Ejemplo n.º 1
0
        protected Sample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            // Get services from the global service container.
              var services = (ServiceContainer)ServiceLocator.Current;
              SampleFramework = services.GetInstance<SampleFramework>();
              ContentManager = services.GetInstance<ContentManager>();
              UIContentManager = services.GetInstance<ContentManager>("UIContent");
              InputService = services.GetInstance<IInputService>();
              AnimationService = services.GetInstance<IAnimationService>();
              Simulation = services.GetInstance<Simulation>();
              ParticleSystemService = services.GetInstance<IParticleSystemService>();
              GraphicsService = services.GetInstance<IGraphicsService>();
              GameObjectService = services.GetInstance<IGameObjectService>();
              UIService = services.GetInstance<IUIService>();

              // Create a local service container which can be modified in samples:
              // The local service container is a child container, i.e. it inherits the
              // services of the global service container. Samples can add new services
              // or override existing entries without affecting the global services container
              // or other samples.
              Services = services.CreateChildContainer();

              // Store a copy of the original graphics screens.
              _originalGraphicsScreens = GraphicsService.Screens.ToArray();

              // Mouse is visible by default.
              SampleFramework.IsMouseVisible = true;
        }
Ejemplo n.º 2
0
        public EditorBase(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            // Get services from the global service container.
            var services = (ServiceContainer)ServiceLocator.Current;
            UIContentManager = services.GetInstance<ContentManager>("UIContent");
            InputService = services.GetInstance<IInputService>();
            AnimationService = services.GetInstance<IAnimationService>();
            GraphicsService = services.GetInstance<IGraphicsService>();
            GameObjectService = services.GetInstance<IGameObjectService>();
            UIService = services.GetInstance<IUIService>();

            // Create a local service container which can be modified in samples:
            // The local service container is a child container, i.e. it inherits the
            // services of the global service container. Samples can add new services
            // or override existing entries without affecting the global services container
            // or other samples.
            Services = services.CreateChildContainer();

            // Load a UI theme, which defines the appearance and default values of UI controls.
            Theme theme = UIContentManager.Load<Theme>("BlendBlue/Theme");

            FigureRenderer = new FigureRenderer(GraphicsService, 2000);
            DebugRenderer = new DebugRenderer(GraphicsService, UIContentManager.Load<SpriteFont>("BlendBlue/Default"));
            UIRenderer = new UIRenderer(GraphicsService.GraphicsDevice, theme);

            UIScreen = new UIScreen("Main Screen", UIRenderer)
            {
                Background = Color.TransparentBlack,
            };

            UIService.Screens.Add(UIScreen);

            Scene = new Scene();
        }
Ejemplo n.º 3
0
        protected override void Initialize()
        {
            // create all application services and add to main services container.
            _services = new ServiceContainer();
            ServiceLocator.SetLocatorProvider(() => _services);

            var vfsStorage = new VfsStorage();
            var pathStorage = new FileSystemStorage("data");
            var uiAssetsStorage = new ZipStorage(pathStorage, "UI_Assets.zip");
            vfsStorage.MountInfos.Add(new VfsMountInfo(uiAssetsStorage, null));

            // Register the virtual file system as a service.
            _services.Register(typeof(IStorage), null, vfsStorage);

            // The GraphicsDeviceManager needs to be registered in the service container.
            // (This is required by the XNA content managers.)
            _services.Register(typeof(IGraphicsDeviceService), null, _graphicsDeviceManager);
            _services.Register(typeof(GraphicsDeviceManager), null, _graphicsDeviceManager);

            var uiContentManager = new StorageContentManager(_services, uiAssetsStorage);
            _services.Register(typeof(ContentManager), "UIContent", uiContentManager);

            // ----- Initialize Services
            // Register the game class.
            _services.Register(typeof(Microsoft.Xna.Framework.Game), null, this);
            _services.Register(typeof(kbPCB), null, this);

            // Input
            _inputManager = new InputManager(false);
            _services.Register(typeof(IInputService), null, _inputManager);

            // Graphics
            _graphicsManager = new GraphicsManager(GraphicsDevice, Window, uiContentManager);
            _services.Register(typeof(IGraphicsService), null, _graphicsManager);

            // GUI
            _uiManager = new UIManager(this, _inputManager);
            _services.Register(typeof(IUIService), null, _uiManager);

            // Animation
            _animationManager = new AnimationManager();
            _services.Register(typeof(IAnimationService), null, _animationManager);

            // Game logic
            _gameObjectManager = new GameObjectManager();
            _services.Register(typeof(IGameObjectService), null, _gameObjectManager);

            // Profiler
            _profiler = new HierarchicalProfiler("Main");
            _services.Register(typeof(HierarchicalProfiler), "Main", _profiler);

            // add more stuff here
            var editor2D = new Editor2D(this);
            Components.Add(editor2D);

            base.Initialize();
        }
Ejemplo n.º 4
0
        //--------------------------------------------------------------
        #region Methods
        //--------------------------------------------------------------

        private static async Task<Tuple<bool, List<Error>>> BuildMonoGameAsync(
            ServiceContainer services, string applicationName, TextDocument document, DelegateCommand<Error> goToLocationCommand)
        {
            string errorMessage = await Task.Run(() =>
            {
                using (var tempDirectoryHelper = new TempDirectoryHelper(applicationName, "ShaderDocument"))
                {
                    var contentBuilder = new GameContentBuilder(services)
                    {
                        IntermediateFolder = tempDirectoryHelper.TempDirectoryName + "\\obj",
                        OutputFolder = tempDirectoryHelper.TempDirectoryName + "\\bin",
                    };

                    string message;
                    contentBuilder.Build(document.Uri.LocalPath, null, "EffectProcessor", null, out message);
                    return message;
                }
            });

            List<Error> errors = null;
            if (!string.IsNullOrEmpty(errorMessage))
            {
                errorMessage = errorMessage.TrimEnd(' ', '\r', '\n');
                errors = new List<Error>();

                // Use regular expression to parse the MSBuild output lines.
                // Example: "X:\DigitalRune\Samples\DigitalRune.Graphics.Content\DigitalRune\Billboard.fx(22,3) : Unexpected token 'x' found. Expected CloseBracket"
                var regex = new Regex(@"(?<file>[^\\/]*)\((?<line>\d+),(?<column>\d+)\) : (?<message>.*)");

                var match = regex.Match(errorMessage);
                if (match.Success)
                {
                    string lineText = match.Groups["line"].Value;
                    string columnText = match.Groups["column"].Value;
                    string message = match.Groups["message"].Value;
                    bool isWarning = match.Groups["warning"].Success;
                    var error = new Error(
                        isWarning ? ErrorType.Warning : ErrorType.Error,
                        $"[MonoGame] {message}",
                        match.Groups["file"].Value,
                        int.Parse(lineText),
                        int.Parse(columnText));

                    error.UserData = document;
                    error.GoToLocationCommand = goToLocationCommand;
                    errors.Add(error);
                }
                else
                {
                    errors.Add(new Error(ErrorType.Error, errorMessage));
                }
            }

            return Tuple.Create(string.IsNullOrEmpty(errorMessage), errors);
        }
Ejemplo n.º 5
0
        //--------------------------------------------------------------
        #region Methods
        //--------------------------------------------------------------

        private static async Task<Tuple<bool, List<Error>>> BuildFxcAsync(
            ServiceContainer services, TextDocument document, DelegateCommand<Error> goToLocationCommand)
        {
            var fxc = services.GetInstance<Fxc>().ThrowIfMissing();
            var result = await fxc.BuildAsync(document.Uri.LocalPath);

            // TODO: Asynchronously parse errors.
            List<Error> errors = null;
            if (result.Item2?.Count > 0)
            {
                // Use regular expression to parse the MSBuild output lines.
                // Example: "X:\DigitalRune\Samples\DigitalRune.Graphics.Content\DigitalRune\Billboard.fx(100,3): error X3000: unrecognized identifier 'x'"
                var regex = new Regex(@"(?<file>[^\\/]*)\((?<line>\d+),(?<column>\d+)\): (?<message>(((?<error>error )|(?<warning>warning ))).*)");

                errors = new List<Error>();
                foreach (var line in result.Item2)
                {
                    var match = regex.Match(line);
                    if (match.Success)
                    {
                        string lineText = match.Groups["line"].Value;
                        string columnText = match.Groups["column"].Value;
                        string message = match.Groups["message"].Value;
                        bool isWarning = match.Groups["warning"].Success;
                        var error = new Error(
                            isWarning ? ErrorType.Warning : ErrorType.Error,
                            $"[FXC] {message}",
                            match.Groups["file"].Value,
                            int.Parse(lineText),
                            int.Parse(columnText));

                        error.UserData = document;
                        error.GoToLocationCommand = goToLocationCommand;
                        errors.Add(error);
                    }
                }
            }

            return Tuple.Create(result.Item1, errors);
        }
Ejemplo n.º 6
0
        //--------------------------------------------------------------
        public MyGame()
        {
            Lock = new object();

              // ----- Service Container
              // MyGame uses a ServiceContainer, which is a simple service locator and
              // Inversion of Control (IoC) container. (The ServiceContainer can be
              // replaced by any other container that implements System.IServiceProvider.)
              _serviceContainer = new ServiceContainer();
              ServiceLocator.SetLocatorProvider(() => _serviceContainer);

              _serviceContainer.Register(typeof(MyGame), null, this);

              // ----- Storage
              // Create a "virtual file system" for reading game assets.
              _titleStorage = new TitleStorage("Content");
              _assetsStorage = new ZipStorage(_titleStorage, "Content.zip");
              _digitalRuneStorage = new ZipStorage(_titleStorage, "DigitalRune.zip");
              _vfsStorage = new VfsStorage();
              _vfsStorage.MountInfos.Add(new VfsMountInfo(_assetsStorage, null));
              _vfsStorage.MountInfos.Add(new VfsMountInfo(_digitalRuneStorage, null));

              // ----- Content
              _contentManager = new StorageContentManager(ServiceLocator.Current, _vfsStorage);
              _serviceContainer.Register(typeof(ContentManager), null, _contentManager);

              // ----- Graphics
              // Create Direct3D 11 device.
              var presentationParameters = new PresentationParameters
              {
            BackBufferWidth = 1,
            BackBufferHeight = 1,
            // Do not associate graphics device with any window.
            DeviceWindowHandle = IntPtr.Zero,
              };
              var graphicsDevice = new GraphicsDevice(GraphicsAdapter.DefaultAdapter, GraphicsProfile.HiDef, presentationParameters);

              // An IGraphicsDeviceService is required by the MonoGame/XNA content manager.
              _serviceContainer.Register(typeof(IGraphicsDeviceService), null, new DummyGraphicsDeviceManager(graphicsDevice));

              // Get DXGIOutput to call WaitForVerticalBlank() in the game loop.
              using (var dxgiFactory = new SharpDX.DXGI.Factory1())
              using (var dxgiAdapter = dxgiFactory.GetAdapter1(0))
            _dxgiOutput = dxgiAdapter.GetOutput(0);

              // Create and register the graphics manager.
              _graphicsManager = new GraphicsManager(graphicsDevice, _contentManager);
              _serviceContainer.Register(typeof(IGraphicsService), null, _graphicsManager);

              // ----- Timing
              // The game loop runs in a parallel thread to keep the UI thread responsive.
              // To measure the time that has passed, we use a HighPrecisionClock.
              _clock = new HighPrecisionClock();
              _clock.Start();
              _gameLoopTask = ThreadPool.RunAsync(GameLoopTaskAction, WorkItemPriority.High, WorkItemOptions.TimeSliced)
                                .AsTask();

              // The FixedStepTimer reads the clock and triggers the game loop at 60 Hz.
              //_timer = new FixedStepTimer(_clock)
              //{
              //  StepSize = new TimeSpan(166667), // ~60 Hz
              //  AccumulateTimeSteps = false,
              //};

              // The VariableStepTimer reads the clock and triggers the game loop as often as possible.
              _timer = new VariableStepTimer(_clock);

              _timer.TimeChanged += (s, e) => GameLoop(e.DeltaTime);
              _timer.Start();

              CoreApplication.Suspending += OnCoreApplicationSuspending;

              // DirectX buffers only a limit amount of Present calls per frame which is controlled by
              // the MaximumFrameLatency property. The default value is usually 3. If the application
              // uses more SwapChainPresentationTargets we must increase this property.
              //var d3dDevice = (SharpDX.Direct3D11.Device)_graphicsManager.GraphicsDevice.Handle;
              //using (var dxgiDevice2 = d3dDevice.QueryInterface<SharpDX.DXGI.Device2>())
              //  dxgiDevice2.MaximumFrameLatency = numberOfSwapChainPanels;
        }
Ejemplo n.º 7
0
    //--------------------------------------------------------------
    #region Creation & Cleanup
    //--------------------------------------------------------------

    /// <summary>
    /// Initializes a new instance of the <see cref="SampleFramework" /> class.
    /// </summary>
    /// <param name="game">The XNA game.</param>
    /// <param name="initialSample">The type of the first sample.</param>
    public SampleFramework(SampleGame game, Type initialSample)
    {
      _game = game;
      _initialSample = initialSample;

      // Get all required services.
      _services = (ServiceContainer)ServiceLocator.Current;
      _inputService = ServiceLocator.Current.GetInstance<IInputService>();
      _graphicsService = _services.GetInstance<IGraphicsService>();
      _gameObjectService = _services.GetInstance<IGameObjectService>();

      InitializeSamples();
      InitializeController();
      InitializeMouse();
      InitializeProfiler();
      InitializeGui();
    }
Ejemplo n.º 8
0
    // Creates a test scene with a lot of randomly placed objects.
    internal static void CreateScene(ServiceContainer services, ContentManager content, DeferredGraphicsScreen graphicsScreen)
    {
      var gameObjectService = services.GetInstance<IGameObjectService>();
      var graphicsService = services.GetInstance<IGraphicsService>();

      gameObjectService.Objects.Add(new DynamicSkyObject(services, true, false, true)
      {
        EnableAmbientLight = false, // Disable ambient light of sky to make shadows more visible.
        EnableCloudShadows = false
      });

      gameObjectService.Objects.Add(new GroundObject(services));
      gameObjectService.Objects.Add(new DynamicObject(services, 1));
      gameObjectService.Objects.Add(new DynamicObject(services, 2));
      gameObjectService.Objects.Add(new DynamicObject(services, 3));
      gameObjectService.Objects.Add(new DynamicObject(services, 5));
      gameObjectService.Objects.Add(new DynamicObject(services, 6));
      gameObjectService.Objects.Add(new DynamicObject(services, 7));
      gameObjectService.Objects.Add(new ObjectCreatorObject(services));
      gameObjectService.Objects.Add(new LavaBallsObject(services));

      var random = new Random();

      // Spheres
      var sphereMesh = SampleHelper.CreateMesh(content, graphicsService, new SphereShape(1));
      for (int i = 0; i < 100; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-100, 100), random.NextFloat(0, 3), random.NextFloat(-100, 100));
        float scale = random.NextFloat(0.5f, 3f);
        var meshNode = new MeshNode(sphereMesh)
        {
          PoseLocal = new Pose(position),
          ScaleLocal = new Vector3F(scale),
          IsStatic = true,
        };
        graphicsScreen.Scene.Children.Add(meshNode);
      }

      // Boxes
      var boxMesh = SampleHelper.CreateMesh(content, graphicsService, new BoxShape(1, 1, 1));
      for (int i = 0; i < 100; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-100, 100), random.NextFloat(0, 3), random.NextFloat(-100, 100));
        QuaternionF orientation = random.NextQuaternionF();
        Vector3F scale = random.NextVector3F(0.1f, 4f);
        var meshNode = new MeshNode(boxMesh)
        {
          PoseLocal = new Pose(position, orientation),
          ScaleLocal = scale,
          IsStatic = true,
        };
        graphicsScreen.Scene.Children.Add(meshNode);
      }

      // Height field with smooth hills.
      var numberOfSamplesX = 20;
      var numberOfSamplesZ = 20;
      var samples = new float[numberOfSamplesX * numberOfSamplesZ];
      for (int z = 0; z < numberOfSamplesZ; z++)
      {
        for (int x = 0; x < numberOfSamplesX; x++)
        {
          if (x == 0 || z == 0 || x == 19 || z == 19)
          {
            // Set this boundary elements to a low height, so that the height field is connected
            // to the ground.
            samples[z * numberOfSamplesX + x] = -1;
          }
          else
          {
            // A sine/cosine function that creates some interesting waves.
            samples[z * numberOfSamplesX + x] = 1 + (float)(Math.Cos(z / 2f) * Math.Sin(x / 2f) * 1);
          }
        }
      }
      var heightField = new HeightField(0, 0, 20, 20, samples, numberOfSamplesX, numberOfSamplesZ);
      var heightFieldMesh = SampleHelper.CreateMesh(content, graphicsService, heightField);
      var heightFieldMeshNode = new MeshNode(heightFieldMesh)
      {
        PoseLocal = new Pose(new Vector3F(20, 0, -20)),
        ScaleLocal = new Vector3F(1, 2, 1),
        IsStatic = true,
      };
      graphicsScreen.Scene.Children.Add(heightFieldMeshNode);

      // Dudes.
      for (int i = 0; i < 10; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-20, 20), 0, random.NextFloat(-20, 20));
        Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
        gameObjectService.Objects.Add(new DudeObject(services) { Pose = new Pose(position, orientation) });
      }

      // Palm trees.
      for (int i = 0; i < 100; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-80, 80), 0, random.NextFloat(-100, 100));
        Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
        float scale = random.NextFloat(0.5f, 1.2f);
        gameObjectService.Objects.Add(new StaticObject(services, "PalmTree/palm_tree", scale, new Pose(position, orientation)));
      }

      // Rocks
      for (int i = 0; i < 100; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-80, 80), 1, random.NextFloat(-100, 100));
        QuaternionF orientation = RandomHelper.Random.NextQuaternionF();
        float scale = random.NextFloat(0.5f, 1.2f);
        gameObjectService.Objects.Add(new StaticObject(services, "Rock/rock_05", scale, new Pose(position, orientation)));
      }

      // Grass
      for (int i = 0; i < 100; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-20, 20), 0, random.NextFloat(-20, 20));
        Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
        float scale = random.NextFloat(0.5f, 1.2f);
        gameObjectService.Objects.Add(new StaticObject(services, "Grass/Grass", scale, new Pose(position, orientation)));
      }

      // More plants
      for (int i = 0; i < 100; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-20, 20), 0, random.NextFloat(-20, 20));
        Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
        float scale = random.NextFloat(0.5f, 1.2f);
        gameObjectService.Objects.Add(new StaticObject(services, "Parviflora/Parviflora", scale, new Pose(position, orientation)));
      }

      // "Skyscrapers"
      for (int i = 0; i < 20; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(90, 100), 0, random.NextFloat(-100, 100));
        Matrix33F orientation = Matrix33F.CreateRotationY(random.NextFloat(0, ConstantsF.TwoPi));
        Vector3F scale = new Vector3F(random.NextFloat(6, 20), random.NextFloat(10, 100), random.NextFloat(6, 20));
        var meshNode = new MeshNode(boxMesh)
        {
          PoseLocal = new Pose(position, orientation),
          ScaleLocal = scale,
          IsStatic = true,
          UserFlags = 1, // Mark the distant huge objects. Used in render callbacks in the CompositeShadowSample.
        };
        graphicsScreen.Scene.Children.Add(meshNode);
      }

      // "Hills"
      for (int i = 0; i < 20; i++)
      {
        Vector3F position = new Vector3F(random.NextFloat(-90, -100), 0, random.NextFloat(-100, 100));
        Vector3F scale = new Vector3F(random.NextFloat(10, 20), random.NextFloat(10, 30), random.NextFloat(10, 20));
        var meshNode = new MeshNode(sphereMesh)
        {
          PoseLocal = new Pose(position),
          ScaleLocal = scale,
          IsStatic = true,
          UserFlags = 1, // Mark the distant huge objects. Used in render callbacks in the CompositeShadowSample.
        };
        graphicsScreen.Scene.Children.Add(meshNode);
      }
    }
Ejemplo n.º 9
0
        //--------------------------------------------------------------
        #region Creation & Cleanup
        //--------------------------------------------------------------

        /// <summary>
        /// Initializes a new instance of the <see cref="EditorViewModel"/> class using the given
        /// name and service provider.
        /// </summary>
        /// <param name="serviceContainer">The <see cref="ServiceContainer"/>.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="serviceContainer"/> is <see langword="null"/>.
        /// </exception>
        public EditorViewModel(ServiceContainer serviceContainer)
        {
            Logger.Debug("Creating EditorViewModel.");

            if (serviceContainer == null)
                throw new ArgumentNullException(nameof(serviceContainer));

            Services = serviceContainer;

            DockStrategy = new EditorDockStrategy();

            _applicationName = EditorHelper.GetDefaultApplicationName();
            _subtitle = null;

            Extensions = new EditorExtensionCollection();

            InitializeCommandItems();

            WindowActivationCommand = new DelegateCommand(() => OnWindowActivated(EventArgs.Empty));
        }
Ejemplo n.º 10
0
        protected override void Initialize()
        {
            _serviceContainer = new ServiceContainer();
            ServiceLocator.SetLocatorProvider(() => _serviceContainer);

            _serviceContainer.Register(typeof(Game), null, this);
            _serviceContainer.Register(typeof(ContentManager), null, Content);

            // Adds the input service, which manages device input, button presses etc.
            _inputManager = new InputManager(false);
            _serviceContainer.Register(typeof(IInputService), null, _inputManager);

            // Adds the UI service which manages UI screens
            _uiManager = new UIManager(this, _inputManager);
            _serviceContainer.Register(typeof(IUIService), null, _uiManager);

            _graphicsManager = new GraphicsManager(GraphicsDevice, Window, Content);
            Services.AddService(typeof(IGraphicsService), _graphicsManager);
            _serviceContainer.Register(typeof(IGraphicsService), null, _graphicsManager);

            _animationManager = new AnimationManager();
            _serviceContainer.Register(typeof(IAnimationService), null, _animationManager);

            _gameObjectManager = new GameObjectManager();
            _serviceContainer.Register(typeof(IGameObjectService), null, _gameObjectManager);

            _debugRenderer = new DebugRenderer(_graphicsManager, Content.Load<SpriteFont>("UI/MiramonteBold"));
            _serviceContainer.Register(typeof(DebugRenderer), null, _debugRenderer);

            _serviceContainer.Register(typeof(ContentManager), null, Content);

            _spriteBatch = new SpriteBatch(GraphicsDevice);
            _serviceContainer.Register(typeof(SpriteBatch), null, _spriteBatch);

            _gameLog = new GameLog();
            _serviceContainer.Register(typeof(GameLog), null, _gameLog);

            _gameSettings = new GameSettings();
            _serviceContainer.Register(typeof(GameSettings), null, _gameSettings);

            var uiTheme = Content.Load<Theme>("UI/UITheme");
            UIRenderer renderer = new UIRenderer(this, uiTheme);

            var screen = new UIScreen("Default", renderer)
            {
                Background = new Color(0, 0, 0, 0),
            };

            _uiManager.Screens.Add(screen);

            _mainGameComponent = new MainGameComponent(this);
            Components.Add(new StartScreenComponent(this));
            Components.Add(new GamerServicesComponent(this));

            //_updateAnimation = () => _animationManager.Update(_deltaTime);

            base.Initialize();
        }
Ejemplo n.º 11
0
        public MyGame()
        {
            // ----- Service Container
              // The MyGame uses a ServiceContainer, which is a simple service locator
              // and Inversion of Control (IoC) container. (The ServiceContainer can be
              // replaced by any other container that implements System.IServiceProvider.)
              _serviceContainer = new ServiceContainer();
              ServiceLocator.SetLocatorProvider(() => _serviceContainer);

              // ----- Storage
              // Create a "virtual file system" for reading game assets.
              var titleStorage = new TitleStorage("Content");
              var assetsStorage = new ZipStorage(titleStorage, "Content.zip");
              var digitalRuneStorage = new ZipStorage(titleStorage, "DigitalRune.zip");
              var vfsStorage = new VfsStorage();
              vfsStorage.MountInfos.Add(new VfsMountInfo(titleStorage, null));
              vfsStorage.MountInfos.Add(new VfsMountInfo(assetsStorage, null));
              vfsStorage.MountInfos.Add(new VfsMountInfo(digitalRuneStorage, null));

              // ----- Content
              _contentManager = new StorageContentManager(ServiceLocator.Current, vfsStorage);
              _serviceContainer.Register(typeof(ContentManager), null, _contentManager);

              // ----- Graphics
              // Create Direct3D 11 device.
              var presentationParameters = new PresentationParameters
              {
            BackBufferWidth = 1,
            BackBufferHeight = 1,
            // Do not associate graphics device with any window.
            DeviceWindowHandle = IntPtr.Zero,
              };
              var graphicsDevice = new GraphicsDevice(GraphicsAdapter.DefaultAdapter, GraphicsProfile.HiDef, presentationParameters);

              // An IGraphicsDeviceService is required by the MonoGame/XNA content manager.
              _serviceContainer.Register(typeof(IGraphicsDeviceService), null, new DummyGraphicsDeviceManager(graphicsDevice));

              // Create and register the graphics manager.
              _graphicsManager = new GraphicsManager(graphicsDevice, _contentManager);
              _serviceContainer.Register(typeof(IGraphicsService), null, _graphicsManager);

              // ----- Timing
              // We can use the CompositionTarget.Rendering event to trigger our game loop.
              // The CompositionTarget.Rendering event is raised once per frame by WPF.

              // To measure the time that has passed, we use a HighPrecisionClock.
              _clock = new HighPrecisionClock();
              _clock.Start();
              CompositionTarget.Rendering += (s, e) => _clock.Update();

              // The FixedStepTimer reads the clock and triggers the game loop at 60 Hz.
              //_timer = new FixedStepTimer(_clock)
              //{
              //  StepSize = new TimeSpan(166667), // ~60 Hz
              //  AccumulateTimeSteps = false,
              //};
              // The VariableStepTimer reads the clock and triggers the game loop as often
              // as possible.
              _timer = new VariableStepTimer(_clock);
              _timer.TimeChanged += (s, e) => GameLoop(e.DeltaTime);
              _timer.Start();
        }
Ejemplo n.º 12
0
        //--------------------------------------------------------------
        #region Properties & Events
        //--------------------------------------------------------------
        #endregion


        //--------------------------------------------------------------
        #region Creation & Cleanup
        //--------------------------------------------------------------
        #endregion


        //--------------------------------------------------------------
        #region Methods
        //--------------------------------------------------------------

        protected override void OnConfigure()
        {
            if (WindowsHelper.IsInDesignMode)
                return;

            Logger.Info("Configuring editor.");

#if !DEBUG
            PresentationTraceSources.DataBindingSource.Switch.Level = SourceLevels.Critical;
#endif

            _serviceContainer = new ServiceContainer();

            // Configure general services.
            _serviceContainer.Register(typeof(IWindowService), null, typeof(WindowManager));

            // Configure editor.
            _editor = new EditorViewModel(_serviceContainer)
            {
                ApplicationName = ApplicationName,
                ApplicationIcon = BitmapFrame.Create(new Uri("pack://application:,,,/DigitalRune.Editor;component/Resources/Raido.ico", UriKind.RelativeOrAbsolute))
            };
            // Core extensions
            _editor.Extensions.Add(new CommandExtension());
            _editor.Extensions.Add(new LayoutExtension());
            _editor.Extensions.Add(new AboutExtension());
            _editor.Extensions.Add(new OptionsExtension());
            _editor.Extensions.Add(new PrintExtension());
            _editor.Extensions.Add(new QuickLaunchExtension());
            _editor.Extensions.Add(new ThemeExtension());
            _editor.Extensions.Add(new StatusExtension());
            _editor.Extensions.Add(new SearchExtension());

            // Common tool windows.
            _editor.Extensions.Add(new OutputExtension());
            _editor.Extensions.Add(new ErrorExtension());
            _editor.Extensions.Add(new OutlineExtension());
            _editor.Extensions.Add(new PropertiesExtension());

            // Document extensions.
            _documentExtension = new DocumentExtension();
            _editor.Extensions.Add(_documentExtension);
            _editor.Extensions.Add(new TextExtension());
            _editor.Extensions.Add(new ShaderExtension());
            _editor.Extensions.Add(new TexturesExtension());
            _editor.Extensions.Add(new ModelsExtension());

            // Other extensions.
            _editor.Extensions.Add(new DiagnosticsExtension());
            _editor.Extensions.Add(new ColorExtension());
            _editor.Extensions.Add(new GameExtension());
            _editor.Extensions.Add(new TestExtension0());

            try
            {
                bool success = _editor.Initialize();
                if (!success)
                {
                    // The editor could not be configured or command line arguments caused the
                    // editor to shut down (e.g. if "--help" was specified).
                    Application.Shutdown(_editor.ExitCode);
                    return;
                }
            }
            catch (Exception exception)
            {
                Logger.Error(exception, "Editor configuration failed.");

                _configurationFailed = true;
                Environment.ExitCode = ExitCodeConfigurationFailed;

                ExceptionHelper.ShowException(exception, ApplicationName, Email);
            }
        }
Ejemplo n.º 13
0
    // Initializes services and adds game components.
    protected override void Initialize()
    {
#if WINDOWS || WINDOWS_UWP || XBOX
      if (GraphicsDevice.GraphicsProfile == GraphicsProfile.Reach)
      {
        throw new NotSupportedException(
          "The DigitalRune Samples and Content for Windows, Universal Windows Apps and Xbox 360 are " +
          "designed for the HiDef graphics profile. A graphics cards supporting DirectX 10.0 or better " +
          "is required.");
      }
#endif

      // ----- Service Container
      // The DigitalRune ServiceContainer is an "inversion of control" container.
      // All game services (such as input, graphics, physics, etc.) are registered
      // in this container. Other game components can access these services via lookup
      // in the service container.
      // The DigitalRune ServiceContainer replaces the XNA GameServiceContainer (see 
      // property Game.Services).

      // Note: The DigitalRune libraries do not require the use of the ServiceContainer
      // or any other IoC container. The ServiceContainer is only used in the sample
      // for convenience - but it is not mandatory.
      _services = new ServiceContainer();

      // The service container is either passed directly to the game components
      // or accessed through the global variable ServiceLocator.Current.
      // The following call makes the service container publicly available in 
      // ServiceLocator.Current.
      ServiceLocator.SetLocatorProvider(() => _services);

      // ----- Storage
      // For XNA the assets are stored in the following folders:
      //
      //   <gameLocation>/
      //     Content/
      //       DigitalRune/
      //         ... DigitalRune assets ...
      //       ... other assets ...
      //
      // For MonoGame the assets (*.xnb files) are stored in ZIP packages. The
      // sample assets are stored in "Content/Content.zip" and the DigitalRune
      // assets are stored in "Content/DigitalRune.zip".
      //
      //   <gameLocation>/
      //     Content/
      //       Content.zip
      //       DigitalRune.zip
      //
      // DigitalRune introduces the concept of "storages". Storages can be used
      // to access files on disk or files stored in packages (e.g. ZIP archives).
      // These storages can be mapped into a "virtual file system", which makes
      // it easier to write portable code. (The game logic can read the files
      // from the virtual file system and does not need to know the specifics
      // about the platform.)
      //
      // The virtual files system should look like this:
      //
      //   /                                     <-- root of virtual file system
      //       DigitalRune/
      //           ... DigitalRune assets ...
      //       ... other assets ...

      // The VfsStorage creates a virtual file system.
      var vfsStorage = new VfsStorage();

      // The TitleStorage reads files from the game's default storage location.
      // --> Create a TitleStorage that reads files from "<gameLocation>/Content".
      var titleStorage = new TitleStorage("Content");

#if MONOGAME
      // A ZipStorage can be used to access files inside a ZIP archive.
      // --> Mount the sample assets to the root of the virtual file system.
      var assetsStorage = new ZipStorage(titleStorage, "Content.zip");
      vfsStorage.MountInfos.Add(new VfsMountInfo(assetsStorage, null));

#if !ANDROID && !IOS && !LINUX && !MACOS
      // --> Mount the DigitalRune assets to the root of the virtual file system.
      var drStorage = new ZipStorage(titleStorage, "DigitalRune.zip");
      vfsStorage.MountInfos.Add(new VfsMountInfo(drStorage, null));
#endif
#endif

      // Finally, map the TitleStorage to the root of the virtual file system.
      // (The TitleStorage is added as the last mount point. The ZIP archives
      // have priority.)
      vfsStorage.MountInfos.Add(new VfsMountInfo(titleStorage, null));

      // Register the virtual file system as a service.
      _services.Register(typeof(IStorage), null, vfsStorage);

      // ----- Content Managers
      // The GraphicsDeviceManager needs to be registered in the service container.
      // (This is required by the XNA content managers.)
      _services.Register(typeof(IGraphicsDeviceService), null, _graphicsDeviceManager);
      _services.Register(typeof(GraphicsDeviceManager), null, _graphicsDeviceManager);

      // Register a default, shared content manager.
      // The new StorageContentManager can be used to read assets from the virtual
      // file system. (Replaces the content manager stored in Game.Content.)
      Content = new StorageContentManager(_services, vfsStorage);
      _services.Register(typeof(ContentManager), null, Content);

      // Create and register content manager that will be used to load the GUI.
#if !MONOGAME
      var uiContentManager = new ContentManager(_services, "Content");
#else
      var uiContentManager = new StorageContentManager(_services, assetsStorage);
#endif
      _services.Register(typeof(ContentManager), "UIContent", uiContentManager);

      // Create content manager that will be used exclusively by the graphics service
      // to load the pre-built effects and resources of DigitalRune.Graphics. (We
      // could use Game.Content, but it is recommended to separate the content. This 
      // allows to unload the content of the samples without unloading the other 
      // content.)
      var graphicsContentManager = new StorageContentManager(_services, vfsStorage);

      // ----- Initialize Services
      // Register the game class.
      _services.Register(typeof(Microsoft.Xna.Framework.Game), null, this);
      _services.Register(typeof(SampleGame), null, this);

#if XBOX
      // On Xbox, we use the XNA gamer services (e.g. for text input).
      Components.Add(new GamerServicesComponent(this));
#endif

      // Input
#if XBOX
      const bool useGamerServices = true;
#else
      const bool useGamerServices = false;
#endif
      _inputManager = new InputManager(useGamerServices);
      _services.Register(typeof(IInputService), null, _inputManager);

      // Graphics
      _graphicsManager = new GraphicsManager(GraphicsDevice, Window, graphicsContentManager);
      _services.Register(typeof(IGraphicsService), null, _graphicsManager);

      // GUI
      _uiManager = new UIManager(this, _inputManager);
      _services.Register(typeof(IUIService), null, _uiManager);

      // Animation
      _animationManager = new AnimationManager();
      _services.Register(typeof(IAnimationService), null, _animationManager);

      // Particle simulation
      _particleSystemManager = new ParticleSystemManager();
      _services.Register(typeof(IParticleSystemService), null, _particleSystemManager);

      // Physics simulation
      ResetPhysicsSimulation();

      // Game logic
      _gameObjectManager = new GameObjectManager();
      _services.Register(typeof(IGameObjectService), null, _gameObjectManager);

      // Profiler
      _profiler = new HierarchicalProfiler("Main");
      _services.Register(typeof(HierarchicalProfiler), "Main", _profiler);

      // Initialize delegates for running tasks in parallel.
      // (Creating delegates allocates memory, therefore we do this only once and
      // cache the delegates.)
      _updateAnimation = () => _animationManager.Update(_deltaTime);
      _updatePhysics = () => _simulation.Update(_deltaTime);
      _updateParticles = () => _particleSystemManager.Update(_deltaTime);

      // SampleFramework
      // The SampleFramework automatically discovers all samples using reflection, provides 
      // controls for switching samples and starts the initial sample.
#if KINECT
      var initialSample = typeof(Kinect.KinectSkeletonMappingSample);
#elif WINDOWS || WINDOWS_UWP
      var initialSample = typeof(Graphics.DeferredLightingSample);
#else
      var initialSample = typeof(Graphics.BasicEffectSample);
#endif
      _sampleFramework = new SampleFramework(this, initialSample);
      _services.Register(typeof(SampleFramework), null, _sampleFramework);

      base.Initialize();
    }