Skip to content

Get 3D coordinates of vertices of rotated and scaled cuboid with scale, center position and rotation on all axis

I have been wrecking my brain trying to figure out this problem I have. I have a cuboid, its rotation on all 3 axis in relation to the world from its center (it’s on 3D space), the cuboid’s center’s position and the scale of the cube in all axis (width, height and depth). I need to find the coordinates of all of the vertices of the cuboid.

While browsing the internet, I only found examples for the 2D cases, and couldn’t figure out how to advance to 3D space.

Can anyone help me please? I will use it in a game engine made with LWJGL (Light Weight Java Game Library).

Edit: (for @httpdigest):

public Vector3f[] getExtents(){

    Matrix4f m = new Matrix4f();

    m.translate(getPosition());
    m.rotate(getRotation().x, new Vector3f(1, 0, 0));
    m.rotate(getRotation().y, new Vector3f(0, 1, 0));
    m.rotate(getRotation().z, new Vector3f(0, 0, 1));
    m.scale(new Vector3f(getScaleX(), getScaleY(), getScaleZ()));
    Vector3f[] corners = new Vector3f[8];
    for (int i = 0; i < corners.length; i++) {
        int x = i % 2 * 2 - 1;
        int y = i / 2 % 2 * 2 - 1;
        int z = i / 4 % 2 * 2 - 1;
        Vector4f corner = Matrix4f.transform(m, new Vector4f(x, y, z, 1), null);
        corners[i] = new Vector3f(corner.x, corner.y, corner.z);
    }
    return corners;
}

This still isn’t accurate, can anyone spot the problem?

Edit: Solution: The angles needed to be in radians, thanks for the support!

Answer

If you are using LWJGL you can also use JOML, in which case the following is probably what you might want:

import org.joml.*;
public class CubePositions {
  public static void main(String[] args) {
    /* Cuboid center position */
    float px = 10, py = 0, pz = 0;
    /* Euler angles around x, y and z */
    float ax = 0, ay = 0, az = (float) java.lang.Math.PI / 2.0f;
    /* Scale factor for x, y und z */
    float sx = 1, sy = 3, sz = 1;
    /* Build transformation matrix */
    Matrix4f m = new Matrix4f()
        .translate(px, py, pz) // <- translate to position
        .rotateXYZ(ax, ay, az) // <- rotation about x, then y, then z
        .scale(sx, sy, sz);    // <- scale
    /* Compute cube corners and print them */
    Vector3f[] corners = new Vector3f[8];
    for (int i = 0; i < corners.length; i++) {
      int x = i % 2 * 2 - 1;
      int y = i / 2 % 2 * 2 - 1;
      int z = i / 4 % 2 * 2 - 1;
      corners[i] = m.transformPosition(x, y, z, new Vector3f());
      System.out.println(String.format(
          "Corner (%+d, %+d, %+d) = %s",
          x, y, z, corners[i]));
    }
  }
}

It computes a transformation matrix M = T * Rx * Ry * Rz * S given the center position, Euler rotations around x, then y and then z and the given scaling factors of the unit axes, and then transforms the positions of the unit cube corners by that matrix via P' = M * P.