Sk3D.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Copyright 2018 Google Inc.
  3. *
  4. * Use of this source code is governed by a BSD-style license that can be
  5. * found in the LICENSE file.
  6. */
  7. #include "include/utils/Sk3D.h"
  8. static void set_col(SkMatrix44* m, int col, const SkPoint3& v) {
  9. m->set(0, col, v.fX);
  10. m->set(1, col, v.fY);
  11. m->set(2, col, v.fZ);
  12. }
  13. static SkPoint3 cross(const SkPoint3& a, const SkPoint3& b) {
  14. return {
  15. a.fY * b.fZ - a.fZ * b.fY,
  16. a.fZ * b.fX - a.fX * b.fZ,
  17. a.fX * b.fY - a.fY * b.fX,
  18. };
  19. }
  20. void Sk3LookAt(SkMatrix44* dst, const SkPoint3& eye, const SkPoint3& center, const SkPoint3& up) {
  21. SkPoint3 f = center - eye;
  22. f.normalize();
  23. SkPoint3 u = up;
  24. u.normalize();
  25. SkPoint3 s = cross(f, u);
  26. s.normalize();
  27. u = cross(s, f);
  28. dst->setIdentity();
  29. set_col(dst, 0, s);
  30. set_col(dst, 1, u);
  31. set_col(dst, 2, -f);
  32. set_col(dst, 3, eye);
  33. dst->invert(dst);
  34. }
  35. bool Sk3Perspective(SkMatrix44* dst, float near, float far, float angle) {
  36. SkASSERT(far > near);
  37. float denomInv = sk_ieee_float_divide(1, far - near);
  38. float halfAngle = angle * 0.5f;
  39. float cot = sk_float_cos(halfAngle) / sk_float_sin(halfAngle);
  40. dst->setIdentity();
  41. dst->set(0, 0, cot);
  42. dst->set(1, 1, cot);
  43. dst->set(2, 2, (far + near) * denomInv);
  44. dst->set(2, 3, 2 * far * near * denomInv);
  45. dst->set(3, 2, -1);
  46. return true;
  47. }
  48. void Sk3MapPts(SkPoint dst[], const SkMatrix44& m4, const SkPoint3 src[], int count) {
  49. for (int i = 0; i < count; ++i) {
  50. SkVector4 v = m4 * SkVector4{ src[i].fX, src[i].fY, src[i].fZ, 1 };
  51. // clip v;
  52. dst[i] = { v.fData[0] / v.fData[3], v.fData[1] / v.fData[3] };
  53. }
  54. }