Hard reset

This commit is contained in:
Ley0k 2016-03-27 11:49:47 +02:00
commit 09bed43f97
1594 changed files with 892326 additions and 0 deletions

148
code/globalcpp/Linklist.h Normal file
View file

@ -0,0 +1,148 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// linklist.h:
//
// WARNING: This file is shared between fgame, cgame and possibly the user interface.
// It is instanced in each one of these directories because of the way that SourceSafe works.
//
#ifndef __linklist_h
#define __linklist_h
#ifdef __cplusplus
extern "C" {
#endif
#define NewNode(type) ((type *)Z_Malloc(sizeof(type)))
#define LL_New(rootnode,type,next,prev) \
{ \
(rootnode) = NewNode(type); \
(rootnode)->prev = (rootnode); \
(rootnode)->next = (rootnode); \
}
#define LL_Add(rootnode, newnode, next, prev) \
{ \
(newnode)->next = (rootnode); \
(newnode)->prev = (rootnode)->prev; \
(rootnode)->prev->next = (newnode); \
(rootnode)->prev = (newnode); \
}
//MED
#define LL_AddFirst(rootnode, newnode, next, prev) \
{ \
(newnode)->prev = (rootnode); \
(newnode)->next = (rootnode)->next; \
(rootnode)->next->prev = (newnode); \
(rootnode)->next = (newnode); \
}
#define LL_Transfer(oldroot,newroot,next,prev) \
{ \
if (oldroot->prev != oldroot) \
{ \
oldroot->prev->next = newroot; \
oldroot->next->prev = newroot->prev; \
newroot->prev->next = oldroot->next; \
newroot->prev = oldroot->prev; \
oldroot->next = oldroot; \
oldroot->prev = oldroot; \
} \
}
#define LL_Reverse(root,type,next,prev) \
{ \
type *newend,*trav,*tprev; \
\
newend = root->next; \
for(trav = root->prev; trav != newend; trav = tprev) \
{ \
tprev = trav->prev; \
LL_Move(trav,newend,next,prev); \
} \
}
#define LL_Remove(node,next,prev) \
{ \
node->prev->next = node->next; \
node->next->prev = node->prev; \
node->next = node; \
node->prev = node; \
}
#define LL_SortedInsertion(rootnode,insertnode,next,prev,type,sortparm) \
{ \
type *hoya; \
\
hoya = rootnode->next; \
while((hoya != rootnode) && (insertnode->sortparm > hoya->sortparm)) \
{ \
hoya = hoya->next; \
} \
LL_Add(hoya,insertnode,next,prev); \
}
#define LL_Move(node,newroot,next,prev) \
{ \
LL_Remove(node,next,prev); \
LL_Add(newroot,node,next,prev); \
}
#define LL_Empty(list,next,prev) \
( \
((list)->next == (list)) && \
((list)->prev == (list)) \
)
#define LL_Free(list) Z_Free(list)
#define LL_Reset(list,next,prev) (list)->next = (list)->prev = (list)
#define LL_SafeRemove(node,next,prev) \
{ \
if( node->prev ) node->prev->next = node->next; \
if( node->next ) node->next->prev = node->prev; \
}
#define LL_SafeAdd(rootnode, newnode, next, prev) \
{ \
(newnode)->next = NULL; \
(newnode)->prev = (rootnode); \
if((rootnode)) (rootnode)->next = (newnode); \
(rootnode) = (newnode); \
}
#define LL_SafeAddFirst(rootnode, newnode, next, prev) \
{ \
(newnode)->prev = NULL; \
(newnode)->next = (rootnode); \
if((rootnode)) (rootnode)->prev = (newnode); \
(rootnode) = (newnode); \
}
#ifdef __cplusplus
}
#endif
#endif

1286
code/globalcpp/archive.cpp Normal file

File diff suppressed because it is too large Load diff

415
code/globalcpp/archive.h Normal file
View file

@ -0,0 +1,415 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// archive.h: OpenMoHAA Archiver
#ifndef __ARCHIVE_H__
#define __ARCHIVE_H__
#include "glb_local.h"
#include "class.h"
#include "str.h"
#define ARCHIVE_NULL_POINTER ( -654321 )
#define ARCHIVE_POINTER_VALID ( 0 )
#define ARCHIVE_POINTER_NULL ( ARCHIVE_NULL_POINTER )
#define ARCHIVE_POINTER_SELF_REFERENTIAL ( -123456 )
#define ARCHIVE_USE_TYPES
#define ARCHIVE_WRITE 0
#define ARCHIVE_READ 1
enum
{
pointer_fixup_normal,
pointer_fixup_safe
};
typedef struct
{
void **ptr;
int index;
int type;
} pointer_fixup_t;
class FileRead : public Class
{
protected:
str filename;
size_t length;
byte *buffer;
byte *pos;
public:
CLASS_PROTOTYPE( FileRead );
FileRead();
~FileRead();
void Close( bool bDoCompression = false );
const char *Filename( void );
size_t Length( void );
size_t Pos( void );
qboolean Seek( size_t newpos );
qboolean Open( const char *name );
qboolean Read( void *dest, size_t size );
};
class Archiver : public Class
{
private:
Container<Class *> classpointerList;
Container<pointer_fixup_t *> fixupList;
protected:
str filename;
qboolean fileerror;
fileHandle_t file;
FileRead readfile;
int archivemode;
int numclassespos;
qboolean harderror;
size_t m_iNumBytesIO;
qboolean silent;
void CheckRead( void );
void CheckType( int type );
int ReadType( void );
size_t ReadSize( void );
void CheckSize( int type, size_t size );
void ArchiveData( int type, void *data, size_t size );
void CheckWrite( void );
void WriteType( int type );
void WriteSize( size_t size );
public:
CLASS_PROTOTYPE( Archiver );
Archiver();
~Archiver();
void FileError( const char *fmt, ... );
void Close( void );
qboolean Read( str &name, qboolean harderror = true );
qboolean Read( const char *name, qboolean harderror = true );
Class *ReadObject( void );
qboolean Create( str &name, qboolean harderror = true );
qboolean Create( const char *name, qboolean harderror = true );
qboolean Loading( void );
qboolean Saving( void );
qboolean NoErrors( void );
void ArchiveVector( Vector * vec );
void ArchiveQuat( Quat * quat );
void ArchiveInteger( int * num );
void ArchiveUnsigned( unsigned * unum );
void ArchiveSize( size_t * unum );
void ArchiveByte( byte * num );
void ArchiveChar( char * ch );
void ArchiveShort( short * num );
void ArchiveUnsignedShort( unsigned short * num );
void ArchiveFloat( float * num );
void ArchiveDouble( double * num );
void ArchiveBoolean( qboolean * boolean );
void ArchiveString( str * string );
void ArchiveConfigString( int cs );
void ArchiveObjectPointer( Class ** ptr );
void ArchiveObjectPosition( void *obj );
void ArchiveSafePointer( SafePtrBase * ptr );
void ArchiveEventPointer( Event ** ev );
void ArchiveBool( bool * boolean );
void ArchivePosition( int * pos );
void ArchiveSvsTime( int * time );
void ArchiveVec2( vec2_t vec );
void ArchiveVec3( vec3_t vec );
void ArchiveVec4( vec4_t vec );
void ArchiveRaw( void *data, size_t size );
void ArchiveObject( Class *obj );
qboolean ObjectPositionExists( void * obj );
void SetSilent( bool bSilent );
};
inline qboolean Archiver::Read
(
str &name,
qboolean harderror
)
{
return Read( name.c_str(), harderror );
}
inline qboolean Archiver::Create
(
str &name,
qboolean harderror
)
{
return Create( name.c_str(), harderror );
}
inline qboolean Archiver::Loading
(
void
)
{
return ( archivemode == ARCHIVE_READ );
}
inline qboolean Archiver::Saving
(
void
)
{
return ( archivemode == ARCHIVE_WRITE );
}
inline qboolean Archiver::NoErrors
(
void
)
{
return ( !fileerror );
}
template< class Type >
inline void Container<Type>::Archive
(
Archiver& arc,
void( *ArchiveFunc )( Archiver& arc, Type *obj )
)
{
int num;
int i;
if( arc.Loading() )
{
arc.ArchiveInteger( &num );
Resize( num );
}
else
{
num = numobjects;
arc.ArchiveInteger( &num );
}
for( i = 1; i <= num; i++ )
{
if( num > numobjects ) {
numobjects = num;
}
ArchiveFunc( arc, &objlist[ i ] );
}
}
template<>
inline void Container<str>::Archive
(
Archiver &arc
)
{
int i, num;
if( arc.Loading() )
{
ClearObjectList();
arc.ArchiveInteger( &num );
Resize( num );
}
else
{
num = numobjects;
arc.ArchiveInteger( &num );
}
for( i = 1; i <= num; i++ )
{
arc.ArchiveString( AddressOfObjectAt( i ) );
}
}
template<>
inline void Container<Vector>::Archive
(
Archiver &arc
)
{
int i, num;
if( arc.Loading() )
{
ClearObjectList();
arc.ArchiveInteger( &num );
Resize( num );
}
else
{
num = numobjects;
arc.ArchiveInteger( &num );
}
for( i = 1; i <= num; i++ )
{
arc.ArchiveVector( AddressOfObjectAt( i ) );
}
}
template<>
inline void Container<int>::Archive
(
Archiver &arc
)
{
int i, num;
if( arc.Loading() )
{
ClearObjectList();
arc.ArchiveInteger( &num );
Resize( num );
}
else
{
num = numobjects;
arc.ArchiveInteger( &num );
}
for( i = 1; i <= num; i++ )
{
arc.ArchiveInteger( AddressOfObjectAt( i ) );
}
}
template<>
inline void Container<float>::Archive
(
Archiver &arc
)
{
int i, num;
if( arc.Loading() )
{
ClearObjectList();
arc.ArchiveInteger( &num );
Resize( num );
}
else
{
num = numobjects;
arc.ArchiveInteger( &num );
}
for( i = 1; i <= num; i++ )
{
arc.ArchiveFloat( AddressOfObjectAt( i ) );
}
}
template< typename c >
inline void ArchiveClass
(
Archiver& arc,
c *obj
)
{
arc.ArchiveObject( obj );
}
#ifndef NO_ARCHIVE
template< typename key, typename value >
void con_set< key, value >::Archive
(
Archiver& arc
)
{
Entry< key, value > *e;
int hash;
int i;
arc.ArchiveUnsigned( &tableLength );
arc.ArchiveUnsigned( &threshold );
arc.ArchiveUnsigned( &count );
arc.ArchiveUnsignedShort( &tableLengthIndex );
if( arc.Loading() )
{
if( tableLength != 1 )
{
table = new Entry< key, value > *[ tableLength ]();
memset( table, 0, tableLength * sizeof( Entry< key, value > * ) );
}
for( i = 0; i < count; i++ )
{
e = new Entry< key, value >;
e->Archive( arc );
hash = HashCode< key >( e->key ) % tableLength;
e->index = i;
e->next = table[ hash ];
table[ hash ] = e;
}
}
else
{
for( i = tableLength - 1; i >= 0; i-- )
{
for( e = table[ i ]; e != NULL; e = e->next )
{
e->Archive( arc );
}
}
}
}
template< typename key, typename value >
void con_map< key, value >::Archive
(
Archiver& arc
)
{
m_con_set.Archive( arc );
}
#endif
#define ArchiveEnum( thing, type ) \
{ \
int tempInt; \
\
tempInt = ( int )( thing ); \
arc.ArchiveInteger( &tempInt ); \
( thing ) = ( type )tempInt; \
}
#endif // __ARCHIVE_H__

View file

@ -0,0 +1,381 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// archive.cpp: OpenMoHAA Archiver
#include "glb_local.h"
#include "archive.h"
#include <lz77.h>
#ifdef GAME_DLL
#include "../game/entity.h"
#endif
CLASS_DECLARATION( Class, FileRead, NULL )
{
{ NULL, NULL }
};
FileRead::FileRead()
{
}
FileRead::~FileRead()
{
}
void FileRead::Close
(
bool bDoCompression
)
{
}
const char *FileRead::Filename
(
void
)
{
return "";
}
size_t FileRead::Length
(
void
)
{
return length;
}
size_t FileRead::Pos
(
void
)
{
return 0;
}
qboolean FileRead::Seek
(
size_t newpos
)
{
return qfalse;
}
qboolean FileRead::Open
(
const char *name
)
{
return qfalse;
}
qboolean FileRead::Read
(
void *dest,
size_t size
)
{
return qfalse;
}
CLASS_DECLARATION( Class, Archiver, NULL )
{
{ NULL, NULL }
};
Archiver::Archiver()
{
}
Archiver::~Archiver()
{
}
void Archiver::FileError
(
const char *fmt,
...
)
{
}
void Archiver::Close
(
void
)
{
}
/****************************************************************************************
File Read/Write functions
*****************************************************************************************/
qboolean Archiver::Read
(
const char *name,
qboolean harderror
)
{
return qfalse;
}
qboolean Archiver::Create
(
const char *name,
qboolean harderror
)
{
return qfalse;
}
inline void Archiver::CheckRead
(
void
)
{
}
inline void Archiver::CheckWrite
(
void
)
{
}
inline size_t Archiver::ReadSize
(
void
)
{
}
inline void Archiver::CheckSize
(
int type,
size_t size
)
{
}
inline void Archiver::WriteSize
(
size_t size
)
{
}
inline int Archiver::ReadType
(
void
)
{
}
inline void Archiver::WriteType
(
int type
)
{
}
inline void Archiver::CheckType
(
int type
)
{
}
/****************************************************************************************
File Archive functions
*****************************************************************************************/
//#define ARCHIVE_USE_TYPES 1
inline void Archiver::ArchiveData
(
int type,
void *data,
size_t size
)
{
}
#define ARCHIVE( func, type ) \
void Archiver::Archive##func \
( \
type * v \
) \
\
{ \
}
ARCHIVE( Vector, Vector );
ARCHIVE( Integer, int );
ARCHIVE( Unsigned, unsigned );
ARCHIVE( Size, size_t );
ARCHIVE( Byte, byte );
ARCHIVE( Char, char );
ARCHIVE( Short, short );
ARCHIVE( UnsignedShort, unsigned short );
ARCHIVE( Float, float );
ARCHIVE( Double, double );
ARCHIVE( Boolean, qboolean );
ARCHIVE( Quat, Quat );
ARCHIVE( Bool, bool );
ARCHIVE( Position, int );
void Archiver::ArchiveSvsTime
(
int *time
)
{
}
void Archiver::ArchiveVec2
(
vec2_t vec
)
{
}
void Archiver::ArchiveVec3
(
vec3_t vec
)
{
}
void Archiver::ArchiveVec4
(
vec4_t vec
)
{
}
void Archiver::ArchiveObjectPointer
(
Class ** ptr
)
{
}
void Archiver::ArchiveObjectPosition( void *obj )
{
}
void Archiver::ArchiveSafePointer
(
SafePtrBase * ptr
)
{
}
void Archiver::ArchiveEventPointer
(
Event ** ev
)
{
}
void Archiver::ArchiveRaw
(
void *data,
size_t size
)
{
}
void Archiver::ArchiveString
(
str * string
)
{
}
void Archiver::ArchiveConfigString( int cs )
{
}
Class * Archiver::ReadObject
(
void
)
{
return NULL;
}
void Archiver::ArchiveObject
(
Class *obj
)
{
}
qboolean Archiver::ObjectPositionExists( void *obj )
{
return qfalse;
}
void Archiver::SetSilent( bool bSilent )
{
}

90
code/globalcpp/baseimp.h Normal file
View file

@ -0,0 +1,90 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#ifndef __BASEIMP_H__
#define __BASEIMP_H__
#ifdef __cplusplus
extern "C" {
#endif
typedef struct aliasListNode_s aliasListNode_t;
typedef struct cvar_s cvar_t;
typedef struct baseImport_s
{
void ( *Printf )( const char *format, ... );
void ( *DPrintf )( const char *format, ... );
const char * ( *LV_ConvertString )( const char *string );
cvar_t * ( *Cvar_Get )( const char *varName, const char *varValue, int varFlags );
void( *Cvar_Set )( const char *varName, const char *varValue );
int( *FS_ReadFile )( const char *qpath, void **buffer, qboolean quiet );
void( *FS_FreeFile )( void *buffer );
size_t( *FS_WriteFile )( const char *qpath, const void *buffer, size_t size );
fileHandle_t( *FS_FOpenFileWrite )( const char *fileName );
fileHandle_t( *FS_FOpenFileAppend )( const char *fileName );
fileHandle_t( *FS_FOpenFile )( const char *fileName );
const char *( *FS_PrepFileWrite )( const char *fileName );
size_t( *FS_Write )( const void *buffer, size_t len, fileHandle_t fileHandle );
size_t( *FS_Read )( void *buffer, size_t len, fileHandle_t fileHandle );
void( *FS_FCloseFile )( fileHandle_t fileHandle );
int( *FS_Tell )( fileHandle_t fileHandle );
int( *FS_Seek )( fileHandle_t fileHandle, long int offset, fsOrigin_t origin );
void( *FS_Flush )( fileHandle_t fileHandle );
int( *FS_FileNewer )( const char *source, const char *destination );
void( *FS_CanonicalFilename )( char *fileName );
char **( *FS_ListFiles )( const char *qpath, const char *extension, qboolean wantSubs, int *numFiles );
void( *FS_FreeFileList )( char **list );
int( *Milliseconds )( );
double( *MillisecondsDbl )( );
void( *Error )( int errortype, const char *format, ... );
void *( *Malloc )( size_t size );
void( *Free )( void *ptr );
int( *Key_StringToKeynum )( const char *str );
char * ( *Key_KeynumToBindString )( int keyNum );
void( *Key_GetKeysForCommand )( const char *command, int *key1, int *key2 );
void( *SendConsoleCommand )( const char *text );
void( *SendServerCommand )( int client, const char *format, ... );
qboolean( *GlobalAlias_Add )( const char *alias, const char *name, const char *parameters );
char * ( *GlobalAlias_FindRandom )( const char *alias, aliasListNode_t **ret );
void( *GlobalAlias_Dump )( );
void( *GlobalAlias_Clear )( );
void( *SetConfigstring )( int index, const char *val );
char *( *GetConfigstring )( int index );
void( *AddSvsTimeFixup )( int *piTime );
} baseImport_t;
extern baseImport_t bi;
extern cvar_t *developer;
extern cvar_t *precache;
extern cvar_t *sv_scriptfiles;
extern cvar_t *g_scriptcheck;
extern cvar_t *g_showopcodes;
void CacheResource( const char *name );
#ifdef __cplusplus
}
#endif
#endif

129
code/globalcpp/basemain.cpp Normal file
View file

@ -0,0 +1,129 @@
#include <glb_local.h>
#include <scriptmaster.h>
#include <baseimp.h>
#include <dummy_base.h>
#include <world.h>
#include <g_spawn.h>
#include <Windows.h>
void BaseInit( void )
{
developer = new cvar_t;
g_scriptcheck = new cvar_t;
g_showopcodes = new cvar_t;
precache = new cvar_t;
sv_scriptfiles = new cvar_t;
memset( developer, 0, sizeof( cvar_t ) );
memset( g_scriptcheck, 0, sizeof( cvar_t ) );
memset( g_showopcodes, 0, sizeof( cvar_t ) );
memset( precache, 0, sizeof( cvar_t ) );
memset( sv_scriptfiles, 0, sizeof( cvar_t ) );
Com_FillBaseImports();
Swap_Init();
Z_InitMemory();
Cmd_Init();
Cvar_Init();
FS_InitFilesystem2();
L_InitEvents();
#ifndef NO_SCRIPTENGINE
level.m_LoopProtection = false;
world = new World;
Director.Init();
Director.Reset( false );
Director.maxTime = 50;
#endif
}
void BaseRunFrame( double frametime )
{
level.setFrametime( frametime );
level.setTime( clock() );
#ifndef NO_SCRIPTENGINE
Director.SetTime( level.inttime );
Director.m_bAllowContextSwitch = true;
#endif
L_ProcessPendingEvents();
#ifndef NO_SCRIPTENGINE
Director.ExecuteRunning();
#endif
}
void BaseIdle( void )
{
double frametime = 0;
double lastframetime;
double tick = 0;
bi.Printf( "BaseIdle()\n" );
tick = ( double )clock();// / 1000.0;
lastframetime = tick;
while( 1 )
{
tick = ( double )clock();// / 1000.0;
frametime = ( tick - lastframetime );
lastframetime = tick;
BaseRunFrame( frametime );
Sleep( 50 );
}
}
int MainEvent( const Container< Event * >& conev );
int main( int argc, char **argv )
{
Container< Event * > conev;
Event *ev;
int i;
char *arg;
BaseInit();
// copy the argument list
for( i = 0; i < argc; i++ )
{
arg = argv[ i ];
if( strlen( arg ) <= 1 ) {
continue;
}
if( *arg != '/' && *arg != '-' && *arg != '+' ) {
continue;
}
ev = new Event( arg + 1 );
for( i++; i < argc; i++ )
{
arg = argv[ i ];
if( *arg == '/' || *arg == '-' || *arg == '+' ) {
i--;
break;
}
ev->AddString( argv[ i ] );
}
conev.AddObject( ev );
}
MainEvent( conev );
conev.FreeObjectList();
}

View file

@ -0,0 +1,4 @@
#include "listener.h"
void BaseRunFrame( double frametime );
void BaseIdle( void );

914
code/globalcpp/class.cpp Normal file
View file

@ -0,0 +1,914 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// class.cpp: General class.
#include "glb_local.h"
#include "scriptmaster.h"
#include <dbgheap.h>
#define CLASS_Printf if( level.current_map ) glbs.Printf
#define CLASS_DPrintf if( level.current_map ) glbs.DPrintf
#define CLASS_Error if( level.current_map ) glbs.Error
ClassDef *ClassDef::classlist;
int ClassDef::numclasses;
int ClassDef::dump_numclasses;
int ClassDef::dump_numevents;
Container< int > ClassDef::sortedList;
Container< ClassDef * > ClassDef::sortedClassList;
int ClassDef::compareClasses( const void *arg1, const void *arg2 )
{
ClassDef *c1 = *( ClassDef ** )arg1;
ClassDef *c2 = *( ClassDef ** )arg2;
return Q_stricmp( c1->classname, c2->classname );
}
void ClassDef::SortClassList( Container< ClassDef * > *sortedList )
{
ClassDef *c;
sortedList->Resize( numclasses );
for( c = classlist->next; c != classlist; c = c->next )
{
sortedList->AddObject( c );
}
qsort( ( void * )sortedList->AddressOfObjectAt( 1 ),
( size_t )sortedList->NumObjects(),
sizeof( ClassDef * ), compareClasses );
}
ClassDef *getClassForID( const char *name )
{
ClassDef *classlist = ClassDef::classlist;
ClassDef *c;
for( c = classlist->next; c != classlist; c = c->next )
{
if( c->classID && !Q_stricmp( c->classID, name ) )
{
return c;
}
}
return NULL;
}
ClassDef *getClass( const char *name )
{
if( name == NULL || name == "" ) {
return NULL;
}
ClassDef *list = ClassDef::classlist;
ClassDef *c;
for( c = list->next; c != list; c = c->next )
{
if( Q_stricmp( c->classname, name ) == 0 ) {
return c;
}
}
return NULL;
}
ClassDef *getClassList
(
void
)
{
return ClassDef::classlist;
}
void listAllClasses
(
void
)
{
ClassDef *c;
ClassDef *list = ClassDef::classlist;
for( c = list->next; c != list; c = c->next )
{
CLASS_DPrintf( "%s\n", c->classname );
}
}
void listInheritanceOrder
(
const char *classname
)
{
ClassDef *cls;
ClassDef *c;
cls = getClass( classname );
if( !cls )
{
CLASS_DPrintf( "Unknown class: %s\n", classname );
return;
}
for( c = cls; c != NULL; c = c->super )
{
CLASS_DPrintf( "%s\n", c->classname );
}
}
qboolean checkInheritance( const ClassDef *superclass, const ClassDef *subclass )
{
const ClassDef *c;
for( c = subclass; c != NULL; c = c->super )
{
if ( c == superclass )
{
return true;
}
}
return false;
}
qboolean checkInheritance( ClassDef *superclass, const char *subclass )
{
ClassDef *c;
c = getClass( subclass );
if ( c == NULL )
{
CLASS_DPrintf( "Unknown class: %s\n", subclass );
return false;
}
return checkInheritance( superclass, c );
}
qboolean checkInheritance( const char *superclass, const char *subclass )
{
ClassDef *c1;
ClassDef *c2;
c1 = getClass( superclass );
c2 = getClass( subclass );
if ( c1 == NULL )
{
CLASS_DPrintf( "Unknown class: %s\n", superclass );
return false;
}
if ( c2 == NULL )
{
CLASS_DPrintf( "Unknown class: %s\n", subclass );
return false;
}
return checkInheritance( c1, c2 );
}
void CLASS_Print( FILE *class_file, const char *fmt, ... )
{
va_list argptr;
char text[ 1024 ];
va_start( argptr, fmt );
vsprintf( text, fmt, argptr );
va_end( argptr );
if( class_file )
fprintf( class_file, text );
else
CLASS_DPrintf( text );
}
size_t totalmemallocated = 0;
unsigned int numclassesallocated = 0;
bool classInited = false;
void *Class::operator new( size_t s )
{
size_t *p;
if ( s == 0 )
return 0;
s += sizeof( unsigned int );
#ifdef GAME_DLL
p = ( size_t * )gi.Malloc( s );
#elif defined ( CGAME_DLL )
p = ( size_t * )cgi.Malloc( s );
#else
p = ( size_t * )glbs.Malloc( s );
#endif
#ifdef _DEBUG
m_Heap.ReferencePointer( p );
#endif
*p = s;
totalmemallocated += s;
numclassesallocated++;
p++;
return p;
}
void Class::operator delete( void *ptr )
{
unsigned int *p = ( ( unsigned int * )ptr ) - 1;
totalmemallocated -= *p;
numclassesallocated--;
#ifdef _DEBUG
m_Heap.DereferencePointer( p );
#endif
#ifdef GAME_DLL
gi.Free( p );
#elif defined ( CGAME_DLL )
cgi.Free( p );
#else
glbs.Free( p );
#endif
}
Class::Class()
{
SafePtrList = NULL;
}
Class::~Class()
{
ClearSafePointers();
}
void Class::Archive( Archiver& arc )
{
}
void Class::ClearSafePointers( void )
{
while( SafePtrList != NULL ) {
SafePtrList->Clear();
}
}
void Class::warning( const char *function, const char *format, ... )
{
char buffer[ MAX_STRING_CHARS ];
const char *classname;
va_list va;
va_start( va, format );
vsprintf( buffer, format, va );
classname = classinfo()->classname;
#ifdef GAME_DLL
gi.DPrintf(
#elif defined CGAME_DLL
cgi.DPrintf(
#else
Com_DPrintf(
#endif
"%s::%s : %s\n", classname, function, buffer );
}
void Class::error
(
const char *function,
const char *fmt,
...
)
{
va_list argptr;
char text[ 1024 ];
va_start( argptr, fmt );
vsprintf( text, fmt, argptr );
va_end( argptr );
if( getClassID() )
{
CLASS_Error( ERR_DROP, "%s::%s : %s\n", getClassID(), function, text );
}
else
{
CLASS_Error( ERR_DROP, "%s::%s : %s\n", getClassname(), function, text );
}
}
ClassDef::ClassDef()
{
this->classname = NULL;
this->classID = NULL;
this->superclass = NULL;
this->responses = NULL;
this->numEvents = 0;
this->responseLookup = NULL;
this->newInstance = NULL;
this->classSize = 0;
this->super = NULL;
this->prev = this;
this->next = this;
#ifndef NO_SCRIPTENGINE
this->waitTillSet = NULL;
#endif
}
ClassDef::ClassDef( const char *classname, const char *classID, const char *superclass, ResponseDef<Class> *responses,
void *( *newInstance )( void ), int classSize )
{
ClassDef *node;
if( classlist == NULL ) {
classlist = new ClassDef;
}
this->classname = classname;
this->classID = classID;
this->superclass = superclass;
this->responses = responses;
this->numEvents = 0;
this->responseLookup = NULL;
this->newInstance = newInstance;
this->classSize = classSize;
this->super = getClass( superclass );
#ifndef NO_SCRIPTENGINE
this->waitTillSet = NULL;
#endif
if( !classID ) {
this->classID = "";
}
for( node = classlist->next; node != classlist; node = node->next )
{
if( ( node->super == NULL ) && ( !Q_stricmp( node->superclass, this->classname ) ) &&
( Q_stricmp( node->classname, "Class" ) ) )
{
node->super = this;
}
}
// Add to front of list
LL_Add( classlist, this, prev, next );
numclasses++;
}
ClassDef::~ClassDef()
{
ClassDef *node;
if( classlist != this )
{
LL_Remove( this, prev, next );
// Check if any subclasses were initialized before their superclass
for( node = classlist->next; node != classlist; node = node->next )
{
if( node->super == this )
{
node->super = NULL;
}
}
}
else
{
// If the head of the list is deleted before the list is cleared, then we may have problems
assert( this->next == this->prev );
}
if( responseLookup )
{
delete[] responseLookup;
responseLookup = NULL;
}
}
#ifndef NO_SCRIPTENGINE
void ClassDef::AddWaitTill( str s )
{
return AddWaitTill( Director.AddString( s ) );
}
void ClassDef::AddWaitTill( const_str s )
{
if( !waitTillSet )
{
waitTillSet = new con_set < const_str, const_str >;
}
waitTillSet->addKeyValue( s ) = s;
}
void ClassDef::RemoveWaitTill( str s )
{
return RemoveWaitTill( Director.AddString( s ) );
}
void ClassDef::RemoveWaitTill( const_str s )
{
if( waitTillSet )
{
waitTillSet->remove( s );
}
}
bool ClassDef::WaitTillDefined( str s )
{
return WaitTillDefined( Director.AddString( s ) );
}
bool ClassDef::WaitTillDefined( const_str s )
{
if( !waitTillSet )
{
return false;
}
return waitTillSet->findKeyValue( s ) != NULL;
}
#endif
EventDef *ClassDef::GetDef( int eventnum )
{
ResponseDef< Class > *r = responseLookup[ eventnum ];
if( r )
{
return r->def;
}
else
{
return NULL;
}
}
int ClassDef::GetFlags( Event *event )
{
EventDef *def = GetDef( event->eventnum );
if( def )
{
return def->flags;
}
else
{
return 0;
}
}
void ClassDef::BuildResponseList( void )
{
ClassDef *c;
ResponseDef<Class> *r;
int ev;
int i;
qboolean *set;
int num;
if( responseLookup )
{
delete[] responseLookup;
responseLookup = NULL;
}
num = Event::NumEventCommands();
responseLookup = ( ResponseDef< Class > ** )new char[ sizeof( ResponseDef< Class > * ) * num ];
memset( responseLookup, 0, sizeof( ResponseDef< Class > * ) * num );
set = new qboolean[ num ];
memset( set, 0, sizeof( qboolean ) * num );
this->numEvents = num;
for( c = this; c != NULL; c = c->super )
{
r = c->responses;
if( r )
{
for( i = 0; r[ i ].event != NULL; i++ )
{
ev = ( int )r[ i ].event->eventnum;
r[ i ].def = r[ i ].event->getInfo();
if( !set[ ev ] )
{
set[ ev ] = true;
if( r[ i ].response )
{
responseLookup[ ev ] = &r[ i ];
}
else
{
responseLookup[ ev ] = NULL;
}
}
}
}
}
delete[] set;
}
void ClassDef::BuildEventResponses( void )
{
ClassDef *c;
int amount;
int numclasses;
amount = 0;
numclasses = 0;
for( c = classlist->next; c != classlist; c = c->next )
{
c->BuildResponseList();
amount += c->numEvents * sizeof( Response * );
numclasses++;
}
CLASS_DPrintf( "\n------------------\nEvent system initialized: "
"%d classes %d events %d total memory in response list\n\n", numclasses, Event::NumEventCommands(), amount );
}
const char *Class::getClassID( void ) const
{
return classinfo()->classID;
}
const char *Class::getClassname( void ) const
{
return classinfo()->classname;
}
const char *Class::getSuperclass( void ) const
{
return classinfo()->superclass;
}
#define MAX_INHERITANCE 64
void ClassEvents
(
const char *classname,
qboolean print_to_disk
)
{
ClassDef *c;
ResponseDef<Class> *r;
int ev;
int i, j;
qboolean *set;
int num, orderNum;
Event **events;
byte *order;
FILE *class_file;
str classNames[ MAX_INHERITANCE ];
str class_filename;
c = getClass( classname );
if( !c )
{
CLASS_DPrintf( "Unknown class: %s\n", classname );
return;
}
class_file = NULL;
if( print_to_disk )
{
class_filename = str( classname ) + ".txt";
class_file = fopen( class_filename.c_str(), "w" );
if( class_file == NULL )
return;
}
num = Event::NumEventCommands();
set = new qboolean[ num ];
memset( set, 0, sizeof( qboolean ) * num );
events = new Event *[ num ];
memset( events, 0, sizeof( Event * ) * num );
order = new byte[ num ];
memset( order, 0, sizeof( byte ) * num );
orderNum = 0;
for( ; c != NULL; c = c->super )
{
if( orderNum < MAX_INHERITANCE )
{
classNames[ orderNum ] = c->classname;
}
r = c->responses;
if( r )
{
for( i = 0; r[ i ].event != NULL; i++ )
{
ev = ( int )r[ i ].event->eventnum;
if( !set[ ev ] )
{
set[ ev ] = true;
if( r[ i ].response )
{
events[ ev ] = r[ i ].event;
order[ ev ] = orderNum;
}
}
}
}
orderNum++;
}
CLASS_Print( class_file, "********************************************************\n" );
CLASS_Print( class_file, "********************************************************\n" );
CLASS_Print( class_file, "* All Events For Class: %s\n", classname );
CLASS_Print( class_file, "********************************************************\n" );
CLASS_Print( class_file, "********************************************************\n\n" );
for( j = orderNum - 1; j >= 0; j-- )
{
CLASS_Print( class_file, "\n********************************************************\n" );
CLASS_Print( class_file, "* Class: %s\n", classNames[ j ].c_str() );
CLASS_Print( class_file, "********************************************************\n\n" );
for( i = 1; i < num; i++ )
{
int index;
index = ClassDef::sortedList.ObjectAt( i );
if( events[ index ] && ( order[ index ] == j ) )
{
Event::eventDefList[ events[ index ] ].PrintEventDocumentation( class_file, qfalse );
}
}
}
if( class_file != NULL )
{
CLASS_DPrintf( "Printed class info to file %s\n", class_filename.c_str() );
fclose( class_file );
}
delete[] events;
delete[] order;
delete[] set;
}
void DumpClass
(
FILE * class_file,
const char * className
)
{
ClassDef *c;
ResponseDef<Class> *r;
int ev;
int i;
int num, num2;
Event **events;
c = getClass( className );
if( !c )
{
return;
}
num = Event::commandList.size();
num2 = Event::NumEventCommands();
events = new Event *[ num2 ];
memset( events, 0, sizeof( Event * ) * num2 );
// gather event responses for this class
r = c->responses;
if( r )
{
for( i = 0; r[ i ].event != NULL; i++ )
{
ev = ( int )r[ i ].event->eventnum;
if( r[ i ].response )
{
events[ ev ] = r[ i ].event;
}
}
}
CLASS_Print( class_file, "\n" );
if( c->classID[ 0 ] )
{
CLASS_Print( class_file, "<h2> <a name=\"%s\">%s (<i>%s</i>)</a>", c->classname, c->classname, c->classID );
}
else
{
CLASS_Print( class_file, "<h2> <a name=\"%s\">%s</a>", c->classname, c->classname );
}
// print out lineage
for( c = c->super; c != NULL; c = c->super )
{
CLASS_Print( class_file, " -> <a href=\"#%s\">%s</a>", c->classname, c->classname );
}
CLASS_Print( class_file, "</h2>\n" );
ClassDef::dump_numclasses++;
CLASS_Print( class_file, "<BLOCKQUOTE>\n" );
for( i = 1; i < num; i++ )
{
int index;
index = ClassDef::sortedList.ObjectAt( i );
if( events[ index ] )
{
Event::eventDefList[ events[ index ] ].PrintEventDocumentation( class_file, qtrue );
ClassDef::dump_numevents++;
}
}
CLASS_Print( class_file, "</BLOCKQUOTE>\n" );
delete[] events;
}
#define MAX_CLASSES 1024
void DumpAllClasses
(
void
)
{
int i, num;
ClassDef *c;
FILE * class_file;
str class_filename;
str class_title;
str classes[ MAX_CLASSES ];
#if defined( GAME_DLL )
class_filename = "g_allclasses.html";
class_title = "Game Module";
#elif defined( CGAME_DLL )
class_filename = "cg_allclasses.html";
class_title = "Client Game Module";
#else
class_filename = "cl_allclasses.html";
class_title = "Client Module";
#endif
class_file = fopen( class_filename.c_str(), "w" );
if( class_file == NULL )
return;
// construct the HTML header for the document
CLASS_Print( class_file, "<HTML>\n" );
CLASS_Print( class_file, "<HEAD>\n" );
CLASS_Print( class_file, "<Title>%s Classes</Title>\n", class_title.c_str() );
CLASS_Print( class_file, "</HEAD>\n" );
CLASS_Print( class_file, "<BODY>\n" );
CLASS_Print( class_file, "<H1>\n" );
CLASS_Print( class_file, "<center>%s Classes</center>\n", class_title.c_str() );
CLASS_Print( class_file, "</H1>\n" );
#if defined( GAME_DLL )
//
// print out some commonly used classnames
//
CLASS_Print( class_file, "<h2>" );
CLASS_Print( class_file, "<a href=\"#Actor\">Actor</a>, " );
CLASS_Print( class_file, "<a href=\"#Animate\">Animate</a>, " );
CLASS_Print( class_file, "<a href=\"#Entity\">Entity</a>, " );
CLASS_Print( class_file, "<a href=\"#ScriptSlave\">ScriptSlave</a>, " );
CLASS_Print( class_file, "<a href=\"#ScriptThread\">ScriptThread</a>, " );
CLASS_Print( class_file, "<a href=\"#Sentient\">Sentient</a>, " );
CLASS_Print( class_file, "<a href=\"#StateMap\">StateMap</a>, " );
CLASS_Print( class_file, "<a href=\"#Trigger\">Trigger</a>, " );
CLASS_Print( class_file, "<a href=\"#World\">World</a>" );
CLASS_Print( class_file, "</h2>" );
#endif
ClassDef::dump_numclasses = 0;
ClassDef::dump_numevents = 0;
ClassDef::sortedList.ClearObjectList();
ClassDef::sortedClassList.ClearObjectList();
Event::SortEventList( &ClassDef::sortedList );
ClassDef::SortClassList( &ClassDef::sortedClassList );
num = ClassDef::sortedClassList.NumObjects();
// go through and process each class from smallest to greatest
for( i = 1; i <= num; i++ )
{
c = ClassDef::sortedClassList.ObjectAt( i );
DumpClass( class_file, c->classname );
}
if( class_file != NULL )
{
CLASS_Print( class_file, "<H2>\n" );
CLASS_Print( class_file, "%d %s Classes.<BR>%d %s Events.\n", ClassDef::dump_numclasses, class_title.c_str(), ClassDef::dump_numevents, class_title.c_str() );
CLASS_Print( class_file, "</H2>\n" );
CLASS_Print( class_file, "</BODY>\n" );
CLASS_Print( class_file, "</HTML>\n" );
CLASS_DPrintf( "Dumped all classes to file %s\n", class_filename.c_str() );
fclose( class_file );
}
}
qboolean Class::inheritsFrom( ClassDef *c ) const
{
return checkInheritance( c, classinfo() );
}
qboolean Class::inheritsFrom( const char * name ) const
{
ClassDef *c;
c = getClass( name );
if ( c == NULL )
{
CLASS_Printf( "Unknown class: %s\n", name );
return false;
}
return checkInheritance( c, classinfo() );
}
qboolean Class::isInheritedBy( const char * name ) const
{
ClassDef *c;
c = getClass( name );
if ( c == NULL )
{
CLASS_DPrintf( "Unknown class: %s\n", name );
return false;
}
return checkInheritance( classinfo(), c );
}
qboolean Class::isInheritedBy( ClassDef *c ) const
{
return checkInheritance( classinfo(), c );
}
ClassDefHook::ClassDefHook()
{
this->classdef = NULL;
}
CLASS_DECLARATION( NULL, Class, NULL )
{
{ NULL, NULL }
};

281
code/globalcpp/class.h Normal file
View file

@ -0,0 +1,281 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// class.h: General class
#ifndef __CLASS_H__
#define __CLASS_H__
#if defined ( GAME_DLL )
#include "g_local.h"
#else
#include "glb_local.h"
#endif
class Class;
class Event;
#define isSubclassOf( classname )inheritsFrom( &classname::ClassInfo )
#define isSuperclassOf( classname )isInheritedBy( &classname::ClassInfo )
#ifndef NO_SCRIPTENGINE
#define CLASS_DECLARATION( parentclass, classname, classid ) \
ClassDef classname::ClassInfo \
( \
#classname, classid, #parentclass, \
(ResponseDef<Class> *)classname::Responses, \
classname::_newInstance, sizeof( classname ) \
); \
void *classname::_newInstance( void ) \
{ \
return new classname; \
} \
ClassDef *classname::classinfo( void ) const \
{ \
return &(classname::ClassInfo); \
} \
ClassDef *classname::classinfostatic( void ) \
{ \
return &(classname::ClassInfo); \
} \
void classname::AddWaitTill( str s ) \
{ \
classname::ClassInfo.AddWaitTill( s ); \
} \
void classname::AddWaitTill( const_str s ) \
{ \
classname::ClassInfo.AddWaitTill( s ); \
} \
void classname::RemoveWaitTill( str s ) \
{ \
classname::ClassInfo.RemoveWaitTill( s ); \
} \
void classname::RemoveWaitTill( const_str s ) \
{ \
classname::ClassInfo.RemoveWaitTill( s ); \
} \
bool classname::WaitTillDefined( str s ) \
{ \
return classname::ClassInfo.WaitTillDefined( s ); \
} \
bool classname::WaitTillDefined( const_str s ) \
{ \
return classname::ClassInfo.WaitTillDefined( s ); \
} \
ResponseDef<classname> classname::Responses[] =
#define CLASS_PROTOTYPE( classname ) \
public: \
static ClassDef ClassInfo; \
static ClassDefHook _ClassInfo_; \
static void *_newInstance( void ); \
static ClassDef *classinfostatic(void); \
virtual ClassDef *classinfo(void) const; \
static void AddWaitTill( str s ); \
static void AddWaitTill( const_str s ); \
static void RemoveWaitTill( str s ); \
static void RemoveWaitTill( const_str s ); \
static bool WaitTillDefined( str s ); \
static bool WaitTillDefined( const_str s ); \
static ResponseDef<classname> Responses[]
#else
#define CLASS_DECLARATION( parentclass, classname, classid ) \
ClassDef classname::ClassInfo \
( \
#classname, classid, #parentclass, \
(ResponseDef<Class> *)classname::Responses, \
classname::_newInstance, sizeof( classname ) \
); \
void *classname::_newInstance( void ) \
{ \
return new classname; \
} \
ClassDef *classname::classinfo( void ) const \
{ \
return &(classname::ClassInfo); \
} \
ClassDef *classname::classinfostatic( void ) \
{ \
return &(classname::ClassInfo); \
} \
ResponseDef<classname> classname::Responses[] =
#define CLASS_PROTOTYPE( classname ) \
public: \
static ClassDef ClassInfo; \
static ClassDefHook _ClassInfo_; \
static void *_newInstance( void ); \
static ClassDef *classinfostatic(void); \
virtual ClassDef *classinfo(void) const; \
static ResponseDef<classname> Responses[]
#endif
typedef void ( Class::*Response )( Event *ev );
class EventDef;
template< class Type >
struct ResponseDef
{
Event *event;
void ( Type::*response )( Event *ev );
EventDef *def;
};
class ClassDef
{
public:
const char *classname;
const char *classID;
const char *superclass;
void *(*newInstance)(void);
int classSize;
ResponseDef<Class> *responses;
ResponseDef<Class> **responseLookup;
ClassDef *super;
ClassDef *next;
ClassDef *prev;
#ifndef NO_SCRIPTENGINE
con_set<const_str, const_str> *waitTillSet;
#endif
int numEvents;
static ClassDef *classlist;
static int numclasses;
static void BuildEventResponses();
void BuildResponseList();
static int dump_numclasses;
static int dump_numevents;
static Container< int > sortedList;
static Container< ClassDef * > sortedClassList;
ClassDef();
~ClassDef();
static int compareClasses( const void *arg1, const void *arg2 );
static void SortClassList( Container< ClassDef * > *sortedList );
#ifndef NO_SCRIPTENGINE
void AddWaitTill( str s );
void AddWaitTill( const_str s );
void RemoveWaitTill( str s );
void RemoveWaitTill( const_str s );
bool WaitTillDefined( str s );
bool WaitTillDefined( const_str s );
#endif
/* Create-a-class function */
ClassDef( const char *classname, const char *classID, const char *superclass, ResponseDef<Class> *responses,
void *( *newInstance )( void ), int classSize );
void CreateInternal( const char *classname, const char *classID, const char *superclass, ResponseDef<Class> *responses,
void *( *newInstance )( void ), int classSize );
void CreateInternalWin( const char *classname, const char *classID, const char *superclass, ResponseDef<Class> *responses,
void *( *newInstance )( void ), int classSize );
EventDef *GetDef( int eventnum );
int GetFlags( Event *event );
void Destroy();
};
ClassDef *getClassList( void );
qboolean checkInheritance( const ClassDef *superclass, const ClassDef *subclass );
qboolean checkInheritance( ClassDef *superclass, const char *subclass );
qboolean checkInheritance( const char *superclass, const char *subclass );
void CLASS_Print( FILE *class_file, const char *fmt, ... );
void ClassEvents( const char *classname, qboolean print_to_disk );
void DumpClass( FILE * class_file, const char * className );
void DumpAllClasses( void );
class ClassDefHook
{
private:
ClassDef *classdef;
public:
//void * operator new( size_t );
//void operator delete( void * );
ClassDefHook();
~ClassDefHook();
/* Hook-a-class function */
ClassDefHook( ClassDef * classdef, ResponseDef<Class> *responses );
};
ClassDef *getClassForID( const char *name );
ClassDef *getClass( const char * name );
ClassDef *getClassList( void );
void listAllClasses( void );
void listInheritanceOrder( const char *classname );
class SafePtrBase;
class Archiver;
class Class
{
public:
SafePtrBase *SafePtrList;
private:
void ClearSafePointers();
public:
CLASS_PROTOTYPE( Class );
void * operator new( size_t );
void operator delete( void * );
Class();
virtual ~Class();
virtual void Archive( Archiver& arc );
const char *getClassID( void ) const;
const char *getClassname( void ) const;
const char *getSuperclass( void ) const;
qboolean inheritsFrom( ClassDef *c ) const;
qboolean inheritsFrom( const char * name ) const;
qboolean isInheritedBy( const char * name ) const;
qboolean isInheritedBy( ClassDef *c ) const;
void warning( const char *function, const char *format, ... );
void error( const char *function, const char *format, ... );
};
#include "safeptr.h"
#endif /* __CLASS_H__ */

1949
code/globalcpp/compiler.cpp Normal file

File diff suppressed because it is too large Load diff

177
code/globalcpp/compiler.h Normal file
View file

@ -0,0 +1,177 @@
/*
===========================================================================
Copyright (C) 2008 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// compiler.h: Script Compiler
#ifndef __COMPILER_H__
#define __COMPILER_H__
#include "glb_local.h"
#include <scriptopcodes.h>
#include <gamescript.h>
#include <parser/parsetree.h>
enum
{
method_game,
method_level,
method_local,
method_parm,
method_self,
method_group,
method_owner,
method_field,
method_array,
};
typedef struct scriptmacro {
str name;
str parameters;
} scriptmacro_t;
#define BREAK_JUMP_LOCATION_COUNT 100
#define CONTINUE_JUMP_LOCATION_COUNT 100
class ScriptCompiler
{
public:
unsigned char *code_pos;
unsigned char *code_ptr;
unsigned char *prog_ptr;
unsigned char *prog_end_ptr;
GameScript *script;
StateScript *stateScript;
bool bCanBreak;
bool bCanContinue;
opcode_info_t prev_opcodes[ 100 ];
unsigned int prev_opcode_pos;
int m_iVarStackOffset;
int m_iInternalMaxVarStackOffset;
int m_iMaxExternalVarStackOffset;
int m_iMaxCallStackOffset;
int m_iHasExternal;
unsigned char *apucBreakJumpLocations[ BREAK_JUMP_LOCATION_COUNT ];
int iBreakJumpLocCount;
unsigned char *apucContinueJumpLocations[ CONTINUE_JUMP_LOCATION_COUNT ];
int iContinueJumpLocCount;
bool compileSuccess;
static int current_label;
public:
ScriptCompiler();
void Reset();
unsigned char PrevOpcode();
char PrevVarStackOffset();
void AbsorbPrevOpcode();
void ClearPrevOpcode();
void AddBreakJumpLocation( unsigned char *pos );
void AddContinueJumpLocation( unsigned char *pos );
void AddJumpLocation( unsigned char *pos );
void AddJumpBackLocation( unsigned char *pos );
void AddJumpToLocation( unsigned char *pos );
bool BuiltinReadVariable( unsigned int sourcePos, int type, int eventnum );
bool BuiltinWriteVariable( unsigned int sourcePos, int type, int eventnum );
void EmitAssignmentStatement( sval_t lhs, unsigned int sourcePos );
void EmitBoolJumpFalse( unsigned int sourcePos );
void EmitBoolJumpTrue( unsigned int sourcePos );
void EmitBoolNot( unsigned int sourcePos );
void EmitBoolToVar( unsigned int sourcePos );
void EmitBreak( unsigned int sourcePos );
void EmitCatch( sval_t val, unsigned char *try_begin_code_pos, unsigned int sourcePos );
void EmitConstArray( sval_t lhs, sval_t rhs, unsigned int sourcePos );
void EmitConstArrayOpcode( int iCount );
void EmitContinue( unsigned int sourcePos );
void EmitDoWhileJump( sval_t while_stmt, sval_t while_expr, unsigned int sourcePos );
void EmitEof( unsigned int sourcePos );
void EmitField( sval_t listener_val, sval_t field_val, unsigned int sourcePos );
void EmitFloat( float value, unsigned int sourcePos );
void EmitFunc1( int opcode, unsigned int sourcePos );
void EmitFunction( int iParamCount, sval_t val, unsigned int sourcePos );
void EmitIfElseJump( sval_t if_stmt, sval_t else_stmt, unsigned int sourcePos );
void EmitIfJump( sval_t if_stmt, unsigned int sourcePos );
void EmitInteger( unsigned int value, unsigned int sourcePos );
void EmitJump( unsigned char *pos, unsigned int sourcePos );
void EmitJumpBack( unsigned char *pos, unsigned int sourcePos );
void EmitLabel( str name, unsigned int sourcePos );
void EmitLabelParameterList( sval_t parameter_list, unsigned int sourcePos );
void EmitLabelPrivate( str name, unsigned int sourcePos );
void EmitLogicJump( sval_t logic_stmt, bool isOr, unsigned int sourcePos );
void EmitMakeArray( sval_t val );
void EmitMethodExpression( int iParamCount, int eventnum, unsigned int sourcePos );
void EmitNil( unsigned int sourcePos );
void EmitNop();
int EmitNot( unsigned int sourcePos );
void EmitOpcode( int opcode, unsigned int sourcePos );
void EmitParameter( sval_u lhs, unsigned int sourcePos );
int EmitParameterList( sval_t event_parameter_list );
void EmitRef( sval_t val, unsigned int sourcePos );
void EmitStatementList( sval_t val );
void EmitString( str value, unsigned int sourcePos );
void EmitSwitch( sval_t val, unsigned int sourcePos );
void EmitValue( sval_t val );
void EmitValue( ScriptVariable& var, unsigned int sourcePos );
void EmitVarToBool( unsigned int sourcePos );
void EmitWhileJump( sval_t while_expr, sval_t while_stmt, sval_t inc_stmt, unsigned int sourcePos );
bool EvalPrevValue( ScriptVariable& var );
void OptimizeInstructions( unsigned char *code, unsigned char *op1, unsigned char *op2 );
int OptimizeValue( int val1, int val2, unsigned char opcode );
void ProcessBreakJumpLocations( int iStartBreakJumpLocCount );
void ProcessContinueJumpLocations( int iStartContinueJumpLocCount );
unsigned char *GetPosition();
// compile
void CompileError( unsigned int sourcePos, const char *format, ... );
scriptmacro_t *GetMacro( char *sourceLine );
char *Preprocess( char *sourceBuffer );
void Preclean( char *processedBuffer );
unsigned int Parse( GameScript *m_GameScript, char *sourceBuffer );
unsigned int Compile( GameScript *m_GameScript, unsigned char *progBuffer );
void Optimize( unsigned char *progBuffer );
static str GetLine( str content, int line );
};
extern ScriptCompiler Compiler;
void CompileAssemble( const char *filename, const char *outputfile );
bool GetCompiledScript( GameScript *scr );
#endif

266
code/globalcpp/console.cpp Normal file
View file

@ -0,0 +1,266 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// console.h: TU Console.
#include "console.h"
#include <Windows.h>
CLASS_DECLARATION( Listener, ConsoleInput, NULL )
{
{ NULL, NULL }
};
#ifdef WIN32
HANDLE WINAPI WIN_CreateThread
(
LPSECURITY_ATTRIBUTES lpThreadAttributes,
SIZE_T dwStackSize,
LPTHREAD_START_ROUTINE lpStartAddress,
LPVOID lpParameter,
DWORD dwCreationFlags,
LPDWORD lpThreadId
)
{
return CreateThread( lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, lpThreadId );
}
DWORD WINAPI InputThread
(
LPVOID lpParameter
)
{
ConsoleInput *console = ( ConsoleInput * )lpParameter;
console->Input_Idle();
return 0;
}
#else
void *InputThread
(
void *arg
)
{
ConsoleInput *console = ( ConsoleInput * )lpParameter;
console->Input_Idle();
return NULL;
}
#endif
ConsoleInput::ConsoleInput()
{
}
ConsoleInput::ConsoleInput( Listener *consoleEvent )
{
m_pConsoleEvent = consoleEvent;
}
void ConsoleInput::InitInput( void )
{
#ifdef WIN32
WIN_CreateThread( NULL, 0, InputThread, ( void * )this, 0, NULL );
#else
pthread_t thread;
pthread_create( &thread, NULL, ( void * ( *)( void * ) )&InputThread, ( void * )this );
#endif
}
bool ConsoleInput::CheckEvent
(
Event *ev
)
{
EventDef *def = m_pConsoleEvent->classinfo()->GetDef( ev->eventnum );
if( !def )
{
return false;
}
if( !( def->flags & EV_CONSOLE ) )
{
return false;
}
return true;
}
void ConsoleInput::PrintHelp
(
void
)
{
ResponseDef< Class > *r;
bi.Printf( "Command list :\n\n" );
r = m_pConsoleEvent->classinfo()->responses;
while( r->event )
{
r->def->PrintEventDocumentation( stdout, false );
r++;
}
}
bool ConsoleInput::Execute
(
const char *data
)
{
char *buffer;
const char *com_token;
str sCommand;
buffer = ( char * )bi.Malloc( strlen( data ) + 1 );
strcpy( buffer, data );
com_token = COM_Parse( &buffer );
if( !com_token )
{
Com_Printf( "Enter a valid command.\n" );
return false;
}
sCommand = com_token;
if( Event::FindEventNum( sCommand ) )
{
Event *ev = new Event( sCommand );
while( 1 )
{
com_token = COM_Parse( &buffer );
if( !com_token[ 0 ] )
break;
ev->AddString( com_token );
}
if( CheckEvent( ev ) )
{
m_pConsoleEvent->ProcessEvent( ev );
}
else
{
Com_Printf( "Command '%s' not available from console.\n", sCommand.c_str() );
return false;
}
}
else
{
Com_Printf( "Command '%s' is not valid. Type help for more info.\n", sCommand.c_str() );
return false;
}
return true;
}
bool ConsoleInput::Execute
(
int argc,
char *argv[]
)
{
size_t iLength = 0;
int i;
char *data;
for( i = 1; i < argc; i++ )
{
iLength += strlen( argv[ i ] ) + 1;
}
if( iLength <= 1 )
{
return false;
}
data = ( char * )bi.Malloc( iLength + 1 );
memset( data, 0, iLength + 1 );
for( i = 1; i < argc; i++ )
{
strcat( data, argv[ i ] );
strcat( data, " " );
}
return Execute( data );
}
void ConsoleInput::Input_Idle
(
void
)
{
char *szBuffer = ( char * )bi.Malloc( 255 );
int i;
while( 1 )
{
i = 0;
/*while( !feof( stdin ) )
{
szBuffer[ i ] = getchar();
if( szBuffer[ i ] == '\r' || szBuffer[ i ] == '\n' )
{
szBuffer[ i ] = 0;
break;
}
if( szBuffer[ i ] == '\b' )
{
szBuffer[ i ] = 0;
i--;
}
else
{
i++;
}
}
*/
fgets( szBuffer, 255, stdin );
OemToCharBuff( szBuffer, szBuffer, 255 );
Execute( szBuffer );
}
}

52
code/globalcpp/console.h Normal file
View file

@ -0,0 +1,52 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// console.h: Console.
#ifndef __CONSOLE_H__
#define __CONSOLE_H__
#include <listener.h>
class ConsoleInput : public Listener {
private:
Listener *m_pConsoleEvent;
public:
void Input_Idle( void );
public:
CLASS_PROTOTYPE( ConsoleInput );
ConsoleInput();
ConsoleInput( Listener *consoleEvent );
void InitInput( void );
bool Execute( const char *data );
bool Execute( int argc, char *argv[] );
bool CheckEvent( Event *ev );
void PrintHelp( void );
};
#endif /* __CONSOLE_H__ */

128
code/globalcpp/const_str.h Normal file
View file

@ -0,0 +1,128 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// const_str.h: Strings constant, improve performance in string comparison
#ifndef __CONST_STR_H__
#define __CONST_STR_H__
enum
{
STRING_EMPTY = 1,
STRING_TOUCH, STRING_BLOCK, STRING_TRIGGER, STRING_USE,
STRING_DAMAGE,STRING_LOCATION,
STRING_SAY, STRING_FAIL, STRING_BUMP,
STRING_DEFAULT, STRING_ALL,
STRING_MOVE_ACTION, STRING_RESUME, STRING_OPEN, STRING_CLOSE, STRING_PICKUP, STRING_REACH, STRING_START,
STRING_TELEPORT,
STRING_MOVE, STRING_MOVE_END, STRING_MOVETO, STRING_WALKTO, STRING_RUNTO, STRING_CROUCHTO, STRING_CRAWLTO, STRING_STOP,
STRING_RESET, STRING_PRESPAWN, STRING_SPAWN, STRING_PLAYERSPAWN, STRING_SKIP, STRING_ROUNDSTART,
STRING_VISIBLE, STRING_NOT_VISIBLE,
STRING_DONE, STRING_ANIMDONE, STRING_UPPERANIMDONE, STRING_SAYDONE, STRING_FLAGGEDANIMDONE,
STRING_IDLE, STRING_WALK, STRING_SHUFFLE,
STRING_ANIM_CROUCH_SCR,
STRING_FORGOT,
STRING_JOG_HUNCH, STRING_JOG_HUNCH_RIFLE,
STRING_KILLED,
STRING_ALARM, STRING_SCRIPTCLASS, STRING_FACT_SCRIPT_FACTORY,
STRING_DEATH, STRING_DEATH_FALL_TO_KNEES,
STRING_ENEMY,
STRING_DEAD,
STRING_MOOD,
STRING_PATROL, STRING_RUNNER, STRING_FOLLOW,
STRING_ACTION, STRING_MOVE_BEGIN, STRING_ACTION_BEGIN, STRING_ACTION_END,
STRING_SUCCESS, STRING_ENTRY, STRING_EXIT, STRING_PATH, STRING_NODE,
STRING_ASK_COUNT,
STRING_ATTACKER, STRING_USECOVER, STRING_WAITCOVER, STRING_VOID, STRING_END, STRING_ATTACK, STRING_NEAR,
STRING_PAPERS, STRING_CHECK_PAPERS,
STRING_TIMEOUT,
STRING_HOSTILE, STRING_LEADER,
STRING_GAMEMAP,
STRING_BORED, STRING_NERVOUS, STRING_CURIOUS, STRING_ALERT, STRING_GREET, STRING_DEFEND,
STRING_ANIM, STRING_ANIM_SCRIPTED, STRING_ANIM_CURIOUS, STRING_ANIMLOOP, STRING_UNDEFINED, STRING_NOTSET,
STRING_INCREMENT, STRING_DECREMENT, STRING_TOGGLE,
STRING_NORMAL, STRING_SUSPENSE, STRING_MYSTERY, STRING_SURPRISE,
STRING_ANIM_CROUCH_RUN_SCR,
STRING_ANIM_AIM_SCR, STRING_ANIM_SHOOT_SCR, STRING_ANIM_MG42_SHOOT_SCR, STRING_ANIM_MG42_IDLE_SCR, STRING_ANIM_MG42_RELOAD_SCR,
STRING_DRIVE,
STRING_GLOBAL_WEAPON_SCR, STRING_GLOBAL_MOVETO_SCR,
STRING_GLOBAL_ANIM_SCR, STRING_GLOBAL_ANIM_SCRIPTED_SCR, STRING_GLOBAL_ANIM_NOCLIP_SCR, STRING_GLOBAL_WALKTO_SCR, STRING_GLOBAL_RUNTO_SCR, STRING_AIMAT,
STRING_GLOBAL_DISABLE_AI_SCR,
STRING_GLOBAL_CROUCHTO_SCR, STRING_GLOBAL_CRAWLTO_SCR,
STRING_GLOBAL_KILLED_SCR, STRING_GLOBAL_PAIN_SCR, STRING_PAIN,
STRING_TRACK, STRING_HASENEMY,
STRING_ANIM_COWER_SCR, STRING_ANIM_STAND_SCR, STRING_ANIM_IDLE_SCR, STRING_ANIM_SURPRISE_SCR, STRING_ANIM_STANDSHOCK_SCR, STRING_ANIM_STANDIDENTIFY_SCR, STRING_ANIM_STANDFLINCH_SCR, STRING_ANIM_DOG_IDLE_SCR, STRING_ANIM_DOG_ATTACK_SCR, STRING_ANIM_DOG_CURIOUS_SCR, STRING_ANIM_DOG_CHASE_SCR,
STRING_CANNON, STRING_GRENADE, STRING_HEAVY,
STRING_ITEM, STRING_ITEMS, STRING_ITEM1, STRING_ITEM2, STRING_ITEM3, STRING_ITEM4,
STRING_STAND,
STRING_MG, STRING_PISTOL, STRING_RIFLE, STRING_SMG,
STRING_TURNTO,
STRING_STANDING, STRING_CROUCHING, STRING_PRONE, STRING_OFFGROUND, STRING_WALKING, STRING_RUNNING, STRING_FALLING,
STRING_ANIM_NOTHING, STRING_ANIM_DIRECT, STRING_ANIM_PATH, STRING_ANIM_WAYPOINT, STRING_ANIM_DIRECT_NOGRAVITY,
STRING_EMOTION_NONE, STRING_EMOTION_NEUTRAL,
STRING_EMOTION_WORRY, STRING_EMOTION_PANIC, STRING_EMOTION_FEAR,
STRING_EMOTION_DISGUST, STRING_EMOTION_ANGER,
STRING_EMOTION_AIMING, STRING_EMOTION_DETERMINED,
STRING_EMOTION_DEAD,
STRING_EMOTION_CURIOUS,
STRING_ANIM_EMOTION_SCR,
STRING_FORCEANIM, STRING_FORCEANIM_SCRIPTED,
STRING_TURRET, STRING_COVER,
STRING_ANIM_PAIN_SCR, STRING_ANIM_KILLED_SCR, STRING_ANIM_ATTACK_SCR, STRING_ANIM_SNIPER_SCR,
STRING_KNEES, STRING_CRAWL, STRING_FLOOR,
STRING_ANIM_PATROL_SCR, STRING_ANIM_RUN_SCR, STRING_CROUCH, STRING_CROUCHWALK, STRING_CROUCHRUN, STRING_ANIM_CROUCH_WALK_SCR, STRING_ANIM_WALK_SCR, STRING_ANIM_PRONE_SCR,
STRING_ANIM_RUNAWAYFIRING_SCR, STRING_ANIM_RUN_SHOOT_SCR, STRING_ANIM_RUNTO_ALARM_SCR, STRING_ANIM_RUNTO_CASUAL_SCR, STRING_ANIM_RUNTO_COVER_SCR, STRING_ANIM_RUNTO_DANGER_SCR, STRING_ANIM_RUNTO_DIVE_SCR, STRING_ANIM_RUNTO_FLEE_SCR, STRING_ANIM_RUNTO_INOPEN_SCR,
STRING_ANIM_DISGUISE_SALUTE_SCR, STRING_ANIM_DISGUISE_WAIT_SCR, STRING_ANIM_DISGUISE_PAPERS_SCR, STRING_ANIM_DISGUISE_ENEMY_SCR, STRING_ANIM_DISGUISE_HALT_SCR, STRING_ANIM_DISGUISE_ACCEPT_SCR, STRING_ANIM_DISGUISE_DENY_SCR,
STRING_ANIM_CORNERLEFT_SCR, STRING_ANIM_CORNERRIGHT_SCR,
STRING_ANIM_OVERATTACK_SCR,
STRING_ANIM_CONTINUE_LAST_ANIM_SCR,
STRING_FLAGGED,
STRING_ANIM_FULLBODY_SCR,
STRING_INTERNAL,
STRING_DISGUISE_SALUTE, STRING_DISGUISE_SENTRY, STRING_DISGUISE_OFFICER, STRING_DISGUISE_ROVER, STRING_DISGUISE_NONE,
STRING_MACHINEGUNNER,
STRING_DISGUISE,
STRING_DOG_IDLE, STRING_DOG_ATTACK, STRING_DOG_CURIOUS, STRING_DOG_GRENADE,
STRING_ANIM_GRENADERETURN_SCR, STRING_ANIM_GRENADEKICK_SCR, STRING_ANIM_GRENADETHROW_SCR, STRING_ANIM_GRENADETOSS_SCR, STRING_ANIM_GRENADEMARTYR_SCR,
STRING_MOVEDONE,
STRING_AIM, STRING_ONTARGET,
STRING_UNARMED,
STRING_BALCONY_IDLE, STRING_BALCONY_CURIOUS, STRING_BALCONY_ATTACK, STRING_BALCONY_DISGUISE, STRING_BALCONY_GRENADE, STRING_BALCONY_PAIN, STRING_BALCONY_KILLED,
STRING_WEAPONLESS,
STRING_DEATH_BALCONY_INTRO, STRING_DEATH_BALCONY_LOOP, STRING_DEATH_BALCONY_OUTTRO,
STRING_SOUNDDONE,
STRING_NOCLIP,
STRING_GERMAN, STRING_AMERICAN, STRING_SPECTATOR, STRING_FREEFORALL, STRING_ALLIES, STRING_AXIS,
STRING_DRAW, STRING_KILLS, STRING_ALLIESWIN, STRING_AXISWIN,
STRING_ANIM_SAY_CURIOUS_SIGHT_SCR, STRING_ANIM_SAY_CURIOUS_SOUND_SCR, STRING_ANIM_SAY_GRENADE_SIGHTED_SCR, STRING_ANIM_SAY_KILL_SCR, STRING_ANIM_SAY_MANDOWN_SCR, STRING_ANIM_SAY_SIGHTED_SCR,
STRING_VEHICLEANIMDONE,
STRING_POSTTHINK,
STRING_TURNDONE,
STRING_ANIM_NO_KILLED_SCR,
STRING_MG42, STRING_MP40,
STRING_REMOVE, STRING_DELETE,
STRING_RESPAWN,
STRING_NONE,
STRING_LENGTH_
};
#endif

491
code/globalcpp/container.h Normal file
View file

@ -0,0 +1,491 @@
/*
===========================================================================
Copyright (C) 2008 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// container.h: C++ Container
#ifndef __CONTAINER_H__
#define __CONTAINER_H__
#ifdef GAME_DLL
#ifdef WIN32
#define glbprintf( text ) gi.Printf( text )
#else
#define glbprintf( text )
#endif
#elif defined CGAME_DLL
#define glbprintf( text ) cgi.Printf( text )
#else
#define glbprintf( text ) printf( text )
#endif
#ifdef _DEBUG
#define CONTAINER_Error( id, text ) glbprintf( text ); assert( 0 );
#else
#define CONTAINER_Error( id, text ) throw( text ) //gi.Error
#endif
#define CONTAINER_DPrintf( text ) glbprintf( text )
#define CONTAINER_WDPrintf( text ) glbprintf( text )
class Archiver;
template< class Type >
class Container
{
private:
Type *objlist;
int numobjects;
int maxobjects;
private:
void Copy( const Container<Type>& container );
public:
Container();
Container( const Container<Type>& container );
~Container();
void Archive( Archiver& arc );
void Archive( Archiver& arc, void( *ArchiveFunc )( Archiver &arc, Type *obj ) );
int AddObject( const Type& obj );
int AddUniqueObject( const Type& obj );
void AddObjectAt( int index, const Type& obj );
Type *AddressOfObjectAt( int index );
// void Archive( Archiver &arc );
void ClearObjectList( void );
void Fix( void );
void FreeObjectList( void );
int IndexOfObject( const Type& obj );
void InsertObjectAt( int index, const Type& obj );
int MaxObjects( void ) const;
int NumObjects( void ) const;
Type& ObjectAt( const int index ) const;
bool ObjectInList( const Type& obj );
void RemoveObjectAt( int index );
void RemoveObject( const Type& obj );
void Reset( void );
void Resize( int maxelements );
void SetObjectAt( int index, const Type& obj );
void Sort( int( *compare )( const void *elem1, const void *elem2 ) );
Type& operator[]( const int index ) const;
Container<Type>& operator=( const Container<Type>& container );
};
template< class Type >
Container<Type>::Container()
{
objlist = NULL;
numobjects = 0;
maxobjects = 0;
}
template< class Type >
Container<Type>::Container( const Container<Type>& container )
{
objlist = NULL;
Copy( container );
}
template< class Type >
Container<Type>::~Container()
{
FreeObjectList();
}
template< class Type >
int Container<Type>::AddObject( const Type& obj )
{
if ( !objlist )
Resize( 10 );
if ( numobjects >= maxobjects ) {
Resize( numobjects * 2 );
}
objlist[numobjects] = obj;
numobjects++;
return numobjects;
}
template< class Type >
int Container<Type>::AddUniqueObject( const Type& obj )
{
int index;
index = IndexOfObject( obj );
if ( !index ) {
index = AddObject( obj );
}
return index;
}
template< class Type >
void Container<Type>::AddObjectAt( int index, const Type& obj )
{
if ( index > maxobjects )
Resize( index );
if ( index > numobjects )
numobjects = index;
SetObjectAt( index, obj );
}
template< class Type >
Type *Container<Type>::AddressOfObjectAt( int index )
{
if ( index > maxobjects ) {
CONTAINER_Error( ERR_DROP, "Container::AddressOfObjectAt : index is greater than maxobjects" );
}
if ( index > numobjects ) {
numobjects = index;
}
return &objlist[index - 1];
}
/*template< class Type >
void Container<Type>::Archive( Archiver &arc )
{
}*/
template< class Type >
void Container<Type>::ClearObjectList( void )
{
if ( objlist && numobjects )
{
delete[] objlist;
if ( maxobjects == 0 )
{
objlist = NULL;
return;
}
objlist = new Type[maxobjects];
numobjects = 0;
}
}
template< class Type >
void Container<Type>::Fix( void )
{
if( !objlist || !numobjects ) {
return;
}
Type *newlist = new Type[ numobjects ];
int j = 0;
for( int i = 0; i < numobjects; i++ )
{
if( objlist[ i ] == NULL ) {
continue;
}
newlist[ j ] = objlist[ i ];
j++;
}
numobjects = j;
delete[] objlist;
objlist = newlist;
if( !numobjects ) {
ClearObjectList();
}
}
template< class Type >
void Container<Type>::FreeObjectList( void )
{
if( objlist ) {
delete[] objlist;
}
objlist = NULL;
numobjects = 0;
maxobjects = 0;
}
template< class Type >
int Container<Type>::IndexOfObject( const Type& obj )
{
int i;
if ( !objlist ) {
return 0;
}
for ( i = 0; i < numobjects; i++ )
{
if ( objlist[i] == obj )
{
return i + 1;
}
}
return 0;
}
template< class Type >
void Container<Type>::InsertObjectAt( int index, const Type& obj )
{
if ( ( index <= 0 ) || ( index > numobjects + 1 ) )
{
CONTAINER_Error( ERR_DROP, "Container::InsertObjectAt : index out of range" );
return;
}
numobjects++;
int arrayIndex = index - 1;
if ( numobjects > maxobjects )
{
maxobjects = numobjects;
if ( !objlist ) {
objlist = new Type[maxobjects];
objlist[arrayIndex] = obj;
return;
}
else
{
Type *temp = objlist;
if ( maxobjects < numobjects )
{
maxobjects = numobjects;
}
objlist = new Type[maxobjects];
int i;
for ( i = arrayIndex - 1; i >= 0; i-- ) {
objlist[i] = temp[i];
}
objlist[arrayIndex] = obj;
for ( i = numobjects - 1; i > arrayIndex; i-- ) {
objlist[i] = temp[i - 1];
}
delete[] temp;
}
}
else
{
for ( int i = numobjects - 1; i > arrayIndex; i-- ) {
objlist[i] = objlist[i - 1];
}
objlist[arrayIndex] = obj;
}
}
template< class Type >
int Container<Type>::MaxObjects( void ) const
{
return maxobjects;
}
template< class Type >
int Container<Type>::NumObjects( void ) const
{
return numobjects;
}
template< class Type >
Type& Container<Type>::ObjectAt( int index ) const
{
if( ( index <= 0 ) || ( index > numobjects ) ) {
CONTAINER_Error( ERR_DROP, "Container::ObjectAt : index out of range" );
}
return objlist[index - 1];
}
template< class Type >
bool Container<Type>::ObjectInList( const Type& obj )
{
if ( !IndexOfObject( obj ) ) {
return false;
}
return true;
}
template< class Type >
void Container<Type>::RemoveObjectAt( int index )
{
int i;
if ( !objlist )
return;
if ( ( index <= 0 ) || ( index > numobjects ) )
return;
i = index - 1;
numobjects--;
for ( i = index - 1; i < numobjects; i++ )
objlist[i] = objlist[i + 1];
}
template< class Type >
void Container<Type>::RemoveObject( const Type& obj )
{
int index;
index = IndexOfObject( obj );
assert( index );
if ( !index )
{
CONTAINER_WDPrintf( "Container::RemoveObject : Object not in list\n" );
return;
}
RemoveObjectAt( index );
}
template< class Type >
void Container<Type>::Reset()
{
objlist = NULL;
numobjects = 0;
maxobjects = 0;
}
template< class Type >
void Container<Type>::Resize( int maxelements )
{
Type* temp;
int i;
if ( maxelements <= 0 )
{
FreeObjectList();
return;
}
if ( !objlist )
{
maxobjects = maxelements;
objlist = new Type[maxobjects];
}
else
{
temp = objlist;
maxobjects = maxelements;
if ( maxobjects < numobjects ) {
maxobjects = numobjects;
}
objlist = new Type[maxobjects];
for ( i = 0; i < numobjects; i++ ) {
objlist[i] = temp[i];
}
delete[] temp;
}
}
template< class Type >
void Container<Type>::SetObjectAt( int index, const Type& obj )
{
if ( !objlist )
return;
if( ( index <= 0 ) || ( index > numobjects ) ) {
CONTAINER_Error( ERR_DROP, "Container::SetObjectAt : index out of range" );
}
objlist[index - 1] = obj;
}
template< class Type >
void Container<Type>::Sort( int( *compare )( const void *elem1, const void *elem2 ) )
{
if ( !objlist ) {
return;
}
qsort( ( void * )objlist, ( size_t )numobjects, sizeof( Type ), compare );
}
template< class Type >
Type& Container<Type>::operator[]( const int index ) const
{
return ObjectAt( index + 1 );
}
template< class Type >
void Container<Type>::Copy( const Container<Type>& container )
{
int i;
if( &container == this ) {
return;
}
FreeObjectList();
numobjects = container.numobjects;
maxobjects = container.maxobjects;
objlist = NULL;
if( container.objlist == NULL || !container.maxobjects ) {
return;
}
Resize( maxobjects );
if( !container.numobjects ) {
return;
}
for( i = 0; i < container.numobjects; i++ ) {
objlist[ i ] = container.objlist[ i ];
}
return;
}
template< class Type >
Container<Type>& Container<Type>::operator=( const Container<Type>& container )
{
Copy( container );
return *this;
}
#endif /* __CONTAINER_H__ */

View file

@ -0,0 +1,62 @@
/*
===========================================================================
Copyright (C) 2008 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// containerclass.h: C++ Class Container for use with SafePtr
#ifndef __CONTAINERCLASS_H__
#define __CONTAINERCLASS_H__
#include "container.h"
template< class Type >
class ContainerClass : public Class {
Container< Type > value;
public:
virtual ~ContainerClass() { value.FreeObjectList(); }
virtual void Archive( Archiver& arc );
int AddObject( const Type& obj ) { return value.AddObject( obj ); }
int AddUniqueObject( const Type& obj ) { return value.AddUniqueObject( obj ); }
void AddObjectAt( int index, const Type& obj ) { return value.AddObjectAt( index, obj ); }
Type *AddressOfObjectAt( int index ) { return value.AddressOfObjectAt( index ); }
void ClearObjectList( void ) { return value.ClearObjectList(); }
void Fix( void ) { return value.Fix(); }
void FreeObjectList( void ) { return value.FreeObjectList(); }
int IndexOfObject( const Type& obj ) { return value.IndexOfObject( obj ); }
void InsertObjectAt( int index, const Type& obj ) { return value.InsertObjectAt( index, obj ); }
int NumObjects( void ) const { return value.NumObjects(); }
Type& ObjectAt( const int index ) const { return value.ObjectAt( index ); }
bool ObjectInList( const Type& obj ) { return value.ObjectInList( obj ); }
void RemoveObjectAt( int index ) { return value.RemoveObjectAt( index ); }
void RemoveObject( const Type& obj ) { return value.RemoveObject( obj ); }
void Reset( void ) { return value.Reset(); }
void Resize( int maxelements ) { return value.Resize( maxelements ); }
void SetObjectAt( int index, const Type& obj ) { return value.SetObjectAt( index, obj ); }
void Sort( int( *compare )( const void *elem1, const void *elem2 ) ) { return value.Sort( compare ); }
Type& operator[]( const int index ) const { return value[ index ]; }
Container<Type>& operator=( const Container<Type>& container ) { return value = container; }
};
#endif /* __CONTAINERCLASS_H__ */

88
code/globalcpp/crc32.h Normal file
View file

@ -0,0 +1,88 @@
/*
===========================================================================
Copyright (C) 2008 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// crc32.h: CRC32 Encryption (used by the Archiver)
#ifndef __CRC32_H__
#define __CRC32_H8_
static unsigned int crc32_tab[] = {
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
};
inline
unsigned int crc32( unsigned int crc, const void *buf, size_t size )
{
const unsigned char *p;
p = ( const unsigned char * )buf;
crc = crc ^ ~0U;
while (size--)
crc = crc32_tab[(crc ^ *p++) & 0xFF] ^ (crc >> 8);
return crc ^ ~0U;
}
#endif // __CRC32_H__

226
code/globalcpp/dbgheap.cpp Normal file
View file

@ -0,0 +1,226 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// dbgheap.cpp: Heap Debugger.
#include <glb_local.h>
#include <dbgheap.h>
DbgHeap m_Heap;
refptr_t *DbgHeap::hashTable[ DBG_HEAP_HASHSIZE ];
#ifdef WIN32
extern "C" {
typedef struct _SYMBOL_INFO {
unsigned long SizeOfStruct;
unsigned long TypeIndex;
unsigned __int64 Reserved[ 2 ];
unsigned long Index;
unsigned long Size;
unsigned __int64 ModBase;
unsigned long Flags;
unsigned __int64 Value;
unsigned __int64 Address;
unsigned long Register;
unsigned long Scope;
unsigned long Tag;
unsigned long NameLen;
unsigned long MaxNameLen;
char Name[ 1 ];
} SYMBOL_INFO, *PSYMBOL_INFO;
unsigned short __stdcall RtlCaptureStackBackTrace
(
unsigned long FramesToSkip,
unsigned long FramesToCapture,
void *BackTrace,
unsigned long *BackTraceHash
);
void * __stdcall GetCurrentProcess
(
void
);
unsigned int __stdcall SymInitialize
(
void *hProcess,
const char *UserSearchPath,
int fInvadeProcess
);
unsigned int __stdcall SymFromAddr
(
void *hProcess,
unsigned long long Address,
unsigned long long *Displacement,
PSYMBOL_INFO Symbol
);
}
#endif
DbgHeap::DbgHeap()
{
}
DbgHeap::~DbgHeap()
{
/*
refptr_t *rootptr;
refptr_t *ref;
refptr_t *next;
for( int i = 0; i < DBG_HEAP_HASHSIZE; i++ )
{
rootptr = hashTable[ i ];
for( ref = rootptr; ref != NULL; ref = next )
{
next = ref->next;
free( ref );
}
}
rootptr = NULL;
*/
}
refptr_t *DbgHeap::FindReference
(
void *ptr
)
{
refptr_t *ref;
refptr_t *rootptr;
rootptr = hashTable[ ( ( size_t )ptr / 8 ) % DBG_HEAP_HASHSIZE ];
for( ref = rootptr; ref != NULL; ref = ref->next )
{
if( ref->ptr == ptr )
return ref;
}
return NULL;
}
void DbgHeap::ReferencePointer
(
void *ptr
)
{
refptr_t *ref = FindReference( ptr );
refptr_t **rootptr;
if( !ref )
{
ref = ( refptr_t * )malloc( sizeof( refptr_t ) );
ref->ptr = ptr;
ref->refcount = 0;
ref->next = NULL;
#ifdef WIN32
RtlCaptureStackBackTrace( 1, DBG_HEAP_MAX_CALLSTACK, ref->callstack, NULL );
#endif
rootptr = &hashTable[ ( ( size_t )ptr / 8 ) % DBG_HEAP_HASHSIZE ];
if( !*rootptr )
{
*rootptr = ref;
}
else
{
ref->next = *rootptr;
*rootptr = ref;
}
}
// Increase the reference count
ref->refcount++;
}
void DbgHeap::DereferencePointer
(
void *ptr
)
{
refptr_t *ref = FindReference( ptr );
assert( ref );
if( !ref )
{
// Trying to dereference a non-existing pointer
exit( EXIT_FAILURE );
return;
}
assert( ref->refcount > 0 );
if( !ref->refcount )
{
// Trying to dereference an unreferenced pointer
exit( EXIT_FAILURE );
return;
}
ref->refcount--;
#ifdef WIN32
RtlCaptureStackBackTrace( 1, DBG_HEAP_MAX_CALLSTACK, ref->callstack, NULL );
#endif
}
void *operator new( size_t size )
{
void *ptr = malloc( size );
m_Heap.ReferencePointer( ptr );
return ptr;
}
void *operator new[]( size_t size )
{
void *ptr = malloc( size );
m_Heap.ReferencePointer( ptr );
return ptr;
}
void operator delete( void *ptr )
{
m_Heap.DereferencePointer( ptr );
free( ptr );
}
void operator delete[]( void *ptr )
{
m_Heap.DereferencePointer( ptr );
free( ptr );
}

64
code/globalcpp/dbgheap.h Normal file
View file

@ -0,0 +1,64 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// dbgheap.h: Heap Debugger.
#ifndef __DBGHEAP_H__
#define __DBGHEAP_H__
#include <stdio.h>
#include <stdlib.h>
#define DBG_HEAP_HASHSIZE 4096
#define DBG_HEAP_MAX_CALLSTACK 16
typedef struct refptr {
void *ptr;
unsigned char refcount;
void *callstack[ DBG_HEAP_MAX_CALLSTACK ];
struct refptr *next;
} refptr_t;
class DbgHeap
{
private:
static refptr_t *hashTable[ DBG_HEAP_HASHSIZE ];
private:
refptr_t *FindReference( void *ptr );
public:
DbgHeap();
~DbgHeap();
void ReferencePointer( void *ptr );
void DereferencePointer( void *ptr );
};
extern void *operator new( size_t size );
extern void *operator new[]( size_t size );
extern void operator delete( void *ptr );
extern void operator delete[]( void *ptr );
extern DbgHeap m_Heap;
#endif /* dbgheap.h */

View file

@ -0,0 +1,268 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#include <q_shared.h>
#include <baseimp.h>
#include <str.h>
#include "dummy_base.h"
#include "../client/client.h"
#include <Windows.h>
clientStatic_t cls;
baseImport_t bi;
cvar_t *developer;
cvar_t *g_scriptcheck;
cvar_t *g_showopcodes;
cvar_t *precache;
cvar_t *sv_scriptfiles;
void Com_FillBaseImports() {
bi.Printf = BI_Printf;
bi.DPrintf = BI_DPrintf;
bi.Error = BI_Error;
bi.Free = BI_Free;
bi.Malloc = BI_Malloc;
bi.Milliseconds = BI_Milliseconds;
bi.FS_FreeFile = FS_FreeFile;
bi.FS_ReadFile = FS_ReadFile2;
bi.FS_CanonicalFilename = FS_CanonicalFilename;
}
void Z_InitMemory() {
}
void Cmd_Init( void ) {
}
void Cvar_Init( void ) {
}
void FS_InitFilesystem( void ) {
}
void FS_InitFilesystem2( void ) {
}
void QDECL Com_Error( int level, const char *error, ... ) {
va_list argptr;
char *buffer;
int size;
va_start( argptr, error );
size = vsnprintf( NULL, 0, error, argptr );
va_end( argptr );
buffer = ( char * )bi.Malloc( size + 1 );
buffer[ size ] = 0;
va_start( argptr, error );
vsnprintf( buffer, size, error, argptr );
va_end( argptr );
bi.Error( level, "%s", buffer );
bi.Free( buffer );
}
void QDECL Com_Printf( const char *msg, ... ) {
va_list argptr;
char *buffer;
int size;
va_start( argptr, msg );
size = vsnprintf( NULL, 0, msg, argptr );
va_end( argptr );
buffer = ( char * )bi.Malloc( size + 1 );
buffer[ size ] = 0;
va_start( argptr, msg );
vsnprintf( buffer, size, msg, argptr );
va_end( argptr );
bi.Printf( "%s", buffer );
bi.Free( buffer );
}
void QDECL Com_DPrintf( const char *msg, ... ) {
va_list argptr;
char *buffer;
int size;
va_start( argptr, msg );
size = vsnprintf( NULL, 0, msg, argptr );
va_end( argptr );
buffer = ( char * )bi.Malloc( size + 1 );
buffer[ size ] = 0;
va_start( argptr, msg );
vsnprintf( buffer, size, msg, argptr );
va_end( argptr );
bi.DPrintf( "%s", buffer );
bi.Free( buffer );
}
void BI_Printf( const char *msg, ... )
{
va_list argptr;
char *buffer;
int size;
va_start( argptr, msg );
size = vsnprintf( NULL, 0, msg, argptr );
va_end( argptr );
buffer = ( char * )bi.Malloc( size + 1 );
buffer[ size ] = 0;
va_start( argptr, msg );
vsnprintf( buffer, size, msg, argptr );
va_end( argptr );
printf( "%s", buffer );
bi.Free( buffer );
}
void BI_DPrintf( const char *msg, ... )
{
#ifdef _DEBUG
va_list argptr;
char *buffer;
int size;
if( !developer->integer ) {
return;
}
va_start( argptr, msg );
size = vsnprintf( NULL, 0, msg, argptr );
va_end( argptr );
buffer = ( char * )bi.Malloc( size + 1 );
buffer[ size ] = 0;
va_start( argptr, msg );
vsnprintf( buffer, size, msg, argptr );
va_end( argptr );
printf( "%s", buffer );
bi.Free( buffer );
#endif
}
void BI_Error( int level, const char *msg, ... )
{
va_list argptr;
char *buffer;
int size;
va_start( argptr, msg );
size = vsnprintf( NULL, 0, msg, argptr );
va_end( argptr );
buffer = ( char * )bi.Malloc( size + 1 );
buffer[ size ] = 0;
va_start( argptr, msg );
vsnprintf( buffer, size, msg, argptr );
va_end( argptr );
BI_Printf( "%s", buffer );
bi.Free( buffer );
}
int BI_Milliseconds( void )
{
return GetTickCount();
}
void *BI_Malloc( int size )
{
return malloc( size );
}
void BI_Free( void *ptr )
{
free( ptr );
}
void FS_FreeFile( void *buffer )
{
bi.Free( buffer );
}
int FS_ReadFile2( const char *name, void **buffer, qboolean bSilent )
{
str filename = name;
FILE *file = fopen( filename, "rb+" );
int size;
char *p;
if( file == NULL )
{
return -1;
}
fseek( file, 0, SEEK_END );
size = ftell( file );
rewind( file );
*buffer = bi.Malloc( size + 1 );
memset( *buffer, 0, size );
fread( *buffer, size, 1, file );
fclose( file );
p = ( char * )*buffer;
p[ size ] = 0;
return size;
}
void FS_CanonicalFilename( char *filename )
{
char *p = filename;
while( *p )
{
if( p[ 0 ] == '/' && p[ 1 ] == '/' )
{
char *p2 = p + 1;
while( *p2 )
{
p2[ 0 ] = p2[ 1 ];
p2++;
}
}
p++;
}
}

View file

@ -0,0 +1,56 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#ifndef __DUMY_BASE_H__
#define __DUMY_BASE_H__
#include <glb_local.h>
#include "q_shared.h"
#ifdef __cplusplus
extern "C" {
#endif
void Com_FillBaseImports();
void Z_InitMemory();
void Cmd_Init( void );
void Cvar_Init( void );
void FS_InitFilesystem( void );
void BI_Printf( const char *msg, ... );
void BI_DPrintf( const char *msg, ... );
void BI_Error( int level, const char *msg, ... );
int BI_Milliseconds( void );
void * BI_Malloc( int size );
void BI_Free( void *ptr );
int FS_ReadFile2( const char *name, void **buffer, qboolean bSilent );
//void FS_FreeFile( void *buffer );
//int FS_ReadFile( const char *name, void **buffer, bool bSilent );
//void FS_CanonicalFilename( char *filename );
#ifdef __cplusplus
}
#endif
#endif /* __DUMY_BASE_H__ */

View file

@ -0,0 +1,60 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#include "game.h"
Game game;
void CacheResource( const char *name )
{
}
SimpleEntity *G_FindTarget( SimpleEntity *next, const char *classname )
{
return NULL;
}
Vector G_GetMovedir( float angle )
{
if( angle == -1.0f )
{
return Vector( 0.0f, 0.0f, 1.0f );
}
else if( angle == -2.0f )
{
return Vector( 0.0f, 0.0f, -1.0f );
}
angle *= ( M_PI * 2.0f / 360.0f );
return Vector( cos( angle ), sin( angle ), 0.0f );
}
float G_Random( float value )
{
return fmod( rand(), value );
}
CLASS_DECLARATION( Listener, Game, NULL )
{
{ NULL, NULL }
};

View file

@ -0,0 +1,46 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// game.cpp : TU Level.
#include "level.h"
Level level;
void Level::setTime( int levelTime )
{
svsTime = levelTime;
inttime = levelTime - svsStartTime;
svsFloatTime = levelTime / 1000.0f;
time = inttime / 1000.0f;
}
void Level::setFrametime( int frametime )
{
intframetime = frametime;
this->frametime = frametime / 1000.0f;
}
CLASS_DECLARATION( Listener, Level, NULL )
{
{ NULL, NULL }
};

View file

@ -0,0 +1,38 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#ifndef __GAME_H__
#define __GAME_H__
#include <listener.h>
class Game : public Listener {
CLASS_PROTOTYPE( Game );
};
extern Game game;
SimpleEntity *G_FindTarget( SimpleEntity *next, const char *classname );
Vector G_GetMovedir( float angle );
float G_Random( float value );
#endif /* __GAME_H__*/

View file

@ -0,0 +1,68 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#ifndef __LEVEL_H__
#define __LEVEL_H__
#include <listener.h>
class SimpleArchivedEntity;
class Level : public Listener {
public:
bool m_LoopDrop;
bool m_LoopProtection;
str m_mapscript;
str current_map;
// Level time
int framenum;
int inttime;
int intframetime;
float time;
float frametime;
int spawnflags;
// Server time
int svsTime;
float svsFloatTime;
int svsStartTime;
int svsEndTime;
bool m_bScriptSpawn;
bool m_bRejectSpawn;
Container< SimpleArchivedEntity * > m_SimpleArchivedEntities;
public:
CLASS_PROTOTYPE( Level );
void setTime( int _svsTime_ );
void setFrametime( int frameTime );
};
extern Level level;
#endif /* __LEVEL_H__*/

1406
code/globalcpp/g_spawn.cpp Normal file

File diff suppressed because it is too large Load diff

81
code/globalcpp/g_spawn.h Normal file
View file

@ -0,0 +1,81 @@
/*
===========================================================================
Copyright (C) 2008 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// g_spawn.h : spawner for scripts.
#ifndef __G_SPAWN_H__
#define __G_SPAWN_H__
#include "glb_local.h"
// spawnflags
// these are set with checkboxes on each entity in the map editor
#define SPAWNFLAG_NOT_EASY 0x00000100
#define SPAWNFLAG_NOT_MEDIUM 0x00000200
#define SPAWNFLAG_NOT_HARD 0x00000400
#define SPAWNFLAG_NOT_DEATHMATCH 0x00000800
#define SPAWNFLAG_DEVELOPMENT 0x00002000
#define SPAWNFLAG_DETAIL 0x00004000
#define SPAWNFLAG_NOCONSOLE 0x00008000
#define SPAWNFLAG_NOPC 0x00010000
class Listener;
class SpawnArgs : public Class
{
private:
Container<str> keyList;
Container<str> valueList;
public:
CLASS_PROTOTYPE( SpawnArgs );
SpawnArgs();
SpawnArgs( SpawnArgs &arglist );
void Clear( void );
char *Parse( char *data );
const char *getArg( const char *key, const char *defaultValue = NULL );
void setArg( const char *key, const char *value );
int NumArgs( void );
const char *getKey( int index );
const char *getValue( int index );
void operator=( SpawnArgs &a );
ClassDef *getClassDef( qboolean *tikiWasStatic = NULL );
Listener *Spawn( void );
Listener *SpawnInternal( void );
virtual void Archive( Archiver &arc );
};
extern Container< SafePtr< Listener > > g_spawnlist;
ClassDef *FindClass( const char *name, qboolean *isModel );
#ifdef GAME_DLL
void G_InitClientPersistant( gclient_t *client );
#endif
#endif

File diff suppressed because it is too large Load diff

179
code/globalcpp/gamescript.h Normal file
View file

@ -0,0 +1,179 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// gamescript.h: Subclass of script that preprocesses labels
#ifndef __GAMESCRIPT_H__
#define __GAMESCRIPT_H__
#include "class.h"
#include "script.h"
#include "archive.h"
class Listener;
class ScriptThread;
class GameScript;
typedef struct {
byte *codepos; // code position pointer
const_str key; // label name
bool isprivate; // new script engine implementation
} script_label_t;
typedef struct {
unsigned int sourcePos;
int column;
int line;
} sourceinfo_t;
class AbstractScript {
public:
// File variables
const_str m_Filename;
char *m_SourceBuffer;
unsigned int m_SourceLength;
// Developper variable
con_set< uchar *, sourceinfo_t > *m_ProgToSource;
public:
AbstractScript();
str& Filename( void );
const_str ConstFilename( void );
bool GetSourceAt( unsigned int sourcePos, str &sourceLine, int &column, int &line );
void PrintSourcePos( sourceinfo_t *sourcePos, bool dev );
void PrintSourcePos( unsigned int sourcePos, bool dev );
void PrintSourcePos( unsigned char *m_pCodePos, bool dev );
void PrintSourcePos( str sourceLine, int column, int line, bool dev );
};
class StateScript : public Class
{
friend class GameScript;
private:
// Label list
con_set< const_str, script_label_t > label_list;
Container< script_label_t * > reverse_label_list;
public:
// Parent gamescript
GameScript *m_Parent;
public:
StateScript();
virtual void Archive( Archiver& arc );
bool AddLabel( str label, unsigned char *pos, bool private_section = false );
bool AddLabel( const_str label, unsigned char *pos, bool private_section = false );
unsigned char *FindLabel( str label );
unsigned char *FindLabel( const_str label );
const_str NearestLabel( unsigned char *pos );
};
class CatchBlock {
public:
// program variable
StateScript m_StateScript;
// code position variables
unsigned char *m_TryStartCodePos;
unsigned char *m_TryEndCodePos;
};
class GameScript : public AbstractScript {
protected:
// try/throw variable
Container<CatchBlock *> m_CatchBlocks;
public:
// program variables
StateScript m_State;
unsigned char *m_ProgBuffer;
unsigned int m_ProgLength;
// compile variables
bool successCompile;
bool m_bPrecompiled;
// stack variables
unsigned int requiredStackSize;
public:
GameScript();
GameScript( const char *filename );
~GameScript();
virtual void Archive( Archiver& arc );
static void Archive( Archiver& arc, GameScript *&scr );
void ArchiveCodePos( Archiver& arc, unsigned char **codePos );
void Close( void );
void Load( const void *sourceBuffer, int sourceLength );
bool GetCodePos( unsigned char *codePos, str& filename, int& pos );
bool SetCodePos( unsigned char *&codePos, str& filename, int pos );
unsigned int GetRequiredStackSize( void );
qboolean labelExists( const char *name );
StateScript *CreateCatchStateScript( unsigned char *try_begin_code_pos, unsigned char *try_end_code_pos );
StateScript *CreateSwitchStateScript( void );
StateScript *GetCatchStateScript( unsigned char *in, unsigned char *&out );
};
class ScriptThreadLabel {
private:
GameScript *m_Script;
const_str m_Label;
public:
ScriptThreadLabel();
ScriptThread *Create( Listener *listener );
void Execute( Listener *listener = NULL );
void Execute( Listener *listener, Event &ev );
void Execute( Listener *listener, Event *ev );
void Set( const char *label );
void SetScript( const ScriptVariable& label );
void SetScript( const char *label );
void SetThread( const ScriptVariable& label );
bool TrySet( const_str label );
bool TrySet( const char *label );
bool TrySetScript( const_str label );
bool TrySetScript( const char *label );
bool IsSet( void );
void Archive( Archiver& arc );
};
#endif

View file

@ -0,0 +1,82 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#ifndef __GLB_LOCAL_H__
#define __GLB_LOCAL_H__
#if defined( GAME_DLL )
#define glbs gi
#include "g_local.h"
#include "qcommon.h"
#else
#if defined( CGAME_DLL )
#define glbs cgi
#else
#define glbs bi
#endif
#include "../qcommon/q_shared.h"
#include <linklist.h>
#include <mem_blockalloc.h>
#include <vector.h>
#include <str.h>
#include <container.h>
#include <const_str.h>
#include <short3.h>
#include <con_set.h>
#include <con_arrayset.h>
#include <scriptexception.h>
#include <class.h>
#include <containerclass.h>
#include <stack.h>
#include <listener.h>
#include "../qcommon/qcommon.h"
#if defined ( CGAME_DLL )
#if defined ( CGAME_HOOK )
#include "../cgame_hook/cgamex86.h"
#endif
#else
#define glbs bi
#include "baseimp.h"
#endif
#endif
#endif /* glb_local.h */

1938
code/globalcpp/hud.cpp Normal file

File diff suppressed because it is too large Load diff

212
code/globalcpp/hud.h Normal file
View file

@ -0,0 +1,212 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// hud.h: New HUD handler for MoHAA
//
#ifndef __HUD_H__
#define __HUD_H__
#include "listener.h"
#include "container.h"
#define TIMER_ACTIVE (1<<0)
#define TIMER_UP (1<<1)
typedef enum hudAlign_s
{
HUD_LEFT = 0,
HUD_CENTER = 1,
HUD_RIGHT = 2,
HUD_TOP = 0,
HUD_BOTTOM = 2,
HUD_INVALID = 3
} hudAlign_t;
class Hud : public Listener
{
private:
unsigned int number; // auto-assigned number
#ifdef GAME_DLL
char clientnum; // assigned client number
#else
fontHeader_t *font;
qhandle_t shaderHandle;
#endif
hudAlign_t alignX, alignY;
float x, y;
float width, height;
Vector color;
float alpha;
str fontName;
str shader;
str text;
bool virtualSize;
bool isDimensional;
bool fade_alpha;
bool fade_move;
bool fade_scale;
int fade_timer_flags;
bool fade_alpha_first;
int fade_move_x_first;
int fade_move_y_first;
float fade_alpha_current;
float fade_move_current;
float fade_scale_current;
float fade_time_current;
float fade_alpha_time;
float fade_move_time;
float fade_scale_time;
float fade_time;
float fade_out_time;
float fade_alpha_start;
float fade_move_x_start;
float fade_move_y_start;
float fade_scale_w_start;
float fade_scale_h_start;
float fade_time_alpha_start;
float fade_alpha_target;
float fade_move_x_target;
float fade_move_y_target;
float fade_scale_w_target;
float fade_scale_h_target;
float fade_time_target;
Vector org;
Vector lastOrg;
qboolean always_show;
qboolean depth;
int enttarget;
#ifdef GAME_DLL
void SetBroadcast( int clientNumber = -1 ); // Broadcast to someone or everyone
#endif
private:
#ifdef GAME_DLL
void WriteNumber();
#endif
public:
CLASS_PROTOTYPE( Hud );
virtual void Archive( Archiver &arc );
static Hud *Find( int index );
static Hud *FindOrCreate( int index );
static int GetFreeNumber( void );
static void ProcessThink( void );
static int Sort( const void *elem1, const void *elem2 );
#ifdef CGAME_DLL
static void ArchiveFunction( Archiver &arc );
#endif
#ifdef GAME_DLL
Hud( int client = -1 );
#else
Hud( int index = -1 );
#endif
~Hud( void );
#ifdef CGAME_DLL
void Draw3D( void );
#endif
void FadeThink( void );
void MoveThink( void );
void ScaleThink( void );
void TimerThink( void );
void Think( void );
void FadeOverTime( float time );
void MoveOverTime( float time );
void ScaleOverTime( float time, short width, short height );
void Refresh( int clientNumber = -1 );
#ifdef GAME_DLL
int GetClient( void );
#endif
void Set3D( Vector vector_or_offset, qboolean always_show, qboolean depth, int entnum = -1 );
void SetNon3D( void );
void SetAlignX( hudAlign_t align );
void SetAlignY( hudAlign_t align );
void SetAlpha( float alpha );
void SetClient( int clientnum, qboolean clears = false );
void SetColor( Vector color );
void SetFont( const char * font );
void SetRectX( short x );
void SetRectY( short y );
void SetRectHeight( short height );
void SetRectWidth( short height );
void SetShader( const char * shader, float width, float height );
void SetText( const char * text );
void SetTimer( float time, float fade_at_time = -1.0f );
void SetTimerUp( float time, float fade_at_time = -1.0f );
void SetVirtualSize( qboolean virtualSize );
// Events
void EventGetAlignX( Event * ev );
void EventGetAlignY( Event * ev );
void EventGetAlpha( Event * ev );
void EventGetColor( Event * ev );
void EventGetFont( Event * ev );
void EventGetHeight( Event *ev );
void EventGetRectX( Event * ev );
void EventGetRectY( Event * ev );
void EventGetTime( Event *ev );
void EventGetWidth( Event *ev );
void EventFadeDone( Event * ev );
void EventFadeOverTime( Event * ev );
void EventMoveDone( Event * ev );
void EventMoveOverTime( Event * ev );
void EventRefresh( Event * ev );
void EventScaleOverTime( Event * ev );
void EventSet3D( Event *ev );
void EventSetNon3D( Event *ev );
void EventSetAlignX( Event * ev );
void EventSetAlignY( Event * ev );
void EventSetAlpha( Event * ev );
void EventSetColor( Event * ev );
void EventSetFont( Event * ev );
void EventSetPlayer( Event * ev );
void EventSetRectX( Event * ev );
void EventSetRectY( Event * ev );
void EventSetShader( Event * ev );
void EventSetText( Event * ev );
void EventSetTimer( Event *ev );
void EventSetTimerUp( Event *ev );
void EventSetVirtualSize( Event * ev );
};
extern Container< Hud * > hudElements;
#endif /* __HUD_H__ */

4773
code/globalcpp/listener.cpp Normal file

File diff suppressed because it is too large Load diff

700
code/globalcpp/listener.h Normal file
View file

@ -0,0 +1,700 @@
/*
===========================================================================
Copyright (C) 2008 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// listener.h: Listener
#ifndef __LISTENER_H__
#define __LISTENER_H__
#include "glb_local.h"
#include "class.h"
class Entity;
class Listener;
class ScriptClass;
class ScriptThread;
class ScriptVariable;
class ScriptVariableList;
class ScriptVM;
class SimpleEntity;
class Archiver;
class EventQueueNode;
// entity subclass
#define EF_ENTITY (1<<0)
#define EF_ANIMATE (1<<1)
#define EF_SENTIENT (1<<2)
#define EF_PLAYER (1<<3)
#define EF_ACTOR (1<<4)
#define EF_ITEM (1<<5)
#define EF_INVENTORYITEM (1<<6)
#define EF_WEAPON (1<<7)
#define EF_PROJECTILE (1<<8)
#define EF_DOOR (1<<9)
#define EF_CAMERA (1<<10)
#define EF_VEHICLE (1<<11)
#define EF_VEHICLETANK (1<<12)
#define EF_VEHICLETURRET (1<<13)
#define EF_TURRET (1<<14)
#define EF_PATHNODE (1<<15)
#define EF_WAYPOINT (1<<16)
#define EF_TEMPWAYPOINT (1<<17)
#define EF_VEHICLEPOINT (1<<18)
#define EF_SPLINEPATH (1<<19)
#define EF_CRATEOBJECT (1<<20)
#define EF_BOT (1<<21)
// Event flags
#define EV_CONSOLE (1<<0) // Allow entry from console
#define EV_CHEAT (1<<1) // Only allow entry from console if cheats are enabled
#define EV_CODEONLY (1<<2) // Hide from eventlist
#define EV_CACHE (1<<3) // This event is used to cache data in
#define EV_TIKIONLY (1<<4) // This command only applies to TIKI files
#define EV_SCRIPTONLY (1<<5) // This command only applies to SCRIPT files
#define EV_SERVERCMD (1<<6) // Client : server command
#define EV_DEFAULT -1 // default flag
// Event types
#define EV_NORMAL 0 // Normal command
#define EV_RETURN 1 // Return as a function (local.var = local ReturnCommand)
#define EV_GETTER 2 // Return as a variable (local.var = local.listener.some_getter)
#define EV_SETTER 3 // Set as a variable (local.listener.some_setter = "value")
// times for posting events
// Even though negative times technically don't make sense, the effect is to
// sort events that take place at the start of a map so that they are executed
// in the proper order. For example, spawnargs must occur before any script
// commands take place, while unused entities must be removed before the spawnargs
// are parsed.
#define EV_REMOVE -12.0f // remove any unused entities before spawnargs are parsed
#define EV_PRIORITY_SPAWNARG -11.0f // for priority spawn args passed in by the bsp file
#define EV_SPAWNARG -10.0f // for spawn args passed in by the bsp file
#define EV_LINKDOORS -9.0f // for finding out which doors are linked together
#define EV_LINKBEAMS -9.0f // for finding out the endpoints of beams
#define EV_VEHICLE -9.0f
#define EV_SETUP_ROPEPIECE -8.0f
#define EV_SETUP_ROPEBASE -7.0f
#define EV_PROCESS_INIT -6.0f
#define EV_POSTSPAWN -5.0f // for any processing that must occur after all objects are spawned
#define EV_SPAWNENTITIES -4.0f
#define EV_PRIORITY_SPAWNACTOR -3.0f
#define EV_SPAWNACTOR -2.0f
// Posted Event Flags
#define EVENT_LEGS_ANIM (1<<0) // this event is associated with an animation for the legs
#define EVENT_TORSO_ANIM (1<<1) // this event is associated with an animation for the torso
#define EVENT_DIALOG_ANIM (1<<2) // this event is associated with an animation for dialog lip syncing
typedef enum
{
IS_STRING,
IS_VECTOR,
IS_BOOLEAN,
IS_INTEGER,
IS_FLOAT,
IS_ENTITY,
IS_LISTENER
} vartype;
class EventArgDef : public Class
{
private:
int type;
str name;
float minRange[ 3 ];
qboolean minRangeDefault[ 3 ];
float maxRange[ 3 ];
qboolean maxRangeDefault[ 3 ];
qboolean optional;
public:
EventArgDef()
{
type = IS_INTEGER;
//name = "undefined";
optional = false;
};
void Setup( const char * eventName, const char *argName, const char *argType, const char *argRange );
void PrintArgument( FILE *event_file = NULL );
void PrintRange( FILE *event_file = NULL );
int getType( void );
const char *getName( void );
qboolean isOptional( void );
float GetMinRange( int index )
{
if( index < 3 )
return minRange[ index ];
return 0.0;
}
qboolean GetMinRangeDefault( int index )
{
if( index < 3 )
return minRangeDefault[ index ];
return false;
}
float GetMaxRange( int index )
{
if( index < 3 )
return maxRange[ index ];
return 0.0;
}
qboolean GetMaxRangeDefault( int index )
{
if( index < 3 )
return maxRangeDefault[ index ];
return false;
}
};
inline int EventArgDef::getType
(
void
)
{
return type;
}
inline const char *EventArgDef::getName
(
void
)
{
return name.c_str();
}
inline qboolean EventArgDef::isOptional
(
void
)
{
return optional;
}
class EventDef {
public:
str command;
int flags;
const char *formatspec;
const char *argument_names;
const char *documentation;
uchar type;
Container<EventArgDef> *definition;
EventDef() { definition = NULL; }
void Error( const char *format, ... );
void PrintDocumentation( FILE *event_file, bool html );
void PrintEventDocumentation( FILE *event_file, bool html );
void DeleteDocumentation( void );
void SetupDocumentation( void );
};
class command_t {
public:
str command;
int flags;
uchar type;
friend bool operator==( const str &name, const command_t &command );
friend bool operator==( const command_t &cmd1, const command_t &cmd2 );
};
inline bool operator==( const str &name, const command_t &command )
{
return command.command == name;
}
#ifndef NO_SCRIPTENGINE
inline bool operator==( const command_t &cmd1, const command_t &cmd2 )
{
return ( cmd2.command == cmd1.command && ( cmd2.type == ( uchar )-1 || cmd2.type == cmd1.type ) );
}
#else
inline bool operator==( const command_t &cmd1, const command_t &cmd2 )
{
return ( cmd2.command == cmd1.command );
}
#endif
class Event : public Class
{
public:
qboolean fromScript;
short unsigned int eventnum;
short unsigned int dataSize;
ScriptVariable *data;
#ifdef _DEBUG
// should be used only for debugging purposes
str name;
#endif
public:
CLASS_PROTOTYPE( Event );
static con_map< Event *, EventDef > eventDefList;
static con_arrayset< command_t, command_t > commandList;
static con_map< const_str, unsigned int > normalCommandList;
static con_map< const_str, unsigned int > returnCommandList;
static con_map< const_str, unsigned int > getterCommandList;
static con_map< const_str, unsigned int > setterCommandList;
static void LoadEvents( void );
static EventQueueNode EventQueue;
static int totalevents;
static int NumEventCommands();
static void ListCommands( const char *mask = NULL );
static void ListDocumentation( const char *mask, qboolean print_to_file = qfalse );
static void PendingEvents( const char *mask = NULL );
static int GetEvent( str name, uchar type = EV_NORMAL );
static int GetEventWithFlags( str name, int flags, uchar type = EV_NORMAL );
static command_t *GetEventInfo( int eventnum );
static int GetEventFlags( int eventnum );
static str& GetEventName( int index );
static int compareEvents( const void *arg1, const void *arg2 );
static void SortEventList( Container< int > *sortedList );
virtual void ErrorInternal( Listener *l, str text );
static unsigned int FindEventNum( str s );
static unsigned int FindNormalEventNum( const_str s );
static unsigned int FindNormalEventNum( str s );
static unsigned int FindReturnEventNum( const_str s );
static unsigned int FindReturnEventNum( str s );
static unsigned int FindSetterEventNum( const_str s );
static unsigned int FindSetterEventNum( str s );
static unsigned int FindGetterEventNum( const_str s );
static unsigned int FindGetterEventNum( str s );
bool operator==( Event ev ) { return eventnum == ev.eventnum; }
bool operator!=( Event ev ) { return eventnum != ev.eventnum; }
void *operator new( size_t size );
void operator delete( void *ptr );
Event();
Event( const Event *ev );
Event( const Event &ev );
Event( int index );
Event( str command );
Event( str command, uchar type );
Event
(
const char *command,
int flags,
const char *formatspec, // Arguments are : 'e' (Entity) 'v' (Vector) 'i' (Integer) 'f' (Float) 's' (String) 'b' (Boolean).
// Uppercase arguments means optional.
const char *argument_names,
const char *documentation,
uchar type = EV_NORMAL
);
virtual ~Event();
virtual void Archive( Archiver &arc );
#ifdef _GAME_DLL
eventInfo_t *getInfo();
#else
EventDef *getInfo();
#endif
str& getName();
void AddContainer( Container< SafePtr< Listener > > *container );
void AddEntity( Entity * ent );
void AddFloat( float number );
void AddInteger( int number );
void AddListener( Listener * listener );
void AddNil( void );
void AddConstString( const_str string );
void AddString( str string );
void AddToken( str token );
void AddTokens( int argc, const char **argv );
void AddValue( const ScriptVariable &value );
void AddVector( const Vector& vector );
void Clear( void );
void CheckPos( int pos );
bool GetBoolean( int pos );
int GetConstString( int pos );
Entity *GetEntity( int pos );
float GetFloat( int pos );
int GetInteger( int pos );
Listener *GetListener( int pos );
class PathNode *GetPathNode( int pos );
#ifndef NO_SCRIPTENGINE
SimpleEntity *GetSimpleEntity( int pos );
#endif
str GetString( int pos );
str GetToken( int pos );
ScriptVariable& GetValue( int pos );
ScriptVariable& GetValue( void );
Vector GetVector( int pos );
class Waypoint *GetWaypoint( int pos );
qboolean IsEntityAt( int pos );
qboolean IsListenerAt( int pos );
qboolean IsNilAt( int pos );
qboolean IsNumericAt( int pos );
#ifndef NO_SCRIPTENGINE
qboolean IsSimpleEntityAt( int pos );
#endif
qboolean IsStringAt( int pos );
qboolean IsVectorAt( int pos );
qboolean IsFromScript( void );
const char *GetFormat();
int NumArgs();
};
#ifdef GAME_DLL
class ConsoleEvent : public Event
{
private:
gentity_t *m_consoleedict;
public:
CLASS_PROTOTYPE( ConsoleEvent );
void *operator new( size_t size );
void operator delete( void *ptr );
ConsoleEvent();
ConsoleEvent( str name ) : Event( name ) { m_consoleedict = NULL; }
void SetConsoleEdict( gentity_t *edict );
gentity_t *GetConsoleEdict( void );
virtual void ErrorInternal( Listener *l, str text );
};
#endif
typedef struct eventInfo
{
Event *ev;
const char *command;
int flags;
const char *formatspec;
const char *argument_names;
const char *documentation;
int type;
eventInfo *prev;
} eventInfo_t;
#define NODE_CANCEL 1
#define NODE_FIXED_EVENT 2
class EventQueueNode {
public:
Event *event;
int inttime;
int flags;
SafePtr< Listener > m_sourceobject;
EventQueueNode *prev;
EventQueueNode *next;
#ifdef _DEBUG
str name;
#endif
EventQueueNode() { prev = this; next = this; }
Listener *GetSourceObject( void ) { return m_sourceobject; }
void SetSourceObject( Listener *obj ) { m_sourceobject = obj; }
};
template< class Type1, class Type2 >
class con_map;
typedef ContainerClass< SafePtr< Listener > > ConList;
typedef con_map< Event *, EventDef * > eventMap;
typedef SafePtr< Listener > ListenerPtr;
class Listener : public Class
{
public:
#ifndef NO_SCRIPTENGINE
con_set< const_str, ConList > *m_NotifyList;
con_set< const_str, ConList > *m_WaitForList;
con_set< const_str, ConList > *m_EndList;
ScriptVariableList *vars;
#endif
static bool EventSystemStarted;
private:
#ifndef NO_SCRIPTENGINE
void ExecuteScriptInternal( Event *ev, ScriptVariable& scriptVariable );
void ExecuteThreadInternal( Event *ev, ScriptVariable& returnValue );
void WaitExecuteScriptInternal( Event *ev, ScriptVariable& returnValue );
void WaitExecuteThreadInternal( Event *ev, ScriptVariable& returnValue );
#endif
EventQueueNode *PostEventInternal( Event *ev, float delay, int flags );
public:
CLASS_PROTOTYPE( Listener );
#ifndef NO_SCRIPTENGINE
/* Game functions */
virtual ScriptThread *CreateThreadInternal( const ScriptVariable& label );
virtual ScriptThread *CreateScriptInternal( const ScriptVariable& label );
virtual void StoppedNotify( void );
virtual void StartedWaitFor( void );
virtual void StoppedWaitFor( const_str name, bool bDeleting );
#endif
virtual Listener *GetScriptOwner( void );
Listener();
virtual ~Listener();
virtual void Archive( Archiver &arc );
void CancelEventsOfType( Event *ev );
void CancelEventsOfType( Event &ev );
void CancelFlaggedEvents( int flags );
void CancelPendingEvents( void );
qboolean EventPending( Event &ev );
void PostEvent( Event *ev, float delay, int flags = 0 );
void PostEvent( const Event &ev, float delay, int flags = 0 );
qboolean PostponeAllEvents( float time );
qboolean PostponeEvent( Event& ev, float time );
bool ProcessEvent( const Event &ev );
bool ProcessEvent( Event *ev );
bool ProcessEvent( Event &ev );
ScriptVariable& ProcessEventReturn( Event * ev );
void ProcessContainerEvent( const Container< Event * >& conev );
qboolean ProcessPendingEvents( void );
bool ProcessScriptEvent( Event &ev );
bool ProcessScriptEvent( Event *ev );
#ifndef NO_SCRIPTENGINE
void CreateVars( void );
void ClearVars( void );
ScriptVariableList *Vars( void );
bool BroadcastEvent( Event &event, ConList *listeners );
bool BroadcastEvent( str name, Event &event );
bool BroadcastEvent( const_str name, Event &event );
void CancelWaiting( str name );
void CancelWaiting( const_str name );
void CancelWaitingAll( void );
void CancelWaitingSources( const_str name, ConList &listeners, ConList &stoppedListeners );
void ExecuteThread( str scriptName, str label, Event *params = NULL );
void ExecuteThread( str scriptName, str label, Event &params );
void EndOn( str name, Listener *listener );
void EndOn( const_str name, Listener *listener );
void Notify( const char *name );
void Register( str name, Listener *listener );
void Register( const_str name, Listener *listener );
void RegisterSource( const_str name, Listener *listener );
void RegisterTarget( const_str name, Listener *listener );
void Unregister( str name );
void Unregister( const_str name );
void Unregister( str name, Listener *listener );
void Unregister( const_str name, Listener *listener );
void UnregisterAll( void );
bool UnregisterSource( const_str name, Listener *listener );
bool UnregisterTarget( const_str name, Listener *listener );
void UnregisterTargets( const_str name, ConList &listeners, ConList &stoppedListeners, Container< const_str > &stoppedNames );
void AbortRegistration( const_str name, Listener *l );
int RegisterSize( const_str name ) const;
int RegisterSize( str name ) const;
int WaitingSize( const_str name ) const;
int WaitingSize( str name ) const;
bool WaitTillDisabled( str s );
bool WaitTillDisabled( const_str s );
#endif
int GetFlags( Event *event ) const;
qboolean ValidEvent( str name ) const;
//
// Scripting functions
//
void CommandDelay( Event *ev );
void EventDelete( Event *ev );
void EventInheritsFrom( Event *ev );
void EventIsInheritedBy( Event *ev );
void GetClassname( Event *ev );
#ifndef NO_SCRIPTENGINE
void CancelFor( Event *ev );
void CreateReturnThread( Event *ev );
void CreateThread( Event *ev );
void ExecuteReturnScript( Event *ev );
void ExecuteScript( Event *ev );
void EventDelayThrow( Event *ev );
void EventEndOn( Event *ev );
void EventGetOwner( Event *ev );
void EventNotify( Event *ev );
void EventThrow( Event *ev );
void EventUnregister( Event *ev );
void WaitCreateReturnThread( Event *ev );
void WaitCreateThread( Event *ev );
void WaitExecuteReturnScript( Event *ev );
void WaitExecuteScript( Event *ev );
void WaitTill( Event *ev );
void WaitTillTimeout( Event *ev );
void WaitTillAny( Event *ev );
void WaitTillAnyTimeout( Event *ev );
#endif
};
qboolean IsNumeric( const char *str );
extern Event EV_DelayThrow;
extern Event EV_Delete;
extern Event EV_Remove;
extern Event EV_ScriptRemove;
extern Event EV_Throw;
extern Event EV_Listener_CreateThread;
extern Event EV_Listener_CreateReturnThread;
extern Event EV_Listener_ExecuteReturnScript;
extern Event EV_Listener_ExecuteScript;
extern Event EV_Listener_WaitCreateReturnThread;
extern int DisableListenerNotify;
extern cvar_t *g_showevents;
extern cvar_t *g_eventlimit;
extern cvar_t *g_timeevents;
extern cvar_t *g_watch;
extern cvar_t *g_eventstats;
extern MEM_BlockAlloc< Event, MEM_BLOCKSIZE > Event_allocator;
#ifdef GAME_DLL
extern MEM_BlockAlloc< ConsoleEvent, MEM_BLOCKSIZE > ConsoleEvent_allocator;
#endif
#if defined( GAME_DLL )
//
// game dll specific defines
//
#define EVENT_DebugPrintf gi.DebugPrintf
#define EVENT_DPrintf gi.DPrintf
#define EVENT_Printf gi.Printf
#define EVENT_time level.time
#define EVENT_realtime gi.Milliseconds()
#define EVENT_Error gi.Error
#define EVENT_FILENAME "events.txt"
#elif defined ( CGAME_DLL )
//
// cgame dll specific defines
//
#define EVENT_DebugPrintf cgi.DebugPrintf
#define EVENT_DPrintf cgi.Printf
#define EVENT_Printf cgi.Printf
#ifndef CGAME_HOOK
#define EVENT_time ( ( ( float )cg.time / 1000.0f ) )
#else
#define EVENT_time ( ( ( float )cg->time / 1000.0f ) )
#endif
#define EVENT_realtime cgi.Milliseconds()
#define EVENT_Error cgi.Error
#define EVENT_FILENAME "cg_events.txt"
#elif defined ( UI_LIB )
#define EVENT_DebugPrintf Com_DebugPrintf
#define EVENT_DPrintf Com_Printf
#define EVENT_Printf Com_Printf
#define EVENT_time ( ( ( float )cls.realtime / 1000.0f ) )
#define EVENT_realtime Sys_Milliseconds()
#define EVENT_Error Com_Error
#define EVENT_FILENAME "ui_events.txt"
#else
//
// client specific defines
//
#define EVENT_DebugPrintf Com_DebugPrintf
#define EVENT_DPrintf Com_Printf
#define EVENT_Printf Com_Printf
#define EVENT_time ( ( ( float )cls.realtime / 1000.0f ) )
#define EVENT_realtime Sys_Milliseconds()
#define EVENT_Error Com_Error
#define EVENT_FILENAME "cl_events.txt"
#endif
void L_ClearEventList();
bool L_EventSystemStarted( void );
void L_InitEvents( void );
void L_ProcessPendingEvents();
void L_ShutdownEvents( void );
void L_ArchiveEvents( Archiver& arc );
void L_UnarchiveEvents( Archiver& arc );
#include "game.h"
#include "level.h"
#endif /* __LISTENER_H__ */

971
code/globalcpp/lz77.cpp Normal file
View file

@ -0,0 +1,971 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// lz77.cpp: LZ77 Compression Algorithm
// FIXME: MOHAA devs decided to make things on their own, so we need to find out their lz77 compression algorithm...
// we need this to make .pth files work properly
// so we currently use an ugly decompile hack to do so
#include "lz77.h"
#include <stdio.h>
#include <string.h>
unsigned int cLZ77::m_pDictionary[ 65535 ];
cLZ77 g_lz77;
/*************************************************************************
* Constants used for LZ77 coding
*************************************************************************/
/* Maximum offset (can be any size < 2^31). Lower values give faster
compression, while higher values gives better compression. The default
value of 100000 is quite high. Experiment to see what works best for
you. */
#define LZ_MAX_OFFSET 100000
/*************************************************************************
* INTERNAL FUNCTIONS *
*************************************************************************/
/*************************************************************************
* _LZ_StringCompare() - Return maximum length string match.
*************************************************************************/
static unsigned int _LZ_StringCompare( unsigned char * str1,
unsigned char * str2, unsigned int minlen, unsigned int maxlen )
{
unsigned int len;
for( len = minlen; ( len < maxlen ) && ( str1[ len ] == str2[ len ] ); ++len );
return len;
}
/*************************************************************************
* _LZ_WriteVarSize() - Write unsigned integer with variable number of
* bytes depending on value.
*************************************************************************/
static int _LZ_WriteVarSize( unsigned int x, unsigned char * buf )
{
unsigned int y;
int num_bytes, i, b;
/* Determine number of bytes needed to store the number x */
y = x >> 3;
for( num_bytes = 5; num_bytes >= 2; --num_bytes )
{
if( y & 0xfe000000 ) break;
y <<= 7;
}
/* Write all bytes, seven bits in each, with 8:th bit set for all */
/* but the last byte. */
for( i = num_bytes - 1; i >= 0; --i )
{
b = ( x >> ( i * 7 ) ) & 0x0000007f;
if( i > 0 )
{
b |= 0x00000080;
}
*buf++ = ( unsigned char )b;
}
/* Return number of bytes written */
return num_bytes;
}
/*************************************************************************
* _LZ_ReadVarSize() - Read unsigned integer with variable number of
* bytes depending on value.
*************************************************************************/
static int _LZ_ReadVarSize( unsigned int * x, unsigned char * buf )
{
unsigned int y, b, num_bytes;
/* Read complete value (stop when byte contains zero in 8:th bit) */
y = 0;
num_bytes = 0;
do
{
b = ( unsigned int )( *buf++ );
y = ( y << 7 ) | ( b & 0x0000007f );
++num_bytes;
} while( b & 0x00000080 );
/* Store value in x */
*x = y;
/* Return number of bytes read */
return num_bytes;
}
/*************************************************************************
* PUBLIC FUNCTIONS *
*************************************************************************/
cLZ77::cLZ77()
{
}
/*************************************************************************
* cLZ77::CompressData - Compress a block of data using an LZ77 coder.
* in - Input (uncompressed) buffer.
* out - Output (compressed) buffer. This buffer must be 0.4% larger
* than the input buffer, plus one byte.
* insize - Number of input bytes.
* out_len - Output length
* The function returns the size of the compressed data.
*************************************************************************/
unsigned int cLZ77::CompressData( unsigned char *in, size_t in_len, unsigned char *out, size_t *out_len )
{
unsigned char *v5; // eax@1
unsigned char *v6; // ebx@2
unsigned int v7; // eax@3
int v8; // edx@3
unsigned int v9; // ecx@3
cLZ77 *v10; // edi@3
unsigned int v11; // esi@3
unsigned int v12; // eax@4
int v13; // ecx@5
unsigned int v14; // eax@7
cLZ77 *v15; // ecx@7
int v16; // esi@7
int v17; // ecx@8
int v18; // edi@9
int v19; // eax@12
int v20; // edx@13
char v21; // zf@15
char v22; // cf@17
unsigned int v24; // eax@20
unsigned char *v25; // ecx@20
unsigned char *v26; // ebx@20
unsigned char *v27; // ecx@21
unsigned char *v28; // eax@23
unsigned char *v29; // eax@23
unsigned char *v30; // edx@25
unsigned int v31; // eax@26
unsigned char *v32; // ebx@26
unsigned int v33; // eax@27
unsigned char *v34; // edx@27
char v35; // cl@27
cLZ77 *v36; // ebx@27
char v37; // cf@29
unsigned char *v38; // esi@32
char v39; // dl@32
unsigned char *v40; // edi@32
char v41; // dl@32
unsigned char *v42; // edi@32
unsigned int v43; // ecx@32
unsigned char *v44; // esi@33
char v45; // cl@33
unsigned char *v46; // edi@33
char v47; // dl@33
unsigned char *v48; // edi@33
unsigned int v49; // ecx@33
int v50; // esi@39
unsigned int v51; // eax@41
unsigned int v52; // edx@41
unsigned int v53; // eax@45
unsigned char *v54; // edi@45
unsigned char *v55; // edx@46
unsigned char *v56; // edx@47
cLZ77 *v57; // ecx@47
int v58; // ecx@49
unsigned int v59; // eax@51
unsigned char *v60; // ebx@51
unsigned char *v61; // edi@52
unsigned char *v62; // edx@54
unsigned char *v63; // edi@54
cLZ77 *v64; // edi@58
int v65; // edx@60
unsigned char *v66; // [sp+0h] [bp-10h]@39
this->op = out;
v5 = in + 4;
this->in_end = &in[ in_len ];
this->ip_end = &in[ in_len - 13 ];
this->ii = in;
this->ip = in + 4;
do
{
v6 = v5;
while( 1 )
{
v8 = v6 - in;
v10 = this;
v11 = 33 * ( *v6 ^ 32 * ( v6[ 1 ] ^ 32 * ( v6[ 2 ] ^ ( ( unsigned int )v6[ 3 ] << 6 ) ) ) ) >> 5;
v9 = ( 33 * ( *v6 ^ 32 * ( v6[ 1 ] ^ 32 * ( v6[ 2 ] ^ ( ( unsigned int )v6[ 3 ] << 6 ) ) ) ) >> 5 ) & 0x3FFF;
this->dindex = v9;
v7 = m_pDictionary[ v9 ];
this->m_off = v7;
if( v6 - in <= v7 || ( v12 = v8 - v7, v10 = this, this->m_off = v12, v12 > 0xBFFF ) )
{
m_pDictionary[ v9 ] = v8;
goto LABEL_64;
}
v13 = ( int )&v6[ -v12 ];
this->m_pos = &v6[ -v12 ];
if( v12 <= 0x800 || *( unsigned char * )( v13 + 3 ) == v6[ 3 ] )
{
if( *( unsigned char * )v13 != *v6 || *( unsigned char * )( v13 + 1 ) != v6[ 1 ] || *( unsigned char * )( v13 + 2 ) != v6[ 2 ] )
{
LABEL_17:
m_pDictionary[ dindex ] = v6 - in;
v5 = this->ip + 1;
v22 = v5 < this->ip_end;
this->ip = v5;
goto LABEL_18;
}
goto LABEL_20;
}
v15 = this;
v16 = v11 & 0x7FF ^ 0x201F;
this->dindex = v16;
v14 = m_pDictionary[ v16 ];
this->m_off = v14;
if( v8 <= v14 )
break;
v10 = this;
v17 = v8 - v14;
this->m_off = v8 - v14;
if( v8 - v14 > 0xBFFF )
goto LABEL_63;
v18 = ( int )&v6[ -v17 ];
this->m_pos = &v6[ -v17 ];
if( ( unsigned int )v17 <= 0x800 || *( unsigned char * )( v18 + 3 ) == v6[ 3 ] )
{
if( *( unsigned char * )v18 != *v6 || *( unsigned char * )( v18 + 1 ) != v6[ 1 ] )
goto LABEL_17;
v21 = *( unsigned char * )( v18 + 2 ) == v6[ 2 ];
}
else
{
if( v8 <= ( unsigned int )v17 )
{
m_pDictionary[ v16 ] = v8;
v15 = this;
goto LABEL_66;
}
v10 = this;
v19 = v8 - v17;
this->m_off = v8 - v17;
if( ( unsigned int )( v8 - v17 ) > 0xBFFF )
{
LABEL_63:
m_pDictionary[ v16 ] = v8;
LABEL_64:
v5 = v10->ip + 1;
v22 = v5 < v10->ip_end;
v10->ip = v5;
goto LABEL_18;
}
v20 = ( int )&v6[ -v19 ];
this->m_pos = &v6[ -v19 ];
if( v6[ -v19 ] != *v6 || *( unsigned char * )( v20 + 1 ) != v6[ 1 ] )
goto LABEL_17;
v21 = *( unsigned char * )( v20 + 2 ) == v6[ 2 ];
}
if( !v21 )
goto LABEL_17;
LABEL_20:
m_pDictionary[ this->dindex ] = v6 - in;
v26 = this->ip;
v25 = this->ii;
v24 = ( unsigned int )&this->ip[ -( unsigned int )v25 ];
if( ( signed int )&this->ip[ -( unsigned int )v25 ] > 0 )
{
v27 = &this->ip[ -( unsigned int )v25 ];
if( v24 > 3 )
{
if( v24 > 0x12 )
{
v65 = v24 - 18;
*this->op++ = 0;
if( v24 - 18 > 0xFF )
{
do
{
v65 -= 255;
*this->op++ = 0;
} while( ( unsigned int )v65 > 0xFF );
}
v64 = this;
*this->op = v65;
}
else
{
v64 = this;
*this->op = v24 - 3;
}
++v64->op;
}
else
{
*( this->op - 2 ) |= v24;
}
do
{
*this->op = *this->ii;
v29 = this->ii;
++this->op;
v28 = v29 + 1;
--v27;
this->ii = v28;
} while( v27 );
v26 = this->ip;
v25 = v28;
}
v30 = this->m_pos;
this->ip = v26 + 4;
if( v30[ 3 ] == v26[ 3 ] )
{
this->ip = v26 + 5;
if( v30[ 4 ] == v26[ 4 ] )
{
this->ip = v26 + 6;
if( v30[ 5 ] == v26[ 5 ] )
{
this->ip = v26 + 7;
if( v30[ 6 ] == v26[ 6 ] )
{
this->ip = v26 + 8;
if( v30[ 7 ] == v26[ 7 ] )
{
this->ip = v26 + 9;
if( v30[ 8 ] == v26[ 8 ] )
{
v50 = ( int )( v30 + 9 );
v66 = this->in_end;
if( v26 + 9 < v66 )
{
if( v26[ 9 ] == v30[ 9 ] )
{
do
{
++v50;
v62 = this->ip;
v63 = this->ip + 1;
this->ip = v63;
} while( v63 < v66 && v62[ 1 ] == *( unsigned char * )v50 );
}
}
v51 = this->m_off;
v52 = ( unsigned int )&this->ip[ -( unsigned int )v25 ];
this->m_len = v52;
if( v51 > 0x4000 )
{
v58 = v51 - 16384;
this->m_off = v51 - 16384;
if( v52 <= 9 )
{
*this->op++ = ( ( v58 & 0x4000u ) >> 11 ) | ( unsigned char )( *( unsigned char * )&( this->m_len ) - 2 ) | 0x10;
goto LABEL_44;
}
v60 = this->op;
this->m_len = v52 - 9;
*v60 = ( ( v58 & 0x4000u ) >> 11 ) | 0x10;
v59 = this->m_len;
++this->op;
for( ; v59 > 0xFF; ++this->op )
{
v61 = this->op;
this->m_len = v59 - 255;
*v61 = 0;
v59 = this->m_len;
}
v56 = this->op;
v57 = this;
}
else
{
this->m_off = v51 - 1;
if( v52 <= 0x21 )
{
*this->op++ = ( *( unsigned char * )&( this->m_len ) - 2 ) | 0x20;
LABEL_44:
v36 = this;
*this->op = 4 * ( this->m_off & 0x3F );
v34 = this->op;
v33 = this->m_off >> 6;
this->op = v34 + 1;
goto LABEL_28;
}
v54 = this->op;
this->m_len = v52 - 33;
*v54 = 32;
v53 = this->m_len;
++this->op;
for( ; v53 > 0xFF; ++this->op )
{
v55 = this->op;
this->m_len = v53 - 255;
*v55 = 0;
v53 = this->m_len;
}
v57 = this;
v56 = this->op;
}
*v56 = *( unsigned char * )&( v57->m_len );
++v57->op;
goto LABEL_44;
}
}
}
}
}
}
v31 = this->m_off;
v32 = this->ip - 1;
this->ip = v32;
this->m_len = v32 - v25;
if( v31 > 0x800 )
{
if( v31 > 0x4000 )
{
v44 = this->op;
v45 = *( unsigned char * )&( this->m_len );
this->m_off = v31 - 16384;
*v44 = ( ( ( v31 - 16384 ) & 0x4000 ) >> 11 ) | ( unsigned char )( v45 - 2 ) | 0x10;
v46 = this->op;
v47 = *( unsigned char * )&( this->m_off );
this->op = v46 + 1;
v46[ 1 ] = 4 * ( v47 & 0x3F );
v48 = this->op;
v49 = this->m_off >> 6;
this->op = v48 + 1;
v48[ 1 ] = v49;
++this->op;
}
else
{
v38 = this->op;
v39 = *( unsigned char * )&( this->m_len );
this->m_off = v31 - 1;
*v38 = ( v39 - 2 ) | 0x20;
v40 = this->op;
v41 = *( unsigned char * )&( this->m_off );
this->op = v40 + 1;
v40[ 1 ] = 4 * ( v41 & 0x3F );
v42 = this->op;
v43 = this->m_off >> 6;
this->op = v42 + 1;
v42[ 1 ] = v43;
++this->op;
}
goto LABEL_29;
}
v35 = *( unsigned char * )&( this->m_len );
v36 = this;
this->m_off = v31 - 1;
*this->op = 4 * ( this->m_off & 7 ) | 32 * ( v35 - 1 );
v34 = this->op;
v33 = this->m_off >> 3;
this->op = v34 + 1;
LABEL_28:
v34[ 1 ] = v33;
++v36->op;
LABEL_29:
v37 = this->ip < this->ip_end;
v6 = this->ip;
this->ii = this->ip;
if( !v37 )
goto LABEL_19;
}
m_pDictionary[ v16 ] = v8;
LABEL_66:
v5 = v15->ip + 1;
v22 = v5 < v15->ip_end;
v15->ip = v5;
LABEL_18:
;
} while( v22 );
LABEL_19:
*out_len = ( unsigned int )&this->op[ -( unsigned int )out ];
return this->in_end - this->ii;
}
/*************************************************************************
* cLZ77::Compress - Compress a block of data using an LZ77 coder.
* in - Input (uncompressed) buffer.
* out - Output (compressed) buffer. This buffer must be 0.4% larger
* than the input buffer, plus one byte.
* insize - Number of input bytes.
* out_len - Output length
* The function returns the size of the compressed data.
*************************************************************************/
int cLZ77::Compress( unsigned char *in, size_t in_len, unsigned char *out, size_t *out_len )
{
unsigned char *v5; // edx@1
unsigned int v6; // ecx@1
unsigned char *v7; // ebx@3
unsigned char v8; // al@6
int result; // eax@7
int v10; // edx@7
int v11; // eax@9
v5 = out;
v6 = in_len;
if( in_len > 0xD )
{
v6 = CompressData( in, in_len, out, out_len );
v5 = &out[ *out_len ];
}
if( v6 )
{
v7 = &in[ in_len ] - v6;
if( v5 != out || v6 > 0xEE )
{
if( v6 <= 3 )
{
*( v5 - 2 ) |= v6;
goto LABEL_6;
}
if( v6 > 0x12 )
{
*v5 = 0;
v11 = v6 - 18;
++v5;
if( v6 - 18 > 0xFF )
{
do
{
*v5 = 0;
v11 -= 255;
++v5;
} while( ( unsigned int )v11 > 0xFF );
}
}
else
{
*( unsigned char * )&v11 = v6 - 3;
}
}
else
{
*( unsigned char * )&v11 = v6 + 17;
}
*v5++ = v11;
do
{
LABEL_6:
v8 = *v7++;
*v5++ = v8;
--v6;
} while( v6 );
}
*v5 = 17;
v10 = ( int )( v5 + 1 );
result = 0;
*( unsigned char * )v10++ = 0;
*( unsigned char * )v10 = 0;
*out_len = v10 + 1 - ( unsigned int )out;
return result;
}
/*************************************************************************
* cLZ77::Decompress - Uncompress a block of data using an LZ77 decoder.
* in - Input (compressed) buffer.
* out - Output (uncompressed) buffer. This buffer must be large
* enough to hold the uncompressed data.
* insize - Number of input bytes.
* out_len - Output length
*************************************************************************/
int cLZ77::Decompress( unsigned char *in, size_t in_len, unsigned char *out, size_t *out_len )
{
unsigned char v5; // al@1
int v6; // esi@2
int v7; // ebx@4
unsigned int v8; // esi@4
unsigned char *v9; // ecx@5
int v10; // edx@5
int v11; // edx@5
unsigned char *v12; // edx@5
unsigned char *v13; // esi@5
unsigned char *v14; // esi@6
unsigned char *v15; // ebx@6
int v16; // ecx@7
unsigned char v17; // dl@7
int v18; // eax@8
unsigned char *v19; // ebx@12
int v20; // esi@12
unsigned int v21; // esi@12
int v22; // ecx@12
int v23; // edx@12
int v24; // eax@12
int v25; // ecx@12
unsigned char *v26; // ecx@12
unsigned char *v27; // ebx@12
int v28; // esi@16
int v29; // ecx@17
int v30; // ebx@17
int v31; // edx@18
int v32; // ecx@18
int v33; // ebx@20
int v34; // ecx@21
int v35; // ebx@21
unsigned int v36; // edx@21
unsigned char *v37; // edx@23
int v38; // esi@24
unsigned char *v39; // ecx@29
unsigned char *v40; // ebx@29
int v41; // ebx@34
int v42; // ecx@35
int v43; // ebx@35
int v44; // edx@36
int v45; // ecx@36
int v46; // edx@38
int v47; // ecx@39
unsigned char *v48; // ecx@39
unsigned int v49; // edx@39
unsigned int v50; // eax@41
int result; // eax@42
unsigned char *v52; // ebx@45
int v53; // edx@45
int v54; // esi@45
int v55; // ecx@45
int v56; // edx@45
int v57; // ebx@49
int v58; // eax@50
int v59; // esi@51
unsigned char *v60; // [sp+0h] [bp-14h]@21
ip_end = &in[ in_len ];
*( unsigned int * )out_len = 0;
ip = in;
op = ( unsigned char * )out;
v5 = *in;
if( *in <= 17u )
{
v16 = ( int )ip;
goto LABEL_46;
}
v6 = v5 - 17;
ip = in + 1;
if( ( unsigned int )v5 - 17 <= 3 )
{
v16 = ( int )( in + 1 );
goto LABEL_8;
}
do
{
*op++ = *ip++;
--v6;
} while( v6 );
LABEL_4:
v7 = ( int )ip;
v8 = *ip++;
if( v8 <= 0xF )
{
v9 = op;
v10 = ( int )&v9[ -( v8 >> 2 ) - 2049 ];
m_pos = ( unsigned char * )v10;
v11 = v10 - 4 * *( unsigned char * )( v7 + 1 );
m_pos = ( unsigned char * )v11;
ip = ( unsigned char * )( v7 + 2 );
*v9 = *( unsigned char * )v11;
v12 = m_pos;
m_pos = v12 + 1;
v13 = op;
op = v13 + 1;
v13[ 1 ] = v12[ 1 ];
LABEL_6:
v14 = m_pos;
m_pos = v14 + 1;
v15 = op;
op = v15 + 1;
v15[ 1 ] = v14[ 1 ];
++op;
goto LABEL_7;
}
while( 1 )
{
if( v8 > 0x3F )
{
v19 = op;
v21 = v8 >> 2;
v22 = ( int )&v19[ -( v21 & 7 ) - 1 ];
v23 = ( int )ip;
m_pos = ( unsigned char * )v22;
v24 = *( unsigned char * )v23;
ip = ( unsigned char * )( v23 + 1 );
v20 = ( v21 >> 3 ) - 1;
v25 = v22 - 8 * v24;
m_pos = ( unsigned char * )v25;
*v19 = *( unsigned char * )v25;
v26 = m_pos;
m_pos = v26 + 1;
v27 = op;
op = v27 + 1;
v27[ 1 ] = v26[ 1 ];
++m_pos;
++op;
do
{
*op++ = *m_pos++;
--v20;
} while( v20 );
goto LABEL_7;
}
if( v8 > 0x1F )
{
v28 = v8 & 0x1F;
if( !v28 )
{
v29 = ( int )ip;
v30 = ( int )ip;
if( !*ip )
{
do
{
v31 = v30 + 1;
v32 = v30;
v28 += 255;
ip = ( unsigned char * )( v30++ + 1 );
} while( !*( unsigned char * )( v32 + 1 ) );
v29 = v31;
}
v33 = *( unsigned char * )v29;
ip = ( unsigned char * )( v29 + 1 );
v28 += v33 + 31;
}
v34 = ( int )( op - 1 );
v60 = op;
v35 = ( int )ip;
m_pos = ( unsigned char * )v34;
v36 = *( unsigned short * )v35;
ip = ( unsigned char * )( v35 + 2 );
m_pos = ( unsigned char * )( v34 - ( v36 >> 2 ) );
goto LABEL_22;
}
if( v8 <= 0xF )
{
v52 = op;
v53 = ( int )&v52[ -( v8 >> 2 ) - 1 ];
v54 = ( int )ip;
m_pos = ( unsigned char * )v53;
v55 = *( unsigned char * )v54;
ip = ( unsigned char * )( v54 + 1 );
v56 = v53 - 4 * v55;
m_pos = ( unsigned char * )v56;
*v52 = *( unsigned char * )v56;
goto LABEL_6;
}
v60 = op;
v41 = ( int )&v60[ -2048 * ( v8 & 8 ) ];
v28 = v8 & 7;
m_pos = ( unsigned char * )v41;
if( !v28 )
{
v42 = ( int )ip;
v43 = ( int )ip;
if( !*ip )
{
do
{
v44 = v43 + 1;
v45 = v43;
v28 += 255;
ip = ( unsigned char * )( v43++ + 1 );
} while( !*( unsigned char * )( v45 + 1 ) );
v42 = v44;
}
v46 = *( unsigned char * )v42;
ip = ( unsigned char * )( v42 + 1 );
v28 += v46 + 7;
}
v48 = m_pos;
v49 = *( unsigned short * )ip;
ip += 2;
v47 = ( int )&v48[ -( v49 >> 2 ) ];
m_pos = ( unsigned char * )v47;
if( ( unsigned char * )v47 == v60 )
break;
m_pos = ( unsigned char * )( v47 - 16384 );
LABEL_22:
if( ( unsigned int )v28 <= 5 )
{
v37 = m_pos;
LABEL_29:
*v60 = *v37;
v39 = m_pos;
m_pos = v39 + 1;
v40 = op;
op = v40 + 1;
v40[ 1 ] = v39[ 1 ];
++m_pos;
++op;
do
{
*op++ = *m_pos++;
--v28;
} while( v28 );
goto LABEL_7;
}
v37 = m_pos;
if( ( signed int )( v60 - v37 ) <= 3 )
goto LABEL_29;
v38 = v28 - 2;
*( unsigned int * )v60 = *( unsigned int * )v37;
op += 4;
m_pos += 4;
do
{
v38 -= 4;
*( unsigned int * )op = *( unsigned int * )m_pos;
op += 4;
m_pos += 4;
} while( ( unsigned int )v38 > 3 );
for( ; v38; --v38 )
*op++ = *m_pos++;
LABEL_7:
v16 = ( int )ip;
v17 = *( ip - 2 ) & 3;
v6 = v17;
if( v17 )
{
LABEL_8:
while( 1 )
{
*op = *( unsigned char * )v16;
v18 = ( int )ip;
++op;
--v6;
ip = ( unsigned char * )( v18 + 1 );
if( !v6 )
break;
v16 = v18 + 1;
}
v8 = *( unsigned char * )( v18 + 1 );
ip = ( unsigned char * )( v18 + 2 );
}
else
{
LABEL_46:
v8 = *( unsigned char * )v16;
ip = ( unsigned char * )( v16 + 1 );
if( v8 <= 0xF )
{
if( !v8 )
{
if( !*( unsigned char * )( v16 + 1 ) )
{
do
{
v57 = ( int )ip;
v8 += 255;
++ip;
} while( !*( unsigned char * )( v57 + 1 ) );
}
v58 = *ip++;
v8 += v58 + 15;
}
*( unsigned int * )op = *( unsigned int * )ip;
op += 4;
ip += 4;
v59 = v8 - 1;
if( v59 )
{
if( ( unsigned int )v59 <= 3 )
{
do
{
*op++ = *ip++;
--v59;
} while( v59 );
}
else
{
do
{
v59 -= 4;
*( unsigned int * )op = *( unsigned int * )ip;
op += 4;
ip += 4;
} while( ( unsigned int )v59 > 3 );
for( ; v59; --v59 )
*op++ = *ip++;
}
}
goto LABEL_4;
}
}
}
*out_len = v47 - ( unsigned int )out;
v50 = ( unsigned int )ip_end;
if( ip == ( unsigned char * )v50 )
result = 0;
else
result = -( ip < ( unsigned char * )v50 ) | 0xFFFFFFFE;
return result;
}
static unsigned char in[ 0x40000 ];
static unsigned char out[ 0x41013 ];
void test_compression()
{
size_t in_len;
size_t out_len;
size_t new_len;
cLZ77 lz77;
memset( &in, 0, 0x40000 );
if( lz77.Compress( in, sizeof( in ), out, &out_len ) )
{
puts( "Compression Failed!" );
return;
}
printf( "Compressed %i bytes into %i bytes\n", 0x40000, out_len );
if( lz77.Decompress( out, out_len, in, &in_len ) )
{
new_len = in_len;
}
else
{
new_len = in_len;
if( in_len == 0x40000 )
{
printf( "Decompressed %i bytes into %i bytes\n", out_len, 0x40000 );
puts( "Compression Test: Passed" );
return;
}
}
printf( "Decompression got FuBar'd... %i != %i\n", 0x40000, new_len );
}

53
code/globalcpp/lz77.h Normal file
View file

@ -0,0 +1,53 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// lz77.h: LZ77 Compression Algorithm
#ifndef __LZ77_H__
#define __LZ77_H__
class cLZ77 {
static unsigned int m_pDictionary[];
unsigned char *ip;
unsigned char *op;
unsigned char *in_end;
unsigned char *ip_end;
unsigned char *ii;
unsigned char *m_pos;
unsigned int m_off;
unsigned int m_len;
unsigned int dindex;
public:
cLZ77();
int Compress( unsigned char *in, size_t in_len, unsigned char *out, size_t *out_len );
int Decompress( unsigned char *in, size_t in_len, unsigned char *out, size_t *out_len );
private:
unsigned int CompressData( unsigned char *in, size_t in_len, unsigned char *out, size_t *out_len );
};
extern cLZ77 g_lz77;
#endif /* __LZ77_H__ */

381
code/globalcpp/md5.cpp Normal file
View file

@ -0,0 +1,381 @@
/*
Copyright (C) 1999, 2000, 2002 Aladdin Enterprises. All rights reserved.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
L. Peter Deutsch
ghost@aladdin.com
*/
/* $Id: md5.c,v 1.6 2002/04/13 19:20:28 lpd Exp $ */
/*
Independent implementation of MD5 (RFC 1321).
This code implements the MD5 Algorithm defined in RFC 1321, whose
text is available at
http://www.ietf.org/rfc/rfc1321.txt
The code is derived from the text of the RFC, including the test suite
(section A.5) but excluding the rest of Appendix A. It does not include
any code or documentation that is identified in the RFC as being
copyrighted.
The original and principal author of md5.c is L. Peter Deutsch
<ghost@aladdin.com>. Other authors are noted in the change history
that follows (in reverse chronological order):
2002-04-13 lpd Clarified derivation from RFC 1321; now handles byte order
either statically or dynamically; added missing #include <string.h>
in library.
2002-03-11 lpd Corrected argument list for main(), and added int return
type, in test program and T value program.
2002-02-21 lpd Added missing #include <stdio.h> in test program.
2000-07-03 lpd Patched to eliminate warnings about "constant is
unsigned in ANSI C, signed in traditional"; made test program
self-checking.
1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5).
1999-05-03 lpd Original version.
*/
#include "md5.h"
#include <string.h>
#undef BYTE_ORDER /* 1 = big-endian, -1 = little-endian, 0 = unknown */
#ifdef ARCH_IS_BIG_ENDIAN
# define BYTE_ORDER (ARCH_IS_BIG_ENDIAN ? 1 : -1)
#else
# define BYTE_ORDER 0
#endif
#define T_MASK ((md5_word_t)~0)
#define T1 /* 0xd76aa478 */ (T_MASK ^ 0x28955b87)
#define T2 /* 0xe8c7b756 */ (T_MASK ^ 0x173848a9)
#define T3 0x242070db
#define T4 /* 0xc1bdceee */ (T_MASK ^ 0x3e423111)
#define T5 /* 0xf57c0faf */ (T_MASK ^ 0x0a83f050)
#define T6 0x4787c62a
#define T7 /* 0xa8304613 */ (T_MASK ^ 0x57cfb9ec)
#define T8 /* 0xfd469501 */ (T_MASK ^ 0x02b96afe)
#define T9 0x698098d8
#define T10 /* 0x8b44f7af */ (T_MASK ^ 0x74bb0850)
#define T11 /* 0xffff5bb1 */ (T_MASK ^ 0x0000a44e)
#define T12 /* 0x895cd7be */ (T_MASK ^ 0x76a32841)
#define T13 0x6b901122
#define T14 /* 0xfd987193 */ (T_MASK ^ 0x02678e6c)
#define T15 /* 0xa679438e */ (T_MASK ^ 0x5986bc71)
#define T16 0x49b40821
#define T17 /* 0xf61e2562 */ (T_MASK ^ 0x09e1da9d)
#define T18 /* 0xc040b340 */ (T_MASK ^ 0x3fbf4cbf)
#define T19 0x265e5a51
#define T20 /* 0xe9b6c7aa */ (T_MASK ^ 0x16493855)
#define T21 /* 0xd62f105d */ (T_MASK ^ 0x29d0efa2)
#define T22 0x02441453
#define T23 /* 0xd8a1e681 */ (T_MASK ^ 0x275e197e)
#define T24 /* 0xe7d3fbc8 */ (T_MASK ^ 0x182c0437)
#define T25 0x21e1cde6
#define T26 /* 0xc33707d6 */ (T_MASK ^ 0x3cc8f829)
#define T27 /* 0xf4d50d87 */ (T_MASK ^ 0x0b2af278)
#define T28 0x455a14ed
#define T29 /* 0xa9e3e905 */ (T_MASK ^ 0x561c16fa)
#define T30 /* 0xfcefa3f8 */ (T_MASK ^ 0x03105c07)
#define T31 0x676f02d9
#define T32 /* 0x8d2a4c8a */ (T_MASK ^ 0x72d5b375)
#define T33 /* 0xfffa3942 */ (T_MASK ^ 0x0005c6bd)
#define T34 /* 0x8771f681 */ (T_MASK ^ 0x788e097e)
#define T35 0x6d9d6122
#define T36 /* 0xfde5380c */ (T_MASK ^ 0x021ac7f3)
#define T37 /* 0xa4beea44 */ (T_MASK ^ 0x5b4115bb)
#define T38 0x4bdecfa9
#define T39 /* 0xf6bb4b60 */ (T_MASK ^ 0x0944b49f)
#define T40 /* 0xbebfbc70 */ (T_MASK ^ 0x4140438f)
#define T41 0x289b7ec6
#define T42 /* 0xeaa127fa */ (T_MASK ^ 0x155ed805)
#define T43 /* 0xd4ef3085 */ (T_MASK ^ 0x2b10cf7a)
#define T44 0x04881d05
#define T45 /* 0xd9d4d039 */ (T_MASK ^ 0x262b2fc6)
#define T46 /* 0xe6db99e5 */ (T_MASK ^ 0x1924661a)
#define T47 0x1fa27cf8
#define T48 /* 0xc4ac5665 */ (T_MASK ^ 0x3b53a99a)
#define T49 /* 0xf4292244 */ (T_MASK ^ 0x0bd6ddbb)
#define T50 0x432aff97
#define T51 /* 0xab9423a7 */ (T_MASK ^ 0x546bdc58)
#define T52 /* 0xfc93a039 */ (T_MASK ^ 0x036c5fc6)
#define T53 0x655b59c3
#define T54 /* 0x8f0ccc92 */ (T_MASK ^ 0x70f3336d)
#define T55 /* 0xffeff47d */ (T_MASK ^ 0x00100b82)
#define T56 /* 0x85845dd1 */ (T_MASK ^ 0x7a7ba22e)
#define T57 0x6fa87e4f
#define T58 /* 0xfe2ce6e0 */ (T_MASK ^ 0x01d3191f)
#define T59 /* 0xa3014314 */ (T_MASK ^ 0x5cfebceb)
#define T60 0x4e0811a1
#define T61 /* 0xf7537e82 */ (T_MASK ^ 0x08ac817d)
#define T62 /* 0xbd3af235 */ (T_MASK ^ 0x42c50dca)
#define T63 0x2ad7d2bb
#define T64 /* 0xeb86d391 */ (T_MASK ^ 0x14792c6e)
static void
md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/)
{
md5_word_t
a = pms->abcd[0], b = pms->abcd[1],
c = pms->abcd[2], d = pms->abcd[3];
md5_word_t t;
#if BYTE_ORDER > 0
/* Define storage only for big-endian CPUs. */
md5_word_t X[16];
#else
/* Define storage for little-endian or both types of CPUs. */
md5_word_t xbuf[16];
const md5_word_t *X;
#endif
{
#if BYTE_ORDER == 0
/*
* Determine dynamically whether this is a big-endian or
* little-endian machine, since we can use a more efficient
* algorithm on the latter.
*/
static const int w = 1;
if (*((const md5_byte_t *)&w)) /* dynamic little-endian */
#endif
#if BYTE_ORDER <= 0 /* little-endian */
{
/*
* On little-endian machines, we can process properly aligned
* data without copying it.
*/
if (!((data - (const md5_byte_t *)0) & 3)) {
/* data are properly aligned */
X = (const md5_word_t *)data;
} else {
/* not aligned */
memcpy(xbuf, data, 64);
X = xbuf;
}
}
#endif
#if BYTE_ORDER == 0
else /* dynamic big-endian */
#endif
#if BYTE_ORDER >= 0 /* big-endian */
{
/*
* On big-endian machines, we must arrange the bytes in the
* right order.
*/
const md5_byte_t *xp = data;
int i;
# if BYTE_ORDER == 0
X = xbuf; /* (dynamic only) */
# else
# define xbuf X /* (static only) */
# endif
for (i = 0; i < 16; ++i, xp += 4)
xbuf[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24);
}
#endif
}
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
/* Round 1. */
/* Let [abcd k s i] denote the operation
a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */
#define F(x, y, z) (((x) & (y)) | (~(x) & (z)))
#define SET(a, b, c, d, k, s, Ti)\
t = a + F(b,c,d) + X[k] + Ti;\
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 0, 7, T1);
SET(d, a, b, c, 1, 12, T2);
SET(c, d, a, b, 2, 17, T3);
SET(b, c, d, a, 3, 22, T4);
SET(a, b, c, d, 4, 7, T5);
SET(d, a, b, c, 5, 12, T6);
SET(c, d, a, b, 6, 17, T7);
SET(b, c, d, a, 7, 22, T8);
SET(a, b, c, d, 8, 7, T9);
SET(d, a, b, c, 9, 12, T10);
SET(c, d, a, b, 10, 17, T11);
SET(b, c, d, a, 11, 22, T12);
SET(a, b, c, d, 12, 7, T13);
SET(d, a, b, c, 13, 12, T14);
SET(c, d, a, b, 14, 17, T15);
SET(b, c, d, a, 15, 22, T16);
#undef SET
/* Round 2. */
/* Let [abcd k s i] denote the operation
a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */
#define G(x, y, z) (((x) & (z)) | ((y) & ~(z)))
#define SET(a, b, c, d, k, s, Ti)\
t = a + G(b,c,d) + X[k] + Ti;\
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 1, 5, T17);
SET(d, a, b, c, 6, 9, T18);
SET(c, d, a, b, 11, 14, T19);
SET(b, c, d, a, 0, 20, T20);
SET(a, b, c, d, 5, 5, T21);
SET(d, a, b, c, 10, 9, T22);
SET(c, d, a, b, 15, 14, T23);
SET(b, c, d, a, 4, 20, T24);
SET(a, b, c, d, 9, 5, T25);
SET(d, a, b, c, 14, 9, T26);
SET(c, d, a, b, 3, 14, T27);
SET(b, c, d, a, 8, 20, T28);
SET(a, b, c, d, 13, 5, T29);
SET(d, a, b, c, 2, 9, T30);
SET(c, d, a, b, 7, 14, T31);
SET(b, c, d, a, 12, 20, T32);
#undef SET
/* Round 3. */
/* Let [abcd k s t] denote the operation
a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */
#define H(x, y, z) ((x) ^ (y) ^ (z))
#define SET(a, b, c, d, k, s, Ti)\
t = a + H(b,c,d) + X[k] + Ti;\
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 5, 4, T33);
SET(d, a, b, c, 8, 11, T34);
SET(c, d, a, b, 11, 16, T35);
SET(b, c, d, a, 14, 23, T36);
SET(a, b, c, d, 1, 4, T37);
SET(d, a, b, c, 4, 11, T38);
SET(c, d, a, b, 7, 16, T39);
SET(b, c, d, a, 10, 23, T40);
SET(a, b, c, d, 13, 4, T41);
SET(d, a, b, c, 0, 11, T42);
SET(c, d, a, b, 3, 16, T43);
SET(b, c, d, a, 6, 23, T44);
SET(a, b, c, d, 9, 4, T45);
SET(d, a, b, c, 12, 11, T46);
SET(c, d, a, b, 15, 16, T47);
SET(b, c, d, a, 2, 23, T48);
#undef SET
/* Round 4. */
/* Let [abcd k s t] denote the operation
a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */
#define I(x, y, z) ((y) ^ ((x) | ~(z)))
#define SET(a, b, c, d, k, s, Ti)\
t = a + I(b,c,d) + X[k] + Ti;\
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 0, 6, T49);
SET(d, a, b, c, 7, 10, T50);
SET(c, d, a, b, 14, 15, T51);
SET(b, c, d, a, 5, 21, T52);
SET(a, b, c, d, 12, 6, T53);
SET(d, a, b, c, 3, 10, T54);
SET(c, d, a, b, 10, 15, T55);
SET(b, c, d, a, 1, 21, T56);
SET(a, b, c, d, 8, 6, T57);
SET(d, a, b, c, 15, 10, T58);
SET(c, d, a, b, 6, 15, T59);
SET(b, c, d, a, 13, 21, T60);
SET(a, b, c, d, 4, 6, T61);
SET(d, a, b, c, 11, 10, T62);
SET(c, d, a, b, 2, 15, T63);
SET(b, c, d, a, 9, 21, T64);
#undef SET
/* Then perform the following additions. (That is increment each
of the four registers by the value it had before this block
was started.) */
pms->abcd[0] += a;
pms->abcd[1] += b;
pms->abcd[2] += c;
pms->abcd[3] += d;
}
void
md5_init(md5_state_t *pms)
{
pms->count[0] = pms->count[1] = 0;
pms->abcd[0] = 0x67452301;
pms->abcd[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476;
pms->abcd[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301;
pms->abcd[3] = 0x10325476;
}
void
md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes)
{
const md5_byte_t *p = data;
int left = nbytes;
int offset = (pms->count[0] >> 3) & 63;
md5_word_t nbits = (md5_word_t)(nbytes << 3);
if (nbytes <= 0)
return;
/* Update the message length. */
pms->count[1] += nbytes >> 29;
pms->count[0] += nbits;
if (pms->count[0] < nbits)
pms->count[1]++;
/* Process an initial partial block. */
if (offset) {
int copy = (offset + nbytes > 64 ? 64 - offset : nbytes);
memcpy(pms->buf + offset, p, copy);
if (offset + copy < 64)
return;
p += copy;
left -= copy;
md5_process(pms, pms->buf);
}
/* Process full blocks. */
for (; left >= 64; p += 64, left -= 64)
md5_process(pms, p);
/* Process a final partial block. */
if (left)
memcpy(pms->buf, p, left);
}
void
md5_finish(md5_state_t *pms, md5_byte_t digest[16])
{
static const md5_byte_t pad[64] = {
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
md5_byte_t data[8];
int i;
/* Save the length before padding. */
for (i = 0; i < 8; ++i)
data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3));
/* Pad to 56 bytes mod 64. */
md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1);
/* Append the length. */
md5_append(pms, data, 8);
for (i = 0; i < 16; ++i)
digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3));
}

91
code/globalcpp/md5.h Normal file
View file

@ -0,0 +1,91 @@
/*
Copyright (C) 1999, 2002 Aladdin Enterprises. All rights reserved.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
L. Peter Deutsch
ghost@aladdin.com
*/
/* $Id: md5.h,v 1.4 2002/04/13 19:20:28 lpd Exp $ */
/*
Independent implementation of MD5 (RFC 1321).
This code implements the MD5 Algorithm defined in RFC 1321, whose
text is available at
http://www.ietf.org/rfc/rfc1321.txt
The code is derived from the text of the RFC, including the test suite
(section A.5) but excluding the rest of Appendix A. It does not include
any code or documentation that is identified in the RFC as being
copyrighted.
The original and principal author of md5.h is L. Peter Deutsch
<ghost@aladdin.com>. Other authors are noted in the change history
that follows (in reverse chronological order):
2002-04-13 lpd Removed support for non-ANSI compilers; removed
references to Ghostscript; clarified derivation from RFC 1321;
now handles byte order either statically or dynamically.
1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5);
added conditionalization for C++ compilation from Martin
Purschke <purschke@bnl.gov>.
1999-05-03 lpd Original version.
*/
#ifndef md5_INCLUDED
# define md5_INCLUDED
/*
* This package supports both compile-time and run-time determination of CPU
* byte order. If ARCH_IS_BIG_ENDIAN is defined as 0, the code will be
* compiled to run only on little-endian CPUs; if ARCH_IS_BIG_ENDIAN is
* defined as non-zero, the code will be compiled to run only on big-endian
* CPUs; if ARCH_IS_BIG_ENDIAN is not defined, the code will be compiled to
* run on either big- or little-endian CPUs, but will run slightly less
* efficiently on either one than if ARCH_IS_BIG_ENDIAN is defined.
*/
typedef unsigned char md5_byte_t; /* 8-bit byte */
typedef unsigned int md5_word_t; /* 32-bit word */
/* Define the state of the MD5 Algorithm. */
typedef struct md5_state_s {
md5_word_t count[2]; /* message length in bits, lsw first */
md5_word_t abcd[4]; /* digest buffer */
md5_byte_t buf[64]; /* accumulate block */
} md5_state_t;
#ifdef __cplusplus
extern "C"
{
#endif
/* Initialize the algorithm. */
void md5_init(md5_state_t *pms);
/* Append a string to the message. */
void md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes);
/* Finish the message and return the digest. */
void md5_finish(md5_state_t *pms, md5_byte_t digest[16]);
#ifdef __cplusplus
} /* end extern "C" */
#endif
#endif /* md5_INCLUDED */

34
code/globalcpp/object.cpp Normal file
View file

@ -0,0 +1,34 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// object.cpp : Object (used by common TIKIs)
#include "object.h"
#if defined ( GAME_DLL ) || defined ( CGAME_DLL )
CLASS_DECLARATION( Animate, Object, NULL )
#else
CLASS_DECLARATION( SimpleEntity, Object, NULL )
#endif
{
{ NULL, NULL }
};

48
code/globalcpp/object.h Normal file
View file

@ -0,0 +1,48 @@
/*
===========================================================================
Copyright (C) 2008 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// object.h: Object (used by common TIKIs)
#ifndef __OBJECT_H__
#define __OBJECT_H__
#if defined ( GAME_DLL ) || defined ( CGAME_DLL )
#include "animate.h"
class Object : public Animate {
public:
CLASS_PROTOTYPE( Object );
};
#else
#include "simpleentity.h"
class Object : public SimpleEntity {
public:
CLASS_PROTOTYPE( Object );
};
#endif
#endif /* __OBJECT_H__ */

91
code/globalcpp/parm.cpp Normal file
View file

@ -0,0 +1,91 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// parm.cpp : Event parameters
#include "glb_local.h"
#include "parm.h"
#include "scriptmaster.h"
#include "scriptvm.h"
Parm parm;
Event EV_Parm_GetOther
(
"other",
EV_DEFAULT,
NULL,
NULL,
"other",
EV_GETTER
);
Event EV_Parm_GetOwner
(
"owner",
EV_DEFAULT,
NULL,
NULL,
"owner",
EV_GETTER
);
Event EV_Parm_GetPreviousThread
(
"previousthread",
EV_DEFAULT,
NULL,
NULL,
"previousthread",
EV_GETTER
);
void Parm::Archive( Archiver& arc )
{
Listener::Archive( arc );
arc.ArchiveSafePointer( &other );
arc.ArchiveSafePointer( &owner );
}
void Parm::GetOther( Event *ev )
{
ev->AddListener( other );
}
void Parm::GetOwner( Event *ev )
{
ev->AddListener( owner );
}
void Parm::GetPreviousThread( Event *ev )
{
ev->AddListener( Director.PreviousThread() );
}
CLASS_DECLARATION( Listener, Parm, NULL )
{
{ &EV_Parm_GetOther, &Parm::GetOther },
{ &EV_Parm_GetOwner, &Parm::GetOwner },
{ &EV_Parm_GetPreviousThread, &Parm::GetPreviousThread },
{ NULL, NULL }
};

55
code/globalcpp/parm.h Normal file
View file

@ -0,0 +1,55 @@
/*
===========================================================================
Copyright (C) 2008 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// parm.h: Event parameters
#ifndef __PARM_H__
#define __PARM_H__
#include "listener.h"
class Parm : public Listener {
public:
// General trigger variables
SafePtr< Listener > other;
SafePtr< Listener > owner;
// Failure variables
qboolean movedone;
qboolean movefail;
qboolean motionfail;
qboolean upperfail;
qboolean sayfail;
public:
CLASS_PROTOTYPE( Parm );
virtual void Archive( Archiver& arc );
void GetOther( Event *ev );
void GetOwner( Event *ev );
void GetPreviousThread( Event *ev );
};
extern Parm parm;
#endif /* __PARM_H__ */

View file

@ -0,0 +1,341 @@
/*
===========================================================================
Copyright (C) 2008 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// parsetree.cpp: Abstract Syntax Layer for Lexer/Parser
#include "glb_local.h"
#include "parsetree.h"
#include <mem_tempalloc.h>
MEM_TempAlloc parsetree_allocator;
yyparsedata parsedata;
sval_u node_none = { 0 };
char *str_replace( char *orig, char *rep, char *with ) {
char *result; // the return string
char *ins; // the next insert point
char *tmp; // varies
int len_rep; // length of rep
int len_with; // length of with
int len_front; // distance between rep and end of last rep
int count; // number of replacements
if( !orig )
return NULL;
if( !rep )
rep = "";
len_rep = strlen( rep );
if( !with )
with = "";
len_with = strlen( with );
ins = orig;
for( count = 0; tmp = strstr( ins, rep ); ++count ) {
ins = tmp + len_rep;
}
// first time through the loop, all the variable are set correctly
// from here on,
// tmp points to the end of the result string
// ins points to the next occurrence of rep in orig
// orig points to the remainder of orig after "end of rep"
tmp = result = ( char * )parsetree_allocator.Alloc( strlen( orig ) + ( len_with - len_rep ) * count + 1 );
if( !result )
return NULL;
while( count-- ) {
ins = strstr( orig, rep );
len_front = ins - orig;
tmp = strncpy( tmp, orig, len_front ) + len_front;
tmp = strcpy( tmp, with ) + len_with;
orig += len_front + len_rep; // move to next "end of rep"
}
strcpy( tmp, orig );
return result;
}
void parsetree_freeall()
{
parsetree_allocator.FreeAll();
if( showopcodes->integer )
{
glbs.DPrintf( "%d bytes freed\n", parsedata.total_length );
}
}
void parsetree_init()
{
parsedata.total_length = 0;
}
int parsetree_length()
{
return parsedata.total_length;
}
#if 0
char *parsetree_string( const char *string )
{
//char *pszString = ( char * )parsetree_allocator.Alloc( strlen( string ) + 1 );
//strcpy( pszString, string );
char *buffer = str_replace( ( char * )string, "\\\"", "\"" );
if( buffer )
{
char *ptr = buffer;
if( ptr[ 0 ] == '"' )
{
ptr++;
}
int len = strlen( buffer );
if( buffer[ len - 1 ] == '"' )
{
buffer[ len - 1 ] = 0;
}
buffer = ptr;
}
return buffer;
}
#endif
extern size_t yyleng;
extern size_t prev_yyleng;
char *parsetree_malloc( size_t s )
{
parsedata.total_length += s;
return ( char * )parsetree_allocator.Alloc( s );
}
int node_compare( void *pe1, void *pe2 )
{
// wtf
// fixme
return 0;
}
sval_u append_lists( sval_u val1, sval_u val2 )
{
val1.node[ 1 ].node[ 1 ] = val2.node[ 0 ];
val1.node[ 1 ] = val2.node[ 1 ];
return val1;
}
sval_u append_node( sval_u val1, sval_u val2 )
{
sval_u *node;
node = ( sval_u * )parsetree_malloc( sizeof( sval_u ) * 2 );
node[ 1 ].node = NULL;
node[ 0 ] = val2;
val1.node[ 1 ].node[ 1 ].node = node;
val1.node[ 1 ].node = node;
return val1;
}
sval_u prepend_node( sval_u val1, sval_u val2 )
{
sval_u *node;
node = ( sval_u * )parsetree_malloc( sizeof( sval_u ) * 2 );
node[ 0 ] = val1;
node[ 1 ] = val2;
val2.node = node;
return val2;
}
sval_u linked_list_end( sval_u val )
{
sval_u *node;
sval_u end;
node = ( sval_u * )parsetree_malloc( sizeof( sval_u ) * 2 );
node[ 0 ] = val;
node[ 1 ].node = NULL;
end.node = ( sval_u * )parsetree_malloc( sizeof( sval_u ) * 2 );
end.node[ 0 ].node = node;
end.node[ 1 ].node = node;
return end;
}
sval_u node1_( int val1 )
{
sval_u val;
val.intValue = val1;
return val;
}
sval_u node1b( int val1 )
{
sval_u val;
val.byteValue = val1;
return val;
}
sval_u node_pos( unsigned int pos )
{
sval_u val;
val.sourcePosValue = pos;
return val;
}
sval_u node_string( char *text )
{
sval_u val;
val.stringValue = text;
return val;
}
sval_u node0( int type )
{
sval_u val;
if( type == sval_none )
{
// memory optimization
val.node = &node_none;
}
else
{
val.node = ( sval_u * )parsetree_malloc( sizeof( sval_u ) * 1 );
val.node[ 0 ].node = NULL;
val.node[ 0 ].type = type;
}
return val;
}
sval_u node1( int type, sval_u val1 )
{
sval_u val;
val.node = ( sval_u * )parsetree_malloc( sizeof( sval_u ) * 2 );
val.node[ 0 ].type = type;
val.node[ 1 ] = val1;
return val;
}
sval_u node2( int type, sval_u val1, sval_u val2 )
{
sval_u val;
val.node = ( sval_u * )parsetree_malloc( sizeof( sval_u ) * 3 );
val.node[ 0 ].type = type;
val.node[ 1 ] = val1;
val.node[ 2 ] = val2;
return val;
}
sval_u node3( int type, sval_u val1, sval_u val2, sval_u val3 )
{
sval_u val;
val.node = ( sval_u * )parsetree_malloc( sizeof( sval_u ) * 4 );
val.node[ 0 ].type = type;
val.node[ 1 ] = val1;
val.node[ 2 ] = val2;
val.node[ 3 ] = val3;
return val;
}
sval_u node4( int type, sval_u val1, sval_u val2, sval_u val3, sval_u val4 )
{
sval_u val;
val.node = ( sval_u * )parsetree_malloc( sizeof( sval_u ) * 5 );
val.node[ 0 ].type = type;
val.node[ 1 ] = val1;
val.node[ 2 ] = val2;
val.node[ 3 ] = val3;
val.node[ 4 ] = val4;
return val;
}
sval_u node5( int type, sval_u val1, sval_u val2, sval_u val3, sval_u val4, sval_u val5 )
{
sval_u val;
val.node = ( sval_u * )parsetree_malloc( sizeof( sval_u ) * 6 );
val.node[ 0 ].type = type;
val.node[ 1 ] = val1;
val.node[ 2 ] = val2;
val.node[ 3 ] = val3;
val.node[ 4 ] = val4;
val.node[ 5 ] = val5;
return val;
}
sval_u node6( int type, sval_u val1, sval_u val2, sval_u val3, sval_u val4, sval_u val5, sval_u val6 )
{
sval_u val;
val.node = ( sval_u * )parsetree_malloc( sizeof( sval_u ) * 7 );
val.node[ 0 ].type = type;
val.node[ 1 ] = val1;
val.node[ 2 ] = val2;
val.node[ 3 ] = val3;
val.node[ 4 ] = val4;
val.node[ 5 ] = val5;
val.node[ 6 ] = val6;
return val;
}

View file

@ -0,0 +1,148 @@
/*
===========================================================================
Copyright (C) 2008 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// parsetree.h: Abstract Syntax Layer for Lexer/Parser
#ifndef __PARSETREE_H__
#define __PARSETREE_H__
#if defined ( GAME_DLL )
#define showopcodes g_showopcodes
#elif defined( CGAME_DLL )
#define showopcodes cg_showopcodes
#else
#define showopcodes g_showopcodes
#endif
typedef enum
{
sval_none,
sval_next,
sval_statement_list,
sval_label,
sval_case,
sval_negative,
sval_assignment,
sval_if,
sval_ifelse,
sval_while,
sval_and,
sval_or,
sval_cmd_method,
sval_cmd_method_ret,
sval_cmd,
sval_cmd_default_ret,
sval_field,
sval_store_method,
sval_store_string,
sval_store_integer,
sval_store_float,
sval_calc_vector,
sval_store_null,
sval_store_nil,
sval_func1,
sval_operation,
sval_not,
sval_array,
sval_constarray,
sval_makearray,
sval_catch,
sval_switch,
sval_break,
sval_continue,
sval_do,
sval_privatelabel,
sval_define
} sval_type_e;
typedef union sval_u {
int type;
char *stringValue;
float floatValue;
int intValue;
char charValue;
unsigned char byteValue;
unsigned char *posValue;
int MaxVarStackOffset;
int HasExternal;
union sval_u *node;
unsigned int sourcePosValue;
} sval_t;
typedef struct {
sval_t val;
unsigned int sourcePos;
} stype_t;
void parsetree_freeall();
void parsetree_init();
int parsetree_length();
char *parsetree_malloc( size_t s );
int node_compare( void *pe1, void *pe2 );
sval_u append_lists( sval_u val1, sval_u val2 );
sval_u append_node( sval_u val1, sval_u val2 );
sval_u prepend_node( sval_u val1, sval_u val2 );
sval_u linked_list_end( sval_u val );
sval_u node1_( int val1 );
sval_u node1b( int val1 );
sval_u node_pos( unsigned int pos );
sval_u node_string( char *text );
sval_u node0( int type );
sval_u node1( int type, sval_u val1 );
sval_u node2( int type, sval_u val1, sval_u val2 );
sval_u node3( int type, sval_u val1, sval_u val2, sval_u val3 );
sval_u node4( int type, sval_u val1, sval_u val2, sval_u val3, sval_u val4 );
sval_u node5( int type, sval_u val1, sval_u val2, sval_u val3, sval_u val4, sval_u val5 );
sval_u node6( int type, sval_u val1, sval_u val2, sval_u val3, sval_u val4, sval_u val5, sval_u val6 );
struct yyexception {
int yylineno;
str yytext;
str yytoken;
yyexception() { yylineno = 0; }
};
struct yyparsedata {
int total_length;
int braces_count;
int line_count;
unsigned int pos;
sval_t val;
char *sourceBuffer;
class GameScript *gameScript;
yyexception exc;
yyparsedata() { total_length = 0, braces_count = 0, line_count = 0, pos = 0; val = sval_t(); sourceBuffer = NULL; gameScript = NULL; }
};
extern yyparsedata parsedata;
#endif

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,326 @@
#ifndef yyHEADER_H
#define yyHEADER_H 1
#define yyIN_HEADER 1
#line 6 "../../../code/globalcpp/parser/yyLexer.h"
#line 8 "../../../code/globalcpp/parser/yyLexer.h"
#define YY_INT_ALIGNED short int
/* A lexical scanner generated by flex */
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 5
#define YY_FLEX_SUBMINOR_VERSION 37
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
/* First, we deal with platform-specific or compiler-specific issues. */
/* begin standard C headers. */
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
/* end standard C headers. */
/* flex integer type definitions */
#ifndef FLEXINT_H
#define FLEXINT_H
/* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
* if you want the limit (max/min) macros for int types.
*/
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS 1
#endif
#include <inttypes.h>
typedef int8_t flex_int8_t;
typedef uint8_t flex_uint8_t;
typedef int16_t flex_int16_t;
typedef uint16_t flex_uint16_t;
typedef int32_t flex_int32_t;
typedef uint32_t flex_uint32_t;
#else
typedef signed char flex_int8_t;
typedef short int flex_int16_t;
typedef int flex_int32_t;
typedef unsigned char flex_uint8_t;
typedef unsigned short int flex_uint16_t;
typedef unsigned int flex_uint32_t;
/* Limits of integral types. */
#ifndef INT8_MIN
#define INT8_MIN (-128)
#endif
#ifndef INT16_MIN
#define INT16_MIN (-32767-1)
#endif
#ifndef INT32_MIN
#define INT32_MIN (-2147483647-1)
#endif
#ifndef INT8_MAX
#define INT8_MAX (127)
#endif
#ifndef INT16_MAX
#define INT16_MAX (32767)
#endif
#ifndef INT32_MAX
#define INT32_MAX (2147483647)
#endif
#ifndef UINT8_MAX
#define UINT8_MAX (255U)
#endif
#ifndef UINT16_MAX
#define UINT16_MAX (65535U)
#endif
#ifndef UINT32_MAX
#define UINT32_MAX (4294967295U)
#endif
#endif /* ! C99 */
#endif /* ! FLEXINT_H */
#ifdef __cplusplus
/* The "const" storage-class-modifier is valid. */
#define YY_USE_CONST
#else /* ! __cplusplus */
/* C99 requires __STDC__ to be defined as 1. */
#if defined (__STDC__)
#define YY_USE_CONST
#endif /* defined (__STDC__) */
#endif /* ! __cplusplus */
#ifdef YY_USE_CONST
#define yyconst const
#else
#define yyconst
#endif
/* Size of default input buffer. */
#ifndef YY_BUF_SIZE
#define YY_BUF_SIZE 16384
#endif
#ifndef YY_TYPEDEF_YY_BUFFER_STATE
#define YY_TYPEDEF_YY_BUFFER_STATE
typedef struct yy_buffer_state *YY_BUFFER_STATE;
#endif
#ifndef YY_TYPEDEF_YY_SIZE_T
#define YY_TYPEDEF_YY_SIZE_T
typedef size_t yy_size_t;
#endif
extern yy_size_t yyleng;
extern FILE *yyin, *yyout;
#ifndef YY_STRUCT_YY_BUFFER_STATE
#define YY_STRUCT_YY_BUFFER_STATE
struct yy_buffer_state
{
FILE *yy_input_file;
char *yy_ch_buf; /* input buffer */
char *yy_buf_pos; /* current position in input buffer */
/* Size of input buffer in bytes, not including room for EOB
* characters.
*/
yy_size_t yy_buf_size;
/* Number of characters read into yy_ch_buf, not including EOB
* characters.
*/
yy_size_t yy_n_chars;
/* Whether we "own" the buffer - i.e., we know we created it,
* and can realloc() it to grow it, and should free() it to
* delete it.
*/
int yy_is_our_buffer;
/* Whether this is an "interactive" input source; if so, and
* if we're using stdio for input, then we want to use getc()
* instead of fread(), to make sure we stop fetching input after
* each newline.
*/
int yy_is_interactive;
/* Whether we're considered to be at the beginning of a line.
* If so, '^' rules will be active on the next match, otherwise
* not.
*/
int yy_at_bol;
int yy_bs_lineno; /**< The line count. */
int yy_bs_column; /**< The column count. */
/* Whether to try to fill the input buffer when we reach the
* end of it.
*/
int yy_fill_buffer;
int yy_buffer_status;
};
#endif /* !YY_STRUCT_YY_BUFFER_STATE */
void yyrestart (FILE *input_file );
void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer );
YY_BUFFER_STATE yy_create_buffer (FILE *file,int size );
void yy_delete_buffer (YY_BUFFER_STATE b );
void yy_flush_buffer (YY_BUFFER_STATE b );
void yypush_buffer_state (YY_BUFFER_STATE new_buffer );
void yypop_buffer_state (void );
YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size );
YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str );
YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,yy_size_t len );
void *yyalloc (yy_size_t );
void *yyrealloc (void *,yy_size_t );
void yyfree (void * );
/* Begin user sect3 */
#define yywrap() 1
#define YY_SKIP_YYWRAP
extern int yylineno;
extern char *yytext;
#define yytext_ptr yytext
#ifdef YY_HEADER_EXPORT_START_CONDITIONS
#define INITIAL 0
#define C_COMMENT 1
#define C_LINE_COMMENT 2
#define VARIABLES 3
#define IDENTIFIER 4
#endif
#ifndef YY_NO_UNISTD_H
/* Special case for "unistd.h", since it is non-ANSI. We include it way
* down here because we want the user's section 1 to have been scanned first.
* The user has a chance to override it with an option.
*/
#include <unistd.h>
#endif
#ifndef YY_EXTRA_TYPE
#define YY_EXTRA_TYPE void *
#endif
/* Accessor methods to globals.
These are made visible to non-reentrant scanners for convenience. */
int yylex_destroy (void );
int yyget_debug (void );
void yyset_debug (int debug_flag );
YY_EXTRA_TYPE yyget_extra (void );
void yyset_extra (YY_EXTRA_TYPE user_defined );
FILE *yyget_in (void );
void yyset_in (FILE * in_str );
FILE *yyget_out (void );
void yyset_out (FILE * out_str );
yy_size_t yyget_leng (void );
char *yyget_text (void );
int yyget_lineno (void );
void yyset_lineno (int line_number );
/* Macros after this point can all be overridden by user definitions in
* section 1.
*/
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
extern "C" int yywrap (void );
#else
extern int yywrap (void );
#endif
#endif
#ifndef yytext_ptr
static void yy_flex_strncpy (char *,yyconst char *,int );
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * );
#endif
#ifndef YY_NO_INPUT
#endif
/* Amount of stuff to slurp up with each read. */
#ifndef YY_READ_BUF_SIZE
#define YY_READ_BUF_SIZE 8192
#endif
/* Number of entries by which start-condition stack grows. */
#ifndef YY_START_STACK_INCR
#define YY_START_STACK_INCR 25
#endif
/* Default declaration of generated scanner - a define so the user can
* easily add parameters.
*/
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
extern int yylex (void);
#define YY_DECL int yylex (void)
#endif /* !YY_DECL */
/* yy_get_previous_state - get the state just before the EOB char was reached */
#undef YY_NEW_FILE
#undef YY_FLUSH_BUFFER
#undef yy_set_bol
#undef yy_new_buffer
#undef yy_set_interactive
#undef YY_DO_BEFORE_ACTION
#ifdef YY_DECL_IS_OURS
#undef YY_DECL_IS_OURS
#undef YY_DECL
#endif
#line 282 "..\\..\\..\\code\\globalcpp\\parser\\yyLexer.l"
#line 325 "../../../code/globalcpp/parser/yyLexer.h"
#undef yyIN_HEADER
#endif /* yyHEADER_H */

View file

@ -0,0 +1,283 @@
%{
/*
* ===========================================================================
* Copyright (C) 2015 the OpenMoHAA team
*
* This file is part of OpenMoHAA source code.
*
* OpenMoHAA source code is free software; you can redistribute it
* and/or modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
* ===========================================================================
*
*
* yyLexer.*: FLEX Lexical grammar for MoHScript.
*/
#include "compiler.h"
#include "yyParser.h"
#include <stdio.h>
void fprintf2( FILE *f, const char *format, ... )
{
va_list va;
static char buffer[ 4200 ];
va_start( va, format );
vsprintf( buffer, format, va );
va_end( va );
glbs.Printf( buffer );
}
#define fprintf fprintf2
int prev_yylex = 0;
extern yyparsedata parsedata;
#define YYLLOCSET { yylval.s.sourcePos = parsedata.pos - yyleng; }
#define YYLEX(n) { prev_yylex = n; return n; }
#define YY_USER_ACTION parsedata.pos; parsedata.pos += yyleng;
#define YY_FATAL_ERROR( n ) yylexerror( n )
void yylexerror( const char *msg )
{
glbs.Printf( "%s\n%s", msg, yytext );
assert( 0 );
}
static void TextEscapeValue( char *str, int len )
{
char *to = parsetree_malloc( len + 1 );
yylval.s.val.stringValue = to;
while( len )
{
if( *str == '\\' )
{
len--;
if( !len )
break;
str++;
if( *str == 'n' )
{
*to = '\n';
}
else if( *str == 't' )
{
*to = '\t';
}
else if( *str == '"' )
{
*to = '\"';
}
else
{
*to = *str;
}
}
else
{
*to = *str;
}
len--;
str++;
to++;
}
*to = 0;
}
static void TextValue( char *str, int len )
{
yylval.s.val.stringValue = parsetree_malloc( len + 1 );
strncpy( yylval.s.val.stringValue, str, len );
yylval.s.val.stringValue[ len ] = 0;
}
static bool UseField( void )
{
//return prev_yylex == TOKEN_PERIOD || prev_yylex == TOKEN_DOLLAR;
return ( !strncmp( yytext, "game.", 5 ) ||
!strncmp( yytext, "group.", 6 ) ||
!strncmp( yytext, "level.", 6 ) ||
!strncmp( yytext, "local.", 6 ) ||
!strncmp( yytext, "parm.", 5 ) ||
!strncmp( yytext, "owner.", 6 ) ||
!strncmp( yytext, "self.", 5 ) ||
*yytext == '$' || *yytext == '-' || *yytext == '/' );
}
%}
/*%option debug*/
%option outfile="../../../code/globalcpp/parser/yyLexer.cpp" header-file="../../../code/globalcpp/parser/yyLexer.h"
%option warn nodefault
%option noyywrap never-interactive
%option yylineno
%x C_COMMENT
%x C_LINE_COMMENT
%x VARIABLES
%x IDENTIFIER
%%
"/*" { BEGIN( C_COMMENT ); }
<C_COMMENT>"*/" { BEGIN( INITIAL ); }
<C_COMMENT>\n { ; }
<C_COMMENT>. { ; }
"*/" { Compiler.CompileError( parsedata.pos - yyleng, "'*/' found outside of comment" ); }
"//"[^\r\n]* { if( prev_yylex != TOKEN_EOL ) YYLEX( TOKEN_EOL ); }
<VARIABLES>[\r\n]* { BEGIN( INITIAL ); YYLEX( TOKEN_EOL ); }
<VARIABLES>"size" { YYLEX( TOKEN_SIZE ); }
<VARIABLES>"." { YYLEX( TOKEN_PERIOD ); }
<VARIABLES>\"([^\\\"]|\\.)*\" { YYLLOCSET; TextEscapeValue( yytext + 1, strlen( yytext ) - 2 ); YYLEX( TOKEN_STRING ); }
<VARIABLES>[a-zA-Z0-9_\"]+ { YYLLOCSET; TextValue( yytext, strlen( yytext ) ); YYLEX( TOKEN_IDENTIFIER ); }
<VARIABLES>. {
for ( int i = yyleng - 1; i >= 0; --i )
unput( yytext[ i ] );
parsedata.pos -= yyleng;
BEGIN( INITIAL );
}
[\r\n]* { if( prev_yylex != TOKEN_EOL ) YYLEX( TOKEN_EOL ); }
[ \t]* { ; }
\"([^\\\"]|\\.)*\" { YYLLOCSET; TextEscapeValue( yytext + 1, strlen( yytext ) - 2 ); YYLEX( TOKEN_STRING ); }
"?" { YYLEX( TOKEN_TERNARY ); }
"if" { YYLEX( TOKEN_IF ); }
"else" { YYLEX( TOKEN_ELSE ); }
"while" { YYLEX( TOKEN_WHILE ); }
"for" { YYLEX( TOKEN_FOR ); }
"do" { YYLEX( TOKEN_DO ); }
"game"? { BEGIN( VARIABLES ); yylval.s.val = node1_( method_game ); YYLEX( TOKEN_LISTENER ); }
"group" { BEGIN( VARIABLES ); yylval.s.val = node1_( method_group ); YYLEX( TOKEN_LISTENER ); }
"level" { BEGIN( VARIABLES ); yylval.s.val = node1_( method_level ); YYLEX( TOKEN_LISTENER ); }
"local" { BEGIN( VARIABLES ); yylval.s.val = node1_( method_local ); YYLEX( TOKEN_LISTENER ); }
"parm" { BEGIN( VARIABLES ); yylval.s.val = node1_( method_parm ); YYLEX( TOKEN_LISTENER ); }
"owner" { BEGIN( VARIABLES ); yylval.s.val = node1_( method_owner ); YYLEX( TOKEN_LISTENER ); }
"self" { BEGIN( VARIABLES ); yylval.s.val = node1_( method_self ); YYLEX( TOKEN_LISTENER ); }
"{" { parsedata.braces_count++; YYLEX( TOKEN_LBRACKET ); }
"}" { parsedata.braces_count--; YYLEX( TOKEN_RBRACKET ); }
"(" { YYLLOCSET; YYLEX( TOKEN_LPAREN ); }
")" { BEGIN( VARIABLES ); YYLLOCSET; YYLEX( TOKEN_RPAREN ); }
"[" { YYLEX( TOKEN_LSQUARE ); }
"]" { BEGIN( VARIABLES ); YYLEX( TOKEN_RSQUARE ); }
"=" { YYLEX( TOKEN_ASSIGNMENT ); }
":" { YYLEX( TOKEN_COLON ); }
"::" { YYLEX( TOKEN_DOUBLE_COLON ); }
";" { YYLEX( TOKEN_SEMICOLON ); }
"==" { YYLEX( TOKEN_EQUALITY ); }
"||" { YYLEX( TOKEN_LOGICAL_OR ); }
"&&" { YYLEX( TOKEN_LOGICAL_AND ); }
"|" { YYLEX( TOKEN_BITWISE_OR ); }
"^" { YYLEX( TOKEN_BITWISE_EXCL_OR ); }
"&" { YYLEX( TOKEN_BITWISE_AND ); }
"!=" { YYLEX( TOKEN_INEQUALITY ); }
"<" { YYLEX( TOKEN_LESS_THAN ); }
">" { YYLEX( TOKEN_GREATER_THAN ); }
"<=" { YYLEX( TOKEN_LESS_THAN_OR_EQUAL ); }
">=" { YYLEX( TOKEN_GREATER_THAN_OR_EQUAL ); }
[ ]"-" { YYLEX( TOKEN_NEG ); }
"+" { YYLEX( TOKEN_PLUS ); }
"+=" { YYLEX( TOKEN_PLUS_EQUALS ); }
"++"|[ ]"++" { YYLEX( TOKEN_INCREMENT ); }
"-"|"-"[ ]|[ ]"-"[ ] { YYLEX( TOKEN_MINUS ); }
"-=" { YYLEX( TOKEN_MINUS_EQUALS ); }
[ ]"-=" { YYLEX( TOKEN_MINUS_EQUALS ); }
"--"|[ ]"--" { YYLEX( TOKEN_DECREMENT ); }
"*" { YYLEX( TOKEN_MULTIPLY ); }
"*=" { YYLEX( TOKEN_MULTIPLY_EQUALS ); }
"/" { YYLEX( TOKEN_DIVIDE ); }
"/=" { YYLEX( TOKEN_DIVIDE_EQUALS ); }
"%" { YYLEX( TOKEN_MODULUS ); }
"%=" { YYLEX( TOKEN_MODULUS_EQUALS ); }
"<<" { YYLEX( TOKEN_SHIFT_LEFT ); }
"<<=" { YYLEX( TOKEN_SHIFT_LEFT_EQUALS ); }
">>" { YYLEX( TOKEN_SHIFT_RIGHT ); }
">>=" { YYLEX( TOKEN_SHIFT_RIGHT_EQUALS ); }
"&=" { YYLEX( TOKEN_AND_EQUALS ); }
"^=" { YYLEX( TOKEN_EXCL_OR_EQUALS ); }
"|=" { YYLEX( TOKEN_OR_EQUALS ); }
"$" { BEGIN( VARIABLES ); YYLEX( TOKEN_DOLLAR ); }
"!" { YYLEX( TOKEN_NOT ); }
"~" { YYLEX( TOKEN_COMPLEMENT ); }
"." { YYLEX( TOKEN_PERIOD ); }
"," { YYLEX( TOKEN_COMMA ); }
"#" { YYLEX( TOKEN_NUMBER ); }
"NULL" { YYLEX( TOKEN_NULL ); }
"NIL" { YYLEX( TOKEN_NIL ); }
[0-9]+ { YYLLOCSET; sscanf( yytext, "%d", &yylval.s.val.intValue ); YYLEX( TOKEN_INTEGER ); }
[0-9\.]+|[0-9\.]+("e+"|"e-")+[0-9\.] { YYLLOCSET; sscanf( yytext, "%f", &yylval.s.val.floatValue ); YYLEX( TOKEN_FLOAT ); }
"try" { YYLEX( TOKEN_TRY ); }
"catch" { YYLEX( TOKEN_CATCH ); }
"switch" { YYLEX( TOKEN_SWITCH ); }
"case" { YYLEX( TOKEN_CASE ); }
"break" { YYLEX( TOKEN_BREAK ); }
"continue" { YYLEX( TOKEN_CONTINUE ); }
"makearray"|"makeArray" { YYLEX( TOKEN_MAKEARRAY ); }
"endarray"|"endArray" { YYLEX( TOKEN_ENDARRAY ); }
[a-zA-Z0-9_\./\\-]+ {
if( UseField() )
{
parsedata.pos -= yyleng;
REJECT;
}
else
{
YYLLOCSET;
TextEscapeValue( yytext, yyleng );
YYLEX( TOKEN_IDENTIFIER );
}
}
. { yylexerror( "bad token:\n" ); }
%{
#undef fprintf
%}
%%

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,159 @@
/* A Bison parser, made by GNU Bison 2.7. */
/* Bison interface for Yacc-like parsers in C
Copyright (C) 1984, 1989-1990, 2000-2012 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
#ifndef YY_YY_CODE_GLOBALCPP_PARSER_YYPARSER_H_INCLUDED
# define YY_YY_CODE_GLOBALCPP_PARSER_YYPARSER_H_INCLUDED
/* Enabling traces. */
#ifndef YYDEBUG
# define YYDEBUG 0
#endif
#if YYDEBUG
extern int yydebug;
#endif
/* Tokens. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
/* Put the tokens into the symbol table, so that GDB and other debuggers
know about them. */
enum yytokentype {
END = 0,
TOKEN_EOL = 258,
TOKEN_COMMA = 259,
TOKEN_TERNARY = 260,
TOKEN_SHIFT_RIGHT_EQUALS = 261,
TOKEN_SHIFT_LEFT_EQUALS = 262,
TOKEN_OR_EQUALS = 263,
TOKEN_EXCL_OR_EQUALS = 264,
TOKEN_AND_EQUALS = 265,
TOKEN_MODULUS_EQUALS = 266,
TOKEN_DIVIDE_EQUALS = 267,
TOKEN_MULTIPLY_EQUALS = 268,
TOKEN_MINUS_EQUALS = 269,
TOKEN_PLUS_EQUALS = 270,
TOKEN_ASSIGNMENT = 271,
TOKEN_LOGICAL_OR = 272,
TOKEN_LOGICAL_AND = 273,
TOKEN_BITWISE_OR = 274,
TOKEN_BITWISE_EXCL_OR = 275,
TOKEN_BITWISE_AND = 276,
TOKEN_INEQUALITY = 277,
TOKEN_EQUALITY = 278,
TOKEN_GREATER_THAN_OR_EQUAL = 279,
TOKEN_GREATER_THAN = 280,
TOKEN_LESS_THAN_OR_EQUAL = 281,
TOKEN_LESS_THAN = 282,
TOKEN_SHIFT_RIGHT = 283,
TOKEN_SHIFT_LEFT = 284,
TOKEN_MINUS = 285,
TOKEN_PLUS = 286,
TOKEN_MODULUS = 287,
TOKEN_DIVIDE = 288,
TOKEN_MULTIPLY = 289,
TOKEN_LISTENER = 290,
TOKEN_COMPLEMENT = 291,
TOKEN_NOT = 292,
TOKEN_NEG = 293,
TOKEN_FLOAT = 294,
TOKEN_INTEGER = 295,
TOKEN_IDENTIFIER = 296,
TOKEN_STRING = 297,
TOKEN_NIL = 298,
TOKEN_NULL = 299,
TOKEN_LBRACKET = 300,
TOKEN_RBRACKET = 301,
TOKEN_COLON = 302,
TOKEN_SEMICOLON = 303,
TOKEN_DOLLAR = 304,
TOKEN_DOUBLE_COLON = 305,
TOKEN_NUMBER = 306,
TOKEN_PERIOD = 307,
TOKEN_DECREMENT = 308,
TOKEN_INCREMENT = 309,
TOKEN_RPAREN = 310,
TOKEN_LPAREN = 311,
TOKEN_RSQUARE = 312,
TOKEN_LSQUARE = 313,
TOKEN_MAKEARRAY = 314,
TOKEN_ENDARRAY = 315,
TOKEN_CATCH = 316,
TOKEN_TRY = 317,
TOKEN_DO = 318,
TOKEN_FOR = 319,
TOKEN_IF = 320,
TOKEN_ELSE = 321,
TOKEN_SWITCH = 322,
TOKEN_WHILE = 323,
TOKEN_BREAK = 324,
TOKEN_CASE = 325,
TOKEN_CONTINUE = 326,
TOKEN_SIZE = 327,
TOKEN_END = 328,
TOKEN_RETURN = 329
};
#endif
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
typedef union YYSTYPE
{
/* Line 2058 of yacc.c */
#line 53 "..\\..\\..\\code\\globalcpp\\parser\\yyParser.yy"
stype_t s;
/* Line 2058 of yacc.c */
#line 137 "../../../code/globalcpp/parser/yyParser.h"
} YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1
# define yystype YYSTYPE /* obsolescent; will be withdrawn */
# define YYSTYPE_IS_DECLARED 1
#endif
extern YYSTYPE yylval;
#ifdef YYPARSE_PARAM
#if defined __STDC__ || defined __cplusplus
int yyparse (void *YYPARSE_PARAM);
#else
int yyparse ();
#endif
#else /* ! YYPARSE_PARAM */
#if defined __STDC__ || defined __cplusplus
int yyparse (void);
#else
int yyparse ();
#endif
#endif /* ! YYPARSE_PARAM */
#endif /* !YY_YY_CODE_GLOBALCPP_PARSER_YYPARSER_H_INCLUDED */

View file

@ -0,0 +1,265 @@
%{
/*
* ===========================================================================
* Copyright (C) 2015 the OpenMoHAA team
*
* This file is part of OpenMoHAA source code.
*
* OpenMoHAA source code is free software; you can redistribute it
* and/or modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
* ===========================================================================
*
*
* yyParser.*: BISON Parser for MoHScript.
*/
#include "compiler.h"
#include "yyParser.h"
#include "yyLexer.h"
int yyerror( const char *msg );
extern int prev_yylex;
extern yyparsedata parsedata;
#define YYLLOC node_pos( parsedata.pos - yyleng )
%}
%output "../../../code/globalcpp/parser/yyParser.cpp"
%defines "../../../code/globalcpp/parser/yyParser.h"
%error-verbose
%expect 281
%token END 0
%token TOKEN_EOL
%left TOKEN_COMMA
%union {
stype_t s;
}
%right TOKEN_ASSIGNMENT
TOKEN_PLUS_EQUALS TOKEN_MINUS_EQUALS TOKEN_MULTIPLY_EQUALS TOKEN_DIVIDE_EQUALS TOKEN_MODULUS_EQUALS
TOKEN_AND_EQUALS TOKEN_EXCL_OR_EQUALS TOKEN_OR_EQUALS
TOKEN_SHIFT_LEFT_EQUALS TOKEN_SHIFT_RIGHT_EQUALS
TOKEN_TERNARY
%left TOKEN_LOGICAL_OR
%left TOKEN_LOGICAL_AND
%left TOKEN_BITWISE_OR
%left TOKEN_BITWISE_EXCL_OR
%left TOKEN_BITWISE_AND
%left TOKEN_EQUALITY TOKEN_INEQUALITY
%left TOKEN_LESS_THAN TOKEN_LESS_THAN_OR_EQUAL TOKEN_GREATER_THAN TOKEN_GREATER_THAN_OR_EQUAL
%left TOKEN_SHIFT_LEFT TOKEN_SHIFT_RIGHT
%left TOKEN_PLUS TOKEN_MINUS
%left TOKEN_MULTIPLY TOKEN_DIVIDE TOKEN_MODULUS
%token <s> TOKEN_LISTENER
%right TOKEN_NEG TOKEN_NOT TOKEN_COMPLEMENT
%token <s> TOKEN_FLOAT TOKEN_INTEGER TOKEN_IDENTIFIER TOKEN_STRING TOKEN_NIL TOKEN_NULL
%token TOKEN_LBRACKET TOKEN_RBRACKET
%token TOKEN_COLON TOKEN_SEMICOLON TOKEN_DOLLAR TOKEN_DOUBLE_COLON TOKEN_NUMBER
%left <s> TOKEN_LSQUARE TOKEN_RSQUARE TOKEN_LPAREN TOKEN_RPAREN TOKEN_INCREMENT TOKEN_DECREMENT TOKEN_PERIOD
%token TOKEN_MAKEARRAY TOKEN_ENDARRAY
TOKEN_CATCH TOKEN_TRY
TOKEN_DO TOKEN_FOR TOKEN_IF TOKEN_ELSE TOKEN_SWITCH TOKEN_WHILE
TOKEN_BREAK TOKEN_CASE TOKEN_CONTINUE
TOKEN_SIZE
TOKEN_END TOKEN_RETURN
%type <s.val> event_parameter_list event_parameter_list_need
%type <s.val> statement_list statement makearray_statement_list makearray_statement
%type <s.val> compound_statement
%type <s.val> expr
%type <s.val> func_prim_expr
%type <s.val> prim_expr
%type <s.val> nonident_prim_expr
%type <s.val> number
%type <s> identifier_prim
%start program
%%
program:
newline statement_list { parsedata.val = node1( sval_statement_list, $2 ); }
;
statement_list:
statement_list statement newline { $$ = append_node( $1, $2 ); }
//| statement_list error TOKEN_EOL { yyerrok; }
| statement newline { $$ = linked_list_end( $1 ); }
| newline { $$ = node0( sval_none ); }
;
statement:
TOKEN_IDENTIFIER event_parameter_list TOKEN_COLON { $$ = node3( sval_label, $1.val, $2, YYLLOC ); }
| TOKEN_PLUS TOKEN_IDENTIFIER event_parameter_list TOKEN_COLON { $$ = node3( sval_label, $2.val, $3, YYLLOC ); }
| TOKEN_MINUS TOKEN_IDENTIFIER event_parameter_list TOKEN_COLON { $$ = node3( sval_privatelabel, $2.val, $3, YYLLOC ); }
| TOKEN_CASE prim_expr event_parameter_list TOKEN_COLON { $$ = node3( sval_case, $2, $3, YYLLOC ); }
| compound_statement
| TOKEN_IF prim_expr newline statement[S] newline { $$ = node3( sval_if, $2, $S, YYLLOC ); }
| TOKEN_IF prim_expr newline statement[S1] newline TOKEN_ELSE newline statement[S2] { $$ = node4( sval_ifelse, $2, $S1, $S2, YYLLOC ); }
| TOKEN_WHILE prim_expr newline statement { $$ = node4( sval_while, $2, $4, node0( sval_none ), YYLLOC ); }
| TOKEN_FOR TOKEN_LPAREN statement[SINIT] TOKEN_SEMICOLON expr[E] TOKEN_SEMICOLON statement_list[INC] TOKEN_RPAREN newline statement[S]
{
sval_u while_stmt = node4( sval_while, $E, $S, node1( sval_statement_list, $INC ), YYLLOC );
$$ = node1( sval_statement_list, append_node( linked_list_end( $SINIT ), while_stmt ) );
}
| TOKEN_DO newline statement[S] newline TOKEN_WHILE prim_expr[E] { $$ = node3( sval_do, $S, $E, YYLLOC ); }
| TOKEN_TRY newline compound_statement newline TOKEN_CATCH newline compound_statement { $$ = node3( sval_catch, $3, $7, YYLLOC ); }
| TOKEN_SWITCH prim_expr newline compound_statement { $$ = node3( sval_switch, $2, $4, YYLLOC ); }
| TOKEN_BREAK { $$ = node1( sval_break, YYLLOC ); }
| TOKEN_CONTINUE { $$ = node1( sval_continue, YYLLOC ); }
| TOKEN_IDENTIFIER event_parameter_list { $$ = node3( sval_cmd, $1.val, node1( sval_none, $2 ), node_pos( $1.sourcePos ) ); }
//| TOKEN_IDENTIFIER TOKEN_DOUBLE_COLON TOKEN_IDENTIFIER event_parameter_list { $$ = node3( sval_cmd, node_string( parsetree_string( str( $1.stringValue ) + "::" + $3.stringValue ) ), node1( sval_none, $4 ), $1.sourcePos ); }
| nonident_prim_expr TOKEN_IDENTIFIER event_parameter_list { $$ = node4( sval_cmd_method, $1, $2.val, node1( sval_none, $3 ), node_pos( $2.sourcePos ) ); }
//| nonident_prim_expr TOKEN_IDENTIFIER TOKEN_DOUBLE_COLON TOKEN_IDENTIFIER event_parameter_list { $$ = node4( sval_cmd_method, $1, node_string( parsetree_string( str( $2.stringValue ) + "::" + $4.stringValue ) ), node1( sval_none, $5 ), $2.sourcePos ); }
| nonident_prim_expr TOKEN_ASSIGNMENT expr { $$ = node3( sval_assignment, $1, $3, YYLLOC ); }
| nonident_prim_expr TOKEN_PLUS_EQUALS expr { $$ = node3( sval_assignment, $1, node4( sval_operation, node1b( OP_BIN_PLUS ), $1, $3, YYLLOC ), YYLLOC ); }
| nonident_prim_expr TOKEN_MINUS_EQUALS expr { $$ = node3( sval_assignment, $1, node4( sval_operation, node1b( OP_BIN_MINUS ), $1, $3, YYLLOC ), YYLLOC ); }
| nonident_prim_expr TOKEN_MULTIPLY_EQUALS expr { $$ = node3( sval_assignment, $1, node4( sval_operation, node1b( OP_BIN_MULTIPLY ), $1, $3, YYLLOC ), YYLLOC ); }
| nonident_prim_expr TOKEN_DIVIDE_EQUALS expr { $$ = node3( sval_assignment, $1, node4( sval_operation, node1b( OP_BIN_DIVIDE ), $1, $3, YYLLOC ), YYLLOC ); }
| nonident_prim_expr TOKEN_MODULUS_EQUALS expr { $$ = node3( sval_assignment, $1, node4( sval_operation, node1b( OP_BIN_PERCENTAGE ), $1, $3, YYLLOC ), YYLLOC ); }
| nonident_prim_expr TOKEN_AND_EQUALS expr { $$ = node3( sval_assignment, $1, node4( sval_operation, node1b( OP_BIN_BITWISE_AND ), $1, $3, YYLLOC ), YYLLOC ); }
| nonident_prim_expr TOKEN_EXCL_OR_EQUALS expr { $$ = node3( sval_assignment, $1, node4( sval_operation, node1b( OP_BIN_BITWISE_EXCL_OR ), $1, $3, YYLLOC ), YYLLOC ); }
| nonident_prim_expr TOKEN_OR_EQUALS expr { $$ = node3( sval_assignment, $1, node4( sval_operation, node1b( OP_BIN_BITWISE_OR ), $1, $3, YYLLOC ), YYLLOC ); }
| nonident_prim_expr TOKEN_SHIFT_LEFT_EQUALS expr { $$ = node3( sval_assignment, $1, node4( sval_operation, node1b( OP_BIN_SHIFT_LEFT ), $1, $3, YYLLOC ), YYLLOC ); }
| nonident_prim_expr TOKEN_SHIFT_RIGHT_EQUALS expr { $$ = node3( sval_assignment, $1, node4( sval_operation, node1b( OP_BIN_SHIFT_RIGHT ), $1, $3, YYLLOC ), YYLLOC ); }
| nonident_prim_expr TOKEN_INCREMENT { $$ = node3( sval_assignment, $1, node2( sval_func1, node1b( OP_UN_INC ), $1 ), YYLLOC ); }
| nonident_prim_expr TOKEN_DECREMENT { $$ = node3( sval_assignment, $1, node2( sval_func1, node1b( OP_UN_DEC ), $1 ), YYLLOC ); }
| statement TOKEN_SEMICOLON
;
compound_statement:
TOKEN_LBRACKET newline statement_list newline TOKEN_RBRACKET { $$ = node1( sval_statement_list, $3 ); }
;
expr:
expr TOKEN_LOGICAL_AND newline expr { $$ = node3( sval_and, $1, $4, YYLLOC ); }
| expr TOKEN_LOGICAL_OR newline expr { $$ = node3( sval_or, $1, $4, YYLLOC ); }
| expr TOKEN_BITWISE_AND newline expr { $$ = node4( sval_operation, node1b( OP_BIN_BITWISE_AND ), $1, $4, YYLLOC ); }
| expr TOKEN_BITWISE_EXCL_OR newline expr { $$ = node4( sval_operation, node1b( OP_BIN_BITWISE_EXCL_OR ), $1, $4, YYLLOC ); }
| expr TOKEN_BITWISE_OR newline expr { $$ = node4( sval_operation, node1b( OP_BIN_BITWISE_OR ), $1, $4, YYLLOC ); }
| expr TOKEN_EQUALITY newline expr { $$ = node4( sval_operation, node1b( OP_BIN_EQUALITY ), $1, $4, YYLLOC ); }
| expr TOKEN_INEQUALITY newline expr { $$ = node4( sval_operation, node1b( OP_BIN_INEQUALITY ), $1, $4, YYLLOC ); }
| expr TOKEN_LESS_THAN newline expr { $$ = node4( sval_operation, node1b( OP_BIN_LESS_THAN ), $1, $4, YYLLOC ); }
| expr TOKEN_GREATER_THAN newline expr { $$ = node4( sval_operation, node1b( OP_BIN_GREATER_THAN ), $1, $4, YYLLOC ); }
| expr TOKEN_LESS_THAN_OR_EQUAL newline expr { $$ = node4( sval_operation, node1b( OP_BIN_LESS_THAN_OR_EQUAL ), $1, $4, YYLLOC ); }
| expr TOKEN_GREATER_THAN_OR_EQUAL newline expr { $$ = node4( sval_operation, node1b( OP_BIN_GREATER_THAN_OR_EQUAL ), $1, $4, YYLLOC ); }
| expr TOKEN_PLUS newline expr { $$ = node4( sval_operation, node1b( OP_BIN_PLUS ), $1, $4, YYLLOC ); }
| expr TOKEN_MINUS newline expr { $$ = node4( sval_operation, node1b( OP_BIN_MINUS ), $1, $4, YYLLOC ); }
| expr TOKEN_MULTIPLY newline expr { $$ = node4( sval_operation, node1b( OP_BIN_MULTIPLY ), $1, $4, YYLLOC ); }
| expr TOKEN_DIVIDE newline expr { $$ = node4( sval_operation, node1b( OP_BIN_DIVIDE ), $1, $4, YYLLOC ); }
| expr TOKEN_MODULUS newline expr { $$ = node4( sval_operation, node1b( OP_BIN_PERCENTAGE ), $1, $4, YYLLOC ); }
| expr TOKEN_SHIFT_LEFT newline expr { $$ = node4( sval_operation, node1b( OP_BIN_SHIFT_LEFT ), $1, $4, YYLLOC ); }
| expr TOKEN_SHIFT_RIGHT newline expr { $$ = node4( sval_operation, node1b( OP_BIN_SHIFT_RIGHT ), $1, $4, YYLLOC ); }
| expr TOKEN_TERNARY expr TOKEN_COLON expr { $$ = node4( sval_ifelse, $1, $3, $5, YYLLOC ); }
| nonident_prim_expr
| func_prim_expr
| identifier_prim { $$ = node1( sval_store_string, $1.val ); }
;
func_prim_expr:
TOKEN_IDENTIFIER event_parameter_list_need { $$ = node3( sval_cmd_default_ret, $1.val, node1( sval_none, $2 ), node_pos( $1.sourcePos ) ); }
//| TOKEN_IDENTIFIER TOKEN_DOUBLE_COLON TOKEN_IDENTIFIER event_parameter_list_need { $$ = node3( sval_cmd_default_ret, node_string( parsetree_string( str( $1.val.stringValue ) + "::" + $3.val.stringValue ) ), node1( sval_none, $4 ), $1.sourcePos ); }
| nonident_prim_expr TOKEN_IDENTIFIER event_parameter_list { $$ = node4( sval_cmd_method_ret, $1, $2.val, node1( sval_none, $3 ), node_pos( $2.sourcePos ) ); }
//| nonident_prim_expr TOKEN_IDENTIFIER TOKEN_DOUBLE_COLON TOKEN_IDENTIFIER event_parameter_list { $$ = node4( sval_cmd_method_ret, $1, node_string( parsetree_string( str( $2.val.stringValue ) + "::" + $4.val.stringValue ) ), node1( sval_none, $5 ), $2.sourcePos ); }
| TOKEN_NEG func_prim_expr { $$ = node3( sval_func1, node1b( OP_UN_MINUS ), $2, YYLLOC ); }
| TOKEN_COMPLEMENT func_prim_expr { $$ = node3( sval_func1, node1b( OP_UN_COMPLEMENT ), $2, YYLLOC ); }
| TOKEN_NOT func_prim_expr { $$ = node2( sval_not, $2, YYLLOC ); }
| TOKEN_IDENTIFIER TOKEN_DOUBLE_COLON prim_expr { $$ = node3( sval_constarray, node2( sval_store_string, $1.val, node_pos( $1.sourcePos ) ), $3, YYLLOC ); }
| nonident_prim_expr TOKEN_DOUBLE_COLON prim_expr { $$ = node3( sval_constarray, $1, $3, YYLLOC ); }
| TOKEN_MAKEARRAY newline makearray_statement_list newline TOKEN_ENDARRAY { $$ = node1( sval_makearray, $3 ); }
;
event_parameter_list:
{ $$ = node0( sval_none ); }
| event_parameter_list prim_expr { $$ = append_node( $1, $2 ); }
| prim_expr { $$ = linked_list_end( $1 ); }
;
event_parameter_list_need:
event_parameter_list_need prim_expr { $$ = append_node( $1, $2 ); }
| prim_expr { $$ = linked_list_end( $1 ); }
;
prim_expr:
nonident_prim_expr
| identifier_prim { $$ = node1( sval_store_string, $1.val ); }
| prim_expr TOKEN_DOUBLE_COLON prim_expr { $$ = node3( sval_constarray, $1, $3, YYLLOC ); }
;
nonident_prim_expr:
TOKEN_DOLLAR TOKEN_LPAREN expr TOKEN_RPAREN { $$ = node3( sval_func1, node1b( OP_UN_TARGETNAME ), $3, YYLLOC ); }
| TOKEN_DOLLAR TOKEN_IDENTIFIER { $$ = node3( sval_func1, node1b( OP_UN_TARGETNAME ), node1( sval_store_string, $2.val ), YYLLOC ); }
| TOKEN_DOLLAR TOKEN_STRING { $$ = node3( sval_func1, node1b( OP_UN_TARGETNAME ), node1( sval_store_string, $2.val ), YYLLOC ); }
| nonident_prim_expr TOKEN_PERIOD TOKEN_IDENTIFIER { $$ = node3( sval_field, $1, $3.val, node_pos( $3.sourcePos ) ); }
| nonident_prim_expr TOKEN_PERIOD TOKEN_STRING { $$ = node3( sval_field, $1, $3.val, node_pos( $3.sourcePos ) ); }
| nonident_prim_expr TOKEN_PERIOD TOKEN_SIZE { $$ = node3( sval_func1, node1b( OP_UN_SIZE ), $1, YYLLOC ); }
| nonident_prim_expr TOKEN_LSQUARE expr TOKEN_RSQUARE { $$ = node3( sval_array, $1, $3, $1 ); }
| TOKEN_STRING { $$ = node1( sval_store_string, $1.val ); }
| number
| TOKEN_LPAREN expr expr expr TOKEN_RPAREN { $$ = node4( sval_calc_vector, $2, $3, $4, YYLLOC ); }
| TOKEN_LISTENER { $$ = node2( sval_store_method, $1.val, YYLLOC ); }
| TOKEN_LPAREN expr TOKEN_RPAREN { $$ = $2; }
| TOKEN_LPAREN TOKEN_RPAREN { $$ = node0( sval_none ); }
| TOKEN_NEG nonident_prim_expr { $$ = node3( sval_func1, node1b( OP_UN_MINUS ), $2, YYLLOC ); }
| TOKEN_COMPLEMENT nonident_prim_expr { $$ = node3( sval_func1, node1b( OP_UN_COMPLEMENT ), $2, YYLLOC ); }
| TOKEN_NOT nonident_prim_expr { $$ = node2( sval_not, $2, YYLLOC ); }
| TOKEN_NULL { $$ = node1( sval_store_null, YYLLOC ); }
| TOKEN_NIL { $$ = node1( sval_store_nil, YYLLOC ); }
;
number:
TOKEN_FLOAT { $$ = node1( sval_store_float, $1.val ); }
| TOKEN_INTEGER { $$ = node1( sval_store_integer, $1.val ); }
;
identifier_prim:
TOKEN_IDENTIFIER
;
makearray_statement_list:
{ $$ = node0( sval_none ); }
| makearray_statement_list makearray_statement newline { $$ = append_node( $1, node1( sval_makearray, $2 ) ); }
| makearray_statement newline { $$ = linked_list_end( node1( sval_makearray, $1 ) ); }
;
makearray_statement:
prim_expr { $$ = linked_list_end( $1 ); }
| makearray_statement prim_expr { $$ = append_node( $1, $2 ); }
;
newline:
{}
| TOKEN_EOL
;
%%

244
code/globalcpp/safeptr.h Normal file
View file

@ -0,0 +1,244 @@
/*
===========================================================================
Copyright (C) 2008 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// safeptr.h: Safe Pointers
#ifndef __SAFEPTR_H__
#define __SAFEPTR_H__
class SafePtrBase
{
private:
void AddReference( Class *ptr );
void RemoveReference( Class *ptr );
protected:
SafePtrBase *prev;
SafePtrBase *next;
Class *ptr;
public:
SafePtrBase();
virtual ~SafePtrBase();
void InitSafePtr( Class *newptr );
Class *Pointer( void );
void Clear( void );
};
inline void SafePtrBase::AddReference( Class *ptr )
{
if( !ptr->SafePtrList )
{
ptr->SafePtrList = this;
LL_Reset( this, next, prev );
}
else
{
LL_Add( ptr->SafePtrList, this, next, prev );
}
}
inline void SafePtrBase::RemoveReference( Class *ptr )
{
if( ptr->SafePtrList == this )
{
if( ptr->SafePtrList->next == this )
{
ptr->SafePtrList = NULL;
}
else
{
ptr->SafePtrList = next;
LL_Remove( this, next, prev );
}
}
else
{
LL_Remove( this, next, prev );
}
}
inline void SafePtrBase::Clear( void )
{
if( ptr )
{
RemoveReference( ptr );
ptr = NULL;
}
}
inline SafePtrBase::SafePtrBase()
{
prev = NULL;
next = NULL;
ptr = NULL;
}
inline SafePtrBase::~SafePtrBase()
{
Clear();
}
inline Class * SafePtrBase::Pointer( void )
{
return ptr;
}
inline void SafePtrBase::InitSafePtr( Class *newptr )
{
if( ptr != newptr )
{
if( ptr )
{
RemoveReference( ptr );
}
ptr = newptr;
if( ptr == NULL )
{
return;
}
AddReference( ptr );
}
}
template<class T>
class SafePtr : public SafePtrBase
{
public:
SafePtr( T* objptr = 0 );
SafePtr( const SafePtr& obj );
SafePtr& operator=( const SafePtr& obj );
SafePtr& operator=( T * const obj );
#ifdef LINUX
friend bool operator==<>( SafePtr<T> a, T *b );
friend bool operator!=<>( SafePtr<T> a, T *b );
friend bool operator==<>( T *a, SafePtr<T> b );
friend bool operator!=<>( T *a, SafePtr<T> b );
friend bool operator==<>( SafePtr<T> a, SafePtr<T> b );
friend bool operator!=<>( SafePtr<T> a, SafePtr<T> b );
#else
// The compiler/linker gets confused when the friend functions definition are not templated
template< class U > friend bool operator==( SafePtr<U> a, U *b );
template< class U > friend bool operator!=( SafePtr<U> a, U *b );
template< class U > friend bool operator==( U *a, SafePtr<U> b );
template< class U > friend bool operator!=( U *a, SafePtr<U> b );
template< class U > friend bool operator==( SafePtr<U> a, SafePtr<U> b );
template< class U > friend bool operator!=( SafePtr<U> a, SafePtr<U> b );
#endif
bool operator !( ) const;
operator T*( ) const;
T* operator->( ) const;
T& operator*( ) const;
};
template<class T>
inline SafePtr<T>::SafePtr( T* objptr )
{
InitSafePtr( ( Class * )objptr );
}
template<class T>
inline SafePtr<T>::SafePtr( const SafePtr& obj )
{
InitSafePtr( obj.ptr );
}
template<class T>
inline SafePtr<T>& SafePtr<T>::operator=( const SafePtr& obj )
{
InitSafePtr( obj.ptr );
return *this;
}
template<class T>
inline SafePtr<T>& SafePtr<T>::operator=( T * const obj )
{
InitSafePtr( obj );
return *this;
}
template<class T>
inline bool operator==( SafePtr<T> a, T *b )
{
return a.ptr == b;
}
template<class T>
inline bool operator!=( SafePtr<T> a, T* b )
{
return a.ptr != b;
}
template<class T>
inline bool operator==( T* a, SafePtr<T> b )
{
return a == b.ptr;
}
template<class T>
inline bool operator!=( T* a, SafePtr<T> b )
{
return a != b.ptr;
}
template<class T>
inline bool operator==( SafePtr<T> a, SafePtr<T> b )
{
return a.ptr == b.ptr;
}
template<class T>
inline bool operator!=( SafePtr<T> a, SafePtr<T> b )
{
return a.ptr != b.ptr;
}
template<class T>
inline bool SafePtr<T>::operator !( ) const
{
return ptr == NULL;
}
template<class T>
inline SafePtr<T>::operator T*( ) const
{
return ( T * )ptr;
}
template<class T>
inline T* SafePtr<T>::operator->( ) const
{
return ( T * )ptr;
}
template<class T>
inline T& SafePtr<T>::operator*( ) const
{
return *( T * )ptr;
}
#endif

1188
code/globalcpp/script.cpp Normal file

File diff suppressed because it is too large Load diff

180
code/globalcpp/script.h Normal file
View file

@ -0,0 +1,180 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// script.h: C++ implementation of tokenization/interpretation.
#ifndef __SCRIPT_H__
#define __SCRIPT_H__
#include "class.h"
#include "vector.h"
#include "str.h"
#include "archive.h"
#define TOKENCOMMENT (';')
#define TOKENCOMMENT2 ('#')
#define TOKENEOL ('\n')
//#define TOKENNULL ('\0')
#define TOKENSPACE (' ')
#define TOKENSPECIAL ('$')
#define MAXTOKEN 256
typedef struct
{
qboolean tokenready;
int offset;
int line;
char token[ MAXTOKEN ];
} scriptmarker_t;
typedef struct
{
//const char *macroName;
//const char *macroText;
str macroName;
str macroText;
} macro;
class Script : public Class
{
protected:
qboolean tokenready;
str filename;
const char *script_p;
const char *end_p;
Container<macro *> macrolist;
int line;
char token[ MAXTOKEN ];
qboolean releaseBuffer;
qboolean hasError;
qboolean AtComment( void );
void CheckOverflow( void );
public:
const char *buffer;
size_t length;
CLASS_PROTOTYPE( Script );
virtual void Archive( Archiver &arc );
~Script();
Script( const char* filename );
Script();
void Close( void );
const char *Filename( void );
int GetLineNumber( void );
void Reset( void );
void MarkPosition( scriptmarker_t *mark );
void RestorePosition( const scriptmarker_t *mark );
qboolean SkipToEOL( void );
void SkipWhiteSpace( qboolean crossline );
void SkipNonToken( qboolean crossline );
qboolean TokenAvailable( qboolean crossline );
qboolean CommentAvailable( qboolean crossline );
void UnGetToken( void );
qboolean AtString( qboolean crossline );
qboolean AtOpenParen( qboolean crossline );
qboolean AtCloseParen( qboolean crossline );
qboolean AtComma( qboolean crossline );
qboolean AtDot( qboolean crossline );
qboolean AtAssignment( qboolean crossline );
const char *GetToken( qboolean crossline );
const char *GetLine( qboolean crossline );
const char *GetRaw( void );
const char *GetString( qboolean crossline );
qboolean GetSpecific( const char *string );
qboolean GetBoolean( qboolean crossline );
int GetInteger( qboolean crossline );
double GetDouble( qboolean crossline );
float GetFloat( qboolean crossline );
Vector GetVector( qboolean crossline );
int LinesInFile( void );
void Parse( const char *data, size_t length, const char *name );
void LoadFile( const char *name );
void LoadFile( const char *name, int length, const char *buf );
const char *Token( void );
void AddMacroDefinition( qboolean crossline );
const char *GetMacroString( const char *theMacroName );
char *EvaluateMacroString( const char *theMacroString );
float EvaluateMacroMath(float value, float newval, char oper);
const char *GetExprToken(const char *ptr, char *token);
const char *GrabNextToken( qboolean crossline );
qboolean isMacro( void );
qboolean EndOfFile();
qboolean isValid( void );
Container<macro *> *GetMacroList() { return &macrolist; }
void AddMacro(const char *name, const char *value);
};
inline void Script::Archive
(
Archiver &arc
)
{
int pos;
arc.ArchiveBoolean( &tokenready );
arc.ArchiveString( &filename );
if ( arc.Loading() )
{
//
// load the file in
//
LoadFile( filename.c_str() );
}
if ( !arc.Loading() )
{
//
// save out current pointer as an offset
//
pos = script_p - buffer;
}
arc.ArchiveInteger( &pos );
if ( arc.Loading() )
{
//
// restore the script pointer
//
script_p = buffer + pos;
}
//const char *end_p;
//Container<macro *> macrolist;
arc.ArchiveInteger( &line );
arc.ArchiveRaw( &token, sizeof( token ) );
//qboolean releaseBuffer;
}
#endif

View file

@ -0,0 +1,73 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// scriptexception.cpp : Script Exception
#include "glb_local.h"
#include "scriptexception.h"
int ScriptException::next_abort = 0;
int ScriptException::next_bIsForAnim = 0;
void ScriptException::CreateException( const char *data )
{
string = data;
bAbort = next_abort;
next_abort = 0;
bIsForAnim = next_bIsForAnim;
next_bIsForAnim = 0;
}
ScriptException::ScriptException( str text )
{
CreateException( text.c_str() );
}
ScriptException::ScriptException( const char *format, ... )
{
va_list va;
char data[4100];
va_start( va, format );
vsprintf( data, format, va);
va_end( va );
CreateException( data );
}
ScriptException::ScriptException( char *text )
{
CreateException( text );
}
void Error( const char * format, ... )
{
va_list va;
char data[4100];
va_start( va, format );
vsprintf( data, format, va);
va_end( va );
throw new ScriptException( ( const char * )data );
}

View file

@ -0,0 +1,54 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// scriptexception.h: Script Exception
#ifndef __EXCEPT_H__
#define __EXCEPT_H__
#include "str.h"
class ScriptException
{
public:
str string;
int bAbort;
int bIsForAnim;
private:
void CreateException( const char *data );
public:
ScriptException( str text );
ScriptException( const char *format, ... );
ScriptException( char *text );
static int next_abort;
static int next_bIsForAnim;
};
void Error( const char * format, ... );
#define ScriptDeprecated( function ) throw ScriptException( function ": DEPRECATED. DON'T USE IT ANYMORE" )
#define ScriptError throw ScriptException
#endif /* __EXCEPT_H__ */

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,587 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// scriptmaster.h: Handle events, parse scripts, spawn at the beginning of the map
#ifndef __SCRIPTMASTER_H__
#define __SCRIPTMASTER_H__
#include "class.h"
#include "listener.h"
#include "scriptvm.h"
#define MAX_COMMANDS 20
#define MAX_EXECUTION_TIME 3000
void Showmenu( str name, qboolean bForce );
void Hidemenu( str name, qboolean bForce );
class con_timer : public Class
{
public:
class Element
{
public:
Class *obj;
int inttime;
};
private:
Container< con_timer::Element > m_Elements;
bool m_bDirty;
int m_inttime;
public:
con_timer();
void AddElement( Class *e, int inttime );
void RemoveElement( Class *e );
Class *GetNextElement( int& foundTime );
void SetDirty( void ) { m_bDirty = true; };
bool IsDirty( void ) { return m_bDirty; };
void SetTime( int inttime ) { m_inttime = inttime; };
static void ArchiveElement( Archiver& arc, Element *e );
virtual void Archive( Archiver& arc );
};
#define MAX_VAR_STACK 1024
#define MAX_FASTEVENT 10
class ScriptMaster : public Listener
{
public:
// VM recursions
int stackCount;
// Global stack (not needed anymore)
#if 0
ScriptVariable avar_Stack[ MAX_VAR_STACK+1 ]; // Global variables stack
Event fastEvent[ MAX_FASTEVENT+1 ]; // Event that will be executed
ScriptVariable *pTop; // Top variable on the stack
#endif
// Command variables
unsigned int cmdCount; // cmd count
int cmdTime; // Elapsed VM execution time
int maxTime; // Maximum VM execution time
// Thread variables
SafePtr<ScriptThread> m_PreviousThread; // parm.previousthread
SafePtr<ScriptThread> m_CurrentThread; // current running thread
con_map< const_str, GameScript * > m_GameScripts; // compiled gamescripts
// Miscellaneous
Container< str > m_menus; // Script menus
con_timer timerList; // waiting threads list
con_arrayset< str, str > StringDict; // const strings (improve performance)
int iPaused; // num times paused
// Context switch variables
bool m_bAllowContextSwitch;
Container< SafePtr< ScriptThread > > m_contextSwitches; // Threads to be prepared for context switching
protected:
static const char *ConstStrings[];
private:
GameScript *GetGameScriptInternal( str& filename );
void InitConstStrings( void );
public:
CLASS_PROTOTYPE( ScriptMaster );
virtual ~ScriptMaster();
virtual void Archive( Archiver &arc );
void ArchiveString( Archiver& arc, const_str& s );
void AddContextSwitch( ScriptThread *thread );
const_str AddString( const char *s );
const_str AddString( str& s );
const_str GetString( const char *s );
const_str GetString( str s );
str& GetString( const_str s );
void AddTiming( ScriptThread *thread, float time );
void RemoveTiming( ScriptThread *thread );
void AddMenu( str name );
void RemoveMenu( str name );
void LoadMenus( void );
ScriptThread *CreateScriptThread( GameScript *scr, Listener *self, const_str label );
ScriptThread *CreateScriptThread( GameScript *scr, Listener *self, str label );
ScriptThread *CreateScriptThread( ScriptClass *scriptClass, const_str label );
ScriptThread *CreateScriptThread( ScriptClass *scriptClass, str label );
ScriptThread *CreateScriptThread( ScriptClass *scriptClass, unsigned char *m_pCodePos );
ScriptThread *CreateThread( GameScript *scr, str label, Listener *self = NULL );
ScriptThread *CreateThread( str filename, str label, Listener *self = NULL );
ScriptClass *CurrentScriptClass( void );
ScriptThread *CurrentThread( void );
ScriptThread *PreviousThread( void );
void ExecuteThread( GameScript *scr, str label = "" );
void ExecuteThread( str filename, str label = "" );
void ExecuteThread( GameScript *scr, str label, Event &parms );
void ExecuteThread( str filename, str label, Event &parms );
GameScript *GetTempScript( const char *data );
GameScript *GetGameScript( str filename, qboolean recompile = false );
GameScript *GetGameScript( const_str filename, qboolean recompile = false );
GameScript *GetScript( str filename, qboolean recompile = false );
GameScript *GetScript( const_str filename, qboolean recompile = false );
void CloseGameScript();
void Reset( qboolean samemap = false );
void Init();
void ExecuteRunning();
void SetTime( int time );
void PrintStatus( void );
void PrintThread( int iThreadNum );
//
// Events
//
void RegisterAliasInternal( Event *ev, bool bCache = false );
void RegisterAlias( Event *ev );
void RegisterAliasAndCache( Event *ev );
void Cache( Event *ev );
};
class ScriptThread : public Listener
{
friend class Flag;
friend class EndOn;
friend class Listener;
friend class ScriptMaster;
private:
ScriptVM *m_ScriptVM;
SafePtr< ScriptThread > m_WaitingContext;
private:
void ScriptExecuteInternal( ScriptVariable *data = NULL, int dataSize = 0 );
public:
CLASS_PROTOTYPE( ScriptThread );
void *operator new( size_t size );
void operator delete( void *ptr );
virtual void Archive( Archiver &arc );
void ArchiveInternal( Archiver& arc );
virtual void StartedWaitFor( void );
virtual void StoppedNotify( void );
virtual void StoppedWaitFor( const_str name, bool bDeleting );
ScriptThread();
ScriptThread( ScriptClass *scriptClass, unsigned char *pCodePos );
virtual ~ScriptThread();
void Execute( Event &ev );
void Execute( Event *ev = NULL );
void DelayExecute( Event& ev );
void DelayExecute( Event *ev = NULL );
void AllowContextSwitch( bool allow = true );
ScriptClass *GetScriptClass( void );
int GetThreadState( void );
ScriptThread *GetWaitingContext( void );
void SetWaitingContext( ScriptThread *thread );
void HandleContextSwitch( ScriptThread *childThread );
void Pause( void );
void ScriptExecute( ScriptVariable *data, int dataSize, ScriptVariable &returnValue );
void Stop( void );
void Wait( float time );
void CanSwitchTeams( Event *ev );
void CharToInt( Event *ev );
void Conprintf( Event *ev );
void CreateHUD( Event *ev );
void Earthquake( Event *ev );
void FadeSound( Event *ev );
void FileOpen( Event *ev );
void FileWrite( Event *ev );
void FileRead( Event *ev );
void FileClose( Event *ev );
void FileEof( Event *ev );
void FileSeek( Event *ev );
void FileTell( Event *ev );
void FileRewind( Event *ev );
void FilePutc( Event *ev );
void FilePuts( Event *ev );
void FileGetc( Event *ev );
void FileGets( Event *ev );
void FileError( Event *ev );
void FileFlush( Event *ev );
void FileExists( Event *ev );
void FileReadAll( Event *ev );
void FileSaveAll( Event *ev );
void FileRemove( Event *ev );
void FileRename( Event *ev );
void FileCopy( Event *ev );
void FileReadPak( Event *ev );
void FileList( Event *ev );
void FileNewDirectory( Event *ev );
void FileRemoveDirectory( Event *ev );
void FlagClear( Event *ev );
void FlagInit( Event *ev );
void FlagSet( Event *ev );
void FlagWait( Event *ev );
void Lock( Event *ev );
void UnLock( Event *ev );
void GetAreaEntities( Event *ev );
void GetArrayKeys( Event *ev );
void GetArrayValues( Event *ev );
void GetEntArray( Event *ev );
void GetPlayerNetname( Event *ev );
void GetPlayerIP( Event *ev );
void GetPlayerPing( Event *ev );
void GetPlayerClientNum( Event *ev );
void GetTime( Event *ev );
void GetDate( Event *ev );
void GetTimeZone( Event *ev );
void PregMatch( Event *ev );
void EventHudDraw3d( Event *ev );
void EventHudDrawTimer( Event *ev );
void EventHudDrawShader( Event *ev );
void EventHudDrawAlign( Event *ev );
void EventHudDrawRect( Event *ev );
void EventHudDrawVirtualSize( Event *ev );
void EventHudDrawColor( Event *ev );
void EventHudDrawAlpha( Event *ev );
void EventHudDrawString( Event *ev );
void EventHudDrawFont( Event *ev );
void EventIHudDraw3d( Event *ev );
void EventIHudDrawShader( Event *ev );
void EventIHudDrawAlign( Event *ev );
void EventIHudDrawRect( Event *ev );
void EventIHudDrawVirtualSize( Event *ev );
void EventIHudDrawColor( Event *ev );
void EventIHudDrawAlpha( Event *ev );
void EventIHudDrawString( Event *ev );
void EventIHudDrawFont( Event *ev );
void EventIHudDrawTimer( Event *ev );
void EventIsArray( Event *ev );
void EventIsDefined( Event *ev );
void EventIsOnGround( Event *ev );
void EventIsOutOfBounds( Event *ev );
void GetEntity( Event *ev );
void MathCos( Event *ev );
void MathSin( Event *ev );
void MathTan( Event *ev );
void MathACos( Event *ev );
void MathASin( Event *ev );
void MathATan( Event *ev );
void MathATan2( Event *ev );
void MathCosH( Event *ev );
void MathSinH( Event *ev );
void MathTanH( Event *ev );
void MathExp( Event *ev );
void MathFrexp( Event *ev );
void MathLdexp( Event *ev );
void MathLog( Event *ev );
void MathLog10( Event *ev );
void MathModf( Event *ev );
void MathPow( Event *ev );
void MathSqrt( Event *ev );
void MathCeil( Event *ev );
void MathFloor( Event *ev );
void MathFmod( Event *ev );
void StringBytesCopy( Event *ev );
void Md5File( Event *ev );
void Md5String( Event *ev );
void RegisterEvent( Event *ev );
void RestoreSound( Event *ev );
void RemoveArchivedClass( Event *ev );
void ServerStufftext( Event *ev );
void SetTimer( Event *ev );
void TeamGetScore( Event *ev );
void TeamSetScore( Event *ev );
void TeamSwitchDelay( Event *ev );
void TraceDetails( Event *ev );
void TypeOfVariable( Event *ev );
void UnregisterEvent( Event *ev );
void VisionGetNaked( Event *ev );
void VisionSetNaked( Event *ev );
void CancelWaiting( Event *ev );
void Abs( Event *ev );
void AddObjective( Event *ev );
void AddObjective( int index, int status, str text, Vector location );
void ClearObjectiveLocation( Event *ev );
void ClearObjectiveLocation( void );
void SetObjectiveLocation( Event *ev );
void SetObjectiveLocation( Vector vLocation );
void SetCurrentObjective( Event *ev );
void SetCurrentObjective( int iObjective );
void AllAIOff( Event *ev );
void AllAIOn( Event *ev );
void EventTeamWin( Event *ev );
void Angles_PointAt( Event *ev );
void Angles_ToForward( Event *ev );
void Angles_ToLeft( Event *ev );
void Angles_ToUp( Event *ev );
void Assert( Event *ev );
void Cache( Event *ev );
void CastBoolean( Event *ev );
void CastEntity( Event *ev );
void CastFloat( Event *ev );
void CastInt( Event *ev );
void CastString( Event *ev );
void CreateReturnThread( Event *ev );
void CreateThread( Event *ev );
void ExecuteReturnScript( Event *ev );
void ExecuteScript( Event *ev );
void EventCreateListener( Event *ev );
void EventDelayThrow( Event *ev );
void EventEnd( Event *ev );
void EventTimeout( Event *ev );
void EventError( Event *ev );
void EventGoto( Event *ev );
void EventRegisterCommand( Event *ev );
void EventGetCvar( Event *ev );
void EventSetCvar( Event *ev );
void EventSightTrace( Event *ev );
void EventTrace( Event *ev );
void EventThrow( Event *ev );
void EventWait( Event *ev );
void EventWaitFrame( Event *ev );
void EventIsAlive( Event *ev );
void EventEarthquake( Event *ev );
void MapEvent( Event *ev );
void CueCamera( Event *ev );
void CuePlayer( Event *ev );
void FreezePlayer( Event *ev );
void ReleasePlayer( Event *ev );
void EventDrawHud( Event *ev );
void EventRadiusDamage( Event *ev );
void GetSelf( Event *ev );
void IPrintln( Event *ev );
void IPrintln_NoLoc( Event *ev );
void IPrintlnBold( Event *ev );
void IPrintlnBold_NoLoc( Event *ev );
void Println( Event *ev );
void Print( Event *ev );
void MPrintln( Event *ev );
void MPrint( Event *ev );
void EventPrint3D( Event *ev );
void EventBspTransition( Event *ev );
void EventLevelTransition( Event *ev );
void EventMissionTransition( Event *ev );
void EventGetBoundKey1( Event *ev );
void EventGetBoundKey2( Event *ev );
void EventLocConvertString( Event *ev );
void RandomFloat( Event *ev );
void RandomInt( Event *ev );
void Spawn( Event *ev );
Listener *SpawnInternal( Event *ev );
void SpawnReturn( Event *ev );
void ForceMusicEvent( Event *ev );
void SoundtrackEvent( Event *ev );
void RestoreSoundtrackEvent( Event *ev );
void EventVectorAdd( Event *ev );
void EventVectorCloser( Event *ev );
void EventVectorCross( Event *ev );
void EventVectorDot( Event *ev );
void EventVectorLength( Event *ev );
void EventVectorNormalize( Event *ev );
void EventVectorScale( Event *ev );
void EventVectorSubtract( Event *ev );
void EventVectorToAngles( Event *ev );
void EventVectorWithin( Event *ev );
void FadeIn( Event *ev );
void FadeOut( Event *ev );
void ClearFade( Event *ev );
void Letterbox( Event *ev );
void ClearLetterbox( Event *ev );
void MusicEvent( Event *ev );
void MusicVolumeEvent( Event *ev );
void RestoreMusicVolumeEvent( Event *ev );
void SetCinematic( Event *ev );
void SetNonCinematic( Event *ev );
void StuffCommand( Event *ev );
void KillEnt( Event *ev );
void RemoveEnt( Event *ev );
void KillClass( Event *ev );
void RemoveClass( Event *ev );
void CameraCommand( Event *ev );
void SetLightStyle( Event *ev );
void CenterPrint( Event *ev );
void LocationPrint( Event *ev );
void TriggerEvent( Event *ev );
void ServerEvent( Event *ev );
void MissionFailed( Event *ev );
};
extern qboolean disable_team_change;
extern qboolean disable_team_spectate;
extern str vision_current;
extern Event EV_ScriptThread_Trace;
extern Event EV_ScriptThread_SightTrace;
extern Event EV_ScriptThread_VisionSetNaked;
extern Event EV_ScriptThread_CancelWaiting;
extern con_set< str, ScriptThreadLabel > m_scriptCmds;
extern ScriptMaster Director;
class LightStyleClass : public Class
{
private:
CLASS_PROTOTYPE( LightStyleClass );
str styles[ MAX_LIGHTSTYLES ];
public:
void SetLightStyle( int index, str style );
void Archive( Archiver &arc );
};
extern LightStyleClass lightStyles;
typedef enum scriptedEvType_e
{
SE_DEFAULT,
SE_CONNECTED,
SE_DISCONNECTED,
SE_SPAWN,
SE_DAMAGE,
SE_KILL,
SE_KEYPRESS,
SE_INTERMISSION,
SE_SERVERCOMMAND,
SE_CHANGETEAM,
SE_MAX
} scriptedEvType_t;
class ScriptEvent : public Class
{
public:
ScriptThreadLabel label;
public:
CLASS_PROTOTYPE( ScriptEvent );
virtual void Archive( Archiver& arc );
bool IsRegistered( void );
void Trigger( Event *ev );
};
inline void ScriptEvent::Archive
(
Archiver& arc
)
{
label.Archive( arc );
}
inline bool ScriptEvent::IsRegistered
(
void
)
{
return label.IsSet();
}
inline void ScriptEvent::Trigger
(
Event *ev
)
{
if( label.IsSet() )
{
label.Execute( NULL, ev );
}
delete ev;
}
extern ScriptEvent scriptedEvents[];
typedef struct mutex_thread_list_s {
SafePtr< ScriptThread > m_pThread;
struct mutex_thread_list_s *next;
struct mutex_thread_list_s *prev;
} mutex_thread_list_t;
class ScriptMutex : public Listener {
public:
SafePtr< ScriptThread > m_pLockThread;
int m_iLockCount;
mutex_thread_list_t m_list;
private:
void setOwner( ScriptThread *pThread );
void Lock( mutex_thread_list_t *pList );
public:
CLASS_PROTOTYPE( ScriptMutex );
ScriptMutex();
~ScriptMutex();
virtual void StoppedNotify( void );
void Lock( void );
void Unlock( void );
};
#endif /* scriptmaster.h */

View file

@ -0,0 +1,236 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// scriptopcodes.cpp
#include "glb_local.h"
#include "scriptopcodes.h"
static opcode_t OpcodeInfo[] =
{
{ "OPCODE_EOF", 0, 0, 0 },
{ "OPCODE_BOOL_JUMP_FALSE4", 5, -1, 0 },
{ "OPCODE_BOOL_JUMP_TRUE4", 5, -1, 0 },
{ "OPCODE_VAR_JUMP_FALSE4", 5, -1, 0 },
{ "OPCODE_VAR_JUMP_TRUE4", 5, -1, 0 },
{ "OPCODE_BOOL_LOGICAL_AND", 5, -1, 0 },
{ "OPCODE_BOOL_LOGICAL_OR", 5, -1, 0 },
{ "OPCODE_VAR_LOGICAL_AND", 5, -1, 0 },
{ "OPCODE_VAR_LOGICAL_OR", 5, -1, 0 },
{ "OPCODE_BOOL_TO_VAR", 0, 0, 0 },
{ "OPCODE_JUMP4", 1 + sizeof( unsigned int ), 0, 0 },
{ "OPCODE_JUMP_BACK4", 1 + sizeof( unsigned int ), 0, 0 },
{ "OPCODE_STORE_INT0", 1, 1, 0 },
{ "OPCODE_STORE_INT1", 1 + sizeof( char ), 1, 0 },
{ "OPCODE_STORE_INT2", 1 + sizeof( short ), 1, 0 },
{ "OPCODE_STORE_INT3", 1 + sizeof( short3 ), 1, 0 },
{ "OPCODE_STORE_INT4", 1 + sizeof( int ), 1, 0 },
{ "OPCODE_BOOL_STORE_FALSE", 1, 1, 0 },
{ "OPCODE_BOOL_STORE_TRUE", 1, 1, 0 },
{ "OPCODE_STORE_STRING", 1 + sizeof( unsigned int ), 1, 0 },
{ "OPCODE_STORE_FLOAT", 1 + sizeof( float ), 1, 0 },
{ "OPCODE_STORE_VECTOR", 1 + sizeof( Vector ), 1, 0 },
{ "OPCODE_CALC_VECTOR", 1, -2, 0 },
{ "OPCODE_STORE_NULL", 1, 1, 0 },
{ "OPCODE_STORE_NIL", 1, 1, 0 },
{ "OPCODE_EXEC_CMD0", 5, 0, 1 },
{ "OPCODE_EXEC_CMD1", 5, -1, 1 },
{ "OPCODE_EXEC_CMD2", 5, -2, 1 },
{ "OPCODE_EXEC_CMD3", 5, -3, 1 },
{ "OPCODE_EXEC_CMD4", 5, -4, 1 },
{ "OPCODE_EXEC_CMD5", 5, -5, 1 },
{ "OPCODE_EXEC_CMD_COUNT1", 6, -128, 1 },
{ "OPCODE_EXEC_CMD_METHOD0", 5, -1, 1 },
{ "OPCODE_EXEC_CMD_METHOD1", 5, -2, 1 },
{ "OPCODE_EXEC_CMD_METHOD2", 5, -3, 1 },
{ "OPCODE_EXEC_CMD_METHOD3", 5, -4, 1 },
{ "OPCODE_EXEC_CMD_METHOD4", 5, -5, 1 },
{ "OPCODE_EXEC_CMD_METHOD5", 5, -6, 1 },
{ "OPCODE_EXEC_CMD_METHOD_COUNT1", 6, -128, 1 },
{ "OPCODE_EXEC_METHOD0", 5, 0, 1 },
{ "OPCODE_EXEC_METHOD1", 5, -1, 1 },
{ "OPCODE_EXEC_METHOD2", 5, -2, 1 },
{ "OPCODE_EXEC_METHOD3", 5, -3, 1 },
{ "OPCODE_EXEC_METHOD4", 5, -4, 1 },
{ "OPCODE_EXEC_METHOD5", 5, -5, 1 },
{ "OPCODE_EXEC_METHOD_COUNT1", 6, -128, 1 },
{ "OPCODE_LOAD_GAME_VAR", 5, -1, 0 },
{ "OPCODE_LOAD_LEVEL_VAR", 5, -1, 0 },
{ "OPCODE_LOAD_LOCAL_VAR", 5, -1, 0 },
{ "OPCODE_LOAD_PARM_VAR", 5, -1, 0 },
{ "OPCODE_LOAD_SELF_VAR", 5, -1, 0 },
{ "OPCODE_LOAD_GROUP_VAR", 5, -1, 0 },
{ "OPCODE_LOAD_OWNER_VAR", 5, -1, 0 },
{ "OPCODE_LOAD_FIELD_VAR", 5, -2, 0 },
{ "OPCODE_LOAD_ARRAY_VAR", 1, -3, 0 },
{ "OPCODE_LOAD_CONST_ARRAY1", 2, -128, 0 },
{ "OPCODE_STORE_FIELD_REF", 5, 0, 0 },
{ "OPCODE_STORE_ARRAY_REF", 1, -1, 0 },
{ "OPCODE_MARK_STACK_POS", 1, 0, 0 },
{ "OPCODE_STORE_PARAM", 1, 1, 0 },
{ "OPCODE_RESTORE_STACK_POS", 1, 0, 0 },
{ "OPCODE_LOAD_STORE_GAME_VAR", 5, 0, 0 },
{ "OPCODE_LOAD_STORE_LEVEL_VAR", 5, 0, 0 },
{ "OPCODE_LOAD_STORE_LOCAL_VAR", 5, 0, 0 },
{ "OPCODE_LOAD_STORE_PARM_VAR", 5, 0, 0 },
{ "OPCODE_LOAD_STORE_SELF_VAR", 5, 0, 0 },
{ "OPCODE_LOAD_STORE_GROUP_VAR", 5, 0, 0 },
{ "OPCODE_LOAD_STORE_OWNER_VAR", 5, 0, 0 },
{ "OPCODE_STORE_GAME_VAR", 5, 1, 0 },
{ "OPCODE_STORE_LEVEL_VAR", 5, 1, 0 },
{ "OPCODE_STORE_LOCAL_VAR", 5, 1, 0 },
{ "OPCODE_STORE_PARM_VAR", 5, 1, 0 },
{ "OPCODE_STORE_SELF_VAR", 5, 1, 0 },
{ "OPCODE_STORE_GROUP_VAR", 5, 1, 0 },
{ "OPCODE_STORE_OWNER_VAR", 5, 1, 0 },
{ "OPCODE_STORE_FIELD", 5, 0, 1 },
{ "OPCODE_STORE_ARRAY", 1, -1, 0 },
{ "OPCODE_STORE_GAME", 1, 1, 0 },
{ "OPCODE_STORE_LEVEL", 1, 1, 0 },
{ "OPCODE_STORE_LOCAL", 1, 1, 0 },
{ "OPCODE_STORE_PARM", 1, 1, 0 },
{ "OPCODE_STORE_SELF", 1, 1, 0 },
{ "OPCODE_STORE_GROUP", 1, 1, 0 },
{ "OPCODE_STORE_OWNER", 1, 1, 0 },
{ "OPCODE_BIN_BITWISE_AND", 1, -1, 0 },
{ "OPCODE_BIN_BITWISE_OR", 1, -1, 0 },
{ "OPCODE_BIN_BITWISE_EXCL_OR", 1, -1, 0 },
{ "OPCODE_BIN_EQUALITY", 1, -1, 0 },
{ "OPCODE_BIN_INEQUALITY", 1, -1, 0 },
{ "OPCODE_BIN_LESS_THAN", 1, -1, 0 },
{ "OPCODE_BIN_GREATER_THAN", 1, -1, 0 },
{ "OPCODE_BIN_LESS_THAN_OR_EQUAL", 1, -1, 0 },
{ "OPCODE_BIN_GREATER_THAN_OR_EQUAL", 1, -1, 0 },
{ "OPCODE_BIN_PLUS", 1, -1, 0 },
{ "OPCODE_BIN_MINUS", 1, -1, 0 },
{ "OPCODE_BIN_MULTIPLY", 1, -1, 0 },
{ "OPCODE_BIN_DIVIDE", 1, -1, 0 },
{ "OPCODE_BIN_PERCENTAGE", 1, -1, 0 },
{ "OPCODE_UN_MINUS", 1, 0, 0 },
{ "OPCODE_UN_COMPLEMENT", 1, 0, 0 },
{ "OPCODE_UN_TARGETNAME", 1, 0, 0 },
{ "OPCODE_BOOL_UN_NOT", 1, 0, 0 },
{ "OPCODE_VAR_UN_NOT", 1, 0, 0 },
{ "OPCODE_UN_CAST_BOOLEAN", 1, 0, 0 },
{ "OPCODE_UN_INC", 1, 0, 0 },
{ "OPCODE_UN_DEC", 1, 0, 0 },
{ "OPCODE_UN_SIZE", 1, 0, 0 },
{ "OPCODE_SWITCH", 5, -1, 0 },
{ "OPCODE_FUNC", 11, -128, 1 },
{ "OPCODE_NOP", 1, 0, 0 },
{ "OPCODE_BIN_SHIFT_LEFT", 1, -1, 0 },
{ "OPCODE_BIN_SHIFT_RIGHT", 1, -1, 0 },
{ "OPCODE_END", 1, -1, 0 },
{ "OPCODE_RETURN", 1, -1, 0 },
};
static const char *aszVarGroupNames[] =
{
"game",
"level",
"local",
"parm",
"self"
};
/*
====================
VarGroupName
====================
*/
const char *VarGroupName( int iVarGroup )
{
return aszVarGroupNames[ iVarGroup ];
}
/*
====================
OpcodeName
====================
*/
const char *OpcodeName( int opcode )
{
return OpcodeInfo[ opcode ].opcodename;
}
/*
====================
OpcodeLength
====================
*/
int OpcodeLength( int opcode )
{
return OpcodeInfo[ opcode ].opcodelength;
}
/*
====================
OpcodeVarStackOffset
====================
*/
int OpcodeVarStackOffset( int opcode )
{
return OpcodeInfo[ opcode ].opcodestackoffset;
}
/*
====================
SetOpcodeVarStackOffset
====================
*/
void SetOpcodeVarStackOffset( int opcode, int iVarStackOffset )
{
OpcodeInfo[ opcode ].opcodestackoffset = iVarStackOffset;
}
/*
====================
IsExternalOpcode
====================
*/
bool IsExternalOpcode( int opcode )
{
return OpcodeInfo[ opcode ].isexternal ? true : false;
}

View file

@ -0,0 +1,186 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// scriptopcodes.h
typedef struct {
const char *opcodename;
int opcodelength;
short opcodestackoffset;
char isexternal;
} opcode_t;
typedef struct {
unsigned char opcode;
char VarStackOffset;
} opcode_info_t;
typedef enum
{
OP_DONE,
OP_BOOL_JUMP_FALSE4,
OP_BOOL_JUMP_TRUE4,
OP_VAR_JUMP_FALSE4,
OP_VAR_JUMP_TRUE4,
OP_BOOL_LOGICAL_AND,
OP_BOOL_LOGICAL_OR,
OP_VAR_LOGICAL_AND,
OP_VAR_LOGICAL_OR,
OP_BOOL_TO_VAR,
OP_JUMP4,
OP_JUMP_BACK4,
OP_STORE_INT0,
OP_STORE_INT1,
OP_STORE_INT2,
OP_STORE_INT3,
OP_STORE_INT4,
OP_BOOL_STORE_FALSE,
OP_BOOL_STORE_TRUE,
OP_STORE_STRING,
OP_STORE_FLOAT,
OP_STORE_VECTOR,
OP_CALC_VECTOR,
OP_STORE_NULL,
OP_STORE_NIL,
OP_EXEC_CMD0, // exec normal
OP_EXEC_CMD1,
OP_EXEC_CMD2,
OP_EXEC_CMD3,
OP_EXEC_CMD4,
OP_EXEC_CMD5,
OP_EXEC_CMD_COUNT1,
OP_EXEC_CMD_METHOD0, // exec from listener
OP_EXEC_CMD_METHOD1,
OP_EXEC_CMD_METHOD2,
OP_EXEC_CMD_METHOD3,
OP_EXEC_CMD_METHOD4,
OP_EXEC_CMD_METHOD5,
OP_EXEC_CMD_METHOD_COUNT1,
OP_EXEC_METHOD0, // exec from listener with return
OP_EXEC_METHOD1,
OP_EXEC_METHOD2,
OP_EXEC_METHOD3,
OP_EXEC_METHOD4,
OP_EXEC_METHOD5,
OP_EXEC_METHOD_COUNT1,
OP_LOAD_GAME_VAR,
OP_LOAD_LEVEL_VAR,
OP_LOAD_LOCAL_VAR,
OP_LOAD_PARM_VAR,
OP_LOAD_SELF_VAR,
OP_LOAD_GROUP_VAR,
OP_LOAD_OWNER_VAR,
OP_LOAD_FIELD_VAR,
OP_LOAD_ARRAY_VAR,
OP_LOAD_CONST_ARRAY1,
OP_STORE_FIELD_REF,
OP_STORE_ARRAY_REF,
OP_MARK_STACK_POS,
OP_STORE_PARAM,
OP_RESTORE_STACK_POS,
OP_LOAD_STORE_GAME_VAR,
OP_LOAD_STORE_LEVEL_VAR,
OP_LOAD_STORE_LOCAL_VAR,
OP_LOAD_STORE_PARM_VAR,
OP_LOAD_STORE_SELF_VAR,
OP_LOAD_STORE_GROUP_VAR,
OP_LOAD_STORE_OWNER_VAR,
OP_STORE_GAME_VAR,
OP_STORE_LEVEL_VAR,
OP_STORE_LOCAL_VAR,
OP_STORE_PARM_VAR,
OP_STORE_SELF_VAR,
OP_STORE_GROUP_VAR,
OP_STORE_OWNER_VAR,
OP_STORE_FIELD,
OP_STORE_ARRAY,
OP_STORE_GAME,
OP_STORE_LEVEL,
OP_STORE_LOCAL,
OP_STORE_PARM,
OP_STORE_SELF,
OP_STORE_GROUP,
OP_STORE_OWNER,
OP_BIN_BITWISE_AND,
OP_BIN_BITWISE_OR,
OP_BIN_BITWISE_EXCL_OR,
OP_BIN_EQUALITY,
OP_BIN_INEQUALITY,
OP_BIN_LESS_THAN,
OP_BIN_GREATER_THAN,
OP_BIN_LESS_THAN_OR_EQUAL,
OP_BIN_GREATER_THAN_OR_EQUAL,
OP_BIN_PLUS,
OP_BIN_MINUS,
OP_BIN_MULTIPLY,
OP_BIN_DIVIDE,
OP_BIN_PERCENTAGE,
OP_UN_MINUS,
OP_UN_COMPLEMENT,
OP_UN_TARGETNAME,
OP_BOOL_UN_NOT,
OP_VAR_UN_NOT,
OP_UN_CAST_BOOLEAN,
OP_UN_INC,
OP_UN_DEC,
OP_UN_SIZE,
OP_SWITCH,
OP_FUNC,
OP_NOP,
OP_BIN_SHIFT_LEFT,
OP_BIN_SHIFT_RIGHT,
OP_END,
OP_RETURN,
OP_PREVIOUS,
OP_MAX = OP_PREVIOUS
} opcode_e;
const char *VarGroupName( int iVarGroup );
const char *OpcodeName( int opcode );
int OpcodeLength( int opcode );
int OpcodeVarStackOffset( int opcode );
void SetOpcodeVarStackOffset( int opcode, int iVarStackOffset );
bool IsExternalOpcode( int opcode );

View file

@ -0,0 +1,275 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// scripttimer.cpp: Scripted Timer & Fader
//
#include "glb_local.h"
#include "scripttimer.h"
#include "level.h"
#include "archive.h"
Event EV_ScriptTimer_Think
(
"scripttimer_think",
EV_CODEONLY,
NULL,
NULL,
"Internal event",
EV_NORMAL
);
Container< ScriptTimer * > m_scriptTimers;
/*void ScriptTimer::HandleTimer( float frametime )
{
ScriptTimer *timer;
for( int i = 0; i < m_scriptTimers.NumObjects(); i++ )
{
timer = m_scriptTimers[ i ];
if( timer->isEnabled() && timer->GetTime() > 0.0f ) {
timer->Think( frametime );
}
}
}*/
ScriptTimer::ScriptTimer( timertype_e type )
{
Reset();
bEnabled = false;
setType( type );
m_scriptTimers.AddObject( this );
}
ScriptTimer::~ScriptTimer()
{
Disable();
if( m_scriptTimers.IndexOfObject( this ) )
{
m_scriptTimers.RemoveObject( this );
}
}
void ScriptTimer::Archive( Archiver &arc )
{
Listener::Archive( arc );
#ifdef CGAME_DLL
arc.ArchiveFloat( &targetTime );
arc.ArchiveFloat( &currentTime );
arc.ArchiveFloat( &realTime );
arc.ArchiveFloat( &glideRatio );
arc.ArchiveInteger( ( int * )&timerType );
arc.ArchiveBool( &bEnabled );
if( arc.Loading() && bEnabled ) {
Enable();
}
#endif
}
void ScriptTimer::GlideRefresh()
{
if( timerType != TIMER_GLIDE ) {
return;
}
if( targetTime <= 0.0f ){
return;
}
float r = realTime / ( targetTime * 0.5f );
if( r > 1.0f )
{
glideRatio = 2.0f - 2.0f * ( r - 1.0f );
if( glideRatio < 0.0f ) {
glideRatio = 0.0f;
}
}
else
{
glideRatio = 2.0f * r;
if( glideRatio > 2.0f ) {
glideRatio = 2.0f;
}
}
}
void ScriptTimer::Think( Event *ev )
{
if( !bEnabled ) {
return;
}
#ifdef CGAME_DLL
float frametime = ( float )cg->frametime;
#else
float frametime = level.frametime;
#endif
GlideRefresh();
if( currentTime < targetTime )
{
realTime += frametime;
if( timerType == TIMER_GLIDE ) {
currentTime += frametime * glideRatio;
} else {
currentTime += frametime;
}
}
else
{
currentTime = targetTime;
realTime = targetTime;
bEnabled = false;
CancelEventsOfType( &EV_ScriptTimer_Think );
return;
}
CancelEventsOfType( &EV_ScriptTimer_Think );
PostEvent( EV_ScriptTimer_Think, level.frametime );
}
void ScriptTimer::Disable()
{
bEnabled = false;
CancelEventsOfType( &EV_ScriptTimer_Think );
}
void ScriptTimer::Enable()
{
bEnabled = true;
CancelEventsOfType( &EV_ScriptTimer_Think );
Event *ev = new Event( &EV_ScriptTimer_Think );
ProcessEvent( ev );
}
qboolean ScriptTimer::Done()
{
return ( currentTime >= targetTime );
}
float ScriptTimer::GetCurrentTime()
{
return realTime;
}
float ScriptTimer::GetRatio()
{
float ratio;
if( targetTime <= 0.0f ) {
return 1.0f;
}
ratio = ( currentTime / targetTime );
// ratio must not go below 0.0 and above 1.0
return ( ratio < 0.0f ? 0.0f : ratio > 1.0f ? 1.0f : ratio );
}
float ScriptTimer::GetTime()
{
return targetTime;
}
float ScriptTimer::LerpValue( float start, float end )
{
return start + ( end - start ) * GetRatio();
}
Vector ScriptTimer::LerpValue( Vector start, Vector end )
{
return start + ( end - start ) * GetRatio();
}
void ScriptTimer::Reset()
{
currentTime = 0.f;
realTime = 0.f;
glideRatio = 0.f;
}
void ScriptTimer::SetCurrentTime( float time )
{
realTime = time * 1000.0f;
if( timerType == TIMER_GLIDE )
{
GlideRefresh();
currentTime = time * 1000.0f * glideRatio;
}
else
{
currentTime = time * 1000.0f;
}
}
void ScriptTimer::SetPhase( float phase )
{
float t = targetTime * ( phase / 2.0f ) / 1000.0f;
SetCurrentTime( t );
}
void ScriptTimer::SetTime( float time )
{
Reset();
targetTime = time * 1000.0f;
}
bool ScriptTimer::isEnabled()
{
return bEnabled;
}
void ScriptTimer::setType( timertype_e type )
{
timerType = type;
}
CLASS_DECLARATION( Listener, ScriptTimer, NULL )
{
{ &EV_ScriptTimer_Think, &ScriptTimer::Think },
{ NULL, NULL }
};

View file

@ -0,0 +1,83 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// scripttimer.cpp: Scripted Timer & Fader
//
#ifndef __SCRIPTTIMER_H__
#define __SCRIPTTIMER_H__
#include "listener.h"
typedef enum timertype_s {
TIMER_NORMAL,
TIMER_GLIDE
} timertype_e;
class ScriptTimer : public Listener
{
private:
float targetTime;
float currentTime;
float realTime;
float glideRatio;
timertype_e timerType;
bool bEnabled;
private:
void GlideRefresh();
public:
CLASS_PROTOTYPE( ScriptTimer );
ScriptTimer( timertype_e type = TIMER_NORMAL );
virtual ~ScriptTimer();
virtual void Archive( Archiver &arc );
void Think( Event *ev );
void Disable();
void Enable();
qboolean Done();
float GetCurrentTime();
float GetRatio();
float GetTime();
float LerpValue( float start, float end );
Vector LerpValue( Vector start, Vector end );
void Reset();
void SetCurrentTime( float time );
void SetPhase( float phase );
void SetTime( float time );
bool isEnabled();
void setType( timertype_e type );
};
#endif /* __SCRIPTTIMER_H__ */

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,306 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// scriptvariable.h: Dynamic variables for scripts.
#ifndef __SCRIPTVARIABLE_H__
#define __SCRIPTVARIABLE_H__
#include "listener.h"
#ifdef GAME_DLL
#include "misc.h"
#endif
enum variabletype
{
VARIABLE_NONE,
VARIABLE_STRING,
VARIABLE_INTEGER,
VARIABLE_FLOAT,
VARIABLE_CHAR,
VARIABLE_CONSTSTRING,
VARIABLE_LISTENER,
VARIABLE_REF,
VARIABLE_ARRAY,
VARIABLE_CONSTARRAY,
VARIABLE_CONTAINER,
VARIABLE_SAFECONTAINER,
VARIABLE_POINTER,
VARIABLE_VECTOR,
VARIABLE_MAX
};
static const char *typenames[] =
{
"none",
"string",
"int",
"float",
"char",
"const string",
"listener",
"ref",
"array",
"const array",
"array",
"array",
"pointer",
"vector",
"double"
};
class ScriptArrayHolder {
public:
con_map< ScriptVariable, ScriptVariable > arrayValue;
unsigned int refCount;
public:
void Archive( Archiver& arc );
static void Archive( Archiver& arc, ScriptArrayHolder *& arrayValue );
};
class ScriptConstArrayHolder {
public:
ScriptVariable *constArrayValue;
unsigned int refCount;
unsigned int size;
public:
void Archive( Archiver& arc );
static void Archive( Archiver& arc, ScriptConstArrayHolder *& constArrayValue );
ScriptConstArrayHolder( ScriptVariable *pVar, unsigned int size );
ScriptConstArrayHolder( unsigned int size );
ScriptConstArrayHolder();
~ScriptConstArrayHolder();
};
class ScriptPointer {
public:
Container< ScriptVariable * > list;
public:
void Archive( Archiver& arc );
static void Archive( Archiver& arc, ScriptPointer *& pointerValue );
void Clear();
void add( ScriptVariable *var );
void remove( ScriptVariable *var );
void setValue( const ScriptVariable& var );
};
class ScriptVariable {
public:
short3 key; // variable name
unsigned char type; // variable type
union anon393 {
public:
char charValue;
float floatValue;
int intValue;
SafePtr<Listener> *listenerValue;
str *stringValue;
float *vectorValue;
ScriptVariable *refValue;
ScriptArrayHolder *arrayValue;
ScriptConstArrayHolder *constArrayValue;
Container< SafePtr< Listener > > *containerValue;
SafePtr< ContainerClass< SafePtr< Listener > > > *safeContainerValue;
ScriptPointer *pointerValue;
} m_data;
private:
void ClearInternal();
void ClearPointerInternal();
public:
CLASS_PROTOTYPE( ScriptVariable );
ScriptVariable();
ScriptVariable( const ScriptVariable& variable );
~ScriptVariable();
void Archive( Archiver& arc );
static void Archive( Archiver& arc, ScriptVariable **obj );
void ArchiveInternal( Archiver& arc );
void CastBoolean( void );
void CastConstArrayValue( void );
void CastEntity( void );
void CastFloat( void );
void CastInteger( void );
void CastString( void );
void Clear();
void ClearPointer();
const char *GetTypeName( void ) const;
variabletype GetType( void ) const;
qboolean IsEntity( void );
qboolean IsListener( void );
qboolean IsNumeric( void );
#ifndef NO_SCRIPTENGINE
qboolean IsSimpleEntity( void );
#endif
qboolean IsString( void );
qboolean IsVector( void );
void PrintValue( void );
void SetFalse( void );
void SetTrue( void );
int arraysize( void ) const;
size_t size( void ) const;
bool booleanNumericValue( void );
bool booleanValue( void ) const;
#ifndef NO_SCRIPTENGINE
str& getName( void );
short3& GetKey();
void SetKey( const short3& key );
#endif
Entity *entityValue( void );
void evalArrayAt( ScriptVariable &var );
void setArrayAt( ScriptVariable &index, ScriptVariable &value );
void setArrayAtRef( ScriptVariable &index, ScriptVariable &value );
void setArrayRefValue( ScriptVariable &var );
char charValue( void ) const;
void setCharValue( char newvalue );
ScriptVariable *constArrayValue( void );
void setConstArrayValue( ScriptVariable *pVar, unsigned int size );
#ifndef NO_SCRIPTENGINE
int constStringValue( void ) const;
void setConstStringValue( const_str s );
#endif
void setContainerValue( Container< SafePtr< Listener > > *newvalue );
void setSafeContainerValue( ContainerClass< SafePtr< Listener > > *newvalue );
float floatValue( void ) const;
void setFloatValue( float newvalue );
int intValue( void ) const;
void setIntValue( int newvalue );
Listener *listenerValue( void ) const;
void setListenerValue( Listener * newvalue );
void newPointer( void );
void setPointer( const ScriptVariable& newvalue );
void setRefValue( ScriptVariable * ref );
//const char *stringValue( void );
str stringValue( void ) const;
void setStringValue( str newvalue );
#ifndef NO_SCRIPTENGINE
SimpleEntity *simpleEntityValue( void ) const;
#endif
Vector vectorValue( void ) const;
void setVectorValue( const Vector &newvector );
class PathNode *pathNodeValue( void ) const;
class Waypoint *waypointValue( void ) const;
void greaterthan( ScriptVariable &variable );
void greaterthanorequal( ScriptVariable &variable );
void lessthan( ScriptVariable &variable );
void lessthanorequal( ScriptVariable &variable );
void complement( void );
void minus( void );
bool operator=( const ScriptVariable& variable );
ScriptVariable &operator[]( ScriptVariable& index );
ScriptVariable *operator[]( unsigned index ) const;
ScriptVariable *operator*( );
void operator+=( const ScriptVariable& value );
void operator-=( const ScriptVariable& value );
void operator*=( const ScriptVariable& value );
void operator/=( const ScriptVariable& value );
void operator%=( const ScriptVariable& value );
void operator&=( const ScriptVariable& value );
void operator^=( const ScriptVariable& value );
void operator|=( const ScriptVariable& value );
void operator<<=( const ScriptVariable& value );
void operator>>=( const ScriptVariable& value );
bool operator!=( const ScriptVariable& value );
bool operator==( const ScriptVariable& value );
ScriptVariable operator++( int );
ScriptVariable operator--( int );
};
#ifndef NO_SCRIPTENGINE
class ScriptVariableList : public Class
{
private:
con_set< short3, ScriptVariable > list;
public:
CLASS_PROTOTYPE( ScriptVariableList );
ScriptVariableList();
virtual void Archive( Archiver &arc );
void ClearList( void );
ScriptVariable *GetOrCreateVariable( str name );
ScriptVariable *GetOrCreateVariable( unsigned int name );
ScriptVariable *GetVariable( str name );
ScriptVariable *GetVariable( unsigned int name );
ScriptVariable *SetVariable( const char *name, int value );
ScriptVariable *SetVariable( const char *name, float value );
ScriptVariable *SetVariable( const char *name, const char *value );
ScriptVariable *SetVariable( const char *name, Entity *value );
ScriptVariable *SetVariable( const char *name, Listener *value );
ScriptVariable *SetVariable( const char *name, Vector &value );
ScriptVariable *SetVariable( const char *name, ScriptVariable& value );
ScriptVariable *SetVariable( unsigned int name, ScriptVariable& value );
};
#endif
#endif /* __SCRIPTVARIABLE_H__ */

2314
code/globalcpp/scriptvm.cpp Normal file

File diff suppressed because it is too large Load diff

328
code/globalcpp/scriptvm.h Normal file
View file

@ -0,0 +1,328 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// scriptvm.h: Script virtual machine interpreter.
#ifndef __SCRIPTVM_H__
#define __SCRIPTVM_H__
#include "listener.h"
#include <gamescript.h>
#include "scriptvariable.h"
#include "con_set.h"
#define MAX_STACK_DEPTH 20 // 9 in mohaa
//#define LOCALSTACK_SIZE 255 // pre-allocated localstack size for each VM
#define MAX_SCRIPTCYCLES 9999 // max cmds
#define STATE_RUNNING 0 // Running
#define STATE_SUSPENDED 1 // Suspended
#define STATE_WAITING 2 // Waiting for something
#define STATE_EXECUTION 3 // Resume to execution
#define STATE_DESTROYED 4 // Pending deletion
#define THREAD_RUNNING 0 // Running
#define THREAD_WAITING 1 // Waiting
#define THREAD_SUSPENDED 2 // Suspended
#define THREAD_CONTEXT_SWITCH 3 // Resume from context switch
// Ley0k: That's the old OpenMOHAA script stuff
// not needed anymore
//
/****************************************************************************************************************************************************************
// IneQuation: MoHAA server-side scripting
// TODO: work on it, it's a stub
// variables
typedef enum {
SVT_INTEGER,
SVT_FLOAT,
SVT_VECTOR,
SVT_STRING,
SVT_ENTITY,
SVT_LISTENER, // for compatibility with the bare Listener MoHAA object which is basically just a data container
SVT_ARRAY
} scriptVariableType_t;
typedef union {
int i;
float f;
char *s;
gentity_t *e;
struct scriptStack_s *l; // for compatibility with the bare Listener MoHAA object which is basically just a data container
struct scriptArray_s *a;
} scriptVariableData_t;
typedef struct scriptArrayElement_s {
scriptVariableData_t data;
struct scriptArrayElement_s *next;
struct scriptArrayElement_s *prev;
} scriptArrayElement_t;
typedef struct scriptArray_s {
int size;
scriptArrayElement_t *first;
} scriptArray_t;
typedef struct scriptVariable_s {
qboolean readonly;
scriptVariableType_t type;
scriptVariableData_t data;
} scriptVariable_t;
// script stack
typedef struct scriptStackVariable_s {
scriptVariable_t var;
struct scriptStackVariable_s *prev;
struct scriptStackVariable_s *next;
} scriptStackVariable_t;
typedef struct scriptStack_s {
int size;
scriptVariable_t *top;
} scriptStack_t;
// compiled script
typedef enum { // what code gets translated into the given instruction
SI_STARTTHREAD, // thread, waitthread, exec, waitexec
SI_TERMINATETHREAD, // end
SI_WAIT, // wait, waitframe
SI_JUMP, // goto, break and continue
SI_CONDITIONALJUMP, // if, for, while, switch
SI_INCR, // ++
SI_DECR, // --
SI_ASSIGN,
SI_EVENT // TODO: this possibly needs expanding into a separate instruction for each event (entity command), need to think the design through
} scriptInstruction_t;
typedef struct scriptStatement_s {
scriptInstruction_t inst;
int numParams;
scriptVariableData_t *params; // malloced at script compilation time
} scriptStatement_t;
typedef struct scriptCompiled_s {
scriptStack_t level;
scriptStack_t parm;
int numStats;
scriptStatement_t *stat;
} scriptCompiled_t;
// script threads
typedef struct scriptThread_s {
scriptVariableData_t object;
scriptStack_t stack;
int pos; // index of the statement we should be executing at this frame
int resumeTime; // execution of thread will stop until level.time >= resumeTime
struct scriptThread_s *next;
struct scriptThread_s *prev;
} scriptThread_t;
typedef struct scriptThreadGroup_s {
scriptStack_t group;
int count;
scriptThread_t *first;
} scriptThreadGroup_t;
****************************************************************************************************************************************************************/
//
//
// End of the old OpenMOHAA script stuff
class ScriptThread;
class ScriptVM;
class ScriptClass : public Listener
{
friend class GameScript;
friend class StateScript;
public:
// script variable
GameScript *m_Script; // current game script
// listener variable
SafePtr<Listener> m_Self; // self
// thread variable
ScriptVM *m_Threads; // threads list
public:
CLASS_PROTOTYPE( ScriptClass );
void *operator new( size_t size );
void operator delete( void *ptr );
ScriptClass( GameScript *gameScript, Listener *self );
ScriptClass();
virtual ~ScriptClass();
virtual void Archive( Archiver& arc );
void ArchiveInternal( Archiver& arc );
static void ArchiveScript( Archiver& arc, ScriptClass **obj );
void ArchiveCodePos( Archiver& arc, unsigned char **codePos );
virtual ScriptThread *CreateThreadInternal( const ScriptVariable& label );
virtual ScriptThread *CreateScriptInternal( const ScriptVariable& label );
void AddThread( ScriptVM * m_ScriptVM );
void KillThreads( void );
void RemoveThread( ScriptVM * m_ScriptVM );
str Filename();
unsigned char *FindLabel( str label );
unsigned char *FindLabel( const_str label );
const_str NearestLabel( unsigned char *pos );
StateScript *GetCatchStateScript( unsigned char *in, unsigned char *&out );
GameScript *GetScript();
Listener *GetSelf();
};
class ScriptCallStack {
public:
// opcode variable
unsigned char *codePos; // opcode will be restored once a DONE was hit
// stack variables
ScriptVariable *localStack;
ScriptVariable *pTop;
// return variable
ScriptVariable returnValue;
// OLD self value
SafePtr< Listener > m_Self;
};
// Ley0k: I'm unsure about this class, MOHAA use it
class ScriptStack
{
public:
ScriptVariable *m_Array;
int m_Count;
};
class ScriptVM
{
friend class ScriptThread;
public:
// important thread variables
ScriptVM *next; // next VM in the current ScriptClass
ScriptThread *m_Thread; // script thread
ScriptClass *m_ScriptClass; // current group of threads
public:
// return variables
ScriptStack *m_Stack; // Currently unused
ScriptVariable m_ReturnValue; // VM return value
// opcode variables
unsigned char *m_PrevCodePos; // previous opcode, for use with script exceptions
unsigned char *m_CodePos; // check compiler.h for the list of all opcodes
public:
// states
unsigned char state; // current VM state
unsigned char m_ThreadState; // current thread state
// stack variables
Container< ScriptCallStack * > callStack; // thread's call stack
ScriptVariable *localStack; // thread's local stack
int localStackSize; // dynamically allocated at initialization
ScriptVariable *pTop; // top stack from the local stack
ScriptVariable *m_StackPos; // marked stack position
// parameters variables
ScriptVariable *m_pOldData; // old fastEvent data, to cleanup
int m_OldDataSize;
bool m_bMarkStack; // changed by OP_MARK_STACK_POS and OP_RESTORE_STACK_POS
Event fastEvent; // parameter list, set when the VM is executed
// miscellaneous
bool m_bAllowContextSwitch; // allow parallel VM executions [experimental feature]
private:
void error( const char *format, ... );
void executeCommand( Listener *listener, int iParamCount, int eventnum, bool bReturn = false );
bool executeGetter( Listener *listener, str& name );
bool executeSetter( Listener *listener, str& name );
void jump( int offset );
void jumpBool( int offset, bool value );
void loadTop( Listener *listener, bool noTop = false );
void storeTop( Listener *listener, bool noTop = false );
void SetFastData( ScriptVariable *data, int dataSize );
bool Switch( StateScript *stateScript, ScriptVariable &var );
unsigned char *ProgBuffer();
void HandleScriptException( ScriptException& exc );
public:
void *operator new( size_t size );
void operator delete( void *ptr );
ScriptVM( ScriptClass *scriptClass, unsigned char *pCodePos, ScriptThread *thread );
~ScriptVM();
void Archive( Archiver& arc );
void EnterFunction( Event *ev );
void LeaveFunction();
void End( const ScriptVariable& returnValue );
void End( void );
void Execute( ScriptVariable *data = NULL, int dataSize = 0, str label = "" );
void NotifyDelete( void );
void Resume( qboolean bForce = false );
void Suspend( void );
str Filename( void );
str Label( void );
ScriptClass *GetScriptClass( void );
bool IsSuspended( void );
int State( void );
int ThreadState( void );
void EventGoto( Event *ev );
bool EventThrow( Event *ev );
void AllowContextSwitch( bool allow = true );
void RequestContextSwitch();
};
extern MEM_BlockAlloc< ScriptClass, MEM_BLOCKSIZE > ScriptClass_allocator;
#endif

View file

@ -0,0 +1,592 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// simpleentity.cpp : Simple entity
#include "glb_local.h"
#include "simpleentity.h"
#include "world.h"
Event EV_SimpleEntity_GetAngle
(
"angle",
EV_DEFAULT,
NULL,
NULL,
"get the angles of the entity using just one value.\n"
"Gets the yaw of the entity or an up and down\n"
"direction if newAngle is[ 0 - 359 ] or - 1 or - 2",
EV_GETTER
);
Event EV_SetAngle
(
"angle",
EV_DEFAULT,
"f",
"newAngle",
"set the angles of the entity using just one value.\n"
"Sets the yaw of the entity or an up and down\n"
"direction if newAngle is[ 0 - 359 ] or - 1 or - 2",
EV_NORMAL
);
Event EV_SimpleEntity_SetterAngle
(
"angle",
EV_DEFAULT,
"f",
"newAngle",
"set the angles of the entity using just one value.\n"
"Sets the yaw of the entity or an up and down\n"
"direction if newAngle is[ 0 - 359 ] or - 1 or - 2",
EV_SETTER
);
Event EV_SimpleEntity_GetAngles
(
"angles",
EV_DEFAULT,
NULL,
NULL,
"get the angles of the entity.",
EV_GETTER
);
Event EV_SetAngles
(
"angles",
EV_DEFAULT,
"v[0,360][0,360][0,360]",
"newAngles",
"Set the angles of the entity to newAngles.",
EV_NORMAL
);
Event EV_SimpleEntity_SetterAngles
(
"angles",
EV_DEFAULT,
"v[0,360][0,360][0,360]",
"newAngles",
"Set the angles of the entity to newAngles.",
EV_SETTER
);
Event EV_SimpleEntity_GetOrigin
(
"origin",
EV_DEFAULT,
NULL,
NULL,
"entity's origin",
EV_GETTER
);
Event EV_SetOrigin
(
"origin",
EV_DEFAULT,
"v",
"newOrigin",
"Set the origin of the entity to newOrigin.",
EV_NORMAL
);
Event EV_SimpleEntity_SetterOrigin
(
"origin",
EV_DEFAULT,
"v",
"newOrigin",
"Set the origin of the entity to newOrigin.",
EV_SETTER
);
Event EV_SimpleEntity_GetTargetname
(
"targetname",
EV_DEFAULT,
NULL,
NULL,
"entity's targetname",
EV_GETTER
);
Event EV_SimpleEntity_SetTargetname
(
"targetname",
EV_DEFAULT,
"s",
"targetName",
"set the targetname of the entity to targetName.",
EV_NORMAL
);
Event EV_SimpleEntity_SetterTargetname
(
"targetname",
EV_DEFAULT,
"s",
"targetName",
"set the targetname of the entity to targetName.",
EV_SETTER
);
Event EV_SimpleEntity_GetTarget
(
"target",
EV_DEFAULT,
NULL,
NULL,
"entity's target",
EV_GETTER
);
Event EV_SimpleEntity_SetTarget
(
"target",
EV_DEFAULT,
"s",
"targetname_to_target",
"target another entity with targetname_to_target.",
EV_NORMAL
);
Event EV_SimpleEntity_SetterTarget
(
"target",
EV_DEFAULT,
"s",
"targetname_to_target",
"target another entity with targetname_to_target.",
EV_SETTER
);
Event EV_SimpleEntity_Centroid
(
"centroid",
EV_DEFAULT,
NULL,
NULL,
"entity's centroid",
EV_GETTER
);
Event EV_SimpleEntity_ForwardVector
(
"forwardvector",
EV_DEFAULT,
NULL,
NULL,
"get the forward vector of angles",
EV_GETTER
);
Event EV_SimpleEntity_LeftVector
(
"leftvector",
EV_DEFAULT,
NULL,
NULL,
"get the left vector of angles",
EV_GETTER
);
Event EV_SimpleEntity_RightVector
(
"rightvector",
EV_DEFAULT,
NULL,
NULL,
"get the right vector of angles",
EV_GETTER
);
Event EV_SimpleEntity_UpVector
(
"upvector",
EV_DEFAULT,
NULL,
NULL,
"get the up vector of angles",
EV_GETTER
);
void SimpleEntity::SimpleArchive( Archiver& arc )
{
int index;
Listener::Archive( arc );
arc.ArchiveVector( &angles );
arc.ArchiveString( &target );
arc.ArchiveString( &targetname );
if( targetname.length() )
{
if( arc.Loading() )
{
arc.ArchiveInteger( &index );
world->AddTargetEntityAt( this, index );
}
else
{
index = world->GetTargetnameIndex( this );
arc.ArchiveInteger( &index );
}
}
}
void SimpleEntity::Archive( Archiver& arc )
{
SimpleEntity::SimpleArchive( arc );
arc.ArchiveVector( &origin );
arc.ArchiveVector( &centroid );
}
void SimpleEntity::setOrigin( Vector origin )
{
this->origin = origin;
this->centroid = origin;
}
void SimpleEntity::setOriginEvent( Vector origin )
{
setOrigin( origin );
}
void SimpleEntity::setAngles( Vector angles )
{
this->angles = angles.AnglesMod();
}
SimpleEntity::SimpleEntity()
{
entflags = 0;
}
SimpleEntity::~SimpleEntity()
{
if( world ) {
world->RemoveTargetEntity( this );
}
}
void SimpleEntity::SetTarget( str target )
{
this->target = target;
}
void SimpleEntity::SetTargetName( str targetname )
{
world->RemoveTargetEntity( this );
this->targetname = targetname;
world->AddTargetEntity( this );
}
str& SimpleEntity::Target()
{
return target;
}
str& SimpleEntity::TargetName()
{
return targetname;
}
SimpleEntity *SimpleEntity::Next( void )
{
SimpleEntity *ent = world->GetTarget( target, true );
if( !ent || !ent->isSubclassOf( SimpleEntity ) )
{
return NULL;
}
else
{
return ent;
}
}
void SimpleEntity::EventGetAngle( Event *ev )
{
ev->AddFloat( angles[ 1 ] );
}
void SimpleEntity::EventGetAngles( Event *ev )
{
ev->AddVector( angles );
}
void SimpleEntity::EventGetOrigin( Event *ev )
{
ev->AddVector( origin );
}
void SimpleEntity::EventGetTargetname( Event *ev )
{
ev->AddString( TargetName() );
}
void SimpleEntity::EventGetTarget( Event *ev )
{
ev->AddString( Target() );
}
void SimpleEntity::EventSetAngle( Event *ev )
{
Vector dir;
float angle = ev->GetFloat( 1 );
dir = G_GetMovedir( angle );
dir.toAngles();
setAngles( dir );
}
void SimpleEntity::EventSetAngles( Event *ev )
{
Vector angles;
if( ev->NumArgs() == 1 )
{
angles = ev->GetVector( 1 );
}
else
{
angles = Vector( ev->GetFloat( 1 ), ev->GetFloat( 2 ), ev->GetFloat( 3 ) );
}
setAngles( angles );
}
void SimpleEntity::EventSetOrigin( Event *ev )
{
setOriginEvent( ev->GetVector( 1 ) );
}
void SimpleEntity::EventSetTargetname( Event *ev )
{
SetTargetName( ev->GetString( 1 ) );
}
void SimpleEntity::EventSetTarget( Event *ev )
{
SetTarget( ev->GetString( 1 ) );
}
void SimpleEntity::GetCentroid( Event *ev )
{
ev->AddVector( centroid );
}
void SimpleEntity::GetForwardVector( Event *ev )
{
Vector fwd;
AngleVectorsLeft( angles, fwd, NULL, NULL );
ev->AddVector( fwd );
}
void SimpleEntity::GetLeftVector( Event *ev )
{
Vector left;
AngleVectorsLeft( angles, NULL, left, NULL );
ev->AddVector( left );
}
void SimpleEntity::GetRightVector( Event *ev )
{
Vector right;
AngleVectors( angles, NULL, right, NULL );
ev->AddVector( right );
}
void SimpleEntity::GetUpVector( Event *ev )
{
Vector up;
AngleVectorsLeft( angles, NULL, NULL, up );
ev->AddVector( up );
}
void SimpleEntity::MPrintf( const char *msg, ... )
{
}
int SimpleEntity::IsSubclassOfEntity( void ) const
{
return ( entflags & EF_ENTITY );
}
int SimpleEntity::IsSubclassOfAnimate( void ) const
{
return ( entflags & EF_ANIMATE );
}
int SimpleEntity::IsSubclassOfSentient( void ) const
{
return ( entflags & EF_SENTIENT );
}
int SimpleEntity::IsSubclassOfPlayer( void ) const
{
return ( entflags & EF_PLAYER );
}
int SimpleEntity::IsSubclassOfActor( void ) const
{
return ( entflags & EF_ACTOR );
}
int SimpleEntity::IsSubclassOfItem( void ) const
{
return ( entflags & EF_ITEM );
}
int SimpleEntity::IsSubclassOfInventoryItem( void ) const
{
return ( entflags & EF_INVENTORYITEM );
}
int SimpleEntity::IsSubclassOfWeapon( void ) const
{
return ( entflags & EF_WEAPON );
}
int SimpleEntity::IsSubclassOfProjectile( void ) const
{
return ( entflags & EF_PROJECTILE );
}
int SimpleEntity::IsSubclassOfDoor( void ) const
{
return ( entflags & EF_DOOR );
}
int SimpleEntity::IsSubclassOfCamera( void ) const
{
return ( entflags & EF_CAMERA );
}
int SimpleEntity::IsSubclassOfVehicle( void ) const
{
return ( entflags & EF_VEHICLE );
}
int SimpleEntity::IsSubclassOfVehicleTank( void ) const
{
return ( entflags & EF_VEHICLETANK );
}
int SimpleEntity::IsSubclassOfVehicleTurretGun( void ) const
{
return ( entflags & EF_VEHICLETURRET );
}
int SimpleEntity::IsSubclassOfTurretGun( void ) const
{
return ( entflags & EF_TURRET );
}
int SimpleEntity::IsSubclassOfPathNode( void ) const
{
return ( entflags & EF_PATHNODE );
}
int SimpleEntity::IsSubclassOfWaypoint( void ) const
{
return ( entflags & EF_WAYPOINT );
}
int SimpleEntity::IsSubclassOfTempWaypoint( void ) const
{
return ( entflags & EF_TEMPWAYPOINT );
}
int SimpleEntity::IsSubclassOfVehiclePoint( void ) const
{
return ( entflags & EF_VEHICLEPOINT );
}
int SimpleEntity::IsSubclassOfSplinePath( void ) const
{
return ( entflags & EF_SPLINEPATH );
}
int SimpleEntity::IsSubclassOfCrateObject( void ) const
{
return ( entflags & EF_CRATEOBJECT );
}
int SimpleEntity::IsSubclassOfBot( void ) const
{
return ( entflags & EF_BOT );
}
CLASS_DECLARATION( Listener, SimpleEntity, NULL )
{
{ &EV_SimpleEntity_GetAngle, &SimpleEntity::EventGetAngle },
{ &EV_SimpleEntity_GetAngles, &SimpleEntity::EventGetAngles },
{ &EV_SimpleEntity_GetOrigin, &SimpleEntity::EventGetOrigin },
{ &EV_SimpleEntity_GetTargetname, &SimpleEntity::EventGetTargetname },
{ &EV_SimpleEntity_GetTarget, &SimpleEntity::EventGetTarget },
{ &EV_SimpleEntity_SetterAngle, &SimpleEntity::EventSetAngle },
{ &EV_SimpleEntity_SetterAngles, &SimpleEntity::EventSetAngles },
{ &EV_SimpleEntity_SetterOrigin, &SimpleEntity::EventSetOrigin },
{ &EV_SimpleEntity_SetterTargetname, &SimpleEntity::EventSetTargetname },
{ &EV_SimpleEntity_SetterTarget, &SimpleEntity::EventSetTarget },
{ &EV_SetAngle, &SimpleEntity::EventSetAngle },
{ &EV_SetAngles, &SimpleEntity::EventSetAngles },
{ &EV_SetOrigin, &SimpleEntity::EventSetOrigin },
{ &EV_SimpleEntity_SetTargetname, &SimpleEntity::EventSetTargetname },
{ &EV_SimpleEntity_SetTarget, &SimpleEntity::EventSetTarget },
{ &EV_SimpleEntity_Centroid, &SimpleEntity::GetCentroid },
{ &EV_SimpleEntity_ForwardVector, &SimpleEntity::GetForwardVector },
{ &EV_SimpleEntity_LeftVector, &SimpleEntity::GetLeftVector },
{ &EV_SimpleEntity_RightVector, &SimpleEntity::GetRightVector },
{ &EV_SimpleEntity_UpVector, &SimpleEntity::GetUpVector },
{ NULL, NULL }
};
SimpleArchivedEntity::SimpleArchivedEntity()
{
level.m_SimpleArchivedEntities.AddObject( this );
}
SimpleArchivedEntity::~SimpleArchivedEntity()
{
level.m_SimpleArchivedEntities.RemoveObject( this );
}
CLASS_DECLARATION( SimpleEntity, SimpleArchivedEntity, NULL )
{
{ NULL, NULL }
};

View file

@ -0,0 +1,130 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// simpleentity.h: Simple entity.
#ifndef __SIMPLEENTITY_H__
#define __SIMPLEENTITY_H__
#include "listener.h"
extern Event EV_SetAngles;
extern Event EV_SetAngle;
extern Event EV_SetOrigin;
typedef int entflags_t;
class SimpleEntity;
typedef SafePtr< SimpleEntity > SimpleEntityPtr;
class SimpleEntity : public Listener
{
public:
// Base coord variable
Vector origin;
Vector angles;
// Flag (used to set a class flag)
entflags_t entflags;
// Used by scripts
str target;
str targetname;
// Centered origin based on mins/maxs
Vector centroid;
public:
CLASS_PROTOTYPE( SimpleEntity );
SimpleEntity();
virtual ~SimpleEntity();
void SimpleArchive( Archiver& arc );
virtual void Archive( Archiver& arc );
virtual void setOrigin( Vector origin );
virtual void setOriginEvent( Vector origin );
virtual void setAngles( Vector angles );
void SetTarget( str target );
void SetTargetName( str targetname );
str& Target();
str& TargetName();
SimpleEntity *Next( void );
int IsSubclassOfEntity( void ) const;
int IsSubclassOfAnimate( void ) const;
int IsSubclassOfSentient( void ) const;
int IsSubclassOfPlayer( void ) const;
int IsSubclassOfActor( void ) const;
int IsSubclassOfItem( void ) const;
int IsSubclassOfInventoryItem( void ) const;
int IsSubclassOfWeapon( void ) const;
int IsSubclassOfProjectile( void ) const;
int IsSubclassOfDoor( void ) const;
int IsSubclassOfCamera( void ) const;
int IsSubclassOfVehicle( void ) const;
int IsSubclassOfVehicleTank( void ) const;
int IsSubclassOfVehicleTurretGun( void ) const;
int IsSubclassOfTurretGun( void ) const;
int IsSubclassOfPathNode( void ) const;
int IsSubclassOfWaypoint( void ) const;
int IsSubclassOfTempWaypoint( void ) const;
int IsSubclassOfVehiclePoint( void ) const;
int IsSubclassOfSplinePath( void ) const;
int IsSubclassOfCrateObject( void ) const;
int IsSubclassOfBot( void ) const;
void EventGetAngle( Event *ev );
void EventGetAngles( Event *ev );
void EventGetOrigin( Event *ev );
void EventGetTargetname( Event *ev );
void EventGetTarget( Event *ev );
void EventSetAngle( Event *ev );
void EventSetAngles( Event *ev );
void EventSetOrigin( Event *ev );
void EventSetTargetname( Event *ev );
void EventSetTarget( Event *ev );
void GetCentroid( Event *ev );
void GetForwardVector( Event *ev );
void GetLeftVector( Event *ev );
void GetRightVector( Event *ev );
void GetUpVector( Event *ev );
void MPrintf( const char *msg, ... );
};
class SimpleArchivedEntity : public SimpleEntity
{
public:
CLASS_PROTOTYPE( SimpleArchivedEntity );
SimpleArchivedEntity();
virtual ~SimpleArchivedEntity();
};
#endif

437
code/globalcpp/slre.c Normal file
View file

@ -0,0 +1,437 @@
/*
* Copyright (c) 2004-2013 Sergey Lyubka <valenok@gmail.com>
* Copyright (c) 2013 Cesanta Software Limited
* All rights reserved
*
* This library is dual-licensed: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation. For the terms of this
* license, see <http://www.gnu.org/licenses/>.
*
* You are free to use this library under the terms of the GNU General
* Public License, 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.
*
* Alternatively, you can license this library under a commercial
* license, as set out in <http://cesanta.com/products.html>.
*/
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include "slre.h"
#define MAX_BRANCHES 100
#define MAX_BRACKETS 100
#define FAIL_IF(condition, error_code) if (condition) return (error_code)
#ifndef ARRAY_SIZE
#define ARRAY_SIZE(ar) (sizeof(ar) / sizeof((ar)[0]))
#endif
#ifdef SLRE_DEBUG
#define DBG(x) printf x
#else
#define DBG(x)
#endif
struct bracket_pair {
const char *ptr; /* Points to the first char after '(' in regex */
int len; /* Length of the text between '(' and ')' */
int branches; /* Index in the branches array for this pair */
int num_branches; /* Number of '|' in this bracket pair */
};
struct branch {
int bracket_index; /* index for 'struct bracket_pair brackets' */
/* array defined below */
const char *schlong; /* points to the '|' character in the regex */
};
struct regex_info {
/*
* Describes all bracket pairs in the regular expression.
* First entry is always present, and grabs the whole regex.
*/
struct bracket_pair brackets[MAX_BRACKETS];
int num_brackets;
/*
* Describes alternations ('|' operators) in the regular expression.
* Each branch falls into a specific branch pair.
*/
struct branch branches[MAX_BRANCHES];
int num_branches;
/* Array of captures provided by the user */
struct slre_cap *caps;
int num_caps;
/* E.g. SLRE_IGNORE_CASE. See enum below */
int flags;
};
static int is_metacharacter(const unsigned char *s) {
static const char *metacharacters = "^$().[]*+?|\\Ssdbfnrtv";
return strchr(metacharacters, *s) != NULL;
}
static int op_len(const char *re) {
return re[0] == '\\' && re[1] == 'x' ? 4 : re[0] == '\\' ? 2 : 1;
}
static int set_len(const char *re, int re_len) {
int len = 0;
while (len < re_len && re[len] != ']') {
len += op_len(re + len);
}
return len <= re_len ? len + 1 : -1;
}
static int get_op_len(const char *re, int re_len) {
return re[0] == '[' ? set_len(re + 1, re_len - 1) + 1 : op_len(re);
}
static int is_quantifier(const char *re) {
return re[0] == '*' || re[0] == '+' || re[0] == '?';
}
static int toi(int x) {
return isdigit(x) ? x - '0' : x - 'W';
}
static int hextoi(const unsigned char *s) {
return (toi(tolower(s[0])) << 4) | toi(tolower(s[1]));
}
static int match_op(const unsigned char *re, const unsigned char *s,
struct regex_info *info) {
int result = 0;
switch (*re) {
case '\\':
/* Metacharacters */
switch (re[1]) {
case 'S': FAIL_IF(isspace(*s), SLRE_NO_MATCH); result++; break;
case 's': FAIL_IF(!isspace(*s), SLRE_NO_MATCH); result++; break;
case 'd': FAIL_IF(!isdigit(*s), SLRE_NO_MATCH); result++; break;
case 'b': FAIL_IF(*s != '\b', SLRE_NO_MATCH); result++; break;
case 'f': FAIL_IF(*s != '\f', SLRE_NO_MATCH); result++; break;
case 'n': FAIL_IF(*s != '\n', SLRE_NO_MATCH); result++; break;
case 'r': FAIL_IF(*s != '\r', SLRE_NO_MATCH); result++; break;
case 't': FAIL_IF(*s != '\t', SLRE_NO_MATCH); result++; break;
case 'v': FAIL_IF(*s != '\v', SLRE_NO_MATCH); result++; break;
case 'x':
/* Match byte, \xHH where HH is hexadecimal byte representaion */
FAIL_IF(hextoi(re + 2) != *s, SLRE_NO_MATCH);
result++;
break;
default:
/* Valid metacharacter check is done in bar() */
FAIL_IF(re[1] != s[0], SLRE_NO_MATCH);
result++;
break;
}
break;
case '|': FAIL_IF(1, SLRE_INTERNAL_ERROR); break;
case '$': FAIL_IF(1, SLRE_NO_MATCH); break;
case '.': result++; break;
default:
if (info->flags & SLRE_IGNORE_CASE) {
FAIL_IF(tolower(*re) != tolower(*s), SLRE_NO_MATCH);
} else {
FAIL_IF(*re != *s, SLRE_NO_MATCH);
}
result++;
break;
}
return result;
}
static int match_set(const char *re, int re_len, const char *s,
struct regex_info *info) {
int len = 0, result = -1, invert = re[0] == '^';
if (invert) re++, re_len--;
while (len <= re_len && re[len] != ']' && result <= 0) {
/* Support character range */
if (re[len] != '-' && re[len + 1] == '-' && re[len + 2] != ']' &&
re[len + 2] != '\0') {
result = info->flags & SLRE_IGNORE_CASE ?
tolower(*s) >= tolower(re[len]) && tolower(*s) <= tolower(re[len + 2]) :
*s >= re[len] && *s <= re[len + 2];
len += 3;
} else {
result = match_op((unsigned char *) re + len, (unsigned char *) s, info);
len += op_len(re + len);
}
}
return (!invert && result > 0) || (invert && result <= 0) ? 1 : -1;
}
static int doh(const char *s, int s_len, struct regex_info *info, int bi);
static int bar(const char *re, int re_len, const char *s, int s_len,
struct regex_info *info, int bi) {
/* i is offset in re, j is offset in s, bi is brackets index */
int i, j, n, step;
for (i = j = 0; i < re_len && j <= s_len; i += step) {
/* Handle quantifiers. Get the length of the chunk. */
step = re[i] == '(' ? info->brackets[bi + 1].len + 2 :
get_op_len(re + i, re_len - i);
DBG(("%s [%.*s] [%.*s] re_len=%d step=%d i=%d j=%d\n", __func__,
re_len - i, re + i, s_len - j, s + j, re_len, step, i, j));
FAIL_IF(is_quantifier(&re[i]), SLRE_UNEXPECTED_QUANTIFIER);
FAIL_IF(step <= 0, SLRE_INVALID_CHARACTER_SET);
if (i + step < re_len && is_quantifier(re + i + step)) {
DBG(("QUANTIFIER: [%.*s]%c [%.*s]\n", step, re + i,
re[i + step], s_len - j, s + j));
if (re[i + step] == '?') {
int result = bar(re + i, step, s + j, s_len - j, info, bi);
j += result > 0 ? result : 0;
i++;
} else if (re[i + step] == '+' || re[i + step] == '*') {
int j2 = j, nj = j, n1, n2 = -1, ni, non_greedy = 0;
/* Points to the regexp code after the quantifier */
ni = i + step + 1;
if (ni < re_len && re[ni] == '?') {
non_greedy = 1;
ni++;
}
do {
if ((n1 = bar(re + i, step, s + j2, s_len - j2, info, bi)) > 0) {
j2 += n1;
}
if (re[i + step] == '+' && n1 < 0) break;
if (ni >= re_len) {
/* After quantifier, there is nothing */
nj = j2;
} else if ((n2 = bar(re + ni, re_len - ni, s + j2,
s_len - j2, info, bi)) >= 0) {
/* Regex after quantifier matched */
nj = j2 + n2;
}
if (nj > j && non_greedy) break;
} while (n1 > 0);
/*
* Even if we found one or more pattern, this branch will be executed,
* changing the next captures.
*/
if (n1 < 0 && n2 < 0 && re[i + step] == '*' &&
(n2 = bar(re + ni, re_len - ni, s + j, s_len - j, info, bi)) > 0) {
nj = j + n2;
}
DBG(("STAR/PLUS END: %d %d %d %d %d\n", j, nj, re_len - ni, n1, n2));
FAIL_IF(re[i + step] == '+' && nj == j, SLRE_NO_MATCH);
/* If while loop body above was not executed for the * quantifier, */
/* make sure the rest of the regex matches */
FAIL_IF(nj == j && ni < re_len && n2 < 0, SLRE_NO_MATCH);
/* Returning here cause we've matched the rest of RE already */
return nj;
}
continue;
}
if (re[i] == '[') {
n = match_set(re + i + 1, re_len - (i + 2), s + j, info);
DBG(("SET %.*s [%.*s] -> %d\n", step, re + i, s_len - j, s + j, n));
FAIL_IF(n <= 0, SLRE_NO_MATCH);
j += n;
} else if (re[i] == '(') {
n = SLRE_NO_MATCH;
bi++;
FAIL_IF(bi >= info->num_brackets, SLRE_INTERNAL_ERROR);
DBG(("CAPTURING [%.*s] [%.*s] [%s]\n",
step, re + i, s_len - j, s + j, re + i + step));
if (re_len - (i + step) <= 0) {
/* Nothing follows brackets */
n = doh(s + j, s_len - j, info, bi);
} else {
int j2;
for (j2 = 0; j2 <= s_len - j; j2++) {
if ((n = doh(s + j, s_len - (j + j2), info, bi)) >= 0 &&
bar(re + i + step, re_len - (i + step),
s + j + n, s_len - (j + n), info, bi) >= 0) break;
}
}
DBG(("CAPTURED [%.*s] [%.*s]:%d\n", step, re + i, s_len - j, s + j, n));
FAIL_IF(n < 0, n);
if (info->caps != NULL && n > 0) {
info->caps[bi - 1].ptr = s + j;
info->caps[bi - 1].len = n;
}
j += n;
} else if (re[i] == '^') {
FAIL_IF(j != 0, SLRE_NO_MATCH);
} else if (re[i] == '$') {
FAIL_IF(j != s_len, SLRE_NO_MATCH);
} else {
FAIL_IF(j >= s_len, SLRE_NO_MATCH);
n = match_op((unsigned char *) (re + i), (unsigned char *) (s + j), info);
FAIL_IF(n <= 0, n);
j += n;
}
}
return j;
}
/* Process branch points */
static int doh(const char *s, int s_len, struct regex_info *info, int bi) {
const struct bracket_pair *b = &info->brackets[bi];
int i = 0, len, result;
const char *p;
do {
p = i == 0 ? b->ptr : info->branches[b->branches + i - 1].schlong + 1;
len = b->num_branches == 0 ? b->len :
i == b->num_branches ? (int) (b->ptr + b->len - p) :
(int) (info->branches[b->branches + i].schlong - p);
DBG(("%s %d %d [%.*s] [%.*s]\n", __func__, bi, i, len, p, s_len, s));
result = bar(p, len, s, s_len, info, bi);
DBG(("%s <- %d\n", __func__, result));
} while (result <= 0 && i++ < b->num_branches); /* At least 1 iteration */
return result;
}
static int baz(const char *s, int s_len, struct regex_info *info) {
int i, result = -1, is_anchored = info->brackets[0].ptr[0] == '^';
for (i = 0; i <= s_len; i++) {
result = doh(s + i, s_len - i, info, 0);
if (result >= 0) {
result += i;
break;
}
if (is_anchored) break;
}
return result;
}
static void setup_branch_points(struct regex_info *info) {
int i, j;
struct branch tmp;
/* First, sort branches. Must be stable, no qsort. Use bubble algo. */
for (i = 0; i < info->num_branches; i++) {
for (j = i + 1; j < info->num_branches; j++) {
if (info->branches[i].bracket_index > info->branches[j].bracket_index) {
tmp = info->branches[i];
info->branches[i] = info->branches[j];
info->branches[j] = tmp;
}
}
}
/*
* For each bracket, set their branch points. This way, for every bracket
* (i.e. every chunk of regex) we know all branch points before matching.
*/
for (i = j = 0; i < info->num_brackets; i++) {
info->brackets[i].num_branches = 0;
info->brackets[i].branches = j;
while (j < info->num_branches && info->branches[j].bracket_index == i) {
info->brackets[i].num_branches++;
j++;
}
}
}
static int foo(const char *re, int re_len, const char *s, int s_len,
struct regex_info *info) {
int i, step, depth = 0;
/* First bracket captures everything */
info->brackets[0].ptr = re;
info->brackets[0].len = re_len;
info->num_brackets = 1;
/* Make a single pass over regex string, memorize brackets and branches */
for (i = 0; i < re_len; i += step) {
step = get_op_len(re + i, re_len - i);
if (re[i] == '|') {
FAIL_IF(info->num_branches >= (int) ARRAY_SIZE(info->branches),
SLRE_TOO_MANY_BRANCHES);
info->branches[info->num_branches].bracket_index =
info->brackets[info->num_brackets - 1].len == -1 ?
info->num_brackets - 1 : depth;
info->branches[info->num_branches].schlong = &re[i];
info->num_branches++;
} else if (re[i] == '\\') {
FAIL_IF(i >= re_len - 1, SLRE_INVALID_METACHARACTER);
if (re[i + 1] == 'x') {
/* Hex digit specification must follow */
FAIL_IF(re[i + 1] == 'x' && i >= re_len - 3,
SLRE_INVALID_METACHARACTER);
FAIL_IF(re[i + 1] == 'x' && !(isxdigit(re[i + 2]) &&
isxdigit(re[i + 3])), SLRE_INVALID_METACHARACTER);
} else {
FAIL_IF(!is_metacharacter((unsigned char *) re + i + 1),
SLRE_INVALID_METACHARACTER);
}
} else if (re[i] == '(') {
FAIL_IF(info->num_brackets >= (int) ARRAY_SIZE(info->brackets),
SLRE_TOO_MANY_BRACKETS);
depth++; /* Order is important here. Depth increments first. */
info->brackets[info->num_brackets].ptr = re + i + 1;
info->brackets[info->num_brackets].len = -1;
info->num_brackets++;
FAIL_IF(info->num_caps > 0 && info->num_brackets - 1 > info->num_caps,
SLRE_CAPS_ARRAY_TOO_SMALL);
} else if (re[i] == ')') {
int ind = info->brackets[info->num_brackets - 1].len == -1 ?
info->num_brackets - 1 : depth;
info->brackets[ind].len = (int) (&re[i] - info->brackets[ind].ptr);
DBG(("SETTING BRACKET %d [%.*s]\n",
ind, info->brackets[ind].len, info->brackets[ind].ptr));
depth--;
FAIL_IF(depth < 0, SLRE_UNBALANCED_BRACKETS);
FAIL_IF(i > 0 && re[i - 1] == '(', SLRE_NO_MATCH);
}
}
FAIL_IF(depth != 0, SLRE_UNBALANCED_BRACKETS);
setup_branch_points(info);
return baz(s, s_len, info);
}
int slre_match(const char *regexp, const char *s, int s_len,
struct slre_cap *caps, int num_caps, int flags) {
struct regex_info info;
/* Initialize info structure */
info.flags = flags;
info.num_brackets = info.num_branches = 0;
info.num_caps = num_caps;
info.caps = caps;
DBG(("========================> [%s] [%.*s]\n", regexp, s_len, s));
return foo(regexp, (int) strlen(regexp), s, s_len, &info);
}

60
code/globalcpp/slre.h Normal file
View file

@ -0,0 +1,60 @@
/*
* Copyright (c) 2004-2013 Sergey Lyubka <valenok@gmail.com>
* Copyright (c) 2013 Cesanta Software Limited
* All rights reserved
*
* This library is dual-licensed: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation. For the terms of this
* license, see <http://www.gnu.org/licenses/>.
*
* You are free to use this library under the terms of the GNU General
* Public License, 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.
*
* Alternatively, you can license this library under a commercial
* license, as set out in <http://cesanta.com/products.html>.
*/
/*
* This is a regular expression library that implements a subset of Perl RE.
* Please refer to README.md for a detailed reference.
*/
#ifndef SLRE_HEADER_DEFINED
#define SLRE_HEADER_DEFINED
#ifdef __cplusplus
extern "C" {
#endif
struct slre_cap {
const char *ptr;
int len;
};
int slre_match(const char *regexp, const char *buf, int buf_len,
struct slre_cap *caps, int num_caps, int flags);
/* Possible flags for slre_match() */
enum { SLRE_IGNORE_CASE = 1 };
/* slre_match() failure codes */
#define SLRE_NO_MATCH -1
#define SLRE_UNEXPECTED_QUANTIFIER -2
#define SLRE_UNBALANCED_BRACKETS -3
#define SLRE_INTERNAL_ERROR -4
#define SLRE_INVALID_CHARACTER_SET -5
#define SLRE_INVALID_METACHARACTER -6
#define SLRE_CAPS_ARRAY_TOO_SMALL -7
#define SLRE_TOO_MANY_BRANCHES -8
#define SLRE_TOO_MANY_BRACKETS -9
#ifdef __cplusplus
}
#endif
#endif /* SLRE_HEADER_DEFINED */

1237
code/globalcpp/vector.h Normal file

File diff suppressed because it is too large Load diff

581
code/globalcpp/world.cpp Normal file
View file

@ -0,0 +1,581 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// world.cpp : Holds the target list, and general info (fog and such).
#include "world.h"
#include <scriptmaster.h>
#ifdef GAME_DLL
#include "../game/soundman.h"
#endif
WorldPtr world;
Event EV_World_SetSoundtrack
(
"soundtrack",
EV_DEFAULT,
"s",
"MusicFile",
"Set music soundtrack for this level."
);
Event EV_World_SetGravity
(
"gravity",
EV_DEFAULT,
"f",
"worldGravity",
"Set the gravity for the whole world."
);
Event EV_World_SetNextMap
(
"nextmap",
EV_DEFAULT,
"s",
"nextMap",
"Set the next map to change to"
);
Event EV_World_SetMessage
(
"message",
EV_DEFAULT,
"s",
"worldMessage",
"Set a message for the world"
);
Event EV_World_SetWaterColor
(
"watercolor",
EV_DEFAULT,
"v",
"waterColor",
"Set the watercolor screen blend"
);
Event EV_World_SetWaterAlpha
(
"wateralpha",
EV_DEFAULT,
"f",
"waterAlpha",
"Set the alpha of the water screen blend"
);
Event EV_World_SetLavaColor
(
"lavacolor",
EV_DEFAULT,
"v",
"lavaColor",
"Set the color of lava screen blend"
);
Event EV_World_SetLavaAlpha
(
"lavaalpha",
EV_DEFAULT,
"f",
"lavaAlpha",
"Set the alpha of lava screen blend"
);
Event EV_World_SetFarPlane_Color
(
"farplane_color",
EV_DEFAULT,
"v",
"farplaneColor",
"Set the color of the far clipping plane fog"
);
Event EV_World_SetFarPlane_Cull
(
"farplane_cull",
EV_DEFAULT,
"b",
"farplaneCull",
"Whether or not the far clipping plane should cull things out of the world"
);
Event EV_World_SetFarPlane
(
"farplane",
EV_DEFAULT,
"f",
"farplaneDistance",
"Set the distance of the far clipping plane"
);
Event EV_World_SetAmbientLight
(
"ambientlight",
EV_DEFAULT,
"b",
"ambientLight",
"Set whether or not ambient light should be used"
);
Event EV_World_SetAmbientIntensity
(
"ambient",
EV_DEFAULT,
"f",
"ambientIntensity",
"Set the intensity of the ambient light"
);
Event EV_World_SetSunColor
(
"suncolor",
EV_DEFAULT,
"v",
"sunColor",
"Set the color of the sun"
);
Event EV_World_SetSunLight
(
"sunlight",
EV_DEFAULT,
"b",
"sunlight",
"Set whether or not there should be sunlight"
);
Event EV_World_SetSunDirection
(
"sundirection",
EV_DEFAULT,
"v",
"sunlightDirection",
"Set the direction of the sunlight"
);
Event EV_World_LightmapDensity
(
"lightmapdensity",
EV_DEFAULT,
"f",
"density",
"Set the default lightmap density for all world surfaces"
);
Event EV_World_SunFlare
(
"sunflare",
EV_DEFAULT,
"v",
"position_of_sun",
"Set the position of the sun for the purposes of the sunflare"
);
Event EV_World_SunFlareInPortalSky
(
"sunflare_inportalsky",
EV_DEFAULT,
NULL,
NULL,
"Let the renderer know that the sun is in the portal sky"
);
Event EV_World_SetSkyAlpha
(
"skyalpha",
EV_DEFAULT,
"f",
"newAlphaForPortalSky",
"Set the alpha on the sky"
);
Event EV_World_SetSkyPortal
(
"skyportal",
EV_DEFAULT,
"b",
"newSkyPortalState",
"Whether or not to use the sky portal at all"
);
Event EV_World_SetNorthYaw
(
"northyaw",
EV_DEFAULT,
"f",
"yaw",
"Sets the yaw direction that is considered to be north"
);
void World::AddTargetEntity( SimpleEntity *ent )
{
str targetname = ent->TargetName();
if( !targetname.length() )
{
return;
}
ConSimple* list = GetTargetList( targetname );
list->AddObject( ent );
}
void World::AddTargetEntityAt( SimpleEntity *ent, int index )
{
str targetname = ent->TargetName();
if( !targetname.length() )
{
return;
}
ConSimple* list = GetTargetList( targetname );
list->AddObjectAt( index, ent );
}
void World::RemoveTargetEntity( SimpleEntity *ent )
{
str targetname = ent->TargetName();
if( !targetname.length() )
{
return;
}
ConSimple* list = GetExistingTargetList( targetname );
if( list )
{
list->RemoveObject( ent );
if( list->NumObjects() <= 0 )
{
m_targetList.remove( Director.AddString( targetname ) );
}
}
}
void World::FreeTargetList()
{
m_targetList.clear();
}
SimpleEntity *World::GetNextEntity( str targetname, SimpleEntity *ent )
{
return GetNextEntity( Director.AddString( targetname ), ent );
}
SimpleEntity *World::GetNextEntity( const_str targetname, SimpleEntity *ent )
{
ConSimple* list = GetTargetList( targetname );
int index;
if( ent )
{
index = list->IndexOfObject( ent ) + 1;
}
else
{
index = 1;
}
if( list->NumObjects() >= index )
{
return list->ObjectAt( index );
}
else
{
return NULL;
}
}
SimpleEntity *World::GetScriptTarget( str targetname )
{
return GetScriptTarget( Director.AddString( targetname ) );
}
SimpleEntity *World::GetScriptTarget( const_str targetname )
{
ConSimple* list = GetTargetList( targetname );
if( list->NumObjects() == 1 )
{
return list->ObjectAt( 1 );
}
else if( list->NumObjects() > 1 )
{
ScriptError( "There are %d entities with targetname '%s'. You are using a command that requires exactly one.", list->NumObjects(), Director.GetString( targetname ).c_str() );
}
return NULL;
}
SimpleEntity *World::GetTarget( str targetname, bool quiet )
{
return GetTarget( Director.AddString( targetname ), quiet );
}
SimpleEntity *World::GetTarget( const_str targetname, bool quiet )
{
ConSimple* list = GetTargetList( targetname );
if( list->NumObjects() == 1 )
{
return list->ObjectAt( 1 );
}
else if( list->NumObjects() > 1 )
{
if( !quiet ) {
warning( "World::GetTarget", "There are %d entities with targetname '%s'. You are using a command that requires exactly one.", list->NumObjects(), Director.GetString( targetname ).c_str() );
}
}
return NULL;
}
int World::GetTargetnameIndex( SimpleEntity *ent )
{
ConSimple* list = GetTargetList( ent->TargetName() );
return list->IndexOfObject( ent );
}
ConSimple *World::GetExistingTargetList( const str& targetname )
{
return GetExistingTargetList( Director.AddString( targetname ) );
}
ConSimple *World::GetExistingTargetList( const_str targetname )
{
return m_targetList.findKeyValue( targetname );
}
ConSimple *World::GetTargetList( str& targetname )
{
return GetTargetList( Director.AddString( targetname ) );
}
ConSimple *World::GetTargetList( const_str targetname )
{
return &m_targetList.addKeyValue( targetname );
}
#ifdef GAME_DLL
World::World()
{
world = this;
world_dying = qfalse;
// Anything that modifies configstrings, or spawns things is ignored when loading savegames
if( LoadingSavegame )
{
return;
}
assert( entnum == ENTITYNUM_WORLD );
setMoveType( MOVETYPE_NONE );
setSolidType( SOLID_BSP );
// world model is always index 1
edict->s.modelindex = 1;
model = "*1";
UpdateConfigStrings();
// clear out the soundtrack from the last level
ChangeSoundtrack( "" );
// set the default gravity
gi.Cvar_Set( "sv_gravity", "800" );
// set the default farplane parameters
farplane_distance = 0;
farplane_color = "0 0 0";
farplane_cull = qtrue;
UpdateFog();
sky_portal = qtrue;
UpdateSky();
m_fAIVisionDistance = 2048.0f;
level.cinematic = spawnflags & WORLD_CINEMATIC;
if( level.cinematic )
gi.Cvar_Set( "sv_cinematic", "1" );
else
gi.Cvar_Set( "sv_cinematic", "0" );
level.nextmap = "";
level.level_name = level.mapname;
SoundMan.Load();
// Set the color for the blends.
level.water_color = Vector( 0, 0, 1 );
level.water_alpha = 0.1f;
level.lava_color = Vector( 1.0f, 0.3f, 0 );
level.lava_alpha = 0.6f;
//
// set the targetname of the world
//
SetTargetName( "world" );
m_fNorth = 0;
}
void World::UpdateConfigStrings( void )
{
//
// make some data visible to connecting client
//
gi.SetConfigstring( CS_GAME_VERSION, GAME_VERSION );
gi.SetConfigstring( CS_LEVEL_START_TIME, va( "%i", level.svsStartTime ) );
// make some data visible to the server
gi.SetConfigstring( CS_MESSAGE, level.level_name.c_str() );
};
void World::UpdateFog( void )
{
gi.SetFarPlane( farplane_distance );
gi.SetConfigstring( CS_FOGINFO, va( "%d %.0f %.4f %.4f %.4f", farplane_cull, farplane_distance, farplane_color.x, farplane_color.y, farplane_color.z ) );
}
void World::UpdateSky( void )
{
gi.SetSkyPortal( sky_portal );
gi.SetConfigstring( CS_SKYINFO, va( "%.4f %d", sky_alpha, sky_portal ) );
}
void World::SetSoundtrack( Event *ev )
{
const char *text;
text = ev->GetString( 1 );
ChangeSoundtrack( text );
}
void World::SetGravity( Event *ev )
{
gi.Cvar_Set( "sv_gravity", ev->GetString( 1 ) );
}
void World::SetFarPlane( Event *ev )
{
farplane_distance = ev->GetFloat( 1 );
UpdateFog();
}
void World::SetFarPlane_Color( Event *ev )
{
farplane_color = ev->GetVector( 1 );
UpdateFog();
}
void World::SetFarPlane_Cull( Event *ev )
{
farplane_cull = ev->GetBoolean( 1 );
UpdateFog();
}
void World::SetSkyAlpha( Event *ev )
{
sky_alpha = ev->GetFloat( 1 );
UpdateSky();
}
void World::SetSkyPortal( Event *ev )
{
sky_portal = ev->GetBoolean( 1 );
UpdateSky();
}
void World::SetNextMap( Event *ev )
{
level.nextmap = ev->GetString( 1 );
}
void World::SetMessage( Event *ev )
{
const char *text;
text = ev->GetString( 1 );
level.level_name = text;
gi.SetConfigstring( CS_MESSAGE, text );
}
void World::SetWaterColor( Event *ev )
{
level.water_color = ev->GetVector( 1 );
}
void World::SetWaterAlpha( Event *ev )
{
level.water_alpha = ev->GetFloat( 1 );
}
void World::SetLavaColor( Event *ev )
{
level.lava_color = ev->GetVector( 1 );
}
void World::SetLavaAlpha( Event *ev )
{
level.lava_alpha = ev->GetFloat( 1 );
}
void World::SetNorthYaw( Event *ev )
{
m_fNorth = anglemod( ev->GetFloat( 1 ) );
}
CLASS_DECLARATION( Entity, World, "worldspawn" )
{
{ &EV_World_SetSoundtrack, &World::SetSoundtrack },
{ &EV_World_SetGravity, &World::SetGravity },
{ &EV_World_SetNextMap, &World::SetNextMap },
{ &EV_World_SetMessage, &World::SetMessage },
{ &EV_World_SetWaterColor, &World::SetWaterColor },
{ &EV_World_SetWaterAlpha, &World::SetWaterAlpha },
{ &EV_World_SetLavaColor, &World::SetLavaColor },
{ &EV_World_SetLavaAlpha, &World::SetLavaAlpha },
{ &EV_World_SetFarPlane_Color, &World::SetFarPlane_Color },
{ &EV_World_SetFarPlane_Cull, &World::SetFarPlane_Cull },
{ &EV_World_SetFarPlane, &World::SetFarPlane },
{ &EV_World_SetSkyAlpha, &World::SetSkyAlpha },
{ &EV_World_SetSkyPortal, &World::SetSkyPortal },
{ &EV_World_SetNorthYaw, &World::SetNorthYaw },
{ &EV_World_SetAmbientLight, NULL },
{ &EV_World_SetAmbientIntensity, NULL },
{ &EV_World_SetSunColor, NULL },
{ &EV_World_SetSunLight, NULL },
{ &EV_World_SetSunDirection, NULL },
{ &EV_World_LightmapDensity, NULL },
{ &EV_World_SunFlare, NULL },
{ &EV_World_SunFlareInPortalSky, NULL },
{ NULL, NULL }
};
#else
World::World()
{
world = this;
world_dying = qfalse;
}
CLASS_DECLARATION( SimpleEntity, World, "worldspawn" )
{
{ NULL, NULL }
};
#endif

111
code/globalcpp/world.h Normal file
View file

@ -0,0 +1,111 @@
/*
===========================================================================
Copyright (C) 2015 the OpenMoHAA team
This file is part of OpenMoHAA source code.
OpenMoHAA source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
OpenMoHAA source code 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 OpenMoHAA source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
// world.h: Global world information (fog and such).
#ifndef __WORLD_H__
#define __WORLD_H__
#if defined ( CGAME_DLL )
#include "../cgame_hook/script/centity.h"
#elif defined ( GAME_DLL )
#include "entity.h"
#else
#include "glb_local.h"
#include "simpleentity.h"
#endif
#include <gamescript.h>
#define WORLD_CINEMATIC 1
typedef Container< SafePtr< SimpleEntity > > ConSimple;
#if defined ( GAME_DLL ) || defined ( CGAME_DLL )
class World : public Entity {
#else
class World : public SimpleEntity {
#endif
con_set < const_str, ConSimple > m_targetList; // moh could have used con_set instead of TargetList
qboolean world_dying;
public:
// farplane variables
float farplane_distance;
Vector farplane_color;
qboolean farplane_cull;
// sky variables
float sky_alpha;
qboolean sky_portal;
// orientation variables
float m_fAIVisionDistance;
float m_fNorth;
public:
CLASS_PROTOTYPE( World );
World();
void AddTargetEntity( SimpleEntity *ent );
void AddTargetEntityAt( SimpleEntity *ent, int index );
void RemoveTargetEntity( SimpleEntity *ent );
void FreeTargetList();
SimpleEntity *GetNextEntity( str targetname, SimpleEntity *ent );
SimpleEntity *GetNextEntity( const_str targetname, SimpleEntity *ent );
SimpleEntity *GetScriptTarget( str targetname );
SimpleEntity *GetScriptTarget( const_str targetname );
SimpleEntity *GetTarget( str targetname, bool quiet );
SimpleEntity *GetTarget( const_str targetname, bool quiet );
int GetTargetnameIndex( SimpleEntity *ent );
ConSimple *GetExistingTargetList( const str& targetname );
ConSimple *GetExistingTargetList( const_str targetname );
ConSimple *GetTargetList( str& targetname );
ConSimple *GetTargetList( const_str targetname );
void SetSoundtrack( Event *ev );
void SetGravity( Event *ev );
void SetNextMap( Event *ev );
void SetMessage( Event *ev );
void SetWaterColor( Event *ev );
void SetWaterAlpha( Event *ev );
void SetLavaColor( Event *ev );
void SetLavaAlpha( Event *ev );
void SetFarPlane_Color( Event *ev );
void SetFarPlane_Cull( Event *ev );
void SetFarPlane( Event *ev );
void SetSkyAlpha( Event *ev );
void SetSkyPortal( Event *ev );
void SetNorthYaw( Event *ev );
void UpdateConfigStrings( void );
void UpdateFog( void );
void UpdateSky( void );
};
typedef SafePtr< World > WorldPtr;
extern WorldPtr world;
#endif /* __WORLD_H__ */