- Home /
Converting c# function to shader.
I have a spline class with a method that draws it to a sprite. The relevant parts are isolated into following code:
SpriteRenderer sr;
private void Awake()
{
sr = GetComponent<SpriteRenderer>();
}
private void Update()
{
Draw();
}
private void Draw()
{
Texture2D texture = new Texture2D(128, 128);
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, 128, 128), Vector2.zero);
sr.sprite = sprite;
Vector2 pixelSize = new Vector2(sr.size.x / texture.width, sr.size.y / texture.height);
Vector2 lowerLeft = (Vector2)transform.position + pixelSize;
Color[] colors = texture.GetPixels();
for (int i = 0; i < colors.Length; ++i)
{
Vector2 pixelPos = lowerLeft;
pixelPos.x += i % texture.width * pixelSize.x;
pixelPos.y += Mathf.Floor(i / texture.width) * pixelSize.y);
// Make pixel red if pixel distance to spline is less than radius.
if (GetDistance() < radius)
{
colors[i] = Color.red;
}
else
{
colors[i] = Color.blue;
}
}
texture.SetPixels(colors);
texture.Apply();
}
Now this is naturally really slow. One spline alone decreases the framerate noticeably. So, i thought this seemed like the kind of thing that would normally be done with shaders, but have absolutely no experience with them. I just want to know if i can actually use my GetDistance() method in a shader, or if i will have to rewrite it. Also, if you know an alternative to shaders that can make this run decently, please tell!
What you're effectively doing is rendering an SDF, so yes the rendering side is definitely possible. However, the most important part of the equation is your GetDistance() function, which you haven't provided. As such it's impossible to comment on how easy converting to a shader would be.
Posting the function would end up becom$$anonymous$$g a mess, because it depends on more functions etc. However, essentially what i am doing is using unitys built in HandleUtility.DistancePointBezier
to get the distances to a series of cubic bezier curves, and then return the smallest one. So i don't actually have the code for calculating the distance. Anyways, if shaders can do it, i will take the time to learn how they work. Thanks.