Beispiel #1
0
//  call of the read function
BOOL GETCCD(UINT drvno, void* dioden, ULONG fftlines, long fkt, ULONG zadr)	
{	//starts data transfer and gets data in buffer dioden
	//drvno: driver number 1..4; 1 for LSCISA1
	//dioden: pointer to destination array of ULONGs
	//fftlines: vertical lines of FFT sensors: vclks=2 * no of lines
	//fkt:  -1=clrread; 0=init dest array with 0; 1=standard read; 2=add to data
	//zadr: cam address on bus -> for series2000 addressed mode
	//returns true; false on error

  	BOOL fResult=FALSE;
	DWORD   ReturnedLength = 0;
	pArrayT pReadArray = NULL;
	pArrayT pCorArray = NULL;
	pArrayT	pDiodenBase = NULL;
	pArrayT	pDiodenBase2 = NULL;
	ULONG arraylength=0;
	sCCDFkts CCDfkt;
	ULONG i = 0;
	BOOL addalloc=FALSE;
	BOOL coralloc=FALSE;
	BYTE chl = 1;
	BYTE chh = 1;

	if (! aINIT[drvno]) return FALSE;	// return with error if no init

	//set function recs
	CCDfkt.Adrwaits = aXCKDelay[drvno]; // pass wait between XCK and ND
	if (_TI)
		{
		CCDfkt.Waits = 0;  // 6000 only valid for  TI sensors, time of vclks in 0 = 2mu
		CCDfkt.Vclks = fftlines * 4;
		}
	  else
		{
		CCDfkt.Waits = 6000;  // 6000 only valid for  FFT sensors, time of vclks in ns = 6000
		CCDfkt.Vclks = fftlines * 2;
		}
	CCDfkt.Fkt	= fkt;
	CCDfkt.Zadr = zadr;

	pReadArray = (pArrayT)dioden;
//	pReadArray = pReadArray + (db-1) * pixel;
	pDiodenBase = pReadArray;
	arraylength = aPIXEL[drvno] * sizeof(ArrayT); //length in bytes


	
	if (fkt==0) // set array to 0
		{
		for (i=0;i<	_PIXEL;i++)
			*(pReadArray++) = 0;
		return TRUE;
		}


	if  (fkt>2)
		return FALSE;  // function not implemented

	#if (_IR2)
		//alloc array for correction 4 x pixel
		//for IR - need 2. array
		pDiodenBase2 = (pArrayT)dioden + aPIXEL[drvno];
		pCorArray = (pArrayT) calloc(aPIXEL[drvno]*4,sizeof(ArrayT));
		if (pCorArray==0) 		
			{ErrorMsg("alloc Cor Buffer failed");
			return FALSE; }
		coralloc=TRUE;
		pReadArray = pCorArray;
		arraylength *= 4;
		CCDfkt.Fkt = 1;		//make standard read
	#else
		// here normal read
		if (fkt!=1) //read in our local array ladioden - add and clrread
			{
			//alloc local array dioden, so we don't overwrite our DIODEN
			pReadArray = (pArrayT) calloc(aPIXEL[drvno],sizeof(ArrayT)); 
			if (pReadArray==0) 		
				{ErrorMsg("alloc ADD/CLR Buffer failed");
				return FALSE; }
			addalloc=TRUE;
			CCDfkt.Fkt = 1;		//make standard read
			}

	
		if ((_IR) && (!addalloc))
			{
			//alloc local array because it is 2*PIXEL -> has to be resortet later
			pReadArray = (pArrayT) calloc(aPIXEL[drvno],sizeof(ArrayT)); 
			if (pReadArray==0) 		
				{ErrorMsg("alloc IR Buffer failed");
				return FALSE; }
			addalloc=TRUE;
			CCDfkt.Fkt = 1;	
			}

	#endif
	
		
	//read camera data
	fResult = DeviceIoControl(ahCCDDRV[drvno],IOCTL_GetCCD,  
		 					&CCDfkt, sizeof(CCDfkt),
							pReadArray,arraylength,
							&ReturnedLength,NULL);
	
	if ((! fResult) || (ReturnedLength!=arraylength))
		{ErrorMsg("Read DMA Buffer failed");
		if (addalloc) free(pReadArray);
		if (coralloc) free(pCorArray);
		return FALSE; }

	//clrread and add: fkt=-1 and 2 could not be implemented with dma
	//so we do it here after reading
	if (fkt==-1)
	{ // return , nothing else to do
		if (addalloc) free(pReadArray);
		if (coralloc) free(pCorArray);
		return TRUE;
		}
 
	if (_RESORT) Resort(drvno,pReadArray);	

	if ((_IR) && (fkt!=2)) // copy back
			{
			pDiodenBase2=pReadArray;
			for (i=0;i<	_PIXEL;i++)
				* (pDiodenBase++) = * (pDiodenBase2++); 
			}

	if (fkt==2) // we must now add our data to DIODEN for online add
			{
			pDiodenBase2=pReadArray;
			for (i=0;i<	_PIXEL;i++)
				* (pDiodenBase++) += * (pDiodenBase2++); 
			}

	if (addalloc) free(pReadArray);
	if (coralloc) free(pCorArray);
	
#if _IS_C4350
//special for Ha Detector head C4350
	V_On(drvno);  //starts new read sequence to Fifo
	V_Off(drvno);
//special end
#endif



	return TRUE; // no Error, all went fine
	};  // GETCCD
Beispiel #2
0
bool _3dsLoadSubChunks(HANDLE h, CHUNK *root, DWORD offset, DWORD length)
{
	while(length)
	{
		SetFilePointer(h, offset, 0, 0);

		CHUNK *chunk;
		chunk = new CHUNK;
		memset(chunk, 0, sizeof(CHUNK));
		LINK(root->Child, chunk);
		chunk->offset = offset;

		DWORD dwR = 0;
		ReadFile(h, &chunk->hdr, sizeof(CHUNK_HDR), &dwR, 0);
		if(dwR != sizeof(CHUNK_HDR))
		{
			ErrorMsg("read error");
			return false;
		}

		length -= chunk->hdr.length;
		offset += chunk->hdr.length;

		switch(chunk->hdr.id)
		{
		// just read data
		case POINT_ARRAY:
		case MSH_MAT_GROUP:
		case MAT_NAME:
		case COLOR_24:
		case MAT_MAPNAME:
		case TEX_VERTS:
			chunk->data_size = chunk->hdr.length - sizeof(CHUNK_HDR);
			chunk->data = _3dsLoadData(h, chunk->offset + sizeof(CHUNK_HDR), chunk->data_size);
			if(!chunk->data) return false;
			break;

		// just read chunks
		case MDATA:
		case N_TRI_OBJECT:
		case MAT_ENTRY:
		case MAT_DIFFUSE:
		case MAT_SPECULAR:
		case MAT_TEXMAP:
			if(!_3dsLoadSubChunks(h, chunk, chunk->offset + sizeof(CHUNK_HDR), chunk->hdr.length - sizeof(CHUNK_HDR))) return false;
			break;

		case NAMED_OBJECT:
			{
				char str[11];
				dwR = 0;
				ReadFile(h, str, 11, &dwR, 0);
				if(dwR != 11)
				{
					ErrorMsg("read error");
					return false;
				}

				chunk->data_size = strlen(str) + 1;
				chunk->data = malloc(chunk->data_size);
				memcpy(chunk->data, str, chunk->data_size);

				if(!_3dsLoadSubChunks(h, chunk, chunk->offset + sizeof(CHUNK_HDR) + chunk->data_size, chunk->hdr.length - sizeof(CHUNK_HDR) - chunk->data_size)) return false;
			}
			break;

		case FACE_ARRAY:
			{
				WORD w;
				dwR = 0;
				ReadFile(h, &w, sizeof(WORD), &dwR, 0);
				if(dwR != sizeof(WORD))
				{
					ErrorMsg("read error");
					return false;
				}

				chunk->data_size = sizeof(WORD) + w * sizeof(_3DS_FACE);
				chunk->data = _3dsLoadData(h, chunk->offset + sizeof(CHUNK_HDR), chunk->data_size);

				if(!_3dsLoadSubChunks(h, chunk, chunk->offset + sizeof(CHUNK_HDR) + chunk->data_size, chunk->hdr.length - sizeof(CHUNK_HDR) - chunk->data_size)) return false;
			}
			break;

		default: // unknow
			UNLINK(root->Child, chunk);
			delete chunk;
		}
	}

	return true;
}
bool D3D11App::initAPI(const API_Revision api_revision, const DXGI_FORMAT backBufferFmt, const DXGI_FORMAT depthBufferFmt, const int samples, const uint flags)
{
	backBufferFormat = backBufferFmt;
	depthBufferFormat = depthBufferFmt;
	msaaSamples = samples;

	const bool sampleBackBuffer = (flags & SAMPLE_BACKBUFFER) != 0;

//	if (screen >= GetSystemMetrics(SM_CMONITORS)) screen = 0;

	IDXGIFactory1 *dxgiFactory;
	if (FAILED(CreateDXGIFactory1(__uuidof(IDXGIFactory1), (void **) &dxgiFactory)))
	{
		ErrorMsg("Couldn't create DXGIFactory");
		return false;
	}

	IDXGIAdapter1 *dxgiAdapter;
	if (dxgiFactory->EnumAdapters1(0, &dxgiAdapter) == DXGI_ERROR_NOT_FOUND)
	{
		ErrorMsg("No adapters found");
		return false;
	}

//	DXGI_ADAPTER_DESC1 adapterDesc;
//	dxgiAdapter->GetDesc1(&adapterDesc);

	IDXGIOutput *dxgiOutput;
	if (dxgiAdapter->EnumOutputs(0, &dxgiOutput) == DXGI_ERROR_NOT_FOUND)
	{
		ErrorMsg("No outputs found");
		return false;
	}

	DXGI_OUTPUT_DESC oDesc;
	dxgiOutput->GetDesc(&oDesc);


	// Find a suitable fullscreen format
	int targetHz = 85;
	DXGI_RATIONAL fullScreenRefresh;
	int fsRefresh = 60;
	fullScreenRefresh.Numerator = fsRefresh;
	fullScreenRefresh.Denominator = 1;
	char str[128];

	uint nModes = 0;
	dxgiOutput->GetDisplayModeList(backBufferFormat, 0, &nModes, NULL);
	DXGI_MODE_DESC *modes = new DXGI_MODE_DESC[nModes];
	dxgiOutput->GetDisplayModeList(backBufferFormat, 0, &nModes, modes);

	resolution->clear();
	for (uint i = 0; i < nModes; i++)
	{
		if (modes[i].Width >= 640 && modes[i].Height >= 480)
		{
			sprintf(str, "%dx%d", modes[i].Width, modes[i].Height);
			int index = resolution->addItemUnique(str);

			if (int(modes[i].Width) == fullscreenWidth && int(modes[i].Height) == fullscreenHeight)
			{
				int refresh = modes[i].RefreshRate.Numerator / modes[i].RefreshRate.Denominator;
				if (abs(refresh - targetHz) < abs(fsRefresh - targetHz))
				{
					fsRefresh = refresh;
					fullScreenRefresh = modes[i].RefreshRate;
				}
				resolution->selectItem(index);
			}
		}
	}
	delete [] modes;

	sprintf(str, "%s (%dx%d)", getTitle(), width, height);

	DWORD wndFlags = 0;
	int x, y, w, h;
	if (fullscreen)
	{
		wndFlags |= WS_POPUP;
		x = y = 0;
		w = width;
		h = height;
	}
	else
	{
		wndFlags |= WS_OVERLAPPEDWINDOW;

		RECT wRect;
		wRect.left = 0;
		wRect.right = width;
		wRect.top = 0;
		wRect.bottom = height;
		AdjustWindowRect(&wRect, wndFlags, FALSE);

		MONITORINFO monInfo;
		monInfo.cbSize = sizeof(monInfo);
		GetMonitorInfo(oDesc.Monitor, &monInfo);

		w = min(wRect.right  - wRect.left, monInfo.rcWork.right  - monInfo.rcWork.left);
		h = min(wRect.bottom - wRect.top,  monInfo.rcWork.bottom - monInfo.rcWork.top);
		x = (monInfo.rcWork.left + monInfo.rcWork.right  - w) / 2;
		y = (monInfo.rcWork.top  + monInfo.rcWork.bottom - h) / 2;
	}


	hwnd = CreateWindow("Game", str, wndFlags, x, y, w, h, HWND_DESKTOP, NULL, hInstance, NULL);

	RECT rect;
	GetClientRect(hwnd, &rect);

	// Create device and swap chain
	DWORD deviceFlags = D3D11_CREATE_DEVICE_SINGLETHREADED;
#ifdef _DEBUG
    deviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

	D3D_FEATURE_LEVEL requested_feature_level = (api_revision == D3D11)? D3D_FEATURE_LEVEL_11_0 : (api_revision == D3D11_1)? D3D_FEATURE_LEVEL_10_1 : D3D_FEATURE_LEVEL_10_0;
	D3D_FEATURE_LEVEL feature_level;
	if (FAILED(D3D11CreateDevice(dxgiAdapter, D3D_DRIVER_TYPE_UNKNOWN, NULL, deviceFlags, &requested_feature_level, 1, D3D11_SDK_VERSION, &device, &feature_level, &context)))
	{
		ErrorMsg("Couldn't create D3D11 device");
		return false;
	}

	while (msaaSamples > 0)
	{
		UINT nQuality;
		if (SUCCEEDED(device->CheckMultisampleQualityLevels(backBufferFormat, msaaSamples, &nQuality)) && nQuality > 0)
		{
			if ((flags & NO_SETTING_CHANGE) == 0) antiAliasSamples = msaaSamples;
			break;
		}
		else
		{
			msaaSamples -= 2;
		}
	}
	DXGI_SWAP_CHAIN_DESC sd;
	memset(&sd, 0, sizeof(sd));
	sd.BufferDesc.Width  = rect.right;
	sd.BufferDesc.Height = rect.bottom;
	sd.BufferDesc.Format = backBufferFormat;
	sd.BufferDesc.RefreshRate = fullScreenRefresh;
	sd.BufferUsage = /*DXGI_USAGE_BACK_BUFFER | */DXGI_USAGE_RENDER_TARGET_OUTPUT | (sampleBackBuffer? DXGI_USAGE_SHADER_INPUT : 0);
	sd.BufferCount = 1;
	sd.OutputWindow = hwnd;
	sd.Windowed = (BOOL) (!fullscreen);
	sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
	sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
	sd.SampleDesc.Count = msaaSamples;
	sd.SampleDesc.Quality = 0;

	if (FAILED(dxgiFactory->CreateSwapChain(device, &sd, &swapChain)))
	{
		ErrorMsg("Couldn't create swapchain");
		return false;
	}

	// We'll handle Alt-Enter ourselves thank you very much ...
	dxgiFactory->MakeWindowAssociation(hwnd, DXGI_MWA_NO_WINDOW_CHANGES | DXGI_MWA_NO_ALT_ENTER);

	dxgiOutput->Release();
	dxgiAdapter->Release();
	dxgiFactory->Release();

	if (fullscreen)
	{
		captureMouse(!configDialog->isVisible());
	}

	renderer = new Direct3D11Renderer(device, context);

	if (!createBuffers(sampleBackBuffer))
	{
		delete renderer;
		return false;
	}
	antiAlias->selectItem(antiAliasSamples / 2);

	linearClamp = renderer->addSamplerState(LINEAR, CLAMP, CLAMP, CLAMP);
	defaultFont = renderer->addFont("../Textures/Fonts/Future.dds", "../Textures/Fonts/Future.font", linearClamp);
	blendSrcAlpha = renderer->addBlendState(SRC_ALPHA, ONE_MINUS_SRC_ALPHA);
	noDepthTest  = renderer->addDepthState(false, false);
	noDepthWrite = renderer->addDepthState(true,  false);
	cullNone  = renderer->addRasterizerState(CULL_NONE);
	cullBack  = renderer->addRasterizerState(CULL_BACK);
	cullFront = renderer->addRasterizerState(CULL_FRONT);

	return true;
}
Beispiel #4
0
SoundID Audio::addSound(const char *fileName, unsigned int flags){
	Sound sound;

	// Clear error flag
	alGetError();

	const char *ext = strrchr(fileName, '.') + 1;
	char str[256];
	if (stricmp(ext, "ogg") == 0){
		FILE *file = fopen(fileName, "rb");
		if (file == NULL){
			sprintf(str, "Couldn't open \"%s\"", fileName);
			ErrorMsg(str);
			return SOUND_NONE;
		}

		OggVorbis_File vf;
		memset(&vf, 0, sizeof(vf));
		if (ov_open(file, &vf, NULL, 0) < 0){
			fclose(file);
			sprintf(str, "\"%s\" is not an ogg file", fileName);
			ErrorMsg(str);
			return SOUND_NONE;
		}

		vorbis_info *vi = ov_info(&vf, -1);

		int nSamples = (uint) ov_pcm_total(&vf, -1);
		int nChannels = vi->channels;
		sound.format = nChannels == 1? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;
		sound.sampleRate = vi->rate;

		sound.size = nSamples * nChannels;

		sound.samples = new short[sound.size];
		sound.size *= sizeof(short);

		int samplePos = 0;
		while (samplePos < sound.size){
			char *dest = ((char *) sound.samples) + samplePos;

			int bitStream, readBytes = ov_read(&vf, dest, sound.size - samplePos, 0, 2, 1, &bitStream);
			if (readBytes <= 0) break;
			samplePos += readBytes;
		}

		ov_clear(&vf);

	} else {
		ALboolean al_bool;
		ALvoid *data;
		alutLoadWAVFile(fileName, &sound.format, &data, &sound.size, &sound.sampleRate, &al_bool);
		sound.samples = (short *) data;
	}

	alGenBuffers(1, &sound.buffer);
	alBufferData(sound.buffer, sound.format, sound.samples, sound.size, sound.sampleRate);
	if (alGetError() != AL_NO_ERROR){
		alDeleteBuffers(1, &sound.buffer);

		sprintf(str, "Couldn't open \"%s\"", fileName);
		ErrorMsg(str);
		return SOUND_NONE;
	}

	return insertSound(sound);
}
Beispiel #5
0
bool OpenGLApp::initAPI(){
	initialMode = CGDisplayCurrentMode(kCGDirectMainDisplay);

	dmodes = CGDisplayAvailableModes(kCGDirectMainDisplay);
	int count = CFArrayGetCount(dmodes);

	Array <DispRes> modes;
	int foundMode = -1;
	for (int i = 0; i < count; i++){
		CFDictionaryRef mode = (CFDictionaryRef) CFArrayGetValueAtIndex(dmodes, i);

		long bitsPerPixel = GetDictionaryLong(mode, kCGDisplayBitsPerPixel);
		Boolean safeForHardware = GetDictionaryBoolean(mode, kCGDisplayModeIsSafeForHardware);
		Boolean stretched = GetDictionaryBoolean(mode, kCGDisplayModeIsStretched);

		if (bitsPerPixel < colorBits || !safeForHardware || stretched) continue;

		long width  = GetDictionaryLong(mode, kCGDisplayWidth);
		long height = GetDictionaryLong(mode, kCGDisplayHeight);
		long refreshRate = GetDictionaryLong(mode, kCGDisplayRefreshRate);

//		printf("Mode: %dx%dx%d @ %d\n", width, height, bitsPerPixel, refreshRate);

		if (width >= 640 && height >= 480){
			modes.add(newRes(width, height, i));

			if (width == fullscreenWidth && height == fullscreenHeight){
				foundMode = i;
			}
		}
	}

	resolution->clear();
	modes.sort(dComp);
	char str[64];
	for (uint i = 0; i < modes.getCount(); i++){
		sprintf(str, "%dx%d", modes[i].w, modes[i].h);
		int index = resolution->addItemUnique(str);
		if (modes[i].index == foundMode) resolution->selectItem(index);
	}

	if (fullscreen){
		if (foundMode < 0 || CGDisplaySwitchToMode(kCGDirectMainDisplay, (CFDictionaryRef) CFArrayGetValueAtIndex(dmodes, foundMode)) != kCGErrorSuccess){
			sprintf(str, "Couldn't set fullscreen to %dx%d.", fullscreenWidth, fullscreenHeight);
			ErrorMsg(str);
			fullscreen = false;
		}
	}


	Rect rect;
	if (fullscreen){
		rect.left = 0;
		rect.top  = 0;
	} else {
		long w = GetDictionaryLong(initialMode, kCGDisplayWidth);
		long h = GetDictionaryLong(initialMode, kCGDisplayHeight);

		rect.left = (w - width) / 2;
		rect.top  = (h - height) / 2;
	}
	rect.right = rect.left + width;
	rect.bottom = rect.top + height;

	WindowAttributes attributes = fullscreen? (kWindowNoTitleBarAttribute | kWindowNoShadowAttribute) : (kWindowStandardDocumentAttributes | kWindowStandardHandlerAttribute);

	OSStatus error = CreateNewWindow(kDocumentWindowClass, attributes, &rect, &window);
	if (error != noErr || window == NULL){
		ErrorMsg("Couldn't create window");
		return false;
	}

    GDHandle screen = GetGWorldDevice(GetWindowPort(window));
    if (screen == NULL){
        ErrorMsg("Couldn't get device");
        ReleaseWindow(window);
        return false;
    }

	AGLPixelFormat pixelFormat;
	while (true){
		GLint attributes[] = {
			fullscreen? AGL_FULLSCREEN : AGL_WINDOW,
			AGL_RGBA,
			AGL_DOUBLEBUFFER,
			AGL_RED_SIZE,            8,
			AGL_GREEN_SIZE,          8,
			AGL_BLUE_SIZE,           8,
			AGL_ALPHA_SIZE,         (colorBits > 24)? 8 : 0,
			AGL_DEPTH_SIZE,          depthBits,
			AGL_STENCIL_SIZE,        stencilBits,
			AGL_SAMPLE_BUFFERS_ARB, (antiAliasSamples > 0),
			AGL_SAMPLES_ARB,         antiAliasSamples,
			AGL_NONE
		};

		pixelFormat = aglChoosePixelFormat(&screen, 1, attributes);
		if (pixelFormat != NULL) break;

		antiAliasSamples -= 2;
		if (antiAliasSamples < 0){
			ErrorMsg("No suitable pixel format");
			ReleaseWindow(window);
			return false;
		}
	}

	glContext = aglCreateContext(pixelFormat, NULL);
    aglDestroyPixelFormat(pixelFormat);

	if (glContext == NULL){
		ErrorMsg("Couldn't create context");
		ReleaseWindow(window);
		return false;
	}

	if (fullscreen){
		CGCaptureAllDisplays();
		aglSetFullScreen(glContext, 0, 0, 0, 0);
	} else {
		if (!aglSetDrawable(glContext, GetWindowPort(window))){
			ErrorMsg("Couldn't set drawable");
			aglDestroyContext(glContext);
			ReleaseWindow(window);
			return false;
		}
	}

	if (!aglSetCurrentContext(glContext)){
		ErrorMsg("Couldn't make context current");
		aglDestroyContext(glContext);
		ReleaseWindow(window);
		return false;
	}

	setWindowTitle(getTitle());
    ShowWindow(window);

	initExtensions();

	if (antiAliasSamples > 0){
		glEnable(GL_MULTISAMPLE_ARB);
	}

	if (fullscreen) captureMouse(!configDialog->isVisible());

	renderer = new OpenGLRenderer(glContext);
	renderer->setViewport(width, height);

	antiAlias->selectItem(antiAliasSamples / 2);

	linearClamp = renderer->addSamplerState(LINEAR, CLAMP, CLAMP, CLAMP);
	defaultFont = renderer->addFont("../Textures/Fonts/Future.dds", "../Textures/Fonts/Future.font", linearClamp);
	blendSrcAlpha = renderer->addBlendState(SRC_ALPHA, ONE_MINUS_SRC_ALPHA);
	noDepthTest  = renderer->addDepthState(false, false);
	noDepthWrite = renderer->addDepthState(true,  false);
	cullNone  = renderer->addRasterizerState(CULL_NONE);
	cullBack  = renderer->addRasterizerState(CULL_BACK);
	cullFront = renderer->addRasterizerState(CULL_FRONT);

	return true;
}
static drm_overlay_fb * drm_create_fb_internal(struct drm_tegra *drm,
                                               int drm_fd,
                                               uint32_t drm_format,
                                               uint32_t width, uint32_t height,
                                               uint32_t *bo_handles,
                                               uint32_t *pitches,
                                               uint32_t *offsets,
                                               Bool dont_map)
{
    struct drm_tegra_bo *bo    = NULL;
    struct drm_tegra_bo *bo_cb = NULL;
    struct drm_tegra_bo *bo_cr = NULL;
    drm_overlay_fb *fb         = NULL;
    uint32_t fb_id             = HANDLE_INVALID;
    Bool from_handle;
    int err;

    if (width == 0 || height == 0)
        return NULL;

    if (!pitches) {
        pitches = alloca(sizeof(uint32_t) * 4);

        pitches[0] = fb_pitch_aligned(drm_format, width);
        pitches[1] = fb_pitch_c_aligned(drm_format, width);
        pitches[2] = fb_pitch_c_aligned(drm_format, width);
        pitches[3] = 0;
    }

    if (!offsets) {
        offsets = alloca(sizeof(uint32_t) * 4);

        offsets[0] = 0;
        offsets[1] = 0;
        offsets[2] = 0;
        offsets[3] = 0;
    }

    from_handle = !!(bo_handles);

    if (from_handle) {
        err = drm_tegra_bo_wrap(&bo, drm, bo_handles[0], 0,
                                pitches[0] * height);
        if (err)
            goto error_cleanup;

        drm_tegra_bo_forbid_caching(bo);

        if (format_planar(drm_format)) {
            err = drm_tegra_bo_wrap(&bo_cb, drm, bo_handles[1], 0,
                                    pitches[1] * height / 2);
            if (err)
                goto error_cleanup;

            drm_tegra_bo_forbid_caching(bo_cb);

            err = drm_tegra_bo_wrap(&bo_cr, drm, bo_handles[2], 0,
                                    pitches[2] * height / 2);
            if (err)
                goto error_cleanup;

            drm_tegra_bo_forbid_caching(bo_cr);
        }

        goto create_framebuffer;
    }

    bo_handles = alloca(sizeof(uint32_t) * 4);

    bo_handles[1] = HANDLE_INVALID;
    bo_handles[2] = HANDLE_INVALID;
    bo_handles[3] = HANDLE_INVALID;

    /* Allocate PLANE[0] */
    err = drm_tegra_bo_new(&bo, drm, 0, offsets[0] +
                           fb_size_aligned(drm_format, width, height));
    if (err)
        goto error_cleanup;

    drm_tegra_bo_get_handle(bo, &bo_handles[0]);

    if (!format_planar(drm_format))
        goto create_framebuffer;

    /* Allocate PLANE[1] */
    err = drm_tegra_bo_new(&bo_cb, drm, 0, offsets[1] +
                           fb_size_c_aligned(drm_format, width, height));
    if (err)
        goto error_cleanup;

    drm_tegra_bo_get_handle(bo_cb, &bo_handles[1]);

    /* Allocate PLANE[2] */
    err = drm_tegra_bo_new(&bo_cr, drm, 0, offsets[2] +
                           fb_size_c_aligned(drm_format, width, height));
    if (err)
        goto error_cleanup;

    drm_tegra_bo_get_handle(bo_cr, &bo_handles[2]);

create_framebuffer:
    err = drmModeAddFB2(drm_fd, width, height, drm_format,
                        bo_handles, pitches, offsets, &fb_id, 0);
    if (err) {
        ErrorMsg("Failed to create DRM framebuffer: %s\n", strerror(-err));
        goto error_cleanup;
    }

    fb = calloc(1, sizeof(*fb));
    if (!fb)
        goto error_cleanup;

    fb->fb_id           = fb_id;
    fb->format          = drm_format;
    fb->width           = width;
    fb->height          = height;
    fb->width_c         = fb_width_c(drm_format, width);
    fb->height_c        = fb_height_c(drm_format, height);
    fb->bpp             = fb_bpp(drm_format);
    fb->bpp_c           = fb_bpp_c(drm_format);
    fb->bo_y_id         = bo_handles[0];
    fb->bo_cb_id        = bo_handles[1];
    fb->bo_cr_id        = bo_handles[2];
    fb->bo_y            = bo;
    fb->bo_cb           = bo_cb;
    fb->bo_cr           = bo_cr;
    fb->pitch_y         = pitches[0];
    fb->pitch_cb        = pitches[1];
    fb->pitch_cr        = pitches[2];
    fb->offset_y        = offsets[0];
    fb->offset_cb       = offsets[1];
    fb->offset_cr       = offsets[2];

    fb->width_pad       = (fb_pitch_aligned(drm_format, width) -
                            fb_pitch(drm_format, width)) *
                                fb_height_aligned(drm_format, height);

    fb->height_pad      = (fb_height_aligned(drm_format, height) - height) *
                            fb_pitch_aligned(drm_format, width);

    fb->height_offset   = (fb_height_aligned(drm_format, height) - height) *
                            fb->bpp / 8;

    fb->width_c_pad     = (fb_pitch_c_aligned(drm_format, width) -
                            fb_pitch_c(drm_format, width)) *
                                fb_height_c_aligned(drm_format, height);

    fb->height_c_pad    = (fb_height_c_aligned(drm_format, height) - fb->height_c) *
                            fb_pitch_c_aligned(drm_format, width);

    fb->height_c_offset = (fb_height_c_aligned(drm_format, height) - fb->height_c) *
                            fb->bpp_c / 8;

    if (dont_map)
        return fb;

    err = drm_tegra_bo_map(fb->bo_y, (void **)&fb->bo_y_mmap);
    if (err)
        goto error_cleanup;

    fb->bo_y_mmap += fb->offset_y;

    if (!format_planar(drm_format))
        return fb;

    err = drm_tegra_bo_map(fb->bo_cb, (void **)&fb->bo_cb_mmap);
    if (err)
        goto error_cleanup;

    err = drm_tegra_bo_map(fb->bo_cr, (void **)&fb->bo_cr_mmap);
    if (err)
        goto error_cleanup;

    fb->bo_cb_mmap += fb->offset_cb;
    fb->bo_cr_mmap += fb->offset_cr;

    return fb;

error_cleanup:
    if (from_handle)
        return NULL;

    if (fb_id != HANDLE_INVALID)
        drmModeRmFB(drm_fd, fb_id);

    drm_tegra_bo_unref(bo);
    drm_tegra_bo_unref(bo_cb);
    drm_tegra_bo_unref(bo_cr);

    free(fb);

    return NULL;
}
static int gettoken(struct context *c,double *val) {
   int ch, i;
   char *end, *pt;
   char buffer[40];

   if (c->backed_token != op_base) {
      ch=c->backed_token;
      if (ch==op_value)
	 *val=c->backed_val;
      c->backed_token=op_base;
      return (ch);
   }

   while ((ch=*(c->cur++))==' ');

   if (isdigit(ch) || ch=='.') {
      --(c->cur);
      *val=strtod(c->cur, &end);
      c->cur=end;
      return (op_value);
   } else if (isalpha(ch)) {
      pt=buffer;
      *pt++=ch;
      while (isalnum(c->cur[0])) {
	 if (pt<buffer+sizeof(buffer)-1)
	    *pt++=c->cur[0];
	 ++c->cur;
      }
      *pt='\0';
      for (i=0; builtins[i].name != NULL; ++i) {
	 if (strcmp(buffer, builtins[i].name)==0)
	    return (builtins[i].op);
      }
      ErrorMsg(2,"Bad token \"%.30s\"\nnear ...%40s\n",buffer,c->cur);
      c->had_error=true;
      while ((ch=*(c->cur++))==' ');
      if (ch=='(')
	 return (op_abs);
      *val=0;
      return (op_value);
   } else
      switch (ch) {
	case '\0':
	   --(c->cur);
	   return (0);
	case '!':
	   if (*c->cur=='=') {
	      ++c->cur;
	      return (op_ne);
	   }
	   return (op_not);
	case '-':
	   return (op_sub);
	case '+':
	   return (op_add);
	case '*':
	   return (op_times);
	case '/':
	   return (op_div);
	case '%':
	   return (op_mod);
	case '^':
	   return (op_pow);
	case '>':
	   if (*c->cur=='=') {
	      ++c->cur;
	      return (op_ge);
	   }
	   return (op_gt);
	case '<':
	   if (*c->cur=='=') {
	      ++c->cur;
	      return (op_le);
	   }
	   return (op_lt);
	case '=':
	   if (*c->cur=='=') {
	      ++c->cur;
	      return (op_eq);
	   }
	   ErrorMsg(2,"Bad token.  Expected \"%.10s\" got \"%.10s\"\nnear ...%40s\n",
			 "==", "=", c->cur);
	   c->had_error=true;
	   return (op_eq);
	case '|':
	   if (*c->cur=='|') {
	      ++c->cur;
	      return (op_or);
	   }
	   ErrorMsg(2,"Bad token.  Expected \"%.10s\" got \"%.10s\"\nnear ...%40s\n",
			 "||", "|", c->cur);
	   c->had_error=true;
	   return (op_or);
	case '&':
	   if (*c->cur=='&') {
	      ++c->cur;
	      return (op_and);
	   }
	   ErrorMsg(2,"Bad token.  Expected \"%.10s\" got \"%.10s\"\nnear ...%40s\n",
			 "&&", "&", c->cur);
	   c->had_error=true;
	   return (op_and);
	case '?':
	   return (op_if);
	case '(':
	case ')':
	case ':':
	case ',':
	   return (ch);
	default:
	   ErrorMsg(2,"Bad token. got \"%1$c\"\nnear ...%2$40s\n",ch,c->cur);
	   c->had_error=true;
	   *val=0;
	   return (op_value);
      }
}
int checkFileForMediaType (CRFSFile *file, CRFSList<MediaType> *mediaTypeList, MediaType **foundMediaType)
{
	MediaType *mt;
	CheckByteGroup *cbg;
	bool matches;
	HRESULT hr;
	LONG lBytesRead;
	LONGLONG actOffset;
	BYTE *necessaryBytes;

	mt = mediaTypeList->First ();

	while (mt != NULL)
	{							// loop over all filetypes
		cbg = mt->checkByteGroups.First ();

		while (cbg != NULL)
		{						// loop over all groups of checkbytes
			matches = true;

			for (unsigned int i = 0; i < cbg->checkByteCount; i ++)
			{					// we need to match all fields in one group
				if (cbg->checkBytes [i].offset < 0)
					actOffset = file->size + cbg->checkBytes [i].offset;
				else
					actOffset = cbg->checkBytes [i].offset;

				if (actOffset > file->size || actOffset < 0)
				{
					matches = false;
					break;
				}

				necessaryBytes = new BYTE [cbg->checkBytes [i].byteCount];

				if (!necessaryBytes)
				{
					ErrorMsg (0, L"Out of memory.");
					return 0;
				}

				// read the necessary amount of bytes to compare to value (after masking)
				hr = file->SyncRead (actOffset, cbg->checkBytes [i].byteCount, necessaryBytes, &lBytesRead);

				if (hr != S_OK)
				{
					matches = false;
					delete [] necessaryBytes;
					break;
				}

				// mask and compare all bytes in this entry
				for (unsigned int j = 0; j < cbg->checkBytes [i].byteCount; j ++)
				{
					if ((necessaryBytes [j] & cbg->checkBytes [i].mask [j]) != cbg->checkBytes [i].value [j])
					{
						matches = false;
						break;
					}
				}
				delete [] necessaryBytes;

				if (!matches)
					break;
			}

			if (matches)		// one group is enought to match the filetype
			{
				*foundMediaType = mt;
				return 1;
			}
			cbg = mt->checkByteGroups.Next (cbg);
		}
		mt = mediaTypeList->Next (mt);
	}

	*foundMediaType = NULL;
	return 1;
}
/* parseCheckBytes splits valueData and places the parsed values in the
   checkBytes array (allocated here) */
static int parseCheckBytes (wchar_t *valueData, CheckByteDetails **checkBytes)
{
	int tokenCount = 0, byteDetailsCount = 0, value;
	wchar_t *token, *nextTokenStart;

	for (int i = 0; i < lstrlen (valueData); i ++)
		if (valueData [i] == TEXT(','))
			tokenCount ++;

	if ((++ tokenCount) % 4)
		return 0;

	byteDetailsCount = tokenCount / 4;
	*checkBytes = new CheckByteDetails [byteDetailsCount];

	if (!*checkBytes)
	{
		ErrorMsg (0, L"Out of memory.");
		return -1;
	}

	nextTokenStart = valueData;

	for (int i = 0; i < byteDetailsCount; i ++)
	{
		token = nextTokenStart;
		getNextToken (&token, &nextTokenStart);
		swscanf_s (token, TEXT(" %lld"), &(*checkBytes) [i].offset);	// offset in file
		token = nextTokenStart;
		getNextToken (&token, &nextTokenStart);
		swscanf_s (token, TEXT(" %u"), &(*checkBytes) [i].byteCount);	// byte count of mask and value
		(*checkBytes) [i].mask = new BYTE [(*checkBytes) [i].byteCount];
		(*checkBytes) [i].value = new BYTE [(*checkBytes) [i].byteCount];

		if (!(*checkBytes) [i].mask || !(*checkBytes) [i].value)
		{
			ErrorMsg (0, L"Out of memory.");
			return -1;
		}

		//TODO: if the next token is smaller than byteCount and not empty we could pad with zeroes
		token = nextTokenStart;
		getNextToken (&token, &nextTokenStart);

		if (*token == TEXT('\0'))	// no mask means all ones
			for (unsigned int j = 0; j < (*checkBytes) [i].byteCount; j ++)
				(*checkBytes) [i].mask [j] = 0xFF;
		else					// otherwise parse mask
		{
			for (unsigned int j = 0; j < (*checkBytes) [i].byteCount && j * 2 < lstrlen (token); j ++)
			{
				swscanf_s (token + j * 2, TEXT(" %2x"), &value);
				(*checkBytes) [i].mask [j] = value;
			}
		}

		token = nextTokenStart;
		getNextToken (&token, &nextTokenStart);

		for (unsigned int j = 0; j < (*checkBytes) [i].byteCount && j * 2 < lstrlen (token); j ++)
		{
			swscanf_s (token + j * 2, TEXT(" %2x"), &value);	// parse value
			(*checkBytes) [i].value [j] = value;
		}
	}
	return byteDetailsCount;
}
Beispiel #10
0
static int nlm_nlm_common_generic_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{

  int err;
  unsigned long base;
#ifdef CONFIG_NLM_COMMON
  static int x=0;
  uint32_t tmp;

  if(!x){
    /*Setting MaxOutSplitTrans to zero*/
    pci_read_config_dword(pdev,0x40,&tmp); 
    tmp = tmp & ~(0x7U<<20);
    pci_write_config_dword(pdev,0x40,tmp);
    pci_read_config_dword(pdev,0x40,&tmp); 
    x=1;
    return -1;
  }
#endif
  nlm_pdev = pdev;
#ifndef CONFIG_NLM_COMMON
  if((err = pci_enable_device(pdev)))
  {
    ErrorMsg("Cannot enable PCI device, aborting.");
    return err;
  }
#endif
  if (!(pci_resource_flags(pdev, 0) & IORESOURCE_MEM))
  {
    ErrorMsg("Cannot find proper PCI device " 
	     	    "base address BAR0, aborting.\n");
    err = -ENODEV;
    pci_disable_device(pdev);
    return err;
  }
  err = pci_request_region(pdev, 0, NLM_DRIVER);
  if (err)
  {
    ErrorMsg("Cannot obtain PCI resources, aborting.");
    err = -ENODEV;
    pci_disable_device(pdev);
    return err;
  }
  pci_set_master(pdev);
#if !defined(CONFIG_NLM_COMMON) && defined(XLR_MSI_IS_SUPPORTED)
  if ((err = pci_find_capability(pdev, PCI_CAP_ID_MSI)))
  {
    Message("Device is MSI capable..Enabling MSI");
    err = pci_enable_msi(pdev);
    msi_irq = pdev->irq;
    if(err == 0) {
      Message("MSI Enabled");
	}
    else{
      ErrorMsg("MSI Enable failed");
      return err;
    }
  }
  else
  {
    ErrorMsg("Device is NOT MSI capable");
    err = -ENODEV;
    pci_disable_device(pdev);
    return err;
  }
#endif
  base = pci_resource_start(pdev, 0);
  nlm_nlm_common_shared_mem_base_host = (unsigned volatile int *)
			ioremap_nocache(base,pci_resource_len(pdev, 0));
  printk("Device Memory Available @ %#x \n",
			(uint32_t)(unsigned long)nlm_nlm_common_shared_mem_base_host);
  if(nlm_nlm_common_shared_mem_base_host == NULL)
  {
    err = -ENODEV;
#if !defined(CONFIG_NLM_COMMON) && defined(XLR_MSI_IS_SUPPORTED)
    pci_disable_msi(pdev);
#endif
#ifndef CONFIG_NLM_COMMON
    pci_disable_device(pdev);
#endif
    return err;
  }

#ifdef XLR_MAILBOX_IS_SUPPORTED
  /* Use BAR2 as the mailbox address */
  base = pci_resource_start(pdev, 2);
  nlm_nlm_common_mailbox_addr = (unsigned int *)ioremap(base,pci_resource_len(pdev, 2));

  if(nlm_nlm_common_mailbox_addr == NULL || base == 0)
  {
    ErrorMsg("MailBox Is Not Supported");
    err = -ENODEV;
    iounmap((void *)nlm_nlm_common_shared_mem_base_host);
		nlm_nlm_common_mailbox_addr	= nlm_nlm_common_shared_mem_base_host = 0;

#if !defined(CONFIG_NLM_COMMON) && defined(XLR_MSI_IS_SUPPORTED)
    pci_disable_msi(pdev);
#endif
#ifndef CONFIG_NLM_COMMON
    pci_disable_device(pdev);
#endif
    return err;
  }
#endif 

#if !defined(CONFIG_NLM_COMMON) && defined(XLR_MSI_IS_SUPPORTED)
  if((err = request_irq(msi_irq,nlm_nlm_common_generic_msi_handler, IRQF_DISABLED,												"nlm_nlm_common_generic_msi_handler", (void *)NULL)))
	{
		ErrorMsg("Cant Register interrupt handler irq %d",msi_irq);
		iounmap((void *)nlm_nlm_common_shared_mem_base_host);
#ifdef XLR_MAILBOX_IS_SUPPORTED
		iounmap((void *)nlm_nlm_common_mailbox_addr);
#endif
		pci_disable_msi(pdev);
		pci_disable_device(pdev);
		return err ;
	}
//pci_set_mwi(pdev); 
#endif

#ifdef CONFIG_SYSCTL
  nlm_pcix_sysctl_header = register_sysctl_table(nlm_pcix_sysctl_tbl);
  if(nlm_pcix_sysctl_header == NULL) {
	  printk(KERN_WARNING "Could not register to sysctl\n");
  }
  else{
	  printk("nlm_pcix: registered with sysctl\n");
  }
#endif

  return 0;
}
/* parses the HKEY_CLASSES_ROOT\Media Type registry key and
   fills the mediaTypeList with all valid byte marks and their
   corresponding major/subtypes */
int getMediaTypeList (CRFSList<MediaType> *mediaTypeList)
{
//these values come from http://msdn.microsoft.com/en-us/library/ms724872(VS.85).aspx
#define MAX_VALUE_SIZE	16384
#define MAX_KEYNAME_SIZE 256

	wchar_t keyName [MAX_KEYNAME_SIZE];
	wchar_t subKeyName [MAX_KEYNAME_SIZE];
	wchar_t valueName [MAX_VALUE_SIZE];
	LONG ret, retSub, retVal;

	HKEY mTypeKey, majorTypeKey, subTypeKey;
	DWORD valueType, valueSize = 0, valueNameSize;
	wchar_t *valueData;
	int mediaTypeCount = 0;
	MediaType *newType;
	CheckByteGroup *newGroup;

	ret = RegOpenKey (HKEY_CLASSES_ROOT, TEXT("Media Type"), &mTypeKey);
	if (ret != ERROR_SUCCESS)
		return -1;

	for (int i = 0; ret != ERROR_NO_MORE_ITEMS; i ++)
	{
		ret = RegEnumKey (mTypeKey, i, keyName, MAX_KEYNAME_SIZE);

		if (ret != ERROR_SUCCESS || !lstrcmp (keyName, TEXT("Extensions")))	// we don't want the Extensions subkey
			continue;

		retSub = RegOpenKey (mTypeKey, keyName, &majorTypeKey);

		if (retSub != ERROR_SUCCESS)
			continue;

		for (int j = 0; retSub != ERROR_NO_MORE_ITEMS; j ++)
		{
			retSub = RegEnumKey (majorTypeKey, j, subKeyName, MAX_KEYNAME_SIZE);
			if (retSub != ERROR_SUCCESS)
				continue;

			retVal = RegOpenKey (majorTypeKey, subKeyName, &subTypeKey);

			newType = new MediaType;
			if (!newType)
			{
				ErrorMsg (0, L"Out of memory.");
				return -1;
			}

			CLSIDFromString (keyName, &newType->majorType);
			CLSIDFromString (subKeyName, &newType->subType);

			for (int k = 0; retVal != ERROR_NO_MORE_ITEMS; k ++)
			{
				valueNameSize = MAX_VALUE_SIZE;
				retVal = RegEnumValue (subTypeKey, k, valueName, &valueNameSize, NULL, &valueType, NULL, &valueSize);

				if (retVal != ERROR_SUCCESS || valueType != REG_SZ || !lstrcmp (valueName, TEXT("Source Filter")))	// we don't need the source filter value
					continue;

				valueData = (wchar_t *) new BYTE [valueSize];

				valueNameSize = MAX_VALUE_SIZE;
				retVal = RegEnumValue (subTypeKey, k, valueName, &valueNameSize, NULL, &valueType,
					(LPBYTE) valueData, &valueSize);

				if (retVal != ERROR_SUCCESS)
				{
					delete [] valueData;
					continue;
				}

				newGroup = new CheckByteGroup;	// each value is one group

				if (!newGroup)
				{
					delete [] valueData;
					ErrorMsg (0, L"Out of memory.");
					return -1;
				}

				newGroup->checkByteCount = parseCheckBytes (valueData, &newGroup->checkBytes);

				if (newGroup->checkByteCount == -1)
				{
					delete [] valueData;
					delete newGroup;

					return -1;	// this means out of memory
				}

				if (!newGroup->checkByteCount)
				{
					// if we get here there was a parse error or an invalid value in the registry
					delete newGroup;
				}
				else
				{
					newType->checkByteGroups.InsertLast (newGroup);
					newType->checkByteGroupCount ++;
				}

				delete [] valueData;
			}

			if (!newType->checkByteGroupCount)
			{
				// if we get here we were unable to parse any of the values in the current subkey
				delete newType;
			}
			else
			{
				mediaTypeList->InsertLast (newType);
				mediaTypeCount ++;
			}
		}
	}
	return mediaTypeCount;
}
Beispiel #12
0
bool BaseApp::onKey(const uint key, const bool pressed) {
//#if defined(DEBUG) && defined(WIN32)
#ifdef WIN32
    if (pressed && key == KEY_F12) {
        if (OpenClipboard(hwnd)) {
            EmptyClipboard();

            char str[256];
            int len = sprintf(str, "camPos = vec3(%.15ff, %.15ff, %.15ff);\r\nwx = %.15ff;\r\nwy = %.15ff;\r\n", camPos.x, camPos.y, camPos.z, wx, wy);

            HGLOBAL handle = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, len + 1);
            char *mem = (char *) GlobalLock(handle);
            if (mem != NULL) {
                strcpy(mem, str);
                GlobalUnlock(handle);
                SetClipboardData(CF_TEXT, handle);
            }
            CloseClipboard();
        }
    }
#endif

    if (pressed && key == screenshotKey) {
        if (!saveScreenshot()) {
            ErrorMsg("Couldn't save screenshot");
        }
        return true;
    }

    if (pressed && key == benchmarkKey) {
        if (benchMarkFile) {
            fclose(benchMarkFile);
            benchMarkFile = NULL;
        } else {
            benchMarkFile = fopen("Benchmark.xls", "w");
            fprintf(benchMarkFile, "Frames/s\n");
        }
        return true;
    }


    bool processed = false;

    if (!mouseCaptured) {
        if (widgets.goToFirst()) {
            do {
                Widget *widget = widgets.getCurrent();
                if (widget->isVisible() || widget->isCapturing()) {
                    widgets.moveCurrentToTop();
                    processed = widget->onKey(key, pressed);
                    break;
                }
            } while (widgets.goToNext());
        }
    }

    if (!processed) {
        if (pressed) {
            processed = true;
            if (key == KEY_ESCAPE) {
                if (!mouseCaptured || (fullscreen && mouseCaptured)) {
                    closeWindow(true, true);
                } else {
                    captureMouse(false);
                }
            } else if (key == fpsKey) {
                showFPS = !showFPS;
            } else if (key == resetKey) {
                resetCamera();
            } else if (key == optionsKey) {
                if (configDialog->isVisible()) {
                    configDialog->setVisible(false);
                    if (keysDialog) keysDialog->setVisible(false);
                    if (joystickDialog) joystickDialog->setVisible(false);
                } else {
                    captureMouse(false);
                    configDialog->setVisible(true);
                    if (keysDialog) keysDialog->setVisible(true);
                    if (joystickDialog) joystickDialog->setVisible(true);
                }
            } else {
                processed = false;
            }
        }
    }

    if (key < elementsOf(keys)) keys[key] = pressed;

    return processed;
}
void NodeThread::run()
{
	int ret;
	exit = 0;

	/*ret = PICA_new_c2n(node_addr.address.toUtf8().constData(),
	                          node_addr.port,
	                          user_account.CA_file.toUtf8().constData(),
	                          user_account.cert_file.toUtf8().constData(),
	                          user_account.pkey_file.toUtf8().constData(),
	                          DHParam::GetDHParamFilename().toUtf8().constData(),
	                          AskPassword::ask_password_cb,
	                          &ci);*/
	ret = PICA_new_c2n(user_account, node_addr.address.toUtf8().constData(), node_addr.port, &ci);

	switch(ret)
	{
	case PICA_OK:

		emit NodeStatusChanged(node_addr.address, node_addr.port, true);

		finished_mutex.lock();
		if (*finished_flag)
		{
			PICA_close_c2n(ci);
			exit = 1;
		}
		else
		{
			*finished_flag = true;
			*connection =  ci;
			emit ConnectedToNode(node_addr.address, node_addr.port, this);
		}
		finished_mutex.unlock();



		break;

	case PICA_ERRSOCK:
	case PICA_ERRDNSRESOLVE:

		emit NodeStatusChanged(node_addr.address, node_addr.port, false);

		exit = 1;
		break;

	case PICA_ERRSSL:
		exit = 1;
		break;

	case PICA_ERRPROTONEW:

		emit ErrorMsg(QString("Node %1:%2 has newer protocol version. Please check if update for pica-client is available")
		              .arg(node_addr.address)
		              .arg(node_addr.port)
		             );
		exit = 1;
		break;

	case PICA_ERRPROTOOLD:

		emit ErrorMsg(QString("Node %1:%2 has older protocol. Disconnected.")
		              .arg(node_addr.address)
		              .arg(node_addr.port)
		             );

		exit = 1;
		break;

	default:
		exit = 1;
	}

	if (exit)
		return;

	do
	{
		write_mutex->lock();
		if (PICA_read(ci, 10000) != PICA_OK || PICA_write(ci) != PICA_OK)
			exit = 1;
		write_mutex->unlock();
		msleep(300);
	}
	while (!exit);

	write_mutex->lock();
	PICA_close_c2n(ci);
	*connection = NULL;
	write_mutex->unlock();
}
Beispiel #14
0
BOOL InitBoard(UINT drvno)
	{		// inits PCI Board and gets all needed addresses
			// and gets Errorcode if any
	ULONG Errorcode = Error_notinitiated;
	BOOL fResult = FALSE;
	DWORD   ReturnedLength;
	ULONG	ctrlcode = 1; // Init Board


	fResult = DeviceIoControl(ahCCDDRV[drvno],IOCTL_SetFct,  // read error code
							&ctrlcode,        // Buffer to driver.
                            sizeof(ctrlcode),
							&Errorcode,sizeof(Errorcode),&ReturnedLength,NULL);
	if (! fResult)
		{ErrorMsg("InitBoard failed");};
	
	// these error messages are for inspection of the driver only
	// they can be omitted because here should be no error
	if (Errorcode==NoError)
			{return TRUE; }  // everything went fine

		else   switch (Errorcode)
			{
			case Error_notinitiated: ErrorMsg("CCD Board not initialized");
			break;
			case Error_noregkey: ErrorMsg(" No registry entry found ");
			break;
			case Error_nosubregkey: ErrorMsg(" No registry sub entry found ");
			break;
			case Error_nobufspace: ErrorMsg(" Can't init buffer space ");
			break;
			case Error_nobios: ErrorMsg(" No PCI bios found ");
			break;
			case Error_noboard: ErrorMsg(" Can't find CCD Board ");
			break;
			case Error_noIORegBase: ErrorMsg(" Can't find PCI space ");
			break;
			case Error_Physnotmapped: ErrorMsg(" Can't map PCI space ");
			break;
			case Error_Fktnotimplemented: ErrorMsg(" function not implemented");
			break;
			case Error_Timer: ErrorMsg(" PCI Timer Error ");
			break;

			}
	return FALSE;
	};  // InitBoard
Beispiel #15
0
STDMETHODIMP CRFSOutputPin::WaitForNext (DWORD dwTimeout, IMediaSample **ppSample, DWORD_PTR *pdwUser)
{
    HRESULT ret = S_OK;
    DWORD r;
    ReadRequest *rr;

    if (!(ppSample && pdwUser))
        return E_POINTER;

    if (m_flush)
        return DoFlush (ppSample, pdwUser);

    m_lock.Lock ();
    rr = m_requests.UnlinkLast ();
    m_lock.Unlock ();

    Anchor<ReadRequest> arr (&rr);

    while (!rr)
    {
        r = WaitForSingleObject (m_event, dwTimeout);

        if (m_flush)
            return DoFlush (ppSample, pdwUser);

        if (r == WAIT_TIMEOUT)
            return VFW_E_TIMEOUT;

        if (r == WAIT_FAILED)
        {
            ErrorMsg (GetLastError (), L"CRFSOutputPin::WaitForNext - WaitForSingleObject");
            return E_FAIL;
        }

        m_lock.Lock ();
        rr = m_requests.UnlinkLast ();
        m_lock.Unlock ();

        if (!rr)
            DbgLog((LOG_TRACE, 2, L"Got nothing?!?!"));
    }

    DWORD count, read, acc = 0;
    SubRequest *sr = rr->subreqs.First ();

    count = rr->count;

    HANDLE *hArray = new HANDLE [count];

    for (DWORD i = 0; i < count; i ++)
    {
        hArray [i] = sr->o.hEvent;
        sr = rr->subreqs.Next (sr);
    }

    // FIXME: Any time spent waiting in WaitForSingleObject above should be subtracted from dwTimeout
    r = WaitForMultipleObjects (count, hArray, TRUE, dwTimeout);

    delete [] hArray;

    if (r == WAIT_TIMEOUT)
    {
        // Put it back into the list.
        m_lock.Lock ();
        arr.Release ();
        m_requests.InsertLast (rr);
        m_lock.Unlock ();
        return VFW_E_TIMEOUT;
    }

    *pdwUser = rr->dwUser;
    *ppSample = rr->pSample;

    if (r == WAIT_FAILED)
    {
        ErrorMsg (GetLastError (), L"CRFSOutputPin::WaitForNext - WaitForMultipleObjects");
        return E_FAIL;
    }

    while (sr = rr->subreqs.UnlinkFirst ())
    {
        read = 0;

        if (!GetOverlappedResult (sr->file, &sr->o, &read, TRUE))
        {
            ErrorMsg (GetLastError (), L"CRFSOutputPin::WaitForNext - GetOverlappedResult");
            acc += read;
            delete sr;
            ret = S_FALSE; // FIXME: Should probably return EOF if that's what happened.
            break;
        }

        acc += read;

        // TODO: Try to recover if read != sr->expected.
        if (read != sr->expected)
        {
            DbgLog((LOG_TRACE, 2, L"CRFSOutputPin::WaitForNext Got %lu expected %lu!", read, sr->expected));
            delete sr;
            ret = S_FALSE;
            break;
        }
        delete sr;
    }

    rr->pSample->SetActualDataLength (acc);

    return ret;
}
int main (int argc, const char * argv[]) {

    FILE   *fp;                                  /* Pointer to the file */
    int    quantum = 0;                /* Quantum value for Round Robin */
    int    parameters[NUMVAL];        /* Process parameters in the line */
    int    i;                    /* Number of parameters in the process */
    
    /* Check if the parameters in the main function are not empty */
    if (argc < NUMPARAMS){
        printf("Need a file with the process information\n\n");
        printf("Abnormal termination\n");
        return (EXIT_FAILURE);
    }
    else {
        
        /* Open the file and check that it exists */
        fp = fopen (argv[1],"r");       /* Open file for read operation */
        if (!fp)                            /* The file does not exists */
            ErrorMsg("'main'","Filename does not exist or is corrupted\n");
        
        else {
            
            /* The first number in the file is the quantum */
            quantum = GetInt(fp);
        
            if (quantum == EXIT_FAILURE)
                ErrorMsg("'main'","The quantum was not found");
            
            else {
                /* Read the process information until the end of file 
                is reached */
                while (!feof(fp)){
                    
                    /* For every four parameters create a new process */
                    for (i = 0; ((i < NUMVAL) && (!feof(fp))); i++) {
                        parameters[i] = GetInt(fp);
                    }
                    
                    /* Do we have only four parameters? */
                    if (i == NUMVAL) {
                        
                        /* Create a new process with its information */
                        CreateProcessList(parameters[0], parameters[1], parameters[2], parameters[3]);
                    }
                }
                
                /* Start by sorting the processes by arrival time */
                SortProcessList(ARRIVALTIME);
                
                /* Apply all the scheduling algorithms and print the results */
                 FirstComeFS();
                 NonPreemptive(CPUBURST);
                 NonPreemptive(PRIORITY);
                 Preemptive(CPUBURST);
                 Preemptive(PRIORITY);
                 RoundRobin(quantum);
                
            }
        }
        
    }
}
Beispiel #17
0
STATIC bool readSampleFile( void )
/********************************/
{
    file_handle             fh;
    uint_16                 size;
    void                    *buff;
    int                     buff_len;
    off_t                   start_position;
    bool                    main_exe;
    samp_block_prefix       prefix;
    samp_block_prefix       *next_prefix;

/* we can add error checking for things like */
/**/
/*    - number of samples match the info # of samples */
/*    - main exe load if there is an overlay table */
/**/
    fh = CurrSIOData->fh;
    start_position = lseek( fh, CurrSIOData->header.sample_start, SEEK_SET );
    if( start_position == (off_t) -1 ) {
        ErrorMsg( LIT( Smp_File_IO_Err ), CurrSIOData->samp_file_name );
        return( false );
    }
    if( read( fh, &prefix, SIZE_PREFIX ) != SIZE_PREFIX ) {
        ErrorMsg( LIT( Smp_File_IO_Err ), CurrSIOData->samp_file_name );
        return( false );
    }
    buff = ProfAlloc( SIZE_DATA );
    buff_len = SIZE_DATA;
    main_exe = false;
    while( prefix.kind != SAMP_LAST ) {
        size = prefix.length;
        if( buff_len < size ) {
            buff = ProfRealloc( buff, size );
            buff_len = size;
        }
        /* reads data & next prefix */
        if( BigRead( fh, buff, size ) != size ) {
            ErrorMsg( LIT( Smp_File_IO_Err ), CurrSIOData->samp_file_name );
            ProfFree( buff );
            return( false );
        }
        next_prefix = (void *)( ((char *) buff) + ( size - SIZE_PREFIX ));

        /* if we're reading a sample record from a callgraph sample */
        /* file, the next record should contain callgraph information */
        /* which we will also want stored in memory for processing */
        /* 16-jul-92 CMS */

//        if( CallGraph && prefix.kind == SAMP_SAMPLES &&
//                         next_prefix->kind == SAMP_CALLGRAPH ) {
//            size = next_prefix->length;
//            /* reads callgraph data & next prefix   */
//            if( BigRead( fh, next_prefix, size ) != size ) {
//                errorIO();
//                ProfFree( buff );
//                ErrorMsg( LIT( Smp_File_IO_Err ), CurrSIOData->samp_file_name );
//                return( false );
//            }
//            next_prefix = (void *)( ((char *) next_prefix) + ( size - SIZE_PREFIX ));
//        }

        switch( prefix.kind ) {
        case SAMP_INFO:
            procInfoBlock( prefix.tick, buff );
            break;
        case SAMP_SAMPLES:
            if( !procSampleBlock( prefix.tick, prefix.length, buff ) ) {
                return( false );
            }
            break;
        case SAMP_MARK:
            procMarkBlock( prefix.tick, buff );
            break;
        case SAMP_OVL_LOAD:
            procOverlayBlock( prefix.tick, buff );
            break;
        case SAMP_ADDR_MAP:
            procAddrBlock( prefix.length, buff );
            break;
        case SAMP_MAIN_LOAD:
            main_exe = true;
            /* fall through */
        case SAMP_CODE_LOAD:
            procImageBlock( buff, main_exe );
            main_exe = false;
            break;
        case SAMP_REMAP_SECTION:
            procRemapBlock( prefix.tick, prefix.length, buff );
            break;
        case SAMP_CALLGRAPH:
//            printf( "sample callgraph\n" );
            break;
        }
        prefix = *next_prefix;
    }
    ProfFree( buff );
    return( true );
}
Beispiel #18
0
int PreProc_FtpDownloadFiles( char *downloadURL, char *tempLocation, int deleteFiles )
{

	if ( IsURL( downloadURL ) && !IsStopped() )
	{
		char	*p;
		long	count=0, filenum;
		char	server[128], path[256], name[64], passwd[32];
#if DEF_WINDOWS
		WIN32_FIND_DATA  lpFindFileData;
		HINTERNET hFind, fs;

		char msg[256];

		ExtractUserFromURL(  downloadURL, server, name, passwd, path );
		DateFixFilename( path, 0 );

		OutDebugs( "Doing PreProcess Download %s...", path );

		fs = (void*)FtpServerOpen( server, name, passwd );

		if ( !fs )
		{
			FtpServerOpenError( server );
			return -1;
		}

		if ( fs )
		{
			long flags = INTERNET_FLAG_NO_CACHE_WRITE;
			char newpath[512];

			// *****************************************************************
			// To be more friendly with various FTP servers, we need to break
			// up the filename from the directory that it is contained in.
			// We can then change to the directory prior to fetching the file.
			// The issue here is that some FTP servers can not get a file that
			// has path information in it (ie: /directory1/dir2/file.dat)
			// *****************************************************************
			int iLen;
			for (iLen=mystrlen(path);iLen && path[iLen]!='/';--iLen)
				;
			if (!iLen)	// then there is no '/'
			{
				mystrcpy( newpath, path+1 );
			}
			else
			{
				path[iLen] = NULL;	// Set the '/' to a NULL so we have a path up to the name.
				if (!::FtpSetCurrentDirectory(fs,"/"))	// Set it to root just to be sure.
				{
					// we have a problem, however there is no real way to action this.
					// so lets just hope that the fetch will still work.
				}

				if (!::FtpSetCurrentDirectory(fs,path))
				{
					// again.
					// we have a problem, however there is no real way to action this.
					// so lets just hope that the fetch will still work.
					path[iLen] = '/';
				}

				mystrcpy( newpath, path+iLen+1 );
			}


			hFind = FtpFindFirstFile( fs, newpath, &lpFindFileData, flags , 0 );
			if ( !hFind ){
				unsigned long len = 512;
				FtpServerClose( fs );

				OutDebugs( "%s Not Found....Trying root level path instead...", newpath );
				fs = (void*)FtpServerOpen( server, name, passwd );
				if ( fs )
				{
					FtpGetCurrentDirectory( fs, newpath, &len );
					strcat( newpath, path );
					hFind = FtpFindFirstFile( fs, newpath, &lpFindFileData, flags , 0 );
				} else
					FtpServerOpenError( server );
			}

			if ( hFind )
				OutDebugs( "Ftp File Found %s size = %d", lpFindFileData.cFileName, lpFindFileData.nFileSizeLow );
			else {
				ErrorMsg( "Cannot open ftp file ...\n%s\nBecause %s", newpath, NetworkErr(NULL) );
				FtpServerClose( fs );
				return -1;
			}

			filenum = 0;

			while( hFind && !IsStopped() )
			{
				long ret;
				char ftpfilename[256], localfilename[256];

				if( hFind )
				{
					ftpfilename[0] = 0;
					if ( !strchr( lpFindFileData.cFileName , '/' ) ){
						// only if NEWPATH has a / in it copy it.
						
						if ( strchr( newpath , '/' ) ){
							mystrcpy( ftpfilename, newpath );
							p = strrchr( ftpfilename, '/');
							if ( p ) *p = 0;
						}
						strcat( ftpfilename, "/" );
						strcat( ftpfilename, lpFindFileData.cFileName );
					} else
						mystrcpy( ftpfilename, lpFindFileData.cFileName );

					// Figure out local file name
					if ( *tempLocation == 0 || GetFileAttributes( tempLocation ) != FILE_ATTRIBUTE_DIRECTORY )
					{
						sprintf( msg, "%%TEMP%%\\%s", FileFromPath( ftpfilename,NULL ) );
						ExpandEnvironmentStrings( msg, localfilename, 255 );
						StatusSetID(  IDS_STOREFILEINTEMP  );
						OutDebugs( "Using system temp location %s", localfilename );
					} else {
						PathFromFullPath( tempLocation, localfilename );
						if( strlen( localfilename ) )
						{
							strcat ( localfilename, "\\" );
							p = FileFromPath( ftpfilename,NULL );
							if ( !p ) p = "temp.log";
							strcat ( localfilename, p );
						} else
							mystrcpy( localfilename, "temp.log" );
						OutDebugs( "Using user temp location %s", localfilename );
					}

					OutDebugs( "Trying to download %d byte file '%s' into '%s' ...", lpFindFileData.nFileSizeLow, ftpfilename, localfilename );

					ret = FtpFileDownload( fs, downloadURL, localfilename, ftpfilename, lpFindFileData.nFileSizeLow );
					if ( ret > 0 )
					{
						if ( deleteFiles ){			// delete remote ftp file after downloading
							StatusSetID( IDS_DELETEFTP, ftpfilename );
							FtpDelFile( fs, ftpfilename );
						}
						AddFileToLogQ( localfilename, filenum++ );
					} else {
						OutDebugs( "error downloading (%d)", ret );
						ErrorMsg( "Cannot download file %s\n%s", NetworkErr(NULL) );
						hFind = NULL;
						FtpServerClose( fs );
						return -2;
					}
					//------------------------
				} //if( hFind )

				if ( hFind ) {
					if( InternetFindNextFile( hFind, &lpFindFileData ) == FALSE )
						hFind = NULL;
				}
			} //while
			FtpServerClose( fs );
		} 
#endif
	}
	return IsStopped();
}
Beispiel #19
0
CDTrigger *CMine::AddTrigger (UINT16 wallnum, INT16 type, BOOL bAutoAddWall) 
{
	INT16 flags;
	INT16 segnum, sidenum, trignum;
	static INT16 defWallTypes [NUM_TRIGGER_TYPES] = {
		WALL_OPEN, WALL_OPEN, WALL_OPEN, WALL_OPEN, WALL_ILLUSION, 
		WALL_OPEN, WALL_OPEN, WALL_OPEN, WALL_OPEN, WALL_OPEN, 
		WALL_OPEN, WALL_OPEN, WALL_OPEN, WALL_OPEN, WALL_ILLUSION,
		WALL_OPEN, WALL_OPEN
		};
	static INT16 defWallTextures [NUM_TRIGGER_TYPES] = {
		0, 0, 0, 0, 426, 
		0, 0, 0, 0, 0, 
		0, 0, 0, 0, 426,
		0, 0
		};

// check if there's already a trigger on the current side
wallnum = FindTriggerWall (&trignum);
if (trignum != NO_TRIGGER) {
	ErrorMsg ("There is already a trigger on this side");
	return NULL;
	}
if (GameInfo ().triggers.count >= MAX_TRIGGERS) {
	ErrorMsg ("The maximum number of triggers has been reached.");
	return NULL;
	}
// if no wall at current side, try to add a wall of proper type
bool bUndo = theApp.SetModified (TRUE);
theApp.LockUndo ();
if (CurrSide ()->nWall >= GameInfo ().walls.count) {
	if (bAutoAddWall) {
		if (GameInfo ().walls.count >= MAX_WALLS) {
			ErrorMsg ("Cannot add a wall to this side,\nsince the maximum number of walls is already reached.");
			return NULL;
			}
		segnum = sidenum = -1;
		GetCurrent (segnum, sidenum);
		if (!AddWall (-1, -1, (Segments (segnum)->children [sidenum] < 0) ? WALL_OVERLAY : defWallTypes [type], 0, 0, -1, defWallTextures [type])) {
			ErrorMsg ("Cannot add a wall for this trigger.");
			theApp.ResetModified (bUndo);
			return NULL;
			}
		}
	else {
		ErrorMsg ("You must add a wall to this side before you can add a trigger.");
		return NULL;
		}
	}
// if D1, then convert type to flag value
if (file_type == RDL_FILE) {
	switch(type) {
		case TT_OPEN_DOOR:
			flags = TRIGGER_CONTROL_DOORS;
			break;
		case TT_MATCEN:
			flags = TRIGGER_MATCEN;
			break;
		case TT_EXIT:
			flags = TRIGGER_EXIT;
			break;
		case TT_SECRET_EXIT:
			flags = TRIGGER_SECRET_EXIT;
			break;
		case TT_ILLUSION_OFF:
			flags = TRIGGER_ILLUSION_OFF;
			break;
		case TT_ILLUSION_ON:
			flags = TRIGGER_ILLUSION_ON;
			break;
		case TT_ENERGY_DRAIN:
			flags = TRIGGER_ENERGY_DRAIN;
			break;
		case TT_SHIELD_DAMAGE:
			flags = TRIGGER_SHIELD_DAMAGE;
			break;
		default:
			flags = 0;
		}
	type = 0;
	}
else
	flags = 0;

trignum = (UINT16) GameInfo ().triggers.count;
// set new trigger data
InitTrigger (Triggers (trignum), type, flags);
// link trigger to the wall
Walls (wallnum)->trigger = (UINT8) trignum;
// update number of Triggers ()
GameInfo ().triggers.count++;
AutoLinkExitToReactor();
theApp.UnlockUndo ();
theApp.MineView ()->Refresh ();
return Triggers (trignum);
}
Beispiel #20
0
// main and only entry point.....
int DoPostProc( long stopped )
{
	char msg[2024];

	if ( !stopped )
	{
		// COMPRESS
		if ( MyPrefStruct.postproc_rarchive )
		{
			StatusSet( "Archiving zip...");			//StatusSetID( IDS_MAKEZIP );
			PostProc_ZipReport( MyPrefStruct.outfile,
								msg,  // final filename
								MyPrefStruct.postproc_deletereport );					//make a zip file
			ErrorMsg( "Your usage report has been compressed.\nYou can access it at\n%s\n\n", msg );
		}

		if ( MyPrefStruct.postproc_larchive && glogFilenamesNum )
		{
			StatusSetID( IDS_COMPRESSING );
			PostProc_GzipLogFiles( glogFilenames, glogFilenamesNum, MyPrefStruct.postproc_deletelog );		// compress log if need to
			sprintf( msg, "Your log file been compressed.\n\n" );
			OutDebug( msg );
		}



		long uploadreporterr = 0;
		long uploadlogserr = 0;

		// UPLOAD
		if ( MyPrefStruct.postproc_uploadreport )
		{
			StatusSetID( IDS_UPLOADREPORT );

			if ( MyPrefStruct.postproc_uploadreport == 2 )
				ResetUploadReportQueue( MyPrefStruct.outfile );
			// copy htmls or zip report to dest...
			uploadreporterr = PostProc_UploadReport( (const char *)MyPrefStruct.postproc_uploadreportlocation,
													 MyPrefStruct.postproc_deletereport,
													 MyPrefStruct.postproc_rarchive,
													 MyPrefStruct.outfile
													);						
			sprintf( msg, "Your usage report has been uploaded to %s.\n\n" , MyPrefStruct.postproc_uploadreportlocation );
			OutDebug( msg );
		}

		if ( MyPrefStruct.postproc_uploadlog )
		{
			StatusSetID( IDS_UPLOADLOGS );
			uploadlogserr = PostProc_UploadLogs( MyPrefStruct.postproc_uploadloglocation,
												 MyPrefStruct.postproc_deletelog,
												 MyPrefStruct.postproc_larchive,
												 glogFilenames, 
												 glogFilenamesNum
												);						// copy htmls or zip report to dest...
			sprintf( msg, "Logs uploaded to %s.\n\n" , MyPrefStruct.postproc_uploadreportlocation );
			OutDebug( msg );
		}

		// EMAIL
		if ( MyPrefStruct.postproc_emailon ){
			DoEmailSend();
		}
	}
	else
		OutDebug( "Post processing skipped... stopped." );

	StopFopenHistory();

	return IsStopped();
}
Beispiel #21
0
HRESULT CRARFileSource::ScanArchive (wchar_t *archive_name, CRFSList<CRFSFile> *file_list, int *files_found, int *ok_files_found)
{
	DWORD dwBytesRead;
	char *filename = NULL;
	wchar_t *current_rar_filename = NULL, *rar_ext;
	bool first_archive_file = true, rewind;
	bool multi_volume = false, new_numbering = false;
	rar_header_t rh;
	BYTE marker [7];
	BYTE expected [7] = { 0x52, 0x61, 0x72, 0x21, 0x1A, 0x07, 0x00 };
	CRFSFilePart *new_part, *prev_part;
	LONGLONG collected;
	DWORD ret;
	DWORD volumes = 0;
	int volume_digits;
	CRFSFile *file = NULL;

	*ok_files_found = 0;
	int compressed_files_found = 0;
	int encrypted_files_found = 0;
	LARGE_INTEGER zero = {0};

	MediaType *mType;
	CRFSList<MediaType> mediaTypeList (true);

	Anchor<CRFSFile> af (&file);
	ArrayAnchor<wchar_t> acrf (&current_rar_filename);

	HANDLE hFile = INVALID_HANDLE_VALUE;
	Anchor<HANDLE> ha (&hFile);

	int cch = lstrlen (archive_name) + 1;

	current_rar_filename = new wchar_t [cch];
	if (!current_rar_filename)
	{
		ErrorMsg (0, L"Out of memory.");
		return E_OUTOFMEMORY;
	}

	CopyMemory (current_rar_filename, archive_name, cch * sizeof (wchar_t));

	rar_ext = wcsrchr (current_rar_filename, '.');

	if (getMediaTypeList (&mediaTypeList) == -1)
		return E_OUTOFMEMORY;

	// Scan through archive volume(s)
	while (true)
	{
		ha.Close ();
		DbgLog((LOG_TRACE, 2, L"Loading file \"%s\".", current_rar_filename));
		hFile = CreateFile (current_rar_filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
		if (hFile == INVALID_HANDLE_VALUE)
		{
			if (first_archive_file || rewind)
			{
				ErrorMsg (GetLastError (), L"Could not open file \"%s\".", current_rar_filename);
				return E_FAIL;
			}
			else
				break;
		}
		rewind = false;

		// Read marker.
		if (!ReadFile (hFile, marker, 7, &dwBytesRead, NULL) || dwBytesRead != 7)
		{
			ErrorMsg (GetLastError (), L"Could not read RAR header.");
			return E_FAIL;
		}

		if (memcmp (marker, expected, 7))
		{
			ErrorMsg (0, L"Incorrect RAR marker.");
			return E_UNEXPECTED;
		}

		// Read archive header.
		if (ret = ReadHeader (hFile, &rh))
			return ret;

		LOG_HEADER(&rh);

		if (rh.ch.type != HEADER_TYPE_ARCHIVE)
		{
			ErrorMsg (0, L"Unexpected RAR header type.");
			return E_UNEXPECTED;
		}

		if (rh.ch.flags & MHD_PASSWORD)
		{
			ErrorMsg (0, L"Encrypted RAR volumes are not supported.");
			return RFS_E_ENCRYPTED;
		}

		if (first_archive_file)
		{
			new_numbering = !!(rh.ch.flags & MHD_NEWNUMBERING);
			multi_volume = !!(rh.ch.flags & MHD_VOLUME);

			if (multi_volume)
			{
				if (!rar_ext)
				{
					ErrorMsg (0, L"Input file does not end with .rar");
					return E_UNEXPECTED;
				}

				// Locate volume counter
				if (new_numbering)
				{
					volume_digits = 0;
					do
					{
						rar_ext --;
						volume_digits ++;
					} while (iswdigit (*(rar_ext - 1)));
				}
				else
				{
					rar_ext += 2;
					volume_digits = 2;
				}

				if (!(rh.ch.flags & MHD_FIRSTVOLUME))
				{
					DbgLog((LOG_TRACE, 2, L"Rewinding to the first file in the set."));
					UpdateArchiveName (rar_ext, volume_digits, volumes, new_numbering);

					first_archive_file = false;
					rewind = true;
					continue;
				}
			}
		}
		else
		{
			ASSERT (new_numbering == !!(rh.ch.flags & MHD_NEWNUMBERING));
			ASSERT (rh.ch.flags & MHD_VOLUME);
		}

		// Find file headers
		while (true)
		{
			// Read file header.
			if (ret = ReadHeader (hFile, &rh))
			{
				if (ret == ERROR_HANDLE_EOF)
					break;
				else
					return ret;
			}

			LOG_HEADER(&rh);

			if (rh.ch.type == HEADER_TYPE_END)
			{
				// TODO: Verify that the volume number in the header matches our volume counter.

				// Check for EARC_NEXT_VOLUME removed as this flag is missing on some archives.

				break;
			}
			if (rh.ch.type != HEADER_TYPE_FILE)
			{
				SetFilePointerEx (hFile, rh.bytesRemaining, NULL, FILE_CURRENT);
				DbgLog((LOG_TRACE, 2, L"Skipping unknown header of type %02x.", rh.ch.type));
				continue;
			}

			DbgLog((LOG_TRACE, 2, L"SIZE %08lx %08lx  OS %02x  CRC %08lx  TIMESTAMP %08lx  VERSION %d  METHOD %02x  LEN %04lx  ATTRIB %08lx",
				rh.fh.size.HighPart, rh.fh.size.LowPart, rh.fh.os, rh.fh.crc, rh.fh.timestamp, rh.fh.version, rh.fh.method, rh.fh.name_len, rh.fh.attributes));

			DbgLog((LOG_TRACE, 2, L"FILENAME \"%S\"", rh.fh.filename));

			if ((rh.ch.flags & LHD_WINDOWMASK) == LHD_DIRECTORY)
			{
				DbgLog((LOG_TRACE, 2, L"Skipping directory."));
				HEADER_SKIP_FILE
			}

			if (filename)
			{
				if (strcmp (filename, rh.fh.filename))
				{
					// TODO: We should probably dump the old file start fresh with this one
					// since the lazy error handling at other places may cause us to end up here.
					DbgLog((LOG_TRACE, 2, L"Incorrect file found."));
					HEADER_SKIP_FILE
				}

				if (!(rh.ch.flags & LHD_SPLIT_BEFORE))
				{
					// TODO: Decide if it's better to ignore the missing flag.
					DbgLog((LOG_TRACE, 2, L"LHD_SPLIT_BEFORE flag was not set as expected."));
					HEADER_SKIP_FILE
				}

				delete [] rh.fh.filename;
			}
Beispiel #22
0
int PostProc_UploadReport( const char *uploadURL, int deletereport, int zipreport, char *reportLocation )
{
	if ( gFopenHistoryPtr && !IsStopped() )
	{
		char	sourcepath[256];
		char	server[256], ftppath[256], name[64], passwd[32];
		char	*source;
		void	*fs;

		if ( IsURL( uploadURL ) )
		{
			char msg[256];
			ExtractUserFromURL( (char*)uploadURL, server, name, passwd, ftppath );
			DateFixFilename( ftppath, 0 );
			fs = (void*)FtpServerOpen( server, name, passwd );
			if ( fs ){
				sprintf( msg, "FTP %s@%s/%s", name,server,ftppath );
				StatusSet( msg );
			} else 
			{
				FtpServerOpenError( server );
				return 1;
			}
		}

		PathFromFullPath( reportLocation, sourcepath );
		DateFixFilename( sourcepath, 0 );

		// ---------------- UPLOAD ALL INDIVIDUAL FILES
		if ( !zipreport )
		{
			long files;
			files = UploadFiles( fs, (char*)uploadURL, sourcepath, ftppath, deletereport );
			if ( files>0 )
				OutDebugs( "%d files uploaded.", files );
			else
				OutDebugs( "Upload canceled" );

			FtpClose( fs );
			OutDebugs( "Ftp Site Closed" );
		} else
		// ----------------- UPLOAD SINGLE ZIP REPORT
		{
			long	uploadStatus = 0;
			char	srczipname[256];
			char	newfilename[256];

			mystrcpy( srczipname, reportLocation );
			DateFixFilename( srczipname, 0 );
			PathFromFullPath( srczipname, sourcepath );

			if ( !strstr( srczipname, ".zip" ) )
			{
				source = strrchr( srczipname, '.' );
				if ( source )
					mystrcpy( source, ".zip" );
				else
					return 3;
			}
			source = srczipname;

			// Find the FILENAME Component
			if ( strstr( srczipname, sourcepath ) )
			{
				source += strlen( sourcepath );
			}

			// generate remote full path PATH+NAME
			CopyFilenameUsingPath( newfilename, (char*)uploadURL, source );

			// Ok things are ok, lets now upload the zip file
			if ( IsURL( uploadURL ) )
			{
				char fullURLPath[256];
				sprintf( fullURLPath, "%s%s", ftppath, source );

				// upload the zip file
				uploadStatus = FtpFileUpload( fs, srczipname, fullURLPath, source );
				if ( uploadStatus == FTPERR_CANTMAKEDIR )
					ErrorMsg( "Could not make directory %s on ftp server .\nMaybe path does not exist?", ftppath );

				FtpClose( fs );
			}

			if( deletereport && uploadStatus == FTPERR_COMPLETE )
			{
				OutDebugs( "Deleting local zip file %s", srczipname );
				remove( srczipname );
			}
		}
	}
	return 0;
}
Beispiel #23
0
bool OpenGLApp::initAPI(){
	screen = DefaultScreen(display);

	int nModes;
    XF86VidModeGetAllModeLines(display, screen, &nModes, &dmodes);

	Array <DispRes> modes;

	char str[64];
	int foundMode = -1;
	for (int i = 0; i < nModes; i++){
		if (dmodes[i]->hdisplay >= 640 && dmodes[i]->vdisplay >= 480){
			modes.add(newRes(dmodes[i]->hdisplay, dmodes[i]->vdisplay, i));

			if (dmodes[i]->hdisplay == fullscreenWidth && dmodes[i]->vdisplay == fullscreenHeight){
				foundMode = i;
			}
		}
	}

	resolution->clear();
	modes.sort(dComp);
	for (uint i = 0; i < modes.getCount(); i++){
		sprintf(str, "%dx%d", modes[i].w, modes[i].h);
		int index = resolution->addItemUnique(str);
		if (modes[i].index == foundMode) resolution->selectItem(index);
	}


	if (fullscreen){
		if (foundMode >= 0 && XF86VidModeSwitchToMode(display, screen, dmodes[foundMode])){
			XF86VidModeSetViewPort(display, screen, 0, 0);
		} else {
			char str[128];
			sprintf(str, "Couldn't set fullscreen at %dx%d.", fullscreenWidth, fullscreenHeight);
			ErrorMsg(str);
			fullscreen = false;
		}
	}

	XVisualInfo *vi;
	while (true){
		int attribs[] = {
			GLX_RGBA,
			GLX_DOUBLEBUFFER,
			GLX_RED_SIZE,      8,
			GLX_GREEN_SIZE,    8,
			GLX_BLUE_SIZE,     8,
			GLX_ALPHA_SIZE,    (colorBits > 24)? 8 : 0,
			GLX_DEPTH_SIZE,    depthBits,
			GLX_STENCIL_SIZE,  stencilBits,
			GLX_SAMPLE_BUFFERS_ARB, (antiAliasSamples > 0),
			GLX_SAMPLES_ARB,         antiAliasSamples,
			None,
		};

		vi = glXChooseVisual(display, screen, attribs);
		if (vi != NULL) break;

		antiAliasSamples -= 2;
		if (antiAliasSamples < 0){
			char str[256];
			sprintf(str, "No Visual matching colorBits=%d, depthBits=%d and stencilBits=%d", colorBits, depthBits, stencilBits);
			ErrorMsg(str);
			return false;
		}
	}


	//printf("Selected visual = 0x%x\n",(unsigned int) (vi->visualid));
	glContext = glXCreateContext(display, vi, None, True);


	XSetWindowAttributes attr;
	attr.colormap = XCreateColormap(display, RootWindow(display, screen), vi->visual, AllocNone);

	attr.border_pixel = 0;
	attr.override_redirect = fullscreen;
    attr.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask |
		PointerMotionMask | StructureNotifyMask;

	window = XCreateWindow(display, RootWindow(display, vi->screen),
			0, 0, width, height, 0, vi->depth, InputOutput, vi->visual,
			CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect, &attr);

	if (!fullscreen){
	    Atom wmDelete;
        wmDelete = XInternAtom(display, "WM_DELETE_WINDOW", True);
        XSetWMProtocols(display, window, &wmDelete, 1);
		char *title = "OpenGL";
        XSetStandardProperties(display, window, title, title, None, NULL, 0, NULL);
	}
    XMapRaised(display, window);

	// Create a blank cursor for cursor hiding
	XColor dummy;
	char data = 0;
	Pixmap blank = XCreateBitmapFromData(display, window, &data, 1, 1);
	blankCursor = XCreatePixmapCursor(display, blank, blank, &dummy, &dummy, 0, 0);
	XFreePixmap(display, blank);


	XGrabKeyboard(display, window, True, GrabModeAsync, GrabModeAsync, CurrentTime);


	glXMakeCurrent(display, window, glContext);

	initExtensions(display);

	if (antiAliasSamples > 0){
		glEnable(GL_MULTISAMPLE_ARB);
	}

	if (fullscreen) captureMouse(!configDialog->isVisible());

	renderer = new OpenGLRenderer(window, glContext, display, screen);
	renderer->setViewport(width, height);

	antiAlias->selectItem(antiAliasSamples / 2);

	linearClamp = renderer->addSamplerState(LINEAR, CLAMP, CLAMP, CLAMP);
	defaultFont = renderer->addFont("../Textures/Fonts/Future.dds", "../Textures/Fonts/Future.font", linearClamp);
	blendSrcAlpha = renderer->addBlendState(SRC_ALPHA, ONE_MINUS_SRC_ALPHA);
	noDepthTest  = renderer->addDepthState(false, false);
	noDepthWrite = renderer->addDepthState(true,  false);
	cullNone  = renderer->addRasterizerState(CULL_NONE);
	cullBack  = renderer->addRasterizerState(CULL_BACK);
	cullFront = renderer->addRasterizerState(CULL_FRONT);

	return true;
}
Beispiel #24
0
long FtpFileDownload( void *fs, char *url, char *dest, char *fullpath, long length )
{
	long	dataread, datatotal=0;

	if ( fs )
	{
		void	*fp;
		FILE	*ff;
		char	*buffer=NULL;

		if ( fs && !IsStopped() )
		{
			if ( !(ff = fopen( dest, "wb+" )) )
			{
				StatusSetf( "Cannot open local file %s for writing.", dest );
				return -2;
			}
	
			fp = (void*)FtpOpen( fs, fullpath, 'R' );
			if ( fp ) 
			{
				if ( !length )
					length = FtpFileGetSize( url );

				StatusSetID( IDS_DOWNLOADING, fullpath );

				buffer = (char*)malloc( 1024*4 );

				if ( length && buffer )
				{
					long writesize;

					dataread = 1;
					while( dataread>0 && buffer && !IsStopped() )
					{
						//sprintf( msg, "Downloading %s...%d KB (%.2f%%)", fullpath, (datatotal)/1024, (100*((datatotal)/(float)length)) );
						StatusSetID( IDS_DOWNLOADINGKB, fullpath, (datatotal)/1024, (100*((datatotal)/(float)length))  );
	
						dataread = NetRead( fp, buffer, 1024*1 );
						datatotal+= dataread;
						if ( dataread ){
							writesize = fwrite( buffer, 1, dataread, ff );
							if ( writesize == 0 ){
								dataread = 0;
								datatotal = -2;
							}
						}
					}
					free( buffer );
				}
				FtpClose( fp );
			} else 
			{
				const char *msg = NetworkErr( NULL );
				if ( !msg ) msg = "Maybe path does not exist?";
				ErrorMsg( "Cannot open ftp file %s\nbecause ...\n%s", fullpath, msg ); 
				datatotal = -1;
			}
			fclose( ff );
		}

		if ( IsStopped() )
		{
			StatusSetID( IDS_DOWNLOADSTOP );
			remove( dest );
			datatotal = -1;
		}

	}
	return datatotal;
}
Beispiel #25
0
bool OpenGLApp::initAPI(){
	if (screen >= GetSystemMetrics(SM_CMONITORS)) screen = 0;

	int monitorCounter = screen;
	EnumDisplayMonitors(NULL, NULL, MonitorEnumProc, (LPARAM) &monitorCounter);

  // TODO: Use this when saving out position?
  // HMONITOR hMonitor = MonitorFromWindow(m_handle->hWnd, MONITOR_DEFAULTTOPRIMARY);

	DWORD flags = WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
	int x, y;


	x = monInfo.rcMonitor.left;
	y = monInfo.rcMonitor.top;

	device.cb = sizeof(device);
	//TODO: Monitor count is not equal to device count?
	EnumDisplayDevices(NULL, 0/*screen*/, &device, 0);

	DEVMODE dm, tdm;
	memset(&dm, 0, sizeof(dm));
	dm.dmSize = sizeof(dm);
	dm.dmBitsPerPel = colorBits;
	dm.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY;
	dm.dmPelsWidth  = fullscreenWidth;
	dm.dmPelsHeight = fullscreenHeight;
	dm.dmDisplayFrequency = 60;

	// Find a suitable fullscreen format
	int i = 0;
	int targetHz = 85;
	char str[128];

	resolution->clear();
	while (EnumDisplaySettings((const char *) device.DeviceName, i, &tdm)){
		if (int(tdm.dmBitsPerPel) == colorBits && tdm.dmPelsWidth >= 640 && tdm.dmPelsHeight >= 480){
			sprintf(str, "%dx%d", tdm.dmPelsWidth, tdm.dmPelsHeight);
			int index = resolution->addItemUnique(str);

			if (int(tdm.dmPelsWidth) == fullscreenWidth && int(tdm.dmPelsHeight) == fullscreenHeight){
				if (abs(int(tdm.dmDisplayFrequency) - targetHz) < abs(int(dm.dmDisplayFrequency) - targetHz)){
					dm = tdm;
				}
				resolution->selectItem(index);
			}
		}
		i++;
	}


	if (fullscreen){
    //TODO: Select correct monitor?
    //dm.dmFields |= DM_POSITION ;
    //dm.dmPosition.x = x;
    //dm.dmPosition.y = y;

		if (ChangeDisplaySettingsEx((const char *) device.DeviceName, &dm, NULL, CDS_FULLSCREEN, NULL) == DISP_CHANGE_SUCCESSFUL){
			flags |= WS_POPUP;
			captureMouse(!configDialog->isVisible());
		} else {
			ErrorMsg("Couldn't set fullscreen mode");
			fullscreen = false;
		}
	}

	sprintf(str, "%s (%dx%d)", getTitle(), width, height);
	if (!fullscreen){
		flags |= WS_OVERLAPPEDWINDOW;

		RECT wRect;
		wRect.left = 0;
		wRect.right = width;
		wRect.top = 0;
		wRect.bottom = height;
		AdjustWindowRect(&wRect, flags, FALSE);

		width  = min(wRect.right  - wRect.left, monInfo.rcWork.right  - monInfo.rcWork.left);
		height = min(wRect.bottom - wRect.top,  monInfo.rcWork.bottom - monInfo.rcWork.top);

		x = (monInfo.rcWork.left + monInfo.rcWork.right  - width ) / 2;
		y = (monInfo.rcWork.top  + monInfo.rcWork.bottom - height) / 2;
	}


	hwnd = CreateWindow("Humus", str, flags, x, y, width, height, HWND_DESKTOP, NULL, hInstance, NULL);
  
	PIXELFORMATDESCRIPTOR pfd = {
        sizeof (PIXELFORMATDESCRIPTOR), 1,
		PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
		PFD_TYPE_RGBA, colorBits,
		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
		depthBits, stencilBits,
		0, PFD_MAIN_PLANE, 0, 0, 0, 0
    };

	hdc = GetDC(hwnd);

	int iAttribs[] = {
		WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
		WGL_ACCELERATION_ARB,   WGL_FULL_ACCELERATION_ARB,
		WGL_DOUBLE_BUFFER_ARB,  GL_TRUE,
		WGL_RED_BITS_ARB,       8,
		WGL_GREEN_BITS_ARB,     8,
		WGL_BLUE_BITS_ARB,      8,
		WGL_ALPHA_BITS_ARB,     (colorBits > 24)? 8 : 0,
		WGL_DEPTH_BITS_ARB,     depthBits,
		WGL_STENCIL_BITS_ARB,   stencilBits,
		0
	};

	int pixelFormats[256];
	int bestFormat = 0;
	int bestSamples = 0;
	uint nPFormats;
	if (wgl_ext_ARB_pixel_format && wglChoosePixelFormatARB(hdc, iAttribs, NULL, elementsOf(pixelFormats), pixelFormats, &nPFormats) && nPFormats > 0){
		int minDiff = 0x7FFFFFFF;
		int attrib = WGL_SAMPLES_ARB;
		int samples;

		// Find a multisample format as close as possible to the requested
		for (uint i = 0; i < nPFormats; i++){
			wglGetPixelFormatAttribivARB(hdc, pixelFormats[i], 0, 1, &attrib, &samples);
			int diff = abs(antiAliasSamples - samples);
			if (diff < minDiff){
				minDiff = diff;
				bestFormat = i;
				bestSamples = samples;
			}
		}
	} else {
		pixelFormats[0] = ChoosePixelFormat(hdc, &pfd);
	}
	antiAliasSamples = bestSamples;

	SetPixelFormat(hdc, pixelFormats[bestFormat], &pfd);

  if(wgl_ext_ARB_create_context)
  {
    glContext = wglCreateContextAttribsARB(hdc, 0, 0);
  }
  else
  {
    glContext = wglCreateContext(hdc);
  }
	wglMakeCurrent(hdc, glContext);

  ogl_LoadFunctions();
	wgl_LoadFunctions(hdc);

	if (wgl_ext_ARB_multisample && antiAliasSamples > 0){
		glEnable(GL_MULTISAMPLE);
	}

	if (fullscreen) captureMouse(!configDialog->isVisible());

	renderer = new OpenGLRenderer(hdc, glContext);
	renderer->setViewport(width, height);

	antiAlias->selectItem(antiAliasSamples / 2);

	linearClamp = renderer->addSamplerState(LINEAR, CLAMP, CLAMP, CLAMP);
	defaultFont = renderer->addFont("../Textures/Fonts/Future.dds", "../Textures/Fonts/Future.font", linearClamp);
	blendSrcAlpha = renderer->addBlendState(SRC_ALPHA, ONE_MINUS_SRC_ALPHA);
	noDepthTest  = renderer->addDepthState(false, false);
	noDepthWrite = renderer->addDepthState(true,  false);
	cullNone  = renderer->addRasterizerState(CULL_NONE);
	cullBack  = renderer->addRasterizerState(CULL_BACK);
	cullFront = renderer->addRasterizerState(CULL_FRONT);

	return true;
}
Beispiel #26
0
STATIC bint procCmd( char * cmd )
/*******************************/
{
    char    *rover;
    int     name_len;
    int     old_len;
    int     cmd_type;
    int     index;
    bint    do_report;
    bint    do_option;

    do_report = P_FALSE;
    for( ;; ) {
        cmd = eatBlanks( cmd );
        if( *cmd == NULLCHAR ) break;
#ifdef __UNIX__
        if( *cmd == '-' ) {
#else
        if( *cmd == '-' || *cmd == '/' ) {
#endif
            do_option = P_TRUE;
            ++cmd;
            cmd_type = minLook( &cmd );
        } else if( *cmd == '?' ) {
            do_option = P_TRUE;
            cmd_type = HELP_OPT;
        } else {
            do_option = P_FALSE;
            rover = cmd;
            cmd = eatAllChars( cmd );
            name_len = cmd - rover;
            if( name_len > _MAX_PATH ) {
                name_len = _MAX_PATH;
            }
            memcpy( SamplePath, rover, name_len );
            SamplePath[name_len] = NULLCHAR;
        }
        if( do_option ) {
            switch( cmd_type ) {
            case FAIL_OPT:
                ErrorMsg( LIT( Cmd_Option_Not_Valid ), cmd-1 );
#if defined( __WINDOWS__ ) || defined( __NT__ ) || defined( __OS2_PM__ )
                fatal( LIT( Usage ) );
#else
                /* fall through */
#endif
            case HELP_OPT:
                index = 0;
                while( cmdUsage[index] ) {
                    ErrorMsg( cmdUsage[index++] );
                }
                exit( 0 );
            case DIP_OPT:
                cmd = eatBlanks( cmd );
                if( *cmd == '=' ) {
                    cmd = eatBlanks( cmd+1 );
                }
                rover = cmd;
                cmd = eatAlphaNum( cmd );
                if( *cmd == NULLCHAR || cmd-rover == 0 ) {
                    if( WProfDips != NULL ) {
                        ProfFree( WProfDips );
                        WProfDips = NULL;
                        WProfDipSize = 0;
                    }
                } else {
                    name_len = cmd - rover;
                    old_len = WProfDipSize;
                    WProfDipSize = old_len + name_len + 1;
                    if( old_len == 0 ) {
                        WProfDipSize++;
                    } else {
                        old_len--;
                    }
                    WProfDips = ProfRealloc( WProfDips, WProfDipSize );
                    memcpy( WProfDips+old_len, rover, name_len );
                    old_len += name_len;
                    WProfDips[old_len++] = NULLCHAR;
                    WProfDips[old_len] = NULLCHAR;
                }
                break;
#if defined( __DOS__ )
            case NOGRAPHICSMOUSE_OPT:
            case NOCHARREMAP_OPT:
                WndStyle &= ~(GUI_CHARMAP_DLG|GUI_CHARMAP_MOUSE);
                break;
#endif
#ifndef NDEBUG
            case R_OPT:
                do_report = P_TRUE;
                break;
#endif
            }
        }
    }
    return( do_report );
}



STATIC char * eatBlanks( char * cmd ) {
/*************************************/
    while( isspace( *cmd ) && *cmd != NULLCHAR ) {
        ++cmd;
    }
    return( cmd );
}



STATIC char * eatAlphaNum( char * cmd ) {
/***************************************/
    while( isalnum( *cmd ) && *cmd != NULLCHAR ) {
        ++cmd;
    }
    return( cmd );
}



STATIC char * eatAllChars( char * cmd ) {
/***************************************/
    while( !isspace( *cmd ) && *cmd != NULLCHAR ) {
        ++cmd;
    }
    return( cmd );
}



STATIC int minLook( char * * value ) {
/************************************/

    int         index;
    int         curr_len;
    char * *    strtab;
    byte *      lentab;
    char *      strlook;
    char *      strchck;
    char *      base_val;
    char        check_char;

    base_val = *value;
    lentab = cmdLen;
    strtab = cmdNames;
    index = 0;
    for(;;) {
        strlook = *strtab++;
        if( strlook == NULL ) {
            return( FAIL_OPT );
        }
        strchck = base_val;
        curr_len = 0;
        for(;;) {
            check_char = tolower( *strchck );
            if( check_char == NULLCHAR
             || !(isalpha( check_char ) || check_char == '?') ) {
                if( curr_len >= *lentab ) {
                    *value += curr_len;
                    return( cmdType[index] );
                }
                break;
            }
            if( *strlook != check_char ) break;
            strlook++;
            strchck++;
            curr_len++;
        }
        lentab++;
        index++;
    }
}
Beispiel #27
0
bool App::load()
{
  if (!GLSL_supported){
    ErrorMsg("No GLSL support");
    return false;
  }

  // Set the shader version used
  ((OpenGLRenderer*)renderer)->SetShaderVersionStr("#version 130");

  // Shaders
  if ((generateRadial = renderer->addShader("generateRadial.shd")) == SHADER_NONE) return false;

  if ((objectShaders[0][0] = renderer->addShader("object.shd")) == SHADER_NONE) return false;
  if ((objectShaders[0][1] = renderer->addShader("object.shd", "#define CONSTANT_MIP\n")) == SHADER_NONE) return false;
  if ((objectShaders[1][0] = renderer->addShader("object.shd", "#define RADIAL_MAP\n")) == SHADER_NONE) return false;
  if ((objectShaders[1][1] = renderer->addShader("object.shd", "#define RADIAL_MAP\n#define CONSTANT_MIP\n")) == SHADER_NONE) return false;

  if ((skyboxShaders[0][0] = renderer->addShader("skybox.shd")) == SHADER_NONE) return false;
  if ((skyboxShaders[0][1] = renderer->addShader("skybox.shd", "#define CONSTANT_MIP\n")) == SHADER_NONE) return false;
  if ((skyboxShaders[1][0] = renderer->addShader("skybox.shd", "#define RADIAL_MAP\n" )) == SHADER_NONE) return false;
  if ((skyboxShaders[1][1] = renderer->addShader("skybox.shd", "#define RADIAL_MAP\n#define CONSTANT_MIP\n" )) == SHADER_NONE) return false;

  // Filtering modes
  if ((trilinearClamp = renderer->addSamplerState(TRILINEAR, CLAMP, CLAMP, CLAMP)) == SS_NONE) return false;
  if ((trilinearAniso = renderer->addSamplerState(TRILINEAR_ANISO, WRAP, WRAP, WRAP)) == SS_NONE) return false;
  
  // Radial textures only wrap in one direction
  if ((radialFilter   = renderer->addSamplerState(TRILINEAR, WRAP, CLAMP, CLAMP)) == SS_NONE) return false;

  // Textures
  const char *files[] = {
    "../Textures/CubeMaps/UnionSquare/posx.jpg", "../Textures/CubeMaps/UnionSquare/negx.jpg",
    "../Textures/CubeMaps/UnionSquare/posy.jpg", "../Textures/CubeMaps/UnionSquare/negy.jpg",
    "../Textures/CubeMaps/UnionSquare/posz.jpg", "../Textures/CubeMaps/UnionSquare/negz.jpg",
  };
  if ((cubeEnv = renderer->addCubemap(files, true, trilinearClamp)) == TEXTURE_NONE) return false;

  if ((radialGenRT = renderer->addRenderTarget(RADIAL_TEX_WIDTH, RADIAL_TEX_HEIGHT, FORMAT_RGBA8, radialFilter)) == TEXTURE_NONE) return false;

  // Draw a quad over the screen
  {
    // Bind the radial env map gen render target
    renderer->changeRenderTarget(radialGenRT);

    renderer->reset();
    renderer->setShader(generateRadial);
    renderer->setTexture("Env", cubeEnv);
    renderer->setDepthState(noDepthWrite);
    renderer->apply();

    glBegin(GL_TRIANGLES);
      glVertex3f(0,  2, 1);
      glVertex3f(3, -1, 1);
      glVertex3f(-3, -1, 1);
    glEnd();

    // Read back the pixels into a image
    Image img;
	  ubyte *pixels = img.create(FORMAT_RGB8, RADIAL_TEX_WIDTH, RADIAL_TEX_HEIGHT, 1, 1);
    glReadPixels(0, 0, img.getWidth(), img.getHeight(), GL_RGB, GL_UNSIGNED_BYTE, pixels);
    img.createMipMaps();

    // Save the image to disk
    if (!img.saveDDS("GenRadialTex.dds")){
      return false;
    }

    // Re-bind the main render target
    renderer->changeToMainFramebuffer();
  }

  if ((radialEnv = renderer->addTexture("GenRadialTex.dds", true, radialFilter)) == TEXTURE_NONE) return false;

  // Upload map to vertex/index buffer
  if (!model->makeDrawable(renderer, true)) return false;

  return true;
}
Beispiel #28
0
STDMETHODIMP CRFSOutputPin::Request (IMediaSample* pSample, DWORD_PTR dwUser)
{
    LONGLONG llPosition;
    DWORD lLength;
    BYTE* pBuffer;

    if (m_flush)
    {
        DbgLog((LOG_TRACE, 2, L"Request called during flush."));
        return VFW_E_WRONG_STATE;
    }

    if (!m_file)
    {
        DbgLog((LOG_TRACE, 2, L"Request called with no file loaded."));
        return E_UNEXPECTED;
    }

    HRESULT hr = ConvertSample (pSample, &llPosition, &lLength, &pBuffer);

    if (FAILED (hr))
        return hr;

    if (!(IsAligned ((INT_PTR) llPosition) && IsAligned ((INT_PTR) lLength) && IsAligned ((INT_PTR) pBuffer)))
    {
        DbgLog((LOG_TRACE, 2, L"SyncReadAligned bad alignment. align = %lu, pos = %lld, len = %lu, buf = %p",
                m_align, llPosition, lLength, pBuffer));
        return VFW_E_BADALIGN;
    }

    LARGE_INTEGER offset;
    DWORD to_read, acc = 0;
    LONGLONG offset2;
    int pos = m_file->FindStartPart (llPosition);

    if (pos == -1)
        return S_FALSE;

    ReadRequest *request = new ReadRequest ();

    if (!request)
        return E_OUTOFMEMORY;

    Anchor<ReadRequest> arr (&request);

    request->dwUser = dwUser;
    request->pSample = pSample;
    request->count = 0;

    CRFSFilePart *part = m_file->array + pos;

    offset2 = llPosition - part->in_file_offset;
    offset.QuadPart = part->in_rar_offset + offset2;

    while (true)
    {
        SubRequest *sr = new SubRequest ();

        if (!sr)
        {
            ErrorMsg (0, L"Out of memory.");
            return E_OUTOFMEMORY;
        }

        request->subreqs.InsertLast (sr);
        request->count ++;

        to_read = min (lLength, (DWORD) (part->size - offset2));

        sr->file = part->file;
        sr->expected = to_read;
        sr->o.hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);

        if (!sr->o.hEvent)
        {
            sr->o.hEvent = INVALID_HANDLE_VALUE;
            return S_FALSE;
        }

        sr->o.Offset = offset.LowPart;
        sr->o.OffsetHigh = offset.HighPart;

        if (!ReadFile (part->file, pBuffer + acc, to_read, NULL, &sr->o))
        {
            DWORD err = GetLastError ();

            // FIXME: Do something smart in response to EOF.
            if (err != ERROR_IO_PENDING && err != ERROR_HANDLE_EOF)
            {
                ErrorMsg (err, L"CRFSOutputPin::Request - ReadFile");
                return S_FALSE;
            }
        }
        lLength -= to_read;
        acc += to_read;

        if (lLength <= 0)
            break;

        pos ++;

        if (pos >= m_file->parts)
            return S_FALSE;

        part ++;
        offset2 = 0;
        offset.QuadPart = part->in_rar_offset;
    }

    m_lock.Lock ();

    arr.Release ();
    m_requests.InsertFirst (request);

    if (!SetEvent (m_event))
        ErrorMsg (GetLastError (), L"CRFSOutputPin::Request - SetEvent");

    m_lock.Unlock ();

    return S_OK;
}
Beispiel #29
0
bool D3D11App::createBuffers(const bool sampleBackBuffer)
{
	if (FAILED(swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID *) &backBuffer))) 
		return false;

	if (FAILED(device->CreateRenderTargetView(backBuffer, NULL, &backBufferRTV)))
		return false;

	if (sampleBackBuffer)
	{
		if ((backBufferTexture = ((Direct3D11Renderer *) renderer)->addTexture(backBuffer)) == TEXTURE_NONE)
			return false;
		backBuffer->AddRef();
	}


	if (depthBufferFormat != DXGI_FORMAT_UNKNOWN)
	{
		// Create depth stencil texture
		D3D11_TEXTURE2D_DESC descDepth;
		descDepth.Width  = width;
		descDepth.Height = height;
		descDepth.MipLevels = 1;
		descDepth.ArraySize = 1;
		descDepth.Format = depthBufferFormat;
		descDepth.SampleDesc.Count = msaaSamples;
		descDepth.SampleDesc.Quality = 0;
		descDepth.Usage = D3D11_USAGE_DEFAULT;
		descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL;
		descDepth.CPUAccessFlags = 0;
		descDepth.MiscFlags = 0;
		if (FAILED(device->CreateTexture2D(&descDepth, NULL, &depthBuffer)))
		{
			ErrorMsg("Couldn't create main depth buffer");
			return false;
		}

		// Create the depth stencil view
		D3D11_DEPTH_STENCIL_VIEW_DESC descDSV;
		ZeroMemory( &descDSV, sizeof(descDSV) );	// ²À ÇÊ¿ä!
		descDSV.Format = descDepth.Format;
		descDSV.ViewDimension = msaaSamples > 1? D3D11_DSV_DIMENSION_TEXTURE2DMS : D3D11_DSV_DIMENSION_TEXTURE2D;
		descDSV.Texture2D.MipSlice = 0;
		if (FAILED(device->CreateDepthStencilView(depthBuffer, &descDSV, &depthBufferDSV)))
			return false;
	}

	context->OMSetRenderTargets(1, &backBufferRTV, depthBufferDSV);

	// Setup the viewport
	D3D11_VIEWPORT viewport;
	viewport.Width  = (float) width;
	viewport.Height = (float) height;
	viewport.MinDepth = 0.0f;
	viewport.MaxDepth = 1.0f;
	viewport.TopLeftX = 0;
	viewport.TopLeftY = 0;
	context->RSSetViewports(1, &viewport);

	((Direct3D11Renderer *) renderer)->setFrameBuffer(backBufferRTV, depthBufferDSV);

	return true;
}
Beispiel #30
0
bool StartVideo(void)
{
#ifndef _XBOX
	SystemParametersInfo(SPI_GETSCREENSAVEACTIVE, 0, &windowSetting.screenSaverStatus, 0);
	if( windowSetting.screenSaverStatus )	
		SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, FALSE, 0, 0);		// Disable screen saver

	windowSetting.timer = SetTimer(g_GraphicsInfo.hWnd, 100, 1000, (TIMERPROC)TimerProc);
#endif
	windowSetting.dps = windowSetting.fps = -1;
	windowSetting.lastSecDlistCount = windowSetting.lastSecFrameCount = 0xFFFFFFFF;

	g_CritialSection.Lock();

    memcpy(&g_curRomInfo.romheader, g_GraphicsInfo.HEADER, sizeof(ROMHeader));
    unsigned char *puc = (unsigned char *) &g_curRomInfo.romheader;
    unsigned int i;
    unsigned char temp;
    for (i = 0; i < sizeof(ROMHeader); i += 4) /* byte-swap the ROM header */
    {
        temp     = puc[i];
        puc[i]   = puc[i+3];
        puc[i+3] = temp;
        temp     = puc[i+1];
        puc[i+1] = puc[i+2];
        puc[i+2] = temp;
    }

	ROM_GetRomNameFromHeader(g_curRomInfo.szGameName, &g_curRomInfo.romheader);
	Ini_GetRomOptions(&g_curRomInfo);
	char *p = g_curRomInfo.szGameName + (lstrlen(g_curRomInfo.szGameName) -1);		// -1 to skip null
	while (p >= g_curRomInfo.szGameName)
	{
		if( *p == ':' || *p == '\\' || *p == '/' )
			*p = '-';
		p--;
	}

	GenerateCurrentRomOptions();
	status.dwTvSystem = CountryCodeToTVSystem(g_curRomInfo.romheader.nCountryID);
	if( status.dwTvSystem == TV_SYSTEM_NTSC )
		status.fRatio = 0.75f;
	else
		status.fRatio = 9/11.0f;;
	
	InitExternalTextures();
		
	try {
		CDeviceBuilder::GetBuilder()->CreateGraphicsContext();
		CGraphicsContext::InitWindowInfo();

		bool res = CGraphicsContext::Get()->Initialize(g_GraphicsInfo.hWnd, g_GraphicsInfo.hStatusBar, 640, 480, TRUE);		
		if(!res )
		{
			g_CritialSection.Unlock();
			return false;
		}

		CDeviceBuilder::GetBuilder()->CreateRender();
		CRender::GetRender()->Initialize();
		DLParser_Init();
		status.bGameIsRunning = true;
	}
	catch(...)
	{
		ErrorMsg("Exception caught while starting video renderer");
		throw 0;
	}

	g_CritialSection.Unlock();
	return true;
}