Beispiel #1
0
 public Shader( IGraphicsDevice graphicsDevice, Stream stream, Graphics.ShaderType shaderType )
     : this(graphicsDevice, shaderType)
 {
     byte [] shaderCode = new byte [ stream.Length ];
     stream.Read ( shaderCode, 0, shaderCode.Length );
     SetShaderAndCompile ( Encoding.UTF8.GetString ( shaderCode ) );
 }
Beispiel #2
0
 internal void Draw(IGraphicsDevice graphicsDevice)
 {
     if (graphicsDevice != null)
     {
         graphicsDevice.DrawUserPrimitives(PrimitiveType.LineStrip, _vertices, 0, _vertices.Length - 1);
     }
 }
Beispiel #3
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="DepthStencilStates" /> class.
 /// </summary>
 /// <param name="graphicsDevice"> The graphics device. </param>
 internal DepthStencilStates(IGraphicsDevice graphicsDevice)
 {
     Default               = Create(graphicsDevice.Device, nameof(Default), true, true, false);
     DepthRead             = Create(graphicsDevice.Device, nameof(DepthRead), true, false, false);
     None                  = Create(graphicsDevice.Device, nameof(None), false, false, false);
     DefaultStencilEnabled = Create(graphicsDevice.Device, nameof(DefaultStencilEnabled), true, true, true);
 }
Beispiel #4
0
 public AnimatedGameWindow(IPlatformWindow window, ISwapChain swapChain, IGraphicsDevice device)
 {
     this.Window    = window;
     this.swapChain = swapChain;
     this.Device    = device;
     this.gameTimer = new GameTimer();
 }
Beispiel #5
0
        public IGraphicsDevice CreateDevice(DotGame.Graphics.DeviceCreationFlags flags)
        {
            if (graphicsDevice != null)
            {
                return(graphicsDevice);
            }

            SwapChainDescription swapChainDescription = new SwapChainDescription()
            {
                BufferCount       = 1,
                Flags             = SwapChainFlags.AllowModeSwitch,
                IsWindowed        = true,
                ModeDescription   = new ModeDescription(Width, Height, new Rational(60, 1), Format.R8G8B8A8_UNorm),
                OutputHandle      = Handle,
                SampleDescription = new SampleDescription(1, 0),
                SwapEffect        = SwapEffect.Discard,
                Usage             = Usage.RenderTargetOutput
            };

            Device device;

            Device.CreateWithSwapChain(DriverType.Hardware, EnumConverter.Convert(flags), swapChainDescription, out device, out swapChain);

            Factory factory = swapChain.GetParent <Factory>();

            factory.MakeWindowAssociation(Handle, WindowAssociationFlags.IgnoreAll);

            graphicsDevice = new GraphicsDevice(this, device, swapChain, flags);

            this.Show();
            return(graphicsDevice);
        }
Beispiel #6
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="SpriteBatch" /> class.
        /// </summary>
        /// <param name="graphicsDevice"> The graphics device. </param>
        /// <param name="center">         (Optional) True to center the coordinate system in the viewport. </param>
        /// <param name="sortAlgorithm">  (Optional) The sort algorithm. </param>
        /// <exception cref="ArgumentException">
        ///     Thrown when one or more arguments have unsupported or
        ///     illegal values.
        /// </exception>
        /// <exception cref="NullReferenceException"> Thrown when a value was unexpectedly null. </exception>
        public SpriteBatch(IGraphicsDevice graphicsDevice,
                           bool center = false,
                           SpriteSortAlgorithm sortAlgorithm = SpriteSortAlgorithm.MergeSort)
        {
            _device  = graphicsDevice.Device;
            _context = graphicsDevice.DeviceContext;

            _center = center;

            _spriteSort = sortAlgorithm switch
            {
                SpriteSortAlgorithm.MergeSort => new SpriteMergeSort(),
                _ => throw new ArgumentException($"invalid sort algorithm ({sortAlgorithm})", nameof(sortAlgorithm))
            };

            _defaultBlendState                    = graphicsDevice.BlendStates.AlphaBlend;
            _defaultSamplerState                  = graphicsDevice.SamplerStates.LinearWrap;
            _defaultDepthStencilState             = graphicsDevice.DepthStencilStates.None;
            _defaultRasterizerState               = graphicsDevice.RasterizerStates.CullBackDepthClipOff;
            _defaultRasterizerScissorEnabledState = graphicsDevice.RasterizerStates.CullBackDepthClipOffScissorEnabled;

            _whiteTexture = graphicsDevice.Textures.White;

            _indexBuffer = IndexBuffer.Create(graphicsDevice, s_indices);

            Assembly assembly = Assembly.GetExecutingAssembly();

            using (Stream stream =
                       assembly.GetManifestResourceStream($"{assembly.GetName().Name}.{Shaders.POSITION_COLOR_TEXTURE}") ??
                       throw new NullReferenceException($"{assembly.GetName().Name}.{Shaders.POSITION_COLOR_TEXTURE}"))
            {
                Shader.Shader.Group group =
                    (_shader = ShaderFileLoader.FromStream(graphicsDevice, stream) ??
                               throw new NullReferenceException(nameof(ShaderFileLoader.FromStream)))["DEFAULT"];
        internal RenderContext(IGraphicsFacade graphicsFacade)
        {
            _graphicsFacade = graphicsFacade;
            _graphicsDevice = graphicsFacade.Device;
            _techniques     = graphicsFacade.Techniques;
            _presets        = graphicsFacade.Presets;

            _sceneBuffer             = _graphicsDevice.CreateConstantBuffer <SceneConstantBufferData>(1);
            _batchBuffer             = _graphicsDevice.CreateConstantBuffer <BatchConstantBufferData>(1);
            _textureDescriptorBuffer = _graphicsDevice.CreateConstantBuffer <TextureDescriptorConstantBufferData>(kBaseTextureSlotId + kTextureBindLimit);
            _instancingBuffers       = new List <IBuffer <RenderJobDescription> >();

            const int kMaxPreallocatedInstanceBufferPower = 20;

            for (var i = 0; i <= kMaxPreallocatedInstanceBufferPower; i++)
            {
                _instancingBuffers.Add(_graphicsDevice.CreateVertexBuffer <RenderJobDescription>(1 << i));
            }

            (_gBufferRtvs, _gBufferSrv, _gBufferSrvs) = _graphicsDevice.CreateScreenSizeRenderTarget(2);
            (_gBufferDsv, _gBufferDepthSrv)           = _graphicsDevice.CreateScreenSizeDepthTarget();
            (_spotlightDescriptionsBuffer, _spotlightDescriptionsBufferSrv) = _graphicsDevice.CreateStructuredBufferAndView <SpotlightDescription>(256);
            (_materialResourcesBuffer, _materialResourcesBufferSrv)         = _graphicsDevice.CreateStructuredBufferAndView <InternalMaterialResourcesDescription>(kMaterialBufferCount);
            (_lightDepthTexture, _lightDepthStencilViews, _lightShaderResourceView, _lightShaderResourceViews) = _graphicsDevice.CreateDepthTextureAndViews(10, new Size(kShadowMapWidthHeight, kShadowMapWidthHeight));

            Trace.Assert(Utilities.SizeOf <SpotlightInfo>() == SpotlightInfo.Size);
            Trace.Assert(Utilities.SizeOf <AtlasLocation>() == AtlasLocation.SIZE);
            Trace.Assert(Utilities.SizeOf <SpotlightDescription>() == SpotlightDescription.Size);
            Trace.Assert(Utilities.SizeOf <RenderJobDescription>() == RenderJobDescription.Size);
            Trace.Assert(Utilities.SizeOf <InternalMaterialResourcesDescription>() == InternalMaterialResourcesDescription.Size);

            water = new WaterWip(graphicsFacade);
            water.Initialize();
        }
Beispiel #8
0
        public static void Install(this REngine engine, IGraphicsDevice device)
        {
            var adapter = new GraphicsDeviceAdapter(device);

            engine.Disposing += (sender, e) => adapter.Dispose();
            adapter.SetEngine(engine);
        }
Beispiel #9
0
 public void LauncherFinalize( IWindow window, IGraphicsDevice graphicsDevice, IAudioDevice audioDevice )
 {
     if ( audioDevice != null )
         audioDevice.Dispose ();
     graphicsDevice.Dispose ();
     window.Dispose ();
 }
Beispiel #10
0
 /// <summary>
 ///     Creates a new <see cref="ConstantBuffer" />.
 /// </summary>
 /// <typeparam name="T"> Generic type parameter. </typeparam>
 /// <param name="graphicsDevice"> The graphics device. </param>
 /// <param name="resourceUsage">  (Optional) The resource usage. </param>
 /// <param name="cpuAccessFlags"> (Optional) The CPU access flags. </param>
 /// <returns>
 ///     A <see cref="ConstantBuffer" />.
 /// </returns>
 public static unsafe ConstantBuffer Create <T>(IGraphicsDevice graphicsDevice,
                                                ResourceUsage resourceUsage   = ResourceUsage.Default,
                                                CpuAccessFlags cpuAccessFlags = CpuAccessFlags.None)
     where T : unmanaged
 {
     return(Create(graphicsDevice, sizeof(T), resourceUsage, cpuAccessFlags));
 }
        /// <inheritdoc />
        public object?ReadContent(IContentManager contentManager, ref ContentReaderParameters parameters)
        {
            SpriteFont font = ContentSerializer.Read <SpriteFont>(parameters.Stream);

            if (font.ImageData.Length <= 0)
            {
                return(null);
            }

            IGraphicsDevice graphicsDevice =
                contentManager.ServiceRegistry.GetService <IGraphicsDevice>();

            try
            {
                using (MemoryStream ms = new MemoryStream(font.ImageData)
                {
                    Position = 0
                })
                {
                    font.Texture = Texture.Load(graphicsDevice.Device, ms) ??
                                   throw new NullReferenceException($"{nameof(font.Texture)}");
                }
            }
            catch { return(null); }

            return(font);
        }
        /// <inheritdoc />
        public object?ReadContent(IContentManager contentManager, ref ContentReaderParameters parameters)
        {
            IGraphicsDevice graphicsDevice =
                contentManager.ServiceRegistry.GetService <IGraphicsDevice>();

            return(Texture.Load(graphicsDevice.Device, parameters.Stream));
        }
 protected override void OnEnable()
 {
     this.device               = Rendering.GraphicsDevice;
     this.effectBloomCombine   = EffectInstance.Create(EffectResourceBloomCombine);
     this.effectBloomExtract   = EffectInstance.Create(EffectResourceBloomExtract);
     this.effectBlurHorizontal = EffectInstance.Create(EffectResourceGaussianBlur);
     this.effectBlurVertical   = EffectInstance.Create(EffectResourceGaussianBlur);
 }
Beispiel #14
0
        // GamePlatform
        // GameWindow
        // SoundDevice
        // ResourceManagement
        // InputDevices
        public Game(IConfiguration configuration, IGraphicsDevice graphicsDevice, IResourceManager resourceManager, IInputManager inputManager)
        {
            this.Configuration   = configuration;
            this.GraphicsDevice  = graphicsDevice;
            this.ResourceManager = resourceManager;

            this.GameComponents.Add((InputManager)inputManager);
        }
Beispiel #15
0
        public Nes(IGraphicsDevice graphicsDevice, IInputDevice inputDevice, IAudioDevice audioDevice)
        {
            _graphicsDevice = graphicsDevice;
            _inputDevice    = inputDevice;
            _audioDevice    = audioDevice;

            Initialization();
        }
Beispiel #16
0
 public Texture2D( IGraphicsDevice graphicsDevice, int width, int height )
 {
     Size = new Vector2 ( width, height );
     texture = GL.GenTexture ();
     GL.BindTexture ( TextureTarget.Texture2D, texture );
     GL.TexImage2D ( TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba8, width, height, 0, PixelFormat.Bgra, PixelType.UnsignedByte, IntPtr.Zero );
     GL.BindTexture ( TextureTarget.Texture2D, 0 );
 }
Beispiel #17
0
 public Texture2D( IGraphicsDevice graphicsDevice, int width, int height )
 {
     Size = new Vector2 ( width, height );
     texture = GL.GenTexture ();
     GL.BindTexture ( All.Texture2D, texture );
     GL.TexImage2D ( All.Texture2D, 0, 32856, width, height, 0, All.BgraImg, All.UnsignedByte, IntPtr.Zero );
     GL.BindTexture ( All.Texture2D, 0 );
 }
Beispiel #18
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="Textures" /> class.
 /// </summary>
 /// <param name="graphicsDevice"> The graphics device. </param>
 /// <exception cref="NullReferenceException"> Thrown when a value was unexpectedly null. </exception>
 internal Textures(IGraphicsDevice graphicsDevice)
 {
     using (MemoryStream ms = new MemoryStream(System.Convert.FromBase64String(WHITE_TEXTURE_BASE64)))
     {
         _white = Texture.Load(graphicsDevice.Device, ms) ??
                  throw new NullReferenceException($"{nameof(White)}");
     }
 }
Beispiel #19
0
        public void LauncherInitialize( out IWindow window, out IGraphicsDevice graphicsDevice, out IAudioDevice audioDevice )
        {
            window = new Window ( frame );
            graphicsDevice = new GraphicsDevice ( window );
            audioDevice = new AudioDevice ( window );

            IsInitialized = true;
        }
Beispiel #20
0
 public GamePlatform(
     IGraphicsDevice graphicsDevice,
     IResourceManager resourceManager,
     IInputManager inputManager)
 {
     this.GraphicsDevice  = graphicsDevice ?? throw new ArgumentNullException(nameof(graphicsDevice));
     this.ResourceManager = resourceManager ?? throw new ArgumentNullException(nameof(resourceManager));
     this.InputManager    = inputManager ?? throw new ArgumentNullException(nameof(inputManager));
 }
Beispiel #21
0
        public TextureFactory(IGraphicsDevice device)
        {
            if (device == null)
            {
                throw new ArgumentNullException("device");
            }

            this.device = device;
        }
Beispiel #22
0
 public RenderBuffer( IGraphicsDevice graphicsDevice, int width, int height )
     : base(graphicsDevice, width, height, SharpDX.Direct3D9.Usage.RenderTarget)
 {
     if ( width == 0 ) width = 1;
     if ( height == 0 ) height = 1;
     SharpDX.Direct3D9.Surface surface = ( Handle as SharpDX.Direct3D9.Texture ).GetSurfaceLevel ( 0 );
     rts = new SharpDX.Direct3D9.RenderToSurface ( graphicsDevice.Handle as SharpDX.Direct3D9.Device,
         surface.Description.Width, surface.Description.Height, surface.Description.Format, true, SharpDX.Direct3D9.Format.D24S8 );
 }
Beispiel #23
0
        public SpriteBatch(IGraphicsDevice graphicsDevice)
        {
            this.GraphicsDevice = graphicsDevice;

            this.batches  = new List <BatchGroup>();
            this.quads    = new List <Quad>();
            this.vertices = new List <IVertexType>();
            this.indices  = new List <int>();
        }
Beispiel #24
0
 public Texture2D( IGraphicsDevice graphicsDevice, int width, int height )
 {
     if ( width == 0 ) width = 1;
     if ( height == 0 ) height = 1;
     texture = new SharpDX.Direct3D9.Texture ( graphicsDevice.Handle as SharpDX.Direct3D9.Device, width, height,
         1, SharpDX.Direct3D9.Usage.AutoGenerateMipMap, SharpDX.Direct3D9.Format.A8R8G8B8, SharpDX.Direct3D9.Pool.Managed );
     texture.FilterTexture ( 0, SharpDX.Direct3D9.Filter.Point );
     Size = new Vector2 ( width, height );
 }
Beispiel #25
0
        internal static void Initialize(WindowMode windowMode)
        {
            var resolution = GetResolution(windowMode);

            var renderer     = Game.Settings.Server.Dedicated ? "Null" : Game.Settings.Graphics.Renderer;
            var rendererPath = Platform.ResolvePath(".", "OpenRA.Renderer." + renderer + ".dll");

            device = CreateDevice(Assembly.LoadFile(rendererPath), resolution.Width, resolution.Height, windowMode);
        }
Beispiel #26
0
 public void LauncherFinalize( IWindow window, IGraphicsDevice graphicsDevice, IAudioDevice audioDevice )
 {
     if ( updateThread != null )
         updateThread.Abort ();
     updateThread = null;
     if ( audioDevice != null )
         audioDevice.Dispose ();
     graphicsDevice.Dispose ();
     window.Dispose ();
 }
Beispiel #27
0
        public void LauncherInitialize( out IWindow window, out IGraphicsDevice graphicsDevice, out IAudioDevice audioDevice )
        {
            window = new Window ( context );
            graphicsDevice = new GraphicsDevice ( window );
            audioDevice = new AudioDevice ( window );

            ( context as Android.App.Activity ).SetContentView ( window.Handle as Android.Views.View );

            IsInitialized = true;
        }
Beispiel #28
0
 public GraphicsDeviceAdapter(IGraphicsDevice device)
 {
     if (device == null)
     {
         throw new ArgumentNullException("device");
     }
     this.device          = device;
     this.delegateHandles = new List <GCHandle>();
     this.gdd             = IntPtr.Zero;
 }
Beispiel #29
0
        public IndexBuffer( IGraphicsDevice graphicsDevice, int indexCount )
        {
            Length = indexCount;

            GL.GenBuffers ( 1, out indexBuffer );

            GL.BindBuffer ( BufferTarget.ElementArrayBuffer, indexBuffer );
            GL.BufferData ( BufferTarget.ElementArrayBuffer, new IntPtr ( Length * sizeof ( int ) ), IntPtr.Zero, BufferUsageHint.StaticDraw );
            GL.BindBuffer ( BufferTarget.ElementArrayBuffer, 0 );
        }
Beispiel #30
0
 protected Texture2D( IGraphicsDevice graphicsDevice, int width, int height, SharpDX.Direct3D9.Usage usage, int mipmapLevel = 1 )
 {
     if ( width == 0 ) width = 1;
     if ( height == 0 ) height = 1;
     texture = new SharpDX.Direct3D9.Texture ( graphicsDevice.Handle as SharpDX.Direct3D9.Device, width, height,
         mipmapLevel, usage, SharpDX.Direct3D9.Format.A8R8G8B8,
         usage.HasFlag ( SharpDX.Direct3D9.Usage.RenderTarget ) ? SharpDX.Direct3D9.Pool.Default : SharpDX.Direct3D9.Pool.Managed );
     texture.FilterTexture ( 0, SharpDX.Direct3D9.Filter.Point );
     Width = width;
     Height = height;
 }
Beispiel #31
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="BlendStates" /> class.
 /// </summary>
 /// <param name="graphicsDevice"> The graphics device. </param>
 internal BlendStates(IGraphicsDevice graphicsDevice)
 {
     Additive   = Create(graphicsDevice.Device, nameof(Additive), BlendOption.SourceAlpha, BlendOption.One, true);
     AlphaBlend = Create(
         graphicsDevice.Device, nameof(AlphaBlend), BlendOption.One, BlendOption.InverseSourceAlpha, true);
     NonPremultiplied = Create(
         graphicsDevice.Device, nameof(NonPremultiplied), BlendOption.SourceAlpha,
         BlendOption.InverseSourceAlpha, true);
     Opaque  = Create(graphicsDevice.Device, nameof(Opaque), BlendOption.One, BlendOption.Zero, true);
     Default = Create(graphicsDevice.Device, nameof(Default), BlendStateDescription.Default());
 }
Beispiel #32
0
        public GraphicsContext( IGraphicsDevice graphicsDevice, bool isImmediate )
        {
            GraphicsDevice = graphicsDevice;
            CullMode = CullMode.ClockWise;

            if ( isImmediate )
                graphicsContext = OpenTK.Graphics.GraphicsContext.CurrentContext as OpenTK.Graphics.GraphicsContext;
            else
                graphicsContext = new OpenTK.Graphics.GraphicsContext ( new OpenTK.Graphics.GraphicsMode ( new OpenTK.Graphics.ColorFormat ( 8, 8, 8, 8 ), 24, 8 ),
                    ( graphicsDevice.Handle as OpenTK.GameWindow ).WindowInfo );
        }
Beispiel #33
0
 public Game1(
     IConfiguration configuration,
     IGraphicsDevice graphicsDevice,
     IResourceManager resourceManager,
     IInputManager inputManager)
     : base(configuration, graphicsDevice, resourceManager, inputManager)
 {
     if (inputManager.HasKeyboard)
     {
         this.keyboard = inputManager.Keyboard;
     }
 }
Beispiel #34
0
        internal static void Initialize(WindowMode windowMode)
        {
            if (Platform.CurrentPlatform == PlatformType.OSX)
            {
                FixOSX();
            }

            var resolution   = GetResolution(windowMode);
            var rendererPath = Path.GetFullPath("OpenRA.Renderer.{0}.dll".F(Game.Settings.Graphics.Renderer));

            device = CreateDevice(Assembly.LoadFile(rendererPath), resolution.Width, resolution.Height, windowMode);
        }
Beispiel #35
0
 private Shader( IGraphicsDevice graphicsDevice, SharpDX.Direct3D9.ShaderBytecode function, Graphics.ShaderType shaderType )
 {
     ShaderType = shaderType;
     switch ( ShaderType )
     {
         case Graphics.ShaderType.VertexShader:
             Handle = new SharpDX.Direct3D9.VertexShader ( graphicsDevice.Handle as SharpDX.Direct3D9.Device, function );
             break;
         case Graphics.ShaderType.PixelShader:
             Handle = new SharpDX.Direct3D9.PixelShader ( graphicsDevice.Handle as SharpDX.Direct3D9.Device, function );
             break;
     }
 }
Beispiel #36
0
        /// <summary>
        /// Constructor.
        /// </summary>
        public Starfield(IGraphicsDevice graphicsDevice)
        {
            if (graphicsDevice == null)
                throw new ArgumentNullException("graphicsDevice");

            this.graphicsDevice = graphicsDevice;

            this.stars = new Star[100];
            for (int i = 0; i < this.stars.Length; i++)
                this.stars[i] = new Star();

            this.random = new Random();
        }
Beispiel #37
0
        /// <inheritdoc />
        protected override void OnInitialize(IServiceRegistry registry)
        {
            IGameWindow gameWindow = registry.GetService <IGameWindow>();

            _title      = gameWindow.Title;
            _gameWindow = gameWindow;

            IGraphicsDevice graphicsDevice = registry.GetService <IGraphicsDevice>();

            _spriteBatch = new SpriteBatch(graphicsDevice);

            _gpuName = graphicsDevice.Adapter?.Desc3.Description ?? "<unknown>";
        }
Beispiel #38
0
        public RenderingScope(IGraphicsDevice device)
        {
            if (device == null)
            {
                throw new ArgumentNullException("device");
            }

            this.device = device;

            // state lists
            this.enabledVertexAttribArrays = new List <uint>(10);
            this.enabledBufferTargets      = new List <uint>(2);
        }
Beispiel #39
0
 public Texture3D( IGraphicsDevice graphicsDevice, ImageInfo [] imageInfo, Color? colorKey = null, int mipmapLevel = 1 )
 {
     MakeTexture ( imageInfo [ 0 ].Width, imageInfo [ 0 ].Height, imageInfo.Length );
     Color [] colours = new Color [ imageInfo [ 0 ].Width * imageInfo [ 0 ].Height * imageInfo.Length ];
     int index = 0;
     foreach ( ImageInfo i in imageInfo )
     {
         Color [] decoded = i.GetPixels ( colorKey );
         decoded.CopyTo ( colours, index );
         index += decoded.Length;
     }
     Buffer = colours;
     GenerateMipmap ( mipmapLevel );
 }
Beispiel #40
0
        public GameWindow(IPlatformWindow platformWindow, IGraphicsDevice graphicsDevice, IGame game)
        {
            this.GraphicsDevice = graphicsDevice ?? throw new ArgumentNullException(nameof(graphicsDevice));
            this.game           = game ?? throw new ArgumentNullException(nameof(game));

            this.platformWindow                     = platformWindow ?? throw new ArgumentNullException(nameof(platformWindow));
            this.platformWindow.SizeChanged        += this.OnSizeChanged;
            this.platformWindow.Activated          += this.OnActivated;
            this.platformWindow.VisibilityChanged  += this.OnVisibilityChanged;
            this.platformWindow.OrientationChanged += this.OnOrientationChanged;
            this.platformWindow.DpiChanged         += this.OnDpiChanged;

            this.gameTimer.IsFixedTimeStep = false;
        }
Beispiel #41
0
        public RenderBuffer( IGraphicsDevice graphicsDevice, int width, int height )
            : base(graphicsDevice, width, height)
        {
            GL.GenFramebuffers ( 1, out depthBuffer );
            GL.BindFramebuffer ( FramebufferTarget.Framebuffer, depthBuffer );
            GL.RenderbufferStorage ( RenderbufferTarget.Renderbuffer, RenderbufferStorage.Depth24Stencil8, width, height );

            GL.GenFramebuffers ( 1, out frameBuffer );
            GL.BindFramebuffer ( FramebufferTarget.Framebuffer, frameBuffer );
            GL.FramebufferRenderbuffer ( FramebufferTarget.Framebuffer, FramebufferAttachment.DepthStencilAttachment, RenderbufferTarget.Renderbuffer, depthBuffer );
            GL.FramebufferTexture2D ( FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, TextureTarget.Texture2D, texture, 0 );

            GL.BindFramebuffer ( FramebufferTarget.Framebuffer, 0 );
        }
Beispiel #42
0
 /// <summary>
 ///     Creates a new <see cref="ConstantBuffer" /> with the specified size in bytes.
 /// </summary>
 /// <param name="graphicsDevice"> The graphics device. </param>
 /// <param name="sizeInBytes">    The size in bytes. </param>
 /// <param name="resourceUsage">  (Optional) The resource usage. </param>
 /// <param name="cpuAccessFlags"> (Optional) The CPU access flags. </param>
 /// <returns>
 ///     A <see cref="ConstantBuffer" />.
 /// </returns>
 /// <remarks>
 ///     The <paramref name="sizeInBytes" /> must be a multiple of 16,
 ///     if not it will be calculated to the minimum multiple of 16 fitting it in.
 ///     e.g.
 ///     - a size in bytes of 11 will be 16.
 ///     - a size in bytes of 23 will be 32.
 ///     - a size in bytes of 80 will be 80.
 ///     > see https://docs.microsoft.com/de-de/windows/win32/api/d3d11/ns-d3d11-d3d11_buffer_desc#remarks
 /// </remarks>
 public static ConstantBuffer Create(IGraphicsDevice graphicsDevice,
                                     int sizeInBytes,
                                     ResourceUsage resourceUsage   = ResourceUsage.Default,
                                     CpuAccessFlags cpuAccessFlags = CpuAccessFlags.None)
 {
     return(new ConstantBuffer(
                new Buffer(
                    graphicsDevice.Device,
                    Math2.Ceiling(sizeInBytes / 16.0f) * 16,
                    resourceUsage,
                    BindFlags.ConstantBuffer,
                    cpuAccessFlags,
                    ResourceOptionFlags.None,
                    0)));
 }
Beispiel #43
0
        public Renderer(GraphicsSettings graphicSettings, IGraphicsDevice device)
        {
            this.Device    = device;
            TempBufferSize = graphicSettings.BatchSize;
            SheetSize      = graphicSettings.SheetSize;

            WorldModelRenderer      = new ModelRenderer(this, Device.CreateShader("model"));
            WorldSpriteRenderer     = new SpriteRenderer(this, Device.CreateShader("shp"));
            WorldRgbaColorRenderer  = new RgbaColorRenderer(this, Device.CreateShader("color"));
            WorldRgbaSpriteRenderer = new SpriteRenderer(this, Device.CreateShader("rgba"));
            SpriteRenderer          = new SpriteRenderer(this, Device.CreateShader("shp"));
            RgbaColorRenderer       = new RgbaColorRenderer(this, Device.CreateShader("color"));
            RgbaSpriteRenderer      = new SpriteRenderer(this, Device.CreateShader("rgba"));
            tempBuffer = Device.CreateVertexBuffer(TempBufferSize);
        }
Beispiel #44
0
        public Ship(IGraphicsDevice graphics, IKeyboard keyboard, IGamePad gamePad)
            : base()
        {
            if (graphics == null)
                throw new ArgumentNullException("graphics");

            if (keyboard == null)
                throw new ArgumentNullException("keyboard");

            if (gamePad == null)
                throw new ArgumentNullException("gamePad");

            this.graphics = graphics;
            this.keyboard = keyboard;
            this.gamePad = gamePad;
        }
Beispiel #45
0
 private Shader( IGraphicsDevice graphicsDevice, SharpDX.D3DCompiler.ShaderBytecode function, Graphics.ShaderType shaderType )
 {
     ShaderType = shaderType;
     this.bytecode = function;
     switch ( ShaderType )
     {
         case Graphics.ShaderType.VertexShader:
             Handle = new SharpDX.Direct3D11.VertexShader ( graphicsDevice.Handle as SharpDX.Direct3D11.Device, function );
             break;
         case Graphics.ShaderType.PixelShader:
             Handle = new SharpDX.Direct3D11.PixelShader ( graphicsDevice.Handle as SharpDX.Direct3D11.Device, function );
             break;
         case Graphics.ShaderType.GeometryShader:
             Handle = new SharpDX.Direct3D11.GeometryShader ( graphicsDevice.Handle as SharpDX.Direct3D11.Device, function );
             break;
     }
 }
Beispiel #46
0
 /// <summary>
 ///     Creates a new <see cref="VertexBuffer" />.
 /// </summary>
 /// <typeparam name="T"> Generic type parameter. </typeparam>
 /// <param name="graphicsDevice"> The graphics device. </param>
 /// <param name="vertices">       The count of the vertices to store in this vertex buffer. </param>
 /// <param name="resourceUsage">  (Optional) The resource usage. </param>
 /// <param name="cpuAccessFlags"> (Optional) The CPU access flags. </param>
 /// <returns>
 ///     A <see cref="VertexBuffer" />.
 /// </returns>
 public static unsafe VertexBuffer Create <T>(IGraphicsDevice graphicsDevice,
                                              int vertices,
                                              ResourceUsage resourceUsage   = ResourceUsage.Dynamic,
                                              CpuAccessFlags cpuAccessFlags = CpuAccessFlags.Write)
     where T : unmanaged
 {
     return(new VertexBuffer(
                new Buffer(
                    graphicsDevice.Device,
                    sizeof(T) * vertices,
                    resourceUsage,
                    BindFlags.VertexBuffer,
                    cpuAccessFlags,
                    ResourceOptionFlags.None,
                    0),
                sizeof(T)));
 }
Beispiel #47
0
 public Texture2D( IGraphicsDevice graphicsDevice, int width, int height, int mipmapLevel = 1, bool isRenderBuffer = false )
 {
     if ( width == 0 ) width = 1;
     if ( height == 0 ) height = 1;
     Size = new Vector2 ( width, height );
     texture = new SharpDX.Direct3D11.Texture2D ( graphicsDevice.Handle as SharpDX.Direct3D11.Device, new SharpDX.Direct3D11.Texture2DDescription ()
     {
         Width = width,
         Height = height,
         Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
         MipLevels = mipmapLevel,
         CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.Read | SharpDX.Direct3D11.CpuAccessFlags.Write,
         Usage = SharpDX.Direct3D11.ResourceUsage.Default,
         BindFlags = SharpDX.Direct3D11.BindFlags.ShaderResource | ( isRenderBuffer ? ( SharpDX.Direct3D11.BindFlags.RenderTarget ) : 0 ),
         ArraySize = 1,
     } );
 }
Beispiel #48
0
        public RenderBuffer( IGraphicsDevice graphicsDevice, int width, int height )
            : base(graphicsDevice, width, height)
        {
            GL.GenFramebuffers ( 1, out depthBuffer );
            GL.BindFramebuffer ( FramebufferTarget.Framebuffer, depthBuffer );
            GL.RenderbufferStorage ( RenderbufferTarget.Renderbuffer, RenderbufferStorage.Depth24Stencil8, width, height );

            GL.GenFramebuffers ( 1, out frameBuffer );
            GL.BindFramebuffer ( FramebufferTarget.Framebuffer, frameBuffer );
            GL.FramebufferRenderbuffer ( FramebufferTarget.Framebuffer, FramebufferAttachment.DepthStencilAttachment, RenderbufferTarget.Renderbuffer, depthBuffer );
            GL.FramebufferTexture2D ( FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, TextureTarget.Texture2D, ( int ) Handle, 0 );

            if ( GL.CheckFramebufferStatus ( FramebufferTarget.Framebuffer ) != FramebufferErrorCode.FramebufferComplete )
                throw new PlatformNotSupportedException ();

            GL.BindFramebuffer ( FramebufferTarget.Framebuffer, 0 );
        }
Beispiel #49
0
        public VertexDeclaration( IGraphicsDevice graphicsDevice, VertexElement [] elements )
        {
            this.elements = elements.GetEnumerator ();
            SharpDX.Direct3D9.Device device = graphicsDevice.Handle as SharpDX.Direct3D9.Device;

            SharpDX.Direct3D9.VertexElement [] convedElements = new SharpDX.Direct3D9.VertexElement [ elements.Length + 1 ];
            for ( int i = 0, offset = 0; i < elements.Length; ++i )
            {
                convedElements [ i ] = new SharpDX.Direct3D9.VertexElement ( 0, ( short ) offset,
                    ConvertType ( elements [ i ].Size ), SharpDX.Direct3D9.DeclarationMethod.Default,
                    ConvertType ( elements [ i ].Type ), ( byte ) elements [ i ].UsageIndex );
                offset += ElementSizeToRealSize ( elements [ i ].Size );
            }
            convedElements [ elements.Length ] = SharpDX.Direct3D9.VertexElement.VertexDeclarationEnd;

            vertexDeclaration = new SharpDX.Direct3D9.VertexDeclaration ( device, convedElements );
        }
Beispiel #50
0
        /// <inheritdoc />
        void IInitializable.Initialize(IServiceRegistry registry)
        {
            _graphicsDevice = registry.GetService <IGraphicsDevice>();

            // ReSharper disable once HeapView.DelegateAllocation
            // ReSharper disable once HeapView.ClosureAllocation
            _graphicsDevice.ResizeFinished += v =>
            {
                GetBrowser().GetHost().NotifyMoveOrResizeStarted();
                Size = new Size((int)v.Width, (int)v.Height);
                GetBrowser().GetHost().WasResized();
            };
            Size = new Size((int)_graphicsDevice.Viewport.Width, (int)_graphicsDevice.Viewport.Height);

            // ReSharper disable once HeapView.DelegateAllocation
            Paint += OnPaint;
        }
Beispiel #51
0
        private ISwapChain CreateOrUpdateRenderTarget(
            IGraphicsDevice device,
            AlphaMode newAlphaMode,
            float newDpi,
            Size newSize,
            ISwapChain renderTarget)
        {
            Size renderTargetSize = new Size((int)renderTarget.Width, (int)renderTarget.Height);

            bool needsTarget      = renderTarget != null;
            bool alphaModeChanged = renderTarget.AlphaMode != newAlphaMode;
            bool dpiChanged       = renderTarget.LogicalDpi != newDpi;
            bool sizeChanged      = renderTargetSize != newSize;
            bool needsCreate      = needsTarget || alphaModeChanged;

            if (!needsCreate && !sizeChanged && !dpiChanged)
            {
                return(null);
            }

            if (newSize.Width <= 0 || newSize.Height <= 0)
            {
                // Zero-sized controls don't have swap chain objects
                return(null);
            }
            else if ((sizeChanged || dpiChanged) && !needsCreate)
            {
                renderTarget.ResizeBuffersWithWidthAndHeightAndDpi(newSize.Width, newSize.Height, newDpi);
                renderTargetSize = newSize;
                //renderTarget.LogicalDpi = newDpi;
            }
            else
            {
                //renderTarget.Target = this.Device.CreateSwapChain(
                //    newSize.Width,
                //    newSize.Height,
                //    newDpi,
                //    newAlphaMode);

                renderTarget.AlphaMode = newAlphaMode;
                //renderTarget.LogicalDpi = newDpi;
                renderTargetSize = newSize;
            }

            return(renderTarget);
        }
Beispiel #52
0
        /// <summary>
        /// Constructor.
        /// </summary>
        public GameConsole(IGameWindow window, IGraphicsDevice graphicsDevice)
            : base()
        {
            if (window == null)
                throw new ArgumentNullException("window");

            if (graphicsDevice == null)
                throw new ArgumentNullException("graphicsDevice");

            this.Window = window;
            this.Window.KeyPress += this.Window_KeyPress;

            this.GraphicsDevice = graphicsDevice;

            this.inputReceivedEventArgs = new GameConsoleInputEventArgs();
            this.outputReceivedEventArgs = new GameConsoleOutputEventArgs();

            this.DefaultTextColor = Color.Black;
            this.BackgroundColor = Color.White;
            this.Height = (int)(this.Window.DisplayHeight * 0.75);
            this.Animate = true;
            this.AnimationTime = TimeSpan.FromMilliseconds(500);
            this.animationElapsedTime = TimeSpan.Zero;

            this.Padding = 4;

            this.maxLines = 25;
            this.lines = new GameConsoleLine[this.maxLines];
            for (int i = 0; i < this.lines.Length; i++)
                this.lines[i] = new GameConsoleLine();

            this.lineCount = 0;
            this.firstLine = 0;

            this.InputEnabled = false;
            this.InputPrompt = "> ";
            this.InputColor = Color.Black;
            this.input = new StringBuilder(128);
            this.cursorPosition = 0;

            this.ToggleKeyCode = 192;
        }
Beispiel #53
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="SamplerStates" /> class.
 /// </summary>
 /// <param name="graphicsDevice"> The graphics device. </param>
 internal SamplerStates(IGraphicsDevice graphicsDevice)
 {
     PointWrap = Create(
         graphicsDevice.Device, nameof(PointWrap), Filter.MinMagMipPoint, TextureAddressMode.Wrap);
     PointClamp = Create(
         graphicsDevice.Device, nameof(PointClamp), Filter.MinMagMipPoint, TextureAddressMode.Clamp);
     PointMirror = Create(
         graphicsDevice.Device, nameof(PointMirror), Filter.MinMagMipPoint, TextureAddressMode.Mirror);
     LinearWrap = Create(
         graphicsDevice.Device, nameof(LinearWrap), Filter.MinMagMipLinear, TextureAddressMode.Wrap);
     LinearClamp = Create(
         graphicsDevice.Device, nameof(LinearClamp), Filter.MinMagMipLinear, TextureAddressMode.Clamp);
     LinearMirror = Create(
         graphicsDevice.Device, nameof(LinearMirror), Filter.MinMagMipLinear, TextureAddressMode.Mirror);
     AnisotropicWrap = Create(
         graphicsDevice.Device, nameof(AnisotropicWrap), Filter.Anisotropic, TextureAddressMode.Wrap);
     AnisotropicClamp = Create(
         graphicsDevice.Device, nameof(AnisotropicClamp), Filter.Anisotropic, TextureAddressMode.Clamp);
     AnisotropicMirror = Create(
         graphicsDevice.Device, nameof(AnisotropicMirror), Filter.Anisotropic, TextureAddressMode.Mirror);
 }
Beispiel #54
0
 public RenderBuffer( IGraphicsDevice graphicsDevice, int width, int height )
     : base(graphicsDevice, width, height, 1, true)
 {
     targetView = new SharpDX.Direct3D11.RenderTargetView ( graphicsDevice.Handle as SharpDX.Direct3D11.Device,
         Handle as SharpDX.Direct3D11.Texture2D, new SharpDX.Direct3D11.RenderTargetViewDescription ()
         {
             Dimension = SharpDX.Direct3D11.RenderTargetViewDimension.Texture2D,
             Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
             Texture2D = new SharpDX.Direct3D11.RenderTargetViewDescription.Texture2DResource () { MipSlice = 0 }
         }
     );
     depthStencilBuffer = new SharpDX.Direct3D11.Texture2D ( graphicsDevice.Handle as SharpDX.Direct3D11.Device,
         new SharpDX.Direct3D11.Texture2DDescription ()
         {
             ArraySize = 1,
             Width = width,
             Height = height,
             Format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
             MipLevels = 0,
             BindFlags = SharpDX.Direct3D11.BindFlags.DepthStencil,
         }
     );
     depthStencil = new SharpDX.Direct3D11.DepthStencilView ( graphicsDevice.Handle as SharpDX.Direct3D11.Device,
         depthStencilBuffer, new SharpDX.Direct3D11.DepthStencilViewDescription ()
         {
             Dimension = SharpDX.Direct3D11.DepthStencilViewDimension.Texture2D,
             Format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt,
             Texture2D = new SharpDX.Direct3D11.DepthStencilViewDescription.Texture2DResource () { MipSlice = 0 }
         }
     );
     shaderView = new SharpDX.Direct3D11.ShaderResourceView ( graphicsDevice.Handle as SharpDX.Direct3D11.Device,
         Handle as SharpDX.Direct3D11.Texture2D, new SharpDX.Direct3D11.ShaderResourceViewDescription ()
         {
             Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
             Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D,
             Texture2D = new SharpDX.Direct3D11.ShaderResourceViewDescription.Texture2DResource () { MipLevels = 1, MostDetailedMip = 0 }
         }
     );
 }
Beispiel #55
0
        internal SpaceWar2Game()
        {
            _contentManager = new ContentManagerWrapper(Content.ServiceProvider, "Content");
            var graphicsDeviceManager = new GraphicsDeviceManager(this);
            _graphicsDevice = new GraphicsDeviceWrapper(graphicsDeviceManager);

            _universe = Universe.CreateDefault();
            _drawingManager = new DrawingManager(_universe);
            _gravitySimulator = new GravitySimulator();
            _shipComponentFactory = new ShipComponentFactory();
            _graphicsFactory = new GraphicsFactory();

            _gameObjectFactory = new GameObjectFactory(_contentManager, _graphicsFactory, _gravitySimulator, _drawingManager, _universe, _shipComponentFactory);

            _keyboardHandler = new KeyboardHandler(new KeyboardWrapper());

            var actionHandler = new ActionHandler(_keyboardHandler);

            _gameEngine = new GameEngine(_universe, _gravitySimulator, _gameObjectFactory, _keyboardHandler, actionHandler, _drawingManager);

            SetUpActions(actionHandler);
        }
Beispiel #56
0
        public Shader( IGraphicsDevice graphicsDevice, ShaderType shaderType, string shaderCode )
        {
            ShaderType = shaderType;

            shaderId = GL.CreateShader ( MistyValueToOriginal ( shaderType ) );

            if ( shaderType == ShaderType.PixelShader )
            {
                shaderCode = "#define getTexUV(texcoord) (vec2(texcoord.st.x, 1.0 - texcoord.st.y))\r\n" + shaderCode;
            }

            shaderCode = string.Format ( "#version {0}{1}0\r\n", graphicsDevice.Information.ShaderVersion.Major, graphicsDevice.Information.ShaderVersion.Minor ) + shaderCode;

            GL.ShaderSource ( shaderId, shaderCode );
            GL.CompileShader ( shaderId );

            int compileState;
            GL.GetShader ( shaderId, ShaderParameter.CompileStatus, out compileState );
            if ( compileState == 0 )
            {
                throw new ArgumentException ( string.Format ( "Compile failed: [Shader Type: {0}]\nLog:\n{1}\nOriginal code:\n{2}",
                    ShaderType, GL.GetShaderInfoLog ( shaderId ), shaderCode ) );
            }
        }
Beispiel #57
0
 public Texture1D( IGraphicsDevice graphicsDevice, ImageInfo imageInfo, Color? colorKey = null, int mipmapLevel = 1 )
 {
     MakeTexture ( imageInfo.Width );
     Buffer = imageInfo.GetPixels ( colorKey );
     GenerateMipmap ( mipmapLevel );
 }
Beispiel #58
0
 public Texture1D( IGraphicsDevice graphicsDevice, int width, int mipmapLevel = 1 )
 {
     MakeTexture ( width );
     GenerateMipmap ( mipmapLevel );
 }
Beispiel #59
0
 public void Draw(IGraphicsDevice graphicsDevice)
 {
 }
Beispiel #60
0
 public VertexDeclaration( IGraphicsDevice graphicsDevice, params VertexElement [] elements )
 {
     Length = elements.Length;
     foreach ( VertexElement e in elements )
         this.elements.Add ( e );
 }