/*
* HelloOpenGlText
*
* Opens a GLFW window and draws a coloured triangle with OpenGL. Adds text on top of that. Press Escape to close it.
*/
#:property AllowUnsafeBlocks=true
#:package [email protected]
#:package [email protected]
#:package [email protected]
#:package [email protected]
#:package [email protected]
#:package [email protected]
// RIAN: Our OpenGL samples run on 4.1 for compatibility with macOS, but we should support up to 4.6 no problem.
using Brutal;
using Brutal.GlfwApi;
using Brutal.Numerics;
using Brutal.OpenGlApi;
using Brutal.SdlApi;
using Brutal.SdlApi.Ttf;
// copying the font setup from the HelloSdlTtf.cs
// yuck, sorry
string[] systemFonts =
[
"/System/Library/Fonts/Supplemental/Arial.ttf", // macOS
@"C:\Windows\Fonts\arial.ttf", // Windows
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", // Debian, Ubuntu
"/usr/share/fonts/TTF/DejaVuSans.ttf", // Arch
"/usr/share/fonts/dejavu-sans-fonts/DejaVuSans.ttf", // Fedora
];
var fontPath = args.Length > 0 ? args[0] : systemFonts.FirstOrDefault(File.Exists);
if (fontPath is null)
{
Console.WriteLine("No system font found. Usage: dotnet run Hello/HelloSdlTtf.cs -- path/to/font.ttf");
return;
}
if (!Glfw.Init())
{
var errorCode = Glfw.GetError(out var errorMessage);
throw new InvalidOperationException($"Failed to initialize GLFW: {errorCode}, {errorMessage}");
}
SdlTtf.Init();
try
{
Run(fontPath);
}
finally
{
SdlTtf.Quit();
Glfw.Terminate();
}
static void Run(string fontPath)
{
var screenWidth = 640;
var screenHeight = 480;
// Closed when Run returns, before Sdl.Ttf quits.
using var font = SdlTtf.OpenFont(fontPath, 32f);
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 = "Hello OpenGL", Size = new int2(screenWidth, screenHeight) }
);
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 the OpenGL functions with GLAD");
}
window.OnKey += (handle, key, _, _, _) =>
{
if (key == GlfwKey.Escape)
handle.ShouldClose = true;
};
// Declared after the window, so the program is deleted while the GL context still exists.
using var triangleProgram = LinkTriangleProgram();
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);
using var textProgram = LinkTextProgram();
var (glTextures, textWidth, textHeight) = SetupFontTexture(font, "Hello Open GL Text!");
var textVertexArray = OpenGl.GenVertexArray().Bind();
var textVertexBuffer = OpenGl.GenBuffer();
textVertexBuffer.Bind(GlBindTarget.ArrayBuffer);
var tx = 320f - (.5f * textWidth);
var tw = textWidth;
var ty = 240f - (.5f * textHeight);
var th = textHeight;
var fontColor = new float4(0, 0, 0, 1);
OpenGl.BufferData<TextVertex>(GlBindTarget.ArrayBuffer, [
new (new float2(tx, ty), new float2(0, 0), fontColor),
new (new float2(tx + tw, ty), new float2(1, 0), fontColor),
new (new float2(tx, ty + th), new float2(0, 1), fontColor),
new (new float2(tx, ty + th), new float2(0, 1), fontColor),
new (new float2(tx + tw, ty), new float2(1, 0), fontColor),
new (new float2(tx + tw, ty + th), new float2(1, 1), fontColor)
], GlBufferUsage.StaticDraw);
OpenGl.VertexAttribute(new GlAttribute(0, 2, OpenGl.GL_FLOAT, GlScaling.Float, 8 * sizeof(float), 0));
OpenGl.VertexAttribute(new GlAttribute(1, 2, OpenGl.GL_FLOAT, GlScaling.Float, 8 * sizeof(float), 2 * sizeof(float)));
OpenGl.VertexAttribute(new GlAttribute(2, 4, OpenGl.GL_FLOAT, GlScaling.Float, 8 * sizeof(float), 4 * sizeof(float)));
OpenGl.EnableVertexAttribArray(0);
OpenGl.EnableVertexAttribArray(1);
OpenGl.EnableVertexAttribArray(2);
OpenGl.Enable(GlCapability.Blend);
OpenGl.BlendFunc(OpenGl.GL_SRC_ALPHA, OpenGl.GL_ONE_MINUS_SRC_ALPHA);
OpenGl.ClearColor(float4.Rgb(0.2f, 0.3f, 0.3f));
OpenGl.Clear(GlClearBit.Color | GlClearBit.Depth);
while (!window.ShouldClose)
{
Glfw.PollEvents();
OpenGl.Clear(GlClearBit.Color | GlClearBit.Depth);
triangleProgram.Use();
vertexArray.Bind();
OpenGl.Draw(GlTopology.Triangles, 3, 1, 0, 0);
textProgram.Use();
textProgram.Uniform("uScreen"u8, new float2(screenWidth, screenHeight));
textVertexArray.Bind();
OpenGl.Draw(GlTopology.Triangles, 6, 1, 0, 0);
window.SwapBuffers();
}
// Vertex arrays and buffers aren't IDisposable, so delete them by hand while the GL context still exists.
OpenGl.DeleteVertexArrays([vertexArray, textVertexArray]);
OpenGl.DeleteBuffers([vertexBuffer, textVertexBuffer]);
OpenGl.DeleteTextures(glTextures);
}
// The shaders are only needed until the program is linked, so they are disposed on return.
static GlProgram LinkTriangleProgram()
{
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();
}
static GlProgram LinkTextProgram()
{
using var vertexShader = OpenGl
.CreateShader(GlShaderType.Vertex)
.SetSource(
"""
#version 410 core
precision mediump float;
layout (location = 0) in vec2 aPos;
layout (location = 1) in vec2 aUV;
layout (location = 2) in vec4 aColor;
uniform vec2 uScreen;
out vec2 vUV;
out vec4 vColor;
void main() {
vec2 ndc = (aPos / uScreen) * 2.0 - 1.0;
ndc.y = -ndc.y;
gl_Position = vec4(ndc, 0.0, 1.0);
vUV = aUV;
vColor = aColor;
}
"""u8
)
.Compile();
using var fragmentShader = OpenGl
.CreateShader(GlShaderType.Fragment)
.SetSource(
"""
#version 410 core
precision mediump float;
in vec2 vUV;
in vec4 vColor;
uniform sampler2D uTex;
out vec4 fragColor;
void main() {
float coverage = texture(uTex, vUV).a;
fragColor = vec4(vColor.rgb, vColor.a * coverage);
}
"""u8
)
.Compile();
return OpenGl.CreateProgram().Attach(vertexShader, fragmentShader).Link();
}
static (GlTexture[], float, float) SetupFontTexture(TtfFont font, string text)
{
GlTexture[] glTextures = [default];
OpenGl.GenTextures(glTextures);
OpenGl.BindTexture(OpenGl.GL_TEXTURE_2D, glTextures[0].Id);
OpenGl.TexParameterFloat(OpenGl.GL_TEXTURE_2D, OpenGl.GL_TEXTURE_MIN_FILTER, (int) OpenGl.GL_LINEAR);
OpenGl.TexParameterFloat(OpenGl.GL_TEXTURE_2D, OpenGl.GL_TEXTURE_MAG_FILTER, (int) OpenGl.GL_LINEAR);
var width = 0;
var height = 0;
unsafe {
var surface = SdlTtf.RenderTextBlended(font, text, 0,
new SdlColor { r = 255, g = 255, b = 255, a = 255 }
);
var converted = Sdl.PInvoke.ConvertSurface(surface, SdlPixelFormat.Rgba32);
width = converted->w;
height = converted->h;
OpenGl.TexImage2D(OpenGl.GL_TEXTURE_2D, 0, (int) OpenGl.GL_RGBA,
width, height, 0, OpenGl.GL_RGBA, OpenGl.GL_UNSIGNED_BYTE, converted->pixels);
Sdl.PInvoke.DestroySurface(surface);
Sdl.PInvoke.DestroySurface(converted);
}
return (glTextures, width, height);
}
record struct Vertex(float2 Position, float3 Color);
record struct TextVertex(float2 Position, float2 UV, float4 Color);