• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2014 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 
8 #include "include/private/SkColorData.h"
9 #include "include/private/base/SkTPin.h"
10 #include "include/private/base/SkTemplates.h"
11 #include "src/base/SkAutoMalloc.h"
12 #include "src/core/SkDistanceFieldGen.h"
13 #include "src/core/SkMask.h"
14 #include "src/core/SkPointPriv.h"
15 
16 #include <utility>
17 
18 using namespace skia_private;
19 
20 #if !defined(SK_DISABLE_SDF_TEXT)
21 
22 struct DFData {
23     float   fAlpha;      // alpha value of source texel
24     float   fDistSq;     // distance squared to nearest (so far) edge texel
25     SkPoint fDistVector; // distance vector to nearest (so far) edge texel
26 };
27 
28 enum NeighborFlags {
29     kLeft_NeighborFlag        = 0x01,
30     kRight_NeighborFlag       = 0x02,
31     kTopLeft_NeighborFlag     = 0x04,
32     kTop_NeighborFlag         = 0x08,
33     kTopRight_NeighborFlag    = 0x10,
34     kBottomLeft_NeighborFlag  = 0x20,
35     kBottom_NeighborFlag      = 0x40,
36     kBottomRight_NeighborFlag = 0x80,
37     kAll_NeighborFlags        = 0xff,
38 
39     kNeighborFlagCount        = 8
40 };
41 
42 // We treat an "edge" as a place where we cross from >=128 to <128, or vice versa, or
43 // where we have two non-zero pixels that are <128.
44 // 'neighborFlags' is used to limit the directions in which we test to avoid indexing
45 // outside of the image
found_edge(const unsigned char * imagePtr,int width,int neighborFlags)46 static bool found_edge(const unsigned char* imagePtr, int width, int neighborFlags) {
47     // the order of these should match the neighbor flags above
48     const int kNum8ConnectedNeighbors = 8;
49     const int offsets[8] = {-1, 1, -width-1, -width, -width+1, width-1, width, width+1 };
50     SkASSERT(kNum8ConnectedNeighbors == kNeighborFlagCount);
51 
52     // search for an edge
53     unsigned char currVal = *imagePtr;
54     unsigned char currCheck = (currVal >> 7);
55     for (int i = 0; i < kNum8ConnectedNeighbors; ++i) {
56         unsigned char neighborVal;
57         if ((1 << i) & neighborFlags) {
58             const unsigned char* checkPtr = imagePtr + offsets[i];
59             neighborVal = *checkPtr;
60         } else {
61             neighborVal = 0;
62         }
63         unsigned char neighborCheck = (neighborVal >> 7);
64         SkASSERT(currCheck == 0 || currCheck == 1);
65         SkASSERT(neighborCheck == 0 || neighborCheck == 1);
66         // if sharp transition
67         if (currCheck != neighborCheck ||
68             // or both <128 and >0
69             (!currCheck && !neighborCheck && currVal && neighborVal)) {
70             return true;
71         }
72     }
73 
74     return false;
75 }
76 
init_glyph_data(DFData * data,unsigned char * edges,const unsigned char * image,int dataWidth,int dataHeight,int imageWidth,int imageHeight,int pad)77 static void init_glyph_data(DFData* data, unsigned char* edges, const unsigned char* image,
78                             int dataWidth, int dataHeight,
79                             int imageWidth, int imageHeight,
80                             int pad) {
81     data += pad*dataWidth;
82     data += pad;
83     edges += (pad*dataWidth + pad);
84 
85     for (int j = 0; j < imageHeight; ++j) {
86         for (int i = 0; i < imageWidth; ++i) {
87             if (255 == *image) {
88                 data->fAlpha = 1.0f;
89             } else {
90                 data->fAlpha = (*image)*0.00392156862f;  // 1/255
91             }
92             int checkMask = kAll_NeighborFlags;
93             if (i == 0) {
94                 checkMask &= ~(kLeft_NeighborFlag|kTopLeft_NeighborFlag|kBottomLeft_NeighborFlag);
95             }
96             if (i == imageWidth-1) {
97                 checkMask &= ~(kRight_NeighborFlag|kTopRight_NeighborFlag|kBottomRight_NeighborFlag);
98             }
99             if (j == 0) {
100                 checkMask &= ~(kTopLeft_NeighborFlag|kTop_NeighborFlag|kTopRight_NeighborFlag);
101             }
102             if (j == imageHeight-1) {
103                 checkMask &= ~(kBottomLeft_NeighborFlag|kBottom_NeighborFlag|kBottomRight_NeighborFlag);
104             }
105             if (found_edge(image, imageWidth, checkMask)) {
106                 *edges = 255;  // using 255 makes for convenient debug rendering
107             }
108             ++data;
109             ++image;
110             ++edges;
111         }
112         data += 2*pad;
113         edges += 2*pad;
114     }
115 }
116 
117 // from Gustavson (2011)
118 // computes the distance to an edge given an edge normal vector and a pixel's alpha value
119 // assumes that direction has been pre-normalized
edge_distance(const SkPoint & direction,float alpha)120 static float edge_distance(const SkPoint& direction, float alpha) {
121     float dx = direction.fX;
122     float dy = direction.fY;
123     float distance;
124     if (SkScalarNearlyZero(dx) || SkScalarNearlyZero(dy)) {
125         distance = 0.5f - alpha;
126     } else {
127         // this is easier if we treat the direction as being in the first octant
128         // (other octants are symmetrical)
129         dx = SkScalarAbs(dx);
130         dy = SkScalarAbs(dy);
131         if (dx < dy) {
132             using std::swap;
133             swap(dx, dy);
134         }
135 
136         // a1 = 0.5*dy/dx is the smaller fractional area chopped off by the edge
137         // to avoid the divide, we just consider the numerator
138         float a1num = 0.5f*dy;
139 
140         // we now compute the approximate distance, depending where the alpha falls
141         // relative to the edge fractional area
142 
143         // if 0 <= alpha < a1
144         if (alpha*dx < a1num) {
145             // TODO: find a way to do this without square roots?
146             distance = 0.5f*(dx + dy) - SkScalarSqrt(2.0f*dx*dy*alpha);
147         // if a1 <= alpha <= 1 - a1
148         } else if (alpha*dx < (dx - a1num)) {
149             distance = (0.5f - alpha)*dx;
150         // if 1 - a1 < alpha <= 1
151         } else {
152             // TODO: find a way to do this without square roots?
153             distance = -0.5f*(dx + dy) + SkScalarSqrt(2.0f*dx*dy*(1.0f - alpha));
154         }
155     }
156 
157     return distance;
158 }
159 
init_distances(DFData * data,unsigned char * edges,int width,int height)160 static void init_distances(DFData* data, unsigned char* edges, int width, int height) {
161     // skip one pixel border
162     DFData* currData = data;
163     DFData* prevData = data - width;
164     DFData* nextData = data + width;
165 
166     for (int j = 0; j < height; ++j) {
167         for (int i = 0; i < width; ++i) {
168             if (*edges) {
169                 // we should not be in the one-pixel outside band
170                 SkASSERT(i > 0 && i < width-1 && j > 0 && j < height-1);
171                 // gradient will point from low to high
172                 // +y is down in this case
173                 // i.e., if you're outside, gradient points towards edge
174                 // if you're inside, gradient points away from edge
175                 SkPoint currGrad;
176                 currGrad.fX = (prevData+1)->fAlpha - (prevData-1)->fAlpha
177                              + SK_ScalarSqrt2*(currData+1)->fAlpha
178                              - SK_ScalarSqrt2*(currData-1)->fAlpha
179                              + (nextData+1)->fAlpha - (nextData-1)->fAlpha;
180                 currGrad.fY = (nextData-1)->fAlpha - (prevData-1)->fAlpha
181                              + SK_ScalarSqrt2*nextData->fAlpha
182                              - SK_ScalarSqrt2*prevData->fAlpha
183                              + (nextData+1)->fAlpha - (prevData+1)->fAlpha;
184                 SkPointPriv::SetLengthFast(&currGrad, 1.0f);
185 
186                 // init squared distance to edge and distance vector
187                 float dist = edge_distance(currGrad, currData->fAlpha);
188                 currGrad.scale(dist, &currData->fDistVector);
189                 currData->fDistSq = dist*dist;
190             } else {
191                 // init distance to "far away"
192                 currData->fDistSq = 2000000.f;
193                 currData->fDistVector.fX = 1000.f;
194                 currData->fDistVector.fY = 1000.f;
195             }
196             ++currData;
197             ++prevData;
198             ++nextData;
199             ++edges;
200         }
201     }
202 }
203 
204 // Danielsson's 8SSEDT
205 
206 // first stage forward pass
207 // (forward in Y, forward in X)
F1(DFData * curr,int width)208 static void F1(DFData* curr, int width) {
209     // upper left
210     DFData* check = curr - width-1;
211     SkPoint distVec = check->fDistVector;
212     float distSq = check->fDistSq - 2.0f*(distVec.fX + distVec.fY - 1.0f);
213     if (distSq < curr->fDistSq) {
214         distVec.fX -= 1.0f;
215         distVec.fY -= 1.0f;
216         curr->fDistSq = distSq;
217         curr->fDistVector = distVec;
218     }
219 
220     // up
221     check = curr - width;
222     distVec = check->fDistVector;
223     distSq = check->fDistSq - 2.0f*distVec.fY + 1.0f;
224     if (distSq < curr->fDistSq) {
225         distVec.fY -= 1.0f;
226         curr->fDistSq = distSq;
227         curr->fDistVector = distVec;
228     }
229 
230     // upper right
231     check = curr - width+1;
232     distVec = check->fDistVector;
233     distSq = check->fDistSq + 2.0f*(distVec.fX - distVec.fY + 1.0f);
234     if (distSq < curr->fDistSq) {
235         distVec.fX += 1.0f;
236         distVec.fY -= 1.0f;
237         curr->fDistSq = distSq;
238         curr->fDistVector = distVec;
239     }
240 
241     // left
242     check = curr - 1;
243     distVec = check->fDistVector;
244     distSq = check->fDistSq - 2.0f*distVec.fX + 1.0f;
245     if (distSq < curr->fDistSq) {
246         distVec.fX -= 1.0f;
247         curr->fDistSq = distSq;
248         curr->fDistVector = distVec;
249     }
250 }
251 
252 // second stage forward pass
253 // (forward in Y, backward in X)
F2(DFData * curr,int width)254 static void F2(DFData* curr, int width) {
255     // right
256     DFData* check = curr + 1;
257     SkPoint distVec = check->fDistVector;
258     float distSq = check->fDistSq + 2.0f*distVec.fX + 1.0f;
259     if (distSq < curr->fDistSq) {
260         distVec.fX += 1.0f;
261         curr->fDistSq = distSq;
262         curr->fDistVector = distVec;
263     }
264 }
265 
266 // first stage backward pass
267 // (backward in Y, forward in X)
B1(DFData * curr,int width)268 static void B1(DFData* curr, int width) {
269     // left
270     DFData* check = curr - 1;
271     SkPoint distVec = check->fDistVector;
272     float distSq = check->fDistSq - 2.0f*distVec.fX + 1.0f;
273     if (distSq < curr->fDistSq) {
274         distVec.fX -= 1.0f;
275         curr->fDistSq = distSq;
276         curr->fDistVector = distVec;
277     }
278 }
279 
280 // second stage backward pass
281 // (backward in Y, backwards in X)
B2(DFData * curr,int width)282 static void B2(DFData* curr, int width) {
283     // right
284     DFData* check = curr + 1;
285     SkPoint distVec = check->fDistVector;
286     float distSq = check->fDistSq + 2.0f*distVec.fX + 1.0f;
287     if (distSq < curr->fDistSq) {
288         distVec.fX += 1.0f;
289         curr->fDistSq = distSq;
290         curr->fDistVector = distVec;
291     }
292 
293     // bottom left
294     check = curr + width-1;
295     distVec = check->fDistVector;
296     distSq = check->fDistSq - 2.0f*(distVec.fX - distVec.fY - 1.0f);
297     if (distSq < curr->fDistSq) {
298         distVec.fX -= 1.0f;
299         distVec.fY += 1.0f;
300         curr->fDistSq = distSq;
301         curr->fDistVector = distVec;
302     }
303 
304     // bottom
305     check = curr + width;
306     distVec = check->fDistVector;
307     distSq = check->fDistSq + 2.0f*distVec.fY + 1.0f;
308     if (distSq < curr->fDistSq) {
309         distVec.fY += 1.0f;
310         curr->fDistSq = distSq;
311         curr->fDistVector = distVec;
312     }
313 
314     // bottom right
315     check = curr + width+1;
316     distVec = check->fDistVector;
317     distSq = check->fDistSq + 2.0f*(distVec.fX + distVec.fY + 1.0f);
318     if (distSq < curr->fDistSq) {
319         distVec.fX += 1.0f;
320         distVec.fY += 1.0f;
321         curr->fDistSq = distSq;
322         curr->fDistVector = distVec;
323     }
324 }
325 
326 // enable this to output edge data rather than the distance field
327 #define DUMP_EDGE 0
328 
329 #if !DUMP_EDGE
330 template <int distanceMagnitude>
pack_distance_field_val(float dist)331 static unsigned char pack_distance_field_val(float dist) {
332     // The distance field is constructed as unsigned char values, so that the zero value is at 128,
333     // Beside 128, we have 128 values in range [0, 128), but only 127 values in range (128, 255].
334     // So we multiply distanceMagnitude by 127/128 at the latter range to avoid overflow.
335     dist = SkTPin<float>(-dist, -distanceMagnitude, distanceMagnitude * 127.0f / 128.0f);
336 
337     // Scale into the positive range for unsigned distance.
338     dist += distanceMagnitude;
339 
340     // Scale into unsigned char range.
341     // Round to place negative and positive values as equally as possible around 128
342     // (which represents zero).
343     return (unsigned char)SkScalarRoundToInt(dist / (2 * distanceMagnitude) * 256.0f);
344 }
345 #endif
346 
347 // assumes a padded 8-bit image and distance field
348 // width and height are the original width and height of the image
generate_distance_field_from_image(unsigned char * distanceField,const unsigned char * copyPtr,int width,int height)349 static bool generate_distance_field_from_image(unsigned char* distanceField,
350                                                const unsigned char* copyPtr,
351                                                int width, int height) {
352     SkASSERT(distanceField);
353     SkASSERT(copyPtr);
354 
355     // we expand our temp data by one more on each side to simplify
356     // the scanning code -- will always be treated as infinitely far away
357     int pad = SK_DistanceFieldPad + 1;
358 
359     // set params for distance field data
360     int dataWidth = width + 2*pad;
361     int dataHeight = height + 2*pad;
362 
363     // create zeroed temp DFData+edge storage
364     UniqueVoidPtr storage(sk_calloc_throw(dataWidth*dataHeight*(sizeof(DFData) + 1)));
365     DFData*        dataPtr = (DFData*)storage.get();
366     unsigned char* edgePtr = (unsigned char*)storage.get() + dataWidth*dataHeight*sizeof(DFData);
367 
368     // copy glyph into distance field storage
369     init_glyph_data(dataPtr, edgePtr, copyPtr,
370                     dataWidth, dataHeight,
371                     width+2, height+2, SK_DistanceFieldPad);
372 
373     // create initial distance data, particularly at edges
374     init_distances(dataPtr, edgePtr, dataWidth, dataHeight);
375 
376     // now perform Euclidean distance transform to propagate distances
377 
378     // forwards in y
379     DFData* currData = dataPtr+dataWidth+1; // skip outer buffer
380     unsigned char* currEdge = edgePtr+dataWidth+1;
381     for (int j = 1; j < dataHeight-1; ++j) {
382         // forwards in x
383         for (int i = 1; i < dataWidth-1; ++i) {
384             // don't need to calculate distance for edge pixels
385             if (!*currEdge) {
386                 F1(currData, dataWidth);
387             }
388             ++currData;
389             ++currEdge;
390         }
391 
392         // backwards in x
393         --currData; // reset to end
394         --currEdge;
395         for (int i = 1; i < dataWidth-1; ++i) {
396             // don't need to calculate distance for edge pixels
397             if (!*currEdge) {
398                 F2(currData, dataWidth);
399             }
400             --currData;
401             --currEdge;
402         }
403 
404         currData += dataWidth+1;
405         currEdge += dataWidth+1;
406     }
407 
408     // backwards in y
409     currData = dataPtr+dataWidth*(dataHeight-2) - 1; // skip outer buffer
410     currEdge = edgePtr+dataWidth*(dataHeight-2) - 1;
411     for (int j = 1; j < dataHeight-1; ++j) {
412         // forwards in x
413         for (int i = 1; i < dataWidth-1; ++i) {
414             // don't need to calculate distance for edge pixels
415             if (!*currEdge) {
416                 B1(currData, dataWidth);
417             }
418             ++currData;
419             ++currEdge;
420         }
421 
422         // backwards in x
423         --currData; // reset to end
424         --currEdge;
425         for (int i = 1; i < dataWidth-1; ++i) {
426             // don't need to calculate distance for edge pixels
427             if (!*currEdge) {
428                 B2(currData, dataWidth);
429             }
430             --currData;
431             --currEdge;
432         }
433 
434         currData -= dataWidth-1;
435         currEdge -= dataWidth-1;
436     }
437 
438     // copy results to final distance field data
439     currData = dataPtr + dataWidth+1;
440     currEdge = edgePtr + dataWidth+1;
441     unsigned char *dfPtr = distanceField;
442     for (int j = 1; j < dataHeight-1; ++j) {
443         for (int i = 1; i < dataWidth-1; ++i) {
444 #if DUMP_EDGE
445             float alpha = currData->fAlpha;
446             float edge = 0.0f;
447             if (*currEdge) {
448                 edge = 0.25f;
449             }
450             // blend with original image
451             float result = alpha + (1.0f-alpha)*edge;
452             unsigned char val = sk_float_round2int(255*result);
453             *dfPtr++ = val;
454 #else
455             float dist;
456             if (currData->fAlpha > 0.5f) {
457                 dist = -SkScalarSqrt(currData->fDistSq);
458             } else {
459                 dist = SkScalarSqrt(currData->fDistSq);
460             }
461             *dfPtr++ = pack_distance_field_val<SK_DistanceFieldMagnitude>(dist);
462 #endif
463             ++currData;
464             ++currEdge;
465         }
466         currData += 2;
467         currEdge += 2;
468     }
469 
470     return true;
471 }
472 
473 // assumes an 8-bit image and distance field
SkGenerateDistanceFieldFromA8Image(unsigned char * distanceField,const unsigned char * image,int width,int height,size_t rowBytes)474 bool SkGenerateDistanceFieldFromA8Image(unsigned char* distanceField,
475                                         const unsigned char* image,
476                                         int width, int height, size_t rowBytes) {
477     SkASSERT(distanceField);
478     SkASSERT(image);
479 
480     // create temp data
481     SkAutoSMalloc<1024> copyStorage((width+2)*(height+2)*sizeof(char));
482     unsigned char* copyPtr = (unsigned char*) copyStorage.get();
483 
484     // we copy our source image into a padded copy to ensure we catch edge transitions
485     // around the outside
486     const unsigned char* currSrcScanLine = image;
487     sk_bzero(copyPtr, (width+2)*sizeof(char));
488     unsigned char* currDestPtr = copyPtr + width + 2;
489     for (int i = 0; i < height; ++i) {
490         *currDestPtr++ = 0;
491         memcpy(currDestPtr, currSrcScanLine, width);
492         currSrcScanLine += rowBytes;
493         currDestPtr += width;
494         *currDestPtr++ = 0;
495     }
496     sk_bzero(currDestPtr, (width+2)*sizeof(char));
497 
498     return generate_distance_field_from_image(distanceField, copyPtr, width, height);
499 }
500 
501 // assumes a 16-bit lcd mask and 8-bit distance field
SkGenerateDistanceFieldFromLCD16Mask(unsigned char * distanceField,const unsigned char * image,int w,int h,size_t rowBytes)502 bool SkGenerateDistanceFieldFromLCD16Mask(unsigned char* distanceField,
503                                            const unsigned char* image,
504                                            int w, int h, size_t rowBytes) {
505     SkASSERT(distanceField);
506     SkASSERT(image);
507 
508     // create temp data
509     SkAutoSMalloc<1024> copyStorage((w+2)*(h+2)*sizeof(char));
510     unsigned char* copyPtr = (unsigned char*) copyStorage.get();
511 
512     // we copy our source image into a padded copy to ensure we catch edge transitions
513     // around the outside
514     const uint16_t* start = reinterpret_cast<const uint16_t*>(image);
515     auto currSrcScanline = SkMask::AlphaIter<SkMask::kLCD16_Format>(start);
516     auto endSrcScanline = SkMask::AlphaIter<SkMask::kLCD16_Format>(start + w);
517     sk_bzero(copyPtr, (w+2)*sizeof(char));
518     unsigned char* currDestPtr = copyPtr + w + 2;
519     for (int i = 0; i < h; ++i, currSrcScanline >>= rowBytes, endSrcScanline >>= rowBytes) {
520         *currDestPtr++ = 0;
521         for (auto src = currSrcScanline; src < endSrcScanline; ++src) {
522             *currDestPtr++ = *src;
523         }
524         *currDestPtr++ = 0;
525     }
526     sk_bzero(currDestPtr, (w+2)*sizeof(char));
527 
528     return generate_distance_field_from_image(distanceField, copyPtr, w, h);
529 }
530 
531 // assumes a 1-bit image and 8-bit distance field
SkGenerateDistanceFieldFromBWImage(unsigned char * distanceField,const unsigned char * image,int width,int height,size_t rowBytes)532 bool SkGenerateDistanceFieldFromBWImage(unsigned char* distanceField,
533                                         const unsigned char* image,
534                                         int width, int height, size_t rowBytes) {
535     SkASSERT(distanceField);
536     SkASSERT(image);
537 
538     // create temp data
539     SkAutoSMalloc<1024> copyStorage((width+2)*(height+2)*sizeof(char));
540     unsigned char* copyPtr = (unsigned char*) copyStorage.get();
541 
542     // we copy our source image into a padded copy to ensure we catch edge transitions
543     // around the outside
544     const unsigned char* currSrcScanLine = image;
545     sk_bzero(copyPtr, (width+2)*sizeof(char));
546     unsigned char* currDestPtr = copyPtr + width + 2;
547     for (int i = 0; i < height; ++i) {
548         *currDestPtr++ = 0;
549 
550         int rowWritesLeft = width;
551         const unsigned char *maskPtr = currSrcScanLine;
552         while (rowWritesLeft > 0) {
553             unsigned mask = *maskPtr++;
554             for (int j = 7; j >= 0 && rowWritesLeft; --j, --rowWritesLeft) {
555                 *currDestPtr++ = (mask & (1 << j)) ? 0xff : 0;
556             }
557         }
558         currSrcScanLine += rowBytes;
559 
560         *currDestPtr++ = 0;
561     }
562     sk_bzero(currDestPtr, (width+2)*sizeof(char));
563 
564     return generate_distance_field_from_image(distanceField, copyPtr, width, height);
565 }
566 
567 #endif // !defined(SK_DISABLE_SDF_TEXT)
568