Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Created January 13, 2019 14:58
Show Gist options
  • Save unitycoder/2fe0bfd2498041dedd5c326c9d4c727e to your computer and use it in GitHub Desktop.
Save unitycoder/2fe0bfd2498041dedd5c326c9d4c727e to your computer and use it in GitHub Desktop.
Compute Shader for Drawing Lines
// https://forum.unity.com/threads/compute-shader-for-line-drawing.599989/
#pragma kernel CSMain
RWTexture2D<float4> surface;
float Line( float2 p, float2 a, float2 b )
{
float2 pa = p-a, ba = b-a;
float h = saturate( dot(pa,ba)/dot(ba,ba) );
float2 d = pa - ba * h;
return dot(d,d);
}
[numthreads(8,8,1)]
void CSMain (uint2 id : SV_DispatchThreadID)
{
float2 uv = float2 ((float)id.x/1024, (float)id.y/1024);
float k = Line(uv,float2(0.3,0.1),float2(0.8,0.5));
float thickness = 0.00001;
surface[id.xy] = lerp( float4(1,1,1,1), float4(0,0,0,1), smoothstep(0.0, thickness, k) );
}
// https://forum.unity.com/threads/compute-shader-for-line-drawing.599989/
using UnityEngine;
public class Line : MonoBehaviour
{
public ComputeShader CS;
void Start()
{
RenderTexture RT = new RenderTexture(1024, 1024, 0);
RT.enableRandomWrite = true;
RT.Create();
CS.SetTexture(0, "surface", RT);
CS.Dispatch(0, RT.width / 8, RT.height / 8, 1);
GetComponent<Renderer>().material.mainTexture = RT;
}
}
@RockyGitHub
Copy link

This is cool! Do you have any reference material on how you came up with this? I'm trying to learn how to be more exact in the drawing of the line, such as bresenham's algorithm for pixel lines

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment