Skip to content

Instantly share code, notes, and snippets.

@Koshimizu-Takehito
Created February 15, 2025 10:50
Show Gist options
  • Save Koshimizu-Takehito/d1de708e3c4820e4bf759bea14cf08ad to your computer and use it in GitHub Desktop.
Save Koshimizu-Takehito/d1de708e3c4820e4bf759bea14cf08ad to your computer and use it in GitHub Desktop.
Circle SDF
#include <metal_stdlib>
using namespace metal;
float smoothMin(float x1, float x2, float k) {
float h = clamp(0.5 - 0.5 * (x2 - x1) / k, 0.0, 1.0);
return mix(x1, x2, h) - k * h * (1.0 - h);
}
float circleSDF(float2 point, float2 center, float radius) {
return length(point - center) - radius;
}
namespace SDF {
[[ stitchable ]] half4 main(float2 position, half4 color, float4 box, float sec) {
float2 pos = -1.0 + 2.0 * position / min(box.w, box.z);
float tx = 0.5 * (1.0 + sin(2.0 * sec)) / 2.0;
float ty = sin(sec);
float sdf1 = circleSDF(pos, float2(tx, 1.0 + ty), 0.4);
float sdf2 = circleSDF(pos, float2(-tx, 1.0 - ty), 0.4);
float sdf3 = smoothMin(sdf1, sdf2, 0.4);
if (sdf3 < 0) {
return half4(0.1, 0.5, 1, 1);
}
return half4(1, 1, 1, 1);
}
}
import SwiftUI
struct ShaderView: View {
let name: String
private let start = Date()
var body: some View {
TimelineView(.animation) { context in
Rectangle().colorEffect(shader(
seconds: context.date.timeIntervalSince(start)
))
}
.ignoresSafeArea()
}
private func shader(seconds: TimeInterval) -> Shader {
let function = ShaderFunction(library: .default, name: name)
return function(.boundingRect, .float(seconds))
}
}
#Preview("SDF") {
ShaderView(name: "SDF::main")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment