mmsplugin.cpp 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. /**
  2. * vim: set ts=4 sw=4 tw=99 noet :
  3. * ======================================================
  4. * TF2 Dynamic Schema Injector
  5. * Written by nosoop
  6. * ======================================================
  7. */
  8. #include <stdio.h>
  9. #include "mmsplugin.h"
  10. #include <utlmap.h>
  11. #include <utlstring.h>
  12. #include <KeyValues.h>
  13. #include <filesystem.h>
  14. #include "memscan.h"
  15. SH_DECL_HOOK3_void(IServerGameDLL, ServerActivate, SH_NOATTRIB, 0, edict_t *, int, int);
  16. SH_DECL_HOOK6(IServerGameDLL, LevelInit, SH_NOATTRIB, 0, bool, char const *, char const *, char const *, char const *, bool, bool);
  17. DynSchema g_Plugin;
  18. IServerGameDLL *server = nullptr;
  19. IVEngineServer *engine = NULL;
  20. IBaseFileSystem *basefilesystem = nullptr;
  21. PLUGIN_EXPOSE(DynSchema, g_Plugin);
  22. class ISchemaAttributeType;
  23. // this may need to be updated in the future
  24. class CEconItemAttributeDefinition
  25. {
  26. public:
  27. // TODO implementing ~CEconItemAttributeDefinition segfaults. not sure what's up.
  28. // ideally we implement it to match the game so InsertOrReplace is sure to work correctly
  29. /* 0x00 */ KeyValues *m_KeyValues;
  30. /* 0x04 */ unsigned short m_iIndex;
  31. /* 0x08 */ ISchemaAttributeType *m_AttributeType;
  32. /* 0x0c */ bool m_bHidden;
  33. /* 0x0d */ bool m_bForceOutputDescription;
  34. /* 0x0e */ bool m_bStoreAsInteger;
  35. /* 0x0f */ bool m_bInstanceData;
  36. /* 0x10 */ int m_iAssetClassExportType;
  37. /* 0x14 */ int m_iAssetClassBucket;
  38. /* 0x18 */ bool m_bIsSetBonus;
  39. /* 0x1c */ int m_iIsUserGenerated;
  40. /* 0x20 */ int m_iEffectType;
  41. /* 0x24 */ int m_iDescriptionFormat;
  42. /* 0x28 */ char *m_pszDescriptionString;
  43. /* 0x2c */ char *m_pszArmoryDesc;
  44. /* 0x30 */ char *m_pszName;
  45. /* 0x34 */ char *m_pszAttributeClass;
  46. /* 0x38 */ bool m_bCanAffectMarketName;
  47. /* 0x39 */ bool m_bCanAffectRecipeCompName;
  48. /* 0x3c */ int m_nTagHandle;
  49. /* 0x40 */ string_t m_iszAttributeClass;
  50. };
  51. // binary refers to 0x58 when iterating over the attribute map, so we'll refer to that value
  52. // we could also do a runtime assertion
  53. static_assert(sizeof(CEconItemAttributeDefinition) + 0x14 == 0x58, "CEconItemAttributeDefinition size mismatch");
  54. // pointer to item schema attribute map singleton
  55. using AttributeMap = CUtlMap<int, CEconItemAttributeDefinition, int>;
  56. AttributeMap *g_SchemaAttributes;
  57. using GetEconItemSchemaFn_t = uintptr_t();
  58. GetEconItemSchemaFn_t *fnGetEconItemSchema = nullptr;
  59. // https://www.unknowncheats.me/wiki/Calling_Functions_From_Injected_Library_Using_Function_Pointers_in_C%2B%2B
  60. #ifdef WIN32
  61. typedef bool (__thiscall *CEconItemAttributeInitFromKV_fn)(CEconItemAttributeDefinition* pThis, KeyValues* pAttributeKeys, CUtlVector<CUtlString>* pErrors);
  62. #elif defined(_LINUX)
  63. typedef bool (__cdecl *CEconItemAttributeInitFromKV_fn)(CEconItemAttributeDefinition* pThis, KeyValues* pAttributeKeys, CUtlVector<CUtlString>* pErrors);
  64. #endif
  65. CEconItemAttributeInitFromKV_fn fnItemAttributeInitFromKV = nullptr;
  66. bool DynSchema::Load(PluginId id, ISmmAPI *ismm, char *error, size_t maxlen, bool late)
  67. {
  68. PLUGIN_SAVEVARS();
  69. GET_V_IFACE_CURRENT(GetEngineFactory, engine, IVEngineServer, INTERFACEVERSION_VENGINESERVER);
  70. GET_V_IFACE_ANY(GetServerFactory, server, IServerGameDLL, INTERFACEVERSION_SERVERGAMEDLL);
  71. GET_V_IFACE_CURRENT(GetFileSystemFactory, basefilesystem, IBaseFileSystem, BASEFILESYSTEM_INTERFACE_VERSION);
  72. SH_ADD_HOOK_MEMFUNC(IServerGameDLL, LevelInit, server, this, &DynSchema::Hook_LevelInitPost, true);
  73. // get the base address of the server
  74. #if _WINDOWS
  75. CWinLibInfo lib(server);
  76. lib.LocatePattern("\xE8\x2A\x2A\x2A\x2A\x83\xC0\x04\xC3", 9, (void**) &fnGetEconItemSchema);
  77. lib.LocatePattern("\x55\x8B\xEC\x53\x8B\x5D\x08\x56\x8B\xF1\x8B\xCB\x57\xE8\x2A\x2A\x2A\x2A", 18, (void**) &fnItemAttributeInitFromKV);
  78. #elif _LINUX
  79. CLinuxLibInfo lib(server);
  80. lib.LocateSymbol("_ZN28CEconItemAttributeDefinition11BInitFromKVEP9KeyValuesP10CUtlVectorI10CUtlString10CUtlMemoryIS3_iEE",
  81. (void**) &fnItemAttributeInitFromKV);
  82. lib.LocateSymbol("_Z15GEconItemSchemav", (void**) &fnGetEconItemSchema);
  83. #endif
  84. if (!fnItemAttributeInitFromKV || !fnGetEconItemSchema) {
  85. META_CONPRINTF("Failed to get GEIS or BIFKV\n");
  86. return false;
  87. }
  88. // is this late enough in the MM:S load stage? we might just have to hold the function
  89. g_SchemaAttributes = reinterpret_cast<AttributeMap*>(fnGetEconItemSchema() + 0x1BC);
  90. return true;
  91. }
  92. bool DynSchema::Unload(char *error, size_t maxlen) {
  93. SH_REMOVE_HOOK_MEMFUNC(IServerGameDLL, LevelInit, server, this, &DynSchema::Hook_LevelInitPost, true);
  94. return true;
  95. }
  96. /**
  97. * Initializes a CEconItemAttributeDefinition from a KeyValues definition, then inserts or
  98. * replaces the appropriate entry in the schema.
  99. */
  100. bool InsertOrReplaceAttribute(KeyValues *pAttribKV) {
  101. int attrdef = atoi(pAttribKV->GetName());
  102. if (attrdef <= 0) {
  103. return false;
  104. }
  105. // TODO only replace injected attribute if it exists
  106. // embed additional custom data into attribute KV; econdata and the like can deal with this
  107. // one could also add this data into the file itself, but this leaves less room for error
  108. pAttribKV->SetBool("injected", true);
  109. CEconItemAttributeDefinition def;
  110. fnItemAttributeInitFromKV(&def, pAttribKV, nullptr);
  111. // TODO verify that this doesn't leak, or just shrug it off
  112. g_SchemaAttributes->InsertOrReplace(attrdef, def);
  113. return true;
  114. }
  115. bool DynSchema::Hook_LevelInitPost(const char *pMapName, char const *pMapEntities,
  116. char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background) {
  117. // this hook should fire shortly after the schema is (re)initialized
  118. char game_path[256];
  119. engine->GetGameDir(game_path, sizeof(game_path));
  120. char buffer[1024];
  121. g_SMAPI->PathFormat(buffer, sizeof(buffer), "%s/%s",
  122. game_path, "addons/dynattrs/items_dynamic.txt");
  123. // always initialize attributes -- it's better than losing attributes on schema reinit
  124. KeyValues::AutoDelete pItemKV("DynamicSchema");
  125. if (pItemKV->LoadFromFile(basefilesystem, buffer)) {
  126. // TODO check for devattribs folder and import KVs from there, then do a final pass
  127. KeyValues *pKVAttributes = pItemKV->FindKey( "attributes" );
  128. if (pKVAttributes) {
  129. FOR_EACH_TRUE_SUBKEY(pKVAttributes, pKVAttribute) {
  130. InsertOrReplaceAttribute(pKVAttribute);
  131. }
  132. }
  133. META_CONPRINTF("Successfully injected custom schema %s\n", buffer);
  134. } else {
  135. META_CONPRINTF("Failed to inject custom schema %s\n", buffer);
  136. }
  137. return true;
  138. }
  139. void DynSchema::AllPluginsLoaded() {
  140. /* This is where we'd do stuff that relies on the mod or other plugins
  141. * being initialized (for example, cvars added and events registered).
  142. */
  143. }
  144. bool DynSchema::Pause(char *error, size_t maxlen) {
  145. return true;
  146. }
  147. bool DynSchema::Unpause(char *error, size_t maxlen) {
  148. return true;
  149. }
  150. const char *DynSchema::GetLicense() {
  151. return "Proprietary";
  152. }
  153. const char *DynSchema::GetVersion() {
  154. return "1.1.0";
  155. }
  156. const char *DynSchema::GetDate() {
  157. return __DATE__;
  158. }
  159. const char *DynSchema::GetLogTag() {
  160. return "dynschema";
  161. }
  162. const char *DynSchema::GetAuthor() {
  163. return "nosoop";
  164. }
  165. const char *DynSchema::GetDescription() {
  166. return "Injects user-defined content into the game schema";
  167. }
  168. const char *DynSchema::GetName() {
  169. return "TF2 Dynamic Schema";
  170. }
  171. const char *DynSchema::GetURL() {
  172. return "https://git.csrd.science/";
  173. }