Skip to content

Instantly share code, notes, and snippets.

@andybak
Created August 23, 2019 13:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andybak/845aa64e9d9aa6080eadd256e863d835 to your computer and use it in GitHub Desktop.
Save andybak/845aa64e9d9aa6080eadd256e863d835 to your computer and use it in GitHub Desktop.
using System.Security.Cryptography.X509Certificates;
using UnityEditor;
using UnityEngine;
namespace SDFr
{
public class GradientBaker : MonoBehaviour
{
public Texture3D sdfTexture;
public float Sphere(Vector3 p, float r) {
return p.magnitude - r ;
}
public float Box(Vector2 p, Vector2 b) {
var d = new Vector2(Mathf.Abs(p.x),Mathf.Abs(p.y)) - b;
return Vector2.Max(d, Vector2.zero).magnitude + Mathf.Min(Mathf.Max(d.x, d.y), 0f);
}
public float Distance(int xx, int yy, int zz)
{
//Example synthetic distance fields
//float x = (float) xx / sdfTexture.width;
//float y = (float) yy / sdfTexture.height;
//float z = (float) zz / sdfTexture.depth;
//return Mathf.Min(Box(new Vector2(x,y), new Vector2(.2f,.2f)), Circle(new Vector2(x+.5f, y), .2f));
//return Mathf.Min(Sphere(new Vector3(x-.5f, y, z), .3f), Sphere(new Vector3(x+.5f, y, z), .3f));
return sdfTexture.GetPixel(xx, yy, zz, 0).r;
}
[ContextMenu("Bake")]
public void Bake()
{
Texture3D outTexture = new Texture3D(sdfTexture.width, sdfTexture.height, sdfTexture.depth, TextureFormat.RGBAFloat, false);
//var center = new Vector3(sdfTexture.width/2f, sdfTexture.height/2f, sdfTexture.depth/2f);
for (int z = 0; z < sdfTexture.depth; z++)
{
for (int y = 0; y < sdfTexture.height; y++)
{
for (int x = 0; x < sdfTexture.width; x++)
{
var normal = new Vector3();
//var toCenter = (new Vector3(x, y, z) - center).normalized;
normal.x = Distance(x - 1, y, z) - Distance(x + 1, y, z);
normal.y = Distance(x, y - 1, z) - Distance(x, y + 1, z);
normal.z = Distance(x, y, z - 1) - Distance(x, y, z + 1);
//var tangent = Vector3.Cross(normal, toCenter);
//var tangent = normal - center;
if (x % 8 == 0 && y % 8 == 0 && z % 8 == 0)
{
Debug.Log(Distance(x - 1, y, z) - Distance(x + 1, y, z));
Debug.Log($@"{x},{y},{z}: {normal.x},{normal.y},{normal.z}");
}
outTexture.SetPixel(x, y, z, new Color(normal.x, normal.y, normal.z));
}
}
}
outTexture.Apply();
AssetDatabase.CreateAsset(outTexture, "Assets/gradient.asset");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment