#version 330 core

uniform sampler2D diffuse;
uniform sampler2D specular;
uniform sampler2D bumpmap;
uniform sampler2D heightmap;

in vec2 pos_zw;
in vec3 normal;
in vec3 ec_pos;
in vec4 uv_offset;
in vec2 dist_blend;

layout (location = 0) out vec4 diffuse_specular;
layout (location = 1) out vec4 normal_depth;

#include <geometry_include.frag>
#include <tangentspace_include.frag>

void main()
{
	vec2 uv = uv_offset.xy;
	vec2 uv2 = uv_offset.zw;
	float blend = dist_blend.y;

	vec3 t, b;
	per_fragment_tangent_space(ec_pos, uv, t, b);

	float heightA = (texture(heightmap, uv).y*0.04 - 0.02)*3.5;
	float heightB = (texture(heightmap, uv2).y*0.04 - 0.02)*3.5;
	//float height = mix(heightA, heightB, blend);

	//height *= 1.0 / ec_pos.z;
	vec2 tex_coord = uv + normalize(-ec_pos).xy*heightA;
	vec2 tex_coord2 = uv2 + normalize(-ec_pos).xy*heightB;

	vec3 bumpA = texture(bumpmap, tex_coord).xyz*2.0 - vec3(1.0);
	vec3 bumpB = texture(bumpmap, tex_coord2).xyz*2.0 - vec3(1.0);
	vec3 bump = normalize(mix(bumpA, bumpB, blend));

	mat3 mr = mat3(t, b, normalize(normal));
	vec3 n = mr * bump;

	diffuse_specular.rgb = mix( texture(diffuse, tex_coord).rgb, texture(diffuse, tex_coord2).rgb, blend);
	diffuse_specular.a = mix( texture(specular, tex_coord).r, texture(specular, tex_coord2).r, blend);

	normal_depth.xyz = normalize(n);
	normal_depth.w = pos_zw.x/pos_zw.y;
}
