private static int DeleteMoonGate(Map map, Point3D p)
		{
			Queue<Item> m_Queue = new Queue<Item>();

			IPooledEnumerable eable = map.GetItemsInRange(p, 0);

			foreach (Item item in eable)
			{
				if (item is PublicMoongate)
				{
					int delta = item.Z - p.Z;

					if (delta >= -12 && delta <= 12)
						m_Queue.Enqueue(item);
				}
			}

			eable.Free();

			int m_Count = m_Queue.Count;

			while (m_Queue.Count > 0)
				(m_Queue.Dequeue()).Delete();

			return m_Count;
		}
Exemple #2
0
		public FileQueue(int concurrentWrites, FileCommitCallback callback)
		{
			if (concurrentWrites < 1)
			{
				throw new ArgumentOutOfRangeException("concurrent" + "Writes");
			}

			if (bufferSize < 1)
			{
				throw new ArgumentOutOfRangeException("buffer" + "Size");
			}

			if (callback == null)
			{
				throw new ArgumentNullException("callback");
			}

			syncRoot = new object();

			active = new Chunk[concurrentWrites];
			pending = new Queue<Page>();

			this.callback = callback;

			idle = new ManualResetEvent(true);
		}
		static VitaNexCore()
		{
			_INITQueue = new Queue<Tuple<string, string>>();
			_INITHandlers = new Dictionary<string, Action<string>>();

			_INITVersion = "2.2.0.0";

			Version = null;

			if (!Directory.Exists(IOUtility.GetSafeDirectoryPath(Core.BaseDirectory + "/VitaNexCore")))
			{
				FirstBoot = true;
			}

			BaseDirectory = IOUtility.EnsureDirectory(Core.BaseDirectory + "/VitaNexCore");

			if (!File.Exists(BaseDirectory + "/FirstBoot.vnc"))
			{
				FirstBoot = true;

				IOUtility.EnsureFile(BaseDirectory + "/FirstBoot.vnc")
						 .AppendText(
							 true,
							 "This file serves no other purpose than to identify if",
							 "the software has been initialized for the first time. ",
							 "To re-initialize 'First-Boot' mode, simply delete this",
							 "file before starting the application.");
			}

			// HACK: See FindRootDirectory summary.
			var root = FindRootDirectory(Core.BaseDirectory + "/Scripts/VitaNex");
			
			if (root == null || !root.Exists)
			{
				return;
			}

			RootDirectory = root;

			ParseVersion();
			ParseINIT();

			RegisterINITHandler(
				"ROOT_DIR",
				path =>
				{
					root = FindRootDirectory(path);

					if (root == null || !root.Exists)
					{
						return;
					}

					RootDirectory = root;

					ParseVersion();
				});
		}
Exemple #4
0
        static void Main(string[] args)
        {
            using (var context = new Context(1))
            {
                using (Socket frontend = context.Socket(SocketType.ROUTER), backend = context.Socket(SocketType.ROUTER))
                {
                    frontend.Bind("tcp://*:5555"); // For Clients
                    backend.Bind("tcp://*:5556"); // For Workers

                    //  Logic of LRU loop
                    //  - Poll backend always, frontend only if 1+ worker ready
                    //  - If worker replies, queue worker as ready and forward reply
                    //    to client if necessary
                    //  - If client requests, pop next worker and send request to it

                    //  Queue of available workers
                    var workerQueue = new Queue<byte[]>();

                    //  Handle worker activity on backend
                    backend.PollInHandler += (socket, revents) =>
                                                 {
                                                     var zmsg = new ZMessage(socket);
                                                     //  Use worker address for LRU routing
                                                     workerQueue.Enqueue(zmsg.Unwrap());

                                                     //  Forward message to client if it's not a READY
                                                     if (!Encoding.Unicode.GetString(zmsg.Address).Equals(LRU_READY))
                                                     {
                                                         zmsg.Send(frontend);
                                                     }
                                                 };

                    frontend.PollInHandler += (socket, revents) =>
                                                  {
                                                      //  Now get next client request, route to next worker
                                                      //  Dequeue and drop the next worker address
                                                      var zmsg = new ZMessage(socket);
                                                      zmsg.Wrap(workerQueue.Dequeue(), new byte[0]);
                                                      zmsg.Send(backend);
                                                  };

                    while (true)
                    {
                        int rc = Context.Poller(workerQueue.Count > 0
                                                    ? new List<Socket>(new Socket[] {frontend, backend})
                                                    : new List<Socket>(new Socket[] {backend}));

                        if (rc == -1)
                        {
                            break;
                        }
                    }
                }
            }
        }
        static UOFLegends()
        {
            CMOptions = new UOFLegendsOptions();

            ObjectStateTypes = typeof(LegendState).GetConstructableChildren();

            ObjectStates = new LegendState[ObjectStateTypes.Length];

            ExportQueue = new ConcurrentDictionary<string, ConcurrentStack<QueuedData>>();

            UpdateTimes = new Queue<TimeSpan>(10);
        }
        public void Start()
        {
            config = new ConfigLoad();
            data_exchange = new DataExchange(this);
            command_handler = new CommandHandler(this);
            queue_command = new Queue<DataXMLPackage>();

            thread_data = new Thread(data_exchange.dataConector);// поток для приема и передачи данных
            thread_data.Start();
            thread_command = new Thread(command_handler.ReadCommandClient);// поток для обработки комманд клиента
            thread_command.Start();

            System.Console.WriteLine("Сервер запущен!"); //\"" + config.vars["S_SERVER_NAME"] + "\"
            command_handler.ReadCommandConsole();
        }
Exemple #7
0
        void doWork()
        {
            if (toUpdate.Count != 0)
            {
                Queue<WorldPosition> cache;
                lock (toUpdate)
                {
                    cache = toUpdate;
                    toUpdate = new Queue<WorldPosition>();
                }

                while (cache.Count != 0)
                    ValidatePhysics(cache.Dequeue());
            }
        }
Exemple #8
0
		public void ReleaseTemp( LocalBuilder local )
		{
			Queue<LocalBuilder> list;

			if ( !m_Temps.TryGetValue( local.LocalType, out list ) )
				m_Temps[local.LocalType] = list = new Queue<LocalBuilder>();

			list.Enqueue( local );
		}
Exemple #9
0
		public LocalBuilder AcquireTemp( Type localType )
		{
			Queue<LocalBuilder> list;

			if ( !m_Temps.TryGetValue( localType, out list ) )
				m_Temps[localType] = list = new Queue<LocalBuilder>();

			if ( list.Count > 0 )
				return list.Dequeue();

			return CreateLocal( localType );
		}
Exemple #10
0
		static VitaNexCore()
		{
			_INITVersion = "2.2.0.0";

			#if MONO
			Version = _INITVersion;
			#endif
			
			_INITQueue = new Queue<Tuple<string, string>>();
			_INITHandlers = new Dictionary<string, Action<string>>();

			//ensuring simply "VitaNexCore" exists causes Mono to look in system root folder "/", so we
			// concatenate to give path relative to Server.  --sith
			if (!Directory.Exists(Core.BaseDirectory + "/VitaNexCore"))
			{
				FirstBoot = true;
			}

			BaseDirectory = IOUtility.EnsureDirectory(Core.BaseDirectory + "/VitaNexCore");

			if (!File.Exists(BaseDirectory + "/FirstBoot.vnc"))
			{
				FirstBoot = true;

				IOUtility.EnsureFile(BaseDirectory + "/FirstBoot.vnc")
						 .AppendText(
							 true,
							 "This file serves no other purpose than to identify if",
							 "the software has been initialized for the first time. ",
							 "To re-initialize 'First-Boot' mode, simply delete this",
							 "file before starting the application.");
			}


			#if !MONO
			// Someone moved VitaNex from Scripts/VitaNex to Scripts/Custom Systems/VitaNex/Core
			//  but this path was not updated... does this cause problems on Windows?  --Sith
			var root = FindRootDirectory("Scripts/VitaNex");
			#else
			var root = new DirectoryInfo(Core.BaseDirectory + @"/Scripts/Custom Systems/VitaNex/Core");
			#endif
			
			if (root == null || !root.Exists)
			{
				return;
			}

			RootDirectory = root;

			ParseVersion();
			ParseINIT();

			RegisterINITHandler(
				"ROOT_DIR",
				path =>
				{
					root = FindRootDirectory(path);

					if (root == null || !root.Exists)
					{
						return;
					}

					RootDirectory = root;

					ParseVersion();
				});
		}
		public StandardSaveStrategy() {
			_decayQueue = new Queue<Item>();
			_decayMapQueue = new Queue<BaseInstanceMap>();
		}
Exemple #12
0
 public PhysicsManager(MainWindow server)
 {
     this.server = server;
     toUpdate = new Queue<WorldPosition>();
     HelpfulStuff.RunPeriodic(doWork, 200);
 }
Exemple #13
0
		public static void Load() {
			if ( m_Loaded )
				return;

			m_Loaded = true;
			m_LoadingType = null;

			Console.Write( "World: Loading..." );

			Stopwatch watch = Stopwatch.StartNew();

			m_Loading = true;

			_addQueue = new Queue<IEntity>();
			_deleteQueue = new Queue<IEntity>();

			int mobileCount = 0, itemCount = 0, guildCount = 0;

			object[] ctorArgs = new object[1];
			Type[] ctorTypes = new Type[1] { typeof( Serial ) };

			List<ItemEntry> items = new List<ItemEntry>();
			List<MobileEntry> mobiles = new List<MobileEntry>();
			List<GuildEntry> guilds = new List<GuildEntry>();

			if ( File.Exists( MobileIndexPath ) && File.Exists( MobileTypesPath ) ) {
				using ( FileStream idx = new FileStream( MobileIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) {
					BinaryReader idxReader = new BinaryReader( idx );

					using ( FileStream tdb = new FileStream( MobileTypesPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) {
						BinaryReader tdbReader = new BinaryReader( tdb );

						int count = tdbReader.ReadInt32();

						ArrayList types = new ArrayList( count );

						for ( int i = 0; i < count; ++i ) {
							string typeName = tdbReader.ReadString();

							Type t = ScriptCompiler.FindTypeByFullName( typeName );

							if ( t == null ) {
								Console.WriteLine( "failed" );
								
								if ( !Core.Service ) {
									Console.WriteLine( "Error: Type '{0}' was not found. Delete all of those types? (y/n)", typeName );

									if ( Console.ReadKey( true ).Key == ConsoleKey.Y ) {
										types.Add( null );
										Console.Write( "World: Loading..." );
										continue;
									}

									Console.WriteLine( "Types will not be deleted. An exception will be thrown." );
								} else {
									Console.WriteLine( "Error: Type '{0}' was not found.", typeName );
								}

								throw new Exception( String.Format( "Bad type '{0}'", typeName ) );
							}

							ConstructorInfo ctor = t.GetConstructor( ctorTypes );

							if ( ctor != null ) {
								types.Add( new object[] { ctor, null } );
							} else {
								throw new Exception( String.Format( "Type '{0}' does not have a serialization constructor", t ) );
							}
						}

						mobileCount = idxReader.ReadInt32();

						m_Mobiles = new Dictionary<Serial, Mobile>( mobileCount );

						for ( int i = 0; i < mobileCount; ++i ) {
							int typeID = idxReader.ReadInt32();
							int serial = idxReader.ReadInt32();
							long pos = idxReader.ReadInt64();
							int length = idxReader.ReadInt32();

							object[] objs = ( object[] ) types[typeID];

							if ( objs == null )
								continue;

							Mobile m = null;
							ConstructorInfo ctor = ( ConstructorInfo ) objs[0];
							string typeName = ( string ) objs[1];

							try {
								ctorArgs[0] = ( Serial ) serial;
								m = ( Mobile ) ( ctor.Invoke( ctorArgs ) );
							} catch {
							}

							if ( m != null ) {
								mobiles.Add( new MobileEntry( m, typeID, typeName, pos, length ) );
								AddMobile( m );
							}
						}

						tdbReader.Close();
					}

					idxReader.Close();
				}
			} else {
				m_Mobiles = new Dictionary<Serial, Mobile>();
			}

			if ( File.Exists( ItemIndexPath ) && File.Exists( ItemTypesPath ) ) {
				using ( FileStream idx = new FileStream( ItemIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) {
					BinaryReader idxReader = new BinaryReader( idx );

					using ( FileStream tdb = new FileStream( ItemTypesPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) {
						BinaryReader tdbReader = new BinaryReader( tdb );

						int count = tdbReader.ReadInt32();

						ArrayList types = new ArrayList( count );

						for ( int i = 0; i < count; ++i ) {
							string typeName = tdbReader.ReadString();

							Type t = ScriptCompiler.FindTypeByFullName( typeName );

							if ( t == null ) {
								Console.WriteLine( "failed" );
								
								
								if ( !Core.Service ) {
									Console.WriteLine( "Error: Type '{0}' was not found. Delete all of those types? (y/n)", typeName );

									if ( Console.ReadKey( true ).Key == ConsoleKey.Y ) {
										types.Add( null );
										Console.Write( "World: Loading..." );
										continue;
									}

									Console.WriteLine( "Types will not be deleted. An exception will be thrown." );
								} else {
									Console.WriteLine( "Error: Type '{0}' was not found.", typeName );
								}

								throw new Exception( String.Format( "Bad type '{0}'", typeName ) );
							}

							ConstructorInfo ctor = t.GetConstructor( ctorTypes );

							if ( ctor != null ) {
								types.Add( new object[] { ctor, typeName } );
							} else {
								throw new Exception( String.Format( "Type '{0}' does not have a serialization constructor", t ) );
							}
						}

						itemCount = idxReader.ReadInt32();

						m_Items = new Dictionary<Serial, Item>( itemCount );

						for ( int i = 0; i < itemCount; ++i ) {
							int typeID = idxReader.ReadInt32();
							int serial = idxReader.ReadInt32();
							long pos = idxReader.ReadInt64();
							int length = idxReader.ReadInt32();

							object[] objs = ( object[] ) types[typeID];

							if ( objs == null )
								continue;

							Item item = null;
							ConstructorInfo ctor = ( ConstructorInfo ) objs[0];
							string typeName = ( string ) objs[1];

							try {
								ctorArgs[0] = ( Serial ) serial;
								item = ( Item ) ( ctor.Invoke( ctorArgs ) );
							} catch {
							}

							if ( item != null ) {
								items.Add( new ItemEntry( item, typeID, typeName, pos, length ) );
								AddItem( item );
							}
						}

						tdbReader.Close();
					}

					idxReader.Close();
				}
			} else {
				m_Items = new Dictionary<Serial, Item>();
			}

			if ( File.Exists( GuildIndexPath ) ) {
				using ( FileStream idx = new FileStream( GuildIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) {
					BinaryReader idxReader = new BinaryReader( idx );

					guildCount = idxReader.ReadInt32();

					CreateGuildEventArgs createEventArgs = new CreateGuildEventArgs( -1 );
					for ( int i = 0; i < guildCount; ++i ) {
						idxReader.ReadInt32();//no typeid for guilds
						int id = idxReader.ReadInt32();
						long pos = idxReader.ReadInt64();
						int length = idxReader.ReadInt32();

						createEventArgs.Id = id;
						BaseGuild guild = EventSink.InvokeCreateGuild( createEventArgs );
						if ( guild != null )
							guilds.Add( new GuildEntry( guild, pos, length ) );
					}

					idxReader.Close();
				}
			}

			bool failedMobiles = false, failedItems = false, failedGuilds = false;
			Type failedType = null;
			Serial failedSerial = Serial.Zero;
			Exception failed = null;
			int failedTypeID = 0;

			if ( File.Exists( MobileDataPath ) ) {
				using ( FileStream bin = new FileStream( MobileDataPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) {
					BinaryFileReader reader = new BinaryFileReader( new BinaryReader( bin ) );

					for ( int i = 0; i < mobiles.Count; ++i ) {
						MobileEntry entry = mobiles[i];
						Mobile m = entry.Mobile;

						if ( m != null ) {
							reader.Seek( entry.Position, SeekOrigin.Begin );

							try {
								m_LoadingType = entry.TypeName;
								m.Deserialize( reader );

								if ( reader.Position != ( entry.Position + entry.Length ) )
									throw new Exception( String.Format( "***** Bad serialize on {0} *****", m.GetType() ) );
							} catch ( Exception e ) {
								mobiles.RemoveAt( i );

								failed = e;
								failedMobiles = true;
								failedType = m.GetType();
								failedTypeID = entry.TypeID;
								failedSerial = m.Serial;

								break;
							}
						}
					}

					reader.Close();
				}
			}

			if ( !failedMobiles && File.Exists( ItemDataPath ) ) {
				using ( FileStream bin = new FileStream( ItemDataPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) {
					BinaryFileReader reader = new BinaryFileReader( new BinaryReader( bin ) );

					for ( int i = 0; i < items.Count; ++i ) {
						ItemEntry entry = items[i];
						Item item = entry.Item;

						if ( item != null ) {
							reader.Seek( entry.Position, SeekOrigin.Begin );

							try {
								m_LoadingType = entry.TypeName;
								item.Deserialize( reader );

								if ( reader.Position != ( entry.Position + entry.Length ) )
									throw new Exception( String.Format( "***** Bad serialize on {0} *****", item.GetType() ) );
							} catch ( Exception e ) {
								items.RemoveAt( i );

								failed = e;
								failedItems = true;
								failedType = item.GetType();
								failedTypeID = entry.TypeID;
								failedSerial = item.Serial;

								break;
							}
						}
					}

					reader.Close();
				}
			}

			m_LoadingType = null;

			if ( !failedMobiles && !failedItems && File.Exists( GuildDataPath ) ) {
				using ( FileStream bin = new FileStream( GuildDataPath, FileMode.Open, FileAccess.Read, FileShare.Read ) ) {
					BinaryFileReader reader = new BinaryFileReader( new BinaryReader( bin ) );

					for ( int i = 0; i < guilds.Count; ++i ) {
						GuildEntry entry = guilds[i];
						BaseGuild g = entry.Guild;

						if ( g != null ) {
							reader.Seek( entry.Position, SeekOrigin.Begin );

							try {
								g.Deserialize( reader );

								if ( reader.Position != ( entry.Position + entry.Length ) )
									throw new Exception( String.Format( "***** Bad serialize on Guild {0} *****", g.Id ) );
							} catch ( Exception e ) {
								guilds.RemoveAt( i );

								failed = e;
								failedGuilds = true;
								failedType = typeof( BaseGuild );
								failedTypeID = g.Id;
								failedSerial = g.Id;

								break;
							}
						}
					}

					reader.Close();
				}
			}

			if ( failedItems || failedMobiles || failedGuilds ) {
				Console.WriteLine( "An error was encountered while loading a saved object" );

				Console.WriteLine( " - Type: {0}", failedType );
				Console.WriteLine( " - Serial: {0}", failedSerial );

				if ( !Core.Service ) {
					Console.WriteLine( "Delete the object? (y/n)" );

					if ( Console.ReadKey( true ).Key == ConsoleKey.Y ) {
						if ( failedType != typeof( BaseGuild ) ) {
							Console.WriteLine( "Delete all objects of that type? (y/n)" );

							if ( Console.ReadKey( true ).Key == ConsoleKey.Y ) {
								if ( failedMobiles ) {
									for ( int i = 0; i < mobiles.Count; ) {
										if ( mobiles[i].TypeID == failedTypeID )
											mobiles.RemoveAt( i );
										else
											++i;
									}
								} else if ( failedItems ) {
									for ( int i = 0; i < items.Count; ) {
										if ( items[i].TypeID == failedTypeID )
											items.RemoveAt( i );
										else
											++i;
									}
								}
							}
						}

						SaveIndex<MobileEntry>( mobiles, MobileIndexPath );
						SaveIndex<ItemEntry>( items, ItemIndexPath );
						SaveIndex<GuildEntry>( guilds, GuildIndexPath );
					}

					Console.WriteLine( "After pressing return an exception will be thrown and the server will terminate." );
					Console.ReadLine();
				} else {
					Console.WriteLine( "An exception will be thrown and the server will terminate." );
				}

				throw new Exception( String.Format( "Load failed (items={0}, mobiles={1}, guilds={2}, type={3}, serial={4})", failedItems, failedMobiles, failedGuilds, failedType, failedSerial ), failed );
			}

			EventSink.InvokeWorldLoad();

			m_Loading = false;

			ProcessSafetyQueues();

			foreach ( Item item in m_Items.Values ) {
				if ( item.Parent == null )
					item.UpdateTotals();

				item.ClearProperties();
			}

			foreach ( Mobile m in m_Mobiles.Values ) {
				m.UpdateRegion(); // Is this really needed?
				m.UpdateTotals();

				m.ClearProperties();
			}

			watch.Stop();

			Console.WriteLine( "done ({1} items, {2} mobiles) ({0:F2} seconds)", watch.Elapsed.TotalSeconds, m_Items.Count, m_Mobiles.Count );
		}
Exemple #14
0
		static VitaNexCore()
		{
			_INITVersion = "3.0.0.0";

			_INITQueue = new Queue<Tuple<string, string>>();
			_INITHandlers = new Dictionary<string, Action<string>>();

			var basePath = IOUtility.GetSafeDirectoryPath(Core.BaseDirectory + "/VitaNexCore");

			if (!Directory.Exists(basePath))
			{
				FirstBoot = true;
			}

			BaseDirectory = IOUtility.EnsureDirectory(basePath);

			var first = IOUtility.GetSafeFilePath(BaseDirectory + "/FirstBoot.vnc", true);

			if (!File.Exists(first))
			{
				FirstBoot = true;

				IOUtility.EnsureFile(first)
						 .AppendText(
							 true,
							 "This file serves no other purpose than to identify if",
							 "the software has been initialized for the first time. ",
							 "To re-initialize 'First-Boot' mode, simply delete this",
							 "file before starting the application.");
			}

			var root = FindRootDirectory(Core.BaseDirectory + "/Scripts/VitaNex");

			if (root != null && root.Exists)
			{
				RootDirectory = root;

				ParseVersion();
				ParseINIT();

				RegisterINITHandler(
					"ROOT_DIR",
					path =>
					{
						root = FindRootDirectory(path);

						if (root == null || !root.Exists)
						{
							return;
						}

						RootDirectory = root;

						ParseVersion();
					});
			}

			BackupExpireAge = TimeSpan.FromDays(7);

			RegisterINITHandler(
				"BACKUP_EXPIRE",
				time =>
				{
					TimeSpan ts;

					if (TimeSpan.TryParse(time, out ts))
					{
						BackupExpireAge = ts;
					}
				});
		}
Exemple #15
0
		public void QueuePoll( ShardPoller poller )
		{
			if ( m_Polls == null )
				m_Polls = new Queue<ShardPoller>( 4 );

			m_Polls.Enqueue( poller );
		}
        public ClientObject(Socket _socket, int id)
        {
            this.closed = false;

            this.clientSocket = _socket;

            this.networkstream = new NetworkStream(this.clientSocket);
            this.sr = new StreamReader(this.networkstream);
            this.sw = new StreamWriter(this.networkstream);

            this.id = id;

            this.sw.WriteLine(@"/id " + this.id.ToString());
            this.sw.Flush();

            this.clientCommands = new Queue<string>();

            var _thread = new Thread(() =>
            {
                try
                {
                    string temp;

                    while (!this.closed)
                    {
                        lock (this.sr)
                            temp = this.sr.ReadLine();

                        lock (this.clientCommands)
                            this.clientCommands.Enqueue(temp);

                        temp = string.Empty;
                    }
                }
                catch (Exception)
                {
                    this.closed = true;
                }
            });
            _thread.Name = "ClientThread_" + id;
            _thread.Start();
        }
Exemple #17
0
        public static void Load()
        {
            if (Loaded)
            {
                return;
            }

            Loaded      = true;
            LoadingType = null;

            Utility.PushColor(ConsoleColor.Yellow);
            Console.WriteLine("World: Loading...");
            Utility.PopColor();

            Stopwatch watch = Stopwatch.StartNew();

            Loading = true;

            _addQueue    = new Queue <IEntity>();
            _deleteQueue = new Queue <IEntity>();

            object[] ctorArgs = new object[1];

            List <ItemEntry>   items   = new List <ItemEntry>();
            List <MobileEntry> mobiles = new List <MobileEntry>();
            List <GuildEntry>  guilds  = new List <GuildEntry>();

            if (File.Exists(MobileIndexPath) && File.Exists(MobileTypesPath))
            {
                using (FileStream idx = new FileStream(MobileIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    BinaryReader idxReader = new BinaryReader(idx);

                    using (FileStream tdb = new FileStream(MobileTypesPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        BinaryReader tdbReader = new BinaryReader(tdb);

                        List <Tuple <ConstructorInfo, string> > types = ReadTypes(tdbReader);

                        int mobileCount = idxReader.ReadInt32();

                        Mobiles = new Dictionary <Serial, Mobile>(mobileCount);

                        for (int i = 0; i < mobileCount; ++i)
                        {
                            int  typeID = idxReader.ReadInt32();
                            int  serial = idxReader.ReadInt32();
                            long pos    = idxReader.ReadInt64();
                            int  length = idxReader.ReadInt32();

                            Tuple <ConstructorInfo, string> objs = types[typeID];

                            if (objs == null)
                            {
                                continue;
                            }

                            Mobile          m        = null;
                            ConstructorInfo ctor     = objs.Item1;
                            string          typeName = objs.Item2;

                            try
                            {
                                ctorArgs[0] = (Serial)serial;
                                m           = (Mobile)ctor.Invoke(ctorArgs);
                            }
                            catch (Exception ex)
                            {
                                Diagnostics.ExceptionLogging.LogException(ex);
                            }

                            if (m != null)
                            {
                                mobiles.Add(new MobileEntry(m, typeID, typeName, pos, length));
                                AddMobile(m);
                            }
                        }

                        tdbReader.Close();
                    }

                    idxReader.Close();
                }
            }
            else
            {
                Mobiles = new Dictionary <Serial, Mobile>();
            }

            if (File.Exists(ItemIndexPath) && File.Exists(ItemTypesPath))
            {
                using (FileStream idx = new FileStream(ItemIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    BinaryReader idxReader = new BinaryReader(idx);

                    using (FileStream tdb = new FileStream(ItemTypesPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        BinaryReader tdbReader = new BinaryReader(tdb);

                        List <Tuple <ConstructorInfo, string> > types = ReadTypes(tdbReader);

                        int itemCount = idxReader.ReadInt32();

                        Items = new Dictionary <Serial, Item>(itemCount);

                        for (int i = 0; i < itemCount; ++i)
                        {
                            int  typeID = idxReader.ReadInt32();
                            int  serial = idxReader.ReadInt32();
                            long pos    = idxReader.ReadInt64();
                            int  length = idxReader.ReadInt32();

                            Tuple <ConstructorInfo, string> objs = types[typeID];

                            if (objs == null)
                            {
                                continue;
                            }

                            Item            item     = null;
                            ConstructorInfo ctor     = objs.Item1;
                            string          typeName = objs.Item2;

                            try
                            {
                                ctorArgs[0] = (Serial)serial;
                                item        = (Item)ctor.Invoke(ctorArgs);
                            }
                            catch (Exception e)
                            {
                                Diagnostics.ExceptionLogging.LogException(e);
                            }

                            if (item != null)
                            {
                                items.Add(new ItemEntry(item, typeID, typeName, pos, length));
                                AddItem(item);
                            }
                        }

                        tdbReader.Close();
                    }

                    idxReader.Close();
                }
            }
            else
            {
                Items = new Dictionary <Serial, Item>();
            }

            if (File.Exists(GuildIndexPath))
            {
                using (FileStream idx = new FileStream(GuildIndexPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    BinaryReader idxReader = new BinaryReader(idx);

                    int guildCount = idxReader.ReadInt32();

                    CreateGuildEventArgs createEventArgs = new CreateGuildEventArgs(-1);

                    for (int i = 0; i < guildCount; ++i)
                    {
                        idxReader.ReadInt32();                         //no typeid for guilds

                        int  id     = idxReader.ReadInt32();
                        long pos    = idxReader.ReadInt64();
                        int  length = idxReader.ReadInt32();

                        createEventArgs.Id = id;

                        EventSink.InvokeCreateGuild(createEventArgs);

                        BaseGuild guild = createEventArgs.Guild;

                        if (guild != null)
                        {
                            guilds.Add(new GuildEntry(guild, pos, length));
                        }
                    }

                    idxReader.Close();
                }
            }

            bool      failedMobiles = false, failedItems = false, failedGuilds = false;
            Type      failedType   = null;
            Serial    failedSerial = Serial.Zero;
            Exception failed       = null;
            int       failedTypeID = 0;

            if (File.Exists(MobileDataPath))
            {
                using (FileStream bin = new FileStream(MobileDataPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin));

                    for (int i = 0; i < mobiles.Count; ++i)
                    {
                        MobileEntry entry = mobiles[i];
                        Mobile      m     = entry.Mobile;

                        if (m != null)
                        {
                            reader.Seek(entry.Position, SeekOrigin.Begin);

                            try
                            {
                                LoadingType = entry.TypeName;

                                m.Deserialize(reader);

                                if (reader.Position != (entry.Position + entry.Length))
                                {
                                    throw new Exception(string.Format("***** Bad serialize on {0} *****", m.GetType()));
                                }
                            }
                            catch (Exception e)
                            {
                                mobiles.RemoveAt(i);

                                failed        = e;
                                failedMobiles = true;
                                failedType    = m.GetType();
                                failedTypeID  = entry.TypeID;
                                failedSerial  = m.Serial;

                                break;
                            }
                        }
                    }

                    reader.Close();
                }
            }

            if (!failedMobiles && File.Exists(ItemDataPath))
            {
                using (FileStream bin = new FileStream(ItemDataPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin));

                    for (int i = 0; i < items.Count; ++i)
                    {
                        ItemEntry entry = items[i];
                        Item      item  = entry.Item;

                        if (item != null)
                        {
                            reader.Seek(entry.Position, SeekOrigin.Begin);

                            try
                            {
                                LoadingType = entry.TypeName;

                                item.Deserialize(reader);

                                if (reader.Position != (entry.Position + entry.Length))
                                {
                                    throw new Exception(string.Format("***** Bad serialize on {0} *****", item.GetType()));
                                }
                            }
                            catch (Exception e)
                            {
                                items.RemoveAt(i);

                                failed       = e;
                                failedItems  = true;
                                failedType   = item.GetType();
                                failedTypeID = entry.TypeID;
                                failedSerial = item.Serial;

                                break;
                            }
                        }
                    }

                    reader.Close();
                }
            }

            LoadingType = null;

            if (!failedMobiles && !failedItems && File.Exists(GuildDataPath))
            {
                using (FileStream bin = new FileStream(GuildDataPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    BinaryFileReader reader = new BinaryFileReader(new BinaryReader(bin));

                    for (int i = 0; i < guilds.Count; ++i)
                    {
                        GuildEntry entry = guilds[i];
                        BaseGuild  g     = entry.Guild;

                        if (g != null)
                        {
                            reader.Seek(entry.Position, SeekOrigin.Begin);

                            try
                            {
                                g.Deserialize(reader);

                                if (reader.Position != (entry.Position + entry.Length))
                                {
                                    throw new Exception(string.Format("***** Bad serialize on Guild {0} *****", g.Id));
                                }
                            }
                            catch (Exception e)
                            {
                                guilds.RemoveAt(i);

                                failed       = e;
                                failedGuilds = true;
                                failedType   = typeof(BaseGuild);
                                failedTypeID = g.Id;
                                failedSerial = g.Id;

                                break;
                            }
                        }
                    }

                    reader.Close();
                }
            }

            if (failedItems || failedMobiles || failedGuilds)
            {
                Utility.PushColor(ConsoleColor.Red);
                Console.WriteLine("An error was encountered while loading a saved object");
                Utility.PopColor();

                Console.WriteLine(" - Type: {0}", failedType);
                Console.WriteLine(" - Serial: {0}", failedSerial);

                if (!Core.Service)
                {
                    Console.WriteLine("Delete the object? (y/n)");

                    if (Console.ReadKey(true).Key == ConsoleKey.Y)
                    {
                        if (failedType != typeof(BaseGuild))
                        {
                            Console.WriteLine("Delete all objects of that type? (y/n)");

                            if (Console.ReadKey(true).Key == ConsoleKey.Y)
                            {
                                if (failedMobiles)
                                {
                                    for (int i = 0; i < mobiles.Count;)
                                    {
                                        if (mobiles[i].TypeID == failedTypeID)
                                        {
                                            mobiles.RemoveAt(i);
                                        }
                                        else
                                        {
                                            ++i;
                                        }
                                    }
                                }
                                else if (failedItems)
                                {
                                    for (int i = 0; i < items.Count;)
                                    {
                                        if (items[i].TypeID == failedTypeID)
                                        {
                                            items.RemoveAt(i);
                                        }
                                        else
                                        {
                                            ++i;
                                        }
                                    }
                                }
                            }
                        }

                        SaveIndex(mobiles, MobileIndexPath);
                        SaveIndex(items, ItemIndexPath);
                        SaveIndex(guilds, GuildIndexPath);
                    }

                    Console.WriteLine("After pressing return an exception will be thrown and the server will terminate.");
                    Console.ReadLine();
                }
                else
                {
                    Utility.PushColor(ConsoleColor.Red);
                    Console.WriteLine("An exception will be thrown and the server will terminate.");
                    Utility.PopColor();
                }

                throw new Exception(
                          string.Format(
                              "Load failed (items={0}, mobiles={1}, guilds={2}, type={3}, serial={4})",
                              failedItems,
                              failedMobiles,
                              failedGuilds,
                              failedType,
                              failedSerial),
                          failed);
            }

            EventSink.InvokeWorldLoad();

            Loading = false;

            ProcessSafetyQueues();

            foreach (Item item in Items.Values)
            {
                if (item.Parent == null)
                {
                    item.UpdateTotals();
                }

                item.ClearProperties();
            }

            foreach (Mobile m in Mobiles.Values)
            {
                m.UpdateRegion();                 // Is this really needed?
                m.UpdateTotals();

                m.ClearProperties();
            }

            watch.Stop();

            Utility.PushColor(ConsoleColor.Green);
            Console.WriteLine(
                "...done ({1} items, {2} mobiles) ({0:F2} seconds)",
                watch.Elapsed.TotalSeconds,
                Items.Count,
                Mobiles.Count);
            Utility.PopColor();
        }
Exemple #18
0
 public User(string login, string auth)
 {
     this.Auth = auth;
     this.Login = login;
     this.messages = new Queue<string>();
 }
Exemple #19
0
 public TimerScheduler( Queue<Timer> queue )
 {
     m_Queue = queue;
     m_ChangeQueue = new Queue<TimerChangeEntry>();
 }
Exemple #20
0
		public ShardPollGump( Mobile from, ShardPoller poller, bool editing, Queue<ShardPoller> polls ) : base( 50, 50 )
		{
			m_From = from;
			m_Poller = poller;
			m_Editing = editing;
			m_Polls = polls;

			Closable = false;

			AddPage( 0 );

			int totalVotes = 0;
			int totalOptionHeight = 0;

			for ( int i = 0; i < poller.Options.Length; ++i )
			{
				totalVotes += poller.Options[i].Votes;
				totalOptionHeight += poller.Options[i].ComputeHeight() + 5;
			}

			bool isViewingResults = editing && poller.Active;
			bool isCompleted = totalVotes > 0 && !poller.Active;

			if ( editing && !isViewingResults )
				totalOptionHeight += 35;

			int height = 115 + totalOptionHeight;

			AddBackground( 1, 1, 398, height - 2, 3600 );
			AddAlphaRegion( 16, 15, 369, height - 31 );

			AddItem( 308, 30, 0x1E5E );

			string title;

			if ( editing )
				title = ( isCompleted ? "Poll Completed" : "Poll Editor" );
			else
				title = "Shard Poll";

			AddHtml( 22, 22, 294, 20, Color( Center( title ), LabelColor32 ), false, false );

			if ( editing )
			{
				AddHtml( 22, 22, 294, 20, Color( String.Format( "{0} total", totalVotes ), LabelColor32 ), false, false );
				AddButton( 287, 23, 0x2622, 0x2623, 2, GumpButtonType.Reply, 0 );
			}

			AddHtml( 22, 50, 294, 40, Color( poller.Title, 0x99CC66 ), false, false );

			AddImageTiled( 32, 88, 264, 1, 9107 );
			AddImageTiled( 42, 90, 264, 1, 9157 );

			int y = 100;

			for ( int i = 0; i < poller.Options.Length; ++i )
			{
				ShardPollOption option = poller.Options[i];
				string text = option.Title;

				if ( editing && totalVotes > 0 )
				{
					double perc = option.Votes / (double)totalVotes;

					text = String.Format( "[{1}: {2}%] {0}", text, option.Votes, (int)(perc*100) );
				}

				int optHeight = option.ComputeHeight();

				y += optHeight/2;

				if ( isViewingResults )
					AddImage( 24, y - 15, 0x25FE );
				else
					AddRadio( 24, y - 15, 0x25F9, 0x25FC, false, 1 + i );

				AddHtml( 60, y - (9 * option.LineBreaks), 250, 18 * option.LineBreaks, Color( text, LabelColor32 ), false, false );

				y += optHeight/2;
				y += 5;
			}

			if ( editing && !isViewingResults )
			{
				AddRadio( 24, y + 15 - 15, 0x25F9, 0x25FC, false, 1 + poller.Options.Length );
				AddHtml( 60, y + 15 - 9, 250, 18, Color( "Create new option.", 0x99CC66 ), false, false );
			}

			AddButton( 314, height - 73, 247, 248, 1, GumpButtonType.Reply, 0 );
			AddButton( 314, height - 47, 242, 241, 0, GumpButtonType.Reply, 0 );
		}
Exemple #21
0
        public static void Run()
        {
            EventSink.Instance = new EventSink();

            if ( !ScriptCompiler.Compile( Environment.Debug ) )
            {
                Console.WriteLine( "Fatal: Compilation failed. Press any key to exit." );
                Console.ReadLine();
                return;
            }

            ScriptCompiler.VerifyLibraries();

            // This instance is shared among timer scheduler and timer executor,
            // and accessed from both core & timer threads.
            Queue<Timer> timerQueue = new Queue<Timer>();

            // Timer scheduler must be set up before world load, since world load
            // could schedule timers on entity deserialization.
            var timerScheduler = TimerScheduler.Instance = new TimerScheduler( timerQueue );
            m_TimerThread = new TimerThread( timerScheduler );

            TimerExecutor timerExecutor = new TimerExecutor( timerQueue );

            PacketHandlers.Instance = new PacketHandlers();

            try
            {
                ScriptCompiler.Configure();

                TileData.Configure();
            }
            catch ( TargetInvocationException e )
            {
                Console.WriteLine( "Fatal: Configure exception: {0}", e.InnerException );
                return;
            }

            Environment.SaveConfig();

            Region.Load();
            World.Instance.Load();

            try
            {
                ScriptCompiler.Initialize();
            }
            catch ( TargetInvocationException e )
            {
                Logger.Error( "Initialize exception: {0}", e.InnerException );
                return;
            }

            m_TimerThread.Start();

            NetServer netServer = new NetServer( new Listener( Listener.Port ) );
            netServer.Initialize();

            GameServer.Instance = new GameServer( netServer, PacketHandlers.Instance );
            GameServer.Instance.Initialize();

            EventSink.Instance.InvokeServerStarted();

            PacketDispatcher.Initialize();

            m_Now = DateTime.UtcNow;
            m_TotalProfile = new MainProfile( m_Now );
            m_CurrentProfile = new MainProfile( m_Now );

            try
            {
                while ( !m_Closing )
                {
                    m_Now = DateTime.UtcNow;

                    Thread.Sleep( 1 );

                    ClockProfile( MainProfile.TimerId.Idle );

                    Mobile.ProcessDeltaQueue();

                    ClockProfile( MainProfile.TimerId.MobileDelta );

                    Item.ProcessDeltaQueue();

                    ClockProfile( MainProfile.TimerId.ItemDelta );

                    timerExecutor.Slice();

                    ClockProfile( MainProfile.TimerId.Timers );

                    netServer.Slice();

                    ClockProfile( MainProfile.TimerId.Network );

                    // Done with this iteration.
                    m_TotalProfile.Next();
                    m_CurrentProfile.Next();
                }
            }
            catch ( Exception e )
            {
                HandleCrashed( e );
            }

            m_TimerThread.Stop();
        }
Exemple #22
0
 public StandardSaveStrategy()
 {
     _decayQueue = new Queue<Item>();
 }
		public bool AddRunebook(Mobile m, Runebook book, bool message)
		{
			if (m == null || m.Deleted || book == null || book.Deleted)
			{
				return false;
			}

			bool mrb = Insensitive.Equals(book.GetType().Name, "InternalRunebook");

			if (book.Entries.Count == 0)
			{
				if (!mrb && message)
				{
					m.SendMessage("That rune book is empty.");
				}

				return false;
			}

			if (Entries.Count >= Entries.Capacity)
			{
				if (!mrb && message)
				{
					m.SendMessage("The category \"{0}\" can't hold more runes.", _Name);
				}

				return false;
			}

			if (Entries.Count + book.Entries.Count > Entries.Capacity)
			{
				if (!mrb && message)
				{
					m.SendMessage("That rune book won't fit in the category \"{0}\".", _Name);
				}

				return false;
			}

			var bEntries = new Queue<RunebookEntry>(book.Entries);

			Entries.ForEach(
				(e, x, y) =>
				{
					if (e != null || bEntries.Count <= 0)
					{
						return;
					}

					var be = bEntries.Dequeue();

					Entries.SetContent(x, y, new RuneCodexEntry(book.Name, be.Description, be.Location.ToMapPoint(be.Map)));
				});

			if (mrb)
			{
				book.Entries.Clear();
				return true;
			}

			book.Delete();

			if (message)
			{
				m.SendMessage("You add the rune book to the category \"{0}\".", _Name);
			}

			return true;
		}