Font.cpp revision 624234f69b2a4781d24f3e4c6ae6450729e38397
1/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "OpenGLRenderer"
18
19#include <cutils/compiler.h>
20
21#include <utils/JenkinsHash.h>
22
23#include <SkGlyph.h>
24#include <SkUtils.h>
25
26#include "Debug.h"
27#include "FontUtil.h"
28#include "Font.h"
29#include "FontRenderer.h"
30#include "Properties.h"
31
32namespace android {
33namespace uirenderer {
34
35///////////////////////////////////////////////////////////////////////////////
36// Font
37///////////////////////////////////////////////////////////////////////////////
38
39Font::Font(FontRenderer* state, const Font::FontDescription& desc) :
40        mState(state), mDescription(desc) {
41}
42
43Font::FontDescription::FontDescription(const SkPaint* paint, const mat4& matrix) {
44    mFontId = SkTypeface::UniqueID(paint->getTypeface());
45    mFontSize = paint->getTextSize();
46    mFlags = 0;
47    if (paint->isFakeBoldText()) {
48        mFlags |= Font::kFakeBold;
49    }
50    mItalicStyle = paint->getTextSkewX();
51    mScaleX = paint->getTextScaleX();
52    mStyle = paint->getStyle();
53    mStrokeWidth = paint->getStrokeWidth();
54    mAntiAliasing = paint->isAntiAlias();
55    mLookupTransform.reset();
56    mLookupTransform[SkMatrix::kMScaleX] = matrix[mat4::kScaleX];
57    mLookupTransform[SkMatrix::kMScaleY] = matrix[mat4::kScaleY];
58    if (!mLookupTransform.invert(&mInverseLookupTransform)) {
59        ALOGW("Could not query the inverse lookup transform for this font");
60    }
61}
62
63Font::~Font() {
64    mState->removeFont(this);
65
66    for (uint32_t i = 0; i < mCachedGlyphs.size(); i++) {
67        delete mCachedGlyphs.valueAt(i);
68    }
69}
70
71hash_t Font::FontDescription::hash() const {
72    uint32_t hash = JenkinsHashMix(0, mFontId);
73    hash = JenkinsHashMix(hash, android::hash_type(mFontSize));
74    hash = JenkinsHashMix(hash, android::hash_type(mFlags));
75    hash = JenkinsHashMix(hash, android::hash_type(mItalicStyle));
76    hash = JenkinsHashMix(hash, android::hash_type(mScaleX));
77    hash = JenkinsHashMix(hash, android::hash_type(mStyle));
78    hash = JenkinsHashMix(hash, android::hash_type(mStrokeWidth));
79    hash = JenkinsHashMix(hash, int(mAntiAliasing));
80    hash = JenkinsHashMix(hash, android::hash_type(mLookupTransform[SkMatrix::kMScaleX]));
81    hash = JenkinsHashMix(hash, android::hash_type(mLookupTransform[SkMatrix::kMScaleY]));
82    return JenkinsHashWhiten(hash);
83}
84
85int Font::FontDescription::compare(const Font::FontDescription& lhs,
86        const Font::FontDescription& rhs) {
87    int deltaInt = int(lhs.mFontId) - int(rhs.mFontId);
88    if (deltaInt != 0) return deltaInt;
89
90    if (lhs.mFontSize < rhs.mFontSize) return -1;
91    if (lhs.mFontSize > rhs.mFontSize) return +1;
92
93    if (lhs.mItalicStyle < rhs.mItalicStyle) return -1;
94    if (lhs.mItalicStyle > rhs.mItalicStyle) return +1;
95
96    deltaInt = int(lhs.mFlags) - int(rhs.mFlags);
97    if (deltaInt != 0) return deltaInt;
98
99    if (lhs.mScaleX < rhs.mScaleX) return -1;
100    if (lhs.mScaleX > rhs.mScaleX) return +1;
101
102    deltaInt = int(lhs.mStyle) - int(rhs.mStyle);
103    if (deltaInt != 0) return deltaInt;
104
105    if (lhs.mStrokeWidth < rhs.mStrokeWidth) return -1;
106    if (lhs.mStrokeWidth > rhs.mStrokeWidth) return +1;
107
108    deltaInt = int(lhs.mAntiAliasing) - int(rhs.mAntiAliasing);
109    if (deltaInt != 0) return deltaInt;
110
111    if (lhs.mLookupTransform[SkMatrix::kMScaleX] <
112            rhs.mLookupTransform[SkMatrix::kMScaleX]) return -1;
113    if (lhs.mLookupTransform[SkMatrix::kMScaleX] >
114            rhs.mLookupTransform[SkMatrix::kMScaleX]) return +1;
115
116    if (lhs.mLookupTransform[SkMatrix::kMScaleY] <
117            rhs.mLookupTransform[SkMatrix::kMScaleY]) return -1;
118    if (lhs.mLookupTransform[SkMatrix::kMScaleY] >
119            rhs.mLookupTransform[SkMatrix::kMScaleY]) return +1;
120
121    return 0;
122}
123
124void Font::invalidateTextureCache(CacheTexture* cacheTexture) {
125    for (uint32_t i = 0; i < mCachedGlyphs.size(); i++) {
126        CachedGlyphInfo* cachedGlyph = mCachedGlyphs.valueAt(i);
127        if (!cacheTexture || cachedGlyph->mCacheTexture == cacheTexture) {
128            cachedGlyph->mIsValid = false;
129        }
130    }
131}
132
133void Font::measureCachedGlyph(CachedGlyphInfo *glyph, int x, int y,
134        uint8_t* bitmap, uint32_t bitmapW, uint32_t bitmapH, Rect* bounds, const float* pos) {
135    int nPenX = x + glyph->mBitmapLeft;
136    int nPenY = y + glyph->mBitmapTop;
137
138    int width = (int) glyph->mBitmapWidth;
139    int height = (int) glyph->mBitmapHeight;
140
141    if (bounds->bottom > nPenY) {
142        bounds->bottom = nPenY;
143    }
144    if (bounds->left > nPenX) {
145        bounds->left = nPenX;
146    }
147    if (bounds->right < nPenX + width) {
148        bounds->right = nPenX + width;
149    }
150    if (bounds->top < nPenY + height) {
151        bounds->top = nPenY + height;
152    }
153}
154
155void Font::drawCachedGlyph(CachedGlyphInfo* glyph, int x, int y,
156        uint8_t* bitmap, uint32_t bitmapW, uint32_t bitmapH, Rect* bounds, const float* pos) {
157    float nPenX = x + glyph->mBitmapLeft;
158    float nPenY = y + glyph->mBitmapTop + glyph->mBitmapHeight;
159
160    float width = (float) glyph->mBitmapWidth;
161    float height = (float) glyph->mBitmapHeight;
162
163    float u1 = glyph->mBitmapMinU;
164    float u2 = glyph->mBitmapMaxU;
165    float v1 = glyph->mBitmapMinV;
166    float v2 = glyph->mBitmapMaxV;
167
168    mState->appendMeshQuad(nPenX, nPenY, u1, v2,
169            nPenX + width, nPenY, u2, v2,
170            nPenX + width, nPenY - height, u2, v1,
171            nPenX, nPenY - height, u1, v1, glyph->mCacheTexture);
172}
173
174void Font::drawCachedGlyphTransformed(CachedGlyphInfo* glyph, int x, int y,
175        uint8_t* bitmap, uint32_t bitmapW, uint32_t bitmapH, Rect* bounds, const float* pos) {
176    SkPoint p[4];
177    p[0].iset(glyph->mBitmapLeft, glyph->mBitmapTop + glyph->mBitmapHeight);
178    p[1].iset(glyph->mBitmapLeft + glyph->mBitmapWidth, glyph->mBitmapTop + glyph->mBitmapHeight);
179    p[2].iset(glyph->mBitmapLeft + glyph->mBitmapWidth, glyph->mBitmapTop);
180    p[3].iset(glyph->mBitmapLeft, glyph->mBitmapTop);
181
182    mDescription.mInverseLookupTransform.mapPoints(p, 4);
183
184    p[0].offset(x, y);
185    p[1].offset(x, y);
186    p[2].offset(x, y);
187    p[3].offset(x, y);
188
189    float u1 = glyph->mBitmapMinU;
190    float u2 = glyph->mBitmapMaxU;
191    float v1 = glyph->mBitmapMinV;
192    float v2 = glyph->mBitmapMaxV;
193
194    mState->appendRotatedMeshQuad(
195            p[0].x(), p[0].y(), u1, v2,
196            p[1].x(), p[1].y(), u2, v2,
197            p[2].x(), p[2].y(), u2, v1,
198            p[3].x(), p[3].y(), u1, v1, glyph->mCacheTexture);
199}
200
201void Font::drawCachedGlyphBitmap(CachedGlyphInfo* glyph, int x, int y,
202        uint8_t* bitmap, uint32_t bitmapW, uint32_t bitmapH, Rect* bounds, const float* pos) {
203    int nPenX = x + glyph->mBitmapLeft;
204    int nPenY = y + glyph->mBitmapTop;
205
206    uint32_t endX = glyph->mStartX + glyph->mBitmapWidth;
207    uint32_t endY = glyph->mStartY + glyph->mBitmapHeight;
208
209    CacheTexture* cacheTexture = glyph->mCacheTexture;
210    uint32_t cacheWidth = cacheTexture->getWidth();
211    const uint8_t* cacheBuffer = cacheTexture->getTexture();
212
213    uint32_t cacheX = 0, cacheY = 0;
214    int32_t bX = 0, bY = 0;
215    for (cacheX = glyph->mStartX, bX = nPenX; cacheX < endX; cacheX++, bX++) {
216        for (cacheY = glyph->mStartY, bY = nPenY; cacheY < endY; cacheY++, bY++) {
217            uint8_t tempCol = cacheBuffer[cacheY * cacheWidth + cacheX];
218            bitmap[bY * bitmapW + bX] = tempCol;
219        }
220    }
221}
222
223void Font::drawCachedGlyph(CachedGlyphInfo* glyph, float x, float hOffset, float vOffset,
224        SkPathMeasure& measure, SkPoint* position, SkVector* tangent) {
225    const float halfWidth = glyph->mBitmapWidth * 0.5f;
226    const float height = glyph->mBitmapHeight;
227
228    vOffset += glyph->mBitmapTop + height;
229
230    SkPoint destination[4];
231    bool ok = measure.getPosTan(x + hOffset + glyph->mBitmapLeft + halfWidth, position, tangent);
232    if (!ok) {
233        ALOGW("The path for drawTextOnPath is empty or null");
234    }
235
236    // Move along the tangent and offset by the normal
237    destination[0].set(-tangent->fX * halfWidth - tangent->fY * vOffset,
238            -tangent->fY * halfWidth + tangent->fX * vOffset);
239    destination[1].set(tangent->fX * halfWidth - tangent->fY * vOffset,
240            tangent->fY * halfWidth + tangent->fX * vOffset);
241    destination[2].set(destination[1].fX + tangent->fY * height,
242            destination[1].fY - tangent->fX * height);
243    destination[3].set(destination[0].fX + tangent->fY * height,
244            destination[0].fY - tangent->fX * height);
245
246    const float u1 = glyph->mBitmapMinU;
247    const float u2 = glyph->mBitmapMaxU;
248    const float v1 = glyph->mBitmapMinV;
249    const float v2 = glyph->mBitmapMaxV;
250
251    mState->appendRotatedMeshQuad(
252            position->x() + destination[0].x(),
253            position->y() + destination[0].y(), u1, v2,
254            position->x() + destination[1].x(),
255            position->y() + destination[1].y(), u2, v2,
256            position->x() + destination[2].x(),
257            position->y() + destination[2].y(), u2, v1,
258            position->x() + destination[3].x(),
259            position->y() + destination[3].y(), u1, v1,
260            glyph->mCacheTexture);
261}
262
263CachedGlyphInfo* Font::getCachedGlyph(SkPaint* paint, glyph_t textUnit, bool precaching) {
264    CachedGlyphInfo* cachedGlyph = NULL;
265    ssize_t index = mCachedGlyphs.indexOfKey(textUnit);
266    if (index >= 0) {
267        cachedGlyph = mCachedGlyphs.valueAt(index);
268
269        // Is the glyph still in texture cache?
270        if (!cachedGlyph->mIsValid) {
271            const SkGlyph& skiaGlyph = GET_METRICS(paint, textUnit,
272                    &mDescription.mLookupTransform);
273            updateGlyphCache(paint, skiaGlyph, cachedGlyph, precaching);
274        }
275    } else {
276        cachedGlyph = cacheGlyph(paint, textUnit, precaching);
277    }
278
279    return cachedGlyph;
280}
281
282void Font::render(SkPaint* paint, const char *text, uint32_t start, uint32_t len,
283            int numGlyphs, int x, int y, const float* positions) {
284    render(paint, text, start, len, numGlyphs, x, y, FRAMEBUFFER, NULL,
285            0, 0, NULL, positions);
286}
287
288void Font::render(SkPaint* paint, const char *text, uint32_t start, uint32_t len,
289        int numGlyphs, SkPath* path, float hOffset, float vOffset) {
290    if (numGlyphs == 0 || text == NULL || len == 0) {
291        return;
292    }
293
294    text += start;
295
296    int glyphsCount = 0;
297    SkFixed prevRsbDelta = 0;
298
299    float penX = 0.0f;
300
301    SkPoint position;
302    SkVector tangent;
303
304    SkPathMeasure measure(*path, false);
305    float pathLength = SkScalarToFloat(measure.getLength());
306
307    if (paint->getTextAlign() != SkPaint::kLeft_Align) {
308        float textWidth = SkScalarToFloat(paint->measureText(text, len));
309        float pathOffset = pathLength;
310        if (paint->getTextAlign() == SkPaint::kCenter_Align) {
311            textWidth *= 0.5f;
312            pathOffset *= 0.5f;
313        }
314        penX += pathOffset - textWidth;
315    }
316
317    while (glyphsCount < numGlyphs && penX < pathLength) {
318        glyph_t glyph = GET_GLYPH(text);
319
320        if (IS_END_OF_STRING(glyph)) {
321            break;
322        }
323
324        CachedGlyphInfo* cachedGlyph = getCachedGlyph(paint, glyph);
325        penX += SkFixedToFloat(AUTO_KERN(prevRsbDelta, cachedGlyph->mLsbDelta));
326        prevRsbDelta = cachedGlyph->mRsbDelta;
327
328        if (cachedGlyph->mIsValid && cachedGlyph->mCacheTexture) {
329            drawCachedGlyph(cachedGlyph, penX, hOffset, vOffset, measure, &position, &tangent);
330        }
331
332        penX += SkFixedToFloat(cachedGlyph->mAdvanceX);
333
334        glyphsCount++;
335    }
336}
337
338void Font::measure(SkPaint* paint, const char* text, uint32_t start, uint32_t len,
339        int numGlyphs, Rect *bounds, const float* positions) {
340    if (bounds == NULL) {
341        ALOGE("No return rectangle provided to measure text");
342        return;
343    }
344    bounds->set(1e6, -1e6, -1e6, 1e6);
345    render(paint, text, start, len, numGlyphs, 0, 0, MEASURE, NULL, 0, 0, bounds, positions);
346}
347
348void Font::precache(SkPaint* paint, const char* text, int numGlyphs) {
349    if (numGlyphs == 0 || text == NULL) {
350        return;
351    }
352    int glyphsCount = 0;
353
354    while (glyphsCount < numGlyphs) {
355        glyph_t glyph = GET_GLYPH(text);
356
357        // Reached the end of the string
358        if (IS_END_OF_STRING(glyph)) {
359            break;
360        }
361
362        CachedGlyphInfo* cachedGlyph = getCachedGlyph(paint, glyph, true);
363
364        glyphsCount++;
365    }
366}
367
368void Font::render(SkPaint* paint, const char* text, uint32_t start, uint32_t len,
369        int numGlyphs, int x, int y, RenderMode mode, uint8_t *bitmap,
370        uint32_t bitmapW, uint32_t bitmapH, Rect* bounds, const float* positions) {
371    if (numGlyphs == 0 || text == NULL || len == 0) {
372        return;
373    }
374
375    static RenderGlyph gRenderGlyph[] = {
376            &android::uirenderer::Font::drawCachedGlyph,
377            &android::uirenderer::Font::drawCachedGlyphTransformed,
378            &android::uirenderer::Font::drawCachedGlyphBitmap,
379            &android::uirenderer::Font::drawCachedGlyphBitmap,
380            &android::uirenderer::Font::measureCachedGlyph,
381            &android::uirenderer::Font::measureCachedGlyph
382    };
383    RenderGlyph render = gRenderGlyph[(mode << 1) + !mIdentityTransform];
384
385    text += start;
386    int glyphsCount = 0;
387
388    const SkPaint::Align align = paint->getTextAlign();
389
390    while (glyphsCount < numGlyphs) {
391        glyph_t glyph = GET_GLYPH(text);
392
393        // Reached the end of the string
394        if (IS_END_OF_STRING(glyph)) {
395            break;
396        }
397
398        CachedGlyphInfo* cachedGlyph = getCachedGlyph(paint, glyph);
399
400        // If it's still not valid, we couldn't cache it, so we shouldn't
401        // draw garbage; also skip empty glyphs (spaces)
402        if (cachedGlyph->mIsValid && cachedGlyph->mCacheTexture) {
403            float penX = x + positions[(glyphsCount << 1)];
404            float penY = y + positions[(glyphsCount << 1) + 1];
405
406            (*this.*render)(cachedGlyph, roundf(penX), roundf(penY),
407                    bitmap, bitmapW, bitmapH, bounds, positions);
408        }
409
410        glyphsCount++;
411    }
412}
413
414void Font::updateGlyphCache(SkPaint* paint, const SkGlyph& skiaGlyph, CachedGlyphInfo* glyph,
415        bool precaching) {
416    glyph->mAdvanceX = skiaGlyph.fAdvanceX;
417    glyph->mAdvanceY = skiaGlyph.fAdvanceY;
418    glyph->mBitmapLeft = skiaGlyph.fLeft;
419    glyph->mBitmapTop = skiaGlyph.fTop;
420    glyph->mLsbDelta = skiaGlyph.fLsbDelta;
421    glyph->mRsbDelta = skiaGlyph.fRsbDelta;
422
423    uint32_t startX = 0;
424    uint32_t startY = 0;
425
426    // Get the bitmap for the glyph
427    if (!skiaGlyph.fImage) {
428        paint->findImage(skiaGlyph, &mDescription.mLookupTransform);
429    }
430    mState->cacheBitmap(skiaGlyph, glyph, &startX, &startY, precaching);
431
432    if (!glyph->mIsValid) {
433        return;
434    }
435
436    uint32_t endX = startX + skiaGlyph.fWidth;
437    uint32_t endY = startY + skiaGlyph.fHeight;
438
439    glyph->mStartX = startX;
440    glyph->mStartY = startY;
441    glyph->mBitmapWidth = skiaGlyph.fWidth;
442    glyph->mBitmapHeight = skiaGlyph.fHeight;
443
444    bool empty = skiaGlyph.fWidth == 0 || skiaGlyph.fHeight == 0;
445    if (!empty) {
446        uint32_t cacheWidth = glyph->mCacheTexture->getWidth();
447        uint32_t cacheHeight = glyph->mCacheTexture->getHeight();
448
449        glyph->mBitmapMinU = startX / (float) cacheWidth;
450        glyph->mBitmapMinV = startY / (float) cacheHeight;
451        glyph->mBitmapMaxU = endX / (float) cacheWidth;
452        glyph->mBitmapMaxV = endY / (float) cacheHeight;
453
454        mState->setTextureDirty();
455    }
456}
457
458CachedGlyphInfo* Font::cacheGlyph(SkPaint* paint, glyph_t glyph, bool precaching) {
459    CachedGlyphInfo* newGlyph = new CachedGlyphInfo();
460    mCachedGlyphs.add(glyph, newGlyph);
461
462    const SkGlyph& skiaGlyph = GET_METRICS(paint, glyph, &mDescription.mLookupTransform);
463    newGlyph->mIsValid = false;
464    newGlyph->mGlyphIndex = skiaGlyph.fID;
465
466    updateGlyphCache(paint, skiaGlyph, newGlyph, precaching);
467
468    return newGlyph;
469}
470
471Font* Font::create(FontRenderer* state, const SkPaint* paint, const mat4& matrix) {
472    FontDescription description(paint, matrix);
473    Font* font = state->mActiveFonts.get(description);
474
475    if (!font) {
476        font = new Font(state, description);
477        state->mActiveFonts.put(description, font);
478    }
479    font->mIdentityTransform = matrix.isIdentity();
480
481    return font;
482}
483
484}; // namespace uirenderer
485}; // namespace android
486