Home / Forums / High-Performance Line Rendering in Unity with GL.LINES

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Tutorial

High-Performance Line Rendering in Unity with GL.LINES

DirectXRay
DirectX 12 / Vulkan Dev
MEMBER
Rep: 240
Join Date: Feb 2023
Posts: 31
Thanks: 60
2y ago · May 18, 2024 5:00 PM
#1
When rendering dozens of snaplines, skeleton bones, and bounding boxes in Unity,
CSHARP
GUI.DrawTexture
can generate significant CPU overhead.

Using Unity's low-level
CODE
GL.LINES
pipeline for maximum FPS:


CSHARP
using UnityEngine;

public class GLESPRenderer : MonoBehaviour
{
    private static Material _lineMaterial;

    private static void CreateLineMaterial()
    {
        if (_lineMaterial == null)
        {
            Shader shader = Shader.Find("Hidden/Internal-Colored");
            _lineMaterial = new Material(shader) { hideFlags = HideFlags.HideAndDontSave };
            _lineMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
            _lineMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
            _lineMaterial.SetInt("_Cull", (int)UnityEngine.Rendering.CullMode.Off);
            _lineMaterial.SetInt("_ZWrite", 0);
            _lineMaterial.SetInt("_ZTest", (int)UnityEngine.Rendering.CompareFunction.Always);
        }
    }

    public static void RenderSnapline(Vector3 screenFrom, Vector3 screenTo, Color color)
    {
        CreateLineMaterial();
        _lineMaterial.SetPass(0);

        GL.PushMatrix();
        GL.LoadPixelMatrix();
        GL.Begin(GL.LINES);
        GL.Color(color);

        GL.Vertex3(screenFrom.x, screenFrom.y, 0);
        GL.Vertex3(screenTo.x, screenTo.y, 0);

        GL.End();
        GL.PopMatrix();
    }
}


Call this inside
CODE
Camera.onPostRender
or your render hook for zero-overhead GPU line drawing!
DirectXRay · DirectX 12 & Vulkan Command Lists
The following users thanked DirectXRay for this post:
GlowShader
Shader & Overlay Artist
MEMBER
Rep: 185
Join Date: Oct 2023
Posts: 36
Thanks: 46
2y ago · May 18, 2024 7:20 PM
#2
CODE
Hidden/Internal-Colored
with
CODE
GL.LoadPixelMatrix()
is the cleanest native way to draw lines in Unity. You can batch hundreds of lines between a single
CODE
GL.Begin(GL.LINES)
and
CODE
GL.End()
!
GlowShader | Shaders, Stencils & DirectX DrawLists
RustMechanic
Unity & IL2CPP Reverser
VIP
Rep: 295
Join Date: Nov 2022
Posts: 32
Thanks: 74
2y ago · May 19, 2024 11:05 AM
#3
Batching all entity lines in one GL pass dropped our render frame time from 4ms down to under 0.2ms. Massive performance boost!
RustMechanic | IL2CPP & Unity Engine Analysis