blob: 7731f4d9be7fdf65f27a4631a091086c7882db9a [file] [log] [blame]
joshualitt1d89e8d2015-04-01 12:40:54 -07001/*
2 * Copyright 2015 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7#include "GrAtlasTextContext.h"
8
joshualitt1d89e8d2015-04-01 12:40:54 -07009#include "GrBatch.h"
10#include "GrBatchFontCache.h"
11#include "GrBatchTarget.h"
12#include "GrDefaultGeoProcFactory.h"
13#include "GrDrawTarget.h"
14#include "GrFontScaler.h"
15#include "GrIndexBuffer.h"
bsalomoned0bcad2015-05-04 10:36:42 -070016#include "GrResourceProvider.h"
joshualitt1d89e8d2015-04-01 12:40:54 -070017#include "GrStrokeInfo.h"
joshualittb7133be2015-04-08 09:08:31 -070018#include "GrTextBlobCache.h"
joshualitt1d89e8d2015-04-01 12:40:54 -070019#include "GrTexturePriv.h"
bsalomon72e3ae42015-04-28 08:08:46 -070020#include "GrVertexBuffer.h"
joshualitt1d89e8d2015-04-01 12:40:54 -070021
22#include "SkAutoKern.h"
23#include "SkColorPriv.h"
joshualitt9bd2daf2015-04-17 09:30:06 -070024#include "SkColorFilter.h"
25#include "SkDistanceFieldGen.h"
joshualitt1d89e8d2015-04-01 12:40:54 -070026#include "SkDraw.h"
27#include "SkDrawFilter.h"
28#include "SkDrawProcs.h"
29#include "SkGlyphCache.h"
30#include "SkGpuDevice.h"
31#include "SkGr.h"
32#include "SkPath.h"
33#include "SkRTConf.h"
34#include "SkStrokeRec.h"
35#include "SkTextBlob.h"
36#include "SkTextMapStateProc.h"
37
38#include "effects/GrBitmapTextGeoProc.h"
joshualitt9bd2daf2015-04-17 09:30:06 -070039#include "effects/GrDistanceFieldGeoProc.h"
joshualitt1d89e8d2015-04-01 12:40:54 -070040
41namespace {
42static const size_t kLCDTextVASize = sizeof(SkPoint) + sizeof(SkIPoint16);
43
44// position + local coord
45static const size_t kColorTextVASize = sizeof(SkPoint) + sizeof(SkIPoint16);
46
47static const size_t kGrayTextVASize = sizeof(SkPoint) + sizeof(GrColor) + sizeof(SkIPoint16);
48
joshualitt9bd2daf2015-04-17 09:30:06 -070049static const int kMinDFFontSize = 18;
50static const int kSmallDFFontSize = 32;
51static const int kSmallDFFontLimit = 32;
52static const int kMediumDFFontSize = 72;
53static const int kMediumDFFontLimit = 72;
54static const int kLargeDFFontSize = 162;
joshualitta7c63892015-04-21 13:24:37 -070055static const int kLargeDFFontLimit = 2 * kLargeDFFontSize;
joshualitt9bd2daf2015-04-17 09:30:06 -070056
57SkDEBUGCODE(static const int kExpectedDistanceAdjustTableSize = 8;)
58static const int kDistanceAdjustLumShift = 5;
59
joshualitt1d89e8d2015-04-01 12:40:54 -070060static const int kVerticesPerGlyph = 4;
61static const int kIndicesPerGlyph = 6;
62
63static size_t get_vertex_stride(GrMaskFormat maskFormat) {
64 switch (maskFormat) {
65 case kA8_GrMaskFormat:
66 return kGrayTextVASize;
67 case kARGB_GrMaskFormat:
68 return kColorTextVASize;
69 default:
70 return kLCDTextVASize;
71 }
72}
73
joshualitt9bd2daf2015-04-17 09:30:06 -070074static size_t get_vertex_stride_df(GrMaskFormat maskFormat, bool useLCDText) {
75 SkASSERT(maskFormat == kA8_GrMaskFormat);
76 if (useLCDText) {
77 return kLCDTextVASize;
78 } else {
79 return kGrayTextVASize;
80 }
81}
82
83static inline GrColor skcolor_to_grcolor_nopremultiply(SkColor c) {
84 unsigned r = SkColorGetR(c);
85 unsigned g = SkColorGetG(c);
86 unsigned b = SkColorGetB(c);
87 return GrColorPackRGBA(r, g, b, 0xff);
88}
89
joshualitt1d89e8d2015-04-01 12:40:54 -070090};
91
92// TODO
joshualitt9bd2daf2015-04-17 09:30:06 -070093// Distance field text in textblobs
joshualitt1d89e8d2015-04-01 12:40:54 -070094
joshualittdbd35932015-04-02 09:19:04 -070095GrAtlasTextContext::GrAtlasTextContext(GrContext* context,
96 SkGpuDevice* gpuDevice,
joshualitt9bd2daf2015-04-17 09:30:06 -070097 const SkDeviceProperties& properties,
98 bool enableDistanceFields)
99 : INHERITED(context, gpuDevice, properties)
100 , fDistanceAdjustTable(SkNEW_ARGS(DistanceAdjustTable, (properties.gamma()))) {
joshualittb7133be2015-04-08 09:08:31 -0700101 // We overallocate vertices in our textblobs based on the assumption that A8 has the greatest
102 // vertexStride
103 SK_COMPILE_ASSERT(kGrayTextVASize >= kColorTextVASize && kGrayTextVASize >= kLCDTextVASize,
104 vertex_attribute_changed);
joshualitt1d89e8d2015-04-01 12:40:54 -0700105 fCurrStrike = NULL;
joshualittb7133be2015-04-08 09:08:31 -0700106 fCache = context->getTextBlobCache();
joshualitt9bd2daf2015-04-17 09:30:06 -0700107
108#if SK_FORCE_DISTANCE_FIELD_TEXT
109 fEnableDFRendering = true;
110#else
111 fEnableDFRendering = enableDistanceFields;
112#endif
113}
114
115void GrAtlasTextContext::DistanceAdjustTable::buildDistanceAdjustTable(float gamma) {
116
117 // This is used for an approximation of the mask gamma hack, used by raster and bitmap
118 // text. The mask gamma hack is based off of guessing what the blend color is going to
119 // be, and adjusting the mask so that when run through the linear blend will
120 // produce the value closest to the desired result. However, in practice this means
121 // that the 'adjusted' mask is just increasing or decreasing the coverage of
122 // the mask depending on what it is thought it will blit against. For black (on
123 // assumed white) this means that coverages are decreased (on a curve). For white (on
124 // assumed black) this means that coverages are increased (on a a curve). At
125 // middle (perceptual) gray (which could be blit against anything) the coverages
126 // remain the same.
127 //
128 // The idea here is that instead of determining the initial (real) coverage and
129 // then adjusting that coverage, we determine an adjusted coverage directly by
130 // essentially manipulating the geometry (in this case, the distance to the glyph
131 // edge). So for black (on assumed white) this thins a bit; for white (on
132 // assumed black) this fake bolds the geometry a bit.
133 //
134 // The distance adjustment is calculated by determining the actual coverage value which
135 // when fed into in the mask gamma table gives us an 'adjusted coverage' value of 0.5. This
136 // actual coverage value (assuming it's between 0 and 1) corresponds to a distance from the
137 // actual edge. So by subtracting this distance adjustment and computing without the
138 // the coverage adjustment we should get 0.5 coverage at the same point.
139 //
140 // This has several implications:
141 // For non-gray lcd smoothed text, each subpixel essentially is using a
142 // slightly different geometry.
143 //
144 // For black (on assumed white) this may not cover some pixels which were
145 // previously covered; however those pixels would have been only slightly
146 // covered and that slight coverage would have been decreased anyway. Also, some pixels
147 // which were previously fully covered may no longer be fully covered.
148 //
149 // For white (on assumed black) this may cover some pixels which weren't
150 // previously covered at all.
151
152 int width, height;
153 size_t size;
154
155#ifdef SK_GAMMA_CONTRAST
156 SkScalar contrast = SK_GAMMA_CONTRAST;
157#else
158 SkScalar contrast = 0.5f;
159#endif
160 SkScalar paintGamma = gamma;
161 SkScalar deviceGamma = gamma;
162
163 size = SkScalerContext::GetGammaLUTSize(contrast, paintGamma, deviceGamma,
164 &width, &height);
165
166 SkASSERT(kExpectedDistanceAdjustTableSize == height);
167 fTable = SkNEW_ARRAY(SkScalar, height);
168
169 SkAutoTArray<uint8_t> data((int)size);
170 SkScalerContext::GetGammaLUTData(contrast, paintGamma, deviceGamma, data.get());
171
172 // find the inverse points where we cross 0.5
173 // binsearch might be better, but we only need to do this once on creation
174 for (int row = 0; row < height; ++row) {
175 uint8_t* rowPtr = data.get() + row*width;
176 for (int col = 0; col < width - 1; ++col) {
177 if (rowPtr[col] <= 127 && rowPtr[col + 1] >= 128) {
178 // compute point where a mask value will give us a result of 0.5
179 float interp = (127.5f - rowPtr[col]) / (rowPtr[col + 1] - rowPtr[col]);
180 float borderAlpha = (col + interp) / 255.f;
181
182 // compute t value for that alpha
183 // this is an approximate inverse for smoothstep()
184 float t = borderAlpha*(borderAlpha*(4.0f*borderAlpha - 6.0f) + 5.0f) / 3.0f;
185
186 // compute distance which gives us that t value
187 const float kDistanceFieldAAFactor = 0.65f; // should match SK_DistanceFieldAAFactor
188 float d = 2.0f*kDistanceFieldAAFactor*t - kDistanceFieldAAFactor;
189
190 fTable[row] = d;
191 break;
192 }
193 }
194 }
joshualitt1d89e8d2015-04-01 12:40:54 -0700195}
196
joshualittdbd35932015-04-02 09:19:04 -0700197GrAtlasTextContext* GrAtlasTextContext::Create(GrContext* context,
198 SkGpuDevice* gpuDevice,
joshualitt9bd2daf2015-04-17 09:30:06 -0700199 const SkDeviceProperties& props,
200 bool enableDistanceFields) {
201 return SkNEW_ARGS(GrAtlasTextContext, (context, gpuDevice, props, enableDistanceFields));
joshualitt1d89e8d2015-04-01 12:40:54 -0700202}
203
joshualittdbd35932015-04-02 09:19:04 -0700204bool GrAtlasTextContext::canDraw(const GrRenderTarget*,
205 const GrClip&,
206 const GrPaint&,
207 const SkPaint& skPaint,
208 const SkMatrix& viewMatrix) {
joshualitt9bd2daf2015-04-17 09:30:06 -0700209 return this->canDrawAsDistanceFields(skPaint, viewMatrix) ||
210 !SkDraw::ShouldDrawTextAsPaths(skPaint, viewMatrix);
joshualitt1d89e8d2015-04-01 12:40:54 -0700211}
212
joshualitt9e36c1a2015-04-14 12:17:27 -0700213GrColor GrAtlasTextContext::ComputeCanonicalColor(const SkPaint& paint, bool lcd) {
214 GrColor canonicalColor = paint.computeLuminanceColor();
215 if (lcd) {
216 // This is the correct computation, but there are tons of cases where LCD can be overridden.
217 // For now we just regenerate if any run in a textblob has LCD.
218 // TODO figure out where all of these overrides are and see if we can incorporate that logic
219 // at a higher level *OR* use sRGB
220 SkASSERT(false);
221 //canonicalColor = SkMaskGamma::CanonicalColor(canonicalColor);
222 } else {
223 // A8, though can have mixed BMP text but it shouldn't matter because BMP text won't have
224 // gamma corrected masks anyways, nor color
225 U8CPU lum = SkComputeLuminance(SkColorGetR(canonicalColor),
226 SkColorGetG(canonicalColor),
227 SkColorGetB(canonicalColor));
228 // reduce to our finite number of bits
229 canonicalColor = SkMaskGamma::CanonicalColor(SkColorSetRGB(lum, lum, lum));
230 }
231 return canonicalColor;
232}
233
234// TODO if this function ever shows up in profiling, then we can compute this value when the
235// textblob is being built and cache it. However, for the time being textblobs mostly only have 1
236// run so this is not a big deal to compute here.
237bool GrAtlasTextContext::HasLCD(const SkTextBlob* blob) {
238 SkTextBlob::RunIterator it(blob);
239 for (; !it.done(); it.next()) {
240 if (it.isLCD()) {
241 return true;
242 }
243 }
244 return false;
245}
246
joshualitt2a0e9f32015-04-13 06:12:21 -0700247bool GrAtlasTextContext::MustRegenerateBlob(SkScalar* outTransX, SkScalar* outTransY,
248 const BitmapTextBlob& blob, const SkPaint& paint,
joshualitt53b5f442015-04-13 06:33:59 -0700249 const SkMaskFilter::BlurRec& blurRec,
joshualittdbd35932015-04-02 09:19:04 -0700250 const SkMatrix& viewMatrix, SkScalar x, SkScalar y) {
joshualitt9e36c1a2015-04-14 12:17:27 -0700251 // If we have LCD text then our canonical color will be set to transparent, in this case we have
252 // to regenerate the blob on any color change
253 if (blob.fKey.fCanonicalColor == SK_ColorTRANSPARENT && blob.fPaintColor != paint.getColor()) {
joshualitt2a0e9f32015-04-13 06:12:21 -0700254 return true;
255 }
256
257 if (blob.fViewMatrix.hasPerspective() != viewMatrix.hasPerspective()) {
258 return true;
259 }
260
261 if (blob.fViewMatrix.hasPerspective() && !blob.fViewMatrix.cheapEqualTo(viewMatrix)) {
262 return true;
263 }
264
joshualitt53b5f442015-04-13 06:33:59 -0700265 // We only cache one masked version
266 if (blob.fKey.fHasBlur &&
267 (blob.fBlurRec.fSigma != blurRec.fSigma ||
268 blob.fBlurRec.fStyle != blurRec.fStyle ||
269 blob.fBlurRec.fQuality != blurRec.fQuality)) {
270 return true;
271 }
272
273 // Similarly, we only cache one version for each style
274 if (blob.fKey.fStyle != SkPaint::kFill_Style &&
275 (blob.fStrokeInfo.fFrameWidth != paint.getStrokeWidth() ||
276 blob.fStrokeInfo.fMiterLimit != paint.getStrokeMiter() ||
277 blob.fStrokeInfo.fJoin != paint.getStrokeJoin())) {
278 return true;
279 }
280
joshualittfcfb9fc2015-04-21 07:35:10 -0700281 // Mixed blobs must be regenerated. We could probably figure out a way to do integer scrolls
282 // for mixed blobs if this becomes an issue.
283 if (blob.hasBitmap() && blob.hasDistanceField()) {
joshualitt473ffa12015-04-22 18:23:15 -0700284 // Identical viewmatrices and we can reuse in all cases
285 if (blob.fViewMatrix.cheapEqualTo(viewMatrix) && x == blob.fX && y == blob.fY) {
286 return false;
287 }
joshualitt2a0e9f32015-04-13 06:12:21 -0700288 return true;
289 }
290
joshualittfcfb9fc2015-04-21 07:35:10 -0700291 if (blob.hasBitmap()) {
joshualitt64c99cc2015-04-21 09:43:03 -0700292 if (blob.fViewMatrix.getScaleX() != viewMatrix.getScaleX() ||
293 blob.fViewMatrix.getScaleY() != viewMatrix.getScaleY() ||
294 blob.fViewMatrix.getSkewX() != viewMatrix.getSkewX() ||
295 blob.fViewMatrix.getSkewY() != viewMatrix.getSkewY()) {
296 return true;
297 }
298
joshualittfcfb9fc2015-04-21 07:35:10 -0700299 // We can update the positions in the cachedtextblobs without regenerating the whole blob,
300 // but only for integer translations.
301 // This cool bit of math will determine the necessary translation to apply to the already
302 // generated vertex coordinates to move them to the correct position
303 SkScalar transX = viewMatrix.getTranslateX() +
304 viewMatrix.getScaleX() * (x - blob.fX) +
305 viewMatrix.getSkewX() * (y - blob.fY) -
306 blob.fViewMatrix.getTranslateX();
307 SkScalar transY = viewMatrix.getTranslateY() +
308 viewMatrix.getSkewY() * (x - blob.fX) +
309 viewMatrix.getScaleY() * (y - blob.fY) -
310 blob.fViewMatrix.getTranslateY();
joshualittf0c000d2015-04-27 09:36:55 -0700311 if (!SkScalarIsInt(transX) || !SkScalarIsInt(transY) ) {
joshualittfcfb9fc2015-04-21 07:35:10 -0700312 return true;
313 }
314
joshualittfcfb9fc2015-04-21 07:35:10 -0700315 (*outTransX) = transX;
316 (*outTransY) = transY;
joshualitta7c63892015-04-21 13:24:37 -0700317 } else if (blob.hasDistanceField()) {
joshualitt64c99cc2015-04-21 09:43:03 -0700318 // A scale outside of [blob.fMaxMinScale, blob.fMinMaxScale] would result in a different
319 // distance field being generated, so we have to regenerate in those cases
320 SkScalar newMaxScale = viewMatrix.getMaxScale();
321 SkScalar oldMaxScale = blob.fViewMatrix.getMaxScale();
322 SkScalar scaleAdjust = newMaxScale / oldMaxScale;
323 if (scaleAdjust < blob.fMaxMinScale || scaleAdjust > blob.fMinMaxScale) {
324 return true;
325 }
326
327 (*outTransX) = x - blob.fX;
328 (*outTransY) = y - blob.fY;
joshualittfcfb9fc2015-04-21 07:35:10 -0700329 }
joshualitta7c63892015-04-21 13:24:37 -0700330 // It is possible that a blob has neither distanceField nor bitmaptext. This is in the case
331 // when all of the runs inside the blob are drawn as paths. In this case, we always regenerate
332 // the blob anyways at flush time, so no need to regenerate explicitly
joshualittfcfb9fc2015-04-21 07:35:10 -0700333
joshualitt2a0e9f32015-04-13 06:12:21 -0700334 return false;
joshualitt1d89e8d2015-04-01 12:40:54 -0700335}
336
337
joshualittdbd35932015-04-02 09:19:04 -0700338inline SkGlyphCache* GrAtlasTextContext::setupCache(BitmapTextBlob::Run* run,
339 const SkPaint& skPaint,
joshualitt9bd2daf2015-04-17 09:30:06 -0700340 const SkMatrix* viewMatrix,
341 bool noGamma) {
342 skPaint.getScalerContextDescriptor(&run->fDescriptor, &fDeviceProperties, viewMatrix, noGamma);
joshualitt1d89e8d2015-04-01 12:40:54 -0700343 run->fTypeface.reset(SkSafeRef(skPaint.getTypeface()));
344 return SkGlyphCache::DetachCache(run->fTypeface, run->fDescriptor.getDesc());
345}
346
joshualittdbd35932015-04-02 09:19:04 -0700347void GrAtlasTextContext::drawTextBlob(GrRenderTarget* rt, const GrClip& clip,
348 const SkPaint& skPaint, const SkMatrix& viewMatrix,
349 const SkTextBlob* blob, SkScalar x, SkScalar y,
350 SkDrawFilter* drawFilter, const SkIRect& clipBounds) {
joshualitt9b8e79e2015-04-24 09:57:12 -0700351 // If we have been abandoned, then don't draw
352 if (!fContext->getTextTarget()) {
353 return;
354 }
355
joshualitt2a0e9f32015-04-13 06:12:21 -0700356 SkAutoTUnref<BitmapTextBlob> cacheBlob;
joshualitt53b5f442015-04-13 06:33:59 -0700357 SkMaskFilter::BlurRec blurRec;
358 BitmapTextBlob::Key key;
359 // It might be worth caching these things, but its not clear at this time
360 // TODO for animated mask filters, this will fill up our cache. We need a safeguard here
361 const SkMaskFilter* mf = skPaint.getMaskFilter();
joshualitt2a0e9f32015-04-13 06:12:21 -0700362 bool canCache = !(skPaint.getPathEffect() ||
joshualitt53b5f442015-04-13 06:33:59 -0700363 (mf && !mf->asABlur(&blurRec)) ||
joshualitt2a0e9f32015-04-13 06:12:21 -0700364 drawFilter);
365
366 if (canCache) {
joshualitt9e36c1a2015-04-14 12:17:27 -0700367 bool hasLCD = HasLCD(blob);
368 // TODO we want to figure out a way to be able to use the canonical color on LCD text,
369 // see the note on ComputeCanonicalColor above. We pick a dummy value for LCD text to
370 // ensure we always match the same key
371 GrColor canonicalColor = hasLCD ? SK_ColorTRANSPARENT :
372 ComputeCanonicalColor(skPaint, hasLCD);
373
joshualitt53b5f442015-04-13 06:33:59 -0700374 key.fUniqueID = blob->uniqueID();
375 key.fStyle = skPaint.getStyle();
376 key.fHasBlur = SkToBool(mf);
joshualitt9e36c1a2015-04-14 12:17:27 -0700377 key.fCanonicalColor = canonicalColor;
joshualitt53b5f442015-04-13 06:33:59 -0700378 cacheBlob.reset(SkSafeRef(fCache->find(key)));
joshualitt2a0e9f32015-04-13 06:12:21 -0700379 }
380
joshualitt1d89e8d2015-04-01 12:40:54 -0700381 SkIRect clipRect;
382 clip.getConservativeBounds(rt->width(), rt->height(), &clipRect);
383
joshualitt2a0e9f32015-04-13 06:12:21 -0700384 SkScalar transX = 0.f;
385 SkScalar transY = 0.f;
386
joshualitt9e36c1a2015-04-14 12:17:27 -0700387 // Though for the time being runs in the textblob can override the paint, they only touch font
388 // info.
389 GrPaint grPaint;
bsalomonbed83a62015-04-15 14:18:34 -0700390 if (!SkPaint2GrPaint(fContext, rt, skPaint, viewMatrix, true, &grPaint)) {
391 return;
392 }
joshualitt9e36c1a2015-04-14 12:17:27 -0700393
joshualittb7133be2015-04-08 09:08:31 -0700394 if (cacheBlob) {
joshualitt53b5f442015-04-13 06:33:59 -0700395 if (MustRegenerateBlob(&transX, &transY, *cacheBlob, skPaint, blurRec, viewMatrix, x, y)) {
joshualitt1d89e8d2015-04-01 12:40:54 -0700396 // We have to remake the blob because changes may invalidate our masks.
397 // TODO we could probably get away reuse most of the time if the pointer is unique,
398 // but we'd have to clear the subrun information
joshualittb7133be2015-04-08 09:08:31 -0700399 fCache->remove(cacheBlob);
joshualitt53b5f442015-04-13 06:33:59 -0700400 cacheBlob.reset(SkRef(fCache->createCachedBlob(blob, key, blurRec, skPaint,
401 kGrayTextVASize)));
joshualitt9e36c1a2015-04-14 12:17:27 -0700402 this->regenerateTextBlob(cacheBlob, skPaint, grPaint.getColor(), viewMatrix, blob, x, y,
joshualittfcfb9fc2015-04-21 07:35:10 -0700403 drawFilter, clipRect, rt, clip, grPaint);
joshualittb7133be2015-04-08 09:08:31 -0700404 } else {
joshualitt9e36c1a2015-04-14 12:17:27 -0700405 // If we can reuse the blob, then make sure we update the blob's viewmatrix, and x/y
406 // offsets
joshualitt2a0e9f32015-04-13 06:12:21 -0700407 cacheBlob->fViewMatrix = viewMatrix;
408 cacheBlob->fX = x;
409 cacheBlob->fY = y;
joshualittb7133be2015-04-08 09:08:31 -0700410 fCache->makeMRU(cacheBlob);
joshualitt1d89e8d2015-04-01 12:40:54 -0700411 }
412 } else {
joshualitt2a0e9f32015-04-13 06:12:21 -0700413 if (canCache) {
joshualitt53b5f442015-04-13 06:33:59 -0700414 cacheBlob.reset(SkRef(fCache->createCachedBlob(blob, key, blurRec, skPaint,
415 kGrayTextVASize)));
joshualitt2a0e9f32015-04-13 06:12:21 -0700416 } else {
417 cacheBlob.reset(fCache->createBlob(blob, kGrayTextVASize));
418 }
joshualitt9e36c1a2015-04-14 12:17:27 -0700419 this->regenerateTextBlob(cacheBlob, skPaint, grPaint.getColor(), viewMatrix, blob, x, y,
joshualittfcfb9fc2015-04-21 07:35:10 -0700420 drawFilter, clipRect, rt, clip, grPaint);
joshualitt1d89e8d2015-04-01 12:40:54 -0700421 }
422
joshualitt9e36c1a2015-04-14 12:17:27 -0700423 cacheBlob->fPaintColor = skPaint.getColor();
joshualitt9a27e632015-04-06 10:53:36 -0700424 this->flush(fContext->getTextTarget(), blob, cacheBlob, rt, skPaint, grPaint, drawFilter,
joshualitt2a0e9f32015-04-13 06:12:21 -0700425 clip, viewMatrix, clipBounds, x, y, transX, transY);
joshualitt1d89e8d2015-04-01 12:40:54 -0700426}
427
joshualitt9bd2daf2015-04-17 09:30:06 -0700428inline bool GrAtlasTextContext::canDrawAsDistanceFields(const SkPaint& skPaint,
429 const SkMatrix& viewMatrix) {
430 // TODO: support perspective (need getMaxScale replacement)
431 if (viewMatrix.hasPerspective()) {
432 return false;
433 }
434
435 SkScalar maxScale = viewMatrix.getMaxScale();
436 SkScalar scaledTextSize = maxScale*skPaint.getTextSize();
437 // Hinted text looks far better at small resolutions
438 // Scaling up beyond 2x yields undesireable artifacts
joshualitta7c63892015-04-21 13:24:37 -0700439 if (scaledTextSize < kMinDFFontSize || scaledTextSize > kLargeDFFontLimit) {
joshualitt9bd2daf2015-04-17 09:30:06 -0700440 return false;
441 }
442
443 if (!fEnableDFRendering && !skPaint.isDistanceFieldTextTEMP() &&
444 scaledTextSize < kLargeDFFontSize) {
445 return false;
446 }
447
448 // rasterizers and mask filters modify alpha, which doesn't
449 // translate well to distance
450 if (skPaint.getRasterizer() || skPaint.getMaskFilter() ||
jvanverthe9c0fc62015-04-29 11:18:05 -0700451 !fContext->getTextTarget()->caps()->shaderCaps()->shaderDerivativeSupport()) {
joshualitt9bd2daf2015-04-17 09:30:06 -0700452 return false;
453 }
454
455 // TODO: add some stroking support
456 if (skPaint.getStyle() != SkPaint::kFill_Style) {
457 return false;
458 }
459
460 return true;
461}
462
joshualittdbd35932015-04-02 09:19:04 -0700463void GrAtlasTextContext::regenerateTextBlob(BitmapTextBlob* cacheBlob,
joshualitt9e36c1a2015-04-14 12:17:27 -0700464 const SkPaint& skPaint, GrColor color,
465 const SkMatrix& viewMatrix,
joshualittdbd35932015-04-02 09:19:04 -0700466 const SkTextBlob* blob, SkScalar x, SkScalar y,
joshualittfcfb9fc2015-04-21 07:35:10 -0700467 SkDrawFilter* drawFilter, const SkIRect& clipRect,
468 GrRenderTarget* rt, const GrClip& clip,
469 const GrPaint& paint) {
joshualitt1d89e8d2015-04-01 12:40:54 -0700470 cacheBlob->fViewMatrix = viewMatrix;
471 cacheBlob->fX = x;
472 cacheBlob->fY = y;
joshualitt1d89e8d2015-04-01 12:40:54 -0700473
474 // Regenerate textblob
475 SkPaint runPaint = skPaint;
476 SkTextBlob::RunIterator it(blob);
477 for (int run = 0; !it.done(); it.next(), run++) {
478 int glyphCount = it.glyphCount();
479 size_t textLen = glyphCount * sizeof(uint16_t);
480 const SkPoint& offset = it.offset();
481 // applyFontToPaint() always overwrites the exact same attributes,
482 // so it is safe to not re-seed the paint for this reason.
483 it.applyFontToPaint(&runPaint);
484
485 if (drawFilter && !drawFilter->filter(&runPaint, SkDrawFilter::kText_Type)) {
486 // A false return from filter() means we should abort the current draw.
487 runPaint = skPaint;
488 continue;
489 }
490
491 runPaint.setFlags(fGpuDevice->filterTextFlags(runPaint));
492
joshualitt1d89e8d2015-04-01 12:40:54 -0700493 // setup vertex / glyphIndex for the new run
494 if (run > 0) {
495 PerSubRunInfo& newRun = cacheBlob->fRuns[run].fSubRunInfo.back();
496 PerSubRunInfo& lastRun = cacheBlob->fRuns[run - 1].fSubRunInfo.back();
497
498 newRun.fVertexStartIndex = lastRun.fVertexEndIndex;
499 newRun.fVertexEndIndex = lastRun.fVertexEndIndex;
500
501 newRun.fGlyphStartIndex = lastRun.fGlyphEndIndex;
502 newRun.fGlyphEndIndex = lastRun.fGlyphEndIndex;
503 }
504
joshualittfcfb9fc2015-04-21 07:35:10 -0700505 if (this->canDrawAsDistanceFields(runPaint, viewMatrix)) {
506 cacheBlob->setHasDistanceField();
507 SkPaint dfPaint = runPaint;
508 SkScalar textRatio;
joshualitt64c99cc2015-04-21 09:43:03 -0700509 this->initDistanceFieldPaint(cacheBlob, &dfPaint, &textRatio, viewMatrix);
joshualittfcfb9fc2015-04-21 07:35:10 -0700510 Run& runIdx = cacheBlob->fRuns[run];
511 PerSubRunInfo& subRun = runIdx.fSubRunInfo.back();
512 subRun.fUseLCDText = runPaint.isLCDRenderText();
513 subRun.fDrawAsDistanceFields = true;
joshualitt9a27e632015-04-06 10:53:36 -0700514
joshualittfcfb9fc2015-04-21 07:35:10 -0700515 SkGlyphCache* cache = this->setupCache(&cacheBlob->fRuns[run], dfPaint, NULL, true);
516
517 SkTDArray<char> fallbackTxt;
518 SkTDArray<SkScalar> fallbackPos;
519 SkPoint dfOffset;
520 int scalarsPerPosition = 2;
521 switch (it.positioning()) {
522 case SkTextBlob::kDefault_Positioning: {
523 this->internalDrawDFText(cacheBlob, run, cache, dfPaint, color, viewMatrix,
524 (const char *)it.glyphs(), textLen,
525 x + offset.x(), y + offset.y(), clipRect, textRatio,
526 &fallbackTxt, &fallbackPos, &dfOffset, runPaint);
527 break;
528 }
529 case SkTextBlob::kHorizontal_Positioning: {
530 scalarsPerPosition = 1;
531 dfOffset = SkPoint::Make(x, y + offset.y());
532 this->internalDrawDFPosText(cacheBlob, run, cache, dfPaint, color, viewMatrix,
533 (const char*)it.glyphs(), textLen, it.pos(),
534 scalarsPerPosition, dfOffset, clipRect, textRatio,
535 &fallbackTxt, &fallbackPos);
536 break;
537 }
538 case SkTextBlob::kFull_Positioning: {
539 dfOffset = SkPoint::Make(x, y);
540 this->internalDrawDFPosText(cacheBlob, run, cache, dfPaint, color, viewMatrix,
541 (const char*)it.glyphs(), textLen, it.pos(),
542 scalarsPerPosition, dfOffset, clipRect, textRatio,
543 &fallbackTxt, &fallbackPos);
544 break;
545 }
546 }
547 if (fallbackTxt.count()) {
548 this->fallbackDrawPosText(cacheBlob, run, rt, clip, paint, runPaint, viewMatrix,
549 fallbackTxt, fallbackPos, scalarsPerPosition, dfOffset,
550 clipRect);
551 }
552
553 SkGlyphCache::AttachCache(cache);
554 } else if (SkDraw::ShouldDrawTextAsPaths(runPaint, viewMatrix)) {
555 cacheBlob->fRuns[run].fDrawAsPaths = true;
556 } else {
557 cacheBlob->setHasBitmap();
558 SkGlyphCache* cache = this->setupCache(&cacheBlob->fRuns[run], runPaint, &viewMatrix,
559 false);
560 switch (it.positioning()) {
561 case SkTextBlob::kDefault_Positioning:
562 this->internalDrawBMPText(cacheBlob, run, cache, runPaint, color, viewMatrix,
563 (const char *)it.glyphs(), textLen,
564 x + offset.x(), y + offset.y(), clipRect);
565 break;
566 case SkTextBlob::kHorizontal_Positioning:
567 this->internalDrawBMPPosText(cacheBlob, run, cache, runPaint, color, viewMatrix,
568 (const char*)it.glyphs(), textLen, it.pos(), 1,
569 SkPoint::Make(x, y + offset.y()), clipRect);
570 break;
571 case SkTextBlob::kFull_Positioning:
572 this->internalDrawBMPPosText(cacheBlob, run, cache, runPaint, color, viewMatrix,
573 (const char*)it.glyphs(), textLen, it.pos(), 2,
574 SkPoint::Make(x, y), clipRect);
575 break;
576 }
577 SkGlyphCache::AttachCache(cache);
joshualitt1d89e8d2015-04-01 12:40:54 -0700578 }
579
580 if (drawFilter) {
581 // A draw filter may change the paint arbitrarily, so we must re-seed in this case.
582 runPaint = skPaint;
583 }
joshualitt1d89e8d2015-04-01 12:40:54 -0700584 }
585}
586
joshualitt64c99cc2015-04-21 09:43:03 -0700587inline void GrAtlasTextContext::initDistanceFieldPaint(BitmapTextBlob* blob,
588 SkPaint* skPaint,
589 SkScalar* textRatio,
joshualitt9bd2daf2015-04-17 09:30:06 -0700590 const SkMatrix& viewMatrix) {
591 // getMaxScale doesn't support perspective, so neither do we at the moment
592 SkASSERT(!viewMatrix.hasPerspective());
593 SkScalar maxScale = viewMatrix.getMaxScale();
594 SkScalar textSize = skPaint->getTextSize();
595 SkScalar scaledTextSize = textSize;
596 // if we have non-unity scale, we need to choose our base text size
597 // based on the SkPaint's text size multiplied by the max scale factor
598 // TODO: do we need to do this if we're scaling down (i.e. maxScale < 1)?
599 if (maxScale > 0 && !SkScalarNearlyEqual(maxScale, SK_Scalar1)) {
600 scaledTextSize *= maxScale;
601 }
602
joshualitt64c99cc2015-04-21 09:43:03 -0700603 // We have three sizes of distance field text, and within each size 'bucket' there is a floor
604 // and ceiling. A scale outside of this range would require regenerating the distance fields
605 SkScalar dfMaskScaleFloor;
606 SkScalar dfMaskScaleCeil;
joshualitt9bd2daf2015-04-17 09:30:06 -0700607 if (scaledTextSize <= kSmallDFFontLimit) {
joshualitt64c99cc2015-04-21 09:43:03 -0700608 dfMaskScaleFloor = kMinDFFontSize;
joshualitta7c63892015-04-21 13:24:37 -0700609 dfMaskScaleCeil = kSmallDFFontLimit;
joshualitt9bd2daf2015-04-17 09:30:06 -0700610 *textRatio = textSize / kSmallDFFontSize;
611 skPaint->setTextSize(SkIntToScalar(kSmallDFFontSize));
612 } else if (scaledTextSize <= kMediumDFFontLimit) {
joshualitta7c63892015-04-21 13:24:37 -0700613 dfMaskScaleFloor = kSmallDFFontLimit;
614 dfMaskScaleCeil = kMediumDFFontLimit;
joshualitt9bd2daf2015-04-17 09:30:06 -0700615 *textRatio = textSize / kMediumDFFontSize;
616 skPaint->setTextSize(SkIntToScalar(kMediumDFFontSize));
617 } else {
joshualitta7c63892015-04-21 13:24:37 -0700618 dfMaskScaleFloor = kMediumDFFontLimit;
619 dfMaskScaleCeil = kLargeDFFontLimit;
joshualitt9bd2daf2015-04-17 09:30:06 -0700620 *textRatio = textSize / kLargeDFFontSize;
621 skPaint->setTextSize(SkIntToScalar(kLargeDFFontSize));
622 }
623
joshualitt64c99cc2015-04-21 09:43:03 -0700624 // Because there can be multiple runs in the blob, we want the overall maxMinScale, and
625 // minMaxScale to make regeneration decisions. Specifically, we want the maximum minimum scale
626 // we can tolerate before we'd drop to a lower mip size, and the minimum maximum scale we can
627 // tolerate before we'd have to move to a large mip size. When we actually test these values
628 // we look at the delta in scale between the new viewmatrix and the old viewmatrix, and test
629 // against these values to decide if we can reuse or not(ie, will a given scale change our mip
630 // level)
joshualitta7c63892015-04-21 13:24:37 -0700631 SkASSERT(dfMaskScaleFloor <= scaledTextSize && scaledTextSize <= dfMaskScaleCeil);
joshualitt64c99cc2015-04-21 09:43:03 -0700632 blob->fMaxMinScale = SkMaxScalar(dfMaskScaleFloor / scaledTextSize, blob->fMaxMinScale);
633 blob->fMinMaxScale = SkMinScalar(dfMaskScaleCeil / scaledTextSize, blob->fMinMaxScale);
634
joshualitt9bd2daf2015-04-17 09:30:06 -0700635 skPaint->setLCDRenderText(false);
636 skPaint->setAutohinted(false);
637 skPaint->setHinting(SkPaint::kNormal_Hinting);
638 skPaint->setSubpixelText(true);
639}
640
joshualittfec19e12015-04-17 10:32:32 -0700641inline void GrAtlasTextContext::fallbackDrawPosText(BitmapTextBlob* blob,
joshualittfcfb9fc2015-04-21 07:35:10 -0700642 int runIndex,
joshualittfec19e12015-04-17 10:32:32 -0700643 GrRenderTarget* rt, const GrClip& clip,
joshualitt9bd2daf2015-04-17 09:30:06 -0700644 const GrPaint& paint,
645 const SkPaint& skPaint,
646 const SkMatrix& viewMatrix,
647 const SkTDArray<char>& fallbackTxt,
648 const SkTDArray<SkScalar>& fallbackPos,
649 int scalarsPerPosition,
650 const SkPoint& offset,
651 const SkIRect& clipRect) {
joshualittfec19e12015-04-17 10:32:32 -0700652 SkASSERT(fallbackTxt.count());
joshualittfcfb9fc2015-04-21 07:35:10 -0700653 blob->setHasBitmap();
654 Run& run = blob->fRuns[runIndex];
joshualitt97202d22015-04-22 13:47:02 -0700655 // Push back a new subrun to fill and set the override descriptor
656 run.push_back();
657 run.fOverrideDescriptor.reset(SkNEW(SkAutoDescriptor));
658 skPaint.getScalerContextDescriptor(run.fOverrideDescriptor,
joshualittfec19e12015-04-17 10:32:32 -0700659 &fDeviceProperties, &viewMatrix, false);
660 SkGlyphCache* cache = SkGlyphCache::DetachCache(run.fTypeface,
joshualitt97202d22015-04-22 13:47:02 -0700661 run.fOverrideDescriptor->getDesc());
joshualittfcfb9fc2015-04-21 07:35:10 -0700662 this->internalDrawBMPPosText(blob, runIndex, cache, skPaint, paint.getColor(), viewMatrix,
joshualitt9bd2daf2015-04-17 09:30:06 -0700663 fallbackTxt.begin(), fallbackTxt.count(),
664 fallbackPos.begin(), scalarsPerPosition, offset, clipRect);
665 SkGlyphCache::AttachCache(cache);
joshualitt9bd2daf2015-04-17 09:30:06 -0700666}
667
668inline GrAtlasTextContext::BitmapTextBlob*
669GrAtlasTextContext::setupDFBlob(int glyphCount, const SkPaint& origPaint,
670 const SkMatrix& viewMatrix, SkGlyphCache** cache,
671 SkPaint* dfPaint, SkScalar* textRatio) {
672 BitmapTextBlob* blob = fCache->createBlob(glyphCount, 1, kGrayTextVASize);
673
674 *dfPaint = origPaint;
joshualitt64c99cc2015-04-21 09:43:03 -0700675 this->initDistanceFieldPaint(blob, dfPaint, textRatio, viewMatrix);
joshualitt9bd2daf2015-04-17 09:30:06 -0700676 blob->fViewMatrix = viewMatrix;
joshualittfcfb9fc2015-04-21 07:35:10 -0700677 Run& run = blob->fRuns[0];
678 PerSubRunInfo& subRun = run.fSubRunInfo.back();
679 subRun.fUseLCDText = origPaint.isLCDRenderText();
680 subRun.fDrawAsDistanceFields = true;
joshualitt9bd2daf2015-04-17 09:30:06 -0700681
682 *cache = this->setupCache(&blob->fRuns[0], *dfPaint, NULL, true);
683 return blob;
684}
685
joshualittdbd35932015-04-02 09:19:04 -0700686void GrAtlasTextContext::onDrawText(GrRenderTarget* rt, const GrClip& clip,
687 const GrPaint& paint, const SkPaint& skPaint,
688 const SkMatrix& viewMatrix,
689 const char text[], size_t byteLength,
690 SkScalar x, SkScalar y, const SkIRect& regionClipBounds) {
joshualitt1d89e8d2015-04-01 12:40:54 -0700691 int glyphCount = skPaint.countText(text, byteLength);
joshualitt1d89e8d2015-04-01 12:40:54 -0700692 SkIRect clipRect;
693 clip.getConservativeBounds(rt->width(), rt->height(), &clipRect);
694
695 // setup cache
joshualitt9bd2daf2015-04-17 09:30:06 -0700696 if (this->canDrawAsDistanceFields(skPaint, viewMatrix)) {
697 SkPaint dfPaint;
698 SkScalar textRatio;
699 SkGlyphCache* cache;
700 SkAutoTUnref<BitmapTextBlob> blob(this->setupDFBlob(glyphCount, skPaint, viewMatrix, &cache,
701 &dfPaint, &textRatio));
joshualitt1d89e8d2015-04-01 12:40:54 -0700702
joshualitt9bd2daf2015-04-17 09:30:06 -0700703 SkTDArray<char> fallbackTxt;
704 SkTDArray<SkScalar> fallbackPos;
705 SkPoint offset;
706 this->internalDrawDFText(blob, 0, cache, dfPaint, paint.getColor(), viewMatrix, text,
707 byteLength, x, y, clipRect, textRatio, &fallbackTxt, &fallbackPos,
708 &offset, skPaint);
709 SkGlyphCache::AttachCache(cache);
joshualitt9bd2daf2015-04-17 09:30:06 -0700710 if (fallbackTxt.count()) {
joshualittfcfb9fc2015-04-21 07:35:10 -0700711 this->fallbackDrawPosText(blob, 0, rt, clip, paint, skPaint, viewMatrix, fallbackTxt,
joshualitt9bd2daf2015-04-17 09:30:06 -0700712 fallbackPos, 2, offset, clipRect);
713 }
joshualittfec19e12015-04-17 10:32:32 -0700714 this->flush(fContext->getTextTarget(), blob, rt, skPaint, paint, clip);
joshualitt9bd2daf2015-04-17 09:30:06 -0700715 } else {
716 SkAutoTUnref<BitmapTextBlob> blob(fCache->createBlob(glyphCount, 1, kGrayTextVASize));
717 blob->fViewMatrix = viewMatrix;
718
719 SkGlyphCache* cache = this->setupCache(&blob->fRuns[0], skPaint, &viewMatrix, false);
720 this->internalDrawBMPText(blob, 0, cache, skPaint, paint.getColor(), viewMatrix, text,
721 byteLength, x, y, clipRect);
722 SkGlyphCache::AttachCache(cache);
723 this->flush(fContext->getTextTarget(), blob, rt, skPaint, paint, clip);
724 }
joshualitt1d89e8d2015-04-01 12:40:54 -0700725}
726
joshualitt9bd2daf2015-04-17 09:30:06 -0700727void GrAtlasTextContext::onDrawPosText(GrRenderTarget* rt, const GrClip& clip,
728 const GrPaint& paint, const SkPaint& skPaint,
729 const SkMatrix& viewMatrix,
730 const char text[], size_t byteLength,
731 const SkScalar pos[], int scalarsPerPosition,
732 const SkPoint& offset, const SkIRect& regionClipBounds) {
733 int glyphCount = skPaint.countText(text, byteLength);
734
735 SkIRect clipRect;
736 clip.getConservativeBounds(rt->width(), rt->height(), &clipRect);
737
738 if (this->canDrawAsDistanceFields(skPaint, viewMatrix)) {
739 SkPaint dfPaint;
740 SkScalar textRatio;
741 SkGlyphCache* cache;
742 SkAutoTUnref<BitmapTextBlob> blob(this->setupDFBlob(glyphCount, skPaint, viewMatrix, &cache,
743 &dfPaint, &textRatio));
744
745 SkTDArray<char> fallbackTxt;
746 SkTDArray<SkScalar> fallbackPos;
747 this->internalDrawDFPosText(blob, 0, cache, dfPaint, paint.getColor(), viewMatrix, text,
748 byteLength, pos, scalarsPerPosition, offset, clipRect,
749 textRatio, &fallbackTxt, &fallbackPos);
750 SkGlyphCache::AttachCache(cache);
joshualitt9bd2daf2015-04-17 09:30:06 -0700751 if (fallbackTxt.count()) {
joshualittfcfb9fc2015-04-21 07:35:10 -0700752 this->fallbackDrawPosText(blob, 0, rt, clip, paint, skPaint, viewMatrix, fallbackTxt,
joshualitt9bd2daf2015-04-17 09:30:06 -0700753 fallbackPos, scalarsPerPosition, offset, clipRect);
754 }
joshualittfec19e12015-04-17 10:32:32 -0700755 this->flush(fContext->getTextTarget(), blob, rt, skPaint, paint, clip);
joshualitt9bd2daf2015-04-17 09:30:06 -0700756 } else {
757 SkAutoTUnref<BitmapTextBlob> blob(fCache->createBlob(glyphCount, 1, kGrayTextVASize));
758 blob->fViewMatrix = viewMatrix;
759 SkGlyphCache* cache = this->setupCache(&blob->fRuns[0], skPaint, &viewMatrix, false);
760 this->internalDrawBMPPosText(blob, 0, cache, skPaint, paint.getColor(), viewMatrix, text,
761 byteLength, pos, scalarsPerPosition, offset, clipRect);
762 SkGlyphCache::AttachCache(cache);
763 this->flush(fContext->getTextTarget(), blob, rt, skPaint, paint, clip);
764 }
765}
766
767void GrAtlasTextContext::internalDrawBMPText(BitmapTextBlob* blob, int runIndex,
768 SkGlyphCache* cache, const SkPaint& skPaint,
769 GrColor color,
770 const SkMatrix& viewMatrix,
771 const char text[], size_t byteLength,
772 SkScalar x, SkScalar y, const SkIRect& clipRect) {
joshualitt1d89e8d2015-04-01 12:40:54 -0700773 SkASSERT(byteLength == 0 || text != NULL);
774
775 // nothing to draw
776 if (text == NULL || byteLength == 0) {
777 return;
778 }
779
780 fCurrStrike = NULL;
781 SkDrawCacheProc glyphCacheProc = skPaint.getDrawCacheProc();
782
783 // Get GrFontScaler from cache
784 GrFontScaler* fontScaler = GetGrFontScaler(cache);
785
786 // transform our starting point
787 {
788 SkPoint loc;
789 viewMatrix.mapXY(x, y, &loc);
790 x = loc.fX;
791 y = loc.fY;
792 }
793
794 // need to measure first
795 if (skPaint.getTextAlign() != SkPaint::kLeft_Align) {
796 SkVector stopVector;
797 MeasureText(cache, glyphCacheProc, text, byteLength, &stopVector);
798
799 SkScalar stopX = stopVector.fX;
800 SkScalar stopY = stopVector.fY;
801
802 if (skPaint.getTextAlign() == SkPaint::kCenter_Align) {
803 stopX = SkScalarHalf(stopX);
804 stopY = SkScalarHalf(stopY);
805 }
806 x -= stopX;
807 y -= stopY;
808 }
809
810 const char* stop = text + byteLength;
811
812 SkAutoKern autokern;
813
814 SkFixed fxMask = ~0;
815 SkFixed fyMask = ~0;
816 SkScalar halfSampleX, halfSampleY;
817 if (cache->isSubpixel()) {
818 halfSampleX = halfSampleY = SkFixedToScalar(SkGlyph::kSubpixelRound);
819 SkAxisAlignment baseline = SkComputeAxisAlignmentForHText(viewMatrix);
820 if (kX_SkAxisAlignment == baseline) {
821 fyMask = 0;
822 halfSampleY = SK_ScalarHalf;
823 } else if (kY_SkAxisAlignment == baseline) {
824 fxMask = 0;
825 halfSampleX = SK_ScalarHalf;
826 }
827 } else {
828 halfSampleX = halfSampleY = SK_ScalarHalf;
829 }
830
831 Sk48Dot16 fx = SkScalarTo48Dot16(x + halfSampleX);
832 Sk48Dot16 fy = SkScalarTo48Dot16(y + halfSampleY);
833
834 while (text < stop) {
835 const SkGlyph& glyph = glyphCacheProc(cache, &text, fx & fxMask, fy & fyMask);
836
837 fx += autokern.adjust(glyph);
838
839 if (glyph.fWidth) {
joshualitt9bd2daf2015-04-17 09:30:06 -0700840 this->bmpAppendGlyph(blob,
841 runIndex,
842 GrGlyph::Pack(glyph.getGlyphID(),
843 glyph.getSubXFixed(),
844 glyph.getSubYFixed(),
845 GrGlyph::kCoverage_MaskStyle),
846 Sk48Dot16FloorToInt(fx),
847 Sk48Dot16FloorToInt(fy),
848 color,
849 fontScaler,
850 clipRect);
joshualitt1d89e8d2015-04-01 12:40:54 -0700851 }
852
853 fx += glyph.fAdvanceX;
854 fy += glyph.fAdvanceY;
855 }
856}
857
joshualitt9bd2daf2015-04-17 09:30:06 -0700858void GrAtlasTextContext::internalDrawBMPPosText(BitmapTextBlob* blob, int runIndex,
859 SkGlyphCache* cache, const SkPaint& skPaint,
860 GrColor color,
861 const SkMatrix& viewMatrix,
862 const char text[], size_t byteLength,
863 const SkScalar pos[], int scalarsPerPosition,
864 const SkPoint& offset, const SkIRect& clipRect) {
joshualitt1d89e8d2015-04-01 12:40:54 -0700865 SkASSERT(byteLength == 0 || text != NULL);
866 SkASSERT(1 == scalarsPerPosition || 2 == scalarsPerPosition);
867
868 // nothing to draw
869 if (text == NULL || byteLength == 0) {
870 return;
871 }
872
873 fCurrStrike = NULL;
874 SkDrawCacheProc glyphCacheProc = skPaint.getDrawCacheProc();
875
876 // Get GrFontScaler from cache
877 GrFontScaler* fontScaler = GetGrFontScaler(cache);
878
879 const char* stop = text + byteLength;
880 SkTextAlignProc alignProc(skPaint.getTextAlign());
881 SkTextMapStateProc tmsProc(viewMatrix, offset, scalarsPerPosition);
882
883 if (cache->isSubpixel()) {
884 // maybe we should skip the rounding if linearText is set
885 SkAxisAlignment baseline = SkComputeAxisAlignmentForHText(viewMatrix);
886
887 SkFixed fxMask = ~0;
888 SkFixed fyMask = ~0;
889 SkScalar halfSampleX = SkFixedToScalar(SkGlyph::kSubpixelRound);
890 SkScalar halfSampleY = SkFixedToScalar(SkGlyph::kSubpixelRound);
891 if (kX_SkAxisAlignment == baseline) {
892 fyMask = 0;
893 halfSampleY = SK_ScalarHalf;
894 } else if (kY_SkAxisAlignment == baseline) {
895 fxMask = 0;
896 halfSampleX = SK_ScalarHalf;
897 }
898
899 if (SkPaint::kLeft_Align == skPaint.getTextAlign()) {
900 while (text < stop) {
901 SkPoint tmsLoc;
902 tmsProc(pos, &tmsLoc);
903 Sk48Dot16 fx = SkScalarTo48Dot16(tmsLoc.fX + halfSampleX);
904 Sk48Dot16 fy = SkScalarTo48Dot16(tmsLoc.fY + halfSampleY);
905
906 const SkGlyph& glyph = glyphCacheProc(cache, &text,
907 fx & fxMask, fy & fyMask);
908
909 if (glyph.fWidth) {
joshualitt9bd2daf2015-04-17 09:30:06 -0700910 this->bmpAppendGlyph(blob,
911 runIndex,
912 GrGlyph::Pack(glyph.getGlyphID(),
913 glyph.getSubXFixed(),
914 glyph.getSubYFixed(),
915 GrGlyph::kCoverage_MaskStyle),
916 Sk48Dot16FloorToInt(fx),
917 Sk48Dot16FloorToInt(fy),
918 color,
919 fontScaler,
920 clipRect);
joshualitt1d89e8d2015-04-01 12:40:54 -0700921 }
922 pos += scalarsPerPosition;
923 }
924 } else {
925 while (text < stop) {
926 const char* currentText = text;
927 const SkGlyph& metricGlyph = glyphCacheProc(cache, &text, 0, 0);
928
929 if (metricGlyph.fWidth) {
930 SkDEBUGCODE(SkFixed prevAdvX = metricGlyph.fAdvanceX;)
931 SkDEBUGCODE(SkFixed prevAdvY = metricGlyph.fAdvanceY;)
932 SkPoint tmsLoc;
933 tmsProc(pos, &tmsLoc);
934 SkPoint alignLoc;
935 alignProc(tmsLoc, metricGlyph, &alignLoc);
936
937 Sk48Dot16 fx = SkScalarTo48Dot16(alignLoc.fX + halfSampleX);
938 Sk48Dot16 fy = SkScalarTo48Dot16(alignLoc.fY + halfSampleY);
939
940 // have to call again, now that we've been "aligned"
941 const SkGlyph& glyph = glyphCacheProc(cache, &currentText,
942 fx & fxMask, fy & fyMask);
943 // the assumption is that the metrics haven't changed
944 SkASSERT(prevAdvX == glyph.fAdvanceX);
945 SkASSERT(prevAdvY == glyph.fAdvanceY);
946 SkASSERT(glyph.fWidth);
947
joshualitt9bd2daf2015-04-17 09:30:06 -0700948 this->bmpAppendGlyph(blob,
949 runIndex,
950 GrGlyph::Pack(glyph.getGlyphID(),
951 glyph.getSubXFixed(),
952 glyph.getSubYFixed(),
953 GrGlyph::kCoverage_MaskStyle),
954 Sk48Dot16FloorToInt(fx),
955 Sk48Dot16FloorToInt(fy),
956 color,
957 fontScaler,
958 clipRect);
joshualitt1d89e8d2015-04-01 12:40:54 -0700959 }
960 pos += scalarsPerPosition;
961 }
962 }
963 } else { // not subpixel
964
965 if (SkPaint::kLeft_Align == skPaint.getTextAlign()) {
966 while (text < stop) {
967 // the last 2 parameters are ignored
968 const SkGlyph& glyph = glyphCacheProc(cache, &text, 0, 0);
969
970 if (glyph.fWidth) {
971 SkPoint tmsLoc;
972 tmsProc(pos, &tmsLoc);
973
974 Sk48Dot16 fx = SkScalarTo48Dot16(tmsLoc.fX + SK_ScalarHalf); //halfSampleX;
975 Sk48Dot16 fy = SkScalarTo48Dot16(tmsLoc.fY + SK_ScalarHalf); //halfSampleY;
joshualitt9bd2daf2015-04-17 09:30:06 -0700976 this->bmpAppendGlyph(blob,
977 runIndex,
978 GrGlyph::Pack(glyph.getGlyphID(),
979 glyph.getSubXFixed(),
980 glyph.getSubYFixed(),
981 GrGlyph::kCoverage_MaskStyle),
982 Sk48Dot16FloorToInt(fx),
983 Sk48Dot16FloorToInt(fy),
984 color,
985 fontScaler,
986 clipRect);
joshualitt1d89e8d2015-04-01 12:40:54 -0700987 }
988 pos += scalarsPerPosition;
989 }
990 } else {
991 while (text < stop) {
992 // the last 2 parameters are ignored
993 const SkGlyph& glyph = glyphCacheProc(cache, &text, 0, 0);
994
995 if (glyph.fWidth) {
996 SkPoint tmsLoc;
997 tmsProc(pos, &tmsLoc);
998
999 SkPoint alignLoc;
1000 alignProc(tmsLoc, glyph, &alignLoc);
1001
1002 Sk48Dot16 fx = SkScalarTo48Dot16(alignLoc.fX + SK_ScalarHalf); //halfSampleX;
1003 Sk48Dot16 fy = SkScalarTo48Dot16(alignLoc.fY + SK_ScalarHalf); //halfSampleY;
joshualitt9bd2daf2015-04-17 09:30:06 -07001004 this->bmpAppendGlyph(blob,
1005 runIndex,
1006 GrGlyph::Pack(glyph.getGlyphID(),
1007 glyph.getSubXFixed(),
1008 glyph.getSubYFixed(),
1009 GrGlyph::kCoverage_MaskStyle),
1010 Sk48Dot16FloorToInt(fx),
1011 Sk48Dot16FloorToInt(fy),
1012 color,
1013 fontScaler,
1014 clipRect);
joshualitt1d89e8d2015-04-01 12:40:54 -07001015 }
1016 pos += scalarsPerPosition;
1017 }
1018 }
1019 }
1020}
1021
joshualitt9bd2daf2015-04-17 09:30:06 -07001022
1023void GrAtlasTextContext::internalDrawDFText(BitmapTextBlob* blob, int runIndex,
1024 SkGlyphCache* cache, const SkPaint& skPaint,
1025 GrColor color,
1026 const SkMatrix& viewMatrix,
1027 const char text[], size_t byteLength,
1028 SkScalar x, SkScalar y, const SkIRect& clipRect,
1029 SkScalar textRatio,
1030 SkTDArray<char>* fallbackTxt,
1031 SkTDArray<SkScalar>* fallbackPos,
1032 SkPoint* offset,
1033 const SkPaint& origPaint) {
1034 SkASSERT(byteLength == 0 || text != NULL);
1035
1036 // nothing to draw
1037 if (text == NULL || byteLength == 0) {
1038 return;
1039 }
1040
1041 SkDrawCacheProc glyphCacheProc = origPaint.getDrawCacheProc();
1042 SkAutoDescriptor desc;
1043 origPaint.getScalerContextDescriptor(&desc, &fDeviceProperties, NULL, true);
1044 SkGlyphCache* origPaintCache = SkGlyphCache::DetachCache(origPaint.getTypeface(),
1045 desc.getDesc());
1046
1047 SkTArray<SkScalar> positions;
1048
1049 const char* textPtr = text;
1050 SkFixed stopX = 0;
1051 SkFixed stopY = 0;
1052 SkFixed origin = 0;
1053 switch (origPaint.getTextAlign()) {
1054 case SkPaint::kRight_Align: origin = SK_Fixed1; break;
1055 case SkPaint::kCenter_Align: origin = SK_FixedHalf; break;
1056 case SkPaint::kLeft_Align: origin = 0; break;
1057 }
1058
1059 SkAutoKern autokern;
1060 const char* stop = text + byteLength;
1061 while (textPtr < stop) {
1062 // don't need x, y here, since all subpixel variants will have the
1063 // same advance
1064 const SkGlyph& glyph = glyphCacheProc(origPaintCache, &textPtr, 0, 0);
1065
1066 SkFixed width = glyph.fAdvanceX + autokern.adjust(glyph);
1067 positions.push_back(SkFixedToScalar(stopX + SkFixedMul(origin, width)));
1068
1069 SkFixed height = glyph.fAdvanceY;
1070 positions.push_back(SkFixedToScalar(stopY + SkFixedMul(origin, height)));
1071
1072 stopX += width;
1073 stopY += height;
1074 }
1075 SkASSERT(textPtr == stop);
1076
1077 // now adjust starting point depending on alignment
1078 SkScalar alignX = SkFixedToScalar(stopX);
1079 SkScalar alignY = SkFixedToScalar(stopY);
1080 if (origPaint.getTextAlign() == SkPaint::kCenter_Align) {
1081 alignX = SkScalarHalf(alignX);
1082 alignY = SkScalarHalf(alignY);
1083 } else if (origPaint.getTextAlign() == SkPaint::kLeft_Align) {
1084 alignX = 0;
1085 alignY = 0;
1086 }
1087 x -= alignX;
1088 y -= alignY;
1089 *offset = SkPoint::Make(x, y);
1090
1091 this->internalDrawDFPosText(blob, runIndex, cache, skPaint, color, viewMatrix, text, byteLength,
1092 positions.begin(), 2, *offset, clipRect, textRatio, fallbackTxt,
1093 fallbackPos);
1094 SkGlyphCache::AttachCache(origPaintCache);
1095}
1096
1097void GrAtlasTextContext::internalDrawDFPosText(BitmapTextBlob* blob, int runIndex,
1098 SkGlyphCache* cache, const SkPaint& skPaint,
1099 GrColor color,
1100 const SkMatrix& viewMatrix,
1101 const char text[], size_t byteLength,
1102 const SkScalar pos[], int scalarsPerPosition,
1103 const SkPoint& offset, const SkIRect& clipRect,
1104 SkScalar textRatio,
1105 SkTDArray<char>* fallbackTxt,
1106 SkTDArray<SkScalar>* fallbackPos) {
1107
1108 SkASSERT(byteLength == 0 || text != NULL);
1109 SkASSERT(1 == scalarsPerPosition || 2 == scalarsPerPosition);
1110
1111 // nothing to draw
1112 if (text == NULL || byteLength == 0) {
1113 return;
1114 }
1115
1116 fCurrStrike = NULL;
1117
1118 SkDrawCacheProc glyphCacheProc = skPaint.getDrawCacheProc();
1119 GrFontScaler* fontScaler = GetGrFontScaler(cache);
1120
1121 const char* stop = text + byteLength;
1122
1123 if (SkPaint::kLeft_Align == skPaint.getTextAlign()) {
1124 while (text < stop) {
1125 const char* lastText = text;
1126 // the last 2 parameters are ignored
1127 const SkGlyph& glyph = glyphCacheProc(cache, &text, 0, 0);
1128
1129 if (glyph.fWidth) {
1130 SkScalar x = offset.x() + pos[0];
1131 SkScalar y = offset.y() + (2 == scalarsPerPosition ? pos[1] : 0);
1132
1133 if (!this->dfAppendGlyph(blob,
1134 runIndex,
1135 GrGlyph::Pack(glyph.getGlyphID(),
1136 glyph.getSubXFixed(),
1137 glyph.getSubYFixed(),
1138 GrGlyph::kDistance_MaskStyle),
1139 x, y, color, fontScaler, clipRect,
1140 textRatio, viewMatrix)) {
1141 // couldn't append, send to fallback
1142 fallbackTxt->append(SkToInt(text-lastText), lastText);
1143 *fallbackPos->append() = pos[0];
1144 if (2 == scalarsPerPosition) {
1145 *fallbackPos->append() = pos[1];
1146 }
1147 }
1148 }
1149 pos += scalarsPerPosition;
1150 }
1151 } else {
1152 SkScalar alignMul = SkPaint::kCenter_Align == skPaint.getTextAlign() ? SK_ScalarHalf
1153 : SK_Scalar1;
1154 while (text < stop) {
1155 const char* lastText = text;
1156 // the last 2 parameters are ignored
1157 const SkGlyph& glyph = glyphCacheProc(cache, &text, 0, 0);
1158
1159 if (glyph.fWidth) {
1160 SkScalar x = offset.x() + pos[0];
1161 SkScalar y = offset.y() + (2 == scalarsPerPosition ? pos[1] : 0);
1162
1163 SkScalar advanceX = SkFixedToScalar(glyph.fAdvanceX) * alignMul * textRatio;
1164 SkScalar advanceY = SkFixedToScalar(glyph.fAdvanceY) * alignMul * textRatio;
1165
1166 if (!this->dfAppendGlyph(blob,
1167 runIndex,
1168 GrGlyph::Pack(glyph.getGlyphID(),
1169 glyph.getSubXFixed(),
1170 glyph.getSubYFixed(),
1171 GrGlyph::kDistance_MaskStyle),
1172 x - advanceX, y - advanceY, color,
1173 fontScaler,
1174 clipRect,
1175 textRatio,
1176 viewMatrix)) {
1177 // couldn't append, send to fallback
1178 fallbackTxt->append(SkToInt(text-lastText), lastText);
1179 *fallbackPos->append() = pos[0];
1180 if (2 == scalarsPerPosition) {
1181 *fallbackPos->append() = pos[1];
1182 }
1183 }
1184 }
1185 pos += scalarsPerPosition;
1186 }
1187 }
1188}
1189
1190void GrAtlasTextContext::bmpAppendGlyph(BitmapTextBlob* blob, int runIndex,
1191 GrGlyph::PackedID packed,
1192 int vx, int vy, GrColor color, GrFontScaler* scaler,
1193 const SkIRect& clipRect) {
joshualittae32c102015-04-21 09:37:57 -07001194 Run& run = blob->fRuns[runIndex];
joshualitt9bd2daf2015-04-17 09:30:06 -07001195 if (!fCurrStrike) {
joshualitt1d89e8d2015-04-01 12:40:54 -07001196 fCurrStrike = fContext->getBatchFontCache()->getStrike(scaler);
joshualittae32c102015-04-21 09:37:57 -07001197 run.fStrike.reset(SkRef(fCurrStrike));
joshualitt1d89e8d2015-04-01 12:40:54 -07001198 }
1199
1200 GrGlyph* glyph = fCurrStrike->getGlyph(packed, scaler);
joshualitt010db532015-04-21 10:07:26 -07001201 if (!glyph) {
joshualitt1d89e8d2015-04-01 12:40:54 -07001202 return;
1203 }
1204
1205 int x = vx + glyph->fBounds.fLeft;
1206 int y = vy + glyph->fBounds.fTop;
1207
1208 // keep them as ints until we've done the clip-test
1209 int width = glyph->fBounds.width();
1210 int height = glyph->fBounds.height();
1211
joshualitt2a0e9f32015-04-13 06:12:21 -07001212#if 0
1213 // Not checking the clip bounds might introduce a performance regression. However, its not
1214 // clear if this is still true today with the larger tiles we use in Chrome. For repositionable
1215 // blobs, we want to make sure we have all of the glyphs, so clipping them out is not ideal.
1216 // We could store the cliprect in the key, but then we'd lose the ability to do integer scrolls
1217 // TODO verify this
joshualitt1d89e8d2015-04-01 12:40:54 -07001218 // check if we clipped out
1219 if (clipRect.quickReject(x, y, x + width, y + height)) {
1220 return;
1221 }
joshualitt2a0e9f32015-04-13 06:12:21 -07001222#endif
joshualitt1d89e8d2015-04-01 12:40:54 -07001223
1224 // If the glyph is too large we fall back to paths
joshualitt010db532015-04-21 10:07:26 -07001225 if (glyph->fTooLargeForAtlas) {
joshualitt9bd2daf2015-04-17 09:30:06 -07001226 this->appendGlyphPath(blob, glyph, scaler, vx, vy);
joshualitt1d89e8d2015-04-01 12:40:54 -07001227 return;
1228 }
1229
joshualitt1d89e8d2015-04-01 12:40:54 -07001230 GrMaskFormat format = glyph->fMaskFormat;
1231
1232 PerSubRunInfo* subRun = &run.fSubRunInfo.back();
1233 if (run.fInitialized && subRun->fMaskFormat != format) {
joshualittfec19e12015-04-17 10:32:32 -07001234 subRun = &run.fSubRunInfo.push_back();
joshualitt1d89e8d2015-04-01 12:40:54 -07001235 }
1236
1237 run.fInitialized = true;
joshualitt1d89e8d2015-04-01 12:40:54 -07001238
1239 size_t vertexStride = get_vertex_stride(format);
1240
1241 SkRect r;
1242 r.fLeft = SkIntToScalar(x);
1243 r.fTop = SkIntToScalar(y);
1244 r.fRight = r.fLeft + SkIntToScalar(width);
1245 r.fBottom = r.fTop + SkIntToScalar(height);
joshualitt9bd2daf2015-04-17 09:30:06 -07001246 subRun->fMaskFormat = format;
1247 this->appendGlyphCommon(blob, &run, subRun, r, color, vertexStride, kA8_GrMaskFormat == format,
joshualittae32c102015-04-21 09:37:57 -07001248 glyph);
joshualitt9bd2daf2015-04-17 09:30:06 -07001249}
joshualitt1d89e8d2015-04-01 12:40:54 -07001250
joshualitt9bd2daf2015-04-17 09:30:06 -07001251bool GrAtlasTextContext::dfAppendGlyph(BitmapTextBlob* blob, int runIndex,
1252 GrGlyph::PackedID packed,
1253 SkScalar sx, SkScalar sy, GrColor color,
1254 GrFontScaler* scaler,
1255 const SkIRect& clipRect,
1256 SkScalar textRatio, const SkMatrix& viewMatrix) {
joshualittae32c102015-04-21 09:37:57 -07001257 Run& run = blob->fRuns[runIndex];
joshualitt9bd2daf2015-04-17 09:30:06 -07001258 if (!fCurrStrike) {
1259 fCurrStrike = fContext->getBatchFontCache()->getStrike(scaler);
joshualittae32c102015-04-21 09:37:57 -07001260 run.fStrike.reset(SkRef(fCurrStrike));
joshualitt9bd2daf2015-04-17 09:30:06 -07001261 }
1262
1263 GrGlyph* glyph = fCurrStrike->getGlyph(packed, scaler);
joshualitt010db532015-04-21 10:07:26 -07001264 if (!glyph) {
joshualitt9bd2daf2015-04-17 09:30:06 -07001265 return true;
1266 }
1267
1268 // fallback to color glyph support
1269 if (kA8_GrMaskFormat != glyph->fMaskFormat) {
1270 return false;
1271 }
1272
1273 SkScalar dx = SkIntToScalar(glyph->fBounds.fLeft + SK_DistanceFieldInset);
1274 SkScalar dy = SkIntToScalar(glyph->fBounds.fTop + SK_DistanceFieldInset);
1275 SkScalar width = SkIntToScalar(glyph->fBounds.width() - 2 * SK_DistanceFieldInset);
1276 SkScalar height = SkIntToScalar(glyph->fBounds.height() - 2 * SK_DistanceFieldInset);
1277
1278 SkScalar scale = textRatio;
1279 dx *= scale;
1280 dy *= scale;
1281 width *= scale;
1282 height *= scale;
1283 sx += dx;
1284 sy += dy;
1285 SkRect glyphRect = SkRect::MakeXYWH(sx, sy, width, height);
1286
1287#if 0
1288 // check if we clipped out
1289 SkRect dstRect;
1290 viewMatrix.mapRect(&dstRect, glyphRect);
1291 if (clipRect.quickReject(SkScalarTruncToInt(dstRect.left()),
1292 SkScalarTruncToInt(dstRect.top()),
1293 SkScalarTruncToInt(dstRect.right()),
1294 SkScalarTruncToInt(dstRect.bottom()))) {
1295 return true;
1296 }
1297#endif
1298
1299 // TODO combine with the above
1300 // If the glyph is too large we fall back to paths
joshualitt010db532015-04-21 10:07:26 -07001301 if (glyph->fTooLargeForAtlas) {
joshualitt9bd2daf2015-04-17 09:30:06 -07001302 this->appendGlyphPath(blob, glyph, scaler, SkScalarRoundToInt(sx - dx),
1303 SkScalarRoundToInt(sy - dy));
1304 return true;
1305 }
1306
joshualitt9bd2daf2015-04-17 09:30:06 -07001307 PerSubRunInfo* subRun = &run.fSubRunInfo.back();
1308 SkASSERT(glyph->fMaskFormat == kA8_GrMaskFormat);
1309 subRun->fMaskFormat = kA8_GrMaskFormat;
1310
1311 size_t vertexStride = get_vertex_stride_df(kA8_GrMaskFormat, subRun->fUseLCDText);
1312
1313 bool useColorVerts = !subRun->fUseLCDText;
1314 this->appendGlyphCommon(blob, &run, subRun, glyphRect, color, vertexStride, useColorVerts,
joshualittae32c102015-04-21 09:37:57 -07001315 glyph);
joshualitt9bd2daf2015-04-17 09:30:06 -07001316 return true;
1317}
1318
1319inline void GrAtlasTextContext::appendGlyphPath(BitmapTextBlob* blob, GrGlyph* glyph,
1320 GrFontScaler* scaler, int x, int y) {
1321 if (NULL == glyph->fPath) {
1322 SkPath* path = SkNEW(SkPath);
1323 if (!scaler->getGlyphPath(glyph->glyphID(), path)) {
1324 // flag the glyph as being dead?
1325 SkDELETE(path);
1326 return;
1327 }
1328 glyph->fPath = path;
1329 }
1330 SkASSERT(glyph->fPath);
1331 blob->fBigGlyphs.push_back(BitmapTextBlob::BigGlyph(*glyph->fPath, x, y));
1332}
1333
1334inline void GrAtlasTextContext::appendGlyphCommon(BitmapTextBlob* blob, Run* run,
1335 Run::SubRunInfo* subRun,
1336 const SkRect& positions, GrColor color,
1337 size_t vertexStride, bool useVertexColor,
joshualittae32c102015-04-21 09:37:57 -07001338 GrGlyph* glyph) {
1339 blob->fGlyphs[subRun->fGlyphEndIndex] = glyph;
joshualitt9bd2daf2015-04-17 09:30:06 -07001340 run->fVertexBounds.joinNonEmptyArg(positions);
1341 run->fColor = color;
joshualitt1d89e8d2015-04-01 12:40:54 -07001342
1343 intptr_t vertex = reinterpret_cast<intptr_t>(blob->fVertices + subRun->fVertexEndIndex);
1344
joshualitt9bd2daf2015-04-17 09:30:06 -07001345 if (useVertexColor) {
joshualitt010db532015-04-21 10:07:26 -07001346 // V0
1347 SkPoint* position = reinterpret_cast<SkPoint*>(vertex);
1348 position->set(positions.fLeft, positions.fTop);
joshualitt1d89e8d2015-04-01 12:40:54 -07001349 SkColor* colorPtr = reinterpret_cast<SkColor*>(vertex + sizeof(SkPoint));
1350 *colorPtr = color;
joshualitt010db532015-04-21 10:07:26 -07001351 vertex += vertexStride;
joshualitt9bd2daf2015-04-17 09:30:06 -07001352
joshualitt010db532015-04-21 10:07:26 -07001353 // V1
1354 position = reinterpret_cast<SkPoint*>(vertex);
1355 position->set(positions.fLeft, positions.fBottom);
1356 colorPtr = reinterpret_cast<SkColor*>(vertex + sizeof(SkPoint));
joshualitt1d89e8d2015-04-01 12:40:54 -07001357 *colorPtr = color;
joshualitt010db532015-04-21 10:07:26 -07001358 vertex += vertexStride;
joshualitt1d89e8d2015-04-01 12:40:54 -07001359
joshualitt010db532015-04-21 10:07:26 -07001360 // V2
1361 position = reinterpret_cast<SkPoint*>(vertex);
1362 position->set(positions.fRight, positions.fBottom);
1363 colorPtr = reinterpret_cast<SkColor*>(vertex + sizeof(SkPoint));
joshualitt1d89e8d2015-04-01 12:40:54 -07001364 *colorPtr = color;
joshualitt010db532015-04-21 10:07:26 -07001365 vertex += vertexStride;
joshualitt1d89e8d2015-04-01 12:40:54 -07001366
joshualitt010db532015-04-21 10:07:26 -07001367 // V3
1368 position = reinterpret_cast<SkPoint*>(vertex);
1369 position->set(positions.fRight, positions.fTop);
1370 colorPtr = reinterpret_cast<SkColor*>(vertex + sizeof(SkPoint));
joshualitt1d89e8d2015-04-01 12:40:54 -07001371 *colorPtr = color;
joshualitt010db532015-04-21 10:07:26 -07001372 } else {
1373 // V0
1374 SkPoint* position = reinterpret_cast<SkPoint*>(vertex);
1375 position->set(positions.fLeft, positions.fTop);
1376 vertex += vertexStride;
1377
1378 // V1
1379 position = reinterpret_cast<SkPoint*>(vertex);
1380 position->set(positions.fLeft, positions.fBottom);
1381 vertex += vertexStride;
1382
1383 // V2
1384 position = reinterpret_cast<SkPoint*>(vertex);
1385 position->set(positions.fRight, positions.fBottom);
1386 vertex += vertexStride;
1387
1388 // V3
1389 position = reinterpret_cast<SkPoint*>(vertex);
1390 position->set(positions.fRight, positions.fTop);
joshualitt1d89e8d2015-04-01 12:40:54 -07001391 }
1392
1393 subRun->fGlyphEndIndex++;
1394 subRun->fVertexEndIndex += vertexStride * kVerticesPerGlyph;
1395}
1396
1397class BitmapTextBatch : public GrBatch {
1398public:
joshualitt9bd2daf2015-04-17 09:30:06 -07001399 typedef GrAtlasTextContext::DistanceAdjustTable DistanceAdjustTable;
joshualittdbd35932015-04-02 09:19:04 -07001400 typedef GrAtlasTextContext::BitmapTextBlob Blob;
joshualitt1d89e8d2015-04-01 12:40:54 -07001401 typedef Blob::Run Run;
1402 typedef Run::SubRunInfo TextInfo;
1403 struct Geometry {
joshualittad802c62015-04-15 05:31:57 -07001404 Blob* fBlob;
joshualitt1d89e8d2015-04-01 12:40:54 -07001405 int fRun;
1406 int fSubRun;
1407 GrColor fColor;
joshualitt2a0e9f32015-04-13 06:12:21 -07001408 SkScalar fTransX;
1409 SkScalar fTransY;
joshualitt1d89e8d2015-04-01 12:40:54 -07001410 };
1411
joshualittad802c62015-04-15 05:31:57 -07001412 static BitmapTextBatch* Create(GrMaskFormat maskFormat, int glyphCount,
1413 GrBatchFontCache* fontCache) {
1414 return SkNEW_ARGS(BitmapTextBatch, (maskFormat, glyphCount, fontCache));
joshualitt1d89e8d2015-04-01 12:40:54 -07001415 }
1416
joshualitt9bd2daf2015-04-17 09:30:06 -07001417 static BitmapTextBatch* Create(GrMaskFormat maskFormat, int glyphCount,
1418 GrBatchFontCache* fontCache,
1419 DistanceAdjustTable* distanceAdjustTable,
1420 SkColor filteredColor, bool useLCDText,
1421 bool useBGR, float gamma) {
1422 return SkNEW_ARGS(BitmapTextBatch, (maskFormat, glyphCount, fontCache, distanceAdjustTable,
1423 filteredColor, useLCDText, useBGR, gamma));
1424 }
1425
joshualitt1d89e8d2015-04-01 12:40:54 -07001426 const char* name() const override { return "BitmapTextBatch"; }
1427
1428 void getInvariantOutputColor(GrInitInvariantOutput* out) const override {
1429 if (kARGB_GrMaskFormat == fMaskFormat) {
1430 out->setUnknownFourComponents();
1431 } else {
1432 out->setKnownFourComponents(fBatch.fColor);
1433 }
1434 }
1435
1436 void getInvariantOutputCoverage(GrInitInvariantOutput* out) const override {
joshualitt9bd2daf2015-04-17 09:30:06 -07001437 if (!fUseDistanceFields) {
1438 // Bitmap Text
1439 if (kARGB_GrMaskFormat != fMaskFormat) {
1440 if (GrPixelConfigIsAlphaOnly(fPixelConfig)) {
1441 out->setUnknownSingleComponent();
1442 } else if (GrPixelConfigIsOpaque(fPixelConfig)) {
1443 out->setUnknownOpaqueFourComponents();
1444 out->setUsingLCDCoverage();
1445 } else {
1446 out->setUnknownFourComponents();
1447 out->setUsingLCDCoverage();
1448 }
1449 } else {
1450 out->setKnownSingleComponent(0xff);
1451 }
1452 } else {
1453 // Distance fields
1454 if (!fUseLCDText) {
joshualitt1d89e8d2015-04-01 12:40:54 -07001455 out->setUnknownSingleComponent();
joshualitt1d89e8d2015-04-01 12:40:54 -07001456 } else {
1457 out->setUnknownFourComponents();
1458 out->setUsingLCDCoverage();
1459 }
joshualitt1d89e8d2015-04-01 12:40:54 -07001460 }
1461 }
1462
1463 void initBatchTracker(const GrPipelineInfo& init) override {
1464 // Handle any color overrides
1465 if (init.fColorIgnored) {
1466 fBatch.fColor = GrColor_ILLEGAL;
1467 } else if (GrColor_ILLEGAL != init.fOverrideColor) {
1468 fBatch.fColor = init.fOverrideColor;
1469 }
1470
1471 // setup batch properties
1472 fBatch.fColorIgnored = init.fColorIgnored;
1473 fBatch.fUsesLocalCoords = init.fUsesLocalCoords;
1474 fBatch.fCoverageIgnored = init.fCoverageIgnored;
1475 }
1476
bsalomonb5238a72015-05-05 07:49:49 -07001477 struct FlushInfo {
1478 SkAutoTUnref<const GrVertexBuffer> fVertexBuffer;
1479 SkAutoTUnref<const GrIndexBuffer> fIndexBuffer;
1480 int fGlyphsToFlush;
1481 int fVertexOffset;
1482 };
1483
joshualitt1d89e8d2015-04-01 12:40:54 -07001484 void generateGeometry(GrBatchTarget* batchTarget, const GrPipeline* pipeline) override {
1485 // if we have RGB, then we won't have any SkShaders so no need to use a localmatrix.
1486 // TODO actually only invert if we don't have RGBA
1487 SkMatrix localMatrix;
1488 if (this->usesLocalCoords() && !this->viewMatrix().invert(&localMatrix)) {
1489 SkDebugf("Cannot invert viewmatrix\n");
1490 return;
1491 }
1492
joshualitt62db8ba2015-04-09 08:22:37 -07001493 GrTexture* texture = fFontCache->getTexture(fMaskFormat);
1494 if (!texture) {
1495 SkDebugf("Could not allocate backing texture for atlas\n");
1496 return;
1497 }
1498
joshualitt9bd2daf2015-04-17 09:30:06 -07001499 SkAutoTUnref<const GrGeometryProcessor> gp;
1500 if (fUseDistanceFields) {
1501 gp.reset(this->setupDfProcessor(this->viewMatrix(), fFilteredColor, this->color(),
1502 texture));
1503 } else {
1504 GrTextureParams params(SkShader::kClamp_TileMode, GrTextureParams::kNone_FilterMode);
joshualitt50cb76b2015-04-28 09:17:05 -07001505
1506 // This will be ignored in the non A8 case
1507 bool opaqueVertexColors = GrColorIsOpaque(this->color());
joshualitt9bd2daf2015-04-17 09:30:06 -07001508 gp.reset(GrBitmapTextGeoProc::Create(this->color(),
1509 texture,
1510 params,
1511 fMaskFormat,
joshualitt50cb76b2015-04-28 09:17:05 -07001512 opaqueVertexColors,
joshualitt9bd2daf2015-04-17 09:30:06 -07001513 localMatrix));
1514 }
joshualitt1d89e8d2015-04-01 12:40:54 -07001515
bsalomonb5238a72015-05-05 07:49:49 -07001516 FlushInfo flushInfo;
1517 flushInfo.fGlyphsToFlush = 0;
joshualitt1d89e8d2015-04-01 12:40:54 -07001518 size_t vertexStride = gp->getVertexStride();
joshualitt9bd2daf2015-04-17 09:30:06 -07001519 SkASSERT(vertexStride == (fUseDistanceFields ?
1520 get_vertex_stride_df(fMaskFormat, fUseLCDText) :
1521 get_vertex_stride(fMaskFormat)));
joshualitt1d89e8d2015-04-01 12:40:54 -07001522
1523 this->initDraw(batchTarget, gp, pipeline);
1524
1525 int glyphCount = this->numGlyphs();
joshualittad802c62015-04-15 05:31:57 -07001526 int instanceCount = fInstanceCount;
bsalomon8415abe2015-05-04 11:41:41 -07001527 const GrVertexBuffer* vertexBuffer;
bsalomonb5238a72015-05-05 07:49:49 -07001528
joshualitt1d89e8d2015-04-01 12:40:54 -07001529 void* vertices = batchTarget->vertexPool()->makeSpace(vertexStride,
1530 glyphCount * kVerticesPerGlyph,
1531 &vertexBuffer,
bsalomonb5238a72015-05-05 07:49:49 -07001532 &flushInfo.fVertexOffset);
1533 flushInfo.fVertexBuffer.reset(SkRef(vertexBuffer));
1534 flushInfo.fIndexBuffer.reset(batchTarget->resourceProvider()->refQuadIndexBuffer());
1535 if (!vertices || !flushInfo.fVertexBuffer) {
joshualitt1d89e8d2015-04-01 12:40:54 -07001536 SkDebugf("Could not allocate vertices\n");
1537 return;
1538 }
1539
1540 unsigned char* currVertex = reinterpret_cast<unsigned char*>(vertices);
1541
joshualitt25ba7ea2015-04-21 07:49:49 -07001542 // We cache some values to avoid going to the glyphcache for the same fontScaler twice
1543 // in a row
1544 const SkDescriptor* desc = NULL;
1545 SkGlyphCache* cache = NULL;
1546 GrFontScaler* scaler = NULL;
joshualitt25ba7ea2015-04-21 07:49:49 -07001547 SkTypeface* typeface = NULL;
1548
joshualitt1d89e8d2015-04-01 12:40:54 -07001549 for (int i = 0; i < instanceCount; i++) {
1550 Geometry& args = fGeoData[i];
1551 Blob* blob = args.fBlob;
1552 Run& run = blob->fRuns[args.fRun];
1553 TextInfo& info = run.fSubRunInfo[args.fSubRun];
1554
1555 uint64_t currentAtlasGen = fFontCache->atlasGeneration(fMaskFormat);
1556 bool regenerateTextureCoords = info.fAtlasGeneration != currentAtlasGen;
joshualitt9bd2daf2015-04-17 09:30:06 -07001557 bool regenerateColors;
1558 if (fUseDistanceFields) {
joshualittfcfb9fc2015-04-21 07:35:10 -07001559 regenerateColors = !fUseLCDText && run.fColor != args.fColor;
joshualitt9bd2daf2015-04-17 09:30:06 -07001560 } else {
1561 regenerateColors = kA8_GrMaskFormat == fMaskFormat && run.fColor != args.fColor;
1562 }
joshualitt2a0e9f32015-04-13 06:12:21 -07001563 bool regeneratePositions = args.fTransX != 0.f || args.fTransY != 0.f;
joshualitt1d89e8d2015-04-01 12:40:54 -07001564 int glyphCount = info.fGlyphEndIndex - info.fGlyphStartIndex;
1565
1566 // We regenerate both texture coords and colors in the blob itself, and update the
1567 // atlas generation. If we don't end up purging any unused plots, we can avoid
1568 // regenerating the coords. We could take a finer grained approach to updating texture
1569 // coords but its not clear if the extra bookkeeping would offset any gains.
1570 // To avoid looping over the glyphs twice, we do one loop and conditionally update color
1571 // or coords as needed. One final note, if we have to break a run for an atlas eviction
1572 // then we can't really trust the atlas has all of the correct data. Atlas evictions
1573 // should be pretty rare, so we just always regenerate in those cases
joshualitt2a0e9f32015-04-13 06:12:21 -07001574 if (regenerateTextureCoords || regenerateColors || regeneratePositions) {
joshualitt1d89e8d2015-04-01 12:40:54 -07001575 // first regenerate texture coordinates / colors if need be
joshualitt1d89e8d2015-04-01 12:40:54 -07001576 bool brokenRun = false;
joshualittae32c102015-04-21 09:37:57 -07001577
1578 // Because the GrBatchFontCache may evict the strike a blob depends on using for
1579 // generating its texture coords, we have to track whether or not the strike has
1580 // been abandoned. If it hasn't been abandoned, then we can use the GrGlyph*s as is
1581 // otherwise we have to get the new strike, and use that to get the correct glyphs.
1582 // Because we do not have the packed ids, and thus can't look up our glyphs in the
1583 // new strike, we instead keep our ref to the old strike and use the packed ids from
1584 // it. These ids will still be valid as long as we hold the ref. When we are done
1585 // updating our cache of the GrGlyph*s, we drop our ref on the old strike
1586 bool regenerateGlyphs = false;
1587 GrBatchTextStrike* strike = NULL;
joshualitt1d89e8d2015-04-01 12:40:54 -07001588 if (regenerateTextureCoords) {
joshualittb4c507e2015-04-08 08:07:59 -07001589 info.fBulkUseToken.reset();
joshualitt25ba7ea2015-04-21 07:49:49 -07001590
1591 // We can reuse if we have a valid strike and our descriptors / typeface are the
1592 // same
joshualitt97202d22015-04-22 13:47:02 -07001593 const SkDescriptor* newDesc = run.fOverrideDescriptor ?
1594 run.fOverrideDescriptor->getDesc() :
joshualitt25ba7ea2015-04-21 07:49:49 -07001595 run.fDescriptor.getDesc();
1596 if (!cache || !SkTypeface::Equal(typeface, run.fTypeface) ||
1597 !(desc->equals(*newDesc))) {
1598 if (cache) {
1599 SkGlyphCache::AttachCache(cache);
1600 }
1601 desc = newDesc;
1602 cache = SkGlyphCache::DetachCache(run.fTypeface, desc);
1603 scaler = GrTextContext::GetGrFontScaler(cache);
joshualittae32c102015-04-21 09:37:57 -07001604 strike = run.fStrike;
joshualitt25ba7ea2015-04-21 07:49:49 -07001605 typeface = run.fTypeface;
1606 }
joshualitt1d89e8d2015-04-01 12:40:54 -07001607
joshualittae32c102015-04-21 09:37:57 -07001608 if (run.fStrike->isAbandoned()) {
1609 regenerateGlyphs = true;
1610 strike = fFontCache->getStrike(scaler);
1611 } else {
1612 strike = run.fStrike;
1613 }
1614 }
1615
1616 for (int glyphIdx = 0; glyphIdx < glyphCount; glyphIdx++) {
joshualitt1d89e8d2015-04-01 12:40:54 -07001617 if (regenerateTextureCoords) {
joshualittae32c102015-04-21 09:37:57 -07001618 size_t glyphOffset = glyphIdx + info.fGlyphStartIndex;
1619 GrGlyph* glyph;
1620 if (regenerateGlyphs) {
1621 // Get the id from the old glyph, and use the new strike to lookup
1622 // the glyph.
1623 glyph = blob->fGlyphs[glyphOffset];
1624 blob->fGlyphs[glyphOffset] = strike->getGlyph(glyph->fPackedID,
1625 scaler);
1626 }
1627 glyph = blob->fGlyphs[glyphOffset];
joshualitt1d89e8d2015-04-01 12:40:54 -07001628 SkASSERT(glyph);
1629
1630 if (!fFontCache->hasGlyph(glyph) &&
1631 !strike->addGlyphToAtlas(batchTarget, glyph, scaler)) {
bsalomonb5238a72015-05-05 07:49:49 -07001632 this->flush(batchTarget, &flushInfo);
joshualitt1d89e8d2015-04-01 12:40:54 -07001633 this->initDraw(batchTarget, gp, pipeline);
joshualitt1d89e8d2015-04-01 12:40:54 -07001634 brokenRun = glyphIdx > 0;
1635
joshualittae32c102015-04-21 09:37:57 -07001636 SkDEBUGCODE(bool success =) strike->addGlyphToAtlas(batchTarget,
1637 glyph,
joshualitt1d89e8d2015-04-01 12:40:54 -07001638 scaler);
1639 SkASSERT(success);
1640 }
joshualittb4c507e2015-04-08 08:07:59 -07001641 fFontCache->addGlyphToBulkAndSetUseToken(&info.fBulkUseToken, glyph,
1642 batchTarget->currentToken());
joshualitt1d89e8d2015-04-01 12:40:54 -07001643
1644 // Texture coords are the last vertex attribute so we get a pointer to the
1645 // first one and then map with stride in regenerateTextureCoords
1646 intptr_t vertex = reinterpret_cast<intptr_t>(blob->fVertices);
1647 vertex += info.fVertexStartIndex;
1648 vertex += vertexStride * glyphIdx * kVerticesPerGlyph;
1649 vertex += vertexStride - sizeof(SkIPoint16);
1650
1651 this->regenerateTextureCoords(glyph, vertex, vertexStride);
1652 }
1653
1654 if (regenerateColors) {
1655 intptr_t vertex = reinterpret_cast<intptr_t>(blob->fVertices);
1656 vertex += info.fVertexStartIndex;
1657 vertex += vertexStride * glyphIdx * kVerticesPerGlyph + sizeof(SkPoint);
1658 this->regenerateColors(vertex, vertexStride, args.fColor);
1659 }
1660
joshualitt2a0e9f32015-04-13 06:12:21 -07001661 if (regeneratePositions) {
1662 intptr_t vertex = reinterpret_cast<intptr_t>(blob->fVertices);
1663 vertex += info.fVertexStartIndex;
1664 vertex += vertexStride * glyphIdx * kVerticesPerGlyph;
1665 SkScalar transX = args.fTransX;
1666 SkScalar transY = args.fTransY;
1667 this->regeneratePositions(vertex, vertexStride, transX, transY);
1668 }
bsalomonb5238a72015-05-05 07:49:49 -07001669 flushInfo.fGlyphsToFlush++;
joshualitt1d89e8d2015-04-01 12:40:54 -07001670 }
1671
joshualitt2a0e9f32015-04-13 06:12:21 -07001672 // We my have changed the color so update it here
1673 run.fColor = args.fColor;
joshualitt1d89e8d2015-04-01 12:40:54 -07001674 if (regenerateTextureCoords) {
joshualittae32c102015-04-21 09:37:57 -07001675 if (regenerateGlyphs) {
1676 run.fStrike.reset(SkRef(strike));
1677 }
joshualitt1d89e8d2015-04-01 12:40:54 -07001678 info.fAtlasGeneration = brokenRun ? GrBatchAtlas::kInvalidAtlasGeneration :
1679 fFontCache->atlasGeneration(fMaskFormat);
1680 }
1681 } else {
bsalomonb5238a72015-05-05 07:49:49 -07001682 flushInfo.fGlyphsToFlush += glyphCount;
joshualittb4c507e2015-04-08 08:07:59 -07001683
1684 // set use tokens for all of the glyphs in our subrun. This is only valid if we
1685 // have a valid atlas generation
1686 fFontCache->setUseTokenBulk(info.fBulkUseToken,
1687 batchTarget->currentToken(),
1688 fMaskFormat);
joshualitt1d89e8d2015-04-01 12:40:54 -07001689 }
1690
1691 // now copy all vertices
1692 size_t byteCount = info.fVertexEndIndex - info.fVertexStartIndex;
1693 memcpy(currVertex, blob->fVertices + info.fVertexStartIndex, byteCount);
1694
1695 currVertex += byteCount;
1696 }
joshualitt25ba7ea2015-04-21 07:49:49 -07001697 // Make sure to attach the last cache if applicable
1698 if (cache) {
1699 SkGlyphCache::AttachCache(cache);
1700 }
bsalomonb5238a72015-05-05 07:49:49 -07001701 this->flush(batchTarget, &flushInfo);
joshualitt1d89e8d2015-04-01 12:40:54 -07001702 }
1703
joshualittad802c62015-04-15 05:31:57 -07001704 // The minimum number of Geometry we will try to allocate.
1705 static const int kMinAllocated = 32;
1706
1707 // Total number of Geometry this Batch owns
1708 int instanceCount() const { return fInstanceCount; }
1709 SkAutoSTMalloc<kMinAllocated, Geometry>* geoData() { return &fGeoData; }
1710
1711 // to avoid even the initial copy of the struct, we have a getter for the first item which
1712 // is used to seed the batch with its initial geometry. After seeding, the client should call
1713 // init() so the Batch can initialize itself
1714 Geometry& geometry() { return fGeoData[0]; }
1715 void init() {
joshualitt444987f2015-05-06 06:46:01 -07001716 const Geometry& geo = fGeoData[0];
1717 fBatch.fColor = geo.fColor;
1718 fBatch.fViewMatrix = geo.fBlob->fViewMatrix;
1719
1720 // We don't yet position distance field text on the cpu, so we have to map the vertex bounds
1721 // into device space
1722 const Run& run = geo.fBlob->fRuns[geo.fRun];
1723 if (run.fSubRunInfo[geo.fSubRun].fDrawAsDistanceFields) {
1724 SkRect bounds = run.fVertexBounds;
1725 fBatch.fViewMatrix.mapRect(&bounds);
1726 this->setBounds(bounds);
1727 } else {
1728 this->setBounds(run.fVertexBounds);
1729 }
joshualittad802c62015-04-15 05:31:57 -07001730 }
joshualitt1d89e8d2015-04-01 12:40:54 -07001731
1732private:
joshualitt9bd2daf2015-04-17 09:30:06 -07001733 BitmapTextBatch(GrMaskFormat maskFormat, int glyphCount, GrBatchFontCache* fontCache)
joshualitt1d89e8d2015-04-01 12:40:54 -07001734 : fMaskFormat(maskFormat)
1735 , fPixelConfig(fontCache->getPixelConfig(maskFormat))
joshualitt9bd2daf2015-04-17 09:30:06 -07001736 , fFontCache(fontCache)
1737 , fUseDistanceFields(false) {
joshualitt1d89e8d2015-04-01 12:40:54 -07001738 this->initClassID<BitmapTextBatch>();
joshualitt1d89e8d2015-04-01 12:40:54 -07001739 fBatch.fNumGlyphs = glyphCount;
joshualittad802c62015-04-15 05:31:57 -07001740 fInstanceCount = 1;
1741 fAllocatedCount = kMinAllocated;
1742 }
1743
joshualitt9bd2daf2015-04-17 09:30:06 -07001744 BitmapTextBatch(GrMaskFormat maskFormat, int glyphCount, GrBatchFontCache* fontCache,
1745 DistanceAdjustTable* distanceAdjustTable, SkColor filteredColor,
1746 bool useLCDText, bool useBGR, float gamma)
1747 : fMaskFormat(maskFormat)
1748 , fPixelConfig(fontCache->getPixelConfig(maskFormat))
1749 , fFontCache(fontCache)
1750 , fDistanceAdjustTable(SkRef(distanceAdjustTable))
1751 , fFilteredColor(filteredColor)
1752 , fUseDistanceFields(true)
1753 , fUseLCDText(useLCDText)
1754 , fUseBGR(useBGR)
1755 , fGamma(gamma) {
1756 this->initClassID<BitmapTextBatch>();
1757 fBatch.fNumGlyphs = glyphCount;
1758 fInstanceCount = 1;
1759 fAllocatedCount = kMinAllocated;
1760 SkASSERT(fMaskFormat == kA8_GrMaskFormat);
1761 }
1762
joshualittad802c62015-04-15 05:31:57 -07001763 ~BitmapTextBatch() {
1764 for (int i = 0; i < fInstanceCount; i++) {
1765 fGeoData[i].fBlob->unref();
1766 }
joshualitt1d89e8d2015-04-01 12:40:54 -07001767 }
1768
1769 void regenerateTextureCoords(GrGlyph* glyph, intptr_t vertex, size_t vertexStride) {
1770 int width = glyph->fBounds.width();
1771 int height = glyph->fBounds.height();
joshualitt1d89e8d2015-04-01 12:40:54 -07001772
joshualitt9bd2daf2015-04-17 09:30:06 -07001773 int u0, v0, u1, v1;
1774 if (fUseDistanceFields) {
1775 u0 = glyph->fAtlasLocation.fX + SK_DistanceFieldInset;
1776 v0 = glyph->fAtlasLocation.fY + SK_DistanceFieldInset;
1777 u1 = u0 + width - 2 * SK_DistanceFieldInset;
1778 v1 = v0 + height - 2 * SK_DistanceFieldInset;
1779 } else {
1780 u0 = glyph->fAtlasLocation.fX;
1781 v0 = glyph->fAtlasLocation.fY;
1782 u1 = u0 + width;
1783 v1 = v0 + height;
1784 }
1785
joshualitt1d89e8d2015-04-01 12:40:54 -07001786 SkIPoint16* textureCoords;
1787 // V0
1788 textureCoords = reinterpret_cast<SkIPoint16*>(vertex);
1789 textureCoords->set(u0, v0);
1790 vertex += vertexStride;
1791
1792 // V1
1793 textureCoords = reinterpret_cast<SkIPoint16*>(vertex);
1794 textureCoords->set(u0, v1);
1795 vertex += vertexStride;
1796
1797 // V2
1798 textureCoords = reinterpret_cast<SkIPoint16*>(vertex);
1799 textureCoords->set(u1, v1);
1800 vertex += vertexStride;
1801
1802 // V3
1803 textureCoords = reinterpret_cast<SkIPoint16*>(vertex);
1804 textureCoords->set(u1, v0);
1805 }
1806
1807 void regenerateColors(intptr_t vertex, size_t vertexStride, GrColor color) {
1808 for (int i = 0; i < kVerticesPerGlyph; i++) {
1809 SkColor* vcolor = reinterpret_cast<SkColor*>(vertex);
1810 *vcolor = color;
1811 vertex += vertexStride;
1812 }
1813 }
1814
joshualitt2a0e9f32015-04-13 06:12:21 -07001815 void regeneratePositions(intptr_t vertex, size_t vertexStride, SkScalar transX,
1816 SkScalar transY) {
1817 for (int i = 0; i < kVerticesPerGlyph; i++) {
1818 SkPoint* point = reinterpret_cast<SkPoint*>(vertex);
1819 point->fX += transX;
1820 point->fY += transY;
1821 vertex += vertexStride;
1822 }
1823 }
1824
joshualitt1d89e8d2015-04-01 12:40:54 -07001825 void initDraw(GrBatchTarget* batchTarget,
1826 const GrGeometryProcessor* gp,
1827 const GrPipeline* pipeline) {
1828 batchTarget->initDraw(gp, pipeline);
1829
1830 // TODO remove this when batch is everywhere
1831 GrPipelineInfo init;
1832 init.fColorIgnored = fBatch.fColorIgnored;
1833 init.fOverrideColor = GrColor_ILLEGAL;
1834 init.fCoverageIgnored = fBatch.fCoverageIgnored;
1835 init.fUsesLocalCoords = this->usesLocalCoords();
1836 gp->initBatchTracker(batchTarget->currentBatchTracker(), init);
1837 }
1838
bsalomonb5238a72015-05-05 07:49:49 -07001839 void flush(GrBatchTarget* batchTarget, FlushInfo* flushInfo) {
bsalomoncb8979d2015-05-05 09:51:38 -07001840 GrVertices vertices;
bsalomonb5238a72015-05-05 07:49:49 -07001841 int glyphsToFlush = flushInfo->fGlyphsToFlush;
1842 int maxGlyphsPerDraw = flushInfo->fIndexBuffer->maxQuads();
bsalomoncb8979d2015-05-05 09:51:38 -07001843 vertices.initInstanced(kTriangles_GrPrimitiveType, flushInfo->fVertexBuffer,
bsalomonb5238a72015-05-05 07:49:49 -07001844 flushInfo->fIndexBuffer, flushInfo->fVertexOffset,
1845 kVerticesPerGlyph, kIndicesPerGlyph, &glyphsToFlush,
1846 maxGlyphsPerDraw);
1847 do {
bsalomoncb8979d2015-05-05 09:51:38 -07001848 batchTarget->draw(vertices);
1849 } while (vertices.nextInstances(&glyphsToFlush, maxGlyphsPerDraw));
bsalomonb5238a72015-05-05 07:49:49 -07001850 flushInfo->fVertexOffset += kVerticesPerGlyph * flushInfo->fGlyphsToFlush;
1851 flushInfo->fGlyphsToFlush = 0;
joshualitt1d89e8d2015-04-01 12:40:54 -07001852 }
1853
1854 GrColor color() const { return fBatch.fColor; }
1855 const SkMatrix& viewMatrix() const { return fBatch.fViewMatrix; }
1856 bool usesLocalCoords() const { return fBatch.fUsesLocalCoords; }
1857 int numGlyphs() const { return fBatch.fNumGlyphs; }
1858
1859 bool onCombineIfPossible(GrBatch* t) override {
1860 BitmapTextBatch* that = t->cast<BitmapTextBatch>();
1861
joshualitt9bd2daf2015-04-17 09:30:06 -07001862 if (fUseDistanceFields != that->fUseDistanceFields) {
joshualitt1d89e8d2015-04-01 12:40:54 -07001863 return false;
1864 }
1865
joshualitt9bd2daf2015-04-17 09:30:06 -07001866 if (!fUseDistanceFields) {
1867 // Bitmap Text
1868 if (fMaskFormat != that->fMaskFormat) {
1869 return false;
1870 }
joshualitt1d89e8d2015-04-01 12:40:54 -07001871
joshualitt9bd2daf2015-04-17 09:30:06 -07001872 // TODO we can often batch across LCD text if we have dual source blending and don't
1873 // have to use the blend constant
1874 if (fMaskFormat != kA8_GrMaskFormat && this->color() != that->color()) {
1875 return false;
1876 }
1877
1878 if (this->usesLocalCoords() && !this->viewMatrix().cheapEqualTo(that->viewMatrix())) {
1879 return false;
1880 }
1881 } else {
1882 // Distance Fields
1883 SkASSERT(this->fMaskFormat == that->fMaskFormat &&
1884 this->fMaskFormat == kA8_GrMaskFormat);
1885
1886 if (!this->viewMatrix().cheapEqualTo(that->viewMatrix())) {
1887 return false;
1888 }
1889
1890 if (fFilteredColor != that->fFilteredColor) {
1891 return false;
1892 }
1893
1894 if (fUseLCDText != that->fUseLCDText) {
1895 return false;
1896 }
1897
1898 if (fUseBGR != that->fUseBGR) {
1899 return false;
1900 }
1901
1902 if (fGamma != that->fGamma) {
1903 return false;
1904 }
1905
1906 // TODO see note above
1907 if (fUseLCDText && this->color() != that->color()) {
1908 return false;
1909 }
joshualitt1d89e8d2015-04-01 12:40:54 -07001910 }
1911
1912 fBatch.fNumGlyphs += that->numGlyphs();
joshualittad802c62015-04-15 05:31:57 -07001913
1914 // copy that->geoData(). We do this manually for performance reasons
1915 SkAutoSTMalloc<kMinAllocated, Geometry>* otherGeoData = that->geoData();
1916 int otherInstanceCount = that->instanceCount();
1917 int allocSize = otherInstanceCount + fInstanceCount;
1918 if (allocSize > fAllocatedCount) {
1919 while (allocSize > fAllocatedCount) {
1920 fAllocatedCount = fAllocatedCount << 1;
1921 }
1922 fGeoData.realloc(fAllocatedCount);
1923 }
1924
1925 memcpy(&fGeoData[fInstanceCount], otherGeoData->get(),
1926 otherInstanceCount * sizeof(Geometry));
1927 int total = fInstanceCount + otherInstanceCount;
1928 for (int i = fInstanceCount; i < total; i++) {
1929 fGeoData[i].fBlob->ref();
1930 }
1931 fInstanceCount = total;
joshualitt99c7c072015-05-01 13:43:30 -07001932
1933 this->joinBounds(that->bounds());
joshualitt1d89e8d2015-04-01 12:40:54 -07001934 return true;
1935 }
1936
joshualitt9bd2daf2015-04-17 09:30:06 -07001937 // TODO just use class params
1938 // TODO trying to figure out why lcd is so whack
1939 GrGeometryProcessor* setupDfProcessor(const SkMatrix& viewMatrix, SkColor filteredColor,
1940 GrColor color, GrTexture* texture) {
1941 GrTextureParams params(SkShader::kClamp_TileMode, GrTextureParams::kBilerp_FilterMode);
1942
1943 // set up any flags
1944 uint32_t flags = 0;
1945 flags |= viewMatrix.isSimilarity() ? kSimilarity_DistanceFieldEffectFlag : 0;
1946 flags |= fUseLCDText ? kUseLCD_DistanceFieldEffectFlag : 0;
1947 flags |= fUseLCDText && viewMatrix.rectStaysRect() ?
1948 kRectToRect_DistanceFieldEffectFlag : 0;
1949 flags |= fUseLCDText && fUseBGR ? kBGR_DistanceFieldEffectFlag : 0;
1950
1951 // see if we need to create a new effect
1952 if (fUseLCDText) {
1953 GrColor colorNoPreMul = skcolor_to_grcolor_nopremultiply(filteredColor);
1954
1955 float redCorrection =
1956 (*fDistanceAdjustTable)[GrColorUnpackR(colorNoPreMul) >> kDistanceAdjustLumShift];
1957 float greenCorrection =
1958 (*fDistanceAdjustTable)[GrColorUnpackG(colorNoPreMul) >> kDistanceAdjustLumShift];
1959 float blueCorrection =
1960 (*fDistanceAdjustTable)[GrColorUnpackB(colorNoPreMul) >> kDistanceAdjustLumShift];
1961 GrDistanceFieldLCDTextGeoProc::DistanceAdjust widthAdjust =
1962 GrDistanceFieldLCDTextGeoProc::DistanceAdjust::Make(redCorrection,
1963 greenCorrection,
1964 blueCorrection);
1965
1966 return GrDistanceFieldLCDTextGeoProc::Create(color,
1967 viewMatrix,
1968 texture,
1969 params,
1970 widthAdjust,
1971 flags);
1972 } else {
1973 flags |= kColorAttr_DistanceFieldEffectFlag;
joshualitt50cb76b2015-04-28 09:17:05 -07001974 bool opaque = GrColorIsOpaque(color);
joshualitt9bd2daf2015-04-17 09:30:06 -07001975#ifdef SK_GAMMA_APPLY_TO_A8
1976 U8CPU lum = SkColorSpaceLuminance::computeLuminance(fGamma, filteredColor);
1977 float correction = (*fDistanceAdjustTable)[lum >> kDistanceAdjustLumShift];
1978 return GrDistanceFieldA8TextGeoProc::Create(color,
1979 viewMatrix,
1980 texture,
1981 params,
1982 correction,
joshualitt50cb76b2015-04-28 09:17:05 -07001983 flags,
1984 opaque);
joshualitt9bd2daf2015-04-17 09:30:06 -07001985#else
1986 return GrDistanceFieldA8TextGeoProc::Create(color,
1987 viewMatrix,
1988 texture,
1989 params,
joshualitt50cb76b2015-04-28 09:17:05 -07001990 flags,
1991 opaque);
joshualitt9bd2daf2015-04-17 09:30:06 -07001992#endif
1993 }
1994
1995 }
1996
joshualitt1d89e8d2015-04-01 12:40:54 -07001997 struct BatchTracker {
1998 GrColor fColor;
1999 SkMatrix fViewMatrix;
2000 bool fUsesLocalCoords;
2001 bool fColorIgnored;
2002 bool fCoverageIgnored;
2003 int fNumGlyphs;
2004 };
2005
2006 BatchTracker fBatch;
joshualittad802c62015-04-15 05:31:57 -07002007 SkAutoSTMalloc<kMinAllocated, Geometry> fGeoData;
2008 int fInstanceCount;
2009 int fAllocatedCount;
joshualitt1d89e8d2015-04-01 12:40:54 -07002010 GrMaskFormat fMaskFormat;
2011 GrPixelConfig fPixelConfig;
2012 GrBatchFontCache* fFontCache;
joshualitt9bd2daf2015-04-17 09:30:06 -07002013
2014 // Distance field properties
2015 SkAutoTUnref<DistanceAdjustTable> fDistanceAdjustTable;
2016 SkColor fFilteredColor;
2017 bool fUseDistanceFields;
2018 bool fUseLCDText;
2019 bool fUseBGR;
2020 float fGamma;
joshualitt1d89e8d2015-04-01 12:40:54 -07002021};
2022
joshualitt9a27e632015-04-06 10:53:36 -07002023void GrAtlasTextContext::flushRunAsPaths(const SkTextBlob::RunIterator& it, const SkPaint& skPaint,
2024 SkDrawFilter* drawFilter, const SkMatrix& viewMatrix,
2025 const SkIRect& clipBounds, SkScalar x, SkScalar y) {
2026 SkPaint runPaint = skPaint;
joshualitt1d89e8d2015-04-01 12:40:54 -07002027
joshualitt9a27e632015-04-06 10:53:36 -07002028 size_t textLen = it.glyphCount() * sizeof(uint16_t);
2029 const SkPoint& offset = it.offset();
joshualitt1d89e8d2015-04-01 12:40:54 -07002030
joshualitt9a27e632015-04-06 10:53:36 -07002031 it.applyFontToPaint(&runPaint);
joshualitt1d89e8d2015-04-01 12:40:54 -07002032
joshualitt9a27e632015-04-06 10:53:36 -07002033 if (drawFilter && !drawFilter->filter(&runPaint, SkDrawFilter::kText_Type)) {
2034 return;
joshualitt1d89e8d2015-04-01 12:40:54 -07002035 }
2036
joshualitt9a27e632015-04-06 10:53:36 -07002037 runPaint.setFlags(fGpuDevice->filterTextFlags(runPaint));
2038
2039 switch (it.positioning()) {
2040 case SkTextBlob::kDefault_Positioning:
2041 this->drawTextAsPath(runPaint, viewMatrix, (const char *)it.glyphs(),
2042 textLen, x + offset.x(), y + offset.y(), clipBounds);
2043 break;
2044 case SkTextBlob::kHorizontal_Positioning:
2045 this->drawPosTextAsPath(runPaint, viewMatrix, (const char*)it.glyphs(),
2046 textLen, it.pos(), 1, SkPoint::Make(x, y + offset.y()),
2047 clipBounds);
2048 break;
2049 case SkTextBlob::kFull_Positioning:
2050 this->drawPosTextAsPath(runPaint, viewMatrix, (const char*)it.glyphs(),
2051 textLen, it.pos(), 2, SkPoint::Make(x, y), clipBounds);
2052 break;
2053 }
2054}
2055
2056inline void GrAtlasTextContext::flushRun(GrDrawTarget* target, GrPipelineBuilder* pipelineBuilder,
2057 BitmapTextBlob* cacheBlob, int run, GrColor color,
joshualitt9bd2daf2015-04-17 09:30:06 -07002058 SkScalar transX, SkScalar transY, const SkPaint& skPaint) {
joshualitt9a27e632015-04-06 10:53:36 -07002059 for (int subRun = 0; subRun < cacheBlob->fRuns[run].fSubRunInfo.count(); subRun++) {
2060 const PerSubRunInfo& info = cacheBlob->fRuns[run].fSubRunInfo[subRun];
2061 int glyphCount = info.fGlyphEndIndex - info.fGlyphStartIndex;
2062 if (0 == glyphCount) {
2063 continue;
2064 }
2065
2066 GrMaskFormat format = info.fMaskFormat;
joshualitt9bd2daf2015-04-17 09:30:06 -07002067 GrColor subRunColor;
2068 if (kARGB_GrMaskFormat == format) {
2069 uint8_t paintAlpha = skPaint.getAlpha();
2070 subRunColor = SkColorSetARGB(paintAlpha, paintAlpha, paintAlpha, paintAlpha);
2071 } else {
2072 subRunColor = color;
2073 }
joshualitt9a27e632015-04-06 10:53:36 -07002074
joshualitt9bd2daf2015-04-17 09:30:06 -07002075 SkAutoTUnref<BitmapTextBatch> batch;
2076 if (info.fDrawAsDistanceFields) {
2077 SkColor filteredColor;
2078 SkColorFilter* colorFilter = skPaint.getColorFilter();
2079 if (colorFilter) {
2080 filteredColor = colorFilter->filterColor(skPaint.getColor());
2081 } else {
2082 filteredColor = skPaint.getColor();
2083 }
2084 bool useBGR = SkPixelGeometryIsBGR(fDeviceProperties.pixelGeometry());
2085 float gamma = fDeviceProperties.gamma();
2086 batch.reset(BitmapTextBatch::Create(format, glyphCount, fContext->getBatchFontCache(),
2087 fDistanceAdjustTable, filteredColor,
2088 info.fUseLCDText, useBGR,
2089 gamma));
2090 } else {
2091 batch.reset(BitmapTextBatch::Create(format, glyphCount, fContext->getBatchFontCache()));
2092 }
joshualittad802c62015-04-15 05:31:57 -07002093 BitmapTextBatch::Geometry& geometry = batch->geometry();
2094 geometry.fBlob = SkRef(cacheBlob);
joshualitt9a27e632015-04-06 10:53:36 -07002095 geometry.fRun = run;
2096 geometry.fSubRun = subRun;
2097 geometry.fColor = subRunColor;
joshualitt2a0e9f32015-04-13 06:12:21 -07002098 geometry.fTransX = transX;
2099 geometry.fTransY = transY;
joshualittad802c62015-04-15 05:31:57 -07002100 batch->init();
joshualitt9a27e632015-04-06 10:53:36 -07002101
joshualitt99c7c072015-05-01 13:43:30 -07002102 target->drawBatch(pipelineBuilder, batch);
joshualitt9a27e632015-04-06 10:53:36 -07002103 }
2104}
2105
2106inline void GrAtlasTextContext::flushBigGlyphs(BitmapTextBlob* cacheBlob, GrRenderTarget* rt,
joshualitt2a0e9f32015-04-13 06:12:21 -07002107 const GrPaint& grPaint, const GrClip& clip,
2108 SkScalar transX, SkScalar transY) {
joshualitt9a27e632015-04-06 10:53:36 -07002109 for (int i = 0; i < cacheBlob->fBigGlyphs.count(); i++) {
joshualitt2a0e9f32015-04-13 06:12:21 -07002110 BitmapTextBlob::BigGlyph& bigGlyph = cacheBlob->fBigGlyphs[i];
2111 bigGlyph.fVx += SkScalarTruncToInt(transX);
2112 bigGlyph.fVy += SkScalarTruncToInt(transY);
joshualitt1d89e8d2015-04-01 12:40:54 -07002113 SkMatrix translate;
joshualitt2a0e9f32015-04-13 06:12:21 -07002114 translate.setTranslate(SkIntToScalar(bigGlyph.fVx),
2115 SkIntToScalar(bigGlyph.fVy));
joshualitt1d89e8d2015-04-01 12:40:54 -07002116 SkPath tmpPath(bigGlyph.fPath);
2117 tmpPath.transform(translate);
2118 GrStrokeInfo strokeInfo(SkStrokeRec::kFill_InitStyle);
joshualitt9a27e632015-04-06 10:53:36 -07002119 fContext->drawPath(rt, clip, grPaint, SkMatrix::I(), tmpPath, strokeInfo);
joshualitt1d89e8d2015-04-01 12:40:54 -07002120 }
2121}
joshualitt9a27e632015-04-06 10:53:36 -07002122
2123void GrAtlasTextContext::flush(GrDrawTarget* target,
2124 const SkTextBlob* blob,
2125 BitmapTextBlob* cacheBlob,
2126 GrRenderTarget* rt,
2127 const SkPaint& skPaint,
2128 const GrPaint& grPaint,
2129 SkDrawFilter* drawFilter,
2130 const GrClip& clip,
2131 const SkMatrix& viewMatrix,
2132 const SkIRect& clipBounds,
joshualitt2a0e9f32015-04-13 06:12:21 -07002133 SkScalar x, SkScalar y,
2134 SkScalar transX, SkScalar transY) {
joshualitt9a27e632015-04-06 10:53:36 -07002135 // We loop through the runs of the blob, flushing each. If any run is too large, then we flush
2136 // it as paths
2137 GrPipelineBuilder pipelineBuilder;
2138 pipelineBuilder.setFromPaint(grPaint, rt, clip);
2139
2140 GrColor color = grPaint.getColor();
joshualitt9a27e632015-04-06 10:53:36 -07002141
2142 SkTextBlob::RunIterator it(blob);
2143 for (int run = 0; !it.done(); it.next(), run++) {
2144 if (cacheBlob->fRuns[run].fDrawAsPaths) {
2145 this->flushRunAsPaths(it, skPaint, drawFilter, viewMatrix, clipBounds, x, y);
2146 continue;
2147 }
joshualitt2a0e9f32015-04-13 06:12:21 -07002148 cacheBlob->fRuns[run].fVertexBounds.offset(transX, transY);
joshualitt9bd2daf2015-04-17 09:30:06 -07002149 this->flushRun(target, &pipelineBuilder, cacheBlob, run, color, transX, transY, skPaint);
joshualitt9a27e632015-04-06 10:53:36 -07002150 }
2151
2152 // Now flush big glyphs
joshualitt2a0e9f32015-04-13 06:12:21 -07002153 this->flushBigGlyphs(cacheBlob, rt, grPaint, clip, transX, transY);
joshualitt9a27e632015-04-06 10:53:36 -07002154}
2155
2156void GrAtlasTextContext::flush(GrDrawTarget* target,
2157 BitmapTextBlob* cacheBlob,
2158 GrRenderTarget* rt,
2159 const SkPaint& skPaint,
2160 const GrPaint& grPaint,
joshualitt9bd2daf2015-04-17 09:30:06 -07002161 const GrClip& clip) {
joshualitt9a27e632015-04-06 10:53:36 -07002162 GrPipelineBuilder pipelineBuilder;
2163 pipelineBuilder.setFromPaint(grPaint, rt, clip);
2164
2165 GrColor color = grPaint.getColor();
joshualitt9a27e632015-04-06 10:53:36 -07002166 for (int run = 0; run < cacheBlob->fRunCount; run++) {
joshualitt9bd2daf2015-04-17 09:30:06 -07002167 this->flushRun(target, &pipelineBuilder, cacheBlob, run, color, 0, 0, skPaint);
joshualitt9a27e632015-04-06 10:53:36 -07002168 }
2169
2170 // Now flush big glyphs
joshualitt2a0e9f32015-04-13 06:12:21 -07002171 this->flushBigGlyphs(cacheBlob, rt, grPaint, clip, 0, 0);
joshualitt9a27e632015-04-06 10:53:36 -07002172}