#version 460

#extension GL_GOOGLE_include_directive : require

#include "gui.layout"

layout (location = 0) in vec4 in_col_1;
layout (location = 1) in vec4 in_col_2;
layout (location = 2) in vec4 in_col_3;
layout (location = 3) in vec4 in_col_4;
layout (location = 4) in vec2 in_dst_start;
layout (location = 5) in vec2 in_dst_end;
layout (location = 6) in vec2 in_src_start;
layout (location = 7) in vec2 in_src_end;
layout (location = 8) in float border_thickness;
layout (location = 9) in float corner_radius;
layout (location = 10) in float edge_softness;
layout (location = 11) in float raised;
layout (location = 12) in float z_index;
layout (location = 13) in uint in_has_texture;

layout (location = 0) flat out uint out_has_texture;

layout (location = 1) out struct FragDataOut {
	vec4  color;
	vec2  uv;
	vec2  dst_pos;
	vec2  dst_center;
	vec2  dst_half_size;
	vec2  sdf_sample_pos;
	float corner_radius;
	float softness;
	float raised;
	float border_thickness;
} FragData;


vec2 Vertices[4] = vec2[4](
	vec2(-1.0, -1.0),
	vec2(-1.0, +1.0),
	vec2(+1.0, -1.0),
	vec2(+1.0, +1.0)
);

vec2 rotate(vec2 coords, float theta)
{
	return mat2(cos(theta), sin(theta), -sin(theta), cos(theta)) * coords;
}

void main()
{
	ivec2 tex_size = textureSize(sampler2D(SpriteAtlas, SamplerNearest), 0);

	vec4 pos_start = vec4(in_dst_start.x, in_dst_start.y - raised, 0.0, 1.0);
	vec4 pos_end = vec4(in_dst_end.x, in_dst_end.y, 0.0, 1.0);

	vec2 half_size = ((pos_end.xy - pos_start.xy) / 2);
	vec2 center = ((pos_end.xy + pos_start.xy) / 2);
	vec2 pos = (Vertices[gl_VertexIndex] * half_size + center);

	vec2 src_half_size = (in_src_end - in_src_start) / 2;
	vec2 src_center = (in_src_end + in_src_start) / 2;
	vec2 src_pos = (Vertices[gl_VertexIndex] * src_half_size + src_center);

	vec2 uvs[4] = vec2[4](
		vec2(in_src_start.x, in_src_start.y),
		vec2(in_src_start.x, in_src_end.y),
		vec2(in_src_end.x, in_src_start.y),
		vec2(in_src_end.x, in_src_end.y)
	);

	vec4 cols[4] = vec4[4](
		in_col_1,
		in_col_2,
		in_col_3,
		in_col_4
	);

	vec2 dst_verts_pct = vec2(bool(gl_VertexIndex >> 1) ? 1.0f : 0.0f, 
													  bool(gl_VertexIndex &  1) ? 0.0f : 1.0f);

	FragData.color = cols[gl_VertexIndex];
	FragData.uv = uvs[gl_VertexIndex] / tex_size;
	FragData.dst_pos = pos;
	FragData.dst_center = center;
	FragData.dst_half_size = half_size;
	FragData.corner_radius = corner_radius;
	FragData.softness = edge_softness;
	FragData.raised = raised;
	FragData.border_thickness = border_thickness;
	FragData.sdf_sample_pos = (2.0f * dst_verts_pct - 1.0f) * half_size;
	out_has_texture = in_has_texture;

	vec4 v_pos = PC.projection * vec4(pos.x, pos.y, z_index, 1);
	gl_Position = vec4(v_pos.x, v_pos.y, v_pos.z, 1);
}
