# Your first GPU triangle

Build a colored triangle that sits inside an ordinary Xui view. You will create its shaders once, submit three vertices, and let the runtime retain the resulting surface between changes.

This example needs `Xui.Core` and the `Xui.CompileTime` analyzer. DemoApp already includes both. The analyzer generates shader source and entry-point helpers from `[ShaderProgram]`; copying the file into a project without that analyzer leaves those helpers undefined. Android additionally needs the shader asset build targets used by DemoApp to compile generated shader source to SPIR-V.

## Draw the triangle

<div class="docs-demo-layout">

```csharp
using System;
using Xui.Core.Canvas;
using Xui.Core.Canvas.Composition.GPU;
using Xui.Core.Canvas.Composition.Graphics;
using Xui.Core.UI;
using Xui.GPU.Backends;
using Xui.GPU.Hardware;
using Xui.GPU.Shaders;
using Xui.GPU.Shaders.Attributes;
using Xui.GPU.Shaders.Types;

namespace Xui.Apps.DemoApp.Docs.Gpu;
[ShaderProgram]
public partial struct TriangleShader
{
    public struct Vertex
    {
        public Float3 Position;
        public Color4 Color;
    }

    public struct Varyings
    {
        [BuiltIn(BuiltIn.Position)]
        public Float4 Position;
        [Location(0)]
        public Color4 Color;
    }

    public struct Bindings
    {
        public Float4x4 Transform;
    }

    [VertexShader]
    public struct VertexStage : IVertexShader<Vertex, Varyings, Bindings>
    {
        public Varyings Execute(Vertex input, in Bindings bindings) => new()
        {
            Position = bindings.Transform * new Float4(input.Position, F32.One),
            Color = input.Color
        };
    }

    [FragmentShader]
    public struct FragmentStage : IFragmentShader<Varyings, FragmentOutput, Bindings>
    {
        public FragmentOutput Execute(Varyings input, in Bindings bindings) => new()
        {
            Color = input.Color
        };
    }
}

public sealed class Triangle : View, IGpuSurfaceContent
{
    private readonly TriangleShader.Vertex[] vertices = [new()
    {
        Position = new(-0.75f, -0.65f, 0),
        Color = new(0.52f, 0.22f, 0.81f, 1)
    }, new()
    {
        Position = new(0, 0.75f, 0),
        Color = new(0.85f, 0.34f, 0.66f, 1)
    }, new()
    {
        Position = new(0.75f, -0.65f, 0),
        Color = new(0.35f, 0.65f, 1, 1)
    }

    ];
    private IGpuVertexShader? vertexShader;
    private IGpuFragmentShader? fragmentShader;
    private IGpuCommandList? commands;
    private GpuPipelineDesc? pipeline;
    private bool dirty = true;
    protected override void RenderCore(IContext context)
    {
        if (context.GpuSurface(new GroupOptions { Key = this, Bounds = Frame, HasUpdates = dirty }, out _))
            return;
        // SVG and unsupported runtimes show a real fallback, not a simulated GPU image.
        context.SetFill(new Color(0xFAF7FFFF));
        context.FillRect(Frame);
        context.SetFill(new Color(0x592C83FF));
        context.SetFont(new Font(17, "Inter"));
        context.TextAlign = TextAlign.Center;
        context.TextBaseline = TextBaseline.Middle;
        context.FillText("GPU surface unavailable in this renderer", Frame.Center);
    }

    void IGpuSurfaceContent.Render(IGpuRenderTarget target)
    {
        if (pipeline is null)
        {
            var device = GetService(typeof(IGpuDevice)) as IGpuDevice ?? throw new NotSupportedException("This window has no GPU device.");
            var backend = GetService(typeof(IShaderBackend)) as IShaderBackend ?? throw new NotSupportedException("This window has no shader backend.");
            var source = TriangleShader.GenerateShaderSource(backend);
            vertexShader = device.CompileVertexShader(source, TriangleShader.GetVertexEntry(backend.Name));
            fragmentShader = device.CompileFragmentShader(source, TriangleShader.GetFragmentEntry(backend.Name));
            commands = device.CreateCommandList();
            pipeline = new()
            {
                VertexShader = vertexShader,
                FragmentShader = fragmentShader,
                DepthTestEnabled = false,
                DepthWriteEnabled = false,
                CullMode = GpuCullMode.None
            };
        }

        var transform = Float4x4.Identity;
        commands!.BeginRenderPass(target, new Color4(0.98f, 0.97f, 1, 1));
        commands.SetPipeline(pipeline);
        commands.SetVertexBuffer<TriangleShader.Vertex>(vertices);
        commands.SetConstantBuffer(in transform);
        commands.Draw(vertices.Length);
        commands.EndRenderPass();
        commands.Commit();
        dirty = false;
    }

    protected override void OnDeactivate()
    {
        commands?.Dispose();
        commands = null;
        vertexShader?.Dispose();
        vertexShader = null;
        fragmentShader?.Dispose();
        fragmentShader = null;
        pipeline = null;
        dirty = true;
        base.OnDeactivate();
    }
}
```

<figure class="docs-demo" data-demo-url="../../../wasm/?embed=1&amp;demo=gpu/triangle">
<div class="docs-demo-stage">
<img src="gpu-triangle.svg" width="400" height="600" alt="Your first GPU triangle: initial rendered view" />
<button type="button" class="docs-demo-start" hidden><span class="docs-demo-pill">Start demo</span></button>
</div>
<div class="docs-demo-actions">
<button type="button" class="docs-demo-close" hidden>Close demo</button>
<span class="docs-demo-status" role="status" aria-live="polite"></span>
</div>
<figcaption>Your first GPU triangle · <a href="gpu-triangle.cs">C# source</a> · <a href="gpu-triangle.svg">SVG</a> · <a href="../../../wasm/?embed=1&amp;demo=gpu/triangle">Open demo</a></figcaption>
</figure>

</div>


The SVG shows the example's **unavailable-renderer fallback**. Start the demo to request a real WebGL 2 surface. On a browser that permits WebGL 2, the rectangle becomes a triangle with interpolated purple, pink, and blue corners. If GPU presentation is unavailable, the fallback stays visible.

## Follow one frame

`RenderCore` supplies a stable `Key`, the view's `Frame`, and whether scene data changed. The runtime creates or resizes a target and calls `IGpuSurfaceContent.Render`. The callback creates shaders and a command list on first use, then begins a pass, binds the pipeline, uploads vertices and a transform, draws, ends, and commits.

The vertices already occupy clip space. The identity matrix keeps their coordinates unchanged. Depth and culling are disabled so a first triangle does not disappear because of an accidental winding convention. The fragment shader returns the interpolated vertex color.

`HasUpdates = false` lets the runtime reuse the previous frame. It still draws again when a target is new or resized. If you change a vertex or uniform later, set the dirty flag and call `InvalidateRender()`.

## Keep ownership explicit

The callback borrows `target`; the view does not dispose it. `OnDeactivate` releases only the resources the view created and resets the dirty state for reactivation. Shader compilation errors remain visible exceptions rather than being swallowed as a missing capability.

To run locally from a checkout:

```sh
dotnet run --project Xui/Apps/DemoApp/DemoApp.Desktop.csproj -- --demo gpu/triangle
```

Continue with [C# shaders](../shaders/index.md) to understand the stage contracts.
