Shader "CrispyPin/Spheres"
{
	Properties
	{
		[Header(Raymarcher Properties)]
		_MaxSteps ("Max steps", Integer) = 128
		_MaxDist ("Max distance", Float) = 128
		_SurfDist ("Surface distance threshold", Range(.0001, .05)) = .001
	}
	SubShader
	{
		Tags { "RenderType"="Opaque" }
		Cull Front
		LOD 100

		Pass
		{
			CGPROGRAM
			#pragma vertex vert
			#pragma fragment frag

			int _MaxSteps;
			float _MaxDist;
			float _SurfDist;
			#define MAX_STEPS _MaxSteps
			#define MAX_DIST _MaxDist
			#define SURF_DIST _SurfDist


			#define SCENE_FN main
			#define LIGHT_FN lighting

			// #define SCENE_SCALE 1

			#define DISCARD_ON_MISS

			#include "lib/libgarbage.cginc"

			#define SPEED 1.5
			#define BOX_SIZE .15
			#define RADIUS BOX_SIZE*2

			float3 checkers(float3 p, float3 a, float3 b, float2 size) {
				float2 q = p.xz / size;
				q = int2(abs(q) + .5);
				int s = ((q.x + q.y) % 2);
				return s * a + (1 - s) * b;
			}

			SurfacePoint main(float3 p) {
				SurfacePoint d;
				const float COUNT_Y = 20;
				const float COUNT_R = 20;

				float lat = asin(p.y) * COUNT_Y;
				float long = atan2(p.z, p.x) * COUNT_R + _Time.y * 16;
				float r = length(p);
				// float grid = (1-abs(smoothstep(0, 0.5, sin(long))-0.5))*2 - 1;
				float grid = (1-abs(smoothstep(0, 0.5, sin(lat))-0.5))*2 - 1;
				d = mSphere(p, 0.21,
					mat(abs(rotY(p, _Time.y*-4)/0.21))
					// mat(lat, long, grid)
				);

				// float long
				lat = floor(lat+0.5)-0.5;
				long = floor(long+0.5)-0.5;
				float sx = sin(long);
				float sz = cos(long);
				float sy = sin(lat);
				d = qUnion(d, mSphere(p - normalize(float3(sx, sy, sz))*r, 0.1));

				return d;
			}


			float3 lighting(Ray ray) {
				float3 sun_dir = normalize(float3(2, 1, -1));
				if (ray.missed) {
					return lRenderSky(ray.dir, sun_dir);
				}
				float3 light = lSun(ray.normal, sun_dir);
				// light *= lShadow(ray.hit_pos + ray.normal * SURF_DIST, sun_dir, 50);
				light += lSky(ray.normal)*5;
				return 1;
			}

			ENDCG
		}
	}
}
