Skip to content

Instantly share code, notes, and snippets.

@Koshimizu-Takehito
Last active May 5, 2024 12:30
Show Gist options
  • Save Koshimizu-Takehito/7bb4a983ae02c1db5f5750aa42550143 to your computer and use it in GitHub Desktop.
Save Koshimizu-Takehito/7bb4a983ae02c1db5f5750aa42550143 to your computer and use it in GitHub Desktop.
#include <metal_stdlib>
using namespace metal;
namespace SmoothMin2d {
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;
}
half3 rgb(float sd1, float sd2, float sd3) {
float t = atan(sd3) / __FLT_M_PI__ + 0.5;
if (sd3 < 0) {
half3 color1 = 1 - (abs(sd1)/0.4) * (1 - half3(1, 0, 1));
half3 color2 = 1 - (abs(sd2)/0.4) * (1 - half3(0, 1, 1));
return mix(color1, color2, t);
}
return mix(half3(0, 0, 1), half3(0.5, 1, 1), t);
}
}
namespace SmoothMin2d {
[[ stitchable ]] half4 main(float2 position, half4 color, float4 box, float sec, float k) {
if (box.w/box.z<1) {
position = position.yx;
}
float2 pos = - 1 + 2.0 * position / min(box.w, box.z);
float tx = 0.5 * (1 + sin(2 * sec))/2;
float ty = sin(sec);
float sd1 = circleSDF(pos, float2( tx, 1.0 + ty), 0.4);
float sd2 = circleSDF(pos, float2(-tx, 1.0 - ty), 0.4);
float sd3 = smoothMin(sd1, sd2, k);
return half4(rgb(sd1, sd2, sd3), 1.0);
}
}
import SwiftUI
struct SmoothMin2dView: View {
@State private var value: Double = 0.8
private let start = Date()
private let shader = ShaderFunction(library: .default, name: "SmoothMin2d::main")
var body: some View {
ZStack {
TimelineView(.animation) { context in
let seconds = context.date.timeIntervalSince(start)
Rectangle()
.colorEffect(
shader(
.boundingRect, // box
.float(seconds), // sec
.float(value) // k
)
)
}
.ignoresSafeArea()
VStack {
Spacer()
Slider(value: $value, in: 0...1)
.tint(.pink)
}
.padding(20)
}
}
}
#Preview {
SmoothMin2dView()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment