length()问题记录
在使用GLSL中的length()函数时,笔者遇到了如下问题
#顶点着色器
layout(location = 0) in vec3 in_Position;
layout(location = 1) in vec3 in_Color;
layout(location = 2) in vec3 in_Normal;
layout(location = 3) in vec2 in_UV;layout(location = 0) out vec3 out_MCPosition;
layout(location = 1) out vec3 out_VCPosition;
layout(location = 2) out vec3 out_Color;
layout(location = 3) out vec3 out_Normal;
layout(location = 4) out vec2 out_UV;void main() {// model and view transformations do not change the w componentout_MCPosition = vec3(objectData.model * vec4(in_Position, 1.0));out_VCPosition = vec3(cameraData.view * vec4(out_MCPosition, 1.0));gl_Position = cameraData.proj * vec4(out_VCPosition, 1.0);out_Color = vec3(1.0f, 1.0f, 1.0f);out_Normal = mat3(objectData.normal) * in_Normal;out_UV = in_UV;
}
#片段着色器
layout(location = 0) in vec3 in_MCPosition;
layout(location = 1) in vec3 in_VCPosition;
layout(location = 2) in vec3 in_Color;
layout(location = 3) in vec3 in_Normal;
layout(location = 4) in vec2 in_UV;void main() {vec4 fragColor = vec4(in_Color, objectData.transparent);uint newHead = atomicCounterIncrement(indexCounter);uint oldHead = imageAtomicExchange(headPointerImage, ivec2(gl_FragCoord.xy), newHead);float dist = in_VCPosition.length();if (in_VCPosition.z > 0 || dist < 0.01f) {return;}uvec4 item = uvec4(0u);// 初始化 itemitem.x = oldHead;item.y = packUnorm4x8(fragColor);item.z = floatBitsToUint(dist);item.w = 0;imageStore(listBuffer, int(newHead), item);
在调试代码时,发现一段计算vec3
长度的代码存在异常。具体而言,以下这行代码总是返回3.0f
,而非预期值:
float dist = in_VCPosition.length();
然而,将代码改成手动计算vec3
的长度后,便能得到正确结果:
float length(vec3 v) {return sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
}float dist = length(in_VCPosition);
目前尚不清楚导致该现象的具体原因,因此将此问题记录于此。若有见多识广的读者了解其中缘由,还望不吝赐教。