Francesco Bonizzi
Francesco Bonizzi

Reputation: 5302

How to convert a 3x2 matrix into 4x4 matrix?

I'm currently using a 3x2 matrix (called Transform), generated like this:

private void CalculateTransform()
{
    _positionToOriginOffset = _position - _origin;

    if (_positionToOriginOffset.X < 0.0f)
        _positionToOriginOffset.X = 0.0f;
    if (_positionToOriginOffset.Y <= _maxY)
        _positionToOriginOffset.Y = _maxY;
    if (_positionToOriginOffset.Y > 0.0f)
        _positionToOriginOffset.Y = 0.0f;

    Transform = SimpleMatrix3x2.Identity;

    if (_zoom != 1.0f || _rotation != 0.0f)
    {
        Transform =
                SimpleMatrix3x2.CreateTranslation(-Position) *
                SimpleMatrix3x2.CreateScale(_zoom) *
                SimpleMatrix3x2.CreateRotation(_rotation) *
                SimpleMatrix3x2.CreateTranslation(Position);
    }

    Transform *= SimpleMatrix3x2.CreateTranslation(-_positionToOriginOffset);
}

public static SimpleMatrix3x2 CreateTranslation(SimpleVector2 position)
{
    SimpleMatrix3x2 result;

    result.M11 = 1.0f;
    result.M12 = 0.0f;
    result.M21 = 0.0f;
    result.M22 = 1.0f;

    result.M31 = position.X;
    result.M32 = position.Y;

    return result;
}

How do I convert a 3x2 matrix into a 4x4?

public static Matrix ToMatrix4x4(SimpleMatrix3x2 matrix)
{
    return new Matrix(...); ?
}

Matrix class is from Microsoft.Xna.Framework and it is a 4x3 Matrix.

Upvotes: 1

Views: 819

Answers (1)

Antoine Boisier-Michaud
Antoine Boisier-Michaud

Reputation: 1675

Programmatically speaking, the XNA matrix class represents a 4x4 matrix. It has a constructor which takes 16 values (m11, m12, ..., m44), so you can simply pass your values to it.

Mathematically speaking, the last column of a 3d transform matrix should contain (0,0,0,1). The second one should have (0, 0, 1, 0), based on the fact that you are converting from a 2d transform matrix. Overall, it should look like this :

return new Matrix(m.11, m.12, 0, 0, 
                  m.21, m.22, 0, 0, 
                  0,    0,    1, 0, 
                  m.31, m.32, 0, 1);

Hope that helped!

Upvotes: 3

Related Questions