Skip to content

Instantly share code, notes, and snippets.

@nbhasin2
Last active April 2, 2025 06:52
Show Gist options
  • Save nbhasin2/50542f2e5047f60d415baf395f5ff4c6 to your computer and use it in GitHub Desktop.
Save nbhasin2/50542f2e5047f60d415baf395f5ff4c6 to your computer and use it in GitHub Desktop.
Shaders_Step6.metal
// Shaders.metal
#include <metal_stdlib>
using namespace metal;
struct VertexOut {
float4 position [[position]];
float2 texCoords;
};
vertex VertexOut circle_vertex(uint vertexID [[vertex_id]]) {
float2 positions[4] = {
float2(-1.0, -1.0), float2(1.0, -1.0),
float2(-1.0, 1.0), float2(1.0, 1.0)
};
VertexOut out;
out.position = float4(positions[vertexID], 0.0, 1.0);
out.texCoords = float2((positions[vertexID].x + 1.0) / 2.0, (1.0 - positions[vertexID].y) / 2.0);
return out;
}
fragment half4 circle_fragment(VertexOut in [[stage_in]], constant float &time [[buffer(0)]]) {
float2 p1 = float2(0.3 + 0.2 * sin(time * 0.8), 0.3 + 0.2 * cos(time * 0.8));
float2 p2 = float2(0.7 + 0.2 * cos(time * 0.6), 0.7 + 0.2 * sin(time * 0.6));
float2 p3 = float2(0.5 + 0.2 * sin(time * 1.5), 0.5 + 0.2 * cos(time * 1.5));
// colors
half3 color1 = half3(1.0, 0.47, 0.2); // brightOrange
half3 color2 = half3(0.2, 0.55, 1.0); // vividBlue
half3 color3 = half3(1.0, 0.31, 0.12); // extraOrange
float maxDist = 0.825;
float influence1 = 1.0 - min(distance(in.texCoords, p1) / maxDist, 1.0);
float influence2 = 1.0 - min(distance(in.texCoords, p2) / maxDist, 1.0);
float influence3 = 1.0 - min(distance(in.texCoords, p3) / maxDist, 1.0);
influence1 = pow(max(influence1, 0.0), 2.0);
influence2 = pow(max(influence2, 0.0), 2.0);
influence3 = pow(max(influence3, 0.0), 2.0);
float totalInfluence = influence1 + influence2 + influence3;
if (totalInfluence > 0.001) {
influence1 /= totalInfluence;
influence2 /= totalInfluence;
influence3 /= totalInfluence;
} else {
influence1 = 0.33;
influence2 = 0.33;
influence3 = 0.34;
}
half3 blendedColor = influence1 * color1 + influence2 * color2 + influence3 * color3;
// TOTALLY OPTIONAL CODE for enhancing saturation.
// You can use this code or just return half4(blendedColor, 1.0);
// Both will look nice i.e return half4(saturated, 1.0); or
// simply return the blendedColor version as below
// half4(blendedColor, 1.0);
// Saturation Version - More pop
// half luminance = dot(blendedColor, half3(0.299, 0.587, 0.114));
// half3 saturated = mix(half3(luminance), blendedColor, 1.2);
// saturated = clamp(saturated, half3(0.0), half3(1.0));
// return half4(saturated, 1.0);
// or Regular version - Less pop
// blendedColor version as below
return half4(blendedColor, 1.0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment