Пример #1
0
        private void InternalCompile()
        {
            if (mLength == 0)
            {
                mLength = (int)mStream.Length;
            }

            if (mStream.Length != mLength)
            {
                int diff = (int)mStream.Length - mLength;
                ServerConsole.ErrorLine("Packet {0:X4}: Bad packet length! ({1}{2} bytes)", mPacketID, diff >= 0 ? "+" : "", diff);
            }

            //mStream.Seek(2, SeekOrigin.Begin);
            //mStream.Write(mLength);

            MemoryStream ms = mStream.BaseStream;

            //mCompiledBuffer = ms.GetBuffer();
            mCompiledLength = (int)ms.Length;
            mCompiledBuffer = new byte[mCompiledLength];
            Buffer.BlockCopy(ms.GetBuffer(), 0, mCompiledBuffer, 0, mCompiledLength);

            PacketWriter.ReleaseInstance(mStream);
            mStream = null;
        }
        public void LoadOther()
        {
            DataTable table;
            int       i = 0;

            // Hotkeys
            Hotkeys = new CharacterHotkey[Global.MAX_HOTKEYS];
            table   = Core.Database.Query("SELECT * FROM `char_hotkey` WHERE `charID` = {0}", ID);
            if (table != null && table.Rows.Count > 0)
            {
                foreach (DataRow row in table.Rows)
                {
                    CharacterHotkey key = CharacterHotkey.Load(row);
                    if (key == null)
                    {
                        ServerConsole.ErrorLine("Failed to load hotkey #{0}", row.Field <int>("index"));
                        continue;
                    }

                    Hotkeys[i++] = key;
                }
            }

            // Fill up until max
            for (; i < Hotkeys.Length; i++)
            {
                Hotkeys[i] = new CharacterHotkey();
            }
        }
Пример #3
0
        protected override bool LoadFromDatabase(DataRow row)
        {
            SkillID     = row.Field <int>("skillID");
            Index       = (ESkill)SkillID;
            Name        = row.Field <string>("name");
            Description = row.Field <string>("description");
            Hit         = row.Field <short>("hit");
            Inf         = (ESkillInf)row.Field <int>("inf");
            Inf2        = (ESkillInf2)row.Field <int>("inf2");
            CastCancel  = row.Field <bool>("castCancel");
            CastDefRate = row.Field <int>("castDefRate");
            Nk          = (ESkillNk)row.Field <short>("nk");
            SkillType   = (EBattleFlag)row.Field <short>("type");

            // Load level
            DataTable table = Core.Database.Query("SELECT * FROM dbskill_level WHERE skillID = {0} ORDER BY level ASC", SkillID);

            if (table != null && table.Rows.Count > 0)
            {
                SkillLevel level;
                foreach (DataRow levelRow in table.Rows)
                {
                    level = SkillLevel.Load(levelRow);
                    if (level == null)
                    {
                        ServerConsole.ErrorLine("Failed to load skill level #" + levelRow.Field <int>("skillID") + " lv " + levelRow.Field <int>("level"));
                        continue;
                    }

                    Level.Add(level);
                }
            }

            return(true);
        }
Пример #4
0
        public static void Spawn(string name, int viewID, Location loc)
        {
            // Search free cell to spawn, if not given
            if (loc.Map.SearchSpawnCell(ref loc) == false)
            {
                // No spot on the map.. maybe a bug or something else
                ServerConsole.ErrorLine("SpawnSub: Failed to locate spawn pos on map " + loc.Map.Name);
                return;
            }

            NpcScript npc = new NpcScript(new DatabaseID(viewID, EDatabaseType.Npc));

            npc.Location = loc;
            npc.Name     = name;
            npc.Class    = (short)viewID;
            npc.NpcType  = ENpcScriptType.Script;

            // TODO: ontouch area

            npc.StatusChange = new WorldObjectStatusChangeList();
            npc.StatusChange.Clear();

            npc.Spawn();

            return;
        }
Пример #5
0
        private static string[] GetReferenceAssemblies(string ConfigFile)
        {
            List <string> list = new List <string>();

            if (File.Exists(ConfigFile))
            {
                using (StreamReader ip = new StreamReader(ConfigFile)) {
                    string line;

                    while ((line = ip.ReadLine()) != null)
                    {
                        if (line.Length == 0 || line.StartsWith("//"))
                        {
                            continue;
                        }
                        list.Add(line);
                    }
                }
            }
            else
            {
                ServerConsole.ErrorLine("Script Assembie Files \"{0}\" not found!", ConfigFile);
            }

            if (Core.Assembly != null)
            {
                list.Add(Core.Assembly.Location);
            }
            list.AddRange(mAdditionalReferences);

            return(list.ToArray());
        }
Пример #6
0
        /*==========================================
         * heap update (helper function)
         *------------------------------------------*/
        private static void UpdateHeapPath(int[] heap, STmpPath[] tp, int index)
        {
            int i, h;

            for (h = 0; h < heap[0]; h++)
            {
                if (heap[h + 1] == index)
                {
                    break;
                }
            }
            if (h == heap[0])
            {
                ServerConsole.ErrorLine("update_heap_path bug\n");
                Core.Kill();
                return;
            }

            for (i = (h - 1) / 2; h > 0 && tp[index].cost < tp[heap[i + 1]].cost; i = (h - 1) / 2)
            {
                heap[h + 1] = heap[i + 1];
                h           = i;
            }

            heap[h + 1] = index;
        }
Пример #7
0
        public static string[] GetNpcs()
        {
            int           count = 0;
            List <string> list  = new List <string>();

            ScriptEntry[] entrys = ScriptDatabase.GetType(EScriptContent.Npc);

            for (int i = 0; i < entrys.Length; i++)
            {
                if (entrys[i].Type != EScriptType.Path)
                {
                    continue;
                }
                if (File.Exists(entrys[i].Path) == false)
                {
                    ServerConsole.ErrorLine("Cant find File/Path: \"" + entrys[i].Path + "\"! Skipping...");
                    continue;
                }

                list.Add(Path.Combine(Environment.CurrentDirectory, entrys[i].Path));
                ServerConsole.InfoLine("\t#{0}: \"{1}\"", (++count), entrys[i].Path);
            }

            return(list.ToArray());
        }
Пример #8
0
        public SocketConnector(string IP, int Port)
        {
            mIP   = IP;
            mPort = Port;
            IPHostEntry iphe = null;

            try {
                iphe = Dns.GetHostEntry(mIP);
                if (iphe == null || iphe.AddressList.Length < 1)
                {
                    throw new Exception("Unable to fetch IP Address from: " + mIP + "::" + mPort);
                }
            } catch (Exception e) {
                throw e;
            }

            //iphe.AddressList[0].ToString()
            IPEndPoint endPoint = null;
            Regex      reIP     = new Regex(@"^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$", RegexOptions.Compiled);

            foreach (IPAddress ip in iphe.AddressList)
            {
                string ipString = ip.ToString();
                if (ipString == "::1" || ipString.Length == 0 || reIP.IsMatch(ipString) == false)
                {
                    continue;
                }

                endPoint = new IPEndPoint(ip, mPort);
                break;
            }
            if (endPoint == null)
            {
                throw new Exception("Failed to load SocketListener");
            }

            bool bSuccess = false;

            do
            {
                SocketListener Listener = new SocketListener(endPoint, this);
                if (bSuccess == false && Listener != null)
                {
                    bSuccess = true;
                }
                mListener = Listener;

                if (bSuccess == false)
                {
                    ServerConsole.ErrorLine("Unable to Connect - retrying in 10sec...");
                    Thread.Sleep(10000);
                }
            } while (bSuccess == false);

            mQueue        = new Queue <NetState>();
            mWorkingQueue = new Queue <NetState>();
            mThrottled    = new Queue <NetState>();
            mPeek         = new byte[4];
        }
Пример #9
0
        private void OnReceive(IAsyncResult asyncResult)
        {
            Socket s = (Socket)asyncResult.AsyncState;

            try {
                int byteCount = s.EndReceive(asyncResult);
                if (byteCount > 0)
                {
                    UpdateAcitivty();

                    byte[] buffer = mRecvBuffer;
                    if (mEncoder != null)
                    {
                        mEncoder.DecodeIncomingPacket(this, ref buffer, ref byteCount);
                    }

                    lock (mBuffer) {
                        mBuffer.Enqueue(buffer, 0, byteCount);
                    }

                    //mMessagePump.OnReceive(this);
                    lock (mMessagePump) {
                        //Core.Set();
                        mMessagePump.HandleReceive(this);
                    }

                    lock (mAsyncLock) {
                        mAsyncState &= ~AsyncNetState.Pending;

                        if ((mAsyncState & AsyncNetState.Paused) == 0)
                        {
                            try {
                                InternalBeginReceive();
                            } catch (Exception ex) {
                                ExceptionHandler.Trace(ex);
                                Dispose(false);
                            }
                        }
                    }
                }
                else
                {
                    Dispose(false);
                }
            } catch (Exception ex) {
                ServerConsole.ErrorLine(ex.Message);
                ServerConsole.ErrorLine(ex.StackTrace);
                //ServerConsole.ErrorLine(Tools.CleanExcepionStacktrace(ex.StackTrace));
                Dispose(false);
            }
        }
Пример #10
0
        public DataTable Query(string query)
        {
            DataTable result = base.Query(query);

            if (LastError != null)
            {
                ServerConsole.ErrorLine(LastError.ToString());
#if !DEBUG
                Core.Kill(false);
#endif
            }

            return(result);
        }
Пример #11
0
        public override DataTable Query(string query, params object[] args)
        {
            DataTable result = base.Query(query, args);

            if (LastError != null)
            {
                ServerConsole.ErrorLine(LastError.ToString());
#if !DEBUG
                Core.Kill(false);
#endif
            }

            return(result);
        }
Пример #12
0
        /// Sends information about the guild of the target
        /// 014f 6: <state>.L
        public static void GuildRequestInfo(NetState state, PacketReader reader)
        {
            if (state.IsValid(EAccountState.World) == false)
            {
                state.Disconnect();
                return;
            }

            Character c = state.Account.ActiveChar;

            // Nothing to send?
            if (!(c.Status.GuildID is WorldID))
            {
                // TODO: or battleground ID
                return;
            }

            int requestType = reader.ReadInt32();

            switch (requestType)
            {
            case 0:
                //clif_guild_basicinfo(sd);
                //clif_guild_allianceinfo(sd);
                break;

            case 1:
                //clif_guild_positionnamelist(sd);
                //clif_guild_memberlist(sd);
                break;

            case 2:
                //clif_guild_positionnamelist(sd);
                //clif_guild_positioninfolist(sd);
                break;

            case 3:
                //clif_guild_skillinfo(sd);
                break;

            case 4:
                //clif_guild_expulsionlist(sd);
                break;

            default:
                ServerConsole.ErrorLine("GuildRequestInfo: Unknown request type {0}", requestType);
                break;
            }
        }
Пример #13
0
        /*==========================================
         * Find the closest reachable cell,
         * 'count' cells away from (x0,y0) in direction (dx,dy).
         *------------------------------------------*/
        public static int BlownPos(Map m, int x0, int y0, int dx, int dy, int count)
        {
            if (count > 25)               //Cap to prevent too much processing...?
            {
                ServerConsole.ErrorLine("path_blownpos: count too many {0}!", count);
                count = 25;
            }
            if (dx > 1 || dx < -1 || dy > 1 || dy < -1)
            {
                ServerConsole.ErrorLine("path_blownpos: illegal dx={0} or dy={1} !", dx, dy);
                dx = (dx > 0) ? 1 : ((dx < 0) ? -1 : 0);
                dy = (dy > 0) ? 1 : ((dy < 0) ? -1 : 0);
            }

            while (count > 0 && (dx != 0 || dy != 0))
            {
                if (!m.CheckCell(x0 + dx, y0 + dy, ECollisionType.Walkable))                  // attempt partial movement
                {
                    bool fx = (dx != 0 && m.CheckCell(x0 + dx, y0, ECollisionType.Walkable));
                    bool fy = (dy != 0 && m.CheckCell(x0, y0 + dy, ECollisionType.Walkable));
                    if (fx && fy)
                    {
                        if (RandomWay.Next(0, 1) == 1)
                        {
                            dx = 0;
                        }
                        else
                        {
                            dy = 0;
                        }
                    }
                    if (!fx)
                    {
                        dx = 0;
                    }
                    if (!fy)
                    {
                        dy = 0;
                    }
                }

                x0 += dx;
                y0 += dy;
                count--;
            }

            return((x0 << 16) | y0);            //TODO: use 'struct point' here instead?
        }
Пример #14
0
        public static string GetClientName(string mapname)
        {
            mapname = mapname.ToLower();
            int max = Global.MAP_NAME_LENGTH;

            if (mapname.Length > max)
            {
                ServerConsole.ErrorLine("Mapname '{0}' exceeds max length of {1}!", mapname, max);
                mapname = mapname.Substring(0, max);
            }
            if (mapname.EndsWith(".gat") == false)
            {
                mapname += ".gat";
            }

            return(mapname);
        }
Пример #15
0
        public static void WalkToXY(WorldObjectUnit obj, Point2D targetLoc)
        {
            // Walking in process?
            if (obj.Walkpath != null || obj.WalkTimer != null)
            {
                // Stop and reset walking
                if (obj.WalkTimer != null)
                {
                    obj.WalkTimer.Stop();
                    obj.WalkTimer = null;
                }
                obj.Walkpath = null;
            }

            obj.TargetLocation = targetLoc;
            if (obj.Location.Point == obj.TargetLocation)
            {
                return;
            }

            // Calc path
            WalkpathData wpd;

            if (PathHelper.SearchPath(out wpd, obj.Map, obj.Location.Point, obj.TargetLocation) == false)
            {
                ServerConsole.ErrorLine("Bad path, cancel moving");
                //obj.Map.DrawGat();
                return;
            }

            obj.Walkpath = wpd;
            // Player needs to notify clients about a successfull move
            if ((obj is Character))
            {
                (obj as Character).Account.Netstate.Send(new WorldResponseWalkOK(obj as Character));
            }

            // Get speed and start timer
            int speed = CalcWalkspeed(obj);

            if (speed > 0)
            {
                obj.WalkTimer = Timer.DelayCall(TimeSpan.FromMilliseconds(speed), TimeSpan.Zero, 1, new TimerStateCallback <WorldObjectUnit>(WalkToXY_Tick), obj);
            }
        }
Пример #16
0
        public static void Trace(Exception ex)
        {
            try {
                using (StreamWriter op = new StreamWriter("network-errors.log", true)) {
                    op.WriteLine("# {0}", DateTime.Now);

                    op.WriteLine(ex);

                    op.WriteLine();
                    op.WriteLine();
                }
            } catch {
            }

            try {
                ServerConsole.ErrorLine(ex.ToString());
            } catch {
            }
        }
Пример #17
0
        public void ReadAll()
        {
            int count = 0;

            ServerConsole.StatusLine("Loading Configuration Files...");

            System.Diagnostics.Stopwatch watch = System.Diagnostics.Stopwatch.StartNew();
            string MainDir = AppDomain.CurrentDomain.BaseDirectory;

            ConfigDir = Path.Combine(MainDir, mPrivateSettings.MainDir);
            if (Directory.Exists(ConfigDir) == false)
            {
                ServerConsole.ErrorLine("Configuration Directory not found!");
                ServerConsole.ErrorLine("# used Main Dir: " + MainDir);
                ServerConsole.ErrorLine("# used Conf Dir: " + mPrivateSettings.MainDir);
                ServerConsole.ErrorLine("# searched in Dir: " + ConfigDir);
                watch.Stop();
                return;
            }

            XmlSerializer xml = new XmlSerializer(typeof(PrivateSettingFileSerializeable));
            PrivateSettingFileSerializeable tempFile;
            List <string> dirFiles = new List <string>();

            // Search for our extension (".cnfx")
            dirFiles.AddRange(Directory.GetFiles(ConfigDir, "*.cnfx", SearchOption.AllDirectories));

            // Iterate and parse them
            foreach (string fileName in dirFiles)
            {
                using (FileStream fs = new FileStream(fileName, FileMode.Open)) {
                    tempFile = xml.Deserialize(fs) as PrivateSettingFileSerializeable;
                    mPrivateSettings.Add(tempFile.ToNonSerializeable());

                    ServerConsole.StatusLine(" # {0}: `{1}` ...", ++count, tempFile.FileName);
                }
            }

            ServerConsole.Status("Done Reading {0} Configs!", mPrivateSettings.Count);
            ServerConsole.WriteLine(EConsoleColor.Status, " Needed {0:F2} sec", watch.Elapsed.TotalSeconds);

            watch.Stop();
        }
Пример #18
0
        protected virtual bool LoadFromDatabase(ResultRow row)
        {
            if (CacheProperties() == false)
            {
                return(false);
            }

            var dict = mDatabaseProperties[GetType()];

            foreach (KeyValuePair <PropertyInfo, StoreableDatabaseObjectAttribute> kvp in dict)
            {
                StoreableDatabaseObjectAttribute att = kvp.Value;
                PropertyInfo prop   = kvp.Key;
                string       dbName = att.DatabaseName;


                if (row.Table.Columns.Contains(dbName) == false)
                {
                    ServerConsole.ErrorLine("Column '{0}' not found in table!", dbName);
                    continue;
                }

                object value     = row[dbName].Value;
                Type   valueType = value.GetType();
                // Catch value "null"
                if (value is DBNull)
                {
                    value = null;
                }
                // Enum's need the exact Enum value..
                if (prop.PropertyType.IsEnum == true)
                {
                    Type enumType = prop.PropertyType;
                    value = Enum.ToObject(enumType, (value == null ? 0 : value));
                }

                prop.SetValue(this, value, null);
            }

            return(true);
        }
Пример #19
0
        public static ECollisionType ByteToFlag(byte gat)
        {
            ECollisionType flag = ECollisionType.NotWalkable;

            switch (gat)
            {
            case 0:
                flag = (ECollisionType.Walkable | ECollisionType.Shootable);
                break;                         // walkable ground

            case 1:
                flag = ECollisionType.NotWalkable;
                break;                         // non-walkable ground

            case 2:
                flag = (ECollisionType.Walkable | ECollisionType.Shootable);
                break;                         // ???

            case 3:
                flag = (ECollisionType.Walkable | ECollisionType.Shootable | ECollisionType.Water);
                break;                         // walkable water

            case 4:
                flag = (ECollisionType.Walkable | ECollisionType.Shootable);
                break;                         // ???

            case 5:
                flag = (ECollisionType.Shootable);
                break;                         // gap (snipable)

            case 6:
                flag = (ECollisionType.Walkable | ECollisionType.Shootable);
                break;                         // ???

            default:
                ServerConsole.ErrorLine("Unknown tile flag {0}, default to NoWalkable", gat);
                break;
            }

            return(flag);
        }
Пример #20
0
        /// <summary>Loads all script files in this directory + sub dirs.</summary>
        /// <param name="ScriptListPath">Full pathname of the directory o search in.</param>
        public static void Initialize(string ScriptListPath)
        {
            ScriptList ScriptEntrys = new ScriptList();

            if (File.Exists(ScriptListPath) == false)
            {
                ServerConsole.ErrorLine("Can't load File from \"" + ScriptListPath + "\"!");
                return;
            }

            using (FileStream s = File.OpenRead(ScriptListPath)) {
                ScriptEntrys = mXmlSerializer.Deserialize(s) as ScriptList;
            }

            // Build absolute paths and load includes
            string basePath = Path.GetDirectoryName(ScriptListPath);

            for (int i = 0; i < ScriptEntrys.Count; i++)
            {
                for (int j = 0; j < ScriptEntrys[i].Entrys.Count; j++)
                {
                    // Include or path?
                    if (ScriptEntrys[i].Entrys[j].Type == EScriptType.Include)
                    {
                        string includePath = Path.Combine(Path.GetDirectoryName(ScriptListPath), ScriptEntrys[i].Entrys[j].Path);
                        ScriptDatabase.Initialize(includePath);
                    }
                    else
                    {
                        // Build an absolute path
                        ScriptEntrys[i].Entrys[j].Path = Path.Combine(basePath, Path.GetDirectoryName(ScriptEntrys[i].Entrys[j].Path)) + @"\" + Path.GetFileName(ScriptEntrys[i].Entrys[j].Path);
                    }
                }
            }

            // Push to static list
            if (ScriptEntrys.Count > 0)
            {
                Scripts.AddRange(ScriptEntrys);
            }
        }
Пример #21
0
        protected virtual List <string> GetUpdateParams()
        {
            List <string> updateParams = new List <string>();
            var           dict         = mDatabaseProperties[GetType()];

            foreach (KeyValuePair <PropertyInfo, StoreableDatabaseObjectAttribute> kvp in dict)
            {
                StoreableDatabaseObjectAttribute att = kvp.Value;
                // Dont update prop?
                if (att.NoUpdate == true)
                {
                    continue;
                }

                PropertyInfo prop   = kvp.Key;
                string       dbName = att.DatabaseName;
                object       value  = null;

                value = prop.GetValue(this, null);

                // If type is null, no conversion is needed
                if (att.Type != null)
                {
                    try {
                        object valueNew = Convert.ChangeType(value, att.Type);
                        // Conversion done without exception, copy back
                        value    = valueNew;
                        valueNew = null;                         // Cleanup
                    } catch {
                        ServerConsole.ErrorLine("Failed to convert value " + value + " (" + value.GetType() + ") to " + att.Type);
                        // Skip if failed to convert!
                        continue;
                    }
                }

                updateParams.Add("`" + dbName + "` = '" + value + "'");
            }

            return(updateParams);
        }
Пример #22
0
        private static Monster SpawnOnceSub(Character character, Location loc, string name, int mobID)
        {
            // Create new world object based on mobID
            Monster mob = new Monster(new DatabaseID(mobID, EDatabaseType.Mob));
            // Search free cell to spawn, if no given
            Point2D spawnPoint = loc.Point;

            if (character != null && (spawnPoint.X < 0 || spawnPoint.Y < 0))
            {
                // if none found, pick random position on map
                if (loc.Map.SearchFreeCell(character, ref spawnPoint, 1, 1, 0) == false)
                {
                    if (spawnPoint.X <= 0 || spawnPoint.Y <= 0 || loc.Map.CheckCell(spawnPoint, ECollisionType.Reachable) == false)
                    {
                        // Failed to fetch random spot on the whole map?
                        if (loc.Map.SearchFreeCell(null, ref spawnPoint, -1, -1, 1) == false)
                        {
                            ServerConsole.ErrorLine("SpawnSub: Failed to locate spawn pos on map " + loc.Map.Name);
                            return(null);
                        }
                    }
                }
            }

            mob.Location = new Location(loc.Map.ID, spawnPoint);
            mob.Name     = name;
            mob.Class    = (short)mobID;

            // mob_parse_dataset here; check for tiny/large, event and so on

            // TODO: takeover of special_state AI ect; need mob_parse_dataset before
            //		 and place in Monster class to store it (look @ eA mob_data)

            mob.ViewData   = WorldObjectViewData.GetViewData(mob.Database, mobID);
            mob.Status     = new WorldObjectStatus(mob);
            mob.BaseStatus = new WorldObjectStatus(mob);
            mob.StatusChange.Clear();

            return(mob);
        }
Пример #23
0
        public void LoadCart()
        {
            Cart.Clear();
            DataTable table = Core.Database.Query("SELECT * FROM `char_cart` WHERE `charID` = {0}", ID);

            if (table == null || table.Rows.Count == 0)
            {
                return;
            }

            foreach (DataRow row in table.Rows)
            {
                CharacterItem item = CharacterItem.Load(row);
                if (item == null)
                {
                    ServerConsole.ErrorLine("Failed to load char cart item #{0}", row.Field <int>("id"));
                    continue;
                }

                Cart.Add(item);
            }
        }
Пример #24
0
 /// <summary>
 /// Realse the given PacketWriter instance and makes it available again in the pool
 /// </summary>
 /// <param name="pw"></param>
 public static void ReleaseInstance(PacketWriter pw)
 {
     lock (mPool) {
         // If we fetch a writer form the pool, he will be removed from it
         // So this catches manually created writers
         if (!mPool.Contains(pw))
         {
             // Then push it to our pool
             mPool.Push(pw);
         }
         else
         {
             try {
                 //TODO: move to global Logger
                 using (StreamWriter op = new StreamWriter("neterr.log")) {
                     op.WriteLine("{0}\tInstance pool contains writer", DateTime.Now);
                 }
             } catch {
                 ServerConsole.ErrorLine("Error on Logging PacketWriter.ReleaseInstance() Error");
             }
         }
     }
 }
Пример #25
0
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var ex = e.ExceptionObject as Exception;

            ServerConsole.Write(EConsoleColor.Error, e.IsTerminating ? "Error: " : "Warning: ");
            ServerConsole.WriteLine(EConsoleColor.Error, Tools.CleanExcepionStacktrace(ex.Message));
            if (ex.StackTrace != string.Empty)
            {
                ServerConsole.WriteLine(ex.StackTrace);
            }

            if (e.IsTerminating == false)
            {
                return;
            }

            mCrashed = true;
            var close = false;

            try {
                var args = new CrashedEventArgs(e.ExceptionObject as Exception);
                Events.InvokeCrashed(args);
                close = args.Close;
            } catch (Exception) {
            }

            if (!close)
            {
                SocketPool.Destroy();

                ServerConsole.ErrorLine("This exception is fatal, press return to exit");
                ServerConsole.Read();
            }

            mClosing = true;
        }
Пример #26
0
        public static void Load()
        {
            if (Loaded == true || Loading == true)
            {
                return;
            }

            Loading = true;
            // Trigger events for scripts
            Events.InvokeWorldLoadStart();

            // Our object manager for databsae objects
            Database = new DatabaseObjectManager();
            // Our object manager for world objects (spawned objects)
            Objects = new WorldObjectManager();

            // Delegate for Send() Method
            mForeachInRangeCallback = new ForeachInRangeVoidDelegate(SendSub);

            mAddQueue = new Queue <DatabaseObject>();
            mDelQueue = new Queue <DatabaseObject>();

            // Load globals from config, initialize packets ect
            ServerConsole.InfoLine("Initialize game symantics...");
            Global.Initialize();
            WorldObjectStatus.Initialize();
            ChatHelper.Initialize();
            PlayerCommandHelper.Initialize();
            PathHelper.Initialize();
            SkillTree.Initialize();
            FameListHelper.Initialize();
            CharacterJobBonus.Initialize();
            CharacterJobModifer.Initialize();

            // Real database loading
            ServerConsole.InfoLine("Begin World loading...");

            DataTable table    = null;
            Stopwatch watchAll = Stopwatch.StartNew();
            Stopwatch watch    = Stopwatch.StartNew();

            //------------- loading start -------------

            #region Mapcache
            ServerConsole.Info("\t# loading Maps from mapcache...");
            watch.Reset();
            watch.Start();
            Mapcache.Initialize();
            watch.Stop();
            ServerConsole.WriteLine(EConsoleColor.Status, " done (" + Mapcache.Maps.Count + " Maps in " + watch.ElapsedMilliseconds + "ms)");
            #endregion


            #region Items
            ServerConsole.Info("\t# loading Items...");
            watch.Reset();
            watch.Start();
            table           = Core.Database.Query("SELECT * FROM dbitem");
            table.TableName = "ItemDB Table";


            if (table == null || table.Rows.Count == 0)
            {
                if (Core.Database.LastError != null)
                {
                    ServerConsole.ErrorLine("failed to load Item Database!");
                    ServerConsole.WriteLine(Core.Database.LastError.ToString());
                }
            }
            else
            {
                ItemDatabaseData item;
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    item = ItemDatabaseData.Load(table.Rows[i]);
                    if (item == null)
                    {
                        ServerConsole.WarningLine("Failed to load item {0}: #{1} {2}", i, table.Rows[i].Field <int>("itemID"), table.Rows[i].Field <string>("nameEnglish"));
                        continue;
                    }
                    Database.Add(item);

                    //ServerConsole.DebugLine("\tLoad: #{0} {1}", item.NameID.ToString().PadLeft(5), item.Name);
                }
            }
            watch.Stop();
            ServerConsole.WriteLine(EConsoleColor.Status, " done (" + Database.Items.Count + " Items in " + watch.ElapsedMilliseconds + "ms)");
            #endregion


            #region Monster
            ServerConsole.Info("\t# loading Mobs...");
            watch.Reset();
            watch.Start();
            table           = Core.Database.Query("SELECT * FROM dbmob");
            table.TableName = "MobDB Table";
            if (table == null || table.Rows.Count == 0)
            {
                if (Core.Database.LastError != null)
                {
                    ServerConsole.ErrorLine("failed to load Monster Database!");
                    ServerConsole.WriteLine(Core.Database.LastError.ToString());
                }
            }
            else
            {
                MonsterDatabaseData mob;
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    mob = MonsterDatabaseData.Load(table.Rows[i]);
                    if (mob == null)
                    {
                        ServerConsole.WarningLine("Failed to load mob {0}: #{1} {2}", i, table.Rows[i].Field <int>("mobID"), table.Rows[i].Field <string>("nameInter"));
                        continue;
                    }
                    Database.Add(mob);

                    //ServerConsole.DebugLine("\tLoad: #{0} {1} ({2} drops, {3} skills)", mob.ID.ToString().PadLeft(5), mob.NameInter, mob.Drops.Count, mob.Skills.Count);
                }
            }
            watch.Stop();
            ServerConsole.WriteLine(EConsoleColor.Status, " done (" + Database.Monster.Count + " Mobs in " + watch.ElapsedMilliseconds + "ms)");


            ServerConsole.Info("\t# loading Mob Skills...");
            watch.Reset();
            watch.Start();
            table           = Core.Database.Query("SELECT * FROM dbmob_skill ORDER BY mobID ASC");
            table.TableName = "MobDB Skill Table";
            if (table == null || table.Rows.Count == 0)
            {
                if (Core.Database.LastError != null)
                {
                    ServerConsole.ErrorLine("failed to load Mob Skill Database!");
                    ServerConsole.WriteLine(Core.Database.LastError.ToString());
                }
            }
            else
            {
                MonsterSkill mobSkill;
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    mobSkill = MonsterSkill.Load(table.Rows[i]);
                    if (mobSkill == null)
                    {
                        throw new Exception(string.Format("Failed to load mob skill #{0}: {1}", table.Rows[i].Field <int>("mobID"), table.Rows[i].Field <string>("info")));
                    }

                    (Database[EDatabaseType.Mob, mobSkill.MobID] as MonsterDatabaseData).Skills.Add(mobSkill);

                    //ServerConsole.DebugLine("\tLoad: #{0} {1} ({2} level)", skill.ID.ToString().PadLeft(5), skill.Name, skill.Level.Count);
                }
            }
            watch.Stop();
            ServerConsole.WriteLine(EConsoleColor.Status, " done in " + watch.ElapsedMilliseconds + "ms");


            ServerConsole.Info("\t# loading Mob Drops...");
            watch.Reset();
            watch.Start();
            table           = Core.Database.Query("SELECT * FROM dbmob_drop ORDER BY mobID ASC");
            table.TableName = "MobDB Drop Table";
            if (table == null || table.Rows.Count == 0)
            {
                if (Core.Database.LastError != null)
                {
                    ServerConsole.ErrorLine("failed to load Mob Drop Database!");
                    ServerConsole.WriteLine(Core.Database.LastError.ToString());
                }
            }
            else
            {
                MonsterDrop drop;
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    drop = MonsterDrop.Load(table.Rows[i]);

                    (Database[EDatabaseType.Mob, drop.MobID] as MonsterDatabaseData).Drops.Add(drop);

                    //ServerConsole.DebugLine("\tLoad: #{0} {1} ({2} level)", skill.ID.ToString().PadLeft(5), skill.Name, skill.Level.Count);
                }
            }
            watch.Stop();
            ServerConsole.WriteLine(EConsoleColor.Status, " done in " + watch.ElapsedMilliseconds + "ms");
            #endregion


            #region General Skills
            ServerConsole.Info("\t# loading Skills...");
            watch.Reset();
            watch.Start();
            table           = Core.Database.Query("SELECT * FROM dbskill");
            table.TableName = "SkillDB Table";
            if (table == null || table.Rows.Count == 0)
            {
                if (Core.Database.LastError != null)
                {
                    ServerConsole.ErrorLine("failed to load Skill Database!");
                    ServerConsole.WriteLine(Core.Database.LastError.ToString());
                }
            }
            else
            {
                SkillDatabaseData skill;
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    skill = SkillDatabaseData.Load(table.Rows[i]);
                    if (skill == null)
                    {
                        ServerConsole.WarningLine("Failed to load skill {0}: #{1} {2}", i, table.Rows[i].Field <int>("skillID"), table.Rows[i].Field <string>("name"));
                        continue;
                    }
                    Database.Add(skill.Index, skill);

                    //ServerConsole.DebugLine("\tLoad: #{0} {1} ({2} level)", skill.ID.ToString().PadLeft(5), skill.Name, skill.Level.Count);
                }
            }
            watch.Stop();
            ServerConsole.WriteLine(EConsoleColor.Status, " done (" + Database.Skill.Count + " Skills in " + watch.ElapsedMilliseconds + "ms)");
            #endregion


            // Loading other shit
            // o.o

            //------------- loading end -------------

            // Trigger event for scripts
            Events.InvokeWorldLoadFinish();

            Loading = false;
            Loaded  = true;

            ProcessSafetyQueues();

            // TODO: Initialize save timer

            ServerConsole.InfoLine("Finished World loading! Needed {0:F2} sec", watchAll.Elapsed.TotalSeconds);

            watch.Stop();
            watch = null;
            watchAll.Stop();
            watchAll = null;
        }
Пример #27
0
        private static void Display(CompilerResults results)
        {
            if (results.Errors.Count > 0)
            {
                Dictionary <string, List <CompilerError> > errors   = new Dictionary <string, List <CompilerError> >(results.Errors.Count, StringComparer.OrdinalIgnoreCase);
                Dictionary <string, List <CompilerError> > warnings = new Dictionary <string, List <CompilerError> >(results.Errors.Count, StringComparer.OrdinalIgnoreCase);

                foreach (CompilerError e in results.Errors)
                {
                    string file = e.FileName;

                    if (string.IsNullOrEmpty(file))
                    {
                        ServerConsole.ErrorLine("\n# {0}: {1}", e.ErrorNumber, e.ErrorText);
                        continue;
                    }

                    Dictionary <string, List <CompilerError> > table = (e.IsWarning ? warnings : errors);

                    List <CompilerError> list = null;
                    table.TryGetValue(file, out list);

                    if (list == null)
                    {
                        table[file] = list = new List <CompilerError>();
                    }

                    list.Add(e);
                }

                if (errors.Count > 0)
                {
                    ServerConsole.ErrorLine("failed ({0} errors, {1} warnings)", errors.Count, warnings.Count);
                }
                else
                {
                    ServerConsole.ErrorLine("done ({0} errors, {1} warnings)", errors.Count, warnings.Count);
                }

                string scriptRoot    = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Scripts" + Path.DirectorySeparatorChar));
                Uri    scriptRootUri = new Uri(scriptRoot);

                if (warnings.Count > 0)
                {
                    ServerConsole.WriteLine(EConsoleColor.DarkYellow, "Script Warnings:");
                }

                foreach (KeyValuePair <string, List <CompilerError> > kvp in warnings)
                {
                    string fileName           = kvp.Key;
                    List <CompilerError> list = kvp.Value;

                    string fullPath = Path.GetFullPath(fileName);
                    string usedPath = Uri.UnescapeDataString(scriptRootUri.MakeRelativeUri(new Uri(fullPath)).OriginalString);

                    ServerConsole.WriteLine(" + {0}:", usedPath);

                    foreach (CompilerError e in list)
                    {
                        ServerConsole.WriteLine("\t#{0}: Line {1}/ Col {2}: {3}", e.ErrorNumber, e.Line, e.Column, e.ErrorText);
                    }
                }

                if (errors.Count > 0)
                {
                    ServerConsole.WriteLine(EConsoleColor.Error, "Script Errors:");
                }

                foreach (KeyValuePair <string, List <CompilerError> > kvp in errors)
                {
                    string fileName           = kvp.Key;
                    List <CompilerError> list = kvp.Value;

                    string fullPath = Path.GetFullPath(fileName);
                    string usedPath = Uri.UnescapeDataString(scriptRootUri.MakeRelativeUri(new Uri(fullPath)).OriginalString);

                    ServerConsole.WriteLine(" + {0}:", usedPath);

                    foreach (CompilerError e in list)
                    {
                        ServerConsole.WriteLine("\t#{0}: Line {1}/ Col {2}: {3}", e.ErrorNumber, e.Line, e.Column, e.ErrorText);
                    }
                }
            }
            else
            {
                ServerConsole.StatusLine("done (0 errors, 0 warnings)");
            }
        }
Пример #28
0
        /// <summary>
        /// Calls a Method/Function from the <see cref="Assemblies"/>
        /// </summary>
        /// <param name="MethodName">The searched Method/Function name</param>
        /// <param name="Arguments">an <see cref="object[]"/> Array which represents the Arguments</param>
        /// <param name="Silent">no Error Output?</param>
        public static bool CallMethod(string MethodName, object[] Arguments, bool Silent)
        {
            Assembly          Assembly      = null;
            List <MethodInfo> invokeList    = new List <MethodInfo>();
            string            NamespaceName = Namespace;

            // Any assembly to call from?
            if (Assemblies == null || Assemblies.Length < 1)
            {
                return(false);
            }

            // Search for the exact name
            // TODO: we need some sort of cache, maybe dictionary to call directly without searching
            for (int i = 0; i < Assemblies.Length; i++)
            {
                if ((Assembly = Assemblies[i]) == null)
                {
                    continue;
                }

                Type[] types = Assembly.GetTypes();
                for (int t = 0; t < types.Length; t++)
                {
                    // We only search in scripting namespace
                    if (types[t].Namespace.StartsWith(NamespaceName) == false)
                    {
                        continue;
                    }
                    try {
                        // Search a puplic and static method
                        MethodInfo info = types[t].GetMethod(MethodName, BindingFlags.Static | BindingFlags.Public);
                        if (info != null)
                        {
                            invokeList.Add(info);
                        }
                    } catch { }
                }
            }

            // Found some? Sort them by call priority (custom attribute)
            if (invokeList.Count > 0)
            {
                invokeList.Sort(new CallPriorityComparer());
            }
            else
            {
                if (Silent == false)
                {
                    ServerConsole.ErrorLine("CallMethod \"{0}.{1}\" failed! Method was not found in {2} Assemblies!", NamespaceName, MethodName, Assemblies.Length);
                }
                return(false);
            }

            for (int i = 0; i < invokeList.Count; i++)
            {
                ParameterInfo[]    args = invokeList[i].GetParameters();
                MethodInvokeHelper inv  = new MethodInvokeHelper(invokeList[i]);
                // Dynamic fill all arguments
                // Note: if more arguments need then given, null will be used
                if (args != null && args.Length > 0)
                {
                    inv.MethodArguments = FillArgList(args, Arguments);
                }

                // Start a thread for every execution
                // TODO: we need some sort of logic here!
                //		 if we execute this for 100 player @ a time, 100 threads are running
                //		 might by slow and unstable..
                Thread thread = new Thread(new ThreadStart(inv.Invoke));
                thread.Name = inv.MethodInfo.Name;
                thread.Start();
            }

            // Garbage
            invokeList.Clear();

            return(true);
        }
Пример #29
0
        private static bool LoadPacketDefintions()
        {
            string filePath = "Config/Server/Packets.xml";

            if (File.Exists(filePath) == false)
            {
                ServerConsole.WriteLine(GodLesZ.Library.EConsoleColor.Error, "failed, file not found!");
                Core.Kill();
                return(false);
            }

            XmlSerializer xml = new XmlSerializer(typeof(PacketList));

            using (Stream fs = File.OpenRead(filePath)) {
                mPackets = (PacketList)xml.Deserialize(fs);
            }

            // TODO: Make a defaul packet version, holding base definitions
            //		 and let them be overritten from higher versions


            // Load all types from script assemblies
            //List<Type> scriptTypes = new List<Type>();

            /*
             * foreach (Assembly asm in Scripting.ScriptCompiler.Assemblies) {
             *      scriptTypes.AddRange(asm.GetTypes());
             * }
             */
            Assembly lookupAsm = Assembly.GetExecutingAssembly();

            // Attach all packet handlers
            foreach (PacketVersion packets in mPackets)
            {
                foreach (PacketDefinition p in packets.Packets)
                {
                    string asmName = string.Format("Rovolution.Server.Network.Packets.{0}", p.HandlerType);

                    /*
                     * foreach (Type type in scriptTypes) {
                     *      if (type.FullName == asmName) {
                     *              MethodInfo info = type.GetMethod(p.HandlerName, BindingFlags.Public | BindingFlags.Static);
                     *              Delegate dele = Delegate.CreateDelegate(typeof(OnPacketReceive), info);
                     *              PacketHandlers.Register(p.ID, p.Length, (OnPacketReceive)dele);
                     *
                     *              found = true;
                     *              break;
                     *      }
                     * }
                     */
                    Type t = lookupAsm.GetType(asmName);
                    if (t != null)
                    {
                        MethodInfo info = t.GetMethod(p.HandlerName, BindingFlags.Public | BindingFlags.Static);
                        if (info == null)
                        {
                            ServerConsole.ErrorLine("Unable to find Packet handler for definition: {0}.{1}", p.HandlerType, p.HandlerName);
                            continue;
                        }
                        Delegate dele = Delegate.CreateDelegate(typeof(OnPacketReceive), info);
                        PacketHandlers.Register(p.HandlerName, p.ID, p.Length, (OnPacketReceive)dele);
                    }
                    else
                    {
                        ServerConsole.ErrorLine("Unable to find Packet handler for definition: {0}.{1}", p.HandlerType, p.HandlerName);
                    }
                }
            }

            return(true);
        }
Пример #30
0
        public static void Send(Packet p, WorldObject source, ESendTarget target)
        {
            if (target != ESendTarget.AllClients && target != ESendTarget.ChatMainchat)
            {
                if (source == null)
                {
                    ServerConsole.ErrorLine("World.Send: WorldObject (source) cant be null on type " + target + "!");
                    return;
                }
            }

            Rectangle2D area;

            switch (target)
            {
            case ESendTarget.Self:
                if (source is Character && (source as Character).Account.Netstate != null)
                {
                    (source as Character).Account.Netstate.Send(p);
                }
                break;

            case ESendTarget.AllClients:
                World.SendAllClients(p);
                break;

            case ESendTarget.AllSameMap:
                // Source must have a map/is moveable
                if (source is WorldObjectUnit)
                {
                    foreach (MapBlock block in (source as WorldObjectUnit).Map.Blocks)
                    {
                        foreach (WorldObject obj in block.Values)
                        {
                            if (obj is Character)
                            {
                                (obj as Character).Account.Netstate.Send(p);
                            }
                        }
                    }
                }
                break;

            case ESendTarget.Area:
            case ESendTarget.AreaWithoutOwnChatrooms:
            case ESendTarget.AreaWithoutChatrooms:
            case ESendTarget.AreaWithoutSelf:
                //if (sd && bl->prev == NULL) //Otherwise source misses the packet
                // TODO: what means that? how exactly do they using ->prev and ->next pointer?
                if ((source is Character) && (target == ESendTarget.Area || target == ESendTarget.AreaWithoutOwnChatrooms))
                {
                    (source as Character).Account.Netstate.Send(p);
                }

                if (source is Character)
                {
                    area = new Rectangle2D((source as Character).Location.X - Global.AREA_SIZE, (source as Character).Location.Y - Global.AREA_SIZE, (source as Character).Location.X + Global.AREA_SIZE, (source as Character).Location.Y + Global.AREA_SIZE, true);
                    (source as Character).Map.ForeachInRange(area, mForeachInRangeCallback, new object[] { source, p, target });
                }
                break;

            case ESendTarget.HearableAreaWithoutChatrooms:
                if (source is Character)
                {
                    area = new Rectangle2D((source as Character).Location.X - (Global.AREA_SIZE - 5), (source as Character).Location.Y - (Global.AREA_SIZE - 5), (source as Character).Location.X + (Global.AREA_SIZE - 5), (source as Character).Location.Y + (Global.AREA_SIZE - 5), true);
                    (source as Character).Map.ForeachInRange(area, mForeachInRangeCallback, new object[] { source, p, ESendTarget.AreaWithoutChatrooms });
                }
                break;
            }
        }