#version 330 core

uniform float time;
uniform vec2 resolution;
uniform vec2 wPos;
uniform vec2 wRad;

in vec4 aPos;
in vec2 mypos;
out vec4 fragColor;


// halfspace discard uniforms: ////////////////////////////////////

uniform int iside=0; // 0=>noDiscard

uniform vec3 eyePos;

uniform vec3  port1;
uniform vec3  port2;

// halfspace discard uniforms end /////////////////////////////////



// https://www.shadertoy.com/view/MdXSzS

void main()
{
	
	//vec2 uv = (gl_FragCoord.xy/resolution.xy)-.5;
	vec2 uv = 0.5*(mypos-wPos)/wRad;


	float intime = time * 0.9 + ((.25+.05*sin(time*.1))/(length(uv.xy)+.07))* 2.2;
	float si = sin(intime);
	float co = cos(intime);
	mat2 ma = mat2(co, si, -si, co);

	float c = 1.0;
	float v1 = 0.0;
	float v2 = 0.0;
	
	for (int i = 0; i < 100; i++)
	{
		float s = float(i) * .035;
		vec3 p = s * vec3(uv, 0.0);
		p.xy *= ma;
		p += vec3(.22,.9, s-1.9-sin(intime*1.13)*.1);
		for (int i = 0; i < 8; i++)
		{
			p = abs(p) / dot(p,p) - 0.659;
		}
		v1 += dot(p,p)*.0015 * (1.8+sin(length(uv.xy*13.0)+.5-intime*.2));
		v2 += dot(p,p)*.0015 * (1.5+sin(length(uv.xy*13.5)+2.2-intime*.3));
		c = length(p.xy*.5) * .35;
	}
	
	float len = length(uv);
	v1 *= smoothstep(.7, .0, len);
	v2 *= smoothstep(.6, .0, len);
	
	float re = clamp(c, 0.0, 1.0);
	float gr = clamp((v1+c)*.25, 0.0, 1.0);
	float bl = clamp(v2, 0.0, 1.0);
	vec3 col = vec3(re, gr, bl) + smoothstep(0.15, .0, len) * .9;

	fragColor=vec4(col, 1.0);

	// fastrgv:  my halfspace-discard addendum:
	vec3 cP1 =  port1 - eyePos;
	vec3 cP2 =  port2 - eyePos;
	vec3 vP0 = aPos.xyz - eyePos;
	float PRAD = 0.80; // larger, but synched with adagate.adb
	float FOV1 = atan(PRAD/length(cP1));
	float FOV2 = atan(PRAD/length(cP2));
	vec3 nP1 = normalize(cP1);
	vec3 nP2 = normalize(cP2);
	vec3 nP0 = normalize(vP0);
	float d1=dot(nP0,nP1);
	float d2=dot(nP0,nP2);
	float a1=acos(d1);
	float a2=acos(d2);
	if( iside != 0 ) {
		if( (iside==2) && (a1>FOV1) ) discard;
		if( (iside==1) && (a2>FOV2) ) discard;
	}

}


//--
//-- Copyright (C) 2019  <fastrgv@gmail.com>
//--
//-- This program is free software: you can redistribute it and/or modify
//-- it under the terms of the GNU General Public License as published by
//-- the Free Software Foundation, either version 3 of the License, or
//-- (at your option) any later version.
//--
//-- This program is distributed in the hope that it will be useful,
//-- but WITHOUT ANY WARRANTY; without even the implied warranty of
//-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//-- GNU General Public License for more details.
//--
//-- You may read the full text of the GNU General Public License
//-- at <http://www.gnu.org/licenses/>.
//--

