Import of core modularization plan (bug 3599).

This commit is contained in:
David Anderson
2009-05-13 21:55:50 -04:00
parent 850dbd62c6
commit 421b58f68e
41 changed files with 1254 additions and 235 deletions
+212
View File
@@ -0,0 +1,212 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#ifndef _INCLUDE_SOURCEMOD_CELLARRAY_H_
#define _INCLUDE_SOURCEMOD_CELLARRAY_H_
#include <stdlib.h>
#include <string.h>
extern HandleType_t htCellArray;
class CellArray
{
public:
CellArray(size_t blocksize) : m_Data(NULL), m_BlockSize(blocksize), m_AllocSize(0), m_Size(0)
{
}
~CellArray()
{
free(m_Data);
}
size_t size() const
{
return m_Size;
}
cell_t *push()
{
if (!GrowIfNeeded(1))
{
return NULL;
}
cell_t *arr = &m_Data[m_Size * m_BlockSize];
m_Size++;
return arr;
}
cell_t *at(size_t b) const
{
return &m_Data[b * m_BlockSize];
}
size_t blocksize() const
{
return m_BlockSize;
}
void clear()
{
m_Size = 0;
}
bool swap(size_t item1, size_t item2)
{
/* Make sure there is extra space available */
if (!GrowIfNeeded(1))
{
return false;
}
cell_t *pri = at(item1);
cell_t *alt = at(item2);
/* Get our temporary array 1 after the limit */
cell_t *temp = &m_Data[m_Size * m_BlockSize];
memcpy(temp, pri, sizeof(cell_t) * m_BlockSize);
memcpy(pri, alt, sizeof(cell_t) * m_BlockSize);
memcpy(alt, temp, sizeof(cell_t) * m_BlockSize);
return true;
}
void remove(size_t index)
{
/* If we're at the end, take the easy way out */
if (index == m_Size - 1)
{
m_Size--;
return;
}
/* Otherwise, it's time to move stuff! */
size_t remaining_indexes = (m_Size - 1) - index;
cell_t *src = at(index + 1);
cell_t *dest = at(index);
memmove(dest, src, sizeof(cell_t) * m_BlockSize * remaining_indexes);
m_Size--;
}
cell_t *insert_at(size_t index)
{
/* Make sure it'll fit */
if (!GrowIfNeeded(1))
{
return NULL;
}
/* move everything up */
cell_t *src = at(index);
cell_t *dst = at(index + 1);
memmove(dst, src, sizeof(cell_t) * m_BlockSize * (m_Size-index));
m_Size++;
return src;
}
bool resize(size_t count)
{
if (count <= m_Size)
{
m_Size = count;
return true;
}
if (!GrowIfNeeded(count - m_Size))
{
return false;
}
m_Size = count;
return true;
}
CellArray *clone()
{
CellArray *array = new CellArray(m_BlockSize);
array->m_AllocSize = m_AllocSize;
array->m_Size = m_Size;
array->m_Data = (cell_t *)malloc(sizeof(cell_t) * m_BlockSize * m_AllocSize);
memcpy(array->m_Data, m_Data, sizeof(cell_t) * m_BlockSize * m_Size);
return array;
}
cell_t *base()
{
return m_Data;
}
size_t mem_usage()
{
return m_AllocSize * m_BlockSize * sizeof(cell_t);
}
private:
bool GrowIfNeeded(size_t count)
{
/* Shortcut out if we can store this */
if (m_Size + count <= m_AllocSize)
{
return true;
}
/* Set a base allocation size of 8 items */
if (!m_AllocSize)
{
m_AllocSize = 8;
}
/* If it's not enough, keep doubling */
while (m_Size + count > m_AllocSize)
{
m_AllocSize *= 2;
}
/* finally, allocate the new block */
if (m_Data)
{
m_Data = (cell_t *)realloc(m_Data, sizeof(cell_t) * m_BlockSize * m_AllocSize);
} else {
m_Data = (cell_t *)malloc(sizeof(cell_t) * m_BlockSize * m_AllocSize);
}
return (m_Data != NULL);
}
private:
cell_t *m_Data;
size_t m_BlockSize;
size_t m_AllocSize;
size_t m_Size;
};
#endif /* _INCLUDE_SOURCEMOD_CELLARRAY_H_ */
+89
View File
@@ -0,0 +1,89 @@
# (C)2004-2008 SourceMod Development Team
# Makefile written by David "BAILOPAN" Anderson
SMSDK = ../..
MMSOURCE17 = ../../../mmsource-1.7
#####################################
### EDIT BELOW FOR OTHER PROJECTS ###
#####################################
BINARY = sourcemod.logic.so
OBJECTS = \
common_logic.cpp \
smn_adt_array.cpp \
smn_sorting.cpp \
smn_maplists.cpp \
smn_adt_stack.cpp \
thread/ThreadWorker.cpp \
thread/BaseWorker.cpp \
thread/PosixThreads.cpp \
ThreadSupport.cpp \
smn_float.cpp \
TextParsers.cpp \
smn_textparse.cpp
##############################################
### CONFIGURE ANY OTHER FLAGS/OPTIONS HERE ###
##############################################
C_OPT_FLAGS = -DNDEBUG -O3 -funroll-loops -pipe -fno-strict-aliasing
C_DEBUG_FLAGS = -D_DEBUG -DDEBUG -g -ggdb3
C_GCC4_FLAGS = -fvisibility=hidden
CPP_GCC4_FLAGS = -fvisibility-inlines-hidden
CPP = gcc
LINK += -lpthread -static-libgcc
INCLUDE += -I. -I$(MMSOURCE17)/core/sourcehook -I$(SMSDK)/public -I$(SMSDK)/public/sourcepawn
CFLAGS += -D_LINUX -Dstricmp=strcasecmp -D_stricmp=strcasecmp -D_strnicmp=strncasecmp -Dstrnicmp=strncasecmp \
-D_snprintf=snprintf -D_vsnprintf=vsnprintf -D_alloca=alloca -Dstrcmpi=strcasecmp -Wall -Werror \
-Wno-uninitialized -mfpmath=sse -msse -DSOURCEMOD_BUILD -DHAVE_STDINT_H -DSM_DEFAULT_THREADER -m32 \
-DSM_LOGIC
CPPFLAGS += -Wno-non-virtual-dtor -fno-exceptions -fno-rtti
################################################
### DO NOT EDIT BELOW HERE FOR MOST PROJECTS ###
################################################
ifeq "$(DEBUG)" "true"
BIN_DIR = Debug
CFLAGS += $(C_DEBUG_FLAGS)
else
BIN_DIR = Release
CFLAGS += $(C_OPT_FLAGS)
endif
GCC_VERSION := $(shell $(CPP) -dumpversion >&1 | cut -b1)
ifeq "$(GCC_VERSION)" "4"
CFLAGS += $(C_GCC4_FLAGS)
CPPFLAGS += $(CPP_GCC4_FLAGS)
endif
OBJ_LINUX := $(OBJECTS:%.cpp=$(BIN_DIR)/%.o)
OBJ_LINUX := $(OBJ_LINUX:%.c=$(BIN_DIR)/%.o)
$(BIN_DIR)/%.o: %.cpp
$(CPP) $(INCLUDE) $(CFLAGS) $(CPPFLAGS) -o $@ -c $<
$(BIN_DIR)/%.o: %.c
$(CPP) $(INCLUDE) $(CFLAGS) -o $@ -c $<
all:
mkdir -p $(BIN_DIR)/thread
$(MAKE) -f Makefile sourcemod
sourcemod: $(OBJ_LINUX)
$(CPP) $(INCLUDE) $(OBJ_LINUX) $(LINK) -m32 -shared -ldl -lm -o $(BIN_DIR)/$(BINARY)
debug:
$(MAKE) -f Makefile all DEBUG=true
default: all
clean:
rm -rf $(BIN_DIR)/*.o
rm -rf $(BIN_DIR)/thread/*.o
rm -rf $(BIN_DIR)/$(BINARY)
File diff suppressed because it is too large Load Diff
+95
View File
@@ -0,0 +1,95 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#ifndef _INCLUDE_SOURCEMOD_TEXTPARSERS_H_
#define _INCLUDE_SOURCEMOD_TEXTPARSERS_H_
#include <ITextParsers.h>
#include "common_logic.h"
using namespace SourceMod;
/**
* @param void * IN: Stream pointer
* @param char * IN/OUT: Stream buffer
* @param size_t IN: Maximum size of buffer
* @param unsigned int * OUT: Number of bytes read (0 = end of stream)
* @return True on success, false on failure
*/
typedef bool (*STREAMREADER)(void *, char *, size_t, unsigned int *);
class TextParsers :
public ITextParsers,
public SMGlobalClass
{
public:
TextParsers();
public: //SMGlobalClass
void OnSourceModAllInitialized();
public:
bool ParseFile_INI(const char *file,
ITextListener_INI *ini_listener,
unsigned int *line,
unsigned int *col);
SMCError ParseFile_SMC(const char *file,
ITextListener_SMC *smc_listener,
SMCStates *states);
SMCError ParseSMCFile(const char *file,
ITextListener_SMC *smc_listener,
SMCStates *states,
char *buffer,
size_t maxsize);
SMCError ParseSMCStream(const char *stream,
size_t length,
ITextListener_SMC *smc_listener,
SMCStates *states,
char *buffer,
size_t maxsize);
unsigned int GetUTF8CharBytes(const char *stream);
const char *GetSMCErrorString(SMCError err);
bool IsWhitespace(const char *stream);
private:
SMCError ParseStream_SMC(void *stream,
STREAMREADER srdr,
ITextListener_SMC *smc,
SMCStates *states);
};
extern TextParsers g_TextParser;
#endif //_INCLUDE_SOURCEMOD_TEXTPARSERS_H_
+52
View File
@@ -0,0 +1,52 @@
/**
* vim: set ts=4 sw=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2009 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#include <sm_platform.h>
#include "ThreadSupport.h"
#include "common_logic.h"
#if defined PLATFORM_POSIX
#include "thread/PosixThreads.h"
#elif defined PLATFORM_WINDOWS
#include "thread/WinThreads.h"
#endif
MainThreader g_MainThreader;
IThreader *g_pThreader = &g_MainThreader;
class RegThreadStuff : public SMGlobalClass
{
public:
void OnSourceModAllInitialized()
{
sharesys->AddInterface(NULL, g_pThreader);
}
} s_RegThreadStuff;
+41
View File
@@ -0,0 +1,41 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#ifndef _INCLUDE_SOURCEMOD_THREAD_SUPPORT_H
#define _INCLUDE_SOURCEMOD_THREAD_SUPPORT_H
#include <IThreader.h>
using namespace SourceMod;
extern IThreader *g_pThreader;
#endif //_INCLUDE_SOURCEMOD_THREAD_SUPPORT_H
+116
View File
@@ -0,0 +1,116 @@
/**
* vim: set ts=4 sw=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#include <new>
#include <stdlib.h>
#include <sm_platform.h>
#include <string.h>
#include "common_logic.h"
#include "ThreadSupport.h"
#include "TextParsers.h"
sm_core_t smcore;
IHandleSys *handlesys;
IdentityToken_t *g_pCoreIdent;
SMGlobalClass *SMGlobalClass::head = NULL;
ISourceMod *g_pSM;
ILibrarySys *libsys;
ITextParsers *textparser = &g_TextParser;
IVEngineServer *engine;
IShareSys *sharesys;
static sm_logic_t logic =
{
NULL,
g_pThreader
};
static void logic_init(const sm_core_t* core, sm_logic_t* _logic)
{
logic.head = SMGlobalClass::head;
memcpy(&smcore, core, sizeof(sm_core_t));
memcpy(_logic, &logic, sizeof(sm_logic_t));
handlesys = core->handlesys;
libsys = core->libsys;
engine = core->engine;
g_pCoreIdent = core->core_ident;
g_pSM = core->sm;
sharesys = core->sharesys;
}
PLATFORM_EXTERN_C ITextParsers *get_textparsers()
{
return &g_TextParser;
}
PLATFORM_EXTERN_C LogicInitFunction logic_load(uint32_t magic)
{
if (magic != SM_LOGIC_MAGIC)
{
return NULL;
}
return logic_init;
}
void CoreNativesToAdd::OnSourceModAllInitialized()
{
smcore.AddNatives(m_NativeList);
}
/* Overload a few things to prevent libstdc++ linking */
#if defined __linux__ || defined __APPLE__
extern "C" void __cxa_pure_virtual(void)
{
}
void *operator new(size_t size)
{
return malloc(size);
}
void *operator new[](size_t size)
{
return malloc(size);
}
void operator delete(void *ptr)
{
free(ptr);
}
void operator delete[](void * ptr)
{
free(ptr);
}
#endif
+49
View File
@@ -0,0 +1,49 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2009 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#ifndef _INCLUDE_SOURCEMOD_COMMON_LOGIC_H_
#define _INCLUDE_SOURCEMOD_COMMON_LOGIC_H_
#include <IHandleSys.h>
#include "../sm_globals.h"
#include "intercom.h"
extern sm_core_t smcore;
extern IHandleSys *handlesys;
extern ISourceMod *g_pSM;
extern ILibrarySys *libsys;
extern ITextParsers *textparser;
extern IVEngineServer *engine;
extern IShareSys *sharesys;
#endif /* _INCLUDE_SOURCEMOD_COMMON_LOGIC_H_ */
+98
View File
@@ -0,0 +1,98 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2009 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#include <sp_vm_api.h>
#include <IHandleSys.h>
#include <IShareSys.h>
#ifndef _INCLUDE_SOURCEMOD_INTERCOM_H_
#define _INCLUDE_SOURCEMOD_INTERCOM_H_
using namespace SourceMod;
/**
* Add 1 to the RHS of this expression to bump the intercom file
* This is to prevent mismatching core/logic binaries
*/
#define SM_LOGIC_MAGIC (0x0F47C0DE - 0)
#if defined SM_LOGIC
class IVEngineServer
#else
class IVEngineServer_Logic
#endif
{
public:
virtual bool IsMapValid(const char *map) = 0;
};
namespace SourceMod
{
class ISourceMod;
class ILibrarySys;
class ITextParsers;
class IThreader;
}
class IVEngineServer;
class ConVar;
struct sm_core_t
{
/* Objects */
IHandleSys *handlesys;
IdentityToken_t *core_ident;
ISourceMod *sm;
ILibrarySys *libsys;
IVEngineServer *engine;
IShareSys *sharesys;
/* Functions */
void (*AddNatives)(sp_nativeinfo_t* nlist);
ConVar * (*FindConVar)(const char*);
unsigned int (*strncopy)(char*, const char*, size_t);
char * (*TrimWhitespace)(char *, size_t &);
void (*LogError)(const char*, ...);
const char * (*GetCvarString)(ConVar*);
size_t (*Format)(char*, size_t, const char*, ...);
};
struct sm_logic_t
{
SMGlobalClass *head;
IThreader *threader;
};
typedef void (*LogicInitFunction)(const sm_core_t *core, sm_logic_t *logic);
typedef LogicInitFunction (*LogicLoadFunction)(uint32_t magic);
typedef ITextParsers *(*GetITextParsers)();
#endif /* _INCLUDE_SOURCEMOD_INTERCOM_H_ */
+20
View File
@@ -0,0 +1,20 @@
Microsoft Visual Studio Solution File, Format Version 10.00
# Visual Studio 2008
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "logic", "logic.vcproj", "{6EF06E6E-0ED5-4E2D-A8F3-01DD1EC25BA7}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{6EF06E6E-0ED5-4E2D-A8F3-01DD1EC25BA7}.Debug|Win32.ActiveCfg = Debug|Win32
{6EF06E6E-0ED5-4E2D-A8F3-01DD1EC25BA7}.Debug|Win32.Build.0 = Debug|Win32
{6EF06E6E-0ED5-4E2D-A8F3-01DD1EC25BA7}.Release|Win32.ActiveCfg = Release|Win32
{6EF06E6E-0ED5-4E2D-A8F3-01DD1EC25BA7}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
+307
View File
@@ -0,0 +1,307 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9.00"
Name="logic"
ProjectGUID="{6EF06E6E-0ED5-4E2D-A8F3-01DD1EC25BA7}"
RootNamespace="jitx86"
Keyword="Win32Proj"
TargetFrameworkVersion="131072"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="2"
CharacterSet="2"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="..;&quot;$(MMSOURCE17)\core\sourcehook&quot;;..\..\..\public;..\..\..\public\sourcepawn"
PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;JITX86_EXPORTS;_CRT_SECURE_NO_DEPRECATE;SM_DEFAULT_THREADER"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
EnableEnhancedInstructionSet="0"
RuntimeTypeInfo="false"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="false"
DebugInformationFormat="4"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)\sourcepawn.jit.x86.dll"
LinkIncremental="2"
IgnoreDefaultLibraryNames="LIBC;LIBCD;LIBCMT"
GenerateDebugInformation="true"
SubSystem="2"
RandomizedBaseAddress="1"
DataExecutionPrevention="0"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="2"
CharacterSet="2"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
FavorSizeOrSpeed="1"
AdditionalIncludeDirectories="..;&quot;$(MMSOURCE17)\core\sourcehook&quot;;..\..\..\public;..\..\..\public\sourcepawn"
PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;JITX86_EXPORTS;_CRT_SECURE_NO_DEPRECATE;SM_LOGIC;SM_DEFAULT_THREADER"
RuntimeLibrary="0"
EnableEnhancedInstructionSet="0"
RuntimeTypeInfo="false"
UsePrecompiledHeader="0"
WarningLevel="3"
Detect64BitPortabilityProblems="false"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
OutputFile="$(OutDir)\sourcemod.logic.dll"
LinkIncremental="1"
IgnoreDefaultLibraryNames="LIBC;LIBCD;LIBCMTD"
GenerateDebugInformation="true"
SubSystem="2"
OptimizeReferences="2"
EnableCOMDATFolding="2"
RandomizedBaseAddress="1"
DataExecutionPrevention="0"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File
RelativePath="..\common_logic.cpp"
>
</File>
<File
RelativePath="..\smn_adt_array.cpp"
>
</File>
<File
RelativePath="..\smn_adt_stack.cpp"
>
</File>
<File
RelativePath="..\smn_float.cpp"
>
</File>
<File
RelativePath="..\smn_maplists.cpp"
>
</File>
<File
RelativePath="..\smn_sorting.cpp"
>
</File>
<File
RelativePath="..\smn_textparse.cpp"
>
</File>
<File
RelativePath="..\TextParsers.cpp"
>
</File>
<File
RelativePath="..\ThreadSupport.cpp"
>
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
>
<File
RelativePath="..\CellArray.h"
>
</File>
<File
RelativePath="..\common_logic.h"
>
</File>
<File
RelativePath="..\intercom.h"
>
</File>
<File
RelativePath="..\svn_version.h"
>
</File>
<File
RelativePath="..\TextParsers.h"
>
</File>
<File
RelativePath="..\ThreadSupport.h"
>
</File>
</Filter>
<Filter
Name="Resource Files"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
>
<File
RelativePath="..\svn_version.tpl"
>
</File>
<File
RelativePath="..\version.rc"
>
</File>
</Filter>
<Filter
Name="Threads"
>
<Filter
Name="Header Files"
>
<File
RelativePath="..\thread\BaseWorker.h"
>
</File>
<File
RelativePath="..\thread\ThreadWorker.h"
>
</File>
<File
RelativePath="..\thread\WinThreads.h"
>
</File>
</Filter>
<Filter
Name="Source Files"
>
<File
RelativePath="..\thread\BaseWorker.cpp"
>
</File>
<File
RelativePath="..\thread\ThreadWorker.cpp"
>
</File>
<File
RelativePath="..\thread\WinThreads.cpp"
>
</File>
</Filter>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
+586
View File
@@ -0,0 +1,586 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#include <stdlib.h>
#include "common_logic.h"
#include "CellArray.h"
HandleType_t htCellArray;
class CellArrayHelpers :
public SMGlobalClass,
public IHandleTypeDispatch
{
public: //SMGlobalClass
void OnSourceModAllInitialized()
{
htCellArray = handlesys->CreateType("CellArray", this, 0, NULL, NULL, g_pCoreIdent, NULL);
}
void OnSourceModShutdown()
{
handlesys->RemoveType(htCellArray, g_pCoreIdent);
}
public: //IHandleTypeDispatch
void OnHandleDestroy(HandleType_t type, void *object)
{
CellArray *array = (CellArray *)object;
delete array;
}
bool GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize)
{
CellArray *pArray = (CellArray *)object;
*pSize = sizeof(CellArray) + pArray->mem_usage();
return true;
}
} s_CellArrayHelpers;
static cell_t CreateArray(IPluginContext *pContext, const cell_t *params)
{
if (!params[1])
{
return pContext->ThrowNativeError("Invalid block size (must be > 0)");
}
CellArray *array = new CellArray(params[1]);
if (params[2])
{
array->resize(params[2]);
}
Handle_t hndl = handlesys->CreateHandle(htCellArray, array, pContext->GetIdentity(), g_pCoreIdent, NULL);
if (!hndl)
{
delete array;
}
return hndl;
}
static cell_t ClearArray(IPluginContext *pContext, const cell_t *params)
{
CellArray *array;
HandleError err;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&array))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
array->clear();
return 1;
}
static cell_t ResizeArray(IPluginContext *pContext, const cell_t *params)
{
CellArray *array;
HandleError err;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&array))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
if (!array->resize(params[2]))
{
return pContext->ThrowNativeError("Unable to resize array to \"%u\"", params[2]);
}
return 1;
}
static cell_t GetArraySize(IPluginContext *pContext, const cell_t *params)
{
CellArray *array;
HandleError err;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&array))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
return (cell_t)array->size();
}
static cell_t PushArrayCell(IPluginContext *pContext, const cell_t *params)
{
CellArray *array;
HandleError err;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&array))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
cell_t *blk = array->push();
if (!blk)
{
return pContext->ThrowNativeError("Failed to grow array");
}
*blk = params[2];
return (cell_t)(array->size() - 1);
}
static cell_t PushArrayString(IPluginContext *pContext, const cell_t *params)
{
CellArray *array;
HandleError err;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&array))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
cell_t *blk = array->push();
if (!blk)
{
return pContext->ThrowNativeError("Failed to grow array");
}
char *str;
pContext->LocalToString(params[2], &str);
smcore.strncopy((char *)blk, str, array->blocksize() * sizeof(cell_t));
return (cell_t)(array->size() - 1);
}
static cell_t PushArrayArray(IPluginContext *pContext, const cell_t *params)
{
CellArray *array;
HandleError err;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&array))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
cell_t *blk = array->push();
if (!blk)
{
return pContext->ThrowNativeError("Failed to grow array");
}
cell_t *addr;
pContext->LocalToPhysAddr(params[2], &addr);
size_t indexes = array->blocksize();
if (params[3] != -1 && (size_t)params[3] <= array->blocksize())
{
indexes = params[3];
}
memcpy(blk, addr, sizeof(cell_t) * indexes);
return (cell_t)(array->size() - 1);
}
static cell_t GetArrayCell(IPluginContext *pContext, const cell_t *params)
{
CellArray *array;
HandleError err;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&array))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
size_t idx = (size_t)params[2];
if (idx >= array->size())
{
return pContext->ThrowNativeError("Invalid index %d (count: %d)", idx, array->size());
}
cell_t *blk = array->at(idx);
idx = (size_t)params[3];
if (params[4] == 0)
{
if (idx >= array->blocksize())
{
return pContext->ThrowNativeError("Invalid block %d (blocksize: %d)", idx, array->blocksize());
}
return blk[idx];
} else {
if (idx >= array->blocksize() * 4)
{
return pContext->ThrowNativeError("Invalid byte %d (blocksize: %d bytes)", idx, array->blocksize() * 4);
}
return (cell_t)*((char *)blk + idx);
}
return 0;
}
static cell_t GetArrayString(IPluginContext *pContext, const cell_t *params)
{
CellArray *array;
HandleError err;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&array))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
size_t idx = (size_t)params[2];
if (idx >= array->size())
{
return pContext->ThrowNativeError("Invalid index %d (count: %d)", idx, array->size());
}
cell_t *blk = array->at(idx);
size_t numWritten = 0;
pContext->StringToLocalUTF8(params[3], params[4], (char *)blk, &numWritten);
return numWritten;
}
static cell_t GetArrayArray(IPluginContext *pContext, const cell_t *params)
{
CellArray *array;
HandleError err;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&array))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
size_t idx = (size_t)params[2];
if (idx >= array->size())
{
return pContext->ThrowNativeError("Invalid index %d (count: %d)", idx, array->size());
}
cell_t *blk = array->at(idx);
size_t indexes = array->blocksize();
if (params[4] != -1 && (size_t)params[4] <= array->blocksize())
{
indexes = params[4];
}
cell_t *addr;
pContext->LocalToPhysAddr(params[3], &addr);
memcpy(addr, blk, sizeof(cell_t) * indexes);
return indexes;
}
static cell_t SetArrayCell(IPluginContext *pContext, const cell_t *params)
{
CellArray *array;
HandleError err;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&array))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
size_t idx = (size_t)params[2];
if (idx >= array->size())
{
return pContext->ThrowNativeError("Invalid index %d (count: %d)", idx, array->size());
}
cell_t *blk = array->at(idx);
idx = (size_t)params[4];
if (params[5] == 0)
{
if (idx >= array->blocksize())
{
return pContext->ThrowNativeError("Invalid block %d (blocksize: %d)", idx, array->blocksize());
}
blk[idx] = params[3];
} else {
if (idx >= array->blocksize() * 4)
{
return pContext->ThrowNativeError("Invalid byte %d (blocksize: %d bytes)", idx, array->blocksize() * 4);
}
*((char *)blk + idx) = (char)params[3];
}
return 1;
}
static cell_t SetArrayString(IPluginContext *pContext, const cell_t *params)
{
CellArray *array;
HandleError err;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&array))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
size_t idx = (size_t)params[2];
if (idx >= array->size())
{
return pContext->ThrowNativeError("Invalid index %d (count: %d)", idx, array->size());
}
cell_t *blk = array->at(idx);
char *str;
pContext->LocalToString(params[3], &str);
return smcore.strncopy((char *)blk, str, array->blocksize() * sizeof(cell_t));
}
static cell_t SetArrayArray(IPluginContext *pContext, const cell_t *params)
{
CellArray *array;
HandleError err;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&array))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
size_t idx = (size_t)params[2];
if (idx >= array->size())
{
return pContext->ThrowNativeError("Invalid index %d (count: %d)", idx, array->size());
}
cell_t *blk = array->at(idx);
size_t indexes = array->blocksize();
if (params[4] != -1 && (size_t)params[4] <= array->blocksize())
{
indexes = params[4];
}
cell_t *addr;
pContext->LocalToPhysAddr(params[3], &addr);
memcpy(blk, addr, sizeof(cell_t) * indexes);
return indexes;
}
static cell_t ShiftArrayUp(IPluginContext *pContext, const cell_t *params)
{
CellArray *array;
HandleError err;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&array))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
size_t idx = (size_t)params[2];
if (idx >= array->size())
{
return pContext->ThrowNativeError("Invalid index %d (count: %d)", idx, array->size());
}
array->insert_at(idx);
return 1;
}
static cell_t RemoveFromArray(IPluginContext *pContext, const cell_t *params)
{
CellArray *array;
HandleError err;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&array))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
size_t idx = (size_t)params[2];
if (idx >= array->size())
{
return pContext->ThrowNativeError("Invalid index %d (count: %d)", idx, array->size());
}
array->remove(idx);
return 1;
}
static cell_t SwapArrayItems(IPluginContext *pContext, const cell_t *params)
{
CellArray *array;
HandleError err;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&array))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
size_t idx1 = (size_t)params[2];
size_t idx2 = (size_t)params[3];
if (idx1 >= array->size())
{
return pContext->ThrowNativeError("Invalid index %d (count: %d)", idx1, array->size());
}
if (idx2 >= array->size())
{
return pContext->ThrowNativeError("Invalid index %d (count: %d)", idx2, array->size());
}
array->swap(idx1, idx2);
return 1;
}
static cell_t CloneArray(IPluginContext *pContext, const cell_t *params)
{
CellArray *oldArray;
HandleError err;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&oldArray))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
CellArray *array = oldArray->clone();
Handle_t hndl = handlesys->CreateHandle(htCellArray, array, pContext->GetIdentity(), g_pCoreIdent, NULL);
if (!hndl)
{
delete array;
}
return hndl;
}
static cell_t FindStringInArray(IPluginContext *pContext, const cell_t *params)
{
CellArray *array;
HandleError err;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&array))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
char *str;
pContext->LocalToString(params[2], &str);
for (unsigned int i = 0; i < array->size(); i++)
{
const char *array_str = (const char *)array->at(i);
if (strcmp(str, array_str) == 0)
{
return (cell_t) i;
}
}
return -1;
}
static cell_t FindValueInArray(IPluginContext *pContext, const cell_t *params)
{
CellArray *array;
HandleError err;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&array))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
for (unsigned int i = 0; i < array->size(); i++)
{
if (params[2] == *array->at(i))
{
return (cell_t) i;
}
}
return -1;
}
REGISTER_NATIVES(cellArrayNatives)
{
{"ClearArray", ClearArray},
{"CreateArray", CreateArray},
{"GetArrayArray", GetArrayArray},
{"GetArrayCell", GetArrayCell},
{"GetArraySize", GetArraySize},
{"GetArrayString", GetArrayString},
{"ResizeArray", ResizeArray},
{"PushArrayArray", PushArrayArray},
{"PushArrayCell", PushArrayCell},
{"PushArrayString", PushArrayString},
{"RemoveFromArray", RemoveFromArray},
{"SetArrayCell", SetArrayCell},
{"SetArrayString", SetArrayString},
{"SetArrayArray", SetArrayArray},
{"ShiftArrayUp", ShiftArrayUp},
{"SwapArrayItems", SwapArrayItems},
{"CloneArray", CloneArray},
{"FindStringInArray", FindStringInArray},
{"FindValueInArray", FindValueInArray},
{NULL, NULL},
};
+307
View File
@@ -0,0 +1,307 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#include <stdlib.h>
#include "common_logic.h"
#include "CellArray.h"
HandleType_t htCellStack;
class CellStackHelpers :
public SMGlobalClass,
public IHandleTypeDispatch
{
public: //SMGlobalClass
void OnSourceModAllInitialized()
{
htCellStack = handlesys->CreateType("CellStack", this, 0, NULL, NULL, g_pCoreIdent, NULL);
}
void OnSourceModShutdown()
{
handlesys->RemoveType(htCellStack, g_pCoreIdent);
}
public: //IHandleTypeDispatch
void OnHandleDestroy(HandleType_t type, void *object)
{
CellArray *array = (CellArray *)object;
delete array;
}
bool GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize)
{
CellArray *pArray = (CellArray *)object;
*pSize = sizeof(CellArray) + pArray->mem_usage();
return true;
}
} s_CellStackHelpers;
static cell_t CreateStack(IPluginContext *pContext, const cell_t *params)
{
if (params[1] < 1)
{
return pContext->ThrowNativeError("Invalid block size (must be > 0)");
}
CellArray *array = new CellArray(params[1]);
Handle_t hndl = handlesys->CreateHandle(htCellStack, array, pContext->GetIdentity(), g_pCoreIdent, NULL);
if (!hndl)
{
delete array;
}
return hndl;
}
static cell_t PushStackCell(IPluginContext *pContext, const cell_t *params)
{
CellArray *array;
HandleError err;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellStack, &sec, (void **)&array))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
cell_t *blk = array->push();
if (!blk)
{
return pContext->ThrowNativeError("Failed to grow stack");
}
*blk = params[2];
return 1;
}
static cell_t PushStackString(IPluginContext *pContext, const cell_t *params)
{
CellArray *array;
HandleError err;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellStack, &sec, (void **)&array))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
cell_t *blk = array->push();
if (!blk)
{
return pContext->ThrowNativeError("Failed to grow stack");
}
char *str;
pContext->LocalToString(params[2], &str);
smcore.strncopy((char *)blk, str, array->blocksize() * sizeof(cell_t));
return 1;
}
static cell_t PushStackArray(IPluginContext *pContext, const cell_t *params)
{
CellArray *array;
HandleError err;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellStack, &sec, (void **)&array))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
cell_t *blk = array->push();
if (!blk)
{
return pContext->ThrowNativeError("Failed to grow array");
}
cell_t *addr;
pContext->LocalToPhysAddr(params[2], &addr);
size_t indexes = array->blocksize();
if (params[3] != -1 && (size_t)params[3] <= array->blocksize())
{
indexes = params[3];
}
memcpy(blk, addr, sizeof(cell_t) * indexes);
return 1;
}
static cell_t PopStackCell(IPluginContext *pContext, const cell_t *params)
{
size_t idx;
HandleError err;
CellArray *array;
cell_t *blk, *buffer;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellStack, &sec, (void **)&array))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
if (array->size() == 0)
{
return 0;
}
pContext->LocalToPhysAddr(params[2], &buffer);
blk = array->at(array->size() - 1);
idx = (size_t)params[3];
if (params[4] == 0)
{
if (idx >= array->blocksize())
{
return pContext->ThrowNativeError("Invalid block %d (blocksize: %d)", idx, array->blocksize());
}
*buffer = blk[idx];
}
else
{
if (idx >= array->blocksize() * 4)
{
return pContext->ThrowNativeError("Invalid byte %d (blocksize: %d bytes)", idx, array->blocksize() * 4);
}
*buffer = (cell_t)*((char *)blk + idx);
}
array->remove(array->size() - 1);
return 1;
}
static cell_t PopStackString(IPluginContext *pContext, const cell_t *params)
{
HandleError err;
CellArray *array;
size_t idx, numWritten;
cell_t *blk, *pWritten;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellStack, &sec, (void **)&array))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
if (array->size() == 0)
{
return 0;
}
idx = array->size() - 1;
blk = array->at(idx);
pContext->StringToLocalUTF8(params[2], params[3], (char *)blk, &numWritten);
pContext->LocalToPhysAddr(params[4], &pWritten);
*pWritten = (cell_t)numWritten;
array->remove(idx);
return 1;
}
static cell_t PopStackArray(IPluginContext *pContext, const cell_t *params)
{
size_t idx;
cell_t *blk;
cell_t *addr;
size_t indexes;
HandleError err;
CellArray *array;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellStack, &sec, (void **)&array))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
if (array->size() == 0)
{
return 0;
}
idx = array->size() - 1;
blk = array->at(idx);
indexes = array->blocksize();
if (params[3] != -1 && (size_t)params[3] <= array->blocksize())
{
indexes = params[3];
}
pContext->LocalToPhysAddr(params[2], &addr);
memcpy(addr, blk, sizeof(cell_t) * indexes);
array->remove(idx);
return indexes;
}
static cell_t IsStackEmpty(IPluginContext *pContext, const cell_t *params)
{
HandleError err;
CellArray *array;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellStack, &sec, (void **)&array))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
if (array->size() == 0)
{
return 1;
}
return 0;
}
REGISTER_NATIVES(cellStackNatives)
{
{"CreateStack", CreateStack},
{"IsStackEmpty", IsStackEmpty},
{"PopStackArray", PopStackArray},
{"PopStackCell", PopStackCell},
{"PopStackString", PopStackString},
{"PushStackArray", PushStackArray},
{"PushStackCell", PushStackCell},
{"PushStackString", PushStackString},
{NULL, NULL},
};
+314
View File
@@ -0,0 +1,314 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include "common_logic.h"
/****************************************
* *
* FLOATING POINT NATIVE IMPLEMENTATIONS *
* *
****************************************/
static cell_t sm_float(IPluginContext *pCtx, const cell_t *params)
{
float val = static_cast<float>(params[1]);
return sp_ftoc(val);
}
static cell_t sm_FloatAbs(IPluginContext *pCtx, const cell_t *params)
{
float val = sp_ctof(params[1]);
val = (val >= 0.0f) ? val : -val;
return sp_ftoc(val);
}
static cell_t sm_FloatAdd(IPluginContext *pCtx, const cell_t *params)
{
float val = sp_ctof(params[1]) + sp_ctof(params[2]);
return sp_ftoc(val);
}
static cell_t sm_FloatSub(IPluginContext *pCtx, const cell_t *params)
{
float val = sp_ctof(params[1]) - sp_ctof(params[2]);
return sp_ftoc(val);
}
static cell_t sm_FloatMul(IPluginContext *pCtx, const cell_t *params)
{
float val = sp_ctof(params[1]) * sp_ctof(params[2]);
return sp_ftoc(val);
}
static cell_t sm_FloatDiv(IPluginContext *pCtx, const cell_t *params)
{
float val = sp_ctof(params[1]) / sp_ctof(params[2]);
return sp_ftoc(val);
}
static cell_t sm_FloatCompare(IPluginContext *pCtx, const cell_t *params)
{
float val1 = sp_ctof(params[1]);
float val2 = sp_ctof(params[2]);
if (val1 > val2)
{
return 1;
} else if (val1 < val2) {
return -1;
}
return 0;
}
static cell_t sm_Logarithm(IPluginContext *pCtx, const cell_t *params)
{
float val = sp_ctof(params[1]);
float base = sp_ctof(params[2]);
if ((val <= 0.0f) || (base <= 0.0f))
{
return pCtx->ThrowNativeError("Cannot evaluate the logarithm of zero or a negative number (val:%f base:%f)", val, base);
}
if (base == 10.0f)
{
val = log10(val);
} else {
val = log(val) / log(base);
}
return sp_ftoc(val);
}
static cell_t sm_Exponential(IPluginContext *pCtx, const cell_t *params)
{
float val = sp_ctof(params[1]);
return sp_ftoc(exp(val));
}
static cell_t sm_Pow(IPluginContext *pCtx, const cell_t *params)
{
float base = sp_ctof(params[1]);
float exponent = sp_ctof(params[2]);
return sp_ftoc(pow(base, exponent));
}
static cell_t sm_SquareRoot(IPluginContext *pCtx, const cell_t *params)
{
float val = sp_ctof(params[1]);
if (val < 0.0f)
{
return pCtx->ThrowNativeError("Cannot evaluate the square root of a negative number (val:%f)", val);
}
return sp_ftoc(sqrt(val));
}
static cell_t sm_RoundToNearest(IPluginContext *pCtx, const cell_t *params)
{
float val = sp_ctof(params[1]);
val = (float)floor(val + 0.5f);
return static_cast<int>(val);
}
static cell_t sm_RoundToFloor(IPluginContext *pCtx, const cell_t *params)
{
float val = sp_ctof(params[1]);
val = floor(val);
return static_cast<int>(val);
}
static cell_t sm_RoundToCeil(IPluginContext *pCtx, const cell_t *params)
{
float val = sp_ctof(params[1]);
val = ceil(val);
return static_cast<int>(val);
}
static cell_t sm_RoundToZero(IPluginContext *pCtx, const cell_t *params)
{
float val = sp_ctof(params[1]);
if (val >= 0.0f)
{
val = floor(val);
} else {
val = ceil(val);
}
return static_cast<int>(val);
}
static cell_t sm_FloatFraction(IPluginContext *pCtx, const cell_t *params)
{
float val = sp_ctof(params[1]);
val = val - floor(val);
return sp_ftoc(val);
}
static cell_t sm_Sine(IPluginContext *pCtx, const cell_t *params)
{
float val = sp_ctof(params[1]);
val = sin(val);
return sp_ftoc(val);
}
static cell_t sm_Cosine(IPluginContext *pCtx, const cell_t *params)
{
float val = sp_ctof(params[1]);
val = cos(val);
return sp_ftoc(val);
}
static cell_t sm_Tangent(IPluginContext *pCtx, const cell_t *params)
{
float val = sp_ctof(params[1]);
val = tan(val);
return sp_ftoc(val);
}
static cell_t sm_ArcSine(IPluginContext *pCtx, const cell_t *params)
{
float val = sp_ctof(params[1]);
val = asin(val);
return sp_ftoc(val);
}
static cell_t sm_ArcCosine(IPluginContext *pCtx, const cell_t *params)
{
float val = sp_ctof(params[1]);
val = acos(val);
return sp_ftoc(val);
}
static cell_t sm_ArcTangent(IPluginContext *pCtx, const cell_t *params)
{
float val = sp_ctof(params[1]);
val = atan(val);
return sp_ftoc(val);
}
static cell_t sm_ArcTangent2(IPluginContext *pCtx, const cell_t *params)
{
float val1 = sp_ctof(params[1]);
float val2 = sp_ctof(params[2]);
val1 = atan2(val1, val2);
return sp_ftoc(val1);
}
#if 0
static cell_t sm_FloatRound(IPluginContext *pCtx, const cell_t *params)
{
float val = sp_ctof(params[1]);
switch (params[2])
{
case 1:
{
val = floor(val);
break;
}
case 2:
{
val = ceil(val);
break;
}
case 3:
{
if (val >= 0.0f)
{
val = floor(val);
} else {
val = ceil(val);
}
break;
}
default:
{
val = (float)floor(val + 0.5f);
break;
}
}
return static_cast<int>(val);
}
#endif
REGISTER_NATIVES(floatnatives)
{
{"float", sm_float},
{"FloatMul", sm_FloatMul},
{"FloatDiv", sm_FloatDiv},
{"FloatAdd", sm_FloatAdd},
{"FloatSub", sm_FloatSub},
{"FloatFraction", sm_FloatFraction},
{"RoundToZero", sm_RoundToZero},
{"RoundToCeil", sm_RoundToCeil},
{"RoundToFloor", sm_RoundToFloor},
{"RoundToNearest", sm_RoundToNearest},
{"FloatCompare", sm_FloatCompare},
{"SquareRoot", sm_SquareRoot},
{"Pow", sm_Pow},
{"Exponential", sm_Exponential},
{"Logarithm", sm_Logarithm},
{"Sine", sm_Sine},
{"Cosine", sm_Cosine},
{"Tangent", sm_Tangent},
{"FloatAbs", sm_FloatAbs},
{"ArcTangent", sm_ArcTangent},
{"ArcCosine", sm_ArcCosine},
{"ArcSine", sm_ArcSine},
{"ArcTangent2", sm_ArcTangent2},
{NULL, NULL}
};
+652
View File
@@ -0,0 +1,652 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#include <sh_list.h>
#include <sm_trie_tpl.h>
#include "common_logic.h"
#include "CellArray.h"
#include <ILibrarySys.h>
#include <ITextParsers.h>
#include <ISourceMod.h>
using namespace SourceHook;
struct maplist_info_t
{
bool bIsCompat;
bool bIsPath;
char name[PLATFORM_MAX_PATH];
char path[PLATFORM_MAX_PATH];
time_t last_modified_time;
CellArray *pArray;
int serial;
};
#define MAPLIST_FLAG_MAPSFOLDER (1<<0) /**< On failure, use all maps in the maps folder. */
#define MAPLIST_FLAG_CLEARARRAY (1<<1) /**< If an input array is specified, clear it before adding. */
#define MAPLIST_FLAG_NO_DEFAULT (1<<2) /**< Do not read "default" or "mapcyclefile" on failure. */
class MapLists : public SMGlobalClass, public ITextListener_SMC
{
public:
enum MapListState
{
MPS_NONE,
MPS_GLOBAL,
MPS_MAPLIST,
};
public:
MapLists()
{
m_pMapCycleFile = NULL;
m_ConfigLastChanged = 0;
m_nSerialChange = 0;
}
void OnSourceModAllInitialized()
{
g_pSM->BuildPath(Path_SM, m_ConfigFile, sizeof(m_ConfigFile), "configs/maplists.cfg");
}
void OnSourceModShutdown()
{
DumpCache(NULL);
}
void AddOrUpdateDefault(const char *name, const char *file)
{
char path[PLATFORM_MAX_PATH];
maplist_info_t *pMapList, **ppMapList;
if ((ppMapList = m_ListLookup.retrieve(name)) == NULL)
{
pMapList = new maplist_info_t;
pMapList->bIsCompat = true;
pMapList->bIsPath = true;
pMapList->last_modified_time = 0;
smcore.strncopy(pMapList->name, name, sizeof(pMapList->name));
pMapList->pArray = NULL;
g_pSM->BuildPath(Path_Game, pMapList->path, sizeof(pMapList->path), "%s", file);
pMapList->serial = 0;
m_ListLookup.insert(name, pMapList);
m_MapLists.push_back(pMapList);
return;
}
pMapList = *ppMapList;
/* Don't modify if it's from the config file */
if (!pMapList->bIsCompat)
{
return;
}
g_pSM->BuildPath(Path_Game, path, sizeof(path), "%s", file);
/* If the path matches, don't reset the serial/time */
if (strcmp(path, pMapList->path) == 0)
{
return;
}
smcore.strncopy(pMapList->path, path, sizeof(pMapList->path));
pMapList->bIsPath = true;
pMapList->last_modified_time = 0;
pMapList->serial = 0;
}
void UpdateCache()
{
bool fileFound;
SMCError error;
time_t fileTime;
SMCStates states = {0, 0};
fileFound = libsys->FileTime(m_ConfigFile, FileTime_LastChange, &fileTime);
/* If the file is found and hasn't changed, bail out now. */
if (fileFound && fileTime == m_ConfigLastChanged)
{
return;
}
/* If the file wasn't found, and we already have entries, we bail out too.
* This case lets us optimize when a user deletes the config file, so we
* don't reparse every single time the function is called.
*/
if (!fileFound && m_MapLists.size() > 0)
{
return;
}
m_pMapCycleFile = smcore.FindConVar("mapcyclefile");
/* Dump everything we know about. */
List<maplist_info_t *> compat;
DumpCache(&compat);
/* All this is to add the default entry back in. */
maplist_info_t *pDefList = new maplist_info_t;
pDefList->bIsPath = true;
smcore.strncopy(pDefList->name, "mapcyclefile", sizeof(pDefList->name));
g_pSM->BuildPath(Path_Game,
pDefList->path,
sizeof(pDefList->path),
"%s",
m_pMapCycleFile ? smcore.GetCvarString(m_pMapCycleFile) : "mapcycle.txt");
pDefList->last_modified_time = 0;
pDefList->pArray = NULL;
pDefList->serial = 0;
m_ListLookup.insert("mapcyclefile", pDefList);
m_MapLists.push_back(pDefList);
/* Now parse the config file even if we don't know about it.
* This will give us a nice error message.
*/
if ((error = textparser->ParseFile_SMC(m_ConfigFile, this, &states))
!= SMCError_Okay)
{
const char *errmsg = textparser->GetSMCErrorString(error);
if (errmsg == NULL)
{
errmsg = "Unknown error";
}
smcore.LogError("[SM] Could not parse file \"%s\"", m_ConfigFile);
smcore.LogError("[SM] Error on line %d (col %d): %s", states.line, states.col, errmsg);
}
else
{
m_ConfigLastChanged = fileTime;
}
/* Now, re-add compat stuff back in if we can. */
List<maplist_info_t *>::iterator iter = compat.begin();
while (iter != compat.end())
{
if (m_ListLookup.retrieve((*iter)->name) != NULL)
{
/* The compatibility shim is no longer needed. */
delete (*iter)->pArray;
delete (*iter);
}
else
{
m_ListLookup.insert((*iter)->name, (*iter));
m_MapLists.push_back((*iter));
}
iter = compat.erase(iter);
}
}
void ReadSMC_ParseStart()
{
m_CurState = MPS_NONE;
m_IgnoreLevel = 0;
m_pCurMapList = NULL;
}
SMCResult ReadSMC_NewSection(const SMCStates *states, const char *name)
{
if (m_IgnoreLevel)
{
m_IgnoreLevel++;
return SMCResult_Continue;
}
if (m_CurState == MPS_NONE)
{
if (strcmp(name, "MapLists") == 0)
{
m_CurState = MPS_GLOBAL;
}
else
{
m_IgnoreLevel = 1;
}
}
else if (m_CurState == MPS_GLOBAL)
{
m_pCurMapList = new maplist_info_t;
memset(m_pCurMapList, 0, sizeof(maplist_info_t));
smcore.strncopy(m_pCurMapList->name, name, sizeof(m_pCurMapList->name));
m_CurState = MPS_MAPLIST;
}
else if (m_CurState == MPS_MAPLIST)
{
m_IgnoreLevel++;
}
return SMCResult_Continue;
}
SMCResult ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
{
if (m_IgnoreLevel || m_pCurMapList == NULL)
{
return SMCResult_Continue;
}
if (strcmp(key, "file") == 0)
{
g_pSM->BuildPath(Path_Game,
m_pCurMapList->path,
sizeof(m_pCurMapList->path),
"%s",
value);
m_pCurMapList->bIsPath = true;
}
else if (strcmp(key, "target") == 0)
{
smcore.strncopy(m_pCurMapList->path, value, sizeof(m_pCurMapList->path));
m_pCurMapList->bIsPath = false;
}
return SMCResult_Continue;
}
SMCResult ReadSMC_LeavingSection(const SMCStates *states)
{
if (m_IgnoreLevel)
{
m_IgnoreLevel--;
return SMCResult_Continue;
}
if (m_CurState == MPS_MAPLIST)
{
if (m_pCurMapList != NULL
&& m_pCurMapList->path[0] != '\0'
&& m_ListLookup.retrieve(m_pCurMapList->name) == NULL)
{
m_ListLookup.insert(m_pCurMapList->name, m_pCurMapList);
m_MapLists.push_back(m_pCurMapList);
m_pCurMapList = NULL;
}
else
{
delete m_pCurMapList;
m_pCurMapList = NULL;
}
m_CurState = MPS_GLOBAL;
}
else if (m_CurState == MPS_GLOBAL)
{
m_CurState = MPS_NONE;
}
return SMCResult_Continue;
}
void ReadSMC_ParseEnd(bool halted, bool failed)
{
delete m_pCurMapList;
m_pCurMapList = NULL;
}
static int sort_maps_in_adt_array(const void *str1, const void *str2)
{
return strcmp((char *)str1, (char *)str2);
}
CellArray *UpdateMapList(CellArray *pUseArray, const char *name, int *pSerial, unsigned int flags)
{
int change_serial;
CellArray *pNewArray = NULL;
bool success, free_new_array;
free_new_array = false;
if ((success = GetMapList(&pNewArray, name, &change_serial)) == false)
{
if ((flags & MAPLIST_FLAG_NO_DEFAULT) != MAPLIST_FLAG_NO_DEFAULT)
{
/* If this list failed, and it's not the default, try the default.
*/
if (strcmp(name, "default") != 0)
{
success = GetMapList(&pNewArray, name, &change_serial);
}
/* If either of the last two conditions failed, try again if we can. */
if (!success && strcmp(name, "mapcyclefile") != 0)
{
success = GetMapList(&pNewArray, "mapcyclefile", &change_serial);
}
}
}
/* If there was a success, and the serial has not changed, bail out. */
if (success && *pSerial == change_serial)
{
return NULL;
}
/**
* If there was a success but no map list, we need to look in the maps folder.
* If there was a failure and the flag is specified, we need to look in the maps folder.
*/
if ((success && pNewArray == NULL)
|| (!success && ((flags & MAPLIST_FLAG_MAPSFOLDER) == MAPLIST_FLAG_MAPSFOLDER)))
{
char path[255];
IDirectory *pDir;
pNewArray = new CellArray(64);
free_new_array = true;
g_pSM->BuildPath(Path_Game, path, sizeof(path), "maps");
if ((pDir = libsys->OpenDirectory(path)) != NULL)
{
char *ptr;
cell_t *blk;
char buffer[PLATFORM_MAX_PATH];
while (pDir->MoreFiles())
{
if (!pDir->IsEntryFile()
|| strcmp(pDir->GetEntryName(), ".") == 0
|| strcmp(pDir->GetEntryName(), "..") == 0)
{
pDir->NextEntry();
continue;
}
smcore.strncopy(buffer, pDir->GetEntryName(), sizeof(buffer));
if ((ptr = strstr(buffer, ".bsp")) == NULL || ptr[4] != '\0')
{
pDir->NextEntry();
continue;
}
*ptr = '\0';
if (!engine->IsMapValid(buffer))
{
pDir->NextEntry();
continue;
}
if ((blk = pNewArray->push()) == NULL)
{
pDir->NextEntry();
continue;
}
smcore.strncopy((char *)blk, buffer, 255);
pDir->NextEntry();
}
libsys->CloseDirectory(pDir);
}
/* Remove the array if there were no items. */
if (pNewArray->size() == 0)
{
delete pNewArray;
pNewArray = NULL;
}
else
{
qsort(pNewArray->base(),
pNewArray->size(),
pNewArray->blocksize() * sizeof(cell_t),
sort_maps_in_adt_array);
}
change_serial = -1;
}
/* If there is still no array by this point, bail out. */
if (pNewArray == NULL)
{
*pSerial = -1;
return NULL;
}
*pSerial = change_serial;
/* If there is no input array, return something temporary. */
if (pUseArray == NULL)
{
if (free_new_array)
{
return pNewArray;
}
else
{
return pNewArray->clone();
}
}
/* Clear the input array if necessary. */
if ((flags & MAPLIST_FLAG_CLEARARRAY) == MAPLIST_FLAG_CLEARARRAY)
{
pUseArray->clear();
}
/* Copy. */
cell_t *blk_dst;
cell_t *blk_src;
for (size_t i = 0; i < pNewArray->size(); i++)
{
blk_dst = pUseArray->push();
blk_src = pNewArray->at(i);
smcore.strncopy((char *)blk_dst, (char *)blk_src, pUseArray->blocksize() * sizeof(cell_t));
}
/* Free resources if necessary. */
if (free_new_array)
{
delete pNewArray;
}
/* Return the array we were given. */
return pUseArray;
}
private:
bool GetMapList(CellArray **ppArray, const char *name, int *pSerial)
{
time_t last_time;
maplist_info_t *pMapList, **ppMapList;
if ((ppMapList = m_ListLookup.retrieve(name)) == NULL)
{
return false;
}
pMapList = *ppMapList;
if (!pMapList->bIsPath)
{
return GetMapList(ppArray, pMapList->path, pSerial);
}
/* If it is a path, and the path is "*", assume all files must be used. */
if (strcmp(pMapList->path, "*") == 0)
{
*ppArray = NULL;
return true;
}
if (m_pMapCycleFile != NULL && strcmp(name, "mapcyclefile") == 0)
{
char path[PLATFORM_MAX_PATH];
g_pSM->BuildPath(Path_Game,
path,
sizeof(path),
"%s",
m_pMapCycleFile ? smcore.GetCvarString(m_pMapCycleFile) : "mapcycle.txt");
if (strcmp(path, pMapList->path) != 0)
{
smcore.strncopy(pMapList->path, path, sizeof(pMapList->path));
pMapList->last_modified_time = 0;
}
}
if (!libsys->FileTime(pMapList->path, FileTime_LastChange, &last_time)
|| last_time > pMapList->last_modified_time)
{
/* Reparse */
FILE *fp;
cell_t *blk;
char buffer[255];
if ((fp = fopen(pMapList->path, "rt")) == NULL)
{
return false;
}
delete pMapList->pArray;
pMapList->pArray = new CellArray(64);
while (!feof(fp) && fgets(buffer, sizeof(buffer), fp) != NULL)
{
size_t len = strlen(buffer);
char *ptr = smcore.TrimWhitespace(buffer, len);
if (*ptr == '\0'
|| *ptr == ';'
|| strncmp(ptr, "//", 2) == 0)
{
continue;
}
if (!engine->IsMapValid(ptr))
{
continue;
}
if ((blk = pMapList->pArray->push()) != NULL)
{
smcore.strncopy((char *)blk, ptr, 255);
}
}
fclose(fp);
pMapList->last_modified_time = last_time;
pMapList->serial = ++m_nSerialChange;
}
if (pMapList->pArray == NULL || pMapList->pArray->size() == 0)
{
return false;
}
*pSerial = pMapList->serial;
*ppArray = pMapList->pArray;
return true;
}
void DumpCache(List<maplist_info_t *> *compat_list)
{
m_ListLookup.clear();
List<maplist_info_t *>::iterator iter = m_MapLists.begin();
while (iter != m_MapLists.end())
{
if (compat_list != NULL && (*iter)->bIsCompat)
{
compat_list->push_back((*iter));
}
else
{
delete (*iter)->pArray;
delete (*iter);
}
iter = m_MapLists.erase(iter);
}
}
private:
char m_ConfigFile[PLATFORM_MAX_PATH];
time_t m_ConfigLastChanged;
ConVar *m_pMapCycleFile;
KTrie<maplist_info_t *> m_ListLookup;
List<maplist_info_t *> m_MapLists;
MapListState m_CurState;
unsigned int m_IgnoreLevel;
maplist_info_t *m_pCurMapList;
int m_nSerialChange;
} s_MapLists;
static cell_t LoadMapList(IPluginContext *pContext, const cell_t *params)
{
char *str;
Handle_t hndl;
cell_t *addr, flags;
CellArray *pArray, *pNewArray;
hndl = params[1];
pContext->LocalToPhysAddr(params[2], &addr);
pContext->LocalToString(params[3], &str);
flags = params[4];
/* Make sure the input Handle is valid */
pArray = NULL;
if (hndl != BAD_HANDLE)
{
HandleError err;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(hndl, htCellArray, &sec, (void **)&pArray))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error %d)", hndl, err);
}
}
/* Make sure the map list cache is up to date at the root */
s_MapLists.UpdateCache();
/* Try to get the map list. */
if ((pNewArray = s_MapLists.UpdateMapList(pArray, str, addr, flags)) == NULL)
{
return BAD_HANDLE;
}
/* If the user wanted a new array, create it now. */
if (hndl == BAD_HANDLE)
{
if ((hndl = handlesys->CreateHandle(htCellArray, pNewArray, pContext->GetIdentity(), g_pCoreIdent, NULL))
== BAD_HANDLE)
{
*addr = -1;
delete pNewArray;
return BAD_HANDLE;
}
}
return hndl;
}
static cell_t SetMapListCompatBind(IPluginContext *pContext, const cell_t *params)
{
char *name, *file;
pContext->LocalToString(params[1], &name);
pContext->LocalToString(params[2], &file);
s_MapLists.UpdateCache();
s_MapLists.AddOrUpdateDefault(name, file);
return 1;
}
REGISTER_NATIVES(mapListNatives)
{
{"ReadMapList", LoadMapList},
{"SetMapListCompatBind", SetMapListCompatBind},
{NULL, NULL},
};
+578
View File
@@ -0,0 +1,578 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "common_logic.h"
#include "CellArray.h"
/***********************************
* About the double array hack *
***************************
Double arrays in Pawn are vectors offset by the current offset. For example:
new array[2][2]
In this array, index 0 contains the offset from the current offset which
results in the final vector [2] (at [0][2]). Meaning, to dereference [1][2],
it is equivalent to:
address = &array[1] + array[1] + 2 * sizeof(cell)
The fact that each offset is from the _current_ position rather than the _base_
position is very important. It means that if you to try to swap vector positions,
the offsets will no longer match, because their current position has changed. A
simple and ingenious way around this is to back up the positions in a separate array,
then to overwrite each position in the old array with absolute indices. Pseudo C++ code:
cell *array; //assumed to be set to the 2+D array
cell *old_offsets = new cell[2];
for (int i=0; i<2; i++)
{
old_offsets = array[i];
array[i] = i;
}
Now, you can swap the array indices with no problem, and do a reverse-lookup to find the original addresses.
After sorting/modification is done, you must relocate the new indices. For example, if the two vectors in our
demo array were swapped, array[0] would be 1 and array[1] would be 0. This is invalid to the virtual machine.
Luckily, this is also simple -- all the information is there.
for (int i=0; i<2; i++)
{
//get the # of the vector we want to relocate in
cell vector_index = array[i];
//get the real address of this vector
char *real_address = (char *)array + (vector_index * sizeof(cell)) + old_offsets[vector_index];
//calc and store the new distance offset
array[i] = real_address - ( (char *)array + (vector_index + sizeof(cell)) )
}
Note that the inner expression can be heavily reduced; it is expanded for readability.
**********************************/
enum SortOrder
{
Sort_Ascending = 0,
Sort_Descending = 1,
Sort_Random = 2,
};
void sort_random(cell_t *array, cell_t size)
{
srand((unsigned int)time(NULL));
for (int i = size-1; i > 0; i--)
{
int n = (rand() % i) + 1;
if (array[i] != array[n])
{
array[i] ^= array[n];
array[n] ^= array[i];
array[i] ^= array[n];
}
}
}
int sort_ints_asc(const void *int1, const void *int2)
{
return (*(int *)int1) - (*(int *)int2);
}
int sort_ints_desc(const void *int1, const void *int2)
{
return (*(int *)int2) - (*(int *)int1);
}
static cell_t sm_SortIntegers(IPluginContext *pContext, const cell_t *params)
{
cell_t *array;
cell_t array_size = params[2];
cell_t type = params[3];
pContext->LocalToPhysAddr(params[1], &array);
if (type == Sort_Ascending)
{
qsort(array, array_size, sizeof(cell_t), sort_ints_asc);
}
else if (type == Sort_Descending)
{
qsort(array, array_size, sizeof(cell_t), sort_ints_desc);
}
else
{
sort_random(array, array_size);
}
return 1;
}
int sort_floats_asc(const void *float1, const void *float2)
{
float r1 = *(float *)float1;
float r2 = *(float *)float2;
if (r1 < r2)
{
return -1;
} else if (r2 < r1) {
return 1;
} else {
return 0;
}
}
int sort_floats_desc(const void *float1, const void *float2)
{
float r1 = *(float *)float1;
float r2 = *(float *)float2;
if (r1 < r2)
{
return 1;
} else if (r2 < r1) {
return -1;
} else {
return 0;
}
}
static cell_t sm_SortFloats(IPluginContext *pContext, const cell_t *params)
{
cell_t *array;
cell_t array_size = params[2];
cell_t type = params[3];
pContext->LocalToPhysAddr(params[1], &array);
if (type == Sort_Ascending)
{
qsort(array, array_size, sizeof(cell_t), sort_floats_asc);
}
else if (type == Sort_Descending)
{
qsort(array, array_size, sizeof(cell_t), sort_floats_desc);
}
else
{
sort_random(array, array_size);
}
return 1;
}
static cell_t *g_CurStringArray = NULL;
static cell_t *g_CurRebaseMap = NULL;
int sort_strings_asc(const void *blk1, const void *blk2)
{
cell_t reloc1 = *(cell_t *)blk1;
cell_t reloc2 = *(cell_t *)blk2;
char *str1 = ((char *)(&g_CurStringArray[reloc1]) + g_CurRebaseMap[reloc1]);
char *str2 = ((char *)(&g_CurStringArray[reloc2]) + g_CurRebaseMap[reloc2]);
return strcmp(str1, str2);
}
int sort_strings_desc(const void *blk1, const void *blk2)
{
cell_t reloc1 = *(cell_t *)blk1;
cell_t reloc2 = *(cell_t *)blk2;
char *str1 = ((char *)(&g_CurStringArray[reloc1]) + g_CurRebaseMap[reloc1]);
char *str2 = ((char *)(&g_CurStringArray[reloc2]) + g_CurRebaseMap[reloc2]);
return strcmp(str2, str1);
}
static cell_t sm_SortStrings(IPluginContext *pContext, const cell_t *params)
{
cell_t *array;
cell_t array_size = params[2];
cell_t type = params[3];
pContext->LocalToPhysAddr(params[1], &array);
/** HACKHACK - back up the old indices, replace the indices with something easier */
cell_t amx_addr, *phys_addr;
int err;
if ((err=pContext->HeapAlloc(array_size, &amx_addr, &phys_addr)) != SP_ERROR_NONE)
{
pContext->ThrowNativeErrorEx(err, "Ran out of memory to sort");
}
g_CurStringArray = array;
g_CurRebaseMap = phys_addr;
for (int i=0; i<array_size; i++)
{
phys_addr[i] = array[i];
array[i] = i;
}
if (type == Sort_Ascending)
{
qsort(array, array_size, sizeof(cell_t), sort_strings_asc);
}
else if (type == Sort_Descending)
{
qsort(array, array_size, sizeof(cell_t), sort_strings_desc);
}
else
{
sort_random(array, array_size);
}
/* END HACKHACK - restore what we damaged so Pawn doesn't throw up.
* We'll browse through each index of the array and patch up the distance.
*/
for (int i=0; i<array_size; i++)
{
/* Compute the final address of the old array and subtract the new location.
* This is the fixed up distance.
*/
array[i] = ((char *)&array[array[i]] + phys_addr[array[i]]) - (char *)&array[i];
}
pContext->HeapPop(amx_addr);
g_CurStringArray = NULL;
g_CurRebaseMap = NULL;
return 1;
}
struct sort_info
{
IPluginFunction *pFunc;
Handle_t hndl;
cell_t array_addr;
cell_t *array_base;
cell_t *array_remap;
};
sort_info g_SortInfo;
int sort1d_amx_custom(const void *elem1, const void *elem2)
{
cell_t c1 = *(cell_t *)elem1;
cell_t c2 = *(cell_t *)elem2;
cell_t result = 0;
IPluginFunction *pf = g_SortInfo.pFunc;
pf->PushCell(c1);
pf->PushCell(c2);
pf->PushCell(g_SortInfo.array_addr);
pf->PushCell(g_SortInfo.hndl);
pf->Execute(&result);
return result;
}
static cell_t sm_SortCustom1D(IPluginContext *pContext, const cell_t *params)
{
cell_t *array;
cell_t array_size = params[2];
IPluginFunction *pFunction = pContext->GetFunctionById(params[3]);
if (!pFunction)
{
return pContext->ThrowNativeError("Function %x is not a valid function", params[3]);
}
pContext->LocalToPhysAddr(params[1], &array);
sort_info oldinfo = g_SortInfo;
g_SortInfo.hndl = params[4];
g_SortInfo.array_addr = params[1];
g_SortInfo.array_remap = NULL;
g_SortInfo.array_base = NULL;
g_SortInfo.pFunc = pFunction;
qsort(array, array_size, sizeof(cell_t), sort1d_amx_custom);
g_SortInfo = oldinfo;
return 1;
}
int sort2d_amx_custom(const void *elem1, const void *elem2)
{
cell_t c1 = *(cell_t *)elem1;
cell_t c2 = *(cell_t *)elem2;
cell_t c1_addr = g_SortInfo.array_addr + (c1 * sizeof(cell_t)) + g_SortInfo.array_remap[c1];
cell_t c2_addr = g_SortInfo.array_addr + (c2 * sizeof(cell_t)) + g_SortInfo.array_remap[c2];
IPluginContext *pContext = g_SortInfo.pFunc->GetParentContext();
cell_t *c1_r, *c2_r;
pContext->LocalToPhysAddr(c1_addr, &c1_r);
pContext->LocalToPhysAddr(c2_addr, &c2_r);
cell_t result = 0;
g_SortInfo.pFunc->PushCell(c1_addr);
g_SortInfo.pFunc->PushCell(c2_addr);
g_SortInfo.pFunc->PushCell(g_SortInfo.array_addr);
g_SortInfo.pFunc->PushCell(g_SortInfo.hndl);
g_SortInfo.pFunc->Execute(&result);
return result;
}
static cell_t sm_SortCustom2D(IPluginContext *pContext, const cell_t *params)
{
cell_t *array;
cell_t array_size = params[2];
IPluginFunction *pFunction;
pContext->LocalToPhysAddr(params[1], &array);
if ((pFunction=pContext->GetFunctionById(params[3])) == NULL)
{
return pContext->ThrowNativeError("Function %x is not a valid function", params[3]);
}
/** back up the old indices, replace the indices with something easier */
cell_t amx_addr, *phys_addr;
int err;
if ((err=pContext->HeapAlloc(array_size, &amx_addr, &phys_addr)) != SP_ERROR_NONE)
{
pContext->ThrowNativeErrorEx(err, "Ran out of memory to sort");
return 0;
}
sort_info oldinfo = g_SortInfo;
g_SortInfo.pFunc = pFunction;
g_SortInfo.hndl = params[4];
g_SortInfo.array_addr = params[1];
/** Same process as in strings, back up the old indices for later fixup */
g_SortInfo.array_base = array;
g_SortInfo.array_remap = phys_addr;
for (int i=0; i<array_size; i++)
{
phys_addr[i] = array[i];
array[i] = i;
}
qsort(array, array_size, sizeof(cell_t), sort2d_amx_custom);
/** Fixup process! */
for (int i=0; i<array_size; i++)
{
/* Compute the final address of the old array and subtract the new location.
* This is the fixed up distance.
*/
array[i] = ((char *)&array[array[i]] + phys_addr[array[i]]) - (char *)&array[i];
}
pContext->HeapPop(amx_addr);
g_SortInfo = oldinfo;
return 1;
}
enum SortType
{
Sort_Integer = 0,
Sort_Float,
Sort_String,
};
int sort_adtarray_strings_asc(const void *str1, const void *str2)
{
return strcmp((char *) str1, (char *) str2);
}
int sort_adtarray_strings_desc(const void *str1, const void *str2)
{
return strcmp((char *) str2, (char *) str1);
}
void sort_adt_random(CellArray *cArray)
{
size_t arraysize = cArray->size();
srand((unsigned int)time(NULL));
for (int i = arraysize-1; i > 0; i--)
{
int n = (rand() % i) + 1;
cArray->swap(i, n);
}
}
static cell_t sm_SortADTArray(IPluginContext *pContext, const cell_t *params)
{
CellArray *cArray;
HandleError err;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&cArray))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
cell_t order = params[2];
if (order == Sort_Random)
{
sort_adt_random(cArray);
return 1;
}
cell_t type = params[3];
size_t arraysize = cArray->size();
size_t blocksize = cArray->blocksize();
cell_t *array = cArray->base();
if (type == Sort_Integer)
{
if (order == Sort_Ascending)
{
qsort(array, arraysize, blocksize * sizeof(cell_t), sort_ints_asc);
}
else
{
qsort(array, arraysize, blocksize * sizeof(cell_t), sort_ints_desc);
}
}
else if (type == Sort_Float)
{
if (order == Sort_Ascending)
{
qsort(array, arraysize, blocksize * sizeof(cell_t), sort_floats_asc);
}
else
{
qsort(array, arraysize, blocksize * sizeof(cell_t), sort_floats_desc);
}
}
else if (type == Sort_String)
{
if (order == Sort_Ascending)
{
qsort(array, arraysize, blocksize * sizeof(cell_t), sort_adtarray_strings_asc);
}
else
{
qsort(array, arraysize, blocksize * sizeof(cell_t), sort_adtarray_strings_desc);
}
}
return 1;
}
struct sort_infoADT
{
IPluginFunction *pFunc;
cell_t *array_base;
cell_t array_bsize;
Handle_t array_hndl;
Handle_t hndl;
};
sort_infoADT g_SortInfoADT;
int sort_adtarray_custom(const void *elem1, const void *elem2)
{
cell_t result = 0;
IPluginFunction *pf = g_SortInfoADT.pFunc;
pf->PushCell(((cell_t) ((cell_t *) elem1 - g_SortInfoADT.array_base)) / g_SortInfoADT.array_bsize);
pf->PushCell(((cell_t) ((cell_t *) elem2 - g_SortInfoADT.array_base)) / g_SortInfoADT.array_bsize);
pf->PushCell(g_SortInfoADT.array_hndl);
pf->PushCell(g_SortInfoADT.hndl);
pf->Execute(&result);
return result;
}
static cell_t sm_SortADTArrayCustom(IPluginContext *pContext, const cell_t *params)
{
CellArray *cArray;
HandleError err;
HandleSecurity sec(pContext->GetIdentity(), g_pCoreIdent);
if ((err = handlesys->ReadHandle(params[1], htCellArray, &sec, (void **)&cArray))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid Handle %x (error: %d)", params[1], err);
}
IPluginFunction *pFunction = pContext->GetFunctionById(params[2]);
if (!pFunction)
{
return pContext->ThrowNativeError("Function %x is not a valid function", params[2]);
}
size_t arraysize = cArray->size();
size_t blocksize = cArray->blocksize();
cell_t *array = cArray->base();
sort_infoADT oldinfo = g_SortInfoADT;
g_SortInfoADT.pFunc = pFunction;
g_SortInfoADT.array_base = array;
g_SortInfoADT.array_bsize = (cell_t) blocksize;
g_SortInfoADT.array_hndl = params[1];
g_SortInfoADT.hndl = params[3];
qsort(array, arraysize, blocksize * sizeof(cell_t), sort_adtarray_custom);
g_SortInfoADT = oldinfo;
return 1;
}
REGISTER_NATIVES(sortNatives)
{
{"SortIntegers", sm_SortIntegers},
{"SortFloats", sm_SortFloats},
{"SortStrings", sm_SortStrings},
{"SortCustom1D", sm_SortCustom1D},
{"SortCustom2D", sm_SortCustom2D},
{"SortADTArray", sm_SortADTArray},
{"SortADTArrayCustom", sm_SortADTArrayCustom},
{NULL, NULL},
};
+325
View File
@@ -0,0 +1,325 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#include "common_logic.h"
#include <ITextParsers.h>
#include <ISourceMod.h>
HandleType_t g_TypeSMC = 0;
class ParseInfo : public ITextListener_SMC
{
public:
ParseInfo()
{
parse_start = NULL;
parse_end = NULL;
new_section = NULL;
key_value = NULL;
end_section = NULL;
raw_line = NULL;
handle = 0;
}
public:
void ReadSMC_ParseStart()
{
if (parse_start)
{
cell_t result;
parse_start->PushCell(handle);
parse_start->Execute(&result);
}
}
void ReadSMC_ParseEnd(bool halted, bool failed)
{
if (parse_end)
{
cell_t result;
parse_end->PushCell(handle);
parse_end->PushCell(halted ? 1 : 0);
parse_end->PushCell(failed ? 1 : 0);
parse_end->Execute(&result);
}
}
SMCResult ReadSMC_NewSection(const SMCStates *states, const char *name)
{
cell_t result = SMCResult_Continue;
if (new_section)
{
new_section->PushCell(handle);
new_section->PushString(name);
new_section->PushCell(1);
new_section->Execute(&result);
}
return (SMCResult)result;
}
SMCResult ReadSMC_KeyValue(const SMCStates *states, const char *key, const char *value)
{
cell_t result = SMCResult_Continue;
if (key_value)
{
key_value->PushCell(handle);
key_value->PushString(key);
key_value->PushString(value);
key_value->PushCell(1);
key_value->PushCell(1);
key_value->Execute(&result);
}
return (SMCResult)result;
}
SMCResult ReadSMC_LeavingSection(const SMCStates *states)
{
cell_t result = SMCResult_Continue;
if (end_section)
{
end_section->PushCell(handle);
end_section->Execute(&result);
}
return (SMCResult)result;
}
SMCResult ReadSMC_RawLine(const SMCStates *states, const char *line)
{
cell_t result = SMCResult_Continue;
if (raw_line)
{
raw_line->PushCell(handle);
raw_line->PushString(line);
raw_line->PushCell(states->line);
raw_line->Execute(&result);
}
return (SMCResult)result;
}
public:
IPluginFunction *parse_start;
IPluginFunction *parse_end;
IPluginFunction *new_section;
IPluginFunction *key_value;
IPluginFunction *end_section;
IPluginFunction *raw_line;
Handle_t handle;
};
class TextParseGlobals :
public SMGlobalClass,
public IHandleTypeDispatch
{
public:
void OnSourceModAllInitialized()
{
HandleAccess sec;
/* These cannot be cloned, because they are locked to a specific plugin.
* However, we let anyone read them because we don't care.
*/
handlesys->InitAccessDefaults(NULL, &sec);
sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
sec.access[HandleAccess_Read] = 0;
g_TypeSMC = handlesys->CreateType("SMCParser", this, 0, NULL, &sec, g_pCoreIdent, NULL);
}
void OnSourceModShutdown()
{
handlesys->RemoveType(g_TypeSMC, g_pCoreIdent);
}
void OnHandleDestroy(HandleType_t type, void *object)
{
ParseInfo *parse = (ParseInfo *)object;
delete parse;
}
bool GetHandleApproxSize(HandleType_t type, void *object, unsigned int *pSize)
{
*pSize = sizeof(ParseInfo);
return true;
}
};
TextParseGlobals g_TextParseGlobals;
static cell_t SMC_CreateParser(IPluginContext *pContext, const cell_t *params)
{
ParseInfo *pInfo = new ParseInfo();
Handle_t hndl = handlesys->CreateHandle(g_TypeSMC, pInfo, pContext->GetIdentity(), g_pCoreIdent, NULL);
/* Should never happen */
if (!hndl)
{
delete pInfo;
return 0;
}
pInfo->handle = hndl;
return hndl;
}
static cell_t SMC_SetParseStart(IPluginContext *pContext, const cell_t *params)
{
Handle_t hndl = (Handle_t)params[1];
HandleError err;
ParseInfo *parse;
if ((err=handlesys->ReadHandle(hndl, g_TypeSMC, NULL, (void **)&parse))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid SMC Parse Handle %x (error %d)", hndl, err);
}
parse->parse_start = pContext->GetFunctionById((funcid_t)params[2]);
return 1;
}
static cell_t SMC_SetParseEnd(IPluginContext *pContext, const cell_t *params)
{
Handle_t hndl = (Handle_t)params[1];
HandleError err;
ParseInfo *parse;
if ((err=handlesys->ReadHandle(hndl, g_TypeSMC, NULL, (void **)&parse))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid SMC Parse Handle %x (error %d)", hndl, err);
}
parse->parse_end = pContext->GetFunctionById((funcid_t)params[2]);
return 1;
}
static cell_t SMC_SetReaders(IPluginContext *pContext, const cell_t *params)
{
Handle_t hndl = (Handle_t)params[1];
HandleError err;
ParseInfo *parse;
if ((err=handlesys->ReadHandle(hndl, g_TypeSMC, NULL, (void **)&parse))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid SMC Parse Handle %x (error %d)", hndl, err);
}
parse->new_section = pContext->GetFunctionById((funcid_t)params[2]);
parse->key_value = pContext->GetFunctionById((funcid_t)params[3]);
parse->end_section = pContext->GetFunctionById((funcid_t)params[4]);
return 1;
}
static cell_t SMC_SetRawLine(IPluginContext *pContext, const cell_t *params)
{
Handle_t hndl = (Handle_t)params[1];
HandleError err;
ParseInfo *parse;
if ((err=handlesys->ReadHandle(hndl, g_TypeSMC, NULL, (void **)&parse))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid SMC Parse Handle %x (error %d)", hndl, err);
}
parse->raw_line = pContext->GetFunctionById((funcid_t)params[2]);
return 1;
}
static cell_t SMC_ParseFile(IPluginContext *pContext, const cell_t *params)
{
Handle_t hndl = (Handle_t)params[1];
HandleError err;
ParseInfo *parse;
if ((err=handlesys->ReadHandle(hndl, g_TypeSMC, NULL, (void **)&parse))
!= HandleError_None)
{
return pContext->ThrowNativeError("Invalid SMC Parse Handle %x (error %d)", hndl, err);
}
char *file;
pContext->LocalToString(params[2], &file);
char path[PLATFORM_MAX_PATH];
g_pSM->BuildPath(Path_Game, path, sizeof(path), "%s", file);
SMCStates states;
SMCError p_err = textparsers->ParseFile_SMC(path, parse, &states);
cell_t *c_line, *c_col;
pContext->LocalToPhysAddr(params[3], &c_line);
pContext->LocalToPhysAddr(params[4], &c_col);
*c_line = states.line;
*c_col = states.col;
return (cell_t)p_err;
}
static cell_t SMC_GetErrorString(IPluginContext *pContext, const cell_t *params)
{
const char *str = textparsers->GetSMCErrorString((SMCError)params[1]);
if (!str)
{
return 0;
}
pContext->StringToLocal(params[2], params[3], str);
return 1;
}
REGISTER_NATIVES(textNatives)
{
{"SMC_CreateParser", SMC_CreateParser},
{"SMC_ParseFile", SMC_ParseFile},
{"SMC_GetErrorString", SMC_GetErrorString},
{"SMC_SetParseStart", SMC_SetParseStart},
{"SMC_SetParseEnd", SMC_SetParseEnd},
{"SMC_SetReaders", SMC_SetReaders},
{"SMC_SetRawLine", SMC_SetRawLine},
{NULL, NULL},
};
+44
View File
@@ -0,0 +1,44 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod GeoIP Extension
* Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
/**
* Autogenerated by build scripts
*/
#ifndef _INCLUDE_GEOIP_VERSION_H_
#define _INCLUDE_GEOIP_VERSION_H_
#define SM_BUILD_STRING "-dev"
#define SM_BUILD_UNIQUEID "2650:5d34bc3edbfa" SM_BUILD_STRING
#define SVN_FULL_VERSION "1.3.0" SM_BUILD_STRING
#define SVN_FILE_VERSION 1,3,0,0
#endif //_INCLUDE_GEOIP_VERSION_H_
+44
View File
@@ -0,0 +1,44 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod GeoIP Extension
* Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
/**
* Autogenerated by build scripts
*/
#ifndef _INCLUDE_LOGIC_VERSION_H_
#define _INCLUDE_LOGIC_VERSION_H_
#define SM_BUILD_STRING "$BUILD_STRING$"
#define SM_BUILD_UNIQUEID "$BUILD_ID$" SM_BUILD_STRING
#define SVN_FULL_VERSION "$PMAJOR$.$PMINOR$.$PREVISION$" SM_BUILD_STRING
#define SVN_FILE_VERSION $PMAJOR$,$PMINOR$,$PREVISION$,0
#endif //_INCLUDE_LOGIC_VERSION_H_
+303
View File
@@ -0,0 +1,303 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#include "BaseWorker.h"
BaseWorker::BaseWorker(IThreadWorkerCallbacks *hooks) :
m_perFrame(SM_DEFAULT_THREADS_PER_FRAME),
m_state(Worker_Stopped),
m_pHooks(hooks)
{
}
BaseWorker::~BaseWorker()
{
if (m_state != Worker_Stopped || m_state != Worker_Invalid)
Stop(true);
if (m_ThreadQueue.size())
Flush(true);
}
void BaseWorker::MakeThread(IThread *pThread)
{
ThreadParams pt;
pt.flags = Thread_AutoRelease;
pt.prio = ThreadPrio_Normal;
MakeThread(pThread, &pt);
}
IThreadHandle *BaseWorker::MakeThread(IThread *pThread, ThreadFlags flags)
{
ThreadParams pt;
pt.flags = flags;
pt.prio = ThreadPrio_Normal;
return MakeThread(pThread, &pt);
}
IThreadHandle *BaseWorker::MakeThread(IThread *pThread, const ThreadParams *params)
{
if (m_state != Worker_Running)
return NULL;
SWThreadHandle *swt = new SWThreadHandle(this, params, pThread);
AddThreadToQueue(swt);
return swt;
}
void BaseWorker::GetPriorityBounds(ThreadPriority &max, ThreadPriority &min)
{
max = ThreadPrio_Normal;
min = ThreadPrio_Normal;
}
unsigned int BaseWorker::Flush(bool flush_cancel)
{
SWThreadHandle *swt;
unsigned int num = 0;
while ((swt=PopThreadFromQueue()) != NULL)
{
swt->m_state = Thread_Done;
if (!flush_cancel)
swt->pThread->RunThread(swt);
swt->pThread->OnTerminate(swt, flush_cancel);
if (swt->m_params.flags & Thread_AutoRelease)
delete swt;
num++;
}
return num;
}
SWThreadHandle *BaseWorker::PopThreadFromQueue()
{
if (!m_ThreadQueue.size())
return NULL;
SourceHook::List<SWThreadHandle *>::iterator begin;
SWThreadHandle *swt;
begin = m_ThreadQueue.begin();
swt = (*begin);
m_ThreadQueue.erase(begin);
return swt;
}
void BaseWorker::AddThreadToQueue(SWThreadHandle *pHandle)
{
m_ThreadQueue.push_back(pHandle);
}
unsigned int BaseWorker::GetMaxThreadsPerFrame()
{
return m_perFrame;
}
WorkerState BaseWorker::GetStatus(unsigned int *threads)
{
if (threads)
*threads = m_perFrame;
return m_state;
}
unsigned int BaseWorker::RunFrame()
{
unsigned int done = 0;
unsigned int max = GetMaxThreadsPerFrame();
SWThreadHandle *swt = NULL;
IThread *pThread = NULL;
while (done < max)
{
if ((swt=PopThreadFromQueue()) == NULL)
{
break;
}
pThread = swt->pThread;
swt->m_state = Thread_Running;
pThread->RunThread(swt);
swt->m_state = Thread_Done;
pThread->OnTerminate(swt, false);
if (swt->m_params.flags & Thread_AutoRelease)
{
delete swt;
}
done++;
}
return done;
}
void BaseWorker::SetMaxThreadsPerFrame(unsigned int threads)
{
m_perFrame = threads;
}
bool BaseWorker::Start()
{
if (m_state != Worker_Invalid && m_state != Worker_Stopped)
{
return false;
}
m_state = Worker_Running;
if (m_pHooks)
{
m_pHooks->OnWorkerStart(this);
}
return true;
}
bool BaseWorker::Stop(bool flush_cancel)
{
if (m_state == Worker_Invalid || m_state == Worker_Stopped)
{
return false;
}
if (m_state == Worker_Paused)
{
if (!Unpause())
{
return false;
}
}
m_state = Worker_Stopped;
Flush(flush_cancel);
if (m_pHooks)
{
m_pHooks->OnWorkerStop(this);
}
return true;
}
bool BaseWorker::Pause()
{
if (m_state != Worker_Running)
{
return false;
}
m_state = Worker_Paused;
return true;
}
bool BaseWorker::Unpause()
{
if (m_state != Worker_Paused)
{
return false;
}
m_state = Worker_Running;
return true;
}
/***********************
* THREAD HANDLE STUFF *
***********************/
void SWThreadHandle::DestroyThis()
{
delete this;
}
void SWThreadHandle::GetParams(ThreadParams *p)
{
*p = m_params;
}
ThreadPriority SWThreadHandle::GetPriority()
{
return m_params.prio;
}
ThreadState SWThreadHandle::GetState()
{
return m_state;
}
IThreadCreator *SWThreadHandle::Parent()
{
return m_parent;
}
bool SWThreadHandle::SetPriority(ThreadPriority prio)
{
if (m_params.prio != ThreadPrio_Normal)
return false;
m_params.prio = prio;
return true;
}
bool SWThreadHandle::Unpause()
{
if (m_state != Thread_Paused)
return false;
m_state = Thread_Running;
return true;
}
bool SWThreadHandle::WaitForThread()
{
return false;
}
SWThreadHandle::SWThreadHandle(IThreadCreator *parent, const ThreadParams *p, IThread *thread) :
m_state(Thread_Paused), m_params(*p), m_parent(parent), pThread(thread)
{
}
IThread *SWThreadHandle::GetThread()
{
return pThread;
}
+104
View File
@@ -0,0 +1,104 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#ifndef _INCLUDE_SOURCEMOD_BASEWORKER_H
#define _INCLUDE_SOURCEMOD_BASEWORKER_H
#include "sh_list.h"
#include "ThreadSupport.h"
#define SM_DEFAULT_THREADS_PER_FRAME 1
class BaseWorker;
//SW = Simple Wrapper
class SWThreadHandle : public IThreadHandle
{
friend class BaseWorker;
public:
SWThreadHandle(IThreadCreator *parent, const ThreadParams *p, IThread *thread);
IThread *GetThread();
public:
//NOTE: We don't support this by default.
//It's specific usage that'd require many mutexes
virtual bool WaitForThread();
public:
virtual void DestroyThis();
virtual IThreadCreator *Parent();
virtual void GetParams(ThreadParams *ptparams);
public:
//Priorities not supported by default.
virtual ThreadPriority GetPriority();
virtual bool SetPriority(ThreadPriority prio);
public:
virtual ThreadState GetState();
virtual bool Unpause();
private:
ThreadState m_state;
ThreadParams m_params;
IThreadCreator *m_parent;
IThread *pThread;
};
class BaseWorker : public IThreadWorker
{
public:
BaseWorker(IThreadWorkerCallbacks *hooks);
virtual ~BaseWorker();
public: //IWorker
virtual unsigned int RunFrame();
//Controls the worker
virtual bool Pause();
virtual bool Unpause();
virtual bool Start();
virtual bool Stop(bool flush_cancel);
//Flushes out any remaining threads
virtual unsigned int Flush(bool flush_cancel);
//returns status and number of threads in queue
virtual WorkerState GetStatus(unsigned int *numThreads);
public: //IThreadCreator
virtual void MakeThread(IThread *pThread);
virtual IThreadHandle *MakeThread(IThread *pThread, ThreadFlags flags);
virtual IThreadHandle *MakeThread(IThread *pThread, const ThreadParams *params);
virtual void GetPriorityBounds(ThreadPriority &max, ThreadPriority &min);
public: //BaseWorker
virtual void AddThreadToQueue(SWThreadHandle *pHandle);
virtual SWThreadHandle *PopThreadFromQueue();
virtual void SetMaxThreadsPerFrame(unsigned int threads);
virtual unsigned int GetMaxThreadsPerFrame();
protected:
SourceHook::List<SWThreadHandle *> m_ThreadQueue;
unsigned int m_perFrame;
volatile WorkerState m_state;
IThreadWorkerCallbacks *m_pHooks;
};
#endif //_INCLUDE_SOURCEMOD_BASEWORKER_H
+309
View File
@@ -0,0 +1,309 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#include <unistd.h>
#include "PosixThreads.h"
#include "ThreadWorker.h"
IThreadWorker *PosixThreader::MakeWorker(IThreadWorkerCallbacks *hooks, bool threaded)
{
if (threaded)
{
return new ThreadWorker(hooks, this, DEFAULT_THINK_TIME_MS);
} else {
return new BaseWorker(hooks);
}
}
void PosixThreader::DestroyWorker(IThreadWorker *pWorker)
{
delete pWorker;
}
void PosixThreader::ThreadSleep(unsigned int ms)
{
usleep( ms * 1000 );
}
void PosixThreader::GetPriorityBounds(ThreadPriority &max, ThreadPriority &min)
{
max = ThreadPrio_Normal;
min = ThreadPrio_Normal;
}
IMutex *PosixThreader::MakeMutex()
{
pthread_mutex_t mutex;
if (pthread_mutex_init(&mutex, NULL) != 0)
return NULL;
PosixMutex *pMutex = new PosixMutex(mutex);
return pMutex;
}
void PosixThreader::MakeThread(IThread *pThread)
{
ThreadParams defparams;
defparams.flags = Thread_AutoRelease;
defparams.prio = ThreadPrio_Normal;
MakeThread(pThread, &defparams);
}
IThreadHandle *PosixThreader::MakeThread(IThread *pThread, ThreadFlags flags)
{
ThreadParams defparams;
defparams.flags = flags;
defparams.prio = ThreadPrio_Normal;
return MakeThread(pThread, &defparams);
}
void *Posix_ThreadGate(void *param)
{
PosixThreader::ThreadHandle *pHandle =
reinterpret_cast<PosixThreader::ThreadHandle *>(param);
//Block this thread from being started initially.
pthread_mutex_lock(&pHandle->m_runlock);
//if we get here, we've obtained the lock and are allowed to run.
//unlock and continue.
pthread_mutex_unlock(&pHandle->m_runlock);
pHandle->m_run->RunThread(pHandle);
ThreadParams params;
pthread_mutex_lock(&pHandle->m_statelock);
pHandle->m_state = Thread_Done;
pHandle->GetParams(&params);
pthread_mutex_unlock(&pHandle->m_statelock);
pHandle->m_run->OnTerminate(pHandle, false);
if (params.flags & Thread_AutoRelease)
delete pHandle;
return 0;
}
ThreadParams g_defparams;
IThreadHandle *PosixThreader::MakeThread(IThread *pThread, const ThreadParams *params)
{
if (params == NULL)
params = &g_defparams;
PosixThreader::ThreadHandle *pHandle =
new PosixThreader::ThreadHandle(this, pThread, params);
pthread_mutex_lock(&pHandle->m_runlock);
int err;
err = pthread_create(&pHandle->m_thread, NULL, Posix_ThreadGate, (void *)pHandle);
if (err != 0)
{
pthread_mutex_unlock(&pHandle->m_runlock);
delete pHandle;
return NULL;
}
//Don't bother setting priority...
if (!(pHandle->m_params.flags & Thread_CreateSuspended))
{
pHandle->m_state = Thread_Running;
err = pthread_mutex_unlock(&pHandle->m_runlock);
if (err != 0)
pHandle->m_state = Thread_Paused;
}
return pHandle;
}
IEventSignal *PosixThreader::MakeEventSignal()
{
return new PosixEventSignal();
}
/*****************
**** Mutexes ****
*****************/
PosixThreader::PosixMutex::~PosixMutex()
{
pthread_mutex_destroy(&m_mutex);
}
bool PosixThreader::PosixMutex::TryLock()
{
int err = pthread_mutex_trylock(&m_mutex);
return (err == 0);
}
void PosixThreader::PosixMutex::Lock()
{
pthread_mutex_lock(&m_mutex);
}
void PosixThreader::PosixMutex::Unlock()
{
pthread_mutex_unlock(&m_mutex);
}
void PosixThreader::PosixMutex::DestroyThis()
{
delete this;
}
/******************
* Thread Handles *
******************/
PosixThreader::ThreadHandle::ThreadHandle(IThreader *parent, IThread *run, const ThreadParams *params) :
m_parent(parent), m_params(*params), m_run(run), m_state(Thread_Paused)
{
pthread_mutex_init(&m_runlock, NULL);
pthread_mutex_init(&m_statelock, NULL);
}
PosixThreader::ThreadHandle::~ThreadHandle()
{
pthread_mutex_destroy(&m_runlock);
pthread_mutex_destroy(&m_statelock);
}
bool PosixThreader::ThreadHandle::WaitForThread()
{
void *arg;
if (pthread_join(m_thread, &arg) != 0)
return false;
return true;
}
ThreadState PosixThreader::ThreadHandle::GetState()
{
ThreadState state;
pthread_mutex_lock(&m_statelock);
state = m_state;
pthread_mutex_unlock(&m_statelock);
return state;
}
IThreadCreator *PosixThreader::ThreadHandle::Parent()
{
return m_parent;
}
void PosixThreader::ThreadHandle::DestroyThis()
{
if (m_params.flags & Thread_AutoRelease)
return;
delete this;
}
void PosixThreader::ThreadHandle::GetParams(ThreadParams *ptparams)
{
if (!ptparams)
return;
*ptparams = m_params;
}
ThreadPriority PosixThreader::ThreadHandle::GetPriority()
{
return ThreadPrio_Normal;
}
bool PosixThreader::ThreadHandle::SetPriority(ThreadPriority prio)
{
return (prio == ThreadPrio_Normal);
}
bool PosixThreader::ThreadHandle::Unpause()
{
if (m_state != Thread_Paused)
return false;
m_state = Thread_Running;
if (pthread_mutex_unlock(&m_runlock) != 0)
{
m_state = Thread_Paused;
return false;
}
return true;
}
/*****************
* EVENT SIGNALS *
*****************/
PosixThreader::PosixEventSignal::PosixEventSignal()
{
pthread_cond_init(&m_cond, NULL);
pthread_mutex_init(&m_mutex, NULL);
}
PosixThreader::PosixEventSignal::~PosixEventSignal()
{
pthread_cond_destroy(&m_cond);
pthread_mutex_destroy(&m_mutex);
}
void PosixThreader::PosixEventSignal::Wait()
{
pthread_mutex_lock(&m_mutex);
pthread_cond_wait(&m_cond, &m_mutex);
pthread_mutex_unlock(&m_mutex);
}
void PosixThreader::PosixEventSignal::Signal()
{
pthread_mutex_lock(&m_mutex);
pthread_cond_broadcast(&m_cond);
pthread_mutex_unlock(&m_mutex);
}
void PosixThreader::PosixEventSignal::DestroyThis()
{
delete this;
}
+115
View File
@@ -0,0 +1,115 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#ifndef _INCLUDE_POSIXTHREADS_H_
#define _INCLUDE_POSIXTHREADS_H_
#include <pthread.h>
#include "IThreader.h"
using namespace SourceMod;
void *Posix_ThreadGate(void *param);
class PosixThreader : public IThreader
{
public:
class ThreadHandle : public IThreadHandle
{
friend class PosixThreader;
friend void *Posix_ThreadGate(void *param);
public:
ThreadHandle(IThreader *parent, IThread *run, const ThreadParams *params);
virtual ~ThreadHandle();
public:
virtual bool WaitForThread();
virtual void DestroyThis();
virtual IThreadCreator *Parent();
virtual void GetParams(ThreadParams *ptparams);
virtual ThreadPriority GetPriority();
virtual bool SetPriority(ThreadPriority prio);
virtual ThreadState GetState();
virtual bool Unpause();
protected:
IThreader *m_parent; //Parent handle
pthread_t m_thread; //Windows HANDLE
ThreadParams m_params; //Current Parameters
IThread *m_run; //Runnable context
pthread_mutex_t m_statelock;
pthread_mutex_t m_runlock;
ThreadState m_state; //internal state
};
class PosixMutex : public IMutex
{
public:
PosixMutex(pthread_mutex_t m) : m_mutex(m)
{
};
virtual ~PosixMutex();
public:
virtual bool TryLock();
virtual void Lock();
virtual void Unlock();
virtual void DestroyThis();
protected:
pthread_mutex_t m_mutex;
};
class PosixEventSignal : public IEventSignal
{
public:
PosixEventSignal();
virtual ~PosixEventSignal();
public:
virtual void Wait();
virtual void Signal();
virtual void DestroyThis();
protected:
pthread_cond_t m_cond;
pthread_mutex_t m_mutex;
};
public:
IMutex *MakeMutex();
void MakeThread(IThread *pThread);
IThreadHandle *MakeThread(IThread *pThread, ThreadFlags flags);
IThreadHandle *MakeThread(IThread *pThread, const ThreadParams *params);
void GetPriorityBounds(ThreadPriority &max, ThreadPriority &min);
void ThreadSleep(unsigned int ms);
IEventSignal *MakeEventSignal();
IThreadWorker *MakeWorker(IThreadWorkerCallbacks *hooks, bool threaded);
void DestroyWorker(IThreadWorker *pWorker);
};
#if defined SM_DEFAULT_THREADER && !defined SM_MAIN_THREADER
#define SM_MAIN_THREADER PosixThreader;
typedef class PosixThreader MainThreader;
#endif
#endif //_INCLUDE_POSIXTHREADS_H_
+320
View File
@@ -0,0 +1,320 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#include "ThreadWorker.h"
ThreadWorker::ThreadWorker(IThreadWorkerCallbacks *hooks) : BaseWorker(hooks),
m_Threader(NULL),
m_QueueLock(NULL),
m_StateLock(NULL),
m_PauseSignal(NULL),
m_AddSignal(NULL),
me(NULL),
m_think_time(DEFAULT_THINK_TIME_MS)
{
m_state = Worker_Invalid;
}
ThreadWorker::ThreadWorker(IThreadWorkerCallbacks *hooks, IThreader *pThreader, unsigned int thinktime) :
BaseWorker(hooks),
m_Threader(pThreader),
m_QueueLock(NULL),
m_StateLock(NULL),
m_PauseSignal(NULL),
m_AddSignal(NULL),
me(NULL),
m_think_time(thinktime)
{
if (m_Threader)
{
m_state = Worker_Stopped;
} else {
m_state = Worker_Invalid;
}
}
ThreadWorker::~ThreadWorker()
{
if (m_state != Worker_Stopped || m_state != Worker_Invalid)
{
Stop(true);
}
if (m_ThreadQueue.size())
{
Flush(true);
}
}
void ThreadWorker::OnTerminate(IThreadHandle *pHandle, bool cancel)
{
//we don't particularly care
return;
}
void ThreadWorker::RunThread(IThreadHandle *pHandle)
{
WorkerState this_state = Worker_Running;
size_t num;
if (m_pHooks)
{
m_pHooks->OnWorkerStart(this);
}
while (true)
{
/**
* Check number of items in the queue
*/
m_StateLock->Lock();
this_state = m_state;
m_StateLock->Unlock();
if (this_state != Worker_Stopped)
{
m_QueueLock->Lock();
num = m_ThreadQueue.size();
if (!num)
{
/**
* if none, wait for an item
*/
m_Waiting = true;
m_QueueLock->Unlock();
/* first check if we should end again */
if (this_state == Worker_Stopped)
{
break;
}
m_AddSignal->Wait();
m_Waiting = false;
} else {
m_QueueLock->Unlock();
}
}
m_StateLock->Lock();
this_state = m_state;
m_StateLock->Unlock();
if (this_state != Worker_Running)
{
if (this_state == Worker_Paused || this_state == Worker_Stopped)
{
//wait until the lock is cleared.
if (this_state == Worker_Paused)
{
m_PauseSignal->Wait();
}
if (this_state == Worker_Stopped)
{
//if we're supposed to flush cleanrly,
// run all of the remaining frames first.
if (!m_FlushType)
{
while (m_ThreadQueue.size())
{
RunFrame();
}
}
break;
}
}
}
/**
* Run the frame.
*/
RunFrame();
/**
* wait in between threads if specified
*/
if (m_think_time)
{
m_Threader->ThreadSleep(m_think_time);
}
}
if (m_pHooks)
{
m_pHooks->OnWorkerStop(this);
}
}
SWThreadHandle *ThreadWorker::PopThreadFromQueue()
{
if (m_state <= Worker_Stopped && !m_QueueLock)
{
return NULL;
}
SWThreadHandle *swt;
m_QueueLock->Lock();
swt = BaseWorker::PopThreadFromQueue();
m_QueueLock->Unlock();
return swt;
}
void ThreadWorker::AddThreadToQueue(SWThreadHandle *pHandle)
{
if (m_state <= Worker_Stopped)
{
return;
}
m_QueueLock->Lock();
BaseWorker::AddThreadToQueue(pHandle);
if (m_Waiting)
{
m_AddSignal->Signal();
}
m_QueueLock->Unlock();
}
WorkerState ThreadWorker::GetStatus(unsigned int *threads)
{
WorkerState state;
m_StateLock->Lock();
state = BaseWorker::GetStatus(threads);
m_StateLock->Unlock();
return state;
}
bool ThreadWorker::Start()
{
if (m_state == Worker_Invalid)
{
if (m_Threader == NULL)
{
return false;
}
} else if (m_state != Worker_Stopped) {
return false;
}
m_Waiting = false;
m_QueueLock = m_Threader->MakeMutex();
m_StateLock = m_Threader->MakeMutex();
m_PauseSignal = m_Threader->MakeEventSignal();
m_AddSignal = m_Threader->MakeEventSignal();
m_state = Worker_Running;
ThreadParams pt;
pt.flags = Thread_Default;
pt.prio = ThreadPrio_Normal;
me = m_Threader->MakeThread(this, &pt);
return true;
}
bool ThreadWorker::Stop(bool flush_cancel)
{
if (m_state == Worker_Invalid || m_state == Worker_Stopped)
{
return false;
}
WorkerState oldstate;
//set new state
m_StateLock->Lock();
oldstate = m_state;
m_state = Worker_Stopped;
m_FlushType = flush_cancel;
m_StateLock->Unlock();
if (oldstate == Worker_Paused)
{
Unpause();
} else {
m_QueueLock->Lock();
if (m_Waiting)
{
m_AddSignal->Signal();
}
m_QueueLock->Unlock();
}
me->WaitForThread();
//destroy it
me->DestroyThis();
//flush all remaining events
Flush(true);
//free mutex locks
m_QueueLock->DestroyThis();
m_StateLock->DestroyThis();
m_PauseSignal->DestroyThis();
m_AddSignal->DestroyThis();
//invalidizzle
m_QueueLock = NULL;
m_StateLock = NULL;
m_PauseSignal = NULL;
m_AddSignal = NULL;
me = NULL;
return true;
}
bool ThreadWorker::Pause()
{
if (m_state != Worker_Running)
{
return false;
}
m_StateLock->Lock();
m_state = Worker_Paused;
m_StateLock->Unlock();
return true;
}
bool ThreadWorker::Unpause()
{
if (m_state != Worker_Paused)
{
return false;
}
m_StateLock->Lock();
m_state = Worker_Running;
m_StateLock->Unlock();
m_PauseSignal->Signal();
if (m_Waiting)
{
m_AddSignal->Signal();
}
return true;
}
+71
View File
@@ -0,0 +1,71 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#ifndef _INCLUDE_SOURCEMOD_THREADWORKER_H
#define _INCLUDE_SOURCEMOD_THREADWORKER_H
#include "BaseWorker.h"
#define DEFAULT_THINK_TIME_MS 50
class ThreadWorker : public BaseWorker, public IThread
{
public:
ThreadWorker(IThreadWorkerCallbacks *hooks);
ThreadWorker(IThreadWorkerCallbacks *hooks, IThreader *pThreader, unsigned int thinktime=DEFAULT_THINK_TIME_MS);
virtual ~ThreadWorker();
public: //IThread
virtual void OnTerminate(IThreadHandle *pHandle, bool cancel);
virtual void RunThread(IThreadHandle *pHandle);
public: //IWorker
//Controls the worker
virtual bool Pause();
virtual bool Unpause();
virtual bool Start();
virtual bool Stop(bool flush_cancel);
//returns status and number of threads in queue
virtual WorkerState GetStatus(unsigned int *numThreads);
public: //BaseWorker
virtual void AddThreadToQueue(SWThreadHandle *pHandle);
virtual SWThreadHandle *PopThreadFromQueue();
protected:
IThreader *m_Threader;
IMutex *m_QueueLock;
IMutex *m_StateLock;
IEventSignal *m_PauseSignal;
IEventSignal *m_AddSignal;
IThreadHandle *me;
unsigned int m_think_time;
volatile bool m_Waiting;
volatile bool m_FlushType;
};
#endif //_INCLUDE_SOURCEMOD_THREADWORKER_H
+320
View File
@@ -0,0 +1,320 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#define _WIN32_WINNT 0x0400
#include "WinThreads.h"
#include "ThreadWorker.h"
IThreadWorker *WinThreader::MakeWorker(IThreadWorkerCallbacks *hooks, bool threaded)
{
if (threaded)
{
return new ThreadWorker(hooks, this, DEFAULT_THINK_TIME_MS);
} else {
return new BaseWorker(hooks);
}
}
void WinThreader::DestroyWorker(IThreadWorker *pWorker)
{
delete pWorker;
}
void WinThreader::ThreadSleep(unsigned int ms)
{
Sleep((DWORD)ms);
}
IMutex *WinThreader::MakeMutex()
{
WinMutex *pMutex = new WinMutex();
return pMutex;
}
IThreadHandle *WinThreader::MakeThread(IThread *pThread, ThreadFlags flags)
{
ThreadParams defparams;
defparams.flags = flags;
defparams.prio = ThreadPrio_Normal;
return MakeThread(pThread, &defparams);
}
void WinThreader::MakeThread(IThread *pThread)
{
ThreadParams defparams;
defparams.flags = Thread_AutoRelease;
defparams.prio = ThreadPrio_Normal;
MakeThread(pThread, &defparams);
}
DWORD WINAPI Win32_ThreadGate(LPVOID param)
{
WinThreader::ThreadHandle *pHandle =
reinterpret_cast<WinThreader::ThreadHandle *>(param);
pHandle->m_run->RunThread(pHandle);
ThreadParams params;
EnterCriticalSection(&pHandle->m_crit);
pHandle->m_state = Thread_Done;
pHandle->GetParams(&params);
LeaveCriticalSection(&pHandle->m_crit);
pHandle->m_run->OnTerminate(pHandle, false);
if (params.flags & Thread_AutoRelease)
delete pHandle;
return 0;
}
void WinThreader::GetPriorityBounds(ThreadPriority &max, ThreadPriority &min)
{
max = ThreadPrio_Maximum;
min = ThreadPrio_Minimum;
}
ThreadParams g_defparams;
IThreadHandle *WinThreader::MakeThread(IThread *pThread, const ThreadParams *params)
{
if (params == NULL)
params = &g_defparams;
WinThreader::ThreadHandle *pHandle =
new WinThreader::ThreadHandle(this, NULL, pThread, params);
DWORD tid;
pHandle->m_thread =
CreateThread(NULL, 0, &Win32_ThreadGate, (LPVOID)pHandle, CREATE_SUSPENDED, &tid);
if (!pHandle->m_thread)
{
delete pHandle;
return NULL;
}
if (pHandle->m_params.prio != ThreadPrio_Normal)
{
pHandle->SetPriority(pHandle->m_params.prio);
}
if (!(pHandle->m_params.flags & Thread_CreateSuspended))
{
pHandle->Unpause();
}
return pHandle;
}
IEventSignal *WinThreader::MakeEventSignal()
{
HANDLE event = CreateEventA(NULL, FALSE, FALSE, NULL);
if (!event)
return NULL;
WinEvent *pEvent = new WinEvent(event);
return pEvent;
}
/*****************
**** Mutexes ****
*****************/
WinThreader::WinMutex::WinMutex()
{
InitializeCriticalSection(&m_crit);
}
WinThreader::WinMutex::~WinMutex()
{
DeleteCriticalSection(&m_crit);
}
bool WinThreader::WinMutex::TryLock()
{
return (TryEnterCriticalSection(&m_crit) != FALSE);
}
void WinThreader::WinMutex::Lock()
{
EnterCriticalSection(&m_crit);
}
void WinThreader::WinMutex::Unlock()
{
LeaveCriticalSection(&m_crit);
}
void WinThreader::WinMutex::DestroyThis()
{
delete this;
}
/******************
* Thread Handles *
******************/
WinThreader::ThreadHandle::ThreadHandle(IThreader *parent, HANDLE hthread, IThread *run, const ThreadParams *params) :
m_parent(parent), m_thread(hthread), m_run(run), m_params(*params),
m_state(Thread_Paused)
{
InitializeCriticalSection(&m_crit);
}
WinThreader::ThreadHandle::~ThreadHandle()
{
if (m_thread)
{
CloseHandle(m_thread);
m_thread = NULL;
}
DeleteCriticalSection(&m_crit);
}
bool WinThreader::ThreadHandle::WaitForThread()
{
if (m_thread == NULL)
return false;
if (WaitForSingleObject(m_thread, INFINITE) != 0)
return false;
return true;
}
ThreadState WinThreader::ThreadHandle::GetState()
{
ThreadState state;
EnterCriticalSection(&m_crit);
state = m_state;
LeaveCriticalSection(&m_crit);
return state;
}
IThreadCreator *WinThreader::ThreadHandle::Parent()
{
return m_parent;
}
void WinThreader::ThreadHandle::DestroyThis()
{
if (m_params.flags & Thread_AutoRelease)
return;
delete this;
}
void WinThreader::ThreadHandle::GetParams(ThreadParams *ptparams)
{
if (!ptparams)
return;
*ptparams = m_params;
}
ThreadPriority WinThreader::ThreadHandle::GetPriority()
{
return m_params.prio;
}
bool WinThreader::ThreadHandle::SetPriority(ThreadPriority prio)
{
if (!m_thread)
return false;
BOOL res = FALSE;
if (prio >= ThreadPrio_Maximum)
res = SetThreadPriority(m_thread, THREAD_PRIORITY_HIGHEST);
else if (prio <= ThreadPrio_Minimum)
res = SetThreadPriority(m_thread, THREAD_PRIORITY_LOWEST);
else if (prio == ThreadPrio_Normal)
res = SetThreadPriority(m_thread, THREAD_PRIORITY_NORMAL);
else if (prio == ThreadPrio_High)
res = SetThreadPriority(m_thread, THREAD_PRIORITY_ABOVE_NORMAL);
else if (prio == ThreadPrio_Low)
res = SetThreadPriority(m_thread, THREAD_PRIORITY_BELOW_NORMAL);
m_params.prio = prio;
return (res != FALSE);
}
bool WinThreader::ThreadHandle::Unpause()
{
if (!m_thread)
return false;
if (m_state != Thread_Paused)
return false;
m_state = Thread_Running;
if (ResumeThread(m_thread) == -1)
{
m_state = Thread_Paused;
return false;
}
return true;
}
/*****************
* EVENT SIGNALS *
*****************/
WinThreader::WinEvent::~WinEvent()
{
CloseHandle(m_event);
}
void WinThreader::WinEvent::Wait()
{
WaitForSingleObject(m_event, INFINITE);
}
void WinThreader::WinEvent::Signal()
{
SetEvent(m_event);
}
void WinThreader::WinEvent::DestroyThis()
{
delete this;
}
+113
View File
@@ -0,0 +1,113 @@
/**
* vim: set ts=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2008 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#ifndef _INCLUDE_WINTHREADS_H_
#define _INCLUDE_WINTHREADS_H_
#include <windows.h>
#include "IThreader.h"
using namespace SourceMod;
DWORD WINAPI Win32_ThreadGate(LPVOID param);
class WinThreader : public IThreader
{
public:
class ThreadHandle : public IThreadHandle
{
friend class WinThreader;
friend DWORD WINAPI Win32_ThreadGate(LPVOID param);
public:
ThreadHandle(IThreader *parent, HANDLE hthread, IThread *run, const ThreadParams *params);
virtual ~ThreadHandle();
public:
virtual bool WaitForThread();
virtual void DestroyThis();
virtual IThreadCreator *Parent();
virtual void GetParams(ThreadParams *ptparams);
virtual ThreadPriority GetPriority();
virtual bool SetPriority(ThreadPriority prio);
virtual ThreadState GetState();
virtual bool Unpause();
protected:
IThreader *m_parent; //Parent handle
HANDLE m_thread; //Windows HANDLE
ThreadParams m_params; //Current Parameters
IThread *m_run; //Runnable context
ThreadState m_state; //internal state
CRITICAL_SECTION m_crit;
};
class WinMutex : public IMutex
{
public:
WinMutex();
virtual ~WinMutex();
public:
virtual bool TryLock();
virtual void Lock();
virtual void Unlock();
virtual void DestroyThis();
protected:
CRITICAL_SECTION m_crit;
};
class WinEvent : public IEventSignal
{
public:
WinEvent(HANDLE event) : m_event(event)
{
};
virtual ~WinEvent();
public:
virtual void Wait();
virtual void Signal();
virtual void DestroyThis();
public:
HANDLE m_event;
};
public:
IMutex *MakeMutex();
void MakeThread(IThread *pThread);
IThreadHandle *MakeThread(IThread *pThread, ThreadFlags flags);
IThreadHandle *MakeThread(IThread *pThread, const ThreadParams *params);
void GetPriorityBounds(ThreadPriority &max, ThreadPriority &min);
void ThreadSleep(unsigned int ms);
IEventSignal *MakeEventSignal();
IThreadWorker *MakeWorker(IThreadWorkerCallbacks *hooks, bool threaded);
void DestroyWorker(IThreadWorker *pWorker);
};
#if defined SM_DEFAULT_THREADER && !defined SM_MAIN_THREADER
#define SM_MAIN_THREADER WinThreader;
typedef class WinThreader MainThreader;
#endif
#endif //_INCLUDE_WINTHREADS_H_
+104
View File
@@ -0,0 +1,104 @@
// Microsoft Visual C++ generated resource script.
//
//#include "resource.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "winres.h"
#include "svn_version.h"
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// English (U.S.) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
#ifdef _WIN32
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#pragma code_page(1252)
#endif //_WIN32
/////////////////////////////////////////////////////////////////////////////
//
// Version
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION SVN_FILE_VERSION
PRODUCTVERSION SVN_FILE_VERSION
FILEFLAGSMASK 0x17L
#ifdef _DEBUG
FILEFLAGS 0x1L
#else
FILEFLAGS 0x0L
#endif
FILEOS 0x4L
FILETYPE 0x2L
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "000004b0"
BEGIN
VALUE "Comments", "SourceMod"
VALUE "FileDescription", "SourceMod Core Logic"
VALUE "FileVersion", SVN_FULL_VERSION
VALUE "InternalName", "sourcemod"
VALUE "LegalCopyright", "Copyright (c) 2004-2009, AlliedModders LLC"
VALUE "OriginalFilename", "sourcemod.logic.dll"
VALUE "ProductName", "SourceMod"
VALUE "ProductVersion", SVN_FULL_VERSION
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x0, 1200
END
END
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE
BEGIN
"resource.h\0"
END
2 TEXTINCLUDE
BEGIN
"#include ""winres.h""\r\n"
"\0"
END
3 TEXTINCLUDE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
#endif // English (U.S.) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED