sdf.h 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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 = maxdist (outside) and 255 = -maxdist (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. // maxdist - The extents of the output distance range 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 sdfBuild(unsigned char* out, int outstride, float maxdist,
  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) bytes.
  45. void sdfBuildNoAlloc(unsigned char* out, int outstride, float maxdist,
  46. const unsigned char* img, int width, int height, int stride,
  47. unsigned char* temp);
  48. void sdfCoverageToDistance(unsigned char* out, int outstride, float maxdist,
  49. const unsigned char* img, int width, int height, int stride);
  50. #endif //SDF_H
  51. #ifdef SDF_IMPLEMENTATION
  52. #include <math.h>
  53. #include <stdlib.h>
  54. #define SDF_MAX_PASSES 10 // Maximum number of distance transform passes
  55. #define SDF_SLACK 0.001f // Controls how much smaller the neighbour value must be to cosnider, too small slack increse iteration count.
  56. #define SDF_SQRT2 1.4142136f // sqrt(2)
  57. #define SDF_BIG 1e+37f // Big value used to initialize the distance field.
  58. static float sdf__edgedf(float gx, float gy, float a)
  59. {
  60. float df, a1;
  61. if ((gx == 0) || (gy == 0)) {
  62. // Either A) gu or gv are zero, or B) both
  63. // Linear approximation is A) correct or B) a fair guess
  64. df = 0.5f - a;
  65. } else {
  66. // Everything is symmetric wrt sign and transposition,
  67. // so move to first octant (gx>=0, gy>=0, gx>=gy) to
  68. // avoid handling all possible edge directions.
  69. gx = fabsf(gx);
  70. gy = fabsf(gy);
  71. if (gx < gy) {
  72. float temp = gx;
  73. gx = gy;
  74. gy = temp;
  75. }
  76. a1 = 0.5f*gy/gx;
  77. if (a < a1) { // 0 <= a < a1
  78. df = 0.5f*(gx + gy) - sqrtf(2.0f*gx*gy*a);
  79. } else if (a < (1.0-a1)) { // a1 <= a <= 1-a1
  80. df = (0.5f-a)*gx;
  81. } else { // 1-a1 < a <= 1
  82. df = -0.5f*(gx + gy) + sqrtf(2.0f*gx*gy*(1.0f-a));
  83. }
  84. }
  85. return df;
  86. }
  87. struct SDFpoint {
  88. float x,y;
  89. };
  90. static float sdf__distsqr(struct SDFpoint* a, struct SDFpoint* b)
  91. {
  92. float dx = b->x - a->x, dy = b->y - a->y;
  93. return dx*dx + dy*dy;
  94. }
  95. static float sdf__clamp01(float x)
  96. {
  97. return x < 0.0f ? 0.0f : (x > 1.0f ? 1.0f : x);
  98. }
  99. void sdfCoverageToDistance(unsigned char* out, int outstride,
  100. const unsigned char* img, int width, int height, int stride)
  101. {
  102. int x, y;
  103. // Zero out borders
  104. for (x = 0; x < width; x++)
  105. out[x] = 0;
  106. for (y = 1; y < height; y++) {
  107. out[y*stride] = 0;
  108. out[width-1+y*stride] = 0;
  109. }
  110. for (x = 0; x < width; x++)
  111. out[x+(height-1)*stride] = 0;
  112. // Calculate position of the anti-aliased pixels and distance to the boundary of the shape.
  113. for (y = 1; y < height-1; y++) {
  114. for (x = 1; x < width-1; x++) {
  115. int k = x + y * stride;
  116. float d, gx, gy, glen;
  117. // Calculate gradient direction
  118. 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];
  119. 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];
  120. if (fabsf(gx) > 0.001f && fabsf(gy) > 0.001f) {
  121. glen = gx*gx + gy*gy;
  122. glen = 1.0f / sqrtf(glen);
  123. gx *= glen;
  124. gy *= glen;
  125. // Find nearest point on contour.
  126. d = sdf__edgedf(gx, gy, (float)img[k]/255.0f);
  127. d = fabsf(d);
  128. if (img[x+y*stride] > 127) d = -d;
  129. out[x+y*outstride] = (unsigned char)(sdf__clamp01(0.5f - d*0.5f) * 255.0f);
  130. } else {
  131. out[x+y*outstride] = img[x+y*stride] > 127 ? 255 : 0;
  132. }
  133. }
  134. }
  135. }
  136. void sdfBuildNoAlloc(unsigned char* out, int outstride, float maxdist,
  137. const unsigned char* img, int width, int height, int stride,
  138. unsigned char* temp)
  139. {
  140. int i, x, y, pass;
  141. float scale;
  142. float* tdist = (float*)&temp[0];
  143. struct SDFpoint* tpt = (struct SDFpoint*)&temp[width * height * sizeof(float)];
  144. // Initialize buffers
  145. for (i = 0; i < width*height; i++) {
  146. tpt[i].x = 0;
  147. tpt[i].y = 0;
  148. tdist[i] = SDF_BIG;
  149. }
  150. // Calculate position of the anti-aliased pixels and distance to the boundary of the shape.
  151. for (y = 1; y < height-1; y++) {
  152. for (x = 1; x < width-1; x++) {
  153. int k = x + y * stride;
  154. if (img[k] > 0 && img[k] < 255) {
  155. struct SDFpoint c = { (float)x, (float)y };
  156. float d, gx, gy, glen;
  157. // Calculate gradient direction
  158. 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];
  159. 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];
  160. if (fabsf(gx) < 0.001f && fabsf(gy) < 0.001f) continue;
  161. glen = gx*gx + gy*gy;
  162. if (glen > 0.0001f) {
  163. glen = 1.0f / sqrtf(glen);
  164. gx *= glen;
  165. gy *= glen;
  166. }
  167. // Find nearest point on contour.
  168. d = sdf__edgedf(gx, gy, (float)img[k]/255.0f);
  169. tpt[k].x = x + gx*d;
  170. tpt[k].y = y + gy*d;
  171. tdist[k] = sdf__distsqr(&c, &tpt[k]);
  172. }
  173. }
  174. }
  175. // Calculate distance transform using sweep-and-update.
  176. for (pass = 0; pass < SDF_MAX_PASSES; pass++){
  177. int changed = 0;
  178. // Bottom-left to top-right.
  179. for (y = 1; y < height-1; y++) {
  180. for (x = 1; x < width-1; x++) {
  181. int k = x+y*width, kn, ch = 0;
  182. struct SDFpoint c = { (float)x, (float)y }, pt = { 0.0f, 0.0f };
  183. float pd = tdist[k], d;
  184. // (-1,-1)
  185. kn = k - 1 - width;
  186. if (tdist[kn] < pd) {
  187. d = sdf__distsqr(&c, &tpt[kn]);
  188. if (d + SDF_SLACK < pd) {
  189. pt = tpt[kn];
  190. pd = d;
  191. ch = 1;
  192. }
  193. }
  194. // (0,-1)
  195. kn = k - 1 - width;
  196. if (tdist[kn] < pd) {
  197. d = sdf__distsqr(&c, &tpt[kn]);
  198. if (d + SDF_SLACK < pd) {
  199. pt = tpt[kn];
  200. pd = d;
  201. ch = 1;
  202. }
  203. }
  204. // (1,-1)
  205. kn = k + 1 - width;
  206. if (tdist[kn] < pd) {
  207. d = sdf__distsqr(&c, &tpt[kn]);
  208. if (d + SDF_SLACK < pd) {
  209. pt = tpt[kn];
  210. pd = d;
  211. ch = 1;
  212. }
  213. }
  214. // (-1,0)
  215. kn = k - 1;
  216. if (tdist[kn] < tdist[k]) {
  217. d = sdf__distsqr(&c, &tpt[kn]);
  218. if (d + SDF_SLACK < pd) {
  219. pt = tpt[kn];
  220. pd = d;
  221. ch = 1;
  222. }
  223. }
  224. if (ch) {
  225. tpt[k] = pt;
  226. tdist[k] = pd;
  227. changed++;
  228. }
  229. }
  230. }
  231. // Top-right to bottom-left.
  232. for (y = height-2; y > 0 ; y--) {
  233. for (x = width-2; x > 0; x--) {
  234. int k = x+y*width, kn, ch = 0;
  235. struct SDFpoint c = { (float)x, (float)y }, pt = { 0.0f, 0.0f };
  236. float pd = tdist[k], d;
  237. // (1,0)
  238. kn = k + 1;
  239. if (tdist[kn] < pd) {
  240. d = sdf__distsqr(&c, &tpt[kn]);
  241. if (d + SDF_SLACK < pd) {
  242. pt = tpt[kn];
  243. pd = d;
  244. ch = 1;
  245. }
  246. }
  247. // (-1,1)
  248. kn = k - 1 + width;
  249. if (tdist[kn] < pd) {
  250. d = sdf__distsqr(&c, &tpt[kn]);
  251. if (d + SDF_SLACK < pd) {
  252. pt = tpt[kn];
  253. pd = d;
  254. ch = 1;
  255. }
  256. }
  257. // (0,1)
  258. kn = k + width;
  259. if (tdist[kn] < pd) {
  260. d = sdf__distsqr(&c, &tpt[kn]);
  261. if (d + SDF_SLACK < pd) {
  262. pt = tpt[kn];
  263. pd = d;
  264. ch = 1;
  265. }
  266. }
  267. // (1,1)
  268. kn = k + 1 + width;
  269. if (tdist[kn] < pd) {
  270. d = sdf__distsqr(&c, &tpt[kn]);
  271. if (d + SDF_SLACK < pd) {
  272. pt = tpt[kn];
  273. pd = d;
  274. ch = 1;
  275. }
  276. }
  277. if (ch) {
  278. tpt[k] = pt;
  279. tdist[k] = pd;
  280. changed++;
  281. }
  282. }
  283. }
  284. if (changed == 0) break;
  285. }
  286. // Map to good range.
  287. scale = 1.0f / maxdist;
  288. for (y = 0; y < height; y++) {
  289. for (x = 0; x < width; x++) {
  290. float d = sqrtf(tdist[x+y*width]) * scale;
  291. if (img[x+y*stride] > 127) d = -d;
  292. out[x+y*outstride] = (unsigned char)(sdf__clamp01(0.5f - d*0.5f) * 255.0f);
  293. }
  294. }
  295. }
  296. int sdfBuild(unsigned char* out, int outstride, float maxdist,
  297. const unsigned char* img, int width, int height, int stride)
  298. {
  299. unsigned char* temp = (unsigned char*)malloc(width*height*sizeof(float)*3);
  300. if (temp == NULL) return 0;
  301. sdfBuildNoAlloc(out, outstride, maxdist, img, width, height, stride, temp);
  302. free(temp);
  303. return 1;
  304. }
  305. #endif //SDF_IMPLEMENTATION