write a bgfx sample app in csharp

To write a bgfx sample app in C#, follow these steps:

  1. Download the latest version of bgfx C# wrapper from the GitHub repository: https://github.com/bkaradzic/bgfx.csharp

  2. Create a new C# console application in your preferred IDE.

  3. Add the downloaded bgfx C# wrapper to your project's references.

  4. Create a new static class called Program and add the following code to the Main method:

main.cs
using System;
using System.Runtime.InteropServices;
using Bgfx;

static class Program
{
    static void Main(string[] args)
    {
        // Create a new bgfx platform data object
        var pd = new PlatformData();
        // Initialize the bgfx library
        Bgfx.Init();
        // Create a new window
        Bgfx.CreateWindow(pd, 1280, 720, Bgfx.ResetFlags.Vsync);
        // Set the view clear color and depth values
        Bgfx.SetViewClear(0, ClearFlags.Color | ClearFlags.Depth, 0x443355FF, 1.0f, 0);
        // Set the view rect
        Bgfx.SetViewRect(0, 0, 0, (ushort)Bgfx.GetStats().Width, (ushort)Bgfx.GetStats().Height);
        // Set the debug flags
        Bgfx.SetDebug(Bgfx.DebugFlags.Text);
        // Create and submit a new vertex buffer with a single triangle
        var vb = Bgfx.CreateVertexBuffer(MemoryMarshal.Cast<Vertex, float>(new[] {
            new Vertex(-1.0f, -1.0f, 0.0f),
            new Vertex( 1.0f, -1.0f, 0.0f),
            new Vertex( 0.0f,  1.0f, 0.0f),
        }), Vertex.VertexLayout);
        Bgfx.Submit(0, 0);

        // Main game loop
        while (!Bgfx.RequestedQuit())
        {
            // Update the bgfx frame
            Bgfx.Frame();
        }

        // Destroy the vertex buffer and shutdown bgfx
        Bgfx.DestroyVertexBuffer(vb);
        Bgfx.Shutdown();
    }

    // Define a struct for a single vertex
    struct Vertex
    {
        public float x;
        public float y;
        public float z;

        public Vertex(float x, float y, float z)
        {
            this.x = x;
            this.y = y;
            this.z = z;
        }

        // Define the vertex layout for bgfx
        public static readonly VertexLayout VertexLayout = new VertexLayout()
           .Begin()
           .Add(VertexAttributeUsage.Position, 3, VertexAttributeType.Float)
           .End();
    }
}
1868 chars
62 lines
  1. Run the program, and you should see a single triangle displayed in the window.

This sample code initializes bgfx, creates a new window, sets clear values and viewport, creates a single triangle with a vertex buffer, and submits it to bgfx for rendering. The main game loop updates the bgfx frame each frame.

gistlibby LogSnag