From 73918b0c70592d16afd688dca0b8b3466ca7bff2 Mon Sep 17 00:00:00 2001 From: Raffaele Picca Date: Mon, 25 Sep 2023 18:57:10 +0200 Subject: [PATCH] Fixing incorrect normal map when using triplanar world mapping and mesh rotation --- scene/resources/material.cpp | 31 ++++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/scene/resources/material.cpp b/scene/resources/material.cpp index 461dbbec2fa..69977776231 100644 --- a/scene/resources/material.cpp +++ b/scene/resources/material.cpp @@ -1059,20 +1059,33 @@ void BaseMaterial3D::_update_shader() { } if (flags[FLAG_UV1_USE_TRIPLANAR] || flags[FLAG_UV2_USE_TRIPLANAR]) { //generate tangent and binormal in world space - code += " TANGENT = vec3(0.0,0.0,-1.0) * abs(NORMAL.x);\n"; - code += " TANGENT+= vec3(1.0,0.0,0.0) * abs(NORMAL.y);\n"; - code += " TANGENT+= vec3(1.0,0.0,0.0) * abs(NORMAL.z);\n"; - code += " TANGENT = normalize(TANGENT);\n"; + if (flags[FLAG_UV1_USE_WORLD_TRIPLANAR]) { + code += " vec3 normal = MODEL_NORMAL_MATRIX * NORMAL;\n"; + } else { + code += " vec3 normal = NORMAL;\n"; + } + code += " TANGENT = vec3(0.0,0.0,-1.0) * abs(normal.x);\n"; + code += " TANGENT+= vec3(1.0,0.0,0.0) * abs(normal.y);\n"; + code += " TANGENT+= vec3(1.0,0.0,0.0) * abs(normal.z);\n"; + if (flags[FLAG_UV1_USE_WORLD_TRIPLANAR]) { + code += " TANGENT = inverse(MODEL_NORMAL_MATRIX) * normalize(TANGENT);\n"; + } else { + code += " TANGENT = normalize(TANGENT);\n"; + } - code += " BINORMAL = vec3(0.0,1.0,0.0) * abs(NORMAL.x);\n"; - code += " BINORMAL+= vec3(0.0,0.0,-1.0) * abs(NORMAL.y);\n"; - code += " BINORMAL+= vec3(0.0,1.0,0.0) * abs(NORMAL.z);\n"; - code += " BINORMAL = normalize(BINORMAL);\n"; + code += " BINORMAL = vec3(0.0,1.0,0.0) * abs(normal.x);\n"; + code += " BINORMAL+= vec3(0.0,0.0,-1.0) * abs(normal.y);\n"; + code += " BINORMAL+= vec3(0.0,1.0,0.0) * abs(normal.z);\n"; + if (flags[FLAG_UV1_USE_WORLD_TRIPLANAR]) { + code += " BINORMAL = inverse(MODEL_NORMAL_MATRIX) * normalize(BINORMAL);\n"; + } else { + code += " BINORMAL = normalize(BINORMAL);\n"; + } } if (flags[FLAG_UV1_USE_TRIPLANAR]) { if (flags[FLAG_UV1_USE_WORLD_TRIPLANAR]) { - code += " uv1_power_normal=pow(abs(mat3(MODEL_MATRIX) * NORMAL),vec3(uv1_blend_sharpness));\n"; + code += " uv1_power_normal=pow(abs(normal),vec3(uv1_blend_sharpness));\n"; code += " uv1_triplanar_pos = (MODEL_MATRIX * vec4(VERTEX, 1.0f)).xyz * uv1_scale + uv1_offset;\n"; } else { code += " uv1_power_normal=pow(abs(NORMAL),vec3(uv1_blend_sharpness));\n";