#include "macros.hlsl"
#include "funny_shared.hlsl"


COMMON {
	cbuffer CameraInfo 
	{
		float4x4 g_matViewProjection;
		float4 g_vViewPosition;
	};

	struct MaterialData_t
	{
		float4 m_vAlbedoColor;
		uint32_t m_uAlbedo;
	};

	struct PerModelData_t
	{
		float4x4 m_matTranslation;
		float4x4 m_matRotation;
		MaterialData_t m_material;
	}

	StructuredBuffer<PerModelData_t> g_modelData;
	struct PS_INPUT
	{
		float4 m_vScreenPosition: SV_POSITION;
		float4 m_vWorldPosition: POSITION;
		float4 m_vTexCoord: TEXCOORD0;
		float4 m_vNormal: NORMAL0;
		uint m_uInstance: SV_InstanceID; 
	}
}
VS
{

	struct VS_INPUT
	{
		float3 m_vPosition: POSITION;
		float2 m_vTexCoord: TEXCOORD0;
		float3 m_vNormal: NORMAL0;
	}

	PS_INPUT vsMain( VS_INPUT input, uint uInstance: SV_InstanceID, uint uBaseInstance: SV_StartInstanceLocation )
	{
		uint uInstance = uBaseInstance + uInstance;

		PS_INPUT output = {};
		output.m_vScreenPosition = float4(input.m_vPosition, 1);
		output.m_vScreenPosition = mul(
			output.m_vScreenPosition,
			g_modelData[uInstance].m_matTranslation
		);

		output.m_vScreenPosition = mul(
			output.m_vScreenPosition,
			g_matViewProjection
		);
		output.m_vWorldPosition = mul(
			float4(input.m_vPosition, 1),
			g_modelData[uInstance].m_matTranslation
		);
		output.m_vNormal = mul(
			float4(input.m_vNormal, 1),
			g_modelData[uInstance].m_matRotation
		);
		output.m_vTexCoord = float4(input.m_vTexCoord, 0, 0);
		output.m_uInstance = uInstance;
		return output;
	}
}
PS
{
	#include "brdf.hlsl"
	#include "textures.hlsl"


	struct PS_OUTPUT
	{
		float4 m_vAlbedo: SV_Target0;
		float4 m_vNormal: SV_Target1;
		float4 m_vWorldPosition: SV_Target2;
	}

	PS_OUTPUT psMain( PS_INPUT input )
	{
		PS_OUTPUT output = {};
		PerModelData_t data = g_modelData[input.m_uInstance];
		if ( data.m_material.m_uAlbedo != -1 )
		{
			output.m_vAlbedo = g_textures[data.m_material.m_uAlbedo]
				.Sample(g_textureSampler, input.m_vTexCoord.xy);
		}
		else 
		{
			output.m_vAlbedo = data.m_material.m_vAlbedoColor;

		}
		output.m_vWorldPosition = input.m_vWorldPosition;
		output.m_vNormal = input.m_vNormal;
		return output;
	}
}

