2
0
mirror of https://github.com/rehlds/metamod-r.git synced 2025-01-15 16:17:58 +03:00

Refactoring

This commit is contained in:
s1lentq 2016-07-26 23:31:47 +07:00
parent 05067b28b5
commit 2e4a5b7c9e
58 changed files with 4059 additions and 6375 deletions

View File

@ -39,7 +39,7 @@ void setupToolchain(NativeBinarySpec b)
{ {
ToolchainConfig cfg = rootProject.createToolchainConfig(b) ToolchainConfig cfg = rootProject.createToolchainConfig(b)
cfg.projectInclude(project, '', '/src', '/include/common', '/include/dlls', '/include/engine', '/include/game_shared', '/include/pm_shared', '/include/public') cfg.projectInclude(project, '', '/src', '/include/common', '/include/dlls', '/include/engine', '/include/game_shared', '/include/pm_shared', '/include/public')
cfg.singleDefines '__METAMOD_BUILD__', '__BUILD_FAST_METAMOD__'; cfg.singleDefines 'METAMOD_CORE';
if (cfg instanceof MsvcToolchainConfig) { if (cfg instanceof MsvcToolchainConfig) {
cfg.compilerOptions.pchConfig = new MsvcToolchainConfig.PrecompiledHeadersConfig( cfg.compilerOptions.pchConfig = new MsvcToolchainConfig.PrecompiledHeadersConfig(
@ -59,8 +59,12 @@ void setupToolchain(NativeBinarySpec b)
'_strnicmp': 'strncasecmp', '_strnicmp': 'strncasecmp',
'_strdup': 'strdup', '_strdup': 'strdup',
'_unlink': 'unlink', '_unlink': 'unlink',
'_write' : 'write',
'_close' : 'close',
'_getcwd' : 'getcwd',
'_vsnprintf': 'vsnprintf', '_vsnprintf': 'vsnprintf',
'_vsnwprintf': 'vswprintf', '_vsnwprintf': 'vswprintf',
'_snprintf': 'snprintf'
]) ])
cfg.compilerOptions.args '-Qoption,cpp,--treat_func_as_string_literal_cpp', '-msse2', '-fomit-frame-pointer', '-inline-forceinline', '-fvisibility=default', '-fvisibility-inlines-hidden', '-fno-rtti', '-g0', '-s' cfg.compilerOptions.args '-Qoption,cpp,--treat_func_as_string_literal_cpp', '-msse2', '-fomit-frame-pointer', '-inline-forceinline', '-fvisibility=default', '-fvisibility-inlines-hidden', '-fno-rtti', '-g0', '-s'
@ -114,12 +118,6 @@ model {
srcDir "version" srcDir "version"
include "**/*.cpp" include "**/*.cpp"
if (GradleCppUtils.windows) {
exclude "osdep_linkent_linux.cpp"
} else {
exclude "osdep_linkent_win32.cpp"
}
exclude "precompiled.cpp" exclude "precompiled.cpp"
} }

View File

@ -44,6 +44,12 @@
<CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" /> <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
<CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" /> <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<TargetName>$(ProjectName)_mm</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<TargetName>$(ProjectName)_mm</TargetName>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile> <ClCompile>
<Optimization>Disabled</Optimization> <Optimization>Disabled</Optimization>
@ -51,9 +57,9 @@
<PreprocessorDefinitions>METAMOD_CORE;WIN32;_DEBUG;_WINDOWS;_USRDLL;METAMOD_EXPORTS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>METAMOD_CORE;WIN32;_DEBUG;_WINDOWS;_USRDLL;METAMOD_EXPORTS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary> <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<PrecompiledHeader>Use</PrecompiledHeader> <PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderOutputFile>.\debug/metamod.pch</PrecompiledHeaderOutputFile> <PrecompiledHeaderOutputFile>$(IntDir)$(TargetName).pch</PrecompiledHeaderOutputFile>
<AssemblerListingLocation>.\debug/asm/</AssemblerListingLocation> <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>
<ObjectFileName>.\debug/obj/</ObjectFileName> <ObjectFileName>$(IntDir)</ObjectFileName>
<ProgramDataBaseFileName>.\debug/inf/</ProgramDataBaseFileName> <ProgramDataBaseFileName>.\debug/inf/</ProgramDataBaseFileName>
<WarningLevel>Level3</WarningLevel> <WarningLevel>Level3</WarningLevel>
<TreatWarningAsError>true</TreatWarningAsError> <TreatWarningAsError>true</TreatWarningAsError>
@ -63,14 +69,15 @@
<PrecompiledHeaderFile>precompiled.h</PrecompiledHeaderFile> <PrecompiledHeaderFile>precompiled.h</PrecompiledHeaderFile>
</ClCompile> </ClCompile>
<Link> <Link>
<OutputFile>.\debug/metamod.dll</OutputFile> <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
<SuppressStartupBanner>true</SuppressStartupBanner> <SuppressStartupBanner>true</SuppressStartupBanner>
<ModuleDefinitionFile>.\metamod.def</ModuleDefinitionFile> <ModuleDefinitionFile>metamod.def</ModuleDefinitionFile>
<GenerateDebugInformation>true</GenerateDebugInformation> <GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>.\debug/inf/metamod.pdb</ProgramDatabaseFile> <ProgramDatabaseFile>$(OutDir)$(TargetName).pdb</ProgramDatabaseFile>
<ImportLibrary>.\debug/metamod.lib</ImportLibrary> <ImportLibrary>$(OutDir)$(TargetName).lib</ImportLibrary>
<TargetMachine>MachineX86</TargetMachine> <TargetMachine>MachineX86</TargetMachine>
<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers> <ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
</Link> </Link>
<Midl> <Midl>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
@ -85,6 +92,24 @@
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<Culture>0x0409</Culture> <Culture>0x0409</Culture>
</ResourceCompile> </ResourceCompile>
<PreBuildEvent>
<Command>IF EXIST "$(ProjectDir)PreBuild.bat" (CALL "$(ProjectDir)PreBuild.bat" "$(ProjectDir)..\version\" "$(ProjectDir)..\")</Command>
</PreBuildEvent>
<PreBuildEvent>
<Message>Setup version from Git revision</Message>
</PreBuildEvent>
<PostBuildEvent>
<Command>IF EXIST "$(ProjectDir)PostBuild.bat" (CALL "$(ProjectDir)PostBuild.bat" "$(TargetDir)" "$(TargetName)" "$(TargetExt)" "$(ProjectDir)")</Command>
</PostBuildEvent>
<PostBuildEvent>
<Message>Automatic deployment script</Message>
</PostBuildEvent>
<CustomBuildStep>
<Command>echo Empty Action</Command>
</CustomBuildStep>
<CustomBuildStep>
<Message>Force build to run Pre-Build event</Message>
</CustomBuildStep>
</ItemDefinitionGroup> </ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile> <ClCompile>
@ -96,9 +121,9 @@
<RuntimeLibrary>MultiThreaded</RuntimeLibrary> <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking> <FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeader>Use</PrecompiledHeader> <PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderOutputFile>.\release/metamod.pch</PrecompiledHeaderOutputFile> <PrecompiledHeaderOutputFile>$(IntDir)$(TargetName).pch</PrecompiledHeaderOutputFile>
<AssemblerListingLocation>.\release/</AssemblerListingLocation> <AssemblerListingLocation>$(IntDir)</AssemblerListingLocation>
<ObjectFileName>.\release/obj/</ObjectFileName> <ObjectFileName>$(IntDir)</ObjectFileName>
<ProgramDataBaseFileName>.\release/inf/</ProgramDataBaseFileName> <ProgramDataBaseFileName>.\release/inf/</ProgramDataBaseFileName>
<WarningLevel>Level3</WarningLevel> <WarningLevel>Level3</WarningLevel>
<TreatWarningAsError>true</TreatWarningAsError> <TreatWarningAsError>true</TreatWarningAsError>
@ -110,10 +135,11 @@
<OutputFile>.\release/metamod.dll</OutputFile> <OutputFile>.\release/metamod.dll</OutputFile>
<SuppressStartupBanner>true</SuppressStartupBanner> <SuppressStartupBanner>true</SuppressStartupBanner>
<ModuleDefinitionFile>.\metamod.def</ModuleDefinitionFile> <ModuleDefinitionFile>.\metamod.def</ModuleDefinitionFile>
<ProgramDatabaseFile>.\release/inf/metamod.pdb</ProgramDatabaseFile> <ProgramDatabaseFile>$(OutDir)$(TargetName).pdb</ProgramDatabaseFile>
<ImportLibrary>.\release/metamod.lib</ImportLibrary> <ImportLibrary>$(OutDir)$(TargetName).lib</ImportLibrary>
<TargetMachine>MachineX86</TargetMachine> <TargetMachine>MachineX86</TargetMachine>
<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers> <ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
</Link> </Link>
<Midl> <Midl>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
@ -128,6 +154,24 @@
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<Culture>0x0409</Culture> <Culture>0x0409</Culture>
</ResourceCompile> </ResourceCompile>
<PreBuildEvent>
<Command>IF EXIST "$(ProjectDir)PreBuild.bat" (CALL "$(ProjectDir)PreBuild.bat" "$(ProjectDir)..\version\" "$(ProjectDir)..\")</Command>
</PreBuildEvent>
<PreBuildEvent>
<Message>Setup version from Git revision</Message>
</PreBuildEvent>
<PostBuildEvent>
<Command>IF EXIST "$(ProjectDir)PostBuild.bat" (CALL "$(ProjectDir)PostBuild.bat" "$(TargetDir)" "$(TargetName)" "$(TargetExt)" "$(ProjectDir)")</Command>
</PostBuildEvent>
<PostBuildEvent>
<Message>Automatic deployment script</Message>
</PostBuildEvent>
<CustomBuildStep>
<Command>echo Empty Action</Command>
</CustomBuildStep>
<CustomBuildStep>
<Message>Force build to run Pre-Build event</Message>
</CustomBuildStep>
</ItemDefinitionGroup> </ItemDefinitionGroup>
<ItemGroup> <ItemGroup>
<ClCompile Include="..\src\api_info.cpp" /> <ClCompile Include="..\src\api_info.cpp" />
@ -157,7 +201,6 @@
<ClCompile Include="..\src\studioapi.cpp" /> <ClCompile Include="..\src\studioapi.cpp" />
<ClCompile Include="..\src\support_meta.cpp" /> <ClCompile Include="..\src\support_meta.cpp" />
<ClCompile Include="..\src\utils.cpp" /> <ClCompile Include="..\src\utils.cpp" />
<ClCompile Include="..\src\vdate.cpp" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClInclude Include="..\src\api_info.h" /> <ClInclude Include="..\src\api_info.h" />
@ -191,8 +234,12 @@
<ClInclude Include="..\src\support_meta.h" /> <ClInclude Include="..\src\support_meta.h" />
<ClInclude Include="..\src\types_meta.h" /> <ClInclude Include="..\src\types_meta.h" />
<ClInclude Include="..\src\utils.h" /> <ClInclude Include="..\src\utils.h" />
<ClInclude Include="..\src\vdate.h" /> </ItemGroup>
<ClInclude Include="..\src\vers_meta.h" /> <ItemGroup>
<None Include="metamod.def" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="metamod.rc" />
</ItemGroup> </ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets"> <ImportGroup Label="ExtensionTargets">

View File

@ -83,9 +83,6 @@
<ClCompile Include="..\src\utils.cpp"> <ClCompile Include="..\src\utils.cpp">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="..\src\vdate.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClInclude Include="..\src\api_info.h"> <ClInclude Include="..\src\api_info.h">
@ -181,11 +178,15 @@
<ClInclude Include="..\src\utils.h"> <ClInclude Include="..\src\utils.h">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="..\src\vdate.h"> </ItemGroup>
<Filter>Source Files</Filter> <ItemGroup>
</ClInclude> <None Include="metamod.def">
<ClInclude Include="..\src\vers_meta.h"> <Filter>Resource Files</Filter>
<Filter>Source Files</Filter> </None>
</ClInclude> </ItemGroup>
<ItemGroup>
<ResourceCompile Include="metamod.rc">
<Filter>Resource Files</Filter>
</ResourceCompile>
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -1,39 +1,3 @@
// vi: set ts=4 sw=4 :
// vim: set tw=75 :
// api_info.cpp - info for api routines
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#include "precompiled.h" #include "precompiled.h"
// trace flag, loglevel, name // trace flag, loglevel, name
@ -88,18 +52,18 @@ dllapi_info_t dllapi_info = {
{ mFALSE, 9, "CreateInstancedBaselines" }, // pfnCreateInstancedBaselines { mFALSE, 9, "CreateInstancedBaselines" }, // pfnCreateInstancedBaselines
{ mFALSE, 3, "InconsistentFile" }, // pfnInconsistentFile { mFALSE, 3, "InconsistentFile" }, // pfnInconsistentFile
{ mFALSE, 20, "AllowLagCompensation" }, // pfnAllowLagCompensation { mFALSE, 20, "AllowLagCompensation" }, // pfnAllowLagCompensation
{ mFALSE, 0, NULL },
{ mFALSE, 0, nullptr },
}; };
newapi_info_t newapi_info = { newapi_info_t newapi_info = {
{ mFALSE, 16, "OnFreeEntPrivateData" }, // pfnOnFreeEntPrivateData { mFALSE, 16, "OnFreeEntPrivateData" }, // pfnOnFreeEntPrivateData
{ mFALSE, 3, "GameShutdown" }, // pfnGameShutdown { mFALSE, 3, "GameShutdown" }, // pfnGameShutdown
{ mFALSE, 14, "ShouldCollide" }, // pfnShouldCollide { mFALSE, 14, "ShouldCollide" }, // pfnShouldCollide
// Added 2005-08-11 (no SDK update)
{ mFALSE, 3, "CvarValue" }, // pfnCvarValue { mFALSE, 3, "CvarValue" }, // pfnCvarValue
// Added 2005-11-22 (no SDK update)
{ mFALSE, 3, "CvarValue2" }, // pfnCvarValue2 { mFALSE, 3, "CvarValue2" }, // pfnCvarValue2
{ mFALSE, 0, NULL },
{ mFALSE, 0, nullptr },
}; };
engine_info_t engine_info = { engine_info_t engine_info = {
@ -244,13 +208,12 @@ engine_info_t engine_info = {
{ mFALSE, 9, "ForceUnmodified" }, // pfnForceUnmodified { mFALSE, 9, "ForceUnmodified" }, // pfnForceUnmodified
{ mFALSE, 9, "GetPlayerStats" }, // pfnGetPlayerStats { mFALSE, 9, "GetPlayerStats" }, // pfnGetPlayerStats
{ mFALSE, 3, "AddServerCommand" }, // pfnAddServerCommand { mFALSE, 3, "AddServerCommand" }, // pfnAddServerCommand
// Added in SDK 2.2:
{ mFALSE, 9, "Voice_GetClientListening" }, // Voice_GetClientListening { mFALSE, 9, "Voice_GetClientListening" }, // Voice_GetClientListening
{ mFALSE, 9, "Voice_SetClientListening" }, // Voice_SetClientListening { mFALSE, 9, "Voice_SetClientListening" }, // Voice_SetClientListening
// Added for HL 1109 (no SDK update):
{ mFALSE, 9, "GetPlayerAuthId" }, // pfnGetPlayerAuthId { mFALSE, 9, "GetPlayerAuthId" }, // pfnGetPlayerAuthId
// Added 2003-11-10 (no SDK update):
{ mFALSE, 30, "SequenceGet" }, // pfnSequenceGet { mFALSE, 30, "SequenceGet" }, // pfnSequenceGet
{ mFALSE, 30, "SequencePickSentence" }, // pfnSequencePickSentence { mFALSE, 30, "SequencePickSentence" }, // pfnSequencePickSentence
{ mFALSE, 30, "GetFileSize" }, // pfnGetFileSize { mFALSE, 30, "GetFileSize" }, // pfnGetFileSize
{ mFALSE, 30, "GetApproxWavePlayLen" }, // pfnGetApproxWavePlayLen { mFALSE, 30, "GetApproxWavePlayLen" }, // pfnGetApproxWavePlayLen
@ -261,12 +224,11 @@ engine_info_t engine_info = {
{ mFALSE, 30, "ProcessTutorMessageDecayBuffer" }, // pfnProcessTutorMessageDecayBuffer { mFALSE, 30, "ProcessTutorMessageDecayBuffer" }, // pfnProcessTutorMessageDecayBuffer
{ mFALSE, 30, "ConstructTutorMessageDecayBuffer" }, // pfnConstructTutorMessageDecayBuffer { mFALSE, 30, "ConstructTutorMessageDecayBuffer" }, // pfnConstructTutorMessageDecayBuffer
{ mFALSE, 9, "ResetTutorMessageDecayData" }, // pfnResetTutorMessageDecayData { mFALSE, 9, "ResetTutorMessageDecayData" }, // pfnResetTutorMessageDecayData
// Added 2005-08-11 (no SDK update)
{ mFALSE, 3, "QueryClientCvarValue" }, //pfnQueryClientCvarValue { mFALSE, 3, "QueryClientCvarValue" }, //pfnQueryClientCvarValue
// Added 2005-11-22 (no SDK update)
{ mFALSE, 3, "QueryClientCvarValue2" }, //pfnQueryClientCvarValue2 { mFALSE, 3, "QueryClientCvarValue2" }, //pfnQueryClientCvarValue2
// Added 2009-06-17 (no SDK update)
{ mFALSE, 8, "CheckParm" }, //pfnCheckParm { mFALSE, 8, "CheckParm" }, //pfnCheckParm
// end // end
{ mFALSE, 0, NULL }, { mFALSE, 0, NULL },
}; };

View File

@ -1,58 +1,20 @@
// vi: set ts=4 sw=4 : #pragma once
// vim: set tw=75 :
// api_info.h - structures to store info about api routines
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef API_INFO_H
#define API_INFO_H
#include "types_meta.h" // mBOOL
#include "types_meta.h"
#define P_PRE 0 // plugin function called before gamedll #define P_PRE 0 // plugin function called before gamedll
#define P_POST 1 // plugin function called after gamedll #define P_POST 1 // plugin function called after gamedll
struct api_info_t
typedef struct api_info_s { {
mBOOL trace; // if true, log info about this function mBOOL trace; // if true, log info about this function
int loglevel; // level at which to log info about this function int loglevel; // level at which to log info about this function
const char *name; // string representation of function name const char *name; // string representation of function name
} api_info_t; };
// DLL api functions // DLL api functions
typedef struct dllapi_info_s { struct dllapi_info_t
{
api_info_t pfnGameInit; api_info_t pfnGameInit;
api_info_t pfnSpawn; api_info_t pfnSpawn;
api_info_t pfnThink; api_info_t pfnThink;
@ -103,25 +65,27 @@ typedef struct dllapi_info_s {
api_info_t pfnCreateInstancedBaselines; api_info_t pfnCreateInstancedBaselines;
api_info_t pfnInconsistentFile; api_info_t pfnInconsistentFile;
api_info_t pfnAllowLagCompensation; api_info_t pfnAllowLagCompensation;
api_info_t END;
} dllapi_info_t;
// end
api_info_t END;
};
// "New" api functions // "New" api functions
typedef struct newapi_info_s { struct newapi_info_t
{
api_info_t pfnOnFreeEntPrivateData; api_info_t pfnOnFreeEntPrivateData;
api_info_t pfnGameShutdown; api_info_t pfnGameShutdown;
api_info_t pfnShouldCollide; api_info_t pfnShouldCollide;
// Added 2005/08/11 (no SDK update)
api_info_t pfnCvarValue; api_info_t pfnCvarValue;
// Added 2005/11/22 (no SDK update)
api_info_t pfnCvarValue2; api_info_t pfnCvarValue2;
api_info_t END;
} newapi_info_t;
// end
api_info_t END;
};
// g_engine functions // g_engine functions
typedef struct engine_info_s { struct engine_info_t
{
api_info_t pfnPrecacheModel; api_info_t pfnPrecacheModel;
api_info_t pfnPrecacheSound; api_info_t pfnPrecacheSound;
api_info_t pfnSetModel; api_info_t pfnSetModel;
@ -263,12 +227,9 @@ typedef struct engine_info_s {
api_info_t pfnForceUnmodified; api_info_t pfnForceUnmodified;
api_info_t pfnGetPlayerStats; api_info_t pfnGetPlayerStats;
api_info_t pfnAddServerCommand; api_info_t pfnAddServerCommand;
// Added in SDK 2.2:
api_info_t pfnVoice_GetClientListening; api_info_t pfnVoice_GetClientListening;
api_info_t pfnVoice_SetClientListening; api_info_t pfnVoice_SetClientListening;
// Added for HL 1109 (no SDK update):
api_info_t pfnGetPlayerAuthId; api_info_t pfnGetPlayerAuthId;
// Added 2003/11/10 (no SDK update):
api_info_t pfnSequenceGet; api_info_t pfnSequenceGet;
api_info_t pfnSequencePickSentence; api_info_t pfnSequencePickSentence;
api_info_t pfnGetFileSize; api_info_t pfnGetFileSize;
@ -280,19 +241,14 @@ typedef struct engine_info_s {
api_info_t pfnProcessTutorMessageDecayBuffer; api_info_t pfnProcessTutorMessageDecayBuffer;
api_info_t pfnConstructTutorMessageDecayBuffer; api_info_t pfnConstructTutorMessageDecayBuffer;
api_info_t pfnResetTutorMessageDecayData; api_info_t pfnResetTutorMessageDecayData;
// Added 2005/08/11 (no SDK update)
api_info_t pfnQueryClientCvarValue; api_info_t pfnQueryClientCvarValue;
// Added 2005/11/22 (no SDK update)
api_info_t pfnQueryClientCvarValue2; api_info_t pfnQueryClientCvarValue2;
// Added 2009/06/17 (no SDK update)
api_info_t pfnEngCheckParm; api_info_t pfnEngCheckParm;
// end // end
api_info_t END; api_info_t END;
} engine_info_t; };
extern dllapi_info_t dllapi_info; extern dllapi_info_t dllapi_info;
extern newapi_info_t newapi_info; extern newapi_info_t newapi_info;
extern engine_info_t engine_info; extern engine_info_t engine_info;
#endif /* API_INFO_H */

View File

@ -1,39 +1,3 @@
// vi: set ts=4 sw=4 :
// vim: set tw=75 :
// commands_meta.cpp - implementation of various console commands
/*
* Copyright (c) 2001-2004 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#include "precompiled.h" #include "precompiled.h"
struct metacmd_t struct metacmd_t
@ -52,6 +16,7 @@ metacmd_t g_meta_cmds[] =
{"cvars", cmd_meta_cvarlist}, {"cvars", cmd_meta_cvarlist},
{"game", cmd_meta_game}, {"game", cmd_meta_game},
{"config", cmd_meta_config}, {"config", cmd_meta_config},
// arguments: existing plugin(s) // arguments: existing plugin(s)
{"pause", []() { cmd_doplug(PC_PAUSE); }}, {"pause", []() { cmd_doplug(PC_PAUSE); }},
{"unpause", []() { cmd_doplug(PC_UNPAUSE); }}, {"unpause", []() { cmd_doplug(PC_UNPAUSE); }},
@ -62,6 +27,7 @@ metacmd_t g_meta_cmds[] =
{"clear", []() { cmd_doplug(PC_CLEAR); }}, {"clear", []() { cmd_doplug(PC_CLEAR); }},
{"info", []() { cmd_doplug(PC_INFO); }}, {"info", []() { cmd_doplug(PC_INFO); }},
{"require", []() { cmd_doplug(PC_REQUIRE); }}, {"require", []() { cmd_doplug(PC_REQUIRE); }},
// arguments: filename, description // arguments: filename, description
{"load", cmd_meta_load}, {"load", cmd_meta_load},
}; };
@ -75,12 +41,14 @@ void meta_register_cmdcvar()
} }
// Parse "meta" console command. // Parse "meta" console command.
void server_meta(void) void server_meta()
{ {
const char *cmd = CMD_ARGV(1); const char *cmd = CMD_ARGV(1);
for (auto& meta_cmd : g_meta_cmds) { for (auto& meta_cmd : g_meta_cmds)
if (!strcmp(cmd, meta_cmd.name)) { {
if (!Q_strcmp(cmd, meta_cmd.name))
{
meta_cmd.handler(); meta_cmd.handler();
return; return;
} }
@ -94,23 +62,24 @@ void server_meta(void)
void client_meta(edict_t* pEntity) void client_meta(edict_t* pEntity)
{ {
const char *cmd = CMD_ARGV(1); const char *cmd = CMD_ARGV(1);
META_LOG("ClientCommand 'meta %s' from player '%s'", CMD_ARGS(), STRING(pEntity->v.netname)); META_LOG("ClientCommand 'meta %s' from player '%s'", CMD_ARGS(), STRING(pEntity->v.netname));
// arguments: none // arguments: none
if (!strcmp(cmd, "version")) if (!Q_strcmp(cmd, "version"))
client_meta_version(pEntity); client_meta_version(pEntity);
else if (!strcmp(cmd, "list"))
else if (!Q_strcmp(cmd, "list"))
client_meta_pluginlist(pEntity); client_meta_pluginlist(pEntity);
// unrecognized else
else { {
META_CLIENT(pEntity, "Unrecognized meta command: %s", cmd); META_CLIENT(pEntity, "Unrecognized meta command: %s", cmd);
client_meta_usage(pEntity); client_meta_usage(pEntity);
return;
} }
} }
// Print usage for "meta" console command. // Print usage for "meta" console command.
void cmd_meta_usage(void) void cmd_meta_usage()
{ {
META_CONS("usage: meta <command> [<arguments>]"); META_CONS("usage: meta <command> [<arguments>]");
META_CONS("valid commands are:"); META_CONS("valid commands are:");
@ -143,37 +112,38 @@ void client_meta_usage(edict_t* pEntity)
} }
// "meta version" console command. // "meta version" console command.
void cmd_meta_version(void) void cmd_meta_version()
{
if (CMD_ARGC() != 2)
{ {
if (CMD_ARGC() != 2) {
META_CONS("usage: meta version"); META_CONS("usage: meta version");
return; return;
} }
META_CONS("%s v%s %s (%s)", VNAME, VVERSION, VDATE, META_INTERFACE_VERSION);
META_CONS("by %s", VAUTHOR); META_CONS("Metamod v%s, API (%s)", APP_VERSION_STRD, META_INTERFACE_VERSION);
META_CONS(" %s", VURL); META_CONS("Metamod build: " __TIME__ " " __DATE__ " (" APP_VERSION_STRD ")");
META_CONS("compiled: %s %s (%s)", COMPILE_TIME, COMPILE_TZONE, OPT_TYPE); META_CONS("Metamod from: " APP_COMMITS_URL APP_COMMIT_ID " " APP_COMMIT_AUTHOR "");
} }
// "meta version" client command. // "meta version" client command.
void client_meta_version(edict_t *pEntity) void client_meta_version(edict_t *pEntity)
{ {
if (CMD_ARGC() != 2) { if (CMD_ARGC() != 2)
{
META_CLIENT(pEntity, "usage: meta version"); META_CLIENT(pEntity, "usage: meta version");
return; return;
} }
META_CLIENT(pEntity, "%s v%s %s (%s)", VNAME, VVERSION, VDATE, META_INTERFACE_VERSION);
META_CLIENT(pEntity, "by %s", VAUTHOR); META_CONS("Metamod v%s, API (%s)", APP_VERSION_STRD, META_INTERFACE_VERSION);
META_CLIENT(pEntity, " %s", VURL); META_CONS("Metamod build: " __TIME__ " " __DATE__ " (" APP_VERSION_STRD ")");
META_CLIENT(pEntity, "compiled: %s %s (%s)", COMPILE_TIME, COMPILE_TZONE, OPT_TYPE); META_CONS("Metamod from: " APP_COMMITS_URL APP_COMMIT_ID " " APP_COMMIT_AUTHOR "");
META_CLIENT(pEntity, "ifvers: %s", META_INTERFACE_VERSION);
} }
// "meta gpl" console command. // "meta gpl" console command.
void cmd_meta_gpl(void) void cmd_meta_gpl()
{ {
META_CONS("%s version %s %s", VNAME, VVERSION, VDATE); META_CONS("Metamod version " __TIME__ " " __DATE__);
META_CONS("Copyright (c) 2001-%s Will Day <willday@hpgx.net>", COPYRIGHT_YEAR); META_CONS("Copyright (c) 2001-2016 Will Day (modification ReHLDS Team)");
META_CONS(""); META_CONS("");
META_CONS(" Metamod is free software; you can redistribute it and/or"); META_CONS(" Metamod is free software; you can redistribute it and/or");
META_CONS(" modify it under the terms of the GNU General Public License"); META_CONS(" modify it under the terms of the GNU General Public License");
@ -193,10 +163,10 @@ void cmd_meta_gpl(void)
META_CONS(" "); META_CONS(" ");
META_CONS(" In addition, as a special exception, the author gives"); META_CONS(" In addition, as a special exception, the author gives");
META_CONS(" permission to link the code of this program with the"); META_CONS(" permission to link the code of this program with the");
META_CONS(" Half-Life Game g_engine (\"HL g_engine\") and Modified Game"); META_CONS(" Half-Life Game Engine (\"HL Engine\") and Modified Game");
META_CONS(" Libraries (\"MODs\") developed by Valve, L.L.C (\"Valve\")."); META_CONS(" Libraries (\"MODs\") developed by Valve, L.L.C (\"Valve\").");
META_CONS(" You must obey the GNU General Public License in all"); META_CONS(" You must obey the GNU General Public License in all");
META_CONS(" respects for all of the code used other than the HL g_engine"); META_CONS(" respects for all of the code used other than the HL Engine");
META_CONS(" and MODs from Valve. If you modify this file, you may"); META_CONS(" and MODs from Valve. If you modify this file, you may");
META_CONS(" extend this exception to your version of the file, but you"); META_CONS(" extend this exception to your version of the file, but you");
META_CONS(" are not obligated to do so. If you do not wish to do so,"); META_CONS(" are not obligated to do so. If you do not wish to do so,");
@ -204,12 +174,14 @@ void cmd_meta_gpl(void)
} }
// "meta game" console command. // "meta game" console command.
void cmd_meta_game(void) void cmd_meta_game()
{
if (CMD_ARGC() != 2)
{ {
if (CMD_ARGC() != 2) {
META_CONS("usage: meta game"); META_CONS("usage: meta game");
return; return;
} }
META_CONS("GameDLL info:"); META_CONS("GameDLL info:");
META_CONS(" name: %s", GameDLL.name); META_CONS(" name: %s", GameDLL.name);
META_CONS(" desc: %s", GameDLL.desc); META_CONS(" desc: %s", GameDLL.desc);
@ -220,67 +192,78 @@ void cmd_meta_game(void)
} }
// "meta refresh" console command. // "meta refresh" console command.
void cmd_meta_refresh(void) void cmd_meta_refresh()
{
if (CMD_ARGC() != 2)
{ {
if (CMD_ARGC() != 2) {
META_CONS("usage: meta refresh"); META_CONS("usage: meta refresh");
return; return;
} }
META_LOG("Refreshing the plugins on demand..."); META_LOG("Refreshing the plugins on demand...");
if (g_plugins->refresh(PT_ANYTIME) != mTRUE)
if (g_plugins->refresh(PT_ANYTIME) != mTRUE) { {
META_LOG("Refresh failed."); META_LOG("Refresh failed.");
} }
} }
// "meta list" console command. // "meta list" console command.
void cmd_meta_pluginlist(void) void cmd_meta_pluginlist()
{
if (CMD_ARGC() != 2)
{ {
if (CMD_ARGC() != 2) {
META_CONS("usage: meta list"); META_CONS("usage: meta list");
return; return;
} }
g_plugins->show(0); g_plugins->show(0);
} }
// "meta list" client command. // "meta list" client command.
void client_meta_pluginlist(edict_t* pEntity) void client_meta_pluginlist(edict_t* pEntity)
{ {
if (CMD_ARGC() != 2) { if (CMD_ARGC() != 2)
{
META_CLIENT(pEntity, "usage: meta list"); META_CLIENT(pEntity, "usage: meta list");
return; return;
} }
g_plugins->show_client(pEntity); g_plugins->show_client(pEntity);
} }
// "meta cmds" console command. // "meta cmds" console command.
void cmd_meta_cmdlist(void) void cmd_meta_cmdlist()
{
if (CMD_ARGC() != 2)
{ {
if (CMD_ARGC() != 2) {
META_CONS("usage: meta cmds"); META_CONS("usage: meta cmds");
return; return;
} }
g_regCmds->show(); g_regCmds->show();
} }
// "meta cvars" console command. // "meta cvars" console command.
void cmd_meta_cvarlist(void) void cmd_meta_cvarlist()
{
if (CMD_ARGC() != 2)
{ {
if (CMD_ARGC() != 2) {
META_CONS("usage: meta cvars"); META_CONS("usage: meta cvars");
return; return;
} }
g_regCvars->show(); g_regCvars->show();
} }
// "meta config" console command. // "meta config" console command.
void cmd_meta_config(void) void cmd_meta_config()
{
if (CMD_ARGC() != 2)
{ {
if (CMD_ARGC() != 2) {
META_CONS("usage: meta cvars"); META_CONS("usage: meta cvars");
return; return;
} }
g_config->show(); g_config->show();
} }
@ -297,31 +280,26 @@ void cmd_meta_config(void)
// path_i386.so, path_i486.so, etc // path_i386.so, path_i486.so, etc
// "meta load" console command. // "meta load" console command.
void cmd_meta_load(void) void cmd_meta_load()
{ {
int argc = CMD_ARGC(); int argc = CMD_ARGC();
if (argc < 3)
if (argc < 3) { {
META_CONS("usage: meta load <name> [<description>]"); META_CONS("usage: meta load <name> [<description>]");
META_CONS(" where <name> is an identifier used to locate the plugin file."); META_CONS(" where <name> is an identifier used to locate the plugin file.");
META_CONS(" The system will look for a number of files based on this name, including:"); META_CONS(" The system will look for a number of files based on this name, including:");
META_CONS(" name"); META_CONS(" name");
#ifdef linux #ifdef _WIN32
META_CONS(" name.dll");
META_CONS(" name_mm.dll");
META_CONS(" mm_name.dll");
#else
META_CONS(" name.so"); META_CONS(" name.so");
META_CONS(" name_mm.so"); META_CONS(" name_mm.so");
META_CONS(" name_MM.so"); META_CONS(" name_MM.so");
META_CONS(" mm_name.so"); META_CONS(" mm_name.so");
META_CONS(" name_i386.so"); #endif
META_CONS(" name_i686.so");
#elif defined(__APPLE__)
META_CONS(" name.dylib");
META_CONS(" name_mm.dylib");
META_CONS(" mm_name.dylib");
#elif defined(_WIN32)
META_CONS(" name.dll");
META_CONS(" name_mm.dll");
META_CONS(" mm_name.dll");
#endif /* linux */
META_CONS(" in a number of directories, including:"); META_CONS(" in a number of directories, including:");
META_CONS(" <gamedir>"); META_CONS(" <gamedir>");
META_CONS(" <gamedir>/dlls"); META_CONS(" <gamedir>/dlls");
@ -340,22 +318,27 @@ void cmd_doplug(PLUG_CMD pcmd)
int argc = CMD_ARGC(); int argc = CMD_ARGC();
const char *cmd = CMD_ARGV(1); const char *cmd = CMD_ARGV(1);
if (argc < 3) { if (argc < 3)
{
META_CONS("usage: meta %s <plugin> [<plugin> ...]", cmd); META_CONS("usage: meta %s <plugin> [<plugin> ...]", cmd);
META_CONS(" where <plugin> can be either the plugin index #"); META_CONS(" where <plugin> can be either the plugin index #");
META_CONS(" or a non-ambiguous prefix string matching name, desc, file, or logtag"); META_CONS(" or a non-ambiguous prefix string matching name, desc, file, or logtag");
return; return;
} }
// i = 2 to skip first arg, as that's the "cmd" // i = 2 to skip first arg, as that's the "cmd"
for (int i = 2; i < argc; i++) { for (int i = 2; i < argc; i++)
{
const char *arg = CMD_ARGV(i); const char *arg = CMD_ARGV(i);
MPlugin *findp; MPlugin *findp;
char *endptr; char *endptr;
// try to match plugin id first // try to match plugin id first
long pindex = strtol(arg, &endptr, 10); int pindex = strtol(arg, &endptr, 10);
if (*arg != '\0' && *endptr == '\0')
if (*arg && !*endptr)
findp = g_plugins->find(pindex); findp = g_plugins->find(pindex);
// else try to match some string (prefix) // else try to match some string (prefix)
else else
findp = g_plugins->find_match(arg); findp = g_plugins->find_match(arg);
@ -364,40 +347,37 @@ void cmd_doplug(PLUG_CMD pcmd)
// - specified plugin was found in the list of current plugins // - specified plugin was found in the list of current plugins
// - plugin successfully loaded and began running // - plugin successfully loaded and began running
// Otherwise, print error and exit. // Otherwise, print error and exit.
if (pcmd == PC_REQUIRE) { if (pcmd == PC_REQUIRE)
if (findp && findp->status >= PL_RUNNING) { {
if (findp && findp->status >= PL_RUNNING)
{
META_DEBUG(3, ("Required plugin '%s' found loaded and running.", arg)); META_DEBUG(3, ("Required plugin '%s' found loaded and running.", arg));
return; return;
} }
// Output to both places, because we don't want the admin // Output to both places, because we don't want the admin
// to miss this.. // to miss this..
if (!findp && meta_errno == ME_NOTUNIQ) { if (!findp && meta_errno == ME_NOTUNIQ)
{
META_ERROR("Unique match for required plugin '%s' was not found! Exiting.", arg); META_ERROR("Unique match for required plugin '%s' was not found! Exiting.", arg);
META_CONS("\nERROR: Unique match for required plugin '%s' was not found! Exiting.\n", arg); META_CONS("\nERROR: Unique match for required plugin '%s' was not found! Exiting.\n", arg);
} }
else if (!findp) { else if (!findp)
{
META_ERROR("Required plugin '%s' was not found! Exiting.", arg); META_ERROR("Required plugin '%s' was not found! Exiting.", arg);
META_CONS("\nERROR: Required plugin '%s' was not found! Exiting.\n", arg); META_CONS("\nERROR: Required plugin '%s' was not found! Exiting.\n", arg);
} }
else { else
{
META_ERROR("Required plugin '%s' did not load successfully! (status=%s) Exiting.", arg, findp->str_status(ST_SIMPLE)); META_ERROR("Required plugin '%s' did not load successfully! (status=%s) Exiting.", arg, findp->str_status(ST_SIMPLE));
META_CONS("\nERROR: Required plugin '%s' did not load successfully! (status=%s) Exiting.\n", arg, findp->str_status(ST_SIMPLE)); META_CONS("\nERROR: Required plugin '%s' did not load successfully! (status=%s) Exiting.\n", arg, findp->str_status(ST_SIMPLE));
} }
// Allow chance to read the message, before any window closes. // Allow chance to read the message, before any window closes.
sleep(1); do_exit(1);
#ifdef linux
// Argh, "quit" appears to segfault the server under linux; I
// was unable to determine why.
exit(1);
#else
// Argh, and exit() appears to generate an "Application Error"
// under MSVC. Interestingly, both seem to work fine with
// mingw32.
SERVER_COMMAND("quit\n");
#endif /* not linux */
} }
if (!findp) { if (!findp)
{
if (meta_errno == ME_NOTUNIQ) if (meta_errno == ME_NOTUNIQ)
META_CONS("Couldn't find unique plugin matching '%s'", arg); META_CONS("Couldn't find unique plugin matching '%s'", arg);
else else
@ -405,39 +385,48 @@ void cmd_doplug(PLUG_CMD pcmd)
return; return;
} }
if (pcmd == PC_PAUSE) { switch (pcmd)
{
case PC_PAUSE:
if (findp->pause()) if (findp->pause())
META_CONS("Paused plugin '%s'", findp->desc); META_CONS("Paused plugin '%s'", findp->desc);
else else
META_CONS("Pause failed for plugin '%s'", findp->desc); META_CONS("Pause failed for plugin '%s'", findp->desc);
} break;
else if (pcmd == PC_UNPAUSE) { case PC_UNPAUSE:
if (findp->unpause()) if (findp->unpause())
META_CONS("Unpaused plugin '%s'", findp->desc); META_CONS("Unpaused plugin '%s'", findp->desc);
else else
META_CONS("Unpause failed for plugin '%s'", findp->desc); META_CONS("Unpause failed for plugin '%s'", findp->desc);
} break;
else if (pcmd == PC_UNLOAD) { case PC_UNLOAD:
{
findp->action = PA_UNLOAD; findp->action = PA_UNLOAD;
if (findp->unload(PT_ANYTIME, PNL_COMMAND, PNL_COMMAND)) { if (findp->unload(PT_ANYTIME, PNL_COMMAND, PNL_COMMAND))
{
META_CONS("Unloaded plugin '%s'", findp->desc); META_CONS("Unloaded plugin '%s'", findp->desc);
g_plugins->show(0); g_plugins->show();
} }
else if (meta_errno == ME_DELAYED) else if (meta_errno == ME_DELAYED)
META_CONS("Unload delayed for plugin '%s'", findp->desc); META_CONS("Unload delayed for plugin '%s'", findp->desc);
else else
META_CONS("Unload failed for plugin '%s'", findp->desc); META_CONS("Unload failed for plugin '%s'", findp->desc);
break;
} }
else if (pcmd == PC_FORCE_UNLOAD) { case PC_FORCE_UNLOAD:
{
findp->action = PA_UNLOAD; findp->action = PA_UNLOAD;
if (findp->unload(PT_ANYTIME, PNL_CMD_FORCED, PNL_CMD_FORCED)) { if (findp->unload(PT_ANYTIME, PNL_CMD_FORCED, PNL_CMD_FORCED))
{
META_CONS("Forced unload plugin '%s'", findp->desc); META_CONS("Forced unload plugin '%s'", findp->desc);
g_plugins->show(0); g_plugins->show();
} }
else else
META_CONS("Forced unload failed for plugin '%s'", findp->desc); META_CONS("Forced unload failed for plugin '%s'", findp->desc);
break;
} }
else if (pcmd == PC_RELOAD) { case PC_RELOAD:
{
findp->action = PA_RELOAD; findp->action = PA_RELOAD;
if (findp->reload(PT_ANYTIME, PNL_COMMAND)) if (findp->reload(PT_ANYTIME, PNL_COMMAND))
META_CONS("Reloaded plugin '%s'", findp->desc); META_CONS("Reloaded plugin '%s'", findp->desc);
@ -447,26 +436,31 @@ void cmd_doplug(PLUG_CMD pcmd)
META_CONS("Reload not allowed for plugin '%s' now, only allowed %s", findp->desc, findp->str_loadable(SL_ALLOWED)); META_CONS("Reload not allowed for plugin '%s' now, only allowed %s", findp->desc, findp->str_loadable(SL_ALLOWED));
else else
META_CONS("Reload failed for plugin '%s'", findp->desc); META_CONS("Reload failed for plugin '%s'", findp->desc);
break;
} }
else if (pcmd == PC_RETRY) { case PC_RETRY:
if (findp->retry(PT_ANYTIME, PNL_COMMAND)) if (findp->retry(PT_ANYTIME, PNL_COMMAND))
META_CONS("Retry succeeded for plugin '%s'", findp->desc); META_CONS("Retry succeeded for plugin '%s'", findp->desc);
else else
META_CONS("Retry failed for plugin '%s'", findp->desc); META_CONS("Retry failed for plugin '%s'", findp->desc);
} break;
else if (pcmd == PC_CLEAR) { case PC_CLEAR:
if (findp->clear()) { if (!findp->clear())
META_CONS("Cleared failed plugin '%s' from list", findp->desc); {
g_plugins->show(0);
}
else
META_CONS("Clear failed for plugin '%s'", findp->desc); META_CONS("Clear failed for plugin '%s'", findp->desc);
return;
} }
else if (pcmd == PC_INFO)
META_CONS("Cleared failed plugin '%s' from list", findp->desc);
g_plugins->show();
break;
case PC_INFO:
findp->show(); findp->show();
else { break;
META_ERROR("Unexpected plug_cmd: %d", pcmd); default:
META_WARNING("Unexpected plug_cmd: %d", pcmd);
META_CONS("Command failed; see log"); META_CONS("Command failed; see log");
break;
} }
} }
} }

View File

@ -1,47 +1,11 @@
// vi: set ts=4 sw=4 : #pragma once
// vim: set tw=75 :
// commands_meta.h - prototypes for console commands #include "types_meta.h"
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef COMMANDS_META_H
#define COMMANDS_META_H
#include "types_meta.h" // mBOOL
// Flags to use for meta_cmd_doplug(), to operate on existing plugins; note // Flags to use for meta_cmd_doplug(), to operate on existing plugins; note
// "load" operates on a non-existing plugin thus isn't included here. // "load" operates on a non-existing plugin thus isn't included here.
typedef enum { enum PLUG_CMD
{
PC_NULL = 0, PC_NULL = 0,
PC_PAUSE, // pause the plugin PC_PAUSE, // pause the plugin
PC_UNPAUSE, // unpause the plugin PC_UNPAUSE, // unpause the plugin
@ -52,24 +16,24 @@ typedef enum {
PC_CLEAR, // remove a failed plugin from the list PC_CLEAR, // remove a failed plugin from the list
PC_FORCE_UNLOAD, // forcibly unload the plugin PC_FORCE_UNLOAD, // forcibly unload the plugin
PC_REQUIRE, // require that this plugin is loaded/running PC_REQUIRE, // require that this plugin is loaded/running
} PLUG_CMD; };
void meta_register_cmdcvar(); void meta_register_cmdcvar();
void server_meta(void); void server_meta();
void cmd_meta_usage(void); void cmd_meta_usage();
void cmd_meta_version(void); void cmd_meta_version();
void cmd_meta_gpl(void); void cmd_meta_gpl();
void cmd_meta_game(void); void cmd_meta_game();
void cmd_meta_refresh(void); void cmd_meta_refresh();
void cmd_meta_load(void); void cmd_meta_load();
void cmd_meta_pluginlist(void); void cmd_meta_pluginlist();
void cmd_meta_cmdlist(void); void cmd_meta_cmdlist();
void cmd_meta_cvarlist(void); void cmd_meta_cvarlist();
void cmd_meta_config(void); void cmd_meta_config();
void cmd_doplug(PLUG_CMD pcmd); void cmd_doplug(PLUG_CMD pcmd);
@ -77,5 +41,3 @@ void client_meta(edict_t *pEntity);
void client_meta_usage(edict_t *pEntity); void client_meta_usage(edict_t *pEntity);
void client_meta_version(edict_t *pEntity); void client_meta_version(edict_t *pEntity);
void client_meta_pluginlist(edict_t *pEntity); void client_meta_pluginlist(edict_t *pEntity);
#endif /* COMMANDS_META_H */

View File

@ -1,42 +1,8 @@
// vi: set ts=4 sw=4 :
// vim: set tw=75 :
// conf_meta.cpp - configfile reading routines
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#include "precompiled.h" #include "precompiled.h"
MConfig::MConfig() : list(NULL), filename(NULL), debuglevel(0), gamedll(NULL), plugins_file(NULL), exec_cfg(NULL) MConfig::MConfig()
: list(nullptr), filename(nullptr), debuglevel(0),
plugins_file(nullptr), exec_cfg(nullptr)
{ {
} }
@ -52,9 +18,11 @@ void MConfig::init(option_t* global_options)
option_t *MConfig::find(const char* lookup) const option_t *MConfig::find(const char* lookup) const
{ {
for (auto optp = list; optp->name; optp++) for (auto optp = list; optp->name; optp++)
if (!strcmp(optp->name, lookup)) { {
if (!Q_strcmp(optp->name, lookup)) {
return optp; return optp;
} }
}
RETURN_ERRNO(NULL, ME_NOTFOUND); RETURN_ERRNO(NULL, ME_NOTFOUND);
} }
@ -62,7 +30,6 @@ option_t* MConfig::find(const char* lookup) const
mBOOL MConfig::set(const char* key, const char* value) mBOOL MConfig::set(const char* key, const char* value)
{ {
option_t* optp = find(key); option_t* optp = find(key);
if (optp) if (optp)
return set(optp, value); return set(optp, value);
@ -80,23 +47,28 @@ mBOOL MConfig::set(option_t* setp, const char* setstr)
if (!setstr) if (!setstr)
return mTRUE; return mTRUE;
switch (setp->type) { switch (setp->type)
{
case CF_INT: case CF_INT:
if (!isdigit(setstr[0])) { if (!isdigit(setstr[0]))
{
META_ERROR("option '%s' invalid format '%s'", setp->name, setstr); META_ERROR("option '%s' invalid format '%s'", setp->name, setstr);
RETURN_ERRNO(mFALSE, ME_FORMAT); RETURN_ERRNO(mFALSE, ME_FORMAT);
} }
*optval = atoi(setstr); *optval = Q_atoi(setstr);
META_DEBUG(3, ("set config int: %s = %d", setp->name, *optval)); META_DEBUG(3, ("set config int: %s = %d", setp->name, *optval));
break; break;
case CF_BOOL: case CF_BOOL:
if (is_yes(setstr)) { if (is_yes(setstr))
{
*optval = TRUE; *optval = TRUE;
} }
else if (is_no(setstr)) { else if (is_no(setstr))
{
*optval = FALSE; *optval = FALSE;
} }
else { else
{
META_ERROR("option '%s' invalid format '%s'", setp->name, META_ERROR("option '%s' invalid format '%s'", setp->name,
setstr); setstr);
RETURN_ERRNO(mFALSE, ME_FORMAT); RETURN_ERRNO(mFALSE, ME_FORMAT);
@ -105,33 +77,23 @@ mBOOL MConfig::set(option_t* setp, const char* setstr)
break; break;
case CF_STR: case CF_STR:
if (*optstr) if (*optstr)
free(*optstr); Q_free(*optstr);
*optstr = _strdup(setstr); *optstr = Q_strdup(setstr);
META_DEBUG(3, ("set config string: %s = %s", setp->name, *optstr)); META_DEBUG(3, ("set config string: %s = %s", setp->name, *optstr));
break; break;
case CF_PATH: case CF_PATH:
if (*optstr) if (*optstr)
free(*optstr); Q_free(*optstr);
full_gamedir_path(setstr, pathbuf); full_gamedir_path(setstr, pathbuf);
*optstr = _strdup(pathbuf); *optstr = Q_strdup(pathbuf);
META_DEBUG(3, ("set config path: %s = %s", setp->name, *optstr)); META_DEBUG(3, ("set config path: %s = %s", setp->name, *optstr));
break; break;
#if 0
case CF_CVAR:
CVAR_SET_STRING(optcvar->name, setstr);
META_DEBUG(3, ("set config cvar: %s = %s", optcvar->name, setstr));
break;
case CF_CMD:
optcmd(setp->name, setstr);
META_DEBUG(3, ("set config command: %s, %s",
optcvar->name, setstr));
break;
#endif
default: default:
META_ERROR("unrecognized config type '%d'", setp->type); META_ERROR("unrecognized config type '%d'", setp->type);
RETURN_ERRNO(mFALSE, ME_ARGUMENT); RETURN_ERRNO(mFALSE, ME_ARGUMENT);
} }
return (mTRUE);
return mTRUE;
} }
mBOOL MConfig::load(const char* fn) mBOOL MConfig::load(const char* fn)
@ -148,58 +110,61 @@ mBOOL MConfig::load(const char* fn)
full_gamedir_path(fn, loadfile); full_gamedir_path(fn, loadfile);
fp = fopen(loadfile, "r"); fp = fopen(loadfile, "r");
if (!fp) { if (!fp)
META_ERROR("unable to open config file '%s': %s", loadfile, {
strerror(errno)); META_ERROR("unable to open config file '%s': %s", loadfile, strerror(errno));
RETURN_ERRNO(mFALSE, ME_NOFILE); RETURN_ERRNO(mFALSE, ME_NOFILE);
} }
META_DEBUG(2, ("Loading from config file: %s", loadfile)); META_DEBUG(2, ("Loading from config file: %s", loadfile));
for (ln = 1; !feof(fp) && fgets(line, sizeof(line), fp); ln++) { for (ln = 1; !feof(fp) && fgets(line, sizeof(line), fp); ln++)
if (line[0] == '#') {
if (line[0] == '#' || line[0] == ';' || !Q_strncmp(line, "//", 2))
continue; continue;
if (line[0] == ';')
continue; if (!(optname = strtok(line, " \t\r\n")))
if (strnmatch(line, "//", 2)) {
continue; META_ERROR("'%s' line %d: bad config format: missing option", loadfile, ln);
if (!(optname = strtok(line, " \t\r\n"))) {
META_ERROR("'%s' line %d: bad config format: missing option",
loadfile, ln);
continue;
}
if (!(optval = strtok(NULL, "\r\n"))) {
META_ERROR("'%s' line %d: bad config format: missing value",
loadfile, ln);
continue; continue;
} }
if (!(optp = find(optname))) { if (!(optval = strtok(NULL, "\r\n")))
META_ERROR("'%s' line %d: unknown option name '%s'", {
loadfile, ln, optname); META_ERROR("'%s' line %d: bad config format: missing value", loadfile, ln);
continue; continue;
} }
if (!set(optp, optval)) { if (!(optp = find(optname)))
META_ERROR("'%s' line %d: unable to set option '%s' value '%s'", {
loadfile, ln, optname, optval); META_ERROR("'%s' line %d: unknown option name '%s'", loadfile, ln, optname);
continue;
}
if (!set(optp, optval))
{
META_ERROR("'%s' line %d: unable to set option '%s' value '%s'", loadfile, ln, optname, optval);
continue; continue;
} }
} }
filename = _strdup(loadfile);
filename = Q_strdup(loadfile);
fclose(fp); fclose(fp);
return (mTRUE); return mTRUE;
} }
void MConfig::show(void) const void MConfig::show() const
{ {
META_CONS("Config options from localinfo and %s:", filename); META_CONS("Config options from localinfo and %s:", filename);
for (auto optp = list; optp->name; optp++) { for (auto optp = list; optp->name; optp++)
{
int *optval = (int *)optp->dest; int *optval = (int *)optp->dest;
char **optstr = (char **)optp->dest; char **optstr = (char **)optp->dest;
// cvar_t *optcvar = (cvar_t *) optp->dest; // cvar_t *optcvar = (cvar_t *) optp->dest;
// SETOPT_FN optcmd = (SETOPT_FN) optp->dest; // SETOPT_FN optcmd = (SETOPT_FN) optp->dest;
switch (optp->type) { switch (optp->type)
{
case CF_INT: case CF_INT:
printf(" %-20s\t%d\n", optp->name, *optval); printf(" %-20s\t%d\n", optp->name, *optval);
break; break;
@ -210,14 +175,6 @@ void MConfig::show(void) const
case CF_PATH: case CF_PATH:
printf(" %-20s\t%s\n", optp->name, *optstr ? *optstr : ""); printf(" %-20s\t%s\n", optp->name, *optstr ? *optstr : "");
break; break;
#if 0
case CF_CVAR:
printf(" %-20s\tstores in: %s\n", optp->name, optcvar->name);
break;
case CF_CMD:
printf(" %-20s\tparsed by: %d\n", optp->name, (int) optcmd);
break;
#endif
case CF_NONE: case CF_NONE:
break; break;
} }

View File

@ -1,96 +1,49 @@
// vi: set ts=4 sw=4 : #pragma once
// vim: set tw=75 :
// conf_meta.h - configfile reading #include "types_meta.h"
// Modeled after mutt/init.[ch].
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef CONF_META_H
#define CONF_META_H
#include "types_meta.h" // mBOOL
// Max length of line in config file. // Max length of line in config file.
#define MAX_CONF_LEN 1024 #define MAX_CONF_LEN 1024
// Supported config value-types. // Supported config value-types.
typedef enum { enum cf_type_t
{
CF_NONE = 0, CF_NONE = 0,
CF_INT, CF_INT,
CF_BOOL, CF_BOOL,
CF_STR, CF_STR,
CF_PATH, CF_PATH,
#if 0 };
CF_CVAR,
CF_CMD,
#endif
} cf_type_t;
typedef mBOOL (*SETOPT_FN) (char *key, char *value); struct option_t
{
typedef struct option_s { char *name; // option name
const char *name; // option name
cf_type_t type; // option type cf_type_t type; // option type
void *dest; // addr of destination variable, or handler function void *dest; // addr of destination variable, or handler function
const char *init; // initial value, as a string, just as config file would char *init; // initial value, as a string, just as config file would
} option_t; };
class MConfig { class MConfig {
public:
MConfig();
int debuglevel; // to use for meta_debug
char *plugins_file; // ie metamod.ini, plugins.ini
char *exec_cfg; // ie metaexec.cfg, exec.cfg
void init(option_t *global_options);
mBOOL load(const char *filename);
mBOOL set(const char *key, const char *value);
void show() const;
private: private:
// data
option_t *list; option_t *list;
char *filename; char *filename;
// functions
option_t *find(const char *lookup) const; option_t *find(const char *lookup) const;
static mBOOL set(option_t *setp, const char *value); static mBOOL set(option_t *setp, const char *value);
// Private; to satisfy -Weffc++ "has pointer data members but does // Private; to satisfy -Weffc++ "has pointer data members but does
// not override" copy/assignment constructor. // not override" copy/assignment constructor.
void operator=(const MConfig &src); void operator=(const MConfig &src);
MConfig(const MConfig &src); MConfig(const MConfig &src);
public:
// contructor
MConfig(void);
// data
int debuglevel; // to use for meta_debug
char *gamedll; // string if specified in config.ini
char *plugins_file; // ie metamod.ini, plugins.ini
char *exec_cfg; // ie metaexec.cfg, exec.cfg
// functions
void init(option_t *global_options);
mBOOL load(const char *filename);
mBOOL set(const char *key, const char *value);
void show(void) const;
}; };
#endif /* CONF_META_H */

View File

@ -1,39 +1,3 @@
// vi: set ts=4 sw=4 :
// vim: set tw=75 :
// dllapi.cpp - implementation of Half-Life DLL routines
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#include "precompiled.h" #include "precompiled.h"
// Original DLL routines, functions returning "void". // Original DLL routines, functions returning "void".
@ -65,110 +29,149 @@
CALL_GAME_API(pfnName, pfn_args, newapi_table); \ CALL_GAME_API(pfnName, pfn_args, newapi_table); \
CALL_PLUGIN_API(P_POST, ret_init, pfnName, pfn_args, MRES_OVERRIDE, newapi_post_table); CALL_PLUGIN_API(P_POST, ret_init, pfnName, pfn_args, MRES_OVERRIDE, newapi_post_table);
void mm_GameDLLInit(void)
// From SDK dlls/game.cpp: {
void mm_GameDLLInit(void) {
META_DLLAPI_HANDLE_void(FN_GAMEINIT, pfnGameInit, ()); META_DLLAPI_HANDLE_void(FN_GAMEINIT, pfnGameInit, ());
RETURN_API_void(); RETURN_API_void();
} }
// From SDK dlls/cbase.cpp: int mm_DispatchSpawn(edict_t *pent)
int mm_DispatchSpawn(edict_t *pent) { {
// 0==Success, -1==Failure ? // Success == 0, Failure == -1 ?
META_DLLAPI_HANDLE(int, 0, FN_DISPATCHSPAWN, pfnSpawn, (pent)); META_DLLAPI_HANDLE(int, 0, FN_DISPATCHSPAWN, pfnSpawn, (pent));
RETURN_API(); RETURN_API();
} }
void mm_DispatchThink(edict_t *pent) {
void mm_DispatchThink(edict_t *pent)
{
META_DLLAPI_HANDLE_void(FN_DISPATCHTHINK, pfnThink, (pent)); META_DLLAPI_HANDLE_void(FN_DISPATCHTHINK, pfnThink, (pent));
RETURN_API_void(); RETURN_API_void();
} }
void mm_DispatchUse(edict_t *pentUsed, edict_t *pentOther) {
void mm_DispatchUse(edict_t *pentUsed, edict_t *pentOther)
{
META_DLLAPI_HANDLE_void(FN_DISPATCHUSE, pfnUse, (pentUsed, pentOther)); META_DLLAPI_HANDLE_void(FN_DISPATCHUSE, pfnUse, (pentUsed, pentOther));
RETURN_API_void(); RETURN_API_void();
} }
void mm_DispatchTouch(edict_t *pentTouched, edict_t *pentOther) {
void mm_DispatchTouch(edict_t *pentTouched, edict_t *pentOther)
{
META_DLLAPI_HANDLE_void(FN_DISPATCHTOUCH, pfnTouch, (pentTouched, pentOther)); META_DLLAPI_HANDLE_void(FN_DISPATCHTOUCH, pfnTouch, (pentTouched, pentOther));
RETURN_API_void(); RETURN_API_void();
} }
void mm_DispatchBlocked(edict_t *pentBlocked, edict_t *pentOther) {
void mm_DispatchBlocked(edict_t *pentBlocked, edict_t *pentOther)
{
META_DLLAPI_HANDLE_void(FN_DISPATCHBLOCKED, pfnBlocked, (pentBlocked, pentOther)); META_DLLAPI_HANDLE_void(FN_DISPATCHBLOCKED, pfnBlocked, (pentBlocked, pentOther));
RETURN_API_void(); RETURN_API_void();
} }
void mm_DispatchKeyValue(edict_t *pentKeyvalue, KeyValueData *pkvd) {
void mm_DispatchKeyValue(edict_t *pentKeyvalue, KeyValueData *pkvd)
{
META_DLLAPI_HANDLE_void(FN_DISPATCHKEYVALUE, pfnKeyValue, (pentKeyvalue, pkvd)); META_DLLAPI_HANDLE_void(FN_DISPATCHKEYVALUE, pfnKeyValue, (pentKeyvalue, pkvd));
RETURN_API_void(); RETURN_API_void();
} }
void mm_DispatchSave(edict_t *pent, SAVERESTOREDATA *pSaveData) {
void mm_DispatchSave(edict_t *pent, SAVERESTOREDATA *pSaveData)
{
META_DLLAPI_HANDLE_void(FN_DISPATCHSAVE, pfnSave, (pent, pSaveData)); META_DLLAPI_HANDLE_void(FN_DISPATCHSAVE, pfnSave, (pent, pSaveData));
RETURN_API_void(); RETURN_API_void();
} }
int mm_DispatchRestore(edict_t *pent, SAVERESTOREDATA *pSaveData, int globalEntity) {
// 0==Success, -1==Failure ? int mm_DispatchRestore(edict_t *pent, SAVERESTOREDATA *pSaveData, int globalEntity)
{
// Success == 0, Failure == -1 ?
META_DLLAPI_HANDLE(int, 0, FN_DISPATCHRESTORE, pfnRestore, (pent, pSaveData, globalEntity)); META_DLLAPI_HANDLE(int, 0, FN_DISPATCHRESTORE, pfnRestore, (pent, pSaveData, globalEntity));
RETURN_API(); RETURN_API();
} }
void mm_DispatchObjectCollsionBox(edict_t *pent) {
void mm_DispatchObjectCollsionBox(edict_t *pent)
{
META_DLLAPI_HANDLE_void(FN_DISPATCHOBJECTCOLLISIONBOX, pfnSetAbsBox, (pent)); META_DLLAPI_HANDLE_void(FN_DISPATCHOBJECTCOLLISIONBOX, pfnSetAbsBox, (pent));
RETURN_API_void(); RETURN_API_void();
} }
void mm_SaveWriteFields(SAVERESTOREDATA *pSaveData, const char *pname, void *pBaseData, TYPEDESCRIPTION *pFields, int fieldCount) {
void mm_SaveWriteFields(SAVERESTOREDATA *pSaveData, const char *pname, void *pBaseData, TYPEDESCRIPTION *pFields, int fieldCount)
{
META_DLLAPI_HANDLE_void(FN_SAVEWRITEFIELDS, pfnSaveWriteFields, (pSaveData, pname, pBaseData, pFields, fieldCount)); META_DLLAPI_HANDLE_void(FN_SAVEWRITEFIELDS, pfnSaveWriteFields, (pSaveData, pname, pBaseData, pFields, fieldCount));
RETURN_API_void(); RETURN_API_void();
} }
void mm_SaveReadFields(SAVERESTOREDATA *pSaveData, const char *pname, void *pBaseData, TYPEDESCRIPTION *pFields, int fieldCount) {
void mm_SaveReadFields(SAVERESTOREDATA *pSaveData, const char *pname, void *pBaseData, TYPEDESCRIPTION *pFields, int fieldCount)
{
META_DLLAPI_HANDLE_void(FN_SAVEREADFIELDS, pfnSaveReadFields, (pSaveData, pname, pBaseData, pFields, fieldCount)); META_DLLAPI_HANDLE_void(FN_SAVEREADFIELDS, pfnSaveReadFields, (pSaveData, pname, pBaseData, pFields, fieldCount));
RETURN_API_void(); RETURN_API_void();
} }
// From SDK dlls/world.cpp: void mm_SaveGlobalState(SAVERESTOREDATA *pSaveData)
void mm_SaveGlobalState(SAVERESTOREDATA *pSaveData) { {
META_DLLAPI_HANDLE_void(FN_SAVEGLOBALSTATE, pfnSaveGlobalState, (pSaveData)); META_DLLAPI_HANDLE_void(FN_SAVEGLOBALSTATE, pfnSaveGlobalState, (pSaveData));
RETURN_API_void(); RETURN_API_void();
} }
void mm_RestoreGlobalState(SAVERESTOREDATA *pSaveData) {
void mm_RestoreGlobalState(SAVERESTOREDATA *pSaveData)
{
META_DLLAPI_HANDLE_void(FN_RESTOREGLOBALSTATE, pfnRestoreGlobalState, (pSaveData)); META_DLLAPI_HANDLE_void(FN_RESTOREGLOBALSTATE, pfnRestoreGlobalState, (pSaveData));
RETURN_API_void(); RETURN_API_void();
} }
void mm_ResetGlobalState(void) {
void mm_ResetGlobalState(void)
{
META_DLLAPI_HANDLE_void(FN_RESETGLOBALSTATE, pfnResetGlobalState, ()); META_DLLAPI_HANDLE_void(FN_RESETGLOBALSTATE, pfnResetGlobalState, ());
RETURN_API_void(); RETURN_API_void();
} }
// From SDK dlls/client.cpp: BOOL mm_ClientConnect(edict_t *pEntity, const char *pszName, const char *pszAddress, char szRejectReason[ 128 ] )
BOOL mm_ClientConnect(edict_t *pEntity, const char *pszName, const char *pszAddress, char szRejectReason[ 128 ] ) { {
g_Players.clear_player_cvar_query(pEntity); g_Players.clear_player_cvar_query(pEntity);
META_DLLAPI_HANDLE(BOOL, TRUE, FN_CLIENTCONNECT, pfnClientConnect, (pEntity, pszName, pszAddress, szRejectReason)); META_DLLAPI_HANDLE(BOOL, TRUE, FN_CLIENTCONNECT, pfnClientConnect, (pEntity, pszName, pszAddress, szRejectReason));
RETURN_API(); RETURN_API();
} }
void mm_ClientDisconnect(edict_t *pEntity) {
void mm_ClientDisconnect(edict_t *pEntity)
{
g_Players.clear_player_cvar_query(pEntity); g_Players.clear_player_cvar_query(pEntity);
META_DLLAPI_HANDLE_void(FN_CLIENTDISCONNECT, pfnClientDisconnect, (pEntity)); META_DLLAPI_HANDLE_void(FN_CLIENTDISCONNECT, pfnClientDisconnect, (pEntity));
RETURN_API_void(); RETURN_API_void();
} }
void mm_ClientKill(edict_t *pEntity) {
void mm_ClientKill(edict_t *pEntity)
{
META_DLLAPI_HANDLE_void(FN_CLIENTKILL, pfnClientKill, (pEntity)); META_DLLAPI_HANDLE_void(FN_CLIENTKILL, pfnClientKill, (pEntity));
RETURN_API_void(); RETURN_API_void();
} }
void mm_ClientPutInServer(edict_t *pEntity) {
void mm_ClientPutInServer(edict_t *pEntity)
{
META_DLLAPI_HANDLE_void(FN_CLIENTPUTINSERVER, pfnClientPutInServer, (pEntity)); META_DLLAPI_HANDLE_void(FN_CLIENTPUTINSERVER, pfnClientPutInServer, (pEntity));
RETURN_API_void(); RETURN_API_void();
} }
void mm_ClientCommand(edict_t *pEntity) {
if(!strcmp(CMD_ARGV(0), "meta")) { void mm_ClientCommand(edict_t *pEntity)
{
if (!Q_strcmp(CMD_ARGV(0), "meta"))
{
client_meta(pEntity); client_meta(pEntity);
} }
META_DLLAPI_HANDLE_void(FN_CLIENTCOMMAND, pfnClientCommand, (pEntity)); META_DLLAPI_HANDLE_void(FN_CLIENTCOMMAND, pfnClientCommand, (pEntity));
RETURN_API_void(); RETURN_API_void();
} }
void mm_ClientUserInfoChanged(edict_t *pEntity, char *infobuffer) {
void mm_ClientUserInfoChanged(edict_t *pEntity, char *infobuffer)
{
META_DLLAPI_HANDLE_void(FN_CLIENTUSERINFOCHANGED, pfnClientUserInfoChanged, (pEntity, infobuffer)); META_DLLAPI_HANDLE_void(FN_CLIENTUSERINFOCHANGED, pfnClientUserInfoChanged, (pEntity, infobuffer));
RETURN_API_void(); RETURN_API_void();
} }
void mm_ServerActivate(edict_t *pEdictList, int edictCount, int clientMax) {
void mm_ServerActivate(edict_t *pEdictList, int edictCount, int clientMax)
{
META_DLLAPI_HANDLE_void(FN_SERVERACTIVATE, pfnServerActivate, (pEdictList, edictCount, clientMax)); META_DLLAPI_HANDLE_void(FN_SERVERACTIVATE, pfnServerActivate, (pEdictList, edictCount, clientMax));
RETURN_API_void(); RETURN_API_void();
} }
void mm_ServerDeactivate(void) {
void mm_ServerDeactivate(void)
{
META_DLLAPI_HANDLE_void(FN_SERVERDEACTIVATE, pfnServerDeactivate, ()); META_DLLAPI_HANDLE_void(FN_SERVERDEACTIVATE, pfnServerDeactivate, ());
// Update loaded plugins. Look for new plugins in inifile, as well as // Update loaded plugins. Look for new plugins in inifile, as well as
// any plugins waiting for a changelevel to load. // any plugins waiting for a changelevel to load.
@ -190,211 +193,263 @@ void mm_ServerDeactivate(void) {
requestid_counter = 0; requestid_counter = 0;
RETURN_API_void(); RETURN_API_void();
} }
void mm_PlayerPreThink(edict_t *pEntity) {
void mm_PlayerPreThink(edict_t *pEntity)
{
META_DLLAPI_HANDLE_void(FN_PLAYERPRETHINK, pfnPlayerPreThink, (pEntity)); META_DLLAPI_HANDLE_void(FN_PLAYERPRETHINK, pfnPlayerPreThink, (pEntity));
RETURN_API_void(); RETURN_API_void();
} }
void mm_PlayerPostThink(edict_t *pEntity) {
void mm_PlayerPostThink(edict_t *pEntity)
{
META_DLLAPI_HANDLE_void(FN_PLAYERPOSTTHINK, pfnPlayerPostThink, (pEntity)); META_DLLAPI_HANDLE_void(FN_PLAYERPOSTTHINK, pfnPlayerPostThink, (pEntity));
RETURN_API_void(); RETURN_API_void();
} }
void mm_StartFrame(void) {
void mm_StartFrame(void)
{
META_DLLAPI_HANDLE_void(FN_STARTFRAME, pfnStartFrame, ()); META_DLLAPI_HANDLE_void(FN_STARTFRAME, pfnStartFrame, ());
RETURN_API_void(); RETURN_API_void();
} }
void mm_ParmsNewLevel(void) {
void mm_ParmsNewLevel(void)
{
META_DLLAPI_HANDLE_void(FN_PARMSNEWLEVEL, pfnParmsNewLevel, ()); META_DLLAPI_HANDLE_void(FN_PARMSNEWLEVEL, pfnParmsNewLevel, ());
RETURN_API_void(); RETURN_API_void();
} }
void mm_ParmsChangeLevel(void) {
void mm_ParmsChangeLevel(void)
{
META_DLLAPI_HANDLE_void(FN_PARMSCHANGELEVEL, pfnParmsChangeLevel, ()); META_DLLAPI_HANDLE_void(FN_PARMSCHANGELEVEL, pfnParmsChangeLevel, ());
RETURN_API_void(); RETURN_API_void();
} }
const char *mm_GetGameDescription(void) {
const char *mm_GetGameDescription(void)
{
META_DLLAPI_HANDLE(const char *, NULL, FN_GETGAMEDESCRIPTION, pfnGetGameDescription, ()); META_DLLAPI_HANDLE(const char *, NULL, FN_GETGAMEDESCRIPTION, pfnGetGameDescription, ());
RETURN_API(); RETURN_API();
} }
void mm_PlayerCustomization(edict_t *pEntity, customization_t *pCust) {
void mm_PlayerCustomization(edict_t *pEntity, customization_t *pCust)
{
META_DLLAPI_HANDLE_void(FN_PLAYERCUSTOMIZATION, pfnPlayerCustomization, (pEntity, pCust)); META_DLLAPI_HANDLE_void(FN_PLAYERCUSTOMIZATION, pfnPlayerCustomization, (pEntity, pCust));
RETURN_API_void(); RETURN_API_void();
} }
void mm_SpectatorConnect(edict_t *pEntity) {
void mm_SpectatorConnect(edict_t *pEntity)
{
META_DLLAPI_HANDLE_void(FN_SPECTATORCONNECT, pfnSpectatorConnect, (pEntity)); META_DLLAPI_HANDLE_void(FN_SPECTATORCONNECT, pfnSpectatorConnect, (pEntity));
RETURN_API_void(); RETURN_API_void();
} }
void mm_SpectatorDisconnect(edict_t *pEntity) {
void mm_SpectatorDisconnect(edict_t *pEntity)
{
META_DLLAPI_HANDLE_void(FN_SPECTATORDISCONNECT, pfnSpectatorDisconnect, (pEntity)); META_DLLAPI_HANDLE_void(FN_SPECTATORDISCONNECT, pfnSpectatorDisconnect, (pEntity));
RETURN_API_void(); RETURN_API_void();
} }
void mm_SpectatorThink(edict_t *pEntity) {
void mm_SpectatorThink(edict_t *pEntity)
{
META_DLLAPI_HANDLE_void(FN_SPECTATORTHINK, pfnSpectatorThink, (pEntity)); META_DLLAPI_HANDLE_void(FN_SPECTATORTHINK, pfnSpectatorThink, (pEntity));
RETURN_API_void(); RETURN_API_void();
} }
void mm_Sys_Error(const char *error_string) {
void mm_Sys_Error(const char *error_string)
{
META_DLLAPI_HANDLE_void(FN_SYS_ERROR, pfnSys_Error, (error_string)); META_DLLAPI_HANDLE_void(FN_SYS_ERROR, pfnSys_Error, (error_string));
RETURN_API_void(); RETURN_API_void();
} }
// From SDK pm_shared/pm_shared.c: void mm_PM_Move (struct playermove_s *ppmove, int server)
void mm_PM_Move (struct playermove_s *ppmove, int server) { {
META_DLLAPI_HANDLE_void(FN_PM_MOVE, pfnPM_Move, (ppmove, server)); META_DLLAPI_HANDLE_void(FN_PM_MOVE, pfnPM_Move, (ppmove, server));
RETURN_API_void(); RETURN_API_void();
} }
void mm_PM_Init(struct playermove_s *ppmove) {
void mm_PM_Init(struct playermove_s *ppmove)
{
META_DLLAPI_HANDLE_void(FN_PM_INIT, pfnPM_Init, (ppmove)); META_DLLAPI_HANDLE_void(FN_PM_INIT, pfnPM_Init, (ppmove));
RETURN_API_void(); RETURN_API_void();
} }
char mm_PM_FindTextureType(char *name) {
char mm_PM_FindTextureType(char *name)
{
META_DLLAPI_HANDLE(char, '\0', FN_PM_FINDTEXTURETYPE, pfnPM_FindTextureType, (name)); META_DLLAPI_HANDLE(char, '\0', FN_PM_FINDTEXTURETYPE, pfnPM_FindTextureType, (name));
RETURN_API(); RETURN_API();
} }
// From SDK dlls/client.cpp: void mm_SetupVisibility(edict_t *pViewEntity, edict_t *pClient, unsigned char **pvs, unsigned char **pas)
void mm_SetupVisibility(edict_t *pViewEntity, edict_t *pClient, unsigned char **pvs, unsigned char **pas) { {
META_DLLAPI_HANDLE_void(FN_SETUPVISIBILITY, pfnSetupVisibility, (pViewEntity, pClient, pvs, pas)); META_DLLAPI_HANDLE_void(FN_SETUPVISIBILITY, pfnSetupVisibility, (pViewEntity, pClient, pvs, pas));
RETURN_API_void(); RETURN_API_void();
} }
void mm_UpdateClientData (const struct edict_s *ent, int sendweapons, struct clientdata_s *cd) {
void mm_UpdateClientData (const struct edict_s *ent, int sendweapons, struct clientdata_s *cd)
{
META_DLLAPI_HANDLE_void(FN_UPDATECLIENTDATA, pfnUpdateClientData, (ent, sendweapons, cd)); META_DLLAPI_HANDLE_void(FN_UPDATECLIENTDATA, pfnUpdateClientData, (ent, sendweapons, cd));
RETURN_API_void(); RETURN_API_void();
} }
int mm_AddToFullPack(struct entity_state_s *state, int e, edict_t *ent, edict_t *host, int hostflags, int player, unsigned char *pSet) {
int mm_AddToFullPack(struct entity_state_s *state, int e, edict_t *ent, edict_t *host, int hostflags, int player, unsigned char *pSet)
{
META_DLLAPI_HANDLE(int, 0, FN_ADDTOFULLPACK, pfnAddToFullPack, (state, e, ent, host, hostflags, player, pSet)); META_DLLAPI_HANDLE(int, 0, FN_ADDTOFULLPACK, pfnAddToFullPack, (state, e, ent, host, hostflags, player, pSet));
RETURN_API(); RETURN_API();
} }
void mm_CreateBaseline(int player, int eindex, struct entity_state_s *baseline, struct edict_s *entity, int playermodelindex, vec3_t player_mins, vec3_t player_maxs) {
void mm_CreateBaseline(int player, int eindex, struct entity_state_s *baseline, struct edict_s *entity, int playermodelindex, vec3_t player_mins, vec3_t player_maxs)
{
META_DLLAPI_HANDLE_void(FN_CREATEBASELINE, pfnCreateBaseline, (player, eindex, baseline, entity, playermodelindex, player_mins, player_maxs)); META_DLLAPI_HANDLE_void(FN_CREATEBASELINE, pfnCreateBaseline, (player, eindex, baseline, entity, playermodelindex, player_mins, player_maxs));
RETURN_API_void(); RETURN_API_void();
} }
void mm_RegisterEncoders(void) {
void mm_RegisterEncoders(void)
{
META_DLLAPI_HANDLE_void(FN_REGISTERENCODERS, pfnRegisterEncoders, ()); META_DLLAPI_HANDLE_void(FN_REGISTERENCODERS, pfnRegisterEncoders, ());
RETURN_API_void(); RETURN_API_void();
} }
int mm_GetWeaponData(struct edict_s *player, struct weapon_data_s *info) {
int mm_GetWeaponData(struct edict_s *player, struct weapon_data_s *info)
{
META_DLLAPI_HANDLE(int, 0, FN_GETWEAPONDATA, pfnGetWeaponData, (player, info)); META_DLLAPI_HANDLE(int, 0, FN_GETWEAPONDATA, pfnGetWeaponData, (player, info));
RETURN_API(); RETURN_API();
} }
void mm_CmdStart(const edict_t *player, const struct usercmd_s *cmd, unsigned int random_seed) {
void mm_CmdStart(const edict_t *player, const struct usercmd_s *cmd, unsigned int random_seed)
{
META_DLLAPI_HANDLE_void(FN_CMDSTART, pfnCmdStart, (player, cmd, random_seed)); META_DLLAPI_HANDLE_void(FN_CMDSTART, pfnCmdStart, (player, cmd, random_seed));
RETURN_API_void(); RETURN_API_void();
} }
void mm_CmdEnd (const edict_t *player) {
void mm_CmdEnd (const edict_t *player)
{
META_DLLAPI_HANDLE_void(FN_CMDEND, pfnCmdEnd, (player)); META_DLLAPI_HANDLE_void(FN_CMDEND, pfnCmdEnd, (player));
RETURN_API_void(); RETURN_API_void();
} }
int mm_ConnectionlessPacket(const struct netadr_s *net_from, const char *args, char *response_buffer, int *response_buffer_size) {
int mm_ConnectionlessPacket(const struct netadr_s *net_from, const char *args, char *response_buffer, int *response_buffer_size)
{
META_DLLAPI_HANDLE(int, 0, FN_CONNECTIONLESSPACKET, pfnConnectionlessPacket, (net_from, args, response_buffer, response_buffer_size)); META_DLLAPI_HANDLE(int, 0, FN_CONNECTIONLESSPACKET, pfnConnectionlessPacket, (net_from, args, response_buffer, response_buffer_size));
RETURN_API(); RETURN_API();
} }
int mm_GetHullBounds(int hullnumber, float *mins, float *maxs) {
int mm_GetHullBounds(int hullnumber, float *mins, float *maxs)
{
META_DLLAPI_HANDLE(int, 0, FN_GETHULLBOUNDS, pfnGetHullBounds, (hullnumber, mins, maxs)); META_DLLAPI_HANDLE(int, 0, FN_GETHULLBOUNDS, pfnGetHullBounds, (hullnumber, mins, maxs));
RETURN_API(); RETURN_API();
} }
void mm_CreateInstancedBaselines (void) {
void mm_CreateInstancedBaselines (void)
{
META_DLLAPI_HANDLE_void(FN_CREATEINSTANCEDBASELINES, pfnCreateInstancedBaselines, ()); META_DLLAPI_HANDLE_void(FN_CREATEINSTANCEDBASELINES, pfnCreateInstancedBaselines, ());
RETURN_API_void(); RETURN_API_void();
} }
int mm_InconsistentFile(const edict_t *player, const char *filename, char *disconnect_message) {
int mm_InconsistentFile(const edict_t *player, const char *filename, char *disconnect_message)
{
META_DLLAPI_HANDLE(int, 0, FN_INCONSISTENTFILE, pfnInconsistentFile, (player, filename, disconnect_message)); META_DLLAPI_HANDLE(int, 0, FN_INCONSISTENTFILE, pfnInconsistentFile, (player, filename, disconnect_message));
RETURN_API(); RETURN_API();
} }
int mm_AllowLagCompensation(void) {
int mm_AllowLagCompensation(void)
{
META_DLLAPI_HANDLE(int, 0, FN_ALLOWLAGCOMPENSATION, pfnAllowLagCompensation, ()); META_DLLAPI_HANDLE(int, 0, FN_ALLOWLAGCOMPENSATION, pfnAllowLagCompensation, ());
RETURN_API(); RETURN_API();
} }
void mm_OnFreeEntPrivateData(edict_t *pEnt)
// New API functions {
// From SDK ?
void mm_OnFreeEntPrivateData(edict_t *pEnt) {
META_NEWAPI_HANDLE_void(FN_ONFREEENTPRIVATEDATA, pfnOnFreeEntPrivateData, (pEnt)); META_NEWAPI_HANDLE_void(FN_ONFREEENTPRIVATEDATA, pfnOnFreeEntPrivateData, (pEnt));
RETURN_API_void(); RETURN_API_void();
} }
void mm_GameShutdown(void) {
void mm_GameShutdown(void)
{
META_NEWAPI_HANDLE_void(FN_GAMESHUTDOWN, pfnGameShutdown, ()); META_NEWAPI_HANDLE_void(FN_GAMESHUTDOWN, pfnGameShutdown, ());
RETURN_API_void(); RETURN_API_void();
} }
int mm_ShouldCollide(edict_t *pentTouched, edict_t *pentOther) {
int mm_ShouldCollide(edict_t *pentTouched, edict_t *pentOther)
{
META_NEWAPI_HANDLE(int, 1, FN_SHOULDCOLLIDE, pfnShouldCollide, (pentTouched, pentOther)); META_NEWAPI_HANDLE(int, 1, FN_SHOULDCOLLIDE, pfnShouldCollide, (pentTouched, pentOther));
RETURN_API(); RETURN_API();
} }
// Added 2005-08-11 (no SDK update)
void mm_CvarValue(const edict_t *pEdict, const char *value) { void mm_CvarValue(const edict_t *pEdict, const char *value)
{
g_Players.clear_player_cvar_query(pEdict); g_Players.clear_player_cvar_query(pEdict);
META_NEWAPI_HANDLE_void(FN_CVARVALUE, pfnCvarValue, (pEdict, value)); META_NEWAPI_HANDLE_void(FN_CVARVALUE, pfnCvarValue, (pEdict, value));
RETURN_API_void(); RETURN_API_void();
} }
//Added 2005-11-22 (no SDK update) void mm_CvarValue2(const edict_t *pEdict, int requestID, const char *cvarName, const char *value)
void mm_CvarValue2(const edict_t *pEdict, int requestID, const char *cvarName, const char *value) { {
META_NEWAPI_HANDLE_void(FN_CVARVALUE2, pfnCvarValue2, (pEdict, requestID, cvarName, value)); META_NEWAPI_HANDLE_void(FN_CVARVALUE2, pfnCvarValue2, (pEdict, requestID, cvarName, value));
RETURN_API_void(); RETURN_API_void();
} }
// From SDK dlls/cbase.cpp:
// "(wd)" indicates my comments on the functions // "(wd)" indicates my comments on the functions
static DLL_FUNCTIONS sFunctionTable = DLL_FUNCTIONS sFunctionTable =
{ {
mm_GameDLLInit, //! pfnGameInit() Initialize the game (one-time call after loading of game .dll) mm_GameDLLInit, // pfnGameInit() Initialize the game (one-time call after loading of game .dll)
mm_DispatchSpawn, //! pfnSpawn() mm_DispatchSpawn, // pfnSpawn()
mm_DispatchThink, //! pfnThink() mm_DispatchThink, // pfnThink()
mm_DispatchUse, //! pfnUse() mm_DispatchUse, // pfnUse()
mm_DispatchTouch, //! pfnTouch() mm_DispatchTouch, // pfnTouch()
mm_DispatchBlocked, //! pfnBlocked() mm_DispatchBlocked, // pfnBlocked()
mm_DispatchKeyValue, //! pfnKeyValue() mm_DispatchKeyValue, // pfnKeyValue()
mm_DispatchSave, //! pfnSave() mm_DispatchSave, // pfnSave()
mm_DispatchRestore, //! pfnRestore() mm_DispatchRestore, // pfnRestore()
mm_DispatchObjectCollsionBox, //! pfnSetAbsBox() mm_DispatchObjectCollsionBox, // pfnSetAbsBox()
mm_SaveWriteFields, //! pfnSaveWriteFields() mm_SaveWriteFields, // pfnSaveWriteFields()
mm_SaveReadFields, //! pfnSaveReadFields() mm_SaveReadFields, // pfnSaveReadFields()
mm_SaveGlobalState, //! pfnSaveGlobalState() mm_SaveGlobalState, // pfnSaveGlobalState()
mm_RestoreGlobalState, //! pfnRestoreGlobalState() mm_RestoreGlobalState, // pfnRestoreGlobalState()
mm_ResetGlobalState, //! pfnResetGlobalState() mm_ResetGlobalState, // pfnResetGlobalState()
mm_ClientConnect, //! pfnClientConnect() (wd) Client has connected mm_ClientConnect, // pfnClientConnect() (wd) Client has connected
mm_ClientDisconnect, //! pfnClientDisconnect() (wd) Player has left the game mm_ClientDisconnect, // pfnClientDisconnect() (wd) Player has left the game
mm_ClientKill, //! pfnClientKill() (wd) Player has typed "kill" mm_ClientKill, // pfnClientKill() (wd) Player has typed "kill"
mm_ClientPutInServer, //! pfnClientPutInServer() (wd) Client is entering the game mm_ClientPutInServer, // pfnClientPutInServer() (wd) Client is entering the game
mm_ClientCommand, //! pfnClientCommand() (wd) Player has sent a command (typed, or from a bind) mm_ClientCommand, // pfnClientCommand() (wd) Player has sent a command (typed, or from a bind)
mm_ClientUserInfoChanged, //! pfnClientUserInfoChanged() (wd) Client has updated their setinfo structure mm_ClientUserInfoChanged, // pfnClientUserInfoChanged() (wd) Client has updated their setinfo structure
mm_ServerActivate, //! pfnServerActivate() (wd) Server is starting a new map mm_ServerActivate, // pfnServerActivate() (wd) Server is starting a new map
mm_ServerDeactivate, //! pfnServerDeactivate() (wd) Server is leaving the map (shutdown, or changelevel); SDK2 mm_ServerDeactivate, // pfnServerDeactivate() (wd) Server is leaving the map (shutdown, or changelevel); SDK2
mm_PlayerPreThink, //! pfnPlayerPreThink() mm_PlayerPreThink, // pfnPlayerPreThink()
mm_PlayerPostThink, //! pfnPlayerPostThink() mm_PlayerPostThink, // pfnPlayerPostThink()
mm_StartFrame, //! pfnStartFrame() mm_StartFrame, // pfnStartFrame()
mm_ParmsNewLevel, //! pfnParmsNewLevel() mm_ParmsNewLevel, // pfnParmsNewLevel()
mm_ParmsChangeLevel, //! pfnParmsChangeLevel() mm_ParmsChangeLevel, // pfnParmsChangeLevel()
mm_GetGameDescription, //! pfnGetGameDescription() Returns string describing current .dll. E.g. "TeamFotrress 2", "Half-Life" mm_GetGameDescription, // pfnGetGameDescription() Returns string describing current .dll. E.g. "TeamFotrress 2", "Half-Life"
mm_PlayerCustomization, //! pfnPlayerCustomization() Notifies .dll of new customization for player. mm_PlayerCustomization, // pfnPlayerCustomization() Notifies .dll of new customization for player.
mm_SpectatorConnect, //! pfnSpectatorConnect() Called when spectator joins server mm_SpectatorConnect, // pfnSpectatorConnect() Called when spectator joins server
mm_SpectatorDisconnect, //! pfnSpectatorDisconnect() Called when spectator leaves the server mm_SpectatorDisconnect, // pfnSpectatorDisconnect() Called when spectator leaves the server
mm_SpectatorThink, //! pfnSpectatorThink() Called when spectator sends a command packet (usercmd_t) mm_SpectatorThink, // pfnSpectatorThink() Called when spectator sends a command packet (usercmd_t)
mm_Sys_Error, //! pfnSys_Error() Notify game .dll that engine is going to shut down. Allows mod authors to set a breakpoint. SDK2 mm_Sys_Error, // pfnSys_Error() Notify game .dll that engine is going to shut down. Allows mod authors to set a breakpoint. SDK2
mm_PM_Move, //! pfnPM_Move() (wd) SDK2 mm_PM_Move, // pfnPM_Move() (wd) SDK2
mm_PM_Init, //! pfnPM_Init() Server version of player movement initialization; (wd) SDK2 mm_PM_Init, // pfnPM_Init() Server version of player movement initialization; (wd) SDK2
mm_PM_FindTextureType, //! pfnPM_FindTextureType() (wd) SDK2 mm_PM_FindTextureType, // pfnPM_FindTextureType() (wd) SDK2
mm_SetupVisibility, //! pfnSetupVisibility() Set up PVS and PAS for networking for this client; (wd) SDK2 mm_SetupVisibility, // pfnSetupVisibility() Set up PVS and PAS for networking for this client; (wd) SDK2
mm_UpdateClientData, //! pfnUpdateClientData() Set up data sent only to specific client; (wd) SDK2 mm_UpdateClientData, // pfnUpdateClientData() Set up data sent only to specific client; (wd) SDK2
mm_AddToFullPack, //! pfnAddToFullPack() (wd) SDK2 mm_AddToFullPack, // pfnAddToFullPack() (wd) SDK2
mm_CreateBaseline, //! pfnCreateBaseline() Tweak entity baseline for network encoding, allows setup of player baselines, too.; (wd) SDK2 mm_CreateBaseline, // pfnCreateBaseline() Tweak entity baseline for network encoding, allows setup of player baselines, too.; (wd) SDK2
mm_RegisterEncoders, //! pfnRegisterEncoders() Callbacks for network encoding; (wd) SDK2 mm_RegisterEncoders, // pfnRegisterEncoders() Callbacks for network encoding; (wd) SDK2
mm_GetWeaponData, //! pfnGetWeaponData() (wd) SDK2 mm_GetWeaponData, // pfnGetWeaponData() (wd) SDK2
mm_CmdStart, //! pfnCmdStart() (wd) SDK2 mm_CmdStart, // pfnCmdStart() (wd) SDK2
mm_CmdEnd, //! pfnCmdEnd() (wd) SDK2 mm_CmdEnd, // pfnCmdEnd() (wd) SDK2
mm_ConnectionlessPacket, //! pfnConnectionlessPacket() (wd) SDK2 mm_ConnectionlessPacket, // pfnConnectionlessPacket() (wd) SDK2
mm_GetHullBounds, //! pfnGetHullBounds() (wd) SDK2 mm_GetHullBounds, // pfnGetHullBounds() (wd) SDK2
mm_CreateInstancedBaselines, //! pfnCreateInstancedBaselines() (wd) SDK2 mm_CreateInstancedBaselines, // pfnCreateInstancedBaselines() (wd) SDK2
mm_InconsistentFile, //! pfnInconsistentFile() (wd) SDK2 mm_InconsistentFile, // pfnInconsistentFile() (wd) SDK2
mm_AllowLagCompensation, //! pfnAllowLagCompensation() (wd) SDK2 mm_AllowLagCompensation, // pfnAllowLagCompensation() (wd) SDK2
}; };
DLL_FUNCTIONS *pHookedDllFunctions = &sFunctionTable; DLL_FUNCTIONS *pHookedDllFunctions = &sFunctionTable;
@ -414,49 +469,45 @@ DLL_FUNCTIONS *pHookedDllFunctions = &sFunctionTable;
// //
// It's unclear whether a DLL coded under SDK2 needs to provide the older // It's unclear whether a DLL coded under SDK2 needs to provide the older
// GetAPI or not.. // GetAPI or not..
C_DLLEXPORT int GetEntityAPI(DLL_FUNCTIONS *pFunctionTable, int interfaceVersion) C_DLLEXPORT int GetEntityAPI(DLL_FUNCTIONS *pFunctionTable, int interfaceVersion)
{ {
META_DEBUG(3, ("called: GetEntityAPI; version=%d", interfaceVersion)); META_DEBUG(3, ("called: GetEntityAPI; version=%d", interfaceVersion));
if(!pFunctionTable) { if (!pFunctionTable)
{
META_ERROR("GetEntityAPI called with null pFunctionTable"); META_ERROR("GetEntityAPI called with null pFunctionTable");
return(FALSE); return FALSE;
} }
else if(interfaceVersion != INTERFACE_VERSION) { else if (interfaceVersion != INTERFACE_VERSION)
{
META_ERROR("GetEntityAPI version mismatch; requested=%d ours=%d", interfaceVersion, INTERFACE_VERSION); META_ERROR("GetEntityAPI version mismatch; requested=%d ours=%d", interfaceVersion, INTERFACE_VERSION);
return(FALSE); return FALSE;
} }
Q_memcpy(pFunctionTable, &sFunctionTable, sizeof(DLL_FUNCTIONS));
memcpy(pFunctionTable, &sFunctionTable, sizeof(DLL_FUNCTIONS)); return TRUE;
return(TRUE);
} }
C_DLLEXPORT int GetEntityAPI2(DLL_FUNCTIONS *pFunctionTable, int *interfaceVersion) C_DLLEXPORT int GetEntityAPI2(DLL_FUNCTIONS *pFunctionTable, int *interfaceVersion)
{ {
META_DEBUG(3, ("called: GetEntityAPI2; version=%d", *interfaceVersion)); META_DEBUG(3, ("called: GetEntityAPI2; version=%d", *interfaceVersion));
if(!pFunctionTable) { if (!pFunctionTable)
{
META_ERROR("GetEntityAPI2 called with null pFunctionTable"); META_ERROR("GetEntityAPI2 called with null pFunctionTable");
return(FALSE); return FALSE;
} }
else if(*interfaceVersion != INTERFACE_VERSION) { else if (*interfaceVersion != INTERFACE_VERSION)
{
META_ERROR("GetEntityAPI2 version mismatch; requested=%d ours=%d", *interfaceVersion, INTERFACE_VERSION); META_ERROR("GetEntityAPI2 version mismatch; requested=%d ours=%d", *interfaceVersion, INTERFACE_VERSION);
//! Tell engine what version we had, so it can figure out who is out of date. //! Tell engine what version we had, so it can figure out who is out of date.
*interfaceVersion = INTERFACE_VERSION; *interfaceVersion = INTERFACE_VERSION;
return(FALSE); return FALSE;
} }
Q_memcpy(pFunctionTable, &sFunctionTable, sizeof(DLL_FUNCTIONS));
memcpy(pFunctionTable, &sFunctionTable, sizeof(DLL_FUNCTIONS)); return TRUE;
return(TRUE);
} }
// I could find _no_ documentation or examples for the intended use of // I could find _no_ documentation or examples for the intended use of
// NEW_DLL_FUNCTIONS. I wouldn't have even _known_ about the // NEW_DLL_FUNCTIONS. I wouldn't have even _known_ about the
// GetNewDLLFunctions() function except for the reference in Adminmod.. It // GetNewDLLFunctions() function except for the reference in Adminmod.. It
@ -468,18 +519,15 @@ C_DLLEXPORT int GetEntityAPI2(DLL_FUNCTIONS *pFunctionTable, int *interfaceVersi
// //
// Interestingly, it appears to be called by the engine _before_ GetAPI. // Interestingly, it appears to be called by the engine _before_ GetAPI.
static meta_new_dll_functions_t sNewFunctionTable ( meta_new_dll_functions_t sNewFunctionTable (
&mm_OnFreeEntPrivateData, //! pfnOnFreeEntPrivateData() Called right before the object's memory is freed. Calls its destructor. &mm_OnFreeEntPrivateData, // pfnOnFreeEntPrivateData() Called right before the object's memory is freed. Calls its destructor.
&mm_GameShutdown, //! pfnGameShutdown() &mm_GameShutdown, // pfnGameShutdown()
&mm_ShouldCollide, //! pfnShouldCollide() &mm_ShouldCollide, // pfnShouldCollide()
// Added 2005-08-11 (no SDK update)
&mm_CvarValue, //! pfnCvarValue() (fz) Obsolete! Use mm_CvarValue2 instead
// Added 2005-11-22 (no SDK update)
&mm_CvarValue2 //! pfnCvarValue2() (fz) When pfnQueryClientCvarValue2() completes it will call
//! pfnCvarValue2() with the request ID supplied earlier, the name of
//! the cvar requested and the value of that cvar.
);
&mm_CvarValue, // pfnCvarValue() (fz) Use mm_CvarValue2 instead
&mm_CvarValue2 // pfnCvarValue2() (fz) When pfnQueryClientCvarValue2() completes it will call
// pfnCvarValue2() with the request ID supplied earlier, the name of the cvar requested and the value of that cvar.
);
NEW_DLL_FUNCTIONS *pHookedNewDllFunctions = &sNewFunctionTable; NEW_DLL_FUNCTIONS *pHookedNewDllFunctions = &sNewFunctionTable;
@ -491,23 +539,22 @@ C_DLLEXPORT int GetNewDLLFunctions(NEW_DLL_FUNCTIONS *pNewFunctionTable, int *in
// them. Otherwise, we're in the position of having to provide answers // them. Otherwise, we're in the position of having to provide answers
// we can't necessarily provide (for instance, ShouldCollide())... // we can't necessarily provide (for instance, ShouldCollide())...
if (!GameDLL.funcs.newapi_table) if (!GameDLL.funcs.newapi_table)
return(FALSE); return FALSE;
#endif #endif
if(!pNewFunctionTable) { if (!pNewFunctionTable)
{
META_ERROR("GetNewDLLFunctions called with null pNewFunctionTable"); META_ERROR("GetNewDLLFunctions called with null pNewFunctionTable");
return(FALSE); return FALSE;
} }
else if(*interfaceVersion != NEW_DLL_FUNCTIONS_VERSION) { else if (*interfaceVersion != NEW_DLL_FUNCTIONS_VERSION)
{
META_ERROR("GetNewDLLFunctions version mismatch; requested=%d ours=%d", *interfaceVersion, NEW_DLL_FUNCTIONS_VERSION); META_ERROR("GetNewDLLFunctions version mismatch; requested=%d ours=%d", *interfaceVersion, NEW_DLL_FUNCTIONS_VERSION);
//! Tell engine what version we had, so it can figure out who is out of date. //! Tell engine what version we had, so it can figure out who is out of date.
*interfaceVersion = NEW_DLL_FUNCTIONS_VERSION; *interfaceVersion = NEW_DLL_FUNCTIONS_VERSION;
return(FALSE); return FALSE;
} }
sNewFunctionTable.copy_to(pNewFunctionTable); sNewFunctionTable.copy_to(pNewFunctionTable);
return TRUE;
return(TRUE);
} }

View File

@ -1,44 +1,7 @@
// vi: set ts=4 sw=4 : #pragma once
// vim: set tw=75 :
// dllapi.h - prototypes and typedefs for Half-Life DLL API routines #include "sdk_util.h"
#include "osdep.h"
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef DLLAPI_H
#define DLLAPI_H
#include "sdk_util.h" // BOOL
#include "osdep.h" // DLLEXPORT, etc
// Typedefs for these are provided in SDK engine/eiface.h, but I didn't // Typedefs for these are provided in SDK engine/eiface.h, but I didn't
// like the names (APIFUNCTION, APIFUNCTION2, NEW_DLL_FUNCTIONS_FN). // like the names (APIFUNCTION, APIFUNCTION2, NEW_DLL_FUNCTIONS_FN).
@ -46,19 +9,11 @@ typedef int (*GETENTITYAPI_FN) (DLL_FUNCTIONS *pFunctionTable, int interfaceVers
typedef int (*GETENTITYAPI2_FN)(DLL_FUNCTIONS *pFunctionTable, int *interfaceVersion); typedef int (*GETENTITYAPI2_FN)(DLL_FUNCTIONS *pFunctionTable, int *interfaceVersion);
typedef int (*GETNEWDLLFUNCTIONS_FN)(NEW_DLL_FUNCTIONS *pFunctionTable, int *interfaceVersion); typedef int (*GETNEWDLLFUNCTIONS_FN)(NEW_DLL_FUNCTIONS *pFunctionTable, int *interfaceVersion);
// From SDK dlls/cbase.h:
C_DLLEXPORT int GetEntityAPI(DLL_FUNCTIONS *pFunctionTable, int interfaceVersion); C_DLLEXPORT int GetEntityAPI(DLL_FUNCTIONS *pFunctionTable, int interfaceVersion);
C_DLLEXPORT int GetEntityAPI2(DLL_FUNCTIONS *pFunctionTable, int *interfaceVersion); C_DLLEXPORT int GetEntityAPI2(DLL_FUNCTIONS *pFunctionTable, int *interfaceVersion);
// No example in SDK..
// From Adminmod dll.cpp:
C_DLLEXPORT int GetNewDLLFunctions(NEW_DLL_FUNCTIONS *pNewFunctionTable, int *interfaceVersion); C_DLLEXPORT int GetNewDLLFunctions(NEW_DLL_FUNCTIONS *pNewFunctionTable, int *interfaceVersion);
extern void mm_GameDLLInit();
// From SDK dlls/game.h:
extern void mm_GameDLLInit( void );
// From SDK dlls/cbase.h:
extern int mm_DispatchSpawn(edict_t *pent); extern int mm_DispatchSpawn(edict_t *pent);
extern void mm_DispatchThink(edict_t *pent); extern void mm_DispatchThink(edict_t *pent);
extern void mm_DispatchUse(edict_t *pentUsed, edict_t *pentOther); extern void mm_DispatchUse(edict_t *pentUsed, edict_t *pentOther);
@ -72,9 +27,7 @@ extern void mm_SaveWriteFields( SAVERESTOREDATA *pSaveData, const char *pname, v
extern void mm_SaveReadFields(SAVERESTOREDATA *pSaveData, const char *pname, void *pBaseData, TYPEDESCRIPTION *pFields, int fieldCount); extern void mm_SaveReadFields(SAVERESTOREDATA *pSaveData, const char *pname, void *pBaseData, TYPEDESCRIPTION *pFields, int fieldCount);
extern void mm_SaveGlobalState(SAVERESTOREDATA *pSaveData); extern void mm_SaveGlobalState(SAVERESTOREDATA *pSaveData);
extern void mm_RestoreGlobalState(SAVERESTOREDATA *pSaveData); extern void mm_RestoreGlobalState(SAVERESTOREDATA *pSaveData);
extern void mm_ResetGlobalState( void ); extern void mm_ResetGlobalState();
// From SDK dlls/client.h:
extern BOOL mm_ClientConnect(edict_t *pEntity, const char *pszName, const char *pszAddress, char szRejectReason[ 128 ]); extern BOOL mm_ClientConnect(edict_t *pEntity, const char *pszName, const char *pszAddress, char szRejectReason[ 128 ]);
extern void mm_ClientDisconnect(edict_t *pEntity); extern void mm_ClientDisconnect(edict_t *pEntity);
extern void mm_ClientKill(edict_t *pEntity); extern void mm_ClientKill(edict_t *pEntity);
@ -82,52 +35,41 @@ extern void mm_ClientPutInServer( edict_t *pEntity );
extern void mm_ClientCommand(edict_t *pEntity); extern void mm_ClientCommand(edict_t *pEntity);
extern void mm_ClientUserInfoChanged(edict_t *pEntity, char *infobuffer); extern void mm_ClientUserInfoChanged(edict_t *pEntity, char *infobuffer);
extern void mm_ServerActivate(edict_t *pEdictList, int edictCount, int clientMax); extern void mm_ServerActivate(edict_t *pEdictList, int edictCount, int clientMax);
extern void mm_ServerDeactivate( void ); extern void mm_ServerDeactivate();
extern void mm_PlayerPreThink(edict_t *pEntity); extern void mm_PlayerPreThink(edict_t *pEntity);
extern void mm_PlayerPostThink(edict_t *pEntity); extern void mm_PlayerPostThink(edict_t *pEntity);
extern void mm_StartFrame( void ); extern void mm_StartFrame();
extern void mm_ParmsNewLevel( void ); extern void mm_ParmsNewLevel();
extern void mm_ParmsChangeLevel( void ); extern void mm_ParmsChangeLevel();
extern const char *mm_GetGameDescription( void ); extern const char *mm_GetGameDescription();
extern void mm_PlayerCustomization(edict_t *pEntity, customization_t *pCust); extern void mm_PlayerCustomization(edict_t *pEntity, customization_t *pCust);
extern void mm_SpectatorConnect (edict_t *pEntity); extern void mm_SpectatorConnect (edict_t *pEntity);
extern void mm_SpectatorDisconnect (edict_t *pEntity); extern void mm_SpectatorDisconnect (edict_t *pEntity);
extern void mm_SpectatorThink (edict_t *pEntity); extern void mm_SpectatorThink (edict_t *pEntity);
extern void mm_Sys_Error(const char *error_string); extern void mm_Sys_Error(const char *error_string);
// From SDK pm_shared/pm_shared.h:
extern void mm_PM_Move(struct playermove_s *ppmove, int server); extern void mm_PM_Move(struct playermove_s *ppmove, int server);
extern void mm_PM_Init(struct playermove_s *ppmove); extern void mm_PM_Init(struct playermove_s *ppmove);
extern char mm_PM_FindTextureType (const char *name); extern char mm_PM_FindTextureType (const char *name);
// From SDK dlls/client.h:
extern void mm_SetupVisibility(edict_t *pViewEntity, edict_t *pClient, unsigned char **pvs, unsigned char **pas); extern void mm_SetupVisibility(edict_t *pViewEntity, edict_t *pClient, unsigned char **pvs, unsigned char **pas);
extern void mm_UpdateClientData (const struct edict_s *ent, int sendweapons, struct clientdata_s *cd); extern void mm_UpdateClientData (const struct edict_s *ent, int sendweapons, struct clientdata_s *cd);
extern int mm_AddToFullPack(struct entity_state_s *state, int e, edict_t *ent, edict_t *host, int hostflags, int player, unsigned char *pSet); extern int mm_AddToFullPack(struct entity_state_s *state, int e, edict_t *ent, edict_t *host, int hostflags, int player, unsigned char *pSet);
extern void mm_CreateBaseline(int player, int eindex, struct entity_state_s *baseline, struct edict_s *entity, int playermodelindex, vec3_t player_mins, vec3_t player_maxs); extern void mm_CreateBaseline(int player, int eindex, struct entity_state_s *baseline, struct edict_s *entity, int playermodelindex, vec3_t player_mins, vec3_t player_maxs);
extern void mm_RegisterEncoders( void ); extern void mm_RegisterEncoders();
extern int mm_GetWeaponData(struct edict_s *player, struct weapon_data_s *info); extern int mm_GetWeaponData(struct edict_s *player, struct weapon_data_s *info);
extern void mm_CmdStart(const edict_t *player, const struct usercmd_s *cmd, unsigned int random_seed); extern void mm_CmdStart(const edict_t *player, const struct usercmd_s *cmd, unsigned int random_seed);
extern void mm_CmdEnd (const edict_t *player); extern void mm_CmdEnd (const edict_t *player);
extern int mm_ConnectionlessPacket(const struct netadr_s *net_from, const char *args, char *response_buffer, int *response_buffer_size); extern int mm_ConnectionlessPacket(const struct netadr_s *net_from, const char *args, char *response_buffer, int *response_buffer_size);
extern int mm_GetHullBounds(int hullnumber, float *mins, float *maxs); extern int mm_GetHullBounds(int hullnumber, float *mins, float *maxs);
extern void mm_CreateInstancedBaselines ( void ); extern void mm_CreateInstancedBaselines ();
extern int mm_InconsistentFile(const edict_t *player, const char *filename, char *disconnect_message); extern int mm_InconsistentFile(const edict_t *player, const char *filename, char *disconnect_message);
extern int mm_AllowLagCompensation( void ); extern int mm_AllowLagCompensation();
// No example from SDK...
extern void mm_OnFreeEntPrivateData(edict_t pEnt); extern void mm_OnFreeEntPrivateData(edict_t pEnt);
extern void mm_GameShutdown(void); extern void mm_GameShutdown();
extern int mm_ShouldCollide(edict_t *pentTouched, edict_t *pentOther); extern int mm_ShouldCollide(edict_t *pentTouched, edict_t *pentOther);
//Added 2005-08-11 (no SDK update) extern void mm_CvarValue(const edict_t *pEnt, const char *value);
extern void mm_CvarValue(const edict_t *pEnt, const char *value); //! Obsolete! Use mm_CvarValue2 instead
//Added 2005-11-22 (no SDK update)
extern void mm_CvarValue2(const edict_t *pEnt, int requestID, const char *cvarName, const char *value); extern void mm_CvarValue2(const edict_t *pEnt, int requestID, const char *cvarName, const char *value);
typedef void (*FN_GAMEINIT)();
// Typedefs for the above functions:
typedef void (*FN_GAMEINIT) ( void );
typedef int (*FN_DISPATCHSPAWN)(edict_t *pent); typedef int (*FN_DISPATCHSPAWN)(edict_t *pent);
typedef void (*FN_DISPATCHTHINK)(edict_t *pent); typedef void (*FN_DISPATCHTHINK)(edict_t *pent);
typedef void (*FN_DISPATCHUSE)(edict_t *pentUsed, edict_t *pentOther); typedef void (*FN_DISPATCHUSE)(edict_t *pentUsed, edict_t *pentOther);
@ -141,8 +83,7 @@ typedef void (*FN_SAVEWRITEFIELDS) ( SAVERESTOREDATA *pSaveData, const char *pna
typedef void (*FN_SAVEREADFIELDS)(SAVERESTOREDATA *pSaveData, const char *pname, void *pBaseData, TYPEDESCRIPTION *pFields, int fieldCount); typedef void (*FN_SAVEREADFIELDS)(SAVERESTOREDATA *pSaveData, const char *pname, void *pBaseData, TYPEDESCRIPTION *pFields, int fieldCount);
typedef void (*FN_SAVEGLOBALSTATE)(SAVERESTOREDATA *pSaveData); typedef void (*FN_SAVEGLOBALSTATE)(SAVERESTOREDATA *pSaveData);
typedef void (*FN_RESTOREGLOBALSTATE)(SAVERESTOREDATA *pSaveData); typedef void (*FN_RESTOREGLOBALSTATE)(SAVERESTOREDATA *pSaveData);
typedef void (*FN_RESETGLOBALSTATE) ( void ); typedef void (*FN_RESETGLOBALSTATE)();
typedef BOOL (*FN_CLIENTCONNECT)(edict_t *pEntity, const char *pszName, const char *pszAddress, char szRejectReason[ 128 ]); typedef BOOL (*FN_CLIENTCONNECT)(edict_t *pEntity, const char *pszName, const char *pszAddress, char szRejectReason[ 128 ]);
typedef void (*FN_CLIENTDISCONNECT)(edict_t *pEntity); typedef void (*FN_CLIENTDISCONNECT)(edict_t *pEntity);
typedef void (*FN_CLIENTKILL)(edict_t *pEntity); typedef void (*FN_CLIENTKILL)(edict_t *pEntity);
@ -150,43 +91,36 @@ typedef void (*FN_CLIENTPUTINSERVER) ( edict_t *pEntity );
typedef void (*FN_CLIENTCOMMAND)(edict_t *pEntity); typedef void (*FN_CLIENTCOMMAND)(edict_t *pEntity);
typedef void (*FN_CLIENTUSERINFOCHANGED)(edict_t *pEntity, char *infobuffer); typedef void (*FN_CLIENTUSERINFOCHANGED)(edict_t *pEntity, char *infobuffer);
typedef void (*FN_SERVERACTIVATE)(edict_t *pEdictList, int edictCount, int clientMax); typedef void (*FN_SERVERACTIVATE)(edict_t *pEdictList, int edictCount, int clientMax);
typedef void (*FN_SERVERDEACTIVATE) ( void ); typedef void (*FN_SERVERDEACTIVATE)();
typedef void (*FN_PLAYERPRETHINK)(edict_t *pEntity); typedef void (*FN_PLAYERPRETHINK)(edict_t *pEntity);
typedef void (*FN_PLAYERPOSTTHINK)(edict_t *pEntity); typedef void (*FN_PLAYERPOSTTHINK)(edict_t *pEntity);
typedef void (*FN_STARTFRAME) ( void ); typedef void (*FN_STARTFRAME)();
typedef void (*FN_PARMSNEWLEVEL) ( void ); typedef void (*FN_PARMSNEWLEVEL)();
typedef void (*FN_PARMSCHANGELEVEL) ( void ); typedef void (*FN_PARMSCHANGELEVEL)();
typedef const char *(*FN_GETGAMEDESCRIPTION) ( void ); typedef const char *(*FN_GETGAMEDESCRIPTION)();
typedef void (*FN_PLAYERCUSTOMIZATION)(edict_t *pEntity, customization_t *pCust); typedef void (*FN_PLAYERCUSTOMIZATION)(edict_t *pEntity, customization_t *pCust);
typedef void (*FN_SPECTATORCONNECT) (edict_t *pEntity); typedef void (*FN_SPECTATORCONNECT) (edict_t *pEntity);
typedef void (*FN_SPECTATORDISCONNECT) (edict_t *pEntity); typedef void (*FN_SPECTATORDISCONNECT) (edict_t *pEntity);
typedef void (*FN_SPECTATORTHINK) (edict_t *pEntity); typedef void (*FN_SPECTATORTHINK) (edict_t *pEntity);
typedef void (*FN_SYS_ERROR)(const char *error_string); typedef void (*FN_SYS_ERROR)(const char *error_string);
typedef void (*FN_PM_MOVE)(struct playermove_s *ppmove, int server); typedef void (*FN_PM_MOVE)(struct playermove_s *ppmove, int server);
typedef void (*FN_PM_INIT)(struct playermove_s *ppmove); typedef void (*FN_PM_INIT)(struct playermove_s *ppmove);
typedef char (*FN_PM_FINDTEXTURETYPE)(char *name); typedef char (*FN_PM_FINDTEXTURETYPE)(char *name);
typedef void (*FN_SETUPVISIBILITY)(edict_t *pViewEntity, edict_t *pClient, unsigned char **pvs, unsigned char **pas); typedef void (*FN_SETUPVISIBILITY)(edict_t *pViewEntity, edict_t *pClient, unsigned char **pvs, unsigned char **pas);
typedef void (*FN_UPDATECLIENTDATA) (const struct edict_s *ent, int sendweapons, struct clientdata_s *cd); typedef void (*FN_UPDATECLIENTDATA) (const struct edict_s *ent, int sendweapons, struct clientdata_s *cd);
typedef int (*FN_ADDTOFULLPACK)(struct entity_state_s *state, int e, edict_t *ent, edict_t *host, int hostflags, int player, unsigned char *pSet); typedef int (*FN_ADDTOFULLPACK)(struct entity_state_s *state, int e, edict_t *ent, edict_t *host, int hostflags, int player, unsigned char *pSet);
typedef void (*FN_CREATEBASELINE)(int player, int eindex, struct entity_state_s *baseline, struct edict_s *entity, int playermodelindex, vec3_t player_mins, vec3_t player_maxs); typedef void (*FN_CREATEBASELINE)(int player, int eindex, struct entity_state_s *baseline, struct edict_s *entity, int playermodelindex, vec3_t player_mins, vec3_t player_maxs);
typedef void (*FN_REGISTERENCODERS) ( void ); typedef void (*FN_REGISTERENCODERS)();
typedef int (*FN_GETWEAPONDATA)(struct edict_s *player, struct weapon_data_s *info); typedef int (*FN_GETWEAPONDATA)(struct edict_s *player, struct weapon_data_s *info);
typedef void (*FN_CMDSTART)(const edict_t *player, const struct usercmd_s *cmd, unsigned int random_seed); typedef void (*FN_CMDSTART)(const edict_t *player, const struct usercmd_s *cmd, unsigned int random_seed);
typedef void (*FN_CMDEND) (const edict_t *player); typedef void (*FN_CMDEND) (const edict_t *player);
typedef int (*FN_CONNECTIONLESSPACKET)(const struct netadr_s *net_from, const char *args, char *response_buffer, int *response_buffer_size); typedef int (*FN_CONNECTIONLESSPACKET)(const struct netadr_s *net_from, const char *args, char *response_buffer, int *response_buffer_size);
typedef int (*FN_GETHULLBOUNDS)(int hullnumber, float *mins, float *maxs); typedef int (*FN_GETHULLBOUNDS)(int hullnumber, float *mins, float *maxs);
typedef void (*FN_CREATEINSTANCEDBASELINES) ( void ); typedef void (*FN_CREATEINSTANCEDBASELINES) ();
typedef int (*FN_INCONSISTENTFILE)(const edict_t *player, const char *filename, char *disconnect_message); typedef int (*FN_INCONSISTENTFILE)(const edict_t *player, const char *filename, char *disconnect_message);
typedef int (*FN_ALLOWLAGCOMPENSATION) ( void ); typedef int (*FN_ALLOWLAGCOMPENSATION)();
typedef void (*FN_ONFREEENTPRIVATEDATA)(edict_t *pEnt); typedef void (*FN_ONFREEENTPRIVATEDATA)(edict_t *pEnt);
typedef void (*FN_GAMESHUTDOWN) (void); typedef void (*FN_GAMESHUTDOWN)();
typedef int (*FN_SHOULDCOLLIDE)(edict_t *pentTouched, edict_t *pentOther); typedef int (*FN_SHOULDCOLLIDE)(edict_t *pentTouched, edict_t *pentOther);
//Added 2005-08-11 (no SDK update)
typedef void (*FN_CVARVALUE)(const edict_t *pEnt, const char *value); //! Obsolete! Use FN_CVARVALUE2 instead typedef void (*FN_CVARVALUE)(const edict_t *pEnt, const char *value); //! Obsolete! Use FN_CVARVALUE2 instead
//Added 2005-11-22 (no SDK update)
typedef void (*FN_CVARVALUE2)(const edict_t *pEnt, int requestID, const char *cvarName, const char *value); typedef void (*FN_CVARVALUE2)(const edict_t *pEnt, int requestID, const char *cvarName, const char *value);
#endif /* DLLAPI_H */

File diff suppressed because it is too large Load Diff

View File

@ -1,41 +1,4 @@
// vi: set ts=4 sw=4 : #pragma once
// vim: set tw=75 :
// engine_api.h - prototypes and typedefs for Half-Life engine functions
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef ENGINE_API_H
#define ENGINE_API_H
#include <archtypes.h> #include <archtypes.h>
@ -43,8 +6,7 @@
typedef int (*GET_ENGINE_FUNCTIONS_FN)(enginefuncs_t *pengfuncsFromEngine, int *interfaceVersion); typedef int (*GET_ENGINE_FUNCTIONS_FN)(enginefuncs_t *pengfuncsFromEngine, int *interfaceVersion);
// According to SDK engine/eiface.h: // According to SDK engine/eiface.h:
//! enginefuncs_t // ONLY ADD NEW FUNCTIONS TO THE END OF THIS STRUCT. INTERFACE VERSION IS FROZEN AT 138
//! ONLY ADD NEW FUNCTIONS TO THE END OF THIS STRUCT. INTERFACE VERSION IS FROZEN AT 138
#define ENGINE_INTERFACE_VERSION 138 #define ENGINE_INTERFACE_VERSION 138
// Protect against other projects which use this include file but use the // Protect against other projects which use this include file but use the
@ -56,7 +18,6 @@ extern meta_enginefuncs_t meta_engfuncs;
extern enginefuncs_t meta_engfuncs; extern enginefuncs_t meta_engfuncs;
#endif #endif
// From SDK engine/eiface.h:
extern int mm_PrecacheModel(const char *s); extern int mm_PrecacheModel(const char *s);
extern int mm_PrecacheSound(const char *s); extern int mm_PrecacheSound(const char *s);
extern void mm_SetModel(edict_t *e, const char *m); extern void mm_SetModel(edict_t *e, const char *m);
@ -83,7 +44,7 @@ extern edict_t *mm_EntitiesInPVS(edict_t *pplayer);
extern void mm_MakeVectors(const float *rgflVector); extern void mm_MakeVectors(const float *rgflVector);
extern void mm_AngleVectors(const float *rgflVector, float *forward, float *right, float *up); extern void mm_AngleVectors(const float *rgflVector, float *forward, float *right, float *up);
extern edict_t *mm_CreateEntity(void); extern edict_t *mm_CreateEntity();
extern void mm_RemoveEntity(edict_t *e); extern void mm_RemoveEntity(edict_t *e);
extern edict_t *mm_CreateNamedEntity(int className); extern edict_t *mm_CreateNamedEntity(int className);
@ -107,7 +68,7 @@ extern void mm_TraceSphere(const float *v1, const float *v2, int fNoMonsters, fl
extern void mm_GetAimVector(edict_t *ent, float speed, float *rgflReturn); extern void mm_GetAimVector(edict_t *ent, float speed, float *rgflReturn);
extern void mm_ServerCommand(const char *str); extern void mm_ServerCommand(const char *str);
extern void mm_ServerExecute(void); extern void mm_ServerExecute();
extern void ClientCommand(edict_t *pEdict, const char *szFmt, ...); extern void ClientCommand(edict_t *pEdict, const char *szFmt, ...);
extern void mm_ParticleEffect(const float *org, const float *dir, float color, float count); extern void mm_ParticleEffect(const float *org, const float *dir, float color, float count);
@ -116,7 +77,7 @@ extern int mm_DecalIndex(const char *name);
extern int mm_PointContents(const float *rgflVector); extern int mm_PointContents(const float *rgflVector);
extern void mm_MessageBegin(int msg_dest, int msg_type, const float *pOrigin, edict_t *ed); extern void mm_MessageBegin(int msg_dest, int msg_type, const float *pOrigin, edict_t *ed);
extern void mm_MessageEnd(void); extern void mm_MessageEnd();
extern void mm_WriteByte(int iValue); extern void mm_WriteByte(int iValue);
extern void mm_WriteChar(int iValue); extern void mm_WriteChar(int iValue);
@ -134,17 +95,8 @@ extern void mm_CVarSetFloat(const char *szVarName, float flValue);
extern void mm_CVarSetString(const char *szVarName, const char *szValue); extern void mm_CVarSetString(const char *szVarName, const char *szValue);
extern void mm_AlertMessage(ALERT_TYPE atype, const char *szFmt, ...); extern void mm_AlertMessage(ALERT_TYPE atype, const char *szFmt, ...);
#ifdef HLSDK_3_2_OLD_EIFACE
extern void mm_EngineFprintf(FILE *pfile, const char *szFmt, ...);
#else
extern void mm_EngineFprintf(void *pfile, const char *szFmt, ...); extern void mm_EngineFprintf(void *pfile, const char *szFmt, ...);
#endif
#ifdef HLSDK_3_2_OLD_EIFACE
extern void *mm_PvAllocEntPrivateData(edict_t *pEdict, long cb);
#else
extern void *mm_PvAllocEntPrivateData(edict_t *pEdict, int32 cb); extern void *mm_PvAllocEntPrivateData(edict_t *pEdict, int32 cb);
#endif
extern void *mm_PvEntPrivateData(edict_t *pEdict); extern void *mm_PvEntPrivateData(edict_t *pEdict);
extern void mm_FreeEntPrivateData(edict_t *pEdict); extern void mm_FreeEntPrivateData(edict_t *pEdict);
@ -164,20 +116,15 @@ extern int mm_RegUserMsg(const char *pszName, int iSize);
extern void mm_AnimationAutomove(const edict_t *pEdict, float flTime); extern void mm_AnimationAutomove(const edict_t *pEdict, float flTime);
extern void mm_GetBonePosition(const edict_t *pEdict, int iBone, float *rgflOrigin, float *rgflAngles); extern void mm_GetBonePosition(const edict_t *pEdict, int iBone, float *rgflOrigin, float *rgflAngles);
#ifdef HLSDK_3_2_OLD_EIFACE
extern unsigned long mm_FunctionFromName( const char *pName );
extern const char *mm_NameForFunction( unsigned long function );
#else
extern uint32 mm_FunctionFromName(const char *pName); extern uint32 mm_FunctionFromName(const char *pName);
extern const char *mm_NameForFunction(uint32 function); extern const char *mm_NameForFunction(uint32 function);
#endif
extern void mm_ClientPrintf(edict_t *pEdict, PRINT_TYPE ptype, const char *szMsg); //! JOHN: engine callbacks so game DLL can print messages to individual clients extern void mm_ClientPrintf(edict_t *pEdict, PRINT_TYPE ptype, const char *szMsg); //! JOHN: engine callbacks so game DLL can print messages to individual clients
extern void mm_ServerPrint(const char *szMsg); extern void mm_ServerPrint(const char *szMsg);
extern const char *mm_Cmd_Args( void ); //! these 3 added extern const char *mm_Cmd_Args(); //! these 3 added
extern const char *mm_Cmd_Argv(int argc); //! so game DLL can easily extern const char *mm_Cmd_Argv(int argc); //! so game DLL can easily
extern int mm_Cmd_Argc( void ); //! access client 'cmd' strings extern int mm_Cmd_Argc(); //! access client 'cmd' strings
extern void mm_GetAttachment(const edict_t *pEdict, int iAttachment, float *rgflOrigin, float *rgflAngles); extern void mm_GetAttachment(const edict_t *pEdict, int iAttachment, float *rgflOrigin, float *rgflAngles);
@ -186,15 +133,11 @@ extern void mm_CRC32_ProcessBuffer(CRC32_t *pulCRC, void *p, int len);
extern void mm_CRC32_ProcessByte(CRC32_t *pulCRC, unsigned char ch); extern void mm_CRC32_ProcessByte(CRC32_t *pulCRC, unsigned char ch);
extern CRC32_t mm_CRC32_Final(CRC32_t pulCRC); extern CRC32_t mm_CRC32_Final(CRC32_t pulCRC);
#ifdef HLSDK_3_2_OLD_EIFACE
extern long mm_RandomLong(long lLow, long lHigh);
#else
extern int32 mm_RandomLong(int32 lLow, int32 lHigh); extern int32 mm_RandomLong(int32 lLow, int32 lHigh);
#endif
extern float mm_RandomFloat(float flLow, float flHigh); extern float mm_RandomFloat(float flLow, float flHigh);
extern void mm_SetView(const edict_t *pClient, const edict_t *pViewent); extern void mm_SetView(const edict_t *pClient, const edict_t *pViewent);
extern float mm_Time( void ); extern float mm_Time();
extern void mm_CrosshairAngle(const edict_t *pClient, float pitch, float yaw); extern void mm_CrosshairAngle(const edict_t *pClient, float pitch, float yaw);
extern byte *mm_LoadFileForMe(const char *filename, int *pLength); extern byte *mm_LoadFileForMe(const char *filename, int *pLength);
@ -208,7 +151,7 @@ extern void mm_FadeClientVolume(const edict_t *pEdict, int fadePercent, int fade
extern void mm_SetClientMaxspeed(const edict_t *pEdict, float fNewMaxspeed); extern void mm_SetClientMaxspeed(const edict_t *pEdict, float fNewMaxspeed);
extern edict_t *mm_CreateFakeClient(const char *netname); //! returns NULL if fake client can't be created extern edict_t *mm_CreateFakeClient(const char *netname); //! returns NULL if fake client can't be created
extern void mm_RunPlayerMove(edict_t *fakeclient, const float *viewangles, float forwardmove, float sidemove, float upmove, unsigned short buttons, byte impulse, byte msec); extern void mm_RunPlayerMove(edict_t *fakeclient, const float *viewangles, float forwardmove, float sidemove, float upmove, unsigned short buttons, byte impulse, byte msec);
extern int mm_NumberOfEntities(void); extern int mm_NumberOfEntities();
extern char *mm_GetInfoKeyBuffer(edict_t *e); //! passing in NULL gets the serverinfo extern char *mm_GetInfoKeyBuffer(edict_t *e); //! passing in NULL gets the serverinfo
extern char *mm_InfoKeyValue(char *infobuffer, const char *key); extern char *mm_InfoKeyValue(char *infobuffer, const char *key);
@ -220,72 +163,59 @@ extern void mm_StaticDecal( const float *origin, int decalIndex, int entityIndex
extern int mm_PrecacheGeneric(const char *s); extern int mm_PrecacheGeneric(const char *s);
extern int mm_GetPlayerUserId(edict_t *e); //! returns the server assigned userid for this player. useful for logging frags, etc. returns -1 if the edict couldn't be found in the list of clients extern int mm_GetPlayerUserId(edict_t *e); //! returns the server assigned userid for this player. useful for logging frags, etc. returns -1 if the edict couldn't be found in the list of clients
extern void mm_BuildSoundMsg(edict_t *entity, int channel, const char *sample, /*int*/float volume, float attenuation, int fFlags, int pitch, int msg_dest, int msg_type, const float *pOrigin, edict_t *ed); extern void mm_BuildSoundMsg(edict_t *entity, int channel, const char *sample, /*int*/float volume, float attenuation, int fFlags, int pitch, int msg_dest, int msg_type, const float *pOrigin, edict_t *ed);
extern int mm_IsDedicatedServer(void);//! is this a dedicated server? extern int mm_IsDedicatedServer();//! is this a dedicated server?
extern cvar_t *mm_CVarGetPointer(const char *szVarName); extern cvar_t *mm_CVarGetPointer(const char *szVarName);
extern unsigned int mm_GetPlayerWONId(edict_t *e); //! returns the server assigned WONid for this player. useful for logging frags, etc. returns -1 if the edict couldn't be found in the list of clients extern unsigned int mm_GetPlayerWONId(edict_t *e); //! returns the server assigned WONid for this player. useful for logging frags, etc. returns -1 if the edict couldn't be found in the list of clients
//! YWB 8/1/99 TFF Physics additions // 8/1/99 TFF Physics additions
extern void mm_Info_RemoveKey(char *s, const char *key); extern void mm_Info_RemoveKey(char *s, const char *key);
extern const char *mm_GetPhysicsKeyValue(const edict_t *pClient, const char *key); extern const char *mm_GetPhysicsKeyValue(const edict_t *pClient, const char *key);
extern void mm_SetPhysicsKeyValue(const edict_t *pClient, const char *key, const char *value); extern void mm_SetPhysicsKeyValue(const edict_t *pClient, const char *key, const char *value);
extern const char *mm_GetPhysicsInfoString(const edict_t *pClient); extern const char *mm_GetPhysicsInfoString(const edict_t *pClient);
extern unsigned short mm_PrecacheEvent(int type, const char *psz); extern unsigned short mm_PrecacheEvent(int type, const char *psz);
extern void mm_PlaybackEvent(int flags, const edict_t *pInvoker, unsigned short eventindex, float delay, float *origin, float *angles, float fparam1, float fparam2, int iparam1, int iparam2, int bparam1, int bparam2); extern void mm_PlaybackEvent(int flags, const edict_t *pInvoker, unsigned short eventindex, float delay, float *origin, float *angles, float fparam1, float fparam2, int iparam1, int iparam2, int bparam1, int bparam2);
extern unsigned char *mm_SetFatPVS(float *org); extern unsigned char *mm_SetFatPVS(float *org);
extern unsigned char *mm_SetFatPAS(float *org); extern unsigned char *mm_SetFatPAS(float *org);
extern int mm_CheckVisibility(edict_t *entity, unsigned char *pset); extern int mm_CheckVisibility(edict_t *entity, unsigned char *pset);
extern void mm_DeltaSetField(struct delta_s *pFields, const char *fieldname); extern void mm_DeltaSetField(struct delta_s *pFields, const char *fieldname);
extern void mm_DeltaUnsetField(struct delta_s *pFields, const char *fieldname); extern void mm_DeltaUnsetField(struct delta_s *pFields, const char *fieldname);
extern void mm_DeltaAddEncoder(const char *name, void (*conditionalencode)(struct delta_s *pFields, const unsigned char *from, const unsigned char *to)); extern void mm_DeltaAddEncoder(const char *name, void (*conditionalencode)(struct delta_s *pFields, const unsigned char *from, const unsigned char *to));
extern int mm_GetCurrentPlayer( void ); extern int mm_GetCurrentPlayer();
extern int mm_CanSkipPlayer(const edict_t *player); extern int mm_CanSkipPlayer(const edict_t *player);
extern int mm_DeltaFindField(struct delta_s *pFields, const char *fieldname); extern int mm_DeltaFindField(struct delta_s *pFields, const char *fieldname);
extern void mm_DeltaSetFieldByIndex(struct delta_s *pFields, int fieldNumber); extern void mm_DeltaSetFieldByIndex(struct delta_s *pFields, int fieldNumber);
extern void mm_DeltaUnsetFieldByIndex(struct delta_s *pFields, int fieldNumber); extern void mm_DeltaUnsetFieldByIndex(struct delta_s *pFields, int fieldNumber);
extern void mm_SetGroupMask(int mask, int op); extern void mm_SetGroupMask(int mask, int op);
extern int CreateInstancedBaseline(int classname, struct entity_state_s *baseline); extern int CreateInstancedBaseline(int classname, struct entity_state_s *baseline);
extern void mm_Cvar_DirectSet(struct cvar_s *var, const char *value); extern void mm_Cvar_DirectSet(struct cvar_s *var, const char *value);
//! Forces the client and server to be running with the same version of the specified file // Forces the client and server to be running with the same version of the specified file e.g., a player model).
//!( e.g., a player model ). // Calling this has no effect in single player
//! Calling this has no effect in single player
extern void mm_ForceUnmodified(FORCE_TYPE type, float *mins, float *maxs, const char *filename); extern void mm_ForceUnmodified(FORCE_TYPE type, float *mins, float *maxs, const char *filename);
extern void mm_GetPlayerStats(const edict_t *pClient, int *ping, int *packet_loss); extern void mm_GetPlayerStats(const edict_t *pClient, int *ping, int *packet_loss);
extern void mm_AddServerCommand( const char *cmd_name, void (*function) (void) ); extern void mm_AddServerCommand(const char *cmd_name, void (*function)());
// Added in SDK 2.2:
extern qboolean mm_Voice_GetClientListening(int iReceiver, int iSender); extern qboolean mm_Voice_GetClientListening(int iReceiver, int iSender);
extern qboolean mm_Voice_SetClientListening(int iReceiver, int iSender, qboolean bListen); extern qboolean mm_Voice_SetClientListening(int iReceiver, int iSender, qboolean bListen);
// Added for HL 1109 (no SDK update):
extern const char *mm_pfnGetPlayerAuthId(edict_t *e); extern const char *mm_pfnGetPlayerAuthId(edict_t *e);
// Added 2003-11-10 (no SDK update):
extern sequenceEntry_s *mm_SequenceGet(const char *fileName, const char *entryName); extern sequenceEntry_s *mm_SequenceGet(const char *fileName, const char *entryName);
extern sentenceEntry_s *mm_SequencePickSentence(const char *groupName, int pickMethod, int *picked); extern sentenceEntry_s *mm_SequencePickSentence(const char *groupName, int pickMethod, int *picked);
extern int mm_GetFileSize(const char *filename); extern int mm_GetFileSize(const char *filename);
extern unsigned int mm_GetApproxWavePlayLen(const char *filepath); extern unsigned int mm_GetApproxWavePlayLen(const char *filepath);
extern int mm_IsCareerMatch(void); extern int mm_IsCareerMatch();
extern int mm_GetLocalizedStringLength(const char *label); extern int mm_GetLocalizedStringLength(const char *label);
extern void mm_RegisterTutorMessageShown(int mid); extern void mm_RegisterTutorMessageShown(int mid);
extern int mm_GetTimesTutorMessageShown(int mid); extern int mm_GetTimesTutorMessageShown(int mid);
extern void mm_ProcessTutorMessageDecayBuffer(int *buffer, int bufferLength); extern void mm_ProcessTutorMessageDecayBuffer(int *buffer, int bufferLength);
extern void mm_ConstructTutorMessageDecayBuffer(int *buffer, int bufferLength); extern void mm_ConstructTutorMessageDecayBuffer(int *buffer, int bufferLength);
extern void mm_ResetTutorMessageDecayData(void); extern void mm_ResetTutorMessageDecayData();
//Added 2005-08-11 (no SDK update)
extern void mm_QueryClientCvarValue(const edict_t *pEdict, const char *cvarName); //! Obsolete! Use mm_QueryClientCvarValue2 instead extern void mm_QueryClientCvarValue(const edict_t *pEdict, const char *cvarName); //! Obsolete! Use mm_QueryClientCvarValue2 instead
//Added 2005-11-22 (no SDK update)
extern void mm_QueryClientCvarValue2(const edict_t *pEdict, const char *cvarName, int requestID); extern void mm_QueryClientCvarValue2(const edict_t *pEdict, const char *cvarName, int requestID);
//Added 2009-06-17 (no SDK update)
extern int mm_EngCheckParm(const char *pchCmdLineToken, char **ppnext); extern int mm_EngCheckParm(const char *pchCmdLineToken, char **ppnext);
// Typedefs for the above functions: // Typedefs for the above functions:
typedef int (*FN_PRECACHEMODEL)(const char *s); typedef int (*FN_PRECACHEMODEL)(const char *s);
typedef int (*FN_PRECACHESOUND)(const char *s); typedef int (*FN_PRECACHESOUND)(const char *s);
typedef void (*FN_SETMODEL)(edict_t *e, const char *m); typedef void (*FN_SETMODEL)(edict_t *e, const char *m);
@ -307,7 +237,7 @@ typedef edict_t * (*FN_FINDCLIENTINPVS) (edict_t *pEdict);
typedef edict_t *(*FN_ENTITIESINPVS)(edict_t *pplayer); typedef edict_t *(*FN_ENTITIESINPVS)(edict_t *pplayer);
typedef void (*FN_MAKEVECTORS)(const float *rgflVector); typedef void (*FN_MAKEVECTORS)(const float *rgflVector);
typedef void (*FN_ANGLEVECTORS)(const float *rgflVector, float *forward, float *right, float *up); typedef void (*FN_ANGLEVECTORS)(const float *rgflVector, float *forward, float *right, float *up);
typedef edict_t * (*FN_CREATEENTITY) (void); typedef edict_t *(*FN_CREATEENTITY)();
typedef void (*FN_REMOVEENTITY)(edict_t *e); typedef void (*FN_REMOVEENTITY)(edict_t *e);
typedef edict_t *(*FN_CREATENAMEDENTITY)(int className); typedef edict_t *(*FN_CREATENAMEDENTITY)(int className);
typedef void (*FN_MAKESTATIC)(edict_t *ent); typedef void (*FN_MAKESTATIC)(edict_t *ent);
@ -326,14 +256,14 @@ typedef const char * (*FN_TRACETEXTURE) (edict_t *pTextureEntity, const float *v
typedef void (*FN_TRACESPHERE)(const float *v1, const float *v2, int fNoMonsters, float radius, edict_t *pentToSkip, TraceResult *ptr); typedef void (*FN_TRACESPHERE)(const float *v1, const float *v2, int fNoMonsters, float radius, edict_t *pentToSkip, TraceResult *ptr);
typedef void (*FN_GETAIMVECTOR)(edict_t *ent, float speed, float *rgflReturn); typedef void (*FN_GETAIMVECTOR)(edict_t *ent, float speed, float *rgflReturn);
typedef void (*FN_SERVERCOMMAND)(char *str); typedef void (*FN_SERVERCOMMAND)(char *str);
typedef void (*FN_SERVEREXECUTE) (void); typedef void (*FN_SERVEREXECUTE)();
typedef void (*FN_CLIENTCOMMAND_ENG)(edict_t *pEdict, char *szFmt, ...); typedef void (*FN_CLIENTCOMMAND_ENG)(edict_t *pEdict, char *szFmt, ...);
typedef void (*FN_PARTICLEEFFECT)(const float *org, const float *dir, float color, float count); typedef void (*FN_PARTICLEEFFECT)(const float *org, const float *dir, float color, float count);
typedef void (*FN_LIGHTSTYLE)(int style, char *val); typedef void (*FN_LIGHTSTYLE)(int style, char *val);
typedef int (*FN_DECALINDEX)(const char *name); typedef int (*FN_DECALINDEX)(const char *name);
typedef int (*FN_POINTCONTENTS)(const float *rgflVector); typedef int (*FN_POINTCONTENTS)(const float *rgflVector);
typedef void (*FN_MESSAGEBEGIN)(int msg_dest, int msg_type, const float *pOrigin, edict_t *ed); typedef void (*FN_MESSAGEBEGIN)(int msg_dest, int msg_type, const float *pOrigin, edict_t *ed);
typedef void (*FN_MESSAGEEND) (void); typedef void (*FN_MESSAGEEND)();
typedef void (*FN_WRITEBYTE)(int iValue); typedef void (*FN_WRITEBYTE)(int iValue);
typedef void (*FN_WRITECHAR)(int iValue); typedef void (*FN_WRITECHAR)(int iValue);
typedef void (*FN_WRITESHORT)(int iValue); typedef void (*FN_WRITESHORT)(int iValue);
@ -348,13 +278,8 @@ typedef const char * (*FN_CVARGETSTRING) (const char *szVarName);
typedef void (*FN_CVARSETFLOAT)(const char *szVarName, float flValue); typedef void (*FN_CVARSETFLOAT)(const char *szVarName, float flValue);
typedef void (*FN_CVARSETSTRING)(const char *szVarName, const char *szValue); typedef void (*FN_CVARSETSTRING)(const char *szVarName, const char *szValue);
typedef void (*FN_ALERTMESSAGE)(ALERT_TYPE atype, const char *szFmt, ...); typedef void (*FN_ALERTMESSAGE)(ALERT_TYPE atype, const char *szFmt, ...);
#ifdef HLSDK_3_2_OLD_EIFACE
typedef void (*FN_ENGINEFPRINTF) (FILE *pfile, const char *szFmt, ...);
typedef void * (*FN_PVALLOCENTPRIVATEDATA) (edict_t *pEdict, long cb);
#else
typedef void (*FN_ENGINEFPRINTF)(void *pfile, const char *szFmt, ...); typedef void (*FN_ENGINEFPRINTF)(void *pfile, const char *szFmt, ...);
typedef void *(*FN_PVALLOCENTPRIVATEDATA)(edict_t *pEdict, int32 cb); typedef void *(*FN_PVALLOCENTPRIVATEDATA)(edict_t *pEdict, int32 cb);
#endif
typedef void *(*FN_PVENTPRIVATEDATA)(edict_t *pEdict); typedef void *(*FN_PVENTPRIVATEDATA)(edict_t *pEdict);
typedef void (*FN_FREEENTPRIVATEDATA)(edict_t *pEdict); typedef void (*FN_FREEENTPRIVATEDATA)(edict_t *pEdict);
typedef const char *(*FN_SZFROMINDEX)(int iString); typedef const char *(*FN_SZFROMINDEX)(int iString);
@ -369,31 +294,22 @@ typedef void * (*FN_GETMODELPTR) (edict_t *pEdict);
typedef int (*FN_REGUSERMSG)(const char *pszName, int iSize); typedef int (*FN_REGUSERMSG)(const char *pszName, int iSize);
typedef void (*FN_ANIMATIONAUTOMOVE)(const edict_t *pEdict, float flTime); typedef void (*FN_ANIMATIONAUTOMOVE)(const edict_t *pEdict, float flTime);
typedef void (*FN_GETBONEPOSITION)(const edict_t *pEdict, int iBone, float *rgflOrigin, float *rgflAngles); typedef void (*FN_GETBONEPOSITION)(const edict_t *pEdict, int iBone, float *rgflOrigin, float *rgflAngles);
#ifdef HLSDK_3_2_OLD_EIFACE
typedef unsigned long (*FN_FUNCTIONFROMNAME) ( const char *pName );
typedef const char * (*FN_NAMEFORFUNCTION) ( unsigned long function );
#else
typedef uint32 (*FN_FUNCTIONFROMNAME)(const char *pName); typedef uint32 (*FN_FUNCTIONFROMNAME)(const char *pName);
typedef const char *(*FN_NAMEFORFUNCTION)(uint32 function); typedef const char *(*FN_NAMEFORFUNCTION)(uint32 function);
#endif
typedef void (*FN_CLIENTPRINTF)(edict_t *pEdict, PRINT_TYPE ptype, const char *szMsg); typedef void (*FN_CLIENTPRINTF)(edict_t *pEdict, PRINT_TYPE ptype, const char *szMsg);
typedef void (*FN_SERVERPRINT)(const char *szMsg); typedef void (*FN_SERVERPRINT)(const char *szMsg);
typedef const char * (*FN_CMD_ARGS) ( void ); typedef const char *(*FN_CMD_ARGS)();
typedef const char *(*FN_CMD_ARGV)(int argc); typedef const char *(*FN_CMD_ARGV)(int argc);
typedef int (*FN_CMD_ARGC) ( void ); typedef int (*FN_CMD_ARGC)();
typedef void (*FN_GETATTACHMENT)(const edict_t *pEdict, int iAttachment, float *rgflOrigin, float *rgflAngles); typedef void (*FN_GETATTACHMENT)(const edict_t *pEdict, int iAttachment, float *rgflOrigin, float *rgflAngles);
typedef void (*FN_CRC32_INIT)(CRC32_t *pulCRC); typedef void (*FN_CRC32_INIT)(CRC32_t *pulCRC);
typedef void (*FN_CRC32_PROCESSBUFFER)(CRC32_t *pulCRC, void *p, int len); typedef void (*FN_CRC32_PROCESSBUFFER)(CRC32_t *pulCRC, void *p, int len);
typedef void (*FN_CRC32_PROCESSBYTE)(CRC32_t *pulCRC, unsigned char ch); typedef void (*FN_CRC32_PROCESSBYTE)(CRC32_t *pulCRC, unsigned char ch);
typedef CRC32_t (*FN_CRC32_FINAL)(CRC32_t pulCRC); typedef CRC32_t (*FN_CRC32_FINAL)(CRC32_t pulCRC);
#ifdef HLSDK_3_2_OLD_EIFACE
typedef long (*FN_RANDOMLONG) (long lLow, long lHigh);
#else
typedef int32 (*FN_RANDOMLONG)(int32 lLow, int32 lHigh); typedef int32 (*FN_RANDOMLONG)(int32 lLow, int32 lHigh);
#endif
typedef float (*FN_RANDOMFLOAT)(float flLow, float flHigh); typedef float (*FN_RANDOMFLOAT)(float flLow, float flHigh);
typedef void (*FN_SETVIEW)(const edict_t *pClient, const edict_t *pViewent); typedef void (*FN_SETVIEW)(const edict_t *pClient, const edict_t *pViewent);
typedef float (*FN_TIME) ( void ); typedef float (*FN_TIME)();
typedef void (*FN_CROSSHAIRANGLE)(const edict_t *pClient, float pitch, float yaw); typedef void (*FN_CROSSHAIRANGLE)(const edict_t *pClient, float pitch, float yaw);
typedef byte *(*FN_LOADFILEFORME)(char *filename, int *pLength); typedef byte *(*FN_LOADFILEFORME)(char *filename, int *pLength);
typedef void (*FN_FREEFILE)(void *buffer); typedef void (*FN_FREEFILE)(void *buffer);
@ -405,7 +321,7 @@ typedef void (*FN_FADECLIENTVOLUME) (const edict_t *pEdict, int fadePercent, int
typedef void (*FN_SETCLIENTMAXSPEED)(edict_t *pEdict, float fNewMaxspeed); typedef void (*FN_SETCLIENTMAXSPEED)(edict_t *pEdict, float fNewMaxspeed);
typedef edict_t *(*FN_CREATEFAKECLIENT)(const char *netname); typedef edict_t *(*FN_CREATEFAKECLIENT)(const char *netname);
typedef void (*FN_RUNPLAYERMOVE)(edict_t *fakeclient, const float *viewangles, float forwardmove, float sidemove, float upmove, unsigned short buttons, byte impulse, byte msec); typedef void (*FN_RUNPLAYERMOVE)(edict_t *fakeclient, const float *viewangles, float forwardmove, float sidemove, float upmove, unsigned short buttons, byte impulse, byte msec);
typedef int (*FN_NUMBEROFENTITIES) (void); typedef int (*FN_NUMBEROFENTITIES)();
typedef char *(*FN_GETINFOKEYBUFFER)(edict_t *e); typedef char *(*FN_GETINFOKEYBUFFER)(edict_t *e);
typedef char *(*FN_INFOKEYVALUE)(char *infobuffer, const char *key); typedef char *(*FN_INFOKEYVALUE)(char *infobuffer, const char *key);
typedef void (*FN_SETKEYVALUE)(char *infobuffer, const char *key, const char *value); typedef void (*FN_SETKEYVALUE)(char *infobuffer, const char *key, const char *value);
@ -415,7 +331,7 @@ typedef void (*FN_STATICDECAL) ( const float *origin, int decalIndex, int entity
typedef int (*FN_PRECACHEGENERIC)(char *s); typedef int (*FN_PRECACHEGENERIC)(char *s);
typedef int (*FN_GETPLAYERUSERID)(edict_t *e); typedef int (*FN_GETPLAYERUSERID)(edict_t *e);
typedef void (*FN_BUILDSOUNDMSG)(edict_t *entity, int channel, const char *sample, /*int*/float volume, float attenuation, int fFlags, int pitch, int msg_dest, int msg_type, const float *pOrigin, edict_t *ed); typedef void (*FN_BUILDSOUNDMSG)(edict_t *entity, int channel, const char *sample, /*int*/float volume, float attenuation, int fFlags, int pitch, int msg_dest, int msg_type, const float *pOrigin, edict_t *ed);
typedef int (*FN_ISDEDICATEDSERVER) (void); typedef int (*FN_ISDEDICATEDSERVER)();
typedef cvar_t *(*FN_CVARGETPOINTER)(const char *szVarName); typedef cvar_t *(*FN_CVARGETPOINTER)(const char *szVarName);
typedef unsigned int (*FN_GETPLAYERWONID)(edict_t *e); typedef unsigned int (*FN_GETPLAYERWONID)(edict_t *e);
typedef void (*FN_INFO_REMOVEKEY)(char *s, const char *key); typedef void (*FN_INFO_REMOVEKEY)(char *s, const char *key);
@ -430,7 +346,7 @@ typedef int (*FN_CHECKVISIBILITY) ( edict_t *entity, unsigned char *pset );
typedef void (*FN_DELTASETFIELD)(struct delta_s *pFields, const char *fieldname); typedef void (*FN_DELTASETFIELD)(struct delta_s *pFields, const char *fieldname);
typedef void (*FN_DELTAUNSETFIELD)(struct delta_s *pFields, const char *fieldname); typedef void (*FN_DELTAUNSETFIELD)(struct delta_s *pFields, const char *fieldname);
typedef void (*FN_DELTAADDENCODER)(char *name, void (*conditionalencode)(struct delta_s *pFields, const unsigned char *from, const unsigned char *to)); typedef void (*FN_DELTAADDENCODER)(char *name, void (*conditionalencode)(struct delta_s *pFields, const unsigned char *from, const unsigned char *to));
typedef int (*FN_GETCURRENTPLAYER) ( void ); typedef int (*FN_GETCURRENTPLAYER)();
typedef int (*FN_CANSKIPPLAYER)(const edict_t *player); typedef int (*FN_CANSKIPPLAYER)(const edict_t *player);
typedef int (*FN_DELTAFINDFIELD)(struct delta_s *pFields, const char *fieldname); typedef int (*FN_DELTAFINDFIELD)(struct delta_s *pFields, const char *fieldname);
typedef void (*FN_DELTASETFIELDBYINDEX)(struct delta_s *pFields, int fieldNumber); typedef void (*FN_DELTASETFIELDBYINDEX)(struct delta_s *pFields, int fieldNumber);
@ -440,29 +356,21 @@ typedef int (*FN_CREATEINSTANCEDBASELINE) ( int classname, struct entity_state_s
typedef void (*FN_CVAR_DIRECTSET)(struct cvar_s *var, const char *value); typedef void (*FN_CVAR_DIRECTSET)(struct cvar_s *var, const char *value);
typedef void (*FN_FORCEUNMODIFIED)(FORCE_TYPE type, float *mins, float *maxs, const char *filename); typedef void (*FN_FORCEUNMODIFIED)(FORCE_TYPE type, float *mins, float *maxs, const char *filename);
typedef void (*FN_GETPLAYERSTATS)(const edict_t *pClient, int *ping, int *packet_loss); typedef void (*FN_GETPLAYERSTATS)(const edict_t *pClient, int *ping, int *packet_loss);
typedef void (*FN_ADDSERVERCOMMAND) ( char *cmd_name, void (*function) (void) ); typedef void (*FN_ADDSERVERCOMMAND)(char *cmd_name, void (*function)());
// Added in SDK 2.2:
typedef qboolean (*FN_VOICE_GETCLIENTLISTENING)(int iReceiver, int iSender); typedef qboolean (*FN_VOICE_GETCLIENTLISTENING)(int iReceiver, int iSender);
typedef qboolean (*FN_VOICE_SETCLIENTLISTENING)(int iReceiver, int iSender, qboolean bListen); typedef qboolean (*FN_VOICE_SETCLIENTLISTENING)(int iReceiver, int iSender, qboolean bListen);
// Added for HL 1109 (no SDK update):
typedef const char *(*FN_GETPLAYERAUTHID)(edict_t *e); typedef const char *(*FN_GETPLAYERAUTHID)(edict_t *e);
// Added 2003-11-10 (no SDK update):
typedef sequenceEntry_s *(*FN_SEQUENCEGET)(const char *fileName, const char *entryName); typedef sequenceEntry_s *(*FN_SEQUENCEGET)(const char *fileName, const char *entryName);
typedef sentenceEntry_s *(*FN_SEQUENCEPICKSENTENCE)(const char *groupName, int pickMethod, int *picked); typedef sentenceEntry_s *(*FN_SEQUENCEPICKSENTENCE)(const char *groupName, int pickMethod, int *picked);
typedef int (*FN_GETFILESIZE)(char *filename); typedef int (*FN_GETFILESIZE)(char *filename);
typedef unsigned int (*FN_GETAPPROXWAVEPLAYLEN)(const char *filepath); typedef unsigned int (*FN_GETAPPROXWAVEPLAYLEN)(const char *filepath);
typedef int (*FN_ISCAREERMATCH) (void); typedef int (*FN_ISCAREERMATCH)();
typedef int (*FN_GETLOCALIZEDSTRINGLENGTH)(const char *label); typedef int (*FN_GETLOCALIZEDSTRINGLENGTH)(const char *label);
typedef void (*FN_REGISTERTUTORMESSAGESHOWN)(int mid); typedef void (*FN_REGISTERTUTORMESSAGESHOWN)(int mid);
typedef int (*FN_GETTIMESTUTORMESSAGESHOWN)(int mid); typedef int (*FN_GETTIMESTUTORMESSAGESHOWN)(int mid);
typedef void (*FN_PROCESSTUTORMESSAGEDECAYBUFFER)(int *buffer, int bufferLength); typedef void (*FN_PROCESSTUTORMESSAGEDECAYBUFFER)(int *buffer, int bufferLength);
typedef void (*FN_CONSTRUCTTUTORMESSAGEDECAYBUFFER)(int *buffer, int bufferLength); typedef void (*FN_CONSTRUCTTUTORMESSAGEDECAYBUFFER)(int *buffer, int bufferLength);
typedef void (*FN_RESETTUTORMESSAGEDECAYDATA) (void); typedef void (*FN_RESETTUTORMESSAGEDECAYDATA)();
//Added 2005-08-11 (no SDK update) typedef void (*FN_QUERYCLIENTCVARVALUE)(const edict_t *pEdict, const char *cvarName); // Use FN_QUERYCLIENTCVARVALUE2 instead
typedef void (*FN_QUERYCLIENTCVARVALUE)(const edict_t *pEdict, const char *cvarName); //! Obsolete! Use FN_QUERYCLIENTCVARVALUE2 instead
//Added 2005-11-22 (no SDK update)
typedef void (*FN_QUERYCLIENTCVARVALUE2)(const edict_t *pEdict, const char *cvarName, int requestID); typedef void (*FN_QUERYCLIENTCVARVALUE2)(const edict_t *pEdict, const char *cvarName, int requestID);
//Added 2009-06-17 (no SDK update)
typedef int (*FN_CHECKPARM)(const char *pchCmdLineToken, char **ppnext); typedef int (*FN_CHECKPARM)(const char *pchCmdLineToken, char **ppnext);
#endif /* ENGINE_API_H */

View File

@ -1,47 +1,11 @@
// vi: set ts=4 sw=4 : #pragma once
// vim: set tw=75 :
// engine_t.h - The engine_t type
/*
* Copyright (c) 2001-2006 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef MM_ENGINE_T_H
#define MM_ENGINE_T_H
#include "eiface.h" // engfuncs_t, globalvars_t #include "eiface.h" // engfuncs_t, globalvars_t
// Our structure for storing engine references. // Our structure for storing engine references.
struct engine_t { struct engine_t
engine_t() : funcs(NULL), globals(NULL), pl_funcs(NULL) {} {
engine_t() : funcs(nullptr), globals(nullptr), pl_funcs(nullptr) {}
enginefuncs_t *funcs; // engine funcs enginefuncs_t *funcs; // engine funcs
globalvars_t *globals; // engine globals globalvars_t *globals; // engine globals
@ -49,6 +13,3 @@ struct engine_t {
}; };
extern engine_t g_engine; extern engine_t g_engine;
#endif /* MM_ENGINE_T_H */

View File

@ -1,41 +1,4 @@
// vi: set ts=4 sw=4 : #pragma once
// vim: set tw=75 :
// enginecallbacks.h - wrapper for <enginecallback.h>
/*
* Copyright (c) 2001-2006 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef MM_ENGINECALLBACKS_H
#define MM_ENGINECALLBACKS_H
// This file is a wrapper around the SDK's enginecallback.h file. We need // This file is a wrapper around the SDK's enginecallback.h file. We need
// this because we use a different type for the global object g_engfuncs, // this because we use a different type for the global object g_engfuncs,
@ -53,17 +16,16 @@
// Use a #define to bend the enginefuncs_t type to our HL_enginefuncs_t // Use a #define to bend the enginefuncs_t type to our HL_enginefuncs_t
// type instead as we now use that for the global object g_engfuncs. // type instead as we now use that for the global object g_engfuncs.
#define enginefuncs_t HL_enginefuncs_t #define enginefuncs_t HL_enginefuncs_t
#endif /* METAMOD_CORE */ #endif
#include <enginecallback.h> // ALERT, etc #include <enginecallback.h> // ALERT, etc
#ifdef METAMOD_CORE #ifdef METAMOD_CORE
#undef enginefuncs_t #undef enginefuncs_t
#endif /* METAMOD_CORE */ #endif
// Also, create some additional macros for engine callback functions, which // Also, create some additional macros for engine callback functions, which
// weren't in SDK dlls/enginecallbacks.h but probably should have been. // weren't in SDK dlls/enginecallbacks.h but probably should have been.
#define GET_INFOKEYBUFFER (*g_engfuncs.pfnGetInfoKeyBuffer) #define GET_INFOKEYBUFFER (*g_engfuncs.pfnGetInfoKeyBuffer)
#define INFOKEY_VALUE (*g_engfuncs.pfnInfoKeyValue) #define INFOKEY_VALUE (*g_engfuncs.pfnInfoKeyValue)
#define SET_CLIENT_KEYVALUE (*g_engfuncs.pfnSetClientKeyValue) #define SET_CLIENT_KEYVALUE (*g_engfuncs.pfnSetClientKeyValue)
@ -72,7 +34,3 @@
#define SET_SERVER_KEYVALUE (*g_engfuncs.pfnSetKeyValue) #define SET_SERVER_KEYVALUE (*g_engfuncs.pfnSetKeyValue)
#define QUERY_CLIENT_CVAR_VALUE (*g_engfuncs.pfnQueryClientCvarValue) #define QUERY_CLIENT_CVAR_VALUE (*g_engfuncs.pfnQueryClientCvarValue)
#define QUERY_CLIENT_CVAR_VALUE2 (*g_engfuncs.pfnQueryClientCvarValue2) #define QUERY_CLIENT_CVAR_VALUE2 (*g_engfuncs.pfnQueryClientCvarValue2)
#endif /* MM_ENGINECALLBACKS_H */

View File

@ -1,109 +1,81 @@
// vi: set ts=4 sw=4 :
// vim: set tw=75 :
// game_support.cpp - info to recognize different HL mod "games"
/*
* Copyright (c) 2001-2013 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#include "precompiled.h" #include "precompiled.h"
// Adapted from adminmod h_export.cpp: // Adapted from adminmod h_export.cpp:
//! this structure contains a list of supported mods and their dlls names //! this structure contains a list of supported mods and their dlls names
//! To add support for another mod add an entry here, and add all the //! To add support for another mod add an entry here, and add all the
//! exported entities to link_func.cpp //! exported entities to link_func.cpp
game_modlist_t known_games = { const game_modinfo_t known_games[] = {
// name/gamedir linux_so win_dll osx_dylib desc // name/gamedir linux_so win_dll desc
// //
// Previously enumerated in this sourcefile, the list is now kept in a // Previously enumerated in this sourcefile, the list is now kept in a
// separate file, generated based on game information stored in a // separate file, generated based on game information stored in a
// convenient db. // convenient db.
// { "cstrike", "cs.so", "mp.dll", "Counter-Strike" },
#include "games.h" { "czero", "cs.so", "mp.dll", "Counter-Strike:Condition Zero" },
// End of list terminator: // End of list terminator:
{NULL, NULL, NULL, NULL, NULL} { NULL, NULL, NULL, NULL }
}; };
// Find a modinfo corresponding to the given game name. // Find a modinfo corresponding to the given game name.
game_modinfo_t* lookup_game(const char* name) inline const game_modinfo_t *lookup_game(const char *name)
{ {
for (int i = 0; known_games[i].name; i++) { for (auto& known : known_games)
auto imod = &known_games[i]; {
if (strcasematch(imod->name, name)) if (known.name && Q_stricmp(known.name, name))
return imod; return &known;
}
// no match found
return NULL;
} }
// no match found
return nullptr;
}
// Installs gamedll from Steam cache
mBOOL install_gamedll(char *from, const char *to) mBOOL install_gamedll(char *from, const char *to)
{ {
int length_in; int length_in;
int length_out; int length_out;
if (NULL == from) return mFALSE; if (!from)
if (NULL == to) to = from; return mFALSE;
if (!to)
to = from;
byte *cachefile = LOAD_FILE_FOR_ME(from, &length_in); byte *cachefile = LOAD_FILE_FOR_ME(from, &length_in);
// If the file seems to exist in the cache. // If the file seems to exist in the cache.
if (NULL != cachefile) { if (cachefile)
{
int fd = open(to, O_WRONLY | O_CREAT | O_EXCL | O_BINARY, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); int fd = open(to, O_WRONLY | O_CREAT | O_EXCL | O_BINARY, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
if (fd < 0) { if (fd < 0)
META_DEBUG(3, ("Installing gamedll from cache: Failed to create file %s: %s\n", to, strerror(errno)) ); {
META_DEBUG(3, ("Installing gamedll from cache: Failed to create file %s: %s", to, strerror(errno)) );
FREE_FILE(cachefile); FREE_FILE(cachefile);
return mFALSE; return mFALSE;
} }
length_out = write(fd, cachefile, length_in); length_out = Q_write(fd, cachefile, length_in);
FREE_FILE(cachefile); FREE_FILE(cachefile);
close(fd); close(fd);
// Writing the file was not successfull // Writing the file was not successfull
if (length_out != length_in) { if (length_out != length_in)
META_DEBUG(3,("Installing gamedll from cache: Failed to write all %d bytes to file, only %d written: %s\n", {
length_in, length_out, strerror(errno)) ); META_DEBUG(3, ("Installing gamedll from chache: Failed to write all %d bytes to file, only %d written: %s", length_in, length_out, strerror(errno)));
// Let's not leave a mess but clean up nicely. // Let's not leave a mess but clean up nicely.
if (length_out >= 0) _unlink(to); if (length_out >= 0)
_unlink(to);
return mFALSE; return mFALSE;
} }
META_LOG("Installed gamedll %s from cache.\n", to); META_LOG("Installed gamedll %s from cache.", to);
} }
else { else
META_DEBUG(3, ("Failed to install gamedll from cache: file %s not found in cache.\n", from) ); {
META_DEBUG(3, ("Failed to install gamedll from cache: file %s not found in cache.", from));
return mFALSE; return mFALSE;
} }
@ -118,160 +90,56 @@ mBOOL install_gamedll(char* from, const char* to)
// - ME_NOTFOUND couldn't recognize game // - ME_NOTFOUND couldn't recognize game
mBOOL setup_gamedll(gamedll_t *gamedll) mBOOL setup_gamedll(gamedll_t *gamedll)
{ {
static char override_desc_buf[256]; const game_modinfo_t *known;
game_modinfo_t* known; const char *knownfn = nullptr;
const char* cp;
const char* knownfn = 0;
const char* usedfn = 0;
char* strippedfn = 0;
bool override = false;
// Check for old-style "metagame.ini" file and complain. // Check for old-style "metagame.ini" file and complain.
if (valid_gamedir_file(OLD_GAMEDLL_TXT)) if (valid_gamedir_file(OLD_GAMEDLL_TXT))
META_ERROR("File '%s' is no longer supported; instead, specify override gamedll in %s or with '+localinfo mm_gamedll <dllfile>'", OLD_GAMEDLL_TXT, CONFIG_INI); {
META_WARNING("File '%s' is no longer supported; instead, specify override gamedll in %s or with '+localinfo mm_gamedll <dllfile>'", OLD_GAMEDLL_TXT, CONFIG_INI);
}
// First, look for a known game, based on gamedir. // First, look for a known game, based on gamedir.
if ((known = lookup_game(gamedll->name))) { if ((known = lookup_game(gamedll->name)))
{
#ifdef _WIN32 #ifdef _WIN32
knownfn = _strdup(known->win_dll); knownfn = known->win_dll;
#elif defined(linux)
knownfn=_strdup(known->linux_so);
#elif defined(__APPLE__)
knownfn=_strdup(known->osx_dylib);
#else #else
#error "OS unrecognized" knownfn = known->linux_so;
#endif /* _WIN32 */ #endif
}
// Neither override nor auto-detect found a gamedll.
if (!known && !g_config->gamedll)
RETURN_ERRNO(mFALSE, ME_NOTFOUND);
// Use override-dll if specified.
if (g_config->gamedll) {
strncpy(gamedll->pathname, g_config->gamedll, sizeof gamedll->pathname - 1);
gamedll->pathname[sizeof gamedll->pathname - 1] = '\0';
override = true;
// If the path is relative, the gamedll file will be missing and
// it might be found in the cache file.
if (!is_absolute_path(gamedll->pathname)) {
// I abuse the real_pathname member here to pass a full pathname to
// the install_gamedll function. I am somewhat opposed to be pushing
// another MAX_PATH sized array on the stack, that's why.
snprintf(gamedll->real_pathname, sizeof(gamedll->real_pathname), "%s/%s", gamedll->gamedir, gamedll->pathname);
// If we could successfully install the gamedll from the cache we
// rectify the pathname to be a full pathname.
if (install_gamedll(gamedll->pathname, gamedll->real_pathname)) {
strncpy(gamedll->pathname, gamedll->real_pathname, sizeof gamedll->pathname - 1);
gamedll->pathname[sizeof gamedll->pathname - 1] = '\0';
}
}
}
// Else use Auto-detect dll.
else {
#ifdef linux
// The engine changed game dll lookup behaviour in that it strips
// anything after the last '_' from the name and tries to load the
// resulting name. The DSO names were changed and do not have the
// '_i386' part in them anymore, so cs_i386.so became cs.so. We
// have to adapt to that and try to load the DSO name without the
// '_*' part first, to see if we have a new version file available.
strippedfn = _strdup(knownfn);
char *loc = strrchr(strippedfn, '_');
// A small safety net here: make sure that we are dealing with
// a file name at least four characters long and ending in
// '.so'. This way we can be sure that we can safely overwrite
// anything from the '_' on with '.so'.
int size = 0;
const char *ext;
if(0 != loc) {
size = strlen(strippedfn);
ext = strippedfn + (size - 3);
}
if(0 != loc && size > 3 && 0 == _stricmp(ext, ".so")) {
strcpy(loc, ".so");
META_DEBUG(4, ("Checking for new version game DLL name '%s'.\n", strippedfn) );
// Again, as above, I abuse the real_pathname member to store the full pathname
// and the pathname member to store the relative name to pass it to the
// install_gamedll function to save stack space. They are going
// to get overwritten later on, so that's ok.
snprintf(gamedll->pathname, sizeof(gamedll->pathname), "dlls/%s",
strippedfn);
// Check if the gamedll file exists. If not, try to install it from
// the cache.
mBOOL ok = mTRUE;
if(!valid_gamedir_file(gamedll->pathname)) {
snprintf(gamedll->real_pathname, sizeof(gamedll->real_pathname), "%s/dlls/%s",
gamedll->gamedir, strippedfn);
ok = install_gamedll(gamedll->pathname, gamedll->real_pathname);
}
if(ok) usedfn = strippedfn;
}
else {
META_DEBUG(4, ("Known game DLL name does not qualify for checking for a stripped version, skipping: '%s'.\n",
strippedfn) );
}
#endif /* linux */
// If no file to be used was found, try the old known DLL file
// name.
if (0 == usedfn) {
META_DEBUG(4, ("Checking for old version game DLL name '%s'.\n", knownfn)); META_DEBUG(4, ("Checking for old version game DLL name '%s'.\n", knownfn));
snprintf(gamedll->pathname, sizeof(gamedll->pathname), "dlls/%s", knownfn); Q_snprintf(gamedll->pathname, sizeof(gamedll->pathname), "dlls/%s", knownfn);
// Check if the gamedll file exists. If not, try to install it from
// the cache. // Check if the gamedll file exists. If not, try to install it from the cache.
if (!valid_gamedir_file(gamedll->pathname)) { if (!valid_gamedir_file(gamedll->pathname))
snprintf(gamedll->real_pathname, sizeof(gamedll->real_pathname), "%s/dlls/%s", {
gamedll->gamedir, knownfn); Q_snprintf(gamedll->real_pathname, sizeof(gamedll->real_pathname), "%s/dlls/%s", gamedll->gamedir, knownfn);
install_gamedll(gamedll->pathname, gamedll->real_pathname); install_gamedll(gamedll->pathname, gamedll->real_pathname);
} }
usedfn = knownfn; }
else
{
// Neither known-list found a gamedll.
RETURN_ERRNO(mFALSE, ME_NOTFOUND);
} }
// Now make an absolute path Q_snprintf(gamedll->pathname, sizeof(gamedll->pathname), "%s/dlls/%s", gamedll->gamedir, knownfn);
snprintf(gamedll->pathname, sizeof(gamedll->pathname), "%s/dlls/%s",
gamedll->gamedir, usedfn);
}
// get filename from pathname // get filename from pathname
cp = strrchr(gamedll->pathname, '/'); char *cp = Q_strrchr(gamedll->pathname, '/');
if (cp) cp++; if (cp)
else cp = gamedll->pathname; cp++;
else
cp = gamedll->pathname;
gamedll->file = cp; gamedll->file = cp;
// If found, store also the supposed "real" dll path based on the Q_strncpy(gamedll->real_pathname, gamedll->pathname, sizeof(gamedll->real_pathname) - 1);
// gamedir, in case it differs from the "override" dll path. gamedll->real_pathname[sizeof(gamedll->real_pathname) - 1] = '\0';
if (known && override)
snprintf(gamedll->real_pathname, sizeof(gamedll->real_pathname),
"%s/dlls/%s", gamedll->gamedir, usedfn);
else { // !known or !override
strncpy(gamedll->real_pathname, gamedll->pathname, sizeof gamedll->real_pathname - 1);
gamedll->real_pathname[sizeof gamedll->pathname - 1] = '\0';
}
if (override) {
// generate a desc
snprintf(override_desc_buf, sizeof(override_desc_buf),
"%s (override)", gamedll->file);
gamedll->desc = override_desc_buf;
// log result
META_LOG("Overriding game '%s' with dllfile '%s'", gamedll->name,
gamedll->file);
}
else {
gamedll->desc = known->desc; gamedll->desc = known->desc;
META_LOG("Recognized game '%s'; using dllfile '%s'", gamedll->name, META_LOG("Recognized game '%s'; using dllfile '%s'", gamedll->name, gamedll->file);
gamedll->file);
}
if (0 != strippedfn) free(strippedfn); return mTRUE;
return (mTRUE);
} }

View File

@ -1,56 +1,16 @@
// vi: set ts=4 sw=4 : #pragma once
// vim: set tw=75 :
// game_support.h - structures for supporting different HL mod "games" #include "types_meta.h"
#include "metamod.h"
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef GAME_SUPPORT_H
#define GAME_SUPPORT_H
#include "types_meta.h" // mBOOL
#include "metamod.h" // gamedll_t
// Information we have about each game/mod DLL. // Information we have about each game/mod DLL.
typedef struct game_modinfo_s { struct game_modinfo_t
{
const char *name; // name (the game dir) const char *name; // name (the game dir)
const char *linux_so; // filename of linux shared lib const char *linux_so; // filename of linux shared lib
const char *win_dll; // filename of win32 dll const char *win_dll; // filename of win32 dll
const char *osx_dylib; // filename os osx dylib const char *osx_dylib; // filename os osx dylib
const char *desc; // our long-name description const char *desc; // our long-name description
} game_modinfo_t; };
typedef game_modinfo_t game_modlist_t[];
game_modinfo_t *lookup_game(const char *name);
mBOOL setup_gamedll(gamedll_t *gamedll); mBOOL setup_gamedll(gamedll_t *gamedll);
#endif /* GAME_SUPPORT_H */

View File

@ -1,131 +0,0 @@
// vi: set ts=4 sw=4 :
// vim: set tw=75 :
// games.h - list of supported game mods and their data
/*
* Copyright (c) 2001-2008 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game Engine ("HL
* Engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL Engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
// This list is now kept in a separate file to facilitate generating the
// list from game data stored in a convenient db.
#ifdef __amd64__
# define MODARCH "_amd64"
#else
# define MODARCH "_i386"
#endif
{"action", "ahl"MODARCH".so", "ahl.dll", "none", "Action Half-Life"},
{"ag", "ag"MODARCH".so", "ag.dll", "none", "Adrenaline Gamer Steam"},
{"ag3", "hl"MODARCH".so", "hl.dll", "none", "Adrenalinegamer 3.x"},
{"aghl", "ag"MODARCH".so", "ag.dll", "none", "Adrenalinegamer 4.x"},
{"arg", "arg"MODARCH".so", "hl.dll", "none", "Arg!"},
{"asheep", "hl"MODARCH".so", "hl.dll", "none", "Azure Sheep"},
{"bg", "bg"MODARCH".so", "bg.dll", "none", "The Battle Grounds"},
{"bot", "bot"MODARCH".so", "bot.dll", "none", "Bot"},
{"brainbread", "bb"MODARCH".so", "bb.dll", "none", "Brain Bread"},
{"bumpercars", "hl"MODARCH".so", "hl.dll", "none", "Bumper Cars"},
{"buzzybots", "bb"MODARCH".so", "bb.dll", "none", "BuzzyBots"},
{"cs13", "cs"MODARCH".so", "mp.dll", "none", "Counter-Strike 1.3"},
{"cstrike", "cs"MODARCH".so", "mp.dll", "cs.dylib", "Counter-Strike"},
{"csv15", "cs"MODARCH".so", "mp.dll", "none", "CS 1.5 for Steam"},
{"czero", "cs"MODARCH".so", "mp.dll", "cs.dylib", "Counter-Strike:Condition Zero"},
{"dcrisis", "dc"MODARCH".so", "dc.dll", "none", "Desert Crisis"},
{"dmc", "dmc"MODARCH".so", "dmc.dll", "dmc.dylib", "Deathmatch Classic"},
{"dod", "dod"MODARCH".so", "dod.dll", "dod.dylib", "Day of Defeat"},
{"dpb", "pb.i386.so", "pb.dll", "none", "Digital Paintball"},
{"dragonmodz", "hl"MODARCH".so", "mp.dll", "none", "Dragon Mod Z"},
{"esf", "hl"MODARCH".so", "hl.dll", "none", "Earth's Special Forces"},
{"existence", "ex"MODARCH".so", "existence.dll", "none", "Existence"},
{"firearms", "fa"MODARCH".so", "firearms.dll", "none", "Firearms"},
{"firearms25", "fa"MODARCH".so", "firearms.dll", "none", "Retro Firearms"},
{"freeze", "mp"MODARCH".so", "mp.dll", "none", "Freeze"},
{"frontline", "front"MODARCH".so", "frontline.dll", "none", "Frontline Force"},
{"gangstawars", "gangsta"MODARCH".so", "gwars27.dll", "none", "Gangsta Wars"},
{"gangwars", "mp"MODARCH".so", "mp.dll", "none", "Gangwars"},
{"gearbox", "opfor"MODARCH".so", "opfor.dll", "opfor.dylib", "Opposing Force"},
{"globalwarfare", "gw"MODARCH".so", "mp.dll", "none", "Global Warfare"},
{"goldeneye", "golden"MODARCH".so", "mp.dll", "none", "Goldeneye"},
{"hl15we", "hl"MODARCH".so", "hl.dll", "none", "Half-Life 1.5: Weapon Edition"},
{"hlrally", "hlr"MODARCH".so", "hlrally.dll", "none", "HL-Rally"},
{"holywars", "hl"MODARCH".so", "holywars.dll", "none", "Holy Wars"},
{"hostileintent", "hl"MODARCH".so", "hl.dll", "none", "Hostile Intent"},
{"ios", "ios"MODARCH".so", "ios.dll", "none", "International Online Soccer"},
{"judgedm", "judge"MODARCH".so", "mp.dll", "none", "Judgement"},
{"kanonball", "hl"MODARCH".so", "kanonball.dll", "none", "Kanonball"},
{"monkeystrike", "ms"MODARCH".so", "monkey.dll", "none", "Monkeystrike"},
{"MorbidPR", "morbid"MODARCH".so", "morbid.dll", "none", "Morbid Inclination"},
{"movein", "hl"MODARCH".so", "hl.dll", "none", "Move In!"},
{"ns", "ns"MODARCH".so", "ns.dll", "none", "Natural Selection"},
{"nsp", "ns"MODARCH".so", "ns.dll", "none", "Natural Selection Beta"},
{"oel", "hl"MODARCH".so", "hl.dll", "none", "OeL Half-Life"},
{"og", "og"MODARCH".so", "og.dll", "none", "Over Ground"},
{"ol", "ol"MODARCH".so", "hl.dll", "none", "Outlawsmod"},
{"ops1942", "spirit"MODARCH".so", "spirit.dll", "none", "Operations 1942"},
{"osjb", "osjb"MODARCH".so", "jail.dll", "none", "Open-Source Jailbreak"},
{"outbreak", "none", "hl.dll", "none", "Out Break"},
{"oz", "mp"MODARCH".so", "mp.dll", "none", "Oz Deathmatch"},
{"paintball", "pb"MODARCH".so", "mp.dll", "none", "Paintball"},
{"penemy", "pe"MODARCH".so", "pe.dll", "none", "Public Enemy"},
{"phineas", "phineas"MODARCH".so", "phineas.dll", "none", "Phineas Bot"},
{"ponreturn", "ponr"MODARCH".so", "mp.dll", "none", "Point of No Return"},
{"pvk", "hl"MODARCH".so", "hl.dll", "none", "Pirates, Vikings and Knights"},
{"rc2", "rc2"MODARCH".so", "rc2.dll", "none", "Rocket Crowbar 2"},
{"retrocs", "rcs"MODARCH".so", "rcs.dll", "none", "Retro Counter-Strike"},
{"rewolf", "hl"MODARCH".so", "gunman.dll", "none", "Gunman Chronicles"},
{"ricochet", "ricochet"MODARCH".so", "mp.dll", "ricochet.dylib", "Ricochet"},
{"rockcrowbar", "rc"MODARCH".so", "rc.dll", "none", "Rocket Crowbar"},
{"rspecies", "hl"MODARCH".so", "hl.dll", "none", "Rival Species"},
{"scihunt", "shunt.so", "shunt.dll", "none", "Scientist Hunt"},
{"sdmmod", "sdmmod"MODARCH".so", "sdmmod.dll", "none", "Special Death Match"},
{"Ship", "ship"MODARCH".so", "ship.dll", "none", "The Ship"},
{"si", "si"MODARCH".so", "si.dll", "none", "Science & Industry"},
{"snow", "snow"MODARCH".so", "snow.dll", "none", "Snow-War"},
{"stargatetc", "hl"MODARCH".so", "hl.dll", "none", "StargateTC"},
{"svencoop", "hl"MODARCH".so", "hl.dll", "none", "Sven Coop"},
{"swarm", "swarm"MODARCH".so", "swarm.dll", "none", "Swarm"},
{"tfc", "tfc"MODARCH".so", "tfc.dll", "tfc.dylib", "Team Fortress Classic"},
{"thewastes", "thewastes"MODARCH".so", "thewastes.dll", "none", "The Wastes"},
{"timeless", "pt"MODARCH".so", "timeless.dll", "none", "Project Timeless"},
{"tod", "hl"MODARCH".so", "hl.dll", "none", "Tour of Duty"},
{"trainhunters", "th"MODARCH".so", "th.dll", "none", "Train Hunters"},
{"trevenge", "trevenge.so", "trevenge.dll", "none", "The Terrorist Revenge"},
{"TS", "ts"MODARCH".so", "mp.dll", "none", "The Specialists"},
{"tt", "tt"MODARCH".so", "tt.dll", "none", "The Trenches"},
{"underworld", "uw"MODARCH".so", "uw.dll", "none", "Underworld Bloodline"},
{"valve", "hl"MODARCH".so", "hl.dll", "hl.dylib", "Half-Life Deathmatch"},
{"vs", "vs"MODARCH".so", "mp.dll", "none", "VampireSlayer"},
{"wantedhl", "hl"MODARCH".so", "wanted.dll", "none", "Wanted!"},
{"wasteland", "whl_linux.so", "mp.dll", "none", "Wasteland"},
{"weapon_wars", "ww"MODARCH".so", "hl.dll", "none", "Weapon Wars"},
{"wizwars", "mp"MODARCH".so", "hl.dll", "none", "Wizard Wars"},
{"wormshl", "wormshl_i586.so", "wormshl.dll", "none", "WormsHL"},
{"zp", "none", "mp.dll", "none", "Zombie Panic"},

View File

@ -1,37 +1,5 @@
// vi: set ts=4 sw=4 :
// vim: set tw=75 :
// h_export.cpp - main exported DLL functionality
// From SDK dlls/h_export.cpp:
/***
*
* Copyright (c) 1999, 2000 Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
/*
===== h_export.cpp ========================================================
Entity classes exported by Halflife.
*/
#include "precompiled.h" #include "precompiled.h"
// From SDK dlls/h_export.cpp:
#ifdef _WIN32 #ifdef _WIN32
//! Required DLL entry point //! Required DLL entry point
// The above SDK comment indicates this routine is required, but the MSDN // The above SDK comment indicates this routine is required, but the MSDN
@ -39,10 +7,12 @@
// completeness. // completeness.
BOOL WINAPI DllMain(HINSTANCE /* hinstDLL */, DWORD fdwReason, LPVOID /* lpvReserved */) BOOL WINAPI DllMain(HINSTANCE /* hinstDLL */, DWORD fdwReason, LPVOID /* lpvReserved */)
{ {
if (fdwReason == DLL_PROCESS_ATTACH) { if (fdwReason == DLL_PROCESS_ATTACH)
{
/* nothing */ /* nothing */
} }
else if (fdwReason == DLL_PROCESS_DETACH) { else if (fdwReason == DLL_PROCESS_DETACH)
{
/* nothing */ /* nothing */
} }
return TRUE; return TRUE;
@ -53,10 +23,12 @@ BOOL WINAPI DllMain(HINSTANCE /* hinstDLL */, DWORD fdwReason, LPVOID /* lpvRese
// just in case we come across a need to do something at dll load or // just in case we come across a need to do something at dll load or
// unload. // unload.
// NOTE: These aren't actually called. Needs investigation. // NOTE: These aren't actually called. Needs investigation.
void _init(void) { void _init()
{
// called before dlopen() returns // called before dlopen() returns
} }
void _fini(void) { void _fini()
{
// called before dlclose() returns // called before dlclose() returns
} }
#endif #endif
@ -94,22 +66,22 @@ extern "C" void __cxa_pure_virtual(void)
void *operator new(size_t size) void *operator new(size_t size)
{ {
return malloc(size); return Q_malloc(size);
} }
void *operator new[](size_t size) void *operator new[](size_t size)
{ {
return malloc(size); return Q_malloc(size);
} }
void operator delete(void *ptr) void operator delete(void *ptr)
{ {
free(ptr); Q_free(ptr);
} }
void operator delete[](void * ptr) void operator delete[](void * ptr)
{ {
free(ptr); Q_free(ptr);
} }
#endif #endif

View File

@ -1,49 +1,7 @@
// vi: set ts=4 sw=4 : #pragma once
// vim: set tw=75 :
// h_export.h - prototypes for h_export.cpp
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef H_EXPORT_H
#define H_EXPORT_H
#include "osdep.h" // DLLEXPORT, WINAPI, etc #include "osdep.h" // DLLEXPORT, WINAPI, etc
// Our GiveFnptrsToDll, called by engine. // Our GiveFnptrsToDll, called by engine.
typedef void (WINAPI *GIVE_ENGINE_FUNCTIONS_FN) (enginefuncs_t typedef void (WINAPI *GIVE_ENGINE_FUNCTIONS_FN)(enginefuncs_t *pengfuncsFromEngine, globalvars_t *pGlobals);
*pengfuncsFromEngine, globalvars_t *pGlobals); C_DLLEXPORT void WINAPI GiveFnptrsToDll(enginefuncs_t *pengfuncsFromEngine, globalvars_t *pGlobals);
C_DLLEXPORT void WINAPI GiveFnptrsToDll(enginefuncs_t *pengfuncsFromEngine,
globalvars_t *pGlobals);
#endif /* H_EXPORT_H */

View File

@ -1,54 +0,0 @@
// vi: set ts=4 sw=4 :
// vim: set tw=75 :
// info_name.h - name, desc, author, etc
/*
* Copyright (c) 2001-2013 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game Engine ("HL
* Engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL Engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef INFO_NAME_H
#define INFO_NAME_H
#define VNAME "Metamod"
#define VAUTHOR "Will Day <willday@metamod.org>"
#define VURL "http://www.metamod.org/"
#define COPYRIGHT_YEAR "2013"
// Various strings for the Windows DLL Resources in res_meta.rc
#define RC_COMMENTS "Metamod allows running multiple mod-like plugin DLLs, to add functionality or change the behavior of the running HLDS game mod. See " VURL
#define RC_DESC "Metamod Half-Life MOD DLL"
#define RC_FILENAME "METAMOD.DLL"
#define RC_INTERNAL "METAMOD"
#define RC_COPYRIGHT "Copyright© 2001-" COPYRIGHT_YEAR " Will Day; GPL licensed"
#define RC_LICENSE "Licensed under the GNU General Public License"
#endif /* INFO_NAME_H */

View File

@ -1,59 +1,29 @@
// vi: set ts=4 sw=4 :
// vim: set tw=75 :
// linkent.cpp - export entities from mod "games" back to the HL engine
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#include "precompiled.h" #include "precompiled.h"
// Function to perform common code of LINK_ENTITY_TO_GAME, rather than // Function to perform common code of LINK_ENTITY_TO_GAME, rather than
// duplicating the code in ~2000 expanded macros. Based on code from Jussi // duplicating the code in ~2000 expanded macros. Based on code from Jussi
// Kivilinna <kijuhe00@students.oamk.fi>. // Kivilinna <kijuhe00@students.oamk.fi>.
void do_link_ent(ENTITY_FN *pfnEntity, int *missing, const char *entStr, entvars_t *pev) void do_link_ent(ENTITY_FN *pfnEntity, int *missing, const char *entStr, entvars_t *pev)
{; {
if(*missing) { if (*missing)
{
META_DEBUG(9, ("Skipping entity '%s'; was previously found missing", entStr)); META_DEBUG(9, ("Skipping entity '%s'; was previously found missing", entStr));
return; return;
} }
if(!*pfnEntity) {
if (!*pfnEntity)
{
META_DEBUG(9, ("Looking up game entity '%s'", entStr)); META_DEBUG(9, ("Looking up game entity '%s'", entStr));
*pfnEntity = (ENTITY_FN)DLSYM(GameDLL.handle, entStr); *pfnEntity = (ENTITY_FN)DLSYM(GameDLL.handle, entStr);
} }
if(!*pfnEntity) {
if (!*pfnEntity)
{
META_ERROR("Couldn't find game entity '%s' in game DLL '%s': %s", entStr, GameDLL.name, DLERROR()); META_ERROR("Couldn't find game entity '%s' in game DLL '%s': %s", entStr, GameDLL.name, DLERROR());
*missing = 1; *missing = 1;
return; return;
} }
META_DEBUG(8, ("Linking game entity '%s'", entStr)); META_DEBUG(8, ("Linking game entity '%s'", entStr));
(*pfnEntity)(pev); (*pfnEntity)(pev);
} }

View File

@ -1,49 +1,4 @@
// vi: set ts=4 sw=4 : #pragma once
// vim: set tw=75 :
// linkent.h - export entities from mod "games" back to the HL engine
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef LINK_ENT_H
#define LINK_ENT_H
#include <extdll.h> // always
#include "osdep.h" // DLLEXPORT, etc
#include "metamod.h" // GameDLL, etc
#include "mlist.h" // MPluginList::find_match, etc
#include "mplugin.h" // MPlugin::info, etc
#include "log_meta.h" // META_DEBUG, etc
// Comments from SDK dlls/util.h: // Comments from SDK dlls/util.h:
//! This is the glue that hooks .MAP entity class names to our CPP classes. //! This is the glue that hooks .MAP entity class names to our CPP classes.
@ -51,12 +6,10 @@
//! The function is used to intialize / allocate the object for the entity. //! The function is used to intialize / allocate the object for the entity.
// Adapted from LINK_ENTITY_TO_FUNC in adminmod linkfunc.cpp. // Adapted from LINK_ENTITY_TO_FUNC in adminmod linkfunc.cpp.
typedef void (*ENTITY_FN)(entvars_t *); typedef void (*ENTITY_FN)(entvars_t *);
// Function to perform common code of LINK_ENTITY_TO_GAME. // Function to perform common code of LINK_ENTITY_TO_GAME.
void do_link_ent(ENTITY_FN *pfnEntity, int *missing, const char *entStr, void do_link_ent(ENTITY_FN *pfnEntity, int *missing, const char *entStr, entvars_t *pev);
entvars_t *pev);
#define LINK_ENTITY_TO_GAME(entityName) \ #define LINK_ENTITY_TO_GAME(entityName) \
C_DLLEXPORT void entityName(entvars_t *pev); \ C_DLLEXPORT void entityName(entvars_t *pev); \
@ -111,5 +64,3 @@ void do_link_ent(ENTITY_FN *pfnEntity, int *missing, const char *entStr,
META_DEBUG(8, ("Linking plugin entity '%s'", entStr)); \ META_DEBUG(8, ("Linking plugin entity '%s'", entStr)); \
(*pfnEntity)(pev); \ (*pfnEntity)(pev); \
} }
#endif /* LINK_ENT_H */

View File

@ -1,39 +1,3 @@
// vi: set ts=4 sw=4 :
// vim: set tw=75 :
// linkgame.cpp - export entities from mod "games" back to the HL engine
/*
* Copyright (c) 2001-2013 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#include "precompiled.h" #include "precompiled.h"
// Entity list for gamedlls adapted from adminmod linkfunc.cpp. // Entity list for gamedlls adapted from adminmod linkfunc.cpp.

View File

@ -1,42 +1,6 @@
// vi: set ts=4 sw=4 :
// vim: set tw=75 :
// log_mega.cpp - logging routines
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#include "precompiled.h" #include "precompiled.h"
cvar_t meta_debug = {"meta_debug", "0", FCVAR_EXTDLL , 0, NULL}; cvar_t meta_debug = { "meta_debug", "0", FCVAR_EXTDLL , 0, nullptr };
enum MLOG_SERVICE enum MLOG_SERVICE
{ {
@ -56,7 +20,7 @@ void META_CONS(const char* fmt, ...)
unsigned int len; unsigned int len;
va_start(ap, fmt); va_start(ap, fmt);
len = vsnprintf(buf, sizeof(buf) - 1, fmt, ap); len = Q_vsnprintf(buf, sizeof(buf) - 1, fmt, ap);
va_end(ap); va_end(ap);
buf[len] = '\n'; buf[len] = '\n';
@ -67,7 +31,8 @@ void META_CONS(const char* fmt, ...)
void META_DEV(const char *fmt, ...) void META_DEV(const char *fmt, ...)
{ {
if (CVAR_GET_FLOAT && CVAR_GET_FLOAT("developer")) { if (CVAR_GET_FLOAT && CVAR_GET_FLOAT("developer"))
{
va_list ap; va_list ap;
va_start(ap, fmt); va_start(ap, fmt);
buffered_ALERT(mlsDEV, at_logged, "[META] dev:", fmt, ap); buffered_ALERT(mlsDEV, at_logged, "[META] dev:", fmt, ap);
@ -119,7 +84,7 @@ void META_CLIENT(edict_t* pEntity, const char* fmt, ...)
unsigned int len; unsigned int len;
va_start(ap, fmt); va_start(ap, fmt);
len = vsnprintf(buf, sizeof(buf) - 1, fmt, ap); len = Q_vsnprintf(buf, sizeof(buf) - 1, fmt, ap);
va_end(ap); va_end(ap);
buf[len] = '\n'; buf[len] = '\n';
@ -137,23 +102,24 @@ struct BufferedMessage
BufferedMessage *next; BufferedMessage *next;
}; };
static BufferedMessage* messageQueueStart = NULL; static BufferedMessage *messageQueueStart = nullptr;
static BufferedMessage* messageQueueEnd = NULL; static BufferedMessage *messageQueueEnd = nullptr;
void buffered_ALERT(MLOG_SERVICE service, ALERT_TYPE atype, const char *prefix, const char *fmt, va_list ap) void buffered_ALERT(MLOG_SERVICE service, ALERT_TYPE atype, const char *prefix, const char *fmt, va_list ap)
{ {
char buf[MAX_LOGMSG_LEN]; char buf[MAX_LOGMSG_LEN];
BufferedMessage* msg;
if (NULL != g_engfuncs.pfnAlertMessage) { if (g_engfuncs.pfnAlertMessage)
vsnprintf(buf, sizeof(buf), fmt, ap); {
Q_vsnprintf(buf, sizeof(buf), fmt, ap);
ALERT(atype, "%s %s\n", prefix, buf); ALERT(atype, "%s %s\n", prefix, buf);
return; return;
} }
// g_engine AlertMessage function not available. Buffer message. // g_engine AlertMessage function not available. Buffer message.
msg = new BufferedMessage; BufferedMessage *msg = new BufferedMessage;
if (NULL == msg) { if (!msg)
{
// though luck, gonna lose this message // though luck, gonna lose this message
return; return;
} }
@ -161,13 +127,15 @@ void buffered_ALERT(MLOG_SERVICE service, ALERT_TYPE atype, const char* prefix,
msg->service = service; msg->service = service;
msg->atype = atype; msg->atype = atype;
msg->prefix = prefix; msg->prefix = prefix;
vsnprintf(msg->buf, sizeof(buf), fmt, ap); Q_vsnprintf(msg->buf, sizeof(buf), fmt, ap);
msg->next = NULL; msg->next = nullptr;
if (NULL == messageQueueEnd) { if (!messageQueueEnd)
{
messageQueueStart = messageQueueEnd = msg; messageQueueStart = messageQueueEnd = msg;
} }
else { else
{
messageQueueEnd->next = msg; messageQueueEnd->next = msg;
messageQueueEnd = msg; messageQueueEnd = msg;
} }
@ -182,18 +150,20 @@ void flush_ALERT_buffer(void)
BufferedMessage *msg = messageQueueStart; BufferedMessage *msg = messageQueueStart;
int dev = (int)CVAR_GET_FLOAT("developer"); int dev = (int)CVAR_GET_FLOAT("developer");
while (NULL != msg) { while (msg)
{
if (msg->service == mlsDEV && dev == 0) { if (msg->service == mlsDEV && dev == 0) {
; ;
} }
else { else
{
ALERT(msg->atype, "b>%s %s\n", msg->prefix, msg->buf); ALERT(msg->atype, "b>%s %s\n", msg->prefix, msg->buf);
} }
messageQueueStart = messageQueueStart->next; messageQueueStart = messageQueueStart->next;
delete msg; delete msg;
msg = messageQueueStart; msg = messageQueueStart;
} }
messageQueueStart = messageQueueEnd = NULL; messageQueueStart = messageQueueEnd = nullptr;
} }

View File

@ -1,41 +1,4 @@
// vi: set ts=4 sw=4 : #pragma once
// vim: set tw=75 :
// log_meta.h - functions & macros for logging
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef LOG_META_H
#define LOG_META_H
#include "enginecallbacks.h" // ALERT, etc #include "enginecallbacks.h" // ALERT, etc
#include "sdk_util.h" // UTIL_VarArgs, etc #include "sdk_util.h" // UTIL_VarArgs, etc
@ -98,5 +61,3 @@ void META_LOG(const char *fmt, ...);
void META_CLIENT(edict_t *pEntity, const char *fmt, ...); void META_CLIENT(edict_t *pEntity, const char *fmt, ...);
void flush_ALERT_buffer(void); void flush_ALERT_buffer(void);
#endif /* LOG_META_H */

View File

@ -1,47 +1,10 @@
// vi: set ts=4 sw=4 : #pragma once
// vim: set tw=75 :
// meta_api.h - description of metamod's DLL interface
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef META_API_H
#define META_API_H
#include "dllapi.h" // GETENTITYAPI_FN, etc #include "dllapi.h" // GETENTITYAPI_FN, etc
#include "engine_api.h" // GET_ENGINE_FUNCTIONS_FN, etc #include "engine_api.h" // GET_ENGINE_FUNCTIONS_FN, etc
#include "plinfo.h" // plugin_info_t, etc #include "plinfo.h" // plugin_info_t, etc
#include "mutil.h" // mutil_funcs_t, etc
#include "osdep.h" // DLLEXPORT, etc #include "osdep.h" // DLLEXPORT, etc
#include "mutil.h"
// Version consists of "major:minor", two separate integer numbers. // Version consists of "major:minor", two separate integer numbers.
// Version 1 original // Version 1 original
@ -60,47 +23,48 @@
// Version 5:9 added GetGameInfo [v1.14] // Version 5:9 added GetGameInfo [v1.14]
// Version 5:10 added GINFO_REALDLL_FULLPATH for GetGameInfo [v1.17] // Version 5:10 added GINFO_REALDLL_FULLPATH for GetGameInfo [v1.17]
// Version 5:11 added plugin loading and unloading API [v1.18] // Version 5:11 added plugin loading and unloading API [v1.18]
// Version 5:12 added util code for checking player query status [v1.18] // Version 5:12 added IS_QUERYING_CLIENT_CVAR to mutils [v1.18]
// Version 5:13 added cvarquery2 support and api for calling hook tables [v1.19] // Version 5:13 added MAKE_REQUESTID and GET_HOOK_TABLES to mutils [v1.19]
#define META_INTERFACE_VERSION "5:13" #define META_INTERFACE_VERSION "5:13"
#ifdef UNFINISHED
// Version 5:99 added event hook utility functions [v.???]
#define META_INTERFACE_VERSION "5:99"
#endif /* UNFINISHED */
// Flags returned by a plugin's api function. // Flags returned by a plugin's api function.
// NOTE: order is crucial, as greater/less comparisons are made. // NOTE: order is crucial, as greater/less comparisons are made.
typedef enum { enum META_RES
{
MRES_UNSET = 0, MRES_UNSET = 0,
MRES_IGNORED, // plugin didn't take any action MRES_IGNORED, // plugin didn't take any action
MRES_HANDLED, // plugin did something, but real function should still be called MRES_HANDLED, // plugin did something, but real function should still be called
MRES_OVERRIDE, // call real function, but use my return value MRES_OVERRIDE, // call real function, but use my return value
MRES_SUPERCEDE, // skip real function; use my return value MRES_SUPERCEDE, // skip real function; use my return value
} META_RES; };
// Variables provided to plugins. // Variables provided to plugins.
typedef struct meta_globals_s { struct meta_globals_t
{
META_RES mres; // writable; plugin's return flag META_RES mres; // writable; plugin's return flag
META_RES prev_mres; // readable; return flag of the previous plugin called META_RES prev_mres; // readable; return flag of the previous plugin called
META_RES status; // readable; "highest" return flag so far META_RES status; // readable; "highest" return flag so far
void *orig_ret; // readable; return value from "real" function void *orig_ret; // readable; return value from "real" function
void *override_ret; // readable; return value from overriding/superceding plugin void *override_ret; // readable; return value from overriding/superceding plugin
} meta_globals_t; };
extern meta_globals_t *gpMetaGlobals; extern meta_globals_t *gpMetaGlobals;
#define SET_META_RESULT(result) gpMetaGlobals->mres = result #define SET_META_RESULT(result) gpMetaGlobals->mres = result
#define RETURN_META(result) \ #define RETURN_META(result) \
do { gpMetaGlobals->mres = result; return; } while (0) do { gpMetaGlobals->mres = result; return; } while (0)
#define RETURN_META_VALUE(result, value) \ #define RETURN_META_VALUE(result, value) \
do { gpMetaGlobals->mres=result; return(value); } while(0) do { gpMetaGlobals->mres = result; return value; } while (0)
#define META_RESULT_STATUS gpMetaGlobals->status #define META_RESULT_STATUS gpMetaGlobals->status
#define META_RESULT_PREVIOUS gpMetaGlobals->prev_mres #define META_RESULT_PREVIOUS gpMetaGlobals->prev_mres
#define META_RESULT_ORIG_RET(type) *(type *)gpMetaGlobals->orig_ret #define META_RESULT_ORIG_RET(type) *(type *)gpMetaGlobals->orig_ret
#define META_RESULT_OVERRIDE_RET(type) *(type *)gpMetaGlobals->override_ret #define META_RESULT_OVERRIDE_RET(type) *(type *)gpMetaGlobals->override_ret
// Table of getapi functions, retrieved from each plugin. // Table of getapi functions, retrieved from each plugin.
typedef struct { struct META_FUNCTIONS
{
GETENTITYAPI_FN pfnGetEntityAPI; GETENTITYAPI_FN pfnGetEntityAPI;
GETENTITYAPI_FN pfnGetEntityAPI_Post; GETENTITYAPI_FN pfnGetEntityAPI_Post;
GETENTITYAPI2_FN pfnGetEntityAPI2; GETENTITYAPI2_FN pfnGetEntityAPI2;
@ -109,13 +73,14 @@ typedef struct {
GETNEWDLLFUNCTIONS_FN pfnGetNewDLLFunctions_Post; GETNEWDLLFUNCTIONS_FN pfnGetNewDLLFunctions_Post;
GET_ENGINE_FUNCTIONS_FN pfnGetEngineFunctions; GET_ENGINE_FUNCTIONS_FN pfnGetEngineFunctions;
GET_ENGINE_FUNCTIONS_FN pfnGetEngineFunctions_Post; GET_ENGINE_FUNCTIONS_FN pfnGetEngineFunctions_Post;
} META_FUNCTIONS; };
// Pair of function tables provided by game DLL. // Pair of function tables provided by game DLL.
typedef struct { struct gamedll_funcs_t
{
DLL_FUNCTIONS *dllapi_table; DLL_FUNCTIONS *dllapi_table;
NEW_DLL_FUNCTIONS *newapi_table; NEW_DLL_FUNCTIONS *newapi_table;
} gamedll_funcs_t; };
// Declared in plugin; referenced in macros. // Declared in plugin; referenced in macros.
extern gamedll_funcs_t *gpGamedllFuncs; extern gamedll_funcs_t *gpGamedllFuncs;
@ -126,46 +91,31 @@ extern mutil_funcs_t *gpMetaUtilFuncs;
// procedure. In particular, this will allow for DLL's that can be used as // procedure. In particular, this will allow for DLL's that can be used as
// both standalone DLL's and metamod plugins. (optional; not required in // both standalone DLL's and metamod plugins. (optional; not required in
// plugin) // plugin)
C_DLLEXPORT void Meta_Init(void); C_DLLEXPORT void Meta_Init();
typedef void (*META_INIT_FN) (void); typedef void (*META_INIT_FN)();
// Get info about plugin, compare meta_interface versions, provide meta // Get info about plugin, compare meta_interface versions, provide meta
// utility callback functions. // utility callback functions.
C_DLLEXPORT int Meta_Query(const char *interfaceVersion, C_DLLEXPORT int Meta_Query(char *interfaceVersion, plugin_info_t **plinfo, mutil_funcs_t *pMetaUtilFuncs);
plugin_info_t **plinfo, typedef int (*META_QUERY_FN) (char *interfaceVersion, plugin_info_t **plinfo, mutil_funcs_t *pMetaUtilFuncs);
mutil_funcs_t *pMetaUtilFuncs);
typedef int (*META_QUERY_FN) (const char *interfaceVersion,
plugin_info_t **plinfo,
mutil_funcs_t *pMetaUtilFuncs);
// Attach the plugin to the API; get the table of getapi functions; give // Attach the plugin to the API; get the table of getapi functions; give
// meta_globals and gamedll_funcs. // meta_globals and gamedll_funcs.
C_DLLEXPORT int Meta_Attach(PLUG_LOADTIME now, C_DLLEXPORT int Meta_Attach(PLUG_LOADTIME now, META_FUNCTIONS *pFunctionTable, meta_globals_t *pMGlobals, gamedll_funcs_t *pGamedllFuncs);
META_FUNCTIONS *pFunctionTable, typedef int (*META_ATTACH_FN) (PLUG_LOADTIME now, META_FUNCTIONS *pFunctionTable, meta_globals_t *pMGlobals, gamedll_funcs_t *pGamedllFuncs);
meta_globals_t *pMGlobals,
gamedll_funcs_t *pGamedllFuncs);
typedef int (*META_ATTACH_FN) (PLUG_LOADTIME now,
META_FUNCTIONS *pFunctionTable,
meta_globals_t *pMGlobals,
gamedll_funcs_t *pGamedllFuncs);
// Detach the plugin; tell why and when. // Detach the plugin; tell why and when.
C_DLLEXPORT int Meta_Detach(PLUG_LOADTIME now, PL_UNLOAD_REASON reason); C_DLLEXPORT int Meta_Detach(PLUG_LOADTIME now, PL_UNLOAD_REASON reason);
typedef int (*META_DETACH_FN) (PLUG_LOADTIME now, PL_UNLOAD_REASON reason); typedef int (*META_DETACH_FN) (PLUG_LOADTIME now, PL_UNLOAD_REASON reason);
// Standard HL SDK interface function prototypes. // Standard HL SDK interface function prototypes.
C_DLLEXPORT int GetEntityAPI_Post(DLL_FUNCTIONS *pFunctionTable, C_DLLEXPORT int GetEntityAPI_Post(DLL_FUNCTIONS *pFunctionTable, int interfaceVersion );
int interfaceVersion ); C_DLLEXPORT int GetEntityAPI2_Post(DLL_FUNCTIONS *pFunctionTable, int *interfaceVersion );
C_DLLEXPORT int GetEntityAPI2_Post(DLL_FUNCTIONS *pFunctionTable,
int *interfaceVersion );
// Additional SDK-like interface function prototypes. // Additional SDK-like interface function prototypes.
C_DLLEXPORT int GetNewDLLFunctions_Post(NEW_DLL_FUNCTIONS *pNewFunctionTable, C_DLLEXPORT int GetNewDLLFunctions_Post(NEW_DLL_FUNCTIONS *pNewFunctionTable, int *interfaceVersion );
int *interfaceVersion ); C_DLLEXPORT int GetEngineFunctions(enginefuncs_t *pengfuncsFromEngine, int *interfaceVersion);
C_DLLEXPORT int GetEngineFunctions(enginefuncs_t *pengfuncsFromEngine, C_DLLEXPORT int GetEngineFunctions_Post(enginefuncs_t *pengfuncsFromEngine, int *interfaceVersion);
int *interfaceVersion);
C_DLLEXPORT int GetEngineFunctions_Post(enginefuncs_t *pengfuncsFromEngine,
int *interfaceVersion);
// Convenience macros for accessing GameDLL functions. Note: these talk // Convenience macros for accessing GameDLL functions. Note: these talk
// _directly_ to the gamedll, and are not multiplexed through Metamod to // _directly_ to the gamedll, and are not multiplexed through Metamod to
@ -232,6 +182,3 @@ C_DLLEXPORT int GetEngineFunctions_Post(enginefuncs_t *pengfuncsFromEngine,
#define MNEW_GameShutdown MNEW_FUNC->pfnGameShutdown #define MNEW_GameShutdown MNEW_FUNC->pfnGameShutdown
#define MNEW_ShouldCollide MNEW_FUNC->pfnShouldCollide #define MNEW_ShouldCollide MNEW_FUNC->pfnShouldCollide
#define MNEW_CvarValue MNEW_FUNC->pfnCvarValue #define MNEW_CvarValue MNEW_FUNC->pfnCvarValue
#define MNEW_CvarValue2 MNEW_FUNC->pfnCvarValue2
#endif /* META_API_H */

View File

@ -1,51 +1,5 @@
// vi: set ts=4 sw=4 :
// vim: set tw=75 :
// meta_eiface.cpp - wrapper for engine/dll interface
/*
* Copyright (c) 2001-2006 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#include "precompiled.h" #include "precompiled.h"
// ------------------------------------------------------------------------
// meta_new_dll_functions_t
// ------------------------------------------------------------------------
// static member initialisation
int meta_new_dll_functions_t::sm_version = 0;
meta_new_dll_functions_t::meta_new_dll_functions_t( meta_new_dll_functions_t::meta_new_dll_functions_t(
void (*_pfnOnFreeEntPrivateData)(edict_t*), void (*_pfnOnFreeEntPrivateData)(edict_t*),
void (*_pfnGameShutdown)(void), void (*_pfnGameShutdown)(void),
@ -61,104 +15,16 @@ meta_new_dll_functions_t::meta_new_dll_functions_t(
pfnCvarValue2 = _pfnCvarValue2; pfnCvarValue2 = _pfnCvarValue2;
} }
void meta_new_dll_functions_t::copy_to(NEW_DLL_FUNCTIONS *_pFuncs) void meta_new_dll_functions_t::copy_to(NEW_DLL_FUNCTIONS *_pFuncs)
{ {
// This is where the magic happens. We check what version of the #if 0
// NEW_DLL_FUNCTIONS interface the engine has and calculate the size of // TODO: Implemented check regamedll
// that interface. Then we only copy the function pointers present in // exit
// that version over to the receiver, so that we do not overwrite his
// memory with functions that he doesn't know of in his copy of the
// struct.
size_t size = get_size();
if (0 == size) { #endif
// Ok, this is a real problem and should *not* happen. Q_memcpy(_pFuncs, this, sizeof(NEW_DLL_FUNCTIONS));
// We try to work with NEW_DLL_FUNCTIONS without knowing what
// interface the attached engine uses. This means that the classes
// defined herein are not used in the way they are meant to because
// someone forgot to first create a HL_enginefuncs_t object and
// initialise it with the pointers passed from the engine.
// We treat this as a major developer error and bluntly exit the
// whole process, assuming that this will never happen on a
// production server as it should have been caught by the developer
// during testing.
//
// We use a printf() to complain since we do not know if we have
// already attached to the engine and can use its alerting
// functions. This should be augemnted with a windows version
// popping open a message box.
fprintf(stderr, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
fprintf(stderr, "ERROR: INTERNAL ERROR.\n");
fprintf(stderr, " Attempt to use meta_new_dll_functions_t without"
" initialised engine interface version!\n");
fprintf(stderr, " %s at %d\n", __FILE__, __LINE__);
exit(1);
} }
memcpy(_pFuncs, this, size);
}
int meta_new_dll_functions_t::determine_interface_version(void)
{
// If the meta_enginefuncs_t::version is 0, i.e. has not yet been
// determined, that is a problem and an error. We should probably throw
// a fit here or something.
// For now we just return 0 and leave it to the caller to complain.
if (meta_enginefuncs_t::version() == 0) return 0;
// The default version is 1.
sm_version = 1;
// With the enginefuncs interface version 156 the function
// pfnCvarValue() was added, which we call version 2.
if (meta_enginefuncs_t::version() >= 156) sm_version = 2;
// With the enginefuncs interface version 157 the function
// pfnCvarValue2() was added, which we call version 3.
if (meta_enginefuncs_t::version() >= 157) sm_version = 3;
return sm_version;
}
size_t meta_new_dll_functions_t::get_size(int _version)
{
size_t size = sizeof(NEW_DLL_FUNCTIONS);
if (0 == _version) {
// Use the current engine's interface version
_version = version();
// Error: meta_enginefuncs_t::version probably not yet set up.
if (0 == _version) return 0;
}
switch (_version) {
case 1:
// Version 1 is missing all functions from CvarValue() on.
size -= sizeof(FN_CVARVALUE);
case 2:
// Version 2 is missing all functions from CvarValue2() on.
size -= sizeof(FN_CVARVALUE2);
}
return size;
}
// --------------------------------------------------------------
// meta_enginefuncs_t
// --------------------------------------------------------------
// static member initialisation
int meta_enginefuncs_t::sm_version = 0;
// -----------------------------------------------------------------
// HL_enginefuncs
// -----------------------------------------------------------------
void HL_enginefuncs_t::initialise_interface(enginefuncs_t* _pFuncs) void HL_enginefuncs_t::initialise_interface(enginefuncs_t* _pFuncs)
{ {
set_from(_pFuncs); set_from(_pFuncs);
@ -166,166 +32,4 @@ void HL_enginefuncs_t::initialise_interface(enginefuncs_t* _pFuncs)
// Now the pfnAlertMessage is available and we trust it to be a valid // Now the pfnAlertMessage is available and we trust it to be a valid
// pointer, so flush the message buffer. // pointer, so flush the message buffer.
flush_ALERT_buffer(); flush_ALERT_buffer();
determine_engine_interface_version();
fixup_engine_interface();
}
// The following part (i.e. the end) of the enginefuncs_t struct is
// used to determine the engine interface version since it is the one
// that changed since SDK 212 engines. We call this the "signature" of
// the enginefuncs interface.
//
// Default version is 138. That's what the SDK says.
//
// 144: const char *(*pfnGetPlayerAuthId) ( edict_t *e );
//
// // PSV: Added for CZ training map
// // const char *(*pfnKeyNameForBinding) ( const char* pBinding );
//
// sequenceEntry_s* (*pfnSequenceGet) ( const char* fileName, const char* entryName );
// sentenceEntry_s* (*pfnSequencePickSentence) ( const char* groupName, int pickMethod, int *picked );
//
// // LH: Give access to filesize via filesystem
// 147: int (*pfnGetFileSize) ( const char *filename );
//
// unsigned int (*pfnGetApproxWavePlayLen) (const char *filepath);
// // MDC: Added for CZ career-mode
// int (*pfnIsCareerMatch) ( void );
//
// // BGC: return the number of characters of the localized string referenced by using "label"
// int (*pfnGetLocalizedStringLength) (const char *label);
//
// // BGC: added to facilitate persistent storage of tutor message decay values for
// // different career game profiles. Also needs to persist regardless of mp.dll being
// // destroyed and recreated.
// void (*pfnRegisterTutorMessageShown) (int mid);
// int (*pfnGetTimesTutorMessageShown) (int mid);
// void (*pfnProcessTutorMessageDecayBuffer) (int *buffer, int bufferLength);
// void (*pfnConstructTutorMessageDecayBuffer) (int *buffer, int bufferLength);
// 155: void (*pfnResetTutorMessageDecayData) ( void );
// 156: void (*pfnQueryClientCvarValue) ( const edict_t *player, const char *cvarName );
// 157: void (*pfnQueryClientCvarValue2) ( const edict_t *player, const char *cvarName, int requestID );
// 158: int (*pfnCheckParm) ( const char *pchCmdLineToke, char **ppnext );
void HL_enginefuncs_t::determine_engine_interface_version(void) const
{
// We only need to do this once.
if (0 != sm_version) {
return;
}
// Now begins our heuristic, where we try to determine the engine
// interface version.
// As alluded to above we are currently only interested, and thus
// only detect, versions 144, 147, 156 or 157 (defined by us).
// The minimal default is 138.
sm_version = 138;
// If GetPlayerAuthId() is present, it is at least 144,
// otherwise leave it at the default 138.
// This may give incorrect results for *really* old engine versions,
// i.e. pre 1.1.0.8. We live with that risk. No one uses them anymore.
// Really.
if (pfnGetPlayerAuthId == NULL) {
return;
}
sm_version = 144;
// The two function pointers for pfnSequenceGet() and
// pfnSequencePickSentence() are only valid in a few engine versions
// and are set to NULL in most other version, so they don't get
// checked.
// If pfnGetFileSize() is present, it is at least 147,
// otherwise leave it at the so far determined value.
if (pfnGetFileSize == NULL) {
return;
}
sm_version = 147;
// Now it gets a bit fuzzy. If all of the functions following GetFileSize()
// but before QueryClientCvarValue() are valid, it is at least 155.
// If even one of them is NULL, then our version can't be higher than 147,
// so use 147. Actually, it could be that there exist engine
// versions where one of them is NULL but the interface is still at
// least 155. If such an engine is found in use, adaptions need to be
// made.
// (Yes, I know this could be done with a little hacky for() loop. We
// don't need to do hacky here.)
int cntInvals = 0;
if (pfnGetApproxWavePlayLen == NULL) cntInvals++;
if (pfnIsCareerMatch == NULL) cntInvals++;
if (pfnGetLocalizedStringLength == NULL) cntInvals++;
if (pfnRegisterTutorMessageShown == NULL) cntInvals++;
if (pfnGetTimesTutorMessageShown == NULL) cntInvals++;
if (pfnProcessTutorMessageDecayBuffer == NULL) cntInvals++;
if (pfnConstructTutorMessageDecayBuffer == NULL) cntInvals++;
if (pfnResetTutorMessageDecayData == NULL) cntInvals++;
if (cntInvals > 0) {
return;
}
sm_version = 155;
// All functions up to QueryClientCvarValue() are valid.
// If QueryClientCvarValue() is not valid, leave it at the so far
// determined version. Otherwise the version is at least 156.
if (pfnQueryClientCvarValue == NULL) {
return;
}
sm_version = 156;
// All functions up to QueryClientCvarValue2() are valid.
// If QueryClientCvarValue2() is not valid, leave it at the so far
// determined version. Otherwise the version is at least 157.
if (pfnQueryClientCvarValue2 == NULL) {
return;
}
sm_version = 157;
// All functions up to CheckParm() are valid.
// If CheckParm() is not valid, leave it at the so far determined
// version. Otherwise the version is at least 158.
if (pfnEngCheckParm == NULL) {
return;
}
sm_version = 158;
}
void HL_enginefuncs_t::fixup_engine_interface(void)
{
// This function will make sure that all function pointers that aren't
// valid are set to NULL, depending on the engine interface version.
// Sometimes a pointer has a valid value although the function doesn't
// exist in the interface version.
switch (version()) {
case 138:
pfnGetPlayerAuthId = NULL;
case 144:
pfnSequenceGet = NULL;
pfnSequencePickSentence = NULL;
pfnGetFileSize = NULL;
case 147:
pfnGetApproxWavePlayLen = NULL;
pfnIsCareerMatch = NULL;
pfnGetLocalizedStringLength = NULL;
pfnRegisterTutorMessageShown = NULL;
pfnGetTimesTutorMessageShown = NULL;
pfnProcessTutorMessageDecayBuffer = NULL;
pfnConstructTutorMessageDecayBuffer = NULL;
pfnResetTutorMessageDecayData = NULL;
case 155:
pfnQueryClientCvarValue = NULL;
case 156:
pfnQueryClientCvarValue2 = NULL;
case 157:
pfnEngCheckParm = NULL;
}
} }

View File

@ -1,48 +1,4 @@
#pragma once
// vi: set ts=4 sw=4 :
// vim: set tw=75 :
// meta_eiface.h - wrapper for engine/dll interface
/*
* Copyright (c) 2001-2006 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef MM_META_EIFACE_H
#define MM_META_EIFACE_H
#include <extdll.h> // NEW_DLL_FUNCTIONS, enginefuncs_t
#include <string.h> // memset()
// We use our own versions of the engine/dll interface structs. We add a // We use our own versions of the engine/dll interface structs. We add a
// few dummy entries to the end and set them to 0. That way we are // few dummy entries to the end and set them to 0. That way we are
@ -51,16 +7,13 @@
// dll overwriting our memory when using an old Metamod with a new game // dll overwriting our memory when using an old Metamod with a new game
// dll. // dll.
// --------------------------------------------------------------------
// meta_new_dll_functions_t // meta_new_dll_functions_t
// --------------------------------------------------------------------
struct meta_new_dll_functions_t: public NEW_DLL_FUNCTIONS struct meta_new_dll_functions_t: public NEW_DLL_FUNCTIONS
{ {
meta_new_dll_functions_t(); meta_new_dll_functions_t();
meta_new_dll_functions_t( meta_new_dll_functions_t(
void (*pfnOnFreeEntPrivateData)(edict_t *), void (*pfnOnFreeEntPrivateData)(edict_t *),
void (*pfnGameShutdown)(void), void (*pfnGameShutdown)(),
int (*pfnShouldCollide)(edict_t *, edict_t *), int (*pfnShouldCollide)(edict_t *, edict_t *),
void (*pfnCvarValue)(const edict_t *, const char *), void (*pfnCvarValue)(const edict_t *, const char *),
void (*pfnCvarValue2)(const edict_t *, int, const char *, const char *) void (*pfnCvarValue2)(const edict_t *, int, const char *, const char *)
@ -74,106 +27,33 @@ struct meta_new_dll_functions_t : public NEW_DLL_FUNCTIONS
// Copy the pointers from this object to a NEW_DLL_FUNCTIONS struct. // Copy the pointers from this object to a NEW_DLL_FUNCTIONS struct.
void copy_to(NEW_DLL_FUNCTIONS* pFuncs); void copy_to(NEW_DLL_FUNCTIONS* pFuncs);
// return the engine's version of NEW_DLL_FUNCTIONS
int version(void);
private:
// data :
// The NEW_DLL_FUNCTIONS struct also changed, but the version
// number did not change. That begs the question why to have
// it versioned in the first place, but whaddaya know.
// While the official version is left at 1, we internally
// calculate a different version of the engine's NEW_DLL_FUNCTIONS
// struct since we know that the engine lies to us about the
// version that it uses.
//
// The default version is 1.
//
// With the enginefuncs interface version 156 the function
// pfnCvarValue() was added, which we call version 2.
//
// With the enginefuncs interface version 157 the function
// pfnCvarValue2() was added, which we call version 3.
//
// If Valve ever decides to change the version of the
// NEW_DLL_FUNCTIONS interface in the future (haha),
// we are in trouble and will need to change our
// internal versions.
static int sm_version;
// functions :
// Calculates our idea of the engine's version of the
// NEW_DLL_FUNCTIONS interface. Stores this version for future
// reference in m_version and returns it.
static int determine_interface_version(void);
// Comfort function to determine the size of the NEW_DLL_FUNCTIONS
// struct for the different versions.
// If passed a version number other than 0, the size for that
// specific version is returned.
// If passed 0 as version number (default) the size for the version
// that was determined to be the version of the currently connected
// engine's interface. Should that version have not yet been
// determined (via the enginefuncs_t interface), 0 is returned to
// indicated this error state.
size_t get_size(int version = 0);
}; };
// Inline functions
inline meta_new_dll_functions_t::meta_new_dll_functions_t() inline meta_new_dll_functions_t::meta_new_dll_functions_t()
{ {
memset(this, 0, sizeof(meta_new_dll_functions_t)); Q_memset(this, 0, sizeof(meta_new_dll_functions_t));
} }
inline meta_new_dll_functions_t::meta_new_dll_functions_t(const meta_new_dll_functions_t& _rhs) inline meta_new_dll_functions_t::meta_new_dll_functions_t(const meta_new_dll_functions_t& _rhs)
{ {
memcpy(this, &_rhs, sizeof(NEW_DLL_FUNCTIONS)); Q_memcpy(this, &_rhs, sizeof(NEW_DLL_FUNCTIONS));
} }
inline meta_new_dll_functions_t& meta_new_dll_functions_t::operator=(const meta_new_dll_functions_t& _rhs) inline meta_new_dll_functions_t& meta_new_dll_functions_t::operator=(const meta_new_dll_functions_t& _rhs)
{ {
memcpy(this, &_rhs, sizeof(NEW_DLL_FUNCTIONS)); Q_memcpy(this, &_rhs, sizeof(NEW_DLL_FUNCTIONS));
return *this; return *this;
} }
inline void meta_new_dll_functions_t::set_from(NEW_DLL_FUNCTIONS* _pFuncs) inline void meta_new_dll_functions_t::set_from(NEW_DLL_FUNCTIONS* _pFuncs)
{ {
memcpy(this, _pFuncs, sizeof(NEW_DLL_FUNCTIONS)); Q_memcpy(this, _pFuncs, sizeof(NEW_DLL_FUNCTIONS));
} }
inline int meta_new_dll_functions_t::version(void)
{
return sm_version ? sm_version : determine_interface_version();
}
// No meta version of DLL_FUNCTIONS because that won't be changing anymore.
// --------------------------------------------------------------------
// meta_enginefuncs_t
// --------------------------------------------------------------------
// meta_enginefuncs_t // meta_enginefuncs_t
struct meta_enginefuncs_t : public enginefuncs_t struct meta_enginefuncs_t : public enginefuncs_t
{ {
meta_enginefuncs_t() meta_enginefuncs_t() {};
{
};
meta_enginefuncs_t(enginefuncs_t* pFuncs) meta_enginefuncs_t(enginefuncs_t* pFuncs)
{ {
set_from(pFuncs); set_from(pFuncs);
@ -184,72 +64,26 @@ struct meta_enginefuncs_t : public enginefuncs_t
// Copy the pointers from this object to an enginefuncs_t struct. // Copy the pointers from this object to an enginefuncs_t struct.
void copy_to(enginefuncs_t* pFuncs); void copy_to(enginefuncs_t* pFuncs);
// The version of the engine functions interface. It is frozen at 138. But no one knows
// when that was and what it looked like then. So we simply interprete it as the
// number of functions that the enginefuncs struct contains.
//
// That means we get gaps inbetween versions and right now we can detect only
// about five different versions anyway, but that suffices for the current itches
// to get scratched.
//
// The default is hence 138.
// A value of 0 means "not yet determined".
// Other possible versions currently detectable:
// 144: engine versions after 1.1.0.9 build 1996
// 147: engine versions after build 2384 with pfnGetFileSize()
// 155: all versions between build 2384 and the one
// including pfnQueryClientCvarValue()
// 156: includes pfnQueryClientCvarValue()
// 157: includes pfnQueryClientCvarValue2()
// 158: includes pfnCheckParm()
static int sm_version;
static int version(void);
}; };
//
// Inline functions
//
inline void meta_enginefuncs_t::set_from(enginefuncs_t* _pFuncs) inline void meta_enginefuncs_t::set_from(enginefuncs_t* _pFuncs)
{ {
memcpy(this, _pFuncs, sizeof(enginefuncs_t)); Q_memcpy(this, _pFuncs, sizeof(enginefuncs_t));
} }
inline void meta_enginefuncs_t::copy_to(enginefuncs_t* _pFuncs) inline void meta_enginefuncs_t::copy_to(enginefuncs_t* _pFuncs)
{ {
memcpy(_pFuncs, this, sizeof(enginefuncs_t)); Q_memcpy(_pFuncs, this, sizeof(enginefuncs_t));
} }
inline int meta_enginefuncs_t::version(void)
{
return sm_version;
}
// --------------------------------------------------------------------
// HL_enginefuncs_t
// --------------------------------------------------------------------
//
// This is a specialisation of the meta_enginefuncs_t struct which is only // This is a specialisation of the meta_enginefuncs_t struct which is only
// used for the initial copy of the engine functions, i.e. those we get // used for the initial copy of the engine functions, i.e. those we get
// passed from the HL engine right at the beginning. // passed from the HL engine right at the beginning.
// This specialisation does some extra initialisation when getting set up
// like calculating the engine interface version and fixing up any invalid
// pointers.
// Since there is only one master copy of engine functions this could be // Since there is only one master copy of engine functions this could be
// implemented as a singleton. This is left as an option for later. // implemented as a singleton. This is left as an option for later.
//
struct HL_enginefuncs_t: public meta_enginefuncs_t struct HL_enginefuncs_t: public meta_enginefuncs_t
{ {
// functions : HL_enginefuncs_t() {};
HL_enginefuncs_t()
{
};
// Fill this object with pointers copied from an enginefuncs_t struct // Fill this object with pointers copied from an enginefuncs_t struct
// and fixup the interface. // and fixup the interface.
@ -257,32 +91,15 @@ struct HL_enginefuncs_t : public meta_enginefuncs_t
// with the pointers passed from the HL engine. // with the pointers passed from the HL engine.
void initialise_interface(enginefuncs_t* pFuncs); void initialise_interface(enginefuncs_t* pFuncs);
private: private:
// functions :
// Moving copy_to() and set_from() to the private space. // Moving copy_to() and set_from() to the private space.
void set_from(enginefuncs_t* pFuncs) void set_from(enginefuncs_t* pFuncs)
{ {
meta_enginefuncs_t::set_from(pFuncs); meta_enginefuncs_t::set_from(pFuncs);
}; }
void copy_to(enginefuncs_t* pFuncs) void copy_to(enginefuncs_t* pFuncs)
{ {
meta_enginefuncs_t::copy_to(pFuncs); meta_enginefuncs_t::copy_to(pFuncs);
}
}; };
// Determine the version of the engine interface from the
// enginefuncs signature.
void determine_engine_interface_version(void) const;
// Fixup the enginefuncs pointers according to the determined
// version as some pointers may be invalid.
void fixup_engine_interface(void);
};
#endif /* META_EIFACE_H */

View File

@ -1,50 +1,15 @@
// vi: set ts=4 sw=4 :
// vim: set tw=75 :
// metamod.cpp - (main) implementation of metamod operations
/*
* Copyright (c) 2001-2004 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#include "precompiled.h" #include "precompiled.h"
cvar_t meta_version = {"metamod_version", VVERSION, FCVAR_SERVER , 0, NULL}; cvar_t meta_version = { "metamod_version", APP_VERSION_STRD, FCVAR_SERVER, 0, nullptr };
MConfig static_config; MConfig static_config;
MConfig *g_config = &static_config; MConfig *g_config = &static_config;
option_t global_options[] = { option_t global_options[] =
{
{ "debuglevel", CF_INT, &g_config->debuglevel, "0" }, { "debuglevel", CF_INT, &g_config->debuglevel, "0" },
{"gamedll", CF_PATH, &g_config->gamedll, NULL},
{ "plugins_file", CF_PATH, &g_config->plugins_file, PLUGINS_INI }, { "plugins_file", CF_PATH, &g_config->plugins_file, PLUGINS_INI },
{ "exec_cfg", CF_STR, &g_config->exec_cfg, EXEC_CFG }, { "exec_cfg", CF_STR, &g_config->exec_cfg, EXEC_CFG },
// list terminator // list terminator
{ NULL, CF_NONE, NULL, NULL } { NULL, CF_NONE, NULL, NULL }
}; };
@ -69,31 +34,31 @@ int requestid_counter = 0;
#ifdef UNFINISHED #ifdef UNFINISHED
MHookList *Hooks; MHookList *Hooks;
#endif /* UNFINISHED */ #endif // UNFINISHED
// Very first metamod function that's run. // Very first metamod function that's run.
// Do startup operations... // Do startup operations...
void metamod_startup(void) void metamod_startup()
{ {
const char *mmfile = NULL; const char *mmfile = NULL;
const char *cfile = NULL; const char *cfile = NULL;
const char *cp; const char *cp;
META_CONS(" "); META_CONS(" ");
META_CONS(" %s version %s Copyright (c) 2001-%s %s", VNAME, VVERSION, COPYRIGHT_YEAR, VAUTHOR); META_CONS(" Metamod version %s Copyright (c) 2001-2016 Will Day (modification ReHLDS Team)", APP_VERSION_STRD);
META_CONS(" %s comes with ABSOLUTELY NO WARRANTY; for details type `meta gpl'.", VNAME); META_CONS(" Metamod comes with ABSOLUTELY NO WARRANTY; for details type `meta gpl'.");
META_CONS(" This is free software, and you are welcome to redistribute it"); META_CONS(" This is free software, and you are welcome to redistribute it");
META_CONS(" under certain conditions; type `meta gpl' for details."); META_CONS(" under certain conditions; type `meta gpl' for details.");
META_CONS(" "); META_CONS(" ");
META_LOG("%s v%s %s", VNAME, VVERSION, VDATE); META_CONS("Metamod v%s, API (%s)", APP_VERSION_STRD, META_INTERFACE_VERSION);
META_LOG("by %s", VAUTHOR); META_CONS("Metamod build: " __TIME__ " " __DATE__ " (" APP_VERSION_STRD ")");
META_LOG(" %s", VURL); META_CONS("Metamod from: " APP_COMMITS_URL APP_COMMIT_ID " " APP_COMMIT_AUTHOR "");
META_LOG("compiled: %s %s (%s)", COMPILE_TIME, COMPILE_TZONE, OPT_TYPE);
// If running with "+developer", allow an opportunity to break in with // If running with "+developer", allow an opportunity to break in with
// a debugger. // a debugger.
if ((int) CVAR_GET_FLOAT("developer") != 0) { if ((int) CVAR_GET_FLOAT("developer") != 0)
{
//sleep(10); // TODO: WAT?????? //sleep(10); // TODO: WAT??????
} }
@ -102,7 +67,8 @@ void metamod_startup(void)
// Get gamedir, very early on, because it seems we need it all over the // Get gamedir, very early on, because it seems we need it all over the
// place here at the start. // place here at the start.
if (!meta_init_gamedll()) { if (!meta_init_gamedll())
{
META_ERROR("Failure to init game DLL; exiting..."); META_ERROR("Failure to init game DLL; exiting...");
do_exit(1); do_exit(1);
} }
@ -121,13 +87,13 @@ void metamod_startup(void)
g_config->init(global_options); g_config->init(global_options);
// Find config file // Find config file
cfile = CONFIG_INI; cfile = CONFIG_INI;
if ((cp = LOCALINFO("mm_configfile")) && *cp != '\0') { if ((cp = LOCALINFO("mm_configfile")) && *cp != '\0')
{
META_LOG("Configfile specified via localinfo: %s", cp); META_LOG("Configfile specified via localinfo: %s", cp);
if (valid_gamedir_file(cp)) if (valid_gamedir_file(cp))
cfile = cp; cfile = cp;
else else
META_ERROR("Empty/missing config.ini file: %s; falling back to %s", META_ERROR("Empty/missing config.ini file: %s; falling back to %s", cp, cfile);
cp, cfile);
} }
// Load config file // Load config file
if (valid_gamedir_file(cfile)) if (valid_gamedir_file(cfile))
@ -136,24 +102,27 @@ void metamod_startup(void)
META_DEBUG(2, ("No config.ini file found: %s", CONFIG_INI)); META_DEBUG(2, ("No config.ini file found: %s", CONFIG_INI));
// Now, override config options with localinfo commandline options. // Now, override config options with localinfo commandline options.
if ((cp = LOCALINFO("mm_debug")) && *cp != '\0') { if ((cp = LOCALINFO("mm_debug")) && *cp != '\0')
{
META_LOG("Debuglevel specified via localinfo: %s", cp); META_LOG("Debuglevel specified via localinfo: %s", cp);
g_config->set("debuglevel", cp); g_config->set("debuglevel", cp);
} }
if ((cp = LOCALINFO("mm_gamedll")) && *cp != '\0') { if ((cp = LOCALINFO("mm_gamedll")) && *cp != '\0')
{
META_LOG("Gamedll specified via localinfo: %s", cp); META_LOG("Gamedll specified via localinfo: %s", cp);
g_config->set("gamedll", cp); g_config->set("gamedll", cp);
} }
if ((cp = LOCALINFO("mm_pluginsfile")) && *cp != '\0') { if ((cp = LOCALINFO("mm_pluginsfile")) && *cp != '\0')
{
META_LOG("Pluginsfile specified via localinfo: %s", cp); META_LOG("Pluginsfile specified via localinfo: %s", cp);
g_config->set("plugins_file", cp); g_config->set("plugins_file", cp);
} }
if ((cp = LOCALINFO("mm_execcfg")) && *cp != '\0') { if ((cp = LOCALINFO("mm_execcfg")) && *cp != '\0')
{
META_LOG("Execcfg specified via localinfo: %s", cp); META_LOG("Execcfg specified via localinfo: %s", cp);
g_config->set("exec_cfg", cp); g_config->set("exec_cfg", cp);
} }
// Check for an initial debug level, since cfg files don't get exec'd // Check for an initial debug level, since cfg files don't get exec'd
// until later. // until later.
if (g_config->debuglevel != 0) if (g_config->debuglevel != 0)
@ -176,13 +145,14 @@ void metamod_startup(void)
g_engine.pl_funcs->pfnCVarRegister = meta_CVarRegister; g_engine.pl_funcs->pfnCVarRegister = meta_CVarRegister;
g_engine.pl_funcs->pfnCvar_RegisterVariable = meta_CVarRegister; g_engine.pl_funcs->pfnCvar_RegisterVariable = meta_CVarRegister;
g_engine.pl_funcs->pfnRegUserMsg = meta_RegUserMsg; g_engine.pl_funcs->pfnRegUserMsg = meta_RegUserMsg;
if (g_engine.pl_funcs->pfnQueryClientCvarValue) if (g_engine.pl_funcs->pfnQueryClientCvarValue)
g_engine.pl_funcs->pfnQueryClientCvarValue = meta_QueryClientCvarValue; g_engine.pl_funcs->pfnQueryClientCvarValue = meta_QueryClientCvarValue;
#ifdef UNFINISHED #ifdef UNFINISHED
// Init the list of event/logline hooks. // Init the list of event/logline hooks.
Hooks = new MHookList(); Hooks = new MHookList();
#endif /* UNFINISHED */ #endif
// Before, we loaded plugins before loading the game DLL, so that if no // Before, we loaded plugins before loading the game DLL, so that if no
// plugins caught engine functions, we could pass engine funcs straight // plugins caught engine functions, we could pass engine funcs straight
@ -208,21 +178,24 @@ void metamod_startup(void)
// Fall back to old plugins filename, if configured one isn't found. // Fall back to old plugins filename, if configured one isn't found.
mmfile = PLUGINS_INI; mmfile = PLUGINS_INI;
if (!valid_gamedir_file(PLUGINS_INI) && valid_gamedir_file(OLD_PLUGINS_INI)) if (!valid_gamedir_file(PLUGINS_INI) && valid_gamedir_file(OLD_PLUGINS_INI))
mmfile = OLD_PLUGINS_INI; mmfile = OLD_PLUGINS_INI;
if (valid_gamedir_file(g_config->plugins_file)) if (valid_gamedir_file(g_config->plugins_file))
mmfile = g_config->plugins_file; mmfile = g_config->plugins_file;
else else
META_ERROR("g_plugins file is empty/missing: %s; falling back to %s", META_ERROR("g_plugins file is empty/missing: %s; falling back to %s", g_config->plugins_file, mmfile);
g_config->plugins_file, mmfile);
g_plugins = new MPluginList(mmfile); g_plugins = new MPluginList(mmfile);
if (!meta_load_gamedll()) { if (!meta_load_gamedll())
{
META_ERROR("Failure to load game DLL; exiting..."); META_ERROR("Failure to load game DLL; exiting...");
do_exit(1); do_exit(1);
} }
if (!g_plugins->load()) {
if (!g_plugins->load())
{
META_ERROR("Failure to load plugins..."); META_ERROR("Failure to load plugins...");
// Exit on failure here? Dunno... // Exit on failure here? Dunno...
} }
@ -230,7 +203,7 @@ void metamod_startup(void)
#ifdef UNFINISHED #ifdef UNFINISHED
// Start up the log parsing thread. // Start up the log parsing thread.
startup_logparse_thread(); startup_logparse_thread();
#endif /* UNFINISHED */ #endif
// Allow for commands to metamod plugins at startup. Autoexec.cfg is // Allow for commands to metamod plugins at startup. Autoexec.cfg is
// read too early, and server.cfg is read too late. // read too early, and server.cfg is read too late.
@ -240,18 +213,21 @@ void metamod_startup(void)
// messages. // messages.
if (valid_gamedir_file(g_config->exec_cfg)) if (valid_gamedir_file(g_config->exec_cfg))
mmfile = g_config->exec_cfg; mmfile = g_config->exec_cfg;
else if (valid_gamedir_file(OLD_EXEC_CFG)) else if (valid_gamedir_file(OLD_EXEC_CFG))
mmfile = OLD_EXEC_CFG; mmfile = OLD_EXEC_CFG;
else else
mmfile = NULL; mmfile = NULL;
if (mmfile) { if (mmfile)
{
if (mmfile[0] == '/') if (mmfile[0] == '/')
META_ERROR("Cannot exec absolute pathnames: %s", mmfile); META_ERROR("Cannot exec absolute pathnames: %s", mmfile);
else { else
{
char cmd[NAME_MAX]; char cmd[NAME_MAX];
META_LOG("Exec'ing metamod exec.cfg: %s...", mmfile); META_LOG("Exec'ing metamod exec.cfg: %s...", mmfile);
snprintf(cmd, sizeof(cmd), "exec %s\n", mmfile); Q_snprintf(cmd, sizeof(cmd), "exec %s\n", mmfile);
SERVER_COMMAND(cmd); SERVER_COMMAND(cmd);
} }
} }
@ -265,7 +241,7 @@ mBOOL meta_init_gamedll(void)
char gamedir[PATH_MAX]; char gamedir[PATH_MAX];
char *cp; char *cp;
memset(&GameDLL, 0, sizeof(GameDLL)); Q_memset(&GameDLL, 0, sizeof(GameDLL));
GET_GAME_DIR(gamedir); GET_GAME_DIR(gamedir);
normalize_pathname(gamedir); normalize_pathname(gamedir);
@ -280,32 +256,37 @@ mBOOL meta_init_gamedll(void)
// Note: the code has always assumed the server op wouldn't do: // Note: the code has always assumed the server op wouldn't do:
// hlds -game other/firearms // hlds -game other/firearms
// //
if (is_absolute_path(gamedir)) { if (is_absolute_path(gamedir))
{
// Old style; GET_GAME_DIR returned full pathname. Copy this into // Old style; GET_GAME_DIR returned full pathname. Copy this into
// our gamedir, and truncate to get the game name. // our gamedir, and truncate to get the game name.
// (note check for both linux and win32 full pathname.) // (note check for both linux and win32 full pathname.)
strncpy(GameDLL.gamedir, gamedir, sizeof GameDLL.gamedir - 1); Q_strncpy(GameDLL.gamedir, gamedir, sizeof(GameDLL.gamedir) - 1);
GameDLL.gamedir[sizeof GameDLL.gamedir - 1] = '\0'; GameDLL.gamedir[sizeof(GameDLL.gamedir) - 1] = '\0';
cp = strrchr(gamedir, '/') + 1;
strncpy(GameDLL.name, cp, sizeof GameDLL.name - 1); cp = Q_strrchr(gamedir, '/') + 1;
GameDLL.name[sizeof GameDLL.name - 1] = '\0';
Q_strncpy(GameDLL.name, cp, sizeof(GameDLL.name) - 1);
GameDLL.name[sizeof(GameDLL.name) - 1] = '\0';
} }
else { else
{
// New style; GET_GAME_DIR returned game name. Copy this into our // New style; GET_GAME_DIR returned game name. Copy this into our
// game name, and prepend the current working directory. // game name, and prepend the current working directory.
char buf[PATH_MAX]; char buf[PATH_MAX];
if (!_getcwd(buf, sizeof(buf))) { if (!_getcwd(buf, sizeof(buf)))
META_ERROR("dll: Couldn't get cwd; %s", strerror(errno)); {
META_WARNING("dll: Couldn't get cwd; %s", strerror(errno));
RETURN_ERRNO(mFALSE, ME_NULLRESULT); RETURN_ERRNO(mFALSE, ME_NULLRESULT);
} }
snprintf(GameDLL.gamedir, sizeof(GameDLL.gamedir), "%s/%s", buf, gamedir);
strncpy(GameDLL.name, gamedir, sizeof GameDLL.name - 1); Q_snprintf(GameDLL.gamedir, sizeof(GameDLL.gamedir), "%s/%s", buf, gamedir);
GameDLL.name[sizeof GameDLL.name - 1] = '\0'; Q_strncpy(GameDLL.name, gamedir, sizeof(GameDLL.name) - 1);
GameDLL.name[sizeof(GameDLL.name) - 1] = '\0';
} }
META_DEBUG(3, ("Game: %s", GameDLL.name)); META_DEBUG(3, ("Game: %s", GameDLL.name));
return mTRUE;
return (mTRUE);
} }
// Load game DLL. // Load game DLL.
@ -323,16 +304,17 @@ mBOOL meta_load_gamedll(void)
GETENTITYAPI2_FN pfn_getapi2; GETENTITYAPI2_FN pfn_getapi2;
GETENTITYAPI_FN pfn_getapi; GETENTITYAPI_FN pfn_getapi;
if (!setup_gamedll(&GameDLL)) { if (!setup_gamedll(&GameDLL))
{
META_ERROR("dll: Unrecognized game: %s", GameDLL.name); META_ERROR("dll: Unrecognized game: %s", GameDLL.name);
// meta_errno should be already set in lookup_game() // meta_errno should be already set in lookup_game()
return (mFALSE); return mFALSE;
} }
// open the game DLL // open the game DLL
if (!(GameDLL.handle = DLOPEN(GameDLL.pathname))) { if (!(GameDLL.handle = DLOPEN(GameDLL.pathname)))
META_ERROR("dll: Couldn't load game DLL %s: %s", GameDLL.pathname, {
DLERROR()); META_ERROR("dll: Couldn't load game DLL %s: %s", GameDLL.pathname, DLERROR());
RETURN_ERRNO(mFALSE, ME_DLOPEN); RETURN_ERRNO(mFALSE, ME_DLOPEN);
} }
@ -340,22 +322,21 @@ mBOOL meta_load_gamedll(void)
// wanted to catch one of the functions, but now that plugins are // wanted to catch one of the functions, but now that plugins are
// dynamically loadable at any time, we have to always pass our table, // dynamically loadable at any time, we have to always pass our table,
// so that any plugin loaded later can catch what they need to. // so that any plugin loaded later can catch what they need to.
if ((pfn_give_engfuncs = (GIVE_ENGINE_FUNCTIONS_FN) DLSYM(GameDLL.handle, if ((pfn_give_engfuncs = (GIVE_ENGINE_FUNCTIONS_FN) DLSYM(GameDLL.handle, "GiveFnptrsToDll")))
"GiveFnptrsToDll"))) { {
pfn_give_engfuncs(&meta_engfuncs, gpGlobals); pfn_give_engfuncs(&meta_engfuncs, gpGlobals);
META_DEBUG(3, ("dll: Game '%s': Called GiveFnptrsToDll", META_DEBUG(3, ("dll: Game '%s': Called GiveFnptrsToDll", GameDLL.name));
GameDLL.name));
} }
else { else
META_ERROR("dll: Couldn't find GiveFnptrsToDll() in game DLL '%s': %s", {
GameDLL.name, DLERROR()); META_ERROR("dll: Couldn't find GiveFnptrsToDll() in game DLL '%s': %s", GameDLL.name, DLERROR());
RETURN_ERRNO(mFALSE, ME_DLMISSING); RETURN_ERRNO(mFALSE, ME_DLMISSING);
} }
// Yes...another macro. // Yes...another macro.
#define GET_FUNC_TABLE_FROM_GAME(gamedll, pfnGetFuncs, STR_GetFuncs, struct_field, API_TYPE, TABLE_TYPE, vers_pass, vers_int, vers_want, gotit) \ #define GET_FUNC_TABLE_FROM_GAME(gamedll, pfnGetFuncs, STR_GetFuncs, struct_field, API_TYPE, TABLE_TYPE, vers_pass, vers_int, vers_want, gotit) \
if ((pfnGetFuncs = (API_TYPE) DLSYM(gamedll.handle, STR_GetFuncs))) { \ if ((pfnGetFuncs = (API_TYPE) DLSYM(gamedll.handle, STR_GetFuncs))) { \
gamedll.funcs.struct_field = (TABLE_TYPE*) calloc(1, sizeof(TABLE_TYPE)); \ gamedll.funcs.struct_field = (TABLE_TYPE *)Q_calloc(1, sizeof(TABLE_TYPE)); \
if (!gamedll.funcs.struct_field) {\ if (!gamedll.funcs.struct_field) {\
META_ERROR("malloc failed for gamedll struct_field: %s", STR_GetFuncs); \ META_ERROR("malloc failed for gamedll struct_field: %s", STR_GetFuncs); \
} \ } \
@ -365,7 +346,7 @@ mBOOL meta_load_gamedll(void)
} \ } \
else { \ else { \
META_ERROR("dll: Failure calling %s in game '%s'", STR_GetFuncs, gamedll.name); \ META_ERROR("dll: Failure calling %s in game '%s'", STR_GetFuncs, gamedll.name); \
free(gamedll.funcs.struct_field); \ Q_free(gamedll.funcs.struct_field); \
gamedll.funcs.struct_field = NULL; \ gamedll.funcs.struct_field = NULL; \
if (vers_int != vers_want) { \ if (vers_int != vers_want) { \
META_ERROR("dll: Interface version didn't match; we wanted %d, they had %d", vers_want, vers_int); \ META_ERROR("dll: Interface version didn't match; we wanted %d, they had %d", vers_want, vers_int); \
@ -390,31 +371,27 @@ mBOOL meta_load_gamedll(void)
// Look for API-NEW interface in Game dll. We do this before API2/API, because // Look for API-NEW interface in Game dll. We do this before API2/API, because
// that's what the engine appears to do.. // that's what the engine appears to do..
iface_vers = NEW_DLL_FUNCTIONS_VERSION; iface_vers = NEW_DLL_FUNCTIONS_VERSION;
GET_FUNC_TABLE_FROM_GAME(GameDLL, pfn_getapinew, "GetNewDLLFunctions", newapi_table, GET_FUNC_TABLE_FROM_GAME(GameDLL, pfn_getapinew, "GetNewDLLFunctions", newapi_table, GETNEWDLLFUNCTIONS_FN, meta_new_dll_functions_t, &iface_vers, iface_vers, NEW_DLL_FUNCTIONS_VERSION, found);
GETNEWDLLFUNCTIONS_FN, meta_new_dll_functions_t,
&iface_vers, iface_vers, NEW_DLL_FUNCTIONS_VERSION, found);
// Look for API2 interface in plugin; preferred over API-1. // Look for API2 interface in plugin; preferred over API-1.
found = 0; found = 0;
iface_vers = INTERFACE_VERSION; iface_vers = INTERFACE_VERSION;
GET_FUNC_TABLE_FROM_GAME(GameDLL, pfn_getapi2, "GetEntityAPI2", dllapi_table, GET_FUNC_TABLE_FROM_GAME(GameDLL, pfn_getapi2, "GetEntityAPI2", dllapi_table, GETENTITYAPI2_FN, DLL_FUNCTIONS, &iface_vers, iface_vers, INTERFACE_VERSION, found);
GETENTITYAPI2_FN, DLL_FUNCTIONS,
&iface_vers, iface_vers, INTERFACE_VERSION, found);
// Look for API-1 in plugin, if API2 interface wasn't found. // Look for API-1 in plugin, if API2 interface wasn't found.
if (!found) { if (!found)
{
found = 0; found = 0;
GET_FUNC_TABLE_FROM_GAME(GameDLL, pfn_getapi, "GetEntityAPI", dllapi_table, GET_FUNC_TABLE_FROM_GAME(GameDLL, pfn_getapi, "GetEntityAPI", dllapi_table, GETENTITYAPI_FN, DLL_FUNCTIONS, INTERFACE_VERSION, INTERFACE_VERSION, INTERFACE_VERSION, found);
GETENTITYAPI_FN, DLL_FUNCTIONS,
INTERFACE_VERSION, INTERFACE_VERSION, INTERFACE_VERSION, found);
} }
// If didn't find either, return failure. // If didn't find either, return failure.
if (!found) { if (!found)
{
META_ERROR("dll: Couldn't find either GetEntityAPI nor GetEntityAPI2 in game DLL '%s'", GameDLL.name); META_ERROR("dll: Couldn't find either GetEntityAPI nor GetEntityAPI2 in game DLL '%s'", GameDLL.name);
RETURN_ERRNO(mFALSE, ME_DLMISSING); RETURN_ERRNO(mFALSE, ME_DLMISSING);
} }
META_LOG("Game DLL for '%s' loaded successfully", GameDLL.desc); META_LOG("Game DLL for '%s' loaded successfully", GameDLL.desc);
return (mTRUE); return mTRUE;
} }

View File

@ -1,41 +1,4 @@
// vi: set ts=4 sw=4 : #pragma once
// vim: set tw=75 :
// metamod.h - (main) description of metamod operations
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef METAMOD_H
#define METAMOD_H
#include "meta_api.h" // META_RES, etc #include "meta_api.h" // META_RES, etc
#include "mlist.h" // MPluginList, etc #include "mlist.h" // MPluginList, etc
@ -45,7 +8,7 @@
#include "types_meta.h" // mBOOL #include "types_meta.h" // mBOOL
#include "mplayer.h" // MPlayerList #include "mplayer.h" // MPlayerList
#include "meta_eiface.h" // HL_enginefuncs_t, meta_enginefuncs_t #include "meta_eiface.h" // HL_enginefuncs_t, meta_enginefuncs_t
#include "engine_t.h" // engine_t, g_engine #include "engine_t.h" // engine_t, Engine
// file that lists plugins to load at startup // file that lists plugins to load at startup
#define PLUGINS_INI "addons/metamod/plugins.ini" #define PLUGINS_INI "addons/metamod/plugins.ini"
@ -61,12 +24,12 @@
// generic config file // generic config file
#define CONFIG_INI "addons/metamod/config.ini" #define CONFIG_INI "addons/metamod/config.ini"
// cvar to contain version // cvar to contain version
extern cvar_t meta_version; extern cvar_t meta_version;
// Info about the game dll/mod. // Info about the game dll/mod.
typedef struct gamedll_s { struct gamedll_t
{
char name[NAME_MAX]; // ie "cstrike" (from gamedir) char name[NAME_MAX]; // ie "cstrike" (from gamedir)
const char *desc; // ie "Counter-Strike" const char *desc; // ie "Counter-Strike"
char gamedir[PATH_MAX]; // ie "/home/willday/half-life/cstrike" char gamedir[PATH_MAX]; // ie "/home/willday/half-life/cstrike"
@ -75,7 +38,8 @@ typedef struct gamedll_s {
char real_pathname[PATH_MAX]; // in case pathname overridden by bot, etc char real_pathname[PATH_MAX]; // in case pathname overridden by bot, etc
DLHANDLE handle; DLHANDLE handle;
gamedll_funcs_t funcs; // dllapi_table, newapi_table gamedll_funcs_t funcs; // dllapi_table, newapi_table
} gamedll_t; };
extern gamedll_t GameDLL; extern gamedll_t GameDLL;
// SDK variables for storing engine funcs and globals. // SDK variables for storing engine funcs and globals.
@ -103,7 +67,7 @@ extern MRegMsgList *g_regMsgs;
#ifdef UNFINISHED #ifdef UNFINISHED
// List of event/logline hooks requested by plugins. // List of event/logline hooks requested by plugins.
extern MHookList *Hooks; extern MHookList *Hooks;
#endif /* UNFINISHED */ #endif
// Data provided to plugins. // Data provided to plugins.
// Separate copies to prevent plugins from modifying "readable" parts. // Separate copies to prevent plugins from modifying "readable" parts.
@ -132,12 +96,12 @@ extern int requestid_counter;
// Max players is always 32, small enough that we can use a static array // Max players is always 32, small enough that we can use a static array
extern MPlayerList g_Players; extern MPlayerList g_Players;
void metamod_startup(void); void metamod_startup();
mBOOL meta_init_gamedll(void); mBOOL meta_init_gamedll();
mBOOL meta_load_gamedll(void); mBOOL meta_load_gamedll();
// ===== lotsa macros... ====================================================== // lotsa macros...
// These are the meat of the metamod processing, and are as ugly as (or // These are the meat of the metamod processing, and are as ugly as (or
// uglier) than they look. This is done via macros, because of the varying // uglier) than they look. This is done via macros, because of the varying
@ -192,7 +156,7 @@ mBOOL meta_load_gamedll(void);
// accept. Thus there are "_void" versions of the 5 macros; these are // accept. Thus there are "_void" versions of the 5 macros; these are
// listed first. // listed first.
// ===== macros for void-returning functions ================================== // macros for void-returning functions
// declare/init some variables // declare/init some variables
#define SETUP_API_CALLS_void(FN_TYPE, pfnName, api_info_table) \ #define SETUP_API_CALLS_void(FN_TYPE, pfnName, api_info_table) \
@ -294,9 +258,9 @@ mBOOL meta_load_gamedll(void);
return; return;
// ===== macros for type-returning functions ================================== // macros for type-returning functions
// declare/init some variables // declare/init some variables
#define SETUP_API_CALLS(ret_t, ret_init, FN_TYPE, pfnName, api_info_table) \ #define SETUP_API_CALLS(ret_t, ret_init, FN_TYPE, pfnName, api_info_table) \
int i; \ int i; \
ret_t dllret = ret_init; \ ret_t dllret = ret_init; \
@ -415,12 +379,7 @@ mBOOL meta_load_gamedll(void);
PublicMetaGlobals = backup_meta_globals; \ PublicMetaGlobals = backup_meta_globals; \
if (status == MRES_OVERRIDE) { \ if (status == MRES_OVERRIDE) { \
META_DEBUG(loglevel, ("Returning (override) %s()", pfn_string)); \ META_DEBUG(loglevel, ("Returning (override) %s()", pfn_string)); \
return(override_ret); \ return override_ret; \
} \ } \
else \ else \
return(orig_ret); return orig_ret;
// ===== end macros ===========================================================
#endif /* METAMOD_H */

View File

@ -1,53 +1,19 @@
// vi: set ts=4 sw=4 :
// vim: set tw=75 :
// mlist.cpp - functions for list of plugins (class MPluginList)
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#include "precompiled.h" #include "precompiled.h"
// Constructor // Constructor
MPluginList::MPluginList(const char* ifile) : size(MAX_PLUGINS), endlist(0) MPluginList::MPluginList(const char* ifile) : size(MAX_PLUGINS), endlist(0)
{ {
// store filename of ini file // store filename of ini file
strncpy(inifile, ifile, sizeof inifile - 1); Q_strncpy(inifile, ifile, sizeof inifile - 1);
inifile[sizeof inifile - 1] = '\0'; inifile[sizeof inifile - 1] = '\0';
// initialize array // initialize array
memset(plist, 0, sizeof(plist)); Q_memset(plist, 0, sizeof(plist));
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++)
{
plist[i].index = i + 1; // 1-based plist[i].index = i + 1; // 1-based
} }
endlist = 0; endlist = 0;
} }
@ -60,7 +26,8 @@ MPlugin* MPluginList::find(DLHANDLE handle)
if (!handle) if (!handle)
RETURN_ERRNO(NULL, ME_ARGUMENT); RETURN_ERRNO(NULL, ME_ARGUMENT);
for (int i = 0; i < endlist; i++) { for (int i = 0; i < endlist; i++)
{
if (plist[i].status < PL_VALID) if (plist[i].status < PL_VALID)
continue; continue;
if (plist[i].handle == handle) if (plist[i].handle == handle)
@ -95,9 +62,11 @@ MPlugin* MPluginList::find(plid_t id)
if (!id) if (!id)
RETURN_ERRNO(NULL, ME_ARGUMENT); RETURN_ERRNO(NULL, ME_ARGUMENT);
for (int i = 0; i < endlist; i++) { for (int i = 0; i < endlist; i++)
{
if (plist[i].status < PL_VALID) if (plist[i].status < PL_VALID)
continue; continue;
if (plist[i].info == id) if (plist[i].info == id)
return &plist[i]; return &plist[i];
} }
@ -116,12 +85,15 @@ MPlugin* MPluginList::find(const char* findpath)
META_DEBUG(8, ("Looking for loaded plugin with dlfnamepath: %s", findpath)); META_DEBUG(8, ("Looking for loaded plugin with dlfnamepath: %s", findpath));
for (int i = 0; i < endlist; i++) { for (int i = 0; i < endlist; i++)
{
META_DEBUG(9, ("Looking at: plugin %s loadedpath: %s", plist[i].file, plist[i].pathname)); META_DEBUG(9, ("Looking at: plugin %s loadedpath: %s", plist[i].file, plist[i].pathname));
if (plist[i].status < PL_VALID) if (plist[i].status < PL_VALID)
continue; continue;
if (!strcmp(plist[i].pathname, findpath)) {
if (!Q_strcmp(plist[i].pathname, findpath))
{
META_DEBUG(8, ("Found loaded plugin %s", plist[i].file)); META_DEBUG(8, ("Found loaded plugin %s", plist[i].file));
return &plist[i]; return &plist[i];
} }
@ -143,11 +115,13 @@ MPlugin* MPluginList::find_memloc(void* memptr)
if (!memptr) if (!memptr)
RETURN_ERRNO(NULL, ME_ARGUMENT); RETURN_ERRNO(NULL, ME_ARGUMENT);
if (!(dlfile = DLFNAME(memptr))) { if (!(dlfile = DLFNAME(memptr)))
{
META_DEBUG(8, ("DLFNAME failed to find memloc %d", memptr)); META_DEBUG(8, ("DLFNAME failed to find memloc %d", memptr));
// meta_errno should be already set in DLFNAME // meta_errno should be already set in DLFNAME
return NULL; return NULL;
} }
return find(dlfile); return find(dlfile);
} }
@ -164,52 +138,66 @@ MPlugin* MPluginList::find_match(const char* prefix)
char buf[NAME_MAX ]; char buf[NAME_MAX ];
if (!prefix) if (!prefix)
{
RETURN_ERRNO(NULL, ME_ARGUMENT); RETURN_ERRNO(NULL, ME_ARGUMENT);
}
pfound = NULL; pfound = NULL;
len = strlen(prefix); len = Q_strlen(prefix);
snprintf(buf, sizeof(buf), "mm_%s", prefix); Q_snprintf(buf, sizeof(buf), "mm_%s", prefix);
for (i = 0; i < endlist; i++) { for (i = 0; i < endlist; i++)
{
iplug = &plist[i]; iplug = &plist[i];
if (iplug->status < PL_VALID) if (iplug->status < PL_VALID)
continue; continue;
if (iplug->info && _strnicmp(iplug->info->name, prefix, len) == 0) {
if (iplug->info && Q_strnicmp(iplug->info->name, prefix, len) == 0)
{
if (pfound) if (pfound)
RETURN_ERRNO(NULL, ME_NOTUNIQ); RETURN_ERRNO(NULL, ME_NOTUNIQ);
pfound = iplug; pfound = iplug;
continue; continue;
} }
else if (_strnicmp(iplug->desc, prefix, len) == 0) { else if (Q_strnicmp(iplug->desc, prefix, len) == 0)
{
if (pfound) if (pfound)
RETURN_ERRNO(NULL, ME_NOTUNIQ); RETURN_ERRNO(NULL, ME_NOTUNIQ);
pfound = iplug; pfound = iplug;
continue; continue;
} }
else if (_strnicmp(iplug->file, prefix, len) == 0) { else if (Q_strnicmp(iplug->file, prefix, len) == 0)
{
if (pfound) if (pfound)
RETURN_ERRNO(NULL, ME_NOTUNIQ); RETURN_ERRNO(NULL, ME_NOTUNIQ);
pfound = iplug; pfound = iplug;
continue; continue;
} }
else if (_strnicmp(iplug->file, buf, strlen(buf)) == 0) { else if (Q_strnicmp(iplug->file, buf, Q_strlen(buf)) == 0)
{
if (pfound) if (pfound)
RETURN_ERRNO(NULL, ME_NOTUNIQ); RETURN_ERRNO(NULL, ME_NOTUNIQ);
pfound = iplug; pfound = iplug;
continue; continue;
} }
else if (iplug->info else if (iplug->info && Q_strnicmp(iplug->info->logtag, prefix, len) == 0)
&& _strnicmp(iplug->info->logtag, prefix, len) == 0) { {
if (pfound) if (pfound)
RETURN_ERRNO(NULL, ME_NOTUNIQ); RETURN_ERRNO(NULL, ME_NOTUNIQ);
pfound = iplug; pfound = iplug;
continue; continue;
} }
} }
if (pfound)
return (pfound);
else
RETURN_ERRNO(NULL, ME_NOTFOUND);
}
if (pfound)
return pfound;
RETURN_ERRNO(NULL, ME_NOTFOUND);
}
// Find a plugin with same file, logtag, desc or significant // Find a plugin with same file, logtag, desc or significant
// prefix of file. Uses the platform_match() method of MPlugin. // prefix of file. Uses the platform_match() method of MPlugin.
@ -221,19 +209,24 @@ MPlugin* MPluginList::find_match(MPlugin* pmatch)
int i; int i;
MPlugin *iplug, *pfound; MPlugin *iplug, *pfound;
if (!pmatch) if (!pmatch)
{
RETURN_ERRNO(NULL, ME_ARGUMENT); RETURN_ERRNO(NULL, ME_ARGUMENT);
}
pfound = NULL; pfound = NULL;
for (i = 0; i < endlist; i++) { for (i = 0; i < endlist; i++)
{
iplug = &plist[i]; iplug = &plist[i];
if (pmatch->platform_match(iplug)) { if (pmatch->platform_match(iplug))
{
pfound = iplug; pfound = iplug;
break; break;
} }
} }
if (pfound) if (pfound)
return (pfound); return pfound;
else
RETURN_ERRNO(NULL, ME_NOTFOUND); RETURN_ERRNO(NULL, ME_NOTFOUND);
} }
@ -242,44 +235,52 @@ MPlugin* MPluginList::plugin_addload(plid_t plid, const char* fname, PLUG_LOADTI
MPlugin pl_temp; MPlugin pl_temp;
MPlugin *pl_found, *pl_added, *pl_loader; MPlugin *pl_found, *pl_added, *pl_loader;
if (!(pl_loader = find(plid))) { if (!(pl_loader = find(plid)))
{
META_DEBUG(1, ("Couldn't find plugin that gave this loading request!")); META_DEBUG(1, ("Couldn't find plugin that gave this loading request!"));
RETURN_ERRNO(NULL, ME_BADREQ); RETURN_ERRNO(NULL, ME_BADREQ);
} }
memset(&pl_temp, 0, sizeof(pl_temp)); Q_memset(&pl_temp, 0, sizeof(pl_temp));
if (!pl_temp.plugin_parseline(fname, pl_loader->index)) { if (!pl_temp.plugin_parseline(fname, pl_loader->index))
{
RETURN_ERRNO(NULL, ME_NOTFOUND); RETURN_ERRNO(NULL, ME_NOTFOUND);
} }
if (pl_temp.resolve() != mTRUE) { if (pl_temp.resolve() != mTRUE)
{
META_DEBUG(1, ("Couldn't resolve given path into a file: %s", pl_temp.file)); META_DEBUG(1, ("Couldn't resolve given path into a file: %s", pl_temp.file));
RETURN_ERRNO(NULL, ME_NOTFOUND); RETURN_ERRNO(NULL, ME_NOTFOUND);
} }
if ((pl_found = find(pl_temp.pathname))) { if ((pl_found = find(pl_temp.pathname)))
{
META_DEBUG(1, ("Plugin '%s' already in current list; file=%s desc='%s'", META_DEBUG(1, ("Plugin '%s' already in current list; file=%s desc='%s'",
pl_temp.file, pl_found->file, pl_found->desc)); pl_temp.file, pl_found->file, pl_found->desc));
RETURN_ERRNO(NULL, ME_ALREADY); RETURN_ERRNO(NULL, ME_ALREADY);
} }
if (!(pl_added = add(&pl_temp))) { if (!(pl_added = add(&pl_temp)))
{
META_DEBUG(1, ("Couldn't add plugin '%s' to list; see log", pl_temp.desc)); META_DEBUG(1, ("Couldn't add plugin '%s' to list; see log", pl_temp.desc));
return NULL; return NULL;
} }
pl_added->action = PA_LOAD; pl_added->action = PA_LOAD;
if (!pl_added->load(now)) { if (!pl_added->load(now))
if (meta_errno == ME_NOTALLOWED || meta_errno == ME_DELAYED) { {
META_DEBUG(1, ("Plugin '%s' couldn't attach; only allowed %s", if (meta_errno == ME_NOTALLOWED || meta_errno == ME_DELAYED)
pl_added->desc, pl_added->str_loadable(SL_ALLOWED))); {
META_DEBUG(1, ("Plugin '%s' couldn't attach; only allowed %s", pl_added->desc, pl_added->str_loadable(SL_ALLOWED)));
pl_added->clear(); pl_added->clear();
} }
else if (pl_added->status == PL_OPENED) { else if (pl_added->status == PL_OPENED)
{
META_DEBUG(1, ("Opened plugin '%s', but failed to attach; see log", pl_added->desc)); META_DEBUG(1, ("Opened plugin '%s', but failed to attach; see log", pl_added->desc));
} }
else { else
{
META_DEBUG(1, ("Couldn't load plugin '%s'; see log", pl_added->desc)); META_DEBUG(1, ("Couldn't load plugin '%s'; see log", pl_added->desc));
} }
return NULL; return NULL;
@ -305,34 +306,41 @@ MPlugin* MPluginList::add(MPlugin* padd)
for (i = 0; i < endlist && plist[i].status != PL_EMPTY; i++); for (i = 0; i < endlist && plist[i].status != PL_EMPTY; i++);
// couldn't find a slot to use // couldn't find a slot to use
if (i == size) { if (i == size)
META_ERROR("Couldn't add plugin '%s' to list; reached max plugins (%d)", {
padd->file, i); META_ERROR("Couldn't add plugin '%s' to list; reached max plugins (%d)", padd->file, i);
RETURN_ERRNO(NULL, ME_MAXREACHED); RETURN_ERRNO(NULL, ME_MAXREACHED);
} }
// if we found the end of the list, advance end marker // if we found the end of the list, advance end marker
if (i == endlist) if (i == endlist)
endlist++; endlist++;
iplug = &plist[i]; iplug = &plist[i];
// copy filename into this free slot // copy filename into this free slot
strncpy(iplug->filename, padd->filename, sizeof iplug->filename - 1); Q_strncpy(iplug->filename, padd->filename, sizeof iplug->filename - 1);
iplug->filename[sizeof iplug->filename - 1] = '\0'; iplug->filename[sizeof iplug->filename - 1] = '\0';
// Copy file offset ptr. // Copy file offset ptr.
// Can't just copy ptr, as it points to offset in padd, which will go // Can't just copy ptr, as it points to offset in padd, which will go
// away; need to point to corresponding offset in iplug. // away; need to point to corresponding offset in iplug.
iplug->file = iplug->filename + (padd->file - padd->filename); iplug->file = iplug->filename + (padd->file - padd->filename);
// copy description // copy description
strncpy(iplug->desc, padd->desc, sizeof iplug->desc - 1); Q_strncpy(iplug->desc, padd->desc, sizeof iplug->desc - 1);
iplug->desc[sizeof iplug->desc - 1] = '\0'; iplug->desc[sizeof iplug->desc - 1] = '\0';
// copy pathname // copy pathname
strncpy(iplug->pathname, padd->pathname, sizeof iplug->pathname - 1); Q_strncpy(iplug->pathname, padd->pathname, sizeof iplug->pathname - 1);
iplug->pathname[sizeof iplug->pathname - 1] = '\0'; iplug->pathname[sizeof iplug->pathname - 1] = '\0';
// copy source // copy source
iplug->source = padd->source; iplug->source = padd->source;
// copy status // copy status
iplug->status = padd->status; iplug->status = padd->status;
//copy other things //copy other things
iplug->source_plugin_index = padd->source_plugin_index; iplug->source_plugin_index = padd->source_plugin_index;
@ -350,55 +358,61 @@ mBOOL MPluginList::ini_startup()
int n, ln; int n, ln;
MPlugin *pmatch; MPlugin *pmatch;
if (!valid_gamedir_file(inifile)) { if (!valid_gamedir_file(inifile))
{
META_ERROR("ini: Metamod plugins file empty or missing: %s", inifile); META_ERROR("ini: Metamod plugins file empty or missing: %s", inifile);
RETURN_ERRNO(mFALSE, ME_NOFILE); RETURN_ERRNO(mFALSE, ME_NOFILE);
} }
full_gamedir_path(inifile, inifile);
full_gamedir_path(inifile, inifile);
fp = fopen(inifile, "r"); fp = fopen(inifile, "r");
if (!fp) { if (!fp)
META_ERROR("ini: Unable to open plugins file '%s': %s", inifile, {
strerror(errno)); META_ERROR("ini: Unable to open plugins file '%s': %s", inifile, strerror(errno));
RETURN_ERRNO(mFALSE, ME_NOFILE); RETURN_ERRNO(mFALSE, ME_NOFILE);
} }
META_LOG("ini: Begin reading plugins list: %s", inifile); META_LOG("ini: Begin reading plugins list: %s", inifile);
for (n = 0 , ln = 1; for (n = 0 , ln = 1; !feof(fp) && fgets(line, sizeof(line), fp) && n < size; ln++)
!feof(fp) && fgets(line, sizeof(line), fp) && n < size; {
ln++) {
// Remove line terminations. // Remove line terminations.
char* cp; char* cp;
if ((cp = strrchr(line, '\r'))) if ((cp = Q_strrchr(line, '\r')))
*cp = '\0'; *cp = '\0';
if ((cp = strrchr(line, '\n')))
if ((cp = Q_strrchr(line, '\n')))
*cp = '\0'; *cp = '\0';
// Parse directly into next entry in array // Parse directly into next entry in array
if (!plist[n].ini_parseline(line)) { if (!plist[n].ini_parseline(line))
{
if (meta_errno == ME_FORMAT) if (meta_errno == ME_FORMAT)
META_ERROR("ini: Skipping malformed line %d of %s", ln, {
inifile); META_ERROR("ini: Skipping malformed line %d of %s", ln, inifile);
}
continue; continue;
} }
// Check for a duplicate - an existing entry with this pathname. // Check for a duplicate - an existing entry with this pathname.
if (find(plist[n].pathname)) { if (find(plist[n].pathname))
{
// Should we check platform specific level here? // Should we check platform specific level here?
META_INFO("ini: Skipping duplicate plugin, line %d of %s: %s", META_INFO("ini: Skipping duplicate plugin, line %d of %s: %s", ln, inifile, plist[n].pathname);
ln, inifile, plist[n].pathname);
continue; continue;
} }
// Check for a matching platform with different platform specifics // Check for a matching platform with different platform specifics
// level. // level.
if (NULL != (pmatch = find_match(&plist[n]))) { if (NULL != (pmatch = find_match(&plist[n])))
if (pmatch->pfspecific >= plist[n].pfspecific) { {
META_DEBUG(1, ("ini: Skipping plugin, line %d of %s: plugin with higher platform specific level already exists. (%d >= %d)", if (pmatch->pfspecific >= plist[n].pfspecific)
ln, inifile, pmatch->pfspecific, plist[n].pfspecific)); {
META_DEBUG(1, ("ini: Skipping plugin, line %d of %s: plugin with higher platform specific level already exists. (%d >= %d)", ln, inifile, pmatch->pfspecific, plist[n].pfspecific));
continue; continue;
} }
META_DEBUG(1, ("ini: Plugin in line %d overrides existing plugin with lower platform specific level %d, ours %d",
ln, pmatch->pfspecific, plist[n].pfspecific)); META_DEBUG(1, ("ini: Plugin in line %d overrides existing plugin with lower platform specific level %d, ours %d", ln, pmatch->pfspecific, plist[n].pfspecific));
int _index = pmatch->index; int _index = pmatch->index;
memset(pmatch, 0, sizeof(MPlugin)); Q_memset(pmatch, 0, sizeof(MPlugin));
pmatch->index = _index; pmatch->index = _index;
} }
plist[n].action = PA_LOAD; plist[n].action = PA_LOAD;
@ -406,14 +420,15 @@ mBOOL MPluginList::ini_startup()
n++; n++;
endlist = n; // mark end of list endlist = n; // mark end of list
} }
META_LOG("ini: Finished reading plugins list: %s; Found %d plugins to load", META_LOG("ini: Finished reading plugins list: %s; Found %d plugins to load", inifile, n);
inifile, n);
fclose(fp); fclose(fp);
if (!n) { if (!n)
{
META_ERROR("ini: Warning; no plugins found to load?"); META_ERROR("ini: Warning; no plugins found to load?");
} }
return (mTRUE);
return mTRUE;
} }
// Re-read plugins.ini looking for added/deleted/changed plugins. // Re-read plugins.ini looking for added/deleted/changed plugins.
@ -428,56 +443,62 @@ mBOOL MPluginList::ini_refresh()
MPlugin *pl_found, *pl_added; MPlugin *pl_found, *pl_added;
fp = fopen(inifile, "r"); fp = fopen(inifile, "r");
if (!fp) { if (!fp)
META_ERROR("ini: Unable to open plugins file '%s': %s", inifile, {
strerror(errno)); META_ERROR("ini: Unable to open plugins file '%s': %s", inifile, strerror(errno));
RETURN_ERRNO(mFALSE, ME_NOFILE); RETURN_ERRNO(mFALSE, ME_NOFILE);
} }
META_LOG("ini: Begin re-reading plugins list: %s", inifile); META_LOG("ini: Begin re-reading plugins list: %s", inifile);
for (n = 0 , ln = 1; for (n = 0 , ln = 1; !feof(fp) && fgets(line, sizeof(line), fp) && n < size; ln++)
!feof(fp) && fgets(line, sizeof(line), fp) && n < size; {
ln++) {
// Remove line terminations. // Remove line terminations.
char *cp; char *cp;
if ((cp = strrchr(line, '\r'))) if ((cp = Q_strrchr(line, '\r')))
*cp = '\0'; *cp = '\0';
if ((cp = strrchr(line, '\n')))
if ((cp = Q_strrchr(line, '\n')))
*cp = '\0'; *cp = '\0';
// Parse into a temp plugin // Parse into a temp plugin
memset(&pl_temp, 0, sizeof(pl_temp)); Q_memset(&pl_temp, 0, sizeof(pl_temp));
if (!pl_temp.ini_parseline(line)) { if (!pl_temp.ini_parseline(line))
{
if (meta_errno == ME_FORMAT) if (meta_errno == ME_FORMAT)
META_ERROR("ini: Skipping malformed line %d of %s", {
ln, inifile); META_ERROR("ini: Skipping malformed line %d of %s",ln, inifile);
}
continue; continue;
} }
// Try to find plugin with this pathname in the current list of // Try to find plugin with this pathname in the current list of
// plugins. // plugins.
if (!(pl_found = find(pl_temp.pathname))) { if (!(pl_found = find(pl_temp.pathname)))
{
// Check for a matching platform with higher platform specifics // Check for a matching platform with higher platform specifics
// level. // level.
if (NULL != (pl_found = find_match(&pl_temp))) { if (NULL != (pl_found = find_match(&pl_temp)))
if (pl_found->pfspecific >= pl_temp.pfspecific) { {
META_DEBUG(1, ("ini: Skipping plugin, line %d of %s: plugin with higher platform specific level already exists. (%d >= %d)", if (pl_found->pfspecific >= pl_temp.pfspecific)
ln, inifile, pl_found->pfspecific, pl_temp.pfspecific)); {
META_DEBUG(1, ("ini: Skipping plugin, line %d of %s: plugin with higher platform specific level already exists. (%d >= %d)", ln, inifile, pl_found->pfspecific, pl_temp.pfspecific));
continue; continue;
} }
if (PA_LOAD == pl_found->action) { if (PA_LOAD == pl_found->action)
META_DEBUG(1, ("ini: Plugin in line %d overrides loading of plugin with lower platform specific level %d, ours %d", {
ln, pl_found->pfspecific, pl_temp.pfspecific)); META_DEBUG(1, ("ini: Plugin in line %d overrides loading of plugin with lower platform specific level %d, ours %d", ln, pl_found->pfspecific, pl_temp.pfspecific));
int _index = pl_found->index; int _index = pl_found->index;
memset(pl_found, 0, sizeof(MPlugin)); Q_memset(pl_found, 0, sizeof(MPlugin));
pl_found->index = _index; pl_found->index = _index;
} }
else { else
META_DEBUG(1, ("ini: Plugin in line %d should override existing plugin with lower platform specific level %d, ours %d. Unable to comply.", {
ln, pl_found->pfspecific, pl_temp.pfspecific)); META_DEBUG(1, ("ini: Plugin in line %d should override existing plugin with lower platform specific level %d, ours %d. Unable to comply.", ln, pl_found->pfspecific, pl_temp.pfspecific));
continue; continue;
} }
} }
// new plugin; add to list // new plugin; add to list
if ((pl_added = add(&pl_temp))) { if ((pl_added = add(&pl_temp)))
{
// try to load this plugin at the next opportunity // try to load this plugin at the next opportunity
pl_added->action = PA_LOAD; pl_added->action = PA_LOAD;
} }
@ -485,42 +506,49 @@ mBOOL MPluginList::ini_refresh()
// error details logged in add() // error details logged in add()
continue; continue;
} }
else { else
{
// This plugin is already in the current list of plugins. // This plugin is already in the current list of plugins.
// Pathname already matches. Recopy desc, if specified in // Pathname already matches. Recopy desc, if specified in
// plugins.ini. // plugins.ini.
if (pl_temp.desc[0] != '<') { if (pl_temp.desc[0] != '<')
strncpy(pl_found->desc, pl_temp.desc, sizeof pl_found->desc - 1); {
Q_strncpy(pl_found->desc, pl_temp.desc, sizeof pl_found->desc - 1);
pl_found->desc[sizeof pl_found->desc - 1] = '\0'; pl_found->desc[sizeof pl_found->desc - 1] = '\0';
} }
// Check the file to see if it looks like it's been modified // Check the file to see if it looks like it's been modified
// since we last loaded it. // since we last loaded it.
if (!pl_found->newer_file()) { if (!pl_found->newer_file())
if (meta_errno == ME_NOFILE) { {
META_ERROR("ini: Skipping plugin, couldn't stat file '%s': %s", if (meta_errno == ME_NOFILE)
pl_found->pathname, strerror(errno)); {
META_ERROR("ini: Skipping plugin, couldn't stat file '%s': %s", pl_found->pathname, strerror(errno));
continue; continue;
} }
else { else
{
// File hasn't been updated. // File hasn't been updated.
// Keep plugin (don't let refresh() unload it). // Keep plugin (don't let refresh() unload it).
pl_found->action = PA_KEEP; pl_found->action = PA_KEEP;
} }
} }
// Newer file on disk. // Newer file on disk.
else if (pl_found->status >= PL_OPENED) { else if (pl_found->status >= PL_OPENED)
{
META_DEBUG(2, ("ini: Plugin '%s' has newer file on disk", pl_found->desc)); META_DEBUG(2, ("ini: Plugin '%s' has newer file on disk", pl_found->desc));
pl_found->action = PA_RELOAD; pl_found->action = PA_RELOAD;
} }
else else
META_ERROR("ini: Plugin '%s' has newer file, but unexpected status (%s)", META_ERROR("ini: Plugin '%s' has newer file, but unexpected status (%s)", pl_found->desc, pl_found->str_status());
pl_found->desc, pl_found->str_status());
} }
if (NULL != pl_found) {
if (pl_found)
{
META_LOG("ini: Read plugin config for: %s", pl_found->desc); META_LOG("ini: Read plugin config for: %s", pl_found->desc);
} }
else { else
{
META_LOG("ini: Read plugin config for: %s", pl_temp.desc); META_LOG("ini: Read plugin config for: %s", pl_temp.desc);
} }
n++; n++;
@ -528,10 +556,12 @@ mBOOL MPluginList::ini_refresh()
META_LOG("ini: Finished reading plugins list: %s; Found %d plugins", inifile, n); META_LOG("ini: Finished reading plugins list: %s; Found %d plugins", inifile, n);
fclose(fp); fclose(fp);
if (!n) { if (!n)
{
META_ERROR("ini: Warning; no plugins found to load?"); META_ERROR("ini: Warning; no plugins found to load?");
} }
return (mTRUE);
return mTRUE;
} }
// Load a plugin from a console command. // Load a plugin from a console command.
@ -549,61 +579,66 @@ mBOOL MPluginList::cmd_addload(const char* args)
// XXX move back to comands_meta ? // XXX move back to comands_meta ?
// parse into a temp plugin // parse into a temp plugin
memset(&pl_temp, 0, sizeof(pl_temp)); Q_memset(&pl_temp, 0, sizeof(pl_temp));
if (pl_temp.cmd_parseline(args) != mTRUE) { if (pl_temp.cmd_parseline(args) != mTRUE)
{
META_CONS("Couldn't parse 'meta load' arguments: %s", args); META_CONS("Couldn't parse 'meta load' arguments: %s", args);
// meta_errno should be already set in cmd_parseline() // meta_errno should be already set in cmd_parseline()
return (mFALSE); return mFALSE;
} }
// resolve given path into a file; accepts various "shortcut" // resolve given path into a file; accepts various "shortcut"
// pathnames. // pathnames.
if (pl_temp.resolve() != mTRUE) { if (pl_temp.resolve() != mTRUE)
{
// Couldn't find a matching file on disk // Couldn't find a matching file on disk
META_CONS("Couldn't resolve given path into a file: %s", META_CONS("Couldn't resolve given path into a file: %s", pl_temp.file);
pl_temp.file);
// meta_errno should be already set in resolve() // meta_errno should be already set in resolve()
return (mFALSE); return mFALSE;
} }
// Try to find plugin with this pathname in the current list of // Try to find plugin with this pathname in the current list of
// plugins. // plugins.
if ((pl_found = find(pl_temp.pathname))) { if ((pl_found = find(pl_temp.pathname)))
{
// Already in list // Already in list
META_CONS("Plugin '%s' already in current list; file=%s desc='%s'", META_CONS("Plugin '%s' already in current list; file=%s desc='%s'", pl_temp.file, pl_found->file, pl_found->desc);
pl_temp.file, pl_found->file, pl_found->desc);
RETURN_ERRNO(mFALSE, ME_ALREADY); RETURN_ERRNO(mFALSE, ME_ALREADY);
} }
// new plugin; add to list // new plugin; add to list
if (!(pl_added = add(&pl_temp))) { if (!(pl_added = add(&pl_temp)))
{
META_CONS("Couldn't add plugin '%s' to list; see log", pl_temp.desc); META_CONS("Couldn't add plugin '%s' to list; see log", pl_temp.desc);
// meta_errno should be already set in add() // meta_errno should be already set in add()
return (mFALSE); return mFALSE;
} }
// try to load new plugin // try to load new plugin
pl_added->action = PA_LOAD; pl_added->action = PA_LOAD;
if (!pl_added->load(PT_ANYTIME)) { if (!pl_added->load(PT_ANYTIME))
{
// load failed // load failed
if (meta_errno == ME_DELAYED) if (meta_errno == ME_DELAYED)
META_CONS("Loaded plugin '%s', but will wait to become active, %s", META_CONS("Loaded plugin '%s', but will wait to become active, %s", pl_added->desc, pl_added->str_loadable(SL_ALLOWED));
pl_added->desc, pl_added->str_loadable(SL_ALLOWED)); else if (meta_errno == ME_NOTALLOWED)
else if (meta_errno == ME_NOTALLOWED) { {
META_CONS("Plugin '%s' couldn't attach; only allowed %s", META_CONS("Plugin '%s' couldn't attach; only allowed %s", pl_added->desc, pl_added->str_loadable(SL_ALLOWED));
pl_added->desc, pl_added->str_loadable(SL_ALLOWED));
pl_added->clear(); pl_added->clear();
} }
else if (pl_added->status == PL_OPENED) else if (pl_added->status == PL_OPENED)
META_CONS("Opened plugin '%s', but failed to attach; see log", pl_added->desc); META_CONS("Opened plugin '%s', but failed to attach; see log", pl_added->desc);
else else
META_CONS("Couldn't load plugin '%s'; see log", pl_added->desc); META_CONS("Couldn't load plugin '%s'; see log", pl_added->desc);
show(0); show(0);
// meta_errno should be already set in load() // meta_errno should be already set in load()
return (mFALSE); return mFALSE;
} }
META_CONS("Loaded plugin '%s' successfully", pl_added->desc); META_CONS("Loaded plugin '%s' successfully", pl_added->desc);
show(0); show(0);
return (mTRUE);
return mTRUE;
} }
// Load plugins at startup. // Load plugins at startup.
@ -611,26 +646,29 @@ mBOOL MPluginList::cmd_addload(const char* args)
// - errno's from ini_startup() // - errno's from ini_startup()
mBOOL MPluginList::load() mBOOL MPluginList::load()
{ {
int i, n; int n = 0;
if (!ini_startup())
if (!ini_startup()) { {
META_ERROR("Problem loading plugins.ini: %s", inifile); META_ERROR("Problem loading plugins.ini: %s", inifile);
// meta_errno should be already set in ini_startup() // meta_errno should be already set in ini_startup()
return (mFALSE); return mFALSE;
} }
META_LOG("dll: Loading plugins..."); META_LOG("dll: Loading plugins...");
for (i = 0 , n = 0; i < endlist; i++) { for (int i = 0; i < endlist; i++)
{
if (plist[i].status < PL_VALID) if (plist[i].status < PL_VALID)
continue; continue;
if (plist[i].load(PT_STARTUP) == mTRUE) if (plist[i].load(PT_STARTUP) == mTRUE)
n++; n++;
else else
// all plugins should be loadable at startup... // all plugins should be loadable at startup...
META_ERROR("dll: Failed to load plugin '%s'", plist[i].file); META_ERROR("dll: Failed to load plugin '%s'", plist[i].file);
} }
META_LOG("dll: Finished loading %d plugins", n); META_LOG("dll: Finished loading %d plugins", n);
return (mTRUE); return mTRUE;
} }
// Update list of loaded plugins from ini file, and load any new/changed plugins. // Update list of loaded plugins from ini file, and load any new/changed plugins.
@ -641,18 +679,22 @@ mBOOL MPluginList::refresh(PLUG_LOADTIME now)
int i, ndone = 0, nkept = 0, nloaded = 0, nunloaded = 0, nreloaded = 0, ndelayed = 0; int i, ndone = 0, nkept = 0, nloaded = 0, nunloaded = 0, nreloaded = 0, ndelayed = 0;
MPlugin* iplug; MPlugin* iplug;
if (!ini_refresh()) { if (!ini_refresh())
{
META_ERROR("dll: Problem reloading plugins.ini: %s", inifile); META_ERROR("dll: Problem reloading plugins.ini: %s", inifile);
// meta_errno should be already set in ini_refresh() // meta_errno should be already set in ini_refresh()
return (mFALSE); return mFALSE;
} }
META_LOG("dll: Updating plugins..."); META_LOG("dll: Updating plugins...");
for (i = 0; i < endlist; i++) { for (i = 0; i < endlist; i++)
{
iplug = &plist[i]; iplug = &plist[i];
if (iplug->status < PL_VALID) if (iplug->status < PL_VALID)
continue; continue;
switch (iplug->action) {
switch (iplug->action)
{
case PA_KEEP: case PA_KEEP:
META_DEBUG(1, ("Keeping plugin '%s'", iplug->desc)); META_DEBUG(1, ("Keeping plugin '%s'", iplug->desc));
iplug->action = PA_NONE; iplug->action = PA_NONE;
@ -674,7 +716,8 @@ mBOOL MPluginList::refresh(PLUG_LOADTIME now)
break; break;
case PA_NONE: case PA_NONE:
// If previously loaded from ini, but apparently removed from new ini. // If previously loaded from ini, but apparently removed from new ini.
if (iplug->source == PS_INI && iplug->status >= PL_RUNNING) { if (iplug->source == PS_INI && iplug->status >= PL_RUNNING)
{
META_DEBUG(1, ("Unloading plugin '%s'", iplug->desc)); META_DEBUG(1, ("Unloading plugin '%s'", iplug->desc));
iplug->action = PA_UNLOAD; iplug->action = PA_UNLOAD;
if (iplug->unload(now, PNL_INI_DELETED, PNL_INI_DELETED)) if (iplug->unload(now, PNL_INI_DELETED, PNL_INI_DELETED))
@ -708,9 +751,9 @@ mBOOL MPluginList::refresh(PLUG_LOADTIME now)
} }
ndone++; ndone++;
} }
META_LOG("dll: Finished updating %d plugins; kept %d, loaded %d, unloaded %d, reloaded %d, delayed %d",
ndone, nkept, nloaded, nunloaded, nreloaded, ndelayed); META_LOG("dll: Finished updating %d plugins; kept %d, loaded %d, unloaded %d, reloaded %d, delayed %d", ndone, nkept, nloaded, nunloaded, nreloaded, ndelayed);
return (mTRUE); return mTRUE;
} }
// Re-enable any plugins currently paused. // Re-enable any plugins currently paused.
@ -718,10 +761,9 @@ mBOOL MPluginList::refresh(PLUG_LOADTIME now)
// - none // - none
void MPluginList::unpause_all(void) void MPluginList::unpause_all(void)
{ {
int i; for (int i = 0; i < endlist; i++)
MPlugin* iplug; {
for (i = 0; i < endlist; i++) { auto iplug = &plist[i];
iplug = &plist[i];
if (iplug->status == PL_PAUSED) if (iplug->status == PL_PAUSED)
iplug->unpause(); iplug->unpause();
} }
@ -733,10 +775,9 @@ void MPluginList::unpause_all(void)
// - none // - none
void MPluginList::retry_all(PLUG_LOADTIME now) void MPluginList::retry_all(PLUG_LOADTIME now)
{ {
int i; for (int i = 0; i < endlist; i++)
MPlugin* iplug; {
for (i = 0; i < endlist; i++) { auto iplug = &plist[i];
iplug = &plist[i];
if (iplug->action != PA_NONE) if (iplug->action != PA_NONE)
iplug->retry(now, PNL_DELAYED); iplug->retry(now, PNL_DELAYED);
} }
@ -747,7 +788,7 @@ void MPluginList::retry_all(PLUG_LOADTIME now)
// - none // - none
void MPluginList::show(int source_index) void MPluginList::show(int source_index)
{ {
int i, n = 0, r = 0; int n = 0, r = 0;
MPlugin *pl; MPlugin *pl;
char desc[15 + 1], file[16 + 1], vers[7 + 1]; // plus 1 for term null char desc[15 + 1], file[16 + 1], vers[7 + 1]; // plus 1 for term null
@ -756,41 +797,44 @@ void MPluginList::show(int source_index)
else else
META_CONS("Child plugins:"); META_CONS("Child plugins:");
META_CONS(" %*s %-*s %-4s %-4s %-*s v%-*s %-3s %-5s %-5s", META_CONS(" %*s %-*s %-4s %-4s %-*s v%-*s %-*s %-5s %-5s", WIDTH_MAX_PLUGINS, "", sizeof(desc) - 1, "description", "stat", "pend",
WIDTH_MAX_PLUGINS, "", sizeof(file) - 1, "file", sizeof(vers) - 1, "ers", 2 + WIDTH_MAX_PLUGINS, "src", "load ", "unlod");
sizeof(desc) - 1, "description",
"stat", "pend", for (int i = 0; i < endlist; i++)
sizeof(file) - 1, "file", sizeof(vers) - 1, "ers", {
"src", "load ", "unlod");
for (i = 0; i < endlist; i++) {
pl = &plist[i]; pl = &plist[i];
if (pl->status < PL_VALID) if (pl->status < PL_VALID)
continue; continue;
if ((source_index > 0) && (pl->source_plugin_index != source_index))
if (source_index > 0 && pl->source_plugin_index != source_index)
continue; continue;
strncpy(desc, pl->desc, sizeof desc - 1);
desc[sizeof desc - 1] = '\0'; Q_strncpy(desc, pl->desc, sizeof(desc) - 1);
strncpy(file, pl->file, sizeof file - 1); desc[sizeof(desc) - 1] = '\0';
file[sizeof file - 1] = '\0';
if (pl->info && pl->info->version) { Q_strncpy(file, pl->file, sizeof(file) - 1);
strncpy(vers, pl->info->version, sizeof vers - 1); file[sizeof(file) - 1] = '\0';
vers[sizeof vers - 1] = '\0';
if (pl->info && pl->info->version)
{
Q_strncpy(vers, pl->info->version, sizeof(vers) - 1);
vers[sizeof(vers) - 1] = '\0';
} }
else { else
strncpy(vers, " -", sizeof vers - 1); {
vers[sizeof vers - 1] = '\0'; Q_strncpy(vers, " -", sizeof(vers) - 1);
vers[sizeof(vers) - 1] = '\0';
} }
META_CONS(" [%*d] %-*s %-4s %-4s %-*s v%-*s %-3s %-5s %-5s",
WIDTH_MAX_PLUGINS, pl->index, META_CONS(" [%*d] %-*s %-4s %-4s %-*s v%-*s %-*s %-5s %-5s", WIDTH_MAX_PLUGINS, pl->index,
sizeof(desc) - 1, desc, sizeof(desc) - 1, desc, pl->str_status(ST_SHOW), pl->str_action(SA_SHOW), sizeof(file) - 1, file, sizeof(vers) - 1, vers,
pl->str_status(ST_SHOW), pl->str_action(SA_SHOW), 2 + WIDTH_MAX_PLUGINS, pl->str_source(SO_SHOW), pl->str_loadable(SL_SHOW), pl->str_unloadable(SL_SHOW));
sizeof(file) - 1, file, sizeof(vers) - 1, vers,
pl->str_source(SO_SHOW),
pl->str_loadable(SL_SHOW), pl->str_unloadable(SL_SHOW));
if (pl->status == PL_RUNNING) if (pl->status == PL_RUNNING)
r++; r++;
n++; n++;
} }
META_CONS("%d plugins, %d running", n, r); META_CONS("%d plugins, %d running", n, r);
} }
@ -803,35 +847,38 @@ void MPluginList::show(int source_index)
// - none // - none
void MPluginList::show_client(edict_t *pEntity) void MPluginList::show_client(edict_t *pEntity)
{ {
int i, n = 0; int n = 0;
MPlugin *pl; MPlugin *pl;
META_CLIENT(pEntity, "Currently running plugins:"); META_CLIENT(pEntity, "Currently running plugins:");
for (i = 0; i < endlist; i++) {
for (int i = 0; i < endlist; i++)
{
pl = &plist[i]; pl = &plist[i];
if (pl->status != PL_RUNNING) if (pl->status != PL_RUNNING || !pl->info)
continue; continue;
n++; n++;
META_CLIENT(pEntity, " [%3d] %s, v%s, %s, by %s, see %s", META_CLIENT(pEntity, " [%3d] %s, v%s, %s, by %s, see %s", n,
n,
pl->info->name ? pl->info->name : "<unknown>", pl->info->name ? pl->info->name : "<unknown>",
pl->info->version ? pl->info->version : "<?>", pl->info->version ? pl->info->version : "<?>",
pl->info->date ? pl->info->date : "<../../..>", pl->info->date ? pl->info->date : "<../../..>",
pl->info->author ? pl->info->author : "<unknown>", pl->info->author ? pl->info->author : "<unknown>",
pl->info->url ? pl->info->url : "<unknown>"); pl->info->url ? pl->info->url : "<unknown>");
} }
META_CLIENT(pEntity, "%d plugins", n); META_CLIENT(pEntity, "%d plugins", n);
} }
mBOOL MPluginList::found_child_plugins(int source_index) mBOOL MPluginList::found_child_plugins(int source_index)
{ {
int i;
if (source_index <= 0) if (source_index <= 0)
return mFALSE; return mFALSE;
for (i = 0; i < endlist; i++) { for (int i = 0; i < endlist; i++)
{
if (plist[i].status < PL_VALID) if (plist[i].status < PL_VALID)
continue; continue;
if (plist[i].source_plugin_index == source_index) if (plist[i].source_plugin_index == source_index)
return mTRUE; return mTRUE;
} }
@ -841,14 +888,14 @@ mBOOL MPluginList::found_child_plugins(int source_index)
void MPluginList::clear_source_plugin_index(int source_index) void MPluginList::clear_source_plugin_index(int source_index)
{ {
int i;
if (source_index <= 0) if (source_index <= 0)
return; return;
for (i = 0; i < endlist; i++) { for (int i = 0; i < endlist; i++)
{
if (plist[i].status < PL_VALID) if (plist[i].status < PL_VALID)
continue; continue;
if (plist[i].source_plugin_index == source_index) if (plist[i].source_plugin_index == source_index)
plist[i].source_plugin_index = -1; plist[i].source_plugin_index = -1;
} }

View File

@ -1,41 +1,4 @@
// vi: set ts=4 sw=4 : #pragma once
// vim: set tw=75 :
// mlist.h - class and constants to describe a list of plugins
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef MLIST_H
#define MLIST_H
#include "types_meta.h" // mBOOL #include "types_meta.h" // mBOOL
#include "mplugin.h" // class MPlugin #include "mplugin.h" // class MPlugin
@ -45,23 +8,15 @@
// for convenience. It would probably be better to dynamically grow the // for convenience. It would probably be better to dynamically grow the
// list as needed, but we do this for now. // list as needed, but we do this for now.
#define MAX_PLUGINS 50 #define MAX_PLUGINS 50
// Width required to printf above MAX, for show() functions. // Width required to printf above MAX, for show() functions.
#define WIDTH_MAX_PLUGINS 2 #define WIDTH_MAX_PLUGINS 2
// A list of plugins. // A list of plugins.
class MPluginList { class MPluginList {
public: public:
// data:
char inifile[PATH_MAX]; // full pathname
MPlugin plist[MAX_PLUGINS]; // array of plugins
int size; // size of list, ie MAX_PLUGINS
int endlist; // index of last used entry
// constructor:
MPluginList(const char *ifile); MPluginList(const char *ifile);
// functions:
MPlugin *find(int pindex); // find by index MPlugin *find(int pindex); // find by index
MPlugin *find(const char *findpath); // find by pathname MPlugin *find(const char *findpath); // find by pathname
MPlugin *find(plid_t id); // find by plid_t MPlugin *find(plid_t id); // find by plid_t
@ -82,9 +37,13 @@ class MPluginList {
mBOOL refresh(PLUG_LOADTIME now); // update from re-read inifile mBOOL refresh(PLUG_LOADTIME now); // update from re-read inifile
void unpause_all(void); // unpause any paused plugins void unpause_all(void); // unpause any paused plugins
void retry_all(PLUG_LOADTIME now); // retry any pending plugin actions void retry_all(PLUG_LOADTIME now); // retry any pending plugin actions
void show(int source_index); // list plugins to console void show(int source_index = 0); // list plugins to console
void show_client(edict_t *pEntity); // list plugins to player client void show_client(edict_t *pEntity); // list plugins to player client
void clear_source_plugin_index(int source_index); void clear_source_plugin_index(int source_index);
};
#endif /* MLIST_H */ public:
char inifile[PATH_MAX]; // full pathname
MPlugin plist[MAX_PLUGINS]; // array of plugins
int size; // size of list, ie MAX_PLUGINS
int endlist; // index of last used entry
};

View File

@ -1,43 +1,5 @@
// vi: set ts=4 sw=4 :
// vim: set tw=75 :
// mplayer.cpp - methods of individual player (class MPlayer) and
// list of players (class MPlayerList).
/*
* Copyright (c) 2005 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#include "precompiled.h" #include "precompiled.h"
// Constructor
MPlayer::MPlayer() : isQueried(mFALSE) MPlayer::MPlayer() : isQueried(mFALSE)
{ {
} }
@ -50,34 +12,35 @@ void MPlayer::set_cvar_query(const char* cvar)
// Do not allow NULL as queried cvar since we use this as // Do not allow NULL as queried cvar since we use this as
// return value in is_querying_cvar as indication if a // return value in is_querying_cvar as indication if a
// client cvar is queried. // client cvar is queried.
if (!cvar) { if (!cvar)
{
meta_errno = ME_ARGUMENT; meta_errno = ME_ARGUMENT;
return; return;
} }
isQueried = mTRUE; isQueried = mTRUE;
strncpy(cvarName, cvar, sizeof cvarName - 1); Q_strncpy(cvarName, cvar, sizeof cvarName - 1);
cvarName[sizeof cvarName - 1] = '\0'; cvarName[sizeof cvarName - 1] = '\0';
} }
// Unmark player as querying a client cvar // Unmark player as querying a client cvar
void MPlayer::clear_cvar_query(const char* /*cvar*/) void MPlayer::clear_cvar_query(const char *cvar)
{ {
isQueried = mFALSE; isQueried = mFALSE;
cvarName[0] = '\0'; cvarName[0] = '\0';
} }
// Check if a client cvar is queried for this player // Check if a client cvar is queried for this player
// Returns NULL if not // Returns NULL if not
// or the name of the cvar. // or the name of the cvar.
const char *MPlayer::is_querying_cvar(void) const const char *MPlayer::is_querying_cvar(void) const
{ {
if (isQueried) { if (isQueried)
{
return cvarName; return cvarName;
} }
return NULL; return nullptr;
} }
// Mark a player as querying a client cvar and stores the cvar name // Mark a player as querying a client cvar and stores the cvar name
@ -86,8 +49,7 @@ const char* MPlayer::is_querying_cvar(void) const
void MPlayerList::set_player_cvar_query(const edict_t *pEntity, const char *cvar) void MPlayerList::set_player_cvar_query(const edict_t *pEntity, const char *cvar)
{ {
int indx = ENTINDEX(pEntity); int indx = ENTINDEX(pEntity);
if (indx >= 1 && indx <= gpGlobals->maxClients)
if (indx >= 1 && indx <= maxplayers)
players[indx].set_cvar_query(cvar); players[indx].set_cvar_query(cvar);
} }
@ -95,14 +57,14 @@ void MPlayerList::set_player_cvar_query(const edict_t* pEntity, const char* cvar
void MPlayerList::clear_player_cvar_query(const edict_t *pEntity, const char *cvar) void MPlayerList::clear_player_cvar_query(const edict_t *pEntity, const char *cvar)
{ {
int indx = ENTINDEX(pEntity); int indx = ENTINDEX(pEntity);
if (indx >= 1 && indx <= gpGlobals->maxClients)
if (indx >= 1 && indx <= maxplayers)
players[indx].clear_cvar_query(cvar); players[indx].clear_cvar_query(cvar);
} }
void MPlayerList::clear_all_cvar_queries(void) void MPlayerList::clear_all_cvar_queries(void)
{ {
for (int indx = 1; indx <= maxplayers; indx++) { for (int indx = 1; indx <= gpGlobals->maxClients; indx++)
{
players[indx].clear_cvar_query(); players[indx].clear_cvar_query();
} }
} }
@ -115,8 +77,7 @@ void MPlayerList::clear_all_cvar_queries(void)
const char *MPlayerList::is_querying_cvar(const edict_t *pEntity) const const char *MPlayerList::is_querying_cvar(const edict_t *pEntity) const
{ {
int indx = ENTINDEX(pEntity); int indx = ENTINDEX(pEntity);
if (indx >= 1 && indx <= gpGlobals->maxClients)
if (indx >= 1 && indx <= maxplayers)
return players[indx].is_querying_cvar(); return players[indx].is_querying_cvar();
RETURN_ERRNO(NULL, ME_NOTFOUND); RETURN_ERRNO(NULL, ME_NOTFOUND);

View File

@ -1,47 +1,6 @@
// vi: set ts=4 sw=4 : #pragma once
// vim: set tw=75 :
// mplayer.h - class to keep info about a player and a class listing all #include "types_meta.h"
// players
/*
* Copyright (c) 2005 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef INCLUDE_METAMOD_PLAYER_H
#define INCLUDE_METAMOD_PLAYER_H
#include "types_meta.h" // mBOOL
// Numbers of players limit set by the engine
#define MAX_PLAYERS 32
// Info on an individual player // Info on an individual player
class MPlayer class MPlayer
@ -50,8 +9,8 @@ public:
MPlayer(); MPlayer();
void set_cvar_query(const char *cvar); // mark this player as querying a client cvar void set_cvar_query(const char *cvar); // mark this player as querying a client cvar
void clear_cvar_query(const char *cvar=NULL); // unmark this player as querying a client cvar void clear_cvar_query(const char *cvar = nullptr); // unmark this player as querying a client cvar
const char *is_querying_cvar(void) const; // check if a player is querying a cvar. returns const char *is_querying_cvar() const; // check if a player is querying a cvar. returns
private: private:
mBOOL isQueried; // is this player currently queried for a cvar value mBOOL isQueried; // is this player currently queried for a cvar value
@ -64,13 +23,11 @@ class MPlayerList
{ {
public: public:
void set_player_cvar_query(const edict_t *pEntity, const char *cvar); void set_player_cvar_query(const edict_t *pEntity, const char *cvar);
void clear_player_cvar_query(const edict_t *pEntity, const char *cvar=NULL); void clear_player_cvar_query(const edict_t *pEntity, const char *cvar = nullptr);
void clear_all_cvar_queries(void); void clear_all_cvar_queries();
const char *is_querying_cvar(const edict_t *pEntity) const; const char *is_querying_cvar(const edict_t *pEntity) const;
private: private:
int maxplayers = 32; int maxplayers = 32;
MPlayer players[MAX_PLAYERS + 1]; // array of players MPlayer players[MAX_CLIENTS + 1]; // array of players
}; };
#endif /* INCLUDE_METAMOD_PLAYER_H */

File diff suppressed because it is too large Load Diff

View File

@ -1,67 +1,24 @@
// vi: set ts=4 sw=4 : #pragma once
// vim: set tw=75 :
// mplugin.h - class and types to describe an individual plugin
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef MPLUGIN_H
#define MPLUGIN_H
#include <time.h> // time_t, etc
#include <eiface.h> // DLL_FUNCTIONS, etc
#include "types_meta.h" // mBOOL
#include "meta_api.h" // GETENTITYAPI_FN, etc
#include "api_info.h" // dllapi_info, etc
#include "support_meta.h" // MAX_DESC_LEN
#include "api_info.h"
#include "support_meta.h"
// Flags to indicate current "load" state of plugin. // Flags to indicate current "load" state of plugin.
// NOTE: order is important, as greater/less comparisons are made. // NOTE: order is important, as greater/less comparisons are made.
typedef enum { enum PLUG_STATUS
{
PL_EMPTY = 0, // empty slot PL_EMPTY = 0, // empty slot
PL_VALID, // has valid info in it PL_VALID, // has valid info in it
PL_BADFILE, // nonexistent file (open failed), PL_BADFILE, // nonexistent file (open failed), or not a valid plugin file (query failed)
// or not a valid plugin file (query failed)
PL_OPENED, // dlopened and queried PL_OPENED, // dlopened and queried
PL_FAILED, // opened, but failed to attach or unattach PL_FAILED, // opened, but failed to attach or unattach
PL_RUNNING, // attached and running PL_RUNNING, // attached and running
PL_PAUSED, // attached but paused PL_PAUSED, // attached but paused
} PLUG_STATUS; };
// Action to take for plugin at next opportunity. // Action to take for plugin at next opportunity.
typedef enum { enum PLUG_ACTION
{
PA_NULL = 0, PA_NULL = 0,
PA_NONE, // no action needed right now PA_NONE, // no action needed right now
PA_KEEP, // keep, after ini refresh PA_KEEP, // keep, after ini refresh
@ -69,51 +26,56 @@ typedef enum {
PA_ATTACH, // attach PA_ATTACH, // attach
PA_UNLOAD, // unload (detach, dlclose) PA_UNLOAD, // unload (detach, dlclose)
PA_RELOAD, // unload and load again PA_RELOAD, // unload and load again
} PLUG_ACTION; };
// Flags to indicate from where the plugin was loaded. // Flags to indicate from where the plugin was loaded.
typedef enum { enum PLOAD_SOURCE
{
PS_INI = 0, // was loaded from the plugins.ini PS_INI = 0, // was loaded from the plugins.ini
PS_CMD, // was loaded via a server command PS_CMD, // was loaded via a server command
PS_PLUGIN, // was loaded via a plugin PS_PLUGIN, // was loaded by other plugin
} PLOAD_SOURCE; };
// Flags for how to word description of plugin loadtime. // Flags for how to word description of plugin loadtime.
typedef enum { enum STR_LOADTIME
{
SL_SIMPLE = 0, // single word SL_SIMPLE = 0, // single word
SL_SHOW, // for "show" output, 5 chars SL_SHOW, // for "show" output, 5 chars
SL_ALLOWED, // when plugin is allowed to load/unload SL_ALLOWED, // when plugin is allowed to load/unload
SL_NOW, // current situation SL_NOW, // current situation
} STR_LOADTIME; };
// Flags for how to format description of status. // Flags for how to format description of status.
typedef enum { enum STR_STATUS
{
ST_SIMPLE = 0, // single word ST_SIMPLE = 0, // single word
ST_SHOW, // for "show" output, 4 chars ST_SHOW, // for "show" output, 4 chars
} STR_STATUS; };
// Flags for how to format description of action. // Flags for how to format description of action.
typedef enum { enum STR_ACTION
{
SA_SIMPLE = 0, // single word SA_SIMPLE = 0, // single word
SA_SHOW, // for "show" output, 4 chars SA_SHOW, // for "show" output, 4 chars
} STR_ACTION; };
// Flags for how to format description of source. // Flags for how to format description of source.
typedef enum { enum STR_SOURCE
{
SO_SIMPLE = 0, // two words SO_SIMPLE = 0, // two words
SO_SHOW, // for "list" output, 3 chars SO_SHOW, // for "list" output, 3 chars
} STR_SOURCE; };
// An individual plugin. // An individual plugin.
class MPlugin { class MPlugin {
private: private:
mBOOL query(void); mBOOL query();
mBOOL attach(PLUG_LOADTIME now); mBOOL attach(PLUG_LOADTIME now);
mBOOL detach(PLUG_LOADTIME now, PL_UNLOAD_REASON reason); mBOOL detach(PLUG_LOADTIME now, PL_UNLOAD_REASON reason);
gamedll_funcs_t gamedll_funcs; gamedll_funcs_t gamedll_funcs;
mutil_funcs_t mutil_funcs; mutil_funcs_t mutil_funcs;
public: public:
// data:
int index; // 1-based int index; // 1-based
char filename[PATH_MAX]; // ie "dlls/mm_test_i386.so", from inifile char filename[PATH_MAX]; // ie "dlls/mm_test_i386.so", from inifile
char *file; // ie "mm_test_i386.so", ptr from filename char *file; // ie "mm_test_i386.so", ptr from filename
@ -138,14 +100,12 @@ class MPlugin {
enginefuncs_t *engine_table; enginefuncs_t *engine_table;
enginefuncs_t *engine_post_table; enginefuncs_t *engine_post_table;
// functions:
mBOOL ini_parseline(char *line); // parse line from inifile mBOOL ini_parseline(char *line); // parse line from inifile
mBOOL cmd_parseline(const char *line); // parse from console command mBOOL cmd_parseline(const char *line); // parse from console command
mBOOL plugin_parseline(const char *fname, int loader_index); // parse from plugin mBOOL plugin_parseline(const char *fname, int loader_index); // parse from plugin
mBOOL check_input(void); mBOOL check_input();
mBOOL resolve(void); // find a matching file on disk mBOOL resolve(); // find a matching file on disk
char *resolve_dirs(char *path); char *resolve_dirs(char *path);
char *resolve_prefix(char *path); char *resolve_prefix(char *path);
char *resolve_suffix(char *path); char *resolve_suffix(char *path);
@ -155,16 +115,15 @@ class MPlugin {
mBOOL load(PLUG_LOADTIME now); mBOOL load(PLUG_LOADTIME now);
mBOOL unload(PLUG_LOADTIME now, PL_UNLOAD_REASON reason, PL_UNLOAD_REASON real_reason); mBOOL unload(PLUG_LOADTIME now, PL_UNLOAD_REASON reason, PL_UNLOAD_REASON real_reason);
mBOOL reload(PLUG_LOADTIME now, PL_UNLOAD_REASON reason); mBOOL reload(PLUG_LOADTIME now, PL_UNLOAD_REASON reason);
mBOOL pause(void); mBOOL pause();
mBOOL unpause(void); mBOOL unpause();
mBOOL retry(PLUG_LOADTIME now, PL_UNLOAD_REASON reason); // if previously failed mBOOL retry(PLUG_LOADTIME now, PL_UNLOAD_REASON reason); // if previously failed
mBOOL clear(void); mBOOL clear();
mBOOL plugin_unload(plid_t plid, PLUG_LOADTIME now, PL_UNLOAD_REASON reason); // other plugin unloading mBOOL plugin_unload(plid_t plid, PLUG_LOADTIME now, PL_UNLOAD_REASON reason); // other plugin unloading
void show(void); // print info about plugin to console void show(); // print info about plugin to console
mBOOL newer_file(void); // check for newer file on disk mBOOL newer_file(); // check for newer file on disk
// output string functions
const char *str_status(STR_STATUS fmt); const char *str_status(STR_STATUS fmt);
const char *str_action(STR_ACTION fmt); const char *str_action(STR_ACTION fmt);
const char *str_source(STR_SOURCE fmt); const char *str_source(STR_SOURCE fmt);
@ -172,25 +131,25 @@ class MPlugin {
const char *str_reason(PL_UNLOAD_REASON preason, PL_UNLOAD_REASON preal_reason); const char *str_reason(PL_UNLOAD_REASON preason, PL_UNLOAD_REASON preal_reason);
const char *str_loadtime(PLUG_LOADTIME pallow, STR_LOADTIME fmt); const char *str_loadtime(PLUG_LOADTIME pallow, STR_LOADTIME fmt);
const char *str_status(void) { return(str_status(ST_SIMPLE)); }; const char *str_status() { return str_status(ST_SIMPLE); };
const char *str_action(void) { return(str_action(SA_SIMPLE)); }; const char *str_action() { return str_action(SA_SIMPLE); };
const char *str_source(void) { return(str_source(SO_SIMPLE)); }; const char *str_source() { return str_source(SO_SIMPLE); };
const char *str_loadable(void) { const char *str_loadable() {
if(info) return(str_loadtime(info->loadable, SL_SIMPLE)); if (info) return str_loadtime(info->loadable, SL_SIMPLE);
else return(" -"); else return " -";
}; };
const char *str_unloadable(void) { const char *str_unloadable() {
if(info) return(str_loadtime(info->unloadable, SL_SIMPLE)); if (info) return str_loadtime(info->unloadable, SL_SIMPLE);
else return(" -"); else return " -";
}; };
const char *str_loadable(STR_LOADTIME fmt) { const char *str_loadable(STR_LOADTIME fmt) {
if(info) return(str_loadtime(info->loadable, fmt)); if (info) return str_loadtime(info->loadable, fmt);
else return(" -"); else return " -";
}; };
const char *str_unloadable(STR_LOADTIME fmt) { const char *str_unloadable(STR_LOADTIME fmt) {
if(info) return(str_loadtime(info->unloadable, fmt)); if (info) return str_loadtime(info->unloadable, fmt);
else return(" -"); else return " -";
}; };
}; };
@ -418,6 +377,3 @@ class MPlugin {
SHOW_IFDEF(api_table, engine_info, pfnResetTutorMessageDecayData, pre_str, post_str); \ SHOW_IFDEF(api_table, engine_info, pfnResetTutorMessageDecayData, pre_str, post_str); \
SHOW_IFDEF(api_table, engine_info, pfnQueryClientCvarValue, pre_str, post_str); \ SHOW_IFDEF(api_table, engine_info, pfnQueryClientCvarValue, pre_str, post_str); \
SHOW_IFDEF(api_table, engine_info, pfnEngCheckParm, pre_str, post_str); SHOW_IFDEF(api_table, engine_info, pfnEngCheckParm, pre_str, post_str);
#endif /* MPLUGIN_H */

View File

@ -1,50 +1,5 @@
// vi: set ts=4 sw=4 :
// vim: set tw=75 :
// mreg.cpp - functions for registered items (classes MRegCmd, MRegCmdList)
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#include "precompiled.h" #include "precompiled.h"
#ifdef linux
// enable extra routines in system header files, like strsignal
# ifndef _GNU_SOURCE
# define _GNU_SOURCE
# endif
#endif /* linux */
///// class MRegCmd:
// Init values. It would probably be more "proper" to use containers and // Init values. It would probably be more "proper" to use containers and
// constructors, rather than arrays and init-functions. // constructors, rather than arrays and init-functions.
void MRegCmd::init(int idx) void MRegCmd::init(int idx)
@ -62,41 +17,42 @@ void MRegCmd::init(int idx)
// meta_errno values: // meta_errno values:
// - ME_BADREQ function disabled/invalid // - ME_BADREQ function disabled/invalid
// - ME_ARGUMENT function pointer is null // - ME_ARGUMENT function pointer is null
mBOOL MRegCmd::call(void) mBOOL MRegCmd::call()
{ {
mBOOL ret; mBOOL ret;
// can we expect to call this function? // can we expect to call this function?
if (status != RG_VALID) if (status != RG_VALID)
RETURN_ERRNO(mFALSE, ME_BADREQ); RETURN_ERRNO(mFALSE, ME_BADREQ);
if (!pfnCmd) if (!pfnCmd)
RETURN_ERRNO(mFALSE, ME_ARGUMENT); RETURN_ERRNO(mFALSE, ME_ARGUMENT);
// try to call this function // try to call this function
ret = os_safe_call(pfnCmd); ret = os_safe_call(pfnCmd);
if (!ret) { if (!ret)
{
META_DEBUG(4, ("Plugin reg_cmd '%s' called after unloaded; removed from list", name)); META_DEBUG(4, ("Plugin reg_cmd '%s' called after unloaded; removed from list", name));
status = RG_INVALID; status = RG_INVALID;
pfnCmd = NULL; pfnCmd = NULL;
// NOTE: we can't free the malloc'd space for the name, as that // NOTE: we can't free the malloc'd space for the name, as that
// would just re-introduce the segfault problem.. // would just re-introduce the segfault problem..
} }
// meta_errno (if failed) is set already in os_safe_call() // meta_errno (if failed) is set already in os_safe_call()
return (ret); return ret;
} }
MRegCmdList::MRegCmdList()
///// class MRegCmdList:
// Constructor
MRegCmdList::MRegCmdList(void)
: mlist(0), size(REG_CMD_GROWSIZE), endlist(0) : mlist(0), size(REG_CMD_GROWSIZE), endlist(0)
{ {
int i; int i;
mlist = (MRegCmd *) malloc(size * sizeof(MRegCmd)); mlist = (MRegCmd *)Q_malloc(size * sizeof(MRegCmd));
// initialize array // initialize array
for (i = 0; i < size; i++) for (i = 0; i < size; i++)
mlist[i].init(i + 1); // 1-based index mlist[i].init(i + 1); // 1-based index
endlist = 0; endlist = 0;
} }
@ -105,11 +61,12 @@ MRegCmdList::MRegCmdList(void)
// - ME_NOTFOUND couldn't find a matching function // - ME_NOTFOUND couldn't find a matching function
MRegCmd *MRegCmdList::find(const char *findname) MRegCmd *MRegCmdList::find(const char *findname)
{ {
int i; for (int i = 0; i < endlist; i++)
for (i = 0; i < endlist; i++) { {
if (!_stricmp(mlist[i].name, findname)) if (!Q_stricmp(mlist[i].name, findname))
return (&mlist[i]); return &mlist[i];
} }
RETURN_ERRNO(NULL, ME_NOTFOUND); RETURN_ERRNO(NULL, ME_NOTFOUND);
} }
@ -120,119 +77,126 @@ MRegCmd* MRegCmdList::find(const char* findname)
// - ME_NOMEM couldn't realloc or malloc for various parts // - ME_NOMEM couldn't realloc or malloc for various parts
MRegCmd *MRegCmdList::add(const char *addname) MRegCmd *MRegCmdList::add(const char *addname)
{ {
MRegCmd* icmd; if (endlist == size)
{
if (endlist == size) {
// grow array // grow array
MRegCmd* temp; int newsize = size + REG_CMD_GROWSIZE;
int i, newsize;
newsize = size + REG_CMD_GROWSIZE;
META_DEBUG(6, ("Growing reg cmd list from %d to %d", size, newsize)); META_DEBUG(6, ("Growing reg cmd list from %d to %d", size, newsize));
temp = (MRegCmd *) realloc(mlist, newsize * sizeof(MRegCmd));
if (!temp) { MRegCmd *temp = (MRegCmd *) realloc(mlist, newsize * sizeof(MRegCmd));
if (!temp)
{
META_ERROR("Couldn't grow registered command list to %d for '%s': %s", newsize, addname, strerror(errno)); META_ERROR("Couldn't grow registered command list to %d for '%s': %s", newsize, addname, strerror(errno));
RETURN_ERRNO(NULL, ME_NOMEM); RETURN_ERRNO(NULL, ME_NOMEM);
} }
mlist = temp; mlist = temp;
size = newsize; size = newsize;
// initialize new (unused) entries // initialize new (unused) entries
for (i = endlist; i < size; i++) for (int i = endlist; i < size; i++)
mlist[i].init(i + 1); // 1-based mlist[i].init(i + 1); // 1-based
} }
icmd = &mlist[endlist];
MRegCmd *icmd = &mlist[endlist];
// Malloc space separately for the command name, because: // Malloc space separately for the command name, because:
// - Can't point to memory loc in plugin (another segv waiting to // - Can't point to memory loc in plugin (another segv waiting to
// happen). // happen).
// - Can't point to memory in mlist which might get moved later by // - Can't point to memory in mlist which might get moved later by
// realloc (again, segv). // realloc (again, segv).
icmd->name = _strdup(addname); icmd->name = Q_strdup(addname);
if (!icmd->name) { if (!icmd->name)
META_ERROR("Couldn't _strdup for adding reg cmd name '%s': %s", {
addname, strerror(errno)); META_ERROR("Couldn't Q_strdup for adding reg cmd name '%s': %s", addname, strerror(errno));
RETURN_ERRNO(NULL, ME_NOMEM); RETURN_ERRNO(NULL, ME_NOMEM);
} }
endlist++;
return (icmd); endlist++;
return icmd;
} }
// Disable any functions belonging to the given plugin (by index id). // Disable any functions belonging to the given plugin (by index id).
void MRegCmdList::disable(int plugin_id) void MRegCmdList::disable(int plugin_id)
{ {
int i; for (int i = 0; i < size; i++)
for (i = 0; i < size; i++) { {
if (mlist[i].plugid == plugin_id) if (mlist[i].plugid == plugin_id)
mlist[i].status = RG_INVALID; mlist[i].status = RG_INVALID;
} }
} }
// List all the registered commands. // List all the registered commands.
void MRegCmdList::show(void) void MRegCmdList::show()
{ {
int i, n = 0, a = 0; int n = 0, a = 0;
MRegCmd *icmd; MRegCmd *icmd;
MPlugin *iplug; MPlugin *iplug;
char bplug[18 + 1]; // +1 for term null char bplug[18 + 1]; // +1 for term null
META_CONS("Registered plugin commands:"); META_CONS("Registered plugin commands:");
META_CONS(" %*s %-*s %-s", META_CONS(" %*s %-*s %-s", WIDTH_MAX_REG, "", sizeof(bplug) - 1, "plugin", "command");
WIDTH_MAX_REG, "", for (int i = 0; i < endlist; i++)
sizeof(bplug) - 1, "plugin", "command"); {
for (i = 0; i < endlist; i++) {
icmd = &mlist[i]; icmd = &mlist[i];
if (icmd->status == RG_VALID) { if (icmd->status == RG_VALID)
{
iplug = g_plugins->find(icmd->plugid); iplug = g_plugins->find(icmd->plugid);
if (iplug) { if (iplug)
strncpy(bplug, iplug->desc, sizeof bplug - 1); {
Q_strncpy(bplug, iplug->desc, sizeof bplug - 1);
bplug[sizeof bplug - 1] = '\0'; bplug[sizeof bplug - 1] = '\0';
} }
else { else
strncpy(bplug, "(unknown)", sizeof bplug - 1); {
Q_strncpy(bplug, "(unknown)", sizeof bplug - 1);
bplug[sizeof bplug - 1] = '\0'; bplug[sizeof bplug - 1] = '\0';
} }
} }
else { else
strncpy(bplug, "(unloaded)", sizeof bplug - 1); {
Q_strncpy(bplug, "(unloaded)", sizeof bplug - 1);
bplug[sizeof bplug - 1] = '\0'; bplug[sizeof bplug - 1] = '\0';
} }
META_CONS(" [%*d] %-*s %-s",
WIDTH_MAX_REG, icmd->index, META_CONS(" [%*d] %-*s %-s", WIDTH_MAX_REG, icmd->index, sizeof(bplug) - 1, bplug, icmd->name);
sizeof(bplug) - 1, bplug, if (icmd->status == RG_VALID)
icmd->name); a++;
if (icmd->status == RG_VALID) a++;
n++; n++;
} }
META_CONS("%d commands, %d available (%d allocated)", n, a, size); META_CONS("%d commands, %d available (%d allocated)", n, a, size);
} }
// List all the registered commands for the given plugin id. // List all the registered commands for the given plugin id.
void MRegCmdList::show(int plugin_id) void MRegCmdList::show(int plugin_id)
{ {
int i, n = 0; int n = 0;
MRegCmd *icmd; MRegCmd *icmd;
// If OS doesn't support DLFNAME, then we can't know what the plugin's // If OS doesn't support DLFNAME, then we can't know what the plugin's
// registered cvars are. // registered cvars are.
DLFNAME(NULL); DLFNAME(NULL);
if (meta_errno == ME_OSNOTSUP) { if (meta_errno == ME_OSNOTSUP)
{
META_CONS("Registered commands: unknown (can't get info under this OS)"); META_CONS("Registered commands: unknown (can't get info under this OS)");
return; return;
} }
META_CONS("Registered commands:"); META_CONS("Registered commands:");
for (i = 0; i < endlist; i++) { for (int i = 0; i < endlist; i++)
{
icmd = &mlist[i]; icmd = &mlist[i];
if (icmd->plugid != plugin_id) if (icmd->plugid != plugin_id)
continue; continue;
META_CONS(" %s", icmd->name); META_CONS(" %s", icmd->name);
n++; n++;
} }
META_CONS("%d commands", n); META_CONS("%d commands", n);
} }
///// class MRegCvar:
// Init values. It would probably be more "proper" to use containers and // Init values. It would probably be more "proper" to use containers and
// constructors, rather than arrays and init-functions. // constructors, rather than arrays and init-functions.
void MRegCvar::init(int idx) void MRegCvar::init(int idx)
@ -248,32 +212,31 @@ void MRegCvar::init(int idx)
// - ME_ARGUMENT given cvar doesn't match this cvar // - ME_ARGUMENT given cvar doesn't match this cvar
mBOOL MRegCvar::set(cvar_t *src) mBOOL MRegCvar::set(cvar_t *src)
{ {
if (_stricmp(src->name, data->name)) { if (Q_stricmp(src->name, data->name))
META_ERROR("Tried to set cvar with mismatched name; src=%s dst=%s", {
src->name, data->name); META_ERROR("Tried to set cvar with mismatched name; src=%s dst=%s", src->name, data->name);
RETURN_ERRNO(mFALSE, ME_ARGUMENT); RETURN_ERRNO(mFALSE, ME_ARGUMENT);
} }
// Would like to free() existing string, but can't tell where it was // Would like to free() existing string, but can't tell where it was
// allocated... // allocated...
data->string = _strdup(src->string); data->string = Q_strdup(src->string);
data->flags = src->flags; data->flags = src->flags;
data->value = src->value; data->value = src->value;
data->next = src->next; data->next = src->next;
return (mTRUE); return mTRUE;
} }
///// class MRegCvarList:
// Constructor // Constructor
MRegCvarList::MRegCvarList(void) MRegCvarList::MRegCvarList()
: vlist(0), size(REG_CVAR_GROWSIZE), endlist(0) : vlist(0), size(REG_CVAR_GROWSIZE), endlist(0)
{ {
int i; vlist = (MRegCvar *)Q_malloc(size * sizeof(MRegCvar));
vlist = (MRegCvar *) malloc(size * sizeof(MRegCvar));
// initialize array // initialize array
for (i = 0; i < size; i++) for (int i = 0; i < size; i++)
vlist[i].init(i + 1); // 1 - based vlist[i].init(i + 1); // 1 - based
endlist = 0; endlist = 0;
} }
@ -285,22 +248,22 @@ MRegCvarList::MRegCvarList(void)
MRegCvar *MRegCvarList::add(const char *addname) MRegCvar *MRegCvarList::add(const char *addname)
{ {
MRegCvar *icvar; MRegCvar *icvar;
if (endlist == size)
if (endlist == size) { {
// grow array // grow array
MRegCvar* temp; int newsize = size + REG_CVAR_GROWSIZE;
int i, newsize;
newsize = size + REG_CVAR_GROWSIZE;
META_DEBUG(6, ("Growing reg cvar list from %d to %d", size, newsize)); META_DEBUG(6, ("Growing reg cvar list from %d to %d", size, newsize));
temp = (MRegCvar *) realloc(vlist, newsize * sizeof(MRegCvar)); MRegCvar *temp = (MRegCvar *) realloc(vlist, newsize * sizeof(MRegCvar));
if (!temp) { if (!temp)
{
META_ERROR("Couldn't grow registered cvar list to %d for '%s'; %s", newsize, addname, strerror(errno)); META_ERROR("Couldn't grow registered cvar list to %d for '%s'; %s", newsize, addname, strerror(errno));
RETURN_ERRNO(NULL, ME_NOMEM); RETURN_ERRNO(NULL, ME_NOMEM);
} }
vlist = temp; vlist = temp;
size = newsize; size = newsize;
// initialize new (unused) entries // initialize new (unused) entries
for (i = endlist; i < size; i++) for (int i = endlist; i < size; i++)
vlist[i].init(i + 1); // 1-based vlist[i].init(i + 1); // 1-based
} }
@ -311,21 +274,21 @@ MRegCvar* MRegCvarList::add(const char* addname)
// happen). // happen).
// - Can't point to memory in vlist which might get moved later by // - Can't point to memory in vlist which might get moved later by
// realloc (again, segv). // realloc (again, segv).
icvar->data = (cvar_t *) malloc(sizeof(cvar_t)); icvar->data = (cvar_t *)Q_malloc(sizeof(cvar_t));
if (!icvar->data) { if (!icvar->data)
META_ERROR("Couldn't malloc cvar for adding reg cvar name '%s': %s", {
addname, strerror(errno)); META_ERROR("Couldn't malloc cvar for adding reg cvar name '%s': %s", addname, strerror(errno));
RETURN_ERRNO(NULL, ME_NOMEM); RETURN_ERRNO(NULL, ME_NOMEM);
} }
icvar->data->name = _strdup(addname);
if (!icvar->data->name) { icvar->data->name = Q_strdup(addname);
META_ERROR("Couldn't _strdup for adding reg cvar name '%s': %s", if (!icvar->data->name)
addname, strerror(errno)); {
META_ERROR("Couldn't Q_strdup for adding reg cvar name '%s': %s", addname, strerror(errno));
RETURN_ERRNO(NULL, ME_NOMEM); RETURN_ERRNO(NULL, ME_NOMEM);
} }
endlist++; endlist++;
return icvar;
return (icvar);
} }
// Try to find a registered cvar with the given name. // Try to find a registered cvar with the given name.
@ -333,11 +296,12 @@ MRegCvar* MRegCvarList::add(const char* addname)
// - ME_NOTFOUND couldn't find a matching cvar // - ME_NOTFOUND couldn't find a matching cvar
MRegCvar *MRegCvarList::find(const char *findname) MRegCvar *MRegCvarList::find(const char *findname)
{ {
int i; for (int i = 0; i < endlist; i++)
for (i = 0; i < endlist; i++) { {
if (!_stricmp(vlist[i].data->name, findname)) if (!_stricmp(vlist[i].data->name, findname))
return (&vlist[i]); return &vlist[i];
} }
RETURN_ERRNO(NULL, ME_NOTFOUND); RETURN_ERRNO(NULL, ME_NOTFOUND);
} }
@ -346,9 +310,11 @@ void MRegCvarList::disable(int plugin_id)
{ {
int i; int i;
MRegCvar *icvar; MRegCvar *icvar;
for (i = 0; i < size; i++) { for (i = 0; i < size; i++)
{
icvar = &vlist[i]; icvar = &vlist[i];
if (icvar->plugid == plugin_id) { if (icvar->plugid == plugin_id)
{
icvar->status = RG_INVALID; icvar->status = RG_INVALID;
icvar->plugid = 0; icvar->plugid = 0;
// Decided not to do this, in order to keep pre-existing values // Decided not to do this, in order to keep pre-existing values
@ -359,7 +325,7 @@ void MRegCvarList::disable(int plugin_id)
} }
// List all the registered cvars. // List all the registered cvars.
void MRegCvarList::show(void) void MRegCvarList::show()
{ {
int i, n = 0, a = 0; int i, n = 0, a = 0;
MRegCvar *icvar; MRegCvar *icvar;
@ -367,40 +333,38 @@ void MRegCvarList::show(void)
char bplug[13 + 1], bname[20 + 1], bval[15 + 1]; // +1 for term null char bplug[13 + 1], bname[20 + 1], bval[15 + 1]; // +1 for term null
META_CONS("Registered plugin cvars:"); META_CONS("Registered plugin cvars:");
META_CONS(" %*s %-*s %-*s %*s %s", META_CONS(" %*s %-*s %-*s %*s %s", WIDTH_MAX_REG, "", sizeof(bplug) - 1, "plugin", sizeof(bname) - 1, "cvar", sizeof(bval) - 1, "float value", "string value");
WIDTH_MAX_REG, "", for (i = 0; i < endlist; i++)
sizeof(bplug) - 1, "plugin", {
sizeof(bname) - 1, "cvar",
sizeof(bval) - 1, "float value",
"string value");
for (i = 0; i < endlist; i++) {
icvar = &vlist[i]; icvar = &vlist[i];
if (icvar->status == RG_VALID) { if (icvar->status == RG_VALID)
{
iplug = g_plugins->find(icvar->plugid); iplug = g_plugins->find(icvar->plugid);
if (iplug) { if (iplug)
strncpy(bplug, iplug->desc, sizeof bplug - 1); {
Q_strncpy(bplug, iplug->desc, sizeof bplug - 1);
bplug[sizeof bplug - 1] = '\0'; bplug[sizeof bplug - 1] = '\0';
} }
else { else
strncpy(bplug, "(unknown)", sizeof bplug - 1); {
Q_strncpy(bplug, "(unknown)", sizeof bplug - 1);
bplug[sizeof bplug - 1] = '\0'; bplug[sizeof bplug - 1] = '\0';
} }
} }
else { else
strncpy(bplug, "(unloaded)", sizeof bplug - 1); {
Q_strncpy(bplug, "(unloaded)", sizeof bplug - 1);
bplug[sizeof bplug - 1] = '\0'; bplug[sizeof bplug - 1] = '\0';
} }
strncpy(bname, icvar->data->name, sizeof bname - 1); Q_strncpy(bname, icvar->data->name, sizeof bname - 1);
bname[sizeof bname - 1] = '\0'; bname[sizeof bname - 1] = '\0';
snprintf(bval, sizeof(bval), "%f", icvar->data->value); Q_snprintf(bval, sizeof(bval), "%f", icvar->data->value);
META_CONS(" [%*d] %-*s %-*s %*s %s", META_CONS(" [%*d] %-*s %-*s %*s %s", WIDTH_MAX_REG, icvar->index, sizeof(bplug) - 1, bplug, sizeof(bname) - 1, bname, sizeof(bval) - 1, bval, icvar->data->string);
WIDTH_MAX_REG, icvar->index,
sizeof(bplug) - 1, bplug, if (icvar->status == RG_VALID)
sizeof(bname) - 1, bname, a++;
sizeof(bval) - 1, bval,
icvar->data->string);
if (icvar->status == RG_VALID) a++;
n++; n++;
} }
META_CONS("%d cvars, %d available (%d allocated)", n, a, size); META_CONS("%d cvars, %d available (%d allocated)", n, a, size);
@ -409,50 +373,47 @@ void MRegCvarList::show(void)
// List the registered cvars for the given plugin id. // List the registered cvars for the given plugin id.
void MRegCvarList::show(int plugin_id) void MRegCvarList::show(int plugin_id)
{ {
int i, n = 0; int n = 0;
MRegCvar *icvar; MRegCvar *icvar;
char bname[30 + 1], bval[15 + 1]; // +1 for term null char bname[30 + 1], bval[15 + 1]; // +1 for term null
// If OS doesn't support DLFNAME, then we can't know what the plugin's // If OS doesn't support DLFNAME, then we can't know what the plugin's
// registered cvars are. // registered cvars are.
DLFNAME(NULL); DLFNAME(NULL);
if (meta_errno == ME_OSNOTSUP) { if (meta_errno == ME_OSNOTSUP)
{
META_CONS("Registered cvars: unknown (can't get info under this OS)"); META_CONS("Registered cvars: unknown (can't get info under this OS)");
return; return;
} }
META_CONS("%-*s %*s %s",
sizeof(bname) - 1, "Registered cvars:", META_CONS("%-*s %*s %s", sizeof(bname) - 1, "Registered cvars:", sizeof(bval) - 1, "float value", "string value");
sizeof(bval) - 1, "float value", for (int i = 0; i < endlist; i++)
"string value"); {
for (i = 0; i < endlist; i++) {
icvar = &vlist[i]; icvar = &vlist[i];
if (icvar->plugid != plugin_id) if (icvar->plugid != plugin_id)
continue; continue;
strncpy(bname, icvar->data->name, sizeof bname - 1);
Q_strncpy(bname, icvar->data->name, sizeof bname - 1);
bname[sizeof bname - 1] = '\0'; bname[sizeof bname - 1] = '\0';
snprintf(bval, sizeof(bval), "%f", icvar->data->value); Q_snprintf(bval, sizeof(bval), "%f", icvar->data->value);
META_CONS(" %-*s %*s %s", META_CONS(" %-*s %*s %s", sizeof(bname) - 1, bname, sizeof(bval) - 1, bval, icvar->data->string);
sizeof(bname) - 1, bname,
sizeof(bval) - 1, bval,
icvar->data->string);
n++; n++;
} }
META_CONS("%d cvars", n); META_CONS("%d cvars", n);
} }
///// class MRegMsgList:
// Constructor // Constructor
MRegMsgList::MRegMsgList(void) MRegMsgList::MRegMsgList()
: size(MAX_REG_MSGS), endlist(0) : size(MAX_REG_MSGS), endlist(0)
{ {
int i;
// initialize array // initialize array
memset(mlist, 0, sizeof(mlist)); Q_memset(mlist, 0, sizeof(mlist));
for (i = 0; i < size; i++) { for (int i = 0; i < size; i++)
{
mlist[i].index = i + 1; // 1-based mlist[i].index = i + 1; // 1-based
} }
endlist = 0; endlist = 0;
} }
@ -461,16 +422,14 @@ MRegMsgList::MRegMsgList(void)
// - ME_MAXREACHED reached max number of msgs allowed // - ME_MAXREACHED reached max number of msgs allowed
MRegMsg *MRegMsgList::add(const char *addname, int addmsgid, int addsize) MRegMsg *MRegMsgList::add(const char *addname, int addmsgid, int addsize)
{ {
MRegMsg* imsg; if (endlist == size)
{
if (endlist == size) {
// all slots used // all slots used
META_ERROR("Couldn't add registered msg '%s' to list; reached max msgs (%d)", META_ERROR("Couldn't add registered msg '%s' to list; reached max msgs (%d)", addname, size);
addname, size);
RETURN_ERRNO(NULL, ME_MAXREACHED); RETURN_ERRNO(NULL, ME_MAXREACHED);
} }
imsg = &mlist[endlist]; MRegMsg *imsg = &mlist[endlist];
endlist++; endlist++;
// Copy msg data into empty slot. // Copy msg data into empty slot.
@ -480,7 +439,7 @@ MRegMsg* MRegMsgList::add(const char* addname, int addmsgid, int addsize)
imsg->msgid = addmsgid; imsg->msgid = addmsgid;
imsg->size = addsize; imsg->size = addsize;
return (imsg); return imsg;
} }
// Try to find a registered msg with the given name. // Try to find a registered msg with the given name.
@ -488,11 +447,12 @@ MRegMsg* MRegMsgList::add(const char* addname, int addmsgid, int addsize)
// - ME_NOTFOUND couldn't find a matching cvar // - ME_NOTFOUND couldn't find a matching cvar
MRegMsg *MRegMsgList::find(const char *findname) MRegMsg *MRegMsgList::find(const char *findname)
{ {
int i; for (int i = 0; i < endlist; i++)
for (i = 0; i < endlist; i++) { {
if (!strcmp(mlist[i].name, findname)) if (!Q_strcmp(mlist[i].name, findname))
return (&mlist[i]); return &mlist[i];
} }
RETURN_ERRNO(NULL, ME_NOTFOUND); RETURN_ERRNO(NULL, ME_NOTFOUND);
} }
@ -501,33 +461,32 @@ MRegMsg* MRegMsgList::find(const char* findname)
// - ME_NOTFOUND couldn't find a matching cvar // - ME_NOTFOUND couldn't find a matching cvar
MRegMsg *MRegMsgList::find(int findmsgid) MRegMsg *MRegMsgList::find(int findmsgid)
{ {
int i; for (int i = 0; i < endlist; i++)
for (i = 0; i < endlist; i++) { {
if (mlist[i].msgid == findmsgid) if (mlist[i].msgid == findmsgid)
return (&mlist[i]); return &mlist[i];
} }
RETURN_ERRNO(NULL, ME_NOTFOUND); RETURN_ERRNO(NULL, ME_NOTFOUND);
} }
// List the registered usermsgs for the gamedll. // List the registered usermsgs for the gamedll.
void MRegMsgList::show(void) void MRegMsgList::show()
{ {
int i, n = 0; int i, n = 0;
MRegMsg *imsg; MRegMsg *imsg;
char bname[25 + 1]; // +1 for term null char bname[25 + 1]; // +1 for term null
META_CONS("%-*s %5s %5s", META_CONS("%-*s %5s %5s", sizeof(bname) - 1, "Game registered user msgs:", "msgid", "size");
sizeof(bname) - 1, "Game registered user msgs:", "msgid", "size"); for (i = 0; i < endlist; i++)
for (i = 0; i < endlist; i++) { {
imsg = &mlist[i]; imsg = &mlist[i];
strncpy(bname, imsg->name, sizeof bname - 1);
Q_strncpy(bname, imsg->name, sizeof bname - 1);
bname[sizeof bname - 1] = '\0'; bname[sizeof bname - 1] = '\0';
META_CONS(" %-*s %3d %3d", META_CONS(" %-*s %3d %3d", sizeof(bname) - 1, bname, imsg->msgid, imsg->size);
sizeof(bname) - 1, bname,
imsg->msgid,
imsg->size);
n++; n++;
} }
META_CONS("%d game user msgs", n); META_CONS("%d game user msgs", n);
} }

View File

@ -1,42 +1,4 @@
// vi: set ts=4 sw=4 : #pragma once
// vim: set tw=75 :
// mreg.h - description of registered items (classes MRegCmd, MRegCmdList)
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef MREG_H
#define MREG_H
#include "types_meta.h" // mBOOL #include "types_meta.h" // mBOOL
// Number of entries to add to reglists when they need to grow. Typically // Number of entries to add to reglists when they need to grow. Typically
@ -57,78 +19,79 @@
#define MAX_REG_MSGS 256 #define MAX_REG_MSGS 256
// Flags to indicate if given cvar or func is part of a loaded plugin. // Flags to indicate if given cvar or func is part of a loaded plugin.
typedef enum { enum REG_STATUS { RG_INVALID, RG_VALID };
RG_INVALID,
RG_VALID,
} REG_STATUS;
// Pointer to function registered by AddServerCommand. // Pointer to function registered by AddServerCommand.
typedef void (*REG_CMD_FN) (void); typedef void (*REG_CMD_FN)();
// An individual registered function/command. // An individual registered function/command.
class MRegCmd { class MRegCmd {
friend class MRegCmdList;
private:
// data:
int index; // 1-based
public: public:
friend class MRegCmdList;
char *name; // space is malloc'd char *name; // space is malloc'd
REG_CMD_FN pfnCmd; // pointer to the function REG_CMD_FN pfnCmd; // pointer to the function
int plugid; // index id of corresponding plugin int plugid; // index id of corresponding plugin
REG_STATUS status; // whether corresponding plugin is loaded REG_STATUS status; // whether corresponding plugin is loaded
// functions:
void init(int idx); // init values, as not using constructors
mBOOL call(void); // try to call the function
};
void init(int idx); // init values, as not using constructors
mBOOL call(); // try to call the function
private:
int index; // 1-based
};
// A list of registered commands. // A list of registered commands.
class MRegCmdList { class MRegCmdList {
public:
MRegCmdList();
MRegCmd *find(const char *findname); // find by MRegCmd->name
MRegCmd *add(const char *addname);
void disable(int plugin_id); // change status to Invalid
void show(); // list all funcs to console
void show(int plugin_id); // list given plugin's funcs to console
private: private:
// data:
MRegCmd *mlist; // malloc'd array of registered commands MRegCmd *mlist; // malloc'd array of registered commands
int size; // current size of list int size; // current size of list
int endlist; // index of last used entry int endlist; // index of last used entry
// Private; to satisfy -Weffc++ "has pointer data members but does // Private; to satisfy -Weffc++ "has pointer data members but does
// not override" copy/assignment constructor. // not override" copy/assignment constructor.
void operator=(const MRegCmdList &src); void operator=(const MRegCmdList &src);
MRegCmdList(const MRegCmdList &src); MRegCmdList(const MRegCmdList &src);
public:
// constructor:
MRegCmdList(void);
// functions:
MRegCmd *find(const char *findname); // find by MRegCmd->name
MRegCmd *add(const char *addname);
void disable(int plugin_id); // change status to Invalid
void show(void); // list all funcs to console
void show(int plugin_id); // list given plugin's funcs to console
}; };
// An individual registered cvar. // An individual registered cvar.
class MRegCvar { class MRegCvar {
friend class MRegCvarList;
private:
// data:
int index; // 1-based
public: public:
friend class MRegCvarList;
cvar_t *data; // actual cvar structure, malloc'd cvar_t *data; // actual cvar structure, malloc'd
int plugid; // index id of corresponding plugin int plugid; // index id of corresponding plugin
REG_STATUS status; // whether corresponding plugin is loaded REG_STATUS status; // whether corresponding plugin is loaded
// functions:
void init(int idx); // init values, as not using constructors void init(int idx); // init values, as not using constructors
mBOOL set(cvar_t *src); mBOOL set(cvar_t *src);
};
private:
int index; // 1-based
};
// A list of registered cvars. // A list of registered cvars.
class MRegCvarList { class MRegCvarList {
public:
MRegCvarList();
MRegCvar *add(const char *addname);
MRegCvar *find(const char *findname); // find by MRegCvar->data.name
void disable(int plugin_id); // change status to Invalid
void show(); // list all cvars to console
void show(int plugin_id); // list given plugin's cvars to console
private: private:
// data:
MRegCvar *vlist; // malloc'd array of registered cvars MRegCvar *vlist; // malloc'd array of registered cvars
int size; // size of list, ie MAX_REG_CVARS int size; // size of list, ie MAX_REG_CVARS
int endlist; // index of last used entry int endlist; // index of last used entry
@ -136,51 +99,33 @@ class MRegCvarList {
// not override" copy/assignment constructor. // not override" copy/assignment constructor.
void operator=(const MRegCvarList &src); void operator=(const MRegCvarList &src);
MRegCvarList(const MRegCvarList &src); MRegCvarList(const MRegCvarList &src);
public:
// constructor:
MRegCvarList(void);
// functions:
MRegCvar *add(const char *addname);
MRegCvar *find(const char *findname); // find by MRegCvar->data.name
void disable(int plugin_id); // change status to Invalid
void show(void); // list all cvars to console
void show(int plugin_id); // list given plugin's cvars to console
}; };
// An individual registered user msg, from gamedll. // An individual registered user msg, from gamedll.
class MRegMsg { class MRegMsg {
friend class MRegMsgList;
private:
// data:
int index; // 1-based
public: public:
friend class MRegMsgList;
const char *name; // name, assumed constant string in gamedll const char *name; // name, assumed constant string in gamedll
int msgid; // msgid, assigned by engine int msgid; // msgid, assigned by engine
int size; // size, if given by gamedll int size; // size, if given by gamedll
};
private:
int index; // 1-based
};
// A list of registered user msgs. // A list of registered user msgs.
class MRegMsgList { class MRegMsgList {
private:
// data:
MRegMsg mlist[MAX_REG_MSGS]; // array of registered msgs
int size; // size of list, ie MAX_REG_MSGS
int endlist; // index of last used entry
public: public:
// constructor: MRegMsgList();
MRegMsgList(void);
// functions:
MRegMsg *add(const char *addname, int addmsgid, int addsize); MRegMsg *add(const char *addname, int addmsgid, int addsize);
MRegMsg *find(const char *findname); MRegMsg *find(const char *findname);
MRegMsg *find(int findmsgid); MRegMsg *find(int findmsgid);
void show(void); // list all msgs to console void show(); // list all msgs to console
};
#endif /* MREG_H */ private:
MRegMsg mlist[MAX_REG_MSGS]; // array of registered msgs
int size; // size of list, ie MAX_REG_MSGS
int endlist; // index of last used entry
};

View File

@ -1,39 +1,3 @@
// vi: set ts=4 sw=4 :
// vim: set tw=75 :
// mutil.cpp - utility functions to provide to plugins
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#include "precompiled.h" #include "precompiled.h"
hudtextparms_t default_csay_tparms = { hudtextparms_t default_csay_tparms = {
@ -46,19 +10,20 @@ hudtextparms_t default_csay_tparms = {
}; };
// Log to console; newline added. // Log to console; newline added.
void mutil_LogConsole(plid_t /* plid */, const char* fmt, ...) void mutil_LogConsole(plid_t plid, const char *fmt, ...)
{ {
va_list ap; va_list ap;
char buf[MAX_LOGMSG_LEN]; char buf[MAX_LOGMSG_LEN];
unsigned int len; unsigned int len;
va_start(ap, fmt); va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap); Q_vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap); va_end(ap);
// end msg with newline // end msg with newline
len = strlen(buf); len = Q_strlen(buf);
if (len < sizeof(buf) - 2) // -1 null, -1 for newline if (len < sizeof(buf) - 2) // -1 null, -1 for newline
strcat(buf, "\n"); Q_strcat(buf, "\n");
else else
buf[len - 1] = '\n'; buf[len - 1] = '\n';
@ -70,11 +35,10 @@ void mutil_LogMessage(plid_t plid, const char* fmt, ...)
{ {
va_list ap; va_list ap;
char buf[MAX_LOGMSG_LEN]; char buf[MAX_LOGMSG_LEN];
plugin_info_t* plinfo; plugin_info_t *plinfo = (plugin_info_t *)plid;
plinfo = (plugin_info_t *)plid;
va_start(ap, fmt); va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap); Q_vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap); va_end(ap);
ALERT(at_logged, "[%s] %s\n", plinfo->logtag, buf); ALERT(at_logged, "[%s] %s\n", plinfo->logtag, buf);
} }
@ -84,11 +48,10 @@ void mutil_LogError(plid_t plid, const char* fmt, ...)
{ {
va_list ap; va_list ap;
char buf[MAX_LOGMSG_LEN]; char buf[MAX_LOGMSG_LEN];
plugin_info_t* plinfo; plugin_info_t *plinfo = (plugin_info_t *)plid;
plinfo = (plugin_info_t *)plid;
va_start(ap, fmt); va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap); Q_vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap); va_end(ap);
ALERT(at_logged, "[%s] ERROR: %s\n", plinfo->logtag, buf); ALERT(at_logged, "[%s] ERROR: %s\n", plinfo->logtag, buf);
} }
@ -105,7 +68,7 @@ void mutil_LogDeveloper(plid_t plid, const char* fmt, ...)
plinfo = (plugin_info_t *)plid; plinfo = (plugin_info_t *)plid;
va_start(ap, fmt); va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap); Q_vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap); va_end(ap);
ALERT(at_logged, "[%s] dev: %s\n", plinfo->logtag, buf); ALERT(at_logged, "[%s] dev: %s\n", plinfo->logtag, buf);
} }
@ -131,17 +94,17 @@ void mutil_CenterSayParms(plid_t plid, hudtextparms_t tparms, const char* fmt, .
// Print a center-message, with text parameters and varargs. Provides // Print a center-message, with text parameters and varargs. Provides
// functionality to the above center_say interfaces. // functionality to the above center_say interfaces.
void mutil_CenterSayVarargs(plid_t plid, hudtextparms_t tparms, void mutil_CenterSayVarargs(plid_t plid, hudtextparms_t tparms, const char* fmt, va_list ap)
const char* fmt, va_list ap)
{ {
char buf[MAX_LOGMSG_LEN]; char buf[MAX_LOGMSG_LEN];
int n; int n;
edict_t *pEntity; edict_t *pEntity;
vsnprintf(buf, sizeof(buf), fmt, ap); Q_vsnprintf(buf, sizeof(buf), fmt, ap);
mutil_LogMessage(plid, "(centersay) %s", buf); mutil_LogMessage(plid, "(centersay) %s", buf);
for (n = 1; n <= gpGlobals->maxClients; n++) { for (n = 1; n <= gpGlobals->maxClients; n++)
{
pEntity = INDEXENT(n); pEntity = INDEXENT(n);
if (FNullEnt(pEntity) || pEntity->free) if (FNullEnt(pEntity) || pEntity->free)
continue; continue;
@ -154,87 +117,83 @@ void mutil_CenterSayVarargs(plid_t plid, hudtextparms_t tparms,
// Jussi Kivilinna. // Jussi Kivilinna.
qboolean mutil_CallGameEntity(plid_t plid, const char *entStr, entvars_t *pev) qboolean mutil_CallGameEntity(plid_t plid, const char *entStr, entvars_t *pev)
{ {
plugin_info_t* plinfo; plugin_info_t *plinfo = (plugin_info_t *)plid;
ENTITY_FN pfnEntity; META_DEBUG(8, ("Looking up game entity '%s' for plugin '%s'", entStr, plinfo->name));
ENTITY_FN pfnEntity = (ENTITY_FN) DLSYM(GameDLL.handle, entStr);
plinfo = (plugin_info_t *)plid; if (!pfnEntity)
META_DEBUG(8, ("Looking up game entity '%s' for plugin '%s'", entStr, {
plinfo->name));
pfnEntity = (ENTITY_FN) DLSYM(GameDLL.handle, entStr);
if (!pfnEntity) {
META_ERROR("Couldn't find game entity '%s' in game DLL '%s' for plugin '%s'", entStr, GameDLL.name, plinfo->name); META_ERROR("Couldn't find game entity '%s' in game DLL '%s' for plugin '%s'", entStr, GameDLL.name, plinfo->name);
return (false); return false;
} }
META_DEBUG(7, ("Calling game entity '%s' for plugin '%s'", entStr,
plinfo->name)); META_DEBUG(7, ("Calling game entity '%s' for plugin '%s'", entStr, plinfo->name));
(*pfnEntity)(pev); (*pfnEntity)(pev);
return (true); return true;
} }
// Find a usermsg, registered by the gamedll, with the corresponding // Find a usermsg, registered by the gamedll, with the corresponding
// msgname, and return remaining info about it (msgid, size). // msgname, and return remaining info about it (msgid, size).
int mutil_GetUserMsgID(plid_t plid, const char* msgname, int* size) int mutil_GetUserMsgID(plid_t plid, const char* msgname, int* size)
{ {
plugin_info_t* plinfo; plugin_info_t *plinfo = (plugin_info_t *)plid;
MRegMsg* umsg; META_DEBUG(8, ("Looking up usermsg name '%s' for plugin '%s'", msgname, plinfo->name));
plinfo = (plugin_info_t *)plid; MRegMsg *umsg = g_regMsgs->find(msgname);
META_DEBUG(8, ("Looking up usermsg name '%s' for plugin '%s'", msgname, if (umsg)
plinfo->name)); {
umsg = g_regMsgs->find(msgname);
if (umsg) {
if (size) if (size)
*size = umsg->size; *size = umsg->size;
return (umsg->msgid); return umsg->msgid;
} }
else else
return (0); return 0;
} }
// Find a usermsg, registered by the gamedll, with the corresponding // Find a usermsg, registered by the gamedll, with the corresponding
// msgid, and return remaining info about it (msgname, size). // msgid, and return remaining info about it (msgname, size).
const char* mutil_GetUserMsgName(plid_t plid, int msgid, int *size) const char* mutil_GetUserMsgName(plid_t plid, int msgid, int *size)
{ {
plugin_info_t* plinfo; plugin_info_t *plinfo = (plugin_info_t *)plid;
MRegMsg* umsg; META_DEBUG(8, ("Looking up usermsg id '%d' for plugin '%s'", msgid, plinfo->name));
plinfo = (plugin_info_t *)plid;
META_DEBUG(8, ("Looking up usermsg id '%d' for plugin '%s'", msgid,
plinfo->name));
// Guess names for any built-in g_engine messages mentioned in the SDK; // Guess names for any built-in g_engine messages mentioned in the SDK;
// from dlls/util.h. // from dlls/util.h.
if (msgid < 64) { if (msgid < 64)
switch (msgid) { {
switch (msgid)
{
case SVC_TEMPENTITY: case SVC_TEMPENTITY:
if (size) *size = -1; if (size) *size = -1;
return ("tempentity?"); return "tempentity?";
case SVC_INTERMISSION: case SVC_INTERMISSION:
if (size) *size = -1; if (size) *size = -1;
return ("intermission?"); return "intermission?";
case SVC_CDTRACK: case SVC_CDTRACK:
if (size) *size = -1; if (size) *size = -1;
return ("cdtrack?"); return "cdtrack?";
case SVC_WEAPONANIM: case SVC_WEAPONANIM:
if (size) *size = -1; if (size) *size = -1;
return ("weaponanim?"); return "weaponanim?";
case SVC_ROOMTYPE: case SVC_ROOMTYPE:
if (size) *size = -1; if (size) *size = -1;
return ("roomtype?"); return "roomtype?";
case SVC_DIRECTOR: case SVC_DIRECTOR:
if (size) *size = -1; if (size) *size = -1;
return ("director?"); return "director?";
} }
} }
umsg = g_regMsgs->find(msgid);
if (umsg) { MRegMsg *umsg = g_regMsgs->find(msgid);
if (umsg)
{
if (size) if (size)
*size = umsg->size; *size = umsg->size;
// 'name' is assumed to be a constant string, allocated in the // 'name' is assumed to be a constant string, allocated in the
// gamedll. // gamedll.
return (umsg->name); return umsg->name;
} }
else else
return (NULL); return NULL;
} }
// Return the full path of the plugin's loaded dll/so file. // Return the full path of the plugin's loaded dll/so file.
@ -244,12 +203,13 @@ const char* mutil_GetPluginPath(plid_t plid)
MPlugin *plug; MPlugin *plug;
plug = g_plugins->find(plid); plug = g_plugins->find(plid);
if (!plug) { if (!plug)
META_ERROR("GetPluginPath: couldn't find plugin '%s'", {
plid->name); META_ERROR("GetPluginPath: couldn't find plugin '%s'", plid->name);
return (NULL); return NULL;
} }
strncpy(buf, plug->pathname, sizeof buf - 1);
Q_strncpy(buf, plug->pathname, sizeof buf - 1);
buf[sizeof buf - 1] = '\0'; buf[sizeof buf - 1] = '\0';
return buf; return buf;
} }
@ -259,7 +219,8 @@ const char* mutil_GetGameInfo(plid_t plid, ginfo_t type)
{ {
static char buf[MAX_STRBUF_LEN]; static char buf[MAX_STRBUF_LEN];
const char *cp; const char *cp;
switch (type) { switch (type)
{
case GINFO_NAME: case GINFO_NAME:
cp = GameDLL.name; cp = GameDLL.name;
break; break;
@ -279,11 +240,11 @@ const char* mutil_GetGameInfo(plid_t plid, ginfo_t type)
cp = GameDLL.real_pathname; cp = GameDLL.real_pathname;
break; break;
default: default:
META_ERROR("GetGameInfo: invalid request '%d' from plugin '%s'", META_ERROR("GetGameInfo: invalid request '%d' from plugin '%s'", type, plid->name);
type, plid->name); return NULL;
return (NULL);
} }
strncpy(buf, cp, sizeof buf - 1);
Q_strncpy(buf, cp, sizeof buf - 1);
buf[sizeof buf - 1] = '\0'; buf[sizeof buf - 1] = '\0';
return buf; return buf;
} }
@ -291,18 +252,21 @@ const char* mutil_GetGameInfo(plid_t plid, ginfo_t type)
int mutil_LoadMetaPlugin(plid_t plid, const char* fname, PLUG_LOADTIME now, void **plugin_handle) int mutil_LoadMetaPlugin(plid_t plid, const char* fname, PLUG_LOADTIME now, void **plugin_handle)
{ {
MPlugin *pl_loaded; MPlugin *pl_loaded;
if (!fname)
if (NULL == fname) { {
return ME_ARGUMENT; return ME_ARGUMENT;
} }
meta_errno = ME_NOERROR; meta_errno = ME_NOERROR;
if (! (pl_loaded = g_plugins->plugin_addload(plid, fname, now))) { if (!(pl_loaded = g_plugins->plugin_addload(plid, fname, now)))
{
if (plugin_handle) if (plugin_handle)
*plugin_handle = NULL; *plugin_handle = nullptr;
return meta_errno; return meta_errno;
} }
else { else
{
if (plugin_handle) if (plugin_handle)
*plugin_handle = (void *)pl_loaded->handle; *plugin_handle = (void *)pl_loaded->handle;
return 0; return 0;
@ -311,11 +275,12 @@ int mutil_LoadMetaPlugin(plid_t plid, const char* fname, PLUG_LOADTIME now, void
int mutil_UnloadMetaPlugin(plid_t plid, const char *fname, PLUG_LOADTIME now, PL_UNLOAD_REASON reason) int mutil_UnloadMetaPlugin(plid_t plid, const char *fname, PLUG_LOADTIME now, PL_UNLOAD_REASON reason)
{ {
MPlugin* findp = NULL; MPlugin *findp = nullptr;
int pindex; int pindex;
char *endptr; char *endptr;
if (NULL == fname) { if (!fname)
{
return ME_ARGUMENT; return ME_ARGUMENT;
} }
@ -340,7 +305,8 @@ int mutil_UnloadMetaPluginByHandle(plid_t plid, void* plugin_handle, PLUG_LOADTI
{ {
MPlugin *findp; MPlugin *findp;
if (NULL == plugin_handle) { if (!plugin_handle)
{
return ME_ARGUMENT; return ME_ARGUMENT;
} }
@ -355,63 +321,65 @@ int mutil_UnloadMetaPluginByHandle(plid_t plid, void* plugin_handle, PLUG_LOADTI
return meta_errno; return meta_errno;
} }
const char* mutil_IsQueryingClientCvar(plid_t /*plid*/, const edict_t* pEdict) const char* mutil_IsQueryingClientCvar(plid_t plid, const edict_t* pEdict)
{ {
return g_Players.is_querying_cvar(pEdict); return g_Players.is_querying_cvar(pEdict);
} }
int mutil_MakeRequestId(plid_t /*plid*/) int mutil_MakeRequestId(plid_t plid)
{ {
//the offset is to distinguish from gamedll requests, if any //the offset is to distinguish from gamedll requests, if any
return (abs(0xbeef << 16) + (++requestid_counter)); return abs(0xbeef << 16) + (++requestid_counter);
} }
void mutil_GetHookTables(plid_t /*plid*/, enginefuncs_t** peng, DLL_FUNCTIONS** pdll, NEW_DLL_FUNCTIONS** pnewdll) void mutil_GetHookTables(plid_t plid, enginefuncs_t** peng, DLL_FUNCTIONS** pdll, NEW_DLL_FUNCTIONS** pnewdll)
{ {
if (peng) if (peng)
*peng = &meta_engfuncs; *peng = &meta_engfuncs;
if (pdll) if (pdll)
*pdll = pHookedDllFunctions; *pdll = pHookedDllFunctions;
if (pnewdll) if (pnewdll)
*pnewdll = pHookedNewDllFunctions; *pnewdll = pHookedNewDllFunctions;
} }
#ifdef UNFINISHED #ifdef UNFINISHED
int mutil_HookGameEvent(plid_t plid, game_event_t event,
event_func_t pfnHandle) int mutil_HookGameEvent(plid_t plid, game_event_t event, event_func_t pfnHandle)
{ {
return(Hooks->add(plid, event, pfnHandle)); return Hooks->add(plid, event, pfnHandle);
} }
int mutil_HookLogTrigger(plid_t plid, const char *trigger, int mutil_HookLogTrigger(plid_t plid, const char *trigger, logmatch_func_t pfnHandle)
logmatch_func_t pfnHandle)
{ {
return(Hooks->add(plid, H_TRIGGER, trigger, pfnHandle)); return Hooks->add(plid, H_TRIGGER, trigger, pfnHandle);
} }
int mutil_HookLogString(plid_t plid, const char *string, int mutil_HookLogString(plid_t plid, const char *string, logmatch_func_t pfnHandle)
logmatch_func_t pfnHandle)
{ {
return(Hooks->add(plid, H_STRING, string, pfnHandle)); return Hooks->add(plid, H_STRING, string, pfnHandle);
} }
int mutil_HookLogRegex(plid_t plid, const char *pattern, int mutil_HookLogRegex(plid_t plid, const char *pattern, logmatch_func_t pfnHandle)
logmatch_func_t pfnHandle)
{ {
return(Hooks->add(plid, H_STRING, pattern, pfnHandle)); return Hooks->add(plid, H_STRING, pattern, pfnHandle);
} }
qboolean mutil_RemoveHookID(plid_t plid, int hookid) { qboolean mutil_RemoveHookID(plid_t plid, int hookid)
mBOOL ret; {
ret=Hooks->remove(plid, hookid); if (Hooks->remove(plid, hookid))
if(ret==mTRUE) return(true); return true;
else return(false);
return false;
} }
int mutil_RemoveHookAll(plid_t plid) { int mutil_RemoveHookAll(plid_t plid)
return(Hooks->remove_all(plid)); {
return Hooks->remove_all(plid);
} }
#endif /* UNFINISHED */
#endif // UNFINISHED
// Meta Utility Function table. // Meta Utility Function table.
mutil_funcs_t MetaUtilFunctions = { mutil_funcs_t MetaUtilFunctions = {
@ -440,5 +408,5 @@ mutil_funcs_t MetaUtilFunctions = {
mutil_HookLogRegex, // pfnLogRegex mutil_HookLogRegex, // pfnLogRegex
mutil_RemoveHookID, // pfnRemoveHookID mutil_RemoveHookID, // pfnRemoveHookID
mutil_RemoveHookAll, // pfnRemoveHookAll mutil_RemoveHookAll, // pfnRemoveHookAll
#endif /* UNFINISHED */ #endif // UNFINISHED
}; };

View File

@ -1,41 +1,4 @@
// vi: set ts=4 sw=4 : #pragma once
// vim: set tw=75 :
// mutil.h - prototypes for utility functions to provide to plugins
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef MUTIL_H
#define MUTIL_H
#include "plinfo.h" // plugin_info_t, etc #include "plinfo.h" // plugin_info_t, etc
#include "sdk_util.h" // hudtextparms_t, etc #include "sdk_util.h" // hudtextparms_t, etc
@ -44,28 +7,27 @@
#define MAX_LOGMSG_LEN 1024 #define MAX_LOGMSG_LEN 1024
// For GetGameInfo: // For GetGameInfo:
typedef enum { enum ginfo_t
{
GINFO_NAME = 0, GINFO_NAME = 0,
GINFO_DESC, GINFO_DESC,
GINFO_GAMEDIR, GINFO_GAMEDIR,
GINFO_DLL_FULLPATH, GINFO_DLL_FULLPATH,
GINFO_DLL_FILENAME, GINFO_DLL_FILENAME,
GINFO_REALDLL_FULLPATH, GINFO_REALDLL_FULLPATH,
} ginfo_t; };
// Meta Utility Function table type. // Meta Utility Function table type.
typedef struct meta_util_funcs_s { struct mutil_funcs_t
{
void (*pfnLogConsole) (plid_t plid, const char *fmt, ...); void (*pfnLogConsole) (plid_t plid, const char *fmt, ...);
void (*pfnLogMessage) (plid_t plid, const char *fmt, ...); void (*pfnLogMessage) (plid_t plid, const char *fmt, ...);
void (*pfnLogError) (plid_t plid, const char *fmt, ...); void (*pfnLogError) (plid_t plid, const char *fmt, ...);
void (*pfnLogDeveloper) (plid_t plid, const char *fmt, ...); void (*pfnLogDeveloper) (plid_t plid, const char *fmt, ...);
void (*pfnCenterSay) (plid_t plid, const char *fmt, ...); void (*pfnCenterSay) (plid_t plid, const char *fmt, ...);
void (*pfnCenterSayParms) (plid_t plid, hudtextparms_t tparms, void (*pfnCenterSayParms) (plid_t plid, hudtextparms_t tparms, const char *fmt, ...);
const char *fmt, ...); void (*pfnCenterSayVarargs) (plid_t plid, hudtextparms_t tparms, const char *fmt, va_list ap);
void (*pfnCenterSayVarargs) (plid_t plid, hudtextparms_t tparms, qboolean (*pfnCallGameEntity) (plid_t plid, const char *entStr, entvars_t *pev);
const char *fmt, va_list ap);
qboolean (*pfnCallGameEntity) (plid_t plid, const char *entStr,
entvars_t *pev);
int (*pfnGetUserMsgID) (plid_t plid, const char *msgname, int *size); int (*pfnGetUserMsgID) (plid_t plid, const char *msgname, int *size);
const char * (*pfnGetUserMsgName) (plid_t plid, int msgid, int *size); const char * (*pfnGetUserMsgName) (plid_t plid, int msgid, int *size);
const char * (*pfnGetPluginPath) (plid_t plid); const char * (*pfnGetPluginPath) (plid_t plid);
@ -77,18 +39,15 @@ typedef struct meta_util_funcs_s {
int (*pfnMakeRequestId) (plid_t plid); int (*pfnMakeRequestId) (plid_t plid);
void (*pfnGetHookTables) (plid_t plid, enginefuncs_t **peng, DLL_FUNCTIONS **pdll, NEW_DLL_FUNCTIONS **pnewdll); void (*pfnGetHookTables) (plid_t plid, enginefuncs_t **peng, DLL_FUNCTIONS **pdll, NEW_DLL_FUNCTIONS **pnewdll);
#ifdef UNFINISHED #ifdef UNFINISHED
int (*pfnHookGameEvent) (plid_t plid, game_event_t event, int (*pfnHookGameEvent) (plid_t plid, game_event_t event, event_func_t pfnHandle);
event_func_t pfnHandle); int (*pfnHookLogTrigger) (plid_t plid, const char *trigger, logmatch_func_t pfnHandle);
int (*pfnHookLogTrigger) (plid_t plid, const char *trigger, int (*pfnHookLogString) (plid_t plid, const char *string, logmatch_func_t pfnHandle);
logmatch_func_t pfnHandle); int (*pfnHookLogRegex) (plid_t plid, const char *pattern, logmatch_func_t pfnHandle);
int (*pfnHookLogString) (plid_t plid, const char *string,
logmatch_func_t pfnHandle);
int (*pfnHookLogRegex) (plid_t plid, const char *pattern,
logmatch_func_t pfnHandle);
qboolean (*pfnRemoveHookID) (plid_t plid, int hookid); qboolean (*pfnRemoveHookID) (plid_t plid, int hookid);
int (*pfnRemoveHookAll) (plid_t plid); int (*pfnRemoveHookAll) (plid_t plid);
#endif /* UNFINISHED */ #endif
} mutil_funcs_t; };
extern mutil_funcs_t MetaUtilFunctions; extern mutil_funcs_t MetaUtilFunctions;
// Meta Utility Functions // Meta Utility Functions
@ -98,10 +57,8 @@ void mutil_LogError(plid_t plid, const char *fmt, ...);
void mutil_LogDeveloper(plid_t plid, const char *fmt, ...); void mutil_LogDeveloper(plid_t plid, const char *fmt, ...);
void mutil_CenterSay(plid_t plid, const char *fmt, ...); void mutil_CenterSay(plid_t plid, const char *fmt, ...);
void mutil_CenterSayParms(plid_t plid, hudtextparms_t tparms, void mutil_CenterSayParms(plid_t plid, hudtextparms_t tparms, const char *fmt, ...);
const char *fmt, ...); void mutil_CenterSayVarargs(plid_t plid, hudtextparms_t tparms, const char *fmt, va_list ap);
void mutil_CenterSayVarargs(plid_t plid, hudtextparms_t tparms,
const char *fmt, va_list ap);
qboolean mutil_CallGameEntity(plid_t plid, const char *entStr, entvars_t *pev); qboolean mutil_CallGameEntity(plid_t plid, const char *entStr, entvars_t *pev);
@ -114,18 +71,14 @@ int mutil_MakeRequestId(plid_t plid);
void mutil_GetHookTables(plid_t plid, enginefuncs_t **peng, DLL_FUNCTIONS **pdll, NEW_DLL_FUNCTIONS **pnewdll); void mutil_GetHookTables(plid_t plid, enginefuncs_t **peng, DLL_FUNCTIONS **pdll, NEW_DLL_FUNCTIONS **pnewdll);
#ifdef UNFINISHED #ifdef UNFINISHED
int mutil_HookGameEvent(plid_t plid, game_event_t event, int mutil_HookGameEvent(plid_t plid, game_event_t event, event_func_t pfnHandle);
event_func_t pfnHandle); int mutil_HookLogTrigger(plid_t plid, const char *trigger, logmatch_func_t pfnHandle);
int mutil_HookLogTrigger(plid_t plid, const char *trigger, int mutil_HookLogString(plid_t plid, const char *string, logmatch_func_t pfnHandle);
logmatch_func_t pfnHandle); int mutil_HookLogRegex(plid_t plid, const char *pattern, logmatch_func_t pfnHandle);
int mutil_HookLogString(plid_t plid, const char *string,
logmatch_func_t pfnHandle);
int mutil_HookLogRegex(plid_t plid, const char *pattern,
logmatch_func_t pfnHandle);
qboolean mutil_RemoveHookID(plid_t plid, int hookid); qboolean mutil_RemoveHookID(plid_t plid, int hookid);
int mutil_RemoveHookAll(plid_t plid); int mutil_RemoveHookAll(plid_t plid);
#endif /* UNFINISHED */ #endif
// Convenience macros for MetaUtil functions // Convenience macros for MetaUtil functions
#define LOG_CONSOLE (*gpMetaUtilFuncs->pfnLogConsole) #define LOG_CONSOLE (*gpMetaUtilFuncs->pfnLogConsole)
@ -154,6 +107,4 @@ int mutil_RemoveHookAll(plid_t plid);
#define HOOK_LOG_REGEX (*gpMetaUtilFuncs->pfnHookLogRegex) #define HOOK_LOG_REGEX (*gpMetaUtilFuncs->pfnHookLogRegex)
#define REMOVE_HOOK_ID (*gpMetaUtilFuncs->pfnRemoveHookID) #define REMOVE_HOOK_ID (*gpMetaUtilFuncs->pfnRemoveHookID)
#define REMOVE_HOOK_ALL (*gpMetaUtilFuncs->pfnRemoveHookAll) #define REMOVE_HOOK_ALL (*gpMetaUtilFuncs->pfnRemoveHookAll)
#endif /* UNFINISHED */ #endif
#endif /* MUTIL_H */

View File

@ -1,39 +1,3 @@
// vi: set ts=4 sw=4 :
// vim: set tw=75 :
// osdep.cpp - routines for operating system differences
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#include "precompiled.h" #include "precompiled.h"
mBOOL dlclose_handle_invalid; mBOOL dlclose_handle_invalid;
@ -41,7 +5,7 @@ mBOOL dlclose_handle_invalid;
// To keep the rest of the sources clean and keep not only OS but also // To keep the rest of the sources clean and keep not only OS but also
// compiler dependant differences in this file, we define a local function // compiler dependant differences in this file, we define a local function
// to set the new handler. // to set the new handler.
void mm_set_new_handler( void ) void mm_set_new_handler()
{ {
#if defined(_MSC_VER) && (_MSC_VER < 1300) #if defined(_MSC_VER) && (_MSC_VER < 1300)
_set_new_handler(meta_new_handler); _set_new_handler(meta_new_handler);
@ -54,28 +18,31 @@ void mm_set_new_handler( void )
// Since windows doesn't provide a verison of strtok_r(), we include one // Since windows doesn't provide a verison of strtok_r(), we include one
// here. This may or may not operate exactly like strtok_r(), but does // here. This may or may not operate exactly like strtok_r(), but does
// what we need it it do. // what we need it it do.
char *my_strtok_r(char *s, const char *delim, char **ptrptr) { char *my_strtok_r(char *s, const char *delim, char **ptrptr)
char *begin=NULL; {
char *end=NULL; char *begin = nullptr;
char *rest=NULL; char *end = nullptr;
char *rest = nullptr;
if (s) if (s)
begin = s; begin = s;
else else
begin = *ptrptr; begin = *ptrptr;
if (!begin) if (!begin)
return(NULL); return nullptr;
end = strpbrk(begin, delim); end = strpbrk(begin, delim);
if(end) { if (end)
{
*end = '\0'; *end = '\0';
rest = end + 1; rest = end + 1;
*ptrptr = rest + strspn(rest, delim); *ptrptr = rest + strspn(rest, delim);
} }
else else
*ptrptr=NULL; *ptrptr = nullptr;
return(begin);
}
#endif /* _WIN32 */
return begin;
}
#endif // _WIN32
#ifdef _WIN32 #ifdef _WIN32
// Windows doesn't provide a functon analagous to dlerr() that returns a // Windows doesn't provide a functon analagous to dlerr() that returns a
@ -83,27 +50,25 @@ char *my_strtok_r(char *s, const char *delim, char **ptrptr) {
// http://msdn.microsoft.com/library/en-us/debug/errors_0sdh.asp // http://msdn.microsoft.com/library/en-us/debug/errors_0sdh.asp
// except without FORMAT_MESSAGE_ALLOCATE_BUFFER, since we use a local // except without FORMAT_MESSAGE_ALLOCATE_BUFFER, since we use a local
// static buffer. // static buffer.
const char *str_GetLastError(void) { const char *str_GetLastError()
{
static char buf[MAX_STRBUF_LEN]; static char buf[MAX_STRBUF_LEN];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&buf, MAX_STRBUF_LEN - 1, NULL);
NULL, GetLastError(), return buf;
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), //! Default language
(LPTSTR) &buf, MAX_STRBUF_LEN-1, NULL);
return(buf);
} }
#endif /* _WIN32 */ #endif
// Find the filename of the DLL/shared-lib where the given memory location // Find the filename of the DLL/shared-lib where the given memory location
// exists. // exists.
#if defined(linux) || defined(__APPLE__) #if defined(linux) || defined(__APPLE__)
// Errno values: // Errno values:
// - ME_NOTFOUND couldn't find a sharedlib that contains memory location // - ME_NOTFOUND couldn't find a sharedlib that contains memory location
const char *DLFNAME(void *memptr) { const char *DLFNAME(void *memptr)
{
Dl_info dli; Dl_info dli;
memset(&dli, 0, sizeof(dli)); Q_memset(&dli, 0, sizeof(dli));
if (dladdr(memptr, &dli)) if (dladdr(memptr, &dli))
return(dli.dli_fname); return dli.dli_fname;
else else
RETURN_ERRNO(NULL, ME_NOTFOUND); RETURN_ERRNO(NULL, ME_NOTFOUND);
} }
@ -129,16 +94,19 @@ const char *DLFNAME(void *memptr) {
// //
// Errno values: // Errno values:
// - ME_NOTFOUND couldn't find a DLL that contains memory location // - ME_NOTFOUND couldn't find a DLL that contains memory location
const char *DLFNAME(void *memptr) { const char *DLFNAME(void *memptr)
{
MEMORY_BASIC_INFORMATION MBI; MEMORY_BASIC_INFORMATION MBI;
static char fname[PATH_MAX]; static char fname[PATH_MAX];
memset(fname, 0, sizeof(fname)); Q_memset(fname, 0, sizeof(fname));
if (!VirtualQuery(memptr, &MBI, sizeof(MBI))) if (!VirtualQuery(memptr, &MBI, sizeof(MBI)))
RETURN_ERRNO(NULL, ME_NOTFOUND); RETURN_ERRNO(NULL, ME_NOTFOUND);
if (MBI.State != MEM_COMMIT) if (MBI.State != MEM_COMMIT)
RETURN_ERRNO(NULL, ME_NOTFOUND); RETURN_ERRNO(NULL, ME_NOTFOUND);
if (!MBI.AllocationBase) if (!MBI.AllocationBase)
RETURN_ERRNO(NULL, ME_NOTFOUND); RETURN_ERRNO(NULL, ME_NOTFOUND);
@ -151,9 +119,9 @@ const char *DLFNAME(void *memptr) {
RETURN_ERRNO(NULL, ME_NOTFOUND); RETURN_ERRNO(NULL, ME_NOTFOUND);
normalize_pathname(fname); normalize_pathname(fname);
return(fname); return fname;
} }
#endif /* _WIN32 */ #endif // _WIN32
// Determine whether the given memory location is valid (ie whether we // Determine whether the given memory location is valid (ie whether we
@ -165,11 +133,12 @@ const char *DLFNAME(void *memptr) {
// we need it for in this particular situation. // we need it for in this particular situation.
// meta_errno values: // meta_errno values:
// - ME_NOTFOUND couldn't find a matching sharedlib for this ptr // - ME_NOTFOUND couldn't find a matching sharedlib for this ptr
mBOOL IS_VALID_PTR(void *memptr) { mBOOL IS_VALID_PTR(void *memptr)
{
Dl_info dli; Dl_info dli;
memset(&dli, 0, sizeof(dli)); Q_memset(&dli, 0, sizeof(dli));
if (dladdr(memptr, &dli)) if (dladdr(memptr, &dli))
return(mTRUE); return mTRUE;
else else
RETURN_ERRNO(mFALSE, ME_NOTFOUND); RETURN_ERRNO(mFALSE, ME_NOTFOUND);
} }
@ -177,40 +146,47 @@ mBOOL IS_VALID_PTR(void *memptr) {
// Use the native windows routine IsBadCodePtr. // Use the native windows routine IsBadCodePtr.
// meta_errno values: // meta_errno values:
// - ME_BADMEMPTR not a valid memory pointer // - ME_BADMEMPTR not a valid memory pointer
mBOOL IS_VALID_PTR(void *memptr) { mBOOL IS_VALID_PTR(void *memptr)
{
if (IsBadCodePtr((FARPROC) memptr)) if (IsBadCodePtr((FARPROC) memptr))
RETURN_ERRNO(mFALSE, ME_BADMEMPTR); RETURN_ERRNO(mFALSE, ME_BADMEMPTR);
else else
return(mTRUE); return mTRUE;
} }
#endif /* _WIN32 */ #endif // _WIN32
// This used to be OS-dependent, as it used a SEGV signal handler under // This used to be OS-dependent, as it used a SEGV signal handler under
// linux, but that was removed because (a) it masked legitimate segfaults // linux, but that was removed because (a) it masked legitimate segfaults
// in plugin commands and produced confusing output ("plugin has been // in plugin commands and produced confusing output ("plugin has been
// unloaded", when really it segfaultd), and (b) wasn't necessary since // unloaded", when really it segfaultd), and (b) wasn't necessary since
// IS_VALID_PTR() should cover the situation. // IS_VALID_PTR() should cover the situation.
mBOOL os_safe_call(REG_CMD_FN pfn) { mBOOL os_safe_call(REG_CMD_FN pfn)
{
// try and see if this is a valid memory location // try and see if this is a valid memory location
if (!IS_VALID_PTR((void *)pfn)) if (!IS_VALID_PTR((void *)pfn))
// meta_errno should be already set in is_valid_ptr() // meta_errno should be already set in is_valid_ptr()
return(mFALSE); return mFALSE;
pfn(); pfn();
return(mTRUE); return mTRUE;
} }
// See comments in osdep.h. // See comments in osdep.h.
#if defined(__GNUC__) || (defined(_MSC_VER) && (_MSC_VER >= 1300)) #if defined(_MSC_VER) && (_MSC_VER >= 1300)
void MM_CDECL meta_new_handler(void) { void __cdecl meta_new_handler()
// This merely because we don't want the program to exit if new() {
// fails..
return; return;
} }
#elif defined(_MSC_VER) #elif defined(_MSC_VER)
int meta_new_handler(size_t size) { int meta_new_handler(size_t size)
{
// This merely because we don't want the program to exit if new() // This merely because we don't want the program to exit if new()
// fails.. // fails..
return(0); return 0;
} }
#endif /* _MSC_VER */ #else
void meta_new_handler()
{
return;
}
#endif

View File

@ -1,194 +1,108 @@
// vi: set ts=4 sw=4 : #pragma once
// vim: set tw=75 :
// osdep.h - operating system dependencies
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef OSDEP_H
#define OSDEP_H
#include <string.h> // strerror()
#include <ctype.h> // isupper, tolower
#include <errno.h> // errno
// Various differences between WIN32 and Linux. // Various differences between WIN32 and Linux.
#include "types_meta.h" // mBOOL #include "types_meta.h" // mBOOL
#include "mreg.h" // REG_CMD_FN, etc #include "mreg.h" // REG_CMD_FN, etc
#include "log_meta.h" // LOG_ERROR, etc #include "log_meta.h" // LOG_ERROR, etc
extern mBOOL dlclose_handle_invalid;
// String describing platform/DLL-type, for matching lines in plugins.ini. // String describing platform/DLL-type, for matching lines in plugins.ini.
#ifdef __linux #ifdef _WIN32
#define PLATFORM "linux" #define UNUSED /**/
# ifdef __amd64__
#define PLATFORM_SPC "lin64"
# else
#define PLATFORM_SPC "lin32"
# endif
#elif defined(_WIN32)
#define PLATFORM "mswin" #define PLATFORM "mswin"
#define PLATFORM_SPC "win32" #define PLATFORM_SPC "win32"
#elif defined(__APPLE__) #define PLATFORM_DLEXT ".dll"
#define PLATFORM "osx"
#define PLATFORM_SPC "osx32"
#else /* unknown */
#error "OS unrecognized"
#endif /* unknown */
// Macro for function-exporting from DLL..
// from SDK dlls/cbase.h:
//! C functions for external declarations that call the appropriate C++ methods
// Windows uses "__declspec(dllexport)" to mark functions in the DLL that
// should be visible/callable externally.
//
// It also apparently requires WINAPI for GiveFnptrsToDll().
//
// See doc/notes_windows_coding for more information..
// Attributes to specify an "exported" function, visible from outside the
// DLL.
#undef DLLEXPORT
#ifdef _WIN32
#define DLLEXPORT __declspec(dllexport)
// WINAPI should be provided in the windows compiler headers.
// It's usually defined to something like "__stdcall".
#elif defined(__GNUC__)
# if __GNUC__ >= 4
#define DLLEXPORT __attribute__ ((visibility("default")))
#else #else
#define DLLEXPORT /* */ #define UNUSED __attribute__((unused))
#define PLATFORM "linux"
#define PLATFORM_SPC "lin32"
#define PLATFORM_DLEXT ".so"
#endif #endif
#define WINAPI /* */
#endif /* linux */
#ifdef __GNUC__
# define DECLSPEC(kw)
# define ATTRIBUTE(kw) __attribute__((kw))
# define MM_CDECL
#elif defined(_MSC_VER)
# define DECLSPEC(kw) __declspec(kw)
# define ATTRIBUTE(kw)
# define MM_CDECL __cdecl
#endif /* _MSC_VER */
// Simplified macro for declaring/defining exported DLL functions. They
// need to be 'extern "C"' so that the C++ compiler enforces parameter
// type-matching, rather than considering routines with mis-matched
// arguments/types to be overloaded functions...
//
// AFAIK, this is os-independent, but it's included here in osdep.h where
// DLLEXPORT is defined, for convenience.
#define C_DLLEXPORT extern "C" DLLEXPORT
#ifdef _MSC_VER
// Disable MSVC warning:
// 4390 : empty controlled statement found; is this what was intended?
// generated by the RETURN macros.
#pragma warning(disable: 4390)
#endif /* _MSC_VER */
extern mBOOL dlclose_handle_invalid;
// Functions & types for DLL open/close/etc operations. // Functions & types for DLL open/close/etc operations.
#if defined(__linux) || defined(__APPLE__) #ifdef _WIN32
#include <dlfcn.h>
typedef void* DLHANDLE;
typedef void* DLFUNC;
inline DLHANDLE DLOPEN(const char *filename) {
return(dlopen(filename, RTLD_NOW));
}
inline DLFUNC DLSYM(DLHANDLE handle, const char *string) {
return(dlsym(handle, string));
}
inline int DLCLOSE(DLHANDLE handle) {
if (!handle) {
dlclose_handle_invalid = mTRUE;
return(1);
}
dlclose_handle_invalid = mFALSE;
return(dlclose(handle));
}
inline const char* DLERROR(void) {
if (dlclose_handle_invalid)
return("Invalid handle.");
return(dlerror());
}
#elif defined(_WIN32)
typedef HINSTANCE DLHANDLE; typedef HINSTANCE DLHANDLE;
typedef FARPROC DLFUNC; typedef FARPROC DLFUNC;
inline DLHANDLE DLOPEN(const char *filename) { inline DLHANDLE DLOPEN(const char *filename)
return(LoadLibrary(filename)); {
return LoadLibraryA(filename);
} }
inline DLFUNC DLSYM(DLHANDLE handle, const char *string) { inline DLFUNC DLSYM(DLHANDLE handle, const char *string)
return(GetProcAddress(handle, string)); {
return GetProcAddress(handle, string);
} }
inline int DLCLOSE(DLHANDLE handle) { inline int DLCLOSE(DLHANDLE handle)
if (!handle) { {
if (!handle)
{
dlclose_handle_invalid = mTRUE; dlclose_handle_invalid = mTRUE;
return(1); return 1;
} }
dlclose_handle_invalid = mFALSE; dlclose_handle_invalid = mFALSE;
// NOTE: Windows FreeLibrary returns success=nonzero, fail=zero, // NOTE: Windows FreeLibrary returns success=nonzero, fail=zero,
// which is the opposite of the unix convention, thus the '!'. // which is the opposite of the unix convention, thus the '!'.
return(!FreeLibrary(handle)); return !FreeLibrary(handle);
} }
// Windows doesn't provide a function corresponding to dlerror(), so // Windows doesn't provide a function corresponding to dlerror(), so
// we make our own. // we make our own.
const char *str_GetLastError(void); const char *str_GetLastError();
inline const char* DLERROR(void) { inline const char *DLERROR()
{
if (dlclose_handle_invalid) if (dlclose_handle_invalid)
return("Invalid handle."); return "Invalid handle.";
return(str_GetLastError());
return str_GetLastError();
} }
#endif /* _WIN32 */ #else
typedef void *DLHANDLE;
typedef void *DLFUNC;
inline DLHANDLE DLOPEN(const char *filename)
{
return dlopen(filename, RTLD_NOW);
}
inline DLFUNC DLSYM(DLHANDLE handle, const char *string)
{
return dlsym(handle, string);
}
// dlclose crashes if handle is null.
inline int DLCLOSE(DLHANDLE handle)
{
if (!handle)
{
dlclose_handle_invalid = mTRUE;
return 1;
}
dlclose_handle_invalid = mFALSE;
return dlclose(handle);
}
inline const char *DLERROR()
{
if (dlclose_handle_invalid)
return "Invalid handle.";
return dlerror();
}
#endif
const char *DLFNAME(void *memptr); const char *DLFNAME(void *memptr);
mBOOL IS_VALID_PTR(void *memptr); mBOOL IS_VALID_PTR(void *memptr);
// Attempt to call the given function pointer, without segfaulting. // Attempt to call the given function pointer, without segfaulting.
mBOOL os_safe_call(REG_CMD_FN pfn); mBOOL os_safe_call(REG_CMD_FN pfn);
// Windows doesn't have an strtok_r() routine, so we write our own. // Windows doesn't have an strtok_r() routine, so we write our own.
#ifdef _WIN32 #ifdef _WIN32
#define strtok_r(s, delim, ptrptr) my_strtok_r(s, delim, ptrptr) #define strtok_r(s, delim, ptrptr) my_strtok_r(s, delim, ptrptr)
char *my_strtok_r(char *s, const char *delim, char **ptrptr); char *my_strtok_r(char *s, const char *delim, char **ptrptr);
#endif /* _WIN32 */ #else
// Linux doesn't have an strlwr() routine, so we write our own.
#define strlwr(s) my_strlwr(s)
char *my_strlwr(char *s);
#endif // _WIN32
// Set filename and pathname maximum lengths. Note some windows compilers // Set filename and pathname maximum lengths. Note some windows compilers
@ -204,8 +118,7 @@ mBOOL os_safe_call(REG_CMD_FN pfn);
#include <stdlib.h> #include <stdlib.h>
#define NAME_MAX _MAX_FNAME #define NAME_MAX _MAX_FNAME
#define PATH_MAX _MAX_PATH #define PATH_MAX _MAX_PATH
#endif /* _WIN32 */ #endif // _WIN32
// Various other windows routine differences. // Various other windows routine differences.
#if defined(__linux) || defined(__APPLE__) #if defined(__linux) || defined(__APPLE__)
@ -222,7 +135,7 @@ mBOOL os_safe_call(REG_CMD_FN pfn);
#define read _read #define read _read
#define write _write #define write _write
#define close _close #define close _close
#endif /* _WIN32 */ #endif // _WIN32
#ifdef __GNUC__ #ifdef __GNUC__
#include <unistd.h> // _getcwd #include <unistd.h> // _getcwd
@ -252,8 +165,7 @@ mBOOL os_safe_call(REG_CMD_FN pfn);
#ifndef S_IWGRP #ifndef S_IWGRP
#define S_IWGRP S_IWUSR #define S_IWGRP S_IWUSR
#endif #endif
#endif /* _WIN32 */ #endif // _WIN32
// Our handler for new(). // Our handler for new().
// //
@ -276,77 +188,83 @@ mBOOL os_safe_call(REG_CMD_FN pfn);
// "real" function and uses the "old" semantic; handler-type is: // "real" function and uses the "old" semantic; handler-type is:
// int newhandler(size_t) // int newhandler(size_t)
// //
#if defined(__GNUC__) || (defined(_MSC_VER) && (_MSC_VER >= 1300)) #if defined(_MSC_VER) && (_MSC_VER >= 1300)
void MM_CDECL meta_new_handler(void); void __cdecl meta_new_handler();
#elif defined(_MSC_VER) #elif defined(_MSC_VER)
int meta_new_handler(size_t size); int meta_new_handler(size_t size);
#endif /* _MSC_VER */ #else
void meta_new_handler();
#endif
// To keep the rest of the sources clean and keep not only OS but also // To keep the rest of the sources clean and keep not only OS but also
// compiler dependant differences in this file, we define a local function // compiler dependant differences in this file, we define a local function
// to set the new handler. // to set the new handler.
void mm_set_new_handler( void ); void mm_set_new_handler( void );
// Thread handling... // Thread handling...
#if defined(__linux) || defined(__APPLE__) #if defined(__linux) || defined(__APPLE__)
#include <pthread.h> #include <pthread.h>
typedef pthread_t THREAD_T; typedef pthread_t THREAD_T;
// returns 0==success, non-zero==failure // returns 0==success, non-zero==failure
inline int THREAD_CREATE(THREAD_T *tid, void (*func)(void)) { inline int THREAD_CREATE(THREAD_T *tid, void (*func)())
{
int ret; int ret;
ret = pthread_create(tid, NULL, (void *(*)(void*)) func, NULL); ret = pthread_create(tid, NULL, (void *(*)(void*)) func, NULL);
if(ret != 0) { if (ret != 0)
{
META_ERROR("Failure starting thread: %s", strerror(ret)); META_ERROR("Failure starting thread: %s", strerror(ret));
return(ret); return ret;
} }
ret = pthread_detach(*tid); ret = pthread_detach(*tid);
if (ret != 0) if (ret != 0)
META_ERROR("Failure detaching thread: %s", strerror(ret)); META_ERROR("Failure detaching thread: %s", strerror(ret));
return(ret); return ret;
} }
#elif defined(_WIN32) #elif defined(_WIN32)
// See: // See:
// http://msdn.microsoft.com/library/en-us/dllproc/prothred_4084.asp // http://msdn.microsoft.com/library/en-us/dllproc/prothred_4084.asp
typedef DWORD THREAD_T; typedef DWORD THREAD_T;
// returns 0==success, non-zero==failure // returns 0==success, non-zero==failure
inline int THREAD_CREATE(THREAD_T *tid, void (*func)(void)) { inline int THREAD_CREATE(THREAD_T *tid, void (*func)())
{
HANDLE ret; HANDLE ret;
// win32 returns NULL==failure, non-NULL==success // win32 returns NULL==failure, non-NULL==success
ret = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) func, NULL, 0, tid); ret = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) func, NULL, 0, tid);
if (ret == NULL) if (ret == NULL)
META_ERROR("Failure starting thread: %s", str_GetLastError()); META_ERROR("Failure starting thread: %s", str_GetLastError());
return(ret==NULL); return ret == NULL;
} }
#endif /* _WIN32 */ #endif // _WIN32
#define THREAD_OK 0 #define THREAD_OK 0
// Mutex handling... // Mutex handling...
#if defined(__linux) || defined(__APPLE__) #if defined(__linux) || defined(__APPLE__)
typedef pthread_mutex_t MUTEX_T; typedef pthread_mutex_t MUTEX_T;
inline int MUTEX_INIT(MUTEX_T *mutex) { inline int MUTEX_INIT(MUTEX_T *mutex)
{
int ret; int ret;
ret = pthread_mutex_init(mutex, NULL); ret = pthread_mutex_init(mutex, NULL);
if (ret != THREAD_OK) if (ret != THREAD_OK)
META_ERROR("mutex_init failed: %s", strerror(ret)); META_ERROR("mutex_init failed: %s", strerror(ret));
return(ret); return ret;
} }
inline int MUTEX_LOCK(MUTEX_T *mutex) { inline int MUTEX_LOCK(MUTEX_T *mutex)
{
int ret; int ret;
ret = pthread_mutex_lock(mutex); ret = pthread_mutex_lock(mutex);
if (ret != THREAD_OK) if (ret != THREAD_OK)
META_ERROR("mutex_lock failed: %s", strerror(ret)); META_ERROR("mutex_lock failed: %s", strerror(ret));
return(ret); return ret;
} }
inline int MUTEX_UNLOCK(MUTEX_T *mutex) { inline int MUTEX_UNLOCK(MUTEX_T *mutex)
{
int ret; int ret;
ret = pthread_mutex_unlock(mutex); ret = pthread_mutex_unlock(mutex);
if (ret != THREAD_OK) if (ret != THREAD_OK)
META_ERROR("mutex_unlock failed: %s", strerror(ret)); META_ERROR("mutex_unlock failed: %s", strerror(ret));
return(ret); return ret;
} }
#elif defined(_WIN32) #elif defined(_WIN32)
// Win32 has "mutexes" as well, but CS's are simpler. // Win32 has "mutexes" as well, but CS's are simpler.
@ -354,44 +272,50 @@ void mm_set_new_handler( void );
// http://msdn.microsoft.com/library/en-us/dllproc/synchro_2a2b.asp // http://msdn.microsoft.com/library/en-us/dllproc/synchro_2a2b.asp
typedef CRITICAL_SECTION MUTEX_T; typedef CRITICAL_SECTION MUTEX_T;
// Note win32 routines don't return any error (return void). // Note win32 routines don't return any error (return void).
inline int MUTEX_INIT(MUTEX_T *mutex) { inline int MUTEX_INIT(MUTEX_T *mutex)
{
InitializeCriticalSection(mutex); InitializeCriticalSection(mutex);
return(THREAD_OK); return THREAD_OK;
} }
inline int MUTEX_LOCK(MUTEX_T *mutex) { inline int MUTEX_LOCK(MUTEX_T *mutex)
{
EnterCriticalSection(mutex); EnterCriticalSection(mutex);
return(THREAD_OK); return THREAD_OK;
} }
inline int MUTEX_UNLOCK(MUTEX_T *mutex) { inline int MUTEX_UNLOCK(MUTEX_T *mutex)
{
LeaveCriticalSection(mutex); LeaveCriticalSection(mutex);
return(THREAD_OK); return THREAD_OK;
} }
#endif /* _WIN32 (mutex) */ #endif // _WIN32
// Condition variables... // Condition variables...
#if defined(__linux) || defined(__APPLE__) #if defined(__linux) || defined(__APPLE__)
typedef pthread_cond_t COND_T; typedef pthread_cond_t COND_T;
inline int COND_INIT(COND_T *cond) { inline int COND_INIT(COND_T *cond)
{
int ret; int ret;
ret = pthread_cond_init(cond, NULL); ret = pthread_cond_init(cond, NULL);
if (ret != THREAD_OK) if (ret != THREAD_OK)
META_ERROR("cond_init failed: %s", strerror(ret)); META_ERROR("cond_init failed: %s", strerror(ret));
return(ret); return ret;
} }
inline int COND_WAIT(COND_T *cond, MUTEX_T *mutex) { inline int COND_WAIT(COND_T *cond, MUTEX_T *mutex)
{
int ret; int ret;
ret = pthread_cond_wait(cond, mutex); ret = pthread_cond_wait(cond, mutex);
if (ret != THREAD_OK) if (ret != THREAD_OK)
META_ERROR("cond_wait failed: %s", strerror(ret)); META_ERROR("cond_wait failed: %s", strerror(ret));
return(ret); return ret;
} }
inline int COND_SIGNAL(COND_T *cond) { inline int COND_SIGNAL(COND_T *cond)
{
int ret; int ret;
ret = pthread_cond_signal(cond); ret = pthread_cond_signal(cond);
if (ret != THREAD_OK) if (ret != THREAD_OK)
META_ERROR("cond_signal failed: %s", strerror(ret)); META_ERROR("cond_signal failed: %s", strerror(ret));
return(ret); return ret;
} }
#elif defined(_WIN32) #elif defined(_WIN32)
// Since win32 doesn't provide condition-variables, we have to model // Since win32 doesn't provide condition-variables, we have to model
@ -408,20 +332,23 @@ void mm_set_new_handler( void );
// See also: // See also:
// http://msdn.microsoft.com/library/en-us/dllproc/synchro_8ann.asp // http://msdn.microsoft.com/library/en-us/dllproc/synchro_8ann.asp
typedef HANDLE COND_T; typedef HANDLE COND_T;
inline int COND_INIT(COND_T *cond) { inline int COND_INIT(COND_T *cond)
{
*cond = CreateEvent(NULL, // security attributes (none) *cond = CreateEvent(NULL, // security attributes (none)
FALSE, // manual-reset type (false==auto-reset) FALSE, // manual-reset type (false==auto-reset)
FALSE, // initial state (unsignaled) FALSE, // initial state (unsignaled)
NULL); // object name (unnamed) NULL); // object name (unnamed)
// returns NULL on error // returns NULL on error
if(*cond==NULL) { if (*cond == NULL)
{
META_ERROR("cond_init failed: %s", str_GetLastError()); META_ERROR("cond_init failed: %s", str_GetLastError());
return(-1); return -1;
} }
else else
return(0); return 0;
} }
inline int COND_WAIT(COND_T *cond, MUTEX_T *mutex) { inline int COND_WAIT(COND_T *cond, MUTEX_T *mutex)
{
DWORD ret; DWORD ret;
LeaveCriticalSection(mutex); LeaveCriticalSection(mutex);
ret = WaitForSingleObject(*cond, INFINITE); ret = WaitForSingleObject(*cond, INFINITE);
@ -429,24 +356,27 @@ void mm_set_new_handler( void );
// returns WAIT_OBJECT_0 if object was signaled; other return // returns WAIT_OBJECT_0 if object was signaled; other return
// values indicate errors. // values indicate errors.
if (ret == WAIT_OBJECT_0) if (ret == WAIT_OBJECT_0)
return(0); return 0;
else { else
{
META_ERROR("cond_wait failed: %s", str_GetLastError()); META_ERROR("cond_wait failed: %s", str_GetLastError());
return(-1); return -1;
} }
} }
inline int COND_SIGNAL(COND_T *cond) { inline int COND_SIGNAL(COND_T *cond)
{
BOOL ret; BOOL ret;
ret = SetEvent(*cond); ret = SetEvent(*cond);
// returns zero on failure // returns zero on failure
if(ret==0) { if (ret == 0)
{
META_ERROR("cond_signal failed: %s", str_GetLastError()); META_ERROR("cond_signal failed: %s", str_GetLastError());
return(-1); return -1;
} }
else else
return(0); return 0;
} }
#endif /* _WIN32 (condition variable) */ #endif // _WIN32
// Normalize/standardize a pathname. // Normalize/standardize a pathname.
// - For win32, this involves: // - For win32, this involves:
@ -459,17 +389,20 @@ void mm_set_new_handler( void );
#if defined(__linux) || defined(__APPLE__) #if defined(__linux) || defined(__APPLE__)
#define normalize_pathname(a) #define normalize_pathname(a)
#elif defined(_WIN32) #elif defined(_WIN32)
inline void normalize_pathname(char *path) { inline void normalize_pathname(char *path)
{
char *cp; char *cp;
META_DEBUG(8, ("normalize: %s", path)); META_DEBUG(8, ("normalize: %s", path));
for(cp=path; *cp; cp++) { for (cp = path; *cp; cp++)
{
if (isupper(*cp)) *cp = tolower(*cp); if (isupper(*cp)) *cp = tolower(*cp);
if (*cp == '\\') *cp = '/'; if (*cp == '\\') *cp = '/';
} }
META_DEBUG(8, ("normalized: %s", path)); META_DEBUG(8, ("normalized: %s", path));
} }
#endif /* _WIN32 */ #endif // _WIN32
// Indicate if pathname appears to be an absolute-path. Under linux this // Indicate if pathname appears to be an absolute-path. Under linux this
// is a leading slash (/). Under win32, this can be: // is a leading slash (/). Under win32, this can be:
@ -477,51 +410,55 @@ inline void normalize_pathname(char *path) {
// - a toplevel path (ie "\blah") // - a toplevel path (ie "\blah")
// - a UNC network address (ie "\\srv1\blah"). // - a UNC network address (ie "\\srv1\blah").
// Also, handle both native and normalized pathnames. // Also, handle both native and normalized pathnames.
inline int is_absolute_path(const char *path) { inline int is_absolute_path(const char *path)
if(path[0]=='/') return(TRUE); {
if (path[0] == '/') return TRUE;
#ifdef _WIN32 #ifdef _WIN32
if(path[1]==':') return(TRUE); if (path[1] == ':') return TRUE;
if(path[0]=='\\') return(TRUE); if (path[0] == '\\') return TRUE;
#endif /* _WIN32 */ #endif // _WIN32
return(FALSE); return FALSE;
} }
#ifdef _WIN32 #ifdef _WIN32
// Buffer pointed to by resolved_name is assumed to be able to store a // Buffer pointed to by resolved_name is assumed to be able to store a
// string of PATH_MAX length. // string of PATH_MAX length.
inline char *realpath(const char *file_name, char *resolved_name) { inline char *realpath(const char *file_name, char *resolved_name)
{
int ret; int ret;
ret = GetFullPathName(file_name, PATH_MAX, resolved_name, NULL); ret = GetFullPathName(file_name, PATH_MAX, resolved_name, NULL);
if(ret > PATH_MAX) { if (ret > PATH_MAX)
{
errno = ENAMETOOLONG; errno = ENAMETOOLONG;
return(NULL); return NULL;
} }
else if(ret > 0) { else if (ret > 0)
{
HANDLE handle; HANDLE handle;
WIN32_FIND_DATA find_data; WIN32_FIND_DATA find_data;
handle = FindFirstFile(resolved_name, &find_data); handle = FindFirstFile(resolved_name, &find_data);
if(INVALID_HANDLE_VALUE == handle) { if (INVALID_HANDLE_VALUE == handle)
{
errno = ENOENT; errno = ENOENT;
return NULL; return NULL;
} }
FindClose(handle); FindClose(handle);
normalize_pathname(resolved_name); normalize_pathname(resolved_name);
return(resolved_name); return resolved_name;
} }
else
return(NULL); return NULL;
} }
#endif /* _WIN32 */ #endif // _WIN32
// Generic "error string" from a recent OS call. For linux, this is based // Generic "error string" from a recent OS call. For linux, this is based
// on errno. For win32, it's based on GetLastError. // on errno. For win32, it's based on GetLastError.
inline const char *str_os_error(void) { inline const char *str_os_error()
#if defined(__linux) || defined(__APPLE__) {
return(strerror(errno)); #ifdef _WIN32
#elif defined(_WIN32) return str_GetLastError();
return(str_GetLastError()); #else
#endif /* _WIN32 */ return strerror(errno);
#endif
} }
#endif /* OSDEP_H */

View File

@ -1,68 +1,35 @@
// vi: set ts=4 sw=4 : #pragma once
// vim: set tw=75 :
// plinfo.h - typedefs for plugin info structure
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef PLINFO_H
#define PLINFO_H
// Flags for plugin to indicate when it can be be loaded/unloaded. // Flags for plugin to indicate when it can be be loaded/unloaded.
// NOTE: order is crucial, as greater/less comparisons are made. // NOTE: order is crucial, as greater/less comparisons are made.
typedef enum { enum PLUG_LOADTIME
{
PT_NEVER = 0, PT_NEVER = 0,
PT_STARTUP, // should only be loaded/unloaded at initial hlds execution PT_STARTUP, // should only be loaded/unloaded at initial hlds execution
PT_CHANGELEVEL, // can be loaded/unloaded between maps PT_CHANGELEVEL, // can be loaded/unloaded between maps
PT_ANYTIME, // can be loaded/unloaded at any time PT_ANYTIME, // can be loaded/unloaded at any time
PT_ANYPAUSE, // can be loaded/unloaded at any time, and can be "paused" during a map PT_ANYPAUSE, // can be loaded/unloaded at any time, and can be "paused" during a map
} PLUG_LOADTIME; };
// Flags to indicate why the plugin is being unloaded. // Flags to indicate why the plugin is being unloaded.
typedef enum { enum PL_UNLOAD_REASON
{
PNL_NULL = 0, PNL_NULL = 0,
PNL_INI_DELETED, // was deleted from plugins.ini PNL_INI_DELETED, // was deleted from plugins.ini
PNL_FILE_NEWER, // file on disk is newer than last load PNL_FILE_NEWER, // file on disk is newer than last load
PNL_COMMAND, // requested by server/console command PNL_COMMAND, // requested by server/console command
PNL_CMD_FORCED, // forced by server/console command PNL_CMD_FORCED, // forced by server/console command
PNL_DELAYED, // delayed from previous request; can't tell origin PNL_DELAYED, // delayed from previous request; can't tell origin
// only used for 'real_reason' on MPlugin::unload() // only used for 'real_reason' on MPlugin::unload()
PNL_PLUGIN, // requested by plugin function call PNL_PLUGIN, // requested by plugin function call
PNL_PLG_FORCED, // forced by plugin function call PNL_PLG_FORCED, // forced by plugin function call
PNL_RELOAD, // forced unload by reload() PNL_RELOAD, // forced unload by reload()
} PL_UNLOAD_REASON; };
// Information plugin provides about itself. // Information plugin provides about itself.
typedef struct { struct plugin_info_t
{
const char *ifvers; // meta_interface version const char *ifvers; // meta_interface version
const char *name; // full name of plugin const char *name; // full name of plugin
const char *version; // version const char *version; // version
@ -72,11 +39,10 @@ typedef struct {
const char *logtag; // log message prefix (unused right now) const char *logtag; // log message prefix (unused right now)
PLUG_LOADTIME loadable; // when loadable PLUG_LOADTIME loadable; // when loadable
PLUG_LOADTIME unloadable; // when unloadable PLUG_LOADTIME unloadable; // when unloadable
} plugin_info_t; };
extern plugin_info_t Plugin_info; extern plugin_info_t Plugin_info;
// Plugin identifier, passed to all Meta Utility Functions. // Plugin identifier, passed to all Meta Utility Functions.
typedef plugin_info_t *plid_t; typedef plugin_info_t *plid_t;
#define PLID &Plugin_info #define PLID &Plugin_info
#endif /* PLINFO_H */

View File

@ -1,14 +1,14 @@
#pragma once #pragma once
#include "version/appversion.h"
#if defined(linux) || defined(__APPLE__) #if defined(linux) || defined(__APPLE__)
// enable extra routines in system header files, like dladdr // enable extra routines in system header files, like dladdr
#ifndef _GNU_SOURCE #ifndef _GNU_SOURCE
#define _GNU_SOURCE #define _GNU_SOURCE
#endif #endif
#include <dlfcn.h> // dlopen, dladdr, etc
#include <signal.h> // sigaction, etc #include <signal.h> // sigaction, etc
#include <setjmp.h> // sigsetjmp, longjmp, etc #endif
#endif /* linux */
#if defined(_MSC_VER) && (_MSC_VER < 1300) #if defined(_MSC_VER) && (_MSC_VER < 1300)
#include <new.h> // set_new_handler() #include <new.h> // set_new_handler()
@ -16,17 +16,6 @@
#include <new> // set_new_handler() #include <new> // set_new_handler()
#endif #endif
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <extdll.h> #include <extdll.h>
#include <studio.h> #include <studio.h>
#include <studioapi.h> #include <studioapi.h>
@ -36,9 +25,6 @@
#include "commands_meta.h" #include "commands_meta.h"
#include "metamod.h" #include "metamod.h"
#include "log_meta.h" #include "log_meta.h"
#include "info_name.h"
#include "vdate.h"
#include "vers_meta.h"
#include "conf_meta.h" #include "conf_meta.h"
#include "support_meta.h" #include "support_meta.h"
#include "dllapi.h" #include "dllapi.h"

View File

@ -1,49 +1,5 @@
// vi: set ts=4 sw=4 :
// vim: set tw=75 :
// reg_support.cpp - support for things "registered" by plugins (console
// cmds, cvars, msgs, etc)
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#include "precompiled.h" #include "precompiled.h"
#ifdef linux
// enable extra routines in system header files, like strsignal
# ifndef _GNU_SOURCE
# define _GNU_SOURCE
# endif
#endif /* linux */
// "Register" support. // "Register" support.
// //
// This code is necessary to support the different "register" engine // This code is necessary to support the different "register" engine
@ -86,30 +42,31 @@
// Windows didn't seem to have a similar routine, and I couldn't find // Windows didn't seem to have a similar routine, and I couldn't find
// another way to get the information.. // another way to get the information..
// Generic command handler, passed to the engine for any AddServerCommand // Generic command handler, passed to the engine for any AddServerCommand
// calls made by the plugin. It finds the appropriate plugin function // calls made by the plugin. It finds the appropriate plugin function
// pointer to call based on CMD_ARGV(0). // pointer to call based on CMD_ARGV(0).
void meta_command_handler(void) void meta_command_handler()
{ {
MRegCmd* icmd;
const char* cmd;
META_DEBUG(5, ("called: meta_command_handler; arg0=%s args='%s'", CMD_ARGV(0), CMD_ARGS())); META_DEBUG(5, ("called: meta_command_handler; arg0=%s args='%s'", CMD_ARGV(0), CMD_ARGS()));
cmd = CMD_ARGV(0); const char *cmd = CMD_ARGV(0);
if (!cmd) { if (!cmd)
{
META_ERROR("Null command name in meta_command_handler() ??"); META_ERROR("Null command name in meta_command_handler() ??");
return; return;
} }
icmd = g_regCmds->find(cmd); MRegCmd *icmd = g_regCmds->find(cmd);
if (!icmd) { if (!icmd)
{
META_ERROR("Couldn't find registered plugin command: %s", cmd); META_ERROR("Couldn't find registered plugin command: %s", cmd);
return; return;
} }
if (icmd->call() != mTRUE) if (icmd->call() != mTRUE)
{
META_CONS("[metamod: command '%s' unavailable; plugin unloaded]", cmd); META_CONS("[metamod: command '%s' unavailable; plugin unloaded]", cmd);
} }
}
// Replacement for engine routine AddServerCommand; called by plugins. // Replacement for engine routine AddServerCommand; called by plugins.
@ -118,10 +75,10 @@ void meta_command_handler(void)
// engine a command string and function pointer allocated locally (in the // engine a command string and function pointer allocated locally (in the
// metamod DLL). // metamod DLL).
// //
// The string handed to the engine is just a _strdup() of the plugin's // The string handed to the engine is just a Q_strdup() of the plugin's
// string. The function pointer handed to the engine is actually a pointer // string. The function pointer handed to the engine is actually a pointer
// to a generic command-handler function (see above). // to a generic command-handler function (see above).
void meta_AddServerCommand(char* cmd_name, void (*function)(void)) void meta_AddServerCommand(char *cmd_name, void (*function)())
{ {
MPlugin *iplug = NULL; MPlugin *iplug = NULL;
MRegCmd *icmd = NULL; MRegCmd *icmd = NULL;
@ -129,7 +86,8 @@ void meta_AddServerCommand(char* cmd_name, void (*function)(void))
META_DEBUG(4, ("called: meta_AddServerCommand; cmd_name=%s, function=%d", cmd_name, function)); META_DEBUG(4, ("called: meta_AddServerCommand; cmd_name=%s, function=%d", cmd_name, function));
// try to find which plugin is registering this command // try to find which plugin is registering this command
if (!(iplug = g_plugins->find_memloc((void *)function))) { if (!(iplug = g_plugins->find_memloc((void *)function)))
{
// if this isn't supported on this OS, don't log an error // if this isn't supported on this OS, don't log an error
if (meta_errno != ME_OSNOTSUP) if (meta_errno != ME_OSNOTSUP)
META_ERROR("Failed to find memloc for regcmd '%s'", cmd_name); META_ERROR("Failed to find memloc for regcmd '%s'", cmd_name);
@ -137,13 +95,16 @@ void meta_AddServerCommand(char* cmd_name, void (*function)(void))
// See if this command was previously registered, ie a "reloaded" plugin. // See if this command was previously registered, ie a "reloaded" plugin.
icmd = g_regCmds->find(cmd_name); icmd = g_regCmds->find(cmd_name);
if (!icmd) { if (!icmd)
{
// If not found, add. // If not found, add.
icmd = g_regCmds->add(cmd_name); icmd = g_regCmds->add(cmd_name);
if (!icmd) { if (!icmd)
{
// error details logged in add() // error details logged in add()
return; return;
} }
// Only register if not previously registered.. // Only register if not previously registered..
REG_SVR_COMMAND(icmd->name, meta_command_handler); REG_SVR_COMMAND(icmd->name, meta_command_handler);
} }
@ -165,7 +126,7 @@ void meta_AddServerCommand(char* cmd_name, void (*function)(void))
// locally (in the metamod DLL). // locally (in the metamod DLL).
// //
// The cvar handed to the engine is globally allocated in the metamod.dll; // The cvar handed to the engine is globally allocated in the metamod.dll;
// the "name" and "string" fields are _strdup()'s of the plugin's strings. // the "name" and "string" fields are Q_strdup()'s of the plugin's strings.
// Note that, once this is done, the cvar_t allocated in the plugin is no // Note that, once this is done, the cvar_t allocated in the plugin is no
// longer used for _anything_. As long as everything sets/gets the cvar // longer used for _anything_. As long as everything sets/gets the cvar
// values via the engine functions, this will work fine. If the plugin // values via the engine functions, this will work fine. If the plugin
@ -173,39 +134,43 @@ void meta_AddServerCommand(char* cmd_name, void (*function)(void))
// it will fail to work properly. // it will fail to work properly.
void meta_CVarRegister(cvar_t *pCvar) void meta_CVarRegister(cvar_t *pCvar)
{ {
MPlugin* iplug = NULL; MPlugin *iplug = nullptr;
MRegCvar* icvar = NULL; MRegCvar *icvar = nullptr;
META_DEBUG(4, ("called: meta_CVarRegister; name=%s", pCvar->name)); META_DEBUG(4, ("called: meta_CVarRegister; name=%s", pCvar->name));
// try to find which plugin is registering this cvar // try to find which plugin is registering this cvar
if (!(iplug = g_plugins->find_memloc((void *)pCvar))) { if (!(iplug = g_plugins->find_memloc((void *)pCvar)))
{
// if this isn't supported on this OS, don't log an error // if this isn't supported on this OS, don't log an error
if (meta_errno != ME_OSNOTSUP) if (meta_errno != ME_OSNOTSUP)
// Note: if cvar_t was malloc'd by the plugin, we can't // Note: if cvar_t was malloc'd by the plugin, we can't
// determine the calling plugin. Thus, this becomes a Debug // determine the calling plugin. Thus, this becomes a Debug
// rather than Error message. // rather than Error message.
META_DEBUG(1, ("Failed to find memloc for regcvar '%s'", META_DEBUG(1, ("Failed to find memloc for regcvar '%s'", pCvar->name));
pCvar->name));
} }
// See if this cvar was previously registered, ie a "reloaded" plugin. // See if this cvar was previously registered, ie a "reloaded" plugin.
icvar = g_regCvars->find(pCvar->name); icvar = g_regCvars->find(pCvar->name);
if (!icvar) { if (!icvar)
{
// If not found, add. // If not found, add.
icvar = g_regCvars->add(pCvar->name); icvar = g_regCvars->add(pCvar->name);
if (!icvar) { if (!icvar)
{
// error details logged in add() // error details logged in add()
return; return;
} }
// Reset to given value // Reset to given value
icvar->set(pCvar); icvar->set(pCvar);
CVAR_REGISTER(icvar->data); CVAR_REGISTER(icvar->data);
} }
// Note: if not a new cvar, then we don't set the values, and just keep // Note: if not a new cvar, then we don't set the values, and just keep
// the pre-existing value. // the pre-existing value.
icvar->status = RG_VALID; icvar->status = RG_VALID;
// Store which plugin this is for, if we know. Use '0' for unknown // Store which plugin this is for, if we know. Use '0' for unknown
// plugin, as plugin index starts at 1. // plugin, as plugin index starts at 1.
if (iplug) if (iplug)
@ -214,7 +179,6 @@ void meta_CVarRegister(cvar_t* pCvar)
icvar->plugid = 0; icvar->plugid = 0;
} }
// Replacement for engine routine RegUserMsg; called by plugins. Rather // Replacement for engine routine RegUserMsg; called by plugins. Rather
// than handing the engine the plugin's string (which is allocated in the // than handing the engine the plugin's string (which is allocated in the
// plugin DLL), this hands the engine a string allocated from the stack. // plugin DLL), this hands the engine a string allocated from the stack.
@ -230,18 +194,13 @@ void meta_CVarRegister(cvar_t* pCvar)
int meta_RegUserMsg(const char *pszName, int iSize) int meta_RegUserMsg(const char *pszName, int iSize)
{ {
char* cp; char *cp = Q_strdup(pszName);
return REG_USER_MSG(cp, iSize);
cp = _strdup(pszName);
return (REG_USER_MSG(cp, iSize));
} }
// Intercept and record queries // Intercept and record queries
void meta_QueryClientCvarValue(const edict_t *player, const char *cvarName) void meta_QueryClientCvarValue(const edict_t *player, const char *cvarName)
{ {
g_Players.set_player_cvar_query(player, cvarName); g_Players.set_player_cvar_query(player, cvarName);
(*g_engfuncs.pfnQueryClientCvarValue)(player, cvarName); (*g_engfuncs.pfnQueryClientCvarValue)(player, cvarName);
} }

View File

@ -1,48 +1,7 @@
// vi: set ts=4 sw=4 : #pragma once
// vim: set tw=75 :
// reg_support.h - functions for "registered" cmd/cvar/msg support void meta_command_handler();
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef REG_SUPPORT_H
#define REG_SUPPORT_H
#include "mreg.h" // REG_CMD_FN, etc
void meta_command_handler(void);
void meta_AddServerCommand(char *cmd_name, REG_CMD_FN function); void meta_AddServerCommand(char *cmd_name, REG_CMD_FN function);
void meta_CVarRegister(cvar_t *pCvar); void meta_CVarRegister(cvar_t *pCvar);
int meta_RegUserMsg(const char *pszName, int iSize); int meta_RegUserMsg(const char *pszName, int iSize);
void meta_QueryClientCvarValue(const edict_t *player, const char *cvarName); void meta_QueryClientCvarValue(const edict_t *player, const char *cvarName);
#endif /* REG_SUPPORT_H */

View File

@ -1,35 +1,3 @@
// vi: set ts=4 sw=4 :
// vim: set tw=75 :
// sdk_util.cpp - utility routines from HL SDK util.cpp
// Selected portions of dlls/util.cpp from SDK 2.1.
// Functions copied from there as needed...
// And modified to avoid buffer overflows (argh).
// Also modified to remove dependency on CBaseEntity class.
/***
*
* Copyright (c) 1999, 2000 Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
/*
===== util.cpp ========================================================
Utility code. Really not optional after all.
*/
#include "precompiled.h" #include "precompiled.h"
char *UTIL_VarArgs(char *format, ...) char *UTIL_VarArgs(char *format, ...)
@ -38,24 +6,21 @@ char* UTIL_VarArgs(char *format, ...)
static char string[1024]; static char string[1024];
va_start(argptr, format); va_start(argptr, format);
vsnprintf(string, sizeof(string), format, argptr); Q_vsnprintf(string, sizeof(string), format, argptr);
va_end(argptr); va_end(argptr);
return string; return string;
} }
//=========================================================
// UTIL_LogPrintf - Prints a logged message to console. // UTIL_LogPrintf - Prints a logged message to console.
// Preceded by LOG: ( timestamp ) < message > // Preceded by LOG: ( timestamp ) < message >
//=========================================================
void UTIL_LogPrintf(char *fmt, ...) void UTIL_LogPrintf(char *fmt, ...)
{ {
va_list argptr; va_list argptr;
static char string[1024]; static char string[1024];
va_start(argptr, fmt); va_start(argptr, fmt);
vsnprintf(string, sizeof(string), fmt, argptr); Q_vsnprintf(string, sizeof(string), fmt, argptr);
va_end(argptr); va_end(argptr);
// Print to server console // Print to server console

View File

@ -1,59 +1,14 @@
// vi: set ts=4 sw=4 : #pragma once
// vim: set tw=75 :
// sdk_util.h - wrapper & extension of util.h from HL SDK
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
// Wrap util.h from SDK with ifndef/endif, to avoid problems from multiple
// inclusions. Dunno why Valve didn't do that in util.h themselves..
#ifndef SDK_UTIL_H
#define SDK_UTIL_H
// We're not including the DBG_EntOfVars and DBG_AssertFunction routines // We're not including the DBG_EntOfVars and DBG_AssertFunction routines
// mentioned in the SDK util.h, so we're going to unset DEBUG here so that // mentioned in the SDK util.h, so we're going to unset DEBUG here so that
// we don't get "unresolved symbol" errors. // we don't get "unresolved symbol" errors.
#ifdef DEBUG #ifdef DEBUG
#undef DEBUG #undef DEBUG
#endif /* DEBUG */ #endif
// Inlcude local enginecallbacks wrapper *first* so that the g_engfuncs // Inlcude local enginecallbacks wrapper *first* so that the g_engfuncs
// type is correct and the <enginecallback.h> header protection is already // type is correct and the <enginecallback.h> header protection is already
// defined. // defined.
#include "enginecallbacks.h" #include "enginecallbacks.h"
#include <util.h> #include <util.h>
#endif /* SDK_UTIL_H */

View File

@ -1,39 +1,3 @@
// vi: set ts=4 sw=4 :
// vim: set tw=75 :
// studio.cpp - player model blending interfaces
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#include "precompiled.h" #include "precompiled.h"
// Another GET-API routine, another interface version. // Another GET-API routine, another interface version.
@ -72,21 +36,24 @@ C_DLLEXPORT int Server_GetBlendingInterface(int version,
// mismatch?", but this will only show in "developer" (-dev) mode. // mismatch?", but this will only show in "developer" (-dev) mode.
META_DEBUG(6, ("called: Server_GetBlendingInterface; version=%d", version)); META_DEBUG(6, ("called: Server_GetBlendingInterface; version=%d", version));
if(missing) { if (missing)
{
META_DEBUG(6, ("Skipping Server_GetBlendingInterface; was previously found missing")); META_DEBUG(6, ("Skipping Server_GetBlendingInterface; was previously found missing"));
return(0); return 0;
} }
if(!getblend) { if (!getblend)
{
META_DEBUG(6, ("Looking up Server_GetBlendingInterface")); META_DEBUG(6, ("Looking up Server_GetBlendingInterface"));
getblend = (GETBLENDAPI_FN) DLSYM(GameDLL.handle, getblend = (GETBLENDAPI_FN) DLSYM(GameDLL.handle,
"Server_GetBlendingInterface"); "Server_GetBlendingInterface");
} }
if(!getblend) { if (!getblend)
{
META_DEBUG(6, ("Couldn't find Server_GetBlendingInterface in game DLL '%s': %s", GameDLL.name, DLERROR())); META_DEBUG(6, ("Couldn't find Server_GetBlendingInterface in game DLL '%s': %s", GameDLL.name, DLERROR()));
missing = 1; missing = 1;
return(0); return 0;
} }
META_DEBUG(6, ("Calling Server_GetBlendingInterface")); META_DEBUG(6, ("Calling Server_GetBlendingInterface"));
return((getblend)(version, ppinterface, pstudio, rotationmatrix, return (getblend)(version, ppinterface, pstudio, rotationmatrix, bonetransform);
bonetransform));
} }

View File

@ -1,43 +1,6 @@
// vi: set ts=4 sw=4 : #pragma once
// vim: set tw=75 :
// studio.cpp - player model blending interfaces #include <studio.h>
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef STUDIOAPI_H
#define STUDIOAPI_H
#include <studio.h> // MAXSTUDIOBONES
// Typedef for Server_GetBlendingInterface() from Eric Smith on the hlcoders // Typedef for Server_GetBlendingInterface() from Eric Smith on the hlcoders
// mailing list. // mailing list.
@ -52,5 +15,3 @@ extern int mm_Server_GetBlendingInterface(int version,
struct engine_studio_api_s *pstudio, struct engine_studio_api_s *pstudio,
float (*rotationmatrix)[3][4], float (*rotationmatrix)[3][4],
float (*bonetransform)[MAXSTUDIOBONES][3][4]); float (*bonetransform)[MAXSTUDIOBONES][3][4]);
#endif /* STUDIOAPI_H */

View File

@ -1,47 +1,12 @@
// vi: set ts=4 sw=4 :
// vim: set tw=75 :
// support_meta.cpp - generic support routines
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#include "precompiled.h" #include "precompiled.h"
META_ERRNO meta_errno; META_ERRNO meta_errno;
void do_exit(int exitval) void __declspec(noreturn) do_exit(int exitval)
{ {
sleep(3); //TerminateProcess(GetCurrentProcess(), 1);
exit(exitval); *((int *)NULL) = 0;
while (true);
} }
// Checks for a non-empty file, relative to the gamedir if necessary. // Checks for a non-empty file, relative to the gamedir if necessary.
@ -58,40 +23,44 @@ int valid_gamedir_file(const char* path)
int ret, reg, size; int ret, reg, size;
if (!path) if (!path)
return (FALSE); return FALSE;
if (!strcmp(path, "/dev/null")) if (!Q_strcmp(path, "/dev/null"))
return (TRUE); return TRUE;
if (is_absolute_path(path)) { if (is_absolute_path(path))
strncpy(buf, path, sizeof(buf)); {
Q_strncpy(buf, path, sizeof(buf));
buf[sizeof buf - 1] = '\0'; buf[sizeof buf - 1] = '\0';
} }
else else
snprintf(buf, sizeof(buf), "%s/%s", GameDLL.gamedir, path); snprintf(buf, sizeof(buf), "%s/%s", GameDLL.gamedir, path);
ret = stat(buf, &st); ret = stat(buf, &st);
if (ret != 0) { if (ret != 0)
{
META_DEBUG(5, ("Unable to stat '%s': %s", buf, strerror(errno))); META_DEBUG(5, ("Unable to stat '%s': %s", buf, strerror(errno)));
return (FALSE); return FALSE;
} }
reg = S_ISREG(st.st_mode); reg = S_ISREG(st.st_mode);
if (!reg) { if (!reg)
{
META_DEBUG(5, ("Not a regular file: %s", buf)); META_DEBUG(5, ("Not a regular file: %s", buf));
return (FALSE); return FALSE;
} }
size = st.st_size; size = st.st_size;
if (!size) { if (!size)
{
META_DEBUG(5, ("Empty file: %s", buf)); META_DEBUG(5, ("Empty file: %s", buf));
return (FALSE); return FALSE;
} }
if (ret == 0 && reg && size) if (ret == 0 && reg && size)
return (TRUE); return TRUE;
else else
return (FALSE); return FALSE;
} }
// Turns path into a full path: // Turns path into a full path:
@ -106,19 +75,22 @@ char* full_gamedir_path(const char* path, char* fullpath)
char buf[PATH_MAX ]; char buf[PATH_MAX ];
// Build pathname from filename, plus gamedir if relative path. // Build pathname from filename, plus gamedir if relative path.
if (is_absolute_path(path)) { if (is_absolute_path(path))
strncpy(buf, path, sizeof buf - 1); {
Q_strncpy(buf, path, sizeof buf - 1);
buf[sizeof buf - 1] = '\0'; buf[sizeof buf - 1] = '\0';
} }
else else snprintf(buf, sizeof(buf), "%s/%s", GameDLL.gamedir, path);
snprintf(buf, sizeof(buf), "%s/%s", GameDLL.gamedir, path);
// Remove relative path components, if possible. // Remove relative path components, if possible.
if (!realpath(buf, fullpath)) { if (!realpath(buf, fullpath))
{
META_DEBUG(4, ("Unable to get realpath for '%s': %s", buf, str_os_error())); META_DEBUG(4, ("Unable to get realpath for '%s': %s", buf, str_os_error()));
strncpy(fullpath, path, PATH_MAX - 1); Q_strncpy(fullpath, path, sizeof(fullpath) - 1);
fullpath[PATH_MAX - 1] = '\0'; fullpath[sizeof(fullpath) - 1] = '\0';
} }
// Replace backslashes, etc. // Replace backslashes, etc.
normalize_pathname(fullpath); normalize_pathname(fullpath);
return (fullpath); return fullpath;
} }

View File

@ -1,120 +1,12 @@
// vi: set ts=4 sw=4 : #pragma once
// vim: set tw=75 :
// support_meta.h - generic support macros
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef SUPPORT_META_H
#define SUPPORT_META_H
#include <string.h> // strcpy(), strncat()
#include <sys/types.h> // stat #include <sys/types.h> // stat
#include <sys/stat.h> // stat #include <sys/stat.h> // stat
#include "osdep.h" // _stricmp, S_ISREG, #include "osdep.h" // _stricmp, S_ISREG,
void do_exit(int exitval) ATTRIBUTE(__noreturn__); void __declspec(noreturn) do_exit(int exitval);
// Unlike snprintf(), strncpy() doesn't necessarily null-terminate the
// target. It appears the former function reasonably considers the given
// size to be "max size of target string" (including the null-terminator),
// whereas strncpy() strangely considers the given size to be "total number
// of bytes to copy". Note strncpy() _always_ writes n bytes, whereas
// snprintf() writes a _max_ of n bytes (incl the NULL). If strncpy()
// needs to write extra bytes to reach n, it uses NULLs, so the target
// _can_ be null-terminated, but only if the source string would have fit
// anyway - in which case why not just use strcpy() instead?
//
// Thus, it appears strncpy() is not only unsafe, it's also inefficient,
// and seemingly no better than plain strcpy() anyway.
//
// With this logic, strncpy() doesn't appear to be much of a "str" function
// at all, IMHO.
//
// Strncat works better, although it considers the given size to be "number
// of bytes to append", and doesn't include the null-terminator in that
// count. Thus, we can use it for what we want to do, by setting the
// target to zero-length (NULL in first byte), and copying n-1 bytes
// (leaving room for the null-termiator).
//
// Why does it have to be soo haaard...
// Also note, some kind of wrapper is necessary to group the two
// statements into one, for use in situations like non-braced else
// statements.
// Technique 1: use "do..while":
#if 0
#define STRNCPY(dst, src, size) \
do { strcpy(dst, "\0"); strncat(dst, src, size-1); } while(0)
#endif
// Technique 2: use parens and commas:
#if 0
#define STRNCPY(dst, src, size) \
(strcpy(dst, "\0"), strncat(dst, src, size-1))
#endif
inline int strnmatch(const char *s1, const char *s2, size_t n) {
if(!s1 || !s2)
return(0);
else
return(!strncmp(s1, s2, n));
}
inline int strcasematch(const char *s1, const char *s2) {
if(!s1 || !s2)
return(0);
else
return(!_stricmp(s1, s2));
}
inline int strncasematch(const char *s1, const char *s2, size_t n) {
if(!s1 || !s2)
return(0);
else
return(!_strnicmp(s1, s2, n));
}
inline int old_valid_file(char *path) {
char *cp;
int len, ret;
cp = (char *) LOAD_FILE_FOR_ME(path, &len);
if(cp && len)
ret=1;
else
ret=0;
FREE_FILE(cp);
return(ret);
}
int valid_gamedir_file(const char *path); int valid_gamedir_file(const char *path);
char *full_gamedir_path(const char *path, char *fullpath); char *full_gamedir_path(const char *path, char *fullpath);
@ -124,12 +16,8 @@ char *full_gamedir_path(const char *path, char *fullpath);
// specify strings used for all the debugging/log messages. // specify strings used for all the debugging/log messages.
#define STRINGIZE(name, len) #name+len #define STRINGIZE(name, len) #name+len
// Max description length for plugins.ini and other places. // Max description length for plugins.ini and other places.
#define MAX_DESC_LEN 256 #define MAX_DESC_LEN 256
// For various character string buffers. // For various character string buffers.
#define MAX_STRBUF_LEN 1024 #define MAX_STRBUF_LEN 1024
#endif /* SUPPORT_META_H */

View File

@ -1,51 +1,12 @@
// vi: set ts=4 sw=4 : #pragma once
// vim: set tw=75 :
// types_meta.h - common internal type, etc definitions
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef TYPES_META_H
#define TYPES_META_H
// Our own boolean type, for stricter type matching. // Our own boolean type, for stricter type matching.
typedef enum mBOOL { enum mBOOL { mFALSE = 0, mTRUE, };
mFALSE = 0,
mTRUE,
} mBOOL;
// Like C's errno, for our various functions; describes causes of failure // Like C's errno, for our various functions; describes causes of failure
// or mFALSE returns. // or mFALSE returns.
typedef enum { enum META_ERRNO
{
ME_NOERROR = 0, ME_NOERROR = 0,
ME_FORMAT, // invalid format ME_FORMAT, // invalid format
ME_COMMENT, // ignored comment ME_COMMENT, // ignored comment
@ -70,13 +31,12 @@ typedef enum {
ME_IFVERSION, // incompatible interface version ME_IFVERSION, // incompatible interface version
ME_UNLOAD_UNLOADER, // tried to unload unloader ME_UNLOAD_UNLOADER, // tried to unload unloader
ME_UNLOAD_SELF, // tried to unload self ME_UNLOAD_SELF, // tried to unload self
} META_ERRNO; };
extern META_ERRNO meta_errno; extern META_ERRNO meta_errno;
#define RETURN_ERRNO(retval, errval) \ #define RETURN_ERRNO(retval, errval) \
do { meta_errno=errval; return(retval); } while(0) do { meta_errno = errval; return retval; } while (0)
#define RETURN_LOGERR_ERRNO(errargs, retval, errval) \ #define RETURN_LOGERR_ERRNO(errargs, retval, errval) \
do { META_ERROR errargs ; meta_errno=errval; return(retval); } while(0) do { META_ERROR errargs; meta_errno = errval; return retval; } while (0)
#endif /* TYPES_META_H */

View File

@ -2,20 +2,20 @@
bool is_yes(const char* str) bool is_yes(const char* str)
{ {
return !strcmp(str, "true") || !strcmp(str, "yes") || !strcmp(str, "1"); return !Q_strcmp(str, "true") || !Q_strcmp(str, "yes") || !Q_strcmp(str, "1");
} }
bool is_no(const char* str) bool is_no(const char* str)
{ {
return !strcmp(str, "false") || !strcmp(str, "no") || !strcmp(str, "0"); return !Q_strcmp(str, "false") || !Q_strcmp(str, "no") || !Q_strcmp(str, "0");
} }
char* ENTITY_KEYVALUE(edict_t* entity, char* key) char* ENTITY_KEYVALUE(edict_t* entity, char* key)
{ {
return (INFOKEY_VALUE(GET_INFOKEYBUFFER(entity), key)); return INFOKEY_VALUE(GET_INFOKEYBUFFER(entity), key);
} }
const char* LOCALINFO(char* key) const char* LOCALINFO(char* key)
{ {
return (ENTITY_KEYVALUE(NULL, key)); return ENTITY_KEYVALUE(NULL, key);
} }

View File

@ -1,56 +0,0 @@
// vi: set ts=4 sw=4 :
// vim: set tw=75 :
// vdate.cpp - compile-time version date
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#include "precompiled.h"
// Grab date/time of compile. The Makefile is set up to recompile this
// module before each link, so that this will always indicate the time the
// library was compiled and linked.
// This is in a separate file from vers_*, so it can be generically used by
// multiple projects.
char const *COMPILE_TIME=__DATE__ ", " __TIME__;
#ifndef COMPILE_TZ
# define COMPILE_TZ ""
#endif
char const *COMPILE_TZONE = COMPILE_TZ;
// Include a string for /usr/bin/ident.
char const *vstring="\n$Pg: " VNAME " -- " VVERSION " | " __DATE__ " - " __TIME__ " $\n";

View File

@ -1,44 +0,0 @@
// vi: set ts=4 sw=4 :
// vim: set tw=75 :
// vdate.h - compile-time version date
/*
* Copyright (c) 2001-2003 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef VDATE_H
#define VDATE_H
extern char const *COMPILE_TIME;
extern char const *COMPILE_TZONE;
#endif /* VDATE_H */

View File

@ -1,55 +0,0 @@
// vi: set ts=4 sw=4 :
// vim: set tw=75 :
// vers_meta.h - version info, intended to be common among DLLs distributed
// with metamod.
/*
* Copyright (c) 2001-2013 Will Day <willday@hpgx.net>
*
* This file is part of Metamod.
*
* Metamod is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* Metamod is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Metamod; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game g_engine ("HL
* g_engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL g_engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#ifndef VERS_META_H
#define VERS_META_H
#ifndef OPT_TYPE
# if defined(_MSC_VER) && defined(_DEBUG)
# define OPT_TYPE "msc debugging"
# elif defined(_MSC_VER) && defined(NDEBUG)
# define OPT_TYPE "msc optimized"
# else
# define OPT_TYPE "default"
# endif /* _MSC_VER */
#endif /* not OPT_TYPE */
#define VDATE "2013-09-26"
#define VVERSION "1.21.1-am"
#define RC_VERS_DWORD 1,21,1,0 // Version Windows DLL Resources in res_meta.rc
#endif /* VERS_META_H */