sdf.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. /*
  2. Copyright (C) 2014 Mikko Mononen ([email protected])
  3. Copyright (C) 2009-2012 Stefan Gustavson ([email protected])
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. */
  20. #ifndef SDF_H
  21. #define SDF_H
  22. // Sweep-and-update Euclidean distance transform of an antialised image for contour textures.
  23. // Based on edtaa3func.c by Stefan Gustavson.
  24. //
  25. // White (255) pixels are treated as object pixels, zero pixels are treated as background.
  26. // An attempt is made to treat antialiased edges correctly. The input image must have
  27. // pixels in the range [0,255], and the antialiased image should be a box-filter
  28. // sampling of the ideal, crisp edge. If the antialias region is more than 1 pixel wide,
  29. // the result from this transform will be inaccurate.
  30. // Pixels at image border are not calculated and are set to 0.
  31. //
  32. // The output distance field is encoded as bytes, where 0 = radius (outside) and 255 = -radius (inside).
  33. // Input and output can be the same buffer.
  34. // out - Output of the distance transform, one byte per pixel.
  35. // outstride - Bytes per row on output image.
  36. // radius - The radius of the distance field narrow band in pixels.
  37. // img - Input image, one byte per pixel.
  38. // width - Width if the image.
  39. // height - Height if the image.
  40. // stride - Bytes per row on input image.
  41. int sdfBuildDistanceField(unsigned char* out, int outstride, float radius,
  42. const unsigned char* img, int width, int height, int stride);
  43. // Same as distXform, but does not allocate any memory.
  44. // The 'temp' array should be enough to fit width * height * sizeof(float) * 3 bytes.
  45. void sdfBuildDistanceFieldNoAlloc(unsigned char* out, int outstride, float radius,
  46. const unsigned char* img, int width, int height, int stride,
  47. unsigned char* temp);
  48. // This function converts the antialiased image where each pixel represents coverage (box-filter
  49. // sampling of the ideal, crisp edge) to a distance field with narrow band radius of sqrt(2).
  50. // This is the fastest way to turn antialised image to contour texture. This function is good
  51. // if you don't need the distance field for effects (i.e. fat outline or dropshadow).
  52. // Input and output buffers must be different.
  53. // out - Output of the distance transform, one byte per pixel.
  54. // outstride - Bytes per row on output image.
  55. // img - Input image, one byte per pixel.
  56. // width - Width if the image.
  57. // height - Height if the image.
  58. // stride - Bytes per row on input image.
  59. void sdfCoverageToDistanceField(unsigned char* out, int outstride,
  60. const unsigned char* img, int width, int height, int stride);
  61. #endif //SDF_H
  62. #ifdef SDF_IMPLEMENTATION
  63. #include <math.h>
  64. #include <stdlib.h>
  65. #define SDF_MAX_PASSES 10 // Maximum number of distance transform passes
  66. #define SDF_SLACK 0.001f // Controls how much smaller the neighbour value must be to cosnider, too small slack increse iteration count.
  67. #define SDF_SQRT2 1.4142136f // sqrt(2)
  68. #define SDF_BIG 1e+37f // Big value used to initialize the distance field.
  69. static float sdf__clamp01(float x)
  70. {
  71. return x < 0.0f ? 0.0f : (x > 1.0f ? 1.0f : x);
  72. }
  73. void sdfCoverageToDistanceField(unsigned char* out, int outstride,
  74. const unsigned char* img, int width, int height, int stride)
  75. {
  76. int x, y;
  77. // Zero out borders
  78. for (x = 0; x < width; x++)
  79. out[x] = 0;
  80. for (y = 1; y < height; y++) {
  81. out[y*outstride] = 0;
  82. out[width-1+y*outstride] = 0;
  83. }
  84. for (x = 0; x < width; x++)
  85. out[x+(height-1)*outstride] = 0;
  86. for (y = 1; y < height-1; y++) {
  87. for (x = 1; x < width-1; x++) {
  88. int k = x + y * stride;
  89. float d, gx, gy, glen, a, a1;
  90. // Skip flat areas.
  91. if (img[k] == 255) {
  92. out[x+y*outstride] = 255;
  93. continue;
  94. }
  95. if (img[k] == 0) {
  96. // Special handling for cases where full opaque pixels are next to full transparent pixels.
  97. // See: https://github.com/memononen/SDF/issues/2
  98. int he = img[k-1] == 255 || img[k+1] == 255;
  99. int ve = img[k-stride] == 255 || img[k+stride] == 255;
  100. if (!he && !ve) {
  101. out[x+y*outstride] = 0;
  102. continue;
  103. }
  104. }
  105. gx = -(float)img[k-stride-1] - SDF_SQRT2*(float)img[k-1] - (float)img[k+stride-1] + (float)img[k-stride+1] + SDF_SQRT2*(float)img[k+1] + (float)img[k+stride+1];
  106. gy = -(float)img[k-stride-1] - SDF_SQRT2*(float)img[k-stride] - (float)img[k-stride+1] + (float)img[k+stride-1] + SDF_SQRT2*(float)img[k+stride] + (float)img[k+stride+1];
  107. a = (float)img[k]/255.0f;
  108. gx = fabsf(gx);
  109. gy = fabsf(gy);
  110. if (gx < 0.0001f || gy < 0.000f) {
  111. d = (0.5f - a) * SDF_SQRT2;
  112. } else {
  113. glen = gx*gx + gy*gy;
  114. glen = 1.0f / sqrtf(glen);
  115. gx *= glen;
  116. gy *= glen;
  117. if (gx < gy) {
  118. float temp = gx;
  119. gx = gy;
  120. gy = temp;
  121. }
  122. a1 = 0.5f*gy/gx;
  123. if (a < a1) { // 0 <= a < a1
  124. d = 0.5f*(gx + gy) - sqrtf(2.0f*gx*gy*a);
  125. } else if (a < (1.0-a1)) { // a1 <= a <= 1-a1
  126. d = (0.5f-a)*gx;
  127. } else { // 1-a1 < a <= 1
  128. d = -0.5f*(gx + gy) + sqrt(2.0f*gx*gy*(1.0f-a));
  129. }
  130. }
  131. d *= 1.0f / SDF_SQRT2;
  132. out[x+y*outstride] = (unsigned char)(sdf__clamp01(0.5f - d) * 255.0f);
  133. }
  134. }
  135. }
  136. static float sdf__edgedf(float gx, float gy, float a)
  137. {
  138. float df, a1;
  139. if ((gx == 0) || (gy == 0)) {
  140. // Either A) gu or gv are zero, or B) both
  141. // Linear approximation is A) correct or B) a fair guess
  142. df = 0.5f - a;
  143. } else {
  144. // Everything is symmetric wrt sign and transposition,
  145. // so move to first octant (gx>=0, gy>=0, gx>=gy) to
  146. // avoid handling all possible edge directions.
  147. gx = fabsf(gx);
  148. gy = fabsf(gy);
  149. if (gx < gy) {
  150. float temp = gx;
  151. gx = gy;
  152. gy = temp;
  153. }
  154. a1 = 0.5f*gy/gx;
  155. if (a < a1) { // 0 <= a < a1
  156. df = 0.5f*(gx + gy) - sqrtf(2.0f*gx*gy*a);
  157. } else if (a < (1.0-a1)) { // a1 <= a <= 1-a1
  158. df = (0.5f-a)*gx;
  159. } else { // 1-a1 < a <= 1
  160. df = -0.5f*(gx + gy) + sqrt(2.0f*gx*gy*(1.0f-a));
  161. }
  162. }
  163. return df;
  164. }
  165. struct SDFpoint {
  166. float x,y;
  167. };
  168. static float sdf__distsqr(struct SDFpoint* a, struct SDFpoint* b)
  169. {
  170. float dx = b->x - a->x, dy = b->y - a->y;
  171. return dx*dx + dy*dy;
  172. }
  173. void sdfBuildDistanceFieldNoAlloc(unsigned char* out, int outstride, float radius,
  174. const unsigned char* img, int width, int height, int stride,
  175. unsigned char* temp)
  176. {
  177. int i, x, y, pass;
  178. float scale;
  179. float* tdist = (float*)&temp[0];
  180. struct SDFpoint* tpt = (struct SDFpoint*)&temp[width * height * sizeof(float)];
  181. // Initialize buffers
  182. for (i = 0; i < width*height; i++) {
  183. tpt[i].x = 0;
  184. tpt[i].y = 0;
  185. tdist[i] = SDF_BIG;
  186. }
  187. // Calculate position of the anti-aliased pixels and distance to the boundary of the shape.
  188. for (y = 1; y < height-1; y++) {
  189. for (x = 1; x < width-1; x++) {
  190. int tk, k = x + y * stride;
  191. struct SDFpoint c = { (float)x, (float)y };
  192. float d, gx, gy, glen;
  193. // Skip flat areas.
  194. if (img[k] == 255) continue;
  195. if (img[k] == 0) {
  196. // Special handling for cases where full opaque pixels are next to full transparent pixels.
  197. // See: https://github.com/memononen/SDF/issues/2
  198. int he = img[k-1] == 255 || img[k+1] == 255;
  199. int ve = img[k-stride] == 255 || img[k+stride] == 255;
  200. if (!he && !ve) continue;
  201. }
  202. // Calculate gradient direction
  203. gx = -(float)img[k-stride-1] - SDF_SQRT2*(float)img[k-1] - (float)img[k+stride-1] + (float)img[k-stride+1] + SDF_SQRT2*(float)img[k+1] + (float)img[k+stride+1];
  204. gy = -(float)img[k-stride-1] - SDF_SQRT2*(float)img[k-stride] - (float)img[k-stride+1] + (float)img[k+stride-1] + SDF_SQRT2*(float)img[k+stride] + (float)img[k+stride+1];
  205. if (fabsf(gx) < 0.001f && fabsf(gy) < 0.001f) continue;
  206. glen = gx*gx + gy*gy;
  207. if (glen > 0.0001f) {
  208. glen = 1.0f / sqrtf(glen);
  209. gx *= glen;
  210. gy *= glen;
  211. }
  212. // Find nearest point on contour.
  213. tk = x + y * width;
  214. d = sdf__edgedf(gx, gy, (float)img[k]/255.0f);
  215. tpt[tk].x = x + gx*d;
  216. tpt[tk].y = y + gy*d;
  217. tdist[tk] = sdf__distsqr(&c, &tpt[tk]);
  218. }
  219. }
  220. // Calculate distance transform using sweep-and-update.
  221. for (pass = 0; pass < SDF_MAX_PASSES; pass++){
  222. int changed = 0;
  223. // Bottom-left to top-right.
  224. for (y = 1; y < height-1; y++) {
  225. for (x = 1; x < width-1; x++) {
  226. int k = x+y*width, kn, ch = 0;
  227. struct SDFpoint c = { (float)x, (float)y }, pt;
  228. float pd = tdist[k], d;
  229. // (-1,-1)
  230. kn = k - 1 - width;
  231. if (tdist[kn] < pd) {
  232. d = sdf__distsqr(&c, &tpt[kn]);
  233. if (d + SDF_SLACK < pd) {
  234. pt = tpt[kn];
  235. pd = d;
  236. ch = 1;
  237. }
  238. }
  239. // (0,-1)
  240. kn = k - width;
  241. if (tdist[kn] < pd) {
  242. d = sdf__distsqr(&c, &tpt[kn]);
  243. if (d + SDF_SLACK < pd) {
  244. pt = tpt[kn];
  245. pd = d;
  246. ch = 1;
  247. }
  248. }
  249. // (1,-1)
  250. kn = k + 1 - width;
  251. if (tdist[kn] < pd) {
  252. d = sdf__distsqr(&c, &tpt[kn]);
  253. if (d + SDF_SLACK < pd) {
  254. pt = tpt[kn];
  255. pd = d;
  256. ch = 1;
  257. }
  258. }
  259. // (-1,0)
  260. kn = k - 1;
  261. if (tdist[kn] < tdist[k]) {
  262. d = sdf__distsqr(&c, &tpt[kn]);
  263. if (d + SDF_SLACK < pd) {
  264. pt = tpt[kn];
  265. pd = d;
  266. ch = 1;
  267. }
  268. }
  269. if (ch) {
  270. tpt[k] = pt;
  271. tdist[k] = pd;
  272. changed++;
  273. }
  274. }
  275. }
  276. // Top-right to bottom-left.
  277. for (y = height-2; y > 0 ; y--) {
  278. for (x = width-2; x > 0; x--) {
  279. int k = x+y*width, kn, ch = 0;
  280. struct SDFpoint c = { (float)x, (float)y }, pt;
  281. float pd = tdist[k], d;
  282. // (1,0)
  283. kn = k + 1;
  284. if (tdist[kn] < pd) {
  285. d = sdf__distsqr(&c, &tpt[kn]);
  286. if (d + SDF_SLACK < pd) {
  287. pt = tpt[kn];
  288. pd = d;
  289. ch = 1;
  290. }
  291. }
  292. // (-1,1)
  293. kn = k - 1 + width;
  294. if (tdist[kn] < pd) {
  295. d = sdf__distsqr(&c, &tpt[kn]);
  296. if (d + SDF_SLACK < pd) {
  297. pt = tpt[kn];
  298. pd = d;
  299. ch = 1;
  300. }
  301. }
  302. // (0,1)
  303. kn = k + width;
  304. if (tdist[kn] < pd) {
  305. d = sdf__distsqr(&c, &tpt[kn]);
  306. if (d + SDF_SLACK < pd) {
  307. pt = tpt[kn];
  308. pd = d;
  309. ch = 1;
  310. }
  311. }
  312. // (1,1)
  313. kn = k + 1 + width;
  314. if (tdist[kn] < pd) {
  315. d = sdf__distsqr(&c, &tpt[kn]);
  316. if (d + SDF_SLACK < pd) {
  317. pt = tpt[kn];
  318. pd = d;
  319. ch = 1;
  320. }
  321. }
  322. if (ch) {
  323. tpt[k] = pt;
  324. tdist[k] = pd;
  325. changed++;
  326. }
  327. }
  328. }
  329. if (changed == 0) break;
  330. }
  331. // Map to good range.
  332. scale = 1.0f / radius;
  333. for (y = 0; y < height; y++) {
  334. for (x = 0; x < width; x++) {
  335. float d = sqrtf(tdist[x+y*width]) * scale;
  336. if (img[x+y*stride] > 127) d = -d;
  337. out[x+y*outstride] = (unsigned char)(sdf__clamp01(0.5f - d*0.5f) * 255.0f);
  338. }
  339. }
  340. }
  341. int sdfBuildDistanceField(unsigned char* out, int outstride, float radius,
  342. const unsigned char* img, int width, int height, int stride)
  343. {
  344. unsigned char* temp = (unsigned char*)malloc(width*height*sizeof(float)*3);
  345. if (temp == NULL) return 0;
  346. sdfBuildDistanceFieldNoAlloc(out, outstride, radius, img, width, height, stride, temp);
  347. free(temp);
  348. return 1;
  349. }
  350. #endif //SDF_IMPLEMENTATION