yhKim
yhKim

Reputation: 21

How to change pivot in OpenGL?

I've developed 3D application. I want to change pivot between model center and user position. When I toggle changing pivot option, 3D model is moved to some position. My partial source below. Please help me.

    glm::vec2 mouse_delta = mouse_move - mouse_click;
    key_yaw = rotate_sensitivity * mouse_delta.x; 
    key_pitch = rotate_sensitivity * mouse_delta.y; 
    UpdateRotateMatrix();

    if (rotate_mode == CCamera::ROT_CENTER)
        UpdateModelMatrix();        
    else if (rotate_mode == CCamera::ROT_CLICKED)
        UpdateModelMatrix(false);

////////////////////////////////////////////////////

void CCamera::UpdateModelMatrix(const bool& bCenter)
{
    glm::vec3 pivot(0.0f);
    if (bCenter)
        pivot = local_position; //50.0, 50.0, 50.0
    else
        pivot = click_position; //1000.0, 1000.0, 1000.0

    glm::mat4 rotate = glm::mat4(1.0f);
    rotate = glm::translate(glm::mat4(1.0f), pivot)*rotate_matrix;
    rotate = rotate * glm::translate(glm::mat4(1.0f), -pivot);

    model_matrix = translate_matrix * rotate;
}

void CCamera::UpdateRotateMatrix()
{
    glm::quat key_quat = glm::quat(glm::vec3(key_pitch, key_yaw, key_roll));
    key_pitch = key_yaw = key_roll = 0;

    camera_quat = key_quat * camera_quat;
    camera_quat = glm::normalize(camera_quat);
    rotate_matrix = glm::mat4_cast(camera_quat);
}

rotation of model center

rotation of some point

Upvotes: 2

Views: 1540

Answers (1)

Rabbid76
Rabbid76

Reputation: 211077

The order of you matrices is messed up.

I you want to rotate around a pivot, then you have to:

glm::mat4 trans_to_pivot   = glm::translate(glm::mat4(1.0f), -pivot);
glm::mat4 trans_from_pivot = glm::translate(glm::mat4(1.0f), pivot);

glm::mat4 rotate = trans_from_pivot * rotate_matrix * trans_to_pivot;

If you want to scale the model you have to do it first:

glm::mat4 rotate = rotate * scale_matrix;

Note in your example scale_matrix is in between trans_to_pivot and trans_from_pivot, so the first translation is scaled, but the the second translation is not scaled.
Of course pivot has to be a coordinate in scaled model space rather than model space.

Upvotes: 1

Related Questions