Compare commits

..
52 changed files with 1 additions and 4599 deletions

View file

@ -125,9 +125,7 @@ Glfw.Terminate();
dotnet run dotnet run
``` ```
That opens a window with no graphics API. For a minimal sample of every package, see [samples](samples/README.md). That opens a window with no graphics API. What you add next is up to you:
What you add next is up to you:
- **Rendering:** `Ahwoo.Brutal.Vulkan.Abstractions` and `Ahwoo.Brutal.Vulkan.Vma` for a Vulkan renderer, `Ahwoo.Brutal.ShaderC` to compile shaders at runtime. - **Rendering:** `Ahwoo.Brutal.Vulkan.Abstractions` and `Ahwoo.Brutal.Vulkan.Vma` for a Vulkan renderer, `Ahwoo.Brutal.ShaderC` to compile shaders at runtime.
- **Debug UI:** `Ahwoo.Brutal.ImGui` and `Ahwoo.Brutal.ImPlot`. - **Debug UI:** `Ahwoo.Brutal.ImGui` and `Ahwoo.Brutal.ImPlot`.

View file

@ -1,197 +0,0 @@
/*
* DemoBox2D
*
* Drops a pile of boxes onto the ground with Box2D and draws them with OpenGL every frame: the
* visual counterpart of the headless Hello/HelloBox2D.cs. Press Escape to close it.
*/
#:property AllowUnsafeBlocks=true
#:package Ahwoo.Brutal.Box2D@2026.10.2
#:package Ahwoo.Brutal.Glfw@2026.10.5
#:package Ahwoo.Brutal.OpenGl@2026.10.2
#:package Ahwoo.Brutal.Core@2026.10.4
#:package Ahwoo.Brutal.Numerics@2026.10.2
using Brutal;
using Brutal.Box2DApi;
using Brutal.GlfwApi;
using Brutal.Numerics;
using Brutal.OpenGlApi;
// GLFW is the only library-wide state, set up here and terminated even if Run throws.
if (!Glfw.Init())
{
var errorCode = Glfw.GetError(out var errorMessage);
throw new InvalidOperationException($"Failed to initialize GLFW: {errorCode}, {errorMessage}");
}
try
{
Run();
}
finally
{
Glfw.Terminate();
}
// Everything else: its using declarations dispose in reverse, the program and shaders, then the
// window, then the physics world with all its bodies.
static void Run()
{
// Physics: a static ground and a handful of boxes dropped from different heights.
using var world = Box2D.CreateWorld(B2WorldDef.Default);
var ground = world.CreateBody(new B2BodyDef { Position = new float2(0, -0.5f) });
ground.CreatePolygonShape(B2ShapeDef.Default, Box2D.MakeBox(9, 0.5f)); // Top surface at y = 0.
var bodies = new List<(B2Body Body, float2 HalfSize, float3 Color)>
{
(ground, new float2(9, 0.5f), new float3(0.6f, 0.6f, 0.6f)),
};
for (var i = 0; i < 12; i++)
{
var body = world.CreateBody(
new B2BodyDef
{
Type = B2BodyType.Dynamic,
Position = new float2(-3 + i % 4 * 2f, 4 + i * 1.2f),
Rotation = new B2Rot(i * 0.4f),
}
);
body.CreatePolygonShape(B2ShapeDef.Default, Box2D.MakeBox(0.5f, 0.5f));
bodies.Add((body, new float2(0.5f, 0.5f), new float3(1.0f - i / 12f, 0.5f, i / 12f)));
}
// Window and OpenGL, as in Hello/HelloOpenGl.cs.
Glfw.WindowHint(GlfwWindowHint.ContextVersionMajor, 4);
Glfw.WindowHint(GlfwWindowHint.ContextVersionMinor, 1);
Glfw.WindowHint(GlfwWindowHint.OpenGlProfile, Glfw.Constants.GLFW_OPENGL_CORE_PROFILE);
if (Platform.IsMacOS)
Glfw.WindowHint(GlfwWindowHint.OpenGlForwardCompat, 1);
// A fixed size keeps the viewport and aspect ratio valid.
Glfw.WindowHint(GlfwWindowHint.Resizable, Glfw.Constants.GLFW_FALSE);
using var window = Glfw.CreateWindow(new GlfwWindow.CreateInfo { Title = "Demo Box2D", Size = new int2(640, 480) });
window.MakeContextCurrent();
Glfw.SwapInterval(1);
unsafe
{
if (!Glad.Initialize(Glfw.PInvoke.GetProcAddress))
throw new InvalidOperationException("Failed to initialize OpenGL");
}
window.OnKey += (handle, key, _, _, _) =>
{
if (key == GlfwKey.Escape)
handle.ShouldClose = true;
};
using var vertexShader = OpenGl
.CreateShader(GlShaderType.Vertex)
.SetSource(
"""
#version 410 core
layout (location = 0) in vec2 aPos;
layout (location = 1) in vec3 aColor;
out vec3 color;
void main()
{
color = aColor;
// Show world x in [-10, 10] and y in [-1, 14].
gl_Position = vec4(aPos.x / 10.0, (aPos.y - 6.5) / 7.5, 0.0, 1.0);
}
"""u8
)
.Compile();
using var fragmentShader = OpenGl
.CreateShader(GlShaderType.Fragment)
.SetSource(
"""
#version 410 core
in vec3 color;
out vec4 FragColor;
void main()
{
FragColor = vec4(color, 1.0);
}
"""u8
)
.Compile();
using var program = OpenGl.CreateProgram().Attach(vertexShader, fragmentShader).Link();
// Vertex arrays and buffers aren't disposable, so they're deleted at the end, while the window's
// context still exists.
var vertexArray = OpenGl.GenVertexArray().Bind();
var vertexBuffer = OpenGl.GenBuffer();
vertexBuffer.Bind(GlBindTarget.ArrayBuffer);
OpenGl.VertexAttribute(new GlAttribute(0, 2, OpenGl.GL_FLOAT, GlScaling.Float, 5 * sizeof(float), 0));
OpenGl.VertexAttribute(
new GlAttribute(1, 3, OpenGl.GL_FLOAT, GlScaling.Float, 5 * sizeof(float), 2 * sizeof(float))
);
OpenGl.EnableVertexAttribArray(0);
OpenGl.EnableVertexAttribArray(1);
// Two triangles per box, five floats (x, y, r, g, b) per vertex.
var vertices = new float[bodies.Count * 6 * 5];
float2[] corners = [new(-1, -1), new(1, -1), new(1, 1), new(-1, -1), new(1, 1), new(-1, 1)];
OpenGl.ClearColor(float4.Rgb(0.2f, 0.3f, 0.3f));
const float TIME_STEP = 1.0f / 60.0f;
var previousTime = Glfw.Time;
var accumulator = 0.0;
while (!window.ShouldClose)
{
Glfw.PollEvents();
// Step physics at a fixed rate whatever the refresh rate, capping the catch-up after a stall.
var now = Glfw.Time;
accumulator += Math.Min(now - previousTime, 0.25);
previousTime = now;
while (accumulator >= TIME_STEP)
{
world.Step(TIME_STEP, 4);
accumulator -= TIME_STEP;
}
var v = 0;
foreach (var (body, halfSize, color) in bodies)
{
var transform = body.GetTransform();
foreach (var corner in corners)
{
var local = corner * halfSize;
var p =
transform.P
+ new float2(
transform.Q.C * local.X - transform.Q.S * local.Y,
transform.Q.S * local.X + transform.Q.C * local.Y
);
vertices[v++] = p.X;
vertices[v++] = p.Y;
vertices[v++] = color.X;
vertices[v++] = color.Y;
vertices[v++] = color.Z;
}
}
OpenGl.Clear(GlClearBit.Color);
program.Use();
vertexArray.Bind();
vertexBuffer.Bind(GlBindTarget.ArrayBuffer);
OpenGl.BufferData(GlBindTarget.ArrayBuffer, vertices, GlBufferUsage.DynamicDraw);
OpenGl.Draw(GlTopology.Triangles, bodies.Count * 6, 1, 0, 0);
window.SwapBuffers();
}
OpenGl.DeleteVertexArrays([vertexArray]);
OpenGl.DeleteBuffers([vertexBuffer]);
}

View file

@ -1,431 +0,0 @@
/*
* DemoGltfViewer
*
* Loads a glTF model, reorders it with meshoptimizer for the GPU's vertex cache and fetch, and
* draws it lit and slowly rotating with OpenGL. Pass a .gltf or .glb path to view your own
* model (`dotnet run Demo/DemoGltfViewer.cs -- model.glb`); without one it builds a torus knot,
* writes it out as a .glb with Brutal.Gltf and views that.
*
* It walks the file's scene graph, placing every triangle primitive with its node's matrix or
* translation, rotation and scale; other primitive modes, and quantized (non-float) positions,
* aren't supported. Materials, textures, cameras, lights, skins, morph targets and animations
* are ignored, so the model is drawn untextured in its rest pose. Press Escape to close it.
*/
// Brutal.Gltf uses reflection-based System.Text.Json, which Native AOT (the default for
// file-based apps) disables.
#:property PublishAot=false
#:property AllowUnsafeBlocks=true
#:package Ahwoo.Brutal.Gltf@2026.10.3
#:package Ahwoo.Brutal.MeshOptimizer@2026.10.2
#:package Ahwoo.Brutal.Glfw@2026.10.5
#:package Ahwoo.Brutal.OpenGl@2026.10.2
#:package Ahwoo.Brutal.Core@2026.10.4
#:package Ahwoo.Brutal.Numerics@2026.10.2
using System.Runtime.InteropServices;
using Brutal;
using Brutal.GlfwApi;
using Brutal.GltfApi;
using Brutal.MeshOptimizer;
using Brutal.Numerics;
using Brutal.OpenGlApi;
// GLFW is the only library-wide state, set up here and terminated even if Run throws.
if (!Glfw.Init())
{
var errorCode = Glfw.GetError(out var errorMessage);
throw new InvalidOperationException($"Failed to initialize GLFW: {errorCode}, {errorMessage}");
}
try
{
Run(args);
}
finally
{
Glfw.Terminate();
}
// Everything else: its using declarations dispose in reverse, the program and shaders, then the
// window, then the glTF loader.
static void Run(string[] args)
{
var path = args.Length > 0 ? args[0] : WriteTorusKnotGlb(Path.Combine(Path.GetTempPath(), "DemoGltfViewer.glb"));
// Every primitive goes into one shared vertex and index list, each mesh loaded once however many
// nodes use it; each draw is one of those primitives with the world transform of a node using it.
using var loader = new GltfLoader(path);
var gltf = loader.GltfJson;
List<Vertex> vertices = [];
List<int> indices = [];
var meshPrimitives = new Dictionary<int, List<Primitive>>();
var draws = new List<(Primitive Primitive, float4x4 World)>();
var (transformsBefore, transformsAfter) = (0f, 0f);
// Draw the file's chosen scene, else its first, else every mesh once where it stands.
if ((gltf.Scene ?? (gltf.Scenes?.Length > 0 ? 0 : null)) is { } scene)
foreach (var root in gltf.Scenes![scene].Nodes ?? [])
AddNode(root, float4x4.Identity);
else
for (var mesh = 0; mesh < (gltf.Meshes?.Length ?? 0); mesh++)
draws.AddRange(LoadMesh(mesh).Select(p => (p, float4x4.Identity)));
if (draws.Count == 0)
throw new NotSupportedException($"{Path.GetFileName(path)} has no triangle meshes to draw");
var triangles = indices.Count / 3;
Console.WriteLine(
$"{Path.GetFileName(path)}: {draws.Count} draws, {triangles} triangles, {vertices.Count} vertices"
);
Console.WriteLine(
$"ACMR (vertex transforms per triangle): {transformsBefore / triangles:F2} -> {transformsAfter / triangles:F2}"
);
// Fit the camera to the placed model: centre it on the origin and back off far enough to see all of it.
float3[] points =
[
.. draws.SelectMany(d =>
vertices
.GetRange(d.Primitive.BaseVertex, d.Primitive.VertexCount)
.Select(v => float3.Transform(v.Position, d.World))
),
];
var min = points.Aggregate(float3.Min);
var max = points.Aggregate(float3.Max);
var centre = (min + max) / 2;
var radius = MathF.Max((max - min).Length() / 2, 1e-3f);
// Places a node and its children: a node has either a matrix or translation, rotation and scale,
// whichever it lacks is identity, and a child's world transform is its local one times its parent's.
void AddNode(int nodeIndex, float4x4 parentWorld)
{
var node = gltf.Nodes[nodeIndex];
var trs =
float4x4.CreateScale(node.Scale)
* float4x4.CreateFromQuaternion(node.Rotation)
* float4x4.CreateTranslation(node.Translation);
var world = node.Matrix * trs * parentWorld;
if (node.Mesh is { } mesh)
draws.AddRange(LoadMesh(mesh).Select(p => (p, world)));
foreach (var child in node.Children ?? [])
AddNode(child, world);
}
// Reads a mesh's triangle primitives, filling in indices and normals where the file has none,
// optimises each and appends it to the shared lists.
List<Primitive> LoadMesh(int meshIndex)
{
if (meshPrimitives.TryGetValue(meshIndex, out var loaded))
return loaded;
meshPrimitives[meshIndex] = loaded = [];
foreach (var primitive in gltf.Meshes![meshIndex].Primitives)
{
if (primitive.Mode != MeshPrimitive.ModeEnum.Triangles)
{
Console.WriteLine(
$"Skipping a {primitive.Mode} primitive in mesh {meshIndex}: only triangles are drawn"
);
continue;
}
var positions = ReadFloat3s(loader, primitive.Attributes["POSITION"]);
int[] ids = primitive.Indices is { } i
? ReadIndices(loader, i)
: [.. Enumerable.Range(0, positions.Length)];
var normals = primitive.Attributes.TryGetValue("NORMAL", out var n)
? ReadFloat3s(loader, n)
: SmoothNormals(positions, ids);
var verts = positions.Zip(normals, (p, q) => new Vertex(p, q)).ToArray();
// Reorder triangles so recently used vertices are reused, then vertices into first-use order.
unsafe
{
fixed (int* p = ids)
fixed (Vertex* v = verts)
{
// AnalyzeVertexCache arguments: cache size 16, warp size 0, primitive group size 0.
transformsBefore +=
MeshOptimizer.AnalyzeVertexCache(p, ids.Length, verts.Length, 16, 0, 0).Acmr * ids.Length / 3;
MeshOptimizer.OptimizeVertexCache(p, p, ids.Length, verts.Length);
MeshOptimizer.OptimizeVertexFetch(v, p, ids.Length, v, verts.Length, ByteSize.Of<Vertex>());
transformsAfter +=
MeshOptimizer.AnalyzeVertexCache(p, ids.Length, verts.Length, 16, 0, 0).Acmr * ids.Length / 3;
}
}
loaded.Add(new Primitive(indices.Count, ids.Length, vertices.Count, verts.Length));
indices.AddRange(ids);
vertices.AddRange(verts);
}
return loaded;
}
// Window and OpenGL, as in Hello/HelloOpenGl.cs.
Glfw.WindowHint(GlfwWindowHint.ContextVersionMajor, 4);
Glfw.WindowHint(GlfwWindowHint.ContextVersionMinor, 1);
Glfw.WindowHint(GlfwWindowHint.OpenGlProfile, Glfw.Constants.GLFW_OPENGL_CORE_PROFILE);
if (Platform.IsMacOS)
Glfw.WindowHint(GlfwWindowHint.OpenGlForwardCompat, 1);
// A fixed size, so the viewport and the projection's aspect ratio never need updating.
Glfw.WindowHint(GlfwWindowHint.Resizable, Glfw.Constants.GLFW_FALSE);
using var window = Glfw.CreateWindow(
new GlfwWindow.CreateInfo { Title = "Demo glTF Viewer", Size = new int2(640, 480) }
);
window.MakeContextCurrent();
Glfw.SwapInterval(1);
unsafe
{
if (!Glad.Initialize(Glfw.PInvoke.GetProcAddress))
throw new InvalidOperationException("Failed to initialize OpenGL");
}
window.OnKey += (handle, key, _, _, _) =>
{
if (key == GlfwKey.Escape)
handle.ShouldClose = true;
};
using var vertexShader = OpenGl
.CreateShader(GlShaderType.Vertex)
.SetSource(
"""
#version 410 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal;
uniform mat4 model;
uniform mat4 viewProjection;
out vec3 normal;
void main()
{
normal = transpose(inverse(mat3(model))) * aNormal;
gl_Position = viewProjection * model * vec4(aPos, 1.0);
}
"""u8
)
.Compile();
using var fragmentShader = OpenGl
.CreateShader(GlShaderType.Fragment)
.SetSource(
"""
#version 410 core
in vec3 normal;
out vec4 FragColor;
void main()
{
// A warm key light and a cool fill from below, plus a little ambient.
vec3 n = normalize(normal);
vec3 key = vec3(1.0, 0.9, 0.75) * max(dot(n, normalize(vec3(0.4, 1.0, 0.6))), 0.0);
vec3 fill = vec3(0.25, 0.3, 0.45) * max(dot(n, normalize(vec3(-0.6, -0.4, -0.3))), 0.0);
FragColor = vec4(vec3(0.8) * (0.15 + key + fill), 1.0);
}
"""u8
)
.Compile();
using var program = OpenGl.CreateProgram().Attach(vertexShader, fragmentShader).Link();
// Vertex arrays and buffers aren't disposable, so they're deleted at the end, while the window's
// context still exists.
var vertexArray = OpenGl.GenVertexArray().Bind();
var vertexBuffer = OpenGl.GenBuffer();
var indexBuffer = OpenGl.GenBuffer();
vertexBuffer.Bind(GlBindTarget.ArrayBuffer);
OpenGl.BufferData(GlBindTarget.ArrayBuffer, vertices.ToArray(), GlBufferUsage.StaticDraw);
indexBuffer.Bind(GlBindTarget.ElementArrayBuffer); // Recorded in the vertex array.
OpenGl.BufferData(GlBindTarget.ElementArrayBuffer, indices.ToArray(), GlBufferUsage.StaticDraw);
OpenGl.VertexAttribute(new GlAttribute(0, 3, OpenGl.GL_FLOAT, GlScaling.Float, 6 * sizeof(float), 0));
OpenGl.VertexAttribute(
new GlAttribute(1, 3, OpenGl.GL_FLOAT, GlScaling.Float, 6 * sizeof(float), 3 * sizeof(float))
);
OpenGl.EnableVertexAttribArray(0);
OpenGl.EnableVertexAttribArray(1);
OpenGl.Enable(GlCapability.DepthTest);
OpenGl.ClearColor(float4.Rgb(0.2f, 0.3f, 0.3f));
// 45 degree field of view: a sphere of this radius just fits at radius / sin(22.5 degrees).
var view = float4x4.CreateLookAt(new float3(0, 0.4f, 1) * radius * 2.8f, float3.Zero, float3.UnitY);
var projection = float4x4.CreatePerspectiveFieldOfView(MathF.PI / 4, 640f / 480f, radius / 10, radius * 10);
while (!window.ShouldClose)
{
Glfw.PollEvents();
OpenGl.Clear(GlClearBit.Color | GlClearBit.Depth);
program.Use();
program.Uniform("viewProjection"u8, view * projection);
vertexArray.Bind();
var spin = float4x4.CreateTranslation(-centre) * float4x4.CreateRotationY((float)Glfw.Time * 0.5f);
foreach (var (primitive, world) in draws)
{
// The first index is passed as a byte offset into the index buffer.
program.Uniform("model"u8, world * spin);
OpenGl.DrawIndexed(
GlTopology.Triangles,
GlIndexType.UInt,
primitive.IndexCount,
1,
primitive.FirstIndex * sizeof(int),
primitive.BaseVertex,
0
);
}
window.SwapBuffers();
}
OpenGl.DeleteVertexArrays([vertexArray]);
OpenGl.DeleteBuffers([vertexBuffer, indexBuffer]);
}
// Reads a float VEC3 accessor, such as positions or normals, which may be interleaved with other data.
static float3[] ReadFloat3s(GltfLoader loader, int accessorIndex)
{
var accessor = loader.GltfJson.Accessors[accessorIndex];
if (accessor.ComponentType != Accessor.ComponentTypeEnum.Float || accessor.Type != Accessor.TypeEnum.Vec3)
throw new NotSupportedException($"Expected float VEC3 data, not {accessor.ComponentType} {accessor.Type}");
var bytes = loader.GetBufferView(accessor.BufferView!.Value)[accessor.ByteOffset..];
var stride = loader.GltfJson.BufferViews[accessor.BufferView.Value].ByteStride ?? 3 * sizeof(float);
var result = new float3[accessor.Count];
for (var i = 0; i < result.Length; i++)
result[i] = MemoryMarshal.Read<float3>(bytes[(i * stride)..]);
return result;
}
// Reads an index accessor of any of the three index sizes glTF allows, widening to 32-bit.
static int[] ReadIndices(GltfLoader loader, int accessorIndex)
{
var accessor = loader.GltfJson.Accessors[accessorIndex];
var bytes = loader.GetBufferView(accessor.BufferView!.Value)[accessor.ByteOffset..];
return accessor.ComponentType switch
{
Accessor.ComponentTypeEnum.UnsignedByte => [.. bytes[..accessor.Count].ToArray().Select(b => (int)b)],
Accessor.ComponentTypeEnum.UnsignedShort =>
[
.. MemoryMarshal.Cast<byte, ushort>(bytes)[..accessor.Count].ToArray().Select(s => (int)s),
],
_ => MemoryMarshal.Cast<byte, int>(bytes)[..accessor.Count].ToArray(),
};
}
// Sums each triangle's area-weighted face normal into its vertices; flat when no vertices are shared.
static float3[] SmoothNormals(float3[] positions, int[] indices)
{
var normals = new float3[positions.Length];
foreach (var t in indices.Chunk(3))
{
var normal = float3.Cross(positions[t[1]] - positions[t[0]], positions[t[2]] - positions[t[0]]);
foreach (var index in t)
normals[index] += normal;
}
return [.. normals.Select(float3.NormalizeOrZero)];
}
// Sweeps a circle along a (2, 3) torus knot and writes the result as a .glb with Brutal.Gltf,
// positions and indices only, so the viewer has to compute its normals.
static string WriteTorusKnotGlb(string path)
{
const int SEGMENTS = 256;
const int SIDES = 24;
static float3 Knot(float u)
{
var r = 2 + MathF.Cos(3 * u);
return new float3(r * MathF.Cos(2 * u), MathF.Sin(3 * u), r * MathF.Sin(2 * u));
}
// Vertex index of a point on the tube, wrapping around both the knot and the tube.
static int At(int ring, int around) => ring % SEGMENTS * SIDES + around % SIDES;
var positions = new List<float3>();
var indices = new List<int>();
for (var s = 0; s < SEGMENTS; s++)
{
// A frame around the curve: tangent from a step ahead, then two perpendicular axes.
var u = s * MathF.Tau / SEGMENTS;
var (here, ahead) = (Knot(u), Knot(u + 0.01f));
var side = float3.Normalize(float3.Cross(ahead - here, ahead + here));
var up = float3.Normalize(float3.Cross(side, ahead - here));
for (var j = 0; j < SIDES; j++)
{
var v = j * MathF.Tau / SIDES;
positions.Add(here + (up * MathF.Cos(v) + side * MathF.Sin(v)) * 0.4f);
// Two triangles joining this point to the next ring, counter-clockwise seen from outside as glTF expects.
indices.AddRange([At(s, j), At(s + 1, j + 1), At(s + 1, j)]);
indices.AddRange([At(s, j), At(s, j + 1), At(s + 1, j + 1)]);
}
}
var positionBytes = MemoryMarshal.AsBytes(positions.ToArray().AsSpan()).ToArray();
var indexBytes = MemoryMarshal.AsBytes(indices.ToArray().AsSpan()).ToArray();
var (min, max) = (positions.Aggregate(float3.Min), positions.Aggregate(float3.Max));
// One binary buffer holding the positions then the indices, a view into each, and an
// accessor saying how to read each view; glTF requires min and max on positions.
var model = new Gltf
{
Asset = new Asset { Version = "2.0" },
Buffers = [new Brutal.GltfApi.Buffer { ByteLength = positionBytes.Length + indexBytes.Length }],
BufferViews =
[
new BufferView { Buffer = 0, ByteLength = positionBytes.Length },
new BufferView
{
Buffer = 0,
ByteOffset = positionBytes.Length,
ByteLength = indexBytes.Length,
},
],
Accessors =
[
new Accessor
{
BufferView = 0,
ComponentType = Accessor.ComponentTypeEnum.Float,
Count = positions.Count,
Type = Accessor.TypeEnum.Vec3,
Min = [min.X, min.Y, min.Z],
Max = [max.X, max.Y, max.Z],
},
new Accessor
{
BufferView = 1,
ComponentType = Accessor.ComponentTypeEnum.UnsignedInt,
Count = indices.Count,
Type = Accessor.TypeEnum.Scalar,
},
],
Meshes =
[
new Mesh
{
Primitives =
[
new MeshPrimitive
{
Attributes = new() { ["POSITION"] = 0 },
Indices = 1,
},
],
},
],
};
model.SaveBinaryModel([.. positionBytes, .. indexBytes], path);
return path;
}
record struct Vertex(float3 Position, float3 Normal);
// Where a primitive lives in the shared index and vertex lists.
record struct Primitive(int FirstIndex, int IndexCount, int BaseVertex, int VertexCount);

View file

@ -1,140 +0,0 @@
/*
* DemoImGui
*
* Dear ImGui on GLFW + OpenGL: a button, a slider and an ImPlot line plot, with fonts
* rasterised by FreeType. Press Escape to close it.
*
* Optionally pass a font:
*
* dotnet run Demo/DemoImGui.cs -- path/to/font.ttf
*/
#:property AllowUnsafeBlocks=true
#:package Ahwoo.Brutal.ImGui@2026.10.3
#:package Ahwoo.Brutal.ImGui.Backends@2026.10.3
#:package Ahwoo.Brutal.ImGui.FreeType@2026.10.3
#:package Ahwoo.Brutal.ImPlot@2026.10.3
#:package Ahwoo.Brutal.Core@2026.10.4
#:package Ahwoo.Brutal.Glfw@2026.10.5
#:package Ahwoo.Brutal.Numerics@2026.10.2
#:package Ahwoo.Brutal.OpenGl@2026.10.2
using Brutal;
using Brutal.GlfwApi;
using Brutal.ImGuiApi;
using Brutal.ImGuiApi.Backends;
using Brutal.ImGuiApi.FreeType;
using Brutal.ImPlotApi;
using Brutal.Numerics;
using Brutal.OpenGlApi;
if (!Glfw.Init())
{
var errorCode = Glfw.GetError(out var errorMessage);
throw new InvalidOperationException($"Failed to initialize GLFW: {errorCode}, {errorMessage}");
}
var context = ImGui.CreateContext();
var plotContext = ImPlot.CreateContext();
ImPlot.SetImGuiContext(context);
try
{
Run(args);
}
finally
{
ImPlot.DestroyContext(plotContext);
ImGui.DestroyContext(context);
Glfw.Terminate();
}
static void Run(string[] args)
{
Glfw.WindowHint(GlfwWindowHint.ContextVersionMajor, 4);
Glfw.WindowHint(GlfwWindowHint.ContextVersionMinor, 1);
Glfw.WindowHint(GlfwWindowHint.OpenGlProfile, Glfw.Constants.GLFW_OPENGL_CORE_PROFILE);
if (Platform.IsMacOS)
Glfw.WindowHint(GlfwWindowHint.OpenGlForwardCompat, 1);
// Declared first so it's disposed last: the backends below need the window and its GL context.
using var window = Glfw.CreateWindow(new GlfwWindow.CreateInfo { Title = "Demo ImGui", Size = new int2(800, 600) });
window.MakeContextCurrent();
Glfw.SwapInterval(1); // Wait for vsync instead of drawing as fast as possible.
unsafe
{
if (!Glad.Initialize(Glfw.PInvoke.GetProcAddress))
throw new InvalidOperationException("Failed to initialize OpenGL");
}
window.OnKey += (handle, key, _, _, _) =>
{
if (key == GlfwKey.Escape)
handle.ShouldClose = true;
};
ImGui.GetIO().IniFilename = null; // Don't write imgui.ini.
// Rasterize fonts with FreeType instead of the built-in stb_truetype.
var fonts = ImGui.GetIO().Fonts;
fonts.SetFontLoader(ImGuiFreeType.GetFontLoader());
if (args.Length > 0)
fonts.AddFontFromFileTTF(args[0], 24f); // Optional: dotnet run Demo/DemoImGui.cs -- path/to/font.ttf.
using var glfwBackend = new GlfwBackend(window, GlfwBackend.ClientApi.OpenGL);
using var openGlBackend = new OpenGlBackend();
var clicks = 0;
var frequency = 1f;
var xs = new float[200];
var ys = new float[200];
OpenGl.ClearColor(float4.Rgb(0.2f, 0.3f, 0.3f));
while (!window.ShouldClose)
{
Glfw.PollEvents();
glfwBackend.NewFrame();
openGlBackend.NewFrame();
ImGui.NewFrame();
// Recycle the scratch memory that interpolated ImGui strings ($"...") use, once per frame.
ImString.SharedStorage.Reset();
var time = (float)Glfw.Time;
for (var i = 0; i < xs.Length; i++)
{
xs[i] = i * 0.05f;
ys[i] = MathF.Sin(xs[i] * frequency + time);
}
ImGui.SetNextWindowSize(new float2(500, 400), ImGuiCond.FirstUseEver);
if (ImGui.Begin("Demo ImGui"u8))
{
ImGui.Text("Hello from Dear ImGui!"u8);
if (ImGui.Button("Click me"u8))
clicks++;
ImGui.SameLine();
ImGui.Text($"Clicked {clicks} times");
ImGui.SliderFloat("Frequency"u8, ref frequency, 0.1f, 5f);
if (ImPlot.BeginPlot("Sine Wave"u8, new float2(-1, -1))) // Fill the rest of the window.
{
ImPlot.PlotLine("sin(x * f + t)"u8, xs, ys);
ImPlot.EndPlot();
}
}
ImGui.End();
ImGui.Render();
OpenGl.Clear(GlClearBit.Color);
openGlBackend.RenderDrawData(ImGui.GetDrawData());
window.SwapBuffers();
}
}

View file

@ -1,256 +0,0 @@
/*
* DemoJolt
*
* Drops a pile of boxes onto the ground with Jolt Physics and draws them in 3D with OpenGL every
* frame: the visual counterpart of the headless Hello/HelloJolt.cs. Press Escape to close it.
*/
#:property AllowUnsafeBlocks=true
#:package Ahwoo.Brutal.Jolt@2026.10.4
#:package Ahwoo.Brutal.Glfw@2026.10.5
#:package Ahwoo.Brutal.OpenGl@2026.10.2
#:package Ahwoo.Brutal.Core@2026.10.4
#:package Ahwoo.Brutal.Numerics@2026.10.2
using Brutal;
using Brutal.GlfwApi;
using Brutal.JoltApi;
using Brutal.Numerics;
using Brutal.OpenGlApi;
const ushort STATIC_LAYER = 0;
const ushort MOVING_LAYER = 1;
// Library-wide state, shut down in reverse even if Run throws: Jolt needs an allocator, a factory
// and its types registered before it can simulate anything, and GLFW provides the window.
Jolt.RegisterDefaultAllocator();
Factory.Instance = Factory.Create();
Jolt.RegisterTypes();
try
{
if (!Glfw.Init())
{
var errorCode = Glfw.GetError(out var errorMessage);
throw new InvalidOperationException($"Failed to initialize GLFW: {errorCode}, {errorMessage}");
}
try
{
Run();
}
finally
{
Glfw.Terminate();
}
}
finally
{
Jolt.UnregisterTypes();
Factory.DestroyInstance();
}
// Everything else: its using declarations dispose in reverse, so the OpenGL objects and window go
// first, then the bodies' shapes and settings, then the physics system and what it was built from.
static void Run()
{
// Physics: a job system and collision layers.
using var tempAllocator = TempAllocatorImpl.Create(10 * 1024 * 1024);
using var jobSystem = JobSystemThreadPool.Create(2048, 8, -1);
using var broadPhaseLayers = BroadPhaseLayerInterfaceTable.Create(2, 2);
broadPhaseLayers.MapObjectToBroadPhaseLayer(STATIC_LAYER, 0);
broadPhaseLayers.MapObjectToBroadPhaseLayer(MOVING_LAYER, 1);
using var pairFilter = ObjectLayerPairFilterTable.Create(2);
pairFilter.EnableCollision(STATIC_LAYER, MOVING_LAYER);
pairFilter.EnableCollision(MOVING_LAYER, MOVING_LAYER);
using var broadPhaseFilter = ObjectVsBroadPhaseLayerFilterTable.Create(broadPhaseLayers, 2, pairFilter, 2);
using var physicsSystem = PhysicsSystem.Create();
physicsSystem.Init(1024, 0, 1024, 1024, broadPhaseLayers, broadPhaseFilter, pairFilter);
var bodyInterface = physicsSystem.GetBodyInterface();
var bodies = new List<(uint Body, float3 HalfSize, float3 Color)>();
var groundHalfSize = new float3(8, 0.5f, 8);
using var groundShape = BoxShapeSettings.Create(groundHalfSize, 0.05f, default);
using var groundSettings = BodyCreationSettings.Create(
groundShape,
new float3(0, -0.5f, 0), // Top surface at y = 0.
floatQuat.Identity,
MotionType.Static,
STATIC_LAYER
);
var boxHalfSize = new float3(0.5f);
using var boxShape = BoxShapeSettings.Create(boxHalfSize, 0.05f, default);
// Bodies are IDs, not disposable: they're removed and destroyed at the end, before their shapes
// and the physics system are disposed.
bodies.Add(
(bodyInterface.CreateAndAddBody(groundSettings, Activation.DontActivate), groundHalfSize, new float3(0.6f))
);
for (var i = 0; i < 20; i++)
{
using var boxSettings = BodyCreationSettings.Create(
boxShape,
new float3(-1.5f + i % 3 * 1.5f, 3 + i * 1.2f, -1.5f + i % 2 * 1.5f),
floatQuat.CreateFromYawPitchRoll(i * 0.5f, i * 0.3f, i * 0.7f),
MotionType.Dynamic,
MOVING_LAYER
);
var body = bodyInterface.CreateAndAddBody(boxSettings, Activation.Activate);
bodies.Add((body, boxHalfSize, new float3(1.0f - i / 20f, 0.5f, i / 20f)));
}
// Window and OpenGL, as in Hello/HelloOpenGl.cs.
Glfw.WindowHint(GlfwWindowHint.ContextVersionMajor, 4);
Glfw.WindowHint(GlfwWindowHint.ContextVersionMinor, 1);
Glfw.WindowHint(GlfwWindowHint.OpenGlProfile, Glfw.Constants.GLFW_OPENGL_CORE_PROFILE);
if (Platform.IsMacOS)
Glfw.WindowHint(GlfwWindowHint.OpenGlForwardCompat, 1);
// A fixed size keeps the viewport and aspect ratio valid.
Glfw.WindowHint(GlfwWindowHint.Resizable, Glfw.Constants.GLFW_FALSE);
using var window = Glfw.CreateWindow(new GlfwWindow.CreateInfo { Title = "Demo Jolt", Size = new int2(640, 480) });
window.MakeContextCurrent();
Glfw.SwapInterval(1);
unsafe
{
if (!Glad.Initialize(Glfw.PInvoke.GetProcAddress))
throw new InvalidOperationException("Failed to initialize OpenGL");
}
window.OnKey += (handle, key, _, _, _) =>
{
if (key == GlfwKey.Escape)
handle.ShouldClose = true;
};
using var vertexShader = OpenGl
.CreateShader(GlShaderType.Vertex)
.SetSource(
"""
#version 410 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal;
uniform mat4 model;
uniform mat4 viewProjection;
out vec3 normal;
void main()
{
normal = mat3(model) * aNormal;
gl_Position = viewProjection * model * vec4(aPos, 1.0);
}
"""u8
)
.Compile();
using var fragmentShader = OpenGl
.CreateShader(GlShaderType.Fragment)
.SetSource(
"""
#version 410 core
in vec3 normal;
uniform vec3 color;
out vec4 FragColor;
void main()
{
// Simple directional light plus a little ambient.
float light = max(dot(normalize(normal), normalize(vec3(0.4, 1.0, 0.6))), 0.0);
FragColor = vec4(color * (0.3 + 0.7 * light), 1.0);
}
"""u8
)
.Compile();
using var program = OpenGl.CreateProgram().Attach(vertexShader, fragmentShader).Link();
// A cube from -1 to 1: two triangles per face, each vertex with a position and a face normal.
var cube = new List<Vertex>();
foreach (
var normal in new[] { float3.UnitX, -float3.UnitX, float3.UnitY, -float3.UnitY, float3.UnitZ, -float3.UnitZ }
)
{
var u = new float3(normal.Y, normal.Z, normal.X);
var v = float3.Cross(normal, u);
float2[] corners = [new(-1, -1), new(1, -1), new(1, 1), new(-1, -1), new(1, 1), new(-1, 1)];
foreach (var corner in corners)
cube.Add(new Vertex(normal + u * corner.X + v * corner.Y, normal));
}
// Vertex arrays and buffers aren't disposable, so they're deleted at the end, while the
// window's context still exists.
var vertexArray = OpenGl.GenVertexArray().Bind();
var vertexBuffer = OpenGl.GenBuffer();
vertexBuffer.Bind(GlBindTarget.ArrayBuffer);
OpenGl.BufferData(GlBindTarget.ArrayBuffer, cube.ToArray(), GlBufferUsage.StaticDraw);
OpenGl.VertexAttribute(new GlAttribute(0, 3, OpenGl.GL_FLOAT, GlScaling.Float, 6 * sizeof(float), 0));
OpenGl.VertexAttribute(
new GlAttribute(1, 3, OpenGl.GL_FLOAT, GlScaling.Float, 6 * sizeof(float), 3 * sizeof(float))
);
OpenGl.EnableVertexAttribArray(0);
OpenGl.EnableVertexAttribArray(1);
OpenGl.Enable(GlCapability.DepthTest);
OpenGl.ClearColor(float4.Rgb(0.2f, 0.3f, 0.3f));
var view = float4x4.CreateLookAt(new float3(8, 7, 12), new float3(0, 1.5f, 0), float3.UnitY);
var projection = float4x4.CreatePerspectiveFieldOfView(float.DegreesToRadians(45), 640f / 480f, 0.1f, 100f);
const float TIME_STEP = 1.0f / 60.0f;
var previousTime = Glfw.Time;
var accumulator = 0.0;
while (!window.ShouldClose)
{
Glfw.PollEvents();
// Step physics at a fixed rate whatever the refresh rate, capping the catch-up after a stall.
var now = Glfw.Time;
accumulator += Math.Min(now - previousTime, 0.25);
previousTime = now;
while (accumulator >= TIME_STEP)
{
physicsSystem.Update(TIME_STEP, 1, tempAllocator, jobSystem);
accumulator -= TIME_STEP;
}
OpenGl.Clear(GlClearBit.Color | GlClearBit.Depth);
program.Use();
program.Uniform("viewProjection"u8, view * projection);
vertexArray.Bind();
foreach (var (body, halfSize, color) in bodies)
{
bodyInterface.GetPositionAndRotation(body, out var position, out var rotation);
var model =
float4x4.CreateScale(halfSize)
* float4x4.CreateFromQuaternion(rotation)
* float4x4.CreateTranslation(position);
program.Uniform("model"u8, model);
program.Uniform("color"u8, color);
OpenGl.Draw(GlTopology.Triangles, cube.Count, 1, 0, 0);
}
window.SwapBuffers();
}
OpenGl.DeleteVertexArrays([vertexArray]);
OpenGl.DeleteBuffers([vertexBuffer]);
foreach (var (body, _, _) in bodies)
{
bodyInterface.RemoveBody(body);
bodyInterface.DestroyBody(body);
}
}
record struct Vertex(float3 Position, float3 Normal);

View file

@ -1,191 +0,0 @@
/*
* DemoRenderDoc
*
* Draws the coloured triangle from Hello/HelloOpenGl.cs and captures a frame with RenderDoc when
* you press F12. Captures work when the app is launched from RenderDoc (Windows or Linux), or on
* Windows when RenderDoc is installed in its default folder; otherwise (always on macOS) it still
* draws and F12 just prints a hint. Press Escape to close it.
*/
#:property AllowUnsafeBlocks=true
#:package Ahwoo.Brutal.Glfw@2026.10.5
#:package Ahwoo.Brutal.OpenGl@2026.10.2
#:package Ahwoo.Brutal.RenderDoc@2026.10.3
#:package Ahwoo.Brutal.Core@2026.10.4
#:package Ahwoo.Brutal.Numerics@2026.10.2
#:package Ahwoo.Brutal.Strings@2026.10.2
using Brutal;
using Brutal.GlfwApi;
using Brutal.Numerics;
using Brutal.OpenGlApi;
using Brutal.RenderDocApi;
using Brutal.Strings;
const string HINT = "RenderDoc isn't loaded: launch this app from RenderDoc (Windows or Linux) to capture frames.";
// Load the in-app API before any graphics API is initialized, so RenderDoc sees every GL call.
RenderDoc.Initialize();
if (RenderDoc.IsAvailable)
{
// F12 is handled below with TriggerCapture, so turn off RenderDoc's own capture keys.
RenderDoc.SetCaptureKeys([]);
Console.WriteLine($"RenderDoc {RenderDoc.Version} loaded, press F12 to capture a frame.");
Console.WriteLine($"Captures are written to {Utf8.GetString(RenderDoc.CaptureFilePathTemplate)}*.rdc");
}
else
{
Console.WriteLine(HINT);
}
if (!Glfw.Init())
{
var errorCode = Glfw.GetError(out var errorMessage);
throw new InvalidOperationException($"Failed to initialize GLFW: {errorCode}, {errorMessage}");
}
try
{
Run();
}
finally
{
Glfw.Terminate();
}
static void Run()
{
// Window, shaders and triangle, as in Hello/HelloOpenGl.cs.
Glfw.WindowHint(GlfwWindowHint.ContextVersionMajor, 4);
Glfw.WindowHint(GlfwWindowHint.ContextVersionMinor, 1);
Glfw.WindowHint(GlfwWindowHint.OpenGlProfile, Glfw.Constants.GLFW_OPENGL_CORE_PROFILE);
if (Platform.IsMacOS)
Glfw.WindowHint(GlfwWindowHint.OpenGlForwardCompat, 1);
// A fixed size keeps the viewport and aspect ratio valid.
Glfw.WindowHint(GlfwWindowHint.Resizable, Glfw.Constants.GLFW_FALSE);
// Declared first so it's disposed last, after the GL objects that need its context.
using var window = Glfw.CreateWindow(
new GlfwWindow.CreateInfo { Title = "Demo RenderDoc", Size = new int2(640, 480) }
);
window.MakeContextCurrent();
Glfw.SwapInterval(1);
unsafe
{
if (!Glad.Initialize(Glfw.PInvoke.GetProcAddress))
throw new InvalidOperationException("Failed to initialize OpenGL");
}
window.OnKey += (handle, key, _, action, _) =>
{
if (key == GlfwKey.Escape)
handle.ShouldClose = true;
if (key != GlfwKey.F12 || action != GlfwKeyAction.Press)
return;
if (!RenderDoc.IsAvailable)
{
Console.WriteLine(HINT);
return;
}
// Captures the next frame that is presented with SwapBuffers.
RenderDoc.TriggerCapture();
};
// Declared after the window, so the program is deleted while the GL context still exists.
using var program = LinkProgram();
// The vertex array and buffer aren't IDisposable, so they're deleted at the end, while the window's
// GL context still exists.
var vertexArray = OpenGl.GenVertexArray().Bind();
var vertexBuffer = OpenGl.GenBuffer();
vertexBuffer.Bind(GlBindTarget.ArrayBuffer);
OpenGl.BufferData(
GlBindTarget.ArrayBuffer,
new Vertex[]
{
new(new float2(0.0f, 0.5f), new float3(1.0f, 0.0f, 0.0f)),
new(new float2(0.5f, -0.5f), new float3(0.0f, 1.0f, 0.0f)),
new(new float2(-0.5f, -0.5f), new float3(0.0f, 0.0f, 1.0f)),
},
GlBufferUsage.StaticDraw
);
OpenGl.VertexAttribute(new GlAttribute(0, 2, OpenGl.GL_FLOAT, GlScaling.Float, 5 * sizeof(float), 0));
OpenGl.VertexAttribute(
new GlAttribute(1, 3, OpenGl.GL_FLOAT, GlScaling.Float, 5 * sizeof(float), 2 * sizeof(float))
);
OpenGl.EnableVertexAttribArray(0);
OpenGl.EnableVertexAttribArray(1);
OpenGl.ClearColor(float4.Rgb(0.2f, 0.3f, 0.3f));
var captureCount = 0u;
while (!window.ShouldClose)
{
Glfw.PollEvents();
OpenGl.Clear(GlClearBit.Color);
program.Use();
vertexArray.Bind();
OpenGl.Draw(GlTopology.Triangles, 3, 1, 0, 0);
window.SwapBuffers();
// A finished capture (from F12 or the RenderDoc UI) is added to RenderDoc's capture list.
if (RenderDoc.IsAvailable && RenderDoc.NumCaptures > captureCount)
{
captureCount = RenderDoc.NumCaptures;
if (RenderDoc.TryGetCapture((int)captureCount - 1, out var path, out _))
Console.WriteLine($"Captured {path}");
}
}
OpenGl.DeleteVertexArrays([vertexArray]);
OpenGl.DeleteBuffers([vertexBuffer]);
}
// The shaders are only needed until the program is linked, so they are disposed on return.
static GlProgram LinkProgram()
{
using var vertexShader = OpenGl
.CreateShader(GlShaderType.Vertex)
.SetSource(
"""
#version 410 core
layout (location = 0) in vec2 aPos;
layout (location = 1) in vec3 aColor;
out vec3 color;
void main()
{
color = aColor;
gl_Position = vec4(aPos, 0.0, 1.0);
}
"""u8
)
.Compile();
using var fragmentShader = OpenGl
.CreateShader(GlShaderType.Fragment)
.SetSource(
"""
#version 410 core
in vec3 color;
out vec4 FragColor;
void main()
{
FragColor = vec4(color, 1.0);
}
"""u8
)
.Compile();
return OpenGl.CreateProgram().Attach(vertexShader, fragmentShader).Link();
}
record struct Vertex(float2 Position, float3 Color);

View file

@ -1,134 +0,0 @@
/*
* DemoSdl
*
* Opens an SDL window and uses its add-ons: Sdl.Image saves and loads a PNG, Sdl.Mixer beeps
* when you press Space, and Sdl.Ttf draws text if you pass a font. Press Escape to close it.
*
* Optionally pass a font:
*
* dotnet run Demo/DemoSdl.cs -- path/to/font.ttf
*/
#:property AllowUnsafeBlocks=true
#:package Ahwoo.Brutal.Sdl@2026.10.3
#:package Ahwoo.Brutal.Sdl.Image@2026.10.3
#:package Ahwoo.Brutal.Sdl.Mixer@2026.10.3
#:package Ahwoo.Brutal.Sdl.Ttf@2026.10.3
using Brutal.SdlApi;
using Brutal.SdlApi.Image;
using Brutal.SdlApi.Mixer;
using Brutal.SdlApi.Ttf;
const uint DEFAULT_PLAYBACK_DEVICE = 0xFFFFFFFFu; // SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK
Sdl.Init.Initialize(SdlInitFlags.Video | SdlInitFlags.Audio);
SdlTtf.Init();
SdlMixer.Init();
try
{
Run(args);
}
finally
{
SdlMixer.Quit();
SdlTtf.Quit();
Sdl.Init.Quit();
}
// Unsafe for the surface and rectangle pointers and the mixer's null spec.
static unsafe void Run(string[] args)
{
// Declared in dependency order, so the using declarations dispose them in reverse when Run returns: the
// track, tone and mixer, then the text, font, image, renderer and window.
using var window = Sdl.Video.CreateWindow("Demo Sdl", 640, 480, SdlWindowFlags.Resizable);
using var renderer = Sdl.Render.CreateRenderer(window, null!); // null picks the best available driver.
Sdl.Render.SetRenderVSync(renderer, 1);
// Sdl.Image: paint a gradient, save it as a PNG, then load it back as a texture.
var imagePath = Path.Combine(Path.GetTempPath(), "DemoSdl.png");
var surface = Sdl.PInvoke.CreateSurface(256, 256, SdlPixelFormat.Rgba8888);
for (var y = 0; y < 256; y++)
for (var x = 0; x < 256; x++)
Sdl.PInvoke.WriteSurfacePixel(surface, x, y, (byte)x, (byte)y, 128, 255);
SdlImage.SavePNG(surface, imagePath);
Sdl.PInvoke.DestroySurface(surface);
using var image = SdlImage.LoadTexture(renderer, imagePath);
// Sdl.Ttf: render text with a font, if one was given (dotnet run Demo/DemoSdl.cs -- path/to/font.ttf).
// Without one, the font and text stay default handles, which Dispose skips.
var hasFont = args.Length > 0;
using var font = hasFont ? SdlTtf.OpenFont(args[0], 32f) : default;
using var text = hasFont ? RenderText(renderer, font, "Demo Sdl Ttf") : default;
var textSize = (w: 0f, h: 0f);
if (hasFont)
Sdl.Render.GetTextureSize(text, out textSize.w, out textSize.h);
// Sdl.Mixer: a 440 Hz tone, played whenever Space is pressed (key auto-repeat is ignored).
using var mixer = SdlMixer.CreateMixerDevice(DEFAULT_PLAYBACK_DEVICE, null);
using var tone = mixer.CreateSineWaveAudio(440, 0.25f, 250);
using var track = mixer.CreateTrack();
track.SetAudio(tone);
var running = true;
while (running)
{
while (Sdl.Events.PollEvent(out var ev))
{
if (ev.type is SdlEventType.Quit or SdlEventType.WindowCloseRequested)
running = false;
else if (ev.type == SdlEventType.KeyDown && ev.key.scancode == SdlScancode.Escape)
running = false;
else if (ev.type == SdlEventType.KeyDown && ev.key.scancode == SdlScancode.Space && ev.key.repeat == 0)
track.Play(0);
}
Sdl.Render.SetRenderDrawColor(renderer, 51, 77, 77, 255);
Sdl.Render.RenderClear(renderer);
Sdl.Render.SetRenderDrawColor(renderer, 255, 255, 255, 255);
Sdl.Render.RenderDebugText(renderer, 16, 16, "Demo Sdl - press Space to beep");
var imageRect = new SdlFRect
{
x = 16,
y = 40,
w = 256,
h = 256,
};
Sdl.Render.RenderTexture(renderer, image, null, &imageRect);
if (hasFont)
{
var textRect = new SdlFRect
{
x = 16,
y = 312,
w = textSize.w,
h = textSize.h,
};
Sdl.Render.RenderTexture(renderer, text, null, &textRect);
}
Sdl.Render.RenderPresent(renderer);
}
static SdlTexture RenderText(SdlRenderer renderer, TtfFont font, string message)
{
var surface = SdlTtf.RenderTextBlended(
font,
message,
0,
new SdlColor
{
r = 255,
g = 255,
b = 255,
a = 255,
}
);
var texture = Sdl.Render.CreateTextureFromSurface(renderer, surface);
Sdl.PInvoke.DestroySurface(surface);
return texture;
}
}

View file

@ -1,241 +0,0 @@
/*
* DemoTexturedQuad
*
* Generates a checkerboard with four mip levels, each tinted a different colour, saves it as a
* KTX2 file, loads it back with TextureLoader and draws it on a floor quad with OpenGL. The tints
* show where the GPU switches mip level as the floor recedes. Press Escape to close it.
*/
#:property AllowUnsafeBlocks=true
#:package Ahwoo.Brutal.Glfw@2026.10.5
#:package Ahwoo.Brutal.Ktx@2026.10.2
#:package Ahwoo.Brutal.OpenGl@2026.10.2
#:package Ahwoo.Brutal.Texture@2026.10.3
#:package Ahwoo.Brutal.Core@2026.10.4
#:package Ahwoo.Brutal.Numerics@2026.10.2
using System.Runtime.InteropServices;
using Brutal;
using Brutal.GlfwApi;
using Brutal.KtxApi;
using Brutal.KtxApi.Abstractions;
using Brutal.Numerics;
using Brutal.OpenGlApi;
using Brutal.TextureApi;
using Brutal.TextureApi.Ktx;
const int SIZE = 256;
const int LEVELS = 4;
// GLFW is the only library-wide state, set up here and terminated even if Run throws.
if (!Glfw.Init())
{
var errorCode = Glfw.GetError(out var errorMessage);
throw new InvalidOperationException($"Failed to initialize GLFW: {errorCode}, {errorMessage}");
}
try
{
Run();
}
finally
{
Glfw.Terminate();
}
// Everything else: its using declarations dispose in reverse, the program and shaders, then the window.
static void Run()
{
// Texture: a KTX2 texture with room for every mip level, as in Hello/HelloKtx.cs.
var createInfo = new KtxTextureCreateInfo
{
VkFormat = (uint)VkFormat.R8G8B8A8Unorm,
BaseWidth = SIZE,
BaseHeight = SIZE,
BaseDepth = 1,
NumDimensions = 2,
NumLevels = LEVELS,
NumLayers = 1,
NumFaces = 1,
};
var createResult = KtxTexture2.Create(
ref createInfo,
KtxTextureCreateStorageEnum.TextureCreateAllocStorage,
out var ktxTexture
);
if (createResult != KtxErrorCode.Success)
throw new KtxTextureException($"Failed to create KTX2 texture: {createResult}", createResult);
// Only needed until it's written, so it's disposed at the end of this block.
var path = Path.Combine(Path.GetTempPath(), "DemoTexturedQuad.ktx2");
using (ktxTexture)
{
// Each level halves in size; the checker squares shrink with it so they line up across levels.
byte4[] tints = [new(255, 255, 255, 255), new(255, 96, 96, 255), new(96, 255, 96, 255), new(96, 96, 255, 255)];
for (var level = 0; level < LEVELS; level++)
{
var size = SIZE >> level;
var square = 32 >> level;
var texels = new byte4[size * size];
for (var y = 0; y < size; y++)
for (var x = 0; x < size; x++)
texels[y * size + x] = (x / square + y / square) % 2 == 0 ? tints[level] : new byte4(40, 40, 40, 255);
ktxTexture.SetImageFromMemory((uint)level, 0, 0, MemoryMarshal.AsBytes(texels.AsSpan()));
}
ktxTexture.WriteToNamedFile(path);
}
Console.WriteLine($"Wrote {path} ({new FileInfo(path).Length} bytes)");
// TextureLoader picks the KTX backend from the file extension, as in Hello/HelloTexture.cs.
var texture = TextureLoader.LoadFromFile(path);
Console.WriteLine($"Loaded {texture.Format}, {texture.Extent.X}x{texture.Extent.Y}, {texture.LevelCount} levels");
// Window and OpenGL, as in Hello/HelloOpenGl.cs.
Glfw.WindowHint(GlfwWindowHint.ContextVersionMajor, 4);
Glfw.WindowHint(GlfwWindowHint.ContextVersionMinor, 1);
Glfw.WindowHint(GlfwWindowHint.OpenGlProfile, Glfw.Constants.GLFW_OPENGL_CORE_PROFILE);
if (Platform.IsMacOS)
Glfw.WindowHint(GlfwWindowHint.OpenGlForwardCompat, 1);
// A fixed size keeps the viewport and aspect ratio valid.
Glfw.WindowHint(GlfwWindowHint.Resizable, Glfw.Constants.GLFW_FALSE);
using var window = Glfw.CreateWindow(
new GlfwWindow.CreateInfo { Title = "Demo Textured Quad", Size = new int2(640, 480) }
);
window.MakeContextCurrent();
Glfw.SwapInterval(1);
unsafe
{
if (!Glad.Initialize(Glfw.PInvoke.GetProcAddress))
throw new InvalidOperationException("Failed to initialize OpenGL");
}
window.OnKey += (handle, key, _, _, _) =>
{
if (key == GlfwKey.Escape)
handle.ShouldClose = true;
};
// Upload every level we loaded instead of letting OpenGL generate its own mips.
GlTexture[] glTextures = [default];
OpenGl.GenTextures(glTextures);
// OpenGL textures, vertex arrays and buffers aren't disposable, so they're deleted at the end,
// while the window's context still exists.
OpenGl.BindTexture(OpenGl.GL_TEXTURE_2D, glTextures[0].Id);
for (var level = 0; level < texture.LevelCount; level++)
{
var size = texture.Extent.X >> level;
unsafe
{
fixed (byte* data = texture.ImageData(level, 0, 0))
OpenGl.TexImage2D(
OpenGl.GL_TEXTURE_2D,
level,
(int)OpenGl.GL_RGBA8,
size,
size,
0,
OpenGl.GL_RGBA,
OpenGl.GL_UNSIGNED_BYTE,
data
);
}
}
TextureLoader.Unload(texture);
// TexParameterFloat with an int calls glTexParameteri; the name is a binding quirk (brutal.opengl#14).
OpenGl.TexParameterFloat(OpenGl.GL_TEXTURE_2D, OpenGl.GL_TEXTURE_MAX_LEVEL, LEVELS - 1);
OpenGl.TexParameterFloat(OpenGl.GL_TEXTURE_2D, OpenGl.GL_TEXTURE_MIN_FILTER, (int)OpenGl.GL_LINEAR_MIPMAP_LINEAR);
OpenGl.TexParameterFloat(OpenGl.GL_TEXTURE_2D, OpenGl.GL_TEXTURE_MAG_FILTER, (int)OpenGl.GL_LINEAR);
using var vertexShader = OpenGl
.CreateShader(GlShaderType.Vertex)
.SetSource(
"""
#version 410 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec2 aUv;
uniform mat4 viewProjection;
out vec2 uv;
void main()
{
uv = aUv;
gl_Position = viewProjection * vec4(aPos, 1.0);
}
"""u8
)
.Compile();
using var fragmentShader = OpenGl
.CreateShader(GlShaderType.Fragment)
.SetSource(
"""
#version 410 core
in vec2 uv;
uniform sampler2D tex;
out vec4 FragColor;
void main()
{
FragColor = texture(tex, uv);
}
"""u8
)
.Compile();
using var program = OpenGl.CreateProgram().Attach(vertexShader, fragmentShader).Link();
// A floor quad (two triangles) on y = 0 that repeats the texture eight times along its length.
var vertexArray = OpenGl.GenVertexArray().Bind();
var vertexBuffer = OpenGl.GenBuffer();
vertexBuffer.Bind(GlBindTarget.ArrayBuffer);
OpenGl.BufferData(
GlBindTarget.ArrayBuffer,
new Vertex[]
{
new(new float3(-2, 0, 2), new float2(0, 0)),
new(new float3(2, 0, 2), new float2(2, 0)),
new(new float3(2, 0, -14), new float2(2, 8)),
new(new float3(-2, 0, 2), new float2(0, 0)),
new(new float3(2, 0, -14), new float2(2, 8)),
new(new float3(-2, 0, -14), new float2(0, 8)),
},
GlBufferUsage.StaticDraw
);
OpenGl.VertexAttribute(new GlAttribute(0, 3, OpenGl.GL_FLOAT, GlScaling.Float, 5 * sizeof(float), 0));
OpenGl.VertexAttribute(
new GlAttribute(1, 2, OpenGl.GL_FLOAT, GlScaling.Float, 5 * sizeof(float), 3 * sizeof(float))
);
OpenGl.EnableVertexAttribArray(0);
OpenGl.EnableVertexAttribArray(1);
OpenGl.ClearColor(float4.Rgb(0.2f, 0.3f, 0.3f));
var view = float4x4.CreateLookAt(new float3(0, 1, 3), new float3(0, 0, -4), float3.UnitY);
var projection = float4x4.CreatePerspectiveFieldOfView(float.DegreesToRadians(60), 640f / 480f, 0.1f, 100f);
while (!window.ShouldClose)
{
Glfw.PollEvents();
OpenGl.Clear(GlClearBit.Color);
program.Use();
program.Uniform("viewProjection"u8, view * projection);
vertexArray.Bind();
OpenGl.Draw(GlTopology.Triangles, 6, 1, 0, 0);
window.SwapBuffers();
}
OpenGl.DeleteVertexArrays([vertexArray]);
OpenGl.DeleteBuffers([vertexBuffer]);
OpenGl.DeleteTextures(glTextures);
}
record struct Vertex(float3 Position, float2 Uv);

View file

@ -1,485 +0,0 @@
/*
* DemoVulkan
*
* Draws a coloured triangle with Vulkan: raw bindings, the Vulkan.Abstractions helpers, and a
* vertex buffer allocated with VMA. Shaders are compiled at startup with ShaderC.
*
* Press Escape to close it.
*/
#:property AllowUnsafeBlocks=true
#:package Ahwoo.Brutal.Vulkan@2026.10.3
#:package Ahwoo.Brutal.Vulkan.Abstractions@2026.10.3
#:package Ahwoo.Brutal.Vulkan.Vma@2026.10.3
#:package Ahwoo.Brutal.Glfw@2026.10.5
#:package Ahwoo.Brutal.ShaderC@2026.10.3
#:package Ahwoo.Brutal.Core@2026.10.4
#:package Ahwoo.Brutal.Memory@2026.10.2
#:package Ahwoo.Brutal.Numerics@2026.10.2
#:package Ahwoo.Brutal.Strings@2026.10.2
using Brutal;
using Brutal.GlfwApi;
using Brutal.Numerics;
using Brutal.ShaderCApi;
using Brutal.Strings;
using Brutal.VulkanApi;
using Brutal.VulkanApi.Abstractions;
using Brutal.VulkanApi.Vma;
if (!Glfw.Init())
{
var errorCode = Glfw.GetError(out var errorMessage);
throw new InvalidOperationException($"Failed to initialize GLFW: {errorCode}, {errorMessage}");
}
// GLFW can't find Brutal's Vulkan loader (libVulkanEx, not libvulkan.1) by itself, so touching Vulkan first loads it.
_ = Vulkan.GetInstanceProcAddr;
try
{
Run();
}
finally
{
Glfw.Terminate();
}
static unsafe void Run()
{
Glfw.WindowHint(GlfwWindowHint.ClientApi, Glfw.Constants.GLFW_NO_API);
Glfw.WindowHint(GlfwWindowHint.Resizable, Glfw.Constants.GLFW_FALSE); // A fixed size means no swapchain rebuilds.
// Declared first so it's disposed last, after the surface and everything else that draws to it.
using var window = Glfw.CreateWindow(
new GlfwWindow.CreateInfo { Title = "Demo Vulkan", Size = new int2(640, 480) }
);
window.OnKey += (handle, key, _, _, _) =>
{
if (key == GlfwKey.Escape)
handle.ShouldClose = true;
};
// VulkanHelpers adds whatever this OS needs (e.g. portability enumeration for MoltenVK).
var instanceExtensions = new HashSet<string>();
VulkanHelpers.AddPlatformRequiredExtensions(instanceExtensions);
var glfwExtensions = Glfw.GetRequiredInstanceExtensions(out var glfwExtensionCount);
for (var i = 0; i < glfwExtensionCount; i++)
instanceExtensions.Add(Utf8.GetString(glfwExtensions[i]));
using var instance = Vulkan.CreateInstance(
new Instance.CreateInfo
{
// For dynamic rendering.
AppInfo = new VkApplicationInfo { ApiVersion = (int)VulkanHelpers.Api.VERSION_1_3 },
Flags = VulkanHelpers.GetPlatformRequiredInstanceCreateFlags(),
EnabledExtensions = instanceExtensions,
EnabledLayers = [],
}
);
if (Glfw.CreateWindowSurface(instance.VkHandle, window, out var surfaceHandle) != (int)VkResult.Success)
throw new InvalidOperationException("Failed to create a Vulkan surface for the window");
var surface = new VkSurfaceKHR((nint)surfaceHandle);
// One queue draws and presents, so find a device with a queue family that can do both.
PhysicalDevice? physicalDevice = null;
var queueFamily = -1;
foreach (var candidate in instance.PhysicalDevices)
{
var families = new VkQueueFamilyProperties[candidate.GetQueueFamilyProperties_Count()];
candidate.GetQueueFamilyProperties_Write(families);
for (var i = 0; i < families.Length && physicalDevice is null; i++)
{
if ((families[i].QueueFlags & VkQueueFlags.GraphicsBit) != 0 && candidate.GetSurfaceSupportKHR(i, surface))
(physicalDevice, queueFamily) = (candidate, i);
}
}
if (physicalDevice is null)
throw new InvalidOperationException(
"No Vulkan device has a queue family that can draw and present to the window"
);
var deviceExtensions = new HashSet<string>();
VulkanHelpers.AddSwapchainExtensions(deviceExtensions);
VulkanHelpers.AddMandatoryIfSupportedDeviceExtensions(deviceExtensions, physicalDevice);
var priority = 1.0f;
var vulkan13Features = new VkPhysicalDeviceVulkan13Features { DynamicRendering = true };
using var device = physicalDevice.CreateDevice(
new DeviceEx.CreateInfo
{
Extensions = deviceExtensions,
QueueCreateInfos =
[
new VkDeviceQueueCreateInfo
{
QueueFamilyIndex = queueFamily,
QueueCount = 1,
QueuePriorities = &priority,
},
],
Next = &vulkan13Features,
}
);
var queue = device.GetQueue(queueFamily, 0);
// VMA: allocate a host-visible, persistently mapped vertex buffer and write the triangle into it.
var allocator = device.CreateVmaAllocator(
new VmaAllocatorCreateInfo
{
Instance = instance,
PhysicalDevice = physicalDevice,
Device = device,
VulkanApiVersion = (uint)VulkanHelpers.Api.VERSION_1_3,
}
);
ReadOnlySpan<Vertex> vertices =
[
new(new float2(0.0f, -0.5f), new float3(1.0f, 0.0f, 0.0f)),
new(new float2(0.5f, 0.5f), new float3(0.0f, 1.0f, 0.0f)),
new(new float2(-0.5f, 0.5f), new float3(0.0f, 0.0f, 1.0f)),
];
var verticesSize = ByteSize.Of(vertices);
allocator.CreateBuffer(
new VkBufferCreateInfo { Size = verticesSize, Usage = VkBufferUsageFlags.VertexBufferBit },
new VmaAllocationCreateInfo
{
Usage = VmaMemoryUsage.Auto,
Flags = VmaAllocationCreateFlags.HostAccessSequentialWriteBit | VmaAllocationCreateFlags.MappedBit,
},
out var vertexBuffer,
out var vertexAllocation,
out var vertexAllocationInfo
);
vertices.CopyTo(new Span<Vertex>((void*)vertexAllocationInfo.PMappedData, vertices.Length));
allocator.FlushAllocation(vertexAllocation, ByteSize.Zero, verticesSize); // A no-op on host-coherent memory.
// Swapchain: one image view per swapchain image.
var capabilities = physicalDevice.GetSurfaceCapabilitiesKHR(surface);
// CurrentExtent is 0xFFFFFFFF (-1 as an int) when the surface lets the swapchain pick its size.
var extent = capabilities.CurrentExtent;
if (extent.Width == -1 && extent.Height == -1)
extent = new VkExtent2D(
Math.Clamp(window.FramebufferSize.X, capabilities.MinImageExtent.Width, capabilities.MaxImageExtent.Width),
Math.Clamp(window.FramebufferSize.Y, capabilities.MinImageExtent.Height, capabilities.MaxImageExtent.Height)
);
// Ask for double buffering, within the surface's limits (a MaxImageCount of 0 means no limit).
var imageCount = Math.Max(capabilities.MinImageCount, 2);
if (capabilities.MaxImageCount > 0)
imageCount = Math.Min(imageCount, capabilities.MaxImageCount);
// Opaque if the surface supports it, otherwise the first mode it does support.
VkCompositeAlphaFlagsKHR[] alphaModes =
[
VkCompositeAlphaFlagsKHR.OpaqueBitKHR,
VkCompositeAlphaFlagsKHR.PreMultipliedBitKHR,
VkCompositeAlphaFlagsKHR.PostMultipliedBitKHR,
VkCompositeAlphaFlagsKHR.InheritBitKHR,
];
var compositeAlpha = alphaModes.First(mode => (capabilities.SupportedCompositeAlpha & mode) != 0);
Span<VkSurfaceFormatKHR> surfaceFormats =
stackalloc VkSurfaceFormatKHR[physicalDevice.GetSurfaceFormatsKHR_Count(surface)];
physicalDevice.GetSurfaceFormatsKHR_Write(surface, surfaceFormats);
var format = surfaceFormats[0].Format;
var swapchain = device.CreateSwapchainKHR(
new VkSwapchainCreateInfoKHR
{
Surface = surface,
MinImageCount = imageCount,
ImageFormat = format,
ImageColorSpace = surfaceFormats[0].ColorSpace,
ImageExtent = extent,
ImageArrayLayers = 1,
ImageUsage = VkImageUsageFlags.ColorAttachmentBit,
ImageSharingMode = VkSharingMode.Exclusive,
PreTransform = capabilities.CurrentTransform,
CompositeAlpha = compositeAlpha,
PresentMode = VkPresentModeKHR.FifoKHR,
Clipped = true,
},
null
);
var images = new VkImage[device.GetSwapchainImagesKHR_Count(swapchain)];
device.GetSwapchainImagesKHR_Write(swapchain, images);
var colorRange = new VkImageSubresourceRange
{
AspectMask = VkImageAspectFlags.ColorBit,
LevelCount = 1,
LayerCount = 1,
};
var imageViews = new VkImageView[images.Length];
for (var i = 0; i < images.Length; i++)
imageViews[i] = device.CreateImageView(
new VkImageViewCreateInfo
{
Image = images[i],
ViewType = VkImageViewType._2D,
Format = format,
SubresourceRange = colorRange,
},
null
);
// Shaders: positions and colours come from the vertex buffer.
using var compiler = ShaderC.CreateCompiler();
using var options = ShaderC.CreateCompilerOptions();
VkShaderModule CompileShader(ReadOnlySpan<byte> glsl, ShaderKind kind)
{
using var spirv = compiler.Compile(glsl, kind, "shader"u8, "main"u8, options);
return ShaderModuleExtensions.FromSpirv(
device,
new ReadOnlySpan<byte>(spirv.GetBytes(), (int)spirv.GetLength()),
null
);
}
// ShaderStages owns the modules and destroys them on Dispose.
using var shaderStages = new ShaderStages(
device,
[
Presets.ShaderStage.Vertex(
CompileShader(
"""
#version 450
layout(location = 0) in vec2 position;
layout(location = 1) in vec3 inColor;
layout(location = 0) out vec3 color;
void main()
{
gl_Position = vec4(position, 0.0, 1.0);
color = inColor;
}
"""u8,
ShaderKind.VertexShader
)
),
Presets.ShaderStage.Fragment(
CompileShader(
"""
#version 450
layout(location = 0) in vec3 color;
layout(location = 0) out vec4 outColor;
void main()
{
outColor = vec4(color, 1.0);
}
"""u8,
ShaderKind.FragmentShader
)
),
],
null
);
// Pipeline: Presets cover the common fixed-function state.
// VertexInput builds the binding and attributes from the Vertex struct's fields.
var vertexInput = new VertexInput(1, 2).AddBindingWithAttributes<Vertex>(0, 0, VkVertexInputRate.Vertex);
var viewport = new VkViewport
{
Width = extent.Width,
Height = extent.Height,
MaxDepth = 1,
};
var scissor = new VkRect2D(extent);
var viewportState = new VkPipelineViewportStateCreateInfo
{
ViewportCount = 1,
Viewports = &viewport,
ScissorCount = 1,
Scissors = &scissor,
};
var rendering = new VkPipelineRenderingCreateInfo { ColorAttachmentCount = 1, ColorAttachmentFormats = &format };
var pipelineLayout = device.CreatePipelineLayout([], [], null);
var pipeline = device.CreateGraphicsPipeline(
VkPipelineCache.NullHandle,
new VkGraphicsPipelineCreateInfo
{
Next = &rendering,
StageCount = shaderStages.Count,
Stages = shaderStages,
VertexInputState = vertexInput,
InputAssemblyState = Presets.InputAssembly.TriangleList,
ViewportState = &viewportState,
RasterizationState = Presets.Rasterization.Fill.CullNone,
MultisampleState = Presets.Multisample.None,
ColorBlendState = Presets.BlendState.BlendNone,
Layout = pipelineLayout,
},
null
);
// Commands and synchronisation: one frame in flight.
var commandPool = device.CreateCommandPool(
new VkCommandPoolCreateInfo
{
QueueFamilyIndex = queueFamily,
Flags = VkCommandPoolCreateFlags.ResetCommandBufferBit,
},
null
);
var commandBuffer = device.AllocateCommandBuffer(
new VkCommandBufferAllocateInfo { CommandPool = commandPool, Level = VkCommandBufferLevel.Primary }
);
var imageAvailable = device.CreateSemaphore(new VkSemaphoreCreateInfo(), null);
var renderFinished = images.Select(_ => device.CreateSemaphore(new VkSemaphoreCreateInfo(), null)).ToArray();
var frameFence = device.CreateFence(VkFenceCreateFlags.SignaledBit, null);
void TransitionImage(
VkImage image,
VkImageLayout from,
VkImageLayout to,
VkPipelineStageFlags srcStage,
VkPipelineStageFlags dstStage,
VkAccessFlags srcAccess,
VkAccessFlags dstAccess
)
{
commandBuffer.PipelineBarrier(
srcStage,
dstStage,
VkDependencyFlags.None,
[],
[],
[
new VkImageMemoryBarrier
{
SrcAccessMask = srcAccess,
DstAccessMask = dstAccess,
OldLayout = from,
NewLayout = to,
SrcQueueFamilyIndex = VK.QUEUE_FAMILY_IGNORED,
DstQueueFamilyIndex = VK.QUEUE_FAMILY_IGNORED,
Image = image,
SubresourceRange = colorRange,
},
]
);
}
while (!window.ShouldClose)
{
Glfw.PollEvents();
device.WaitForFence(frameFence, -1);
device.ResetFences([frameFence]);
// The window can't be resized, so the swapchain is never rebuilt: ErrorOutOfDateKHR throws here and a
// SuboptimalKHR result is ignored. A resizable window would recreate the swapchain in both cases.
device.AcquireNextImageKHR(swapchain, -1, imageAvailable, VkFence.NullHandle, out var imageIndex);
var image = images[imageIndex];
commandBuffer.Reset();
commandBuffer.Begin(VkCommandBufferUsageFlags.OneTimeSubmitBit);
TransitionImage(
image,
VkImageLayout.Undefined,
VkImageLayout.ColorAttachmentOptimal,
VkPipelineStageFlags.ColorAttachmentOutputBit,
VkPipelineStageFlags.ColorAttachmentOutputBit,
VkAccessFlags.None,
VkAccessFlags.ColorAttachmentWriteBit
);
var colorAttachment = new VkRenderingAttachmentInfo
{
ImageView = imageViews[imageIndex],
ImageLayout = VkImageLayout.ColorAttachmentOptimal,
LoadOp = VkAttachmentLoadOp.Clear,
StoreOp = VkAttachmentStoreOp.Store,
ClearValue = new VkClearColorValue { Float32 = new float4(0.1f, 0.1f, 0.1f, 1.0f) },
};
commandBuffer.BeginRendering(
new VkRenderingInfo
{
RenderArea = new VkRect2D(extent),
LayerCount = 1,
ColorAttachmentCount = 1,
ColorAttachments = &colorAttachment,
}
);
commandBuffer.BindPipeline(VkPipelineBindPoint.Graphics, pipeline);
commandBuffer.BindVertexBuffers(0, [vertexBuffer], [new ByteSize64(0)]);
commandBuffer.Draw(3, 1, 0, 0);
commandBuffer.EndRendering();
TransitionImage(
image,
VkImageLayout.ColorAttachmentOptimal,
VkImageLayout.PresentSrcKHR,
VkPipelineStageFlags.ColorAttachmentOutputBit,
VkPipelineStageFlags.BottomOfPipeBit,
VkAccessFlags.ColorAttachmentWriteBit,
VkAccessFlags.None
);
commandBuffer.End();
var signalSemaphore = renderFinished[imageIndex];
queue.Submit(
[imageAvailable],
[VkPipelineStageFlags.ColorAttachmentOutputBit],
[commandBuffer],
[signalSemaphore],
frameFence
);
queue.PresentKHR(
new VkPresentInfoKHR
{
WaitSemaphoreCount = 1,
WaitSemaphores = &signalSemaphore,
SwapchainCount = 1,
Swapchains = &swapchain,
ImageIndices = &imageIndex,
}
);
}
// The handles above aren't IDisposable, so they're destroyed here once the GPU is idle, before the
// using declarations dispose the shader stages, device, instance and window.
device.WaitIdle();
allocator.DestroyBuffer(vertexBuffer, vertexAllocation);
device.DestroyVmaAllocator(allocator);
device.DestroyFence(frameFence, null);
device.DestroySemaphore(imageAvailable, null);
foreach (var semaphore in renderFinished)
device.DestroySemaphore(semaphore, null);
device.DestroyCommandPool(commandPool, null);
device.DestroyPipeline(pipeline, null);
device.DestroyPipelineLayout(pipelineLayout, null);
foreach (var imageView in imageViews)
device.DestroyImageView(imageView, null);
device.DestroySwapchainKHR(swapchain, null);
instance.DestroySurfaceKHR(surface, null);
}
struct Vertex(float2 position, float3 color)
{
public float2 Position = position;
public float3 Color = color;
}

View file

@ -1,45 +0,0 @@
/*
* HelloBox2D
*
* Drops a box onto the ground with Box2D and prints where it is as it falls and comes to rest.
* See Demo/DemoBox2D.cs for a version that draws a stack of boxes with OpenGL.
*/
#:package Ahwoo.Brutal.Box2D@2026.10.2
#:package Ahwoo.Brutal.Core@2026.10.4
#:package Ahwoo.Brutal.Numerics@2026.10.2
using Brutal.Box2DApi;
using Brutal.Numerics;
Run();
static void Run()
{
// Default gravity is (0, -10). Disposing the world also destroys its bodies and shapes.
using var world = Box2D.CreateWorld(B2WorldDef.Default);
// A static ground whose top surface is at y = 0.
var ground = world.CreateBody(new B2BodyDef { Position = new float2(0, -0.5f) });
ground.CreatePolygonShape(B2ShapeDef.Default, Box2D.MakeBox(5, 0.5f));
// A 1x1 dynamic box, 4 units above the ground.
var box = world.CreateBody(new B2BodyDef { Type = B2BodyType.Dynamic, Position = new float2(0, 4) });
box.CreatePolygonShape(B2ShapeDef.Default, Box2D.MakeBox(0.5f, 0.5f));
// Two seconds at 60 Hz; the box should land and settle with its centre at y = 0.5.
const float TIME_STEP = 1.0f / 60.0f;
for (var step = 0; step <= 120; step++)
{
if (step > 0)
world.Step(TIME_STEP, 4);
if (step % 20 == 0)
{
var position = box.GetPosition();
Console.WriteLine(
$"t = {step * TIME_STEP:F2}s position = ({position.X:F2}, {position.Y:F2}) awake = {box.IsAwake()}"
);
}
}
}

View file

@ -1,35 +0,0 @@
/*
* HelloCollections
*
* Uses NativeList<T>, a growable list backed by unmanaged memory: add, insert,
* remove, iterate and edit it as a span.
*/
#:package Ahwoo.Brutal.Collections@2026.10.2
#:package Ahwoo.Brutal.Core@2026.10.4
// RIAN: This package will be greatly improved in an upcoming release of custom allocators, and collections that use them.
using Brutal.Collections;
Run();
static void Run()
{
// A List<T>-like collection backed by unmanaged memory, freed when Run returns.
using var list = new NativeList<int>();
list.Add(1);
list.AddRange([2, 3, 4, 5]);
list.Insert(0, 0);
list.RemoveAt(3);
Console.WriteLine($"Count = {(int)list.Count}, Capacity = {(int)list.Capacity}");
foreach (var value in list)
Console.WriteLine(value);
var span = list.AsSpan();
span.Reverse();
Console.WriteLine($"Reversed in place: {string.Join(", ", span.ToArray())}");
}

View file

@ -1,27 +0,0 @@
/*
* HelloConcurrency
*
* Runs a few jobs across worker threads with the JobScheduler and waits for them to finish.
*/
#:package Ahwoo.Brutal.Concurrency@2026.10.2
// RIAN: This job system is finely-tuned for the way RW projects like to implement concurrency, and has limitations we should document at some stage.
using Brutal.Concurrency.Jobs;
var scheduler = new JobScheduler(3, "HelloScheduler");
// The second argument is an estimated cost, used to balance jobs across worker threads.
for (var i = 1; i <= 6; i++)
scheduler.Queue(new HelloJob(i), 10);
scheduler.ExecuteJobs();
scheduler.Wait();
Console.WriteLine("All jobs finished");
class HelloJob(int id) : IJob
{
public void Run() => Console.WriteLine($"Job {id} running on thread {Environment.CurrentManagedThreadId}");
}

View file

@ -1,29 +0,0 @@
/*
* HelloCore
*
* Shows a few Brutal.Core basics: platform detection, ByteSize/ElementCount arithmetic and Ptr<T>.
*/
#:property AllowUnsafeBlocks=true
#:package Ahwoo.Brutal.Core@2026.10.4
// RIAN: This package mainly contains the absolute bare minimum types and methods we use often across our packages.
using Brutal;
using Brutal.Pointers;
Console.WriteLine($"Running on {Platform.CurrentFamily}");
var stride = ByteSize.Of<float>();
var total = stride * new ElementCount(1024);
Console.WriteLine($"1024 floats = {total}");
var alternative = ByteSize.Of<float>(1024);
Console.WriteLine($"1024 floats = {alternative}");
unsafe
{
var raw = stackalloc int[4] { 10, 20, 30, 40 };
Ptr<int> p = raw;
Console.WriteLine($"p.Value = {p.Value}, p[2] = {p[2]}, p.Offset(1).Value = {p.Offset(1).Value}");
}

View file

@ -1,53 +0,0 @@
/*
* HelloFmod
*
* Starts FMOD, prints its version and plays a 440 Hz tone from FMOD's built-in oscillator.
*
* FMOD natives are not bundled: put your licensed FMOD 2.03 Core library (fmod.dll, libfmod.so
* or libfmod.dylib) on the library search path (PATH on Windows, LD_LIBRARY_PATH on Linux,
* DYLD_LIBRARY_PATH on macOS), or this throws DllNotFoundException.
*/
#:package Ahwoo.Brutal.Fmod@2026.10.4
#:package Ahwoo.Brutal.Core@2026.10.4
// RIAN: It needs to be stressed that we do not provide FMOD binaries, and you must obtain them from the official FMOD website.
using Brutal.FmodApi;
// The FMOD system owns everything else; closing and releasing it frees anything left behind.
var system = Fmod.SystemCreate(Fmod.VERSION);
system.Init(32, InitFlags.Normal, 0);
try
{
Run(system);
}
finally
{
system.Close();
system.Release();
}
static void Run(FmodSystem system)
{
system.GetVersion(out var version, out _);
Console.WriteLine($"FMOD version: {version >> 16:x}.{(version >> 8) & 0xff:x2}.{version & 0xff:x2}");
var dsp = system.CreateDspByType(DspType.Oscillator); // Generates a sine wave by default.
dsp.SetParameterFloat((int)DspOscillator.Rate, 440.0f);
var channel = system.PlayDsp(dsp, default, false);
channel.SetVolume(0.5f);
Console.WriteLine("Playing a 440 Hz tone...");
for (var i = 0; i < 100; i++)
{
system.Update();
Thread.Sleep(10);
}
// Channels and DSPs aren't IDisposable, so stop and release them by hand.
channel.Stop();
dsp.Release();
}

View file

@ -1,49 +0,0 @@
/*
* HelloGlfw
*
* Opens an empty GLFW window with no graphics API. Press Escape to close it.
*/
#:package Ahwoo.Brutal.Glfw@2026.10.5
#:package Ahwoo.Brutal.Numerics@2026.10.2
using Brutal.GlfwApi;
using Brutal.Numerics;
if (!Glfw.Init())
{
var errorCode = Glfw.GetError(out var errorMessage);
throw new InvalidOperationException($"Failed to initialize GLFW: {errorCode}, {errorMessage}");
}
try
{
Run();
}
finally
{
Glfw.Terminate();
}
static void Run()
{
// Destroyed when Run returns, before GLFW is terminated.
using var window = Glfw.CreateWindow(
new GlfwWindow.CreateInfo
{
Title = "Hello Glfw",
Size = new int2(640, 480),
Monitor = GlfwMonitor.Null, // Windowed mode.
Share = null, // No shared context.
}
);
window.OnKey += (handle, key, _, _, _) =>
{
if (key == GlfwKey.Escape)
handle.ShouldClose = true;
};
while (!window.ShouldClose)
Glfw.PollEvents();
}

View file

@ -1,49 +0,0 @@
/*
* HelloGli
*
* Creates a texture with a full mip chain using GLI, saves it as a .dds and loads it back.
*/
#:property AllowUnsafeBlocks=true
#:package Ahwoo.Brutal.Gli@2026.10.2
#:package Ahwoo.Brutal.Numerics@2026.10.2
// RIAN: This package may be deprecated in the future, as the extensions it supports may be covered by better packages.
using Brutal.GliApi;
using Brutal.Numerics;
Run();
static void Run()
{
var extent = new int3(64, 64, 1);
// A 2D RGBA texture with a full mip chain (64x64 down to 1x1).
using var texture = new Gli.Texture(
Gli.Target._2D,
Gli.Format.RGBA8_UNorm_Pack8,
extent,
1,
1,
7,
Gli.Swizzles.Identity
);
unsafe
{
// Only the top mip level is filled; the smaller levels are left empty.
new Span<byte4>(texture.ImageData(0), extent.X * extent.Y).Fill(new byte4(255, 128, 0, 255));
}
var path = Path.Combine(Path.GetTempPath(), "HelloGli.dds");
texture.Save(path);
Console.WriteLine($"Wrote {path}");
using var loaded = new Gli.Texture(path);
Console.WriteLine($"Loaded {loaded.Target} {loaded.Format}, {loaded.Levels} levels, {loaded.Size} bytes");
for (var level = 0; level < loaded.Levels; level++)
Console.WriteLine(
$" Level {level}: {loaded.ImageExtent(level).X}x{loaded.ImageExtent(level).Y}, {loaded.ImageSize(level)} bytes"
);
}

View file

@ -1,50 +0,0 @@
/*
* HelloGltf
*
* Parses a tiny inline glTF (one triangle), reads its vertex positions and saves it back out.
*/
// Brutal.Gltf uses reflection-based System.Text.Json, which Native AOT (the default for
// file-based apps) disables.
#:property PublishAot=false
#:package Ahwoo.Brutal.Gltf@2026.10.3
using System.Runtime.InteropServices;
using Brutal.GltfApi;
// A single triangle, with its vertex positions embedded as a base64 buffer.
float[] positions = [0, 0, 0, 1, 0, 0, 0, 1, 0];
var buffer = Convert.ToBase64String(MemoryMarshal.AsBytes(positions.AsSpan()));
var json = $$"""
{
"asset": { "version": "2.0" },
"scene": 0,
"scenes": [{ "nodes": [0] }],
"nodes": [{ "name": "Triangle", "mesh": 0 }],
"meshes": [{ "primitives": [{ "attributes": { "POSITION": 0 } }] }],
"buffers": [{ "uri": "data:application/octet-stream;base64,{{buffer}}", "byteLength": 36 }],
"bufferViews": [{ "buffer": 0, "byteLength": 36 }],
"accessors": [{ "bufferView": 0, "componentType": 5126, "count": 3, "type": "VEC3", "min": [0, 0, 0], "max": [1, 1, 0] }]
}
""";
var model = GltfUtility.DeserializeModelJson(json);
Console.WriteLine(
$"glTF {model.Asset.Version}: {model.Scenes.Length} scene, {model.Nodes.Length} node, {model.Meshes.Length} mesh"
);
var node = model.Nodes[0];
var accessor = model.Accessors[model.Meshes[node.Mesh!.Value].Primitives[0].Attributes["POSITION"]];
// Reading from byte 0 works because this buffer holds only tightly packed positions; real files need the
// accessor and buffer view offsets and stride (see ReadFloat3s in Demo/DemoGltfViewer.cs). The second
// argument is the folder that relative buffer URIs are resolved against.
var vertices = MemoryMarshal.Cast<byte, float>(model.LoadBinaryBuffer(0, Path.GetTempPath()));
Console.WriteLine($"Node '{node.Name}' has {accessor.Count} vertices:");
for (var i = 0; i < accessor.Count; i++)
Console.WriteLine($" ({vertices[i * 3]}, {vertices[i * 3 + 1]}, {vertices[i * 3 + 2]})");
var path = Path.Combine(Path.GetTempPath(), "HelloGltf.gltf");
model.SaveModel(path);
Console.WriteLine($"Wrote {path}");

View file

@ -1,115 +0,0 @@
/*
* HelloImGui
*
* Dear ImGui with its GLFW and OpenGL backends: some text, a button and a slider.
* Press Escape to close it. See Demo/DemoImGui.cs for FreeType fonts and ImPlot.
*/
#:property AllowUnsafeBlocks=true
#:package Ahwoo.Brutal.ImGui@2026.10.3
#:package Ahwoo.Brutal.ImGui.Backends@2026.10.3
#:package Ahwoo.Brutal.Core@2026.10.4
#:package Ahwoo.Brutal.Glfw@2026.10.5
#:package Ahwoo.Brutal.Numerics@2026.10.2
#:package Ahwoo.Brutal.OpenGl@2026.10.2
// RIAN: Please look at this example carefully, especially how the SharedStorage is reset once per frame.
// The shared storage (leveraged for allocation-free string interpolation) will OoM eventually if you don't.
using Brutal;
using Brutal.GlfwApi;
using Brutal.ImGuiApi;
using Brutal.ImGuiApi.Backends;
using Brutal.Numerics;
using Brutal.OpenGlApi;
// GLFW and OpenGL are just the host here: a window and a GL context for ImGui to draw into.
if (!Glfw.Init())
{
var errorCode = Glfw.GetError(out var errorMessage);
throw new InvalidOperationException($"Failed to initialize GLFW: {errorCode}, {errorMessage}");
}
var context = ImGui.CreateContext();
try
{
Run();
}
finally
{
ImGui.DestroyContext(context);
Glfw.Terminate();
}
static void Run()
{
Glfw.WindowHint(GlfwWindowHint.ContextVersionMajor, 4);
Glfw.WindowHint(GlfwWindowHint.ContextVersionMinor, 1);
Glfw.WindowHint(GlfwWindowHint.OpenGlProfile, Glfw.Constants.GLFW_OPENGL_CORE_PROFILE);
if (Platform.IsMacOS)
Glfw.WindowHint(GlfwWindowHint.OpenGlForwardCompat, 1);
// Declared first so it's disposed last: the backends below need the window and its GL context.
using var window = Glfw.CreateWindow(
new GlfwWindow.CreateInfo { Title = "Hello ImGui", Size = new int2(800, 600) }
);
window.MakeContextCurrent();
Glfw.SwapInterval(1); // Wait for vsync instead of drawing as fast as possible.
unsafe
{
if (!Glad.Initialize(Glfw.PInvoke.GetProcAddress))
throw new InvalidOperationException("Failed to load OpenGL functions with GLAD");
}
window.OnKey += (handle, key, _, _, _) =>
{
if (key == GlfwKey.Escape)
handle.ShouldClose = true;
};
ImGui.GetIO().IniFilename = null; // Don't write imgui.ini.
// ImGui.Backends: feed GLFW input to ImGui and render its draw lists with OpenGL.
using var glfwBackend = new GlfwBackend(window, GlfwBackend.ClientApi.OpenGL);
using var openGlBackend = new OpenGlBackend();
var clicks = 0;
var value = 0.5f;
OpenGl.ClearColor(float4.Rgb(0.2f, 0.3f, 0.3f));
while (!window.ShouldClose)
{
Glfw.PollEvents();
glfwBackend.NewFrame();
openGlBackend.NewFrame();
ImGui.NewFrame();
// Recycle the scratch memory that interpolated ImGui strings ($"...") use, once per frame.
ImString.SharedStorage.Reset();
ImGui.SetNextWindowSize(new float2(400, 200), ImGuiCond.FirstUseEver);
if (ImGui.Begin("Hello ImGui"u8))
{
ImGui.Text("Hello from Dear ImGui!"u8);
if (ImGui.Button("Click me"u8))
clicks++;
ImGui.SameLine();
ImGui.Text($"Clicked {clicks} times");
ImGui.SliderFloat("Value"u8, ref value, 0f, 1f);
}
ImGui.End();
ImGui.Render();
OpenGl.Clear(GlClearBit.Color);
openGlBackend.RenderDrawData(ImGui.GetDrawData());
window.SwapBuffers();
}
}

View file

@ -1,85 +0,0 @@
/*
* HelloImGuiAbstractions
*
* The in-game ConsoleWindow and its TerminalInterface: registers [TerminalAction] commands, runs
* a few command lines with typed arguments, then draws the console headless.
* See Hello/HelloImGui.cs for Dear ImGui on screen.
*/
#:package Ahwoo.Brutal.ImGui.Abstractions@2026.10.3
#:package Ahwoo.Brutal.Core@2026.10.4
#:package Ahwoo.Brutal.ImGui@2026.10.3
#:package Ahwoo.Brutal.Numerics@2026.10.2
// RIAN: This sample primarly showcases the console interface that all RW projects use.
using Brutal.ImGuiApi;
using Brutal.ImGuiApi.Abstractions;
using Brutal.Numerics;
var context = ImGui.CreateContext();
try
{
Run();
}
finally
{
ImGui.DestroyContext(context);
}
static void Run()
{
var io = ImGui.GetIO();
io.IniFilename = null; // Don't write imgui.ini.
io.DisplaySize = new float2(800, 600); // No window, so tell ImGui how big the screen is.
io.DeltaTime = 1f / 60f;
// Claim a renderer that handles texture requests so ImGui builds the font atlas during the frame.
// Nothing uploads it here, which is fine for a headless frame.
io.BackendFlags |= ImGuiBackendFlags.RendererHasTextures;
// Disposed when Run returns, before the ImGui context is destroyed.
using var console = new ConsoleWindow();
console.DisableMessageFading();
// Commands are plain methods; the terminal parses arguments into their parameter types.
console.Terminal.RegisterCommand(Hello);
console.Terminal.RegisterCommand(Add);
console.Terminal.OnOutput += (message, type) => Say($"[{type}] {message}"); // Parse errors land here.
// What a player would type into the console; ';' separates commands on one line.
string[] lines = ["hello World", "add 2 3; add 40", "add two 3"];
foreach (var line in lines)
{
Console.WriteLine($"> {line}");
console.Submit(line);
}
// Draw the open console as a game would each frame; it sizes itself to its log, which takes a
// frame to measure, so draw two.
console.Show();
for (var frame = 0; frame < 2; frame++)
{
ImGui.NewFrame();
var viewport = ImGui.GetMainViewport();
console.Draw(viewport.Pos, viewport.Size, io.DeltaTime);
ImGui.Render();
}
var drawData = ImGui.GetDrawData();
Console.WriteLine($"Console drawn: {drawData.TotalVtxCount} vertices, {drawData.TotalIdxCount} indices");
// Print to the in-game console, and echo to stdout since there's no window to see it in.
void Say(string message)
{
console.Print(message);
Console.WriteLine(message);
}
[TerminalAction("hello", "Prints a greeting")]
void Hello(string name) => Say($"Hello, {name}!");
[TerminalAction("add", "Adds two integers")]
void Add(int a, int b = 2) => Say($"{a} + {b} = {a + b}");
}

View file

@ -1,114 +0,0 @@
/*
* HelloImGuiExtensions
*
* ImGuiEx widgets that bind straight to C# enums, driven headless by simulated mouse clicks.
* See Hello/HelloImGui.cs for Dear ImGui on screen.
*/
#:package Ahwoo.Brutal.ImGui.Extensions@2026.10.3
#:package Ahwoo.Brutal.Core@2026.10.4
#:package Ahwoo.Brutal.ImGui@2026.10.3
#:package Ahwoo.Brutal.Numerics@2026.10.2
// RIAN: This package contains small extras for ImGui that we like, but possibly needs a better name as it's very opinionated.
using Brutal.ImGuiApi;
using Brutal.ImGuiApi.Extensions;
using Brutal.Numerics;
var context = ImGui.CreateContext();
try
{
Run();
}
finally
{
ImGui.DestroyContext(context);
}
static void Run()
{
var io = ImGui.GetIO();
io.IniFilename = null; // Don't write imgui.ini.
io.DisplaySize = new float2(800, 600); // No window, so tell ImGui how big the screen is.
io.DeltaTime = 1f / 60f;
// Claim a renderer that handles texture requests so ImGui builds the font atlas during the frame.
// Nothing uploads it here, which is fine for a headless frame.
io.BackendFlags |= ImGuiBackendFlags.RendererHasTextures;
var shape = Shape.Circle;
var layers = Layers.Ground;
var triangleCenter = float2.Zero;
var waterCenter = float2.Zero;
Console.WriteLine($"Before: shape = {shape}, layers = {layers}");
// No backend, so feed ImGui a click on "Triangle" then on "Water". A new window takes
// a frame to settle its layout, so the clicks start on frame 2.
for (var frame = 0; frame < 7; frame++)
{
switch (frame)
{
case 2:
io.AddMousePosEvent(triangleCenter.X, triangleCenter.Y);
io.AddMouseButtonEvent(0, true);
break;
case 4:
io.AddMousePosEvent(waterCenter.X, waterCenter.Y);
io.AddMouseButtonEvent(0, true);
break;
case 3:
case 5:
io.AddMouseButtonEvent(0, false);
break;
}
ImGui.NewFrame();
ImGui.Begin("Hello ImGui Extensions"u8);
// ImGuiEx widgets take the enum by ref, no casting to and from int.
ImGuiEx.RadioButton("Circle"u8, ref shape, Shape.Circle);
ImGui.SameLine();
ImGuiEx.RadioButton("Square"u8, ref shape, Shape.Square);
ImGui.SameLine();
ImGuiEx.RadioButton("Triangle"u8, ref shape, Shape.Triangle);
triangleCenter = (ImGui.GetItemRectMin() + ImGui.GetItemRectMax()) * 0.5f;
ImGuiEx.Combo("Shape"u8, ref shape, "Circle\0Square\0Triangle\0"u8);
// Works for [Flags] enums too: each checkbox toggles one bit.
ImGuiEx.CheckboxFlags("Ground"u8, ref layers, Layers.Ground);
ImGuiEx.CheckboxFlags("Water"u8, ref layers, Layers.Water);
waterCenter = (ImGui.GetItemRectMin() + ImGui.GetItemRectMax()) * 0.5f;
ImGuiEx.CheckboxFlags("Sky"u8, ref layers, Layers.Sky);
ImGui.End();
ImGui.Render();
}
Console.WriteLine($"After: shape = {shape}, layers = {layers}");
// Plus a few non-widget helpers, e.g. colour conversion on a float4.
var red = ImGuiEx.ColorConvertHSVtoRGB(new float4(0f, 1f, 1f, 1f));
Console.WriteLine($"HSV(0, 1, 1) -> RGB({red.X}, {red.Y}, {red.Z})");
}
enum Shape
{
Circle,
Square,
Triangle,
}
[Flags]
enum Layers
{
None = 0,
Ground = 1,
Water = 2,
Sky = 4,
}

Some files were not shown because too many files have changed in this diff Show more