CameraAdjust.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace EZXR.Glass.Core
  5. {
  6. public class CameraAdjust
  7. {
  8. private static CameraAdjust instance;
  9. public static CameraAdjust Instance
  10. {
  11. get
  12. {
  13. if (instance == null)
  14. {
  15. instance = new CameraAdjust();
  16. }
  17. return instance;
  18. }
  19. }
  20. /// <summary>
  21. /// 目标屏幕像素宽
  22. /// </summary>
  23. int screenWidth = 640;
  24. /// <summary>
  25. /// 目标屏幕像素高
  26. /// </summary>
  27. int screenHeight = 480;
  28. public Camera myCamera;
  29. public float left = -0.2F;
  30. public float right = 0.2F;
  31. public float top = 0.2F;
  32. public float bottom = -0.2F;
  33. public static float ax, ay, u0, v0, dx, dy;
  34. public float offset_left, offset_horizontal, offset_top, offset_vertical;
  35. public static float[] projector_KK = null;
  36. public void SetCameraProjectionMatrix(Camera camera, float[] k, int targetScreenWidth, int targetScreenHeight)
  37. {
  38. myCamera = camera;
  39. SetK(k);
  40. screenWidth = targetScreenWidth;
  41. screenHeight = targetScreenHeight;
  42. RefreshCameraMatrix();
  43. }
  44. void SetK(float[] k)
  45. {
  46. ax = k[0];
  47. ay = k[4];
  48. u0 = k[2];
  49. v0 = k[5];
  50. if (ax == 0 || ay == 0)
  51. {
  52. return;
  53. }
  54. dx = myCamera.nearClipPlane / ax;
  55. dy = myCamera.nearClipPlane / ay;
  56. }
  57. void RefreshCameraMatrix()
  58. {
  59. left = u0 * dx * (-1) + (offset_horizontal) + (offset_left);
  60. right = (screenWidth - u0) * dx + (offset_horizontal);
  61. top = dy * v0 + offset_vertical + offset_top;
  62. bottom = (screenHeight - v0) * dy * (-1) + offset_vertical;
  63. Matrix4x4 m = PerspectiveOffCenter(left, right, bottom, top, myCamera.nearClipPlane, myCamera.farClipPlane);
  64. myCamera.projectionMatrix = m;
  65. }
  66. Matrix4x4 PerspectiveOffCenter(float left, float right, float bottom, float top, float near, float far)
  67. {
  68. float x = 2.0F * near / (right - left);
  69. float y = 2.0F * near / (top - bottom);
  70. float a = (right + left) / (right - left);
  71. float b = (top + bottom) / (top - bottom);
  72. float c = -(far + near) / (far - near);
  73. float d = -(2.0F * far * near) / (far - near);
  74. float e = -1.0F;
  75. Matrix4x4 m = new Matrix4x4();
  76. m[0, 0] = x;
  77. m[0, 1] = 0;
  78. m[0, 2] = a;
  79. m[0, 3] = 0;
  80. m[1, 0] = 0;
  81. m[1, 1] = y;
  82. m[1, 2] = b;
  83. m[1, 3] = 0;
  84. m[2, 0] = 0;
  85. m[2, 1] = 0;
  86. m[2, 2] = c;
  87. m[2, 3] = d;
  88. m[3, 0] = 0;
  89. m[3, 1] = 0;
  90. m[3, 2] = e;
  91. m[3, 3] = 0;
  92. return m;
  93. }
  94. }
  95. }