//This is a "base class" for all DragonAPI shader programs (represented Javaside with the ShaderProgram class); it has library functions and commonly used uniform values for which ShaderProgram has built-in functions.

varying vec2 texcoord;

//uniform sampler2D bgl_RenderedTexture;

uniform int time;
uniform int screenWidth;
uniform int screenHeight;

uniform mat4 modelview;
uniform mat4 projection;
uniform vec3 focus;

uniform float intensity;

//On screen distance, proportional to screen size
float distsq(vec2 a, vec2 b) {
	float f = float(screenHeight)/float(screenWidth);
	float dx = (a.x-b.x);
	float dy = (a.y-b.y)*f;
	return dx*dx+dy*dy;
}

//Angle in radians, pt in 0-1 screen coords
vec2 rotate(vec2 pt, vec2 origin, float ang) {
	pt.x *= float(screenWidth);
	pt.y *= float(screenHeight);
	origin.x *= float(screenWidth);
	origin.y *= float(screenHeight);
	vec2 r = pt-origin;
	float s = sin(ang);
	float c = cos(ang);
	mat2 m = mat2(c, -s, s, c);
	vec2 ret = m * r;
	ret += origin;
	ret.x /= float(screenWidth);
	ret.y /= float(screenHeight);
	return ret;
}

vec3 rgb2hsb(vec3 c) {
    vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
    vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));
    vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));
    float d = q.x - min(q.w, q.y);
    float e = 1.0e-10;
    return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);
}

// Function from Iñigo Quiles
// https://www.shadertoy.com/view/MsS3Wc
vec3 hsb2rgb(vec3 c){
    vec3 rgb = clamp(abs(mod(c.x * 6.0 + vec3(0.0, 4.0, 2.0), 6.0) - 3.0) - 1.0, 0.0, 1.0);
    rgb = rgb * rgb * (3.0 - 2.0 * rgb);
    return c.z * mix(vec3(1.0), rgb, c.y);
}

float getVisualBrightness(vec3 color) {
	return color.r*0.2989+color.g*0.5870+color.b*0.1140;
}

vec2 getScreenPos(float x, float y, float z) {
	vec4 clipSpacePos = projection * (modelview * vec4(x, y, z, 1.0));
	vec3 ndcSpacePos = clipSpacePos.xyz / clipSpacePos.w;
	return ((ndcSpacePos.xy + 1.0) / 2.0);
}

//Is relative to the actual tile/entity/etc position
vec2 getScreenPosVec(vec3 worldPos) {
	return getScreenPos(worldPos.x, worldPos.y, worldPos.z);
}

float roundToNearest(float val, float base) {
	return ceil(val/base)*base;
}