Example #1
0
boost::unordered_set<dataPoint> *GetDBHash(DBHandles *d, std::string symbolTableName,
        char *date1, char *date2, std::string contractName)
{
    //IQFeed will give the data backwards, so we need to order the dates properly
    char *firstDate = date2, *secondDate = date1;
    std::string errorString;

    UDate udate1 = GetUDate(date1, dateGC);
    UDate udate2 = GetUDate(date2, dateGC);

    if (udate1 < udate2)
    {
        firstDate = date1;
        secondDate = date2;
    }

    WriteLog("Getting data from %s to %s\n", firstDate, secondDate);

    char query[256];
    if (o.isOption || o.isFutures)
    {
        sprintf(query, "SELECT transactiontime, tickId FROM %s WHERE transactiontime >= '%s' "
                "AND transactiontime <= '%s' and contract = '%s'",
                symbolTableName.c_str(), firstDate, secondDate, contractName.c_str());
    }
    else
    {
        sprintf(query, "SELECT transactiontime, tickId FROM %s WHERE transactiontime >= '%s' "
                "AND transactiontime <= '%s'",
                symbolTableName.c_str(), firstDate, secondDate);
    }

    CreateStatement(d);

    SQLRETURN ret;
    if (!SQL_SUCCEEDED(ret = SQLExecDirect(d->hstmt, (SQLCHAR *) query, SQL_NTS)))
        throw DataException(__FILE__, __LINE__);

    char transactionTime[64];
    int tickId;
    SQLLEN indicator;
    boost::unordered_set<dataPoint> *hash = new boost::unordered_set<dataPoint>();

    if (!SQL_SUCCEEDED(ret = SQLBindCol(d->hstmt, 1, SQL_C_CHAR, transactionTime, sizeof(transactionTime), &indicator)))
        throw DataException(__FILE__, __LINE__);

    if (!SQL_SUCCEEDED(ret = SQLBindCol(d->hstmt, 2, SQL_INTEGER, &tickId, sizeof(tickId), &indicator)))
        throw DataException(__FILE__, __LINE__);

    int numRows = 0;
    while (SQL_SUCCEEDED(ret = SQLFetch(d->hstmt)))
    {
        dataPoint newData;

        newData.date = GetUDate(transactionTime, dateGC);
        newData.tickId = tickId;
        try
        {
            hash->insert(newData);
        }
        catch (const std::bad_alloc &)
        {
            WriteLog("Fuck ran out of memory... Let's forget about getting more data from the database and keep going\n");
            break;
        }
        numRows++;
    }
    WriteLog("Total of %d rows retrieved\n", numRows);

    CloseStatement(d);

    return hash;
}
bool CAmuseAction_UseDevice::GoProcess(std::list<CAmuseAction_Base*>& rNewAction)
{
	CAmuseRoom *pRoom = m_pActPlayer->AmuseRoom();
	if (pRoom == NULL)
	{
		WriteLog(LOGLEVEL_ERROR, "Amuse room is null");
		return false;
	}

	CAmuseAction_UseDevice* pUseDeviceAction = (CAmuseAction_UseDevice*)(m_pActPlayer->UniqueAmuseAction( eAmuseAction_UseDevice ));
	if ( pUseDeviceAction != NULL )
	{
		GameMsg_S2C_DoAmuseActionFail msgResponse;
		msgResponse.m_strError = "DoAmuseAction_AlreadyInDevice";
		m_pActPlayer->SendPlayerMsg( &msgResponse );
	}
	else
	{
		CAmuseRoomDevice* pAmuseDevice = m_pActPlayer->AmuseRoom()->GetRoomDevice( m_nDeviceID );
		if ( pAmuseDevice != NULL )
		{
			unsigned int nNow = (unsigned int)time(NULL);
			if ( pAmuseDevice->GetDeviceType() == AmuseRoomDeviceType_TimeEgg )
			{
				TimeEggEntry* pEgg = m_pActPlayer->GetTimeEggInCurScene();
				if ( pEgg && nNow < pEgg->m_nEndTime )
				{
					GameMsg_S2C_DoAmuseActionFail msgResponse;
					msgResponse.m_strError = "DoAmuseAction_OpenTimeEggNotTime";
					m_pActPlayer->SendPlayerMsg( &msgResponse );
					return false;
				}
			}
			if ( pAmuseDevice->HasUser( m_pActPlayer->RoleID() ) )
			{
				GameMsg_S2C_DoAmuseActionFail msgResponse;
				msgResponse.m_strError = "DoAmuseAction_UseSameDevice";
				m_pActPlayer->SendPlayerMsg( &msgResponse );
			}
			else
			{
				if ( pAmuseDevice->ReachCapacity() )
				{
					GameMsg_S2C_DoAmuseActionFail msgResponse;
					msgResponse.m_strError = "DoAmuseAction_UseFullDevice";
					m_pActPlayer->SendPlayerMsg( &msgResponse );
				}
				else
				{
					if ( _ProcessUseDevice( *pAmuseDevice, rNewAction ) )
					{
						CAmuseAction_UsePose* pUsePoseAction = (CAmuseAction_UsePose*)(m_pActPlayer->UniqueAmuseAction( eAmuseAction_UsePose ));
						if ( pUsePoseAction != NULL )
						{
							m_pActPlayer->AmuseActionOver( pUsePoseAction );

							CAmuseActionParam_LeavePose* pLeavePoseParam = new CAmuseActionParam_LeavePose();
							pLeavePoseParam->m_nPlayerID = m_pActPlayer->RoleID();

							GameMsg_S2C_DoAmuseActionSuc msgLeavePose;
							msgLeavePose.m_pActionParam = pLeavePoseParam;
							m_pActPlayer->AmuseRoom()->SendMsgToAll( &msgLeavePose );
						}

						if ( !m_pActPlayer->CoupleCOM()->IsSingle() && pAmuseDevice->HasUser( m_pActPlayer->CoupleCOM()->CoupleID() ) )
						{
							if ( m_pActPlayer->CoupleCOM()->IsMarried() )
							{
								m_nPartnerType = eAmusePartner_Couple;
							}
							else
							{
								m_nPartnerType = eAmusePartner_Lover;
							}
						}

						pAmuseDevice->UserIn( m_pActPlayer->RoleID() );

						if ( m_nPartnerType == eAmusePartner_None )
						{
							CAmuseRoomComponent* pPartner = pAmuseDevice->GetOtherPlayer(m_pActPlayer->RoleID());
							if ( pPartner && m_pActPlayer->FriendCOM()->IsFriend(pPartner->RoleID()) )
							{
								m_nPartnerType = eAmusePartner_Friend;
							}
						}

						CAmuseActionParam_UseDevice* pUseDeviceParam = new CAmuseActionParam_UseDevice();
						pUseDeviceParam->m_nPlayerID = m_pActPlayer->RoleID();
						pUseDeviceParam->m_nDeviceID = (char)m_nDeviceID;
						pUseDeviceParam->m_nPartnerType = (char)m_nPartnerType;
						pUseDeviceParam->m_bInviter = !m_bIsInvited;
						if ( pAmuseDevice->GetDeviceType() == AmuseRoomDeviceType_TimeEgg )
						{
							TimeEggSetting& setting = CAmuseRoomDataManager::Instance().GetTimeEggSetting();
							pUseDeviceParam->m_listCost = setting.m_listCostItem;
						}

						GameMsg_S2C_DoAmuseActionSuc msgUseDevice;
						msgUseDevice.m_pActionParam = pUseDeviceParam;
						m_pActPlayer->AmuseRoom()->SendMsgToAll( &msgUseDevice );

						m_bSuccess = true;
						return true;
					}
				}
			}
		}
	}

	return false;
}
Example #3
0
link *GetData(std::string symbol)
{
    SOCKET s;
    char command[1000];

    WriteLog("Getting data for %s\n", symbol.c_str());

    GetSocket(&s);

    //get the historical data
    getCommand(command, symbol.c_str(), o);

    int rc = send(s, command, (int) strlen(command), 0);
    if (rc == SOCKET_ERROR)
    {
        WriteLog("error sending data to data feed, error Code %d\n", WSAGetLastError());
        throw DataException(__FILE__, __LINE__);
    }

    char *buffer = (char *) calloc(BUFFER_SIZE, sizeof(char));
    if (buffer == NULL)
    {
        WriteLog("calloc error for buffer\n");
        throw DataException(__FILE__, __LINE__);
    }

    char *bufferPtr = buffer;
    char *begin = buffer;
    char *end = NULL;

    link *head = NULL;

    unsigned long startTime = timeGetTime();
    unsigned long currentTime = 0;
    unsigned long totalTime = 0;
    link *currentLink = NULL;

    int numBlocks = 0;
    int totalRows = 0;

    bool exit = false;

    while (exit == false)
    {
        char oneLine[5120];
        char beginTimestamp[128];
        char endTimestamp[128];

        rc = recv(s, bufferPtr, (int) (BUFFER_SIZE - (bufferPtr - buffer)-1), 0);
        if (rc == 0 || rc == SOCKET_ERROR) {
            WriteLog("error receiving data from data feed, error code = %d\n", WSAGetLastError());
            throw DataException(__FILE__, __LINE__);
        }

        if (rc > BUFFER_SIZE - (bufferPtr - buffer)-1 || rc > BUFFER_SIZE) {
            WriteLog("Something f'ed with the data received, it's bigger than it should be\n");
            throw DataException(__FILE__, __LINE__);
        }

        begin = buffer;

        int numRows = 0;

        //validate each row, looking for the end of data message
        while ((end = strchr(begin, '\n')) != NULL)
        {
            //copy the line into oneLine so that we can check
            //for any errors.  I guess I could have just checked
            //it from the line itself but whatever, easier to debug
            memset(oneLine, 0, sizeof(oneLine));
            strncpy(oneLine, begin, end-begin + 1);
            //printf("%s\n", oneLine);

            //check for an error first
            if (isError(oneLine, symbol.c_str()) == true)
            {
                //end of data
                exit = true;
                break;
            }

            //always extract the timestamp to endTimestamp since
            //we don't know when it will end, but if it's the first
            //row of the block, then copy it to beginTimestamp
            ExtractTimestamp(oneLine, endTimestamp);
            if (numRows == 0)
                strcpy(beginTimestamp, endTimestamp);

            begin = end + 1;

            numRows++;
        }

        //if the very first line of the buffer is an !ENDMSG!,
        //then just break out of this loop
        if (buffer == begin)
        {
            break;
        }

        //create a new link
        link *newLink = (link *) calloc(1, sizeof(link));
        if (newLink == NULL)
        {
            WriteLog("Calloc error for newLink\n");
            throw DataException(__FILE__, __LINE__);
        }

        //create a new buffer for the new block that contains only the
        //valid data for that block
        int blockSize = begin - buffer + 1;

        newLink->buffer = (char *) calloc(blockSize, sizeof(char));
        if (newLink->buffer == NULL)
        {
            WriteLog("Calloc error for newLink->buffer\n");
            throw DataException(__FILE__, __LINE__);
        }

        //copy everything up to the beginning of begin, because
        //that is likely an uncompleted line of data
        memcpy(newLink->buffer, buffer, begin - buffer);

        strcpy(newLink->beginTimestamp, beginTimestamp);
        strcpy(newLink->endTimestamp, endTimestamp);

        if (head == NULL)
        {
            head = newLink;
            currentLink = head;
        }
        else
        {
            currentLink->next = newLink;
        }
        currentLink->numRows = numRows;
        currentLink = newLink;

        //move any other stragglers to the front of the buffer
        memmove(buffer, begin, strlen(begin));
        bufferPtr = buffer + strlen(begin);
        //clear everything else after that to prevent errors
        memset(bufferPtr, 0, BUFFER_SIZE - (bufferPtr - buffer));

        //stats gathering shit
        totalRows += numRows;
        currentTime = timeGetTime();
        totalTime = currentTime - startTime;

        numBlocks++;

        if (numBlocks % 100 == 0)
        {
            WriteLog("%s: reading rows=%d, total time = %d, rows/s = %.2f\n",
                     symbol.c_str(), totalRows, totalTime/1000, 1000.0* totalRows / totalTime);
        }
    }

    WriteLog("%s: FINAL: reading rows=%d, total time = %d, rows/s = %.2f, numBlocks = %d\n",
             symbol.c_str(), totalRows, totalTime/1000, 1000.0* totalRows / totalTime, numBlocks);

    free(buffer);
    closesocket(s);

    return head;
}
bool cRenderer::RenderImage()
{
	WriteLog("cRenderer::RenderImage()", 2);

	if (image->IsAllocated())
	{
		image->SetImageParameters(params->imageAdjustments);

		int progressiveSteps;
		if (data->configuration.UseProgressive())
			progressiveSteps =
				(int)(log((double)max(image->GetWidth(), image->GetHeight())) / log(2.0)) - 3;
		else
			progressiveSteps = 0;

		if (progressiveSteps < 0) progressiveSteps = 0;
		int progressive = pow(2.0, (double)progressiveSteps - 1);
		if (progressive == 0) progressive = 1;

		// prepare multiple threads
		QThread **thread = new QThread *[data->configuration.GetNumberOfThreads()];
		cRenderWorker::sThreadData *threadData =
			new cRenderWorker::sThreadData[data->configuration.GetNumberOfThreads()];
		cRenderWorker **worker = new cRenderWorker *[data->configuration.GetNumberOfThreads()];

		if (scheduler) delete scheduler;
		scheduler = new cScheduler(image->GetHeight(), progressive);

		cProgressText progressText;
		progressText.ResetTimer();

		for (int i = 0; i < data->configuration.GetNumberOfThreads(); i++)
		{
			threadData[i].id = i + 1;
			if (data->configuration.UseNetRender())
			{
				if (i < data->netRenderStartingPositions.size())
				{
					threadData[i].startLine = data->netRenderStartingPositions.at(i);
				}
				else
				{
					threadData[i].startLine = 0;
					qCritical() << "NetRender - Mising starting positions data";
				}
			}
			else
			{
				threadData[i].startLine = (image->GetHeight() / data->configuration.GetNumberOfThreads())
																	* i / scheduler->GetProgressiveStep()
																	* scheduler->GetProgressiveStep();
			}
			threadData[i].scheduler = scheduler;
		}

		QString statusText;
		QString progressTxt;

		QElapsedTimer timerRefresh;
		timerRefresh.start();
		qint64 lastRefreshTime = 0;
		QList<int> listToRefresh;
		QList<int> listToSend;

		QElapsedTimer timerProgressRefresh;
		timerProgressRefresh.start();

		WriteLog("Start rendering", 2);
		do
		{
			WriteLogDouble("Progressive loop", scheduler->GetProgressiveStep(), 2);
			for (int i = 0; i < data->configuration.GetNumberOfThreads(); i++)
			{
				WriteLog(QString("Thread ") + QString::number(i) + " create", 3);
				thread[i] = new QThread;
				worker[i] = new cRenderWorker(
					params, fractal, &threadData[i], data, image); // Warning! not needed to delete object
				worker[i]->moveToThread(thread[i]);
				QObject::connect(thread[i], SIGNAL(started()), worker[i], SLOT(doWork()));
				QObject::connect(worker[i], SIGNAL(finished()), thread[i], SLOT(quit()));
				QObject::connect(worker[i], SIGNAL(finished()), worker[i], SLOT(deleteLater()));
				thread[i]->setObjectName("RenderWorker #" + QString::number(i));
				thread[i]->start();
				WriteLog(QString("Thread ") + QString::number(i) + " started", 3);
			}

			while (!scheduler->AllLinesDone())
			{
				gApplication->processEvents();

				if (*data->stopRequest || progressText.getTime() > data->configuration.GetMaxRenderTime()
						|| systemData.globalStopRequest)
				{
					scheduler->Stop();
				}

				Wait(10); // wait 10ms

				if (data->configuration.UseRefreshRenderedList())
				{
					// get list of last rendered lines
					QList<int> list = scheduler->GetLastRenderedLines();
					// create list of lines for image refresh
					listToRefresh += list;
				}

				// status bar and progress bar
				double percentDone = scheduler->PercentDone();
				data->lastPercentage = percentDone;
				statusText = QObject::tr("Rendering image");
				progressTxt = progressText.getText(percentDone);
				data->statistics.time = progressText.getTime();

				if (timerProgressRefresh.elapsed() > 1000)
				{
					emit updateProgressAndStatus(statusText, progressTxt, percentDone);
					emit updateStatistics(data->statistics);
					timerProgressRefresh.restart();
				}

				// refresh image
				if (listToRefresh.size() > 0)
				{
					if (timerRefresh.elapsed() > lastRefreshTime
							&& (scheduler->GetProgressivePass() > 1 || !data->configuration.UseProgressive()))
					{
						timerRefresh.restart();

						emit updateProgressAndStatus(statusText, progressTxt, percentDone);
						emit updateStatistics(data->statistics);

						QSet<int> set_listToRefresh = listToRefresh.toSet(); // removing duplicates
						listToRefresh = set_listToRefresh.toList();
						qSort(listToRefresh);
						listToSend += listToRefresh;

						image->CompileImage(&listToRefresh);

						if (data->configuration.UseRenderTimeEffects())
						{
							if (params->ambientOcclusionEnabled
									&& params->ambientOcclusionMode == params::AOmodeScreenSpace)
							{
								cRenderSSAO rendererSSAO(params, data, image);
								rendererSSAO.setProgressive(scheduler->GetProgressiveStep());
								rendererSSAO.RenderSSAO(&listToRefresh);
							}
						}

						image->ConvertTo8bit();

						if (data->configuration.UseImageRefresh())
						{
							image->UpdatePreview(&listToRefresh);
							image->GetImageWidget()->update();
						}

						// sending rendered lines to NetRender server
						if (data->configuration.UseNetRender() && gNetRender->IsClient()
								&& gNetRender->GetStatus() == CNetRender::netRender_WORKING)
						{
							// If ACK was already received, then server is ready to take new data.
							if (netRenderAckReceived)
							{
								QList<QByteArray> renderedLinesData;
								for (int i = 0; i < listToSend.size(); i++)
								{
									// avoid sending already rendered lines
									if (scheduler->IsLineDoneByServer(listToSend.at(i)))
									{
										listToSend.removeAt(i);
										i--;
										continue;
									}
									// creating data set to send
									QByteArray lineData;
									CreateLineData(listToSend.at(i), &lineData);
									renderedLinesData.append(lineData);
								}
								// sending data
								if (listToSend.size() > 0)
								{
									emit sendRenderedLines(listToSend, renderedLinesData);
									emit NotifyClientStatus();
									netRenderAckReceived = false;
									listToSend.clear();
								}
							}
						}

						if (data->configuration.UseNetRender() && gNetRender->IsServer())
						{
							QList<int> toDoList = scheduler->CreateDoneList();
							if (toDoList.size() > data->configuration.GetNumberOfThreads())
							{
								for (int c = 0; c < gNetRender->GetClientCount(); c++)
								{
									emit SendToDoList(c, toDoList);
								}
							}
						}

						lastRefreshTime = timerRefresh.elapsed() * data->configuration.GetRefreshRate()
															/ (listToRefresh.size());

						if (lastRefreshTime < 100)
							lastRefreshTime = 100; // the shortest refresh time can be 100ms

						// do not refresh and send data too often
						if (data->configuration.UseNetRender())
						{
							if (lastRefreshTime < 500) lastRefreshTime = 500;
						}

						timerRefresh.restart();
						listToRefresh.clear();
					} // timerRefresh
				}		// isPreview
			}			// while scheduler

			for (int i = 0; i < data->configuration.GetNumberOfThreads(); i++)
			{
				while (thread[i]->isRunning())
				{
					gApplication->processEvents();
				};
				WriteLog(QString("Thread ") + QString::number(i) + " finished", 2);
				delete thread[i];
			}
		} while (scheduler->ProgressiveNextStep());

		// send last rendered lines
		if (data->configuration.UseNetRender() && gNetRender->IsClient()
				&& gNetRender->GetStatus() == CNetRender::netRender_WORKING)
		{
			if (netRenderAckReceived)
			{
				QList<QByteArray> renderedLinesData;
				for (int i = 0; i < listToSend.size(); i++)
				{
					// avoid sending already rendered lines
					if (scheduler->IsLineDoneByServer(listToSend.at(i)))
					{
						listToSend.removeAt(i);
						i--;
						continue;
					}
					QByteArray lineData;
					CreateLineData(listToSend.at(i), &lineData);
					renderedLinesData.append(lineData);
				}

				if (listToSend.size() > 0)
				{
					emit sendRenderedLines(listToSend, renderedLinesData);
					emit NotifyClientStatus();
					netRenderAckReceived = false;
					listToSend.clear();
				}
			}
		}

		if (data->configuration.UseNetRender())
		{
			if (gNetRender->IsClient())
			{
				gNetRender->SetStatus(CNetRender::netRender_READY);
				emit NotifyClientStatus();
			}

			if (gNetRender->IsServer())
			{
				emit StopAllClients();
			}
		}
		// refresh image at end
		WriteLog("image->CompileImage()", 2);
		image->CompileImage();

		if (!(gNetRender->IsClient() && data->configuration.UseNetRender()))
		{
			bool ssaoUsed = false;
			if (params->ambientOcclusionEnabled
					&& params->ambientOcclusionMode == params::AOmodeScreenSpace)
			{
				cRenderSSAO rendererSSAO(params, data, image);
				connect(&rendererSSAO,
					SIGNAL(updateProgressAndStatus(const QString &, const QString &, double)), this,
					SIGNAL(updateProgressAndStatus(const QString &, const QString &, double)));
				rendererSSAO.RenderSSAO();
				ssaoUsed = true;
			}
Example #5
0
//调度模块启动
bool __cdecl CDataBaseSink::StartService(IUnknownEx * pIUnknownEx)
{
	CString strFile,strTemp;
	CTime tmCur = CTime::GetCurrentTime();
	CString strTime = tmCur.Format("%m%d");
	strFile.Format("log\\%s游戏服务.log",strTime);

	strTemp.Format("into StartService");
	WriteLog(strFile, strTemp);

	//效验参数
	ASSERT(m_pGameUserDBInfo!=NULL);
	ASSERT(m_pGameScoreDBInfo!=NULL);
	ASSERT(m_pGameServiceOption!=NULL);
	ASSERT(m_AttemperEvent.IsValid()==true);

	//创建实例
	if ((m_GameUserDB.GetInterface()==NULL)&&(m_GameUserDB.CreateInstance()==false))
	{
		m_pIEventService->ShowEventNotify(TEXT("用户数据库对象创建失败"),Level_Exception);
		return false;
	}

	//创建实例
	if ((m_GameScoreDB.GetInterface()==NULL)&&(m_GameScoreDB.CreateInstance()==false))
	{
		m_pIEventService->ShowEventNotify(TEXT("游戏数据库对象创建失败"),Level_Exception);
		return false;
	}

	try
	{
		//变量定义
		BYTE * pcbAddr=NULL;
		TCHAR szDataBaseAddr[16]=TEXT("");

		//连接用户数据库
		pcbAddr=(BYTE *)&m_pGameUserDBInfo->dwDataBaseAddr;
		_snprintf(szDataBaseAddr,sizeof(szDataBaseAddr),TEXT("%d.%d.%d.%d"),pcbAddr[0],pcbAddr[1],pcbAddr[2],pcbAddr[3]);

	strTemp.Format("m_pGameUserDBInfo %s	%d	%s	%s	%s",
		szDataBaseAddr,m_pGameUserDBInfo->wDataBasePort,m_pGameUserDBInfo->szDataBaseName,
			m_pGameUserDBInfo->szDataBaseUser,m_pGameUserDBInfo->szDataBasePass);
	WriteLog(strFile, strTemp);

		m_GameUserDB->SetConnectionInfo(szDataBaseAddr,m_pGameUserDBInfo->wDataBasePort,m_pGameUserDBInfo->szDataBaseName,
			m_pGameUserDBInfo->szDataBaseUser,m_pGameUserDBInfo->szDataBasePass);
		m_GameUserDB->OpenConnection();

		//连接游戏数据库
		pcbAddr=(BYTE *)&m_pGameScoreDBInfo->dwDataBaseAddr;
		_snprintf(szDataBaseAddr,sizeof(szDataBaseAddr),TEXT("%d.%d.%d.%d"),pcbAddr[0],pcbAddr[1],pcbAddr[2],pcbAddr[3]);

	strTemp.Format("m_pGameScoreDBInfo %s	%d	%s	%s	%s",
		szDataBaseAddr,m_pGameScoreDBInfo->wDataBasePort,m_pGameScoreDBInfo->szDataBaseName,
			m_pGameScoreDBInfo->szDataBaseUser,m_pGameScoreDBInfo->szDataBasePass
		);
	WriteLog(strFile, strTemp);
		m_GameScoreDB->SetConnectionInfo(szDataBaseAddr,m_pGameScoreDBInfo->wDataBasePort,m_pGameScoreDBInfo->szDataBaseName,
			m_pGameScoreDBInfo->szDataBaseUser,m_pGameScoreDBInfo->szDataBasePass);
		m_GameScoreDB->OpenConnection();

		return true;
	}
	catch (IADOError * pIADOError)
	{
		m_pIEventService->ShowEventNotify(pIADOError->GetErrorDescribe(),Level_Exception);
	}

	return false;
}
Example #6
0
//登录请求处理
bool CDataBaseSink::OnRequestLogon(const NTY_DataBaseEvent & DataBaseEvent, void * pDataBuffer, WORD wDataSize)
{
	CString strFile,strTemp;
	CTime tmCur = CTime::GetCurrentTime();
	CString strTime = tmCur.Format("%m%d");
	strFile.Format("log\\%s游戏服务.log",strTime);

	strTemp.Format("into OnRequestLogon");
	WriteLog(strFile, strTemp);

	try
	{
		//登录处理
		LONG lReturnValue=-1;
		LPCTSTR pszPassword=NULL;
		switch (DataBaseEvent.wRequestID)
		{
		case DBR_GR_LOGON_BY_ACCOUNTS:		//帐户登录
			{
	strTemp.Format("into 帐户登录");
	WriteLog(strFile, strTemp);

				//效验参数
				ASSERT(wDataSize==sizeof(DBR_GR_LogonByAccounts));
				if (wDataSize!=sizeof(DBR_GR_LogonByAccounts)) return false;

				//执行查询
				DBR_GR_LogonByAccounts * pLogonByAccounts=(DBR_GR_LogonByAccounts *)pDataBuffer;
				lReturnValue=SPLogonByAccounts(pLogonByAccounts->szAccounts,pLogonByAccounts->szPassWord,pLogonByAccounts->dwClientIP);
				pszPassword=pLogonByAccounts->szPassWord;

				break;
			}
		case DBR_GR_LOGON_BY_USERID:		//I D 登录
			{
	strTemp.Format("into I D 登录");
	WriteLog(strFile, strTemp);
				//效验参数
				ASSERT(wDataSize==sizeof(DBR_GR_LogonByUserID));
				if (wDataSize!=sizeof(DBR_GR_LogonByUserID)) return false;

				//执行查询
				DBR_GR_LogonByUserID * pLogonByUserID=(DBR_GR_LogonByUserID *)pDataBuffer;
				lReturnValue=SPLogonByUserID(pLogonByUserID->dwUserID,pLogonByUserID->szPassWord,pLogonByUserID->dwClientIP);
				pszPassword=pLogonByUserID->szPassWord;

	strTemp.Format("pszPassword=%s", pszPassword);
	WriteLog(strFile, strTemp);

				break;
			}
		default :	//默认处理
			{
				ASSERT(FALSE); 
				return false;
			}
		}

		//登录失败
		if (lReturnValue!=0L)
		{
			DBR_GR_LogonError LogonError;
			LogonError.lErrorCode=lReturnValue;
			m_GameScoreDB->GetFieldValue(TEXT("ErrorDescribe"),LogonError.szErrorDescribe,sizeof(LogonError.szErrorDescribe));
			m_AttemperEvent.PostDataBaseEvent(DBR_GR_LOGON_ERROR,DataBaseEvent.wIndex,DataBaseEvent.wRoundID,&LogonError,sizeof(LogonError));
			m_GameScoreDB->CloseRecordset();
			return true;
		}

		//变量定义
		DBR_GR_LogonSuccess LogonSuccess;
		memset(&LogonSuccess,0,sizeof(LogonSuccess));
		CopyMemory(LogonSuccess.szPassWord,pszPassword,sizeof(LogonSuccess.szPassWord));

	strTemp.Format("aaaa");
	WriteLog(strFile, strTemp);

		//读取用户信息
		m_GameScoreDB->GetFieldValue(TEXT("UserID"),LogonSuccess.dwUserID);
		m_GameScoreDB->GetFieldValue(TEXT("Gender"),LogonSuccess.cbGender);
		m_GameScoreDB->GetFieldValue(TEXT("MemberOrder"),LogonSuccess.cbMember);
		m_GameScoreDB->GetFieldValue(TEXT("FaceID"),LogonSuccess.wFaceID);
		m_GameScoreDB->GetFieldValue(TEXT("GroupID"),LogonSuccess.dwGroupID);
		m_GameScoreDB->GetFieldValue(TEXT("Experience"),LogonSuccess.lExperience);
		m_GameScoreDB->GetFieldValue(TEXT("UserRight"),LogonSuccess.dwUserRight);
		m_GameScoreDB->GetFieldValue(TEXT("MasterRight"),LogonSuccess.dwMasterRight);
		m_GameScoreDB->GetFieldValue(TEXT("Accounts"),LogonSuccess.szAccounts,sizeof(LogonSuccess.szAccounts));
		m_GameScoreDB->GetFieldValue(TEXT("GroupName"),LogonSuccess.szGroupName,sizeof(LogonSuccess.szGroupName));

	strTemp.Format("bbbb");
	WriteLog(strFile, strTemp);
		//读取游戏信息
		m_GameScoreDB->GetFieldValue(TEXT("Score"),LogonSuccess.lScore);
		m_GameScoreDB->GetFieldValue(TEXT("WinCount"),LogonSuccess.lWinCount);
		m_GameScoreDB->GetFieldValue(TEXT("LostCount"),LogonSuccess.lLostCount);
		m_GameScoreDB->GetFieldValue(TEXT("DrawCount"),LogonSuccess.lDrawCount);
		m_GameScoreDB->GetFieldValue(TEXT("FleeCount"),LogonSuccess.lFleeCount);

	strTemp.Format("cccc");
	WriteLog(strFile, strTemp);

		//投递调度通知
		m_AttemperEvent.PostDataBaseEvent(DBR_GR_LOGON_SUCCESS,DataBaseEvent.wIndex,DataBaseEvent.wRoundID,
			&LogonSuccess,sizeof(LogonSuccess));
	}
	catch (IADOError * pIADOError)
	{
		//输出错误
		if (m_pIEventService!=NULL) m_pIEventService->ShowEventNotify(pIADOError->GetErrorDescribe(),Level_Exception);

		//操作失败
		DBR_GR_LogonError LogonError;
		LogonError.lErrorCode=-1;
		lstrcpyn(LogonError.szErrorDescribe,TEXT("由于数据库操作异常,请您稍后重试或选择另一游戏服务器!"),sizeof(LogonError.szErrorDescribe));
		m_AttemperEvent.PostDataBaseEvent(DBR_GR_LOGON_ERROR,DataBaseEvent.wIndex,DataBaseEvent.wRoundID,
			&LogonError,sizeof(LogonError));
	}

	//关闭记录集
	m_GameScoreDB->CloseRecordset();

	return true;
}
bool CAmuseAction_InviteDevice::GoProcess(std::list<CAmuseAction_Base*>& rNewAction)
{
	CAmuseRoom *pRoom = m_pActPlayer->AmuseRoom();
	if (pRoom == NULL)
	{
		WriteLog(LOGLEVEL_ERROR, "Amuse room is null");
		return false;
	}

	CAmuseAction_UseDevice* pUseDeviceAction = (CAmuseAction_UseDevice*)(m_pActPlayer->UniqueAmuseAction( eAmuseAction_UseDevice ));
	if ( pUseDeviceAction != NULL && m_pActPlayer->AttrCOM()->GetRoleID() != m_nInviteeID )
	{
		int nDeviceID = pUseDeviceAction->m_nDeviceID;

		CAmuseRoomDevice* pAmuseDevice = m_pActPlayer->AmuseRoom()->GetRoomDevice( nDeviceID );
		if ( pAmuseDevice != NULL && pAmuseDevice->HasUser( m_pActPlayer->RoleID() ) && pAmuseDevice->InviteType() != eAmuseInvite_None )
		{
			TimeEggEntry* pInviterEgg = NULL;
			TimeEggEntry* pInviteeEgg = NULL;
			//时光蛋相关操作
			EggInviteType nInviterInviteType = EggInviteType_None;
			if (pAmuseDevice->GetDeviceType() == AmuseRoomDeviceType_TimeEgg)
			{
				nInviterInviteType = m_pActPlayer->GetInviteTypeInCurScene();
				pInviterEgg = m_pActPlayer->GetTimeEggInCurScene();
				GameMsg_S2C_DoAmuseActionFail msgResponse;
				if (!m_pActPlayer->CheckInviteTypeInCurScene(nInviterInviteType, m_nInviteeID, msgResponse.m_strError))
				{
					m_pActPlayer->SendPlayerMsg( &msgResponse );
					return false;
				}
				if ( nInviterInviteType == EggInviteType_Create && !pUseDeviceAction->m_bIsInvited )
				{
					if ( m_pActPlayer->CoupleCOM()->IsSingle() || m_pActPlayer->CoupleCOM()->CoupleID() != m_nInviteeID )
					{
						if ( !m_pActPlayer->FriendCOM()->IsFriend(m_nInviteeID) )
						{
							msgResponse.m_strError = "DoAmuseAction_NoRelation";
							m_pActPlayer->SendPlayerMsg( &msgResponse );
							return false;
						}
					}
				}
			}
			if ( !pAmuseDevice->ReachCapacity() )
			{
				CAmuseRoomComponent* pInviteePlayer = m_pActPlayer->AmuseRoom()->GetAmusePlayer( m_nInviteeID );
				if ( pInviteePlayer != NULL )
				{
					if (pAmuseDevice->GetDeviceType() == AmuseRoomDeviceType_TimeEgg)
					{
						pInviteeEgg = pInviteePlayer->GetTimeEggInCurScene();
						GameMsg_S2C_DoAmuseActionFail msgResponse;
						if ( nInviterInviteType == EggInviteType_Create )
						{
							if ( pInviteeEgg )
							{
								msgResponse.m_strError = "DoAmuseAction_PartnerAlreadyExistEgg";
								m_pActPlayer->SendPlayerMsg( &msgResponse );
								return false;
							}
						}
						else if ( nInviterInviteType == EggInviteType_Open )
						{
							if ( pInviteeEgg == NULL )
							{
								msgResponse.m_strError = "DoAmuseAction_PartnerAlreadyOpenTimeEgg";
								m_pActPlayer->SendPlayerMsg( &msgResponse );
								return false;
							}
							else if ( pInviterEgg->m_nEggID != pInviteeEgg->m_nEggID )
							{
								msgResponse.m_strError = "DoAmuseAction_NoRightPartner";
								m_pActPlayer->SendPlayerMsg( &msgResponse );
								return false;
							}
						}
					}
					CAmuseAction_Base* pInviteeAction = pInviteePlayer->UniqueAmuseAction( eAmuseAction_UseDevice );
					if ( pInviteeAction == NULL )
					{
						CAmuseAction_RequestDevice* pRequestAction = new CAmuseAction_RequestDevice( pInviteePlayer, m_pActPlayer->AmuseRoom()->ActionID() );
						pRequestAction->m_nInviterID = m_pActPlayer->RoleID();
						pRequestAction->m_nDeviceID = nDeviceID;
						rNewAction.push_back( pRequestAction );

						m_bSuccess = true;
					}
					else
					{
						GameMsg_S2C_DoAmuseActionFail msgResponse;
						msgResponse.m_strError = "DoAmuseAction_InviteeBusyPlayer";
						m_pActPlayer->SendPlayerMsg( &msgResponse );
					}
				}
				else
				{
					GameMsg_S2C_DoAmuseActionFail msgResponse;
					msgResponse.m_strError = "DoAmuseAction_InviteNoPlayer";
					m_pActPlayer->SendPlayerMsg( &msgResponse );
				}
			}
			else
			{
				GameMsg_S2C_DoAmuseActionFail msgResponse;
				msgResponse.m_strError = "DoAmuseAction_InviteFullDevice";
				m_pActPlayer->SendPlayerMsg( &msgResponse );
			}
		}
	}

	return false;
}
Example #8
0
void sysLogger::DoLog(wxLogLevel level, const wxChar *msg, time_t timestamp)
{
	wxString msgtype, preamble;
	int icon = 0;

	switch (level)
	{
		case wxLOG_FatalError:
			msgtype = wxT("FATAL  ");
			preamble = _("A fatal error has occurred:\n\n");
			icon = wxICON_ERROR;
			break;

		case wxLOG_Error:
			msgtype = wxT("ERROR  ");
			preamble = _("An error has occurred:\n\n");
			icon = wxICON_ERROR;
			break;

		case wxLOG_QuietError:
			msgtype = wxT("ERROR  ");
			break;

		case wxLOG_Warning:
			msgtype = wxT("WARNING");
			preamble = _("Warning:\n\n");
			icon = wxICON_EXCLAMATION;
			break;

		case wxLOG_Message:
			msgtype = wxT("MESSAGE");
			preamble = wxT("");
			icon = wxICON_INFORMATION;
			break;

		case wxLOG_Info:
			msgtype = wxT("INFO   ");
			break;

		case wxLOG_Status:
			msgtype = wxT("STATUS ");
			break;

		case wxLOG_Notice:
			msgtype = wxT("NOTICE ");
			break;

		case wxLOG_Sql:
			msgtype = wxT("QUERY  ");
			break;

		case wxLOG_Script:
			msgtype = wxT("SCRIPT ");
			break;

		case wxLOG_ScriptVerbose:
			msgtype = wxT("SCRIPT ");
			break;

		case wxLOG_Trace:
			msgtype = wxT("TRACE  ");
			break;

		case wxLOG_Debug:
			msgtype = wxT("DEBUG  ");
			break;

		default:
			msgtype = wxT("UNKNOWN");
			icon = wxICON_INFORMATION;
			break;
	}

	// Convert the timestamp
	wxDateTime *time = new wxDateTime(timestamp);
	wxString fullmsg;

	// Build the message.
	fullmsg << time->FormatISODate() << wxT(" ") <<
	        time->FormatISOTime() << wxT(" ") << msgtype << wxT(": ") << msg;

	// Make sure to delete the time that we allocated
	delete time;

	// Display the message if required
	switch (logLevel)
	{
		case LOG_NONE:
			break;

		case LOG_ERRORS:
			if (level == wxLOG_FatalError ||
			        level == wxLOG_Error ||
			        level == wxLOG_QuietError)
				WriteLog(fullmsg);
			break;

		case LOG_NOTICE:
			if (level == wxLOG_FatalError ||
			        level == wxLOG_Error ||
			        level == wxLOG_QuietError ||
			        level == wxLOG_Notice)
				WriteLog(fullmsg);
			break;

		case LOG_SQL:
			if (level == wxLOG_FatalError ||
			        level == wxLOG_Error ||
			        level == wxLOG_QuietError ||
			        level == wxLOG_Message ||
			        level == wxLOG_Status ||
			        level == wxLOG_Notice ||
			        level == wxLOG_Sql ||
			        level == wxLOG_Script)
				WriteLog(fullmsg);
			break;

		case LOG_DEBUG:
			WriteLog(fullmsg);
			break;
	}

	// Display a messagebox if required.
#if !defined(PGSCLI)
	if (icon != 0 && !SilenceMessage(msg))
		wxMessageBox(preamble + wxGetTranslation(msg), appearanceFactory->GetLongAppName(), wxOK | wxCENTRE | icon);
#endif // PGSCLI
}