public void SetUp()
 {
     _sceneFactory = Substitute.For <ISceneFactory>();
     _sceneFactory.Create().Returns(ci => TestSceneFactory.Create());
     _sceneSerializer         = Substitute.For <ISceneSerializer>();
     _createEmptySceneService = new CreateEmptySceneService(_sceneFactory, _sceneSerializer);
 }
Example #2
0
        public void Start(string sceneName)
        {
            if (!_initialized)
            {
                _pendingScene = sceneName;
                return;
            }

            if (_sceneFactory == null)
            {
                _sceneFactory = Game.Services.GetService <ISceneFactory>();
                if (_sceneFactory == null)
                {
                    throw new Exception("an ISceneComposer service provider is required");
                }
            }

            _outgoingScene = ActiveScene;
            var scene   = _sceneFactory.Create(sceneName);
            var context = new Context(
                scene,
                this,
                _physicsManager,
                _inputManager,
                new ContentManager(Game.Content.ServiceProvider, Game.Content.RootDirectory),
                Game.GraphicsDevice);

            scene.Activate(context);
            ActiveScene = scene;
            SceneActivated?.Invoke(this, new SceneActivatedEventArgs()
            {
                Scene = scene
            });
        }
Example #3
0
 public EngineConfig(
     ISceneFactory sceneFactory,
     IEnumerable <Control> controls)
 {
     SceneFactory = sceneFactory;
     Controls     = controls.ToDictionary((ks) => ks.Name);
 }
Example #4
0
        public bool Start(Simian simian)
        {
            m_simian      = simian;
            m_httpServer  = simian.GetAppModule <IHttpServer>();
            m_assetClient = simian.GetAppModule <IAssetClient>();

            m_sceneFactory = simian.GetAppModule <ISceneFactory>();
            if (m_sceneFactory != null)
            {
                m_sceneFactory.OnSceneStart += SceneStartHandler;
                m_sceneFactory.OnSceneStop  += SceneStopHandler;
            }

            IConfigSource source = simian.Config;

            IConfig config = source.Configs["SimianGrid"];

            if (config != null)
            {
                m_serverUrl = config.GetString("GridService", null);
            }

            if (String.IsNullOrEmpty(m_serverUrl))
            {
                m_log.Error("[SimianGrid] config section is missing the GridService URL");
                return(false);
            }

            return(true);
        }
 public SceneSerializer(ISceneFactory sceneFactory, ISceneBehaviorFactoryProvider sceneBehaviorFactoryProvider,
                        IComponentFactoryProvider componentFactoryProvider, IAssetStore assetStore)
 {
     _sceneFactory = sceneFactory;
     _sceneBehaviorFactoryProvider = sceneBehaviorFactoryProvider;
     _componentFactoryProvider     = componentFactoryProvider;
     _assetStore = assetStore;
 }
 public void SetUp()
 {
     _assetStore   = Substitute.For <IAssetStore>();
     _sceneLoader  = Substitute.For <ISceneLoader>();
     _sceneFactory = Substitute.For <ISceneFactory>();
     _sceneBehaviorFactoryProvider = Substitute.For <ISceneBehaviorFactoryProvider>();
     _sceneBehaviorFactoryProvider.Get(Arg.Any <string>()).ThrowsForAnyArgs(new InvalidOperationException("Missing substitute configuration."));
     _sceneManager = new SceneManager(_assetStore, _sceneLoader, _sceneFactory, _sceneBehaviorFactoryProvider);
 }
Example #7
0
        public SceneManager(IAssetStore assetStore, ISceneLoader sceneLoader, ISceneFactory sceneFactory,
                            ISceneBehaviorFactoryProvider sceneBehaviorFactoryProvider)
        {
            _assetStore   = assetStore;
            _sceneLoader  = sceneLoader;
            _sceneFactory = sceneFactory;
            _sceneBehaviorFactoryProvider = sceneBehaviorFactoryProvider;

            _sceneLoadRequest.MarkAsHandled();
        }
Example #8
0
 public Game(IConfigurationManager configurationManager, IInputManager inputManager, IContentManager contentManager, IRenderer renderer, ISceneManager sceneManager, ISceneFactory sceneFactory) : base("iLogical",
                                                                                                                                                                                                        "GameCore")
 {
     _configurationManager = configurationManager;
     _inputManager         = inputManager;
     _contentManager       = contentManager;
     _renderer             = renderer;
     _sceneManager         = sceneManager;
     _sceneFactory         = sceneFactory;
 }
Example #9
0
        public override void Initialize()
        {
            base.Initialize();
            this._sceneFactory   = Game.Services.GetService <ISceneFactory>();
            this._physicsManager = Game.Services.GetService <IPhysicsManager>();
            this._inputManager   = Game.Services.GetService <IInputManager>();
            _initialized         = true;

            if (_pendingScene != null)
            {
                var sceneName = _pendingScene;
                _pendingScene = null;
                Start(sceneName);
            }
        }
Example #10
0
        public void LoadSceneFromModule(Module.Module module, string sceneRef)
        {
            try
            {
                XDocument doc = XDocument.Parse(module.GetFileXML(sceneRef, ResourceType.Scene));

                XElement root     = doc.Element("Scene");
                string   typeName = root.Attribute("Type").Value;

                ISceneFactory fac = OrionEngine.Instance.GetFactoryFor <ISceneFactory>(typeName);
                CurrentScene = fac.GetScene(typeName, OrionEngine.Instance, module, root);
            }
            catch (Exception)
            {
                LogManager.Instance.LogError("Error loading scene from module.");
            }
        }
        public void SetUp()
        {
            _sceneFactory = Substitute.For <ISceneFactory>();
            _sceneFactory.Create().Returns(ci => TestSceneFactory.Create());

            _sceneBehaviorFactoryProvider = Substitute.For <ISceneBehaviorFactoryProvider>();
            var emptySceneBehaviorFactory = Substitute.For <ISceneBehaviorFactory>();

            emptySceneBehaviorFactory.BehaviorName.Returns(string.Empty);
            emptySceneBehaviorFactory.Create(Arg.Any <Scene>())
            .Returns(ci => SceneBehavior.CreateEmpty(ci.Arg <Scene>()));
            _sceneBehaviorFactoryProvider.Get(string.Empty).Returns(emptySceneBehaviorFactory);

            _componentFactoryProvider = Substitute.For <IComponentFactoryProvider>();
            _assetStore = Substitute.For <IAssetStore>();

            _sceneSerializer = new SceneSerializer(_sceneFactory, _sceneBehaviorFactoryProvider, _componentFactoryProvider, _assetStore);
        }
Example #12
0
        public bool Start(Simian simian)
        {
            m_simian = simian;

            m_httpServer = simian.GetAppModule <IHttpServer>();
            if (m_httpServer == null)
            {
                m_log.Error("StandaloneGridClient requires an IHttpServer");
                return(false);
            }

            m_sceneFactory = simian.GetAppModule <ISceneFactory>();
            if (m_sceneFactory == null)
            {
                m_log.Error("StandaloneGridClient requires an ISceneFactory");
                return(false);
            }

            m_assetClient = simian.GetAppModule <IAssetClient>();

            return(true);
        }
Example #13
0
        protected override void OnLoad(EventArgs e)
        {
            using (ILifetimeScope scope = lifetimeScope.BeginLifetimeScope())
            {
                ISceneFactory sceneFactory = scope.Resolve <ISceneFactory>();

                ClientModel client;
                using (StreamReader sr = new StreamReader(Path.Combine(Directory.GetCurrentDirectory(), "Json", "model.json")))
                {
                    client = JsonConvert.DeserializeObject <ClientModel>(sr.ReadToEnd());
                }

                scene = sceneFactory.CreateScene(client.Scene);

                GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f);
                GL.Enable(EnableCap.Texture2D);
                GL.Disable(EnableCap.DepthTest);
                GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);

                renderService.Initialise();
            }

            base.OnLoad(e);
        }
Example #14
0
        public void Start(IScene scene)
        {
            m_scene = scene;
            m_lastCameraPositions = new Dictionary<uint, Vector3>();
            m_borderCrossThrottles = new Dictionary<UUID, int>();

            // Create an AABB for this scene that extends beyond the borders by BORDER_CROSS_THRESHOLD
            // that is used to check for border crossings
            m_borderCrossAABB = new AABB(Vector3.Zero, new Vector3(scene.MaxPosition - scene.MinPosition));
            m_borderCrossAABB.Min -= new Vector3(BORDER_CROSS_THRESHOLD, BORDER_CROSS_THRESHOLD, BORDER_CROSS_THRESHOLD);
            m_borderCrossAABB.Max += new Vector3(BORDER_CROSS_THRESHOLD, BORDER_CROSS_THRESHOLD, BORDER_CROSS_THRESHOLD);

            m_scheduler = m_scene.Simian.GetAppModule<IScheduler>();
            if (m_scheduler == null)
            {
                m_log.Warn("Neighbors requires an IScheduler");
                return;
            }

            m_httpServer = m_scene.Simian.GetAppModule<IHttpServer>();
            if (m_httpServer == null)
            {
                m_log.Warn("Neighbors requires an IHttpServer");
                return;
            }

            m_udp = m_scene.GetSceneModule<LLUDP>();
            if (m_udp == null)
            {
                m_log.Warn("Neighbors requires an LLUDP");
                return;
            }

            m_userClient = m_scene.Simian.GetAppModule<IUserClient>();
            if (m_userClient == null)
            {
                m_log.Warn("Neighbors requires an IUserClient");
                return;
            }

            m_gridClient = scene.Simian.GetAppModule<IGridClient>();

            // Add neighbor messaging handlers
            string urlFriendlySceneName = WebUtil.UrlEncode(scene.Name);
            string regionPath = "/regions/" + urlFriendlySceneName;
            m_httpServer.AddHandler("POST", null, regionPath + "/region/online", true, true, RegionOnlineHandler);
            m_httpServer.AddHandler("POST", null, regionPath + "/region/offline", true, true, RegionOfflineHandler);
            m_httpServer.AddHandler("POST", null, regionPath + "/child_avatar/update", true, true, ChildAvatarUpdateHandler);

            m_scene.AddPublicCapability("region/online", m_httpServer.HttpAddress.Combine(regionPath + "/region/online"));
            m_scene.AddPublicCapability("region/offline", m_httpServer.HttpAddress.Combine(regionPath + "/region/offline"));
            m_scene.AddPublicCapability("child_avatar/update", m_httpServer.HttpAddress.Combine(regionPath + "/child_avatar/update"));

            // Track local scenes going up and down
            m_sceneFactory = scene.Simian.GetAppModule<ISceneFactory>();
            if (m_sceneFactory != null)
            {
                m_sceneFactory.OnSceneStart += SceneStartHandler;
                m_sceneFactory.OnSceneStop += SceneStopHandler;
            }

            m_scene.OnPresenceAdd += PresenceAddHandler;
            m_scene.OnEntityAddOrUpdate += EntityAddOrUpdateHandler;

            m_childUpdates = new ThrottledQueue<uint, IScenePresence>(5.0f, 200, true, SendChildUpdate);
            m_childUpdates.Start();
        }
Example #15
0
        public void Start(IScene scene)
        {
            m_scene = scene;
            m_lastCameraPositions  = new Dictionary <uint, Vector3>();
            m_borderCrossThrottles = new Dictionary <UUID, int>();

            // Create an AABB for this scene that extends beyond the borders by BORDER_CROSS_THRESHOLD
            // that is used to check for border crossings
            m_borderCrossAABB      = new AABB(Vector3.Zero, new Vector3(scene.MaxPosition - scene.MinPosition));
            m_borderCrossAABB.Min -= new Vector3(BORDER_CROSS_THRESHOLD, BORDER_CROSS_THRESHOLD, BORDER_CROSS_THRESHOLD);
            m_borderCrossAABB.Max += new Vector3(BORDER_CROSS_THRESHOLD, BORDER_CROSS_THRESHOLD, BORDER_CROSS_THRESHOLD);

            m_scheduler = m_scene.Simian.GetAppModule <IScheduler>();
            if (m_scheduler == null)
            {
                m_log.Warn("Neighbors requires an IScheduler");
                return;
            }

            m_httpServer = m_scene.Simian.GetAppModule <IHttpServer>();
            if (m_httpServer == null)
            {
                m_log.Warn("Neighbors requires an IHttpServer");
                return;
            }

            m_udp = m_scene.GetSceneModule <LLUDP>();
            if (m_udp == null)
            {
                m_log.Warn("Neighbors requires an LLUDP");
                return;
            }

            m_userClient = m_scene.Simian.GetAppModule <IUserClient>();
            if (m_userClient == null)
            {
                m_log.Warn("Neighbors requires an IUserClient");
                return;
            }

            m_gridClient = scene.Simian.GetAppModule <IGridClient>();

            // Add neighbor messaging handlers
            string urlFriendlySceneName = WebUtil.UrlEncode(scene.Name);
            string regionPath           = "/regions/" + urlFriendlySceneName;

            m_httpServer.AddHandler("POST", null, regionPath + "/region/online", true, true, RegionOnlineHandler);
            m_httpServer.AddHandler("POST", null, regionPath + "/region/offline", true, true, RegionOfflineHandler);
            m_httpServer.AddHandler("POST", null, regionPath + "/child_avatar/update", true, true, ChildAvatarUpdateHandler);

            m_scene.AddPublicCapability("region/online", m_httpServer.HttpAddress.Combine(regionPath + "/region/online"));
            m_scene.AddPublicCapability("region/offline", m_httpServer.HttpAddress.Combine(regionPath + "/region/offline"));
            m_scene.AddPublicCapability("child_avatar/update", m_httpServer.HttpAddress.Combine(regionPath + "/child_avatar/update"));

            // Track local scenes going up and down
            m_sceneFactory = scene.Simian.GetAppModule <ISceneFactory>();
            if (m_sceneFactory != null)
            {
                m_sceneFactory.OnSceneStart += SceneStartHandler;
                m_sceneFactory.OnSceneStop  += SceneStopHandler;
            }

            m_scene.OnPresenceAdd       += PresenceAddHandler;
            m_scene.OnEntityAddOrUpdate += EntityAddOrUpdateHandler;

            m_childUpdates = new ThrottledQueue <uint, IScenePresence>(5.0f, 200, true, SendChildUpdate);
            m_childUpdates.Start();
        }
Example #16
0
        public bool Start(Simian simian)
        {
            m_simian = simian;

            m_httpServer = simian.GetAppModule<IHttpServer>();
            if (m_httpServer == null)
            {
                m_log.Error("StandaloneGridClient requires an IHttpServer");
                return false;
            }

            m_sceneFactory = simian.GetAppModule<ISceneFactory>();
            if (m_sceneFactory == null)
            {
                m_log.Error("StandaloneGridClient requires an ISceneFactory");
                return false;
            }

            m_assetClient = simian.GetAppModule<IAssetClient>();

            return true;
        }
Example #17
0
 public SceneManager(Game game, Engine engine, ISceneFactory sceneFactory) : base(game)
 {
     _engine       = engine;
     _sceneFactory = sceneFactory;
     game.Components.Add(this);
 }
Example #18
0
 public Game(ICalendar calendar, ISceneFactory sceneFactory)
 {
     _calendar     = calendar;
     _sceneFactory = sceneFactory;
 }
Example #19
0
        public bool Start(Simian simian)
        {
            m_simian = simian;

            if (File.Exists("motd.txt"))
            {
                m_motd = File.ReadAllLines("motd.txt");
            }

            else
            {
                m_motd = new string[0];
            }

            m_sceneFactory = m_simian.GetAppModule <ISceneFactory>();
            if (m_sceneFactory != null)
            {
                m_sceneFactory.OnSceneStart += SceneStartHandler;
            }

            m_clientConnectedCallback = new AsyncCallback(
                delegate(IAsyncResult ar)
            {
                if (m_scene == null)
                {
                    return;
                }

                try
                {
                    //accept connection for a new user
                    IRCUser user   = new IRCUser(m_scene, null, UUID.Random());
                    user.TCPClient = m_listener.EndAcceptTcpClient(ar);
                    m_log.Info("Connection from " + user.TCPClient.Client.RemoteEndPoint);

                    //add new user to dictionary
                    m_users.Add(user);

                    //begin listening for data on the new connection, and also for the next client connection
                    user.TCPClient.Client.BeginReceive(user.Buffer, 0, TCP_BUFFER_LENGTH, SocketFlags.None, m_dataReceivedCallback, user);
                    m_listener.BeginAcceptTcpClient(m_clientConnectedCallback, user);

                    //fire ClientConnected event
                    if (ClientConnected != null)
                    {
                        ClientConnected(user);
                    }
                }
                catch (ObjectDisposedException) { }
            }
                );

            m_dataReceivedCallback = new AsyncCallback(
                delegate(IAsyncResult ar)
            {
                IRCUser user = (IRCUser)ar.AsyncState;

                //number of bytes read
                int bytesRead = user.TCPClient.Client.EndReceive(ar);

                //name or address, depending on whether or not user is authenticated
                string displayName = user.Name == null ? user.TCPClient.Client.RemoteEndPoint.ToString() : user.Name;

                //check for disconnection
                if (bytesRead == 0 || !user.TCPClient.Client.Connected)
                {
                    m_log.Info("Client " + displayName + " disconnected.");

                    SendToUserChannels(user, IRCMessageType.Quit, "Disconnected");     //TODO: quit messages

                    //remove user from disctionary
                    RemoveUser(user);

                    //fire ClientDisconnected event
                    if (ClientDisconnected != null)
                    {
                        ClientDisconnected(user, null);
                    }

                    return;
                }

                //trim buffer length to the number of bytes read
                byte[] buffer = new byte[bytesRead];
                Array.Copy(user.Buffer, 0, buffer, 0, bytesRead);

                //split message into string lines
                string[] delimiters = new string[] { "\0", "\r", "\n" };
                string[] lines      = Encoding.ASCII.GetString(buffer).Split(delimiters, StringSplitOptions.RemoveEmptyEntries);

                //parse each line
                for (int i = 0, len = lines.Length; i < len; i++)
                {
                    m_log.Info("<" + displayName + ">: " + lines[i]);

                    //fire DataReceived event
                    if (DataReceived != null)
                    {
                        DataReceived(user, lines[i]);
                    }

                    ParseCommand(user, lines[i]);
                }

                //keep listening for data
                try
                {
                    user.TCPClient.Client.BeginReceive(user.Buffer, 0, TCP_BUFFER_LENGTH, SocketFlags.None, m_dataReceivedCallback, user);
                }
                catch (Exception ex)
                {
                    m_log.Warn(ex.Message);
                    RemoveUser(user);
                }
            }
                );

            try
            {
                m_listener = new TcpListener(IPAddress.Any, 6667);
                m_listener.Start();
                m_listener.BeginAcceptTcpClient(m_clientConnectedCallback, this);
            }
            catch (Exception ex)
            {
                m_log.Error("Failed to start IRC server: " + ex.Message);
                return(false);
            }

            m_log.Info("IRC server listening on port 6667");
            return(true);
        }
Example #20
0
        public bool Start(Simian simian)
        {
            m_simian = simian;
            m_httpServer = simian.GetAppModule<IHttpServer>();
            m_assetClient = simian.GetAppModule<IAssetClient>();

            m_sceneFactory = simian.GetAppModule<ISceneFactory>();
            if (m_sceneFactory != null)
            {
                m_sceneFactory.OnSceneStart += SceneStartHandler;
                m_sceneFactory.OnSceneStop += SceneStopHandler;
            }

            IConfigSource source = simian.Config;

            IConfig config = source.Configs["SimianGrid"];
            if (config != null)
                m_serverUrl = config.GetString("GridService", null);

            if (String.IsNullOrEmpty(m_serverUrl))
            {
                m_log.Error("[SimianGrid] config section is missing the GridService URL");
                return false;
            }

            return true;
        }
 public CreateEmptySceneService(ISceneFactory sceneFactory, ISceneSerializer sceneSerializer)
 {
     _sceneFactory    = sceneFactory;
     _sceneSerializer = sceneSerializer;
 }
 public SceneLoaderIntegrationTestsSut(IAssetStore assetStore, ISceneFactory sceneFactory, ISceneLoader sceneLoader)
 {
     AssetStore   = assetStore;
     SceneFactory = sceneFactory;
     SceneLoader  = sceneLoader;
 }
Example #23
0
        public bool LoadModules()
        {
            #region Application Module Whitelist Loading

            // Load the application module whitelist
            List <KeyValuePair <int, string> > whitelist = new List <KeyValuePair <int, string> >();

            IConfig config = Config.Configs["ApplicationModules"];
            if (config != null)
            {
                foreach (string key in config.GetKeys())
                {
                    int runLevel = config.GetInt(key, -1);
                    if (runLevel >= 0)
                    {
                        whitelist.Add(new KeyValuePair <int, string>(runLevel, key));
                    }
                }
            }

            // Sort the list based on runlevel
            whitelist.Sort(delegate(KeyValuePair <int, string> lhs, KeyValuePair <int, string> rhs) { return(lhs.Key.CompareTo(rhs.Key)); });

            #endregion Application Module Whitelist Loading

            #region Module Container Loading

            AggregateCatalog catalog = new AggregateCatalog();

            AssemblyCatalog  assemblyCatalog  = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
            DirectoryCatalog directoryCatalog = new DirectoryCatalog(".", "Simian.*.dll");

            catalog.Catalogs.Add(assemblyCatalog);
            catalog.Catalogs.Add(directoryCatalog);

            m_moduleContainer = new CompositionContainer(catalog, true);

            try
            {
                m_log.InfoFormat("Found {0} modules in the current assembly and {1} modules in external assemblies",
                                 assemblyCatalog.Parts.Count(), directoryCatalog.Parts.Count());
            }
            catch (System.Reflection.ReflectionTypeLoadException ex)
            {
                StringBuilder error = new StringBuilder("Error(s) encountered loading extension modules. You may have an incompatible or out of date extension .dll in the current folder.");
                foreach (Exception loaderEx in ex.LoaderExceptions)
                {
                    error.Append("\n " + loaderEx.Message);
                }
                m_log.Error(error.ToString());

                return(false);
            }

            #endregion Module Container Loading

            #region Module Loading

            IEnumerable <Lazy <object, object> >        exportEnumerable = m_moduleContainer.GetExports(typeof(IApplicationModule), null, null);
            Dictionary <string, Lazy <object, object> > exports          = new Dictionary <string, Lazy <object, object> >();
            List <IApplicationModule> imports   = new List <IApplicationModule>();
            List <string>             notLoaded = new List <string>();

            // Reshuffle exportEnumerable into a dictionary mapping module names to their lazy instantiations
            foreach (Lazy <object, object> lazyExport in exportEnumerable)
            {
                IDictionary <string, object> metadata = (IDictionary <string, object>)lazyExport.Metadata;
                object nameObj;
                if (metadata.TryGetValue("Name", out nameObj))
                {
                    string name = (string)nameObj;

                    if (!exports.ContainsKey(name))
                    {
                        exports.Add(name, lazyExport);
                    }
                    else
                    {
                        m_log.Warn("Found an IApplicationModule with a duplicate name: " + name);
                    }
                }
            }

            // Load modules in the order they appear in the whitelist
            foreach (KeyValuePair <int, string> kvp in whitelist)
            {
                string whitelisted = kvp.Value;

                Lazy <object, object> lazyExport;
                if (exports.TryGetValue(whitelisted, out lazyExport))
                {
                    imports.Add((IApplicationModule)lazyExport.Value);
                    exports.Remove(whitelisted);
                }
                else
                {
                    notLoaded.Add(whitelisted);
                }
            }

            // Populate m_applicationModules
            m_applicationModules = imports.ToArray();

            // Start the application modules
            for (int i = 0; i < m_applicationModules.Length; i++)
            {
                IApplicationModule module = m_applicationModules[i];
                if (!(module is ISceneFactory))
                {
                    module.Start(this);
                }
            }

            // ISceneFactory modules are always started last
            for (int i = 0; i < m_applicationModules.Length; i++)
            {
                IApplicationModule module = m_applicationModules[i];
                if (module is ISceneFactory)
                {
                    module.Start(this);
                }
            }

            #endregion Module Loading

            #region Logging

            m_log.InfoFormat("Loaded {0} application modules", m_applicationModules.Length);

            if (exports.Count > 0)
            {
                StringBuilder skippedStr = new StringBuilder("Skipped application modules: ");
                foreach (string exportName in exports.Keys)
                {
                    skippedStr.Append(exportName + " ");
                }
                m_log.Info(skippedStr.ToString());
            }

            if (notLoaded.Count > 0)
            {
                StringBuilder notLoadedStr = new StringBuilder("Did not load whitelisted application modules: ");
                foreach (string entry in notLoaded)
                {
                    notLoadedStr.Append(entry + " ");
                }
                m_log.Warn(notLoadedStr.ToString());
            }

            #endregion Logging

            // Get a reference to the HTTP server if we have one
            m_httpServer = GetAppModule <IHttpServer>();
            if (m_httpServer != null)
            {
                m_capabilityRouter = new CapabilityRouter(m_httpServer.HttpAddress.Combine(CAPABILITY_PATH));
                m_httpServer.AddHandler(null, null, CAPABILITY_PATH, false, false, m_capabilityRouter.RouteCapability);
            }

            // Get a reference to the ISceneFactory if we have one
            m_sceneFactory = GetAppModule <ISceneFactory>();
            if (m_sceneFactory != null)
            {
                AddCommandHandler("scene", SceneHandler);
            }

            return(true);
        }
Example #24
0
        public bool Start(Simian simian)
        {
            m_simian = simian;

            if (File.Exists("motd.txt"))
                m_motd = File.ReadAllLines("motd.txt");

            else m_motd = new string[0];

            m_sceneFactory = m_simian.GetAppModule<ISceneFactory>();
            if (m_sceneFactory != null)
            {
                m_sceneFactory.OnSceneStart += SceneStartHandler;
            }

            m_clientConnectedCallback = new AsyncCallback(
                delegate(IAsyncResult ar)
                {
                    if (m_scene == null)
                        return;

                    try
                    {
                        //accept connection for a new user
                        IRCUser user = new IRCUser(m_scene, null, UUID.Random());
                        user.TCPClient = m_listener.EndAcceptTcpClient(ar);
                        m_log.Info("Connection from " + user.TCPClient.Client.RemoteEndPoint);

                        //add new user to dictionary
                        m_users.Add(user);

                        //begin listening for data on the new connection, and also for the next client connection
                        user.TCPClient.Client.BeginReceive(user.Buffer, 0, TCP_BUFFER_LENGTH, SocketFlags.None, m_dataReceivedCallback, user);
                        m_listener.BeginAcceptTcpClient(m_clientConnectedCallback, user);

                        //fire ClientConnected event
                        if (ClientConnected != null)
                            ClientConnected(user);
                    }
                    catch (ObjectDisposedException) { }
                }
            );

            m_dataReceivedCallback = new AsyncCallback(
                delegate(IAsyncResult ar)
                {
                    IRCUser user = (IRCUser)ar.AsyncState;

                    //number of bytes read
                    int bytesRead = user.TCPClient.Client.EndReceive(ar);

                    //name or address, depending on whether or not user is authenticated
                    string displayName = user.Name == null ? user.TCPClient.Client.RemoteEndPoint.ToString() : user.Name;

                    //check for disconnection
                    if (bytesRead == 0 || !user.TCPClient.Client.Connected)
                    {
                        m_log.Info("Client " + displayName + " disconnected.");

                        SendToUserChannels(user, IRCMessageType.Quit, "Disconnected"); //TODO: quit messages

                        //remove user from disctionary
                        RemoveUser(user);

                        //fire ClientDisconnected event
                        if (ClientDisconnected != null)
                            ClientDisconnected(user, null);

                        return;
                    }

                    //trim buffer length to the number of bytes read
                    byte[] buffer = new byte[bytesRead];
                    Array.Copy(user.Buffer, 0, buffer, 0, bytesRead);

                    //split message into string lines
                    string[] delimiters = new string[] { "\0", "\r", "\n" };
                    string[] lines = Encoding.ASCII.GetString(buffer).Split(delimiters, StringSplitOptions.RemoveEmptyEntries);

                    //parse each line
                    for (int i = 0, len = lines.Length; i < len; i++)
                    {
                        m_log.Info("<" + displayName + ">: " + lines[i]);

                        //fire DataReceived event
                        if (DataReceived != null)
                            DataReceived(user, lines[i]);

                        ParseCommand(user, lines[i]);
                    }

                    //keep listening for data
                    try
                    {
                        user.TCPClient.Client.BeginReceive(user.Buffer, 0, TCP_BUFFER_LENGTH, SocketFlags.None, m_dataReceivedCallback, user);
                    }
                    catch (Exception ex)
                    {
                        m_log.Warn(ex.Message);
                        RemoveUser(user);
                    }
                }
            );

            try
            {
                m_listener = new TcpListener(IPAddress.Any, 6667);
                m_listener.Start();
                m_listener.BeginAcceptTcpClient(m_clientConnectedCallback, this);
            }
            catch (Exception ex)
            {
                m_log.Error("Failed to start IRC server: " + ex.Message);
                return false;
            }

            m_log.Info("IRC server listening on port 6667");
            return true;
        }