Add files via upload

This commit is contained in:
0TheSpy
2021-06-16 16:11:47 +03:00
committed by GitHub
parent d05ba71db8
commit 692f7e2f3d
97 changed files with 32215 additions and 0 deletions

79
SpyCustom/IVGUI.h Normal file
View File

@ -0,0 +1,79 @@
#ifndef IVGUI_H
#define IVGUI_H
#ifdef _WIN32
#pragma once
#endif
#include "interface.h"
#include "VGUI.h"
#include "IAppSystem.h"
class KeyValues;
namespace vgui
{
typedef unsigned long HPanel;
typedef int HContext;
enum
{
DEFAULT_VGUI_CONTEXT = ((vgui::HContext)~0)
};
typedef unsigned long HPanel;
class IVGui : public IAppSystem
{
public:
virtual void Start() = 0;
virtual void Stop() = 0;
virtual bool IsRunning() = 0;
virtual void RunFrame() = 0;
virtual void ShutdownMessage(unsigned int shutdownID) = 0;
virtual VPANEL AllocPanel() = 0;
virtual void FreePanel(VPANEL panel) = 0;
virtual void DPrintf(PRINTF_FORMAT_STRING const char* format, ...) = 0;
virtual void DPrintf2(PRINTF_FORMAT_STRING const char* format, ...) = 0;
virtual void SpewAllActivePanelNames() = 0;
virtual HPanel PanelToHandle(VPANEL panel) = 0;
virtual VPANEL HandleToPanel(HPanel index) = 0;
virtual void MarkPanelForDeletion(VPANEL panel) = 0;
virtual void AddTickSignal(VPANEL panel, int intervalMilliseconds = 0) = 0;
virtual void RemoveTickSignal(VPANEL panel) = 0;
virtual void PostMessage(VPANEL target, KeyValues* params, VPANEL from, float delaySeconds = 0.0f) = 0;
virtual HContext CreateContext() = 0;
virtual void DestroyContext(HContext context) = 0;
virtual void AssociatePanelWithContext(HContext context, VPANEL pRoot) = 0;
virtual void ActivateContext(HContext context) = 0;
virtual void SetSleep(bool state) = 0;
virtual bool GetShouldVGuiControlSleep() = 0;
virtual void SetVRMode(bool bVRMode) = 0;
virtual bool GetVRMode() = 0;
virtual void AddTickSignalToHead(VPANEL panel, int intervalMilliseconds = 0) = 0;
};
#define VGUI_IVGUI_INTERFACE_VERSION "VGUI_ivgui008"
};
#endif

17
SpyCustom/IVguiMatInfo.h Normal file
View File

@ -0,0 +1,17 @@
#ifndef IVGUIMATINFO_H
#define IVGUIMATINFO_H
#include "IVguiMatInfoVar.h"
class IVguiMatInfo
{
public:
virtual ~IVguiMatInfo() {}
virtual IVguiMatInfoVar* FindVarFactory(const char* varName, bool* found) = 0;
virtual int GetNumAnimationFrames() = 0;
};
#endif

View File

@ -0,0 +1,15 @@
#ifndef IVGUIMATINFOVAR_H
#define IVGUIMATINFOVAR_H
class IVguiMatInfoVar
{
public:
virtual ~IVguiMatInfoVar() {}
virtual int GetIntValue(void) const = 0;
virtual void SetIntValue(int val) = 0;
};
#endif

206
SpyCustom/KeyBindingMap.h Normal file
View File

@ -0,0 +1,206 @@
#ifndef KEYBINDINGMAP_H
#define KEYBINDINGMAP_H
#ifdef _WIN32
#pragma once
#endif
#include "utlvector.h"
namespace vgui
{
class Panel;
enum
{
MODIFIER_SHIFT = (1 << 0),
MODIFIER_CONTROL = (1 << 1),
MODIFIER_ALT = (1 << 2),
};
struct BoundKey_t
{
BoundKey_t();
BoundKey_t(const BoundKey_t& src);
~BoundKey_t();
BoundKey_t& operator =(const BoundKey_t& src);
bool isbuiltin;
char const* bindingname;
int keycode;
int modifiers;
};
struct KeyBindingMap_t
{
KeyBindingMap_t();
KeyBindingMap_t(const KeyBindingMap_t& src);
~KeyBindingMap_t();
char const* bindingname;
ALIGN16 MessageFunc_t func;
char const* helpstring;
char const* docstring;
bool passive;
};
#define DECLARE_KEYBINDINGMAP( className ) \
static void KB_AddToMap \
( \
char const *bindingname, \
vgui::KeyCode defaultcode, \
int default_modifiers, \
vgui::MessageFunc_t function, \
char const *helpstring, \
char const *docstring, \
bool passive \
) \
{ \
vgui::PanelKeyBindingMap *map = vgui::FindOrAddPanelKeyBindingMap( GetPanelClassName() ); \
\
vgui::KeyBindingMap_t entry; \
entry.bindingname = bindingname; \
\
entry.func = function; \
\
entry.helpstring = helpstring; \
entry.docstring = docstring; \
\
entry.passive = passive; \
\
map->entries.AddToTail( entry ); \
\
vgui::BoundKey_t kb; \
kb.isbuiltin = true; \
kb.bindingname = bindingname; \
kb.keycode = defaultcode; \
kb.modifiers = default_modifiers; \
map->defaultkeys.AddToTail( kb ); \
map->boundkeys.AddToTail( kb ); \
} \
\
static void KB_ChainToMap( void ) \
{ \
static bool chained = false; \
if ( chained ) \
return; \
chained = true; \
vgui::PanelKeyBindingMap *map = vgui::FindOrAddPanelKeyBindingMap( GetPanelClassName() ); \
map->pfnClassName = &GetPanelClassName; \
if ( map && GetPanelBaseClassName() && GetPanelBaseClassName()[0] ) \
{ \
map->baseMap = vgui::FindOrAddPanelKeyBindingMap( GetPanelBaseClassName() ); \
} \
} \
\
static void KB_AddBoundKey \
( \
char const *bindingname, \
int keycode, \
int modifiers \
) \
{ \
vgui::PanelKeyBindingMap *map = vgui::FindOrAddPanelKeyBindingMap( GetPanelClassName() ); \
vgui::BoundKey_t kb; \
kb.isbuiltin = true; \
kb.bindingname = bindingname; \
kb.keycode = keycode; \
kb.modifiers = modifiers; \
map->defaultkeys.AddToTail( kb ); \
map->boundkeys.AddToTail( kb ); \
} \
\
class className##_RegisterKBMap; \
friend class className##_RegisterKBMap; \
class className##_RegisterKBMap \
{ \
public: \
className##_RegisterKBMap() \
{ \
className::KB_ChainToMap(); \
} \
}; \
className##_RegisterKBMap m_RegisterClassKB; \
\
virtual vgui::PanelKeyBindingMap *GetKBMap() \
{ \
static vgui::PanelKeyBindingMap *s_pMap = vgui::FindOrAddPanelKeyBindingMap( GetPanelClassName() ); \
return s_pMap; \
}
#define _KBMapFuncCommonFunc( name, keycode, modifiers, function, help, doc, passive ) \
class PanelKBMapFunc_##name; \
friend class PanelKBMapFunc_##name; \
class PanelKBMapFunc_##name \
{ \
public: \
static void InitVar() \
{ \
static bool bAdded = false; \
if ( !bAdded ) \
{ \
bAdded = true; \
KB_AddToMap( #name, keycode, modifiers, (vgui::MessageFunc_t)&ThisClass::function, help, doc, passive ); \
} \
} \
PanelKBMapFunc_##name() \
{ \
PanelKBMapFunc_##name::InitVar(); \
} \
}; \
PanelKBMapFunc_##name m_##name##_register;
#define _KBBindKeyCommon( name, keycode, modifiers, _classname ) \
class PanelKBBindFunc_##_classname; \
friend class PanelKBBindFunc_##_classname; \
class PanelKBBindFunc_##_classname \
{ \
public: \
static void InitVar() \
{ \
static bool bAdded = false; \
if ( !bAdded ) \
{ \
bAdded = true; \
KB_AddBoundKey( #name, keycode, modifiers ); \
} \
} \
PanelKBBindFunc_##_classname() \
{ \
PanelKBBindFunc_##_classname::InitVar(); \
} \
}; \
PanelKBBindFunc_##_classname m_##_classname##_bindkey_register;
#define KEYBINDING_FUNC( name, keycode, modifiers, function, help, doc ) _KBMapFuncCommonFunc( name, keycode, modifiers, function, help, doc, false ); virtual void function()
#define KEYBINDING_FUNC_NODECLARE( name, keycode, modifiers, function, help, doc ) _KBMapFuncCommonFunc( name, keycode, modifiers, function, help, doc, false );
#define KEYBINDING_FUNC_PASSIVE( name, keycode, modifiers, function, help, doc ) _KBMapFuncCommonFunc( name, keycode, modifiers, function, help, doc, true ); virtual void function()
#define KEYBINDING_FUNC_PASSIVE_NODECLARE( name, keycode, modifiers, function, help, doc ) _KBMapFuncCommonFunc( name, keycode, modifiers, function, help, doc, true );
#define KEYBINDING_ADDBINDING( name, keycode, modifiers ) _KBBindKeyCommon( name, keycode, modifiers, name );
#define KEYBINDING_ADDBINDING_MULTIPLE( name, keycode, modifiers, _classname ) _KBBindKeyCommon( name, keycode, modifiers, _classname );
struct PanelKeyBindingMap
{
PanelKeyBindingMap()
{
baseMap = NULL;
pfnClassName = NULL;
processed = false;
}
CUtlVector< KeyBindingMap_t > entries;
bool processed;
PanelKeyBindingMap* baseMap;
CUtlVector< BoundKey_t > defaultkeys;
CUtlVector< BoundKey_t > boundkeys;
char const* (*pfnClassName)(void);
};
PanelKeyBindingMap* FindPanelKeyBindingMap(char const* className);
PanelKeyBindingMap* FindOrAddPanelKeyBindingMap(char const* className);
}
#endif

15
SpyCustom/KeyCode.h Normal file
View File

@ -0,0 +1,15 @@
#ifndef KEYCODE_H
#define KEYCODE_H
#ifdef _WIN32
#pragma once
#endif
#include "ButtonCode.h"
namespace vgui
{
typedef ButtonCode_t KeyCode;
}
#endif

1830
SpyCustom/KeyValues.cpp Normal file

File diff suppressed because it is too large Load Diff

167
SpyCustom/Label.h Normal file
View File

@ -0,0 +1,167 @@
#ifndef LABEL_H
#define LABEL_H
#ifdef _WIN32
#pragma once
#endif
#include "utlvector.h"
#include "VGUI.h"
#include "Panel.h"
#include "PHandle.h"
namespace vgui
{
class Label : public Panel
{
DECLARE_CLASS_SIMPLE(Label, Panel);
public:
Label(Panel* parent, const char* panelName, const char* text);
Label(Panel* parent, const char* panelName, const wchar_t* wszText);
~Label();
public:
virtual void SetText(const char* tokenName);
virtual void SetText(const wchar_t* unicodeString, bool bClearUnlocalizedSymbol = false);
virtual void GetText(OUT_Z_BYTECAP(bufferLen) char* textOut, int bufferLen);
virtual void GetText(OUT_Z_BYTECAP(bufLenInBytes) wchar_t* textOut, int bufLenInBytes);
virtual void GetContentSize(int& wide, int& tall);
enum Alignment
{
a_northwest = 0,
a_north,
a_northeast,
a_west,
a_center,
a_east,
a_southwest,
a_south,
a_southeast,
};
virtual void SetContentAlignment(Alignment alignment);
virtual void SetEnabled(bool state);
virtual void SetTextInset(int xInset, int yInset);
virtual void GetTextInset(int* xInset, int* yInset);
virtual void SetFgColor(Color color);
virtual Color GetFgColor();
virtual void SetDisabledFgColor1(Color color);
virtual void SetDisabledFgColor2(Color color);
virtual Color GetDisabledFgColor1();
virtual Color GetDisabledFgColor2();
enum EColorState
{
CS_NORMAL,
CS_DULL,
CS_BRIGHT,
};
virtual void SetTextColorState(EColorState state);
virtual void SetFont(HFont font);
virtual HFont GetFont();
virtual Panel* HasHotkey(wchar_t key);
virtual void SetHotkey(wchar_t key);
virtual wchar_t GetHotKey();
virtual void SetAssociatedControl(Panel* control);
virtual int AddImage(IImage* image, int preOffset);
virtual void SetImageAtIndex(int index, IImage* image, int preOffset);
virtual void SetImagePreOffset(int index, int preOffset);
virtual IImage* GetImageAtIndex(int index);
virtual int GetImageCount();
virtual void ClearImages();
virtual void ResetToSimpleTextImage();
virtual void SetImageBounds(int index, int x, int width);
virtual TextImage* GetTextImage();
virtual int SetTextImageIndex(int newIndex);
virtual bool RequestInfo(KeyValues* outputData);
virtual void SizeToContents();
enum Padding
{
Content = 8,
};
void SetWrap(bool bWrap);
void SetCenterWrap(bool bWrap);
void SetAllCaps(bool bAllCaps);
protected:
virtual void PerformLayout();
virtual wchar_t CalculateHotkey(const char* text);
virtual wchar_t CalculateHotkey(const wchar_t* text);
virtual void ComputeAlignment(int& tx0, int& ty0, int& tx1, int& ty1);
virtual void Paint();
MESSAGE_FUNC_PARAMS(OnSetText, "SetText", params);
virtual void DrawDashedLine(int x0, int y0, int x1, int y1, int dashLen, int gapLen);
virtual void OnRequestFocus(VPANEL subFocus, VPANEL defaultPanel);
MESSAGE_FUNC(OnHotkeyPressed, "Hotkey");
virtual void OnMousePressed(MouseCode code);
virtual void OnSizeChanged(int wide, int tall);
virtual void EnsureImageCapacity(int maxIndex);
virtual void ApplySchemeSettings(IScheme* pScheme);
virtual void GetSettings(KeyValues* outResourceData);
virtual void ApplySettings(KeyValues* inResourceData);
virtual const char* GetDescription(void);
MESSAGE_FUNC_PARAMS(OnDialogVariablesChanged, "DialogVariables", dialogVariables);
void HandleAutoSizing(void);
private:
void Init();
Alignment _contentAlignment;
TextImage* _textImage;
struct TImageInfo
{
IImage* image;
short offset;
short xpos;
short width;
};
CUtlVector<TImageInfo> _imageDar;
int _textInset[2];
Color _disabledFgColor1;
Color _disabledFgColor2;
Color _associateColor;
int _textImageIndex;
EColorState _textColorState;
PHandle _associate;
char* _associateName;
char* _fontOverrideName;
wchar_t _hotkey;
bool m_bWrap;
bool m_bCenterWrap;
bool m_bAllCaps;
bool m_bAutoWideToContents;
bool m_bAutoWideDirty;
bool m_bUseProportionalInsets;
};
}
#endif

304
SpyCustom/ListPanel.h Normal file
View File

@ -0,0 +1,304 @@
#ifndef LISTPANEL_H
#define LISTPANEL_H
#ifdef _WIN32
#pragma once
#endif
#include "utllinkedlist.h"
#include "utlvector.h"
#include "utlrbtree.h"
#include "VGUI.h"
#include "Panel.h"
class KeyValues;
namespace vgui
{
class ScrollBar;
class TextImage;
class ImagePanel;
class Label;
class Button;
class IDraggerEvent;
class FastSortListPanelItem;
class ListPanelItem
{
public:
ListPanelItem() :
kv(0),
userData(0),
m_pDragData(0),
m_bImage(false),
m_nImageIndex(-1),
m_nImageIndexSelected(-1),
m_pIcon(0)
{
}
KeyValues* kv;
unsigned int userData;
KeyValues* m_pDragData;
bool m_bImage;
int m_nImageIndex;
int m_nImageIndexSelected;
IImage* m_pIcon;
};
typedef int __cdecl SortFunc(
ListPanel* pPanel,
const ListPanelItem& item1,
const ListPanelItem& item2);
class ListPanel : public Panel
{
DECLARE_CLASS_SIMPLE(ListPanel, Panel);
public:
ListPanel(Panel* parent, const char* panelName);
~ListPanel();
enum ColumnFlags_e
{
COLUMN_FIXEDSIZE = 0x01,
COLUMN_RESIZEWITHWINDOW = 0x02,
COLUMN_IMAGE = 0x04,
COLUMN_HIDDEN = 0x08,
COLUMN_UNHIDABLE = 0x10,
};
virtual void AddColumnHeader(int index, const char* columnName, const char* columnText, int startingWidth, int minWidth, int maxWidth, int columnFlags = 0);
virtual void AddColumnHeader(int index, const char* columnName, const char* columnText, int width, int columnFlags = 0);
virtual void RemoveColumn(int column);
virtual int FindColumn(const char* columnName);
virtual void SetColumnHeaderHeight(int height);
virtual void SetColumnHeaderText(int column, const char* text);
virtual void SetColumnHeaderText(int column, wchar_t* text);
virtual void SetColumnHeaderImage(int column, int imageListIndex);
virtual void SetColumnHeaderTooltip(int column, const char* tooltipText);
virtual void SetColumnTextAlignment(int column, int align);
virtual int GetNumColumnHeaders() const;
virtual bool GetColumnHeaderText(int index, char* pOut, int maxLen);
virtual void SetSortFunc(int column, SortFunc* func);
virtual void SetSortColumn(int column);
virtual void SortList(void);
virtual void SetColumnSortable(int column, bool sortable);
virtual void SetColumnVisible(int column, bool visible);
int GetSortColumn() const;
virtual void SetAllowUserModificationOfColumns(bool allowed);
virtual int AddItem(const KeyValues* data, unsigned int userData, bool bScrollToItem, bool bSortOnAdd);
void SetItemDragData(int itemID, const KeyValues* data);
virtual int GetItemCount(void);
virtual int GetItem(const char* itemName);
virtual KeyValues* GetItem(int itemID);
virtual int GetItemCurrentRow(int itemID);
virtual int GetItemIDFromRow(int currentRow);
virtual unsigned int GetItemUserData(int itemID);
virtual ListPanelItem* GetItemData(int itemID);
virtual void SetUserData(int itemID, unsigned int userData);
virtual int GetItemIDFromUserData(unsigned int userData);
virtual void ApplyItemChanges(int itemID);
virtual void RemoveItem(int itemID);
virtual void RereadAllItems();
virtual void RemoveAll();
virtual void DeleteAllItems();
virtual void GetCellText(int itemID, int column, OUT_Z_BYTECAP(bufferSizeInBytes) wchar_t* buffer, int bufferSizeInBytes);
virtual IImage* GetCellImage(int itemID, int column);
virtual int FirstItem() const;
virtual int NextItem(int iItem) const;
virtual int InvalidItemID() const;
virtual bool IsValidItemID(int itemID);
virtual void SetItemVisible(int itemID, bool state);
virtual void SetItemDisabled(int itemID, bool state);
bool IsItemVisible(int itemID);
virtual void SetFont(HFont font);
virtual void SetImageList(ImageList* imageList, bool deleteImageListWhenDone);
virtual int GetSelectedItemsCount();
virtual int GetSelectedItem(int selectionIndex);
virtual void ClearSelectedItems();
virtual bool IsItemSelected(int itemID);
virtual void AddSelectedItem(int itemID);
virtual void SetSingleSelectedItem(int itemID);
virtual int GetSelectedColumn();
virtual void SetSelectIndividualCells(bool state);
void SetMultiselectEnabled(bool bState);
bool IsMultiselectEnabled() const;
virtual void SetSelectedCell(int row, int column);
virtual bool GetCellAtPos(int x, int y, int& row, int& column);
virtual bool GetCellBounds(int row, int column, int& x, int& y, int& wide, int& tall);
virtual void SetEmptyListText(const char* text);
virtual void SetEmptyListText(const wchar_t* text);
void ResetScrollBar();
virtual void OnCreateDragData(KeyValues* msg);
void SetIgnoreDoubleClick(bool state);
virtual void EnterEditMode(int itemID, int column, vgui::Panel* editPanel);
virtual void LeaveEditMode();
virtual bool IsInEditMode();
MESSAGE_FUNC_INT(ResizeColumnToContents, "ResizeColumnToContents", column);
#ifdef _X360
virtual void NavigateTo();
#endif
int m_nUserConfigFileVersion;
protected:
virtual Panel* GetCellRenderer(int row, int column);
virtual void OnMouseWheeled(int delta);
virtual void OnSizeChanged(int wide, int tall);
virtual void PerformLayout();
virtual void Paint();
virtual void PaintBackground();
virtual void ApplySchemeSettings(IScheme* pScheme);
virtual void OnMousePressed(MouseCode code);
virtual void OnMouseDoublePressed(MouseCode code);
#ifdef _X360
virtual void OnKeyCodePressed(KeyCode code);
#else
virtual void OnKeyCodePressed(KeyCode code);
#endif
MESSAGE_FUNC(OnSliderMoved, "ScrollBarSliderMoved");
MESSAGE_FUNC_INT_INT(OnColumnResized, "ColumnResized", column, delta);
MESSAGE_FUNC_INT(OnSetSortColumn, "SetSortColumn", column);
MESSAGE_FUNC(OpenColumnChoiceMenu, "OpenColumnChoiceMenu");
MESSAGE_FUNC_INT(OnToggleColumnVisible, "ToggleColumnVisible", col);
virtual float GetRowsPerPage();
virtual int GetStartItem();
virtual void ApplyUserConfigSettings(KeyValues* userConfig);
virtual void GetUserConfigSettings(KeyValues* userConfig);
virtual bool HasUserConfigSettings();
public:
virtual void SetSortColumnEx(int iPrimarySortColumn, int iSecondarySortColumn, bool bSortAscending);
void GetSortColumnEx(int& iPrimarySortColumn, int& iSecondarySortColumn, bool& bSortAscending) const;
private:
void CleanupItem(FastSortListPanelItem* data);
void IndexItem(int itemID);
void UpdateSelection(vgui::MouseCode code, int x, int y, int row, int column);
void HandleMultiSelection(int itemID, int row, int column);
void HandleAddSelection(int itemID, int row, int column);
struct IndexItem_t
{
ListPanelItem* dataItem;
int duplicateIndex;
};
typedef CUtlRBTree<IndexItem_t, int> IndexRBTree_t;
struct column_t
{
Button* m_pHeader;
int m_iMinWidth;
int m_iMaxWidth;
bool m_bResizesWithWindow;
Panel* m_pResizer;
SortFunc* m_pSortFunc;
bool m_bTypeIsText;
bool m_bHidden;
bool m_bUnhidable;
IndexRBTree_t m_SortedTree;
int m_nContentAlignment;
};
CUtlLinkedList<column_t, unsigned char> m_ColumnsData;
CUtlVector<unsigned char> m_ColumnsHistory;
CUtlVector<unsigned char> m_CurrentColumns;
int m_iColumnDraggerMoved;
int m_lastBarWidth;
CUtlLinkedList<FastSortListPanelItem*, int> m_DataItems;
CUtlVector<int> m_VisibleItems;
int m_iSortColumn;
int m_iSortColumnSecondary;
void ResortColumnRBTree(int col);
static bool RBTreeLessFunc(vgui::ListPanel::IndexItem_t& item1, vgui::ListPanel::IndexItem_t& item2);
TextImage* m_pTextImage;
ImagePanel* m_pImagePanel;
Label* m_pLabel;
ScrollBar* m_hbar;
ScrollBar* m_vbar;
int m_iSelectedColumn;
bool m_bNeedsSort : 1;
bool m_bSortAscending : 1;
bool m_bSortAscendingSecondary : 1;
bool m_bCanSelectIndividualCells : 1;
bool m_bShiftHeldDown : 1;
bool m_bMultiselectEnabled : 1;
bool m_bAllowUserAddDeleteColumns : 1;
bool m_bDeleteImageListWhenDone : 1;
bool m_bIgnoreDoubleClick : 1;
int m_iHeaderHeight;
int m_iRowHeight;
CUtlVector<int> m_SelectedItems;
int m_LastItemSelected;
int m_iTableStartX;
int m_iTableStartY;
Color m_LabelFgColor;
Color m_DisabledColor;
Color m_SelectionFgColor;
Color m_DisabledSelectionFgColor;
ImageList* m_pImageList;
TextImage* m_pEmptyListText;
PHandle m_hEditModePanel;
int m_iEditModeItemID;
int m_iEditModeColumn;
void ResetColumnHeaderCommands();
};
}
#endif

View File

@ -0,0 +1,72 @@
#ifndef MATERIALSYSTEMUTIL_H
#define MATERIALSYSTEMUTIL_H
#ifdef _WIN32
#pragma once
#endif
#include "imageformat.h"
#include "imaterialsystem.h"
class IMaterial;
class ITexture;
class KeyValues;
class KeyValues;
class CMaterialReference
{
public:
CMaterialReference(char const* pMaterialName = 0, const char* pTextureGroupName = 0, bool bComplain = true);
~CMaterialReference();
void Init(const char* pMaterialName, const char* pTextureGroupName, bool bComplain = true);
void Init(const char* pMaterialName, KeyValues* pVMTKeyValues);
void Init(IMaterial* pMaterial);
void Init(CMaterialReference& ref);
void Init(const char* pMaterialName, const char* pTextureGroupName, KeyValues* pVMTKeyValues);
void Shutdown();
bool IsValid() { return m_pMaterial != 0; }
operator IMaterial* () { return m_pMaterial; }
operator IMaterial* () const { return m_pMaterial; }
operator IMaterial const* () const { return m_pMaterial; }
IMaterial* operator->() { return m_pMaterial; }
private:
IMaterial* m_pMaterial;
};
class CTextureReference
{
public:
CTextureReference();
CTextureReference(const CTextureReference& ref);
~CTextureReference();
void Init(char const* pTexture, const char* pTextureGroupName, bool bComplain = true);
void InitProceduralTexture(const char* pTextureName, const char* pTextureGroupName, int w, int h, ImageFormat fmt, int nFlags);
void InitRenderTarget(int w, int h, RenderTargetSizeMode_t sizeMode, ImageFormat fmt, MaterialRenderTargetDepth_t depth, bool bHDR, char* pStrOptionalName = NULL);
#if defined( _X360 )
void InitRenderTargetTexture(int width, int height, RenderTargetSizeMode_t sizeMode, ImageFormat fmt, MaterialRenderTargetDepth_t depth, bool bHDR, char* pStrOptionalName = NULL);
void InitRenderTargetSurface(int width, int height, ImageFormat fmt, bool bSameAsTexture);
#endif
void Init(ITexture* pTexture);
void Shutdown(bool bDeleteIfUnReferenced = false);
bool IsValid() { return m_pTexture != 0; }
operator ITexture* () { return m_pTexture; }
operator ITexture const* () const { return m_pTexture; }
ITexture* operator->() { return m_pTexture; }
void operator=(CTextureReference& ref);
private:
ITexture* m_pTexture;
};
#endif

262
SpyCustom/Menu.h Normal file
View File

@ -0,0 +1,262 @@
#ifndef MENU_H
#define MENU_H
#ifdef _WIN32
#pragma once
#endif
#include "Panel.h"
#include "Label.h"
#include "utllinkedlist.h"
#include "utlvector.h"
namespace vgui
{
class MenuItem;
class ScrollBar;
class MenuSeparator;
class Menu : public Panel
{
DECLARE_CLASS_SIMPLE(Menu, Panel);
friend class MenuItem;
public:
enum MenuDirection_e
{
LEFT,
RIGHT,
UP,
DOWN,
CURSOR,
ALIGN_WITH_PARENT,
};
Menu(Panel* parent, const char* panelName);
~Menu();
static void PlaceContextMenu(Panel* parent, Menu* menu);
static void OnInternalMousePressed(Panel* other, MouseCode code);
virtual void PositionRelativeToPanel(Panel* reference, MenuDirection_e direction, int nAdditionalYOffset = 0, bool showMenu = false);
virtual int AddMenuItem(const char* itemName, const char* itemText, const char* command, Panel* target, const KeyValues* userData = NULL);
virtual int AddMenuItem(const char* itemName, const wchar_t* wszItemText, const char* command, Panel* target, const KeyValues* userData = NULL);
virtual int AddMenuItem(const char* itemName, const char* itemText, KeyValues* message, Panel* target, const KeyValues* userData = NULL);
virtual int AddMenuItem(const char* itemName, const wchar_t* wszItemText, KeyValues* message, Panel* target, const KeyValues* userData = NULL);
virtual int AddMenuItem(const char* itemText, const char* command, Panel* target, const KeyValues* userData = NULL);
virtual int AddMenuItem(const char* itemText, KeyValues* message, Panel* target, const KeyValues* userData = NULL);
virtual int AddMenuItem(const char* itemText, Panel* target, const KeyValues* userData = NULL);
virtual int AddCheckableMenuItem(const char* itemName, const char* itemText, const char* command, Panel* target, const KeyValues* userData = NULL);
virtual int AddCheckableMenuItem(const char* itemName, const wchar_t* wszItemText, const char* command, Panel* target, const KeyValues* userData = NULL);
virtual int AddCheckableMenuItem(const char* itemName, const char* itemText, KeyValues* message, Panel* target, const KeyValues* userData = NULL);
virtual int AddCheckableMenuItem(const char* itemName, const wchar_t* wszItemText, KeyValues* message, Panel* target, const KeyValues* userData = NULL);
virtual int AddCheckableMenuItem(const char* itemText, const char* command, Panel* target, const KeyValues* userData = NULL);
virtual int AddCheckableMenuItem(const char* itemText, KeyValues* message, Panel* target, const KeyValues* userData = NULL);
virtual int AddCheckableMenuItem(const char* itemText, Panel* target, const KeyValues* userData = NULL);
virtual int AddCascadingMenuItem(const char* itemName, const char* itemText, const char* command, Panel* target, Menu* cascadeMenu, const KeyValues* userData = NULL);
virtual int AddCascadingMenuItem(const char* itemName, const wchar_t* wszItemText, const char* command, Panel* target, Menu* cascadeMenu, const KeyValues* userData = NULL);
virtual int AddCascadingMenuItem(const char* itemName, const char* itemText, KeyValues* message, Panel* target, Menu* cascadeMenu, const KeyValues* userData = NULL);
virtual int AddCascadingMenuItem(const char* itemName, const wchar_t* wszItemText, KeyValues* message, Panel* target, Menu* cascadeMenu, const KeyValues* userData = NULL);
virtual int AddCascadingMenuItem(const char* itemText, const char* command, Panel* target, Menu* cascadeMenu, const KeyValues* userData = NULL);
virtual int AddCascadingMenuItem(const char* itemText, KeyValues* message, Panel* target, Menu* cascadeMenu, const KeyValues* userData = NULL);
virtual int AddCascadingMenuItem(const char* itemText, Panel* target, Menu* cascadeMenu, const KeyValues* userData = NULL);
virtual int AddMenuItem(MenuItem* panel);
virtual void AddSeparator();
virtual void AddSeparatorAfterItem(int itemID);
virtual void UpdateMenuItem(int itemID, const char* itemText, KeyValues* message, const KeyValues* userData = NULL);
virtual void UpdateMenuItem(int itemID, const wchar_t* wszItemText, KeyValues* message, const KeyValues* userData = NULL);
virtual void MoveMenuItem(int itemID, int moveBeforeThisItemID);
virtual bool IsValidMenuID(int itemID);
virtual int GetInvalidMenuID();
KeyValues* GetItemUserData(int itemID);
void GetItemText(int itemID, wchar_t* text, int bufLenInBytes);
void GetItemText(int itemID, char* text, int bufLenInBytes);
virtual void SetItemEnabled(const char* itemName, bool state);
virtual void SetItemEnabled(int itemID, bool state);
virtual void SetItemVisible(const char* itemName, bool visible);
virtual void SetItemVisible(int itemID, bool visible);
void DeleteItem(int itemID);
void DeleteAllItems();
virtual void SetFixedWidth(int width);
void SetContentAlignment(Label::Alignment alignment);
virtual void SetMenuItemHeight(int itemHeight);
virtual int GetMenuItemHeight() const;
virtual void SetNumberOfVisibleItems(int numItems);
void EnableUseMenuManager(bool bUseMenuManager);
virtual void PerformLayout(void);
virtual void SetBorder(class IBorder* border);
virtual void ApplySchemeSettings(IScheme* pScheme);
enum MenuTypeAheadMode
{
COMPAT_MODE = 0,
HOT_KEY_MODE,
TYPE_AHEAD_MODE,
};
virtual void SetTypeAheadMode(MenuTypeAheadMode mode);
virtual int GetTypeAheadMode();
virtual void OnKeyTyped(wchar_t unichar);
virtual void OnKeyCodeTyped(KeyCode code);
virtual void SetVisible(bool state);
virtual void ActivateItem(int itemID);
virtual void SilentActivateItem(int itemID);
virtual void ActivateItemByRow(int row);
virtual int GetActiveItem();
virtual int GetItemCount();
virtual int GetMenuID(int index);
int GetCurrentlyVisibleItemsCount();
MenuItem* GetMenuItem(int itemID);
void CloseOtherMenus(MenuItem* item);
virtual void OnKillFocus();
int GetMenuMode();
enum MenuMode
{
MOUSE = 0,
KEYBOARD,
};
void SetCurrentlyHighlightedItem(int itemID);
int GetCurrentlyHighlightedItem();
void ClearCurrentlyHighlightedItem();
void SetMenuItemChecked(int itemID, bool state);
bool IsChecked(int index);
void SetMinimumWidth(int width);
int GetMinimumWidth();
virtual void SetFgColor(Color newColor);
virtual void SetBgColor(Color newColor);
virtual void SetFont(HFont font);
void SetCurrentKeyBinding(int itemID, char const* hotkey);
void ForceCalculateWidth();
void SetUseFallbackFont(bool bState, HFont hFallback);
protected:
int AddMenuItemCharCommand(MenuItem* item, const char* command, Panel* target, const KeyValues* userData);
int AddMenuItemKeyValuesCommand(MenuItem* item, KeyValues* message, Panel* target, const KeyValues* userData);
virtual void OnCommand(const char* command);
MESSAGE_FUNC_PTR(OnMenuItemSelected, "MenuItemSelected", panel);
virtual void AddScrollBar();
virtual void RemoveScrollBar();
MESSAGE_FUNC(OnSliderMoved, "ScrollBarSliderMoved");
virtual void Paint();
virtual void LayoutMenuBorder();
virtual void MakeItemsVisibleInScrollRange(int maxVisibleItems, int nNumPixelsAvailable);
virtual void OnMouseWheeled(int delta);
virtual void OnHotKey(wchar_t unichar);
virtual void OnTypeAhead(wchar_t unichar);
int CountVisibleItems();
void ComputeWorkspaceSize(int& workWide, int& workTall);
int ComputeFullMenuHeightWithInsets();
void CalculateWidth();
void LayoutScrollBar();
void PositionCascadingMenu();
void SizeMenuItems();
void OnCursorMoved(int x, int y);
void OnKeyCodePressed(KeyCode code);
void OnMenuClose();
MESSAGE_FUNC(OnKeyModeSet, "KeyModeSet");
void SetCurrentlySelectedItem(MenuItem* item);
void SetCurrentlySelectedItem(int itemID);
MESSAGE_FUNC_INT(OnCursorEnteredMenuItem, "CursorEnteredMenuItem", VPanel);
MESSAGE_FUNC_INT(OnCursorExitedMenuItem, "CursorExitedMenuItem", VPanel);
void MoveAlongMenuItemList(int direction, int loopCount);
enum
{
DEFAULT_MENU_ITEM_HEIGHT = 22,
MENU_UP = -1,
MENU_DOWN = 1
};
#ifdef DBGFLAG_VALIDATE
virtual void Validate(CValidator& validator, char* pchName);
#endif
private:
MenuItem* GetParentMenuItem();
int m_iMenuItemHeight;
int m_iFixedWidth;
int m_iMinimumWidth;
int m_iNumVisibleLines;
ScrollBar* m_pScroller;
CUtlLinkedList<MenuItem*, int> m_MenuItems;
CUtlVector<int> m_VisibleSortedItems;
CUtlVector<int> m_SortedItems;
CUtlVector<int> m_Separators;
CUtlVector<MenuSeparator*> m_SeparatorPanels;
bool _sizedForScrollBar : 1;
bool m_bUseFallbackFont : 1;
bool _recalculateWidth : 1;
bool m_bUseMenuManager : 1;
int _menuWide;
int m_iCurrentlySelectedItemID;
int m_iInputMode;
int m_iCheckImageWidth;
int m_iProportionalScrollBarSize;
Label::Alignment m_Alignment;
Color _borderDark;
int m_iActivatedItem;
HFont m_hItemFont;
HFont m_hFallbackItemFont;
#define TYPEAHEAD_BUFSIZE 256
MenuTypeAheadMode m_eTypeAheadMode;
wchar_t m_szTypeAheadBuf[TYPEAHEAD_BUFSIZE];
int m_iNumTypeAheadChars;
double m_fLastTypeAheadTime;
};
}
#endif

1949
SpyCustom/Menu.hpp Normal file

File diff suppressed because it is too large Load Diff

107
SpyCustom/MenuItem.h Normal file
View File

@ -0,0 +1,107 @@
#ifndef MENUITEM_H
#define MENUITEM_H
#ifdef _WIN32
#pragma once
#endif
#include "VGUI.h"
#include "Button.h"
#include "Menu.h"
namespace vgui
{
class IBorder;
class TextImage;
class Menu;
class Image;
class MenuItem : public Button
{
DECLARE_CLASS_SIMPLE(MenuItem, Button);
public:
MenuItem(Menu* parent, const char* panelName, const char* text, Menu* cascadeMenu = NULL, bool checkable = false);
MenuItem(Menu* parent, const char* panelName, const wchar_t* wszText, Menu* cascadeMenu = NULL, bool checkable = false);
~MenuItem();
virtual void Paint();
virtual void FireActionSignal();
virtual bool CanBeDefaultButton(void);
void OnCursorEntered();
void OnCursorExited();
void CloseCascadeMenu();
MESSAGE_FUNC(OnKillFocus, "MenuClose");
bool HasMenu();
void SetTextImageSize(int wide, int tall);
void GetTextImageSize(int& wide, int& tall);
void GetArrowImageSize(int& wide, int& tall);
void GetCheckImageSize(int& wide, int& tall);
Menu* GetMenu();
virtual void PerformLayout();
void OnCursorMoved(int x, int y);
MESSAGE_FUNC(ArmItem, "ArmItem");
MESSAGE_FUNC(DisarmItem, "DisarmItem");
bool IsItemArmed();
void OpenCascadeMenu();
bool IsCheckable();
bool IsChecked();
void SetChecked(bool state);
KeyValues* GetUserData();
void SetUserData(const KeyValues* kv);
int GetActiveItem() { if (m_pCascadeMenu) { return m_pCascadeMenu->GetActiveItem(); } else { return 0; } }
Menu* GetParentMenu();
void SetCurrentKeyBinding(char const* keyName);
virtual void GetContentSize(int& cw, int& ch);
protected:
void OnKeyCodeReleased(KeyCode code);
void OnMenuClose();
MESSAGE_FUNC(OnKeyModeSet, "KeyModeSet");
virtual void Init(void);
virtual void ApplySchemeSettings(IScheme* pScheme);
virtual IBorder* GetBorder(bool depressed, bool armed, bool selected, bool keyfocus);
private:
enum { CHECK_INSET = 6 };
Menu* m_pCascadeMenu;
bool m_bCheckable;
bool m_bChecked;
TextImage* m_pCascadeArrow;
Image* m_pCheck;
TextImage* m_pBlankCheck;
TextImage* m_pCurrentKeyBinding;
KeyValues* m_pUserData;
};
}
#endif

327
SpyCustom/MessageMap.h Normal file
View File

@ -0,0 +1,327 @@
#ifndef MESSAGEMAP_H
#define MESSAGEMAP_H
#ifdef _WIN32
#pragma once
#endif
#include "dmxelement.h"
#pragma pointers_to_members( full_generality, virtual_inheritance )
namespace vgui
{
#ifndef ARRAYSIZE
#define ARRAYSIZE(p) (sizeof(p)/sizeof(p[0]))
#endif
enum DataType_t
{
DATATYPE_VOID,
DATATYPE_CONSTCHARPTR,
DATATYPE_INT,
DATATYPE_FLOAT,
DATATYPE_PTR,
DATATYPE_BOOL,
DATATYPE_KEYVALUES,
DATATYPE_CONSTWCHARPTR,
DATATYPE_UINT64,
DATATYPE_HANDLE,
};
class Panel;
typedef uintp VPANEL;
typedef void (Panel::* MessageFunc_t)(void);
#pragma warning(disable:4121)
struct MessageMapItem_t
{
const char* name;
ALIGN16 MessageFunc_t func;
int numParams;
DataType_t firstParamType;
const char* firstParamName;
DataType_t secondParamType;
const char* secondParamName;
int nameSymbol;
int firstParamSymbol;
int secondParamSymbol;
};
#define DECLARE_PANELMESSAGEMAP( className ) \
static void AddToMap( char const *scriptname, vgui::MessageFunc_t function, int paramCount, int p1type, const char *p1name, int p2type, const char *p2name ) \
{ \
vgui::PanelMessageMap *map = vgui::FindOrAddPanelMessageMap( GetPanelClassName() ); \
\
vgui::MessageMapItem_t entry; \
entry.name = scriptname; \
entry.func = function; \
entry.numParams = paramCount; \
entry.firstParamType = (vgui::DataType_t)p1type; \
entry.firstParamName = p1name; \
entry.secondParamType = (vgui::DataType_t)p2type; \
entry.secondParamName = p2name; \
entry.nameSymbol = 0; \
entry.firstParamSymbol = 0; \
entry.secondParamSymbol = 0; \
\
map->entries.AddToTail( entry ); \
} \
\
static void ChainToMap( void ) \
{ \
static bool chained = false; \
if ( chained ) \
return; \
chained = true; \
vgui::PanelMessageMap *map = vgui::FindOrAddPanelMessageMap( GetPanelClassName() ); \
map->pfnClassName = &GetPanelClassName; \
if ( map && GetPanelBaseClassName() && GetPanelBaseClassName()[0] ) \
{ \
map->baseMap = vgui::FindOrAddPanelMessageMap( GetPanelBaseClassName() ); \
} \
} \
\
class className##_RegisterMap; \
friend class className##_RegisterMap; \
class className##_RegisterMap \
{ \
public: \
className##_RegisterMap() \
{ \
className::ChainToMap(); \
} \
}; \
className##_RegisterMap m_RegisterClass; \
\
virtual vgui::PanelMessageMap *GetMessageMap() \
{ \
static vgui::PanelMessageMap *s_pMap = vgui::FindOrAddPanelMessageMap( GetPanelClassName() ); \
return s_pMap; \
}
#define VGUI_USEKEYBINDINGMAPS 1
#if defined( VGUI_USEKEYBINDINGMAPS )
#define DECLARE_CLASS_SIMPLE( className, baseClassName ) \
typedef baseClassName BaseClass; \
typedef className ThisClass; \
public: \
DECLARE_PANELMESSAGEMAP( className ); \
DECLARE_PANELANIMATION( className ); \
DECLARE_KEYBINDINGMAP( className ); \
static char const *GetPanelClassName() { return #className; } \
static char const *GetPanelBaseClassName() { return #baseClassName; }
#define DECLARE_CLASS_SIMPLE_NOBASE( className ) \
typedef className ThisClass; \
public: \
DECLARE_PANELMESSAGEMAP( className ); \
DECLARE_PANELANIMATION( className ); \
DECLARE_KEYBINDINGMAP( className ); \
static char const *GetPanelClassName() { return #className; } \
static char const *GetPanelBaseClassName() { return NULL; }
#else
#define DECLARE_CLASS_SIMPLE( className, baseClassName ) \
typedef baseClassName BaseClass; \
typedef className ThisClass; \
public: \
DECLARE_PANELMESSAGEMAP( className ); \
DECLARE_PANELANIMATION( className ); \
static char const *GetPanelClassName() { return #className; } \
static char const *GetPanelBaseClassName() { return #baseClassName; }
#define DECLARE_CLASS_SIMPLE_NOBASE( className ) \
typedef className ThisClass; \
public: \
DECLARE_PANELMESSAGEMAP( className ); \
DECLARE_PANELANIMATION( className ); \
static char const *GetPanelClassName() { return #className; } \
static char const *GetPanelBaseClassName() { return NULL; }
#endif
#define _MessageFuncCommon( name, scriptname, paramCount, p1type, p1name, p2type, p2name ) \
class PanelMessageFunc_##name; \
friend class PanelMessageFunc_##name; \
class PanelMessageFunc_##name \
{ \
public: \
static void InitVar() \
{ \
static bool bAdded = false; \
if ( !bAdded ) \
{ \
bAdded = true; \
AddToMap( scriptname, (vgui::MessageFunc_t)&ThisClass::name, paramCount, p1type, p1name, p2type, p2name ); \
} \
} \
PanelMessageFunc_##name() \
{ \
PanelMessageFunc_##name::InitVar(); \
} \
}; \
PanelMessageFunc_##name m_##name##_register; \
#define MESSAGE_FUNC( name, scriptname ) _MessageFuncCommon( name, scriptname, 0, 0, 0, 0, 0 ); virtual void name( void )
#define MESSAGE_FUNC_INT( name, scriptname, p1 ) _MessageFuncCommon( name, scriptname, 1, vgui::DATATYPE_INT, #p1, 0, 0 ); virtual void name( int p1 )
#define MESSAGE_FUNC_UINT64( name, scriptname, p1 ) _MessageFuncCommon( name, scriptname, 1, vgui::DATATYPE_UINT64, #p1, 0, 0 ); virtual void name( uint64 p1 )
#define MESSAGE_FUNC_PTR( name, scriptname, p1 ) _MessageFuncCommon( name, scriptname, 1, vgui::DATATYPE_PTR, #p1, 0, 0 ); virtual void name( vgui::Panel *p1 )
#define MESSAGE_FUNC_HANDLE( name, scriptname, p1 ) _MessageFuncCommon( name, scriptname, 1, vgui::DATATYPE_HANDLE, #p1, 0, 0 ); virtual void name( vgui::VPANEL p1 )
#define MESSAGE_FUNC_FLOAT( name, scriptname, p1 ) _MessageFuncCommon( name, scriptname, 1, vgui::DATATYPE_FLOAT, #p1, 0, 0 ); virtual void name( float p1 )
#define MESSAGE_FUNC_CHARPTR( name, scriptname, p1 ) _MessageFuncCommon( name, scriptname, 1, vgui::DATATYPE_CONSTCHARPTR, #p1, 0, 0 ); virtual void name( const char *p1 )
#define MESSAGE_FUNC_WCHARPTR( name, scriptname, p1 ) _MessageFuncCommon( name, scriptname, 1, vgui::DATATYPE_CONSTWCHARPTR, #p1, 0, 0 ); virtual void name( const wchar_t *p1 )
#define MESSAGE_FUNC_INT_INT( name, scriptname, p1, p2 ) _MessageFuncCommon( name, scriptname, 2, vgui::DATATYPE_INT, #p1, vgui::DATATYPE_INT, #p2 ); virtual void name( int p1, int p2 )
#define MESSAGE_FUNC_PTR_INT( name, scriptname, p1, p2 ) _MessageFuncCommon( name, scriptname, 2, vgui::DATATYPE_PTR, #p1, vgui::DATATYPE_INT, #p2 ); virtual void name( vgui::Panel *p1, int p2 )
#define MESSAGE_FUNC_HANDLE_INT( name, scriptname, p1, p2 ) _MessageFuncCommon( name, scriptname, 2, vgui::DATATYPE_HANDLE, #p1, vgui::DATATYPE_INT, #p2 ); virtual void name( vgui::VPANEL p1, int p2 )
#define MESSAGE_FUNC_ENUM_ENUM( name, scriptname, t1, p1, t2, p2 ) _MessageFuncCommon( name, scriptname, 2, vgui::DATATYPE_PTR, #p1, vgui::DATATYPE_PTR, #p2 ); virtual void name( t1 p1, t2 p2 )
#define MESSAGE_FUNC_INT_CHARPTR( name, scriptname, p1, p2 ) _MessageFuncCommon( name, scriptname, 2, vgui::DATATYPE_INT, #p1, vgui::DATATYPE_CONSTCHARPTR, #p2 ); virtual void name( int p1, const char *p2 )
#define MESSAGE_FUNC_PTR_CHARPTR( name, scriptname, p1, p2 ) _MessageFuncCommon( name, scriptname, 2, vgui::DATATYPE_PTR, #p1, vgui::DATATYPE_CONSTCHARPTR, #p2 ); virtual void name( vgui::Panel *p1, const char *p2 )
#define MESSAGE_FUNC_HANDLE_CHARPTR( name, scriptname, p1, p2 ) _MessageFuncCommon( name, scriptname, 2, vgui::DATATYPE_HANDLE, #p1, vgui::DATATYPE_CONSTCHARPTR, #p2 ); virtual void name( vgui::VPANEL p1, const char *p2 )
#define MESSAGE_FUNC_PTR_WCHARPTR( name, scriptname, p1, p2 ) _MessageFuncCommon( name, scriptname, 2, vgui::DATATYPE_PTR, #p1, vgui::DATATYPE_CONSTWCHARPTR, #p2 ); virtual void name( vgui::Panel *p1, const wchar_t *p2 )
#define MESSAGE_FUNC_HANDLE_WCHARPTR( name, scriptname, p1, p2 ) _MessageFuncCommon( name, scriptname, 2, vgui::DATATYPE_HANDLE, #p1, vgui::DATATYPE_CONSTWCHARPTR, #p2 ); virtual void name( vgui::VPANEL p1, const wchar_t *p2 )
#define MESSAGE_FUNC_CHARPTR_CHARPTR( name, scriptname, p1, p2 ) _MessageFuncCommon( name, scriptname, 2, vgui::DATATYPE_CONSTCHARPTR, #p1, vgui::DATATYPE_CONSTCHARPTR, #p2 ); virtual void name( const char *p1, const char *p2 )
#define MESSAGE_FUNC_PARAMS( name, scriptname, p1 ) _MessageFuncCommon( name, scriptname, 1, vgui::DATATYPE_KEYVALUES, NULL, 0, 0 ); virtual void name( KeyValues *p1 )
#define MESSAGE_FUNC_NV( name, scriptname ) _MessageFuncCommon( name, scriptname, 0, 0, 0, 0, 0 ); void name( void )
#define MESSAGE_FUNC_NV_INT( name, scriptname, p1 ) _MessageFuncCommon( name, scriptname, 1, vgui::DATATYPE_INT, #p1, 0, 0 ); void name( int p1 )
#define MESSAGE_FUNC_NV_INT_INT( name, scriptname, p1, p2 ) _MessageFuncCommon( name, scriptname, 2, vgui::DATATYPE_INT, #p1, vgui::DATATYPE_INT, #p2 ); void name( int p1, int p2 )
struct PanelMessageMap
{
PanelMessageMap()
{
baseMap = NULL;
pfnClassName = NULL;
processed = false;
}
CUtlVector< MessageMapItem_t > entries;
bool processed;
PanelMessageMap* baseMap;
char const* (*pfnClassName)(void);
};
PanelMessageMap* FindPanelMessageMap(char const* className);
PanelMessageMap* FindOrAddPanelMessageMap(char const* className);
#define MAP_MESSAGE( type, name, func ) { name, (vgui::MessageFunc_t)(&type::func), 0 }
#define MAP_MESSAGE_PARAMS( type, name, func ) { name, (vgui::MessageFunc_t)(&type::func), 1, vgui::DATATYPE_KEYVALUES, NULL }
#define MAP_MESSAGE_PTR( type, name, func, param1 ) { name, (vgui::MessageFunc_t)(&type::func), 1, vgui::DATATYPE_PTR, param1 }
#define MAP_MESSAGE_INT( type, name, func, param1 ) { name, (vgui::MessageFunc_t)(&type::func), 1, vgui::DATATYPE_INT, param1 }
#define MAP_MESSAGE_BOOL( type, name, func, param1 ) { name, (vgui::MessageFunc_t)(&type::func), 1, vgui::DATATYPE_BOOL, param1 }
#define MAP_MESSAGE_FLOAT( type, name, func, param1 ) { name, (vgui::MessageFunc_t)(&type::func), 1, vgui::DATATYPE_FLOAT, param1 }
#define MAP_MESSAGE_PTR( type, name, func, param1 ) { name, (vgui::MessageFunc_t)(&type::func), 1, vgui::DATATYPE_PTR, param1 }
#define MAP_MESSAGE_CONSTCHARPTR( type, name, func, param1) { name, (vgui::MessageFunc_t)(&type::func), 1, vgui::DATATYPE_CONSTCHARPTR, param1 }
#define MAP_MESSAGE_CONSTWCHARPTR( type, name, func, param1) { name, (vgui::MessageFunc_t)(&type::func), 1, vgui::DATATYPE_CONSTWCHARPTR, param1 }
#define MAP_MESSAGE_INT_INT( type, name, func, param1, param2 ) { name, (vgui::MessageFunc_t)&type::func, 2, vgui::DATATYPE_INT, param1, vgui::DATATYPE_INT, param2 }
#define MAP_MESSAGE_PTR_INT( type, name, func, param1, param2 ) { name, (vgui::MessageFunc_t)&type::func, 2, vgui::DATATYPE_PTR, param1, vgui::DATATYPE_INT, param2 }
#define MAP_MESSAGE_INT_CONSTCHARPTR( type, name, func, param1, param2 ) { name, (vgui::MessageFunc_t)&type::func, 2, vgui::DATATYPE_INT, param1, vgui::DATATYPE_CONSTCHARPTR, param2 }
#define MAP_MESSAGE_PTR_CONSTCHARPTR( type, name, func, param1, param2 ) { name, (vgui::MessageFunc_t)&type::func, 2, vgui::DATATYPE_PTR, param1, vgui::DATATYPE_CONSTCHARPTR, param2 }
#define MAP_MESSAGE_PTR_CONSTWCHARPTR( type, name, func, param1, param2 ) { name, (vgui::MessageFunc_t)&type::func, 2, vgui::DATATYPE_PTR, param1, vgui::DATATYPE_CONSTWCHARPTR, param2 }
#define MAP_MESSAGE_CONSTCHARPTR_CONSTCHARPTR( type, name, func, param1, param2 ) { name, (vgui::MessageFunc_t)&type::func, 2, vgui::DATATYPE_CONSTCHARPTR, param1, vgui::DATATYPE_CONSTCHARPTR, param2 }
struct PanelMap_t
{
MessageMapItem_t* dataDesc;
int dataNumFields;
const char* dataClassName;
PanelMap_t* baseMap;
int processed;
};
#define DECLARE_PANELMAP() \
static vgui::PanelMap_t m_PanelMap; \
static vgui::MessageMapItem_t m_MessageMap[]; \
virtual vgui::PanelMap_t *GetPanelMap( void );
#define IMPLEMENT_PANELMAP( derivedClass, baseClass ) \
vgui::PanelMap_t derivedClass::m_PanelMap = { derivedClass::m_MessageMap, ARRAYSIZE(derivedClass::m_MessageMap), #derivedClass, &baseClass::m_PanelMap }; \
vgui::PanelMap_t *derivedClass::GetPanelMap( void ) { return &m_PanelMap; }
typedef vgui::Panel* (*PANELCREATEFUNC)(void);
class CBuildFactoryHelper
{
public:
static CBuildFactoryHelper* m_sHelpers;
public:
CBuildFactoryHelper(char const* className, PANELCREATEFUNC func);
CBuildFactoryHelper* GetNext(void);
char const* GetClassName() const;
vgui::Panel* CreatePanel();
static vgui::Panel* InstancePanel(char const* className);
static void GetFactoryNames(CUtlVector< char const* >& list);
static CDmxElement* CreatePanelDmxElement(vgui::Panel* pPanel);
static Panel* UnserializeDmxElementPanel(CDmxElement* pElement);
static bool Serialize(CUtlBuffer& buf, vgui::Panel* pPanel);
static bool Unserialize(Panel** ppPanel, CUtlBuffer& buf, const char* pFileName = NULL);
private:
static bool HasFactory(char const* className);
CBuildFactoryHelper* m_pNext;
int m_Type;
PANELCREATEFUNC m_CreateFunc;
char const* m_pClassName;
};
#define DECLARE_BUILD_FACTORY( className ) \
static vgui::Panel *Create_##className( void ) \
{ \
return new className( NULL, NULL ); \
}; \
static vgui::CBuildFactoryHelper g_##className##_Helper( #className, Create_##className );\
className *g_##className##LinkerHack = NULL;
#define DECLARE_BUILD_FACTORY_DEFAULT_TEXT( className, defaultText ) \
static vgui::Panel *Create_##className( void ) \
{ \
return new className( NULL, NULL, #defaultText ); \
}; \
static vgui::CBuildFactoryHelper g_##className##_Helper( #className, Create_##className );\
className *g_##className##LinkerHack = NULL;
#define DECLARE_BUILD_FACTORY_CUSTOM( className, createFunc ) \
static vgui::CBuildFactoryHelper g_##className##_Helper( #className, createFunc );\
className *g_##className##LinkerHack = NULL;
#define DECLARE_BUILD_FACTORY_CUSTOM_ALIAS( className, factoryName, createFunc ) \
static vgui::CBuildFactoryHelper g_##factoryName##_Helper( #factoryName, createFunc );\
className *g_##factoryName##LinkerHack = NULL;
}
#endif

15
SpyCustom/MouseCode.h Normal file
View File

@ -0,0 +1,15 @@
#ifndef MOUSECODE_H
#define MOUSECODE_H
#ifdef _WIN32
#pragma once
#endif
#include "ButtonCode.h"
namespace vgui
{
typedef ButtonCode_t MouseCode;
}
#endif

View File

@ -0,0 +1,57 @@
#include "NetVarManager.hpp"
#include <cctype>
#ifdef DUMP_NETVARS
#define IF_DUMPING(...) __VA_ARGS__
#else
#define IF_DUMPING(...)
#endif
IF_DUMPING(static FILE* s_fp;)
netvar_manager::netvar_manager()
{
IF_DUMPING(fopen_s(&s_fp, "netvar_dump.txt", "w");)
for (auto clazz = iff.g_pClient->GetAllClasses(); clazz; clazz = clazz->m_pNext)
if (clazz->m_pRecvTable)
dump_recursive(clazz->m_pNetworkName, clazz->m_pRecvTable, 0);
IF_DUMPING(fclose(s_fp);)
}
auto netvar_manager::dump_recursive(const char* base_class, RecvTable* table, const std::uint16_t offset) -> void
{
for (auto i = 0; i < table->m_nProps; ++i)
{
const auto prop_ptr = &table->m_pProps[i];
if (!prop_ptr || isdigit(prop_ptr->m_pVarName[0]))
continue;
if (fnv::hash_runtime(prop_ptr->m_pVarName) == FNV("baseclass"))
continue;
if (prop_ptr->m_RecvType == DPT_DataTable &&
prop_ptr->m_pDataTable != nullptr &&
prop_ptr->m_pDataTable->m_pNetTableName[0] == 'D')
{
dump_recursive(base_class, prop_ptr->m_pDataTable, std::uint16_t(offset + prop_ptr->m_Offset));
}
char hash_name[256];
strcpy_s(hash_name, base_class);
strcat_s(hash_name, "->");
strcat_s(hash_name, prop_ptr->m_pVarName);
const auto hash = fnv::hash_runtime(hash_name);
const auto total_offset = std::uint16_t(offset + prop_ptr->m_Offset);
IF_DUMPING(fprintf(s_fp, "%s\t0x%04X\t%s\n", base_class, total_offset, prop_ptr->m_pVarName);)
m_props[hash] =
{
prop_ptr,
total_offset
};
}
}

217
SpyCustom/NetVarManager.hpp Normal file
View File

@ -0,0 +1,217 @@
#ifndef NETVARMGR
#define NETVARMGR
#pragma once
#include "cdll_int.h"
#include "dt_recv.h"
#include "client_class.h"
#include <vector>
#include "Interfaces.hpp"
#include <cstdlib>
namespace detail
{
template <typename Type, Type OffsetBasis, Type Prime>
struct size_dependant_data
{
using type = Type;
constexpr static auto k_offset_basis = OffsetBasis;
constexpr static auto k_prime = Prime;
};
template <size_t Bits>
struct size_selector;
template <>
struct size_selector<32>
{
using type = size_dependant_data<std::uint32_t, 0x811c9dc5ul, 16777619ul>;
};
template <>
struct size_selector<64>
{
using type = size_dependant_data<std::uint64_t, 0xcbf29ce484222325ull, 1099511628211ull>;
};
template <std::size_t Size>
class fnv_hash
{
private:
using data_t = typename size_selector<Size>::type;
public:
using hash = typename data_t::type;
private:
constexpr static auto k_offset_basis = data_t::k_offset_basis;
constexpr static auto k_prime = data_t::k_prime;
public:
template <std::size_t N>
static __forceinline constexpr auto hash_constexpr(const char(&str)[N], const std::size_t size = N) -> hash
{
return static_cast<hash>(1ull * (size == 1
? (k_offset_basis ^ str[0])
: (hash_constexpr(str, size - 1) ^ str[size - 1])) * k_prime);
}
static auto __forceinline hash_runtime(const char* str) -> hash
{
auto result = k_offset_basis;
do
{
result ^= *str++;
result *= k_prime;
} while (*(str - 1) != '\0');
return result;
}
};
}
namespace fnv2 {
constexpr uint32_t offsetBasis = 0x811c9dc5;
constexpr uint32_t prime = 0x1000193;
constexpr uint32_t hash(const char* str, const uint32_t value = offsetBasis) noexcept
{
return *str ? hash(str + 1, (value ^ *str) * static_cast<unsigned long long>(prime)) : value;
}
constexpr uint32_t hashRuntime(const char* str) noexcept
{
auto value = offsetBasis;
while (*str) {
value ^= *str++;
value *= prime;
}
return value;
}
}
using fnv = ::detail::fnv_hash<sizeof(void*) * 8>;
#define FNV(str) (std::integral_constant<fnv::hash, fnv::hash_constexpr(str)>::value)
#include <map>
#include <type_traits>
class netvar_manager
{
private:
struct stored_data
{
RecvProp* prop_ptr;
std::uint16_t class_relative_offset;
};
public:
static auto get() -> const netvar_manager&
{
static netvar_manager instance;
return instance;
}
auto get_offset(const fnv::hash hash) const -> std::uint16_t
{
return m_props.at(hash).class_relative_offset;
}
auto get_prop(const fnv::hash hash) const -> RecvProp*
{
return m_props.at(hash).prop_ptr;
}
__declspec(noinline) static auto get_offset_by_hash(const fnv::hash hash) -> std::uint16_t
{
return get().get_offset(hash);
}
template<fnv::hash Hash>
static auto get_offset_by_hash_cached() -> std::uint16_t
{
static auto offset = std::uint16_t(0);
if (!offset)
offset = get_offset_by_hash(Hash);
return offset;
}
private:
netvar_manager();
auto dump_recursive(const char* base_class, RecvTable* table, std::uint16_t offset) -> void;
private:
std::map<fnv::hash, stored_data> m_props;
};
#define PNETVAR_OFFSET(funcname, class_name, var_name, offset, ...) \
auto funcname() -> std::add_pointer_t<__VA_ARGS__> \
{ \
constexpr auto hash = fnv::hash_constexpr(class_name "->" var_name); \
const auto addr = std::uintptr_t(this) + offset + netvar_manager::get_offset_by_hash_cached<hash>(); \
return reinterpret_cast<std::add_pointer_t<__VA_ARGS__>>(addr); \
}
#define PNETVAR(funcname, class_name, var_name, ...) \
PNETVAR_OFFSET(funcname, class_name, var_name, 0, __VA_ARGS__)
#define NETVAR_OFFSET(funcname, class_name, var_name, offset, ...) \
auto funcname() -> std::add_lvalue_reference_t<__VA_ARGS__> \
{ \
constexpr auto hash = fnv::hash_constexpr(class_name "->" var_name); \
const auto addr = std::uintptr_t(this) + offset + netvar_manager::get_offset_by_hash_cached<hash>(); \
return *reinterpret_cast<std::add_pointer_t<__VA_ARGS__>>(addr); \
}
#define NETVAR(funcname, class_name, var_name, ...) \
NETVAR_OFFSET(funcname, class_name, var_name, 0, __VA_ARGS__)
#define NETPROP(funcname, class_name, var_name) \
static auto funcname() -> RecvProp* \
{ \
constexpr auto hash = fnv::hash_constexpr(class_name "->" var_name); \
static RecvProp* prop_ptr; \
if(!prop_ptr) prop_ptr = netvar_manager::get().get_prop(hash); \
return prop_ptr; \
}
class recv_prop_hook
{
public:
recv_prop_hook(RecvProp* prop, const RecvVarProxyFn proxy_fn) :
m_property(prop),
m_original_proxy_fn(prop->m_ProxyFn)
{
set_proxy_function(proxy_fn);
}
~recv_prop_hook()
{
m_property->m_ProxyFn = m_original_proxy_fn;
}
auto get_original_function() const -> RecvVarProxyFn
{
return m_original_proxy_fn;
}
auto set_proxy_function(const RecvVarProxyFn proxy_fn) const -> void
{
m_property->m_ProxyFn = proxy_fn;
}
private:
RecvProp* m_property;
RecvVarProxyFn m_original_proxy_fn;
};
#endif

1102
SpyCustom/Options.hpp Normal file

File diff suppressed because it is too large Load Diff

265
SpyCustom/Other.cpp Normal file
View File

@ -0,0 +1,265 @@
#include "Other.hpp"
#include "PatternScan.hpp"
void UpdateFlashLight(CFlashlightEffect* pFlashLight, const Vector& vecPos, const Vector& vecForward, const Vector& vecRight, const Vector& vecUp)
{
typedef void(__thiscall* UpdateLight_t)(void*, int, const Vector&, const Vector&, const Vector&, const Vector&, float, float, float, bool, const char*);
static UpdateLight_t oUpdateLight = NULL;
if (!oUpdateLight)
{
DWORD callInstruction = FindPatternV2("client.dll", "E8 ? ?? ? ? 8B 06 F3 0F 10 46");
DWORD relativeAddress = *(DWORD*)(callInstruction + 1);
DWORD nextInstruction = callInstruction + 5;
oUpdateLight = (UpdateLight_t)(nextInstruction + relativeAddress);
}
oUpdateLight(pFlashLight, pFlashLight->m_nEntIndex, vecPos, vecForward, vecRight, vecUp,
pFlashLight->m_flFov, pFlashLight->m_flFarZ, pFlashLight->m_flLinearAtten, pFlashLight->m_bCastsShadows,
pFlashLight->m_textureName);
}
CFlashlightEffect* CreateFlashLight(int nEntIndex, const char* pszTextureName, float flFov, float flFarZ, float flLinearAtten)
{
CFlashlightEffect* pFlashLight = reinterpret_cast<CFlashlightEffect*>(iff.g_pMemAlloc->Alloc(sizeof(CFlashlightEffect)));
if (!pFlashLight)
return NULL;
static DWORD oConstructor = FindPatternV2("client.dll", "55 8B EC F3 0F 10 45 ? B8");
__asm
{
movss xmm3, flFov
mov ecx, pFlashLight
push flLinearAtten
push flFarZ
push pszTextureName
push nEntIndex
call oConstructor
}
pFlashLight->m_bIsOn = true;
return pFlashLight;
}
void DestroyFlashLight(CFlashlightEffect* pFlashLight)
{
static DWORD oDestructor = FindPatternV2("client.dll", "56 8B F1 E8 ? ? ? ? 8B 4E 28");
__asm
{
mov ecx, pFlashLight
push ecx
call oDestructor
}
}
void AngleVectors(const Vector& angles, Vector* forward, Vector* right, Vector* up)
{
float sr, sp, sy, cr, cp, cy;
SinCos(DEG2RAD(angles[1]), &sy, &cy);
SinCos(DEG2RAD(angles[0]), &sp, &cp);
SinCos(DEG2RAD(angles[2]), &sr, &cr);
if (forward)
{
forward->x = cp * cy;
forward->y = cp * sy;
forward->z = -sp;
}
if (right)
{
right->x = (-1 * sr * sp * cy + -1 * cr * -sy);
right->y = (-1 * sr * sp * sy + -1 * cr * cy);
right->z = -1 * sr * cp;
}
if (up)
{
up->x = (cr * sp * cy + -sr * -sy);
up->y = (cr * sp * sy + -sr * cy);
up->z = cr * cp;
}
}
static bool ToggleButton(ButtonCode_t code)
{
static int buttonPressedTick = 0;
if (iff.g_pInputSystem->IsButtonDown(code) && (GetTickCount64() - buttonPressedTick) > 300)
{
buttonPressedTick = GetTickCount64();
return true;
}
return false;
}
void FlashlightRun(C_BasePlayer* local)
{
static CFlashlightEffect* pFlashLight = NULL;
if (opt.disconnected)
{
#ifdef DEBUG
printf("nullify pFlashlight bc disconnected\n");
#endif
pFlashLight = NULL;
opt.disconnected = 0;
}
if (ToggleButton(KEY_L))
{
if (!pFlashLight)
{
#ifdef DEBUG
printf("creating fl\n");
#endif
pFlashLight = CreateFlashLight(local->GetIndex(), g_Options.flashlightTexture.value->mystring, *g_Options.flashlightFOV, *g_Options.flashlightFarZ, *g_Options.flashlightLinearAtten);
iff.g_pEngineClient->ExecuteClientCmd("play items/flashlight1.wav");
}
else
{
#ifdef DEBUG
printf("destroying fl\n");
#endif
DestroyFlashLight(pFlashLight);
pFlashLight = NULL;
iff.g_pEngineClient->ExecuteClientCmd("play items/flashlight1.wav");
}
}
if (pFlashLight)
{
Vector f, r, u;
Vector viewAngles;
iff.g_pEngineClient->GetViewAngles(viewAngles);
AngleVectors(viewAngles, &f, &r, &u);
pFlashLight->m_bIsOn = true;
pFlashLight->m_bCastsShadows = *g_Options.flashlightShadows;
pFlashLight->m_flFov = *g_Options.flashlightFOV;
UpdateFlashLight(pFlashLight, local->GetOrigin() + local->GetViewOffset(), f, r, u);
}
}
#define DRAW_SCREEN_EFFECT(material) \
{ \
const auto drawFunction = relativeToAbsolute<uintptr_t>(FindPatternV2("client.dll", "E8 ? ? ? ? 83 C4 0C 8D 4D F8") + 1); \
int w, h; \
iff.g_pVGuiSurface->GetScreenSize(w, h); \
__asm { \
__asm push h \
__asm push w \
__asm push 0 \
__asm xor edx, edx \
__asm mov ecx, material \
__asm call drawFunction \
__asm add esp, 12 \
} \
}
void NightvisionRun(C_BasePlayer* local) {
static int m_flNightVisionAlpha = NetvarSys::Get().GetOffset("DT_CSPlayer", "m_flFlashDuration") - 0x1C;
if (ToggleButton(KEY_N) )
{
if (!local->GetNightvision())
{
local->GetNightvision() = true;
*(float*)(uintptr_t(local) + m_flNightVisionAlpha) = 1.0f;
iff.g_pEngineClient->ExecuteClientCmd("play items/nvg_on.wav");
}
else
{
local->GetNightvision() = false;
*(float*)(uintptr_t(local) + m_flNightVisionAlpha) = 0;
iff.g_pEngineClient->ExecuteClientCmd("play items/nvg_off.wav");
}
}
}
void do_precipitation() {
static void* rain_networkable = nullptr;
C_Precipitation* rain_ent = (C_Precipitation*)iff.g_pEntityList->GetClientEntity(MAX_EDICTS - 1);
static ClientClass* precipitation_client_class = nullptr;
if (!iff.g_pEngineClient->IsInGame() || !iff.g_pEngineClient->IsConnected()) {
rain_networkable = rain_ent = nullptr;
return;
}
int localplayer_index = iff.g_pEngineClient->GetLocalPlayer();
C_BasePlayer* localplayer = static_cast<C_BasePlayer*>(iff.g_pEntityList->GetClientEntity(localplayer_index));
if (!localplayer) return;
if (!(localplayer->GetLifeState() == LIFE_ALIVE && localplayer->GetHealth() > 0))
return;
if (!precipitation_client_class) {
for (auto pclass = iff.g_pClient->GetAllClasses(); pclass && !precipitation_client_class; pclass = pclass->m_pNext)
if (strstr(pclass->GetName(), "CPrecipitation"))
{
#ifdef DEBUG
printf("class found %x\n", pclass);
#endif
precipitation_client_class = pclass;
}
}
else {
if (!rain_ent && precipitation_client_class && precipitation_client_class->m_pCreateFn) {
#ifdef DEBUG
printf("Creating precipitation\n");
#endif
rain_networkable = ((void* (*)(int, int))precipitation_client_class->m_pCreateFn)(MAX_EDICTS - 1, 0);
if (rain_networkable) {
rain_ent = (C_Precipitation*)iff.g_pEntityList->GetClientEntity(MAX_EDICTS - 1);
rain_ent->GetPrecipitationType() = (PrecipitationType_t)*g_Options.weathertype;
rain_ent->PreDataUpdate(DataUpdateType_t::DATA_UPDATE_CREATED);
rain_ent->OnPreDataChanged(DataUpdateType_t::DATA_UPDATE_CREATED);
rain_ent->GetMins() = Vector(-32767.0f, -32767.0f, -32767.0f);
rain_ent->GetMaxs() = Vector(32767.0f, 32767.0f, 32767.0f);
rain_ent->OnDataChanged(DataUpdateType_t::DATA_UPDATE_CREATED);
rain_ent->PostDataUpdate(DataUpdateType_t::DATA_UPDATE_CREATED);
#ifdef DEBUG
printf("Created precipitation %x\n", rain_ent);
#endif
}
}
}
}

15
SpyCustom/Other.hpp Normal file
View File

@ -0,0 +1,15 @@
#ifndef OTHER
#define OTHER
#pragma once
#include "Interfaces.hpp"
#include "Options.hpp"
#include "c_baseentity.h"
void FlashlightRun(C_BasePlayer* local);
void NightvisionRun(C_BasePlayer* local);
void do_precipitation();
#endif OTHER

70
SpyCustom/PHandle.h Normal file
View File

@ -0,0 +1,70 @@
#ifndef PHANDLE_H
#define PHANDLE_H
#ifdef _WIN32
#pragma once
#endif
#include "VGUI.h"
namespace vgui
{
class Panel;
class PHandle
{
public:
PHandle() : m_iPanelID(INVALID_PANEL) {}
Panel* Get();
Panel* Set(Panel* pPanel);
Panel* Set(HPanel hPanel);
operator Panel* () { return Get(); }
Panel* operator ->() { return Get(); }
Panel* operator = (Panel* pPanel) { return Set(pPanel); }
bool operator == (Panel* pPanel) { return (Get() == pPanel); }
operator bool() { return Get() != 0; }
private:
HPanel m_iPanelID;
};
class VPanelHandle
{
public:
VPanelHandle() : m_iPanelID(INVALID_PANEL) {}
VPANEL Get();
VPANEL Set(VPANEL pPanel);
operator VPANEL () { return Get(); }
VPANEL operator = (VPANEL pPanel) { return Set(pPanel); }
bool operator == (VPANEL pPanel) { return (Get() == pPanel); }
operator bool() { return Get() != 0; }
private:
HPanel m_iPanelID;
};
template< class PanelType >
class DHANDLE : public PHandle
{
public:
PanelType* Get() { return (PanelType*)PHandle::Get(); }
PanelType* Set(PanelType* pPanel) { return (PanelType*)PHandle::Set(pPanel); }
PanelType* Set(HPanel hPanel) { return (PanelType*)PHandle::Set(hPanel); }
operator PanelType* () { return (PanelType*)PHandle::Get(); }
PanelType* operator ->() { return (PanelType*)PHandle::Get(); }
PanelType* operator = (PanelType* pPanel) { return (PanelType*)PHandle::Set(pPanel); }
bool operator == (Panel* pPanel) { return (PHandle::Get() == pPanel); }
operator bool() { return PHandle::Get() != NULL; }
};
};
#endif

962
SpyCustom/Panel.h Normal file
View File

@ -0,0 +1,962 @@
#ifndef PANEL_H
#define PANEL_H
#ifdef _WIN32
#pragma once
#endif
#include "utlflags.h"
#include "vgui.h"
#include "Dar.h"
#include "MessageMap.h"
#if defined( VGUI_USEKEYBINDINGMAPS )
#include "KeyBindingMap.h"
#endif
#include "IClientPanel.h"
#include "IScheme.h"
#include "Controls.h"
#include "PHandle.h"
#include "PanelAnimationVar.h"
#include "color.h"
#include "keyvalues.h"
#include "ikeyvaluessystem.h"
#include "utlsymbol.h"
#include "BuildGroup.h"
#include "dmxelement.h"
#ifdef PostMessage
#undef PostMessage
#endif
#ifdef SetCursor
#undef SetCursor
#endif
class CUtlBuffer;
struct DmxElementUnpackStructure_t;
namespace vgui
{
#if !defined( _GAMECONSOLE )
#define VGUI_USEDRAGDROP 1
#endif
#if defined( VGUI_USEKEYBINDINGMAPS )
struct PanelKeyBindingMap;
#endif
template< class T >
inline T* SETUP_PANEL(T* panel)
{
panel->MakeReadyForUse();
return panel;
}
#define CREATE_PANEL(type, parent, name) (SETUP_PANEL(new type(parent, name)))
#if defined( VGUI_USEDRAGDROP )
struct DragDrop_t;
class Menu;
#endif
class Panel;
struct SizerAddArgs_t
{
SizerAddArgs_t()
{
m_flExpandFactor = 0.0f;
m_nPadding = 5;
m_bMinorExpand = true;
m_nMinX = -1;
m_nMinY = -1;
m_bIgnoreMemberMin = false;
}
SizerAddArgs_t& Expand(float flExpandFactor) { m_flExpandFactor = flExpandFactor; return *this; }
SizerAddArgs_t& Padding(int nPadding) { m_nPadding = nPadding; return *this; }
SizerAddArgs_t& MinorExpand(bool bMinorExpand) { m_bMinorExpand = bMinorExpand; return *this; }
SizerAddArgs_t& MinSize(int nMinX, int nMinY) { m_nMinX = nMinX; m_nMinY = nMinY; return *this; }
SizerAddArgs_t& MinX(int nMinX) { m_nMinX = nMinX; return *this; }
SizerAddArgs_t& MinY(int nMinY) { m_nMinY = nMinY; return *this; }
SizerAddArgs_t& IgnoreMemberMin(bool bIgnoreMemberMin = true) { m_bIgnoreMemberMin = bIgnoreMemberMin; return *this; }
SizerAddArgs_t& FixedSize(int nX, int nY)
{
IgnoreMemberMin(true);
MinSize(nX, nY);
Expand(0.f);
MinorExpand(false);
return *this;
}
float m_flExpandFactor;
int m_nPadding;
bool m_bMinorExpand;
int m_nMinX;
int m_nMinY;
bool m_bIgnoreMemberMin;
};
enum SizerLayoutDirection_t
{
ESLD_HORIZONTAL,
ESLD_VERTICAL
};
enum SizerElementType_t
{
ESET_SIZER,
ESET_PANEL,
ESET_SPACER,
};
class CSizerBase
{
public:
CSizerBase();
virtual ~CSizerBase();
int GetElementCount() { return m_Members.Count(); }
SizerElementType_t GetElementType(int i);
Panel* GetPanel(int i);
void SetElementArgs(int nIndex, const SizerAddArgs_t& args) { m_Members[nIndex].Fill(args); }
void InsertPanel(int nIndex, Panel* pPanel, const SizerAddArgs_t& args);
void InsertSizer(int nIndex, CSizerBase* pSizer, const SizerAddArgs_t& args);
void InsertSpacer(int nIndex, const SizerAddArgs_t& args);
void AddPanel(Panel* pPanel, const SizerAddArgs_t& args) { InsertPanel(GetElementCount(), pPanel, args); }
void AddSizer(CSizerBase* pSizer, const SizerAddArgs_t& args) { InsertSizer(GetElementCount(), pSizer, args); }
void AddSpacer(const SizerAddArgs_t& args) { InsertSpacer(GetElementCount(), args); }
void RemoveElement(int i, bool bDelete);
void RemoveAllMembers(bool bDelete);
void GetMinSize(int& OutX, int& OutY);
void RecursiveInvalidateCachedSize();
virtual void DoLayout(int BaseX, int BaseY, int SizeX, int SizeY) = 0;
virtual void CalculateSize() = 0;
protected:
class CSizerMember
{
friend class CSizerBase;
public:
SizerElementType_t GetElementType() const;
Panel* GetPanel() const;
void GetMemberMinSize(int& OutX, int& OutY);
void RecursiveInvalidateCachedSize();
void Place(int BaseX, int BaseY, int SizeX, int SizeY);
float GetExpandFactor() { return m_flExpandFactor; }
bool GetMinorExpand() { return m_bMinorExpand; }
void DiscardOwnedSizer();
bool IsVisible();
void Fill(const SizerAddArgs_t& args);
private:
void RecursiveRemove(bool bDelete);
Panel* m_pPanel;
CSizerBase* m_pSizer;
int m_nPadding;
float m_flExpandFactor;
bool m_bMinorExpand;
bool m_bIgnoreMemberMin;
int m_nMinX;
int m_nMinY;
};
CUtlVector<CSizerMember> m_Members;
int m_nMinXSize;
int m_nMinYSize;
};
inline int SizerMajorAxis(SizerLayoutDirection_t Dir, int X, int Y) { return (Dir == ESLD_HORIZONTAL) ? X : Y; }
inline int SizerMinorAxis(SizerLayoutDirection_t Dir, int X, int Y) { return (Dir == ESLD_VERTICAL) ? X : Y; }
inline int SizerXAxis(SizerLayoutDirection_t Dir, int MajorAxis, int MinorAxis) { return (Dir == ESLD_HORIZONTAL) ? MajorAxis : MinorAxis; }
inline int SizerYAxis(SizerLayoutDirection_t Dir, int MajorAxis, int MinorAxis) { return (Dir == ESLD_VERTICAL) ? MajorAxis : MinorAxis; }
class CBoxSizer : public CSizerBase
{
public:
CBoxSizer(SizerLayoutDirection_t LayoutDirection);
virtual void CalculateSize();
virtual void DoLayout(int BaseX, int BaseY, int SizeX, int SizeY);
protected:
SizerLayoutDirection_t m_LayoutDirection;
};
struct OverridableColorEntry
{
char const* name() { return m_pszScriptName; }
char const* m_pszScriptName;
Color* m_pColor;
Color m_colFromScript;
UtlSymId_t m_sColorNameFromScript;
bool m_bOverridden;
};
#define REGISTER_COLOR_AS_OVERRIDABLE( name, scriptname ) \
AddToOverridableColors( &name, scriptname );
#define DECLARE_VGUI_UNPACK() \
DECLARE_DMXELEMENT_UNPACK() \
private: \
static DmxElementUnpackStructure_t *s_pUnpackParams; \
public: \
virtual const DmxElementUnpackStructure_t* GetUnpackStructure() const { return s_pUnpackParams; }
#define DECLARE_VGUI_UNPACK_NAMESPACE( _namespace ) \
template <typename T> friend DmxElementUnpackStructure_t *DmxElementUnpackInit##_namespace(T *); \
private: \
static DmxElementUnpackStructure_t *s_pUnpackParams; \
public: \
virtual const DmxElementUnpackStructure_t* GetUnpackStructure() const { return s_pUnpackParams; }
#define BEGIN_VGUI_UNPACK( _structName ) BEGIN_DMXELEMENT_UNPACK( _structName )
#define END_VGUI_UNPACK( _structName ) \
END_DMXELEMENT_UNPACK( _structName, s_pUnpackParams ) \
DmxElementUnpackStructure_t *_structName::s_pUnpackParams = _structName##_UnpackInit::s_pUnpack;
#define BEGIN_VGUI_UNPACK_NAMESPACE( _nameSpace, _structName ) BEGIN_DMXELEMENT_UNPACK_NAMESPACE( _nameSpace, _structName )
#define END_VGUI_UNPACK_NAMESPACE( _nameSpace, _structName ) \
END_DMXELEMENT_UNPACK_NAMESPACE( _nameSpace, _structName, s_pUnpackParams ) \
DmxElementUnpackStructure_t *_structName::s_pUnpackParams = _namespace##_structName##_UnpackInit::s_pUnpack;
class IPanelAnimationPropertyConverter
{
public:
virtual void GetData(Panel* panel, KeyValues* kv, PanelAnimationMapEntry* entry) = 0;
virtual void SetData(Panel* panel, KeyValues* kv, PanelAnimationMapEntry* entry) = 0;
virtual void InitFromDefault(Panel* panel, PanelAnimationMapEntry* entry) = 0;
};
#if defined( VGUI_USEKEYBINDINGMAPS )
enum KeyBindingContextHandle_t
{
INVALID_KEYBINDINGCONTEXT_HANDLE = 0xffffffff,
};
#endif
#define PANEL_ROUND_CORNER_TOP_LEFT (1 << 0)
#define PANEL_ROUND_CORNER_TOP_RIGHT (1 << 1)
#define PANEL_ROUND_CORNER_BOTTOM_LEFT (1 << 2)
#define PANEL_ROUND_CORNER_BOTTOM_RIGHT (1 << 3)
#define PANEL_ROUND_CORNER_ALL PANEL_ROUND_CORNER_TOP_LEFT | PANEL_ROUND_CORNER_TOP_RIGHT | PANEL_ROUND_CORNER_BOTTOM_LEFT | PANEL_ROUND_CORNER_BOTTOM_RIGHT
class Panel : public IClientPanel
{
DECLARE_CLASS_SIMPLE_NOBASE(Panel);
DECLARE_DMXELEMENT_UNPACK_NAMESPACE(vgui);
public:
static void InitPropertyConverters(void);
static void AddPropertyConverter(char const* typeName, IPanelAnimationPropertyConverter* converter);
Panel();
Panel(Panel* parent);
Panel(Panel* parent, const char* panelName);
Panel(Panel* parent, const char* panelName, HScheme scheme);
virtual ~Panel();
virtual VPANEL GetVPanel() { return _vpanel; }
HPanel ToHandle() const;
void SetName(const char* panelName);
const char* GetName();
const char* GetClassName();
void MakeReadyForUse();
void SetPos(int x, int y);
void GetPos(int& x, int& y);
void SetSize(int wide, int tall);
void GetSize(int& wide, int& tall);
void SetBounds(int x, int y, int wide, int tall);
void GetBounds(int& x, int& y, int& wide, int& tall);
int GetWide();
void SetWide(int wide);
int GetTall();
void SetTall(int tall);
void SetMinimumSize(int wide, int tall);
void GetMinimumSize(int& wide, int& tall);
bool IsBuildModeEditable();
void SetBuildModeEditable(bool state);
bool IsBuildModeDeletable();
void SetBuildModeDeletable(bool state);
bool IsBuildModeActive();
void SetZPos(int z);
int GetZPos(void);
void SetAlpha(int alpha);
int GetAlpha();
virtual void SetVisible(bool state);
virtual bool IsVisible();
virtual bool IsFullyVisible();
virtual VPANEL IsWithinTraverse(int x, int y, bool traversePopups);
MESSAGE_FUNC(Repaint, "Repaint");
virtual void PostMessage(VPANEL target, KeyValues* message, float delaySeconds = 0.0f);
bool IsWithin(int x, int y);
void LocalToScreen(int& x, int& y);
void ScreenToLocal(int& x, int& y);
void ParentLocalToScreen(int& x, int& y);
void MakePopup(bool showTaskbarIcon = true, bool disabled = false);
virtual void OnMove();
virtual Panel* GetParent();
virtual VPANEL GetVParent();
virtual void SetParent(Panel* newParent);
virtual void SetParent(VPANEL newParent);
virtual bool HasParent(VPANEL potentialParent);
int GetChildCount();
Panel* GetChild(int index);
int FindChildIndexByName(const char* childName);
Panel* FindChildByName(const char* childName, bool recurseDown = false);
Panel* FindSiblingByName(const char* siblingName);
void CallParentFunction(KeyValues* message);
virtual bool LookupElementBounds(const char* elementName, int& x, int& y, int& wide, int& tall) { return false; }
virtual void SetAutoDelete(bool state);
virtual bool IsAutoDeleteSet();
virtual void DeletePanel();
virtual void AddActionSignalTarget(Panel* messageTarget);
virtual void AddActionSignalTarget(VPANEL messageTarget);
virtual void RemoveActionSignalTarget(Panel* oldTarget);
virtual void PostActionSignal(KeyValues* message);
virtual bool RequestInfoFromChild(const char* childName, KeyValues* outputData);
virtual void PostMessageToChild(const char* childName, KeyValues* messsage);
virtual void PostMessage(Panel* target, KeyValues* message, float delaySeconds = 0.0f);
virtual bool RequestInfo(KeyValues* outputData);
virtual bool SetInfo(KeyValues* inputData);
virtual void SetSilentMode(bool bSilent);
virtual void InstallMouseHandler(Panel* pHandler);
virtual void SetEnabled(bool state);
virtual bool IsEnabled();
virtual bool IsPopup();
virtual void GetClipRect(int& x0, int& y0, int& x1, int& y1);
virtual void MoveToFront();
enum PinCorner_e
{
PIN_TOPLEFT = 0,
PIN_TOPRIGHT,
PIN_BOTTOMLEFT,
PIN_BOTTOMRIGHT,
PIN_NO,
PIN_CENTER_TOP,
PIN_CENTER_RIGHT,
PIN_CENTER_BOTTOM,
PIN_CENTER_LEFT,
};
enum AutoResize_e
{
AUTORESIZE_NO = 0,
AUTORESIZE_RIGHT,
AUTORESIZE_DOWN,
AUTORESIZE_DOWNANDRIGHT,
};
void SetPinCorner(PinCorner_e pinCorner, int nOffsetX, int nOffsetY);
void SetAutoResize(PinCorner_e pinCorner, AutoResize_e resizeDir, int nPinOffsetX, int nPinOffsetY, int nUnpinnedCornerOffsetX, int nUnpinnedCornerOffsetY);
AutoResize_e GetAutoResize();
PinCorner_e GetPinCorner();
void GetPinOffset(int& dx, int& dy);
void GetResizeOffset(int& dx, int& dy);
void PinToSibling(const char* pszSibling, PinCorner_e pinOurCorner, PinCorner_e pinSibling);
void UpdateSiblingPin(void);
virtual void SetBgColor(Color color);
virtual void SetFgColor(Color color);
virtual Color GetBgColor();
virtual Color GetFgColor();
virtual void SetCursor(HCursor cursor);
virtual HCursor GetCursor();
virtual void RequestFocus(int direction = 0);
virtual bool HasFocus();
virtual void InvalidateLayout(bool layoutNow = false, bool reloadScheme = false);
virtual bool RequestFocusPrev(VPANEL panel = NULL);
virtual bool RequestFocusNext(VPANEL panel = NULL);
virtual void SetTabPosition(int position);
virtual int GetTabPosition();
virtual void SetBorder(IBorder* border);
virtual IBorder* GetBorder();
virtual void SetPaintBorderEnabled(bool state);
virtual void SetPaintBackgroundEnabled(bool state);
virtual void SetPaintEnabled(bool state);
virtual void SetPostChildPaintEnabled(bool state);
virtual void SetPaintBackgroundType(int type);
virtual void GetInset(int& left, int& top, int& right, int& bottom);
virtual void GetPaintSize(int& wide, int& tall);
virtual void SetBuildGroup(BuildGroup* buildGroup);
virtual bool IsBuildGroupEnabled();
virtual bool IsCursorNone();
virtual bool IsCursorOver();
virtual void MarkForDeletion();
virtual bool IsLayoutInvalid();
virtual Panel* HasHotkey(wchar_t key);
virtual bool IsOpaque();
bool IsRightAligned();
bool IsBottomAligned();
bool IsPercentage();
virtual HScheme GetScheme();
virtual void SetScheme(const char* tag);
virtual void SetScheme(HScheme scheme);
virtual Color GetSchemeColor(const char* keyName, IScheme* pScheme);
virtual Color GetSchemeColor(const char* keyName, Color defaultColor, IScheme* pScheme);
virtual void ApplySchemeSettings(IScheme* pScheme);
virtual void ApplySettings(KeyValues* inResourceData);
virtual void OnUnserialized(CDmxElement* pElement);
virtual void GetSettings(KeyValues* outResourceData);
virtual const char* GetDescription();
virtual const char* GetModuleName();
virtual void ApplyUserConfigSettings(KeyValues* userConfig);
virtual void GetUserConfigSettings(KeyValues* userConfig);
virtual bool HasUserConfigSettings();
virtual void OnMessage(const KeyValues* params, VPANEL fromPanel);
MESSAGE_FUNC_CHARPTR(OnCommand, "Command", command);
MESSAGE_FUNC(OnMouseCaptureLost, "MouseCaptureLost");
MESSAGE_FUNC(OnSetFocus, "SetFocus");
MESSAGE_FUNC(OnKillFocus, "KillFocus");
MESSAGE_FUNC(OnDelete, "Delete");
virtual void OnThink();
virtual void OnChildAdded(VPANEL child);
virtual void OnSizeChanged(int newWide, int newTall);
virtual void OnTick();
MESSAGE_FUNC_INT_INT(OnCursorMoved, "OnCursorMoved", x, y);
virtual void OnCursorEntered();
virtual void OnCursorExited();
virtual void OnMousePressed(MouseCode code);
virtual void OnMouseDoublePressed(MouseCode code);
virtual void OnMouseReleased(MouseCode code);
virtual void OnMouseWheeled(int delta);
virtual void SetTriplePressAllowed(bool state);
virtual bool IsTriplePressAllowed() const;
virtual void OnMouseTriplePressed(MouseCode code);
static char const* KeyCodeToString(KeyCode code);
static wchar_t const* KeyCodeToDisplayString(KeyCode code);
static wchar_t const* KeyCodeModifiersToDisplayString(KeyCode code, int modifiers);
static KeyCode StringToKeyCode(char const* str);
#if defined( VGUI_USEKEYBINDINGMAPS )
static KeyBindingContextHandle_t CreateKeyBindingsContext(char const* filename, char const* pathID = 0);
virtual void SetKeyBindingsContext(KeyBindingContextHandle_t handle);
virtual KeyBindingContextHandle_t GetKeyBindingsContext() const;
virtual bool IsValidKeyBindingsContext() const;
static int GetPanelsWithKeyBindingsCount(KeyBindingContextHandle_t handle);
static Panel* GetPanelWithKeyBindings(KeyBindingContextHandle_t handle, int index);
static void RevertKeyBindings(KeyBindingContextHandle_t handle);
static void ReloadKeyBindings(KeyBindingContextHandle_t handle);
static void SaveKeyBindings(KeyBindingContextHandle_t handle);
static void SaveKeyBindingsToFile(KeyBindingContextHandle_t handle, char const* filename, char const* pathID = 0);
static void LoadKeyBindings(KeyBindingContextHandle_t handle);
static void LoadKeyBindingsForOnePanel(KeyBindingContextHandle_t handle, Panel* panelOfInterest);
virtual bool IsKeyRebound(KeyCode code, int modifiers);
virtual bool IsKeyOverridden(KeyCode code, int modifiers);
virtual void AddKeyBinding(char const* bindingName, int keycode, int modifiers);
KeyBindingMap_t* LookupBinding(char const* bindingName);
KeyBindingMap_t* LookupBindingByKeyCode(KeyCode code, int modifiers);
void LookupBoundKeys(char const* bindingName, CUtlVector< BoundKey_t* >& list);
BoundKey_t* LookupDefaultKey(char const* bindingName);
PanelKeyBindingMap* LookupMapForBinding(char const* bindingName);
int GetKeyMappingCount();
void RevertKeyBindingsToDefault();
void RemoveAllKeyBindings();
void ReloadKeyBindings();
virtual void EditKeyBindings();
void SaveKeyBindingsToBuffer(int level, CUtlBuffer& buf);
bool ParseKeyBindings(KeyValues* kv);
virtual char const* GetKeyBindingsFile() const;
virtual char const* GetKeyBindingsFilePathID() const;
void SetAllowKeyBindingChainToParent(bool state);
bool IsKeyBindingChainToParentAllowed() const;
#endif
virtual void OnKeyCodePressed(KeyCode code);
virtual void OnKeyCodeTyped(KeyCode code);
virtual void OnKeyTyped(wchar_t unichar);
virtual void OnKeyCodeReleased(KeyCode code);
virtual void OnKeyFocusTicked();
MESSAGE_FUNC(OnMouseFocusTicked, "OnMouseFocusTicked");
virtual void PaintBackground();
virtual void Paint();
virtual void PaintBorder();
virtual void PaintBuildOverlay();
virtual void PostChildPaint();
virtual void PerformLayout();
DECLARE_PANELMAP();
virtual VPANEL GetCurrentKeyFocus();
BaseTooltip* GetTooltip();
void SetTooltip(BaseTooltip* pToolTip, const char* pszText);
virtual bool IsProportional() { return _flags.IsFlagSet(IS_PROPORTIONAL); }
virtual void SetProportional(bool state);
virtual void SetMouseInputEnabled(bool state);
virtual void SetKeyBoardInputEnabled(bool state);
virtual bool IsMouseInputEnabled();
virtual bool IsKeyBoardInputEnabled();
void DisableMouseInputForThisPanel(bool bDisable);
bool IsMouseInputDisabledForThisPanel() const;
virtual void DrawTexturedBox(int x, int y, int wide, int tall, Color color, float normalizedAlpha);
virtual void DrawBox(int x, int y, int wide, int tall, Color color, float normalizedAlpha, bool hollow = false);
virtual void DrawBoxFade(int x, int y, int wide, int tall, Color color, float normalizedAlpha, unsigned int alpha0, unsigned int alpha1, bool bHorizontal, bool hollow = false);
virtual void DrawHollowBox(int x, int y, int wide, int tall, Color color, float normalizedAlpha);
virtual void DrawHollowBox(int x, int y, int wide, int tall, Color color, float normalizedAlpha, int cornerWide, int cornerTall);
unsigned char GetRoundedCorners() { return m_roundedCorners; }
void SetRoundedCorners(unsigned char cornerFlags) { m_roundedCorners = cornerFlags; }
bool ShouldDrawTopLeftCornerRounded() { return 0 != (m_roundedCorners & PANEL_ROUND_CORNER_TOP_LEFT); }
bool ShouldDrawTopRightCornerRounded() { return 0 != (m_roundedCorners & PANEL_ROUND_CORNER_TOP_RIGHT); }
bool ShouldDrawBottomLeftCornerRounded() { return 0 != (m_roundedCorners & PANEL_ROUND_CORNER_BOTTOM_LEFT); }
bool ShouldDrawBottomRightCornerRounded() { return 0 != (m_roundedCorners & PANEL_ROUND_CORNER_BOTTOM_RIGHT); }
virtual void SetDragEnabled(bool enabled);
virtual bool IsDragEnabled() const;
virtual void SetShowDragHelper(bool enabled);
virtual void OnDragFailed(CUtlVector< KeyValues* >& msglist);
virtual void SetBlockDragChaining(bool block);
virtual bool IsBlockingDragChaining() const;
virtual int GetDragStartTolerance() const;
virtual void SetDragSTartTolerance(int nTolerance);
virtual void SetDropEnabled(bool enabled, float m_flHoverContextTime = 0.0f);
virtual bool IsDropEnabled() const;
virtual bool GetDropContextMenu(Menu* menu, CUtlVector< KeyValues* >& msglist);
virtual void OnDropContextHoverShow(CUtlVector< KeyValues* >& msglist);
virtual void OnDropContextHoverHide(CUtlVector< KeyValues* >& msglist);
#if defined( VGUI_USEDRAGDROP )
virtual DragDrop_t* GetDragDropInfo();
#endif
virtual void OnGetAdditionalDragPanels(CUtlVector< Panel* >& dragabbles);
virtual void OnCreateDragData(KeyValues* msg);
virtual bool IsDroppable(CUtlVector< KeyValues* >& msglist);
virtual void OnDraggablePanelPaint();
virtual void OnDroppablePanelPaint(CUtlVector< KeyValues* >& msglist, CUtlVector< Panel* >& dragPanels);
virtual void OnPanelDropped(CUtlVector< KeyValues* >& msglist);
virtual void OnPanelEnteredDroppablePanel(CUtlVector< KeyValues* >& msglist);
virtual void OnPanelExitedDroppablePanel(CUtlVector< KeyValues* >& msglist);
virtual Panel* GetDropTarget(CUtlVector< KeyValues* >& msglist);
virtual Panel* GetDragPanel();
virtual bool IsBeingDragged();
virtual HCursor GetDropCursor(CUtlVector< KeyValues* >& msglist);
virtual HCursor GetDragFailCursor(CUtlVector< KeyValues* >& msglist) { return dc_no; }
Color GetDropFrameColor();
Color GetDragFrameColor();
virtual bool CanStartDragging(int startx, int starty, int mx, int my);
virtual void FillRectSkippingPanel(const Color clr, int x, int y, int w, int h, Panel* skipPanel);
virtual int GetPaintBackgroundType();
virtual void GetCornerTextureSize(int& w, int& h);
bool IsChildOfModalSubTree();
bool IsChildOfSurfaceModalPanel();
bool ShouldHandleInputMessage();
virtual void SetSkipChildDuringPainting(Panel* child);
void SetStartDragWhenMouseExitsPanel(bool state);
bool IsStartDragWhenMouseExitsPanel() const;
void SetMessageContextId_R(int nContextID);
void PostMessageToAllSiblings(KeyValues* msg, float delaySeconds = 0.0f);
template< class S >
void PostMessageToAllSiblingsOfType(KeyValues* msg, float delaySeconds = 0.0f);
void SetConsoleStylePanel(bool bConsoleStyle);
bool IsConsoleStylePanel() const;
enum NAV_DIRECTION { ND_UP, ND_DOWN, ND_LEFT, ND_RIGHT, ND_BACK, ND_NONE };
virtual Panel* NavigateUp();
virtual Panel* NavigateDown();
virtual Panel* NavigateLeft();
virtual Panel* NavigateRight();
virtual void NavigateTo();
virtual void NavigateFrom();
virtual void NavigateToChild(Panel* pNavigateTo);
Panel* SetNavUp(Panel* navUp);
Panel* SetNavDown(Panel* navDown);
Panel* SetNavLeft(Panel* navLeft);
Panel* SetNavRight(Panel* navRight);
NAV_DIRECTION GetLastNavDirection();
MESSAGE_FUNC_CHARPTR(OnNavigateTo, "OnNavigateTo", panelName);
MESSAGE_FUNC_CHARPTR(OnNavigateFrom, "OnNavigateFrom", panelName);
protected:
virtual void OnStartDragging();
virtual void OnContinueDragging();
virtual void OnFinishDragging(bool mousereleased, MouseCode code, bool aborted = false);
virtual void DragDropStartDragging();
virtual void GetDragData(CUtlVector< KeyValues* >& list);
virtual void CreateDragData();
virtual void PaintTraverse(bool Repaint, bool allowForce = true);
protected:
MESSAGE_FUNC_ENUM_ENUM(OnRequestFocus, "OnRequestFocus", VPANEL, subFocus, VPANEL, defaultPanel);
MESSAGE_FUNC_INT_INT(OnScreenSizeChanged, "OnScreenSizeChanged", oldwide, oldtall);
virtual void* QueryInterface(EInterfaceID id);
void AddToOverridableColors(Color* pColor, char const* scriptname)
{
int iIdx = m_OverridableColorEntries.AddToTail();
m_OverridableColorEntries[iIdx].m_pszScriptName = scriptname;
m_OverridableColorEntries[iIdx].m_pColor = pColor;
m_OverridableColorEntries[iIdx].m_bOverridden = false;
}
void ApplyOverridableColors(IScheme* pScheme);
void SetOverridableColor(Color* pColor, const Color& newColor);
protected:
void SetNavUp(const char* controlName);
void SetNavDown(const char* controlName);
void SetNavLeft(const char* controlName);
void SetNavRight(const char* controlName);
public:
Panel* GetNavUp(Panel* first = NULL);
Panel* GetNavDown(Panel* first = NULL);
Panel* GetNavLeft(Panel* first = NULL);
Panel* GetNavRight(Panel* first = NULL);
inline void SetWorldPositionCurrentFrame(bool bWorldPositionCurrentFrame) { m_bWorldPositionCurrentFrame = bWorldPositionCurrentFrame; }
inline bool GetWorldPositionCurrentFrame() { return m_bWorldPositionCurrentFrame; }
protected:
Panel* GetNavUpPanel();
Panel* GetNavDownPanel();
Panel* GetNavLeftPanel();
Panel* GetNavRightPanel();
bool m_PassUnhandledInput;
NAV_DIRECTION m_LastNavDirection;
void InternalInitDefaultValues(PanelAnimationMap* map);
private:
enum BuildModeFlags_t
{
BUILDMODE_EDITABLE = 0x01,
BUILDMODE_DELETABLE = 0x02,
BUILDMODE_SAVE_XPOS_RIGHTALIGNED = 0x04,
BUILDMODE_SAVE_XPOS_CENTERALIGNED = 0x08,
BUILDMODE_SAVE_YPOS_BOTTOMALIGNED = 0x10,
BUILDMODE_SAVE_YPOS_CENTERALIGNED = 0x20,
BUILDMODE_SAVE_WIDE_FULL = 0x40,
BUILDMODE_SAVE_TALL_FULL = 0x80,
BUILDMODE_SAVE_PROPORTIONAL_TO_PARENT = 0x100,
BUILDMODE_SAVE_PERCENTAGE = 0x200,
};
enum PanelFlags_t
{
MARKED_FOR_DELETION = 0x0001,
NEEDS_REPAINT = 0x0002,
PAINT_BORDER_ENABLED = 0x0004,
PAINT_BACKGROUND_ENABLED = 0x0008,
PAINT_ENABLED = 0x0010,
POST_CHILD_PAINT_ENABLED = 0x0020,
AUTODELETE_ENABLED = 0x0040,
NEEDS_LAYOUT = 0x0080,
NEEDS_SCHEME_UPDATE = 0x0100,
NEEDS_DEFAULT_SETTINGS_APPLIED = 0x0200,
#if defined( VGUI_USEKEYBINDINGMAPS )
ALLOW_CHAIN_KEYBINDING_TO_PARENT = 0x0400,
#endif
IN_PERFORM_LAYOUT = 0x0800,
IS_PROPORTIONAL = 0x1000,
TRIPLE_PRESS_ALLOWED = 0x2000,
DRAG_REQUIRES_PANEL_EXIT = 0x4000,
IS_MOUSE_DISABLED_FOR_THIS_PANEL_ONLY = 0x8000,
ALL_FLAGS = 0xFFFF,
};
virtual Panel* GetPanel() { return this; }
void Think();
void PerformApplySchemeSettings();
void InternalPerformLayout();
void InternalSetCursor();
MESSAGE_FUNC_INT_INT(InternalCursorMoved, "CursorMoved", xpos, ypos);
MESSAGE_FUNC(InternalCursorEntered, "CursorEntered");
MESSAGE_FUNC(InternalCursorExited, "CursorExited");
MESSAGE_FUNC_INT(InternalMousePressed, "MousePressed", code);
MESSAGE_FUNC_INT(InternalMouseDoublePressed, "MouseDoublePressed", code);
MESSAGE_FUNC_INT(InternalMouseTriplePressed, "MouseTriplePressed", code);
MESSAGE_FUNC_INT(InternalMouseReleased, "MouseReleased", code);
MESSAGE_FUNC_INT(InternalMouseWheeled, "MouseWheeled", delta);
MESSAGE_FUNC_INT(InternalKeyCodePressed, "KeyCodePressed", code);
MESSAGE_FUNC_INT(InternalKeyCodeTyped, "KeyCodeTyped", code);
MESSAGE_FUNC_INT(InternalKeyTyped, "KeyTyped", unichar);
MESSAGE_FUNC_INT(InternalKeyCodeReleased, "KeyCodeReleased", code);
MESSAGE_FUNC(InternalKeyFocusTicked, "KeyFocusTicked");
MESSAGE_FUNC(InternalMouseFocusTicked, "MouseFocusTicked");
MESSAGE_FUNC(InternalInvalidateLayout, "Invalidate");
MESSAGE_FUNC(InternalMove, "Move");
virtual void InternalFocusChanged(bool lost);
void Init(int x, int y, int wide, int tall);
void PreparePanelMap(PanelMap_t* panelMap);
bool InternalRequestInfo(PanelAnimationMap* map, KeyValues* outputData);
bool InternalSetInfo(PanelAnimationMap* map, KeyValues* inputData);
PanelAnimationMapEntry* FindPanelAnimationEntry(char const* scriptname, PanelAnimationMap* map);
void InternalApplySettings(PanelAnimationMap* map, KeyValues* inResourceData);
void ApplyAutoResizeSettings(KeyValues* inResourceData);
void FindDropTargetPanel_R(CUtlVector< VPANEL >& panelList, int x, int y, VPANEL check);
Panel* FindDropTargetPanel();
int GetProportionalScaledValue(int rootTall, int normalizedValue);
#if defined( VGUI_USEDRAGDROP )
DragDrop_t* m_pDragDrop;
Color m_clrDragFrame;
Color m_clrDropFrame;
#endif
BaseTooltip* m_pTooltips;
bool m_bToolTipOverridden;
PHandle m_SkipChild;
long m_lLastDoublePressTime;
HFont m_infoFont;
#if defined( VGUI_USEKEYBINDINGMAPS )
KeyBindingContextHandle_t m_hKeyBindingsContext;
#endif
VPANEL _vpanel;
CUtlString _panelName;
IBorder* _border;
CUtlFlags< unsigned short > _flags;
Dar<HPanel> _actionSignalTargetDar;
CUtlVector<OverridableColorEntry> m_OverridableColorEntries;
Color _fgColor;
Color _bgColor;
HBuildGroup _buildGroup;
short m_nPinDeltaX;
short m_nPinDeltaY;
short m_nResizeDeltaX;
short m_nResizeDeltaY;
HCursor _cursor;
unsigned short _buildModeFlags;
byte _pinCorner : 4;
byte _autoResizeDirection : 4;
GCC_DIAG_PUSH_OFF(overflow)
DECLARE_DMXELEMENT_BITFIELD(_pinCorner, byte, Panel)
DECLARE_DMXELEMENT_BITFIELD(_autoResizeDirection, byte, Panel)
GCC_DIAG_POP()
unsigned char _tabPosition;
HScheme m_iScheme;
bool m_bIsDMXSerialized : 1;
bool m_bUseSchemeColors : 1;
bool m_bIsSilent : 1;
bool m_bIsConsoleStylePanel : 1;
DECLARE_DMXELEMENT_BITFIELD(m_bUseSchemeColors, bool, Panel)
DECLARE_DMXELEMENT_BITFIELD(m_bIsSilent, bool, Panel)
char* _pinToSibling;
byte _pinToSiblingCorner;
byte _pinCornerToSibling;
PHandle m_pinSibling;
char* _tooltipText;
PHandle m_hMouseEventHandler;
bool m_bWorldPositionCurrentFrame;
CUtlSymbol m_sBorderName;
protected:
CUtlString m_sNavUpName;
PHandle m_NavUp;
CUtlString m_sNavDownName;
PHandle m_NavDown;
CUtlString m_sNavLeftName;
PHandle m_NavLeft;
CUtlString m_sNavRightName;
PHandle m_NavRight;
protected:
static int s_NavLock;
private:
CPanelAnimationVar(float, m_flAlpha, "alpha", "255");
CPanelAnimationVar(int, m_nPaintBackgroundType, "PaintBackgroundType", "0");
CPanelAnimationVarAliasType(int, m_nBgTextureId1, "Texture1", "vgui/hud/800corner1", "textureid");
CPanelAnimationVarAliasType(int, m_nBgTextureId2, "Texture2", "vgui/hud/800corner2", "textureid");
CPanelAnimationVarAliasType(int, m_nBgTextureId3, "Texture3", "vgui/hud/800corner3", "textureid");
CPanelAnimationVarAliasType(int, m_nBgTextureId4, "Texture4", "vgui/hud/800corner4", "textureid");
unsigned char m_roundedCorners;
friend class BuildGroup;
friend class BuildModeDialog;
friend class PHandle;
void OnOldMessage(KeyValues* params, VPANEL ifromPanel);
public:
virtual void GetSizerMinimumSize(int& wide, int& tall);
virtual void GetSizerClientArea(int& x, int& y, int& wide, int& tall);
CSizerBase* GetSizer();
void SetSizer(CSizerBase* pSizer);
protected:
CSizerBase* m_pSizer;
};
inline void Panel::DisableMouseInputForThisPanel(bool bDisable)
{
_flags.SetFlag(IS_MOUSE_DISABLED_FOR_THIS_PANEL_ONLY, bDisable);
}
inline bool Panel::IsMouseInputDisabledForThisPanel() const
{
return _flags.IsFlagSet(IS_MOUSE_DISABLED_FOR_THIS_PANEL_ONLY);
}
template< class S >
inline void Panel::PostMessageToAllSiblingsOfType(KeyValues* msg, float delaySeconds )
{
Panel* parent = GetParent();
if (parent)
{
int nChildCount = parent->GetChildCount();
for (int i = 0; i < nChildCount; ++i)
{
Panel* sibling = parent->GetChild(i);
if (sibling == this)
continue;
if (dynamic_cast<S*>(sibling))
{
PostMessage(sibling->GetVPanel(), msg->MakeCopy(), delaySeconds);
}
}
}
msg->deleteThis();
}
}
#endif

View File

@ -0,0 +1,153 @@
#ifndef PANELANIMATIONVAR_H
#define PANELANIMATIONVAR_H
#ifdef _WIN32
#pragma once
#endif
#include "utlvector.h"
#include "Panel.h"
#define DECLARE_PANELANIMATION( className ) \
static void AddToAnimationMap( char const *scriptname, char const *type, char const *var, \
char const *defaultvalue, bool array, PANELLOOKUPFUNC func ) \
{ \
PanelAnimationMap *map = FindOrAddPanelAnimationMap( GetPanelClassName() ); \
\
PanelAnimationMapEntry entry; \
entry.m_pszScriptName = scriptname; \
entry.m_pszVariable = var; \
entry.m_pszType = type; \
entry.m_pszDefaultValue = defaultvalue; \
entry.m_pfnLookup = func; \
entry.m_bArray = array; \
\
map->entries.AddToTail( entry ); \
} \
\
static void ChainToAnimationMap( void ) \
{ \
static bool chained = false; \
if ( chained ) \
return; \
chained = true; \
PanelAnimationMap *map = FindOrAddPanelAnimationMap( GetPanelClassName() ); \
map->pfnClassName = GetPanelClassName; \
if ( map && GetPanelBaseClassName() && GetPanelBaseClassName()[0] ) \
{ \
map->baseMap = FindOrAddPanelAnimationMap( GetPanelBaseClassName() ); \
} \
} \
\
class className##_Register; \
friend class className##_Register; \
class className##_Register \
{ \
public: \
className##_Register() \
{ \
className::ChainToAnimationMap(); \
} \
}; \
className##_Register m_RegisterAnimationClass; \
\
virtual PanelAnimationMap *GetAnimMap() \
{ \
return FindOrAddPanelAnimationMap( GetPanelClassName() ); \
}
typedef void* (*PANELLOOKUPFUNC)(vgui::Panel* panel);
#define CPanelAnimationVarAliasType( type, name, scriptname, defaultvalue, typealias ) \
class PanelAnimationVar_##name; \
friend class PanelAnimationVar_##name; \
static void *GetVar_##name( vgui::Panel *panel ) \
{ \
return &(( ThisClass *)panel)->name; \
} \
class PanelAnimationVar_##name \
{ \
public: \
static void InitVar() \
{ \
static bool bAdded = false; \
if ( !bAdded ) \
{ \
bAdded = true; \
AddToAnimationMap( scriptname, typealias, #name, defaultvalue, false, ThisClass::GetVar_##name ); \
} \
} \
PanelAnimationVar_##name() \
{ \
PanelAnimationVar_##name::InitVar(); \
} \
}; \
PanelAnimationVar_##name m_##name##_register; \
type name;
#define CPanelAnimationVar( type, name, scriptname, defaultvalue ) \
CPanelAnimationVarAliasType( type, name, scriptname, defaultvalue, #type )
#define CPanelAnimationStringVarAliasType( count, name, scriptname, defaultvalue, typealias ) \
class PanelAnimationVar_##name; \
friend class PanelAnimationVar_##name; \
static void *GetVar_##name( vgui::Panel *panel ) \
{ \
return &(( ThisClass *)panel)->name; \
} \
class PanelAnimationVar_##name \
{ \
public: \
static void InitVar() \
{ \
static bool bAdded = false; \
if ( !bAdded ) \
{ \
bAdded = true; \
AddToAnimationMap( scriptname, typealias, #name, defaultvalue, true, ThisClass::GetVar_##name ); \
} \
} \
PanelAnimationVar_##name() \
{ \
PanelAnimationVar_##name::InitVar(); \
} \
}; \
PanelAnimationVar_##name m_##name##_register; \
char name[ count ];
#define CPanelAnimationStringVar( count, name, scriptname, defaultvalue ) \
CPanelAnimationStringVarAliasType( count, name, scriptname, defaultvalue, "string" )
struct PanelAnimationMapEntry
{
char const* name() { return m_pszScriptName; }
char const* type() { return m_pszType; }
char const* defaultvalue() { return m_pszDefaultValue; }
bool isarray() { return m_bArray; }
char const* m_pszScriptName;
char const* m_pszVariable;
char const* m_pszType;
char const* m_pszDefaultValue;
bool m_bArray;
PANELLOOKUPFUNC m_pfnLookup;
};
struct PanelAnimationMap
{
PanelAnimationMap()
{
baseMap = NULL;
pfnClassName = NULL;
}
CUtlVector< PanelAnimationMapEntry > entries;
PanelAnimationMap* baseMap;
char const* (*pfnClassName)(void);
};
PanelAnimationMap* FindPanelAnimationMap(char const* className);
PanelAnimationMap* FindOrAddPanelAnimationMap(char const* className);
void PanelAnimationDumpVars(char const* className);
#endif

View File

@ -0,0 +1,210 @@
#ifndef PARTICLESPHERERENDERER_H
#define PARTICLESPHERERENDERER_H
#ifdef _WIN32
#pragma once
#endif
#include "particlemgr.h"
#include "particle_util.h"
class CParticleSphereRenderer
{
public:
CParticleSphereRenderer();
void Init(CParticleMgr* pParticleMgr, IMaterial* pMaterial);
void StartRender(VMatrix& effectMatrix);
void RenderParticle(
ParticleDraw* pDraw,
const Vector& vOriginalPos,
const Vector& vTransformedPos,
float flAlpha,
float flParticleSize,
float flAngle = 0.0f);
void RenderParticle_AddColor(
ParticleDraw* pDraw,
const Vector& vOriginalPos,
const Vector& vTransformedPos,
float flAlpha,
float flParticleSize,
const Vector& vToAdd0to1
);
const Vector& GetBaseColor() const;
void SetBaseColor(const Vector& vColor);
const CParticleLightInfo& GetAmbientLight() const;
void SetAmbientLight(const CParticleLightInfo& info);
const CParticleLightInfo& GetDirectionalLight() const;
void SetDirectionalLight(const CParticleLightInfo& info);
private:
void AddLightColor(
Vector const* pPos,
Vector const* pLightPos,
Vector const* pLightColor,
float flLightIntensity,
Vector* pOutColor);
inline void ClampColor(Vector& vColor);
private:
int m_iLastTickStartRenderCalled;
CParticleMgr* m_pParticleMgr;
Vector m_vBaseColor;
CParticleLightInfo m_AmbientLight;
CParticleLightInfo m_DirectionalLight;
bool m_bUsingPixelShaders;
};
inline void CParticleSphereRenderer::AddLightColor(
Vector const* pPos,
Vector const* pLightPos,
Vector const* pLightColor,
float flLightIntensity,
Vector* pOutColor)
{
if (flLightIntensity)
{
float fDist = pPos->DistToSqr(*pLightPos);
float fAmt;
if (fDist > 0.0001f)
fAmt = flLightIntensity / fDist;
else
fAmt = 1000.f;
*pOutColor += *pLightColor * fAmt;
}
}
inline void CParticleSphereRenderer::ClampColor(Vector& vColor)
{
float flMax = MAX(vColor.x, MAX(vColor.y, vColor.z));
if (flMax > 1)
{
vColor *= 255.0f / flMax;
}
else
{
vColor *= 255.0;
}
}
inline const Vector& CParticleSphereRenderer::GetBaseColor() const
{
return m_vBaseColor;
}
inline void CParticleSphereRenderer::SetBaseColor(const Vector& vColor)
{
m_vBaseColor = vColor;
}
inline const CParticleLightInfo& CParticleSphereRenderer::GetAmbientLight() const
{
return m_AmbientLight;
}
inline void CParticleSphereRenderer::SetAmbientLight(const CParticleLightInfo& info)
{
m_AmbientLight = info;
}
inline const CParticleLightInfo& CParticleSphereRenderer::GetDirectionalLight() const
{
return m_DirectionalLight;
}
inline void CParticleSphereRenderer::SetDirectionalLight(const CParticleLightInfo& info)
{
m_DirectionalLight = info;
}
inline void CParticleSphereRenderer::RenderParticle(
ParticleDraw* pDraw,
const Vector& vOriginalPos,
const Vector& vTransformedPos,
float flAlpha,
float flParticleSize,
float flAngle)
{
#ifdef _DEBUG
if (pDraw->GetMeshBuilder())
{
Assert(m_iLastTickStartRenderCalled == gpGlobals->tickcount);
}
#endif
Vector vColor = m_vBaseColor;
AddLightColor(&vOriginalPos, &m_AmbientLight.m_vPos, &m_AmbientLight.m_vColor, m_AmbientLight.m_flIntensity, &vColor);
if (!m_bUsingPixelShaders)
{
AddLightColor(&vOriginalPos, &m_DirectionalLight.m_vPos, &m_DirectionalLight.m_vColor, m_DirectionalLight.m_flIntensity, &vColor);
}
ClampColor(vColor);
RenderParticle_Color255SizeNormalAngle(
pDraw,
vTransformedPos,
vColor,
flAlpha,
flParticleSize,
vec3_origin,
flAngle);
}
inline void CParticleSphereRenderer::RenderParticle_AddColor(
ParticleDraw* pDraw,
const Vector& vOriginalPos,
const Vector& vTransformedPos,
float flAlpha,
float flParticleSize,
const Vector& vToAdd0to1
)
{
#ifdef _DEBUG
if (pDraw->GetMeshBuilder())
{
Assert(m_iLastTickStartRenderCalled == gpGlobals->tickcount);
}
#endif
Vector vColor = m_vBaseColor + vToAdd0to1;
AddLightColor(&vOriginalPos, &m_AmbientLight.m_vPos, &m_AmbientLight.m_vColor, m_AmbientLight.m_flIntensity, &vColor);
if (!m_bUsingPixelShaders)
{
AddLightColor(&vOriginalPos, &m_DirectionalLight.m_vPos, &m_DirectionalLight.m_vColor, m_DirectionalLight.m_flIntensity, &vColor);
}
ClampColor(vColor);
RenderParticle_Color255Size(
pDraw,
vTransformedPos,
vColor,
flAlpha,
flParticleSize);
}
#endif

76
SpyCustom/PatternScan.cpp Normal file
View File

@ -0,0 +1,76 @@
#include "PatternScan.hpp"
DWORD WaitOnModuleHandle(std::string moduleName)
{
DWORD ModuleHandle = NULL;
while (!ModuleHandle)
{
ModuleHandle = (DWORD)GetModuleHandle(moduleName.c_str());
if (!ModuleHandle)
Sleep(50);
}
return ModuleHandle;
}
DWORD FindPatternV2(std::string moduleName, std::string pattern)
{
const char* pat = pattern.c_str();
DWORD firstMatch = 0;
DWORD rangeStart = (DWORD)GetModuleHandleA(moduleName.c_str());
MODULEINFO miModInfo; GetModuleInformation(GetCurrentProcess(), (HMODULE)rangeStart, &miModInfo, sizeof(MODULEINFO));
DWORD rangeEnd = rangeStart + miModInfo.SizeOfImage;
for (DWORD pCur = rangeStart; pCur < rangeEnd; pCur++)
{
if (!*pat)
return firstMatch;
if (*(PBYTE)pat == '\?' || *(BYTE*)pCur == getByte(pat))
{
if (!firstMatch)
firstMatch = pCur;
if (!pat[2])
return firstMatch;
if (*(PWORD)pat == '\?\?' || *(PBYTE)pat != '\?')
pat += 3;
else
pat += 2;
}
else
{
pat = pattern.c_str();
firstMatch = 0;
}
}
return NULL;
}
bool bCompare(const BYTE* Data, const BYTE* Mask, const char* szMask)
{
for (; *szMask; ++szMask, ++Mask, ++Data)
{
if (*szMask == 'x' && *Mask != *Data)
{
return false;
}
}
return (*szMask) == 0;
}
DWORD FindPattern(std::string moduleName, BYTE* Mask, char* szMask)
{
DWORD Address = WaitOnModuleHandle(moduleName.c_str());
MODULEINFO ModInfo; GetModuleInformation(GetCurrentProcess(), (HMODULE)Address, &ModInfo, sizeof(MODULEINFO));
DWORD Length = ModInfo.SizeOfImage;
for (DWORD c = 0; c < Length; c += 1)
{
if (bCompare((BYTE*)(Address + c), Mask, szMask))
{
return (DWORD)(Address + c);
}
}
return 0;
}

20
SpyCustom/PatternScan.hpp Normal file
View File

@ -0,0 +1,20 @@
#ifndef PATTERNSCAN
#define PATTERNSCAN
#pragma once
#include <Windows.h>
#include <Psapi.h>
#include <string>
#define INRANGE(x,a,b) (x >= a && x <= b)
#define getBits( x ) (INRANGE((x&(~0x20)),'A','F') ? ((x&(~0x20)) - 'A' + 0xa) : (INRANGE(x,'0','9') ? x - '0' : 0))
#define getByte( x ) (getBits(x[0]) << 4 | getBits(x[1]))
DWORD WaitOnModuleHandle(std::string moduleName);
DWORD FindPatternV2(std::string moduleName, std::string pattern);
bool bCompare(const BYTE* Data, const BYTE* Mask, const char* szMask);
DWORD FindPattern(std::string moduleName, BYTE* Mask, char* szMask);
#endif

View File

@ -0,0 +1,207 @@
#include "PlayerInventory.hpp"
void CSharedObjectTypeCache::AddObject(void* obj)
{
typedef void(__thiscall* tOriginal)(void*, void*);
getvfunc<tOriginal>(this, 1)(this, obj);
}
void CSharedObjectTypeCache::RemoveObject(void* obj)
{
typedef void(__thiscall* tOriginal)(void*, void*);
getvfunc<tOriginal>(this, 3)(this, obj);
}
std::vector<CEconItem*> CSharedObjectTypeCache::GetEconItems()
{
std::vector<CEconItem*> ret;
auto size = *reinterpret_cast<size_t*>(this + 0x18);
auto data = *reinterpret_cast<uintptr_t**>(this + 0x4);
for (size_t i = 0; i < size; i++)
ret.push_back(reinterpret_cast<CEconItem*>(data[i]));
return ret;
}
template<typename TYPE>
void CEconItem::SetAttributeValue(int index, TYPE val)
{
auto v15 = (DWORD*)GetItemSchema();
auto v16 = *(DWORD*)(v15[72] + 4 * index);
static auto fnSetDynamicAttributeValue
= reinterpret_cast<int(__thiscall*)(CEconItem*, DWORD, void*)>(
FindPatternV2("client.dll", "55 8B EC 83 E4 F8 83 EC 3C 53 8B 5D 08 56 57 6A 00")
);
fnSetDynamicAttributeValue(this, v16, &val);
}
int C_EconItemDefinition::get_equipped_position()
{
return *reinterpret_cast<int*>(reinterpret_cast<uintptr_t>(this) + 0x24C);
}
const char* C_EconItemDefinition::get_world_model_name()
{
return *reinterpret_cast<const char**>(uintptr_t(this) + 0x9C);
}
uint32_t* CEconItem::GetAccountID()
{
return reinterpret_cast<uint32_t*>(this + 0x1C);
}
uint64_t* CEconItem::GetItemID()
{
return reinterpret_cast<uint64_t*>(this + 0x8);
}
uint64_t* CEconItem::GetOriginalID()
{
return reinterpret_cast<uint64_t*>(this + 0x10);
}
uint16_t* CEconItem::GetDefIndex()
{
return reinterpret_cast<uint16_t*>(this + 0x24);
}
uint32_t* CEconItem::GetInventory()
{
return reinterpret_cast<uint32_t*>(this + 0x20);
}
unsigned char* CEconItem::GetFlags()
{
return reinterpret_cast<unsigned char*>(this + 0x30);
}
unsigned short* CEconItem::GetEconItemData()
{
return reinterpret_cast<unsigned short*>(this + 0x26);
}
C_EconItemDefinition* C_EconItemView::get_static_data()
{
static auto fn = reinterpret_cast<C_EconItemDefinition * (__thiscall*)(void*)>(FindPatternV2("client.dll", "55 8B EC 51 53 8B D9 8B ? ? ? ? ? 56 57 8B ? ? ? ? ? 85 FF 74 16"));
return fn(this);
}
CEconItem* C_EconItemView::get_soc_data()
{
static auto fn = reinterpret_cast<CEconItem * (__thiscall*)(C_EconItemView*)>(FindPatternV2("client.dll", "55 8B EC 83 E4 F0 83 EC 18 56 8B F1 57 8B 86"));
return fn(this);
}
void CPlayerInventory::RemoveItem(uint64_t ID)
{
static auto fnRemoveItem
= reinterpret_cast<int(__thiscall*)(void*, int64_t)>(
FindPatternV2("client.dll", "55 8B EC 83 E4 F8 56 57 FF 75 0C 8B F1")
);
fnRemoveItem(this, ID);
}
CSharedObjectTypeCache* CPlayerInventory::GetBaseTypeCache()
{
static auto fnGCSDK_CGCClient_FindSOCache
= reinterpret_cast<uintptr_t(__thiscall*)(uintptr_t, uint64_t, uint64_t, bool)>(
FindPatternV2("client.dll", "55 8B EC 83 E4 F8 83 EC 1C 0F 10 45 08")
);
static auto fnGCSDK_CSharedObjectCache_CreateBaseTypeCache
= reinterpret_cast<CSharedObjectTypeCache * (__thiscall*)(uintptr_t, int)>(
FindPatternV2("client.dll", "55 8B EC 51 53 56 8B D9 8D 45 08")
);
static auto g_GCClientSystem = **reinterpret_cast<uintptr_t**>(FindPatternV2("client.dll", "8B 0D ? ? ? ? 6A 00 83 EC 10") + 0x2);
auto SOCahce = fnGCSDK_CGCClient_FindSOCache(g_GCClientSystem + 0x60, *reinterpret_cast<uint64_t*>(this + 0x8), *reinterpret_cast<uint64_t*>(this + 0x10), 0);
return fnGCSDK_CSharedObjectCache_CreateBaseTypeCache(SOCahce, 1);
}
void CPlayerInventory::RemoveItem(CEconItem* item)
{
RemoveItem(*item->GetItemID());
GetBaseTypeCache()->RemoveObject(item);
}
void CPlayerInventory::ClearInventory()
{
auto BaseTypeCache = this->GetBaseTypeCache();
auto items = BaseTypeCache->GetEconItems();
for (auto item : items)
{
RemoveItem(*item->GetItemID());
BaseTypeCache->RemoveObject(item);
}
}
uint32_t CPlayerInventory::GetSteamID()
{
return *reinterpret_cast<uint32_t*>(this + 0x8);
}
CUtlVector< C_EconItemView* >* CPlayerInventory::GetInventoryItems()
{
return reinterpret_cast<CUtlVector<C_EconItemView*>*>(this + 0x2C);
}
bool CPlayerInventory::AddEconItem(CEconItem* item, int a3, int a4, char a5)
{
static auto fnAddEconItem
= reinterpret_cast<C_EconItemView * (__thiscall*)(void*, CEconItem*, int, int, char)>(
FindPatternV2("client.dll", "55 8B EC 83 E4 F8 A1 ? ? ? ? 83 EC 14 53 56 57 8B F9 8B 08")
);
GetBaseTypeCache()->AddObject(item);
auto ret = fnAddEconItem(this, item, a3, a4, a5);
return ret;
}
CPlayerInventory* CSInventoryManager::GetLocalPlayerInventory()
{
static auto local_inventory_offset = *reinterpret_cast<uintptr_t*>(FindPatternV2("client.dll", "8B 8B ? ? ? ? E8 ? ? ? ? 89 44 24 18") + 0x2);
return *reinterpret_cast<CPlayerInventory**>(this + local_inventory_offset);
}
CEconItem* CreateEconItem()
{
static auto fnCreateSharedObjectSubclass_EconItem_
= reinterpret_cast<CEconItem * (__stdcall*)()>(
*reinterpret_cast<uintptr_t*>(FindPatternV2("client.dll", "C7 45 ? ? ? ? ? C7 45 ? ? ? ? ? C7 45 ? ? ? ? ? C7 45 ? ? ? ? ? C7 45 ? ? ? ? ? C7 45 ? ? ? ? ? E8 ? ? ? ? 83 F8 FF 75 09 8D 45 E4 50 E8 ? ? ? ? 8D 45 E4 C7 45 ? ? ? ? ? 50 C7 45 ? ? ? ? ? C7 45 ? ? ? ? ? C7 45 ? ? ? ? ? C7 45 ? ? ? ? ? C7 45 ? ? ? ? ? C7 45 ? ? ? ? ? E8 ? ? ? ? 83 F8 FF 75 09 8D 45 E4 50 E8 ? ? ? ? 8D 45 E4 C7 45 ? ? ? ? ? 50 C7 45 ? ? ? ? ? C7 45 ? ? ? ? ? C7 45 ? ? ? ? ? C7 45 ? ? ? ? ? C7 45 ? ? ? ? ? C7 45 ? ? ? ? ? E8 ? ? ? ? 83 F8 FF 75 09 8D 45 E4 50 E8 ? ? ? ? 8D 45 E4 C7 45 ? ? ? ? ? 50 C7 45 ? ? ? ? ? C7 45 ? ? ? ? ? C7 45 ? ? ? ? ? C7 45 ? ? ? ? ? C7 45 ? ? ? ? ? C7 45 ? ? ? ? ? E8 ? ? ? ? 83 F8 FF 75 09 8D 45 E4 50 E8 ? ? ? ? 8D 45 E4") + 3)
);
return fnCreateSharedObjectSubclass_EconItem_();
}
uintptr_t GetItemSchema()
{
static auto fnGetItemSchema
= reinterpret_cast<uintptr_t(__stdcall*)()>(
FindPatternV2("client.dll", "A1 ? ? ? ? 85 C0 75 53")
);
return fnGetItemSchema();
}

View File

@ -0,0 +1,138 @@
#ifndef PLAYERINV
#define PLAYERINV
#pragma once
#include "PatternScan.hpp"
#include "Interfaces.hpp"
#include "utlvector.h"
#include "stdint.h"
#include <vector>
#include "icliententity.h"
enum ItemQuality
{
ITEM_QUALITY_DEFAULT,
ITEM_QUALITY_GENUINE,
ITEM_QUALITY_VINTAGE,
ITEM_QUALITY_UNUSUAL,
ITEM_QUALITY_SKIN,
ITEM_QUALITY_COMMUNITY,
ITEM_QUALITY_DEVELOPER,
ITEM_QUALITY_SELFMADE,
ITEM_QUALITY_CUSTOMIZED,
ITEM_QUALITY_STRANGE,
ITEM_QUALITY_COMPLETED,
ITEM_QUALITY_UNK2,
ITEM_QUALITY_TOURNAMENT
};
enum ItemRarity
{
ITEM_RARITY_DEFAULT,
ITEM_RARITY_COMMON,
ITEM_RARITY_UNCOMMON,
ITEM_RARITY_RARE,
ITEM_RARITY_MYTHICAL,
ITEM_RARITY_LEGENDARY,
ITEM_RARITY_ANCIENT,
ITEM_RARITY_IMMORTAL
};
class CEconItem
{
unsigned short* GetEconItemData();
void UpdateEquippedState(unsigned int state);
public:
uint32_t* GetInventory();
uint32_t* GetAccountID();
uint16_t* GetDefIndex();
uint64_t* GetItemID();
uint64_t* GetOriginalID();
unsigned char* GetFlags();
void SetQuality(ItemQuality quality);
void SetRarity(ItemRarity rarity);
void SetOrigin(int origin);
void SetLevel(int level);
void SetInUse(bool in_use);
void SetCustomName(const char* name);
void SetCustomDesc(const char* name);
void SetPaintSeed(float seed);
void SetPaintKit(float kit);
void SetPaintWear(float wear);
void SetStatTrak(int val);
void AddSticker(int index, int kit, float wear, float scale, float rotation);
template<typename TYPE>
void SetAttributeValue(int index, TYPE val);
};
class C_EconItemDefinition
{
public:
int get_equipped_position();
const char* get_world_model_name();
};
class C_EconItemView
{
private:
using str_32 = char[32];
public:
int32_t m_bInitialized;
int16_t m_iItemDefinitionIndex;
int32_t m_iEntityLevel;
int32_t m_iAccountID;
int32_t m_iItemIDLow;
int32_t m_iItemIDHigh;
int32_t m_iEntityQuality;
str_32 m_iCustomName;
CUtlVector<IRefCounted*>& m_CustomMaterials();
CUtlVector<IRefCounted*>& m_VisualsDataProcessors();
C_EconItemDefinition* get_static_data();
CEconItem* get_soc_data();
};
class CSharedObjectTypeCache
{
public:
void AddObject(void* obj);
void RemoveObject(void* obj);
std::vector<CEconItem*> GetEconItems();
};
class CPlayerInventory
{
public:
void RemoveItem(uint64_t ID);
void RemoveItem(CEconItem* item);
void ClearInventory();
CSharedObjectTypeCache* GetBaseTypeCache();
uint32_t GetSteamID();
CUtlVector<C_EconItemView*>* GetInventoryItems();
bool AddEconItem(CEconItem* item, int a3, int a4, char a5);
};
class CSInventoryManager
{
public:
CPlayerInventory* GetLocalPlayerInventory();
};
uintptr_t GetItemSchema();
CEconItem* CreateEconItem();
#endif

581
SpyCustom/ProtoParse.h Normal file
View File

@ -0,0 +1,581 @@
#pragma once
#include <cstdint>
#include <string>
#include <vector>
#define MAKE_TAG(FIELD_NUMBER, TYPE) static_cast<uint32_t>(((FIELD_NUMBER) << kTagTypeBits) | (TYPE))
#define make_struct(_name_, _size_) \
struct _name_ : ProtoWriter { \
constexpr static size_t MAX_FIELD = _size_; \
_name_() : ProtoWriter(MAX_FIELD) {} \
_name_(void* data, size_t size) : ProtoWriter(data, size, MAX_FIELD) {} \
_name_(std::string data) : ProtoWriter(data, MAX_FIELD) {}
#define make_field(_name_, _id_, _type_) \
constexpr static Tag _name_ = { _id_, _type_ }; \
void clear_##_name_() { this->clear(_name_); } \
bool has_##_name_() { return this->has(_name_); } \
Field get_##_name_() { return this->get(_name_); } \
std::vector<Field> getAll_##_name_() { return this->getAll(_name_); } \
\
void add_##_name_(std::string v) { this->add(_name_, v); } \
template<typename T> void add_##_name_(T v) { this->add(_name_, v); } \
void replace_##_name_(std::string v) { this->replace(_name_, v); } \
void replace_##_name_(std::string v, uint32_t index) { this->replace(_name_, v, index); } \
template<typename T> void replace_##_name_(T v) { this->replace(_name_, v); } \
template<typename T> void replace_##_name_(T v, uint32_t index) { this->replace(_name_, v, index); } \
template<class T> T get_##_name_() { return std::move( T(this->get(_name_).String()) ); }
struct Tag
{
unsigned field;
unsigned type;
};
enum FieldType {
TYPE_DOUBLE = 1,
TYPE_FLOAT = 2,
TYPE_INT64 = 3,
TYPE_UINT64 = 4,
TYPE_INT32 = 5,
TYPE_FIXED64 = 6,
TYPE_FIXED32 = 7,
TYPE_BOOL = 8,
TYPE_STRING = 9,
TYPE_GROUP = 10,
TYPE_MESSAGE = 11,
TYPE_BYTES = 12,
TYPE_UINT32 = 13,
TYPE_ENUM = 14,
TYPE_SFIXED32 = 15,
TYPE_SFIXED64 = 16,
TYPE_SINT32 = 17,
TYPE_SINT64 = 18,
MAX_FIELD_TYPE = 18,
};
struct Field
{
friend class ProtoWriter;
public:
inline Field& operator=(const Field& f);
Field() : tag({ 0,0 }), value(""), full("") { }
Field(unsigned field, unsigned type, std::string value, std::string full);
Field(Tag tag, std::string value);
Field(unsigned field, unsigned type, std::string value);
template<typename T>
Field(Tag tag, T value);
template<typename T>
Field(unsigned field, unsigned type, T value);
public:
static Field ReadField(void* data, size_t& bytesRead);
public:
inline float Float();
inline double Double();
inline int32_t Int32();
inline int64_t Int64();
inline uint32_t UInt32();
inline uint64_t UInt64();
inline uint32_t Fixed32();
inline uint64_t Fixed64();
inline int32_t SFixed32();
inline int64_t SFixed64();
inline bool Bool();
inline std::string String();
private:
Tag tag;
std::string value;
std::string full;
static std::string getBytesVarint32(uint32_t value);
static std::string getBytesVarint64(uint64_t value);
static uint32_t readVarUint32(void* data, size_t& bytesRead);
static uint64_t readVarUint64(void* data, size_t& bytesRead);
enum WireType {
WIRETYPE_VARINT = 0,
WIRETYPE_FIXED64 = 1,
WIRETYPE_LENGTH_DELIMITED = 2,
WIRETYPE_START_GROUP = 3,
WIRETYPE_END_GROUP = 4,
WIRETYPE_FIXED32 = 5,
};
constexpr static WireType kWireTypeForFieldType[MAX_FIELD_TYPE + 1] = {
static_cast<WireType>(-1),
WIRETYPE_FIXED64,
WIRETYPE_FIXED32,
WIRETYPE_VARINT,
WIRETYPE_VARINT,
WIRETYPE_VARINT,
WIRETYPE_FIXED64,
WIRETYPE_FIXED32,
WIRETYPE_VARINT,
WIRETYPE_LENGTH_DELIMITED,
WIRETYPE_START_GROUP,
WIRETYPE_LENGTH_DELIMITED,
WIRETYPE_LENGTH_DELIMITED,
WIRETYPE_VARINT,
WIRETYPE_VARINT,
WIRETYPE_FIXED32,
WIRETYPE_FIXED64,
WIRETYPE_VARINT,
WIRETYPE_VARINT,
};
constexpr static int kTagTypeBits = 3;
constexpr static uint32_t kTagTypeMask = (1 << kTagTypeBits) - 1;
constexpr static int kMaxVarintBytes = 10;
constexpr static int kMaxVarint32Bytes = 5;
};
class ProtoWriter
{
public:
inline ProtoWriter();
inline ProtoWriter(size_t maxFields);
inline ProtoWriter(void* data, size_t size, size_t maxFields);
inline ProtoWriter(std::string dataStr, size_t maxFields);
public:
inline void add(Field field);
inline void replace(Field field);
inline void replace(Field field, uint32_t index);
inline void clear(unsigned fieldId);
inline bool has(unsigned fieldId);
inline Field get(unsigned fieldId);
inline std::vector<Field> getAll(unsigned fieldId);
public:
inline void add(Tag tag, std::string value);
inline void replace(Tag tag, std::string value);
inline void replace(Tag tag, std::string value, uint32_t index);
inline void clear(Tag tag);
inline bool has(Tag tag);
inline Field get(Tag tag);
inline std::vector<Field> getAll(Tag tag);
template<typename T>
inline void add(Tag tag, T value);
template<typename T>
inline void replace(Tag tag, T value);
template<typename T>
inline void replace(Tag tag, T value, uint32_t index);
std::string serialize();
void print();
private:
std::vector<std::vector<Field>> fields;
};
#pragma region Helper Functions
std::string Field::getBytesVarint32(uint32_t value)
{
uint8_t bytes[kMaxVarint32Bytes];
int size = 0;
while (value > 0x7F) {
bytes[size++] = (static_cast<uint8_t>(value) & 0x7F) | 0x80;
value >>= 7;
}
bytes[size++] = static_cast<uint8_t>(value) & 0x7F;
return std::string{ reinterpret_cast<const char*>(&bytes[0]), (size_t)size };
}
std::string Field::getBytesVarint64(uint64_t value)
{
uint8_t bytes[kMaxVarintBytes];
int size = 0;
while (value > 0x7F) {
bytes[size++] = (static_cast<uint8_t>(value) & 0x7F) | 0x80;
value >>= 7;
}
bytes[size++] = static_cast<uint8_t>(value) & 0x7F;
return std::string{ reinterpret_cast<const char*>(&bytes[0]), (size_t)size };
}
uint32_t Field::readVarUint32(void* data, size_t& bytesRead)
{
auto ptr = reinterpret_cast<const uint8_t*>(data);
auto value = 0u;
auto bytes = 0u;
do {
value |= static_cast<uint32_t>(*ptr & 0x7f) << (7 * bytes);
bytes++;
} while (*(ptr++) & 0x80 && bytes <= 5);
bytesRead = bytes;
return value;
}
uint64_t Field::readVarUint64(void* data, size_t& bytesRead)
{
auto ptr = reinterpret_cast<const uint8_t*>(data);
auto value = 0ull;
auto bytes = 0u;
do
{
value |= static_cast<uint64_t>(*ptr & 0x7f) << (7 * bytes);
bytes++;
} while (*(ptr++) & 0x80 && bytes <= 10);
bytesRead = bytes;
return value;
}
Field Field::ReadField(void* data, size_t& bytesRead)
{
unsigned field = *reinterpret_cast<uint16_t*>(data);
unsigned type = field & kTagTypeMask;
if (field == 0xffff) {
bytesRead = 0;
return Field();
}
if (field & 0x80) {
field = ((field & 0x7f) | ((field & 0xff00) >> 1)) >> kTagTypeBits;
bytesRead = 2;
}
else {
field = (field & 0xff) >> kTagTypeBits;
bytesRead = 1;
}
size_t length, sizeDelimited;
std::string value, full;
switch (type)
{
case WIRETYPE_VARINT:
readVarUint64((void*)((ptrdiff_t)data + bytesRead), length);
value = std::string{ reinterpret_cast<const char*>((void*)((ptrdiff_t)data + bytesRead)), length };
full = std::string{ reinterpret_cast<const char*>(data), bytesRead + length };
bytesRead += length;
break;
case WIRETYPE_FIXED64:
value = std::string{ reinterpret_cast<const char*>((void*)((ptrdiff_t)data + bytesRead)), 8 };
full = std::string{ reinterpret_cast<const char*>(data), bytesRead + 8 };
bytesRead += 8;
break;
case WIRETYPE_LENGTH_DELIMITED:
sizeDelimited = readVarUint32((void*)((ptrdiff_t)data + bytesRead), length);
value = std::string{ reinterpret_cast<const char*>((void*)((ptrdiff_t)data + bytesRead)), length + sizeDelimited };
full = std::string{ reinterpret_cast<const char*>(data), bytesRead + length + sizeDelimited };
bytesRead += length + sizeDelimited;
break;
case WIRETYPE_START_GROUP:
throw("WIRETYPE_START_GROUP unrealised");
break;
case WIRETYPE_END_GROUP:
throw("WIRETYPE_END_GROUP unrealised");
break;
case WIRETYPE_FIXED32:
value = std::string{ reinterpret_cast<const char*>((void*)((ptrdiff_t)data + bytesRead)), 4 };
full = std::string{ reinterpret_cast<const char*>(data), bytesRead + 4 };
bytesRead += 4;
break;
default:
throw("Unknown type %i", type);
break;
}
return Field(field, type, value, full);
}
#pragma endregion
#pragma region Field Definition
Field& Field::operator=(const Field& f) {
this->tag = f.tag;
this->value = f.value;
this->full = f.full;
return *this;
}
Field::Field(unsigned field, unsigned type, std::string value, std::string full) {
this->tag = { field, type };
this->value = value;
this->full = full;
}
template<typename T>
Field::Field(Tag tag, T value) {
auto wireType = kWireTypeForFieldType[tag.type];
full = getBytesVarint32(MAKE_TAG(tag.field, wireType));
switch (wireType) {
case WIRETYPE_VARINT:
full += getBytesVarint64(static_cast<uint64_t>(value));
break;
case WIRETYPE_FIXED32:
full += std::string{ reinterpret_cast<const char*>(&value), 4 };
break;
case WIRETYPE_FIXED64:
full += std::string{ reinterpret_cast<const char*>(&value), 8 };
break;
}
}
template<typename T>
Field::Field(unsigned field, unsigned type, T value) {
auto wireType = kWireTypeForFieldType[type];
tag = { field, (unsigned)wireType };
full = getBytesVarint32(MAKE_TAG(field, wireType));
switch (wireType) {
case WIRETYPE_VARINT:
full += getBytesVarint64(static_cast<uint64_t>(value));
break;
case WIRETYPE_FIXED32:
full += std::string{ reinterpret_cast<const char*>(&value), 4 };
break;
case WIRETYPE_FIXED64:
full += std::string{ reinterpret_cast<const char*>(&value), 8 };
break;
}
}
Field::Field(Tag tag, std::string value) {
auto wireType = kWireTypeForFieldType[tag.type];
full = getBytesVarint32(MAKE_TAG(tag.field, wireType));
full += getBytesVarint32(value.size());
full += value;
}
Field::Field(unsigned field, unsigned type, std::string value) {
auto wireType = kWireTypeForFieldType[type];
tag = { field, (unsigned)wireType };
full = getBytesVarint32(MAKE_TAG(field, wireType));
full += getBytesVarint32(value.size());
full += value;
}
float Field::Float() {
return *reinterpret_cast<float*>((void*)value.data());
}
double Field::Double() {
return *reinterpret_cast<double*>((void*)value.data());
}
int32_t Field::Int32() {
size_t bytesRead;
return static_cast<int32_t>(readVarUint64((void*)value.data(), bytesRead));
}
int64_t Field::Int64() {
size_t bytesRead;
return readVarUint64((void*)value.data(), bytesRead);
}
uint32_t Field::UInt32() {
size_t bytesRead;
return readVarUint32((void*)value.data(), bytesRead);
}
uint64_t Field::UInt64() {
size_t bytesRead;
return readVarUint64((void*)value.data(), bytesRead);
}
uint32_t Field::Fixed32() {
return *reinterpret_cast<uint32_t*>((void*)value.data());
}
uint64_t Field::Fixed64() {
return *reinterpret_cast<uint64_t*>((void*)value.data());
}
int32_t Field::SFixed32() {
return *reinterpret_cast<int32_t*>((void*)value.data());
}
int64_t Field::SFixed64() {
return *reinterpret_cast<int64_t*>((void*)value.data());
}
bool Field::Bool() {
size_t bytesRead;
return !!readVarUint32((void*)value.data(), bytesRead);
}
std::string Field::String()
{
size_t bytesRead;
void* data = (void*)value.data();
auto length = readVarUint32((void*)value.data(), bytesRead);
auto value = std::string{ reinterpret_cast<const char*>((void*)((ptrdiff_t)data + bytesRead)), length };
return value;
}
#pragma endregion
#pragma region ProtoWriter Definition
ProtoWriter::ProtoWriter()
{
}
ProtoWriter::ProtoWriter(size_t maxFields)
{
size_t vector_size = maxFields + 1;
fields.resize(vector_size);
fields.reserve(vector_size);
}
ProtoWriter::ProtoWriter(void* data, size_t size, size_t maxFields) : ProtoWriter(maxFields)
{
size_t vector_size = maxFields + 1,
pos = 0,
bytesRead;
if (data == nullptr)
return;
while (pos < size) {
auto field = Field::ReadField((void*)((ptrdiff_t)data + pos), bytesRead);
if (!bytesRead) break;
auto index = field.tag.field;
if (index >= vector_size) throw("fields range error: field[%i]", index);
fields[index].push_back(field);
pos += bytesRead;
}
}
ProtoWriter::ProtoWriter(std::string dataStr, size_t maxFields) : ProtoWriter((void*)dataStr.data(), dataStr.size(), maxFields)
{
}
std::string ProtoWriter::serialize()
{
std::string result;
for (auto& f0 : fields) {
for (auto& f1 : f0) {
result += f1.full;
}
}
return result;
}
void ProtoWriter::print()
{
auto data = serialize();
void* mem = (void*)data.data();
size_t size = data.size();
int j = 0;
for (size_t i = 0; i <= size; ++i) {
printf("%.2X ", *(unsigned char*)((uintptr_t)mem + i));
j++;
if (j == 16)
{
j = 0;
printf("\n");
}
}
printf("\n");
}
void ProtoWriter::add(Field field)
{
fields[field.tag.field].push_back(field);
}
void ProtoWriter::replace(Field field)
{
fields[field.tag.field].clear();
fields[field.tag.field].push_back(field);
}
void ProtoWriter::replace(Field field, uint32_t index)
{
fields[field.tag.field][index] = field;
}
void ProtoWriter::clear(unsigned fieldId)
{
return fields[fieldId].clear();
}
bool ProtoWriter::has(unsigned fieldId)
{
return fields[fieldId].size() > 0;
}
Field ProtoWriter::get(unsigned fieldId)
{
if (fields[fieldId].empty())
return Field();
return fields[fieldId][0];
}
std::vector<Field> ProtoWriter::getAll(unsigned fieldId)
{
return fields[fieldId];
}
template<typename T>
void ProtoWriter::add(Tag tag, T value)
{
fields[tag.field].push_back(Field(tag, value));
}
template<typename T>
void ProtoWriter::replace(Tag tag, T value)
{
fields[tag.field].clear();
fields[tag.field].push_back(Field(tag, value));
}
template<typename T>
void ProtoWriter::replace(Tag tag, T value, uint32_t index)
{
fields[tag.field][index] = Field(tag, value);
}
void ProtoWriter::add(Tag tag, std::string value)
{
fields[tag.field].push_back(Field(tag, value));
}
void ProtoWriter::replace(Tag tag, std::string value)
{
fields[tag.field].clear();
fields[tag.field].push_back(Field(tag, value));
}
void ProtoWriter::replace(Tag tag, std::string value, uint32_t index)
{
fields[tag.field][index] = Field(tag, value);
}
void ProtoWriter::clear(Tag tag)
{
return fields[tag.field].clear();
}
bool ProtoWriter::has(Tag tag)
{
return fields[tag.field].size() > 0;
}
Field ProtoWriter::get(Tag tag)
{
if (fields[tag.field].empty())
return Field();
return fields[tag.field][0];
}
std::vector<Field> ProtoWriter::getAll(Tag tag)
{
return fields[tag.field];
}
#pragma endregion

View File

@ -0,0 +1,105 @@
#pragma once
#include "pbwrap.hpp"
#define k_EMsgGCCStrike15_v2_MatchmakingGC2ClientReserve 9107
#define k_EMsgGCClientWelcome 4004
#define k_EMsgGCClientHello 4006
#define k_EMsgGCAdjustItemEquippedState 1059
#define k_EMsgGCCStrike15_v2_MatchmakingClient2GCHello 9109
#define k_EMsgGCCStrike15_v2_MatchmakingGC2ClientHello 9110
#define k_EMsgGCCStrike15_v2_ClientGCRankUpdate 9194
using namespace pbwrap;
struct CMsgClientHello : pbmsg<8> {
PBMSG_CTOR;
PBFIELD(3, types::Uint32, client_session_need);
};
struct MatchmakingGC2ClientHello : pbmsg<20> {
struct PlayerRankingInfo : pbmsg<6> {
PBMSG_CTOR;
PBFIELD(1, types::Uint32, account_id);
PBFIELD(2, types::Uint32, rank_id);
PBFIELD(3, types::Uint32, wins);
PBFIELD(6, types::Uint32, rank_type_id);
};
struct PlayerCommendationInfo : pbmsg<4> {
PBMSG_CTOR;
PBFIELD(1, types::Uint32, cmd_friendly);
PBFIELD(2, types::Uint32, cmd_teaching);
PBFIELD(4, types::Uint32, cmd_leader);
};
PBMSG_CTOR;
PBFIELD(7, PlayerRankingInfo, ranking);
PBFIELD(8, PlayerCommendationInfo, commendation);
PBFIELD(17, types::Int32, player_level);
PBFIELD(18, types::Int32, player_cur_xp);
PBFIELD(4, types::Uint32, penalty_seconds);
PBFIELD(5, types::Uint32, penalty_reason);
PBFIELD(6, types::Int32, vac_banned);
};
struct CMsgGCCStrike15_v2_ClientGCRankUpdate : pbmsg<1> {
PBMSG_CTOR;
PBFIELD(1, MatchmakingGC2ClientHello::PlayerRankingInfo, ranking);
};
struct CSOEconItemEquipped : pbmsg<2> {
PBMSG_CTOR;
PBFIELD(1, types::Int32, new_class);
PBFIELD(2, types::Int32, new_slot);
};
struct CSOEconItemAttribute : pbmsg<3> {
PBMSG_CTOR;
PBFIELD(1, types::Uint32, def_index);
PBFIELD(2, types::Uint32, value);
PBFIELD(3, types::Bytes, value_bytes);
};
struct CSOEconItem : pbmsg<19> {
PBMSG_CTOR;
PBFIELD(1, types::Uint64, id);
PBFIELD(2, types::Uint32, account_id);
PBFIELD(3, types::Uint32, inventory);
PBFIELD(4, types::Int32, def_index);
PBFIELD(5, types::Uint32, quantity);
PBFIELD(6, types::Uint32, level);
PBFIELD(7, types::Uint32, quality);
PBFIELD(8, types::Uint32, flags);
PBFIELD(9, types::Uint32, origin);
PBFIELD(10, types::String, custom_name);
PBFIELD(11, types::String, custom_desc);
PBFIELD(12, CSOEconItemAttribute, attribute);
PBFIELD(14, types::Bool, in_use);
PBFIELD(15, types::Uint32, style);
PBFIELD(16, types::Uint64, original_id);
PBFIELD(18, CSOEconItemEquipped, equipped_state);
PBFIELD(19, types::Uint32, rarity);
};
struct CMsgClientWelcome : pbmsg<11> {
struct SubscribedType : pbmsg<2> {
PBMSG_CTOR;
PBFIELD(1, types::Int32, type_id);
PBFIELD(2, CSOEconItem, object_data);
};
struct CMsgSOCacheSubscribed : pbmsg<4> {
PBMSG_CTOR;
PBFIELD(2, SubscribedType, objects);
};
PBMSG_CTOR;
PBFIELD(3, CMsgSOCacheSubscribed, outofdate_subscribed_caches);
};
struct CMsgAdjustItemEquippedState : pbmsg<4> {
PBMSG_CTOR;
PBFIELD(1, types::Uint64, item_id);
PBFIELD(2, types::Uint32, new_class);
PBFIELD(3, types::Uint32, new_slot);
PBFIELD(4, types::Bool, swap);
};

234
SpyCustom/RichText.h Normal file
View File

@ -0,0 +1,234 @@
#ifndef RICHTEXT_H
#define RICHTEXT_H
#ifdef _WIN32
#pragma once
#endif
#include "Panel.h"
#include "utlvector.h"
namespace vgui
{
class ClickPanel;
class RichText : public Panel
{
DECLARE_CLASS_SIMPLE(RichText, Panel);
public:
RichText(Panel* parent, const char* panelName);
~RichText();
virtual void SetText(const char* text);
virtual void SetText(const wchar_t* text);
void GetText(int offset, OUT_Z_BYTECAP(bufLenInBytes) wchar_t* buf, int bufLenInBytes);
void GetText(int offset, OUT_Z_BYTECAP(bufLenInBytes) char* pch, int bufLenInBytes);
void SetFont(HFont font);
void InsertChar(wchar_t ch);
void InsertString(const char* text);
void InsertString(const wchar_t* wszText);
void SelectNone();
void SelectAllText();
void SelectNoText();
MESSAGE_FUNC(CutSelected, "DoCutSelected");
MESSAGE_FUNC(CopySelected, "DoCopySelected");
void SetPanelInteractive(bool bInteractive) { m_bInteractive = bInteractive; }
void SetUnusedScrollbarInvisible(bool bInvis) { m_bUnusedScrollbarInvis = bInvis; }
void GotoTextStart();
void GotoTextEnd();
void SetVerticalScrollbar(bool state);
void SetMaximumCharCount(int maxChars);
void InsertColorChange(Color col);
void InsertIndentChange(int pixelsIndent);
void InsertClickableTextStart(const char* pchClickAction = NULL);
void InsertClickableTextEnd();
void InsertPossibleURLString(const char* text, Color URLTextColor, Color normalTextColor);
void InsertFade(float flSustain, float flLength);
void ResetAllFades(bool bHold, bool bOnlyExpired = false, float flNewSustain = -1.0f);
void SetToFullHeight();
int GetNumLines();
virtual bool RequestInfo(KeyValues* outputData);
virtual void SetFgColor(Color color);
virtual void SetDrawOffsets(int ofsx, int ofsy);
bool IsScrollbarVisible();
void SetURLClickedHandler(Panel* pPanelToHandleClickMsg);
void SetUnderlineFont(HFont font);
bool IsAllTextAlphaZero() const;
bool HasText() const;
void SetDrawTextOnly();
protected:
virtual void OnThink();
virtual void PerformLayout();
virtual void ApplySchemeSettings(IScheme* pScheme);
virtual void Paint();
virtual void ApplySettings(KeyValues* inResourceData);
virtual void GetSettings(KeyValues* outResourceData);
virtual const char* GetDescription(void);
MESSAGE_FUNC_WCHARPTR(OnSetText, "SetText", text);
MESSAGE_FUNC(OnSliderMoved, "ScrollBarSliderMoved");
virtual void OnKillFocus();
virtual void OnMouseWheeled(int delta);
virtual void OnKeyCodeTyped(KeyCode code);
MESSAGE_FUNC_INT(OnClickPanel, "ClickPanel", index);
virtual void OnCursorMoved(int x, int y);
virtual void OnMousePressed(MouseCode code);
virtual void OnMouseDoublePressed(MouseCode code);
virtual void OnMouseReleased(MouseCode code);
virtual void OnMouseFocusTicked();
virtual void OnCursorEntered();
virtual void OnCursorExited();
virtual void OnMouseCaptureLost();
virtual void OnSizeChanged(int newWide, int newTall);
virtual void OnSetFocus();
int ParseTextStringForUrls(const char* text, int startPos, char* pchURLText, int cchURLText, char* pchURL, int cchURL, bool& clickable);
virtual void OnTextClicked(const wchar_t* text);
#ifdef DBGFLAG_VALIDATE
virtual void Validate(CValidator& validator, char* pchName);
#endif
protected:
ScrollBar* _vertScrollBar;
private:
int GetLineHeight();
HFont GetDefaultFont();
const wchar_t* ResolveLocalizedTextAndVariables(char const* pchLookup, OUT_Z_BYTECAP(outbufsizeinbytes) wchar_t* outbuf, size_t outbufsizeinbytes);
void CheckRecalcLineBreaks();
void GotoWordRight();
void GotoWordLeft();
void TruncateTextStream();
bool GetSelectedRange(int& cx0, int& cx1);
void CursorToPixelSpace(int cursorPos, int& cx, int& cy);
int PixelToCursorSpace(int cx, int cy);
void AddAnotherLine(int& cx, int& cy);
void RecalculateDefaultState(int startIndex);
void LayoutVerticalScrollBarSlider();
void OpenEditMenu();
void FinishingURL(int x, int y);
int GetStartDrawIndex(int& lineBreakIndexIndex);
int GetCursorLine();
int GetClickableTextIndexStart(int startIndex);
void CreateEditMenu();
MESSAGE_FUNC_INT(MoveScrollBar, "MoveScrollBar", delta);
MESSAGE_FUNC_INT(MoveScrollBarDirect, "MoveScrollBarDirect", delta);
void InvalidateLineBreakStream();
void RecalculateLineBreaks();
struct TFade
{
float flFadeStartTime;
float flFadeLength;
float flFadeSustain;
int iOriginalAlpha;
};
struct TFormatStream
{
Color color;
int pixelsIndent;
bool textClickable;
CUtlSymbol m_sClickableTextAction;
TFade fade;
int textStreamIndex;
};
bool m_bResetFades;
bool m_bInteractive;
bool m_bUnusedScrollbarInvis;
bool m_bAllTextAlphaIsZero;
CUtlVector<wchar_t> m_TextStream;
CUtlVector<int> m_LineBreaks;
CUtlVector<TFormatStream> m_FormatStream;
bool m_bRecalcLineBreaks;
int _recalculateBreaksIndex;
bool _invalidateVerticalScrollbarSlider;
int _cursorPos;
bool _mouseSelection;
bool _mouseDragSelection;
int _select[2];
int _pixelsIndent;
int _maxCharCount;
HFont _font;
HFont m_hFontUnderline;
Color _selectionColor;
Color _selectionTextColor;
bool _currentTextClickable;
CUtlVector<ClickPanel*> _clickableTextPanels;
int _clickableTextIndex;
Color _defaultTextColor;
int _drawOffsetX;
int _drawOffsetY;
Panel* m_pInterior;
PHandle m_hPanelToHandleClickingURLs;
Menu* m_pEditMenu;
char* m_pszInitialText;
bool _recalcSavedRenderState;
struct TRenderState
{
int x, y;
Color textColor;
int pixelsIndent;
bool textClickable;
int formatStreamIndex;
};
TRenderState m_CachedRenderState;
bool UpdateRenderState(int textStreamPos, TRenderState& renderState);
void CalculateFade(TRenderState& renderState);
void GenerateRenderStateForTextStreamIndex(int textStreamIndex, TRenderState& renderState);
int FindFormatStreamIndexForTextStreamPos(int textStreamIndex);
int DrawString(int iFirst, int iLast, TRenderState& renderState, HFont font);
};
}
#endif

View File

@ -0,0 +1,44 @@
#ifndef IVDEBUGOVERLAY_H
#define IVDEBUGOVERLAY_H
#ifdef _WIN32
#pragma once
#endif
class Vector;
#define VDEBUG_OVERLAY_INTERFACE_VERSION "VDebugOverlay003"
#define NDEBUG_PERSIST_TILL_NEXT_SERVER (0.0f)
class OverlayText_t;
abstract_class IVDebugOverlay
{
public:
virtual void __unkn() = 0;
virtual void AddEntityTextOverlay(int ent_index, int line_offset, float duration, int r, int g, int b, int a, const char* format, ...) = 0;
virtual void AddBoxOverlay(const Vector& origin, const Vector& mins, const Vector& max, Vector const& orientation, int r, int g, int b, int a, float duration) = 0;
virtual void AddSphereOverlay(const Vector& vOrigin, float flRadius, int nTheta, int nPhi, int r, int g, int b, int a, float flDuration) = 0;
virtual void AddTriangleOverlay(const Vector& p1, const Vector& p2, const Vector& p3, int r, int g, int b, int a, bool noDepthTest, float duration) = 0;
virtual void AddLineOverlay(const Vector& origin, const Vector& dest, int r, int g, int b, bool noDepthTest, float duration) = 0;
virtual void AddTextOverlay(const Vector& origin, float duration, const char* format, ...) = 0;
virtual void AddTextOverlay(const Vector& origin, int line_offset, float duration, const char* format, ...) = 0;
virtual void AddScreenTextOverlay(float flXPos, float flYPos, float flDuration, int r, int g, int b, int a, const char* text) = 0;
virtual void AddSweptBoxOverlay(const Vector& start, const Vector& end, const Vector& mins, const Vector& max, const QAngle& angles, int r, int g, int b, int a, float flDuration) = 0;
virtual void AddGridOverlay(const Vector& origin) = 0;
virtual void AddCoordFrameOverlay(const matrix3x4_t& frame, float flScale, int vColorTable[3][3] = NULL) = 0;
virtual int ScreenPosition(const Vector& point, Vector& screen) = 0;
virtual int ScreenPosition(float flXPos, float flYPos, Vector& screen) = 0;
virtual OverlayText_t* GetFirst(void) = 0;
virtual OverlayText_t* GetNext(OverlayText_t* current) = 0;
virtual void ClearDeadOverlays(void) = 0;
virtual void ClearAllOverlays() = 0;
virtual void AddTextOverlayRGB(const Vector& origin, int line_offset, float duration, float r, float g, float b, float alpha, const char* format, ...) = 0;
virtual void AddTextOverlayRGB(const Vector& origin, int line_offset, float duration, int r, int g, int b, int a, const char* format, ...) = 0;
virtual void AddLineOverlayAlpha(const Vector& origin, const Vector& dest, int r, int g, int b, int a, bool noDepthTest, float duration) = 0;
virtual void AddBoxOverlay2(const Vector& origin, const Vector& mins, const Vector& max, QAngle const& orientation, const Color& faceColor, const Color& edgeColor, float duration) = 0;
virtual void PurgeTextOverlays() = 0;
virtual void DrawPill(const Vector& mins, const Vector& max, float& diameter, int r, int g, int b, int a, float duration) = 0;
};
#endif

125
SpyCustom/iviewrender.h Normal file
View File

@ -0,0 +1,125 @@
#if !defined( IVIEWRENDER_H )
#define IVIEWRENDER_H
#ifdef _WIN32
#pragma once
#endif
#include "ivrenderview.h"
#define MAX_DEPTH_TEXTURE_SHADOWS 1
#define MAX_DEPTH_TEXTURE_HIGHRES_SHADOWS 0
#define MAX_DEPTH_TEXTURE_SHADOWS_TOOLS 8
#define MAX_DEPTH_TEXTURE_HIGHRES_SHADOWS_TOOLS 0
enum DrawFlags_t
{
DF_RENDER_REFRACTION = 0x1,
DF_RENDER_REFLECTION = 0x2,
DF_CLIP_Z = 0x4,
DF_CLIP_BELOW = 0x8,
DF_RENDER_UNDERWATER = 0x10,
DF_RENDER_ABOVEWATER = 0x20,
DF_RENDER_WATER = 0x40,
DF_SSAO_DEPTH_PASS = 0x80,
DF_RENDER_PSEUDO_TRANSLUCENT_WATER = 0x100,
DF_WATERHEIGHT = 0x200,
DF_DRAW_SSAO = 0x400,
DF_DRAWSKYBOX = 0x800,
DF_FUDGE_UP = 0x1000,
DF_DRAW_ENTITITES = 0x2000,
DF_SKIP_WORLD = 0x4000,
DF_SKIP_WORLD_DECALS_AND_OVERLAYS = 0x8000,
DF_UNUSED5 = 0x10000,
DF_SAVEGAMESCREENSHOT = 0x20000,
DF_CLIP_SKYBOX = 0x40000,
DF_DRAW_SIMPLE_WORLD_MODEL = 0x80000,
DF_SHADOW_DEPTH_MAP = 0x100000,
DF_FAST_ENTITY_RENDERING = 0x200000,
DF_DRAW_SIMPLE_WORLD_MODEL_WATER = 0x400000,
};
class CViewSetup;
class C_BaseEntity;
struct vrect_t;
class C_BaseViewModel;
abstract_class IViewRender
{
public:
virtual void Init(void) = 0;
virtual void LevelInit(void) = 0;
virtual void LevelShutdown(void) = 0;
virtual void Shutdown(void) = 0;
virtual void OnRenderStart() = 0;
virtual void Render(vrect_t* rect) = 0;
virtual void RenderView(const CViewSetup& view, const CViewSetup& hudViewSetup, int nClearFlags, int whatToDraw) = 0;
virtual int GetDrawFlags() = 0;
virtual void StartPitchDrift(void) = 0;
virtual void StopPitchDrift(void) = 0;
virtual VPlane* GetFrustum() = 0;
virtual bool ShouldDrawBrushModels(void) = 0;
virtual const CViewSetup* GetPlayerViewSetup(int nSlot = -1) const = 0;
virtual const CViewSetup* GetViewSetup(void) const = 0;
virtual void DisableVis(void) = 0;
virtual int BuildWorldListsNumber() const = 0;
virtual void SetCheapWaterStartDistance(float flCheapWaterStartDistance) = 0;
virtual void SetCheapWaterEndDistance(float flCheapWaterEndDistance) = 0;
virtual void GetWaterLODParams(float& flCheapWaterStartDistance, float& flCheapWaterEndDistance) = 0;
virtual void DriftPitch(void) = 0;
virtual void SetScreenOverlayMaterial(IMaterial* pMaterial) = 0;
virtual IMaterial* GetScreenOverlayMaterial() = 0;
virtual void WriteSaveGameScreenshot(const char* pFilename) = 0;
virtual void WriteSaveGameScreenshotOfSize(const char* pFilename, int width, int height) = 0;
virtual void QueueOverlayRenderView(const CViewSetup& view, int nClearFlags, int whatToDraw) = 0;
virtual float GetZNear() = 0;
virtual float GetZFar() = 0;
virtual void GetScreenFadeDistances(float* pMin, float* pMax, float* pScale) = 0;
virtual C_BaseEntity* GetCurrentlyDrawingEntity() = 0;
virtual void SetCurrentlyDrawingEntity(C_BaseEntity* pEnt) = 0;
virtual bool UpdateShadowDepthTexture(ITexture* pRenderTarget, ITexture* pDepthTexture, const CViewSetup& shadowView, bool bRenderWorldAndObjects = true, bool bRenderViewModels = false) = 0;
virtual void FreezeFrame(float flFreezeTime) = 0;
virtual void InitFadeData(void) = 0;
};
extern IViewRender* view;
#endif

View File

@ -0,0 +1,144 @@
#if !defined( IVIEWRENDER_BEAMS_H )
#define IVIEWRENDER_BEAMS_H
#ifdef _WIN32
#pragma once
#endif
#include "vector.h"
#include "beam_flags.h"
#include "tempentity.h"
extern void SetBeamCreationAllowed(bool state);
extern bool BeamCreationAllowed(void);
class C_Beam;
class Beam_t;
struct BeamTrail_t
{
BeamTrail_t* next;
float die;
Vector org;
Vector vel;
};
struct BeamInfo_t
{
int m_nType;
C_BaseEntity* m_pStartEnt;
int m_nStartAttachment;
C_BaseEntity* m_pEndEnt;
int m_nEndAttachment;
Vector m_vecStart;
Vector m_vecEnd;
int m_nModelIndex;
const char* m_pszModelName;
int m_nHaloIndex;
const char* m_pszHaloName;
float m_flHaloScale;
float m_flLife;
float m_flWidth;
float m_flEndWidth;
float m_flFadeLength;
float m_flAmplitude;
float m_flBrightness;
float m_flSpeed;
int m_nStartFrame;
float m_flFrameRate;
float m_flRed;
float m_flGreen;
float m_flBlue;
bool m_bRenderable;
int m_nSegments;
int m_nFlags;
Vector m_vecCenter;
float m_flStartRadius;
float m_flEndRadius;
BeamInfo_t()
{
m_nType = TE_BEAMPOINTS;
m_nSegments = -1;
m_pszModelName = NULL;
m_pszHaloName = NULL;
m_nModelIndex = -1;
m_nHaloIndex = -1;
m_bRenderable = true;
m_nFlags = 0;
}
};
abstract_class IViewRenderBeams
{
public:
public:
public:
virtual void InitBeams(void) = 0;
virtual void ShutdownBeams(void) = 0;
virtual void ClearBeams(void) = 0;
virtual void UpdateTempEntBeams() = 0;
virtual void DrawBeam(C_Beam* pbeam, ITraceFilter* pEntityBeamTraceFilter = NULL) = 0;
virtual void DrawBeam(Beam_t* pbeam) = 0;
virtual void KillDeadBeams(CBaseEntity* pEnt) = 0;
virtual Beam_t* CreateBeamEnts(BeamInfo_t& beamInfo) = 0;
virtual Beam_t* CreateBeamEntPoint(BeamInfo_t& beamInfo) = 0;
virtual Beam_t* CreateBeamPoints(BeamInfo_t& beamInfo) = 0;
virtual Beam_t* CreateBeamRing(BeamInfo_t& beamInfo) = 0;
virtual Beam_t* CreateBeamRingPoint(BeamInfo_t& beamInfo) = 0;
virtual Beam_t* CreateBeamCirclePoints(BeamInfo_t& beamInfo) = 0;
virtual Beam_t* CreateBeamFollow(BeamInfo_t& beamInfo) = 0;
virtual void FreeBeam(Beam_t* pBeam) = 0;
virtual void UpdateBeamInfo(Beam_t* pBeam, BeamInfo_t& beamInfo) = 0;
virtual void CreateBeamEnts(int startEnt, int endEnt, int modelIndex, int haloIndex, float haloScale,
float life, float width, float m_nEndWidth, float m_nFadeLength, float amplitude,
float brightness, float speed, int startFrame,
float framerate, float r, float g, float b, int type = -1) = 0;
virtual void CreateBeamEntPoint(int nStartEntity, const Vector* pStart, int nEndEntity, const Vector* pEnd,
int modelIndex, int haloIndex, float haloScale,
float life, float width, float m_nEndWidth, float m_nFadeLength, float amplitude,
float brightness, float speed, int startFrame,
float framerate, float r, float g, float b) = 0;
virtual void CreateBeamPoints(Vector& start, Vector& end, int modelIndex, int haloIndex, float haloScale,
float life, float width, float m_nEndWidth, float m_nFadeLength, float amplitude,
float brightness, float speed, int startFrame,
float framerate, float r, float g, float b) = 0;
virtual void CreateBeamRing(int startEnt, int endEnt, int modelIndex, int haloIndex, float haloScale,
float life, float width, float m_nEndWidth, float m_nFadeLength, float amplitude,
float brightness, float speed, int startFrame,
float framerate, float r, float g, float b, int flags = 0) = 0;
virtual void CreateBeamRingPoint(const Vector& center, float start_radius, float end_radius, int modelIndex, int haloIndex, float haloScale,
float life, float width, float m_nEndWidth, float m_nFadeLength, float amplitude,
float brightness, float speed, int startFrame,
float framerate, float r, float g, float b, int flags = 0) = 0;
virtual void CreateBeamCirclePoints(int type, Vector& start, Vector& end,
int modelIndex, int haloIndex, float haloScale, float life, float width,
float m_nEndWidth, float m_nFadeLength, float amplitude, float brightness, float speed,
int startFrame, float framerate, float r, float g, float b) = 0;
virtual void CreateBeamFollow(int startEnt, int modelIndex, int haloIndex, float haloScale,
float life, float width, float m_nEndWidth, float m_nFadeLength, float r, float g, float b,
float brightness) = 0;
};
#endif

152
SpyCustom/ivmodelinfo.h Normal file
View File

@ -0,0 +1,152 @@
#ifndef IVMODELINFO_H
#define IVMODELINFO_H
#ifdef _WIN32
#pragma once
#endif
#include "platform.h"
#include "dbg.h"
class IMaterial;
class KeyValues;
struct vcollide_t;
struct model_t;
class Vector;
class QAngle;
class CGameTrace;
struct cplane_t;
typedef CGameTrace trace_t;
struct studiohdr_t;
struct virtualmodel_t;
typedef unsigned char byte;
struct virtualterrainparams_t;
class CPhysCollide;
typedef unsigned short MDLHandle_t;
class CUtlBuffer;
class IClientRenderable;
class CStudioHdr;
enum RenderableTranslucencyType_t
{
RENDERABLE_IS_OPAQUE = 0,
RENDERABLE_IS_TRANSLUCENT,
RENDERABLE_IS_TWO_PASS,
};
abstract_class IModelLoadCallback
{
public:
virtual void OnModelLoadComplete(const model_t * pModel) = 0;
protected:
~IModelLoadCallback();
};
class CRefCountedModelIndex
{
private:
int m_nIndex;
public:
CRefCountedModelIndex() : m_nIndex(-1) { }
~CRefCountedModelIndex() { Set(-1); }
CRefCountedModelIndex(const CRefCountedModelIndex& src) : m_nIndex(-1) { Set(src.m_nIndex); }
CRefCountedModelIndex& operator=(const CRefCountedModelIndex& src) { Set(src.m_nIndex); return *this; }
explicit CRefCountedModelIndex(int i) : m_nIndex(-1) { Set(i); }
CRefCountedModelIndex& operator=(int i) { Set(i); return *this; }
int Get() const { return m_nIndex; }
void Set(int i);
void Clear() { Set(-1); }
operator int() const { return m_nIndex; }
};
#define VMODELINFO_CLIENT_INTERFACE_VERSION "VModelInfoClient006"
#define VMODELINFO_SERVER_INTERFACE_VERSION_3 "VModelInfoServer003"
#define VMODELINFO_SERVER_INTERFACE_VERSION "VModelInfoServer004"
inline bool IsDynamicModelIndex(int modelindex) { return modelindex < -1; }
inline bool IsClientOnlyModelIndex(int modelindex) { return modelindex < -1 && (modelindex & 1); }
class IVModelInfo
{
public:
virtual ~IVModelInfo(void) {}
virtual const model_t* GetModel(int modelindex) const = 0;
virtual int GetModelIndex(const char* name) const = 0;
virtual const char* GetModelName(const model_t* model) const = 0;
virtual vcollide_t* GetVCollide(const model_t* model) const = 0;
virtual vcollide_t* GetVCollide(int modelindex) const = 0;
virtual void GetModelBounds(const model_t* model, Vector& mins, Vector& maxs) const = 0;
virtual void GetModelRenderBounds(const model_t* model, Vector& mins, Vector& maxs) const = 0;
virtual int GetModelFrameCount(const model_t* model) const = 0;
virtual int GetModelType(const model_t* model) const = 0;
virtual void* GetModelExtraData(const model_t* model) = 0;
virtual bool ModelHasMaterialProxy(const model_t* model) const = 0;
virtual bool IsTranslucent(model_t const* model) const = 0;
virtual bool IsTranslucentTwoPass(const model_t* model) const = 0;
virtual void Unused0() {};
virtual void UNUSED() = 0;
virtual void UNUSE11D() = 0;
virtual RenderableTranslucencyType_t ComputeTranslucencyType(const model_t* model, int nSkin, int nBody) = 0;
virtual int GetModelMaterialCount(const model_t* model) const = 0;
virtual void GetModelMaterials(const model_t* model, int count, IMaterial** ppMaterial) = 0;
virtual bool IsModelVertexLit(const model_t* model) const = 0;
virtual const char* GetModelKeyValueText(const model_t* model) = 0;
virtual bool GetModelKeyValue(const model_t* model, CUtlBuffer& buf) = 0;
virtual float GetModelRadius(const model_t* model) = 0;
virtual CStudioHdr* GetStudioHdr(MDLHandle_t handle) = 0;
virtual const studiohdr_t* FindModel(const studiohdr_t* pStudioHdr, void** cache, const char* modelname) const = 0;
virtual const studiohdr_t* FindModel(void* cache) const = 0;
virtual virtualmodel_t* GetVirtualModel(const studiohdr_t* pStudioHdr) const = 0;
virtual uint8_t* GetAnimBlock(const studiohdr_t* pStudioHdr, int iBlock) const = 0;
virtual void GetModelMaterialColorAndLighting(const model_t* model, Vector const& origin, QAngle const& angles, trace_t* pTrace, Vector& lighting, Vector& matColor) = 0;
virtual void GetIlluminationPoint(const model_t* model, IClientRenderable* pRenderable, Vector const& origin, QAngle const& angles, Vector* pLightingCenter) = 0;
virtual int GetModelContents(int modelIndex) const = 0;
virtual studiohdr_t* GetStudiomodel(const model_t* mod) = 0;
virtual int GetModelSpriteWidth(const model_t* model) const = 0;
virtual int GetModelSpriteHeight(const model_t* model) const = 0;
virtual void SetLevelScreenFadeRange(float flMinSize, float flMaxSize) = 0;
virtual void GetLevelScreenFadeRange(float* pMinArea, float* pMaxArea) const = 0;
virtual void SetViewScreenFadeRange(float flMinSize, float flMaxSize) = 0;
virtual unsigned char ComputeLevelScreenFade(const Vector& vecAbsOrigin, float flRadius, float flFadeScale) const = 0;
virtual unsigned char ComputeViewScreenFade(const Vector& vecAbsOrigin, float flRadius, float flFadeScale) const = 0;
virtual int GetAutoplayList(const studiohdr_t* pStudioHdr, unsigned short** pAutoplayList) const = 0;
virtual CPhysCollide* GetCollideForVirtualTerrain(int index) = 0;
virtual bool IsUsingFBTexture(const model_t* model, int nSkin, int nBody, IClientRenderable** pClientRenderable) const = 0;
virtual const model_t* FindOrLoadModel(const char* name) const = 0;
virtual MDLHandle_t GetCacheHandle(const model_t* model) const = 0;
virtual int GetBrushModelPlaneCount(const model_t* model) const = 0;
virtual void GetBrushModelPlane(const model_t* model, int nIndex, cplane_t& plane, Vector* pOrigin) const = 0;
virtual int GetSurfacepropsForVirtualTerrain(int index) = 0;
virtual bool UsesEnvCubemap(const model_t* model) const = 0;
virtual bool UsesStaticLighting(const model_t* model) const = 0;
};
typedef IVModelInfo IVModelInfo003;
abstract_class IVModelInfoClient : public IVModelInfo
{
public:
virtual void OnDynamicModelsStringTableChange(int nStringIndex, const char* pString, const void* pData) = 0;
virtual const model_t* FindOrLoadModel(const char* name) = 0;
};
struct virtualterrainparams_t
{
int index;
};
#endif

131
SpyCustom/ivmodelrender.h Normal file
View File

@ -0,0 +1,131 @@
#ifndef IVMODELRENDER_H
#define IVMODELRENDER_H
#ifdef _WIN32
#pragma once
#endif
#include "interface.h"
#include "mathlib.h"
#include "istudiorender.h"
#include "idatacache.h"
struct mstudioanimdesc_t;
struct mstudioseqdesc_t;
struct model_t;
class IClientRenderable;
class Vector;
struct studiohdr_t;
class IMaterial;
class CStudioHdr;
struct MaterialLightingState_t;
FORWARD_DECLARE_HANDLE(LightCacheHandle_t);
struct DrawModelState_t
{
studiohdr_t* m_pStudioHdr;
studiohwdata_t* m_pStudioHWData;
IClientRenderable* m_pRenderable;
const matrix3x4_t* m_pModelToWorld;
StudioDecalHandle_t m_decals;
int m_drawFlags;
int m_lod;
};
#define VENGINE_HUDMODEL_INTERFACE_VERSION "VEngineModel016"
typedef unsigned short ModelInstanceHandle_t;
enum
{
MODEL_INSTANCE_INVALID = (ModelInstanceHandle_t)~0
};
struct ModelRenderInfo_t
{
Vector origin;
Vector angles;
char pad[4];
IClientRenderable* pRenderable;
const model_t* pModel;
const matrix3x4_t* pModelToWorld;
const matrix3x4_t* pLightingOffset;
const Vector* pLightingOrigin;
int flags;
int entity_index;
int skin;
int body;
int hitboxset;
ModelInstanceHandle_t instance;
ModelRenderInfo_t()
{
pModelToWorld = NULL;
pLightingOffset = NULL;
pLightingOrigin = NULL;
}
};
struct StaticPropRenderInfo_t
{
const matrix3x4_t* pModelToWorld;
const model_t* pModel;
IClientRenderable* pRenderable;
Vector* pLightingOrigin;
short skin;
ModelInstanceHandle_t instance;
};
struct LightingQuery_t
{
Vector m_LightingOrigin;
ModelInstanceHandle_t m_InstanceHandle;
bool m_bAmbientBoost;
};
struct StaticLightingQuery_t : public LightingQuery_t
{
IClientRenderable * m_pRenderable;
};
class IVModelRender
{
public:
virtual int DrawModel(int flags, IClientRenderable* pRenderable, ModelInstanceHandle_t instance, int entity_index, const model_t* model, Vector const& origin, QAngle const& angles, int skin, int body, int hitboxset, const matrix3x4_t* modelToWorld = NULL, const matrix3x4_t* pLightingOffset = NULL) = 0;
virtual void ForcedMaterialOverride(IMaterial* newMaterial, OverrideType_t nOverrideType = OVERRIDE_NORMAL, int nOverrides = 0) = 0;
virtual bool IsForcedMaterialOverride(void) = 0;
virtual void SetViewTarget(const CStudioHdr* pStudioHdr, int nBodyIndex, const Vector& target) = 0;
virtual ModelInstanceHandle_t CreateInstance(IClientRenderable* pRenderable, LightCacheHandle_t* pCache = NULL) = 0;
virtual void DestroyInstance(ModelInstanceHandle_t handle) = 0;
virtual void SetStaticLighting(ModelInstanceHandle_t handle, LightCacheHandle_t* pHandle) = 0;
virtual LightCacheHandle_t GetStaticLighting(ModelInstanceHandle_t handle) = 0;
virtual bool ChangeInstance(ModelInstanceHandle_t handle, IClientRenderable* pRenderable) = 0;
virtual void AddDecal(ModelInstanceHandle_t handle, Ray_t const& ray, Vector const& decalUp, int decalIndex, int body, bool noPokeThru, int maxLODToDecal) = 0;
virtual void RemoveAllDecals(ModelInstanceHandle_t handle) = 0;
virtual bool ModelHasDecals(ModelInstanceHandle_t handle) = 0;
virtual void RemoveAllDecalsFromAllModels() = 0;
virtual matrix3x4_t* DrawModelShadowSetup(IClientRenderable* pRenderable, int body, int skin, DrawModelInfo_t* pInfo, matrix3x4_t* pCustomBoneToWorld = NULL) = 0;
virtual void DrawModelShadow(IClientRenderable* pRenderable, const DrawModelInfo_t& info, matrix3x4_t* pCustomBoneToWorld = NULL) = 0;
virtual bool RecomputeStaticLighting(ModelInstanceHandle_t handle) = 0;
virtual void ReleaseAllStaticPropColorData(void) = 0;
virtual void RestoreAllStaticPropColorData(void) = 0;
virtual int DrawModelEx(ModelRenderInfo_t& pInfo) = 0;
virtual int DrawModelExStaticProp(ModelRenderInfo_t& pInfo) = 0;
virtual bool DrawModelSetup(ModelRenderInfo_t& pInfo, DrawModelState_t* pState, matrix3x4_t** ppBoneToWorldOut) = 0;
virtual void DrawModelExecute(IMatRenderContext* ctx, const DrawModelState_t& state, const ModelRenderInfo_t& pInfo, matrix3x4_t* pCustomBoneToWorld = NULL) = 0;
virtual void SetupLighting(const Vector& vecCenter) = 0;
virtual int DrawStaticPropArrayFast(StaticPropRenderInfo_t* pProps, int count, bool bShadowDepth) = 0;
virtual void SuppressEngineLighting(bool bSuppress) = 0;
virtual void SetupColorMeshes(int nTotalVerts) = 0;
virtual void SetupLightingEx(const Vector& vecCenter, ModelInstanceHandle_t handle) = 0;
virtual bool GetBrightestShadowingLightSource(const Vector& vecCenter, Vector& lightPos, Vector& lightBrightness, bool bAllowNonTaggedLights) = 0;
virtual void ComputeLightingState(int nCount, const LightingQuery_t* pQuery, MaterialLightingState_t* pState, ITexture** ppEnvCubemapTexture) = 0;
virtual void GetModelDecalHandles(StudioDecalHandle_t* pDecals, int nDecalStride, int nCount, const ModelInstanceHandle_t* pHandles) = 0;
virtual void ComputeStaticLightingState(int nCount, const StaticLightingQuery_t* pQuery, MaterialLightingState_t* pState, MaterialLightingState_t* pDecalState, ColorMeshInfo_t** ppStaticLighting, ITexture** ppEnvCubemapTexture, DataCacheHandle_t* pColorMeshHandles) = 0;
virtual void CleanupStaticLightingState(int nCount, DataCacheHandle_t* pColorMeshHandles) = 0;
};
#endif

310
SpyCustom/ivrenderview.h Normal file
View File

@ -0,0 +1,310 @@
#if !defined( IVRENDERVIEW_H )
#define IVRENDERVIEW_H
#ifdef _WIN32
#pragma once
#endif
#include "basetypes.h"
#include "vplane.h"
#include "interface.h"
#include "imaterialsystem.h"
#include "const.h"
#include "vertexcolor.h"
#include "refcount.h"
class CViewSetup;
class CEngineSprite;
class IClientEntity;
class IMaterial;
struct model_t;
class IClientRenderable;
class IMatRenderContext;
class CVolumeCuller;
enum
{
DRAWWORLDLISTS_DRAW_STRICTLYABOVEWATER = 0x001,
DRAWWORLDLISTS_DRAW_STRICTLYUNDERWATER = 0x002,
DRAWWORLDLISTS_DRAW_INTERSECTSWATER = 0x004,
DRAWWORLDLISTS_DRAW_WATERSURFACE = 0x008,
DRAWWORLDLISTS_DRAW_SKYBOX = 0x010,
DRAWWORLDLISTS_DRAW_CLIPSKYBOX = 0x020,
DRAWWORLDLISTS_DRAW_SHADOWDEPTH = 0x040,
DRAWWORLDLISTS_DRAW_REFRACTION = 0x080,
DRAWWORLDLISTS_DRAW_REFLECTION = 0x100,
DRAWWORLDLISTS_DRAW_WORLD_GEOMETRY = 0x200,
DRAWWORLDLISTS_DRAW_DECALS_AND_OVERLAYS = 0x400,
DRAWWORLDLISTS_DRAW_SIMPLE_WORLD_MODEL = 0x800,
DRAWWORLDLISTS_DRAW_SIMPLE_WORLD_MODEL_WATER = 0x1000,
DRAWWORLDLISTS_DRAW_SKIP_DISPLACEMENTS = 0x2000,
DRAWWORLDLISTS_DRAW_SSAO = 0x4000,
};
enum
{
MAT_SORT_GROUP_STRICTLY_ABOVEWATER = 0,
MAT_SORT_GROUP_STRICTLY_UNDERWATER,
MAT_SORT_GROUP_INTERSECTS_WATER_SURFACE,
MAT_SORT_GROUP_WATERSURFACE,
MAX_MAT_SORT_GROUPS
};
enum ERenderDepthMode_t
{
DEPTH_MODE_NORMAL = 0,
DEPTH_MODE_SHADOW = 1,
DEPTH_MODE_SSA0 = 2,
DEPTH_MODE_MAX
};
static const char* s_pMatSortGroupsString[] =
{
"Sort: Abovewater",
"Sort: Underwater",
"Sort: IntersectsWater",
"Sort: WaterSurface",
};
typedef VPlane Frustum[FRUSTUM_NUMPLANES];
typedef unsigned short LeafIndex_t;
enum
{
INVALID_LEAF_INDEX = (LeafIndex_t)~0
};
#if 1
struct WorldListLeafData_t
{
LeafIndex_t leafIndex;
int16 waterData;
uint16 firstTranslucentSurface;
uint16 translucentSurfaceCount;
};
#else
struct WorldListLeafData_t
{
uint32 leafIndex;
int32 waterData;
uint32 firstTranslucentSurface;
uint32 translucentSurfaceCount;
};
#endif
struct WorldListInfo_t
{
int m_ViewFogVolume;
int m_LeafCount;
bool m_bHasWater;
WorldListLeafData_t* m_pLeafDataList;
};
class IWorldRenderList : public IRefCounted
{
};
struct VisibleFogVolumeInfo_t
{
int m_nVisibleFogVolume;
int m_nVisibleFogVolumeLeaf;
bool m_bEyeInFogVolume;
float m_flDistanceToWater;
float m_flWaterHeight;
IMaterial* m_pFogVolumeMaterial;
};
struct BrushVertex_t
{
Vector m_Pos;
Vector m_Normal;
Vector m_TangentS;
Vector m_TangentT;
Vector2D m_TexCoord;
Vector2D m_LightmapCoord;
private:
BrushVertex_t(const BrushVertex_t& src);
};
struct VisOverrideData_t
{
Vector m_vecVisOrigin;
float m_fDistToAreaPortalTolerance;
Vector m_vPortalCorners[4];
bool m_bTrimFrustumToPortalCorners;
Vector m_vPortalOrigin;
Vector m_vPortalForward;
float m_flPortalRadius;
};
class IBrushSurface
{
public:
virtual void ComputeTextureCoordinate(Vector const& worldPos, Vector2D& texCoord) = 0;
virtual void ComputeLightmapCoordinate(Vector const& worldPos, Vector2D& lightmapCoord) = 0;
virtual int GetVertexCount() const = 0;
virtual void GetVertexData(BrushVertex_t* pVerts) = 0;
virtual IMaterial* GetMaterial() = 0;
};
class IBrushRenderer
{
public:
virtual bool RenderBrushModelSurface(IClientEntity* pBaseEntity, IBrushSurface* pBrushSurface) = 0;
};
#define MAX_VIS_LEAVES 32
enum DrawBrushModelMode_t
{
DBM_DRAW_ALL = 0,
DBM_DRAW_OPAQUE_ONLY,
DBM_DRAW_TRANSLUCENT_ONLY,
};
struct BrushArrayInstanceData_t
{
matrix3x4a_t* m_pBrushToWorld;
const model_t* m_pBrushModel;
Vector4D m_DiffuseModulation;
ShaderStencilState_t* m_pStencilState;
};
class IVRenderView
{
public:
virtual void DrawBrushModel(
IClientEntity* baseentity,
model_t* model,
const Vector& origin,
const QAngle& angles,
bool bUnused) = 0;
virtual void DrawIdentityBrushModel(IWorldRenderList* pList, model_t* model) = 0;
virtual void TouchLight(struct dlight_t* light) = 0;
virtual void Draw3DDebugOverlays(void) = 0;
virtual void SetBlend(float blend) = 0;
virtual float GetBlend(void) = 0;
virtual void SetColorModulation(float const* blend) = 0;
virtual void GetColorModulation(float* blend) = 0;
virtual void SceneBegin(void) = 0;
virtual void SceneEnd(void) = 0;
virtual void GetVisibleFogVolume(const Vector& eyePoint, const VisOverrideData_t* pVisOverrideData, VisibleFogVolumeInfo_t* pInfo) = 0;
virtual IWorldRenderList* CreateWorldList() = 0;
#if defined(_PS3)
virtual IWorldRenderList* CreateWorldList_PS3(int viewID) = 0;
virtual void BuildWorldLists_PS3_Epilogue(IWorldRenderList* pList, WorldListInfo_t* pInfo, bool bShadowDepth) = 0;
#else
virtual void BuildWorldLists_Epilogue(IWorldRenderList* pList, WorldListInfo_t* pInfo, bool bShadowDepth) = 0;
#endif
virtual void BuildWorldLists(IWorldRenderList* pList, WorldListInfo_t* pInfo, int iForceFViewLeaf, const VisOverrideData_t* pVisData = NULL, bool bShadowDepth = false, float* pReflectionWaterHeight = NULL) = 0;
virtual void DrawWorldLists(IMatRenderContext* pRenderContext, IWorldRenderList* pList, unsigned long flags, float waterZAdjust) = 0;
virtual void GetWorldListIndicesInfo(WorldListIndicesInfo_t* pIndicesInfoOut, IWorldRenderList* pList, unsigned long nFlags) = 0;
virtual void DrawTopView(bool enable) = 0;
virtual void TopViewNoBackfaceCulling(bool bDisable) = 0;
virtual void TopViewNoVisCheck(bool bDisable) = 0;
virtual void TopViewBounds(Vector2D const& mins, Vector2D const& maxs) = 0;
virtual void SetTopViewVolumeCuller(const CVolumeCuller* pVolumeCuller) = 0;
virtual void DrawLights(void) = 0;
virtual void DrawMaskEntities(void) = 0;
virtual void DrawTranslucentSurfaces(IMatRenderContext* pRenderContext, IWorldRenderList* pList, int* pSortList, int sortCount, unsigned long flags) = 0;
virtual void DrawLineFile(void) = 0;
virtual void DrawLightmaps(IWorldRenderList* pList, int pageId) = 0;
virtual void ViewSetupVis(bool novis, int numorigins, const Vector origin[]) = 0;
virtual bool AreAnyLeavesVisible(int* leafList, int nLeaves) = 0;
virtual void VguiPaint(void) = 0;
virtual void ViewDrawFade(byte* color, IMaterial* pMaterial, bool mapFullTextureToScreen = true) = 0;
virtual void OLD_SetProjectionMatrix(float fov, float zNear, float zFar) = 0;
virtual colorVec GetLightAtPoint(Vector& pos) = 0;
virtual int GetViewEntity(void) = 0;
virtual bool IsViewEntity(int entindex) = 0;
virtual float GetFieldOfView(void) = 0;
virtual unsigned char** GetAreaBits(void) = 0;
virtual void SetFogVolumeState(int nVisibleFogVolume, bool bUseHeightFog) = 0;
virtual void InstallBrushSurfaceRenderer(IBrushRenderer* pBrushRenderer) = 0;
virtual void DrawBrushModelShadow(IClientRenderable* pRenderable) = 0;
virtual bool LeafContainsTranslucentSurfaces(IWorldRenderList* pList, int sortIndex, unsigned long flags) = 0;
virtual bool DoesBoxIntersectWaterVolume(const Vector& mins, const Vector& maxs, int leafWaterDataID) = 0;
virtual void SetAreaState(
unsigned char chAreaBits[MAX_AREA_STATE_BYTES],
unsigned char chAreaPortalBits[MAX_AREA_PORTAL_STATE_BYTES]) = 0;
virtual void VGui_Paint(int mode) = 0;
virtual void Push3DView(IMatRenderContext* pRenderContext, const CViewSetup& view, int nFlags, ITexture* pRenderTarget, Frustum frustumPlanes) = 0;
virtual void Push2DView(IMatRenderContext* pRenderContext, const CViewSetup& view, int nFlags, ITexture* pRenderTarget, Frustum frustumPlanes) = 0;
virtual void PopView(IMatRenderContext* pRenderContext, Frustum frustumPlanes) = 0;
virtual void SetMainView(const Vector& vecOrigin, const QAngle& angles) = 0;
enum
{
VIEW_SETUP_VIS_EX_RETURN_FLAGS_USES_RADIAL_VIS = 0x00000001
};
virtual void ViewSetupVisEx(bool novis, int numorigins, const Vector origin[], unsigned int& returnFlags) = 0;
virtual void OverrideViewFrustum(Frustum custom) = 0;
virtual void DrawBrushModelShadowDepth(IClientEntity* baseentity, model_t* model, const Vector& origin, const QAngle& angles, ERenderDepthMode_t DepthMode) = 0;
virtual void UpdateBrushModelLightmap(model_t* model, IClientRenderable* pRenderable) = 0;
virtual void BeginUpdateLightmaps(void) = 0;
virtual void EndUpdateLightmaps() = 0;
virtual void OLD_SetOffCenterProjectionMatrix(float fov, float zNear, float zFar, float flAspectRatio, float flBottom, float flTop, float flLeft, float flRight) = 0;
virtual void OLD_SetProjectionMatrixOrtho(float left, float top, float right, float bottom, float zNear, float zFar) = 0;
virtual void Push3DView(IMatRenderContext* pRenderContext, const CViewSetup& view, int nFlags, ITexture* pRenderTarget, Frustum frustumPlanes, ITexture* pDepthTexture) = 0;
virtual void GetMatricesForView(const CViewSetup& view, VMatrix* pWorldToView, VMatrix* pViewToProjection, VMatrix* pWorldToProjection, VMatrix* pWorldToPixels) = 0;
virtual void DrawBrushModelEx(IClientEntity* baseentity, model_t* model, const Vector& origin, const QAngle& angles, DrawBrushModelMode_t mode) = 0;
virtual bool DoesBrushModelNeedPowerOf2Framebuffer(const model_t* model) = 0;
virtual void DrawBrushModelArray(IMatRenderContext* pContext, int nCount, const BrushArrayInstanceData_t* pInstanceData, int nModelTypeFlags) = 0;
};
#define VENGINE_RENDERVIEW_INTERFACE_VERSION "VEngineRenderView014"
#if defined(_STATIC_LINKED) && defined(CLIENT_DLL)
namespace Client
{
extern IVRenderView* render;
}
#else
extern IVRenderView* render;
#endif
#endif

1270
SpyCustom/jobthread.h Normal file

File diff suppressed because it is too large Load Diff

420
SpyCustom/keyvalues.h Normal file
View File

@ -0,0 +1,420 @@
#ifndef KEYVALUES_H
#define KEYVALUES_H
#ifdef _WIN32
#pragma once
#endif
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#endif
#include "utlvector.h"
#include "color.h"
#include "exprevaluator.h"
#define TRACK_KV_ADD( ptr, name ) track.AddKv( ptr, name )
#define SPLIT_3_BYTES_INTO_1_AND_2( x1, x2, x3 ) do { x1 = (uint8)(x3); x2 = (uint16)( (x3) >> 8 ); } while( 0 )
#define FOR_EACH_SUBKEY( kvRoot, kvSubKey ) \
for ( KeyValues * kvSubKey = kvRoot->GetFirstSubKey(); kvSubKey != NULL; kvSubKey = kvSubKey->GetNextKey() )
#define FOR_EACH_TRUE_SUBKEY( kvRoot, kvSubKey ) \
for ( KeyValues * kvSubKey = kvRoot->GetFirstTrueSubKey(); kvSubKey != NULL; kvSubKey = kvSubKey->GetNextTrueSubKey() )
#define FOR_EACH_VALUE( kvRoot, kvValue ) \
for ( KeyValues * kvValue = kvRoot->GetFirstValue(); kvValue != NULL; kvValue = kvValue->GetNextValue() )
class IBaseFileSystem;
class CUtlBuffer;
class Color;
class CKeyValuesTokenReader;
class KeyValues;
class IKeyValuesDumpContext;
typedef void* FileHandle_t;
class CKeyValuesGrowableStringTable;
#define KV_BINARY_POOLED_FORMAT 0xAA
#define FOR_EACH_SUBKEY( kvRoot, kvSubKey ) \
for ( KeyValues * kvSubKey = kvRoot->GetFirstSubKey(); kvSubKey != NULL; kvSubKey = kvSubKey->GetNextKey() )
#define FOR_EACH_TRUE_SUBKEY( kvRoot, kvSubKey ) \
for ( KeyValues * kvSubKey = kvRoot->GetFirstTrueSubKey(); kvSubKey != NULL; kvSubKey = kvSubKey->GetNextTrueSubKey() )
#define FOR_EACH_VALUE( kvRoot, kvValue ) \
for ( KeyValues * kvValue = kvRoot->GetFirstValue(); kvValue != NULL; kvValue = kvValue->GetNextValue() )
class KeyValues
{
friend class CKeyValuesTokenReader;
public:
static void SetUseGrowableStringTable(bool bUseGrowableTable);
explicit KeyValues(const char* setName);
class AutoDelete
{
public:
explicit inline AutoDelete(KeyValues* pKeyValues) : m_pKeyValues(pKeyValues) {}
explicit inline AutoDelete(const char* pchKVName) : m_pKeyValues(new KeyValues(pchKVName)) {}
inline ~AutoDelete(void) { delete m_pKeyValues; }
inline void Assign(KeyValues* pKeyValues) { m_pKeyValues = pKeyValues; }
inline KeyValues* Detach() { KeyValues* retval = m_pKeyValues; Assign(NULL); return retval; }
KeyValues* operator->() { return m_pKeyValues; }
operator KeyValues* () { return m_pKeyValues; }
private:
AutoDelete(AutoDelete const& x);
AutoDelete& operator= (AutoDelete const& x);
protected:
KeyValues* m_pKeyValues;
};
class AutoDeleteInline : public AutoDelete
{
public:
explicit inline AutoDeleteInline(KeyValues* pKeyValues) : AutoDelete(pKeyValues) {}
inline operator KeyValues* () const { return m_pKeyValues; }
inline KeyValues* Get() const { return m_pKeyValues; }
};
KeyValues(const char* setName, const char* firstKey, const char* firstValue);
KeyValues(const char* setName, const char* firstKey, const wchar_t* firstValue);
KeyValues(const char* setName, const char* firstKey, int firstValue);
KeyValues(const char* setName, const char* firstKey, const char* firstValue, const char* secondKey, const char* secondValue);
KeyValues(const char* setName, const char* firstKey, int firstValue, const char* secondKey, int secondValue);
~KeyValues();
const char* GetName() const;
void SetName(const char* setName);
int GetNameSymbol() const;
int GetNameSymbolCaseSensitive() const;
void UsesEscapeSequences(bool state);
bool LoadFromFile(IBaseFileSystem* filesystem, const char* resourceName, const char* pathID = NULL);
bool SaveToFile(IBaseFileSystem* filesystem, const char* resourceName, const char* pathID = NULL, bool bWriteEmptySubkeys = false);
bool LoadFromBuffer(char const* resourceName, const char* pBuffer, IBaseFileSystem* pFileSystem = NULL, const char* pPathID = NULL);
bool LoadFromBuffer(char const* resourceName, CUtlBuffer& buf, IBaseFileSystem* pFileSystem = NULL, const char* pPathID = NULL);
KeyValues* FindKey(const char* keyName, bool bCreate = false);
KeyValues* FindKey(int keySymbol) const;
KeyValues* CreateNewKey();
void AddSubKey(KeyValues* pSubkey);
void RemoveSubKey(KeyValues* subKey);
void InsertSubKey(int nIndex, KeyValues* pSubKey);
bool ContainsSubKey(KeyValues* pSubKey);
void SwapSubKey(KeyValues* pExistingSubKey, KeyValues* pNewSubKey);
void ElideSubKey(KeyValues* pSubKey);
KeyValues* CreateKey(const char* keyName);
KeyValues* CreatePeerKey(const char* keyName);
KeyValues* GetFirstSubKey() { return m_pSub; }
KeyValues* GetNextKey() { return m_pPeer; }
void SetNextKey(KeyValues* pDat);
KeyValues* FindLastSubKey();
KeyValues* GetFirstTrueSubKey();
KeyValues* GetNextTrueSubKey();
KeyValues* GetFirstValue();
KeyValues* GetNextValue();
int GetInt(const char* keyName = NULL, int defaultValue = 0);
uint64 GetUint64(const char* keyName = NULL, uint64 defaultValue = 0);
float GetFloat(const char* keyName = NULL, float defaultValue = 0.0f);
const char* GetString(const char* keyName = NULL, const char* defaultValue = "");
const wchar_t* GetWString(const char* keyName = NULL, const wchar_t* defaultValue = L"");
void* GetPtr(const char* keyName = NULL, void* defaultValue = (void*)0);
Color GetColor(const char* keyName = NULL, const Color& defaultColor = Color(0, 0, 0, 0));
bool GetBool(const char* keyName = NULL, bool defaultValue = false) { return GetInt(keyName, defaultValue ? 1 : 0) ? true : false; }
bool IsEmpty(const char* keyName = NULL);
int GetInt(int keySymbol, int defaultValue = 0);
uint64 GetUint64(int keySymbol, uint64 defaultValue = 0);
float GetFloat(int keySymbol, float defaultValue = 0.0f);
const char* GetString(int keySymbol, const char* defaultValue = "");
const wchar_t* GetWString(int keySymbol, const wchar_t* defaultValue = L"");
void* GetPtr(int keySymbol, void* defaultValue = (void*)0);
Color GetColor(int keySymbol );
bool GetBool(int keySymbol, bool defaultValue = false) { return GetInt(keySymbol, defaultValue ? 1 : 0) ? true : false; }
bool IsEmpty(int keySymbol);
void SetWString(const char* keyName, const wchar_t* value);
void SetString(const char* keyName, const char* value);
void SetInt(const char* keyName, int value);
void SetUint64(const char* keyName, uint64 value);
void SetFloat(const char* keyName, float value);
void SetPtr(const char* keyName, void* value);
void SetColor(const char* keyName, Color value);
void SetBool(const char* keyName, bool value) { SetInt(keyName, value ? 1 : 0); }
void* operator new(size_t iAllocSize);
void* operator new(size_t iAllocSize, int nBlockUse, const char* pFileName, int nLine);
void operator delete(void* pMem);
void operator delete(void* pMem, int nBlockUse, const char* pFileName, int nLine);
KeyValues& operator=(KeyValues& src);
bool IsEqual(KeyValues* pRHS);
void ChainKeyValue(KeyValues* pChain);
void RecursiveSaveToFile(CUtlBuffer& buf, int indentLevel);
bool WriteAsBinary(CUtlBuffer& buffer) const;
bool ReadAsBinary(CUtlBuffer& buffer, int nStackDepth = 0);
bool WriteAsBinaryFiltered(CUtlBuffer& buffer);
bool ReadAsBinaryFiltered(CUtlBuffer& buffer, int nStackDepth = 0);
KeyValues* MakeCopy(void) const;
void CopySubkeys(KeyValues* pParent) const;
void Clear(void);
enum types_t
{
TYPE_NONE = 0,
TYPE_STRING,
TYPE_INT,
TYPE_FLOAT,
TYPE_PTR,
TYPE_WSTRING,
TYPE_COLOR,
TYPE_UINT64,
TYPE_COMPILED_INT_BYTE,
TYPE_COMPILED_INT_0,
TYPE_COMPILED_INT_1,
TYPE_NUMTYPES,
};
types_t GetDataType(const char* keyName = NULL);
types_t GetDataType() const;
void deleteThis();
void SetStringValue(char const* strValue);
void UnpackIntoStructure(struct KeyValuesUnpackStructure const* pUnpackTable, void* pDest);
bool ProcessResolutionKeys(const char* pResString);
bool Dump(IKeyValuesDumpContext* pDump, int nIndentLevel = 0);
enum MergeKeyValuesOp_t
{
MERGE_KV_ALL,
MERGE_KV_UPDATE,
MERGE_KV_DELETE,
MERGE_KV_BORROW,
};
void MergeFrom(KeyValues* kvMerge, MergeKeyValuesOp_t eOp = MERGE_KV_ALL);
static KeyValues* FromString(char const* szName, char const* szStringVal, char const** ppEndOfParse = NULL);
KeyValues* CreateKeyUsingKnownLastChild(const char* keyName, KeyValues* pLastChild);
void AddSubkeyUsingKnownLastChild(KeyValues* pSubKey, KeyValues* pLastChild);
KeyValues(KeyValues&);
void RecursiveCopyKeyValues(KeyValues& src);
void RemoveEverything();
void RecursiveSaveToFile(IBaseFileSystem* filesystem, FileHandle_t f, CUtlBuffer* pBuf, int indentLevel, bool bWriteEmptySubkeys = false);
void WriteConvertedString(IBaseFileSystem* filesystem, FileHandle_t f, CUtlBuffer* pBuf, const char* pszString);
void RecursiveLoadFromBuffer(char const* resourceName, CUtlBuffer& buf);
void AppendIncludedKeys(CUtlVector< KeyValues* >& includedKeys);
void ParseIncludedKeys(char const* resourceName, const char* filetoinclude,
IBaseFileSystem* pFileSystem, const char* pPathID, CUtlVector< KeyValues* >& includedKeys);
void MergeBaseKeys(CUtlVector< KeyValues* >& baseKeys);
void RecursiveMergeKeyValues(KeyValues* baseKV);
void InternalWrite(IBaseFileSystem* filesystem, FileHandle_t f, CUtlBuffer* pBuf, const void* pData, int len);
void Init();
const char* ReadToken(CUtlBuffer& buf, bool& wasQuoted, bool& wasConditional);
void WriteIndents(IBaseFileSystem* filesystem, FileHandle_t f, CUtlBuffer* pBuf, int indentLevel);
void FreeAllocatedValue();
void AllocateValueBlock(int size);
bool ReadAsBinaryPooledFormat(CUtlBuffer& buf, IBaseFileSystem* pFileSystem, unsigned int poolKey, GetSymbolProc_t pfnEvaluateSymbolProc);
bool EvaluateConditional(const char* str);
uint32 m_iKeyName : 24;
uint32 m_iKeyNameCaseSensitive1 : 8;
char* m_sValue;
wchar_t* m_wsValue;
union
{
int m_iValue;
float m_flValue;
void* m_pValue;
unsigned char m_Color[4];
};
char m_iDataType;
char m_bHasEscapeSequences;
uint16 m_iKeyNameCaseSensitive2;
KeyValues* m_pPeer;
KeyValues* m_pSub;
KeyValues* m_pChain;
GetSymbolProc_t m_pExpressionGetSymbolProc;
private:
static int (*s_pfGetSymbolForString)(const char* name, bool bCreate);
static const char* (*s_pfGetStringForSymbol)(int symbol);
static CKeyValuesGrowableStringTable* s_pGrowableStringTable;
public:
static int GetSymbolForStringClassic(const char* name, bool bCreate = true);
static const char* GetStringForSymbolClassic(int symbol);
static int GetSymbolForStringGrowable(const char* name, bool bCreate = true);
static const char* GetStringForSymbolGrowable(int symbol);
};
typedef KeyValues::AutoDelete KeyValuesAD;
enum KeyValuesUnpackDestinationTypes_t
{
UNPACK_TYPE_FLOAT,
UNPACK_TYPE_VECTOR,
UNPACK_TYPE_VECTOR_COLOR,
UNPACK_TYPE_STRING,
UNPACK_TYPE_INT,
UNPACK_TYPE_FOUR_FLOATS,
UNPACK_TYPE_TWO_FLOATS,
};
#define UNPACK_FIXED( kname, kdefault, dtype, ofs ) { kname, kdefault, dtype, ofs, 0 }
#define UNPACK_VARIABLE( kname, kdefault, dtype, ofs, sz ) { kname, kdefault, dtype, ofs, sz }
#define UNPACK_END_MARKER { NULL, NULL, UNPACK_TYPE_FLOAT, 0 }
struct KeyValuesUnpackStructure
{
char const* m_pKeyName;
char const* m_pKeyDefault;
KeyValuesUnpackDestinationTypes_t m_eDataType;
size_t m_nFieldOffset;
size_t m_nFieldSize;
};
inline int KeyValues::GetInt(int keySymbol, int defaultValue)
{
KeyValues* dat = FindKey(keySymbol);
return dat ? dat->GetInt((const char*)NULL, defaultValue) : defaultValue;
}
inline uint64 KeyValues::GetUint64(int keySymbol, uint64 defaultValue)
{
KeyValues* dat = FindKey(keySymbol);
return dat ? dat->GetUint64((const char*)NULL, defaultValue) : defaultValue;
}
inline float KeyValues::GetFloat(int keySymbol, float defaultValue)
{
KeyValues* dat = FindKey(keySymbol);
return dat ? dat->GetFloat((const char*)NULL, defaultValue) : defaultValue;
}
inline const char* KeyValues::GetString(int keySymbol, const char* defaultValue)
{
KeyValues* dat = FindKey(keySymbol);
return dat ? dat->GetString((const char*)NULL, defaultValue) : defaultValue;
}
inline const wchar_t* KeyValues::GetWString(int keySymbol, const wchar_t* defaultValue)
{
KeyValues* dat = FindKey(keySymbol);
return dat ? dat->GetWString((const char*)NULL, defaultValue) : defaultValue;
}
inline void* KeyValues::GetPtr(int keySymbol, void* defaultValue)
{
KeyValues* dat = FindKey(keySymbol);
return dat ? dat->GetPtr((const char*)NULL, defaultValue) : defaultValue;
}
inline Color KeyValues::GetColor(int keySymbol)
{
Color defaultValue(0, 0, 0, 0);
KeyValues* dat = FindKey(keySymbol);
return dat ? dat->GetColor() : defaultValue;
}
inline bool KeyValues::IsEmpty(int keySymbol)
{
KeyValues* dat = FindKey(keySymbol);
return dat ? dat->IsEmpty() : true;
}
class IKeyValuesDumpContext
{
public:
virtual bool KvBeginKey(KeyValues* pKey, int nIndentLevel) = 0;
virtual bool KvWriteValue(KeyValues* pValue, int nIndentLevel) = 0;
virtual bool KvEndKey(KeyValues* pKey, int nIndentLevel) = 0;
};
class IKeyValuesDumpContextAsText : public IKeyValuesDumpContext
{
public:
virtual bool KvBeginKey(KeyValues* pKey, int nIndentLevel);
virtual bool KvWriteValue(KeyValues* pValue, int nIndentLevel);
virtual bool KvEndKey(KeyValues* pKey, int nIndentLevel);
public:
virtual bool KvWriteIndent(int nIndentLevel);
virtual bool KvWriteText(char const* szText) = 0;
};
class CKeyValuesDumpContextAsDevMsg : public IKeyValuesDumpContextAsText
{
public:
CKeyValuesDumpContextAsDevMsg(int nDeveloperLevel = 1) : m_nDeveloperLevel(nDeveloperLevel) {}
public:
virtual bool KvBeginKey(KeyValues* pKey, int nIndentLevel);
virtual bool KvWriteText(char const* szText);
protected:
int m_nDeveloperLevel;
};
inline bool KeyValuesDumpAsDevMsg(KeyValues* pKeyValues, int nIndentLevel = 0, int nDeveloperLevel = 1)
{
CKeyValuesDumpContextAsDevMsg ctx(nDeveloperLevel);
return pKeyValues->Dump(&ctx, nIndentLevel);
}
#endif

38
SpyCustom/l2cache.h Normal file
View File

@ -0,0 +1,38 @@
#ifndef CL2CACHE_H
#define CL2CACHE_H
#ifdef _WIN32
#pragma once
#endif
class P4Event_BSQ_cache_reference;
class CL2Cache
{
public:
CL2Cache();
~CL2Cache();
void Start(void);
void End(void);
int GetL2CacheMisses(void)
{
return m_iL2CacheMissCount;
}
#ifdef DBGFLAG_VALIDATE
void Validate(CValidator& validator, tchar* pchName);
#endif
private:
int m_nID;
P4Event_BSQ_cache_reference* m_pL2CacheEvent;
int64 m_i64Start;
int64 m_i64End;
int m_iL2CacheMissCount;
};
#endif

157
SpyCustom/lerp_functions.h Normal file
View File

@ -0,0 +1,157 @@
#ifndef LERP_FUNCTIONS_H
#define LERP_FUNCTIONS_H
#ifdef _WIN32
#pragma once
#endif
template <class T>
inline T LoopingLerp(float flPercent, T flFrom, T flTo)
{
T s = flTo * flPercent + flFrom * (1.0f - flPercent);
return s;
}
template <>
inline float LoopingLerp(float flPercent, float flFrom, float flTo)
{
if (fabs(flTo - flFrom) >= 0.5f)
{
if (flFrom < flTo)
flFrom += 1.0f;
else
flTo += 1.0f;
}
float s = flTo * flPercent + flFrom * (1.0f - flPercent);
s = s - (int)(s);
if (s < 0.0f)
s = s + 1.0f;
return s;
}
template <class T>
inline T Lerp_Hermite(const T& , float t, const T& p0, const T& p1, const T& p2)
{
T d1 = p1 - p0;
T d2 = p2 - p1;
T output;
float tSqr = t * t;
float tCube = t * tSqr;
output = p1 * (2 * tCube - 3 * tSqr + 1);
output += p2 * (-2 * tCube + 3 * tSqr);
output += d1 * (tCube - 2 * tSqr + t);
output += d2 * (tCube - tSqr);
return output;
}
template <class T>
inline T Derivative_Hermite(float t, const T& p0, const T& p1, const T& p2)
{
T d1 = p1 - p0;
T d2 = p2 - p1;
T output;
float tSqr = t * t;
output = p1 * (6 * tSqr - 6 * t);
output += p2 * (-6 * tSqr + 6 * t);
output += d1 * (3 * tSqr - 4 * t + 1);
output += d2 * (3 * tSqr - 2 * t);
return output;
}
inline void Lerp_Clamp(int val)
{
}
inline void Lerp_Clamp(float val)
{
}
inline void Lerp_Clamp(const Vector& val)
{
}
inline void Lerp_Clamp(const QAngle& val)
{
}
template< class T, int minValue, int maxValue, int startValue >
inline void Lerp_Clamp(CRangeCheckedVar<T, minValue, maxValue, startValue>& val)
{
val.Clamp();
}
template<>
inline QAngle Lerp_Hermite<QAngle>(const QAngle&, float t, const QAngle& p0, const QAngle& p1, const QAngle& p2)
{
return Lerp(t, p1, p2);
}
template <class T>
inline T LoopingLerp_Hermite(T current, float t, T p0, T p1, T p2)
{
return Lerp_Hermite(current, t, p0, p1, p2);
}
template <>
inline float LoopingLerp_Hermite(float , float t, float p0, float p1, float p2)
{
if (fabs(p1 - p0) > 0.5f)
{
if (p0 < p1)
p0 += 1.0f;
else
p1 += 1.0f;
}
if (fabs(p2 - p1) > 0.5f)
{
if (p1 < p2)
{
p1 += 1.0f;
if (abs(p1 - p0) > 0.5)
{
if (p0 < p1)
p0 += 1.0f;
else
p1 += 1.0f;
}
}
else
{
p2 += 1.0f;
}
}
float s = Lerp_Hermite( 0.0f, t, p0, p1, p2);
s = s - (int)(s);
if (s < 0.0f)
{
s = s + 1.0f;
}
return s;
}
template< int minValue, int maxValue, int startValue >
inline CRangeCheckedVar<float, minValue, maxValue, startValue> LoopingLerp_Hermite(CRangeCheckedVar<float, minValue, maxValue, startValue> current, float t, CRangeCheckedVar<float, minValue, maxValue, startValue> p0, CRangeCheckedVar<float, minValue, maxValue, startValue> p1, CRangeCheckedVar<float, minValue, maxValue, startValue> p2)
{
return LoopingLerp_Hermite((float)current, t, (float)p0, (float)p1, (float)p2);
}
#endif

139
SpyCustom/lightdesc.h Normal file
View File

@ -0,0 +1,139 @@
#ifndef LIGHTDESC_H
#define LIGHTDESC_H
#include "ssemath.h"
#include "vector.h"
enum LightType_t
{
MATERIAL_LIGHT_DISABLE = 0,
MATERIAL_LIGHT_POINT,
MATERIAL_LIGHT_DIRECTIONAL,
MATERIAL_LIGHT_SPOT,
};
enum LightType_OptimizationFlags_t
{
LIGHTTYPE_OPTIMIZATIONFLAGS_HAS_ATTENUATION0 = 1,
LIGHTTYPE_OPTIMIZATIONFLAGS_HAS_ATTENUATION1 = 2,
LIGHTTYPE_OPTIMIZATIONFLAGS_HAS_ATTENUATION2 = 4,
LIGHTTYPE_OPTIMIZATIONFLAGS_DERIVED_VALUES_CALCED = 8,
};
struct LightDesc_t
{
LightType_t m_Type;
Vector m_Color;
Vector m_Position;
Vector m_Direction;
float m_Range;
float m_Falloff;
float m_Attenuation0;
float m_Attenuation1;
float m_Attenuation2;
float m_Theta;
float m_Phi;
float m_ThetaDot;
float m_PhiDot;
unsigned int m_Flags;
protected:
float OneOver_ThetaDot_Minus_PhiDot;
float m_RangeSquared;
public:
void RecalculateDerivedValues(void);
LightDesc_t(void)
{
}
LightDesc_t(const Vector& pos, const Vector& color)
{
InitPoint(pos, color);
}
LightDesc_t(const Vector& pos, const Vector& color, const Vector& point_at,
float inner_cone_boundary, float outer_cone_boundary)
{
InitSpot(pos, color, point_at, inner_cone_boundary, outer_cone_boundary);
}
void InitPoint(const Vector& pos, const Vector& color);
void InitDirectional(const Vector& dir, const Vector& color);
void InitSpot(const Vector& pos, const Vector& color, const Vector& point_at,
float inner_cone_boundary, float outer_cone_boundary);
void ComputeLightAtPoints(const FourVectors& pos, const FourVectors& normal,
FourVectors& color, bool DoHalfLambert = false) const;
void ComputeNonincidenceLightAtPoints(const FourVectors& pos, FourVectors& color) const;
void ComputeLightAtPointsForDirectional(const FourVectors& pos,
const FourVectors& normal,
FourVectors& color, bool DoHalfLambert = false) const;
void SetupOldStyleAttenuation(float fQuadatricAttn, float fLinearAttn, float fConstantAttn);
void SetupNewStyleAttenuation(float fFiftyPercentDistance, float fZeroPercentDistance);
bool IsDirectionWithinLightCone(const Vector& rdir) const
{
return ((m_Type != MATERIAL_LIGHT_SPOT) || (rdir.Dot(m_Direction) >= m_PhiDot));
}
float OneOverThetaDotMinusPhiDot() const
{
return OneOver_ThetaDot_Minus_PhiDot;
}
};
inline void LightDesc_t::InitPoint(const Vector& pos, const Vector& color)
{
m_Type = MATERIAL_LIGHT_POINT;
m_Color = color;
m_Position = pos;
m_Range = 0.0;
m_Attenuation0 = 1.0;
m_Attenuation1 = 0;
m_Attenuation2 = 0;
RecalculateDerivedValues();
}
inline void LightDesc_t::InitDirectional(const Vector& dir, const Vector& color)
{
m_Type = MATERIAL_LIGHT_DIRECTIONAL;
m_Color = color;
m_Direction = dir;
m_Range = 0.0;
m_Attenuation0 = 1.0;
m_Attenuation1 = 0;
m_Attenuation2 = 0;
RecalculateDerivedValues();
}
inline void LightDesc_t::InitSpot(const Vector& pos, const Vector& color, const Vector& point_at,
float inner_cone_boundary, float outer_cone_boundary)
{
m_Type = MATERIAL_LIGHT_SPOT;
m_Color = color;
m_Position = pos;
m_Direction = point_at;
m_Direction -= pos;
VectorNormalizeFast(m_Direction);
m_Falloff = 5.0;
m_Theta = inner_cone_boundary;
m_Phi = outer_cone_boundary;
m_Range = 0.0;
m_Attenuation0 = 1.0;
m_Attenuation1 = 0;
m_Attenuation2 = 0;
RecalculateDerivedValues();
}
#endif

View File

@ -0,0 +1,21 @@
#ifndef LOCALFLEXCONTROLLER_H
#define LOCALFLEXCONTROLLER_H
#ifdef _WIN32
#pragma once
#endif
#include "platform.h"
enum LocalFlexController_t
{
DUMMY_FLEX_CONTROLLER = 0x7fffffff
};
inline LocalFlexController_t& operator++(LocalFlexController_t& a) { return a = LocalFlexController_t(int(a) + 1); }
inline LocalFlexController_t& operator--(LocalFlexController_t& a) { return a = LocalFlexController_t(int(a) - 1); }
inline LocalFlexController_t operator++(LocalFlexController_t& a, int) { LocalFlexController_t t = a; a = LocalFlexController_t(int(a) + 1); return t; }
inline LocalFlexController_t operator--(LocalFlexController_t& a, int) { LocalFlexController_t t = a; a = LocalFlexController_t(int(a) - 1); return t; }
#endif

421
SpyCustom/logging.h Normal file
View File

@ -0,0 +1,421 @@
#ifndef LOGGING_H
#define LOGGING_H
#if !defined(__SPU__)
#if defined( COMPILER_MSVC )
#pragma once
#endif
#include "color.h"
#include "icommandline.h"
#include <stdio.h>
#if defined( _X360 )
#include "xbox/xbox_console.h"
#endif
#if defined( _WIN32 ) || (defined(POSIX) && !defined(_GAMECONSOLE))
#include "win32consoleio.h"
#endif
class CLoggingSystem;
class CThreadFastMutex;
const int MAX_LOGGING_MESSAGE_LENGTH = 2048;
const int MAX_LOGGING_IDENTIFIER_LENGTH = 32;
const int MAX_LOGGING_CHANNEL_COUNT = 256;
const int MAX_LOGGING_TAG_COUNT = 1024;
const int MAX_LOGGING_TAG_CHARACTER_COUNT = 8192;
const int MAX_LOGGING_LISTENER_COUNT = 16;
const Color UNSPECIFIED_LOGGING_COLOR(0, 0, 0, 0);
typedef int LoggingChannelID_t;
const LoggingChannelID_t INVALID_LOGGING_CHANNEL_ID = -1;
enum LoggingSeverity_t
{
LS_MESSAGE = 0,
LS_WARNING = 1,
LS_ASSERT = 2,
LS_ERROR = 3,
LS_HIGHEST_SEVERITY = 4,
};
enum LoggingResponse_t
{
LR_CONTINUE,
LR_DEBUGGER,
LR_ABORT,
};
enum LoggingChannelFlags_t
{
LCF_CONSOLE_ONLY = 0x00000001,
LCF_DO_NOT_ECHO = 0x00000002,
};
typedef void (*RegisterTagsFunc)();
struct LoggingContext_t
{
LoggingChannelID_t m_ChannelID;
LoggingChannelFlags_t m_Flags;
LoggingSeverity_t m_Severity;
Color m_Color;
};
class ILoggingListener
{
public:
virtual void Log(const LoggingContext_t* pContext, const tchar* pMessage) = 0;
};
class ILoggingResponsePolicy
{
public:
virtual LoggingResponse_t OnLog(const LoggingContext_t* pContext) = 0;
};
class CSimpleLoggingListener : public ILoggingListener
{
public:
CSimpleLoggingListener(bool bQuietPrintf = false, bool bQuietDebugger = false) :
m_bQuietPrintf(bQuietPrintf),
m_bQuietDebugger(bQuietDebugger)
{
}
virtual void Log(const LoggingContext_t* pContext, const tchar* pMessage)
{
#ifdef _X360
if (!m_bQuietDebugger && XBX_IsConsoleConnected())
{
XBX_DebugString(XMAKECOLOR(0, 0, 0), pMessage);
}
else
#endif
{
#if !defined( _CERT ) && !defined( DBGFLAG_STRINGS_STRIP )
if (!m_bQuietPrintf)
{
_tprintf(_T("%s"), pMessage);
}
#endif
#ifdef _WIN32
if (!m_bQuietDebugger && Plat_IsInDebugSession())
{
Plat_DebugString(pMessage);
}
#endif
}
}
bool m_bQuietPrintf;
bool m_bQuietDebugger;
};
class CSimpleWindowsLoggingListener : public ILoggingListener
{
public:
virtual void Log(const LoggingContext_t* pContext, const tchar* pMessage)
{
if (Plat_IsInDebugSession())
{
Plat_DebugString(pMessage);
}
if (pContext->m_Severity == LS_ERROR)
{
if (Plat_IsInDebugSession())
DebuggerBreak();
Plat_MessageBox("Error", pMessage);
}
}
};
#if !defined(_GAMECONSOLE)
class CColorizedLoggingListener : public CSimpleLoggingListener
{
public:
CColorizedLoggingListener(bool bQuietPrintf = false, bool bQuietDebugger = false) : CSimpleLoggingListener(bQuietPrintf, bQuietDebugger)
{
InitWin32ConsoleColorContext(&m_ColorContext);
}
virtual void Log(const LoggingContext_t* pContext, const tchar* pMessage)
{
if (!m_bQuietPrintf)
{
int nPrevColor = -1;
if (pContext->m_Color != UNSPECIFIED_LOGGING_COLOR)
{
nPrevColor = SetWin32ConsoleColor(&m_ColorContext,
pContext->m_Color.r(), pContext->m_Color.g(), pContext->m_Color.b(),
MAX(MAX(pContext->m_Color.r(), pContext->m_Color.g()), pContext->m_Color.b()) > 128);
}
_tprintf(_T("%s"), pMessage);
if (nPrevColor >= 0)
{
RestoreWin32ConsoleColor(&m_ColorContext, nPrevColor);
}
}
#ifdef _WIN32
if (!m_bQuietDebugger && Plat_IsInDebugSession())
{
Plat_DebugString(pMessage);
}
#endif
}
Win32ConsoleColorContext_t m_ColorContext;
};
#endif
class CDefaultLoggingResponsePolicy : public ILoggingResponsePolicy
{
public:
virtual LoggingResponse_t OnLog(const LoggingContext_t* pContext)
{
if (pContext->m_Severity == LS_ASSERT && !CommandLine()->FindParm("-noassert"))
{
return LR_DEBUGGER;
}
else if (pContext->m_Severity == LS_ERROR)
{
return LR_ABORT;
}
else
{
return LR_CONTINUE;
}
}
};
class CNonFatalLoggingResponsePolicy : public ILoggingResponsePolicy
{
public:
virtual LoggingResponse_t OnLog(const LoggingContext_t* pContext)
{
if ((pContext->m_Severity == LS_ASSERT && !CommandLine()->FindParm("-noassert")) || pContext->m_Severity == LS_ERROR)
{
return LR_DEBUGGER;
}
else
{
return LR_CONTINUE;
}
}
};
class CLoggingSystem
{
public:
struct LoggingChannel_t;
CLoggingSystem();
~CLoggingSystem();
LoggingChannelID_t RegisterLoggingChannel(const char* pChannelName, RegisterTagsFunc registerTagsFunc, int flags = 0, LoggingSeverity_t minimumSeverity = LS_MESSAGE, Color spewColor = UNSPECIFIED_LOGGING_COLOR);
LoggingChannelID_t FindChannel(const char* pChannelName) const;
int GetChannelCount() const { return m_nChannelCount; }
LoggingChannel_t* GetChannel(LoggingChannelID_t channelID);
const LoggingChannel_t* GetChannel(LoggingChannelID_t channelID) const;
bool HasTag(LoggingChannelID_t channelID, const char* pTag) const { return GetChannel(channelID)->HasTag(pTag); }
bool IsValidChannelID(LoggingChannelID_t channelID) const { return (channelID >= 0) && (channelID < m_nChannelCount); }
bool IsChannelEnabled(LoggingChannelID_t channelID, LoggingSeverity_t severity) const { return IsValidChannelID(channelID) && GetChannel(channelID)->IsEnabled(severity); }
void SetChannelSpewLevel(LoggingChannelID_t channelID, LoggingSeverity_t minimumSeverity);
void SetChannelSpewLevelByName(const char* pName, LoggingSeverity_t minimumSeverity);
void SetChannelSpewLevelByTag(const char* pTag, LoggingSeverity_t minimumSeverity);
void SetGlobalSpewLevel(LoggingSeverity_t minimumSeverity);
Color GetChannelColor(LoggingChannelID_t channelID) const { return GetChannel(channelID)->m_SpewColor; }
void SetChannelColor(LoggingChannelID_t channelID, Color color) { GetChannel(channelID)->m_SpewColor = color; }
LoggingChannelFlags_t GetChannelFlags(LoggingChannelID_t channelID) const { return GetChannel(channelID)->m_Flags; }
void SetChannelFlags(LoggingChannelID_t channelID, LoggingChannelFlags_t flags) { GetChannel(channelID)->m_Flags = flags; }
void AddTagToCurrentChannel(const char* pTagName);
void PushLoggingState(bool bThreadLocal = false, bool bClearState = true);
void PopLoggingState(bool bThreadLocal = false);
void RegisterLoggingListener(ILoggingListener* pListener);
bool IsListenerRegistered(ILoggingListener* pListener);
void ResetCurrentLoggingState();
void SetLoggingResponsePolicy(ILoggingResponsePolicy* pLoggingResponse);
LoggingResponse_t LogDirect(LoggingChannelID_t channelID, LoggingSeverity_t severity, Color color, const tchar* pMessage);
struct LoggingTag_t
{
const char* m_pTagName;
LoggingTag_t* m_pNextTag;
};
struct LoggingChannel_t
{
bool HasTag(const char* pTag) const
{
LoggingTag_t* pCurrentTag = m_pFirstTag;
while (pCurrentTag != NULL)
{
if (stricmp(pCurrentTag->m_pTagName, pTag) == 0)
{
return true;
}
pCurrentTag = pCurrentTag->m_pNextTag;
}
return false;
}
bool IsEnabled(LoggingSeverity_t severity) const { return severity >= m_MinimumSeverity; }
void SetSpewLevel(LoggingSeverity_t severity) { m_MinimumSeverity = severity; }
LoggingChannelID_t m_ID;
LoggingChannelFlags_t m_Flags;
LoggingSeverity_t m_MinimumSeverity;
Color m_SpewColor;
char m_Name[MAX_LOGGING_IDENTIFIER_LENGTH];
LoggingTag_t* m_pFirstTag;
};
private:
struct LoggingState_t
{
int m_nPreviousStackEntry;
int m_nListenerCount;
ILoggingListener* m_RegisteredListeners[MAX_LOGGING_LISTENER_COUNT];
ILoggingResponsePolicy* m_pLoggingResponse;
};
LoggingState_t* GetCurrentState();
const LoggingState_t* GetCurrentState() const;
int FindUnusedStateIndex();
LoggingTag_t* AllocTag(const char* pTagName);
int m_nChannelCount;
LoggingChannel_t m_RegisteredChannels[MAX_LOGGING_CHANNEL_COUNT];
int m_nChannelTagCount;
LoggingTag_t m_ChannelTags[MAX_LOGGING_TAG_COUNT];
int m_nTagNamePoolIndex;
char m_TagNamePool[MAX_LOGGING_TAG_CHARACTER_COUNT];
CThreadFastMutex* m_pStateMutex;
int m_nGlobalStateIndex;
static const int MAX_LOGGING_STATE_COUNT = 16;
LoggingState_t m_LoggingStates[MAX_LOGGING_STATE_COUNT];
CDefaultLoggingResponsePolicy m_DefaultLoggingResponse;
CSimpleLoggingListener m_DefaultLoggingListener;
};
#ifdef DBGFLAG_STRINGS_STRIP
#define InternalMsg( Channel, Severity, ... ) do { if ( Severity == LS_ERROR && LoggingSystem_IsChannelEnabled( Channel, Severity ) ) LoggingSystem_Log( Channel, Severity, ##__VA_ARGS__ ); } while( 0 )
#else
#define InternalMsg( Channel, Severity, ... ) do { if ( LoggingSystem_IsChannelEnabled( Channel, Severity ) ) LoggingSystem_Log( Channel, Severity, ##__VA_ARGS__ ); } while( 0 )
#endif
#define Log_Msg( Channel, ... ) InternalMsg( Channel, LS_MESSAGE, ##__VA_ARGS__ )
#define Log_Warning( Channel, ... ) InternalMsg( Channel, LS_WARNING, ##__VA_ARGS__ )
#define Log_Error( Channel, ... ) InternalMsg( Channel, LS_ERROR, ##__VA_ARGS__ )
#ifdef DBGFLAG_STRINGS_STRIP
#define Log_Assert( ... ) LR_CONTINUE
#else
#define Log_Assert( Message, ... ) LoggingSystem_LogAssert( Message, ##__VA_ARGS__ )
#endif
#define DECLARE_LOGGING_CHANNEL( Channel ) extern LoggingChannelID_t Channel
#define DEFINE_LOGGING_CHANNEL_NO_TAGS( Channel, ChannelName, ... ) \
LoggingChannelID_t Channel = LoggingSystem_RegisterLoggingChannel( ChannelName, NULL, ##__VA_ARGS__ )
#define BEGIN_DEFINE_LOGGING_CHANNEL( Channel, ChannelName, ... ) \
static void Register_##Channel##_Tags(); \
LoggingChannelID_t Channel = LoggingSystem_RegisterLoggingChannel( ChannelName, Register_##Channel##_Tags, ##__VA_ARGS__ ); \
void Register_##Channel##_Tags() \
{
#define ADD_LOGGING_CHANNEL_TAG( Tag ) LoggingSystem_AddTagToCurrentChannel( Tag )
#define END_DEFINE_LOGGING_CHANNEL() \
}
PLATFORM_INTERFACE LoggingChannelID_t LoggingSystem_RegisterLoggingChannel(const char* pName, RegisterTagsFunc registerTagsFunc, int flags = 0, LoggingSeverity_t severity = LS_MESSAGE, Color color = UNSPECIFIED_LOGGING_COLOR);
PLATFORM_INTERFACE void LoggingSystem_RegisterLoggingListener(ILoggingListener* pListener);
PLATFORM_INTERFACE void LoggingSystem_UnregisterLoggingListener(ILoggingListener* pListener);
PLATFORM_INTERFACE void LoggingSystem_ResetCurrentLoggingState();
PLATFORM_INTERFACE void LoggingSystem_SetLoggingResponsePolicy(ILoggingResponsePolicy* pResponsePolicy);
PLATFORM_INTERFACE void LoggingSystem_PushLoggingState(bool bThreadLocal = false, bool bClearState = true);
PLATFORM_INTERFACE void LoggingSystem_PopLoggingState(bool bThreadLocal = false);
PLATFORM_INTERFACE void LoggingSystem_AddTagToCurrentChannel(const char* pTagName);
PLATFORM_INTERFACE LoggingChannelID_t LoggingSystem_FindChannel(const char* pChannelName);
PLATFORM_INTERFACE int LoggingSystem_GetChannelCount();
PLATFORM_INTERFACE LoggingChannelID_t LoggingSystem_GetFirstChannelID();
PLATFORM_INTERFACE LoggingChannelID_t LoggingSystem_GetNextChannelID(LoggingChannelID_t channelID);
PLATFORM_INTERFACE const CLoggingSystem::LoggingChannel_t* LoggingSystem_GetChannel(LoggingChannelID_t channelID);
PLATFORM_INTERFACE bool LoggingSystem_HasTag(LoggingChannelID_t channelID, const char* pTag);
PLATFORM_INTERFACE bool LoggingSystem_IsChannelEnabled(LoggingChannelID_t channelID, LoggingSeverity_t severity);
PLATFORM_INTERFACE void LoggingSystem_SetChannelSpewLevel(LoggingChannelID_t channelID, LoggingSeverity_t minimumSeverity);
PLATFORM_INTERFACE void LoggingSystem_SetChannelSpewLevelByName(const char* pName, LoggingSeverity_t minimumSeverity);
PLATFORM_INTERFACE void LoggingSystem_SetChannelSpewLevelByTag(const char* pTag, LoggingSeverity_t minimumSeverity);
PLATFORM_INTERFACE void LoggingSystem_SetGlobalSpewLevel(LoggingSeverity_t minimumSeverity);
PLATFORM_INTERFACE int32 LoggingSystem_GetChannelColor(LoggingChannelID_t channelID);
PLATFORM_INTERFACE void LoggingSystem_SetChannelColor(LoggingChannelID_t channelID, int color);
PLATFORM_INTERFACE LoggingChannelFlags_t LoggingSystem_GetChannelFlags(LoggingChannelID_t channelID);
PLATFORM_INTERFACE void LoggingSystem_SetChannelFlags(LoggingChannelID_t channelID, LoggingChannelFlags_t flags);
PLATFORM_INTERFACE LoggingResponse_t LoggingSystem_Log(LoggingChannelID_t channelID, LoggingSeverity_t severity, PRINTF_FORMAT_STRING const char* pMessageFormat, ...) FMTFUNCTION(3, 4);
PLATFORM_OVERLOAD LoggingResponse_t LoggingSystem_Log(LoggingChannelID_t channelID, LoggingSeverity_t severity, Color spewColor, PRINTF_FORMAT_STRING const char* pMessageFormat, ...) FMTFUNCTION(4, 5);
PLATFORM_INTERFACE LoggingResponse_t LoggingSystem_LogDirect(LoggingChannelID_t channelID, LoggingSeverity_t severity, Color spewColor, const char* pMessage);
PLATFORM_INTERFACE LoggingResponse_t LoggingSystem_LogAssert(PRINTF_FORMAT_STRING const char* pMessageFormat, ...) FMTFUNCTION(1, 2);
#endif
#endif

66
SpyCustom/math_pfns.h Normal file
View File

@ -0,0 +1,66 @@
#ifndef _MATH_PFNS_H_
#define _MATH_PFNS_H_
#if defined( _X360 )
#include <xboxmath.h>
#endif
#if !defined( _X360 )
extern float (*pfSqrt)(float x);
extern float (*pfRSqrt)(float x);
extern float (*pfRSqrtFast)(float x);
extern void (*pfFastSinCos)(float x, float* s, float* c);
extern float (*pfFastCos)(float x);
#define FastSqrt(x) (*pfSqrt)(x)
#define FastRSqrt(x) (*pfRSqrt)(x)
#define FastRSqrtFast(x) (*pfRSqrtFast)(x)
#define FastSinCos(x,s,c) (*pfFastSinCos)(x,s,c)
#define FastCos(x) (*pfFastCos)(x)
#if defined(__i386__) || defined(_M_IX86)
#undef FastSqrt
#define FastSqrt(x) ::sqrtf(x)
#endif
#endif
#if defined( _X360 )
FORCEINLINE float _VMX_Sqrt(float x)
{
return __fsqrts(x);
}
FORCEINLINE float _VMX_RSqrt(float x)
{
float rroot = __frsqrte(x);
return (0.5f * rroot) * (3.0f - (x * rroot) * rroot);
}
FORCEINLINE float _VMX_RSqrtFast(float x)
{
return __frsqrte(x);
}
FORCEINLINE void _VMX_SinCos(float a, float* pS, float* pC)
{
XMScalarSinCos(pS, pC, a);
}
FORCEINLINE float _VMX_Cos(float a)
{
return XMScalarCos(a);
}
#define FastSqrt(x) _VMX_Sqrt(x)
#define FastRSqrt(x) _VMX_RSqrt(x)
#define FastRSqrtFast(x) _VMX_RSqrtFast(x)
#define FastSinCos(x,s,c) _VMX_SinCos(x,s,c)
#define FastCos(x) _VMX_Cos(x)
#endif
#endif

1785
SpyCustom/mathlib.h Normal file

File diff suppressed because it is too large Load Diff

40
SpyCustom/mem.h Normal file
View File

@ -0,0 +1,40 @@
#ifndef TIER0_MEM_H
#define TIER0_MEM_H
#ifdef _WIN32
#pragma once
#endif
#include <stddef.h>
#ifdef LINUX
#undef offsetof
#define offsetof(s,m) (size_t)&(((s *)0)->m)
#endif
#include "platform.h"
#if !defined(STATIC_TIER0) && !defined(_STATIC_LINKED)
#ifdef TIER0_DLL_EXPORT
# define MEM_INTERFACE DLL_EXPORT
#else
# define MEM_INTERFACE DLL_IMPORT
#endif
#else
#define MEM_INTERFACE extern
#endif
MEM_INTERFACE void* MemAllocScratch(int nMemSize);
MEM_INTERFACE void MemFreeScratch();
#ifdef _LINUX
MEM_INTERFACE void ZeroMemory(void* mem, size_t length);
#endif
#endif

567
SpyCustom/memalloc.h Normal file
View File

@ -0,0 +1,567 @@
#ifndef TIER0_MEMALLOC_H
#define TIER0_MEMALLOC_H
#ifdef _WIN32
#pragma once
#endif
#ifndef POSIX
#endif
#if defined( _MEMTEST )
#ifdef _WIN32
#define USE_MEM_DEBUG 1
#endif
#endif
#define MEM_DEBUG_CLASSNAME 1
#include <stddef.h>
#if defined( OSX )
#include <malloc/malloc.h>
#endif
#include "mem.h"
#if !defined(STEAM) && !defined(NO_MALLOC_OVERRIDE)
struct _CrtMemState;
#define MEMALLOC_VERSION 1
typedef size_t(*MemAllocFailHandler_t)(size_t);
class IMemAlloc
{
public:
virtual void* Alloc(size_t nSize) = 0;
virtual void* Realloc(void* pMem, size_t nSize) = 0;
virtual void Free(void* pMem) = 0;
virtual void* Expand_NoLongerSupported(void* pMem, size_t nSize) = 0;
virtual void* Alloc(size_t nSize, const char* pFileName, int nLine) = 0;
virtual void* Realloc(void* pMem, size_t nSize, const char* pFileName, int nLine) = 0;
virtual void Free(void* pMem, const char* pFileName, int nLine) = 0;
virtual void* Expand_NoLongerSupported(void* pMem, size_t nSize, const char* pFileName, int nLine) = 0;
virtual size_t GetSize(void* pMem) = 0;
virtual void PushAllocDbgInfo(const char* pFileName, int nLine) = 0;
virtual void PopAllocDbgInfo() = 0;
virtual long CrtSetBreakAlloc(long lNewBreakAlloc) = 0;
virtual int CrtSetReportMode(int nReportType, int nReportMode) = 0;
virtual int CrtIsValidHeapPointer(const void* pMem) = 0;
virtual int CrtIsValidPointer(const void* pMem, unsigned int size, int access) = 0;
virtual int CrtCheckMemory(void) = 0;
virtual int CrtSetDbgFlag(int nNewFlag) = 0;
virtual void CrtMemCheckpoint(_CrtMemState* pState) = 0;
virtual void DumpStats() = 0;
virtual void DumpStatsFileBase(char const* pchFileBase) = 0;
virtual void* CrtSetReportFile(int nRptType, void* hFile) = 0;
virtual void* CrtSetReportHook(void* pfnNewHook) = 0;
virtual int CrtDbgReport(int nRptType, const char* szFile,
int nLine, const char* szModule, const char* pMsg) = 0;
virtual int heapchk() = 0;
virtual bool IsDebugHeap() = 0;
virtual void GetActualDbgInfo(const char*& pFileName, int& nLine) = 0;
virtual void RegisterAllocation(const char* pFileName, int nLine, int nLogicalSize, int nActualSize, unsigned nTime) = 0;
virtual void RegisterDeallocation(const char* pFileName, int nLine, int nLogicalSize, int nActualSize, unsigned nTime) = 0;
virtual int GetVersion() = 0;
virtual void CompactHeap() = 0;
virtual MemAllocFailHandler_t SetAllocFailHandler(MemAllocFailHandler_t pfnMemAllocFailHandler) = 0;
virtual void DumpBlockStats(void*) = 0;
#if defined( _MEMTEST )
virtual void SetStatsExtraInfo(const char* pMapName, const char* pComment) = 0;
#endif
virtual size_t MemoryAllocFailed() = 0;
virtual uint32 GetDebugInfoSize() = 0;
virtual void SaveDebugInfo(void* pvDebugInfo) = 0;
virtual void RestoreDebugInfo(const void* pvDebugInfo) = 0;
virtual void InitDebugInfo(void* pvDebugInfo, const char* pchRootFileName, int nLine) = 0;
virtual void GlobalMemoryStatus(size_t* pUsedMemory, size_t* pFreeMemory) = 0;
};
MEM_INTERFACE IMemAlloc* g_pMemAlloc;
#ifdef MEMALLOC_REGIONS
#ifndef MEMALLOC_REGION
#define MEMALLOC_REGION 0
#endif
inline void* MemAlloc_Alloc(size_t nSize)
{
return g_pMemAlloc->RegionAlloc(MEMALLOC_REGION, nSize);
}
inline void* MemAlloc_Alloc(size_t nSize, const char* pFileName, int nLine)
{
return g_pMemAlloc->RegionAlloc(MEMALLOC_REGION, nSize, pFileName, nLine);
}
#else
#undef MEMALLOC_REGION
inline void* MemAlloc_Alloc(size_t nSize)
{
return g_pMemAlloc->Alloc(nSize);
}
inline void* MemAlloc_Alloc(size_t nSize, const char* pFileName, int nLine)
{
return g_pMemAlloc->Alloc(nSize, pFileName, nLine);
}
#endif
inline void MemAlloc_Free(void* ptr)
{
g_pMemAlloc->Free(ptr);
}
inline void MemAlloc_Free(void* ptr, const char* pFileName, int nLine)
{
g_pMemAlloc->Free(ptr, pFileName, nLine);
}
inline bool ValueIsPowerOfTwo(size_t value)
{
return (value & (value - 1)) == 0;
}
inline void* MemAlloc_AllocAligned(size_t size, size_t align)
{
unsigned char* pAlloc, * pResult;
if (!IsPowerOfTwo(align))
return NULL;
align = (align > sizeof(void*) ? align : sizeof(void*)) - 1;
if ((pAlloc = (unsigned char*)g_pMemAlloc->Alloc(sizeof(void*) + align + size)) == (unsigned char*)NULL)
return NULL;
pResult = (unsigned char*)((size_t)(pAlloc + sizeof(void*) + align) & ~align);
((unsigned char**)(pResult))[-1] = pAlloc;
return (void*)pResult;
}
inline void* MemAlloc_AllocAligned(size_t size, size_t align, const char* pszFile, int nLine)
{
unsigned char* pAlloc, * pResult;
if (!IsPowerOfTwo(align))
return NULL;
align = (align > sizeof(void*) ? align : sizeof(void*)) - 1;
if ((pAlloc = (unsigned char*)g_pMemAlloc->Alloc(sizeof(void*) + align + size, pszFile, nLine)) == (unsigned char*)NULL)
return NULL;
pResult = (unsigned char*)((size_t)(pAlloc + sizeof(void*) + align) & ~align);
((unsigned char**)(pResult))[-1] = pAlloc;
return (void*)pResult;
}
inline void* MemAlloc_AllocAlignedUnattributed(size_t size, size_t align)
{
unsigned char* pAlloc, * pResult;
if (!ValueIsPowerOfTwo(align))
return NULL;
align = (align > sizeof(void*) ? align : sizeof(void*)) - 1;
if ((pAlloc = (unsigned char*)MemAlloc_Alloc(sizeof(void*) + align + size)) == (unsigned char*)NULL)
return NULL;
pResult = (unsigned char*)((size_t)(pAlloc + sizeof(void*) + align) & ~align);
((unsigned char**)(pResult))[-1] = pAlloc;
return (void*)pResult;
}
inline void* MemAlloc_AllocAlignedFileLine(size_t size, size_t align, const char* pszFile, int nLine)
{
unsigned char* pAlloc, * pResult;
if (!ValueIsPowerOfTwo(align))
return NULL;
align = (align > sizeof(void*) ? align : sizeof(void*)) - 1;
if ((pAlloc = (unsigned char*)MemAlloc_Alloc(sizeof(void*) + align + size, pszFile, nLine)) == (unsigned char*)NULL)
return NULL;
pResult = (unsigned char*)((size_t)(pAlloc + sizeof(void*) + align) & ~align);
((unsigned char**)(pResult))[-1] = pAlloc;
return (void*)pResult;
}
inline void* MemAlloc_ReallocAligned(void* ptr, size_t size, size_t align)
{
if (!IsPowerOfTwo(align))
return NULL;
if (((size_t)ptr & (align - 1)) != 0)
return NULL;
if (!ptr)
return MemAlloc_AllocAligned(size, align);
void* pAlloc, * pResult;
pAlloc = ptr;
pAlloc = (void*)(((size_t)pAlloc & ~(sizeof(void*) - 1)) - sizeof(void*));
pAlloc = *((void**)pAlloc);
size_t nOffset = (size_t)ptr - (size_t)pAlloc;
size_t nOldSize = g_pMemAlloc->GetSize(pAlloc);
if (nOldSize >= size + nOffset)
return ptr;
pResult = MemAlloc_AllocAligned(size, align);
memcpy(pResult, ptr, nOldSize - nOffset);
g_pMemAlloc->Free(pAlloc);
return pResult;
}
inline void MemAlloc_FreeAligned(void* pMemBlock)
{
void* pAlloc;
if (pMemBlock == NULL)
return;
pAlloc = pMemBlock;
pAlloc = (void*)(((size_t)pAlloc & ~(sizeof(void*) - 1)) - sizeof(void*));
pAlloc = *((void**)pAlloc);
g_pMemAlloc->Free(pAlloc);
}
inline void MemAlloc_FreeAligned(void* pMemBlock, const char* pFileName, int nLine)
{
void* pAlloc;
if (pMemBlock == NULL)
return;
pAlloc = pMemBlock;
pAlloc = (void*)(((size_t)pAlloc & ~(sizeof(void*) - 1)) - sizeof(void*));
pAlloc = *((void**)pAlloc);
g_pMemAlloc->Free(pAlloc, pFileName, nLine);
}
inline size_t MemAlloc_GetSizeAligned(void* pMemBlock)
{
void* pAlloc;
if (pMemBlock == NULL)
return 0;
pAlloc = pMemBlock;
pAlloc = (void*)(((size_t)pAlloc & ~(sizeof(void*) - 1)) - sizeof(void*));
pAlloc = *((void**)pAlloc);
return g_pMemAlloc->GetSize(pAlloc) - ((byte*)pMemBlock - (byte*)pAlloc);
}
#if (defined(_DEBUG) || defined(USE_MEM_DEBUG))
#define MEM_ALLOC_CREDIT_(tag) CMemAllocAttributeAlloction memAllocAttributeAlloction( tag, __LINE__ )
#define MemAlloc_PushAllocDbgInfo( pszFile, line ) g_pMemAlloc->PushAllocDbgInfo( pszFile, line )
#define MemAlloc_PopAllocDbgInfo() g_pMemAlloc->PopAllocDbgInfo()
#define MemAlloc_RegisterAllocation( pFileName, nLine, nLogicalSize, nActualSize, nTime ) g_pMemAlloc->RegisterAllocation( pFileName, nLine, nLogicalSize, nActualSize, nTime )
#define MemAlloc_RegisterDeallocation( pFileName, nLine, nLogicalSize, nActualSize, nTime ) g_pMemAlloc->RegisterDeallocation( pFileName, nLine, nLogicalSize, nActualSize, nTime )
#else
#define MEM_ALLOC_CREDIT_(tag) ((void)0)
#define MemAlloc_PushAllocDbgInfo( pszFile, line ) ((void)0)
#define MemAlloc_PopAllocDbgInfo() ((void)0)
#define MemAlloc_RegisterAllocation( pFileName, nLine, nLogicalSize, nActualSize, nTime ) ((void)0)
#define MemAlloc_RegisterDeallocation( pFileName, nLine, nLogicalSize, nActualSize, nTime ) ((void)0)
#endif
#define MemAlloc_DumpStats() g_pMemAlloc->DumpStats()
#define MemAlloc_CompactHeap() g_pMemAlloc->CompactHeap()
#define MemAlloc_OutOfMemory() g_pMemAlloc->OutOfMemory()
#define MemAlloc_CompactIncremental() g_pMemAlloc->CompactIncremental()
#define MemAlloc_DumpStatsFileBase( _filename ) g_pMemAlloc->DumpStatsFileBase( _filename )
#define MemAlloc_CrtCheckMemory() g_pMemAlloc->CrtCheckMemory()
#define MemAlloc_GlobalMemoryStatus( _usedMemory, _freeMemory ) g_pMemAlloc->GlobalMemoryStatus( _usedMemory, _freeMemory )
#define MemAlloc_MemoryAllocFailed() g_pMemAlloc->MemoryAllocFailed()
#define MemAlloc_GetDebugInfoSize() g_pMemAlloc->GetDebugInfoSize()
#define MemAlloc_SaveDebugInfo( pvDebugInfo ) g_pMemAlloc->SaveDebugInfo( pvDebugInfo )
#define MemAlloc_RestoreDebugInfo( pvDebugInfo ) g_pMemAlloc->RestoreDebugInfo( pvDebugInfo )
#define MemAlloc_InitDebugInfo( pvDebugInfo, pchRootFileName, nLine ) g_pMemAlloc->InitDebugInfo( pvDebugInfo, pchRootFileName, nLine )
#define MemAlloc_GetSize( x ) g_pMemAlloc->GetSize( x );
class CMemAllocAttributeAlloction
{
public:
CMemAllocAttributeAlloction(const char* pszFile, int line)
{
MemAlloc_PushAllocDbgInfo(pszFile, line);
}
~CMemAllocAttributeAlloction()
{
MemAlloc_PopAllocDbgInfo();
}
};
#define MEM_ALLOC_CREDIT() MEM_ALLOC_CREDIT_(__FILE__)
#if defined(_WIN32) && ( defined(_DEBUG) || defined(USE_MEM_DEBUG) )
#pragma warning(disable:4290)
#pragma warning(push)
#include <typeinfo>
#if defined(_CPPRTTI) && defined(MEM_DEBUG_CLASSNAME)
#define MEM_ALLOC_CREDIT_CLASS() MEM_ALLOC_CREDIT_( typeid(*this).name() )
#define MEM_ALLOC_CLASSNAME(type) (typeid((type*)(0)).name())
#else
#define MEM_ALLOC_CREDIT_CLASS() MEM_ALLOC_CREDIT_( __FILE__ )
#define MEM_ALLOC_CLASSNAME(type) (__FILE__)
#endif
#ifdef _MSC_VER
#define MEM_ALLOC_CREDIT_FUNCTION() MEM_ALLOC_CREDIT_( __FUNCTION__ )
#else
#define MEM_ALLOC_CREDIT_FUNCTION() (__FILE__)
#endif
#pragma warning(pop)
#else
#define MEM_ALLOC_CREDIT_CLASS()
#define MEM_ALLOC_CLASSNAME(type) NULL
#define MEM_ALLOC_CREDIT_FUNCTION()
#endif
#if (defined(_DEBUG) || defined(USE_MEM_DEBUG))
struct MemAllocFileLine_t
{
const char* pszFile;
int line;
};
#define MEMALLOC_DEFINE_EXTERNAL_TRACKING( tag ) \
static CUtlMap<void *, MemAllocFileLine_t, int> g_##tag##Allocs( DefLessFunc( void *) ); \
static const char *g_psz##tag##Alloc = strcpy( (char *)g_pMemAlloc->Alloc( strlen( #tag "Alloc" ) + 1, "intentional leak", 0 ), #tag "Alloc" );
#define MemAlloc_RegisterExternalAllocation( tag, p, size ) \
if ( !p ) \
; \
else \
{ \
MemAllocFileLine_t fileLine = { g_psz##tag##Alloc, 0 }; \
g_pMemAlloc->GetActualDbgInfo( fileLine.pszFile, fileLine.line ); \
if ( fileLine.pszFile != g_psz##tag##Alloc ) \
{ \
g_##tag##Allocs.Insert( p, fileLine ); \
} \
\
MemAlloc_RegisterAllocation( fileLine.pszFile, fileLine.line, size, size, 0); \
}
#define MemAlloc_RegisterExternalDeallocation( tag, p, size ) \
if ( !p ) \
; \
else \
{ \
MemAllocFileLine_t fileLine = { g_psz##tag##Alloc, 0 }; \
CUtlMap<void *, MemAllocFileLine_t, int>::IndexType_t iRecordedFileLine = g_##tag##Allocs.Find( p ); \
if ( iRecordedFileLine != g_##tag##Allocs.InvalidIndex() ) \
{ \
fileLine = g_##tag##Allocs[iRecordedFileLine]; \
g_##tag##Allocs.RemoveAt( iRecordedFileLine ); \
} \
\
MemAlloc_RegisterDeallocation( fileLine.pszFile, fileLine.line, size, size, 0); \
}
#else
#define MEMALLOC_DEFINE_EXTERNAL_TRACKING( tag )
#define MemAlloc_RegisterExternalAllocation( tag, p, size ) ((void)0)
#define MemAlloc_RegisterExternalDeallocation( tag, p, size ) ((void)0)
#endif
#elif defined( POSIX )
#if defined( OSX )
inline void* memalign(size_t alignment, size_t size) { void* pTmp = NULL; pTmp = malloc(size); return pTmp; }
#endif
inline void* _aligned_malloc(size_t nSize, size_t align) { return memalign(align, nSize); }
inline void _aligned_free(void* ptr) { free(ptr); }
inline void* MemAlloc_Alloc(size_t nSize, const char* pFileName = NULL, int nLine = 0) { return malloc(nSize); }
inline void MemAlloc_Free(void* ptr, const char* pFileName = NULL, int nLine = 0) { free(ptr); }
inline void* MemAlloc_AllocAligned(size_t size, size_t align, const char* pszFile = NULL, int nLine = 0) { return memalign(align, size); }
inline void* MemAlloc_AllocAlignedFileLine(size_t size, size_t align, const char* pszFile = NULL, int nLine = 0) { return memalign(align, size); }
inline void MemAlloc_FreeAligned(void* pMemBlock, const char* pszFile = NULL, int nLine = 0) { free(pMemBlock); }
#if defined( OSX )
inline size_t _msize(void* ptr) { return malloc_size(ptr); }
#else
inline size_t _msize(void* ptr) { return malloc_usable_size(ptr); }
#endif
inline void* MemAlloc_ReallocAligned(void* ptr, size_t size, size_t align)
{
void* ptr_new_aligned = memalign(align, size);
if (ptr_new_aligned)
{
size_t old_size = _msize(ptr);
size_t copy_size = (size < old_size) ? size : old_size;
memcpy(ptr_new_aligned, ptr, copy_size);
free(ptr);
}
return ptr_new_aligned;
}
#else
#define MemAlloc_GetDebugInfoSize() g_pMemAlloc->GetDebugInfoSize()
#define MemAlloc_SaveDebugInfo( pvDebugInfo ) g_pMemAlloc->SaveDebugInfo( pvDebugInfo )
#define MemAlloc_RestoreDebugInfo( pvDebugInfo ) g_pMemAlloc->RestoreDebugInfo( pvDebugInfo )
#define MemAlloc_InitDebugInfo( pvDebugInfo, pchRootFileName, nLine ) g_pMemAlloc->InitDebugInfo( pvDebugInfo, pchRootFileName, nLine )
#endif
#if !defined(STEAM) && defined(NO_MALLOC_OVERRIDE)
#define MEM_ALLOC_CREDIT_(tag) ((void)0)
#define MEM_ALLOC_CREDIT() MEM_ALLOC_CREDIT_(__FILE__)
#define MEM_ALLOC_CREDIT_FUNCTION()
#define MEM_ALLOC_CREDIT_CLASS()
#define MEM_ALLOC_CLASSNAME(type) NULL
#define MemAlloc_PushAllocDbgInfo( pszFile, line )
#define MemAlloc_PopAllocDbgInfo()
#define MemAlloc_RegisterAllocation( pFileName, nLine, nLogicalSize, nActualSize, nTime ) ((void)0)
#define MemAlloc_RegisterDeallocation( pFileName, nLine, nLogicalSize, nActualSize, nTime ) ((void)0)
#define MemAlloc_DumpStats() ((void)0)
#define MemAlloc_CompactHeap() ((void)0)
#define MemAlloc_OutOfMemory() ((void)0)
#define MemAlloc_CompactIncremental() ((void)0)
#define MemAlloc_DumpStatsFileBase( _filename ) ((void)0)
inline bool MemAlloc_CrtCheckMemory() { return true; }
inline void MemAlloc_GlobalMemoryStatus(size_t* pusedMemory, size_t* pfreeMemory)
{
*pusedMemory = 0;
*pfreeMemory = 0;
}
#define MemAlloc_MemoryAllocFailed() 0
#define MemAlloc_GetDebugInfoSize() 0
#define MemAlloc_SaveDebugInfo( pvDebugInfo ) ((void)0)
#define MemAlloc_RestoreDebugInfo( pvDebugInfo ) ((void)0)
#define MemAlloc_InitDebugInfo( pvDebugInfo, pchRootFileName, nLine ) ((void)0)
#define MEMALLOC_DEFINE_EXTERNAL_TRACKING( tag )
#define MemAlloc_RegisterExternalAllocation( tag, p, size ) ((void)0)
#define MemAlloc_RegisterExternalDeallocation( tag, p, size ) ((void)0)
#endif
#if defined( POSIX ) && !defined( NO_HOOK_MALLOC )
PLATFORM_INTERFACE void MemoryLogMessage(char const* s);
PLATFORM_INTERFACE void EnableMemoryLogging(bool bOnOff);
PLATFORM_INTERFACE void DumpMemoryLog(int nThresh);
PLATFORM_INTERFACE void DumpMemorySummary(void);
PLATFORM_INTERFACE void SetMemoryMark(void);
PLATFORM_INTERFACE void DumpChangedMemory(int nThresh);
#else
FORCEINLINE void MemoryLogMessage(char const* s)
{
}
FORCEINLINE void EnableMemoryLogging(bool bOnOff)
{
}
FORCEINLINE void DumpMemoryLog(int nThresh)
{
}
FORCEINLINE void DumpMemorySummary(void)
{
}
FORCEINLINE void SetMemoryMark(void)
{
}
FORCEINLINE void DumpChangedMemory(int nThresh)
{
}
#endif
#ifdef POSIX
PLATFORM_INTERFACE size_t ApproximateProcessMemoryUsage(void);
#else
FORCEINLINE size_t ApproximateProcessMemoryUsage(void)
{
return 0;
}
#endif
struct aligned_tmp_t
{
};
template< int bytesAlignment = 16, class T = aligned_tmp_t >
class CAlignedNewDelete : public T
{
public:
void* operator new(size_t nSize)
{
return MemAlloc_AllocAligned(nSize, bytesAlignment);
}
void* operator new(size_t nSize, int nBlockUse, const char* pFileName, int nLine)
{
return MemAlloc_AllocAlignedFileLine(nSize, bytesAlignment, pFileName, nLine);
}
void operator delete(void* pData)
{
if (pData)
{
MemAlloc_FreeAligned(pData);
}
}
void operator delete(void* pData, int nBlockUse, const char* pFileName, int nLine)
{
if (pData)
{
MemAlloc_FreeAligned(pData, pFileName, nLine);
}
}
};
#endif

16
SpyCustom/memdbgoff.h Normal file
View File

@ -0,0 +1,16 @@
#ifdef MEM_OVERRIDE_ON
#undef malloc
#undef realloc
#undef calloc
#undef free
#undef _expand
#undef _msize
#undef new
#undef _aligned_malloc
#undef _aligned_free
#undef _malloc_dbg
#undef MEM_OVERRIDE_ON
#endif

219
SpyCustom/memdbgon.h Normal file
View File

@ -0,0 +1,219 @@
#if !defined(STEAM) && !defined(NO_MALLOC_OVERRIDE)
#if defined(_DEBUG) && !defined(USE_MEM_DEBUG)
#define USE_MEM_DEBUG 1
#endif
#if defined(NO_HOOK_MALLOC)
#undef USE_MEM_DEBUG
#endif
#if (defined(_DEBUG) || !defined(_INC_CRTDBG)) || defined(MEMDBGON_H)
#include "basetypes.h"
#ifdef _WIN32
#include <tchar.h>
#else
#include <wchar.h>
#endif
#include <string.h>
#include <malloc.h>
#include "commonmacros.h"
#include "memalloc.h"
#if defined(USE_MEM_DEBUG)
#if defined( POSIX )
#define _NORMAL_BLOCK 1
#include <cstddef>
#include <glob.h>
#include <new>
#include <sys/types.h>
#if !defined( DID_THE_OPERATOR_NEW )
#define DID_THE_OPERATOR_NEW
void* operator new(size_t nSize, int blah, const char* pFileName, int nLine);
void* operator new[](size_t nSize, int blah, const char* pFileName, int nLine);
#endif
#else
#if !defined(_DEBUG)
#define _DEBUG 1
#include <crtdbg.h>
#undef _DEBUG
#else
#include <crtdbg.h>
#endif
#endif
#endif
#include "memdbgoff.h"
#define MEM_OVERRIDE_ON 1
#undef malloc
#undef realloc
#undef calloc
#undef _expand
#undef free
#undef _msize
#undef _aligned_malloc
#undef _aligned_free
#ifndef MEMDBGON_H
inline void* MemAlloc_InlineCallocMemset(void* pMem, size_t nCount, size_t nElementSize)
{
memset(pMem, 0, nElementSize * nCount);
return pMem;
}
#endif
#define calloc(c, s) MemAlloc_InlineCallocMemset(malloc(c*s), c, s)
#define free(p) g_pMemAlloc->Free( p )
#define _msize(p) g_pMemAlloc->GetSize( p )
#define _expand(p, s) _expand_NoLongerSupported(p, s)
#define _aligned_free( p ) MemAlloc_FreeAligned( p )
#if defined(USE_MEM_DEBUG)
#define malloc(s) g_pMemAlloc->Alloc( s, __FILE__, __LINE__)
#define realloc(p, s) g_pMemAlloc->Realloc( p, s, __FILE__, __LINE__ )
#define _aligned_malloc( s, a ) MemAlloc_AllocAligned( s, a, __FILE__, __LINE__ )
#define _malloc_dbg(s, t, f, l) WHYCALLINGTHISDIRECTLY(s)
#if !defined( LINUX )
#if defined(__AFX_H__) && defined(DEBUG_NEW)
#define new DEBUG_NEW
#else
#undef new
#define MEMALL_DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#define new MEMALL_DEBUG_NEW
#endif
#endif
#undef _strdup
#undef strdup
#undef _wcsdup
#undef wcsdup
#define _strdup(s) MemAlloc_StrDup(s, __FILE__, __LINE__)
#define strdup(s) MemAlloc_StrDup(s, __FILE__, __LINE__)
#define _wcsdup(s) MemAlloc_WcStrDup(s, __FILE__, __LINE__)
#define wcsdup(s) MemAlloc_WcStrDup(s, __FILE__, __LINE__)
#if !defined(MEMDBGON_H)
inline char* MemAlloc_StrDup(const char* pString, const char* pFileName, unsigned nLine)
{
char* pMemory;
if (!pString)
return NULL;
size_t len = strlen(pString) + 1;
if ((pMemory = (char*)g_pMemAlloc->Alloc(len, pFileName, nLine)) != NULL)
{
return strcpy(pMemory, pString);
}
return NULL;
}
inline wchar_t* MemAlloc_WcStrDup(const wchar_t* pString, const char* pFileName, unsigned nLine)
{
wchar_t* pMemory;
if (!pString)
return NULL;
size_t len = (wcslen(pString) + 1);
if ((pMemory = (wchar_t*)g_pMemAlloc->Alloc(len * sizeof(wchar_t), pFileName, nLine)) != NULL)
{
return wcscpy(pMemory, pString);
}
return NULL;
}
#endif
#else
#define malloc(s) g_pMemAlloc->Alloc( s )
#define realloc(p, s) g_pMemAlloc->Realloc( p, s )
#define _aligned_malloc( s, a ) MemAlloc_AllocAligned( s, a )
#ifndef _malloc_dbg
#define _malloc_dbg(s, t, f, l) WHYCALLINGTHISDIRECTLY(s)
#endif
#undef new
#undef _strdup
#undef strdup
#undef _wcsdup
#undef wcsdup
#define _strdup(s) MemAlloc_StrDup(s)
#define strdup(s) MemAlloc_StrDup(s)
#define _wcsdup(s) MemAlloc_WcStrDup(s)
#define wcsdup(s) MemAlloc_WcStrDup(s)
#if !defined(MEMDBGON_H)
inline char* MemAlloc_StrDup(const char* pString)
{
char* pMemory;
if (!pString)
return NULL;
size_t len = strlen(pString) + 1;
if ((pMemory = (char*)g_pMemAlloc->Alloc(len)) != NULL)
{
return strcpy(pMemory, pString);
}
return NULL;
}
inline wchar_t* MemAlloc_WcStrDup(const wchar_t* pString)
{
wchar_t* pMemory;
if (!pString)
return NULL;
size_t len = (wcslen(pString) + 1);
if ((pMemory = (wchar_t*)g_pMemAlloc->Alloc(len * sizeof(wchar_t))) != NULL)
{
return wcscpy(pMemory, pString);
}
return NULL;
}
#endif
#endif
#define MEMDBGON_H
#else
#if defined(USE_MEM_DEBUG)
#ifndef _STATIC_LINKED
#pragma message ("Note: file includes crtdbg.h directly, therefore will cannot use memdbgon.h in non-debug build")
#else
#error "Error: file includes crtdbg.h directly, therefore will cannot use memdbgon.h in non-debug build. Not recoverable in static build"
#endif
#endif
#endif
#else
#include "memalloc.h"
#endif

590
SpyCustom/mempool.h Normal file
View File

@ -0,0 +1,590 @@
#ifndef MEMPOOL_H
#define MEMPOOL_H
#ifdef _WIN32
#pragma once
#endif
#include "memalloc.h"
#include "tslist.h"
#include "platform.h"
#include "utlvector.h"
#include "utlrbtree.h"
typedef void (*MemoryPoolReportFunc_t)(PRINTF_FORMAT_STRING char const* pMsg, ...);
class CUtlMemoryPool
{
public:
enum MemoryPoolGrowType_t
{
GROW_NONE = 0,
GROW_FAST = 1,
GROW_SLOW = 2
};
CUtlMemoryPool(int blockSize, int numElements, int growMode = GROW_FAST, const char* pszAllocOwner = NULL, int nAlignment = 0);
~CUtlMemoryPool();
void* Alloc();
void* Alloc(size_t amount);
void* AllocZero();
void* AllocZero(size_t amount);
void Free(void* pMem);
void Clear();
static void SetErrorReportFunc(MemoryPoolReportFunc_t func);
int Count() const { return m_BlocksAllocated; }
int PeakCount() const { return m_PeakAlloc; }
int BlockSize() const { return m_BlockSize; }
int Size() const;
bool IsAllocationWithinPool(void* pMem) const;
protected:
class CBlob
{
public:
CBlob* m_pPrev, * m_pNext;
int m_NumBytes;
char m_Data[1];
char m_Padding[3];
};
void Init();
void AddNewBlob();
void ReportLeaks();
int m_BlockSize;
int m_BlocksPerBlob;
int m_GrowMode;
int m_BlocksAllocated;
int m_PeakAlloc;
unsigned short m_nAlignment;
unsigned short m_NumBlobs;
void* m_pHeadOfFreeList;
const char* m_pszAllocOwner;
CBlob m_BlobHead;
static MemoryPoolReportFunc_t g_ReportFunc;
};
class CMemoryPoolMT : public CUtlMemoryPool
{
public:
CMemoryPoolMT(int blockSize, int numElements, int growMode = GROW_FAST, const char* pszAllocOwner = NULL, int nAlignment = 0) : CUtlMemoryPool(blockSize, numElements, growMode, pszAllocOwner, nAlignment) {}
void* Alloc() { AUTO_LOCK(m_mutex); return CUtlMemoryPool::Alloc(); }
void* Alloc(size_t amount) { AUTO_LOCK(m_mutex); return CUtlMemoryPool::Alloc(amount); }
void* AllocZero() { AUTO_LOCK(m_mutex); return CUtlMemoryPool::AllocZero(); }
void* AllocZero(size_t amount) { AUTO_LOCK(m_mutex); return CUtlMemoryPool::AllocZero(amount); }
void Free(void* pMem) { AUTO_LOCK(m_mutex); CUtlMemoryPool::Free(pMem); }
void Clear() { AUTO_LOCK(m_mutex); return CUtlMemoryPool::Clear(); }
private:
CThreadFastMutex m_mutex;
};
template< class T >
class CClassMemoryPool : public CUtlMemoryPool
{
public:
CClassMemoryPool(int numElements, int growMode = GROW_FAST, int nAlignment = 0) :
CUtlMemoryPool(sizeof(T), numElements, growMode, MEM_ALLOC_CLASSNAME(T), nAlignment) {}
T* Alloc();
T* AllocZero();
void Free(T* pMem);
void Clear();
};
template <int ITEM_SIZE, int ALIGNMENT, int CHUNK_SIZE, class CAllocator, bool GROWMODE = false, int COMPACT_THRESHOLD = 4 >
class CAlignedMemPool
{
enum
{
BLOCK_SIZE = COMPILETIME_MAX(ALIGN_VALUE(ITEM_SIZE, ALIGNMENT), 8),
};
public:
CAlignedMemPool();
void* Alloc();
void Free(void* p);
static int __cdecl CompareChunk(void* const* ppLeft, void* const* ppRight);
void Compact();
int NumTotal() { AUTO_LOCK(m_mutex); return m_Chunks.Count() * (CHUNK_SIZE / BLOCK_SIZE); }
int NumAllocated() { AUTO_LOCK(m_mutex); return NumTotal() - m_nFree; }
int NumFree() { AUTO_LOCK(m_mutex); return m_nFree; }
int BytesTotal() { AUTO_LOCK(m_mutex); return NumTotal() * BLOCK_SIZE; }
int BytesAllocated() { AUTO_LOCK(m_mutex); return NumAllocated() * BLOCK_SIZE; }
int BytesFree() { AUTO_LOCK(m_mutex); return NumFree() * BLOCK_SIZE; }
int ItemSize() { return ITEM_SIZE; }
int BlockSize() { return BLOCK_SIZE; }
int ChunkSize() { return CHUNK_SIZE; }
private:
struct FreeBlock_t
{
FreeBlock_t* pNext;
byte reserved[BLOCK_SIZE - sizeof(FreeBlock_t*)];
};
CUtlVector<void*> m_Chunks;
FreeBlock_t* m_pFirstFree;
int m_nFree;
CAllocator m_Allocator;
double m_TimeLastCompact;
CThreadFastMutex m_mutex;
};
template <typename T, int nInitialCount = 0, bool bDefCreateNewIfEmpty = true >
class CObjectPool
{
public:
CObjectPool()
{
int i = nInitialCount;
while (i-- > 0)
{
m_AvailableObjects.PushItem(new T);
}
}
~CObjectPool()
{
Purge();
}
int NumAvailable()
{
return m_AvailableObjects.Count();
}
void Purge()
{
T* p = NULL;
while (m_AvailableObjects.PopItem(&p))
{
delete p;
}
}
T* GetObject(bool bCreateNewIfEmpty = bDefCreateNewIfEmpty)
{
T* p = NULL;
if (!m_AvailableObjects.PopItem(&p))
{
p = (bCreateNewIfEmpty) ? new T : NULL;
}
return p;
}
void PutObject(T* p)
{
m_AvailableObjects.PushItem(p);
}
private:
CTSList<T*> m_AvailableObjects;
};
template <size_t PROVIDED_ITEM_SIZE, int ITEM_COUNT>
class CFixedBudgetMemoryPool
{
public:
CFixedBudgetMemoryPool()
{
m_pBase = m_pLimit = 0;
COMPILE_TIME_ASSERT(ITEM_SIZE % 4 == 0);
}
bool Owns(void* p)
{
return (p >= m_pBase && p < m_pLimit);
}
void* Alloc()
{
MEM_ALLOC_CREDIT_CLASS();
#ifndef USE_MEM_DEBUG
if (!m_pBase)
{
LOCAL_THREAD_LOCK();
if (!m_pBase)
{
byte* pMemory = m_pBase = (byte*)malloc(ITEM_COUNT * ITEM_SIZE);
m_pLimit = m_pBase + (ITEM_COUNT * ITEM_SIZE);
for (int i = 0; i < ITEM_COUNT; i++)
{
m_freeList.Push((TSLNodeBase_t*)pMemory);
pMemory += ITEM_SIZE;
}
}
}
void* p = m_freeList.Pop();
if (p)
return p;
#endif
return malloc(ITEM_SIZE);
}
void Free(void* p)
{
#ifndef USE_MEM_DEBUG
if (Owns(p))
m_freeList.Push((TSLNodeBase_t*)p);
else
#endif
free(p);
}
void Clear()
{
#ifndef USE_MEM_DEBUG
if (m_pBase)
{
free(m_pBase);
}
m_pBase = m_pLimit = 0;
Construct(&m_freeList);
#endif
}
bool IsEmpty()
{
#ifndef USE_MEM_DEBUG
if (m_pBase && m_freeList.Count() != ITEM_COUNT)
return false;
#endif
return true;
}
enum
{
ITEM_SIZE = ALIGN_VALUE(PROVIDED_ITEM_SIZE, TSLIST_NODE_ALIGNMENT)
};
CTSListBase m_freeList;
byte* m_pBase;
byte* m_pLimit;
};
#define BIND_TO_FIXED_BUDGET_POOL( poolName ) \
inline void* operator new( size_t size ) { return poolName.Alloc(); } \
inline void* operator new( size_t size, int nBlockUse, const char *pFileName, int nLine ) { return poolName.Alloc(); } \
inline void operator delete( void* p ) { poolName.Free(p); } \
inline void operator delete( void* p, int nBlockUse, const char *pFileName, int nLine ) { poolName.Free(p); }
template< class T >
inline T* CClassMemoryPool<T>::Alloc()
{
T* pRet;
{
MEM_ALLOC_CREDIT_CLASS();
pRet = (T*)CUtlMemoryPool::Alloc();
}
if (pRet)
{
Construct(pRet);
}
return pRet;
}
template< class T >
inline T* CClassMemoryPool<T>::AllocZero()
{
T* pRet;
{
MEM_ALLOC_CREDIT_CLASS();
pRet = (T*)CUtlMemoryPool::AllocZero();
}
if (pRet)
{
Construct(pRet);
}
return pRet;
}
template< class T >
inline void CClassMemoryPool<T>::Free(T* pMem)
{
if (pMem)
{
Destruct(pMem);
}
CUtlMemoryPool::Free(pMem);
}
template< class T >
inline void CClassMemoryPool<T>::Clear()
{
CUtlRBTree<void*, int> freeBlocks;
SetDefLessFunc(freeBlocks);
void* pCurFree = m_pHeadOfFreeList;
while (pCurFree != NULL)
{
freeBlocks.Insert(pCurFree);
pCurFree = *((void**)pCurFree);
}
for (CBlob* pCur = m_BlobHead.m_pNext; pCur != &m_BlobHead; pCur = pCur->m_pNext)
{
int nElements = pCur->m_NumBytes / this->m_BlockSize;
T* p = (T*)AlignValue(pCur->m_Data, this->m_nAlignment);
T* pLimit = p + nElements;
while (p < pLimit)
{
if (freeBlocks.Find(p) == freeBlocks.InvalidIndex())
{
Destruct(p);
}
p++;
}
}
CUtlMemoryPool::Clear();
}
#define DECLARE_FIXEDSIZE_ALLOCATOR( _class ) \
public: \
inline void* operator new( size_t size ) { MEM_ALLOC_CREDIT_(#_class " pool"); return s_Allocator.Alloc(size); } \
inline void* operator new( size_t size, int nBlockUse, const char *pFileName, int nLine ) { MEM_ALLOC_CREDIT_(#_class " pool"); return s_Allocator.Alloc(size); } \
inline void operator delete( void* p ) { s_Allocator.Free(p); } \
inline void operator delete( void* p, int nBlockUse, const char *pFileName, int nLine ) { s_Allocator.Free(p); } \
private: \
static CUtlMemoryPool s_Allocator
#define DEFINE_FIXEDSIZE_ALLOCATOR( _class, _initsize, _grow ) \
CUtlMemoryPool _class::s_Allocator(sizeof(_class), _initsize, _grow, #_class " pool")
#define DEFINE_FIXEDSIZE_ALLOCATOR_ALIGNED( _class, _initsize, _grow, _alignment ) \
CUtlMemoryPool _class::s_Allocator(sizeof(_class), _initsize, _grow, #_class " pool", _alignment )
#define DECLARE_FIXEDSIZE_ALLOCATOR_MT( _class ) \
public: \
inline void* operator new( size_t size ) { MEM_ALLOC_CREDIT_(#_class " pool"); return s_Allocator.Alloc(size); } \
inline void* operator new( size_t size, int nBlockUse, const char *pFileName, int nLine ) { MEM_ALLOC_CREDIT_(#_class " pool"); return s_Allocator.Alloc(size); } \
inline void operator delete( void* p ) { s_Allocator.Free(p); } \
inline void operator delete( void* p, int nBlockUse, const char *pFileName, int nLine ) { s_Allocator.Free(p); } \
private: \
static CMemoryPoolMT s_Allocator
#define DEFINE_FIXEDSIZE_ALLOCATOR_MT( _class, _initsize, _grow ) \
CMemoryPoolMT _class::s_Allocator(sizeof(_class), _initsize, _grow, #_class " pool")
#define DECLARE_FIXEDSIZE_ALLOCATOR_EXTERNAL( _class ) \
public: \
inline void* operator new( size_t size ) { MEM_ALLOC_CREDIT_(#_class " pool"); return s_pAllocator->Alloc(size); } \
inline void* operator new( size_t size, int nBlockUse, const char *pFileName, int nLine ) { MEM_ALLOC_CREDIT_(#_class " pool"); return s_pAllocator->Alloc(size); } \
inline void operator delete( void* p ) { s_pAllocator->Free(p); } \
private: \
static CUtlMemoryPool* s_pAllocator
#define DEFINE_FIXEDSIZE_ALLOCATOR_EXTERNAL( _class, _allocator ) \
CUtlMemoryPool* _class::s_pAllocator = _allocator
template <int ITEM_SIZE, int ALIGNMENT, int CHUNK_SIZE, class CAllocator, bool GROWMODE, int COMPACT_THRESHOLD >
inline CAlignedMemPool<ITEM_SIZE, ALIGNMENT, CHUNK_SIZE, CAllocator, GROWMODE, COMPACT_THRESHOLD>::CAlignedMemPool()
: m_pFirstFree(0),
m_nFree(0),
m_TimeLastCompact(0)
{
{ COMPILE_TIME_ASSERT(sizeof(FreeBlock_t) >= BLOCK_SIZE); }
{ COMPILE_TIME_ASSERT(ALIGN_VALUE(sizeof(FreeBlock_t), ALIGNMENT) == sizeof(FreeBlock_t)); }
}
template <int ITEM_SIZE, int ALIGNMENT, int CHUNK_SIZE, class CAllocator, bool GROWMODE, int COMPACT_THRESHOLD >
inline void* CAlignedMemPool<ITEM_SIZE, ALIGNMENT, CHUNK_SIZE, CAllocator, GROWMODE, COMPACT_THRESHOLD>::Alloc()
{
AUTO_LOCK(m_mutex);
if (!m_pFirstFree)
{
if (!GROWMODE && m_Chunks.Count())
{
return NULL;
}
FreeBlock_t* pNew = (FreeBlock_t*)m_Allocator.Alloc(CHUNK_SIZE);
Assert((unsigned)pNew % ALIGNMENT == 0);
m_Chunks.AddToTail(pNew);
m_nFree = CHUNK_SIZE / BLOCK_SIZE;
m_pFirstFree = pNew;
for (int i = 0; i < m_nFree - 1; i++)
{
pNew->pNext = pNew + 1;
pNew++;
}
pNew->pNext = NULL;
}
void* p = m_pFirstFree;
m_pFirstFree = m_pFirstFree->pNext;
m_nFree--;
return p;
}
template <int ITEM_SIZE, int ALIGNMENT, int CHUNK_SIZE, class CAllocator, bool GROWMODE, int COMPACT_THRESHOLD >
inline void CAlignedMemPool<ITEM_SIZE, ALIGNMENT, CHUNK_SIZE, CAllocator, GROWMODE, COMPACT_THRESHOLD>::Free(void* p)
{
AUTO_LOCK(m_mutex);
FreeBlock_t* pFree = ((FreeBlock_t*)p);
FreeBlock_t* pCur = m_pFirstFree;
FreeBlock_t* pPrev = NULL;
while (pCur && pFree > pCur)
{
pPrev = pCur;
pCur = pCur->pNext;
}
pFree->pNext = pCur;
if (pPrev)
{
pPrev->pNext = pFree;
}
else
{
m_pFirstFree = pFree;
}
m_nFree++;
if (m_nFree >= (CHUNK_SIZE / BLOCK_SIZE) * COMPACT_THRESHOLD)
{
double time = Plat_FloatTime();
double compactTime = (m_nFree >= (CHUNK_SIZE / BLOCK_SIZE) * COMPACT_THRESHOLD * 4) ? 15.0 : 30.0;
if (m_TimeLastCompact > time || m_TimeLastCompact + compactTime < time)
{
Compact();
m_TimeLastCompact = time;
}
}
}
template <int ITEM_SIZE, int ALIGNMENT, int CHUNK_SIZE, class CAllocator, bool GROWMODE, int COMPACT_THRESHOLD >
inline void CAlignedMemPool<ITEM_SIZE, ALIGNMENT, CHUNK_SIZE, CAllocator, GROWMODE, COMPACT_THRESHOLD>::Compact()
{
FreeBlock_t* pCur = m_pFirstFree;
FreeBlock_t* pPrev = NULL;
m_Chunks.Sort(CompareChunk);
#ifdef VALIDATE_ALIGNED_MEM_POOL
{
FreeBlock_t* p = m_pFirstFree;
while (p)
{
if (p->pNext && p > p->pNext)
{
__asm { int 3 }
}
p = p->pNext;
}
for (int i = 0; i < m_Chunks.Count(); i++)
{
if (i + 1 < m_Chunks.Count())
{
if (m_Chunks[i] > m_Chunks[i + 1])
{
__asm { int 3 }
}
}
}
}
#endif
int i;
for (i = 0; i < m_Chunks.Count(); i++)
{
int nBlocksPerChunk = CHUNK_SIZE / BLOCK_SIZE;
FreeBlock_t* pChunkLimit = ((FreeBlock_t*)m_Chunks[i]) + nBlocksPerChunk;
int nFromChunk = 0;
if (pCur == m_Chunks[i])
{
FreeBlock_t* pFirst = pCur;
while (pCur && pCur >= m_Chunks[i] && pCur < pChunkLimit)
{
pCur = pCur->pNext;
nFromChunk++;
}
pCur = pFirst;
}
while (pCur && pCur >= m_Chunks[i] && pCur < pChunkLimit)
{
if (nFromChunk != nBlocksPerChunk)
{
if (pPrev)
{
pPrev->pNext = pCur;
}
else
{
m_pFirstFree = pCur;
}
pPrev = pCur;
}
else if (pPrev)
{
pPrev->pNext = NULL;
}
else
{
m_pFirstFree = NULL;
}
pCur = pCur->pNext;
}
if (nFromChunk == nBlocksPerChunk)
{
m_Allocator.Free(m_Chunks[i]);
m_nFree -= nBlocksPerChunk;
m_Chunks[i] = 0;
}
}
for (i = m_Chunks.Count() - 1; i >= 0; i--)
{
if (!m_Chunks[i])
{
m_Chunks.FastRemove(i);
}
}
}
#endif

231
SpyCustom/meshreader.h Normal file
View File

@ -0,0 +1,231 @@
#ifndef MESHREADER_H
#define MESHREADER_H
#ifdef _WIN32
#pragma once
#endif
class CBaseMeshReader : protected MeshDesc_t
{
public:
CBaseMeshReader();
~CBaseMeshReader();
void BeginRead(
IMesh* pMesh,
int firstVertex = 0,
int numVertices = 0,
int firstIndex = 0,
int numIndices = 0);
void EndRead();
void BeginRead_Direct(const MeshDesc_t& desc, int numVertices, int nIndices);
void Reset();
protected:
IMesh* m_pMesh;
int m_MaxVertices;
int m_MaxIndices;
};
class CMeshReader : public CBaseMeshReader
{
public:
public:
int NumIndices() const;
unsigned short Index(int index) const;
const Vector& Position(int iVertex) const;
unsigned int Color(int iVertex) const;
const float* TexCoord(int iVertex, int stage) const;
void TexCoord2f(int iVertex, int stage, float& s, float& t) const;
const Vector2D& TexCoordVector2D(int iVertex, int stage) const;
int NumBoneWeights() const;
float Wrinkle(int iVertex) const;
const Vector& Normal(int iVertex) const;
void Normal(int iVertex, Vector& vNormal) const;
const Vector& TangentS(int iVertex) const;
const Vector& TangentT(int iVertex) const;
float BoneWeight(int iVertex) const;
#ifdef NEW_SKINNING
float* BoneMatrix(int iVertex) const;
#else
unsigned char* BoneMatrix(int iVertex) const;
#endif
};
inline CBaseMeshReader::CBaseMeshReader()
{
m_pMesh = NULL;
}
inline CBaseMeshReader::~CBaseMeshReader()
{
Assert(!m_pMesh);
}
inline void CBaseMeshReader::BeginRead(
IMesh* pMesh,
int firstVertex,
int numVertices,
int firstIndex,
int numIndices)
{
Assert(pMesh && (!m_pMesh));
if (numVertices < 0)
{
numVertices = pMesh->VertexCount();
}
if (numIndices < 0)
{
numIndices = pMesh->IndexCount();
}
m_pMesh = pMesh;
m_MaxVertices = numVertices;
m_MaxIndices = numIndices;
VertexCompressionType_t compressionType = CompressionType(pMesh->GetVertexFormat());
Assert(compressionType == VERTEX_COMPRESSION_NONE);
if (compressionType != VERTEX_COMPRESSION_NONE)
{
Warning("Cannot use CBaseMeshReader with compressed vertices! Will get junk data or a crash.\n");
}
pMesh->ModifyBeginEx(true, firstVertex, numVertices, firstIndex, numIndices, *this);
Reset();
}
inline void CBaseMeshReader::EndRead()
{
Assert(m_pMesh);
m_pMesh->ModifyEnd(*this);
m_pMesh = NULL;
}
inline void CBaseMeshReader::BeginRead_Direct(const MeshDesc_t& desc, int nVertices, int nIndices)
{
MeshDesc_t* pThis = this;
*pThis = desc;
m_MaxVertices = nVertices;
m_MaxIndices = nIndices;
Assert(desc.m_CompressionType == VERTEX_COMPRESSION_NONE);
if (desc.m_CompressionType != VERTEX_COMPRESSION_NONE)
{
Warning("Cannot use CBaseMeshReader with compressed vertices!\n");
}
}
inline void CBaseMeshReader::Reset()
{
}
inline int CMeshReader::NumIndices() const
{
return m_MaxIndices;
}
inline unsigned short CMeshReader::Index(int index) const
{
Assert((index >= 0) && (index < m_MaxIndices));
return m_pIndices[index * m_nIndexSize];
}
inline const Vector& CMeshReader::Position(int iVertex) const
{
Assert(iVertex >= 0 && iVertex < m_MaxVertices);
return *(Vector*)((char*)m_pPosition + iVertex * m_VertexSize_Position);
}
inline unsigned int CMeshReader::Color(int iVertex) const
{
Assert(iVertex >= 0 && iVertex < m_MaxVertices);
unsigned char* pColor = m_pColor + iVertex * m_VertexSize_Color;
return (pColor[0] << 16) | (pColor[1] << 8) | (pColor[2]) | (pColor[3] << 24);
}
inline const float* CMeshReader::TexCoord(int iVertex, int iStage) const
{
Assert(iVertex >= 0 && iVertex < m_MaxVertices);
return (float*)((char*)m_pTexCoord[iStage] + iVertex * m_VertexSize_TexCoord[iStage]);
}
inline void CMeshReader::TexCoord2f(int iVertex, int iStage, float& s, float& t) const
{
Assert(iVertex >= 0 && iVertex < m_MaxVertices);
float* p = (float*)((char*)m_pTexCoord[iStage] + iVertex * m_VertexSize_TexCoord[iStage]);
s = p[0];
t = p[1];
}
inline const Vector2D& CMeshReader::TexCoordVector2D(int iVertex, int iStage) const
{
Assert(iVertex >= 0 && iVertex < m_MaxVertices);
Vector2D* p = (Vector2D*)((char*)m_pTexCoord[iStage] + iVertex * m_VertexSize_TexCoord[iStage]);
return *p;
}
inline float CMeshReader::Wrinkle(int iVertex) const
{
Assert(iVertex >= 0 && iVertex < m_MaxVertices);
return *(float*)((char*)m_pWrinkle + iVertex * m_VertexSize_Wrinkle);
}
inline int CMeshReader::NumBoneWeights() const
{
return m_NumBoneWeights;
}
inline const Vector& CMeshReader::Normal(int iVertex) const
{
Assert(iVertex >= 0 && iVertex < m_MaxVertices);
return *(const Vector*)(const float*)((char*)m_pNormal + iVertex * m_VertexSize_Normal);
}
inline void CMeshReader::Normal(int iVertex, Vector& vNormal) const
{
Assert(iVertex >= 0 && iVertex < m_MaxVertices);
const float* p = (const float*)((char*)m_pNormal + iVertex * m_VertexSize_Normal);
vNormal.Init(p[0], p[1], p[2]);
}
inline const Vector& CMeshReader::TangentS(int iVertex) const
{
Assert(iVertex >= 0 && iVertex < m_MaxVertices);
return *(const Vector*)((char*)m_pTangentS + iVertex * m_VertexSize_TangentS);
}
inline const Vector& CMeshReader::TangentT(int iVertex) const
{
Assert(iVertex >= 0 && iVertex < m_MaxVertices);
return *(const Vector*)((char*)m_pTangentT + iVertex * m_VertexSize_TangentT);
}
inline float CMeshReader::BoneWeight(int iVertex) const
{
Assert(iVertex >= 0 && iVertex < m_MaxVertices);
float* p = (float*)((char*)m_pBoneWeight + iVertex * m_VertexSize_BoneWeight);
return *p;
}
#endif

16
SpyCustom/meshutils.h Normal file
View File

@ -0,0 +1,16 @@
#ifndef MESHUTILS_H
#define MESHUTILS_H
#ifdef _WIN32
#pragma once
#endif
void GenerateSequentialIndexBuffer(unsigned short* pIndexMemory, int nIndexCount, int nFirstVertex);
void GenerateQuadIndexBuffer(unsigned short* pIndexMemory, int nIndexCount, int nFirstVertex);
void GeneratePolygonIndexBuffer(unsigned short* pIndexMemory, int nIndexCount, int nFirstVertex);
void GenerateLineStripIndexBuffer(unsigned short* pIndexMemory, int nIndexCount, int nFirstVertex);
void GenerateLineLoopIndexBuffer(unsigned short* pIndexMemory, int nIndexCount, int nFirstVertex);
#endif

74
SpyCustom/messagebox.h Normal file
View File

@ -0,0 +1,74 @@
#ifndef MESSAGEBOX_H
#define MESSAGEBOX_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui.h"
#include "Frame.h"
#ifdef MessageBox
#undef MessageBox
#endif
namespace vgui
{
class MessageBox : public Frame
{
DECLARE_CLASS_SIMPLE(MessageBox, Frame);
public:
MessageBox(const char* title, const char* text, Panel* parent = NULL);
MessageBox(const wchar_t* wszTitle, const wchar_t* wszText, Panel* parent = NULL);
~MessageBox();
virtual void DoModal(Frame* pFrameOver = NULL);
virtual void ShowWindow(Frame* pFrameOver = NULL);
virtual void SetCommand(const char* command);
virtual void SetCommand(KeyValues* command);
virtual void SetOKButtonVisible(bool state);
virtual void SetOKButtonText(const char* buttonText);
virtual void SetOKButtonText(const wchar_t* wszButtonText);
void SetCancelButtonVisible(bool state);
void SetCancelButtonText(const char* buttonText);
void SetCancelButtonText(const wchar_t* wszButtonText);
void SetCancelCommand(KeyValues* command);
virtual void DisableCloseButton(bool state);
virtual void OnCommand(const char* pCommand);
void ShowMessageBoxOverCursor(bool bEnable);
protected:
virtual void PerformLayout();
virtual void ApplySchemeSettings(IScheme* pScheme);
protected:
Button* m_pOkButton;
Button* m_pCancelButton;
Label* m_pMessageLabel;
private:
MESSAGE_FUNC(OnShutdownRequest, "ShutdownRequest");
void Init();
KeyValues* m_OkCommand;
KeyValues* m_CancelCommand;
vgui::Frame* m_pFrameOver;
bool m_bNoAutoClose : 1;
bool m_bShowMessageBoxOverCursor : 1;
};
}
#endif

57
SpyCustom/minidump.h Normal file
View File

@ -0,0 +1,57 @@
#ifndef MINIDUMP_H
#define MINIDUMP_H
#ifdef _WIN32
#pragma once
#endif
#include "platform.h"
PLATFORM_INTERFACE void SetMinidumpFilenamePrefix(const char* pszPrefix);
PLATFORM_INTERFACE void SetMinidumpComment(const char* pszComment);
PLATFORM_INTERFACE void WriteMiniDump(const char* pszFilenameSuffix = NULL);
typedef void (*FnWMain)(int, tchar* []);
typedef void (*FnVoidPtrFn)(void*);
#if defined(_WIN32) && !defined(_X360)
typedef void (*FnWMain)(int, tchar* []);
typedef int (*FnWMainIntRet)(int, tchar* []);
typedef void (*FnVoidPtrFn)(void*);
enum ECatchAndWriteMinidumpAction
{
k_ECatchAndWriteMiniDumpAbort = 0,
k_ECatchAndWriteMiniDumpReThrow = 1,
k_ECatchAndWriteMiniDumpIgnore = 2,
};
PLATFORM_INTERFACE void CatchAndWriteMiniDump(FnWMain pfn, int argc, tchar* argv[]);
PLATFORM_INTERFACE void CatchAndWriteMiniDumpForVoidPtrFn(FnVoidPtrFn pfn, void* pv, bool bExitQuietly);
PLATFORM_INTERFACE void CatchAndWriteMiniDumpEx(FnWMain pfn, int argc, tchar* argv[], ECatchAndWriteMinidumpAction eAction);
PLATFORM_INTERFACE int CatchAndWriteMiniDumpExReturnsInt(FnWMainIntRet pfn, int argc, tchar* argv[], ECatchAndWriteMinidumpAction eAction);
PLATFORM_INTERFACE void CatchAndWriteMiniDumpExForVoidPtrFn(FnVoidPtrFn pfn, void* pv, ECatchAndWriteMinidumpAction eAction);
struct _EXCEPTION_POINTERS;
typedef void (*FnMiniDump)(unsigned int uStructuredExceptionCode, _EXCEPTION_POINTERS* pExceptionInfo, const char* pszFilenameSuffix);
PLATFORM_INTERFACE FnMiniDump SetMiniDumpFunction(FnMiniDump pfn);
PLATFORM_INTERFACE bool WriteMiniDumpUsingExceptionInfo(
unsigned int uStructuredExceptionCode,
_EXCEPTION_POINTERS* pExceptionInfo,
int minidumpType,
const char* pszFilenameSuffix = NULL,
tchar* ptchMinidumpFileNameBuffer = NULL
);
PLATFORM_INTERFACE void MinidumpSetUnhandledExceptionFunction(FnMiniDump pfn);
PLATFORM_INTERFACE void EnableCrashingOnCrashes();
#endif
#endif

148
SpyCustom/modelloader.h Normal file
View File

@ -0,0 +1,148 @@
#if !defined( MOD_LOADER_H )
#define MOD_LOADER_H
#ifdef _WIN32
#pragma once
#endif
struct model_t;
class IMaterial;
class IFileList;
#include "utlmemory.h"
abstract_class IModelLoader
{
public:
enum REFERENCETYPE
{
FMODELLOADER_NOTLOADEDORREFERENCED = 0,
FMODELLOADER_LOADED = (1 << 0),
FMODELLOADER_SERVER = (1 << 1),
FMODELLOADER_CLIENT = (1 << 2),
FMODELLOADER_CLIENTDLL = (1 << 3),
FMODELLOADER_STATICPROP = (1 << 4),
FMODELLOADER_DETAILPROP = (1 << 5),
FMODELLOADER_REFERENCEMASK = (FMODELLOADER_SERVER | FMODELLOADER_CLIENT | FMODELLOADER_CLIENTDLL | FMODELLOADER_STATICPROP | FMODELLOADER_DETAILPROP),
FMODELLOADER_TOUCHED_BY_PRELOAD = (1 << 15),
FMODELLOADER_LOADED_BY_PRELOAD = (1 << 16),
FMODELLOADER_TOUCHED_MATERIALS = (1 << 17),
};
enum ReloadType_t
{
RELOAD_LOD_CHANGED = 0,
RELOAD_EVERYTHING,
RELOAD_REFRESH_MODELS,
};
virtual void Init(void) = 0;
virtual void Shutdown(void) = 0;
virtual int GetCount(void) = 0;
virtual model_t* GetModelForIndex(int i) = 0;
virtual const char* GetName(const model_t* model) = 0;
virtual void* GetExtraData(model_t* model) = 0;
virtual int GetModelFileSize(const char* name) = 0;
virtual model_t* GetModelForName(const char* name, REFERENCETYPE referencetype) = 0;
virtual model_t* ReferenceModel(const char* name, REFERENCETYPE referencetype) = 0;
virtual void UnreferenceModel(model_t* model, REFERENCETYPE referencetype) = 0;
virtual void UnreferenceAllModels(REFERENCETYPE referencetype) = 0;
virtual void UnloadUnreferencedModels(void) = 0;
virtual void PurgeUnusedModels(void) = 0;
virtual bool Map_GetRenderInfoAllocated(void) = 0;
virtual void Map_SetRenderInfoAllocated(bool allocated) = 0;
virtual void Map_LoadDisplacements(model_t* model, bool bRestoring) = 0;
virtual void Print(void) = 0;
virtual bool Map_IsValid(char const* mapname) = 0;
virtual void RecomputeSurfaceFlags(model_t* mod) = 0;
virtual void Studio_ReloadModels(ReloadType_t reloadType) = 0;
virtual bool IsLoaded(const model_t* mod) = 0;
virtual bool LastLoadedMapHasHDRLighting(void) = 0;
virtual void ReloadFilesInList(IFileList* pFilesToReload) = 0;
virtual const char* GetActiveMapName(void) = 0;
};
extern IModelLoader* modelloader;
class CMapLoadHelper
{
public:
CMapLoadHelper(int lumpToLoad);
~CMapLoadHelper(void);
byte* LumpBase(void);
int LumpSize(void);
int LumpOffset(void);
int LumpVersion() const;
const char* GetMapName(void);
char* GetLoadName(void);
char* GetDiskName(void);
struct worldbrushdata_t* GetMap(void);
static void Init(model_t* pMapModel, const char* pLoadname);
static void InitFromMemory(model_t* pMapModel, const void* pData, int nDataSize);
static void Shutdown(void);
static int GetRefCount(void);
static void FreeLightingLump();
static int LumpSize(int lumpId);
static int LumpOffset(int lumpId);
void LoadLumpElement(int nElemIndex, int nElemSize, void* pData);
void LoadLumpData(int offset, int size, void* pData);
private:
int m_nLumpSize;
int m_nLumpOffset;
int m_nLumpVersion;
byte* m_pRawData;
byte* m_pData;
byte* m_pUncompressedData;
int m_nLumpID;
char m_szLumpFilename[MAX_PATH];
};
void Mod_RecomputeTranslucency(model_t* mod, int nSkin, int nBody, void * pClientRenderable);
int Mod_GameLumpSize(int lumpId);
int Mod_GameLumpVersion(int lumpId);
bool Mod_LoadGameLump(int lumpId, void* pBuffer, int size);
int Mod_GetMaterialCount(model_t* mod);
int Mod_GetModelMaterials(model_t* mod, int count, IMaterial** ppMaterial);
bool Mod_MarkWaterSurfaces(model_t* pModel);
void ConnectMDLCacheNotify();
void DisconnectMDLCacheNotify();
void InitStudioModelState(model_t* pModel);
char* GetMapNameOnDisk(char* pDiskName, const char* pFullMapName, unsigned int nDiskNameSize);
extern bool g_bLoadedMapHasBakedPropLighting;
extern bool g_bBakedPropLightingNoSeparateHDR;
#endif

15
SpyCustom/modes.h Normal file
View File

@ -0,0 +1,15 @@
#if !defined( MODES_H )
#define MODES_H
#ifdef _WIN32
#pragma once
#endif
typedef struct vmode_s
{
int width;
int height;
int bpp;
int refreshRate;
} vmode_t;
#endif

178
SpyCustom/mouthinfo.h Normal file
View File

@ -0,0 +1,178 @@
#if !defined( MOUTHINFO_H )
#define MOUTHINFO_H
#ifdef _WIN32
#pragma once
#endif
class CAudioSource;
#pragma pack(push,4)
class CVoiceData
{
public:
CVoiceData(void)
{
m_flElapsed = 0.0f;
m_pAudioSource = NULL;
m_bIgnorePhonemes = false;
}
void SetElapsedTime(float t)
{
m_flElapsed = t;
}
float GetElapsedTime() const
{
return m_flElapsed;
}
void SetSource(CAudioSource* source, bool bIgnorePhonemes)
{
m_pAudioSource = source;
m_bIgnorePhonemes = bIgnorePhonemes;
}
bool ShouldIgnorePhonemes() const
{
return m_bIgnorePhonemes;
}
CAudioSource* GetSource()
{
return m_pAudioSource;
}
private:
float m_flElapsed;
CAudioSource* m_pAudioSource;
bool m_bIgnorePhonemes;
};
#define UNKNOWN_VOICE_SOURCE -1
class CMouthInfo
{
public:
byte mouthopen;
byte sndcount;
int sndavg;
public:
CMouthInfo(void) { m_nVoiceSources = 0; m_needsEnvelope = false; }
virtual ~CMouthInfo(void) { ClearVoiceSources(); }
int GetNumVoiceSources(void);
CVoiceData* GetVoiceSource(int number);
void ClearVoiceSources(void);
int GetIndexForSource(CAudioSource* source);
bool IsSourceReferenced(CAudioSource* source);
CVoiceData* AddSource(CAudioSource* source, bool bIgnorePhonemes);
void RemoveSource(CAudioSource* source);
void RemoveSourceByIndex(int index);
bool IsActive(void);
bool NeedsEnvelope() { return m_needsEnvelope != 0; }
void ActivateEnvelope() { m_needsEnvelope = true; }
private:
enum
{
MAX_VOICE_DATA = 4
};
short m_nVoiceSources;
short m_needsEnvelope;
CVoiceData m_VoiceSources[MAX_VOICE_DATA];
};
#pragma pack(pop)
inline bool CMouthInfo::IsActive(void)
{
return (GetNumVoiceSources() > 0) ? true : false;
}
inline int CMouthInfo::GetNumVoiceSources(void)
{
return m_nVoiceSources;
}
inline CVoiceData* CMouthInfo::GetVoiceSource(int number)
{
if (number < 0 || number >= m_nVoiceSources)
return NULL;
return &m_VoiceSources[number];
}
inline void CMouthInfo::ClearVoiceSources(void)
{
m_nVoiceSources = 0;
}
inline int CMouthInfo::GetIndexForSource(CAudioSource* source)
{
for (int i = 0; i < m_nVoiceSources; i++)
{
CVoiceData* v = &m_VoiceSources[i];
if (!v)
continue;
if (v->GetSource() == source)
return i;
}
return UNKNOWN_VOICE_SOURCE;
}
inline bool CMouthInfo::IsSourceReferenced(CAudioSource* source)
{
if (GetIndexForSource(source) != UNKNOWN_VOICE_SOURCE)
return true;
return false;
}
inline void CMouthInfo::RemoveSource(CAudioSource* source)
{
int idx = GetIndexForSource(source);
if (idx == UNKNOWN_VOICE_SOURCE)
return;
RemoveSourceByIndex(idx);
}
inline void CMouthInfo::RemoveSourceByIndex(int index)
{
if (index < 0 || index >= m_nVoiceSources)
return;
m_VoiceSources[index] = m_VoiceSources[--m_nVoiceSources];
}
inline CVoiceData* CMouthInfo::AddSource(CAudioSource* source, bool bIgnorePhonemes)
{
int idx = GetIndexForSource(source);
if (idx == UNKNOWN_VOICE_SOURCE)
{
if (m_nVoiceSources < MAX_VOICE_DATA)
{
idx = m_nVoiceSources++;
}
else
{
return NULL;
}
}
CVoiceData* data = &m_VoiceSources[idx];
data->SetSource(source, bIgnorePhonemes);
data->SetElapsedTime(0.0f);
return data;
}
#endif

36
SpyCustom/netchannel.hpp Normal file
View File

@ -0,0 +1,36 @@
#pragma once
typedef const void(__thiscall* pShutdown)(void*, void*, const char*);
pShutdown oShutdown;
void __fastcall hkShutdown(void* thisptr, void* unk1, void* unk2, const char* reason) noexcept
{
#ifdef DEBUG
printf("shutdown (%x) HOOKED %s\n", thisptr, reason);
#endif
if (*g_Options.discmsg_active) {
#ifdef DEBUG
printf("set new reason %s\n", g_Options.discmsg.value->mystring);
#endif
char customreason[256] = "#";
strcat_s( customreason, MakeControlChars(g_Options.discmsg.value->mystring));
oShutdown(thisptr, nullptr, customreason);
}
else
oShutdown(thisptr, nullptr, reason);
}
inline void HookNetchannel()
{
DWORD ptrShutdown = *((DWORD*)iff.g_pEngineClient->GetNetChannelInfo()) + 36 * 4;
DWORD addrShutdown = *(DWORD*)ptrShutdown;
oShutdown = (pShutdown)DetourFunction(
(PBYTE)(addrShutdown),
(PBYTE)hkShutdown);
#ifdef DEBUG
printf("Detoured at %x\n", addrShutdown);
#endif
opt.netchannedlhooked = 1;
}

110
SpyCustom/netvars.cpp Normal file
View File

@ -0,0 +1,110 @@
#include "netvars.hpp"
#include <fstream>
#include <utility>
#include "interfaces.hpp"
void NetvarSys::Initialize()
{
m_tables.clear();
ClientClass* clientClass = iff.g_pClient->GetAllClasses();
if (!clientClass)
return;
while (clientClass)
{
RecvTable* recvTable = clientClass->m_pRecvTable;
m_tables.push_back(recvTable);
clientClass = clientClass->m_pNext;
}
}
#undef GetProp
int NetvarSys::GetOffset(const char* tableName, const char* propName)
{
int offset = this->GetProp(tableName, propName);
if (!offset)
{
#ifdef DEBUG
printf("%s not found!\n", propName);
#endif
return 0;
}
#ifdef DEBUG
printf("%s: 0x%02X\n", propName, offset);
#endif
return offset;
}
int NetvarSys::GetProp(const char* tableName, const char* propName, RecvProp** prop)
{
RecvTable* recvTable = GetTable(tableName);
if (!recvTable)
return 0;
int offset = this->GetProp(recvTable, propName, prop);
if (!offset)
return 0;
return offset;
}
int NetvarSys::GetProp(RecvTable* recvTable, const char* propName, RecvProp** prop)
{
int extraOffset = 0;
for (int i = 0; i < recvTable->m_nProps; ++i)
{
RecvProp* recvProp = &recvTable->m_pProps[i];
RecvTable* child = recvProp->m_pDataTable;
if (child && (child->m_nProps > 0))
{
int tmp = this->GetProp(child, propName, prop);
if (tmp)
extraOffset += (recvProp->m_Offset + tmp);
}
if (_stricmp(recvProp->m_pVarName, propName))
continue;
if (prop)
*prop = recvProp;
return (recvProp->m_Offset + extraOffset);
}
return extraOffset;
}
RecvTable* NetvarSys::GetTable(const char* tableName)
{
if (m_tables.empty())
return 0;
for (const auto& table : m_tables)
{
if (!table)
continue;
if (_stricmp(table->m_pNetTableName, tableName) == 0)
return table;
}
return 0;
}

37
SpyCustom/netvars.hpp Normal file
View File

@ -0,0 +1,37 @@
#pragma once
#include <memory>
#include <iostream>
#include <unordered_map>
#include "dt_recv.h"
#include "Singleton.hpp"
class NetvarSys
: public Singleton<NetvarSys>
{
public:
void Initialize();
int GetOffset(const char* tableName, const char* propName);
RecvTable* GetTable(const char* tableName);
std::vector<RecvTable*> m_tables;
private:
int GetProp(const char* tableName, const char* propName, RecvProp** prop = 0);
int GetProp(RecvTable* recvTable, const char* propName, RecvProp** prop = 0);
};
#define NETVAR_OFFSET2(funcname, class_name, var_name, offset, ...) \
auto funcname() -> std::add_lvalue_reference_t<__VA_ARGS__> \
{ \
static int netvar = NetvarSys::Get().GetOffset(class_name, var_name); \
auto addr = std::uintptr_t(this) + offset + netvar; \
return *reinterpret_cast<std::add_pointer_t<__VA_ARGS__>>(addr); \
}
#define NETVAR2(funcname, class_name, var_name, ...) \
NETVAR_OFFSET2(funcname, class_name, var_name, 0, __VA_ARGS__)

View File

@ -0,0 +1,63 @@
#ifndef NETWORKSTRINGTABLEDEFS_H
#define NETWORKSTRINGTABLEDEFS_H
#ifdef _WIN32
#pragma once
#endif
typedef int TABLEID;
#define INVALID_STRING_TABLE -1
const unsigned short INVALID_STRING_INDEX = (unsigned short)-1;
#define MAX_TABLES 32
#define INTERFACENAME_NETWORKSTRINGTABLESERVER "VEngineServerStringTable001"
#define INTERFACENAME_NETWORKSTRINGTABLECLIENT "VEngineClientStringTable001"
class INetworkStringTable;
typedef void (*pfnStringChanged)(void* object, INetworkStringTable* stringTable, int stringNumber, char const* newString, void const* newData);
class INetworkStringTable
{
public:
virtual ~INetworkStringTable(void) {};
virtual const char* GetTableName(void) const = 0;
virtual TABLEID GetTableId(void) const = 0;
virtual int GetNumStrings(void) const = 0;
virtual int GetMaxStrings(void) const = 0;
virtual int GetEntryBits(void) const = 0;
virtual void SetTick(int tick) = 0;
virtual bool ChangedSinceTick(int tick) const = 0;
virtual int AddString(bool bIsServer, const char* value, int length = -1, const void* userdata = 0) = 0;
virtual const char* GetString(int stringNumber) = 0;
virtual void SetStringUserData(int stringNumber, int length, const void* userdata) = 0;
virtual const void* GetStringUserData(int stringNumber, int* length) = 0;
virtual int FindStringIndex(char const* string) = 0;
virtual void SetStringChangedCallback(void* object, pfnStringChanged changeFunc) = 0;
};
class INetworkStringTableContainer
{
public:
virtual ~INetworkStringTableContainer(void) {};
virtual INetworkStringTable* CreateStringTable(const char* tableName, int maxentries, int userdatafixedsize = 0, int userdatanetworkbits = 0) = 0;
virtual void RemoveAllTables(void) = 0;
virtual INetworkStringTable* FindTable(const char* tableName) const = 0;
virtual INetworkStringTable* GetTable(TABLEID stringTable) const = 0;
virtual int GetNumTables(void) const = 0;
virtual INetworkStringTable* CreateStringTableEx(const char* tableName, int maxentries, int userdatafixedsize = 0, int userdatanetworkbits = 0, bool bIsFilenames = false) = 0;
virtual void SetAllowClientSideAddString(INetworkStringTable* table, bool bAllowClientSideAddString) = 0;
};
#endif

737
SpyCustom/networkvar.h Normal file
View File

@ -0,0 +1,737 @@
#ifndef NETWORKVAR_H
#define NETWORKVAR_H
#ifdef _WIN32
#pragma once
#endif
#include "dbg.h"
#include "convar.h"
#if defined( CLIENT_DLL ) || defined( GAME_DLL )
#include "basehandle.h"
#endif
#pragma warning( disable : 4284 )
#define MyOffsetOf( type, var ) ( (int)&((type*)0)->var )
#ifdef _DEBUG
extern bool g_bUseNetworkVars;
#define CHECK_USENETWORKVARS if(g_bUseNetworkVars)
#else
#define CHECK_USENETWORKVARS
#endif
inline int InternalCheckDeclareClass(const char* pClassName, const char* pClassNameMatch, void* pTestPtr, void* pBasePtr)
{
Assert(pTestPtr == pBasePtr);
Assert((void*)pClassName == (void*)pClassNameMatch);
return 0;
}
template <typename T>
inline int CheckDeclareClass_Access(T*, const char* pShouldBe)
{
return T::CheckDeclareClass(pShouldBe);
}
#ifndef _STATIC_LINKED
#ifdef _MSC_VER
#if defined(_DEBUG) && (_MSC_VER > 1200 )
#define VALIDATE_DECLARE_CLASS 1
#endif
#endif
#endif
#ifdef VALIDATE_DECLARE_CLASS
#define DECLARE_CLASS( className, baseClassName ) \
typedef baseClassName BaseClass; \
typedef className ThisClass; \
template <typename T> friend int CheckDeclareClass_Access(T *, const char *pShouldBe); \
static int CheckDeclareClass( const char *pShouldBe ) \
{ \
InternalCheckDeclareClass( pShouldBe, #className, (ThisClass*)0xFFFFF, (BaseClass*)(ThisClass*)0xFFFFF ); \
return CheckDeclareClass_Access( (BaseClass *)NULL, #baseClassName ); \
}
#define DECLARE_CLASS_GAMEROOT( className, baseClassName ) \
typedef baseClassName BaseClass; \
typedef className ThisClass; \
template <typename T> friend int CheckDeclareClass_Access(T *, const char *pShouldBe); \
static int CheckDeclareClass( const char *pShouldBe ) \
{ \
return InternalCheckDeclareClass( pShouldBe, #className, (ThisClass*)0xFFFFF, (BaseClass*)(ThisClass*)0xFFFFF ); \
}
#define DECLARE_CLASS_NOFRIEND( className, baseClassName ) \
DECLARE_CLASS( className, baseClassName )
#define DECLARE_CLASS_NOBASE( className ) \
typedef className ThisClass; \
template <typename T> friend int CheckDeclareClass_Access(T *, const char *pShouldBe); \
static int CheckDeclareClass( const char *pShouldBe ) \
{ \
return InternalCheckDeclareClass( pShouldBe, #className, 0, 0 ); \
}
#else
#define DECLARE_CLASS( className, baseClassName ) \
typedef baseClassName BaseClass; \
typedef className ThisClass;
#define DECLARE_CLASS_GAMEROOT( className, baseClassName ) DECLARE_CLASS( className, baseClassName )
#define DECLARE_CLASS_NOFRIEND( className, baseClassName ) DECLARE_CLASS( className, baseClassName )
#define DECLARE_CLASS_NOBASE( className ) typedef className ThisClass;
#endif
class CBaseEntity;
class CAutoInitEntPtr
{
public:
CAutoInitEntPtr()
{
m_pEnt = NULL;
}
CBaseEntity* m_pEnt;
};
#define DECLARE_NETWORKVAR_CHAIN() \
CAutoInitEntPtr __m_pChainEntity; \
void NetworkStateChanged() { CHECK_USENETWORKVARS __m_pChainEntity.m_pEnt->NetworkStateChanged(); } \
void NetworkStateChanged( void *pVar ) { CHECK_USENETWORKVARS __m_pChainEntity.m_pEnt->NetworkStateChanged(); }
#define IMPLEMENT_NETWORKVAR_CHAIN( varName ) \
(varName)->__m_pChainEntity.m_pEnt = this;
template< class T >
static inline void DispatchNetworkStateChanged(T* pObj)
{
CHECK_USENETWORKVARS pObj->NetworkStateChanged();
}
template< class T >
static inline void DispatchNetworkStateChanged(T* pObj, void* pVar)
{
CHECK_USENETWORKVARS pObj->NetworkStateChanged(pVar);
}
#define DECLARE_EMBEDDED_NETWORKVAR() \
template <typename T> friend int ServerClassInit(T *); \
template <typename T> friend int ClientClassInit(T *); \
virtual void NetworkStateChanged() {} virtual void NetworkStateChanged( void *pProp ) {}
#define CNetworkVarEmbedded( type, name ) \
class NetworkVar_##name; \
friend class NetworkVar_##name; \
static inline int GetOffset_##name() { return MyOffsetOf(ThisClass,name); } \
typedef ThisClass ThisClass_##name; \
class NetworkVar_##name : public type \
{ \
template< class T > NetworkVar_##name& operator=( const T &val ) { *((type*)this) = val; return *this; } \
public: \
void CopyFrom( const type &src ) { *((type *)this) = src; NetworkStateChanged(); } \
virtual void NetworkStateChanged() \
{ \
DispatchNetworkStateChanged( (ThisClass_##name*)( ((char*)this) - GetOffset_##name() ) ); \
} \
virtual void NetworkStateChanged( void *pVar ) \
{ \
DispatchNetworkStateChanged( (ThisClass_##name*)( ((char*)this) - GetOffset_##name() ), pVar ); \
} \
}; \
NetworkVar_##name name;
template<typename T>
FORCEINLINE void NetworkVarConstruct(T& x) { x = T(0); }
FORCEINLINE void NetworkVarConstruct(color32_s& x) { x.r = x.g = x.b = x.a = 0; }
template< class Type, class Changer >
class CNetworkVarBase
{
public:
inline CNetworkVarBase()
{
NetworkVarConstruct(m_Value);
}
template< class C >
const Type& operator=(const C& val)
{
return Set((const Type)val);
}
template< class C >
const Type& operator=(const CNetworkVarBase< C, Changer >& val)
{
return Set((const Type)val.m_Value);
}
const Type& Set(const Type& val)
{
if (memcmp(&m_Value, &val, sizeof(Type)))
{
NetworkStateChanged();
m_Value = val;
}
return m_Value;
}
Type& GetForModify()
{
NetworkStateChanged();
return m_Value;
}
template< class C >
const Type& operator+=(const C& val)
{
return Set(m_Value + (const Type)val);
}
template< class C >
const Type& operator-=(const C& val)
{
return Set(m_Value - (const Type)val);
}
template< class C >
const Type& operator/=(const C& val)
{
return Set(m_Value / (const Type)val);
}
template< class C >
const Type& operator*=(const C& val)
{
return Set(m_Value * (const Type)val);
}
template< class C >
const Type& operator^=(const C& val)
{
return Set(m_Value ^ (const Type)val);
}
template< class C >
const Type& operator|=(const C& val)
{
return Set(m_Value | (const Type)val);
}
const Type& operator++()
{
return (*this += 1);
}
Type operator--()
{
return (*this -= 1);
}
Type operator++(int)
{
Type val = m_Value;
(*this += 1);
return val;
}
Type operator--(int)
{
Type val = m_Value;
(*this -= 1);
return val;
}
template< class C >
const Type& operator&=(const C& val)
{
return Set(m_Value & (const Type)val);
}
operator const Type& () const
{
return m_Value;
}
const Type& Get() const
{
return m_Value;
}
const Type* operator->() const
{
return &m_Value;
}
Type m_Value;
protected:
inline void NetworkStateChanged()
{
Changer::NetworkStateChanged(this);
}
};
template< class Type, class Changer >
class CNetworkColor32Base : public CNetworkVarBase< Type, Changer >
{
public:
inline void Init(byte rVal, byte gVal, byte bVal)
{
SetR(rVal);
SetG(gVal);
SetB(bVal);
}
inline void Init(byte rVal, byte gVal, byte bVal, byte aVal)
{
SetR(rVal);
SetG(gVal);
SetB(bVal);
SetA(aVal);
}
const Type& operator=(const Type& val)
{
return this->Set(val);
}
const Type& operator=(const CNetworkColor32Base<Type, Changer>& val)
{
return CNetworkVarBase<Type, Changer>::Set(val.m_Value);
}
inline byte GetR() const { return CNetworkColor32Base<Type, Changer>::m_Value.r; }
inline byte GetG() const { return CNetworkColor32Base<Type, Changer>::m_Value.g; }
inline byte GetB() const { return CNetworkColor32Base<Type, Changer>::m_Value.b; }
inline byte GetA() const { return CNetworkColor32Base<Type, Changer>::m_Value.a; }
inline void SetR(byte val) { SetVal(CNetworkColor32Base<Type, Changer>::m_Value.r, val); }
inline void SetG(byte val) { SetVal(CNetworkColor32Base<Type, Changer>::m_Value.g, val); }
inline void SetB(byte val) { SetVal(CNetworkColor32Base<Type, Changer>::m_Value.b, val); }
inline void SetA(byte val) { SetVal(CNetworkColor32Base<Type, Changer>::m_Value.a, val); }
protected:
inline void SetVal(byte& out, const byte& in)
{
if (out != in)
{
CNetworkVarBase< Type, Changer >::NetworkStateChanged();
out = in;
}
}
};
template< class Type, class Changer >
class CNetworkVectorBase : public CNetworkVarBase< Type, Changer >
{
public:
inline void Init(float ix = 0, float iy = 0, float iz = 0)
{
SetX(ix);
SetY(iy);
SetZ(iz);
}
const Type& operator=(const Type& val)
{
return CNetworkVarBase< Type, Changer >::Set(val);
}
const Type& operator=(const CNetworkVectorBase<Type, Changer>& val)
{
return CNetworkVarBase<Type, Changer>::Set(val.m_Value);
}
inline float GetX() const { return CNetworkVectorBase<Type, Changer>::m_Value.x; }
inline float GetY() const { return CNetworkVectorBase<Type, Changer>::m_Value.y; }
inline float GetZ() const { return CNetworkVectorBase<Type, Changer>::m_Value.z; }
inline float operator[](int i) const { return CNetworkVectorBase<Type, Changer>::m_Value[i]; }
inline void SetX(float val) { DetectChange(CNetworkVectorBase<Type, Changer>::m_Value.x, val); }
inline void SetY(float val) { DetectChange(CNetworkVectorBase<Type, Changer>::m_Value.y, val); }
inline void SetZ(float val) { DetectChange(CNetworkVectorBase<Type, Changer>::m_Value.z, val); }
inline void Set(int i, float val) { DetectChange(CNetworkVectorBase<Type, Changer>::m_Value[i], val); }
bool operator==(const Type& val) const
{
return CNetworkVectorBase<Type, Changer>::m_Value == (Type)val;
}
bool operator!=(const Type& val) const
{
return CNetworkVectorBase<Type, Changer>::m_Value != (Type)val;
}
const Type operator+(const Type& val) const
{
return CNetworkVectorBase<Type, Changer>::m_Value + val;
}
const Type operator-(const Type& val) const
{
return CNetworkVectorBase<Type, Changer>::m_Value - val;
}
const Type operator*(const Type& val) const
{
return CNetworkVectorBase<Type, Changer>::m_Value * val;
}
const Type& operator*=(float val)
{
return CNetworkVarBase< Type, Changer >::Set(CNetworkVectorBase<Type, Changer>::m_Value * val);
}
const Type operator*(float val) const
{
return CNetworkVectorBase<Type, Changer>::m_Value * val;
}
const Type operator/(const Type& val) const
{
return CNetworkVectorBase<Type, Changer>::m_Value / val;
}
private:
inline void DetectChange(float& out, float in)
{
if (out != in)
{
CNetworkVectorBase<Type, Changer>::NetworkStateChanged();
out = in;
}
}
};
template< class Type, class Changer >
class CNetworkQuaternionBase : public CNetworkVarBase< Type, Changer >
{
public:
inline void Init(float ix = 0, float iy = 0, float iz = 0, float iw = 0)
{
SetX(ix);
SetY(iy);
SetZ(iz);
SetW(iw);
}
const Type& operator=(const Type& val)
{
return CNetworkVarBase< Type, Changer >::Set(val);
}
const Type& operator=(const CNetworkQuaternionBase<Type, Changer>& val)
{
return CNetworkVarBase<Type, Changer>::Set(val.m_Value);
}
inline float GetX() const { return CNetworkQuaternionBase<Type, Changer>::m_Value.x; }
inline float GetY() const { return CNetworkQuaternionBase<Type, Changer>::m_Value.y; }
inline float GetZ() const { return CNetworkQuaternionBase<Type, Changer>::m_Value.z; }
inline float GetW() const { return CNetworkQuaternionBase<Type, Changer>::m_Value.w; }
inline float operator[](int i) const { return CNetworkQuaternionBase<Type, Changer>::m_Value[i]; }
inline void SetX(float val) { DetectChange(CNetworkQuaternionBase<Type, Changer>::m_Value.x, val); }
inline void SetY(float val) { DetectChange(CNetworkQuaternionBase<Type, Changer>::m_Value.y, val); }
inline void SetZ(float val) { DetectChange(CNetworkQuaternionBase<Type, Changer>::m_Value.z, val); }
inline void SetW(float val) { DetectChange(CNetworkQuaternionBase<Type, Changer>::m_Value.w, val); }
inline void Set(int i, float val) { DetectChange(CNetworkQuaternionBase<Type, Changer>::m_Value[i], val); }
bool operator==(const Type& val) const
{
return CNetworkQuaternionBase<Type, Changer>::m_Value == (Type)val;
}
bool operator!=(const Type& val) const
{
return CNetworkQuaternionBase<Type, Changer>::m_Value != (Type)val;
}
const Type operator+(const Type& val) const
{
return CNetworkQuaternionBase<Type, Changer>::m_Value + val;
}
const Type operator-(const Type& val) const
{
return CNetworkQuaternionBase<Type, Changer>::m_Value - val;
}
const Type operator*(const Type& val) const
{
return CNetworkQuaternionBase<Type, Changer>::m_Value * val;
}
const Type& operator*=(float val)
{
return CNetworkQuaternionBase< Type, Changer >::Set(CNetworkQuaternionBase<Type, Changer>::m_Value * val);
}
const Type operator*(float val) const
{
return CNetworkQuaternionBase<Type, Changer>::m_Value * val;
}
const Type operator/(const Type& val) const
{
return CNetworkQuaternionBase<Type, Changer>::m_Value / val;
}
private:
inline void DetectChange(float& out, float in)
{
if (out != in)
{
CNetworkQuaternionBase<Type, Changer>::NetworkStateChanged();
out = in;
}
}
};
#if defined( CLIENT_DLL ) || defined( GAME_DLL )
inline void NetworkVarConstruct(CBaseHandle& x) {}
template< class Type, class Changer >
class CNetworkHandleBase : public CNetworkVarBase< CBaseHandle, Changer >
{
public:
const Type* operator=(const Type* val)
{
return Set(val);
}
const Type& operator=(const CNetworkHandleBase<Type, Changer>& val)
{
const CBaseHandle& handle = CNetworkVarBase<CBaseHandle, Changer>::Set(val.m_Value);
return *(const Type*)handle.Get();
}
bool operator !() const
{
return !CNetworkHandleBase<Type, Changer>::m_Value.Get();
}
operator Type* () const
{
return static_cast<Type*>(CNetworkHandleBase<Type, Changer>::m_Value.Get());
}
const Type* Set(const Type* val)
{
if (CNetworkHandleBase<Type, Changer>::m_Value != val)
{
this->NetworkStateChanged();
CNetworkHandleBase<Type, Changer>::m_Value = val;
}
return val;
}
Type* Get() const
{
return static_cast<Type*>(CNetworkHandleBase<Type, Changer>::m_Value.Get());
}
Type* operator->() const
{
return static_cast<Type*>(CNetworkHandleBase<Type, Changer>::m_Value.Get());
}
bool operator==(const Type* val) const
{
return CNetworkHandleBase<Type, Changer>::m_Value == val;
}
bool operator!=(const Type* val) const
{
return CNetworkHandleBase<Type, Changer>::m_Value != val;
}
};
#define CNetworkHandle( type, name ) CNetworkHandleInternal( type, name, NetworkStateChanged )
#define CNetworkHandleInternal( type, name, stateChangedFn ) \
NETWORK_VAR_START( type, name ) \
NETWORK_VAR_END( type, name, CNetworkHandleBase, stateChangedFn )
#endif
#define CNetworkVar( type, name ) \
NETWORK_VAR_START( type, name ) \
NETWORK_VAR_END( type, name, CNetworkVarBase, NetworkStateChanged )
#define CNetworkVarForDerived( type, name ) \
virtual void NetworkStateChanged_##name() {} \
virtual void NetworkStateChanged_##name( void *pVar ) {} \
NETWORK_VAR_START( type, name ) \
NETWORK_VAR_END( type, name, CNetworkVarBase, NetworkStateChanged_##name )
#define CNetworkVectorForDerived( name ) \
virtual void NetworkStateChanged_##name() {} \
virtual void NetworkStateChanged_##name( void *pVar ) {} \
CNetworkVectorInternal( Vector, name, NetworkStateChanged_##name )
#define CNetworkHandleForDerived( type, name ) \
virtual void NetworkStateChanged_##name() {} \
virtual void NetworkStateChanged_##name( void *pVar ) {} \
CNetworkHandleInternal( type, name, NetworkStateChanged_##name )
#define CNetworkArrayForDerived( type, name, count ) \
virtual void NetworkStateChanged_##name() {} \
virtual void NetworkStateChanged_##name( void *pVar ) {} \
CNetworkArrayInternal( type, name, count, NetworkStateChanged_##name )
#define IMPLEMENT_NETWORK_VAR_FOR_DERIVED( name ) \
virtual void NetworkStateChanged_##name() { CHECK_USENETWORKVARS NetworkStateChanged(); } \
virtual void NetworkStateChanged_##name( void *pVar ) { CHECK_USENETWORKVARS NetworkStateChanged( pVar ); }
#define CNetworkVarForDerived_OnByDefault( type, name ) \
virtual void NetworkStateChanged_##name() { CHECK_USENETWORKVARS NetworkStateChanged(); } \
virtual void NetworkStateChanged_##name( void *pVar ) { CHECK_USENETWORKVARS NetworkStateChanged( pVar ); } \
NETWORK_VAR_START( type, name ) \
NETWORK_VAR_END( type, name, CNetworkVarBase, NetworkStateChanged_##name )
#define DISABLE_NETWORK_VAR_FOR_DERIVED( name ) \
virtual void NetworkStateChanged_##name() {} \
virtual void NetworkStateChanged_##name( void *pVar ) {}
#define CNetworkVector( name ) CNetworkVectorInternal( Vector, name, NetworkStateChanged )
#define CNetworkQAngle( name ) CNetworkVectorInternal( QAngle, name, NetworkStateChanged )
#define CNetworkVectorInternal( type, name, stateChangedFn ) \
NETWORK_VAR_START( type, name ) \
NETWORK_VAR_END( type, name, CNetworkVectorBase, stateChangedFn )
#define CNetworkQuaternion( name ) \
NETWORK_VAR_START( Quaternion, name ) \
NETWORK_VAR_END( Quaternion, name, CNetworkQuaternionBase, NetworkStateChanged )
#define CNetworkColor32( name ) \
NETWORK_VAR_START( color32, name ) \
NETWORK_VAR_END( color32, name, CNetworkColor32Base, NetworkStateChanged )
#define CNetworkString( name, length ) \
class NetworkVar_##name; \
friend class NetworkVar_##name; \
typedef ThisClass MakeANetworkVar_##name; \
class NetworkVar_##name \
{ \
public: \
NetworkVar_##name() { m_Value[0] = '\0'; } \
operator const char*() const { return m_Value; } \
const char* Get() const { return m_Value; } \
char* GetForModify() \
{ \
NetworkStateChanged(); \
return m_Value; \
} \
protected: \
inline void NetworkStateChanged() \
{ \
CHECK_USENETWORKVARS ((ThisClass*)(((char*)this) - MyOffsetOf(ThisClass,name)))->NetworkStateChanged(); \
} \
private: \
char m_Value[length]; \
}; \
NetworkVar_##name name;
#define CNetworkArrayInternal( type, name, count, stateChangedFn ) \
class NetworkVar_##name; \
friend class NetworkVar_##name; \
typedef ThisClass MakeANetworkVar_##name; \
class NetworkVar_##name \
{ \
public: \
inline NetworkVar_##name() \
{ \
for ( int i = 0 ; i < count ; ++i ) \
NetworkVarConstruct( m_Value[i] ); \
} \
template <typename T> friend int ServerClassInit(T *); \
const type& operator[]( int i ) const \
{ \
return Get( i ); \
} \
\
const type& Get( int i ) const \
{ \
Assert( i >= 0 && i < count ); \
return m_Value[i]; \
} \
\
type& GetForModify( int i ) \
{ \
Assert( i >= 0 && i < count ); \
NetworkStateChanged( i ); \
return m_Value[i]; \
} \
\
void Set( int i, const type &val ) \
{ \
Assert( i >= 0 && i < count ); \
if( memcmp( &m_Value[i], &val, sizeof(type) ) ) \
{ \
NetworkStateChanged( i ); \
m_Value[i] = val; \
} \
} \
const type* Base() const { return m_Value; } \
int Count() const { return count; } \
protected: \
inline void NetworkStateChanged( int index ) \
{ \
CHECK_USENETWORKVARS ((ThisClass*)(((char*)this) - MyOffsetOf(ThisClass,name)))->stateChangedFn( &m_Value[index] ); \
} \
type m_Value[count]; \
}; \
NetworkVar_##name name;
#define CNetworkArray( type, name, count ) CNetworkArrayInternal( type, name, count, NetworkStateChanged )
#define NETWORK_VAR_START( type, name ) \
class NetworkVar_##name; \
friend class NetworkVar_##name; \
typedef ThisClass MakeANetworkVar_##name; \
class NetworkVar_##name \
{ \
public: \
template <typename T> friend int ServerClassInit(T *);
#define NETWORK_VAR_END( type, name, base, stateChangedFn ) \
public: \
static inline void NetworkStateChanged( void *ptr ) \
{ \
CHECK_USENETWORKVARS ((ThisClass*)(((char*)ptr) - MyOffsetOf(ThisClass,name)))->stateChangedFn( ptr ); \
} \
}; \
base< type, NetworkVar_##name > name;
#endif

View File

@ -0,0 +1,222 @@
#ifndef PARTICLE_ITERATORS_H
#define PARTICLE_ITERATORS_H
#ifdef _WIN32
#pragma once
#endif
#include "imesh.h"
#include "particledraw.h"
#define NUM_PARTICLES_PER_BATCH 200
#ifndef _XBOX
#define MAX_TOTAL_PARTICLES 2048
#else
#define MAX_TOTAL_PARTICLES 1024
#endif
class CParticleRenderIterator
{
friend class CParticleMgr;
friend class CParticleEffectBinding;
public:
CParticleRenderIterator();
const Particle* GetFirst();
const Particle* GetNext(float sortKey);
ParticleDraw* GetParticleDraw() const;
private:
void TestFlushBatch();
private:
CParticleEffectBinding* m_pEffectBinding;
CEffectMaterial* m_pMaterial;
ParticleDraw* m_pParticleDraw;
CMeshBuilder* m_pMeshBuilder;
IMesh* m_pMesh;
bool m_bBucketSort;
float m_MinZ;
float m_MaxZ;
float m_zCoords[MAX_TOTAL_PARTICLES];
int m_nZCoords;
Particle* m_pCur;
bool m_bGotFirst;
float m_flPrevZ;
int m_nParticlesInCurrentBatch;
};
class CParticleSimulateIterator
{
friend class CParticleMgr;
friend class CParticleEffectBinding;
public:
CParticleSimulateIterator();
Particle* GetFirst();
Particle* GetNext();
float GetTimeDelta() const;
void RemoveParticle(Particle* pParticle);
void RemoveAllParticles();
private:
CParticleEffectBinding* m_pEffectBinding;
CEffectMaterial* m_pMaterial;
float m_flTimeDelta;
bool m_bGotFirst;
Particle* m_pNextParticle;
};
inline CParticleRenderIterator::CParticleRenderIterator()
{
m_pCur = NULL;
m_bGotFirst = false;
m_flPrevZ = 0;
m_nParticlesInCurrentBatch = 0;
m_MinZ = 1e24;
m_MaxZ = -1e24;
m_nZCoords = 0;
}
inline const Particle* CParticleRenderIterator::GetFirst()
{
Assert(!m_bGotFirst);
m_bGotFirst = true;
m_pCur = m_pMaterial->m_Particles.m_pNext;
if (m_pCur == &m_pMaterial->m_Particles)
return NULL;
m_pParticleDraw->m_pSubTexture = m_pCur->m_pSubTexture;
return m_pCur;
}
inline void CParticleRenderIterator::TestFlushBatch()
{
++m_nParticlesInCurrentBatch;
if (m_nParticlesInCurrentBatch >= NUM_PARTICLES_PER_BATCH)
{
m_pMeshBuilder->End(false, true);
m_pMeshBuilder->Begin(m_pMesh, MATERIAL_QUADS, NUM_PARTICLES_PER_BATCH * 4);
m_nParticlesInCurrentBatch = 0;
}
}
inline const Particle* CParticleRenderIterator::GetNext(float sortKey)
{
Assert(m_bGotFirst);
Assert(m_pCur);
TestFlushBatch();
Particle* pNext = m_pCur->m_pNext;
if (m_bBucketSort)
{
m_MinZ = MIN(sortKey, m_MinZ);
m_MaxZ = MAX(sortKey, m_MaxZ);
m_zCoords[m_nZCoords] = sortKey;
++m_nZCoords;
}
else
{
if (m_pCur != m_pMaterial->m_Particles.m_pNext && m_flPrevZ > sortKey)
{
SwapParticles(m_pCur->m_pPrev, m_pCur);
}
else
{
m_flPrevZ = sortKey;
}
}
m_pCur = pNext;
if (m_pCur == &m_pMaterial->m_Particles)
return NULL;
m_pParticleDraw->m_pSubTexture = m_pCur->m_pSubTexture;
return m_pCur;
}
inline ParticleDraw* CParticleRenderIterator::GetParticleDraw() const
{
return m_pParticleDraw;
}
inline CParticleSimulateIterator::CParticleSimulateIterator()
{
m_pNextParticle = NULL;
#ifdef _DEBUG
m_bGotFirst = false;
#endif
}
inline Particle* CParticleSimulateIterator::GetFirst()
{
#ifdef _DEBUG
if (m_bGotFirst)
{
Assert(m_pNextParticle == &m_pMaterial->m_Particles);
}
#endif
Particle* pRet = m_pMaterial->m_Particles.m_pNext;
if (pRet == &m_pMaterial->m_Particles)
return NULL;
#ifdef _DEBUG
m_bGotFirst = true;
#endif
m_pNextParticle = pRet->m_pNext;
return pRet;
}
inline Particle* CParticleSimulateIterator::GetNext()
{
Particle* pRet = m_pNextParticle;
if (pRet == &m_pMaterial->m_Particles)
return NULL;
m_pNextParticle = pRet->m_pNext;
return pRet;
}
inline void CParticleSimulateIterator::RemoveParticle(Particle* pParticle)
{
m_pEffectBinding->RemoveParticle(pParticle);
}
inline void CParticleSimulateIterator::RemoveAllParticles()
{
Particle* pParticle = GetFirst();
while (pParticle)
{
RemoveParticle(pParticle);
pParticle = GetNext();
}
}
inline float CParticleSimulateIterator::GetTimeDelta() const
{
return m_flTimeDelta;
}
#endif

View File

@ -0,0 +1,66 @@
#ifndef PARTICLE_PARSE_H
#define PARTICLE_PARSE_H
#ifdef _WIN32
#pragma once
#endif
#include "utlvector.h"
#include "utlstring.h"
#include "ifilelist.h"
enum ParticleAttachment_t
{
PATTACH_ABSORIGIN = 0,
PATTACH_ABSORIGIN_FOLLOW,
PATTACH_CUSTOMORIGIN,
PATTACH_POINT,
PATTACH_POINT_FOLLOW,
PATTACH_WORLDORIGIN,
PATTACH_ROOTBONE_FOLLOW,
MAX_PATTACH_TYPES,
};
extern int GetAttachTypeFromString(const char* pszString);
#define PARTICLE_DISPATCH_FROM_ENTITY (1<<0)
#define PARTICLE_DISPATCH_RESET_PARTICLES (1<<1)
struct te_tf_particle_effects_colors_t
{
Vector m_vecColor1;
Vector m_vecColor2;
};
struct te_tf_particle_effects_control_point_t
{
ParticleAttachment_t m_eParticleAttachment;
Vector m_vecOffset;
};
void ParseParticleEffects(bool bLoadSheets, bool bPrecache);
void ParseParticleEffectsMap(const char* pMapName, bool bLoadSheets, IFileList* pFilesToReload = NULL);
void GetParticleManifest(CUtlVector<CUtlString>& list);
void PrecacheStandardParticleSystems();
class IFileList;
void ReloadParticleEffectsInList(IFileList* pFilesToReload);
void DispatchParticleEffect(const char* pszParticleName, ParticleAttachment_t iAttachType, CBaseEntity* pEntity, const char* pszAttachmentName, bool bResetAllParticlesOnEntity = false);
void DispatchParticleEffect(const char* pszParticleName, ParticleAttachment_t iAttachType, CBaseEntity* pEntity = NULL, int iAttachmentPoint = -1, bool bResetAllParticlesOnEntity = false);
void DispatchParticleEffect(const char* pszParticleName, Vector vecOrigin, QAngle vecAngles, CBaseEntity* pEntity = NULL);
void DispatchParticleEffect(const char* pszParticleName, Vector vecOrigin, Vector vecStart, QAngle vecAngles, CBaseEntity* pEntity = NULL);
void DispatchParticleEffect(int iEffectIndex, Vector vecOrigin, Vector vecStart, QAngle vecAngles, CBaseEntity* pEntity = NULL);
void DispatchParticleEffect(const char* pszParticleName, ParticleAttachment_t iAttachType, CBaseEntity* pEntity, const char* pszAttachmentName, Vector vecColor1, Vector vecColor2, bool bUseColors = true, bool bResetAllParticlesOnEntity = false);
void DispatchParticleEffect(const char* pszParticleName, Vector vecOrigin, QAngle vecAngles, Vector vecColor1, Vector vecColor2, bool bUseColors = true, CBaseEntity* pEntity = NULL, int iAttachType = PATTACH_CUSTOMORIGIN);
void StopParticleEffects(CBaseEntity* pEntity);
#endif

View File

@ -0,0 +1,110 @@
#ifndef PARTICLEPROPERTY_H
#define PARTICLEPROPERTY_H
#ifdef _WIN32
#pragma once
#endif
#include "smartptr.h"
#include "globalvars_base.h"
#include "particles_new.h"
#include "particle_parse.h"
class CBaseEntity;
class CNewParticleEffect;
#ifdef CLIENT_DLL
#define INVALID_PARTICLE_ATTACHMENT 0
#else
#define INVALID_PARTICLE_ATTACHMENT -1
#endif
struct ParticleControlPoint_t
{
ParticleControlPoint_t()
{
iControlPoint = 0;
iAttachType = PATTACH_ABSORIGIN_FOLLOW;
iAttachmentPoint = 0;
vecOriginOffset = vec3_origin;
}
int iControlPoint;
ParticleAttachment_t iAttachType;
int iAttachmentPoint;
Vector vecOriginOffset;
EHANDLE hEntity;
};
struct ParticleEffectList_t
{
ParticleEffectList_t()
{
pParticleEffect = NULL;
}
CUtlVector<ParticleControlPoint_t> pControlPoints;
CSmartPtr<CNewParticleEffect> pParticleEffect;
};
extern int GetAttachTypeFromString(const char* pszString);
class CParticleProperty
{
DECLARE_CLASS_NOBASE(CParticleProperty);
DECLARE_EMBEDDED_NETWORKVAR();
DECLARE_PREDICTABLE();
DECLARE_DATADESC();
public:
CParticleProperty();
~CParticleProperty();
void Init(CBaseEntity* pEntity);
CBaseEntity* GetOuter(void) { return m_pOuter; }
CNewParticleEffect* Create(const char* pszParticleName, ParticleAttachment_t iAttachType, const char* pszAttachmentName);
CNewParticleEffect* Create(const char* pszParticleName, ParticleAttachment_t iAttachType, int iAttachmentPoint = INVALID_PARTICLE_ATTACHMENT, Vector vecOriginOffset = vec3_origin);
void AddControlPoint(CNewParticleEffect* pEffect, int iPoint, C_BaseEntity* pEntity, ParticleAttachment_t iAttachType, const char* pszAttachmentName = NULL, Vector vecOriginOffset = vec3_origin);
void AddControlPoint(int iEffectIndex, int iPoint, C_BaseEntity* pEntity, ParticleAttachment_t iAttachType, int iAttachmentPoint = INVALID_PARTICLE_ATTACHMENT, Vector vecOriginOffset = vec3_origin);
inline void SetControlPointParent(CNewParticleEffect* pEffect, int whichControlPoint, int parentIdx);
void SetControlPointParent(int iEffectIndex, int whichControlPoint, int parentIdx);
void StopEmission(CNewParticleEffect* pEffect = NULL, bool bWakeOnStop = false, bool bDestroyAsleepSystems = false);
void StopEmissionAndDestroyImmediately(CNewParticleEffect* pEffect = NULL);
void StopParticlesInvolving(CBaseEntity* pEntity);
void StopParticlesNamed(const char* pszEffectName, bool bForceRemoveInstantly = false);
void StopParticlesWithNameAndAttachment(const char* pszEffectName, int iAttachmentPoint, bool bForceRemoveInstantly = false);
void OnParticleSystemUpdated(CNewParticleEffect* pEffect, float flTimeDelta);
void OnParticleSystemDeleted(CNewParticleEffect* pEffect);
#ifdef CLIENT_DLL
void OwnerSetDormantTo(bool bDormant);
#endif
void ReplaceParticleEffect(CNewParticleEffect* pOldEffect, CNewParticleEffect* pNewEffect);
void DebugPrintEffects(void);
int FindEffect(const char* pEffectName, int nStart = 0);
inline CNewParticleEffect* GetParticleEffectFromIdx(int idx);
private:
int GetParticleAttachment(C_BaseEntity* pEntity, const char* pszAttachmentName, const char* pszParticleName);
int FindEffect(CNewParticleEffect* pEffect);
void UpdateParticleEffect(ParticleEffectList_t* pEffect, bool bInitializing = false, int iOnlyThisControlPoint = -1);
void UpdateControlPoint(ParticleEffectList_t* pEffect, int iPoint, bool bInitializing);
private:
CBaseEntity* m_pOuter;
CUtlVector<ParticleEffectList_t> m_ParticleEffects;
int m_iDormancyChangedAtFrame;
friend class CBaseEntity;
};
#include "particle_property_inlines.h"
#endif

View File

@ -0,0 +1,25 @@
#ifndef PARTICLEPROPERTY_H
#pragma message("Do not include particle_property_inlines.h from anywhere other than particle_property.h!")
#pragma error
#endif
#ifndef PARTICLEPROPERTY_INLINES_H
#define PARTICLEPROPERTY_INLINES_H
#ifdef _WIN32
#pragma once
#endif
void CParticleProperty::SetControlPointParent(CNewParticleEffect* pEffect, int whichControlPoint, int parentIdx)
{
pEffect->SetControlPointParent(whichControlPoint, parentIdx);
}
CNewParticleEffect* CParticleProperty::GetParticleEffectFromIdx(int idx)
{
return m_ParticleEffects[idx].pParticleEffect.GetObject();
}
#endif

289
SpyCustom/particle_util.h Normal file
View File

@ -0,0 +1,289 @@
#ifndef PARTICLE_UTIL_H
#define PARTICLE_UTIL_H
#include "IMesh.h"
#include "particledraw.h"
#include "particlemgr.h"
#include "cdll_client_int.h"
#include "timedevent.h"
inline float FLerp(float minVal, float maxVal, float t)
{
return minVal + (maxVal - minVal) * t;
}
inline Vector VecLerp(const Vector& minVal, const Vector& maxVal, float t)
{
return minVal + (maxVal - minVal) * t;
}
inline float FRand(float minVal, float maxVal)
{
return minVal + ((float)rand() / RAND_MAX) * (maxVal - minVal);
}
inline void PhysicallySimulate(Vector& pos, Vector& velocity, const Vector& acceleration, const float fTimeDelta)
{
pos = pos + (velocity + (acceleration * fTimeDelta * 0.5f)) * fTimeDelta;
velocity = velocity + acceleration * fTimeDelta;
}
inline Vector GetGravityVector()
{
return Vector(0, 0, -150);
}
inline void RenderParticle_Color255SizeSpecularTCoord3(
ParticleDraw* pDraw,
const Vector& pos,
const Vector& color,
const float alpha,
const float size,
const unsigned char* specular,
const float tCoord
)
{
if (alpha < 0.5f)
return;
CMeshBuilder* pBuilder = pDraw->GetMeshBuilder();
if (!pBuilder)
return;
unsigned char ubColor[4];
ubColor[0] = (unsigned char)RoundFloatToInt(color.x);
ubColor[1] = (unsigned char)RoundFloatToInt(color.y);
ubColor[2] = (unsigned char)RoundFloatToInt(color.z);
ubColor[3] = (unsigned char)RoundFloatToInt(alpha);
pBuilder->Position3f(pos.x - size, pos.y - size, pos.z);
pBuilder->Color4ubv(ubColor);
pBuilder->TexCoord3f(0, pDraw->m_pSubTexture->m_tCoordMins[0], pDraw->m_pSubTexture->m_tCoordMaxs[1], tCoord);
pBuilder->Specular3ubv(specular);
pBuilder->AdvanceVertex();
pBuilder->Position3f(pos.x - size, pos.y + size, pos.z);
pBuilder->Color4ubv(ubColor);
pBuilder->TexCoord3f(0, pDraw->m_pSubTexture->m_tCoordMins[0], pDraw->m_pSubTexture->m_tCoordMins[1], tCoord);
pBuilder->Specular3ubv(specular);
pBuilder->AdvanceVertex();
pBuilder->Position3f(pos.x + size, pos.y + size, pos.z);
pBuilder->Color4ubv(ubColor);
pBuilder->TexCoord3f(0, pDraw->m_pSubTexture->m_tCoordMaxs[0], pDraw->m_pSubTexture->m_tCoordMins[1], tCoord);
pBuilder->Specular3ubv(specular);
pBuilder->AdvanceVertex();
pBuilder->Position3f(pos.x + size, pos.y - size, pos.z);
pBuilder->Color4ubv(ubColor);
pBuilder->TexCoord3f(0, pDraw->m_pSubTexture->m_tCoordMaxs[0], pDraw->m_pSubTexture->m_tCoordMaxs[1], tCoord);
pBuilder->Specular3ubv(specular);
pBuilder->AdvanceVertex();
}
inline void RenderParticle_Color255Size(
ParticleDraw* pDraw,
const Vector& pos,
const Vector& color,
const float alpha,
const float size)
{
if (alpha < 0.5f)
return;
CMeshBuilder* pBuilder = pDraw->GetMeshBuilder();
if (!pBuilder)
return;
unsigned char ubColor[4];
ubColor[0] = (unsigned char)RoundFloatToInt(color.x);
ubColor[1] = (unsigned char)RoundFloatToInt(color.y);
ubColor[2] = (unsigned char)RoundFloatToInt(color.z);
ubColor[3] = (unsigned char)RoundFloatToInt(alpha);
pBuilder->Position3f(pos.x - size, pos.y - size, pos.z);
pBuilder->Color4ubv(ubColor);
pBuilder->TexCoord2f(0, pDraw->m_pSubTexture->m_tCoordMins[0], pDraw->m_pSubTexture->m_tCoordMaxs[1]);
pBuilder->AdvanceVertex();
pBuilder->Position3f(pos.x - size, pos.y + size, pos.z);
pBuilder->Color4ubv(ubColor);
pBuilder->TexCoord2f(0, pDraw->m_pSubTexture->m_tCoordMins[0], pDraw->m_pSubTexture->m_tCoordMins[1]);
pBuilder->AdvanceVertex();
pBuilder->Position3f(pos.x + size, pos.y + size, pos.z);
pBuilder->Color4ubv(ubColor);
pBuilder->TexCoord2f(0, pDraw->m_pSubTexture->m_tCoordMaxs[0], pDraw->m_pSubTexture->m_tCoordMins[1]);
pBuilder->AdvanceVertex();
pBuilder->Position3f(pos.x + size, pos.y - size, pos.z);
pBuilder->Color4ubv(ubColor);
pBuilder->TexCoord2f(0, pDraw->m_pSubTexture->m_tCoordMaxs[0], pDraw->m_pSubTexture->m_tCoordMaxs[1]);
pBuilder->AdvanceVertex();
}
inline void RenderParticle_Color255SizeNormal(
ParticleDraw* pDraw,
const Vector& pos,
const Vector& color,
const float alpha,
const float size,
const Vector& vNormal)
{
if (alpha < 0.5f)
return;
CMeshBuilder* pBuilder = pDraw->GetMeshBuilder();
if (!pBuilder)
return;
unsigned char ubColor[4];
ubColor[0] = (unsigned char)RoundFloatToInt(color.x);
ubColor[1] = (unsigned char)RoundFloatToInt(color.y);
ubColor[2] = (unsigned char)RoundFloatToInt(color.z);
ubColor[3] = (unsigned char)RoundFloatToInt(alpha);
}
inline void RenderParticle_Color255SizeNormalAngle(
ParticleDraw* pDraw,
const Vector& pos,
const Vector& color,
const float alpha,
const float size,
const Vector& vNormal,
const float angle)
{
if (alpha < 0.5f)
return;
CMeshBuilder* pBuilder = pDraw->GetMeshBuilder();
if (!pBuilder)
return;
unsigned char ubColor[4];
ubColor[0] = (unsigned char)RoundFloatToInt(color.x);
ubColor[1] = (unsigned char)RoundFloatToInt(color.y);
ubColor[2] = (unsigned char)RoundFloatToInt(color.z);
ubColor[3] = (unsigned char)RoundFloatToInt(alpha);
float ca = (float)cos(angle);
float sa = (float)sin(angle);
}
inline void RenderParticle_ColorSize(
ParticleDraw* pDraw,
const Vector& pos,
const Vector& color,
const float alpha,
const float size
)
{
if (alpha < 0.001f)
return;
CMeshBuilder* pBuilder = pDraw->GetMeshBuilder();
if (!pBuilder)
return;
unsigned char ubColor[4];
ubColor[0] = (unsigned char)RoundFloatToInt(color.x * 254.9f);
ubColor[1] = (unsigned char)RoundFloatToInt(color.y * 254.9f);
ubColor[2] = (unsigned char)RoundFloatToInt(color.z * 254.9f);
ubColor[3] = (unsigned char)RoundFloatToInt(alpha * 254.9f);
}
inline void RenderParticle_ColorSizeAngle(
ParticleDraw* pDraw,
const Vector& pos,
const Vector& color,
const float alpha,
const float size,
const float angle)
{
if (alpha < 0.001f)
return;
CMeshBuilder* pBuilder = pDraw->GetMeshBuilder();
if (!pBuilder)
return;
unsigned char ubColor[4];
ubColor[0] = (unsigned char)RoundFloatToInt(color.x * 254.9f);
ubColor[1] = (unsigned char)RoundFloatToInt(color.y * 254.9f);
ubColor[2] = (unsigned char)RoundFloatToInt(color.z * 254.9f);
ubColor[3] = (unsigned char)RoundFloatToInt(alpha * 254.9f);
float sa, ca;
SinCos(angle, &sa, &ca);
}
inline void RenderParticle_ColorSizeAngles(
ParticleDraw* pDraw,
const Vector& pos,
const Vector& color,
const float alpha,
const float size,
const QAngle& angles)
{
if (alpha < 0.001f)
return;
CMeshBuilder* pBuilder = pDraw->GetMeshBuilder();
if (!pBuilder)
return;
unsigned char ubColor[4];
ubColor[0] = (unsigned char)RoundFloatToInt(color.x * 254.9f);
ubColor[1] = (unsigned char)RoundFloatToInt(color.y * 254.9f);
ubColor[2] = (unsigned char)RoundFloatToInt(color.z * 254.9f);
ubColor[3] = (unsigned char)RoundFloatToInt(alpha * 254.9f);
Vector vNorm, vWidth, vHeight;
AngleVectors(angles, &vNorm, &vWidth, &vHeight);
Vector vVertex = pos;
}
inline float GetAlphaDistanceFade(
const Vector& pos,
const float fadeNearDist,
const float fadeFarDist)
{
if (-pos.z > fadeFarDist)
{
return 1;
}
else if (-pos.z > fadeNearDist)
{
return (-pos.z - fadeNearDist) / (fadeFarDist - fadeNearDist);
}
else
{
return 0;
}
}
inline Vector WorldGetLightForPoint(const Vector& vPos, bool bClamp)
{
#if defined(PARTICLEPROTOTYPE_APP)
return Vector(1, 1, 1);
#else
return engine->GetLightForPoint(vPos, bClamp);
#endif
}
#endif

56
SpyCustom/particledraw.h Normal file
View File

@ -0,0 +1,56 @@
#ifndef PARTICLEDRAW_H
#define PARTICLEDRAW_H
class IMaterial;
class CMeshBuilder;
class CParticleSubTexture;
class ParticleDraw
{
friend class CParticleEffectBinding;
public:
ParticleDraw();
void Init(CMeshBuilder* pMeshBuilder, IMaterial* pMaterial, float fTimeDelta);
float GetTimeDelta() const;
CMeshBuilder* GetMeshBuilder();
CParticleSubTexture* m_pSubTexture;
private:
CMeshBuilder* m_pMeshBuilder;
IMaterial* m_pMaterial;
float m_fTimeDelta;
};
inline ParticleDraw::ParticleDraw()
{
m_pMaterial = 0;
}
inline void ParticleDraw::Init(CMeshBuilder* pMeshBuilder, IMaterial* pMaterial, float fTimeDelta)
{
m_pMeshBuilder = pMeshBuilder;
m_pMaterial = pMaterial;
m_fTimeDelta = fTimeDelta;
}
inline float ParticleDraw::GetTimeDelta() const
{
return m_fTimeDelta;
}
inline CMeshBuilder* ParticleDraw::GetMeshBuilder()
{
return m_pMeshBuilder;
}
#endif

617
SpyCustom/particlemgr.h Normal file
View File

@ -0,0 +1,617 @@
#ifndef PARTICLEMGR_H
#define PARTICLEMGR_H
#ifdef _WIN32
#pragma once
#endif
#include "imaterial.h"
#include "imaterialsystem.h"
#include "vector.h"
#include "vmatrix.h"
#include "Mathlib.h"
#include "iclientrenderable.h"
#include "clientleafsystem.h"
#include "fasttimer.h"
#include "utllinkedlist.h"
#include "UtlDict.h"
#ifdef WIN32
#include <typeinfo>
#else
#include <typeinfo>
#endif
#include "utlintrusivelist.h"
#include "utlobjectreference.h"
#include "utlstring.h"
class IParticleEffect;
class IClientParticleListener;
struct Particle;
class ParticleDraw;
class CMeshBuilder;
class CUtlMemoryPool;
class CEffectMaterial;
class CParticleSimulateIterator;
class CParticleRenderIterator;
class IThreadPool;
class CParticleSystemDefinition;
class CParticleMgr;
class CNewParticleEffect;
class CParticleCollection;
#define INVALID_MATERIAL_HANDLE NULL
class CParticleSubTexture;
class CParticleSubTextureGroup;
struct Particle
{
Particle* m_pPrev, * m_pNext;
CParticleSubTexture* m_pSubTexture;
Vector m_Pos;
};
typedef CParticleSubTexture* PMaterialHandle;
class CEffectMaterial
{
public:
CEffectMaterial();
public:
CParticleSubTextureGroup* m_pGroup;
Particle m_Particles;
CEffectMaterial* m_pHashedNext;
};
class CParticleSubTextureGroup
{
public:
CParticleSubTextureGroup();
~CParticleSubTextureGroup();
IMaterial* m_pPageMaterial;
};
class CParticleSubTexture
{
public:
CParticleSubTexture();
float m_tCoordMins[2];
float m_tCoordMaxs[2];
CParticleSubTextureGroup* m_pGroup;
CParticleSubTextureGroup m_DefaultGroup;
#ifdef _DEBUG
char* m_szDebugName;
#endif
IMaterial* m_pMaterial;
};
abstract_class IParticleEffect
{
public:
virtual ~IParticleEffect() {}
virtual void Update(float fTimeDelta) {}
virtual void StartRender(VMatrix & effectMatrix) {}
virtual bool ShouldSimulate() const = 0;
virtual void SetShouldSimulate(bool bSim) = 0;
virtual void SimulateParticles(CParticleSimulateIterator* pIterator) = 0;
virtual void RenderParticles(CParticleRenderIterator* pIterator) = 0;
virtual void NotifyRemove() {}
virtual void NotifyDestroyParticle(Particle* pParticle) {}
virtual const Vector& GetSortOrigin() = 0;
virtual const Vector* GetParticlePosition(Particle* pParticle) { return &pParticle->m_Pos; }
virtual const char* GetEffectName() { return "???"; }
};
#define REGISTER_EFFECT( effect ) \
IParticleEffect* effect##_Factory() \
{ \
return new effect; \
} \
struct effect##_RegistrationHelper \
{ \
effect##_RegistrationHelper() \
{ \
ParticleMgr()->RegisterEffect( typeid( effect ).name(), effect##_Factory ); \
} \
}; \
static effect##_RegistrationHelper g_##effect##_RegistrationHelper
#define REGISTER_EFFECT_USING_CREATE( effect ) \
IParticleEffect* effect##_Factory() \
{ \
return effect::Create( #effect ).GetObject(); \
} \
struct effect##_RegistrationHelper \
{ \
effect##_RegistrationHelper() \
{ \
ParticleMgr()->RegisterEffect( typeid( effect ).name(), effect##_Factory ); \
} \
}; \
static effect##_RegistrationHelper g_##effect##_RegistrationHelper
class CParticleEffectBinding : public CDefaultClientRenderable
{
friend class CParticleMgr;
friend class CParticleSimulateIterator;
friend class CNewParticleEffect;
public:
CParticleEffectBinding();
~CParticleEffectBinding();
public:
void SimulateParticles(float flTimeDelta);
PMaterialHandle FindOrAddMaterial(const char* pMaterialName);
Particle* AddParticle(int sizeInBytes, PMaterialHandle pMaterial);
void SetBBox(const Vector& bbMin, const Vector& bbMax, bool bDisableAutoUpdate = true);
void GetWorldspaceBounds(Vector* pMins, Vector* pMaxs);
const matrix3x4_t& GetLocalSpaceTransform() const;
void SetLocalSpaceTransform(const matrix3x4_t& transform);
bool EnlargeBBoxToContain(const Vector& pt);
void SetDrawThruLeafSystem(int bDraw);
void SetDrawBeforeViewModel(int bDraw);
int GetRemoveFlag() { return GetFlag(FLAGS_REMOVE); }
void SetRemoveFlag() { SetFlag(FLAGS_REMOVE, 1); }
int GetAlwaysSimulate() { return GetFlag(FLAGS_ALWAYSSIMULATE); }
void SetAlwaysSimulate(int bAlwaysSimulate) { SetFlag(FLAGS_ALWAYSSIMULATE, bAlwaysSimulate); }
void SetIsNewParticleSystem(void) { SetFlag(FLAGS_NEW_PARTICLE_SYSTEM, 1); }
int WasDrawnPrevFrame() { return GetFlag(FLAGS_DRAWN_PREVFRAME); }
void SetWasDrawnPrevFrame(int bWasDrawnPrevFrame) { SetFlag(FLAGS_DRAWN_PREVFRAME, bWasDrawnPrevFrame); }
int IsEffectCameraSpace() { return GetFlag(FLAGS_CAMERASPACE); }
void SetEffectCameraSpace(int bCameraSpace) { SetFlag(FLAGS_CAMERASPACE, bCameraSpace); }
int GetAutoApplyLocalTransform() const { return GetFlag(FLAGS_AUTOAPPLYLOCALTRANSFORM); }
void SetAutoApplyLocalTransform(int b) { SetFlag(FLAGS_AUTOAPPLYLOCALTRANSFORM, b); }
int GetAutoUpdateBBox() { return GetFlag(FLAGS_AUTOUPDATEBBOX); }
void SetAutoUpdateBBox(int bAutoUpdate) { SetFlag(FLAGS_AUTOUPDATEBBOX, bAutoUpdate); }
int GetNumActiveParticles();
void SetParticleCullRadius(float flMaxParticleRadius);
int GetActiveParticleList(int nCount, Particle** ppParticleList);
void DetectChanges();
private:
void SetFlag(int flag, int bOn) { if (bOn) m_Flags |= flag; else m_Flags &= ~flag; }
int GetFlag(int flag) const { return m_Flags & flag; }
void Init(CParticleMgr* pMgr, IParticleEffect* pSim);
void Term();
void RemoveParticle(Particle* pParticle);
void StartDrawMaterialParticles(
CEffectMaterial* pMaterial,
float flTimeDelta,
IMesh*& pMesh,
CMeshBuilder& builder,
ParticleDraw& particleDraw,
bool bWireframe);
int DrawMaterialParticles(
bool bBucketSort,
CEffectMaterial* pMaterial,
float flTimeDelta,
bool bWireframe
);
void GrowBBoxFromParticlePositions(CEffectMaterial* pMaterial, bool& bboxSet, Vector& bbMin, Vector& bbMax);
void RenderStart(VMatrix& mTempModel, VMatrix& mTempView);
void RenderEnd(VMatrix& mModel, VMatrix& mView);
void BBoxCalcStart(Vector& bbMin, Vector& bbMax);
void BBoxCalcEnd(bool bboxSet, Vector& bbMin, Vector& bbMax);
void DoBucketSort(
CEffectMaterial* pMaterial,
float* zCoords,
int nZCoords,
float minZ,
float maxZ);
int GetRemovalInProgressFlag() { return GetFlag(FLAGS_REMOVALINPROGRESS); }
void SetRemovalInProgressFlag() { SetFlag(FLAGS_REMOVALINPROGRESS, 1); }
int GetNeedsBBoxUpdate() { return GetFlag(FLAGS_NEEDS_BBOX_UPDATE); }
void SetNeedsBBoxUpdate(int bFirstUpdate) { SetFlag(FLAGS_NEEDS_BBOX_UPDATE, bFirstUpdate); }
int GetFirstFrameFlag() { return GetFlag(FLAGS_FIRST_FRAME); }
void SetFirstFrameFlag(int bFirstUpdate) { SetFlag(FLAGS_FIRST_FRAME, bFirstUpdate); }
int WasDrawn() { return GetFlag(FLAGS_DRAWN); }
void SetDrawn(int bDrawn) { SetFlag(FLAGS_DRAWN, bDrawn); }
bool RecalculateBoundingBox();
CEffectMaterial* GetEffectMaterial(CParticleSubTexture* pSubTexture);
public:
virtual const Vector& GetRenderOrigin(void);
virtual const QAngle& GetRenderAngles(void);
virtual const matrix3x4_t& RenderableToWorldTransform();
virtual void GetRenderBounds(Vector& mins, Vector& maxs);
virtual bool ShouldDraw(void);
virtual int DrawModel(int flags, const RenderableInstance_t& instance);
private:
enum
{
FLAGS_REMOVE = (1 << 0),
FLAGS_REMOVALINPROGRESS = (1 << 1),
FLAGS_NEEDS_BBOX_UPDATE = (1 << 2),
FLAGS_AUTOUPDATEBBOX = (1 << 3),
FLAGS_ALWAYSSIMULATE = (1 << 4),
FLAGS_DRAWN = (1 << 5),
FLAGS_DRAWN_PREVFRAME = (1 << 6),
FLAGS_CAMERASPACE = (1 << 7),
FLAGS_DRAW_THRU_LEAF_SYSTEM = (1 << 8),
FLAGS_DRAW_BEFORE_VIEW_MODEL = (1 << 9),
FLAGS_AUTOAPPLYLOCALTRANSFORM = (1 << 10),
FLAGS_FIRST_FRAME = (1 << 11),
FLAGS_NEW_PARTICLE_SYSTEM = (1 << 12)
};
VMatrix m_LocalSpaceTransform;
bool m_bLocalSpaceTransformIdentity;
Vector m_Min;
Vector m_Max;
Vector m_LastMin;
Vector m_LastMax;
float m_flParticleCullRadius;
unsigned short m_nActiveParticles;
unsigned short m_FrameCode;
unsigned short m_ListIndex;
IParticleEffect* m_pSim;
CParticleMgr* m_pParticleMgr;
int m_Flags;
enum { EFFECT_MATERIAL_HASH_SIZE = 8 };
CEffectMaterial* m_EffectMaterialHash[EFFECT_MATERIAL_HASH_SIZE];
#ifdef INFESTED_PARTICLES
public:
#endif
CUtlLinkedList<CEffectMaterial*, unsigned short> m_Materials;
unsigned short m_UpdateBBoxCounter;
};
class CParticleLightInfo
{
public:
Vector m_vPos;
Vector m_vColor;
float m_flIntensity;
};
typedef IParticleEffect* (*CreateParticleEffectFN)();
enum
{
TOOLPARTICLESYSTEMID_INVALID = -1,
};
class CParticleCollection;
class CNonDrawingParticleSystem
{
public:
CNonDrawingParticleSystem* m_pNext;
CNonDrawingParticleSystem* m_pPrev;
CParticleCollection* m_pSystem;
FORCEINLINE CParticleCollection* operator()(void) const
{
return m_pSystem;
}
FORCEINLINE CParticleCollection* Get(void) const
{
return m_pSystem;
}
~CNonDrawingParticleSystem(void);
};
class CClientTools;
class CParticleMgr
{
friend class CParticleEffectBinding;
friend class CParticleCollection;
friend class CNonDrawingParticleSystem;
friend class CClientTools;
public:
CParticleMgr();
virtual ~CParticleMgr();
bool Init(unsigned long nPreallocatedParticles, IMaterialSystem* pMaterial);
void Term();
void LevelInit();
void RegisterEffect(const char* pEffectType, CreateParticleEffectFN func);
IParticleEffect* CreateEffect(const char* pEffectType);
bool AddEffect(CParticleEffectBinding* pEffect, IParticleEffect* pSim);
void RemoveEffect(CParticleEffectBinding* pEffect);
void AddEffect(CNewParticleEffect* pEffect);
void RemoveEffect(CNewParticleEffect* pEffect);
void RemoveAllEffects();
void IncrementFrameCode();
void Simulate(float fTimeDelta);
void PostRender();
void DrawBeforeViewModelEffects();
VMatrix& GetModelView();
Particle* AllocParticle(int size);
void FreeParticle(Particle*);
PMaterialHandle GetPMaterial(const char* pMaterialName);
IMaterial* PMaterialToIMaterial(PMaterialHandle hMaterial);
void RepairPMaterial(PMaterialHandle hMaterial);
void GetDirectionalLightInfo(CParticleLightInfo& info) const;
void SetDirectionalLightInfo(const CParticleLightInfo& info);
void SpewInfo(bool bDetail);
void AddEffectListener(IClientParticleListener* pListener);
void RemoveEffectListener(IClientParticleListener* pListener);
int AllocateToolParticleEffectId();
void RemoveAllNewEffects();
CNewParticleEffect* FirstNewEffect();
CNewParticleEffect* NextNewEffect(CNewParticleEffect* pEffect);
void RenderParticleSystems(bool bEnable);
bool ShouldRenderParticleSystems() const;
void RemoveOldParticleEffects(float flTime);
int GetNumParticles() const { return m_nCurrentParticlesAllocated; }
CNonDrawingParticleSystem* CreateNonDrawingEffect(const char* pEffectName);
private:
struct RetireInfo_t
{
CParticleCollection* m_pCollection;
float m_flScreenArea;
bool m_bFirstFrame;
};
void UpdateAllEffects(float flTimeDelta);
void UpdateNewEffects(float flTimeDelta);
void SpewActiveParticleSystems();
CParticleSubTextureGroup* FindOrAddSubTextureGroup(IMaterial* pPageMaterial);
int ComputeParticleDefScreenArea(int nInfoCount, RetireInfo_t* pInfo, float* pTotalArea, CParticleSystemDefinition* pDef,
const CViewSetup& view, const VMatrix& worldToPixels, float flFocalDist);
bool RetireParticleCollections(CParticleSystemDefinition* pDef, int nCount, RetireInfo_t* pInfo, float flScreenArea, float flMaxTotalArea);
void BuildParticleSimList(CUtlVector< CNewParticleEffect* >& list);
bool EarlyRetireParticleSystems(int nCount, CNewParticleEffect** ppEffects);
static int RetireSort(const void* p1, const void* p2);
private:
int m_nCurrentParticlesAllocated;
CParticleLightInfo m_DirectionalLight;
unsigned short m_FrameCode;
bool m_bUpdatingEffects;
bool m_bRenderParticleEffects;
CUtlLinkedList<CParticleEffectBinding*, unsigned short> m_Effects;
CUtlIntrusiveDList< CNewParticleEffect > m_NewEffects;
CUtlIntrusiveDList< CNonDrawingParticleSystem > m_NonDrawingParticleSystems;
CUtlVector< IClientParticleListener*> m_effectListeners;
IMaterialSystem* m_pMaterialSystem;
VMatrix m_mModelView;
CUtlVector<CParticleSubTextureGroup*> m_SubTextureGroups;
CUtlDict<CParticleSubTexture*, unsigned short> m_SubTextures;
CParticleSubTexture m_DefaultInvalidSubTexture;
CUtlMap< const char*, CreateParticleEffectFN > m_effectFactories;
int m_nToolParticleEffectId;
IThreadPool* m_pThreadPool[2];
};
inline int CParticleMgr::AllocateToolParticleEffectId()
{
return m_nToolParticleEffectId++;
}
class IClientParticleListener
{
public:
virtual void OnParticleEffectAdded(IParticleEffect* pEffect) = 0;
virtual void OnParticleEffectRemoved(IParticleEffect* pEffect) = 0;
};
float Helper_GetTime();
float Helper_GetFrameTime();
float Helper_RandomFloat(float minVal, float maxVal);
int Helper_RandomInt(int minVal, int maxVal);
inline VMatrix& CParticleMgr::GetModelView()
{
return m_mModelView;
}
inline const matrix3x4_t& CParticleEffectBinding::GetLocalSpaceTransform() const
{
return m_LocalSpaceTransform.As3x4();
}
CParticleMgr* ParticleMgr();
struct StandardParticle_t : public Particle
{
void SetColor(float r, float g, float b);
void SetAlpha(float a);
Vector m_Velocity;
float m_Lifetime;
unsigned char m_EffectData;
unsigned short m_EffectDataWord;
unsigned char m_Color[4];
};
inline void TransformParticle(const VMatrix& vMat, const Vector& vIn, Vector& vOut)
{
vOut.x = vMat.m[0][0] * vIn.x + vMat.m[0][1] * vIn.y + vMat.m[0][2] * vIn.z + vMat.m[0][3];
vOut.y = vMat.m[1][0] * vIn.x + vMat.m[1][1] * vIn.y + vMat.m[1][2] * vIn.z + vMat.m[1][3];
vOut.z = vMat.m[2][0] * vIn.x + vMat.m[2][1] * vIn.y + vMat.m[2][2] * vIn.z + vMat.m[2][3];
}
inline void StandardParticle_t::SetColor(float r, float g, float b)
{
m_Color[0] = (unsigned char)(r * 255.9f);
m_Color[1] = (unsigned char)(g * 255.9f);
m_Color[2] = (unsigned char)(b * 255.9f);
}
inline void StandardParticle_t::SetAlpha(float a)
{
m_Color[3] = (unsigned char)(a * 255.9f);
}
inline void UnlinkParticle(Particle* pParticle)
{
pParticle->m_pPrev->m_pNext = pParticle->m_pNext;
pParticle->m_pNext->m_pPrev = pParticle->m_pPrev;
}
inline void InsertParticleBefore(Particle* pInsert, Particle* pNext)
{
pInsert->m_pNext = pNext;
pInsert->m_pPrev = pNext->m_pPrev;
pInsert->m_pNext->m_pPrev = pInsert->m_pPrev->m_pNext = pInsert;
}
inline void InsertParticleAfter(Particle* pInsert, Particle* pPrev)
{
pInsert->m_pPrev = pPrev;
pInsert->m_pNext = pPrev->m_pNext;
pInsert->m_pNext->m_pPrev = pInsert->m_pPrev->m_pNext = pInsert;
}
inline void SwapParticles(Particle* pPrev, Particle* pCur)
{
UnlinkParticle(pCur);
InsertParticleBefore(pCur, pPrev);
}
#include "particle_iterators.h"
#endif

1954
SpyCustom/particles.h Normal file

File diff suppressed because it is too large Load Diff

295
SpyCustom/particles_new.h Normal file
View File

@ -0,0 +1,295 @@
#ifndef PARTICLES_NEW_H
#define PARTICLES_NEW_H
#ifdef _WIN32
#pragma once
#endif
#include "particlemgr.h"
#include "particles.h"
#include "particlesphererenderer.h"
#include "smartptr.h"
#include "particles_simple.h"
#include "utlobjectreference.h"
class CNewParticleEffect : public IParticleEffect, public CParticleCollection, public CDefaultClientRenderable
{
public:
DECLARE_CLASS_NOBASE(CNewParticleEffect);
DECLARE_REFERENCED_CLASS(CNewParticleEffect);
public:
friend class CRefCountAccessor;
CNewParticleEffect* m_pNext;
CNewParticleEffect* m_pPrev;
void SetSortOrigin(const Vector& vSortOrigin);
bool ShouldDraw(void);
virtual bool IsTransparent(void);
virtual bool IsTwoPass(void);
virtual bool UsesPowerOfTwoFrameBufferTexture(void);
virtual bool UsesFullFrameBufferTexture(void);
const QAngle& GetRenderAngles(void);
const matrix3x4_t& RenderableToWorldTransform();
void GetRenderBounds(Vector& mins, Vector& maxs);
void DetectChanges(void);
const Vector& GetRenderOrigin(void);
PMaterialHandle GetPMaterial(const char* name);
bool RecalculateBoundingBox();
Particle* AddParticle(unsigned int particleSize, PMaterialHandle material, const Vector& origin);
const char* GetEffectName();
void SetDontRemove(bool bSet);
void SetDrawn(bool bDrawn);
void SetFirstFrameFlag(bool bFirst);
void SetNeedsBBoxUpdate(bool bNeedsUpdate);
void SetAutoUpdateBBox(bool bNeedsUpdate);
void SetRemoveFlag(void);
bool GetRemoveFlag(void);
bool GetFirstFrameFlag(void);
bool GetNeedsBBoxUpdate(void);
bool GetAutoUpdateBBox(void);
bool ShouldPerformCullCheck() const;
void MarkShouldPerformCullCheck(bool bEnable);
CBaseEntity* GetOwner(void) { return m_hOwner; }
void SetOwner(CBaseEntity* pOwner) { m_hOwner = pOwner; }
CNewParticleEffect* ReplaceWith(const char* pParticleSystemName);
static CSmartPtr<CNewParticleEffect> Create(CBaseEntity* pOwner, const char* pParticleSystemName,
const char* pDebugName = NULL);
static CSmartPtr<CNewParticleEffect> Create(CBaseEntity* pOwner, CParticleSystemDefinition* pDef,
const char* pDebugName = NULL);
virtual int DrawModel(int flags);
void DebugDrawBbox(bool bCulled);
public:
void StopEmission(bool bInfiniteOnly = false, bool bRemoveAllParticles = false, bool bWakeOnStop = false);
void SetDormant(bool bDormant);
void SetControlPoint(int nWhichPoint, const Vector& v);
void SetControlPointEntity(int nWhichPoint, CBaseEntity* pEntity);
void SetControlPointOrientation(int nWhichPoint, const Quaternion& q);
void SetControlPointOrientation(int nWhichPoint, const Vector& forward, const Vector& right, const Vector& up);
void SetControlPointForwardVector(int nWhichPoint, const Vector& v);
void SetControlPointUpVector(int nWhichPoint, const Vector& v);
void SetControlPointRightVector(int nWhichPoint, const Vector& v);
FORCEINLINE EHANDLE const& GetControlPointEntity(int nWhichPoint)
{
return m_hControlPointOwners[nWhichPoint];
}
public:
virtual void SimulateParticles(CParticleSimulateIterator* pIterator)
{
}
virtual void RenderParticles(CParticleRenderIterator* pIterator)
{
}
virtual void SetParticleCullRadius(float radius);
virtual void NotifyRemove(void);
virtual const Vector& GetSortOrigin(void);
virtual void Update(float flTimeDelta);
void SetDynamicallyAllocated(bool bDynamic = true);
virtual bool ShouldSimulate() const { return m_bSimulate; }
virtual void SetShouldSimulate(bool bSim) { m_bSimulate = bSim; }
int AllocateToolParticleEffectId();
int GetToolParticleEffectId() const;
CNewParticleEffect(CBaseEntity* pOwner, const char* pEffectName);
CNewParticleEffect(CBaseEntity* pOwner, CParticleSystemDefinition* pEffect);
virtual ~CNewParticleEffect();
protected:
int IsReleased();
const char* m_pDebugName;
bool m_bDontRemove : 1;
bool m_bRemove : 1;
bool m_bDrawn : 1;
bool m_bNeedsBBoxUpdate : 1;
bool m_bIsFirstFrame : 1;
bool m_bAutoUpdateBBox : 1;
bool m_bAllocated : 1;
bool m_bSimulate : 1;
bool m_bShouldPerformCullCheck : 1;
int m_nToolParticleEffectId;
Vector m_vSortOrigin;
EHANDLE m_hOwner;
EHANDLE m_hControlPointOwners[MAX_PARTICLE_CONTROL_POINTS];
Vector m_LastMin;
Vector m_LastMax;
private:
void AddRef();
void Release();
void RecordControlPointOrientation(int nWhichPoint);
void Construct();
int m_RefCount;
CNewParticleEffect(const CNewParticleEffect&);
};
inline int CNewParticleEffect::GetToolParticleEffectId() const
{
return m_nToolParticleEffectId;
}
inline int CNewParticleEffect::AllocateToolParticleEffectId()
{
m_nToolParticleEffectId = ParticleMgr()->AllocateToolParticleEffectId();
return m_nToolParticleEffectId;
}
inline void CNewParticleEffect::SetSortOrigin(const Vector& vSortOrigin)
{
m_vSortOrigin = vSortOrigin;
}
inline const Vector& CNewParticleEffect::GetSortOrigin(void)
{
return m_vSortOrigin;
}
inline bool CNewParticleEffect::ShouldDraw(void)
{
return true;
}
inline bool CNewParticleEffect::IsTransparent(void)
{
return CParticleCollection::IsTranslucent();
}
inline const QAngle& CNewParticleEffect::GetRenderAngles(void)
{
return vec3_angle;
}
inline const matrix3x4_t& CNewParticleEffect::RenderableToWorldTransform()
{
static matrix3x4_t mat;
SetIdentityMatrix(mat);
PositionMatrix(GetRenderOrigin(), mat);
return mat;
}
inline Vector const& CNewParticleEffect::GetRenderOrigin(void)
{
return m_vSortOrigin;
}
inline PMaterialHandle CNewParticleEffect::GetPMaterial(const char* name)
{
Assert(0);
return NULL;
}
inline Particle* CNewParticleEffect::AddParticle(unsigned int particleSize, PMaterialHandle material, const Vector& origin)
{
Assert(0);
return NULL;
}
inline const char* CNewParticleEffect::GetEffectName()
{
return GetName();
}
inline void CNewParticleEffect::SetDontRemove(bool bSet)
{
m_bDontRemove = bSet;
}
inline void CNewParticleEffect::SetDrawn(bool bDrawn)
{
m_bDrawn = bDrawn;
}
inline void CNewParticleEffect::SetFirstFrameFlag(bool bFirst)
{
m_bIsFirstFrame = bFirst;
}
inline void CNewParticleEffect::SetDynamicallyAllocated(bool bDynamic)
{
m_bAllocated = bDynamic;
}
inline void CNewParticleEffect::SetNeedsBBoxUpdate(bool bNeedsUpdate)
{
m_bNeedsBBoxUpdate = bNeedsUpdate;
}
inline void CNewParticleEffect::SetAutoUpdateBBox(bool bNeedsUpdate)
{
m_bAutoUpdateBBox = bNeedsUpdate;
}
inline void CNewParticleEffect::SetRemoveFlag(void)
{
m_bRemove = true;
}
inline bool CNewParticleEffect::GetRemoveFlag(void)
{
return m_bRemove;
}
inline bool CNewParticleEffect::GetFirstFrameFlag(void)
{
return m_bIsFirstFrame;
}
inline bool CNewParticleEffect::GetNeedsBBoxUpdate(void)
{
return m_bNeedsBBoxUpdate;
}
inline bool CNewParticleEffect::GetAutoUpdateBBox(void)
{
return m_bAutoUpdateBBox;
}
inline bool CNewParticleEffect::ShouldPerformCullCheck() const
{
return m_bShouldPerformCullCheck;
}
inline void CNewParticleEffect::MarkShouldPerformCullCheck(bool bEnable)
{
m_bShouldPerformCullCheck = bEnable;
}
inline CSmartPtr<CNewParticleEffect> CNewParticleEffect::Create(CBaseEntity* pOwner, const char* pParticleSystemName, const char* pDebugName)
{
CNewParticleEffect* pRet = new CNewParticleEffect(pOwner, pParticleSystemName);
pRet->m_pDebugName = pDebugName;
pRet->SetDynamicallyAllocated(true);
return pRet;
}
inline CSmartPtr<CNewParticleEffect> CNewParticleEffect::Create(CBaseEntity* pOwner, CParticleSystemDefinition* pDef, const char* pDebugName)
{
CNewParticleEffect* pRet = new CNewParticleEffect(pOwner, pDef);
pRet->m_pDebugName = pDebugName;
pRet->SetDynamicallyAllocated(true);
return pRet;
}
typedef CUtlReference<CNewParticleEffect> HPARTICLEFFECT;
#endif

View File

@ -0,0 +1,206 @@
#ifndef PARTICLES_SIMPLE_H
#define PARTICLES_SIMPLE_H
#ifdef _WIN32
#pragma once
#endif
#include "particlemgr.h"
#include "ParticleSphereRenderer.h"
#include "smartptr.h"
class CParticleEffect : public IParticleEffect
{
public:
DECLARE_CLASS_NOBASE(CParticleEffect);
friend class CRefCountAccessor;
void SetSortOrigin(const Vector& vSortOrigin);
PMaterialHandle GetPMaterial(const char* name);
Particle* AddParticle(unsigned int particleSize, PMaterialHandle material, const Vector& origin);
CParticleEffectBinding& GetBinding() { return m_ParticleEffect; }
const char* GetEffectName();
void AddFlags(int iFlags) { m_Flags |= iFlags; }
void RemoveFlags(int iFlags) { m_Flags &= ~iFlags; }
void SetDontRemove(bool bSet)
{
if (bSet)
AddFlags(FLAG_DONT_REMOVE);
else
RemoveFlags(FLAG_DONT_REMOVE);
}
public:
virtual void SetParticleCullRadius(float radius);
virtual void NotifyRemove(void);
virtual const Vector& GetSortOrigin();
virtual void NotifyDestroyParticle(Particle* pParticle);
virtual void Update(float flTimeDelta);
void SetDynamicallyAllocated(bool bDynamic = true);
virtual bool ShouldSimulate() const { return m_bSimulate; }
virtual void SetShouldSimulate(bool bSim) { m_bSimulate = bSim; }
int AllocateToolParticleEffectId();
int GetToolParticleEffectId() const;
protected:
CParticleEffect(const char* pDebugName);
virtual ~CParticleEffect();
int IsReleased();
enum
{
FLAG_ALLOCATED = (1 << 1),
FLAG_DONT_REMOVE = (1 << 2),
};
char const* m_pDebugName;
CParticleEffectBinding m_ParticleEffect;
Vector m_vSortOrigin;
int m_Flags;
bool m_bSimulate;
int m_nToolParticleEffectId;
private:
void AddRef();
void Release();
int m_RefCount;
CParticleEffect(const CParticleEffect&);
};
inline int CParticleEffect::GetToolParticleEffectId() const
{
return m_nToolParticleEffectId;
}
inline int CParticleEffect::AllocateToolParticleEffectId()
{
m_nToolParticleEffectId = ParticleMgr()->AllocateToolParticleEffectId();
return m_nToolParticleEffectId;
}
enum SimpleParticleFlag_t
{
SIMPLE_PARTICLE_FLAG_WINDBLOWN = 0x1,
SIMPLE_PARTICLE_FLAG_NO_VEL_DECAY = 0x2
};
class SimpleParticle : public Particle
{
public:
SimpleParticle() : m_iFlags(0) {}
Vector m_vecVelocity;
float m_flRoll;
float m_flDieTime;
float m_flLifetime;
unsigned char m_uchColor[3];
unsigned char m_uchStartAlpha;
unsigned char m_uchEndAlpha;
unsigned char m_uchStartSize;
unsigned char m_uchEndSize;
unsigned char m_iFlags;
float m_flRollDelta;
};
class CSimpleEmitter : public CParticleEffect
{
public:
DECLARE_CLASS(CSimpleEmitter, CParticleEffect);
static CSmartPtr<CSimpleEmitter> Create(const char* pDebugName);
virtual void SimulateParticles(CParticleSimulateIterator* pIterator);
virtual void RenderParticles(CParticleRenderIterator* pIterator);
void SetNearClip(float nearClipMin, float nearClipMax);
void SetDrawBeforeViewModel(bool state = true);
SimpleParticle* AddSimpleParticle(PMaterialHandle hMaterial, const Vector& vOrigin, float flDieTime = 3, unsigned char uchSize = 10);
void SetShouldDrawForSplitScreenUser(int nSlot);
protected:
CSimpleEmitter(const char* pDebugName = NULL);
virtual ~CSimpleEmitter();
virtual float UpdateAlpha(const SimpleParticle* pParticle);
virtual float UpdateScale(const SimpleParticle* pParticle);
virtual float UpdateRoll(SimpleParticle* pParticle, float timeDelta);
virtual void UpdateVelocity(SimpleParticle* pParticle, float timeDelta);
virtual Vector UpdateColor(const SimpleParticle* pParticle);
float m_flNearClipMin;
float m_flNearClipMax;
int m_nSplitScreenPlayerSlot;
private:
CSimpleEmitter(const CSimpleEmitter&);
};
class CEmberEffect : public CSimpleEmitter
{
public:
CEmberEffect(const char* pDebugName);
static CSmartPtr<CEmberEffect> Create(const char* pDebugName);
virtual void UpdateVelocity(SimpleParticle* pParticle, float timeDelta);
virtual Vector UpdateColor(const SimpleParticle* pParticle);
private:
CEmberEffect(const CEmberEffect&);
};
class CFireSmokeEffect : public CSimpleEmitter
{
public:
CFireSmokeEffect(const char* pDebugName);
static CSmartPtr<CFireSmokeEffect> Create(const char* pDebugName);
virtual void UpdateVelocity(SimpleParticle* pParticle, float timeDelta);
virtual float UpdateAlpha(const SimpleParticle* pParticle);
protected:
VPlane m_planeClip;
private:
CFireSmokeEffect(const CFireSmokeEffect&);
};
class CFireParticle : public CSimpleEmitter
{
public:
CFireParticle(const char* pDebugName);
static CSmartPtr<CFireParticle> Create(const char* pDebugName);
virtual Vector UpdateColor(const SimpleParticle* pParticle);
private:
CFireParticle(const CFireParticle&);
};
#endif

779
SpyCustom/pbwrap.hpp Normal file
View File

@ -0,0 +1,779 @@
#pragma once
#include <stdint.h>
#include <string>
#include <vector>
#include <tuple>
#define PBFIELD(number, type, name) \
pbfield<number, type> name() const { \
return std::move(pbfield<number, type>( fv_ )); \
}
#if defined(__GNUC__)
#include <cstring>
#include <memory>
#define __forceinline __attribute__((always_inline))
#define PBMSG_CTOR(class_name) \
class_name() : pbmsg() {} \
class_name(void* buf, size_t bytes) : pbmsg(buf, bytes) {} \
class_name(const std::string& buf) : pbmsg(buf) {}
#elif defined(_MSC_VER)
#define PBMSG_CTOR using pbmsg::pbmsg
#endif
namespace pbwrap
{
static constexpr int32_t k_invalid_id = -1;
enum e_field_type
{
TYPE_DOUBLE = 1,
TYPE_FLOAT = 2,
TYPE_INT64 = 3,
TYPE_UINT64 = 4,
TYPE_INT32 = 5,
TYPE_FIXED64 = 6,
TYPE_FIXED32 = 7,
TYPE_BOOL = 8,
TYPE_STRING = 9,
TYPE_GROUP = 10,
TYPE_MESSAGE = 11,
TYPE_BYTES = 12,
TYPE_UINT32 = 13,
TYPE_ENUM = 14,
TYPE_SFIXED32 = 15,
TYPE_SFIXED64 = 16,
TYPE_SINT32 = 17,
TYPE_SINT64 = 18,
MAX_FIELD_TYPE = 18,
};
enum e_wire_type
{
WIRETYPE_VARINT = 0,
WIRETYPE_FIXED64 = 1,
WIRETYPE_LENGTH_DELIMITED = 2,
WIRETYPE_START_GROUP = 3,
WIRETYPE_END_GROUP = 4,
WIRETYPE_FIXED32 = 5,
};
static constexpr e_wire_type k_wire_type_for_field_type[MAX_FIELD_TYPE + 1] = {
static_cast<e_wire_type>(k_invalid_id),
WIRETYPE_FIXED64,
WIRETYPE_FIXED32,
WIRETYPE_VARINT,
WIRETYPE_VARINT,
WIRETYPE_VARINT,
WIRETYPE_FIXED64,
WIRETYPE_FIXED32,
WIRETYPE_VARINT,
WIRETYPE_LENGTH_DELIMITED,
WIRETYPE_START_GROUP,
WIRETYPE_LENGTH_DELIMITED,
WIRETYPE_LENGTH_DELIMITED,
WIRETYPE_VARINT,
WIRETYPE_VARINT,
WIRETYPE_FIXED32,
WIRETYPE_FIXED64,
WIRETYPE_VARINT,
WIRETYPE_VARINT,
};
namespace utils
{
static constexpr int k_tag_type_bits = 3;
static constexpr uint32_t k_tag_type_mask = (1 << k_tag_type_bits) - 1;
static constexpr int k_max_varint_bytes = 10;
static constexpr int k_max_varint32_bytes = 5;
__forceinline auto make_tag(uint32_t field_number, uint32_t wire_type) -> uint32_t
{
return static_cast<uint32_t>((field_number << k_tag_type_bits) | wire_type);
}
static auto get_bytes_varint32(uint32_t value) -> std::string
{
uint8_t bytes[k_max_varint32_bytes];
int size = 0;
while (value > 0x7F)
{
bytes[size++] = (static_cast<uint8_t>(value) & 0x7F) | 0x80;
value >>= 7;
}
bytes[size++] = static_cast<uint8_t>(value) & 0x7F;
return std::string{ reinterpret_cast<const char*>(&bytes[0]), (size_t)size };
}
static auto get_bytes_varint64(uint64_t value) -> std::string
{
uint8_t bytes[k_max_varint_bytes];
int size = 0;
while (value > 0x7F)
{
bytes[size++] = (static_cast<uint8_t>(value) & 0x7F) | 0x80;
value >>= 7;
}
bytes[size++] = static_cast<uint8_t>(value) & 0x7F;
return std::string{ reinterpret_cast<const char*>(&bytes[0]), (size_t)size };
}
static auto read_varuint32(const void* data, size_t& bytes_read) -> uint32_t
{
auto ptr = reinterpret_cast<const uint8_t*>(data);
auto value = 0u;
auto bytes = 0u;
do
{
value |= static_cast<uint32_t>(*ptr & 0x7f) << (7 * bytes);
bytes++;
} while (*(ptr++) & 0x80 && bytes <= 5);
bytes_read = bytes;
return value;
}
static auto read_varuint64(const void* data, size_t& bytes_read) -> uint64_t
{
auto ptr = reinterpret_cast<const uint8_t*>(data);
auto value = 0ull;
auto bytes = 0u;
do
{
value |= static_cast<uint64_t>(*ptr & 0x7f) << (7 * bytes);
bytes++;
} while (*(ptr++) & 0x80 && bytes <= 10);
bytes_read = bytes;
return value;
}
static auto read_field(const void* data, size_t& bytes_read)
-> std::tuple<uint32_t, uint32_t, std::string, std::string>
{
uint32_t field = *reinterpret_cast<const uint16_t*>(data);
uint32_t wire_type = field & k_tag_type_mask;
if (field == 0xffff)
{
bytes_read = 0;
return std::make_tuple(k_invalid_id, k_invalid_id, "", "");
}
if (field & 0x80)
{
field = ((field & 0x7f) | ((field & 0xff00) >> 1)) >> k_tag_type_bits;
bytes_read = 2;
}
else
{
field = (field & 0xff) >> k_tag_type_bits;
bytes_read = 1;
}
std::string value_bytes, full_bytes;
size_t length, size_delimited;
switch (wire_type)
{
case WIRETYPE_VARINT:
read_varuint64((void*)((ptrdiff_t)data + bytes_read), length);
value_bytes = std::string{ reinterpret_cast<const char*>((void*)((ptrdiff_t)data + bytes_read)), length };
full_bytes = std::string{ reinterpret_cast<const char*>(data), bytes_read + length };
bytes_read += length;
break;
case WIRETYPE_FIXED64:
value_bytes = std::string{ reinterpret_cast<const char*>((void*)((ptrdiff_t)data + bytes_read)), 8 };
full_bytes = std::string{ reinterpret_cast<const char*>(data), bytes_read + 8 };
bytes_read += 8;
break;
case WIRETYPE_LENGTH_DELIMITED:
size_delimited = read_varuint32((void*)((ptrdiff_t)data + bytes_read), length);
value_bytes = std::string{
reinterpret_cast<const char*>((void*)((ptrdiff_t)data + bytes_read)), length + size_delimited
};
full_bytes = std::string{ reinterpret_cast<const char*>(data), bytes_read + length + size_delimited };
bytes_read += length + size_delimited;
break;
case WIRETYPE_START_GROUP:
throw std::runtime_error("WIRETYPE_START_GROUP not implemented");
break;
case WIRETYPE_END_GROUP:
throw std::runtime_error("WIRETYPE_END_GROUP not implemented");
break;
case WIRETYPE_FIXED32:
value_bytes = std::string{ reinterpret_cast<const char*>((void*)((ptrdiff_t)data + bytes_read)), 4 };
full_bytes = std::string{ reinterpret_cast<const char*>(data), bytes_read + 4 };
bytes_read += 4;
break;
default:
throw std::runtime_error("Unknown wire type");
break;
}
return std::make_tuple(field, wire_type, std::move(value_bytes), std::move(full_bytes));
}
template <typename T>
auto get_field_bytes(uint32_t field, uint32_t wire_type, T value)
-> std::pair<std::string, std::string>
{
const auto tag = get_bytes_varint32(make_tag(field, wire_type));
std::string bytes{};
switch (wire_type)
{
case WIRETYPE_VARINT:
bytes += get_bytes_varint64(static_cast<uint64_t>(value));
break;
case WIRETYPE_FIXED32:
bytes += std::string{ reinterpret_cast<const char*>(&value), 4 };
break;
case WIRETYPE_FIXED64:
bytes += std::string{ reinterpret_cast<const char*>(&value), 8 };
break;
}
return { bytes, tag + bytes };
}
template <>
inline auto get_field_bytes<std::string>(uint32_t field, uint32_t wire_type, std::string value)
-> std::pair<std::string, std::string>
{
const auto tag = get_bytes_varint32(make_tag(field, wire_type));
std::string bytes{};
bytes += get_bytes_varint32(value.size());
bytes += value;
return { bytes, tag + bytes };
}
template <>
inline auto get_field_bytes<const char*>(uint32_t field, uint32_t wire_type, const char* value)
-> std::pair<std::string, std::string>
{
const auto tag = get_bytes_varint32(make_tag(field, wire_type));
std::string bytes{};
bytes += get_bytes_varint32(strlen(value));
bytes += value;
return { bytes, tag + bytes };
}
}
namespace types
{
struct Int32
{
static constexpr e_field_type field_type = TYPE_INT32;
using type = int32_t;
static __forceinline auto get(const std::string& value) -> int32_t
{
size_t bytes_read;
return utils::read_varuint32(value.data(), bytes_read);
}
};
struct Uint32
{
static constexpr e_field_type field_type = TYPE_UINT32;
using type = uint32_t;
static __forceinline auto get(const std::string& value) -> uint32_t
{
size_t bytes_read;
return utils::read_varuint32(value.data(), bytes_read);
}
};
struct Int64
{
static constexpr e_field_type field_type = TYPE_INT64;
using type = int64_t;
static __forceinline auto get(const std::string& value) -> int64_t
{
size_t bytes_read;
return utils::read_varuint64(value.data(), bytes_read);
}
};
struct Uint64
{
static constexpr e_field_type field_type = TYPE_UINT64;
using type = uint64_t;
static __forceinline auto get(const std::string& value) -> uint64_t
{
size_t bytes_read;
return utils::read_varuint64(value.data(), bytes_read);
}
};
struct Float
{
static constexpr e_field_type field_type = TYPE_FLOAT;
using type = float;
static __forceinline auto get(const std::string& value) -> float
{
return *reinterpret_cast<const float*>(value.data());
}
};
struct Double
{
static constexpr e_field_type field_type = TYPE_DOUBLE;
using type = double;
static __forceinline auto get(const std::string& value) -> double
{
return *reinterpret_cast<const double*>(value.data());
}
};
struct Fixed32
{
static constexpr e_field_type field_type = TYPE_FIXED32;
using type = int32_t;
static __forceinline auto get(const std::string& value) -> int32_t
{
return *reinterpret_cast<const int32_t*>(value.data());
}
};
struct Fixed64
{
static constexpr e_field_type field_type = TYPE_FIXED64;
using type = int64_t;
static __forceinline auto get(const std::string& value) -> int64_t
{
return *reinterpret_cast<const int64_t*>(value.data());
}
};
struct Bool
{
static constexpr e_field_type field_type = TYPE_BOOL;
using type = bool;
static __forceinline auto get(const std::string& value) -> bool
{
size_t bytes_read;
return !!utils::read_varuint32(value.data(), bytes_read);
}
};
struct String
{
static constexpr e_field_type field_type = TYPE_STRING;
using type = std::string;
static __forceinline auto get(const std::string& value) -> std::string
{
size_t bytes_read;
const auto length = utils::read_varuint32(value.data(), bytes_read);
auto result = std::string{ value.data() + bytes_read, length };
return std::move(result);
}
};
struct Group : String
{
static constexpr e_field_type field_type = TYPE_GROUP;
};
struct Message : String
{
static constexpr e_field_type field_type = TYPE_MESSAGE;
};
struct Bytes : String
{
static constexpr e_field_type field_type = TYPE_BYTES;
};
struct Enum : Int32
{
static constexpr e_field_type field_type = TYPE_ENUM;
};
struct Sfixed32 : Fixed32
{
static constexpr e_field_type field_type = TYPE_SFIXED32;
};
struct Sfixed64 : Fixed64
{
static constexpr e_field_type field_type = TYPE_SFIXED64;
};
struct Sint32
{
static constexpr e_field_type field_type = TYPE_SINT32;
using type = int32_t;
};
struct Sint64
{
static constexpr e_field_type field_type = TYPE_SINT64;
using type = int64_t;
};
}
namespace base
{
struct field_vector
{
using Entry = std::pair<std::string, std::string>;
using Field = std::vector<Entry>;
using Fields = std::vector<Field>;
const std::shared_ptr<Fields> fields;
const size_t max_size;
explicit field_vector(const size_t max_size) : fields{ std::make_shared<Fields>() }, max_size{ max_size + 1 }
{
fields->resize(this->max_size);
}
auto clear(const uint32_t field) const -> void
{
if (field >= max_size)
throw std::runtime_error("field range error");
auto& fld = fields->at(field);
if (!fld.empty())
fld.clear();
}
auto has(const uint32_t field, const size_t index = 0) const -> bool
{
if (field >= max_size)
throw std::runtime_error("field range error");
auto& fld = fields->at(field);
return fld.size() > index;
}
auto count(const uint32_t field) const -> size_t
{
if (field >= max_size)
throw std::runtime_error("field range error");
auto& fld = fields->at(field);
return fld.size();
}
auto add(const uint32_t field, const Entry& entry) const -> void
{
if (field >= max_size)
throw std::runtime_error("field range error");
fields->at(field).emplace_back(entry);
}
auto set(const uint32_t field, const Entry& entry, const size_t index = 0) const -> void
{
if (field >= max_size)
throw std::runtime_error("field range error");
auto& fld = fields->at(field);
if (index == 0 && fld.empty())
{
fld.emplace_back(entry);
}
else
{
if (index >= fld.size())
throw std::runtime_error("field range error");
fld.at(index) = entry;
}
}
auto get(const uint32_t field, const size_t index = 0) const -> std::string
{
if (field >= max_size)
throw std::runtime_error("field range error");
const auto& fld = fields->at(field);
if (index >= fld.size())
throw std::runtime_error("field range error");
return fld.at(index).first;
}
auto get_all(const uint32_t field) const -> std::vector<std::string>
{
if (field >= max_size)
throw std::runtime_error("field range error");
const auto& fld = fields->at(field);
std::vector<std::string> ret;
for (const auto& v : fld)
ret.emplace_back(v.first);
return std::move(ret);
}
};
template <int Field, typename Type>
struct header
{
static constexpr uint32_t field = Field;
static constexpr e_field_type type = Type::field_type;
static constexpr e_wire_type wire_type = k_wire_type_for_field_type[type];
};
struct msg
{
static constexpr e_field_type field_type = TYPE_STRING;
using type = std::string;
virtual ~msg() = default;
msg() = delete;
explicit msg(const size_t max_size) : fv_{ field_vector(max_size) }
{
}
auto serialize() const -> std::string
{
std::string result;
for (const auto& f0 : *fv_.fields)
for (const auto& f1 : f0)
result.append(f1.second);
return std::move(result);
}
auto parse(const uint8_t* buf, size_t bytes) -> void
{
if (buf == nullptr)
return;
size_t pos = 0, bytes_read;
uint32_t field, wire_type;
std::string field_value_bytes, field_full_bytes;
while (pos < bytes)
{
std::tie(field, wire_type, field_value_bytes, field_full_bytes) = utils::read_field(buf + pos, bytes_read);
if (bytes_read == 0)
break;
if (field >= fv_.max_size)
throw std::runtime_error("field range error");
fv_.fields->at(field).emplace_back(field_value_bytes, field_full_bytes);
pos += bytes_read;
}
}
protected:
const field_vector fv_;
};
template <int Field, typename Type>
struct field
{
virtual ~field() = default;
explicit field(const field_vector& fv) : fv_{ fv }
{
}
auto clear() const -> void
{
fv_.clear(hdr.field);
}
auto has(size_t index = 0) const -> bool
{
return fv_.has(hdr.field, index);
}
auto count() const -> size_t
{
return fv_.count(hdr.field);
}
protected:
static constexpr header<Field, Type> hdr{};
const field_vector fv_;
};
}
template <int Field, typename Type, typename S = void>
struct pbfield;
template <int Field, typename Type>
struct pbfield<Field, Type, typename std::enable_if<!std::is_base_of<base::msg, Type>::value>::type
> : base::field<Field, Type>
{
virtual ~pbfield() = default;
explicit pbfield(const base::field_vector& fv) : base::field<Field, Type>{ fv }
{
}
using type = typename Type::type;
auto add(type&& value) const -> void
{
const auto pair = utils::get_field_bytes(hdr.field, hdr.wire_type, value);
fv_.add(hdr.field, pair);
}
auto set(type&& value, size_t index = 0) const -> void
{
const auto pair = utils::get_field_bytes(hdr.field, hdr.wire_type, value);
fv_.set(hdr.field, pair, index);
}
auto set(const type& value, size_t index = 0) const -> void
{
const auto pair = utils::get_field_bytes(hdr.field, hdr.wire_type, value);
fv_.set(hdr.field, pair, index);
}
auto set(std::vector<type>&& values) const -> void
{
fv_.clear(hdr.field);
for (auto& v : values)
{
const auto pair = utils::get_field_bytes(hdr.field, hdr.wire_type, v);
fv_.add(hdr.field, pair);
}
}
auto set(std::vector<type>& values) const -> void
{
fv_.clear(hdr.field);
for (auto& v : values)
{
const auto pair = utils::get_field_bytes(hdr.field, hdr.wire_type, v);
fv_.add(hdr.field, pair);
}
}
auto get_all() const -> std::vector<type>
{
const auto values = fv_.get_all(hdr.field);
std::vector<type> ret;
for (const auto& v : values)
ret.emplace_back(Type::get(v));
return std::move(ret);
}
auto get(size_t index = 0) const -> type
{
const auto value = fv_.get(hdr.field, index);
return Type::get(value);
}
private:
using base::field<Field, Type>::hdr;
using base::field<Field, Type>::fv_;
};
template <int Field, typename Type>
struct pbfield<Field, Type, typename std::enable_if<std::is_base_of<base::msg, Type>::value>::type
> : base::field<Field, Type>
{
virtual ~pbfield() = default;
explicit pbfield(const base::field_vector& fv) : base::field<Field, Type>{ fv }
{
}
using type = typename Type::type;
auto add(const Type& value) const -> void
{
const auto v = value.serialize();
const auto pair = utils::get_field_bytes(hdr.field, hdr.wire_type, v);
fv_.add(hdr.field, pair);
}
auto set(const Type& value, size_t index = 0) const -> void
{
const auto v = value.serialize();
const auto pair = utils::get_field_bytes(hdr.field, hdr.wire_type, v);
fv_.set(hdr.field, pair, index);
}
auto get_all() const -> std::vector<Type>
{
const auto values = fv_.get_all(hdr.field);
std::vector<Type> ret;
for (const auto& v : values)
{
const auto s = types::String::get(v);
ret.emplace_back(s);
}
return std::move(ret);
}
auto get(size_t index = 0) const -> Type
{
const auto value = fv_.get(hdr.field, index);
const auto s = types::String::get(value);
return std::move(Type(s));
}
private:
using base::field<Field, Type>::hdr;
using base::field<Field, Type>::fv_;
};
template <size_t MsgSize>
struct pbmsg : base::msg
{
virtual ~pbmsg() = default;
explicit pbmsg() : msg(MsgSize)
{
}
explicit pbmsg(void* buf, size_t bytes) : msg(MsgSize)
{
parse(reinterpret_cast<const uint8_t*>(buf), bytes);
}
explicit pbmsg(const std::string& buf) : msg(MsgSize)
{
parse(reinterpret_cast<const uint8_t*>(buf.data()), buf.size());
}
};
}

1280
SpyCustom/platform.h Normal file

File diff suppressed because it is too large Load Diff

113
SpyCustom/playernet_vars.h Normal file
View File

@ -0,0 +1,113 @@
#ifndef PLAYERNET_VARS_H
#define PLAYERNET_VARS_H
#ifdef _WIN32
#pragma once
#endif
#include "shared_classnames.h"
#include "networkvar.h"
#include "datamap.h"
#define NUM_AUDIO_LOCAL_SOUNDS 8
struct fogparams_t
{
DECLARE_CLASS_NOBASE(fogparams_t);
DECLARE_EMBEDDED_NETWORKVAR();
#ifndef CLIENT_DLL
DECLARE_SIMPLE_DATADESC();
#endif
bool operator !=(const fogparams_t& other) const;
CNetworkVector(dirPrimary);
CNetworkColor32(colorPrimary);
CNetworkColor32(colorSecondary);
CNetworkColor32(colorPrimaryLerpTo);
CNetworkColor32(colorSecondaryLerpTo);
CNetworkVar(float, start);
CNetworkVar(float, end);
CNetworkVar(float, farz);
CNetworkVar(float, maxdensity);
CNetworkVar(float, startLerpTo);
CNetworkVar(float, endLerpTo);
CNetworkVar(float, lerptime);
CNetworkVar(float, duration);
CNetworkVar(bool, enable);
CNetworkVar(bool, blend);
};
#ifdef CLIENT_DLL
#define CFogController C_FogController
#endif
class CFogController;
struct fogplayerparams_t
{
DECLARE_CLASS_NOBASE(fogplayerparams_t);
DECLARE_EMBEDDED_NETWORKVAR();
#ifndef CLIENT_DLL
DECLARE_SIMPLE_DATADESC();
#endif
CNetworkHandle(CFogController, m_hCtrl);
float m_flTransitionTime;
color32 m_OldColor;
float m_flOldStart;
float m_flOldEnd;
color32 m_NewColor;
float m_flNewStart;
float m_flNewEnd;
fogplayerparams_t()
{
m_hCtrl.Set(NULL);
m_flTransitionTime = -1.0f;
m_OldColor.r = m_OldColor.g = m_OldColor.b = m_OldColor.a = 0;
m_flOldStart = 0.0f;
m_flOldEnd = 0.0f;
m_NewColor.r = m_NewColor.g = m_NewColor.b = m_NewColor.a = 0;
m_flNewStart = 0.0f;
m_flNewEnd = 0.0f;
}
};
struct sky3dparams_t
{
DECLARE_CLASS_NOBASE(sky3dparams_t);
DECLARE_EMBEDDED_NETWORKVAR();
#ifndef CLIENT_DLL
DECLARE_SIMPLE_DATADESC();
#endif
CNetworkVar(int, scale);
CNetworkVector(origin);
CNetworkVar(int, area);
CNetworkVarEmbedded(fogparams_t, fog);
};
struct audioparams_t
{
DECLARE_CLASS_NOBASE(audioparams_t);
DECLARE_EMBEDDED_NETWORKVAR();
#ifndef CLIENT_DLL
DECLARE_SIMPLE_DATADESC();
#endif
CNetworkArray(Vector, localSound, NUM_AUDIO_LOCAL_SOUNDS)
CNetworkVar(int, soundscapeIndex);
CNetworkVar(int, localBits);
CNetworkHandle(CBaseEntity, ent);
};
#endif

View File

@ -0,0 +1,22 @@
#ifndef PRECIPITATION_SHARED_H
#define PRECIPITATION_SHARED_H
#ifdef _WIN32
#pragma once
#endif
enum PrecipitationType_t
{
PRECIPITATION_TYPE_RAIN = 0,
PRECIPITATION_TYPE_SNOW,
PRECIPITATION_TYPE_ASH,
PRECIPITATION_TYPE_SNOWFALL,
PRECIPITATION_TYPE_PARTICLERAIN,
PRECIPITATION_TYPE_PARTICLEASH,
PRECIPITATION_TYPE_PARTICLERAINSTORM,
PRECIPITATION_TYPE_PARTICLESNOW,
NUM_PRECIPITATION_TYPES
};
#endif

View File

@ -0,0 +1,185 @@
#ifndef PREDICTABLE_ENTITY_H
#define PREDICTABLE_ENTITY_H
#ifdef _WIN32
#pragma once
#endif
#include "platform.h"
#include "predictioncopy.h"
#include "shared_classnames.h"
#ifndef NO_ENTITY_PREDICTION
#define UsePrediction() 1
#else
#define UsePrediction() 0
#endif
#if defined( CLIENT_DLL )
#include "iclassmap.h"
#include "recvproxy.h"
class SendTable;
#else
#include "sendproxy.h"
#endif
#if defined( CLIENT_DLL )
#define DECLARE_NETWORKCLASS() \
DECLARE_CLIENTCLASS()
#define DECLARE_NETWORKCLASS_NOBASE() \
DECLARE_CLIENTCLASS_NOBASE()
#else
#define DECLARE_NETWORKCLASS() \
DECLARE_SERVERCLASS()
#define DECLARE_NETWORKCLASS_NOBASE() \
DECLARE_SERVERCLASS_NOBASE()
#endif
#if defined( CLIENT_DLL )
#ifndef NO_ENTITY_PREDICTION
#define DECLARE_PREDICTABLE() \
public: \
static typedescription_t m_PredDesc[]; \
static datamap_t m_PredMap; \
virtual datamap_t *GetPredDescMap( void ); \
template <typename T> friend datamap_t *PredMapInit(T *)
#else
#define DECLARE_PREDICTABLE() template <typename T> friend datamap_t *PredMapInit(T *)
#endif
#ifndef NO_ENTITY_PREDICTION
#define BEGIN_PREDICTION_DATA( className ) \
datamap_t className::m_PredMap = { 0, 0, #className, &BaseClass::m_PredMap }; \
datamap_t *className::GetPredDescMap( void ) { return &m_PredMap; } \
BEGIN_PREDICTION_DATA_GUTS( className )
#define BEGIN_PREDICTION_DATA_NO_BASE( className ) \
datamap_t className::m_PredMap = { 0, 0, #className, NULL }; \
datamap_t *className::GetPredDescMap( void ) { return &m_PredMap; } \
BEGIN_PREDICTION_DATA_GUTS( className )
#define BEGIN_PREDICTION_DATA_GUTS( className ) \
template <typename T> datamap_t *PredMapInit(T *); \
template <> datamap_t *PredMapInit<className>( className * ); \
namespace className##_PredDataDescInit \
{ \
datamap_t *g_PredMapHolder = PredMapInit( (className *)NULL ); \
} \
\
template <> datamap_t *PredMapInit<className>( className * ) \
{ \
typedef className classNameTypedef; \
static typedescription_t predDesc[] = \
{ \
{ FIELD_VOID,0, {0,0},0,0,0,0,0,0},
#define END_PREDICTION_DATA() \
}; \
\
if ( sizeof( predDesc ) > sizeof( predDesc[0] ) ) \
{ \
classNameTypedef::m_PredMap.dataNumFields = ARRAYSIZE( predDesc ) - 1; \
classNameTypedef::m_PredMap.dataDesc = &predDesc[1]; \
} \
else \
{ \
classNameTypedef::m_PredMap.dataNumFields = 1; \
classNameTypedef::m_PredMap.dataDesc = predDesc; \
} \
return &classNameTypedef::m_PredMap; \
}
#else
#define BEGIN_PREDICTION_DATA( className ) \
template <> inline datamap_t *PredMapInit<className>( className * ) \
{ \
if ( 0 ) \
{ \
typedef className classNameTypedef; \
typedescription_t predDesc[] = \
{ \
{ FIELD_VOID,0, {0,0},0,0,0,0,0,0},
#define BEGIN_PREDICTION_DATA_NO_BASE( className ) BEGIN_PREDICTION_DATA( className )
#define END_PREDICTION_DATA() \
}; \
predDesc[0].flags = 0; \
} \
}
#endif
#else
#define DECLARE_PREDICTABLE()
#define BEGIN_PREDICTION_DATA( className )
#define END_PREDICTION_DATA()
#endif
#if defined( CLIENT_DLL )
#define LINK_ENTITY_TO_CLASS( localName, className ) \
static C_BaseEntity *C##className##Factory( void ) \
{ \
return static_cast< C_BaseEntity * >( new className ); \
}; \
class C##localName##Foo \
{ \
public: \
C##localName##Foo( void ) \
{ \
GetClassMap().Add( #localName, #className, sizeof( className ), \
&C##className##Factory ); \
} \
}; \
static C##localName##Foo g_C##localName##Foo;
#define BEGIN_NETWORK_TABLE( className, tableName ) BEGIN_RECV_TABLE( className, tableName )
#define BEGIN_NETWORK_TABLE_NOBASE( className, tableName ) BEGIN_RECV_TABLE_NOBASE( className, tableName )
#define END_NETWORK_TABLE END_RECV_TABLE
#define IMPLEMENT_NETWORKCLASS_ALIASED(className, dataTable) \
IMPLEMENT_CLIENTCLASS( C_##className, dataTable, C##className )
#define IMPLEMENT_NETWORKCLASS(className, dataTable) \
IMPLEMENT_CLIENTCLASS(className, dataTable, className)
#define IMPLEMENT_NETWORKCLASS_DT(className, dataTable) \
IMPLEMENT_CLIENTCLASS_DT(className, dataTable, className)
#else
#define BEGIN_NETWORK_TABLE( className, tableName ) BEGIN_SEND_TABLE( className, tableName )
#define BEGIN_NETWORK_TABLE_NOBASE( className, tableName ) BEGIN_SEND_TABLE_NOBASE( className, tableName )
#define END_NETWORK_TABLE END_SEND_TABLE
#define IMPLEMENT_NETWORKCLASS_ALIASED(className, dataTable) \
IMPLEMENT_SERVERCLASS( C##className, dataTable )
#define IMPLEMENT_NETWORKCLASS(className, dataTable) \
IMPLEMENT_SERVERCLASS(className, dataTable)
#define IMPLEMENT_NETWORKCLASS_DT(className, dataTable) \
IMPLEMENT_SERVERCLASS_ST(className, dataTable)
#endif
abstract_class IPredictableList
{
public:
virtual CBaseEntity* GetPredictable(int slot) = 0;
virtual int GetPredictableCount(void) = 0;
};
extern IPredictableList* predictables;
#endif

53
SpyCustom/predictableid.h Normal file
View File

@ -0,0 +1,53 @@
#ifndef PREDICTABLEID_H
#define PREDICTABLEID_H
#ifdef _WIN32
#pragma once
#endif
#if !defined( NO_ENTITY_PREDICTION )
class CPredictableId
{
public:
CPredictableId(void);
static void ResetInstanceCounters(void);
bool IsActive(void) const;
void Init(int player, int command, const char* classname, const char* module, int line);
int GetPlayer(void) const;
int GetHash(void) const;
int GetInstanceNumber(void) const;
int GetCommandNumber(void) const;
void SetAcknowledged(bool ack);
bool GetAcknowledged(void) const;
int GetRaw(void) const;
void SetRaw(int raw);
char const* Describe(void) const;
bool operator ==(const CPredictableId& other) const;
bool operator !=(const CPredictableId& other) const;
private:
void SetCommandNumber(int commandNumber);
void SetPlayer(int playerIndex);
void SetInstanceNumber(int counter);
struct bitfields
{
unsigned int ack : 1;
unsigned int player : 5;
unsigned int command : 10;
unsigned int hash : 12;
unsigned int instance : 4;
} m_PredictableID;
};
FORCEINLINE void NetworkVarConstruct(CPredictableId& x) {}
#endif
#endif

278
SpyCustom/predictioncopy.h Normal file
View File

@ -0,0 +1,278 @@
#ifndef PREDICTIONCOPY_H
#define PREDICTIONCOPY_H
#ifdef _WIN32
#pragma once
#endif
#include <memory.h>
#include "datamap.h"
#include "ehandle.h"
#include "utlstring.h"
#if defined( CLIENT_DLL )
class C_BaseEntity;
typedef CHandle<C_BaseEntity> EHANDLE;
#if defined( _DEBUG )
class IGameSystem;
IGameSystem* GetPredictionCopyTester(void);
#endif
#else
class CBaseEntity;
typedef CHandle<CBaseEntity> EHANDLE;
#endif
enum
{
PC_EVERYTHING = 0,
PC_NON_NETWORKED_ONLY,
PC_NETWORKED_ONLY,
};
#define PC_DATA_PACKED true
#define PC_DATA_NORMAL false
typedef void (*FN_FIELD_COMPARE)(const char* classname, const char* fieldname, const char* fieldtype,
bool networked, bool noterrorchecked, bool differs, bool withintolerance, const char* value);
class CPredictionCopy
{
public:
typedef enum
{
DIFFERS = 0,
IDENTICAL,
WITHINTOLERANCE,
} difftype_t;
CPredictionCopy(int type, void* dest, bool dest_packed, void const* src, bool src_packed,
bool counterrors = false, bool reporterrors = false, bool performcopy = true,
bool describefields = false, FN_FIELD_COMPARE func = NULL);
void CopyShort(difftype_t dt, short* outvalue, const short* invalue, int count);
void CopyInt(difftype_t dt, int* outvalue, const int* invalue, int count);
void CopyBool(difftype_t dt, bool* outvalue, const bool* invalue, int count);
void CopyFloat(difftype_t dt, float* outvalue, const float* invalue, int count);
void CopyString(difftype_t dt, char* outstring, const char* instring);
void CopyVector(difftype_t dt, Vector& outValue, const Vector& inValue);
void CopyVector(difftype_t dt, Vector* outValue, const Vector* inValue, int count);
void CopyQuaternion(difftype_t dt, Quaternion& outValue, const Quaternion& inValue);
void CopyQuaternion(difftype_t dt, Quaternion* outValue, const Quaternion* inValue, int count);
void CopyEHandle(difftype_t dt, EHANDLE* outvalue, EHANDLE const* invalue, int count);
void FORCEINLINE CopyData(difftype_t dt, int size, char* outdata, const char* indata)
{
if (!m_bPerformCopy)
return;
if (dt == IDENTICAL)
return;
memcpy(outdata, indata, size);
}
int TransferData(const char* operation, int entindex, datamap_t* dmap);
private:
void TransferData_R(int chaincount, datamap_t* dmap);
void DetermineWatchField(const char* operation, int entindex, datamap_t* dmap);
void DumpWatchField(typedescription_t* field);
void WatchMsg(PRINTF_FORMAT_STRING const char* fmt, ...);
difftype_t CompareShort(short* outvalue, const short* invalue, int count);
difftype_t CompareInt(int* outvalue, const int* invalue, int count);
difftype_t CompareBool(bool* outvalue, const bool* invalue, int count);
difftype_t CompareFloat(float* outvalue, const float* invalue, int count);
difftype_t CompareData(int size, char* outdata, const char* indata);
difftype_t CompareString(char* outstring, const char* instring);
difftype_t CompareVector(Vector& outValue, const Vector& inValue);
difftype_t CompareVector(Vector* outValue, const Vector* inValue, int count);
difftype_t CompareQuaternion(Quaternion& outValue, const Quaternion& inValue);
difftype_t CompareQuaternion(Quaternion* outValue, const Quaternion* inValue, int count);
difftype_t CompareEHandle(EHANDLE* outvalue, EHANDLE const* invalue, int count);
void DescribeShort(difftype_t dt, short* outvalue, const short* invalue, int count);
void DescribeInt(difftype_t dt, int* outvalue, const int* invalue, int count);
void DescribeBool(difftype_t dt, bool* outvalue, const bool* invalue, int count);
void DescribeFloat(difftype_t dt, float* outvalue, const float* invalue, int count);
void DescribeData(difftype_t dt, int size, char* outdata, const char* indata);
void DescribeString(difftype_t dt, char* outstring, const char* instring);
void DescribeVector(difftype_t dt, Vector& outValue, const Vector& inValue);
void DescribeVector(difftype_t dt, Vector* outValue, const Vector* inValue, int count);
void DescribeQuaternion(difftype_t dt, Quaternion& outValue, const Quaternion& inValue);
void DescribeQuaternion(difftype_t dt, Quaternion* outValue, const Quaternion* inValue, int count);
void DescribeEHandle(difftype_t dt, EHANDLE* outvalue, EHANDLE const* invalue, int count);
void WatchShort(difftype_t dt, short* outvalue, const short* invalue, int count);
void WatchInt(difftype_t dt, int* outvalue, const int* invalue, int count);
void WatchBool(difftype_t dt, bool* outvalue, const bool* invalue, int count);
void WatchFloat(difftype_t dt, float* outvalue, const float* invalue, int count);
void WatchData(difftype_t dt, int size, char* outdata, const char* indata);
void WatchString(difftype_t dt, char* outstring, const char* instring);
void WatchVector(difftype_t dt, Vector& outValue, const Vector& inValue);
void WatchVector(difftype_t dt, Vector* outValue, const Vector* inValue, int count);
void WatchQuaternion(difftype_t dt, Quaternion& outValue, const Quaternion& inValue);
void WatchQuaternion(difftype_t dt, Quaternion* outValue, const Quaternion* inValue, int count);
void WatchEHandle(difftype_t dt, EHANDLE* outvalue, EHANDLE const* invalue, int count);
void ReportFieldsDiffer(PRINTF_FORMAT_STRING const char* fmt, ...);
void DescribeFields(difftype_t dt, PRINTF_FORMAT_STRING const char* fmt, ...);
bool CanCheck(void);
void CopyFields(int chaincount, datamap_t* pMap, typedescription_t* pFields, int fieldCount);
private:
int m_nType;
void* m_pDest;
void const* m_pSrc;
int m_nDestOffsetIndex;
int m_nSrcOffsetIndex;
bool m_bErrorCheck;
bool m_bReportErrors;
bool m_bDescribeFields;
typedescription_t* m_pCurrentField;
char const* m_pCurrentClassName;
datamap_t* m_pCurrentMap;
bool m_bShouldReport;
bool m_bShouldDescribe;
int m_nErrorCount;
bool m_bPerformCopy;
FN_FIELD_COMPARE m_FieldCompareFunc;
typedescription_t* m_pWatchField;
char const* m_pOperation;
};
typedef void (*FN_FIELD_DESCRIPTION)(const char* classname, const char* fieldname, const char* fieldtype,
bool networked, const char* value);
class CPredictionDescribeData
{
public:
CPredictionDescribeData(void const* src, bool src_packed, FN_FIELD_DESCRIPTION func = 0);
void DescribeShort(const short* invalue, int count);
void DescribeInt(const int* invalue, int count);
void DescribeBool(const bool* invalue, int count);
void DescribeFloat(const float* invalue, int count);
void DescribeData(int size, const char* indata);
void DescribeString(const char* instring);
void DescribeVector(const Vector& inValue);
void DescribeVector(const Vector* inValue, int count);
void DescribeQuaternion(const Quaternion& inValue);
void DescribeQuaternion(const Quaternion* inValue, int count);
void DescribeEHandle(EHANDLE const* invalue, int count);
void DumpDescription(datamap_t* pMap);
private:
void DescribeFields_R(int chain_count, datamap_t* pMap, typedescription_t* pFields, int fieldCount);
void const* m_pSrc;
int m_nSrcOffsetIndex;
void Describe(PRINTF_FORMAT_STRING const char* fmt, ...);
typedescription_t* m_pCurrentField;
char const* m_pCurrentClassName;
datamap_t* m_pCurrentMap;
bool m_bShouldReport;
FN_FIELD_DESCRIPTION m_FieldDescFunc;
};
#if defined( CLIENT_DLL )
class CValueChangeTracker
{
public:
CValueChangeTracker();
void Reset();
void StartTrack(char const* pchContext);
void EndTrack();
bool IsActive() const;
void SetupTracking(C_BaseEntity* ent, char const* pchFieldName);
void ClearTracking();
void Spew();
C_BaseEntity* GetEntity();
private:
enum
{
eChangeTrackerBufSize = 128,
};
void GetValue(char* buf, size_t bufsize);
bool m_bActive : 1;
bool m_bTracking : 1;
EHANDLE m_hEntityToTrack;
CUtlVector< typedescription_t* > m_FieldStack;
CUtlString m_strFieldName;
CUtlString m_strContext;
char m_OrigValueBuf[eChangeTrackerBufSize];
CUtlVector< CUtlString > m_History;
};
extern CValueChangeTracker* g_pChangeTracker;
class CValueChangeTrackerScope
{
public:
CValueChangeTrackerScope(char const* pchContext)
{
m_bCallEndTrack = true;
g_pChangeTracker->StartTrack(pchContext);
}
CValueChangeTrackerScope(C_BaseEntity* pEntity, char const* pchContext)
{
m_bCallEndTrack = g_pChangeTracker->GetEntity() == pEntity;
if (m_bCallEndTrack)
{
g_pChangeTracker->StartTrack(pchContext);
}
}
~CValueChangeTrackerScope()
{
if (m_bCallEndTrack)
{
g_pChangeTracker->EndTrack();
}
}
private:
bool m_bCallEndTrack;
};
#if defined( _DEBUG )
#define PREDICTION_TRACKVALUECHANGESCOPE( context ) CValueChangeTrackerScope scope( context );
#define PREDICTION_TRACKVALUECHANGESCOPE_ENTITY( entity, context ) CValueChangeTrackerScope scope( entity, context );
#define PREDICTION_STARTTRACKVALUE( context ) g_pChangeTracker->StartTrack( context );
#define PREDICTION_ENDTRACKVALUE() g_pChangeTracker->EndTrack();
#define PREDICTION_SPEWVALUECHANGES() g_pChangeTracker->Spew();
#else
#define PREDICTION_TRACKVALUECHANGESCOPE( context )
#define PREDICTION_TRACKVALUECHANGESCOPE_ENTITY( entity, context )
#define PREDICTION_STARTTRACKVALUE( context )
#define PREDICTION_ENDTRACKVALUE()
#define PREDICTION_SPEWVALUECHANGES()
#endif
#endif
#endif

262
SpyCustom/protobuffs.cpp Normal file
View File

@ -0,0 +1,262 @@
#include "Protobuffs.hpp"
#include "Interfaces.hpp"
#include "inventory_changer.h"
extern Protobuffs ProtoFeatures;
#define CAST(cast, address, add) reinterpret_cast<cast>((uint32_t)address + (uint32_t)add)
void Protobuffs::WritePacket(std::string packet, void* thisPtr, void* oldEBP, void* pubDest, uint32_t cubDest, uint32_t* pcubMsgSize)
{
if ((uint32_t)packet.size() <= cubDest - 8)
{
memcpy((void*)((DWORD)pubDest + 8), (void*)packet.data(), packet.size());
*pcubMsgSize = packet.size() + 8;
}
else if (iff.g_pMemAlloc)
{
auto memPtr = *CAST(void**, thisPtr, 0x18);
auto memPtrSize = *CAST(uint32_t*, thisPtr, 0x1C);
auto newSize = (memPtrSize - cubDest) + packet.size() + 8;
auto memory = iff.g_pMemAlloc->Realloc(memPtr, newSize + 4);
*CAST(void**, thisPtr, 0x18) = memory;
*CAST(uint32_t*, thisPtr, 0x1C) = newSize;
*CAST(void**, oldEBP, -0x14) = memory;
memcpy(CAST(void*, memory, 0x1C), (void*)packet.data(), packet.size());
*pcubMsgSize = packet.size() + 8;
}
}
static bool onceChanger = false;
void Protobuffs::ReceiveMessage(void* thisPtr, void* oldEBP, uint32_t messageType, void* pubDest, uint32_t cubDest, uint32_t* pcubMsgSize)
{
if (messageType == k_EMsgGCCStrike15_v2_MatchmakingGC2ClientHello)
{
#ifdef DEBUG
printf("Packet == k_EMsgGCCStrike15_v2_MatchmakingGC2ClientHello\n");
#endif
if (g_Options.profile_active) {
MatchmakingGC2ClientHello msg((void*)((DWORD)pubDest + 8), *pcubMsgSize - 8);
MatchmakingGC2ClientHello::PlayerCommendationInfo commendations;
commendations.cmd_friendly().set(g_Options.comfriendly);
commendations.cmd_teaching().set(g_Options.comteacher);
commendations.cmd_leader().set(g_Options.comleader);
msg.commendation().set(commendations);
msg.player_level().set(g_Options.level);
msg.player_cur_xp().set(g_Options.xp);
if (g_Options.banduration != 0) {
msg.penalty_reason().set(g_Options.banreason);
msg.penalty_seconds().set(g_Options.banduration);
}
msg.vac_banned().set(g_Options.vacban);
MatchmakingGC2ClientHello::PlayerRankingInfo ranking;
ranking.account_id().set(iff.g_SteamUser->GetSteamID().GetAccountID());
ranking.rank_type_id().set(6);
ranking.rank_id().set(g_Options.rankz.value->arr[0].rank);
ranking.wins().set(g_Options.rankz.value->arr[0].wins);
msg.ranking().set(ranking);
auto packet = msg.serialize();
WritePacket(packet, thisPtr, oldEBP, pubDest, cubDest, pcubMsgSize);
#ifdef DEBUG
printf("send packet 0 6 rank %d wins %d\n", g_Options.rankz.value->arr[0].rank, g_Options.rankz.value->arr[0].wins);
#endif
}
}
else if (messageType == k_EMsgGCCStrike15_v2_ClientGCRankUpdate)
{
#ifdef DEBUG
printf("Packet == k_EMsgGCCStrike15_v2_ClientGCRankUpdate\n");
#endif
if (g_Options.profile_active) {
CMsgGCCStrike15_v2_ClientGCRankUpdate msg((void*)((DWORD)pubDest + 8), *pcubMsgSize - 8);
auto ranking = msg.ranking().get();
int ranktype = ranking.rank_type_id().get();
#ifdef DEBUG
printf("ranktype = %d\n", ranktype);
#endif
int rankcount = 0;
if (ranktype == 7) rankcount = 1;
if (ranktype == 10) rankcount = 2;
ranking.rank_id().set(g_Options.rankz.value->arr[rankcount].rank);
ranking.wins().set(g_Options.rankz.value->arr[rankcount].wins);
msg.ranking().set(ranking);
auto packet = msg.serialize();
WritePacket(packet, thisPtr, oldEBP, pubDest, cubDest, pcubMsgSize);
}
}
else if (messageType == k_EMsgGCClientWelcome)
{
#ifdef DEBUG
printf("Packet == k_EMsgGCClientWelcome\n");
#endif
auto packet = inventory_changer(pubDest, pcubMsgSize);
WritePacket(packet, thisPtr, oldEBP, pubDest, cubDest, pcubMsgSize);
}
#ifdef DEBUG
printf(".GC Receive: %d\n", messageType);
#endif
}
bool Protobuffs::PreSendMessage(uint32_t& unMsgType, void* pubData, uint32_t& cubData)
{
uint32_t MessageType = unMsgType & 0x7FFFFFFF;
#ifdef DEBUG
printf(".GC Sent: %d\n", MessageType);
#endif
return true;
}
bool Protobuffs::SendClientHello()
{
CMsgClientHello msg;
msg.client_session_need().set(1);
auto packet = msg.serialize();
void* ptr = malloc(packet.size() + 8);
if (!ptr)
return false;
((uint32_t*)ptr)[0] = k_EMsgGCClientHello | ((DWORD)1 << 31);
((uint32_t*)ptr)[1] = 0;
memcpy((void*)((DWORD)ptr + 8), (void*)packet.data(), packet.size());
bool result = iff.g_SteamGameCoordinator->GCSendMessage(k_EMsgGCClientHello | ((DWORD)1 << 31), ptr, packet.size() + 8) == k_EGCResultOK;
free(ptr);
return result;
}
bool Protobuffs::SendMatchmakingClient2GCHello()
{
ProtoWriter msg(0);
auto packet = msg.serialize();
void* ptr = malloc(packet.size() + 8);
if (!ptr)
return false;
((uint32_t*)ptr)[0] = k_EMsgGCCStrike15_v2_MatchmakingClient2GCHello | ((DWORD)1 << 31);
((uint32_t*)ptr)[1] = 0;
memcpy((void*)((DWORD)ptr + 8), (void*)packet.data(), packet.size());
bool result = iff.g_SteamGameCoordinator->GCSendMessage(k_EMsgGCCStrike15_v2_MatchmakingClient2GCHello | ((DWORD)1 << 31), ptr, packet.size() + 8) == k_EGCResultOK;
free(ptr);
return result;
}
bool Protobuffs::SendClientGcRankUpdate()
{
MatchmakingGC2ClientHello::PlayerRankingInfo rank_wingman;
rank_wingman.rank_type_id().set(7);
CMsgGCCStrike15_v2_ClientGCRankUpdate msg;
msg.ranking().set(rank_wingman);
auto packet = msg.serialize();
void* ptr = malloc(packet.size() + 8);
if (!ptr)
return false;
((uint32_t*)ptr)[0] = k_EMsgGCCStrike15_v2_ClientGCRankUpdate | ((DWORD)1 << 31);
((uint32_t*)ptr)[1] = 0;
memcpy((void*)((DWORD)ptr + 8), (void*)packet.data(), packet.size());
bool result = iff.g_SteamGameCoordinator->GCSendMessage(k_EMsgGCCStrike15_v2_ClientGCRankUpdate | ((DWORD)1 << 31), ptr, packet.size() + 8) == k_EGCResultOK;
free(ptr);
return result;
}
bool Protobuffs::EquipWeapon(int weaponid, int classid, int slotid)
{
CMsgAdjustItemEquippedState msg;
msg.item_id().set(START_ITEM_INDEX + weaponid);
msg.new_class().set(classid);
msg.new_slot().set(slotid);
msg.swap().set(true);
auto packet = msg.serialize();
void* ptr = malloc(packet.size() + 8);
if (!ptr)
return false;
((uint32_t*)ptr)[0] = k_EMsgGCAdjustItemEquippedState | ((DWORD)1 << 31);
((uint32_t*)ptr)[1] = 0;
memcpy((void*)((DWORD)ptr + 8), (void*)packet.data(), packet.size());
bool result = iff.g_SteamGameCoordinator->GCSendMessage(k_EMsgGCAdjustItemEquippedState | ((DWORD)1 << 31), ptr, packet.size() + 8) == k_EGCResultOK;
free(ptr);
return result;
}
VMTHook* ProtoHook = nullptr;
Protobuffs ProtoFeatures;
EGCResult __fastcall hkGCRetrieveMessage(void* ecx, void*, uint32_t* punMsgType, void* pubDest, uint32_t cubDest, uint32_t* pcubMsgSize)
{
static auto oGCRetrieveMessage = ProtoHook->GetOriginal<EGCResult(__thiscall*)(void*, uint32_t* punMsgType, void* pubDest, uint32_t cubDest, uint32_t* pcubMsgSize)>(2);
auto status = oGCRetrieveMessage(ecx, punMsgType, pubDest, cubDest, pcubMsgSize);
if (status == k_EGCResultOK)
{
void* thisPtr = nullptr;
__asm mov thisPtr, ebx;
auto oldEBP = *reinterpret_cast<void**>((uint32_t)_AddressOfReturnAddress() - 4);
uint32_t messageType = *punMsgType & 0x7FFFFFFF;
ProtoFeatures.ReceiveMessage(thisPtr, oldEBP, messageType, pubDest, cubDest, pcubMsgSize);
}
return status;
}
EGCResult __fastcall hkGCSendMessage(void* ecx, void*, uint32_t unMsgType, const void* pubData, uint32_t cubData)
{
static auto oGCSendMessage = ProtoHook->GetOriginal<EGCResult(__thiscall*)(void*, uint32_t unMsgType, const void* pubData, uint32_t cubData)>(0);
bool sendMessage = ProtoFeatures.PreSendMessage(unMsgType, const_cast<void*>(pubData), cubData);
if (!sendMessage)
return k_EGCResultOK;
return oGCSendMessage(ecx, unMsgType, const_cast<void*>(pubData), cubData);
}

30
SpyCustom/protobuffs.hpp Normal file
View File

@ -0,0 +1,30 @@
#pragma once
#include <windows.h>
#include <string>
#include "VMT.hpp"
#include "steam.h"
#include "intrin.h"
extern VMTHook* ProtoHook;
class Protobuffs
{
public:
static void WritePacket(std::string packet, void* thisPtr, void* oldEBP, void* pubDest, uint32_t cubDest, uint32_t* pcubMsgSize);
void ReceiveMessage(void* thisPtr, void* oldEBP, uint32_t messageType, void* pubDest, uint32_t cubDest, uint32_t* pcubMsgSize);
bool PreSendMessage(uint32_t& unMsgType, void* pubData, uint32_t& cubData);
bool SendClientHello();
bool SendMatchmakingClient2GCHello();
bool SendClientGcRankUpdate();
bool EquipWeapon(int weaponid, int classid, int slotid);
};
extern Protobuffs ProtoFeatures;
EGCResult __fastcall hkGCRetrieveMessage(void* ecx, void*, uint32_t* punMsgType, void* pubDest, uint32_t cubDest, uint32_t* pcubMsgSize);
EGCResult __fastcall hkGCSendMessage(void* ecx, void*, uint32_t unMsgType, const void* pubData, uint32_t cubData);

195
SpyCustom/proxies.hpp Normal file
View File

@ -0,0 +1,195 @@
#pragma once
RecvVarProxyFn fnSequenceProxyFn = NULL;
void SetViewModelSequence(const CRecvProxyData* pDataConst, void* pStruct, void* pOut) {
CRecvProxyData* pData = const_cast<CRecvProxyData*>(pDataConst);
C_BaseViewModel* pViewModel = (C_BaseViewModel*)pStruct;
if (pViewModel) {
IClientEntity* pOwner = iff.g_pEntityList->GetClientEntityFromHandle(pViewModel->GetOwner());
if (pOwner && pOwner->GetIndex() == iff.g_pEngineClient->GetLocalPlayer()) {
const model_t* pModel = iff.g_pMdlInfo->GetModel(pViewModel->GetModelIndex());
const char* szModel = iff.g_pMdlInfo->GetModelName(pModel);
int m_nSequence = pData->m_Value.m_Int;
auto model = fnv2::hashRuntime(szModel);
static int defknifethash = fnv2::hash("models/weapons/v_knife_default_t.mdl");
static int defknifecthash = fnv2::hash("models/weapons/v_knife_default_ct.mdl");
if (model == defknifethash || model == defknifecthash) model = fnv2::hash(g_Options.weapons.value->arr[0].model);
for (int i = 2; i < g_Options.models.value->itemcount; i++) {
if (model == g_Options.models.value->arr[i].vmodel_hash)
{
if (g_Options.models.value->arr[i].seq_active)
m_nSequence = g_Options.models.value->arr[i].seqs[m_nSequence].seq_repl;
break;
}
if (model == fnv2::hash(g_Options.models.value->arr[i].vmodel_orig))
{
if (g_Options.models.value->arr[i].seq_active)
m_nSequence = g_Options.models.value->arr[i].seqs[m_nSequence].seq_repl;
break;
}
}
switch (model) {
case fnv2::hash("models/weapons/v_knife_butterfly.mdl"):
{
switch (m_nSequence)
{
case SEQUENCE_DEFAULT_DRAW:
m_nSequence = random(SEQUENCE_BUTTERFLY_DRAW, SEQUENCE_BUTTERFLY_DRAW2); break;
case SEQUENCE_DEFAULT_LOOKAT01:
m_nSequence = random(SEQUENCE_BUTTERFLY_LOOKAT01, SEQUENCE_BUTTERFLY_LOOKAT03); break;
default:
m_nSequence++;
}
break;
}
case fnv2::hash("models/weapons/v_knife_falchion_advanced.mdl"):
{
switch (m_nSequence)
{
case SEQUENCE_DEFAULT_IDLE2:
m_nSequence = SEQUENCE_FALCHION_IDLE1; break;
case SEQUENCE_DEFAULT_HEAVY_MISS1:
m_nSequence = random(SEQUENCE_FALCHION_HEAVY_MISS1, SEQUENCE_FALCHION_HEAVY_MISS1_NOFLIP); break;
case SEQUENCE_DEFAULT_LOOKAT01:
m_nSequence = random(SEQUENCE_FALCHION_LOOKAT01, SEQUENCE_FALCHION_LOOKAT02); break;
case SEQUENCE_DEFAULT_DRAW:
case SEQUENCE_DEFAULT_IDLE1:
m_nSequence = m_nSequence; break;
default:
m_nSequence--;
}
break;
}
case fnv2::hash("models/weapons/v_knife_push.mdl"):
{
switch (m_nSequence)
{
case SEQUENCE_DEFAULT_IDLE2:
m_nSequence = SEQUENCE_DAGGERS_IDLE1; break;
case SEQUENCE_DEFAULT_LIGHT_MISS1:
case SEQUENCE_DEFAULT_LIGHT_MISS2:
m_nSequence = random(SEQUENCE_DAGGERS_LIGHT_MISS1, SEQUENCE_DAGGERS_LIGHT_MISS5); break;
case SEQUENCE_DEFAULT_HEAVY_MISS1:
m_nSequence = random(SEQUENCE_DAGGERS_HEAVY_MISS2, SEQUENCE_DAGGERS_HEAVY_MISS1); break;
case SEQUENCE_DEFAULT_HEAVY_HIT1:
case SEQUENCE_DEFAULT_HEAVY_BACKSTAB:
case SEQUENCE_DEFAULT_LOOKAT01:
m_nSequence = m_nSequence + 3; break;
case SEQUENCE_DEFAULT_DRAW:
case SEQUENCE_DEFAULT_IDLE1:
m_nSequence = m_nSequence; break;
default:
m_nSequence = m_nSequence + 2;
}
break;
}
case fnv2::hash("models/weapons/v_knife_survival_bowie.mdl"):
{
switch (m_nSequence)
{
case SEQUENCE_DEFAULT_DRAW:
case SEQUENCE_DEFAULT_IDLE1:
m_nSequence = m_nSequence; break;
case SEQUENCE_DEFAULT_IDLE2:
m_nSequence = SEQUENCE_BOWIE_IDLE1; break;
default:
m_nSequence = m_nSequence - 1;
}
break;
}
case fnv2::hash("models/weapons/v_knife_ursus.mdl"):
case fnv2::hash("models/weapons/v_knife_skeleton.mdl"):
case fnv2::hash("models/weapons/v_knife_outdoor.mdl"):
case fnv2::hash("models/weapons/v_knife_cord.mdl"):
case fnv2::hash("models/weapons/v_knife_canis.mdl"):
{
switch (m_nSequence)
{
case SEQUENCE_DEFAULT_DRAW:
m_nSequence = random(SEQUENCE_BUTTERFLY_DRAW, SEQUENCE_BUTTERFLY_DRAW2); break;
case SEQUENCE_DEFAULT_LOOKAT01:
m_nSequence = random(SEQUENCE_BUTTERFLY_LOOKAT01, 14); break;
default:
m_nSequence = m_nSequence + 1;
}
break;
}
case fnv2::hash("models/weapons/v_knife_stiletto.mdl"):
{
switch (m_nSequence)
{
case SEQUENCE_DEFAULT_LOOKAT01:
m_nSequence = random(12, 13); break;
}
break;
}
case fnv2::hash("models/weapons/v_knife_widowmaker.mdl"):
{
switch (m_nSequence)
{
case SEQUENCE_DEFAULT_LOOKAT01:
m_nSequence = random(14, 15); break;
}
break;
}
case fnv2::hash("models/weapons/v_fists.mdl"):
case fnv2::hash("models/weapons/v_axe.mdl"):
case fnv2::hash("models/weapons/v_hammer.mdl"):
case fnv2::hash("models/weapons/v_spanner.mdl"):
{
static int lastpunch = 3;
switch (m_nSequence)
{
case SEQUENCE_DEFAULT_DRAW:
m_nSequence = 1; break;
case 1:
case 2:
case 12:
m_nSequence = 0; break;
default:
if (lastpunch == 3) lastpunch = 2; else lastpunch = 3;
m_nSequence = lastpunch;
}
break;
}
}
#ifdef DEBUG
cout << "activ " << (char*)pViewModel->GetSequenceActivity(m_nSequence);
printf(" new seq %d (%s)\n ", m_nSequence, szModel);
#endif
pData->m_Value.m_Int = m_nSequence;
}
}
fnSequenceProxyFn(pData, pStruct, pOut);
}

111
SpyCustom/ragdoll.h Normal file
View File

@ -0,0 +1,111 @@
#ifndef RAGDOLL_H
#define RAGDOLL_H
#ifdef _WIN32
#pragma once
#endif
#include "ragdoll_shared.h"
#define RAGDOLL_VISUALIZE 0
class C_BaseEntity;
class CStudioHdr;
struct mstudiobone_t;
class Vector;
class IPhysicsObject;
class CBoneAccessor;
abstract_class IRagdoll
{
public:
virtual ~IRagdoll() {}
virtual void RagdollBone(C_BaseEntity * ent, mstudiobone_t * pbones, int boneCount, bool* boneSimulated, CBoneAccessor & pBoneToWorld) = 0;
virtual const Vector& GetRagdollOrigin() = 0;
virtual void GetRagdollBounds(Vector& mins, Vector& maxs) = 0;
virtual int RagdollBoneCount() const = 0;
virtual IPhysicsObject* GetElement(int elementNum) = 0;
virtual void DrawWireframe(void) = 0;
virtual void VPhysicsUpdate(IPhysicsObject* pObject) = 0;
};
class CRagdoll : public IRagdoll
{
public:
CRagdoll();
~CRagdoll(void);
DECLARE_SIMPLE_DATADESC();
void Init(
C_BaseEntity* ent,
CStudioHdr* pstudiohdr,
const Vector& forceVector,
int forceBone,
const matrix3x4_t* pDeltaBones0,
const matrix3x4_t* pDeltaBones1,
const matrix3x4_t* pCurrentBonePosition,
float boneDt);
virtual void RagdollBone(C_BaseEntity* ent, mstudiobone_t* pbones, int boneCount, bool* boneSimulated, CBoneAccessor& pBoneToWorld);
virtual const Vector& GetRagdollOrigin();
virtual void GetRagdollBounds(Vector& theMins, Vector& theMaxs);
void BuildRagdollBounds(C_BaseEntity* ent);
virtual IPhysicsObject* GetElement(int elementNum);
virtual IPhysicsConstraintGroup* GetConstraintGroup() { return m_ragdoll.pGroup; }
virtual void DrawWireframe();
virtual void VPhysicsUpdate(IPhysicsObject* pPhysics);
virtual int RagdollBoneCount() const { return m_ragdoll.listCount; }
void SetInitialBonePosition(CStudioHdr* pstudiohdr, const CBoneAccessor& pDesiredBonePosition);
bool IsValid() { return m_ragdoll.listCount > 0; }
bool IsAsleep(void) const { return m_allAsleep; }
void ResetRagdollSleepAfterTime(void);
float GetLastVPhysicsUpdateTime() const { return m_lastUpdate; }
private:
void CheckSettleStationaryRagdoll();
void PhysForceRagdollToSleep();
ragdoll_t m_ragdoll;
Vector m_mins, m_maxs;
Vector m_origin;
float m_lastUpdate;
bool m_allAsleep;
Vector m_vecLastOrigin;
float m_flLastOriginChangeTime;
float m_flAwakeTime;
#if RAGDOLL_VISUALIZE
matrix3x4_t m_savedBone1[MAXSTUDIOBONES];
matrix3x4_t m_savedBone2[MAXSTUDIOBONES];
matrix3x4_t m_savedBone3[MAXSTUDIOBONES];
#endif
public:
ragdoll_t* GetRagdoll(void) { return &m_ragdoll; }
};
CRagdoll* CreateRagdoll(
C_BaseEntity* ent,
CStudioHdr* pstudiohdr,
const Vector& forceVector,
int forceBone,
const matrix3x4_t* pDeltaBones0,
const matrix3x4_t* pDeltaBones1,
const matrix3x4_t* pCurrentBonePosition,
float boneDt);
void NoteRagdollCreationTick(C_BaseEntity* pRagdoll);
bool WasRagdollCreatedOnCurrentTick(C_BaseEntity* pRagdoll);
#endif

135
SpyCustom/ragdoll_shared.h Normal file
View File

@ -0,0 +1,135 @@
#ifndef RAGDOLL_SHARED_H
#define RAGDOLL_SHARED_H
#ifdef _WIN32
#pragma once
#endif
class IPhysicsObject;
class IPhysicsConstraint;
class IPhysicsConstraintGroup;
class IPhysicsCollision;
class IPhysicsEnvironment;
class IPhysicsSurfaceProps;
struct matrix3x4_t;
struct vcollide_t;
struct studiohdr_t;
class CStudioHdr;
class CBoneAccessor;
#include "vector.h"
#include "bone_accessor.h"
#define RAGDOLL_MAX_ELEMENTS 24
#define RAGDOLL_INDEX_BITS 5
#define CORE_DISSOLVE_FADE_START 0.2f
#define CORE_DISSOLVE_MODEL_FADE_START 0.1f
#define CORE_DISSOLVE_MODEL_FADE_LENGTH 0.05f
#define CORE_DISSOLVE_FADEIN_LENGTH 0.1f
struct ragdollelement_t
{
Vector originParentSpace;
IPhysicsObject* pObject;
IPhysicsConstraint* pConstraint;
int parentIndex;
};
struct ragdollanimatedfriction_t
{
float flFrictionTimeIn;
float flFrictionTimeOut;
float flFrictionTimeHold;
int iMinAnimatedFriction;
int iMaxAnimatedFriction;
};
struct ragdoll_t
{
int listCount;
bool allowStretch;
bool unused;
IPhysicsConstraintGroup* pGroup;
ragdollelement_t list[RAGDOLL_MAX_ELEMENTS];
int boneIndex[RAGDOLL_MAX_ELEMENTS];
ragdollanimatedfriction_t animfriction;
};
struct ragdollparams_t
{
void* pGameData;
vcollide_t* pCollide;
CStudioHdr* pStudioHdr;
int modelIndex;
Vector forcePosition;
Vector forceVector;
int forceBoneIndex;
const matrix3x4_t* pCurrentBones;
float jointFrictionScale;
bool allowStretch;
bool fixedConstraints;
};
class CRagdollLRURetirement : public CAutoGameSystemPerFrame
{
public:
CRagdollLRURetirement(char const* name) : CAutoGameSystemPerFrame(name)
{
}
virtual void Update(float frametime);
virtual void FrameUpdatePostEntityThink(void);
void MoveToTopOfLRU(CBaseAnimating* pRagdoll, bool bImportant = false);
void SetMaxRagdollCount(int iMaxCount) { m_iMaxRagdolls = iMaxCount; }
virtual void LevelInitPreEntity(void);
int CountRagdolls(bool bOnlySimulatingRagdolls) { return bOnlySimulatingRagdolls ? m_iSimulatedRagdollCount : m_iRagdollCount; }
private:
typedef CHandle<CBaseAnimating> CRagdollHandle;
CUtlLinkedList< CRagdollHandle > m_LRU;
CUtlLinkedList< CRagdollHandle > m_LRUImportantRagdolls;
int m_iMaxRagdolls;
int m_iSimulatedRagdollCount;
int m_iRagdollCount;
};
extern CRagdollLRURetirement s_RagdollLRU;
class CRagdollLowViolenceManager
{
public:
CRagdollLowViolenceManager() { m_bLowViolence = false; }
void SetLowViolence(const char* pMapName);
bool IsLowViolence(void) { return m_bLowViolence; }
private:
bool m_bLowViolence;
};
extern CRagdollLowViolenceManager g_RagdollLVManager;
bool RagdollCreate(ragdoll_t& ragdoll, const ragdollparams_t& params, IPhysicsEnvironment* pPhysEnv);
void RagdollActivate(ragdoll_t& ragdoll, vcollide_t* pCollide, int modelIndex, bool bForceWake = true);
void RagdollSetupCollisions(ragdoll_t& ragdoll, vcollide_t* pCollide, int modelIndex);
void RagdollDestroy(ragdoll_t& ragdoll);
bool RagdollGetBoneMatrix(const ragdoll_t& ragdoll, CBoneAccessor& pBoneToWorld, int objectIndex);
int RagdollExtractBoneIndices(int* boneIndexOut, CStudioHdr* pStudioHdr, vcollide_t* pCollide);
void RagdollComputeExactBbox(const ragdoll_t& ragdoll, const Vector& origin, Vector& outMins, Vector& outMaxs);
bool RagdollIsAsleep(const ragdoll_t& ragdoll);
void RagdollSetupAnimatedFriction(IPhysicsEnvironment* pPhysEnv, ragdoll_t* ragdoll, int iModelIndex);
void RagdollApplyAnimationAsVelocity(ragdoll_t& ragdoll, const matrix3x4_t* pBoneToWorld);
void RagdollApplyAnimationAsVelocity(ragdoll_t& ragdoll, const matrix3x4_t* pPrevBones, const matrix3x4_t* pCurrentBones, float dt);
void RagdollSolveSeparation(ragdoll_t& ragdoll, CBaseEntity* pEntity);
#endif

77
SpyCustom/random.h Normal file
View File

@ -0,0 +1,77 @@
#ifndef VSTDLIB_RANDOM_H
#define VSTDLIB_RANDOM_H
#include "vstdlib.h"
#include "basetypes.h"
#include "threadtools.h"
#include "interface.h"
#define NTAB 32
#pragma warning(push)
#pragma warning( disable:4251 )
class IUniformRandomStream
{
public:
virtual void SetSeed(int iSeed) = 0;
virtual float RandomFloat(float flMinVal = 0.0f, float flMaxVal = 1.0f) = 0;
virtual int RandomInt(int iMinVal, int iMaxVal) = 0;
virtual float RandomFloatExp(float flMinVal = 0.0f, float flMaxVal = 1.0f, float flExponent = 1.0f) = 0;
};
class VSTDLIB_CLASS CUniformRandomStream : public IUniformRandomStream
{
public:
CUniformRandomStream();
virtual void SetSeed(int iSeed);
virtual float RandomFloat(float flMinVal = 0.0f, float flMaxVal = 1.0f);
virtual int RandomInt(int iMinVal, int iMaxVal);
virtual float RandomFloatExp(float flMinVal = 0.0f, float flMaxVal = 1.0f, float flExponent = 1.0f);
private:
int GenerateRandomNumber();
int m_idum;
int m_iy;
int m_iv[NTAB];
CThreadFastMutex m_mutex;
};
class VSTDLIB_CLASS CGaussianRandomStream
{
public:
CGaussianRandomStream(IUniformRandomStream* pUniformStream = NULL);
void AttachToStream(IUniformRandomStream* pUniformStream = NULL);
float RandomFloat(float flMean = 0.0f, float flStdDev = 1.0f);
private:
IUniformRandomStream* m_pUniformStream;
bool m_bHaveValue;
float m_flRandomValue;
CThreadFastMutex m_mutex;
};
VSTDLIB_INTERFACE void RandomSeed(int iSeed);
VSTDLIB_INTERFACE float RandomFloat(float flMinVal = 0.0f, float flMaxVal = 1.0f);
VSTDLIB_INTERFACE float RandomFloatExp(float flMinVal = 0.0f, float flMaxVal = 1.0f, float flExponent = 1.0f);
VSTDLIB_INTERFACE int RandomInt(int iMinVal, int iMaxVal);
VSTDLIB_INTERFACE float RandomGaussianFloat(float flMean = 0.0f, float flStdDev = 1.0f);
VSTDLIB_INTERFACE void InstallUniformRandomStream(IUniformRandomStream* pStream);
#pragma warning(pop)
#endif

109
SpyCustom/rangecheckedvar.h Normal file
View File

@ -0,0 +1,109 @@
#ifndef RANGECHECKEDVAR_H
#define RANGECHECKEDVAR_H
#ifdef _WIN32
#pragma once
#endif
#include "dbg.h"
#include "threadtools.h"
#include "vector.h"
#include <float.h>
class CDisableRangeChecks
{
public:
CDisableRangeChecks();
~CDisableRangeChecks();
};
template< class T >
inline void RangeCheck(const T& value, int minValue, int maxValue)
{
#ifdef _DEBUG
extern bool g_bDoRangeChecks;
if (ThreadInMainThread() && g_bDoRangeChecks)
{
Assert(_finite(value));
}
#endif
}
inline void RangeCheck(const Vector& value, int minValue, int maxValue)
{
#ifdef _DEBUG
RangeCheck(value.x, minValue, maxValue);
RangeCheck(value.y, minValue, maxValue);
RangeCheck(value.z, minValue, maxValue);
#endif
}
template< class T, int minValue, int maxValue, int startValue >
class CRangeCheckedVar
{
public:
inline CRangeCheckedVar()
{
m_Val = startValue;
}
inline CRangeCheckedVar(const T& value)
{
*this = value;
}
T GetRaw() const
{
return m_Val;
}
inline void Clamp()
{
if (m_Val < minValue)
m_Val = minValue;
else if (m_Val > maxValue)
m_Val = maxValue;
}
inline operator const T& () const
{
return m_Val;
}
inline CRangeCheckedVar<T, minValue, maxValue, startValue>& operator=(const T& value)
{
RangeCheck(value, minValue, maxValue);
m_Val = value;
return *this;
}
inline CRangeCheckedVar<T, minValue, maxValue, startValue>& operator+=(const T& value)
{
return (*this = m_Val + value);
}
inline CRangeCheckedVar<T, minValue, maxValue, startValue>& operator-=(const T& value)
{
return (*this = m_Val - value);
}
inline CRangeCheckedVar<T, minValue, maxValue, startValue>& operator*=(const T& value)
{
return (*this = m_Val * value);
}
inline CRangeCheckedVar<T, minValue, maxValue, startValue>& operator/=(const T& value)
{
return (*this = m_Val / value);
}
private:
T m_Val;
};
#endif

45
SpyCustom/recvproxy.h Normal file
View File

@ -0,0 +1,45 @@
#ifndef RECVPROXY_H
#define RECVPROXY_H
class CRecvProxyData;
void RecvProxy_IntToEHandle(const CRecvProxyData* pData, void* pStruct, void* pOut);
void RecvProxy_IntToMoveParent(const CRecvProxyData* pData, void* pStruct, void* pOut);
void RecvProxy_IntToColor32(const CRecvProxyData* pData, void* pStruct, void* pOut);
void RecvProxy_IntSubOne(const CRecvProxyData* pData, void* pStruct, void* pOut);
void RecvProxy_ShortSubOne(const CRecvProxyData* pData, void* pStruct, void* pOut);
void RecvProxy_InterpolationAmountChanged(const CRecvProxyData* pData, void* pStruct, void* pOut);
RecvProp RecvPropTime(
char* pVarName,
int offset,
int sizeofVar = SIZEOF_IGNORE);
#if !defined( NO_ENTITY_PREDICTION ) && defined( USE_PREDICTABLEID )
RecvProp RecvPropPredictableId(
char* pVarName,
int offset,
int sizeofVar = SIZEOF_IGNORE);
#endif
RecvProp RecvPropEHandle(
char* pVarName,
int offset,
int sizeofVar = SIZEOF_IGNORE,
RecvVarProxyFn proxyFn = RecvProxy_IntToEHandle);
RecvProp RecvPropBool(
char* pVarName,
int offset,
int sizeofVar);
RecvProp RecvPropIntWithMinusOneFlag(
char* pVarName,
int offset,
int sizeofVar = SIZEOF_IGNORE,
RecvVarProxyFn proxyFn = RecvProxy_IntSubOne);
#endif

320
SpyCustom/refcount.h Normal file
View File

@ -0,0 +1,320 @@
#ifndef REFCOUNT_H
#define REFCOUNT_H
#include "threadtools.h"
#if defined( _WIN32 )
#pragma once
#endif
class IRefCounted
{
public:
virtual int AddRef() = 0;
virtual int Release() = 0;
};
template <class REFCOUNTED_ITEM_PTR>
inline int SafeRelease(REFCOUNTED_ITEM_PTR& pRef)
{
REFCOUNTED_ITEM_PTR* ppRef = &pRef;
if (*ppRef)
{
int result = (*ppRef)->Release();
*ppRef = NULL;
return result;
}
return 0;
}
template <class T = IRefCounted>
class CAutoRef
{
public:
CAutoRef(T* pRef)
: m_pRef(pRef)
{
if (m_pRef)
m_pRef->AddRef();
}
~CAutoRef()
{
if (m_pRef)
m_pRef->Release();
}
private:
T* m_pRef;
};
#define RetAddRef( p ) ( (p)->AddRef(), (p) )
#define InlineAddRef( p ) ( (p)->AddRef(), (p) )
template <class T>
class CBaseAutoPtr
{
public:
CBaseAutoPtr() : m_pObject(0) {}
CBaseAutoPtr(T* pFrom) : m_pObject(pFrom) {}
operator const void* () const { return m_pObject; }
operator void* () { return m_pObject; }
operator const T* () const { return m_pObject; }
operator const T* () { return m_pObject; }
operator T* () { return m_pObject; }
int operator=(int i) { AssertMsg(i == 0, "Only NULL allowed on integer assign"); m_pObject = 0; return 0; }
T* operator=(T* p) { m_pObject = p; return p; }
bool operator !() const { return (!m_pObject); }
bool operator!=(int i) const { AssertMsg(i == 0, "Only NULL allowed on integer compare"); return (m_pObject != NULL); }
bool operator==(const void* p) const { return (m_pObject == p); }
bool operator!=(const void* p) const { return (m_pObject != p); }
bool operator==(T* p) const { return operator==((void*)p); }
bool operator!=(T* p) const { return operator!=((void*)p); }
bool operator==(const CBaseAutoPtr<T>& p) const { return operator==((const void*)p); }
bool operator!=(const CBaseAutoPtr<T>& p) const { return operator!=((const void*)p); }
T* operator->() { return m_pObject; }
T& operator *() { return *m_pObject; }
T** operator &() { return &m_pObject; }
const T* operator->() const { return m_pObject; }
const T& operator *() const { return *m_pObject; }
T* const* operator &() const { return &m_pObject; }
protected:
CBaseAutoPtr(const CBaseAutoPtr<T>& from) : m_pObject(from.m_pObject) {}
void operator=(const CBaseAutoPtr<T>& from) { m_pObject = from.m_pObject; }
T* m_pObject;
};
template <class T>
class CRefPtr : public CBaseAutoPtr<T>
{
typedef CBaseAutoPtr<T> BaseClass;
public:
CRefPtr() {}
CRefPtr(T* pInit) : BaseClass(pInit) {}
CRefPtr(const CRefPtr<T>& from) : BaseClass(from) {}
~CRefPtr() { if (BaseClass::m_pObject) BaseClass::m_pObject->Release(); }
void operator=(const CRefPtr<T>& from) { BaseClass::operator=(from); }
int operator=(int i) { return BaseClass::operator=(i); }
T* operator=(T* p) { return BaseClass::operator=(p); }
operator bool() const { return !BaseClass::operator!(); }
operator bool() { return !BaseClass::operator!(); }
void SafeRelease() { if (BaseClass::m_pObject) BaseClass::m_pObject->Release(); BaseClass::m_pObject = 0; }
void AssignAddRef(T* pFrom) { SafeRelease(); if (pFrom) pFrom->AddRef(); BaseClass::m_pObject = pFrom; }
void AddRefAssignTo(T*& pTo) { ::SafeRelease(pTo); if (BaseClass::m_pObject) BaseClass::m_pObject->AddRef(); pTo = BaseClass::m_pObject; }
};
class CRefMT
{
public:
static int Increment(int* p) { return ThreadInterlockedIncrement((long*)p); }
static int Decrement(int* p) { return ThreadInterlockedDecrement((long*)p); }
};
class CRefST
{
public:
static int Increment(int* p) { return ++(*p); }
static int Decrement(int* p) { return --(*p); }
};
template <const bool bSelfDelete, typename CRefThreading = CRefMT>
class NO_VTABLE CRefCountServiceBase
{
protected:
CRefCountServiceBase()
: m_iRefs(1)
{
}
virtual ~CRefCountServiceBase()
{
}
virtual bool OnFinalRelease()
{
return true;
}
int GetRefCount() const
{
return m_iRefs;
}
int DoAddRef()
{
return CRefThreading::Increment(&m_iRefs);
}
int DoRelease()
{
int result = CRefThreading::Decrement(&m_iRefs);
if (result)
return result;
if (OnFinalRelease() && bSelfDelete)
delete this;
return 0;
}
private:
int m_iRefs;
};
class CRefCountServiceNull
{
protected:
static int DoAddRef() { return 1; }
static int DoRelease() { return 1; }
};
template <typename CRefThreading = CRefMT>
class NO_VTABLE CRefCountServiceDestruct
{
protected:
CRefCountServiceDestruct()
: m_iRefs(1)
{
}
virtual ~CRefCountServiceDestruct()
{
}
int GetRefCount() const
{
return m_iRefs;
}
int DoAddRef()
{
return CRefThreading::Increment(&m_iRefs);
}
int DoRelease()
{
int result = CRefThreading::Decrement(&m_iRefs);
if (result)
return result;
this->~CRefCountServiceDestruct();
return 0;
}
private:
int m_iRefs;
};
typedef CRefCountServiceBase<true, CRefST> CRefCountServiceST;
typedef CRefCountServiceBase<false, CRefST> CRefCountServiceNoDeleteST;
typedef CRefCountServiceBase<true, CRefMT> CRefCountServiceMT;
typedef CRefCountServiceBase<false, CRefMT> CRefCountServiceNoDeleteMT;
typedef CRefCountServiceNoDeleteMT CRefCountServiceNoDelete;
typedef CRefCountServiceMT CRefCountService;
template < class REFCOUNT_SERVICE = CRefCountService >
class NO_VTABLE CRefCounted : public REFCOUNT_SERVICE
{
public:
virtual ~CRefCounted() {}
int AddRef() { return REFCOUNT_SERVICE::DoAddRef(); }
int Release() { return REFCOUNT_SERVICE::DoRelease(); }
};
template < class BASE1, class REFCOUNT_SERVICE = CRefCountService >
class NO_VTABLE CRefCounted1 : public BASE1,
public REFCOUNT_SERVICE
{
public:
virtual ~CRefCounted1() {}
int AddRef() { return REFCOUNT_SERVICE::DoAddRef(); }
int Release() { return REFCOUNT_SERVICE::DoRelease(); }
};
template < class BASE1, class BASE2, class REFCOUNT_SERVICE = CRefCountService >
class NO_VTABLE CRefCounted2 : public BASE1, public BASE2,
public REFCOUNT_SERVICE
{
public:
virtual ~CRefCounted2() {}
int AddRef() { return REFCOUNT_SERVICE::DoAddRef(); }
int Release() { return REFCOUNT_SERVICE::DoRelease(); }
};
template < class BASE1, class BASE2, class BASE3, class REFCOUNT_SERVICE = CRefCountService >
class NO_VTABLE CRefCounted3 : public BASE1, public BASE2, public BASE3,
public REFCOUNT_SERVICE
{
virtual ~CRefCounted3() {}
int AddRef() { return REFCOUNT_SERVICE::DoAddRef(); }
int Release() { return REFCOUNT_SERVICE::DoRelease(); }
};
template < class BASE1, class BASE2, class BASE3, class BASE4, class REFCOUNT_SERVICE = CRefCountService >
class NO_VTABLE CRefCounted4 : public BASE1, public BASE2, public BASE3, public BASE4,
public REFCOUNT_SERVICE
{
public:
virtual ~CRefCounted4() {}
int AddRef() { return REFCOUNT_SERVICE::DoAddRef(); }
int Release() { return REFCOUNT_SERVICE::DoRelease(); }
};
template < class BASE1, class BASE2, class BASE3, class BASE4, class BASE5, class REFCOUNT_SERVICE = CRefCountService >
class NO_VTABLE CRefCounted5 : public BASE1, public BASE2, public BASE3, public BASE4, public BASE5,
public REFCOUNT_SERVICE
{
public:
virtual ~CRefCounted5() {}
int AddRef() { return REFCOUNT_SERVICE::DoAddRef(); }
int Release() { return REFCOUNT_SERVICE::DoRelease(); }
};
template <class BASE_REFCOUNTED, int FINAL_REFS, const char* pszName>
class CRefDebug : public BASE_REFCOUNTED
{
public:
#ifdef _DEBUG
CRefDebug()
{
AssertMsg(this->GetRefCount() == 1, "Expected initial ref count of 1");
DevMsg("%s:create 0x%x\n", (pszName) ? pszName : "", this);
}
virtual ~CRefDebug()
{
AssertDevMsg(this->GetRefCount() == FINAL_REFS, "Object still referenced on destroy?");
DevMsg("%s:destroy 0x%x\n", (pszName) ? pszName : "", this);
}
int AddRef()
{
DevMsg("%s:(0x%x)->AddRef() --> %d\n", (pszName) ? pszName : "", this, this->GetRefCount() + 1);
return BASE_REFCOUNTED::AddRef();
}
int Release()
{
DevMsg("%s:(0x%x)->Release() --> %d\n", (pszName) ? pszName : "", this, this->GetRefCount() - 1);
Assert(this->GetRefCount() > 0);
return BASE_REFCOUNTED::Release();
}
#endif
};
#endif

11
SpyCustom/resource.h Normal file
View File

@ -0,0 +1,11 @@
#define IDR_WAVE1 101
#define IDR_WAVE2 102
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 103
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif

View File

@ -0,0 +1,96 @@
#ifndef SCENEENTITY_SHARED_H
#define SCENEENTITY_SHARED_H
#ifdef _WIN32
#pragma once
#endif
#if defined( CLIENT_DLL )
#define CBaseFlex C_BaseFlex
#define CSceneEntity C_SceneEntity
#endif
#include "iscenetokenprocessor.h"
class CBaseFlex;
class CChoreoEvent;
class CChoreoScene;
class CChoreoActor;
class CSceneEntity;
class CSceneEventInfo
{
public:
CSceneEventInfo()
:
m_pEvent(0),
m_pScene(0),
m_pActor(0),
m_bStarted(false),
m_iLayer(-1),
m_iPriority(0),
m_nSequence(0),
m_bIsGesture(false),
m_flWeight(0.0f),
m_hTarget(),
m_bIsMoving(false),
m_bHasArrived(false),
m_flInitialYaw(0.0f),
m_flTargetYaw(0.0f),
m_flFacingYaw(0.0f),
m_nType(0),
m_flNext(0.0f),
m_bClientSide(false)
{
}
CChoreoEvent* m_pEvent;
CChoreoScene* m_pScene;
CChoreoActor* m_pActor;
bool m_bStarted;
public:
int m_iLayer;
int m_iPriority;
int m_nSequence;
bool m_bIsGesture;
float m_flWeight;
EHANDLE m_hTarget;
bool m_bIsMoving;
bool m_bHasArrived;
float m_flInitialYaw;
float m_flTargetYaw;
float m_flFacingYaw;
int m_nType;
float m_flNext;
bool m_bClientSide;
void InitWeight(CBaseFlex* pActor);
float UpdateWeight(CBaseFlex* pActor);
};
class CSceneTokenProcessor : public ISceneTokenProcessor
{
public:
const char* CurrentToken(void);
bool GetToken(bool crossline);
bool TokenAvailable(void);
void Error(PRINTF_FORMAT_STRING const char* fmt, ...);
void SetBuffer(char* buffer);
private:
const char* m_pBuffer;
char m_szToken[1024];
};
extern CSceneTokenProcessor g_TokenProcessor;
void Scene_Printf(PRINTF_FORMAT_STRING const char* pFormat, ...);
extern ConVar scene_clientflex;
#endif

79
SpyCustom/sdk_hud_chat.h Normal file
View File

@ -0,0 +1,79 @@
#ifndef SDK_HUD_CHAT_H
#define SDK_HUD_CHAT_H
#ifdef _WIN32
#pragma once
#endif
#include "hud_basechat.h"
#include "GetVFunc.hpp"
class CHudChatLine : public CBaseHudChatLine
{
DECLARE_CLASS_SIMPLE(CHudChatLine, CBaseHudChatLine);
public:
CHudChatLine(vgui::Panel* parent, const char* panelName) : CBaseHudChatLine(parent, panelName) {}
virtual void ApplySchemeSettings(vgui::IScheme* pScheme);
void PerformFadeout(void);
void MsgFunc_SayText(bf_read& msg);
private:
CHudChatLine(const CHudChatLine&);
};
class CHudChatInputLine : public CBaseHudChatInputLine
{
DECLARE_CLASS_SIMPLE(CHudChatInputLine, CBaseHudChatInputLine);
public:
CHudChatInputLine(CBaseHudChat* parent, char const* panelName) : CBaseHudChatInputLine(parent, panelName) {}
virtual void ApplySchemeSettings(vgui::IScheme* pScheme);
};
class CHudChat : public CBaseHudChat
{
DECLARE_CLASS_SIMPLE(CHudChat, CBaseHudChat);
public:
CHudChat(const char* pElementName);
virtual void CreateChatInputLine(void);
virtual void CreateChatLines(void);
virtual void Init(void);
virtual void Reset(void);
virtual void ApplySchemeSettings(vgui::IScheme* pScheme);
void MsgFunc_SayText(bf_read& msg);
void MsgFunc_TextMsg(bf_read& msg);
enum ChatFilters
{
CHAT_FILTER_NONE = 0,
CHAT_FILTER_JOINLEAVE = 0x000001,
CHAT_FILTER_NAMECHANGE = 0x000002,
CHAT_FILTER_PUBLICCHAT = 0x000004,
CHAT_FILTER_SERVERMSG = 0x000008,
CHAT_FILTER_TEAMCHANGE = 0x000010,
CHAT_FILTER_ACHIEVEMENT = 0x000020,
};
void ChatPrintf2(int iPlayerIndex, int iFilter, const char* fmt, ...)
{
char msg[1024];
va_list args;
va_start(args, fmt);
vsnprintf(msg, 1024, fmt, args);
getvfunc<void(__cdecl*)(void*, int, int, const char*, ...)>(this, 27)(this, iPlayerIndex, iFilter, fmt);
va_end(args);
}
int GetChatInputOffset(void);
};
#endif

5073
SpyCustom/seemath.h Normal file

File diff suppressed because it is too large Load Diff

52
SpyCustom/sendproxy.h Normal file
View File

@ -0,0 +1,52 @@
#ifndef SENDPROXY_H
#define SENDPROXY_H
#include "dt_send.h"
class DVariant;
void SendProxy_Color32ToInt(const SendProp* pProp, const void* pStruct, const void* pData, DVariant* pOut, int iElement, int objectID);
void SendProxy_EHandleToInt(const SendProp* pProp, const void* pStruct, const void* pVarData, DVariant* pOut, int iElement, int objectID);
void SendProxy_IntAddOne(const SendProp* pProp, const void* pStruct, const void* pVarData, DVariant* pOut, int iElement, int objectID);
void SendProxy_ShortAddOne(const SendProp* pProp, const void* pStruct, const void* pVarData, DVariant* pOut, int iElement, int objectID);
SendProp SendPropBool(
const char* pVarName,
int offset,
int sizeofVar);
SendProp SendPropEHandle(
const char* pVarName,
int offset,
int sizeofVar = SIZEOF_IGNORE,
int flags = 0,
SendVarProxyFn proxyFn = SendProxy_EHandleToInt);
SendProp SendPropTime(
const char* pVarName,
int offset,
int sizeofVar = SIZEOF_IGNORE);
#if !defined( NO_ENTITY_PREDICTION )
SendProp SendPropPredictableId(
const char* pVarName,
int offset,
int sizeofVar = SIZEOF_IGNORE);
#endif
SendProp SendPropIntWithMinusOneFlag(
const char* pVarName,
int offset,
int sizeofVar = SIZEOF_IGNORE,
int bits = -1,
SendVarProxyFn proxyFn = SendProxy_IntAddOne);
SendProp SendPropStringT(const char* pVarName, int offset, int sizeofVar);
void* SendProxy_OnlyToTeam(const SendProp* pProp, const void* pStruct, const void* pVarData, CSendProxyRecipients* pRecipients, int objectID);
#endif

View File

@ -0,0 +1,34 @@
#ifndef SEQUENCE_TRANSITIONER_H
#define SEQUENCE_TRANSITIONER_H
#ifdef _WIN32
#pragma once
#endif
class CSequenceTransitioner
{
public:
void CheckForSequenceChange(
CStudioHdr* hdr,
int nCurSequence,
bool bForceNewSequence,
bool bInterpolate
);
void UpdateCurrent(
CStudioHdr* hdr,
int nCurSequence,
float flCurCycle,
float flCurPlaybackRate,
float flCurTime
);
void RemoveAll(void) { m_animationQueue.RemoveAll(); };
public:
CUtlVector< CAnimationLayer > m_animationQueue;
};
#endif

47
SpyCustom/shake.h Normal file
View File

@ -0,0 +1,47 @@
#ifndef SHAKE_H
#define SHAKE_H
#ifdef _WIN32
#pragma once
#endif
struct ScreenShake_t
{
int command;
float amplitude;
float frequency;
float duration;
};
enum ShakeCommand_t
{
SHAKE_START = 0,
SHAKE_STOP,
SHAKE_AMPLITUDE,
SHAKE_FREQUENCY,
SHAKE_START_RUMBLEONLY,
SHAKE_START_NORUMBLE,
};
extern int gmsgShake;
extern int gmsgFade;
#define FFADE_IN 0x0001
#define FFADE_OUT 0x0002
#define FFADE_MODULATE 0x0004
#define FFADE_STAYOUT 0x0008
#define FFADE_PURGE 0x0010
#define SCREENFADE_FRACBITS 9
struct ScreenFade_t
{
unsigned short duration;
unsigned short holdTime;
short fadeFlags;
byte r, g, b, a;
};
#endif

View File

@ -0,0 +1,17 @@
#ifndef SHARED_CLASSNAMES_H
#define SHARED_CLASSNAMES_H
#ifdef _WIN32
#pragma once
#endif
#if defined( CLIENT_DLL )
#define CBaseEntity C_BaseEntity
#define CBaseCombatCharacter C_BaseCombatCharacter
#define CBaseAnimating C_BaseAnimating
#define CBasePlayer C_BasePlayer
#endif
#endif

838
SpyCustom/shareddefs.h Normal file
View File

@ -0,0 +1,838 @@
#ifndef SHADERAPI_SHAREDDEFS_H
#define SHADERAPI_SHAREDDEFS_H
#ifdef _WIN32
#pragma once
#endif
enum ShaderShadeMode_t
{
SHADER_FLAT = 0,
SHADER_SMOOTH
};
enum ShaderTexCoordComponent_t
{
SHADER_TEXCOORD_S = 0,
SHADER_TEXCOORD_T,
SHADER_TEXCOORD_U
};
enum ShaderTexFilterMode_t
{
SHADER_TEXFILTERMODE_NEAREST,
SHADER_TEXFILTERMODE_LINEAR,
SHADER_TEXFILTERMODE_NEAREST_MIPMAP_NEAREST,
SHADER_TEXFILTERMODE_LINEAR_MIPMAP_NEAREST,
SHADER_TEXFILTERMODE_NEAREST_MIPMAP_LINEAR,
SHADER_TEXFILTERMODE_LINEAR_MIPMAP_LINEAR,
SHADER_TEXFILTERMODE_ANISOTROPIC
};
enum ShaderTexWrapMode_t
{
SHADER_TEXWRAPMODE_CLAMP,
SHADER_TEXWRAPMODE_REPEAT,
SHADER_TEXWRAPMODE_BORDER
};
enum TextureStage_t
{
SHADER_TEXTURE_STAGE0 = 0,
SHADER_TEXTURE_STAGE1,
};
enum Sampler_t
{
SHADER_SAMPLER0 = 0,
SHADER_SAMPLER1,
SHADER_SAMPLER2,
SHADER_SAMPLER3,
SHADER_SAMPLER4,
SHADER_SAMPLER5,
SHADER_SAMPLER6,
SHADER_SAMPLER7,
SHADER_SAMPLER8,
SHADER_SAMPLER9,
SHADER_SAMPLER10,
SHADER_SAMPLER11,
SHADER_SAMPLER12,
SHADER_SAMPLER13,
SHADER_SAMPLER14,
SHADER_SAMPLER15,
};
enum VertexTextureSampler_t
{
SHADER_VERTEXTEXTURE_SAMPLER0 = 0,
SHADER_VERTEXTEXTURE_SAMPLER1,
SHADER_VERTEXTEXTURE_SAMPLER2,
SHADER_VERTEXTEXTURE_SAMPLER3,
};
#if defined( _X360 )
#define REVERSE_DEPTH_ON_X360
#endif
#if defined( REVERSE_DEPTH_ON_X360 )
#define ReverseDepthOnX360() true
#else
#define ReverseDepthOnX360() false
#endif
#include "bittools.h"
#define TICK_INTERVAL (gpGlobals->interval_per_tick)
#define TIME_TO_TICKS( dt ) ( (int)( 0.5f + (float)(dt) / TICK_INTERVAL ) )
#define TICKS_TO_TIME( t ) ( TICK_INTERVAL *( t ) )
#define ROUND_TO_TICKS( t ) ( TICK_INTERVAL * TIME_TO_TICKS( t ) )
#define TICK_NEVER_THINK (-1)
#define ANIMATION_CYCLE_BITS 15
#define ANIMATION_CYCLE_MINFRAC (1.0f / (1<<ANIMATION_CYCLE_BITS))
#define CONCEPT_WEIGHT 5.0f
class CViewVectors
{
public:
CViewVectors() {}
CViewVectors(
Vector vView,
Vector vHullMin,
Vector vHullMax,
Vector vDuckHullMin,
Vector vDuckHullMax,
Vector vDuckView,
Vector vObsHullMin,
Vector vObsHullMax,
Vector vDeadViewHeight)
{
m_vView = vView;
m_vHullMin = vHullMin;
m_vHullMax = vHullMax;
m_vDuckHullMin = vDuckHullMin;
m_vDuckHullMax = vDuckHullMax;
m_vDuckView = vDuckView;
m_vObsHullMin = vObsHullMin;
m_vObsHullMax = vObsHullMax;
m_vDeadViewHeight = vDeadViewHeight;
}
Vector m_vView;
Vector m_vHullMin;
Vector m_vHullMax;
Vector m_vDuckHullMin;
Vector m_vDuckHullMax;
Vector m_vDuckView;
Vector m_vObsHullMin;
Vector m_vObsHullMax;
Vector m_vDeadViewHeight;
};
#define VEC_VIEW g_pGameRules->GetViewVectors()->m_vView
#define VEC_HULL_MIN g_pGameRules->GetViewVectors()->m_vHullMin
#define VEC_HULL_MAX g_pGameRules->GetViewVectors()->m_vHullMax
#define VEC_DUCK_HULL_MIN g_pGameRules->GetViewVectors()->m_vDuckHullMin
#define VEC_DUCK_HULL_MAX g_pGameRules->GetViewVectors()->m_vDuckHullMax
#define VEC_DUCK_VIEW g_pGameRules->GetViewVectors()->m_vDuckView
#define VEC_OBS_HULL_MIN g_pGameRules->GetViewVectors()->m_vObsHullMin
#define VEC_OBS_HULL_MAX g_pGameRules->GetViewVectors()->m_vObsHullMax
#define VEC_DEAD_VIEWHEIGHT g_pGameRules->GetViewVectors()->m_vDeadViewHeight
#define WATERJUMP_HEIGHT 8
#define MAX_CLIMB_SPEED 200
#define TIME_TO_DUCK_MSECS 400
#define TIME_TO_UNDUCK_MSECS 200
inline float FractionDucked(int msecs)
{
return clamp((float)msecs / (float)TIME_TO_DUCK_MSECS, 0.0f, 1.0f);
}
inline float FractionUnDucked(int msecs)
{
return clamp((float)msecs / (float)TIME_TO_UNDUCK_MSECS, 0.0f, 1.0f);
}
#define MAX_WEAPON_SLOTS 6
#define MAX_WEAPON_POSITIONS 20
#define MAX_ITEM_TYPES 6
#define MAX_WEAPONS 48
#define MAX_ITEMS 5
#define WEAPON_NOCLIP -1
#define MAX_AMMO_TYPES 32
#define MAX_AMMO_SLOTS 32
#define HUD_PRINTNOTIFY 1
#define HUD_PRINTCONSOLE 2
#define HUD_PRINTTALK 3
#define HUD_PRINTCENTER 4
#define CLOSE_CAPTION_WARNIFMISSING ( 1<<0 )
#define CLOSE_CAPTION_FROMPLAYER ( 1<<1 )
#define CLOSE_CAPTION_GENDER_MALE ( 1<<2 )
#define CLOSE_CAPTION_GENDER_FEMALE ( 1<<3 )
#define HIDEHUD_WEAPONSELECTION ( 1<<0 )
#define HIDEHUD_FLASHLIGHT ( 1<<1 )
#define HIDEHUD_ALL ( 1<<2 )
#define HIDEHUD_HEALTH ( 1<<3 )
#define HIDEHUD_PLAYERDEAD ( 1<<4 )
#define HIDEHUD_NEEDSUIT ( 1<<5 )
#define HIDEHUD_MISCSTATUS ( 1<<6 )
#define HIDEHUD_CHAT ( 1<<7 )
#define HIDEHUD_CROSSHAIR ( 1<<8 )
#define HIDEHUD_VEHICLE_CROSSHAIR ( 1<<9 )
#define HIDEHUD_INVEHICLE ( 1<<10 )
#define HIDEHUD_BONUS_PROGRESS ( 1<<11 )
#define HIDEHUD_RADAR ( 1<<12 )
#define HIDEHUD_BITCOUNT 13
#define bits_SUIT_DEVICE_SPRINT 0x00000001
#define bits_SUIT_DEVICE_FLASHLIGHT 0x00000002
#define bits_SUIT_DEVICE_BREATHER 0x00000004
#define MAX_SUIT_DEVICES 3
#define MAX_PLAYERS 33
#define MAX_PLACE_NAME_LENGTH 18
#define TEAM_ANY -1
#define TEAM_INVALID -1
#define TEAM_UNASSIGNED 0
#define TEAM_SPECTATOR 1
#define LAST_SHARED_TEAM TEAM_SPECTATOR
#define FIRST_GAME_TEAM (LAST_SHARED_TEAM+1)
#define MAX_TEAMS 32
#define MAX_TEAM_NAME_LENGTH 32
#define WEAPON_NOT_CARRIED 0
#define WEAPON_IS_CARRIED_BY_PLAYER 1
#define WEAPON_IS_ACTIVE 2
#define SKILL_EASY 1
#define SKILL_MEDIUM 2
#define SKILL_HARD 3
#define ITEM_FLAG_SELECTONEMPTY (1<<0)
#define ITEM_FLAG_NOAUTORELOAD (1<<1)
#define ITEM_FLAG_NOAUTOSWITCHEMPTY (1<<2)
#define ITEM_FLAG_LIMITINWORLD (1<<3)
#define ITEM_FLAG_EXHAUSTIBLE (1<<4)
#define ITEM_FLAG_DOHITLOCATIONDMG (1<<5)
#define ITEM_FLAG_NOAMMOPICKUPS (1<<6)
#define ITEM_FLAG_NOITEMPICKUP (1<<7)
#define MAX_VIEWMODELS 2
#define MAX_BEAM_ENTS 10
#define TRACER_TYPE_DEFAULT 0x00000001
#define TRACER_TYPE_GUNSHIP 0x00000002
#define TRACER_TYPE_STRIDER 0x00000004
#define TRACER_TYPE_GAUSS 0x00000008
#define TRACER_TYPE_WATERBULLET 0x00000010
#define MUZZLEFLASH_TYPE_DEFAULT 0x00000001
#define MUZZLEFLASH_TYPE_GUNSHIP 0x00000002
#define MUZZLEFLASH_TYPE_STRIDER 0x00000004
enum
{
MUZZLEFLASH_AR2 = 0,
MUZZLEFLASH_SHOTGUN,
MUZZLEFLASH_SMG1,
MUZZLEFLASH_SMG2,
MUZZLEFLASH_PISTOL,
MUZZLEFLASH_COMBINE,
MUZZLEFLASH_357,
MUZZLEFLASH_RPG,
MUZZLEFLASH_COMBINE_TURRET,
MUZZLEFLASH_FIRSTPERSON = 0x100,
};
#define TRACER_FLAG_WHIZ 0x0001
#define TRACER_FLAG_USEATTACHMENT 0x0002
#define TRACER_DONT_USE_ATTACHMENT -1
enum
{
ENTITY_DISSOLVE_NORMAL = 0,
ENTITY_DISSOLVE_ELECTRICAL,
ENTITY_DISSOLVE_ELECTRICAL_LIGHT,
ENTITY_DISSOLVE_CORE,
ENTITY_DISSOLVE_BITS = 3
};
#define HITGROUP_GENERIC 0
#define HITGROUP_HEAD 1
#define HITGROUP_CHEST 2
#define HITGROUP_STOMACH 3
#define HITGROUP_LEFTARM 4
#define HITGROUP_RIGHTARM 5
#define HITGROUP_LEFTLEG 6
#define HITGROUP_RIGHTLEG 7
#define HITGROUP_GEAR 10
enum PLAYER_ANIM
{
PLAYER_IDLE,
PLAYER_WALK,
PLAYER_JUMP,
PLAYER_SUPERJUMP,
PLAYER_DIE,
PLAYER_ATTACK1,
PLAYER_IN_VEHICLE,
PLAYER_RELOAD,
PLAYER_START_AIMING,
PLAYER_LEAVE_AIMING,
};
#ifdef HL2_DLL
#define PLAYER_FATAL_FALL_SPEED 922.5f
#define PLAYER_MAX_SAFE_FALL_SPEED 526.5f
#define PLAYER_LAND_ON_FLOATING_OBJECT 173
#define PLAYER_MIN_BOUNCE_SPEED 173
#define PLAYER_FALL_PUNCH_THRESHOLD 303.0f
#else
#define PLAYER_FATAL_FALL_SPEED 1024
#define PLAYER_MAX_SAFE_FALL_SPEED 580
#define PLAYER_LAND_ON_FLOATING_OBJECT 200
#define PLAYER_MIN_BOUNCE_SPEED 200
#define PLAYER_FALL_PUNCH_THRESHOLD (float)350
#endif
#define DAMAGE_FOR_FALL_SPEED 100.0f / ( PLAYER_FATAL_FALL_SPEED - PLAYER_MAX_SAFE_FALL_SPEED )
#define AUTOAIM_2DEGREES 0.0348994967025
#define AUTOAIM_5DEGREES 0.08715574274766
#define AUTOAIM_8DEGREES 0.1391731009601
#define AUTOAIM_10DEGREES 0.1736481776669
#define AUTOAIM_20DEGREES 0.3490658503989
#define AUTOAIM_SCALE_DEFAULT 1.0f
#define AUTOAIM_SCALE_DIRECT_ONLY 0.0f
#define DMG_GENERIC 0
#define DMG_CRUSH (1 << 0)
#define DMG_BULLET (1 << 1)
#define DMG_SLASH (1 << 2)
#define DMG_BURN (1 << 3)
#define DMG_VEHICLE (1 << 4)
#define DMG_FALL (1 << 5)
#define DMG_BLAST (1 << 6)
#define DMG_CLUB (1 << 7)
#define DMG_SHOCK (1 << 8)
#define DMG_SONIC (1 << 9)
#define DMG_ENERGYBEAM (1 << 10)
#define DMG_PREVENT_PHYSICS_FORCE (1 << 11)
#define DMG_NEVERGIB (1 << 12)
#define DMG_ALWAYSGIB (1 << 13)
#define DMG_DROWN (1 << 14)
#define DMG_PARALYZE (1 << 15)
#define DMG_NERVEGAS (1 << 16)
#define DMG_POISON (1 << 17)
#define DMG_RADIATION (1 << 18)
#define DMG_DROWNRECOVER (1 << 19)
#define DMG_ACID (1 << 20)
#define DMG_SLOWBURN (1 << 21)
#define DMG_REMOVENORAGDOLL (1<<22)
#define DMG_PHYSGUN (1<<23)
#define DMG_PLASMA (1<<24)
#define DMG_AIRBOAT (1<<25)
#define DMG_DISSOLVE (1<<26)
#define DMG_BLAST_SURFACE (1<<27)
#define DMG_DIRECT (1<<28)
#define DMG_BUCKSHOT (1<<29)
#define DMG_LASTGENERICFLAG DMG_BUCKSHOT
#define DAMAGE_NO 0
#define DAMAGE_EVENTS_ONLY 1
#define DAMAGE_YES 2
#define DAMAGE_AIM 3
enum
{
OBS_MODE_NONE = 0,
OBS_MODE_DEATHCAM,
OBS_MODE_FREEZECAM,
OBS_MODE_FIXED,
OBS_MODE_IN_EYE,
OBS_MODE_CHASE,
OBS_MODE_ROAMING,
NUM_OBSERVER_MODES,
};
#define LAST_PLAYER_OBSERVERMODE OBS_MODE_ROAMING
enum {
OBS_ALLOW_ALL = 0,
OBS_ALLOW_TEAM,
OBS_ALLOW_NONE,
OBS_ALLOW_NUM_MODES,
};
enum
{
TYPE_TEXT = 0,
TYPE_INDEX,
TYPE_URL,
TYPE_FILE,
};
enum
{
VGUI_SCREEN_ACTIVE = 0x1,
VGUI_SCREEN_VISIBLE_TO_TEAMMATES = 0x2,
VGUI_SCREEN_ATTACHED_TO_VIEWMODEL = 0x4,
VGUI_SCREEN_TRANSPARENT = 0x8,
VGUI_SCREEN_ONLY_USABLE_BY_OWNER = 0x10,
VGUI_SCREEN_MAX_BITS = 5
};
typedef enum
{
USE_OFF = 0,
USE_ON = 1,
USE_SET = 2,
USE_TOGGLE = 3
} USE_TYPE;
#define COLOR_RED Color(255, 64, 64, 255)
#define COLOR_BLUE Color(153, 204, 255, 255)
#define COLOR_YELLOW Color(255, 178, 0, 255)
#define COLOR_GREEN Color(153, 255, 153, 255)
#define COLOR_GREY Color(204, 204, 204, 255)
enum
{
DONT_BLEED = -1,
BLOOD_COLOR_RED = 0,
BLOOD_COLOR_YELLOW,
BLOOD_COLOR_GREEN,
BLOOD_COLOR_MECH,
#if defined( HL2_EPISODIC )
BLOOD_COLOR_ANTLION,
BLOOD_COLOR_ZOMBIE,
BLOOD_COLOR_ANTLION_WORKER,
BLOOD_COLOR_BLOB,
BLOOD_COLOR_BLOB_FROZEN,
#endif
#if defined( INFESTED_DLL )
BLOOD_COLOR_BLOB,
BLOOD_COLOR_BLOB_FROZEN,
#endif
BLOOD_COLOR_BRIGHTGREEN,
};
enum PassengerRole_t
{
VEHICLE_ROLE_NONE = -1,
VEHICLE_ROLE_DRIVER = 0,
LAST_SHARED_VEHICLE_ROLE,
};
enum
{
FX_WATER_IN_SLIME = 0x1,
};
#define MAX_CONTEXT_LENGTH 32
#define NO_THINK_CONTEXT -1
enum
{
EFL_KILLME = (1 << 0),
EFL_DORMANT = (1 << 1),
EFL_NOCLIP_ACTIVE = (1 << 2),
EFL_SETTING_UP_BONES = (1 << 3),
EFL_KEEP_ON_RECREATE_ENTITIES = (1 << 4),
EFL_DIRTY_SHADOWUPDATE = (1 << 5),
EFL_NOTIFY = (1 << 6),
EFL_FORCE_CHECK_TRANSMIT = (1 << 7),
EFL_BOT_FROZEN = (1 << 8),
EFL_SERVER_ONLY = (1 << 9),
EFL_NO_AUTO_EDICT_ATTACH = (1 << 10),
EFL_DIRTY_ABSTRANSFORM = (1 << 11),
EFL_DIRTY_ABSVELOCITY = (1 << 12),
EFL_DIRTY_ABSANGVELOCITY = (1 << 13),
EFL_DIRTY_SURROUNDING_COLLISION_BOUNDS = (1 << 14),
EFL_DIRTY_SPATIAL_PARTITION = (1 << 15),
EFL_HAS_PLAYER_CHILD = (1 << 16),
EFL_IN_SKYBOX = (1 << 17),
EFL_USE_PARTITION_WHEN_NOT_SOLID = (1 << 18),
EFL_TOUCHING_FLUID = (1 << 19),
EFL_IS_BEING_LIFTED_BY_BARNACLE = (1 << 20),
EFL_NO_ROTORWASH_PUSH = (1 << 21),
EFL_NO_THINK_FUNCTION = (1 << 22),
EFL_NO_GAME_PHYSICS_SIMULATION = (1 << 23),
EFL_CHECK_UNTOUCH = (1 << 24),
EFL_DONTBLOCKLOS = (1 << 25),
EFL_DONTWALKON = (1 << 26),
EFL_NO_DISSOLVE = (1 << 27),
EFL_NO_MEGAPHYSCANNON_RAGDOLL = (1 << 28),
EFL_NO_WATER_VELOCITY_CHANGE = (1 << 29),
EFL_NO_PHYSCANNON_INTERACTION = (1 << 30),
EFL_NO_DAMAGE_FORCES = (1 << 31),
};
const int FX_BLOODSPRAY_DROPS = 0x01;
const int FX_BLOODSPRAY_GORE = 0x02;
const int FX_BLOODSPRAY_CLOUD = 0x04;
const int FX_BLOODSPRAY_ALL = 0xFF;
#define MAX_SCREEN_OVERLAYS 10
enum
{
GROUNDLINK = 0,
TOUCHLINK,
STEPSIMULATION,
MODELSCALE,
POSITIONWATCHER,
PHYSICSPUSHLIST,
VPHYSICSUPDATEAI,
VPHYSICSWATCHER,
NUM_DATAOBJECT_TYPES,
};
class CBaseEntity;
class CBaseEntity;
enum FireBulletsFlags_t
{
FIRE_BULLETS_FIRST_SHOT_ACCURATE = 0x1,
FIRE_BULLETS_DONT_HIT_UNDERWATER = 0x2,
FIRE_BULLETS_ALLOW_WATER_SURFACE_IMPACTS = 0x4,
FIRE_BULLETS_TEMPORARY_DANGER_SOUND = 0x8,
FIRE_BULLETS_NO_PIERCING_SPARK = 0x16,
FIRE_BULLETS_HULL = 0x32,
FIRE_BULLETS_ANGULAR_SPREAD = 0x64,
};
struct FireBulletsInfo_t
{
FireBulletsInfo_t()
{
m_iShots = 1;
m_vecSpread.Init(0, 0, 0);
m_flDistance = 8192;
m_iTracerFreq = 4;
m_flDamage = 0.0f;
m_flPlayerDamage = 0.0f;
m_pAttacker = NULL;
m_nFlags = 0;
m_pAdditionalIgnoreEnt = NULL;
m_flDamageForceScale = 1.0f;
#ifdef _DEBUG
m_iAmmoType = -1;
m_vecSrc.Init(VEC_T_NAN, VEC_T_NAN, VEC_T_NAN);
m_vecDirShooting.Init(VEC_T_NAN, VEC_T_NAN, VEC_T_NAN);
#endif
m_bPrimaryAttack = true;
}
FireBulletsInfo_t(int nShots, const Vector& vecSrc, const Vector& vecDir, const Vector& vecSpread, float flDistance, int nAmmoType, bool bPrimaryAttack = true)
{
m_iShots = nShots;
m_vecSrc = vecSrc;
m_vecDirShooting = vecDir;
m_vecSpread = vecSpread;
m_flDistance = flDistance;
m_iAmmoType = nAmmoType;
m_iTracerFreq = 4;
m_flDamage = 0;
m_flPlayerDamage = 0;
m_pAttacker = NULL;
m_nFlags = 0;
m_pAdditionalIgnoreEnt = NULL;
m_flDamageForceScale = 1.0f;
m_bPrimaryAttack = bPrimaryAttack;
}
int m_iShots;
Vector m_vecSrc;
Vector m_vecDirShooting;
Vector m_vecSpread;
float m_flDistance;
int m_iAmmoType;
int m_iTracerFreq;
float m_flDamage;
float m_flPlayerDamage;
int m_nFlags;
float m_flDamageForceScale;
CBaseEntity* m_pAttacker;
CBaseEntity* m_pAdditionalIgnoreEnt;
bool m_bPrimaryAttack;
};
struct StepSimulationStep
{
int nTickCount;
Vector vecOrigin;
Quaternion qRotation;
};
struct StepSimulationData
{
bool m_bOriginActive;
bool m_bAnglesActive;
StepSimulationStep m_Previous2;
StepSimulationStep m_Previous;
StepSimulationStep m_Discontinuity;
StepSimulationStep m_Next;
QAngle m_angNextRotation;
int m_nLastProcessTickCount;
Vector m_vecNetworkOrigin;
int m_networkCell[3];
QAngle m_angNetworkAngles;
};
struct ModelScale
{
float m_flModelScaleStart;
float m_flModelScaleGoal;
float m_flModelScaleFinishTime;
float m_flModelScaleStartTime;
};
#include "soundflags.h"
struct CSoundParameters;
typedef short HSOUNDSCRIPTHANDLE;
struct EmitSound_t
{
EmitSound_t() :
m_nChannel(0),
m_pSoundName(0),
m_flVolume(VOL_NORM),
m_SoundLevel(SNDLVL_NONE),
m_nFlags(0),
m_nPitch(PITCH_NORM),
m_pOrigin(0),
m_flSoundTime(0.0f),
m_pflSoundDuration(0),
m_bEmitCloseCaption(true),
m_bWarnOnMissingCloseCaption(false),
m_bWarnOnDirectWaveReference(false),
m_nSpeakerEntity(-1),
m_UtlVecSoundOrigin(),
m_hSoundScriptHandle(-1)
{
}
EmitSound_t(const CSoundParameters& src);
int m_nChannel;
char const* m_pSoundName;
float m_flVolume;
soundlevel_t m_SoundLevel;
int m_nFlags;
int m_nPitch;
const Vector* m_pOrigin;
float m_flSoundTime;
float* m_pflSoundDuration;
bool m_bEmitCloseCaption;
bool m_bWarnOnMissingCloseCaption;
bool m_bWarnOnDirectWaveReference;
int m_nSpeakerEntity;
mutable CUtlVector< Vector > m_UtlVecSoundOrigin;
mutable HSOUNDSCRIPTHANDLE m_hSoundScriptHandle;
};
#define MAX_ACTORS_IN_SCENE 16
#define MAX_CONTROL_POINTS 8
#define MAX_CONTROL_POINT_GROUPS 8
#define MAX_PREVIOUS_POINTS 3
#define MAX_CONTROL_POINT_TEAMS 8
#define MAX_CAPLAYOUT_LENGTH 32
#define MAX_ROUND_NAME 32
#define MAX_ROUND_IMAGE_NAME 64
#define TEAMPLAY_ROUND_WIN_SCORE 1
enum
{
CP_WARN_NORMAL = 0,
CP_WARN_FINALCAP,
CP_WARN_NO_ANNOUNCEMENTS
};
#define PREDICTION_ERROR_CHECK_LEVEL 0
#define PREDICTION_ERROR_CHECK_STACKS_FOR_MISSING 0
enum
{
RT_STATE_SETUP,
RT_STATE_NORMAL,
};
enum
{
SIMULATION_TIME_WINDOW_BITS = 8,
};
#define CELL_COUNT( bits ) ( (MAX_COORD_INTEGER*2) / (1 << (bits)) )
#define CELL_COUNT_BITS( bits ) MINIMUM_BITS_NEEDED( CELL_COUNT( bits ) )
#define CELL_BASEENTITY_ORIGIN_CELL_BITS 5
#ifdef GAME_HAS_NO_USE_KEY
#define COMMENTARY_BUTTONS (IN_ATTACK | IN_ATTACK2 | IN_USE)
#else
#define COMMENTARY_BUTTONS (IN_USE)
#endif
bool IsHeadTrackingEnabled();
#define MAX_SPLITSCREEN_PLAYERS 1
inline bool IsSplitScreenSupported()
{
return (MAX_SPLITSCREEN_PLAYERS > 1) ? true : false;
}
enum InvalidatePhysicsBits_t
{
POSITION_CHANGED = 0x1,
ANGLES_CHANGED = 0x2,
VELOCITY_CHANGED = 0x4,
ANIMATION_CHANGED = 0x8,
BOUNDS_CHANGED = 0x10,
SEQUENCE_CHANGED = 0x20,
};
enum Class_T
{
CLASS_NONE = 0,
CLASS_PLAYER,
CLASS_PLAYER_ALLY,
CLASS_PLAYER_ALLY_VITAL,
CLASS_ANTLION,
CLASS_BARNACLE,
CLASS_BLOB,
CLASS_BULLSEYE,
CLASS_CITIZEN_PASSIVE,
CLASS_CITIZEN_REBEL,
CLASS_COMBINE,
CLASS_COMBINE_GUNSHIP,
CLASS_CONSCRIPT,
CLASS_HEADCRAB,
CLASS_MANHACK,
CLASS_METROPOLICE,
CLASS_MILITARY,
CLASS_SCANNER,
CLASS_STALKER,
CLASS_VORTIGAUNT,
CLASS_ZOMBIE,
CLASS_PROTOSNIPER,
CLASS_MISSILE,
CLASS_FLARE,
CLASS_EARTH_FAUNA,
CLASS_HACKED_ROLLERMINE,
CLASS_COMBINE_HUNTER,
LAST_SHARED_ENTITY_CLASS,
};
#define FACTION_NONE 0
#define LAST_SHARED_FACTION (FACTION_NONE)
#define NUM_SHARED_FACTIONS (FACTION_NONE + 1)
#endif