Example #1
0
int fileSendUdp(int socket, char *filename, struct sockaddr_in addr) {
	
	fd_set rfds;
	struct timeval tv;
	int received;
	FILE *stream;																//fopen check
	for(int i = 0; i < strlen(filename); i++)
	{
		if(filename[i] == '\n')
			filename[i] = '\0';
	}
	if(fopen_s(&stream, adaptFileName(filename), "rb" )) {
		perror("fopen error");
		return -1;
	}
	else {
		char sendline[1024] = "/sendfile ";										//command to server for start receiving
		strcat_s(sendline, 1024, filename);
		//send(socket, sendline, 1024, 0);
		sendto(socket, sendline, 1024, NULL, (struct sockaddr*)&addr, sizeof(addr));
	}
	char buff[1024];
	int sizeCheck = 0, fileSize;
	fseek(stream,0,SEEK_END);
    fileSize = ftell(stream);													//filesize calc
	fseek(stream,0,SEEK_SET);
	printf("Filesize: %d\n", fileSize);
	char fsz[1024];
	_itoa_s(fileSize, fsz, 1024, 10);											//send file size to server
	//send(socket, fsz, 1024, 0);
	sendto(socket, fsz, 1024, NULL, (struct sockaddr*)&addr, sizeof(addr));
	//recv(socket, fsz, 1024, 0);
	int addrSize = sizeof(addr);
	recvfrom(socket, fsz, 1024, NULL, (struct sockaddr*)&addr, &addrSize);
	int servFileSize = atoi(fsz);
	printf("Server's file size: %d\n", servFileSize);
	if(servFileSize == fileSize) {
		puts("File already exist on server");
		fclose(stream);
		return 0;
	}
	sizeCheck = servFileSize;
	fseek(stream, servFileSize, SEEK_SET);
	//int n = 1;
	//bool next = true;
	while(sizeCheck < fileSize - 1) {
		int read;
		FD_ZERO(&rfds);
		FD_SET(socket, &rfds);
		tv.tv_sec = 1;
		tv.tv_usec = 0;
		select(0, &rfds, NULL, NULL, &tv);
		recvfrom(socket, fsz, 1024, NULL, (struct sockaddr*)&addr, &addrSize);
		servFileSize = atoi(fsz);
		fseek(stream,servFileSize,SEEK_SET);
		read = fread_s(buff, 1024, sizeof(bool), 1024, stream);	
		int sent = sendto(socket, buff, read, NULL, (struct sockaddr*)&addr, sizeof(addr));
		sizeCheck += read;
									
	}
	fclose(stream);
	printf("done\n");
	return 0;
}
Example #2
0
s32 main()
{
    srand((u32)time(0));

    //setup data depending on which function will be run
    //TrainData will contain random values for teaching the network
    //TestData is for testing the network after it's trained
#if A
    const char *filename = "nn1a.csv";
    
    r32 TrainData[DataPointCount][2];
    r32 TestData[DataPointCount][2];
    
    for(u32 i = 0;
        i < ArrayCount(TrainData);
        ++i)
    {
        TrainData[i][0] = RandomBetween(-1,7);
        TrainData[i][1] = FunctionProblemOne(TrainData[i][0]);
        
        TestData[i][0] = RandomBetween(-1,7);
        TestData[i][1] = FunctionProblemOne(TrainData[i][0]);
    }

    u32 numLayers = 3;
    u32 lSz[3] = {1,25,1};
#endif
#if B
    const char *filename = "nn2a.csv";

    r32 TrainData[DataPointCount][3];
    r32 TestData[DataPointCount][3];
    
    for(u32 i = 0;
        i < ArrayCount(TrainData);
        ++i)
    {
        TrainData[i][0] = RandomBetween(-3,3);
        TrainData[i][1] = RandomBetween(-3,3);
        TrainData[i][2] = FunctionProblemTwo(TrainData[i][0], TrainData[i][1]);
        
        TestData[i][0] = RandomBetween(-3,3);
        TestData[i][1] = RandomBetween(-3,3);
        TestData[i][2] = FunctionProblemTwo(TrainData[i][0], TrainData[i][1]);
    }

    u32 numLayers = 4;
    u32 lSz[4] = {2,25,10,1};
#endif
#if C
    const char *filename = "nn1b.csv";
    
    r32 TrainData[DataPointCount][2];
    r32 TestData[DataPointCount][2];
    
    for(u32 i = 0;
        i < ArrayCount(TrainData);
        ++i)
    {
        TrainData[i][0] = RandomBetween(-1,7);
        TrainData[i][1] = FunctionProblemOneWithNoise(TrainData[i][0]);
        
        TestData[i][0] = RandomBetween(-1,7);
        TestData[i][1] = FunctionProblemOneWithNoise(TrainData[i][0]);
    }

    u32 numLayers = 3;
    u32 lSz[3] = {1,25,1};
#endif
#if D
    const char *filename = "nn2b.csv";
        
    r32 TrainData[DataPointCount][3];
    r32 TestData[DataPointCount][3];
    
    for(u32 i = 0;
        i < ArrayCount(TrainData);
        ++i)
    {
        TrainData[i][0] = RandomBetween(-3,3);
        TrainData[i][1] = RandomBetween(-3,3);
        TrainData[i][2] = FunctionProblemTwoWithNoise(TrainData[i][0], TrainData[i][1]);
        
        TestData[i][0] = RandomBetween(-3,3);
        TestData[i][1] = RandomBetween(-3,3);
        TestData[i][2] = FunctionProblemTwoWithNoise(TrainData[i][0], TrainData[i][1]);
    }

    u32 numLayers = 4;
    u32 lSz[4] = {2,25,10,1};
#endif

    //crash if I missed a number change
    Assert(numLayers == ArrayCount(lSz));
	
	r32 beta = 0.3f, alpha = 0.1f;
	u32 num_iter = 5000000;

	CBackProp *bp = new CBackProp(numLayers, lSz, beta, alpha);

    u32 DataPointSize = lSz[0] + lSz[numLayers - 1];

    //iterate up to the max iterations
    for (u32 IterationIndex = 0;
         IterationIndex < num_iter;
         ++IterationIndex)
	{
        r32 MeanSquareError = 0;
	
        for(u32 DataPointIndex = 0;
            DataPointIndex < DataPointCount;
            ++DataPointIndex)
        {
            //backpropogate the training data and caluculate the mse
            r32 *target = &TrainData[DataPointIndex][lSz[0]];
            bp->bpgt(TrainData[DataPointIndex], target);
            MeanSquareError += bp->mse(target);
        }

        //if average of MSE over the set of test data is below the threshold, end training
        MeanSquareError /= DataPointCount;
        if(MeanSquareError < Thresh)
        {
            printf("network trained, MSE: %f\n", MeanSquareError);
            break;
        }
        else
        {
            printf("training... MSE: %f\n", MeanSquareError);
        }
	}

#if 1

    //create ofs to create csvs of the data
    
    const char *path_prefix = "../data/";
    char OutputFilename[80];
    strcpy_s(OutputFilename, path_prefix);
    strcat_s(OutputFilename, filename);
    char TestDataFilename[80];
    strcpy_s(TestDataFilename, path_prefix);
    strcat_s(TestDataFilename, "test");
    strcat_s(TestDataFilename, filename);

    printf("%s\n%s\n", OutputFilename, TestDataFilename);
    
    std::ofstream NetworkOutput, TestDataOutput;
    NetworkOutput.open(OutputFilename, std::ofstream::out);
    TestDataOutput.open(TestDataFilename, std::ofstream::out);

    //iterate through each test data point, feed forward, and save out the results
	for (u32 i = 0 ; i < DataPointCount ; i++ )
	{
        r32 *DataPoint = TestData[i];
		bp->ffwd(DataPoint);
        r32 output = DataPoint[lSz[0]];
        r32 prediction = bp->Out(0);
        r32 reNormalized = (prediction * 10) - 5;

        for(u32 InputIndex = 0;
            InputIndex < lSz[0];
            ++InputIndex)
        {
            NetworkOutput << DataPoint[InputIndex] << ',';
            TestDataOutput << DataPoint[InputIndex] << ',';
        }
        NetworkOutput << reNormalized << std::endl;
        TestDataOutput << ((output*10)-5) << std::endl;
	}
#endif

    NetworkOutput.close();
    
    return 1;
}
Example #3
0
UINT iTunesApi::Init()
{
    int result = FALSE;

	char newlibvar[2048];
	char *libvar;

	memset(newlibvar, 0, sizeof(newlibvar));
	libvar = getenv("path");
    sprintf(newlibvar, "path=%s", libvar);
	strcat_s(newlibvar, ";C:\\Program Files\\Common Files\\Apple\\Mobile Device Support;");
	strcat_s(newlibvar, "C:\\Program Files\\Common Files\\Apple\\Apple Application Support;");
	_putenv(newlibvar);

    _iTunes_mobile_device_dll = ::LoadLibrary(L"iTunesMobileDevice.dll");
    _core_function_dll = ::LoadLibrary(L"CoreFoundation.dll");

    //am
    LOAD_LIBRARY_API(_iTunes_mobile_device_dll, AMRestoreRegisterForDeviceNotifications, func_AMRestoreRegisterForDeviceNotifications, "AMRestoreRegisterForDeviceNotifications");
    LOAD_LIBRARY_API(_iTunes_mobile_device_dll, AMDServiceConnectionSend, func_AMDServiceConnectionSend, "AMDServiceConnectionSend");
    LOAD_LIBRARY_API(_iTunes_mobile_device_dll, AMDServiceConnectionReceive, func_AMDServiceConnectionReceive, "AMDServiceConnectionReceive");
    LOAD_LIBRARY_API(_iTunes_mobile_device_dll, AMDeviceGetInterfaceType, func_AMDeviceGetInterfaceType, "AMDeviceGetInterfaceType");
    LOAD_LIBRARY_API(_iTunes_mobile_device_dll, AMDServiceConnectionInvalidate, func_AMDServiceConnectionInvalidate, "AMDServiceConnectionInvalidate");
    LOAD_LIBRARY_API(_iTunes_mobile_device_dll, AMDeviceRetain, func_AMDeviceRetain, "AMDeviceRetain");
    LOAD_LIBRARY_API(_iTunes_mobile_device_dll, AMDeviceNotificationSubscribe, func_AMDeviceNotificationSubscribe, "AMDeviceNotificationSubscribe");
    LOAD_LIBRARY_API(_iTunes_mobile_device_dll, AMDeviceConnect, func_AMDeviceConnect, "AMDeviceConnect");
    LOAD_LIBRARY_API(_iTunes_mobile_device_dll, AMDeviceCopyDeviceIdentifier, func_AMDeviceCopyDeviceIdentifier, "AMDeviceCopyDeviceIdentifier");
    LOAD_LIBRARY_API(_iTunes_mobile_device_dll, AMDeviceDisconnect, func_AMDeviceDisconnect, "AMDeviceDisconnect");
    LOAD_LIBRARY_API(_iTunes_mobile_device_dll, AMDeviceIsPaired, func_AMDeviceIsPaired, "AMDeviceIsPaired");
    LOAD_LIBRARY_API(_iTunes_mobile_device_dll, AMDeviceValidatePairing, func_AMDeviceValidatePairing, "AMDeviceValidatePairing");
    LOAD_LIBRARY_API(_iTunes_mobile_device_dll, AMDeviceStartSession, func_AMDeviceStartSession, "AMDeviceStartSession");
    LOAD_LIBRARY_API(_iTunes_mobile_device_dll, AMDeviceStopSession, func_AMDeviceStopSession, "AMDeviceStopSession");
    LOAD_LIBRARY_API(_iTunes_mobile_device_dll, AMDeviceSetValue, func_AMDeviceSetValue, "AMDeviceSetValue");
    LOAD_LIBRARY_API(_iTunes_mobile_device_dll, AMDeviceCopyValue, func_AMDeviceCopyValue, "AMDeviceCopyValue");
    LOAD_LIBRARY_API(_iTunes_mobile_device_dll, AMDeviceGetInterfaceType, func_AMDeviceGetInterfaceType, "AMDeviceGetInterfaceType");

    LOAD_LIBRARY_API(_iTunes_mobile_device_dll, AMDeviceSecureStartService, func_AMDeviceSecureStartService, "AMDeviceSecureStartService");
    LOAD_LIBRARY_API(_iTunes_mobile_device_dll, AMDServiceConnectionGetSocket, func_AMDServiceConnectionGetSocket, "AMDServiceConnectionGetSocket");
    LOAD_LIBRARY_API(_iTunes_mobile_device_dll, AMDServiceConnectionGetSecureIOContext, func_AMDServiceConnectionGetSecureIOContext, "AMDServiceConnectionGetSecureIOContext");

    //afc
    LOAD_LIBRARY_API(_iTunes_mobile_device_dll, AFCConnectionOpen, func_AFCConnectionOpen, "AFCConnectionOpen");
    LOAD_LIBRARY_API(_iTunes_mobile_device_dll, AFCFileInfoOpen, func_AFCFileInfoOpen, "AFCFileInfoOpen");
    LOAD_LIBRARY_API(_iTunes_mobile_device_dll, AFCKeyValueRead, func_AFCKeyValueRead, "AFCKeyValueRead");

    LOAD_LIBRARY_API(_iTunes_mobile_device_dll, AFCDirectoryOpen, func_AFCDirectoryOpen, "AFCDirectoryOpen");
    LOAD_LIBRARY_API(_iTunes_mobile_device_dll, AFCFileRefOpen, func_AFCFileRefOpen, "AFCFileRefOpen");
    LOAD_LIBRARY_API(_iTunes_mobile_device_dll, AFCFileRefRead, func_AFCFileRefRead, "AFCFileRefRead");
    LOAD_LIBRARY_API(_iTunes_mobile_device_dll, AFCFileRefClose, func_AFCFileRefClose, "AFCFileRefClose");

	//cfstring
    LOAD_LIBRARY_API(_core_function_dll, CFStringMakeConstantString, func_CFStringMakeConstantString, "__CFStringMakeConstantString");

	//cf
    LOAD_LIBRARY_API(_core_function_dll, CFStringGetCString, func_CFStringGetCString, "CFStringGetCString");
    LOAD_LIBRARY_API(_core_function_dll, CFGetTypeID, func_CFGetTypeID, "CFGetTypeID");
    LOAD_LIBRARY_API(_core_function_dll, CFStringGetTypeID, func_CFStringGetTypeID, "CFStringGetTypeID");
    LOAD_LIBRARY_API(_core_function_dll, CFStringGetLength, func_CFStringGetLength, "CFStringGetLength");

    result = TRUE;
Exit0:
    if(!result)
	{
		LPVOID lpMsgBuf;
		FormatMessage(
			FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
			NULL,
			GetLastError(),
			MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),
			(LPTSTR)&lpMsgBuf,
			0,
			NULL
			);
        MessageBox(NULL,(LPCTSTR)lpMsgBuf, L"Load iTunesMobileDevice.dll Failed!!!",MB_OK | MB_ICONINFORMATION);
		LocalFree(lpMsgBuf);
	}
    return result;
}
void EncryptWindow::DoEncryption (char *szVaultpath)
{
	// Goes through each of the file info objects in the added
	// dynlist and encrypts each file one by one, placing the encrypted
	// file in the destination vault path. Which will be in the "EncryptedVault" directory
	// which resides at the same location as this executable.

	SingleFileInfo *pinfo;

	int a = 0;
	char szDestpath[SIZE_STRING];

	char szFileonly[SIZE_STRING];
	char szPathonly[SIZE_STRING];
	char szTemp[SIZE_STRING];

	Show ();
	SendMessage(m_hwndprogress, PBM_SETRANGE, 0L, MAKELONG (0, m_dlFileinfolist.GetNumItems ()));

	for (a=0;a<m_dlFileinfolist.GetNumItems ();a++) {
		pinfo = (SingleFileInfo *) m_dlFileinfolist.GetItem (a);

		if (pinfo->bIsDir == true) {

			ZeroMemory (szDestpath, SIZE_STRING);
			strcpy_s (szDestpath, SIZE_STRING, szVaultpath);
			strcat_s (szDestpath, SIZE_STRING, "\\");

			ZeroMemory (szFileonly, SIZE_STRING);
			ZeroMemory (szPathonly, SIZE_STRING);
			
			GetPathOnly (pinfo->szRootdir, szPathonly, szFileonly, "\\");

			ZeroMemory (szTemp, SIZE_STRING);

			StripStartPath (pinfo->szRootdir, pinfo->szFilepath, szTemp);

			strcat_s (szDestpath, SIZE_STRING, szFileonly);
			//strcat_s (szDestpath, SIZE_STRING, "\\");
			strcat_s (szDestpath, SIZE_STRING, szTemp);

			m_enc.EncryptFileEx3 (pinfo->szFilepath, szDestpath, m_szPassword, true);
			
			m_pdiag->OutputText ("Encrypt Source: ", pinfo->szFilepath);
			m_pdiag->OutputText ("Encrypt Dest: ", szDestpath);


		} else {
			ZeroMemory (szDestpath, SIZE_STRING);
			strcpy_s (szDestpath, SIZE_STRING, szVaultpath);
			strcat_s (szDestpath, SIZE_STRING, "\\");

			ZeroMemory (szFileonly, SIZE_STRING);
			ZeroMemory (szPathonly, SIZE_STRING);

			GetPathOnly (pinfo->szFilepath, szPathonly, szFileonly, "\\");

			strcat_s (szDestpath, SIZE_STRING, szFileonly);

			m_pdiag->OutputText ("Encrypt Source: ", pinfo->szFilepath);
			m_pdiag->OutputText ("Encrypt Dest: ", szDestpath);

			m_enc.EncryptFileEx3 (pinfo->szFilepath, szDestpath, m_szPassword, true);
		}

		SendMessage (m_hwndprogress, PBM_SETPOS, a, 0L);
	}

	Hide ();
}
Example #5
0
bool CAXModel::Load(const char* strFileName)
{
	this->Unload();

	m_strFile = strFileName;

	LPD3DXBUFFER pAdjacencyBuffer = NULL;
	LPD3DXBUFFER pMtrlBuffer = NULL;
	if (FAILED(D3DXLoadMeshFromXA(m_strFile.c_str(), D3DXMESH_MANAGED, APROJECT_WINDOW->GetD3DDevice(), &pAdjacencyBuffer, &pMtrlBuffer, NULL, &m_dwNumMaterials, &m_pMeshObject)))
		return false;

	// Optimize the mesh for performance
	if (FAILED(m_pMeshObject->OptimizeInplace(D3DXMESHOPT_COMPACT | D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_VERTEXCACHE, (DWORD*)pAdjacencyBuffer->GetBufferPointer(), NULL, NULL, NULL)))
	{
		SAFE_RELEASE(pAdjacencyBuffer);
		SAFE_RELEASE(pMtrlBuffer);
		return false;
	}

	D3DXMATERIAL* d3dxMtrls = (D3DXMATERIAL*)pMtrlBuffer->GetBufferPointer();
	do
	{
		if (d3dxMtrls && m_dwNumMaterials > 0)
		{
			// Allocate memory for the materials and textures
			m_pMaterials = new D3DMATERIAL9[m_dwNumMaterials];
			if (m_pMaterials == NULL)
				break;

			m_pTextures = new LPDIRECT3DBASETEXTURE9[m_dwNumMaterials];
			if (m_pTextures == NULL)
				break;

			m_strMaterials = new CHAR[m_dwNumMaterials][MAX_PATH];
			if (m_strMaterials == NULL)
				break;

			// Copy each material and create its texture
			for (DWORD i = 0; i < m_dwNumMaterials; i++)
			{
				// Copy the material
				m_pMaterials[i] = d3dxMtrls[i].MatD3D;
				m_pTextures[i] = NULL;

				// Create a texture
				if (d3dxMtrls[i].pTextureFilename)
				{
					strcpy_s(m_strMaterials[i], MAX_PATH, d3dxMtrls[i].pTextureFilename);

					CHAR strTexture[MAX_PATH];
					D3DXIMAGE_INFO ImgInfo;

					// First attempt to look for texture in the same folder as the input folder.
					int p = 0;
					strcpy_s(strTexture, MAX_PATH, m_strFile.c_str());
					for (DWORD j = 0; j < strlen(strTexture); j++)
					{
						if (strTexture[j] == '/')
							p = j;
					}
					strTexture[p + 1] = 0;
					strcat_s(strTexture, MAX_PATH, d3dxMtrls[i].pTextureFilename);

					// Inspect the texture file to determine the texture type.
					if (FAILED(D3DXGetImageInfoFromFileA(strTexture, &ImgInfo)))
						continue;

					// Call the appropriate loader according to the texture type.
					switch (ImgInfo.ResourceType)
					{
						case D3DRTYPE_TEXTURE:
						{
							IDirect3DTexture9* pTex;
							if (SUCCEEDED(D3DXCreateTextureFromFileA(APROJECT_WINDOW->GetD3DDevice(), strTexture, &pTex)))
							{
								pTex->QueryInterface(IID_IDirect3DBaseTexture9, (LPVOID*)&m_pTextures[i]);
								pTex->Release();
							}
							break;
						}

						case D3DRTYPE_CUBETEXTURE:
						{
							IDirect3DCubeTexture9* pTex;
							if (SUCCEEDED(D3DXCreateCubeTextureFromFileA(APROJECT_WINDOW->GetD3DDevice(), strTexture, &pTex)))
							{
								pTex->QueryInterface(IID_IDirect3DBaseTexture9, (LPVOID*)&m_pTextures[i]);
								pTex->Release();
							}
							break;
						}

						case D3DRTYPE_VOLUMETEXTURE:
						{
							IDirect3DVolumeTexture9* pTex;
							if (SUCCEEDED(D3DXCreateVolumeTextureFromFileA(APROJECT_WINDOW->GetD3DDevice(), strTexture, &pTex)))
							{
								pTex->QueryInterface(IID_IDirect3DBaseTexture9, (LPVOID*)&m_pTextures[i]);
								pTex->Release();
							}
							break;
						}
					}
				}
			}
		}
	} while (0);

	// Extract data from m_pMesh for easy access
	D3DVERTEXELEMENT9 decl[MAX_FVF_DECL_SIZE];
	m_dwNumVertices = m_pMeshObject->GetNumVertices();
	m_dwNumFaces = m_pMeshObject->GetNumFaces();
	m_dwBytesPerVertex = m_pMeshObject->GetNumBytesPerVertex();
	m_pMeshObject->GetIndexBuffer(&m_pIB);
	m_pMeshObject->GetVertexBuffer(&m_pVB);
	m_pMeshObject->GetDeclaration(decl);
	APROJECT_WINDOW->GetD3DDevice()->CreateVertexDeclaration(decl, &m_pDecl);

	SAFE_RELEASE(pAdjacencyBuffer);
	SAFE_RELEASE(pMtrlBuffer);

	return true;
}
bool ApplicationClass::Frame()
{
	char text[32], itoaTemp[16], videoCard[128];

	if(!m_Input->Frame())
	{
		return false;
	}

	if(m_Input->IsKeyPressed(DIK_ESCAPE))
	{
		return false;
	}

	m_Timer->Frame();
	m_Cpu->Frame();
	m_Fps->Frame();

	_itoa_s(m_Fps->GetFps(), itoaTemp, 10);
	strcpy_s(text, "FPSTime: ");
	strcat_s(text, itoaTemp);

	if(!m_Text->UpdateString("FPS", text, m_D3D->GetDeviceContext()))
	{
	}

	_itoa_s(m_Cpu->GetCpuPercentage(), itoaTemp, 10);
	strcpy_s(text, "CPUTime: ");
	strcat_s(text, itoaTemp);
	strcat_s(text, "%");

	if(!m_Text->UpdateString("CPU", text, m_D3D->GetDeviceContext()))
	{
	}

	float x, y, z;
	m_Position->GetPosition(x, y, z);

	strcpy_s(text, "POS (X: ");
	_itoa_s((int)x, itoaTemp, 10);
	strcat_s(text, itoaTemp);

	strcat_s(text, " Y: ");
	_itoa_s((int)y, itoaTemp, 10);
	strcat_s(text, itoaTemp);

	strcat_s(text, " Z: ");
	_itoa_s((int)z, itoaTemp, 10);
	strcat_s(text, itoaTemp);

	strcat_s(text, ")");

	if(!m_Text->UpdateString("POS", text, m_D3D->GetDeviceContext()))
	{
		MessageBox(NULL, L"Failed To Update Position String", L"Error", MB_OK);
	}
	
	m_Position->GetRotation(x, y, z);

	strcpy_s(text, "ROT (X: ");
	_itoa_s((int)x, itoaTemp, 10);
	strcat_s(text, itoaTemp);

	strcat_s(text, " Y: ");
	_itoa_s((int)y, itoaTemp, 10);
	strcat_s(text, itoaTemp);

	strcat_s(text, " Z: ");
	_itoa_s((int)z, itoaTemp, 10);
	strcat_s(text, itoaTemp);

	strcat_s(text, ")");

	if(!m_Text->UpdateString("ROT", text, m_D3D->GetDeviceContext()))
	{
		MessageBox(NULL, L"Failed To Update Rotation String", L"Error", MB_OK);
	}

	float drawpct = (float)m_QuadTree->GetDrawCount() / (float)m_QuadTree->GetTriangleCount();
	_itoa_s(drawpct*100, itoaTemp, 10);
	strcpy_s(text, "Draw: ");
	strcat_s(text, itoaTemp);
	strcat_s(text, "%");
	
	if(!m_Text->UpdateString("QTR", text, m_D3D->GetDeviceContext()))
	{
	}

	_itoa_s(m_QuadTree->GetDrawCount(), itoaTemp, 10);
	strcpy_s(text, "Tri's: ");
	strcat_s(text, itoaTemp);

	if(!m_Text->UpdateString("XCS", text, m_D3D->GetDeviceContext()))
	{
	}

	if(!HandleInput(m_Timer->GetTime()))
	{
		return false;
	}

	if(!RenderGraphics())
	{
		return false;
	}

	return true;
}
Example #7
0
BOOL CAudioFormatDlg::OpenUsingRegisteredClass (CString link)
{
	TCHAR key[MAX_PATH + MAX_PATH];

	if (GetRegKey (HKEY_CLASSES_ROOT, _T (".htm"), key) == ERROR_SUCCESS) {
		LPCTSTR mode = _T ("\\shell\\open\\command");
		strcat(key, mode);
		if (GetRegKey (HKEY_CLASSES_ROOT, key, key) == ERROR_SUCCESS) {
			LPTSTR pos = strstr(key, _T ("\"%1\""));
			if (pos == NULL) {
				// No quotes found

				pos = strstr(key, _T ("%1")); // Check for %1, without quotes

				if (pos == NULL) // No parameter at all...
					pos = key + _tcslen (key) - 1;
				else
					*pos = _T ('\0'); // Remove the parameter
			} else
				*pos = _T ('\0'); // Remove the parameter

			strcat_s(pos, strlen(pos) + 2, _T (" "));
			strcat_s(pos, strlen(pos) + strlen(link) + 1, link);

			HINSTANCE result = (HINSTANCE) WinExec (key, SW_SHOW);
			if ((int) result <= HINSTANCE_ERROR) {
				CString str;
				switch ((int) result)
				{
				case 0:
					str = _T ("The operating system is out\nof memory or resources.");
					break;
				case SE_ERR_PNF:
					str = _T ("The specified path was not found.");
					break;
				case SE_ERR_FNF:
					str = _T ("The specified file was not found.");
					break;
				case ERROR_BAD_FORMAT:
					str = _T ("The .EXE file is invalid\n(non-Win32 .EXE or error in .EXE image).");
					break;
				case SE_ERR_ACCESSDENIED:
					str = _T ("The operating system denied\naccess to the specified file.");
					break;
				case SE_ERR_ASSOCINCOMPLETE:
					str = _T ("The filename association is\nincomplete or invalid.");
					break;
				case SE_ERR_DDEBUSY:
					str = _T ("The DDE transaction could not\nbe completed because other DDE transactions\nwere being processed.");
					break;
				case SE_ERR_DDEFAIL:
					str = _T ("The DDE transaction failed.");
					break;
				case SE_ERR_DDETIMEOUT:
					str = _T ("The DDE transaction could not\nbe completed because the request timed out.");
					break;
				case SE_ERR_DLLNOTFOUND:
					str = _T ("The specified dynamic-link library was not found.");
					break;
				case SE_ERR_NOASSOC:
					str = _T ("There is no application associated\nwith the given filename extension.");
					break;
				case SE_ERR_OOM:
					str = _T ("There was not enough memory to complete the operation.");
					break;
				case SE_ERR_SHARE:
					str = _T ("A sharing violation occurred.");
					break;
				default:
					str.Format (_T ("Unknown Error (%d) occurred."), (int) result);
				}
				str = _T ("Unable to open hyperlink:\n\n") + str;
				AfxMessageBox (str, MB_ICONEXCLAMATION | MB_OK);
			} else {
				return TRUE;
			}
		}
	}
	return FALSE;
}
Example #8
0
void LoadLangDll()
{
	if ((g_langid != g_ShellCache.GetLangID()) && ((g_langTimeout == 0) || (g_langTimeout < GetTickCount())))
	{
		g_langid = g_ShellCache.GetLangID();
		DWORD langId = g_langid;
		TCHAR langDll[MAX_PATH * 4] = { 0 };
		HINSTANCE hInst = NULL;
		TCHAR langdir[MAX_PATH] = { 0 };
		char langdirA[MAX_PATH] = { 0 };
		if (GetModuleFileName(g_hmodThisDll, langdir, _countof(langdir)) == 0)
			return;
		if (GetModuleFileNameA(g_hmodThisDll, langdirA, _countof(langdirA)) == 0)
			return;
		TCHAR * dirpoint = _tcsrchr(langdir, '\\');
		char * dirpointA = strrchr(langdirA, '\\');
		if (dirpoint)
			*dirpoint = 0;
		if (dirpointA)
			*dirpointA = 0;
		dirpoint = _tcsrchr(langdir, '\\');
		dirpointA = strrchr(langdirA, '\\');
		if (dirpoint)
			*dirpoint = 0;
		if (dirpointA)
			*dirpointA = 0;
		strcat_s(langdirA, "\\Languages");

		BOOL bIsWow = FALSE;
		IsWow64Process(GetCurrentProcess(), &bIsWow);

		do
		{
			if (bIsWow)
				_stprintf_s(langDll, _T("%s\\Languages\\TortoiseShell32%lu.dll"), langdir, langId);
			else
				_stprintf_s(langDll, _T("%s\\Languages\\TortoiseShell%lu.dll"), langdir, langId);
			BOOL versionmatch = TRUE;

			struct TRANSARRAY
			{
				WORD wLanguageID;
				WORD wCharacterSet;
			};

			DWORD dwReserved, dwBufferSize;
			dwBufferSize = GetFileVersionInfoSize((LPTSTR)langDll, &dwReserved);

			if (dwBufferSize > 0)
			{
				LPVOID pBuffer = (void*)malloc(dwBufferSize);

				if (pBuffer != (void*)NULL)
				{
					UINT        nInfoSize = 0;
					UINT        nFixedLength = 0;
					LPSTR       lpVersion = NULL;
					VOID*       lpFixedPointer;
					TRANSARRAY* lpTransArray;
					TCHAR       strLangProductVersion[MAX_PATH] = { 0 };

					if (GetFileVersionInfo((LPTSTR)langDll,
						dwReserved,
						dwBufferSize,
						pBuffer))
					{
						// Query the current language
						if (VerQueryValue(pBuffer,
							_T("\\VarFileInfo\\Translation"),
							&lpFixedPointer,
							&nFixedLength))
						{
							lpTransArray = (TRANSARRAY*)lpFixedPointer;

							_stprintf_s(strLangProductVersion, _T("\\StringFileInfo\\%04x%04x\\ProductVersion"),
								lpTransArray[0].wLanguageID, lpTransArray[0].wCharacterSet);

							if (VerQueryValue(pBuffer,
								(LPTSTR)strLangProductVersion,
								(LPVOID *)&lpVersion,
								&nInfoSize))
							{
								versionmatch = (_tcscmp((LPCTSTR)lpVersion, _T(STRPRODUCTVER)) == 0);
							}

						}
					}
					free(pBuffer);
				} // if (pBuffer != (void*) NULL)
			} // if (dwBufferSize > 0)
			else
				versionmatch = FALSE;

			if (versionmatch)
				hInst = LoadLibrary(langDll);
			if (hInst != NULL)
			{
				if (g_hResInst != g_hmodThisDll)
					FreeLibrary(g_hResInst);
				g_hResInst = hInst;
			}
			else
			{
				DWORD lid = SUBLANGID(langId);
				lid--;
				if (lid > 0)
				{
					langId = MAKELANGID(PRIMARYLANGID(langId), lid);
				}
				else
					langId = 0;
			}
		} while ((hInst == NULL) && (langId != 0));
		if (hInst == NULL)
		{
			// either the dll for the selected language is not present, or
			// it is the wrong version.
			// fall back to English and set a timeout so we don't retry
			// to load the language dll too often
			if (g_hResInst != g_hmodThisDll)
				FreeLibrary(g_hResInst);
			g_hResInst = g_hmodThisDll;
			g_langid = 1033;
			// set a timeout of 10 seconds
			if (g_ShellCache.GetLangID() != 1033)
				g_langTimeout = GetTickCount() + 10000;
		}
		else
			g_langTimeout = 0;
	} // if (g_langid != g_ShellCache.GetLangID())
}
noesisModel_t *Anim_DS_Load(BYTE *fileBuffer, int bufferLen, int &numMdl, noeRAPI_t *rapi)
{
	//for vanquish, append any matching dtt files (they're just paired dat files)
	char *inFile = rapi->Noesis_GetInputName();
	BYTE *skeletonFile = NULL;
	xmlSkeleton_t xml;
	xmlAnim_t xml_anim;
	bool bparsedXml = false;
	bool bparsedAnim = false;
	if (inFile && inFile[0])
	{
		char fn[MAX_NOESIS_PATH];
		rapi->Noesis_GetExtensionlessName(fn, inFile);
		rapi->Noesis_GetDirForFilePath(fn, inFile);
		strcat_s(fn, MAX_NOESIS_PATH, "Skeleton-out.hkx");

		// parsing xml
		bparsedXml = ParseSkeleton(&xml, fn, rapi);
		bparsedAnim = ParseAnim(&xml_anim, inFile, rapi);
	}

	if (!bparsedXml || !bparsedAnim)
	{
		rapi->LogOutput("An error occured while parsing the skeleton xml file...");
		return NULL;
	}

	modelBone_t * bones = rapi->Noesis_AllocBones(xml.numBones);

	for (int i = 0; i < xml.numBones; i++)
	{
		modelBone_t *bone = bones + i;

		short parent = xml.parentindices[i];
		bone->index = i;
		bone->eData.parent = (parent >= 0) ? bones + parent : NULL;
		sprintf_s(bone->name, xml.names[i].length() + 1, xml.names[i].c_str());

		g_mfn->Math_QuatToMat(xml.quat[i].q, &bone->mat, false, false);

		g_mfn->Math_VecScaleVec(bone->mat.x1, xml.scl[i].v);
		g_mfn->Math_VecScaleVec(bone->mat.x2, xml.scl[i].v);
		g_mfn->Math_VecScaleVec(bone->mat.x3, xml.scl[i].v);
		g_mfn->Math_VecCopy(xml.trn[i].v, bone->mat.o);
	}

	rapi->rpgMultiplyBones(bones, xml.numBones);

	//char* infile = rapi->Noesis_GetInputName();
	char anim_name[MAX_NOESIS_PATH];
	rapi->Noesis_GetLocalFileName(anim_name, inFile);
	std::string anim_name_t;
	anim_name_t.append(anim_name);
	for (int i = 0; i < 10; ++i)
	{
		anim_name_t.pop_back();
	}

	strcpy_s(anim_name, anim_name_t.c_str());

	int FrameNumber = xml_anim.FrameNumber;
	int TrackNumber = xml_anim.TrackNumber;
	int FloatNumber = xml_anim.FloatNumber;

	float AnimDuration = xml_anim.AnimDuration;
	float incrFrame = xml_anim.incFrame;
	int numAnimKeys = xml_anim.numAnimKeys;

	//convert anim keys to matrices
	bool printed = false;
	RichMat43 *mats = (RichMat43 *) rapi->Noesis_UnpooledAlloc(sizeof(RichMat43)*numAnimKeys);
	for (int i = 0; i < numAnimKeys; i++)
	{
		RichQuat q = xml_anim.keys[i].rot;
		modelBone_t *bone = bones + (i % xml.numBones);
		mats[i] = q.ToMat43(true);
		mats[i][3] = xml_anim.keys[i].trn;

		mats[i][1][0] = -mats[i][1][0];
		mats[i][2][0] = -mats[i][2][0];
		mats[i][3][0] = -mats[i][3][0];
		mats[i][0][1] = -mats[i][0][1];
		mats[i][0][2] = -mats[i][0][2];
	}

	int totalFrames = FrameNumber;
	float frameRate = 30;
	noesisAnim_t *na = rapi->rpgAnimFromBonesAndMatsFinish(bones, xml.numBones, (modelMatrix_t *) mats, totalFrames, frameRate);
	rapi->Noesis_UnpooledFree(mats);
	if (na)
	{
		na->aseq = rapi->Noesis_AnimSequencesAlloc(1, totalFrames);
		for (int i = 0; i < 1; i++)
		{ //fill in the sequence info
			noesisASeq_t *seq = na->aseq->s + i;

			seq->name = rapi->Noesis_PooledString(anim_name);
			seq->startFrame = 0;
			seq->endFrame = 0 + FrameNumber - 1;
			seq->frameRate = frameRate;
		}

		numMdl = 1;
	}

	noesisModel_t * my_mdl = rapi->Noesis_AllocModelContainer(NULL, na, 1);

	return my_mdl;
}
void ckLowLevelAPI::getWindowsFontDirectory(char* buf, u32 buf_size)
{
    GetWindowsDirectory(buf, buf_size);
    strcat_s(buf, buf_size, "\\Fonts\\");
}
pse_op_error_t sqlite_read_db(uint32_t leaf_id, pse_vmc_hash_tree_cache_t* cache)
{
    PROFILE_START("sqlite_read_db");
   
    int            rc;
    pse_op_error_t ret = OP_SUCCESS;
    sqlite3_stmt*  stat = NULL;
    char           sql_sentence[1024] = {0};
    int            result;
    uint32_t       node_id;
    const void*    ptr_blob_content;
    uint32_t       blob_len;
    uint32_t       record_count = 0;
    uint32_t       read_list_array[INIT_TOTAL_NODE_NUMBER_FOR_READING] = {0};
    sqlite3        *db = NULL;
    uint8_t*       node_ptr = NULL;
    uint32_t       child_node_id = leaf_id;
    uint32_t       internal_index = 0;
    uint32_t       count = 0;

    if( !cache)
    {
        PROFILE_END("sqlite_read_db");
        return OP_ERROR_INVALID_PARAMETER;
    }

    if(leaf_id < INIT_MIN_LEAF_NODE_ID || leaf_id > INIT_MAX_LEAF_NODE_ID)
    {
        PROFILE_END("sqlite_read_db");
        return OP_ERROR_INVALID_PARAMETER;
    }

    ret = sqlite_open_db(&db);
    if(OP_SUCCESS != ret) 
    {
        pse_vmc_db_state = PSE_VMC_DB_STATE_DOWN;
        PROFILE_END("sqlite_read_db");
        return ret;
    }

    // layout of read_list_array is : Leaf Node ID + ancestor Node IDs + Brother Node IDs.
    find_all_related_node_index(leaf_id, read_list_array);

    // prepare sql statement
    if (_snprintf_s(sql_sentence, sizeof(sql_sentence), "select * from HASH_TREE_NODE_TABLE where ID IN (") < 0)
    {
        ret = OP_ERROR_INTERNAL;
        goto clean_up;
    }
    
    for(uint32_t index=0; index < INIT_TOTAL_NODE_NUMBER_FOR_READING; index++)
    {
        char id[10];

        if (_snprintf_s(id, sizeof(id), "%u", read_list_array[index]) < 0) 
        {
            ret = OP_ERROR_INTERNAL;
            goto clean_up;
        }

        if (strncat_s(sql_sentence, sizeof(sql_sentence), id, strnlen_s(id, 10)) != 0)
        {
            ret = OP_ERROR_INTERNAL;
            goto clean_up;
        }

        if (index != INIT_TOTAL_NODE_NUMBER_FOR_READING - 1)
        {
            if (strncat_s(sql_sentence, sizeof(sql_sentence), ",", 1) != 0)
            {
                ret = OP_ERROR_INTERNAL;
                goto clean_up;
            }
        }
    }
    if (strcat_s(sql_sentence, sizeof(sql_sentence), ") order by ID desc") != 0)
    {
        ret = OP_ERROR_INTERNAL;
        goto clean_up;
    }

    // prepare sql statement
    rc = sqlite3_prepare_v2(db, sql_sentence, -1, &stat, 0);
    EXIT_IFNOT_SQLITE_OK(rc, clean_up)

    // query
    // the result set are sorted, from leaf to up layers
    while ((result = sqlite3_step(stat)) == SQLITE_ROW)
    {
        // to calculate number of records returned 
        record_count++;

        node_id = sqlite3_column_int(stat, 0);
        ptr_blob_content = sqlite3_column_blob(stat, 1);
        if(!ptr_blob_content)
        {
            ret = OP_ERROR_INVALID_VMC_DB;
            goto clean_up;
        }
        blob_len = sqlite3_column_bytes(stat, 1);

        if(1 == node_id)
        {
            assert(0);
            ret = OP_ERROR_INVALID_VMC_DB;
            goto clean_up;
        }
        else if(INIT_MIN_LEAF_NODE_ID <= node_id)
        {
            // node_id has already been checked and 
            // it will not exceed INIT_MAX_LEAF_NODE_ID
            assert(node_id <= INIT_MAX_LEAF_NODE_ID);

            // leaf node
            if(blob_len != LEAF_NODE_SIZE)
            {
                ret = OP_ERROR_INVALID_VMC_DB;
                goto clean_up;
            }

            if (node_id == leaf_id)
            {
                cache->self.node_id = node_id;
                node_ptr = (uint8_t*)&cache->self.leaf;
            }
            else
            {
                cache->brother.node_id = node_id;
                node_ptr = (uint8_t*)&cache->brother.leaf;
            }
        }
        else 
        {
            assert(node_id <= INIT_MAX_LEAF_NODE_ID);

            // internal nodes
            if(blob_len != INTERNAL_NODE_SIZE)
            {
                ret = OP_ERROR_INVALID_VMC_DB;
                goto clean_up;
            }

            if (node_id == child_node_id / 2)
            {
                // this is ancestor node
                node_ptr = (uint8_t*)&cache->ancestors[internal_index].internal;
                cache->ancestors[internal_index].node_id = node_id;
            }
            else 
            {
                // this is brother of ancestors
                node_ptr = (uint8_t*)&cache->brother_of_ancestors[internal_index].internal;
                cache->brother_of_ancestors[internal_index].node_id = node_id;
            }

            count++;
            if (count == 2)
            {
                // internal nodes are arranged as pairs, one is ancestor, another is the brother of the ancestor
                count = 0;
                internal_index++;   // go up a level
                child_node_id = node_id; // now current node becomes child
            }
        }

        // copy blob data to output buffer
        if(0 != memcpy_s(node_ptr, 
                        blob_len, 
                        ptr_blob_content, 
                        blob_len))
        {
            ret = OP_ERROR_INTERNAL;
            goto clean_up;
        }
    }

    if (record_count != INIT_TOTAL_NODE_NUMBER_FOR_READING)
    {
        ret = OP_ERROR_INVALID_VMC_DB;
        goto clean_up;
    }

    if (result != SQLITE_DONE)
    {
        ret = OP_ERROR_SQLITE_INTERNAL;
    }
    
clean_up:
    assert(db != NULL);
    sqlite3_finalize(stat);
    sqlite3_close_v2(db);

    PROFILE_END("sqlite_read_db");
    return ret;
}
INT_PTR CALLBACK Dlg_AchievementsReporter::AchievementsReporterProc( HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
	switch( uMsg )
	{
		case WM_INITDIALOG:
		{
			HWND hList = GetDlgItem( hDlg, IDC_RA_REPORTBROKENACHIEVEMENTSLIST );
			SetupColumns( hList );

			for( size_t i = 0; i < g_pActiveAchievements->NumAchievements(); ++i )
				AddAchievementToListBox( hList, &g_pActiveAchievements->GetAchievement( i ) );

			ListView_SetExtendedListViewStyle( hList, LVS_EX_CHECKBOXES | LVS_EX_HEADERDRAGDROP );
			SetDlgItemText( hDlg, IDC_RA_BROKENACH_BUGREPORTER, Widen( RAUsers::LocalUser().Username() ).c_str() );
		}
		return FALSE;

	case WM_COMMAND:
		switch( LOWORD( wParam ) )
		{
		case IDOK:
		{
			HWND hList = GetDlgItem( hDlg, IDC_RA_REPORTBROKENACHIEVEMENTSLIST );

			const bool bProblem1Sel = ( IsDlgButtonChecked( hDlg, IDC_RA_PROBLEMTYPE1 ) == BST_CHECKED );
			const bool bProblem2Sel = ( IsDlgButtonChecked( hDlg, IDC_RA_PROBLEMTYPE2 ) == BST_CHECKED );

			if( ( bProblem1Sel == false ) && ( bProblem2Sel == false ) )
			{
				MessageBox( nullptr, L"Please select a problem type.", L"Warning", MB_ICONWARNING );
				return FALSE;
			}

			int nProblemType = bProblem1Sel ? 1 : bProblem2Sel ? 2 : 0;	// 0==?
			const char* sProblemTypeNice = PROBLEM_STR[ nProblemType ];

			char sBuggedIDs[ 1024 ];
			sprintf_s( sBuggedIDs, 1024, "" );

			int nReportCount = 0;

			const size_t nListSize = ListView_GetItemCount( hList );
			for( size_t i = 0; i < nListSize; ++i )
			{
				if( ListView_GetCheckState( hList, i ) != 0 )
				{
					//	NASTY big assumption here...
					char buffer[ 1024 ];
					sprintf_s( buffer, 1024, "%d,", g_pActiveAchievements->GetAchievement( i ).ID() );
					strcat_s( sBuggedIDs, 1024, buffer );

					//ListView_GetItem( hList );	
					nReportCount++;
				}
			}

			if( nReportCount > 5 )
			{
				if( MessageBox( nullptr, L"You have over 5 achievements selected. Is this OK?", L"Warning", MB_YESNO ) == IDNO )
					return FALSE;
			}

			wchar_t sBugReportCommentWide[ 4096 ];
			GetDlgItemText( hDlg, IDC_RA_BROKENACHIEVEMENTREPORTCOMMENT, sBugReportCommentWide, 4096 );
			std::string sBugReportComment = Narrow( sBugReportCommentWide );

			char sBugReportInFull[ 8192 ];
			sprintf_s( sBugReportInFull, 8192,
					"--New Bug Report--\n"
					"\n"
					"Game: %s\n"
					"Achievement IDs: %s\n"
					"Problem: %s\n"
					"Reporter: %s\n"
					"ROM Checksum: %s\n"
					"\n"
					"Comment: %s\n"
					"\n"
					"Is this OK?",
					CoreAchievements->GameTitle().c_str(),
					sBuggedIDs,
					sProblemTypeNice,
					RAUsers::LocalUser().Username().c_str(),
					g_sCurrentROMMD5.c_str(),
					sBugReportComment.c_str() );

			if( MessageBox( nullptr, Widen( sBugReportInFull ).c_str(), L"Summary", MB_YESNO ) == IDNO )
				return FALSE;

			PostArgs args;
			args[ 'u' ] = RAUsers::LocalUser().Username();
			args[ 't' ] = RAUsers::LocalUser().Token();
			args[ 'i' ] = sBuggedIDs;
			args[ 'p' ] = std::to_string( nProblemType );
			args[ 'n' ] = sBugReportComment.c_str();
			args[ 'm' ] = g_sCurrentROMMD5;

			Document doc;
			if( RAWeb::DoBlockingRequest( RequestSubmitTicket, args, doc ) )
			{
				if( doc[ "Success" ].GetBool() )
				{
					char buffer[ 2048 ];
					sprintf_s( buffer, 2048, "Submitted OK!\n"
							"\n"
							"Thankyou for reporting that bug(s), and sorry it hasn't worked correctly.\n"
							"\n"
							"The development team will investigate this bug as soon as possible\n"
							"and we will send you a message on RetroAchievements.org\n"
							"as soon as we have a solution.\n"
							"\n"
							"Thanks again!" );

					MessageBox( hDlg, Widen( buffer ).c_str(), L"Success!", MB_OK );
					EndDialog( hDlg, TRUE );
					return TRUE;
				}
				else
				{
					char buffer[ 2048 ];
					sprintf_s( buffer, 2048,
							"Failed!\n"
							"\n"
							"Response From Server:\n"
							"\n"
							"Error code: %d", doc.GetParseError() );
					MessageBox( hDlg, Widen( buffer ).c_str(), L"Error from server!", MB_OK );
					return FALSE;
				}
			}
			else
			{
				MessageBox( hDlg,
							L"Failed!\n"
							L"\n"
							L"Cannot reach server... are you online?\n"
							L"\n",
							L"Error!", MB_OK );
				return FALSE;
			}
		}
		break;

		case IDCANCEL:
			EndDialog( hDlg, TRUE );
			return TRUE;
		}
		return FALSE;

	case WM_CLOSE:
		EndDialog( hDlg, FALSE );
		return TRUE;

	default:
		return FALSE;
	}
}
/**
 * @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(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->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 && !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;
}
Example #14
0
//-----------------------------------------------------------------------------
//	sends command down the serial port, puts the reply into response
//-----------------------------------------------------------------------------
static bool SendCommand(void) {

	if (!serialRunning)	{						// no comms until it's all been set up
		ERROR_MESSAGE_EXT(_T("DAQ error - serial not running\r\n"));
		return false;
	}

	WaitForSerial();

	DWORD nBytes;
	serialBusy = true;
	bool ok = true;

	strcat_s(command, COMMAND_LENGTH, "\r\n");		// append "\r\n"

	// send the command
	WriteFile(hSerialDaq, command, strlen(command), &nBytes, NULL);
	ok = (nBytes == strlen(command));

	if (ok) {
		// get the response a byte at a time until I get '\n'
		int i;
		for (i = 0; i < RESPONSE_LENGTH; i++)  {
			do {
				ReadFile(hSerialDaq, response + i, 1, &nBytes, NULL);
			} while (nBytes == 0);

/*			ReadFile(hSerialDaq, response + i, 1, &nBytes, NULL);
			// ReadFile returns true if there's a timeout
			if (!nBytes) 								// there was a timeout
				break;*/

			if (response[i] == '\n') {					// success
				ok = true;
				break;
			}
		}
		response[i + 1] = '\0';							// terminate string
	} else
		ERROR_MESSAGE_EXT(_T("SendCommand error\r\n"));


	// report any comms errors
	if (!ok) {
		serialRunning = false;
		switch (command[0]) {
			case '#':
				ERROR_MESSAGE_EXT(_T("Housekeeping board comms error\r\n"));
				break;
			case '*':
				ERROR_MESSAGE_EXT(_T("Analog board comms error\r\n"));
				break;
			case '$':
				ERROR_MESSAGE_EXT(_T("Pump drive board comms error\r\n"));
				break;
		}
	}

	serialBusy = false;
	return ok;
}
Example #15
0
BOOL CALLBACK DdkHookAppDlgProc(HWND hDlg,UINT uMsg,WPARAM wParam,LPARAM lParam) {
	int n=0;
	LVCOLUMN COL;
	BOOL RetBOOL;
	switch(uMsg) {
		case WM_INITDIALOG:
			hDdkHookAppDlg=hDlg;
			hListPS=GetDlgItem(hDlg,IDC_LIST_PS);
			hEditPS=GetDlgItem(hDlg,IDC_EDIT_PS);
			hEditState=GetDlgItem(hDlg,IDC_EDIT_STATE);
			COL.mask=LVCF_FMT|LVCF_WIDTH|LVCF_TEXT|LVCF_SUBITEM;
			COL.fmt=LVCFMT_LEFT; //왼쪽 정렬
			COL.cx=150;
			COL.pszText="ProcName"; //항목의 이름
			COL.iSubItem=0; //항목의 번호
			SendMessage(hListPS, LVM_INSERTCOLUMN,COL.iSubItem,(LPARAM)&COL);
			COL.cx=50;
			COL.pszText="ProcID"; //항목의 이름
			COL.iSubItem=1; //항목의 번호
			SendMessage(hListPS, LVM_INSERTCOLUMN,COL.iSubItem,(LPARAM)&COL);
			PSList();
			return TRUE;
		case WM_NOTIFY:
			switch(LOWORD(wParam)) {
				case IDC_LIST_PS:
					if(((LPNMHDR)lParam)->code==NM_DBLCLK) {
						char Text1[32]={0},Text2[32]={0},Temp[128]={0};
						ULONG ret;
						int iSlected=ListView_GetNextItem(hListPS,-1,LVNI_FOCUSED);
						if(iSlected==-1) {
							MessageBox(hDlg,"No Items in ListView","Error",MB_OK|MB_ICONINFORMATION);
							break;
						}
						ListView_GetItemText(hListPS,iSlected,0,Text1,32);
						strcpy_s(Temp,Text1);
						ListView_GetItemText(hListPS,iSlected,1,Text1,32);
						sprintf_s(Text2,"(%s): %s",Text1,"프로세스강제종료막음");
						strcat_s(Temp,Text2);
						SetWindowText(hEditPS,Temp);
						//-----------------------------
						handle=CreateFile(FullDeviceName,GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
						if(handle==(HANDLE)-1) {
							SetWindowText(hEditPS,"");
							MessageBox(hDlg,"CreateFile Error","Error",MB_OK);
							break;
						}
						WriteFile(handle,Text1,(DWORD)strlen(Text1),&ret,NULL);
						CloseHandle(handle);
					}
					break;
			}
			return TRUE;
		case WM_COMMAND:
			switch(LOWORD(wParam)) {
				case IDC_BT_REVIEW:
					ListView_DeleteAllItems(hListPS);
					PSList();
					break;
				case IDC_BT_DRINST:
					RetBOOL=DriverInstall(DriverName,DriverExe);
					if(!RetBOOL) SetWindowText(hEditState,"Cannot install");
					else {
						bInstall=TRUE;
						RetBOOL=DriverStart(DriverName);
						if(!RetBOOL) SetWindowText(hEditState,"Cannot start");
						else {
							bStart=TRUE;
							SetWindowText(hEditState,"Started");
						}
					}
					break;
				case IDC_BT_DRREM:
					if(bInstall) {
						RetBOOL=DriverStop(DriverName);
						if(!RetBOOL) SetWindowText(hEditState,"Cannot stop");
						else {
							bStart=FALSE;
							RetBOOL=DriverRemove(DriverName,DriverExe);
							if(!RetBOOL) SetWindowText(hEditState,"Cannot remove");
							else {
								bInstall=FALSE;
								SetWindowText(hEditState,"Removed");
							}
						}
					}
					else SetWindowText(hEditState,"Cannot remove");
					break;
			}
			return TRUE;
		case WM_CLOSE:
			if(bStart) DriverStop(DriverName);
			if(bInstall) DriverRemove(DriverName,DriverExe);
			EndDialog(hDlg,0);
			return TRUE;
	}
	return FALSE;
}
Example #16
0
void va_PrintLineConsole( char const *format, va_list args ) {
    char buffer[ kConsoleBufferSize ];
    vsprintf_s( buffer, kConsoleBufferSize, format, args );
    strcat_s( buffer, "\n" );
    printf( "%s", buffer );
}
Example #17
0
void va_PrintLine( char const *format, va_list args ) {
    char buffer[ kVSOutputBufferSize ];
    vsprintf_s( buffer, kVSOutputBufferSize, format, args );
    strcat_s( buffer, "\n" );
    OutputDebugString( buffer );
}
Example #18
0
void HeightMap::Initialize(char* mapFileName, char* textureFileName, int bitNum/*= 8*/)
{
	D3DXMatrixIdentity(&world);
	texture = TextureManager::GetTexture(textureFileName);
	ZeroMemory(&material, sizeof(D3DMATERIAL9));
	material.Ambient = D3DXCOLOR(0.7f, 0.7f, 0.7f, 1.0f);
	material.Diffuse = D3DXCOLOR(0.7f, 0.7f, 0.7f, 1.0f);
	material.Specular = D3DXCOLOR(0.7f, 0.7f, 0.7f, 1.0f);

	char fullPath[256];
	strcpy_s(fullPath, HEIGHTMAP_DIRECTORY);
	strcat_s(fullPath, mapFileName);

	FILE* fp = nullptr;
	fopen_s(&fp, fullPath, "rb");

	if (fp != nullptr)
	{
		fseek(fp, 0, SEEK_END);
		vertexCount = ftell(fp);
		fseek(fp, 0, SEEK_SET);

		//총 픽셀 개수 보정
		vertexSizeCount = vertexCount / (bitNum / 8);

		mapSize = (int)(sqrt(vertexSizeCount));

		assert(vertexSizeCount == mapSize*mapSize && "가로세로길이가 동일해야 합니다.");

		std::vector<unsigned char> fileData;
		fileData.resize(vertexSizeCount);

		if ( bitNum == 24 )
		{
			int d[3];
			for ( int i = 0; i < vertexSizeCount; ++i )
			{
				d[0] = fgetc(fp);
				d[1] = fgetc(fp) << 8;
				d[2] = fgetc(fp) << 16;
				int a = d[0] | d[1] | d[2];
				fileData[i] = a;
			}
		}
		else if ( bitNum == 16 )
		{
			int d[2];
			for ( int i = 0; i < vertexSizeCount; ++i )
			{
				d[0] = fgetc(fp);
				d[1] = fgetc(fp) << 8;
				int a = d[0] | d[1];
				fileData[i] = a;
			}
		}
		else
		{
			for ( int i = 0; i < vertexSizeCount; ++i )
			{
				fileData[i] = fgetc(fp);
			}
		}
		fclose(fp);

		tileCount = mapSize - 1;

		std::vector<FVF_PositionNormalTexture> fvfVertex;
		fvfVertex.resize(vertexSizeCount);
		vertex.resize(vertexSizeCount);

		for (int z = 0; z < mapSize; ++z)
		{
			for (int x = 0; x < mapSize; ++x)
			{
				int index = z * mapSize + x;
				FVF_PositionNormalTexture v;
				v.pos = D3DXVECTOR3((float)x, fileData[index] * 0.2f, (float)-z);
				v.normal = D3DXVECTOR3(0,1,0);
				v.tex = D3DXVECTOR2(x / (float)tileCount, z / (float)tileCount);

				fvfVertex[index] = v;
				vertex[index] = v.pos;
			}
		}

		//노말값들 갱신
		//필요한건 벡터 4개
		//왼쪽, 오른쪽, 위쪽, 아래쪽

		for (int z = 1; z < tileCount; ++z)
		{
			for (int x = 1; x < tileCount; ++x)
			{
				int index = z * mapSize + x;
				D3DXVECTOR3 left = vertex[index - 1];
				D3DXVECTOR3 right = vertex[index + 1];
				D3DXVECTOR3 front = vertex[index - mapSize];
				D3DXVECTOR3 rear = vertex[index + mapSize];
				D3DXVECTOR3 leftToRight = right - left;
				D3DXVECTOR3 frontToRear = rear - front;
				D3DXVECTOR3 normal;
				D3DXVec3Cross(&normal, &leftToRight, &frontToRear);
				D3DXVec3Normalize(&normal, &normal);

				fvfVertex[index].normal = normal;
			}
		}

		//버벡스 버퍼, 인덱스 버퍼 만들기
		std::vector<DWORD> indexData;
		triangleCount = tileCount * tileCount * 2;
		indexData.resize(triangleCount * 3);
		for (int z = 0; z < tileCount; ++z)
		{
			for (int x = 0, k = 0; x < tileCount; ++x, ++k)
			{
				int _0 = (x + 0) + (z + 0) * mapSize;
				int _1 = (x + 1) + (z + 0) * mapSize;
				int _2 = (x + 0) + (z + 1) * mapSize;
				int _3 = (x + 1) + (z + 1) * mapSize;

				indexData[z * (6 * tileCount) + k] = (_0);
				indexData[z * (6 * tileCount) + ++k] = (_1);
				indexData[z * (6 * tileCount) + ++k] = (_2);

				indexData[z * (6 * tileCount) + ++k] = (_3);
				indexData[z * (6 * tileCount) + ++k] = (_2);
				indexData[z * (6 * tileCount) + ++k] = (_1);
			}
		}
		int bufferSize = fvfVertex.size() * sizeof(FVF_PositionNormalTexture);
		GameManager::GetDevice()->CreateVertexBuffer(
			bufferSize,
			0,
			FVF_PositionNormalTexture::FVF,
			D3DPOOL_MANAGED,
			&vertexBuffer,
			nullptr);
		LPVOID pV;
		vertexBuffer->Lock(0, 0, &pV, 0);
		memcpy_s(pV, bufferSize, &fvfVertex[0], bufferSize);
		vertexBuffer->Unlock();

		bufferSize = indexData.size() * sizeof(DWORD);
		GameManager::GetDevice()->CreateIndexBuffer(
			bufferSize,
			0,
			D3DFMT_INDEX32,
			D3DPOOL_MANAGED,
			&indexBuffer,
			nullptr);
		LPVOID pI;
		indexBuffer->Lock(0, 0, &pI, 0);
		memcpy_s(pI, bufferSize, &indexData[0], bufferSize);
		indexBuffer->Unlock();
	}
}
Example #19
0
static void DoWebAccessible(HWND w,IAccessible *pAccessible,T_SUIVI_ACCESSIBLE *ptSuivi)
#endif
{
	TRACE((TRACE_ENTER,_F_, ""));

	UNREFERENCED_PARAMETER(w);
	
	HRESULT hr;
	IAccessible *pChild=NULL;
	VARIANT vtChild;
	VARIANT vtState,vtRole;
	long l,lCount;
	long returnCount;
	VARIANT* pArray = NULL;
	
#ifdef TRACES_ACTIVEES
	char szTab[200];
	strcpy_s(szTab,sizeof(szTab),paramszTab);
	if (strlen(szTab)<sizeof(szTab)-5) strcat_s(szTab,sizeof(szTab),"  ");
#endif
	
	// si fini ou erreur, on termine la récursivité
	if (ptSuivi->iErreur!=0) goto end;

	// parcours de la suite : combien de fils ?
	hr=pAccessible->get_accChildCount(&lCount);
	if (FAILED(hr)) goto end;
	TRACE((TRACE_DEBUG,_F_,"%sget_accChildCount()==%ld",szTab,lCount));

	// plus de fils ou lu assez de champs, on termine !
	if (lCount==0)
	{
		TRACE((TRACE_INFO,_F_,"%sPas de fils",szTab));
		goto end;
	}
	if (ptSuivi->iTextFieldIndex>MAX_TEXT_FIELDS)
	{
		TRACE((TRACE_INFO,_F_,"Trop de champs, on arrête la recherche dans la page (lCount=%d ptSuivi->iTextFieldIndex=%d)",lCount,ptSuivi->iTextFieldIndex));
		goto end;
	}
	if (ptSuivi->iPwdIndex!=-1 && (ptSuivi->iTextFieldIndex - ptSuivi->iPwdIndex)>10) // optimisation : on ne lit pas plus de 10 champs après le mdp
	{
		TRACE((TRACE_INFO,_F_,"Fin de la recherche dans la page (ptSuivi->iTextFieldIndex=%d ptSuivi->iPwdIndex=%d)",ptSuivi->iTextFieldIndex,ptSuivi->iPwdIndex));
		goto end;
	}

	pArray = new VARIANT[lCount];
	hr = AccessibleChildren(pAccessible, 0L, lCount, pArray, &returnCount);
	if (FAILED(hr))
	{
		TRACE((TRACE_DEBUG,_F_,"%sAccessibleChildren()=0x%08lx",szTab,hr));
	}
	else
	{
		TRACE((TRACE_DEBUG,_F_,"%sAccessibleChildren() returnCount=%d",szTab,returnCount));
		for (l=0;l<lCount;l++)
		{
			VARIANT *pVarCurrent = &pArray[l];
			VariantInit(&vtRole);
			VariantInit(&vtState);
			pChild=NULL;
				
			TRACE((TRACE_DEBUG,_F_,"%s --------------------------------- l=%ld vt=%d lVal=0x%08lx",szTab,l,pVarCurrent->vt,pVarCurrent->lVal));
			if (pVarCurrent->vt!=VT_DISPATCH) goto suivant;
			if (pVarCurrent->lVal==NULL) goto suivant; // ISSUE#80 0.96B2 
			((IDispatch*)(pVarCurrent->lVal))->QueryInterface(IID_IAccessible, (void**) &pChild);
			if (FAILED(hr)) { TRACE((TRACE_ERROR,_F_,"%sQueryInterface(IID_IAccessible)=0x%08lx",szTab,hr)); goto suivant; }
			TRACE((TRACE_DEBUG,_F_,"%sQueryInterface(IID_IAccessible)=0x%08lx -> pChild=0x%08lx",szTab,hr,pChild));
			
			vtChild.vt=VT_I4;
			vtChild.lVal=CHILDID_SELF;
			hr=pChild->get_accState(vtChild,&vtState);
			if (FAILED(hr)) { TRACE((TRACE_ERROR,_F_,"get_accState()=0x%08lx",hr)); goto suivant; }
			TRACE((TRACE_DEBUG,_F_,"%sget_accState() vtState.lVal=0x%08lx",szTab,vtState.lVal));

			hr=pChild->get_accRole(vtChild,&vtRole);
			if (FAILED(hr)) { TRACE((TRACE_ERROR,_F_,"get_accRole()=0x%08lx",hr)); goto suivant; }
			TRACE((TRACE_DEBUG,_F_,"%sget_accRole() vtRole.lVal=0x%08lx",szTab,vtRole.lVal));
			
			//hr=pChild->get_accName(vtChild,&bstrName);
			//if (FAILED(hr)) { TRACE((TRACE_ERROR,_F_,"get_accName()=0x%08lx",hr)); goto suivant; }
			//TRACE((TRACE_DEBUG,_F_,"%sget_accName() name=%S",szTab,bstrName));
			
			// Reconnaissance du champ mot de passe : Nième champ ayant pour role et state les valeurs suivantes :
			// - Role = ROLE_SYSTEM_TEXT
			// - State = (STATE_SYSTEM_FOCUSABLE | STATE_SYSTEM_FOCUSED) & STATE_SYSTEM_PROTECTED

			// Reconnaissance du champ identifiant : Nième champ précédant le champ mot de passe et ayant pour role et state les valeurs suivantes :
			// - Role = ROLE_SYSTEM_TEXT
			// - State = (STATE_SYSTEM_FOCUSABLE | STATE_SYSTEM_FOCUSED)

			// ISSUE#279 : cas spécifique IE
			// TRACE((TRACE_DEBUG,_F_,"%sptSuivi->iBrowser=%d",szTab,ptSuivi->iBrowser));
			if (ptSuivi->iBrowser!=BROWSER_IE)
			{
				if ((vtRole.lVal == ROLE_SYSTEM_TEXT) && 
					((vtState.lVal & STATE_SYSTEM_FOCUSED) || (vtState.lVal & STATE_SYSTEM_FOCUSABLE)))
				{
					// c'est un champ de saisie, s'il est protégé c'est le mdp sinon c'est un id
					if (vtState.lVal & STATE_SYSTEM_PROTECTED)
					{
						TRACE((TRACE_INFO,_F_,"Champ mot de passe trouve (ROLE_SYSTEM_TEXT + STATE_SYSTEM_FOCUS* + STATE_SYSTEM_PROTECTED)"));
						pChild->AddRef();
						ptSuivi->pTextFields[ptSuivi->iTextFieldIndex]=pChild;
						ptSuivi->iNbPwdFound++; 
						TRACE((TRACE_INFO,_F_,"Champ mot de passe trouve : c'est le %dieme, on attendait le %d",ptSuivi->iNbPwdFound,atoi(gptActions[ptSuivi->iAction].szPwdName)));
						if (ptSuivi->iNbPwdFound==atoi(gptActions[ptSuivi->iAction].szPwdName)) 
						{
							ptSuivi->iPwdIndex=ptSuivi->iTextFieldIndex;
						}
						ptSuivi->iTextFieldIndex++;
					}
					else
					{
						TRACE((TRACE_INFO,_F_,"Un champ id trouve (ROLE_SYSTEM_TEXT + STATE_SYSTEM_FOCUS*)"));
						pChild->AddRef();
						ptSuivi->pTextFields[ptSuivi->iTextFieldIndex]=pChild;
						ptSuivi->iTextFieldIndex++;
					}
				}
				else
				{
	#ifdef TRACES_ACTIVEES
					DoWebAccessible(szTab,NULL,pChild,ptSuivi);
	#else
					DoWebAccessible(NULL,pChild,ptSuivi);
	#endif
				}
			}
			else // ISSUE#279 : IE
			{
				if ((vtRole.lVal == ROLE_SYSTEM_TEXT) && !(vtState.lVal & STATE_SYSTEM_READONLY))
				{
					// c'est un champ de saisie, s'il est protégé c'est le mdp sinon c'est un id
					if (vtState.lVal & STATE_SYSTEM_PROTECTED)
					{
						TRACE((TRACE_INFO,_F_,"Champ mot de passe trouve (ROLE_SYSTEM_TEXT + STATE_SYSTEM_FOCUS* + STATE_SYSTEM_PROTECTED)"));
						pChild->AddRef();
						ptSuivi->pTextFields[ptSuivi->iTextFieldIndex]=pChild;
						ptSuivi->iNbPwdFound++; 
						TRACE((TRACE_INFO,_F_,"Champ mot de passe trouve : c'est le %dieme, on attendait le %d",ptSuivi->iNbPwdFound,atoi(gptActions[ptSuivi->iAction].szPwdName)));
						if (ptSuivi->iNbPwdFound==atoi(gptActions[ptSuivi->iAction].szPwdName)) 
						{
							ptSuivi->iPwdIndex=ptSuivi->iTextFieldIndex;
						}
						ptSuivi->iTextFieldIndex++;
					}
					else
					{
						TRACE((TRACE_INFO,_F_,"Un champ id trouve (ROLE_SYSTEM_TEXT + STATE_SYSTEM_FOCUS*)"));
						pChild->AddRef();
						ptSuivi->pTextFields[ptSuivi->iTextFieldIndex]=pChild;
						ptSuivi->iTextFieldIndex++;
					}
				}
				else
				{
	#ifdef TRACES_ACTIVEES
					DoWebAccessible(szTab,NULL,pChild,ptSuivi);
	#else
					DoWebAccessible(NULL,pChild,ptSuivi);
	#endif
				}

			}
suivant:
			if (pChild!=NULL) { pChild->Release(); pChild=NULL; }
		}
	}
	
end:
	if (pArray!=NULL) delete[] pArray;
	TRACE((TRACE_LEAVE,_F_, ""));
}
void EncryptWindow::DoDecryption ()
{
	SingleFileInfo *pinfo;

	int a = 0;
	int errorcount = 0;
	char szDestpath[SIZE_STRING];

	char szFileonly[SIZE_STRING];
	char szPathonly[SIZE_STRING];
	char szTemp[SIZE_STRING];

	char szTempdir[SIZE_STRING];
	ZeroMemory (szTempdir, SIZE_STRING);
	//strcpy_s (szTempdir, SIZE_STRING, "C:\\Temp\\TempEnc");
	GetEnvironmentVariable ("Temp", szTempdir, SIZE_STRING);
	strcat_s (szTempdir, SIZE_STRING, "\\CedeCrypt.tmp");

	Show ();
	SendMessage(m_hwndprogress, PBM_SETRANGE, 0L, MAKELONG (0, m_dlFileinfolist.GetNumItems ()));

	for (a=0;a<m_dlFileinfolist.GetNumItems ();a++) {

		pinfo = (SingleFileInfo *) m_dlFileinfolist.GetItem (a);

		if (pinfo->bIsDir == true) {
			
			ZeroMemory (szDestpath, SIZE_STRING);
			strcpy_s (szDestpath, SIZE_STRING, szTempdir);
			strcat_s (szDestpath, SIZE_STRING, "\\");

			ZeroMemory (szFileonly, SIZE_STRING);
			ZeroMemory (szPathonly, SIZE_STRING);
			
			GetPathOnly (pinfo->szRootdir, szPathonly, szFileonly, "\\");

			ZeroMemory (szTemp, SIZE_STRING);
			StripStartPath (pinfo->szRootdir, pinfo->szFilepath, szTemp);

			strcat_s (szDestpath, SIZE_STRING, szFileonly);
			strcat_s (szDestpath, SIZE_STRING, szTemp);
			
			//m_pdiag->OutputText ("Encrypt Source: ", pinfo->szFilepath);
			//m_pdiag->OutputText ("BlankFile Dest: ", szDestpath);

			if (m_enc.EncryptFileEx3 (pinfo->szFilepath, szDestpath, m_szPassword, false) == false) {
				errorcount++;
			}
		} else {

			ZeroMemory (szDestpath, SIZE_STRING);
			strcpy_s (szDestpath, SIZE_STRING, szTempdir);
			strcat_s (szDestpath, SIZE_STRING, "\\");

			ZeroMemory (szFileonly, SIZE_STRING);
			ZeroMemory (szPathonly, SIZE_STRING);

			GetPathOnly (pinfo->szFilepath, szPathonly, szFileonly, "\\");
			
			strcat_s (szDestpath, SIZE_STRING, szFileonly);

			//m_pdiag->OutputText ("BlankFile Dest: ", szDestpath);

			if (m_enc.EncryptFileEx3 (pinfo->szFilepath, szDestpath, m_szPassword, false) == false) {
				errorcount++;
			}
		}

		SendMessage (m_hwndprogress, PBM_SETPOS, a, 0L);
	}


	m_idecrypterrorcount = errorcount;
	Hide ();
}
ulong cdecl NewDisasm(ulong nOldDisasmSize, uchar *src, ulong srcsize,
					  ulong srcip, uchar *srcdec,
					  t_disasm *disasm,int disasmmode,ulong threadid)
{
	uint16_t i;
	unsigned int j;
	cs_insn *insn;
	size_t count;
	char base_str_lowercase[] = "0123456789abcdef";
	char base_str_uppercase[] = "0123456789ABCDEF";
	char *p;
	ulong nsize = nOldDisasmSize;

	if (g_EnableOllyCapstone == 0)
		return nsize;

	if (*g_pDisasmLowercase)
		p = base_str_lowercase;
	else
		p = base_str_uppercase;

	count = cs_disasm(g_cshHandle, src, srcsize, srcip, 1, &insn);
	if (count != 1)
	{
		
		fpAddToList(0, 1, "[%s error] cs_disasm(): %s.", OLLY_CAPSTONE_NAME, 
			cs_strerror(cs_errno(g_cshHandle)));
		
		return nsize; /*using result from Olly */
	}
	else
	{
		if (disasm == NULL)
		{
			cs_free(insn, count);
			return nsize;
		}

		switch(disasmmode & DISASM_MODE) /* extract disassembling mode */
		{
		case DISASM_DATA:
		case DISASM_TRACE:
		case DISASM_FILE:
		case DISASM_CODE:
		case DISASM_ALL:
		case DISASM_RTRACE:

			for (j = 0, i = 0; i < insn->size && j < TEXTLEN-2; ++i)
			{
				disasm->dump[j++] = p[insn->bytes[i] >> 4 ];
				disasm->dump[j++] = p[insn->bytes[i] & 0xf];
			}
			disasm->dump[j] = '\0';

			strcpy_s(disasm->result, TEXTLEN, insn->mnemonic);
			strcat_s(disasm->result, TEXTLEN, " ");
			strcat_s(disasm->result, TEXTLEN, insn->op_str);

			if (!(*g_pDisasmLowercase))
			{
				p = disasm->result;
				while (*p)
					*p++ = (char)toupper(*p);
			}

		case DISASM_SIZE: /* Determine command size only */
			nsize = insn->size;
			break;
		default:
			break;
		}

		cs_free(insn, count);
	}

	return nsize;
}
void EncryptWindow::DoBlankSetup ()
{
	SingleFileInfo *pinfo;

	int a = 0;
	char szDestpath[SIZE_STRING];

	char szFileonly[SIZE_STRING];
	char szPathonly[SIZE_STRING];
	char szTemp[SIZE_STRING];

	char szTempdir[SIZE_STRING];
	ZeroMemory (szTempdir, SIZE_STRING);
	//strcpy_s (szTempdir, SIZE_STRING, "C:\\Temp\\TempEnc");

	GetEnvironmentVariable ("Temp", szTempdir, SIZE_STRING);
	strcat_s (szTempdir, SIZE_STRING, "\\CedeCrypt.tmp");
	

	for (a=0;a<m_dlFileinfolist.GetNumItems ();a++) {

		pinfo = (SingleFileInfo *) m_dlFileinfolist.GetItem (a);

		if (pinfo->bIsDir == true) {
			
			ZeroMemory (szDestpath, SIZE_STRING);
			strcpy_s (szDestpath, SIZE_STRING, szTempdir);
			strcat_s (szDestpath, SIZE_STRING, "\\");

			ZeroMemory (szFileonly, SIZE_STRING);
			ZeroMemory (szPathonly, SIZE_STRING);
			
			GetPathOnly (pinfo->szRootdir, szPathonly, szFileonly, "\\");

			ZeroMemory (szTemp, SIZE_STRING);
			StripStartPath (pinfo->szRootdir, pinfo->szFilepath, szTemp);

			strcat_s (szDestpath, SIZE_STRING, szFileonly);
			strcat_s (szDestpath, SIZE_STRING, szTemp);
			
			//m_pdiag->OutputText ("Encrypt Source: ", pinfo->szFilepath);
			m_pdiag->OutputText ("BlankFile Dest: ", szDestpath);

			m_enc.SetupBlankFile (szDestpath);
		} else {

			ZeroMemory (szDestpath, SIZE_STRING);
			strcpy_s (szDestpath, SIZE_STRING, szTempdir);
			strcat_s (szDestpath, SIZE_STRING, "\\");

			ZeroMemory (szFileonly, SIZE_STRING);
			ZeroMemory (szPathonly, SIZE_STRING);

			GetPathOnly (pinfo->szFilepath, szPathonly, szFileonly, "\\");
			
			strcat_s (szDestpath, SIZE_STRING, szFileonly);

			m_pdiag->OutputText ("BlankFile Dest: ", szDestpath);

			m_enc.SetupBlankFile (szDestpath);
		}
	}
}
/**
 * @brief Display information and statistics about a .ani file.
 * @details This is called when -i switch is on when running ac.exe
 */
void anim_display_info(char *real_filename)
{
	CFILE				*fp;
	anim				A;
	float				percent;
	int				i, uncompressed, compressed, *key_frame_nums=NULL, tmp;
	char filename[MAX_FILENAME_LEN];

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

	fp = cfopen(filename, "rb");
	if ( !fp ) {
		printf("Fatal error opening %s", filename);
		return;
	}

	anim_read_header(&A, fp);
	// read the keyframe frame nums and offsets
	key_frame_nums = (int*)vm_malloc(sizeof(int)*A.num_keys);
	Assert(key_frame_nums != NULL);
	if (key_frame_nums == NULL)
		return;

	for ( i = 0; i < A.num_keys; i++ ) {
		key_frame_nums[i] = 0;
		cfread(&key_frame_nums[i], 2, 1, fp);
		cfread(&tmp, 4, 1, fp);
	}

	cfread(&compressed, 4, 1, fp);

	uncompressed = A.width * A.height * A.total_frames;	// 8 bits per pixel
	percent = i2fl(compressed) / uncompressed * 100.0f;

	printf("%% of uncompressed size:    %.0f%%\n", percent);
	printf("Width:                     %d\n", A.width);
	printf("Height:                    %d\n", A.height);
	printf("Total Frames:              %d\n", A.total_frames);

#ifndef NDEBUG
	printf("Key Frames:                %d\n", A.num_keys);
	if ( A.num_keys > 1 && (A.total_frames != A.num_keys) ) {
		printf("key list: (");
		for ( i = 0; i < A.num_keys; i++ ) {
			if ( i < A.num_keys-1 ) 
				printf("%d, ", key_frame_nums[i]);
			else
				printf("%d)\n", key_frame_nums[i]);
		}
	}
#endif

	printf("FPS:                       %d\n", A.fps);

#ifndef NDEBUG
	printf("Transparent RGB:           (%u,%u,%u)\n", A.xparent_r, A.xparent_g, A.xparent_b); 
#endif

	printf("ac version:                %d\n", A.version);

	if ( key_frame_nums != NULL ) {
		vm_free(key_frame_nums);
	}

	cfclose(fp);
}
Example #24
0
extern "C" DLL_EXPORT const char* _dbg_dbginit()
{
    if(!EngineCheckStructAlignment(UE_STRUCT_TITAN_ENGINE_CONTEXT, sizeof(TITAN_ENGINE_CONTEXT_t)))
        return "Invalid TITAN_ENGINE_CONTEXT_t alignment!";
    if(sizeof(TITAN_ENGINE_CONTEXT_t) != sizeof(REGISTERCONTEXT))
        return "Invalid REGISTERCONTEXT alignment!";
    dputs("Initializing wait objects...");
    waitinitialize();
    dputs("Initializing debugger...");
    dbginit();
    dputs("Initializing debugger functions...");
    dbgfunctionsinit();
    dputs("Setting JSON memory management functions...");
    json_set_alloc_funcs(json_malloc, json_free);
    dputs("Initializing capstone...");
    Capstone::GlobalInitialize();
    dputs("Initializing Yara...");
    if(yr_initialize() != ERROR_SUCCESS)
        return "Failed to initialize Yara!";
    dputs("Getting directory information...");
    wchar_t wszDir[deflen] = L"";
    if(!GetModuleFileNameW(hInst, wszDir, deflen))
        return "GetModuleFileNameW failed!";
    char dir[deflen] = "";
    strcpy_s(dir, StringUtils::Utf16ToUtf8(wszDir).c_str());
    int len = (int)strlen(dir);
    while(dir[len] != '\\')
        len--;
    dir[len] = 0;
    strcpy_s(alloctrace, dir);
    strcat_s(alloctrace, "\\alloctrace.txt");
    DeleteFileW(StringUtils::Utf8ToUtf16(alloctrace).c_str());
    setalloctrace(alloctrace);
    strcpy_s(dbbasepath, dir); //debug directory
    strcat_s(dbbasepath, "\\db");
    CreateDirectoryW(StringUtils::Utf8ToUtf16(dbbasepath).c_str(), 0); //create database directory
    char szLocalSymbolPath[MAX_PATH] = "";
    strcpy_s(szLocalSymbolPath, dir);
    strcat_s(szLocalSymbolPath, "\\symbols");

    char cachePath[MAX_SETTING_SIZE];
    if(!BridgeSettingGet("Symbols", "CachePath", cachePath) || !*cachePath)
    {
        strcpy_s(szSymbolCachePath, szLocalSymbolPath);
        BridgeSettingSet("Symbols", "CachePath", ".\\symbols");
    }
    else
    {
        if (_strnicmp(cachePath, ".\\", 2) == 0)
        {
            strncpy_s(szSymbolCachePath, dir, _TRUNCATE);
            strncat_s(szSymbolCachePath, cachePath + 1, _TRUNCATE);
        }
        else
        {
            // Trim the buffer to fit inside MAX_PATH
            strncpy_s(szSymbolCachePath, cachePath, _TRUNCATE);
        }

        if(strstr(szSymbolCachePath, "http://") || strstr(szSymbolCachePath, "https://"))
        {
            if(Script::Gui::MessageYesNo("It is strongly discouraged to use symbol servers in your path directly (use the store option instead).\n\nDo you want me to fix this?"))
            {
                strcpy_s(szSymbolCachePath, szLocalSymbolPath);
                BridgeSettingSet("Symbols", "CachePath", ".\\symbols");
            }
        }
    }
    dputs(szSymbolCachePath);
    SetCurrentDirectoryW(StringUtils::Utf8ToUtf16(dir).c_str());
    dputs("Allocating message stack...");
    gMsgStack = MsgAllocStack();
    if(!gMsgStack)
        return "Could not allocate message stack!";
    dputs("Initializing global script variables...");
    varinit();
    dputs("Registering debugger commands...");
    registercommands();
    dputs("Starting command loop...");
    hCommandLoopThread = CreateThread(0, 0, DbgCommandLoopThread, 0, 0, 0);
    char plugindir[deflen] = "";
    strcpy_s(plugindir, dir);
    strcat_s(plugindir, "\\plugins");
    CreateDirectoryW(StringUtils::Utf8ToUtf16(plugindir).c_str(), 0);
    dputs("Loading plugins...");
    pluginload(plugindir);
    dputs("Handling command line...");
    //handle command line
    int argc = 0;
    wchar_t** argv = CommandLineToArgvW(GetCommandLineW(), &argc);
    if(argc == 2) //we have an argument
    {
        String str = "init \"";
        str += StringUtils::Utf16ToUtf8(argv[1]);
        str += "\"";
        DbgCmdExec(str.c_str());
    }
    else if(argc == 5) //4 arguments (JIT)
    {
        if(_wcsicmp(argv[1], L"-a") == 0 && !_wcsicmp(argv[3], L"-e"))
        {
            String str = "attach .";
            str += StringUtils::Utf16ToUtf8(argv[2]);
            str += ", .";
            str += StringUtils::Utf16ToUtf8(argv[4]);
            DbgCmdExec(str.c_str());
        }
    }
    LocalFree(argv);
    dputs("Initialization successful!");
    bIsStopped = false;
    return nullptr;
}
INT_PTR CALLBACK TwoGameOverPro(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	UNREFERENCED_PARAMETER(lParam);
	static HWND hCtrlBlock;
	static int num = 0;
	HDC hDC = 0;
	PAINTSTRUCT PtStr;
	switch (message)
	{
	case WM_TIMER:
		SetTimer(hDlg, 0, 10000, 0);
		if (num) {
			KillTimer(hDlg, 0);
			PostMessage(hDlg, WM_CLOSE, wParam, lParam);
		}
		num++;
		break;
	case WM_INITDIALOG:
	{
		return (INT_PTR)TRUE;
	}
	case WM_PAINT:
	{
		char str1[20] = "YOU FOOD:";
		char str2[20] = "YOU SCORE:";
		char str3[20] = { 0 };
		hDC = BeginPaint(hDlg, &PtStr);
		_itoa_s(Point_A, str3, 20);
		strcat_s(str1, str3);
		strcat_s(str2, str3);
		strcat_s(str2, "0");
		TextOutA(hDC, 210, 460, str1, strlen(str1));
		TextOutA(hDC, 210, 490, str2, strlen(str2));

		_itoa_s(Point_B, str3, 20);
		strcpy_s(str1, "YOU FOOD:");
		strcpy_s(str2, "YOU SCORE:");
		strcat_s(str1, str3);
		strcat_s(str2, str3);
		strcat_s(str2, "0");
		TextOutA(hDC, 210 + GameWindowX_B, 460, str1, strlen(str1));
		TextOutA(hDC, 210 + GameWindowX_B, 490, str2, strlen(str2));
		EndPaint(hDlg, &PtStr);
		int Left, Right;
		if (Point_A > Point_B) {
			Left = IDB_SMILE;
			Right = IDB_CRY;
		}
		else if (Point_A < Point_B) {
			Left = IDB_CRY;
			Right = IDB_SMILE;
		}
		else {
			Left = IDB_SMILE;
			Right = IDB_SMILE;
		}
		hCtrlBlock = GetDlgItem(hDlg, IDC_PAINTA);
		Backgroundpaste(hCtrlBlock, Left, -10, 0);
		hCtrlBlock = GetDlgItem(hDlg, IDC_PAINTB);
		Backgroundpaste(hCtrlBlock, Right, 15, 0);
		PostMessage(hDlg, WM_TIMER, wParam, lParam);
	}
	break;
	case WM_COMMAND:
		if (LOWORD(wParam) == ID_OK || LOWORD(wParam) == IDCANCEL) {
			PostMessage(hDlg, WM_CLOSE, wParam, lParam);
		}
		break;
	case WM_CLOSE:
		EndDialog(hDlg, LOWORD(wParam));
		break;
	}
	return (INT_PTR)FALSE;
}
Example #26
0
bool DirectGraphicsSprite::LoadImage(char *Filename, int xs, int ys, int xfs, int yfs, 
														 int xfc,  int yfc)
{
	if(GameRunning == false) 
		return false;

	bool			fromrar;
	HRESULT			hresult;
	char			*pData; 
	char			Temp[256];
	unsigned long	Size; 

	// zuerst eine evtl benutzte Textur freigeben
	SafeRelease(itsTexture);

	fromrar = false;

	// Zuerst checken, ob sich die Grafik in einem MOD-Ordner befindet
	if (CommandLineParams.RunOwnLevelList == true)
	{
		sprintf_s(Temp, "levels/%s/%s", CommandLineParams.OwnLevelList, Filename);
		if (FileExists(Temp))
			goto loadfile;
	}

	// Dann checken, ob sich das File im Standard Ordner befindet
	sprintf_s(Temp, "data/%s", Filename);
	if (FileExists(Temp))
		goto loadfile;

	// Auch nicht? Dann ist es hoffentlich im RAR file
	if (urarlib_get(&pData, &Size, Filename, RARFILENAME, convertText(RARFILEPASSWORD)) == false)
	{		
		sprintf_s(Temp, "\n-> Error loading %s from Archive !\n", Filename);
		Protokoll.WriteText(Temp, true);
		return false;
	}
	else
		fromrar = true;

loadfile:

	// normal von Platte laden?
	if (fromrar == false)
	{
		// Textur laden
		hresult = D3DXCreateTextureFromFileEx(
				  lpD3DDevice,
				  Temp,
				  NULL, NULL,				  // x und y Grösse des Sprites (aus Datei übernehmen)
				  1,                          // Nur eine Version der Textur
				  0,                          // Immer 0 setzen
				  D3DFMT_UNKNOWN,			  // Format aus der Datei lesen
				  D3DPOOL_MANAGED,            // DX bestimmt wo die Textur gespeichert wird 
				  D3DX_FILTER_NONE,			  // Keine Filter verwenden
				  D3DX_FILTER_NONE,
				  0xFFFF00FF,                 // Colorkeyfarbe (Lila)
				  NULL,						  // Keine Image Info
				  NULL,						  // Keine Palette angeben
				  &itsTexture);
	}
	else
	{
		// Textur aus Speicher erzeugen
		hresult = D3DXCreateTextureFromFileInMemoryEx(
				  lpD3DDevice,
				  (LPVOID)pData,
				  Size, 
				  NULL, NULL,				  // x und y Grösse des Sprites (aus Datei übernehmen)
				  1,                          // Nur eine Version der Textur
				  0,                          // Immer 0 setzen
				  D3DFMT_UNKNOWN,			  // Format aus der Datei lesen
				  D3DPOOL_MANAGED,            // DX bestimmt wo die Textur gespeichert wird 
				  D3DX_FILTER_NONE,			  // Keine Filter verwenden
				  D3DX_FILTER_NONE,
				  0xFFFF00FF,                 // Colorkeyfarbe (Lila)
				  NULL,						  // Keine Image Info
				  NULL,						  // Keine Palette angeben
				  &itsTexture);

		free(pData);
	}

	// Fehler beim Laden ?
	if(hresult != D3D_OK)
	{
		strcpy_s(Temp, strlen("Fehler beim Laden von ") + 1, "Fehler beim Laden von ");
		strcat_s(Temp, strlen(Filename) + 1, Filename);
		strcat_s(Temp, 4, " !\n");
		Protokoll.WriteText(Temp, true);
		return false;
	}
	
	// Grösse der Textur anpassen
	D3DSURFACE_DESC desc;
	itsTexture->GetLevelDesc(0,&desc);	

	// Grösse setzen
	itsXSize		= (float)desc.Width;
	itsYSize		= (float)desc.Height;
	itsXFrameCount	= xfc;
	itsYFrameCount	= yfc;
	itsXFrameSize	= xfs;
	itsYFrameSize	= yfs;
	itsRect.left	= 0;
	itsRect.top		= 0;
	itsRect.right	= (int)itsXSize;
	itsRect.bottom	= (int)itsYSize;

	// Ausschnitte vorberechnen
	for (int i = 0; i < xfc * yfc; i++)
	{
		itsPreCalcedRects[i].top	= (i/itsXFrameCount) * itsYFrameSize;
		itsPreCalcedRects[i].left	= (i%itsXFrameCount) * itsXFrameSize;
		itsPreCalcedRects[i].right  = itsPreCalcedRects[i].left + itsXFrameSize;
		itsPreCalcedRects[i].bottom = itsPreCalcedRects[i].top  + itsYFrameSize;
	}

	itsRect = itsPreCalcedRects[0];

	// Bild korrekt geladen
	sprintf_s(Temp, "%s %s %s %s", TextArray [TEXT_LADE_BITMAP], Filename, TextArray [TEXT_LADEN_ERFOLGREICH], "\n");
	Protokoll.WriteText(Temp, false);			

	DisplayLoadInfo(Temp);

	LoadedTextures++;							// Anzahl der geladenen Texturen erhöhen
	//_itoa_s(LoadedTextures, Temp, 10);
//	Protokoll.WriteText(Temp, false);
//	Protokoll.WriteText(" Sprite Textur(en) geladen !\n", false);
	return true;
}
Example #27
0
// Update the scene - move/rotate each model and the camera, then update their matrices
void CScene::UpdateScene( float frameTime )
{
	//Show Framerate
	char caption[100];
	char buffer[6];
	
	//copy in base text
	strcpy_s( caption,  "Final Project - Project SPARTA - FPS:");
	
	//calculate FPS
	int FPS = int ( 1.0f / frameTime );
	
	//convert to string in base 10 and add to caption
	_itoa_s( FPS,buffer,10 );
	strcat_s( caption, buffer );
	
	//add in object and light counts as above
	strcat_s( caption, " O: " );
	_itoa_s( miNumObjects, buffer, 10 );
	strcat_s( caption, buffer );

	strcat_s( caption, " L: " );
	_itoa_s( miNumLights, buffer, 10 );
	strcat_s( caption, buffer );

	//pass the new caption to the window
	SetWindowTextA( HWnd, caption );

	// Control camera position and update its matrices (view matrix, projection matrix) each frame
	// Don't be deceived into thinking that this is a new method to control models - the same code we used previously is in the camera class
	Camera.Control( frameTime, Key_Up, Key_Down, Key_Left, Key_Right, Key_W, Key_S, Key_A, Key_D );
	Camera.UpdateMatrices();
	

	//update all the objects, including calculating the matrix
	for(int i = 0; i < miNumObjects; i++)
	{
		mpObjects[i]->Update(frameTime);
	}

	//same for the lights
	for(int i = 0; i < miNumLights; i++)
	{
		mpLights[i]->Update(frameTime);
	}


	// Allow user to quit with escape key
	if (KeyHit( Key_Escape )) 
	{
		DestroyWindow( HWnd );
	}

	if (KeyHit( Key_F1 ) )
	{
		mb_showCost = !mb_showCost;
		mb_showWallIM = false;
		mb_showPathIM = false;
		mb_showBaseIM = false;
		mb_showBase2IM = false;
		mb_showHTIM = false;
		mb_showLTIM = false;
		mb_showMTIM = false;
	}

	if (KeyHit( Key_F2 ) )
	{
		mb_showCost = false;
		mb_showWallIM = !mb_showWallIM;
		mb_showPathIM = false;
		mb_showBaseIM = false;
		mb_showBase2IM = false;
		mb_showHTIM = false;
		mb_showLTIM = false;
		mb_showMTIM = false;
	}

	if (KeyHit( Key_F3 ) )
	{
		mb_showCost = false;
		mb_showWallIM = false;
		mb_showPathIM = !mb_showPathIM;
		mb_showBaseIM = false;
		mb_showBase2IM = false;
		mb_showHTIM = false;
		mb_showLTIM = false;
		mb_showMTIM = false;
	}

	if (KeyHit( Key_F4 ) )
	{
		mb_showCost = false;
		mb_showWallIM = false;
		mb_showPathIM = false;
		mb_showBaseIM = !mb_showBaseIM;
		mb_showBase2IM = false;
		mb_showHTIM = false;
		mb_showLTIM = false;
		mb_showMTIM = false;
	}

	if (KeyHit( Key_F5 ) )
	{
		mb_showCost = false;
		mb_showWallIM = false;
		mb_showPathIM = false;
		mb_showBaseIM = false;
		mb_showBase2IM = !mb_showBase2IM;
		mb_showHTIM = false;
		mb_showLTIM = false;
		mb_showMTIM = false;
	}

	if (KeyHit( Key_F6 ) )
	{
		mb_showCost = false;
		mb_showWallIM = false;
		mb_showPathIM = false;
		mb_showBaseIM = false;
		mb_showBase2IM = false;
		mb_showHTIM = !mb_showHTIM;
		mb_showLTIM = false;
		mb_showMTIM = false;
	}

	if (KeyHit( Key_F7 ) )
	{
		mb_showCost = false;
		mb_showWallIM = false;
		mb_showPathIM = false;
		mb_showBaseIM = false;
		mb_showBase2IM = false;
		mb_showHTIM = false;
		mb_showLTIM = !mb_showLTIM;
		mb_showMTIM = false;
	}

	if (KeyHit( Key_F8 ) )
	{
		mb_showCost = false;
		mb_showWallIM = false;
		mb_showPathIM = false;
		mb_showBaseIM = false;
		mb_showBase2IM = false;
		mb_showHTIM = false;
		mb_showLTIM = false;
		mb_showMTIM = !mb_showMTIM;
	}
}
//Generates a list of available campaigns. Sets active campaign to "freespace2.fc2", or if that is unavailable, the first campaign found
void pilot_set_start_campaign(player* p)
{
	char wild_card[10];
	int i, j, incr = 0;
	char *t = NULL;
	int rc = 0;
	char *campaign_file_list[MAX_CAMPAIGNS];

	memset(wild_card, 0, sizeof(wild_card));
	strcpy_s(wild_card, NOX("*"));
	strcat_s(wild_card, FS_CAMPAIGN_FILE_EXT);

	// set filter for cf_get_file_list() if there isn't one set already (the simroom has a special one)
	if (Get_file_list_filter == NULL)
		Get_file_list_filter = campaign_file_list_filter;

	// now get the list of all campaign names
	// NOTE: we don't do sorting here, but we assume CF_SORT_NAME, and do it manually below
	rc = cf_get_file_list(MAX_CAMPAIGNS, campaign_file_list, CF_TYPE_MISSIONS, wild_card, CF_SORT_NONE);

	for (i = 0; i < rc; i++) 
	{
		if (!stricmp(campaign_file_list[i], Default_campaign_file_name))
		{
			strcpy_s(p->current_campaign, campaign_file_list[i]);
			return;
		}
	}

	// now sort everything
	incr = local_num_campaigns / 2;

	while (incr > 0) {
		for (i = incr; i < local_num_campaigns; i++) {
			j = i - incr;
	
			while (j >= 0) {
				char *name1 = Campaign_names[j];
				char *name2 = Campaign_names[j + incr];

				// if we hit this then a coder probably did something dumb (like not needing to sort)
				if ( (name1 == NULL) || (name2 == NULL) ) {
					Int3();
					break;
				}

				if ( !strnicmp(name1, "the ", 4) )
					name1 += 4;

				if ( !strnicmp(name2, "the ", 4) )
					name2 += 4;

				if (stricmp(name1, name2) > 0) {
					// first, do filenames
					t = campaign_file_list[j];
					campaign_file_list[j] = campaign_file_list[j + incr];
					campaign_file_list[j + incr] = t;

					j -= incr;
				} else {
					break;
				}
			}
		}

		incr /= 2;
	}

	if (rc > 0)
		strcpy_s(p->current_campaign, campaign_file_list[0]);
	else
		strcpy_s(p->current_campaign, "<none>");

}
Example #29
0
DWORD WINAPI myThread1(LPVOID lpParameter)
{
	SOCKET new_socket = *((SOCKET*)lpParameter);
    char hashsend[256] = "1q2w3e4r";//Случайная последовательность

    char answer[1024];
    char buffer[256];
    int n;
    //Аутентификация пользователя
    int is_auntentity_ok = 0;
    char savebuf[256];
     //do
    // {
         n = send(new_socket,"Please, give me your username and password via blank:",255,0);
       //  if (n < 0)
       //      error("ERROR writing to socket");

         memset(buffer,0,256);//Взятие данных от пользователя
         n = recv(new_socket,buffer,256,0);
         Sleep(5);
        // if (n < 0)
        //     error("ERROR reading from socket");
         printf("Here is the message: %s\n",buffer);
         char temp[256];
         memset(temp,0,256);
         memset(savebuf,0,256);
         strncpy_s(temp,buffer,strlen(buffer));
         struct ArrFields arrfields = readFile();
         int i = 0;
         int yes = 0;
         for(i = 0; i < arrfields.size; i++)
         {
             char usrpassw [256];
             memset(usrpassw,0,256);
             strcat_s(usrpassw,arrfields.arr[i].username);
             strcat_s(usrpassw," ");
             strcat_s(usrpassw,arrfields.arr[i].password);
             if(strcmp(temp,usrpassw) == 0)
             {
                 yes = 1;
                 strncpy_s(savebuf,temp,strlen(temp));
             }
         }
         printf("%i\n",yes);
         if(yes == 1)
         {
             is_auntentity_ok = 1;
             printf("%s\n",hashsend);
             printf("%i\n",strlen(hashsend));
             n = send(new_socket,hashsend,strlen(hashsend),0);
       //      if (n < 0)
       //          error("ERROR writing to socket");
         }
         else
         {
             n = send(new_socket,"Polzovatel' and Parol' neverny!",255,0);
      //       if (n < 0)
      //           error("ERROR writing to socket");
             //close(newsockfd);
             //killclient();
         }
   //  } while(is_auntentity_ok != 1);
     is_auntentity_ok = 0;
    // do
    // {
          char hashbuf[256];
          memset(hashbuf,0,256);
          strcat_s(hashbuf,savebuf);
          strcat_s(hashbuf,hashsend);
         printf("%s\n",hashbuf);
         printf("%i\n",strlen(hashbuf));
         unsigned int res = HashH37(hashbuf);//Вычисление хэш-функции
         printf("%i\n",res);
         char ans [256];
         memset(ans,0,256);
         memset(buffer,0,256);
         sprintf_s(buffer, "%d", res);
         strcpy_s(ans,buffer);
         printf("Подсчитанный хеш: %s\n",ans);
         printf("Подсчитанный хеш длина: %i\n",strlen(ans));
         memset(buffer,0,256);
         n = recv(new_socket,buffer,256,0);
         printf("Полученный хеш: %s\n",buffer);
         printf("Полученный хеш длина: %i\n",strlen(buffer));
      //   if (n < 0)
      //       error("ERROR reading from socket");
         if (strcmp(ans,buffer) == 0)
         {
             printf("Hash ok\n");
             n = send(new_socket,"Hello!",255,0);
      //       if (n < 0)
      //           error("ERROR writing to socket");
             is_auntentity_ok = 1;
            }
         else
         {
             printf("Hash not ok\n");
             n = send(new_socket,"Hash neveren",255,0);
       //      if (n < 0)
        //         error("ERROR writing to socket");
             killclient();
            }
    // } while(is_auntentity_ok != 1);
     while(1)
     {
         memset(buffer,0,256);
         memset(answer,0,256);
         n = recv(new_socket,buffer,256,0);
       //  if (n < 0)
       //      error("ERROR reading from socket");
         printf("Here is the message: %s\n",buffer);
         char tempbuf[256];
         memset(tempbuf,0,256);
         strncpy_s(tempbuf,buffer,strlen(buffer)-1);
         printf("%s\n",tempbuf);
         if(strcmp(tempbuf,"logout") == 0)
         {
             printf("logout yes\n");
             n = send(new_socket,"Good Buy!",255,0);
    //         if (n < 0)
    //             error("ERROR writing to socket");
             char path[256];
             memset(path,0,256);
             closesocket(new_socket);
         }
         else if(strcmp(tempbuf,"who") == 0)
         {
             printf("who yes\n");
             char whomessage[1024];
             memset(whomessage,0,1024);
             chDirectory(arrfields, "/home/anton/workspace/tcpproj", "Anton");
             strcpy_s(whomessage,createWhoMessage(arrfields));
             n = send(new_socket,whomessage,255,0);
    //         if (n < 0)
     //            error("ERROR writing to socket");
         }

         else
         {
             printf("%s\n",buffer);


             FILE *fp;
             int status;
             char path[256];
             memset(path,0,256);
             fp = _popen(buffer, "r");
             if (fp == NULL)
                 error("Failed to execute a command in the terminal\n");
             char prov[256];
             memset(prov,0,256);
             strncpy_s(prov,buffer,strlen(buffer)-1);
             if((strcmp(prov,"cd") == 0) || (strcmp(prov,"cd ..") == 0))
             {
                 printf("cdok");
                 strcpy_s(answer,"cdok");
             }
             else {
                 while (fgets(path, 256, fp) != NULL)
                 {
                     printf("%s", path);
                     memset(buffer,0,256);
                     strncpy_s(buffer,path,strlen(path));
                     strcat_s(answer,buffer);
                 }
             }
             n = send(new_socket,answer,strlen(answer),0);
    //         if (n < 0)
    //             error("ERROR writing to socket");
             status = _pclose(fp);
             if (status == -1) {
                 error("Error with executing of command\n");
             }
         }
     }
     closesocket(new_socket);
	return 0;
}
Example #30
-1
/**
**  Handle keys in input mode.
**
**  @param key  Key scancode.
**  @return     True input finished.
*/
static int InputKey(int key)
{
	switch (key) {
		case SDLK_RETURN:
		case SDLK_KP_ENTER: { // RETURN
			// Replace ~~ with ~
			Replace2TildeByTilde(Input);
#ifdef DEBUG
			if (Input[0] == '-') {
				if (!GameObserve && !GamePaused && !GameEstablishing) {
					CommandLog("input", NoUnitP, FlushCommands, -1, -1, NoUnitP, Input, -1);
					CclCommand(Input + 1, false);
				}
			} else
#endif
				if (!IsNetworkGame()) {
					if (!GameObserve && !GamePaused && !GameEstablishing) {
						if (HandleCheats(Input)) {
							CommandLog("input", NoUnitP, FlushCommands, -1, -1, NoUnitP, Input, -1);
						}
					}
				}

			// Check for Replay and ffw x
#ifdef DEBUG
			if (strncmp(Input, "ffw ", 4) == 0) {
#else
			if (strncmp(Input, "ffw ", 4) == 0 && ReplayGameType != ReplayNone) {
#endif
				FastForwardCycle = atoi(&Input[4]);
			}

			if (Input[0]) {
				// Replace ~ with ~~
				ReplaceTildeBy2Tilde(Input);
				char chatMessage[sizeof(Input) + 40];
				snprintf(chatMessage, sizeof(chatMessage), "~%s~<%s>~> %s",
						 PlayerColorNames[ThisPlayer->Index].c_str(),
						 ThisPlayer->Name.c_str(), Input);
				// FIXME: only to selected players ...
				NetworkSendChatMessage(chatMessage);
			}
		}
	// FALL THROUGH
		case SDLK_ESCAPE:
			KeyState = KeyStateCommand;
			UI.StatusLine.Clear();
			return 1;

#ifdef USE_MAC
		case SDLK_DELETE:
#endif
		case SDLK_BACKSPACE:
			if (InputIndex) {
				if (Input[InputIndex - 1] == '~') {
					Input[--InputIndex] = '\0';
				}
				InputIndex = UTF8GetPrev(Input, InputIndex);
				if (InputIndex >= 0) {
					Input[InputIndex] = '\0';
					ShowInput();
				}
			}
			return 1;

		case SDLK_TAB: {
			char *namestart = strrchr(Input, ' ');
			if (namestart) {
				++namestart;
			} else {
				namestart = Input;
			}
			if (!strlen(namestart)) {
				return 1;
			}
			for (int i = 0; i < PlayerMax; ++i) {
				if (Players[i].Type != PlayerPerson) {
					continue;
				}
				if (!strncasecmp(namestart, Players[i].Name.c_str(), strlen(namestart))) {
					InputIndex += strlen(Players[i].Name.c_str()) - strlen(namestart);
					strcpy_s(namestart, sizeof(Input) - (namestart - Input), Players[i].Name.c_str());
					if (namestart == Input) {
						InputIndex += 2;
						strcat_s(namestart, sizeof(Input) - (namestart - Input), ": ");
					}
					ShowInput();
				}
			}
			return 1;
		}
		default:
			if (key >= ' ') {
				gcn::Key k(key);
				std::string kstr = k.toString();
				if (key == '~') {
					if (InputIndex < (int)sizeof(Input) - 2) {
						Input[InputIndex++] = key;
						Input[InputIndex++] = key;
						Input[InputIndex] = '\0';
						ShowInput();
					}
				} else if (InputIndex < (int)(sizeof(Input) - kstr.size())) {
					for (size_t i = 0; i < kstr.size(); ++i) {
						Input[InputIndex++] = kstr[i];
					}
					Input[InputIndex] = '\0';
					ShowInput();
				}
				return 1;
			}
			break;
	}
	return 0;
}

/**
**  Save a screenshot.
*/
static void Screenshot()
{
	CFile fd;
	char filename[30];

	for (int i = 1; i <= 99; ++i) {
		// FIXME: what if we can't write to this directory?
		snprintf(filename, sizeof(filename), "screen%02d.png", i);
		if (fd.open(filename, CL_OPEN_READ) == -1) {
			break;
		}
		fd.close();
	}
	SaveScreenshotPNG(filename);
}