matrix_4x4.cc 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * Copyright 2019 Google Inc. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "matrix_4x4.h"
  17. #include <algorithm>
  18. #include <cmath>
  19. #include <cstring>
  20. namespace cardboard {
  21. Matrix4x4 Matrix4x4::Identity()
  22. {
  23. Matrix4x4 ret;
  24. for (int j = 0; j < 4; ++j) {
  25. for (int i = 0; i < 4; ++i) {
  26. ret.m[j][i] = (i == j) ? 1 : 0;
  27. }
  28. }
  29. return ret;
  30. }
  31. Matrix4x4 Matrix4x4::Zeros()
  32. {
  33. Matrix4x4 ret;
  34. for (int j = 0; j < 4; ++j) {
  35. for (int i = 0; i < 4; ++i) {
  36. ret.m[j][i] = 0;
  37. }
  38. }
  39. return ret;
  40. }
  41. Matrix4x4 Matrix4x4::Translation(float x, float y, float z)
  42. {
  43. Matrix4x4 ret = Matrix4x4::Identity();
  44. ret.m[3][0] = x;
  45. ret.m[3][1] = y;
  46. ret.m[3][2] = z;
  47. return ret;
  48. }
  49. Matrix4x4 Matrix4x4::Perspective(const std::array<float, 4>& fov, float zNear, float zFar)
  50. {
  51. Matrix4x4 ret = Matrix4x4::Zeros();
  52. const float xLeft = -std::tan(fov[0] * M_PI / 180.0f) * zNear;
  53. const float xRight = std::tan(fov[1] * M_PI / 180.0f) * zNear;
  54. const float yBottom = -std::tan(fov[2] * M_PI / 180.0f) * zNear;
  55. const float yTop = std::tan(fov[3] * M_PI / 180.0f) * zNear;
  56. const float X = (2 * zNear) / (xRight - xLeft);
  57. const float Y = (2 * zNear) / (yTop - yBottom);
  58. const float A = (xRight + xLeft) / (xRight - xLeft);
  59. const float B = (yTop + yBottom) / (yTop - yBottom);
  60. const float C = (zNear + zFar) / (zNear - zFar);
  61. const float D = (2 * zNear * zFar) / (zNear - zFar);
  62. ret.m[0][0] = X;
  63. ret.m[2][0] = A;
  64. ret.m[1][1] = Y;
  65. ret.m[2][1] = B;
  66. ret.m[2][2] = C;
  67. ret.m[3][2] = D;
  68. ret.m[2][3] = -1;
  69. return ret;
  70. }
  71. void Matrix4x4::ToArray(float* array) const { std::memcpy(array, &m[0][0], 16 * sizeof(float)); }
  72. } // namespace cardboard