// Cheap shadows are hard. In fact, I'd almost say, shadowing particular scenes with limited // iterations is impossible... However, I'd be very grateful if someone could prove me wrong. :) private static float SoftShadow(Float3 ro, Float3 lp, Float3 n, float k) { const int iter = 24; ro += n * 0.0015f; Float3 rd = lp - ro; float shade = 1.0f; float t = 0; float end = Hlsl.Max(Hlsl.Length(rd), 0.0001f); rd /= end; for (int i = 0; i < iter; i++) { float d = M(ro + rd * t); shade = Hlsl.Min(shade, k * d / t); t += Hlsl.Clamp(d, 0.01f, 0.25f); if (d < 0.0f || t > end) { break; } } return(Hlsl.Max(shade, 0.0f)); }
static float SDBox(float3 p, float3 b) { float3 q = Hlsl.Abs(p) - b; return(Hlsl.Length(Hlsl.Max(q, 0.0f)) + Hlsl.Min(Hlsl.Max(q.X, Hlsl.Max(q.Y, q.Z)), 0.0f)); }
// Various distance metrics. private static float Distance(Float2 p) { if (SHAPE == 0) { return(Hlsl.Length(p)); } else { p = Hlsl.Abs(p); } switch (SHAPE) { case 1: return(Hlsl.Max(Hlsl.Length(p), (p.X + p.Y) * 0.7071f + 0.015f)); case 2: return(Hlsl.Max((p.X + p.Y) * 0.7071f, Hlsl.Max(p.X, p.Y))); case 3: return(Hlsl.Pow(Hlsl.Dot(Hlsl.Pow(p, 3), 1), 1.0f / 3.0f)); default: return((p.X + p.Y) * 0.7071f); } }
// The scene's distance function: There'd be faster ways to do this, but it's // more readable this way. Plus, this is a pretty simple scene, so it's // efficient enough. private static float M(Float3 p) { float fl = -p.Z; float obj = Truchet(p.XY); obj = Hlsl.Max(obj, Hlsl.Abs(p.Z) - 0.125f) - Hlsl.SmoothStep(0.03f, 0.25f, -obj) * 0.1f; float studs = 1e5f; const float sc = 0.5f; Float2 q = p.XY + 0.5f * sc; Float2 iq = Hlsl.Floor(q / sc) + 0.5f; q -= iq * sc; if (Mod(iq.X + iq.Y, 2.0f) > 0.5f) { studs = Hlsl.Max(Hlsl.Length(q) - 0.1f * sc - 0.02f, Hlsl.Abs(p.Z) - 0.26f); } objID = fl < obj && fl < studs ? 0 : obj < studs ? 1 : 2; return(Hlsl.Min(Hlsl.Min(fl, obj), studs)); }