SkGeometry.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488
  1. /*
  2. * Copyright 2006 The Android Open Source Project
  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/core/SkMatrix.h"
  8. #include "include/core/SkPoint3.h"
  9. #include "include/private/SkNx.h"
  10. #include "src/core/SkGeometry.h"
  11. #include "src/core/SkPointPriv.h"
  12. #include <utility>
  13. static SkVector to_vector(const Sk2s& x) {
  14. SkVector vector;
  15. x.store(&vector);
  16. return vector;
  17. }
  18. ////////////////////////////////////////////////////////////////////////
  19. static int is_not_monotonic(SkScalar a, SkScalar b, SkScalar c) {
  20. SkScalar ab = a - b;
  21. SkScalar bc = b - c;
  22. if (ab < 0) {
  23. bc = -bc;
  24. }
  25. return ab == 0 || bc < 0;
  26. }
  27. ////////////////////////////////////////////////////////////////////////
  28. static int valid_unit_divide(SkScalar numer, SkScalar denom, SkScalar* ratio) {
  29. SkASSERT(ratio);
  30. if (numer < 0) {
  31. numer = -numer;
  32. denom = -denom;
  33. }
  34. if (denom == 0 || numer == 0 || numer >= denom) {
  35. return 0;
  36. }
  37. SkScalar r = numer / denom;
  38. if (SkScalarIsNaN(r)) {
  39. return 0;
  40. }
  41. SkASSERTF(r >= 0 && r < SK_Scalar1, "numer %f, denom %f, r %f", numer, denom, r);
  42. if (r == 0) { // catch underflow if numer <<<< denom
  43. return 0;
  44. }
  45. *ratio = r;
  46. return 1;
  47. }
  48. // Just returns its argument, but makes it easy to set a break-point to know when
  49. // SkFindUnitQuadRoots is going to return 0 (an error).
  50. static int return_check_zero(int value) {
  51. if (value == 0) {
  52. return 0;
  53. }
  54. return value;
  55. }
  56. /** From Numerical Recipes in C.
  57. Q = -1/2 (B + sign(B) sqrt[B*B - 4*A*C])
  58. x1 = Q / A
  59. x2 = C / Q
  60. */
  61. int SkFindUnitQuadRoots(SkScalar A, SkScalar B, SkScalar C, SkScalar roots[2]) {
  62. SkASSERT(roots);
  63. if (A == 0) {
  64. return return_check_zero(valid_unit_divide(-C, B, roots));
  65. }
  66. SkScalar* r = roots;
  67. // use doubles so we don't overflow temporarily trying to compute R
  68. double dr = (double)B * B - 4 * (double)A * C;
  69. if (dr < 0) {
  70. return return_check_zero(0);
  71. }
  72. dr = sqrt(dr);
  73. SkScalar R = SkDoubleToScalar(dr);
  74. if (!SkScalarIsFinite(R)) {
  75. return return_check_zero(0);
  76. }
  77. SkScalar Q = (B < 0) ? -(B-R)/2 : -(B+R)/2;
  78. r += valid_unit_divide(Q, A, r);
  79. r += valid_unit_divide(C, Q, r);
  80. if (r - roots == 2) {
  81. if (roots[0] > roots[1]) {
  82. using std::swap;
  83. swap(roots[0], roots[1]);
  84. } else if (roots[0] == roots[1]) { // nearly-equal?
  85. r -= 1; // skip the double root
  86. }
  87. }
  88. return return_check_zero((int)(r - roots));
  89. }
  90. ///////////////////////////////////////////////////////////////////////////////
  91. ///////////////////////////////////////////////////////////////////////////////
  92. void SkEvalQuadAt(const SkPoint src[3], SkScalar t, SkPoint* pt, SkVector* tangent) {
  93. SkASSERT(src);
  94. SkASSERT(t >= 0 && t <= SK_Scalar1);
  95. if (pt) {
  96. *pt = SkEvalQuadAt(src, t);
  97. }
  98. if (tangent) {
  99. *tangent = SkEvalQuadTangentAt(src, t);
  100. }
  101. }
  102. SkPoint SkEvalQuadAt(const SkPoint src[3], SkScalar t) {
  103. return to_point(SkQuadCoeff(src).eval(t));
  104. }
  105. SkVector SkEvalQuadTangentAt(const SkPoint src[3], SkScalar t) {
  106. // The derivative equation is 2(b - a +(a - 2b +c)t). This returns a
  107. // zero tangent vector when t is 0 or 1, and the control point is equal
  108. // to the end point. In this case, use the quad end points to compute the tangent.
  109. if ((t == 0 && src[0] == src[1]) || (t == 1 && src[1] == src[2])) {
  110. return src[2] - src[0];
  111. }
  112. SkASSERT(src);
  113. SkASSERT(t >= 0 && t <= SK_Scalar1);
  114. Sk2s P0 = from_point(src[0]);
  115. Sk2s P1 = from_point(src[1]);
  116. Sk2s P2 = from_point(src[2]);
  117. Sk2s B = P1 - P0;
  118. Sk2s A = P2 - P1 - B;
  119. Sk2s T = A * Sk2s(t) + B;
  120. return to_vector(T + T);
  121. }
  122. static inline Sk2s interp(const Sk2s& v0, const Sk2s& v1, const Sk2s& t) {
  123. return v0 + (v1 - v0) * t;
  124. }
  125. void SkChopQuadAt(const SkPoint src[3], SkPoint dst[5], SkScalar t) {
  126. SkASSERT(t > 0 && t < SK_Scalar1);
  127. Sk2s p0 = from_point(src[0]);
  128. Sk2s p1 = from_point(src[1]);
  129. Sk2s p2 = from_point(src[2]);
  130. Sk2s tt(t);
  131. Sk2s p01 = interp(p0, p1, tt);
  132. Sk2s p12 = interp(p1, p2, tt);
  133. dst[0] = to_point(p0);
  134. dst[1] = to_point(p01);
  135. dst[2] = to_point(interp(p01, p12, tt));
  136. dst[3] = to_point(p12);
  137. dst[4] = to_point(p2);
  138. }
  139. void SkChopQuadAtHalf(const SkPoint src[3], SkPoint dst[5]) {
  140. SkChopQuadAt(src, dst, 0.5f);
  141. }
  142. /** Quad'(t) = At + B, where
  143. A = 2(a - 2b + c)
  144. B = 2(b - a)
  145. Solve for t, only if it fits between 0 < t < 1
  146. */
  147. int SkFindQuadExtrema(SkScalar a, SkScalar b, SkScalar c, SkScalar tValue[1]) {
  148. /* At + B == 0
  149. t = -B / A
  150. */
  151. return valid_unit_divide(a - b, a - b - b + c, tValue);
  152. }
  153. static inline void flatten_double_quad_extrema(SkScalar coords[14]) {
  154. coords[2] = coords[6] = coords[4];
  155. }
  156. /* Returns 0 for 1 quad, and 1 for two quads, either way the answer is
  157. stored in dst[]. Guarantees that the 1/2 quads will be monotonic.
  158. */
  159. int SkChopQuadAtYExtrema(const SkPoint src[3], SkPoint dst[5]) {
  160. SkASSERT(src);
  161. SkASSERT(dst);
  162. SkScalar a = src[0].fY;
  163. SkScalar b = src[1].fY;
  164. SkScalar c = src[2].fY;
  165. if (is_not_monotonic(a, b, c)) {
  166. SkScalar tValue;
  167. if (valid_unit_divide(a - b, a - b - b + c, &tValue)) {
  168. SkChopQuadAt(src, dst, tValue);
  169. flatten_double_quad_extrema(&dst[0].fY);
  170. return 1;
  171. }
  172. // if we get here, we need to force dst to be monotonic, even though
  173. // we couldn't compute a unit_divide value (probably underflow).
  174. b = SkScalarAbs(a - b) < SkScalarAbs(b - c) ? a : c;
  175. }
  176. dst[0].set(src[0].fX, a);
  177. dst[1].set(src[1].fX, b);
  178. dst[2].set(src[2].fX, c);
  179. return 0;
  180. }
  181. /* Returns 0 for 1 quad, and 1 for two quads, either way the answer is
  182. stored in dst[]. Guarantees that the 1/2 quads will be monotonic.
  183. */
  184. int SkChopQuadAtXExtrema(const SkPoint src[3], SkPoint dst[5]) {
  185. SkASSERT(src);
  186. SkASSERT(dst);
  187. SkScalar a = src[0].fX;
  188. SkScalar b = src[1].fX;
  189. SkScalar c = src[2].fX;
  190. if (is_not_monotonic(a, b, c)) {
  191. SkScalar tValue;
  192. if (valid_unit_divide(a - b, a - b - b + c, &tValue)) {
  193. SkChopQuadAt(src, dst, tValue);
  194. flatten_double_quad_extrema(&dst[0].fX);
  195. return 1;
  196. }
  197. // if we get here, we need to force dst to be monotonic, even though
  198. // we couldn't compute a unit_divide value (probably underflow).
  199. b = SkScalarAbs(a - b) < SkScalarAbs(b - c) ? a : c;
  200. }
  201. dst[0].set(a, src[0].fY);
  202. dst[1].set(b, src[1].fY);
  203. dst[2].set(c, src[2].fY);
  204. return 0;
  205. }
  206. // F(t) = a (1 - t) ^ 2 + 2 b t (1 - t) + c t ^ 2
  207. // F'(t) = 2 (b - a) + 2 (a - 2b + c) t
  208. // F''(t) = 2 (a - 2b + c)
  209. //
  210. // A = 2 (b - a)
  211. // B = 2 (a - 2b + c)
  212. //
  213. // Maximum curvature for a quadratic means solving
  214. // Fx' Fx'' + Fy' Fy'' = 0
  215. //
  216. // t = - (Ax Bx + Ay By) / (Bx ^ 2 + By ^ 2)
  217. //
  218. SkScalar SkFindQuadMaxCurvature(const SkPoint src[3]) {
  219. SkScalar Ax = src[1].fX - src[0].fX;
  220. SkScalar Ay = src[1].fY - src[0].fY;
  221. SkScalar Bx = src[0].fX - src[1].fX - src[1].fX + src[2].fX;
  222. SkScalar By = src[0].fY - src[1].fY - src[1].fY + src[2].fY;
  223. SkScalar numer = -(Ax * Bx + Ay * By);
  224. SkScalar denom = Bx * Bx + By * By;
  225. if (denom < 0) {
  226. numer = -numer;
  227. denom = -denom;
  228. }
  229. if (numer <= 0) {
  230. return 0;
  231. }
  232. if (numer >= denom) { // Also catches denom=0.
  233. return 1;
  234. }
  235. SkScalar t = numer / denom;
  236. SkASSERT((0 <= t && t < 1) || SkScalarIsNaN(t));
  237. return t;
  238. }
  239. int SkChopQuadAtMaxCurvature(const SkPoint src[3], SkPoint dst[5]) {
  240. SkScalar t = SkFindQuadMaxCurvature(src);
  241. if (t == 0 || t == 1) {
  242. memcpy(dst, src, 3 * sizeof(SkPoint));
  243. return 1;
  244. } else {
  245. SkChopQuadAt(src, dst, t);
  246. return 2;
  247. }
  248. }
  249. void SkConvertQuadToCubic(const SkPoint src[3], SkPoint dst[4]) {
  250. Sk2s scale(SkDoubleToScalar(2.0 / 3.0));
  251. Sk2s s0 = from_point(src[0]);
  252. Sk2s s1 = from_point(src[1]);
  253. Sk2s s2 = from_point(src[2]);
  254. dst[0] = to_point(s0);
  255. dst[1] = to_point(s0 + (s1 - s0) * scale);
  256. dst[2] = to_point(s2 + (s1 - s2) * scale);
  257. dst[3] = to_point(s2);
  258. }
  259. //////////////////////////////////////////////////////////////////////////////
  260. ///// CUBICS // CUBICS // CUBICS // CUBICS // CUBICS // CUBICS // CUBICS /////
  261. //////////////////////////////////////////////////////////////////////////////
  262. static SkVector eval_cubic_derivative(const SkPoint src[4], SkScalar t) {
  263. SkQuadCoeff coeff;
  264. Sk2s P0 = from_point(src[0]);
  265. Sk2s P1 = from_point(src[1]);
  266. Sk2s P2 = from_point(src[2]);
  267. Sk2s P3 = from_point(src[3]);
  268. coeff.fA = P3 + Sk2s(3) * (P1 - P2) - P0;
  269. coeff.fB = times_2(P2 - times_2(P1) + P0);
  270. coeff.fC = P1 - P0;
  271. return to_vector(coeff.eval(t));
  272. }
  273. static SkVector eval_cubic_2ndDerivative(const SkPoint src[4], SkScalar t) {
  274. Sk2s P0 = from_point(src[0]);
  275. Sk2s P1 = from_point(src[1]);
  276. Sk2s P2 = from_point(src[2]);
  277. Sk2s P3 = from_point(src[3]);
  278. Sk2s A = P3 + Sk2s(3) * (P1 - P2) - P0;
  279. Sk2s B = P2 - times_2(P1) + P0;
  280. return to_vector(A * Sk2s(t) + B);
  281. }
  282. void SkEvalCubicAt(const SkPoint src[4], SkScalar t, SkPoint* loc,
  283. SkVector* tangent, SkVector* curvature) {
  284. SkASSERT(src);
  285. SkASSERT(t >= 0 && t <= SK_Scalar1);
  286. if (loc) {
  287. *loc = to_point(SkCubicCoeff(src).eval(t));
  288. }
  289. if (tangent) {
  290. // The derivative equation returns a zero tangent vector when t is 0 or 1, and the
  291. // adjacent control point is equal to the end point. In this case, use the
  292. // next control point or the end points to compute the tangent.
  293. if ((t == 0 && src[0] == src[1]) || (t == 1 && src[2] == src[3])) {
  294. if (t == 0) {
  295. *tangent = src[2] - src[0];
  296. } else {
  297. *tangent = src[3] - src[1];
  298. }
  299. if (!tangent->fX && !tangent->fY) {
  300. *tangent = src[3] - src[0];
  301. }
  302. } else {
  303. *tangent = eval_cubic_derivative(src, t);
  304. }
  305. }
  306. if (curvature) {
  307. *curvature = eval_cubic_2ndDerivative(src, t);
  308. }
  309. }
  310. /** Cubic'(t) = At^2 + Bt + C, where
  311. A = 3(-a + 3(b - c) + d)
  312. B = 6(a - 2b + c)
  313. C = 3(b - a)
  314. Solve for t, keeping only those that fit betwee 0 < t < 1
  315. */
  316. int SkFindCubicExtrema(SkScalar a, SkScalar b, SkScalar c, SkScalar d,
  317. SkScalar tValues[2]) {
  318. // we divide A,B,C by 3 to simplify
  319. SkScalar A = d - a + 3*(b - c);
  320. SkScalar B = 2*(a - b - b + c);
  321. SkScalar C = b - a;
  322. return SkFindUnitQuadRoots(A, B, C, tValues);
  323. }
  324. void SkChopCubicAt(const SkPoint src[4], SkPoint dst[7], SkScalar t) {
  325. SkASSERT(t > 0 && t < SK_Scalar1);
  326. Sk2s p0 = from_point(src[0]);
  327. Sk2s p1 = from_point(src[1]);
  328. Sk2s p2 = from_point(src[2]);
  329. Sk2s p3 = from_point(src[3]);
  330. Sk2s tt(t);
  331. Sk2s ab = interp(p0, p1, tt);
  332. Sk2s bc = interp(p1, p2, tt);
  333. Sk2s cd = interp(p2, p3, tt);
  334. Sk2s abc = interp(ab, bc, tt);
  335. Sk2s bcd = interp(bc, cd, tt);
  336. Sk2s abcd = interp(abc, bcd, tt);
  337. dst[0] = to_point(p0);
  338. dst[1] = to_point(ab);
  339. dst[2] = to_point(abc);
  340. dst[3] = to_point(abcd);
  341. dst[4] = to_point(bcd);
  342. dst[5] = to_point(cd);
  343. dst[6] = to_point(p3);
  344. }
  345. /* http://code.google.com/p/skia/issues/detail?id=32
  346. This test code would fail when we didn't check the return result of
  347. valid_unit_divide in SkChopCubicAt(... tValues[], int roots). The reason is
  348. that after the first chop, the parameters to valid_unit_divide are equal
  349. (thanks to finite float precision and rounding in the subtracts). Thus
  350. even though the 2nd tValue looks < 1.0, after we renormalize it, we end
  351. up with 1.0, hence the need to check and just return the last cubic as
  352. a degenerate clump of 4 points in the sampe place.
  353. static void test_cubic() {
  354. SkPoint src[4] = {
  355. { 556.25000, 523.03003 },
  356. { 556.23999, 522.96002 },
  357. { 556.21997, 522.89001 },
  358. { 556.21997, 522.82001 }
  359. };
  360. SkPoint dst[10];
  361. SkScalar tval[] = { 0.33333334f, 0.99999994f };
  362. SkChopCubicAt(src, dst, tval, 2);
  363. }
  364. */
  365. void SkChopCubicAt(const SkPoint src[4], SkPoint dst[],
  366. const SkScalar tValues[], int roots) {
  367. #ifdef SK_DEBUG
  368. {
  369. for (int i = 0; i < roots - 1; i++)
  370. {
  371. SkASSERT(0 < tValues[i] && tValues[i] < 1);
  372. SkASSERT(0 < tValues[i+1] && tValues[i+1] < 1);
  373. SkASSERT(tValues[i] < tValues[i+1]);
  374. }
  375. }
  376. #endif
  377. if (dst) {
  378. if (roots == 0) { // nothing to chop
  379. memcpy(dst, src, 4*sizeof(SkPoint));
  380. } else {
  381. SkScalar t = tValues[0];
  382. SkPoint tmp[4];
  383. for (int i = 0; i < roots; i++) {
  384. SkChopCubicAt(src, dst, t);
  385. if (i == roots - 1) {
  386. break;
  387. }
  388. dst += 3;
  389. // have src point to the remaining cubic (after the chop)
  390. memcpy(tmp, dst, 4 * sizeof(SkPoint));
  391. src = tmp;
  392. // watch out in case the renormalized t isn't in range
  393. if (!valid_unit_divide(tValues[i+1] - tValues[i],
  394. SK_Scalar1 - tValues[i], &t)) {
  395. // if we can't, just create a degenerate cubic
  396. dst[4] = dst[5] = dst[6] = src[3];
  397. break;
  398. }
  399. }
  400. }
  401. }
  402. }
  403. void SkChopCubicAtHalf(const SkPoint src[4], SkPoint dst[7]) {
  404. SkChopCubicAt(src, dst, 0.5f);
  405. }
  406. static void flatten_double_cubic_extrema(SkScalar coords[14]) {
  407. coords[4] = coords[8] = coords[6];
  408. }
  409. /** Given 4 points on a cubic bezier, chop it into 1, 2, 3 beziers such that
  410. the resulting beziers are monotonic in Y. This is called by the scan
  411. converter. Depending on what is returned, dst[] is treated as follows:
  412. 0 dst[0..3] is the original cubic
  413. 1 dst[0..3] and dst[3..6] are the two new cubics
  414. 2 dst[0..3], dst[3..6], dst[6..9] are the three new cubics
  415. If dst == null, it is ignored and only the count is returned.
  416. */
  417. int SkChopCubicAtYExtrema(const SkPoint src[4], SkPoint dst[10]) {
  418. SkScalar tValues[2];
  419. int roots = SkFindCubicExtrema(src[0].fY, src[1].fY, src[2].fY,
  420. src[3].fY, tValues);
  421. SkChopCubicAt(src, dst, tValues, roots);
  422. if (dst && roots > 0) {
  423. // we do some cleanup to ensure our Y extrema are flat
  424. flatten_double_cubic_extrema(&dst[0].fY);
  425. if (roots == 2) {
  426. flatten_double_cubic_extrema(&dst[3].fY);
  427. }
  428. }
  429. return roots;
  430. }
  431. int SkChopCubicAtXExtrema(const SkPoint src[4], SkPoint dst[10]) {
  432. SkScalar tValues[2];
  433. int roots = SkFindCubicExtrema(src[0].fX, src[1].fX, src[2].fX,
  434. src[3].fX, tValues);
  435. SkChopCubicAt(src, dst, tValues, roots);
  436. if (dst && roots > 0) {
  437. // we do some cleanup to ensure our Y extrema are flat
  438. flatten_double_cubic_extrema(&dst[0].fX);
  439. if (roots == 2) {
  440. flatten_double_cubic_extrema(&dst[3].fX);
  441. }
  442. }
  443. return roots;
  444. }
  445. /** http://www.faculty.idc.ac.il/arik/quality/appendixA.html
  446. Inflection means that curvature is zero.
  447. Curvature is [F' x F''] / [F'^3]
  448. So we solve F'x X F''y - F'y X F''y == 0
  449. After some canceling of the cubic term, we get
  450. A = b - a
  451. B = c - 2b + a
  452. C = d - 3c + 3b - a
  453. (BxCy - ByCx)t^2 + (AxCy - AyCx)t + AxBy - AyBx == 0
  454. */
  455. int SkFindCubicInflections(const SkPoint src[4], SkScalar tValues[]) {
  456. SkScalar Ax = src[1].fX - src[0].fX;
  457. SkScalar Ay = src[1].fY - src[0].fY;
  458. SkScalar Bx = src[2].fX - 2 * src[1].fX + src[0].fX;
  459. SkScalar By = src[2].fY - 2 * src[1].fY + src[0].fY;
  460. SkScalar Cx = src[3].fX + 3 * (src[1].fX - src[2].fX) - src[0].fX;
  461. SkScalar Cy = src[3].fY + 3 * (src[1].fY - src[2].fY) - src[0].fY;
  462. return SkFindUnitQuadRoots(Bx*Cy - By*Cx,
  463. Ax*Cy - Ay*Cx,
  464. Ax*By - Ay*Bx,
  465. tValues);
  466. }
  467. int SkChopCubicAtInflections(const SkPoint src[], SkPoint dst[10]) {
  468. SkScalar tValues[2];
  469. int count = SkFindCubicInflections(src, tValues);
  470. if (dst) {
  471. if (count == 0) {
  472. memcpy(dst, src, 4 * sizeof(SkPoint));
  473. } else {
  474. SkChopCubicAt(src, dst, tValues, count);
  475. }
  476. }
  477. return count + 1;
  478. }
  479. // Assumes the third component of points is 1.
  480. // Calcs p0 . (p1 x p2)
  481. static double calc_dot_cross_cubic(const SkPoint& p0, const SkPoint& p1, const SkPoint& p2) {
  482. const double xComp = (double) p0.fX * ((double) p1.fY - (double) p2.fY);
  483. const double yComp = (double) p0.fY * ((double) p2.fX - (double) p1.fX);
  484. const double wComp = (double) p1.fX * (double) p2.fY - (double) p1.fY * (double) p2.fX;
  485. return (xComp + yComp + wComp);
  486. }
  487. // Returns a positive power of 2 that, when multiplied by n, and excepting the two edge cases listed
  488. // below, shifts the exponent of n to yield a magnitude somewhere inside [1..2).
  489. // Returns 2^1023 if abs(n) < 2^-1022 (including 0).
  490. // Returns NaN if n is Inf or NaN.
  491. inline static double previous_inverse_pow2(double n) {
  492. uint64_t bits;
  493. memcpy(&bits, &n, sizeof(double));
  494. bits = ((1023llu*2 << 52) + ((1llu << 52) - 1)) - bits; // exp=-exp
  495. bits &= (0x7ffllu) << 52; // mantissa=1.0, sign=0
  496. memcpy(&n, &bits, sizeof(double));
  497. return n;
  498. }
  499. inline static void write_cubic_inflection_roots(double t0, double s0, double t1, double s1,
  500. double* t, double* s) {
  501. t[0] = t0;
  502. s[0] = s0;
  503. // This copysign/abs business orients the implicit function so positive values are always on the
  504. // "left" side of the curve.
  505. t[1] = -copysign(t1, t1 * s1);
  506. s[1] = -fabs(s1);
  507. // Ensure t[0]/s[0] <= t[1]/s[1] (s[1] is negative from above).
  508. if (copysign(s[1], s[0]) * t[0] > -fabs(s[0]) * t[1]) {
  509. using std::swap;
  510. swap(t[0], t[1]);
  511. swap(s[0], s[1]);
  512. }
  513. }
  514. SkCubicType SkClassifyCubic(const SkPoint P[4], double t[2], double s[2], double d[4]) {
  515. // Find the cubic's inflection function, I = [T^3 -3T^2 3T -1] dot D. (D0 will always be 0
  516. // for integral cubics.)
  517. //
  518. // See "Resolution Independent Curve Rendering using Programmable Graphics Hardware",
  519. // 4.2 Curve Categorization:
  520. //
  521. // https://www.microsoft.com/en-us/research/wp-content/uploads/2005/01/p1000-loop.pdf
  522. double A1 = calc_dot_cross_cubic(P[0], P[3], P[2]);
  523. double A2 = calc_dot_cross_cubic(P[1], P[0], P[3]);
  524. double A3 = calc_dot_cross_cubic(P[2], P[1], P[0]);
  525. double D3 = 3 * A3;
  526. double D2 = D3 - A2;
  527. double D1 = D2 - A2 + A1;
  528. // Shift the exponents in D so the largest magnitude falls somewhere in 1..2. This protects us
  529. // from overflow down the road while solving for roots and KLM functionals.
  530. double Dmax = std::max(std::max(fabs(D1), fabs(D2)), fabs(D3));
  531. double norm = previous_inverse_pow2(Dmax);
  532. D1 *= norm;
  533. D2 *= norm;
  534. D3 *= norm;
  535. if (d) {
  536. d[3] = D3;
  537. d[2] = D2;
  538. d[1] = D1;
  539. d[0] = 0;
  540. }
  541. // Now use the inflection function to classify the cubic.
  542. //
  543. // See "Resolution Independent Curve Rendering using Programmable Graphics Hardware",
  544. // 4.4 Integral Cubics:
  545. //
  546. // https://www.microsoft.com/en-us/research/wp-content/uploads/2005/01/p1000-loop.pdf
  547. if (0 != D1) {
  548. double discr = 3*D2*D2 - 4*D1*D3;
  549. if (discr > 0) { // Serpentine.
  550. if (t && s) {
  551. double q = 3*D2 + copysign(sqrt(3*discr), D2);
  552. write_cubic_inflection_roots(q, 6*D1, 2*D3, q, t, s);
  553. }
  554. return SkCubicType::kSerpentine;
  555. } else if (discr < 0) { // Loop.
  556. if (t && s) {
  557. double q = D2 + copysign(sqrt(-discr), D2);
  558. write_cubic_inflection_roots(q, 2*D1, 2*(D2*D2 - D3*D1), D1*q, t, s);
  559. }
  560. return SkCubicType::kLoop;
  561. } else { // Cusp.
  562. if (t && s) {
  563. write_cubic_inflection_roots(D2, 2*D1, D2, 2*D1, t, s);
  564. }
  565. return SkCubicType::kLocalCusp;
  566. }
  567. } else {
  568. if (0 != D2) { // Cusp at T=infinity.
  569. if (t && s) {
  570. write_cubic_inflection_roots(D3, 3*D2, 1, 0, t, s); // T1=infinity.
  571. }
  572. return SkCubicType::kCuspAtInfinity;
  573. } else { // Degenerate.
  574. if (t && s) {
  575. write_cubic_inflection_roots(1, 0, 1, 0, t, s); // T0=T1=infinity.
  576. }
  577. return 0 != D3 ? SkCubicType::kQuadratic : SkCubicType::kLineOrPoint;
  578. }
  579. }
  580. }
  581. template <typename T> void bubble_sort(T array[], int count) {
  582. for (int i = count - 1; i > 0; --i)
  583. for (int j = i; j > 0; --j)
  584. if (array[j] < array[j-1])
  585. {
  586. T tmp(array[j]);
  587. array[j] = array[j-1];
  588. array[j-1] = tmp;
  589. }
  590. }
  591. /**
  592. * Given an array and count, remove all pair-wise duplicates from the array,
  593. * keeping the existing sorting, and return the new count
  594. */
  595. static int collaps_duplicates(SkScalar array[], int count) {
  596. for (int n = count; n > 1; --n) {
  597. if (array[0] == array[1]) {
  598. for (int i = 1; i < n; ++i) {
  599. array[i - 1] = array[i];
  600. }
  601. count -= 1;
  602. } else {
  603. array += 1;
  604. }
  605. }
  606. return count;
  607. }
  608. #ifdef SK_DEBUG
  609. #define TEST_COLLAPS_ENTRY(array) array, SK_ARRAY_COUNT(array)
  610. static void test_collaps_duplicates() {
  611. static bool gOnce;
  612. if (gOnce) { return; }
  613. gOnce = true;
  614. const SkScalar src0[] = { 0 };
  615. const SkScalar src1[] = { 0, 0 };
  616. const SkScalar src2[] = { 0, 1 };
  617. const SkScalar src3[] = { 0, 0, 0 };
  618. const SkScalar src4[] = { 0, 0, 1 };
  619. const SkScalar src5[] = { 0, 1, 1 };
  620. const SkScalar src6[] = { 0, 1, 2 };
  621. const struct {
  622. const SkScalar* fData;
  623. int fCount;
  624. int fCollapsedCount;
  625. } data[] = {
  626. { TEST_COLLAPS_ENTRY(src0), 1 },
  627. { TEST_COLLAPS_ENTRY(src1), 1 },
  628. { TEST_COLLAPS_ENTRY(src2), 2 },
  629. { TEST_COLLAPS_ENTRY(src3), 1 },
  630. { TEST_COLLAPS_ENTRY(src4), 2 },
  631. { TEST_COLLAPS_ENTRY(src5), 2 },
  632. { TEST_COLLAPS_ENTRY(src6), 3 },
  633. };
  634. for (size_t i = 0; i < SK_ARRAY_COUNT(data); ++i) {
  635. SkScalar dst[3];
  636. memcpy(dst, data[i].fData, data[i].fCount * sizeof(dst[0]));
  637. int count = collaps_duplicates(dst, data[i].fCount);
  638. SkASSERT(data[i].fCollapsedCount == count);
  639. for (int j = 1; j < count; ++j) {
  640. SkASSERT(dst[j-1] < dst[j]);
  641. }
  642. }
  643. }
  644. #endif
  645. static SkScalar SkScalarCubeRoot(SkScalar x) {
  646. return SkScalarPow(x, 0.3333333f);
  647. }
  648. /* Solve coeff(t) == 0, returning the number of roots that
  649. lie withing 0 < t < 1.
  650. coeff[0]t^3 + coeff[1]t^2 + coeff[2]t + coeff[3]
  651. Eliminates repeated roots (so that all tValues are distinct, and are always
  652. in increasing order.
  653. */
  654. static int solve_cubic_poly(const SkScalar coeff[4], SkScalar tValues[3]) {
  655. if (SkScalarNearlyZero(coeff[0])) { // we're just a quadratic
  656. return SkFindUnitQuadRoots(coeff[1], coeff[2], coeff[3], tValues);
  657. }
  658. SkScalar a, b, c, Q, R;
  659. {
  660. SkASSERT(coeff[0] != 0);
  661. SkScalar inva = SkScalarInvert(coeff[0]);
  662. a = coeff[1] * inva;
  663. b = coeff[2] * inva;
  664. c = coeff[3] * inva;
  665. }
  666. Q = (a*a - b*3) / 9;
  667. R = (2*a*a*a - 9*a*b + 27*c) / 54;
  668. SkScalar Q3 = Q * Q * Q;
  669. SkScalar R2MinusQ3 = R * R - Q3;
  670. SkScalar adiv3 = a / 3;
  671. if (R2MinusQ3 < 0) { // we have 3 real roots
  672. // the divide/root can, due to finite precisions, be slightly outside of -1...1
  673. SkScalar theta = SkScalarACos(SkScalarPin(R / SkScalarSqrt(Q3), -1, 1));
  674. SkScalar neg2RootQ = -2 * SkScalarSqrt(Q);
  675. tValues[0] = SkScalarPin(neg2RootQ * SkScalarCos(theta/3) - adiv3, 0, 1);
  676. tValues[1] = SkScalarPin(neg2RootQ * SkScalarCos((theta + 2*SK_ScalarPI)/3) - adiv3, 0, 1);
  677. tValues[2] = SkScalarPin(neg2RootQ * SkScalarCos((theta - 2*SK_ScalarPI)/3) - adiv3, 0, 1);
  678. SkDEBUGCODE(test_collaps_duplicates();)
  679. // now sort the roots
  680. bubble_sort(tValues, 3);
  681. return collaps_duplicates(tValues, 3);
  682. } else { // we have 1 real root
  683. SkScalar A = SkScalarAbs(R) + SkScalarSqrt(R2MinusQ3);
  684. A = SkScalarCubeRoot(A);
  685. if (R > 0) {
  686. A = -A;
  687. }
  688. if (A != 0) {
  689. A += Q / A;
  690. }
  691. tValues[0] = SkScalarPin(A - adiv3, 0, 1);
  692. return 1;
  693. }
  694. }
  695. /* Looking for F' dot F'' == 0
  696. A = b - a
  697. B = c - 2b + a
  698. C = d - 3c + 3b - a
  699. F' = 3Ct^2 + 6Bt + 3A
  700. F'' = 6Ct + 6B
  701. F' dot F'' -> CCt^3 + 3BCt^2 + (2BB + CA)t + AB
  702. */
  703. static void formulate_F1DotF2(const SkScalar src[], SkScalar coeff[4]) {
  704. SkScalar a = src[2] - src[0];
  705. SkScalar b = src[4] - 2 * src[2] + src[0];
  706. SkScalar c = src[6] + 3 * (src[2] - src[4]) - src[0];
  707. coeff[0] = c * c;
  708. coeff[1] = 3 * b * c;
  709. coeff[2] = 2 * b * b + c * a;
  710. coeff[3] = a * b;
  711. }
  712. /* Looking for F' dot F'' == 0
  713. A = b - a
  714. B = c - 2b + a
  715. C = d - 3c + 3b - a
  716. F' = 3Ct^2 + 6Bt + 3A
  717. F'' = 6Ct + 6B
  718. F' dot F'' -> CCt^3 + 3BCt^2 + (2BB + CA)t + AB
  719. */
  720. int SkFindCubicMaxCurvature(const SkPoint src[4], SkScalar tValues[3]) {
  721. SkScalar coeffX[4], coeffY[4];
  722. int i;
  723. formulate_F1DotF2(&src[0].fX, coeffX);
  724. formulate_F1DotF2(&src[0].fY, coeffY);
  725. for (i = 0; i < 4; i++) {
  726. coeffX[i] += coeffY[i];
  727. }
  728. int numRoots = solve_cubic_poly(coeffX, tValues);
  729. // now remove extrema where the curvature is zero (mins)
  730. // !!!! need a test for this !!!!
  731. return numRoots;
  732. }
  733. int SkChopCubicAtMaxCurvature(const SkPoint src[4], SkPoint dst[13],
  734. SkScalar tValues[3]) {
  735. SkScalar t_storage[3];
  736. if (tValues == nullptr) {
  737. tValues = t_storage;
  738. }
  739. SkScalar roots[3];
  740. int rootCount = SkFindCubicMaxCurvature(src, roots);
  741. // Throw out values not inside 0..1.
  742. int count = 0;
  743. for (int i = 0; i < rootCount; ++i) {
  744. if (0 < roots[i] && roots[i] < 1) {
  745. tValues[count++] = roots[i];
  746. }
  747. }
  748. if (dst) {
  749. if (count == 0) {
  750. memcpy(dst, src, 4 * sizeof(SkPoint));
  751. } else {
  752. SkChopCubicAt(src, dst, tValues, count);
  753. }
  754. }
  755. return count + 1;
  756. }
  757. // Returns a constant proportional to the dimensions of the cubic.
  758. // Constant found through experimentation -- maybe there's a better way....
  759. static SkScalar calc_cubic_precision(const SkPoint src[4]) {
  760. return (SkPointPriv::DistanceToSqd(src[1], src[0]) + SkPointPriv::DistanceToSqd(src[2], src[1])
  761. + SkPointPriv::DistanceToSqd(src[3], src[2])) * 1e-8f;
  762. }
  763. // Returns true if both points src[testIndex], src[testIndex+1] are in the same half plane defined
  764. // by the line segment src[lineIndex], src[lineIndex+1].
  765. static bool on_same_side(const SkPoint src[4], int testIndex, int lineIndex) {
  766. SkPoint origin = src[lineIndex];
  767. SkVector line = src[lineIndex + 1] - origin;
  768. SkScalar crosses[2];
  769. for (int index = 0; index < 2; ++index) {
  770. SkVector testLine = src[testIndex + index] - origin;
  771. crosses[index] = line.cross(testLine);
  772. }
  773. return crosses[0] * crosses[1] >= 0;
  774. }
  775. // Return location (in t) of cubic cusp, if there is one.
  776. // Note that classify cubic code does not reliably return all cusp'd cubics, so
  777. // it is not called here.
  778. SkScalar SkFindCubicCusp(const SkPoint src[4]) {
  779. // When the adjacent control point matches the end point, it behaves as if
  780. // the cubic has a cusp: there's a point of max curvature where the derivative
  781. // goes to zero. Ideally, this would be where t is zero or one, but math
  782. // error makes not so. It is not uncommon to create cubics this way; skip them.
  783. if (src[0] == src[1]) {
  784. return -1;
  785. }
  786. if (src[2] == src[3]) {
  787. return -1;
  788. }
  789. // Cubics only have a cusp if the line segments formed by the control and end points cross.
  790. // Detect crossing if line ends are on opposite sides of plane formed by the other line.
  791. if (on_same_side(src, 0, 2) || on_same_side(src, 2, 0)) {
  792. return -1;
  793. }
  794. // Cubics may have multiple points of maximum curvature, although at most only
  795. // one is a cusp.
  796. SkScalar maxCurvature[3];
  797. int roots = SkFindCubicMaxCurvature(src, maxCurvature);
  798. for (int index = 0; index < roots; ++index) {
  799. SkScalar testT = maxCurvature[index];
  800. if (0 >= testT || testT >= 1) { // no need to consider max curvature on the end
  801. continue;
  802. }
  803. // A cusp is at the max curvature, and also has a derivative close to zero.
  804. // Choose the 'close to zero' meaning by comparing the derivative length
  805. // with the overall cubic size.
  806. SkVector dPt = eval_cubic_derivative(src, testT);
  807. SkScalar dPtMagnitude = SkPointPriv::LengthSqd(dPt);
  808. SkScalar precision = calc_cubic_precision(src);
  809. if (dPtMagnitude < precision) {
  810. // All three max curvature t values may be close to the cusp;
  811. // return the first one.
  812. return testT;
  813. }
  814. }
  815. return -1;
  816. }
  817. #include "src/pathops/SkPathOpsCubic.h"
  818. typedef int (SkDCubic::*InterceptProc)(double intercept, double roots[3]) const;
  819. static bool cubic_dchop_at_intercept(const SkPoint src[4], SkScalar intercept, SkPoint dst[7],
  820. InterceptProc method) {
  821. SkDCubic cubic;
  822. double roots[3];
  823. int count = (cubic.set(src).*method)(intercept, roots);
  824. if (count > 0) {
  825. SkDCubicPair pair = cubic.chopAt(roots[0]);
  826. for (int i = 0; i < 7; ++i) {
  827. dst[i] = pair.pts[i].asSkPoint();
  828. }
  829. return true;
  830. }
  831. return false;
  832. }
  833. bool SkChopMonoCubicAtY(SkPoint src[4], SkScalar y, SkPoint dst[7]) {
  834. return cubic_dchop_at_intercept(src, y, dst, &SkDCubic::horizontalIntersect);
  835. }
  836. bool SkChopMonoCubicAtX(SkPoint src[4], SkScalar x, SkPoint dst[7]) {
  837. return cubic_dchop_at_intercept(src, x, dst, &SkDCubic::verticalIntersect);
  838. }
  839. ///////////////////////////////////////////////////////////////////////////////
  840. //
  841. // NURB representation for conics. Helpful explanations at:
  842. //
  843. // http://citeseerx.ist.psu.edu/viewdoc/
  844. // download?doi=10.1.1.44.5740&rep=rep1&type=ps
  845. // and
  846. // http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/NURBS/RB-conics.html
  847. //
  848. // F = (A (1 - t)^2 + C t^2 + 2 B (1 - t) t w)
  849. // ------------------------------------------
  850. // ((1 - t)^2 + t^2 + 2 (1 - t) t w)
  851. //
  852. // = {t^2 (P0 + P2 - 2 P1 w), t (-2 P0 + 2 P1 w), P0}
  853. // ------------------------------------------------
  854. // {t^2 (2 - 2 w), t (-2 + 2 w), 1}
  855. //
  856. // F' = 2 (C t (1 + t (-1 + w)) - A (-1 + t) (t (-1 + w) - w) + B (1 - 2 t) w)
  857. //
  858. // t^2 : (2 P0 - 2 P2 - 2 P0 w + 2 P2 w)
  859. // t^1 : (-2 P0 + 2 P2 + 4 P0 w - 4 P1 w)
  860. // t^0 : -2 P0 w + 2 P1 w
  861. //
  862. // We disregard magnitude, so we can freely ignore the denominator of F', and
  863. // divide the numerator by 2
  864. //
  865. // coeff[0] for t^2
  866. // coeff[1] for t^1
  867. // coeff[2] for t^0
  868. //
  869. static void conic_deriv_coeff(const SkScalar src[],
  870. SkScalar w,
  871. SkScalar coeff[3]) {
  872. const SkScalar P20 = src[4] - src[0];
  873. const SkScalar P10 = src[2] - src[0];
  874. const SkScalar wP10 = w * P10;
  875. coeff[0] = w * P20 - P20;
  876. coeff[1] = P20 - 2 * wP10;
  877. coeff[2] = wP10;
  878. }
  879. static bool conic_find_extrema(const SkScalar src[], SkScalar w, SkScalar* t) {
  880. SkScalar coeff[3];
  881. conic_deriv_coeff(src, w, coeff);
  882. SkScalar tValues[2];
  883. int roots = SkFindUnitQuadRoots(coeff[0], coeff[1], coeff[2], tValues);
  884. SkASSERT(0 == roots || 1 == roots);
  885. if (1 == roots) {
  886. *t = tValues[0];
  887. return true;
  888. }
  889. return false;
  890. }
  891. // We only interpolate one dimension at a time (the first, at +0, +3, +6).
  892. static void p3d_interp(const SkScalar src[7], SkScalar dst[7], SkScalar t) {
  893. SkScalar ab = SkScalarInterp(src[0], src[3], t);
  894. SkScalar bc = SkScalarInterp(src[3], src[6], t);
  895. dst[0] = ab;
  896. dst[3] = SkScalarInterp(ab, bc, t);
  897. dst[6] = bc;
  898. }
  899. static void ratquad_mapTo3D(const SkPoint src[3], SkScalar w, SkPoint3 dst[3]) {
  900. dst[0].set(src[0].fX * 1, src[0].fY * 1, 1);
  901. dst[1].set(src[1].fX * w, src[1].fY * w, w);
  902. dst[2].set(src[2].fX * 1, src[2].fY * 1, 1);
  903. }
  904. static SkPoint project_down(const SkPoint3& src) {
  905. return {src.fX / src.fZ, src.fY / src.fZ};
  906. }
  907. // return false if infinity or NaN is generated; caller must check
  908. bool SkConic::chopAt(SkScalar t, SkConic dst[2]) const {
  909. SkPoint3 tmp[3], tmp2[3];
  910. ratquad_mapTo3D(fPts, fW, tmp);
  911. p3d_interp(&tmp[0].fX, &tmp2[0].fX, t);
  912. p3d_interp(&tmp[0].fY, &tmp2[0].fY, t);
  913. p3d_interp(&tmp[0].fZ, &tmp2[0].fZ, t);
  914. dst[0].fPts[0] = fPts[0];
  915. dst[0].fPts[1] = project_down(tmp2[0]);
  916. dst[0].fPts[2] = project_down(tmp2[1]); dst[1].fPts[0] = dst[0].fPts[2];
  917. dst[1].fPts[1] = project_down(tmp2[2]);
  918. dst[1].fPts[2] = fPts[2];
  919. // to put in "standard form", where w0 and w2 are both 1, we compute the
  920. // new w1 as sqrt(w1*w1/w0*w2)
  921. // or
  922. // w1 /= sqrt(w0*w2)
  923. //
  924. // However, in our case, we know that for dst[0]:
  925. // w0 == 1, and for dst[1], w2 == 1
  926. //
  927. SkScalar root = SkScalarSqrt(tmp2[1].fZ);
  928. dst[0].fW = tmp2[0].fZ / root;
  929. dst[1].fW = tmp2[2].fZ / root;
  930. SkASSERT(sizeof(dst[0]) == sizeof(SkScalar) * 7);
  931. SkASSERT(0 == offsetof(SkConic, fPts[0].fX));
  932. return SkScalarsAreFinite(&dst[0].fPts[0].fX, 7 * 2);
  933. }
  934. void SkConic::chopAt(SkScalar t1, SkScalar t2, SkConic* dst) const {
  935. if (0 == t1 || 1 == t2) {
  936. if (0 == t1 && 1 == t2) {
  937. *dst = *this;
  938. return;
  939. } else {
  940. SkConic pair[2];
  941. if (this->chopAt(t1 ? t1 : t2, pair)) {
  942. *dst = pair[SkToBool(t1)];
  943. return;
  944. }
  945. }
  946. }
  947. SkConicCoeff coeff(*this);
  948. Sk2s tt1(t1);
  949. Sk2s aXY = coeff.fNumer.eval(tt1);
  950. Sk2s aZZ = coeff.fDenom.eval(tt1);
  951. Sk2s midTT((t1 + t2) / 2);
  952. Sk2s dXY = coeff.fNumer.eval(midTT);
  953. Sk2s dZZ = coeff.fDenom.eval(midTT);
  954. Sk2s tt2(t2);
  955. Sk2s cXY = coeff.fNumer.eval(tt2);
  956. Sk2s cZZ = coeff.fDenom.eval(tt2);
  957. Sk2s bXY = times_2(dXY) - (aXY + cXY) * Sk2s(0.5f);
  958. Sk2s bZZ = times_2(dZZ) - (aZZ + cZZ) * Sk2s(0.5f);
  959. dst->fPts[0] = to_point(aXY / aZZ);
  960. dst->fPts[1] = to_point(bXY / bZZ);
  961. dst->fPts[2] = to_point(cXY / cZZ);
  962. Sk2s ww = bZZ / (aZZ * cZZ).sqrt();
  963. dst->fW = ww[0];
  964. }
  965. SkPoint SkConic::evalAt(SkScalar t) const {
  966. return to_point(SkConicCoeff(*this).eval(t));
  967. }
  968. SkVector SkConic::evalTangentAt(SkScalar t) const {
  969. // The derivative equation returns a zero tangent vector when t is 0 or 1,
  970. // and the control point is equal to the end point.
  971. // In this case, use the conic endpoints to compute the tangent.
  972. if ((t == 0 && fPts[0] == fPts[1]) || (t == 1 && fPts[1] == fPts[2])) {
  973. return fPts[2] - fPts[0];
  974. }
  975. Sk2s p0 = from_point(fPts[0]);
  976. Sk2s p1 = from_point(fPts[1]);
  977. Sk2s p2 = from_point(fPts[2]);
  978. Sk2s ww(fW);
  979. Sk2s p20 = p2 - p0;
  980. Sk2s p10 = p1 - p0;
  981. Sk2s C = ww * p10;
  982. Sk2s A = ww * p20 - p20;
  983. Sk2s B = p20 - C - C;
  984. return to_vector(SkQuadCoeff(A, B, C).eval(t));
  985. }
  986. void SkConic::evalAt(SkScalar t, SkPoint* pt, SkVector* tangent) const {
  987. SkASSERT(t >= 0 && t <= SK_Scalar1);
  988. if (pt) {
  989. *pt = this->evalAt(t);
  990. }
  991. if (tangent) {
  992. *tangent = this->evalTangentAt(t);
  993. }
  994. }
  995. static SkScalar subdivide_w_value(SkScalar w) {
  996. return SkScalarSqrt(SK_ScalarHalf + w * SK_ScalarHalf);
  997. }
  998. void SkConic::chop(SkConic * SK_RESTRICT dst) const {
  999. Sk2s scale = Sk2s(SkScalarInvert(SK_Scalar1 + fW));
  1000. SkScalar newW = subdivide_w_value(fW);
  1001. Sk2s p0 = from_point(fPts[0]);
  1002. Sk2s p1 = from_point(fPts[1]);
  1003. Sk2s p2 = from_point(fPts[2]);
  1004. Sk2s ww(fW);
  1005. Sk2s wp1 = ww * p1;
  1006. Sk2s m = (p0 + times_2(wp1) + p2) * scale * Sk2s(0.5f);
  1007. SkPoint mPt = to_point(m);
  1008. if (!mPt.isFinite()) {
  1009. double w_d = fW;
  1010. double w_2 = w_d * 2;
  1011. double scale_half = 1 / (1 + w_d) * 0.5;
  1012. mPt.fX = SkDoubleToScalar((fPts[0].fX + w_2 * fPts[1].fX + fPts[2].fX) * scale_half);
  1013. mPt.fY = SkDoubleToScalar((fPts[0].fY + w_2 * fPts[1].fY + fPts[2].fY) * scale_half);
  1014. }
  1015. dst[0].fPts[0] = fPts[0];
  1016. dst[0].fPts[1] = to_point((p0 + wp1) * scale);
  1017. dst[0].fPts[2] = dst[1].fPts[0] = mPt;
  1018. dst[1].fPts[1] = to_point((wp1 + p2) * scale);
  1019. dst[1].fPts[2] = fPts[2];
  1020. dst[0].fW = dst[1].fW = newW;
  1021. }
  1022. /*
  1023. * "High order approximation of conic sections by quadratic splines"
  1024. * by Michael Floater, 1993
  1025. */
  1026. #define AS_QUAD_ERROR_SETUP \
  1027. SkScalar a = fW - 1; \
  1028. SkScalar k = a / (4 * (2 + a)); \
  1029. SkScalar x = k * (fPts[0].fX - 2 * fPts[1].fX + fPts[2].fX); \
  1030. SkScalar y = k * (fPts[0].fY - 2 * fPts[1].fY + fPts[2].fY);
  1031. void SkConic::computeAsQuadError(SkVector* err) const {
  1032. AS_QUAD_ERROR_SETUP
  1033. err->set(x, y);
  1034. }
  1035. bool SkConic::asQuadTol(SkScalar tol) const {
  1036. AS_QUAD_ERROR_SETUP
  1037. return (x * x + y * y) <= tol * tol;
  1038. }
  1039. // Limit the number of suggested quads to approximate a conic
  1040. #define kMaxConicToQuadPOW2 5
  1041. int SkConic::computeQuadPOW2(SkScalar tol) const {
  1042. if (tol < 0 || !SkScalarIsFinite(tol) || !SkPointPriv::AreFinite(fPts, 3)) {
  1043. return 0;
  1044. }
  1045. AS_QUAD_ERROR_SETUP
  1046. SkScalar error = SkScalarSqrt(x * x + y * y);
  1047. int pow2;
  1048. for (pow2 = 0; pow2 < kMaxConicToQuadPOW2; ++pow2) {
  1049. if (error <= tol) {
  1050. break;
  1051. }
  1052. error *= 0.25f;
  1053. }
  1054. // float version -- using ceil gives the same results as the above.
  1055. if (false) {
  1056. SkScalar err = SkScalarSqrt(x * x + y * y);
  1057. if (err <= tol) {
  1058. return 0;
  1059. }
  1060. SkScalar tol2 = tol * tol;
  1061. if (tol2 == 0) {
  1062. return kMaxConicToQuadPOW2;
  1063. }
  1064. SkScalar fpow2 = SkScalarLog2((x * x + y * y) / tol2) * 0.25f;
  1065. int altPow2 = SkScalarCeilToInt(fpow2);
  1066. if (altPow2 != pow2) {
  1067. SkDebugf("pow2 %d altPow2 %d fbits %g err %g tol %g\n", pow2, altPow2, fpow2, err, tol);
  1068. }
  1069. pow2 = altPow2;
  1070. }
  1071. return pow2;
  1072. }
  1073. // This was originally developed and tested for pathops: see SkOpTypes.h
  1074. // returns true if (a <= b <= c) || (a >= b >= c)
  1075. static bool between(SkScalar a, SkScalar b, SkScalar c) {
  1076. return (a - b) * (c - b) <= 0;
  1077. }
  1078. static SkPoint* subdivide(const SkConic& src, SkPoint pts[], int level) {
  1079. SkASSERT(level >= 0);
  1080. if (0 == level) {
  1081. memcpy(pts, &src.fPts[1], 2 * sizeof(SkPoint));
  1082. return pts + 2;
  1083. } else {
  1084. SkConic dst[2];
  1085. src.chop(dst);
  1086. const SkScalar startY = src.fPts[0].fY;
  1087. SkScalar endY = src.fPts[2].fY;
  1088. if (between(startY, src.fPts[1].fY, endY)) {
  1089. // If the input is monotonic and the output is not, the scan converter hangs.
  1090. // Ensure that the chopped conics maintain their y-order.
  1091. SkScalar midY = dst[0].fPts[2].fY;
  1092. if (!between(startY, midY, endY)) {
  1093. // If the computed midpoint is outside the ends, move it to the closer one.
  1094. SkScalar closerY = SkTAbs(midY - startY) < SkTAbs(midY - endY) ? startY : endY;
  1095. dst[0].fPts[2].fY = dst[1].fPts[0].fY = closerY;
  1096. }
  1097. if (!between(startY, dst[0].fPts[1].fY, dst[0].fPts[2].fY)) {
  1098. // If the 1st control is not between the start and end, put it at the start.
  1099. // This also reduces the quad to a line.
  1100. dst[0].fPts[1].fY = startY;
  1101. }
  1102. if (!between(dst[1].fPts[0].fY, dst[1].fPts[1].fY, endY)) {
  1103. // If the 2nd control is not between the start and end, put it at the end.
  1104. // This also reduces the quad to a line.
  1105. dst[1].fPts[1].fY = endY;
  1106. }
  1107. // Verify that all five points are in order.
  1108. SkASSERT(between(startY, dst[0].fPts[1].fY, dst[0].fPts[2].fY));
  1109. SkASSERT(between(dst[0].fPts[1].fY, dst[0].fPts[2].fY, dst[1].fPts[1].fY));
  1110. SkASSERT(between(dst[0].fPts[2].fY, dst[1].fPts[1].fY, endY));
  1111. }
  1112. --level;
  1113. pts = subdivide(dst[0], pts, level);
  1114. return subdivide(dst[1], pts, level);
  1115. }
  1116. }
  1117. int SkConic::chopIntoQuadsPOW2(SkPoint pts[], int pow2) const {
  1118. SkASSERT(pow2 >= 0);
  1119. *pts = fPts[0];
  1120. SkDEBUGCODE(SkPoint* endPts);
  1121. if (pow2 == kMaxConicToQuadPOW2) { // If an extreme weight generates many quads ...
  1122. SkConic dst[2];
  1123. this->chop(dst);
  1124. // check to see if the first chop generates a pair of lines
  1125. if (SkPointPriv::EqualsWithinTolerance(dst[0].fPts[1], dst[0].fPts[2]) &&
  1126. SkPointPriv::EqualsWithinTolerance(dst[1].fPts[0], dst[1].fPts[1])) {
  1127. pts[1] = pts[2] = pts[3] = dst[0].fPts[1]; // set ctrl == end to make lines
  1128. pts[4] = dst[1].fPts[2];
  1129. pow2 = 1;
  1130. SkDEBUGCODE(endPts = &pts[5]);
  1131. goto commonFinitePtCheck;
  1132. }
  1133. }
  1134. SkDEBUGCODE(endPts = ) subdivide(*this, pts + 1, pow2);
  1135. commonFinitePtCheck:
  1136. const int quadCount = 1 << pow2;
  1137. const int ptCount = 2 * quadCount + 1;
  1138. SkASSERT(endPts - pts == ptCount);
  1139. if (!SkPointPriv::AreFinite(pts, ptCount)) {
  1140. // if we generated a non-finite, pin ourselves to the middle of the hull,
  1141. // as our first and last are already on the first/last pts of the hull.
  1142. for (int i = 1; i < ptCount - 1; ++i) {
  1143. pts[i] = fPts[1];
  1144. }
  1145. }
  1146. return 1 << pow2;
  1147. }
  1148. bool SkConic::findXExtrema(SkScalar* t) const {
  1149. return conic_find_extrema(&fPts[0].fX, fW, t);
  1150. }
  1151. bool SkConic::findYExtrema(SkScalar* t) const {
  1152. return conic_find_extrema(&fPts[0].fY, fW, t);
  1153. }
  1154. bool SkConic::chopAtXExtrema(SkConic dst[2]) const {
  1155. SkScalar t;
  1156. if (this->findXExtrema(&t)) {
  1157. if (!this->chopAt(t, dst)) {
  1158. // if chop can't return finite values, don't chop
  1159. return false;
  1160. }
  1161. // now clean-up the middle, since we know t was meant to be at
  1162. // an X-extrema
  1163. SkScalar value = dst[0].fPts[2].fX;
  1164. dst[0].fPts[1].fX = value;
  1165. dst[1].fPts[0].fX = value;
  1166. dst[1].fPts[1].fX = value;
  1167. return true;
  1168. }
  1169. return false;
  1170. }
  1171. bool SkConic::chopAtYExtrema(SkConic dst[2]) const {
  1172. SkScalar t;
  1173. if (this->findYExtrema(&t)) {
  1174. if (!this->chopAt(t, dst)) {
  1175. // if chop can't return finite values, don't chop
  1176. return false;
  1177. }
  1178. // now clean-up the middle, since we know t was meant to be at
  1179. // an Y-extrema
  1180. SkScalar value = dst[0].fPts[2].fY;
  1181. dst[0].fPts[1].fY = value;
  1182. dst[1].fPts[0].fY = value;
  1183. dst[1].fPts[1].fY = value;
  1184. return true;
  1185. }
  1186. return false;
  1187. }
  1188. void SkConic::computeTightBounds(SkRect* bounds) const {
  1189. SkPoint pts[4];
  1190. pts[0] = fPts[0];
  1191. pts[1] = fPts[2];
  1192. int count = 2;
  1193. SkScalar t;
  1194. if (this->findXExtrema(&t)) {
  1195. this->evalAt(t, &pts[count++]);
  1196. }
  1197. if (this->findYExtrema(&t)) {
  1198. this->evalAt(t, &pts[count++]);
  1199. }
  1200. bounds->set(pts, count);
  1201. }
  1202. void SkConic::computeFastBounds(SkRect* bounds) const {
  1203. bounds->set(fPts, 3);
  1204. }
  1205. #if 0 // unimplemented
  1206. bool SkConic::findMaxCurvature(SkScalar* t) const {
  1207. // TODO: Implement me
  1208. return false;
  1209. }
  1210. #endif
  1211. SkScalar SkConic::TransformW(const SkPoint pts[], SkScalar w, const SkMatrix& matrix) {
  1212. if (!matrix.hasPerspective()) {
  1213. return w;
  1214. }
  1215. SkPoint3 src[3], dst[3];
  1216. ratquad_mapTo3D(pts, w, src);
  1217. matrix.mapHomogeneousPoints(dst, src, 3);
  1218. // w' = sqrt(w1*w1/w0*w2)
  1219. // use doubles temporarily, to handle small numer/denom
  1220. double w0 = dst[0].fZ;
  1221. double w1 = dst[1].fZ;
  1222. double w2 = dst[2].fZ;
  1223. return sk_double_to_float(sqrt(sk_ieee_double_divide(w1 * w1, w0 * w2)));
  1224. }
  1225. int SkConic::BuildUnitArc(const SkVector& uStart, const SkVector& uStop, SkRotationDirection dir,
  1226. const SkMatrix* userMatrix, SkConic dst[kMaxConicsForArc]) {
  1227. // rotate by x,y so that uStart is (1.0)
  1228. SkScalar x = SkPoint::DotProduct(uStart, uStop);
  1229. SkScalar y = SkPoint::CrossProduct(uStart, uStop);
  1230. SkScalar absY = SkScalarAbs(y);
  1231. // check for (effectively) coincident vectors
  1232. // this can happen if our angle is nearly 0 or nearly 180 (y == 0)
  1233. // ... we use the dot-prod to distinguish between 0 and 180 (x > 0)
  1234. if (absY <= SK_ScalarNearlyZero && x > 0 && ((y >= 0 && kCW_SkRotationDirection == dir) ||
  1235. (y <= 0 && kCCW_SkRotationDirection == dir))) {
  1236. return 0;
  1237. }
  1238. if (dir == kCCW_SkRotationDirection) {
  1239. y = -y;
  1240. }
  1241. // We decide to use 1-conic per quadrant of a circle. What quadrant does [xy] lie in?
  1242. // 0 == [0 .. 90)
  1243. // 1 == [90 ..180)
  1244. // 2 == [180..270)
  1245. // 3 == [270..360)
  1246. //
  1247. int quadrant = 0;
  1248. if (0 == y) {
  1249. quadrant = 2; // 180
  1250. SkASSERT(SkScalarAbs(x + SK_Scalar1) <= SK_ScalarNearlyZero);
  1251. } else if (0 == x) {
  1252. SkASSERT(absY - SK_Scalar1 <= SK_ScalarNearlyZero);
  1253. quadrant = y > 0 ? 1 : 3; // 90 : 270
  1254. } else {
  1255. if (y < 0) {
  1256. quadrant += 2;
  1257. }
  1258. if ((x < 0) != (y < 0)) {
  1259. quadrant += 1;
  1260. }
  1261. }
  1262. const SkPoint quadrantPts[] = {
  1263. { 1, 0 }, { 1, 1 }, { 0, 1 }, { -1, 1 }, { -1, 0 }, { -1, -1 }, { 0, -1 }, { 1, -1 }
  1264. };
  1265. const SkScalar quadrantWeight = SK_ScalarRoot2Over2;
  1266. int conicCount = quadrant;
  1267. for (int i = 0; i < conicCount; ++i) {
  1268. dst[i].set(&quadrantPts[i * 2], quadrantWeight);
  1269. }
  1270. // Now compute any remaing (sub-90-degree) arc for the last conic
  1271. const SkPoint finalP = { x, y };
  1272. const SkPoint& lastQ = quadrantPts[quadrant * 2]; // will already be a unit-vector
  1273. const SkScalar dot = SkVector::DotProduct(lastQ, finalP);
  1274. SkASSERT(0 <= dot && dot <= SK_Scalar1 + SK_ScalarNearlyZero);
  1275. if (dot < 1) {
  1276. SkVector offCurve = { lastQ.x() + x, lastQ.y() + y };
  1277. // compute the bisector vector, and then rescale to be the off-curve point.
  1278. // we compute its length from cos(theta/2) = length / 1, using half-angle identity we get
  1279. // length = sqrt(2 / (1 + cos(theta)). We already have cos() when to computed the dot.
  1280. // This is nice, since our computed weight is cos(theta/2) as well!
  1281. //
  1282. const SkScalar cosThetaOver2 = SkScalarSqrt((1 + dot) / 2);
  1283. offCurve.setLength(SkScalarInvert(cosThetaOver2));
  1284. if (!SkPointPriv::EqualsWithinTolerance(lastQ, offCurve)) {
  1285. dst[conicCount].set(lastQ, offCurve, finalP, cosThetaOver2);
  1286. conicCount += 1;
  1287. }
  1288. }
  1289. // now handle counter-clockwise and the initial unitStart rotation
  1290. SkMatrix matrix;
  1291. matrix.setSinCos(uStart.fY, uStart.fX);
  1292. if (dir == kCCW_SkRotationDirection) {
  1293. matrix.preScale(SK_Scalar1, -SK_Scalar1);
  1294. }
  1295. if (userMatrix) {
  1296. matrix.postConcat(*userMatrix);
  1297. }
  1298. for (int i = 0; i < conicCount; ++i) {
  1299. matrix.mapPoints(dst[i].fPts, 3);
  1300. }
  1301. return conicCount;
  1302. }