GrQuadPerEdgeAA.cpp 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147
  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 "src/gpu/ops/GrQuadPerEdgeAA.h"
  8. #include "include/private/SkNx.h"
  9. #include "src/gpu/GrVertexWriter.h"
  10. #include "src/gpu/SkGr.h"
  11. #include "src/gpu/glsl/GrGLSLColorSpaceXformHelper.h"
  12. #include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
  13. #include "src/gpu/glsl/GrGLSLGeometryProcessor.h"
  14. #include "src/gpu/glsl/GrGLSLPrimitiveProcessor.h"
  15. #include "src/gpu/glsl/GrGLSLVarying.h"
  16. #include "src/gpu/glsl/GrGLSLVertexGeoBuilder.h"
  17. #define AI SK_ALWAYS_INLINE
  18. namespace {
  19. // Helper data types since there is a lot of information that needs to be passed around to
  20. // avoid recalculation in the different procedures for tessellating an AA quad.
  21. using V4f = skvx::Vec<4, float>;
  22. using M4f = skvx::Vec<4, int32_t>;
  23. struct Vertices {
  24. // X, Y, and W coordinates in device space. If not perspective, w should be set to 1.f
  25. V4f fX, fY, fW;
  26. // U, V, and R coordinates representing local quad. Ignored depending on uvrCount (0, 1, 2).
  27. V4f fU, fV, fR;
  28. int fUVRCount;
  29. };
  30. struct QuadMetadata {
  31. // Normalized edge vectors of the device space quad, ordered L, B, T, R (i.e. nextCCW(x) - x).
  32. V4f fDX, fDY;
  33. // 1 / edge length of the device space quad
  34. V4f fInvLengths;
  35. // Edge mask (set to all 1s if aa flags is kAll), otherwise 1.f if edge was AA, 0.f if non-AA.
  36. V4f fMask;
  37. };
  38. struct Edges {
  39. // a * x + b * y + c = 0; positive distance is inside the quad; ordered LBTR.
  40. V4f fA, fB, fC;
  41. // Whether or not the edge normals had to be flipped to preserve positive distance on the inside
  42. bool fFlipped;
  43. };
  44. static constexpr float kTolerance = 1e-2f;
  45. // True/false bit masks for initializing an M4f
  46. static constexpr int32_t kTrue = ~0;
  47. static constexpr int32_t kFalse = 0;
  48. static AI V4f fma(const V4f& f, const V4f& m, const V4f& a) {
  49. return mad(f, m, a);
  50. }
  51. // These rotate the points/edge values either clockwise or counterclockwise assuming tri strip
  52. // order.
  53. static AI V4f nextCW(const V4f& v) {
  54. return skvx::shuffle<2, 0, 3, 1>(v);
  55. }
  56. static AI V4f nextCCW(const V4f& v) {
  57. return skvx::shuffle<1, 3, 0, 2>(v);
  58. }
  59. // Replaces zero-length 'bad' edge vectors with the reversed opposite edge vector.
  60. // e3 may be null if only 2D edges need to be corrected for.
  61. static AI void correct_bad_edges(const M4f& bad, V4f* e1, V4f* e2, V4f* e3) {
  62. if (any(bad)) {
  63. // Want opposite edges, L B T R -> R T B L but with flipped sign to preserve winding
  64. *e1 = if_then_else(bad, -skvx::shuffle<3, 2, 1, 0>(*e1), *e1);
  65. *e2 = if_then_else(bad, -skvx::shuffle<3, 2, 1, 0>(*e2), *e2);
  66. if (e3) {
  67. *e3 = if_then_else(bad, -skvx::shuffle<3, 2, 1, 0>(*e3), *e3);
  68. }
  69. }
  70. }
  71. // Replace 'bad' coordinates by rotating CCW to get the next point. c3 may be null for 2D points.
  72. static AI void correct_bad_coords(const M4f& bad, V4f* c1, V4f* c2, V4f* c3) {
  73. if (any(bad)) {
  74. *c1 = if_then_else(bad, nextCCW(*c1), *c1);
  75. *c2 = if_then_else(bad, nextCCW(*c2), *c2);
  76. if (c3) {
  77. *c3 = if_then_else(bad, nextCCW(*c3), *c3);
  78. }
  79. }
  80. }
  81. static AI QuadMetadata get_metadata(const Vertices& vertices, GrQuadAAFlags aaFlags) {
  82. V4f dx = nextCCW(vertices.fX) - vertices.fX;
  83. V4f dy = nextCCW(vertices.fY) - vertices.fY;
  84. V4f invLengths = rsqrt(fma(dx, dx, dy * dy));
  85. V4f mask = aaFlags == GrQuadAAFlags::kAll ? V4f(1.f) :
  86. V4f{(GrQuadAAFlags::kLeft & aaFlags) ? 1.f : 0.f,
  87. (GrQuadAAFlags::kBottom & aaFlags) ? 1.f : 0.f,
  88. (GrQuadAAFlags::kTop & aaFlags) ? 1.f : 0.f,
  89. (GrQuadAAFlags::kRight & aaFlags) ? 1.f : 0.f};
  90. return { dx * invLengths, dy * invLengths, invLengths, mask };
  91. }
  92. static AI Edges get_edge_equations(const QuadMetadata& metadata, const Vertices& vertices) {
  93. V4f dx = metadata.fDX;
  94. V4f dy = metadata.fDY;
  95. // Correct for bad edges by copying adjacent edge information into the bad component
  96. correct_bad_edges(metadata.fInvLengths >= 1.f / kTolerance, &dx, &dy, nullptr);
  97. V4f c = fma(dx, vertices.fY, -dy * vertices.fX);
  98. // Make sure normals point into the shape
  99. V4f test = fma(dy, nextCW(vertices.fX), fma(-dx, nextCW(vertices.fY), c));
  100. if (any(test < -kTolerance)) {
  101. return {-dy, dx, -c, true};
  102. } else {
  103. return {dy, -dx, c, false};
  104. }
  105. }
  106. // Sets 'outset' to the magnitude of outset/inset to adjust each corner of a quad given the
  107. // edge angles and lengths. If the quad is too small, has empty edges, or too sharp of angles,
  108. // false is returned and the degenerate slow-path should be used.
  109. static bool get_optimized_outset(const QuadMetadata& metadata, bool rectilinear, V4f* outset) {
  110. if (rectilinear) {
  111. *outset = 0.5f;
  112. // Stay in the fast path as long as all edges are at least a pixel long (so 1/len <= 1)
  113. return all(metadata.fInvLengths <= 1.f);
  114. }
  115. if (any(metadata.fInvLengths >= 1.f / kTolerance)) {
  116. // Have an empty edge from a degenerate quad, so there's no hope
  117. return false;
  118. }
  119. // The distance the point needs to move is 1/2sin(theta), where theta is the angle between the
  120. // two edges at that point. cos(theta) is equal to dot(dxy, nextCW(dxy))
  121. V4f cosTheta = fma(metadata.fDX, nextCW(metadata.fDX), metadata.fDY * nextCW(metadata.fDY));
  122. // If the angle is too shallow between edges, go through the degenerate path, otherwise adding
  123. // and subtracting very large vectors in almost opposite directions leads to float errors
  124. if (any(abs(cosTheta) >= 0.9f)) {
  125. return false;
  126. }
  127. *outset = 0.5f * rsqrt(1.f - cosTheta * cosTheta); // 1/2sin(theta)
  128. // When outsetting or insetting, the current edge's AA adds to the length:
  129. // cos(pi - theta)/2sin(theta) + cos(pi-ccw(theta))/2sin(ccw(theta))
  130. // Moving an adjacent edge updates the length by 1/2sin(theta|ccw(theta))
  131. V4f halfTanTheta = -cosTheta * (*outset); // cos(pi - theta) = -cos(theta)
  132. V4f edgeAdjust = metadata.fMask * (halfTanTheta + nextCCW(halfTanTheta)) +
  133. nextCCW(metadata.fMask) * nextCCW(*outset) +
  134. nextCW(metadata.fMask) * (*outset);
  135. // If either outsetting (plus edgeAdjust) or insetting (minus edgeAdjust) make edgeLen negative
  136. // then use the slow path
  137. V4f threshold = 0.1f - (1.f / metadata.fInvLengths);
  138. return all(edgeAdjust > threshold) && all(edgeAdjust < -threshold);
  139. }
  140. // Ignores the quad's fW, use outset_projected_vertices if it's known to need 3D.
  141. static AI void outset_vertices(const V4f& outset, const QuadMetadata& metadata, Vertices* quad) {
  142. // The mask is rotated compared to the outsets and edge vectors, since if the edge is "on"
  143. // both its points need to be moved along their other edge vectors.
  144. auto maskedOutset = -outset * nextCW(metadata.fMask);
  145. auto maskedOutsetCW = outset * metadata.fMask;
  146. // x = x + outset * mask * nextCW(xdiff) - outset * nextCW(mask) * xdiff
  147. quad->fX += fma(maskedOutsetCW, nextCW(metadata.fDX), maskedOutset * metadata.fDX);
  148. quad->fY += fma(maskedOutsetCW, nextCW(metadata.fDY), maskedOutset * metadata.fDY);
  149. if (quad->fUVRCount > 0) {
  150. // We want to extend the texture coords by the same proportion as the positions.
  151. maskedOutset *= metadata.fInvLengths;
  152. maskedOutsetCW *= nextCW(metadata.fInvLengths);
  153. V4f du = nextCCW(quad->fU) - quad->fU;
  154. V4f dv = nextCCW(quad->fV) - quad->fV;
  155. quad->fU += fma(maskedOutsetCW, nextCW(du), maskedOutset * du);
  156. quad->fV += fma(maskedOutsetCW, nextCW(dv), maskedOutset * dv);
  157. if (quad->fUVRCount == 3) {
  158. V4f dr = nextCCW(quad->fR) - quad->fR;
  159. quad->fR += fma(maskedOutsetCW, nextCW(dr), maskedOutset * dr);
  160. }
  161. }
  162. }
  163. // Updates (x,y,w) to be at (x2d,y2d) once projected. Updates (u,v,r) to match if provided.
  164. // Gracefully handles 2D content if *w holds all 1s.
  165. static void outset_projected_vertices(const V4f& x2d, const V4f& y2d,
  166. GrQuadAAFlags aaFlags, Vertices* quad) {
  167. // Left to right, in device space, for each point
  168. V4f e1x = skvx::shuffle<2, 3, 2, 3>(quad->fX) - skvx::shuffle<0, 1, 0, 1>(quad->fX);
  169. V4f e1y = skvx::shuffle<2, 3, 2, 3>(quad->fY) - skvx::shuffle<0, 1, 0, 1>(quad->fY);
  170. V4f e1w = skvx::shuffle<2, 3, 2, 3>(quad->fW) - skvx::shuffle<0, 1, 0, 1>(quad->fW);
  171. correct_bad_edges(fma(e1x, e1x, e1y * e1y) < kTolerance * kTolerance, &e1x, &e1y, &e1w);
  172. // // Top to bottom, in device space, for each point
  173. V4f e2x = skvx::shuffle<1, 1, 3, 3>(quad->fX) - skvx::shuffle<0, 0, 2, 2>(quad->fX);
  174. V4f e2y = skvx::shuffle<1, 1, 3, 3>(quad->fY) - skvx::shuffle<0, 0, 2, 2>(quad->fY);
  175. V4f e2w = skvx::shuffle<1, 1, 3, 3>(quad->fW) - skvx::shuffle<0, 0, 2, 2>(quad->fW);
  176. correct_bad_edges(fma(e2x, e2x, e2y * e2y) < kTolerance * kTolerance, &e2x, &e2y, &e2w);
  177. // Can only move along e1 and e2 to reach the new 2D point, so we have
  178. // x2d = (x + a*e1x + b*e2x) / (w + a*e1w + b*e2w) and
  179. // y2d = (y + a*e1y + b*e2y) / (w + a*e1w + b*e2w) for some a, b
  180. // This can be rewritten to a*c1x + b*c2x + c3x = 0; a * c1y + b*c2y + c3y = 0, where
  181. // the cNx and cNy coefficients are:
  182. V4f c1x = e1w * x2d - e1x;
  183. V4f c1y = e1w * y2d - e1y;
  184. V4f c2x = e2w * x2d - e2x;
  185. V4f c2y = e2w * y2d - e2y;
  186. V4f c3x = quad->fW * x2d - quad->fX;
  187. V4f c3y = quad->fW * y2d - quad->fY;
  188. // Solve for a and b
  189. V4f a, b, denom;
  190. if (aaFlags == GrQuadAAFlags::kAll) {
  191. // When every edge is outset/inset, each corner can use both edge vectors
  192. denom = c1x * c2y - c2x * c1y;
  193. a = (c2x * c3y - c3x * c2y) / denom;
  194. b = (c3x * c1y - c1x * c3y) / denom;
  195. } else {
  196. // Force a or b to be 0 if that edge cannot be used due to non-AA
  197. M4f aMask = M4f{(aaFlags & GrQuadAAFlags::kLeft) ? kTrue : kFalse,
  198. (aaFlags & GrQuadAAFlags::kLeft) ? kTrue : kFalse,
  199. (aaFlags & GrQuadAAFlags::kRight) ? kTrue : kFalse,
  200. (aaFlags & GrQuadAAFlags::kRight) ? kTrue : kFalse};
  201. M4f bMask = M4f{(aaFlags & GrQuadAAFlags::kTop) ? kTrue : kFalse,
  202. (aaFlags & GrQuadAAFlags::kBottom) ? kTrue : kFalse,
  203. (aaFlags & GrQuadAAFlags::kTop) ? kTrue : kFalse,
  204. (aaFlags & GrQuadAAFlags::kBottom) ? kTrue : kFalse};
  205. // When aMask[i]&bMask[i], then a[i], b[i], denom[i] match the kAll case.
  206. // When aMask[i]&!bMask[i], then b[i] = 0, a[i] = -c3x/c1x or -c3y/c1y, using better denom
  207. // When !aMask[i]&bMask[i], then a[i] = 0, b[i] = -c3x/c2x or -c3y/c2y, ""
  208. // When !aMask[i]&!bMask[i], then both a[i] = 0 and b[i] = 0
  209. M4f useC1x = abs(c1x) > abs(c1y);
  210. M4f useC2x = abs(c2x) > abs(c2y);
  211. denom = if_then_else(aMask,
  212. if_then_else(bMask,
  213. c1x * c2y - c2x * c1y, /* A & B */
  214. if_then_else(useC1x, c1x, c1y)), /* A & !B */
  215. if_then_else(bMask,
  216. if_then_else(useC2x, c2x, c2y), /* !A & B */
  217. V4f(1.f))); /* !A & !B */
  218. a = if_then_else(aMask,
  219. if_then_else(bMask,
  220. c2x * c3y - c3x * c2y, /* A & B */
  221. if_then_else(useC1x, -c3x, -c3y)), /* A & !B */
  222. V4f(0.f)) / denom; /* !A */
  223. b = if_then_else(bMask,
  224. if_then_else(aMask,
  225. c3x * c1y - c1x * c3y, /* A & B */
  226. if_then_else(useC2x, -c3x, -c3y)), /* !A & B */
  227. V4f(0.f)) / denom; /* !B */
  228. }
  229. V4f newW = quad->fW + a * e1w + b * e2w;
  230. // If newW < 0, scale a and b such that the point reaches the infinity plane instead of crossing
  231. // This breaks orthogonality of inset/outsets, but GPUs don't handle negative Ws well so this
  232. // is far less visually disturbing (likely not noticeable since it's at extreme perspective).
  233. // The alternative correction (multiply xyw by -1) has the disadvantage of changing how local
  234. // coordinates would be interpolated.
  235. static const float kMinW = 1e-6f;
  236. if (any(newW < 0.f)) {
  237. V4f scale = if_then_else(newW < kMinW, (kMinW - quad->fW) / (newW - quad->fW), V4f(1.f));
  238. a *= scale;
  239. b *= scale;
  240. }
  241. quad->fX += a * e1x + b * e2x;
  242. quad->fY += a * e1y + b * e2y;
  243. quad->fW += a * e1w + b * e2w;
  244. correct_bad_coords(abs(denom) < kTolerance, &quad->fX, &quad->fY, &quad->fW);
  245. if (quad->fUVRCount > 0) {
  246. // Calculate R here so it can be corrected with U and V in case it's needed later
  247. V4f e1u = skvx::shuffle<2, 3, 2, 3>(quad->fU) - skvx::shuffle<0, 1, 0, 1>(quad->fU);
  248. V4f e1v = skvx::shuffle<2, 3, 2, 3>(quad->fV) - skvx::shuffle<0, 1, 0, 1>(quad->fV);
  249. V4f e1r = skvx::shuffle<2, 3, 2, 3>(quad->fR) - skvx::shuffle<0, 1, 0, 1>(quad->fR);
  250. correct_bad_edges(fma(e1u, e1u, e1v * e1v) < kTolerance * kTolerance, &e1u, &e1v, &e1r);
  251. V4f e2u = skvx::shuffle<1, 1, 3, 3>(quad->fU) - skvx::shuffle<0, 0, 2, 2>(quad->fU);
  252. V4f e2v = skvx::shuffle<1, 1, 3, 3>(quad->fV) - skvx::shuffle<0, 0, 2, 2>(quad->fV);
  253. V4f e2r = skvx::shuffle<1, 1, 3, 3>(quad->fR) - skvx::shuffle<0, 0, 2, 2>(quad->fR);
  254. correct_bad_edges(fma(e2u, e2u, e2v * e2v) < kTolerance * kTolerance, &e2u, &e2v, &e2r);
  255. quad->fU += a * e1u + b * e2u;
  256. quad->fV += a * e1v + b * e2v;
  257. if (quad->fUVRCount == 3) {
  258. quad->fR += a * e1r + b * e2r;
  259. correct_bad_coords(abs(denom) < kTolerance, &quad->fU, &quad->fV, &quad->fR);
  260. } else {
  261. correct_bad_coords(abs(denom) < kTolerance, &quad->fU, &quad->fV, nullptr);
  262. }
  263. }
  264. }
  265. // Calculate area of intersection between quad (xs, ys) and a pixel at 'pixelCenter'.
  266. // a, b, c are edge equations of the quad, flipped is true if the line equations had their normals
  267. // reversed to correct for matrix transforms.
  268. static float get_exact_coverage(const SkPoint& pixelCenter, const Vertices& quad,
  269. const Edges& edges) {
  270. // Ordering of vertices given default tri-strip that produces CCW points
  271. static const int kCCW[] = {0, 1, 3, 2};
  272. // Ordering of vertices given inverted tri-strip that produces CCW
  273. static const int kFlippedCCW[] = {0, 2, 3, 1};
  274. // Edge boundaries of the pixel
  275. float left = pixelCenter.fX - 0.5f;
  276. float right = pixelCenter.fX + 0.5f;
  277. float top = pixelCenter.fY - 0.5f;
  278. float bot = pixelCenter.fY + 0.5f;
  279. // Whether or not the 4 corners of the pixel are inside the quad geometry. Variable names are
  280. // intentional to work easily with the helper macros.
  281. bool topleftInside = all((edges.fA * left + edges.fB * top + edges.fC) >= 0.f);
  282. bool botleftInside = all((edges.fA * left + edges.fB * bot + edges.fC) >= 0.f);
  283. bool botrightInside = all((edges.fA * right + edges.fB * bot + edges.fC) >= 0.f);
  284. bool toprightInside = all((edges.fA * right + edges.fB * top + edges.fC) >= 0.f);
  285. if (topleftInside && botleftInside && botrightInside && toprightInside) {
  286. // Quad fully contains the pixel, so we know the area will be 1.f
  287. return 1.f;
  288. }
  289. // Track whether or not the quad vertices in (xs, ys) are on the proper sides of l, t, r, and b
  290. M4f leftValid = quad.fX >= left;
  291. M4f rightValid = quad.fX <= right;
  292. M4f topValid = quad.fY >= top;
  293. M4f botValid = quad.fY <= bot;
  294. // Intercepts of quad lines with the 4 pixel edges
  295. V4f leftCross = -(edges.fC + edges.fA * left) / edges.fB;
  296. V4f rightCross = -(edges.fC + edges.fA * right) / edges.fB;
  297. V4f topCross = -(edges.fC + edges.fB * top) / edges.fA;
  298. V4f botCross = -(edges.fC + edges.fB * bot) / edges.fA;
  299. // State for implicitly tracking the intersection boundary and area
  300. SkPoint firstPoint = {0.f, 0.f};
  301. SkPoint lastPoint = {0.f, 0.f};
  302. bool intersected = false;
  303. float area = 0.f;
  304. // Adds a point to the intersection hull, remembering first point (for closing) and the
  305. // current point, and updates the running area total.
  306. // See http://mathworld.wolfram.com/PolygonArea.html
  307. auto accumulate = [&](const SkPoint& p) {
  308. if (intersected) {
  309. float da = lastPoint.fX * p.fY - p.fX * lastPoint.fY;
  310. area += da;
  311. } else {
  312. firstPoint = p;
  313. intersected = true;
  314. }
  315. lastPoint = p;
  316. };
  317. // Used during iteration over the quad points to check if edge intersections are valid and
  318. // should be accumulated.
  319. #define ADD_EDGE_CROSSING_X(SIDE) \
  320. do { \
  321. if (SIDE##Cross[ei] >= top && SIDE##Cross[ei] <= bot) { \
  322. accumulate({SIDE, SIDE##Cross[ei]}); \
  323. addedIntersection = true; \
  324. } \
  325. } while(false)
  326. #define ADD_EDGE_CROSSING_Y(SIDE) \
  327. do { \
  328. if (SIDE##Cross[ei] >= left && SIDE##Cross[ei] <= right) { \
  329. accumulate({SIDE##Cross[ei], SIDE}); \
  330. addedIntersection = true; \
  331. } \
  332. } while(false)
  333. #define TEST_EDGES(SIDE, AXIS, I, NI) \
  334. do { \
  335. if (!SIDE##Valid[I] && SIDE##Valid[NI]) { \
  336. ADD_EDGE_CROSSING_##AXIS(SIDE); \
  337. crossedEdges = true; \
  338. } \
  339. } while(false)
  340. // Used during iteration over the quad points to check if a pixel corner should be included
  341. // in the intersection boundary
  342. #define ADD_CORNER(CHECK, SIDE_LR, SIDE_TB) \
  343. if (!CHECK##Valid[i] || !CHECK##Valid[ni]) { \
  344. if (SIDE_TB##SIDE_LR##Inside) { \
  345. accumulate({SIDE_LR, SIDE_TB}); \
  346. } \
  347. }
  348. #define TEST_CORNER_X(SIDE, I, NI) \
  349. do { \
  350. if (!SIDE##Valid[I] && SIDE##Valid[NI]) { \
  351. ADD_CORNER(top, SIDE, top) else ADD_CORNER(bot, SIDE, bot) \
  352. } \
  353. } while(false)
  354. #define TEST_CORNER_Y(SIDE, I, NI) \
  355. do { \
  356. if (!SIDE##Valid[I] && SIDE##Valid[NI]) { \
  357. ADD_CORNER(left, left, SIDE) else ADD_CORNER(right, right, SIDE) \
  358. } \
  359. } while(false)
  360. // Iterate over the 4 points of the quad, adding valid intersections with the pixel edges
  361. // or adding interior pixel corners as it goes. This automatically keeps all accumulated points
  362. // in CCW ordering so the area can be calculated on the fly and there's no need to store the
  363. // list of hull points. This is somewhat inspired by the Sutherland-Hodgman algorithm but since
  364. // there are only 4 points in each source polygon, there is no point list maintenance.
  365. for (int j = 0; j < 4; ++j) {
  366. // Current vertex
  367. int i = edges.fFlipped ? kFlippedCCW[j] : kCCW[j];
  368. // Moving to this vertex
  369. int ni = edges.fFlipped ? kFlippedCCW[(j + 1) % 4] : kCCW[(j + 1) % 4];
  370. // Index in edge vectors corresponding to move from i to ni
  371. int ei = edges.fFlipped ? ni : i;
  372. bool crossedEdges = false;
  373. bool addedIntersection = false;
  374. // First check if there are any outside -> inside edge crossings. There can be 0, 1, or 2.
  375. // 2 can occur if one crossing is still outside the pixel, or if they both go through
  376. // the corner (in which case a duplicate point is added, but that doesn't change area).
  377. // Outside to inside crossing
  378. TEST_EDGES(left, X, i, ni);
  379. TEST_EDGES(right, X, i, ni);
  380. TEST_EDGES(top, Y, i, ni);
  381. TEST_EDGES(bot, Y, i, ni);
  382. // Inside to outside crossing (swapping ni and i in the boolean test)
  383. TEST_EDGES(left, X, ni, i);
  384. TEST_EDGES(right, X, ni, i);
  385. TEST_EDGES(top, Y, ni, i);
  386. TEST_EDGES(bot, Y, ni, i);
  387. // If we crossed edges but didn't add any intersections, check the corners of the pixel.
  388. // If the pixel corners are inside the quad, include them in the boundary.
  389. if (crossedEdges && !addedIntersection) {
  390. // This can lead to repeated points, but those just accumulate zero area
  391. TEST_CORNER_X(left, i, ni);
  392. TEST_CORNER_X(right, i, ni);
  393. TEST_CORNER_Y(top, i, ni);
  394. TEST_CORNER_Y(bot, i, ni);
  395. TEST_CORNER_X(left, ni, i);
  396. TEST_CORNER_X(right, ni, i);
  397. TEST_CORNER_Y(top, ni, i);
  398. TEST_CORNER_Y(bot, ni, i);
  399. }
  400. // Lastly, if the next point is completely inside the pixel it gets included in the boundary
  401. if (leftValid[ni] && rightValid[ni] && topValid[ni] && botValid[ni]) {
  402. accumulate({quad.fX[ni], quad.fY[ni]});
  403. }
  404. }
  405. #undef TEST_CORNER_Y
  406. #undef TEST_CORNER_X
  407. #undef ADD_CORNER
  408. #undef TEST_EDGES
  409. #undef ADD_EDGE_CROSSING_Y
  410. #undef ADD_EDGE_CROSSING_X
  411. // After all points have been considered, close the boundary to get final area. If we never
  412. // added any points, it means the quad didn't intersect the pixel rectangle.
  413. if (intersected) {
  414. // Final equation for area of convex polygon is to multiply by -1/2 (minus since the points
  415. // were in CCW order).
  416. accumulate(firstPoint);
  417. return -0.5f * area;
  418. } else {
  419. return 0.f;
  420. }
  421. }
  422. // Outsets or insets xs/ys in place. To be used when the interior is very small, edges are near
  423. // parallel, or edges are very short/zero-length. Returns coverage for each vertex.
  424. // Requires (dx, dy) to already be fixed for empty edges.
  425. static V4f compute_degenerate_quad(GrQuadAAFlags aaFlags, const V4f& mask, const Edges& edges,
  426. bool outset, Vertices* quad) {
  427. // Move the edge 1/2 pixel in or out depending on 'outset'.
  428. V4f oc = edges.fC + mask * (outset ? 0.5f : -0.5f);
  429. // There are 6 points that we care about to determine the final shape of the polygon, which
  430. // are the intersections between (e0,e2), (e1,e0), (e2,e3), (e3,e1) (corresponding to the
  431. // 4 corners), and (e1, e2), (e0, e3) (representing the intersections of opposite edges).
  432. V4f denom = edges.fA * nextCW(edges.fB) - edges.fB * nextCW(edges.fA);
  433. V4f px = (edges.fB * nextCW(oc) - oc * nextCW(edges.fB)) / denom;
  434. V4f py = (oc * nextCW(edges.fA) - edges.fA * nextCW(oc)) / denom;
  435. correct_bad_coords(abs(denom) < kTolerance, &px, &py, nullptr);
  436. // Calculate the signed distances from these 4 corners to the other two edges that did not
  437. // define the intersection. So p(0) is compared to e3,e1, p(1) to e3,e2 , p(2) to e0,e1, and
  438. // p(3) to e0,e2
  439. V4f dists1 = px * skvx::shuffle<3, 3, 0, 0>(edges.fA) +
  440. py * skvx::shuffle<3, 3, 0, 0>(edges.fB) +
  441. skvx::shuffle<3, 3, 0, 0>(oc);
  442. V4f dists2 = px * skvx::shuffle<1, 2, 1, 2>(edges.fA) +
  443. py * skvx::shuffle<1, 2, 1, 2>(edges.fB) +
  444. skvx::shuffle<1, 2, 1, 2>(oc);
  445. // If all the distances are >= 0, the 4 corners form a valid quadrilateral, so use them as
  446. // the 4 points. If any point is on the wrong side of both edges, the interior has collapsed
  447. // and we need to use a central point to represent it. If all four points are only on the
  448. // wrong side of 1 edge, one edge has crossed over another and we use a line to represent it.
  449. // Otherwise, use a triangle that replaces the bad points with the intersections of
  450. // (e1, e2) or (e0, e3) as needed.
  451. M4f d1v0 = dists1 < kTolerance;
  452. M4f d2v0 = dists2 < kTolerance;
  453. M4f d1And2 = d1v0 & d2v0;
  454. M4f d1Or2 = d1v0 | d2v0;
  455. V4f coverage;
  456. if (!any(d1Or2)) {
  457. // Every dists1 and dists2 >= kTolerance so it's not degenerate, use all 4 corners as-is
  458. // and use full coverage
  459. coverage = 1.f;
  460. } else if (any(d1And2)) {
  461. // A point failed against two edges, so reduce the shape to a single point, which we take as
  462. // the center of the original quad to ensure it is contained in the intended geometry. Since
  463. // it has collapsed, we know the shape cannot cover a pixel so update the coverage.
  464. SkPoint center = {0.25f * (quad->fX[0] + quad->fX[1] + quad->fX[2] + quad->fX[3]),
  465. 0.25f * (quad->fY[0] + quad->fY[1] + quad->fY[2] + quad->fY[3])};
  466. coverage = get_exact_coverage(center, *quad, edges);
  467. px = center.fX;
  468. py = center.fY;
  469. } else if (all(d1Or2)) {
  470. // Degenerates to a line. Compare p[2] and p[3] to edge 0. If they are on the wrong side,
  471. // that means edge 0 and 3 crossed, and otherwise edge 1 and 2 crossed.
  472. if (dists1[2] < kTolerance && dists1[3] < kTolerance) {
  473. // Edges 0 and 3 have crossed over, so make the line from average of (p0,p2) and (p1,p3)
  474. px = 0.5f * (skvx::shuffle<0, 1, 0, 1>(px) + skvx::shuffle<2, 3, 2, 3>(px));
  475. py = 0.5f * (skvx::shuffle<0, 1, 0, 1>(py) + skvx::shuffle<2, 3, 2, 3>(py));
  476. float mc02 = get_exact_coverage({px[0], py[0]}, *quad, edges);
  477. float mc13 = get_exact_coverage({px[1], py[1]}, *quad, edges);
  478. coverage = V4f{mc02, mc13, mc02, mc13};
  479. } else {
  480. // Edges 1 and 2 have crossed over, so make the line from average of (p0,p1) and (p2,p3)
  481. px = 0.5f * (skvx::shuffle<0, 0, 2, 2>(px) + skvx::shuffle<1, 1, 3, 3>(px));
  482. py = 0.5f * (skvx::shuffle<0, 0, 2, 2>(py) + skvx::shuffle<1, 1, 3, 3>(py));
  483. float mc01 = get_exact_coverage({px[0], py[0]}, *quad, edges);
  484. float mc23 = get_exact_coverage({px[2], py[2]}, *quad, edges);
  485. coverage = V4f{mc01, mc01, mc23, mc23};
  486. }
  487. } else {
  488. // This turns into a triangle. Replace corners as needed with the intersections between
  489. // (e0,e3) and (e1,e2), which must now be calculated
  490. using V2f = skvx::Vec<2, float>;
  491. V2f eDenom = skvx::shuffle<0, 1>(edges.fA) * skvx::shuffle<3, 2>(edges.fB) -
  492. skvx::shuffle<0, 1>(edges.fB) * skvx::shuffle<3, 2>(edges.fA);
  493. V2f ex = (skvx::shuffle<0, 1>(edges.fB) * skvx::shuffle<3, 2>(oc) -
  494. skvx::shuffle<0, 1>(oc) * skvx::shuffle<3, 2>(edges.fB)) / eDenom;
  495. V2f ey = (skvx::shuffle<0, 1>(oc) * skvx::shuffle<3, 2>(edges.fA) -
  496. skvx::shuffle<0, 1>(edges.fA) * skvx::shuffle<3, 2>(oc)) / eDenom;
  497. if (SkScalarAbs(eDenom[0]) > kTolerance) {
  498. px = if_then_else(d1v0, V4f(ex[0]), px);
  499. py = if_then_else(d1v0, V4f(ey[0]), py);
  500. }
  501. if (SkScalarAbs(eDenom[1]) > kTolerance) {
  502. px = if_then_else(d2v0, V4f(ex[1]), px);
  503. py = if_then_else(d2v0, V4f(ey[1]), py);
  504. }
  505. coverage = 1.f;
  506. }
  507. outset_projected_vertices(px, py, aaFlags, quad);
  508. return coverage;
  509. }
  510. // Computes the vertices for the two nested quads used to create AA edges. The original single quad
  511. // should be duplicated as input in 'inner' and 'outer', and the resulting quad frame will be
  512. // stored in-place on return. Returns per-vertex coverage for the inner vertices.
  513. static V4f compute_nested_quad_vertices(GrQuadAAFlags aaFlags, bool rectilinear,
  514. Vertices* inner, Vertices* outer, SkRect* domain) {
  515. SkASSERT(inner->fUVRCount == 0 || inner->fUVRCount == 2 || inner->fUVRCount == 3);
  516. SkASSERT(outer->fUVRCount == inner->fUVRCount);
  517. QuadMetadata metadata = get_metadata(*inner, aaFlags);
  518. // Calculate domain first before updating vertices. It's only used when not rectilinear.
  519. if (!rectilinear) {
  520. SkASSERT(domain);
  521. // The domain is the bounding box of the quad, outset by 0.5. Don't worry about edge masks
  522. // since the FP only applies the domain on the exterior triangles, which are degenerate for
  523. // non-AA edges.
  524. domain->fLeft = min(outer->fX) - 0.5f;
  525. domain->fRight = max(outer->fX) + 0.5f;
  526. domain->fTop = min(outer->fY) - 0.5f;
  527. domain->fBottom = max(outer->fY) + 0.5f;
  528. }
  529. // When outsetting, we want the new edge to be .5px away from the old line, which means the
  530. // corners may need to be adjusted by more than .5px if the matrix had sheer. This adjustment
  531. // is only computed if there are no empty edges, and it may signal going through the slow path.
  532. V4f outset = 0.5f;
  533. if (get_optimized_outset(metadata, rectilinear, &outset)) {
  534. // Since it's not subpixel, outsetting and insetting are trivial vector additions.
  535. outset_vertices(outset, metadata, outer);
  536. outset_vertices(-outset, metadata, inner);
  537. return 1.f;
  538. }
  539. // Only compute edge equations once since they are the same for inner and outer quads
  540. Edges edges = get_edge_equations(metadata, *inner);
  541. // Calculate both outset and inset, returning the coverage reported for the inset, since the
  542. // outset will always have 0.0f.
  543. compute_degenerate_quad(aaFlags, metadata.fMask, edges, true, outer);
  544. return compute_degenerate_quad(aaFlags, metadata.fMask, edges, false, inner);
  545. }
  546. // Generalizes compute_nested_quad_vertices to extrapolate local coords such that after perspective
  547. // division of the device coordinates, the original local coordinate value is at the original
  548. // un-outset device position.
  549. static V4f compute_nested_persp_quad_vertices(const GrQuadAAFlags aaFlags, Vertices* inner,
  550. Vertices* outer, SkRect* domain) {
  551. SkASSERT(inner->fUVRCount == 0 || inner->fUVRCount == 2 || inner->fUVRCount == 3);
  552. SkASSERT(outer->fUVRCount == inner->fUVRCount);
  553. // Calculate the projected 2D quad and use it to form projeccted inner/outer quads
  554. V4f iw = 1.0f / inner->fW;
  555. V4f x2d = inner->fX * iw;
  556. V4f y2d = inner->fY * iw;
  557. Vertices inner2D = { x2d, y2d, /*w*/ 1.f, 0.f, 0.f, 0.f, 0 }; // No uvr outsetting in 2D
  558. Vertices outer2D = inner2D;
  559. V4f coverage = compute_nested_quad_vertices(
  560. aaFlags, /* rect */ false, &inner2D, &outer2D, domain);
  561. // Now map from the 2D inset/outset back to 3D and update the local coordinates as well
  562. outset_projected_vertices(inner2D.fX, inner2D.fY, aaFlags, inner);
  563. outset_projected_vertices(outer2D.fX, outer2D.fY, aaFlags, outer);
  564. return coverage;
  565. }
  566. enum class CoverageMode {
  567. kNone,
  568. kWithPosition,
  569. kWithColor
  570. };
  571. static CoverageMode get_mode_for_spec(const GrQuadPerEdgeAA::VertexSpec& spec) {
  572. if (spec.usesCoverageAA()) {
  573. if (spec.compatibleWithCoverageAsAlpha() && spec.hasVertexColors() &&
  574. !spec.requiresGeometryDomain()) {
  575. // Using a geometric domain acts as a second source of coverage and folding the original
  576. // coverage into color makes it impossible to apply the color's alpha to the geometric
  577. // domain's coverage when the original shape is clipped.
  578. return CoverageMode::kWithColor;
  579. } else {
  580. return CoverageMode::kWithPosition;
  581. }
  582. } else {
  583. return CoverageMode::kNone;
  584. }
  585. }
  586. // Writes four vertices in triangle strip order, including the additional data for local
  587. // coordinates, geometry + texture domains, color, and coverage as needed to satisfy the vertex spec
  588. static void write_quad(GrVertexWriter* vb, const GrQuadPerEdgeAA::VertexSpec& spec,
  589. CoverageMode mode, const V4f& coverage, SkPMColor4f color4f,
  590. const SkRect& geomDomain, const SkRect& texDomain, const Vertices& quad) {
  591. static constexpr auto If = GrVertexWriter::If<float>;
  592. for (int i = 0; i < 4; ++i) {
  593. // save position, this is a float2 or float3 or float4 depending on the combination of
  594. // perspective and coverage mode.
  595. vb->write(quad.fX[i], quad.fY[i],
  596. If(spec.deviceQuadType() == GrQuad::Type::kPerspective, quad.fW[i]),
  597. If(mode == CoverageMode::kWithPosition, coverage[i]));
  598. // save color
  599. if (spec.hasVertexColors()) {
  600. bool wide = spec.colorType() == GrQuadPerEdgeAA::ColorType::kHalf;
  601. vb->write(GrVertexColor(
  602. color4f * (mode == CoverageMode::kWithColor ? coverage[i] : 1.f), wide));
  603. }
  604. // save local position
  605. if (spec.hasLocalCoords()) {
  606. vb->write(quad.fU[i], quad.fV[i],
  607. If(spec.localQuadType() == GrQuad::Type::kPerspective, quad.fR[i]));
  608. }
  609. // save the geometry domain
  610. if (spec.requiresGeometryDomain()) {
  611. vb->write(geomDomain);
  612. }
  613. // save the texture domain
  614. if (spec.hasDomain()) {
  615. vb->write(texDomain);
  616. }
  617. }
  618. }
  619. GR_DECLARE_STATIC_UNIQUE_KEY(gAAFillRectIndexBufferKey);
  620. static const int kVertsPerAAFillRect = 8;
  621. static const int kIndicesPerAAFillRect = 30;
  622. static sk_sp<const GrGpuBuffer> get_index_buffer(GrResourceProvider* resourceProvider) {
  623. GR_DEFINE_STATIC_UNIQUE_KEY(gAAFillRectIndexBufferKey);
  624. // clang-format off
  625. static const uint16_t gFillAARectIdx[] = {
  626. 0, 1, 2, 1, 3, 2,
  627. 0, 4, 1, 4, 5, 1,
  628. 0, 6, 4, 0, 2, 6,
  629. 2, 3, 6, 3, 7, 6,
  630. 1, 5, 3, 3, 5, 7,
  631. };
  632. // clang-format on
  633. GR_STATIC_ASSERT(SK_ARRAY_COUNT(gFillAARectIdx) == kIndicesPerAAFillRect);
  634. return resourceProvider->findOrCreatePatternedIndexBuffer(
  635. gFillAARectIdx, kIndicesPerAAFillRect, GrQuadPerEdgeAA::kNumAAQuadsInIndexBuffer,
  636. kVertsPerAAFillRect, gAAFillRectIndexBufferKey);
  637. }
  638. } // anonymous namespace
  639. namespace GrQuadPerEdgeAA {
  640. // This is a more elaborate version of SkPMColor4fNeedsWideColor that allows "no color" for white
  641. ColorType MinColorType(SkPMColor4f color, GrClampType clampType, const GrCaps& caps) {
  642. if (color == SK_PMColor4fWHITE) {
  643. return ColorType::kNone;
  644. } else {
  645. return SkPMColor4fNeedsWideColor(color, clampType, caps) ? ColorType::kHalf
  646. : ColorType::kByte;
  647. }
  648. }
  649. ////////////////// Tessellate Implementation
  650. void* Tessellate(void* vertices, const VertexSpec& spec, const GrQuad& deviceQuad,
  651. const SkPMColor4f& color4f, const GrQuad& localQuad, const SkRect& domain,
  652. GrQuadAAFlags aaFlags) {
  653. SkASSERT(deviceQuad.quadType() <= spec.deviceQuadType());
  654. SkASSERT(!spec.hasLocalCoords() || localQuad.quadType() <= spec.localQuadType());
  655. CoverageMode mode = get_mode_for_spec(spec);
  656. // Load position data into V4fs (always x, y, and load w to avoid branching down the road)
  657. Vertices outer;
  658. outer.fX = deviceQuad.x4f();
  659. outer.fY = deviceQuad.y4f();
  660. outer.fW = deviceQuad.w4f(); // Guaranteed to be 1f if it's not perspective
  661. // Load local position data into V4fs (either none, just u,v or all three)
  662. outer.fUVRCount = spec.localDimensionality();
  663. if (spec.hasLocalCoords()) {
  664. outer.fU = localQuad.x4f();
  665. outer.fV = localQuad.y4f();
  666. outer.fR = localQuad.w4f(); // Will be ignored if the local quad type isn't perspective
  667. }
  668. GrVertexWriter vb{vertices};
  669. if (spec.usesCoverageAA()) {
  670. SkASSERT(mode == CoverageMode::kWithPosition || mode == CoverageMode::kWithColor);
  671. // Must calculate two new quads, an outset and inset by .5 in projected device space, so
  672. // duplicate the original quad for the inner space
  673. Vertices inner = outer;
  674. SkRect geomDomain;
  675. V4f maxCoverage = 1.f;
  676. if (spec.deviceQuadType() == GrQuad::Type::kPerspective) {
  677. // For perspective, send quads with all edges non-AA through the tessellation to ensure
  678. // their corners are processed the same as adjacent quads. This approach relies on
  679. // solving edge equations to reconstruct corners, which can create seams if an inner
  680. // fully non-AA quad is not similarly processed.
  681. maxCoverage = compute_nested_persp_quad_vertices(aaFlags, &inner, &outer, &geomDomain);
  682. } else if (aaFlags != GrQuadAAFlags::kNone) {
  683. // In 2D, the simpler corner math does not cause issues with seaming against non-AA
  684. // inner quads.
  685. maxCoverage = compute_nested_quad_vertices(
  686. aaFlags, spec.deviceQuadType() <= GrQuad::Type::kRectilinear, &inner, &outer,
  687. &geomDomain);
  688. } else if (spec.requiresGeometryDomain()) {
  689. // The quad itself wouldn't need a geometric domain, but the batch does, so set the
  690. // domain to the bounds of the X/Y coords. Since it's non-AA, this won't actually be
  691. // evaluated by the shader, but make sure not to upload uninitialized data.
  692. geomDomain.fLeft = min(outer.fX);
  693. geomDomain.fRight = max(outer.fX);
  694. geomDomain.fTop = min(outer.fY);
  695. geomDomain.fBottom = max(outer.fY);
  696. }
  697. // Write two quads for inner and outer, inner will use the
  698. write_quad(&vb, spec, mode, maxCoverage, color4f, geomDomain, domain, inner);
  699. write_quad(&vb, spec, mode, 0.f, color4f, geomDomain, domain, outer);
  700. } else {
  701. // No outsetting needed, just write a single quad with full coverage
  702. SkASSERT(mode == CoverageMode::kNone && !spec.requiresGeometryDomain());
  703. write_quad(&vb, spec, mode, 1.f, color4f, SkRect::MakeEmpty(), domain, outer);
  704. }
  705. return vb.fPtr;
  706. }
  707. bool ConfigureMeshIndices(GrMeshDrawOp::Target* target, GrMesh* mesh, const VertexSpec& spec,
  708. int quadCount) {
  709. if (spec.usesCoverageAA()) {
  710. // AA quads use 8 vertices, basically nested rectangles
  711. sk_sp<const GrGpuBuffer> ibuffer = get_index_buffer(target->resourceProvider());
  712. if (!ibuffer) {
  713. return false;
  714. }
  715. mesh->setPrimitiveType(GrPrimitiveType::kTriangles);
  716. mesh->setIndexedPatterned(std::move(ibuffer), kIndicesPerAAFillRect, kVertsPerAAFillRect,
  717. quadCount, kNumAAQuadsInIndexBuffer);
  718. } else {
  719. // Non-AA quads use 4 vertices, and regular triangle strip layout
  720. if (quadCount > 1) {
  721. sk_sp<const GrGpuBuffer> ibuffer = target->resourceProvider()->refQuadIndexBuffer();
  722. if (!ibuffer) {
  723. return false;
  724. }
  725. mesh->setPrimitiveType(GrPrimitiveType::kTriangles);
  726. mesh->setIndexedPatterned(std::move(ibuffer), 6, 4, quadCount,
  727. GrResourceProvider::QuadCountOfQuadBuffer());
  728. } else {
  729. mesh->setPrimitiveType(GrPrimitiveType::kTriangleStrip);
  730. mesh->setNonIndexedNonInstanced(4);
  731. }
  732. }
  733. return true;
  734. }
  735. ////////////////// VertexSpec Implementation
  736. int VertexSpec::deviceDimensionality() const {
  737. return this->deviceQuadType() == GrQuad::Type::kPerspective ? 3 : 2;
  738. }
  739. int VertexSpec::localDimensionality() const {
  740. return fHasLocalCoords ? (this->localQuadType() == GrQuad::Type::kPerspective ? 3 : 2) : 0;
  741. }
  742. ////////////////// Geometry Processor Implementation
  743. class QuadPerEdgeAAGeometryProcessor : public GrGeometryProcessor {
  744. public:
  745. static sk_sp<GrGeometryProcessor> Make(const VertexSpec& spec) {
  746. return sk_sp<QuadPerEdgeAAGeometryProcessor>(new QuadPerEdgeAAGeometryProcessor(spec));
  747. }
  748. static sk_sp<GrGeometryProcessor> Make(const VertexSpec& vertexSpec, const GrShaderCaps& caps,
  749. GrTextureType textureType, GrPixelConfig textureConfig,
  750. const GrSamplerState& samplerState,
  751. const GrSwizzle& swizzle, uint32_t extraSamplerKey,
  752. sk_sp<GrColorSpaceXform> textureColorSpaceXform) {
  753. return sk_sp<QuadPerEdgeAAGeometryProcessor>(new QuadPerEdgeAAGeometryProcessor(
  754. vertexSpec, caps, textureType, textureConfig, samplerState, swizzle,
  755. extraSamplerKey, std::move(textureColorSpaceXform)));
  756. }
  757. const char* name() const override { return "QuadPerEdgeAAGeometryProcessor"; }
  758. void getGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder* b) const override {
  759. // texturing, device-dimensions are single bit flags
  760. uint32_t x = fTexDomain.isInitialized() ? 0 : 1;
  761. x |= fSampler.isInitialized() ? 0 : 2;
  762. x |= fNeedsPerspective ? 0 : 4;
  763. // local coords require 2 bits (3 choices), 00 for none, 01 for 2d, 10 for 3d
  764. if (fLocalCoord.isInitialized()) {
  765. x |= kFloat3_GrVertexAttribType == fLocalCoord.cpuType() ? 8 : 16;
  766. }
  767. // similar for colors, 00 for none, 01 for bytes, 10 for half-floats
  768. if (fColor.isInitialized()) {
  769. x |= kUByte4_norm_GrVertexAttribType == fColor.cpuType() ? 32 : 64;
  770. }
  771. // and coverage mode, 00 for none, 01 for withposition, 10 for withcolor, 11 for
  772. // position+geomdomain
  773. SkASSERT(!fGeomDomain.isInitialized() || fCoverageMode == CoverageMode::kWithPosition);
  774. if (fCoverageMode != CoverageMode::kNone) {
  775. x |= fGeomDomain.isInitialized() ?
  776. 384 : (CoverageMode::kWithPosition == fCoverageMode ? 128 : 256);
  777. }
  778. b->add32(GrColorSpaceXform::XformKey(fTextureColorSpaceXform.get()));
  779. b->add32(x);
  780. }
  781. GrGLSLPrimitiveProcessor* createGLSLInstance(const GrShaderCaps& caps) const override {
  782. class GLSLProcessor : public GrGLSLGeometryProcessor {
  783. public:
  784. void setData(const GrGLSLProgramDataManager& pdman, const GrPrimitiveProcessor& proc,
  785. FPCoordTransformIter&& transformIter) override {
  786. const auto& gp = proc.cast<QuadPerEdgeAAGeometryProcessor>();
  787. if (gp.fLocalCoord.isInitialized()) {
  788. this->setTransformDataHelper(SkMatrix::I(), pdman, &transformIter);
  789. }
  790. fTextureColorSpaceXformHelper.setData(pdman, gp.fTextureColorSpaceXform.get());
  791. }
  792. private:
  793. void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) override {
  794. using Interpolation = GrGLSLVaryingHandler::Interpolation;
  795. const auto& gp = args.fGP.cast<QuadPerEdgeAAGeometryProcessor>();
  796. fTextureColorSpaceXformHelper.emitCode(args.fUniformHandler,
  797. gp.fTextureColorSpaceXform.get());
  798. args.fVaryingHandler->emitAttributes(gp);
  799. if (gp.fCoverageMode == CoverageMode::kWithPosition) {
  800. // Strip last channel from the vertex attribute to remove coverage and get the
  801. // actual position
  802. if (gp.fNeedsPerspective) {
  803. args.fVertBuilder->codeAppendf("float3 position = %s.xyz;",
  804. gp.fPosition.name());
  805. } else {
  806. args.fVertBuilder->codeAppendf("float2 position = %s.xy;",
  807. gp.fPosition.name());
  808. }
  809. gpArgs->fPositionVar = {"position",
  810. gp.fNeedsPerspective ? kFloat3_GrSLType
  811. : kFloat2_GrSLType,
  812. GrShaderVar::kNone_TypeModifier};
  813. } else {
  814. // No coverage to eliminate
  815. gpArgs->fPositionVar = gp.fPosition.asShaderVar();
  816. }
  817. // Handle local coordinates if they exist
  818. if (gp.fLocalCoord.isInitialized()) {
  819. // NOTE: If the only usage of local coordinates is for the inline texture fetch
  820. // before FPs, then there are no registered FPCoordTransforms and this ends up
  821. // emitting nothing, so there isn't a duplication of local coordinates
  822. this->emitTransforms(args.fVertBuilder,
  823. args.fVaryingHandler,
  824. args.fUniformHandler,
  825. gp.fLocalCoord.asShaderVar(),
  826. args.fFPCoordTransformHandler);
  827. }
  828. // Solid color before any texturing gets modulated in
  829. if (gp.fColor.isInitialized()) {
  830. SkASSERT(gp.fCoverageMode != CoverageMode::kWithColor || !gp.fNeedsPerspective);
  831. // The color cannot be flat if the varying coverage has been modulated into it
  832. args.fVaryingHandler->addPassThroughAttribute(gp.fColor, args.fOutputColor,
  833. gp.fCoverageMode == CoverageMode::kWithColor ?
  834. Interpolation::kInterpolated : Interpolation::kCanBeFlat);
  835. } else {
  836. // Output color must be initialized to something
  837. args.fFragBuilder->codeAppendf("%s = half4(1);", args.fOutputColor);
  838. }
  839. // If there is a texture, must also handle texture coordinates and reading from
  840. // the texture in the fragment shader before continuing to fragment processors.
  841. if (gp.fSampler.isInitialized()) {
  842. // Texture coordinates clamped by the domain on the fragment shader; if the GP
  843. // has a texture, it's guaranteed to have local coordinates
  844. args.fFragBuilder->codeAppend("float2 texCoord;");
  845. if (gp.fLocalCoord.cpuType() == kFloat3_GrVertexAttribType) {
  846. // Can't do a pass through since we need to perform perspective division
  847. GrGLSLVarying v(gp.fLocalCoord.gpuType());
  848. args.fVaryingHandler->addVarying(gp.fLocalCoord.name(), &v);
  849. args.fVertBuilder->codeAppendf("%s = %s;",
  850. v.vsOut(), gp.fLocalCoord.name());
  851. args.fFragBuilder->codeAppendf("texCoord = %s.xy / %s.z;",
  852. v.fsIn(), v.fsIn());
  853. } else {
  854. args.fVaryingHandler->addPassThroughAttribute(gp.fLocalCoord, "texCoord");
  855. }
  856. // Clamp the now 2D localCoordName variable by the domain if it is provided
  857. if (gp.fTexDomain.isInitialized()) {
  858. args.fFragBuilder->codeAppend("float4 domain;");
  859. args.fVaryingHandler->addPassThroughAttribute(gp.fTexDomain, "domain",
  860. Interpolation::kCanBeFlat);
  861. args.fFragBuilder->codeAppend(
  862. "texCoord = clamp(texCoord, domain.xy, domain.zw);");
  863. }
  864. // Now modulate the starting output color by the texture lookup
  865. args.fFragBuilder->codeAppendf("%s = ", args.fOutputColor);
  866. args.fFragBuilder->appendTextureLookupAndModulate(
  867. args.fOutputColor, args.fTexSamplers[0], "texCoord", kFloat2_GrSLType,
  868. &fTextureColorSpaceXformHelper);
  869. args.fFragBuilder->codeAppend(";");
  870. }
  871. // And lastly, output the coverage calculation code
  872. if (gp.fCoverageMode == CoverageMode::kWithPosition) {
  873. GrGLSLVarying coverage(kFloat_GrSLType);
  874. args.fVaryingHandler->addVarying("coverage", &coverage);
  875. if (gp.fNeedsPerspective) {
  876. // Multiply by "W" in the vertex shader, then by 1/w (sk_FragCoord.w) in
  877. // the fragment shader to get screen-space linear coverage.
  878. args.fVertBuilder->codeAppendf("%s = %s.w * %s.z;",
  879. coverage.vsOut(), gp.fPosition.name(),
  880. gp.fPosition.name());
  881. args.fFragBuilder->codeAppendf("float coverage = %s * sk_FragCoord.w;",
  882. coverage.fsIn());
  883. } else {
  884. args.fVertBuilder->codeAppendf("%s = %s;",
  885. coverage.vsOut(), gp.fCoverage.name());
  886. args.fFragBuilder->codeAppendf("float coverage = %s;", coverage.fsIn());
  887. }
  888. if (gp.fGeomDomain.isInitialized()) {
  889. // Calculate distance from sk_FragCoord to the 4 edges of the domain
  890. // and clamp them to (0, 1). Use the minimum of these and the original
  891. // coverage. This only has to be done in the exterior triangles, the
  892. // interior of the quad geometry can never be clipped by the domain box.
  893. args.fFragBuilder->codeAppend("float4 geoDomain;");
  894. args.fVaryingHandler->addPassThroughAttribute(gp.fGeomDomain, "geoDomain",
  895. Interpolation::kCanBeFlat);
  896. args.fFragBuilder->codeAppend(
  897. "if (coverage < 0.5) {"
  898. " float4 dists4 = clamp(float4(1, 1, -1, -1) * "
  899. "(sk_FragCoord.xyxy - geoDomain), 0, 1);"
  900. " float2 dists2 = dists4.xy * dists4.zw;"
  901. " coverage = min(coverage, dists2.x * dists2.y);"
  902. "}");
  903. }
  904. args.fFragBuilder->codeAppendf("%s = half4(half(coverage));",
  905. args.fOutputCoverage);
  906. } else {
  907. // Set coverage to 1, since it's either non-AA or the coverage was already
  908. // folded into the output color
  909. SkASSERT(!gp.fGeomDomain.isInitialized());
  910. args.fFragBuilder->codeAppendf("%s = half4(1);", args.fOutputCoverage);
  911. }
  912. }
  913. GrGLSLColorSpaceXformHelper fTextureColorSpaceXformHelper;
  914. };
  915. return new GLSLProcessor;
  916. }
  917. private:
  918. QuadPerEdgeAAGeometryProcessor(const VertexSpec& spec)
  919. : INHERITED(kQuadPerEdgeAAGeometryProcessor_ClassID)
  920. , fTextureColorSpaceXform(nullptr) {
  921. SkASSERT(!spec.hasDomain());
  922. this->initializeAttrs(spec);
  923. this->setTextureSamplerCnt(0);
  924. }
  925. QuadPerEdgeAAGeometryProcessor(const VertexSpec& spec, const GrShaderCaps& caps,
  926. GrTextureType textureType, GrPixelConfig textureConfig,
  927. const GrSamplerState& samplerState,
  928. const GrSwizzle& swizzle,
  929. uint32_t extraSamplerKey,
  930. sk_sp<GrColorSpaceXform> textureColorSpaceXform)
  931. : INHERITED(kQuadPerEdgeAAGeometryProcessor_ClassID)
  932. , fTextureColorSpaceXform(std::move(textureColorSpaceXform))
  933. , fSampler(textureType, textureConfig, samplerState, swizzle, extraSamplerKey) {
  934. SkASSERT(spec.hasLocalCoords());
  935. this->initializeAttrs(spec);
  936. this->setTextureSamplerCnt(1);
  937. }
  938. void initializeAttrs(const VertexSpec& spec) {
  939. fNeedsPerspective = spec.deviceDimensionality() == 3;
  940. fCoverageMode = get_mode_for_spec(spec);
  941. if (fCoverageMode == CoverageMode::kWithPosition) {
  942. if (fNeedsPerspective) {
  943. fPosition = {"positionWithCoverage", kFloat4_GrVertexAttribType, kFloat4_GrSLType};
  944. } else {
  945. fPosition = {"position", kFloat2_GrVertexAttribType, kFloat2_GrSLType};
  946. fCoverage = {"coverage", kFloat_GrVertexAttribType, kFloat_GrSLType};
  947. }
  948. } else {
  949. if (fNeedsPerspective) {
  950. fPosition = {"position", kFloat3_GrVertexAttribType, kFloat3_GrSLType};
  951. } else {
  952. fPosition = {"position", kFloat2_GrVertexAttribType, kFloat2_GrSLType};
  953. }
  954. }
  955. // Need a geometry domain when the quads are AA and not rectilinear, since their AA
  956. // outsetting can go beyond a half pixel.
  957. if (spec.requiresGeometryDomain()) {
  958. fGeomDomain = {"geomDomain", kFloat4_GrVertexAttribType, kFloat4_GrSLType};
  959. }
  960. int localDim = spec.localDimensionality();
  961. if (localDim == 3) {
  962. fLocalCoord = {"localCoord", kFloat3_GrVertexAttribType, kFloat3_GrSLType};
  963. } else if (localDim == 2) {
  964. fLocalCoord = {"localCoord", kFloat2_GrVertexAttribType, kFloat2_GrSLType};
  965. } // else localDim == 0 and attribute remains uninitialized
  966. if (ColorType::kByte == spec.colorType()) {
  967. fColor = {"color", kUByte4_norm_GrVertexAttribType, kHalf4_GrSLType};
  968. } else if (ColorType::kHalf == spec.colorType()) {
  969. fColor = {"color", kHalf4_GrVertexAttribType, kHalf4_GrSLType};
  970. }
  971. if (spec.hasDomain()) {
  972. fTexDomain = {"texDomain", kFloat4_GrVertexAttribType, kFloat4_GrSLType};
  973. }
  974. this->setVertexAttributes(&fPosition, 6);
  975. }
  976. const TextureSampler& onTextureSampler(int) const override { return fSampler; }
  977. Attribute fPosition; // May contain coverage as last channel
  978. Attribute fCoverage; // Used for non-perspective position to avoid Intel Metal issues
  979. Attribute fColor; // May have coverage modulated in if the FPs support it
  980. Attribute fLocalCoord;
  981. Attribute fGeomDomain; // Screen-space bounding box on geometry+aa outset
  982. Attribute fTexDomain; // Texture-space bounding box on local coords
  983. // The positions attribute may have coverage built into it, so float3 is an ambiguous type
  984. // and may mean 2d with coverage, or 3d with no coverage
  985. bool fNeedsPerspective;
  986. CoverageMode fCoverageMode;
  987. // Color space will be null and fSampler.isInitialized() returns false when the GP is configured
  988. // to skip texturing.
  989. sk_sp<GrColorSpaceXform> fTextureColorSpaceXform;
  990. TextureSampler fSampler;
  991. typedef GrGeometryProcessor INHERITED;
  992. };
  993. sk_sp<GrGeometryProcessor> MakeProcessor(const VertexSpec& spec) {
  994. return QuadPerEdgeAAGeometryProcessor::Make(spec);
  995. }
  996. sk_sp<GrGeometryProcessor> MakeTexturedProcessor(const VertexSpec& spec, const GrShaderCaps& caps,
  997. GrTextureType textureType, GrPixelConfig textureConfig,
  998. const GrSamplerState& samplerState, const GrSwizzle& swizzle, uint32_t extraSamplerKey,
  999. sk_sp<GrColorSpaceXform> textureColorSpaceXform) {
  1000. return QuadPerEdgeAAGeometryProcessor::Make(spec, caps, textureType, textureConfig,
  1001. samplerState, swizzle, extraSamplerKey,
  1002. std::move(textureColorSpaceXform));
  1003. }
  1004. } // namespace GrQuadPerEdgeAA