第 22 课:View Space, Deeper UnderStanding
我的解:这里我的问题在于,忘了写转置
本课需 HLSL 顶点 / 纹理对象,暂以代码复盘呈现。
我的解
cbuffer Transform : register(b0) {
float4x4 modelMatrix;
float4x4 projectionMatrix;
};
struct VSInput {
float3 position : Position;
};
struct VSOutput {
float4 position : SV_Position;
float3 wolrdPos : POSITION0;
};
#define CAMERA_POS float3(0.0, 2.0, 4.0)
#define CAMERA_ROTATE float3(-0.4, 0.0, 0.0)
float4x4 RotX(float a)
{
float s = sin(a);
float c = cos(a);
return float4x4(
1, 0, 0, 0,
0, c,-s, 0,
0, s, c, 0,
0, 0, 0, 1
);
}
float4x4 RotY(float a)
{
float s = sin(a);
float c = cos(a);
return float4x4(
c, 0, s, 0,
0, 1, 0, 0,
-s, 0, c, 0,
0, 0, 0, 1
);
}
float4x4 RotZ(float a)
{
float s = sin(a);
float c = cos(a);
return float4x4(
c,-s, 0, 0,
s, c, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
);
}
// Efficiently inverts a view matrix that
// contains only rotation and translation.
// Assumes the rotation part is orthonormal
// (i.e., no scaling or skewing), which is typical
// for camera view matrices in real-time rendering.
float4x4 InvertViewMatrix(float4x4 m) {
float3 right = m[0].xyz;
float3 up = m[1].xyz;
float3 forward = m[2].xyz;
float3 position = m[3].xyz;
float3x3 rotationInv = float3x3(
right.x, up.x, forward.x,
right.y, up.y, forward.y,
right.z, up.z, forward.z
);
float3 positionInv = -mul(rotationInv, position);
return float4x4(
float4(rotationInv[0], 0.0),
float4(rotationInv[1], 0.0),
float4(rotationInv[2], 0.0),
float4(positionInv, 1.0)
);
}
VSOutput main(VSInput input) {
VSOutput output;
float4 worldPos = mul(modelMatrix, float4(input.position, 1.0));
// setViewPosition
float4x4 M_trans = transpose(float4x4(
1,0,0,CAMERA_POS.x,
0,1,0,CAMERA_POS.y,
0,0,1,CAMERA_POS.z,
0,0,0,1
));
float4x4 M_rotate = transpose(mul(RotY(CAMERA_ROTATE.y),mul(RotX(CAMERA_ROTATE.x),RotZ(CAMERA_ROTATE.z))));
float4x4 M_view_movement = mul(M_trans, M_rotate);
float4x4 M_view = InvertViewMatrix(M_view_movement);
float4 viewPos = mul(M_view, worldPos);
output.position = mul(projectionMatrix, viewPos);
output.wolrdPos = worldPos.xyz;
return output;
}
复盘笔记
- 这里我的问题在于,忘了写转置