camera.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #include "camera.h"
  2. void cameraRecompute(struct Camera *cam) {
  3. cam->dir = aVec3fNormalize(cam->dir);
  4. const struct AVec3f
  5. z = aVec3fNeg(cam->dir),
  6. x = aVec3fNormalize(aVec3fCross(cam->up, z)),
  7. y = aVec3fCross(z, x);
  8. cam->axes = aMat3fv(x, y, z);
  9. cam->orientation = aMat3fTranspose(cam->axes);
  10. cam->view_projection = aMat4fMul(cam->projection,
  11. aMat4f3(cam->orientation, aVec3fMulMat(cam->orientation, aVec3fNeg(cam->pos))));
  12. }
  13. void cameraProjection(struct Camera *cam, float znear, float zfar, float horizfov, float aspect) {
  14. const float w = 2.f * znear * tanf(horizfov / 2.f), h = w / aspect;
  15. cam->z_far = zfar;
  16. cam->z_near = znear;
  17. //aAppDebugPrintf("%f %f %f %f -> %f %f", near, far, horizfov, aspect, w, h);
  18. cam->projection = aMat4fPerspective(znear, zfar, w, h);
  19. }
  20. void cameraLookAt(struct Camera *cam, struct AVec3f pos, struct AVec3f at, struct AVec3f up) {
  21. cam->pos = pos;
  22. cam->dir = aVec3fNormalize(aVec3fSub(at, pos));
  23. cam->up = up;
  24. cameraRecompute(cam);
  25. }
  26. void cameraMove(struct Camera *cam, struct AVec3f v) {
  27. cam->pos = aVec3fAdd(cam->pos, aVec3fMulf(cam->axes.X, v.x));
  28. cam->pos = aVec3fAdd(cam->pos, aVec3fMulf(cam->axes.Y, v.y));
  29. cam->pos = aVec3fAdd(cam->pos, aVec3fMulf(cam->axes.Z, v.z));
  30. }
  31. void cameraRotateYaw(struct Camera *cam, float yaw) {
  32. const struct AMat3f rot = aMat3fRotateAxis(cam->up, yaw);
  33. cam->dir = aVec3fMulMat(rot, cam->dir);
  34. }
  35. void cameraRotatePitch(struct Camera *cam, float pitch) {
  36. /* TODO limit pitch */
  37. const struct AMat3f rot = aMat3fRotateAxis(cam->axes.X, pitch);
  38. cam->dir = aVec3fMulMat(rot, cam->dir);
  39. }