如何在光线追踪器中将光线从世界 space 反向旋转到对象 space

How to inverse rotate a ray in a ray tracer from world space to object space

我目前正在使用 C# 实现光线追踪器,我正在尝试将我的光线反向旋转到 3Dobject 的旋转以进行交叉检测,但我似乎在这里做错了很多事情...

我的代码:

static internal Ray TranformRay(Ray r, Vector3 objectLocation, Vector3 objectRotation, float objectScale)
{
         //reverse location tranformation
        Vector3 newOrigin = r.origin - objectLocation;

        //reverse rotation transformation
        objectRotation = -1* objectRotation;
        Matrix4x4 ReverseRotation = Matrix4x4.CreateFromYawPitchRoll(Computations.ToRadians(objectRotation.X), Computations.ToRadians(objectRotation.Y), Computations.ToRadians(objectRotation.Z));
        newOrigin = Vector3.Transform(newOrigin, ReverseRotation);
        Vector3 newDirection = Vector3.Normalize(Vector3.TransformNormal(r.direction, ReverseRotation));

        //reverse scale
        newDirection /= objectScale;

        return new Ray(newOrigin, newDirection);
    }

my Ray r 是我当前需要转换的光线。 我的世界中的 3D 对象具有位置、旋转、比例。

谁能告诉我我做错了什么?

我假设您想将光线从世界 space 转换为对象 space。然后你应该计算你的对象到世界的转换并调用 Matrix4x4.Invert 来产生逆变换。不是所有的变换都是可逆的,但正常的仿射变换应该没问题。

编辑: 您通常会通过调用 Matrix4x4 Create Scale/rotation/translation 方法并将变换相乘来生成对象到世界的变换。我还建议使用四元数代替欧拉角进行旋转。四元数应该可以更轻松地应用多个连续旋转。

假设您的光线是原点和方向,您将使用 Vector3.Transform 来变换原点并使用 Vector3.TransformNormal 来变换方向。后者不应用矩阵的翻译部分。

这假设您使用的是 System.Numerics 库,但大多数矢量库应该具有等效的功能。