code stringlengths 1 2.06M | language stringclasses 1 value |
|---|---|
#ifndef POPUP_MAIN_DIALOG_H
#define POPUP_MAIN_DIALOG_H
#include "MyTabCtrl.h"
#include "PopupClientInfo.h"
#include "PopupMessageInfo.h"
class CpopupDialog;
// PopupMainDialog dialog
class PopupMainDialog : public CDialog
{
DECLARE_DYNAMIC(PopupMainDialog)
public:
PopupMainDialog(CWnd* pParent = NULL); // standard constructor
virtual ~PopupMainDialog();
void clearClients();
void updateClientStatus(const PopupClientInfo & p_client);
void appendHistory(const PopupMessageInfo & p_message,
bool p_received = true);
// Dialog Data
enum { IDD = IDD_TAB_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
virtual BOOL OnInitDialog();
virtual void OnOK();
DECLARE_MESSAGE_MAP()
CpopupDlg *m_parent;
public:
CMyTabCtrl m_tabCtrl;
};
#endif | C++ |
#if !defined(AFX_MYTABCTRL_H__F3E8650F_019C_479F_9E0F_60FE1181F49F__INCLUDED_)
#define AFX_MYTABCTRL_H__F3E8650F_019C_479F_9E0F_60FE1181F49F__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// MyTabCtrl.h : header file
//
class CSenderDialog;
class PopupHistoryDialog;
class PopupPropertiesDlg;
/////////////////////////////////////////////////////////////////////////////
// CMyTabCtrl window
class CMyTabCtrl : public CTabCtrl
{
// Construction
public:
typedef enum {
POPUP_SENDER_TAB,
POPUP_HISTORY_TAB,
POPUP_PPTIES_TAB,
POPUP_NB_TABS
};
CMyTabCtrl();
CDialog *m_tabPages[POPUP_NB_TABS];
int m_tabCurrent;
int m_nNumberOfPages;
CSenderDialog *m_senderDialog;
PopupHistoryDialog *m_historyDialog;
PopupPropertiesDlg *m_pptiesDialog;
// Attributes
public:
// Operations
public:
void Init();
void SetRectangle();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CMyTabCtrl)
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CMyTabCtrl();
virtual BOOL btnOkClicked();
void setActiveTab(int p_tabId);
// Generated message map functions
protected:
//{{AFX_MSG(CMyTabCtrl)
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_MYTABCTRL_H__F3E8650F_019C_479F_9E0F_60FE1181F49F__INCLUDED_)
| C++ |
//this file is part of ePopup
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#pragma once
#include "popup.h"
#include "Options.h"
struct Options;
/////////////////////////////////////////////////////////////////////////////////////////
///PopupServerThread
class PopupServerThread : public CWinThread
{
public:
DECLARE_DYNCREATE(PopupServerThread)
protected:
PopupServerThread() {}
public:
virtual BOOL InitInstance();
virtual int Run();
void kill();
};
| C++ |
#ifndef C_SENDER_DIALOG_H
#define C_SENDER_DIALOG_H
#pragma once
#include "afxwin.h"
#include "afxcmn.h"
#include "PopupMessageInfo.h"
#include "PopupClientInfo.h"
#include "resource.h"
class CpopupApp;
// CSenderDialog dialog
class CSenderDialog : public CDialog
{
DECLARE_DYNAMIC(CSenderDialog)
public:
CSenderDialog(CWnd* pParent = NULL); // standard constructor
virtual ~CSenderDialog();
// Dialog Data
enum { IDD = IDD_DIALOG_SENDEVENT };
virtual BOOL validateDialog();
void clearClients();
void updateClientStatus(const PopupClientInfo & p_client);
bool SetFromMessageInfo(const PopupMessageInfo & p_message, bool _replyAll);
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
virtual BOOL OnInitDialog( );
virtual void OnOK( );
bool validateData(CString & errMsg, PopupMessageInfo & p_msg);
CpopupApp *m_app;
// Event attributes
CString m_popupResourceName;
CString m_popupTarget;
CString m_popupImageFile;
CString m_popupSoundFile;
CString m_popupVideoFile;
bool m_modal;
bool m_raw;
CImageList m_imageList;
CButton m_chkModal;
CComboBox m_cbImageFile;
CComboBox m_cbSoundFile;
CComboBox m_cbVideoFile;
CListCtrl m_lcTargetName;
CListCtrl m_lcPopupResourceName;
BOOL m_chkKill;
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnBnClickedCheckModal();
afx_msg void OnBnClickedButtonBrowseImage();
afx_msg void OnBnClickedButtonBrowseSound();
afx_msg void OnBnClickedButtonBrowseVideo();
afx_msg void OnLvnGetdispinfoListTarget(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnLvnItemchangedListResource(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnLvnGetdispinfoListResource(NMHDR *pNMHDR, LRESULT *pResult);
CString m_message;
CEdit m_editMessage;
friend class CMyTabCtrl;
public:
BOOL m_rawData;
CButton m_chkRaw;
afx_msg void OnBnClickedCheckRawData();
afx_msg void OnBnClickedButtonClear();
};
#endif | C++ |
#ifndef RESOURCE_ENTRY_H
#define RESOURCE_ENTRY_H
#include "stdafx.h"
#include <CString>
#include <vector>
//===============================================================
// Resource entry representation (images and sounds)
//===============================================================
struct ResourceEntry
{
std::vector<CString> m_imagesPath;
std::vector<CString> m_soundsPath;
std::vector<CString> m_videosPath;
int m_nbTimesShown;
ResourceEntry() : m_nbTimesShown(0) {}
virtual ~ResourceEntry() {}
LPCTSTR getRandomImage();
LPCTSTR getRandomSound();
LPCTSTR getRandomVideo();
bool isSoundNotAvailable();
void clear();
};
#endif // ResourceEntry
| C++ |
//this file is part of ePopup
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#pragma once
#include "popup.h"
#include "Options.h"
#include "PopupClient.h"
class CpopupApp;
class CpopupDlg;
struct Options;
/////////////////////////////////////////////////////////////////////////////////////////
///PopupClientThread
class PopupClientThread : public CWinThread
{
public:
DECLARE_DYNCREATE(PopupClientThread)
protected:
PopupClientThread();
CpopupApp *m_popupapp;
CpopupDlg *m_popupdlg;
Options &m_options;
CpopupApp::PopupResources &m_resources;
Logger &m_logger;
PopupClient *m_popupclient;
public:
virtual int Run();
virtual BOOL InitInstance();
void kill();
};
| C++ |
//this file is part of ePopup
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#pragma once
#include "popup.h"
class CpopupApp;
class CpopupDlg;
/////////////////////////////////////////////////////////////////////////////////////////
///PopupEventThread
class PopupEventThread : public CWinThread
{
public:
DECLARE_DYNCREATE(PopupEventThread)
protected:
PopupEventThread();
CpopupApp *m_popupapp;
CpopupDlg *m_popupdlg;
public:
virtual int Run();
virtual BOOL InitInstance();
};
| C++ |
//this file is part of ePopup
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#pragma once
#include <atlenc.h>
bool IsValidEd2kString(LPCTSTR psz);
bool IsValidEd2kStringA(LPCSTR psz);
__inline bool NeedUTF8String(LPCWSTR pwsz)
{
while (*pwsz != L'\0')
{
if (*pwsz >= 0x100U)
return true;
pwsz++;
}
return false;
}
//#define ED2KCODEPAGE 28591 // ISO 8859-1 Latin I
//
//void CreateBOMUTF8String(const CStringW& rwstrUnicode, CStringA& rstrUTF8);
//
//__inline void OptCreateED2KUTF8String(bool bOptUTF8, const CStringW& rwstr, CStringA& rstrUTF8)
//{
// if (bOptUTF8 && NeedUTF8String(rwstr))
// {
// CreateBOMUTF8String(rwstr, rstrUTF8);
// }
// else
// {
// // backward compatibility: use local codepage
// UINT cp = bOptUTF8 ? ED2KCODEPAGE : _AtlGetConversionACP();
// int iSize = WideCharToMultiByte(cp, 0, rwstr, -1, NULL, 0, NULL, NULL);
// if (iSize >= 1)
// {
// int iChars = iSize - 1;
// LPSTR pszUTF8 = rstrUTF8.GetBuffer(iChars);
// WideCharToMultiByte(cp, 0, rwstr, -1, pszUTF8, iSize, NULL, NULL);
// rstrUTF8.ReleaseBuffer(iChars);
// }
// }
//}
CStringA wc2utf8(const CStringW& rwstr);
CString OptUtf8ToStr(const CStringA& rastr);
CString OptUtf8ToStr(LPCSTR psz, int iLen);
CString OptUtf8ToStr(const CStringW& rwstr);
CStringA StrToUtf8(const CString& rstr);
CString EncodeUrlUtf8(const CString& rstr);
int utf8towc(LPCSTR pcUtf8, UINT uUtf8Size, LPWSTR pwc, UINT uWideCharSize);
int ByteStreamToWideChar(LPCSTR pcUtf8, UINT uUtf8Size, LPWSTR pwc, UINT uWideCharSize);
CStringW DecodeDoubleEncodedUtf8(LPCWSTR pszFileName);
#define SHORT_ED2K_STR 256
#define SHORT_RAW_ED2K_MB_STR (SHORT_ED2K_STR*2)
#define SHORT_RAW_ED2K_UTF8_STR (SHORT_ED2K_STR*4)
///////////////////////////////////////////////////////////////////////////////
// TUnicodeToUTF8
template< int t_nBufferLength = SHORT_ED2K_STR*4 >
class TUnicodeToUTF8
{
public:
TUnicodeToUTF8(const CStringW& rwstr)
{
int iBuffSize;
int iMaxEncodedStrSize = rwstr.GetLength()*4;
if (iMaxEncodedStrSize > t_nBufferLength)
{
iBuffSize = iMaxEncodedStrSize;
m_psz = new char[iBuffSize];
}
else
{
iBuffSize = ARRSIZE(m_acBuff);
m_psz = m_acBuff;
}
m_iChars = AtlUnicodeToUTF8(rwstr, rwstr.GetLength(), m_psz, iBuffSize);
ASSERT( m_iChars > 0 || rwstr.GetLength() == 0 );
}
TUnicodeToUTF8(LPCWSTR pwsz, int iLength = -1)
{
if (iLength == -1)
iLength = wcslen(pwsz);
int iBuffSize;
int iMaxEncodedStrSize = iLength*4;
if (iMaxEncodedStrSize > t_nBufferLength)
{
iBuffSize = iMaxEncodedStrSize;
m_psz = new char[iBuffSize];
}
else
{
iBuffSize = ARRSIZE(m_acBuff);
m_psz = m_acBuff;
}
m_iChars = AtlUnicodeToUTF8(pwsz, iLength, m_psz, iBuffSize);
ASSERT( m_iChars > 0 || iLength == 0 );
}
~TUnicodeToUTF8()
{
if (m_psz != m_acBuff)
delete[] m_psz;
}
operator LPCSTR() const
{
return m_psz;
}
int GetLength() const
{
return m_iChars;
}
private:
int m_iChars;
LPSTR m_psz;
char m_acBuff[t_nBufferLength];
};
typedef TUnicodeToUTF8<> CUnicodeToUTF8;
///////////////////////////////////////////////////////////////////////////////
// TUnicodeToBOMUTF8
template< int t_nBufferLength = SHORT_ED2K_STR*4 >
class TUnicodeToBOMUTF8
{
public:
TUnicodeToBOMUTF8(const CStringW& rwstr)
{
int iBuffSize;
int iMaxEncodedStrSize = 3 + rwstr.GetLength()*4;
if (iMaxEncodedStrSize > t_nBufferLength)
{
iBuffSize = iMaxEncodedStrSize;
m_psz = new char[iBuffSize];
}
else
{
iBuffSize = ARRSIZE(m_acBuff);
m_psz = m_acBuff;
}
m_psz[0] = 0xEFU;
m_psz[1] = 0xBBU;
m_psz[2] = 0xBFU;
m_iChars = 3 + AtlUnicodeToUTF8(rwstr, rwstr.GetLength(), m_psz + 3, iBuffSize - 3);
ASSERT( m_iChars > 3 || rwstr.GetLength() == 0 );
}
~TUnicodeToBOMUTF8()
{
if (m_psz != m_acBuff)
delete[] m_psz;
}
operator LPCSTR() const
{
return m_psz;
}
int GetLength() const
{
return m_iChars;
}
private:
int m_iChars;
LPSTR m_psz;
char m_acBuff[t_nBufferLength];
};
typedef TUnicodeToBOMUTF8<> CUnicodeToBOMUTF8;
///////////////////////////////////////////////////////////////////////////////
// TUnicodeToMultiByte
template< int t_nBufferLength = SHORT_ED2K_STR*2 >
class TUnicodeToMultiByte
{
public:
TUnicodeToMultiByte(const CStringW& rwstr, UINT uCodePage = _AtlGetConversionACP())
{
int iBuffSize;
int iMaxEncodedStrSize = rwstr.GetLength()*2;
if (iMaxEncodedStrSize > t_nBufferLength)
{
iBuffSize = iMaxEncodedStrSize;
m_psz = new char[iBuffSize];
}
else
{
iBuffSize = ARRSIZE(m_acBuff);
m_psz = m_acBuff;
}
m_iChars = WideCharToMultiByte(uCodePage, 0, rwstr, rwstr.GetLength(), m_psz, iBuffSize, NULL, 0);
ASSERT( m_iChars > 0 || rwstr.GetLength() == 0 );
}
~TUnicodeToMultiByte()
{
if (m_psz != m_acBuff)
delete[] m_psz;
}
operator LPCSTR() const
{
return m_psz;
}
int GetLength() const
{
return m_iChars;
}
private:
int m_iChars;
LPSTR m_psz;
char m_acBuff[t_nBufferLength];
};
typedef TUnicodeToMultiByte<> CUnicodeToMultiByte;
| C++ |
#pragma once
/////////////////////////////////////////////////////////////////////////////
// CTrayMenuBtn window
class CTrayMenuBtn : public CWnd
{
public:
CTrayMenuBtn();
virtual ~CTrayMenuBtn();
bool m_bBold;
bool m_bMouseOver;
bool m_bNoHover;
bool m_bUseIcon;
bool m_bParentCapture;
UINT m_nBtnID;
CSize m_sIcon;
HICON m_hIcon;
CString m_strText;
CFont m_cfFont;
protected:
DECLARE_MESSAGE_MAP()
afx_msg void OnPaint();
};
| C++ |
#pragma once
#include "DialogMinTrayBtn.h"
//#include "PopupSystrayDlg.h"
#include "ResizableDialog.h"
#define IDT_SINGLE_CLICK 100
class CTrayDialog : public CDialogMinTrayBtn<CResizableDialog>
{
protected:
typedef CDialogMinTrayBtn<CResizableDialog> CTrayDialogBase;
public:
CTrayDialog(UINT uIDD, CWnd* pParent = NULL); // standard constructor
void TraySetMinimizeToTray(bool* pbMinimizeToTray);
BOOL TraySetMenu(UINT nResourceID);
BOOL TraySetMenu(HMENU hMenu);
BOOL TraySetMenu(LPCTSTR lpszMenuName);
BOOL TrayUpdate();
BOOL TrayShow();
BOOL TrayHide();
void TraySetToolTip(LPCTSTR lpszToolTip);
void TraySetIcon(HICON hIcon, bool bDelete = false);
void TraySetIcon(UINT nResourceID);
void TraySetIcon(LPCTSTR lpszResourceName);
BOOL TrayIsVisible();
virtual void TrayMinimizeToTrayChange();
virtual void RestoreWindow();
virtual void OnTrayLButtonDown(CPoint pt);
virtual void OnTrayLButtonUp(CPoint pt);
virtual void OnTrayLButtonDblClk(CPoint pt);
virtual void OnTrayRButtonUp(CPoint pt);
virtual void OnTrayRButtonDblClk(CPoint pt);
virtual void OnTrayMouseMove(CPoint pt);
protected:
bool* m_pbMinimizeToTray;
bool m_bCurIconDelete;
HICON m_hPrevIconDelete;
bool m_bLButtonDblClk;
bool m_bLButtonDown;
BOOL m_bTrayIconVisible;
NOTIFYICONDATA m_nidIconData;
CMenu m_mnuTrayMenu;
UINT m_nDefaultMenuItem;
UINT m_uSingleClickTimer;
void KillSingleClickTimer();
DECLARE_MESSAGE_MAP()
afx_msg LRESULT OnTrayNotify(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnTaskBarCreated(WPARAM wParam, LPARAM lParam);
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnDestroy();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnTimer(UINT nIDEvent);
};
| C++ |
//this file is part of ePopup
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#pragma once
#include <CString>
#include <string>
#include <sstream>
bool _tmakepathlimit(TCHAR *path, const TCHAR *drive, const TCHAR *dir, const TCHAR *fname, const TCHAR *ext);
int FontPointSizeToLogUnits(int nPointSize);
bool CreatePointFont(CFont &rFont, int nPointSize, LPCTSTR lpszFaceName);
bool CreatePointFontIndirect(CFont &rFont, const LOGFONT *lpLogFont);
bool isImage(const CString & filePath);
bool isSound(const CString & filePath);
bool isVideo(const CString & filePath);
bool isWavSound(const char *p_buffer);
bool isJpegImage(const char *p_image);
bool isGifImage(const char *p_image);
bool isWmvVideo(const char *p_video);
bool isAviVideo(const char *p_video);
bool isMpegVideo(const char *p_video);
bool deleteDirectory(CString, bool suppressionDefinitive = true);
CString basename(const CString & str);
//std::string basename(const std::string & str);
bool absolutePath(const std::string & relPath, std::string & absPath);
bool absolutePath(const CString & relPath, CString & absPath);
CString comboToCString(CComboBox & combo, bool useCursor = false);
std::stringstream &operator<<(std::stringstream &logger, LPCTSTR message);
std::string MFCStringToSTLString(const CString & str);
unsigned int splitString(const std::string & _str, unsigned int maxlinelen, std::string & _res);
//unsigned long long checksum(const char *p_buff, size_t p_len);
//bool getFileExtension(const std::string & p_filename, std::string & p_extension);
//void lowercase(std::string & p_string);
//bool mktempFile(std::string & p_dest, const std::string & p_tempdir, const std::string & p_extension);
| C++ |
#pragma once
#ifdef _DEBUG
#define CATCH_DFLT_ALL(fname)
#else
#define CATCH_DFLT_ALL(fname) \
catch(...){ \
if (thePrefs.GetVerbose()) \
DebugLogError(LOG_STATUSBAR, _T("Unknown exception in ") fname); \
ASSERT(0); \
}
#endif
// This type of "last chance" exception handling is to be used at least in several callback functions to avoid memory leaks.
// It is *not* thought as a proper handling of exceptions in general!
// -> Use explicit exception handlers where needed!
#define CATCH_MFC_EXCEPTION(fname) \
catch(CException* e){ \
TCHAR szError[1024]; \
e->GetErrorMessage(szError, _countof(szError)); \
const CRuntimeClass* pRuntimeClass = e->GetRuntimeClass(); \
LPCSTR pszClassName = (pRuntimeClass) ? pRuntimeClass->m_lpszClassName : NULL; \
if (!pszClassName) \
pszClassName = "CException"; \
if (thePrefs.GetVerbose()) \
DebugLogError(LOG_STATUSBAR, _T("Unknown %hs exception in ") fname _T(" - %s"), pszClassName, szError); \
e->Delete(); \
}
#define CATCH_STR_EXCEPTION(fname) \
catch(CString strError){ \
if (thePrefs.GetVerbose()) \
DebugLogError(LOG_STATUSBAR, _T("Unknown CString exception in ") fname _T(" - %s"), strError); \
}
#define CATCH_DFLT_EXCEPTIONS(fname) \
CATCH_MFC_EXCEPTION(fname) \
CATCH_STR_EXCEPTION(fname)
class CMsgBoxException : public CException
{
DECLARE_DYNAMIC(CMsgBoxException)
public:
explicit CMsgBoxException(LPCTSTR pszMsg, UINT uType = MB_ICONWARNING, UINT uHelpID = 0)
{
m_strMsg = pszMsg;
m_uType = uType;
m_uHelpID = uHelpID;
}
CString m_strMsg;
UINT m_uType;
UINT m_uHelpID;
};
class CClientException : public CException
{
DECLARE_DYNAMIC(CClientException)
public:
CClientException(LPCTSTR pszMsg, bool bDelete)
{
m_strMsg = pszMsg;
m_bDelete = bDelete;
}
CString m_strMsg;
bool m_bDelete;
};
| C++ |
#pragma once
class CEnBitmap : public CBitmap
{
public:
CEnBitmap();
virtual ~CEnBitmap();
BOOL LoadImage(LPCTSTR pszImagePath, COLORREF crBack = 0);
BOOL LoadImage(UINT uIDRes, LPCTSTR pszResourceType, HMODULE hInst = NULL, COLORREF crBack = 0);
BOOL LoadImage(LPCTSTR lpszResourceName, LPCTSTR pszResourceType, HMODULE hInst = NULL, COLORREF crBack = 0);
// helpers
static BOOL GetResource(LPCTSTR lpName, LPCTSTR lpType, HMODULE hInst, void* pResource, int& nBufSize);
static IPicture* LoadFromBuffer(BYTE* pBuff, int nSize);
protected:
BOOL Attach(IPicture* pPicture, COLORREF crBack);
};
| C++ |
//this file is part of ePopup
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#pragma once
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h"
#include <map>
#include <vector>
#include <sstream>
#include <Options.h>
#include <Logger.h>
#include "PopupClientInfo.h"
//===============================================================
// Options defines
//===============================================================
// Sameple of popup.ini
/*
###################################
# Mandatory options:
###################################
Resource path=C:\Documents and Settings\Guigui\Bureau\Popup\res
Server hostname=pcguigui
Server port=2000
User name=Svr
###################################
# Auto mode could be any mode:
#-----------------------------
# - normal : display messages as they come
# - prompt : prompts before displaying message
# - mute : switch off Popup. Messages are queued.
# - textonly : displays only the text part of the message.
#
# Setting delay to 0 seconds means that auto mode
# is turned off
####################################
Auto mode=textonly
Auto mode delay=10
*/
// End of sample
#define POPUP_RES_PATH "Resource path"
#define SERVER_HOSTNAME "Server hostname"
#define SERVER_PORT "Server port"
#define CLIENT_USER_NAME "User name"
#define AUTO_MODE "Auto mode"
#define AUTO_MODE_DELAY "Auto mode delay"
#define WEB_BROWSER_PATH "Web browser"
#define APP_ARGS_SUFFIX "_args"
#define APP_ASSOCIATIONS_KEY "extensions"
#define APP_DEFAULT_EXTENSION "default"
#define USER_NAME_MAX_LENGTH 64
#define HOSTNAME_MAX_LENGTH 64
#define APP_PATH_MAX_LENGTH 512
//===============================================================
// Forward declarations
//===============================================================
class CpopupDlg;
struct Options;
struct ResourceEntry;
struct Logger;
class PopupClient;
class PopupServer;
//===============================================================
// Popup app class definition
//===============================================================
class CpopupApp : public CWinApp
{
public:
CpopupApp(LPCTSTR lpszAppName = NULL);
typedef std::map<CString, ResourceEntry*> PopupResources;
// Main dialog
CpopupDlg* popupdlg;
// Options
Options m_options;
// Resources vector
PopupResources m_resources;
// Logging stream
Logger m_logger;
// Reference to popup client object
PopupClient* m_popupclient;
// Reference to popup server object
PopupServer* m_popupserver;
// Mutex to protect access to clients list
static CMutex s_clientmutex;
// Paths to different folders
CString m_basedir;
CString m_userdir;
CString m_tempdir;
CString m_inifile;
CString m_hostname;
CString m_username;
std::string m_servername;
int m_serverport;
PopupClientMode m_automode;
int m_automodeDelay;
bool m_resetTimer;
// Methods
virtual BOOL InitInstance();
void exitApp();
// Assess "connected" users list
bool getUsers(std::vector<PopupClientInfo> &users);
ResourceEntry *getRandomResource();
bool getApplicationByExtension(const std::string & p_extension,
std::string & p_app, std::string & p_args,
bool _setDefault = true);
bool openFile(const std::string & p_file);
bool openURL(const std::string & p_file);
protected:
// Methods
bool loadOptions();
bool initUserDirectory();
bool loadEnvironment();
bool saveOptions();
bool loadResources();
bool restartNetwork();
bool loadResourceDir(const CString & p_dir);
bool dumpResources();
friend class PopupPropertiesDlg;
};
// Main application instance
extern CpopupApp theApp;
| C++ |
// ------------------------------------------------------------
// CDialogMinTrayBtn template class
// MFC CDialog with minimize to systemtray button (0.04)
// Supports WinXP styles (thanks to David Yuheng Zhao for CVisualStylesXP - yuheng_zhao@yahoo.com)
// ------------------------------------------------------------
// DialogMinTrayBtn.h
// zegzav - 2002,2003 - eMule project (http://www.emule-project.net)
// ------------------------------------------------------------
#pragma once
#define HTMINTRAYBUTTON 65
//bluecow/sony: moved out of class for VC 2003 compatiblity; zegzav: made extern for proper look (thanks)
extern BOOL (WINAPI *_TransparentBlt)(HDC, int, int, int, int, HDC, int, int, int, int, UINT);
template <class BASE= CDialog> class CDialogMinTrayBtn : public BASE
{
public:
// constructor
CDialogMinTrayBtn();
CDialogMinTrayBtn(LPCTSTR lpszTemplateName, CWnd* pParentWnd = NULL);
CDialogMinTrayBtn(UINT nIDTemplate, CWnd* pParentWnd = NULL);
// methods
void MinTrayBtnShow();
void MinTrayBtnHide();
__inline BOOL MinTrayBtnIsVisible() const { return m_bMinTrayBtnVisible; }
void MinTrayBtnEnable();
void MinTrayBtnDisable();
__inline BOOL MinTrayBtnIsEnabled() const { return m_bMinTrayBtnEnabled; }
void SetWindowText(LPCTSTR lpszString);
protected:
// messages
virtual BOOL OnInitDialog();
afx_msg void OnNcPaint();
afx_msg BOOL OnNcActivate(BOOL bActive);
#if _MFC_VER>=0x0800
afx_msg LRESULT OnNcHitTest(CPoint point);
#else
afx_msg UINT OnNcHitTest(CPoint point);
#endif
afx_msg void OnNcLButtonDown(UINT nHitTest, CPoint point);
afx_msg void OnNcRButtonDown(UINT nHitTest, CPoint point);
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
afx_msg void OnTimer(UINT_PTR nIDEvent);
afx_msg LRESULT _OnThemeChanged();
DECLARE_MESSAGE_MAP()
private:
// internal methods
void MinTrayBtnInit();
void MinTrayBtnDraw();
BOOL MinTrayBtnHitTest(CPoint point) const;
void MinTrayBtnUpdatePosAndSize();
void MinTrayBtnSetUp();
void MinTrayBtnSetDown();
__inline const CPoint &MinTrayBtnGetPos() const { return m_MinTrayBtnPos; }
__inline const CSize &MinTrayBtnGetSize() const { return m_MinTrayBtnSize; }
__inline CRect MinTrayBtnGetRect() const { return CRect(MinTrayBtnGetPos(), MinTrayBtnGetSize()); }
BOOL IsWindowsClassicStyle() const;
INT GetVisualStylesXPColor() const;
BOOL MinTrayBtnInitBitmap();
// data members
CPoint m_MinTrayBtnPos;
CSize m_MinTrayBtnSize;
BOOL m_bMinTrayBtnVisible;
BOOL m_bMinTrayBtnEnabled;
BOOL m_bMinTrayBtnUp;
BOOL m_bMinTrayBtnCapture;
BOOL m_bMinTrayBtnActive;
BOOL m_bMinTrayBtnHitTest;
UINT_PTR m_nMinTrayBtnTimerId;
CBitmap m_bmMinTrayBtnBitmap;
BOOL m_bMinTrayBtnWindowsClassicStyle;
static const TCHAR *m_pszMinTrayBtnBmpName[];
};
| C++ |
#ifndef LOGGER_HPP
#define LOGGER_HPP
#include <sstream>
//===============================================================
// Logging utility
//===============================================================
struct Logger : public std::stringstream
{
std::string m_logFilePath;
bool m_enabled;
public:
Logger(const std::string & outputDir = "");
bool setPath(const std::string & outputDir);
virtual ~Logger() {}
void flush();
};
#endif // LOGGER_HPP
| C++ |
#pragma once
#include "afxcmn.h"
#include "Popup.h"
#include "PopupDlg.h"
#include "PopupMessageInfo.h"
#include <vector>
// PopupHistoryDialog dialog
class PopupHistoryDialog : public CDialog
{
DECLARE_DYNAMIC(PopupHistoryDialog)
public:
PopupHistoryDialog(CWnd* pParent = NULL); // standard constructor
virtual ~PopupHistoryDialog();
virtual BOOL validateDialog();
void appendHistory(const PopupMessageInfo & p_message,
bool p_received = true);
void OnOK();
// Dialog Data
enum { IDD = IDD_DIALOG_HISTORY };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
BOOL OnInitDialog();
DECLARE_MESSAGE_MAP()
public:
CListCtrl m_messageListCtrl;
private:
CImageList m_imageList;
PopupMessageList m_history;
PopupMessageList m_sentHistory;
CpopupDlg *m_parent;
afx_msg void OnNMDblclkListMessages(NMHDR *pNMHDR, LRESULT *pResult);
CListCtrl m_sentMessageListCtrl;
afx_msg void OnNMDblclkListSentMessages(NMHDR *pNMHDR, LRESULT *pResult);
};
| C++ |
#pragma once
/////////////////////////////////////////////////////////////////////////////////////////
///PopupAutoModeThread
class PopupAutoModeThread : public CWinThread
{
public:
DECLARE_DYNCREATE(PopupAutoModeThread)
protected:
PopupAutoModeThread() {}
public:
virtual BOOL InitInstance();
virtual int Run();
};
| C++ |
// CTaskbarNotifier Header file
// By John O'Byrne - 15 July 2002
// Modified by kei-kun
#pragma once
#define TN_TEXT_NORMAL 0x0000
#define TN_TEXT_BOLD 0x0001
#define TN_TEXT_ITALIC 0x0002
#define TN_TEXT_UNDERLINE 0x0004
//START - enkeyDEV(kei-kun) -TaskbarNotifier-
enum TbnMsg {
TBN_NONOTIFY,
TBN_NULL,
TBN_CHAT,
TBN_DOWNLOADFINISHED,
TBN_LOG,
TBN_IMPORTANTEVENT,
TBN_NEWVERSION,
TBN_DOWNLOADADDED
};
//END - enkeyDEV(kei-kun) -TaskbarNotifier-
///////////////////////////////////////////////////////////////////////////////
// CTaskbarNotifierHistory
class CTaskbarNotifierHistory : public CObject
{
public:
CTaskbarNotifierHistory() {}
virtual ~CTaskbarNotifierHistory() {}
CString m_strMessage;
int m_nMessageType;
CString m_strLink;
};
///////////////////////////////////////////////////////////////////////////////
// CTaskbarNotifier
class CTaskbarNotifier : public CWnd
{
DECLARE_DYNAMIC(CTaskbarNotifier)
public:
CTaskbarNotifier();
virtual ~CTaskbarNotifier();
typedef enum { LEFT_TO_RIGHT, RIGHT_TO_LEFT, UP_TO_DOWN, DOWN_TO_UP} Direction;
int Create(CWnd *pWndParent);
bool isReady();
void SetPopupImage(LPCTSTR strBmpFilePath);
void SetPopupImage(int rcId);
void Show(LPCTSTR message = NULL, Direction direction = DOWN_TO_UP, UINT shiftValue = 0, bool p_modal = false);
void Hide();
void addSyncNotifier(CTaskbarNotifier *p_syncNofifier);
BOOL SetBitmap(UINT nBitmapID, int red = -1, int green = -1, int blue = -1);
BOOL SetBitmap(LPCTSTR pszFileName,int red = -1, int green = -1, int blue = -1);
BOOL SetBitmap(CBitmap* pBitmap, int red, int green, int blue);
void SetTextFont(LPCTSTR pszFont, int nSize, int nNormalStyle, int nSelectedStyle);
void SetTextDefaultFont();
void SetTextColor(COLORREF crNormalTextColor, COLORREF crSelectedTextColor);
void SetTextRect(RECT rcText);
void SetTextFormat(UINT uTextFormat);
inline UINT getImageSize() const { return m_nImageSize; }
protected:
void setupMessage(LPCTSTR message);
std::vector<CTaskbarNotifier*> m_syncNotifiers;
bool m_modal;
bool m_bIsShowingAnim;
CString m_strConfigFilePath;
time_t m_tConfigFileLastModified;
CWnd *m_pWndParent;
CFont m_fontNormal;
CFont m_fontSelected;
COLORREF m_crNormalTextColor;
COLORREF m_crSelectedTextColor;
HCURSOR m_hCursor;
CBitmap m_bitmapBackground;
HRGN m_hBitmapRegion;
int m_nBitmapWidth;
int m_nBitmapHeight;
bool m_bBitmapAlpha;
CString m_strCaption;
UINT m_nImageSize;
CString m_strLink;
CRect m_rcText;
CRect m_rcCloseBtn;
CRect m_rcHistoryBtn;
CPoint m_ptMousePosition;
UINT m_uTextFormat;
BOOL m_bMouseIsOver;
BOOL m_bTextSelected;
int m_nAnimStatus;
int m_nTaskbarPlacement;
DWORD m_dwTimerPrecision;
DWORD m_dwTimeToStay;
DWORD m_dwShowEvents;
DWORD m_dwHideEvents;
DWORD m_dwTimeToShow;
DWORD m_dwTimeToHide;
int m_nCurrentPosX;
int m_nCurrentPosY;
int m_nCurrentWidth;
int m_nCurrentHeight;
int m_nIncrementShow;
int m_nIncrementHide;
int m_nHistoryPosition; //<<--enkeyDEV(kei-kun) -TaskbarNotifier-
int m_nActiveMessageType; //<<--enkeyDEV(kei-kun) -TaskbarNotifier-
CObList m_MessageHistory; //<<--enkeyDEV(kei-kun) -TaskbarNotifier-
HMODULE m_hMsImg32Dll;
CRect m_replyRect;
CRect m_replyAllRect;
BOOL (WINAPI *m_pfnAlphaBlend)(HDC, int, int, int, int, HDC, int, int, int, int, BLENDFUNCTION);
HRGN CreateRgnFromBitmap(HBITMAP hBmp, COLORREF color);
void startAnimation(Direction direction, UINT shiftValue);
DECLARE_MESSAGE_MAP()
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnPaint();
afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message);
afx_msg void OnTimer(UINT nIDEvent);
afx_msg void OnSysColorChange();
};
| C++ |
//this file is part of ePopup
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#pragma once
#include "TrayDialog.h"
#include "resource.h"
#include <string>
#include "Popup.h"
#include "PopupClientUI.h"
#ifdef _DEBUG
#define POPUP_GUID _T("POPUP-{4EADC6FC-516F-4b7c-9066-97D893649570}-DEBUG")
#else
#define POPUP_GUID _T("POPUP-{4EADC6FC-516F-4b7c-9066-97D893649570}")
#endif
class CTaskbarNotifier;
class PopupClient;
class PopupMainDialog;
enum PopupWndMessages
{
UM_FIRST_POPUP_USER_MSG = (WM_USER + 0x100 + 1),
UM_TRAY_ICON_NOTIFY_MESSAGE,
UM_REPLY_BTN_CLICKED,
UM_REPLYALL_BTN_CLICKED,
};
class CpopupDlg : public CTrayDialog, PopupClientUI
{
public:
CpopupDlg(CWnd* pParent = NULL);
~CpopupDlg();
enum { IDD = IDD_POPUP_DIALOG };
bool m_noSleep;
virtual void RestoreWindow();
CTaskbarNotifier* m_wndTaskbarNotifier;
CTaskbarNotifier* m_wndTaskbarNotifierText;
virtual void EndDialog(int res);
// PopupClientUI implementation
void notifyMessage(const PopupMessageInfo & p_message, bool _isReplay = false);
void updateConnectionInfos(bool p_connected, const std::string & p_tooltipinfo);
void kill();
void appendLog(const std::string & p_log);
void clearClients();
void updateClientStatus(const PopupClientInfo & p_client);
void notifyNetworkError(const std::string & p_error);
std::string getTemporaryDir();
bool setMode(const PopupClientMode & p_mode);
inline bool isMuted() const { return m_mode == POPUP_MODE_MUTED; }
inline void resetTimer() { m_resetTimer = true; }
void startServer();
void recordMessageSent(const PopupMessageInfo & p_message);
bool m_resetTimer;
bool m_doServer;
PopupClientMode m_mode;
PopupMainDialog *m_mainDialog;
// Mutex to protect access to events list
static CMutex s_eventmutex;
protected:
HICON m_hIcon, m_hIconMute, m_hIconPrompt, m_hIconTextOnly;
bool m_connected;
bool m_senderDialogOn;
CpopupApp *m_app;
PopupMessageList m_incomingMessages;
std::string m_connectionInfos;
PopupMessageInfo m_currentMessageDisplayed;
void MinimizeWindow();
virtual BOOL OnInitDialog();
void updateToolTip();
void OnTrayRButtonUp(CPoint pt);
bool isReadyToDisplayNextMessage();
void displayMessage(const PopupMessageInfo & p_message);
void updateIcon();
bool acceptMessage(const PopupMessageInfo & p_message);
virtual void OnTrayLButtonDown(CPoint pt);
void notifyMode();
void OnOK();
friend class PopupEventThread;
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnTcnSelchangeTab1(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg LRESULT OnReply(WPARAM wParam,LPARAM lParam);
afx_msg LRESULT OnReplyAll(WPARAM wParam,LPARAM lParam);
};
| C++ |
#include <PopupDefaultLogger.hpp>
#include <PopupSqlite3Database.hpp>
#include <string>
using namespace Popup;
using namespace std;
static PopupDefaultLogger logger;
static void dump(const PopupDatabaseUser * user)
{
logger.appendLog(POPUP_LOG_INFO,
"id=%u name=%s nickname=%s avatar=%s",
user->getID(), user->getLogin().c_str(),
user->getNickname().c_str(), user->getAvatarPath().c_str());
}
int main(int argc, char *argv[])
{
if (argc <= 1)
{
logger.appendLog(POPUP_LOG_ERROR, "Usage: %s <file.db>\n", argv[0]);
}
else
{
PopupSqlite3Database database(string(argv[1]), &logger);
string message;
PopupDatabaseUser *user = database.connect("guigui", "bonjour", message);
user = database.newUser("guigui", "bonjour", "Maqui de Daube", "./path.png", message);
if (user != 0) {
dump(user);
}
PopupDatabaseUser *user2 = database.newUser("guigui", "bonjourno",
"Maqui de Daube2", "./path.png", message);
user2 = database.newUser("guigui2", "bonjourno",
"Maqui de Daube2", "./path.png", message);
delete user2;
user2 = database.connect("guigui2", "bonjourno", message);
if (user2 != 0) {
dump(user2);
}
database.updateNickname(user2, "COnnardo", message);
dump(user2);
database.updateNickname(user2, "Maqui de Daube", message);
PopupDatabaseUser *user3 = database.connect("guigui2", "bonjour", message);
}
return 0;
}
| C++ |
int main()
{
}
| C++ |
#include <PopupDefaultLogger.hpp>
#include <PopupQSqliteDatabase.hpp>
#include <string>
using namespace Popup;
using namespace std;
int main(int argc, char *argv[])
{
PopupDefaultLogger logger;
if (argc <= 1) {
logger.appendLog(POPUP_LOG_ERROR, "Usage: %s <file.db>\n", argv[0]);
} else {
PopupQSqliteDatabase database(string(argv[1]), &logger);
string message;
PopupDatabaseUser *user = database.connect("guigui", "bonjour", &message);
if (user != 0) {
logger.appendLog(POPUP_LOG_INFO, "Success : user name=%s id = %u\n",
user->getLogin().c_str(), user->getID());
} else {
logger.appendLog(POPUP_LOG_ERROR, "Failed : %s\n", message.c_str());
}
}
return 0;
}
| C++ |
#include <PopupQSqliteDatabase.hpp>
#include <QFile>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QVariant>
using namespace Popup;
using namespace std;
struct MyDatabaseUser : PopupDatabaseUser
{
unsigned long id;
string login;
string iconpath;
string nickname;
unsigned long getID() const { return id; }
const std::string & getLogin() const { return login; }
const std::string & getNickname() const { return nickname; }
const std::string & getIconPath() const { return iconpath; }
};
PopupQSqliteDatabase::PopupQSqliteDatabase(const string & p_path,
const PopupLoggerUI *p_logger)
: m_db(QSqlDatabase::addDatabase("QSQLITE")),
m_logger(p_logger), m_connected(false)
{
if (!QFile::exists(p_path.c_str())) {
m_logger->appendLog(POPUP_LOG_INFO,
"No such sqlite database: %s. Creating database.",
p_path.c_str());
}
else
{
m_db.setDatabaseName(p_path.c_str());
if (!m_db.open()) {
m_logger->appendLog(POPUP_LOG_CRITICAL,
"Oopps!! Cannot open sqlite database %s.",
p_path.c_str());
}
else {
m_connected = true;
}
}
}
PopupQSqliteDatabase::~PopupQSqliteDatabase()
{
if ((m_connected == true) && (m_db.isOpen())) {
m_db.close();
}
}
PopupDatabaseUser *PopupQSqliteDatabase::connect(const string & p_login,
const std::string & p_password,
std::string *p_message)
{
QSqlQuery query;
query.exec("SELECT * FROM users");
//query.prepare("SELECT * FROM users WHERE login=\":login\";");
//query.bindValue(":login", QString(p_login.c_str()));
//query.exec();
if (query.isActive())
{
QSqlRecord record = query.record();
int idCol = record.indexOf("id");
int nnameCol = record.indexOf("nickname");
int hashCol = record.indexOf("hash");
int iconPathCol = record.indexOf("iconpath");
MyDatabaseUser *databaseUser = new MyDatabaseUser();
databaseUser->id = query.value(idCol).toUInt();
printf("id= %d", databaseUser->id);
databaseUser->login = p_login;
databaseUser->nickname = query.value(nnameCol).toString().toStdString();
string hash = query.value(hashCol).toString().toStdString();
databaseUser->iconpath = query.value(iconPathCol).toString().toStdString();
return databaseUser;
}
else
{
m_logger->appendLog(POPUP_LOG_ERROR, "Oops! Fait chier la bite!");
return NULL;
}
}
bool PopupQSqliteDatabase::update(const PopupDatabaseUser *p_user)
{
return false;
}
| C++ |
#pragma once
#include <stdlib.h>
#include <string.h>
#define DIGITS "0.123456789"
#define WHITESPACE_CHARS " \n\r\t"
class ScriptScanner
{
public:
ScriptScanner(char* str);
~ScriptScanner(void);
float NextFuncTime();
char* NextFunc();
float NextFuncArg();
void hasExec();
bool ReadOneLine();
private:
char* str;
float _nextFuncTime;
char* _nextFunc;
float _nextFuncArg;
bool _hasExeced;
void eatWhitespace();
void toEOL();
char* nexta();
double nextd();
bool isAlpha(char c);
bool hasNexta();
bool hasNextc(char c);
bool hasNextd();
}; | C++ |
// stdafx.cpp : source file that includes just the standard includes
// FrcCppTest.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| C++ |
#pragma once
#include <iostream>
#include <fstream>
#include <streambuf>
#include <string>
#include <sstream>
#include <Windows.h>
#include "ScriptScanner.h"
typedef void (*FUNC)(float param);
class ScriptInterpreter
{
public:
ScriptInterpreter(void);
~ScriptInterpreter(void);
void OpenScript(char* fileName);
void Start();
int Tick();
void RegisterFunc(FUNC func);
private:
char* script;
float startTime;
ScriptScanner* scan;
}; | C++ |
#include "ScriptInterpreter.h"
ScriptInterpreter::ScriptInterpreter(void)
{
}
ScriptInterpreter::~ScriptInterpreter(void)
{
}
float getelap()
{
return (float)GetTickCount64() / (float)1000;
}
void ScriptInterpreter::OpenScript(char* file)
{
std::fstream f(file);
if(!f.is_open())
{
printf("Could not find script file: %s", file);
return;
}
std::stringstream buf;
buf << f.rdbuf();
std::string s = buf.str();
const char* srcString = s.c_str();
f.close();
this->script = new char[strlen(srcString)];
strcpy(this->script, srcString);
scan = new ScriptScanner(this->script);
}
void ScriptInterpreter::Start()
{
this->startTime = getelap();
}
int ScriptInterpreter::Tick()
{
float execTime = getelap() - this->startTime;
scan->ReadOneLine();
while(scan->NextFuncTime() <= execTime)
{
char* func = scan->NextFunc();
float funcTime = scan->NextFuncTime();
float funcArg = scan->NextFuncArg();
printf("Exec: at: %f\tFunc: %s\tArg: %f\n", funcTime, func, funcArg);
if(!strcmp(func, "return"))
return 0;
scan->hasExec();
scan->ReadOneLine();
}
return 1;
} | C++ |
#include "ScriptScanner.h"
bool strcont(char c, char* str)
{
for(int i = 0; str[i] != 0; i++)
{
if(str[i] == c)
return 1;
}
return 0;
}
ScriptScanner::ScriptScanner(char* str)
{
this->str = str;
}
ScriptScanner::~ScriptScanner(void)
{
}
bool ScriptScanner::ReadOneLine()
{
// A line that we parse looks like this:
// 5.5: setThing(3); This is a comment.\n
if(!this->_hasExeced) // Check if this function has already executed
return 0;
this->_hasExeced = false;
double time = nextd(); // Get the time
this->eatWhitespace();
if(!this->hasNextc(':')) // Check for the colon
return 1;
this->eatWhitespace();
char* func = this->nexta(); // Get the function
if(!this->hasNextc('(')) // Check for open paren
return 1;
if(this->hasNextd()) // Check if there is an arg
{
this->_nextFuncArg = this->nextd(); // Get the arg
}
else
{
this->_nextFuncArg = 0; // Otherwise set arg to zero
}
if(!this->hasNextc(')')) // Check for close parenthesis
return 1;
if(!this->hasNextc(';')) // Check for semicolon
return 1;
this->toEOL(); // Skip over comments, to next line.
this->_nextFunc = func;
this->_nextFuncTime = time;
return 0;
}
void ScriptScanner::hasExec()
{
this->_hasExeced = true;
}
float ScriptScanner::NextFuncTime()
{
return this->_nextFuncTime;
}
char* ScriptScanner::NextFunc()
{
return this->_nextFunc;
}
float ScriptScanner::NextFuncArg()
{
return this->_nextFuncArg;
}
bool ScriptScanner::isAlpha(char c)
{
return (c >= 65 && c <= 90) || (c >= 97 && c <= 122);
}
bool ScriptScanner::hasNexta()
{
return this->isAlpha(this->str[0]);
}
bool ScriptScanner::hasNextc(char c)
{
if(this->str[0] == c)
{
this->str++;
return true;
}
return false;
}
bool ScriptScanner::hasNextd()
{
return strcont(this->str[0], DIGITS);
}
char* ScriptScanner::nexta()
{
char* buf = new char[strlen(this->str)];
int i = 0;
while(this->isAlpha(this->str[0]))
{
buf[i++] = this->str[0];
this->str++;
}
buf[i] = '\0';
this->eatWhitespace();
return buf;
}
double ScriptScanner::nextd()
{
char* buf = new char[strlen(this->str)];
int i = 0;
while(strcont(this->str[0], DIGITS))
{
buf[i++] = this->str[0];
this->str++;
}
buf[i] = '\0';
double val = atof(buf);
this->eatWhitespace();
return val;
}
void ScriptScanner::eatWhitespace()
{
while(strcont(this->str[0], WHITESPACE_CHARS)) this->str++;
}
void ScriptScanner::toEOL()
{
while(this->str[0] != '\n') this->str++;
this->str++;
} | C++ |
//include "stdafx.h"
//#include "ScriptInterpreter.h"
#include <winsock2.h>
#include <WS2tcpip.h>
typedef struct DashboardDatatype
{
float voltage;
};
#include <cstdio>
int printf_wrap(const char* format, ...)
{
va_list args;
va_start(args, format);
int retVal = vprintf(format, args);
va_end(args);
return retVal;
}
int main(int argc, char* argv)
{
printf("%s\n", "hi");
printf_wrap("The word is %s\n", "hi");
/*
WSADATA* data;
WORD version = MAKEWORD(2, 2);
int result = WSAStartup(version, 0);
int _sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
sockaddr_in addr;
addr.sin_port = 1165;
addr.sin_family = AF_INET;
inet_pton(AF_INET, "192.168.0.155", &addr.sin_addr);
connect(_sock, (sockaddr*) &addr, sizeof addr);
DashboardDatatype d;
char buf[sizeof(DashboardDatatype)];
while(true)
{
for(float i = 0; i < 50; i++)
{
d.voltage = i;
memcpy(buf, &d, sizeof(d));
send(_sock, buf, 4, 0);
Sleep(1000);
}
}*/
} | C++ |
#ifndef OI_H
#define OI_H
#include "WPILib.h"
#include "Robotmap.h"
class OI
{
private:
Joystick* joystickDriveLeft;
Joystick* joystickDriveRight;
Joystick* joystickGameMech;
// **************************************
// **************** Drive ***************
// **************************************
JoystickButton* btnBrake;
JoystickButton* btnCoast;
JoystickButton* btnShift;
// **************************************
// ********** Launcher Motors ***********
// **************************************
JoystickButton* btnStartLauncher;
JoystickButton* btnStopLauncher;
// **************************************
// ********** Loader/Launcher ***********
// **************************************
JoystickButton* btnFire;
JoystickButton* btnLoad;
JoystickButton* btnUnjam;
// **************************************
// *************** Climber **************
// **************************************
JoystickButton* btnBeginClimb;
JoystickButton* btnEndClimb;
public:
OI();
float GetStickLeftY();
float GetStickRightY();
float GetThrottle();
//bool GetBut(int i);
};
#endif
| C++ |
#ifndef COMMAND_BASE_H
#define COMMAND_BASE_H
#include "Commands/Command.h"
#include "Subsystems/ClimberSubsystem.h"
#include "Subsystems/DriveSubsystem.h"
#include "Subsystems/FrisbeeLauncher.h"
#include "Subsystems/FrisbeeLoader.h"
#include "Subsystems/GyroSubsystem.h"
#include "OI.h"
/**
* The base for all commands. All atomic commands should subclass CommandBase.
* CommandBase stores creates and stores each control system. To access a
* subsystem elsewhere in your code in your code use CommandBase.examplesubsystem
*/
class CommandBase: public Command
{
public:
CommandBase(const char *name);
CommandBase();
static void init();
// Create a single static instance of all of your subsystems
static OI *oi;
static DriveSubsystem* drive;
static FrisbeeLauncher* launcher;
static FrisbeeLoader* loader;
static ClimberSubsystem* climber;
static GyroSubsystem* gyro;
};
#endif
| C++ |
#include "logging.h"
#include "Robotmap.h"
#include <cstdio>
#include <stdarg.h>
void log(LogType level, char* format, ...)
{
if (level >= MINIMUM_LOG_LEVEL)
{
va_list args;
va_start(args, format);
vprintf(format, args);
printf("\n");
va_end(args);
}
}
| C++ |
#ifndef SCRIPT_SCANNER_H
#define SCRIPT_SCANNER_H
class ScriptScanner
{
public:
ScriptScanner(char* str);
~ScriptScanner(void);
float NextFuncTime();
char* NextFunc();
float NextFuncArg();
void hasExec();
bool ReadOneLine();
private:
char* str;
float _nextFuncTime;
char* _nextFunc;
float _nextFuncArg;
bool _hasExeced;
void eatWhitespace();
void toEOL();
char* nexta();
double nextd();
bool isAlpha(char c);
bool hasNexta();
bool hasNextc(char c);
bool hasNextd();
};
#endif
| C++ |
#ifndef SCRIPT_INTERPRETER_H
#define SCRIPT_INTERPRETER_H
#include "ScriptScanner.h"
class ScriptInterpreter
{
public:
typedef void (*ScriptInterpreterCallbackFunc)(const char* func, float param, void* ref);
ScriptInterpreter(void);
~ScriptInterpreter(void);
int OpenScript(const char* fileName);
void Start(void* ref);
int Tick();
void SetCallback(ScriptInterpreterCallbackFunc func);
private:
char* script;
void* refNum;
float startTime;
ScriptScanner* scan;
ScriptInterpreterCallbackFunc _callback;
};
#endif
| C++ |
#include "ScriptInterpreter.h"
#include <iostream>
#include <fstream>
#include <streambuf>
#include <string>
#include <sstream>
#include "stdlib.h"
#include "Timer.h"
#include "ScriptScanner.h"
#include "../logging.h"
#define GETELAP Timer::GetFPGATimestamp
ScriptInterpreter::ScriptInterpreter(void)
{
}
ScriptInterpreter::~ScriptInterpreter(void)
{
delete this->script;
this->script = NULL;
}
void ScriptInterpreter::SetCallback(ScriptInterpreterCallbackFunc func)
{
this->_callback = func;
}
int ScriptInterpreter::OpenScript(const char* file)
{
std::fstream f(file);
if(!f.is_open())
{
log(kError, "Could not find script file: %s", file);
return 1;
}
std::stringstream buf;
buf << f.rdbuf();
std::string s = buf.str();
const char* srcString = s.c_str();
buf.flush();
f.close();
this->script = new char[strlen(srcString) + 1];
strcpy(this->script, srcString);
delete srcString;
return 0;
}
void ScriptInterpreter::Start(void* ref)
{
this->refNum = ref;
scan = new ScriptScanner(script);
this->startTime = GETELAP(); // Write down our offset time.
}
int ScriptInterpreter::Tick()
{
float execTime = GETELAP() - this->startTime; // Offset current time from when we started.
scan->ReadOneLine(); // Check that we have a line ready.
while(scan->NextFuncTime() <= execTime) // Run all of the lines that execute before or on now.
{
char* func = scan->NextFunc();
float funcTime = scan->NextFuncTime();
float funcArg = scan->NextFuncArg();
//log(kInformation, "Exec: at: %f\tFunc: %s\tArg: %f", funcTime, func, funcArg);
printf("Exec: at: %f\tFunc: %s\tArg: %f\n", funcTime, func, funcArg);
_callback(func, funcArg, this->refNum);
if(!strcmp(func, "return"))
break;
scan->hasExec(); // We have now executed the line.
scan->ReadOneLine(); // Read another one.
}
return 1; // If Tick() is required again, return 1.
}
| C++ |
#include "ScriptScanner.h"
#include <stdlib.h>
#include <string.h>
#define DIGITS "-0.123456789"
#define WHITESPACE_CHARS " \n\r\t"
bool strcont(char c, char* str)
{
for(int i = 0; str[i] != 0; i++)
{
if(str[i] == c)
return 1;
}
return 0;
}
ScriptScanner::ScriptScanner(char* str)
{
this->str = str;
}
ScriptScanner::~ScriptScanner(void)
{
}
bool ScriptScanner::ReadOneLine()
{
// A line that we parse looks like this:
// 5.5: setThing(3); This is a comment.\n
if(!this->_hasExeced) // Check if this function has already executed
return 0;
this->_hasExeced = false;
double time = nextd(); // Get the time
this->eatWhitespace();
if(!this->hasNextc(':')) // Check for the colon
return 1;
this->eatWhitespace();
char* func = this->nexta(); // Get the function
if(!this->hasNextc('(')) // Check for open paren
return 1;
if(this->hasNextd()) // Check if there is an arg
{
this->_nextFuncArg = this->nextd(); // Get the arg
}
else
{
this->_nextFuncArg = 0; // Otherwise set arg to zero
}
if(!this->hasNextc(')')) // Check for close parenthesis
return 1;
if(!this->hasNextc(';')) // Check for semicolon
return 1;
this->toEOL(); // Skip over comments, to next line.
this->eatWhitespace();
this->_nextFunc = func;
this->_nextFuncTime = time;
return 0;
}
void ScriptScanner::hasExec()
{
this->_hasExeced = true;
}
float ScriptScanner::NextFuncTime()
{
return this->_nextFuncTime;
}
char* ScriptScanner::NextFunc()
{
return this->_nextFunc;
}
float ScriptScanner::NextFuncArg()
{
return this->_nextFuncArg;
}
bool ScriptScanner::isAlpha(char c)
{
return (c >= 65 && c <= 90) || (c >= 97 && c <= 122);
}
bool ScriptScanner::hasNexta()
{
return this->isAlpha(this->str[0]);
}
bool ScriptScanner::hasNextc(char c)
{
if(this->str[0] == c)
{
this->str++;
return true;
}
return false;
}
bool ScriptScanner::hasNextd()
{
return strcont(this->str[0], DIGITS);
}
char* ScriptScanner::nexta()
{
char* buf = new char[strlen(this->str)];
int i = 0;
while(this->isAlpha(this->str[0]))
{
buf[i++] = this->str[0];
this->str++;
}
buf[i] = '\0';
this->eatWhitespace();
return buf;
}
double ScriptScanner::nextd()
{
char* buf = new char[strlen(this->str)];
int i = 0;
while(strcont(this->str[0], DIGITS))
{
buf[i++] = this->str[0];
this->str++;
}
buf[i] = '\0';
double val = atof(buf);
this->eatWhitespace();
return val;
}
void ScriptScanner::eatWhitespace()
{
while(strcont(this->str[0], WHITESPACE_CHARS)) this->str++;
}
void ScriptScanner::toEOL()
{
while(this->str[0] != '\n') this->str++;
this->str++;
}
| C++ |
#include "WPILib.h"
#include "Commands/Command.h"
#include "CommandBase.h"
#include "Commands/Autonomous/AutonomousCommand.h"
#include "Commands/Drive/TankDriveCommand.h"
class CommandBasedRobot: public IterativeRobot
{
private:
Command *autonomousCommand;
Command *tankControl;
Compressor* c;
virtual void RobotInit()
{
printf("RobotInit Called\n");
CommandBase::init();
autonomousCommand = new AutonomousCommand(AUTO_SCRIPT);
tankControl = new TankDriveCommand();
c = new Compressor(COMPRESSOR_TRANSDUCER, COMPRESSOR_SPIKE);
}
virtual void AutonomousInit()
{
printf("AutonomousInit Called\n");
autonomousCommand->Start();
}
virtual void AutonomousPeriodic()
{
Scheduler::GetInstance()->Run();
}
virtual void TeleopInit()
{
// This makes sure that the autonomous stops running when
// teleop starts running. If you want the autonomous to
// continue until interrupted by another command, remove
// this line or comment it out.
autonomousCommand->Cancel();
tankControl->Start();
c->Start();
}
virtual void TeleopPeriodic()
{
Scheduler::GetInstance()->Run();
}
};
START_ROBOT_CLASS(CommandBasedRobot)
;
| C++ |
#ifndef GYROSUBSYSTEM_H
#define GYROSUBSYSTEM_H
#include "Commands/Subsystem.h"
#include "WPILib.h"
/**
*
*
* @author Matthew
*/
class GyroSubsystem: public Subsystem
{
private:
Gyro* gyroYaw;
public:
GyroSubsystem();
void InitDefaultCommand();
float GetYawAngle();
void ResetYaw();
};
#endif
| C++ |
#include "FrisbeeLauncher.h"
FrisbeeLauncher::FrisbeeLauncher() :
Subsystem("FrisbeeLauncher")
{
firstStage = new CANJaguar(MOTOR_LAUNCHER_STAGE_1, CANJaguar::kVoltage);
secondStage = new CANJaguar(MOTOR_LAUNCHER_STAGE_2, CANJaguar::kVoltage);
this->firstStage->SetSafetyEnabled(false);
this->firstStage->SetSafetyEnabled(false);
}
void FrisbeeLauncher::InitDefaultCommand()
{
}
void FrisbeeLauncher::SetLauncherSpeed(float voltage)
{
if (voltage < 0) // So that you can't run the shooter backwards
return;
this->_isRunning = voltage > 0; // Set isRunning to true if speed > 0
this->firstStage->Set(voltage);
this->secondStage->Set(voltage);
}
bool FrisbeeLauncher::IsRunning()
{
return _isRunning;
}
| C++ |
#include "DriveSubsystem.h"
DriveSubsystem::DriveSubsystem() :
Subsystem("DriveSubsystem")
{
shiftSolenoid = new Solenoid(SOLENOID_SHIFTER);
motorLeft = new CANJaguar(MOTOR_LEFT, CANJaguar::kPercentVbus);
motorRight = new CANJaguar(MOTOR_RIGHT, CANJaguar::kPercentVbus);
//_isClosedLoop = false;
drive = new RobotDrive(motorLeft, motorRight);
drive->SetSafetyEnabled(false);
motorLeft->SetSafetyEnabled(false);
motorRight->SetSafetyEnabled(false);
}
void DriveSubsystem::InitDefaultCommand()
{
}
void DriveSubsystem::TankDrive(float l, float r)
{
drive->TankDrive(l, r, false);
}
void DriveSubsystem::SetCoastBrakeMode(CANJaguar::NeutralMode m)
{
motorLeft->ConfigNeutralMode(m);
motorRight->ConfigNeutralMode(m);
}
void DriveSubsystem::RotateSpeed(float x)
{
drive->TankDrive(-x, x, false);
}
void DriveSubsystem::Shift(bool o)
{
shiftSolenoid->Set(o);
}
void DriveSubsystem::ShiftLow()
{
this->Shift(false);
}
void DriveSubsystem::ShiftHigh()
{
this->Shift(true);
}
| C++ |
#ifndef DRIVESUBSYSTEM_H
#define DRIVESUBSYSTEM_H
#include "WPILib.h"
#include "Commands/Subsystem.h"
#include "../Robotmap.h"
/**
*
*
* @author Matthew Kennedy of FRC1294
*/
class DriveSubsystem: public Subsystem {
private:
// It's desirable that everything possible under private except
// for methods that implement subsystem capabilities
RobotDrive* drive;
CANJaguar* motorLeft;
CANJaguar* motorRight;
Solenoid* shiftSolenoid;
bool _isClosedLoop;
public:
DriveSubsystem();
void InitDefaultCommand();
void TankDrive(float l, float r);
void RotateSpeed(float x);
void Shift(bool high);
void ShiftLow();
void ShiftHigh();
void SetCoastBrakeMode(CANJaguar::NeutralMode mode);
};
#endif
| C++ |
#include "ClimberSubsystem.h"
#include "../Robotmap.h"
ClimberSubsystem::ClimberSubsystem() :
Subsystem("ClimberSubsystem")
{
//this->climbJagRight = new CANJaguar(MOTOR_CLIMBER_RIGHT, CANJaguar::kPercentVbus);
//this->climbJagLeft = new CANJaguar(MOTOR_CLIMBER_LEFT, CANJaguar::kPercentVbus);
this->climbJagLeft = new Jaguar(MOTOR_CLIMBER_LEFT);
this->climbJagRight = new Jaguar(MOTOR_CLIMBER_RIGHT);
this->solenoidArm = new Solenoid(SOLENOID_CLIMBER_ARMS);
this->solenoidTip = new Solenoid(SOLENOID_TIP);
}
void ClimberSubsystem::InitDefaultCommand()
{
}
void ClimberSubsystem::SetLeftClimbMotor(float speed)
{
climbJagLeft->Set(speed);
}
void ClimberSubsystem::SetRightClimbMotor(float speed)
{
climbJagRight->Set(speed);
}
void ClimberSubsystem::SetArmPosition(bool out)
{
solenoidArm->Set(out);
}
void ClimberSubsystem::SetRobotTip(bool tipped)
{
solenoidTip->Set(tipped);
}
| C++ |
#ifndef FRISBEELAUNCHER_H
#define FRISBEELAUNCHER_H
#include "WPIlib.h"
#include "Commands/Subsystem.h"
#include "../Robotmap.h"
/**
*
*
* @author Matthew
*/
class FrisbeeLauncher: public Subsystem {
private:
CANJaguar* firstStage;
CANJaguar* secondStage;
bool _isRunning;
public:
FrisbeeLauncher();
void InitDefaultCommand();
void SetLauncherSpeed(float voltage);
bool IsRunning();
};
#endif
| C++ |
#ifndef CLIMBERSUBSYSTEM_H
#define CLIMBERSUBSYSTEM_H
#include "Commands/Subsystem.h"
#include "WPILib.h"
/**
*
*
* @author Matthew
*/
class ClimberSubsystem: public Subsystem
{
private:
Jaguar *climbJagLeft;
Jaguar *climbJagRight;
Solenoid* solenoidTip;
Solenoid* solenoidArm;
public:
ClimberSubsystem();
void InitDefaultCommand();
void SetLeftClimbMotor(float speed);
void SetRightClimbMotor(float speed);
void SetArmPosition(bool out);
void SetRobotTip(bool tipped);
};
#endif
| C++ |
#ifndef FRISBEELOADER_H
#define FRISBEELOADER_H
#include "Commands/Subsystem.h"
#include "WPILib.h"
/**
*
*
* @author Matthew
*/
class FrisbeeLoader: public Subsystem {
private:
Solenoid* pusherSolenoid;
DigitalInput* feedSwitch;
CANJaguar* feedMotor;
public:
FrisbeeLoader();
void InitDefaultCommand();
/**
* true is deployed (firing shot) and false is retracted (reload)
*/
void SetPusher(bool position);
bool GetFeedSwitch();
void SetFeederMotor(float speed);
};
#endif
| C++ |
#include "GyroSubsystem.h"
#include "../Robotmap.h"
GyroSubsystem::GyroSubsystem() :
Subsystem("GyroSubsystem")
{
this->gyroYaw = new Gyro(new AnalogChannel(GYRO_YAW_PIN));
}
void GyroSubsystem::InitDefaultCommand()
{
}
float GyroSubsystem::GetYawAngle()
{
return gyroYaw->GetAngle();
}
void GyroSubsystem::ResetYaw()
{
gyroYaw->Reset();
}
| C++ |
#include "FrisbeeLoader.h"
#include "../Robotmap.h"
FrisbeeLoader::FrisbeeLoader() :
Subsystem("FrisbeeLoader")
{
pusherSolenoid = new Solenoid(SOLENOID_FEEDER);
feedSwitch = new DigitalInput(FEED_SWITCH);
feedMotor = new CANJaguar(MOTOR_FEEDER, CANJaguar::kVoltage);
}
void FrisbeeLoader::InitDefaultCommand()
{
}
void FrisbeeLoader::SetPusher(bool p)
{
pusherSolenoid->Set(p);
}
void FrisbeeLoader::SetFeederMotor(float on)
{
feedMotor->Set(on * FEEDER_MOTOR_VOLTAGE);
}
bool FrisbeeLoader::GetFeedSwitch()
{
return feedSwitch->Get();
}
| C++ |
#include "AutonomousCommand.h"
AutonomousCommand::AutonomousCommand(const char* autoScriptFile)
{
// Only require the launcher, because that is the only thing that we don't
// set via another command.
fireShot = NULL;
gyroRotate = NULL;
//driveCmd = NULL;
Requires(launcher);
si = new ScriptInterpreter();
si->OpenScript(autoScriptFile); // Point the interpereter at our file
si->SetCallback(AutonomousCommand::CallbackSt); // Wire up the callback to our static wrapper
}
AutonomousCommand::~AutonomousCommand()
{
delete si;
delete fireShot;
delete gyroRotate;
this->si = NULL;
this->fireShot = NULL;
this->gyroRotate = NULL;
}
// Called just before this Command runs the first time
void AutonomousCommand::Initialize()
{
this->scriptIsCompleted = false; // We aren't done, we've barely begun!
si->Start(this); // Init the interpreter and tell it to call us back when it needs to.
}
// Called repeatedly when this Command is scheduled to run
void AutonomousCommand::Execute()
{
si->Tick(); // Tick the interpereter so that it processes everything that is scheduled.
}
// Make this return true when this Command no longer needs to run execute()
bool AutonomousCommand::IsFinished()
{
return this->scriptIsCompleted;
}
// Called once after isFinished returns true
void AutonomousCommand::End()
{
this->launcher->SetLauncherSpeed(0.0); // Safety thing
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void AutonomousCommand::Interrupted()
{
this->launcher->SetLauncherSpeed(0.0); // Safety thing
}
void AutonomousCommand::Callback(const char* func, float param)
{
/**
*
* Most of the following follow the same pattern:
* Check if we need to construct the command, and if so, do that.
* Set any parameters on it.
* Start!
*
*/
if (!strcmp(func, "fireShot"))
{
if (!fireShot)
fireShot = new FireShotCommand();
fireShot->Start();
}
else if (!strcmp(func, "rotate"))
{
if (!this->gyroRotate)
this->gyroRotate = new GyroRotateCommand();
this->gyroRotate->SetParams(param, 3.0); // Angle and timeout
this->gyroRotate->Start();
}
/*
else if (!strcmp(func, "drive"))
{
if(!driveCmd)
driveCmd = new DriveDistCommand();
this->driveCmd->SetParams(param); // Go the distance specified
this->driveCmd->Start();
}*/
else if (!strcmp(func, "setShooter"))
{
launcher->SetLauncherSpeed(param);
}
else if (!strcmp(func, "return"))
{
this->scriptIsCompleted = true;
}
else
{
log(kError, "Unknown function called: Func: %s Arg: %s", func, param);
}
}
| C++ |
#ifndef AUTONOMOUSCOMMAND_H
#define AUTONOMOUSCOMMAND_H
#include "../../ScriptParser/ScriptInterpreter.h"
#include "../../CommandBase.h"
#include "../Launcher/FireShotCommand.h"
#include "../Drive/ClosedLoop/GyroRotateCommand.h"
/**
*
*
* @author matthew
*/
class AutonomousCommand: public CommandBase
{
private:
void Callback(const char* func, float arg);
static void CallbackSt(const char* func, float arg, void* ref)
{
((AutonomousCommand*)ref)->Callback(func, arg);
};
ScriptInterpreter* si;
bool scriptIsCompleted;
FireShotCommand* fireShot;
GyroRotateCommand* gyroRotate;
public:
AutonomousCommand(const char* autoScriptFile);
~AutonomousCommand();
virtual void Initialize();
virtual void Execute();
virtual bool IsFinished();
virtual void End();
virtual void Interrupted();
};
#endif
| C++ |
#include "ClimbCommand.h"
ClimbCommand::ClimbCommand() {
Requires(drive);
Requires(climber);
}
// Called just before this Command runs the first time
void ClimbCommand::Initialize()
{
climber->SetArmPosition(true);
climber->SetRobotTip(true);
}
// Called repeatedly when this Command is scheduled to run
void ClimbCommand::Execute()
{
float l = oi->GetStickLeftY();
float r = oi->GetStickRightY();
//float throttle = oi->GetThrottle();
printf("Left: %d, Right: %d\n", l, r);
climber->SetLeftClimbMotor(l);
climber->SetRightClimbMotor(r);
}
// Make this return true when this Command no longer needs to run execute()
bool ClimbCommand::IsFinished() {
return false;
}
// Called once after isFinished returns true
void ClimbCommand::End()
{
climber->SetArmPosition(false);
climber->SetRobotTip(false);
climber->SetLeftClimbMotor(0);
climber->SetRightClimbMotor(0);
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void ClimbCommand::Interrupted()
{
climber->SetArmPosition(false);
climber->SetRobotTip(false);
climber->SetLeftClimbMotor(0);
climber->SetRightClimbMotor(0);
}
| C++ |
#ifndef CLIMBCOMMAND_H
#define CLIMBCOMMAND_H
#include "../../CommandBase.h"
/**
*
*
* @author Matthew
*/
class ClimbCommand: public CommandBase {
public:
ClimbCommand();
virtual void Initialize();
virtual void Execute();
virtual bool IsFinished();
virtual void End();
virtual void Interrupted();
};
#endif
| C++ |
#ifndef LOADFRISBEECOMMAND_H
#define LOADFRISBEECOMMAND_H
#include "Commands/CommandGroup.h"
/**
*
*
* @author Matthew
*/
class LoadFrisbeeCommand: public CommandGroup {
public:
LoadFrisbeeCommand();
};
#endif
| C++ |
#ifndef FEEDUNTILPRESSSTATECOMMAND_H
#define FEEDUNTILPRESSSTATECOMMAND_H
#include "../../CommandBase.h"
/**
*
*
* @author Matthew
*/
class FeedUntilPressStateCommand: public CommandBase {
private:
bool _waitState;
public:
FeedUntilPressStateCommand(bool waitState, double timeout);
virtual void Initialize();
virtual void Execute();
virtual bool IsFinished();
virtual void End();
virtual void Interrupted();
};
#endif
| C++ |
#include "LoadFrisbeeCommand.h"
#include "FeedUntilPressStateCommand.h"
LoadFrisbeeCommand::LoadFrisbeeCommand()
{
AddSequential(new FeedUntilPressStateCommand(false, 1.5));
AddSequential(new FeedUntilPressStateCommand(true, 1.5));
}
| C++ |
#include "UnjamLoaderCommand.h"
UnjamLoaderCommand::UnjamLoaderCommand()
{
Requires(loader);
SetTimeout(0.6);
}
// Called just before this Command runs the first time
void UnjamLoaderCommand::Initialize()
{
loader->SetFeederMotor(-1.0);
}
// Called repeatedly when this Command is scheduled to run
void UnjamLoaderCommand::Execute()
{
}
// Make this return true when this Command no longer needs to run execute()
bool UnjamLoaderCommand::IsFinished()
{
return IsTimedOut();
}
// Called once after isFinished returns true
void UnjamLoaderCommand::End()
{
loader->SetFeederMotor(0);
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void UnjamLoaderCommand::Interrupted()
{
loader->SetFeederMotor(0);
}
| C++ |
#include "FireShotCommand.h"
#include "FeedUntilPressStateCommand.h"
#include "LoadFrisbeeCommand.h"
class FireShotEngageCommand: public CommandBase
{
private:
bool _on;
public:
FireShotEngageCommand(double timeout, bool on)
{
this->SetTimeout(timeout);
this->_on = on;
Requires(loader);
}
// Called just before this Command runs the first time
void Initialize()
{
loader->SetPusher(this->_on); // Put the solenoid in/out based on [_out]
}
// Nothing to do here
void Execute()
{
}
// Return true when we are timed out.
bool IsFinished()
{
return IsTimedOut();
}
void End() // Do nothing
{
}
void Interrupted() // Do nothing
{
}
};
FireShotCommand::FireShotCommand()
{
//this->SetTimeout(1.1);
AddSequential(new FireShotEngageCommand(0.5, true)); // Pusher out
AddSequential(new FireShotEngageCommand(0.5, false)); // Pusher in
AddSequential(new LoadFrisbeeCommand());
}
| C++ |
#ifndef UNJAMLOADERCOMMAND_H
#define UNJAMLOADERCOMMAND_H
#include "../../CommandBase.h"
/**
*
*
* @author Matthew
*/
class UnjamLoaderCommand: public CommandBase
{
public:
UnjamLoaderCommand();
virtual void Initialize();
virtual void Execute();
virtual bool IsFinished();
virtual void End();
virtual void Interrupted();
};
#endif
| C++ |
#include "FeedUntilPressStateCommand.h"
FeedUntilPressStateCommand::FeedUntilPressStateCommand(bool waitState,
double timeout)
{
this->_waitState = waitState;
this->SetTimeout(timeout);
Requires(loader);
}
void FeedUntilPressStateCommand::Initialize()
{
loader->SetFeederMotor(1.0);
}
void FeedUntilPressStateCommand::Execute()
{
}
bool FeedUntilPressStateCommand::IsFinished()
{
bool b = loader->GetFeedSwitch();
return (b == this->_waitState) || this->IsTimedOut();
}
void FeedUntilPressStateCommand::End()
{
loader->SetFeederMotor(false);
}
void FeedUntilPressStateCommand::Interrupted()
{
loader->SetFeederMotor(false);
}
| C++ |
#ifndef STARTLAUNCHERCOMMAND_H
#define STARTLAUNCHERCOMMAND_H
#include "../../../CommandBase.h"
/**
*
*
* @author Matthew
*/
class StartLauncherCommand: public CommandBase
{
public:
StartLauncherCommand();
virtual void Initialize();
virtual void Execute();
virtual bool IsFinished();
virtual void End();
virtual void Interrupted();
};
#endif
| C++ |
#include "StopLauncherCommand.h"
StopLauncherCommand::StopLauncherCommand()
{
Requires(launcher);
}
// Called just before this Command runs the first time
void StopLauncherCommand::Initialize()
{
launcher->SetLauncherSpeed(0);
}
// Called repeatedly when this Command is scheduled to run
void StopLauncherCommand::Execute()
{
}
// Make this return true when this Command no longer needs to run execute()
bool StopLauncherCommand::IsFinished()
{
return false;
}
// Called once after isFinished returns true
void StopLauncherCommand::End()
{
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void StopLauncherCommand::Interrupted()
{
}
| C++ |
#ifndef STOPLAUNCHERCOMMAND_H
#define STOPLAUNCHERCOMMAND_H
#include "../../../CommandBase.h"
/**
*
*
* @author Matthew
*/
class StopLauncherCommand: public CommandBase
{
public:
StopLauncherCommand();
virtual void Initialize();
virtual void Execute();
virtual bool IsFinished();
virtual void End();
virtual void Interrupted();
};
#endif
| C++ |
#include "StartLauncherCommand.h"
StartLauncherCommand::StartLauncherCommand()
{
Requires(launcher);
}
// Called just before this Command runs the first time
void StartLauncherCommand::Initialize()
{
launcher->SetLauncherSpeed(LAUNCHER_SPEED);
}
// Called repeatedly when this Command is scheduled to run
void StartLauncherCommand::Execute()
{
}
// Make this return true when this Command no longer needs to run execute()
bool StartLauncherCommand::IsFinished()
{
return true;
}
// Called once after isFinished returns true
void StartLauncherCommand::End()
{
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void StartLauncherCommand::Interrupted()
{
}
| C++ |
#ifndef FIRESHOTCOMMAND_H
#define FIRESHOTCOMMAND_H
#include "Commands/CommandGroup.h"
#include "../../CommandBase.h"
/**
*
*
* @author Matthew
*/
class FireShotCommand: public CommandGroup
{
public:
FireShotCommand();
};
#endif
| C++ |
#include "SetCoastBrakeCommand.h"
SetCoastBrakeCommand::SetCoastBrakeCommand(CANJaguar::NeutralMode mode)
{
this->m_mode = mode;
isdone = false;
}
// Called just before this Command runs the first time
void SetCoastBrakeCommand::Initialize()
{
drive->SetCoastBrakeMode(this->m_mode);
}
void SetCoastBrakeCommand::Execute()
{
drive->SetCoastBrakeMode(this->m_mode);
isdone = true;
}
// Make this return true when this Command no longer needs to run execute()
bool SetCoastBrakeCommand::IsFinished()
{
return isdone;
}
// Called once after isFinished returns true
void SetCoastBrakeCommand::End()
{
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void SetCoastBrakeCommand::Interrupted()
{
}
| C++ |
#ifndef TANKDRIVECOMMAND_H
#define TANKDRIVECOMMAND_H
#include "../../CommandBase.h"
/**
*
*
* @author Matthew
*/
class TankDriveCommand: public CommandBase
{
public:
TankDriveCommand();
virtual void Execute();
virtual void Initialize();
virtual bool IsFinished();
virtual void End();
virtual void Interrupted();
};
#endif
| C++ |
#include "TankDriveCommand.h"
TankDriveCommand::TankDriveCommand()
{
Requires(drive);
}
void TankDriveCommand::Initialize()
{
}
// Called repeatedly when this Command is scheduled to run
void TankDriveCommand::Execute()
{
float l = oi->GetStickLeftY();
float r = oi->GetStickRightY();
drive->TankDrive(l, r);
}
// Make this return true when this Command no longer needs to run execute()
bool TankDriveCommand::IsFinished()
{
return false;
}
// Called once after isFinished returns true
void TankDriveCommand::End()
{
drive->TankDrive(0, 0);
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void TankDriveCommand::Interrupted()
{
drive->TankDrive(0, 0);
}
| C++ |
#ifndef SETCOASTBRAKECOMMAND_H
#define SETCOASTBRAKECOMMAND_H
#include "../../CommandBase.h"
/**
*
*
* @author Matthew
*/
class SetCoastBrakeCommand: public CommandBase
{
private:
CANJaguar::NeutralMode m_mode;
bool isdone;
public:
SetCoastBrakeCommand(CANJaguar::NeutralMode m_mode);
virtual void Initialize();
virtual void Execute();
virtual bool IsFinished();
virtual void End();
virtual void Interrupted();
};
#endif
| C++ |
#include "ShiftHighCommand.h"
ShiftHighCommand::ShiftHighCommand()
{
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
}
// Called just before this Command runs the first time
void ShiftHighCommand::Initialize()
{
drive->ShiftHigh();
}
bool ShiftHighCommand::IsFinished()
{
return true;
}
void ShiftHighCommand::Execute() { }
void ShiftHighCommand::End() { }
void ShiftHighCommand::Interrupted() { }
| C++ |
#ifndef SHIFTLOWCOMMAND_H
#define SHIFTLOWCOMMAND_H
#include "../../CommandBase.h"
/**
*
*
* @author Matthew
*/
class ShiftLowCommand: public CommandBase
{
public:
ShiftLowCommand();
virtual void Initialize();
virtual bool IsFinished();
virtual void Execute();
virtual void End();
virtual void Interrupted();
};
#endif
| C++ |
#include "ShiftLowCommand.h"
ShiftLowCommand::ShiftLowCommand()
{
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
}
void ShiftLowCommand::Initialize()
{
drive->ShiftLow();
}
bool ShiftLowCommand::IsFinished()
{
return true;
}
void ShiftLowCommand::Execute() { }
void ShiftLowCommand::End() { }
void ShiftLowCommand::Interrupted() { }
| C++ |
#ifndef SHIFTHIGHCOMMAND_H
#define SHIFTHIGHCOMMAND_H
#include "../../CommandBase.h"
/**
*
*
* @author Matthew
*/
class ShiftHighCommand: public CommandBase
{
public:
ShiftHighCommand();
virtual void Initialize();
virtual bool IsFinished();
virtual void Execute();
virtual void End();
virtual void Interrupted();
};
#endif
| C++ |
#ifndef GYROROTATECOMMAND_H
#define GYROROTATECOMMAND_H
#include "../../../CommandBase.h"
#include "WPILib.h"
/**
*
*
* @author Matthew
*/
class GyroRotateCommand: public CommandBase, public PIDOutput, public PIDSource
{
private:
PIDController* pid;
float headingGoal;
public:
GyroRotateCommand();
~GyroRotateCommand();
virtual void Initialize();
virtual void Execute();
virtual bool IsFinished();
virtual void End();
virtual void Interrupted();
void SetParams(double headingDiff, double timeout);
/**
* PIDOuptut implementation
*/
void PIDWrite(float output);
virtual double PIDGet();
};
#endif
| C++ |
#include "GyroRotateCommand.h"
#include "../../../logging.h"
GyroRotateCommand::GyroRotateCommand()
{
//Requires(drive); // We require the drivetrain
}
void GyroRotateCommand::SetParams(double headingDiff, double timeout)
{
this->gyro->ResetYaw();
this->SetTimeout(timeout);
this->headingGoal = headingDiff; // Set heading to current position + the goal
}
GyroRotateCommand::~GyroRotateCommand()
{
if (pid)
{
pid->Disable();
}
delete pid;
pid = NULL;
}
// Called just before this Command runs the first time
void GyroRotateCommand::Initialize()
{
this->gyro->ResetYaw();
pid = new PIDController(GYRO_ROTATE_kP, GYRO_ROTATE_kI, GYRO_ROTATE_kD, this, this, 0.05);
pid->SetSetpoint(headingGoal);
pid->SetOutputRange(-0.85, 0.85); // Steering only goes [-1,1]
pid->Enable();
}
// Called repeatedly when this Command is scheduled to run
void GyroRotateCommand::Execute()
{
}
// Return true when we're done
bool GyroRotateCommand::IsFinished()
{
return IsTimedOut();
}
// Called once after isFinished returns true
void GyroRotateCommand::End()
{
pid->Disable();
drive->RotateSpeed(0);
delete pid;
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
void GyroRotateCommand::Interrupted()
{
pid->Disable();
this->drive->RotateSpeed(0);
}
void GyroRotateCommand::PIDWrite(float f)
{
this->drive->RotateSpeed(f);
}
double GyroRotateCommand::PIDGet()
{
float a = this->gyro->GetYawAngle();
log(kInformation, "Angle: %.1f Sp: %.1f Err: %.2f\n", a, this->headingGoal, a - this->headingGoal);
return a;
}
| C++ |
#include "CommandBase.h"
CommandBase::CommandBase(const char *name) :
Command(name)
{
}
CommandBase::CommandBase() :
Command()
{
}
// Initialize a single static instance of all of your subsystems to NULL
FrisbeeLauncher* CommandBase::launcher = NULL;
FrisbeeLoader* CommandBase::loader = NULL;
DriveSubsystem* CommandBase::drive = NULL;
GyroSubsystem* CommandBase::gyro = NULL;
ClimberSubsystem* CommandBase::climber = NULL;
OI* CommandBase::oi = NULL;
void CommandBase::init()
{
// Create a single static instance of all of your subsystems. The following
// line should be repeated for each subsystem in the project.
launcher = new FrisbeeLauncher();
loader = new FrisbeeLoader();
drive = new DriveSubsystem();
gyro = new GyroSubsystem();
climber = new ClimberSubsystem();
oi = new OI();
}
| C++ |
#include "OI.h"
#include "Commands/Climber/ClimbCommand.h"
#include "Commands/Drive/SetCoastBrakeCommand.h"
#include "Commands/Drive/ShiftHighCommand.h"
#include "Commands/Drive/ShiftLowCommand.h"
#include "Commands/Drive/TankDriveCommand.h"
#include "Commands/Launcher/LauncherMotors/StartLauncherCommand.h"
#include "Commands/Launcher/LauncherMotors/StopLauncherCommand.h"
#include "Commands/Launcher/FireShotCommand.h"
#include "Commands/Launcher/LoadFrisbeeCommand.h"
#include "Commands/Launcher/UnjamLoaderCommand.h"
#include "etc/JoystickAxisButton.h"
OI::OI()
{
/**********************************/
/************** Drive *************/
/**********************************/
joystickDriveLeft = new Joystick(JOYSTICK_DRIVE_LEFT);
joystickDriveRight = new Joystick(JOYSTICK_DRIVE_RIGHT);
// Coast and brake for jags
btnBrake = new JoystickButton(joystickDriveRight, JOYSTICK_BUTTON_BRAKE);
btnBrake->WhenPressed(
new SetCoastBrakeCommand(CANJaguar::kNeutralMode_Brake));
btnCoast = new JoystickButton(joystickDriveRight, JOYSTICK_BUTTON_COAST);
btnCoast->WhenPressed(
new SetCoastBrakeCommand(CANJaguar::kNeutralMode_Coast));
// Define a button for shifting the gearboxes
btnShift = new JoystickButton(joystickDriveRight, JOYSTICK_BUTTON_SHIFT);
btnShift->WhenPressed(new ShiftHighCommand());
btnShift->WhenReleased(new ShiftLowCommand());
/**********************************/
/************ Game Mech ***********/
/**********************************/
joystickGameMech = new Joystick(JOYSTICK_GAME_MECH);
// Fire button
btnFire = new JoystickButton(joystickGameMech, JOYSTICK_BUTTON_FIRE);
btnFire->WhenPressed(new FireShotCommand());
// Load one frisbee after we fire our last frisbee
btnLoad = new JoystickButton(joystickGameMech, JOYSTICK_BUTTON_INIT_SHOT);
btnLoad->WhenPressed(new LoadFrisbeeCommand());
// The two directions of the switch to spin the launcher
btnStartLauncher = new JoystickButton(joystickGameMech,
JOYSTICK_BUTTON_START_LAUNCHER);
btnStartLauncher->WhenPressed(new StartLauncherCommand());
btnStopLauncher = new JoystickButton(joystickGameMech,
JOYSTICK_BUTTON_STOP_LAUNCHER);
btnStopLauncher->WhenPressed(new StopLauncherCommand());
// Run backwards to unload a frisbee
btnUnjam = new JoystickButton(joystickGameMech, JOYSTICK_BUTTON_UNJAM);
btnUnjam->WhenPressed(new UnjamLoaderCommand());
// Tip into the wall, prepare for climb. Start a new ClimbCommand, which interrupts the TankDriveCommand
btnBeginClimb = new JoystickButton(joystickGameMech, JOYSTICK_BUTTON_TIP);
btnBeginClimb->WhenPressed(new ClimbCommand());
// Tip away from the wall, reset to driving. We do this by interrupting the ClimbCommand
btnEndClimb = new JoystickButton(joystickGameMech, JOYSTICK_BUTTON_UNTIP);
btnEndClimb->WhenPressed(new TankDriveCommand());
}
float OI::GetStickLeftY()
{
return joystickDriveLeft->GetAxis(Joystick::kYAxis);
}
float OI::GetStickRightY()
{
return joystickDriveRight->GetAxis(Joystick::kYAxis);
}
float OI::GetThrottle()
{
// Scale from [1, -1] to [0, 1]
//return (joystickDriveRight->GetAxis(Joystick::kThrottleAxis) - 1) / -2;
return 1.0;
}
| C++ |
#ifndef RANDOM_H
#define RANDOM_H
#include <stdint.h>
#define NUM_MAX 624
/*
class Random
{
public:
void getSeed(uint32_t);
// virtual void getState(uint32_t *);
// virtual uint32_t saveState(uint32_t *, uint32_t *);
virtual uint32_t rand();
protected:
uint32_t SEED;
};
*/
class Mersenne_Twister //: public Random
{
public:
Mersenne_Twister(uint32_t);
void getSeed(uint32_t);
uint32_t rand();
private:
int INDEX;
uint32_t MT[NUM_MAX];
uint32_t SEED;
uint32_t W;
uint32_t N;
uint32_t M;
uint32_t R;
uint32_t A;
uint32_t U;
uint32_t S;
uint32_t B;
uint32_t T;
uint32_t C;
uint32_t L;
void initializeGenerator();
void generateNumbers();
};
#endif
| C++ |
#include <fstream>
#include <iostream>
#include <sstream>
#include <cstdlib>
#include "bsp-generator.h"
#include "map.h"
Map::Map(Mersenne_Twister *mt, std::string filename)
{
RNG = mt;
loadMap(filename);
}
Map::~Map()
{
MAP.clear();
}
/*
bool Map::isBlocked(Object *viewer, Object *viewed)
{
int dx, dy, absx, absy, sx, sy;
dx = viewed->x() - viewer->x();
dy = viewed->y() - viewer->y();
absx = abs(dx);
absy = abs(dy);
sx = (dx >= 0) ? 1 : -1;
sy = (dy >= 0) ? 1 : -1;
return true;
}
*/
bool Map::isBlocked(int x, int y)
{
Terrain *t = (Terrain *) MAP[y][x]->head()->object();
if (t->isPassable())
return true;
else
return false;
}
bool Map::isEmpty(int x, int y)
{
if (MAP[y][x]->size() < 2)
return true;
else
return false;
}
char Map::display(int x, int y)
{
return MAP[y][x]->tail()->object()->symbol();
}
int Map::height()
{
return HEIGHT;
}
int Map::level()
{
return LEVEL;
}
int Map::width()
{
return WIDTH;
}
Object *Map::isAt(int x, int y)
{
return MAP[y][x]->head()->object();
}
void Map::add(int x, int y, Object *object)
{
MAP[y][x]->add(object);
}
// This function updates the screen on any objects that may have changed position
void Map::refresh()
{
Object *object;
for (int i=0; i<HEIGHT; i++)
{
for (int j=0; j<WIDTH; j++)
{
for (int k=1; k<MAP[i][j]->size(); k++) // k is initialized to 1 since the head is always a terrain object.
{
object = MAP[i][j]->pop();
MAP[object->y()][object->x()]->push(object);
/* object = MAP[i][j]->isAt(k);
if ((object->x() != j) || (object->y() != i)) // if the object has moved
{
MAP[i][j]->remove(object);
MAP[object->y()][object->x()]->add(object);
}
*/ }
}
}
}
// This function sets the position to the desired tile.
void Map::set(Object *object)
{
MAP[object->y()][object->x()]->add(object);
}
// This function loads the map data from a .map file.
void Map::loadMap(std::string filename)
{
bool hasdownstairs, hasupstairs;
int i, j;
char c;
std::string line;
std::ifstream myfile(filename.c_str());
if (myfile.is_open())
{
getline(myfile, line);
std::stringstream ss;
ss << line;
ss >> WIDTH >> HEIGHT >> LEVEL; // The beginning of every .map file should be the width, height and level number.
std::cerr << "Width: " << WIDTH << " Height: " << HEIGHT << std::endl;
for (i=0; i<HEIGHT; i++)
{
std::vector< Double_Linked_List * > row;
for (j=0; j<WIDTH; j++)
{
row.push_back(new Double_Linked_List());
}
MAP.push_back(row);
}
// Read in the rest of the file.
getline(myfile, line);
ss << line;
if (line == "MAP") // The map is already defined.
{
for (i=0; i<HEIGHT; i++)
{
getline(myfile, line);
for (j=0; j<WIDTH; j++)
{
c = line[j];
if (c == '.')
MAP[i][j]->add(new Terrain("floor", c, i, j, 0, true, false, 10));
else if (c == '#')
MAP[i][j]->add(new Terrain("wall", c, i, j, 0, false, false, 0));
else if (c == '+')
MAP[i][j]->add(new Terrain("door", c, i, j, 0, true, false, 20));
else if (c == '>')
MAP[i][j]->add(new Terrain("downstairs", c, i, j, 0, true, false, 20));
else if (c == '<')
MAP[i][j]->add(new Terrain("upstairs", c, i, j, 0, true, false, 20));
else // This is for undefined characters
MAP[i][j]->add(new Terrain("nothing", ' ', i, j, 0, true, false, 0));
}
}
}
else if (line == "RANDOM") // The map must be procedurally generated.
{
getline(myfile, line);
ss << line;
ss >> hasdownstairs >> hasupstairs;
BSP_Generator *bsp = new BSP_Generator(RNG, WIDTH, HEIGHT, hasdownstairs, hasupstairs);
for (i=0; i<HEIGHT; i++)
{
for (j=0; j<WIDTH; j++)
{
c = bsp->isAt(j, i);
if (c == '.')
MAP[i][j]->add(new Terrain("floor", '.', i, j, 0, true, false, 10));
else if (c == '#')
MAP[i][j]->add(new Terrain("wall", '#', i, j, 0, false, false, 0));
else if (c == '+')
MAP[i][j]->add(new Terrain("door", c, i, j, 0, true, false, 20));
else if (c == '>')
MAP[i][j]->add(new Terrain("downstairs", c, i, j, 0, true, false, 20));
else if (c == '<')
MAP[i][j]->add(new Terrain("upstairs", c, i, j, 0, true, false, 20));
else // This is for undefined characters
MAP[i][j]->add(new Terrain("nothing", ' ', i, j, 0, true, false, 0));
}
}
delete bsp;
}
else
{
std::cerr << "Invalid file: " << filename << "!" << std::endl;
myfile.close();
return;
}
}
else
std::cerr << "Unable to open file " << filename << "!" << std::endl;
myfile.close();
// printMap();
}
// DEBUG ONLY
void Map::printMap()
{
for (int i=0; i<HEIGHT; i++)
{
for (int j=0; j<HEIGHT; j++)
{
for (int k=0; k<MAP[i][j]->size(); k++)
{
std::cerr << MAP[i][j]->isAt(k)->symbol();
}
}
std::cerr << std::endl;
}
}
| C++ |
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <curses.h>
#include "window.h"
Curses_Window::Curses_Window(Map *map)
{
MAP = map;
QUIT = false;
// Initialize ncurses windows
initscr();
keypad(stdscr, true);
nonl();
cbreak();
noecho();
// Create the windows
// GAME = newwin(50, 50, 10, 10);
// STATUS = newwin(50, 20, 10, 70);
// MESSAGE = newwin(10, 50, 0, 10);
}
Curses_Window::~Curses_Window()
{
QUIT = true;
MAP = NULL;
delwin(GAME);
delwin(STATUS);
delwin(MESSAGE);
endwin();
}
void Curses_Window::display(Creature *p)
{
wrefresh(stdscr); // This must me called first, or the screen will remain blank until
// the user has pressed a key.
// Display the game map
// MAP->set(p);
MAP->refresh();
GAME = newwin(50, 50, 5, 0);
for (int i=0; i<MAP->height(); i++)
{
for (int j=0; j<MAP->width(); j++)
{
// mvwaddch(GAME, i, j, MAP->display(j, i)->symbol());
mvwaddch(GAME, i, j, MAP->display(j, i));
}
}
wrefresh(GAME);
// Display the status screen.
STATUS = newwin(50, 30, 5, 60);
char *cstr = new char [p->name().size()+1]; // This is an ugly hack to get around C++'s inability
strcpy(cstr, p->name().c_str()); // to pass a non-POD data type to a variadic function.
mvwprintw(STATUS, 0, 0, "Name:\t\t%s", cstr); // You are not expected to understand this.
delete cstr;
mvwprintw(STATUS, 1, 0, "Location:\t%d %d", p->x(), p->y());
mvwprintw(STATUS, 2, 0, "Hitpoints:\t%d/%d", p->currentHitpoints(), p->maximumHitpoints());
mvwprintw(STATUS, 3, 0, "Energy:\t\t%d/%d", p->currentEnergy(), p->maximumEnergy());
mvwprintw(STATUS, 4, 0, "Strength:\t%d/%d", p->currentStrength(), p->maximumStrength());
mvwprintw(STATUS, 5, 0, "Dexterity:\t%d/%d", p->currentDexterity(), p->maximumDexterity());
mvwprintw(STATUS, 6, 0, "Constitution:\t%d/%d", p->currentConstitution(), p->maximumConstitution());
wrefresh(STATUS);
// Make sure to update the windows.
// wrefresh(GAME);
// wrefresh(STATUS);
// wrefresh(MESSAGE);
// refresh();
}
void Curses_Window::processInput(Creature *p)
{
int x = p->x();
int y = p->y();
int input = getch(); // ncurses function
switch(input)
{
case 'h':
if (MAP->isBlocked(x-1,y))
p->move(x-1,y,0);
break;
case 'j':
if (MAP->isBlocked(x,y+1))
p->move(x,y+1,0);
break;
case 'k':
if (MAP->isBlocked(x,y-1))
p->move(x,y-1,0);
break;
case 'l':
if (MAP->isBlocked(x+1,y))
p->move(x+1,y,0);
break;
case 'y':
if (MAP->isBlocked(x-1,y-1))
p->move(x-1,y-1,0);
break;
case 'u':
if (MAP->isBlocked(x+1,y-1))
p->move(x+1,y-1,0);
break;
case 'b':
if (MAP->isBlocked(x-1,y+1))
p->move(x-1,y+1,0);
break;
case 'n':
if (MAP->isBlocked(x+1,y+1))
p->move(x+1,y+1,0);
break;
case 'q':
QUIT = true;
break;
case '4':
if (MAP->isBlocked(x-1,y))
p->move(x-1,y,0);
break;
case '2':
if (MAP->isBlocked(x,y+1))
p->move(x,y+1,0);
break;
case '8':
if (MAP->isBlocked(x,y-1))
p->move(x,y-1,0);
break;
case '6':
if (MAP->isBlocked(x+1,y))
p->move(x+1,y,0);
break;
case '7':
if (MAP->isBlocked(x-1,y-1))
p->move(x-1,y-1,0);
break;
case '9':
if (MAP->isBlocked(x+1,y-1))
p->move(x+1,y-1,0);
break;
case '1':
if (MAP->isBlocked(x-1,y+1))
p->move(x-1,y+1,0);
break;
case '3':
if (MAP->isBlocked(x+1,y+1))
p->move(x+1,y+1,0);
break;
case KEY_LEFT:
if (MAP->isBlocked(x-1,y))
p->move(x-1,y,0);
break;
case KEY_DOWN:
if (MAP->isBlocked(x,y+1))
p->move(x,y+1,0);
break;
case KEY_UP:
if (MAP->isBlocked(x,y-1))
p->move(x,y-1,0);
break;
case KEY_RIGHT:
if (MAP->isBlocked(x+1,y))
p->move(x+1,y,0);
break;
case KEY_HOME:
if (MAP->isBlocked(x-1,y-1))
p->move(x-1,y-1,0);
break;
case KEY_PPAGE:
if (MAP->isBlocked(x+1,y-1))
p->move(x+1,y-1,0);
break;
case KEY_END:
if (MAP->isBlocked(x-1,y+1))
p->move(x-1,y+1,0);
break;
case KEY_NPAGE:
if (MAP->isBlocked(x+1,y+1))
p->move(x+1,y+1,0);
break;
default:
break;
}
}
bool Curses_Window::quitGame()
{
return QUIT;
}
| C++ |
#ifndef MAP_H
#define MAP_H
#include <string>
#include <vector>
#include "double-linked-list.h"
#include "object.h"
#include "random.h"
class Map
{
public:
Map(Mersenne_Twister *, /*Double_Linked_List *,*/ std::string);
~Map();
// bool isBlocked(Object *, Object *);
bool isBlocked(int, int);
bool isEmpty(int, int);
char display(int, int);
int height();
int level();
int width();
Object *isAt(int, int);
void add(int, int, Object *);
void refresh();
void set(Object *);
private:
int HEIGHT;
int LEVEL;
int WIDTH;
Mersenne_Twister *RNG;
std::vector< std::vector< Double_Linked_List * > > MAP;
void loadMap(std::string);
void printMap();
};
#endif
| C++ |
#ifndef DOUBLE_LINKED_LIST
#define DOUBLE_LINKED_LIST
#include "object.h"
class Node
{
public:
Node(Object *, Node *, Node *);
~Node();
// Object *OBJECT;
// Node *PREVIOUS;
// Node *NEXT;
Node *next();
Node *previous();
Object *object();
void setNext(Node *);
private:
Node *NEXT;
Node *PREVIOUS;
Object *OBJECT;
};
class Double_Linked_List
{
public:
Double_Linked_List();
~Double_Linked_List();
bool contains(Object *);
bool isEmpty();
int size();
Object *isAt(int);
Object *pop();
Node *head();
Node *node(int);
Node *tail();
void add(Object *);
void push(Object *);
void remove(Object *);
private:
Node *HEAD;
Node *TAIL;
int SIZE;
};
#endif
| C++ |
#include <iostream>
#include <cstdlib>
#include "bsp-generator.h"
Room::Room(int xx1, int xx2, int yy1, int yy2)
{
x1 = xx1;
x2 = xx2;
y1 = yy1;
y2 = yy2;
// std::cout << x1 << " " << x2 << " " << y1 << " " << y2 << std::endl;
}
Tree_Node::Tree_Node(Tree_Node *myparent, int x1, int x2, int y1, int y2)
{
room = new Room(x1, x2, y1, y2);
left = NULL;
right = NULL;
parent = myparent;
hasldoor = false;
hasrdoor = false;
hastdoor = false;
hasbdoor = false;
}
Tree_Node::~Tree_Node()
{
if (left != NULL)
delete left;
if (right != NULL)
delete right;
delete room;
}
bool Tree_Node::isLeaf()
{
if ((left == NULL) && (right == NULL))
return true;
else
return false;
}
Tree::Tree(int width, int height)
{
HEAD = new Tree_Node(NULL, 0, width-1, 0, height-1);
}
Tree::~Tree()
{
if (HEAD != NULL)
delete HEAD;
}
Tree_Node *Tree::head()
{
return HEAD;
}
void Tree::printTree()
{
printTreeHelper(HEAD);
}
void Tree::printTreeHelper(Tree_Node *t)
{
if (t->left != NULL)
printTreeHelper(t->left);
if (t->right != NULL)
printTreeHelper(t->right);
std::cout << t->room->x1 << " " << t->room->x2 << " " << t->room->y1 << " " << t->room->y2 << std::endl;
return;
}
BSP_Generator::BSP_Generator(Mersenne_Twister *r, int width, int height, bool hasdownstairs, bool hasupstairs)
{
RNG = r;
WIDTH = width;
HEIGHT = height;
HASDOWNSTAIRS = hasdownstairs;
HASUPSTAIRS = hasupstairs;
BSP = new Tree(WIDTH, HEIGHT);
MAP.resize(WIDTH*HEIGHT);
generateDungeon();
// BSP->printTree();
}
BSP_Generator::~BSP_Generator()
{
if (BSP != NULL)
delete BSP;
}
void BSP_Generator::generateDungeon()
{
for (int i=0; i<HEIGHT; i++)
{
for (int j=0; j<WIDTH; j++)
{
MAP[i*WIDTH+j] = '.'; // Initialize the map to the default floor tile.
// std::cout << MAP[i*WIDTH+j];
}
// std::cout << std::endl;
}
generateHelper(BSP->head());
generateWalls();
generateDoors();
generateStairs();
}
void BSP_Generator::generateHelper(Tree_Node *tn)
{
int x = tn->room->x2 - tn->room->x1;
int y = tn->room->y2 - tn->room->y1;
int d;
int r = RNG->rand();
bool finished = false;
if ((x <= 15) && (y <= 10)) // Do not generate rooms or levels less than 25 square units.
{
tn->left = NULL;
tn->right = NULL;
// std::cout << "Creating Room: " << tn->isLeaf() << tn->room->x1 << " " << tn->room->x2 << " " << tn->room->y1 << " " << tn->room->y2 << std::endl;
return;
}
if ((x <= 15) && (y > 10))
tn->vertical = false;
else if ((x > 15) && (y < 10))
tn->vertical = true;
else if ((r%2) == 0)
tn->vertical = true;
else
tn->vertical = false;
if (tn->vertical == true)
{
while(finished == false)
{
// d = ((RNG->rand() % (x - 7)) + 6) + tn->room->x1;
d = (RNG->rand() % x) + tn->room->x1;
// std::cout << d << std::endl;
if ((d > (tn->room->x1 + 4)) && (d < (tn->room->x2 - 4))) // if d is within the requested range
finished = true;
}
// std::cout << "vertical cut " << d << std::endl;
tn->left = new Tree_Node(tn, tn->room->x1, d, tn->room->y1, tn->room->y2);
tn->right = new Tree_Node(tn, d, tn->room->x2, tn->room->y1, tn->room->y2);
}
else
{
while(!finished)
{
// d = ((RNG->rand() % (x - 7)) + 6) + tn->room->x1;
d = (RNG->rand() % y) + tn->room->y1;
// std::cout << d << std::endl;
if ((d > (tn->room->y1 + 4)) && (d < (tn->room->y2 - 4))) // if d is within the requested range
finished = true;
}
// std::cout << "horizontal cut " << d << std::endl;
tn->left = new Tree_Node(tn, tn->room->x1, tn->room->x2, tn->room->y1, d);
tn->right = new Tree_Node(tn, tn->room->x1, tn->room->x2, d, tn->room->y2);
}
// std::cout << "Creating Room: " << tn->isLeaf() << " " << tn->room->x1 << " " << tn->room->x2 << " " << tn->room->y1 << " " << tn->room->y2 << std::endl;
generateHelper(tn->left);
generateHelper(tn->right);
}
// This function creates walls around each room.
void BSP_Generator::generateWalls()
{
generateWallHelper(BSP->head());
}
void BSP_Generator::generateWallHelper(Tree_Node *t)
{
if (t->isLeaf()) // Only generate walls around the rooms in the leaf nodes of the tree to prevent overlap.
{
Room *r = t->room;
for (int i=r->x1; i<=r->x2; i++)
{
MAP[(r->y1)*WIDTH+i] = '#';
MAP[(r->y2)*WIDTH+i] = '#';
}
for (int j=r->y1; j<=r->y2; j++)
{
MAP[j*WIDTH+r->x1] = '#';
MAP[j*WIDTH+r->x2] = '#';
}
}
else
{
generateWallHelper(t->left);
generateWallHelper(t->right);
}
return;
}
void BSP_Generator::printDungeon()
{
std::cout << "Printing Map:" << std::endl;
for (int i=0; i<HEIGHT; i++)
{
for (int j=0; j<WIDTH; j++)
{
std::cout << MAP[i*WIDTH+j];
}
std::cout << std::endl;
}
}
void BSP_Generator::printRooms()
{
std::cout << "Printing Rooms:" << std::endl;
printHelper(BSP->head());
}
void BSP_Generator::printHelper(Tree_Node *t)
{
if (t->isLeaf() == true)
std::cout << t->room->x1 << " " << t->room->x2 << " " << t->room->y1 << " " << t->room->y2 << std::endl;
else
{
printHelper(t->left);
printHelper(t->right);
}
}
char BSP_Generator::isAt(int x, int y)
{
return MAP[y*WIDTH+x];
}
void BSP_Generator::generateDoors()
{
generateDoorHelper(BSP->head());
}
void BSP_Generator::generateDoorHelper(Tree_Node *t)
{
if (t->isLeaf() == true)
{
// std::cout << "Generating door for " << t->room->x1 << " " << t->room->x2 << " " << t->room->y1 << " " << t->room->y2 << std::endl;
bool hasdoorone = false, hasdoortwo = false;
int a = t->room->x2 - t->room->x1 - 1; // Subtracting one ensures that no door is created in the
int b = t->room->y2 - t->room->y1 - 1; // corners of each room.
int pos;
// First, create doors in vertical walls.
for (int i=1; i<=b; i++) // Check to see if a door has already been created in this wall section.
{
if (MAP[(t->room->y1 + i) * WIDTH + t->room->x1] == '+')
hasdoorone = true;
if (MAP[(t->room->y1 + i) * WIDTH + t->room->x2] == '+')
hasdoortwo = true;
/*
if (hasdoorone==true)
std::cout << "Wall[" << t->room->y1 << ".." << t->room->y2 << "][" << t->room->x1 << "] already has a wall!" << std::endl;
else
std::cout << "Generating door for Wall[" << t->room->y1 << ".." << t->room->y2 << "][" << t->room->x1 << "]!" << std::endl;
if (hasdoortwo==true)
std::cout << "Wall[" << t->room->y1 << ".." << t->room->y2 << "][" << t->room->x2 << "] already has a wall!" << std::endl;
else
std::cout << "Generating door for Wall[" << t->room->y1 << ".." << t->room->y2 << "][" << t->room->x2 << "]!" << std::endl;
*/
}
if ((!hasdoorone) && (t->room->x1 != 0)) // Do not make a door in the left or right border of the map.
{
pos = (RNG->rand() % b) + 1;
MAP[(t->room->y1 + pos) * WIDTH + t->room->x1] = '+';
// std::cout << (t->room->y1 + pos) << " " << t->room->x1 << " " << MAP[(t->room->y1 + pos) * WIDTH + t->room->x2] << std::endl;
}
if ((!hasdoortwo) && (t->room->x2 != (WIDTH-1))) // Do not make a door in the left or right border of the map.
{
pos = (RNG->rand() % b) + 1;
MAP[(t->room->y1 + pos) * WIDTH + t->room->x2] = '+';
// std::cout << (t->room->y1 + pos) << " " << t->room->x2 << " " << MAP[(t->room->y1 + pos) * WIDTH + t->room->x2] << std::endl;
}
hasdoorone = false;
hasdoortwo = false;
// Next, create doors in horizontal walls.
for (int j=1; j<=a; j++) // Check to see if a door has already been created in this wall section.
{
if (MAP[t->room->y1 * WIDTH + (t->room->x1 + j)] == '+')
hasdoorone = true;
if (MAP[t->room->y2 * WIDTH + (t->room->x1 + j)] == '+')
hasdoortwo = true;
/*
if (hasdoorone==true)
std::cout << "Wall[" << t->room->y1 << "][" << t->room->x1 << ".." << t->room->x2 << "] already has a wall!" << std::endl;
else
std::cout << "Generating door for Wall[" << t->room->y1 << "][" << t->room->x1 << ".." << t->room->x2 << "]!" << std::endl;
if (hasdoortwo==true)
std::cout << "Wall[" << t->room->y2 << "][" << t->room->x1 << ".." << t->room->x2 << "] already has a wall!" << std::endl;
else
std::cout << "Generating door for Wall[" << t->room->y2 << "][" << t->room->x1 << ".." << t->room->x2 << "]!" << std::endl;
*/
}
if ((!hasdoorone) && (t->room->y1 != 0)) // Do not make a door in the top or bottom border of the map.
{
pos = (RNG->rand() % a) + 1;
MAP[t->room->y1 * WIDTH + (t->room->x1 + pos)] = '+';
// std::cout << t->room->y1 << " " << t->room->x1 + pos << " " << MAP[t->room->y1 * WIDTH + (t->room->x1 + pos)] << std::endl;
}
if ((!hasdoortwo) && (t->room->y2 != (HEIGHT-1))) // Do not make a door in the top or bottom border of the map.
{
pos = (RNG->rand() % a) + 1;
MAP[t->room->y2 * WIDTH + (t->room->x1 + pos)] = '+';
// std::cout << t->room->y2 << " " << t->room->x1 + pos << " " << MAP[t->room->y2 * WIDTH + (t->room->x1 + pos)] << std::endl;
}
}
else
{
generateDoorHelper(t->left);
generateDoorHelper(t->right);
}
}
void BSP_Generator::generateStairs()
{
bool found = false;
char c;
int x, y;
if (HASDOWNSTAIRS) // Place Down stairs.
{
while (!found)
{
x = RNG->rand() % (WIDTH-1);
y = RNG->rand() % (HEIGHT-1);
if ((MAP[y*WIDTH+x] != '#') || (MAP[y*WIDTH+x] != '+') || (MAP[y*WIDTH+x] != '<'))
{
MAP[y*WIDTH + x] = '>';
found = true;
}
}
}
found = false;
if (HASUPSTAIRS) // Place Up stairs.
{
while (!found)
{
x = RNG->rand() % (WIDTH-1);
y = RNG->rand() % (HEIGHT-1);
if ((MAP[y*WIDTH+x] != '#') || (MAP[y*WIDTH+x] != '+') || (MAP[y*WIDTH+x] != '>'))
{
MAP[y*WIDTH + x] = '<';
found = true;
}
}
}
}
| C++ |
#ifndef WINDOW_H
#define WINDOW_H
#include <string>
#include "object.h"
#include "map.h"
/*
class Window
{
public:
// Window();
// ~Window();
virtual void display(Creature *);
// virtual void print(std::string);
virtual void processInput(Creature *);
protected:
Map *MAP;
};
*/
class Curses_Window //: public Window
{
public:
Curses_Window(Map *);
~Curses_Window();
void display(Creature *);
// void print(std::string);
void processInput(Creature *);
bool quitGame();
public:
bool QUIT;
Map *MAP;
WINDOW *GAME;
WINDOW *STATUS;
WINDOW *MESSAGE;
};
#endif
| C++ |
#include "double-linked-list.h"
Node::Node(Object *object, Node *previous, Node *next)
{
OBJECT = object;
PREVIOUS = previous;
NEXT = next;
}
Node::~Node()
{
if (PREVIOUS != NULL)
PREVIOUS->NEXT = NEXT;
if (NEXT != NULL)
NEXT->PREVIOUS = PREVIOUS;
// delete OBJECT;
}
Node *Node::next()
{
return NEXT;
}
Node *Node::previous()
{
return PREVIOUS;
}
Object *Node::object()
{
return OBJECT;
}
void Node::setNext(Node *next)
{
NEXT = next;
}
Double_Linked_List::Double_Linked_List()
{
HEAD = NULL;
TAIL = HEAD;
SIZE = 0;
}
Double_Linked_List::~Double_Linked_List()
{
if (SIZE == 0)
return;
Node *temp;
TAIL = NULL;
while (HEAD != NULL)
{
temp = HEAD;
HEAD = HEAD->next();
delete temp;
}
}
// This function returns true if the list contains a pointer to the specified object. It returns false otherwise.
bool Double_Linked_List::contains(Object *obj)
{
Node *temp = HEAD;
while (temp != NULL)
{
if (temp->object() == obj)
return true;
temp = temp->next();
}
return false;
}
bool Double_Linked_List::isEmpty()
{
if (SIZE == 0)
return true;
else
return false;
}
int Double_Linked_List::size()
{
return SIZE;
}
Object *Double_Linked_List::isAt(int position)
{
Node *temp;
temp = HEAD;
if (position >= SIZE)
return NULL;
for (int i=0; i<position; i++)
{
temp = temp->next();
}
return temp->object();
}
Object *Double_Linked_List::pop()
{
if (TAIL == NULL)
return NULL;
Node *temp = TAIL;
Object *object = temp->object();
if (TAIL == HEAD) // If this is the only element.
{
HEAD = NULL;
TAIL = NULL;
}
else
TAIL = TAIL->previous();
delete temp;
SIZE--;
return object;
}
Node *Double_Linked_List::head()
{
return HEAD;
}
Node *Double_Linked_List::node(int position)
{
Node *temp = HEAD;
if (position >= SIZE)
return NULL;
for (int i=0; i<position; i++)
{
temp = temp->next();
}
return temp;
}
Node *Double_Linked_List::tail()
{
return TAIL;
}
void Double_Linked_List::add(Object *object)
{
if (SIZE == 0)
{
HEAD = new Node(object, NULL, NULL);
TAIL = HEAD;
}
else
{
TAIL->setNext(new Node(object, TAIL, NULL));
TAIL = TAIL->next();
}
SIZE++;
}
void Double_Linked_List::push(Object *object)
{
add(object);
}
void Double_Linked_List::remove(Object *object)
{
Node *temp = HEAD;
while (temp != NULL)
{
if (temp->object() == object)
{
delete temp;
SIZE--;
return;
}
temp = temp->next();
}
}
| C++ |
#ifndef ASTAR_PATHFINDER_H
#define ASTAR_PATHFINDER_H
#include "double-linked-list.h"
#include "map.h"
class Astar_Pathfinder
{
public:
Astar_Pathfinder(Map *, int, int, int, int);
Double_Linked_List *getPath();
private:
Map *MAP;
Double_Linked_List *CAMEFROM; // the map of navigated nodes
Double_Linked_List *CLOSED; // the closed list
Double_Linked_List *OPEN; // the open list
int X1;
int Y1;
int X2;
int Y2;
bool generatePath();
int estimateDistance(int, int, int, int);
// void reconstructPath(Node *);
};
#endif
| C++ |
#ifndef OBJECT_H
#define OBJECT_H
#include <string>
class Object
{
public:
// Object();
// ~Object();
virtual bool isCreature();// {return false;}
virtual bool isItem();// {return false;}
virtual bool isTerrain();// {return false;}
std::string name();
char symbol();
int x();
int y();
int z();
protected:
std::string NAME;
char SYM;
int X;
int Y;
int Z;
};
class Creature : public Object
{
public:
Creature(std::string, char, int, int, int, bool, int, int, int, int, int, int, int, int, int, int);
bool isCreature();
bool isItem();
bool isTerrain();
bool isPC();
int currentHitpoints();
int currentEnergy();
int currentStrength();
int currentDexterity();
int currentConstitution();
int maximumHitpoints();
int maximumEnergy();
int maximumStrength();
int maximumDexterity();
int maximumConstitution();
void setSymbol(char);
void move(int, int, int);
void setCurrentHitpoints(int);
void setCurrentEnergy(int);
void setCurrentStrength(int);
void setCurrentDexterity(int);
void setCurrentConstitution(int);
void setMaximumHitpoints(int);
void setMaximumEnergy(int);
void setMaximumStrength(int);
void setMaximumDexterity(int);
void setMaximumConstitution(int);
private:
bool IS_PC;
int CURR_HP;
int CURR_EN;
int CURR_STR;
int CURR_DEX;
int CURR_CON;
int MAX_HP;
int MAX_EN;
int MAX_STR;
int MAX_DEX;
int MAX_CON;
};
class Terrain : public Object
{
public:
Terrain(std::string, char, int, int, int, bool, bool, int);
bool isTerrain();
bool isItem();
bool isCreature();
bool isPassable();
bool isWater();
// The following functions are for the benefit of the A* Pathfinder.
int fCost();
int gCost();
int hCost();
int terrainCost();
// int xPrevious();
// int yPrevious();
// void setFCost(int);
void setGCost(int);
void setHCost(int);
// void setXPrevious(int);
// void setYPrevious(int);
private:
bool PASSABLE;
bool WATER;
// The following variables are for the benefit of the A* Pathfinder.
int FCOST;
int GCOST;
int HCOST;
int TCOST;
// int XPREV;
// int YPREV;
};
#endif
| C++ |
#ifndef BSP_GENERATOR_H
#define BSP_GENERATOR_H
#include <vector>
#include "random.h"
struct Room
{
Room(int, int, int, int);
int x1;
int x2;
int y1;
int y2;
};
struct Tree_Node
{
Tree_Node(Tree_Node *, int, int, int, int);
~Tree_Node();
bool isLeaf();
bool vertical;
bool hasldoor;
bool hasrdoor;
bool hastdoor;
bool hasbdoor;
Room *room;
Tree_Node *left;
Tree_Node *parent;
Tree_Node *right;
};
class Tree
{
public:
Tree(int, int);
~Tree();
Tree_Node *head();
void printTree();
private:
Tree_Node *HEAD;
void printTreeHelper(Tree_Node *);
};
class BSP_Generator
{
public:
BSP_Generator(Mersenne_Twister *, int, int, bool, bool);
~BSP_Generator();
void printRooms();
void printDungeon();
char isAt(int, int);
private:
bool HASDOWNSTAIRS;
bool HASUPSTAIRS;
int WIDTH;
int HEIGHT;
Tree *BSP;
Mersenne_Twister *RNG;
std::vector<char> MAP;
void generateDungeon();
void generateHelper(Tree_Node *);
void printHelper(Tree_Node *);
void generateWalls();
void generateWallHelper(Tree_Node *);
void generateDoors();
void generateDoorHelper(Tree_Node *);
void generateStairs();
};
#endif
| C++ |
#include <iostream>
#include <curses.h>
#include <ctime>
#include "map.h"
#include "object.h"
#include "double-linked-list.h"
#include "random.h"
#include "window.h"
using namespace std;
#define STARTX 5
#define STARTY 11
#define STARTZ 0
/*
void display(Creature *p, Map *m)
{
m->refresh();
m->set(p->x(),p->y(),p->symbol());
for (int i=0; i<m->height(); i++)
{
for (int j=0; j<m->width(); j++)
mvaddch(i, j, m->isAt(j, i));
}
mvprintw(m->height(), 0, "Name:\t\tElzair");
mvprintw(m->height()+1, 0, "Location:\t%d %d", p->x(), p->y());
mvprintw(m->height()+2, 0, "Hitpoints:\t%d/%d", p->currentHitpoints(), p->maximumHitpoints());
mvprintw(m->height()+3, 0, "Energy:\t\t%d/%d", p->currentEnergy(), p->maximumEnergy());
mvprintw(m->height()+4, 0, "Strength:\t%d/%d", p->currentStrength(), p->maximumStrength());
mvprintw(m->height()+5, 0, "Dexterity:\t%d/%d", p->currentDexterity(), p->maximumDexterity());
mvprintw(m->height()+6, 0, "Constitution:\t%d/%d", p->currentConstitution(), p->maximumConstitution());
refresh();
}
*/
int main(int argc, char **argv)
{
cerr << "Hello world!" << endl;
string filename;
if (argc == 2)
filename = argv[1];
else
filename = "test.map";
cerr << filename << endl;
Creature *p = new Creature("Player", '@', STARTX, STARTY, STARTZ, true, 100, 100, 10, 10, 10, 100, 100, 10, 10, 10);
// Initialize terrain types
Double_Linked_List *terrain = new Double_Linked_List();
Mersenne_Twister *mt = new Mersenne_Twister(time(NULL));
Map *m = new Map(mt, filename);
m->add(STARTX, STARTY, p);
Curses_Window *window = new Curses_Window(m);
while(!window->quitGame())
{
window->display(p);
window->processInput(p);
}
delete m;
delete p;
delete terrain;
delete mt;
delete window;
return 0;
}
/*
int main(int argc, char **argv)
{
int end = false;
int input;
Map *m = new Map("test.map");
Creature *p = new Creature("Player", '@', STARTX, STARTY, STARTZ, true, 100, 100, 10, 10, 10, 100, 100, 10, 10, 10);
Double_Linked_List *l = new Double_Linked_List();
Mersenne_Twister *mt = new Mersenne_Twister(time(NULL));
initscr();
keypad(stdscr, true);
nonl();
cbreak();
noecho();
while (!end)
{
display(p, m);
input = getch();
int x = p->x();
int y = p->y();
switch(input)
{
case 'h':
if (m->isAt(x-1,y) != '#')
p->move(x-1,y,0);
break;
case 'j':
if (m->isAt(x,y+1) != '#')
p->move(x,y+1,0);
break;
case 'k':
if (m->isAt(x,y-1) != '#')
p->move(x,y-1,0);
break;
case 'l':
if (m->isAt(x+1,y) != '#')
p->move(x+1,y,0);
break;
case 'y':
if (m->isAt(x-1,y-1) != '#')
p->move(x-1,y-1,0);
break;
case 'u':
if (m->isAt(x+1,y-1) != '#')
p->move(x+1,y-1,0);
break;
case 'b':
if (m->isAt(x-1,y+1) != '#')
p->move(x-1,y+1,0);
break;
case 'n':
if (m->isAt(x+1,y+1) != '#')
p->move(x+1,y+1,0);
break;
case 'q':
end = true;
break;
case '4':
if (m->isAt(x-1,y) != '#')
p->move(x-1,y,0);
break;
case '2':
if (m->isAt(x,y+1) != '#')
p->move(x,y+1,0);
break;
case '8':
if (m->isAt(x,y-1) != '#')
p->move(x,y-1,0);
break;
case '6':
if (m->isAt(x+1,y) != '#')
p->move(x+1,y,0);
break;
case '7':
if (m->isAt(x-1,y-1) != '#')
p->move(x-1,y-1,0);
break;
case '9':
if (m->isAt(x+1,y-1) != '#')
p->move(x+1,y-1,0);
break;
case '1':
if (m->isAt(x-1,y+1) != '#')
p->move(x-1,y+1,0);
break;
case '3':
if (m->isAt(x+1,y+1) != '#')
p->move(x+1,y+1,0);
break;
case KEY_LEFT:
if (m->isAt(x-1,y) != '#')
p->move(x-1,y,0);
break;
case KEY_DOWN:
if (m->isAt(x,y+1) != '#')
p->move(x,y+1,0);
break;
case KEY_UP:
if (m->isAt(x,y-1) != '#')
p->move(x,y-1,0);
break;
case KEY_RIGHT:
if (m->isAt(x+1,y) != '#')
p->move(x+1,y,0);
break;
case KEY_HOME:
if (m->isAt(x-1,y-1) != '#')
p->move(x-1,y-1,0);
break;
case KEY_PPAGE:
if (m->isAt(x+1,y-1) != '#')
p->move(x+1,y-1,0);
break;
case KEY_END:
if (m->isAt(x-1,y+1) != '#')
p->move(x-1,y+1,0);
break;
case KEY_NPAGE:
if (m->isAt(x+1,y+1) != '#')
p->move(x+1,y+1,0);
break;
default:
break;
}
}
endwin();
return 0;
}
*/
| C++ |
#include "object.h"
/*
Object::Object()
{
5+1;
}
Object::~Object()
{
5+2;
}
*/
bool Object::isCreature()
{
return false;
}
bool Object::isItem()
{
return false;
}
bool Object::isTerrain()
{
return false;
}
std::string Object::name()
{
return NAME;
}
char Object::symbol()
{
return SYM;
}
int Object::x()
{
return X;
}
int Object::y()
{
return Y;
}
int Object::z()
{
return Z;
}
Creature::Creature(std::string name, char symbol, int x, int y, int z, bool ispc, int hitpoints, int energy, int strength, int dexterity, int constitution, int maximum_hitpoints, int maximum_energy, int maximum_strength, int maximum_dexterity, int maximum_constitution)
{
NAME = name;
X = x;
Y = y;
Z = z;
SYM = symbol;
IS_PC = ispc;
CURR_HP = hitpoints;
CURR_EN = energy;
CURR_STR = strength;
CURR_DEX = dexterity;
CURR_CON = constitution;
MAX_HP = maximum_hitpoints;
MAX_EN = maximum_energy;
MAX_STR = maximum_strength;
MAX_DEX = maximum_dexterity;
MAX_CON = maximum_constitution;
}
bool Creature::isCreature()
{
return true;
}
bool Creature::isItem()
{
return false;
}
bool Creature::isTerrain()
{
return false;
}
bool Creature::isPC()
{
return IS_PC;
}
int Creature::currentHitpoints()
{
return CURR_HP;
}
int Creature::currentEnergy()
{
return CURR_EN;
}
int Creature::currentStrength()
{
return CURR_STR;
}
int Creature::currentDexterity()
{
return CURR_DEX;
}
int Creature::currentConstitution()
{
return CURR_CON;
}
int Creature::maximumHitpoints()
{
return MAX_HP;
}
int Creature::maximumEnergy()
{
return MAX_HP;
}
int Creature::maximumStrength()
{
return MAX_STR;
}
int Creature::maximumDexterity()
{
return MAX_DEX;
}
int Creature::maximumConstitution()
{
return MAX_CON;
}
void Creature::setSymbol(char symbol)
{
SYM = symbol;
}
void Creature::move(int x, int y, int z)
{
X = x;
Y = y;
Z = z;
}
void Creature::setCurrentHitpoints(int hitpoints)
{
CURR_HP = hitpoints;
}
void Creature::setCurrentEnergy(int energy)
{
CURR_EN = energy;
}
void Creature::setCurrentStrength(int strength)
{
CURR_STR = strength;
}
void Creature::setCurrentDexterity(int dexterity)
{
CURR_DEX = dexterity;
}
void Creature::setCurrentConstitution(int constitution)
{
CURR_CON = constitution;
}
void Creature::setMaximumHitpoints(int maximum_hitpoints)
{
MAX_HP = maximum_hitpoints;
}
void Creature::setMaximumEnergy(int maximum_energy)
{
MAX_EN = maximum_energy;
}
void Creature::setMaximumStrength(int maximum_strength)
{
MAX_STR = maximum_strength;
}
void Creature::setMaximumDexterity(int maximum_dexterity)
{
MAX_DEX = maximum_dexterity;
}
void Creature::setMaximumConstitution(int maximum_constitution)
{
MAX_CON = maximum_constitution;
}
Terrain::Terrain(std::string name, char symbol, int x, int y, int z, bool passable, bool water, int cost)
{
NAME = name;
SYM = symbol;
X = x;
Y = y;
Z = z;
PASSABLE= passable;
WATER = water;
TCOST = cost;
FCOST = 0;
GCOST = 0;
HCOST = 0;
}
bool Terrain::isCreature()
{
return false;
}
bool Terrain::isItem()
{
return false;
}
bool Terrain::isTerrain()
{
return true;
}
bool Terrain::isPassable()
{
return PASSABLE;
}
bool Terrain::isWater()
{
return WATER;
}
int Terrain::fCost()
{
return FCOST;
}
int Terrain::gCost()
{
return GCOST;
}
int Terrain::hCost()
{
return HCOST;
}
int Terrain::terrainCost()
{
return TCOST;
}
/*
int Terrain::previousX()
{
return XPREV;
}
int Terrain::previousY()
{
return YPREV;
}
void Terrain::setFCost(int fcost)
{
FCOST = fcost;
}
*/
void Terrain::setGCost(int gcost)
{
GCOST = gcost;
FCOST = GCOST*TCOST + HCOST; // Update the FCOST variable
}
void Terrain::setHCost(int hcost)
{
HCOST = hcost;
FCOST = GCOST*TCOST + HCOST; // Update the FCOST variable
}
/*
void Terrain::setXPrevious(int xprevious)
{
XPREV = xprevious;
}
void Terrain::setYPrevious(int yprevious)
{
YPREV = yprevious;
}
*/
| C++ |
#include "random.h"
/*
void Random::getSeed(uint32_t seed)
{
SEED = seed;
}
*/
Mersenne_Twister::Mersenne_Twister(uint32_t seed)
{
W = 32;
N = 624;
M = 397;
R = 31;
A = 0x9908b0df;
U = 1;;
S = 7;
B = 0x9d2c5680;
T = 15;
C = 0xefc60000;
L = 18;
INDEX = 0;
SEED = seed;
initializeGenerator();
}
// Initialize the generator from a seed
void Mersenne_Twister::initializeGenerator()
{
MT[0] = SEED;
for (int i=1; i<NUM_MAX; i++)
{
MT[i] = (1812433253 * (MT[i-1] ^ (MT[i-1] >> 30))) + i;
}
}
// Generate an array of 624 untempered numbers
void Mersenne_Twister::generateNumbers()
{
int i, y;
for (i=0; i<NUM_MAX; i++)
{
y = ((MT[i]>>31)<<31) + ((MT[(i+1)%NUM_MAX]<<1)>>1);
MT[i] = MT[(i+397)%NUM_MAX] ^ (y>>1);
if ((y%2)==1)
MT[i] ^= 2567483615;
}
}
void Mersenne_Twister::getSeed(uint32_t seed)
{
SEED = seed;
}
// Extract a tempered pseudorandom number based on the index-th value, calling generateNumbers() every 624 numbers
uint32_t Mersenne_Twister::rand()
{
if (INDEX == 0)
generateNumbers();
uint32_t y = MT[INDEX];
y ^= (y >> 11);
y ^= (y << 7 ) & 2636928640;
y ^= (y << 15) & 4022730752;
y ^= (y >> 18);
INDEX = ++INDEX % NUM_MAX;
return y;
}
| C++ |
#include <iostream>
#include "astar-pathfinder.h"
Astar_Pathfinder::Astar_Pathfinder(Map *map, int x1, int y1, int x2, int y2)
{
MAP = map;
X1 = x1;
X2 = x2;
Y1 = y1;
Y2 = y2;
CAMEFROM = new Double_Linked_List();
CLOSED = new Double_Linked_List();
OPEN = new Double_Linked_List();
if (!generatePath())
CAMEFROM = NULL;
}
bool Astar_Pathfinder::generatePath()
{
int i, j, yx, yy, tentative_g_cost;
Node *tempa, *tempb;
Object *object;
Terrain *n, *x, *y, *start, *goal;
// The set of nodes already evaluated.
// closedset := the empty set
// The set of tentative nodes to be evaluated.
// openset := set containing the initial node
// The map of navigated nodes.
// came_from := the empty map
// Distance from start along optimal path.
// g_score[start] := 0
// h_score[start] := heuristic_estimate_of_distance(start, goal)
object = MAP->isAt(X1, Y1);
if (object->isTerrain())
start = (Terrain *) object;
else
std::cerr << "Error in Astar_Pathfinder::generatePath(): object is not terrain!" << std::endl;
object = MAP->isAt(X2, Y2);
if (object->isTerrain())
goal = (Terrain *) object;
else
std::cerr << "Error in Astar_Pathfinder::generatePath(): object is not terrain!" << std::endl;
start->setGCost(0);
start->setHCost(estimateDistance(X1, Y1, X2, Y2));
// Estimated total distance from start to goal through y.
// f_score[start] := h_score[start]
// Add starting position to OPEN list.
OPEN->add((Object *)start);
bool tentative_is_better;
while (!OPEN->isEmpty())
{
tempa = OPEN->node(0);
x = (Terrain *) tempa->object();
// x := the object in openset having the lowest f_score[] value
for (i=1; i<OPEN->size(); i++)
{
tempb = OPEN->node(i);
n = (Terrain *) tempb->object();
if (n->fCost() < x->fCost())
{
x = n;
tempa = tempb;
}
}
if (x == goal)
{
// reconstructPath(came_from, came_from[goal]);
return true;
}
// remove x from openset
OPEN->remove((Object *)x);
// add x to closedset
CLOSED->add((Object *)x);
// foreach y in neighbor_nodes(x)
for (i=-1; i<=1; i++)
{
for (j=-1; j<=1; j++)
{
yx = x->x() + j;
yy = y->y() + i;
if (((i == 0 ) && ( j == 0)) || (yx < 0) || (yx >= MAP->width()) || (yy < 0) || (yy >= MAP->height()))
continue;
y = (Terrain *) MAP->isAt(j, i);
// if y in closedset
if (CLOSED->contains(y))
{
continue;
}
tentative_g_cost = x->gCost() + estimateDistance(x->x(), x->y(), y->x(), y->y());
// if y not in openset
if (!OPEN->contains((Object *)y))
{
OPEN->add(y);
tentative_is_better = true;
}
else if (tentative_g_cost < y->gCost())
tentative_is_better = true;
else
tentative_is_better = false;
if (tentative_is_better == true)
{
// came_from[y] := x
CAMEFROM->add(x);
// g_score[y] := tentative_g_score
y->setGCost(tentative_g_cost);
// h_score[y] := heuristic_estimate_of_distance(y, goal)
y->setHCost(estimateDistance(y->x(), y->y(), goal->x(), goal->y()));
// f_score[y] := g_score[y] + h_score[y]
// Update(closedset,y)
// Update(openset,y)
}
}
}
}
return false;
}
// This function returns a pointer to CAMEFROM, the list containing the path.
Double_Linked_List *Astar_Pathfinder::getPath()
{
return CAMEFROM;
}
// This function estimates the distance from one point to another in Manhattan units.
int Astar_Pathfinder::estimateDistance(int x1, int y1, int x2, int y2)
{
return (x2 - x1) + (y2 - y1);
}
/*
void Astar_Pathfinder::reconstructPath(came_from, current_node)
{
if came_from[current_node] is set
p = reconstruct_path(came_from, came_from[current_node])
return (p + current_node)
else
return current_node
}
*/
| C++ |
/* //device/apps/Quake/quake/src/QW/client/main.c
**
** Copyright 2007, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#include <nativehelper/jni.h>
#include <stdio.h>
#include <assert.h>
#include <private/opengles/gl_context.h>
#include <GLES/gl.h>
// Delegate to "C" routines to do the rest of the processing.
// (We do this because it's difficult to mix the C++ headers
// for JNI and gl_context with the C headers for quake.)
extern "C"
{
void AndroidInit(int width, int height);
int AndroidEvent(int type, int value);
void AndroidStep();
int AndroidQuiting();
}
void
qinit(JNIEnv *env, jobject thiz, /* jobjectArray config, */
jint width, jint height) {
AndroidInit(width, height);
}
jboolean
qevent(JNIEnv *env, jobject thiz, jint type, jint value) {
return AndroidEvent(type, value) ? JNI_TRUE : JNI_FALSE;
}
void
qstep(JNIEnv *env, jobject thiz) {
AndroidStep();
}
jboolean
qquitting(JNIEnv *env, jobject thiz) {
return AndroidQuiting() ? JNI_TRUE : JNI_FALSE;
}
static const char *classPathName = "com/android/quake/QuakeApplication";
static JNINativeMethod methods[] = {
{"init", "(II)V", (void*)qinit },
{"event", "(II)Z", (void*)qevent },
{"step", "()V", (void*)qstep },
{"quitting", "()Z", (void*)qquitting },
};
/*
* Register several native methods for one class.
*/
static int registerNativeMethods(JNIEnv* env, const char* className,
JNINativeMethod* gMethods, int numMethods)
{
jclass clazz;
clazz = env->FindClass(className);
if (clazz == NULL) {
fprintf(stderr,
"Native registration unable to find class '%s'\n", className);
return JNI_FALSE;
}
if (env->RegisterNatives(clazz, gMethods, numMethods) < 0) {
fprintf(stderr, "RegisterNatives failed for '%s'\n", className);
return JNI_FALSE;
}
return JNI_TRUE;
}
/*
* Register native methods for all classes we know about.
*/
static int registerNatives(JNIEnv* env)
{
if (!registerNativeMethods(env, classPathName,
methods, sizeof(methods) / sizeof(methods[0]))) {
return JNI_FALSE;
}
return JNI_TRUE;
}
/*
* Set some test stuff up.
*
* Returns the JNI version on success, -1 on failure.
*/
jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
JNIEnv* env = NULL;
jint result = -1;
if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
fprintf(stderr, "ERROR: GetEnv failed\n");
goto bail;
}
assert(env != NULL);
printf("In mgmain JNI_OnLoad\n");
if (!registerNatives(env)) {
fprintf(stderr, "ERROR: miniglobe native registration failed\n");
goto bail;
}
/* success -- return valid version number */
result = JNI_VERSION_1_4;
bail:
return result;
}
| C++ |
/*
Copyright (C) 1996-1997 Id Software, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// conproc.c
#include <windows.h>
#include "conproc.h"
#include "quakedef.h"
HANDLE heventDone;
HANDLE hfileBuffer;
HANDLE heventChildSend;
HANDLE heventParentSend;
HANDLE hStdout;
HANDLE hStdin;
DWORD RequestProc (DWORD dwNichts);
LPVOID GetMappedBuffer (HANDLE hfileBuffer);
void ReleaseMappedBuffer (LPVOID pBuffer);
BOOL GetScreenBufferLines (int *piLines);
BOOL SetScreenBufferLines (int iLines);
BOOL ReadText (LPTSTR pszText, int iBeginLine, int iEndLine);
BOOL WriteText (LPCTSTR szText);
int CharToCode (char c);
BOOL SetConsoleCXCY(HANDLE hStdout, int cx, int cy);
void InitConProc (HANDLE hFile, HANDLE heventParent, HANDLE heventChild)
{
DWORD dwID;
CONSOLE_SCREEN_BUFFER_INFO info;
int wheight, wwidth;
// ignore if we don't have all the events.
if (!hFile || !heventParent || !heventChild)
return;
hfileBuffer = hFile;
heventParentSend = heventParent;
heventChildSend = heventChild;
// so we'll know when to go away.
heventDone = CreateEvent (NULL, FALSE, FALSE, NULL);
if (!heventDone)
{
Con_SafePrintf ("Couldn't create heventDone\n");
return;
}
if (!CreateThread (NULL,
0,
(LPTHREAD_START_ROUTINE) RequestProc,
0,
0,
&dwID))
{
CloseHandle (heventDone);
Con_SafePrintf ("Couldn't create QHOST thread\n");
return;
}
// save off the input/output handles.
hStdout = GetStdHandle (STD_OUTPUT_HANDLE);
hStdin = GetStdHandle (STD_INPUT_HANDLE);
// force 80 character width, at least 25 character height
SetConsoleCXCY (hStdout, 80, 25);
}
void DeinitConProc (void)
{
if (heventDone)
SetEvent (heventDone);
}
DWORD RequestProc (DWORD dwNichts)
{
int *pBuffer;
DWORD dwRet;
HANDLE heventWait[2];
int iBeginLine, iEndLine;
heventWait[0] = heventParentSend;
heventWait[1] = heventDone;
while (1)
{
dwRet = WaitForMultipleObjects (2, heventWait, FALSE, INFINITE);
// heventDone fired, so we're exiting.
if (dwRet == WAIT_OBJECT_0 + 1)
break;
pBuffer = (int *) GetMappedBuffer (hfileBuffer);
// hfileBuffer is invalid. Just leave.
if (!pBuffer)
{
Con_SafePrintf ("Invalid hfileBuffer\n");
break;
}
switch (pBuffer[0])
{
case CCOM_WRITE_TEXT:
// Param1 : Text
pBuffer[0] = WriteText ((LPCTSTR) (pBuffer + 1));
break;
case CCOM_GET_TEXT:
// Param1 : Begin line
// Param2 : End line
iBeginLine = pBuffer[1];
iEndLine = pBuffer[2];
pBuffer[0] = ReadText ((LPTSTR) (pBuffer + 1), iBeginLine,
iEndLine);
break;
case CCOM_GET_SCR_LINES:
// No params
pBuffer[0] = GetScreenBufferLines (&pBuffer[1]);
break;
case CCOM_SET_SCR_LINES:
// Param1 : Number of lines
pBuffer[0] = SetScreenBufferLines (pBuffer[1]);
break;
}
ReleaseMappedBuffer (pBuffer);
SetEvent (heventChildSend);
}
return 0;
}
LPVOID GetMappedBuffer (HANDLE hfileBuffer)
{
LPVOID pBuffer;
pBuffer = MapViewOfFile (hfileBuffer,
FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0);
return pBuffer;
}
void ReleaseMappedBuffer (LPVOID pBuffer)
{
UnmapViewOfFile (pBuffer);
}
BOOL GetScreenBufferLines (int *piLines)
{
CONSOLE_SCREEN_BUFFER_INFO info;
BOOL bRet;
bRet = GetConsoleScreenBufferInfo (hStdout, &info);
if (bRet)
*piLines = info.dwSize.Y;
return bRet;
}
BOOL SetScreenBufferLines (int iLines)
{
return SetConsoleCXCY (hStdout, 80, iLines);
}
BOOL ReadText (LPTSTR pszText, int iBeginLine, int iEndLine)
{
COORD coord;
DWORD dwRead;
BOOL bRet;
coord.X = 0;
coord.Y = iBeginLine;
bRet = ReadConsoleOutputCharacter(
hStdout,
pszText,
80 * (iEndLine - iBeginLine + 1),
coord,
&dwRead);
// Make sure it's null terminated.
if (bRet)
pszText[dwRead] = '\0';
return bRet;
}
BOOL WriteText (LPCTSTR szText)
{
DWORD dwWritten;
INPUT_RECORD rec;
char upper, *sz;
sz = (LPTSTR) szText;
while (*sz)
{
// 13 is the code for a carriage return (\n) instead of 10.
if (*sz == 10)
*sz = 13;
upper = toupper(*sz);
rec.EventType = KEY_EVENT;
rec.Event.KeyEvent.bKeyDown = TRUE;
rec.Event.KeyEvent.wRepeatCount = 1;
rec.Event.KeyEvent.wVirtualKeyCode = upper;
rec.Event.KeyEvent.wVirtualScanCode = CharToCode (*sz);
rec.Event.KeyEvent.uChar.AsciiChar = *sz;
rec.Event.KeyEvent.uChar.UnicodeChar = *sz;
rec.Event.KeyEvent.dwControlKeyState = isupper(*sz) ? 0x80 : 0x0;
WriteConsoleInput(
hStdin,
&rec,
1,
&dwWritten);
rec.Event.KeyEvent.bKeyDown = FALSE;
WriteConsoleInput(
hStdin,
&rec,
1,
&dwWritten);
sz++;
}
return TRUE;
}
int CharToCode (char c)
{
char upper;
upper = toupper(c);
switch (c)
{
case 13:
return 28;
default:
break;
}
if (isalpha(c))
return (30 + upper - 65);
if (isdigit(c))
return (1 + upper - 47);
return c;
}
BOOL SetConsoleCXCY(HANDLE hStdout, int cx, int cy)
{
CONSOLE_SCREEN_BUFFER_INFO info;
COORD coordMax;
coordMax = GetLargestConsoleWindowSize(hStdout);
if (cy > coordMax.Y)
cy = coordMax.Y;
if (cx > coordMax.X)
cx = coordMax.X;
if (!GetConsoleScreenBufferInfo(hStdout, &info))
return FALSE;
// height
info.srWindow.Left = 0;
info.srWindow.Right = info.dwSize.X - 1;
info.srWindow.Top = 0;
info.srWindow.Bottom = cy - 1;
if (cy < info.dwSize.Y)
{
if (!SetConsoleWindowInfo(hStdout, TRUE, &info.srWindow))
return FALSE;
info.dwSize.Y = cy;
if (!SetConsoleScreenBufferSize(hStdout, info.dwSize))
return FALSE;
}
else if (cy > info.dwSize.Y)
{
info.dwSize.Y = cy;
if (!SetConsoleScreenBufferSize(hStdout, info.dwSize))
return FALSE;
if (!SetConsoleWindowInfo(hStdout, TRUE, &info.srWindow))
return FALSE;
}
if (!GetConsoleScreenBufferInfo(hStdout, &info))
return FALSE;
// width
info.srWindow.Left = 0;
info.srWindow.Right = cx - 1;
info.srWindow.Top = 0;
info.srWindow.Bottom = info.dwSize.Y - 1;
if (cx < info.dwSize.X)
{
if (!SetConsoleWindowInfo(hStdout, TRUE, &info.srWindow))
return FALSE;
info.dwSize.X = cx;
if (!SetConsoleScreenBufferSize(hStdout, info.dwSize))
return FALSE;
}
else if (cx > info.dwSize.X)
{
info.dwSize.X = cx;
if (!SetConsoleScreenBufferSize(hStdout, info.dwSize))
return FALSE;
if (!SetConsoleWindowInfo(hStdout, TRUE, &info.srWindow))
return FALSE;
}
return TRUE;
}
| C++ |
/*
Copyright (C) 1996-1997 Id Software, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// sv_main.c -- server main program
#include "quakedef.h"
server_t sv;
server_static_t svs;
char localmodels[MAX_MODELS][5]; // inline model names for precache
//============================================================================
/*
===============
SV_Init
===============
*/
void SV_Init (void)
{
int i;
extern cvar_t sv_maxvelocity;
extern cvar_t sv_gravity;
extern cvar_t sv_nostep;
extern cvar_t sv_friction;
extern cvar_t sv_edgefriction;
extern cvar_t sv_stopspeed;
extern cvar_t sv_maxspeed;
extern cvar_t sv_accelerate;
extern cvar_t sv_idealpitchscale;
extern cvar_t sv_aim;
Cvar_RegisterVariable (&sv_maxvelocity);
Cvar_RegisterVariable (&sv_gravity);
Cvar_RegisterVariable (&sv_friction);
Cvar_RegisterVariable (&sv_edgefriction);
Cvar_RegisterVariable (&sv_stopspeed);
Cvar_RegisterVariable (&sv_maxspeed);
Cvar_RegisterVariable (&sv_accelerate);
Cvar_RegisterVariable (&sv_idealpitchscale);
Cvar_RegisterVariable (&sv_aim);
Cvar_RegisterVariable (&sv_nostep);
for (i=0 ; i<MAX_MODELS ; i++)
sprintf (localmodels[i], "*%i", i);
}
/*
=============================================================================
EVENT MESSAGES
=============================================================================
*/
/*
==================
SV_StartParticle
Make sure the event gets sent to all clients
==================
*/
void SV_StartParticle (vec3_t org, vec3_t dir, int color, int count)
{
int i, v;
if (sv.datagram.cursize > MAX_DATAGRAM-16)
return;
MSG_WriteByte (&sv.datagram, svc_particle);
MSG_WriteCoord (&sv.datagram, org[0]);
MSG_WriteCoord (&sv.datagram, org[1]);
MSG_WriteCoord (&sv.datagram, org[2]);
for (i=0 ; i<3 ; i++)
{
v = (int)(dir[i]*16);
if (v > 127)
v = 127;
else if (v < -128)
v = -128;
MSG_WriteChar (&sv.datagram, v);
}
MSG_WriteByte (&sv.datagram, count);
MSG_WriteByte (&sv.datagram, color);
}
/*
==================
SV_StartSound
Each entity can have eight independant sound sources, like voice,
weapon, feet, etc.
Channel 0 is an auto-allocate channel, the others override anything
allready running on that entity/channel pair.
An attenuation of 0 will play full volume everywhere in the level.
Larger attenuations will drop off. (max 4 attenuation)
==================
*/
void SV_StartSound (edict_t *entity, int channel, const char *sample, int volume,
float attenuation)
{
int sound_num;
int field_mask;
int i;
int ent;
if (volume < 0 || volume > 255)
Sys_Error ("SV_StartSound: volume = %i", volume);
if (attenuation < 0 || attenuation > 4)
Sys_Error ("SV_StartSound: attenuation = %f", attenuation);
if (channel < 0 || channel > 7)
Sys_Error ("SV_StartSound: channel = %i", channel);
if (sv.datagram.cursize > MAX_DATAGRAM-16)
return;
// find precache number for sound
for (sound_num=1 ; sound_num<MAX_SOUNDS
&& sv.sound_precache[sound_num] ; sound_num++)
if (!strcmp(sample, sv.sound_precache[sound_num]))
break;
if ( sound_num == MAX_SOUNDS || !sv.sound_precache[sound_num] )
{
Con_Printf ("SV_StartSound: %s not precacheed\n", sample);
return;
}
ent = NUM_FOR_EDICT(entity);
channel = (ent<<3) | channel;
field_mask = 0;
if (volume != DEFAULT_SOUND_PACKET_VOLUME)
field_mask |= SND_VOLUME;
if (attenuation != DEFAULT_SOUND_PACKET_ATTENUATION)
field_mask |= SND_ATTENUATION;
// directed messages go only to the entity the are targeted on
MSG_WriteByte (&sv.datagram, svc_sound);
MSG_WriteByte (&sv.datagram, field_mask);
if (field_mask & SND_VOLUME)
MSG_WriteByte (&sv.datagram, volume);
if (field_mask & SND_ATTENUATION)
MSG_WriteByte (&sv.datagram, (int) (attenuation*64));
MSG_WriteShort (&sv.datagram, channel);
MSG_WriteByte (&sv.datagram, sound_num);
for (i=0 ; i<3 ; i++)
MSG_WriteCoord (&sv.datagram, entity->u.v.origin[i]+0.5*(entity->u.v.mins[i]+entity->u.v.maxs[i]));
}
/*
==============================================================================
CLIENT SPAWNING
==============================================================================
*/
/*
================
SV_SendServerinfo
Sends the first message from the server to a connected client.
This will be sent on the initial connection and upon each server load.
================
*/
void SV_SendServerinfo (client_t *client)
{
char **s;
char message[2048];
MSG_WriteByte (&client->message, svc_print);
sprintf (message, "%c\nVERSION %4.2f SERVER (%i CRC)", 2, VERSION, pr_crc);
MSG_WriteString (&client->message,message);
MSG_WriteByte (&client->message, svc_serverinfo);
MSG_WriteLong (&client->message, PROTOCOL_VERSION);
MSG_WriteByte (&client->message, svs.maxclients);
if (!coop.value && deathmatch.value)
MSG_WriteByte (&client->message, GAME_DEATHMATCH);
else
MSG_WriteByte (&client->message, GAME_COOP);
sprintf (message, pr_strings+sv.edicts->u.v.message);
MSG_WriteString (&client->message,message);
for (s = sv.model_precache+1 ; *s ; s++)
MSG_WriteString (&client->message, *s);
MSG_WriteByte (&client->message, 0);
for (s = sv.sound_precache+1 ; *s ; s++)
MSG_WriteString (&client->message, *s);
MSG_WriteByte (&client->message, 0);
// send music
MSG_WriteByte (&client->message, svc_cdtrack);
MSG_WriteByte (&client->message, (int) sv.edicts->u.v.sounds);
MSG_WriteByte (&client->message, (int) sv.edicts->u.v.sounds);
// set view
MSG_WriteByte (&client->message, svc_setview);
MSG_WriteShort (&client->message, NUM_FOR_EDICT(client->edict));
MSG_WriteByte (&client->message, svc_signonnum);
MSG_WriteByte (&client->message, 1);
client->sendsignon = true;
client->spawned = false; // need prespawn, spawn, etc
}
/*
================
SV_ConnectClient
Initializes a client_t for a new net connection. This will only be called
once for a player each game, not once for each level change.
================
*/
void SV_ConnectClient (int clientnum)
{
edict_t *ent;
client_t *client;
int edictnum;
struct qsocket_s *netconnection;
int i;
float spawn_parms[NUM_SPAWN_PARMS];
client = svs.clients + clientnum;
Con_DPrintf ("Client %s connected\n", client->netconnection->address);
edictnum = clientnum+1;
ent = EDICT_NUM(edictnum);
// set up the client_t
netconnection = client->netconnection;
if (sv.loadgame)
memcpy (spawn_parms, client->spawn_parms, sizeof(spawn_parms));
memset (client, 0, sizeof(*client));
client->netconnection = netconnection;
strcpy (client->name, "unconnected");
client->active = true;
client->spawned = false;
client->edict = ent;
client->message.data = client->msgbuf;
client->message.maxsize = sizeof(client->msgbuf);
client->message.allowoverflow = true; // we can catch it
#ifdef IDGODS
client->privileged = IsID(&client->netconnection->addr);
#else
client->privileged = false;
#endif
if (sv.loadgame)
memcpy (client->spawn_parms, spawn_parms, sizeof(spawn_parms));
else
{
// call the progs to get default spawn parms for the new client
PR_ExecuteProgram (pr_global_struct->SetNewParms);
for (i=0 ; i<NUM_SPAWN_PARMS ; i++)
client->spawn_parms[i] = (&pr_global_struct->parm1)[i];
}
SV_SendServerinfo (client);
}
/*
===================
SV_CheckForNewClients
===================
*/
void SV_CheckForNewClients (void)
{
struct qsocket_s *ret;
int i;
//
// check for new connections
//
while (1)
{
ret = NET_CheckNewConnections ();
if (!ret)
break;
//
// init a new client structure
//
for (i=0 ; i<svs.maxclients ; i++)
if (!svs.clients[i].active)
break;
if (i == svs.maxclients)
Sys_Error ("Host_CheckForNewClients: no free clients");
svs.clients[i].netconnection = ret;
SV_ConnectClient (i);
net_activeconnections++;
}
}
/*
===============================================================================
FRAME UPDATES
===============================================================================
*/
/*
==================
SV_ClearDatagram
==================
*/
void SV_ClearDatagram (void)
{
SZ_Clear (&sv.datagram);
}
/*
=============================================================================
The PVS must include a small area around the client to allow head bobbing
or other small motion on the client side. Otherwise, a bob might cause an
entity that should be visible to not show up, especially when the bob
crosses a waterline.
=============================================================================
*/
int fatbytes;
byte fatpvs[MAX_MAP_LEAFS/8];
void SV_AddToFatPVS (vec3_t org, mnode_t *node)
{
int i;
byte *pvs;
mplane_t *plane;
float d;
while (1)
{
// if this is a leaf, accumulate the pvs bits
if (node->contents < 0)
{
if (node->contents != CONTENTS_SOLID)
{
pvs = Mod_LeafPVS ( (mleaf_t *)node, sv.worldmodel);
for (i=0 ; i<fatbytes ; i++)
fatpvs[i] |= pvs[i];
}
return;
}
plane = node->plane;
d = DotProduct (org, plane->normal) - plane->dist;
if (d > 8)
node = node->children[0];
else if (d < -8)
node = node->children[1];
else
{ // go down both
SV_AddToFatPVS (org, node->children[0]);
node = node->children[1];
}
}
}
/*
=============
SV_FatPVS
Calculates a PVS that is the inclusive or of all leafs within 8 pixels of the
given point.
=============
*/
byte *SV_FatPVS (vec3_t org)
{
fatbytes = (sv.worldmodel->numleafs+31)>>3;
Q_memset (fatpvs, 0, fatbytes);
SV_AddToFatPVS (org, sv.worldmodel->nodes);
return fatpvs;
}
//=============================================================================
/*
=============
SV_WriteEntitiesToClient
=============
*/
void SV_WriteEntitiesToClient (edict_t *clent, sizebuf_t *msg)
{
int e, i;
int bits;
byte *pvs;
vec3_t org;
float miss;
edict_t *ent;
// find the client's PVS
VectorAdd (clent->u.v.origin, clent->u.v.view_ofs, org);
pvs = SV_FatPVS (org);
// send over all entities (excpet the client) that touch the pvs
ent = NEXT_EDICT(sv.edicts);
for (e=1 ; e<sv.num_edicts ; e++, ent = NEXT_EDICT(ent))
{
#ifdef QUAKE2
// don't send if flagged for NODRAW and there are no lighting effects
if (ent->u.v.effects == EF_NODRAW)
continue;
#endif
// ignore if not touching a PV leaf
if (ent != clent) // clent is ALLWAYS sent
{
// ignore ents without visible models
if (!ent->u.v.modelindex || !pr_strings[ent->u.v.model])
continue;
for (i=0 ; i < ent->num_leafs ; i++)
if (pvs[ent->leafnums[i] >> 3] & (1 << (ent->leafnums[i]&7) ))
break;
if (i == ent->num_leafs)
continue; // not visible
}
if (msg->maxsize - msg->cursize < 16)
{
Con_Printf ("packet overflow\n");
return;
}
// send an update
bits = 0;
for (i=0 ; i<3 ; i++)
{
miss = ent->u.v.origin[i] - ent->baseline.origin[i];
if ( miss < -0.1 || miss > 0.1 )
bits |= U_ORIGIN1<<i;
}
if ( ent->u.v.angles[0] != ent->baseline.angles[0] )
bits |= U_ANGLE1;
if ( ent->u.v.angles[1] != ent->baseline.angles[1] )
bits |= U_ANGLE2;
if ( ent->u.v.angles[2] != ent->baseline.angles[2] )
bits |= U_ANGLE3;
if (ent->u.v.movetype == MOVETYPE_STEP)
bits |= U_NOLERP; // don't mess up the step animation
if (ent->baseline.colormap != ent->u.v.colormap)
bits |= U_COLORMAP;
if (ent->baseline.skin != ent->u.v.skin)
bits |= U_SKIN;
if (ent->baseline.frame != ent->u.v.frame)
bits |= U_FRAME;
if (ent->baseline.effects != ent->u.v.effects)
bits |= U_EFFECTS;
if (ent->baseline.modelindex != ent->u.v.modelindex)
bits |= U_MODEL;
if (e >= 256)
bits |= U_LONGENTITY;
if (bits >= 256)
bits |= U_MOREBITS;
//
// write the message
//
MSG_WriteByte (msg,bits | U_SIGNAL);
if (bits & U_MOREBITS)
MSG_WriteByte (msg, bits>>8);
if (bits & U_LONGENTITY)
MSG_WriteShort (msg,e);
else
MSG_WriteByte (msg,e);
if (bits & U_MODEL)
MSG_WriteByte (msg, (int) ent->u.v.modelindex);
if (bits & U_FRAME)
MSG_WriteByte (msg, (int) ent->u.v.frame);
if (bits & U_COLORMAP)
MSG_WriteByte (msg, (int) ent->u.v.colormap);
if (bits & U_SKIN)
MSG_WriteByte (msg, (int) ent->u.v.skin);
if (bits & U_EFFECTS)
MSG_WriteByte (msg, (int) ent->u.v.effects);
if (bits & U_ORIGIN1)
MSG_WriteCoord (msg, ent->u.v.origin[0]);
if (bits & U_ANGLE1)
MSG_WriteAngle(msg, ent->u.v.angles[0]);
if (bits & U_ORIGIN2)
MSG_WriteCoord (msg, ent->u.v.origin[1]);
if (bits & U_ANGLE2)
MSG_WriteAngle(msg, ent->u.v.angles[1]);
if (bits & U_ORIGIN3)
MSG_WriteCoord (msg, ent->u.v.origin[2]);
if (bits & U_ANGLE3)
MSG_WriteAngle(msg, ent->u.v.angles[2]);
}
}
/*
=============
SV_CleanupEnts
=============
*/
void SV_CleanupEnts (void)
{
int e;
edict_t *ent;
ent = NEXT_EDICT(sv.edicts);
for (e=1 ; e<sv.num_edicts ; e++, ent = NEXT_EDICT(ent))
{
ent->u.v.effects = (int)ent->u.v.effects & ~EF_MUZZLEFLASH;
}
}
/*
==================
SV_WriteClientdataToMessage
==================
*/
void SV_WriteClientdataToMessage (edict_t *ent, sizebuf_t *msg)
{
int bits;
int i;
edict_t *other;
int items;
#ifndef QUAKE2
eval_t *val;
#endif
//
// send a damage message
//
if (ent->u.v.dmg_take || ent->u.v.dmg_save)
{
other = PROG_TO_EDICT(ent->u.v.dmg_inflictor);
MSG_WriteByte (msg, svc_damage);
MSG_WriteByte (msg, (int) ent->u.v.dmg_save);
MSG_WriteByte (msg, (int) ent->u.v.dmg_take);
for (i=0 ; i<3 ; i++)
MSG_WriteCoord (msg, other->u.v.origin[i] + 0.5*(other->u.v.mins[i] + other->u.v.maxs[i]));
ent->u.v.dmg_take = 0;
ent->u.v.dmg_save = 0;
}
//
// send the current viewpos offset from the view entity
//
SV_SetIdealPitch (); // how much to look up / down ideally
// a fixangle might get lost in a dropped packet. Oh well.
if ( ent->u.v.fixangle )
{
MSG_WriteByte (msg, svc_setangle);
for (i=0 ; i < 3 ; i++)
MSG_WriteAngle (msg, ent->u.v.angles[i] );
ent->u.v.fixangle = 0;
}
bits = 0;
if (ent->u.v.view_ofs[2] != DEFAULT_VIEWHEIGHT)
bits |= SU_VIEWHEIGHT;
if (ent->u.v.idealpitch)
bits |= SU_IDEALPITCH;
// stuff the sigil bits into the high bits of items for sbar, or else
// mix in items2
#ifdef QUAKE2
items = (int)ent->u.v.items | ((int)ent->u.v.items2 << 23);
#else
val = GetEdictFieldValue(ent, "items2");
if (val)
items = (int)ent->u.v.items | ((int)val->_float << 23);
else
items = (int)ent->u.v.items | ((int)pr_global_struct->serverflags << 28);
#endif
bits |= SU_ITEMS;
if ( (int)ent->u.v.flags & FL_ONGROUND)
bits |= SU_ONGROUND;
if ( ent->u.v.waterlevel >= 2)
bits |= SU_INWATER;
for (i=0 ; i<3 ; i++)
{
if (ent->u.v.punchangle[i])
bits |= (SU_PUNCH1<<i);
if (ent->u.v.velocity[i])
bits |= (SU_VELOCITY1<<i);
}
if (ent->u.v.weaponframe)
bits |= SU_WEAPONFRAME;
if (ent->u.v.armorvalue)
bits |= SU_ARMOR;
// if (ent->u.v.weapon)
bits |= SU_WEAPON;
// send the data
MSG_WriteByte (msg, svc_clientdata);
MSG_WriteShort (msg, bits);
if (bits & SU_VIEWHEIGHT)
MSG_WriteChar (msg, (int) ent->u.v.view_ofs[2]);
if (bits & SU_IDEALPITCH)
MSG_WriteChar (msg, (int) ent->u.v.idealpitch);
for (i=0 ; i<3 ; i++)
{
if (bits & (SU_PUNCH1<<i))
MSG_WriteChar (msg, (int) ent->u.v.punchangle[i]);
if (bits & (SU_VELOCITY1<<i))
MSG_WriteChar (msg, (int) ent->u.v.velocity[i]/16);
}
// [always sent] if (bits & SU_ITEMS)
MSG_WriteLong (msg, items);
if (bits & SU_WEAPONFRAME)
MSG_WriteByte (msg, (int) ent->u.v.weaponframe);
if (bits & SU_ARMOR)
MSG_WriteByte (msg, (int) ent->u.v.armorvalue);
if (bits & SU_WEAPON)
MSG_WriteByte (msg, SV_ModelIndex(pr_strings+ent->u.v.weaponmodel));
MSG_WriteShort (msg, (int) ent->u.v.health);
MSG_WriteByte (msg, (int) ent->u.v.currentammo);
MSG_WriteByte (msg, (int) ent->u.v.ammo_shells);
MSG_WriteByte (msg, (int) ent->u.v.ammo_nails);
MSG_WriteByte (msg, (int) ent->u.v.ammo_rockets);
MSG_WriteByte (msg, (int) ent->u.v.ammo_cells);
if (standard_quake)
{
MSG_WriteByte (msg, (int) ent->u.v.weapon);
}
else
{
for(i=0;i<32;i++)
{
if ( ((int)ent->u.v.weapon) & (1<<i) )
{
MSG_WriteByte (msg, i);
break;
}
}
}
}
/*
=======================
SV_SendClientDatagram
=======================
*/
qboolean SV_SendClientDatagram (client_t *client)
{
byte buf[MAX_DATAGRAM];
sizebuf_t msg;
msg.data = buf;
msg.maxsize = sizeof(buf);
msg.cursize = 0;
MSG_WriteByte (&msg, svc_time);
MSG_WriteFloat (&msg, sv.time);
// add the client specific data to the datagram
SV_WriteClientdataToMessage (client->edict, &msg);
SV_WriteEntitiesToClient (client->edict, &msg);
// copy the server datagram if there is space
if (msg.cursize + sv.datagram.cursize < msg.maxsize)
SZ_Write (&msg, sv.datagram.data, sv.datagram.cursize);
// send the datagram
if (NET_SendUnreliableMessage (client->netconnection, &msg) == -1)
{
SV_DropClient (true);// if the message couldn't send, kick off
return false;
}
return true;
}
/*
=======================
SV_UpdateToReliableMessages
=======================
*/
void SV_UpdateToReliableMessages (void)
{
int i, j;
client_t *client;
// check for changes to be sent over the reliable streams
for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
{
if (host_client->old_frags != host_client->edict->u.v.frags)
{
for (j=0, client = svs.clients ; j<svs.maxclients ; j++, client++)
{
if (!client->active)
continue;
MSG_WriteByte (&client->message, svc_updatefrags);
MSG_WriteByte (&client->message, i);
MSG_WriteShort (&client->message, (int) host_client->edict->u.v.frags);
}
host_client->old_frags = (int) host_client->edict->u.v.frags;
}
}
for (j=0, client = svs.clients ; j<svs.maxclients ; j++, client++)
{
if (!client->active)
continue;
SZ_Write (&client->message, sv.reliable_datagram.data, sv.reliable_datagram.cursize);
}
SZ_Clear (&sv.reliable_datagram);
}
/*
=======================
SV_SendNop
Send a nop message without trashing or sending the accumulated client
message buffer
=======================
*/
void SV_SendNop (client_t *client)
{
sizebuf_t msg;
byte buf[4];
msg.data = buf;
msg.maxsize = sizeof(buf);
msg.cursize = 0;
MSG_WriteChar (&msg, svc_nop);
if (NET_SendUnreliableMessage (client->netconnection, &msg) == -1)
SV_DropClient (true); // if the message couldn't send, kick off
client->last_message = realtime;
}
/*
=======================
SV_SendClientMessages
=======================
*/
void SV_SendClientMessages (void)
{
int i;
// update frags, names, etc
SV_UpdateToReliableMessages ();
// build individual updates
for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
{
if (!host_client->active)
continue;
if (host_client->spawned)
{
if (!SV_SendClientDatagram (host_client))
continue;
}
else
{
// the player isn't totally in the game yet
// send small keepalive messages if too much time has passed
// send a full message when the next signon stage has been requested
// some other message data (name changes, etc) may accumulate
// between signon stages
if (!host_client->sendsignon)
{
if (realtime - host_client->last_message > 5)
SV_SendNop (host_client);
continue; // don't send out non-signon messages
}
}
// check for an overflowed message. Should only happen
// on a very fucked up connection that backs up a lot, then
// changes level
if (host_client->message.overflowed)
{
SV_DropClient (true);
host_client->message.overflowed = false;
continue;
}
if (host_client->message.cursize || host_client->dropasap)
{
if (!NET_CanSendMessage (host_client->netconnection))
{
// I_Printf ("can't write\n");
continue;
}
if (host_client->dropasap)
SV_DropClient (false); // went to another level
else
{
if (NET_SendMessage (host_client->netconnection
, &host_client->message) == -1)
SV_DropClient (true); // if the message couldn't send, kick off
SZ_Clear (&host_client->message);
host_client->last_message = realtime;
host_client->sendsignon = false;
}
}
}
// clear muzzle flashes
SV_CleanupEnts ();
}
/*
==============================================================================
SERVER SPAWNING
==============================================================================
*/
/*
================
SV_ModelIndex
================
*/
int SV_ModelIndex (const char *name)
{
int i;
if (!name || !name[0])
return 0;
for (i=0 ; i<MAX_MODELS && sv.model_precache[i] ; i++)
if (!strcmp(sv.model_precache[i], name))
return i;
if (i==MAX_MODELS || !sv.model_precache[i])
Sys_Error ("SV_ModelIndex: model %s not precached", name);
return i;
}
/*
================
SV_CreateBaseline
================
*/
void SV_CreateBaseline (void)
{
int i;
edict_t *svent;
int entnum;
for (entnum = 0; entnum < sv.num_edicts ; entnum++)
{
// get the current server version
svent = EDICT_NUM(entnum);
if (svent->free)
continue;
if (entnum > svs.maxclients && !svent->u.v.modelindex)
continue;
//
// create entity baseline
//
VectorCopy (svent->u.v.origin, svent->baseline.origin);
VectorCopy (svent->u.v.angles, svent->baseline.angles);
svent->baseline.frame = (int) svent->u.v.frame;
svent->baseline.skin = (int) svent->u.v.skin;
if (entnum > 0 && entnum <= svs.maxclients)
{
svent->baseline.colormap = entnum;
svent->baseline.modelindex = SV_ModelIndex("progs/player.mdl");
}
else
{
svent->baseline.colormap = 0;
svent->baseline.modelindex =
SV_ModelIndex(pr_strings + svent->u.v.model);
}
//
// add to the message
//
MSG_WriteByte (&sv.signon,svc_spawnbaseline);
MSG_WriteShort (&sv.signon,entnum);
MSG_WriteByte (&sv.signon, svent->baseline.modelindex);
MSG_WriteByte (&sv.signon, svent->baseline.frame);
MSG_WriteByte (&sv.signon, svent->baseline.colormap);
MSG_WriteByte (&sv.signon, svent->baseline.skin);
for (i=0 ; i<3 ; i++)
{
MSG_WriteCoord(&sv.signon, svent->baseline.origin[i]);
MSG_WriteAngle(&sv.signon, svent->baseline.angles[i]);
}
}
}
/*
================
SV_SendReconnect
Tell all the clients that the server is changing levels
================
*/
void SV_SendReconnect (void)
{
char data[128];
sizebuf_t msg;
msg.data = (byte*) data;
msg.cursize = 0;
msg.maxsize = sizeof(data);
MSG_WriteChar (&msg, svc_stufftext);
MSG_WriteString (&msg, "reconnect\n");
NET_SendToAll (&msg, 5);
if (cls.state != ca_dedicated)
#ifdef QUAKE2
Cbuf_InsertText ("reconnect\n");
#else
Cmd_ExecuteString2 ("reconnect\n", src_command);
#endif
}
/*
================
SV_SaveSpawnparms
Grabs the current state of each client for saving across the
transition to another level
================
*/
void SV_SaveSpawnparms (void)
{
int i, j;
svs.serverflags = (int) pr_global_struct->serverflags;
for (i=0, host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
{
if (!host_client->active)
continue;
// call the progs to get default spawn parms for the new client
pr_global_struct->self = EDICT_TO_PROG(host_client->edict);
PR_ExecuteProgram (pr_global_struct->SetChangeParms);
for (j=0 ; j<NUM_SPAWN_PARMS ; j++)
host_client->spawn_parms[j] = (&pr_global_struct->parm1)[j];
}
}
/*
================
SV_SpawnServer
This is called at the start of each level
================
*/
extern float scr_centertime_off;
#ifdef QUAKE2
void SV_SpawnServer (char *server, char *startspot)
#else
void SV_SpawnServer (char *server)
#endif
{
edict_t *ent;
int i;
// let's not have any servers with no name
if (hostname.string[0] == 0)
Cvar_Set ("hostname", "UNNAMED");
scr_centertime_off = 0;
Con_DPrintf ("SpawnServer: %s\n",server);
svs.changelevel_issued = false; // now safe to issue another
//
// tell all connected clients that we are going to a new level
//
if (sv.active)
{
SV_SendReconnect ();
}
//
// make cvars consistant
//
if (coop.value)
Cvar_SetValue ("deathmatch", 0);
current_skill = (int)(skill.value + 0.5);
if (current_skill < 0)
current_skill = 0;
if (current_skill > 3)
current_skill = 3;
Cvar_SetValue ("skill", (float)current_skill);
//
// set up the new server
//
Host_ClearMemory ();
memset (&sv, 0, sizeof(sv));
strcpy (sv.name, server);
#ifdef QUAKE2
if (startspot)
strcpy(sv.startspot, startspot);
#endif
// load progs to get entity field count
PR_LoadProgs ();
// allocate server memory
sv.max_edicts = MAX_EDICTS;
sv.edicts = (edict_t*) Hunk_AllocName (sv.max_edicts*pr_edict_size, "edicts");
sv.datagram.maxsize = sizeof(sv.datagram_buf);
sv.datagram.cursize = 0;
sv.datagram.data = sv.datagram_buf;
sv.reliable_datagram.maxsize = sizeof(sv.reliable_datagram_buf);
sv.reliable_datagram.cursize = 0;
sv.reliable_datagram.data = sv.reliable_datagram_buf;
sv.signon.maxsize = sizeof(sv.signon_buf);
sv.signon.cursize = 0;
sv.signon.data = sv.signon_buf;
// leave slots at start for clients only
sv.num_edicts = svs.maxclients+1;
for (i=0 ; i<svs.maxclients ; i++)
{
ent = EDICT_NUM(i+1);
svs.clients[i].edict = ent;
}
sv.state = ss_loading;
sv.paused = false;
sv.time = 1.0;
strcpy (sv.name, server);
sprintf (sv.modelname,"maps/%s.bsp", server);
sv.worldmodel = Mod_ForName (sv.modelname, false);
if (!sv.worldmodel)
{
Con_Printf ("Couldn't spawn server %s\n", sv.modelname);
sv.active = false;
return;
}
sv.models[1] = sv.worldmodel;
//
// clear world interaction links
//
SV_ClearWorld ();
sv.sound_precache[0] = pr_strings;
sv.model_precache[0] = pr_strings;
sv.model_precache[1] = sv.modelname;
for (i=1 ; i<sv.worldmodel->numsubmodels ; i++)
{
sv.model_precache[1+i] = localmodels[i];
sv.models[i+1] = Mod_ForName (localmodels[i], false);
}
//
// load the rest of the entities
//
ent = EDICT_NUM(0);
memset (&ent->u.v, 0, progs->entityfields * 4);
ent->free = false;
ent->u.v.model = sv.worldmodel->name - pr_strings;
ent->u.v.modelindex = 1; // world model
ent->u.v.solid = SOLID_BSP;
ent->u.v.movetype = MOVETYPE_PUSH;
if (coop.value)
pr_global_struct->coop = coop.value;
else
pr_global_struct->deathmatch = deathmatch.value;
pr_global_struct->mapname = sv.name - pr_strings;
#ifdef QUAKE2
pr_global_struct->startspot = sv.startspot - pr_strings;
#endif
// serverflags are for cross level information (sigils)
pr_global_struct->serverflags = svs.serverflags;
ED_LoadFromFile (sv.worldmodel->entities);
sv.active = true;
// all setup is completed, any further precache statements are errors
sv.state = ss_active;
// run two frames to allow everything to settle
host_frametime = 0.1;
SV_Physics ();
SV_Physics ();
// create a baseline for more efficient communications
SV_CreateBaseline ();
// send serverinfo to all connected clients
for (i=0,host_client = svs.clients ; i<svs.maxclients ; i++, host_client++)
if (host_client->active)
SV_SendServerinfo (host_client);
Con_DPrintf ("Server spawned.\n");
}
| C++ |
/*
Copyright (C) 1996-1997 Id Software, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "quakedef.h"
#include "net_loop.h"
#include "net_dgrm.h"
net_driver_t net_drivers[MAX_NET_DRIVERS] =
{
{
"Loopback",
false,
Loop_Init,
Loop_Listen,
Loop_SearchForHosts,
Loop_Connect,
Loop_CheckNewConnections,
Loop_GetMessage,
Loop_SendMessage,
Loop_SendUnreliableMessage,
Loop_CanSendMessage,
Loop_CanSendUnreliableMessage,
Loop_Close,
Loop_Shutdown,
0
}
,
{
"Datagram",
false,
Datagram_Init,
Datagram_Listen,
Datagram_SearchForHosts,
Datagram_Connect,
Datagram_CheckNewConnections,
Datagram_GetMessage,
Datagram_SendMessage,
Datagram_SendUnreliableMessage,
Datagram_CanSendMessage,
Datagram_CanSendUnreliableMessage,
Datagram_Close,
Datagram_Shutdown,
0
}
};
int net_numdrivers = 2;
#include "net_udp.h"
net_landriver_t net_landrivers[MAX_NET_DRIVERS] =
{
{
"UDP",
false,
0,
UDP_Init,
UDP_Shutdown,
UDP_Listen,
UDP_OpenSocket,
UDP_CloseSocket,
UDP_Connect,
UDP_CheckNewConnections,
UDP_Read,
UDP_Write,
UDP_Broadcast,
UDP_AddrToString,
UDP_StringToAddr,
UDP_GetSocketAddr,
UDP_GetNameFromAddr,
UDP_GetAddrFromName,
UDP_AddrCompare,
UDP_GetSocketPort,
UDP_SetSocketPort
}
};
int net_numlandrivers = 1;
| C++ |
/*
Copyright (C) 1996-1997 Id Software, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// r_misc.c
#include "quakedef.h"
/*
==================
R_InitTextures
==================
*/
void R_InitTextures (void)
{
int x,y, m;
byte *dest;
// create a simple checkerboard texture for the default
r_notexture_mip = (texture_t*) Hunk_AllocName (sizeof(texture_t) + 16*16+8*8+4*4+2*2, "notexture");
r_notexture_mip->width = r_notexture_mip->height = 16;
r_notexture_mip->offsets[0] = sizeof(texture_t);
r_notexture_mip->offsets[1] = r_notexture_mip->offsets[0] + 16*16;
r_notexture_mip->offsets[2] = r_notexture_mip->offsets[1] + 8*8;
r_notexture_mip->offsets[3] = r_notexture_mip->offsets[2] + 4*4;
for (m=0 ; m<4 ; m++)
{
dest = (byte *)r_notexture_mip + r_notexture_mip->offsets[m];
for (y=0 ; y< (16>>m) ; y++)
for (x=0 ; x< (16>>m) ; x++)
{
if ( (y< (8>>m) ) ^ (x< (8>>m) ) )
*dest++ = 0;
else
*dest++ = 0xff;
}
}
}
byte dottexture[8][8] =
{
{0,1,1,0,0,0,0,0},
{1,1,1,1,0,0,0,0},
{1,1,1,1,0,0,0,0},
{0,1,1,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
};
// Initialize particle texture, can be called multiple times.
void R_InitParticleTexture2 (void)
{
int x,y;
byte data[8][8][4];
//
// particle texture
//
GL_Bind(particletexture);
for (x=0 ; x<8 ; x++)
{
for (y=0 ; y<8 ; y++)
{
data[y][x][0] = 255;
data[y][x][1] = 255;
data[y][x][2] = 255;
data[y][x][3] = dottexture[x][y]*255;
}
}
glTexImage2DHelper (GL_TEXTURE_2D, 0, gl_alpha_format, 8, 8, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
void R_InitParticleTexture (void)
{
particletexture = texture_extension_number++;
R_InitParticleTexture2();
}
/*
===============
R_Envmap_f
Grab six views for environment mapping tests
===============
*/
void R_Envmap_f (void)
{
#ifdef USE_OPENGLES
// Not implemented
#else
byte buffer[256*256*4];
char name[1024];
glDrawBuffer (GL_FRONT);
glReadBuffer (GL_FRONT);
envmap = true;
r_refdef.vrect.x = 0;
r_refdef.vrect.y = 0;
r_refdef.vrect.width = 256;
r_refdef.vrect.height = 256;
r_refdef.viewangles[0] = 0;
r_refdef.viewangles[1] = 0;
r_refdef.viewangles[2] = 0;
GL_BeginRendering (&glx, &gly, &glwidth, &glheight);
R_RenderView ();
glReadPixels (0, 0, 256, 256, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
COM_WriteFile ("env0.rgb", buffer, sizeof(buffer));
r_refdef.viewangles[1] = 90;
GL_BeginRendering (&glx, &gly, &glwidth, &glheight);
R_RenderView ();
glReadPixels (0, 0, 256, 256, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
COM_WriteFile ("env1.rgb", buffer, sizeof(buffer));
r_refdef.viewangles[1] = 180;
GL_BeginRendering (&glx, &gly, &glwidth, &glheight);
R_RenderView ();
glReadPixels (0, 0, 256, 256, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
COM_WriteFile ("env2.rgb", buffer, sizeof(buffer));
r_refdef.viewangles[1] = 270;
GL_BeginRendering (&glx, &gly, &glwidth, &glheight);
R_RenderView ();
glReadPixels (0, 0, 256, 256, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
COM_WriteFile ("env3.rgb", buffer, sizeof(buffer));
r_refdef.viewangles[0] = -90;
r_refdef.viewangles[1] = 0;
GL_BeginRendering (&glx, &gly, &glwidth, &glheight);
R_RenderView ();
glReadPixels (0, 0, 256, 256, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
COM_WriteFile ("env4.rgb", buffer, sizeof(buffer));
r_refdef.viewangles[0] = 90;
r_refdef.viewangles[1] = 0;
GL_BeginRendering (&glx, &gly, &glwidth, &glheight);
R_RenderView ();
glReadPixels (0, 0, 256, 256, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
COM_WriteFile ("env5.rgb", buffer, sizeof(buffer));
envmap = false;
glDrawBuffer (GL_BACK);
glReadBuffer (GL_BACK);
GL_EndRendering ();
#endif
}
/*
===============
R_Init
===============
*/
void R_Init (void)
{
extern byte *hunk_base;
extern cvar_t gl_finish;
Cmd_AddCommand ("timerefresh", R_TimeRefresh_f);
Cmd_AddCommand ("envmap", R_Envmap_f);
Cmd_AddCommand ("pointfile", R_ReadPointFile_f);
Cvar_RegisterVariable (&r_norefresh);
Cvar_RegisterVariable (&r_lightmap);
Cvar_RegisterVariable (&r_fullbright);
Cvar_RegisterVariable (&r_drawentities);
Cvar_RegisterVariable (&r_drawviewmodel);
Cvar_RegisterVariable (&r_shadows);
Cvar_RegisterVariable (&r_mirroralpha);
Cvar_RegisterVariable (&r_wateralpha);
Cvar_RegisterVariable (&r_dynamic);
Cvar_RegisterVariable (&r_novis);
Cvar_RegisterVariable (&r_speeds);
Cvar_RegisterVariable (&gl_finish);
Cvar_RegisterVariable (&gl_clear);
Cvar_RegisterVariable (&gl_texsort);
if (gl_mtexable)
Cvar_SetValue ("gl_texsort", 0.0);
Cvar_RegisterVariable (&gl_cull);
Cvar_RegisterVariable (&gl_smoothmodels);
Cvar_RegisterVariable (&gl_affinemodels);
Cvar_RegisterVariable (&gl_polyblend);
Cvar_RegisterVariable (&gl_flashblend);
Cvar_RegisterVariable (&gl_playermip);
Cvar_RegisterVariable (&gl_nocolors);
Cvar_RegisterVariable (&gl_keeptjunctions);
Cvar_RegisterVariable (&gl_reporttjunctions);
Cvar_RegisterVariable (&gl_doubleeyes);
R_InitParticles ();
R_InitParticleTexture ();
#ifdef GLTEST
Test_Init ();
#endif
playertextures = texture_extension_number;
texture_extension_number += 16;
}
/*
===============
R_TranslatePlayerSkin
Translates a skin texture by the per-player color lookup
===============
*/
void R_TranslatePlayerSkin (int playernum)
{
int top, bottom;
byte translate[256];
unsigned translate32[256];
int i, j, s;
model_t *model;
aliashdr_t *paliashdr;
byte *original;
unsigned* pixels;
unsigned *out;
unsigned scaled_width, scaled_height;
int inwidth, inheight;
byte *inrow;
unsigned frac, fracstep;
extern byte **player_8bit_texels_tbl;
GL_DisableMultitexture();
top = cl.scores[playernum].colors & 0xf0;
bottom = (cl.scores[playernum].colors &15)<<4;
for (i=0 ; i<256 ; i++)
translate[i] = i;
for (i=0 ; i<16 ; i++)
{
if (top < 128) // the artists made some backwards ranges. sigh.
translate[TOP_RANGE+i] = top+i;
else
translate[TOP_RANGE+i] = top+15-i;
if (bottom < 128)
translate[BOTTOM_RANGE+i] = bottom+i;
else
translate[BOTTOM_RANGE+i] = bottom+15-i;
}
//
// locate the original skin pixels
//
currententity = &cl_entities[1+playernum];
model = currententity->model;
if (!model)
return; // player doesn't have a model yet
if (model->type != mod_alias)
return; // only translate skins on alias models
paliashdr = (aliashdr_t *)Mod_Extradata (model);
s = paliashdr->skinwidth * paliashdr->skinheight;
if (currententity->skinnum < 0 || currententity->skinnum >= paliashdr->numskins) {
Con_Printf("(%d): Invalid player skin #%d\n", playernum, currententity->skinnum);
original = (byte *)paliashdr + paliashdr->texels[0];
} else
original = (byte *)paliashdr + paliashdr->texels[currententity->skinnum];
if (s & 3)
Sys_Error ("R_TranslateSkin: s&3");
inwidth = paliashdr->skinwidth;
inheight = paliashdr->skinheight;
// because this happens during gameplay, do it fast
// instead of sending it through gl_upload 8
GL_Bind(playertextures + playernum);
#if 0
byte translated[320*200];
for (i=0 ; i<s ; i+=4)
{
translated[i] = translate[original[i]];
translated[i+1] = translate[original[i+1]];
translated[i+2] = translate[original[i+2]];
translated[i+3] = translate[original[i+3]];
}
// don't mipmap these, because it takes too long
GL_Upload8 (translated, paliashdr->skinwidth, paliashdr->skinheight, false, false, true);
#else
scaled_width = (unsigned int) (gl_max_size.value < 512 ? gl_max_size.value : 512);
scaled_height = (unsigned int) (gl_max_size.value < 256 ? gl_max_size.value : 256);
// allow users to crunch sizes down even more if they want
scaled_width >>= (int)gl_playermip.value;
scaled_height >>= (int)gl_playermip.value;
#define PIXEL_COUNT (512*256)
#define PIXELS_SIZE (PIXEL_COUNT * sizeof(unsigned))
pixels = (unsigned*) malloc(PIXELS_SIZE);
if(!pixels)
{
Sys_Error("Out of memory.");
}
if (VID_Is8bit()) { // 8bit texture upload
byte *out2;
out2 = (byte *)pixels;
memset(pixels, 0, PIXELS_SIZE);
fracstep = inwidth*0x10000/scaled_width;
for (i=0 ; i< (int) scaled_height ; i++, out2 += scaled_width)
{
inrow = original + inwidth*(i*inheight/scaled_height);
frac = fracstep >> 1;
for (j=0 ; j< (int) scaled_width ; j+=4)
{
out2[j] = translate[inrow[frac>>16]];
frac += fracstep;
out2[j+1] = translate[inrow[frac>>16]];
frac += fracstep;
out2[j+2] = translate[inrow[frac>>16]];
frac += fracstep;
out2[j+3] = translate[inrow[frac>>16]];
frac += fracstep;
}
}
GL_Upload8_EXT ((byte *)pixels, scaled_width, scaled_height, false, false);
}
else
{
for (i=0 ; i<256 ; i++)
translate32[i] = d_8to24table[translate[i]];
out = pixels;
fracstep = inwidth*0x10000/scaled_width;
for (i=0 ; i< (int) scaled_height ; i++, out += scaled_width)
{
inrow = original + inwidth*(i*inheight/scaled_height);
frac = fracstep >> 1;
for (j=0 ; j< (int) scaled_width ; j+=4)
{
out[j] = translate32[inrow[frac>>16]];
frac += fracstep;
out[j+1] = translate32[inrow[frac>>16]];
frac += fracstep;
out[j+2] = translate32[inrow[frac>>16]];
frac += fracstep;
out[j+3] = translate32[inrow[frac>>16]];
frac += fracstep;
}
}
glTexImage2DHelper (GL_TEXTURE_2D, 0, gl_solid_format, scaled_width, scaled_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
#endif
free(pixels);
}
/*
===============
R_NewMap
===============
*/
void R_NewMap (void)
{
int i;
for (i=0 ; i<256 ; i++)
d_lightstylevalue[i] = 264; // normal light value
memset (&r_worldentity, 0, sizeof(r_worldentity));
r_worldentity.model = cl.worldmodel;
// clear out efrags in case the level hasn't been reloaded
// FIXME: is this one short?
for (i=0 ; i<cl.worldmodel->numleafs ; i++)
cl.worldmodel->leafs[i].efrags = NULL;
r_viewleaf = NULL;
R_ClearParticles ();
GL_BuildLightmaps ();
// identify sky texture
skytexturenum = -1;
mirrortexturenum = -1;
for (i=0 ; i<cl.worldmodel->numtextures ; i++)
{
if (!cl.worldmodel->textures[i])
continue;
if (!Q_strncmp(cl.worldmodel->textures[i]->name,"sky",3) )
skytexturenum = i;
if (!Q_strncmp(cl.worldmodel->textures[i]->name,"window02_1",10) )
mirrortexturenum = i;
cl.worldmodel->textures[i]->texturechain = NULL;
}
#ifdef QUAKE2
R_LoadSkys ();
#endif
}
/*
====================
R_TimeRefresh_f
For program optimization
====================
*/
void R_TimeRefresh_f (void)
{
#ifdef USE_OPENGLES
// Not implemented
Con_Printf("TimeRefresh not implemented.\n");
#else
int i;
float start, stop, time;
int startangle;
vrect_t vr;
glDrawBuffer (GL_FRONT);
glFinish ();
start = Sys_FloatTime ();
for (i=0 ; i<128 ; i++)
{
r_refdef.viewangles[1] = i/128.0*360.0;
R_RenderView ();
}
glFinish ();
stop = Sys_FloatTime ();
time = stop-start;
Con_Printf ("%f seconds (%f fps)\n", time, 128/time);
glDrawBuffer (GL_BACK);
GL_EndRendering ();
#endif
}
void D_FlushCaches (void)
{
}
| C++ |
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <limits.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <string.h>
#include <ctype.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <errno.h>
#include "quakedef.h"
qboolean isDedicated;
int nostdout = 0;
char *basedir = ".";
char *cachedir = "/tmp";
cvar_t sys_linerefresh = {"sys_linerefresh","0"};// set for entity display
// =======================================================================
// General routines
// =======================================================================
void Sys_DebugNumber(int y, int val)
{
}
/*
void Sys_Printf (char *fmt, ...)
{
va_list argptr;
char text[1024];
va_start (argptr,fmt);
vsprintf (text,fmt,argptr);
va_end (argptr);
fprintf(stderr, "%s", text);
Con_Print (text);
}
void Sys_Printf (char *fmt, ...)
{
va_list argptr;
char text[1024], *t_p;
int l, r;
if (nostdout)
return;
va_start (argptr,fmt);
vsprintf (text,fmt,argptr);
va_end (argptr);
l = strlen(text);
t_p = text;
// make sure everything goes through, even though we are non-blocking
while (l)
{
r = write (1, text, l);
if (r != l)
sleep (0);
if (r > 0)
{
t_p += r;
l -= r;
}
}
}
*/
void Sys_Printf (char *fmt, ...)
{
va_list argptr;
char text[1024];
unsigned char *p;
va_start (argptr,fmt);
vsprintf (text,fmt,argptr);
va_end (argptr);
if (strlen(text) > sizeof(text))
Sys_Error("memory overwrite in Sys_Printf");
if (nostdout)
return;
for (p = (unsigned char *)text; *p; p++) {
*p &= 0x7f;
if ((*p > 128 || *p < 32) && *p != 10 && *p != 13 && *p != 9)
printf("[%02x]", *p);
else
putc(*p, stdout);
}
}
#if 0
static char end1[] =
"\x1b[?7h\x1b[40m\x1b[2J\x1b[0;1;41m\x1b[1;1H QUAKE: The Doomed Dimension \x1b[33mby \x1b[44mid\x1b[41m Software \x1b[2;1H ---------------------------------------------------------------------------- \x1b[3;1H CALL 1-800-IDGAMES TO ORDER OR FOR TECHNICAL SUPPORT \x1b[4;1H PRICE: $45.00 (PRICES MAY VARY OUTSIDE THE US.) \x1b[5;1H \x1b[6;1H \x1b[37mYes! You only have one fourth of this incredible epic. That is because most \x1b[7;1H of you have paid us nothing or at most, very little. You could steal the \x1b[8;1H game from a friend. But we both know you'll be punished by God if you do. \x1b[9;1H \x1b[33mWHY RISK ETERNAL DAMNATION? CALL 1-800-IDGAMES AND BUY NOW! \x1b[10;1H \x1b[37mRemember, we love you almost as much as He does. \x1b[11;1H \x1b[12;1H \x1b[33mProgramming: \x1b[37mJohn Carmack, Michael Abrash, John Cash \x1b[13;1H \x1b[33mDesign: \x1b[37mJohn Romero, Sandy Petersen, American McGee, Tim Willits \x1b[14;1H \x1b[33mArt: \x1b[37mAdrian Carmack, Kevin Cloud \x1b[15;1H \x1b[33mBiz: \x1b[37mJay Wilbur, Mike Wilson, Donna Jackson \x1b[16;1H \x1b[33mProjects: \x1b[37mShawn Green \x1b[33mSupport: \x1b[37mBarrett Alexander \x1b[17;1H \x1b[33mSound Effects: \x1b[37mTrent Reznor and Nine Inch Nails \x1b[18;1H For other information or details on ordering outside the US, check out the \x1b[19;1H files accompanying QUAKE or our website at http://www.idsoftware.com. \x1b[20;1H \x1b[0;41mQuake is a trademark of Id Software, inc., (c)1996 Id Software, inc. \x1b[21;1H All rights reserved. NIN logo is a registered trademark licensed to \x1b[22;1H Nothing Interactive, Inc. All rights reserved. \x1b[40m\x1b[23;1H\x1b[0m";
static char end2[] =
"\x1b[?7h\x1b[40m\x1b[2J\x1b[0;1;41m\x1b[1;1H QUAKE \x1b[33mby \x1b[44mid\x1b[41m Software \x1b[2;1H ----------------------------------------------------------------------------- \x1b[3;1H \x1b[37mWhy did you quit from the registered version of QUAKE? Did the \x1b[4;1H scary monsters frighten you? Or did Mr. Sandman tug at your \x1b[5;1H little lids? No matter! What is important is you love our \x1b[6;1H game, and gave us your money. Congratulations, you are probably \x1b[7;1H not a thief. \x1b[8;1H Thank You. \x1b[9;1H \x1b[33;44mid\x1b[41m Software is: \x1b[10;1H PROGRAMMING: \x1b[37mJohn Carmack, Michael Abrash, John Cash \x1b[11;1H \x1b[33mDESIGN: \x1b[37mJohn Romero, Sandy Petersen, American McGee, Tim Willits \x1b[12;1H \x1b[33mART: \x1b[37mAdrian Carmack, Kevin Cloud \x1b[13;1H \x1b[33mBIZ: \x1b[37mJay Wilbur, Mike Wilson \x1b[33mPROJECTS MAN: \x1b[37mShawn Green \x1b[14;1H \x1b[33mBIZ ASSIST: \x1b[37mDonna Jackson \x1b[33mSUPPORT: \x1b[37mBarrett Alexander \x1b[15;1H \x1b[33mSOUND EFFECTS AND MUSIC: \x1b[37mTrent Reznor and Nine Inch Nails \x1b[16;1H \x1b[17;1H If you need help running QUAKE refer to the text files in the \x1b[18;1H QUAKE directory, or our website at http://www.idsoftware.com. \x1b[19;1H If all else fails, call our technical support at 1-800-IDGAMES. \x1b[20;1H \x1b[0;41mQuake is a trademark of Id Software, inc., (c)1996 Id Software, inc. \x1b[21;1H All rights reserved. NIN logo is a registered trademark licensed \x1b[22;1H to Nothing Interactive, Inc. All rights reserved. \x1b[23;1H\x1b[40m\x1b[0m";
#endif
void Sys_Quit (void)
{
Host_Shutdown();
fcntl (0, F_SETFL, fcntl (0, F_GETFL, 0) & ~FNDELAY);
#if 0
if (registered.value)
printf("%s", end2);
else
printf("%s", end1);
#endif
fflush(stdout);
exit(0);
}
void Sys_Init(void)
{
#if id386
Sys_SetFPCW();
#endif
}
void Sys_Error (char *error, ...)
{
va_list argptr;
char string[1024];
// change stdin to non blocking
fcntl (0, F_SETFL, fcntl (0, F_GETFL, 0) & ~FNDELAY);
va_start (argptr,error);
vsprintf (string,error,argptr);
va_end (argptr);
fprintf(stderr, "Error: %s\n", string);
Host_Shutdown ();
exit (1);
}
void Sys_Warn (char *warning, ...)
{
va_list argptr;
char string[1024];
va_start (argptr,warning);
vsprintf (string,warning,argptr);
va_end (argptr);
fprintf(stderr, "Warning: %s", string);
}
/*
============
Sys_FileTime
returns -1 if not present
============
*/
int Sys_FileTime (char *path)
{
struct stat buf;
if (stat (path,&buf) == -1)
return -1;
return buf.st_mtime;
}
void Sys_mkdir (char *path)
{
mkdir (path, 0777);
}
int Sys_FileOpenRead (char *path, int *handle)
{
int h;
struct stat fileinfo;
h = open (path, O_RDONLY, 0666);
*handle = h;
if (h == -1)
return -1;
if (fstat (h,&fileinfo) == -1)
Sys_Error ("Error fstating %s", path);
return fileinfo.st_size;
}
int Sys_FileOpenWrite (char *path)
{
int handle;
umask (0);
handle = open(path,O_RDWR | O_CREAT | O_TRUNC
, 0666);
if (handle == -1)
Sys_Error ("Error opening %s: %s", path,strerror(errno));
return handle;
}
int Sys_FileWrite (int handle, void *src, int count)
{
return write (handle, src, count);
}
void Sys_FileClose (int handle)
{
close (handle);
}
void Sys_FileSeek (int handle, int position)
{
lseek (handle, position, SEEK_SET);
}
int Sys_FileRead (int handle, void *dest, int count)
{
return read (handle, dest, count);
}
void Sys_DebugLog(char *file, char *fmt, ...)
{
va_list argptr;
static char data[1024];
int fd;
va_start(argptr, fmt);
vsprintf(data, fmt, argptr);
va_end(argptr);
// fd = open(file, O_WRONLY | O_BINARY | O_CREAT | O_APPEND, 0666);
fd = open(file, O_WRONLY | O_CREAT | O_APPEND, 0666);
write(fd, data, strlen(data));
close(fd);
}
void Sys_EditFile(char *filename)
{
char cmd[256];
char *term;
char *editor;
term = getenv("TERM");
if (term && !strcmp(term, "xterm"))
{
editor = getenv("VISUAL");
if (!editor)
editor = getenv("EDITOR");
if (!editor)
editor = getenv("EDIT");
if (!editor)
editor = "vi";
sprintf(cmd, "xterm -e %s %s", editor, filename);
system(cmd);
}
}
double Sys_FloatTime (void)
{
struct timeval tp;
struct timezone tzp;
static int secbase;
gettimeofday(&tp, &tzp);
if (!secbase)
{
secbase = tp.tv_sec;
return tp.tv_usec/1000000.0;
}
return (tp.tv_sec - secbase) + tp.tv_usec/1000000.0;
}
// =======================================================================
// Sleeps for microseconds
// =======================================================================
static volatile int oktogo;
void alarm_handler(int x)
{
oktogo=1;
}
void Sys_LineRefresh(void)
{
}
void floating_point_exception_handler(int whatever)
{
// Sys_Warn("floating point exception\n");
signal(SIGFPE, floating_point_exception_handler);
}
char *Sys_ConsoleInput(void)
{
static char text[256];
int len;
fd_set fdset;
struct timeval timeout;
if (cls.state == ca_dedicated) {
FD_ZERO(&fdset);
FD_SET(0, &fdset); // stdin
timeout.tv_sec = 0;
timeout.tv_usec = 0;
if (select (1, &fdset, NULL, NULL, &timeout) == -1 || !FD_ISSET(0, &fdset))
return NULL;
len = read (0, text, sizeof(text));
if (len < 1)
return NULL;
text[len-1] = 0; // rip off the /n and terminate
return text;
}
return NULL;
}
#if !id386
void Sys_HighFPPrecision (void)
{
}
void Sys_LowFPPrecision (void)
{
}
#endif
int main (int c, char **v)
{
double time, oldtime, newtime;
quakeparms_t parms;
extern int vcrFile;
extern int recording;
int j;
// static char cwd[1024];
// signal(SIGFPE, floating_point_exception_handler);
signal(SIGFPE, SIG_IGN);
memset(&parms, 0, sizeof(parms));
COM_InitArgv(c, v);
parms.argc = com_argc;
parms.argv = com_argv;
#ifdef GLQUAKE
parms.memsize = 16*1024*1024;
#else
parms.memsize = 8*1024*1024;
#endif
j = COM_CheckParm("-mem");
if (j)
parms.memsize = (int) (Q_atof(com_argv[j+1]) * 1024 * 1024);
parms.membase = malloc (parms.memsize);
parms.basedir = basedir;
// caching is disabled by default, use -cachedir to enable
// parms.cachedir = cachedir;
fcntl(0, F_SETFL, fcntl (0, F_GETFL, 0) | FNDELAY);
Host_Init(&parms);
Sys_Init();
if (COM_CheckParm("-nostdout"))
nostdout = 1;
else {
fcntl(0, F_SETFL, fcntl (0, F_GETFL, 0) | FNDELAY);
printf ("Linux Quake -- Version %0.3f\n", LINUX_VERSION);
}
oldtime = Sys_FloatTime () - 0.1;
while (1)
{
// find time spent rendering last frame
newtime = Sys_FloatTime ();
time = newtime - oldtime;
if (cls.state == ca_dedicated)
{ // play vcrfiles at max speed
if (time < sys_ticrate.value && (vcrFile == -1 || recording) )
{
usleep(1);
continue; // not time to run a server only tic yet
}
time = sys_ticrate.value;
}
if (time > sys_ticrate.value*2)
oldtime = newtime;
else
oldtime += time;
Host_Frame (time);
// graphic debugging aids
if (sys_linerefresh.value)
Sys_LineRefresh ();
}
}
/*
================
Sys_MakeCodeWriteable
================
*/
void Sys_MakeCodeWriteable (unsigned long startaddr, unsigned long length)
{
int r;
unsigned long addr;
int psize = getpagesize();
addr = (startaddr & ~(psize-1)) - psize;
// fprintf(stderr, "writable code %lx(%lx)-%lx, length=%lx\n", startaddr,
// addr, startaddr+length, length);
r = mprotect((char*)addr, length + startaddr - addr + psize, 7);
if (r < 0)
Sys_Error("Protection change failed\n");
}
| C++ |
/*
Copyright (C) 1996-1997 Id Software, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
//
// vid_vga.c: VGA-specific DOS video stuff
//
// TODO: proper handling of page-swap failure
#include <dos.h>
#include "quakedef.h"
#include "d_local.h"
#include "dosisms.h"
#include "vid_dos.h"
#include <dpmi.h>
extern regs_t regs;
int VGA_width, VGA_height, VGA_rowbytes, VGA_bufferrowbytes;
byte *VGA_pagebase;
vmode_t *VGA_pcurmode;
static int VGA_planar;
static int VGA_numpages;
static int VGA_buffersize;
void *vid_surfcache;
int vid_surfcachesize;
int VGA_highhunkmark;
#include "vgamodes.h"
#define NUMVIDMODES (sizeof(vgavidmodes) / sizeof(vgavidmodes[0]))
void VGA_UpdatePlanarScreen (void *srcbuffer);
static byte backingbuf[48*24];
/*
================
VGA_BeginDirectRect
================
*/
void VGA_BeginDirectRect (viddef_t *lvid, struct vmode_s *pcurrentmode, int x,
int y, byte *pbitmap, int width, int height)
{
int i, j, k, plane, reps, repshift;
if (!lvid->direct)
return;
if (lvid->aspect > 1.5)
{
reps = 2;
repshift = 1;
}
else
{
reps = 1;
repshift = 0;
}
if (pcurrentmode->planar)
{
for (plane=0 ; plane<4 ; plane++)
{
// select the correct plane for reading and writing
outportb (SC_INDEX, MAP_MASK);
outportb (SC_DATA, 1 << plane);
outportb (GC_INDEX, READ_MAP);
outportb (GC_DATA, plane);
for (i=0 ; i<(height << repshift) ; i += reps)
{
for (k=0 ; k<reps ; k++)
{
for (j=0 ; j<(width >> 2) ; j++)
{
backingbuf[(i + k) * 24 + (j << 2) + plane] =
lvid->direct[(y + i + k) * VGA_rowbytes +
(x >> 2) + j];
lvid->direct[(y + i + k) * VGA_rowbytes + (x>>2) + j] =
pbitmap[(i >> repshift) * 24 +
(j << 2) + plane];
}
}
}
}
}
else
{
for (i=0 ; i<(height << repshift) ; i += reps)
{
for (j=0 ; j<reps ; j++)
{
memcpy (&backingbuf[(i + j) * 24],
lvid->direct + x + ((y << repshift) + i + j) *
VGA_rowbytes,
width);
memcpy (lvid->direct + x + ((y << repshift) + i + j) *
VGA_rowbytes,
&pbitmap[(i >> repshift) * width],
width);
}
}
}
}
/*
================
VGA_EndDirectRect
================
*/
void VGA_EndDirectRect (viddef_t *lvid, struct vmode_s *pcurrentmode, int x,
int y, int width, int height)
{
int i, j, k, plane, reps, repshift;
if (!lvid->direct)
return;
if (lvid->aspect > 1.5)
{
reps = 2;
repshift = 1;
}
else
{
reps = 1;
repshift = 0;
}
if (pcurrentmode->planar)
{
for (plane=0 ; plane<4 ; plane++)
{
// select the correct plane for writing
outportb (SC_INDEX, MAP_MASK);
outportb (SC_DATA, 1 << plane);
for (i=0 ; i<(height << repshift) ; i += reps)
{
for (k=0 ; k<reps ; k++)
{
for (j=0 ; j<(width >> 2) ; j++)
{
lvid->direct[(y + i + k) * VGA_rowbytes + (x>>2) + j] =
backingbuf[(i + k) * 24 + (j << 2) + plane];
}
}
}
}
}
else
{
for (i=0 ; i<(height << repshift) ; i += reps)
{
for (j=0 ; j<reps ; j++)
{
memcpy (lvid->direct + x + ((y << repshift) + i + j) *
VGA_rowbytes,
&backingbuf[(i + j) * 24],
width);
}
}
}
}
/*
================
VGA_Init
================
*/
void VGA_Init (void)
{
int i;
// link together all the VGA modes
for (i=0 ; i<(NUMVIDMODES - 1) ; i++)
{
vgavidmodes[i].pnext = &vgavidmodes[i+1];
}
// add the VGA modes at the start of the mode list
vgavidmodes[NUMVIDMODES-1].pnext = pvidmodes;
pvidmodes = &vgavidmodes[0];
numvidmodes += NUMVIDMODES;
}
/*
================
VGA_WaitVsync
================
*/
void VGA_WaitVsync (void)
{
while ((inportb (0x3DA) & 0x08) == 0)
;
}
/*
================
VGA_ClearVideoMem
================
*/
void VGA_ClearVideoMem (int planar)
{
if (planar)
{
// enable all planes for writing
outportb (SC_INDEX, MAP_MASK);
outportb (SC_DATA, 0x0F);
}
Q_memset (VGA_pagebase, 0, VGA_rowbytes * VGA_height);
}
/*
================
VGA_FreeAndAllocVidbuffer
================
*/
qboolean VGA_FreeAndAllocVidbuffer (viddef_t *lvid, int allocnewbuffer)
{
int tsize, tbuffersize;
if (allocnewbuffer)
{
// alloc an extra line in case we want to wrap, and allocate the z-buffer
tbuffersize = (lvid->rowbytes * (lvid->height + 1)) +
(lvid->width * lvid->height * sizeof (*d_pzbuffer));
}
else
{
// just allocate the z-buffer
tbuffersize = lvid->width * lvid->height * sizeof (*d_pzbuffer);
}
tsize = D_SurfaceCacheForRes (lvid->width, lvid->height);
tbuffersize += tsize;
// see if there's enough memory, allowing for the normal mode 0x13 pixel,
// z, and surface buffers
if ((host_parms.memsize - tbuffersize + SURFCACHE_SIZE_AT_320X200 +
0x10000 * 3) < minimum_memory)
{
Con_Printf ("Not enough memory for video mode\n");
VGA_pcurmode = NULL; // so no further accesses to the buffer are
// attempted, particularly when clearing
return false; // not enough memory for mode
}
VGA_buffersize = tbuffersize;
vid_surfcachesize = tsize;
if (d_pzbuffer)
{
D_FlushCaches ();
Hunk_FreeToHighMark (VGA_highhunkmark);
d_pzbuffer = NULL;
}
VGA_highhunkmark = Hunk_HighMark ();
d_pzbuffer = Hunk_HighAllocName (VGA_buffersize, "video");
vid_surfcache = (byte *)d_pzbuffer
+ lvid->width * lvid->height * sizeof (*d_pzbuffer);
if (allocnewbuffer)
{
lvid->buffer = (void *)( (byte *)vid_surfcache + vid_surfcachesize);
lvid->conbuffer = lvid->buffer;
}
return true;
}
/*
================
VGA_CheckAdequateMem
================
*/
qboolean VGA_CheckAdequateMem (int width, int height, int rowbytes,
int allocnewbuffer)
{
int tbuffersize;
tbuffersize = width * height * sizeof (*d_pzbuffer);
if (allocnewbuffer)
{
// alloc an extra line in case we want to wrap, and allocate the z-buffer
tbuffersize += (rowbytes * (height + 1));
}
tbuffersize += D_SurfaceCacheForRes (width, height);
// see if there's enough memory, allowing for the normal mode 0x13 pixel,
// z, and surface buffers
if ((host_parms.memsize - tbuffersize + SURFCACHE_SIZE_AT_320X200 +
0x10000 * 3) < minimum_memory)
{
return false; // not enough memory for mode
}
return true;
}
/*
================
VGA_InitMode
================
*/
int VGA_InitMode (viddef_t *lvid, vmode_t *pcurrentmode)
{
vextra_t *pextra;
pextra = pcurrentmode->pextradata;
if (!VGA_FreeAndAllocVidbuffer (lvid, pextra->vidbuffer))
return -1; // memory alloc failed
if (VGA_pcurmode)
VGA_ClearVideoMem (VGA_pcurmode->planar);
// mode 0x13 is the base for all the Mode X-class mode sets
regs.h.ah = 0;
regs.h.al = 0x13;
dos_int86(0x10);
VGA_pagebase = (void *)real2ptr(0xa0000);
lvid->direct = (pixel_t *)VGA_pagebase;
// set additional registers as needed
VideoRegisterSet (pextra->pregset);
VGA_numpages = 1;
lvid->numpages = VGA_numpages;
VGA_width = (lvid->width + 0x1F) & ~0x1F;
VGA_height = lvid->height;
VGA_planar = pcurrentmode->planar;
if (VGA_planar)
VGA_rowbytes = lvid->rowbytes / 4;
else
VGA_rowbytes = lvid->rowbytes;
VGA_bufferrowbytes = lvid->rowbytes;
lvid->colormap = host_colormap;
lvid->fullbright = 256 - LittleLong (*((int *)lvid->colormap + 2048));
lvid->maxwarpwidth = WARP_WIDTH;
lvid->maxwarpheight = WARP_HEIGHT;
lvid->conbuffer = lvid->buffer;
lvid->conrowbytes = lvid->rowbytes;
lvid->conwidth = lvid->width;
lvid->conheight = lvid->height;
VGA_pcurmode = pcurrentmode;
VGA_ClearVideoMem (pcurrentmode->planar);
if (_vid_wait_override.value)
{
Cvar_SetValue ("vid_wait", (float)VID_WAIT_VSYNC);
}
else
{
Cvar_SetValue ("vid_wait", (float)VID_WAIT_NONE);
}
D_InitCaches (vid_surfcache, vid_surfcachesize);
return 1;
}
/*
================
VGA_SetPalette
================
*/
void VGA_SetPalette(viddef_t *lvid, vmode_t *pcurrentmode, unsigned char *pal)
{
int shiftcomponents=2;
int i;
UNUSED(lvid);
UNUSED(pcurrentmode);
dos_outportb(0x3c8, 0);
for (i=0 ; i<768 ; i++)
outportb(0x3c9, pal[i]>>shiftcomponents);
}
/*
================
VGA_SwapBuffersCopy
================
*/
void VGA_SwapBuffersCopy (viddef_t *lvid, vmode_t *pcurrentmode,
vrect_t *rects)
{
UNUSED(pcurrentmode);
// TODO: can write a dword at a time
// TODO: put in ASM
// TODO: copy only specified rectangles
if (VGA_planar)
{
// TODO: copy only specified rectangles
VGA_UpdatePlanarScreen (lvid->buffer);
}
else
{
while (rects)
{
VGA_UpdateLinearScreen (
lvid->buffer + rects->x + (rects->y * lvid->rowbytes),
VGA_pagebase + rects->x + (rects->y * VGA_rowbytes),
rects->width,
rects->height,
lvid->rowbytes,
VGA_rowbytes);
rects = rects->pnext;
}
}
}
/*
================
VGA_SwapBuffers
================
*/
void VGA_SwapBuffers (viddef_t *lvid, vmode_t *pcurrentmode, vrect_t *rects)
{
UNUSED(lvid);
if (vid_wait.value == VID_WAIT_VSYNC)
VGA_WaitVsync ();
VGA_SwapBuffersCopy (lvid, pcurrentmode, rects);
}
| C++ |
/*
Copyright (C) 1996-1997 Id Software, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// sbar.c -- status bar code
#include "quakedef.h"
int sb_updates; // if >= vid.numpages, no update needed
#define STAT_MINUS 10 // num frame for '-' stats digit
qpic_t *sb_nums[2][11];
qpic_t *sb_colon, *sb_slash;
qpic_t *sb_ibar;
qpic_t *sb_sbar;
qpic_t *sb_scorebar;
qpic_t *sb_weapons[7][8]; // 0 is active, 1 is owned, 2-5 are flashes
qpic_t *sb_ammo[4];
qpic_t *sb_sigil[4];
qpic_t *sb_armor[3];
qpic_t *sb_items[32];
qpic_t *sb_faces[7][2]; // 0 is gibbed, 1 is dead, 2-6 are alive
// 0 is static, 1 is temporary animation
qpic_t *sb_face_invis;
qpic_t *sb_face_quad;
qpic_t *sb_face_invuln;
qpic_t *sb_face_invis_invuln;
qboolean sb_showscores;
int sb_lines; // scan lines to draw
qpic_t *rsb_invbar[2];
qpic_t *rsb_weapons[5];
qpic_t *rsb_items[2];
qpic_t *rsb_ammo[3];
qpic_t *rsb_teambord; // PGM 01/19/97 - team color border
//MED 01/04/97 added two more weapons + 3 alternates for grenade launcher
qpic_t *hsb_weapons[7][5]; // 0 is active, 1 is owned, 2-5 are flashes
//MED 01/04/97 added array to simplify weapon parsing
int hipweapons[4] = {HIT_LASER_CANNON_BIT,HIT_MJOLNIR_BIT,4,HIT_PROXIMITY_GUN_BIT};
//MED 01/04/97 added hipnotic items array
qpic_t *hsb_items[2];
void Sbar_MiniDeathmatchOverlay (void);
void Sbar_DeathmatchOverlay (void);
void M_DrawPic (int x, int y, qpic_t *pic);
/*
===============
Sbar_ShowScores
Tab key down
===============
*/
void Sbar_ShowScores (void)
{
if (sb_showscores)
return;
sb_showscores = true;
sb_updates = 0;
}
/*
===============
Sbar_DontShowScores
Tab key up
===============
*/
void Sbar_DontShowScores (void)
{
sb_showscores = false;
sb_updates = 0;
}
/*
===============
Sbar_Changed
===============
*/
void Sbar_Changed (void)
{
sb_updates = 0; // update next frame
}
/*
===============
Sbar_Init
===============
*/
void Sbar_Init (void)
{
int i;
for (i=0 ; i<10 ; i++)
{
sb_nums[0][i] = Draw_PicFromWad (va("num_%i",i));
sb_nums[1][i] = Draw_PicFromWad (va("anum_%i",i));
}
sb_nums[0][10] = Draw_PicFromWad ("num_minus");
sb_nums[1][10] = Draw_PicFromWad ("anum_minus");
sb_colon = Draw_PicFromWad ("num_colon");
sb_slash = Draw_PicFromWad ("num_slash");
sb_weapons[0][0] = Draw_PicFromWad ("inv_shotgun");
sb_weapons[0][1] = Draw_PicFromWad ("inv_sshotgun");
sb_weapons[0][2] = Draw_PicFromWad ("inv_nailgun");
sb_weapons[0][3] = Draw_PicFromWad ("inv_snailgun");
sb_weapons[0][4] = Draw_PicFromWad ("inv_rlaunch");
sb_weapons[0][5] = Draw_PicFromWad ("inv_srlaunch");
sb_weapons[0][6] = Draw_PicFromWad ("inv_lightng");
sb_weapons[1][0] = Draw_PicFromWad ("inv2_shotgun");
sb_weapons[1][1] = Draw_PicFromWad ("inv2_sshotgun");
sb_weapons[1][2] = Draw_PicFromWad ("inv2_nailgun");
sb_weapons[1][3] = Draw_PicFromWad ("inv2_snailgun");
sb_weapons[1][4] = Draw_PicFromWad ("inv2_rlaunch");
sb_weapons[1][5] = Draw_PicFromWad ("inv2_srlaunch");
sb_weapons[1][6] = Draw_PicFromWad ("inv2_lightng");
for (i=0 ; i<5 ; i++)
{
sb_weapons[2+i][0] = Draw_PicFromWad (va("inva%i_shotgun",i+1));
sb_weapons[2+i][1] = Draw_PicFromWad (va("inva%i_sshotgun",i+1));
sb_weapons[2+i][2] = Draw_PicFromWad (va("inva%i_nailgun",i+1));
sb_weapons[2+i][3] = Draw_PicFromWad (va("inva%i_snailgun",i+1));
sb_weapons[2+i][4] = Draw_PicFromWad (va("inva%i_rlaunch",i+1));
sb_weapons[2+i][5] = Draw_PicFromWad (va("inva%i_srlaunch",i+1));
sb_weapons[2+i][6] = Draw_PicFromWad (va("inva%i_lightng",i+1));
}
sb_ammo[0] = Draw_PicFromWad ("sb_shells");
sb_ammo[1] = Draw_PicFromWad ("sb_nails");
sb_ammo[2] = Draw_PicFromWad ("sb_rocket");
sb_ammo[3] = Draw_PicFromWad ("sb_cells");
sb_armor[0] = Draw_PicFromWad ("sb_armor1");
sb_armor[1] = Draw_PicFromWad ("sb_armor2");
sb_armor[2] = Draw_PicFromWad ("sb_armor3");
sb_items[0] = Draw_PicFromWad ("sb_key1");
sb_items[1] = Draw_PicFromWad ("sb_key2");
sb_items[2] = Draw_PicFromWad ("sb_invis");
sb_items[3] = Draw_PicFromWad ("sb_invuln");
sb_items[4] = Draw_PicFromWad ("sb_suit");
sb_items[5] = Draw_PicFromWad ("sb_quad");
sb_sigil[0] = Draw_PicFromWad ("sb_sigil1");
sb_sigil[1] = Draw_PicFromWad ("sb_sigil2");
sb_sigil[2] = Draw_PicFromWad ("sb_sigil3");
sb_sigil[3] = Draw_PicFromWad ("sb_sigil4");
sb_faces[4][0] = Draw_PicFromWad ("face1");
sb_faces[4][1] = Draw_PicFromWad ("face_p1");
sb_faces[3][0] = Draw_PicFromWad ("face2");
sb_faces[3][1] = Draw_PicFromWad ("face_p2");
sb_faces[2][0] = Draw_PicFromWad ("face3");
sb_faces[2][1] = Draw_PicFromWad ("face_p3");
sb_faces[1][0] = Draw_PicFromWad ("face4");
sb_faces[1][1] = Draw_PicFromWad ("face_p4");
sb_faces[0][0] = Draw_PicFromWad ("face5");
sb_faces[0][1] = Draw_PicFromWad ("face_p5");
sb_face_invis = Draw_PicFromWad ("face_invis");
sb_face_invuln = Draw_PicFromWad ("face_invul2");
sb_face_invis_invuln = Draw_PicFromWad ("face_inv2");
sb_face_quad = Draw_PicFromWad ("face_quad");
Cmd_AddCommand ("+showscores", Sbar_ShowScores);
Cmd_AddCommand ("-showscores", Sbar_DontShowScores);
sb_sbar = Draw_PicFromWad ("sbar");
sb_ibar = Draw_PicFromWad ("ibar");
sb_scorebar = Draw_PicFromWad ("scorebar");
//MED 01/04/97 added new hipnotic weapons
if (hipnotic)
{
hsb_weapons[0][0] = Draw_PicFromWad ("inv_laser");
hsb_weapons[0][1] = Draw_PicFromWad ("inv_mjolnir");
hsb_weapons[0][2] = Draw_PicFromWad ("inv_gren_prox");
hsb_weapons[0][3] = Draw_PicFromWad ("inv_prox_gren");
hsb_weapons[0][4] = Draw_PicFromWad ("inv_prox");
hsb_weapons[1][0] = Draw_PicFromWad ("inv2_laser");
hsb_weapons[1][1] = Draw_PicFromWad ("inv2_mjolnir");
hsb_weapons[1][2] = Draw_PicFromWad ("inv2_gren_prox");
hsb_weapons[1][3] = Draw_PicFromWad ("inv2_prox_gren");
hsb_weapons[1][4] = Draw_PicFromWad ("inv2_prox");
for (i=0 ; i<5 ; i++)
{
hsb_weapons[2+i][0] = Draw_PicFromWad (va("inva%i_laser",i+1));
hsb_weapons[2+i][1] = Draw_PicFromWad (va("inva%i_mjolnir",i+1));
hsb_weapons[2+i][2] = Draw_PicFromWad (va("inva%i_gren_prox",i+1));
hsb_weapons[2+i][3] = Draw_PicFromWad (va("inva%i_prox_gren",i+1));
hsb_weapons[2+i][4] = Draw_PicFromWad (va("inva%i_prox",i+1));
}
hsb_items[0] = Draw_PicFromWad ("sb_wsuit");
hsb_items[1] = Draw_PicFromWad ("sb_eshld");
}
if (rogue)
{
rsb_invbar[0] = Draw_PicFromWad ("r_invbar1");
rsb_invbar[1] = Draw_PicFromWad ("r_invbar2");
rsb_weapons[0] = Draw_PicFromWad ("r_lava");
rsb_weapons[1] = Draw_PicFromWad ("r_superlava");
rsb_weapons[2] = Draw_PicFromWad ("r_gren");
rsb_weapons[3] = Draw_PicFromWad ("r_multirock");
rsb_weapons[4] = Draw_PicFromWad ("r_plasma");
rsb_items[0] = Draw_PicFromWad ("r_shield1");
rsb_items[1] = Draw_PicFromWad ("r_agrav1");
// PGM 01/19/97 - team color border
rsb_teambord = Draw_PicFromWad ("r_teambord");
// PGM 01/19/97 - team color border
rsb_ammo[0] = Draw_PicFromWad ("r_ammolava");
rsb_ammo[1] = Draw_PicFromWad ("r_ammomulti");
rsb_ammo[2] = Draw_PicFromWad ("r_ammoplasma");
}
}
//=============================================================================
// drawing routines are relative to the status bar location
/*
=============
Sbar_DrawPic
=============
*/
void Sbar_DrawPic (int x, int y, qpic_t *pic)
{
if (cl.gametype == GAME_DEATHMATCH)
Draw_Pic (x /* + ((vid.width - 320)>>1)*/, y + (vid.height-SBAR_HEIGHT), pic);
else
Draw_Pic (x + ((vid.width - 320)>>1), y + (vid.height-SBAR_HEIGHT), pic);
}
/*
=============
Sbar_DrawTransPic
=============
*/
void Sbar_DrawTransPic (int x, int y, qpic_t *pic)
{
if (cl.gametype == GAME_DEATHMATCH)
Draw_TransPic (x /*+ ((vid.width - 320)>>1)*/, y + (vid.height-SBAR_HEIGHT), pic);
else
Draw_TransPic (x + ((vid.width - 320)>>1), y + (vid.height-SBAR_HEIGHT), pic);
}
/*
================
Sbar_DrawCharacter
Draws one solid graphics character
================
*/
void Sbar_DrawCharacter (int x, int y, int num)
{
if (cl.gametype == GAME_DEATHMATCH)
Draw_Character ( x /*+ ((vid.width - 320)>>1) */ + 4 , y + vid.height-SBAR_HEIGHT, num);
else
Draw_Character ( x + ((vid.width - 320)>>1) + 4 , y + vid.height-SBAR_HEIGHT, num);
}
/*
================
Sbar_DrawString
================
*/
void Sbar_DrawString (int x, int y, char *str)
{
if (cl.gametype == GAME_DEATHMATCH)
Draw_String (x /*+ ((vid.width - 320)>>1)*/, y+ vid.height-SBAR_HEIGHT, str);
else
Draw_String (x + ((vid.width - 320)>>1), y+ vid.height-SBAR_HEIGHT, str);
}
/*
=============
Sbar_itoa
=============
*/
int Sbar_itoa (int num, char *buf)
{
char *str;
int pow10;
int dig;
str = buf;
if (num < 0)
{
*str++ = '-';
num = -num;
}
for (pow10 = 10 ; num >= pow10 ; pow10 *= 10)
;
do
{
pow10 /= 10;
dig = num/pow10;
*str++ = '0'+dig;
num -= dig*pow10;
} while (pow10 != 1);
*str = 0;
return str-buf;
}
/*
=============
Sbar_DrawNum
=============
*/
void Sbar_DrawNum (int x, int y, int num, int digits, int color)
{
char str[12];
char *ptr;
int l, frame;
l = Sbar_itoa (num, str);
ptr = str;
if (l > digits)
ptr += (l-digits);
if (l < digits)
x += (digits-l)*24;
while (*ptr)
{
if (*ptr == '-')
frame = STAT_MINUS;
else
frame = *ptr -'0';
Sbar_DrawTransPic (x,y,sb_nums[color][frame]);
x += 24;
ptr++;
}
}
//=============================================================================
int fragsort[MAX_SCOREBOARD];
char scoreboardtext[MAX_SCOREBOARD][20];
int scoreboardtop[MAX_SCOREBOARD];
int scoreboardbottom[MAX_SCOREBOARD];
int scoreboardcount[MAX_SCOREBOARD];
int scoreboardlines;
/*
===============
Sbar_SortFrags
===============
*/
void Sbar_SortFrags (void)
{
int i, j, k;
// sort by frags
scoreboardlines = 0;
for (i=0 ; i<cl.maxclients ; i++)
{
if (cl.scores[i].name[0])
{
fragsort[scoreboardlines] = i;
scoreboardlines++;
}
}
for (i=0 ; i<scoreboardlines ; i++)
for (j=0 ; j<scoreboardlines-1-i ; j++)
if (cl.scores[fragsort[j]].frags < cl.scores[fragsort[j+1]].frags)
{
k = fragsort[j];
fragsort[j] = fragsort[j+1];
fragsort[j+1] = k;
}
}
int Sbar_ColorForMap (int m)
{
return m < 128 ? m + 8 : m + 8;
}
/*
===============
Sbar_UpdateScoreboard
===============
*/
void Sbar_UpdateScoreboard (void)
{
int i, k;
int top, bottom;
scoreboard_t *s;
Sbar_SortFrags ();
// draw the text
memset (scoreboardtext, 0, sizeof(scoreboardtext));
for (i=0 ; i<scoreboardlines; i++)
{
k = fragsort[i];
s = &cl.scores[k];
sprintf (&scoreboardtext[i][1], "%3i %s", s->frags, s->name);
top = s->colors & 0xf0;
bottom = (s->colors & 15) <<4;
scoreboardtop[i] = Sbar_ColorForMap (top);
scoreboardbottom[i] = Sbar_ColorForMap (bottom);
}
}
/*
===============
Sbar_SoloScoreboard
===============
*/
void Sbar_SoloScoreboard (void)
{
char str[80];
int minutes, seconds, tens, units;
int l;
sprintf (str,"Monsters:%3i /%3i", cl.stats[STAT_MONSTERS], cl.stats[STAT_TOTALMONSTERS]);
Sbar_DrawString (8, 4, str);
sprintf (str,"Secrets :%3i /%3i", cl.stats[STAT_SECRETS], cl.stats[STAT_TOTALSECRETS]);
Sbar_DrawString (8, 12, str);
// time
minutes = (int)(cl.time / 60);
seconds = (int)(cl.time - 60*minutes);
tens = seconds / 10;
units = seconds - 10*tens;
sprintf (str,"Time :%3i:%i%i", minutes, tens, units);
Sbar_DrawString (184, 4, str);
// draw level name
l = strlen (cl.levelname);
Sbar_DrawString (232 - l*4, 12, cl.levelname);
}
/*
===============
Sbar_DrawScoreboard
===============
*/
void Sbar_DrawScoreboard (void)
{
Sbar_SoloScoreboard ();
if (cl.gametype == GAME_DEATHMATCH)
Sbar_DeathmatchOverlay ();
#if 0
int i, j, c;
int x, y;
int l;
int top, bottom;
scoreboard_t *s;
if (cl.gametype != GAME_DEATHMATCH)
{
Sbar_SoloScoreboard ();
return;
}
Sbar_UpdateScoreboard ();
l = scoreboardlines <= 6 ? scoreboardlines : 6;
for (i=0 ; i<l ; i++)
{
x = 20*(i&1);
y = i/2 * 8;
s = &cl.scores[fragsort[i]];
if (!s->name[0])
continue;
// draw background
top = s->colors & 0xf0;
bottom = (s->colors & 15)<<4;
top = Sbar_ColorForMap (top);
bottom = Sbar_ColorForMap (bottom);
Draw_Fill ( x*8+10 + ((vid.width - 320)>>1), y + vid.height - SBAR_HEIGHT, 28, 4, top);
Draw_Fill ( x*8+10 + ((vid.width - 320)>>1), y+4 + vid.height - SBAR_HEIGHT, 28, 4, bottom);
// draw text
for (j=0 ; j<20 ; j++)
{
c = scoreboardtext[i][j];
if (c == 0 || c == ' ')
continue;
Sbar_DrawCharacter ( (x+j)*8, y, c);
}
}
#endif
}
//=============================================================================
/*
===============
Sbar_DrawInventory
===============
*/
void Sbar_DrawInventory (void)
{
int i;
char num[6];
float time;
int flashon;
if (rogue)
{
if ( cl.stats[STAT_ACTIVEWEAPON] >= RIT_LAVA_NAILGUN )
Sbar_DrawPic (0, -24, rsb_invbar[0]);
else
Sbar_DrawPic (0, -24, rsb_invbar[1]);
}
else
{
Sbar_DrawPic (0, -24, sb_ibar);
}
// weapons
for (i=0 ; i<7 ; i++)
{
if (cl.items & (IT_SHOTGUN<<i) )
{
time = cl.item_gettime[i];
flashon = (int)((cl.time - time)*10);
if (flashon >= 10)
{
if ( cl.stats[STAT_ACTIVEWEAPON] == (IT_SHOTGUN<<i) )
flashon = 1;
else
flashon = 0;
}
else
flashon = (flashon%5) + 2;
Sbar_DrawPic (i*24, -16, sb_weapons[flashon][i]);
if (flashon > 1)
sb_updates = 0; // force update to remove flash
}
}
// MED 01/04/97
// hipnotic weapons
if (hipnotic)
{
int grenadeflashing=0;
for (i=0 ; i<4 ; i++)
{
if (cl.items & (1<<hipweapons[i]) )
{
time = cl.item_gettime[hipweapons[i]];
flashon = (int)((cl.time - time)*10);
if (flashon >= 10)
{
if ( cl.stats[STAT_ACTIVEWEAPON] == (1<<hipweapons[i]) )
flashon = 1;
else
flashon = 0;
}
else
flashon = (flashon%5) + 2;
// check grenade launcher
if (i==2)
{
if (cl.items & HIT_PROXIMITY_GUN)
{
if (flashon)
{
grenadeflashing = 1;
Sbar_DrawPic (96, -16, hsb_weapons[flashon][2]);
}
}
}
else if (i==3)
{
if (cl.items & (IT_SHOTGUN<<4))
{
if (flashon && !grenadeflashing)
{
Sbar_DrawPic (96, -16, hsb_weapons[flashon][3]);
}
else if (!grenadeflashing)
{
Sbar_DrawPic (96, -16, hsb_weapons[0][3]);
}
}
else
Sbar_DrawPic (96, -16, hsb_weapons[flashon][4]);
}
else
Sbar_DrawPic (176 + (i*24), -16, hsb_weapons[flashon][i]);
if (flashon > 1)
sb_updates = 0; // force update to remove flash
}
}
}
if (rogue)
{
// check for powered up weapon.
if ( cl.stats[STAT_ACTIVEWEAPON] >= RIT_LAVA_NAILGUN )
{
for (i=0;i<5;i++)
{
if (cl.stats[STAT_ACTIVEWEAPON] == (RIT_LAVA_NAILGUN << i))
{
Sbar_DrawPic ((i+2)*24, -16, rsb_weapons[i]);
}
}
}
}
// ammo counts
for (i=0 ; i<4 ; i++)
{
sprintf (num, "%3i",cl.stats[STAT_SHELLS+i] );
if (num[0] != ' ')
Sbar_DrawCharacter ( (6*i+1)*8 - 2, -24, 18 + num[0] - '0');
if (num[1] != ' ')
Sbar_DrawCharacter ( (6*i+2)*8 - 2, -24, 18 + num[1] - '0');
if (num[2] != ' ')
Sbar_DrawCharacter ( (6*i+3)*8 - 2, -24, 18 + num[2] - '0');
}
flashon = 0;
// items
for (i=0 ; i<6 ; i++)
if (cl.items & (1<<(17+i)))
{
time = cl.item_gettime[17+i];
if (time && time > cl.time - 2 && flashon )
{ // flash frame
sb_updates = 0;
}
else
{
//MED 01/04/97 changed keys
if (!hipnotic || (i>1))
{
Sbar_DrawPic (192 + i*16, -16, sb_items[i]);
}
}
if (time && time > cl.time - 2)
sb_updates = 0;
}
//MED 01/04/97 added hipnotic items
// hipnotic items
if (hipnotic)
{
for (i=0 ; i<2 ; i++)
if (cl.items & (1<<(24+i)))
{
time = cl.item_gettime[24+i];
if (time && time > cl.time - 2 && flashon )
{ // flash frame
sb_updates = 0;
}
else
{
Sbar_DrawPic (288 + i*16, -16, hsb_items[i]);
}
if (time && time > cl.time - 2)
sb_updates = 0;
}
}
if (rogue)
{
// new rogue items
for (i=0 ; i<2 ; i++)
{
if (cl.items & (1<<(29+i)))
{
time = cl.item_gettime[29+i];
if (time && time > cl.time - 2 && flashon )
{ // flash frame
sb_updates = 0;
}
else
{
Sbar_DrawPic (288 + i*16, -16, rsb_items[i]);
}
if (time && time > cl.time - 2)
sb_updates = 0;
}
}
}
else
{
// sigils
for (i=0 ; i<4 ; i++)
{
if (cl.items & (1<<(28+i)))
{
time = cl.item_gettime[28+i];
if (time && time > cl.time - 2 && flashon )
{ // flash frame
sb_updates = 0;
}
else
Sbar_DrawPic (320-32 + i*8, -16, sb_sigil[i]);
if (time && time > cl.time - 2)
sb_updates = 0;
}
}
}
}
//=============================================================================
/*
===============
Sbar_DrawFrags
===============
*/
void Sbar_DrawFrags (void)
{
int i, k, l;
int top, bottom;
int x, y, f;
int xofs;
char num[12];
scoreboard_t *s;
Sbar_SortFrags ();
// draw the text
l = scoreboardlines <= 4 ? scoreboardlines : 4;
x = 23;
if (cl.gametype == GAME_DEATHMATCH)
xofs = 0;
else
xofs = (vid.width - 320)>>1;
y = vid.height - SBAR_HEIGHT - 23;
for (i=0 ; i<l ; i++)
{
k = fragsort[i];
s = &cl.scores[k];
if (!s->name[0])
continue;
// draw background
top = s->colors & 0xf0;
bottom = (s->colors & 15)<<4;
top = Sbar_ColorForMap (top);
bottom = Sbar_ColorForMap (bottom);
Draw_Fill (xofs + x*8 + 10, y, 28, 4, top);
Draw_Fill (xofs + x*8 + 10, y+4, 28, 3, bottom);
// draw number
f = s->frags;
sprintf (num, "%3i",f);
Sbar_DrawCharacter ( (x+1)*8 , -24, num[0]);
Sbar_DrawCharacter ( (x+2)*8 , -24, num[1]);
Sbar_DrawCharacter ( (x+3)*8 , -24, num[2]);
if (k == cl.viewentity - 1)
{
Sbar_DrawCharacter (x*8+2, -24, 16);
Sbar_DrawCharacter ( (x+4)*8-4, -24, 17);
}
x+=4;
}
}
//=============================================================================
/*
===============
Sbar_DrawFace
===============
*/
void Sbar_DrawFace (void)
{
int f, anim;
// PGM 01/19/97 - team color drawing
// PGM 03/02/97 - fixed so color swatch only appears in CTF modes
if (rogue &&
(cl.maxclients != 1) &&
(teamplay.value>3) &&
(teamplay.value<7))
{
int top, bottom;
int xofs;
char num[12];
scoreboard_t *s;
s = &cl.scores[cl.viewentity - 1];
// draw background
top = s->colors & 0xf0;
bottom = (s->colors & 15)<<4;
top = Sbar_ColorForMap (top);
bottom = Sbar_ColorForMap (bottom);
if (cl.gametype == GAME_DEATHMATCH)
xofs = 113;
else
xofs = ((vid.width - 320)>>1) + 113;
Sbar_DrawPic (112, 0, rsb_teambord);
Draw_Fill (xofs, vid.height-SBAR_HEIGHT+3, 22, 9, top);
Draw_Fill (xofs, vid.height-SBAR_HEIGHT+12, 22, 9, bottom);
// draw number
f = s->frags;
sprintf (num, "%3i",f);
if (top==8)
{
if (num[0] != ' ')
Sbar_DrawCharacter(109, 3, 18 + num[0] - '0');
if (num[1] != ' ')
Sbar_DrawCharacter(116, 3, 18 + num[1] - '0');
if (num[2] != ' ')
Sbar_DrawCharacter(123, 3, 18 + num[2] - '0');
}
else
{
Sbar_DrawCharacter ( 109, 3, num[0]);
Sbar_DrawCharacter ( 116, 3, num[1]);
Sbar_DrawCharacter ( 123, 3, num[2]);
}
return;
}
// PGM 01/19/97 - team color drawing
if ( (cl.items & (IT_INVISIBILITY | IT_INVULNERABILITY) )
== (IT_INVISIBILITY | IT_INVULNERABILITY) )
{
Sbar_DrawPic (112, 0, sb_face_invis_invuln);
return;
}
if (cl.items & IT_QUAD)
{
Sbar_DrawPic (112, 0, sb_face_quad );
return;
}
if (cl.items & IT_INVISIBILITY)
{
Sbar_DrawPic (112, 0, sb_face_invis );
return;
}
if (cl.items & IT_INVULNERABILITY)
{
Sbar_DrawPic (112, 0, sb_face_invuln);
return;
}
if (cl.stats[STAT_HEALTH] >= 100)
f = 4;
else
f = cl.stats[STAT_HEALTH] / 20;
if (cl.time <= cl.faceanimtime)
{
anim = 1;
sb_updates = 0; // make sure the anim gets drawn over
}
else
anim = 0;
Sbar_DrawPic (112, 0, sb_faces[f][anim]);
}
/*
===============
Sbar_Draw
===============
*/
void Sbar_Draw (void)
{
if (scr_con_current == vid.height)
return; // console is full screen
#if 0
if (sb_updates >= vid.numpages)
return;
#else
// Always draw status bar, to handle hardware that always destroys
// the frame buffer. (essentially an infinite number of vid pages.)
#endif
scr_copyeverything = 1;
sb_updates++;
if (sb_lines && vid.width > 320)
Draw_TileClear (0, vid.height - sb_lines, vid.width, sb_lines);
if (sb_lines > 24)
{
Sbar_DrawInventory ();
if (cl.maxclients != 1)
Sbar_DrawFrags ();
}
if (sb_showscores || cl.stats[STAT_HEALTH] <= 0)
{
Sbar_DrawPic (0, 0, sb_scorebar);
Sbar_DrawScoreboard ();
sb_updates = 0;
}
else if (sb_lines)
{
Sbar_DrawPic (0, 0, sb_sbar);
// keys (hipnotic only)
//MED 01/04/97 moved keys here so they would not be overwritten
if (hipnotic)
{
if (cl.items & IT_KEY1)
Sbar_DrawPic (209, 3, sb_items[0]);
if (cl.items & IT_KEY2)
Sbar_DrawPic (209, 12, sb_items[1]);
}
// armor
if (cl.items & IT_INVULNERABILITY)
{
Sbar_DrawNum (24, 0, 666, 3, 1);
Sbar_DrawPic (0, 0, draw_disc);
}
else
{
if (rogue)
{
Sbar_DrawNum (24, 0, cl.stats[STAT_ARMOR], 3,
cl.stats[STAT_ARMOR] <= 25);
if (cl.items & RIT_ARMOR3)
Sbar_DrawPic (0, 0, sb_armor[2]);
else if (cl.items & RIT_ARMOR2)
Sbar_DrawPic (0, 0, sb_armor[1]);
else if (cl.items & RIT_ARMOR1)
Sbar_DrawPic (0, 0, sb_armor[0]);
}
else
{
Sbar_DrawNum (24, 0, cl.stats[STAT_ARMOR], 3
, cl.stats[STAT_ARMOR] <= 25);
if (cl.items & IT_ARMOR3)
Sbar_DrawPic (0, 0, sb_armor[2]);
else if (cl.items & IT_ARMOR2)
Sbar_DrawPic (0, 0, sb_armor[1]);
else if (cl.items & IT_ARMOR1)
Sbar_DrawPic (0, 0, sb_armor[0]);
}
}
// face
Sbar_DrawFace ();
// health
Sbar_DrawNum (136, 0, cl.stats[STAT_HEALTH], 3
, cl.stats[STAT_HEALTH] <= 25);
// ammo icon
if (rogue)
{
if (cl.items & RIT_SHELLS)
Sbar_DrawPic (224, 0, sb_ammo[0]);
else if (cl.items & RIT_NAILS)
Sbar_DrawPic (224, 0, sb_ammo[1]);
else if (cl.items & RIT_ROCKETS)
Sbar_DrawPic (224, 0, sb_ammo[2]);
else if (cl.items & RIT_CELLS)
Sbar_DrawPic (224, 0, sb_ammo[3]);
else if (cl.items & RIT_LAVA_NAILS)
Sbar_DrawPic (224, 0, rsb_ammo[0]);
else if (cl.items & RIT_PLASMA_AMMO)
Sbar_DrawPic (224, 0, rsb_ammo[1]);
else if (cl.items & RIT_MULTI_ROCKETS)
Sbar_DrawPic (224, 0, rsb_ammo[2]);
}
else
{
if (cl.items & IT_SHELLS)
Sbar_DrawPic (224, 0, sb_ammo[0]);
else if (cl.items & IT_NAILS)
Sbar_DrawPic (224, 0, sb_ammo[1]);
else if (cl.items & IT_ROCKETS)
Sbar_DrawPic (224, 0, sb_ammo[2]);
else if (cl.items & IT_CELLS)
Sbar_DrawPic (224, 0, sb_ammo[3]);
}
Sbar_DrawNum (248, 0, cl.stats[STAT_AMMO], 3,
cl.stats[STAT_AMMO] <= 10);
}
if (vid.width > 320) {
if (cl.gametype == GAME_DEATHMATCH)
Sbar_MiniDeathmatchOverlay ();
}
}
//=============================================================================
/*
==================
Sbar_IntermissionNumber
==================
*/
void Sbar_IntermissionNumber (int x, int y, int num, int digits, int color)
{
char str[12];
char *ptr;
int l, frame;
l = Sbar_itoa (num, str);
ptr = str;
if (l > digits)
ptr += (l-digits);
if (l < digits)
x += (digits-l)*24;
while (*ptr)
{
if (*ptr == '-')
frame = STAT_MINUS;
else
frame = *ptr -'0';
Draw_TransPic (x,y,sb_nums[color][frame]);
x += 24;
ptr++;
}
}
/*
==================
Sbar_DeathmatchOverlay
==================
*/
void Sbar_DeathmatchOverlay (void)
{
qpic_t *pic;
int i, k, l;
int top, bottom;
int x, y, f;
char num[12];
scoreboard_t *s;
scr_copyeverything = 1;
scr_fullupdate = 0;
pic = Draw_CachePic ("gfx/ranking.lmp");
M_DrawPic ((320-pic->width)/2, 8, pic);
// scores
Sbar_SortFrags ();
// draw the text
l = scoreboardlines;
x = 80 + ((vid.width - 320)>>1);
y = 40;
for (i=0 ; i<l ; i++)
{
k = fragsort[i];
s = &cl.scores[k];
if (!s->name[0])
continue;
// draw background
top = s->colors & 0xf0;
bottom = (s->colors & 15)<<4;
top = Sbar_ColorForMap (top);
bottom = Sbar_ColorForMap (bottom);
Draw_Fill ( x, y, 40, 4, top);
Draw_Fill ( x, y+4, 40, 4, bottom);
// draw number
f = s->frags;
sprintf (num, "%3i",f);
Draw_Character ( x+8 , y, num[0]);
Draw_Character ( x+16 , y, num[1]);
Draw_Character ( x+24 , y, num[2]);
if (k == cl.viewentity - 1)
Draw_Character ( x - 8, y, 12);
#if 0
{
int total;
int n, minutes, tens, units;
// draw time
total = cl.completed_time - s->entertime;
minutes = (int)total/60;
n = total - minutes*60;
tens = n/10;
units = n%10;
sprintf (num, "%3i:%i%i", minutes, tens, units);
Draw_String ( x+48 , y, num);
}
#endif
// draw name
Draw_String (x+64, y, s->name);
y += 10;
}
}
/*
==================
Sbar_DeathmatchOverlay
==================
*/
void Sbar_MiniDeathmatchOverlay (void)
{
qpic_t *pic;
int i, k, l;
int top, bottom;
int x, y, f;
char num[12];
scoreboard_t *s;
int numlines;
if (vid.width < 512 || !sb_lines)
return;
scr_copyeverything = 1;
scr_fullupdate = 0;
// scores
Sbar_SortFrags ();
// draw the text
l = scoreboardlines;
y = vid.height - sb_lines;
numlines = sb_lines/8;
if (numlines < 3)
return;
//find us
for (i = 0; i < scoreboardlines; i++)
if (fragsort[i] == cl.viewentity - 1)
break;
if (i == scoreboardlines) // we're not there
i = 0;
else // figure out start
i = i - numlines/2;
if (i > scoreboardlines - numlines)
i = scoreboardlines - numlines;
if (i < 0)
i = 0;
x = 324;
for (/* */; i < scoreboardlines && y < (int) (vid.height - 8) ; i++)
{
k = fragsort[i];
s = &cl.scores[k];
if (!s->name[0])
continue;
// draw background
top = s->colors & 0xf0;
bottom = (s->colors & 15)<<4;
top = Sbar_ColorForMap (top);
bottom = Sbar_ColorForMap (bottom);
Draw_Fill ( x, y+1, 40, 3, top);
Draw_Fill ( x, y+4, 40, 4, bottom);
// draw number
f = s->frags;
sprintf (num, "%3i",f);
Draw_Character ( x+8 , y, num[0]);
Draw_Character ( x+16 , y, num[1]);
Draw_Character ( x+24 , y, num[2]);
if (k == cl.viewentity - 1) {
Draw_Character ( x, y, 16);
Draw_Character ( x + 32, y, 17);
}
#if 0
{
int total;
int n, minutes, tens, units;
// draw time
total = cl.completed_time - s->entertime;
minutes = (int)total/60;
n = total - minutes*60;
tens = n/10;
units = n%10;
sprintf (num, "%3i:%i%i", minutes, tens, units);
Draw_String ( x+48 , y, num);
}
#endif
// draw name
Draw_String (x+48, y, s->name);
y += 8;
}
}
/*
==================
Sbar_IntermissionOverlay
==================
*/
void Sbar_IntermissionOverlay (void)
{
qpic_t *pic;
int dig;
int num;
scr_copyeverything = 1;
scr_fullupdate = 0;
if (cl.gametype == GAME_DEATHMATCH)
{
Sbar_DeathmatchOverlay ();
return;
}
pic = Draw_CachePic ("gfx/complete.lmp");
Draw_Pic (64, 24, pic);
pic = Draw_CachePic ("gfx/inter.lmp");
Draw_TransPic (0, 56, pic);
// time
dig = cl.completed_time/60;
Sbar_IntermissionNumber (160, 64, dig, 3, 0);
num = cl.completed_time - dig*60;
Draw_TransPic (234,64,sb_colon);
Draw_TransPic (246,64,sb_nums[0][num/10]);
Draw_TransPic (266,64,sb_nums[0][num%10]);
Sbar_IntermissionNumber (160, 104, cl.stats[STAT_SECRETS], 3, 0);
Draw_TransPic (232,104,sb_slash);
Sbar_IntermissionNumber (240, 104, cl.stats[STAT_TOTALSECRETS], 3, 0);
Sbar_IntermissionNumber (160, 144, cl.stats[STAT_MONSTERS], 3, 0);
Draw_TransPic (232,144,sb_slash);
Sbar_IntermissionNumber (240, 144, cl.stats[STAT_TOTALMONSTERS], 3, 0);
}
/*
==================
Sbar_FinaleOverlay
==================
*/
void Sbar_FinaleOverlay (void)
{
qpic_t *pic;
scr_copyeverything = 1;
pic = Draw_CachePic ("gfx/finale.lmp");
Draw_TransPic ( (vid.width-pic->width)/2, 16, pic);
}
| C++ |
/*
Copyright (C) 1996-1997 Id Software, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// snd_mix.c -- portable code to mix sounds for snd_dma.c
#include "quakedef.h"
#ifdef _WIN32
#include "winquake.h"
#else
#define DWORD unsigned long
#endif
#define PAINTBUFFER_SIZE 512
typedef union {
portable_samplepair_t paintbuffer[PAINTBUFFER_SIZE];
int intbuf[PAINTBUFFER_SIZE * sizeof(portable_samplepair_t) / sizeof(int)];
} portableOrInt_t;
portableOrInt_t paintbuffer;
int snd_scaletable[32][256];
int *snd_p, snd_linear_count, snd_vol;
short *snd_out;
void Snd_WriteLinearBlastStereo16 (void);
extern void SNDDMA_ReportWrite(size_t lengthBytes);
#if !id386
void Snd_WriteLinearBlastStereo16 (void)
{
int i;
int val;
for (i=0 ; i<snd_linear_count ; i+=2)
{
val = (snd_p[i]*snd_vol)>>8;
if (val > 0x7fff)
snd_out[i] = 0x7fff;
else if (val < (short)0x8000)
snd_out[i] = (short)0x8000;
else
snd_out[i] = val;
val = (snd_p[i+1]*snd_vol)>>8;
if (val > 0x7fff)
snd_out[i+1] = 0x7fff;
else if (val < (short)0x8000)
snd_out[i+1] = (short)0x8000;
else
snd_out[i+1] = val;
}
SNDDMA_ReportWrite(snd_linear_count << 1);
}
#endif
void S_TransferStereo16 (int endtime)
{
int lpos;
int lpaintedtime;
DWORD *pbuf;
#ifdef _WIN32
int reps;
DWORD dwSize,dwSize2;
DWORD *pbuf2;
HRESULT hresult;
#endif
snd_vol = (int)(volume.value*256);
snd_p = paintbuffer.intbuf;
lpaintedtime = paintedtime;
#ifdef _WIN32
if (pDSBuf)
{
reps = 0;
while ((hresult = pDSBuf->lpVtbl->Lock(pDSBuf, 0, gSndBufSize, &pbuf, &dwSize,
&pbuf2, &dwSize2, 0)) != DS_OK)
{
if (hresult != DSERR_BUFFERLOST)
{
Con_Printf ("S_TransferStereo16: DS::Lock Sound Buffer Failed\n");
S_Shutdown ();
S_Startup ();
return;
}
if (++reps > 10000)
{
Con_Printf ("S_TransferStereo16: DS: couldn't restore buffer\n");
S_Shutdown ();
S_Startup ();
return;
}
}
}
else
#endif
{
pbuf = (DWORD *)shm->buffer;
}
while (lpaintedtime < endtime)
{
// handle recirculating buffer issues
lpos = lpaintedtime & ((shm->samples>>1)-1);
snd_out = (short *) pbuf + (lpos<<1);
snd_linear_count = (shm->samples>>1) - lpos;
if (lpaintedtime + snd_linear_count > endtime)
snd_linear_count = endtime - lpaintedtime;
snd_linear_count <<= 1;
// write a linear blast of samples
Snd_WriteLinearBlastStereo16 ();
snd_p += snd_linear_count;
lpaintedtime += (snd_linear_count>>1);
}
#ifdef _WIN32
if (pDSBuf)
pDSBuf->lpVtbl->Unlock(pDSBuf, pbuf, dwSize, NULL, 0);
#endif
}
void S_TransferPaintBuffer(int endtime)
{
int out_idx;
int count;
int out_mask;
int *p;
int step;
int val;
int snd_vol;
DWORD *pbuf;
#ifdef _WIN32
int reps;
DWORD dwSize,dwSize2;
DWORD *pbuf2;
HRESULT hresult;
#endif
if (shm->samplebits == 16 && shm->channels == 2)
{
S_TransferStereo16 (endtime);
return;
}
p = paintbuffer.intbuf;
count = (endtime - paintedtime) * shm->channels;
out_mask = shm->samples - 1;
out_idx = paintedtime * shm->channels & out_mask;
step = 3 - shm->channels;
snd_vol = (int)(volume.value*256);
#ifdef _WIN32
if (pDSBuf)
{
reps = 0;
while ((hresult = pDSBuf->lpVtbl->Lock(pDSBuf, 0, gSndBufSize, &pbuf, &dwSize,
&pbuf2,&dwSize2, 0)) != DS_OK)
{
if (hresult != DSERR_BUFFERLOST)
{
Con_Printf ("S_TransferPaintBuffer: DS::Lock Sound Buffer Failed\n");
S_Shutdown ();
S_Startup ();
return;
}
if (++reps > 10000)
{
Con_Printf ("S_TransferPaintBuffer: DS: couldn't restore buffer\n");
S_Shutdown ();
S_Startup ();
return;
}
}
}
else
#endif
{
pbuf = (DWORD *)shm->buffer;
}
if (shm->samplebits == 16)
{
short *out = (short *) pbuf;
while (count--)
{
val = (*p * snd_vol) >> 8;
p+= step;
if (val > 0x7fff)
val = 0x7fff;
else if (val < (short)0x8000)
val = (short)0x8000;
out[out_idx] = val;
out_idx = (out_idx + 1) & out_mask;
}
}
else if (shm->samplebits == 8)
{
unsigned char *out = (unsigned char *) pbuf;
while (count--)
{
val = (*p * snd_vol) >> 8;
p+= step;
if (val > 0x7fff)
val = 0x7fff;
else if (val < (short)0x8000)
val = (short)0x8000;
out[out_idx] = (val>>8) + 128;
out_idx = (out_idx + 1) & out_mask;
}
}
#ifdef _WIN32
if (pDSBuf) {
DWORD dwNewpos, dwWrite;
int il = paintedtime;
int ir = endtime - paintedtime;
ir += il;
pDSBuf->lpVtbl->Unlock(pDSBuf, pbuf, dwSize, NULL, 0);
pDSBuf->lpVtbl->GetCurrentPosition(pDSBuf, &dwNewpos, &dwWrite);
// if ((dwNewpos >= il) && (dwNewpos <= ir))
// Con_Printf("%d-%d p %d c\n", il, ir, dwNewpos);
}
#endif
}
/*
===============================================================================
CHANNEL MIXING
===============================================================================
*/
void SND_PaintChannelFrom8 (channel_t *ch, sfxcache_t *sc, int endtime);
void SND_PaintChannelFrom16 (channel_t *ch, sfxcache_t *sc, int endtime);
void S_PaintChannels(int endtime)
{
int i;
int end;
channel_t *ch;
sfxcache_t *sc;
int ltime, count;
while (paintedtime < endtime)
{
// if paintbuffer is smaller than DMA buffer
end = endtime;
if (endtime - paintedtime > PAINTBUFFER_SIZE)
end = paintedtime + PAINTBUFFER_SIZE;
// clear the paint buffer
Q_memset(paintbuffer.paintbuffer, 0, (end - paintedtime) * sizeof(portable_samplepair_t));
// paint in the channels.
ch = channels;
for (i=0; i<total_channels ; i++, ch++)
{
if (!ch->sfx)
continue;
if (!ch->leftvol && !ch->rightvol)
continue;
sc = S_LoadSound (ch->sfx);
if (!sc)
continue;
ltime = paintedtime;
while (ltime < end)
{ // paint up to end
if (ch->end < end)
count = ch->end - ltime;
else
count = end - ltime;
if (count > 0)
{
if (sc->width == 1)
SND_PaintChannelFrom8(ch, sc, count);
else
SND_PaintChannelFrom16(ch, sc, count);
ltime += count;
}
// if at end of loop, restart
if (ltime >= ch->end)
{
if (sc->loopstart >= 0)
{
ch->pos = sc->loopstart;
ch->end = ltime + sc->length - ch->pos;
}
else
{ // channel just stopped
ch->sfx = NULL;
break;
}
}
}
}
// transfer out according to DMA format
S_TransferPaintBuffer(end);
paintedtime = end;
}
}
void SND_InitScaletable (void)
{
int i, j;
for (i=0 ; i<32 ; i++)
for (j=0 ; j<256 ; j++)
snd_scaletable[i][j] = ((signed char)j) * i * 8;
}
#if !id386
void SND_PaintChannelFrom8 (channel_t *ch, sfxcache_t *sc, int count)
{
int data;
int *lscale, *rscale;
unsigned char *sfx;
int i;
if (ch->leftvol > 255)
ch->leftvol = 255;
if (ch->rightvol > 255)
ch->rightvol = 255;
lscale = snd_scaletable[ch->leftvol >> 3];
rscale = snd_scaletable[ch->rightvol >> 3];
sfx = sc->data.uc + ch->pos;
for (i=0 ; i<count ; i++)
{
data = sfx[i];
paintbuffer.paintbuffer[i].left += lscale[data];
paintbuffer.paintbuffer[i].right += rscale[data];
}
ch->pos += count;
}
#endif // !id386
void SND_PaintChannelFrom16 (channel_t *ch, sfxcache_t *sc, int count)
{
int data;
int left, right;
int leftvol, rightvol;
signed short *sfx;
int i;
leftvol = ch->leftvol;
rightvol = ch->rightvol;
sfx = sc->data.ss + ch->pos;
for (i=0 ; i<count ; i++)
{
data = sfx[i];
left = (data * leftvol) >> 8;
right = (data * rightvol) >> 8;
paintbuffer.paintbuffer[i].left += left;
paintbuffer.paintbuffer[i].right += right;
}
ch->pos += count;
}
| C++ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.