// AUTOGENERATED COPYRIGHT HEADER START
// Copyright (C) 2020-2023 Michael Fabian 'Xaymar' Dirks <info@xaymar.com>
// AUTOGENERATED COPYRIGHT HEADER END

// Always provided by OBS
uniform float4x4 ViewProj<
	bool automatic = true;
	string name = "View Projection Matrix";
>;

// Provided by Stream Effects
uniform float4 Time<
	bool automatic = true;
	string name = "Time Array";
	string description = "A float4 value containing the total time, rendering time and the time since the last tick. The last value is a random number between 0 and 1.";
>;
uniform float4x4 Random<
	bool automatic = true;
	string name = "Random Array";
	string description = "A float4x4 value containing random values between 0 and 1";
>;
uniform texture2d InputA<
	bool automatic = true;
>;
uniform texture2d InputB<
	bool automatic = true;
>;
uniform float TransitionTime<
	bool automatic = true;
>;
uniform int2 TransitionSize<
	bool automatic = true;
>;

uniform float Sharpness<
	string field_type = "slider";
	string suffix = " %";
	float minimum = 8.0;
	float maximum = 128.0;
	float step = 0.01;
	float scale = 1.0;
> = 10.0;

// ---------- Shader Code
sampler_state def_sampler {
	AddressU  = Clamp;
	AddressV  = Clamp;
	Filter    = Linear;
};

struct VertData {
	float4 pos : POSITION;
	float2 uv  : TEXCOORD0;
};

VertData VSDefault(VertData v_in) {
	VertData vert_out;
	vert_out.pos = mul(float4(v_in.pos.xyz, 1.0), ViewProj);
	vert_out.uv  = v_in.uv;
	return vert_out;
}

float4 RGBtoHSV(float4 RGBA) {
	const float4 K = float4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
	const float e = 1.0e-10;
	float4 p = lerp(float4(RGBA.bg, K.wz), float4(RGBA.gb, K.xy), step(RGBA.b, RGBA.g));
	float4 q = lerp(float4(p.xyw, RGBA.r), float4(RGBA.r, p.yzx), step(p.x, RGBA.r));
	float d = q.x - min(q.w, q.y);
	return float4(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x, RGBA.a);
}

float4 HSVtoRGB(float4 HSVA) {
	const float4 K = float4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
	float4 v = float4(0,0,0,0);
	v.rgb = HSVA.z * lerp(K.xxx, clamp(abs(frac(HSVA.xxx + K.xyz) * 6.0 - K.www) - K.xxx, 0.0, 1.0), HSVA.y);
	v.a = HSVA.a;
	return v;
}

float4 PSDefault(VertData v_in) : TARGET {
	float4 sampleA = InputA.Sample(def_sampler, v_in.uv);
	float4 sampleB = InputB.Sample(def_sampler, v_in.uv);

	float4 hslA = RGBtoHSV(sampleA);
	float4 hslB = RGBtoHSV(sampleB);
	float4 hslT = hslB - hslA;
	if (hslT.r > 0.5) {
		hslB.r = 1.0 + (-1.0 + hslB.r);
	}
	if (hslT.g > 0.5) {
		hslB.g = 1.0 + (-1.0 + hslB.g);
	}
	if (hslT.b > 0.5) {
		hslB.b = 1.0 + (-1.0 + hslB.b);
	}

	float4 rgb = HSVtoRGB(lerp(hslA, hslB, TransitionTime));
	
	return rgb;
}

technique Draw
{
	pass
	{
		vertex_shader = VSDefault(v_in);
		pixel_shader  = PSDefault(v_in); 
	}
}
