added source folders

This commit is contained in:
purpleyouko committed 2025-08-11 11:09:09 -05:00
1 parent f23521f720
commit cfdc19df45
145 files changed
+54574

No files matched your search

+52
View File
@@ -0,0 +1,52 @@
/* Copyright (C) 2000 MySQL AB
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/*
Data structures for mysys/my_alloc.c (root memory allocator)
*/
#ifndef _my_alloc_h
#define _my_alloc_h
#define ALLOC_MAX_BLOCK_TO_DROP 4096
#define ALLOC_MAX_BLOCK_USAGE_BEFORE_DROP 10
typedef struct st_used_mem
{ /* struct for once_alloc (block) */
struct st_used_mem *next; /* Next block in use */
unsigned int left; /* memory left in block */
unsigned int size; /* size of block */
} USED_MEM;
typedef struct st_mem_root
{
USED_MEM *free; /* blocks with free memory in it */
USED_MEM *used; /* blocks almost without free memory */
USED_MEM *pre_alloc; /* preallocated block */
/* if block have less memory it will be put in 'used' list */
unsigned int min_malloc;
unsigned int block_size; /* initial block size */
unsigned int block_num; /* allocated blocks counter */
/*
first free block in queue test counter (if it exceed
MAX_BLOCK_USAGE_BEFORE_DROP block will be dropped in 'used' list)
*/
unsigned int first_block_usage;
void (*error_handler)(void);
} MEM_ROOT;
#endif
+101
View File
@@ -0,0 +1,101 @@
/* Copyright (C) 2000 MySQL AB
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#ifndef _dbug_h
#define _dbug_h
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(DBUG_OFF) && !defined(_lint)
extern int _db_on_,_no_db_;
extern FILE *_db_fp_;
extern char *_db_process_;
extern int _db_keyword_(const char *keyword);
extern int _db_strict_keyword_(const char *keyword);
extern void _db_setjmp_(void);
extern void _db_longjmp_(void);
extern void _db_push_(const char *control);
extern void _db_pop_(void);
extern void _db_enter_(const char *_func_,const char *_file_,uint _line_,
const char **_sfunc_,const char **_sfile_,
uint *_slevel_, char ***);
extern void _db_return_(uint _line_,const char **_sfunc_,const char **_sfile_,
uint *_slevel_);
extern void _db_pargs_(uint _line_,const char *keyword);
extern void _db_doprnt_ _VARARGS((const char *format,...));
extern void _db_dump_(uint _line_,const char *keyword,const char *memory,
uint length);
extern void _db_output_(uint flag);
extern void _db_lock_file(void);
extern void _db_unlock_file(void);
#define DBUG_ENTER(a) const char *_db_func_, *_db_file_; uint _db_level_; \
char **_db_framep_; \
_db_enter_ (a,__FILE__,__LINE__,&_db_func_,&_db_file_,&_db_level_, \
&_db_framep_)
#define DBUG_LEAVE \
(_db_return_ (__LINE__, &_db_func_, &_db_file_, &_db_level_))
#define DBUG_RETURN(a1) {DBUG_LEAVE; return(a1);}
#define DBUG_VOID_RETURN {DBUG_LEAVE; return;}
#define DBUG_EXECUTE(keyword,a1) \
{if (_db_on_) {if (_db_keyword_ (keyword)) { a1 }}}
#define DBUG_PRINT(keyword,arglist) \
{if (_db_on_) {_db_pargs_(__LINE__,keyword); _db_doprnt_ arglist;}}
#define DBUG_PUSH(a1) _db_push_ (a1)
#define DBUG_POP() _db_pop_ ()
#define DBUG_PROCESS(a1) (_db_process_ = a1)
#define DBUG_FILE (_db_fp_)
#define DBUG_SETJMP(a1) (_db_setjmp_ (), setjmp (a1))
#define DBUG_LONGJMP(a1,a2) (_db_longjmp_ (), longjmp (a1, a2))
#define DBUG_DUMP(keyword,a1,a2)\
{if (_db_on_) {_db_dump_(__LINE__,keyword,a1,a2);}}
#define DBUG_IN_USE (_db_fp_ && _db_fp_ != stderr)
#define DEBUGGER_OFF _no_db_=1;_db_on_=0;
#define DEBUGGER_ON _no_db_=0
#define DBUG_LOCK_FILE { _db_lock_file(); }
#define DBUG_UNLOCK_FILE { _db_unlock_file(); }
#define DBUG_OUTPUT(A) { _db_output_(A); }
#define DBUG_ASSERT(A) assert(A)
#define DBUG_EXECUTE_IF(keyword,a1) \
{if (_db_on_) {if (_db_strict_keyword_ (keyword)) { a1 }}}
#else /* No debugger */
#define DBUG_ENTER(a1)
#define DBUG_RETURN(a1) return(a1)
#define DBUG_VOID_RETURN return
#define DBUG_EXECUTE(keyword,a1) {}
#define DBUG_EXECUTE_IF(keyword,a1) {}
#define DBUG_PRINT(keyword,arglist) {}
#define DBUG_PUSH(a1) {}
#define DBUG_POP() {}
#define DBUG_PROCESS(a1) {}
#define DBUG_FILE (stderr)
#define DBUG_SETJMP setjmp
#define DBUG_LONGJMP longjmp
#define DBUG_DUMP(keyword,a1,a2) {}
#define DBUG_IN_USE 0
#define DEBUGGER_OFF
#define DEBUGGER_ON
#define DBUG_LOCK_FILE
#define DBUG_UNLOCK_FILE
#define DBUG_OUTPUT(A)
#define DBUG_ASSERT(A) {}
#endif
#ifdef __cplusplus
}
#endif
#endif
+77
View File
@@ -0,0 +1,77 @@
/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#ifndef _my_getopt_h
#define _my_getopt_h
C_MODE_START
#define GET_NO_ARG 1
#define GET_BOOL 2
#define GET_INT 3
#define GET_UINT 4
#define GET_LONG 5
#define GET_ULONG 6
#define GET_LL 7
#define GET_ULL 8
#define GET_STR 9
#define GET_STR_ALLOC 10
#define GET_DISABLED 11
#define GET_ASK_ADDR 128
#define GET_TYPE_MASK 127
enum get_opt_arg_type { NO_ARG, OPT_ARG, REQUIRED_ARG };
struct my_option
{
const char *name; /* Name of the option */
int id; /* unique id or short option */
const char *comment; /* option comment, for autom. --help */
gptr *value; /* The variable value */
gptr *u_max_value; /* The user def. max variable value */
const char **str_values; /* Pointer to possible values */
ulong var_type;
enum get_opt_arg_type arg_type;
longlong def_value; /* Default value */
longlong min_value; /* Min allowed value */
longlong max_value; /* Max allowed value */
longlong sub_size; /* Subtract this from given value */
long block_size; /* Value should be a mult. of this */
int app_type; /* To be used by an application */
};
typedef my_bool (* my_get_one_option) (int, const struct my_option *, char * );
typedef void (* my_error_reporter) (enum loglevel level, const char *format, ... );
extern char *disabled_my_option;
extern my_bool my_getopt_print_errors;
extern my_error_reporter my_getopt_error_reporter;
extern int handle_options (int *argc, char ***argv,
const struct my_option *longopts, my_get_one_option);
extern void my_print_help(const struct my_option *options);
extern void my_print_variables(const struct my_option *options);
extern void my_getopt_register_get_addr(gptr* (*func_addr)(const char *, uint,
const struct my_option *));
ulonglong getopt_ull_limit_value(ulonglong num, const struct my_option *optp);
my_bool getopt_compare_strings(const char *s, const char *t, uint length);
C_MODE_END
#endif /* _my_getopt_h */
File diff suppressed because it is too large. Load diff
+46
View File
@@ -0,0 +1,46 @@
/* Copyright (C) 2000 MySQL AB
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#ifndef _list_h_
#define _list_h_
#ifdef __cplusplus
extern "C" {
#endif
typedef struct st_list {
struct st_list *prev,*next;
void *data;
} LIST;
typedef int (*list_walk_action)(void *,void *);
extern LIST *list_add(LIST *root,LIST *element);
extern LIST *list_delete(LIST *root,LIST *element);
extern LIST *list_cons(void *data,LIST *root);
extern LIST *list_reverse(LIST *root);
extern void list_free(LIST *root,unsigned int free_data);
extern unsigned int list_length(LIST *);
extern int list_walk(LIST *,list_walk_action action,gptr argument);
#define list_rest(a) ((a)->next)
#define list_push(a,b) (a)=list_cons((b),(a))
#define list_pop(A) {LIST *old=(A); (A)=list_delete(old,old) ; my_free((gptr) old,MYF(MY_FAE)); }
#ifdef __cplusplus
}
#endif
#endif
+903
View File
@@ -0,0 +1,903 @@
/* Copyright (C) 2000-2003 MySQL AB
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#ifndef _my_sys_h
#define _my_sys_h
C_MODE_START
#ifdef HAVE_AIOWAIT
#include <sys/asynch.h> /* Used by record-cache */
typedef struct my_aio_result {
aio_result_t result;
int pending;
} my_aio_result;
#endif
#ifndef THREAD
extern int NEAR my_errno; /* Last error in mysys */
#else
#include <my_pthread.h>
#endif
#ifndef _m_ctype_h
#include <m_ctype.h> /* for CHARSET_INFO */
#endif
#include <stdarg.h>
#include <typelib.h>
#define MYSYS_PROGRAM_USES_CURSES() { error_handler_hook = my_message_curses; mysys_uses_curses=1; }
#define MYSYS_PROGRAM_DONT_USE_CURSES() { error_handler_hook = my_message_no_curses; mysys_uses_curses=0;}
#define MY_INIT(name); { my_progname= name; my_init(); }
#define ERRMSGSIZE (SC_MAXWIDTH) /* Max length of a error message */
#define NRERRBUFFS (2) /* Buffers for parameters */
#define MY_FILE_ERROR ((uint) ~0)
/* General bitmaps for my_func's */
#define MY_FFNF 1 /* Fatal if file not found */
#define MY_FNABP 2 /* Fatal if not all bytes read/writen */
#define MY_NABP 4 /* Error if not all bytes read/writen */
#define MY_FAE 8 /* Fatal if any error */
#define MY_WME 16 /* Write message on error */
#define MY_WAIT_IF_FULL 32 /* Wait and try again if disk full error */
#define MY_IGNORE_BADFD 32 /* my_sync: ignore 'bad descriptor' errors */
#define MY_RAID 64 /* Support for RAID */
#define MY_FULL_IO 512 /* For my_read - loop intil I/O is complete */
#define MY_DONT_CHECK_FILESIZE 128 /* Option to init_io_cache() */
#define MY_LINK_WARNING 32 /* my_redel() gives warning if links */
#define MY_COPYTIME 64 /* my_redel() copys time */
#define MY_DELETE_OLD 256 /* my_create_with_symlink() */
#define MY_RESOLVE_LINK 128 /* my_realpath(); Only resolve links */
#define MY_HOLD_ORIGINAL_MODES 128 /* my_copy() holds to file modes */
#define MY_REDEL_MAKE_BACKUP 256
#define MY_SEEK_NOT_DONE 32 /* my_lock may have to do a seek */
#define MY_DONT_WAIT 64 /* my_lock() don't wait if can't lock */
#define MY_ZEROFILL 32 /* my_malloc(), fill array with zero */
#define MY_ALLOW_ZERO_PTR 64 /* my_realloc() ; zero ptr -> malloc */
#define MY_FREE_ON_ERROR 128 /* my_realloc() ; Free old ptr on error */
#define MY_HOLD_ON_ERROR 256 /* my_realloc() ; Return old ptr on error */
#define MY_THREADSAFE 128 /* pread/pwrite: Don't allow interrupts */
#define MY_DONT_OVERWRITE_FILE 1024 /* my_copy: Don't overwrite file */
#define MY_CHECK_ERROR 1 /* Params to my_end; Check open-close */
#define MY_GIVE_INFO 2 /* Give time info about process*/
#define ME_HIGHBYTE 8 /* Shift for colours */
#define ME_NOCUR 1 /* Don't use curses message */
#define ME_OLDWIN 2 /* Use old window */
#define ME_BELL 4 /* Ring bell then printing message */
#define ME_HOLDTANG 8 /* Don't delete last keys */
#define ME_WAITTOT 16 /* Wait for errtime secs of for a action */
#define ME_WAITTANG 32 /* Wait for a user action */
#define ME_NOREFRESH 64 /* Dont refresh screen */
#define ME_NOINPUT 128 /* Dont use the input libary */
#define ME_COLOUR1 ((1 << ME_HIGHBYTE)) /* Possibly error-colours */
#define ME_COLOUR2 ((2 << ME_HIGHBYTE))
#define ME_COLOUR3 ((3 << ME_HIGHBYTE))
/* Bits in last argument to fn_format */
#define MY_REPLACE_DIR 1 /* replace dir in name with 'dir' */
#define MY_REPLACE_EXT 2 /* replace extension with 'ext' */
#define MY_UNPACK_FILENAME 4 /* Unpack name (~ -> home) */
#define MY_PACK_FILENAME 8 /* Pack name (home -> ~) */
#define MY_RESOLVE_SYMLINKS 16 /* Resolve all symbolic links */
#define MY_RETURN_REAL_PATH 32 /* return full path for file */
#define MY_SAFE_PATH 64 /* Return NULL if too long path */
#define MY_RELATIVE_PATH 128 /* name is relative to 'dir' */
/* My seek flags */
#define MY_SEEK_SET 0
#define MY_SEEK_CUR 1
#define MY_SEEK_END 2
/* Some constants */
#define MY_WAIT_FOR_USER_TO_FIX_PANIC 60 /* in seconds */
#define MY_WAIT_GIVE_USER_A_MESSAGE 10 /* Every 10 times of prev */
#define MIN_COMPRESS_LENGTH 50 /* Don't compress small bl. */
#define DFLT_INIT_HITS 3
/* root_alloc flags */
#define MY_KEEP_PREALLOC 1
#define MY_MARK_BLOCKS_FREE 2 /* move used to free list and reuse them */
/* Internal error numbers (for assembler functions) */
#define MY_ERRNO_EDOM 33
#define MY_ERRNO_ERANGE 34
/* Bits for get_date timeflag */
#define GETDATE_DATE_TIME 1
#define GETDATE_SHORT_DATE 2
#define GETDATE_HHMMSSTIME 4
#define GETDATE_GMT 8
#define GETDATE_FIXEDLENGTH 16
/* defines when allocating data */
#ifdef SAFEMALLOC
#define my_malloc(SZ,FLAG) _mymalloc((SZ), __FILE__, __LINE__, FLAG )
#define my_malloc_ci(SZ,FLAG) _mymalloc((SZ), sFile, uLine, FLAG )
#define my_realloc(PTR,SZ,FLAG) _myrealloc((PTR), (SZ), __FILE__, __LINE__, FLAG )
#define my_checkmalloc() _sanity( __FILE__, __LINE__ )
#define my_free(PTR,FLAG) _myfree((PTR), __FILE__, __LINE__,FLAG)
#define my_memdup(A,B,C) _my_memdup((A),(B), __FILE__,__LINE__,C)
#define my_strdup(A,C) _my_strdup((A), __FILE__,__LINE__,C)
#define my_strdup_with_length(A,B,C) _my_strdup_with_length((A),(B),__FILE__,__LINE__,C)
#define TRASH(A,B) bfill(A, B, 0x8F)
#define QUICK_SAFEMALLOC sf_malloc_quick=1
#define NORMAL_SAFEMALLOC sf_malloc_quick=0
extern uint sf_malloc_prehunc,sf_malloc_endhunc,sf_malloc_quick;
extern ulonglong sf_malloc_mem_limit;
#define CALLER_INFO_PROTO , const char *sFile, uint uLine
#define CALLER_INFO , __FILE__, __LINE__
#define ORIG_CALLER_INFO , sFile, uLine
#else
#define my_checkmalloc()
#undef TERMINATE
#define TERMINATE(A) {}
#define QUICK_SAFEMALLOC
#define NORMAL_SAFEMALLOC
extern gptr my_malloc(uint Size,myf MyFlags);
#define my_malloc_ci(SZ,FLAG) my_malloc( SZ, FLAG )
extern gptr my_realloc(gptr oldpoint,uint Size,myf MyFlags);
extern void my_no_flags_free(gptr ptr);
extern gptr my_memdup(const byte *from,uint length,myf MyFlags);
extern char *my_strdup(const char *from,myf MyFlags);
extern char *my_strdup_with_length(const byte *from, uint length,
myf MyFlags);
/* we do use FG (as a no-op) in below so that a typo on FG is caught */
#define my_free(PTR,FG) ((void)FG,my_no_flags_free(PTR))
#define CALLER_INFO_PROTO /* nothing */
#define CALLER_INFO /* nothing */
#define ORIG_CALLER_INFO /* nothing */
#define TRASH(A,B) /* nothing */
#endif
#ifdef HAVE_LARGE_PAGES
extern uint my_get_large_page_size(void);
extern gptr my_large_malloc(uint size, myf my_flags);
extern void my_large_free(gptr ptr, myf my_flags);
#else
#define my_get_large_page_size() (0)
#define my_large_malloc(A,B) my_malloc_lock((A),(B))
#define my_large_free(A,B) my_free_lock((A),(B))
#endif /* HAVE_LARGE_PAGES */
#ifdef HAVE_ALLOCA
#if defined(_AIX) && !defined(__GNUC__) && !defined(_AIX43)
#pragma alloca
#endif /* _AIX */
#if defined(__MWERKS__)
#undef alloca
#define alloca _alloca
#endif /* __MWERKS__ */
#if defined(__GNUC__) && !defined(HAVE_ALLOCA_H) && ! defined(alloca)
#define alloca __builtin_alloca
#endif /* GNUC */
#define my_alloca(SZ) alloca((size_t) (SZ))
#define my_afree(PTR) {}
#else
#define my_alloca(SZ) my_malloc(SZ,MYF(0))
#define my_afree(PTR) my_free(PTR,MYF(MY_WME))
#endif /* HAVE_ALLOCA */
#ifdef MSDOS
#ifdef __ZTC__
void * __CDECL halloc(long count,size_t length);
void __CDECL hfree(void *ptr);
#endif
#if defined(USE_HALLOC)
#if defined(_VCM_) || defined(M_IC80386)
#undef USE_HALLOC
#endif
#endif
#ifdef USE_HALLOC
#define malloc(a) halloc((long) (a),1)
#define free(a) hfree(a)
#endif
#endif /* MSDOS */
#ifndef errno /* did we already get it? */
#ifdef HAVE_ERRNO_AS_DEFINE
#include <errno.h> /* errno is a define */
#else
extern int errno; /* declare errno */
#endif
#endif /* #ifndef errno */
extern char NEAR errbuff[NRERRBUFFS][ERRMSGSIZE];
extern char *home_dir; /* Home directory for user */
extern const char *my_progname; /* program-name (printed in errors) */
extern char NEAR curr_dir[]; /* Current directory for user */
extern int (*error_handler_hook)(uint my_err, const char *str,myf MyFlags);
extern int (*fatal_error_handler_hook)(uint my_err, const char *str,
myf MyFlags);
extern uint my_file_limit;
#ifdef HAVE_LARGE_PAGES
extern my_bool my_use_large_pages;
extern uint my_large_page_size;
#endif
/* charsets */
extern CHARSET_INFO *default_charset_info;
extern CHARSET_INFO *all_charsets[256];
extern CHARSET_INFO compiled_charsets[];
/* statistics */
extern ulong my_file_opened,my_stream_opened, my_tmp_file_created;
extern uint mysys_usage_id;
extern my_bool my_init_done;
/* Point to current my_message() */
extern void (*my_sigtstp_cleanup)(void),
/* Executed before jump to shell */
(*my_sigtstp_restart)(void),
(*my_abort_hook)(int);
/* Executed when comming from shell */
extern int NEAR my_umask, /* Default creation mask */
NEAR my_umask_dir,
NEAR my_recived_signals, /* Signals we have got */
NEAR my_safe_to_handle_signal, /* Set when allowed to SIGTSTP */
NEAR my_dont_interrupt; /* call remember_intr when set */
extern my_bool NEAR mysys_uses_curses, my_use_symdir;
extern ulong sf_malloc_cur_memory, sf_malloc_max_memory;
extern ulong my_default_record_cache_size;
extern my_bool NEAR my_disable_locking,NEAR my_disable_async_io,
NEAR my_disable_flush_key_blocks, NEAR my_disable_symlinks;
extern char wild_many,wild_one,wild_prefix;
extern const char *charsets_dir;
extern char *defaults_extra_file;
extern const char *defaults_group_suffix;
extern const char *defaults_file;
extern my_bool timed_mutexes;
typedef struct wild_file_pack /* Struct to hold info when selecting files */
{
uint wilds; /* How many wildcards */
uint not_pos; /* Start of not-theese-files */
my_string *wild; /* Pointer to wildcards */
} WF_PACK;
enum loglevel {
ERROR_LEVEL,
WARNING_LEVEL,
INFORMATION_LEVEL
};
enum cache_type
{
TYPE_NOT_SET= 0, READ_CACHE, WRITE_CACHE,
SEQ_READ_APPEND /* sequential read or append */,
READ_FIFO, READ_NET,WRITE_NET};
enum flush_type
{
FLUSH_KEEP, FLUSH_RELEASE, FLUSH_IGNORE_CHANGED, FLUSH_FORCE_WRITE
};
typedef struct st_record_cache /* Used when cacheing records */
{
File file;
int rc_seek,error,inited;
uint rc_length,read_length,reclength;
my_off_t rc_record_pos,end_of_file;
byte *rc_buff,*rc_buff2,*rc_pos,*rc_end,*rc_request_pos;
#ifdef HAVE_AIOWAIT
int use_async_io;
my_aio_result aio_result;
#endif
enum cache_type type;
} RECORD_CACHE;
enum file_type
{
UNOPEN = 0, FILE_BY_OPEN, FILE_BY_CREATE, STREAM_BY_FOPEN, STREAM_BY_FDOPEN,
FILE_BY_MKSTEMP, FILE_BY_DUP
};
struct st_my_file_info
{
my_string name;
enum file_type type;
#if defined(THREAD) && !defined(HAVE_PREAD)
pthread_mutex_t mutex;
#endif
};
extern struct st_my_file_info *my_file_info;
typedef struct st_my_tmpdir
{
char **list;
uint cur, max;
#ifdef THREAD
pthread_mutex_t mutex;
#endif
} MY_TMPDIR;
typedef struct st_dynamic_array
{
char *buffer;
uint elements,max_element;
uint alloc_increment;
uint size_of_element;
} DYNAMIC_ARRAY;
typedef struct st_dynamic_string
{
char *str;
uint length,max_length,alloc_increment;
} DYNAMIC_STRING;
struct st_io_cache;
typedef int (*IO_CACHE_CALLBACK)(struct st_io_cache*);
#ifdef THREAD
typedef struct st_io_cache_share
{
/* to sync on reads into buffer */
pthread_mutex_t mutex;
pthread_cond_t cond;
int count, total;
/* actual IO_CACHE that filled the buffer */
struct st_io_cache *active;
#ifdef NOT_YET_IMPLEMENTED
/* whether the structure should be free'd */
my_bool alloced;
#endif
} IO_CACHE_SHARE;
#endif
typedef struct st_io_cache /* Used when cacheing files */
{
/* Offset in file corresponding to the first byte of byte* buffer. */
my_off_t pos_in_file;
/*
The offset of end of file for READ_CACHE and WRITE_CACHE.
For SEQ_READ_APPEND it the maximum of the actual end of file and
the position represented by read_end.
*/
my_off_t end_of_file;
/* Points to current read position in the buffer */
byte *read_pos;
/* the non-inclusive boundary in the buffer for the currently valid read */
byte *read_end;
byte *buffer; /* The read buffer */
/* Used in ASYNC_IO */
byte *request_pos;
/* Only used in WRITE caches and in SEQ_READ_APPEND to buffer writes */
byte *write_buffer;
/*
Only used in SEQ_READ_APPEND, and points to the current read position
in the write buffer. Note that reads in SEQ_READ_APPEND caches can
happen from both read buffer (byte* buffer) and write buffer
(byte* write_buffer).
*/
byte *append_read_pos;
/* Points to current write position in the write buffer */
byte *write_pos;
/* The non-inclusive boundary of the valid write area */
byte *write_end;
/*
Current_pos and current_end are convenience variables used by
my_b_tell() and other routines that need to know the current offset
current_pos points to &write_pos, and current_end to &write_end in a
WRITE_CACHE, and &read_pos and &read_end respectively otherwise
*/
byte **current_pos, **current_end;
#ifdef THREAD
/*
The lock is for append buffer used in SEQ_READ_APPEND cache
need mutex copying from append buffer to read buffer.
*/
pthread_mutex_t append_buffer_lock;
/*
The following is used when several threads are reading the
same file in parallel. They are synchronized on disk
accesses reading the cached part of the file asynchronously.
It should be set to NULL to disable the feature. Only
READ_CACHE mode is supported.
*/
IO_CACHE_SHARE *share;
#endif
/*
A caller will use my_b_read() macro to read from the cache
if the data is already in cache, it will be simply copied with
memcpy() and internal variables will be accordinging updated with
no functions invoked. However, if the data is not fully in the cache,
my_b_read() will call read_function to fetch the data. read_function
must never be invoked directly.
*/
int (*read_function)(struct st_io_cache *,byte *,uint);
/*
Same idea as in the case of read_function, except my_b_write() needs to
be replaced with my_b_append() for a SEQ_READ_APPEND cache
*/
int (*write_function)(struct st_io_cache *,const byte *,uint);
/*
Specifies the type of the cache. Depending on the type of the cache
certain operations might not be available and yield unpredicatable
results. Details to be documented later
*/
enum cache_type type;
/*
Callbacks when the actual read I/O happens. These were added and
are currently used for binary logging of LOAD DATA INFILE - when a
block is read from the file, we create a block create/append event, and
when IO_CACHE is closed, we create an end event. These functions could,
of course be used for other things
*/
IO_CACHE_CALLBACK pre_read;
IO_CACHE_CALLBACK post_read;
IO_CACHE_CALLBACK pre_close;
/*
Counts the number of times, when we were forced to use disk. We use it to
increase the binlog_cache_disk_use status variable.
*/
ulong disk_writes;
void* arg; /* for use by pre/post_read */
char *file_name; /* if used with 'open_cached_file' */
char *dir,*prefix;
File file; /* file descriptor */
/*
seek_not_done is set by my_b_seek() to inform the upcoming read/write
operation that a seek needs to be preformed prior to the actual I/O
error is 0 if the cache operation was successful, -1 if there was a
"hard" error, and the actual number of I/O-ed bytes if the read/write was
partial.
*/
int seek_not_done,error;
/* buffer_length is memory size allocated for buffer or write_buffer */
uint buffer_length;
/* read_length is the same as buffer_length except when we use async io */
uint read_length;
myf myflags; /* Flags used to my_read/my_write */
/*
alloced_buffer is 1 if the buffer was allocated by init_io_cache() and
0 if it was supplied by the user.
Currently READ_NET is the only one that will use a buffer allocated
somewhere else
*/
my_bool alloced_buffer;
#ifdef HAVE_AIOWAIT
/*
As inidicated by ifdef, this is for async I/O, which is not currently
used (because it's not reliable on all systems)
*/
uint inited;
my_off_t aio_read_pos;
my_aio_result aio_result;
#endif
} IO_CACHE;
typedef int (*qsort2_cmp)(const void *, const void *, const void *);
/* defines for mf_iocache */
/* Test if buffer is inited */
#define my_b_clear(info) (info)->buffer=0
#define my_b_inited(info) (info)->buffer
#define my_b_EOF INT_MIN
#define my_b_read(info,Buffer,Count) \
((info)->read_pos + (Count) <= (info)->read_end ?\
(memcpy(Buffer,(info)->read_pos,(size_t) (Count)), \
((info)->read_pos+=(Count)),0) :\
(*(info)->read_function)((info),Buffer,Count))
#define my_b_write(info,Buffer,Count) \
((info)->write_pos + (Count) <=(info)->write_end ?\
(memcpy((info)->write_pos, (Buffer), (size_t)(Count)),\
((info)->write_pos+=(Count)),0) : \
(*(info)->write_function)((info),(Buffer),(Count)))
#define my_b_get(info) \
((info)->read_pos != (info)->read_end ?\
((info)->read_pos++, (int) (uchar) (info)->read_pos[-1]) :\
_my_b_get(info))
/* my_b_write_byte dosn't have any err-check */
#define my_b_write_byte(info,chr) \
(((info)->write_pos < (info)->write_end) ?\
((*(info)->write_pos++)=(chr)) :\
(_my_b_write(info,0,0) , ((*(info)->write_pos++)=(chr))))
#define my_b_fill_cache(info) \
(((info)->read_end=(info)->read_pos),(*(info)->read_function)(info,0,0))
#define my_b_tell(info) ((info)->pos_in_file + \
(uint) (*(info)->current_pos - (info)->request_pos))
/* tell write offset in the SEQ_APPEND cache */
my_off_t my_b_append_tell(IO_CACHE* info);
my_off_t my_b_safe_tell(IO_CACHE* info); /* picks the correct tell() */
#define my_b_bytes_in_cache(info) (uint) (*(info)->current_end - \
*(info)->current_pos)
typedef uint32 ha_checksum;
/* Define the type of function to be passed to process_default_option_files */
typedef int (*Process_option_func)(void *ctx, const char *group_name,
const char *option);
#include <my_alloc.h>
/* Prototypes for mysys and my_func functions */
extern int my_copy(const char *from,const char *to,myf MyFlags);
extern int my_append(const char *from,const char *to,myf MyFlags);
extern int my_delete(const char *name,myf MyFlags);
extern int my_getwd(my_string buf,uint size,myf MyFlags);
extern int my_setwd(const char *dir,myf MyFlags);
extern int my_lock(File fd,int op,my_off_t start, my_off_t length,myf MyFlags);
extern gptr my_once_alloc(uint Size,myf MyFlags);
extern void my_once_free(void);
extern char *my_once_strdup(const char *src,myf myflags);
extern char *my_once_memdup(const char *src, uint len, myf myflags);
extern File my_open(const char *FileName,int Flags,myf MyFlags);
extern File my_register_filename(File fd, const char *FileName,
enum file_type type_of_file,
uint error_message_number, myf MyFlags);
extern File my_create(const char *FileName,int CreateFlags,
int AccsesFlags, myf MyFlags);
extern int my_close(File Filedes,myf MyFlags);
extern File my_dup(File file, myf MyFlags);
extern int my_mkdir(const char *dir, int Flags, myf MyFlags);
extern int my_readlink(char *to, const char *filename, myf MyFlags);
extern int my_realpath(char *to, const char *filename, myf MyFlags);
extern File my_create_with_symlink(const char *linkname, const char *filename,
int createflags, int access_flags,
myf MyFlags);
extern int my_delete_with_symlink(const char *name, myf MyFlags);
extern int my_rename_with_symlink(const char *from,const char *to,myf MyFlags);
extern int my_symlink(const char *content, const char *linkname, myf MyFlags);
extern uint my_read(File Filedes,byte *Buffer,uint Count,myf MyFlags);
extern uint my_pread(File Filedes,byte *Buffer,uint Count,my_off_t offset,
myf MyFlags);
extern int my_rename(const char *from,const char *to,myf MyFlags);
extern my_off_t my_seek(File fd,my_off_t pos,int whence,myf MyFlags);
extern my_off_t my_tell(File fd,myf MyFlags);
extern uint my_write(File Filedes,const byte *Buffer,uint Count,
myf MyFlags);
extern uint my_pwrite(File Filedes,const byte *Buffer,uint Count,
my_off_t offset,myf MyFlags);
extern uint my_fread(FILE *stream,byte *Buffer,uint Count,myf MyFlags);
extern uint my_fwrite(FILE *stream,const byte *Buffer,uint Count,
myf MyFlags);
extern my_off_t my_fseek(FILE *stream,my_off_t pos,int whence,myf MyFlags);
extern my_off_t my_ftell(FILE *stream,myf MyFlags);
extern gptr _mymalloc(uint uSize,const char *sFile,
uint uLine, myf MyFlag);
extern gptr _myrealloc(gptr pPtr,uint uSize,const char *sFile,
uint uLine, myf MyFlag);
extern gptr my_multi_malloc _VARARGS((myf MyFlags, ...));
extern void _myfree(gptr pPtr,const char *sFile,uint uLine, myf MyFlag);
extern int _sanity(const char *sFile,unsigned int uLine);
extern gptr _my_memdup(const byte *from,uint length,
const char *sFile, uint uLine,myf MyFlag);
extern my_string _my_strdup(const char *from, const char *sFile, uint uLine,
myf MyFlag);
extern char *_my_strdup_with_length(const byte *from, uint length,
const char *sFile, uint uLine,
myf MyFlag);
#ifdef __WIN__
extern int my_access(const char *path, int amode);
#else
#define my_access access
#endif
extern int check_if_legal_filename(const char *path);
#ifndef TERMINATE
extern void TERMINATE(FILE *file);
#endif
extern void init_glob_errs(void);
extern FILE *my_fopen(const char *FileName,int Flags,myf MyFlags);
extern FILE *my_fdopen(File Filedes,const char *name, int Flags,myf MyFlags);
extern int my_fclose(FILE *fd,myf MyFlags);
extern int my_chsize(File fd,my_off_t newlength, int filler, myf MyFlags);
extern int my_sync(File fd, myf my_flags);
extern int my_error _VARARGS((int nr,myf MyFlags, ...));
extern int my_printf_error _VARARGS((uint my_err, const char *format,
myf MyFlags, ...)
__attribute__ ((format (printf, 2, 4))));
extern int my_error_register(const char **errmsgs, int first, int last);
extern const char **my_error_unregister(int first, int last);
extern int my_message(uint my_err, const char *str,myf MyFlags);
extern int my_message_no_curses(uint my_err, const char *str,myf MyFlags);
extern int my_message_curses(uint my_err, const char *str,myf MyFlags);
extern my_bool my_init(void);
extern void my_end(int infoflag);
extern int my_redel(const char *from, const char *to, int MyFlags);
extern int my_copystat(const char *from, const char *to, int MyFlags);
extern my_string my_filename(File fd);
#ifndef THREAD
extern void dont_break(void);
extern void allow_break(void);
#else
#define dont_break()
#define allow_break()
#endif
extern my_bool init_tmpdir(MY_TMPDIR *tmpdir, const char *pathlist);
extern char *my_tmpdir(MY_TMPDIR *tmpdir);
extern void free_tmpdir(MY_TMPDIR *tmpdir);
extern void my_remember_signal(int signal_number,sig_handler (*func)(int));
extern uint dirname_part(my_string to,const char *name);
extern uint dirname_length(const char *name);
#define base_name(A) (A+dirname_length(A))
extern int test_if_hard_path(const char *dir_name);
extern my_bool has_path(const char *name);
extern char *convert_dirname(char *to, const char *from, const char *from_end);
extern void to_unix_path(my_string name);
extern my_string fn_ext(const char *name);
extern my_string fn_same(my_string toname,const char *name,int flag);
extern my_string fn_format(my_string to,const char *name,const char *dir,
const char *form, uint flag);
extern size_s strlength(const char *str);
extern void pack_dirname(my_string to,const char *from);
extern uint unpack_dirname(my_string to,const char *from);
extern uint cleanup_dirname(my_string to,const char *from);
extern uint system_filename(my_string to,const char *from);
extern uint unpack_filename(my_string to,const char *from);
extern my_string intern_filename(my_string to,const char *from);
extern my_string directory_file_name(my_string dst, const char *src);
extern int pack_filename(my_string to, const char *name, size_s max_length);
extern my_string my_path(my_string to,const char *progname,
const char *own_pathname_part);
extern my_string my_load_path(my_string to, const char *path,
const char *own_path_prefix);
extern int wild_compare(const char *str,const char *wildstr,pbool str_is_pattern);
extern WF_PACK *wf_comp(my_string str);
extern int wf_test(struct wild_file_pack *wf_pack,const char *name);
extern void wf_end(struct wild_file_pack *buffer);
extern size_s strip_sp(my_string str);
extern void get_date(my_string to,int timeflag,time_t use_time);
extern void soundex(CHARSET_INFO *, my_string out_pntr, my_string in_pntr,pbool remove_garbage);
extern int init_record_cache(RECORD_CACHE *info,uint cachesize,File file,
uint reclength,enum cache_type type,
pbool use_async_io);
extern int read_cache_record(RECORD_CACHE *info,byte *to);
extern int end_record_cache(RECORD_CACHE *info);
extern int write_cache_record(RECORD_CACHE *info,my_off_t filepos,
const byte *record,uint length);
extern int flush_write_cache(RECORD_CACHE *info);
extern long my_clock(void);
extern sig_handler sigtstp_handler(int signal_number);
extern void handle_recived_signals(void);
extern sig_handler my_set_alarm_variable(int signo);
extern void my_string_ptr_sort(void *base,uint items,size_s size);
extern void radixsort_for_str_ptr(uchar* base[], uint number_of_elements,
size_s size_of_element,uchar *buffer[]);
extern qsort_t qsort2(void *base_ptr, size_t total_elems, size_t size,
qsort2_cmp cmp, void *cmp_argument);
extern qsort2_cmp get_ptr_compare(uint);
void my_store_ptr(byte *buff, uint pack_length, my_off_t pos);
my_off_t my_get_ptr(byte *ptr, uint pack_length);
extern int init_io_cache(IO_CACHE *info,File file,uint cachesize,
enum cache_type type,my_off_t seek_offset,
pbool use_async_io, myf cache_myflags);
extern my_bool reinit_io_cache(IO_CACHE *info,enum cache_type type,
my_off_t seek_offset,pbool use_async_io,
pbool clear_cache);
extern void setup_io_cache(IO_CACHE* info);
extern int _my_b_read(IO_CACHE *info,byte *Buffer,uint Count);
#ifdef THREAD
extern int _my_b_read_r(IO_CACHE *info,byte *Buffer,uint Count);
extern void init_io_cache_share(IO_CACHE *info,
IO_CACHE_SHARE *s, uint num_threads);
extern void remove_io_thread(IO_CACHE *info);
#endif
extern int _my_b_seq_read(IO_CACHE *info,byte *Buffer,uint Count);
extern int _my_b_net_read(IO_CACHE *info,byte *Buffer,uint Count);
extern int _my_b_get(IO_CACHE *info);
extern int _my_b_async_read(IO_CACHE *info,byte *Buffer,uint Count);
extern int _my_b_write(IO_CACHE *info,const byte *Buffer,uint Count);
extern int my_b_append(IO_CACHE *info,const byte *Buffer,uint Count);
extern int my_b_safe_write(IO_CACHE *info,const byte *Buffer,uint Count);
extern int my_block_write(IO_CACHE *info, const byte *Buffer,
uint Count, my_off_t pos);
extern int my_b_flush_io_cache(IO_CACHE *info, int need_append_buffer_lock);
#define flush_io_cache(info) my_b_flush_io_cache((info),1)
extern int end_io_cache(IO_CACHE *info);
extern uint my_b_fill(IO_CACHE *info);
extern void my_b_seek(IO_CACHE *info,my_off_t pos);
extern uint my_b_gets(IO_CACHE *info, char *to, uint max_length);
extern my_off_t my_b_filelength(IO_CACHE *info);
extern uint my_b_printf(IO_CACHE *info, const char* fmt, ...);
extern uint my_b_vprintf(IO_CACHE *info, const char* fmt, va_list ap);
extern my_bool open_cached_file(IO_CACHE *cache,const char *dir,
const char *prefix, uint cache_size,
myf cache_myflags);
extern my_bool real_open_cached_file(IO_CACHE *cache);
extern void close_cached_file(IO_CACHE *cache);
File create_temp_file(char *to, const char *dir, const char *pfx,
int mode, myf MyFlags);
#define my_init_dynamic_array(A,B,C,D) init_dynamic_array(A,B,C,D CALLER_INFO)
#define my_init_dynamic_array_ci(A,B,C,D) init_dynamic_array(A,B,C,D ORIG_CALLER_INFO)
extern my_bool init_dynamic_array(DYNAMIC_ARRAY *array,uint element_size,
uint init_alloc,uint alloc_increment
CALLER_INFO_PROTO);
extern my_bool insert_dynamic(DYNAMIC_ARRAY *array,gptr element);
extern byte *alloc_dynamic(DYNAMIC_ARRAY *array);
extern byte *pop_dynamic(DYNAMIC_ARRAY*);
extern my_bool set_dynamic(DYNAMIC_ARRAY *array,gptr element,uint array_index);
extern void get_dynamic(DYNAMIC_ARRAY *array,gptr element,uint array_index);
extern void delete_dynamic(DYNAMIC_ARRAY *array);
extern void delete_dynamic_element(DYNAMIC_ARRAY *array, uint array_index);
extern void freeze_size(DYNAMIC_ARRAY *array);
#define dynamic_array_ptr(array,array_index) ((array)->buffer+(array_index)*(array)->size_of_element)
#define dynamic_element(array,array_index,type) ((type)((array)->buffer) +(array_index))
#define push_dynamic(A,B) insert_dynamic(A,B)
#define reset_dynamic(array) ((array)->elements= 0)
extern my_bool init_dynamic_string(DYNAMIC_STRING *str, const char *init_str,
uint init_alloc,uint alloc_increment);
extern my_bool dynstr_append(DYNAMIC_STRING *str, const char *append);
my_bool dynstr_append_mem(DYNAMIC_STRING *str, const char *append,
uint length);
extern my_bool dynstr_set(DYNAMIC_STRING *str, const char *init_str);
extern my_bool dynstr_realloc(DYNAMIC_STRING *str, ulong additional_size);
extern void dynstr_free(DYNAMIC_STRING *str);
#ifdef HAVE_MLOCK
extern byte *my_malloc_lock(uint length,myf flags);
extern void my_free_lock(byte *ptr,myf flags);
#else
#define my_malloc_lock(A,B) my_malloc((A),(B))
#define my_free_lock(A,B) my_free((A),(B))
#endif
#define alloc_root_inited(A) ((A)->min_malloc != 0)
#define ALLOC_ROOT_MIN_BLOCK_SIZE (MALLOC_OVERHEAD + sizeof(USED_MEM) + 8)
#define clear_alloc_root(A) do { (A)->free= (A)->used= (A)->pre_alloc= 0; (A)->min_malloc=0;} while(0)
extern void init_alloc_root(MEM_ROOT *mem_root, uint block_size,
uint pre_alloc_size);
extern gptr alloc_root(MEM_ROOT *mem_root,unsigned int Size);
extern gptr multi_alloc_root(MEM_ROOT *mem_root, ...);
extern void free_root(MEM_ROOT *root, myf MyFLAGS);
extern void set_prealloc_root(MEM_ROOT *root, char *ptr);
extern void reset_root_defaults(MEM_ROOT *mem_root, uint block_size,
uint prealloc_size);
extern char *strdup_root(MEM_ROOT *root,const char *str);
extern char *strmake_root(MEM_ROOT *root,const char *str,uint len);
extern char *memdup_root(MEM_ROOT *root,const char *str,uint len);
extern int get_defaults_options(int argc, char **argv,
char **defaults, char **extra_defaults,
char **group_suffix);
extern int load_defaults(const char *conf_file, const char **groups,
int *argc, char ***argv);
extern int modify_defaults_file(const char *file_location, const char *option,
const char *option_value,
const char *section_name, int remove_option);
extern int my_search_option_files(const char *conf_file, int *argc,
char ***argv, uint *args_used,
Process_option_func func, void *func_ctx);
extern void free_defaults(char **argv);
extern void my_print_default_files(const char *conf_file);
extern void print_defaults(const char *conf_file, const char **groups);
extern my_bool my_compress(byte *, ulong *, ulong *);
extern my_bool my_uncompress(byte *, ulong *, ulong *);
extern byte *my_compress_alloc(const byte *packet, ulong *len, ulong *complen);
extern ha_checksum my_checksum(ha_checksum crc, const byte *mem, uint count);
extern uint my_bit_log2(ulong value);
extern uint my_count_bits(ulonglong v);
extern uint my_count_bits_ushort(ushort v);
extern void my_sleep(ulong m_seconds);
extern ulong crc32(ulong crc, const uchar *buf, uint len);
extern uint my_set_max_open_files(uint files);
void my_free_open_file_info(void);
ulonglong my_getsystime(void);
my_bool my_gethwaddr(uchar *to);
#ifdef HAVE_SYS_MMAN_H
#include <sys/mman.h>
#ifndef MAP_NOSYNC
#define MAP_NOSYNC 0
#endif
#define my_mmap(a,b,c,d,e,f) mmap(a,b,c,d,e,f)
#ifdef HAVE_GETPAGESIZE
#define my_getpagesize() getpagesize()
#else
/* qnx ? */
#define my_getpagesize() 8192
#endif
#define my_munmap(a,b) munmap((a),(b))
#else
/* not a complete set of mmap() flags, but only those that nesessary */
#define PROT_READ 1
#define PROT_WRITE 2
#define MAP_SHARED 0x0001
#define MAP_NOSYNC 0x0800
#define MAP_FAILED ((void *)-1)
#define MS_SYNC 0x0000
#ifndef __NETWARE__
#define HAVE_MMAP
#endif
int my_getpagesize(void);
void *my_mmap(void *, size_t, int, int, int, my_off_t);
int my_munmap(void *, size_t);
#endif
int my_msync(int, void *, size_t, int);
/* character sets */
extern uint get_charset_number(const char *cs_name, uint cs_flags);
extern uint get_collation_number(const char *name);
extern const char *get_charset_name(uint cs_number);
extern CHARSET_INFO *get_charset(uint cs_number, myf flags);
extern CHARSET_INFO *get_charset_by_name(const char *cs_name, myf flags);
extern CHARSET_INFO *get_charset_by_csname(const char *cs_name,
uint cs_flags, myf my_flags);
extern void free_charsets(void);
extern char *get_charsets_dir(char *buf);
extern my_bool my_charset_same(CHARSET_INFO *cs1, CHARSET_INFO *cs2);
extern my_bool init_compiled_charsets(myf flags);
extern void add_compiled_collation(CHARSET_INFO *cs);
extern ulong escape_string_for_mysql(CHARSET_INFO *charset_info,
char *to, ulong to_length,
const char *from, ulong length);
#ifdef __WIN__
#define BACKSLASH_MBTAIL
/* File system character set */
extern CHARSET_INFO *fs_character_set(void);
#endif
extern ulong escape_quotes_for_mysql(CHARSET_INFO *charset_info,
char *to, ulong to_length,
const char *from, ulong length);
extern void thd_increment_bytes_sent(ulong length);
extern void thd_increment_bytes_received(ulong length);
extern void thd_increment_net_big_packet_count(ulong length);
#ifdef __WIN__
extern my_bool have_tcpip; /* Is set if tcpip is used */
/* implemented in my_windac.c */
int my_security_attr_create(SECURITY_ATTRIBUTES **psa, const char **perror,
DWORD owner_rights, DWORD everybody_rights);
void my_security_attr_free(SECURITY_ATTRIBUTES *sa);
/* implemented in my_conio.c */
char* my_cgets(char *string, unsigned long clen, unsigned long* plen);
#endif
#ifdef __NETWARE__
void netware_reg_user(const char *ip, const char *user,
const char *application);
#endif
C_MODE_END
#include "raid.h"
#endif /* _my_sys_h */
+839
View File
@@ -0,0 +1,839 @@
/* Copyright (C) 2000-2003 MySQL AB
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#ifndef _mysql_h
#define _mysql_h
#ifdef __CYGWIN__ /* CYGWIN implements a UNIX API */
#undef WIN
#undef _WIN
#undef _WIN32
#undef _WIN64
#undef __WIN__
#endif
#ifdef __cplusplus
extern "C" {
#endif
#ifndef _global_h /* If not standard header */
#include <sys/types.h>
#ifdef __LCC__
#include <winsock.h> /* For windows */
#endif
typedef char my_bool;
#if (defined(_WIN32) || defined(_WIN64)) && !defined(__WIN__)
#define __WIN__
#endif
#if !defined(__WIN__)
#define STDCALL
#else
#define STDCALL __stdcall
#endif
typedef char * gptr;
#ifndef my_socket_defined
#ifdef __WIN__
#define my_socket SOCKET
#else
typedef int my_socket;
#endif /* __WIN__ */
#endif /* my_socket_defined */
#endif /* _global_h */
#include "mysql_com.h"
#include "mysql_time.h"
#include "mysql_version.h"
#include "typelib.h"
#include "my_list.h" /* for LISTs used in 'MYSQL' and 'MYSQL_STMT' */
extern unsigned int mysql_port;
extern char *mysql_unix_port;
#define CLIENT_NET_READ_TIMEOUT 365*24*3600 /* Timeout on read */
#define CLIENT_NET_WRITE_TIMEOUT 365*24*3600 /* Timeout on write */
#ifdef __NETWARE__
#pragma pack(push, 8) /* 8 byte alignment */
#endif
#define IS_PRI_KEY(n) ((n) & PRI_KEY_FLAG)
#define IS_NOT_NULL(n) ((n) & NOT_NULL_FLAG)
#define IS_BLOB(n) ((n) & BLOB_FLAG)
#define IS_NUM(t) ((t) <= FIELD_TYPE_INT24 || (t) == FIELD_TYPE_YEAR || (t) == FIELD_TYPE_NEWDECIMAL)
#define IS_NUM_FIELD(f) ((f)->flags & NUM_FLAG)
#define INTERNAL_NUM_FIELD(f) (((f)->type <= FIELD_TYPE_INT24 && ((f)->type != FIELD_TYPE_TIMESTAMP || (f)->length == 14 || (f)->length == 8)) || (f)->type == FIELD_TYPE_YEAR)
typedef struct st_mysql_field {
char *name; /* Name of column */
char *org_name; /* Original column name, if an alias */
char *table; /* Table of column if column was a field */
char *org_table; /* Org table name, if table was an alias */
char *db; /* Database for table */
char *catalog; /* Catalog for table */
char *def; /* Default value (set by mysql_list_fields) */
unsigned long length; /* Width of column (create length) */
unsigned long max_length; /* Max width for selected set */
unsigned int name_length;
unsigned int org_name_length;
unsigned int table_length;
unsigned int org_table_length;
unsigned int db_length;
unsigned int catalog_length;
unsigned int def_length;
unsigned int flags; /* Div flags */
unsigned int decimals; /* Number of decimals in field */
unsigned int charsetnr; /* Character set */
enum enum_field_types type; /* Type of field. See mysql_com.h for types */
} MYSQL_FIELD;
typedef char **MYSQL_ROW; /* return data as array of strings */
typedef unsigned int MYSQL_FIELD_OFFSET; /* offset to current field */
#ifndef _global_h
#if defined(NO_CLIENT_LONG_LONG)
typedef unsigned long my_ulonglong;
#elif defined (__WIN__)
typedef unsigned __int64 my_ulonglong;
#else
typedef unsigned long long my_ulonglong;
#endif
#endif
#define MYSQL_COUNT_ERROR (~(my_ulonglong) 0)
typedef struct st_mysql_rows {
struct st_mysql_rows *next; /* list of rows */
MYSQL_ROW data;
unsigned long length;
} MYSQL_ROWS;
typedef MYSQL_ROWS *MYSQL_ROW_OFFSET; /* offset to current row */
#include "my_alloc.h"
typedef struct st_mysql_data {
my_ulonglong rows;
unsigned int fields;
MYSQL_ROWS *data;
MEM_ROOT alloc;
#if !defined(CHECK_EMBEDDED_DIFFERENCES) || defined(EMBEDDED_LIBRARY)
MYSQL_ROWS **prev_ptr;
#endif
} MYSQL_DATA;
enum mysql_option
{
MYSQL_OPT_CONNECT_TIMEOUT, MYSQL_OPT_COMPRESS, MYSQL_OPT_NAMED_PIPE,
MYSQL_INIT_COMMAND, MYSQL_READ_DEFAULT_FILE, MYSQL_READ_DEFAULT_GROUP,
MYSQL_SET_CHARSET_DIR, MYSQL_SET_CHARSET_NAME, MYSQL_OPT_LOCAL_INFILE,
MYSQL_OPT_PROTOCOL, MYSQL_SHARED_MEMORY_BASE_NAME, MYSQL_OPT_READ_TIMEOUT,
MYSQL_OPT_WRITE_TIMEOUT, MYSQL_OPT_USE_RESULT,
MYSQL_OPT_USE_REMOTE_CONNECTION, MYSQL_OPT_USE_EMBEDDED_CONNECTION,
MYSQL_OPT_GUESS_CONNECTION, MYSQL_SET_CLIENT_IP, MYSQL_SECURE_AUTH,
MYSQL_REPORT_DATA_TRUNCATION, MYSQL_OPT_RECONNECT
};
struct st_mysql_options {
unsigned int connect_timeout, read_timeout, write_timeout;
unsigned int port, protocol;
unsigned long client_flag;
char *host,*user,*password,*unix_socket,*db;
struct st_dynamic_array *init_commands;
char *my_cnf_file,*my_cnf_group, *charset_dir, *charset_name;
char *ssl_key; /* PEM key file */
char *ssl_cert; /* PEM cert file */
char *ssl_ca; /* PEM CA file */
char *ssl_capath; /* PEM directory of CA-s? */
char *ssl_cipher; /* cipher to use */
char *shared_memory_base_name;
unsigned long max_allowed_packet;
my_bool use_ssl; /* if to use SSL or not */
my_bool compress,named_pipe;
/*
On connect, find out the replication role of the server, and
establish connections to all the peers
*/
my_bool rpl_probe;
/*
Each call to mysql_real_query() will parse it to tell if it is a read
or a write, and direct it to the slave or the master
*/
my_bool rpl_parse;
/*
If set, never read from a master, only from slave, when doing
a read that is replication-aware
*/
my_bool no_master_reads;
#if !defined(CHECK_EMBEDDED_DIFFERENCES) || defined(EMBEDDED_LIBRARY)
my_bool separate_thread;
#endif
enum mysql_option methods_to_use;
char *client_ip;
/* Refuse client connecting to server if it uses old (pre-4.1.1) protocol */
my_bool secure_auth;
/* 0 - never report, 1 - always report (default) */
my_bool report_data_truncation;
/* function pointers for local infile support */
int (*local_infile_init)(void **, const char *, void *);
int (*local_infile_read)(void *, char *, unsigned int);
void (*local_infile_end)(void *);
int (*local_infile_error)(void *, char *, unsigned int);
void *local_infile_userdata;
};
enum mysql_status
{
MYSQL_STATUS_READY,MYSQL_STATUS_GET_RESULT,MYSQL_STATUS_USE_RESULT
};
enum mysql_protocol_type
{
MYSQL_PROTOCOL_DEFAULT, MYSQL_PROTOCOL_TCP, MYSQL_PROTOCOL_SOCKET,
MYSQL_PROTOCOL_PIPE, MYSQL_PROTOCOL_MEMORY
};
/*
There are three types of queries - the ones that have to go to
the master, the ones that go to a slave, and the adminstrative
type which must happen on the pivot connectioin
*/
enum mysql_rpl_type
{
MYSQL_RPL_MASTER, MYSQL_RPL_SLAVE, MYSQL_RPL_ADMIN
};
typedef struct character_set
{
unsigned int number; /* character set number */
unsigned int state; /* character set state */
const char *csname; /* collation name */
const char *name; /* character set name */
const char *comment; /* comment */
const char *dir; /* character set directory */
unsigned int mbminlen; /* min. length for multibyte strings */
unsigned int mbmaxlen; /* max. length for multibyte strings */
} MY_CHARSET_INFO;
struct st_mysql_methods;
typedef struct st_mysql
{
NET net; /* Communication parameters */
gptr connector_fd; /* ConnectorFd for SSL */
char *host,*user,*passwd,*unix_socket,*server_version,*host_info,*info;
char *db;
struct charset_info_st *charset;
MYSQL_FIELD *fields;
MEM_ROOT field_alloc;
my_ulonglong affected_rows;
my_ulonglong insert_id; /* id if insert on table with NEXTNR */
my_ulonglong extra_info; /* Not used */
unsigned long thread_id; /* Id for connection in server */
unsigned long packet_length;
unsigned int port;
unsigned long client_flag,server_capabilities;
unsigned int protocol_version;
unsigned int field_count;
unsigned int server_status;
unsigned int server_language;
unsigned int warning_count;
struct st_mysql_options options;
enum mysql_status status;
my_bool free_me; /* If free in mysql_close */
my_bool reconnect; /* set to 1 if automatic reconnect */
/* session-wide random string */
char scramble[SCRAMBLE_LENGTH+1];
/*
Set if this is the original connection, not a master or a slave we have
added though mysql_rpl_probe() or mysql_set_master()/ mysql_add_slave()
*/
my_bool rpl_pivot;
/*
Pointers to the master, and the next slave connections, points to
itself if lone connection.
*/
struct st_mysql* master, *next_slave;
struct st_mysql* last_used_slave; /* needed for round-robin slave pick */
/* needed for send/read/store/use result to work correctly with replication */
struct st_mysql* last_used_con;
LIST *stmts; /* list of all statements */
const struct st_mysql_methods *methods;
void *thd;
/*
Points to boolean flag in MYSQL_RES or MYSQL_STMT. We set this flag
from mysql_stmt_close if close had to cancel result set of this object.
*/
my_bool *unbuffered_fetch_owner;
} MYSQL;
typedef struct st_mysql_res {
my_ulonglong row_count;
MYSQL_FIELD *fields;
MYSQL_DATA *data;
MYSQL_ROWS *data_cursor;
unsigned long *lengths; /* column lengths of current row */
MYSQL *handle; /* for unbuffered reads */
MEM_ROOT field_alloc;
unsigned int field_count, current_field;
MYSQL_ROW row; /* If unbuffered read */
MYSQL_ROW current_row; /* buffer to current row */
my_bool eof; /* Used by mysql_fetch_row */
/* mysql_stmt_close() had to cancel this result */
my_bool unbuffered_fetch_cancelled;
const struct st_mysql_methods *methods;
} MYSQL_RES;
#define MAX_MYSQL_MANAGER_ERR 256
#define MAX_MYSQL_MANAGER_MSG 256
#define MANAGER_OK 200
#define MANAGER_INFO 250
#define MANAGER_ACCESS 401
#define MANAGER_CLIENT_ERR 450
#define MANAGER_INTERNAL_ERR 500
#if !defined(MYSQL_SERVER) && !defined(MYSQL_CLIENT)
#define MYSQL_CLIENT
#endif
typedef struct st_mysql_manager
{
NET net;
char *host,*user,*passwd;
unsigned int port;
my_bool free_me;
my_bool eof;
int cmd_status;
int last_errno;
char* net_buf,*net_buf_pos,*net_data_end;
int net_buf_size;
char last_error[MAX_MYSQL_MANAGER_ERR];
} MYSQL_MANAGER;
typedef struct st_mysql_parameters
{
unsigned long *p_max_allowed_packet;
unsigned long *p_net_buffer_length;
} MYSQL_PARAMETERS;
#if !defined(MYSQL_SERVER) && !defined(EMBEDDED_LIBRARY)
#define max_allowed_packet (*mysql_get_parameters()->p_max_allowed_packet)
#define net_buffer_length (*mysql_get_parameters()->p_net_buffer_length)
#endif
/*
Set up and bring down the server; to ensure that applications will
work when linked against either the standard client library or the
embedded server library, these functions should be called.
*/
int STDCALL mysql_server_init(int argc, char **argv, char **groups);
void STDCALL mysql_server_end(void);
/*
mysql_server_init/end need to be called when using libmysqld or
libmysqlclient (exactly, mysql_server_init() is called by mysql_init() so
you don't need to call it explicitely; but you need to call
mysql_server_end() to free memory). The names are a bit misleading
(mysql_SERVER* to be used when using libmysqlCLIENT). So we add more general
names which suit well whether you're using libmysqld or libmysqlclient. We
intend to promote these aliases over the mysql_server* ones.
*/
#define mysql_library_init mysql_server_init
#define mysql_library_end mysql_server_end
MYSQL_PARAMETERS *STDCALL mysql_get_parameters(void);
/*
Set up and bring down a thread; these function should be called
for each thread in an application which opens at least one MySQL
connection. All uses of the connection(s) should be between these
function calls.
*/
my_bool STDCALL mysql_thread_init(void);
void STDCALL mysql_thread_end(void);
/*
Functions to get information from the MYSQL and MYSQL_RES structures
Should definitely be used if one uses shared libraries.
*/
my_ulonglong STDCALL mysql_num_rows(MYSQL_RES *res);
unsigned int STDCALL mysql_num_fields(MYSQL_RES *res);
my_bool STDCALL mysql_eof(MYSQL_RES *res);
MYSQL_FIELD *STDCALL mysql_fetch_field_direct(MYSQL_RES *res,
unsigned int fieldnr);
MYSQL_FIELD * STDCALL mysql_fetch_fields(MYSQL_RES *res);
MYSQL_ROW_OFFSET STDCALL mysql_row_tell(MYSQL_RES *res);
MYSQL_FIELD_OFFSET STDCALL mysql_field_tell(MYSQL_RES *res);
unsigned int STDCALL mysql_field_count(MYSQL *mysql);
my_ulonglong STDCALL mysql_affected_rows(MYSQL *mysql);
my_ulonglong STDCALL mysql_insert_id(MYSQL *mysql);
unsigned int STDCALL mysql_errno(MYSQL *mysql);
const char * STDCALL mysql_error(MYSQL *mysql);
const char *STDCALL mysql_sqlstate(MYSQL *mysql);
unsigned int STDCALL mysql_warning_count(MYSQL *mysql);
const char * STDCALL mysql_info(MYSQL *mysql);
unsigned long STDCALL mysql_thread_id(MYSQL *mysql);
const char * STDCALL mysql_character_set_name(MYSQL *mysql);
int STDCALL mysql_set_character_set(MYSQL *mysql, const char *csname);
MYSQL * STDCALL mysql_init(MYSQL *mysql);
my_bool STDCALL mysql_ssl_set(MYSQL *mysql, const char *key,
const char *cert, const char *ca,
const char *capath, const char *cipher);
my_bool STDCALL mysql_change_user(MYSQL *mysql, const char *user,
const char *passwd, const char *db);
MYSQL * STDCALL mysql_real_connect(MYSQL *mysql, const char *host,
const char *user,
const char *passwd,
const char *db,
unsigned int port,
const char *unix_socket,
unsigned long clientflag);
int STDCALL mysql_select_db(MYSQL *mysql, const char *db);
int STDCALL mysql_query(MYSQL *mysql, const char *q);
int STDCALL mysql_send_query(MYSQL *mysql, const char *q,
unsigned long length);
int STDCALL mysql_real_query(MYSQL *mysql, const char *q,
unsigned long length);
MYSQL_RES * STDCALL mysql_store_result(MYSQL *mysql);
MYSQL_RES * STDCALL mysql_use_result(MYSQL *mysql);
/* perform query on master */
my_bool STDCALL mysql_master_query(MYSQL *mysql, const char *q,
unsigned long length);
my_bool STDCALL mysql_master_send_query(MYSQL *mysql, const char *q,
unsigned long length);
/* perform query on slave */
my_bool STDCALL mysql_slave_query(MYSQL *mysql, const char *q,
unsigned long length);
my_bool STDCALL mysql_slave_send_query(MYSQL *mysql, const char *q,
unsigned long length);
void STDCALL mysql_get_character_set_info(MYSQL *mysql,
MY_CHARSET_INFO *charset);
/* local infile support */
#define LOCAL_INFILE_ERROR_LEN 512
void
mysql_set_local_infile_handler(MYSQL *mysql,
int (*local_infile_init)(void **, const char *,
void *),
int (*local_infile_read)(void *, char *,
unsigned int),
void (*local_infile_end)(void *),
int (*local_infile_error)(void *, char*,
unsigned int),
void *);
void
mysql_set_local_infile_default(MYSQL *mysql);
/*
enable/disable parsing of all queries to decide if they go on master or
slave
*/
void STDCALL mysql_enable_rpl_parse(MYSQL* mysql);
void STDCALL mysql_disable_rpl_parse(MYSQL* mysql);
/* get the value of the parse flag */
int STDCALL mysql_rpl_parse_enabled(MYSQL* mysql);
/* enable/disable reads from master */
void STDCALL mysql_enable_reads_from_master(MYSQL* mysql);
void STDCALL mysql_disable_reads_from_master(MYSQL* mysql);
/* get the value of the master read flag */
my_bool STDCALL mysql_reads_from_master_enabled(MYSQL* mysql);
enum mysql_rpl_type STDCALL mysql_rpl_query_type(const char* q, int len);
/* discover the master and its slaves */
my_bool STDCALL mysql_rpl_probe(MYSQL* mysql);
/* set the master, close/free the old one, if it is not a pivot */
int STDCALL mysql_set_master(MYSQL* mysql, const char* host,
unsigned int port,
const char* user,
const char* passwd);
int STDCALL mysql_add_slave(MYSQL* mysql, const char* host,
unsigned int port,
const char* user,
const char* passwd);
int STDCALL mysql_shutdown(MYSQL *mysql,
enum mysql_enum_shutdown_level
shutdown_level);
int STDCALL mysql_dump_debug_info(MYSQL *mysql);
int STDCALL mysql_refresh(MYSQL *mysql,
unsigned int refresh_options);
int STDCALL mysql_kill(MYSQL *mysql,unsigned long pid);
int STDCALL mysql_set_server_option(MYSQL *mysql,
enum enum_mysql_set_option
option);
int STDCALL mysql_ping(MYSQL *mysql);
const char * STDCALL mysql_stat(MYSQL *mysql);
const char * STDCALL mysql_get_server_info(MYSQL *mysql);
const char * STDCALL mysql_get_client_info(void);
unsigned long STDCALL mysql_get_client_version(void);
const char * STDCALL mysql_get_host_info(MYSQL *mysql);
unsigned long STDCALL mysql_get_server_version(MYSQL *mysql);
unsigned int STDCALL mysql_get_proto_info(MYSQL *mysql);
MYSQL_RES * STDCALL mysql_list_dbs(MYSQL *mysql,const char *wild);
MYSQL_RES * STDCALL mysql_list_tables(MYSQL *mysql,const char *wild);
MYSQL_RES * STDCALL mysql_list_processes(MYSQL *mysql);
int STDCALL mysql_options(MYSQL *mysql,enum mysql_option option,
const char *arg);
void STDCALL mysql_free_result(MYSQL_RES *result);
void STDCALL mysql_data_seek(MYSQL_RES *result,
my_ulonglong offset);
MYSQL_ROW_OFFSET STDCALL mysql_row_seek(MYSQL_RES *result,
MYSQL_ROW_OFFSET offset);
MYSQL_FIELD_OFFSET STDCALL mysql_field_seek(MYSQL_RES *result,
MYSQL_FIELD_OFFSET offset);
MYSQL_ROW STDCALL mysql_fetch_row(MYSQL_RES *result);
unsigned long * STDCALL mysql_fetch_lengths(MYSQL_RES *result);
MYSQL_FIELD * STDCALL mysql_fetch_field(MYSQL_RES *result);
MYSQL_RES * STDCALL mysql_list_fields(MYSQL *mysql, const char *table,
const char *wild);
unsigned long STDCALL mysql_escape_string(char *to,const char *from,
unsigned long from_length);
unsigned long STDCALL mysql_hex_string(char *to,const char *from,
unsigned long from_length);
unsigned long STDCALL mysql_real_escape_string(MYSQL *mysql,
char *to,const char *from,
unsigned long length);
void STDCALL mysql_debug(const char *debug);
char * STDCALL mysql_odbc_escape_string(MYSQL *mysql,
char *to,
unsigned long to_length,
const char *from,
unsigned long from_length,
void *param,
char *
(*extend_buffer)
(void *, char *to,
unsigned long *length));
void STDCALL myodbc_remove_escape(MYSQL *mysql,char *name);
unsigned int STDCALL mysql_thread_safe(void);
my_bool STDCALL mysql_embedded(void);
MYSQL_MANAGER* STDCALL mysql_manager_init(MYSQL_MANAGER* con);
MYSQL_MANAGER* STDCALL mysql_manager_connect(MYSQL_MANAGER* con,
const char* host,
const char* user,
const char* passwd,
unsigned int port);
void STDCALL mysql_manager_close(MYSQL_MANAGER* con);
int STDCALL mysql_manager_command(MYSQL_MANAGER* con,
const char* cmd, int cmd_len);
int STDCALL mysql_manager_fetch_line(MYSQL_MANAGER* con,
char* res_buf,
int res_buf_size);
my_bool STDCALL mysql_read_query_result(MYSQL *mysql);
/*
The following definitions are added for the enhanced
client-server protocol
*/
/* statement state */
enum enum_mysql_stmt_state
{
MYSQL_STMT_INIT_DONE= 1, MYSQL_STMT_PREPARE_DONE, MYSQL_STMT_EXECUTE_DONE,
MYSQL_STMT_FETCH_DONE
};
/*
This structure is used to define bind information, and
internally by the client library.
Public members with their descriptions are listed below
(conventionally `On input' refers to the binds given to
mysql_stmt_bind_param, `On output' refers to the binds given
to mysql_stmt_bind_result):
buffer_type - One of the MYSQL_* types, used to describe
the host language type of buffer.
On output: if column type is different from
buffer_type, column value is automatically converted
to buffer_type before it is stored in the buffer.
buffer - On input: points to the buffer with input data.
On output: points to the buffer capable to store
output data.
The type of memory pointed by buffer must correspond
to buffer_type. See the correspondence table in
the comment to mysql_stmt_bind_param.
The two above members are mandatory for any kind of bind.
buffer_length - the length of the buffer. You don't have to set
it for any fixed length buffer: float, double,
int, etc. It must be set however for variable-length
types, such as BLOBs or STRINGs.
length - On input: in case when lengths of input values
are different for each execute, you can set this to
point at a variable containining value length. This
way the value length can be different in each execute.
If length is not NULL, buffer_length is not used.
Note, length can even point at buffer_length if
you keep bind structures around while fetching:
this way you can change buffer_length before
each execution, everything will work ok.
On output: if length is set, mysql_stmt_fetch will
write column length into it.
is_null - On input: points to a boolean variable that should
be set to TRUE for NULL values.
This member is useful only if your data may be
NULL in some but not all cases.
If your data is never NULL, is_null should be set to 0.
If your data is always NULL, set buffer_type
to MYSQL_TYPE_NULL, and is_null will not be used.
is_unsigned - On input: used to signify that values provided for one
of numeric types are unsigned.
On output describes signedness of the output buffer.
If, taking into account is_unsigned flag, column data
is out of range of the output buffer, data for this column
is regarded truncated. Note that this has no correspondence
to the sign of result set column, if you need to find it out
use mysql_stmt_result_metadata.
error - where to write a truncation error if it is present.
possible error value is:
0 no truncation
1 value is out of range or buffer is too small
Please note that MYSQL_BIND also has internals members.
*/
typedef struct st_mysql_bind
{
unsigned long *length; /* output length pointer */
my_bool *is_null; /* Pointer to null indicator */
void *buffer; /* buffer to get/put data */
/* set this if you want to track data truncations happened during fetch */
my_bool *error;
enum enum_field_types buffer_type; /* buffer type */
/* output buffer length, must be set when fetching str/binary */
unsigned long buffer_length;
unsigned char *row_ptr; /* for the current data position */
unsigned long offset; /* offset position for char/binary fetch */
unsigned long length_value; /* Used if length is 0 */
unsigned int param_number; /* For null count and error messages */
unsigned int pack_length; /* Internal length for packed data */
my_bool error_value; /* used if error is 0 */
my_bool is_unsigned; /* set if integer type is unsigned */
my_bool long_data_used; /* If used with mysql_send_long_data */
my_bool is_null_value; /* Used if is_null is 0 */
void (*store_param_func)(NET *net, struct st_mysql_bind *param);
void (*fetch_result)(struct st_mysql_bind *, MYSQL_FIELD *,
unsigned char **row);
void (*skip_result)(struct st_mysql_bind *, MYSQL_FIELD *,
unsigned char **row);
} MYSQL_BIND;
/* statement handler */
typedef struct st_mysql_stmt
{
MEM_ROOT mem_root; /* root allocations */
LIST list; /* list to keep track of all stmts */
MYSQL *mysql; /* connection handle */
MYSQL_BIND *params; /* input parameters */
MYSQL_BIND *bind; /* output parameters */
MYSQL_FIELD *fields; /* result set metadata */
MYSQL_DATA result; /* cached result set */
MYSQL_ROWS *data_cursor; /* current row in cached result */
/* copy of mysql->affected_rows after statement execution */
my_ulonglong affected_rows;
my_ulonglong insert_id; /* copy of mysql->insert_id */
/*
mysql_stmt_fetch() calls this function to fetch one row (it's different
for buffered, unbuffered and cursor fetch).
*/
int (*read_row_func)(struct st_mysql_stmt *stmt,
unsigned char **row);
unsigned long stmt_id; /* Id for prepared statement */
unsigned long flags; /* i.e. type of cursor to open */
unsigned long prefetch_rows; /* number of rows per one COM_FETCH */
/*
Copied from mysql->server_status after execute/fetch to know
server-side cursor status for this statement.
*/
unsigned int server_status;
unsigned int last_errno; /* error code */
unsigned int param_count; /* input parameter count */
unsigned int field_count; /* number of columns in result set */
enum enum_mysql_stmt_state state; /* statement state */
char last_error[MYSQL_ERRMSG_SIZE]; /* error message */
char sqlstate[SQLSTATE_LENGTH+1];
/* Types of input parameters should be sent to server */
my_bool send_types_to_server;
my_bool bind_param_done; /* input buffers were supplied */
unsigned char bind_result_done; /* output buffers were supplied */
/* mysql_stmt_close() had to cancel this result */
my_bool unbuffered_fetch_cancelled;
/*
Is set to true if we need to calculate field->max_length for
metadata fields when doing mysql_stmt_store_result.
*/
my_bool update_max_length;
} MYSQL_STMT;
enum enum_stmt_attr_type
{
/*
When doing mysql_stmt_store_result calculate max_length attribute
of statement metadata. This is to be consistent with the old API,
where this was done automatically.
In the new API we do that only by request because it slows down
mysql_stmt_store_result sufficiently.
*/
STMT_ATTR_UPDATE_MAX_LENGTH,
/*
unsigned long with combination of cursor flags (read only, for update,
etc)
*/
STMT_ATTR_CURSOR_TYPE,
/*
Amount of rows to retrieve from server per one fetch if using cursors.
Accepts unsigned long attribute in the range 1 - ulong_max
*/
STMT_ATTR_PREFETCH_ROWS
};
typedef struct st_mysql_methods
{
my_bool (*read_query_result)(MYSQL *mysql);
my_bool (*advanced_command)(MYSQL *mysql,
enum enum_server_command command,
const char *header,
unsigned long header_length,
const char *arg,
unsigned long arg_length,
my_bool skip_check);
MYSQL_DATA *(*read_rows)(MYSQL *mysql,MYSQL_FIELD *mysql_fields,
unsigned int fields);
MYSQL_RES * (*use_result)(MYSQL *mysql);
void (*fetch_lengths)(unsigned long *to,
MYSQL_ROW column, unsigned int field_count);
void (*flush_use_result)(MYSQL *mysql);
#if !defined(MYSQL_SERVER) || defined(EMBEDDED_LIBRARY)
MYSQL_FIELD * (*list_fields)(MYSQL *mysql);
my_bool (*read_prepare_result)(MYSQL *mysql, MYSQL_STMT *stmt);
int (*stmt_execute)(MYSQL_STMT *stmt);
int (*read_binary_rows)(MYSQL_STMT *stmt);
int (*unbuffered_fetch)(MYSQL *mysql, char **row);
void (*free_embedded_thd)(MYSQL *mysql);
const char *(*read_statistics)(MYSQL *mysql);
my_bool (*next_result)(MYSQL *mysql);
int (*read_change_user_result)(MYSQL *mysql, char *buff, const char *passwd);
#endif
} MYSQL_METHODS;
MYSQL_STMT * STDCALL mysql_stmt_init(MYSQL *mysql);
int STDCALL mysql_stmt_prepare(MYSQL_STMT *stmt, const char *query,
unsigned long length);
int STDCALL mysql_stmt_execute(MYSQL_STMT *stmt);
int STDCALL mysql_stmt_fetch(MYSQL_STMT *stmt);
int STDCALL mysql_stmt_fetch_column(MYSQL_STMT *stmt, MYSQL_BIND *bind,
unsigned int column,
unsigned long offset);
int STDCALL mysql_stmt_store_result(MYSQL_STMT *stmt);
unsigned long STDCALL mysql_stmt_param_count(MYSQL_STMT * stmt);
my_bool STDCALL mysql_stmt_attr_set(MYSQL_STMT *stmt,
enum enum_stmt_attr_type attr_type,
const void *attr);
my_bool STDCALL mysql_stmt_attr_get(MYSQL_STMT *stmt,
enum enum_stmt_attr_type attr_type,
void *attr);
my_bool STDCALL mysql_stmt_bind_param(MYSQL_STMT * stmt, MYSQL_BIND * bnd);
my_bool STDCALL mysql_stmt_bind_result(MYSQL_STMT * stmt, MYSQL_BIND * bnd);
my_bool STDCALL mysql_stmt_close(MYSQL_STMT * stmt);
my_bool STDCALL mysql_stmt_reset(MYSQL_STMT * stmt);
my_bool STDCALL mysql_stmt_free_result(MYSQL_STMT *stmt);
my_bool STDCALL mysql_stmt_send_long_data(MYSQL_STMT *stmt,
unsigned int param_number,
const char *data,
unsigned long length);
MYSQL_RES *STDCALL mysql_stmt_result_metadata(MYSQL_STMT *stmt);
MYSQL_RES *STDCALL mysql_stmt_param_metadata(MYSQL_STMT *stmt);
unsigned int STDCALL mysql_stmt_errno(MYSQL_STMT * stmt);
const char *STDCALL mysql_stmt_error(MYSQL_STMT * stmt);
const char *STDCALL mysql_stmt_sqlstate(MYSQL_STMT * stmt);
MYSQL_ROW_OFFSET STDCALL mysql_stmt_row_seek(MYSQL_STMT *stmt,
MYSQL_ROW_OFFSET offset);
MYSQL_ROW_OFFSET STDCALL mysql_stmt_row_tell(MYSQL_STMT *stmt);
void STDCALL mysql_stmt_data_seek(MYSQL_STMT *stmt, my_ulonglong offset);
my_ulonglong STDCALL mysql_stmt_num_rows(MYSQL_STMT *stmt);
my_ulonglong STDCALL mysql_stmt_affected_rows(MYSQL_STMT *stmt);
my_ulonglong STDCALL mysql_stmt_insert_id(MYSQL_STMT *stmt);
unsigned int STDCALL mysql_stmt_field_count(MYSQL_STMT *stmt);
my_bool STDCALL mysql_commit(MYSQL * mysql);
my_bool STDCALL mysql_rollback(MYSQL * mysql);
my_bool STDCALL mysql_autocommit(MYSQL * mysql, my_bool auto_mode);
my_bool STDCALL mysql_more_results(MYSQL *mysql);
int STDCALL mysql_next_result(MYSQL *mysql);
void STDCALL mysql_close(MYSQL *sock);
/* status return codes */
#define MYSQL_NO_DATA 100
#define MYSQL_DATA_TRUNCATED 101
#define mysql_reload(mysql) mysql_refresh((mysql),REFRESH_GRANT)
#ifdef USE_OLD_FUNCTIONS
MYSQL * STDCALL mysql_connect(MYSQL *mysql, const char *host,
const char *user, const char *passwd);
int STDCALL mysql_create_db(MYSQL *mysql, const char *DB);
int STDCALL mysql_drop_db(MYSQL *mysql, const char *DB);
#define mysql_reload(mysql) mysql_refresh((mysql),REFRESH_GRANT)
#endif
#define HAVE_MYSQL_REAL_CONNECT
/*
The following functions are mainly exported because of mysqlbinlog;
They are not for general usage
*/
#define simple_command(mysql, command, arg, length, skip_check) \
(*(mysql)->methods->advanced_command)(mysql, command, \
NullS, 0, arg, length, skip_check)
unsigned long net_safe_read(MYSQL* mysql);
#ifdef __NETWARE__
#pragma pack(pop) /* restore alignment */
#endif
#ifdef __cplusplus
}
#endif
#endif /* _mysql_h */
+444
View File
@@ -0,0 +1,444 @@
/* Copyright (C) 2000 MySQL AB
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/*
** Common definition between mysql server & client
*/
#ifndef _mysql_com_h
#define _mysql_com_h
#define NAME_LEN 64 /* Field/table name length */
#define HOSTNAME_LENGTH 60
#define USERNAME_LENGTH 16
#define SERVER_VERSION_LENGTH 60
#define SQLSTATE_LENGTH 5
#define LOCAL_HOST "localhost"
#define LOCAL_HOST_NAMEDPIPE "."
#if defined(__WIN__) && !defined( _CUSTOMCONFIG_)
#define MYSQL_NAMEDPIPE "MySQL"
#define MYSQL_SERVICENAME "MySQL"
#endif /* __WIN__ */
/*
You should add new commands to the end of this list, otherwise old
servers won't be able to handle them as 'unsupported'.
*/
enum enum_server_command
{
COM_SLEEP, COM_QUIT, COM_INIT_DB, COM_QUERY, COM_FIELD_LIST,
COM_CREATE_DB, COM_DROP_DB, COM_REFRESH, COM_SHUTDOWN, COM_STATISTICS,
COM_PROCESS_INFO, COM_CONNECT, COM_PROCESS_KILL, COM_DEBUG, COM_PING,
COM_TIME, COM_DELAYED_INSERT, COM_CHANGE_USER, COM_BINLOG_DUMP,
COM_TABLE_DUMP, COM_CONNECT_OUT, COM_REGISTER_SLAVE,
COM_STMT_PREPARE, COM_STMT_EXECUTE, COM_STMT_SEND_LONG_DATA, COM_STMT_CLOSE,
COM_STMT_RESET, COM_SET_OPTION, COM_STMT_FETCH,
/* don't forget to update const char *command_name[] in sql_parse.cc */
/* Must be last */
COM_END
};
/*
Length of random string sent by server on handshake; this is also length of
obfuscated password, recieved from client
*/
#define SCRAMBLE_LENGTH 20
#define SCRAMBLE_LENGTH_323 8
/* length of password stored in the db: new passwords are preceeded with '*' */
#define SCRAMBLED_PASSWORD_CHAR_LENGTH (SCRAMBLE_LENGTH*2+1)
#define SCRAMBLED_PASSWORD_CHAR_LENGTH_323 (SCRAMBLE_LENGTH_323*2)
#define NOT_NULL_FLAG 1 /* Field can't be NULL */
#define PRI_KEY_FLAG 2 /* Field is part of a primary key */
#define UNIQUE_KEY_FLAG 4 /* Field is part of a unique key */
#define MULTIPLE_KEY_FLAG 8 /* Field is part of a key */
#define BLOB_FLAG 16 /* Field is a blob */
#define UNSIGNED_FLAG 32 /* Field is unsigned */
#define ZEROFILL_FLAG 64 /* Field is zerofill */
#define BINARY_FLAG 128 /* Field is binary */
/* The following are only sent to new clients */
#define ENUM_FLAG 256 /* field is an enum */
#define AUTO_INCREMENT_FLAG 512 /* field is a autoincrement field */
#define TIMESTAMP_FLAG 1024 /* Field is a timestamp */
#define SET_FLAG 2048 /* field is a set */
#define NO_DEFAULT_VALUE_FLAG 4096 /* Field doesn't have default value */
#define NUM_FLAG 32768 /* Field is num (for clients) */
#define PART_KEY_FLAG 16384 /* Intern; Part of some key */
#define GROUP_FLAG 32768 /* Intern: Group field */
#define UNIQUE_FLAG 65536 /* Intern: Used by sql_yacc */
#define BINCMP_FLAG 131072 /* Intern: Used by sql_yacc */
#define REFRESH_GRANT 1 /* Refresh grant tables */
#define REFRESH_LOG 2 /* Start on new log file */
#define REFRESH_TABLES 4 /* close all tables */
#define REFRESH_HOSTS 8 /* Flush host cache */
#define REFRESH_STATUS 16 /* Flush status variables */
#define REFRESH_THREADS 32 /* Flush thread cache */
#define REFRESH_SLAVE 64 /* Reset master info and restart slave
thread */
#define REFRESH_MASTER 128 /* Remove all bin logs in the index
and truncate the index */
/* The following can't be set with mysql_refresh() */
#define REFRESH_READ_LOCK 16384 /* Lock tables for read */
#define REFRESH_FAST 32768 /* Intern flag */
/* RESET (remove all queries) from query cache */
#define REFRESH_QUERY_CACHE 65536
#define REFRESH_QUERY_CACHE_FREE 0x20000L /* pack query cache */
#define REFRESH_DES_KEY_FILE 0x40000L
#define REFRESH_USER_RESOURCES 0x80000L
#define CLIENT_LONG_PASSWORD 1 /* new more secure passwords */
#define CLIENT_FOUND_ROWS 2 /* Found instead of affected rows */
#define CLIENT_LONG_FLAG 4 /* Get all column flags */
#define CLIENT_CONNECT_WITH_DB 8 /* One can specify db on connect */
#define CLIENT_NO_SCHEMA 16 /* Don't allow database.table.column */
#define CLIENT_COMPRESS 32 /* Can use compression protocol */
#define CLIENT_ODBC 64 /* Odbc client */
#define CLIENT_LOCAL_FILES 128 /* Can use LOAD DATA LOCAL */
#define CLIENT_IGNORE_SPACE 256 /* Ignore spaces before '(' */
#define CLIENT_PROTOCOL_41 512 /* New 4.1 protocol */
#define CLIENT_INTERACTIVE 1024 /* This is an interactive client */
#define CLIENT_SSL 2048 /* Switch to SSL after handshake */
#define CLIENT_IGNORE_SIGPIPE 4096 /* IGNORE sigpipes */
#define CLIENT_TRANSACTIONS 8192 /* Client knows about transactions */
#define CLIENT_RESERVED 16384 /* Old flag for 4.1 protocol */
#define CLIENT_SECURE_CONNECTION 32768 /* New 4.1 authentication */
#define CLIENT_MULTI_STATEMENTS 65536 /* Enable/disable multi-stmt support */
#define CLIENT_MULTI_RESULTS 131072 /* Enable/disable multi-results */
#define CLIENT_REMEMBER_OPTIONS (((ulong) 1) << 31)
#define SERVER_STATUS_IN_TRANS 1 /* Transaction has started */
#define SERVER_STATUS_AUTOCOMMIT 2 /* Server in auto_commit mode */
#define SERVER_STATUS_MORE_RESULTS 4 /* More results on server */
#define SERVER_MORE_RESULTS_EXISTS 8 /* Multi query - next query exists */
#define SERVER_QUERY_NO_GOOD_INDEX_USED 16
#define SERVER_QUERY_NO_INDEX_USED 32
/*
The server was able to fulfill the clients request and opened a
read-only non-scrollable cursor for a query. This flag comes
in reply to COM_STMT_EXECUTE and COM_STMT_FETCH commands.
*/
#define SERVER_STATUS_CURSOR_EXISTS 64
/*
This flag is sent when a read-only cursor is exhausted, in reply to
COM_STMT_FETCH command.
*/
#define SERVER_STATUS_LAST_ROW_SENT 128
#define SERVER_STATUS_DB_DROPPED 256 /* A database was dropped */
#define SERVER_STATUS_NO_BACKSLASH_ESCAPES 512
#define MYSQL_ERRMSG_SIZE 512
#define NET_READ_TIMEOUT 30 /* Timeout on read */
#define NET_WRITE_TIMEOUT 60 /* Timeout on write */
#define NET_WAIT_TIMEOUT 8*60*60 /* Wait for new query */
#define ONLY_KILL_QUERY 1
struct st_vio; /* Only C */
typedef struct st_vio Vio;
#define MAX_TINYINT_WIDTH 3 /* Max width for a TINY w.o. sign */
#define MAX_SMALLINT_WIDTH 5 /* Max width for a SHORT w.o. sign */
#define MAX_MEDIUMINT_WIDTH 8 /* Max width for a INT24 w.o. sign */
#define MAX_INT_WIDTH 10 /* Max width for a LONG w.o. sign */
#define MAX_BIGINT_WIDTH 20 /* Max width for a LONGLONG */
#define MAX_CHAR_WIDTH 255 /* Max length for a CHAR colum */
#define MAX_BLOB_WIDTH 8192 /* Default width for blob */
typedef struct st_net {
#if !defined(CHECK_EMBEDDED_DIFFERENCES) || !defined(EMBEDDED_LIBRARY)
Vio* vio;
unsigned char *buff,*buff_end,*write_pos,*read_pos;
my_socket fd; /* For Perl DBI/dbd */
unsigned long max_packet,max_packet_size;
unsigned int pkt_nr,compress_pkt_nr;
unsigned int write_timeout, read_timeout, retry_count;
int fcntl;
my_bool compress;
/*
The following variable is set if we are doing several queries in one
command ( as in LOAD TABLE ... FROM MASTER ),
and do not want to confuse the client with OK at the wrong time
*/
unsigned long remain_in_buf,length, buf_length, where_b;
unsigned int *return_status;
unsigned char reading_or_writing;
char save_char;
my_bool no_send_ok; /* For SPs and other things that do multiple stmts */
my_bool no_send_eof; /* For SPs' first version read-only cursors */
/*
Set if OK packet is already sent, and we do not need to send error
messages
*/
my_bool no_send_error;
/*
Pointer to query object in query cache, do not equal NULL (0) for
queries in cache that have not stored its results yet
*/
#endif
char last_error[MYSQL_ERRMSG_SIZE], sqlstate[SQLSTATE_LENGTH+1];
unsigned int last_errno;
unsigned char error;
gptr query_cache_query;
my_bool report_error; /* We should report error (we have unreported error) */
my_bool return_errno;
} NET;
#define packet_error (~(unsigned long) 0)
enum enum_field_types { MYSQL_TYPE_DECIMAL, MYSQL_TYPE_TINY,
MYSQL_TYPE_SHORT, MYSQL_TYPE_LONG,
MYSQL_TYPE_FLOAT, MYSQL_TYPE_DOUBLE,
MYSQL_TYPE_NULL, MYSQL_TYPE_TIMESTAMP,
MYSQL_TYPE_LONGLONG,MYSQL_TYPE_INT24,
MYSQL_TYPE_DATE, MYSQL_TYPE_TIME,
MYSQL_TYPE_DATETIME, MYSQL_TYPE_YEAR,
MYSQL_TYPE_NEWDATE, MYSQL_TYPE_VARCHAR,
MYSQL_TYPE_BIT,
MYSQL_TYPE_NEWDECIMAL=246,
MYSQL_TYPE_ENUM=247,
MYSQL_TYPE_SET=248,
MYSQL_TYPE_TINY_BLOB=249,
MYSQL_TYPE_MEDIUM_BLOB=250,
MYSQL_TYPE_LONG_BLOB=251,
MYSQL_TYPE_BLOB=252,
MYSQL_TYPE_VAR_STRING=253,
MYSQL_TYPE_STRING=254,
MYSQL_TYPE_GEOMETRY=255
};
/* For backward compatibility */
#define CLIENT_MULTI_QUERIES CLIENT_MULTI_STATEMENTS
#define FIELD_TYPE_DECIMAL MYSQL_TYPE_DECIMAL
#define FIELD_TYPE_NEWDECIMAL MYSQL_TYPE_NEWDECIMAL
#define FIELD_TYPE_TINY MYSQL_TYPE_TINY
#define FIELD_TYPE_SHORT MYSQL_TYPE_SHORT
#define FIELD_TYPE_LONG MYSQL_TYPE_LONG
#define FIELD_TYPE_FLOAT MYSQL_TYPE_FLOAT
#define FIELD_TYPE_DOUBLE MYSQL_TYPE_DOUBLE
#define FIELD_TYPE_NULL MYSQL_TYPE_NULL
#define FIELD_TYPE_TIMESTAMP MYSQL_TYPE_TIMESTAMP
#define FIELD_TYPE_LONGLONG MYSQL_TYPE_LONGLONG
#define FIELD_TYPE_INT24 MYSQL_TYPE_INT24
#define FIELD_TYPE_DATE MYSQL_TYPE_DATE
#define FIELD_TYPE_TIME MYSQL_TYPE_TIME
#define FIELD_TYPE_DATETIME MYSQL_TYPE_DATETIME
#define FIELD_TYPE_YEAR MYSQL_TYPE_YEAR
#define FIELD_TYPE_NEWDATE MYSQL_TYPE_NEWDATE
#define FIELD_TYPE_ENUM MYSQL_TYPE_ENUM
#define FIELD_TYPE_SET MYSQL_TYPE_SET
#define FIELD_TYPE_TINY_BLOB MYSQL_TYPE_TINY_BLOB
#define FIELD_TYPE_MEDIUM_BLOB MYSQL_TYPE_MEDIUM_BLOB
#define FIELD_TYPE_LONG_BLOB MYSQL_TYPE_LONG_BLOB
#define FIELD_TYPE_BLOB MYSQL_TYPE_BLOB
#define FIELD_TYPE_VAR_STRING MYSQL_TYPE_VAR_STRING
#define FIELD_TYPE_STRING MYSQL_TYPE_STRING
#define FIELD_TYPE_CHAR MYSQL_TYPE_TINY
#define FIELD_TYPE_INTERVAL MYSQL_TYPE_ENUM
#define FIELD_TYPE_GEOMETRY MYSQL_TYPE_GEOMETRY
#define FIELD_TYPE_BIT MYSQL_TYPE_BIT
/* Shutdown/kill enums and constants */
/* Bits for THD::killable. */
#define MYSQL_SHUTDOWN_KILLABLE_CONNECT (unsigned char)(1 << 0)
#define MYSQL_SHUTDOWN_KILLABLE_TRANS (unsigned char)(1 << 1)
#define MYSQL_SHUTDOWN_KILLABLE_LOCK_TABLE (unsigned char)(1 << 2)
#define MYSQL_SHUTDOWN_KILLABLE_UPDATE (unsigned char)(1 << 3)
enum mysql_enum_shutdown_level {
/*
We want levels to be in growing order of hardness (because we use number
comparisons). Note that DEFAULT does not respect the growing property, but
it's ok.
*/
SHUTDOWN_DEFAULT = 0,
/* wait for existing connections to finish */
SHUTDOWN_WAIT_CONNECTIONS= MYSQL_SHUTDOWN_KILLABLE_CONNECT,
/* wait for existing trans to finish */
SHUTDOWN_WAIT_TRANSACTIONS= MYSQL_SHUTDOWN_KILLABLE_TRANS,
/* wait for existing updates to finish (=> no partial MyISAM update) */
SHUTDOWN_WAIT_UPDATES= MYSQL_SHUTDOWN_KILLABLE_UPDATE,
/* flush InnoDB buffers and other storage engines' buffers*/
SHUTDOWN_WAIT_ALL_BUFFERS= (MYSQL_SHUTDOWN_KILLABLE_UPDATE << 1),
/* don't flush InnoDB buffers, flush other storage engines' buffers*/
SHUTDOWN_WAIT_CRITICAL_BUFFERS= (MYSQL_SHUTDOWN_KILLABLE_UPDATE << 1) + 1,
/* Now the 2 levels of the KILL command */
#if MYSQL_VERSION_ID >= 50000
KILL_QUERY= 254,
#endif
KILL_CONNECTION= 255
};
enum enum_cursor_type
{
CURSOR_TYPE_NO_CURSOR= 0,
CURSOR_TYPE_READ_ONLY= 1,
CURSOR_TYPE_FOR_UPDATE= 2,
CURSOR_TYPE_SCROLLABLE= 4
};
/* options for mysql_set_option */
enum enum_mysql_set_option
{
MYSQL_OPTION_MULTI_STATEMENTS_ON,
MYSQL_OPTION_MULTI_STATEMENTS_OFF
};
#define net_new_transaction(net) ((net)->pkt_nr=0)
#ifdef __cplusplus
extern "C" {
#endif
my_bool my_net_init(NET *net, Vio* vio);
void my_net_local_init(NET *net);
void net_end(NET *net);
void net_clear(NET *net);
my_bool net_realloc(NET *net, unsigned long length);
my_bool net_flush(NET *net);
my_bool my_net_write(NET *net,const char *packet,unsigned long len);
my_bool net_write_command(NET *net,unsigned char command,
const char *header, unsigned long head_len,
const char *packet, unsigned long len);
int net_real_write(NET *net,const char *packet,unsigned long len);
unsigned long my_net_read(NET *net);
/*
The following function is not meant for normal usage
Currently it's used internally by manager.c
*/
struct sockaddr;
int my_connect(my_socket s, const struct sockaddr *name, unsigned int namelen,
unsigned int timeout);
struct rand_struct {
unsigned long seed1,seed2,max_value;
double max_value_dbl;
};
#ifdef __cplusplus
}
#endif
/* The following is for user defined functions */
enum Item_result {STRING_RESULT=0, REAL_RESULT, INT_RESULT, ROW_RESULT,
DECIMAL_RESULT};
typedef struct st_udf_args
{
unsigned int arg_count; /* Number of arguments */
enum Item_result *arg_type; /* Pointer to item_results */
char **args; /* Pointer to argument */
unsigned long *lengths; /* Length of string arguments */
char *maybe_null; /* Set to 1 for all maybe_null args */
char **attributes; /* Pointer to attribute name */
unsigned long *attribute_lengths; /* Length of attribute arguments */
} UDF_ARGS;
/* This holds information about the result */
typedef struct st_udf_init
{
my_bool maybe_null; /* 1 if function can return NULL */
unsigned int decimals; /* for real functions */
unsigned long max_length; /* For string functions */
char *ptr; /* free pointer for function data */
my_bool const_item; /* 0 if result is independent of arguments */
} UDF_INIT;
/* Constants when using compression */
#define NET_HEADER_SIZE 4 /* standard header size */
#define COMP_HEADER_SIZE 3 /* compression header extra size */
/* Prototypes to password functions */
#ifdef __cplusplus
extern "C" {
#endif
/*
These functions are used for authentication by client and server and
implemented in sql/password.c
*/
void randominit(struct rand_struct *, unsigned long seed1,
unsigned long seed2);
double my_rnd(struct rand_struct *);
void create_random_string(char *to, unsigned int length, struct rand_struct *rand_st);
void hash_password(unsigned long *to, const char *password, unsigned int password_len);
void make_scrambled_password_323(char *to, const char *password);
void scramble_323(char *to, const char *message, const char *password);
my_bool check_scramble_323(const char *, const char *message,
unsigned long *salt);
void get_salt_from_password_323(unsigned long *res, const char *password);
void make_password_from_salt_323(char *to, const unsigned long *salt);
void make_scrambled_password(char *to, const char *password);
void scramble(char *to, const char *message, const char *password);
my_bool check_scramble(const char *reply, const char *message,
const unsigned char *hash_stage2);
void get_salt_from_password(unsigned char *res, const char *password);
void make_password_from_salt(char *to, const unsigned char *hash_stage2);
char *octet2hex(char *to, const char *str, unsigned int len);
/* end of password.c */
char *get_tty_password(char *opt_message);
const char *mysql_errno_to_sqlstate(unsigned int mysql_errno);
/* Some other useful functions */
my_bool my_init(void);
extern int modify_defaults_file(const char *file_location, const char *option,
const char *option_value,
const char *section_name, int remove_option);
int load_defaults(const char *conf_file, const char **groups,
int *argc, char ***argv);
my_bool my_thread_init(void);
void my_thread_end(void);
#ifdef _global_h
ulong STDCALL net_field_length(uchar **packet);
my_ulonglong net_field_length_ll(uchar **packet);
char *net_store_length(char *pkg, ulonglong length);
#endif
#ifdef __cplusplus
}
#endif
#define NULL_LENGTH ((unsigned long) ~0) /* For net_store_length */
#define MYSQL_STMT_HEADER 4
#define MYSQL_LONG_DATA_HEADER 6
#endif
+32
View File
@@ -0,0 +1,32 @@
/* Copyright (C) 2000 MySQL AB
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/* Defines that are unique to the embedded version of MySQL */
#ifdef EMBEDDED_LIBRARY
/* Things we don't need in the embedded version of MySQL */
/* TODO HF add #undef HAVE_VIO if we don't want client in embedded library */
#undef HAVE_PSTACK /* No stacktrace */
#undef HAVE_DLOPEN /* No udf functions */
#undef HAVE_OPENSSL
#undef HAVE_SMEM /* No shared memory */
#undef HAVE_NDBCLUSTER_DB /* No NDB cluster */
#define DONT_USE_RAID
#endif /* EMBEDDED_LIBRARY */
+56
View File
@@ -0,0 +1,56 @@
/* Copyright (C) 2004 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#ifndef _mysql_time_h_
#define _mysql_time_h_
/*
Time declarations shared between the server and client API:
you should not add anything to this header unless it's used
(and hence should be visible) in mysql.h.
If you're looking for a place to add new time-related declaration,
it's most likely my_time.h. See also "C API Handling of Date
and Time Values" chapter in documentation.
*/
enum enum_mysql_timestamp_type
{
MYSQL_TIMESTAMP_NONE= -2, MYSQL_TIMESTAMP_ERROR= -1,
MYSQL_TIMESTAMP_DATE= 0, MYSQL_TIMESTAMP_DATETIME= 1, MYSQL_TIMESTAMP_TIME= 2
};
/*
Structure which is used to represent datetime values inside MySQL.
We assume that values in this structure are normalized, i.e. year <= 9999,
month <= 12, day <= 31, hour <= 23, hour <= 59, hour <= 59. Many functions
in server such as my_system_gmt_sec() or make_time() family of functions
rely on this (actually now usage of make_*() family relies on a bit weaker
restriction). Also functions that produce MYSQL_TIME as result ensure this.
There is one exception to this rule though if this structure holds time
value (time_type == MYSQL_TIMESTAMP_TIME) days and hour member can hold
bigger values.
*/
typedef struct st_mysql_time
{
unsigned int year, month, day, hour, minute, second;
unsigned long second_part;
my_bool neg;
enum enum_mysql_timestamp_type time_type;
} MYSQL_TIME;
#endif /* _mysql_time_h_ */
+29
View File
@@ -0,0 +1,29 @@
/* Copyright Abandoned 1996, 1999, 2001 MySQL AB
This file is public domain and comes with NO WARRANTY of any kind */
/* Version numbers for protocol & mysqld */
#ifndef _mysql_version_h
#define _mysql_version_h
#ifdef _CUSTOMCONFIG_
#include <custom_conf.h>
#else
#define PROTOCOL_VERSION 10
#define MYSQL_SERVER_VERSION "5.0.15"
#define MYSQL_BASE_VERSION "mysqld-5.0"
#define MYSQL_SERVER_SUFFIX_DEF ""
#define FRM_VER 6
#define MYSQL_VERSION_ID 50015
#define MYSQL_PORT 3306
#define MYSQL_UNIX_ADDR "/tmp/mysql.sock"
#define MYSQL_CONFIG_NAME "my"
#define MYSQL_COMPILATION_COMMENT "Official MySQL binary"
/* mysqld compile time options */
#endif /* _CUSTOMCONFIG_ */
#ifndef LICENSE
#define LICENSE GPL
#endif /* LICENSE */
#endif /* _mysql_version_h */
+456
View File
@@ -0,0 +1,456 @@
/* Autogenerated file, please don't edit */
{ "ER_HASHCHK", 1000 },
{ "ER_NISAMCHK", 1001 },
{ "ER_NO", 1002 },
{ "ER_YES", 1003 },
{ "ER_CANT_CREATE_FILE", 1004 },
{ "ER_CANT_CREATE_TABLE", 1005 },
{ "ER_CANT_CREATE_DB", 1006 },
{ "ER_DB_CREATE_EXISTS", 1007 },
{ "ER_DB_DROP_EXISTS", 1008 },
{ "ER_DB_DROP_DELETE", 1009 },
{ "ER_DB_DROP_RMDIR", 1010 },
{ "ER_CANT_DELETE_FILE", 1011 },
{ "ER_CANT_FIND_SYSTEM_REC", 1012 },
{ "ER_CANT_GET_STAT", 1013 },
{ "ER_CANT_GET_WD", 1014 },
{ "ER_CANT_LOCK", 1015 },
{ "ER_CANT_OPEN_FILE", 1016 },
{ "ER_FILE_NOT_FOUND", 1017 },
{ "ER_CANT_READ_DIR", 1018 },
{ "ER_CANT_SET_WD", 1019 },
{ "ER_CHECKREAD", 1020 },
{ "ER_DISK_FULL", 1021 },
{ "ER_DUP_KEY", 1022 },
{ "ER_ERROR_ON_CLOSE", 1023 },
{ "ER_ERROR_ON_READ", 1024 },
{ "ER_ERROR_ON_RENAME", 1025 },
{ "ER_ERROR_ON_WRITE", 1026 },
{ "ER_FILE_USED", 1027 },
{ "ER_FILSORT_ABORT", 1028 },
{ "ER_FORM_NOT_FOUND", 1029 },
{ "ER_GET_ERRNO", 1030 },
{ "ER_ILLEGAL_HA", 1031 },
{ "ER_KEY_NOT_FOUND", 1032 },
{ "ER_NOT_FORM_FILE", 1033 },
{ "ER_NOT_KEYFILE", 1034 },
{ "ER_OLD_KEYFILE", 1035 },
{ "ER_OPEN_AS_READONLY", 1036 },
{ "ER_OUTOFMEMORY", 1037 },
{ "ER_OUT_OF_SORTMEMORY", 1038 },
{ "ER_UNEXPECTED_EOF", 1039 },
{ "ER_CON_COUNT_ERROR", 1040 },
{ "ER_OUT_OF_RESOURCES", 1041 },
{ "ER_BAD_HOST_ERROR", 1042 },
{ "ER_HANDSHAKE_ERROR", 1043 },
{ "ER_DBACCESS_DENIED_ERROR", 1044 },
{ "ER_ACCESS_DENIED_ERROR", 1045 },
{ "ER_NO_DB_ERROR", 1046 },
{ "ER_UNKNOWN_COM_ERROR", 1047 },
{ "ER_BAD_NULL_ERROR", 1048 },
{ "ER_BAD_DB_ERROR", 1049 },
{ "ER_TABLE_EXISTS_ERROR", 1050 },
{ "ER_BAD_TABLE_ERROR", 1051 },
{ "ER_NON_UNIQ_ERROR", 1052 },
{ "ER_SERVER_SHUTDOWN", 1053 },
{ "ER_BAD_FIELD_ERROR", 1054 },
{ "ER_WRONG_FIELD_WITH_GROUP", 1055 },
{ "ER_WRONG_GROUP_FIELD", 1056 },
{ "ER_WRONG_SUM_SELECT", 1057 },
{ "ER_WRONG_VALUE_COUNT", 1058 },
{ "ER_TOO_LONG_IDENT", 1059 },
{ "ER_DUP_FIELDNAME", 1060 },
{ "ER_DUP_KEYNAME", 1061 },
{ "ER_DUP_ENTRY", 1062 },
{ "ER_WRONG_FIELD_SPEC", 1063 },
{ "ER_PARSE_ERROR", 1064 },
{ "ER_EMPTY_QUERY", 1065 },
{ "ER_NONUNIQ_TABLE", 1066 },
{ "ER_INVALID_DEFAULT", 1067 },
{ "ER_MULTIPLE_PRI_KEY", 1068 },
{ "ER_TOO_MANY_KEYS", 1069 },
{ "ER_TOO_MANY_KEY_PARTS", 1070 },
{ "ER_TOO_LONG_KEY", 1071 },
{ "ER_KEY_COLUMN_DOES_NOT_EXITS", 1072 },
{ "ER_BLOB_USED_AS_KEY", 1073 },
{ "ER_TOO_BIG_FIELDLENGTH", 1074 },
{ "ER_WRONG_AUTO_KEY", 1075 },
{ "ER_READY", 1076 },
{ "ER_NORMAL_SHUTDOWN", 1077 },
{ "ER_GOT_SIGNAL", 1078 },
{ "ER_SHUTDOWN_COMPLETE", 1079 },
{ "ER_FORCING_CLOSE", 1080 },
{ "ER_IPSOCK_ERROR", 1081 },
{ "ER_NO_SUCH_INDEX", 1082 },
{ "ER_WRONG_FIELD_TERMINATORS", 1083 },
{ "ER_BLOBS_AND_NO_TERMINATED", 1084 },
{ "ER_TEXTFILE_NOT_READABLE", 1085 },
{ "ER_FILE_EXISTS_ERROR", 1086 },
{ "ER_LOAD_INFO", 1087 },
{ "ER_ALTER_INFO", 1088 },
{ "ER_WRONG_SUB_KEY", 1089 },
{ "ER_CANT_REMOVE_ALL_FIELDS", 1090 },
{ "ER_CANT_DROP_FIELD_OR_KEY", 1091 },
{ "ER_INSERT_INFO", 1092 },
{ "ER_UPDATE_TABLE_USED", 1093 },
{ "ER_NO_SUCH_THREAD", 1094 },
{ "ER_KILL_DENIED_ERROR", 1095 },
{ "ER_NO_TABLES_USED", 1096 },
{ "ER_TOO_BIG_SET", 1097 },
{ "ER_NO_UNIQUE_LOGFILE", 1098 },
{ "ER_TABLE_NOT_LOCKED_FOR_WRITE", 1099 },
{ "ER_TABLE_NOT_LOCKED", 1100 },
{ "ER_BLOB_CANT_HAVE_DEFAULT", 1101 },
{ "ER_WRONG_DB_NAME", 1102 },
{ "ER_WRONG_TABLE_NAME", 1103 },
{ "ER_TOO_BIG_SELECT", 1104 },
{ "ER_UNKNOWN_ERROR", 1105 },
{ "ER_UNKNOWN_PROCEDURE", 1106 },
{ "ER_WRONG_PARAMCOUNT_TO_PROCEDURE", 1107 },
{ "ER_WRONG_PARAMETERS_TO_PROCEDURE", 1108 },
{ "ER_UNKNOWN_TABLE", 1109 },
{ "ER_FIELD_SPECIFIED_TWICE", 1110 },
{ "ER_INVALID_GROUP_FUNC_USE", 1111 },
{ "ER_UNSUPPORTED_EXTENSION", 1112 },
{ "ER_TABLE_MUST_HAVE_COLUMNS", 1113 },
{ "ER_RECORD_FILE_FULL", 1114 },
{ "ER_UNKNOWN_CHARACTER_SET", 1115 },
{ "ER_TOO_MANY_TABLES", 1116 },
{ "ER_TOO_MANY_FIELDS", 1117 },
{ "ER_TOO_BIG_ROWSIZE", 1118 },
{ "ER_STACK_OVERRUN", 1119 },
{ "ER_WRONG_OUTER_JOIN", 1120 },
{ "ER_NULL_COLUMN_IN_INDEX", 1121 },
{ "ER_CANT_FIND_UDF", 1122 },
{ "ER_CANT_INITIALIZE_UDF", 1123 },
{ "ER_UDF_NO_PATHS", 1124 },
{ "ER_UDF_EXISTS", 1125 },
{ "ER_CANT_OPEN_LIBRARY", 1126 },
{ "ER_CANT_FIND_DL_ENTRY", 1127 },
{ "ER_FUNCTION_NOT_DEFINED", 1128 },
{ "ER_HOST_IS_BLOCKED", 1129 },
{ "ER_HOST_NOT_PRIVILEGED", 1130 },
{ "ER_PASSWORD_ANONYMOUS_USER", 1131 },
{ "ER_PASSWORD_NOT_ALLOWED", 1132 },
{ "ER_PASSWORD_NO_MATCH", 1133 },
{ "ER_UPDATE_INFO", 1134 },
{ "ER_CANT_CREATE_THREAD", 1135 },
{ "ER_WRONG_VALUE_COUNT_ON_ROW", 1136 },
{ "ER_CANT_REOPEN_TABLE", 1137 },
{ "ER_INVALID_USE_OF_NULL", 1138 },
{ "ER_REGEXP_ERROR", 1139 },
{ "ER_MIX_OF_GROUP_FUNC_AND_FIELDS", 1140 },
{ "ER_NONEXISTING_GRANT", 1141 },
{ "ER_TABLEACCESS_DENIED_ERROR", 1142 },
{ "ER_COLUMNACCESS_DENIED_ERROR", 1143 },
{ "ER_ILLEGAL_GRANT_FOR_TABLE", 1144 },
{ "ER_GRANT_WRONG_HOST_OR_USER", 1145 },
{ "ER_NO_SUCH_TABLE", 1146 },
{ "ER_NONEXISTING_TABLE_GRANT", 1147 },
{ "ER_NOT_ALLOWED_COMMAND", 1148 },
{ "ER_SYNTAX_ERROR", 1149 },
{ "ER_DELAYED_CANT_CHANGE_LOCK", 1150 },
{ "ER_TOO_MANY_DELAYED_THREADS", 1151 },
{ "ER_ABORTING_CONNECTION", 1152 },
{ "ER_NET_PACKET_TOO_LARGE", 1153 },
{ "ER_NET_READ_ERROR_FROM_PIPE", 1154 },
{ "ER_NET_FCNTL_ERROR", 1155 },
{ "ER_NET_PACKETS_OUT_OF_ORDER", 1156 },
{ "ER_NET_UNCOMPRESS_ERROR", 1157 },
{ "ER_NET_READ_ERROR", 1158 },
{ "ER_NET_READ_INTERRUPTED", 1159 },
{ "ER_NET_ERROR_ON_WRITE", 1160 },
{ "ER_NET_WRITE_INTERRUPTED", 1161 },
{ "ER_TOO_LONG_STRING", 1162 },
{ "ER_TABLE_CANT_HANDLE_BLOB", 1163 },
{ "ER_TABLE_CANT_HANDLE_AUTO_INCREMENT", 1164 },
{ "ER_DELAYED_INSERT_TABLE_LOCKED", 1165 },
{ "ER_WRONG_COLUMN_NAME", 1166 },
{ "ER_WRONG_KEY_COLUMN", 1167 },
{ "ER_WRONG_MRG_TABLE", 1168 },
{ "ER_DUP_UNIQUE", 1169 },
{ "ER_BLOB_KEY_WITHOUT_LENGTH", 1170 },
{ "ER_PRIMARY_CANT_HAVE_NULL", 1171 },
{ "ER_TOO_MANY_ROWS", 1172 },
{ "ER_REQUIRES_PRIMARY_KEY", 1173 },
{ "ER_NO_RAID_COMPILED", 1174 },
{ "ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE", 1175 },
{ "ER_KEY_DOES_NOT_EXITS", 1176 },
{ "ER_CHECK_NO_SUCH_TABLE", 1177 },
{ "ER_CHECK_NOT_IMPLEMENTED", 1178 },
{ "ER_CANT_DO_THIS_DURING_AN_TRANSACTION", 1179 },
{ "ER_ERROR_DURING_COMMIT", 1180 },
{ "ER_ERROR_DURING_ROLLBACK", 1181 },
{ "ER_ERROR_DURING_FLUSH_LOGS", 1182 },
{ "ER_ERROR_DURING_CHECKPOINT", 1183 },
{ "ER_NEW_ABORTING_CONNECTION", 1184 },
{ "ER_DUMP_NOT_IMPLEMENTED", 1185 },
{ "ER_FLUSH_MASTER_BINLOG_CLOSED", 1186 },
{ "ER_INDEX_REBUILD", 1187 },
{ "ER_MASTER", 1188 },
{ "ER_MASTER_NET_READ", 1189 },
{ "ER_MASTER_NET_WRITE", 1190 },
{ "ER_FT_MATCHING_KEY_NOT_FOUND", 1191 },
{ "ER_LOCK_OR_ACTIVE_TRANSACTION", 1192 },
{ "ER_UNKNOWN_SYSTEM_VARIABLE", 1193 },
{ "ER_CRASHED_ON_USAGE", 1194 },
{ "ER_CRASHED_ON_REPAIR", 1195 },
{ "ER_WARNING_NOT_COMPLETE_ROLLBACK", 1196 },
{ "ER_TRANS_CACHE_FULL", 1197 },
{ "ER_SLAVE_MUST_STOP", 1198 },
{ "ER_SLAVE_NOT_RUNNING", 1199 },
{ "ER_BAD_SLAVE", 1200 },
{ "ER_MASTER_INFO", 1201 },
{ "ER_SLAVE_THREAD", 1202 },
{ "ER_TOO_MANY_USER_CONNECTIONS", 1203 },
{ "ER_SET_CONSTANTS_ONLY", 1204 },
{ "ER_LOCK_WAIT_TIMEOUT", 1205 },
{ "ER_LOCK_TABLE_FULL", 1206 },
{ "ER_READ_ONLY_TRANSACTION", 1207 },
{ "ER_DROP_DB_WITH_READ_LOCK", 1208 },
{ "ER_CREATE_DB_WITH_READ_LOCK", 1209 },
{ "ER_WRONG_ARGUMENTS", 1210 },
{ "ER_NO_PERMISSION_TO_CREATE_USER", 1211 },
{ "ER_UNION_TABLES_IN_DIFFERENT_DIR", 1212 },
{ "ER_LOCK_DEADLOCK", 1213 },
{ "ER_TABLE_CANT_HANDLE_FT", 1214 },
{ "ER_CANNOT_ADD_FOREIGN", 1215 },
{ "ER_NO_REFERENCED_ROW", 1216 },
{ "ER_ROW_IS_REFERENCED", 1217 },
{ "ER_CONNECT_TO_MASTER", 1218 },
{ "ER_QUERY_ON_MASTER", 1219 },
{ "ER_ERROR_WHEN_EXECUTING_COMMAND", 1220 },
{ "ER_WRONG_USAGE", 1221 },
{ "ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT", 1222 },
{ "ER_CANT_UPDATE_WITH_READLOCK", 1223 },
{ "ER_MIXING_NOT_ALLOWED", 1224 },
{ "ER_DUP_ARGUMENT", 1225 },
{ "ER_USER_LIMIT_REACHED", 1226 },
{ "ER_SPECIFIC_ACCESS_DENIED_ERROR", 1227 },
{ "ER_LOCAL_VARIABLE", 1228 },
{ "ER_GLOBAL_VARIABLE", 1229 },
{ "ER_NO_DEFAULT", 1230 },
{ "ER_WRONG_VALUE_FOR_VAR", 1231 },
{ "ER_WRONG_TYPE_FOR_VAR", 1232 },
{ "ER_VAR_CANT_BE_READ", 1233 },
{ "ER_CANT_USE_OPTION_HERE", 1234 },
{ "ER_NOT_SUPPORTED_YET", 1235 },
{ "ER_MASTER_FATAL_ERROR_READING_BINLOG", 1236 },
{ "ER_SLAVE_IGNORED_TABLE", 1237 },
{ "ER_INCORRECT_GLOBAL_LOCAL_VAR", 1238 },
{ "ER_WRONG_FK_DEF", 1239 },
{ "ER_KEY_REF_DO_NOT_MATCH_TABLE_REF", 1240 },
{ "ER_OPERAND_COLUMNS", 1241 },
{ "ER_SUBQUERY_NO_1_ROW", 1242 },
{ "ER_UNKNOWN_STMT_HANDLER", 1243 },
{ "ER_CORRUPT_HELP_DB", 1244 },
{ "ER_CYCLIC_REFERENCE", 1245 },
{ "ER_AUTO_CONVERT", 1246 },
{ "ER_ILLEGAL_REFERENCE", 1247 },
{ "ER_DERIVED_MUST_HAVE_ALIAS", 1248 },
{ "ER_SELECT_REDUCED", 1249 },
{ "ER_TABLENAME_NOT_ALLOWED_HERE", 1250 },
{ "ER_NOT_SUPPORTED_AUTH_MODE", 1251 },
{ "ER_SPATIAL_CANT_HAVE_NULL", 1252 },
{ "ER_COLLATION_CHARSET_MISMATCH", 1253 },
{ "ER_SLAVE_WAS_RUNNING", 1254 },
{ "ER_SLAVE_WAS_NOT_RUNNING", 1255 },
{ "ER_TOO_BIG_FOR_UNCOMPRESS", 1256 },
{ "ER_ZLIB_Z_MEM_ERROR", 1257 },
{ "ER_ZLIB_Z_BUF_ERROR", 1258 },
{ "ER_ZLIB_Z_DATA_ERROR", 1259 },
{ "ER_CUT_VALUE_GROUP_CONCAT", 1260 },
{ "ER_WARN_TOO_FEW_RECORDS", 1261 },
{ "ER_WARN_TOO_MANY_RECORDS", 1262 },
{ "ER_WARN_NULL_TO_NOTNULL", 1263 },
{ "ER_WARN_DATA_OUT_OF_RANGE", 1264 },
{ "WARN_DATA_TRUNCATED", 1265 },
{ "ER_WARN_USING_OTHER_HANDLER", 1266 },
{ "ER_CANT_AGGREGATE_2COLLATIONS", 1267 },
{ "ER_DROP_USER", 1268 },
{ "ER_REVOKE_GRANTS", 1269 },
{ "ER_CANT_AGGREGATE_3COLLATIONS", 1270 },
{ "ER_CANT_AGGREGATE_NCOLLATIONS", 1271 },
{ "ER_VARIABLE_IS_NOT_STRUCT", 1272 },
{ "ER_UNKNOWN_COLLATION", 1273 },
{ "ER_SLAVE_IGNORED_SSL_PARAMS", 1274 },
{ "ER_SERVER_IS_IN_SECURE_AUTH_MODE", 1275 },
{ "ER_WARN_FIELD_RESOLVED", 1276 },
{ "ER_BAD_SLAVE_UNTIL_COND", 1277 },
{ "ER_MISSING_SKIP_SLAVE", 1278 },
{ "ER_UNTIL_COND_IGNORED", 1279 },
{ "ER_WRONG_NAME_FOR_INDEX", 1280 },
{ "ER_WRONG_NAME_FOR_CATALOG", 1281 },
{ "ER_WARN_QC_RESIZE", 1282 },
{ "ER_BAD_FT_COLUMN", 1283 },
{ "ER_UNKNOWN_KEY_CACHE", 1284 },
{ "ER_WARN_HOSTNAME_WONT_WORK", 1285 },
{ "ER_UNKNOWN_STORAGE_ENGINE", 1286 },
{ "ER_WARN_DEPRECATED_SYNTAX", 1287 },
{ "ER_NON_UPDATABLE_TABLE", 1288 },
{ "ER_FEATURE_DISABLED", 1289 },
{ "ER_OPTION_PREVENTS_STATEMENT", 1290 },
{ "ER_DUPLICATED_VALUE_IN_TYPE", 1291 },
{ "ER_TRUNCATED_WRONG_VALUE", 1292 },
{ "ER_TOO_MUCH_AUTO_TIMESTAMP_COLS", 1293 },
{ "ER_INVALID_ON_UPDATE", 1294 },
{ "ER_UNSUPPORTED_PS", 1295 },
{ "ER_GET_ERRMSG", 1296 },
{ "ER_GET_TEMPORARY_ERRMSG", 1297 },
{ "ER_UNKNOWN_TIME_ZONE", 1298 },
{ "ER_WARN_INVALID_TIMESTAMP", 1299 },
{ "ER_INVALID_CHARACTER_STRING", 1300 },
{ "ER_WARN_ALLOWED_PACKET_OVERFLOWED", 1301 },
{ "ER_CONFLICTING_DECLARATIONS", 1302 },
{ "ER_SP_NO_RECURSIVE_CREATE", 1303 },
{ "ER_SP_ALREADY_EXISTS", 1304 },
{ "ER_SP_DOES_NOT_EXIST", 1305 },
{ "ER_SP_DROP_FAILED", 1306 },
{ "ER_SP_STORE_FAILED", 1307 },
{ "ER_SP_LILABEL_MISMATCH", 1308 },
{ "ER_SP_LABEL_REDEFINE", 1309 },
{ "ER_SP_LABEL_MISMATCH", 1310 },
{ "ER_SP_UNINIT_VAR", 1311 },
{ "ER_SP_BADSELECT", 1312 },
{ "ER_SP_BADRETURN", 1313 },
{ "ER_SP_BADSTATEMENT", 1314 },
{ "ER_UPDATE_LOG_DEPRECATED_IGNORED", 1315 },
{ "ER_UPDATE_LOG_DEPRECATED_TRANSLATED", 1316 },
{ "ER_QUERY_INTERRUPTED", 1317 },
{ "ER_SP_WRONG_NO_OF_ARGS", 1318 },
{ "ER_SP_COND_MISMATCH", 1319 },
{ "ER_SP_NORETURN", 1320 },
{ "ER_SP_NORETURNEND", 1321 },
{ "ER_SP_BAD_CURSOR_QUERY", 1322 },
{ "ER_SP_BAD_CURSOR_SELECT", 1323 },
{ "ER_SP_CURSOR_MISMATCH", 1324 },
{ "ER_SP_CURSOR_ALREADY_OPEN", 1325 },
{ "ER_SP_CURSOR_NOT_OPEN", 1326 },
{ "ER_SP_UNDECLARED_VAR", 1327 },
{ "ER_SP_WRONG_NO_OF_FETCH_ARGS", 1328 },
{ "ER_SP_FETCH_NO_DATA", 1329 },
{ "ER_SP_DUP_PARAM", 1330 },
{ "ER_SP_DUP_VAR", 1331 },
{ "ER_SP_DUP_COND", 1332 },
{ "ER_SP_DUP_CURS", 1333 },
{ "ER_SP_CANT_ALTER", 1334 },
{ "ER_SP_SUBSELECT_NYI", 1335 },
{ "ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG", 1336 },
{ "ER_SP_VARCOND_AFTER_CURSHNDLR", 1337 },
{ "ER_SP_CURSOR_AFTER_HANDLER", 1338 },
{ "ER_SP_CASE_NOT_FOUND", 1339 },
{ "ER_FPARSER_TOO_BIG_FILE", 1340 },
{ "ER_FPARSER_BAD_HEADER", 1341 },
{ "ER_FPARSER_EOF_IN_COMMENT", 1342 },
{ "ER_FPARSER_ERROR_IN_PARAMETER", 1343 },
{ "ER_FPARSER_EOF_IN_UNKNOWN_PARAMETER", 1344 },
{ "ER_VIEW_NO_EXPLAIN", 1345 },
{ "ER_FRM_UNKNOWN_TYPE", 1346 },
{ "ER_WRONG_OBJECT", 1347 },
{ "ER_NONUPDATEABLE_COLUMN", 1348 },
{ "ER_VIEW_SELECT_DERIVED", 1349 },
{ "ER_VIEW_SELECT_CLAUSE", 1350 },
{ "ER_VIEW_SELECT_VARIABLE", 1351 },
{ "ER_VIEW_SELECT_TMPTABLE", 1352 },
{ "ER_VIEW_WRONG_LIST", 1353 },
{ "ER_WARN_VIEW_MERGE", 1354 },
{ "ER_WARN_VIEW_WITHOUT_KEY", 1355 },
{ "ER_VIEW_INVALID", 1356 },
{ "ER_SP_NO_DROP_SP", 1357 },
{ "ER_SP_GOTO_IN_HNDLR", 1358 },
{ "ER_TRG_ALREADY_EXISTS", 1359 },
{ "ER_TRG_DOES_NOT_EXIST", 1360 },
{ "ER_TRG_ON_VIEW_OR_TEMP_TABLE", 1361 },
{ "ER_TRG_CANT_CHANGE_ROW", 1362 },
{ "ER_TRG_NO_SUCH_ROW_IN_TRG", 1363 },
{ "ER_NO_DEFAULT_FOR_FIELD", 1364 },
{ "ER_DIVISION_BY_ZERO", 1365 },
{ "ER_TRUNCATED_WRONG_VALUE_FOR_FIELD", 1366 },
{ "ER_ILLEGAL_VALUE_FOR_TYPE", 1367 },
{ "ER_VIEW_NONUPD_CHECK", 1368 },
{ "ER_VIEW_CHECK_FAILED", 1369 },
{ "ER_PROCACCESS_DENIED_ERROR", 1370 },
{ "ER_RELAY_LOG_FAIL", 1371 },
{ "ER_PASSWD_LENGTH", 1372 },
{ "ER_UNKNOWN_TARGET_BINLOG", 1373 },
{ "ER_IO_ERR_LOG_INDEX_READ", 1374 },
{ "ER_BINLOG_PURGE_PROHIBITED", 1375 },
{ "ER_FSEEK_FAIL", 1376 },
{ "ER_BINLOG_PURGE_FATAL_ERR", 1377 },
{ "ER_LOG_IN_USE", 1378 },
{ "ER_LOG_PURGE_UNKNOWN_ERR", 1379 },
{ "ER_RELAY_LOG_INIT", 1380 },
{ "ER_NO_BINARY_LOGGING", 1381 },
{ "ER_RESERVED_SYNTAX", 1382 },
{ "ER_WSAS_FAILED", 1383 },
{ "ER_DIFF_GROUPS_PROC", 1384 },
{ "ER_NO_GROUP_FOR_PROC", 1385 },
{ "ER_ORDER_WITH_PROC", 1386 },
{ "ER_LOGGING_PROHIBIT_CHANGING_OF", 1387 },
{ "ER_NO_FILE_MAPPING", 1388 },
{ "ER_WRONG_MAGIC", 1389 },
{ "ER_PS_MANY_PARAM", 1390 },
{ "ER_KEY_PART_0", 1391 },
{ "ER_VIEW_CHECKSUM", 1392 },
{ "ER_VIEW_MULTIUPDATE", 1393 },
{ "ER_VIEW_NO_INSERT_FIELD_LIST", 1394 },
{ "ER_VIEW_DELETE_MERGE_VIEW", 1395 },
{ "ER_CANNOT_USER", 1396 },
{ "ER_XAER_NOTA", 1397 },
{ "ER_XAER_INVAL", 1398 },
{ "ER_XAER_RMFAIL", 1399 },
{ "ER_XAER_OUTSIDE", 1400 },
{ "ER_XAER_RMERR", 1401 },
{ "ER_XA_RBROLLBACK", 1402 },
{ "ER_NONEXISTING_PROC_GRANT", 1403 },
{ "ER_PROC_AUTO_GRANT_FAIL", 1404 },
{ "ER_PROC_AUTO_REVOKE_FAIL", 1405 },
{ "ER_DATA_TOO_LONG", 1406 },
{ "ER_SP_BAD_SQLSTATE", 1407 },
{ "ER_STARTUP", 1408 },
{ "ER_LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR", 1409 },
{ "ER_CANT_CREATE_USER_WITH_GRANT", 1410 },
{ "ER_WRONG_VALUE_FOR_TYPE", 1411 },
{ "ER_TABLE_DEF_CHANGED", 1412 },
{ "ER_SP_DUP_HANDLER", 1413 },
{ "ER_SP_NOT_VAR_ARG", 1414 },
{ "ER_SP_NO_RETSET", 1415 },
{ "ER_CANT_CREATE_GEOMETRY_OBJECT", 1416 },
{ "ER_FAILED_ROUTINE_BREAK_BINLOG", 1417 },
{ "ER_BINLOG_UNSAFE_ROUTINE", 1418 },
{ "ER_BINLOG_CREATE_ROUTINE_NEED_SUPER", 1419 },
{ "ER_EXEC_STMT_WITH_OPEN_CURSOR", 1420 },
{ "ER_STMT_HAS_NO_OPEN_CURSOR", 1421 },
{ "ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG", 1422 },
{ "ER_NO_DEFAULT_FOR_VIEW_FIELD", 1423 },
{ "ER_SP_NO_RECURSION", 1424 },
{ "ER_TOO_BIG_SCALE", 1425 },
{ "ER_TOO_BIG_PRECISION", 1426 },
{ "ER_M_BIGGER_THAN_D", 1427 },
{ "ER_WRONG_LOCK_OF_SYSTEM_TABLE", 1428 },
{ "ER_CONNECT_TO_FOREIGN_DATA_SOURCE", 1429 },
{ "ER_QUERY_ON_FOREIGN_DATA_SOURCE", 1430 },
{ "ER_FOREIGN_DATA_SOURCE_DOESNT_EXIST", 1431 },
{ "ER_FOREIGN_DATA_STRING_INVALID_CANT_CREATE", 1432 },
{ "ER_FOREIGN_DATA_STRING_INVALID", 1433 },
{ "ER_CANT_CREATE_FEDERATED_TABLE", 1434 },
{ "ER_TRG_IN_WRONG_SCHEMA", 1435 },
{ "ER_STACK_OVERRUN_NEED_MORE", 1436 },
{ "ER_TOO_LONG_BODY", 1437 },
{ "ER_WARN_CANT_DROP_DEFAULT_KEYCACHE", 1438 },
{ "ER_TOO_BIG_DISPLAYWIDTH", 1439 },
{ "ER_XAER_DUPID", 1440 },
{ "ER_DATETIME_FUNCTION_OVERFLOW", 1441 },
{ "ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG", 1442 },
{ "ER_VIEW_PREVENT_UPDATE", 1443 },
{ "ER_PS_NO_RECURSION", 1444 },
{ "ER_SP_CANT_SET_AUTOCOMMIT", 1445 },
{ "ER_NO_VIEW_USER", 1446 },
{ "ER_VIEW_FRM_NO_USER", 1447 },
{ "ER_VIEW_OTHER_USER", 1448 },
{ "ER_NO_SUCH_USER", 1449 },
{ "ER_FORBID_SCHEMA_CHANGE", 1450 },
{ "ER_ROW_IS_REFERENCED_2", 1451 },
{ "ER_NO_REFERENCED_ROW_2", 1452 },
{ "ER_SP_BAD_VAR_SHADOW", 1453 },
+458
View File
@@ -0,0 +1,458 @@
/* Autogenerated file, please don't edit */
#define ER_ERROR_FIRST 1000
#define ER_HASHCHK 1000
#define ER_NISAMCHK 1001
#define ER_NO 1002
#define ER_YES 1003
#define ER_CANT_CREATE_FILE 1004
#define ER_CANT_CREATE_TABLE 1005
#define ER_CANT_CREATE_DB 1006
#define ER_DB_CREATE_EXISTS 1007
#define ER_DB_DROP_EXISTS 1008
#define ER_DB_DROP_DELETE 1009
#define ER_DB_DROP_RMDIR 1010
#define ER_CANT_DELETE_FILE 1011
#define ER_CANT_FIND_SYSTEM_REC 1012
#define ER_CANT_GET_STAT 1013
#define ER_CANT_GET_WD 1014
#define ER_CANT_LOCK 1015
#define ER_CANT_OPEN_FILE 1016
#define ER_FILE_NOT_FOUND 1017
#define ER_CANT_READ_DIR 1018
#define ER_CANT_SET_WD 1019
#define ER_CHECKREAD 1020
#define ER_DISK_FULL 1021
#define ER_DUP_KEY 1022
#define ER_ERROR_ON_CLOSE 1023
#define ER_ERROR_ON_READ 1024
#define ER_ERROR_ON_RENAME 1025
#define ER_ERROR_ON_WRITE 1026
#define ER_FILE_USED 1027
#define ER_FILSORT_ABORT 1028
#define ER_FORM_NOT_FOUND 1029
#define ER_GET_ERRNO 1030
#define ER_ILLEGAL_HA 1031
#define ER_KEY_NOT_FOUND 1032
#define ER_NOT_FORM_FILE 1033
#define ER_NOT_KEYFILE 1034
#define ER_OLD_KEYFILE 1035
#define ER_OPEN_AS_READONLY 1036
#define ER_OUTOFMEMORY 1037
#define ER_OUT_OF_SORTMEMORY 1038
#define ER_UNEXPECTED_EOF 1039
#define ER_CON_COUNT_ERROR 1040
#define ER_OUT_OF_RESOURCES 1041
#define ER_BAD_HOST_ERROR 1042
#define ER_HANDSHAKE_ERROR 1043
#define ER_DBACCESS_DENIED_ERROR 1044
#define ER_ACCESS_DENIED_ERROR 1045
#define ER_NO_DB_ERROR 1046
#define ER_UNKNOWN_COM_ERROR 1047
#define ER_BAD_NULL_ERROR 1048
#define ER_BAD_DB_ERROR 1049
#define ER_TABLE_EXISTS_ERROR 1050
#define ER_BAD_TABLE_ERROR 1051
#define ER_NON_UNIQ_ERROR 1052
#define ER_SERVER_SHUTDOWN 1053
#define ER_BAD_FIELD_ERROR 1054
#define ER_WRONG_FIELD_WITH_GROUP 1055
#define ER_WRONG_GROUP_FIELD 1056
#define ER_WRONG_SUM_SELECT 1057
#define ER_WRONG_VALUE_COUNT 1058
#define ER_TOO_LONG_IDENT 1059
#define ER_DUP_FIELDNAME 1060
#define ER_DUP_KEYNAME 1061
#define ER_DUP_ENTRY 1062
#define ER_WRONG_FIELD_SPEC 1063
#define ER_PARSE_ERROR 1064
#define ER_EMPTY_QUERY 1065
#define ER_NONUNIQ_TABLE 1066
#define ER_INVALID_DEFAULT 1067
#define ER_MULTIPLE_PRI_KEY 1068
#define ER_TOO_MANY_KEYS 1069
#define ER_TOO_MANY_KEY_PARTS 1070
#define ER_TOO_LONG_KEY 1071
#define ER_KEY_COLUMN_DOES_NOT_EXITS 1072
#define ER_BLOB_USED_AS_KEY 1073
#define ER_TOO_BIG_FIELDLENGTH 1074
#define ER_WRONG_AUTO_KEY 1075
#define ER_READY 1076
#define ER_NORMAL_SHUTDOWN 1077
#define ER_GOT_SIGNAL 1078
#define ER_SHUTDOWN_COMPLETE 1079
#define ER_FORCING_CLOSE 1080
#define ER_IPSOCK_ERROR 1081
#define ER_NO_SUCH_INDEX 1082
#define ER_WRONG_FIELD_TERMINATORS 1083
#define ER_BLOBS_AND_NO_TERMINATED 1084
#define ER_TEXTFILE_NOT_READABLE 1085
#define ER_FILE_EXISTS_ERROR 1086
#define ER_LOAD_INFO 1087
#define ER_ALTER_INFO 1088
#define ER_WRONG_SUB_KEY 1089
#define ER_CANT_REMOVE_ALL_FIELDS 1090
#define ER_CANT_DROP_FIELD_OR_KEY 1091
#define ER_INSERT_INFO 1092
#define ER_UPDATE_TABLE_USED 1093
#define ER_NO_SUCH_THREAD 1094
#define ER_KILL_DENIED_ERROR 1095
#define ER_NO_TABLES_USED 1096
#define ER_TOO_BIG_SET 1097
#define ER_NO_UNIQUE_LOGFILE 1098
#define ER_TABLE_NOT_LOCKED_FOR_WRITE 1099
#define ER_TABLE_NOT_LOCKED 1100
#define ER_BLOB_CANT_HAVE_DEFAULT 1101
#define ER_WRONG_DB_NAME 1102
#define ER_WRONG_TABLE_NAME 1103
#define ER_TOO_BIG_SELECT 1104
#define ER_UNKNOWN_ERROR 1105
#define ER_UNKNOWN_PROCEDURE 1106
#define ER_WRONG_PARAMCOUNT_TO_PROCEDURE 1107
#define ER_WRONG_PARAMETERS_TO_PROCEDURE 1108
#define ER_UNKNOWN_TABLE 1109
#define ER_FIELD_SPECIFIED_TWICE 1110
#define ER_INVALID_GROUP_FUNC_USE 1111
#define ER_UNSUPPORTED_EXTENSION 1112
#define ER_TABLE_MUST_HAVE_COLUMNS 1113
#define ER_RECORD_FILE_FULL 1114
#define ER_UNKNOWN_CHARACTER_SET 1115
#define ER_TOO_MANY_TABLES 1116
#define ER_TOO_MANY_FIELDS 1117
#define ER_TOO_BIG_ROWSIZE 1118
#define ER_STACK_OVERRUN 1119
#define ER_WRONG_OUTER_JOIN 1120
#define ER_NULL_COLUMN_IN_INDEX 1121
#define ER_CANT_FIND_UDF 1122
#define ER_CANT_INITIALIZE_UDF 1123
#define ER_UDF_NO_PATHS 1124
#define ER_UDF_EXISTS 1125
#define ER_CANT_OPEN_LIBRARY 1126
#define ER_CANT_FIND_DL_ENTRY 1127
#define ER_FUNCTION_NOT_DEFINED 1128
#define ER_HOST_IS_BLOCKED 1129
#define ER_HOST_NOT_PRIVILEGED 1130
#define ER_PASSWORD_ANONYMOUS_USER 1131
#define ER_PASSWORD_NOT_ALLOWED 1132
#define ER_PASSWORD_NO_MATCH 1133
#define ER_UPDATE_INFO 1134
#define ER_CANT_CREATE_THREAD 1135
#define ER_WRONG_VALUE_COUNT_ON_ROW 1136
#define ER_CANT_REOPEN_TABLE 1137
#define ER_INVALID_USE_OF_NULL 1138
#define ER_REGEXP_ERROR 1139
#define ER_MIX_OF_GROUP_FUNC_AND_FIELDS 1140
#define ER_NONEXISTING_GRANT 1141
#define ER_TABLEACCESS_DENIED_ERROR 1142
#define ER_COLUMNACCESS_DENIED_ERROR 1143
#define ER_ILLEGAL_GRANT_FOR_TABLE 1144
#define ER_GRANT_WRONG_HOST_OR_USER 1145
#define ER_NO_SUCH_TABLE 1146
#define ER_NONEXISTING_TABLE_GRANT 1147
#define ER_NOT_ALLOWED_COMMAND 1148
#define ER_SYNTAX_ERROR 1149
#define ER_DELAYED_CANT_CHANGE_LOCK 1150
#define ER_TOO_MANY_DELAYED_THREADS 1151
#define ER_ABORTING_CONNECTION 1152
#define ER_NET_PACKET_TOO_LARGE 1153
#define ER_NET_READ_ERROR_FROM_PIPE 1154
#define ER_NET_FCNTL_ERROR 1155
#define ER_NET_PACKETS_OUT_OF_ORDER 1156
#define ER_NET_UNCOMPRESS_ERROR 1157
#define ER_NET_READ_ERROR 1158
#define ER_NET_READ_INTERRUPTED 1159
#define ER_NET_ERROR_ON_WRITE 1160
#define ER_NET_WRITE_INTERRUPTED 1161
#define ER_TOO_LONG_STRING 1162
#define ER_TABLE_CANT_HANDLE_BLOB 1163
#define ER_TABLE_CANT_HANDLE_AUTO_INCREMENT 1164
#define ER_DELAYED_INSERT_TABLE_LOCKED 1165
#define ER_WRONG_COLUMN_NAME 1166
#define ER_WRONG_KEY_COLUMN 1167
#define ER_WRONG_MRG_TABLE 1168
#define ER_DUP_UNIQUE 1169
#define ER_BLOB_KEY_WITHOUT_LENGTH 1170
#define ER_PRIMARY_CANT_HAVE_NULL 1171
#define ER_TOO_MANY_ROWS 1172
#define ER_REQUIRES_PRIMARY_KEY 1173
#define ER_NO_RAID_COMPILED 1174
#define ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE 1175
#define ER_KEY_DOES_NOT_EXITS 1176
#define ER_CHECK_NO_SUCH_TABLE 1177
#define ER_CHECK_NOT_IMPLEMENTED 1178
#define ER_CANT_DO_THIS_DURING_AN_TRANSACTION 1179
#define ER_ERROR_DURING_COMMIT 1180
#define ER_ERROR_DURING_ROLLBACK 1181
#define ER_ERROR_DURING_FLUSH_LOGS 1182
#define ER_ERROR_DURING_CHECKPOINT 1183
#define ER_NEW_ABORTING_CONNECTION 1184
#define ER_DUMP_NOT_IMPLEMENTED 1185
#define ER_FLUSH_MASTER_BINLOG_CLOSED 1186
#define ER_INDEX_REBUILD 1187
#define ER_MASTER 1188
#define ER_MASTER_NET_READ 1189
#define ER_MASTER_NET_WRITE 1190
#define ER_FT_MATCHING_KEY_NOT_FOUND 1191
#define ER_LOCK_OR_ACTIVE_TRANSACTION 1192
#define ER_UNKNOWN_SYSTEM_VARIABLE 1193
#define ER_CRASHED_ON_USAGE 1194
#define ER_CRASHED_ON_REPAIR 1195
#define ER_WARNING_NOT_COMPLETE_ROLLBACK 1196
#define ER_TRANS_CACHE_FULL 1197
#define ER_SLAVE_MUST_STOP 1198
#define ER_SLAVE_NOT_RUNNING 1199
#define ER_BAD_SLAVE 1200
#define ER_MASTER_INFO 1201
#define ER_SLAVE_THREAD 1202
#define ER_TOO_MANY_USER_CONNECTIONS 1203
#define ER_SET_CONSTANTS_ONLY 1204
#define ER_LOCK_WAIT_TIMEOUT 1205
#define ER_LOCK_TABLE_FULL 1206
#define ER_READ_ONLY_TRANSACTION 1207
#define ER_DROP_DB_WITH_READ_LOCK 1208
#define ER_CREATE_DB_WITH_READ_LOCK 1209
#define ER_WRONG_ARGUMENTS 1210
#define ER_NO_PERMISSION_TO_CREATE_USER 1211
#define ER_UNION_TABLES_IN_DIFFERENT_DIR 1212
#define ER_LOCK_DEADLOCK 1213
#define ER_TABLE_CANT_HANDLE_FT 1214
#define ER_CANNOT_ADD_FOREIGN 1215
#define ER_NO_REFERENCED_ROW 1216
#define ER_ROW_IS_REFERENCED 1217
#define ER_CONNECT_TO_MASTER 1218
#define ER_QUERY_ON_MASTER 1219
#define ER_ERROR_WHEN_EXECUTING_COMMAND 1220
#define ER_WRONG_USAGE 1221
#define ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT 1222
#define ER_CANT_UPDATE_WITH_READLOCK 1223
#define ER_MIXING_NOT_ALLOWED 1224
#define ER_DUP_ARGUMENT 1225
#define ER_USER_LIMIT_REACHED 1226
#define ER_SPECIFIC_ACCESS_DENIED_ERROR 1227
#define ER_LOCAL_VARIABLE 1228
#define ER_GLOBAL_VARIABLE 1229
#define ER_NO_DEFAULT 1230
#define ER_WRONG_VALUE_FOR_VAR 1231
#define ER_WRONG_TYPE_FOR_VAR 1232
#define ER_VAR_CANT_BE_READ 1233
#define ER_CANT_USE_OPTION_HERE 1234
#define ER_NOT_SUPPORTED_YET 1235
#define ER_MASTER_FATAL_ERROR_READING_BINLOG 1236
#define ER_SLAVE_IGNORED_TABLE 1237
#define ER_INCORRECT_GLOBAL_LOCAL_VAR 1238
#define ER_WRONG_FK_DEF 1239
#define ER_KEY_REF_DO_NOT_MATCH_TABLE_REF 1240
#define ER_OPERAND_COLUMNS 1241
#define ER_SUBQUERY_NO_1_ROW 1242
#define ER_UNKNOWN_STMT_HANDLER 1243
#define ER_CORRUPT_HELP_DB 1244
#define ER_CYCLIC_REFERENCE 1245
#define ER_AUTO_CONVERT 1246
#define ER_ILLEGAL_REFERENCE 1247
#define ER_DERIVED_MUST_HAVE_ALIAS 1248
#define ER_SELECT_REDUCED 1249
#define ER_TABLENAME_NOT_ALLOWED_HERE 1250
#define ER_NOT_SUPPORTED_AUTH_MODE 1251
#define ER_SPATIAL_CANT_HAVE_NULL 1252
#define ER_COLLATION_CHARSET_MISMATCH 1253
#define ER_SLAVE_WAS_RUNNING 1254
#define ER_SLAVE_WAS_NOT_RUNNING 1255
#define ER_TOO_BIG_FOR_UNCOMPRESS 1256
#define ER_ZLIB_Z_MEM_ERROR 1257
#define ER_ZLIB_Z_BUF_ERROR 1258
#define ER_ZLIB_Z_DATA_ERROR 1259
#define ER_CUT_VALUE_GROUP_CONCAT 1260
#define ER_WARN_TOO_FEW_RECORDS 1261
#define ER_WARN_TOO_MANY_RECORDS 1262
#define ER_WARN_NULL_TO_NOTNULL 1263
#define ER_WARN_DATA_OUT_OF_RANGE 1264
#define WARN_DATA_TRUNCATED 1265
#define ER_WARN_USING_OTHER_HANDLER 1266
#define ER_CANT_AGGREGATE_2COLLATIONS 1267
#define ER_DROP_USER 1268
#define ER_REVOKE_GRANTS 1269
#define ER_CANT_AGGREGATE_3COLLATIONS 1270
#define ER_CANT_AGGREGATE_NCOLLATIONS 1271
#define ER_VARIABLE_IS_NOT_STRUCT 1272
#define ER_UNKNOWN_COLLATION 1273
#define ER_SLAVE_IGNORED_SSL_PARAMS 1274
#define ER_SERVER_IS_IN_SECURE_AUTH_MODE 1275
#define ER_WARN_FIELD_RESOLVED 1276
#define ER_BAD_SLAVE_UNTIL_COND 1277
#define ER_MISSING_SKIP_SLAVE 1278
#define ER_UNTIL_COND_IGNORED 1279
#define ER_WRONG_NAME_FOR_INDEX 1280
#define ER_WRONG_NAME_FOR_CATALOG 1281
#define ER_WARN_QC_RESIZE 1282
#define ER_BAD_FT_COLUMN 1283
#define ER_UNKNOWN_KEY_CACHE 1284
#define ER_WARN_HOSTNAME_WONT_WORK 1285
#define ER_UNKNOWN_STORAGE_ENGINE 1286
#define ER_WARN_DEPRECATED_SYNTAX 1287
#define ER_NON_UPDATABLE_TABLE 1288
#define ER_FEATURE_DISABLED 1289
#define ER_OPTION_PREVENTS_STATEMENT 1290
#define ER_DUPLICATED_VALUE_IN_TYPE 1291
#define ER_TRUNCATED_WRONG_VALUE 1292
#define ER_TOO_MUCH_AUTO_TIMESTAMP_COLS 1293
#define ER_INVALID_ON_UPDATE 1294
#define ER_UNSUPPORTED_PS 1295
#define ER_GET_ERRMSG 1296
#define ER_GET_TEMPORARY_ERRMSG 1297
#define ER_UNKNOWN_TIME_ZONE 1298
#define ER_WARN_INVALID_TIMESTAMP 1299
#define ER_INVALID_CHARACTER_STRING 1300
#define ER_WARN_ALLOWED_PACKET_OVERFLOWED 1301
#define ER_CONFLICTING_DECLARATIONS 1302
#define ER_SP_NO_RECURSIVE_CREATE 1303
#define ER_SP_ALREADY_EXISTS 1304
#define ER_SP_DOES_NOT_EXIST 1305
#define ER_SP_DROP_FAILED 1306
#define ER_SP_STORE_FAILED 1307
#define ER_SP_LILABEL_MISMATCH 1308
#define ER_SP_LABEL_REDEFINE 1309
#define ER_SP_LABEL_MISMATCH 1310
#define ER_SP_UNINIT_VAR 1311
#define ER_SP_BADSELECT 1312
#define ER_SP_BADRETURN 1313
#define ER_SP_BADSTATEMENT 1314
#define ER_UPDATE_LOG_DEPRECATED_IGNORED 1315
#define ER_UPDATE_LOG_DEPRECATED_TRANSLATED 1316
#define ER_QUERY_INTERRUPTED 1317
#define ER_SP_WRONG_NO_OF_ARGS 1318
#define ER_SP_COND_MISMATCH 1319
#define ER_SP_NORETURN 1320
#define ER_SP_NORETURNEND 1321
#define ER_SP_BAD_CURSOR_QUERY 1322
#define ER_SP_BAD_CURSOR_SELECT 1323
#define ER_SP_CURSOR_MISMATCH 1324
#define ER_SP_CURSOR_ALREADY_OPEN 1325
#define ER_SP_CURSOR_NOT_OPEN 1326
#define ER_SP_UNDECLARED_VAR 1327
#define ER_SP_WRONG_NO_OF_FETCH_ARGS 1328
#define ER_SP_FETCH_NO_DATA 1329
#define ER_SP_DUP_PARAM 1330
#define ER_SP_DUP_VAR 1331
#define ER_SP_DUP_COND 1332
#define ER_SP_DUP_CURS 1333
#define ER_SP_CANT_ALTER 1334
#define ER_SP_SUBSELECT_NYI 1335
#define ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG 1336
#define ER_SP_VARCOND_AFTER_CURSHNDLR 1337
#define ER_SP_CURSOR_AFTER_HANDLER 1338
#define ER_SP_CASE_NOT_FOUND 1339
#define ER_FPARSER_TOO_BIG_FILE 1340
#define ER_FPARSER_BAD_HEADER 1341
#define ER_FPARSER_EOF_IN_COMMENT 1342
#define ER_FPARSER_ERROR_IN_PARAMETER 1343
#define ER_FPARSER_EOF_IN_UNKNOWN_PARAMETER 1344
#define ER_VIEW_NO_EXPLAIN 1345
#define ER_FRM_UNKNOWN_TYPE 1346
#define ER_WRONG_OBJECT 1347
#define ER_NONUPDATEABLE_COLUMN 1348
#define ER_VIEW_SELECT_DERIVED 1349
#define ER_VIEW_SELECT_CLAUSE 1350
#define ER_VIEW_SELECT_VARIABLE 1351
#define ER_VIEW_SELECT_TMPTABLE 1352
#define ER_VIEW_WRONG_LIST 1353
#define ER_WARN_VIEW_MERGE 1354
#define ER_WARN_VIEW_WITHOUT_KEY 1355
#define ER_VIEW_INVALID 1356
#define ER_SP_NO_DROP_SP 1357
#define ER_SP_GOTO_IN_HNDLR 1358
#define ER_TRG_ALREADY_EXISTS 1359
#define ER_TRG_DOES_NOT_EXIST 1360
#define ER_TRG_ON_VIEW_OR_TEMP_TABLE 1361
#define ER_TRG_CANT_CHANGE_ROW 1362
#define ER_TRG_NO_SUCH_ROW_IN_TRG 1363
#define ER_NO_DEFAULT_FOR_FIELD 1364
#define ER_DIVISION_BY_ZERO 1365
#define ER_TRUNCATED_WRONG_VALUE_FOR_FIELD 1366
#define ER_ILLEGAL_VALUE_FOR_TYPE 1367
#define ER_VIEW_NONUPD_CHECK 1368
#define ER_VIEW_CHECK_FAILED 1369
#define ER_PROCACCESS_DENIED_ERROR 1370
#define ER_RELAY_LOG_FAIL 1371
#define ER_PASSWD_LENGTH 1372
#define ER_UNKNOWN_TARGET_BINLOG 1373
#define ER_IO_ERR_LOG_INDEX_READ 1374
#define ER_BINLOG_PURGE_PROHIBITED 1375
#define ER_FSEEK_FAIL 1376
#define ER_BINLOG_PURGE_FATAL_ERR 1377
#define ER_LOG_IN_USE 1378
#define ER_LOG_PURGE_UNKNOWN_ERR 1379
#define ER_RELAY_LOG_INIT 1380
#define ER_NO_BINARY_LOGGING 1381
#define ER_RESERVED_SYNTAX 1382
#define ER_WSAS_FAILED 1383
#define ER_DIFF_GROUPS_PROC 1384
#define ER_NO_GROUP_FOR_PROC 1385
#define ER_ORDER_WITH_PROC 1386
#define ER_LOGGING_PROHIBIT_CHANGING_OF 1387
#define ER_NO_FILE_MAPPING 1388
#define ER_WRONG_MAGIC 1389
#define ER_PS_MANY_PARAM 1390
#define ER_KEY_PART_0 1391
#define ER_VIEW_CHECKSUM 1392
#define ER_VIEW_MULTIUPDATE 1393
#define ER_VIEW_NO_INSERT_FIELD_LIST 1394
#define ER_VIEW_DELETE_MERGE_VIEW 1395
#define ER_CANNOT_USER 1396
#define ER_XAER_NOTA 1397
#define ER_XAER_INVAL 1398
#define ER_XAER_RMFAIL 1399
#define ER_XAER_OUTSIDE 1400
#define ER_XAER_RMERR 1401
#define ER_XA_RBROLLBACK 1402
#define ER_NONEXISTING_PROC_GRANT 1403
#define ER_PROC_AUTO_GRANT_FAIL 1404
#define ER_PROC_AUTO_REVOKE_FAIL 1405
#define ER_DATA_TOO_LONG 1406
#define ER_SP_BAD_SQLSTATE 1407
#define ER_STARTUP 1408
#define ER_LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR 1409
#define ER_CANT_CREATE_USER_WITH_GRANT 1410
#define ER_WRONG_VALUE_FOR_TYPE 1411
#define ER_TABLE_DEF_CHANGED 1412
#define ER_SP_DUP_HANDLER 1413
#define ER_SP_NOT_VAR_ARG 1414
#define ER_SP_NO_RETSET 1415
#define ER_CANT_CREATE_GEOMETRY_OBJECT 1416
#define ER_FAILED_ROUTINE_BREAK_BINLOG 1417
#define ER_BINLOG_UNSAFE_ROUTINE 1418
#define ER_BINLOG_CREATE_ROUTINE_NEED_SUPER 1419
#define ER_EXEC_STMT_WITH_OPEN_CURSOR 1420
#define ER_STMT_HAS_NO_OPEN_CURSOR 1421
#define ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG 1422
#define ER_NO_DEFAULT_FOR_VIEW_FIELD 1423
#define ER_SP_NO_RECURSION 1424
#define ER_TOO_BIG_SCALE 1425
#define ER_TOO_BIG_PRECISION 1426
#define ER_M_BIGGER_THAN_D 1427
#define ER_WRONG_LOCK_OF_SYSTEM_TABLE 1428
#define ER_CONNECT_TO_FOREIGN_DATA_SOURCE 1429
#define ER_QUERY_ON_FOREIGN_DATA_SOURCE 1430
#define ER_FOREIGN_DATA_SOURCE_DOESNT_EXIST 1431
#define ER_FOREIGN_DATA_STRING_INVALID_CANT_CREATE 1432
#define ER_FOREIGN_DATA_STRING_INVALID 1433
#define ER_CANT_CREATE_FEDERATED_TABLE 1434
#define ER_TRG_IN_WRONG_SCHEMA 1435
#define ER_STACK_OVERRUN_NEED_MORE 1436
#define ER_TOO_LONG_BODY 1437
#define ER_WARN_CANT_DROP_DEFAULT_KEYCACHE 1438
#define ER_TOO_BIG_DISPLAYWIDTH 1439
#define ER_XAER_DUPID 1440
#define ER_DATETIME_FUNCTION_OVERFLOW 1441
#define ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG 1442
#define ER_VIEW_PREVENT_UPDATE 1443
#define ER_PS_NO_RECURSION 1444
#define ER_SP_CANT_SET_AUTOCOMMIT 1445
#define ER_NO_VIEW_USER 1446
#define ER_VIEW_FRM_NO_USER 1447
#define ER_VIEW_OTHER_USER 1448
#define ER_NO_SUCH_USER 1449
#define ER_FORBID_SCHEMA_CHANGE 1450
#define ER_ROW_IS_REFERENCED_2 1451
#define ER_NO_REFERENCED_ROW_2 1452
#define ER_SP_BAD_VAR_SHADOW 1453
#define ER_ERROR_LAST 1453
+183
View File
@@ -0,0 +1,183 @@
/*
* Module: sched.h
*
* Purpose:
* Provides an implementation of POSIX realtime extensions
* as defined in
*
* POSIX 1003.1b-1993 (POSIX.1b)
*
* --------------------------------------------------------------------------
*
* Pthreads-win32 - POSIX Threads Library for Win32
* Copyright(C) 1998 John E. Bossom
* Copyright(C) 1999,2005 Pthreads-win32 contributors
*
* Contact Email: rpj@callisto.canberra.edu.au
*
* The current list of contributors is contained
* in the file CONTRIBUTORS included with the source
* code distribution. The list can also be seen at the
* following World Wide Web location:
* http://sources.redhat.com/pthreads-win32/contributors.html
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#if !defined(_SCHED_H)
#define _SCHED_H
#undef PTW32_SCHED_LEVEL
#if defined(_POSIX_SOURCE)
#define PTW32_SCHED_LEVEL 0
/* Early POSIX */
#endif
#if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309
#undef PTW32_SCHED_LEVEL
#define PTW32_SCHED_LEVEL 1
/* Include 1b, 1c and 1d */
#endif
#if defined(INCLUDE_NP)
#undef PTW32_SCHED_LEVEL
#define PTW32_SCHED_LEVEL 2
/* Include Non-Portable extensions */
#endif
#define PTW32_SCHED_LEVEL_MAX 3
#if ( defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112 ) || !defined(PTW32_SCHED_LEVEL)
#define PTW32_SCHED_LEVEL PTW32_SCHED_LEVEL_MAX
/* Include everything */
#endif
#if defined(__GNUC__) && !defined(__declspec)
# error Please upgrade your GNU compiler to one that supports __declspec.
#endif
/*
* When building the library, you should define PTW32_BUILD so that
* the variables/functions are exported correctly. When using the library,
* do NOT define PTW32_BUILD, and then the variables/functions will
* be imported correctly.
*/
#if !defined(PTW32_STATIC_LIB)
# if defined(PTW32_BUILD)
# define PTW32_DLLPORT __declspec (dllexport)
# else
# define PTW32_DLLPORT __declspec (dllimport)
# endif
#else
# define PTW32_DLLPORT
#endif
/*
* This is a duplicate of what is in the autoconf config.h,
* which is only used when building the pthread-win32 libraries.
*/
#if !defined(PTW32_CONFIG_H)
# if defined(WINCE)
# define NEED_ERRNO
# define NEED_SEM
# endif
# if defined(__MINGW64__)
# define HAVE_STRUCT_TIMESPEC
# define HAVE_MODE_T
# elif defined(_UWIN) || defined(__MINGW32__)
# define HAVE_MODE_T
# endif
#endif
/*
*
*/
#if PTW32_SCHED_LEVEL >= PTW32_SCHED_LEVEL_MAX
#if defined(NEED_ERRNO)
#include "need_errno.h"
#else
#include <errno.h>
#endif
#endif /* PTW32_SCHED_LEVEL >= PTW32_SCHED_LEVEL_MAX */
#if (defined(__MINGW64__) || defined(__MINGW32__)) || defined(_UWIN)
# if PTW32_SCHED_LEVEL >= PTW32_SCHED_LEVEL_MAX
/* For pid_t */
# include <sys/types.h>
/* Required by Unix 98 */
# include <time.h>
# else
typedef int pid_t;
# endif
#else
typedef int pid_t;
#endif
/* Thread scheduling policies */
enum {
SCHED_OTHER = 0,
SCHED_FIFO,
SCHED_RR,
SCHED_MIN = SCHED_OTHER,
SCHED_MAX = SCHED_RR
};
struct sched_param {
int sched_priority;
};
#if defined(__cplusplus)
extern "C"
{
#endif /* __cplusplus */
PTW32_DLLPORT int __cdecl sched_yield (void);
PTW32_DLLPORT int __cdecl sched_get_priority_min (int policy);
PTW32_DLLPORT int __cdecl sched_get_priority_max (int policy);
PTW32_DLLPORT int __cdecl sched_setscheduler (pid_t pid, int policy);
PTW32_DLLPORT int __cdecl sched_getscheduler (pid_t pid);
/*
* Note that this macro returns ENOTSUP rather than
* ENOSYS as might be expected. However, returning ENOSYS
* should mean that sched_get_priority_{min,max} are
* not implemented as well as sched_rr_get_interval.
* This is not the case, since we just don't support
* round-robin scheduling. Therefore I have chosen to
* return the same value as sched_setscheduler when
* SCHED_RR is passed to it.
*/
#define sched_rr_get_interval(_pid, _interval) \
( errno = ENOTSUP, (int) -1 )
#if defined(__cplusplus)
} /* End of extern "C" */
#endif /* __cplusplus */
#undef PTW32_SCHED_LEVEL
#undef PTW32_SCHED_LEVEL_MAX
#endif /* !_SCHED_H */
+34
View File
@@ -0,0 +1,34 @@
/* Copyright (C) 2000 MySQL AB
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#ifndef _typelib_h
#define _typelib_h
typedef struct st_typelib { /* Different types saved here */
unsigned int count; /* How many types */
const char *name; /* Name of typelib */
const char **type_names;
unsigned int *type_lengths;
} TYPELIB;
extern int find_type(char *x,TYPELIB *typelib,unsigned int full_name);
extern void make_type(char *to,unsigned int nr,TYPELIB *typelib);
extern const char *get_type(TYPELIB *typelib,unsigned int nr);
extern TYPELIB sql_protocol_typelib;
#endif /* _typelib_h */
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large. Load diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+46
View File
@@ -0,0 +1,46 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://osroseon.to.md
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "charserver.h"
// Constructor
CCharClient::CCharClient( )
{
userid = 0;
platinum = false;
memset( &username, '\0', 17 );
memset( &password, '\0', 33 );
memset( &charname, '\0', 17 );
accesslevel = 0;
channel = 0;
clanid = 0;
clan_rank = 0;
level = 0;
job = 0;
charid = 0;
isLoggedIn = false;
logout = false;
}
// Deconstructor
CCharClient::~CCharClient( )
{
}
+579
View File
@@ -0,0 +1,579 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://osroseon.to.md
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
developed with Main erose/hrose source server + some change from the original eich source
*/
#include "charserver.h"
// Do player identification
bool CCharServer::pakDoIdentify( CCharClient* thisclient, CPacket* P )
{
if (thisclient->isLoggedIn) return false;
MYSQL_RES *result;
MYSQL_ROW row;
thisclient->userid = GETDWORD((*P), 0x00);
memcpy( thisclient->password, &P->Buffer[4], 32 );
result = DB->QStore("SELECT username,lastsvr,accesslevel,platinum FROM accounts WHERE id=%i AND password='%s'", thisclient->userid, thisclient->password);
if(result==NULL) return false;
if (mysql_num_rows( result ) != 1)
{
Log( MSG_HACK, "Someone tried to connect to char server with an invalid account" );
DB->QFree( );
return false;
}
else
{
row = mysql_fetch_row(result);
strncpy_s (thisclient->username, row[0], 16);
thisclient->channel = atoi(row[1]);
thisclient->accesslevel = atoi(row[2]);
thisclient->platinum = atoi(row[3]);
DB->QFree( );
}
Log( MSG_INFO,"User '%s'(#%i) logged in", thisclient->username, thisclient->userid );
BEGINPACKET( pak, 0x070c );
ADDBYTE ( pak, 0 );
ADDDWORD ( pak, 0x87654321);
ADDDWORD ( pak, 0x00000000 );
thisclient->SendPacket( &pak );
result = DB->QStore( "SELECT online FROM accounts WHERE username='%s'", thisclient->username );
if(result==NULL) return false;
row = mysql_fetch_row(result);
bool online = atoi(row[0]);
DB->QFree( );
if(online)
return false;
if(!DB->QExecute( "UPDATE accounts SET online=1 WHERE username='%s'", thisclient->username ))
return false;
thisclient->isLoggedIn = true;
thisclient->returnedfromWS=false;
return true;
}
// Get this clients character list
bool CCharServer::pakGetCharacters( CCharClient* thisclient, CPacket* P )
{
if (!thisclient->isLoggedIn) return false;
// Properly delete items, quests, friends when deleting a character
// Hooray for joins.
MYSQL_RES *result;
MYSQL_ROW row;
DB->QExecute( "DELETE FROM characters, items, list_friend, list_quest USING characters LEFT JOIN items ON items.owner = characters.id LEFT JOIN list_friend \
ON (list_friend.id = characters.id OR list_friend.idfriend = characters.id) LEFT JOIN list_quest ON list_quest.owner = characters.id WHERE (characters.deletetime > 0 AND characters.deletetime <= %i)", GetServerTime( ) );
CItem items[10];
unsigned int charnum=0;
CCharacter chars[5];
// 0 1 2 3 4 5 6 7
result = DB->QStore("SELECT char_name,level,face,hairStyle,sex,classid,id,deletetime FROM characters WHERE account_name='%s'", thisclient->username);
if(result==NULL) return false;
while (row = mysql_fetch_row(result))
{
strcpy( chars[charnum].char_name , row[0] );
chars[charnum].level = atoi(row[1]);
chars[charnum].face = atoi(row[2]);
chars[charnum].hairStyle = atoi(row[3]);
chars[charnum].sex = atoi(row[4]);
chars[charnum].classid = atoi(row[5]);
chars[charnum].id = atoi(row[6]);
chars[charnum].DeleteTime = atoi(row[7]);
if(chars[charnum].DeleteTime > 0)
{
chars[charnum].DeleteTime = chars[charnum].DeleteTime - GetServerTime( );
}
charnum++;
}
DB->QFree( );
BEGINPACKET( pak, 0x0712 );
ADDBYTE ( pak, charnum );
for (unsigned k=0;k<charnum;k++)
{
for(unsigned j=0; j<10; j++)
ClearItem( items[j] );
// 0 1 2 3 4 5
//result = DB->QStore("SELECT itemnum,itemtype,refine,durability,lifespan,slotnum FROM items WHERE owner=%i AND slotnum<10", chars[k].id);
result = DB->QStore("SELECT itemid, itemtype, refine, durability, lifespan FROM charitems WHERE owner=%i", chars[k].id);
if(result == NULL) return false;
char *tmpid;
char *itmp;
while( row = mysql_fetch_row(result) )
{
tmpid = strtok( row[0] , "|");
for(unsigned int i=1;i<10; i++)
{
if((tmpid = strtok( NULL , "|"))!= NULL)
{
items[i].itemnum = atoi(tmpid);
}
}
tmpid = strtok( row[1] , "|");
for(unsigned int i=1;i<10; i++)
{
if((tmpid = strtok( NULL , "|"))!= NULL)
{
items[i].itemtype = atoi(tmpid);
}
}
tmpid = strtok( row[2] , "|");
for(unsigned int i=1;i<10; i++)
{
if((tmpid = strtok( NULL , "|"))!= NULL)
{
items[i].refine = atoi(tmpid);
}
}
tmpid = strtok( row[3] , "|");
for(unsigned int i=1;i<10; i++)
{
if((tmpid = strtok( NULL , "|"))!= NULL)
{
items[i].durability = atoi(tmpid);
}
}
tmpid = strtok( row[4] , "|");
for(unsigned int i=1;i<10; i++)
{
if((tmpid = strtok( NULL , "|"))!= NULL)
{
items[i].lifespan = atoi(tmpid);
}
}
}
/*
while(row = mysql_fetch_row(result))
{
unsigned itemnum = atoi(row[5]);
items[itemnum].itemnum = atoi(row[0]);
items[itemnum].itemtype = atoi(row[1]);
items[itemnum].refine = atoi(row[2]);
items[itemnum].durability = atoi(row[3]);
items[itemnum].lifespan = atoi(row[4]);
}*/
DB->QFree( );
ADDSTRING ( pak, chars[k].char_name );
ADDBYTE ( pak, 0x00 );
ADDBYTE ( pak, chars[k].sex ); // SEX
ADDWORD ( pak, chars[k].level ); // LEVEL
ADDWORD ( pak, chars[k].classid ); // CLASSID
ADDDWORD ( pak, chars[k].DeleteTime ); // DELETE TIME
ADDBYTE ( pak, 0x00 );//thisclient->platinum?0x01:0x00 ); // IS PLATINUM? 00-NO;01-YES;02-YES BUT USER IS NOT
ADDDWORD ( pak, chars[k].face ); // FACE
ADDDWORD ( pak, chars[k].hairStyle ); // HAIR
ADDWORD ( pak, items[2].itemnum ); // CAP
ADDWORD ( pak, items[2].refine ); // CAP REFINE
ADDWORD ( pak, items[3].itemnum ); // BODY
ADDWORD ( pak, items[3].refine ); // BODY REFINE
ADDWORD ( pak, items[5].itemnum ); // GLOVES
ADDWORD ( pak, items[5].refine ); // GLOVES REFINE
ADDWORD ( pak, items[6].itemnum ); // BOOTS
ADDWORD ( pak, items[6].refine ); // BOOTS REFINE
ADDWORD ( pak, items[1].itemnum ); // FACE
ADDWORD ( pak, items[1].refine ); // FACE REFINE
ADDWORD ( pak, items[4].itemnum ); // BACK
ADDWORD ( pak, items[4].refine ); // BACK REFINE
ADDWORD ( pak, items[7].itemnum ); // WEAPON
ADDWORD ( pak, items[7].refine ); // WEAPON REFINE
ADDWORD ( pak, items[8].itemnum ); // SUBWEAPON
ADDWORD ( pak, items[8].refine ); // SUBWEAPON REFINE
}
thisclient->SendPacket( &pak );
return true;
}
// Send away the world IP
bool CCharServer::pakRequestWorld( CCharClient* thisclient, CPacket* P )
{
if (!thisclient->isLoggedIn) return false;
MYSQL_ROW row;
MYSQL_RES *result;
memcpy( thisclient->charname, &P->Buffer[3], P->Size-6-4 );
thisclient->charname[P->Size-6-4] = 0;
Log( MSG_INFO,"User %s(%i) selected char '%s'", thisclient->username, thisclient->userid, thisclient->charname);
if(!DB->QExecute("UPDATE accounts SET lastchar='%s' WHERE id=%i", thisclient->charname, thisclient->userid))
return false;
result = DB->QStore("SELECT host,port FROM channels WHERE id=%i", thisclient->channel);
if(result==NULL) return false;
if(mysql_num_rows( result )!=1 )
{
Log( MSG_WARNING, "Invalid Server: %i", thisclient->channel );
DB->QFree( );
return false;
}
row = mysql_fetch_row( result );
BEGINPACKET( pak, 0x711 );
ADDWORD ( pak, atoi(row[1]) ); // PORT
ADDDWORD ( pak, thisclient->userid );
ADDDWORD ( pak, 0x87654321 );
ADDSTRING ( pak, row[0] );//IP
ADDBYTE ( pak, 0 );
thisclient->SendPacket( &pak );
DB->QFree( );
//CHAR INFORMATION 0 1 2 3 4
result = DB->QStore("SELECT clanid,clan_rank,id,level,classid FROM characters WHERE char_name='%s'", thisclient->charname);
if(result==NULL) return false;
if(mysql_num_rows(result)!=1)
{
Log( MSG_WARNING, "Number of user with charname '%s' is %i", thisclient->charname,mysql_num_rows(result));
DB->QFree( );
return false;
}
row = mysql_fetch_row( result );
thisclient->clanid = atoi( row[0] );
thisclient->clan_rank = atoi( row[1] );
thisclient->charid = atoi( row[2] );
thisclient->level = atoi( row[3] );
thisclient->job = atoi( row[4] );
DB->QFree( );
//MESSENGER INFORMATION
// // 0 1
result = DB->QStore("SELECT idfriend,namefriend FROM list_friend WHERE id=%i", thisclient->charid);
if(result==NULL) return false;
BYTE nfriends = mysql_num_rows(result) & 0xff;
RESETPACKET( pak, 0x7e1 );// Friend list command
ADDBYTE ( pak, 0x06 );// Sending Friend List
ADDBYTE ( pak, nfriends );// # friends
while(row = mysql_fetch_row( result ))
{
CFriendList * newfriend = new CFriendList;
assert(newfriend);
newfriend->id = atoi(row[0]); //friendid
strcpy(newfriend->name, row[1]); //friend name
thisclient->FriendList.push_back( newfriend );
ADDWORD (pak, newfriend->id);// friend id
ADDWORD (pak, 0x0000 );
CCharClient* otherclient = (CCharClient*) GetClientByID( newfriend->id );
if(otherclient!=NULL) //is online??
{
ADDBYTE (pak, 0x07 ); //online
ChangeMessengerStatus ( thisclient, otherclient, 0x07);
}
else
{
ADDBYTE (pak, 0x08 );//offline
}
ADDSTRING (pak, newfriend->name); //friend name
ADDBYTE (pak, 0x00 );
}
thisclient->SendPacket( &pak );
DB->QFree( );
thisclient->logout = false;
//SEND CLAN INFORMATION
SendClanInfo (thisclient);
return true;
}
// Create a character
bool CCharServer::pakCreateChar( CCharClient* thisclient, CPacket* P )
{
if (!thisclient->isLoggedIn) return false;
// Get info from packet
unsigned sex = GETBYTE((*P), 0 ) % 2;
unsigned hairstyle = GETBYTE((*P), 2 );
unsigned face = GETBYTE((*P), 3 );
string newname = (char*)&P->Buffer[7];
MYSQL_RES *result;
result = DB->QStore("SELECT id FROM characters WHERE account_name='%s'", thisclient->username);
if(result==NULL) return false;
if ( mysql_num_rows( result ) == 5 )
{
STARTPACKET( pak, 0x0713, 8 );
SETWORD ( pak, 0x00, 4 )
thisclient->SendPacket( &pak );
DB->QFree( );
return true;
}
DB->QFree( );
result = DB->QStore("SELECT id FROM characters WHERE char_name='%s'", newname.c_str());
if(result==NULL) return false;
if ( mysql_num_rows( result ) > 0 )
{
STARTPACKET( pak, 0x0713, 8 );
SETWORD ( pak, 0x00, 2 );
thisclient->SendPacket( &pak );
DB->QFree( );
return true;
}
DB->QFree( );
if(!DB->QExecute("INSERT INTO characters (account_name, char_name, face, hairStyle, sex) VALUES('%s','%s',%i,%i,%i)", thisclient->username, newname.c_str(), face, hairstyle, sex))
return false;
unsigned int mid = (unsigned)mysql_insert_id( DB->Mysql );
MYSQL_ROW row;
char tmp1[1024] = ""; //itemid
char tmp2[1024] = ""; //itemtype
char tmp3[1024] = ""; //refine
char tmp4[1024] = ""; //durability
char tmp5[1024] = ""; //lifespan
char tmp6[1024] = ""; //count
char tmp7[1024] = ""; //stats
char tmp8[1024] = ""; //socketed
char tmp9[1024] = ""; //appraised
sprintf(&tmp2[strlen(tmp2)], "0|0|0|3|0|0|0|8|0|0|0|0|2|0");
sprintf(&tmp3[strlen(tmp3)], "0|0|0|0|0|0|0|0|0|0|0|0|0|0");
sprintf(&tmp4[strlen(tmp4)], "0|0|0|40|0|0|0|40|0|0|0|0|40|0");
sprintf(&tmp5[strlen(tmp5)], "0|0|0|100|0|0|0|100|0|0|0|0|100|0");
sprintf(&tmp6[strlen(tmp6)], "0|0|0|1|0|0|0|1|0|0|0|0|1|0");
sprintf(&tmp7[strlen(tmp7)], "0|0|0|0|0|0|0|0|0|0|0|0|0|0");
sprintf(&tmp8[strlen(tmp8)], "0|0|0|0|0|0|0|0|0|0|0|0|0|0");
sprintf(&tmp9[strlen(tmp9)], "0|0|0|1|0|0|0|1|0|0|0|0|1|0");
int tran = 1;
//if(!DB->QExecute("INSERT INTO items VALUES(%i,30,3,0,40,100,3,1,0,0,0,0)", mid))
// return false;
//if(!DB->QExecute("INSERT INTO items VALUES(%i,1,8,0,40,100,7,1,0,0,0,0)", mid))
// return false;
if(sex==0)
{
//if(!DB->QExecute("INSERT INTO items VALUES(%i,222,2,0,40,100,12,1,0,0,0,0)", mid))
// return false;
sprintf(&tmp1[strlen(tmp1)], "0|0|0|30|0|0|0|1|0|0|0|0|222|0");
if(!DB->QExecute("INSERT INTO charitems (owner,itemid,itemtype,refine,durability,lifespan,count,stats,socketed,appraised,trans_action) VALUES('%i','%s','%s','%s','%s','%s','%s','%s','%s','%s','%i')",
mid,tmp1,tmp2,tmp3,tmp4,tmp5,tmp6,tmp7,tmp8,tmp9,tran))
return false;
}
else
{
//if(!DB->QExecute("INSERT INTO items VALUES(%i,221,2,0,40,100,12,1,0,0,0,0)", mid))
// return false;
sprintf(&tmp1[strlen(tmp1)], "0|0|0|30|0|0|0|1|0|0|0|0|221|0");
if(!DB->QExecute("INSERT INTO charitems (owner,itemid,itemtype,refine,durability,lifespan,count,stats,socketed,appraised,trans_action) VALUES('%i','%s','%s','%s','%s','%s','%s','%s','%s','%s','%i')",
mid,tmp1,tmp2,tmp3,tmp4,tmp5,tmp6,tmp7,tmp8,tmp9,tran))
return false;
}
STARTPACKET( pak, 0x0713, 8 );
SETWORD ( pak, 0x00, 0 );
thisclient->SendPacket( &pak );
return true;
}
// Connect WorldServer
bool CCharServer::pakWSReady ( CCharClient* thisclient, CPacket* P )
{
if(thisclient->isLoggedIn) return false;
if(GETDWORD((*P),0) != Config.CharPass )
{
Log( MSG_HACK, "WorldServer Tried to connect CharServer with wrong password ");
return true;
}
thisclient->userid = GETDWORD((*P), 4); //our channelid
thisclient->accesslevel = 0xffff; //this will identify thisclient as channel
// add channel
CChanels* newchannel = new (nothrow) CChanels;
if(newchannel==NULL)
return false;
newchannel->id = GETDWORD((*P), 4);
newchannel->ip = inet_ntoa( thisclient->clientinfo.sin_addr );
newchannel->port = GETWORD((*P),8 );
Log( MSG_INFO, "Channel #%i connected from ip %s", newchannel->id, newchannel->ip );
// Connect to charserver
newchannel->sock = socket( AF_INET, SOCK_STREAM, 0 );
if (newchannel->sock == INVALID_SOCKET)
{
Log( MSG_WARNING, "Could not access worldserver IP: %s , Port: %i", newchannel->ip, newchannel->port );
delete newchannel;
return false;
}
struct sockaddr_in ain;
ain.sin_family = AF_INET;
ain.sin_addr.s_addr = inet_addr(newchannel->ip);
ain.sin_port = htons( newchannel->port );
memset(&(ain.sin_zero), '\0', 8);
if ( connect( newchannel->sock , (SOCKADDR*) &ain, sizeof(ain) ) == SOCKET_ERROR)
{
Log( MSG_WARNING, "Could not access worldserver IP: %s , Port: %i", newchannel->ip , newchannel->port );
delete newchannel;
return false;
}
ChannelList.push_back( newchannel );
thisclient->isLoggedIn = true;
BEGINPACKET( pak, 0x500 );
ADDDWORD ( pak, Config.WorldPass );
//cryptPacket( (char*)&pak, NULL );
//EncryptBuffer( CryptTable,(unsigned char*)&pak );
Log( MSG_INFO, "Accessing worldserver IP: %s , Port: %i", newchannel->ip , newchannel->port );
send( newchannel->sock, (char*)&pak, pak.Size, 0 );
return true;
}
// Login Connected
bool CCharServer::pakLoginConnected( CCharClient* thisclient, CPacket* P )
{
if(thisclient->isLoggedIn) return false;
if(GETDWORD((*P),0) != Config.CharPass )
{
Log( MSG_HACK, "LoginServer Tried to connect CharServer with wrong password ");
return true;
}
thisclient->isLoggedIn = true;
return true;
}
// Return to char select
bool CCharServer::pakWSCharSelect ( CCharClient* thisclient, CPacket* P )
{
//if(!thisclient->isLoggedIn) return false;
Log( MSG_INFO, "World server requested char select" );
unsigned int userid = GETDWORD( (*P), 0 );
CCharClient* otherclient = GetClientByUserID( userid );
if(otherclient==NULL)
{
Log(MSG_WARNING, "Invalid userid: %i", userid );
return true;
}
BEGINPACKET( pak, 0x71c );
//ADDBYTE ( pak, 0x00 );
otherclient->SendPacket( &pak );
Log( MSG_INFO, "Client returning to char select" );
return true;
}
// ???
bool CCharServer::pak7e5 ( CCharClient* thisclient, CPacket* P )
{
BEGINPACKET( pak, 0 );
if(!thisclient->isLoggedIn) return false;
unsigned int action = GETBYTE((*P),0);
switch(action)
{
case 0x03:
RESETPACKET( pak, 0x7e5 );
ADDBYTE ( pak, 0x01 );
ADDWORD ( pak, 0x0000 );
thisclient->SendPacket( &pak );
break;
default:
Log( MSG_WARNING,"Unknown 7e5 action %i",action);
}
return true;
}
// Create a chatroom?
bool CCharServer::pakChatrooms ( CCharClient* thisclient, CPacket* P )
{
if(!thisclient->isLoggedIn) return false;
return true;
}
// delete/resurect character
bool CCharServer::pakDeleteChar( CCharClient* thisclient, CPacket* P )
{
if(!thisclient->isLoggedIn) return false;
short int action = GETBYTE((*P), 1 );
unsigned long int DeleteTime = 0;
switch(action)
{
case 0x00://Resurect
{
DeleteTime = 0;
if(!DB->QExecute(" UPDATE characters SET deletetime=0 WHERE char_name='%s'",
(char*)&P->Buffer[2] ))
return false;
}
break;
case 0x01://Delete
{
DeleteTime = GetServerTime( ) + Config.DeleteTime;
if(!DB->QExecute(" UPDATE characters SET deletetime=%i WHERE char_name='%s'",
DeleteTime, (char*)&P->Buffer[2] ))
return false;
}
break;
}
BEGINPACKET( pak, 0x714 );
if(DeleteTime > 0 )
{
ADDDWORD ( pak, Config.DeleteTime );
}
else
{
ADDDWORD ( pak, 0x00000000 );
}
ADDSTRING ( pak, (char*)&P->Buffer[2] );
ADDBYTE ( pak, 0x00 );
thisclient->SendPacket( &pak );
return true;
}
bool CCharServer::pakUpdateLevel( CCharClient* thisclient, CPacket* P )
{
if(!thisclient->isLoggedIn) return false;
WORD charid = GETWORD((*P),0);
WORD level = GETWORD((*P),2);
for(UINT i=0;i<ClientList.size();i++)
{
CCharClient* player = (CCharClient*) ClientList.at(i);
if(player->charid==charid)
{
player->level = level;
break;
}
}
return true;
}
// Disconnect client from char/world server
bool CCharServer::pakLoginDSClient( CCharClient* thisclient, CPacket* P )
{
if(!thisclient->isLoggedIn) return false;
BYTE action = GETBYTE((*P),0);
switch(action)
{
case 1:
{
unsigned int userid = GETDWORD ((*P), 1);
CCharClient* otherclient = GetClientByUserID( userid );
if(otherclient==NULL)
{
Log( MSG_WARNING, "Userid '%u' is not online", userid );
return true;
}
otherclient->isLoggedIn = false;
otherclient->isActive = false;
BEGINPACKET( pak, 0x502 );
ADDBYTE ( pak, 1 );
ADDDWORD ( pak, userid );
ADDBYTE ( pak, 0x00 );
CChanels* thischannel = GetChannelByID( otherclient->channel );
if(thischannel!=NULL){
send( thischannel->sock, (char*)&pak, pak.Size, 0 );}
else { Log(MSG_ERROR, "Check serverid in worldserver.conf it should be the same as ID in channels in the mysql database %i",thisclient->channel);}
}
break;
}
return true;
}
+204
View File
@@ -0,0 +1,204 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://osroseon.to.md
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "charserver.h"
// Constructor
CCharServer::CCharServer( string fn )
{
LoadConfigurations( (char*)fn.c_str() );
GServer = this;
}
// Deconstructor
CCharServer::~CCharServer( )
{
}
// Return a new clientsocket structure
CCharClient* CCharServer::CreateClientSocket( )
{
CCharClient* thisclient = new (nothrow) CCharClient( );
return thisclient;
}
//loadserver encryption
void CCharServer::LoadEncryption( )
{
GenerateCryptTables( CryptTable, 0x87654321 );
}
// When Server is ready
bool CCharServer::OnServerReady( )
{
DB->QExecute( "DELETE FROM channels WHERE id=%u", Config.ServerID);
if(!DB->QExecute("INSERT INTO channels (id,name,host,port,connected,maxconnections,owner) VALUES (%i,'%s','%s',%i,0,%i,%i)",
Config.ServerID, Config.ServerName, Config.CharIP, Config.CharPort, Config.MaxConnections, Config.ParentID))
{
Log(MSG_WARNING, "Error accessing to database, the other server will not connect to CharServer" );
}
MYSQL_RES *result;
MYSQL_ROW row;
// Load all our clans
result = DB->QStore("SELECT id,logo,back,name,cp,grade,slogan,news FROM list_clan");
if(result==NULL) return false;
while(row = mysql_fetch_row(result))
{
CClans* thisclan = new CClans;
assert(thisclan); // maybe remove
thisclan->id = atoi(row[0]);
thisclan->logo = atoi(row[1]);
thisclan->back = atoi(row[2]);
strcpy(thisclan->name,row[3]);
thisclan->cp = atoi(row[4]);
thisclan->grade = atoi(row[5]);
strcpy(thisclan->slogan,row[6]);
strcpy(thisclan->news,row[7]);
ClanList.push_back( thisclan );
}
DB->QFree( );
// Load Clans
for(UINT i=0;i<ClanList.size( );i++)
{
CClans* Clan = ClanList.at( i );
result = DB->QStore("SELECT id,char_name,clan_rank FROM characters WHERE clanid=%i order by clan_rank",Clan->id);
if(result==NULL) return false;
while(row = mysql_fetch_row(result))
{
CClanMembers* newmember = new CClanMembers;
assert(newmember);
newmember->id = atoi(row[0]);
strcpy(newmember->name,row[1]);
newmember->clan_rank = atoi(row[2]);
Clan->ClanMembers.push_back( newmember );
}
DB->QFree( );
}
Log( MSG_INFO, "Clans Information Loaded" );
return true;
}
// When a a client is disconnected
void CCharServer::OnClientDisconnect( CClientSocket* thisclient )
{
CCharClient* thisclientwc = (CCharClient*)thisclient;
DB->QExecute( "UPDATE accounts SET online=0 WHERE username='%s'", thisclientwc->username );
if(!thisclientwc->logout)
{
// Send logout message to friends
for(UINT i=0;i<thisclientwc->FriendList.size( );i++)
{
CFriendList* Friend = thisclientwc->FriendList.at( i );;
CCharClient* otherclient = GetClientByID( Friend->id );
if(otherclient!=NULL)
{
ChangeMessengerStatus ( thisclientwc, otherclient, 0x08);
}
}
//set logout messga to clan
CClans* thisclan = GetClanByID(thisclientwc->clanid);
if(thisclan==NULL)
return;
for(UINT i=0;i<thisclan->ClanMembers.size( );i++)
{
CClanMembers* ClanMember = thisclan->ClanMembers.at( i );
CCharClient* otherclient = GetClientByID( ClanMember->id );
if(otherclient!=NULL)
ChangeClanStatus (thisclientwc, otherclient, 0xff);
}
}
}
// Deletes an old clientsocket structure
void CCharServer::DeleteClientSocket( CClientSocket* thisclient )
{
if (thisclient->isserver)
Log( MSG_INFO, "Server disconnected" );
else
Log( MSG_INFO, "User disconnected" );
delete (CCharClient*)thisclient;
}
// Load Server configuration
void CCharServer::LoadConfigurations( const char* file )
{
//Database
Config.SQLServer.pcServer = ConfigGetString ( file, "mysql_host", "localhost" );
Config.SQLServer.pcDatabase = ConfigGetString ( file, "mysql_database", "roseon_beta" );
Config.SQLServer.pcUserName = ConfigGetString ( file, "mysql_user", "root" );
Config.SQLServer.pcPassword = ConfigGetString ( file, "mysql_pass", "" );
Config.SQLServer.pcPort = ConfigGetInt ( file, "mysql_port", 3306 );
//Server
Config.ServerID = ConfigGetInt ( file, "serverid", 1 );
Config.ServerType = 1; // Char always = 1
Config.CharIP = ConfigGetString ( file, "serverip", "127.0.0.1" );
Config.CharPort = ConfigGetInt ( file, "serverport", 29100 );
Config.ParentID = ConfigGetInt ( file, "parentid", 0 );
Config.ServerName = ConfigGetString ( file, "servername", "Server" );
Config.CharsPort = ConfigGetInt ( file, "CharsPort", 29110 );
//Char
Config.usethreads = ConfigGetInt ( file, "usethreads", 0 )==0?false:true;
Config.DeleteTime = ConfigGetInt ( file, "deletetime", 36000 );
Config.MinimumAccessLevel = ConfigGetInt ( file, "accesslevel", 100 );
//Password
Config.LoginPass = ConfigGetInt ( file, "loginpass", 123456 );
Config.CharPass = ConfigGetInt ( file, "charpass", 123456 );
Config.WorldPass = ConfigGetInt ( file, "worldpass", 123456 );
}
// Incoming packet
bool CCharServer::OnReceivePacket( CClientSocket* thisclient, CPacket *P )
{
Log(MSG_INFO,"Packet received at OnReceivePacket");
switch( P->Command )
{
case 0x0500: return pakWSReady ( (CCharClient*)thisclient, P );
case 0x0501: return pakLoginConnected ( (CCharClient*)thisclient, P );
case 0x0502: return pakLoginDSClient ( (CCharClient*)thisclient, P );
case 0x0505: return pakWSCharSelect ( (CCharClient*)thisclient, P );
case 0x070b: return pakDoIdentify ( (CCharClient*)thisclient, P );
case 0x0712: return pakGetCharacters ( (CCharClient*)thisclient, P );
case 0x0713: return pakCreateChar ( (CCharClient*)thisclient, P );
case 0x0714: return pakDeleteChar ( (CCharClient*)thisclient, P );
case 0x0715: return pakRequestWorld ( (CCharClient*)thisclient, P );
case 0x0787: return pakClanChat ( (CCharClient*)thisclient, P );
case 0x07e0: return pakClanManager ( (CCharClient*)thisclient, P );
case 0x07e1: return pakMessengerManager ( (CCharClient*)thisclient, P );
case 0x07e2: return pakMessengerChat ( (CCharClient*)thisclient, P );
case 0x07e3: return pakChatrooms ( (CCharClient*)thisclient, P );
case 0x07e5: return pak7e5 ( (CCharClient*)thisclient, P );
case 0x07e6: return pakUploadCM ( (CCharClient*)thisclient, P );
case 0x07e7: return pakDownloadCM ( (CCharClient*)thisclient, P );
case 0x07e8: return pakClanIconTime ( (CCharClient*)thisclient, P );
case 0x079e: return pakUpdateLevel ( (CCharClient*)thisclient, P );
default:
Log( MSG_WARNING, "(SID:%i) Received unknown packet. Command:%04x Size:%04x", thisclient->sock, P->Command, P->Size );
break;
}
return true;
}
bool CCharServer::Ping( )
{
return DB->Ping( );
}
+115
View File
@@ -0,0 +1,115 @@
/*
Open Source Rose Online Team - http://osroseon.to.md/
note: the Server is develop with erose source server + eich source
*/
#ifndef __ROSE_SERVERS__
#define __ROSE_SERVERS__
#include <time.h>
#include "../common/sockets.h"
#include "datatypes.h"
#define ClearItem(i) { i.durability=0; i.itemnum=0; i.itemtype=0; i.lifespan=0; i.refine=0; }
using namespace std;
// Clent class
class CCharClient : public CClientSocket
{
public:
CCharClient ( ); // constructor
~CCharClient ( ); // destructor
// User information
UINT userid;
bool platinum;
char username[17];
char password[33];
UINT accesslevel;
UINT channel;
// Character information
char charname[17];
UINT clanid;
int clan_rank;
UINT level;
UINT job;
UINT charid;
bool isLoggedIn;
bool returnedfromWS;
bool logout;
vector<CFriendList*> FriendList;
};
// Server class
class CCharServer : public CServerSocket
{
public:
CCharServer ( string );
~CCharServer( );
CCharClient* CreateClientSocket( );
void DeleteClientSocket( CClientSocket* thisclient );
void LoadEncryption( );
void OnClientDisconnect( CClientSocket* thisclient );
bool OnServerReady( );
void LoadConfigurations( const char* );
bool OnReceivePacket( CClientSocket* thisclient, CPacket* P );
bool Ping( );
// Extra functions
CChanels* GetChannelByID( UINT id );
CCharClient* GetClientByUserID( UINT id );
CCharClient* GetClientByID( UINT id );
CCharClient* GetClientByName( char *name );
CCharClient* GetClientByUserName( char *username );
CClans* GetClanByID( int id );
unsigned long int GetServerTime( );
// Community functions
bool ChangeMessengerStatus (CCharClient* thisclient, CCharClient* otherclient, int status);
bool pakMessengerManager ( CCharClient* thisclient, CPacket* P );
bool pakMessengerChat ( CCharClient* thisclient, CPacket* P );
// Clan Functions
bool SendClanInfo (CCharClient* thisclient);
bool ChangeClanStatus (CCharClient* thisclient, CCharClient* otherclient, int channel);
bool SendToClanMembers( int clanid,CPacket* pak );
bool UpdateClanWindow( int clanid );
bool pakClanMembers ( CCharClient* thisclient );
bool pakClanManager ( CCharClient* thisclient, CPacket* P );
bool pakClanChat ( CCharClient* thisclient, CPacket* P );
bool ClanLogout ( CCharClient* thisclient );
bool pakUploadCM ( CCharClient* thisclient, CPacket* P );
bool pakDownloadCM( CCharClient* thisclient, CPacket* P );
bool pakClanIconTime( CCharClient* thisclient, CPacket* P );
// General Packets
bool pakUpdateLevel( CCharClient* thisclient, CPacket* P );
bool pakDoIdentify( CCharClient* thisclient, CPacket* P );
bool pakGetCharacters( CCharClient* thisclient, CPacket* P );
bool pakRequestWorld( CCharClient* thisclient, CPacket* P );
bool pakCreateChar( CCharClient* thisclient, CPacket* P );
bool pakDeleteChar( CCharClient* thisclient, CPacket* P );
bool pakWSReady ( CCharClient* thisclient, CPacket* P );
bool pakWSCharSelect ( CCharClient* thisclient, CPacket* P );
bool pakLoginConnected ( CCharClient* thisclient, CPacket* P );
bool pakLoginDSClient( CCharClient* thisclient, CPacket* P );
bool pak7e5 ( CCharClient* thisclient, CPacket* P );
bool pakChatrooms ( CCharClient* thisclient, CPacket* P );
// Variables
string filename;
vector <CClans*> ClanList;
vector <CChanels*> ChannelList;
//Login
SOCKET lsock; // Socket to Login
char* lct; // Encryption table for login server
CDatabase* DB;
};
void StartSignal( );
void StopSignal( );
void HandleSignal( int num );
extern class CCharServer* GServer;
#endif
File diff suppressed because it is too large. Load diff
+215
View File
@@ -0,0 +1,215 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://osroseon.to.md
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "charserver.h"
// Change messenger status 07 - online | 08 - offline
bool CCharServer::ChangeMessengerStatus (CCharClient* thisclient, CCharClient* otherclient, int status)
{
BEGINPACKET( pak, 0x7e1 );
ADDBYTE ( pak, 0x08 );
ADDWORD ( pak, thisclient->charid );
ADDWORD ( pak, 0x0000 );
ADDBYTE ( pak, status );
otherclient->SendPacket(&pak);
return true;
}
// Messenger actions (add/remove/invite)
bool CCharServer::pakMessengerManager ( CCharClient* thisclient, CPacket* P )
{
BYTE action = GETBYTE((*P),0);
switch (action)
{
case 0x01://wanna be my friend?
{
char* nick = new (nothrow) char[P->Size];
if(nick==NULL)
{
Log(MSG_ERROR, "Error allocing memory: pakMessengerManager 1" );
return false;
}
memcpy( nick, &P->Buffer[1], P->Size );
CCharClient* otherclient = (CCharClient*) GetClientByName (nick);
if(otherclient!=NULL)
{//Send friend invitation (check this one)
BEGINPACKET( pak, 0x7e1 );
ADDBYTE ( pak, 0x01 );
ADDWORD ( pak, 0x0000 );
ADDSTRING ( pak, thisclient->charname );
ADDBYTE ( pak, 0x00 );
otherclient->SendPacket(&pak);
}
else
{//This charname doesnt exist
BEGINPACKET( pak, 0x7e1 );
ADDBYTE ( pak, 0x04 );
ADDSTRING ( pak, nick );
ADDBYTE ( pak, 0x00 );
thisclient->SendPacket(&pak);
}
delete []nick;
}
break;
case 0x02://yes i want
{
char* nick = new (nothrow) char[P->Size];
if(nick==NULL)
{
Log(MSG_ERROR, "Error allocing memory: pakMessengerManager 2" );
return false;
}
memcpy( nick, &P->Buffer[3], P->Size );
CCharClient* otherclient = (CCharClient*) GetClientByName (nick);
if(otherclient!=NULL)
{
BEGINPACKET( pak, 0x7e1 );
ADDBYTE ( pak, 0x02 );
ADDWORD ( pak, thisclient->charid );
ADDBYTE ( pak, 0x00 );
ADDWORD ( pak, 0x0000 );
ADDSTRING ( pak, thisclient->charname );
ADDBYTE ( pak, 0x00);
otherclient->SendPacket(&pak);
//Add friend to my friend list(sql)
if(!DB->QExecute("INSERT INTO list_friend (id,idfriend,namefriend) VALUES (%i,%i,'%s')",
otherclient->charid,thisclient->charid,thisclient->charname))
return false;
CFriendList * newfriend1 = new (nothrow) CFriendList;
if(newfriend1==NULL)
return false;
newfriend1->id = otherclient->charid; //friendid
strcpy(newfriend1->name, otherclient->charname); //friend name
thisclient->FriendList.push_back( newfriend1 );
RESETPACKET( pak, 0x7e1 );
ADDBYTE ( pak, 0x02 );
ADDWORD ( pak, otherclient->charid );
ADDBYTE ( pak, 0x00 );
ADDWORD ( pak, 0x0000 );
ADDSTRING ( pak, otherclient->charname );
ADDBYTE ( pak, 0x00);
thisclient->SendPacket(&pak);
//Add me to his friend list (sql)
if(!DB->QExecute("INSERT INTO list_friend (id,idfriend,namefriend) VALUES (%i,%i,'%s')",
thisclient->charid,otherclient->charid,otherclient->charname))
return false;
CFriendList * newfriend2 = new (nothrow) CFriendList;
if(newfriend2==NULL)
return false;
newfriend2->id = thisclient->charid; //friendid
strcpy(newfriend2->name, thisclient->charname); //friend name
otherclient->FriendList.push_back( newfriend2 );
}
else//not founded
{
BEGINPACKET( pak, 0x7e1 );
ADDBYTE ( pak, 0x04 );
ADDWORD ( pak, 0x0000 );
ADDSTRING ( pak, nick );
ADDBYTE ( pak, 0x00 );
thisclient->SendPacket(&pak);
}
delete []nick;
}
break;
case 0x03://no, i dont want
{
char* nick = new (nothrow) char[P->Size];
if(nick==NULL)
{
Log(MSG_ERROR, "Error allocing memory: pakMessengerManager 3" );
return false;
}
memcpy( nick, &P->Buffer[3], P->Size );
CCharClient* otherclient = (CCharClient*) GetClientByName (nick);
if(otherclient!=NULL)
{
BEGINPACKET( pak, 0x7e1 );
ADDBYTE ( pak, 0x03 );
ADDSTRING ( pak, thisclient->charname );
ADDBYTE ( pak, 0x00);
otherclient->SendPacket(&pak);
}
else
{
BEGINPACKET( pak, 0x7e1 );
ADDBYTE ( pak, 0x04 );
ADDWORD ( pak, 0x0000 );
ADDSTRING ( pak, nick );
ADDBYTE ( pak, 0x00 );
thisclient->SendPacket(&pak);
}
}
break;
case 0x05://freakin later
{
WORD id = GETWORD ((*P),1);
if(!DB->QExecute("DELETE FROM list_friend WHERE id=%i and idfriend=%i",
thisclient->charid,id))
return false;
CCharClient* otherclient = (CCharClient*) GetClientByID(id);
if(otherclient!=NULL)
{
ChangeMessengerStatus ( thisclient, otherclient, 0x08);
}
}
break;
case 0xfa://messenger logout
{
WORD id = GETWORD ((*P),1);
CCharClient* ctherclient = (CCharClient*) GetClientByID(id);
if(ctherclient==NULL)
return true;
ctherclient->logout = true;
for(UINT i=0;i<ctherclient->FriendList.size();i++)
{
CFriendList* thisfriend = ctherclient->FriendList.at( i );
CCharClient* otherclient = (CCharClient*) GetClientByID( thisfriend->id );
if(otherclient!=NULL)
{
ChangeMessengerStatus ( ctherclient, otherclient, 0x08);
}
}
//Logout in clan
ClanLogout ( ctherclient );
}
break;
default:
Log( MSG_INFO, "Friend action unknown: %i", action );
break;
}
return true;
}
// Messenger Chat
bool CCharServer::pakMessengerChat ( CCharClient* thisclient, CPacket* P )
{
WORD id = GETWORD((*P),0);
CCharClient* otherclient = (CCharClient*) GetClientByID(id);
if(otherclient!=NULL)
{
BEGINPACKET( pak, 0x7e2 );
ADDWORD ( pak, thisclient->charid );
for (int i=2;i<(P->Size-6);i++)
ADDBYTE ( pak, GETBYTE((*P),i ));
otherclient->SendPacket(&pak);
}
return true;
}
+68
View File
@@ -0,0 +1,68 @@
/*
Open Source Rose Online Team - http://osroseon.to.md/
note: the Server is develop with erose source server + eich source
*/
#ifndef __ROSE_DATATYPES__
#define __ROSE_DATATYPES__
#include "../common/sockets.h"
// List of clan members
struct CClanMembers
{
UINT id;
char name[50];
int clan_rank;
};
// An item (for figuring out what a user is wearing)
struct CItem {
UINT owner;
UINT itemnum;
UINT itemtype;
UINT refine;
UINT durability;
UINT lifespan;
};
// A single client character
struct CCharacter {
char char_name[17];
UINT level;
UINT face;
UINT hairStyle;
int sex;
UINT classid;
UINT id;
unsigned long int DeleteTime;
};
// List of friends
struct CFriendList
{
int id;
char name[17];
};
// List of clan
struct CClans
{
int id;
int logo;
int back;
int grade;
int cp;
char name[17];
char slogan[30];
char news[260];
vector<CClanMembers*> ClanMembers;
};
// Channel list
struct CChanels
{
UINT id;
char* ip;
UINT port;
SOCKET sock;
};
#endif
+184
View File
@@ -0,0 +1,184 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://osroseon.to.md
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "charserver.h"
// Search client by userid
CCharClient* CCharServer::GetClientByUserID( UINT userid )
{
for(UINT i=0;i<ClientList.size( );i++)
{
CCharClient* client = (CCharClient*) ClientList.at( i );
if(client->userid==userid)
{
return client;
}
}
return NULL;
}
// Search the client by char id
CCharClient* CCharServer::GetClientByID( UINT charid )
{
for(UINT i=0;i<ClientList.size( );i++)
{
CCharClient* client = (CCharClient*) ClientList.at( i );
if(client->charid==charid)
{
return client;
}
}
return NULL;
}
// Search the client by char name
CCharClient* CCharServer::GetClientByName( char *name )
{
try
{
for(UINT i=0;i<ClientList.size( );i++)
{
CCharClient* client = (CCharClient*) ClientList.at( i );
if(strcmp(client->charname, name)==0)
{
return client;
}
}
}
catch(...)
{
return NULL;
}
return NULL;
}
// Search the client by char name
CCharClient* CCharServer::GetClientByUserName( char *username )
{
for(UINT i=0;i<ClientList.size( );i++)
{
CCharClient* client = (CCharClient*) ClientList.at( i );
if(strcmp(client->username, username)==0)
{
return client;
}
}
return NULL;
}
// Search the clan by clan id
CClans* CCharServer::GetClanByID( int id )
{
for(UINT i=0;i<ClanList.size();i++)
{
CClans* thisclan = ClanList.at( i );
if (thisclan->id==id)
return thisclan;
}
return NULL;
}
// Send packet to all the clan members
bool CCharServer::SendToClanMembers( int clanid,CPacket* pak )
{
CClans* thisclan = GetClanByID(clanid);
if(thisclan==0)
return false;
for(UINT i=0;i<thisclan->ClanMembers.size();i++)
{
CClanMembers* thismember = thisclan->ClanMembers.at(i);
CCharClient* otherclient = (CCharClient*) GetClientByID (thismember->id);
if(otherclient!=0)
{
otherclient->SendPacketCpy(pak);
}
}
return true;
}
// Update clan window all members 07
bool CCharServer::UpdateClanWindow( int clanid )
{
CClans* thisclan = GetClanByID(clanid);
if(thisclan==0)
return false;
for(UINT i=0;i<thisclan->ClanMembers.size();i++)
{
CClanMembers* thismember = thisclan->ClanMembers.at(i);
CCharClient* otherclient = (CCharClient*) GetClientByID (thismember->id);
if(otherclient!=0)
{
BEGINPACKET( pak, 0x7e0);
ADDBYTE ( pak, 0x33);
ADDWORD ( pak, clanid);
ADDWORD ( pak, 0x0000);
ADDWORD ( pak, thisclan->back );//clan background
ADDWORD ( pak, thisclan->logo );//clanlogo
ADDBYTE ( pak, thisclan->grade);//clan grade
ADDBYTE ( pak, otherclient->clan_rank);
ADDDWORD ( pak, thisclan->cp );
ADDDWORD ( pak, 0x00000064 );
ADDDWORD ( pak, 0x00000000 );
ADDDWORD ( pak, 0x00000000 );
ADDWORD ( pak, 0x0003 );//?????????
ADDWORD ( pak, 0x0000 );
ADDWORD ( pak, 0x0000 );
for(int i=0;i<119;i++)
ADDBYTE ( pak, 0x00);
ADDSTRING ( pak, thisclan->name);//clan name
ADDBYTE ( pak, 0x00);
ADDSTRING ( pak, thisclan->slogan);//Clan slogan
ADDBYTE ( pak, 0x00);
ADDSTRING ( pak, thisclan->news);//Clan news
ADDBYTE ( pak, 0x00);
otherclient->SendPacket(&pak);
}
}
return true;
}
// Get channel by id
CChanels* CCharServer::GetChannelByID( unsigned int id )
{
for(unsigned int i=0;i<ChannelList.size();i++)
{
CChanels* thischannel = ChannelList.at(i);
if(thischannel->id==id)
return thischannel;
}
return NULL;
}
// Returns the current time/date
unsigned long int CCharServer::GetServerTime( )
{
// Get time/date and write it to the beginning of the row
time_t rawtime; // For time
struct tm* timeinfo; // "
time ( &rawtime );
timeinfo = localtime( &rawtime );
unsigned long int uCurTime = 0;
uCurTime += (timeinfo->tm_sec * 1 );
uCurTime += (timeinfo->tm_min * 60 );
uCurTime += (timeinfo->tm_hour * 3600 );
uCurTime += (timeinfo->tm_yday * 86400 );
uCurTime += ((timeinfo->tm_year-2000) * 86400*366 );
return uCurTime;
}
+67
View File
@@ -0,0 +1,67 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://osroseon.to.md
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "charserver.h"
unsigned char LOG_THISSERVER = 0;
class CCharServer* GServer;
// Main function
int main(int argc, char *argv[])
{
LOG_THISSERVER = LOG_CHARACTER_SERVER;
InitWinSocket( );
string fileconf = "charserver.conf";
if(argc>1)
{
fileconf = argv[1];
}
CCharServer *server = new (nothrow) CCharServer( fileconf );
if(server==NULL)
return -1;
MYSQL mysql;
server->DB = new CDatabase( server->Config.SQLServer.pcServer,
server->Config.SQLServer.pcUserName,
server->Config.SQLServer.pcPassword,
server->Config.SQLServer.pcDatabase,
server->Config.SQLServer.pcPort, &mysql );
server->port = server->Config.CharPort;
if(server->Config.usethreads)
Log( MSG_INFO, "Using Threads" );
if(server->DB->Connect( )==0) Log( MSG_INFO, "Connected to MySQL server" );
else
{
delete server;
#ifdef _WIN32
system("pause");
#endif
return -1;
}
server->LoadEncryption ();
// Start server
server->StartServer();
// Close server
server->DB->Disconnect( );
delete server;
CloseWinSocket( );
return EXIT_SUCCESS;
}
// -----------------------------------------------------------------------------------------
+109
View File
@@ -0,0 +1,109 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://osroseon.to.md
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "charserver.h"
/*
/ from signal.h
* NOTE: SIGINT is produced when the user presses Ctrl-C.
* SIGILL has not been tested.
* SIGFPE doesn't seem to work?
* SIGSEGV does not catch writing to a NULL pointer (that shuts down
* your app; can you say "segmentation violation core dump"?).
* SIGTERM comes from what kind of termination request exactly?
* SIGBREAK is indeed produced by pressing Ctrl-Break.
* SIGABRT is produced by calling abort.
*/
void StartSignal( )
{
signal( SIGINT, HandleSignal );
signal( SIGILL, HandleSignal );
signal( SIGFPE, HandleSignal );
signal( SIGSEGV, HandleSignal );
signal( SIGTERM, HandleSignal );
signal( SIGBREAK, HandleSignal );
signal( SIGABRT, HandleSignal );
}
void StopSignal( )
{
signal( SIGINT, 0 );
signal( SIGILL, 0 );
signal( SIGFPE, 0 );
signal( SIGSEGV, 0 );
signal( SIGTERM, 0 );
signal( SIGBREAK, 0 );
signal( SIGABRT, 0 );
}
void HandleSignal( int num )
{
switch(num)
{
case SIGINT:/* Interactive attention */
Log( MSG_ERROR, "Signal received: SIGINT" );
#ifdef _WIN32
Sleep(1000);
#else
usleep(1000);
#endif
raise(num);
break;
case SIGILL:/* Illegal instruction */
Log( MSG_ERROR, "Signal received: SIGILL, Server will be closed, Trying to save..." );
GServer->isActive = false;
#ifdef _WIN32
Sleep(1000);
#else
usleep(1000);
#endif
raise(num);
break;
case SIGFPE:/* Floating point error */
Log( MSG_ERROR, "Signal received: SIGFPE, Server will be closed, Trying to save..." );
GServer->isActive = false;
raise(num);
break;
case SIGSEGV:/* Segmentation violation */
Log( MSG_ERROR, "Signal received: SIGSEGV, Server will be closed, Trying to save..." );
GServer->isActive = false;
#ifdef _WIN32
Sleep(1000);
#else
usleep(1000);
#endif
raise(num);
break;
case SIGTERM:/* Termination request */
Log( MSG_INFO, "Signal received: SIGTERM, Server will be closed" );
GServer->isActive = false;
break;
#ifdef _WIN32
case SIGBREAK:/* Control-break */
Log( MSG_INFO, "Signal received: SIGBREAK, Server will be closed" );
GServer->isActive = false;
break;
#endif
default:
cout << "Unknown Signal Number: " << num << endl;
raise(num);
}
}
+66
View File
@@ -0,0 +1,66 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://osroseon.to.md
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "sockets.h"
// Constructor
CBaseSocket::CBaseSocket( )
{
sock = INVALID_SOCKET;
isActive = false;
}
// Destructor
CBaseSocket::~CBaseSocket( )
{
}
// Close all open sockets
void CBaseSocket::CloseSocket( void )
{
// Leave function, if socket isn't active
if ( !isActive ) return;
// Close socket
close( sock );
sock = INVALID_SOCKET;
isActive = false;
}
// Init winsocket, if we are using Windows
bool InitWinSocket ( void )
{
#ifdef _WIN32
WSADATA wsa;
return (WSAStartup(MAKEWORD(2,0),&wsa)==0);
#else
return true;
#endif
}
// Close winsocket, if we are using Windows
void CloseWinSocket( void )
{
#ifdef _WIN32
WSACleanup( );
#endif
}
+216
View File
@@ -0,0 +1,216 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://osroseon.to.md
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
developed with Main erose/hrose source server + some change from the original eich source
*/
#include "sockets.h"
#include "seh.hpp"
#include "config.h"
// Constructor
CClientSocket::CClientSocket( )
{
PacketSize = 6; // Starting size
PacketOffset = 0; // No bytes read, yet.
}
// Destructor
CClientSocket::~CClientSocket( )
{
}
// Receive this client's socket
bool CClientSocket::ReceiveData( )
{
int ReceivedBytes;
short BytesToRead;
// Calculate bytes to read to get the full packet
BytesToRead = PacketSize - PacketOffset;
// This should never happen, but it is integrated:
if ( BytesToRead > 0x400 - PacketOffset ) return false;
if ( BytesToRead == 0 ) return false;
// Receive data from client
ReceivedBytes = recv( sock, (char*)&Buffer[ PacketOffset ], BytesToRead, 0 );
if ( ReceivedBytes <= 0 ) return false;
// Update pointer
PacketOffset += ReceivedBytes;
// If the packet is not complete, leave the function
if ( ReceivedBytes != BytesToRead ) return true;
if ( PacketSize == 6 )
{
// We received the headerblock
#ifndef USE124
PacketSize = DecryptBufferHeader( &CryptStatus, CryptTable, Buffer );
#else
CPacket* header = (CPacket*)&Buffer;
PacketSize = header->Size;
#endif
// Did we receive an incorrect buffer?
if ( PacketSize < 6 )
{
Log(MSG_ERROR, "(SID:%i) Client sent incorrect blockheader.", sock );
return false;
}
// Is the packet larger than just the header, then continue receiving
if ( PacketSize > 6 ) return true;
}
#ifndef USE124
// We received the whole packet - Now we try to decrypt it
if ( !DecryptBufferData( CryptTable, Buffer ) )
{
Log(MSG_ERROR, "(SID:%i) Client sent illegal block.", sock );
return false;
}
#else
cryptPacket( (char*)Buffer, this->ct);
#endif
CPacket* pak = (CPacket*)&Buffer;
//comment to prevent packet logging
FILE *fh = NULL;
fopen_s (&fh, "log/inoutpackets.log", "a+");
if ( fh != NULL ) {
fprintf( fh, "(SID:%08u) IN %04x: ", sock, pak->Command );
for ( int i=0; i<pak->Size-6; ++i ) fprintf( fh, "%02x ", (unsigned char)pak->Buffer[i] );
fprintf( fh, "\n" );
fclose( fh );
}
// Handle actions for this packet
if ( !GS->OnReceivePacket( this, pak ) )
{
//Log(MSG_ERROR, "onrecieve packet returned false");
return false;
}
// Reset values for the next packet
PacketSize = 6;
PacketOffset = 0;
//Log(MSG_DEBUG, "onrecieve packet returned true");
return true;
}
// Send a packet to this client
void CClientSocket::SendPacket( CPacket *P )
{
//first log it so we don't have to worry about encryption. Comment to prevent logging
bool LogFile = true;
FILE *fh = NULL;
fopen_s (&fh, "log/receivedpackets.log", "a+");
if ( fh != NULL && LogFile)
{
fprintf( fh, "(SID:%08u) OUT %04x: ", sock, P->Command );
for ( int i=0; i<P->Size-6; ++i ) fprintf( fh, "%02x ", (unsigned char)P->Buffer[i] );
fprintf( fh, "\n" );
fclose( fh );
}
// :WARNING: IF WE ADD A CRYPT FUNCTION HERE WE MUST COPY THE
// PACKET AND NOT USE THE ORIGINAL, IT WILL FUCK UP
// THE SENDTOALL FUNCTIONS
unsigned char* Buffer2 = (unsigned char*)P;
unsigned Size = P->Size;
#ifndef USE124
if(this == NULL)
{
Log(MSG_WARNING,"tried to send a packet to a socket that doesn't exist any more");
return;
}
//__seh_try
//{
// EncryptBuffer( CryptTable, Buffer );
//}
//__seh_except(info, context)
//{
// Log(MSG_WARNING,"Caught a bad packet %s. Send cancelled", Buffer);
// return;
//}
//__seh_end
EncryptBuffer( CryptTable, Buffer2 );
#endif
send( sock, (char*)Buffer2, Size, 0 );
//record teh packet that we just sent
//CPacket* pak = (CPacket*)&Buffer;
}
//-------------------------------------------------------------------------
// Send a packet to a client without encrypting the source packet
//-------------------------------------------------------------------------
void CClientSocket::SendPacketCpy( CPacket *P )
{
CPacket NewPacket;
memcpy( &NewPacket, P, sizeof( CPacket ) );
SendPacket( &NewPacket );
}
// Handle client socket (threads)
PVOID ClientMainThread( PVOID ClientSocket )
{
CClientSocket* thisplayer = (CClientSocket*) ClientSocket;
fd_set fds;
while(thisplayer->isActive)
{
FD_ZERO(&fds);
FD_SET (thisplayer->sock, &fds);
int Select = select( thisplayer->sock+1, &fds, NULL, NULL, NULL );
if(Select == SOCKET_ERROR)
{
Log( MSG_ERROR,NULL,"Error in Select");
thisplayer->isActive = false;
}
else
{
if(FD_ISSET( thisplayer->sock, &fds ))
{
if (thisplayer->isserver == true)
{
//Log( MSG_INFO,"ISC PACKET in ClientMainThread");
thisplayer->ISCThread();
}
else
if(!thisplayer->ReceiveData( ))
{
thisplayer->isActive = false;
}
}
}
}
thisplayer->GS->DisconnectClient( thisplayer );
pthread_exit(NULL);
return 0 ;
}
// -----------------------------------------------------------------------------------------
+549
View File
@@ -0,0 +1,549 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://osroseon.to.md
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
developed with Main erose/hrose source server + some change from the original eich source
*/
#include "sockets.h"
#include <iostream>
// Constructor
CServerSocket::CServerSocket( )
{
#ifdef USE124
csum = new char [0x200];
csumlen = buildChecksum(csum, "TRose.exe");
if(csumlen < 0)
std::cout << "Failed to generate checksum, error: " << csumlen << std::endl;
else
std::cout << "Generated checksum" << std::endl;
#endif
ConnectedClients = 0;
}
// Destructor
CServerSocket::~CServerSocket( )
{
}
// Start up our server
bool CServerSocket::StartServer( )
{
//struct sockaddr_in ain;
int test;
sock = socket( AF_INET, SOCK_STREAM, 0 );
if (sock == INVALID_SOCKET)
{
Log( MSG_FATALERROR, "Could not create a socket" );
return false;
}
int optval = 1;
if(setsockopt(sock, SOL_SOCKET,SO_KEEPALIVE,(const char*)&optval,sizeof(optval))==-1)
{
Log(MSG_ERROR, "setsockopt:SO_KEEPALIVE" );
}
setsockopt(sock, IPPROTO_TCP,TCP_NODELAY,(const char*)&optval,sizeof(optval));
ain.sin_family = AF_INET;
ain.sin_addr.s_addr = INADDR_ANY;
ain.sin_port = htons( port );
memset(&(ain.sin_zero), '\0', 8);
if ( bind( sock, (const sockaddr*)&ain, sizeof( struct sockaddr ) ) )
{
Log( MSG_FATALERROR, "Could not bind socket" );
std::cout <<"socket " << sock << std::endl;
std::cin >> test;
closesocket( sock );
sock = INVALID_SOCKET;
return false;
}
if ( listen( sock, SOMAXCONN ) == -1 )
{
Log( MSG_FATALERROR, "Could not listen on socket" );
closesocket( sock );
sock = INVALID_SOCKET;
return false;
}
if (LOG_THISSERVER == LOG_CHARACTER_SERVER)
{
//struct sockaddr_in ain;
sckISC = socket( AF_INET, SOCK_STREAM, 0 );
if (sckISC == INVALID_SOCKET) {
Log( MSG_ERROR, "Could not create valid ISC socket (WSK2 ERROR: %i)", WSAGetLastError( ) );
return false;
}
optval = 1;
if(setsockopt(sckISC, SOL_SOCKET,SO_KEEPALIVE,(const char*)&optval,sizeof(optval))==-1)
{
Log(MSG_ERROR, "setsockopt:SO_KEEPALIVE" );
}
setsockopt(sckISC, IPPROTO_TCP,TCP_NODELAY,(const char*)&optval,sizeof(optval));
sain.sin_family = AF_INET;
sain.sin_addr.s_addr = INADDR_ANY;
sain.sin_port = htons( Config.CharsPort);//29110 );
memset(&(sain.sin_zero), '\0', 8);
if ( bind( sckISC, (const sockaddr*)&sain, sizeof( struct sockaddr ) ) )
{
Log( MSG_FATALERROR, "Could not bind socket" );
closesocket( sckISC );
sckISC = INVALID_SOCKET;
return false;
}
if ( listen( sckISC, SOMAXCONN ) == -1 )
{
Log( MSG_FATALERROR, "Could not listen on socket" );
closesocket( sckISC );
sckISC = INVALID_SOCKET;
return false;
}
Log( MSG_INFO, "opened ISC poort %i",29110 );
}
if (LOG_THISSERVER == LOG_WORLD_SERVER)
{
struct sockaddr_in aina; //if this doesn't work. change back to ain
sckISC = socket( AF_INET, SOCK_STREAM, 0 );
if (sckISC == INVALID_SOCKET) {
Log( MSG_ERROR, "Could not create valid ISC socket (WSK2 ERROR: %i)", WSAGetLastError( ) );
return false;
}
aina.sin_family = AF_INET;
aina.sin_addr.s_addr = inet_addr(Config.CharIP);//( "127.0.0.1" );
aina.sin_port = htons( Config.CharPort);//29110 );
if ( connect( sckISC, (const sockaddr*)&aina, sizeof( aina ) ) == SOCKET_ERROR ) {
Log( MSG_ERROR, "Could not connect to ISC (WSK2 ERROR: %i)", WSAGetLastError( ) );
closesocket( sckISC );
sckISC = INVALID_SOCKET;
return false;
}
sckISCII = socket( AF_INET, SOCK_STREAM, 0 );
if (sckISCII == INVALID_SOCKET) {
Log( MSG_ERROR, "Could not create valid ISC socket (WSK2 ERROR: %i)", WSAGetLastError( ) );
return false;
}
optval = 1;
if(setsockopt(sckISCII, SOL_SOCKET,SO_KEEPALIVE,(const char*)&optval,sizeof(optval))==-1)
{
Log(MSG_ERROR, "setsockopt:SO_KEEPALIVE" );
}
setsockopt(sckISCII, IPPROTO_TCP,TCP_NODELAY,(const char*)&optval,sizeof(optval));
sain.sin_family = AF_INET;
sain.sin_addr.s_addr = INADDR_ANY;
sain.sin_port = htons( Config.WorldsPort );//29210 );
memset(&(sain.sin_zero), '\0', 8);
if ( bind( sckISCII, (const sockaddr*)&sain, sizeof( struct sockaddr ) ) )
{
Log( MSG_FATALERROR, "Could not bind socket" );
closesocket( sckISCII );
sckISCII = INVALID_SOCKET;
return false;
}
if ( listen( sckISCII, SOMAXCONN ) == -1 )
{
Log( MSG_FATALERROR, "Could not listen on socket" );
closesocket( sckISCII );
sckISCII = INVALID_SOCKET;
return false;
}
Log( MSG_INFO, "opened ISC poort %i",Config.WorldsPort );//29210 );
}
if (LOG_THISSERVER == LOG_LOGIN_SERVER)
{
struct sockaddr_in aina; //may need to change back to ain
sckISC = socket( AF_INET, SOCK_STREAM, 0 );
if (sckISC == INVALID_SOCKET) {
Log( MSG_ERROR, "Could not create valid ISC socket (WSK2 ERROR: %i)", WSAGetLastError( ) );
return false;
}
}
isActive = true;
if ( !this->OnServerReady( ) )
{
Log( MSG_FATALERROR, "Server could not start" );
closesocket( sock );
sock = INVALID_SOCKET;
isActive = false;
return false;
}
Log( MSG_INFO, "Server started on port %i and is listening.", port );
//ISCThread( );
ServerLoop( );
// Nothing past here is ever really called
OnServerDie( );
closesocket( sock );
return true;
}
// Raven0123
void CServerSocket::CryptISCPak( char* pak )
{
return;
unsigned paksize = *((unsigned short*)&pak[0]);
for( unsigned short i = 2; i < paksize; i ++ )
pak[i] ^= 0x81 * i * paksize;
}
// Raven0123
//void CServerSocket::ISCThread()
bool CClientSocket::ISCThread()
{
unsigned char buffer[0x400];
unsigned recvd = 0;
unsigned bufsize = 0;
unsigned readlen = 6;
bool go = true;
do {
recvd = recv( sock, (char*)&buffer[bufsize], readlen-bufsize, 0 );
if( recvd == 0){
return false;
}
if( recvd == SOCKET_ERROR ) {
return false;
}
bufsize += recvd;
if( bufsize != readlen ) continue;//return;//continue;
if( bufsize == 6 ) {
readlen = *((unsigned short*)&buffer[0]);
if( readlen < 6 ) Log( MSG_ERROR, "Invalid server Packet Header" );
if( readlen > 6 ) continue;//return;//continue;
}
GS->OnReceivePacket( this, (CPacket*)&buffer[0] );
go = false;
bufsize = 0;
readlen = 6;
} while ( go==true );
return true;
}
// Server is started, lets run our loop :D
void CServerSocket::ServerLoop( )
{
fd_set fds;
int activity;
maxfd = 0;
sockaddr_in ClientInfo;
SOCKET NewSocket;
timeval timeout;
maxfd = sock;
OnServerStep();
do
{
if (!Ping( ))
isActive = false;
timeout.tv_sec = 0;
timeout.tv_usec = 1000;
NewSocket = INVALID_SOCKET;
FD_ZERO( &fds );
if(!Config.usethreads)
FillFDS( &fds );
FD_SET( sock, &fds );
activity = select( maxfd+1, &fds, NULL, NULL, &timeout );
if ( activity == 0 )
{
// continue;
FD_ZERO( &fds );
if(!Config.usethreads)
FillFDS( &fds );
FD_SET( sckISC, &fds );
activity = select( maxfd+1, &fds, NULL, NULL, &timeout );
if ( activity == 0 )continue;
if ( activity < 0 && errno != EINTR )
{
#ifdef _WIN32
Log( MSG_ERROR, "Select command failed. Error #%i", WSAGetLastError() );
#else
Log( MSG_ERROR, "Select command failed. Error #%i", errno );
#endif
isActive = false;
}
if ( FD_ISSET( sckISC, &fds ) )
{
int clientinfolen = sizeof( sockaddr_in );
#ifdef _WIN32
NewSocket = accept( sckISC, (sockaddr*)&ClientInfo, (int*)&clientinfolen );
#else
NewSocket = accept( sckISC, (sockaddr*)&ClientInfo, (socklen_t*)&clientinfolen );
#endif
// TODO: check if server is full
if (NewSocket != INVALID_SOCKET)
{
AddUser( NewSocket, &ClientInfo, true );
}
else
{
#ifdef _WIN32
Log( MSG_ERROR, "Error accepting socket: %i", WSAGetLastError() );
#else
Log( MSG_ERROR, "Error accepting socket: %i", errno );
#endif
}
}
}
if ( activity < 0 && errno != EINTR )
{
#ifdef _WIN32
Log( MSG_ERROR, "Select command failed. Error #%i", WSAGetLastError() );
#else
Log( MSG_ERROR, "Select command failed. Error #%i", errno );
#endif
isActive = false;
}
if ( FD_ISSET( sock, &fds ) )
{
int clientinfolen = sizeof( sockaddr_in );
#ifdef _WIN32
NewSocket = accept( sock, (sockaddr*)&ClientInfo, (int*)&clientinfolen );
#else
NewSocket = accept( sock, (sockaddr*)&ClientInfo, (socklen_t*)&clientinfolen );
#endif
// TODO: check if server is full
if (NewSocket != INVALID_SOCKET)
AddUser( NewSocket, &ClientInfo, false );
else
{
#ifdef _WIN32
Log( MSG_ERROR, "Error accepting socket: %i", WSAGetLastError() );
#else
Log( MSG_ERROR, "Error accepting socket: %i", errno );
#endif
}
}
if(!Config.usethreads)
HandleClients( &fds );
} while( isActive );
}
// Fills out an FDS for the server
void CServerSocket::FillFDS( fd_set* fds )
{
for(UINT i=0;i<ClientList.size( );i++)
{
CClientSocket* client = ClientList.at( i );
if(client->isActive)
{
FD_SET( (unsigned)client->sock, fds );
if(client->sock>maxfd)
maxfd=client->sock;
}
else
{
DisconnectClient( client );
}
}
}
// Handle all our clients
void CServerSocket::HandleClients( fd_set* fds )
{
for(UINT i=0;i<ClientList.size( );i++)
{
CClientSocket* client = ClientList.at( i );
if(!client->isActive)
continue;
if(FD_ISSET( client->sock, fds ))
{
if (client->isserver == true)
{
//Log( MSG_INFO,"ISC PACKET in HandleClients");
if(!client->ISCThread()){
client->isActive = false;
DisconnectClient( client );}
}
else
if(!client->ReceiveData( ) )
{
client->isActive = false;
DisconnectClient( client );
}
}
}
}
// Add a new user to our server
void CServerSocket::AddUser( SOCKET sock, sockaddr_in* ClientInfo, bool server )
{
ConnectedClients++;
CClientSocket* thisclient = this->CreateClientSocket( );
if (thisclient==NULL)
{
closesocket( thisclient->sock );
if (thisclient!=0) delete thisclient;
thisclient=0;
return;
}
#ifdef USE124
thisclient->ct = new char[TABLE_SIZE];
buildCryptTable(thisclient->ct, csum, csumlen);
#endif
thisclient->CryptTable = CryptTable;
thisclient->CryptStatus.CurAddValue = 0;
thisclient->CryptStatus.CurEncryptionValue = CryptTable->EncryptionStartValue;
thisclient->GS = this;
thisclient->sock = sock;
thisclient->isActive = true;
if (!OnClientConnect( thisclient )) {
closesocket( thisclient->sock );
if (thisclient!=0) delete thisclient;
thisclient=0;
return;
}
thisclient->ClientIP = "";
thisclient->ClientIP = inet_ntoa( ClientInfo->sin_addr );
char *tmp;
memset(&thisclient->ClientSubNet, '\0', 12 );
sprintf_s(thisclient->ClientSubNet, "%i.%i.%i",
(ClientInfo->sin_addr.s_addr )&0xFF, (ClientInfo->sin_addr.s_addr>>8 )&0xFF,
(ClientInfo->sin_addr.s_addr>>16)&0xFF);
ClientList.push_back( thisclient );
if(Config.usethreads)
{
pthread_create( &threads[sock], NULL, ClientMainThread, (PVOID)thisclient);
}
memcpy( &thisclient->clientinfo, ClientInfo, sizeof(struct sockaddr_in));
if(server==true)
{
thisclient->isserver=true;
Log( MSG_INFO, "Server connected from %s", inet_ntoa( ClientInfo->sin_addr ) );
}
else
{
thisclient->isserver=false;
Log( MSG_INFO, "User connected from %s", inet_ntoa( ClientInfo->sin_addr ) );
}
}
// Disconnect our user
void CServerSocket::DisconnectClient( CClientSocket* thisclient )
{
ConnectedClients--;
OnClientDisconnect( thisclient );
closesocket( thisclient->sock );
thisclient->isActive = false;
thisclient->sock = INVALID_SOCKET;
for(UINT i=0;i<ClientList.size( );i++)
{
CClientSocket* client = ClientList.at( i );
if( client == thisclient )
{
ClientList.erase( ClientList.begin( ) + i );
break;
}
}
DeleteClientSocket( thisclient );
}
// This function creates an appropriate client socket
CClientSocket* CServerSocket::CreateClientSocket ( )
{
CClientSocket* thisclient;
thisclient = new (nothrow) CClientSocket( );
return thisclient;
}
// This function deletes an old client socket
void CServerSocket::DeleteClientSocket( CClientSocket* thisclient )
{
if (thisclient->isserver)
Log( MSG_INFO, "Server disconnected" );
else
Log( MSG_INFO, "User disconnected" );
delete thisclient;
}
//This function loads the encryption
void CServerSocket::LoadEncryption( )
{
GenerateCryptTables( CryptTable, 0x87654321 );
//port = ConfigGetInt("server.conf", "loginport", 29000);
}
// This function is called just before proccessing clients
void CServerSocket::OnServerStep( )
{
}
// This function is called just before the server starts
bool CServerSocket::OnServerReady( )
{
return true;
}
// This function is called just before the server dies
void CServerSocket::OnServerDie( )
{
// DOESNT WORK - DAMN CONSOLE APPS
}
// This function is called, if a client receives data
bool CServerSocket::OnReceivePacket( CClientSocket* thisclient, CPacket *P )
{
return true;
}
// This function is called, if a client connects
bool CServerSocket::OnClientConnect( CClientSocket* thisclient )
{
return true;
}
// This function is called, if a client disconnects
void CServerSocket::OnClientDisconnect( CClientSocket* thisclient )
{
}
// Raven0123
void CServerSocket::SendISCPacket( CPacket* pak )
{
send( sckISC, (char*)pak, pak->Size, 0 );
}
void CServerSocket::ReceivedISCPacket( CPacket* pak )
{
Log( MSG_DEBUG, "GOT ISC PACKET (BASESERVER) - 0x%04x %04x", pak->Command, pak->Size );
}
bool CServerSocket::DoSQL(char *Format, ...) {
int retval;
char Buffer[0x1500];
va_list ap; va_start( ap, Format );
vsprintf_s( Buffer, Format, ap );
va_end ( ap );
retval = mysql_query( mysql, Buffer );
if( retval != 0 ) Log( MSG_ERROR, "MySQL Query Error '%s'", mysql_error( mysql ) );
return (retval==0);
}
bool CServerSocket::Ping( )
{
return true;
}
+114
View File
@@ -0,0 +1,114 @@
/*******************************************************************************************
___ ___ ___ ___
___| _ \/ _ \/ __| __|
/ -_) / (_) \__ \ _|
\___|_|_\\___/|___/___|
eROSE Server Develped by Brett19.
hROSE Team: Brett19 and bdaan
Year: 2006
Release Date: Summer-Winter 2006
*******************************************************************************************/
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <ctype.h>
// Find the entry
bool ConfigGetEntry( const char *pcFile, const char *pcNameMust, char* &pcResult )
{
char pcBuffer[ 512 ];
char *pcName, *pcPar, *pcPoint;
unsigned len;
pcResult=0;
// Open file
FILE* fh = NULL;
fopen_s (&fh, pcFile, "r");
if ( fh == NULL ) return false;
do
{
fgets( pcBuffer, 510, fh );
len = (unsigned)strlen( pcBuffer );
if ( pcBuffer[ len-1 ] == '\n' ) --len;
pcBuffer[ len ] = 0;
pcName = pcBuffer;
while ( *pcName==' ' || *pcName=='\t' ) ++pcName;
if ( *pcName==0 || *pcName=='#' ) continue;
pcPoint = pcName;
while ( *pcPoint!=' ' && *pcPoint!='\t' && *pcPoint!='#' && *pcPoint!='=' && *pcPoint!=0 ) ++pcPoint;
if ( *pcPoint==0 || *pcPoint=='#' ) continue;
pcPar = pcPoint;
while ( *pcPar==' ' || *pcPar=='\t' || *pcPar=='=' ) ++pcPar;
*pcPoint=0;
#ifdef _WIN32
if ( !_strcmpi( pcName, pcNameMust ) )
{
pcResult = _strdup( pcPar );
pcPoint = pcResult + strlen( pcPar );
if ( *pcPoint==0 ) return true;
--pcPoint;
while( *pcPoint==' ' || *pcPoint=='\t' ) *pcPoint--=0;
return true;
}
#else
if ( strcasecmp( pcName, pcNameMust )==0 )
{
pcResult = _strdup( pcPar );
pcPoint = pcResult + strlen( pcPar );
if ( *pcPoint==0 ) return true;
--pcPoint;
while( *pcPoint==' ' || *pcPoint=='\t' ) *pcPoint--=0;
return true;
}
#endif
} while ( !feof( fh ) );
// Close file
fclose( fh );
return true;
}
// -----------------------------------------------------------------------------------------
// Returns a text
// -----------------------------------------------------------------------------------------
char *ConfigGetString( const char *pcFile, const char *pcName, const char *pcDefault )
{
char *pcRet, *pcRetReal, *pcRetOld;
if ( !ConfigGetEntry( pcFile, pcName, pcRet ) ) return _strdup( pcDefault );
if (pcRet==0) return _strdup( pcDefault );
pcRetOld = pcRet;
if ( *pcRet=='"' )
{
++pcRet;
pcRet[ strlen(pcRet) - 1 ] = 0;
}
pcRetReal = _strdup( pcRet );
free( pcRetOld );
return pcRetReal;
}
// Returns a number
unsigned ConfigGetInt( const char *pcFile, const char *pcName, unsigned uDefault )
{
char *pcRet;
unsigned uRet;
if ( !ConfigGetEntry( pcFile, pcName, pcRet ) ) return uDefault;
if (pcRet==0) return uDefault;
uRet = atoi( pcRet );
free( pcRet );
return uRet;
}
// -----------------------------------------------------------------------------------------
+24
View File
@@ -0,0 +1,24 @@
/*******************************************************************************************
___ ___ ___ ___
___| _ \/ _ \/ __| __|
/ -_) / (_) \__ \ _|
\___|_|_\\___/|___/___|
eROSE Server Develped by Brett19.
hROSE Team: Brett19 and bdaan
Year: 2006
Release Date: Summer-Winter 2006
*******************************************************************************************/
#ifndef __ROSE_CONFIG_FUNCTIONS__
#define __ROSE_CONFIG_FUNCTIONS__
// -----------------------------------------------------------------------------------------
// Config load functions
// -----------------------------------------------------------------------------------------
char *ConfigGetString( const char *pcFile, const char *pcName, const char *pcDefault );
unsigned ConfigGetInt( const char *pcFile, const char *pcName, unsigned uDefault );
// -----------------------------------------------------------------------------------------
#endif
+188
View File
@@ -0,0 +1,188 @@
#include "database.h"
#include "../log.h"
// constructor
CDatabase::CDatabase( char* server , char* username, char* password, char* database, unsigned int port , MYSQL* mysql)
{
Server = server;
Username = username;
Password = password;
Database = database;
Port = port;
Mysql = mysql;
LastPing = time( NULL );
SQLMutex = PTHREAD_MUTEX_INITIALIZER;
mysql_init( Mysql );
}
// deconstructor
CDatabase::~CDatabase( )
{
}
// disconnect from mysql
void CDatabase::Disconnect( )
{
mysql_close( Mysql );
}
int CDatabase::Connect( )
{
Log( MSG_INFO, "Connecting to MySQL" );
if(!mysql_real_connect( Mysql, Server, Username, Password, Database,Port, NULL, 0 ))
{
Log( MSG_FATALERROR, "Error connecting to MySQL server: %s\n", mysql_error( Mysql ) );
return -1;
}
// Get timeout so we know when to ping - Drakia
MYSQL_RES *myresult = QStore("SELECT @@wait_timeout");
MYSQL_ROW row = mysql_fetch_row( myresult );
Timeout = atoi(row[0]) - 60; // Set the timeout to 1 minute before the connection will timeout
QFree( );
Log( MSG_INFO, "MySQL Ping Timeout: %d seconds", Timeout );
return 0;
}
// reconnect to mysql
int CDatabase::Reconnect( )
{
Log( MSG_INFO, "Reconnecting to Mysql" );
if(!mysql_real_connect( Mysql, Server, Username, Password, Database,Port, NULL, 0 ))
{
Log( MSG_FATALERROR, "Error reconnecting to MySQL server: %s\n", mysql_error( Mysql ) );
return -1;
}
return 0;
}
// execute query
bool CDatabase::QExecute( const char *Format,... )
{
bool Qfail = true;
char query[80000];
va_list ap;
va_start( ap, Format );
vsprintf_s (query, Format, ap);
va_end ( ap );
Log( MSG_QUERY, query );
pthread_mutex_lock( &SQLMutex );
while(Qfail)
{
if(mysql_query( Mysql, query )!=0)
{
Log( MSG_FATALERROR, "Could not execute query: %s", mysql_error( Mysql ) );
if(Reconnect( )==-1)
{
Log( MSG_FATALERROR, "Could not execute query: %s", mysql_error( Mysql ) );
pthread_mutex_unlock( &SQLMutex );
return false;
}
else Qfail = false;
}
else Qfail = false;
}
pthread_mutex_unlock( &SQLMutex );
return true;
}
MYSQL_RES* CDatabase::QStore( const char *Format, ...)
{
bool Qfail = true;
char query[80000];
va_list ap;
va_start( ap, Format );
vsprintf_s( query, Format, ap );
va_end ( ap );
result = NULL;
Log( MSG_QUERY, query );
//Log( MSG_INFO, query );
//Log( MSG_INFO, "Locking pthread mutex" );
pthread_mutex_lock( &SQLMutex );
//Log( MSG_INFO, "Locked pthread mutex" );
while(Qfail)
{
if(mysql_query( Mysql, query )!=0)
{
Log( MSG_FATALERROR, "Could not execute query: %s", mysql_error( Mysql ) );
if(Reconnect( )==-1)
{
Log( MSG_FATALERROR, "Could not execute query: %s", mysql_error( Mysql ) );
pthread_mutex_unlock( &SQLMutex );
return NULL;
}
else Qfail = false;
}
else Qfail = false;
// Log( MSG_INFO, "mysql answer: %s", mysql_error( Mysql ) );
}
//Log( MSG_INFO, "reading mysql result" );
result = mysql_store_result( Mysql );
//Log( MSG_INFO, "returning mysql result" );
return result;
}
MYSQL_RES* CDatabase::QUse( const char *Format, ...)
{
bool Qfail = true;
char query[1024];
va_list ap;
va_start( ap, Format );
vsprintf_s( query, Format, ap );
va_end ( ap );
result = NULL;
Log( MSG_QUERY, query );
pthread_mutex_lock( &SQLMutex );
while(Qfail)
{
if(mysql_query( Mysql, query )!=0)
{
Log( MSG_FATALERROR, "Could not execute query: %s", mysql_error( Mysql ) );
if(Reconnect( )==-1)
{
Log( MSG_FATALERROR, "Could not execute query: %s", mysql_error( Mysql ) );
pthread_mutex_unlock( &SQLMutex );
return NULL;
}
else Qfail = false;
}
else Qfail = false;
}
result = mysql_use_result( Mysql );
return result;
}
bool CDatabase::DoSQL(const char *Format, ...) {
int retval;
char Buffer[1024];
va_list ap; va_start( ap, Format );
vsprintf_s( Buffer, Format, ap );
va_end ( ap );
retval = mysql_query( Mysql, Buffer );
if( retval!=0 ) Log( MSG_ERROR, "MySQL Query Error '%s'", mysql_error( Mysql ) );
return (retval==0);
}
void CDatabase::QFree( )
{
mysql_free_result( result );
pthread_mutex_unlock( &SQLMutex );
}
bool CDatabase::Ping( )
{
if ( time( NULL ) > ( LastPing + Timeout ) ) {
Log(MSG_INFO, "MySql Ping");
LastPing = time( NULL );
MYSQL_RES *res = QStore("SELECT @@wait_timeout");
if (res == NULL) {
Log( MSG_ERROR, "MySQL Ping Failed, Attempting reconnect" );
QFree( );
return !Reconnect( );
}
MYSQL_ROW row = mysql_fetch_row(res);
Timeout = atoi(row[0]) - 60;
QFree( );
Log( MSG_INFO, "MySql Pong, new Timeout: %d seconds", Timeout);
}
return true;
}
+33
View File
@@ -0,0 +1,33 @@
#ifndef _ROSE_DATABASE_
#define _ROSE_DATABASE_
#include "../sockets.h"
class CDatabase
{
public:
CDatabase( char* , char*, char*, char*, unsigned int, MYSQL* );
~CDatabase( );
char* Server;
char* Username;
char* Password;
char* Database;
unsigned int Port;
unsigned int Timeout;
time_t LastPing;
int Connect( );
int Reconnect( );
void Disconnect( );
bool QExecute( const char *format,... );
MYSQL_RES* QUse( const char *format,... );
MYSQL_RES* QStore( const char *format,... );
bool DoSQL(const char *Format, ...);
void QFree( );
bool Ping( );
MYSQL* Mysql;
MYSQL_RES* result;
pthread_mutex_t SQLMutex;
};
#endif
+91
View File
@@ -0,0 +1,91 @@
#include "sockets.h"
CPacket::CPacket( unsigned short mycommand, unsigned short mysize, unsigned short myunused )
{
Command = mycommand;
Size = mysize;
Unused = myunused;
}
CPacket::~CPacket( ) { }
void CPacket::StartPacket( unsigned short mycommand, unsigned short mysize, unsigned short myunused )
{
Command = mycommand;
Size = mysize;
Unused = myunused;
}
void CPacket::AddByte( unsigned char value )
{
Buffer[Size-6] = value;
Size += 1;
}
void CPacket::AddWord( unsigned short value )
{
*((unsigned short*)&Buffer[Size-6]) = value;
Size += 2;
}
void CPacket::AddDWord( unsigned value )
{
*((unsigned*)&Buffer[Size-6]) = value;
Size += 4;
}
void CPacket::AddQWord( unsigned long long value )
{
*((unsigned long long*)&Buffer[Size-6]) = value;
Size += 8;
}
void CPacket::AddFloat( float value )
{
*((float*)&Buffer[Size-6]) = value;
Size += 4;
}
void CPacket::AddString( char* value )
{
for(unsigned char c=0; c<(unsigned)strlen(value); c++)
AddByte( value[c] );
}
void CPacket::SetByte( unsigned short pos, unsigned char value )
{
Buffer[pos] = value;
}
void CPacket::SetWord( unsigned short pos, unsigned short value )
{
*((unsigned short*)&Buffer[pos]) = value;
}
void CPacket::SetDWord( unsigned short pos, unsigned value )
{
*((unsigned*)&Buffer[pos]) = value;
}
void CPacket::SetQWord( unsigned short pos, unsigned long long value )
{
*((unsigned long long*)&Buffer[pos]) = value;
}
void CPacket::SetFloat( unsigned short pos, float value )
{
*((float*)&Buffer[pos]) = value;
}
unsigned char CPacket::GetByte( unsigned short pos )
{
return Buffer[pos];
}
unsigned short CPacket::GetWord( unsigned short pos )
{
return *((unsigned short*)&Buffer[pos]);
}
unsigned CPacket::GetDWord( unsigned short pos )
{
return *((unsigned*)&Buffer[pos]);
}
unsigned long long CPacket::GetQWord( unsigned short pos )
{
return *((unsigned long long*)&Buffer[pos]);
}
float CPacket::GetFloat( unsigned short pos )
{
return *((float*)&Buffer[pos]);
}
char* CPacket::GetString( unsigned short pos )
{
return (char*)&Buffer[pos];
}
+167
View File
@@ -0,0 +1,167 @@
#ifdef _WIN32
#include <conio.h>
#include <windows.h>
#include <cstdio>
#endif
#include <cstdio>
#include <string>
#include <time.h>
#include "log.h"
// Basic colors
typedef enum
{
BLACK,
BLUE,
GREEN,
CYAN,
RED,
MAGENTA,
BROWN,
LIGHTGRAY,
DARKGRAY,
LIGHTBLUE,
LIGHTGREEN,
LIGHTCYAN,
LIGHTRED,
LIGHTMAGENTA,
YELLOW,
WHITE
} COLORS;
// Our base colors
static int __BACKGROUND = BLACK;
static int __FOREGROUND = LIGHTGRAY;
// Change console text color
void textcolor(int color)
{
#ifdef _WIN32
__FOREGROUND = color;
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color + (__BACKGROUND << 4));
#else
#endif
}
// This function logs based on flags
void Log( enum msg_type flag, const char *Format, ... )
{
va_list ap; // For arguments
va_start( ap, Format );
// Timestamp
time_t rtime;
time (&rtime);
char timestamp[26];
ctime_s (timestamp, sizeof (timestamp), &rtime);
timestamp[strlen (timestamp) - 1] = ' ';
switch (flag) {
case MSG_NONE: // direct printf replacement
textcolor(WHITE);
vprintf( Format, ap );
break;
case MSG_STATUS:
textcolor(GREEN);
printf("[STATUS]: ");
break;
case MSG_SQL:
textcolor(CYAN);
printf("[SQL]: ");
break;
case MSG_INFO:
textcolor(LIGHTGREEN);
printf("[INFO]: ");
break;
case MSG_NOTICE:
textcolor(LIGHTCYAN);
printf("[NOTICE]: ");
break;
case MSG_WARNING:
textcolor(YELLOW);
printf("[WARNING]: ");
break;
case MSG_DEBUG:
textcolor(LIGHTBLUE);
printf("[DEBUG]: ");
break;
case MSG_ERROR:
textcolor(RED);
printf("[ERROR]: ");
break;
case MSG_FATALERROR:
textcolor(LIGHTRED);
printf("[FATAL ERROR]: ");
break;
case MSG_HACK:
textcolor(LIGHTRED);
printf("[HACK]: ");
break;
case MSG_LOAD:
textcolor(BROWN);
printf("[LOADING]: ");
break;
case MSG_GMACTION:
textcolor(MAGENTA);
printf("[GM ACTION]: ");
break;
case MSG_START:
textcolor(MAGENTA);
vprintf( Format, ap );
printf( "\r\n" );
break;
//case MSG_SDEBUG:
// textcolor(MAGENTA);
// printf("[SDEBUG]: ");
// break;
//case MSG_QUERY:
// textcolor(LIGHTBLUE);
// printf("[QUERY]: ");
// break;
//default:
// textcolor(MAGENTA);
// printf("[UNKNOWN CASE]: ");
// break;
}
textcolor(LIGHTGRAY);
if(flag!=MSG_QUERY)
{
printf( "%s- ", timestamp );
vprintf( Format, ap );
printf( (flag==MSG_LOAD) ? "\r" : "\n" );
}
FILE *fh = NULL;
switch(LOG_THISSERVER)
{
case LOG_LOGIN_SERVER:
fopen_s (&fh, LOG_DIRECTORY LOG_FILENAME_LOGINFILE, "a+");
break;
case LOG_CHARACTER_SERVER:
fopen_s (&fh, LOG_DIRECTORY LOG_FILENAME_CHARFILE, "a+");
break;
case LOG_WORLD_SERVER:
fopen_s (&fh, LOG_DIRECTORY LOG_FILENAME_WORLDFILE, "a+");
break;
case LOG_SAME_FILE:
fopen_s (&fh, LOG_DIRECTORY LOG_DEFAULT_FILE, "a+");
break;
default:
break;
}
if(flag == MSG_QUERY)
{
if(fh != NULL)
fclose(fh);
fopen_s (&fh, LOG_DIRECTORY "queries.txt", "a+");
}
if ( fh != NULL )
{
fprintf( fh, "%s- ", timestamp );
vfprintf( fh, Format, ap );
fputc( '\n', fh );
fclose( fh );
}
va_end ( ap );
}
+58
View File
@@ -0,0 +1,58 @@
/*
Open Source Rose Online Team - http://osroseon.to.md/
note: the Server is develop with erose source server + eich source
*/
#ifndef __ROSE_LOGGING_FUNCTIONS__
#define __ROSE_LOGGING_FUNCTIONS__
// Log path
#ifdef _WIN32
# define LOG_DIRECTORY "log/"
#endif
#ifdef __unix__
# define LOG_DIRECTORY "/var/log/roseserver/"
#endif
#define LOG_LOGIN_SERVER 0x01
#define LOG_CHARACTER_SERVER 0x02
#define LOG_WORLD_SERVER 0x03
#define LOG_SAME_FILE 0x04
// Log File names
extern unsigned char LOG_THISSERVER;
#define LOG_FILENAME_LOGINFILE "loginserver.log"
#define LOG_FILENAME_CHARFILE "charserver.log"
#define LOG_FILENAME_WORLDFILE "worldserver.log"
#define LOG_DEFAULT_FILE "server.log"
#define LOG_FILENAME_ERRORFILE "errors.log"
#define LOG_LOGINPACKETS "loginpacket.log"
#define LOG_CHARPACKETS "charpackets.log"
#define LOG_WORLDPACKETS "worldpackets.log"
#define LOG_DEFAULTPACKETS "packets.log"
// Error Types
enum msg_type {
MSG_NONE,
MSG_STATUS,
MSG_SQL,
MSG_INFO,
MSG_NOTICE,
MSG_WARNING,
MSG_DEBUG,
MSG_ERROR,
MSG_FATALERROR,
MSG_HACK,
MSG_LOAD,
MSG_SDEBUG,
MSG_GMACTION,
MSG_START,
MSG_QUERY,
MSG_QUESTDEBUG
};
// Logging function
void Log( msg_type flag, const char* Format, ... );
#endif
+739
View File
@@ -0,0 +1,739 @@
/* Copyright (C) 2000-2003 MySQL AB
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 2 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, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#ifndef _mysql_h
#define _mysql_h
#ifdef __CYGWIN__ /* CYGWIN implements a UNIX API */
#undef WIN
#undef _WIN
#undef _WIN32
#undef _WIN64
#undef __WIN__
#endif
#ifdef __cplusplus
extern "C" {
#endif
#ifndef _global_h /* If not standard header */
#include <sys/types.h>
#ifdef __LCC__
#include <winsock.h> /* For windows */
#endif
typedef char my_bool;
#if (defined(_WIN32) || defined(_WIN64)) && !defined(__WIN__)
#define __WIN__
#endif
#if !defined(__WIN__)
#define STDCALL
#else
#define STDCALL __stdcall
#endif
typedef char * gptr;
#ifndef my_socket_defined
#ifdef __WIN__
#define my_socket SOCKET
#else
typedef int my_socket;
#endif /* __WIN__ */
#endif /* my_socket_defined */
#endif /* _global_h */
#include "mysql_com.h"
#include "mysql_time.h"
#include "mysql_version.h"
#include "typelib.h"
#include "my_list.h" /* for LISTs used in 'MYSQL' and 'MYSQL_STMT' */
extern unsigned int mysql_port;
extern char *mysql_unix_port;
#define CLIENT_NET_READ_TIMEOUT 365*24*3600 /* Timeout on read */
#define CLIENT_NET_WRITE_TIMEOUT 365*24*3600 /* Timeout on write */
#ifdef __NETWARE__
#pragma pack(push, 8) /* 8 byte alignment */
#endif
#define IS_PRI_KEY(n) ((n) & PRI_KEY_FLAG)
#define IS_NOT_NULL(n) ((n) & NOT_NULL_FLAG)
#define IS_BLOB(n) ((n) & BLOB_FLAG)
#define IS_NUM(t) ((t) <= FIELD_TYPE_INT24 || (t) == FIELD_TYPE_YEAR)
#define IS_NUM_FIELD(f) ((f)->flags & NUM_FLAG)
#define INTERNAL_NUM_FIELD(f) (((f)->type <= FIELD_TYPE_INT24 && ((f)->type != FIELD_TYPE_TIMESTAMP || (f)->length == 14 || (f)->length == 8)) || (f)->type == FIELD_TYPE_YEAR)
typedef struct st_mysql_field {
char *name; /* Name of column */
char *org_name; /* Original column name, if an alias */
char *table; /* Table of column if column was a field */
char *org_table; /* Org table name, if table was an alias */
char *db; /* Database for table */
char *catalog; /* Catalog for table */
char *def; /* Default value (set by mysql_list_fields) */
unsigned long length; /* Width of column (create length) */
unsigned long max_length; /* Max width for selected set */
unsigned int name_length;
unsigned int org_name_length;
unsigned int table_length;
unsigned int org_table_length;
unsigned int db_length;
unsigned int catalog_length;
unsigned int def_length;
unsigned int flags; /* Div flags */
unsigned int decimals; /* Number of decimals in field */
unsigned int charsetnr; /* Character set */
enum enum_field_types type; /* Type of field. See mysql_com.h for types */
} MYSQL_FIELD;
typedef char **MYSQL_ROW; /* return data as array of strings */
typedef unsigned int MYSQL_FIELD_OFFSET; /* offset to current field */
#ifndef _global_h
#if defined(NO_CLIENT_LONG_LONG)
typedef unsigned long my_ulonglong;
#elif defined (__WIN__)
typedef unsigned __int64 my_ulonglong;
#else
typedef unsigned long long my_ulonglong;
#endif
#endif
#define MYSQL_COUNT_ERROR (~(my_ulonglong) 0)
typedef struct st_mysql_rows {
struct st_mysql_rows *next; /* list of rows */
MYSQL_ROW data;
unsigned long length;
} MYSQL_ROWS;
typedef MYSQL_ROWS *MYSQL_ROW_OFFSET; /* offset to current row */
#include "my_alloc.h"
typedef struct st_mysql_data {
my_ulonglong rows;
unsigned int fields;
MYSQL_ROWS *data;
MEM_ROOT alloc;
#if !defined(CHECK_EMBEDDED_DIFFERENCES) || defined(EMBEDDED_LIBRARY)
MYSQL_ROWS **prev_ptr;
#endif
} MYSQL_DATA;
enum mysql_option
{
MYSQL_OPT_CONNECT_TIMEOUT, MYSQL_OPT_COMPRESS, MYSQL_OPT_NAMED_PIPE,
MYSQL_INIT_COMMAND, MYSQL_READ_DEFAULT_FILE, MYSQL_READ_DEFAULT_GROUP,
MYSQL_SET_CHARSET_DIR, MYSQL_SET_CHARSET_NAME, MYSQL_OPT_LOCAL_INFILE,
MYSQL_OPT_PROTOCOL, MYSQL_SHARED_MEMORY_BASE_NAME, MYSQL_OPT_READ_TIMEOUT,
MYSQL_OPT_WRITE_TIMEOUT, MYSQL_OPT_USE_RESULT,
MYSQL_OPT_USE_REMOTE_CONNECTION, MYSQL_OPT_USE_EMBEDDED_CONNECTION,
MYSQL_OPT_GUESS_CONNECTION, MYSQL_SET_CLIENT_IP, MYSQL_SECURE_AUTH
};
struct st_mysql_options {
unsigned int connect_timeout, read_timeout, write_timeout;
unsigned int port, protocol;
unsigned long client_flag;
char *host,*user,*password,*unix_socket,*db;
struct st_dynamic_array *init_commands;
char *my_cnf_file,*my_cnf_group, *charset_dir, *charset_name;
char *ssl_key; /* PEM key file */
char *ssl_cert; /* PEM cert file */
char *ssl_ca; /* PEM CA file */
char *ssl_capath; /* PEM directory of CA-s? */
char *ssl_cipher; /* cipher to use */
char *shared_memory_base_name;
unsigned long max_allowed_packet;
my_bool use_ssl; /* if to use SSL or not */
my_bool compress,named_pipe;
/*
On connect, find out the replication role of the server, and
establish connections to all the peers
*/
my_bool rpl_probe;
/*
Each call to mysql_real_query() will parse it to tell if it is a read
or a write, and direct it to the slave or the master
*/
my_bool rpl_parse;
/*
If set, never read from a master, only from slave, when doing
a read that is replication-aware
*/
my_bool no_master_reads;
#if !defined(CHECK_EMBEDDED_DIFFERENCES) || defined(EMBEDDED_LIBRARY)
my_bool separate_thread;
#endif
enum mysql_option methods_to_use;
char *client_ip;
/* Refuse client connecting to server if it uses old (pre-4.1.1) protocol */
my_bool secure_auth;
/* function pointers for local infile support */
int (*local_infile_init)(void **, const char *, void *);
int (*local_infile_read)(void *, char *, unsigned int);
void (*local_infile_end)(void *);
int (*local_infile_error)(void *, char *, unsigned int);
void *local_infile_userdata;
};
enum mysql_status
{
MYSQL_STATUS_READY,MYSQL_STATUS_GET_RESULT,MYSQL_STATUS_USE_RESULT
};
enum mysql_protocol_type
{
MYSQL_PROTOCOL_DEFAULT, MYSQL_PROTOCOL_TCP, MYSQL_PROTOCOL_SOCKET,
MYSQL_PROTOCOL_PIPE, MYSQL_PROTOCOL_MEMORY
};
/*
There are three types of queries - the ones that have to go to
the master, the ones that go to a slave, and the adminstrative
type which must happen on the pivot connectioin
*/
enum mysql_rpl_type
{
MYSQL_RPL_MASTER, MYSQL_RPL_SLAVE, MYSQL_RPL_ADMIN
};
struct st_mysql_methods;
typedef struct st_mysql
{
NET net; /* Communication parameters */
gptr connector_fd; /* ConnectorFd for SSL */
char *host,*user,*passwd,*unix_socket,*server_version,*host_info,*info;
char *db;
struct charset_info_st *charset;
MYSQL_FIELD *fields;
MEM_ROOT field_alloc;
my_ulonglong affected_rows;
my_ulonglong insert_id; /* id if insert on table with NEXTNR */
my_ulonglong extra_info; /* Used by mysqlshow */
unsigned long thread_id; /* Id for connection in server */
unsigned long packet_length;
unsigned int port;
unsigned long client_flag,server_capabilities;
unsigned int protocol_version;
unsigned int field_count;
unsigned int server_status;
unsigned int server_language;
unsigned int warning_count;
struct st_mysql_options options;
enum mysql_status status;
my_bool free_me; /* If free in mysql_close */
my_bool reconnect; /* set to 1 if automatic reconnect */
/* session-wide random string */
char scramble[SCRAMBLE_LENGTH+1];
/*
Set if this is the original connection, not a master or a slave we have
added though mysql_rpl_probe() or mysql_set_master()/ mysql_add_slave()
*/
my_bool rpl_pivot;
/*
Pointers to the master, and the next slave connections, points to
itself if lone connection.
*/
struct st_mysql* master, *next_slave;
struct st_mysql* last_used_slave; /* needed for round-robin slave pick */
/* needed for send/read/store/use result to work correctly with replication */
struct st_mysql* last_used_con;
LIST *stmts; /* list of all statements */
const struct st_mysql_methods *methods;
void *thd;
/*
Points to boolean flag in MYSQL_RES or MYSQL_STMT. We set this flag
from mysql_stmt_close if close had to cancel result set of this object.
*/
my_bool *unbuffered_fetch_owner;
} MYSQL;
typedef struct st_mysql_res {
my_ulonglong row_count;
MYSQL_FIELD *fields;
MYSQL_DATA *data;
MYSQL_ROWS *data_cursor;
unsigned long *lengths; /* column lengths of current row */
MYSQL *handle; /* for unbuffered reads */
MEM_ROOT field_alloc;
unsigned int field_count, current_field;
MYSQL_ROW row; /* If unbuffered read */
MYSQL_ROW current_row; /* buffer to current row */
my_bool eof; /* Used by mysql_fetch_row */
/* mysql_stmt_close() had to cancel this result */
my_bool unbuffered_fetch_cancelled;
const struct st_mysql_methods *methods;
} MYSQL_RES;
#define MAX_MYSQL_MANAGER_ERR 256
#define MAX_MYSQL_MANAGER_MSG 256
#define MANAGER_OK 200
#define MANAGER_INFO 250
#define MANAGER_ACCESS 401
#define MANAGER_CLIENT_ERR 450
#define MANAGER_INTERNAL_ERR 500
#if !defined(MYSQL_SERVER) && !defined(MYSQL_CLIENT)
#define MYSQL_CLIENT
#endif
typedef struct st_mysql_manager
{
NET net;
char *host,*user,*passwd;
unsigned int port;
my_bool free_me;
my_bool eof;
int cmd_status;
int last_errno;
char* net_buf,*net_buf_pos,*net_data_end;
int net_buf_size;
char last_error[MAX_MYSQL_MANAGER_ERR];
} MYSQL_MANAGER;
typedef struct st_mysql_parameters
{
unsigned long *p_max_allowed_packet;
unsigned long *p_net_buffer_length;
} MYSQL_PARAMETERS;
#if !defined(MYSQL_SERVER) && !defined(EMBEDDED_LIBRARY)
#define max_allowed_packet (*mysql_get_parameters()->p_max_allowed_packet)
#define net_buffer_length (*mysql_get_parameters()->p_net_buffer_length)
#endif
/*
Set up and bring down the server; to ensure that applications will
work when linked against either the standard client library or the
embedded server library, these functions should be called.
*/
int STDCALL mysql_server_init(int argc, char **argv, char **groups);
void STDCALL mysql_server_end(void);
/*
mysql_server_init/end need to be called when using libmysqld or
libmysqlclient (exactly, mysql_server_init() is called by mysql_init() so
you don't need to call it explicitely; but you need to call
mysql_server_end() to free memory). The names are a bit misleading
(mysql_SERVER* to be used when using libmysqlCLIENT). So we add more general
names which suit well whether you're using libmysqld or libmysqlclient. We
intend to promote these aliases over the mysql_server* ones.
*/
#define mysql_library_init mysql_server_init
#define mysql_library_end mysql_server_end
MYSQL_PARAMETERS *STDCALL mysql_get_parameters(void);
/*
Set up and bring down a thread; these function should be called
for each thread in an application which opens at least one MySQL
connection. All uses of the connection(s) should be between these
function calls.
*/
my_bool STDCALL mysql_thread_init(void);
void STDCALL mysql_thread_end(void);
/*
Functions to get information from the MYSQL and MYSQL_RES structures
Should definitely be used if one uses shared libraries.
*/
my_ulonglong STDCALL mysql_num_rows(MYSQL_RES *res);
unsigned int STDCALL mysql_num_fields(MYSQL_RES *res);
my_bool STDCALL mysql_eof(MYSQL_RES *res);
MYSQL_FIELD *STDCALL mysql_fetch_field_direct(MYSQL_RES *res,
unsigned int fieldnr);
MYSQL_FIELD * STDCALL mysql_fetch_fields(MYSQL_RES *res);
MYSQL_ROW_OFFSET STDCALL mysql_row_tell(MYSQL_RES *res);
MYSQL_FIELD_OFFSET STDCALL mysql_field_tell(MYSQL_RES *res);
unsigned int STDCALL mysql_field_count(MYSQL *mysql);
my_ulonglong STDCALL mysql_affected_rows(MYSQL *mysql);
my_ulonglong STDCALL mysql_insert_id(MYSQL *mysql);
unsigned int STDCALL mysql_errno(MYSQL *mysql);
const char * STDCALL mysql_error(MYSQL *mysql);
const char *STDCALL mysql_sqlstate(MYSQL *mysql);
unsigned int STDCALL mysql_warning_count(MYSQL *mysql);
const char * STDCALL mysql_info(MYSQL *mysql);
unsigned long STDCALL mysql_thread_id(MYSQL *mysql);
const char * STDCALL mysql_character_set_name(MYSQL *mysql);
int STDCALL mysql_set_character_set(MYSQL *mysql, char *csname);
MYSQL * STDCALL mysql_init(MYSQL *mysql);
my_bool STDCALL mysql_ssl_set(MYSQL *mysql, const char *key,
const char *cert, const char *ca,
const char *capath, const char *cipher);
my_bool STDCALL mysql_change_user(MYSQL *mysql, const char *user,
const char *passwd, const char *db);
MYSQL * STDCALL mysql_real_connect(MYSQL *mysql, const char *host,
const char *user,
const char *passwd,
const char *db,
unsigned int port,
const char *unix_socket,
unsigned long clientflag);
int STDCALL mysql_select_db(MYSQL *mysql, const char *db);
int STDCALL mysql_query(MYSQL *mysql, const char *q);
int STDCALL mysql_send_query(MYSQL *mysql, const char *q,
unsigned long length);
int STDCALL mysql_real_query(MYSQL *mysql, const char *q,
unsigned long length);
MYSQL_RES * STDCALL mysql_store_result(MYSQL *mysql);
MYSQL_RES * STDCALL mysql_use_result(MYSQL *mysql);
/* perform query on master */
my_bool STDCALL mysql_master_query(MYSQL *mysql, const char *q,
unsigned long length);
my_bool STDCALL mysql_master_send_query(MYSQL *mysql, const char *q,
unsigned long length);
/* perform query on slave */
my_bool STDCALL mysql_slave_query(MYSQL *mysql, const char *q,
unsigned long length);
my_bool STDCALL mysql_slave_send_query(MYSQL *mysql, const char *q,
unsigned long length);
/* local infile support */
#define LOCAL_INFILE_ERROR_LEN 512
void
mysql_set_local_infile_handler(MYSQL *mysql,
int (*local_infile_init)(void **, const char *,
void *),
int (*local_infile_read)(void *, char *,
unsigned int),
void (*local_infile_end)(void *),
int (*local_infile_error)(void *, char*,
unsigned int),
void *);
void
mysql_set_local_infile_default(MYSQL *mysql);
/*
enable/disable parsing of all queries to decide if they go on master or
slave
*/
void STDCALL mysql_enable_rpl_parse(MYSQL* mysql);
void STDCALL mysql_disable_rpl_parse(MYSQL* mysql);
/* get the value of the parse flag */
int STDCALL mysql_rpl_parse_enabled(MYSQL* mysql);
/* enable/disable reads from master */
void STDCALL mysql_enable_reads_from_master(MYSQL* mysql);
void STDCALL mysql_disable_reads_from_master(MYSQL* mysql);
/* get the value of the master read flag */
my_bool STDCALL mysql_reads_from_master_enabled(MYSQL* mysql);
enum mysql_rpl_type STDCALL mysql_rpl_query_type(const char* q, int len);
/* discover the master and its slaves */
my_bool STDCALL mysql_rpl_probe(MYSQL* mysql);
/* set the master, close/free the old one, if it is not a pivot */
int STDCALL mysql_set_master(MYSQL* mysql, const char* host,
unsigned int port,
const char* user,
const char* passwd);
int STDCALL mysql_add_slave(MYSQL* mysql, const char* host,
unsigned int port,
const char* user,
const char* passwd);
int STDCALL mysql_shutdown(MYSQL *mysql,
enum mysql_enum_shutdown_level
shutdown_level);
int STDCALL mysql_dump_debug_info(MYSQL *mysql);
int STDCALL mysql_refresh(MYSQL *mysql,
unsigned int refresh_options);
int STDCALL mysql_kill(MYSQL *mysql,unsigned long pid);
int STDCALL mysql_set_server_option(MYSQL *mysql,
enum enum_mysql_set_option
option);
int STDCALL mysql_ping(MYSQL *mysql);
const char * STDCALL mysql_stat(MYSQL *mysql);
const char * STDCALL mysql_get_server_info(MYSQL *mysql);
const char * STDCALL mysql_get_client_info(void);
unsigned long STDCALL mysql_get_client_version(void);
const char * STDCALL mysql_get_host_info(MYSQL *mysql);
unsigned long STDCALL mysql_get_server_version(MYSQL *mysql);
unsigned int STDCALL mysql_get_proto_info(MYSQL *mysql);
MYSQL_RES * STDCALL mysql_list_dbs(MYSQL *mysql,const char *wild);
MYSQL_RES * STDCALL mysql_list_tables(MYSQL *mysql,const char *wild);
MYSQL_RES * STDCALL mysql_list_processes(MYSQL *mysql);
int STDCALL mysql_options(MYSQL *mysql,enum mysql_option option,
const char *arg);
void STDCALL mysql_free_result(MYSQL_RES *result);
void STDCALL mysql_data_seek(MYSQL_RES *result,
my_ulonglong offset);
MYSQL_ROW_OFFSET STDCALL mysql_row_seek(MYSQL_RES *result,
MYSQL_ROW_OFFSET offset);
MYSQL_FIELD_OFFSET STDCALL mysql_field_seek(MYSQL_RES *result,
MYSQL_FIELD_OFFSET offset);
MYSQL_ROW STDCALL mysql_fetch_row(MYSQL_RES *result);
unsigned long * STDCALL mysql_fetch_lengths(MYSQL_RES *result);
MYSQL_FIELD * STDCALL mysql_fetch_field(MYSQL_RES *result);
MYSQL_RES * STDCALL mysql_list_fields(MYSQL *mysql, const char *table,
const char *wild);
unsigned long STDCALL mysql_escape_string(char *to,const char *from,
unsigned long from_length);
unsigned long STDCALL mysql_hex_string(char *to,const char *from,
unsigned long from_length);
unsigned long STDCALL mysql_real_escape_string(MYSQL *mysql,
char *to,const char *from,
unsigned long length);
void STDCALL mysql_debug(const char *debug);
char * STDCALL mysql_odbc_escape_string(MYSQL *mysql,
char *to,
unsigned long to_length,
const char *from,
unsigned long from_length,
void *param,
char *
(*extend_buffer)
(void *, char *to,
unsigned long *length));
void STDCALL myodbc_remove_escape(MYSQL *mysql,char *name);
unsigned int STDCALL mysql_thread_safe(void);
my_bool STDCALL mysql_embedded(void);
MYSQL_MANAGER* STDCALL mysql_manager_init(MYSQL_MANAGER* con);
MYSQL_MANAGER* STDCALL mysql_manager_connect(MYSQL_MANAGER* con,
const char* host,
const char* user,
const char* passwd,
unsigned int port);
void STDCALL mysql_manager_close(MYSQL_MANAGER* con);
int STDCALL mysql_manager_command(MYSQL_MANAGER* con,
const char* cmd, int cmd_len);
int STDCALL mysql_manager_fetch_line(MYSQL_MANAGER* con,
char* res_buf,
int res_buf_size);
my_bool STDCALL mysql_read_query_result(MYSQL *mysql);
/*
The following definitions are added for the enhanced
client-server protocol
*/
/* statement state */
enum enum_mysql_stmt_state
{
MYSQL_STMT_INIT_DONE= 1, MYSQL_STMT_PREPARE_DONE, MYSQL_STMT_EXECUTE_DONE,
MYSQL_STMT_FETCH_DONE
};
/* bind structure */
typedef struct st_mysql_bind
{
unsigned long *length; /* output length pointer */
my_bool *is_null; /* Pointer to null indicator */
void *buffer; /* buffer to get/put data */
enum enum_field_types buffer_type; /* buffer type */
unsigned long buffer_length; /* buffer length, must be set for str/binary */
/* Following are for internal use. Set by mysql_stmt_bind_param */
unsigned char *inter_buffer; /* for the current data position */
unsigned long offset; /* offset position for char/binary fetch */
unsigned long internal_length; /* Used if length is 0 */
unsigned int param_number; /* For null count and error messages */
unsigned int pack_length; /* Internal length for packed data */
my_bool is_unsigned; /* set if integer type is unsigned */
my_bool long_data_used; /* If used with mysql_send_long_data */
my_bool internal_is_null; /* Used if is_null is 0 */
void (*store_param_func)(NET *net, struct st_mysql_bind *param);
void (*fetch_result)(struct st_mysql_bind *, unsigned char **row);
void (*skip_result)(struct st_mysql_bind *, MYSQL_FIELD *,
unsigned char **row);
} MYSQL_BIND;
/* statement handler */
typedef struct st_mysql_stmt
{
MEM_ROOT mem_root; /* root allocations */
LIST list; /* list to keep track of all stmts */
MYSQL *mysql; /* connection handle */
MYSQL_BIND *params; /* input parameters */
MYSQL_BIND *bind; /* output parameters */
MYSQL_FIELD *fields; /* result set metadata */
MYSQL_DATA result; /* cached result set */
MYSQL_ROWS *data_cursor; /* current row in cached result */
/* copy of mysql->affected_rows after statement execution */
my_ulonglong affected_rows;
my_ulonglong insert_id; /* copy of mysql->insert_id */
/*
mysql_stmt_fetch() calls this function to fetch one row (it's different
for buffered, unbuffered and cursor fetch).
*/
int (*read_row_func)(struct st_mysql_stmt *stmt,
unsigned char **row);
unsigned long stmt_id; /* Id for prepared statement */
unsigned int last_errno; /* error code */
unsigned int param_count; /* input parameter count */
unsigned int field_count; /* number of columns in result set */
enum enum_mysql_stmt_state state; /* statement state */
char last_error[MYSQL_ERRMSG_SIZE]; /* error message */
char sqlstate[SQLSTATE_LENGTH+1];
/* Types of input parameters should be sent to server */
my_bool send_types_to_server;
my_bool bind_param_done; /* input buffers were supplied */
my_bool bind_result_done; /* output buffers were supplied */
/* mysql_stmt_close() had to cancel this result */
my_bool unbuffered_fetch_cancelled;
/*
Is set to true if we need to calculate field->max_length for
metadata fields when doing mysql_stmt_store_result.
*/
my_bool update_max_length;
} MYSQL_STMT;
enum enum_stmt_attr_type
{
/*
When doing mysql_stmt_store_result calculate max_length attribute
of statement metadata. This is to be consistent with the old API,
where this was done automatically.
In the new API we do that only by request because it slows down
mysql_stmt_store_result sufficiently.
*/
STMT_ATTR_UPDATE_MAX_LENGTH
};
typedef struct st_mysql_methods
{
my_bool (*read_query_result)(MYSQL *mysql);
my_bool (*advanced_command)(MYSQL *mysql,
enum enum_server_command command,
const char *header,
unsigned long header_length,
const char *arg,
unsigned long arg_length,
my_bool skip_check);
MYSQL_DATA *(*read_rows)(MYSQL *mysql,MYSQL_FIELD *mysql_fields,
unsigned int fields);
MYSQL_RES * (*use_result)(MYSQL *mysql);
void (*fetch_lengths)(unsigned long *to,
MYSQL_ROW column, unsigned int field_count);
void (*flush_use_result)(MYSQL *mysql);
#if !defined(MYSQL_SERVER) || defined(EMBEDDED_LIBRARY)
MYSQL_FIELD * (*list_fields)(MYSQL *mysql);
my_bool (*read_prepare_result)(MYSQL *mysql, MYSQL_STMT *stmt);
int (*stmt_execute)(MYSQL_STMT *stmt);
int (*read_binary_rows)(MYSQL_STMT *stmt);
int (*unbuffered_fetch)(MYSQL *mysql, char **row);
void (*free_embedded_thd)(MYSQL *mysql);
const char *(*read_statistics)(MYSQL *mysql);
my_bool (*next_result)(MYSQL *mysql);
int (*read_change_user_result)(MYSQL *mysql, char *buff, const char *passwd);
#endif
} MYSQL_METHODS;
MYSQL_STMT * STDCALL mysql_stmt_init(MYSQL *mysql);
int STDCALL mysql_stmt_prepare(MYSQL_STMT *stmt, const char *query,
unsigned long length);
int STDCALL mysql_stmt_execute(MYSQL_STMT *stmt);
int STDCALL mysql_stmt_fetch(MYSQL_STMT *stmt);
int STDCALL mysql_stmt_fetch_column(MYSQL_STMT *stmt, MYSQL_BIND *bind,
unsigned int column,
unsigned long offset);
int STDCALL mysql_stmt_store_result(MYSQL_STMT *stmt);
unsigned long STDCALL mysql_stmt_param_count(MYSQL_STMT * stmt);
my_bool STDCALL mysql_stmt_attr_set(MYSQL_STMT *stmt,
enum enum_stmt_attr_type attr_type,
const void *attr);
my_bool STDCALL mysql_stmt_attr_get(MYSQL_STMT *stmt,
enum enum_stmt_attr_type attr_type,
void *attr);
my_bool STDCALL mysql_stmt_bind_param(MYSQL_STMT * stmt, MYSQL_BIND * bnd);
my_bool STDCALL mysql_stmt_bind_result(MYSQL_STMT * stmt, MYSQL_BIND * bnd);
my_bool STDCALL mysql_stmt_close(MYSQL_STMT * stmt);
my_bool STDCALL mysql_stmt_reset(MYSQL_STMT * stmt);
my_bool STDCALL mysql_stmt_free_result(MYSQL_STMT *stmt);
my_bool STDCALL mysql_stmt_send_long_data(MYSQL_STMT *stmt,
unsigned int param_number,
const char *data,
unsigned long length);
MYSQL_RES *STDCALL mysql_stmt_result_metadata(MYSQL_STMT *stmt);
MYSQL_RES *STDCALL mysql_stmt_param_metadata(MYSQL_STMT *stmt);
unsigned int STDCALL mysql_stmt_errno(MYSQL_STMT * stmt);
const char *STDCALL mysql_stmt_error(MYSQL_STMT * stmt);
const char *STDCALL mysql_stmt_sqlstate(MYSQL_STMT * stmt);
MYSQL_ROW_OFFSET STDCALL mysql_stmt_row_seek(MYSQL_STMT *stmt,
MYSQL_ROW_OFFSET offset);
MYSQL_ROW_OFFSET STDCALL mysql_stmt_row_tell(MYSQL_STMT *stmt);
void STDCALL mysql_stmt_data_seek(MYSQL_STMT *stmt, my_ulonglong offset);
my_ulonglong STDCALL mysql_stmt_num_rows(MYSQL_STMT *stmt);
my_ulonglong STDCALL mysql_stmt_affected_rows(MYSQL_STMT *stmt);
my_ulonglong STDCALL mysql_stmt_insert_id(MYSQL_STMT *stmt);
unsigned int STDCALL mysql_stmt_field_count(MYSQL_STMT *stmt);
my_bool STDCALL mysql_commit(MYSQL * mysql);
my_bool STDCALL mysql_rollback(MYSQL * mysql);
my_bool STDCALL mysql_autocommit(MYSQL * mysql, my_bool auto_mode);
my_bool STDCALL mysql_more_results(MYSQL *mysql);
int STDCALL mysql_next_result(MYSQL *mysql);
void STDCALL mysql_close(MYSQL *sock);
/* status return codes */
#define MYSQL_NO_DATA 100
#define mysql_reload(mysql) mysql_refresh((mysql),REFRESH_GRANT)
#ifdef USE_OLD_FUNCTIONS
MYSQL * STDCALL mysql_connect(MYSQL *mysql, const char *host,
const char *user, const char *passwd);
int STDCALL mysql_create_db(MYSQL *mysql, const char *DB);
int STDCALL mysql_drop_db(MYSQL *mysql, const char *DB);
#define mysql_reload(mysql) mysql_refresh((mysql),REFRESH_GRANT)
#endif
#define HAVE_MYSQL_REAL_CONNECT
/*
The following functions are mainly exported because of mysqlbinlog;
They are not for general usage
*/
#define simple_command(mysql, command, arg, length, skip_check) \
(*(mysql)->methods->advanced_command)(mysql, command, \
NullS, 0, arg, length, skip_check)
unsigned long net_safe_read(MYSQL* mysql);
#ifdef __NETWARE__
#pragma pack(pop) /* restore alignment */
#endif
#ifdef __cplusplus
}
#endif
#endif /* _mysql_h */
+530
View File
@@ -0,0 +1,530 @@
#include <fstream>
#include <iostream>
#include "rosecrypt.hpp"
#include <cstdlib>
#define LOGINSERVER_CRYPTTABLE_START_VALUE 0x0042D266
//-------------------------------------------------------------------------
// This structure saves values while the tables are generated
//-------------------------------------------------------------------------
struct CCryptTableControlStruct
{
unsigned CountTableMod[4];
unsigned char CurTableMod ;
unsigned ValueTableMod[4];
};
//------------------------------------------------------------------------
// This structure is used by the encryption routines
//-------------------------------------------------------------------------
typedef unsigned long long int u64;
struct CCryptBuffer
{
u64 AddBufferLen : 11;
u64 Command : 11;
u64 AddTableValue : 11;
u64 EncryptAddValue : 4;
u64 EncryptValue : 3;
};
//-------------------------------------------------------------------------
// This table is used to calculate a checksum (size of 256 bytes)
//-------------------------------------------------------------------------
const unsigned char CheckSumTable[] =
"\x00\x5E\xBC\xE2\x61\x3F\xDD\x83\xC2\x9C\x7E\x20\xA3\xFD\x1F\x41"
"\x9D\xC3\x21\x7F\xFC\xA2\x40\x1E\x5F\x01\xE3\xBD\x3E\x60\x82\xDC"
"\x23\x7D\x9F\xC1\x42\x1C\xFE\xA0\xE1\xBF\x5D\x03\x80\xDE\x3C\x62"
"\xBE\xE0\x02\x5C\xDF\x81\x63\x3D\x7C\x22\xC0\x9E\x1D\x43\xA1\xFF"
"\x46\x18\xFA\xA4\x27\x79\x9B\xC5\x84\xDA\x38\x66\xE5\xBB\x59\x07"
"\xDB\x85\x67\x39\xBA\xE4\x06\x58\x19\x47\xA5\xFB\x78\x26\xC4\x9A"
"\x65\x3B\xD9\x87\x04\x5A\xB8\xE6\xA7\xF9\x1B\x45\xC6\x98\x7A\x24"
"\xF8\xA6\x44\x1A\x99\xC7\x25\x7B\x3A\x64\x86\xD8\x5B\x05\xE7\xB9"
"\x8C\xD2\x30\x6E\xED\xB3\x51\x0F\x4E\x10\xF2\xAC\x2F\x71\x93\xCD"
"\x11\x4F\xAD\xF3\x70\x2E\xCC\x92\xD3\x8D\x6F\x31\xB2\xEC\x0E\x50"
"\xAF\xF1\x13\x4D\xCE\x90\x72\x2C\x6D\x33\xD1\x8F\x0C\x52\xB0\xEE"
"\x32\x6C\x8E\xD0\x53\x0D\xEF\xB1\xF0\xAE\x4C\x12\x91\xCF\x2D\x73"
"\xCA\x94\x76\x28\xAB\xF5\x17\x49\x08\x56\xB4\xEA\x69\x37\xD5\x8B"
"\x57\x09\xEB\xB5\x36\x68\x8A\xD4\x95\xCB\x29\x77\xF4\xAA\x48\x16"
"\xE9\xB7\x55\x0B\x88\xD6\x34\x6A\x2B\x75\x97\xC9\x4A\x14\xF6\xA8"
"\x74\x2A\xC8\x96\x15\x4B\xA9\xF7\xB6\xE8\x0A\x54\xD7\x89\x6B\x35";
//----------------------------------------------------------------------------
// Private function, that generates the next value for the tables
//----------------------------------------------------------------------------
unsigned ctGenerateNextValue( CCryptTable *CryptTables, CCryptTableControlStruct *ControlStruct )
{
// Get the last value depending on the current TableMod.
int Value = ControlStruct->ValueTableMod[ ControlStruct->CurTableMod ];
// Update generatecount, depending on the current TableMod
ControlStruct->CountTableMod [ ControlStruct->CurTableMod ];
// Calculate and return the next value
switch ( ControlStruct->CurTableMod )
{
case 0:
Value = (int(Value * 0x8088405)) + 1;
ControlStruct->ValueTableMod[ 0 ] = Value;
return int(Value + (Value<0?0xFFFF:0)) >> 0x10;
case 1:
Value = (0x3039 - (int(Value * 0x3E39B193))) & 0x7FFFFFFF;
ControlStruct->ValueTableMod[ 1 ] = Value;
return Value;
case 2:
Value = (int(Value * 0x41C64E6D) + 0x3039);
ControlStruct->ValueTableMod[ 2 ] = Value;
return int(Value + (Value<0?0xFFFF:0)) >> 0x10;
case 3:
Value = (int(Value * 0x343FD) + 0x269EC3) & 0x7FFFFFFF;
ControlStruct->ValueTableMod[ 3 ] = Value;
return int(Value + (Value<0?0xFFFF:0)) >> 0x10;
default:
return 0;
}
return 0;
}
//-------------------------------------------------------------------------
// Private functions, that searches a value in an existing table to
// check if this value already exists.
//-------------------------------------------------------------------------
bool ctValueExistsInTable( CCryptTable *CryptTables, unsigned char Table, unsigned Value, unsigned short EntryCount )
{
for ( unsigned short i=0; i<EntryCount; ++i )
if ( (unsigned)CryptTables->Tables[ Table ][ i ] == Value ) return true;
return false;
}
//-------------------------------------------------------------------------
// This function generates a new crypt table depending on the ModValue
// parameter.
//-------------------------------------------------------------------------
void GenerateCryptTables( CCryptTable* &CryptTables, unsigned ModValue )
{
CCryptTableControlStruct ControlStruct;
unsigned char TableFuncList[ 17 ];
unsigned char table;
unsigned short entry;
unsigned value;
int ivalue;
// Allocate memory for structure
CryptTables = (CCryptTable*)malloc( sizeof( CCryptTable ) );
CryptTables->Tables = (unsigned **)calloc( 16, sizeof( unsigned ) );
// Prepare values
ModValue = (int(ModValue * 0x41C64E6D) + 0x3039);
ModValue = int(ModValue + ((int)ModValue<0?0xFFFF:0)) >> 0x10;
// Startvalue for checksum variable for each user
CryptTables->EncryptionStartValue = ModValue;
// set startvalues
for ( table=0; table<4; ++table )
{
ControlStruct.CountTableMod[ table ] = 0;
ControlStruct.ValueTableMod[ table ] = ModValue;
}
// Generate TableMod list for creation
ControlStruct.CurTableMod = 0;
for ( table=0; table<0x11; ++table )
{
ivalue = ctGenerateNextValue( CryptTables, &ControlStruct ) & 0x80000003;
if ( ivalue<0 ) ivalue = ( ( ivalue - 1 ) | 0xFFFFFFFC ) + 1;
TableFuncList[ table ] = ( unsigned char )ivalue;
}
// Create tables
for ( table=0; table<16; ++table )
{
// Prepare creation loop for current table
CryptTables->Tables[ table ] = (unsigned*)calloc( 0x800, sizeof( unsigned ) );
ControlStruct.CurTableMod = TableFuncList[ table ] & 3;
// Generate current table
entry = 0;
do
{
// Generate next value
value = ctGenerateNextValue( CryptTables, &ControlStruct );
// Check, if value already exist in table 0
if ( ctValueExistsInTable( CryptTables, 0, value, entry ) ) continue;
// Save value to memory
CryptTables->Tables[ table ][ entry ] = value;
++entry;
} while ( entry<0x800 );
}
// Generate additional table
CryptTables->AddTable = (unsigned short*)calloc( 0x200, sizeof( unsigned short ) );
ControlStruct.CurTableMod = table = (unsigned char)(TableFuncList[ 0x10 ]) & 3;
entry = 0;
do
{
// Generate next value
value = ctGenerateNextValue( CryptTables, &ControlStruct ) & 0x7FF;
// Check, if value already exist
for ( ivalue=0; ivalue<=(int)entry; ++ivalue )
if ( (unsigned)CryptTables->AddTable[ivalue] == value ) { value=0xFFFFFFFF; break; }
// If value exist, continue
if ( value==0xFFFFFFFF ) continue;
// Save value
CryptTables->AddTable[ entry++ ] = value;
} while ( entry<0x200 );
}
//-------------------------------------------------------------------------
// This function generates a new crypt table used by the Login Server
//-------------------------------------------------------------------------
void GenerateLoginServerCryptTables( CCryptTable* &CryptTables )
{
CCryptTableControlStruct ControlStruct;
unsigned char table;
unsigned short entry;
unsigned value;
int ivalue;
// Allocate memory for structure
CryptTables = (CCryptTable*)malloc( sizeof( CCryptTable ) );
CryptTables->Tables = (unsigned **)calloc( 16, sizeof( unsigned ) );
// Set default startvalues
for ( table=0; table<4; ++table )
{
ControlStruct.CountTableMod[ table ] = 0;
ControlStruct.ValueTableMod[ table ] = LOGINSERVER_CRYPTTABLE_START_VALUE;
}
// Another startvalue
CryptTables->EncryptionStartValue = LOGINSERVER_CRYPTTABLE_START_VALUE;
// Generate default tables
for ( table=0; table<16; ++table )
{
// Prepare creation loop for current table
ControlStruct.CurTableMod = table & 3;
CryptTables->Tables[ table ] = (unsigned*)calloc( 0x800, sizeof( unsigned ) );
entry = 0;
do
{
// Generate next value depend on CurTableMod
value = ctGenerateNextValue( CryptTables, &ControlStruct );
// Only take value, if it doesn't exist in table 0 already
if ( ctValueExistsInTable( CryptTables, 0, value, entry ) ) continue;
// Save value to structure
CryptTables->Tables[ table ][ entry ] = value;
++entry;
} while ( entry<0x800 );
}
// Create additional table
CryptTables->AddTable = (unsigned short*)calloc( 0x200, sizeof( unsigned short ) );
entry = 0;
do
{
// Generate next value for table
ControlStruct.CountTableMod[1];
ivalue = ControlStruct.ValueTableMod[1];
ivalue *= 0x3E39B193;
value = (0x3039 - (unsigned)ivalue) & 0x7FFFFFFF;
ControlStruct.ValueTableMod[1] = value;
// Don't save, if value already exist
value &= 0x7FF;
for ( ivalue=0; ivalue<=(int)entry; ++ivalue )
if ( (unsigned)CryptTables->AddTable[ivalue] == value ) { value=0xFFFFFFFF; break; }
// If value already exist, continue
if ( value==0xFFFFFFFF ) continue;
// Save value to structure
CryptTables->AddTable[ entry ] = value;
++entry;
} while ( entry<0x200 );
}
//-------------------------------------------------------------------------
// This function frees the memory of a crypt table
//-------------------------------------------------------------------------
void FreeCryptTables( CCryptTable* &CryptTables )
{
unsigned char c;
// Free every table
for ( c=0; c<16; ++c )
free( CryptTables->Tables[ c ] );
// Free memory
free( CryptTables->AddTable );
free( CryptTables->Tables );
free( CryptTables );
CryptTables = NULL;
}
//-------------------------------------------------------------------------
// This function decrypts a received 6-byte buffer and returns the full
// size of the incoming packet (including this 6-byte header).
// If the buffer is incorrect, this function returns a zero.
//-------------------------------------------------------------------------
int DecryptBufferHeader( CCryptStatus *ri, CCryptTable *CryptTables, unsigned char *Buffer )
{
CCryptBuffer TempBuffer;
unsigned BigBuffer;
unsigned char c;
// Read "AddTableValue" from buffer
BigBuffer = *((unsigned*)Buffer);
TempBuffer.AddTableValue = ( ( Buffer[4] >> 0x03 ) & 0x0007 ) | ( ( BigBuffer ) & 0x0038 ) | \
( ( BigBuffer >> 0x03 ) & 0x01C0 ) | ( ( BigBuffer >> 0x11 ) & 0x0600 );
// Decrypt header in the buffer
for ( c=0; c<5; ++c )
Buffer[c] ^= CryptTables->Tables[ c ][ TempBuffer.AddTableValue ];
BigBuffer = *((unsigned*)Buffer);
TempBuffer.EncryptValue = ( BigBuffer >> 0x0F ) & 0x0007 ;
TempBuffer.Command = ( ( BigBuffer >> 0x0C ) & 0x0007 ) | ( ( BigBuffer << 0x03 ) & 0x0038 ) | \
( ( Buffer[4] << 0x06 ) & 0x01C0 ) | ( ( BigBuffer >> 0x13 ) & 0x0600 );
TempBuffer.AddBufferLen = ( ( BigBuffer >> 0x06 ) & 0x0007 ) | ( ( BigBuffer >> 0x0F ) & 0x0038 ) | \
( ( BigBuffer >> 0x11 ) & 0x01C0 ) | ( ( Buffer[4] << 0x03 ) & 0x0600 );
TempBuffer.EncryptAddValue = ( ( BigBuffer >> 0x1E ) & 0x0003 ) | ( ( BigBuffer >> 0x13 ) & 0x000C );
// Size correct?
if ( TempBuffer.AddBufferLen < 0x06 || TempBuffer.AddBufferLen > 0x400 )
return 0;
// Header Checksum correct? ~ not implented yet ~
/*
if ( ((unsigned)( TempBuffer.AddTableValue + TempBuffer.EncryptAddValue ) & 7 ) != \
((unsigned)( TempBuffer.EncryptValue ) & 7 ) )
return 0;
*/
// Save CryptBuffer temporary to buffer for later use
*((unsigned*)Buffer) = *((unsigned *)&TempBuffer) ;
Buffer[4] = ((unsigned char*)&TempBuffer)[4];
// Update encryption value
ri->CurEncryptionValue = ( ri->CurEncryptionValue * 0x343FD ) + 0x269EC3;
// Everything went ok
return TempBuffer.AddBufferLen;
}
//-------------------------------------------------------------------------
// This function will decrypt the full buffer after it is received.
// If it fails, it will return FALSE.
//-------------------------------------------------------------------------
bool DecryptBufferData( CCryptTable *CryptTables, unsigned char *Buffer )
{
CCryptBuffer TempBuffer;
unsigned short c, BufferLen;
unsigned char CheckSum;
// Read CryptBuffer from received buffer
*((unsigned *)&TempBuffer) = *((unsigned*)Buffer);
((unsigned char*)&TempBuffer)[4] = Buffer[4];
// Calculate CheckSum for bufferheader
for ( CheckSum=0, c=0; c<5; ++c )
CheckSum = CheckSumTable[ (unsigned char)Buffer[ c ] ^ CheckSum ];
// Calculate real buffer length and check it
BufferLen = (unsigned short)(TempBuffer.AddBufferLen - TempBuffer.EncryptValue);
if ( BufferLen < 0x06 ) return false;
// Decrypt buffer data
if ( BufferLen > 0x06 )
{
for ( c=6; c<BufferLen; ++c )
{
Buffer[c] ^= CryptTables->Tables[ (TempBuffer.EncryptAddValue + c) & 0x000F ] \
[ (TempBuffer.AddTableValue + c) & 0x07FF ];
CheckSum = CheckSumTable [ (unsigned char)Buffer[ c ] ^ CheckSum ];
}
}
// Check CheckSum
if ( Buffer[5] != CheckSum )
return false;
// Complete buffer
*((unsigned short*)(Buffer )) = BufferLen ;
*((unsigned short*)(Buffer+2)) = TempBuffer.Command;
return true;
}
//-------------------------------------------------------------------------
// This functions will encrypt a buffer. The buffer must have at least a
// size of 6 bytes. The first two bytes must be the size of the buffer.
//-------------------------------------------------------------------------
void EncryptBuffer( CCryptTable *CryptTables, unsigned char *Buffer )
{
CCryptBuffer TempBuffer;
unsigned short c;
unsigned char CheckSum;
unsigned EncryptValue;
// Generate some random values for encrypting
TempBuffer.AddTableValue = (rand( ) % 0x800);
TempBuffer.EncryptAddValue = (rand( ) % 0x10 );
TempBuffer.EncryptValue = TempBuffer.AddTableValue + TempBuffer.EncryptAddValue;
// Fill other fields with values from Buffer
TempBuffer.AddBufferLen = *((unsigned short*)(Buffer ));
TempBuffer.Command = *((unsigned short*)(Buffer+2));
// Build new bufferheader
Buffer[4] = (((unsigned)TempBuffer.AddBufferLen ) & 0x00000007 ) ^ \
(((unsigned)TempBuffer.Command >> 0x03 ) & 0x000000C0 );
EncryptValue = (((unsigned)TempBuffer.AddBufferLen >> 0x03 ) & 0x00000007 );
EncryptValue |= (((unsigned)TempBuffer.AddBufferLen << 0x06 ) & 0x00007000 );
EncryptValue |= (((unsigned)TempBuffer.AddBufferLen << 0x13 ) & 0x30000000 );
EncryptValue |= (((unsigned)TempBuffer.Command << 0x17 ) & 0x03800000 );
EncryptValue |= (((unsigned)TempBuffer.Command << 0x0F ) & 0x001C0000 );
EncryptValue |= (((unsigned)TempBuffer.Command ) & 0x000001C0 );
EncryptValue |= (((unsigned)TempBuffer.EncryptValue << 0x09 ) & 0x00000E00 );
EncryptValue |= (((unsigned)TempBuffer.EncryptAddValue << 0x1A ) & 0x0C000000 );
EncryptValue |= (((unsigned)TempBuffer.EncryptAddValue << 0x1C ) & 0xC0000000 );
*((unsigned*)Buffer) = EncryptValue;
// Encrypt bufferheader
for ( CheckSum=0, c=0; c<5; ++c )
{
CheckSum = CheckSumTable [ ((unsigned char*)&TempBuffer)[ c ] ^ CheckSum ];
Buffer[c] ^= CryptTables->Tables[ c ][ TempBuffer.AddTableValue ];
}
// Encrypt bufferdata if exists
if ( TempBuffer.AddBufferLen > 0x06 )
{
for ( c=6; c<TempBuffer.AddBufferLen; ++c )
{
CheckSum = CheckSumTable [ (unsigned char)Buffer[ c ] ^ CheckSum ];
Buffer[c] ^= CryptTables->Tables[ (TempBuffer.EncryptAddValue + c) & 0x000F ] \
[ (TempBuffer.AddTableValue + c) & 0x07FF ];
}
}
Buffer[ 5 ] = CheckSum;
// Complete bufferheader
EncryptValue = *((unsigned*)Buffer) & 0xFF9C7FC7;
EncryptValue |= (((unsigned)TempBuffer.AddTableValue << 0x03 ) & 0x00000038 );
EncryptValue |= (((unsigned)TempBuffer.AddTableValue << 0x09 ) & 0x00038000 );
EncryptValue |= (((unsigned)TempBuffer.AddTableValue << 0x0C ) & 0x00600000 );
Buffer[ 4 ] = (Buffer[4]&0xC7) | (((unsigned)TempBuffer.AddTableValue ) & 0x38 );
*((unsigned*)Buffer) = EncryptValue;
}
//-------------------------------------------------------------------------
bool CryptISCPak( unsigned char* pak )
{
unsigned paksize = *((unsigned short*)&pak[0]);
for( unsigned short i = 2; i < paksize; i ++ )
pak[i] ^= 0x81 * i * paksize;
return true;
}
#ifdef USE124
// This encryption code was taken from the dRose source. Not sure who to credit other than them.
// To use 124 you will need the 124 trose.exe in your server directory.
int buildChecksum(char* csum, char* path)
{
char buf[0x200];
int bytesread=0;
FILE* fh;
if (path==0) path = "TRose.exe";
fh = fopen( path, "rb" );
if ( fh == NULL ) return -1;
fseek(fh, -512, SEEK_END);
bytesread = fread(buf, 1, 0x200, fh);
fclose(fh);
if (bytesread!=0x200) return -2;
short keylen = buf[0x0f];
char* key = new char[keylen+1];
unsigned short key_ct[] = {0x94, 0x20, 0x5F, 0x53, 0x14, 0xF2, 0x61, 0x11, 0x54, 0xFF, 0x72, 0x99, 0x44, 0xF4, 0xA1, 0xAA, 0xBA, 0xC2, 0x54, 0x52, 0x6F, 0x73, 0x65, 0x2E, 0x65, 0x78, 0x65};
for(int i=0; i<keylen; i++)
key[i] = key_ct[i] ^ buf[0x18A + i];
int csumlen=0;
int multiplier=1;
for(int i=keylen; i>0; i--) {
int tmp = (key[i-1]-0x30)*multiplier;
multiplier *= 0x0a;
csumlen += tmp;
}
delete [] key;
unsigned short csumtable[] = {0x34, 0x5C, 0x3D, 0x52, 0xCE, 0xF3, 0x12, 0xD4, 0x05, 0x91, 0xEE, 0xFF, 0x49, 0xC2, 0xD2};
int tmp=0;
for(int i=0; i<csumlen; i++) {
csum[i] = csumtable[tmp] ^ buf[0x87 + i];
if (tmp==0x0e) tmp=0; else tmp++;
}
return csumlen;
}
void buildCryptTable(char* crypttable, char* checksum, int checksumlen)
{
for (int i=0; i<0x008; i++) crypttable[i]=0;
for (int i=0; i<0x100; i++) crypttable[i+8]=i;
int csumpos=0;
int modifier=0;
for (int i=0; i<0x40*4; i++) {
int curpos=crypttable[8+i];
modifier = (checksum[csumpos] + curpos + modifier) & 0xff;
crypttable[8+i] = crypttable[modifier+8];
crypttable[modifier+8] = curpos;
csumpos=++csumpos%checksumlen;
}
}
void cryptPacket(char *packet, char *crypttable)
{
unsigned short paksize=(*((unsigned short*)&packet[0])) - 2;
for(int i=0; i<paksize; i++) {
unsigned tmp1=(*((unsigned*)&crypttable[0]) + 1) & 0xff;
unsigned tmp2=(unsigned)crypttable[tmp1+8];
unsigned tmp3=((*((unsigned*)&crypttable[4]) + tmp2) & 0xff);
unsigned tmp4=crypttable[tmp3+8];
*((unsigned*)&crypttable[0]) = tmp1;
*((unsigned*)&crypttable[4]) = tmp3;
crypttable[tmp3+8] = tmp2;
crypttable[tmp1+8] = tmp4;
packet[i+2] = crypttable[((tmp4 + tmp2) & 0xff) + 8] ^ packet[i+2];
}
}
#endif
+50
View File
@@ -0,0 +1,50 @@
#ifndef __ROSE_SERVER__CRYPTION_ROUTINES__HEADER_FILE__
#define __ROSE_SERVER__CRYPTION_ROUTINES__HEADER_FILE__
//#define USE124
//-------------------------------------------------------------------------
// This structure contains generated tables, which are needed to
// encrypt and decrypt packets.
//-------------------------------------------------------------------------
struct CCryptTable
{
unsigned** Tables; // Main encryption table
unsigned short* AddTable; // Less important encryption table
unsigned EncryptionStartValue; // Start value for sending clients
};
//-------------------------------------------------------------------------
// This structure contains informations about current encrypt-values.
// Startvalues should be "EncryptionStartValue" from the CCryptTable for
// CurEncryptionValue and zero for CurAddValue.
// * This values changes every incoming encryption.
//-------------------------------------------------------------------------
struct CCryptStatus
{
unsigned CurEncryptionValue; // Current encryption value
unsigned CurAddValue; // Current additional value
};
//-------------------------------------------------------------------------
// Functions, used to generate and delete CryptTables
//-------------------------------------------------------------------------
void GenerateCryptTables ( CCryptTable* &CryptTables, unsigned ModValue );
void GenerateLoginServerCryptTables ( CCryptTable* &CryptTables );
void FreeCryptTables ( CCryptTable* &CryptTables );
//-------------------------------------------------------------------------
// Functions, used to decrypt/encrypt a buffer - serverside
//-------------------------------------------------------------------------
int DecryptBufferHeader ( CCryptStatus *ri, CCryptTable *CryptTables, unsigned char *Buffer );
bool DecryptBufferData ( CCryptTable *CryptTables, unsigned char *Buffer );
void EncryptBuffer ( CCryptTable *CryptTables, unsigned char *Buffer );
bool CryptISCPak( unsigned char* pak ); // Raven0123
//-------------------------------------------------------------------------
#ifndef USE124
#define TABLE_SIZE (256+8)
int buildChecksum(char* csum, char* path=0);
void buildCryptTable(char* crypttable, char* checksum, int checksumlen);
void cryptPacket(char *packet, char *crypttable);
#endif
#endif
+29
View File
@@ -0,0 +1,29 @@
//#include <cstring>
#include "seh.hpp"
#ifdef __WIN32__
EXCEPTION_DISPOSITION __SEH_HANDLER::ExceptionRouter(PEXCEPTION_RECORD pRecord,
__SEH_EXCEPTION_REGISTRATION* pReg,
PCONTEXT pContext,
PEXCEPTION_RECORD pRecord2)
{
return pReg->exthandler->ExceptionHandler(pRecord, pReg, pContext, pRecord2);
}
EXCEPTION_DISPOSITION __SEH_HANDLER::ExceptionHandler(PEXCEPTION_RECORD pRecord,
__SEH_EXCEPTION_REGISTRATION* pReg,
PCONTEXT pContext,
PEXCEPTION_RECORD pRecord2)
{
/*std::memcpy(&excContext, pContext, sizeof(_CONTEXT));
std::memcpy(&excRecord, pRecord, sizeof(_EXCEPTION_RECORD));*/
memcpy(&excContext, pContext, sizeof(_CONTEXT));
memcpy(&excRecord, pRecord, sizeof(_EXCEPTION_RECORD));
longjmp(context, 1);
}
#endif
+96
View File
@@ -0,0 +1,96 @@
#ifndef __FV_SEH_H__
#define __FV_SEH_H__
#ifdef __WIN32__
#include <windows.h>
#include <excpt.h>
#endif
#include <setjmp.h>
//#include <fv/defs.hpp>
//NAMESPACE_BEGIN(PU)
//NAMESPACE_BEGIN(SEH)
#ifdef __WIN32__
class __SEH_HANDLER;
typedef struct tag__SEH_EXCEPTION_REGISTRATION
{
tag__SEH_EXCEPTION_REGISTRATION* prev;
PEXCEPTION_HANDLER handler;
__SEH_HANDLER* exthandler;
} __SEH_EXCEPTION_REGISTRATION;
class __SEH_HANDLER
{
public:
__SEH_HANDLER() { }
static EXCEPTION_DISPOSITION ExceptionRouter(PEXCEPTION_RECORD pRecord,
__SEH_EXCEPTION_REGISTRATION* pReg,
PCONTEXT pContext,
PEXCEPTION_RECORD pRecord2);
virtual EXCEPTION_DISPOSITION ExceptionHandler(PEXCEPTION_RECORD pRecord,
__SEH_EXCEPTION_REGISTRATION* pReg,
PCONTEXT pContext,
PEXCEPTION_RECORD pRecord2);
jmp_buf context;
EXCEPTION_RECORD excRecord;
CONTEXT excContext;
};
#define __seh_try \
{ \
__SEH_EXCEPTION_REGISTRATION _lseh_er; \
__SEH_HANDLER _lseh_handler; \
\
_lseh_er.handler = \
reinterpret_cast<PEXCEPTION_HANDLER>(__SEH_HANDLER::ExceptionRouter); \
_lseh_er.exthandler = &_lseh_handler; \
asm volatile ("movl %%fs:0, %0" : "=r" (_lseh_er.prev)); \
asm volatile ("movl %0, %%fs:0" : : "r" (&_lseh_er)); \
int _lseh_setjmp_res = setjmp(_lseh_handler.context); \
while(true) { \
if(_lseh_setjmp_res != 0) { \
break; \
} \
#define __seh_finally \
break; \
} \
while(true) {
#define __seh_except(rec, ctx) \
break; \
} \
PEXCEPTION_RECORD rec = &_lseh_handler.excRecord; \
PCONTEXT ctx = &_lseh_handler.excContext; \
\
asm volatile ("movl %0, %%fs:0" : : "r" (_lseh_er.prev)); \
if(_lseh_setjmp_res != 0)
#define __seh_end }
#else
#define __seh_try
#define __seh_except(rec, ctx) if(false) {
#define __seh_end }
#define __seh_finally
#endif
//NAMESPACE_END(SEH)
//NAMESPACE_END(PU)
#endif
+438
View File
@@ -0,0 +1,438 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://osroseon.to.md
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
//#define _CRT_NO_TIME_T
#ifndef __ROSE_SOCKETS__
#define __ROSE_SOCKETS__
#define USEIFO
#ifdef _WIN32
#include <windows.h>
#define close closesocket
#ifdef FD_SETSIZE
#undef FD_SETSIZE
#endif
#define FD_SETSIZE 1024
#else
#include <winsock2.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <cstdarg>
#include <errno.h>
#define SOCKET int
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define PVOID void *
#define ioctlsocket ioctl
#define SOCKADDR struct sockaddr
#define closesocket close
#endif
#include "mysql.h"
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <string>
#include <cstdio>
#include <exception>
#include <time.h>
#include <assert.h>
#include <math.h>
#include <cmath>
#include <map>
#include "pthread.h"
#include <vector>
#include <csignal>
#include "log.h"
#include "rosecrypt.hpp"
#include "config.h"
#include "database/database.h"
#pragma comment(lib, "Ws2_32.lib")
// Just some defs for easier use
typedef char SBYTE;
typedef unsigned char BYTE;
typedef short SWORD;
typedef unsigned short WORD;
typedef long SDWORD;
typedef unsigned long DWORD;
typedef long long SQWORD;
typedef unsigned long long QWORD;
typedef unsigned __int8 byte;
typedef unsigned __int16 word;
typedef unsigned __int32 dword;
typedef unsigned __int64 qword;
typedef char* strings;
using std::cout;
using std::endl;
using std::system;
using std::vector;
using std::map;
using std::nothrow;
using std::string;
#define STARTPACKET(p,c,s) CPacket p; p.Command = c; p.Size = s;
#define SETBYTE(p,o,v) p.Buffer[o]=v;
#define SETWORD(p,o,v) *((unsigned short*)&p.Buffer[o])=v;
#define SETDWORD(p,o,v) *((unsigned*)&p.Buffer[o])=v;
#define SETQWORD(p,o,v) *((long long*)&p.Buffer[o])=v;
#define SETFLOAT(p,o,v) *((float*)&p.Buffer[o])=v;
#define BEGINPACKET(p,c) CPacket p; p.Command = c; p.Size = 6;
#define RESETPACKET(p,c) p.Command = c; p.Size = 6;
#define ADDBYTE(p,v) { p.Buffer[p.Size-6]=v; p.Size+=1; }
#define ADDWORD(p,v) { *((WORD*)&p.Buffer[p.Size-6])=v; p.Size+=2; }
#define ADDDWORD(p,v) { *((unsigned*)&p.Buffer[p.Size-6])=v; p.Size+=4; }
#define ADDQWORD(p,v) { *((QWORD*)&p.Buffer[p.Size-6])=v; p.Size+=8; }
#define ADDFLOAT(p,v) { *((float*)&p.Buffer[p.Size-6])=v; p.Size+=4; }
#define ADDSTRING(p,v) { for(int q=0; q<(int)strlen((char*)v); q++) ADDBYTE(p,(v)[q]); }
#define GETBYTE(p,o) (p.Buffer[o])
#define GETWORD(p,o) *((WORD*)&p.Buffer[o])
#define GETDWORD(p,o) *((DWORD*)&p.Buffer[o])
#define GETQWORD(p,o) *((QWORD*)&p.Buffer[o])
#define GETFLOAT(p,o) *((float*)&p.Buffer[o])
#define pi 3.1415926535897932384626433832795
#define r2d pi/180
#define ZONE_SIZE 6400
#define ENTITY_NO_TYPE 0
#define ENTITY_PLAYER 1
#define ENTITY_MONSTER 2
#define ENTITY_NPC 3
#define ENTITY_SUMMON 4
#define ENTITY_DROP 5
// Structures
// Packet information
struct CPacket
{
unsigned short Size; // Packet size
unsigned short Command; // Packet command
unsigned short Unused; // unused
unsigned char Buffer[0x400]; // Packet data //0x600
CPacket( unsigned short mycommand=0, unsigned short mysize=6, unsigned short myunused=0 );
~CPacket( );
void StartPacket( unsigned short mycommand, unsigned short mysize=6, unsigned short myunused=0 );
void AddByte( unsigned char value );
void AddWord( unsigned short value );
void AddDWord( unsigned value );
void AddQWord( unsigned long long value );
void AddFloat( float value );
void AddString( char* value );
void SetByte( unsigned short pos, unsigned char value );
void SetWord( unsigned short pos, unsigned short value );
void SetDWord( unsigned short pos, unsigned value );
void SetQWord( unsigned short pos, unsigned long long value );
void SetFloat( unsigned short pos, float value );
unsigned char GetByte( unsigned short pos );
unsigned short GetWord( unsigned short pos );
unsigned GetDWord( unsigned short pos );
unsigned long long GetQWord( unsigned short pos );
float GetFloat( unsigned short pos );
char* GetString( unsigned short pos );
// Functions added by Drakia
template <class T> void Add( T value ) {
*((T*)&Buffer[Size]) = value;
Size += sizeof(T);
}
void AddString( char* value, bool NullTerminate ) {
for (dword i = 0; i < strlen((const char*)value); i++) {
Add<byte>(value[i]);
}
if (NullTerminate) Add<byte>(0);
}
template <class T> void AddString( char* value ) {
Add<T>(strlen((const char*)value));
AddString(value, false);
}
void AddBytes( byte* value, dword len ) {
for (dword i = 0; i < len; i++)
Add<byte>((byte)value[i]);
}
};
// SQL Configuration
struct CROSEServerConfigSQL
{
char* pcServer; // IP
char* pcDatabase; // Database
char* pcUserName; // UserName
char* pcPassword; // Password
int pcPort; // port
};
// Server configuration
struct CROSEServerConfig
{
// GLOBAL
CROSEServerConfigSQL SQLServer; // SQL Information
bool usethreads; // Use Threads (in sockets)
bool Verbose; // print server information?
unsigned MaxConnections; // Max connections
unsigned UserPerThread; // User per thread
bool AllowMultipleConnections; // Allow multiple connection from same ip?
bool StayInServerLoop; // Server actived?
UINT ServerID; //id from this server
UINT ParentID; //id from the server to connect
char* ServerName; //Server name
UINT ServerType; //0 login - 1 server(char) - 2 channel(world)
// LOGINSERVER
unsigned int MinimumAccessLevel; // Minimum access level
char* LoginIP; // LoginIP [external]
unsigned int LoginPort; // Login port
unsigned int LoginPass;
bool CreateLoginAccount; // Create account in login if not exist?
bool Testserver; // channel for test ?
// CHARSEVER
unsigned long int DeleteTime; // Delete time
char* CharIP; // CharIP
unsigned int CharPort; // Char port
unsigned int CharPass;
unsigned int CharsPort;
// WORLDSERVER
char* WorldIP;
unsigned int WorldPort;
unsigned int WorldsPort;
unsigned int WorldPass;
UINT EXP_RATE;
UINT DROP_RATE;
UINT BASE_DROP_CHANCE;
UINT ZULY_RATE;
UINT AUTOSAVE;
UINT SAVETIME;
UINT MapDelay;
UINT VisualDelay;
UINT WorldDelay;
UINT DeathDelay; //Set a timer delay so that we don't have a problem with monster death
UINT AIWatch; //Set an AI script number to watch for. Debug only
UINT SpawnType;
char* WELCOME_MSG;
UINT DROP_TYPE;
int MaxStat;
int Partygap;
int FairyMode;
int FairyStay;
int FairyWait;
int FairyMax;
int ScrollFairy;
int FairyTestMode;
int PlayerDmg;
int MonsterDmg;
int Cfmode;
int BlueChance;
int StatChance;
int SlotChance;
int RefineChance;
int Rare_Refine;
int KillOnFail;
int MaxLevel;
int DropMultiple;
int KTPointRate;
UINT AttkMult;
UINT SkillMult;
UINT DropDelay;
// COMMAND LEVELS
int Command_Go;
int Command_Who;
int Command_Who2;
int Command_Broadcast;
int Command_Mute;
int Command_Tele;
int Command_Level;
int Command_LevelUp;
int Command_TeleToMe;
int Command_Save;
int Command_Reload;
int Command_Ann;
int Command_SSpawn;
int Command_Set;
int Command_ESpawn;
int Command_DSpawn;
int Command_DelSpawn;
int Command_Pak;
int Command_Pak2;
int Command_Pakm;
int Command_Info;
int Command_Exp;
int Command_Mon;
int Command_Kick;
int Command_Job;
int Command_Cha;
int Command_Item;
int Command_Drop;
int Command_GiveZuly;
int Command_Npc;
int Command_GiveFairy;
int Command_ManageFairy;
int Command_ChangeFairyWait;
int Command_ChangeFairyStay;
int Command_ChangeFairyTestMode;
int Command_Move;
int Command_Goto;
int Command_PlayerInfo;
int Command_Give2;
int Command_Ban;
int Command_Ani;
int Command_Summon;
int Command_ReloadQuest;
int Command_Shutdown;
int Command_DQuest;
int Command_IQuest;
int Command_ShopType;
int Command_Stat;
int Command_KillInRange;
int Command_GoToMap;
int Command_Heal;
int Command_ServerInfo;
int Command_TargetInfo;
int Command_Hide;
int Command_Class;
int Command_Monster;
int Command_GlobalTime;
int Command_Here;
int Command_Face;
int Command_Hair;
int Command_Pvp;
int Command_go;
int Command_Convert;
int Command_Rate;
int Command_Moveto;
int Command_Settime;
int Command_Transx;
int Command_Partylvl;
int Command_Pdmg;
int Command_Mdmg;
int Command_Rules;
int Command_Cfmode;
char* Command_GlobalPrefix;
};
// Classes
// Base class
class CBaseSocket
{
public:
CBaseSocket( ); // Constructor
virtual ~CBaseSocket( ); // Destructor
void CloseSocket( void ); // Close Socket
SOCKET sock; // This is our socket
SOCKET sckISC; // Raven0123
SOCKET sckISCII;
bool isActive; // Is this socket connected?
bool isserver;
CCryptTable* CryptTable; // This is for decrypting incomming packets
#ifdef USE124
char* csum;
int csumlen;
#endif
string ClientIP; // Client IP
char ClientSubNet[12]; // Lan Subnet
};
// Client class
class CClientSocket : public CBaseSocket
{
public:
CClientSocket( ); // Client Constructor
~CClientSocket( ); // Client Destructor
bool ReceiveData( ); // Receive packet
void SendPacket( CPacket *P ); // Send Packet
void SendPacketCpy( CPacket *P ); // Send a packet without encrypting the orginal packet
CCryptStatus CryptStatus; // Status of the encryption
class CServerSocket* GS; // Pointer to Server class
bool ISCThread(); // Raven0123
struct sockaddr_in clientinfo;
void* player;
#ifdef USE124
char* ct;
#endif
private:
unsigned short PacketSize; // Size of the current packet
unsigned short PacketOffset; // Current offset of the data
unsigned char Buffer[ 0xFFF ]; // Buffer to receive data into
unsigned char tempBuffer[0xFFF];
};
// Server class
class CServerSocket : public CBaseSocket
{
private:
//void CryptISCPak( char* pak ); // Raven0123
//void ISCThread(); // Raven0123
//SOCKET sckISC; // Raven0123
public:
void CryptISCPak( char* pak ); // Raven0123
CServerSocket( ); // Constructor
~CServerSocket( ); // Destructor
bool StartServer( ); // Start Server
void FillFDS( fd_set* fds ); // Create FDS table
void HandleClients( fd_set* fds ); // Handle Clients
void AddUser( SOCKET sock, sockaddr_in* ClientInfo, bool server ); // Add User
void DisconnectClient( CClientSocket* thisclient ); // Disconnect Client
bool DoSQL(char *Format, ...);
// Virtual Functions
virtual void LoadEncryption( ); //load encryption
virtual void ServerLoop( ); // Main Loop
virtual CClientSocket* CreateClientSocket( ); // Create a client
virtual void DeleteClientSocket( CClientSocket* thisclient ); // Delete client
virtual bool OnServerReady( ); // Executed with server is ready
virtual void OnServerStep( ); // Executed
virtual void OnServerDie( );
virtual bool OnReceivePacket( CClientSocket* thisclient, CPacket* P );
virtual void ReceivedISCPacket( CPacket* pak ); // Raven0123
virtual bool OnClientConnect( CClientSocket* thisclient );
virtual void OnClientDisconnect( CClientSocket* thisclient );
// Variables
CROSEServerConfig Config; // Hold server configuration
int maxfd;
MYSQL *mysql;
virtual bool Ping( ); // Used to ping the mysql server
vector<CClientSocket*> ClientList;
UINT ConnectedClients;
unsigned short port;
struct sockaddr_in ain;
struct sockaddr_in sain;
pthread_t threads[65535];
void SendISCPacket( CPacket* pak ); // Raven0123
};
PVOID ClientMainThread( PVOID ); // Handle clients
bool InitWinSocket ( void ); // Init windows sockets (wsa)
void CloseWinSocket( void ); // Close Windows sockets (wsa)
// -----------------------------------------------------------------------------------------
#endif
+28
View File
@@ -0,0 +1,28 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://osroseon.to.md
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
// Server list
struct CServers
{
UINT id;
char* ip;
UINT port;
SOCKET sock;
};
+21
View File
@@ -0,0 +1,21 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://osroseon.to.md
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "loginserver.h"
+37
View File
@@ -0,0 +1,37 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://osroseon.to.md
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "loginserver.h"
// Constructor
CLoginClient::CLoginClient( )
{
userid = 0;
isLoggedIn = false;
accesslevel = 0;
username.reserve(17);
password.reserve(33);
}
// Deconstructor
CLoginClient::~CLoginClient( )
{
}
+240
View File
@@ -0,0 +1,240 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://osroseon.to.md
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
developed with Main erose/hrose source server + some change from the original eich source
*/
#include "loginserver.h"
// Send Server encryption
bool CLoginServer::pakEncryptionRequest( CLoginClient* thisclient, CPacket* P )
{
try
{
thisclient->CryptStatus.CurAddValue = rand( ) | (rand( )<<16);
STARTPACKET( pak, 0x7FF, 11 );
SETBYTE ( pak, 0x00, 0x02 );
SETDWORD ( pak, 0x01, thisclient->CryptStatus.CurAddValue );
thisclient->SendPacket( &pak );
return true;
}
catch(...)
{
Log(MSG_ERROR, "pakEncryptionRequest");
}
}
// Packet when user login (chck user and pass)
bool CLoginServer::pakUserLogin( CLoginClient* thisclient, CPacket* P )
{
Log(MSG_DEBUG,"User Login request received");
try
{
if ( thisclient->isLoggedIn ) return false;
MYSQL_ROW row;
thisclient->username.assign( (const char*)&P->Buffer, 32, (P->Size-6-32)>16?16:P->Size-6-32 );
thisclient->password.assign( (const char*)&P->Buffer, 0, 32 );
BEGINPACKET( pak, 0x708 );
MYSQL_RES *result = DB->QStore( "SELECT id,password,accesslevel,online FROM accounts WHERE username='%s'", thisclient->username.c_str() );
if(result == NULL)
{
Log(MSG_WARNING,"DB Query returned a NULL result");
return false;
}
if( mysql_num_rows( result ) == 1 )
{
row = mysql_fetch_row(result);
int res = 0;
#ifdef _WIN32
res = _stricmp( row[1], thisclient->password.c_str() );
#else
res = strcasecmp( row[1], thisclient->password.c_str() );
#endif
if ( res == 0 )
{
if(atoi(row[3])==1)
{ // characters is already logged
Log(MSG_WARNING, "Account %s try re-login", thisclient->username.c_str() );
ADDBYTE( pak, 4 );
ADDDWORD( pak, 0 );
thisclient->SendPacket( &pak );
DB->QFree( );
DB->QExecute( "update accounts set login_count=1 WHERE username='%s'", thisclient->username.c_str());
return true;
}
thisclient->accesslevel = atoi(row[2]);
if( thisclient->accesslevel < Config.MinimumAccessLevel )
{ //The server are under inspection
Log(MSG_WARNING,"User accesslevel %i is lower than minimum %i",thisclient->accesslevel,Config.MinimumAccessLevel);
ADDBYTE( pak, 0 );
ADDDWORD( pak, 0 );
thisclient->SendPacket( &pak );
DB->QFree( );
return true;
}
if ( thisclient->accesslevel > 0 )
{
thisclient->userid = atoi(row[0]);
thisclient->isLoggedIn = true;
DB->QFree( );
//OK!
Log(MSG_WARNING,"User %s passed to charserver",thisclient->username.c_str());
ADDDWORD( pak, 0x0c000000 );//ADDDWORD( pak, 0x6f000000 );
ADDBYTE( pak, 0 );
result = DB->QStore( "SELECT id,name FROM channels WHERE owner=0" );
if(result==NULL) return false;
while( row = mysql_fetch_row(result) )
{
if (Config.Testserver){ADDBYTE( pak, 63 + atoi( row[0] ) );}
else{
ADDBYTE( pak, 48 + atoi( row[0] ) );}
ADDSTRING( pak, row[1] );
ADDBYTE( pak, 0 );
ADDDWORD(pak, atoi( row[0] ) );
}
DB->QFree( );
}
else
{
//BANNED
Log(MSG_WARNING,"User %s banned",thisclient->username.c_str());
ADDBYTE( pak, 5 );
ADDDWORD( pak, 0 );
DB->QFree( );
}
}
else
{
//BAD PASSWORD
Log(MSG_WARNING,"User %s attempted to log in with invalid password",thisclient->username.c_str());
ADDBYTE( pak, 3 );
ADDDWORD( pak, 0 );
DB->QFree( );
}
}
else
{
DB->QFree( );
if(Config.CreateLoginAccount)
{
if(!DB->QExecute("INSERT into accounts (username,password,accesslevel) values ('%s','%s',100)",thisclient->username.c_str(),thisclient->password.c_str()))
return true;
Log( MSG_INFO, "New Account created '%s'", thisclient->username.c_str() );
}
//BAD USERNAME
ADDBYTE( pak, 2 );
ADDDWORD( pak, 0 );
}
/*
1 - general error | 4 - your account is already logged
6 - topup account | 7 - cannot connect to server please try again
8 - server exceeded | 9 - account have not been verified
10 - login failed | 11 - ip capacity is full
*/
thisclient->SendPacket ( &pak );
return true;
}
catch(...)
{
Log(MSG_ERROR, "Error in pakUserLogin");
}
}
// Send server list
bool CLoginServer::pakGetServers( CLoginClient* thisclient, CPacket* P )
{
try
{
if( !thisclient->isLoggedIn ) return false;
MYSQL_ROW row;
unsigned servernum = GETDWORD( (*P), 0 );
MYSQL_RES *result = DB->QStore( "SELECT id,name,connected,maxconnections FROM channels WHERE owner=%i", servernum );
if(result==NULL) return false;
BEGINPACKET( pak, 0x704 );
ADDDWORD ( pak, servernum );
ADDBYTE ( pak, (BYTE)mysql_num_rows( result ) ); //old function
while(row = mysql_fetch_row(result))
{
UINT connected = atoi(row[2]);
UINT maxconnections = atoi(row[3]);
BYTE id = atoi( row[0] );
BYTE status = ((100 * connected) / (maxconnections == 0 ? 1 : maxconnections)) & 0xff;
ADDWORD( pak, id );
ADDBYTE( pak, 0 );
ADDWORD( pak, status );
ADDSTRING( pak, row[1] ); // Name
ADDBYTE( pak, 0 );
}
DB->QFree( );
thisclient->SendPacket ( &pak );
return true;
}
catch(...)
{
Log(MSG_ERROR, "Error in pakGetServers");
}
}
// Send server IP
bool CLoginServer::pakGetIP( CLoginClient* thisclient, CPacket* P )
{
try
{
if (!thisclient->isLoggedIn) return false;
MYSQL_ROW row;
DWORD servernum = GETDWORD( (*P), 0 );
BYTE channelnum = GETBYTE( (*P), 4 );
BEGINPACKET( pak, 0x70a );
if(!DB->QExecute( "UPDATE accounts SET lastsvr=%i,lastip='%s' WHERE id=%i", channelnum, inet_ntoa( thisclient->clientinfo.sin_addr ), thisclient->userid))
return false;
MYSQL_RES *result = DB->QStore( "SELECT host,port,connected,maxconnections FROM channels WHERE id=%i", servernum );
if(result==NULL) return false;
if(mysql_num_rows(result)!=1)
{
Log(MSG_WARNING, "Player selected a invalid channel or channel offline" );
DB->QFree( );
return true;
}
row = mysql_fetch_row(result);
UINT connected = atoi(row[2]);
UINT maxconnections = atoi(row[3]);
Log(MSG_DEBUG, "IP from database. Sent to client: %s ",row[0] );
ADDBYTE( pak, 0 ); //atoi(row[0]) ); // What is status? It's NULL in tables - Drakia
ADDDWORD( pak, thisclient->userid );
ADDDWORD( pak, 0x87654321 );
ADDSTRING( pak, row[0] );
ADDBYTE( pak, 0 );
ADDWORD( pak, atoi(row[1]) );
DB->QFree( );
thisclient->SendPacket ( &pak );
return true;
}
catch(...)
{
Log(MSG_ERROR, "Error in pakGetIP");
}
}
+142
View File
@@ -0,0 +1,142 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://osroseon.to.md
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "loginserver.h"
// Constructor
CLoginServer::CLoginServer( string fn )
{
filename = fn;
LoadConfigurations( (const char*)filename.c_str() );
GServer = this;
}
// Destructor
CLoginServer::~CLoginServer( )
{
}
// Create client socket (alloc memory)
CLoginClient* CLoginServer::CreateClientSocket( )
{
try
{
CLoginClient* thisclient = new (nothrow) CLoginClient( );
if(thisclient==NULL)
return NULL;
thisclient->GS = this;
return thisclient;
}
catch(...)
{
Log(MSG_ERROR, "Error in CreateClientSocket");
}
}
//loadserver encryption
void CLoginServer::LoadEncryption( )
{
GenerateLoginServerCryptTables( CryptTable );
}
// Delete client socket (free memory)
void CLoginServer::DeleteClientSocket( CClientSocket* thisclient )
{
try
{
Log( MSG_INFO, "User disconnected" );
delete (CLoginClient*)thisclient;
}
catch(...)
{
Log(MSG_ERROR, "Error in DeleteClientSocket");
}
}
// Load information when server is ready
bool CLoginServer::OnServerReady( )
{
return true;
}
// Load Server configuration
void CLoginServer::LoadConfigurations( const char* file )
{
try
{
//Database
Config.SQLServer.pcServer = ConfigGetString ( file, "mysql_host", "localhost" );
Config.SQLServer.pcDatabase = ConfigGetString ( file, "mysql_database", "irose2" );
Config.SQLServer.pcUserName = ConfigGetString ( file, "mysql_user", "root" );
Config.SQLServer.pcPassword = ConfigGetString ( file, "mysql_pass", "root" );
Config.SQLServer.pcPort = ConfigGetInt ( file, "mysql_port", 3306 );
//Server
Config.ServerID = ConfigGetInt ( file, "serverid", 0 );
Config.ServerType = 0; // Login is always 0
Config.LoginIP = ConfigGetString ( file, "serverip", "127.0.0.1" );
Config.LoginPort = ConfigGetInt ( file, "serverport", 29000 );
Config.ServerName = ConfigGetString ( file, "servername", "Loginserver" );
//Passwords
Config.LoginPass = ConfigGetInt ( file, "loginpass", 123456 );
Config.CharPass = ConfigGetInt ( file, "charpass", 123456 );
Config.WorldPass = ConfigGetInt ( file, "worldpass", 123456 );
//Login
Config.MinimumAccessLevel = ConfigGetInt ( file, "accesslevel", 100 );
Config.usethreads = ConfigGetInt ( file, "usethreads", 0 )==0?false:true;
Config.CreateLoginAccount = ConfigGetInt ( file, "CreateLoginAccount", 0 )==0?false:true;
Config.Testserver = ConfigGetInt ( file, "Testserver", 1 )==0?false:true;
}
catch(...)
{
Log(MSG_FATALERROR, "Error parsing configuration file");
}
}
// Handle packets
bool CLoginServer::OnReceivePacket( CClientSocket* thisclient, CPacket *P )
{
//Log(MSG_ERROR, "Packet received");
switch( P->Command )
{
case 0x703: return pakEncryptionRequest( (CLoginClient*)thisclient, P );
case 0x708: return pakUserLogin ( (CLoginClient*)thisclient, P );
case 0x704: return pakGetServers ( (CLoginClient*)thisclient, P );
case 0x70a: return pakGetIP ( (CLoginClient*)thisclient, P );
case 0x808: return true;
default:
Log( MSG_WARNING, "[%i]Login Server Received unknown packet. Command:%04x Size:%04x", thisclient->sock, P->Command, P->Size );
break;
}
return true;
}
//<<<<<<< .mine
//bool CLoginServer::Ping( ) {
// return DB->Ping( );
//}
//=======
bool CLoginServer::Ping( ) {
return DB->Ping( );
}
//>>>>>>> .r81
+77
View File
@@ -0,0 +1,77 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://osroseon.to.md
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#ifndef __ROSE_SERVER__
#define __ROSE_SERVER__
#include "../common/sockets.h"
#include "datatype.h"
// Player class
class CLoginClient : public CClientSocket
{
public:
CLoginClient ( ); // Constructor
~CLoginClient ( ); // destructor
// Variables
bool isLoggedIn;
UINT userid;
string username;
string password;
WORD accesslevel;
};
// Server class
class CLoginServer : public CServerSocket
{
public:
CLoginServer ( string ); // Constructor
~CLoginServer( ); // Destructor
//Functions
CLoginClient* CreateClientSocket( ); // Create a client
void DeleteClientSocket( CClientSocket* thisclient ); // Delete a client
void LoadEncryption( );
bool OnReceivePacket( CClientSocket* thisclient, CPacket* P );
bool OnServerReady(void);
void LoadConfigurations( const char* );
bool Ping( );
// Packets
bool pakEncryptionRequest( CLoginClient* thisclient, CPacket* P );
bool pakConnectToChar( CLoginClient* thisclient, CPacket *P );
bool pakUserLogin( CLoginClient* thisclient, CPacket* P );
bool pakGetServers( CLoginClient* thisclient, CPacket* P );
bool pakGetIP( CLoginClient* thisclient, CPacket* P );
// Variables
string filename;
vector<CServers*> ServerList; // list of channels;
CDatabase *DB;
};
void StartSignal( );
void StopSignal( );
void HandleSignal( int num );
extern class CLoginServer* GServer;
#endif
+65
View File
@@ -0,0 +1,65 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://osroseon.to.md
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "loginserver.h"
unsigned char LOG_THISSERVER = 0;
class CLoginServer* GServer;
// Main Funtion
int main(int argc, char *argv[])
{
LOG_THISSERVER = LOG_LOGIN_SERVER;
InitWinSocket( );
string fileconf = "loginserver.conf";
if(argc>1)
{
fileconf = argv[1];
}
CLoginServer *server = new (nothrow) CLoginServer( fileconf );
MYSQL mysql;
server->DB = new CDatabase( server->Config.SQLServer.pcServer,
server->Config.SQLServer.pcUserName,
server->Config.SQLServer.pcPassword,
server->Config.SQLServer.pcDatabase,
server->Config.SQLServer.pcPort, &mysql );
server->port = server->Config.LoginPort;
if(server->Config.usethreads)
Log( MSG_INFO, "Using Threads" );
// Start server
if(server->DB->Connect( )==0) Log( MSG_INFO, "Connected to MySQL server" );
else
{
delete server;
#ifdef _WIN32
system("pause");
#endif
return -1;
}
server->LoadEncryption ();
server->StartServer( );
server->DB->Disconnect( );
// Close server
delete server;
CloseWinSocket( );
return EXIT_SUCCESS;
}
+109
View File
@@ -0,0 +1,109 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://osroseon.to.md
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "loginserver.h"
/*
/ from signal.h
* NOTE: SIGINT is produced when the user presses Ctrl-C.
* SIGILL has not been tested.
* SIGFPE doesn't seem to work?
* SIGSEGV does not catch writing to a NULL pointer (that shuts down
* your app; can you say "segmentation violation core dump"?).
* SIGTERM comes from what kind of termination request exactly?
* SIGBREAK is indeed produced by pressing Ctrl-Break.
* SIGABRT is produced by calling abort.
*/
void StartSignal( )
{
signal( SIGINT, HandleSignal );
signal( SIGILL, HandleSignal );
signal( SIGFPE, HandleSignal );
signal( SIGSEGV, HandleSignal );
signal( SIGTERM, HandleSignal );
signal( SIGBREAK, HandleSignal );
signal( SIGABRT, HandleSignal );
}
void StopSignal( )
{
signal( SIGINT, 0 );
signal( SIGILL, 0 );
signal( SIGFPE, 0 );
signal( SIGSEGV, 0 );
signal( SIGTERM, 0 );
signal( SIGBREAK, 0 );
signal( SIGABRT, 0 );
}
void HandleSignal( int num )
{
switch(num)
{
case SIGINT:/* Interactive attention */
Log( MSG_ERROR, "Signal received: SIGINT" );
#ifdef _WIN32
Sleep(1000);
#else
usleep(1000);
#endif
raise(num);
break;
case SIGILL:/* Illegal instruction */
Log( MSG_ERROR, "Signal received: SIGILL, Server will be closed, Trying to save..." );
GServer->isActive = false;
#ifdef _WIN32
Sleep(1000);
#else
usleep(1000);
#endif
raise(num);
break;
case SIGFPE:/* Floating point error */
Log( MSG_ERROR, "Signal received: SIGFPE, Server will be closed, Trying to save..." );
GServer->isActive = false;
raise(num);
break;
case SIGSEGV:/* Segmentation violation */
Log( MSG_ERROR, "Signal received: SIGSEGV, Server will be closed, Trying to save..." );
GServer->isActive = false;
#ifdef _WIN32
Sleep(1000);
#else
usleep(1000);
#endif
raise(num);
break;
case SIGTERM:/* Termination request */
Log( MSG_INFO, "Signal received: SIGTERM, Server will be closed" );
GServer->isActive = false;
break;
#ifdef _WIN32
case SIGBREAK:/* Control-break */
Log( MSG_INFO, "Signal received: SIGBREAK, Server will be closed" );
GServer->isActive = false;
break;
#endif
default:
cout << "Unknown Signal Number: " << num << endl;
raise(num);
}
}
+946
View File
@@ -0,0 +1,946 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://www.osrose.net
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "worldserver.h"
// Add Player buffs
bool CWorldServer::AddBuffs( CSkills* thisskill, CCharacter* character, int Evalue )
{
//Log(MSG_INFO, "called addbuffs." );
bool bflag = false;
for(unsigned int i=0;i<2;i++)
{
if(thisskill->status[i] != 0) // sets status flags in magicstatus array
{
bflag = CheckABuffs( thisskill, character, Evalue, i );
}
else // some skills are instant effects without status changes e.g. healing.
{
if(thisskill->buff[i] != 0)
{
bflag = InstantBuff( thisskill, character, Evalue, i );
}
}
}
return bflag;
}
// handle instant effect skills without status changes
bool CWorldServer::InstantBuff( CSkills* thisskill, CCharacter* character, int Evalue, int i )
{
//Log( MSG_INFO, "Instant skill cast: Status (should be zero):%i buff: %i", thisskill->status[i], thisskill->buff[i] );
switch( thisskill->buff[i])
{
case 16: // HP
{
if(thisskill->duration <= 0 )//is heal
{
if(character->Stats->HP <= 0) //character is dead
return true;
character->Stats->HP += (long int)thisskill->value1[i]; //apparently there is no buff here. // + Evalue - 8;
if(character->Stats->HP > character->Stats->MaxHP )
character->Stats->HP = character->Stats->MaxHP;
return true;
}
}
break;
case 17: // MP
{
if(thisskill->duration <= 0 )// recover MP
{
character->Stats->MP += (long int)thisskill->value1[i];
if(character->Stats->MP > character->Stats->MaxMP)
character->Stats->MP = character->Stats->MaxMP;
return true;
}
}
break;
case 76: // Stamina
{
if(character->IsPlayer()) //monsters do not have stamina it would seem
{
if(thisskill->duration <= 0 )// recover Stamina
{
CPlayer* thisclient = GServer->GetClientByID(character->clientid);
if(thisclient == NULL)return false;
thisclient->CharInfo->stamina += (long int)thisskill->value1[i];
if(thisclient->CharInfo->stamina > 5000)
thisclient->CharInfo->stamina = 5000;
//Log(MSG_INFO,"Character %i Stamina is now %i", character->clientid, thisclient->CharInfo->stamina);
return true;
}
}
else
return false;
}
break;
default:
return false;
break;
}
return false;
}
// Add DeBuffs
bool CWorldServer::CheckABuffs( CSkills* thisskill, CCharacter* character, int Evalue ,int i)
{
//Log( MSG_INFO, "checkabuffs status: %i buff: %i",( thisskill->status[i], thisskill->buff[i] ));
bool bflag = false;
if(thisskill->status[i] != 0)
{
switch( thisskill->status[i])
{
case 7: case 8: case 9: case 10: case 11: //poisoned
{
//Log( MSG_INFO, "checkabuffs: Poisoned Status detected %i", thisskill->status[i] );
CBValue BuffValue = GetBuffValue( thisskill, character, Evalue, i, 0xff, character->Status->Poisoned, character->Status->Poisoned,true, true );
if(BuffValue.Position != 0xff)
{
UINT j = BuffValue.Position;
if(j>14)
{
character->Status->Poisoned = j;
character->MagicStatus[j].Buff = 1; // needs some value or else it will not be counted in GetBuffValue. trying it with 1
character->MagicStatus[j].BuffTime = clock();
character->MagicStatus[j].Duration = thisskill->duration;
character->MagicStatus[j].Value = 0; // this might cause headaches later
character->MagicStatus[j].Status = thisskill->status[i];
//Log( MSG_INFO, "Poisoned Status applied");
bflag = true;
}
}
}
break;
case 30: // muted
{
//Log( MSG_INFO, "checkabuffs: Mute Status detected %i", thisskill->status[i] );
CBValue BuffValue = GetBuffValue( thisskill, character, Evalue, i, 0xff, character->Status->Muted, character->Status->Muted, true, true );
if(BuffValue.Position != 0xff)
{
UINT j = BuffValue.Position;
if(j>14)
{
character->Status->Muted = j;
character->Status->CanCastSkill = false;
character->MagicStatus[j].Buff = 1; // needs some value or else it will not be counted in GetBuffValue. trying it with 1
character->MagicStatus[j].BuffTime = clock();
character->MagicStatus[j].Duration = thisskill->duration;
character->MagicStatus[j].Value = 0; // this might cause headaches later
character->MagicStatus[j].Status = thisskill->status[i];
//Log( MSG_INFO, "Muted Status applied");
bflag = true;
}
}
}
break;
case 31: // sleep
{
//Log( MSG_INFO, "checkabuffs: Sleep Status detected %i", thisskill->status[i] );
CBValue BuffValue = GetBuffValue( thisskill, character, Evalue, i, 0xff, character->Status->Sleep, character->Status->Sleep, true, true );
Log( MSG_INFO, "Sleep Status attempted. position = %i", BuffValue.Position);
if(BuffValue.Position != 0xff)
{
UINT j = BuffValue.Position;
if(j>14)
{
character->Status->Sleep = j;
character->Status->CanAttack = false;
character->Status->CanMove = false;
character->Status->CanCastSkill = false;
character->MagicStatus[j].Buff = 1; // needs some value or else it will not be counted in GetBuffValue. trying it with 1
character->MagicStatus[j].BuffTime = clock();
character->MagicStatus[j].Duration = thisskill->duration;
character->MagicStatus[j].Value = 0; // this might cause headaches later
character->MagicStatus[j].Status = thisskill->status[i];
//Log( MSG_INFO, "Sleep Status applied");
bflag = true;
}
}
}
break;
case 32: // faint
{
//Log( MSG_INFO, "checkabuffs: Fainted Status detected %i", thisskill->status[i] );
CBValue BuffValue = GetBuffValue( thisskill, character, Evalue, i, 0xff, character->Status->Faint, character->Status->Faint, true, true );
//Log( MSG_INFO, "Stun Status attempted. position = %i", BuffValue.Position);
if(BuffValue.Position != 0xff)
{
UINT j = BuffValue.Position;
if(j>14)
{
character->Status->Faint = j;
character->Status->CanAttack = false;
character->MagicStatus[j].Buff = 1; // needs some value or else it will not be counted in GetBuffValue. trying it with 1
character->MagicStatus[j].BuffTime = clock();
character->MagicStatus[j].Duration = thisskill->duration;
character->MagicStatus[j].Value = 0; // this might cause headaches later
character->MagicStatus[j].Status = thisskill->status[i];
//Log( MSG_INFO, "Fainted Status applied");
bflag = true;
}
}
}
break;
case 39: // Dispell. removes all buff and debuff effects
{
Log( MSG_INFO, "checkabuffs: Dispell Status detected %i", thisskill->status[i] );
// some dispell skills have duration of 2 seconds. Others have zero.
// for now we will treat them all as instants so we don't need a buff slot
float randv = GServer->RandNumber(0, 100);
if(randv <= thisskill->successrate)
{
for(int j=0;j<30;j++)
{ // Clean Buffs
character->MagicStatus[j].Duration = 0;
}
Log( MSG_INFO, "Dispell Status applied successfully");
// the rest will be taken care of in RefreshBuffs()
}
bflag = true;
}
break;
case 54: //A_GMExtra_Damage:
case 36: //A_Extra_Damage:
{
CBValue BuffValue = GetBuffValue( thisskill, character, Evalue, i,
character->Status->ExtraDamage_up,
character->Status->ExtraDamage_down,
character->Stats->ExtraDamage, true );
if(BuffValue.Position != 0xff)
{
UINT j = BuffValue.Position;
character->Stats->ExtraDamage = thisskill->atkpower;
if(j<15)
character->Status->ExtraDamage_up = j;
else
character->Status->ExtraDamage_down = j;
character->MagicStatus[j].Buff = thisskill->buff[i];
character->MagicStatus[j].BuffTime = clock();
character->MagicStatus[j].Duration = thisskill->duration;
character->MagicStatus[j].Value = thisskill->atkpower;
character->MagicStatus[j].Status = thisskill->status[i];
bflag = true;
Log( MSG_INFO, "Extra Damage Buff. Value %i Status %i",character->MagicStatus[j].Value,character->MagicStatus[j].Status);
}
}
case 35: // shield damage
{
// uses skill power not buff value. Add later
}
break;
case 18: // attack power up
case 19: // attack power down
case 48: // attack power up
{
//Log( MSG_INFO, "checkabuffs: Attack buff detected %i", thisskill->buff[i] );
CBValue BuffValue = GetBuffValue( thisskill, character, Evalue, i,
character->Status->Attack_up,
character->Status->Attack_down,
character->Stats->Attack_Power, true );
if(BuffValue.NewValue!=0)
{
UINT j = BuffValue.Position;
character->Stats->Attack_Power = BuffValue.NewValue;
if(j<15)
character->Status->Attack_up = j;
else
character->Status->Attack_down = j;
character->MagicStatus[j].Buff = thisskill->buff[i];
character->MagicStatus[j].BuffTime = clock();
character->MagicStatus[j].Duration = thisskill->duration;
character->MagicStatus[j].Value = BuffValue.Value;
character->MagicStatus[j].Status = thisskill->status[i];
bflag = true;
}
}
break;
case 20: // def up
case 21: // def down
case 49: // def up
{
//Log( MSG_INFO, "checkabuffs: Defense buff detected %i", thisskill->buff[i] );
CBValue BuffValue = GetBuffValue( thisskill, character, Evalue, i,
character->Status->Defense_up,
character->Status->Defense_down,
character->Stats->Defense, true );
if(BuffValue.NewValue!=0)
{
UINT j = BuffValue.Position;
character->Stats->Defense = BuffValue.NewValue;
if(j<15)
character->Status->Defense_up = j;
else
character->Status->Defense_down = j;
character->MagicStatus[j].Buff = thisskill->buff[i];
character->MagicStatus[j].BuffTime = clock();
character->MagicStatus[j].Duration = thisskill->duration;
character->MagicStatus[j].Value = BuffValue.Value;
character->MagicStatus[j].Status = thisskill->status[i];
bflag = true;
}
}
break;
case 24: //accuracy up
case 25: //accuracy down
case 51: //attack accuracy up.
{
CBValue BuffValue = GetBuffValue( thisskill, character, Evalue, i,
character->Status->Accury_up,
character->Status->Accury_down,
character->Stats->Accury, true );
if(BuffValue.NewValue!=0)
{
UINT j = BuffValue.Position;
character->Stats->Accury = BuffValue.NewValue;
if(j<15)
character->Status->Accury_up = j;
else
character->Status->Accury_down = j;
character->MagicStatus[j].Buff = thisskill->buff[i];
character->MagicStatus[j].BuffTime = clock();
character->MagicStatus[j].Duration = thisskill->duration;
character->MagicStatus[j].Value = BuffValue.Value;
character->MagicStatus[j].Status = thisskill->status[i];
bflag = true;
}
}
break;
case 22: // macic resistance up
case 23: // magic resistance down
case 50: // magic resistance up
{
CBValue BuffValue = GetBuffValue( thisskill, character, Evalue, i,
character->Status->Magic_Defense_up,
character->Status->Magic_Defense_down,
character->Stats->Magic_Defense, true );
if(BuffValue.NewValue!=0)
{
UINT j = BuffValue.Position;
character->Stats->Magic_Defense = BuffValue.NewValue;
if(j<15)
character->Status->Magic_Defense_up = j;
else
character->Status->Magic_Defense_down = j;
character->MagicStatus[j].Buff = thisskill->buff[i];
character->MagicStatus[j].BuffTime = clock();
character->MagicStatus[j].Duration = thisskill->duration;
character->MagicStatus[j].Value = BuffValue.Value;
character->MagicStatus[j].Status = thisskill->status[i];
bflag = true;
}
}
break;
case 28: //dodge up
case 29: //dodge down
case 53: //dodge rate up
{
CBValue BuffValue = GetBuffValue( thisskill, character, Evalue, i,
character->Status->Dodge_up,
character->Status->Dodge_down,
character->Stats->Dodge, true );
if(BuffValue.NewValue!=0)
{
UINT j = BuffValue.Position;
character->Stats->Dodge = BuffValue.NewValue;
if(j<15)
character->Status->Dodge_up = j;
else
character->Status->Dodge_down = j;
character->MagicStatus[j].Buff = thisskill->buff[i];
character->MagicStatus[j].BuffTime = clock();
character->MagicStatus[j].Duration = thisskill->duration;
character->MagicStatus[j].Value = BuffValue.Value;
character->MagicStatus[j].Status = thisskill->status[i];
bflag = true;
}
}
break;
case 14: //dash
case 15: //slow
case 46: //movement speed increased
{
//Log( MSG_INFO, "checkabuffs: move speed buff detected %i", thisskill->buff[i] );
CBValue BuffValue = GetBuffValue( thisskill, character, Evalue, i,
character->Status->Dash_up,
character->Status->Dash_down,
character->Stats->Move_Speed, true );
if(BuffValue.NewValue != 0)
{
UINT j = BuffValue.Position;
character->Stats->Move_Speed = BuffValue.NewValue;
if(j<15)
character->Status->Dash_up = j;
else
character->Status->Dash_down = j;
//Log( MSG_INFO, "Move speed buff position %i. new move speed %i. buff value %i", j,BuffValue.NewValue,BuffValue.Value );
character->MagicStatus[j].Buff = thisskill->buff[i];
character->MagicStatus[j].BuffTime = clock();
character->MagicStatus[j].Duration = thisskill->duration;
character->MagicStatus[j].Value = BuffValue.Value;
character->MagicStatus[j].Status = thisskill->status[i];
bflag = true;
}
}
break;
case 16: // haste attack
case 17: // slow attack
case 47: // attack speed up
{
CBValue BuffValue = GetBuffValue( thisskill, character, Evalue, i,
character->Status->Haste_up,
character->Status->Haste_down,
(UINT)character->Stats->Attack_Speed, true );
if(BuffValue.NewValue!=0)
{
UINT j = BuffValue.Position;
character->Stats->Attack_Speed = BuffValue.NewValue;
if(j<15)
character->Status->Haste_up = j;
else
character->Status->Haste_down = j;
character->MagicStatus[j].Buff = thisskill->buff[i];
character->MagicStatus[j].BuffTime = clock();
character->MagicStatus[j].Duration = thisskill->duration;
character->MagicStatus[j].Value = BuffValue.Value;
character->MagicStatus[j].Status = thisskill->status[i];
bflag = true;
}
}
break;
case 26: // crit up
case 27: // crit down
case 52: // crit up
{
CBValue BuffValue = GetBuffValue( thisskill, character, Evalue, i,
character->Status->Critical_up,
character->Status->Critical_down,
character->Stats->Critical, true );
if(BuffValue.NewValue != 0)
{
UINT j = BuffValue.Position;
character->Stats->Critical = BuffValue.NewValue;
if(j<15)
character->Status->Critical_up = j;
else
character->Status->Critical_down = j;
character->MagicStatus[j].Buff = thisskill->buff[i];
character->MagicStatus[j].BuffTime = clock();
character->MagicStatus[j].Duration = thisskill->duration;
character->MagicStatus[j].Value = BuffValue.Value;
character->MagicStatus[j].Status = thisskill->status[i];
bflag = true;
}
}
break;
case 12: // max HP up
case 44: // max HP up
{
CBValue BuffValue = GetBuffValue( thisskill, character, Evalue, i,
character->Status->HP_up,
character->Status->HP_down,
character->Stats->MaxHP, true );
if(BuffValue.NewValue!=0)
{
UINT j = BuffValue.Position;
character->Stats->MaxHP = BuffValue.NewValue;
if(j<15)
character->Status->HP_up = j;
else
character->Status->HP_down = j;
character->MagicStatus[j].Buff = thisskill->buff[i];
character->MagicStatus[j].BuffTime = clock();
character->MagicStatus[j].Duration = thisskill->duration;
character->MagicStatus[j].Value = BuffValue.Value;
character->MagicStatus[j].Status = thisskill->status[i];
bflag = true;
}
}
break;
case 13: // max MP up
case 45: // max MP up
{
CBValue BuffValue = GetBuffValue( thisskill, character, Evalue, i,
character->Status->MP_up,
character->Status->MP_down,
character->Stats->MaxMP, true );
if(BuffValue.NewValue!=0)
{
UINT j = BuffValue.Position;
character->Stats->MaxMP = BuffValue.NewValue;
if(j<15)
character->Status->MP_up = j;
else
character->Status->MP_down = j;
character->MagicStatus[j].Buff = thisskill->buff[i];
character->MagicStatus[j].BuffTime = clock();
character->MagicStatus[j].Duration = thisskill->duration;
character->MagicStatus[j].Value = BuffValue.Value;
character->MagicStatus[j].Status = thisskill->status[i];
bflag = true;
}
}
break;
default:
Log(MSG_WARNING,"Status %i unknown. Possibly not coded yet",thisskill->status[i]);
break;
}
}
return bflag;
}
// Get the new buffs values (character)
CBValue CWorldServer::GetBuffValue( CSkills* thisskill, CCharacter* character, UINT Evalue, UINT i, UINT up, UINT down, UINT CurrentValue, bool Buff, bool Status )
{
CBValue NewValue;
NewValue.Position = 0xff;
NewValue.NewValue = 0;
NewValue.Value = 0;
INT Value = 0;
UINT NormalValue = 0;
UINT UpValue = 0;
UINT DownValue = 0;
bool BuffFlag = false;
// not currently detecting debuffs properly so let's bring in some new code :)
//PY buff mod based on thiskill->status[i]
switch(thisskill->status[i])
{
case 12: case 13: case 14: case 16: case 18: case 20: case 22: case 24: case 26: case 28: case 35: case 36: case 53:
case 54:
Buff = true;
break;
case 7: case 8: case 9: case 10: case 15: case 17: case 19: case 21: case 23: case 25: case 27: case 29:
case 30: case 31: case 32: case 59: case 60:
Buff = false;
break;
default:
Buff = true;
break;
}
Log(MSG_INFO, "Current Buff boolean status %i Skill status = %i up: %i down: %i", Buff,thisskill->status[i],up,down);
//PY end
if(Buff) //skill is a buff
{
//find whether character already has buffs for this stat
for(UINT z=0;z<15;z++) // 0 to 14 are upward
{
if(character->MagicStatus[z].Status == thisskill->status[i])
{
NewValue.Position = z;
//Log(MSG_INFO, "Existing Buff position = %i",z);
NormalValue = CurrentValue - character->MagicStatus[z].Value;
UpValue = character->MagicStatus[z].Value;
BuffFlag = true;
break;
}
}
if(BuffFlag == false) // no active buffs so find a new slot
{
for(UINT z=0;z<15;z++) // 0 to 14 are upward
{
if(character->MagicStatus[z].Status == 0)
{
NewValue.Position = z;
//Log(MSG_INFO, "New Buff position = %i",z);
NormalValue = CurrentValue;
BuffFlag = true;
break;
}
}
}
}
else
{
//find whether character already has debuffs for this stat
for(UINT z=15;z<32;z++) // 15 to 32 are downward
{
if(character->MagicStatus[z].Status == thisskill->status[i])
{
NewValue.Position = z;
//Log(MSG_INFO, "Existing De-Buff position = %i",z);
NormalValue = CurrentValue + character->MagicStatus[z].Value;
DownValue = character->MagicStatus[z].Value;
BuffFlag = true;
break;
}
}
if(BuffFlag == false) // no active debuffs so find a new slot
{
for(UINT z=15;z<32;z++) // 15 to 32 are downward
{
if(character->MagicStatus[z].Status == 0)
{
NewValue.Position = z;
//Log(MSG_INFO, "New De-Buff position = %i",z);
NormalValue = CurrentValue;
BuffFlag = true;
break;
}
}
}
}
if(BuffFlag == false) // no available spaces found
return NewValue;
//if(up != 0xff) //currently have a buff. up is its location
//{
// UpValue = character->MagicStatus[up].Value;
//Log(MSG_INFO, "Current active buff detected in position %i with value %i", NewValue.Position,UpValue);
// NormalValue = CurrentValue - character->MagicStatus[up].Value;
// if(Buff)
// NewValue.Position = up;
//}
//else // don't currently have a buff
if(NewValue.Position == 0xff)
{
//Log(MSG_INFO, "No buff currently active");
if(Buff) //is this skill a buff?
{
for(UINT z=0;z<15;z++) // 0 to 14 are upward
{
if(character->MagicStatus[z].Status == 0)
{
NewValue.Position = z; //z is the new index in the magicstatus array where the buff will be placed
//Log(MSG_INFO, "Buff position = %i",z);
break;
}
}
if(NewValue.Position == 0xff) //no spaces found ??
return NewValue;
NormalValue = CurrentValue; // no buffs currently active so set normalvalue to currentvalue
}
else //debuff
{
for(UINT z=15;z<30;z++) // 15 to 29 are downward
{
if(character->MagicStatus[z].Status == 0)
{
NewValue.Position = z; //z is the new index in the magicstatus array where the buff will be placed
Log(MSG_INFO, "DeBuff position = %i",z);
break;
}
}
if(NewValue.Position == 0xff) //no spaces found ??
return NewValue;
NormalValue = CurrentValue; // no buffs currently active so set normalvalue to currentvalue
}
}
/*
if (!Status) // status boolean set false as default so it will run this code in pretty much all cases
{
Log(MSG_INFO, "Status set to false so checking for debuffs");
if( down != 0xff) //do we have a debuff in place already? down is its location
{
DownValue = character->MagicStatus[down].Value;
Log(MSG_INFO, "Current active de-buff detected in position %i with value %i", i,DownValue);
if( NormalValue!=0)
NormalValue += character->MagicStatus[down].Value;
else
NormalValue = CurrentValue + character->MagicStatus[down].Value;
if(!Buff)
NewValue.Position = down;
}
else
{
Log(MSG_INFO, "No de-buff currently active");
if(!Buff) //is this a debuff?
{
Log(MSG_INFO, "Buff is false so adding a new de-buff");
for(UINT z=15;z<30;z++) // 15 to 29 are downward
{
if(character->MagicStatus[z].Status == thisskill->status[i])
{
NewValue.Position = z; //z is the index in the magicstatus array where the de-buff will be placed
Log(MSG_INFO, "#1 found status De-Buff in position = %i. refreshing it.",z);
break;
}
if(character->MagicStatus[z].Status == 0)
{
NewValue.Position = z; //z is the new index in the magicstatus array where the de-buff will be placed
Log(MSG_INFO, "#1 De-Buff position = %i",z);
break;
}
}
if(NewValue.Position == 0xff)
return NewValue;
NormalValue = CurrentValue;
}
}
}
else if ( down != 0xff ) //Status = true and we currently have a debuff in effect??
{
Log(MSG_INFO, "Current active debuff detected in position %i with value %i", DownValue, character->MagicStatus[down].Value);
NormalValue = CurrentValue + character->MagicStatus[down].Value;
if(!Buff)
NewValue.Position = down;
}
else //status set true and no current debuff. Used for skills with only a Status effect but no buff/debuff value
{
for(UINT z=15;z<30;z++) //check magicstatus array debuff area for spaces
{
if(character->MagicStatus[z].Status == 0)
{
NewValue.Position = z; //z is the new index in the magicstatus array where the de-buff will be placed
Log(MSG_INFO, "#2 De-Buff position = %i",z);
break;
}
}
if(NewValue.Position == 0xff)
return NewValue;
NormalValue = CurrentValue;
}
*/
//Log(MSG_INFO, "Newvalue.position = %i",NewValue.Position);
if( thisskill->value2[i] > 0 )
{
Value = NormalValue * thisskill->value2[i] / 100;
//Log(MSG_INFO, "Percentage buff = %i",Value);
}
if( thisskill->value1[i] > 0 )
{
Value += thisskill->value1[i];
if(thisskill->buff[i] == A_DASH || thisskill->buff[i] == MOV_SPEED)
{
//Log(MSG_DEBUG,"Made it into the DASH calculations. Evalue = %i",Evalue);
if( Evalue <= 60 )
{
int temp1 = Evalue - 60;
//Log(MSG_DEBUG,"temp1 = %i",temp1);
float temp2 = (20.0 / 45.0);
//Log(MSG_DEBUG,"temp2 = %f",temp2);
int temp = (int)(temp1 * temp2);
//Log(MSG_DEBUG,"Result of calculation for INT < 60 = %i",temp);
//int temp = (int)((Evalue - 60) * (20.0 / 45.0));
//Log(MSG_DEBUG,"Result of calculation for INT < 60 = %i",temp);
Value += temp;
}
if( Evalue > 60 && Evalue <= 150)
{
int temp1 = Evalue - 60;
float temp2 = (17.0 / 45.0);
int temp = (int)(temp1 * temp2);
Value += temp;
}
if( Evalue > 150 && Evalue <= 195)
{
int temp1 = Evalue - 150;
float temp2 = (18.0 / 45.0);
int temp = (int)(temp1 * temp2);
Value += 34 + temp;
}
if( Evalue > 195 && Evalue <= 240)
{
int temp1 = Evalue - 195;
float temp2 = (19.0 / 45.0);
int temp = (int)(temp1 * temp2);
Value += 52 + temp;
}
if( Evalue > 240 && Evalue <= 285)
{
int temp1 = Evalue - 240;
float temp2 = (17.0 / 45.0);
int temp = (int)(temp1 * temp2);
Value += 71 + temp;
}
if( Evalue > 285 && Evalue <= 330)
{
int temp1 = Evalue - 285;
float temp2 = (18.0 / 45.0);
int temp = (int)(temp1 * temp2);
Value += 88 + temp;
}
if( Evalue > 330 && Evalue <= 375)
{
int temp1 = Evalue - 330;
float temp2 = (17.0 / 45.0);
int temp = (int)(temp1 * temp2);
Value += 106 + temp;
}
if( Evalue > 375 && Evalue <= 385)
{
int temp1 = Evalue - 420;
float temp2 = (19.0 / 45.0);
int temp = (int)(temp1 * temp2);
Value += 123 + temp;
}
}
// Value += (Evalue - 15) / 10;
else
Value += (Evalue-15)/32;
//Log(MSG_INFO, "Number buff = %i",Value);
}
if(Buff)
{
if( Value + CurrentValue - DownValue >= CurrentValue )
{
CurrentValue = NormalValue - DownValue + Value;
}
else
{
CurrentValue = 0;
}
}
else
{
CurrentValue = NormalValue + UpValue - Value;
}
NewValue.NewValue = CurrentValue;
NewValue.Value = Value;
return NewValue;
}
// Build Buffs to Show
unsigned int CWorldServer::BuildBuffs( CCharacter* character )
{
BYTE buff1 = 0;
BYTE buff2 = 0;
BYTE buff3 = 0;
BYTE buff4 = 0;
//Build Debuffs and Buffs
//Up
if(character->Status->Attack_up != 0xff)//A_ATTACK:
buff2 += ATTACK_UP;
if(character->Status->Defense_up != 0xff)//A_DEFENSE:
buff2 += DEFENSE_UP;
if(character->Status->Magic_Defense_up != 0xff)//A_MDEFENSE_UP
buff2 += MDEFENSE_UP;
if(character->Status->Accury_up != 0xff)//A_ACCUR:
buff3 += HITRATE_UP;
if(character->Status->Dash_up != 0xff)//A_DASH:
buff1 += DASH_UP;
if(character->Status->Haste_up != 0xff)//A_HASTE:
buff2 += HASTE_UP;
if(character->Status->HP_up != 0xff)//A_HP:
buff1 += HP_UP;
if(character->Status->MP_up != 0xff)//A_MP:
buff1 += MP_UP;
if(character->Status->Critical_up != 0xff)//A_CRITICAL:
buff3 += CRITICAL_UP;
if(character->Status->Dodge_up != 0xff)//A_DODGE:
buff1 += DODGE_UP;
if(character->Status->ExtraDamage_up != 0xff)//A_Extra_Damage:
buff4 += DAMAGE_UP;
//Down
if(character->Status->Attack_down != 0xff) // A_ATTACK:
buff2 += ATTACK_DOWN;
if(character->Status->Defense_down != 0xff)//A_DEFENSE:
buff2 += DEFENSE_DOWN;
if(character->Status->Magic_Defense_down != 0xff)
buff2 += MDEFENSE_DOWN;
if(character->Status->Accury_down != 0xff)//A_ACCUR:
buff3 += HITRATE_DOWN;
if(character->Status->Dash_down != 0xff)//A_DASH:
buff1 += DASH_DOWN;
if(character->Status->Haste_down != 0xff)//A_HASTE:
buff2 += HASTE_DOWN;
if(character->Status->HP_down != 0xff)//A_HP:
buff1 += 0;
if(character->Status->MP_down != 0xff)//A_MP:
buff1 += 0;
if(character->Status->Critical_down != 0xff)//A_CRITICAL:
buff3 += CRITICAL_DOWN;
if(character->IsSummon( ))
buff4 += SUMMON;
if(character->Status->Stuned != 0xff)//A_STUN
buff4+= STUN;
if(character->Status->Poisoned != 0xff)//A_POISON
buff1+= POISONED;
if(character->Status->Muted != 0xff)//A_MUTE
buff3+= MUTED;
return (buff1 * 0x01) + (buff2 * 0x100 ) + (buff3 * 0x10000) + (buff4 * 0x1000000);
}
// Build Buffs to Show
unsigned int CWorldServer::BuildUpBuffs( CCharacter* character )
{
BYTE buff1 = 0;
BYTE buff2 = 0;
BYTE buff3 = 0;
BYTE buff4 = 0;
// Buffs
//Up
if(character->Status->Attack_up != 0xff)//A_ATTACK:
buff2 += ATTACK_UP;
if(character->Status->Defense_up != 0xff)//A_DEFENSE:
buff2 += DEFENSE_UP;
if(character->Status->Magic_Defense_up != 0xff)//A_MDEFENSE_UP
buff2 += MDEFENSE_UP;
if(character->Status->Accury_up != 0xff)//A_ACCUR:
buff3 += HITRATE_UP;
if(character->Status->Dash_up != 0xff)//A_DASH:
buff1 += DASH_UP;
if(character->Status->Haste_up != 0xff)//A_HASTE:
buff2 += HASTE_UP;
if(character->Status->HP_up != 0xff)//A_HP:
buff1 += HP_UP;
if(character->Status->MP_up != 0xff)//A_MP:
buff1 += MP_UP;
if(character->Status->Critical_up != 0xff)//A_CRITICAL:
buff3 += CRITICAL_UP;
if(character->Status->Dodge_up != 0xff)//A_DODGE:
buff1 += DODGE_UP;
if(character->Status->ExtraDamage_up != 0xff)//A_Extra_Damage:
buff4 += DAMAGE_UP;
return (buff1 * 0x01) + (buff2 * 0x100 ) + (buff3 * 0x10000) + (buff4 * 0x1000000);
}
// Build Buffs to Show
unsigned int CWorldServer::BuildDeBuffs( CCharacter* character )
{
BYTE buff1 = 0;
BYTE buff2 = 0;
BYTE buff3 = 0;
BYTE buff4 = 0;
//Build Debuffs
//Down
if(character->Status->Attack_down != 0xff) // A_ATTACK:
buff2 += ATTACK_DOWN;
if(character->Status->Defense_down != 0xff)//A_DEFENSE:
buff2 += DEFENSE_DOWN;
if(character->Status->Magic_Defense_down != 0xff)
buff2 += MDEFENSE_DOWN;
if(character->Status->Accury_down != 0xff)//A_ACCUR:
buff3 += HITRATE_DOWN;
if(character->Status->Dash_down != 0xff)//A_DASH:
buff1 += DASH_DOWN;
if(character->Status->Haste_down != 0xff)//A_HASTE:
buff2 += HASTE_DOWN;
if(character->Status->HP_down != 0xff)//A_HP:
buff1 += 0;
if(character->Status->MP_down != 0xff)//A_MP:
buff1 += 0;
if(character->Status->Critical_down != 0xff)//A_CRITICAL:
buff3 += CRITICAL_DOWN;
if(character->IsSummon( ))
buff4 += SUMMON;
if(character->Status->Stuned != 0xff)//A_STUN
buff4+= STUN;
if(character->Status->Poisoned != 0xff)//A_POISON
buff1+= POISONED;
if(character->Status->Muted != 0xff)//A_MUTE
buff3+= MUTED;
return (buff1 * 0x01) + (buff2 * 0x100 ) + (buff3 * 0x10000) + (buff4 * 0x1000000);
}
+847
View File
@@ -0,0 +1,847 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://www.osrose.net
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "character.h"
#include "worldserver.h"
void CCharacter::DoAttack( )
{
//if(Status->Sleep <= 0xff)
//{
// ClearBattle( Battle );
// return; // can't take any action while we are asleep can we?
//}
//Log(MSG_INFO,"skill type %i selected. Chartype = %i",Battle->atktype, CharType);
if(Battle->iscasting == 1)
{
CCharacter* Enemy = GetCharTarget( );
if(Enemy == NULL)
{
ClearBattle( Battle );
return;
}
//Log(MSG_DEBUG,"Iscasting detected as true. Reset to false.");
if(CanAttack())
{
if(IsPlayer())
{
Log(MSG_DEBUG,"Should reach here once on normal attack. iscasting state = %i",Battle->iscasting);
}
ClearBattle( Battle );
StartAction(Enemy, NORMAL_ATTACK, 0);
return;
}
else
{
return;
}
}
if(!CanAttack())
{
return;
}
if(IsSummon())
{
CCharacter* Enemy = GetCharTarget( );
if(Enemy == NULL || (Battle->atktype != SKILL_AOE && Battle->atktype != BUFF_AOE))
{
//Log(MSG_DEBUG,"No Enemy found");
ClearBattle( Battle );
return;
}
if(this == Enemy) //summoned monster is attacking itself. It has been observed to happen
{
//Log(MSG_INFO,"Clearing Battle for this summon");
ClearBattle( Battle );
return;
}
if(Enemy->IsSummon())
{
CMonster* thisMonster = reinterpret_cast<CMonster*>(this);
if(thisMonster == NULL)
{
ClearBattle( Battle );
return;
}
CMonster* otherMonster = reinterpret_cast<CMonster*>(Enemy);
if(otherMonster == NULL)
{
ClearBattle( Battle );
return;
}
if(thisMonster->owner == otherMonster->owner)
{
//Log(MSG_INFO,"Clearing Battle for this summon");
ClearBattle( Battle );
return;
}
}
}
CMap* map = GServer->MapList.Index[Position->Map];
//Log(MSG_INFO,"DoAttack Battle Attack type = %i",Battle->atktype);
switch(Battle->atktype)
{
case NORMAL_ATTACK://normal attack
{
//if(!Status->CanAttack)
// return; //can't attack right now.
CCharacter* Enemy = GetCharTarget( );
if(Enemy == NULL)
{
ClearBattle( Battle );
return;
}
if(Enemy == this)
{
//Log(MSG_INFO,"WTF?? I AM trying to attack myself");
ClearBattle( Battle );
}
if(IsTargetReached( Enemy ))
{
//if(IsMonster())
// Log(MSG_INFO,"Monster is trying to hit the player");
NormalAttack( Enemy );
if (Enemy->IsMonster()) // do monster AI script when monster is attacked.
{
CMonster* monster = GServer->GetMonsterByID(Enemy->clientid, Enemy->Position->Map);
if(monster == NULL)return;
//monster->DoAi(monster->thisnpc->AI, 3);
monster->DoAi(monster->monAI, 3);
}
}
}
break;
case SKILL_ATTACK://skill attack
{
CCharacter* Enemy = GetCharTarget( );
if(Enemy == NULL)
{
ClearBattle( Battle );
return;
}
CSkills* skill = GServer->GetSkillByID( Battle->skillid );
if(skill == NULL)
{
//ClearBattle( Battle );
return;
}
if(IsTargetReached( Enemy, skill ))
{
SkillAttack( Enemy, skill );
if (Enemy->IsMonster())
{
CMonster* monster = GServer->GetMonsterByID(Enemy->clientid, Enemy->Position->Map);
if(monster == NULL)return;
monster->DoAi(monster->monAI, 3);
}
}
}
break;
case SKILL_BUFF://buffs
{
CCharacter* Enemy = GetCharTarget( );
if(Enemy == NULL)
{
//Log(MSG_DEBUG,"this target is NULL");
ClearBattle( Battle );
return;
}
CSkills* skill = GServer->GetSkillByID( Battle->skillid );
if(skill == NULL)
{
//Log(MSG_DEBUG,"this skill is NULL");
return;
}
if(IsTargetReached( Enemy, skill ))
{
//Log(MSG_DEBUG,"Skill successfully cast");
BuffSkill( Enemy, skill );
}
}
break;
case SKILL_AOE:
//case SKILL_SELF: //this is impossible. it can never be set
case AOE_TARGET:
{
//Log(MSG_DEBUG,"Called skill type %i",Battle->atktype);
CCharacter* Enemy = NULL;
CSkills* skill = GServer->GetSkillByID( Battle->skillid );
if(skill == NULL)
{
ClearBattle( Battle );
return;
}
if(Battle->atktype == AOE_TARGET)
{
float distance = GServer->distance( Position->current, Position->destiny );
if(distance <= skill->range)
{
Position->destiny = Position->current;
AoeSkill( skill, Enemy );
}
}
else
{
Position->skilltargetpos = Position->current;
AoeSkill( skill, NULL );
}
}
break;
case BUFF_SELF:
{
// return; // can't cast skills right now
CSkills* skill = GServer->GetSkillByID( Battle->skillid );
if(skill == NULL)
{
//ClearBattle( Battle );
return;
}
BuffSkill( this, skill );
}
break;
case BUFF_AOE:
{
//Log(MSG_INFO,"BUFF AOE selected");
CSkills* skill = GServer->GetSkillByID( Battle->skillid );
if(skill == NULL)
{
//ClearBattle( Battle );
return;
}
AoeBuff( skill );
}
break;
default:
return;
break;
}
}
// do normal attack
void CCharacter::NormalAttack( CCharacter* Enemy )
{
Enemy->OnBeAttacked( this );
Position->destiny = Position->current;
// PY code
float mod = 0;
if(IsPlayer())
{
mod = 23 + (Stats->Level / 1.5);
}
else
{
mod = 23 + (Stats->Level / 4);
}
float attack = 0;
if(Stats->magicattack == 1)
{
attack = (float) Stats->Attack_Power / Enemy->Stats->Magic_Defense;
attack *= mod;
}
else
{
attack = (float) Stats->Attack_Power / Enemy->Stats->Defense;
attack *= mod;
}
//PY end
if(attack < 5) attack = 5;
float d_attack = attack / 100;
mod = GServer->RandNumber( 0, 10 ) * d_attack;
attack += mod;
long int hitpower = (long int)floor(attack + GServer->RandNumber(0, 10));
if(IsPlayer( )) //temp fix to find balance btw monster and player
{
hitpower = (long int)floor(attack * (GServer->Config.PlayerDmg/100.00));
hitpower+=((hitpower*(Stats->ExtraDamage))/100);
}
if(IsMonster( )) //temp fix to find balance btw monster and player
hitpower = (long int)floor(attack * (GServer->Config.MonsterDmg/100.00));
bool critical = false;
if(hitpower <= 5)
{
hitpower = 5;
}
else
{
if(GServer->RandNumber(0,300)<Stats->Critical)
{
hitpower = (long int)floor(hitpower * 1.5);
critical = true;
}
}
// dodge
unsigned int hitvalue = (unsigned int)floor((double)(Stats->Accury * 100 / Enemy->Stats->Dodge));
if(hitvalue>100) hitvalue = 100;
if(GServer->RandNumber( 0, 100 )>hitvalue)
hitpower = 0; // dodged
if (hitpower > 0x7ff)//2047 packet size limit.
{
hitpower=0x7ff;
}
//maybe this little line here will fix my ghosty problem
//they are definitely attacking. But no animation so maybe atktarget is empty
Battle->atktarget = Battle->target;
//Well it does make the damage show up at teh client but the animation is still dodgey
if(IsMonster())
{
//Log(MSG_INFO,"Monster hits player for %i damage. Attack target = %i",hitpower,Battle->atktarget);
}
//Log( MSG_INFO, "hitpower %i. Attack %f ", hitpower,attack );
if(!Enemy->IsSummon( ) && Enemy->IsMonster( ))
{
Enemy->AddDamage( this, hitpower );
Enemy->damagecounter += hitpower;// is for AI
}
Enemy->Stats->HP -= hitpower;
if(IsPlayer())
Log(MSG_DEBUG,"Player attack did damage %i",hitpower);
if(IsMonster())
Log(MSG_DEBUG,"Monster attack did damage %i",hitpower);
BEGINPACKET( pak, 0x799 );
ADDWORD ( pak, clientid );
ADDWORD ( pak, Battle->atktarget );
if(Enemy->IsDead())
{
CDrop* thisdrop = NULL;
ADDWORD ( pak, (hitpower | ( critical?0xb000:0x8000 ) ));
if(!Enemy->IsSummon( ) && !Enemy->IsPlayer( ))
{
thisdrop = Enemy->GetDrop( );
if(thisdrop != NULL)
{
ADDFLOAT ( pak, thisdrop->pos.x*100 );
ADDFLOAT ( pak, thisdrop->pos.y*100 );
if(thisdrop->type == 1)
{
ADDWORD( pak, 0xccdf );
ADDDWORD( pak, thisdrop->amount );
}
else
{
ADDWORD ( pak, GServer->BuildItemHead( thisdrop->item ) );
ADDDWORD ( pak, GServer->BuildItemData( thisdrop->item ) );
}
ADDWORD ( pak, thisdrop->clientid );
ADDWORD ( pak, thisdrop->owner );
CMap* map = GServer->MapList.Index[thisdrop->posMap];
map->AddDrop( thisdrop );
}
}
GServer->SendToVisible( &pak, Enemy, thisdrop );
OnEnemyDie( Enemy );
}
else
{
ADDWORD ( pak, (hitpower|(hitpower>0?(critical?0x4000:0):0)));
GServer->SendToVisible( &pak, Enemy );
}
ReduceABC( );
Battle->lastAtkTime = clock( );
}
// do skill attack
bool CCharacter::SkillAttack( CCharacter* Enemy, CSkills* skill )
{
Position->destiny = Position->current;
//if(Battle->castTime == 0)
//{
BEGINPACKET( pak, 0x7bb );
ADDWORD ( pak, clientid );
GServer->SendToVisible( &pak, this );
// Battle->castTime = clock();
// return true;
//}
//else
//{
// clock_t etime = clock() - Battle->castTime;
// if(etime < SKILL_DELAY)
// return true;
//}
//Battle->castTime = 0;
UseAtkSkill( Enemy, skill );
Stats->MP -= (skill->mp - (skill->mp * Stats->MPReduction / 100));
if(Stats->MP < 0)
Stats->MP = 0;
//Battle->atktype = NORMAL_ATTACK;
//Battle->skilltarget = 0;
//Battle->atktarget = Battle->target;
//Battle->skillid = 0;
GServer->DoSkillScript( this, skill );
Battle->lastAtkTime = clock( );
if(Enemy->IsDead())
ClearBattle(Battle);
Battle->iscasting = 1;
//Log(MSG_DEBUG,"Cast a skill. Iscasting set to true");
return true;
}
// do buff skill
bool CCharacter::BuffSkill( CCharacter* Target, CSkills* skill )
{
Position->destiny = Position->current;
//if(Battle->castTime == 0)
//{
BEGINPACKET( pak, 0x7bb );
ADDWORD ( pak, clientid );
GServer->SendToVisible( &pak, (CCharacter*)this );
// Battle->castTime = clock();
// return true;
//}
//else
//{
// clock_t etime = clock() - Battle->castTime;
// if(etime < SKILL_DELAY)
// return true;
//}
//Battle->castTime = 0;
//Log(MSG_DEBUG,"applied buff skill %i",skill->id);
UseBuffSkill( Target, skill );
Stats->MP -= (skill->mp - (skill->mp * Stats->MPReduction / 100));
if(Stats->MP < 0) Stats->MP = 0;
GServer->DoSkillScript( this, skill ); //summons a monster. Why do we do this for all skills?
if(!IsMonster())
{
ClearBattle( Battle ); // clear battle for players when they use buff skills
//Battle->bufftarget = 0;
//Battle->skilltarget = 0;
//Battle->skillid = 0;
//Battle->atktype = NORMAL_ATTACK;
}
else //Monsters need to be reset to normal attack and clear skill attacks.
{
//Battle->atktarget = Battle->target;
//Battle->bufftarget = 0;
//Battle->skilltarget = 0;
//Battle->skillid = 0;
//Battle->atktype = NORMAL_ATTACK;
//StartAction(Target, NORMAL_ATTACK);
}
Battle->lastAtkTime = clock( );
Battle->iscasting = 1;
return true;
}
//arnold
// do AoE skill
bool CCharacter::AoeSkill( CSkills* skill, CCharacter* Enemy )
{
Position->destiny = Position->current;
//Log(MSG_INFO,"Doing AOE Skill");
//if(Battle->castTime == 0)
//{
BEGINPACKET( pak, 0x7bb );
ADDWORD ( pak, clientid );
GServer->SendToVisible( &pak, (CCharacter*)this );
// Battle->castTime = clock();
// return true;
//}
//else
//{
// clock_t etime = clock() - Battle->castTime;
// if(etime < SKILL_DELAY)
// return true;
//}
//Battle->castTime = 0;
CMap* map = GServer->MapList.Index[Position->Map];
//PY replacement code
if(IsPlayer() || IsSummon())
{
for(UINT i=0;i<map->MonsterList.size();i++)
{
CMonster* monster = map->MonsterList.at(i);
if(monster == NULL) continue;
if(monster->clientid == clientid) continue;
if(monster->IsSummon( ) && (map->allowpvp == 0 || monster->owner == clientid)) continue;
if(GServer->IsMonInCircle( Position->skilltargetpos, monster->Position->current,(float)skill->aoeradius + 1))
UseAtkSkill( (CCharacter*) monster, skill );
}
}
if(IsMonster() && !IsSummon())
{
for(UINT i=0;i<map->PlayerList.size();i++)
{
CPlayer* player = map->PlayerList.at(i);
if(player == NULL)continue;
if(player->clientid == clientid) continue;
if(GServer->IsMonInCircle( Position->skilltargetpos,player->Position->current,(float)skill->aoeradius+1))
UseAtkSkill( (CCharacter*) player, skill );
}
}
//PY end
// this code appears to me to be completely wrong replaced with code above
/*
for(UINT i=0;i<map->MonsterList.size();i++)
{
CMonster* monster = map->MonsterList.at(i);
if(monster->clientid == clientid) continue;
if(IsSummon( ) || IsPlayer( ))
{
if(monster->IsSummon( ) && (map->allowpvp==0 || monster->owner == clientid)) continue;
}
else
{
if(!monster->IsSummon( )) continue;
}
if(GServer->IsMonInCircle( Position->skilltargetpos, monster->Position->current,(float)skill->aoeradius + 1))
UseAtkSkill( (CCharacter*) monster, skill );
}
if(map->allowpvp!=0 || (IsMonster( ) && !IsSummon( )))
{
for(UINT i=0;i<map->PlayerList.size();i++)
{
CPlayer* player = map->PlayerList.at(i);
if(player->clientid==clientid) continue;
if(GServer->IsMonInCircle( Position->skilltargetpos,player->Position->current,(float)skill->aoeradius+1))
UseAtkSkill( (CCharacter*) player, skill );
}
}*/
Battle->iscasting = 1;
//Log(MSG_DEBUG,"Cast a skill. Iscasting set to true");
if(Enemy != NULL)
{
if(Enemy->IsDead( ))
ClearBattle( Battle );
}
else
ClearBattle( Battle );
Stats->MP -= (skill->mp - (skill->mp * Stats->MPReduction / 100));
if(Stats->MP < 0) Stats->MP = 0;
Battle->lastAtkTime = clock( );
return true;
}
bool CCharacter::AoeBuff( CSkills* skill )
{
//Log(MSG_INFO,"BUFF AOE called");
Position->destiny = Position->current;
BEGINPACKET( pak, 0x7bb );
ADDWORD ( pak, clientid );
GServer->SendToVisible( &pak, (CCharacter*)this );
CMap* map = GServer->MapList.Index[Position->Map];
if(CharType != 2) //player || Summon || NPC. Anything that is not a monster
{
for(UINT i=0;i<map->PlayerList.size();i++)
{
CPlayer* player = map->PlayerList.at(i);
if(player == NULL)continue;
switch(skill->target)
{
case 1: //tPartyMember
if(player->Party->party == GetParty())
{
//Log(MSG_INFO,"Applying AOE buff as long as I can find a close enough party member");
if (player == this) //it is me so I had better cast it anyway ^-^
{
UseBuffSkill( (CCharacter*)player, skill );
}
else if(player->Party->party != NULL) // Don't cast the skill on players who are not in any party at all.
{
if(GServer->IsMonInCircle( Position->current,player->Position->current,(float)skill->aoeradius + 1))
UseBuffSkill( (CCharacter*)player, skill );
}
}
break;
case 2: //tClanMember
if (player->Clan == GetClan( ) && (player->Clan != 0 || player == this))
{
//Log(MSG_INFO,"Applying AOE buff as long as I can find a close enough clan member");
if(GServer->IsMonInCircle( Position->current, player->Position->current, (float)skill->aoeradius + 1 ) )
UseBuffSkill( (CCharacter*)player, skill );
}
break;
case 3: //tAlly
case 7: //tAllCharacters
case 8: //tAllMembers. all characters
{
Log(MSG_INFO,"Applying AOE buff as long as I can find a close enough allied Player");
if(GServer->IsMonInCircle( Position->current,player->Position->current,(float)skill->aoeradius + 1))
UseBuffSkill( (CCharacter*)player, skill );
}
break;
case 5: //tHostileCharacter
{
if (CharType == 2)
{
//Log(MSG_INFO,"Applying AOE buff as long as I can find a close enough hostile Player");
if(GServer->IsMonInCircle( Position->current,player->Position->current,(float)skill->aoeradius + 1))
UseBuffSkill( (CCharacter*)player, skill );
}
}
break;
}
}
}
else if (CharType == 2) //monster
{
for(UINT i=0;i<map->MonsterList.size();i++)
{
CMonster* monster = map->MonsterList.at(i);
if(monster == NULL)continue;
switch(skill->target)
{
case tPartyMember: // party
break;
case 2: //tClanMember
break;
case 3: //tAlly
case 7: //tAllCharacters
case 8: //tAllMembers. all characters
{
//Log(MSG_INFO,"Applying AOE buff as long as I can find a close enough monster");
if(GServer->IsMonInCircle( Position->current,monster->Position->current,(float)skill->aoeradius + 1))
UseBuffSkill( (CCharacter*)monster, skill );
}
break;
case tHostileCharacter:
break;
}
}
}
Stats->MP -= (skill->mp - (skill->mp * Stats->MPReduction / 100));
if(Stats->MP < 0) Stats->MP = 0;
//Battle->atktarget = Battle->target;
//Battle->bufftarget = 0;
//Battle->skilltarget = 0;
//Battle->skillid = 0;
//Battle->atktype = NORMAL_ATTACK;
ClearBattle( Battle );
Battle->lastAtkTime = clock( );
Battle->iscasting = 1;
return true;
}
// use skill attack
void CCharacter::UseAtkSkill( CCharacter* Enemy, CSkills* skill, bool deBuff)
{
long int skillpower = skill->atkpower;
UINT weapontype = 0;
float mod = 0;
float attack = 0;
if(IsPlayer())
{
mod = 20 + (Stats->Level / 2);
}
else
{
mod = 15 + (Stats->Level / 2);
}
if(skill->skilltype == 6 || skill->skilltype == 7) //magical damage
{
attack = skillpower / (Enemy->Stats->Magic_Defense / 2);
}
else
{
attack = skillpower / (Enemy->Stats->Defense / 2);
}
attack *= mod;
attack += (Stats->Attack_Power / 2); // let's add our AP to the skillpower to make it worthwhile to cast skills.
skillpower = (int)attack;
bool bflag = false;
Enemy->OnBeAttacked( this );
if(skillpower <= 0) skillpower = 0;
if(IsPlayer())
{
skillpower += (int)(skillpower * (Stats->ExtraDamage))/100;
}
if (skill->atkpower == 0)
{
skillpower = 0; // If the skill has a 0 atk power, it isn't meant to damage
Log( MSG_INFO, "This skill does no damage" );
//ClearBattle( Battle );
return; // probably need to add some alternative code here for legitimate skills that have no attack power.
}
if(skillpower >2046)skillpower = 2046;
//Log(MSG_DEBUG,"Cast a skill. damage is %i",skillpower);
if(!Enemy->IsSummon( ) && Enemy->IsMonster( ))
{
Enemy->AddDamage( this, skillpower );
Enemy->damagecounter += skillpower;// is for AI
}
Enemy->Stats->HP -= skillpower;
if(IsPlayer())
Log(MSG_DEBUG,"Player Spell did damage %i",skillpower);
if(IsMonster())
Log(MSG_DEBUG,"Monster spell did damage %i",skillpower);
BEGINPACKET( pak, 0x7b6 );
ADDWORD ( pak, Enemy->clientid );
ADDWORD ( pak, clientid );
ADDDWORD ( pak, 0x000007f8 );
ADDBYTE ( pak, 0x00 );
if (Enemy->Stats->HP<1)
{
ADDWORD ( pak, skillpower + 0x8000 );
}
else
{
ADDWORD ( pak, skillpower + 0x2000 );
}
if(Enemy->IsDead())
{
//Log(MSG_DEBUG,"Enemy died");
CDrop* thisdrop = NULL;
ADDDWORD ( pak, 16 );
if(!Enemy->IsSummon( ) && !Enemy->IsPlayer( ))
{
thisdrop = Enemy->GetDrop( );
if(thisdrop != NULL)
{
ADDFLOAT ( pak, thisdrop->pos.x*100 );
ADDFLOAT ( pak, thisdrop->pos.y*100 );
if(thisdrop->type==1)
{
ADDWORD( pak, 0xccdf );
ADDDWORD( pak, thisdrop->amount );
}
else
{
ADDWORD ( pak, GServer->BuildItemHead( thisdrop->item ) );
ADDDWORD ( pak, GServer->BuildItemData( thisdrop->item ) );
}
ADDWORD ( pak, thisdrop->clientid );
ADDWORD ( pak, thisdrop->owner );
CMap* map = GServer->MapList.Index[thisdrop->posMap];
map->AddDrop( thisdrop );
}
}
GServer->SendToVisible( &pak, Enemy, thisdrop );
OnEnemyDie( Enemy );
}
else
{
ADDDWORD ( pak, 4 );
GServer->SendToVisible( &pak, Enemy );
bflag = GServer->AddBuffs( skill, Enemy, GetInt( ) );
//Send (de)buff information to the whole world
if(skill->nbuffs > 0 && bflag)
{
BEGINPACKET( pak, 0x7b5 );
ADDWORD ( pak, Battle->skilltarget );
ADDWORD ( pak, clientid );
ADDWORD ( pak, Battle->skillid );
ADDWORD ( pak, GetInt( ) );
ADDBYTE ( pak, skill->nbuffs );
GServer->SendToVisible( &pak, Enemy );
}
}
if (deBuff) return;
//Send skill animation to the world
RESETPACKET( pak, 0x7b9);
ADDWORD ( pak, clientid);
ADDWORD ( pak, Battle->skillid);
ADDWORD ( pak, 1);
GServer->SendToVisible( &pak, this );
Battle->bufftarget = 0;
Battle->skilltarget = 0;
Battle->skillid = 0;
//Battle->atktype = NORMAL_ATTACK;
}
// use buff skill
void CCharacter::UseBuffSkill( CCharacter* Target, CSkills* skill )
{
bool bflag = false;
bflag = GServer->AddBuffs( skill, Target, GetInt( ) );
if(skill->nbuffs > 0 && bflag == true)
{
BEGINPACKET( pak, 0x7b5 );
ADDWORD ( pak, Target->clientid );
ADDWORD ( pak, clientid );
ADDWORD ( pak, Battle->skillid );
ADDWORD ( pak, GetInt( )/4 );
ADDBYTE ( pak, skill->nbuffs );
GServer->SendToVisible( &pak, Target );
//Log(MSG_DEBUG,"Buff Skill. buffs applied 1");
}
BEGINPACKET( pak, 0x7b9);
ADDWORD ( pak, clientid);
ADDWORD ( pak, Battle->skillid);
ADDWORD ( pak, 1);
GServer->SendToVisible( &pak, this );
//Log(MSG_DEBUG,"Buff Skill. buffs applied 2 nbuffs = %i",skill->nbuffs);
//Log(MSG_INFO,"Target HP = %i",Target->Stats->HP);
}
// Use a skill
bool CCharacter::UseSkill( CSkills* skill, CCharacter *Target )
{
if (skill->atkpower > 0)
{
Log(MSG_INFO, "Need to do %i%s %s in range %i to target %i",
( skill->atkpower ),
( (skill->range > 0) ? " AOE" : "" ),
( (GServer->isSkillTargetFriendly(skill)) ? "healing" : "damage" ),
( skill->range ),
( skill->target ) );
}
for (int i = 0; i < 2; i++) {
Log(MSG_INFO, "Status ID: %i", skill->status[i]);
if (skill->status[i] == 0) continue;
CStatus* status = GServer->GetStatusByID(skill->status[i]);
if (status == NULL) continue;
/************************
We'll probably need to use status->decrease (Figure out whether buf is up/down
status->repeat will tell us whether it's a one-time (Stat Boost [2]), repeat
(Recovery, continueing damage [1]) or Special (Status Effect [3]).
************************/
if (status->repeat == 1) // Continuous
{
Log(MSG_INFO, "Need to take stat %i and %s it by %i%s over %i seconds", skill->buff[i],
((status->decrease) ? "decrease" : "increase"),
((skill->value1[i] != 0) ? skill->value1[i] : skill->value2[i]),
((skill->value1[i] != 0) ? "" : "%"), skill->duration);
}
else if (status->repeat == 2) // Once (Stat Boost)
{
Log(MSG_INFO, "Need to take stat %i and %s it by %i%s for %i seconds", skill->buff[i],
((status->decrease) ? "decrease" : "increase"),
((skill->value1[i] != 0) ? skill->value1[i] : skill->value2[i]),
((skill->value1[i] != 0) ? "" : "%"), skill->duration);
} else if (status->repeat == 3) // Status Effect (Poison,etc)
{
Log(MSG_INFO, "Need to give user status effect %i for %i seconds", skill->buff[i],
((skill->value1[i] != 0) ? skill->value1[i] : skill->value2[i]),
( skill->duration ) );
}
}
return true;
}
+570
View File
@@ -0,0 +1,570 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://www.osrose.net
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
developed with Main erose/hrose source server + some change from the original eich source
*/
#include "character.h"
#include "worldserver.h"
// return true if this character is monster
bool CCharacter::IsMonster( )
{
if(CharType == 2 || CharType == 3)
return true;
return false;
}
// return true if this character is player
bool CCharacter::IsPlayer( )
{
if(CharType == 1)
return true;
return false;
}
//return true if this character is an NPC
bool CCharacter::IsNPC( )
{
if(CharType == 4)
return true;
return false;
}
// return true if HP is lower to 1
bool CCharacter::IsDead( )
{
if(Stats->HP <= 0)
return true;
return false;
}
// return true if this character is summon
bool CCharacter::IsSummon( )
{
if(this == NULL) return false;
if(CharType == 3)// this line is erroring. No idea why
return true;
return false;
}
// Virtual function [return item drop]
CDrop* CCharacter::GetDrop( )
{
return NULL;
}
// start action [attack]
void CCharacter::StartAction( CCharacter* Target, BYTE action, UINT skillid)
{
BEGINPACKET( pak, 0 );
switch(action)
{
case NORMAL_ATTACK:
{
//Log( MSG_INFO, "case NORMAL_ATTACK");
if(Target == NULL)return;
RESETPACKET( pak, 0x798 );
ADDWORD ( pak, clientid );
ADDWORD ( pak, Target->clientid );
ADDWORD ( pak, Stats->Move_Speed );
ADDFLOAT ( pak, Target->Position->current.x * 100 );
ADDFLOAT ( pak, Target->Position->current.y * 100 );
Battle->target = Target->clientid;
Battle->atktarget = Target->clientid;
Battle->atktype = action;
Battle->skilltarget = 0;
Battle->bufftarget = 0;
Battle->skillid = 0;
Position->destiny = Target->Position->current;
Position->lastMoveTime = clock();
}
break;
case SKILL_ATTACK: //Log( MSG_INFO, "case SKILL_ATTACK");
case SKILL_BUFF:
{
if(Target == NULL)return;
RESETPACKET( pak, 0x7b3 );
ADDWORD ( pak, clientid );
ADDWORD ( pak, Target->clientid );
ADDWORD ( pak, skillid );
ADDWORD ( pak, 0x0000 );
ADDFLOAT ( pak, Target->Position->current.x * 100 );
ADDFLOAT ( pak, Target->Position->current.y * 100 );
Battle->target = Target->clientid;
if(action == SKILL_ATTACK)
{
//Log( MSG_INFO, "case SKILL_ATTACK");
Battle->skilltarget = Target->clientid;
Battle->bufftarget = 0;
}
else
{
//Log( MSG_INFO, "case SKILL_BUFF");
Battle->bufftarget = Target->clientid;
Battle->skilltarget = 0;
}
Battle->atktype = action;
Position->destiny = Target->Position->current;
Battle->skillid = skillid;
Position->lastMoveTime = clock();
}
break;
case SKILL_AOE://Log( MSG_INFO, "case SKILL_AOE");
case BUFF_SELF://Log( MSG_INFO, "case BUFF_SELF");
case BUFF_AOE:
{
//Log( MSG_INFO, "case BUFF_AOE");
RESETPACKET( pak, 0x7b2);
ADDWORD ( pak, clientid );
ADDWORD ( pak, skillid );
Battle->atktype = action;
Battle->skillid = skillid;
//Log( MSG_INFO, "BUFF_AOE packet sent");
}
break;
case AOE_TARGET:
{
//Log( MSG_INFO, "case AOE_TARGET");
//Target is NULL for this function when cast by a player
//Target is NOT NULL when it comes from a monster
if(Target != NULL) //monster attack
{
Position->skilltargetpos.x = Target->Position->current.x;
Position->skilltargetpos.y = Target->Position->current.y;
}
RESETPACKET( pak, 0x7b4 );
ADDWORD ( pak, clientid );
ADDWORD ( pak, skillid );
ADDFLOAT ( pak, Position->skilltargetpos.x * 100 );
ADDFLOAT ( pak, Position->skilltargetpos.y * 100 );
Battle->atktype = action;
Battle->skillid = skillid;
Battle->skilltarget = 0;
Battle->bufftarget = 0;
}
break;
default:
return;
break;
}
GServer->SendToVisible( &pak, this );
Battle->contatk = true;
//Log(MSG_INFO,"Battle Attacktype = %i",Battle->atktype);
return;
}
bool CCharacter::IsOnBattle( )
{
if(Battle->atktype == 0)
{
if(Battle->iscasting == 1)
{
clock_t etime = clock() - Battle->lastAtkTime;
if( etime < CLOCKS_PER_SEC * 100 / Stats->Attack_Speed )
{
//Log(MSG_DEBUG,"Iscasting is true while NOT in battle. Reset to false.");
Battle->iscasting = 0;
return false;
}
}
return false;
}
switch(Battle->atktype)
{
case NORMAL_ATTACK:
{
if(Battle->atktarget != 0) return true;
}
break;
case SKILL_ATTACK:
case AOE_TARGET:
{
if(Battle->skilltarget != 0 && Battle->skillid != 0) return true;
}
break;
case SKILL_BUFF:
{
if(Battle->bufftarget != 0 && Battle->skillid != 0) return true;
}
break;
case SKILL_AOE:
//case SKILL_SELF: //no such skill type
case BUFF_SELF:
case BUFF_AOE:
{
if(Battle->skillid != 0) return true;
}
break;
default: return false;
}
}
bool CCharacter::CanAttack( )
{
clock_t etime = clock() - Battle->lastAtkTime;
if (Stats->Attack_Speed < 1)
{
Log( MSG_INFO, "weapon with no attackspeed.");
return false;
}
if(Battle->iscasting == 1)
{
if( etime < CLOCKS_PER_SEC * 25 / Stats->Attack_Speed ) //should make the delay 4 times longer
{
//if(IsPlayer())
// Log(MSG_INFO,"Cannot use magic attack yet. Last attack time = %i",Battle->lastAtkTime);
return false;
}
else
{
Battle->iscasting = 0;
//if(IsPlayer())
// Log(MSG_INFO,"OK Now we can use a new (magic or normal) attack.");
return true;
}
}
else //normal attack
{
if( etime < CLOCKS_PER_SEC * 100 / Stats->Attack_Speed )
{
//if(IsPlayer())
// Log(MSG_INFO,"Cannot attack yet. Last attack time = %i",Battle->lastAtkTime);
return false;
}
//if(IsPlayer())
// Log(MSG_INFO,"OK Now we can use a normal attack");
}
return true;
}
// return true if target is reached
bool CCharacter::IsTargetReached( CCharacter* Enemy, CSkills* skill )
{
CMap* map = GServer->MapList.Index[Position->Map];
if(map == NULL)return false;
float distance = GServer->distance( Position->current, Enemy->Position->current );
if(skill == NULL) //it's a normal attack
{
if(distance <= Stats->Attack_Distance)
{
return true;
}
else
{
Position->destiny = Enemy->Position->current;
}
}
else
{
if(distance <= skill->range)
{
return true;
}
else
{
Position->destiny = Enemy->Position->current;
}
}
//Log(MSG_INFO,"Monster cannot attack. Too far away");
return false;
}
// return true if the character is moving
bool CCharacter::IsMoving( )
{
if(Position->current.x == Position->destiny.x && Position->current.y == Position->destiny.y )
return false;
return true;
}
// VIRTUAL [add player damage]
void CCharacter::AddDamage( CCharacter* enemy, long int hitpower)
{
}
// return character target
CCharacter* CCharacter::GetCharTarget( )
{
CCharacter* thistarget = GServer->MapList.Index[Position->Map]->GetCharInMap( Battle->target );
if (thistarget != NULL)
return thistarget;
//if I don't currently have a target then return the character who just hit me
return GServer->MapList.Index[Position->Map]->GetCharInMap( Battle->hitby );
}
// VIRTUAL [reduce ammon/bullets/cannons]
void CCharacter::ReduceABC( )
{
}
// VIRTUAL [get extra buff value]
int CCharacter::GetEVBuff( )
{
return 0;
}
// VIRTUAL [return intelligence]
unsigned int CCharacter::GetInt( )
{
return 15;
}
// Check For Debuffs
void CCharacter::RefreshBuff( )
{
bool bflag = false;
for( UINT i=0;i<30;i++)
{
if(MagicStatus[i].Buff == 0) continue;
clock_t etime = clock() - MagicStatus[i].BuffTime;
if( etime >= MagicStatus[i].Duration * CLOCKS_PER_SEC )
{
switch(MagicStatus[i].Status)
{
case 18: // attack power up
case 19: // attack power down
case 48: // attack power up
if(i<15)
Status->Attack_up = 0xff;
else
Status->Attack_down = 0xff;
Stats->Attack_Power = GetAttackPower( );
break;
case 20: // def up
case 21: // def down
case 49: // def up
if(i<15)
Status->Defense_up= 0xff;
else
Status->Defense_down = 0xff;
Stats->Defense = GetDefense( );
break;
case 24: //accuracy up
case 25: //accuracy down
case 51: //attack accuracy up.
if(i<15)
Status->Accury_up= 0xff;
else
Status->Accury_down = 0xff;
Stats->Accury = GetAccury( );
break;
case 22: // macic resistance up
case 23: // magic resistance down
case 50: // magic resistance up
if(i<15)
Status->Magic_Defense_up = 0xff;
else
Status->Magic_Defense_down = 0xff;
Stats->Magic_Defense = GetMagicDefense( );
break;
case 28: //dodge up
case 29: //dodge down
case 53: //dodge rate up
if(i<15)
Status->Dodge_up = 0xff;
else
Status->Dodge_down = 0xff;
Stats->Dodge = GetDodge( );
break;
case 14: //dash
case 15: //slow
case 46: //movement speed increased
if(i<15)
Status->Dash_up = 0xff;
else
Status->Dash_down = 0xff;
Stats->Move_Speed = GetMoveSpeed( );
break;
case 16: // haste attack
case 17: // slow attack
case 47: // attack speed up
if(i<15)
Status->Haste_up = 0xff;
else
Status->Haste_down = 0xff;
Stats->Attack_Speed = GetAttackSpeed( );
break;
case 26: // crit up
case 27: // crit down
case 52: // crit up
if(i<15)
Status->Critical_up = 0xff;
else
Status->Critical_down = 0xff;
Stats->Critical = GetCritical( );
break;
case 12: // max HP up
case 44: // max HP up
if(i<15)
Status->HP_up = 0xff;
else
Status->HP_down = 0xff;
Stats->MaxHP = GetMaxHP( );
break;
case 13: // max MP up
case 45: // max MP up
if(i<15)
Status->MP_up = 0xff;
else
Status->MP_down = 0xff;
Stats->MaxMP = GetMaxMP( );
break;
case 32: // faint
Status->Stuned = 0xff;
Status->CanAttack = true;
//printf("removing stun\n");
break;
case 7: case 8: case 9: case 10: case 11: //poisoned
Status->Poisoned = 0xff;
//printf("removing poison\n");
break;
case 30: // muted
Status->Muted = 0xff;
Status->CanCastSkill = true;
break;
case 31: // sleep May need to be fixed later to accomodate multiple status effects.
Status->Sleep = 0xff;
Status->CanMove = true;
Status->CanCastSkill = true;
Status->CanAttack = true;
break;
case 54: //A_GMExtra_Damage:
case 36: //A_Extra_Damage:
if(i<15)
{
Status->ExtraDamage_up = 0xff;
Stats->ExtraDamage = 0xff;
}
else
{
Status->ExtraDamage_down = 0xff;
Stats->ExtraDamage = 0xff;
}
break;
case 56: // Taunt
Status->Taunt = 0xff;
break;
}
MagicStatus[i].Status = 0;
MagicStatus[i].Buff = 0;
MagicStatus[i].BuffTime = 0;
MagicStatus[i].Duration = 0;
MagicStatus[i].Value = 0;
bflag = true;
}
else if (MagicStatus[i].Status >= 7 && MagicStatus[i].Status <= 11 && etime > 1*CLOCKS_PER_SEC) //Do poison dmg every 1.5 seconds
{
Stats->HP -= MagicStatus[i].Status; //Actually take 7, 8, 9, 10 or 11 from the health. Based on the Status itself
MagicStatus[i].BuffTime += 1*CLOCKS_PER_SEC;
MagicStatus[i].Duration -= 1;
//printf("did %i poison dmg to the player, still %i seconds and %i HP remain \n", MagicStatus[i].Status, MagicStatus[i].Duration, Stats->HP);
//A bunch of messy code to send dmg packet
BEGINPACKET( pak, 0x7b6 );
ADDWORD ( pak, clientid );
ADDWORD ( pak, 0 );
ADDDWORD ( pak, 0x000007f8 );
ADDBYTE ( pak, 0x00 );
ADDDWORD ( pak, MagicStatus[i].Status );
//If Enemy is killed
if( IsDead())
{
//printf("char died\n");
CDrop* thisdrop = NULL;
ADDDWORD ( pak, 16 );
if( !IsSummon( ) && !IsPlayer( ))
{
thisdrop = GetDrop( );
if( thisdrop!=NULL)
{
ADDFLOAT ( pak, thisdrop->pos.x*100 );
ADDFLOAT ( pak, thisdrop->pos.y*100 );
if( thisdrop->type==1)
{
ADDDWORD( pak, 0xccccccdf );
ADDDWORD( pak, thisdrop->amount );
}
else
{
ADDDWORD ( pak, GServer->BuildItemHead( thisdrop->item ) );
ADDDWORD ( pak, GServer->BuildItemData( thisdrop->item ) );
}
ADDWORD ( pak, thisdrop->clientid );
ADDWORD ( pak, thisdrop->owner );
CMap* map = GServer->MapList.Index[thisdrop->posMap];
map->AddDrop( thisdrop );
}
}
GServer->SendToVisible( &pak, this, thisdrop );
}
//If enemy is still alive
else
{
ADDDWORD ( pak, 4 );
GServer->SendToVisible( &pak, this );
}
}
}
if(bflag)
{
BEGINPACKET( pak,0x7b7 );
ADDWORD ( pak, clientid );
ADDDWORD ( pak, GServer->BuildBuffs( this ) );
GServer->SendToVisible( &pak, this );
}
}
// VIRTUAL [return party pointer]
CParty* CCharacter::GetParty( )
{
return NULL;
}
// VIRTUAL [return clan pointer]
CLAN* CCharacter::GetClan( )
{
return NULL;
}
bool CCharacter::IsAttacking( )
{
if(IsOnBattle( ))
{
switch(Battle->atktype)
{
case SKILL_BUFF:
case BUFF_SELF:
case BUFF_AOE:
return false;
}
}
else return false;
return true;
}
+478
View File
@@ -0,0 +1,478 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://www.osrose.net
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "worldserver.h"
// Map Process
PVOID MapProcess( PVOID TS )
{
bool only_npc = false;
while(GServer->ServerOnline)
{
pthread_mutex_lock( &GServer->PlayerMutex );
pthread_mutex_lock( &GServer->MapMutex );
for(UINT i=0;i<GServer->MapList.Map.size();i++)
{
CMap* map = GServer->MapList.Map.at(i);
if( map->PlayerList.size()<1 )
only_npc = true;
else
only_npc = false;
//continue;
if(!only_npc)
{
// Player update //------------------------
for(UINT j=0;j<map->PlayerList.size();j++)
{
CPlayer* player = map->PlayerList.at(j);
if(!player->Session->inGame && player->Session->Respawned == 1) //only set in pakUserDied on receiving respawn packet 0x753
{
Log( MSG_INFO, "ingame: = %i respawned: = %i",player->Session->inGame,player->Session->Respawned);
if(!player->RespawnPlayer(player)) //so we respawn the player
{
Log( MSG_INFO, "Player not respawned correctly");
}
else
{
Log( MSG_INFO, "Player Respawned" );
}
player->Session->inGame = true;
player->Session->Respawned = 2; //testing toggle
}
if(player->IsDead( )) continue;
if(player->UpdateValues( )) //checks if player is on a cart. otherwise returns true
{
//if(player->Session->Respawned == 2){Log( MSG_INFO, "Running UpdatePosition" );}
player->UpdatePosition( );
//if(player->Session->Respawned == 2){Log( MSG_INFO, "ran UpdatePosition" );}
}
if(player->IsOnBattle( ))
{
//if(player->Session->Respawned == 2){Log( MSG_INFO, "Player is in battle so call DoAttack" );}
player->DoAttack( );
//if(player->Session->Respawned == 2){Log( MSG_INFO, "ran DoAttack" );}
}
player->RefreshBuff( );
//if(player->Session->Respawned == 2){Log( MSG_INFO, "ran refreshbuff" );}
player->PlayerHeal( );
//if(player->Session->Respawned == 2){Log( MSG_INFO, "ran playerheal" );}
player->Regeneration( );
//if(player->Session->Respawned == 2){Log( MSG_INFO, "ran regeneration" );}
player->CheckPlayerLevelUP( );
//if(player->Session->Respawned == 2){Log( MSG_INFO, "ran Check Levelup" );}
if(3600000 < (UINT)GServer->round((clock( ) - player->Session->LogTime))) //1 hour since login
{
//if(player->Session->Respawned == 2){Log( MSG_INFO, "updating logtime stuff" );}
player->Session->logtime += 1;
player->Session->TotalLogTime ++;
GServer->DB->QExecute("UPDATE accounts SET logtime = %i, totlogtime = %i WHERE id = %i", player->Session->logtime, player->Session->TotalLogTime, player->Session->userid);
player->Session->LogTime = clock();
}
//if(player->Session->Respawned == 2){Log( MSG_INFO, "Checking autosave" );}
if( GServer->Config.AUTOSAVE == 1 )
{
clock_t etime = clock() - player->lastSaveTime;
if( etime >= GServer->Config.SAVETIME*1000 )
{
player->savedata( );
player->lastSaveTime = clock();
}
//if(player->Session->Respawned == 2){Log( MSG_INFO, "saved player data" );}
}
//if(player->Session->Respawned == 2){Log( MSG_INFO, "Checking ItemXPTimer" );}
if(player->Stats->ItemXPTimer > 0) // does the player have a timed XPRate buff?
{
clock_t etime = clock() - player->Stats->ItemXPTime;
if(etime >= player->Stats->ItemXPTimer) // turn off timed XPRate buff when time exceeds timer
{
player->Stats->ItemXPTime = 0;
player->Stats->ItemXPRate = 1;
}
//if(player->Session->Respawned == 2){Log( MSG_INFO, "set XPRates and stuff" );}
}
player->Session->Respawned = 0; //resetting respawned status
}
// Monster update //------------------------
pthread_mutex_lock( &map->MonsterMutex );
//spawn TD monsters
unsigned nextmon = map->TDMobList[map->TDNextSpawn];
if(nextmon != 0)
{
//Log(MSG_DEBUG,"Spawning TD mobs");
clock_t etime = clock() - map->lastTDSpawnTime;
if(etime >= map->TDMobDelay) // check if elapsed time is greater than spawn delay
{
//spawn the next monster on the list
//Log(MSG_DEBUG,"Spawning TD mob of type %i at position %i in the list for map %i",nextmon, map->TDNextSpawn, map->id);
map->AddMonster(nextmon, GServer->WPList[map->id][1].pos, 0, 0, 0, 1, 0, 999 ); //spawn a TD mob with no AI
//Log(MSG_DEBUG,"Spawned mob in addmonster");
map->TDMobList[map->TDNextSpawn] = 0; //clear the spawn
//Log(MSG_DEBUG,"cleared the spawn");
map->TDNextSpawn++; //move the pointer
//Log(MSG_DEBUG,"moved the pointer");
if(map->TDNextSpawn > 100)map->TDNextSpawn = 0;
map->lastTDSpawnTime = clock();
}
}
//TD spawn end
for(UINT j=0;j<map->MonsterList.size();j++)
{
CMonster* monster = map->MonsterList.at(j);
//UINT thistimer = monster->AItimer;
clock_t etime = clock() - monster->lastAiUpdate;
//if(etime < monster->AItimer) continue; //not time to run AI for this monster yet
if(monster->hitcount == 0xFF)//this is a delay for new monster spawns this might olso fix invisible monsters(if they attack directly on spawning the client dosn't get the attack packet(its not in it's visible list yet))
{
monster->hitcount = 0;
//monster->DoAi(monster->thisnpc->AI, 0);
monster->DoAi(monster->monAI, 0);
monster->lastAiUpdate=clock();
}
//still need this for special spawns
if(!map->IsNight( ) && monster->Status->nightonly)// if day, delete all night time monsters
{
//Log( MSG_INFO, "Night Only monster deleted. Type %i", monster->montype);
map->DeleteMonster( monster, true, j );
continue;
}
if(map->IsNight() && monster->Status->dayonly)
{
//Log( MSG_INFO, "Day Only monster deleted. Type %i", monster->montype);
map->DeleteMonster( monster, true, j );
continue;
}
//Do TD stuff
if(monster->monAI == 999 && etime >= monster->AItimer) //It's a TD mob
{
monster->UpdatePosition( );
float distance = GServer->distance( monster->Position->current, monster->Position->destiny );
//Log( MSG_INFO, "Found a TD monster %f from target. Waypoint type = %i stance %i speed %i", distance,GServer->WPList[map->id][monster->NextWayPoint].WPType,monster->Stats->stance, monster->Stats->Move_Speed);
//Log( MSG_INFO, "monster location X: %f Y: %f",monster->Position->current.x, monster->Position->current.y);
//Log( MSG_INFO, "WP location X: %f Y: %f ", GServer->WPList[map->id][monster->NextWayPoint].pos.x,GServer->WPList[map->id][monster->NextWayPoint].pos.y);
if(distance < 1) //monster has reached it's destination
{
switch(GServer->WPList[map->id][monster->NextWayPoint].WPType)
{
case 1: //Start waypoint
case 2: //regular waypoint. Increment waypoint counter. Set detiny to next waypoint
{
//Log( MSG_INFO, "Monster reached waypoint %i type: %i", monster->NextWayPoint,GServer->WPList[map->id][monster->NextWayPoint].WPType);
monster->NextWayPoint++;
monster->Position->destiny.x = GServer->WPList[map->id][monster->NextWayPoint].pos.x;
monster->Position->destiny.y = GServer->WPList[map->id][monster->NextWayPoint].pos.y;
BEGINPACKET( pak, 0x797 );
ADDWORD ( pak, monster->clientid );
ADDWORD ( pak, 0x0000 );
ADDWORD ( pak, monster->Stats->Move_Speed ); //speed
ADDFLOAT ( pak, monster->Position->destiny.x * 100 );
ADDFLOAT ( pak, monster->Position->destiny.y * 100 );
ADDWORD ( pak, 0xcdcd );
ADDBYTE ( pak, monster->Stats->stance ); //should be walking
GServer->SendToVisible(&pak, monster);
}
break;
case 3: //Final waypoint. do stuff. suicide
{
//Log( MSG_INFO, "Reached final waypoint");
//monster->Stats->HP = 0;
map->DeleteMonster( monster, true, j );
//Log( MSG_INFO, "monster successfully deleted");
continue;
}
break;
default:
Log( MSG_INFO, "WPType %i not recognized",GServer->WPList[map->id][monster->NextWayPoint].WPType);
break;
}
}
else
{
//send move packet again to try to synchronise the monster movement
BEGINPACKET( pak, 0x797 );
ADDWORD ( pak, monster->clientid );
ADDWORD ( pak, 0x0000 );
ADDWORD ( pak, monster->Stats->Move_Speed ); //speed
ADDFLOAT ( pak, monster->Position->destiny.x * 100 );
ADDFLOAT ( pak, monster->Position->destiny.y * 100 );
ADDWORD ( pak, 0xcdcd );
ADDBYTE ( pak, monster->Stats->stance ); //should be walking
GServer->SendToVisible(&pak, monster);
}
monster->lastAiUpdate = clock();
}
//end TD stuff
if(!monster->PlayerInRange( )) continue;
//if(!monster->UpdateValues( )) continue;
monster->UpdatePosition( );
if(monster->IsOnBattle( ))
{
monster->DoAttack( ); // why was this commented? Monsters were not attacking
//monster->DoAi(monster->thisnpc->AI, 2); //don't use thisnpc->AI any more.
if(etime >= monster->AItimer)
{
monster->DoAi(monster->monAI, 2);
monster->lastAiUpdate = clock();
}
//Log(MSG_INFO,"Monster type: %i current HP: %i",monster->montype, monster->Stats->HP);
}
else
{
//monster->DoAi(monster->thisnpc->AI, 1);
if(etime >= monster->AItimer)
{
monster->DoAi(monster->monAI, 1);
monster->lastAiUpdate = clock();
}
}
monster->RefreshBuff( );
if (monster->IsSummon())
{
monster->SummonUpdate(monster,map, j);
continue;
}
if(monster->IsDead())
{
if(clock() - monster->DeathDelayTimer > GServer->Config.DeathDelay)
{
//Log(MSG_DEBUG,"Found dead monster montype %i",monster->montype);
monster->OnDie( ); //all this does is give exp
//Log(MSG_DEBUG,"back from giving exp");
monster->DoAi(monster->monAI, 5);
//Log(MSG_DEBUG,"ran AI");
map->DeleteMonster( monster, true, j );
//Log(MSG_DEBUG,"deleted monster");
continue;
}
/*else
{
Log(MSG_DEBUG,"Dead monster found. waiting for death delay timer");
}*/
}
}
}
if(only_npc)
pthread_mutex_lock( &map->MonsterMutex );
//AIP for NPCs
for(UINT j=0;j<map->NPCList.size();j++)
{
CNPC* npc = map->NPCList.at(j);
if(npc->thisnpc->AI != 0)
{
CAip* script = NULL;
for(unsigned k=0; k < GServer->AipList.size(); k++)
{
if (GServer->AipList.at(k)->AInumber == npc->thisnpc->AI)
{
script = GServer->AipList.at(k);
break;
}
}
if(script == NULL)
{
//Log( MSG_WARNING, "Invalid AI script for AI %i", npc->thisnpc->AI );
continue;
}
UINT thistimer = script->minTime * 1000; //seems to be set in seconds in AIP
if(thistimer<(UINT)GServer->round((clock( ) - npc->lastAiUpdate))) //check AIP conditions when the timer calls for it
{
CNPCData* thisnpc = GServer->GetNPCDataByID( npc->npctype );
if(thisnpc == NULL)
{
Log( MSG_WARNING, "Invalid montype %i", npc->npctype );
continue;
}
CMonster* monster = new (nothrow) CMonster( npc->pos, npc->npctype, map->id, 0, 0 );
monster->thisnpc = thisnpc;
monster->CharType = 4;
int AIP = monster->thisnpc->AI;
int lma_previous_eventID = npc->thisnpc->eventid;
monster->DoAi(monster->thisnpc->AI, 1);
//check if eventID changed, if we do it in AIP conditions / actions, it just fails...
if (lma_previous_eventID != npc->thisnpc->eventid)
{
//Log(MSG_WARNING,"Event ID not the same NPC %i from %i to %i in map %i, npc->thisnpc->eventid=%i !", npc->npctype, lma_previous_eventID, monster->thisnpc->eventid, map->id, npc->thisnpc->eventid);
npc->thisnpc->eventid = monster->thisnpc->eventid;
BEGINPACKET( pak, 0x790 );
ADDWORD ( pak, npc->clientid );
ADDWORD ( pak, npc->thisnpc->eventid );
GServer->SendToMap(&pak, map->id);
}
if(AIP == GServer->Config.AIWatch)
Log(MSG_DEBUG,"NPC AI number %i successfully run",monster->thisnpc->AI);
if(monster->IsOnBattle())
{
//Log(MSG_DEBUG,"NPC %i is registered as in battle",monster->thisnpc->id);
monster->DoAttack( );
}
//map->DeleteMonster(monster);
//delete monster;
npc->lastAiUpdate = clock();
if(AIP == GServer->Config.AIWatch)
Log(MSG_DEBUG,"LastAiUpdate clock reset");
}
}
//LMA: Sometimes another NPC does the job for you.
if(npc->thisnpc->eventid != GServer->ObjVar[npc->npctype][0])
{
int new_event_id = GServer->ObjVar[npc->npctype][0];
//Log(MSG_WARNING,"(2)Event ID not the same NPC %i from %i to %i in map %i, npc->thisnpc->eventid=%i !",npc->npctype,npc->thisnpc->eventid,new_event_id,map->id,npc->thisnpc->eventid);
npc->thisnpc->eventid = new_event_id;
//LMA: We have to change the event ID here since we didn't send the clientID :(
BEGINPACKET( pak, 0x790 );
ADDWORD ( pak, npc->clientid );
ADDWORD ( pak, npc->thisnpc->eventid );
GServer->SendToMap(&pak,map->id);
}
}
pthread_mutex_unlock( &map->MonsterMutex );
}
pthread_mutex_unlock( &GServer->MapMutex );
pthread_mutex_unlock( &GServer->PlayerMutex );
#ifdef _WIN32
Sleep(GServer->Config.MapDelay);
#else
usleep(GServer->Config.MapDelay);
#endif
}
pthread_exit( NULL );
return 0;
}
// Visibility Process
PVOID VisibilityProcess(PVOID TS)
{
while(GServer->ServerOnline)
{
pthread_mutex_lock( &GServer->PlayerMutex );
pthread_mutex_lock( &GServer->MapMutex );
for(UINT i=0;i<GServer->MapList.Map.size();i++)
{
CMap* map = GServer->MapList.Map.at(i);
map->CleanDrops( );//moved for test
map->RespawnMonster( );//moved for test
if( map->PlayerList.size()<1 )
continue;
for(UINT j=0;j<map->PlayerList.size();j++)
{
CPlayer* player = map->PlayerList.at(j);
if(!player->Session->inGame) continue;
if(!player->VisiblityList()) Log(MSG_WARNING, "Visibility False: %u", player->clientid );
}
}
pthread_mutex_unlock( &GServer->MapMutex );
pthread_mutex_unlock( &GServer->PlayerMutex );
#ifdef _WIN32
Sleep(GServer->Config.VisualDelay);
#else
usleep(GServer->Config.VisualDelay);
#endif
}
pthread_exit(NULL);
return 0;
}
// World Process
PVOID WorldProcess( PVOID TS )
{
while( GServer->ServerOnline )
{
pthread_mutex_lock( &GServer->MapMutex );
for(UINT i=0;i<GServer->MapList.Map.size();i++)
{
CMap* map = GServer->MapList.Map.at(i);
if( map->PlayerList.size()<1 )
continue;
map->UpdateTime( );
pthread_mutex_lock( &map->DropMutex );
//map->CleanDrops( );
pthread_mutex_unlock( &map->DropMutex );
pthread_mutex_lock( &map->MonsterMutex );
//map->RespawnMonster( );
pthread_mutex_unlock( &map->MonsterMutex );
}
pthread_mutex_unlock( &GServer->MapMutex );
GServer->RefreshFairy( );
#ifdef _WIN32
Sleep(GServer->Config.WorldDelay);
#else
usleep(GServer->Config.WorldDelay);
#endif
}
pthread_exit(NULL);
return 0;
}
// Shutdown Server Process
void ShutdownServer(PVOID TS)
{
int minutes = (int)TS;
#ifdef _WIN32
Sleep(minutes*60000);
#else
usleep(minutes*60000);
#endif
Log( MSG_INFO, "Saving User Information... " );
GServer->DisconnectAll();
Log( MSG_INFO, "Waiting Process to ShutDown... " );
GServer->ServerOnline = false;
int status,res;
res = pthread_join( GServer->WorldThread[0], (PVOID*)&status );
if(res)
{
Log( MSG_WARNING, "World thread can't be joined" );
}
else
{
Log( MSG_INFO, "World thread closed." );
}
res = pthread_join( GServer->WorldThread[1], (PVOID*)&status );
if(res)
{
Log( MSG_WARNING, "Visibility thread can't be joined" );
}
else
{
Log( MSG_INFO, "Visibility thread closed." );
}
res = pthread_join( GServer->MapThread[0], (PVOID*)&status );
if(res)
{
Log( MSG_WARNING, "Map thread can't be joined" );
}
else
{
Log( MSG_INFO, "Map thread closed." );
}
Log( MSG_INFO, "All Threads Closed." );
GServer->isActive = false;
pthread_exit(NULL);
}
+195
View File
@@ -0,0 +1,195 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://www.osrose.net
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "worldmonster.h"
// update attack values and destiny position
bool CMonster::UpdateValues( )
{
return true; //bypass for AIP
/*if(IsSummon( ))
{
CPlayer* thisclient = GetOwner( );
if(thisclient!=NULL)if(thisclient->Stats->HP>0)
{
if(!IsOnBattle( ) && thisclient->IsAttacking( ))
{
Battle->target = thisclient->Battle->target;
Battle->atktarget = Battle->target;
Battle->atktype = NORMAL_ATTACK;
Battle->contatk = true;
CCharacter* Enemy = GetCharTarget( );
if(Enemy!=NULL)
StartAction( Enemy, NORMAL_ATTACK );
}
else
if(!IsOnBattle( ))
{
Position->source = thisclient->Position->current;
float distance = GServer->distance( Position->destiny , thisclient->Position->current );
if((distance>15 && !IsOnBattle()) || distance>50)
Move( );
}
}
else
{
UnspawnMonster( );
return false;
}
}
if(!IsMoving( ) && !IsOnBattle( ) && CanMove( ))
{
clock_t etime = clock() - Position->lastMoveTime;
if(etime > 20*CLOCKS_PER_SEC)
Move( );
}
if(!IsSummon( ))
{
CPlayer* player = GetNearPlayer( 10 );
if(player!=NULL)
OnEnemyOnSight( (CCharacter*)player );
CCharacter* Enemy = GetCharTarget( );
if(Enemy!=NULL)
{
//need a skill timer here. It casts all teh time otherwise.
int randv = GServer->RandNumber(1, 100);
if(randv < 50 || GServer->Config.MobSkill == 0)//normal attack
{
StartAction( Enemy, NORMAL_ATTACK );
}
else //skill attack
{
CSkills* skill = GServer->GetSkillByID(GServer->Config.MobSkill);
switch (skill->type)
{
case 6:
Log( MSG_DEBUG, "Monster used an attack skill. id = %i",GServer->Config.MobSkill);
StartAction( Enemy, SKILL_ATTACK, GServer->Config.MobSkill);
break;
case 17:
Log( MSG_DEBUG, "Monster used an AOE skill. id = %i",GServer->Config.MobSkill);
StartAction( Enemy, SKILL_AOE, GServer->Config.MobSkill);
break;
}
}
}
}*/
if(IsMonster( ))
{}
return true;
}
// Spawn a monster
void CMonster::SpawnMonster( CPlayer* player, CMonster* thismon )
{
BEGINPACKET( pak, 0x792 );
ADDWORD ( pak, clientid );
ADDFLOAT ( pak, Position->current.x*100 );
ADDFLOAT ( pak, Position->current.y*100 );
ADDFLOAT ( pak, Position->destiny.x*100 );
ADDFLOAT ( pak, Position->destiny.y*100 );
/*
if(IsDead( ))
{
ADDWORD ( pak, 0x0003 );
ADDWORD ( pak, 0x0000 );
}
else if(IsOnBattle( ))
{
ADDWORD ( pak, 0x0002 );
ADDWORD ( pak, Battle->target );
}
else if(IsMoving( ))
{
ADDWORD ( pak, 0x0001 );
ADDWORD ( pak, 0x0000 );
}
else
{
ADDWORD ( pak, 0x0000 );
ADDWORD ( pak, 0x0000 );
}
*/
ADDBYTE ( pak, 0x00 );
ADDDWORD ( pak, 0x00000000 );
ADDDWORD ( pak, Stats->HP );
if(thismon->owner != player->clientid)
{
CMap* map = GServer->MapList.Index[Position->Map];
if(IsSummon( ) && map->allowpvp!=0) {ADDDWORD( pak, 0x00000064 );} //Hostil
else if (IsSummon( ) && map->allowpvp==0) {ADDDWORD ( pak, 0x00000000 );}//Friendly
else {ADDDWORD( pak, 0x00000064 );} //Hostil
}
else {ADDDWORD( pak, 0x00000000 );}//Friendly
ADDDWORD( pak, GServer->BuildBuffs( this ) );
ADDWORD ( pak, montype );
ADDWORD ( pak, 0x0000 );
if(IsSummon( ))
{
ADDWORD( pak, owner );
ADDWORD( pak, 0x0000 ); //id del skill (si es summon de skill)
}
player->client->SendPacket( &pak );
}
// UnSpawn a Monster Why the fuck do we need this??????????
bool CMonster::UnspawnMonster( )
{
Log( MSG_INFO, "Unspawning monster %i ",this->montype);
GServer->MapList.Index[Position->Map]->DeleteMonster( this, true );
return true;
}
// Move a mob (random place)
void CMonster::Move( )
{
Position->destiny = GServer->RandInCircle( Position->source, 5 );
Position->lastMoveTime = clock();
//ClearBattle( Battle );
BEGINPACKET( pak, 0x797 );
ADDWORD ( pak, clientid );
ADDWORD ( pak, 0x0000 );//???
ADDWORD ( pak, Stats->Move_Speed ); //speed
ADDFLOAT ( pak, Position->destiny.x*100 );
ADDFLOAT ( pak, Position->destiny.y*100 );
ADDWORD ( pak, 0xcdcd );
//ADDBYTE ( pak, 0x01 ); //replaced for AIP
ADDBYTE ( pak, Stats->stance );
GServer->SendToVisible(&pak, this);
}
// Move a mob (specified point)
void CMonster::MoveTo( fPoint nPos, bool randcircle )
{
if(randcircle) Position->destiny = GServer->RandInCircle( nPos, 5 );
else Position->destiny = nPos;
Position->lastMoveTime = clock();
BEGINPACKET( pak, 0x797 );
ADDWORD ( pak, clientid );
ADDWORD ( pak, 0x0000 ); // ???
ADDWORD ( pak, Stats->Move_Speed );
ADDFLOAT ( pak, Position->destiny.x*100 );
ADDFLOAT ( pak, Position->destiny.y*100 );
ADDWORD ( pak, 0xcdcd );
//ADDBYTE ( pak, 0x01 ); // replaced for AIP
ADDBYTE ( pak, Stats->stance);
GServer->SendToVisible(&pak, this );
}
+21
View File
@@ -0,0 +1,21 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://www.osrose.net
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "worldmonster.h"
+435
View File
@@ -0,0 +1,435 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://www.osrose.net
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "worldmonster.h"
// called when a monster is attacked [attack/use atk skill/use buff/run/summon]//Enemy is the one attacking?
bool CMonster::OnBeAttacked( CCharacter* Enemy )
{
Battle->hitby = Enemy->clientid;
if(!IsOnBattle( ))
{
CMap* map = GServer->MapList.Index[Position->Map];
map->UpdateSpawnCounter( montype, Status->spawnid, 3); // update the counters
if(thisnpc->aggresive == 0) //prevent monsters with zero aggresion fighting back.
return true;
//StartAction( Enemy, NORMAL_ATTACK, 0 ); // temporary removal for testing
}
return true;
}
// called when a monster die [give exp/give extra drop]
bool CMonster::OnDie( )
{
/* Don't need this now. AIP takes care of it.
CMap* map = GServer->MapList.Index[Position->Map];
if(map->ghost!=0)
{
if((map->IsNight( ) || map->ghost==2) && !IsGhost( ) && !IsGhostSeed( ) && !IsSummon( ))
{
UINT gs = GServer->RandNumber( 0, 100 );
if(gs<30) // 30% / 70%
{ // spawn a ghost seed [for now will be 701 [level 1 ghost seed] ]
map->AddMonster( 701, Position->current, 0, Position->respawn, 0 );
}
}
}*/
GServer->GiveExp( this );
return true;
}
// called when we create a new monster [attack players?]
bool CMonster::OnSpawn( bool Attack )
{
if(IsGhost( ) && Attack )
{
CPlayer* player = GetNearPlayer( );
if(player == NULL) // no players or too far
return true;
StartAction( (CCharacter*)player, NORMAL_ATTACK, 0 );
}
return true;
}
// [not]called when a monster is almost dead [run/use only skills/call a healer? :S xD]
bool CMonster::OnAlmostDie( )
{
return true;
}
// called when a enemy is on sight
bool CMonster::OnEnemyOnSight( CCharacter* Enemy )
{
//return true //enable for AI stuff
clock_t etime = clock() - lastSighCheck;
if(etime<5000) return true;
if(!IsOnBattle( ))
{
if(thisnpc->aggresive>1)
{
UINT aggro = GServer->RandNumber(2,15);
if(thisnpc->aggresive>=aggro && !IsGhostSeed( ))
{
StartAction( (CCharacter*) Enemy, NORMAL_ATTACK, 0 );
}
else
if(IsGhostSeed( ) || thisnpc->aggresive>5)
MoveTo( Enemy->Position->current, true );
}
lastSighCheck = clock();
}
return true;
}
// called when enemy die
bool CMonster::OnEnemyDie( CCharacter* Enemy )
{
Position->destiny = Position->source;
ClearBattle( Battle );
MoveTo( Position->source );
return true;
}
bool CMonster::OnFar( )
{
if(!IsSummon())return true;
Position->destiny = Position->source;
ClearBattle( Battle );
MoveTo( Position->source );
return true;
}
/*bool CMonster::Guardiantree(CMonster* monster,CMap* map)
{
return true;
if(Stats->HP>9000)monster->hitcount=0;
switch (monster->hitcount)
{
case 0:
if(Stats->HP<9000)
{
for(unsigned char i=0;i<5;i++){
fPoint position = GServer->RandInCircle( monster->Position->current, 5 );
CMonster* newmonster=map->AddMonster( 210, position, 0, 0, 10 );
newmonster->hitcount=0;
}
monster->hitcount=1;
}
break;
case 1:
if(Stats->HP<8000)
{
/* for(unsigned char i=0;i<5;i++){
fPoint position = GServer->RandInCircle( monster->Position->current, 5 );
CMonster* newmonster=map->AddMonster( 210, position, 0, NULL, NULL, 0, true );
newmonster->hitcount=0;
}*/
/*monster->hitcount=2;
}
break;
case 2:
if(Stats->HP<7000)
{
for(unsigned char i=0;i<5;i++){
fPoint position = GServer->RandInCircle( monster->Position->current, 5 );
CMonster* newmonster=map->AddMonster( 210, position, 0, NULL, NULL, 0, true );
newmonster->hitcount=0;
}
monster->hitcount=3;
}
break;
case 3:
if(Stats->HP<6000)
{
/* for(unsigned char i=0;i<5;i++){
fPoint position = GServer->RandInCircle( monster->Position->current, 5 );
CMonster* newmonster=map->AddMonster( 210, position, 0, NULL, NULL, 0, true );
newmonster->hitcount=0;
}*/
/*monster->hitcount=4;
}
break;
case 4:
if(Stats->HP<5000)
{
for(unsigned char i=0;i<5;i++)
{
fPoint position = GServer->RandInCircle( monster->Position->current, 5 );
CMonster* newmonster=map->AddMonster( 210, position, 0, NULL, NULL, 0, true );
newmonster->hitcount=0;
}
monster->hitcount=5;
CDrop* thisdrop = new CDrop;
assert(thisdrop);
thisdrop->clientid = GServer->GetNewClientID();
thisdrop->type = 2; // ITEM
thisdrop->pos = GServer->RandInCircle( monster->Position->current, 3 );
thisdrop->posMap = monster->Position->Map;
thisdrop->droptime = time(NULL);
thisdrop->amount = 1;
thisdrop->item.count = thisdrop->amount;
thisdrop->owner = 0;
thisdrop->item.itemtype=10;
thisdrop->item.itemnum=rand()%4+10;
map->AddDrop( thisdrop );
}
break;
case 5:
if(Stats->HP<4000)
{
/* for(unsigned char i=0;i<5;i++){
fPoint position = GServer->RandInCircle( monster->Position->current, 5 );
CMonster* newmonster=map->AddMonster( 210, position, 0, NULL, NULL, 0, true );
newmonster->hitcount=0;
}*/
/*monster->hitcount=6;
}
break;
case 6:
if(Stats->HP<3000)
{
for(unsigned char i=0;i<5;i++){
fPoint position = GServer->RandInCircle( monster->Position->current, 5 );
CMonster* newmonster=map->AddMonster( 210, position, 0, NULL, NULL, 0, true );
newmonster->hitcount=0;
}
monster->hitcount=7;
CDrop* thisdrop = new CDrop;
assert(thisdrop);
thisdrop->clientid = GServer->GetNewClientID();
thisdrop->type = 2; // ITEM
thisdrop->pos = GServer->RandInCircle( monster->Position->current, 3 );
thisdrop->posMap = monster->Position->Map;
thisdrop->droptime = time(NULL);
thisdrop->amount = 1;
thisdrop->item.count = thisdrop->amount;
thisdrop->owner = 0;
thisdrop->item.itemtype=10;
thisdrop->item.itemnum=rand()%4+29;
map->AddDrop( thisdrop );
}
break;
case 7:
if(Stats->HP<2000)
{
/* for(unsigned char i=0;i<5;i++){
fPoint position = GServer->RandInCircle( monster->Position->current, 5 );
CMonster* newmonster=map->AddMonster( 210, position, 0, NULL, NULL, 0, true );
newmonster->hitcount=0;
}*/
/*monster->hitcount=8;
}
break;
default:
monster->hitcount=9;
}
return true;
}
*/
/*bool CMonster::Scarab(CMonster* monster,CMap* map)
{
return true;
fPoint position;
CMonster* othermon;
CMonster* newmonster;
if (monster->hitcount>5)monster->hitcount=0;
switch (monster->hitcount)
{
case 0:
position = GServer->RandInCircle( monster->Position->current, 1 );
newmonster=map->AddMonster( 210, position, 0, NULL, NULL, 0, true );
newmonster->hitcount=1;
GServer->ClearClientID( monster->clientid );
for(UINT i=0;i<map->MonsterList.size();i++)
{
othermon = map->MonsterList.at(i);
if(othermon==monster)
{
map->MonsterList.erase( map->MonsterList.begin()+i );
delete monster;
}
}
break;
case 1:
position = GServer->RandInCircle( monster->Position->current, 1 );
newmonster=map->AddMonster( 210, position, 0, NULL, NULL, 0, true );
newmonster->hitcount=2;
GServer->ClearClientID( monster->clientid );
for(UINT i=0;i<map->MonsterList.size();i++)
{
othermon = map->MonsterList.at(i);
if(othermon==monster)
{
map->MonsterList.erase( map->MonsterList.begin()+i );
delete monster;
}
}
break;
case 2:
CDrop* thisdrop = new CDrop;
assert(thisdrop);
thisdrop->clientid = GServer->GetNewClientID();
thisdrop->type = 2; // ITEM
thisdrop->pos = GServer->RandInCircle( monster->Position->current, 3 );
thisdrop->posMap = monster->Position->Map;
thisdrop->droptime = time(NULL);
thisdrop->amount = rand()%3+1;
thisdrop->item.count = thisdrop->amount;
thisdrop->owner = 0;
thisdrop->item.itemtype=12;
thisdrop->item.itemnum=rand()%10+11;
map->AddDrop( thisdrop );
GServer->ClearClientID( monster->clientid );
for(UINT i=0;i<map->MonsterList.size();i++)
{
othermon = map->MonsterList.at(i);
if(othermon==monster)
{
map->MonsterList.erase( map->MonsterList.begin()+i );
delete monster;
}
}
break;
}
return true;
}*/
bool CMonster::SummonUpdate(CMonster* monster, CMap* map, UINT j)
{
BEGINPACKET( pak, 0x799 );
clock_t etime = clock() - lastDegenTime;
CPlayer* ownerclient = monster->GetOwner( );
if( etime >= 4 * CLOCKS_PER_SEC && Stats->HP > 0 )
{
Stats->HP -= 4;
lastDegenTime = clock();
if (Stats->HP < 1||ownerclient == NULL||ownerclient->IsDead())//orphan check
{
Log( MSG_INFO, "Deleting orphan summon %i (summonupdate)",monster->montype);
ADDWORD ( pak, monster->clientid );
ADDWORD ( pak, monster->clientid );
ADDDWORD ( pak, 0x8005 );
GServer->SendToVisible( &pak, monster );
map->DeleteMonster( monster, true, j );
return true;
}
else
if (montype > 800 && montype < 811)
{
/*
CPlayer* ownerclient = monster->GetOwner( );
float distance = 0x9;
for(UINT i=0;i<GServer->MapList.Index[Position->Map]->PlayerList.size();i++)
{
CPlayer* thisclient = GServer->MapList.Index[Position->Map]->PlayerList.at(i);
float tempdist = GServer->distance( Position->current, thisclient->Position->current );
if(tempdist<distance)
{
thisclient->Stats->HP += ((((montype-800)*5)+((ownerclient->Stats->Level)/10))+10);
thisclient->Stats->MP += (((montype-800)*5)+((ownerclient->Stats->Level)/25));
BEGINPACKET( pak, 0x7b2);
ADDWORD ( pak, monster->clientid );
ADDWORD ( pak, 0x0b9d );
ADDBYTE ( pak, 0x06 );
thisclient->client->SendPacket(&pak);
RESETPACKET( pak, 0x7b5);
ADDWORD ( pak, thisclient->clientid );
ADDWORD ( pak, monster->clientid );
ADDWORD ( pak, 0x0b9d+0x3000+((ownerclient->Stats->Level%4)*0x4000) );
ADDBYTE ( pak, ownerclient->Stats->Level/4 );
thisclient->client->SendPacket(&pak);
RESETPACKET( pak, 0x7b9);
ADDWORD ( pak, monster->clientid );
ADDWORD ( pak, 0x0b9d );
thisclient->client->SendPacket(&pak);
}
}*/
}
// SET MONSTER HEALTH
//hopefully this will 100% control the health of summons from the server end
BEGINPACKET( pak1, 0x79f );
ADDWORD( pak1, clientid );
ADDWORD( pak1, Stats->HP );
ADDWORD( pak1, 0 );
//thisclient->client->SendPacket( &pak );
GServer->SendToVisible( &pak1, monster );
}
else
if (Stats->HP < 1)
{
Log( MSG_INFO, "Deleting dead summon %i (summonupdate)",monster->montype);
ADDWORD ( pak, monster->clientid );
ADDWORD ( pak, monster->clientid );
ADDDWORD ( pak, 0x8005 );
GServer->SendToVisible( &pak, monster );
map->DeleteMonster( monster, true, j );
}
return true;
}
void CMonster::DoAi(int ainumber,char type)//ainumber is monster->AI type is add=0 idle=1 attacking=2 attacked=3 after killing target=4 hp<1=5
{
CAip* script = NULL;
int AIWatch = GServer->Config.AIWatch;
int aiindex = (ainumber*0x10000)+(type*0x100);
if(type == 5)
{
//Log(MSG_INFO,"Monster died. Activating AI type 5");
}
for(unsigned j=0; j < GServer->AipList.size(); j++)
{
if (GServer->AipList.at(j)->AipID == aiindex)
{
script = GServer->AipList.at(j);
//if(ainumber == AIWatch)Log(MSG_DEBUG, "Record count = %i",script->recordcount[type]);
if(ainumber == AIWatch)Log(MSG_DEBUG, "aiCondition type: %i Index: %i condition count %i", type, aiindex, script->ConditionCount);
int success = AI_SUCCESS; //needs to be AI_SUCCESS otherwise would not perform conditionless actions
int thisaction = 0;
for (dword i = 0; i < script->ConditionCount; i++)
{
int command = script->Conditions[i]->opcode;
if (command > 30 || command < 0) continue;
success = (*GServer->aiCondFunc[command])(GServer, this, script->Conditions[i]->data);
if(ainumber == AIWatch)Log(MSG_DEBUG, "aiCondition %03u returned %d", command, success);
if (success == AI_FAILURE)
break;
}
if (success == AI_SUCCESS)
{
for (dword i = 0; i < script->ActionCount; i++)
{
int command = script->Actions[i]->opcode;
if (command > 38 || command < 0) continue;
success = (*GServer->aiActFunc[command])(GServer, this, script->Actions[i]->data);
if(ainumber == AIWatch)Log(MSG_DEBUG, "aiAction: %03u returned %d", command, success);
}
if(success == AI_SUCCESS)
return; //automatically return after performing the first successful action
}
aiindex++;
}
else if(GServer->AipList.at(j)->AipID > aiindex)return;
}
return;
}
+195
View File
@@ -0,0 +1,195 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://www.osrose.net
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "worldmonster.h"
// Get Mob Attack Power
unsigned int CMonster::GetAttackPower( )
{
unsigned int attack;
attack = thisnpc->atkpower;
if(thisnpc->weapon != 0)
attack += GServer->EquipList[8].Index[thisnpc->weapon]->attackpower;
if(Status->Attack_up!=0xff)
attack += MagicStatus[Status->Attack_up].Value;
if(Status->Attack_down!=0xff)
attack -= MagicStatus[Status->Attack_down].Value;
return attack;
}
// Get Monster Defense
unsigned int CMonster::GetDefense( )
{
unsigned int defense;
defense = thisnpc->defense;
if(thisnpc->subweapon!=0)
defense += GServer->EquipList[SUBWEAPON].Index[thisnpc->subweapon]->defense;
if(Status->Defense_up!=0xff)
defense += MagicStatus[Status->Defense_up].Value;
if(Status->Defense_down!=0xff)
defense -= MagicStatus[Status->Defense_down].Value;
if(defense == 0)defense = 1; //hopefully stops some division by zero errors.
return defense;
}
// Get Monster atk speed
unsigned int CMonster::GetAttackSpeed( )
{
unsigned int aspeed = (unsigned int)thisnpc->atkspeed;
if(aspeed == 0) aspeed = 1; // prevent a /0 when hunting dragon egg
if(Status->Haste_up!=0xff)
aspeed += MagicStatus[Status->Haste_up].Value;
if(Status->Haste_down!=0xff)
aspeed -= MagicStatus[Status->Haste_down].Value;
return aspeed;
}
// Get Monster Movement speed
unsigned int CMonster::GetMoveSpeed( )
{
unsigned int mspeed = 0;
if (Stats->stance == 0) //mWalking. All other stances produce running animation at client
{
mspeed = thisnpc->wspeed;
}
else
{
mspeed = thisnpc->rspeed;
}
if(Status->Dash_up!=0xff)
mspeed += MagicStatus[Status->Dash_up].Value;
if(Status->Dash_down!=0xff)
mspeed -= MagicStatus[Status->Dash_down].Value;
return mspeed;
}
// return dodge
unsigned int CMonster::GetDodge( )
{
UINT dodge = 0;
dodge = thisnpc->dodge;
if(dodge == 0) dodge = thisnpc->defense; // prevent a /0 for hawk skill
if(Status->Dodge_up!=0xff)
dodge += MagicStatus[Status->Dodge_up].Value;
if(Status->Dodge_down!=0xff)
dodge -= MagicStatus[Status->Dodge_down].Value;
if(dodge == 0)dodge = 1; //hopefully stops some division by zero errors.
return dodge;
}
// return accury
unsigned int CMonster::GetAccury( )
{
UINT hitrate = 0;
hitrate = thisnpc->hitrate;
if(Status->Accury_up!=0xff)
hitrate += MagicStatus[Status->Accury_up].Value;
if(Status->Accury_down!=0xff)
hitrate -= MagicStatus[Status->Accury_down].Value;
return hitrate;
}
// return magic defense
unsigned int CMonster::GetMagicDefense( )
{
UINT mdef = 0;
mdef = thisnpc->magicdefense;
if(Status->Magic_Defense_up!=0xff)
mdef += MagicStatus[Status->Magic_Defense_up].Value;
if(Status->Magic_Defense_down!=0xff)
mdef -= MagicStatus[Status->Magic_Defense_down].Value;
if(mdef == 0)mdef = 1; //hopefully stops some division by zero errors.
return mdef;
}
// return magic attack
unsigned int CMonster::GetMagicAttack( )
{
return thisnpc->magicattack;
}
// return max hp
unsigned int CMonster::GetMaxHP( )
{
UINT MaxHP = 0;
MaxHP = thisnpc->hp;
if(owner == 0)
MaxHP *= thisnpc->level;
//if(MaxHP == 0)
//MaxHP = thisnpc->shp; // Bullshit. npc->shp is the flying height of a monster such as a bee. Dumb ass!!
return MaxHP;
}
unsigned int CMonster::GetCritical( )
{
return 60; //60 = 20% of 300 our critical probability
}
float CMonster::GetAttackDistance( )
{
return thisnpc->atkdistance;
}
unsigned int CMonster::GetXPRate( )
{
return 0;
}
unsigned int CMonster::GetItemDropRate( )
{
return 0;
}
unsigned int CMonster::GetItemDropCountRate( )
{
return 0;
}
unsigned int CMonster::GetZulyDropRate( )
{
return 0;
}
// set monster stats values
bool CMonster::SetStats( )
{
if(thisnpc == NULL) return false;
Stats->Level = thisnpc->level;
Stats->Attack_Power = GetAttackPower( );
Stats->Defense = GetDefense( );
Stats->xprate = GetXPRate( );
Stats->itemdroprate = GetItemDropRate( );
Stats->zulydroprate = GetZulyDropRate( );
Stats->Attack_Speed = GetAttackSpeed( );
Stats->Move_Speed = GetMoveSpeed( );
Stats->Dodge = GetDodge( );
Stats->Accury = GetAccury( );
Stats->Critical = GetCritical( );
Stats->Magic_Defense = GetMagicDefense( );
Stats->magicattack = GetMagicAttack( );
Stats->Attack_Distance = GetAttackDistance( );
for(int i=0;i<20;i++)
{
AIVar[i] = 0;
}
return true;
}
+375
View File
@@ -0,0 +1,375 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://www.osrose.net
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "worldserver.h"
// Party Actions [invite/leave/kick]
bool CWorldServer::pakPartyActions( CPlayer* thisclient, CPacket* P )
{
unsigned int action = GETBYTE((*P),0);
CMap* map = MapList.Index[thisclient->Position->Map];
if(map == NULL)return true;
switch(action)
{
case 0x00://Invita a new party
case 0x01://invite a existent party
{
UINT clientid = GETWORD((*P),1);
if(thisclient->Party->party!=NULL)
{
if(thisclient->Party->party->Members.size()>=thisclient->Party->party->Capacity)
{
SendSysMsg( thisclient, "Party is full" );
return true;
}
}
CPlayer* otherclient = map->GetPlayerInMap( clientid );// have to be in same map
if(otherclient == NULL)
{
BEGINPACKET( pak, 0x7d1 );
ADDBYTE ( pak, 0x00 );//No encontro el ID
ADDWORD ( pak, clientid );
ADDBYTE ( pak, 0x00 );
thisclient->client->SendPacketCpy( &pak );
return true;
}
if(otherclient->Party->party != NULL)
{
BEGINPACKET( pak, 0x7d1 );
ADDBYTE ( pak, 0x01 );//No puede ser solicitado (ya tiene party)
ADDWORD ( pak, clientid );
ADDBYTE ( pak, 0x00 );
thisclient->client->SendPacketCpy( &pak );
return true;
}
if(abs(otherclient->Stats->Level-thisclient->Stats->Level)>(Config.Partygap+1))
{
BEGINPACKET( pak, 0x7d1 );
ADDBYTE ( pak, 0x07 );//Level inapropiado
ADDWORD ( pak, clientid );
ADDBYTE ( pak, 0x00 );
thisclient->client->SendPacketCpy( &pak );
return true;
}
BEGINPACKET( pak, 0x7d0 );
ADDBYTE ( pak, action );
ADDWORD ( pak, thisclient->clientid );
ADDBYTE ( pak, 0x00 );
otherclient->client->SendPacketCpy( &pak );
}
break;
case 0x02://Leave Party
{
if(thisclient->Party->party == NULL)
return true;
CParty* party = thisclient->Party->party;
if(party == NULL)
return true;
bool pflag = false;
if(!party->RemovePlayer( thisclient )) //if this player is not in this party
return true;
if(party->Members.size()>1)
{
for(UINT i=0;i<party->Members.size();i++)
{
CPlayer* thismember = party->Members.at(i);
if(thismember == NULL)
return true;
BEGINPACKET( pak, 0x7d2 );
ADDWORD ( pak, 0xff00 );
ADDDWORD ( pak, thisclient->CharInfo->charid );
if(!pflag)
{
ADDDWORD( pak, thismember->CharInfo->charid );
if(thisclient->Party->IsMaster)
thismember->Party->IsMaster = true;
pflag = true;
}
thismember->client->SendPacketCpy( &pak );
}
}
else
{
for(UINT i=0;i<party->Members.size();i++)
{
CPlayer* thismember = party->Members.at(i);
if(thismember == NULL)
return true;
BEGINPACKET( pak, 0x7d1 );
ADDBYTE ( pak, 0x05 );
ADDWORD ( pak, 0x0000 );
ADDWORD ( pak, 0x0000 );
thismember->client->SendPacket( &pak );
thismember->Party->party = NULL;
thismember->Party->IsMaster = true;
}
RemoveParty( party );
delete party;
}
}
break;
case 0x03: // Give leader
{
if(thisclient->Party->party == NULL)
return true;
unsigned int charid = GETDWORD((*P),1);
if( !thisclient->Party->IsMaster || thisclient->CharInfo->charid == charid )
return true;
CPlayer* otherclient = GetClientByCID( charid );
if(otherclient == NULL)
return true;
BEGINPACKET(pak, 0x07d1)
ADDBYTE(pak, 8);
ADDWORD(pak, otherclient->clientid);
ADDWORD(pak, 0);
otherclient->Party->IsMaster = true;
thisclient->Party->IsMaster = false;
thisclient->Party->party->SendToMembers( &pak );
}
break;
case 0x81: //Kick from party
{
unsigned int charid = GETDWORD((*P),1);
if(thisclient->Party->party==NULL)
return true;
if(!thisclient->Party->IsMaster || thisclient->CharInfo->charid==charid)
return true;
CParty* party = thisclient->Party->party;
if(party == NULL)
return true;
CPlayer* thismember = party->GetMemberByCharID( charid );
if(thismember == NULL)
return true;
BEGINPACKET( pak, 0x7d1 ); // Kicked from party message
ADDBYTE ( pak, 0x80 );
ADDDWORD ( pak, thismember->CharInfo->charid );
thismember->client->SendPacketCpy( &pak );
RESETPACKET( pak, 0x7d2 );
ADDWORD ( pak, 0xff00 );
ADDDWORD ( pak, thismember->CharInfo->charid );
bool pflag = false;
if(!party->RemovePlayer( thismember )) //if this player is not in this party
return true;
if(party->Members.size()>1)
{
for(UINT i=0;i<party->Members.size();i++)
{
CPlayer* othermember = party->Members.at(i);
if(othermember == NULL)
return true;
if(!pflag)
{
ADDDWORD( pak, othermember->CharInfo->charid );
if(thismember->Party->IsMaster)
othermember->Party->IsMaster = true;
pflag = true;
}
othermember->client->SendPacketCpy( &pak );
}
}
else
{
for(UINT i=0;i<party->Members.size();i++)
{
CPlayer* othermember = party->Members.at(i);
if(othermember == NULL)
return true;
RESETPACKET( pak, 0x7d1 );
ADDBYTE ( pak, 0x05 );
ADDWORD ( pak, 0x0000 );
ADDWORD ( pak, 0x0000 );
othermember->client->SendPacketCpy( &pak );
othermember->Party->party = NULL;
othermember->Party->IsMaster = true;
}
RemoveParty( party );
delete party;
}
}
break;
default:
Log(MSG_WARNING,"Party unknown action: %i", action);
}
return true;
}
// Party Manager
bool CWorldServer::pakPartyManager( CPlayer* thisclient, CPacket* P )
{
unsigned int action = GETBYTE((*P),0);
switch(action)
{
case 0x02://Acepto
{
if(thisclient->Party->party!=NULL)// have party
return true;
unsigned int clientid = GETWORD((*P),1);
CPlayer* otherclient = GetClientByID( clientid, thisclient->Position->Map );
if(otherclient == NULL)
{
BEGINPACKET( pak, 0x7d1 );
ADDBYTE ( pak, 0x00 );//No encontro el ID
ADDWORD ( pak, clientid );
ADDBYTE ( pak, 0x00 );
thisclient->client->SendPacketCpy( &pak );
return true;
}
CParty* party = otherclient->Party->party;
if(party != NULL)
{
if(party->Members.size()>=party->Capacity)
{
SendSysMsg( thisclient, "Party is Full" );
return true;
}
}
if(abs(otherclient->Stats->Level-thisclient->Stats->Level)>(Config.Partygap+1))
{
BEGINPACKET( pak, 0x7d1 );
ADDBYTE ( pak, 0x07 );//Level inapropiado
ADDWORD ( pak, clientid );
ADDBYTE ( pak, 0x00 );
thisclient->client->SendPacketCpy( &pak );
return true;
}
BEGINPACKET( pak, 0x7d1 );
ADDBYTE ( pak, 0x02 );//Acepto Party
ADDWORD ( pak, otherclient->clientid );
ADDBYTE ( pak, 0x00 );
otherclient->client->SendPacketCpy( &pak );
if( party == NULL )
{ // new party
CParty* thisparty = new CParty;
thisparty->counted = false;
thisparty->Pending_Exp = 0;
thisparty->AddPlayer( otherclient );
AddParty( thisparty );
otherclient->Party->IsMaster = true;
party = thisparty;
}
//Send Party Level and Party Exp
RESETPACKET( pak, 0x7d4 ); //
ADDBYTE ( pak, party->PartyLevel );
ADDDWORD ( pak, party->Exp );
thisclient->client->SendPacketCpy( &pak );
thisclient->Party->IsMaster = false;
// Send New Party Member info to other players
RESETPACKET( pak, 0x7d2 );
ADDBYTE ( pak, party->Option );
ADDBYTE ( pak, 0x01 );
ADDDWORD ( pak, thisclient->CharInfo->charid );
ADDWORD ( pak, thisclient->clientid );
ADDWORD ( pak, thisclient->Stats->MaxHP );
ADDWORD ( pak, thisclient->Stats->HP );
ADDDWORD ( pak, 0x00000000 );
ADDDWORD ( pak, 0x0000000f );
ADDWORD ( pak, 0x1388 );
ADDSTRING ( pak, thisclient->CharInfo->charname );
ADDBYTE ( pak, 0x00 );
party->SendToMembers( &pak );
// Send To New Party Member the members List
RESETPACKET( pak, 0x7d2 );
ADDBYTE ( pak, party->Option );
ADDBYTE ( pak, party->Members.size() );
for(int i=0;i<party->Members.size();i++)
{
CPlayer* member= party->Members.at(i);
if(member == NULL)
continue;
ADDDWORD ( pak, member->CharInfo->charid );
ADDWORD ( pak, member->clientid );
ADDWORD ( pak, member->Stats->MaxHP );
ADDWORD ( pak, member->Stats->HP );
ADDDWORD ( pak, 0x00000000 );
ADDDWORD ( pak, 0x0000000f );
ADDWORD ( pak, 0x1388 );
ADDSTRING ( pak, member->CharInfo->charname );
ADDBYTE ( pak, 0x00 );
}
thisclient->client->SendPacketCpy( &pak );
party->AddPlayer( thisclient );
}
break;
case 0x04://No acepto
{
unsigned int clientid = GETWORD((*P),1);
CPlayer* otherclient = GetClientByID( clientid, thisclient->Position->Map );
if(otherclient == NULL)
{
BEGINPACKET( pak, 0x7d1 );
ADDBYTE ( pak, 0x00 );//No encontro el ID
ADDWORD ( pak, clientid );
ADDBYTE ( pak, 0x00 );
thisclient->client->SendPacketCpy( &pak );
return true;
}
BEGINPACKET( pak, 0x7d1 );
ADDBYTE ( pak, 0x04 );//No acepto
ADDWORD ( pak, thisclient->clientid );
ADDBYTE ( pak, 0x00 );
otherclient->client->SendPacketCpy( &pak );
}
break;
default:
Log(MSG_WARNING,"Party Manager unknown action: %i", action);
}
return true;
}
// Party Chat
bool CWorldServer::pakPartyChat( CPlayer* thisclient, CPacket* P )
{
CParty* party = thisclient->Party->party;
if(party == NULL)
return true;
BEGINPACKET( pak, 0x786 );
ADDWORD ( pak, thisclient->clientid );
ADDSTRING ( pak, P->Buffer );
ADDBYTE ( pak, 0 );
party->SendToMembers( &pak );
return true;
}
// Change Party Options
bool CWorldServer::pakPartyOption( CPlayer* thisclient, CPacket* P )
{
if(!thisclient->Party->IsMaster)
return true;
CParty* party = thisclient->Party->party;
if(party == NULL)
return true;
party->Option = GETBYTE((*P),0);
BEGINPACKET( pak, 0x7d7 );
ADDBYTE ( pak, party->Option );
ADDBYTE ( pak, 0x00 );
party->SendToMembers( &pak );
return true;
}
unsigned int CWorldServer::GetMaxPartyExp( unsigned int partylevel )
{
unsigned int exp = 540;
exp += 100 * partylevel + ( partylevel-2*10 );
return exp;
}
+296
View File
@@ -0,0 +1,296 @@
#include "main.h"
dword GetRewardValue(dword function, dword amount, CWorldClient* client, word nDupCNT){
switch(function){
case 0:
{
dword tempVal = amount + 0x1E;
tempVal *= client->GetStat(sCharm) + 0x0a;
tempVal *= (100 & 0xFFFF);//World Rate
tempVal *= 0x14;//Fame + 0x14
tempVal = ((tempVal / (client->stats_base[sLevel] + 0x46)) / 0x7530) + amount;
return tempVal;
}
break;
case 1:
{
dword tempVal = (client->stats_base[sLevel] + 3) * amount;
tempVal *= (client->GetStat(sCharm) >> 1) + client->stats_base[sLevel] + 0x28;
tempVal *= (100 & 0xFFFF);//World Rate
return tempVal / 0x2710;
}
break;
case 2:
return (amount * nDupCNT);
break;
case 3:
case 5:
{
dword tempVal = amount + 0x14;
tempVal *= client->GetStat(sCharm) + 0x0a;
tempVal *= (100 & 0xFFFF);//World Rate
tempVal *= 0x14;//Fame + 0x14
tempVal = ((tempVal / (client->stats_base[sLevel] + 0x46)) / 0x7530) + amount;
return tempVal;
}
break;
case 4:
{
dword tempVal = amount + 0x2;
tempVal *= (client->GetStat(sCharm) + client->stats_base[sLevel] + 0x28);
tempVal *= 0x28;//Fame + 0x28
tempVal *= (100 & 0xFFFF);//World Rate
return tempVal / 0x222E0;
}
break;
case 6:
{
dword tempVal = amount + 0x14;
tempVal *= client->GetStat(sCharm) + client->stats_base[sLevel];
tempVal *= 0x14;//Fame + 0x14
tempVal *= (100 & 0xFFFF);//World Rate
return (tempVal / 0x2DC6C0) + amount;
}
break;
}
return amount;
}
//Update Quest
QUESTREWD(000){
GETREWDDATA(000);
switch(data->btOp){//0 remove, 1 start, 4 select
case 0:
{
for(dword i = 0; i < 10; i++){
if(client->quest.quests[i].QuestID != data->iQuestSN) continue;
memset(&client->quest.quests[i], 0, sizeof(SQuest));
break;
}
}
break;
case 1:
{
for(dword i = 0; i < 10; i++){
if(client->quest.quests[i].QuestID == 0) continue;
memset(&client->quest.quests[i], 0, sizeof(SQuest));
client->quest.quests[i].QuestID = data->iQuestSN;
client->quest.quests[i].Time = clock_t();
break;
}
}
break;
case 4:
{
client->ActiveQuest = data->iQuestSN;
}
break;
}
return QUEST_SUCCESS;
}
//Update Quest Items
QUESTREWD(001){
return QUEST_SUCCESS;
}
//Set Quest Variable
QUESTREWD(002){
return QUEST_SUCCESS;
}
//Update Stats
QUESTREWD(003){
GETREWDDATA(003);
for(dword i = 0; i < data->iDataCnt; i++){
qword address = i * 0x0C;
address += (qword)data;
address += 4;
STR_ABIL_DATA* curAbil = (STR_ABIL_DATA*)address;
if(!OperateValues(curAbil->btOp, &client->stats_base[curAbil->iType], curAbil->iValue))
return QUEST_FAILURE;
}
return QUEST_SUCCESS;
}
//Set Quest Variable
QUESTREWD(004){
return QUEST_SUCCESS;
}
//Give Reward
QUESTREWD(005){
GETREWDDATA(005);
switch(data->btTarget){
case 0://EXP
{
client->basic.exp += GetRewardValue(data->btEquation, data->iValue, client, 0);
CPacket pakout(0x79b);
pakout.Add<dword>(client->basic.exp);
pakout.Add<dword>(client->stats_base[sStamina]);
pakout.Add<word>(0);
server->SendPacket(client, &pakout);
}
break;
case 1://Zuly
client->inv.money += GetRewardValue(data->btEquation, data->iValue, client, 1);//dunno nDupCount for this one!
CPacket pakout(0x71D);
pakout.Add<qword>(client->inv.money);
server->SendPacket(client, &pakout);
break;
case 2://Item
{
CItem nItem;
nItem.type = data->iItemSN / 1000;
nItem.id = data->iItemSN - (nItem.type * 1000);
if(nItem.IsStackable()){
nItem.count = GetRewardValue(data->btEquation, data->iValue, client, 0);
}else{
nItem.itemdata = 0;
nItem.durability = 40;
nItem.lifespan = 1000;
nItem.appraised = 1;
}
client->AddItem(&nItem, true);
}
break;
}
return QUEST_SUCCESS;
}
//Restore HP/MP
QUESTREWD(006){
return QUEST_SUCCESS;
}
//Teleport
QUESTREWD(007){
GETREWDDATA(007);
client->MoveMap(data->iZoneSN, (float)data->iX, (float)data->iY);
return QUEST_SUCCESS;
}
//Spawn Monster
QUESTREWD(008){
return QUEST_SUCCESS;
}
//Execute Quest Trigger
QUESTREWD(009){
return QUEST_SUCCESS;
}
//Reset Stats
QUESTREWD(010){
client->stats_base[sStatPoints] = 0;
client->stats_base[sStrength] = 15;
client->stats_base[sDexterity] = 15;
client->stats_base[sIntelligence] = 15;
client->stats_base[sConcentration] = 15;
client->stats_base[sCharm] = 10;
client->stats_base[sSensibility] = 10;
for(int i = 0; i <= client->stats_base[sLevel]; i++)
client->stats_base[sStatPoints] += (i + 9);
return QUEST_SUCCESS;
}
//Update Quest Var
QUESTREWD(011){
return QUEST_SUCCESS;
}
//NPC Speak
QUESTREWD(012){
return QUEST_SUCCESS;
}
//Unknown
QUESTREWD(013){
return QUEST_SUCCESS;
}
//Learn Skill
QUESTREWD(014){
return QUEST_SUCCESS;
}
//Set Quest Flag
QUESTREWD(015){
GETREWDDATA(015);
client->quest.SetFlag(data->nSN, (data->btOp == 1)?true:false);
return QUEST_SUCCESS;
}
//Unknown
QUESTREWD(016){
return QUEST_SUCCESS;
}
//Reset All Quest Flags
QUESTREWD(017){
memset(&client->quest.flags, 0, 244);
return QUEST_SUCCESS;
}
//Send Announcement
QUESTREWD(018){
return QUEST_SUCCESS;
}
//Execute Quest Trigger in Other Map
QUESTREWD(019){
return QUEST_SUCCESS;
}
//PvP Status
QUESTREWD(020){
return QUEST_SUCCESS;
}
//Set Respawn Position
QUESTREWD(021){
return QUEST_SUCCESS;
}
//Unknown
QUESTREWD(022){
return QUEST_SUCCESS;
}
//Raise Clan Grade
QUESTREWD(023){
return QUEST_SUCCESS;
}
//Clan Money
QUESTREWD(024){
return QUEST_SUCCESS;
}
//Clan Points
QUESTREWD(025){
return QUEST_SUCCESS;
}
//Clan Skill
QUESTREWD(026){
return QUEST_SUCCESS;
}
//Clan Contribution
QUESTREWD(027){
return QUEST_SUCCESS;
}
//Clan Teleportation
QUESTREWD(028){
return QUEST_SUCCESS;
}
+229
View File
@@ -0,0 +1,229 @@
#include "main.h"
int OperateValues(byte btOp, int* value1PTR, int value2){
int value1 = *value1PTR;
switch(btOp){
case 0:
return (value1 == value2);
case 1:
return (value1 <= value2);
case 2:
return (value1 >= value2);
case 3:
return (value1 > value2);
case 4:
return (value1 < value2);
case 5:
(*value1PTR) = value2;
return 1;
case 6:
(*value1PTR) = value1 + value2;
return 1;
case 7:
(*value1PTR) = value1 - value2;
return 1;
default:
return 0;
}
}
//Check Quest
QUESTCOND(000){
GETCONDDATA(000);
for(dword i = 0; i < 10; i++){
if(client->quest.quests[i].QuestID == data->iQuestSN)
return QUEST_SUCCESS;
}
return QUEST_FAILURE;
}
//Check Quest Variable
QUESTCOND(001){
return QUEST_SUCCESS;
}
//Check Quest Variable
QUESTCOND(002){
return QUEST_SUCCESS;
}
//Check Stats
QUESTCOND(003){
GETCONDDATA(003);
for(int i = 0; i < data->iDataCnt; i++){
qword address = i * 0x0C;
address += (qword)data;
address += 4;
STR_ABIL_DATA* curAbil = (STR_ABIL_DATA*)address;
if(!OperateValues(curAbil->btOp, &client->stats_base[curAbil->iType], curAbil->iValue))
return QUEST_FAILURE;
}
return QUEST_SUCCESS;
}
//Check Items
QUESTCOND(004){
GETCONDDATA(004);
for(int i = 0; i < data->iDataCnt; i++){
//QWord for 64bit safe pointers.
qword address = i * 0x10;
address += (qword)data;
address += 4;
STR_ITEM_DATA* curItem = (STR_ITEM_DATA*)address;
if(curItem->uiItemSN == 0 && curItem->iWhere != 0){
int itemHead = client->inv.items[curItem->iWhere].itemhead;
if(!OperateValues(curItem->btOp, &itemHead, curItem->uiItemSN))
return QUEST_FAILURE;
}
Log(MSG_INFO,"uiItemSN: %u iWhere: %u iRequestCnt: %u btOp: %u", curItem->uiItemSN, curItem->iWhere, curItem->iRequestCnt, curItem->btOp);
}
return QUEST_SUCCESS;
}
//Check Party
QUESTCOND(005){
return QUEST_SUCCESS;
}
//Near Point
QUESTCOND(006){
GETCONDDATA(006);
client->UpdatePosition();
if(data->iZoneSN != 0){
if(client->basic.map != data->iZoneSN)
return QUEST_FAILURE;
}
float dx = client->basic.pos.x - (float)data->iX;
float dy = client->basic.pos.y - (float)data->iY;
float distance = sqrt((dx*dx) + (dy*dy));
return (distance < data->iRadius)?QUEST_SUCCESS:QUEST_FAILURE;
}
//World Time
QUESTCOND(007){
return QUEST_SUCCESS;
}
//Quest Time
QUESTCOND(008){
return QUEST_SUCCESS;
}
//Check Skill
QUESTCOND(009){
GETCONDDATA(009);
int checkVal = (data->btOp)?QUEST_SUCCESS:QUEST_FAILURE;
for(dword i = 0; i < 90; i++){
if(client->skill.Skills[i] == data->iSkillSN1)
return (data->btOp)?QUEST_SUCCESS:QUEST_FAILURE;
}
return (data->btOp)?QUEST_FAILURE:QUEST_SUCCESS;
}
//Unknown
QUESTCOND(010){
return QUEST_SUCCESS;
}
//Quest Variable
QUESTCOND(011){
return QUEST_SUCCESS;
}
//Execute Trigger in Zone
QUESTCOND(012){
return QUEST_SUCCESS;
}
//Near NPC
QUESTCOND(013){
return QUEST_SUCCESS;
}
//Check Quest Flag
QUESTCOND(014){
GETCONDDATA(014);
bool dataOp = (data->btOp)?true:false;
return (client->quest.GetFlag(data->nSN) == dataOp)?QUEST_SUCCESS:QUEST_FAILURE;
}
//Unknown
QUESTCOND(015){
return QUEST_SUCCESS;
}
//Zone Time
QUESTCOND(016){
return QUEST_SUCCESS;
}
//NPC Variables
QUESTCOND(017){
return QUEST_SUCCESS;
}
//Time on Date
QUESTCOND(018){
return QUEST_SUCCESS;
}
//Time on Day
QUESTCOND(019){
return QUEST_SUCCESS;
}
//Unknown
QUESTCOND(020){
return QUEST_SUCCESS;
}
//Unknown
QUESTCOND(021){
return QUEST_SUCCESS;
}
//Check Server/Channel
QUESTCOND(022){
return QUEST_SUCCESS;
}
//In Clan
QUESTCOND(023){
return QUEST_SUCCESS;
}
//Clan Position
QUESTCOND(024){
return QUEST_SUCCESS;
}
//Clan Contribution
QUESTCOND(025){
return QUEST_SUCCESS;
}
//Clan Grade
QUESTCOND(026){
return QUEST_SUCCESS;
}
//Clan Points
QUESTCOND(027){
return QUEST_SUCCESS;
}
//Clan Funds
QUESTCOND(028){
return QUEST_SUCCESS;
}
//Clan Members
QUESTCOND(029){
return QUEST_SUCCESS;
}
//Clan Skills
QUESTCOND(030){
return QUEST_SUCCESS;
}
+200
View File
@@ -0,0 +1,200 @@
#define QUESTCOND(cond) int QUEST_COND_ ## cond ## (class CWorldServer* server, class CPlayer* client, byte* raw)
typedef int (*fpQuestCond)(class CWorldServer*, class CPlayer*, byte*);
#define GETCONDDATA(cond) STR_COND_ ## cond ## * data = (STR_COND_ ## cond ## *)raw;
QUESTCOND(000);QUESTCOND(001);QUESTCOND(002);
QUESTCOND(003);QUESTCOND(004);QUESTCOND(005);
QUESTCOND(006);QUESTCOND(007);QUESTCOND(008);
QUESTCOND(009);QUESTCOND(010);QUESTCOND(011);
QUESTCOND(012);QUESTCOND(013);QUESTCOND(014);
QUESTCOND(015);QUESTCOND(016);QUESTCOND(017);
QUESTCOND(018);QUESTCOND(019);QUESTCOND(020);
QUESTCOND(021);QUESTCOND(022);QUESTCOND(023);
QUESTCOND(024);QUESTCOND(025);QUESTCOND(026);
QUESTCOND(027);QUESTCOND(028);QUESTCOND(029);
QUESTCOND(030);
struct STR_COND_000 {
int iQuestSN;
};
struct STR_COND_001 {
int iDataCnt;
STR_QUEST_DATA* CheckData;
};
struct STR_COND_002 {
int iDataCnt;
STR_QUEST_DATA* CheckData;
};
struct STR_COND_003 {
int iDataCnt;
STR_ABIL_DATA* CheckData;
};
struct STR_COND_004 {
int iDataCnt;
STR_ITEM_DATA* CheckData;
};
struct STR_COND_005 {
byte btIsLeader;
int iLevel;
byte btReversed;
};
struct STR_COND_006 {
int iZoneSN;
int iX;
int iY;
int iZ;
int iRadius;
};
struct STR_COND_007 {
dword ulTime;
dword ulEndTime;
};
struct STR_COND_008 {
dword ulTime;
byte btOp;
};
struct STR_COND_009 {
int iSkillSN1;
int iSkillSN2;
byte btOp;
};
struct STR_COND_010 {
byte btLowPcnt;
byte btHighPcnt;
};
struct STR_COND_011 {
union {
byte btWho;
word usWho;
};
word nVarNo;
int iValue;
byte btOp;
};
struct STR_COND_012 {
union {
word iZone;
dword ulZone;
};
int iX;
int iY;
union {
int iEventID;
dword m_HashEventOBJ;
};
};
struct STR_COND_013 {
int iNpcNo;
};
struct STR_COND_014 {
word nSN;
byte btOp;
};
struct STR_COND_015 {
word nNumber1;
word nNumber2;
};
struct STR_COND_016 {
union {
byte btWho;
dword ulWho;
};
dword ulTime;
dword ulEndTime;
};
struct STR_COND_017 {
STR_NPCVAR NpcVar1;
STR_NPCVAR NpcVar2;
byte btOp;
};
struct STR_COND_018 {
byte btDate;
byte btHour1;
byte btMin1;
byte btHour2;
byte btMin2;
};
struct STR_COND_019 {
byte btWeekDay;
byte btHour1;
byte btMin1;
byte btHour2;
byte btMin2;
};
struct STR_COND_020 {
int iNo1;
int iNo2;
};
struct STR_COND_021 {
union {
byte btSelObjType;
dword ulSelObjType;
};
int iRadius;
};
struct STR_COND_022 {
word nX;
word nY;
};
struct STR_COND_023 {
byte btReg;
};
struct STR_COND_024 {
word nPOS;
byte btOP;
};
struct STR_COND_025 {
word nCONT;
byte btOP;
};
struct STR_COND_026 {
word nGRD;
byte btOP;
};
struct STR_COND_027 {
word nPOINT;
byte btOP;
};
struct STR_COND_028 {
word iMONEY;
byte btOP;
};
struct STR_COND_029 {
word nMemberCNT;
byte btOP;
};
struct STR_COND_030 {
word nSkill1;
word nSkill2;
byte btOP;
};
+61
View File
@@ -0,0 +1,61 @@
#pragma once
#include "worldserver.h"
class CQuestTrigger {
public:
struct SQuestDatum {
int size;
int opcode;
byte* data;
};
string TriggerName;
dword TriggerHash;
byte CheckNext;
dword ConditionCount;
SQuestDatum** Conditions;
dword ActionCount;
SQuestDatum** Actions;
private:
};
struct STR_NPCVAR {
dword iNpcNo;
word nVarNo;
word unused;
};
struct STR_ITEM_DATA {
dword uiItemSN;
dword iWhere;
dword iRequestCnt;
byte btOp;
};
struct STR_QUEST_DATA {
union {
dword iType;
struct {
word m_wVarNO;
word m_wVarTYPE;
};
};
word nValue;
byte btOp;
};
struct STR_ABIL_DATA {
dword iType;
int iValue;
byte btOp;
};
#define QUEST_FAILURE 0
#define QUEST_SUCCESS 1
int OperateValues(byte btOp, int* value1PTR, int value2);
#include "QuestConditions.h"
#include "quest/QuestActions.h"
+898
View File
@@ -0,0 +1,898 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://www.osrose.net
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
developed with Main erose/hrose source server + some change from the original eich source
*/
#include "worldserver.h"
// from Paul_T
bool CWorldServer::SendPM( CPlayer* thisclient, const char* Format, ... )
{
char buf[512];
va_list ap;
va_start( ap, Format );
vsprintf( buf, Format, ap );
BEGINPACKET( pak, 0x0784 );
ADDSTRING( pak, "Server" );
ADDBYTE( pak, 0 );
ADDSTRING( pak, buf );
ADDBYTE( pak, 0 );
thisclient->client->SendPacket(&pak);
va_end( ap );
return true;
}
// from Paul_T
bool CWorldServer::SendGlobalMSG( CPlayer* thisclient, const char* Format, ... )
{
char buf[512];
va_list ap;
va_start( ap, Format );
vsprintf( buf, Format, ap );
BEGINPACKET( pak, 0x0784 );
ADDSTRING( pak, thisclient->CharInfo->charname );
ADDBYTE( pak, 0 );
ADDSTRING( pak, buf );
ADDBYTE( pak, 0 );
SendToAll(&pak);
va_end( ap );
return true;
}
// NPC Announce to the server
bool CWorldServer::NPCAnnounce( const char msg[200], const char npc[50])
{
BEGINPACKET( pak, 0x702 );
ADDSTRING( pak, npc );
ADDSTRING( pak, "> " );
ADDSTRING( pak, msg);
ADDBYTE( pak, 0x00);
SendToAll( &pak );
return true;
}
// NPC Whisper to a character
bool CWorldServer::NPCWhisper( CPlayer* thisclient, CMonster* thismon, const char msg[200], const char npc[50] )
{
BEGINPACKET( pak, 0x0784 );
ADDSTRING( pak, npc );
ADDBYTE( pak, 0 );
ADDSTRING( pak, msg );
ADDBYTE( pak, 0 );
thisclient->client->SendPacket(&pak);
return true;
}
// NPC Shout to the current map
bool CWorldServer::NPCShout( int map, const char msg[200], const char npc[50] )
{
BEGINPACKET(pak, 0x0785);
ADDSTRING ( pak, npc );
ADDBYTE ( pak, 0 );
ADDSTRING ( pak, msg );
ADDBYTE ( pak, 0 );
SendToMap ( &pak, map );
return true;
}
bool CWorldServer::DoSkillScript( CCharacter* character, CSkills* thisskill )
{
try
{
if(thisskill == 0)
return false;
if(thisskill->script == 0)
return false;
if(thisskill->svalue1 == 0)
return false;
fPoint position = RandInCircle( character->Position->current, 1 );
CMap* map = MapList.Index[character->Position->Map];
map->AddMonster( thisskill->svalue1, position, character->clientid,0,1 );
return true;
}
catch (...)
{
Log(MSG_WARNING, "Error in CWorldServer::DoSkillScript( CCharacter* character, CSkills* thisskill )(serverFunctions.cpp)" );
return false;
}
}
// Build Drop. New experimental method.
CDrop* CWorldServer::GetNewDrop( CMonster* thismon )
{
//Log(MSG_DEBUG,"Monster %i killed. FInding a drop",thismon->montype);
CPlayer* thisclient = GServer->GetClientByCID(thismon->MonsterDrop->firsthit);
if(thisclient == NULL)return NULL;
if( thisclient->Session->codedebug )
SendPM(thisclient, "Drops function called after killing monster type %i",thismon->montype);
int randv;
int i;
CDrop* newdrop = new (nothrow) CDrop;
if(newdrop == NULL)
{
Log(MSG_WARNING, "newDrop is NULL [getdrop]" );
return NULL;
}
CMDrops* thisdrop = NULL;
CMDrops* testdrop = NULL;
newdrop->clientid = GetNewClientID( );
newdrop->posMap = thismon->Position->Map;
newdrop->pos = RandInCircle( thismon->Position->current, 3 );
//newdrop->droptime = time(NULL);
newdrop->owner = thismon->MonsterDrop->firsthit;
newdrop->thisparty = thismon->thisparty;
ClearItem(newdrop->item);
int droprate = 80; // base drop percentage for monsters your own level
int DropFloor = Config.BASE_DROP_CHANCE;
int leveldif = (int)((float)thismon->thisnpc->level - (float)thisclient->Stats->Level);
float mod = droprate * 0.01 * leveldif;
int dropchance = int(droprate + mod);
if(dropchance < DropFloor) dropchance = DropFloor; //always a small chance of a drop even when the mob is more than 20 levels beneath your own
if(thismon->thisnpc->level == 1)
dropchance = 80;
//if( thisclient->Session->codedebug )
// SendPM(thisclient, "Drop chance (based on level diference) = %i", dropchance );
int droprand = GServer->RandNumber(0,100);
if (droprand > dropchance)
{
if( thisclient->Session->codedebug )
SendPM(thisclient, "Drop rate check failed with %i. No drop this time",droprand);
return NULL; // no drop here. not this time anyway.
}
// Each monster has its own rates for zuly and item drops defined in the stb
// first check for Zuly drops
randv = RandNumber( 1, 100);
//if( thisclient->Session->codedebug )
//{
// SendPM(thisclient, "randv = %i. money = %i. zulyrate = %i. ", randv,thismon->thisnpc->money,thisclient->Stats->zulydroprate );
//}
if(randv <= (thismon->thisnpc->money + thisclient->Stats->zulydroprate)) // zuly drop
{
newdrop->type = 1; //zuly
newdrop->amount = thismon->thisnpc->level * 5 * (Config.ZULY_RATE + thisclient->Stats->zulydroprate) + RandNumber( 1, 10 );
if( thisclient->Session->codedebug )
{
SendPM(thisclient, "Zuly drop selected " );
}
return newdrop;
}
//now check for item drops
//if( thisclient->Session->codedebug )
//{
// SendPM(thisclient, "randv = %i. Item = %i. Itemrate = %i", randv,thismon->thisnpc->item,thisclient->Stats->itemdroprate );
//}
if(randv <= (thismon->thisnpc->item + thisclient->Stats->itemdroprate + thismon->thisnpc->money)) // Item drop
{
//OK got an item. Now we find which one
//Map drop or mob drop? map = 50% mob = 50%. Maybe should be configurable or modified by monster data?
int randv2 = RandNumber( 1, 100);
if(randv2 <= 50) //map drop
{
for(i=0;i<GServer->MDropList.size();i++)
{
testdrop = GServer->MDropList.at(i);
if(testdrop == NULL) return NULL;
if(testdrop->Dropid == thismon->Position->Map)
{
thisdrop = testdrop;
}
}
if( thisclient->Session->codedebug )
{
SendPM(thisclient, "Map drop selected for map %i. ", thismon->Position->Map );
}
}
else // mob drop
{
for(i=0;i<GServer->MDropList.size();i++)
{
testdrop = GServer->MDropList.at(i);
if(testdrop == NULL) return NULL;
if(testdrop->Dropid == thismon->thisnpc->dropid)
{
thisdrop = testdrop;
}
}
if( thisclient->Session->codedebug )
{
SendPM(thisclient, "Mob drop selected for dropid %i. ", thismon->thisnpc->dropid );
}
}
if(thisdrop == NULL)
{
Log(MSG_WARNING, "Thisdrop is NULL [getdrop]" );
return NULL;
}
newdrop->type = 2; //Item
dword randitem = RandNumber( 1, thisdrop->TotalChance );
UINT itemindex = 0;
//if( thisclient->Session->codedebug )
//{
// SendPM(thisclient, "random chance %i", randitem);
//}
i=0;
do
{
//if( thisclient->Session->codedebug )
//{
// SendPM(thisclient, "Index: %i Item id: %i chance: %i", i, thisdrop->item[i], thisdrop->RunningTotal[i]);
//}
i++;
}
while (randitem > thisdrop->RunningTotal[i]);
itemindex = i;
if(thisdrop->item[itemindex] == 0)
{
Log(MSG_DEBUG, "item at itemindex %i does not exist",itemindex );
return NULL; //no item listed for this dropid
}
//ok we found an item. Now we process it.
//if( thisclient->Session->codedebug )
//{
// SendPM(thisclient, "Found an item to drop itemindex: %i id: %i. ", itemindex, thisdrop->item[itemindex] );
//}
if(thisdrop->item[itemindex] < 100000)
{
newdrop->item.itemtype = thisdrop->item[itemindex] / 1000;
newdrop->item.itemnum = thisdrop->item[itemindex] % 1000;
}
else
{
newdrop->item.itemtype = thisdrop->item[itemindex] / 1000000;
newdrop->item.itemnum = thisdrop->item[itemindex] % 1000000;
}
//if( thisclient->Session->codedebug )
//{
// SendPM(thisclient, "Item type = %i. item number = %i", newdrop->item.itemtype,newdrop->item.itemnum );
//}
newdrop->item.lifespan = 10 + rand()%80;
switch( newdrop->item.itemtype )
{
case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9:
newdrop->item.type = GServer->EquipList[newdrop->item.itemtype].Index[newdrop->item.itemnum]->type;
newdrop->item.raretype = GServer->EquipList[newdrop->item.itemtype].Index[newdrop->item.itemnum]->raretype;
break;
case 10:
newdrop->item.type = GServer->UseList.Index[newdrop->item.itemnum]->type;
newdrop->item.raretype = 0;
break;
case 11:
newdrop->item.type = GServer->JemList.Index[newdrop->item.itemnum]->type;
newdrop->item.raretype = 0;
break;
case 12:
newdrop->item.type = GServer->NaturalList.Index[newdrop->item.itemnum]->type;
newdrop->item.raretype = 0;
break;
case 14:
newdrop->item.type = GServer->PatList.Index[newdrop->item.itemnum]->type;
newdrop->item.raretype = 0;
break;
default:
Log(MSG_DEBUG, "itemtype %i does not exist",newdrop->item.itemtype );
return NULL;
break;
}
float dmod = 0; //random number from 0 to 100 made up of 5 sub numbers to keep
//the average value near to 50
for(i=0; i<5; i++)
{
float r1 = rand()%20;
dmod += r1;
}
newdrop->item.durability = 10 + (int)dmod;
newdrop->item.appraised = true;
newdrop->item.stats = 0;
newdrop->item.count = 1;
if( newdrop->item.itemtype == 8 || newdrop->item.itemtype == 9 )
{
//This probability is now configurable
int psocked = rand()%101; //Probability of finding a socketed item
if( psocked < Config.SlotChance) //default should be around 5% needs to be rare
{
newdrop->item.socketed = true;
}
else
{
newdrop->item.socketed = false;
}
}
else
{
newdrop->item.socketed = false;
}
float TmpMod = thisclient->Attr->Cha / 30;
int chamod = (int)floor(TmpMod);
if(chamod < 0) chamod = 0;
int basedrop = thisclient->Stats->itemdroprate; //Base number of items to be dropped.
int maxdrop = basedrop + Config.DropMultiple;
if(newdrop->item.itemtype == 11) //gems only get 1
newdrop->item.count = 1;
if( newdrop->item.itemtype == 10 || newdrop->item.itemtype == 12 )
{
newdrop->item.count = RandNumber(basedrop, maxdrop);
if(thismon->thisnpc->level == 1)
newdrop->item.count = 1; //limit the drop rate of items from level 1 event mobs
if(newdrop->item.count == 0)
newdrop->item.count = 1;
if(newdrop->item.type == 314) //skillbooks
newdrop->item.count = 1;
if(newdrop->item.itemtype == 12)
{
newdrop->item.count = RandNumber(1, 6) + RandNumber(0, thisclient->Stats->itemdropcountrate); //basic type 12 items
//some item types have their own rules
if(newdrop->item.type == 428) //special skill items such as mana jams and scrolls
newdrop->item.count = RandNumber(1, 3);
if(newdrop->item.itemnum > 300 && newdrop->item.itemnum < 360) //bullets get a lot higher count.
{
newdrop->item.count *= 10;
newdrop->item.count += 10;
}
}
}
else if( newdrop->item.itemtype >1 && newdrop->item.itemtype !=7 && newdrop->item.itemtype < 10)
{
// check to see if the item will be refined
int prefine = rand()%100; //Probability of finding a refined item
int refinechance = Config.RefineChance;
if(prefine < refinechance) // default = 5%
{
int refinelevel = rand()%101; //which level of refine do we actually get
if( refinelevel < 5) //default 5%
newdrop->item.refine = 4 * 16;
else if( refinelevel < 15 ) //10%
newdrop->item.refine = 3 * 16;
else if(refinelevel < 35 ) // 20%
newdrop->item.refine = 2 * 16;
else // 65%
newdrop->item.refine = 16;
}
else //95%
newdrop->item.refine = 0;
int StatChance = Config.StatChance;
if(newdrop->item.raretype > 0) // it's a blue item
{
newdrop->item.durability += 10; //make blues a little more durable
newdrop->item.appraised = false; //blues need to be appraised
newdrop->item.stats = RandNumber(0, 29) * 10 + 1; // stats can only be 1,11,21,,,,,291
}
else // not a blue item
{
int pstats = RandNumber(1, 100);
if( pstats < StatChance) // default 5%
newdrop->item.stats = RandNumber(0, 29) * 10 + 1; // stats can only be 1,11,21,,,,,291
}
}
newdrop->item.gem = 0;
if(newdrop->item.count == 0)
newdrop->item.count = 1; //just in case this is causing bugged items.
if( thisclient->Session->codedebug )
{
SendPM(thisclient, "Dropped item type: %i ID: %i count %i", newdrop->item.itemtype, newdrop->item.itemnum,newdrop->item.count);
}
return newdrop;
}
return NULL;
// did not qualify to drop anything this time
}
// Build Drop the PY way
CDrop* CWorldServer::GetPYDrop( CMonster* thismon, UINT droptype )
{ //if droptype = 1 then it is a normal drop. if it is 2 then it is a potential side drop.
//type 2 removed a it is now handled by AIP
//Log( MSG_INFO, "PYDrops function selected" );
//Log( MSG_INFO, "monster is %i", thismon->montype );
CDrop* newdrop = new (nothrow) CDrop;
/*
if(newdrop == NULL)
{
Log(MSG_WARNING, "Error allocing memory [getdrop]" );
return NULL;
}
newdrop->clientid = GetNewClientID( );
newdrop->posMap = thismon->Position->Map;
newdrop->pos = RandInCircle( thismon->Position->current, 3 );
//newdrop->droptime = time(NULL);
newdrop->owner = thismon->MonsterDrop->firsthit;
newdrop->thisparty = thismon->thisparty;
ClearItem(newdrop->item);
CPlayer* thisclient = GServer->GetClientByCID(thismon->MonsterDrop->firsthit);
if(thisclient == NULL)return NULL;
// code to modify drop chance for different levels
//float charm = 0;
//float droprate = thismon->thisnpc->dropchance;
int droprate = Config.DROP_RATE;
int DropFloor = Config.BASE_DROP_CHANCE;
int leveldif = (int)((float)thismon->thisnpc->level - (float)thisclient->Stats->Level);
float mod = droprate * 0.01 * leveldif;
int dropchance = int(droprate + mod);
if(dropchance < DropFloor) dropchance = DropFloor; //always a small chance of a drop even when the mob is more than 20 levels beneath your own
if(thismon->thisnpc->level == 1)
dropchance = 80;
if( thisclient->Session->codedebug )
SendPM(thisclient, "Drop rate (based on level diference) = %i", dropchance );
int droprand = GServer->RandNumber(0,100);
if (droprand > dropchance)
{
if( thisclient->Session->codedebug )
SendPM(thisclient, "Drop rate check failed with %i. No drop this time",droprand);
return NULL; // no drop here. not this time anyway.
}
int DropListSize = MDropList.size();
CItemType prob[MDropList.size()];
bool isdrop = false;
int n = 0;
int test = 0;
long int probmax = 0;
int itemnumber[MDropList.size()];
int itemtype[MDropList.size()];
int probability[MDropList.size()];
int alternate[MDropList.size()][8];
if( thismon->IsGhost())
{
// Stuff to do if the mob is a ghost of any type
int selection = 1 + rand()%10;
if( selection <= 5 )
{
newdrop->type = 1; //Drop Zuly.
newdrop->amount = thismon->thisnpc->level * 10 * Config.ZULY_RATE + RandNumber( 1, 10 );
return newdrop;
}
else
{
for(int i=0; i<SkillbookList.size( ); i++)
{
newdrop->type = 2;
CMDrops* thisdrop = GServer->SkillbookList.at(i);
if(thisdrop->level_min <= thismon->thisnpc->level && thisdrop->level_max >= thismon->thisnpc->level)
{
itemnumber[n] = thisdrop->itemnum;
itemtype[n] = thisdrop->itemtype;
probability[n] = thisdrop->prob;
probmax += thisdrop->prob;
n++;
}
}
}
}
else // Stuff to do if the mob isn't a ghost
{
int dropmode = 0;
int randv = RandNumber( 1, 100);
// Each monster has its own rates for zuly and item drops defined in the stb
// We also add a small amount based on the player's ItemDropRate and ZulyDroprate.
dropchance = thismon->thisnpc->item + thismon->thisnpc->money + thisclient->Stats->itemdroprate + thisclient->Stats->zulydroprate;
if( thisclient->Session->codedebug )
{
SendPM(thisclient, "randv = %i. total drop chance = %i. money = %i. zulyrate = %i. Item = %i. Itemrate = %i", randv,dropchance,thismon->thisnpc->money,thisclient->Stats->zulydroprate,thismon->thisnpc->item,thisclient->Stats->itemdroprate );
}
if(randv > dropchance)return NULL; // did not qualify to drop anything this time
if(randv <= (thismon->thisnpc->money + thisclient->Stats->zulydroprate)) // zuly drop instead of item drop
{
newdrop->type = 1;
newdrop->amount = thismon->thisnpc->level * 5 * Config.ZULY_RATE + RandNumber( 1, 10 );
return newdrop;
}
int randomdrop = GServer->RandNumber(1, 100);
for(int i=0; i<MDropList.size( ); i++)
{
isdrop = true; // start out true then eliminate drops later
CMDrops* thisdrop = GServer->MDropList.at(i);
if(thisdrop->mob != 0 && thisdrop->mob != thismon->montype)
isdrop = false;
if(thisdrop->map != 0 && thisdrop->map != thismon->Position->Map)
isdrop = false;
if(thisdrop->level_max > thisdrop->level_min && (thismon->thisnpc->level < thisdrop->level_min || thismon->thisnpc->level > thisdrop->level_max))
isdrop = false;
test = GServer->RandNumber(1, 10000);
if(thisdrop->prob < test)
isdrop = false;
if(isdrop == true)
{
itemnumber[n] = thisdrop->itemnum;
itemtype[n] = thisdrop->itemtype;
alternate[n][0] = 0;
for(int j=1;i<8;i++)
{
alternate[n][j] = thisdrop->alt[j];
}
n++;
}
}
}
int newn = n;
if(n == 0)
return NULL;
int maxitems = n;
// randomize the item from the list
n = GServer->RandNumber(0, maxitems);
newdrop->item.itemnum = itemnumber[n];
newdrop->item.itemtype = itemtype[n];
newdrop->type = 2;
if( thisclient->Session->codedebug )
{
for(int j=0;j<maxitems;j++)
{
SendPM(thisclient,"Shortlist item %i, type = %i. id = %i",j, itemtype[j], itemnumber[j]);
}
SendPM(thisclient, "Selected item %i. type = %i. id = %i ",n, newdrop->item.itemtype,newdrop->item.itemnum);
}
newdrop->item.lifespan = 10 + rand()%80;
float dmod = 0; //random number from 0 to 100 made up of 5 sub numbers to keep
//the average value near to 50
for(int i=0; i<5; i++)
{
float r1 = rand()%20;
dmod += r1;
}
newdrop->item.durability = 10 + (int)dmod;
if( newdrop->item.itemtype == 8 || newdrop->item.itemtype == 9 )
{
//This probability is now configurable from WorldServer.conf
int psocked = rand()%101; //Probability of finding a socketed item
if( psocked < Config.SlotChance) //default should be around 5% needs to be rare
{
newdrop->item.socketed = true;
}
else
{
newdrop->item.socketed = false;
}
}
else
{
newdrop->item.socketed = false;
}
//Log( MSG_INFO, "Socket are OK");
newdrop->item.appraised = false;
newdrop->item.stats = 0;
newdrop->item.count = 1;
//int chamod = 0;
int chamod = (int)floor(thisclient->Attr->Cha / 30);
if(chamod < 0) chamod = 0;
int basedrop = thisclient->Stats->itemdroprate; //Base number of items to be dropped.
int maxdrop = basedrop + Config.DropMultiple + chamod;
if(newdrop->item.itemtype == 11) //gems only get 1
newdrop->item.count = 1;
if( newdrop->item.itemtype == 10 || newdrop->item.itemtype == 12 )
{
newdrop->item.count = RandNumber(basedrop, maxdrop);
if(thismon->thisnpc->level == 1)
newdrop->item.count = 1 + chamod; //limit the drop rate of items from level 1 event mobs
if(newdrop->item.count == 0)
newdrop->item.count = 1;
if(newdrop->item.type == 314) //skillbooks
newdrop->item.count = 1;
if(newdrop->item.itemtype == 10)
{
if(newdrop->item.itemnum >= 441 && newdrop->item.itemnum <= 888)// skillbooks
newdrop->item.count = 1;
}
if(newdrop->item.itemtype == 12)
{
newdrop->item.count = RandNumber(0, 6) + RandNumber(0, thisclient->Stats->itemdropcountrate); //basic type 12 items
//some item types have their own rules
if(newdrop->item.type == 428) //special skill items such as mana jams and scrolls
newdrop->item.count = RandNumber(0, 3);
if(newdrop->item.itemnum > 300 && newdrop->item.itemnum < 360) //bullets get a lot higher count.
{
newdrop->item.count *= 10;
newdrop->item.count += 10;
}
}
}
else if( newdrop->item.itemtype >1 && newdrop->item.itemtype !=7 && newdrop->item.itemtype < 10)
{
// check to see if the item will be refined
int prefine = rand()%100; //Probability of finding a refined item
int refinechance = Config.RefineChance;
if(prefine < refinechance) // default = 5%
{
int refinelevel = rand()%101; //which level of refine do we actually get
if( refinelevel < 5) //default 5%
newdrop->item.refine = 4 * 16;
else if( refinelevel < 15 ) //10%
newdrop->item.refine = 3 * 16;
else if(refinelevel < 35 ) // 20%
newdrop->item.refine = 2 * 16;
else // 65%
newdrop->item.refine = 16;
}
else //99%
newdrop->item.refine = 0;
// will the item be a blue?
bool blue = false;
int bluechance1 = RandNumber( 1, 100);
int bluechance2 = Config.BlueChance + chamod;
if( thisclient->Session->codedebug )
Log( MSG_INFO, "Blue chance = %i", bluechance2);
//This probability is now configurable from WorldServer.conf. CHA also has an effect
if(bluechance1 < bluechance2) // some percentage of drops will be specials or blues whenever one is available.
{
if( thisclient->Session->codedebug )
Log( MSG_INFO, "Selected a blue item");
int p = 1;
while(alternate[n][p] != 0 && p < 8)
{
p++;
}
if(p > 1) // blues available for this item
{
//Log( MSG_INFO, "blue item available");
p--;
int bluenum = RandNumber( 1, p);
newdrop->item.itemnum = alternate[n][bluenum];
blue = true;
}
}
//is the item a blue or other special or unique type?
if(newdrop->item.itemtype < 10 || newdrop->item.itemtype == 14) //equipable or PAT
{
if(GServer->EquipList[newdrop->item.itemtype].Index[newdrop->item.itemnum]->raretype != 0)
blue = true;
}
// will the items get stats? All blue items will. Uniques count as blues.
int pstats = rand()%101; //Probability of the item having stats. default = 5%
if(blue == true)
{
pstats = 0;
}
int StatChance = Config.StatChance;
if( pstats < StatChance) // default 5%
newdrop->item.stats = RandNumber( 1, 300);
}
newdrop->item.gem = 0;
//newdrop->droptime = clock(); //moved to AddDrop function
*/
return newdrop;
}
UINT CWorldServer::GetColorExp( UINT playerlevel,UINT moblevel, UINT exp )
{
/*
purple = +16 - 200%
red = +10 - 150%
orange = +4 - 125%
yellow = same - 100%
green = -4 - 80%
blue = -9 - 50%
white = -15 - 20%
*/
int dif = moblevel - playerlevel;
//Log(MSG_INFO,"Level dif = %i XP factor is %i",dif,factor);
if(dif > 15) //purple
exp = (UINT)floor(exp * 2.0);
else if(dif > 10) //red
exp = (UINT)floor(exp * 1.5);
else if(dif > 4) //orange
exp = (UINT)floor(exp * 1.25);
else if(dif >= 0) //yellow
exp = (UINT)floor(exp * 1.0);
else if(dif > -4) //green
exp = (UINT)floor(exp * 0.8);
else if(dif > -9) //blue
exp = (UINT)floor(exp * 0.5);
if(dif <= -9) //white
exp = (UINT)floor(exp * 0.2);
if(playerlevel < 10) // lower the rate for the first 10 levels
exp = (UINT)floor(exp * 0.5);
return exp;
}
bool CWorldServer::SendSysMsg( CPlayer* thisclient, string message )
{
BEGINPACKET( pak, 0x7df );
ADDBYTE ( pak, 0xf1 );
ADDSTRING ( pak, message.c_str( ));
ADDBYTE ( pak, 0x00 );
thisclient->client->SendPacket( &pak );
return true;
}
// teleport to specificated map and position
bool CWorldServer::TeleportTo ( CPlayer* thisclient, int map, fPoint position )
{
if(map > 70)
return true;
MapList.Index[map]->TeleportPlayer( thisclient, position, false );
return true;
}
// Learn Skill
bool CWorldServer::LearnSkill( CPlayer* thisclient, UINT skill, bool cost )
{
/*
0 - ya aprendido
1 - aprendio
2 - no job
3 - falta otro skill
4 - no status points (lvl)
5 - no se puede subir de lvl el skill
6 - numero incorrecto de skill
7 - no tienes suficientes sp
*/
BEGINPACKET(pak1, 0 );
BEGINPACKET(pak2, 0 );
BEGINPACKET(pak3, 0 );
//int b=1;
CSkills* thisskill = SkillList.at( skill);
char skilltype = thisskill->type;
//int skillpoints = thisskill->sp;
if(thisclient->Session->codedebug) //Debug code
{
char buffer[200];
sprintf ( buffer, "Attempting to learn a new skill. id = %i skill type = %i Cost to learn = %i", thisskill->id,thisskill->type,thisskill->sp );
SendPM(thisclient, buffer);
}
int newslot = thisclient->GetNewSkillSlot(skilltype);
//CSkills* thisskill = 0;
if (newslot != 0xffff)
{
switch(skilltype)
{
case 0:
thisclient->bskills[newslot]= skill;
if (cost)
thisclient->CharInfo->SkillPoints -= thisskill->sp;
RESETPACKET(pak1, 0x7b0);
ADDBYTE(pak1, 1);
ADDBYTE(pak1, newslot);
ADDWORD(pak1, skill);
ADDWORD(pak1, thisclient->CharInfo->SkillPoints);
thisclient->client->SendPacket(&pak1);
thisclient->SetStats();
return true;
case 1:
thisclient->askill[newslot]= skill;
if (cost)
thisclient->CharInfo->SkillPoints-=thisskill->sp;
RESETPACKET(pak2, 0x7b0);
ADDBYTE(pak2, 1);
ADDBYTE(pak2, 30+newslot);
ADDWORD(pak2, skill);
ADDWORD(pak2, thisclient->CharInfo->SkillPoints);
thisclient->client->SendPacket(&pak2);
thisclient->SetStats();
return true;
case 2:
thisclient->pskill[newslot]= skill;
if (cost)
thisclient->CharInfo->SkillPoints-=thisskill->sp;
RESETPACKET(pak3, 0x7b0);
ADDBYTE(pak3, 1);
ADDBYTE(pak3, 60+newslot);
ADDWORD(pak3, skill);
ADDWORD(pak3, thisclient->CharInfo->SkillPoints);
thisclient->client->SendPacket(&pak3);
thisclient->SetStats();
return true;
default:
return false;
}
}
return false;
}
//add / remove a Fairy
void CWorldServer::DoFairyStuff(CPlayer* targetclient, int action)
{
BEGINPACKET( pak, 0x7dc );
ADDBYTE( pak, action );
ADDWORD( pak, targetclient->clientid);
SendToVisible( &pak, targetclient );
}
void CWorldServer::DoFairyFree( int fairy )
{
GServer->FairyList.at(fairy)->assigned = false;
GServer->FairyList.at(fairy)->ListIndex = 0;
if(GServer->Config.FairyTestMode == 0)
GServer->FairyList.at(fairy)->WaitTime = GServer->Config.FairyWait * (rand()% GServer->GetFairyRange(1)+ GServer->GetFairyRange(0));
GServer->FairyList.at(fairy)->LastTime = clock();
}
void CWorldServer::RefreshFairy( )
{
//fairy: The wait timer should be possibibly bigger when there is few people online.
if (Config.FairyMode == 1 && ClientList.size() > 2) //if fairy mode on and a few people online
{
for (int i=0; i<Config.FairyMax; i++) // check all fairies
{
if ( FairyList.at(i)->LastTime <= ( clock() - (FairyList.at(i)->WaitTime * 60 * CLOCKS_PER_SEC) ) && !FairyList.at(i)->assigned ) // if fairy hour is now
{
if(ClientList.size() > 2) //stop solo players from getting fairied and screwing up their stats during testing.
{
int value = rand()%(int)(ClientList.size()-1) + 1; //choose random value in clientlist
CPlayer* targetclient = (CPlayer*) ClientList.at(value)->player;
if(targetclient == NULL)
return;
FairyList.at(i)->ListIndex = value;
FairyList.at(i)->LastTime = clock();
FairyList.at(i)->assigned = true;
FairyList.at(i)->scroll = false; // Scroll value set to false. this is NOT a scroll buff fairy
targetclient->Fairy = true;
targetclient->FairyListIndex = i; // FairyList index number of our actual fairy
DoFairyStuff(targetclient, 1); // spawn fairy to target
targetclient->SetStats();
}
}
if ( (FairyList.at(i)->LastTime + (Config.FairyStay*60*CLOCKS_PER_SEC)) <= clock() && FairyList.at(i)->assigned) // id time for our fairy to go away
{
CPlayer* oldclient = (CPlayer*) ClientList.at(FairyList.at(i)->ListIndex)->player;
if(FairyList.at(i)->scroll == true) //this is a scroll fairy
{
GServer->Config.ScrollFairy --; //reduce count of scroll fairies by one
if(GServer->Config.ScrollFairy < 0)GServer->Config.ScrollFairy = 0; //Make sure we don't go negative
GServer->Config.FairyMax = (int)ceil((float)GServer->ClientList.size() / 50.0) + GServer->Config.ScrollFairy; //recalculate the maximum number of fairies
FairyList.at(i)->scroll = false; //reset scroll value
}
DoFairyFree(i);
oldclient->Fairy = false;
oldclient->FairyListIndex = 0;
DoFairyStuff(oldclient, 0); // unspawn fairy
oldclient->SetStats();
}
}
}
// this close fairies after their time if GM de activate fairy mode when some fairies are assigned.
if (Config.FairyMode == 0 && ClientList.size() > 1){ // if serevr mode off and someone online
for (int i=0; i<Config.FairyMax; i++)
{
if ( (FairyList.at(i)->LastTime + (Config.FairyStay*60*CLOCKS_PER_SEC)) <= clock() && FairyList.at(i)->assigned)
{
CPlayer* oldclient = (CPlayer*) ClientList.at(FairyList.at(i)->ListIndex)->player;
DoFairyFree(i);
oldclient->Fairy = 0;
oldclient->FairyListIndex = 0;
DoFairyStuff(oldclient, 0);
oldclient->SetStats();
}
}
}
}
+113
View File
@@ -0,0 +1,113 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://www.osrose.net
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "worldserver.h"
/*
/ from signal.h
* NOTE: SIGINT is produced when the user presses Ctrl-C.
* SIGILL has not been tested.
* SIGFPE doesn't seem to work?
* SIGSEGV does not catch writing to a NULL pointer (that shuts down
* your app; can you say "segmentation violation core dump"?).
* SIGTERM comes from what kind of termination request exactly?
* SIGBREAK is indeed produced by pressing Ctrl-Break.
* SIGABRT is produced by calling abort.
*/
void StartSignal( )
{
signal( SIGINT, HandleSignal );
signal( SIGILL, HandleSignal );
signal( SIGFPE, HandleSignal );
signal( SIGSEGV, HandleSignal );
signal( SIGTERM, HandleSignal );
signal( SIGBREAK, HandleSignal );
signal( SIGABRT, HandleSignal );
}
void StopSignal( )
{
signal( SIGINT, 0 );
signal( SIGILL, 0 );
signal( SIGFPE, 0 );
signal( SIGSEGV, 0 );
signal( SIGTERM, 0 );
signal( SIGBREAK, 0 );
signal( SIGABRT, 0 );
}
void HandleSignal( int num )
{
switch(num)
{
case SIGINT:/* Interactive attention */
Log( MSG_ERROR, "Signal received: SIGINT" );
#ifdef _WIN32
Sleep(1000);
#else
usleep(1000);
#endif
delete GServer;
raise(num);
break;
case SIGILL:/* Illegal instruction */
Log( MSG_ERROR, "Signal received: SIGILL, Server will be closed, Trying to save..." );
GServer->DisconnectAll();
#ifdef _WIN32
Sleep(1000);
#else
usleep(1000);
#endif
delete GServer;
raise(num);
break;
case SIGFPE:/* Floating point error */
Log( MSG_ERROR, "Signal received: SIGFPE, Server will be closed, Trying to save..." );
GServer->DisconnectAll();
delete GServer;
raise(num);
break;
case SIGSEGV:/* Segmentation violation */
Log( MSG_ERROR, "Signal received: SIGSEGV, Server will be closed, Trying to save..." );
GServer->DisconnectAll();
#ifdef _WIN32
Sleep(1000);
#else
usleep(1000);
#endif
delete GServer;
raise(num);
break;
case SIGTERM:/* Termination request */
Log( MSG_INFO, "Signal received: SIGTERM, Server will be closed" );
pthread_create( &GServer->WorldThread[SHUTDOWN_THREAD], NULL, (void *(__cdecl *)(void *))ShutdownServer, (PVOID)0);
break;
#ifdef _WIN32
case SIGBREAK:/* Control-break */
Log( MSG_INFO, "Signal received: SIGBREAK, Server will be closed" );
pthread_create( &GServer->WorldThread[SHUTDOWN_THREAD], NULL, (void *(__cdecl *)(void *))ShutdownServer, (PVOID)0);
break;
#endif
default:
cout << "Unknown Signal Number: " << num << endl;
raise(num);
}
}
+53
View File
@@ -0,0 +1,53 @@
// Spawn a monster
void CMonster::SpawnMonster( CPlayer* player, CMonster* thismon )
{
BEGINPACKET( pak, 0x792 );
ADDWORD ( pak, clientid );
ADDFLOAT ( pak, Position->current.x*100 );
ADDFLOAT ( pak, Position->current.y*100 );
ADDFLOAT ( pak, Position->destiny.x*100 );
ADDFLOAT ( pak, Position->destiny.y*100 );
if(IsDead( ))
{
ADDWORD ( pak, 0x0003 );
ADDWORD ( pak, 0x0000 );
}
else if(IsOnBattle( ))
{
ADDWORD ( pak, 0x0002 );
ADDWORD ( pak, Battle->target );
}
else if(IsMoving( ))
{
ADDWORD ( pak, 0x0001 );
ADDWORD ( pak, 0x0000 );
}
else
{
ADDWORD ( pak, 0x0000 );
ADDWORD ( pak, 0x0000 );
}
ADDBYTE ( pak, thisnpc->stance );
ADDWORD ( pak, Stats->HP );
ADDDWORD ( pak, Stats->HP );
if(thismon->owner != player->clientid)
{
CMap* map = GServer->MapList.Index[Position->Map];
if(IsSummon( ) && map->allowpvp!=0) {ADDWORD( pak, 0x0064 );} //Hostil
else if (IsSummon( ) && map->allowpvp==0) {ADDWORD ( pak, 0x0000 );}//Friendly
else {ADDWORD( pak, 0x0064 );} //Hostil
}
else {ADDWORD( pak, 0x0000 );}//Friendly
ADDDWORD( pak, GServer->BuildBuffs( this ) );
ADDWORD ( pak, montype );
ADDWORD ( pak, 0x0000 );
if(IsSummon( ))
{
ADDWORD( pak, owner );
ADDWORD( pak, 0x0000 ); //
}
player->client->SendPacket( &pak );
}
+70
View File
@@ -0,0 +1,70 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://www.osrose.net
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "worldmonster.h"
// Monster Contructor
CMonster::CMonster( fPoint MonsterPosition, UINT MonsterType, UINT MonsterMap, UINT Owner, UINT spawnid )
{
montype = MonsterType;
SpawnTime = clock( );
lastSighCheck = clock( );
MonsterDrop = NULL;
Position->source = MonsterPosition;
Position->current = MonsterPosition;
Position->destiny = MonsterPosition;
Position->Map = MonsterMap;
Position->respawn = spawnid;
Position->lastMoveTime = clock();
// Magic status (buffs)
for(unsigned int i=0;i<30;i++)
{
MagicStatus[i].Status = 0;
MagicStatus[i].Buff = 0;
MagicStatus[i].Value = 0;
MagicStatus[i].Duration = 0;
MagicStatus[i].BuffTime = 0;
}
// Monster drop
MonsterDrop = new MDrop;
assert(MonsterDrop);
MonsterDrop->drop = false;
MonsterDrop->firsthit = 0;
MonsterDrop->firstlevel = 0;
MonsterDrop->mobdrop = NULL;
MonsterDrop->mapdrop = NULL;
clientid = GServer->GetNewClientID();
owner = Owner;
thisparty = NULL;
if(owner == 0) CharType = TMONSTER;
else CharType = TSUMMON;
}
// Monster destructor
CMonster::~CMonster( )
{
if(MonsterDrop!=NULL);
delete MonsterDrop;
for(UINT i=0;i<PlayersDamage.size();i++)
delete PlayersDamage.at(i);
PlayersDamage.clear();
}
+110
View File
@@ -0,0 +1,110 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://www.osrose.net
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#ifndef __ROSE_MONSTER__
#define __ROSE_MONSTER__
#include "character.h"
#include "player.h"
#include "worldserver.h"
class CMonster : public CCharacter
{
public:
CMonster( fPoint Position, UINT MonsterType, UINT MonsterMap, UINT Owner=0, UINT spawnid=0 );
~CMonster( );
// times
clock_t SpawnTime;
clock_t lastSighCheck;
clock_t lastDegenTime;
clock_t lastAiUpdate;
clock_t DeathDelayTimer;
MDrop* MonsterDrop;
UINT activecycle;
unsigned int montype;
unsigned int owner;
unsigned int monAI;
unsigned int AItimer;
unsigned char hitcount; //for guardiantree scarab spawning
unsigned int IsCasting;
unsigned int NextWayPoint;
CParty* thisparty;
CNPCData* thisnpc;
vector<MonsterDamage*> PlayersDamage;
// Monster Functions
void DoAi(int ainumber,char type);
//bool Guardiantree(CMonster* monster, CMap* map);
bool Scarab(CMonster* monster, CMap* map);
bool SummonUpdate(CMonster* monster, CMap* map, UINT j);
bool SetStats( );
bool UnspawnMonster( );
bool IsGhost( );
bool IsGhostSeed( );
bool CanMove( );
void OnEnemyDie( void* enemy );
bool ReadyToMove( );
void MoveTo( fPoint nPos, bool randcircle=true );
void Move( );
CPlayer* GetOwner( );
void SpawnMonster( CPlayer* player, CMonster* thismon );
bool PlayerInRange( );
CPlayer* GetNearPlayer( UINT mdist = 20 );
void AddDamage( CCharacter* enemy, long int hitpower);
CDrop* GetDrop( );
//
bool IsMonster( );
bool UpdateValues( );
// Stats
unsigned int GetAttackPower( );
unsigned int GetDefense( );
unsigned int GetXPRate( );
unsigned int GetItemDropRate( );
unsigned int GetItemDropCountRate( );
unsigned int GetZulyDropRate( );
unsigned int GetGreyDrops( );
unsigned int GetDodge( );
unsigned int GetAccury( );
unsigned int GetMagicDefense( );
unsigned int GetMagicAttack( );
unsigned int GetCritical( );
unsigned int GetAttackSpeed( );
unsigned int GetMoveSpeed( );
unsigned int GetMaxHP( );
float GetAttackDistance( );
// Events
bool OnBeAttacked( CCharacter* Enemy );
bool OnEnemyOnSight( CCharacter* Enemy );
bool OnDie( );
bool OnEnemyDie( CCharacter* Enemy );
bool OnSpawn( bool );
bool OnAlmostDie( );
bool OnFar( );
};
#endif
+458
View File
@@ -0,0 +1,458 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://www.osrose.net
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
developed with Main erose/hrose source server
+ some change from the original eich source
+ parts copied from/based on work from ExJem
*/
//#define debugging
#ifndef __ROSE_SERVERS__
#define __ROSE_SERVERS__
#include "datatypes.h"
#include "sockets.h"
#include "worldmonster.h"
#include "quest/CRoseArray.hpp"
#include "quest/CRoseFile.hpp"
#include "quest/CStrStb.hpp"
#include "quest/CIntStb.hpp"
#include "quest/QuestTrigger.h"
#include "aip/Aip.h"
#include "worldmap.h"
#include "player.h"
#include "character.h"
#include "party.h"
#include "stbhandler.h"
#include "stlhandler.h"
#include "strhashing.h"
#define MAXVISUALRANGE 90
#define MINVISUALRANGE 80
#define ClearItem(i) { i.appraised=false; i.count=0; i.durability=0; i.itemnum=0; i.itemtype=0; i.lifespan=0; i.refine=0; i.socketed=false; i.stats=0; i.gem=0; }
#define WORLD_THREAD 0
#define VISUALITY_THREAD 1
#define SHUTDOWN_THREAD 2
#define MAX_MAPS 115
// Main loginserver server class
class CWorldServer : public CServerSocket
{
public:
//------------------ MAIN (worldserver.cpp)
CWorldServer ( string );
CClientSocket* CreateClientSocket( );
~CWorldServer( );
bool OnReceivePacket( CClientSocket* thisclient, CPacket* P );
void ReceivedISCPacket( CPacket* pak ); // Raven0123
void SendISCServerInfo( );
void OnClientDisconnect( CClientSocket* thisclient );
void DeleteClientSocket( CClientSocket* thisclient );
bool OnServerReady( );
void SpawnMonsters( );
bool Ping( );
void LoadConfigurations( const char* );
void LoadCommandLevels( void );
void ServerLoop( );
void LoadEncryption( );
bool pakGiveItem( CPlayer* thisclient, unsigned char itemtype, unsigned short itemid, unsigned short count );
bool pakGiveExp( CPlayer* thisclient, unsigned exp );
bool pakGiveMoney( CPlayer* thisclient, unsigned amount );
bool pakTeleport( CPlayer* thisclient, unsigned short map, float x, float y );
bool pakLearnSkill( CPlayer* thisclient, unsigned short skillid );
void DePopulateZone( CPlayer* thisclient, int zonex, int zoney );
bool pakQuestTrigger( CPlayer* thisclient, CPacket* pak );
//------------------ WORLD PROCESS (worldprocess.cpp)
bool GiveExp( CMonster* thismon );
//------------------ BUFFS (buff.cpp)
CBValue GetBuffValue( CSkills* thisskill, CCharacter* character, UINT Evalue, UINT i, UINT up, UINT down, UINT CurrentValue, bool Buff=true, bool Status=false );
//CBValue GetBuffValue( CSkills* thisskill, CCharacter* character, UINT Evalue, UINT i, UINT up, UINT down, UINT CurrentValue, bool Buff=true );
bool CheckABuffs( CSkills* thisskill, CCharacter* character, int Evalue ,int i);
//bool CheckDBuffs( CSkills* thisskill, CCharacter* character, int Evalue ,int i);
bool AddBuffs( CSkills* thisskill, CCharacter* character, int Evalue , bool flag);
//bool AddDeBuffs( CSkills* thisskill, CCharacter* character, int Evalue );
bool AddBuffs( CSkills* thisskill, CCharacter* character, int Evalue );
bool InstantBuff( CSkills* thisskill, CCharacter* character, int Evalue, int i );
//------------------ SERVER EXTRAS (extrafunctions.cpp)
bool IsValidItem(UINT type, UINT id );
unsigned BuildItemShow(CItem thisitem);
UINT GetUIntValue( const char* s , void* var=NULL );
int GetIntValue( const char* s , void* var=NULL );
char* GetStrValue( const char* s , void* var=NULL );
bool SendSysMsg( CPlayer* thisclient, string message );
UINT RandNumber( UINT init, UINT range, UINT seed=0 );
UINT GetColorExp( UINT playerlevel,UINT moblevel, UINT exp );
bool CheckInventorySlot( CPlayer* thisclient, int slot );
bool pakGMClass( CPlayer* thisclient, char* classid );
bool pakGMKillInRange( CPlayer* thisclient, int range );
bool pakGMHide( CPlayer* thisclient, int mode );
void SendToVisible( CPacket* pak, CPlayer* thisclient, bool thisclients=true );
void SendToVisible( CPacket* pak, CPlayer* thisclient, CPlayer* xotherclient );
void SendToVisible( CPacket* pak, class CCharacter* character, CDrop* thisdrop=NULL );
bool IsMonInCircle( CPlayer* thisclient, CMonster* thismon, float radius );
bool IsPlayerInCircle( CPlayer* thisclient, CPlayer* otherclient, float radius );
CUseInfo* GetUseItemInfo( CPlayer* thisclient, UINT slot );
bool IsVisible( CPlayer* thisclient, CPlayer* otherclient );
bool IsMonInCircle( fPoint center, fPoint position, float radius );
bool IsVisible( CPlayer* thisclient, CMonster* thismon );
bool IsVisible( CPlayer* thisclient, CDrop* thisdrop );
CItem GetItemByHeadAndData( unsigned head, unsigned data );
bool IsVisible( CPlayer* thisclient, CNPC* thisnpc );
void SendToVisible( CPacket* pak, CMonster* thismon, CDrop* thisdrop=NULL );
void SendToVisible( CPacket* pak, CDrop* thisdrop );
CPlayer* GetClientByUserName( char *username );
UINT BuildBuffs( CCharacter* player );
UINT BuildUpBuffs( CCharacter* player );
UINT BuildDeBuffs( CCharacter* player );
void CheckForLevelUp ( CPlayer* thisclient );
bool isSkillTargetFriendly( CSkills* thisskill );
CRespawnPoint* GetRespawnByID( UINT id );
CPlayer* GetClientByCID( UINT id, UINT map=0 );
CPlayer* GetClientByCharName( char* name );
CPlayer* GetClientByID( UINT id, UINT map=0 );
CTeleGate* GetTeleGateByID( UINT id );
UINT BuildItemHead( CItem thisitem );
UINT BuildItemData( CItem thisitem );
CMonster* GetMonsterByID( UINT id, UINT map );
CSpawnArea* GetSpawnArea( UINT id, UINT map=0 );
#ifdef USEIFO
CMobGroup* GetMobGroup( UINT id, UINT map=0 );
#endif
bool DeleteSpawn( CSpawnArea* spawn );
CNPCData* GetNPCDataByID( UINT id );
void SendToMap( CPacket* pak, int mapid );
unsigned BuildItemRefine(CItem thisitem );
CMDrops* GetDropData( UINT id );
CRespawnPoint* GetRespawnByMap( int id );
CSkills* GetSkillByID( UINT id );
CStatus* GetStatusByID( UINT id );
void ClearClientID( UINT id );
CDrop* GetDropByID( UINT id, UINT map=0 );
CNPC* GetNPCByID( UINT id, UINT map=0 );
CDrop* GetNewDrop( CMonster* thismon );
CDrop* GetPYDrop( CMonster* thismon, UINT droptype );
void SendToAll( CPacket* pak );
UINT GetNewClientID( );
void DisconnectAll();
CPlayer* GetClientByUserID( UINT userid );
UINT GetMatIDfromRecipe (UINT CraftLevel, UINT matType);
UINT GetFairyRange( UINT part );
void RefreshFairy( );
inline dword GetStorageFee(dword iBasePrice, dword iPriceRate, dword uiDupCnt) {return ((((iBasePrice*5) / 0x3E8)+1)*(iPriceRate+1)) * uiDupCnt;};
//------------------ Fairies ---------------------
void DoFairyStuff( CPlayer* targetclient, int action );
void DoFairyFree( int fairy );
//------------------ MATH (extrafunctions.cpp)
fPoint RandInCircle(fPoint center, float radius);
fPoint RandInPoly(fPoint p[], int pcount);
fPoint RandInTriangle(fPoint p1, fPoint p2, fPoint p3);
float AreaOfTriangle(fPoint p1, fPoint p2, fPoint p3);
float distance( fPoint pos1, fPoint pos2 );
//------------------ PACKETS (worldpackets.cpp)
bool pakItemMall( CPlayer* thisclient, CPacket* P );
bool pakWeight( CPlayer* thisclient, CPacket* P );
bool pakPrintscreen( CPlayer* thisclient, CPacket* P );
bool pakModifiedItemDone( CPlayer* thisclient, CPacket* P );
bool pakSpawnDrop( CPlayer* thisclient, CDrop* thisdrop );
bool pakChangeStorage( CPlayer* thisclient, CPacket* P );
bool pakModifiedItem( CPlayer* thisclient, CPacket* P );
bool pakPartyManager( CPlayer* thisclient, CPacket* P );
bool pakLevelUpSkill( CPlayer *thisclient, CPacket* P );
bool pakChangeStance( CPlayer* thisclient, CPacket* P );
bool pakCharDSClient( CPlayer* thisclient, CPacket* P );
bool pakChangeEquip( CPlayer* thisclient, CPacket* P );
bool pakStartAttack( CPlayer* thisclient, CPacket* P );
bool pakSpawnNPC( CPlayer* thisclient, CNPC* thisnpc );
bool pakRideRequest( CPlayer* thisclient, CPacket* P );
bool pakPartyActions( CPlayer* thisclient, CPacket* P );
bool pakPartyOption( CPlayer* thisclient, CPacket* P );
bool pakTradeAction( CPlayer* thisclient, CPacket* P );
bool pakChangeCart( CPlayer* thisclient, CPacket* P );
bool pakSkillSelf ( CPlayer* thisclient, CPacket* P );
bool pakDoIdentify( CPlayer *thisclient, CPacket *P );
bool pakNormalChat( CPlayer* thisclient, CPacket* P );
bool pakCharSelect( CPlayer* thisclient, CPacket* P );
bool pakStartSkill( CPlayer* thisclient, CPacket* P );
bool pakRepairHammer( CPlayer* thisclient, CPacket* P );
bool pakRepairItem( CPlayer* thisclient, CPacket* P );
bool pakMoveSkill( CPlayer* thisclient, CPacket* P );
bool pakCloseShop( CPlayer* thisclient, CPacket* P );
bool pakStoreZuly( CPlayer* thisclient, CPacket* P );
bool pakPartyChat( CPlayer* thisclient, CPacket* P );
bool pakGameGuard( CPlayer* thisclient, CPacket* P );
bool pakOpenShop( CPlayer* thisclient, CPacket* P );
bool pakShowShop( CPlayer* thisclient, CPacket* P );
bool pakSellShop( CPlayer* thisclient, CPacket* P );
bool pakMoveChar( CPlayer* thisclient, CPacket* P );
bool pakStopChar( CPlayer* thisclient, CPacket* P );
bool pakPickDrop( CPlayer* thisclient, CPacket* P );
bool pakAddStats( CPlayer* thisclient, CPacket* P );
bool pakShowHeal( CPlayer* thisclient, CPacket* P );
bool pakSkillAOE( CPlayer* thisclient, CPacket* P );
bool pakidentify( CPlayer* thisclient, CPacket* P );
bool pakUserDied( CPlayer* thisclient, CPacket* P );
bool pakSaveTown( CPlayer* thisclient, CPacket* P );
bool pakTradeAdd( CPlayer* thisclient, CPacket* P );
bool pakUseItem ( CPlayer* thisclient, CPacket* P );
bool pakWhisper( CPlayer* thisclient, CPacket* P );
bool pakEquipABC(CPlayer* thisclient, CPacket *P );
bool pakStorage( CPlayer* thisclient, CPacket* P );
bool pakBuyShop( CPlayer* thisclient, CPacket* P );
bool pakDoEmote( CPlayer* thisclient, CPacket* P );
bool pakNPCBuy( CPlayer* thisclient, CPacket* P );
bool pakDoDrop( CPlayer* thisclient, CPacket* P );
bool pakShout( CPlayer* thisclient, CPacket* P );
bool pakCraft( CPlayer* thisclient, CPacket* P );
bool pakRespawn( CPlayer* thisclient, CPacket* P );
bool pakDoID( CPlayer* thisclient, CPacket* P );
bool pakGate( CPlayer* thisclient, CPacket* P );
bool pakExit( CPlayer* thisclient, CPacket* P );
bool pakPing( CPlayer* thisclient, CPacket* P );
bool SendLevelUPtoChar(CPlayer* thisclient );
void pakPlayer( CPlayer *thisclient );
void pakInventory( CPlayer *thisclient );
void pakQuestData( CPlayer *thisclient );
void pakClearUser( CPlayer* thisclient );
bool LearnSkill( CPlayer* thisclient, UINT skill, bool cost = true );
//-------------------------- Clan functions
bool pakClanManager ( CPlayer* thisclient, CPacket* P );
bool pakCreateClan ( CPlayer* thisclient, CPacket* P );
//------------------ GM COMMANDS (gmcmds.cpp)
bool pakGMMoveTo( CPlayer* thisclient, fPoint position );
bool pakGMTeleAllHere( CPlayer* thisclient );
bool GMShowTargetInfo( CPlayer* thisclient );
bool pakGMServerInfo( CPlayer* thisclient );
bool pakGMHeal( CPlayer* thisclient, int hpamount, int mpamount );
bool pakGMStat( CPlayer* thisclient, const char* statname, int statvalue );
bool pakGMItemtoplayer(CPlayer* thisclient, char* name , UINT itemid , UINT itemtype , UINT itemamount , UINT itemrefine , UINT itemls, UINT itemstats , UINT itemsocket) ;
bool pakGMItem( CPlayer* thisclient, UINT itemid , UINT itemtype , UINT itemamount , UINT itemrefine , UINT itemls, UINT itemstats , UINT itemsocket );
bool pakGMTeleOtherPlayer( CPlayer *thisclient, char* name, int map, float x, float y );
bool pakGMZuly( CPlayer* thisclient, int mode, int amount, char* charname );
bool pakGMTele( CPlayer* thisclient, int map, float x, float y );
bool pakGMMon( CPlayer* thisclient, int montype, int moncount, int monAI );
bool pakGMZulygive(CPlayer* thisclient, char* name, int zuly);
bool pakGMFairyto(CPlayer* thisclient, char* name, int mode);
bool pakGMManageFairy(CPlayer* thisclient, int mode);
bool pakGMChangeFairyWait(CPlayer* thisclient, int newvalue);
bool pakGMChangeFairyStay(CPlayer* thisclient, int newvalue);
bool pakGMChangeFairyTestMode(CPlayer* thisclient, int mode);
bool pakGMTelePlayerHere( CPlayer* thisclient, char* name );
bool pakGMLevel( CPlayer* thisclient, int level , char* name);
bool pakGMTeleToPlayer( CPlayer* thisclient, char* name );
bool pakGMDoEmote( CPlayer* thisclient, int emotionid );
bool pakGMCommand( CPlayer* thisclient, CPacket* P );
bool ReloadMobSpawn( CPlayer* thisclient, int id );
bool pakGMKick( CPlayer* thisclient, char* name );
bool pakGMAnn( CPlayer* thisclient, CPacket *P );
bool pakGMBan( CPlayer* thisclient, char* name );
bool pakGMInfo(CPlayer* thisclient, char* name);
bool pakGMNpc(CPlayer* thisclient, int npcid, int dialogid);
bool pakGMGotomap( CPlayer* thisclient, int map );
bool pakGMEffect( CPlayer* thisclient, int effect);
bool pakGMMute( CPlayer* thisclient, char* name, int time);
bool pakGMPartylvl( CPlayer* partyclient, int level );
bool pakGMChangePlayerDmg(CPlayer* thisclient, int rate);
bool pakGMChangeMonsterDmg(CPlayer* thisclient, int rate);
bool pakGMChangeMSpeedModif(CPlayer* thisclient, int modif);
bool pakGMChangeCfmode(CPlayer* thisclient, int mode);
bool pakGMUnionPoints(CPlayer* thisclient, char* name, int nb_points);
//------------------ CHAR SERVER COMMANDS (worldpackets.cpp)
bool TeleportTo ( CPlayer* thisclient, int map, fPoint position );
bool pakCSCharSelect( CPlayer* thisclient, CPacket* P );
bool pakCSReady( CPlayer* thisclient, CPacket* P );
//----------------- Server StartUp Functions (startup.cpp)
bool LoadSTBData( );
bool LoadZoneData( );
bool LoadConsItem( );
bool LoadSellData( );
bool LoadProductItem( );
bool LoadPatItem( );
bool LoadNaturalItem( );
bool LoadJemItem( );
bool LoadEquip( );
bool LoadItemStats( );
bool LoadTeleGateData( );
bool LoadMonsterSpawn( );
bool LoadMobGroups( );
bool LoadRespawnData( );
bool LoadWayPoints( );
bool LoadBreak( );
bool LoadGrades(); //LMA: loading refines (grades) bonuses.
bool LoadNewDrops( );
bool LoadPYDropsData( );
bool LoadSkillBookDropsData( );
bool LoadConfig( );
bool LoadLTB( );
bool LoadStatusData( );
bool LoadSkillData( );
bool LoadMonsters( );
bool LoadNPCData( );
bool LoadUpgrade( );
bool LoadNPCs( );
bool LoadSTB( );
bool LoadAIP( );
bool CleanConnectedList( );
void LoadZones();
// QSD Fuctions
void ReadQSD(strings path, dword index);
void LoadQuestData();
inline int round(double x) {return int(x > 0.0 ? x + 0.5 : x - 0.5);};
// AIP Functions
void ReadAIP(strings path, dword index);
void LoadAipData();
// Server Functions
bool SendPM( CPlayer* thisclient, const char* Format, ... );
bool SendGlobalMSG( CPlayer* thisclient, const char* Format, ... );
//bool CWorldServer::NPCShout( CMonster* thismon, char msg[200], char npc[50] );
bool NPCShout( int thismap, const char msg[200], const char npc[50] );
bool NPCMessage( CMonster* thismon, const char msg[200], const char npc[50] );
bool NPCWhisper( CPlayer* thisclient, CMonster* thismon, const char msg[200], const char npc[50] );
bool NPCAnnounce( const char msg[200], const char npc[50] );
UINT GetMaxPartyExp( UINT partylevel );
bool DoSkillScript( CCharacter* character, CSkills* thisskill );
bool AddParty( CParty* );
bool RemoveParty( CParty* );
UINT ClientIDList[0x10000]; // Clients List
UINT ClientIDIndex; // Index pointer for Client ID List
SOCKET csock; // Socket for accessing the char server
char* cct; // Encryption table for char server
vector<CTeleGate*> TeleGateList; // Telegates List
vector<CStatus*> StatusList; // Status List
vector<CSkills*> SkillList; // Skills List
vector<CMDrops*> MDropList; // Drops List
map<int, char*> NpcNameList; //LMA: npc name map.
map<UINT, char*> STLNameList; //LMA: Name for all things taken from STL.
map<UINT, char*> STLCommentList; //LMA: Comment for all things taken from STL.
//IfoObject WarpGate; //LMA: Warp Gate for Union.
CGrade GradeList[10];
int maxGrades; //Nb grades (refines)
vector<CMDrops*> SkillbookList; // Skillbook drop list
vector<CNPCData*> NPCData; // NPC/Mobs List
//vector<CAIPData*> AIPData; // AIP filename list
vector<CParty*> PartyList; // Party List
vector<CFairy*> FairyList; // Fairy List
std::map< unsigned, CNPCTrigger* > NPCActionList;
struct UpgradeList
{
UINT BindRune_Level;
UINT Talisman_Level;
UINT BindRune_Success;
UINT Talisman_Success;
};
CItemStas StatsList[500];
UpgradeList upgrade[10];
CEquipList EquipList[10];
CJemList JemList;
CNaturalList NaturalList;
CPatList PatList;
CProductList ProductList;
CBreakList BreakList;
CSellList SellList;
CUseList UseList;
CMapList MapList;
CSTBData STB_NPC; // NPC data
CSTBData STB_SKILL; // Skill data
CSTBData STB_STATUS; // Status Data
CSTBData STB_QUEST; // Quest data
CSTBData STB_ITEM[14]; // Item data
CSTBData STB_DROP; // Drop list
CSTBData STB_ZONE; // Zone data
CSTBData STB_PRODUCT; // Crafting data
CSTBData STB_BREAK; // Break data
CSTBData STB_SELL; // npc sell index
CSTBData ListGrade; // LMA: used to store the refine bonuses (% and +).
CSTBData ListUpGrade; // Bindrune and Tlisman upgrade data
vector<CQuestTrigger*> TriggerList;
fpQuestCond qstCondFunc[31];
fpQuestRewd qstRewdFunc[51];
vector<CAip*> AipList;
//vector<CAIPScript*> AIPList;
UINT maxSpawnId;
fpAiCond aiCondFunc[35];
fpAiAct aiActFunc[40];
int ObjVar[2000][20]; //NPC variables used in AI
UINT ThisSession; //session ID from database
UINT ServerStartTime; //time the server was started
UINT ServerRunTime; //Hours the server has been running
CLTBstring Ltbstring[200];
TowerDef WPList[100][100]; //Way point list for tower def. [mapid][wp id]
//int AIindex[500][6][20][1];
clock_t lastServerStep; // Last Update
clock_t LastUpdateTime; // Store the last update World Time
bool ServerOnline;
string filename;
pthread_t WorldThread[3];
pthread_t MapThread[200];
pthread_attr_t at;
pthread_mutex_t MapMutex,SQLMutex,PlayerMutex;
CDatabase* DB;
//Test thingies
unsigned ATTK_SPEED_MOD;
unsigned HIT_DELAY_MOD;
unsigned MOVE_SPEED_MOD;
};
extern class CWorldServer* GServer;
PVOID VisibilityProcess( PVOID TS );
PVOID MapProcess( PVOID TS );
PVOID WorldProcess( PVOID TS );
void ShutdownServer( PVOID TS );
void StartSignal( );
void StopSignal( );
void HandleSignal( int num );
// -----------------------------------------------------------------------------------------
#endif
+165
View File
@@ -0,0 +1,165 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://www.osrose.net
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "worldserver.h"
// Give Exp the KTRose way
bool CWorldServer::GiveExp( CMonster* thismon )
{
//Log(MSG_DEBUG,"Awarding EXP");
int tmpMult = 1;
if( thismon->owner != 0) // Summon
{
MapList.Index[thismon->Position->Map]->DeleteMonster( thismon );
return true;
}
// Give Experience Drops and Quest Items
vector<CPartyExp*> PartyExp;
vector<CParty*> PartyList;
for(UINT i=0;i<thismon->PlayersDamage.size();i++) // this is the list of players who did damage to the monster who just died
{
MonsterDamage* thisplayer = thismon->PlayersDamage.at(i);
CPlayer* thisclient = GetClientByCID( thisplayer->charid, thismon->Position->Map );
if( thisplayer->damage > 0 && thisclient != NULL ) //player did some damage. just making sure
{
//Log(MSG_DEBUG,"Player did %i damage max = %i",thisplayer->damage,thismon->Stats->MaxHP);
float MyPercent = (float)thisplayer->damage / thismon->Stats->MaxHP; //Figure out how much of the actual kill I am responsible for
if (MyPercent > 1.5)
MyPercent = 1.5; //set overkill ceiling
if( thisclient->Battle->target == thismon->clientid )
{
ClearBattle( thisclient->Battle )
thisclient->Position->destiny = thisclient->Position->current;
//Log(MSG_DEBUG,"(GiveExp) Destiny set to current position X: %f Y: %f.",thisclient->Position->current.x,thisclient->Position->current.y);
}
if( thismon->MonsterDrop->firsthit == thisclient->CharInfo->charid )
{
for( int q=0;q<10;q++)
{
// Give Quest Item
if( thisclient->quest.quests[q].QuestID != 0 )
{
Log(MSG_DEBUG,"Giving quest reward item for quest %i",thisclient->quest.quests[q].QuestID);
BEGINPACKET( pak, 0x731 )
ADDWORD ( pak, thismon->montype );
thisclient->client->SendPacket( &pak );
break;
}
}
}
//assign my own exp for monsters that I personally damaged
unsigned int exp = (unsigned int)floor(thismon->thisnpc->exp * MyPercent);
//unsigned int exp = (unsigned int)ceil((double)((thismon->thisnpc->exp * thisplayer->damage) / (thismon->thisnpc->hp*thismon->thisnpc->level)));
exp = exp * Config.EXP_RATE * tmpMult; //calculate base exp for this client. No medals or stuff accounted for yet
//Log(MSG_DEBUG,"MaxXP: %i config rate: %i percent: %f Total XP: %i", thismon->thisnpc->exp, Config.EXP_RATE, MyPercent, exp);
thisclient->CharInfo->Pending_Exp += (exp * thisclient->Stats->xprate); //store exp into thisclient's pending_exp using personal xprate adjustments
if( thisclient->Party->party != NULL ) //player is in a party so scan the party members
{
//Log(MSG_DEBUG,"Player is in a party");
CParty* party = thisclient->Party->party; //assign a party
if(party == NULL)
return true;
//Log(MSG_DEBUG,"party found. Counted = %i", party->counted);
for(UINT p=0;p<party->Members.size();p++) //loop through all the members in the party
{
//Log(MSG_DEBUG,"member %i being parsed", p);
if(!party->counted)
{
//Log(MSG_DEBUG,"party added to list. level = %i", party->PartyLevel);
party->counted = true; //tag the party so we don't add it to the list twice
PartyList.push_back( party ); //we will need this list later to convert pending exp to real exp
}
CPlayer* thismember = party->Members.at(p); //find a party member
if(thismember == NULL)
return true;
float RawTmpExp = (exp * (party->PartyLevel + 25) / 50);
unsigned int tempxp =(unsigned int)(floor)(RawTmpExp);
if (tempxp < 1)tempxp = 1;
//Log(MSG_DEBUG,"member %i pending exp = %i tempxp: %i", p, thismember->CharInfo->Pending_Exp, tempxp);
thismember->CharInfo->Pending_Exp += tempxp; // add a percentage of thisclient's non-adjusted exp to all party members including himself
//Log(MSG_DEBUG,"member %i pending exp (after tempxp) = %i", p, thismember->CharInfo->Pending_Exp);
}
if(party->PartyLevel < 50) //only give party exp if party level is under 50
{
party->Pending_Exp += exp; //add thisclient's non-adjusted xp to the pending exp of the party
}
}
else //not in a party so deal with all the exp now
{
//SendPM(thisclient, "You receive %i EXP",thisclient->CharInfo->Pending_Exp);
thisclient->CharInfo->Exp += thisclient->CharInfo->Pending_Exp;
thisclient->CharInfo->Pending_Exp = 0;
if(!thisclient->CheckPlayerLevelUP())
{
BEGINPACKET( pak, 0x79b );
ADDDWORD ( pak, thisclient->CharInfo->Exp );
ADDWORD ( pak, thisclient->CharInfo->stamina );
ADDWORD ( pak, 0 );
thisclient->client->SendPacket( &pak );
}
}
//Log(MSG_DEBUG,"Player rewarded %i experience after all mods",thisexp);
}
}
//new way PY
//Log(MSG_DEBUG,"Parsing party list now");
for(int p=0;p<PartyList.size();p++) //loop through our party list to assign final exp to all party members. We already did non-party members up there^
{
CParty* thisparty = PartyList.at( p );
if(thisparty == NULL)
{
//Log(MSG_DEBUG,"Party not valid");
continue;
}
//Log(MSG_DEBUG,"Party %i exp: %i pending exp: %i", p, thisparty->Exp, thisparty->Pending_Exp );
thisparty->counted = false; //reset the boolean for next time
for(UINT i=0;i<thisparty->Members.size();i++) //loop through all the members in the party
{
CPlayer* thismember = thisparty->Members.at(i); //find a party member
if(thismember == NULL)
return true;
thismember->CharInfo->Exp += thismember->CharInfo->Pending_Exp;
//Log(MSG_DEBUG,"Added pending exp %i to regular exp %i for member %i", thismember->CharInfo->Pending_Exp, thismember->CharInfo->Exp, i);
thismember->CharInfo->Pending_Exp = 0;
if(!thismember->CheckPlayerLevelUP( ))
{
BEGINPACKET( pak, 0x79b );
ADDDWORD ( pak, thismember->CharInfo->Exp );
ADDWORD ( pak, thismember->CharInfo->stamina );
ADDWORD ( pak, 0 );
thismember->client->SendPacket( &pak );
}
}
thisparty->Exp += thisparty->Pending_Exp;
thisparty->Pending_Exp = 0;
if( thisparty->Exp > GetMaxPartyExp(thisparty->PartyLevel)) //level up the party
{
thisparty->PartyLevel++;
thisparty->Exp -= GetMaxPartyExp(thisparty->PartyLevel-1);
}
BEGINPACKET( pak, 0x7d4 );
ADDBYTE ( pak, thisparty->PartyLevel );
ADDDWORD ( pak, thisparty->Exp );
thisparty->SendToMembers( &pak );
}
return true;
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+247
View File
@@ -0,0 +1,247 @@
// Props to ExJam for this code :D
#define AIACT(act) int F_AI_ACT_ ## act (class CWorldServer* server, class CCharacter* entity, byte* raw)
typedef int (*fpAiAct)(class CWorldServer*, class CCharacter*, byte*);
#define GETAIACTDATA(act) STR_AI_ACT_ ## act * data = (STR_AI_ACT_ ## act *)raw;
AIACT(000);AIACT(001);AIACT(002);
AIACT(003);AIACT(004);AIACT(005);
AIACT(006);AIACT(007);AIACT(008);
AIACT(009);AIACT(010);AIACT(011);
AIACT(012);AIACT(013);AIACT(014);
AIACT(015);AIACT(016);AIACT(017);
AIACT(018);AIACT(019);AIACT(020);
AIACT(021);AIACT(022);AIACT(023);
AIACT(024);AIACT(025);AIACT(026);
AIACT(027);AIACT(028);AIACT(029);
AIACT(030);AIACT(031);AIACT(032);
AIACT(033);AIACT(034);AIACT(035);
AIACT(036);AIACT(037);AIACT(038);
#define AI_ACT_COUNT 38
struct STR_AI_ACT_000 {
//Unknown (0x00 bytes)
};
struct STR_AI_ACT_001 {
//Do Action (0x04 bytes)
byte cAction; //Pos: 0x00
};
struct STR_AI_ACT_002 {
//Say LTB String (0x04 bytes)
dword iStrID; //Pos: 0x00
};
struct STR_AI_ACT_003 {
//Move (1) (0x08 bytes)
dword iDistance; //Pos: 0x00
byte cSpeed; //Pos: 0x04
};
struct STR_AI_ACT_004 {
//Move (2) (0x08 bytes)
dword iDistance; //Pos: 0x00
byte cSpeed; //Pos: 0x04
};
struct STR_AI_ACT_005 {
//Move (3) (0x04 bytes)
byte cSpeed; //Pos: 0x00
};
struct STR_AI_ACT_006 {
//Move (?) (0x08 bytes)
dword iDistance; //Pos: 0x00
byte cAbType; //Pos: 0x04
byte cMoreLess; //Pos: 0x05
};
struct STR_AI_ACT_007 {
//Unknown (0x00 bytes)
};
struct STR_AI_ACT_008 {
//Move (4) (0x08 bytes)
dword iDistance; //Pos: 0x00
byte cSpeed; //Pos: 0x04
};
struct STR_AI_ACT_009 {
//Spawn Monster (1) (0x04 bytes)
word wMonster; //Pos: 0x00
};
struct STR_AI_ACT_010 {
//Spawn Monster (2) (0x04 bytes)
word wMonster; //Pos: 0x00
};
struct STR_AI_ACT_011 {
//Spawn Monster (3) (0x08 bytes)
int iDistance; //Pos: 0x00
int iNumOfMonster; //Pos: 0x04
};
struct STR_AI_ACT_012 {
//Unknown (0x00 bytes)
};
struct STR_AI_ACT_013 {
//Unknown (0x00 bytes)
};
struct STR_AI_ACT_014 {
//Unknown (0x04 bytes)
int iDistance; //Pos: 0x00
};
struct STR_AI_ACT_015 {
//Retaliate ? (0x00 bytes)
};
struct STR_AI_ACT_016 {
//Unknown (0x04 bytes)
int iDistance; //Pos: 0x00
};
struct STR_AI_ACT_017 {
//Drop Item (0x10 bytes)
word items[6];
byte btToOwner; //Pos: 0x0c
};
struct STR_AI_ACT_018 {
//Spawn Monster (4) (0x08 bytes)
short cMonster; //Pos: 0x00
short wHowMany; //Pos: 0x02
int iDistance; //Pos: 0x04
};
struct STR_AI_ACT_019 {
//Unknown (0x00 bytes)
};
struct STR_AI_ACT_020 {
//Spawn Monster (5) (0x08 bytes)
word cMonster; //Pos: 0x00
byte btPos; //Pos: 0x02
int iDistance; //Pos: 0x04
};
struct STR_AI_ACT_021 {
//Unknown (0x00 bytes)
};
struct STR_AI_ACT_022 {
//Unknown (0x00 bytes)
};
struct STR_AI_ACT_023 {
//Unknown (0x00 bytes)
};
struct STR_AI_ACT_024 {
//Do Skill (0x08 bytes)
byte btTarget; //Pos: 0x00
word nSkill; //Pos: 0x02
word nMotion; //Pos: 0x04
};
struct STR_AI_ACT_025
{
//Set Variable (1) (0x0c bytes)
union
{
byte btVarIDX; //Pos: 0x00
char cVarIdx[4];
};
dword iValue; //Pos: 0x04
byte btOp; //Pos: 0x08
};
struct STR_AI_ACT_026 {
//Set Variable (2) (0x00 bytes)
union{word nVarNo; //Pos: 0x00
char cVarNo[4];};
dword iValue; //Pos: 0x04
byte btOp; //Pos: 0x08
};
struct STR_AI_ACT_027 {
//Set Variable (3) (0x00 bytes)
union{word nVarNo; //Pos: 0x00
char cVarNo[4];};
dword iValue; //Pos: 0x04
byte btOp; //Pos: 0x08
};
struct STR_AI_ACT_028
{
//Shout/Ann LTB String (0x08 bytes)
union
{
byte btMsgType;
int iMsgType;
};
dword iStrID; //Pos: 0x04
};
struct STR_AI_ACT_029 {
//Unknown (0x00 bytes)
};
struct STR_AI_ACT_030 {
//Do Trigger (0x0d bytes)
word lenszTrigger; //Pos: 0x00
char* szTrigger; //Pos: 0x02
};
struct STR_AI_ACT_031 {
//Unknown (0x00 bytes)
};
struct STR_AI_ACT_032 {
//Zone (1) (0x04 bytes)
word nZoneNo; //Pos: 0x00
byte btOnOff; //Pos: 0x02
};
struct STR_AI_ACT_033 {
//Zone (2) (0x00 bytes)
};
struct STR_AI_ACT_034 {
//Item (?) (0x04 bytes)
word nItemNum; //Pos: 0x00
word nCount; //Pos: 0x02
};
struct STR_AI_ACT_035 {
//Set Variable (4) (0x0c bytes)
union{word nVarIDX; //Pos: 0x00
char cVarIdx[4];};
dword iValue; //Pos: 0x04
byte btOp; //Pos: 0x08
};
struct STR_AI_ACT_036 {
//Monster (1) (0x04 bytes)
word nMonster; //Pos: 0x00
byte btMaster; //Pos: 0x02
};
struct STR_AI_ACT_037 {
//Monster (2) (0x0c bytes)
word nMonster; //Pos: 0x00
byte nPos; //Pos: 0x02
dword iDistance; //Pos: 0x04
byte btMaster; //Pos: 0x08
};
struct STR_AI_ACT_038
{
//TDEF set destiny position
byte cSpeed;
};
File diff suppressed because it is too large. Load diff
+266
View File
@@ -0,0 +1,266 @@
// Props to ExJam for this code :D
#define AICOND(cond) int F_AI_COND_ ## cond (class CWorldServer* server, class CCharacter* entity, byte* raw)
typedef int (*fpAiCond)(class CWorldServer*, class CCharacter*, byte*);
#define GETAICONDDATA(cond) STR_AI_COND_ ## cond * data = (STR_AI_COND_ ## cond *)raw;
AICOND(000);AICOND(001);AICOND(002);
AICOND(003);AICOND(004);AICOND(005);
AICOND(006);AICOND(007);AICOND(008);
AICOND(009);AICOND(010);AICOND(011);
AICOND(012);AICOND(013);AICOND(014);
AICOND(015);AICOND(016);AICOND(017);
AICOND(018);AICOND(019);AICOND(020);
AICOND(021);AICOND(022);AICOND(023);
AICOND(024);AICOND(025);AICOND(026);
AICOND(027);AICOND(028);AICOND(029);
AICOND(030);AICOND(031);AICOND(032);
#define AI_COND_COUNT 33
struct STR_AI_COND_000
{
//Hold or Attack (0x04 bytes)
byte cNotfightOrDelay; //Pos: 0x00
};
struct STR_AI_COND_001
{
//Damage (0x08 bytes)
dword iDamage; //Pos: 0x00
byte cRecvOrGive; //Pos: 0x04
};
struct STR_AI_COND_002
{
//Check Near (1) (0x0c bytes)
int iDistance; //Pos: 0x00
union
{
byte btIsAllied; //Pos: 0x04
word nIsAllied;
};
short nLevelDiff; //Pos: 0x06
short nLevelDiff2; //Pos: 0x08
word wChrNum; //Pos: 0x0a
};
struct STR_AI_COND_003
{
//Check Distance (1) (0x04 bytes)
int iDistance; //Pos: 0x00
};
struct STR_AI_COND_004
{
//Check Distance (2) (0x08 bytes)
int iDistance; //Pos: 0x00
byte cMoreLess; //Pos: 0x04
};
struct STR_AI_COND_005
{
//Check AB (1) (0x0c bytes)
byte cAbType; //Pos: 0x00
int iDiff; //Pos: 0x04
byte cMoreLess; //Pos: 0x08
};
struct STR_AI_COND_006
{
//Check HP (0x08 bytes)
dword wHP; //Pos: 0x00
byte cMoreLess; //Pos: 0x04
};
struct STR_AI_COND_007
{
//Random Chance (0x04 bytes)
byte cPercent; //Pos: 0x00
};
struct STR_AI_COND_008
{
//Check Near (2) (0x0c bytes)
dword iDistance; //Pos: 0x00
short nLevelDiff; //Pos: 0x04
short nLevelDiff2; //Pos: 0x06
byte btIsAllied; //Pos: 0x08
};
struct STR_AI_COND_009
{
//Unknown (0x00 bytes)
};
struct STR_AI_COND_010
{
//Check AB (2) (0x04 bytes)
byte cAbType; //Pos: 0x00
byte cMoreLess; //Pos: 0x01
};
struct STR_AI_COND_011 {
//Check AB (3) (0x0c bytes)
byte cAbType; //Pos: 0x00
word tBuffer; //Pos: 0x02
dword iValue; //Pos: 0x04
byte cMoreLess; //Pos: 0x08
};
struct STR_AI_COND_012
{
//Check Time (1) (0x04 bytes)
byte cWhen; //Pos: 0x00
};
struct STR_AI_COND_013
{
//Check Target (1) (0x04 bytes)
byte btCheckTarget; //Pos: 0x00
byte btStatusType; //Pos: 0x01
byte btHave; //Pos: 0x02
};
struct STR_AI_COND_014
{
//Check Variable (1) (0x0c bytes)
byte btVarIDX; //Pos: 0x00
word tBuffer; //Pos: 0x02
dword iValue; //Pos: 0x04
byte btOp; //Pos: 0x08
};
struct STR_AI_COND_015
{
//Check Variable (2) (0x0c bytes)
word nVarIDX; //Pos: 0x00
word tBuffer; //Pos: 0x02
dword iValue; //Pos: 0x04
byte btOp; //Pos: 0x08
};
struct STR_AI_COND_016
{
//Check Variable (3) (0x00 bytes)
word nVarIDX; //Pos: 0x00
word tBuffer; //Pos: 0x02
dword iValue; //Pos: 0x04
byte btOp; //Pos: 0x08
};
struct STR_AI_COND_017
{
//Select NPC (0x04 bytes)
dword iNpcNo; //Pos: 0x00
};
struct STR_AI_COND_018
{
//Check Distance (3) (0x08 bytes)
dword iDistance; //Pos: 0x00
byte btOp; //Pos: 0x04
};
struct STR_AI_COND_019
{
//Check Time (2) (0x08 bytes)
dword ulTime; //Pos: 0x00
dword ulEndTime; //Pos: 0x04
};
struct STR_AI_COND_020
{
//Check AB (4) (0x0c bytes)
union
{
byte btAbType; //Pos: 0x00
dword iAbType;
};
dword iValue; //Pos: 0x04
byte btOp; //Pos: 0x08
};
struct STR_AI_COND_021
{
//Unknown (0x00 bytes)
};
struct STR_AI_COND_022
{
//Unknown (0x00 bytes)
};
struct STR_AI_COND_023
{
//Check Time (3) (0x08 bytes)
dword ulTime; //Pos: 0x00
dword ulEndTime; //Pos: 0x04
};
struct STR_AI_COND_024
{
//Check Date Time (4) (0x08 bytes)
byte btDate; //Pos: 0x00
byte btHour1; //Pos: 0x01
byte btMin1; //Pos: 0x02
byte btHour2; //Pos: 0x03
byte btMin2; //Pos: 0x04
};
struct STR_AI_COND_025
{
//Check Weekday Time (5) (0x08 bytes)
byte btWeekDay; //Pos: 0x00
byte btHour1; //Pos: 0x01
byte btMin1; //Pos: 0x02
byte btHour2; //Pos: 0x03
byte btMin2; //Pos: 0x04
};
struct STR_AI_COND_026
{
//Check Position (0x04 bytes)
word nMin; //Pos: 0x00
word nMax; //Pos: 0x02
};
struct STR_AI_COND_027
{
//Check Near Character (0x10 bytes)
int iDistance; //Pos: 0x00
byte btIsAllied; //Pos: 0x04
short nLevelDiff; //Pos: 0x06
short nLevelDiff2; //Pos: 0x08
short wChrNum; //Pos: 0x0a
byte btOp; //Pos: 0x0c
};
struct STR_AI_COND_028
{
//Check Variable (4) (0x0c bytes)
word nVarIDX; //Pos: 0x00
dword iValue; //Pos: 0x04
byte btOp; //Pos: 0x08
};
struct STR_AI_COND_029
{
//Check Target (2) (0x04 bytes)
byte btTargetType; //Pos: 0x00
};
struct STR_AI_COND_030
{
//Unknown (0x04 bytes)
dword Timer; //Pos: 0x00
};
struct STR_AI_COND_031
{
//no data needed here
};
struct STR_AI_COND_032
{
//no data needed here
};
+167
View File
@@ -0,0 +1,167 @@
// Props to ExJam for this code :D
#include "../WorldServer.h"
void CWorldServer::ReadAIP(strings path, dword index)
{
CRoseFile* fh = new CRoseFile(path, FM_READ | FM_BINARY);
if(fh->IsOpen())
{ // goto done;
//Log(MSG_LOAD, "Loading %s ", path);
dword BlockCount = fh->Get<dword>();
dword mintime = fh->Get<dword>();
dword mindamage = fh->Get<dword>();
dword titlestringlength = fh->Get<dword>();
strings title = new char[titlestringlength+1];
strings title2 = new char[32+1];
fh->Read(title, titlestringlength, 1);
for(dword i = 0; i < BlockCount; i++)
{
titlestringlength = 32;
fh->Read(title2, titlestringlength, 1);//on spawn-idle-attack-attacked-killed target-dead
dword RecordCount = fh->Get<dword>();
for(dword j = 0; j < RecordCount; j++)
{
CAip* script = new CAip();
fh->Read(title2, titlestringlength, 1);// 00 ==============================
script->ConditionCount = fh->Get<dword>();
if(script->ConditionCount > 0)
{
script->Conditions = new CAip::SAipDatum*[script->ConditionCount];
for(dword k = 0; k < script->ConditionCount; k++)
{
CAip::SAipDatum* data = new CAip::SAipDatum();
data->size = fh->Get<dword>();
data->opcode = fh->Get<dword>() - 0x04000001;
data->data = new byte[data->size - 8];
fh->Read(data->data, data->size - 8, 1);
script->Conditions[k] = data;
}
}
else
{
script->Conditions = NULL;
}
script->ActionCount = fh->Get<dword>();
if(script->ActionCount > 0)
{
script->Actions = new CAip::SAipDatum*[script->ActionCount];
for(dword k = 0; k < script->ActionCount; k++)
{
CAip::SAipDatum* data = new CAip::SAipDatum();
data->size = fh->Get<dword>();
data->opcode = fh->Get<dword>() - 0x0B000001;
data->data = new byte[data->size - 8];
fh->Read(data->data, data->size - 8, 1);
script->Actions[k] = data;
}
}
else
{
script->Actions = NULL;
}
script->AInumber = index;
script->AipID=((index*0x10000)+(i*0x100)+j);
script->minDamage = mindamage;
script->minTime = mintime;
script->recordcount[i] = RecordCount;
AipList.push_back( script );
}
}
}
else
Log( MSG_ERROR, "AIP File: '%s' failed to load properly", path );
fh->Close();
delete fh;
}
void CWorldServer::LoadAipData()
{
CStrStb* stbAip = new CStrStb("3DDATA\\STB\\FILE_AI.STB");
Log(MSG_INFO, "Loading AIP files");
for(dword i = 1; i < stbAip->Rows(); i++)
{
if(stbAip->Data(i, 0))
{
GServer->ReadAIP(stbAip->Data(i, 0),i);
}
}
//Log(MSG_INFO, "%i aip entrys",AipList.size());
Log(MSG_INFO, "Finished loading aip data ");
aiCondFunc[0] = &F_AI_COND_000;
aiCondFunc[1] = &F_AI_COND_001;
aiCondFunc[2] = &F_AI_COND_002;
aiCondFunc[3] = &F_AI_COND_003;
aiCondFunc[4] = &F_AI_COND_004;
aiCondFunc[5] = &F_AI_COND_005;
aiCondFunc[6] = &F_AI_COND_006;
aiCondFunc[7] = &F_AI_COND_007;
aiCondFunc[8] = &F_AI_COND_008;
aiCondFunc[9] = &F_AI_COND_009;
aiCondFunc[10] = &F_AI_COND_010;
aiCondFunc[11] = &F_AI_COND_011;
aiCondFunc[12] = &F_AI_COND_012;
aiCondFunc[13] = &F_AI_COND_013;
aiCondFunc[14] = &F_AI_COND_014;
aiCondFunc[15] = &F_AI_COND_015;
aiCondFunc[16] = &F_AI_COND_016;
aiCondFunc[17] = &F_AI_COND_017;
aiCondFunc[18] = &F_AI_COND_018;
aiCondFunc[19] = &F_AI_COND_019;
aiCondFunc[20] = &F_AI_COND_020;
aiCondFunc[21] = &F_AI_COND_021;
aiCondFunc[22] = &F_AI_COND_022;
aiCondFunc[23] = &F_AI_COND_023;
aiCondFunc[24] = &F_AI_COND_024;
aiCondFunc[25] = &F_AI_COND_025;
aiCondFunc[26] = &F_AI_COND_026;
aiCondFunc[27] = &F_AI_COND_027;
aiCondFunc[28] = &F_AI_COND_028;
aiCondFunc[29] = &F_AI_COND_029;
aiCondFunc[30] = &F_AI_COND_030;
aiActFunc[0] = &F_AI_ACT_000;
aiActFunc[1] = &F_AI_ACT_001;
aiActFunc[2] = &F_AI_ACT_002;
aiActFunc[3] = &F_AI_ACT_003;
aiActFunc[4] = &F_AI_ACT_004;
aiActFunc[5] = &F_AI_ACT_005;
aiActFunc[6] = &F_AI_ACT_006;
aiActFunc[7] = &F_AI_ACT_007;
aiActFunc[8] = &F_AI_ACT_008;
aiActFunc[9] = &F_AI_ACT_009;
aiActFunc[10] = &F_AI_ACT_010;
aiActFunc[11] = &F_AI_ACT_011;
aiActFunc[12] = &F_AI_ACT_012;
aiActFunc[13] = &F_AI_ACT_013;
aiActFunc[14] = &F_AI_ACT_014;
aiActFunc[15] = &F_AI_ACT_015;
aiActFunc[16] = &F_AI_ACT_016;
aiActFunc[17] = &F_AI_ACT_017;
aiActFunc[18] = &F_AI_ACT_018;
aiActFunc[19] = &F_AI_ACT_019;
aiActFunc[20] = &F_AI_ACT_020;
aiActFunc[21] = &F_AI_ACT_021;
aiActFunc[22] = &F_AI_ACT_022;
aiActFunc[23] = &F_AI_ACT_023;
aiActFunc[24] = &F_AI_ACT_024;
aiActFunc[25] = &F_AI_ACT_025;
aiActFunc[26] = &F_AI_ACT_026;
aiActFunc[27] = &F_AI_ACT_027;
aiActFunc[28] = &F_AI_ACT_028;
aiActFunc[29] = &F_AI_ACT_029;
aiActFunc[30] = &F_AI_ACT_030;
aiActFunc[31] = &F_AI_ACT_031;
aiActFunc[32] = &F_AI_ACT_032;
aiActFunc[33] = &F_AI_ACT_033;
aiActFunc[34] = &F_AI_ACT_034;
aiActFunc[35] = &F_AI_ACT_035;
aiActFunc[36] = &F_AI_ACT_036;
aiActFunc[37] = &F_AI_ACT_037;
delete stbAip;
}
+29
View File
@@ -0,0 +1,29 @@
// Props to ExJam for this code :]
class CAip
{
public:
struct SAipDatum
{
int size;
int opcode;
byte* data;
};
dword AInumber;
dword AipID;
dword minDamage;
dword minTime;
byte recordcount[6];
dword ConditionCount;
SAipDatum** Conditions;
dword ActionCount;
SAipDatum** Actions;
int AipVar;
private:
};
#define AI_FAILURE 8
#define AI_SUCCESS 7
#include "AiConditions.h"
#include "AiActions.h"
+975
View File
@@ -0,0 +1,975 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://www.osrose.net
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "character.h"
#include "worldserver.h"
void CCharacter::DoAttack( )
{
//if(Status->Sleep <= 0xff)
//{
// ClearBattle( Battle );
// return; // can't take any action while we are asleep can we?
//}
//if(IsPlayer())
//{
// Log(MSG_INFO,"DoAttack Attack type %i selected. Chartype = %i casting = %i",Battle->atktype, CharType, Battle->iscasting);
//}
//if(CharType = 4) //it's an npc
//{
// Log(MSG_DEBUG,"NPC battle sequence");
//}
if(Battle->iscasting == 1)
{
CCharacter* Enemy = GetCharTarget( );
if(Enemy == NULL)
{
ClearBattle( Battle );
return;
}
//Log(MSG_DEBUG,"Iscasting detected as true.");
if(CanAttack())
{
if(IsPlayer())
{
//Log(MSG_DEBUG,"Should reach here once on normal attack. iscasting state = %i attack type = %i",Battle->iscasting, Battle->atktype);
if(Battle->atktype == 3) //buff
{
ClearBattle( Battle );
return;
}
else // if not buffing then resume normal attack.
{
//ClearBattle( Battle );
StartAction(Enemy, NORMAL_ATTACK, 0);
}
}
else //monsters should always resume normal attack
{
StartAction(Enemy, NORMAL_ATTACK, 0);
}
}
else
{
return;
}
return;
}
if(!CanAttack())
{
return;
}
if(IsSummon())
{
//Log(MSG_DEBUG,"Summon attacking in function DoAttack");
CCharacter* Enemy = GetCharTarget( );
if(Enemy == NULL) // || (Battle->atktype != SKILL_AOE && Battle->atktype != BUFF_AOE))
{
Log(MSG_DEBUG,"No Enemy found");
ClearBattle( Battle );
return;
}
if(this == Enemy) //summoned monster is attacking itself. It has been observed to happen
{
//Log(MSG_INFO,"Clearing Battle for this summon");
ClearBattle( Battle );
return;
}
if(Enemy->IsSummon())
{
CMonster* thisMonster = reinterpret_cast<CMonster*>(this);
if(thisMonster == NULL)
{
ClearBattle( Battle );
return;
}
CMonster* otherMonster = reinterpret_cast<CMonster*>(Enemy);
if(otherMonster == NULL)
{
ClearBattle( Battle );
return;
}
if(thisMonster->owner == otherMonster->owner)
{
//Log(MSG_INFO,"Clearing Battle for this summon");
ClearBattle( Battle );
return;
}
}
}
CMap* map = GServer->MapList.Index[Position->Map];
//if(IsPlayer())
//{
// Log(MSG_INFO,"DoAttack Battle Attack type = %i",Battle->atktype);
//}
switch(Battle->atktype)
{
case NORMAL_ATTACK://normal attack
{
//if(!Status->CanAttack)
// return; //can't attack right now.
CCharacter* Enemy = GetCharTarget( );
if(Enemy == NULL)
{
ClearBattle( Battle );
return;
}
if(Enemy == this)
{
//Log(MSG_INFO,"WTF?? I AM trying to attack myself");
ClearBattle( Battle );
}
if(IsTargetReached( Enemy ))
{
//if(IsMonster())
// Log(MSG_INFO,"Monster is trying to hit the player");
NormalAttack( Enemy );
if (Enemy->IsMonster()) // do monster AI script when monster is attacked.
{
CMonster* monster = GServer->GetMonsterByID(Enemy->clientid, Enemy->Position->Map);
if(monster == NULL)return;
//monster->DoAi(monster->thisnpc->AI, 3);
monster->DoAi(monster->monAI, 3);
}
}
}
break;
case SKILL_ATTACK://skill attack
{
CCharacter* Enemy = GetCharTarget( );
if(Enemy == NULL)
{
ClearBattle( Battle );
return;
}
CSkills* skill = GServer->GetSkillByID( Battle->skillid );
if(skill == NULL)
{
//ClearBattle( Battle );
return;
}
if(IsTargetReached( Enemy, skill ))
{
//Log(MSG_DEBUG,"Skill Attack reached target and started");
SkillAttack( Enemy, skill );
if (Enemy->IsMonster())
{
CMonster* monster = GServer->GetMonsterByID(Enemy->clientid, Enemy->Position->Map);
if(monster == NULL)return;
monster->DoAi(monster->monAI, 3);
Battle->atktype = NORMAL_ATTACK;
}
}
//else
//{
//Log(MSG_DEBUG,"Skill Attack failed to reach target");
//}
}
break;
case SKILL_BUFF://buffs
{
CCharacter* Enemy = GetCharTarget( );
if(Enemy == NULL)
{
//Log(MSG_DEBUG,"this target is NULL");
ClearBattle( Battle );
return;
}
CSkills* skill = GServer->GetSkillByID( Battle->skillid );
if(skill == NULL)
{
//Log(MSG_DEBUG,"this skill is NULL");
return;
}
if(IsTargetReached( Enemy, skill ))
{
//Log(MSG_DEBUG,"Skill successfully cast");
BuffSkill( Enemy, skill );
}
}
break;
case SKILL_AOE:
//case SKILL_SELF: //this is impossible. it can never be set
case AOE_TARGET:
{
//Log(MSG_DEBUG,"Called skill type %i",Battle->atktype);
CCharacter* Enemy = NULL;
CSkills* skill = GServer->GetSkillByID( Battle->skillid );
if(skill == NULL)
{
ClearBattle( Battle );
return;
}
if(Battle->atktype == AOE_TARGET)
{
float distance = GServer->distance( Position->current, Position->destiny );
if(distance <= skill->range)
{
Position->destiny = Position->current;
AoeSkill( skill, Enemy );
}
}
else
{
Position->skilltargetpos = Position->current;
AoeSkill( skill, NULL );
}
}
break;
case BUFF_SELF:
{
CSkills* skill = GServer->GetSkillByID( Battle->skillid );
if(skill == NULL)
{
//ClearBattle( Battle );
return;
}
BuffSkill( this, skill );
}
break;
case BUFF_AOE:
{
//Log(MSG_INFO,"BUFF AOE selected");
CSkills* skill = GServer->GetSkillByID( Battle->skillid );
if(skill == NULL)
{
return;
}
AoeBuff( skill );
}
break;
default:
return;
break;
}
}
// do normal attack
void CCharacter::NormalAttack( CCharacter* Enemy )
{
Enemy->OnBeAttacked( this );
Position->destiny = Position->current;
//Log(MSG_DEBUG,"(NormalAttack) Destiny set to current position X: %f Y: %f.",Position->current.x,Position->current.y);
// Even newer formula based on Jayce's idea
//dodge. gives a percentage chance
unsigned int hitpower = 0;
bool critical = false;
unsigned int totalchance = Stats->Accury + Enemy->Stats->Dodge;
double acdm = Stats->Accury * 100 / totalchance;
unsigned int hitchance = (unsigned int)floor(acdm);
if(GServer->RandNumber( 0, 100 ) > hitchance)
{
hitpower = 0; // dodged
//Log(MSG_DEBUG,"accuracy %i dodge %i",Stats->Accury,Enemy->Stats->Dodge);
//Log(MSG_DEBUG,"Dodged total %i mod %f hit chance %i",totalchance,acdm,hitchance);
}
else
{
//level adjustment. Not yet implemented
unsigned int leveltotal = Stats->Level + Enemy->Stats->Level;
double levelmod = Stats->Level * 200 / leveltotal;
//calculate damage
if(Stats->magicattack == 1) //magic attacks such as wands and some monsters
{
unsigned int totalpower = Stats->Attack_Power + Enemy->Stats->Magic_Defense;
double hitmod = Stats->Attack_Power * 100 / totalpower + Stats->Level; //percentage of hitpower to use * 100
hitpower = (unsigned int)floor((double)(hitmod * Stats->Attack_Power / 100));
}
else
{
unsigned int totalpower = Stats->Attack_Power + Enemy->Stats->Defense;
double hitmod = Stats->Attack_Power * 100 / totalpower + Stats->Level; //percentage of hitpower to use * 100
hitpower = (unsigned int)floor((double)(Stats->Attack_Power * hitmod / 100));
//Log(MSG_DEBUG,"Normal Attack: AP %i DEF %i",Stats->Attack_Power,Enemy->Stats->Defense);
//Log(MSG_DEBUG,"Normal Attack: hit total %i hitmod %f hit power %i",totalpower,hitmod,hitpower);
}
//add some randomness. + or - 5% of hitpower
int min = (int)floor((double)(hitpower * 0.85));
int max = (int)floor((double)(hitpower * 1.15));
int dif = max - min;
int mod = GServer->RandNumber( 0, dif );
hitpower = min + mod;
//Log(MSG_DEBUG,"min %i max %i dif %i mod %i modified hit power %i", min, max, dif, mod, hitpower);
if(hitpower <= 5)
{
hitpower = 5;
}
else
{
if(GServer->RandNumber(0,300)<Stats->Critical)
{
hitpower = (long int)floor(hitpower * 1.5);
critical = true;
//Log(MSG_DEBUG,"CRITICAL hit power %i", hitpower);
}
}
if (hitpower > 0x7ff)//2047 packet size limit.
hitpower = 0x7ff;
//Log(MSG_DEBUG,"Successful hit hit chance %i damage %i",hitchance, hitpower);
}
//end jayce formula
Battle->atktarget = Battle->target;
//if(IsMonster())
//{
//Log(MSG_INFO,"Monster hits player for %i damage. Attack target = %i",hitpower,Battle->atktarget);
//}
//Log( MSG_INFO, "hitpower %i. Attack %f ", hitpower,attack );
if(!Enemy->IsSummon( ) && Enemy->IsMonster( ))
{
Enemy->AddDamage( this, hitpower );
Enemy->damagecounter += hitpower;// is for AI
}
Enemy->Stats->HP -= hitpower;
//if(IsPlayer())
// Log(MSG_DEBUG,"Player attack did damage %i",hitpower);
//if(IsMonster())
// Log(MSG_DEBUG,"Monster attack did damage %i",hitpower);
BEGINPACKET( pak, 0x799 );
ADDWORD ( pak, clientid );
ADDWORD ( pak, Battle->atktarget );
if(Enemy->IsDead())
{
CDrop* thisdrop = NULL;
ADDWORD ( pak, (hitpower | ( critical?0xb000:0x8000 ) ));
if(!Enemy->IsSummon( ) && !Enemy->IsPlayer( ))
{
int thisdroprate = Stats->itemdroprate + GServer->Config.DROP_RATE;
//Log(MSG_DEBUG,"Monster killed. calling drops function %i times",thisdroprate);
for(int j=0;j<thisdroprate;j++)
{
thisdrop = Enemy->GetDrop( );
if(thisdrop != NULL)
{
CMap* map = GServer->MapList.Index[thisdrop->posMap];
map->AddDrop( thisdrop );
}
}
}
GServer->SendToVisible( &pak, Enemy );
ClearBattle(Battle);
//ClearBattle(Enemy->Battle);
if(Enemy->IsMonster())
{
CMonster* monster = reinterpret_cast<CMonster*>(Enemy);
if(monster == NULL)
{
//Log(MSG_DEBUG,"Monster killed. Failed to create monster object");
return;
}
else
{
//Log(MSG_DEBUG,"Monster killed. Setting death delay timer");
monster->DeathDelayTimer = clock();
}
}
OnEnemyDie( Enemy );
ClearBattle(Battle);
GServer->SendToVisible( &pak, Enemy );
}
else
{
ADDWORD ( pak, (hitpower|(hitpower>0?(critical?0x4000:0):0)));
//ADDDWORD ( pak, (hitpower>0?(critical?12:0):0) );
GServer->SendToVisible( &pak, Enemy );
}
ReduceABC( );
Battle->lastAtkTime = clock( );
//Battle->lastAtkTime = Battle->NextAtkTime;
}
// do skill attack
bool CCharacter::SkillAttack( CCharacter* Enemy, CSkills* skill )
{
Position->destiny = Position->current;
//Log(MSG_DEBUG,"(SkillAttack) Destiny set to current position X: %f Y: %f.",Position->current.x,Position->current.y);
//if(Battle->castTime == 0)
//{
BEGINPACKET( pak, 0x7bb );
ADDWORD ( pak, clientid );
GServer->SendToVisible( &pak, this );
// Battle->castTime = clock();
// return true;
//}
//else
//{
// clock_t etime = clock() - Battle->castTime;
// if(etime < SKILL_DELAY)
// return true;
//}
//Battle->castTime = 0;
UseAtkSkill( Enemy, skill );
Stats->MP -= (skill->mp - (skill->mp * Stats->MPReduction / 100));
if(Stats->MP < 0)
Stats->MP = 0;
//Battle->atktype = NORMAL_ATTACK;
//Battle->skilltarget = 0;
//Battle->atktarget = Battle->target;
//Battle->skillid = 0;
GServer->DoSkillScript( this, skill );
Battle->lastAtkTime = clock( );
//Battle->lastAtkTime = Battle->NextAtkTime;
if(Enemy->IsDead())
ClearBattle(Battle);
Battle->iscasting = 1;
//Log(MSG_DEBUG,"Cast a skill. Iscasting set to true");
return true;
}
// do buff skill
bool CCharacter::BuffSkill( CCharacter* Target, CSkills* skill )
{
Position->destiny = Position->current;
//Log(MSG_DEBUG,"(BuffSkill) Destiny set to current position X: %f Y: %f.",Position->current.x,Position->current.y);
//if(Battle->castTime == 0)
//{
BEGINPACKET( pak, 0x7bb );
ADDWORD ( pak, clientid );
GServer->SendToVisible( &pak, (CCharacter*)this );
// Battle->castTime = clock();
// return true;
//}
//else
//{
// clock_t etime = clock() - Battle->castTime;
// if(etime < SKILL_DELAY)
// return true;
//}
//Battle->castTime = 0;
//Log(MSG_DEBUG,"applied buff skill %i",skill->id);
UseBuffSkill( Target, skill );
Stats->MP -= (skill->mp - (skill->mp * Stats->MPReduction / 100));
if(Stats->MP < 0) Stats->MP = 0;
GServer->DoSkillScript( this, skill ); //summons a monster. Why do we do this for all skills?
if(!IsMonster())
{
//ClearBattle( Battle );
//Battle->bufftarget = 0;
//Battle->skilltarget = 0;
//Battle->skillid = 0;
//Battle->atktype = NORMAL_ATTACK;
}
else //Monsters need to be reset to normal attack and clear skill attacks.
{
//Battle->atktarget = Battle->target;
//Battle->bufftarget = 0;
//Battle->skilltarget = 0;
//Battle->skillid = 0;
//Battle->atktype = NORMAL_ATTACK;
//StartAction(Target, NORMAL_ATTACK);
}
//Battle->lastAtkTime = clock( );
Battle->lastAtkTime = Battle->NextAtkTime;
Battle->iscasting = 1;
return true;
}
//arnold
// do AoE skill
bool CCharacter::AoeSkill( CSkills* skill, CCharacter* Enemy )
{
Position->destiny = Position->current;
//Log(MSG_DEBUG,"(AoeSkill) Destiny set to current position X: %f Y: %f.",Position->current.x,Position->current.y);
//Log(MSG_INFO,"Doing AOE Skill");
//if(Battle->castTime == 0)
//{
BEGINPACKET( pak, 0x7bb );
ADDWORD ( pak, clientid );
GServer->SendToVisible( &pak, (CCharacter*)this );
// Battle->castTime = clock();
// return true;
//}
//else
//{
// clock_t etime = clock() - Battle->castTime;
// if(etime < SKILL_DELAY)
// return true;
//}
//Battle->castTime = 0;
CMap* map = GServer->MapList.Index[Position->Map];
//PY replacement code
if(IsPlayer() || IsSummon())
{
for(UINT i=0;i<map->MonsterList.size();i++)
{
CMonster* monster = map->MonsterList.at(i);
if(monster == NULL) continue;
if(monster->clientid == clientid) continue;
if(monster->IsSummon( ) && (map->allowpvp == 0 || monster->owner == clientid)) continue;
if(GServer->IsMonInCircle( Position->skilltargetpos, monster->Position->current,(float)skill->aoeradius + 1))
UseAtkSkill( (CCharacter*) monster, skill,1 );
}
}
if(IsMonster() && !IsSummon())
{
for(UINT i=0;i<map->PlayerList.size();i++)
{
CPlayer* player = map->PlayerList.at(i);
if(player == NULL)continue;
if(player->clientid == clientid) continue;
if(GServer->IsMonInCircle( Position->skilltargetpos, player->Position->current, (float)skill->aoeradius+1))
UseAtkSkill( (CCharacter*) player, skill,1 );
}
}
//PY end
// this code appears to me to be completely wrong replaced with code above
/*
for(UINT i=0;i<map->MonsterList.size();i++)
{
CMonster* monster = map->MonsterList.at(i);
if(monster->clientid == clientid) continue;
if(IsSummon( ) || IsPlayer( ))
{
if(monster->IsSummon( ) && (map->allowpvp==0 || monster->owner == clientid)) continue;
}
else
{
if(!monster->IsSummon( )) continue;
}
if(GServer->IsMonInCircle( Position->skilltargetpos, monster->Position->current,(float)skill->aoeradius + 1))
UseAtkSkill( (CCharacter*) monster, skill );
}
if(map->allowpvp!=0 || (IsMonster( ) && !IsSummon( )))
{
for(UINT i=0;i<map->PlayerList.size();i++)
{
CPlayer* player = map->PlayerList.at(i);
if(player->clientid==clientid) continue;
if(GServer->IsMonInCircle( Position->skilltargetpos,player->Position->current,(float)skill->aoeradius+1))
UseAtkSkill( (CCharacter*) player, skill );
}
}*/
Battle->iscasting = 1;
//Log(MSG_DEBUG,"Cast a skill. Iscasting set to true");
if(Enemy != NULL)
{
if(Enemy->IsDead( ))
ClearBattle( Battle );
}
else
ClearBattle( Battle );
Stats->MP -= (skill->mp - (skill->mp * Stats->MPReduction / 100));
if(Stats->MP < 0) Stats->MP = 0;
Battle->lastAtkTime = clock( );
//Battle->lastAtkTime = Battle->NextAtkTime;
//Send skill animation to the world
RESETPACKET( pak, 0x7b9);
ADDWORD ( pak, clientid);
ADDWORD ( pak, Battle->skillid);
ADDWORD ( pak, 1);
GServer->SendToVisible( &pak, this );
Battle->bufftarget = 0;
Battle->skilltarget = 0;
Battle->skillid = 0;
return true;
}
bool CCharacter::AoeBuff( CSkills* skill )
{
//Log(MSG_INFO,"BUFF AOE called with skill target ",skill->target);
Position->destiny = Position->current;
//Log(MSG_DEBUG,"(AoeBuff) Destiny set to current position X: %f Y: %f.",Position->current.x,Position->current.y);
BEGINPACKET( pak, 0x7bb );
ADDWORD ( pak, clientid );
GServer->SendToVisible( &pak, (CCharacter*)this );
CMap* map = GServer->MapList.Index[Position->Map];
if(CharType != 2) //player || Summon || NPC. Anything that is not a monster
{
//Log(MSG_INFO,"It's a Player, Summon or NPC");
for(UINT i=0;i<map->PlayerList.size();i++)
{
CPlayer* player = map->PlayerList.at(i);
if(player == NULL)continue;
switch(skill->target)
{
case 1: //tPartyMember
if(player->Party->party == GetParty())
{
//Log(MSG_INFO,"Applying AOE buff as long as I can find a close enough party member");
if (player == this) //it is me so I had better cast it anyway ^-^
{
UseBuffSkill( (CCharacter*)player, skill );
}
else if(player->Party->party != NULL) // Don't cast the skill on players who are not in any party at all.
{
if(GServer->IsMonInCircle( Position->current,player->Position->current,(float)skill->aoeradius + 1))
UseBuffSkill( (CCharacter*)player, skill );
}
}
break;
case 2: //tClanMember
if (player->Clan == GetClan( ) && (player->Clan != 0 || player == this))
{
//Log(MSG_INFO,"Applying AOE buff as long as I can find a close enough clan member");
if(GServer->IsMonInCircle( Position->current, player->Position->current, (float)skill->aoeradius + 1 ) )
UseBuffSkill( (CCharacter*)player, skill );
}
break;
case 3: //tAlly
case 7: //tAllCharacters
case 8: //tAllMembers. all characters
{
//Log(MSG_INFO,"Applying AOE buff as long as I can find a close enough allied Player");
if(GServer->IsMonInCircle( Position->current,player->Position->current,(float)skill->aoeradius + 1))
UseBuffSkill( (CCharacter*)player, skill );
}
break;
case 5: //tHostileCharacter
{
if (CharType == 2)
{
//Log(MSG_INFO,"Applying AOE buff as long as I can find a close enough hostile Player");
if(GServer->IsMonInCircle( Position->current,player->Position->current,(float)skill->aoeradius + 1))
UseBuffSkill( (CCharacter*)player, skill );
}
}
break;
default:
//Log(MSG_INFO,"No valid skill target found");
break;
}
}
}
else if (CharType == 2) //monster
{
//Log(MSG_INFO,"It's a monster");
for(UINT i=0;i<map->MonsterList.size();i++)
{
CMonster* monster = map->MonsterList.at(i);
if(monster == NULL)continue;
switch(skill->target)
{
case tPartyMember: // party
break;
case 2: //tClanMember
break;
case 3: //tAlly
case 7: //tAllCharacters
case 8: //tAllMembers. all characters
{
//Log(MSG_INFO,"Applying AOE buff as long as I can find a close enough monster");
if(GServer->IsMonInCircle( Position->current,monster->Position->current,(float)skill->aoeradius + 1))
UseBuffSkill( (CCharacter*)monster, skill );
}
break;
case tHostileCharacter:
break;
default:
break;
}
}
}
Stats->MP -= (skill->mp - (skill->mp * Stats->MPReduction / 100));
if(Stats->MP < 0) Stats->MP = 0;
//Battle->atktarget = Battle->target;
//Battle->bufftarget = 0;
//Battle->skilltarget = 0;
//Battle->skillid = 0;
//Battle->atktype = NORMAL_ATTACK;
ClearBattle( Battle );
Battle->lastAtkTime = clock( );
//Battle->lastAtkTime = Battle->NextAtkTime;
Battle->iscasting = 1;
//Send skill animation to the world
BEGINPACKET( pak1, 0x7b9);
ADDWORD ( pak1, clientid);
ADDWORD ( pak1, Battle->skillid);
ADDWORD ( pak1, 1);
GServer->SendToVisible( &pak1, this );
return true;
}
// use skill attack
void CCharacter::UseAtkSkill( CCharacter* Enemy, CSkills* skill, bool deBuff)
{
// Even newer formula based on Jayce's idea
//dodge. gives a percentage chance
Battle->iscasting = 1;
unsigned int hitpower = 0;
unsigned int Attack = 0;
// skill attacks now based on a percentage of base attack power so that they scale with level
Attack = (unsigned int)floor((double)skill->atkpower * Stats->Attack_Power / 100);
int success = GServer->RandNumber(0,100);
if(success <= skill->success)
{
//calculate damage
if(skill->skilltype == 6 || skill->skilltype == 7) //magical damage
{
//unsigned int totalpower = skill->atkpower + Enemy->Stats->Magic_Defense;
unsigned int totalpower = Attack + Enemy->Stats->Magic_Defense;
double hitmod = Attack * 100 / totalpower; //percentage of hitpower to use * 100
hitpower = (unsigned int)floor((double)(hitmod * Attack / 100));
//Log(MSG_DEBUG,"Skill magic: AP %i DEF %i",Stats->Attack_Power,Enemy->Stats->Defense);
//Log(MSG_DEBUG,"Skill magic: Skill power %i. Attack %i",skill->atkpower,Attack);
//Log(MSG_DEBUG,"Skill magic: hit total %i mod %f hit power %i",totalpower,hitmod,hitpower);
}
else
{
//unsigned int totalpower = skill->atkpower + Enemy->Stats->Defense;
unsigned int totalpower = Attack + Enemy->Stats->Defense;
double hitmod = Attack * 100 / totalpower; //percentage of hitpower to use * 100
hitpower = (unsigned int)floor((double)(hitmod * Attack / 100));
//Log(MSG_DEBUG,"Skill physical: AP %i DEF %i",Stats->Attack_Power,Enemy->Stats->Defense);
//Log(MSG_DEBUG,"Skill physical: Skill power %i. Attack %i",skill->atkpower,Attack);
//Log(MSG_DEBUG,"skill physical: hit total %i mod %f hit power %i",totalpower,hitmod,hitpower);
}
//add some randomness. + or - 5% of hitpower
int min = (int)floor((double)(hitpower * 0.85));
int max = (int)floor((double)(hitpower * 1.15));
int dif = max - min;
int mod = GServer->RandNumber( 0, dif );
hitpower = min + mod;
}
bool bflag = false;
Enemy->OnBeAttacked( this );
if(hitpower <= 0) hitpower = 0;
if(IsPlayer())
{
hitpower += (int)(hitpower * (Stats->ExtraDamage))/100;
}
if (skill->atkpower == 0)
{
hitpower = 0; // If the skill has a 0 atk power, it isn't meant to damage
Log( MSG_INFO, "This skill does no damage" );
//ClearBattle( Battle );
return; // probably need to add some alternative code here for legitimate skills that have no attack power.
}
if(hitpower > 2046)hitpower = 2046;
//Log(MSG_DEBUG,"Cast a skill. damage is %i",skillpower);
if(!Enemy->IsSummon( ) && Enemy->IsMonster( ))
{
Enemy->AddDamage( this, hitpower );
Enemy->damagecounter += hitpower;// is for AI
}
//Log( MSG_INFO, "modified skillpower = %i",hitpower );
Enemy->Stats->HP -= hitpower;
//if(IsPlayer())
// Log(MSG_DEBUG,"Player Spell did damage %i",hitpower);
//if(IsMonster())
// Log(MSG_DEBUG,"Monster spell did damage %i",hitpower);
BEGINPACKET( pak, 0x7b6 );
ADDWORD ( pak, Enemy->clientid );
ADDWORD ( pak, clientid );
ADDDWORD ( pak, 0x000007f8 );
ADDBYTE ( pak, 0x00 );
if (Enemy->Stats->HP < 1)
{
ADDWORD ( pak, hitpower + 0x8000 );
}
else
{
ADDWORD ( pak, hitpower + 0x2000 );
}
if(Enemy->IsDead())
{
//Log(MSG_DEBUG,"Enemy died");
CDrop* thisdrop = NULL;
ADDDWORD ( pak, 16 );
if(!Enemy->IsSummon( ) && !Enemy->IsPlayer( ))
{
//Log(MSG_DEBUG,"Monster killed. calling drops function %i times",Stats->itemdroprate);
int thisdroprate = Stats->itemdroprate + GServer->Config.DROP_RATE;
for(int j=0;j<thisdroprate;j++)
{
thisdrop = Enemy->GetDrop( );
if(thisdrop != NULL)
{
CMap* map = GServer->MapList.Index[thisdrop->posMap];
map->AddDrop( thisdrop );
}
}
}
CMonster* monster = reinterpret_cast<CMonster*>(Enemy);
if(Enemy->IsMonster())
{
if(monster == NULL)
{
//Log(MSG_DEBUG,"Monster killed. Failed to create monster object");
return;
}
else
{
//Log(MSG_DEBUG,"Monster killed. Setting death delay timer");
monster->DeathDelayTimer = clock();
}
}
OnEnemyDie( Enemy );
ClearBattle(Battle);
GServer->SendToVisible( &pak, Enemy );
}
else
{
ADDDWORD ( pak, 4 );
GServer->SendToVisible( &pak, Enemy );
bflag = GServer->AddBuffs( skill, Enemy, GetInt( ) );
//Send (de)buff information to the whole world
if(skill->nbuffs > 0 && bflag)
{
RESETPACKET( pak, 0x7b5 );
ADDWORD ( pak, Battle->skilltarget );
ADDWORD ( pak, clientid );
ADDWORD ( pak, Battle->skillid );
ADDWORD ( pak, GetInt( ) );
ADDBYTE ( pak, skill->nbuffs );
GServer->SendToVisible( &pak, Enemy );
}
}
if (deBuff) return;
//Send skill animation to the world
RESETPACKET( pak, 0x7b9);
ADDWORD ( pak, clientid);
ADDWORD ( pak, Battle->skillid);
ADDWORD ( pak, 1);
GServer->SendToVisible( &pak, this );
Battle->bufftarget = 0;
Battle->skilltarget = 0;
Battle->skillid = 0;
//Battle->lastAtkTime = clock( );
Battle->lastAtkTime = Battle->NextAtkTime; //trying this to time skills better
//Battle->atktype = NORMAL_ATTACK;
}
// use buff skill
void CCharacter::UseBuffSkill( CCharacter* Target, CSkills* skill, bool deBuff )
{
bool bflag = false;
bflag = GServer->AddBuffs( skill, Target, GetInt( ) );
//Log(MSG_INFO,"In UseBuffSkills, skill %i, nbuffs %i, bflag %i to %u",skill->id,skill->nbuffs,bflag,Target->clientid);
if(skill->nbuffs > 0 && bflag == true)
{
BEGINPACKET( pak, 0x7b5 );
ADDWORD ( pak, Target->clientid );
ADDWORD ( pak, clientid );
ADDWORD ( pak, Battle->skillid );
ADDWORD ( pak, GetInt( )/4 );
ADDBYTE ( pak, skill->nbuffs );
GServer->SendToVisible( &pak, Target );
//Log(MSG_DEBUG,"Buff Skill. buffs applied 1");
}
if (deBuff) return;
BEGINPACKET( pak, 0x7b9);
ADDWORD ( pak, clientid);
ADDWORD ( pak, Battle->skillid);
ADDWORD ( pak, 1);
GServer->SendToVisible( &pak, this );
//Log(MSG_DEBUG,"Buff Skill. buffs applied 2 nbuffs = %i",skill->nbuffs);
//Log(MSG_INFO,"UseBuffSkill: Target HP = %i",Target->Stats->HP);
}
// use buff skill from QSD
void CCharacter::UseBuffSkillQSD( CCharacter* Target, CSkills* skill, bool deBuff )
{
bool bflag = false;
bflag = GServer->AddBuffs( skill, Target, 1 );
//Log(MSG_INFO,"In UseBuffSkillsQSD, skill %i, nbuffs %i, bflag %i to %u",skill->id,skill->nbuffs,bflag,Target->clientid);
if(skill->nbuffs > 0 && bflag == true)
{
BEGINPACKET( pak, 0x7b5 );
ADDWORD ( pak, Target->clientid );
ADDWORD ( pak, Target->clientid );
ADDWORD ( pak, skill->id );
ADDWORD ( pak, 1 );
ADDBYTE ( pak, skill->nbuffs );
GServer->SendToVisible( &pak, Target );
//Log(MSG_DEBUG,"Buff Skill. buffs applied 1");
}
if (deBuff) return;
BEGINPACKET( pak, 0x7b9);
ADDWORD ( pak, Target->clientid);
ADDWORD ( pak, skill->id);
ADDWORD ( pak, 1);
GServer->SendToVisible( &pak, this );
//Log(MSG_DEBUG,"Buff Skill. buffs applied 2 nbuffs = %i",skill->nbuffs);
//Log(MSG_INFO,"UseBuffSkillQSD: Target HP = %i",Target->Stats->HP);
}
// Use a skill
bool CCharacter::UseSkill( CSkills* skill, CCharacter *Target )
{
if (skill->atkpower > 0)
{
Log(MSG_INFO, "Need to do %i%s %s in range %i to target %i",
( skill->atkpower ),
( (skill->range > 0) ? " AOE" : "" ),
( (GServer->isSkillTargetFriendly(skill)) ? "healing" : "damage" ),
( skill->range ),
( skill->target ) );
}
for (int i = 0; i < 2; i++) {
Log(MSG_INFO, "Status ID: %i", skill->status[i]);
if (skill->status[i] == 0) continue;
CStatus* status = GServer->GetStatusByID(skill->status[i]);
if (status == NULL) continue;
/************************
We'll probably need to use status->decrease (Figure out whether buf is up/down
status->repeat will tell us whether it's a one-time (Stat Boost [2]), repeat
(Recovery, continueing damage [1]) or Special (Status Effect [3]).
************************/
if (status->repeat == 1) // Continuous
{
Log(MSG_INFO, "Need to take stat %i and %s it by %i%s over %i seconds", skill->buff[i],
((status->decrease) ? "decrease" : "increase"),
((skill->value1[i] != 0) ? skill->value1[i] : skill->value2[i]),
((skill->value1[i] != 0) ? "" : "%"), skill->duration);
}
else if (status->repeat == 2) // Once (Stat Boost)
{
Log(MSG_INFO, "Need to take stat %i and %s it by %i%s for %i seconds", skill->buff[i],
((status->decrease) ? "decrease" : "increase"),
((skill->value1[i] != 0) ? skill->value1[i] : skill->value2[i]),
((skill->value1[i] != 0) ? "" : "%"), skill->duration);
} else if (status->repeat == 3) // Status Effect (Poison,etc)
{
Log(MSG_INFO, "Need to give user status effect %i for %i seconds", skill->buff[i],
((skill->value1[i] != 0) ? skill->value1[i] : skill->value2[i]),
( skill->duration ) );
}
}
return true;
}
+802
View File
@@ -0,0 +1,802 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://www.osrose.net
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "character.h"
#include "worldserver.h"
void CCharacter::DoAttack( )
{
//if(Status->Sleep <= 0xff)
//{
// ClearBattle( Battle );
// return; // can't take any action while we are asleep can we?
//}
if(IsSummon())
{
CCharacter* Enemy = GetCharTarget( );
if(Enemy == NULL && Battle->atktype != SKILL_AOE && Battle->atktype != BUFF_AOE)
{
//Log(MSG_DEBUG,"No Enemy found");
ClearBattle( Battle );
return;
}
//Log(MSG_DEBUG,"Client id: %i Enemy client id: %i",clientid, Enemy->clientid);
if(this == Enemy) //summoned monster is attacking itself. It has been observed to happen
{
//Log(MSG_INFO,"Clearing Battle for this summon");
ClearBattle( Battle );
return;
}
}
CMap* map = GServer->MapList.Index[Position->Map];
//Log(MSG_INFO,"DoAttack Battle Attack type = %i",Battle->atktype);
switch(Battle->atktype)
{
case NORMAL_ATTACK://normal attack
{
//if(!Status->CanAttack)
// return; //can't attack right now.
CCharacter* Enemy = GetCharTarget( );
if(Enemy == NULL)
{
ClearBattle( Battle );
return;
}
if(Enemy == this)
{
//Log(MSG_INFO,"WTF?? I AM trying to attack myself");
ClearBattle( Battle );
}
if(IsTargetReached( Enemy ) && CanAttack( ))
{
NormalAttack( Enemy );
if (Enemy->IsMonster()) // do monster AI script when monster is attacked.
{
CMonster* monster = GServer->GetMonsterByID(Enemy->clientid, Enemy->Position->Map);
if(monster == NULL)return;
monster->DoAi(monster->thisnpc->AI, 3);
}
}
}
break;
case SKILL_ATTACK://skill attack
{
//if(!Status->CanCastSkill)
// return; // can't cast skills right now
CCharacter* Enemy = GetCharTarget( );
if(Enemy == NULL)
{
ClearBattle( Battle );
return;
}
CSkills* skill = GServer->GetSkillByID( Battle->skillid );
if(skill == NULL)
{
//ClearBattle( Battle );
return;
}
if(IsTargetReached( Enemy, skill ) && CanAttack( ))
{
SkillAttack( Enemy, skill );
if (Enemy->IsMonster())
{
CMonster* monster = GServer->GetMonsterByID(Enemy->clientid, Enemy->Position->Map);
if(monster == NULL)return;
monster->DoAi(monster->thisnpc->AI, 3);
}
}
}
break;
case SKILL_BUFF://buffs
{
//if(!Status->CanCastSkill)
// return; // can't cast skills right now
CCharacter* Enemy = GetCharTarget( );
if(Enemy == NULL)
{
//Log(MSG_DEBUG,"this target is NULL");
ClearBattle( Battle );
return;
}
CSkills* skill = GServer->GetSkillByID( Battle->skillid );
if(skill == NULL)
{
//Log(MSG_DEBUG,"this skill is NULL");
//ClearBattle( Battle );
return;
}
//Log(MSG_DEBUG,"Called skill buff code for skill %i",skill->id);
if(IsTargetReached( Enemy, skill ) && CanAttack( ))
{
//Log(MSG_DEBUG,"Skill successfully cast");
BuffSkill( Enemy, skill );
}
}
break;
case SKILL_AOE:
//case SKILL_SELF: //this is impossible. it can never be set
case AOE_TARGET:
{
//if(!Status->CanCastSkill)
// return; // can't cast skills right now
//Log(MSG_DEBUG,"Called skill type %i",Battle->atktype);
CCharacter* Enemy = NULL;
CSkills* skill = GServer->GetSkillByID( Battle->skillid );
if(skill == NULL)
{
ClearBattle( Battle );
return;
}
if(Battle->atktype == AOE_TARGET)
{
float distance = GServer->distance( Position->current, Position->destiny );
if(distance <= skill->range && CanAttack( ))
{
Position->destiny = Position->current;
AoeSkill( skill, Enemy );
}
}
else
{
Position->skilltargetpos = Position->current;
AoeSkill( skill, NULL );
}
}
break;
case BUFF_SELF:
{
//if(!Status->CanCastSkill)
// return; // can't cast skills right now
CSkills* skill = GServer->GetSkillByID( Battle->skillid );
if(skill == NULL)
{
//ClearBattle( Battle );
return;
}
BuffSkill( this, skill );
}
break;
case BUFF_AOE:
{
//if(!Status->CanCastSkill)
// return; // can't cast skills right now
Log(MSG_INFO,"BUFF AOE selected");
CSkills* skill = GServer->GetSkillByID( Battle->skillid );
if(skill == NULL)
{
//ClearBattle( Battle );
return;
}
AoeBuff( skill );
}
break;
default:
return;
break;
}
}
// do normal attack
void CCharacter::NormalAttack( CCharacter* Enemy )
{
Enemy->OnBeAttacked( this );
Position->destiny = Position->current;
// PY code
float mod = 0;
if(IsPlayer())
{
mod = 23 + (Stats->Level / 1.5);
}
else
{
mod = 23 + (Stats->Level / 4);
}
float attack = 0;
if(Stats->magicattack == 1)
{
attack = (float) Stats->Attack_Power / Enemy->Stats->Magic_Defense;
attack *= mod;
}
else
{
attack = (float) Stats->Attack_Power / Enemy->Stats->Defense;
attack *= mod;
}
//PY end
if(attack < 5) attack = 5;
float d_attack = attack / 100;
mod = GServer->RandNumber( 0, 10 ) * d_attack;
attack += mod;
long int hitpower = (long int)floor(attack + GServer->RandNumber(0, 10));
if(IsPlayer( )) //temp fix to find balance btw monster and player
{
hitpower = (long int)floor(attack * (GServer->Config.PlayerDmg/100.00));
hitpower+=((hitpower*(Stats->ExtraDamage))/100);
}
if(IsMonster( )) //temp fix to find balance btw monster and player
hitpower = (long int)floor(attack * (GServer->Config.MonsterDmg/100.00));
bool critical = false;
if(hitpower <= 5)
{
hitpower = 5;
}
else
{
if(GServer->RandNumber(0,300)<Stats->Critical)
{
hitpower = (long int)floor(hitpower * 1.5);
critical = true;
}
}
// dodge
unsigned int hitvalue = (unsigned int)floor((double)(Stats->Accury * 100 / Enemy->Stats->Dodge));
if(hitvalue>100) hitvalue = 100;
if(GServer->RandNumber( 0, 100 )>hitvalue)
hitpower = 0; // dodged
if (hitpower > 0x7ff)//2047 packet size limit.
{
hitpower=0x7ff;
}
//maybe this little line here will fix my ghosty problem
//they are definitely attacking. But no animation so maybe atktarget is empty
Battle->atktarget = Battle->target;
//Well it does make the damage show up at teh client but the animation is still dodgey
if(IsMonster())
{
Log(MSG_INFO,"Monster hits player for %i damage. Attack target = %i",hitpower,Battle->atktarget);
}
//Log( MSG_INFO, "hitpower %i. Attack %f ", hitpower,attack );
if(!Enemy->IsSummon( ) && Enemy->IsMonster( ))
{
Enemy->AddDamage( this, hitpower );
Enemy->damagecounter += hitpower;// is for AI
}
Enemy->Stats->HP -= hitpower;
BEGINPACKET( pak, 0x799 );
ADDWORD ( pak, clientid );
ADDWORD ( pak, Battle->atktarget );
#ifdef USE124
ADDDWORD ( pak, hitpower );
#endif
if(Enemy->IsDead())
{
CDrop* thisdrop = NULL;
#ifndef USE124
ADDWORD ( pak, (hitpower | ( critical?0xb000:0x8000 ) ));
#else
ADDDWORD ( pak, critical?28:16 );
#endif
if(!Enemy->IsSummon( ) && !Enemy->IsPlayer( ))
{
thisdrop = Enemy->GetDrop( );
if(thisdrop!=NULL)
{
ADDFLOAT ( pak, thisdrop->pos.x*100 );
ADDFLOAT ( pak, thisdrop->pos.y*100 );
if(thisdrop->type == 1)
{
ADDWORD( pak, 0xccdf );
ADDDWORD( pak, thisdrop->amount );
}
else
{
ADDWORD ( pak, GServer->BuildItemHead( thisdrop->item ) );
ADDDWORD ( pak, GServer->BuildItemData( thisdrop->item ) );
}
ADDWORD ( pak, thisdrop->clientid );
ADDWORD ( pak, thisdrop->owner );
CMap* map = GServer->MapList.Index[thisdrop->posMap];
map->AddDrop( thisdrop );
}
}
GServer->SendToVisible( &pak, Enemy, thisdrop );
OnEnemyDie( Enemy );
}
else
{
#ifndef USE124
ADDWORD ( pak, (hitpower|(hitpower>0?(critical?0x4000:0):0)));
#else
ADDDWORD ( pak, (hitpower>0?(critical?12:0):0) );
#endif
GServer->SendToVisible( &pak, Enemy );
}
ReduceABC( );
Battle->lastAtkTime = clock( );
}
// do skill attack
bool CCharacter::SkillAttack( CCharacter* Enemy, CSkills* skill )
{
Position->destiny = Position->current;
//if(Battle->castTime==0)
//{
BEGINPACKET( pak, 0x7bb );
ADDWORD ( pak, clientid );
GServer->SendToVisible( &pak, this );
// Battle->castTime = clock();
// return true;
//}
//else
//{
// clock_t etime = clock() - Battle->castTime;
// if(etime<SKILL_DELAY)
// return true;
//}
//Battle->castTime = 0;
UseAtkSkill( Enemy, skill );
Stats->MP -= (skill->mp - (skill->mp * Stats->MPReduction / 100));
if(Stats->MP<0) Stats->MP=0;
if(Battle->contatk)
{
Battle->atktype = NORMAL_ATTACK;
Battle->skilltarget = 0;
Battle->atktarget = Battle->target;
Battle->skillid = 0;
}
else
{
//ClearBattle( Battle );
}
GServer->DoSkillScript( this, skill );
Battle->lastAtkTime = clock( );
return true;
}
// do buff skill
bool CCharacter::BuffSkill( CCharacter* Target, CSkills* skill )
{
Position->destiny = Position->current;
//if(Battle->castTime == 0)
//{
BEGINPACKET( pak, 0x7bb );
ADDWORD ( pak, clientid );
GServer->SendToVisible( &pak, (CCharacter*)this );
// Battle->castTime = clock();
// return true;
//}
//else
//{
// clock_t etime = clock() - Battle->castTime;
// if(etime < SKILL_DELAY)
// return true;
//}
//Battle->castTime = 0;
//Log(MSG_DEBUG,"applied buff skill %i",skill->id);
UseBuffSkill( Target, skill );
Stats->MP -= (skill->mp - (skill->mp * Stats->MPReduction / 100));
if(Stats->MP < 0) Stats->MP = 0;
GServer->DoSkillScript( this, skill ); //summons a monster. Why do we do this for all skills?
if(!IsMonster())
{
ClearBattle( Battle ); // clear battle for players when they use buff skills
//Battle->bufftarget = 0;
//Battle->skilltarget = 0;
//Battle->skillid = 0;
//Battle->atktype = NORMAL_ATTACK;
}
else //Monsters need to be reset to normal attack and clear skill attacks.
{
Battle->bufftarget = 0;
Battle->skilltarget = 0;
Battle->skillid = 0;
Battle->atktype = NORMAL_ATTACK;
}
Battle->lastAtkTime = clock( );
return true;
}
//arnold
// do AoE skill
bool CCharacter::AoeSkill( CSkills* skill, CCharacter* Enemy )
{
Position->destiny = Position->current;
//Log(MSG_INFO,"Doing AOE Skill");
//if(Battle->castTime == 0)
//{
BEGINPACKET( pak, 0x7bb );
ADDWORD ( pak, clientid );
GServer->SendToVisible( &pak, (CCharacter*)this );
// Battle->castTime = clock();
// return true;
//}
//else
//{
// clock_t etime = clock() - Battle->castTime;
// if(etime < SKILL_DELAY)
// return true;
//}
//Battle->castTime = 0;
CMap* map = GServer->MapList.Index[Position->Map];
//PY replacement code
if(IsPlayer() || IsSummon())
{
for(UINT i=0;i<map->MonsterList.size();i++)
{
CMonster* monster = map->MonsterList.at(i);
if(monster->clientid == clientid) continue;
if(monster->IsSummon( ) && (map->allowpvp == 0 || monster->owner == clientid)) continue;
if(GServer->IsMonInCircle( Position->skilltargetpos, monster->Position->current,(float)skill->aoeradius + 1))
UseAtkSkill( (CCharacter*) monster, skill );
}
}
if(IsMonster() && !IsSummon())
{
for(UINT i=0;i<map->PlayerList.size();i++)
{
CPlayer* player = map->PlayerList.at(i);
if(player->clientid == clientid) continue;
if(GServer->IsMonInCircle( Position->skilltargetpos,player->Position->current,(float)skill->aoeradius+1))
UseAtkSkill( (CCharacter*) player, skill );
}
}
//PY end
// this code appears to me to be completely wrong replaced with code above
/*
for(UINT i=0;i<map->MonsterList.size();i++)
{
CMonster* monster = map->MonsterList.at(i);
if(monster->clientid == clientid) continue;
if(IsSummon( ) || IsPlayer( ))
{
if(monster->IsSummon( ) && (map->allowpvp==0 || monster->owner == clientid)) continue;
}
else
{
if(!monster->IsSummon( )) continue;
}
if(GServer->IsMonInCircle( Position->skilltargetpos, monster->Position->current,(float)skill->aoeradius + 1))
UseAtkSkill( (CCharacter*) monster, skill );
}
if(map->allowpvp!=0 || (IsMonster( ) && !IsSummon( )))
{
for(UINT i=0;i<map->PlayerList.size();i++)
{
CPlayer* player = map->PlayerList.at(i);
if(player->clientid==clientid) continue;
if(GServer->IsMonInCircle( Position->skilltargetpos,player->Position->current,(float)skill->aoeradius+1))
UseAtkSkill( (CCharacter*) player, skill );
}
}*/
if(Enemy != NULL)
{
if(!Enemy->IsDead( ))
{
Battle->atktarget = Battle->target;
Battle->atktype = NORMAL_ATTACK;
Battle->skilltarget = 0;
Battle->skillid = 0;
}
else ClearBattle( Battle );
}
else ClearBattle( Battle );
Stats->MP -= (skill->mp - (skill->mp * Stats->MPReduction / 100));
if(Stats->MP < 0) Stats->MP = 0;
Battle->lastAtkTime = clock( );
return true;
}
bool CCharacter::AoeBuff( CSkills* skill )
{
//Log(MSG_INFO,"BUFF AOE called");
Position->destiny = Position->current;
BEGINPACKET( pak, 0x7bb );
ADDWORD ( pak, clientid );
GServer->SendToVisible( &pak, (CCharacter*)this );
CMap* map = GServer->MapList.Index[Position->Map];
if(CharType == 1 || CharType == 3) //player || Summon
{
for(UINT i=0;i<map->PlayerList.size();i++)
{
CPlayer* player = map->PlayerList.at(i);
switch(skill->target)
{
case 1: //tPartyMember
if(player->Party->party == GetParty( ))
{
//Log(MSG_INFO,"Applying AOE buff as long as I can find a close enough party member");
if(GServer->IsMonInCircle( Position->current,player->Position->current,(float)skill->aoeradius + 1))
UseBuffSkill( (CCharacter*)player, skill );
}
break;
case 2: //tClanMember
if (player->Clan == GetClan( ))
{
//Log(MSG_INFO,"Applying AOE buff as long as I can find a close enough clan member");
if(GServer->IsMonInCircle( Position->current, player->Position->current, (float)skill->aoeradius + 1 ) )
UseBuffSkill( (CCharacter*)player, skill );
}
break;
case 3: //tAlly
case 7: //tAllCharacters
case 8: //tAllMembers. all characters
{
//Log(MSG_INFO,"Applying AOE buff as long as I can find a close enough allied Player");
if(GServer->IsMonInCircle( Position->current,player->Position->current,(float)skill->aoeradius + 1))
UseBuffSkill( (CCharacter*)player, skill );
}
break;
case 5: //tHostileCharacter
{
if (CharType == 2)
{
//Log(MSG_INFO,"Applying AOE buff as long as I can find a close enough hostile Player");
if(GServer->IsMonInCircle( Position->current,player->Position->current,(float)skill->aoeradius + 1))
UseBuffSkill( (CCharacter*)player, skill );
}
}
break;
}
}
}
else if (CharType == 2) //monster
{
for(UINT i=0;i<map->MonsterList.size();i++)
{
CMonster* monster = map->MonsterList.at(i);
switch(skill->target)
{
case tPartyMember: // party
break;
case 2: //tClanMember
break;
case 3: //tAlly
case 7: //tAllCharacters
case 8: //tAllMembers. all characters
{
Log(MSG_INFO,"Applying AOE buff as long as I can find a close enough monster");
if(GServer->IsMonInCircle( Position->current,monster->Position->current,(float)skill->aoeradius + 1))
UseBuffSkill( (CCharacter*)monster, skill );
}
break;
case tHostileCharacter:
break;
}
}
}
Stats->MP -= (skill->mp - (skill->mp * Stats->MPReduction / 100));
if(Stats->MP < 0) Stats->MP = 0;
Battle->bufftarget = 0;
Battle->skilltarget = 0;
Battle->skillid = 0;
Battle->atktype = NORMAL_ATTACK;
//ClearBattle( Battle );
Battle->lastAtkTime = clock( );
return true;
}
// use skill attack
void CCharacter::UseAtkSkill( CCharacter* Enemy, CSkills* skill, bool deBuff)
{
long int skillpower = 0;
if(skill->skilltype == 6 || skill->skilltype == 7) //magical damage
{
skillpower = skill->atkpower * 2;
}
else // physical damage
{
skillpower = skill->atkpower * 2;
}
UINT weapontype = 0;
float mod = 0;
float attack = 0;
if(IsPlayer())
{
mod = 35 + (Stats->Level / 2);
}
else
{
mod = 35 + (Stats->Level / 2);
}
if(skill->skilltype == 6 || skill->skilltype == 7) //magical damage
{
attack = skillpower / Enemy->Stats->Magic_Defense;
}
else
{
attack = skillpower / Enemy->Stats->Defense;
}
attack *= mod;
attack += (Stats->Attack_Power / 2); // let's add our AP to the skillpower to make it worthwhile to cast skills.
skillpower = (int)attack;
bool bflag = false;
Enemy->OnBeAttacked( this );
if(skillpower <= 0) skillpower = 0;
if(IsPlayer())
{
skillpower += (int)(skillpower * (Stats->ExtraDamage))/100;
}
if (skill->atkpower == 0)
{
skillpower = 0; // If the skill has a 0 atk power, it isn't meant to damage
Log( MSG_INFO, "This skill does no damage" );
//ClearBattle( Battle );
return; // probably need to add some alternative code here for legitimate skills that have no attack power.
}
if(skillpower >2046)skillpower = 2046;
if(!Enemy->IsSummon( ) && Enemy->IsMonster( ))
{
Enemy->AddDamage( this, skillpower );
Enemy->damagecounter += skillpower;// is for AI
}
Enemy->Stats->HP -= skillpower;
BEGINPACKET( pak, 0x7b6 );
ADDWORD ( pak, Enemy->clientid );
ADDWORD ( pak, clientid );
ADDDWORD ( pak, 0x000007f8 );
ADDBYTE ( pak, 0x00 );
if (Enemy->Stats->HP<1)
{
ADDWORD ( pak, skillpower + 0x8000 );
}
else
{
ADDWORD ( pak, skillpower + 0x2000 );
}
if(Enemy->IsDead())
{
CDrop* thisdrop = NULL;
ADDDWORD ( pak, 16 );
if(!Enemy->IsSummon( ) && !Enemy->IsPlayer( ))
{
thisdrop = Enemy->GetDrop( );
if(thisdrop!=NULL)
{
ADDFLOAT ( pak, thisdrop->pos.x*100 );
ADDFLOAT ( pak, thisdrop->pos.y*100 );
if(thisdrop->type==1)
{
ADDWORD( pak, 0xccdf );
ADDDWORD( pak, thisdrop->amount );
}
else
{
ADDWORD ( pak, GServer->BuildItemHead( thisdrop->item ) );
ADDDWORD ( pak, GServer->BuildItemData( thisdrop->item ) );
}
ADDWORD ( pak, thisdrop->clientid );
ADDWORD ( pak, thisdrop->owner );
CMap* map = GServer->MapList.Index[thisdrop->posMap];
map->AddDrop( thisdrop );
}
}
GServer->SendToVisible( &pak, Enemy, thisdrop );
OnEnemyDie( Enemy );
}
else
{
ADDDWORD ( pak, 4 );
GServer->SendToVisible( &pak, Enemy );
bflag = GServer->AddBuffs( skill, Enemy, GetInt( ) );
//Send (de)buff information to the whole world
if(skill->nbuffs>0 && bflag)
{
BEGINPACKET( pak, 0x7b5 );
ADDWORD ( pak, Battle->skilltarget );
ADDWORD ( pak, clientid );
ADDWORD ( pak, Battle->skillid );
ADDWORD ( pak, GetInt( ) );
ADDBYTE ( pak, skill->nbuffs );
GServer->SendToVisible( &pak, Enemy );
}
}
if (deBuff) return;
//Send skill animation to the world
RESETPACKET( pak, 0x7b9);
ADDWORD ( pak, clientid);
ADDWORD ( pak, Battle->skillid);
ADDWORD ( pak, 1);
GServer->SendToVisible( &pak, this );
Battle->bufftarget = 0;
Battle->skilltarget = 0;
Battle->skillid = 0;
Battle->atktype = NORMAL_ATTACK;
}
// use buff skill
void CCharacter::UseBuffSkill( CCharacter* Target, CSkills* skill )
{
bool bflag = false;
bflag = GServer->AddBuffs( skill, Target, GetInt( ) );
if(skill->nbuffs > 0 && bflag == true)
{
BEGINPACKET( pak, 0x7b5 );
ADDWORD ( pak, Target->clientid );
ADDWORD ( pak, clientid );
ADDWORD ( pak, Battle->skillid );
ADDWORD ( pak, GetInt( )/4 );
ADDBYTE ( pak, skill->nbuffs );
GServer->SendToVisible( &pak, Target );
//Log(MSG_DEBUG,"Buff Skill. buffs applied 1");
}
BEGINPACKET( pak, 0x7b9);
ADDWORD ( pak, clientid);
ADDWORD ( pak, Battle->skillid);
ADDWORD ( pak, 1);
GServer->SendToVisible( &pak, this );
//Log(MSG_DEBUG,"Buff Skill. buffs applied 2 nbuffs = %i",skill->nbuffs);
//Log(MSG_INFO,"Target HP = %i",Target->Stats->HP);
}
// Use a skill
bool CCharacter::UseSkill( CSkills* skill, CCharacter *Target )
{
if (skill->atkpower > 0)
{
Log(MSG_INFO, "Need to do %i%s %s in range %i to target %i",
( skill->atkpower ),
( (skill->range > 0) ? " AOE" : "" ),
( (GServer->isSkillTargetFriendly(skill)) ? "healing" : "damage" ),
( skill->range ),
( skill->target ) );
}
for (int i = 0; i < 2; i++) {
Log(MSG_INFO, "Status ID: %i", skill->status[i]);
if (skill->status[i] == 0) continue;
CStatus* status = GServer->GetStatusByID(skill->status[i]);
if (status == NULL) continue;
/************************
We'll probably need to use status->decrease (Figure out whether buf is up/down
status->repeat will tell us whether it's a one-time (Stat Boost [2]), repeat
(Recovery, continueing damage [1]) or Special (Status Effect [3]).
************************/
if (status->repeat == 1) // Continuous
{
Log(MSG_INFO, "Need to take stat %i and %s it by %i%s over %i seconds", skill->buff[i],
((status->decrease) ? "decrease" : "increase"),
((skill->value1[i] != 0) ? skill->value1[i] : skill->value2[i]),
((skill->value1[i] != 0) ? "" : "%"), skill->duration);
}
else if (status->repeat == 2) // Once (Stat Boost)
{
Log(MSG_INFO, "Need to take stat %i and %s it by %i%s for %i seconds", skill->buff[i],
((status->decrease) ? "decrease" : "increase"),
((skill->value1[i] != 0) ? skill->value1[i] : skill->value2[i]),
((skill->value1[i] != 0) ? "" : "%"), skill->duration);
} else if (status->repeat == 3) // Status Effect (Poison,etc)
{
Log(MSG_INFO, "Need to give user status effect %i for %i seconds", skill->buff[i],
((skill->value1[i] != 0) ? skill->value1[i] : skill->value2[i]),
( skill->duration ) );
}
}
return true;
}
+205
View File
@@ -0,0 +1,205 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://www.osrose.net
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "character.h"
#include "worldserver.h"
//constructor
CCharacter::CCharacter( )
{
// STATS
Stats = new STATS;
//refnpc=NULL;
assert(Stats);
Stats->Level = 0;
Stats->HP = 0;
Stats->MP = 0;
Stats->MaxHP = 0;
Stats->MaxMP = 0;
Stats->Attack_Power = 0;
Stats->Defense = 0;
Stats->Critical = 0;
Stats->Dodge = 0;
Stats->Accury = 0;
Stats->Magic_Defense = 0;
Stats->Move_Speed = 0;
Stats->Attack_Speed = 0;
Stats->Attack_Distance = 0;
Stats->MaxWeight = 0;
Stats->MaxSummonGauge = 0;
Stats->MPReduction = 0;
Stats->ExtraDamage = 0;
// POSITION
Position = new POSITION;
assert(Position);
Position->Map = 0;
Position->lastMoveTime = 0;
Position->saved = 0;
Position->respawn = 0;
//BATLE
Battle = new BATTLE;
assert(Battle);
ClearBattle( Battle );
Battle->castTime = 0;
//STATUS
Status = new STATUS;
assert(Status);
//Stats up
Status->Attack_up = 0xff;
Status->Defense_up = 0xff;
Status->Magic_Defense_up = 0xff;
Status->Accury_up = 0xff;
Status->Critical_up = 0xff;
Status->Dodge_up = 0xff;
Status->Haste_up = 0xff;
Status->Dash_up = 0xff;
Status->HP_up = 0xff;
Status->MP_up = 0xff;
//Stats down
Status->Attack_down = 0xff;
Status->Defense_down = 0xff;
Status->Magic_Defense_down = 0xff;
Status->Accury_down = 0xff;
Status->Critical_down = 0xff;
Status->Dodge_down = 0xff;
Status->Haste_down = 0xff;
Status->Dash_down = 0xff;
Status->HP_down = 0xff;
Status->MP_down = 0xff;
//Status
Status->Stuned = 0xff;
Status->Poisoned = 0xff;
Status->Muted = 0xff;
Status->ExtraDamage_up = 0xff;
Status->ExtraDamage_down = 0xff;
Status->Sleep = 0xff;
Status->CanAttack = true;
Status->CanRun = true;
Status->CanMove = true;
Status->CanCastSkill = true;
// Stance
Status->Stance = RUNNING;
for(int i=0;i<30;i++)
{
MagicStatus[i].Status = 0;
MagicStatus[i].Buff = 0;
MagicStatus[i].Value =0;
MagicStatus[i].Duration = 0;
MagicStatus[i].BuffTime = 0;
}
CharType = 0;
clientid = 0xffff;
nearChar = NULL;
findChar = NULL;
}
//deconstructor
CCharacter::~CCharacter( )
{
delete Stats;
delete Position;
delete Battle;
delete Status;
}
// Virtual
bool CCharacter::UpdateValues( )
{
return true;
}
// update position
void CCharacter::UpdatePosition( )
{
float ntime;
clock_t etime = clock() - Position->lastMoveTime;
if(IsOnBattle( ) && Battle->target != 0)
{
CCharacter* Target = GetCharTarget( );
if(Target == NULL)
ClearBattle( Battle );
}
if(!IsMoving())
{
if(IsPlayer())Position->lastMoveTime = clock();
return;
}
float dx = Position->destiny.x - Position->current.x;
float dy = Position->destiny.y - Position->current.y;
float distance = sqrt( (dx*dx) + (dy*dy) );
if(IsPlayer())
{
ntime = ( distance / (float(Stats->Move_Speed)/GServer->MOVE_SPEED_MOD)) * CLOCKS_PER_SEC; // calculates clock ticks to target position
//Log( MSG_DEBUG, "Dist: %f Speed: %i Mod: %i ntime: %f", distance, Stats->Move_Speed, GServer->MOVE_SPEED_MOD, ntime);
}
if(IsMonster())
{
ntime = ( distance / (float(Stats->Move_Speed)/GServer->MOVE_SPEED_MOD)) * CLOCKS_PER_SEC; // calculates clock ticks to target position
Position->current.x = dx*(etime/ntime) + Position->current.x;
Position->current.y = dy*(etime/ntime) + Position->current.y;
}
//float ntime = ( distance / Stats->Move_Speed * GServer->MOVE_SPEED_MOD ); // lmame method
/*if(IsPlayer())
{
Log(MSG_DEBUG,"ntime = %f distance = %f ",ntime, distance );
}*/
if(IsOnBattle() && distance <= Stats->Attack_Distance) //this will prevent the character from moving if in battle and in range
{
Position->destiny.x = Position->current.x;
Position->destiny.y = Position->current.y;
dx = 0;
dy = 0;
}
if (ntime <= etime || distance == 0)
{
/*if(IsPlayer())
{
Log(MSG_DEBUG,"Movement timed out or target reached. Set current to destiny.");
}*/
Position->current.x = Position->destiny.x;
Position->current.y = Position->destiny.y;
}
else
{
if(IsPlayer())
{
/*{
Log(MSG_DEBUG,"Still moving. Distance to target %f time to target %f", distance, ntime);
}*/
Position->current.x = dx*(etime/ntime) + Position->current.x;
Position->current.y = dy*(etime/ntime) + Position->current.y;
}
}
/*if(IsPlayer())
{
if(Position->current.x == Position->destiny.x)
{
Log(MSG_DEBUG,"Character is at destiny position in the X direction.");
}
else
{
Log(MSG_DEBUG,"Character is still moving. current x %f Destination x %f",Position->current.x,Position->destiny.x);
}
}*/
Position->lastMoveTime = clock();
}
+118
View File
@@ -0,0 +1,118 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://www.osrose.net
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#ifndef _ROSE_CHARACTER_
#define _ROSE_CHARACTER_
#include "chartype.h"
//#include "party.h"
class CCharacter
{
public:
CCharacter( );
~CCharacter( );
unsigned int clientid;
BYTE CharType; // 0 = undefined | 1 = player | 2 = monster | 3 = summon | 4 = NPC
CCharacter* nearChar;
CCharacter* findChar;
int damagecounter;
STATS *Stats;
POSITION *Position;
BATTLE* Battle;
STATUS* Status;
MAGICSTATUS MagicStatus[30];
int AIVar[20];
// Batle Functions
void DoAttack( );
void NormalAttack( CCharacter* Enemy );
bool SkillAttack( CCharacter* Enemy, CSkills* skill );
bool BuffSkill( CCharacter* Target, CSkills* skill );
bool AoeSkill( CSkills* skill, CCharacter* Enemy=NULL );
bool AoeBuff( CSkills* skill );
void UseBuffSkill( CCharacter* Target, CSkills* skill, bool deBuff = false );
void UseBuffSkillQSD( CCharacter* Target, CSkills* skill, bool deBuff = false );
//void UseAtkSkill( CCharacter* Enemy, CSkills* skill );
void UseAtkSkill( CCharacter* Enemy, CSkills* skill, bool deBuff= false );
int GetHitRate(CCharacter* pDEF);
int GetCritRate();
int GetAtkDmg(CCharacter* pDEF, word wHitCNT, int iSuc);
int GetMgcDmg(CCharacter* pDEF, word wHitCNT, int iSuc);
bool UseSkill( CSkills* skill, CCharacter *Target = NULL );
//functions
bool IsMonster( );
bool IsPlayer( );
bool IsDead( );
bool IsSummon( );
bool IsOnBattle( );
bool IsNPC( );
void StartAction( CCharacter* Target, BYTE action, UINT skillid=0 );
//void StartAction2( CCharacter* Target, BYTE action, UINT skillid=0, bool restart=false, CCharacter* receiver=NULL);
bool IsTargetReached( CCharacter* , CSkills* skill=NULL );
bool CanAttack( );
bool IsMoving( );
CCharacter* GetCharTarget( );
bool IsAttacking( );
// virtual functions
// Events
virtual bool OnBeAttacked( CCharacter* );
virtual bool OnDie( );
virtual bool OnEnemyDie( CCharacter* );
virtual bool OnEnemyOnSight( CCharacter* );
virtual bool OnSpawn( bool );
virtual bool OnAlmostDie( );
virtual bool OnFar( );
// Functions
virtual CDrop* GetDrop( );
virtual void AddDamage( CCharacter* enemy, long int hitpower);
virtual void UpdatePosition( );
virtual bool UpdateValues( );
virtual void ReduceABC( );
virtual int GetEVBuff( );
void RefreshBuff( );
virtual CParty* GetParty( );
virtual CLAN* GetClan( );
// stats
virtual unsigned int GetAttackPower( );
virtual unsigned int GetDefense( );
virtual unsigned int GetXPRate( );
virtual unsigned int GetItemDropRate( );
virtual unsigned int GetItemDropCountRate( );
virtual unsigned int GetDodge( );
virtual unsigned int GetAccury( );
virtual unsigned int GetMagicDefense( );
virtual unsigned int GetMagicAttack( );
virtual unsigned int GetCritical( );
virtual unsigned int GetAttackSpeed( );
virtual unsigned int GetMoveSpeed( );
virtual unsigned int GetMaxHP( );
virtual unsigned int GetMaxMP( );
virtual float GetAttackDistance( );
virtual unsigned int GetInt( );
};
#endif
+63
View File
@@ -0,0 +1,63 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://www.osrose.net
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "character.h"
//virtual [called when a enemy hit this character]
bool CCharacter::OnBeAttacked( CCharacter* Enemy )
{
return true;
}
// virtual [called when this character die]
bool CCharacter::OnDie( )
{
return true;
}
// virtual [called when enemy die]
bool CCharacter::OnEnemyDie( CCharacter* Enemy )
{
return true;
}
// virtual [called when a enmy is on sigh]
bool CCharacter::OnEnemyOnSight( CCharacter* Enemy )
{
return true;
}
// virtual [called when this character spawn]
bool CCharacter::OnSpawn( bool )
{
return true;
}
// virtual [called when this character is almost dead]
bool CCharacter::OnAlmostDie( )
{
return true;
}
// virtual [called when character is far]
bool CCharacter::OnFar( )
{
return true;
}
+606
View File
@@ -0,0 +1,606 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://www.osrose.net
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
developed with Main erose/hrose source server + some change from the original eich source
*/
#include "character.h"
#include "worldserver.h"
// return true if this character is monster
bool CCharacter::IsMonster( )
{
if(CharType == 2 || CharType == 3)
return true;
return false;
}
// return true if this character is player
bool CCharacter::IsPlayer( )
{
if(CharType == 1)
return true;
return false;
}
//return true if this character is an NPC
bool CCharacter::IsNPC( )
{
if(CharType == 4)
return true;
return false;
}
// return true if HP is lower to 1
bool CCharacter::IsDead( )
{
if(Stats->HP <= 0)
return true;
return false;
}
// return true if this character is summon
bool CCharacter::IsSummon( )
{
if(this == NULL) return false;
if(CharType == 3)// this line is erroring. No idea why
return true;
return false;
}
// Virtual function [return item drop]
CDrop* CCharacter::GetDrop( )
{
return NULL;
}
// start action [attack]
void CCharacter::StartAction( CCharacter* Target, BYTE action, UINT skillid)
{
BEGINPACKET( pak, 0 );
switch(action)
{
case NORMAL_ATTACK:
{
//Log( MSG_INFO, "case NORMAL_ATTACK");
if(Target == NULL)return;
RESETPACKET( pak, 0x798 );
ADDWORD ( pak, clientid );
ADDWORD ( pak, Target->clientid );
ADDWORD ( pak, Stats->Move_Speed );
ADDFLOAT ( pak, Target->Position->current.x * 100 );
ADDFLOAT ( pak, Target->Position->current.y * 100 );
Battle->target = Target->clientid;
Battle->atktarget = Target->clientid;
Battle->atktype = action;
Battle->skilltarget = 0;
Battle->bufftarget = 0;
Battle->skillid = 0;
Position->destiny = Target->Position->current; //move to intercept target
Position->lastMoveTime = clock();
//Log(MSG_DEBUG,"Normal Attack set destiny X: %f Y: %f.",Position->current.x,Position->current.y);
}
break;
case SKILL_ATTACK: //Log( MSG_INFO, "case SKILL_ATTACK");
case SKILL_BUFF:
{
if(Target == NULL)return;
RESETPACKET( pak, 0x7b3 );
ADDWORD ( pak, clientid );
ADDWORD ( pak, Target->clientid );
ADDWORD ( pak, skillid );
ADDWORD ( pak, 0x0000 );
ADDFLOAT ( pak, Target->Position->current.x * 100 );
ADDFLOAT ( pak, Target->Position->current.y * 100 );
Battle->target = Target->clientid;
if(action == SKILL_ATTACK)
{
//Log( MSG_INFO, "case SKILL_ATTACK");
Battle->skilltarget = Target->clientid;
Battle->bufftarget = 0;
}
else
{
//Log( MSG_INFO, "case SKILL_BUFF");
Battle->bufftarget = Target->clientid;
Battle->skilltarget = 0;
}
Battle->atktype = action;
Position->destiny = Target->Position->current; //move toward target
Battle->skillid = skillid;
Position->lastMoveTime = clock();
//Log(MSG_DEBUG,"Skill Attack set destiny X: %f Y: %f.",Position->current.x,Position->current.y);
}
break;
case SKILL_AOE://Log( MSG_INFO, "case SKILL_AOE");
case BUFF_SELF://Log( MSG_INFO, "case BUFF_SELF");
case BUFF_AOE:
{
//Log( MSG_INFO, "Battle set for skill %i Action = %i", skillid, action);
//Log( MSG_INFO, "case BUFF_AOE");
RESETPACKET( pak, 0x7b2);
ADDWORD ( pak, clientid );
ADDWORD ( pak, skillid );
Battle->atktype = action;
Battle->skillid = skillid;
Position->skilltargetpos.x = Position->current.x;
Position->skilltargetpos.y = Position->current.y;
//Log( MSG_INFO, "BUFF_AOE packet sent");
}
break;
case AOE_TARGET:
{
//Log( MSG_INFO, "case AOE_TARGET");
//Target is NULL for this function when cast by a player
//Target is NOT NULL when it comes from a monster
if(Target != NULL) //monster attack
{
Position->skilltargetpos.x = Target->Position->current.x;
Position->skilltargetpos.y = Target->Position->current.y;
}
RESETPACKET( pak, 0x7b4 );
ADDWORD ( pak, clientid );
ADDWORD ( pak, skillid );
ADDFLOAT ( pak, Position->skilltargetpos.x * 100 );
ADDFLOAT ( pak, Position->skilltargetpos.y * 100 );
Battle->atktype = action;
Battle->skillid = skillid;
Battle->skilltarget = 0;
Battle->bufftarget = 0;
}
break;
default:
return;
break;
}
GServer->SendToVisible( &pak, this );
Battle->contatk = true;
//Log(MSG_INFO,"Battle Attacktype = %i",Battle->atktype);
return;
}
bool CCharacter:: IsOnBattle( )
{
if(Battle->atktype == 0)
{
if(Battle->iscasting == 1)
{
clock_t etime = clock() - Battle->lastAtkTime;
if( etime < CLOCKS_PER_SEC * 100 / Stats->Attack_Speed )
{
//Log(MSG_DEBUG,"Iscasting is true while NOT in battle. Reset to false.");
Battle->iscasting = 0;
}
else
{
return false;
}
}
}
switch(Battle->atktype)
{
case 1: //NORMAL_ATTACK:
{
if(Battle->atktarget != 0) return true;
}
break;
case 2: //SKILL_ATTACK:
case 8: //AOE_TARGET:
{
if(Battle->skilltarget != 0 && Battle->skillid != 0) return true;
}
break;
case 3: //SKILL_BUFF:
{
if(Battle->bufftarget != 0 && Battle->skillid != 0) return true;
}
break;
case 4: //SKILL_AOE:
//case SKILL_SELF: //no such skill type
case 6: //BUFF_SELF:
case 7: //BUFF_AOE:
{
if(Battle->skillid != 0) return true;
}
break;
default: return false;
}
}
bool CCharacter::CanAttack( )
{
clock_t etime = clock() - Battle->lastAtkTime;
if(CharType == 4) //it's an npc
{
//Log(MSG_DEBUG, "It's an NPC so set speed to 1");
//always return true for an NPC
Stats->Attack_Speed = 1;
}
if (Stats->Attack_Speed < 1)
{
Log( MSG_INFO, "weapon with no attackspeed.");
return false;
}
if(Battle->iscasting == 1)
{
if( etime < CLOCKS_PER_SEC * GServer->Config.SkillMult / Stats->Attack_Speed ) //should make the delay 4 times longer
{
//Log(MSG_INFO,"Cannot attack yet. Last attack time = %i",Battle->lastAtkTime);
return false;
}
else
{
Log(MSG_INFO,"iscasting reset to 0 after time delay");
Battle->iscasting = 0;
Battle->NextAtkTime = Battle->lastAtkTime + (CLOCKS_PER_SEC * GServer->Config.SkillMult / Stats->Attack_Speed);
return true;
}
}
else //normal attack
{
if( etime < CLOCKS_PER_SEC * GServer->Config.AttkMult / Stats->Attack_Speed )
{
//Log(MSG_INFO,"Cannot attack yet. Last attack time = %i",Battle->lastAtkTime);
return false;
}
}
Battle->NextAtkTime = Battle->lastAtkTime + (CLOCKS_PER_SEC * GServer->Config.SkillMult / Stats->Attack_Speed);
return true;
}
// return true if target is reached
bool CCharacter::IsTargetReached( CCharacter* Enemy, CSkills* skill )
{
CMap* map = GServer->MapList.Index[Position->Map];
if(map == NULL)
return true;
float distance = GServer->distance( Position->current, Enemy->Position->current );
if(skill == NULL) //it's a normal attack
{
if(distance <= Stats->Attack_Distance)
{
Position->destiny = Position->current;
//Log(MSG_DEBUG,"(istargetreached) Destiny set to current position X: %f Y: %f.",Position->current.x,Position->current.y);
return true;
}
else
{
Position->destiny = Enemy->Position->current;
//Log(MSG_DEBUG,"(istargetreached) Destiny set to Enemy position X: %f Y: %f.",Position->current.x,Position->current.y);
}
}
else // skill attack
{
float SkillRange = (float)skill->range;
if(SkillRange == 0)
{
SkillRange = Stats->Attack_Distance;
}
if(distance <= SkillRange)
{
Position->destiny = Position->current;
//Log(MSG_DEBUG,"(istargetreached skill) Destiny set to current position X: %f Y: %f.",Position->current.x,Position->current.y);
return true;
}
else
{
Position->destiny = Enemy->Position->current;
//Log(MSG_DEBUG,"(istargetreached skill) Destiny set to Enemy position X: %f Y: %f.",Position->current.x,Position->current.y);
//Log(MSG_DEBUG,"(istargetreached skill) Distance: %f range: %i.", distance, SkillRange);
}
}
//Log(MSG_INFO,"(istargetreached) Cannot attack. Too far away");
return false;
}
// return true if the character is moving
bool CCharacter::IsMoving( )
{
if(Position->current.x == Position->destiny.x && Position->current.y == Position->destiny.y )
return false;
return true;
}
// VIRTUAL [add player damage]
void CCharacter::AddDamage( CCharacter* enemy, long int hitpower)
{
}
// return character target
CCharacter* CCharacter::GetCharTarget( )
{
CCharacter* thistarget = GServer->MapList.Index[Position->Map]->GetCharInMap( Battle->target );
if (thistarget != NULL)
{
//Log(MSG_DEBUG, "getchartarget found target OK");
return thistarget;
}
//Log(MSG_DEBUG, "getchartarget failed to find target");
//if I don't currently have a target then return the character who just hit me
return GServer->MapList.Index[Position->Map]->GetCharInMap( Battle->hitby );
}
// VIRTUAL [reduce ammon/bullets/cannons]
void CCharacter::ReduceABC( )
{
}
// VIRTUAL [get extra buff value]
int CCharacter::GetEVBuff( )
{
return 0;
}
// VIRTUAL [return intelligence]
unsigned int CCharacter::GetInt( )
{
return 15;
}
// Check For Debuffs
void CCharacter::RefreshBuff( )
{
bool bflag = false;
for( UINT i=0;i<30;i++)
{
if(MagicStatus[i].Buff == 0) continue;
clock_t etime = clock() - MagicStatus[i].BuffTime;
if( etime >= MagicStatus[i].Duration * CLOCKS_PER_SEC )
{
switch(MagicStatus[i].Status)
{
case 18: // attack power up
case 19: // attack power down
case 48: // attack power up
if(i<15)
Status->Attack_up = 0xff;
else
Status->Attack_down = 0xff;
Stats->Attack_Power = GetAttackPower( );
break;
case 20: // def up
case 21: // def down
case 49: // def up
if(i<15)
Status->Defense_up= 0xff;
else
Status->Defense_down = 0xff;
Stats->Defense = GetDefense( );
break;
case 24: //accuracy up
case 25: //accuracy down
case 51: //attack accuracy up.
if(i<15)
Status->Accury_up= 0xff;
else
Status->Accury_down = 0xff;
Stats->Accury = GetAccury( );
break;
case 22: // macic resistance up
case 23: // magic resistance down
case 50: // magic resistance up
if(i<15)
Status->Magic_Defense_up = 0xff;
else
Status->Magic_Defense_down = 0xff;
Stats->Magic_Defense = GetMagicDefense( );
break;
case 28: //dodge up
case 29: //dodge down
case 53: //dodge rate up
if(i<15)
Status->Dodge_up = 0xff;
else
Status->Dodge_down = 0xff;
Stats->Dodge = GetDodge( );
break;
case 14: //dash
case 15: //slow
case 46: //movement speed increased
if(i<15)
Status->Dash_up = 0xff;
else
Status->Dash_down = 0xff;
Stats->Move_Speed = GetMoveSpeed( );
break;
case 16: // haste attack
case 17: // slow attack
case 47: // attack speed up
if(i<15)
Status->Haste_up = 0xff;
else
Status->Haste_down = 0xff;
Stats->Attack_Speed = GetAttackSpeed( );
break;
case 26: // crit up
case 27: // crit down
case 52: // crit up
if(i<15)
Status->Critical_up = 0xff;
else
Status->Critical_down = 0xff;
Stats->Critical = GetCritical( );
break;
case 12: // max HP up
case 44: // max HP up
if(i<15)
Status->HP_up = 0xff;
else
Status->HP_down = 0xff;
Stats->MaxHP = GetMaxHP( );
break;
case 13: // max MP up
case 45: // max MP up
if(i<15)
Status->MP_up = 0xff;
else
Status->MP_down = 0xff;
Stats->MaxMP = GetMaxMP( );
break;
case 32: // faint
Status->Stuned = 0xff;
Status->CanAttack = true;
//printf("removing stun\n");
break;
case 7: case 8: case 9: case 10: case 11: //poisoned
Status->Poisoned = 0xff;
//printf("removing poison\n");
break;
case 30: // muted
Status->Muted = 0xff;
Status->CanCastSkill = true;
break;
case 31: // sleep May need to be fixed later to accomodate multiple status effects.
Status->Sleep = 0xff;
Status->CanMove = true;
Status->CanCastSkill = true;
Status->CanAttack = true;
break;
case 54: //A_GMExtra_Damage:
case 36: //A_Extra_Damage:
if(i<15)
{
Status->ExtraDamage_up = 0xff;
Stats->ExtraDamage = 0xff;
}
else
{
Status->ExtraDamage_down = 0xff;
Stats->ExtraDamage = 0xff;
}
break;
case 56: // Taunt
Status->Taunt = 0xff;
break;
default:
break;
}
MagicStatus[i].Status = 0;
MagicStatus[i].Buff = 0;
MagicStatus[i].BuffTime = 0;
MagicStatus[i].Duration = 0;
MagicStatus[i].Value = 0;
bflag = true;
}
else if (MagicStatus[i].Status >= 7 && MagicStatus[i].Status <= 11 && etime > 1*CLOCKS_PER_SEC) //Do poison dmg every 1.5 seconds
{
Stats->HP -= MagicStatus[i].Status; //Actually take 7, 8, 9, 10 or 11 from the health. Based on the Status itself
MagicStatus[i].BuffTime += 1*CLOCKS_PER_SEC;
MagicStatus[i].Duration -= 1;
//printf("did %i poison dmg to the player, still %i seconds and %i HP remain \n", MagicStatus[i].Status, MagicStatus[i].Duration, Stats->HP);
//A bunch of messy code to send dmg packet
BEGINPACKET( pak, 0x7b6 );
ADDWORD ( pak, clientid ); // client taking damage
ADDWORD ( pak, 0 ); // client doing damage
ADDDWORD ( pak, 0x000007f8 );
ADDBYTE ( pak, 0x00 );
if (Stats->HP < 1)
{
ADDWORD ( pak, MagicStatus[i].Status + 0x8000 );
}
else
{
ADDWORD ( pak, MagicStatus[i].Status + 0x2000 );
}
//ADDDWORD ( pak, MagicStatus[i].Status ); //damage amount
//If poisoned entity (player or monster) is killed
if( IsDead())
{
//printf("char died\n");
Log( MSG_INFO, "found dead monster");
CDrop* thisdrop = NULL;
CMap* map = GServer->MapList.Index[thisdrop->posMap];
ADDDWORD ( pak, 16 );
if( !IsSummon( ) && !IsPlayer( ))
{
thisdrop = GetDrop( );
if( thisdrop != NULL)
{
map->AddDrop( thisdrop );
}
}
GServer->SendToVisible( &pak, this ); // removed thisdrop from the packet
//kill the monster if its HP is less than 0
BEGINPACKET( pak1, 0x799 );
ADDWORD ( pak1, clientid );
ADDWORD ( pak1, clientid );
ADDDWORD ( pak1, 0x8005 );
GServer->SendToVisible( &pak1, this );
}
//If enemy is still alive
else
{
ADDDWORD ( pak, 4 );
GServer->SendToVisible( &pak, this );
}
}
}
if(bflag)
{
BEGINPACKET( pak,0x7b7 );
ADDWORD ( pak, clientid );
ADDDWORD ( pak, GServer->BuildBuffs( this ) );
GServer->SendToVisible( &pak, this );
}
}
// VIRTUAL [return party pointer]
CParty* CCharacter::GetParty( )
{
return NULL;
}
// VIRTUAL [return clan pointer]
CLAN* CCharacter::GetClan( )
{
return NULL;
}
bool CCharacter::IsAttacking( )
{
if(IsOnBattle( ))
{
switch(Battle->atktype)
{
case SKILL_BUFF:
case BUFF_SELF:
case BUFF_AOE:
return false;
default:
return false;
break;
}
}
else return false;
}
+111
View File
@@ -0,0 +1,111 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://www.osrose.net
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#include "character.h"
// virtual [return attackpower]
unsigned int CCharacter::GetAttackPower( )
{
return 0;
}
// virtual [return defense]
unsigned int CCharacter::GetDefense( )
{
return 0;
}
// virtual [return dodge]
unsigned int CCharacter::GetDodge( )
{
return 0;
}
// virtual [return xprate]
unsigned int CCharacter::GetXPRate( )
{
return 0;
}
// virtual [return item drop rate]
unsigned int CCharacter::GetItemDropRate( )
{
return 0;
}
// virtual [return item drop rate]
unsigned int CCharacter::GetItemDropCountRate( )
{
return 0;
}
// virtual [return accury]
unsigned int CCharacter::GetAccury( )
{
return 0;
}
// virtual [return magic defense]
unsigned int CCharacter::GetMagicDefense( )
{
return 0;
}
// virtual [return magic attack]
unsigned int CCharacter::GetMagicAttack( )
{
return 0;
}
// virtual [return critical]
unsigned int CCharacter::GetCritical( )
{
return 0;
}
// virtual [return attackspeed]
unsigned int CCharacter::GetAttackSpeed( )
{
return 0;
}
// virtual [return movespeed]
unsigned int CCharacter::GetMoveSpeed( )
{
return 0;
}
// virtual [return maxhp]
unsigned int CCharacter::GetMaxHP( )
{
return 0;
}
// virtual [return maxmp]
unsigned int CCharacter::GetMaxMP( )
{
return 0;
}
// virtual [return attackdistance]
float CCharacter::GetAttackDistance( )
{
return 0;
}
+303
View File
@@ -0,0 +1,303 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://www.osrose.net
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
depeloped with Main erose/hrose source server + some change from the original eich source
*/
#ifndef _CHARACTER_TYPE_
#define _CHARACTER_TYPE_
#define MAX_STORAGE 160
#define MAX_INVENTORY 140
#define MAX_BASICSKILL 42
#define MAX_QUICKBAR 32
#define ClearBattle(i) { i->target=0;i->atktarget=0; i->bufftarget=0; i->skilltarget=0; i->skillid=0; i->atktype=0; i->hitby=0; i->iscasting=0; }
typedef unsigned char BYTE;
#include "datatypes.h"
#define TPLAYER 1
#define TMONSTER 2
#define TSUMMON 3
#define TNPC 4
//**************** SHARED ****************//
struct POSITION
{
fPoint source; // source position
fPoint current; // current position
fPoint destiny; // destiny position
fPoint skilltargetpos;
unsigned int Map; // current map
unsigned int respawn; // respawn id [player = respawnid | monster = spawnid]
unsigned int saved; // saved id [player town | monster = 0]
clock_t lastMoveTime;
};
struct STATS
{
int Level;
long int HP;
long int MP;
unsigned int MaxHP;
unsigned int MaxMP;
unsigned int stance;
unsigned int Attack_Power;
unsigned int Defense;
unsigned int Critical;
unsigned int Dodge;
unsigned int Accury;
unsigned int Magic_Defense;
unsigned int Move_Speed;
unsigned int Mspd_base;
unsigned int Attack_Speed;
float Attack_Distance;
unsigned int MaxWeight;
unsigned int MaxSummonGauge;
unsigned int MPReduction;
unsigned int ExtraDamage;
unsigned int xprate;
unsigned int itemdroprate;
unsigned int itemdropcountrate;
unsigned int zulydroprate;
unsigned int greydrop;
unsigned int magicattack;
int ItemXPRate;
int ItemDropRate;
clock_t ItemXPTimer;
unsigned int ItemXPTime;
clock_t ItemDropRateTimer;
};
struct BATTLE
{
unsigned int target;
unsigned int atktarget;
unsigned int bufftarget;
unsigned int skilltarget;
unsigned int skillid;
unsigned int atktype;
unsigned int hitby;
unsigned int iscasting;
bool contatk;
clock_t lastAtkTime;
clock_t castTime;
clock_t NextAtkTime;
};
struct STATUS
{
//Stats up
BYTE Dash_up;
BYTE Haste_up;
BYTE Attack_up;
BYTE Defense_up;
BYTE Magic_Defense_up;
BYTE Accury_up;
BYTE Critical_up;
BYTE Dodge_up;
BYTE HP_up;
BYTE MP_up;
BYTE MaxHP_up;
BYTE MaxMP_up;
BYTE HPMP_up;
//Stats down
BYTE Dash_down;
BYTE Haste_down;
BYTE Attack_down;
BYTE Defense_down;
BYTE Magic_Defense_down;
BYTE Accury_down;
BYTE Critical_down;
BYTE Dodge_down;
BYTE HP_down;
BYTE MP_down;
BYTE MaxHP_down;
BYTE MaxMP_down;
BYTE HPMP_down;
//Status Effects
BYTE Poisoned;
BYTE Muted;
BYTE Sleep;
BYTE Faint;
BYTE Stuned;
BYTE Camo;
BYTE Invis;
BYTE Shield;
BYTE Curse;
BYTE Recover;
BYTE Dispell;
BYTE Detect;
BYTE Invinc;
BYTE Flame;
BYTE ExtraDamage_up;
BYTE ExtraDamage_down;
BYTE Taunt;
bool CanAttack;
bool CanRun;
bool CanMove;
bool CanCastSkill;
bool IsTowerDef;
bool nightonly;
bool dayonly;
UINT spawnid;
// Stance
BYTE Stance;
};
struct MAGICSTATUS
{
unsigned int Status; // Store the skill Status
unsigned int Buff; // Store the buff type
unsigned int Value; // Buff Value
unsigned int Duration; // Skill Duration
clock_t BuffTime; // Buff Time
};
//**************************************************************/
//***************Player only******************************************/
struct ATTRIBUTES
{
unsigned int Str;
unsigned int Dex;
unsigned int Int;
unsigned int Con;
unsigned int Cha;
unsigned int Sen;
unsigned int Estr;
unsigned int Edex;
unsigned int Eint;
unsigned int Econ;
unsigned int Echa;
unsigned int Esen;
};
struct USEDITEM
{
clock_t lastRegTime; // Last Regeneration
UINT usevalue; // Max Heal Value
UINT usetype; // Consumible Type (MP/HP/STAMINA/...)
UINT userate; // consumible rate
UINT used; // Consumible Used
};
// Player information
struct INFO
{
char charname[17];
unsigned int charid;
BYTE Sex;
UINT Face;
UINT Hair;
UINT Exp;
UINT Pending_Exp; //temporary storage space for exp during calculations
UINT Job;
long int Zulies;
long int Storage_Zulies;
long int LastGlobal;
int StatPoints;
int SkillPoints;
unsigned int stamina;
UINT IsGM;
UINT IsDev;
//int xprate
};
struct SESSION
{
unsigned int userid;
char username[17];
char password[33];
int accesslevel;
bool isLoggedIn;
bool inGame;
UINT Respawned;
BYTE RespawnChoice;
bool codedebug;
UINT KTPoints;
UINT NewPoints;
UINT logtime; // tracks total log points. 1 point = 1 hour. 5 points = 1KTPoint
clock_t LogTime; // time for the current session
UINT TotalLogTime;
UINT award;
};
struct RIDE
{
bool Drive;
bool Ride;
UINT charid;
};
struct TRADE
{
unsigned int short trade_itemid[0xa];
unsigned int trade_count[0xb];
unsigned int trade_status;
unsigned int trade_target;
};
struct PARTY
{
class CParty* party;
bool IsMaster;
};
struct SHOP
{
bool open;
char name[64];
CBuying BuyingList[30];
CSelling SellingList[30];
UINT Buying;
UINT Selling;
UINT ShopType;
};
struct SKILLS
{
unsigned id;
unsigned level;
CSkills* thisskill;
};
struct CLAN
{
unsigned int clanid;
unsigned int clanrank;
unsigned int grade;
unsigned int CP;
unsigned int logo;
unsigned int back;
char clanname[17];
};
struct UNION_s
{
UINT unionvar[11];
};
//***************Monster only******************************************/
#endif
+257
View File
@@ -0,0 +1,257 @@
/*
Rose Online Server Emulator
Copyright (C) 2006,2007 OSRose Team http://www.osrose.net
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 2
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
developed with Main erose/hrose source server + some change from the original eich source
*/
#include "worldserver.h"
// Clan Manager
bool CWorldServer::pakClanManager ( CPlayer* thisclient, CPacket* P )
{
int action = GETBYTE((*P),0);
//Log(MSG_DEBUG, "Clan action %i", action );
switch(action)
{
case 0xfa://new member added
{
MYSQL_ROW row;
int charid = GETWORD((*P),1);
int clanid = GETWORD((*P),3);
Log(MSG_INFO, "Adding member %d to clan %d", charid, clanid);
CPlayer* otherclient = GetClientByCID ( charid );
if(otherclient==NULL) {
Log(MSG_ERROR, "Char with id %d doesn't exist", charid);
return true;
}
MYSQL_RES *result = DB->QStore("SELECT logo,back,name,grade FROM list_clan where id = %i", clanid);
if(result==NULL)
{
Log(MSG_INFO, "NULL result from query to list_clan");
return true;
}
if(mysql_num_rows(result)!=1)
{
Log(MSG_WARNING, "Invalid clan %i", clanid );
DB->QFree( );
return true;
}
row = mysql_fetch_row(result);
otherclient->Clan->logo = atoi(row[0]);
otherclient->Clan->back = atoi(row[1]);
strcpy(otherclient->Clan->clanname,row[2]);
otherclient->Clan->grade = atoi(row[3]);
DB->QFree( );
otherclient->Clan->clanid=clanid;
otherclient->Clan->clanrank=1;
BEGINPACKET( pak, 0x7e0 );
ADDBYTE ( pak, 0x35 );//funcion
ADDWORD ( pak, otherclient->clientid );//client id
ADDWORD ( pak, clanid );//?
ADDWORD ( pak, 0x0000 );
ADDWORD ( pak, otherclient->Clan->back );
ADDWORD ( pak, otherclient->Clan->logo );
ADDBYTE ( pak, otherclient->Clan->grade );
ADDBYTE ( pak, otherclient->Clan->clanrank );
ADDSTRING ( pak, otherclient->Clan->clanname );
ADDBYTE ( pak, 0x00 );
SendToVisible( &pak, otherclient );
}
break;
case 0xfb://Member Kicked
{
char nick[30];
memcpy( nick, &P->Buffer[1], P->Size );
CPlayer* otherclient = GetClientByCharName( nick );
if(otherclient!=NULL)
{
otherclient->Clan->clanid=0;
otherclient->Clan->clanrank=1;
otherclient->Clan->back=0;
otherclient->Clan->logo=0;
otherclient->Clan->grade=0;
strcpy(otherclient->Clan->clanname,"");
BEGINPACKET( pak, 0x7e0 );
ADDBYTE ( pak, 0x35 );
ADDWORD ( pak, otherclient->clientid );
ADDQWORD ( pak, 0 );
ADDWORD ( pak, 0x0001 );
SendToVisible( &pak, otherclient );
}
}
break;
case 0xfc://member change rank
{
char nick[30];
int newrank = GETBYTE((*P),1);
memcpy( nick, &P->Buffer[2], P->Size );
CPlayer* otherclient = GetClientByCharName( nick );
if(otherclient!=NULL)
{
otherclient->Clan->clanrank = newrank;
}
}
break;
case 0xfd://disorg
{
unsigned int clanid = GETWORD((*P),1);
unsigned int charid = GETWORD((*P),3);
CPlayer* tclient = GetClientByCID( charid );
if(tclient == NULL)
return true;
tclient->Clan->clanid = 0;
tclient->Clan->clanrank = 1;
tclient->Clan->grade = 0;
tclient->Clan->back = 0;
tclient->Clan->logo = 0;
memset( &tclient->Clan->clanname, '\0', 17 );
BEGINPACKET( pak, 0x7e0 );
ADDBYTE ( pak, 0x35 );
ADDWORD ( pak, tclient->clientid );
ADDQWORD ( pak, 0 );
ADDWORD ( pak, 0x0001 );
SendToVisible( &pak, tclient );
}
break;
case 0xfe://Member Leave
{
char nick[17];
memcpy( nick, &P->Buffer[1], P->Size );
CPlayer* otherclient = GetClientByCharName(nick);
if(otherclient!=NULL)
{
otherclient->Clan->clanid=0;
otherclient->Clan->clanrank=0;
otherclient->Clan->back=0;
otherclient->Clan->logo=0;
otherclient->Clan->grade=0;
strcpy(otherclient->Clan->clanname,"");
BEGINPACKET( pak, 0x7e0 );
ADDBYTE ( pak, 0x35 );
ADDWORD ( pak, otherclient->clientid );
ADDQWORD ( pak, 0 );
ADDWORD ( pak, 0x0001 );
SendToVisible( &pak, otherclient );
}
}
break;
case 0xff: // update clan mark
{
unsigned int clanid = GETWORD((*P),1);
unsigned int clanlogo = GETDWORD((*P), 3 );
for(unsigned int i=0;i<ClientList.size();i++)
{
if(ClientList.at(i)->player==NULL) continue;
CPlayer* player = (CPlayer*)ClientList.at(i)->player;
if(player->Clan->clanid==clanid)
{
player->Clan->back = 0;
player->Clan->logo = clanlogo;
BEGINPACKET( pak, 0x7e0 );
ADDBYTE ( pak, 0x35 );//funcion
ADDWORD ( pak, player->clientid );//cleint id
ADDWORD ( pak, clanid );
ADDWORD ( pak, 0x0000 );//?
ADDWORD ( pak, player->Clan->back );//?
ADDWORD ( pak, player->Clan->logo );//?
ADDBYTE ( pak, player->Clan->grade );
ADDBYTE ( pak, player->Clan->clanrank );
ADDSTRING ( pak, player->Clan->clanname );
ADDBYTE ( pak, 0x00 );
SendToVisible( &pak, player );
}
}
}
break;
default:
Log( MSG_INFO, "Clan manager unknow action %i", action );
}
return true;
}
// Create a new clan
bool CWorldServer::pakCreateClan ( CPlayer* thisclient, CPacket* P )
{
if(thisclient->CharInfo->Zulies<1000000)
return true;
thisclient->CharInfo->Zulies -= 1000000;
MYSQL_ROW row;
int background = GETWORD((*P),1);
int icon = GETWORD((*P),3);
const char *name = "";
const char *slogan = "";
name=(char*)&P->Buffer[5];
slogan=(char*)&P->Buffer[strlen(name)+6];
//Check if name already exists
MYSQL_RES *result = DB->QStore("SELECT name FROM list_clan WHERE name='%s'", name);
if(result==NULL) return true;
if ( mysql_num_rows( result ) > 0 )
{
BEGINPACKET( pak, 0x07e0 );
ADDWORD ( pak, 0x42 );
thisclient->client->SendPacket( &pak );
DB->QFree( );
return true;
}
DB->QFree( );
//Check if user can create a clan
if( thisclient->Clan->clanid != 0 )
{
BEGINPACKET( pak, 0x07e0 );
ADDWORD ( pak, 0x44 );
thisclient->client->SendPacket( &pak );
return true;
}
//Add clan to sql table
DB->QExecute( "INSERT into list_clan (logo,back,name,cp,grade,slogan,news) values (%i,%i,'%s',0,1,'%s','')",
icon,background,name,slogan);
thisclient->Clan->clanid = mysql_insert_id(DB->Mysql);
thisclient->Clan->clanrank = 6;
thisclient->Clan->logo = icon;
thisclient->Clan->back = background;
strncpy(thisclient->Clan->clanname,name,16);
thisclient->Clan->grade = 1;
//Update user clan information
DB->QExecute( "UPDATE characters set clanid=%i,clan_rank=6 where id=%i",
thisclient->Clan->clanid,thisclient->CharInfo->charid);
//load clan info in char server
BEGINPACKET( pak, 0x7e0 );
ADDBYTE ( pak, 0xfa ); //action to update clan informacion (charserver)
ADDWORD ( pak, thisclient->Clan->clanid );
ADDWORD ( pak, thisclient->CharInfo->charid );
ADDWORD ( pak, thisclient->clientid );
SendISCPacket( &pak );
//Send to other players
RESETPACKET( pak, 0x7e0 );
ADDBYTE ( pak, 0x35 );
ADDWORD ( pak, thisclient->clientid );
ADDWORD ( pak, thisclient->Clan->clanid);
ADDWORD ( pak, 0x0000 );//???
ADDWORD ( pak, background );
ADDWORD ( pak, icon );
ADDBYTE ( pak, 0x01 );//clan grade
ADDBYTE ( pak, 0x06 );//clan rank
ADDSTRING ( pak, name );
ADDBYTE ( pak, 0x00 );
SendToVisible( &pak, thisclient );
return true;
}
File diff suppressed because it is too large. Load diff
Loaded 100 of 145 files, more files were not shown because too many files have changed in this diff. Show more