Exemple #1
0
 private static BlendState Create(Device5 device,
                                  string name,
                                  BlendOption sourceBlend,
                                  BlendOption destinationBlend,
                                  bool blendEnabled)
 {
     return(Create(
                device,
                name,
                new BlendStateDescription
     {
         AlphaToCoverageEnable = false,
         IndependentBlendEnable = false,
         RenderTarget =
         {
             [0] = new RenderTargetBlendDescription
             {
             IsBlendEnabled = blendEnabled,
             SourceBlend = sourceBlend,
             DestinationBlend = destinationBlend,
             SourceAlphaBlend = sourceBlend,
             DestinationAlphaBlend = destinationBlend,
             BlendOperation = BlendOperation.Add,
             AlphaBlendOperation = BlendOperation.Add,
             RenderTargetWriteMask = ColorWriteMaskFlags.All
             }
         }
     }));
 }
Exemple #2
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"];
Exemple #3
0
 /// <summary>
 ///     Loads texture 2 d.
 /// </summary>
 /// <param name="device"> The device. </param>
 /// <param name="stream"> The stream. </param>
 /// <returns>
 ///     The texture 2 d.
 /// </returns>
 public static Texture2D LoadTexture2D(Device5 device, Stream stream)
 {
     using (BitmapSource bitmapSource = LoadBitmap(stream))
     {
         int stride = bitmapSource.Size.Width * 4;
         using (DataStream buffer = new DataStream(bitmapSource.Size.Height * stride, true, true))
         {
             bitmapSource.CopyPixels(stride, buffer);
             return(new Texture2D(
                        device,
                        new Texture2DDescription
             {
                 Width = bitmapSource.Size.Width,
                 Height = bitmapSource.Size.Height,
                 ArraySize = 1,
                 BindFlags = BindFlags.ShaderResource,
                 Usage = ResourceUsage.Immutable,
                 CpuAccessFlags = CpuAccessFlags.None,
                 Format = Format.R8G8B8A8_UNorm,
                 MipLevels = 1,
                 OptionFlags = ResourceOptionFlags.None,
                 SampleDescription = new SampleDescription(1, 0)
             }, new DataRectangle(buffer.DataPointer, stride)));
         }
     }
 }
Exemple #4
0
 private static BlendState Create(Device5 device, string name, BlendStateDescription description)
 {
     return(new BlendState(device, description)
     {
         DebugName = name
     });
 }
Exemple #5
0
 private static RasterizerState Create(Device5 device,
                                       string name,
                                       FillMode fillMode,
                                       CullMode cullMode,
                                       bool depthClipEnabled,
                                       bool scissorEnabled,
                                       bool multiSampleEnabled)
 {
     return(new RasterizerState(
                device,
                new RasterizerStateDescription
     {
         FillMode = fillMode,
         CullMode = cullMode,
         IsFrontCounterClockwise = false,
         DepthBias = 0,
         DepthBiasClamp = 0,
         SlopeScaledDepthBias = 0,
         IsDepthClipEnabled = depthClipEnabled,
         IsScissorEnabled = scissorEnabled,
         IsMultisampleEnabled = multiSampleEnabled,
         IsAntialiasedLineEnabled = multiSampleEnabled
     })
     {
         DebugName = name
     });
 }
 private static DepthStencilState Create(Device5 device,
                                         string name,
                                         bool depthEnable,
                                         bool depthWriteEnable,
                                         bool stencilEnabled)
 {
     return(new DepthStencilState(
                device,
                new DepthStencilStateDescription
     {
         IsDepthEnabled = depthEnable,
         DepthWriteMask = depthWriteEnable ? DepthWriteMask.All : DepthWriteMask.Zero,
         DepthComparison = Comparison.LessEqual,
         IsStencilEnabled = stencilEnabled,
         StencilReadMask = 0xFF,
         StencilWriteMask = 0xFF,
         FrontFace = new DepthStencilOperationDescription
         {
             FailOperation = StencilOperation.Keep,
             DepthFailOperation = StencilOperation.Keep,
             PassOperation = StencilOperation.Keep,
             Comparison = Comparison.Always
         },
         BackFace = new DepthStencilOperationDescription
         {
             FailOperation = StencilOperation.Keep,
             DepthFailOperation = StencilOperation.Keep,
             PassOperation = StencilOperation.Keep,
             Comparison = Comparison.Always
         }
     })
     {
         DebugName = name
     });
 }
Exemple #7
0
 /// <summary>
 ///     Creates a texture.
 /// </summary>
 /// <param name="device"> The device. </param>
 /// <param name="width">  The width. </param>
 /// <param name="height"> The height. </param>
 /// <param name="format"> (Optional) Describes the format to use. </param>
 /// <returns>
 ///     The new texture.
 /// </returns>
 public static Texture2D CreateTexture(Device5 device,
                                       int width,
                                       int height,
                                       Format format = Format.B8G8R8A8_UNorm)
 {
     return(new Texture2D(
                device,
                new Texture2DDescription
     {
         Width = width,
         Height = height,
         ArraySize = 1,
         BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
         Usage = ResourceUsage.Default,
         CpuAccessFlags = CpuAccessFlags.None,
         Format = format,
         MipLevels = 1,
         OptionFlags = ResourceOptionFlags.None,
         SampleDescription = new SampleDescription(1, 0)
     }));
 }
Exemple #8
0
        /// <summary>
        ///     Converts this object to a texture 2 d array.
        /// </summary>
        /// <param name="device">        The device. </param>
        /// <param name="bitmapSources"> The bitmap sources. </param>
        /// <returns>
        ///     The given data converted to a Texture2D.
        /// </returns>
        internal static Texture2D ToTexture2DArray(Device5 device, BitmapSource[] bitmapSources)
        {
            int width  = bitmapSources[0].Size.Width;
            int height = bitmapSources[0].Size.Height;

            Texture2D texArray = new Texture2D(
                device,
                new Texture2DDescription
            {
                Width             = width,
                Height            = height,
                ArraySize         = bitmapSources.Length,
                BindFlags         = BindFlags.ShaderResource,
                Usage             = ResourceUsage.Default,
                CpuAccessFlags    = CpuAccessFlags.None,
                Format            = Format.R8G8B8A8_UNorm,
                MipLevels         = 1,
                OptionFlags       = ResourceOptionFlags.None,
                SampleDescription = new SampleDescription(1, 0)
            });

            int stride = width * 4;

            for (int i = 0; i < bitmapSources.Length; i++)
            {
                using (BitmapSource bitmap = bitmapSources[i])
                {
                    using (DataStream buffer = new DataStream(height * stride, true, true))
                    {
                        bitmap.CopyPixels(stride, buffer);
                        DataBox box = new DataBox(buffer.DataPointer, stride, 1);
                        device.ImmediateContext.UpdateSubresource(
                            box, texArray, Resource.CalculateSubResourceIndex(0, i, 1));
                    }
                }
            }
            return(texArray);
        }
Exemple #9
0
 public BusWindow()
 {
     InitializeComponent();
     Device1.SetBinding(TextBlock.TextProperty, new Binding("Info1")
     {
         Source = DataList
     });
     Device2.SetBinding(TextBlock.TextProperty, new Binding("Info2")
     {
         Source = DataList
     });
     Device3.SetBinding(TextBlock.TextProperty, new Binding("Info3")
     {
         Source = DataList
     });
     Device4.SetBinding(TextBlock.TextProperty, new Binding("Info4")
     {
         Source = DataList
     });
     Device5.SetBinding(TextBlock.TextProperty, new Binding("Info5")
     {
         Source = DataList
     });
 }
Exemple #10
0
 private static SamplerState Create(Device5 device,
                                    string name,
                                    Filter filter,
                                    TextureAddressMode textureAddressMode)
 {
     return(new SamplerState(
                device,
                new SamplerStateDescription
     {
         AddressU = textureAddressMode,
         AddressV = textureAddressMode,
         AddressW = textureAddressMode,
         BorderColor = Color.White,
         ComparisonFunction = Comparison.Never,
         Filter = filter,
         MaximumAnisotropy = 16,
         MaximumLod = float.MaxValue,
         MinimumLod = float.MinValue,
         MipLodBias = 0.0f
     })
     {
         DebugName = name
     });
 }
Exemple #11
0
        /// <summary>
        ///     Initializes the <see cref="GraphicsDevice" />.
        /// </summary>
        /// <param name="parameters"> [in,out] Options for controlling the operation. </param>
        public void Initialize(ref GameGraphicsParameters parameters)
        {
            if (IsInitialized)
            {
                return;
            }

            _vSync = parameters.UseVSync ? 1 : 0;

            using (Factory4 factory4 = new Factory4())
            {
                _dxgiFactory = factory4.QueryInterface <Factory5>();
            }

            ModeDescription modeDescription =
                new ModeDescription(
                    parameters.Width,
                    parameters.Height,
                    parameters.Rational,
                    parameters.Format);

            if (parameters.AdapterLuid != -1 && parameters.OutputIndex != -1)
            {
                using (Adapter adapter = _dxgiFactory.GetAdapterByLuid(parameters.AdapterLuid))
                    using (Output output = adapter.GetOutput(parameters.OutputIndex))
                    {
                        _adapter4 = adapter.QueryInterface <Adapter4>();
                        _output6  = output.QueryInterface <Output6>();
                        _output6.GetClosestMatchingMode(
                            null,
                            modeDescription,
                            out modeDescription);
                    }
            }
            else
            {
                IEnumerable <Adapter> adapters =
                    _dxgiFactory.Adapters1
                    .Where(
                        a => (a.Description1.Flags & AdapterFlags.Software) !=
                        AdapterFlags.Software && a.GetOutputCount() > 0)
                    .Select(
                        a => (adapter: a,
                              featureLevel: SharpDX.Direct3D11.Device.GetSupportedFeatureLevel(a)))
                    .GroupBy(t => t.featureLevel)
                    .OrderByDescending(t => t.Key)
                    .First()
                    .Select(k => k.adapter);

                _adapter4 = null;
                foreach (Adapter adapter in adapters)
                {
                    using (adapter)
                    {
                        for (int o = 0; o < adapter.GetOutputCount(); o++)
                        {
                            using (Output output = adapter.GetOutput(o))
                            {
                                output.GetClosestMatchingMode(
                                    null,
                                    modeDescription,
                                    out ModeDescription desc);
                                if (_adapter4 == null ||
                                    desc.RefreshRate.Numerator / desc.RefreshRate.Denominator >
                                    modeDescription.RefreshRate.Numerator / modeDescription.RefreshRate.Denominator)
                                {
                                    modeDescription = desc;
                                    Interlocked.Exchange(ref _output6, output.QueryInterface <Output6>())?.Dispose();
                                    Interlocked.Exchange(ref _adapter4, adapter.QueryInterface <Adapter4>())?.Dispose();
                                }
                            }
                        }
                    }
                }
            }

            // ReSharper disable once VariableHidesOuterVariable
            Device CreateDevice(in GameGraphicsParameters parameters)
            {
                if (_adapter4 != null)
                {
                    Console.WriteLine("------- GRAPHIC CARD INFORMATION -------");
                    Console.WriteLine($"Luid:\t\t\t{_adapter4.Description2.Luid}");
                    Console.WriteLine(
                        $"Description:\t\t{_adapter4.Description2.Description.TrimEnd('\t', ' ', '\r', '\n', (char)0)}");
                    Console.WriteLine($"DeviceId:\t\t{_adapter4.Description2.DeviceId}");
                    Console.WriteLine($"VendorId:\t\t{_adapter4.Description2.VendorId}");
                    Console.WriteLine($"Revision:\t\t{_adapter4.Description2.Revision}");
                    Console.WriteLine($"SubsystemId:\t\t{_adapter4.Description2.SubsystemId}");
#if x64
                    Console.WriteLine();
                    Console.WriteLine($"SystemMemory:\t\t{_adapter4.Description2.DedicatedSystemMemory}");
                    Console.WriteLine($"VideoMemory:\t\t{_adapter4.Description2.DedicatedVideoMemory}");
                    Console.WriteLine($"SharedSystemMemory:\t{_adapter4.Description2.SharedSystemMemory}");
#endif
                    Console.WriteLine();
                    Console.WriteLine($"Format:\t\t\t{modeDescription.Format}");
                    Console.WriteLine($"Width x Height:\t\t{modeDescription.Width} x {modeDescription.Height}");
                    Console.WriteLine(
                        $"RefreshRate:\t\t{modeDescription.RefreshRate} ({modeDescription.RefreshRate.Numerator / modeDescription.RefreshRate.Denominator}HZ)");
                    Console.WriteLine($"Scaling:\t\t{modeDescription.Scaling}");
                    Console.WriteLine($"ScanlineOrdering:\t{modeDescription.ScanlineOrdering}");
                    Console.WriteLine();
                    Console.WriteLine($"DeviceName:\t\t{_output6.Description.DeviceName}");
                    Console.WriteLine(
                        $"DesktopBounds:\t\t{_output6.Description.DesktopBounds.Left};{_output6.Description.DesktopBounds.Top};{_output6.Description.DesktopBounds.Right};{_output6.Description.DesktopBounds.Bottom}");
                    Console.WriteLine($"MonitorHandle:\t\t{_output6.Description.MonitorHandle}");
                    Console.WriteLine($"IsAttachedToDesktop:\t{_output6.Description.IsAttachedToDesktop}");
                    Console.WriteLine($"Rotation:\t\t{_output6.Description.Rotation}");
                    Console.WriteLine("----------------------------------------\n");

                    return(new Device(_adapter4, parameters.DeviceCreationFlags, s_featureLevels));
                }
                return(new Device(parameters.DriverType, parameters.DeviceCreationFlags, s_featureLevels));
            }

            using (Device defaultDevice = CreateDevice(in parameters))
            {
                _d3DDevice5 = defaultDevice.QueryInterface <Device5>();
            }

            _d3DDeviceContext = _d3DDevice5.ImmediateContext3.QueryInterface <DeviceContext4>();
            _dxgiDevice4      = _d3DDevice5.QueryInterface <Device4>();

            SampleDescription sampleDescription = new SampleDescription(1, 0);
            if (parameters.EnableMultiSampling && parameters.MultiSampleCount != MultiSampleCount.None)
            {
                sampleDescription.Count   = (int)parameters.MultiSampleCount;
                sampleDescription.Quality =
                    Math.Max(
                        _d3DDevice5.CheckMultisampleQualityLevels(
                            modeDescription.Format,
                            sampleDescription.Count) - 1,
                        0);
            }

            SwapChainDescription swapChainDescription = new SwapChainDescription
            {
                BufferCount       = parameters.BufferCount,
                ModeDescription   = modeDescription,
                IsWindowed        = true,
                OutputHandle      = parameters.Handle,
                SampleDescription = sampleDescription,
                SwapEffect        = parameters.SwapEffect,
                Usage             = parameters.Usage,
                Flags             = parameters.SwapChainFlags
            };

            using (SwapChain swapChain = new SwapChain(_dxgiFactory, _d3DDevice5, swapChainDescription))
            {
                _swapChain4 = swapChain.QueryInterface <SwapChain4>();
            }

            _dxgiFactory.MakeWindowAssociation(parameters.Handle, parameters.WindowAssociationFlags);

            _swapChain4.ResizeTarget(ref modeDescription);

            SetFullscreenState(parameters.DisplayType == DisplayType.Fullscreen);

            _resizeParameters = new ResizeParameters
            {
                BufferCount    = parameters.BufferCount,
                Width          = parameters.Width,
                Height         = parameters.Height,
                SwapChainFlags = parameters.SwapChainFlags
            };

            Resize(_resizeParameters);

            _blendStates        = new BlendStates(this);
            _depthStencilStates = new DepthStencilStates(this);
            _rasterizerStates   = new RasterizerStates(this);
            _samplerStates      = new SamplerStates(this);
            _textures           = new Textures(this);

            IsInitialized = true;
        }
Exemple #12
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="VideoPlayer" /> class.
 /// </summary>
 /// <param name="device"> The device. </param>
 /// <param name="width">  The width. </param>
 /// <param name="height"> The height. </param>
 public VideoPlayer(Device5 device, int width, int height)
     : base(nameof(VideoPlayer))
 {
     _outputTexture   = TextureHelper.CreateTexture(device, width, height);
     _backgroundColor = Color.Transparent;
 }