bool DirectSound::init()
{
  HRESULT hr;

  dsoundDLL = LoadLibrary("DSOUND.DLL");
  HRESULT (WINAPI *DSoundCreate)(LPCGUID,LPDIRECTSOUND *,IUnknown *);  
  if(dsoundDLL != NULL) {    
    DSoundCreate = (HRESULT (WINAPI *)(LPCGUID,LPDIRECTSOUND *,IUnknown *))
      GetProcAddress(dsoundDLL, "DirectSoundCreate");
    
    if(DSoundCreate == NULL) {
      theApp.directXMessage("DirectSoundCreate");
      return false;
    }
  } else {
    theApp.directXMessage("DSOUND.DLL");
    return false;
  }
  
  if((hr = DSoundCreate(NULL,&pDirectSound,NULL) != DS_OK)) {
    //    errorMessage(myLoadString(IDS_ERROR_SOUND_CREATE), hr);
    systemMessage(IDS_CANNOT_CREATE_DIRECTSOUND,
                  "Cannot create DirectSound %08x", hr);
    pDirectSound = NULL;
    dsbSecondary = NULL;
    return false;
  }

  if((hr=pDirectSound->SetCooperativeLevel((HWND)*theApp.m_pMainWnd,
                                           DSSCL_EXCLUSIVE)) != DS_OK) {
    //    errorMessage(myLoadString(IDS_ERROR_SOUND_LEVEL), hr);
    systemMessage(IDS_CANNOT_SETCOOPERATIVELEVEL,
                  "Cannot SetCooperativeLevel %08x", hr);
    return false;
  }

  DSBUFFERDESC dsbdesc;
  ZeroMemory(&dsbdesc,sizeof(DSBUFFERDESC));
  dsbdesc.dwSize=sizeof(DSBUFFERDESC);
  dsbdesc.dwFlags = DSBCAPS_PRIMARYBUFFER;
  
  if((hr=pDirectSound->CreateSoundBuffer(&dsbdesc,
                                         &dsbPrimary,
                                         NULL) != DS_OK)) {
    //    errorMessage(myLoadString(IDS_ERROR_SOUND_BUFFER),hr);
    systemMessage(IDS_CANNOT_CREATESOUNDBUFFER,
                  "Cannot CreateSoundBuffer %08x", hr);
    return false;
  }
  
  // Set primary buffer format

  memset(&wfx, 0, sizeof(WAVEFORMATEX)); 
  wfx.wFormatTag = WAVE_FORMAT_PCM; 
  wfx.nChannels = 2;
  switch(soundQuality) {
  case 2:
    wfx.nSamplesPerSec = 22050;
    soundBufferLen = 736*2;
    soundBufferTotalLen = 7360*2;
    break;
  case 4:
    wfx.nSamplesPerSec = 11025;
    soundBufferLen = 368*2;
    soundBufferTotalLen = 3680*2;
    break;
  default:
    soundQuality = 1;
    wfx.nSamplesPerSec = 44100;
    soundBufferLen = 1470*2;
    soundBufferTotalLen = 14700*2;
  }
  wfx.wBitsPerSample = 16; 
  wfx.nBlockAlign = (wfx.wBitsPerSample / 8) * wfx.nChannels;
  wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign;

  if((hr = dsbPrimary->SetFormat(&wfx)) != DS_OK) {
    //    errorMessage(myLoadString(IDS_ERROR_SOUND_PRIMARY),hr);
    systemMessage(IDS_CANNOT_SETFORMAT_PRIMARY,
                  "Cannot SetFormat for primary %08x", hr);
    return false;
  }
  
  ZeroMemory(&dsbdesc,sizeof(DSBUFFERDESC));  
  dsbdesc.dwSize = sizeof(DSBUFFERDESC);
  dsbdesc.dwFlags = DSBCAPS_GETCURRENTPOSITION2|DSBCAPS_CTRLPOSITIONNOTIFY;
  dsbdesc.dwBufferBytes = soundBufferTotalLen;
  dsbdesc.lpwfxFormat = &wfx;

  if((hr = pDirectSound->CreateSoundBuffer(&dsbdesc, &dsbSecondary, NULL))
     != DS_OK) {
    dsbdesc.dwFlags = DSBCAPS_GETCURRENTPOSITION2;
    if((hr = pDirectSound->CreateSoundBuffer(&dsbdesc, &dsbSecondary, NULL))
       != DS_OK) {
      systemMessage(IDS_CANNOT_CREATESOUNDBUFFER_SEC,
                    "Cannot CreateSoundBuffer secondary %08x", hr);
      return false;
    }
  }

  dsbSecondary->SetCurrentPosition(0);

  if(!theApp.useOldSync) {
    hr = dsbSecondary->QueryInterface(IID_IDirectSoundNotify,
                                      (void **)&dsbNotify);
    if(!FAILED(hr)) {
      dsbEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
      
      DSBPOSITIONNOTIFY notify[10];
      
      for(int i = 0; i < 10; i++) {
        notify[i].dwOffset = i*soundBufferLen;
        notify[i].hEventNotify = dsbEvent;
      }
      if(FAILED(dsbNotify->SetNotificationPositions(10, notify))) {
        dsbNotify->Release();
        dsbNotify = NULL;
        CloseHandle(dsbEvent);
        dsbEvent = NULL;
      }
    }
  }
  
  hr = dsbPrimary->Play(0,0,DSBPLAY_LOOPING);

  if(hr != DS_OK) {
    //    errorMessage(myLoadString(IDS_ERROR_SOUND_PLAYPRIM), hr);
    systemMessage(IDS_CANNOT_PLAY_PRIMARY, "Cannot Play primary %08x", hr);
    return false;
  }

  systemSoundOn = true;
  
  return true;
}
Esempio n. 2
0
bool MainWnd::FileRun()
{
  // save battery file before we change the filename...
  if(rom != NULL || gbRom != NULL) {
    if(theApp.autoSaveLoadCheatList)
      winSaveCheatListDefault();
    writeBatteryFile();
    cheatSearchCleanup(&cheatSearchData);
    theApp.emuCleanUp();
    remoteCleanUp(); 
    emulating = false;   
  }
  char tempName[2048];
  char file[2048];
  
  utilGetBaseName(theApp.szFile, tempName);
  
  _fullpath(file, tempName, 1024);
  theApp.filename = file;

  int index = theApp.filename.ReverseFind('.');
  if(index != -1)
    theApp.filename = theApp.filename.Left(index);

  CString ipsname;
  ipsname.Format("%s.ips", theApp.filename);  

  if(!theApp.dir.GetLength()) {
    int index = theApp.filename.ReverseFind('\\');
    if(index != -1) {
      theApp.dir = theApp.filename.Left(index-1);
    }
  }

  IMAGE_TYPE type = utilFindType(theApp.szFile);

  if(type == IMAGE_UNKNOWN) {
    systemMessage(IDS_UNSUPPORTED_FILE_TYPE,
                  "Unsupported file type: %s", theApp.szFile);
    return false;
  }

  theApp.cartridgeType = (int)type;
  if(type == IMAGE_GB) {
    if(!gbLoadRom(theApp.szFile))
      return false;
    theApp.emuWriteState = gbWriteSaveState;
    theApp.emuWriteMemState = gbWriteMemSaveState;
    theApp.emuReadState = gbReadSaveState;
    theApp.emuReadMemState = gbReadMemSaveState;
    theApp.emuWriteBattery = gbWriteBatteryFile;
    theApp.emuReadBattery = gbReadBatteryFile;
    theApp.emuReset = gbReset;
    theApp.emuCleanUp = gbCleanUp;
    theApp.emuWritePNG = gbWritePNGFile;
    theApp.emuWriteBMP = gbWriteBMPFile;
    theApp.emuMain = gbEmulate;
#ifdef FINAL_VERSION
    theApp.emuCount = 70000/4;
#else
    theApp.emuCount = 1000;
#endif
    gbBorderOn = theApp.winGbBorderOn;
    if(theApp.autoIPS) {
      int size = gbRomSize;
      utilApplyIPS(ipsname, &gbRom, &size);
      if(size != gbRomSize) {
        extern bool gbUpdateSizes();
        gbUpdateSizes();
        gbReset();
      }
    }
  } else {
    int size = CPULoadRom(theApp.szFile);
    if(!size)
      return false;
    
    flashSetSize(theApp.winFlashSize);
    rtcEnable(theApp.winRtcEnable);
    cpuSaveType = theApp.winSaveType;

    //    if(cpuEnhancedDetection && winSaveType == 0) {
    //      utilGBAFindSave(rom, size);
    //    }
    GetModuleFileName(NULL, tempName, 2048);

    char *p = strrchr(tempName, '\\');
    if(p)
      *p = 0;
    
    char buffer[5];
    strncpy(buffer, (const char *)&rom[0xac], 4);
    buffer[4] = 0;

    strcat(tempName, "\\vba-over.ini");
    
    UINT i = GetPrivateProfileInt(buffer,
                                  "rtcEnabled",
                                  -1,
                                  tempName);
    if(i != (UINT)-1)
      rtcEnable(i == 0 ? false : true);

    i = GetPrivateProfileInt(buffer,
                             "flashSize",
                             -1,
                             tempName);
    if(i != (UINT)-1 && (i == 0x10000 || i == 0x20000))
      flashSetSize((int)i);

    i = GetPrivateProfileInt(buffer,
                             "saveType",
                             -1,
                             tempName);
    if(i != (UINT)-1 && (i <= 5))
      cpuSaveType = (int)i;

    theApp.emuWriteState = CPUWriteState;
    theApp.emuWriteMemState = CPUWriteMemState;
    theApp.emuReadState = CPUReadState;
    theApp.emuReadMemState = CPUReadMemState;
    theApp.emuWriteBattery = CPUWriteBatteryFile;
    theApp.emuReadBattery = CPUReadBatteryFile;
    theApp.emuReset = CPUReset;
    theApp.emuCleanUp = CPUCleanUp;
    theApp.emuWritePNG = CPUWritePNGFile;
    theApp.emuWriteBMP = CPUWriteBMPFile;
    theApp.emuMain = CPULoop;
#ifdef FINAL_VERSION
    theApp.emuCount = 250000;
#else
    theApp.emuCount = 5000;
#endif
    if(theApp.removeIntros && rom != NULL) {
      *((u32 *)rom)= 0xea00002e;
    }
    
    if(theApp.autoIPS) {
      int size = 0x2000000;
      utilApplyIPS(ipsname, &rom, &size);
      if(size != 0x2000000) {
        CPUReset();
      }
    }
  }
    
  if(theApp.soundInitialized) {
    if(theApp.cartridgeType == 1)
      gbSoundReset();
    else
      soundReset();
  } else {
    if(!soundOffFlag)
      soundInit();
    theApp.soundInitialized = true;
  }

  if(type == IMAGE_GBA) {
    skipBios = theApp.skipBiosFile ? true : false;
    CPUInit((char *)(LPCTSTR)theApp.biosFileName, theApp.useBiosFile ? true : false);
    CPUReset();
  }
  
  readBatteryFile();

  if(theApp.autoSaveLoadCheatList)
    winLoadCheatListDefault();
  
  theApp.addRecentFile(theApp.szFile);

  theApp.updateWindowSize(theApp.videoOption);

  theApp.updateFrameSkip();

  if(theApp.autoHideMenu && theApp.videoOption > VIDEO_4X && theApp.menuToggle)
    OnFileTogglemenu();
 
  emulating = true;

  if(theApp.autoLoadMostRecent)
    OnFileLoadgameMostrecent();

  theApp.frameskipadjust = 0;
  theApp.renderedFrames = 0;
  theApp.autoFrameSkipLastTime = theApp.throttleLastTime = systemGetClock();

  theApp.rewindCount = 0;
  theApp.rewindCounter = 0;
  theApp.rewindSaveNeeded = false;
  
  theApp.disablePowerManagement();
  
  return true;
}
Esempio n. 3
0
void GBMapView::savePNG(const char *name)
{
  u8 writeBuffer[1024 * 3];

  FILE *fp = fopen(name,"wb");

  if(!fp) {
    systemMessage(MSG_ERROR_CREATING_FILE, "Error creating file %s", name);
    return;
  }

  png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
                                                NULL,
                                                NULL,
                                                NULL);
  if(!png_ptr) {
    fclose(fp);
    return;
  }

  png_infop info_ptr = png_create_info_struct(png_ptr);

  if(!info_ptr) {
    png_destroy_write_struct(&png_ptr,NULL);
    fclose(fp);
    return;
  }

  if(setjmp(png_ptr->jmpbuf)) {
    png_destroy_write_struct(&png_ptr,NULL);
    fclose(fp);
    return;
  }

  png_init_io(png_ptr,fp);

  png_set_IHDR(png_ptr,
               info_ptr,
               w,
               h,
               8,
               PNG_COLOR_TYPE_RGB,
               PNG_INTERLACE_NONE,
               PNG_COMPRESSION_TYPE_DEFAULT,
               PNG_FILTER_TYPE_DEFAULT);

  png_write_info(png_ptr,info_ptr);

  u8 *b = writeBuffer;

  int sizeX = w;
  int sizeY = h;

  u8 *pixU8 = (u8 *)data;
  for(int y = 0; y < sizeY; y++) {
    for(int x = 0; x < sizeX; x++) {
      int blue = *pixU8++;
      int green = *pixU8++;
      int red = *pixU8++;

      *b++ = red;
      *b++ = green;
      *b++ = blue;
    }
    png_write_row(png_ptr,writeBuffer);

    b = writeBuffer;
  }

  png_write_end(png_ptr, info_ptr);

  png_destroy_write_struct(&png_ptr, &info_ptr);

  fclose(fp);
}
Esempio n. 4
0
void ChatBox::userParted(const QString &name)
{
	systemMessage(tr("<b>%1</b> left the session").arg(esc(name)));
}
Esempio n. 5
0
void Logging::OnMaxtextLog() 
{
  systemMessage(0, "Max text length reached %d", m_log.GetLimitText());
}
Esempio n. 6
0
void TabBarPlus::init(HINSTANCE hInst, HWND parent, bool isVertical, bool isTraditional, bool isMultiLine)
{
	Window::init(hInst, parent);
	int vertical = isVertical?(TCS_VERTICAL | TCS_MULTILINE | TCS_RIGHTJUSTIFY):0;
	_isTraditional = isTraditional;
	_isVertical = isVertical;
	_isMultiLine = isMultiLine;

	INITCOMMONCONTROLSEX icce;
	icce.dwSize = sizeof(icce);
	icce.dwICC = ICC_TAB_CLASSES;
	InitCommonControlsEx(&icce);
    int multiLine = isMultiLine?(_isTraditional?TCS_MULTILINE:0):0;

	int style = WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE |\
        TCS_TOOLTIPS | TCS_FOCUSNEVER | TCS_TABS | vertical | multiLine;

	//if (isOwnerDrawTab() && (!_isTraditional))
	{
		style |= TCS_OWNERDRAWFIXED;
		//printStr(TEXT("ownerDraw"));
	}
	_hSelf = ::CreateWindowEx(
				/*TCS_EX_FLATSEPARATORS */0,
				WC_TABCONTROL,
				TEXT("Tab"),
				style,
				0, 0, 0, 0,
				_hParent,
				NULL,
				_hInst,
				0);

	if (!_hSelf)
	{
		systemMessage(TEXT("System Err"));
		throw int(69);
	}
	if (!_isTraditional)
    {
		if (!_hwndArray[_nbCtrl])
		{
			_hwndArray[_nbCtrl] = _hSelf;
			_ctrlID = _nbCtrl;
		}
		else
		{
			int i = 0;
			bool found = false;
			for ( ; i < nbCtrlMax && !found ; i++)
				if (!_hwndArray[i])
					found = true;
			if (!found)
			{
				_ctrlID = -1;
				::MessageBox(NULL, TEXT("The nb of Tab Control is over its limit"), TEXT("Tab Control err"), MB_OK);
				destroy();
				throw int(96);
			}
			_hwndArray[i] = _hSelf;
			_ctrlID = i;
		}
		_nbCtrl++;

        ::SetWindowLongPtr(_hSelf, GWLP_USERDATA, (LONG_PTR)this);
	    _tabBarDefaultProc = reinterpret_cast<WNDPROC>(::SetWindowLongPtr(_hSelf, GWLP_WNDPROC, (LONG_PTR)TabBarPlus_Proc));
    }

	LOGFONT LogFont;

	_hFont = (HFONT)::SendMessage(_hSelf, WM_GETFONT, 0, 0);

	if (_hFont == NULL)
		_hFont = (HFONT)::GetStockObject(DEFAULT_GUI_FONT);

	if (_hLargeFont == NULL)
		_hLargeFont = (HFONT)::GetStockObject(SYSTEM_FONT);

	if (::GetObject(_hFont, sizeof(LOGFONT), &LogFont) != 0)
	{
		LogFont.lfEscapement  = 900;
		LogFont.lfOrientation = 900;
		_hVerticalFont = CreateFontIndirect(&LogFont);

		LogFont.lfWeight = 900;
		_hVerticalLargeFont = CreateFontIndirect(&LogFont);
	}
}
void MainWnd::OnToolsPlayStartmovieplaying()
{
  static bool moviePlayMessage = false;

  if(!moviePlayMessage) {
    moviePlayMessage = true;
    CString msg = winResLoadString(IDS_MOVIE_PLAY);
    CString title = winResLoadString(IDS_CONFIRM_ACTION);
    if(MessageBox(msg,
                  title,
                  MB_OKCANCEL) == IDCANCEL)
      return;
  }

  CString captureBuffer;
  CString capdir = regQueryStringValue("movieRecordDir", "");

  if(capdir.IsEmpty())
    capdir = getDirFromFile(theApp.filename);

  CString filter = theApp.winLoadFilter(IDS_FILTER_VMV);
  CString title = winResLoadString(IDS_SELECT_MOVIE_NAME);

  LPCTSTR exts[] = { ".VMV" };

  FileDlg dlg(this, "", filter, 1, "VMV", exts, capdir, title, false);

  if(dlg.DoModal() == IDCANCEL) {
    return;
  }

  CString movieName = dlg.GetPathName();
  captureBuffer = movieName;

  theApp.movieFile = fopen(movieName, "rb");

  if(!theApp.movieFile) {
    systemMessage(IDS_CANNOT_OPEN_FILE, "Cannot open file %s",
                  (const char *)movieName);
    return;
  }
  int version = 0;
  fread(&version, 1, sizeof(int), theApp.movieFile);
  if(version != 1) {
    systemMessage(IDS_UNSUPPORTED_MOVIE_VERSION,
                  "Unsupported movie version %d.",
                  version);
    fclose(theApp.movieFile);
    theApp.movieFile = NULL;
    return;
  }
  movieName = movieName.Left(movieName.GetLength()-3)+"VM0";
  if(loadSaveGame(movieName)) {
    moviePlaying = true;
    movieFrame = 0;
    moviePlayFrame = 0;
    movieLastJoypad = 0;
    theApp.movieReadNext();
  } else {
    systemMessage(IDS_CANNOT_OPEN_FILE, "Cannot open file %s",
                  (const char *)movieName);
  }
}
Esempio n. 8
0
void Process::listenerStdErr()
{
	//BOOL Result = 0;
	//DWORD size = 0;
	DWORD bytesAvail = 0;
	BOOL result = 0;
	HANDLE hListenerEvent = ::OpenEvent(EVENT_ALL_ACCESS, FALSE, TEXT("listenerStdErrEvent"));

	int taille = 0;
	//TCHAR bufferOut[MAX_LINE_LENGTH + 1];
	TCHAR bufferErr[MAX_LINE_LENGTH + 1];

	int nExitCode = STILL_ACTIVE;

	DWORD errbytesRead;

	::ResumeThread(_hProcessThread);

    bool goOn = true;
	while (goOn)
	{ // got data
		memset(bufferErr, 0x00, MAX_LINE_LENGTH + 1);
		taille = sizeof(bufferErr) - sizeof(TCHAR);

		Sleep(50);

		if (!::PeekNamedPipe(_hPipeErrR, bufferErr, taille, &errbytesRead, &bytesAvail, NULL))
		{
			bytesAvail = 0;
            goOn = false;
			break;
		}

		if(errbytesRead)
		{
			result = :: ReadFile(_hPipeErrR, bufferErr, taille, &errbytesRead, NULL);
			if ((!result) && (errbytesRead == 0))
            {
                goOn = false;
				break;
            }
		}
		//outbytesRead = strlen(bufferOut);
		bufferErr[errbytesRead] = '\0';
		generic_string s;
		s.assign(bufferErr);
		_stderrStr += s;

		if (::GetExitCodeProcess(_hProcess, (unsigned long*)&nExitCode))
		{
			if (nExitCode != STILL_ACTIVE)
            {
                goOn = false;
				break; // EOF condition
            }
		}
		//else
			//break;
	}
	//_exitCode = nExitCode;

	if(!::SetEvent(hListenerEvent))
	{
		systemMessage(TEXT("Thread stdout listener"));
	}
}
Esempio n. 9
0
void CChatSession::OnDisconnect()
{
	m_nState = csClosed;
	emit systemMessage("Connection lost");
}
Esempio n. 10
0
void ChatBox::kicked(const QString &kickedBy)
{
	systemMessage(tr("You have been kicked by %1").arg(kickedBy.toHtmlEscaped()));
}
Esempio n. 11
0
void AccelEditor::OnRemove()
{
	// Some controls
	POSITION selected = m_currents.GetFirstSelectedItemPosition();
	if (selected == NULL)
		return;

	HTREEITEM hItem = m_commands.GetSelectedItem();
	if (hItem == NULL)
		return;

	// Ref to the ID command
	WORD wIDCommand = LOWORD(m_commands.GetItemData(hItem));

	// Run through the accels, and control if it can be deleted.
	CCmdAccelOb *pCmdAccel;
	if (m_mgr.m_mapAccelTable.Lookup(wIDCommand, pCmdAccel) == TRUE)
	{
		POSITION pos = pCmdAccel->m_Accels.GetHeadPosition();
		POSITION PrevPos;
		while (pos != NULL)
		{
			PrevPos = pos;
			CAccelsOb *pAccel = pCmdAccel->m_Accels.GetNext(pos);
			do
			{
				int indexCurrent = m_currents.GetNextSelectedItem(selected);
				CAccelsOb *pAccelCurrent = reinterpret_cast<CAccelsOb *>(m_currents.GetItemData(indexCurrent));
				if (pAccel == pAccelCurrent)
				{
					if (!pAccel->m_bLocked)
					{
						// not locked, so we delete the key
						pCmdAccel->m_Accels.RemoveAt(PrevPos);
						delete pAccel;
						// and update the listboxes/key editor/static text
						m_currents.DeleteItem(indexCurrent);
						m_modified = TRUE;
						break;
					}
					else
					{
						systemMessage(0, "Unable to remove this locked accelerator: ", m_currents.GetItemText(indexCurrent, KEY_COLUMN));
						m_currents.SetItemState(indexCurrent, 0, LVIS_SELECTED); // deselect it
						break;
					}
				}
			}
			while (selected != NULL);

			selected = m_currents.GetFirstSelectedItemPosition();
			if (selected == NULL)	// the normal exit of this function
			{
				m_currents.SetItemState(m_currents.GetNextItem(-1, LVIS_FOCUSED), LVIS_SELECTED, LVIS_SELECTED);
				if (m_currents.GetSelectedCount() == 0)
				{
					GetDlgItem(IDC_REMOVE)->EnableWindow(FALSE);
					GetDlgItem(IDC_ACCELEDIT_REPLACE)->EnableWindow(FALSE);
				}
				GetDlgItem(IDC_ACCELEDIT_APPLY)->EnableWindow(m_modified);
				return;
			}
		}
		systemMessage(0, "internal error (AccelEditor::Remove : pAccel unavailable)");
		return;
	}
	systemMessage(0, "internal error (AccelEditor::Remove : Lookup failed)");
}
Esempio n. 12
0
void ChatBox::userParted(const QString &name)
{
	systemMessage(tr("<b>%1</b> left the session").arg(name.toHtmlEscaped()));
	notification::playSound(notification::Event::LOGOUT);
}
Esempio n. 13
0
void ChatBox::userJoined(int id, const QString &name)
{
	Q_UNUSED(id);
	systemMessage(tr("<b>%1</b> joined the session").arg(name.toHtmlEscaped()));
	notification::playSound(notification::Event::LOGIN);
}
Esempio n. 14
0
bool MainWnd::FileRun()
{
  // save battery file before we change the filename...
  if(rom != NULL || gbRom != NULL) {
    if(theApp.autoSaveLoadCheatList)
      winSaveCheatListDefault();
    writeBatteryFile();
    cheatSearchCleanup(&cheatSearchData);
    theApp.emulator.emuCleanUp();
    remoteCleanUp();
    emulating = false;
#ifdef APU_LOGGER_H
    end_apu_log();
#endif
  }
  char tempName[2048];
  char file[2048];
  CString oldFile = theApp.filename;

  utilStripDoubleExtension(theApp.szFile, tempName);

  _fullpath(file, tempName, 2048);
  theApp.filename = file;

  int index = theApp.filename.ReverseFind('.');
  if(index != -1)
    theApp.filename = theApp.filename.Left(index);

  if( theApp.filename != oldFile ) {
	  // clear cheat list when another game is loaded
	  cheatsDeleteAll( false );
	  gbCheatRemoveAll();
  }

  CString patchName;
  patchName.Format("%s.ips", theApp.filename);
  if( !fileExists( patchName ) ) {
	  patchName.Format("%s.ups", theApp.filename);
	  if( !fileExists( patchName ) ) {
		  patchName.Format("%s.ppf", theApp.filename);
		  if( !fileExists( patchName ) ) {
			  // don't use any patches
			  patchName.Empty();
		  }
	  }
  }


  if(!theApp.dir.GetLength()) {
    int index = theApp.filename.ReverseFind('\\');
    if(index != -1) {
      theApp.dir = theApp.filename.Left(index-1);
    }
  }

  IMAGE_TYPE type = utilFindType(theApp.szFile);

  if(type == IMAGE_UNKNOWN) {
    systemMessage(IDS_UNSUPPORTED_FILE_TYPE,
                  "Unsupported file type: %s", theApp.szFile);
    return false;
  }
  systemSaveUpdateCounter = SYSTEM_SAVE_NOT_UPDATED;
  theApp.cartridgeType = type;
  if(type == IMAGE_GB) {
    if(!gbLoadRom(theApp.szFile))
      return false;

    gbGetHardwareType();

    // used for the handling of the gb Boot Rom
    if (gbHardware & 5)
    {
      skipBios = theApp.skipBiosFile;
	  gbCPUInit(theApp.biosFileNameGB, theApp.useBiosFileGB);
    }



    gbReset();
    theApp.emulator = GBSystem;
    gbBorderOn = theApp.winGbBorderOn;
    theApp.romSize = gbRomSize;


    if(theApp.autoPatch && !patchName.IsEmpty()) {
      int size = gbRomSize;
      applyPatch(patchName, &gbRom, &size);
      if(size != gbRomSize) {
        extern bool gbUpdateSizes();
        gbUpdateSizes();
        gbReset();
        theApp.romSize = size;
      }
    }
  } else {
    int size = CPULoadRom(theApp.szFile);
    if(!size)
      return false;

    theApp.romSize = size;

    flashSetSize(theApp.winFlashSize);
    rtcEnable(theApp.winRtcEnable);
    cpuSaveType = theApp.winSaveType;

    GetModuleFileName(NULL, tempName, 2048);

    char *p = strrchr(tempName, '\\');
    if(p)
      *p = 0;

    char buffer[5];
    strncpy(buffer, (const char *)&rom[0xac], 4);
    buffer[4] = 0;

    strcat(tempName, "\\vba-over.ini");

    UINT i = GetPrivateProfileInt(buffer,
					                "rtcEnabled",
                                  -1,
                                  tempName);
    if(i != (UINT)-1)
      rtcEnable(i == 0 ? false : true);

    i = GetPrivateProfileInt(buffer,
                             "flashSize",
                             -1,
                             tempName);
    if(i != (UINT)-1 && (i == 0x10000 || i == 0x20000))
      flashSetSize((int)i);

    i = GetPrivateProfileInt(buffer,
                             "saveType",
                             -1,
                             tempName);
    if(i != (UINT)-1 && (i <= 5))
      cpuSaveType = (int)i;
    i = GetPrivateProfileInt(buffer,
                             "mirroringEnabled",
                             -1,
                             tempName);
    if(i != (UINT)-1)
      doMirroring (i == 0 ? false : true);

    theApp.emulator = GBASystem;
    /* disabled due to problems
    if(theApp.removeIntros && rom != NULL) {
      *((u32 *)rom)= 0xea00002e;
    }
    */

    if(theApp.autoPatch && !patchName.IsEmpty()) {
      int size = 0x2000000;
      applyPatch(patchName, &rom, &size);
      if(size != 0x2000000) {
        CPUReset();
      }
    }
  }

  if(theApp.soundInitialized) {
    if(theApp.cartridgeType == 1)
      gbSoundReset();
    else
      soundReset();
  } else {
	  soundInit();
    theApp.soundInitialized = true;
  }

#ifdef APU_LOGGER_H
  begin_apu_log("apu_log.txt");
#endif

  if(type == IMAGE_GBA) {
    skipBios = theApp.skipBiosFile;
    CPUInit(theApp.biosFileNameGBA.GetString(), theApp.useBiosFileGBA);
    CPUReset();
  }

  readBatteryFile();

  if(theApp.autoSaveLoadCheatList)
    winLoadCheatListDefault();

  theApp.addRecentFile(theApp.szFile);

  theApp.updateWindowSize(theApp.videoOption);

  theApp.updateFrameSkip();

  emulating = true;

  if(theApp.autoLoadMostRecent)
    OnFileLoadgameMostrecent();

  theApp.frameskipadjust = 0;
  theApp.renderedFrames = 0;
  theApp.autoFrameSkipLastTime = systemGetClock();

  theApp.rewindCount = 0;
  theApp.rewindCounter = 0;
  theApp.rewindSaveNeeded = false;

  toolsClearLog();

  return true;
}
Esempio n. 15
0
// autoroom, auto-creates a net room
Bool AutoRoom(const char *NewName, const char *Creator, g_slot NewGroup, h_slot NewHall)
	{
	if (!*NewName)
		{
		return (FALSE);
		}

	r_slot testslot = RoomExists(NewName);
	if (testslot != CERROR)
		{
		return (FALSE);
		}

	testslot = IdExists(NewName, FALSE);
	if (testslot != CERROR)
		{
		return (FALSE);
		}

	// add: locking the room database now, to ensure that this slot continues to be free
	const r_slot newSlot = FindFreeRoomSlot();
	if (newSlot == CERROR)
		{
		return (FALSE);
		}

	RoomC RoomBuffer;

	RoomBuffer.SetInuse(TRUE);
	RoomBuffer.SetPublic(TRUE);
	RoomBuffer.SetShared(TRUE);

	RoomBuffer.SetNetID(NewName);
	RoomBuffer.SetName(NewName);

	RoomBuffer.SetCreator(Creator);

	// Make sure no messages are in this room currently
	MessageDat.EnsureRoomEmpty(newSlot);

	cycleroom(newSlot, TRUE, TRUE);
#ifndef WINCIT
	// cycleroom() does this in wincit with its data syncronization. non-wincit needs CurrentUser to be updated
	CurrentUser->SetInRoom(newSlot, TRUE); 
#endif

	if (NewGroup >= 0)
		{
		RoomBuffer.SetGroupOnly(TRUE);
		RoomBuffer.SetBooleanGroup(FALSE);
		RoomBuffer.SetGroup(NewGroup);
		}

	// Create the room!
	RoomBuffer.Save(newSlot);

	// remove and unwindow room from all halls
	for (h_slot j = 0; j < cfg.maxhalls; j++)
		{
		HallData[j].SetRoomInHall(newSlot, FALSE);
		HallData[j].SetWindowedIntoHall(newSlot, FALSE);
		}

	// put room in maintenance hall
	HallData[MAINTENANCE].SetRoomInHall(newSlot, TRUE);

	// put room in hall if hall set in nodes.cit
	if (NewHall >= 0)
		{
		HallData[NewHall].SetRoomInHall(newSlot, TRUE);
		}

	HallData.Save();

	Message *Msg = new Message;

	if (Msg)
		{
#ifdef WINCIT
        trap(T_NEWROOM, "wow", getmsg(110), NewName, '>', Creator);
#else
        trap(T_NEWROOM, getmsg(110), NewName, '>', Creator);
#endif

		Msg->SetTextWithFormat(getmsg(457), cfg.Uroom_nym, NewName, '>', Creator);
		Msg->SetRoomNumber(newSlot);

		systemMessage(Msg);
		delete Msg;
		}
	else
		{
		OutOfMemory(46);
		}

	AddNetIDToNetIDCit(NewName, Creator);

	return (TRUE);
	}
Esempio n. 16
0
TRIGGER( targetobj )(obj user, obj usedon)
{
  cleanup();
  if(Q4BL(user, "The blacksmith skill", 0x00))
  {
    return(0x00);
  }
  if(!Q4ZM(user))
  {
    return(0x00);
  }
  if(isWeapon(usedon) && hasResource(usedon, resourceTypeToId("metal")))
  {
    if(isInContainer(usedon))
    {
      obj container = getTopmostContainer(usedon);
      if(isMobile(container))
      {
        if(container != user)
        {
          systemMessage(user, "You can't work on that item.");
          return(0x00);
        }
      }
    }
    int Q4G6 = getWeaponCurHP(usedon);
    int Q56H = getWeaponMaxHP(usedon);
    if((Q56H == 0x00) || (Q4G6 >= Q56H))
    {
      systemMessage(user, "That is already in full repair.");
      return(0x00);
    }
    int Q5MK = (Q56H - Q4G6) * 0x04E2 / Q56H - 0xFA;
    int Q4Q1;
    int success = testAndLearnSkill(user, 0x07, Q5MK, 0x32);
    Q56H --;
    Q4G6 --;
    if(Q4G6 < 0x01)
    {
      systemMessage(user, "You destroyed the item.");
      deleteObject(usedon);
    }
    else
    {
      if(success > 0x00)
      {
        Q4G6 = Q56H;
        systemMessage(user, "You repair the item.");
      }
      Q4Q1 = setWeaponMaxHP(usedon, Q56H);
      Q4Q1 = setWeaponCurHP(usedon, Q4G6);
    }
    if(Q46J(user, this))
    {
      deleteObject(this);
    }
    return(0x00);
  }
  systemMessage(user, "You can't repair that.");
  return(0x00);
}
Esempio n. 17
0
void TERMWINDOWMEMBER EnterRoom(Bool GroupOnly)
	{
	doCR();

	if (!loggedIn)
		{
		CRmPrintfCR(getmsg(239));
		return;
		}

	if (!LockMenu(MENU_ENTER))
		{
		return;
		}

	// The user must be able to make a room, and at least one of the remaining bits
	if (CurrentUser->IsMakeRoom()  && (cfg.nonAideRoomOk || HallData[thisHall].IsEnterRoom() || CurrentUser->IsAide()))
		{
		// There must be no limit to the number of rooms to make, be an aide, or be under the limit
		if (!cfg.numRooms || CurrentUser->IsAide() || roomsMade < cfg.numRooms)
			{
			label roomname;
			label groupname;
			g_slot groupslot;
			r_slot newSlot;
			Bool test;

			SetDoWhat(ENTERROOM);

			newSlot = FindFreeRoomSlot();

			if (newSlot == CERROR)
				{
				mPrintf(getmsg(490), cfg.Uroom_nym);
				UnlockMenu(MENU_ENTER);
				return;
				}

			if (!CurrentUser->IsExpert())
				{
				dispBlb(B_NEWROOM);
				doCR();
				}

			do
				{
				char Prompt[128];
				sprintf(Prompt, getmsg(106), cfg.Lroom_nym);

				do
					{
					getString(Prompt, roomname, LABELSIZE, ns);

					if (*roomname == '?')
						{
						MRO.Verbose = FALSE;
						listRooms(0);
						}
					} while (*roomname == '?');

				normalizeString(roomname);

				if (!*roomname)
					{
					UnlockMenu(MENU_ENTER);
					return;
					}

				test = TRUE;
				if (RoomExists(roomname) != CERROR)
					{
					mPrintfCR(getmsg(105), roomname, cfg.Lroom_nym);
					test = FALSE;
					}
				} while (!test);

			CurrentRoom->Clear();

			if (GroupOnly)
				{
				char String[128];
				sprintf(String, getmsg(588), cfg.Lgroup_nym, cfg.Lroom_nym);

				do
					{
					if (!AskGroupName(groupname, ns, String, LABELSIZE, TRUE))
						{
						CurrentRoom->Load(thisRoom); // From official release
						UnlockMenu(MENU_ENTER);
						return;
						}

					groupslot = FindGroupByPartialName(groupname, FALSE);

					test = TRUE;
					if (groupslot == CERROR || !CurrentUser->IsInGroup(groupslot))
						{
						CRmPrintfCR(getmsg(584), cfg.Lgroup_nym);
						test = FALSE;
						}
					} while (!test);

				CurrentRoom->SetGroup(groupslot);
				}

			CurrentRoom->SetInuse(TRUE);
			CurrentRoom->SetGroupOnly(GroupOnly);

			char Prompt[128], InfoLine[80];

			sprintf(Prompt, getmsg(107), cfg.Lroom_nym);
			getNormStr(Prompt, InfoLine, 79);
			CurrentRoom->SetInfoLine(InfoLine);

			sprintf(Prompt, getmenumsg(MENU_ENTER, 43), cfg.Lroom_nym);
			CurrentRoom->SetPublic(getYesNo(Prompt, 1));

			sprintf(Prompt, getmenumsg(MENU_ENTER, 44), roomname, (CurrentRoom->IsPublic()) ?
					getmenumsg(MENU_ENTER, 45) : getmenumsg(MENU_ENTER, 46), cfg.Lroom_nym);

			if (!getYesNo(Prompt, 0))
				{
				CurrentRoom->Load(thisRoom);
				UnlockMenu(MENU_ENTER);
				return;
				}

			CurrentRoom->SetName(roomname);

			label L;
			CurrentUser->GetName(L, sizeof(L));
			CurrentRoom->SetCreator(L);

			// Make sure that there are no stray messages still in this room
			MessageDat.EnsureRoomEmpty(newSlot);

			// Borgah!						VVV as if it could be BIO...
			if (!CurrentRoom->IsPublic() || CurrentRoom->IsBIO())
				{
				cycleroom(newSlot, FALSE, TRUE);
				}
			else
				{
				cycleroom(newSlot, TRUE, TRUE);
				}

			CurrentRoom->Save(newSlot);

			// remove and unwindow room from all halls
			for (h_slot j = 0; j < cfg.maxhalls; j++)
				{
				HallData[j].SetRoomInHall(newSlot, FALSE);
				HallData[j].SetWindowedIntoHall(newSlot, FALSE);
				}

			// put room in current hall
			HallData[thisHall].SetRoomInHall(newSlot, TRUE);

			// put room in maintenance hall
			HallData[MAINTENANCE].SetRoomInHall(newSlot, TRUE);

			HallData.Save();

			Message *Msg = new Message;

			if (Msg)
				{
				label UserName;
				CurrentUser->GetName(UserName, sizeof(UserName));

#ifdef WINCIT
                trap(T_NEWROOM, WindowCaption, getmsg(110), roomname, CurrentRoom->IsPublic() ? '>' : ')', UserName);
#else
                trap(T_NEWROOM, getmsg(110), roomname, CurrentRoom->IsPublic() ? '>' : ')', UserName);
#endif

				Msg->SetTextWithFormat(getmsg(457), cfg.Uroom_nym, roomname, CurrentRoom->IsPublic() ? '>' : ')',
						UserName);

				Msg->SetRoomNumber(newSlot);

				systemMessage(Msg);

				// Do it again because of funky compression stuff.
				Msg->SetTextWithFormat(getmsg(457), cfg.Uroom_nym, roomname, CurrentRoom->IsPublic() ? '>' : ')',
						UserName);

				if (CurrentRoom->IsGroupOnly())
					{
					Msg->SetGroup(CurrentRoom->GetGroup());
					}

				Msg->SetRoomNumber(AIDEROOM);

				systemMessage(Msg);

				delete Msg;
				}
			else
				{
				OutOfMemory(50);
				}

			CurrentUser->SetInRoom(newSlot, TRUE);

			roomsMade++;

			gotoRoom(roomname, FALSE, FALSE, FALSE);
			}
		else
			{
			CRmPrintfCR(getmenumsg(MENU_ENTER, 31), ltoac(cfg.numRooms), cfg.Lroom_nym);
			}
		}
	else
		{
		CRmPrintfCR(getmenumsg(MENU_ENTER, 32), cfg.Lrooms_nym);
		}

	UnlockMenu(MENU_ENTER);
	}
Esempio n. 18
0
TRIGGER( targetobj )(obj user, obj usedon)
{
  if(usedon == NULL())
  {
    return(0x00);
  }
  if(isAtHome(usedon))
  {
    systemMessage(user, "That belongs to someone else.");
    return(0x00);
  }
  int Q62A = getObjType(this);
  int Q66P = getObjType(usedon);
  loc Q66U = loc( getLocation(user) );
  loc Q61U = loc( getLocation(this) );
  loc Q66N = loc( getLocation(usedon) );
  obj Q4EZ;
  list args;
  if(testAndLearnSkill(user, 0x08, 0x00, 0x50) > 0x00)
  {
    switch(Q62A)
    {
    case 0x1BD1:
      switch(Q66P)
      {
      case 0x1BD4:
        attachScript(user, "makingarrows");
        args = list( this, usedon );
        message(user, "makearrows", args);
        break;
      default:
        systemMessage(user, "Can't use feathers on that.");
        return(0x00);
        break;
      }
      break;
    case 0x1BD4:
      switch(Q66P)
      {
      case 0x1BD1:
        attachScript(user, "makingarrows");
        args = list( usedon, this );
        message(user, "makearrows", args);
        break;
      default:
        systemMessage(user, "Can't use shafts on that.");
        return(0x00);
        break;
      }
      break;
    default:
      return(0x00);
      break;
    }
  }
  else
  {
    systemMessage(user, "Fletching failed.");
    int Q5MT;
    int Q4Q1;
    if(!random(0x00, 0x03))
    {
      debugMessage("!rand");
      debugMessage("thistype = " + Q62A);
      if(Q62A == 0x1BD1)
      {
        systemMessage(user, "A feather was destroyed.");
        returnResourcesToBank(this, 0x01, "feathers");
        Q4Q1 = getResource(Q5MT, this, "feathers", 0x03, 0x02);
      }
      if(Q62A == 0x1BD4)
      {
        systemMessage(user, "A shaft was destroyed.");
        returnResourcesToBank(this, 0x01, "wood");
        Q4Q1 = getResource(Q5MT, this, "wood", 0x03, 0x02);
      }
      if(Q5MT < 0x01)
      {
        deleteObject(this);
      }
    }
  }
  return(0x01);
}
Esempio n. 19
0
void MainWnd::OnToolsRecordStartavirecording()
{
	CString captureBuffer;
	CString capdir = regQueryStringValue( "aviRecordDir", NULL );

	if( capdir.IsEmpty() ) {
		capdir = getDirFromFile( theApp.filename );
	}

	CString filter = theApp.winLoadFilter( IDS_FILTER_AVI );
	CString title = winResLoadString( IDS_SELECT_AVI_NAME );

	LPCTSTR exts[] = { ".AVI" };

	FileDlg dlg( this, "", filter, 1, "AVI", exts, capdir, title, true );

	if( dlg.DoModal() == IDCANCEL ) {
		return;
	}

	captureBuffer = theApp.soundRecordName =  dlg.GetPathName();
	theApp.aviRecordName = captureBuffer;
	aviRecording = true;

	if( dlg.m_ofn.nFileOffset > 0 ) {
		captureBuffer = captureBuffer.Left( dlg.m_ofn.nFileOffset );
	}

	int len = captureBuffer.GetLength();

	if( ( len > 3 ) && captureBuffer[ len - 1 ] == '\\' ) {
		captureBuffer = captureBuffer.Left( len - 1 );
	}

	regSetStringValue( "aviRecordDir", captureBuffer );


	// create AVI file
	bool ret;

	if( theApp.aviRecorder ) {
		delete theApp.aviRecorder;
		theApp.aviRecorder = NULL;
	}
	theApp.aviRecorder = new AVIWrite();

	// create AVI file
	ret = theApp.aviRecorder->CreateAVIFile( theApp.aviRecordName );
	if( !ret ) {
		systemMessage( IDS_AVI_CANNOT_CREATE_AVI, "Cannot create AVI file." );
		delete theApp.aviRecorder;
		theApp.aviRecorder = NULL;
		aviRecording = false;
		return;
	}

	// add video stream
	ret = theApp.aviRecorder->CreateVideoStream(
		sizeX,
		sizeY,
		( systemColorDepth == 32 ) ? 24 : 16,
		60,
		this->GetSafeHwnd()
		);
	if( !ret ) {
		systemMessage( IDS_AVI_CANNOT_CREATE_VIDEO, "Cannot create video stream in AVI file. Make sure the selected codec supports input in RGB24 color space!" );
		delete theApp.aviRecorder;
		theApp.aviRecorder = NULL;
		aviRecording = false;
		return;
	}

	// add audio stream
	ret = theApp.aviRecorder->CreateAudioStream(
		2,
		soundGetSampleRate(),
		16,
		this->GetSafeHwnd()
		);
	if( !ret ) {
		systemMessage( IDS_AVI_CANNOT_CREATE_AUDIO, "Cannot create audio stream in AVI file." );
		delete theApp.aviRecorder;
		theApp.aviRecorder = NULL;
		aviRecording = false;
		return;
	}
}
Esempio n. 20
0
BOOL XAudio2_Config::OnInitDialog()
{
	CDialog::OnInitDialog();

	m_combo_dev.ResetContent();

	m_slider_buffer.SetRange( 2, 10, FALSE );
	m_slider_buffer.SetTicFreq( 1 );
	m_slider_buffer.SetPos( (int)m_buffer_count );

	CString info;
	int pos = m_slider_buffer.GetPos();
	info.Format( _T("%i frames = %.2f ms"), pos, (float)pos / 60.0f * 1000.0f );
	m_info_buffer.SetWindowText( info );

	HRESULT hr;
	IXAudio2 *xa = NULL;
	UINT32 flags = 0;
#ifdef _DEBUG
	flags = XAUDIO2_DEBUG_ENGINE;
#endif

	hr = XAudio2Create( &xa, flags );
	if( hr != S_OK ) {
		systemMessage( IDS_XAUDIO2_FAILURE, NULL );
	} else {
		UINT32 dev_count = 0;
		hr = xa->GetDeviceCount( &dev_count );
		if( hr != S_OK ) {
			systemMessage( IDS_XAUDIO2_CANNOT_ENUMERATE_DEVICES, NULL );
		} else {
			XAUDIO2_DEVICE_DETAILS dd;
			for( UINT32 i = 0; i < dev_count; i++ ) {
				hr = xa->GetDeviceDetails( i, &dd );
				if( hr != S_OK ) {
					continue;
				} else {
#ifdef _UNICODE
					int id = m_combo_dev.AddString( dd.DisplayName );
#else
					CHAR temp[256];
					ZeroMemory( temp, sizeof( temp ) );
					WideCharToMultiByte(
						CP_ACP,
						WC_NO_BEST_FIT_CHARS,
						dd.DisplayName,
						-1,
						temp,
						sizeof( temp ) - 1,
						NULL,
						NULL );
					
					int id = m_combo_dev.AddString( temp );
#endif
					if( id < 0 ) {
						systemMessage( IDS_XAUDIO2_CANNOT_ENUMERATE_DEVICES, NULL );
						break;
					} else {
						m_combo_dev.SetItemData( id, i );
					}
				}
			}

			// select the currently configured device {
			int count = m_combo_dev.GetCount();
			if( count > 0 ) {
				for( int i = 0; i < count; i++ ) {
					if( m_combo_dev.GetItemData( i ) == m_selected_device_index ) {
						m_combo_dev.SetCurSel( i );
						break;
					}
				}
			}
			// }

		}
		xa->Release();
		xa = NULL;
	}

	return TRUE;  // return TRUE unless you set the focus to a control
	// EXCEPTION: OCX Property Pages should return FALSE
}
Esempio n. 21
0
void ChatBox::userJoined(const QString &name)
{
	systemMessage(tr("<b>%1</b> joined the session").arg(esc(name)));
}
Esempio n. 22
0
void DirectSound::write(u16 * finalWave, int length)
{
	if(!pDirectSound) return;


	HRESULT      hr;
	DWORD        status = 0;
	DWORD        play = 0;
	LPVOID       lpvPtr1;
	DWORD        dwBytes1 = 0;
	LPVOID       lpvPtr2;
	DWORD        dwBytes2 = 0;

	if( !speedup && synchronize && !theApp.throttle ) {
		hr = dsbSecondary->GetStatus(&status);
		if( status & DSBSTATUS_PLAYING ) {
			if( !soundPaused ) {
				while( true ) {
					dsbSecondary->GetCurrentPosition(&play, NULL);
					  int BufferLeft = ((soundNextPosition <= play) ?
					  play - soundNextPosition :
					  soundBufferTotalLen - soundNextPosition + play);

		          if(BufferLeft > soundBufferLen)
				  {
					if (BufferLeft > soundBufferTotalLen - (soundBufferLen * 3))
						soundBufferLow = true;
					break;
				   }
				   soundBufferLow = false;

		          if(dsbEvent) {
		            WaitForSingleObject(dsbEvent, 50);
		          }
		        }
			}
		}/* else {
		 // TODO: remove?
			 setsoundPaused(true);
		}*/
	}


	// Obtain memory address of write block.
	// This will be in two parts if the block wraps around.
	if( DSERR_BUFFERLOST == ( hr = dsbSecondary->Lock(
		soundNextPosition,
		soundBufferLen,
		&lpvPtr1,
		&dwBytes1,
		&lpvPtr2,
		&dwBytes2,
		0 ) ) ) {
			// If DSERR_BUFFERLOST is returned, restore and retry lock.
			dsbSecondary->Restore();
			hr = dsbSecondary->Lock(
				soundNextPosition,
				soundBufferLen,
				&lpvPtr1,
				&dwBytes1,
				&lpvPtr2,
				&dwBytes2,
				0 );
	}

	soundNextPosition += soundBufferLen;
	soundNextPosition = soundNextPosition % soundBufferTotalLen;

	if( SUCCEEDED( hr ) ) {
		// Write to pointers.
		CopyMemory( lpvPtr1, finalWave, dwBytes1 );
		if ( lpvPtr2 ) {
			CopyMemory( lpvPtr2, finalWave + dwBytes1, dwBytes2 );
		}

		// Release the data back to DirectSound.
		hr = dsbSecondary->Unlock( lpvPtr1, dwBytes1, lpvPtr2, dwBytes2 );
	} else {
		systemMessage( 0, "dsbSecondary->Lock() failed: %08x", hr );
		return;
	}
}
Esempio n. 23
0
void Logging::OnErrspaceLog() 
{
  systemMessage(0, "Error allocating space");
}
Esempio n. 24
0
bool DirectSound::init(long sampleRate)
{
	HRESULT hr;
	DWORD freq;
	DSBUFFERDESC dsbdesc;
	int i;

	hr = CoCreateInstance( CLSID_DirectSound8, NULL, CLSCTX_INPROC_SERVER, IID_IDirectSound8, (LPVOID *)&pDirectSound );
	if( hr != S_OK ) {
		systemMessage( IDS_CANNOT_CREATE_DIRECTSOUND, NULL, hr );
		return false;
	}

	pDirectSound->Initialize( &DSDEVID_DefaultPlayback );
	if( hr != DS_OK ) {
		systemMessage( IDS_CANNOT_CREATE_DIRECTSOUND, NULL, hr );
		return false;
	}

	if( FAILED( hr = pDirectSound->SetCooperativeLevel( theApp.m_pMainWnd->GetSafeHwnd(), DSSCL_EXCLUSIVE ) ) ) {
		systemMessage( IDS_CANNOT_SETCOOPERATIVELEVEL, "Cannot SetCooperativeLevel %08x", hr );
		return false;
	}


	// Create primary sound buffer
	ZeroMemory( &dsbdesc, sizeof(DSBUFFERDESC) );
	dsbdesc.dwSize = sizeof(DSBUFFERDESC);
	dsbdesc.dwFlags = DSBCAPS_PRIMARYBUFFER;
	if( theApp.dsoundDisableHardwareAcceleration ) {
		dsbdesc.dwFlags |= DSBCAPS_LOCSOFTWARE;
	}

	if( FAILED( hr = pDirectSound->CreateSoundBuffer( &dsbdesc, &dsbPrimary, NULL ) ) ) {
		systemMessage(IDS_CANNOT_CREATESOUNDBUFFER, "Cannot CreateSoundBuffer %08x", hr);
		return false;
	}

	freq = sampleRate;
	// calculate the number of samples per frame first
	// then multiply it with the size of a sample frame (16 bit * stereo)
	soundBufferLen = ( freq / 60 ) * 4;
	soundBufferTotalLen = soundBufferLen * 10;
	soundNextPosition = 0;

	ZeroMemory( &wfx, sizeof(WAVEFORMATEX) );
	wfx.wFormatTag = WAVE_FORMAT_PCM;
	wfx.nChannels = 2;
	wfx.nSamplesPerSec = freq;
	wfx.wBitsPerSample = 16;
	wfx.nBlockAlign = wfx.nChannels * wfx.wBitsPerSample / 8;
	wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign;

	if( FAILED( hr = dsbPrimary->SetFormat( &wfx ) ) ) {
		systemMessage( IDS_CANNOT_SETFORMAT_PRIMARY, "CreateSoundBuffer(primary) failed %08x", hr );
		return false;
	}


	// Create secondary sound buffer
	ZeroMemory( &dsbdesc, sizeof(DSBUFFERDESC) );
	dsbdesc.dwSize = sizeof(DSBUFFERDESC);
	dsbdesc.dwFlags = DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_CTRLPOSITIONNOTIFY | DSBCAPS_GLOBALFOCUS;
	if( theApp.dsoundDisableHardwareAcceleration ) {
		dsbdesc.dwFlags |= DSBCAPS_LOCSOFTWARE;
	}
	dsbdesc.dwBufferBytes = soundBufferTotalLen;
	dsbdesc.lpwfxFormat = &wfx;

	if( FAILED( hr = pDirectSound->CreateSoundBuffer( &dsbdesc, &dsbSecondary, NULL ) ) ) {
		systemMessage( IDS_CANNOT_CREATESOUNDBUFFER, "CreateSoundBuffer(secondary) failed %08x", hr );
		return false;
	}

	if( FAILED( hr = dsbSecondary->SetCurrentPosition( 0 ) ) ) {
		systemMessage( 0, "dsbSecondary->SetCurrentPosition failed %08x", hr );
		return false;
	}


	if( SUCCEEDED( hr = dsbSecondary->QueryInterface( IID_IDirectSoundNotify8, (LPVOID*)&dsbNotify ) ) ) {
		dsbEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
		DSBPOSITIONNOTIFY notify[10];
		for( i = 0; i < 10; i++ ) {
			notify[i].dwOffset = i * soundBufferLen;
			notify[i].hEventNotify = dsbEvent;
		}

		if( FAILED( dsbNotify->SetNotificationPositions( 10, notify ) ) ) {
			dsbNotify->Release();
			dsbNotify = NULL;
			CloseHandle(dsbEvent);
			dsbEvent = NULL;
		}
	}


	// Play primary buffer
	if( FAILED( hr = dsbPrimary->Play( 0, 0, DSBPLAY_LOOPING ) ) ) {
		systemMessage( IDS_CANNOT_PLAY_PRIMARY, "Cannot Play primary %08x", hr );
		return false;
	}

	return true;
}
Esempio n. 25
0
TRIGGER( targetobj )(obj user, obj usedon)
{
  removeObjVar(this, "inUse");
  if(usedon == NULL())
  {
    return(0x00);
  }
  if(getDistanceInTiles(getLocation(user), getLocation(usedon)) > 0x03)
  {
    systemMessage(user, "That is too far away.");
    return(0x00);
  }
  if(getDistanceInTiles(getLocation(this), getLocation(usedon)) > 0x03)
  {
    systemMessage(user, "The ore is too far away.");
    return(0x00);
  }
  if(!canSeeObj(user, usedon))
  {
    systemMessage(user, "You can't see that.");
    return(0x00);
  }
  int Q4Q1;
  int Q4YO;
  Q4Q1 = getResource(Q4YO, this, "metal", 0x03, 0x02);
  int Q4Z5 = 0x00;
  int Q4ZU = 0x00;
  obj ore = this;
  int Q62A = getObjType(this);
  int Q66P = getObjType(usedon);
  if(Q66P == 0x0FB1)
  {
    Q4Z5 = 0x01;
  }
  if(Q66P >= 0x197A)
  {
    if(Q66P <= 0x19A9)
    {
      Q4Z5 = 0x01;
    }
  }
  if(Q66P > 0x19B6)
  {
    if(Q66P < 0x19BB)
    {
      Q4ZU = 0x01;
      if(isInContainer(this))
      {
        obj Q61O = getTopmostContainer(this);
        int Q62E = getWeight(Q61O) + getWeight(usedon);
      }
      if(isInContainer(usedon))
      {
        obj Q66Q = getTopmostContainer(usedon);
        int Q66T = getWeight(Q66Q) + getWeight(this);
      }
      if((Q62E > 0x03E8) || (Q66T > 0x03E8))
      {
        ebarkTo(user, user, "The weight is too great to combine in a container.");
        return(0x00);
      }
    }
  }
  if(Q4ZU)
  {
    ore = this;
    if(Q62A == 0x19B9)
    {
      Q4Q1 = getResource(Q4YO, ore, "metal", 0x03, 0x02);
      transferResources(usedon, ore, Q4YO, "metal");
    }
    if(Q62A == 0x19B8)
    {
      switch(Q66P)
      {
      case 0x19B9:
      case 0x19B8:
        Q4Q1 = getResource(Q4YO, usedon, "metal", 0x03, 0x02);
        transferResources(ore, usedon, Q4YO, "metal");
        break;
      case 0x19B7:
      case 0x19BA:
        Q4Q1 = getResource(Q4YO, ore, "metal", 0x03, 0x02);
        transferResources(usedon, ore, Q4YO, "metal");
        break;
      default:
        return(0x00);
        break;
      }
    }
    if(Q62A == 0x19BA)
    {
      switch(Q66P)
      {
      case 0x19B9:
      case 0x19B8:
        Q4Q1 = getResource(Q4YO, usedon, "metal", 0x03, 0x02);
        transferResources(ore, usedon, Q4YO, "metal");
        break;
      case 0x19B7:
      case 0x19BA:
        Q4Q1 = getResource(Q4YO, ore, "metal", 0x03, 0x02);
        transferResources(usedon, ore, Q4YO, "metal");
        break;
      default:
        return(0x00);
        break;
      }
    }
    if(Q62A == 0x19B7)
    {
      switch(Q66P)
      {
      case 0x19B9:
      case 0x19B8:
      case 0x19BA:
        Q4Q1 = getResource(Q4YO, usedon, "metal", 0x03, 0x02);
        transferResources(ore, usedon, Q4YO, "metal");
        break;
      case 0x19B7:
        Q4Q1 = getResource(Q4YO, ore, "metal", 0x03, 0x02);
        transferResources(usedon, ore, Q4YO, "metal");
        break;
      default:
        return(0x00);
        break;
      }
    }
    Q4Q1 = getResource(Q4YO, ore, "metal", 0x03, 0x02);
    if(Q4YO < 0x01)
    {
      deleteObject(ore);
    }
    Q4Q1 = getResource(Q4YO, usedon, "metal", 0x03, 0x02);
    if(Q4YO < 0x01)
    {
      deleteObject(usedon);
    }
    if(hasObjVar(this, "inUse"))
    {
      removeObjVar(this, "inUse");
    }
    return(0x00);
  }
  if(Q4Z5)
  {
    obj Q47G = getBackpack(user);
    ore = this;
    int Q5GQ = getObjType(ore);
    int Q4Y6 = 0x1BF2;
    Q4Q1 = getResource(Q4YO, ore, "metal", 0x03, 0x02);
    int count = Q4YO / 0x02;
    if(count < 0x01)
    {
      systemMessage(user, "There is not enough metal-bearing ore in this pile to make an ingot.");
      if(hasObjVar(this, "inUse"))
      {
        removeObjVar(this, "inUse");
      }
      return(0x00);
    }
    if(testSkill(user, 0x2D))
    {
      obj Q5BW = createNoResObjectIn(Q4Y6, Q47G);
      transferResources(Q5BW, ore, count, "metal");
      returnResourcesToBank(ore, count, "metal");
      Q4Q1 = putObjContainer(Q5BW, Q47G);
      Q4Q1 = getResource(Q4YO, ore, "metal", 0x03, 0x02);
      if(Q4YO < 0x01)
      {
        deleteObject(ore);
      }
      systemMessage(user, "You smelt the ore removing the impurities and put the metal in your backpack.");
    }
    else
    {
      if(count == 0x01)
      {
        systemMessage(user, "You burn away the impurities but are left with no useable metal.");
        deleteObject(ore);
        return(0x01);
      }
      returnResourcesToBank(ore, count, "metal");
      systemMessage(user, "You burn away the impurities but are left with less useable metal.");
      Q4Q1 = getResource(Q4YO, ore, "metal", 0x03, 0x02);
      if(Q4YO < 0x01)
      {
        deleteObject(ore);
      }
    }
  }
  return(0x01);
}
Esempio n. 26
0
bool XAudio2_Output::init(long sampleRate)
{
	if( failed || initialized ) return false;

	HRESULT hr;

	// Initialize XAudio2
	UINT32 flags = 0;
//#ifdef _DEBUG
//	flags = XAUDIO2_DEBUG_ENGINE;
//#endif

	hr = XAudio2Create( &xaud, flags );
	if( hr != S_OK ) {
		systemMessage( IDS_XAUDIO2_FAILURE, NULL );
		failed = true;
		return false;
	}


	freq = sampleRate;

	// calculate the number of samples per frame first
	// then multiply it with the size of a sample frame (16 bit * stereo)
	soundBufferLen = ( freq / 60 ) * 4;

	// create own buffers to store sound data because it must not be
	// manipulated while the voice plays from it
	buffers = (BYTE *)malloc( ( bufferCount + 1 ) * soundBufferLen );
	// + 1 because we need one temporary buffer when all others are in use

	WAVEFORMATEX wfx;
	ZeroMemory( &wfx, sizeof( wfx ) );
	wfx.wFormatTag = WAVE_FORMAT_PCM;
	wfx.nChannels = 2;
	wfx.nSamplesPerSec = freq;
	wfx.wBitsPerSample = 16;
	wfx.nBlockAlign = wfx.nChannels * ( wfx.wBitsPerSample / 8 );
	wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign;


	// create sound receiver
	hr = xaud->CreateMasteringVoice(
		&mVoice,
		XAUDIO2_DEFAULT_CHANNELS,
		XAUDIO2_DEFAULT_SAMPLERATE,
		0,
		theApp.xa2Device,
		NULL );
	if( hr != S_OK ) {
		systemMessage( IDS_XAUDIO2_CANNOT_CREATE_MASTERINGVOICE, NULL );
		failed = true;
		return false;
	}


	// create sound emitter
	hr = xaud->CreateSourceVoice( &sVoice, &wfx, 0, 4.0f, &notify );
	if( hr != S_OK ) {
		systemMessage( IDS_XAUDIO2_CANNOT_CREATE_SOURCEVOICE, NULL );
		failed = true;
		return false;
	}


	if( theApp.xa2Upmixing ) {
		// set up stereo upmixing
		XAUDIO2_DEVICE_DETAILS dd;
		ZeroMemory( &dd, sizeof( dd ) );
		hr = xaud->GetDeviceDetails( 0, &dd );
		ASSERT( hr == S_OK );
		float *matrix = NULL;
		matrix = (float*)malloc( sizeof( float ) * 2 * dd.OutputFormat.Format.nChannels );
        if( matrix == NULL ) return false;
		bool matrixAvailable = true;
		switch( dd.OutputFormat.Format.nChannels ) {
			case 4: // 4.0
	//Speaker \ Left Source           Right Source
	/*Front L*/	matrix[0] = 1.0000f;  matrix[1] = 0.0000f;
	/*Front R*/	matrix[2] = 0.0000f;  matrix[3] = 1.0000f;
	/*Back  L*/	matrix[4] = 1.0000f;  matrix[5] = 0.0000f;
	/*Back  R*/	matrix[6] = 0.0000f;  matrix[7] = 1.0000f;
				break;
			case 5: // 5.0
	//Speaker \ Left Source           Right Source
	/*Front L*/	matrix[0] = 1.0000f;  matrix[1] = 0.0000f;
	/*Front R*/	matrix[2] = 0.0000f;  matrix[3] = 1.0000f;
	/*Front C*/	matrix[4] = 0.7071f;  matrix[5] = 0.7071f;
	/*Side  L*/	matrix[6] = 1.0000f;  matrix[7] = 0.0000f;
	/*Side  R*/	matrix[8] = 0.0000f;  matrix[9] = 1.0000f;
				break;
			case 6: // 5.1
	//Speaker \ Left Source           Right Source
	/*Front L*/	matrix[0] = 1.0000f;  matrix[1] = 0.0000f;
	/*Front R*/	matrix[2] = 0.0000f;  matrix[3] = 1.0000f;
	/*Front C*/	matrix[4] = 0.7071f;  matrix[5] = 0.7071f;
	/*LFE    */	matrix[6] = 0.0000f;  matrix[7] = 0.0000f;
	/*Side  L*/	matrix[8] = 1.0000f;  matrix[9] = 0.0000f;
	/*Side  R*/	matrix[10] = 0.0000f;  matrix[11] = 1.0000f;
				break;
			case 7: // 6.1
	//Speaker \ Left Source           Right Source
	/*Front L*/	matrix[0] = 1.0000f;  matrix[1] = 0.0000f;
	/*Front R*/	matrix[2] = 0.0000f;  matrix[3] = 1.0000f;
	/*Front C*/	matrix[4] = 0.7071f;  matrix[5] = 0.7071f;
	/*LFE    */	matrix[6] = 0.0000f;  matrix[7] = 0.0000f;
	/*Side  L*/	matrix[8] = 1.0000f;  matrix[9] = 0.0000f;
	/*Side  R*/	matrix[10] = 0.0000f;  matrix[11] = 1.0000f;
	/*Back  C*/	matrix[12] = 0.7071f;  matrix[13] = 0.7071f;
				break;
			case 8: // 7.1
	//Speaker \ Left Source           Right Source
	/*Front L*/	matrix[0] = 1.0000f;  matrix[1] = 0.0000f;
	/*Front R*/	matrix[2] = 0.0000f;  matrix[3] = 1.0000f;
	/*Front C*/	matrix[4] = 0.7071f;  matrix[5] = 0.7071f;
	/*LFE    */	matrix[6] = 0.0000f;  matrix[7] = 0.0000f;
	/*Back  L*/	matrix[8] = 1.0000f;  matrix[9] = 0.0000f;
	/*Back  R*/	matrix[10] = 0.0000f;  matrix[11] = 1.0000f;
	/*Side  L*/	matrix[12] = 1.0000f;  matrix[13] = 0.0000f;
	/*Side  R*/	matrix[14] = 0.0000f;  matrix[15] = 1.0000f;
				break;
			default:
				matrixAvailable = false;
				break;
		}
		if( matrixAvailable ) {
			hr = sVoice->SetOutputMatrix( NULL, 2, dd.OutputFormat.Format.nChannels, matrix );
			ASSERT( hr == S_OK );
		}
		free( matrix );
		matrix = NULL;
	}


	hr = sVoice->Start( 0 );
	ASSERT( hr == S_OK );
	playing = true;

	currentBuffer = 0;
	device_changed = false;

	initialized = true;
	return true;
}
Esempio n. 27
0
void Process::error(const char *txt2display, BOOL & returnCode, int errCode)
{
	systemMessage(txt2display);
	returnCode = FALSE;
	throw int(errCode);
}
Esempio n. 28
0
///////////////////////////////////////////
// Dispatches Zone data packets based on the opCode
void EQPacket::dispatchZoneData(const uint8_t *data, size_t len, 
				uint8_t dir, uint16_t opCode)
{
#ifdef DEBUG_PACKET
    debug ("dispatchZoneData()");
#endif /* DEBUG_PACKET */

    QString  tempStr;

    bool unk = true;

    switch (opCode)
      {
      case OP_ClientUpdate: // old PlayerPosCode:
        {
#ifdef PACKET_PAYLOAD_SIZE_DIAG
	  if ((len != sizeof(playerSpawnPosStruct)) &&
	      (len != sizeof(playerSelfPosStruct)))
	  {
	    fprintf(stderr, "WARNING: OP_ClientUpdate (%04x) (dataLen: %d != sizeof(playerSpawnPosStruct):%d or sizeof(playerSpawnSelfStruct):%d)\n",
		    OP_ClientUpdate, len, 
		    sizeof(playerSpawnPosStruct), sizeof(playerSelfPosStruct));
	    unk = true;
	  }
	  else
	    unk = false;
#else
	  unk = false;
#endif
	  
	  if (len == sizeof(playerSpawnPosStruct))
	    emit playerUpdate((const playerSpawnPosStruct*)data, len, dir);
	  else if (len == sizeof(playerSelfPosStruct))
	    emit playerUpdate((const playerSelfPosStruct*)data, len, dir);
	  else
	    unk = true;
	  
	  break;
        }

      case OP_MobUpdate: // old MobUpdateCode:
        {
	  unk = ! ValidatePayload(OP_MobUpdate, spawnPositionUpdate);
	  
	  emit updateSpawns((const spawnPositionUpdate *)data, len, dir);
	  
	  break;
        }
	
      case OP_WearChange: // old SpawnUpdateCode:
        {
	  unk = ! ValidatePayload(OP_WearChange, SpawnUpdateStruct);
	  SpawnUpdateStruct *su = (SpawnUpdateStruct*)data;
//	    printf("SpawnUpdateCode(id=%d, sub=%d, arg1=%d, arg2=%d)\n", 
//		   su->spawnId, su->subcommand, 
//		   su->arg1, su->arg2);
	    /* Belith - I believe this is depreciated no? Doesn't work anyway ;) */
	  switch(su->subcommand) {
	  case 17:
	    emit updateSpawnMaxHP(su, len, dir);
	    break;
	  }
	  
	  break;
	  emit updateSpawnInfo(su, len, dir);
        }

      case OP_SpawnAppearance: // old SpawnAppearanceCode:
        {
	  unk = false;
	  
	  emit spawnAppearance((const spawnAppearanceStruct*)data, len, dir);
	  break;
        }
	
      case OP_CommonMessage: // old ChannelMessageCode:
	{
	  unk = false;
	  
	  emit channelMessage((const channelMessageStruct*)data, len, dir);
	  
	  break;
	}
	
      case OP_FormattedMessage: // old FormattedMessageCode:
	{
	  unk = false;
	  
	  emit formattedMessage((const formattedMessageStruct*)data, len, dir);
	  
	  break;
	}
	
      case OP_SimpleMessage: // old SimpleMessageCode:
	{
	  unk = false;

	  emit simpleMessage((const simpleMessageStruct*)data, len, dir);
	  
	  break;
	}
	
      case OP_SpecialMesg:
	{
	  unk = false;
	  
	  emit specialMessage((const specialMessageStruct*)data, len, dir);

	  break;
	}
	
      case OP_GuildMOTD:
	{
	  unk = false;
	  
	  emit guildMOTD((const guildMOTDStruct*)data, len, dir);
	  
	  break;
	}
	
      case OP_Death: // old NewCorpseCode:
	{
	  unk = ! ValidatePayload(OP_Death, newCorpseStruct);

	  emit killSpawn((const newCorpseStruct*) data, len, dir);
	  
	  break;
	} /* end CorpseCode */
	
      case OP_DeleteSpawn: // old DeleteSpawnCode:
	{
	  unk = ! ValidatePayload(OP_DeleteSpawn, deleteSpawnStruct);
	  
	  emit deleteSpawn((const deleteSpawnStruct*)data, len, dir);
	  
	  break;
	}
	
      case OP_ItemLinkResponse: // old ItemInfoCode:
	{
	  unk = false;
	  
	  if (dir == DIR_SERVER)
	    emit itemInfo((const itemInfoStruct*)data, len, dir);
	  else
	    emit itemInfoReq((const itemInfoReqStruct*)data, len, dir);
	}
	
      case OP_ItemPacket: // old ItemCode:
	{
	  unk = false;
	  
	  if (dir == DIR_SERVER)
	    emit item((const itemPacketStruct*)data, len, dir);
	  
	  break;
	}
	
      case OP_ItemPlayerPacket:
	{
	  unk = false;
	  
	  if (dir == DIR_SERVER)
	    emit playerItem((const char*)data, len, dir);
	  
	  break;
	}

      case OP_NewSpawn: // old NewSpawnCode:
	{
	  unk = ! ValidatePayload(OP_NewSpawn, newSpawnStruct);
	  
	  emit newSpawn((const newSpawnStruct*)data, len, dir);
	  
	  break;
	}
	
      case OP_ItemTextFile: // old BookTextCode:
	{
	  unk = false;
	  
	  printf("BOOK: '%s'\n", ((const bookTextStruct *)data)->text);
	  emit bookText((const bookTextStruct*)data, len, dir);
	  
	  break;
        }
	
      case OP_MoneyOnCorpse: // old MoneyOnCorpseCode:
	{
	  unk = ! ValidatePayload(OP_MoneyOnCorpse, moneyOnCorpseStruct);
	  
	  emit moneyOnCorpse((const moneyOnCorpseStruct*)data, len, dir);
	  
	  break;
	} /* end MoneyOnCorpseCode */
	
      case OP_RandomReply: // old RandomCode:
        {
	  unk = ! ValidatePayload(OP_RandomReply, randomStruct);
	  
	  emit random((const randomStruct*)data, len, dir);
	  
	  break;
        }
	
      case OP_RandomReq: // RandomReqCode:
        {
	  unk = ! ValidatePayload(OP_RandomReq, randomReqStruct);
	  
	  emit random((const randomReqStruct*)data, len, dir);
	  
	  break;
        }
	
      case OP_Emote: // old EmoteEmoteTextCode:
        {
	  unk = false;
	  
	  emit emoteText((const emoteTextStruct*)data, len, dir);
	  
	  break;
        }
	
      case OP_CorpseLocResponse: // old CorpseLocCode:
        {
	  unk = ! ValidatePayload(OP_CorpseLocResponse, corpseLocStruct);
	  
	  emit corpseLoc((const corpseLocStruct*)data, len, dir);
	  
	  break;
        }
	
      case OP_InspectAnswer: // old InspectDataCode:
        {
	  unk = ! ValidatePayload(OP_InspectAnswer, inspectDataStruct);
	  
	  emit inspectData((const inspectDataStruct *)data, len, dir);
	  
	  break;
        }
	
      case OP_HPUpdate: // old NpcHpUpdateCode:
	{
	  unk = ! ValidatePayload(OP_HPUpdate, hpNpcUpdateStruct);
	  
	  emit updateNpcHP((const hpNpcUpdateStruct*)data, len, dir);
	  
	  break;
	}
	
      case SPMesgCode:
        {
	  unk = false;
	  
	  emit spMessage((const spMesgStruct *)data, len, dir);
	  
	  break;
        }
	
      case OP_MemorizeSpell: // old MemSpellCode:
        {
	  unk = ! ValidatePayload(OP_MemorizeSpell, memSpellStruct);
	  
	  emit handleSpell((const memSpellStruct*)data, len, dir);
	  
	  break;
        }
	
      case OP_BeginCast: // old BeginCastCode
        {
	  unk = ! ValidatePayload(OP_BeginCast, beginCastStruct);
	  
	  emit beginCast((const beginCastStruct*)data, len, dir);
	  
	  break;
        }
	
      case OP_CastSpell: // old StartCastCode:
        {
	  unk = ! ValidatePayload(OP_CastSpell, startCastStruct);
	  
	  emit startCast((const startCastStruct*)data, len, dir);
	  
	  break;
        }
	
      case OP_BuffFadeMsg: // old SpellFadeCode:
	{
	  unk = false;
	  
	  emit spellFaded((const spellFadedStruct*)data, len, dir);
	  
	  break;
	}
	
      case OP_ExpUpdate: // old ExpUpdateCode:
        {
	  unk = ! ValidatePayload(OP_ExpUpdate, expUpdateStruct);
	  
	  emit updateExp((const expUpdateStruct*)data, len, dir);
	  
	  break;
        }
	
      case OP_LevelUpdate: // old LevelUpUpdateCode:
        {
	  unk = ! ValidatePayload(OP_LevelUpdate, levelUpUpdateStruct);
	  
	  emit updateLevel((const levelUpUpdateStruct *)data, len, dir);
	  
	  break;
        }
	
      case OP_SkillUpdate: // old SkillIncCode
        {
	  unk = ! ValidatePayload(OP_SkillUpdate, skillIncStruct);
	  
	  emit increaseSkill((const skillIncStruct *)data, len, dir);
	  
	  break;
        }
	
      case OP_MoveDoor: // old DoorOpenCode:
        {
	  unk = false;
	  
	  emit doorOpen(data, len, dir);
	  
	  break;
        }
	
      case OP_Illusion: // old IllusionCode:
        {
	  unk = false;
	  
	  emit illusion(data, len, dir);
	  
	  break;
        }
	
      case OP_ZoneChange: // old ZoneChangeCode:
        {
	  unk = ! ValidatePayload(OP_ZoneChange, zoneChangeStruct);
	  
	  // in the process of zoning, server hasn't switched yet.
	  
	  emit zoneChange((const zoneChangeStruct*)data, len, dir);
	  break;
        }
	
      case OP_ZoneEntry: // old ZoneEntryCode:
        {
	  // We're only interested in the server version
	  
	  if (dir == DIR_CLIENT)
	  {
	    unk = ! ValidatePayload(OP_ZoneEntry, ClientZoneEntryStruct);
	    emit zoneEntry((const ClientZoneEntryStruct*)data, len, dir);
	    break;
	  }
	  
	  unk = ! ValidatePayload(OP_ZoneEntry, ServerZoneEntryStruct);
	  
	  emit zoneEntry((const ServerZoneEntryStruct*)data, len, dir);
	  
	  break;
        } /* end ZoneEntryCode */
	
      case OP_NewZone: // old - NewZoneCode:
        {
	  unk = ! ValidatePayload(OP_NewZone, newZoneStruct);
	  
	  emit zoneNew((const newZoneStruct*)data, len, dir);
	  
	  if (m_vPacket)
	    printf("New Zone at byte: %ld\n", m_vPacket->FilePos());
	  
	  break;
        }
	
      case OP_PlayerProfile:	// Character Profile server to client - old CharProfileCode
	{
	  unk = false;
	  
	  ValidatePayload(OP_PlayerProfile, charProfileStruct);
	  
	  emit backfillPlayer((const charProfileStruct*)data, len, DIR_SERVER);
	  
	  break;
	}
	
      case OP_ZoneSpawns: // ZoneSpawnsCode:
	{
	  unk = false; 
	  
	  emit zoneSpawns((const zoneSpawnsStruct*)data, len, dir);
	  
	  break;
	}
	
      case OP_TimeOfDay: // old TimeOfDayCode:
	{
	  unk = ! ValidatePayload(OP_TimeOfDay, timeOfDayStruct);
	  
	  emit timeOfDay((const timeOfDayStruct*)data, len, dir);
	  
	  break;
	}
	
      case WearChangeCode:
        {
	  unk = ! ValidatePayload(WearChangeCode, wearChangeStruct);
	  
	  emit spawnWearingUpdate ((const wearChangeStruct*)data, len, dir);
	  
	  break;
        }
	
      case OP_Action:
	{
	  unk = ! ValidatePayload(OP_Action, actionStruct);
	  
	  emit action((const actionStruct*)data, len, dir);
	  
	  break;
	}
	
      case OP_CastBuff: // old ActionCode:
        {
	  unk = false;
	  
	  emit action2Message ((const action2Struct *)data, len, dir);
	  
	  break;
        }
	
      case OP_Stamina: /// old StaminaCode:
        {
	  unk = ! ValidatePayload(OP_Stamina, staminaStruct);
	  
	  emit updateStamina((const staminaStruct *)data, len, dir);
	  
	  break;
        }
	
      case OP_GroundSpawn: // old MakeDropCode:
        {
#ifdef PACKET_PAYLOAD_SIZE_DIAG
	  if ((len != sizeof(makeDropStruct)) &&
	      (len != 0))
	    {
	      fprintf(stderr, "WARNING: OP_GroundSpawn (%04x) (dataLen: %d != sizeof(makeDropStruct):%d or 0)\n",
		      OP_GroundSpawn, len, 
		      sizeof(makeDropStruct));
	      unk = true;
	    }
	  else
	    unk = false;
#else
	  unk = false;
#endif
	  
	  emit newGroundItem((const makeDropStruct*)data, len, dir);
	  
	  break;
        }
	
      case OP_ClickObject: // Old RemDropCode:
        {
	  unk = ! ValidatePayload(OP_ClickObject, remDropStruct);
	  
	  emit removeGroundItem((const remDropStruct *)data, len, dir);
	  
	  break;
        }
	
      case OP_ShopRequest: // old OpenVendorCode:
        {
	  unk = false;
	  
	  emit openVendor(data, len, dir);
	  
	  break;
        }
	
      case OP_ShopEnd: // old CloseVendorCode:
        {
	  unk = false;
	  
	  emit closeVendor(data, len, dir);
	  
	  break;
        }
	
      case OP_GMTraining: // old OpenGMCode:
        {
	  unk = false;
	  
	  emit openGM(data, len, dir);
	  
	  break;
        }
	
      case OP_GMEndTrainingResponse: // old CloseGMCode:
        {
	  unk = false;
	  
	  emit closeGM(data, len, dir);
	  
	  break;
        }
	
      case OP_Consider: // old ConsiderCode:
        {
	  unk = false;
	  
	  ValidatePayload(OP_Consider, considerStruct);
	  
	  emit consMessage((const considerStruct*)data, len, dir);
	  
	  break;
        }
	
      case OP_TargetMouse: // old ClientTargetCode:
        {
	  unk = ! ValidatePayload(OP_TargetMouse, clientTargetStruct);
	  
	  emit clientTarget((const clientTargetStruct*) data, len, dir);
	  
	  break;
        }
	
      case OP_SpawnDoor: // old DoorSpawnsCode:
        {
	  unk = false;
	  
#ifdef PACKET_PAYLOAD_SIZE_DIAG
	  // verify size
	  
	  if (len % sizeof(doorStruct) != 0)
          {
	    printf("WARNING: OP_SpawnDoor (%.04x) (dataLen:%d "
		   "%% sizeof(doorStruct):%d) != 0!\n", 
		   OP_SpawnDoor, len, sizeof(doorStruct));
	    
	    unk = true;
	    break;
            }
#endif
	  int nDoors = len / sizeof(doorStruct);
	  const DoorSpawnsStruct *doorsStruct = (const DoorSpawnsStruct *)data;
	  for (int i = 0; i < nDoors; i++) {
	    emit newDoorSpawn(&doorsStruct->doors[i], len, dir);
	  }
	  
	  emit newDoorSpawns(doorsStruct, len, dir);
	  
	  break;
        }

      case OP_Buff: // old BuffDropCode: 
	{
	  unk = ! ValidatePayload(OP_Buff, buffStruct);
	  
	  emit buff((const buffStruct*)data, len, dir);
	  
	  // this is the server 'buff fading' AND the client 'cancel buff'
	  break;
	}
	
      case OP_Logout: // no contents
	{
	  unk = false;
	  
	  emit logOut(data, len, dir);
	  
	  break;
	}
	
      case OP_SendZonePoints:
	{
	  unk = false;
#ifdef PACKET_PAYLOAD_SIZE_DIAG
	  const zonePointsStruct* zp = (const zonePointsStruct*)data;
	  // verify size
	  if (((len - sizeof(zp->count) - sizeof(zp->unknown0xxx)) 
	       % sizeof(zonePointStruct)) != 0)
	  {
	    fprintf(stderr, "WARNING: OP_SendZonePoints (%04x) (dataLen: %d %% sizeof(zonePointStruct):%d) != 0!\n",
		    OP_SendZonePoints, len, sizeof(zonePointStruct));
	    unk = true;
	    break;
	  }
#endif

	  emit zonePoints((const zonePointsStruct*)data, len, dir);

	  break;
	}
	
      case OP_GuildMemberList: // old GuildMemberListCode
	{
	  unk = false;
	  break;
	}
	
      case OP_GuildMemberUpdate: // old GuildMemberUpdateCode:
	{
	  unk = false;
	  break;
	}
	
      case OP_SetRunMode: // old cRunToggleCode:
	{
	  //unk = ! ValidatePayload(cRunToggleCode, cRunToggleStruct);
	  //emit cRunToggle((const cRunToggleStruct*)data, len, dir);
	  unk = false;
	  break;
	}
	
      case OP_Jump: // old cJumpCode:
	{
	  //no data
	  unk = false;
	  break;
	}
	
      case OP_Camp: // old cStartCampingCode:
	{
	  //no data
	  unk = false;
	  break;
	}
	
      case OP_SenseHeading: // old cSenseHeadingCode:
	{
	  //no data
	  unk = false;
	  break;
	}
	
      case OP_Forage: // old ForageCode:
	{
	  //no data
	  unk = false;
	  break;
	}

#if 0 // ZBTEMP	: If we don't bother setting unk, don't bother processing
      case OP_ConsiderCorpse: //unknown contents // old cConCorpseCode:  
	{
	  //unk = ! ValidatePayload(cConCorpseCode, cConCorpseStruct);
	  //emit cConCorpse((const cConCorpseStruct*)data, len, dir);
	  break;
	}
	
      case OP_LootRequest:  //unknown contents - old cLootCorpseCode
	{
	  //unk = ! ValidatePayload(cLootCorpseCode, cLootCorpseStruct);
	  //emit cLootCorpse((const cLootCorpseStruct*)data, len, dir);
	  break;
	}
	
      case OP_EndLootRequest:  //unknown contents - old cDoneLootingCode
	{
	  //unk = ! ValidatePayload(cDoneLootingCode, cDoneLootingStruct);
	  //emit cDoneLooting((const cDoneLootingStruct*)data, len, dir);
	  break;
	}
	
      case OP_LootComplete:  //unknown contents - old sDoneLootingCode
	{
	  //unk = ! ValidatePayload(sDoneLootingCode, sDoneLootingStruct);
	  //emit sDoneLooting((const sDoneLootingStruct*)data, len, dir);
	  break;
	}
	
      case OP_WhoAllRequest:  //unknown contents - old WhoAllReqCode
	{
	  //unk = ! ValidatePayload(cWhoAllCode, cWhoAllStruct);
	  //emit cWhoAll((const cWhoAllStruct*)data, len, dir);
	  break;
	}
	
      case OP_WhoAllResponse: // old sWhoAllOutputCode: unknown contents
	{
	  //unk = ! ValidatePayload(sWhoAllOutputCode, sWhoAllOutputStruct);
	  //emit sWhoAllOutput((const sWhoAllOutputStruct*)data, len, dir);
	  break;
	}
      
      case OP_ShopPlayerBuy:  //unknown contents - old BuyItemCode
	{
	  //unk = ! ValidatePayload(xBuyItemCode, xBuyItemStruct);
	  //emit xBuyItem((const xBuyItemStruct*)data, len, dir);
	  //both the client command and the server acknowledgement when buying
	  break;
	}
#endif // ZBTEMP

#if 0 // ZBTEMP: OPCode Graveyard
      case CastOnCode:
        {
	  unk = false;
	  
	  emit castOn((castOnStruct*)data, len, dir);
	  
	  break;
        }
	
      case ManaDecrementCode:
        {
	  unk = ! ValidatePayload(ManaDecrementCode, manaDecrementStruct);
	  
	  emit manaChange((struct manaDecrementStruct *)data, len, dir);
	  
	  break;
        }
	
      case BadCastCode:
        {
	  unk = false; //! ValidatePayload(BadCastCode, badCastStruct);
	  
	  emit interruptSpellCast((const badCastStruct*)data, len, dir);
	  
	  break;
        }
	
      case SysMsgCode:
        {
	  unk = false;
	  
	  emit systemMessage((const sysMsgStruct*)data, len, dir);
	  
	  break;
        }
	
      case AltExpUpdateCode:
        {
	  unk = ! ValidatePayload(AltExpUpdateCode, altExpUpdateStruct);
	  
	  emit updateAltExp((const altExpUpdateStruct*)data, len, dir);
	  
	  break;
        }
	
      case Attack2Code:
        {
	  unk = false;
	  
	  emit attack2Hand1 ((const attack2Struct *)data, len, dir);
	  
	  break;
        }
	
      case NewGuildInZoneCode:
        {
	  unk = false;
	  
	  break;
        }
	
      case MoneyUpdateCode:
        {  
	  unk = false;
	  
	  emit moneyUpdate((const moneyUpdateStruct*)data, len, dir);
	  
	  break;
        }
	
      case MoneyThingCode:
        {
            unk = false;
	    
	    emit moneyThing((const moneyThingStruct*)data, len, dir);
	    
            break;
        }
	
      case BindWoundCode:
        {
	  unk = false;
	  
	  emit bindWound((bindWoundStruct*)data, len, dir);
	  
	  break;
        }
	
      case GroupInfoCode:
        {
	  // Too much still unknown.
	  
	  unk = ! ValidatePayload(GroupInfoCode, groupMemberStruct);
	  
	  emit groupInfo((const groupMemberStruct*)data, len, dir);
	  
	  break;
        }
	
      case GroupInviteCode:
        {
	  unk = ! ValidatePayload(GroupInviteCode, groupInviteStruct);
	  
	  emit groupInvite((const groupInviteStruct*)data, len, dir);
	  
	  break;
        }
	
      case GroupDeclineCode:
        {
	  unk = ! ValidatePayload(GroupDeclineCode, groupDeclineStruct);
	  
	  emit groupDecline((const groupDeclineStruct*)data, len, dir);
	  
	  break;
        }
	
      case GroupAcceptCode:
        {
	  unk = ! ValidatePayload(GroupAcceptCode, groupAcceptStruct);
	  
	  emit groupAccept((const groupAcceptStruct*)data, len, dir);
	  
	  break;
        }
	
      case GroupDeleteCode:
        {
	  unk = ! ValidatePayload(GroupDeleteCode, groupDeleteStruct);
	  
	  emit groupDelete((const groupDeleteStruct*)data, len, dir);
	  
	  break;
        }
	
      case CharUpdateCode:
        {
	  break;
        }
	
      case cChatFiltersCode:
	{
	  //unk = ! ValidatePayload(cChatFiltersCode, cChatFiltersStruct);
	  //emit cChatFilters((const cChatFiltersStruct*)data, len, dir);
	  unk = false;
	  break;
	}
	
      case cOpenSpellBookCode:
	{
	  //unk = ! ValidatePayload(cOpenSpellBookCode, cOpenSpellBookStruct);
	  //emit cOpenSpellBook((const cOpenSpellBookStruct*)data, len, dir);
	  unk = false;
	  break;
	}
	
      case OP_SwapSpell: // old TradeSpellBookSlotsCode:
	{
	  unk = ! ValidatePayload(OP_SwapSpell, tradeSpellBookSlotsStruct);
	  emit tradeSpellBookSlots((const tradeSpellBookSlotsStruct*)data, len, dir);
	  break;
	}
	
      case sSpellFizzleRegainCode:  //unknown contents, also comes when you Forage
	{
	  //unk = ! ValidatePayload(sSpellFizzleRegainCode, sSpellFizzleRegainStruct);
	  //emit sSpellFizzleRegain((const sSpellFizzleRegainStruct*)data, len, dir);
	  break;
	}
	
      case sSpellInterruptedCode:  //unknown contents
	{
	  //unk = ! ValidatePayload(sSpellInterruptedCode, sSpellInterruptedStruct);
	  //emit sSpellInterrupted((const sSpellInterruptedStruct*)data, len, dir);
	  break;
	}
	
      case cHideCode:
	{
	  //no data
	  unk = false;
	  break;
	}
	
      case cSneakCode:
	{
	  //no data
	  unk = false;
	  break;
	}
	
      case cTrackCode:
	{
	  //no data
	  unk = false;
	  break;
	}
#endif // ZBTEMP // Currently dead opcodes
	
      default:
        {
        }
      } /* end switch(opCode) */

    emit decodedZonePacket(data, len, dir, opCode, unk);
}
Esempio n. 29
0
void GBMapView::saveBMP(const char *name)
{
  u8 writeBuffer[1024 * 3];

  FILE *fp = fopen(name,"wb");

  if(!fp) {
    systemMessage(MSG_ERROR_CREATING_FILE, "Error creating file %s", name);
    return;
  }

  struct {
    u8 ident[2];
    u8 filesize[4];
    u8 reserved[4];
    u8 dataoffset[4];
    u8 headersize[4];
    u8 width[4];
    u8 height[4];
    u8 planes[2];
    u8 bitsperpixel[2];
    u8 compression[4];
    u8 datasize[4];
    u8 hres[4];
    u8 vres[4];
    u8 colors[4];
    u8 importantcolors[4];
    u8 pad[2];
  } bmpheader;
  memset(&bmpheader, 0, sizeof(bmpheader));

  bmpheader.ident[0] = 'B';
  bmpheader.ident[1] = 'M';

  u32 fsz = sizeof(bmpheader) + w*h*3;
  utilPutDword(bmpheader.filesize, fsz);
  utilPutDword(bmpheader.dataoffset, 0x38);
  utilPutDword(bmpheader.headersize, 0x28);
  utilPutDword(bmpheader.width, w);
  utilPutDword(bmpheader.height, h);
  utilPutDword(bmpheader.planes, 1);
  utilPutDword(bmpheader.bitsperpixel, 24);
  utilPutDword(bmpheader.datasize, 3*w*h);

  fwrite(&bmpheader, 1, sizeof(bmpheader), fp);

  u8 *b = writeBuffer;

  int sizeX = w;
  int sizeY = h;

  u8 *pixU8 = (u8 *)data+3*w*(h-1);
  for(int y = 0; y < sizeY; y++) {
    for(int x = 0; x < sizeX; x++) {
      *b++ = *pixU8++; // B
      *b++ = *pixU8++; // G
      *b++ = *pixU8++; // R
    }
    pixU8 -= 2*3*w;
    fwrite(writeBuffer, 1, 3*w, fp);

    b = writeBuffer;
  }

  fclose(fp);
}
Esempio n. 30
0
int winVideoModeSelect(CWnd *pWnd, GUID **guid)
{
#ifdef _AFXDLL
  HINSTANCE h = AfxLoadLibrary("ddraw.dll");
#else
  HMODULE h = LoadLibrary( _T("ddraw.dll") );
#endif
 
  // If ddraw.dll doesn't exist in the search path,
  // then DirectX probably isn't installed, so fail.
  if (!h)
    return -1;
  
  gDriverCnt = 0;
  
  // Note that you must know which version of the
  // function to retrieve (see the following text).
  // For this example, we use the ANSI version.
  LPDIRECTDRAWENUMERATEEX lpDDEnumEx;
  lpDDEnumEx = (LPDIRECTDRAWENUMERATEEX)
    GetProcAddress(h,"DirectDrawEnumerateExA");
 
  // If the function is there, call it to enumerate all display 
  // devices attached to the desktop, and any non-display DirectDraw
  // devices.
  if (lpDDEnumEx)
    lpDDEnumEx(DDEnumCallbackEx, NULL, 
               DDENUM_ATTACHEDSECONDARYDEVICES |
               DDENUM_NONDISPLAYDEVICES 
               );
  else {
    /*
     * We must be running on an old version of DirectDraw.
     * Therefore MultiMon isn't supported. Fall back on
     * DirectDrawEnumerate to enumerate standard devices on a 
     * single-monitor system.
     */
    BOOL (WINAPI *lpDDEnum)(LPDDENUMCALLBACK, LPVOID);
    
    lpDDEnum = (BOOL (WINAPI *)(LPDDENUMCALLBACK, LPVOID))
      GetProcAddress(h, "DirectDrawEnumerateA");
    if(lpDDEnum)
      lpDDEnum(DDEnumCallback,NULL);
    
    /* Note that it could be handy to let the OldCallback function
     * be a wrapper for a DDEnumCallbackEx. 
     * 
     * Such a function would look like:
     *    BOOL FAR PASCAL OldCallback(GUID FAR *lpGUID,
     *                                LPSTR pDesc,
     *                                LPSTR pName,
     *                                LPVOID pContext)
     *    {
     *         return Callback(lpGUID,pDesc,pName,pContext,NULL);
     *    }
     */
  }

  int selected = 0;

  if(gDriverCnt > 1) {
    VideoDriverSelect d(pWnd);

    INT_PTR selected = d.DoModal();

    if(selected == -1) {
#ifdef _AFXDLL
      AfxFreeLibrary( h );
#else
      FreeLibrary( h );
#endif
      
      return -1;
    }
  }

  HRESULT (WINAPI *DDrawCreateEx)(GUID *,LPVOID *,REFIID,IUnknown *);  
  DDrawCreateEx = (HRESULT (WINAPI *)(GUID *,LPVOID *,REFIID,IUnknown *))
    GetProcAddress(h, "DirectDrawCreateEx");

  LPDIRECTDRAW7 ddraw = NULL;
  if(DDrawCreateEx) {
    HRESULT hret = DDrawCreateEx(Drivers[selected].pGUID,
                                 (void **)&ddraw,
                                 IID_IDirectDraw7,
                                 NULL);
    if(hret != DD_OK) {
      systemMessage(0, "Error during DirectDrawCreateEx: %08x", hret);
#ifdef _AFXDLL
      AfxFreeLibrary( h );
#else
      FreeLibrary( h );
#endif
      return -1;
    }
  } else {
    // should not happen....
    systemMessage(0, "Error getting DirectDrawCreateEx");
#ifdef _AFXDLL
    AfxFreeLibrary( h );
#else
    FreeLibrary( h );
#endif
    return -1;
  }  
  
  VideoMode dlg(ddraw, pWnd);

  INT_PTR res = dlg.DoModal();

  if(res != -1) {
    *guid = Drivers[selected].pGUID;
  }
  ddraw->Release();
  ddraw = NULL;

  // If the library was loaded by calling LoadLibrary(),
  // then you must use FreeLibrary() to let go of it.
#ifdef _AFXDLL
  AfxFreeLibrary( h );
#else
  FreeLibrary( h );
#endif

  return (int)res;
}