NeHe OpenGL Lesson48 - ArcBall Rotation (Mouse Rotation)

lesson48_screenshot

This sample provides us an ArcBall module that we could use to rotate object along the screen with mouse. The underneath idea is mapping a 2d screen position into a 3d sphere coordinate. A rotation Quat  could be calculated out by two sphere coordinates (the start, end position). Then a rotation matrix created based on the quat.

This sample also provide some other useful technologies:

1) convert quat to a rotation matrix;

2) use OpenGL fucntion “glMultMatrixf(Transform.M);”to set up the model view matrix directly;

 

Mapping 2D Mouse Position into 3D Sphere Coordinate

At first we simply scale down the mouse coordinates from the range of [0...width), [0...height) to [-1...1], [1...-1] (Y flipped).

X  =  (MousePt.X / ((Width  - 1) / 2));
Y  = -(MousePt.Y / ((Height - 1) / 2));

Calculate the 3D Sphere coordinates:

复制代码
length      = (X * X) + (Y * Y);

//If the point is mapped outside of the sphere... (length > radius squared)
if (length > 1.0f)
{
    GLfloat norm;

    //Compute a normalizing factor (radius / sqrt(length))
    norm    = 1.0f / FuncSqrt(length);

    //Return the "normalized" vector, a point on the sphere
    NewVec->s.X = TempPt.s.X * norm;
    NewVec->s.Y = TempPt.s.Y * norm;
    NewVec->s.Z = 0.0f;
}
else    //Else it's on the inside
{
    //Return a vector to a point mapped inside the sphere sqrt(radius squared - length)
    NewVec->s.X = TempPt.s.X;
    NewVec->s.Y = TempPt.s.Y;
    NewVec->s.Z = FuncSqrt(1.0f - length);
}
复制代码

 

The full source code could be found here.

posted @   opencoder  阅读(568)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示