// **************************************
// DOME FLAT TO GRID for WINGS RX
// **************************************
// Domemapping for 2D contents at the dome rim
// places 2D image along grid lines of dome master
// (C) 2018 VIOSO GmbH
// version 1.1 (bf)
// date: 05.11.2018


 const float c_PI   =3.141592653589793238462643383279502884197169399375105820974944592308;
 const float c_PIH  =c_PI/2.0;
 const float c_2PI  =2.0*c_PI;
 const float c_G2R  =c_PI/180.0;
 const float c_G2RH =c_G2R/2.0;
 const vec4 c_BgColor= vec4( 0, 0, 0, 0);

//@implements: sampler2D
struct DOME_flat2grid {

	sampler2D sampler;
	
	//@ label: "Aspect X", editor: range,  min: 0, max: 300, range_min: 0, range_max: 300, range_default: 16
	float ratiox;
	//@ label: "Aspect Y", editor: range,  min: 0, max: 300, range_min: 0, range_max: 300, range_default: 9
	float ratioy;
	//@ label: "Azimuth/Position", editor: range,  min: 0, max: 360, range_min: 0, range_max: 360, range_default: 270
	float azimuth;
	//@ label: "Elevation/Height", editor: range,  min: 0, max: 90, range_min: 0, range_max: 180, range_default: 140
	float elevation;
	//@ label: "Field of view", editor: range,  min: 0, max: 360, range_min: 0, range_max: 360, range_default: 30
	float fov;

	
	
};

vec4 texture(DOME_flat2grid s, vec2 tex_coords)

{
	
	vec2 pos = tex_coords;
	float f,u,v;
	vec4 vA;
	vec2 vPos	=vec2 ( 2.0*(pos.x - 0.5), 2.0*(pos.y - 0.5) );
	float d=length(vPos);
	vec4 vT		=vec4( s.azimuth , s.elevation ,s.fov, s.ratiox / s.ratioy );	// AZIMUTH later;//
	f=mod( vT.x + 180.0, 360.0); // MAYBE Fmod ?
	
	vT.x=(f<0.0)? f + 180.0 : f - 180.0;
	
	f=atan( vPos.y, vPos.x )/c_PI;
	u=(1.0 + f)/2.0;
	v=d;
	
	vA.zw=vec2( vT.w*vT.z/360.0, vT.z/90.0);
	vA.xy=vec2( (1.0 + vT.x/180.0 - vA.z)/2.0, vT.y/90.0 - vA.w/2.0 );
	
	f=( u - vA.x )/vA.z;
	v=( v - vA.y )/vA.w;
	if(f<0.0)
		f=( 1.0 + u - vA.x )/vA.z;
	else if(f>=1.0)
		f=( u - 1.0 - vA.x )/vA.z;
			
	vec2 texco = vec2 (f,v);	
	texco.x = 1-texco.x;
	texco = 1-texco;
	
return ( (d>1.0) || (f<0) || (f>=1) || (v<0) || (v>=1) )? c_BgColor : texture( s.sampler,texco);
	
	
	
} 