#version 150 //GL 3.2

#include <hostdefs>
#line 4
#include "data/shader/ubo.glsl"
#line 6

uniform bool transform_with_matr_M = true;

layout(triangles) in;
layout( triangle_strip, max_vertices=8 ) out;

flat in int instance_id[];

//Original triangles' world-space vertices projected from the light onto the z=0 plane
out vec2 v0f, v1f, v2f;



void emit( in vec2 vert_wld_xy, float vert_wld_z )
{
	vec4 vert_clip = matr_PV * vec4( vert_wld_xy,vert_wld_z, 1.0 );
	gl_Position = vert_clip;

	EmitVertex();
}

void main()
{
	//World-space triangle vertices
	vec3 v0n, v1n, v2n;
	if (transform_with_matr_M)
	{
		mat4x3 matr_M = inst_matrs_M[ inst_offset + instance_id[0] ];
		v0n = matr_M * gl_in[0].gl_Position;
		v1n = matr_M * gl_in[1].gl_Position;
		v2n = matr_M * gl_in[2].gl_Position;
	}
	else
	{
		vec4 translate_scale = inst_vecs[ inst_offset + instance_id[0] ];
		v0n = gl_in[0].gl_Position.xyz*translate_scale.w + translate_scale.xyz;
		v1n = gl_in[1].gl_Position.xyz*translate_scale.w + translate_scale.xyz;
		v2n = gl_in[2].gl_Position.xyz*translate_scale.w + translate_scale.xyz;
	}
	vec3 e01 = v1n - v0n;
	vec3 e20 = v0n - v2n;

	//Vectors `L0`, `L1`, `L2` from each vertex to the light's center
	vec3 light_pos = light_pos_xyzw.xyz;
	vec3 L0 = light_pos-v0n, L1, L2;
	//	Only generate shadow volume from triangles facing away from the light
	if ( dot( cross(e01,e20), L0 ) < 0.0 ) return; //Note `e20`, not `e02`, so test flipped
	L1 = light_pos - v1n;
	L2 = light_pos - v2n;

	v0f = v0n.xy - (v0n.z/L0.z)*L0.xy;
	v1f = v1n.xy - (v1n.z/L1.z)*L1.xy;
	v2f = v2n.xy - (v2n.z/L2.z)*L2.xy;

	/*vec2 cen = ( v0f + v1f + v2f )*(1.0/3.0);
	v0f += ( v0f - cen )*0.01;
	v1f += ( v1f - cen )*0.01;
	v2f += ( v2f - cen )*0.01;*/

	emit(v0n.xy,v0n.z); emit(v0f,0.0);
	emit(v1n.xy,v1n.z); emit(v1f,0.0);
	emit(v2n.xy,v2n.z); emit(v2f,0.0);
	emit(v0n.xy,v0n.z); emit(v0f,0.0);
	EndPrimitive();
}
