从屏幕坐标计算光线方向矢量 [英] Calculate ray direction vector from screen coordanate

查看:303
本文介绍了从屏幕坐标计算光线方向矢量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种更好的方法(或者说,这是是最好的方式)将像素坐标从任意相机传输到相应的光线方向位置/方向。

I'm looking for a better way (or a note that this is the best way) to transfer a pixel coordinate to its corresponding ray direction from a arbitrary camera position/direction.

我当前的方法如下。我定义一个摄像机作为位置矢量,外观矢量和向上矢量,命名为。 (注意,观察向量是相机所面向的方向上的单位向量,NOT((position-lookat)是方向,XNA的Matrix.CreateLookAt中的标准)这三个向量可以唯一地定义相机位置。这里是实际的代码(好吧,不是真的,简单的抽象版本)(语言是HLSL)

My current method is as follows. I define a "camera" as a position vector, lookat vector, and up vector, named as such. (Note that the lookat vector is a unit vector in the direction the camera is facing, NOT where (position - lookat) is the direction, as is the standard in XNA's Matrix.CreateLookAt) These three vectors can uniquely define a camera position. Here's the actual code (well, not really the actual, a simplified abstracted version) (Language is HLSL)

float xPixelCoordShifted = (xPixelCoord / screenWidth * 2 - 1) * aspectRatio;
float yPixelCoordShifted = yPixelCoord / screenHeight * 2 - 1;
float3 right = cross(lookat, up);
float3 actualUp = cross(right, lookat);
float3 rightShift = mul(right, xPixelCoordShifted);
float3 upShift = mul(actualUp, yPixelCoordShifted);
return normalize(lookat + rightShift + upShift);

(返回值是光线的方向)

(the return value is the direction of the ray)

所以我要问的是,这是一个更好的方法来做到这一点,也许使用矩阵等。这个方法的问题是,如果你有太宽的视角,屏幕的边缘

So what I'm asking is this- What's a better way to do this, maybe using matrices, etc. The problem with this method is that if you have too wide a viewing angle, the edges of the screen get sort of "radially stretched".

推荐答案

您可以计算它( ray )in像素着色器,HLSL代码:

You can calculate it (ray) in pixel shader, HLSL code:

float4x4 WorldViewProjMatrix; // World*View*Proj
float4x4 WorldViewProjMatrixInv; // (World*View*Proj)^(-1)

void VS( float4 vPos : POSITION,
     out float4 oPos : POSITION,
     out float4 pos  : TEXCOORD0 )
{
    oPos = mul(vPos, WorldViewProjMatrix);
    pos = oPos;
}

float4 PS( float4 pos : TEXCOORD0 )
{
    float4 posWS = mul(pos, WorldViewProjMatrixInv);
    float3 ray = posWS.xyz / posWS.w;

    return float4(0, 0, 0, 1);
}

相机的位置和方向信息位于 View matrix(Matrix.CreateLookAt)。

The information about your camera's position and direction is in View matrix (Matrix.CreateLookAt).

这篇关于从屏幕坐标计算光线方向矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆