反向进行矩阵乘法 [英] Doing a matrix multiplication in reverse

查看:220
本文介绍了反向进行矩阵乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关以下内容的后续操作:根据相机坐标计算世界坐标

我正在将2D向量与转换矩阵(OpenGL的模型视图矩阵)相乘,以从我的相机坐标中获得世界坐标.

我这样计算:

private Vector2f toWorldCoordinates(Vector2f position) {

    glPushMatrix();
    glScalef(this.zoom, this.zoom, 1);
    glTranslatef(this.position.x, this.position.y, 0);
    glRotatef(ROTATION, 0, 0, 1);

    ByteBuffer m = ByteBuffer.allocateDirect(64);
    m.order(ByteOrder.nativeOrder());
    glGetFloatv(GL_MODELVIEW_MATRIX, m);

    float x = (position.x * m.getFloat(0)) + (position.y * m.getFloat(4)) + m.getFloat(12);
    float y = (position.x * m.getFloat(16)) + (position.y * m.getFloat(20)) + m.getFloat(28);

    glPopMatrix();
    return new Vector2f(x, y);
}

现在,我也想反之亦然:计算世界上某个位置的相机坐标.我该如何冲销此计算?

解决方案

要为上述逆变换创建一个表示逆变换的矩阵,请逆变换应用,其中旋转和平移的值为负,而旋转和平移的值为负.缩放:

glRotatef(-ROTATION, 0, 0, 1);
glTranslatef(-this.position.x, -this.position.y, 0);
glScalef(1.0f / this.zoom, 1.0f / this.zoom, 1);

然后像以前一样乘以位置矢量.

另一种方法是计算逆矩阵,但是这种方法要简单得多.

Follow-up for: Calculating world coordinates from camera coordinates

I'm multiplying a 2D vector with a transformation matrix (OpenGL's model-view matrix) to get world coordinates from my camera coordinates.

I do this calculation like this:

private Vector2f toWorldCoordinates(Vector2f position) {

    glPushMatrix();
    glScalef(this.zoom, this.zoom, 1);
    glTranslatef(this.position.x, this.position.y, 0);
    glRotatef(ROTATION, 0, 0, 1);

    ByteBuffer m = ByteBuffer.allocateDirect(64);
    m.order(ByteOrder.nativeOrder());
    glGetFloatv(GL_MODELVIEW_MATRIX, m);

    float x = (position.x * m.getFloat(0)) + (position.y * m.getFloat(4)) + m.getFloat(12);
    float y = (position.x * m.getFloat(16)) + (position.y * m.getFloat(20)) + m.getFloat(28);

    glPopMatrix();
    return new Vector2f(x, y);
}

Now I also want to do this vice-versa: calculate the camera coordinates for a position in the world. How can I reverse this calculation?

解决方案

To create a matrix representing the inverse transform to the one above, apply the transforms in reverse, with negative quantities for the rotation and translation and an inverse quantity for the zoom:

glRotatef(-ROTATION, 0, 0, 1);
glTranslatef(-this.position.x, -this.position.y, 0);
glScalef(1.0f / this.zoom, 1.0f / this.zoom, 1);

Then multiply by the position vector as before.

The alternative is to compute the inverse matrix, but this way is much simpler.

这篇关于反向进行矩阵乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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