Skip to content

Instantly share code, notes, and snippets.

@fjolnir
Created January 24, 2012 09:35
Show Gist options
  • Save fjolnir/1669264 to your computer and use it in GitHub Desktop.
Save fjolnir/1669264 to your computer and use it in GitHub Desktop.
- (vec4_t)mapToSphere:(vec2_t)aWindowCoord // http://www.tommyhinks.com/docs/shoemake92_arcball.pdf
{
// normalize window coordinates
vec4_t viewport;
glGetFloatv(GL_VIEWPORT, viewport.f);
vec3_t p = { 2.0*aWindowCoord.x/viewport.z - 1.0, 2.0*aWindowCoord.y/viewport.w - 1.0, 0 };
// Map to sphere
float mag = p.x*p.x + p.y*p.y;
if(mag > 1.0) {
float scale = 1.0 / sqrtf(mag);
p.x *= scale;
p.y *= scale;
p.z = 0.0;
} else
p.z = -sqrtf(1.0f - mag);
vec4_t out = { .xyz = p, .andW = 1.0f };
return out;
}
static vec4_t lastMouseLoc;
- (void)mouseDown:(NSEvent *)aEvent
{
lastMouseLoc = [self mapToSphere:vec2_create(aEvent.locationInWindow.x, aEvent.locationInWindow.y)];
}
- (void)mouseDragged:(NSEvent *)aEvent
{
vec4_t mouseLoc = [self mapToSphere:vec2_create(aEvent.locationInWindow.x, aEvent.locationInWindow.y)];
TCamera *cam = [TScene globalScene].camera;
quat_t rotation;
rotation.vec = vec3_cross(lastMouseLoc.xyz, mouseLoc.xyz);
rotation.scalar = vec3_dot(lastMouseLoc.xyz, mouseLoc.xyz);
rotation = quat_normalize(rotation);
cam.orientation = quat_multQuat(rotation, cam.orientation);
cam.position = quat_rotatePoint(rotation, cam.position);
[cam updateMatrix];
lastMouseLoc = mouseLoc;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment