For my project i need to warp a quad mesh and correct the affine UV mapping to a Projective mapping.
I’ve digged the web to find some practical examples but some solution are to difficult to me that i’ve no experince with shader programming.
The ready to go solution it’s starting from this thread: Correcting affine texture mapping for trapezoids
But i’d like to do something more complex that a trapezoid like this:
and transform like this:
I’ve tried to follow the explanation from this topic: unity - How can I fix zig-zagging UV mapping artifacts on a generated mesh that tapers? - Game Development Stack Exchange
and i wrote my shader that is this:
Shader "Unlit/ProjectiveShader"
{
Properties
{
_MainTex("Texture", 2D) = "white" {}
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
// make fog work
#pragma multi_compile_fog
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float3 uv : TEXCOORD0; // Change float2 to float 3.
};
struct v2f
{
float3 uv : TEXCOORD0;
UNITY_FOG_COORDS(1)
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
float4 _MainTex_ST;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
//o.uv = TRANSFORM_TEX(v.uv, _MainTex);
o.uv = v.uv;
// If you define a float4 with the special name _MainTex_ST,
// you can get the same effect the macro had by doing this:
o.uv.xy = o.uv.xy * _MainTex_ST.xy + _MainTex_ST.zw;
UNITY_TRANSFER_FOG(o,o.vertex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
float2 uv = i.uv.xy / i.uv.z;
// sample the texture
fixed4 col = tex2D(_MainTex, i.uv);
// apply fog
UNITY_APPLY_FOG(i.fogCoord, col);
return col;
}
ENDCG
}
}
}
but seems doesn’t work at all.
The most complete explanation start here Quadrilateral Interpolation, Part 2 – Nathan Reed’s coding blog and it’s very well explained but before i start to reinvent the wheel, someone know if there is a ready shader in the asset store ?
If not it’s better to try to convert the last solution to a Cg shader that works in unity? Or there is a better way?
Thank you a lot