OpenGL
Sway.Gl puts your own OpenGL rendering inside the widget tree. A GlView is a normal widget: it is sized by its
parent, and it can be clipped, transformed, faded and overlapped like any other. Use it for 3D previews, custom
visualisations or anything else that is easier to write as shaders than as Skia drawing.
Reference Sway.Gl (which brings in Silk.NET.OpenGL) and add using Sway.Gl;.
Writing a scene
Subclass GlScene. Every method runs on the UI thread with the window's GL context current. On desktop that is
OpenGL 3.3 core, so use vertex arrays and shaders; there is no fixed-function pipeline.
sealed class TriangleScene : GlScene
{
uint _program, _vao, _vbo;
public override void Initialize(GL gl)
{
// compile shaders, create buffers: called once, before the first Render
}
public override void Render(GL gl, GlFrame frame)
{
// draw into the bound framebuffer (colour, depth and stencil, cleared to transparent black)
gl.Viewport(0, 0, (uint)frame.Width, (uint)frame.Height);
// frame.Time and frame.Delta are in seconds, frame.Aspect is width / height
}
public override void OnDrag(Offset delta) { /* pointer dragged over the view, logical pixels */ }
public override void OnScroll(float delta) { /* wheel over the view, positive scrolls down */ }
public override void Dispose(GL gl) { /* delete what Initialize created */ }
}
GlFrame carries the framebuffer size in physical pixels, the time since the view first drew, and the time since the
previous frame.
Placing it in the tree
new Column(children:
[
new Text("Drag to rotate"),
new SizedBox(height: 320, child: new GlView(new CubeScene())),
])
| Parameter | Default | Meaning |
|---|---|---|
scene | The GlScene to run. | |
continuous | true | Redraw every frame. With false the scene redraws only when the view is rebuilt or resized. |
samples | 4 | Requested MSAA sample count. |
fallback | transparent | Colour painted where GL is unavailable. |
The scene renders into an offscreen framebuffer that is then drawn onto Skia's canvas, so Skia's GL state is flushed before the scene runs and invalidated afterwards. You don't need to save and restore state yourself.
Where it works
GlView needs the window's own GL context, which only the desktop host has. On the headless, web and Android hosts,
and under a RepaintBoundary (which records instead of drawing), it paints the fallback colour instead. Don't put a
GlView inside a RepaintBoundary.
A complete example, a lit cube between ordinary widgets, is in Sway.Example.Desktop/GlDemo.cs. Run it with
SWAY_GL_DEMO=1 dotnet run --project Sway.Example.Desktop.