// Copyright (C) 2011 Kimmo Lahtinen - All Rights Reserved

// Uniform transforms
uniform highp vec3 uni_base_texture_params;
uniform highp vec3 uni_grass_texture_params;
uniform highp vec3 uni_roots_texture_params;

// Input from engine (per vertex)
attribute highp vec4 in_pos_and_depth_from_surface;
attribute highp float in_texturing_axis;

// Output to pixel shader
varying vec2 frag_uv_base;
varying vec2 frag_uv_grass;
varying vec2 frag_uv_roots;
varying vec2 frag_uv_lightmap;
varying float frag_overlay_alpha;
varying vec3 frag_light_color;

void main(void)
{
	// Transform position
	vec3 vtx_pos = in_pos_and_depth_from_surface.xyz;
	gl_Position = to_screen_pos_3d(vtx_pos);

	// Fade grass under water (TODOmaybe: would be better to use a separate water bottom overlay texture)
	frag_overlay_alpha = min(smoothstep(-0.1, 0.0, vtx_pos.z) + 0.55, 1.0);
//	frag_overlay_alpha = 1.0;

	// Texturing
	float u_pos = vtx_pos[int(in_texturing_axis)];

	// Base texture UVs
	// Align center of texture to 0 in Z direction
	{
		float pixels_per_tile = uni_base_texture_params.z;
		vec2 uv_scale = 1.0 / (uni_base_texture_params.xy / pixels_per_tile);
		frag_uv_base = vec2(u_pos * uv_scale.x,	-vtx_pos.z * uv_scale.y);

		// Move upwards so it fits (0.5 == halfway is at 0)
		frag_uv_base.y += 0.5;
	}

	float surface_depth = in_pos_and_depth_from_surface.w;

	// Grass texture UVs
	{
		vec2 uv_scale = 1.0 / (uni_grass_texture_params.xy / uni_grass_texture_params.z);
		frag_uv_grass = vec2(u_pos * uv_scale.x, surface_depth * uv_scale.y);
	}

	// Roots texture UVs
	{
		vec2 uv_scale = 1.0 / (uni_roots_texture_params.xy / uni_roots_texture_params.z);
		frag_uv_roots = vec2(u_pos * uv_scale.x, surface_depth * uv_scale.y);
	}

	// Manually adjust the textures to be about cool beans
	{
		// TODO: these should be texture resolution dependent (and uniforms probably)

		float overhang_adjust = 0.32;
		frag_uv_grass.y += overhang_adjust;
		frag_uv_roots.y += overhang_adjust;

		float base_adjust = 0.04;
		frag_uv_base.y += base_adjust;
	}

	// Lightmap texturing
	{
		frag_uv_lightmap =  cutaway_lightmap_uv(vtx_pos.xy, int(in_texturing_axis));
	}

	if (in_texturing_axis == 0.0)
	{
		// Just offset the UVs a bit on the other side so it doesn't look mirrored at the corner
		frag_uv_base.x -= 0.89;
		frag_uv_grass.x -= 0.2;
		frag_uv_roots.x -= 0.35;

		frag_uv_base.x *= -1.0; // Invert so shading in the texture goes to better direction
	}

	// Calculate lighting for the surface (with arbitrary normals to give a slight shading to one side)
	frag_light_color = (in_texturing_axis == 0.0)
		? light_surface(normalize(vec3(-0.7, 0, 1)))
		: light_surface(vec3(0, 0, 1));
}
