Home c# Using DirectX in C #

Using DirectX in C #

Author

Date

Category


Answer 1, authority 100%

You can connect DX functions to create graphics by installing the DirectX SDK which can be downloaded from the Microsoft offsite. And to remake it for it means using the DX API (DirectDraw) as a drawing function, the most banal and simple way in my opinion is to write the same program using Microsoft Visual C++, where graphics are output using DirectDraw.

This is a rather extensive topic to describe all the stages here, because we need to write a procedure for calling a window, initializing a palette and much more, so I will share a link to a resource that helped me figure it out.


Answer 2, authority 25%

once in C #, then maybe you need to redo it to Direct2D, and not DirectX?
here is library


Answer 3, authority 25%

There is a wonderful SharpDX library in C #

Main code (Shader code below)

// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Diagnostics;
using System.Windows.Forms;
using SharpDX;
using SharpDX.D3DCompiler;
using SharpDX.Direct3D;
using SharpDX.Direct3D11;
using SharpDX.DXGI;
using SharpDX.Windows;
using Buffer = SharpDX.Direct3D11.Buffer;
using Device = SharpDX.Direct3D11.Device;
namespace MiniCube
{
  /// & lt; summary & gt;
  /// SharpDX MiniCube Direct3D 11 Sample
  /// & lt; / summary & gt;
  internal static class Program
  {
 // [STAThread]
    private static void Main ()
    {
      var form = new RenderForm ("SharpDX - MiniCube Direct3D11 Sample");
      // SwapChain description
      var desc = new SwapChainDescription ()
      {
        BufferCount = 1,
        ModeDescription =
          new ModeDescription (form.ClientSize.Width, form.ClientSize.Height,
                    new Rational (60, 1), Format.R8G8B8A8_UNorm),
        IsWindowed = true,
        OutputHandle = form.Handle,
        SampleDescription = new SampleDescription (1, 0),
        SwapEffect = SwapEffect.Discard,
        Usage = Usage.RenderTargetOutput
      };
      // Used for debugging dispose object references
      // Configuration.EnableObjectTracking = true;
      // Disable throws on shader compilation errors
      //Configuration.ThrowOnShaderCompileError = false;
      // Create Device and SwapChain
      Device device;
      SwapChain swapChain;
Device.CreateWithSwapChain (DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain);
      var context = device.ImmediateContext;
      // Ignore all windows events
      var factory = swapChain.GetParent & lt; Factory & gt; ();
      factory.MakeWindowAssociation (form.Handle, WindowAssociationFlags.IgnoreAll);
      // Compile Vertex and Pixel shaders
      var vertexShaderByteCode = ShaderBytecode.CompileFromFile ("MiniCube.fx", "VS", "vs_4_0");
      var vertexShader = new VertexShader (device, vertexShaderByteCode);
      var pixelShaderByteCode = ShaderBytecode.CompileFromFile ("MiniCube.fx", "PS", "ps_4_0");
      var pixelShader = new PixelShader (device, pixelShaderByteCode);
      var signature = ShaderSignature.GetInputSignature (vertexShaderByteCode);
      // Layout from VertexShader input signature
      var layout = new InputLayout (device, signature, new []
          {
            new InputElement ("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
            new InputElement ("COLOR", 0, Format.R32G32B32A32_Float, 16, 0)
          });
      // Instantiate Vertex buiffer from vertex data
      var vertices = Buffer.Create (device, BindFlags.VertexBuffer, new []
                 {
                   new Vector4 (-1.0f, -1.0f, -1.0f, 1.0f), new Vector4 (1.0f, 0.0f, 0.0f, 1.0f), // Front
                   new Vector4 (-1.0f, 1.0f, -1.0f, 1.0f), new Vector4 (1.0f, 0.0f, 0.0f, 1.0f),
                   new Vector4 (1.0f, 1.0f, -1.0f, 1.0f), new Vector4 (1.0f, 0.0f, 0.0f, 1.0f),
                   new Vector4 (-1.0f, -1.0f, -1.0f, 1.0f), new Vector4 (1.0f, 0.0f, 0.0f, 1.0f),
new Vector4 (1.0f, 1.0f, -1.0f, 1.0f), new Vector4 (1.0f, 0.0f, 0.0f, 1.0f),
                   new Vector4 (1.0f, -1.0f, -1.0f, 1.0f), new Vector4 (1.0f, 0.0f, 0.0f, 1.0f),
                   new Vector4 (-1.0f, -1.0f, 1.0f, 1.0f), new Vector4 (0.0f, 1.0f, 0.0f, 1.0f), // BACK
                   new Vector4 (1.0f, 1.0f, 1.0f, 1.0f), new Vector4 (0.0f, 1.0f, 0.0f, 1.0f),
                   new Vector4 (-1.0f, 1.0f, 1.0f, 1.0f), new Vector4 (0.0f, 1.0f, 0.0f, 1.0f),
                   new Vector4 (-1.0f, -1.0f, 1.0f, 1.0f), new Vector4 (0.0f, 1.0f, 0.0f, 1.0f),
                   new Vector4 (1.0f, -1.0f, 1.0f, 1.0f), new Vector4 (0.0f, 1.0f, 0.0f, 1.0f),
                   new Vector4 (1.0f, 1.0f, 1.0f, 1.0f), new Vector4 (0.0f, 1.0f, 0.0f, 1.0f),
                   new Vector4 (-1.0f, 1.0f, -1.0f, 1.0f), new Vector4 (0.0f, 0.0f, 1.0f, 1.0f), // Top
                   new Vector4 (-1.0f, 1.0f, 1.0f, 1.0f), new Vector4 (0.0f, 0.0f, 1.0f, 1.0f),
                   new Vector4 (1.0f, 1.0f, 1.0f, 1.0f), new Vector4 (0.0f, 0.0f, 1.0f, 1.0f),
                   new Vector4 (-1.0f, 1.0f, -1.0f, 1.0f), new Vector4 (0.0f, 0.0f, 1.0f, 1.0f),
                   new Vector4 (1.0f, 1.0f, 1.0f, 1.0f), new Vector4 (0.0f, 0.0f, 1.0f, 1.0f),
                   new Vector4 (1.0f, 1.0f, -1.0f, 1.0f), new Vector4 (0.0f, 0.0f, 1.0f, 1.0f),
                   new Vector4 (-1.0f, -1.0f, -1.0f, 1.0f), new Vector4 (1.0f, 1.0f, 0.0f, 1.0f), // Bottom
                   new Vector4 (1.0f, -1.0f, 1.0f, 1.0f), new Vector4 (1.0f, 1.0f, 0.0f, 1.0f),
new Vector4 (-1.0f, -1.0f, 1.0f, 1.0f), new Vector4 (1.0f, 1.0f, 0.0f, 1.0f),
                   new Vector4 (-1.0f, -1.0f, -1.0f, 1.0f), new Vector4 (1.0f, 1.0f, 0.0f, 1.0f),
                   new Vector4 (1.0f, -1.0f, -1.0f, 1.0f), new Vector4 (1.0f, 1.0f, 0.0f, 1.0f),
                   new Vector4 (1.0f, -1.0f, 1.0f, 1.0f), new Vector4 (1.0f, 1.0f, 0.0f, 1.0f),
                   new Vector4 (-1.0f, -1.0f, -1.0f, 1.0f), new Vector4 (1.0f, 0.0f, 1.0f, 1.0f), // Left
                   new Vector4 (-1.0f, -1.0f, 1.0f, 1.0f), new Vector4 (1.0f, 0.0f, 1.0f, 1.0f),
                   new Vector4 (-1.0f, 1.0f, 1.0f, 1.0f), new Vector4 (1.0f, 0.0f, 1.0f, 1.0f),
                   new Vector4 (-1.0f, -1.0f, -1.0f, 1.0f), new Vector4 (1.0f, 0.0f, 1.0f, 1.0f),
                   new Vector4 (-1.0f, 1.0f, 1.0f, 1.0f), new Vector4 (1.0f, 0.0f, 1.0f, 1.0f),
                   new Vector4 (-1.0f, 1.0f, -1.0f, 1.0f), new Vector4 (1.0f, 0.0f, 1.0f, 1.0f),
                   new Vector4 (1.0f, -1.0f, -1.0f, 1.0f), new Vector4 (0.0f, 1.0f, 1.0f, 1.0f), // Right
                   new Vector4 (1.0f, 1.0f, 1.0f, 1.0f), new Vector4 (0.0f, 1.0f, 1.0f, 1.0f),
                   new Vector4 (1.0f, -1.0f, 1.0f, 1.0f), new Vector4 (0.0f, 1.0f, 1.0f, 1.0f),
                   new Vector4 (1.0f, -1.0f, -1.0f, 1.0f), new Vector4 (0.0f, 1.0f, 1.0f, 1.0f),
                   new Vector4 (1.0f, 1.0f, -1.0f, 1.0f), new Vector4 (0.0f, 1.0f, 1.0f, 1.0f),
                   new Vector4 (1.0f, 1.0f, 1.0f, 1.0f), new Vector4 (0.0f, 1.0f, 1.0f, 1.0f),
});
      // Create Constant Buffer
      var contantBuffer = new Buffer (device, Utilities.SizeOf & lt; Matrix & gt; (), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0);
      // Prepare All the stages
      context.InputAssembler.InputLayout = layout;
      context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
      context.InputAssembler.SetVertexBuffers (0, new VertexBufferBinding (vertices, Utilities.SizeOf & lt; Vector4 & gt; () * 2, 0));
      context.VertexShader.SetConstantBuffer (0, contantBuffer);
      context.VertexShader.Set (vertexShader);
      context.PixelShader.Set (pixelShader);
      // Prepare matrices
      var view = Matrix.LookAtLH (new Vector3 (0, 0, -5), new Vector3 (0, 0, 0), Vector3.UnitY);
      Matrix proj = Matrix.Identity;
      // Use clock
      var clock = new Stopwatch ();
      clock.Start ();
      // Declare texture for rendering
      bool userResized = true;
      Texture2D backBuffer = null;
      RenderTargetView renderView = null;
      Texture2D depthBuffer = null;
      DepthStencilView depthView = null;
      // Setup handler on resize form
      form.UserResized + = (sender, args) = & gt; userResized = true;
      // Setup full screen mode change F5 (Full) F4 (Window)
      form.KeyUp + = (sender, args) = & gt;
        {
          if (args.KeyCode == Keys.F5)
            swapChain.SetFullscreenState (true, null);
          else if (args.KeyCode == Keys.F4)
            swapChain.SetFullscreenState (false, null);
          else if (args.KeyCode == Keys.Escape)
            form.Close ();
};
      // Main loop
      RenderLoop.Run (form, () = & gt;
      {
        // If Form resized
        if (userResized)
        {
          // Dispose all previous allocated resources
          Utilities.Dispose (ref backBuffer);
          Utilities.Dispose (ref renderView);
          Utilities.Dispose (ref depthBuffer);
          Utilities.Dispose (ref depthView);
          // Resize the backbuffer
          swapChain.ResizeBuffers (desc.BufferCount, form.ClientSize.Width, form.ClientSize.Height, Format.Unknown, SwapChainFlags.None);
          // Get the backbuffer from the swapchain
          backBuffer = Texture2D.FromSwapChain & lt; Texture2D & gt; (swapChain, 0);
          // Renderview on the backbuffer
          renderView = new RenderTargetView (device, backBuffer);
          // Create the depth buffer
          depthBuffer = new Texture2D (device, new Texture2DDescription ()
          {
            Format = Format.D32_Float_S8X24_UInt,
            ArraySize = 1,
            MipLevels = 1,
            Width = form.ClientSize.Width,
            Height = form.ClientSize.Height,
            SampleDescription = new SampleDescription (1, 0),
            Usage = ResourceUsage.Default,
            BindFlags = BindFlags.DepthStencil,
            CpuAccessFlags = CpuAccessFlags.None,
            OptionFlags = ResourceOptionFlags.None
          });
          // Create the depth buffer view
          depthView = new DepthStencilView (device, depthBuffer);
// Setup targets and viewport for rendering
          context.Rasterizer.SetViewport (new Viewport (0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f));
          context.OutputMerger.SetTargets (depthView, renderView);
          // Setup new projection matrix with correct aspect ratio
          proj = Matrix.PerspectiveFovLH ((float) Math.PI / 4.0f, form.ClientSize.Width / (float) form.ClientSize.Height, 0.1f, 100.0f);
          // We are done resizing
          userResized = false;
        }
        var time = clock.ElapsedMilliseconds / 1000.0f;
        var viewProj = Matrix.Multiply (view, proj);
        // Clear views
        context.ClearDepthStencilView (depthView, DepthStencilClearFlags.Depth, 1.0f, 0);
        context.ClearRenderTargetView (renderView, Color.Black);
        // Update WorldViewProj Matrix
        var worldViewProj = Matrix.RotationX (time) * Matrix.RotationY (time * 2) * Matrix.RotationZ (time * .7f) * viewProj;
        worldViewProj.Transpose ();
        context.UpdateSubresource (ref worldViewProj, contantBuffer);
        // Draw the cube
        context.Draw (36, 0);
        // Present!
        swapChain.Present (0, PresentFlags.None);
      });
      // Release all resources
      signature.Dispose ();
      vertexShaderByteCode.Dispose ();
      vertexShader.Dispose ();
      pixelShaderByteCode.Dispose ();
      pixelShader.Dispose ();
      vertices.Dispose ();
      layout.Dispose ();
      contantBuffer.Dispose ();
      depthBuffer.Dispose ();
      depthView.Dispose ();
      renderView.Dispose ();
      backBuffer.Dispose ();
context.ClearState ();
      context.Flush ();
      device.Dispose ();
      context.Dispose ();
      swapChain.Dispose ();
      factory.Dispose ();
    }
  }
}

Shader Code

// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
struct VS_IN
{
  float4 pos: POSITION;
  float4 col: COLOR;
};
struct PS_IN
{
  float4 pos: SV_POSITION;
  float4 col: COLOR;
};
float4x4 worldViewProj;
PS_IN VS (VS_IN input)
{
  PS_IN output = (PS_IN) 0;
  output.pos = mul (input.pos, worldViewProj);
  output.col = input.col;
  return output;
}
float4 PS (PS_IN input): SV_Target
{
  return input.col;
}

SharpDX MiniCube Direct3D 11 Sample (license MIT)

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions