Пример #1
0
        protected override void Update(GameTime gameTime)
        {
            if (_pendingCoreGame != null && _coreGame == null)
            {
                _coreGame = _pendingCoreGame;
                _coreGame.AssignHost(this);

                if (_shouldLoadContentOnDelayedGame)
                {
                    _coreGame.LoadContent();
                }
            }

            if (_coreGame != null)
            {
#if PLATFORM_WINDOWS
                if (Window != null)
                {
                    if (_windowWidth != Window.ClientBounds.Width ||
                        _windowHeight != Window.ClientBounds.Height)
                    {
                        OnClientSizeChanged(this, EventArgs.Empty);
                    }
                }
#endif

                _coreGame.Update(gameTime);
                return;
            }
        }
Пример #2
0
        protected override void Draw(GameTime gameTime)
        {
            if (_coreGame != null)
            {
                _coreGame.Draw(gameTime);
                return;
            }

            GraphicsDevice.Clear(Color.Black);

            var width  = GraphicsDevice.PresentationParameters.BackBufferWidth;
            var height = GraphicsDevice.PresentationParameters.BackBufferHeight;

            _splashSpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
            var rect = new Rectangle(0, 0, width, height);

            if (_splash != null)
            {
                _splashSpriteBatch.Draw(
                    _splash,
                    rect,
                    Color.White);
            }
            _splashSpriteBatch.End();

            if (!_hasStartedDelayLoad && _coreGame == null)
            {
                ThreadPool.QueueUserWorkItem(o =>
                {
                    var result       = StartupSequence.Start(new string[0]);
                    _pendingCoreGame = result.GameInstance;
                });
                _hasStartedDelayLoad = true;
            }
        }
Пример #3
0
        public void Render2D(ICoreGame game)
        {
            var renderContext = game.RenderContext;

            if (this.m_CaptureState == null)
            {
                return;
            }

            if (this.m_CaptureState.Mode == CaptureStateMode.Converting ||
                this.m_CaptureState.Mode == CaptureStateMode.Actioning)
            {
                this.m_2DRenderUtilities.RenderRectangle(
                    renderContext,
                    new Microsoft.Xna.Framework.Rectangle(
                        (this.m_CaptureState.RenderTarget.Width / 2) - 100,
                        15,
                        200,
                        24),
                    Microsoft.Xna.Framework.Color.Black,
                    true);
            }

            switch (this.m_CaptureState.Mode)
            {
                case CaptureStateMode.Converting:
                    var total = this.m_CaptureState.CaptureBitmap.Width * this.m_CaptureState.CaptureBitmap.Height;
                    var count = this.m_CaptureState.CapturedFrameConversionX +
                                (this.m_CaptureState.CapturedFrameConversionY * this.m_CaptureState.CaptureBitmap.Width);

                    this.m_2DRenderUtilities.RenderText(
                        renderContext,
                        new Microsoft.Xna.Framework.Vector2(this.m_CaptureState.RenderTarget.Width / 2, 20),
                        "Converting screen capture: " + Math.Round((count / (double)total) * 100.0) + "%",
                        this.m_DefaultFont,
                        horizontalAlignment: HorizontalAlignment.Center);
                    break;
                case CaptureStateMode.Actioning:
                    var tick = ".";
                    for (var i = 0; i < this.m_CaptureState.UploadTick / 15; i++)
                        tick += ".";
                    this.m_CaptureState.UploadTick += 1;
                    if (this.m_CaptureState.UploadTick > 15 * 4)
                    {
                        this.m_CaptureState.UploadTick = 0;
                    }

                    this.m_2DRenderUtilities.RenderText(
                        renderContext,
                        new Microsoft.Xna.Framework.Vector2(this.m_CaptureState.RenderTarget.Width / 2, 20),
                        "Uploading screen capture." + tick,
                        this.m_DefaultFont,
                        horizontalAlignment: HorizontalAlignment.Center);
                    break;
            }
        }
Пример #4
0
        public EditorHostGame(ICoreGame coreGame)
        {
            _coreGame         = coreGame;
            _serviceContainer = new GameServiceContainer();

            _graphicsDeviceService = new EditorGraphicsDeviceService();
            _serviceContainer.AddService <IGraphicsDeviceService>(_graphicsDeviceService);
            _editorGameWindow = new EditorGameWindow(this);
            _contentManager   = new ContentManager(_serviceContainer, "Content");
        }
        public EditorHostGame(ICoreGame coreGame, ISharedRendererClientFactory sharedRendererClientFactory)
        {
            _coreGame         = coreGame;
            _serviceContainer = new GameServiceContainer();

            _graphicsDeviceService = new EditorGraphicsDeviceService(sharedRendererClientFactory);
            _serviceContainer.AddService <IGraphicsDeviceService>(_graphicsDeviceService);
            _editorGameWindow = new EditorGameWindow(this);
            _contentManager   = new ContentManager(_serviceContainer, "Content");
        }
Пример #6
0
        public DefaultGameContext(
            IKernel kernel,
            IAnalyticsEngine analyticsEngine,
            ICoreGame game,
            IGameWindow window,
            IWorld world,
            IWorldManager worldManager)
        {
            _kernel          = kernel;
            _analyticsEngine = analyticsEngine;
            _coroutine       = kernel.Get <ICoroutine>();

            Game         = game;
            World        = world;
            WorldManager = worldManager;
            Window       = window;
        }
Пример #7
0
        public HostedGameRunner(
            ICoreGame game,
            ILogShipping logShipping,
            Api.Version1.Core.IConsoleHandle consoleHandle,
            ISharedRendererClientFactory sharedRendererClientFactory,
            IWantsUpdateSignal[] wantsUpdateSignals,
            IEditorClientProvider editorClientProvider)
        {
            _game          = game;
            _logShipping   = logShipping;
            _consoleHandle = consoleHandle;
            _sharedRendererClientFactory = sharedRendererClientFactory;
            _wantsUpdateSignals          = wantsUpdateSignals;
            _gameHosterClient            = editorClientProvider.GetClient <GameHosterClient>();

            State    = LoadedGameState.Loaded;
            _playing = false;
        }
Пример #8
0
        public HostGame(ICoreGame preloadedCoreGame)
#endif
        {
#if !PLATFORM_ANDROID
            _coreGame = preloadedCoreGame;
#endif

            _graphicsDeviceManager = new GraphicsDeviceManager(this);

            if (_coreGame != null)
            {
                _coreGame.AssignHost(this);
                _shouldHandleResize = true;
                _windowWidth        = Window.ClientBounds.Width;
                _windowHeight       = Window.ClientBounds.Height;
                _coreGame.PrepareGraphicsDeviceManager(_graphicsDeviceManager);
                _graphicsDeviceManager.PreparingDeviceSettings +=
                    (sender, e) =>
                {
                    _coreGame.PrepareDeviceSettings(e.GraphicsDeviceInformation);
                };
            }
            else
            {
                _shouldLoadContentOnDelayedGame = false;
                _backgroundColor = Color.Black;
#if PLATFORM_ANDROID
                _graphicsDeviceManager.IsFullScreen = true;
                _gameActivity = gameActivity;
                try
                {
                    var layout       = _gameActivity.Window.DecorView.FindViewById(Android.Resource.Id.Content);
                    var colorId      = _gameActivity.Resources.GetIdentifier("splash_background", "color", Android.App.Application.Context.PackageName);
                    var androidColor = _gameActivity.Resources.GetColor(colorId);
                    _backgroundColor = new Color(androidColor.R, androidColor.G, androidColor.B, (byte)255);
                }
                catch
                {
                    // Setting background is optional.
                }
#endif
            }
        }
Пример #9
0
        public void LoadFromPath(
            IConsoleHandle consoleHandle,
            IBaseDirectory baseDirectory,
            IBackBufferDimensions backBufferDimensions,
            string gameAssembly)
        {
            // Wrap the backbuffer dimensions service in a proxy, since GraphicsDevice can not
            // cross the AppDomain boundary.
            backBufferDimensions = new BackBufferDimensionsProxy(backBufferDimensions);

            // Load the target assembly.
            consoleHandle.LogDebug("Loading game assembly from " + gameAssembly + "...");
            var assembly = Assembly.LoadFrom(gameAssembly);

            consoleHandle.LogDebug("Constructing standard kernel...");
            var kernel = new StandardKernel();

            kernel.Bind <IRawLaunchArguments>()
            .ToMethod(x => new DefaultRawLaunchArguments(new string[0]))
            .InSingletonScope();

            // Bind our extension hook first so that it runs before everything else.
            kernel.Bind <IEngineHook>().To <ExtensionEngineHook>().InSingletonScope();

            Func <System.Reflection.Assembly, Type[]> TryGetTypes = a =>
            {
                try
                {
                    return(a.GetTypes());
                }
                catch
                {
                    return(new Type[0]);
                }
            };

            consoleHandle.LogDebug("Finding configuration classes in " + gameAssembly + "...");
            var typeSource = new List <Type>();

            foreach (var attribute in assembly.GetCustomAttributes(false))
            {
                if (attribute.GetType().FullName == "Protogame.ConfigurationAttribute")
                {
                    typeSource.Add(((ConfigurationAttribute)attribute).GameConfigurationOrServerClass);
                }
            }

            if (typeSource.Count == 0)
            {
                // Scan all types to find implementors of IGameConfiguration
                typeSource.AddRange(from type in TryGetTypes(assembly)
                                    select type);
            }

            consoleHandle.LogDebug("Found {0} configuration classes in " + gameAssembly, typeSource.Count);

            consoleHandle.LogDebug("Constructing game configurations...");
            var gameConfigurations = new List <IGameConfiguration>();

            foreach (var type in typeSource)
            {
                if (typeof(IGameConfiguration).IsAssignableFrom(type) &&
                    !type.IsInterface && !type.IsAbstract)
                {
                    gameConfigurations.Add(Activator.CreateInstance(type) as IGameConfiguration);
                }
            }

            ICoreGame game = null;
            var       hasBoundNewEventEngine = false;

            consoleHandle.LogDebug("Configuring kernel and constructing game instance ({0} configurations)...", gameConfigurations.Count);
            foreach (var configuration in gameConfigurations)
            {
                consoleHandle.LogDebug("Configuring with {0}...", configuration.GetType().FullName);

                configuration.ConfigureKernel(kernel);

                // Rebind services so the game renders correctly inside the editor.
                kernel.Rebind <IBaseDirectory>().ToMethod(x => baseDirectory).InSingletonScope();
                kernel.Rebind <IBackBufferDimensions>().ToMethod(x => backBufferDimensions).InSingletonScope();
                kernel.Rebind <IDebugRenderer>().To <DefaultDebugRenderer>().InSingletonScope();
                var bindings = kernel.GetCopyOfBindings();
                var mustBindNewEventEngine = false;
                if (bindings.ContainsKey(typeof(IEngineHook)))
                {
                    if (bindings[typeof(IEngineHook)].Any(x => x.Target == typeof(EventEngineHook)))
                    {
                        mustBindNewEventEngine = !hasBoundNewEventEngine;
                        kernel.UnbindSpecific <IEngineHook>(x => x.Target == typeof(EventEngineHook));
                    }

                    if (mustBindNewEventEngine)
                    {
                        kernel.Bind <IEngineHook>().ToMethod(ctx =>
                        {
                            _editorEventEngineHook = ctx.Kernel.Get <EditorEventEngineHook>(ctx.Parent);
                            return(_editorEventEngineHook);
                        }).InSingletonScope();
                    }
                }

                if (game == null)
                {
                    game = configuration.ConstructGame(kernel);
                }
            }

            if (game != null)
            {
                consoleHandle.LogDebug("Game instance is {0}", game.GetType().FullName);
            }

            _game          = game;
            _logShipping   = kernel.Get <ILogShipping>();
            _consoleHandle = consoleHandle;

            consoleHandle.LogDebug("LoadFromPath complete");
        }
Пример #10
0
        public void Update(ICoreGame game)
        {
            if (this.m_CaptureState == null || this.m_CaptureState.Mode != CaptureStateMode.Converting)
            {
                return;
            }

            var start = DateTime.Now;

            while ((DateTime.Now - start).TotalMilliseconds < 3)
            {
                if (this.ProcessCaptureFramePixel())
                {
                    break;
                }
            }

            if (this.m_CaptureState.Mode != CaptureStateMode.Converting)
            {
                using (var memory = new MemoryStream())
                {
                    this.m_CaptureState.CaptureBitmap.Save(memory, ImageFormat.Png);

                    memory.Seek(0, SeekOrigin.Begin);
                    var bytes = new byte[(int)memory.Length];
                    memory.Read(bytes, 0, (int)memory.Length);

                    this.m_CaptureState.CaptureBitmap.Dispose();
                    this.m_CaptureState.CaptureBitmap = null;

                    this.m_CaptureState.Mode = CaptureStateMode.Actioning;
                    this.m_CaptureState.ActionThread = new Thread(() =>
                        {
                            try
                            {
                                this.m_CaptureState.Action(bytes);
                                this.m_CaptureState = null;
                            }
                            catch (Exception ex)
                            {
                                // We can't upload the screenshot, so report the exception.
                                CrashReport.CrashReporter.Record(ex);
                                this.m_CaptureState = null;
                            }
                        });
                    this.m_CaptureState.ActionThread.IsBackground = true;
                    this.m_CaptureState.ActionThread.Start();
                }
            }
        }
Пример #11
0
 public void RenderBelow(ICoreGame game)
 {
     if (this.m_CaptureState != null && this.m_CaptureState.Mode == CaptureStateMode.Requested)
     {
         game.RenderContext.PushRenderTarget(this.m_CaptureState.RenderTarget);
     }
 }
Пример #12
0
        public void RenderAbove(ICoreGame game)
        {
            if (this.m_CaptureState != null && this.m_CaptureState.Mode == CaptureStateMode.Requested)
            {
                game.RenderContext.PopRenderTarget();

                this.m_CaptureState.Mode = CaptureStateMode.Converting;
                this.m_CaptureState.CaptureBuffer =
                    new Microsoft.Xna.Framework.Color[this.m_CaptureState.RenderTarget.Width * this.m_CaptureState.RenderTarget.Height];
                this.m_CaptureState.RenderTarget.GetData(this.m_CaptureState.CaptureBuffer);
                this.m_CaptureState.CaptureBitmap = new Bitmap(
                    this.m_CaptureState.RenderTarget.Width,
                    this.m_CaptureState.RenderTarget.Height,
                    PixelFormat.Format32bppArgb);
                this.m_CaptureState.CapturedFrameConversionX = 0;
                this.m_CaptureState.CapturedFrameConversionY = 0;
            }
        }
Пример #13
0
        public static int RealMain(string[] args)
        {
            int?trackProcessId = null;

            Console.Error.WriteLine("GameHost RealMain called with: " + args.Aggregate((a, b) => a + " " + b));
            var    argsList     = new Queue <string>(args);
            string editorUrl    = null;
            string assemblyFile = null;

            while (argsList.Count > 0)
            {
                var arg = argsList.Dequeue();
                switch (arg)
                {
                case "--trace":
                {
                    var pid     = argsList.Dequeue();
                    var process = Process.GetProcessById(int.Parse(pid));
                    process.Exited += (sender, e) =>
                    {
                        Console.Error.WriteLine("Parent process " + pid + " has exited, closing game host process.");
                        Environment.Exit(0);
                    };
                    process.EnableRaisingEvents = true;
                    if (process.HasExited)
                    {
                        Console.Error.WriteLine("Parent process " + pid + " has exited, closing game host process.");
                        Environment.Exit(0);
                    }
                    break;
                }

                case "--debug":
                    Debugger.Launch();
                    break;

                case "--editor-url":
                    editorUrl = argsList.Dequeue();
                    break;

                case "--assembly-path":
                    assemblyFile = argsList.Dequeue();
                    break;
                }
            }

            AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
            {
                Console.Error.WriteLine(e.ExceptionObject);
            };

            if (editorUrl == null || assemblyFile == null)
            {
                System.Console.Error.WriteLine("Editor URL or assembly file not specified");
                return(1);
            }

            System.Console.Error.WriteLine("Starting game host...");
            System.Console.Error.WriteLine("Editor URL is: {0}", editorUrl);
            System.Console.Error.WriteLine("Assembly path is: {0}", assemblyFile);

            System.Console.Error.WriteLine("Configuring kernel...");

            var kernel = new StandardKernel();

            kernel.Bind <IEditorClientProvider>().To <EditorClientProvider>().InSingletonScope();
            kernel.Bind <IProjectManager>().To <ProjectManager>().InSingletonScope();
            kernel.Bind <IWantsUpdateSignal>().To <ProjectManagerUpdateSignal>().InSingletonScope();
            kernel.Bind <IWantsUpdateSignal>().To <PresenceCheckerUpdateSignal>().InSingletonScope();
            kernel.Bind <Api.Version1.Core.IConsoleHandle>().To <ConsoleHandle>().InSingletonScope();
            kernel.Bind <IGameRunner>().To <HostedGameRunner>().InSingletonScope();
            kernel.Bind <HostedEventEngineHook>().To <HostedEventEngineHook>().InSingletonScope();
            kernel.Bind <ISharedRendererClientFactory>().ToFactory();

            System.Console.Error.WriteLine("Configuring editor client provider with URL: {0}", editorUrl);
            var editorClientProvider = kernel.Get <IEditorClientProvider>();

            editorClientProvider.CreateChannel(editorUrl);

            // Load the target assembly.
            System.Console.Error.WriteLine("Loading game assembly from " + assemblyFile + "...");
            var assembly = Assembly.LoadFrom(assemblyFile);

            System.Console.Error.WriteLine("Constructing standard kernel...");
            kernel.Bind <IRawLaunchArguments>()
            .ToMethod(x => new DefaultRawLaunchArguments(new string[0]))
            .InSingletonScope();

            // Bind our extension hook first so that it runs before everything else.
            kernel.Bind <IEngineHook>().To <ExtensionEngineHook>().InSingletonScope();

            Func <System.Reflection.Assembly, Type[]> TryGetTypes = a =>
            {
                try
                {
                    return(a.GetTypes());
                }
                catch
                {
                    return(new Type[0]);
                }
            };

            System.Console.Error.WriteLine("Finding configuration classes in " + assemblyFile + "...");
            var typeSource = new List <Type>();

            foreach (var attribute in assembly.GetCustomAttributes(false))
            {
                if (attribute.GetType().FullName == "Protogame.ConfigurationAttribute")
                {
                    typeSource.Add(((ConfigurationAttribute)attribute).GameConfigurationOrServerClass);
                }
            }

            if (typeSource.Count == 0)
            {
                // Scan all types to find implementors of IGameConfiguration
                typeSource.AddRange(from type in TryGetTypes(assembly)
                                    select type);
            }

            System.Console.Error.WriteLine("Found {0} configuration classes in " + assemblyFile, typeSource.Count);

            System.Console.Error.WriteLine("Constructing game configurations...");
            var gameConfigurations = new List <IGameConfiguration>();

            foreach (var type in typeSource)
            {
                if (typeof(IGameConfiguration).IsAssignableFrom(type) &&
                    !type.IsInterface && !type.IsAbstract)
                {
                    gameConfigurations.Add(Activator.CreateInstance(type) as IGameConfiguration);
                }
            }

            ICoreGame game = null;
            var       hasBoundNewEventEngine = false;

            System.Console.Error.WriteLine("Configuring kernel and constructing game instance ({0} configurations)...", gameConfigurations.Count);
            foreach (var configuration in gameConfigurations)
            {
                System.Console.Error.WriteLine("Configuring with {0}...", configuration.GetType().FullName);

                configuration.ConfigureKernel(kernel);

                // Rebind services so the game renders correctly inside the editor.
                kernel.Rebind <IBaseDirectory>().To <HostedBaseDirectory>().InSingletonScope();
                kernel.Rebind <IBackBufferDimensions>().To <HostedBackBufferDimensions>().InSingletonScope();
                kernel.Rebind <IDebugRenderer>().To <DefaultDebugRenderer>().InSingletonScope();
                var bindings = kernel.GetCopyOfBindings();
                var mustBindNewEventEngine = false;
                if (bindings.ContainsKey(typeof(IEngineHook)))
                {
                    if (bindings[typeof(IEngineHook)].Any(x => x.Target == typeof(EventEngineHook)))
                    {
                        mustBindNewEventEngine = !hasBoundNewEventEngine;
                        kernel.UnbindSpecific <IEngineHook>(x => x.Target == typeof(EventEngineHook));
                    }

                    if (mustBindNewEventEngine)
                    {
                        kernel.Bind <IEngineHook>().ToMethod(ctx =>
                        {
                            return(ctx.Kernel.Get <HostedEventEngineHook>(ctx.Parent));
                        }).InSingletonScope();
                    }
                }

                if (game == null)
                {
                    game = configuration.ConstructGame(kernel);
                }
            }

            if (game != null)
            {
                System.Console.Error.WriteLine("Game instance is {0}", game.GetType().FullName);
            }

            var runner = kernel.Get <IGameRunner>(new NamedConstructorArgument("game", game));

            System.Console.Error.WriteLine("Configuring gRPC logging...");
            GrpcEnvironment.SetLogger(new GrpcLogger());

            System.Console.Error.WriteLine("Creating gRPC server...");
            var server = new Srv
            {
                Services =
                {
                    GameHostServer.BindService(kernel.Get <GameHostServerImpl>())
                },
                Ports = { new ServerPort("localhost", 0, ServerCredentials.Insecure) }
            };

            server.Start();

            var serverUrl = "localhost:" + server.Ports.Select(x => x.BoundPort).First();

            System.Console.Error.WriteLine("gRPC server started on {0}", serverUrl);

            Console.WriteLine(serverUrl);
            Console.Error.WriteLine(serverUrl);

            System.Console.Error.WriteLine("LoadFromPath complete");

            runner.Run();

            return(0);
        }
Пример #14
0
        public static StartupSequenceResult Start(string[] args)
        {
            StartupTrace.WriteLine("Protected Startup: Execution of protected startup has begun");

            var stopwatch = new Stopwatch();

            stopwatch.Start();

            var kernel = new StandardKernel();

            kernel.Bind <IRawLaunchArguments>()
            .ToMethod(x => new DefaultRawLaunchArguments(args))
            .InSingletonScope();

            Func <System.Reflection.Assembly, Type[]> TryGetTypes = assembly =>
            {
                try
                {
                    return(assembly.GetTypes());
                }
                catch
                {
                    return(new Type[0]);
                }
            };

            StartupTrace.WriteLine("Protected Startup: Scanning for implementations of IGameConfiguration");

            var assemblies = AppDomain.CurrentDomain.GetAssemblies();
            var typeSource = new List <Type>();

            foreach (var assembly in assemblies)
            {
                typeSource.AddRange(assembly.GetCustomAttributes(false).OfType <ConfigurationAttribute>().Select(x => x.GameConfigurationOrServerClass));
            }

            StartupTrace.TimingEntries["scanForConfigurationAttributes"] = stopwatch.Elapsed;
            stopwatch.Restart();

            if (typeSource.Count == 0)
            {
                // Scan all types to find implementors of IGameConfiguration
                typeSource.AddRange(from assembly in AppDomain.CurrentDomain.GetAssemblies()
                                    from type in TryGetTypes(assembly)
                                    select type);

                StartupTrace.TimingEntries["scanForGameConfigurationImplementations"] = stopwatch.Elapsed;
                stopwatch.Restart();
            }

            // Search the application domain for implementations of
            // the IGameConfiguration.
            var gameConfigurations = new List <IGameConfiguration>();

            foreach (var type in typeSource)
            {
                if (typeof(IGameConfiguration).IsAssignableFrom(type) &&
                    !type.IsInterface && !type.IsAbstract)
                {
                    gameConfigurations.Add(Activator.CreateInstance(type) as IGameConfiguration);
                }
            }

            StartupTrace.WriteLine("Protected Startup: Found " + gameConfigurations.Count + " implementations of IGameConfiguration");

#if CAN_RUN_DEDICATED_SERVER
            StartupTrace.WriteLine("Protected Startup: Scanning for implementations of IServerConfiguration");

            // Search the application domain for implementations of
            // the IServerConfiguration.
            var serverConfigurations = new List <IServerConfiguration>();
            foreach (var type in typeSource)
            {
                if (typeof(IServerConfiguration).IsAssignableFrom(type) &&
                    !type.IsInterface && !type.IsAbstract)
                {
                    serverConfigurations.Add(Activator.CreateInstance(type) as IServerConfiguration);
                }
            }

            StartupTrace.WriteLine("Protected Startup: Found " + serverConfigurations.Count + " implementations of IServerConfiguration");

            if (gameConfigurations.Count == 0 && serverConfigurations.Count == 0)
            {
                throw new InvalidOperationException(
                          "You must have at least one implementation of " +
                          "IGameConfiguration or IServerConfiguration in your game.");
            }
#else
            if (gameConfigurations.Count == 0)
            {
                throw new InvalidOperationException(
                          "You must have at least one implementation of " +
                          "IGameConfiguration in your game.");
            }
#endif

            StartupTrace.TimingEntries["constructGameConfigurationImplementations"] = stopwatch.Elapsed;
            stopwatch.Restart();

            ICoreGame game = null;

#if CAN_RUN_DEDICATED_SERVER
            ICoreServer server = null;
#endif

            StartupTrace.WriteLine("Protected Startup: Starting iteration through game configuration implementations");

            foreach (var configuration in gameConfigurations)
            {
                StartupTrace.WriteLine("Protected Startup: Configuring kernel with " + configuration.GetType().FullName);
                configuration.ConfigureKernel(kernel);

                StartupTrace.TimingEntries["configureKernel(" + configuration.GetType().FullName + ")"] = stopwatch.Elapsed;
                stopwatch.Restart();

                // We only construct one game.  In the event there are
                // multiple game configurations (such as a third-party library
                // providing additional game tools, it's expected that libraries
                // will return null for ConstructGame).
                if (game == null)
                {
                    StartupTrace.WriteLine("Protected Startup: Attempted to construct game with " + configuration.GetType().FullName);
                    game = configuration.ConstructGame(kernel);
                    StartupTrace.WriteLineIf(game != null, "Protected Startup: Constructed game with " + configuration.GetType().FullName);

                    StartupTrace.TimingEntries["constructGame(" + configuration.GetType().FullName + ")"] = stopwatch.Elapsed;
                    stopwatch.Restart();
                }
            }

            StartupTrace.WriteLine("Protected Startup: Finished iteration through game configuration implementations");

#if CAN_RUN_DEDICATED_SERVER
            StartupTrace.WriteLine("Protected Startup: Starting iteration through server configuration implementations");

            foreach (var serverConfiguration in serverConfigurations)
            {
                StartupTrace.WriteLine("Protected Startup: Configuring kernel with " + serverConfiguration.GetType().FullName);
                serverConfiguration.ConfigureKernel(kernel);

                // We only construct one server.  In the event there are
                // multiple server configurations (such as a third-party library
                // providing additional game tools, it's expected that libraries
                // will return null for ConstructServer).
                if (server == null)
                {
                    StartupTrace.WriteLine("Protected Startup: Attempted to construct server with " + serverConfiguration.GetType().FullName);
                    server = serverConfiguration.ConstructServer(kernel);
                    Debug.WriteLineIf(server != null, "Protected Startup: Constructed server with " + serverConfiguration.GetType().FullName);
                }
            }

            StartupTrace.WriteLine("Protected Startup: Finished iteration through server configuration implementations");

            if (game == null && server == null)
            {
                throw new InvalidOperationException(
                          "No implementation of IGameConfiguration provided " +
                          "a game instance from ConstructGame, and " +
                          "no implementation of IServerConfiguration provided " +
                          "a server instance from ConstructServer.");
            }

            if (game != null && server != null)
            {
                throw new InvalidOperationException(
                          "An implementation of IGameConfiguration provided " +
                          "a game instance, and an implementation of " +
                          "IServerConfiguration provided a server instance.  " +
                          "It's not possible to determine whether the game or " +
                          "server should be started with this configuration.  " +
                          "Move one of the implementations so that it's not in " +
                          "the default loaded application domain.");
            }
#else
            if (game == null)
            {
                throw new InvalidOperationException(
                          "No implementation of IGameConfiguration provided " +
                          "a game instance from ConstructGame.");
            }
#endif

            StartupTrace.TimingEntries["finalizeStartup"] = stopwatch.Elapsed;
            stopwatch.Stop();

            return(new StartupSequenceResult
            {
                Kernel = kernel,
                GameInstance = game,
#if CAN_RUN_DEDICATED_SERVER
                ServerInstance = server,
#endif
            });
        }
Пример #15
0
 public void RenderEarly(ICoreGame game, SpriteBatch hostLoadedSpriteBatch, Texture2D hostLoadedSplashScreenTexture)
 {
     game.GraphicsDevice.Clear(new Color(0x33, 0x33, 0x33, 0xFF));
 }