SkiaShader.cpp revision 68a9dd8c88869fa47aa7d3c2e9ecce5077452f57
1/*
2 * Copyright (C) 2010 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#include "SkiaShader.h"
18
19#include "Caches.h"
20#include "Extensions.h"
21#include "Layer.h"
22#include "Matrix.h"
23#include "Texture.h"
24#include "hwui/Bitmap.h"
25
26#include <SkMatrix.h>
27#include <utils/Log.h>
28
29namespace android {
30namespace uirenderer {
31
32///////////////////////////////////////////////////////////////////////////////
33// Support
34///////////////////////////////////////////////////////////////////////////////
35
36static constexpr GLenum gTileModes[] = {
37        GL_CLAMP_TO_EDGE,   // == SkShader::kClamp_TileMode
38        GL_REPEAT,          // == SkShader::kRepeat_Mode
39        GL_MIRRORED_REPEAT  // == SkShader::kMirror_TileMode
40};
41
42static_assert(gTileModes[SkShader::kClamp_TileMode] == GL_CLAMP_TO_EDGE,
43        "SkShader TileModes have changed");
44static_assert(gTileModes[SkShader::kRepeat_TileMode] == GL_REPEAT,
45        "SkShader TileModes have changed");
46static_assert(gTileModes[SkShader::kMirror_TileMode] == GL_MIRRORED_REPEAT,
47        "SkShader TileModes have changed");
48
49/**
50 * This function does not work for n == 0.
51 */
52static inline bool isPowerOfTwo(unsigned int n) {
53    return !(n & (n - 1));
54}
55
56static inline void bindUniformColor(int slot, FloatColor color) {
57    glUniform4fv(slot, 1, reinterpret_cast<const float*>(&color));
58}
59
60static inline void bindTexture(Caches* caches, Texture* texture, GLenum wrapS, GLenum wrapT) {
61    caches->textureState().bindTexture(texture->target(), texture->id());
62    texture->setWrapST(wrapS, wrapT);
63}
64
65/**
66 * Compute the matrix to transform to screen space.
67 * @param screenSpace Output param for the computed matrix.
68 * @param unitMatrix The unit matrix for gradient shaders, as returned by SkShader::asAGradient,
69 *      or identity.
70 * @param localMatrix Local matrix, as returned by SkShader::getLocalMatrix().
71 * @param modelViewMatrix Model view matrix, as supplied by the OpenGLRenderer.
72 */
73static void computeScreenSpaceMatrix(mat4& screenSpace, const SkMatrix& unitMatrix,
74        const SkMatrix& localMatrix, const mat4& modelViewMatrix) {
75    mat4 shaderMatrix;
76    // uses implicit construction
77    shaderMatrix.loadInverse(localMatrix);
78    // again, uses implicit construction
79    screenSpace.loadMultiply(unitMatrix, shaderMatrix);
80    screenSpace.multiply(modelViewMatrix);
81}
82
83///////////////////////////////////////////////////////////////////////////////
84// Gradient shader matrix helpers
85///////////////////////////////////////////////////////////////////////////////
86
87static void toLinearUnitMatrix(const SkPoint pts[2], SkMatrix* matrix) {
88    SkVector vec = pts[1] - pts[0];
89    const float mag = vec.length();
90    const float inv = mag ? 1.0f / mag : 0;
91
92    vec.scale(inv);
93    matrix->setSinCos(-vec.fY, vec.fX, pts[0].fX, pts[0].fY);
94    matrix->postTranslate(-pts[0].fX, -pts[0].fY);
95    matrix->postScale(inv, inv);
96}
97
98static void toCircularUnitMatrix(const float x, const float y, const float radius,
99        SkMatrix* matrix) {
100    const float inv = 1.0f / radius;
101    matrix->setTranslate(-x, -y);
102    matrix->postScale(inv, inv);
103}
104
105static void toSweepUnitMatrix(const float x, const float y, SkMatrix* matrix) {
106    matrix->setTranslate(-x, -y);
107}
108
109///////////////////////////////////////////////////////////////////////////////
110// Common gradient code
111///////////////////////////////////////////////////////////////////////////////
112
113static bool isSimpleGradient(const SkShader::GradientInfo& gradInfo) {
114    return gradInfo.fColorCount == 2 && gradInfo.fTileMode == SkShader::kClamp_TileMode;
115}
116
117///////////////////////////////////////////////////////////////////////////////
118// Store / apply
119///////////////////////////////////////////////////////////////////////////////
120
121bool tryStoreGradient(Caches& caches, const SkShader& shader, const Matrix4 modelViewMatrix,
122        GLuint* textureUnit, ProgramDescription* description,
123        SkiaShaderData::GradientShaderData* outData) {
124    SkShader::GradientInfo gradInfo;
125    gradInfo.fColorCount = 0;
126    gradInfo.fColors = nullptr;
127    gradInfo.fColorOffsets = nullptr;
128
129    SkMatrix unitMatrix;
130    switch (shader.asAGradient(&gradInfo)) {
131        case SkShader::kLinear_GradientType:
132            description->gradientType = ProgramDescription::kGradientLinear;
133
134            toLinearUnitMatrix(gradInfo.fPoint, &unitMatrix);
135            break;
136        case SkShader::kRadial_GradientType:
137            description->gradientType = ProgramDescription::kGradientCircular;
138
139            toCircularUnitMatrix(gradInfo.fPoint[0].fX, gradInfo.fPoint[0].fY,
140                    gradInfo.fRadius[0], &unitMatrix);
141            break;
142        case SkShader::kSweep_GradientType:
143            description->gradientType = ProgramDescription::kGradientSweep;
144
145            toSweepUnitMatrix(gradInfo.fPoint[0].fX, gradInfo.fPoint[0].fY, &unitMatrix);
146            break;
147        default:
148            // Do nothing. This shader is unsupported.
149            return false;
150    }
151    description->hasGradient = true;
152    description->isSimpleGradient = isSimpleGradient(gradInfo);
153
154    computeScreenSpaceMatrix(outData->screenSpace, unitMatrix,
155            shader.getLocalMatrix(), modelViewMatrix);
156
157    // re-query shader to get full color / offset data
158    std::unique_ptr<SkColor[]> colorStorage(new SkColor[gradInfo.fColorCount]);
159    std::unique_ptr<SkScalar[]> colorOffsets(new SkScalar[gradInfo.fColorCount]);
160    gradInfo.fColors = &colorStorage[0];
161    gradInfo.fColorOffsets = &colorOffsets[0];
162    shader.asAGradient(&gradInfo);
163
164    if (CC_UNLIKELY(!description->isSimpleGradient)) {
165        outData->gradientSampler = (*textureUnit)++;
166
167#ifndef SK_SCALAR_IS_FLOAT
168    #error Need to convert gradInfo.fColorOffsets to float!
169#endif
170        outData->gradientTexture = caches.gradientCache.get(
171                gradInfo.fColors, gradInfo.fColorOffsets, gradInfo.fColorCount);
172        outData->wrapST = gTileModes[gradInfo.fTileMode];
173    } else {
174        outData->gradientSampler = 0;
175        outData->gradientTexture = nullptr;
176
177        outData->startColor.setUnPreMultipliedSRGB(gradInfo.fColors[0]);
178        outData->endColor.setUnPreMultipliedSRGB(gradInfo.fColors[1]);
179    }
180
181    return true;
182}
183
184void applyGradient(Caches& caches, const SkiaShaderData::GradientShaderData& data,
185        const GLsizei width, const GLsizei height) {
186
187    if (CC_UNLIKELY(data.gradientTexture)) {
188        caches.textureState().activateTexture(data.gradientSampler);
189        bindTexture(&caches, data.gradientTexture, data.wrapST, data.wrapST);
190        glUniform1i(caches.program().getUniform("gradientSampler"), data.gradientSampler);
191    } else {
192        bindUniformColor(caches.program().getUniform("startColor"), data.startColor);
193        bindUniformColor(caches.program().getUniform("endColor"), data.endColor);
194    }
195
196    glUniform2f(caches.program().getUniform("screenSize"), 1.0f / width, 1.0f / height);
197    glUniformMatrix4fv(caches.program().getUniform("screenSpace"), 1,
198            GL_FALSE, &data.screenSpace.data[0]);
199}
200
201bool tryStoreBitmap(Caches& caches, const SkShader& shader, const Matrix4& modelViewMatrix,
202        GLuint* textureUnit, ProgramDescription* description,
203        SkiaShaderData::BitmapShaderData* outData) {
204    SkBitmap bitmap;
205    SkShader::TileMode xy[2];
206    if (!shader.isABitmap(&bitmap, nullptr, xy)) {
207        return false;
208    }
209
210    // TODO: create  hwui-owned BitmapShader.
211    Bitmap* hwuiBitmap = static_cast<Bitmap*>(bitmap.pixelRef());
212    outData->bitmapTexture = caches.textureCache.get(hwuiBitmap);
213    if (!outData->bitmapTexture) return false;
214
215    outData->bitmapSampler = (*textureUnit)++;
216
217    const float width = outData->bitmapTexture->width();
218    const float height = outData->bitmapTexture->height();
219
220    description->hasBitmap = true;
221    description->isShaderBitmapExternal = hwuiBitmap->isHardware();
222    // gralloc doesn't support non-clamp modes
223    if (hwuiBitmap->isHardware() || (!caches.extensions().hasNPot()
224            && (!isPowerOfTwo(width) || !isPowerOfTwo(height))
225            && (xy[0] != SkShader::kClamp_TileMode || xy[1] != SkShader::kClamp_TileMode))) {
226        // need non-clamp mode, but it's not supported for this draw,
227        // so enable custom shader logic to mimic
228        description->useShaderBasedWrap = true;
229        description->bitmapWrapS = gTileModes[xy[0]];
230        description->bitmapWrapT = gTileModes[xy[1]];
231
232        outData->wrapS = GL_CLAMP_TO_EDGE;
233        outData->wrapT = GL_CLAMP_TO_EDGE;
234    } else {
235        outData->wrapS = gTileModes[xy[0]];
236        outData->wrapT = gTileModes[xy[1]];
237    }
238
239    computeScreenSpaceMatrix(outData->textureTransform, SkMatrix::I(), shader.getLocalMatrix(),
240            modelViewMatrix);
241    outData->textureDimension[0] = 1.0f / width;
242    outData->textureDimension[1] = 1.0f / height;
243
244    return true;
245}
246
247void applyBitmap(Caches& caches, const SkiaShaderData::BitmapShaderData& data) {
248    caches.textureState().activateTexture(data.bitmapSampler);
249    bindTexture(&caches, data.bitmapTexture, data.wrapS, data.wrapT);
250    data.bitmapTexture->setFilter(GL_LINEAR);
251
252    glUniform1i(caches.program().getUniform("bitmapSampler"), data.bitmapSampler);
253    glUniformMatrix4fv(caches.program().getUniform("textureTransform"), 1, GL_FALSE,
254            &data.textureTransform.data[0]);
255    glUniform2fv(caches.program().getUniform("textureDimension"), 1, &data.textureDimension[0]);
256}
257
258SkiaShaderType getComposeSubType(const SkShader& shader) {
259    // First check for a gradient shader.
260    switch (shader.asAGradient(nullptr)) {
261        case SkShader::kNone_GradientType:
262            // Not a gradient shader. Fall through to check for other types.
263            break;
264        case SkShader::kLinear_GradientType:
265        case SkShader::kRadial_GradientType:
266        case SkShader::kSweep_GradientType:
267            return kGradient_SkiaShaderType;
268        default:
269            // This is a Skia gradient that has no SkiaShader equivalent. Return None to skip.
270            return kNone_SkiaShaderType;
271    }
272
273    // The shader is not a gradient. Check for a bitmap shader.
274    if (shader.isABitmap()) {
275        return kBitmap_SkiaShaderType;
276    }
277    return kNone_SkiaShaderType;
278}
279
280void storeCompose(Caches& caches, const SkShader& bitmapShader, const SkShader& gradientShader,
281        const Matrix4& modelViewMatrix, GLuint* textureUnit,
282        ProgramDescription* description, SkiaShaderData* outData) {
283    LOG_ALWAYS_FATAL_IF(!tryStoreBitmap(caches, bitmapShader, modelViewMatrix,
284                textureUnit, description, &outData->bitmapData),
285            "failed storing bitmap shader data");
286    LOG_ALWAYS_FATAL_IF(!tryStoreGradient(caches, gradientShader, modelViewMatrix,
287                textureUnit, description, &outData->gradientData),
288            "failing storing gradient shader data");
289}
290
291bool tryStoreCompose(Caches& caches, const SkShader& shader, const Matrix4& modelViewMatrix,
292        GLuint* textureUnit, ProgramDescription* description,
293        SkiaShaderData* outData) {
294
295    SkShader::ComposeRec rec;
296    if (!shader.asACompose(&rec)) return false;
297
298    const SkiaShaderType shaderAType = getComposeSubType(*rec.fShaderA);
299    const SkiaShaderType shaderBType = getComposeSubType(*rec.fShaderB);
300
301    // check that type enum values are the 2 flags that compose the kCompose value
302    if ((shaderAType & shaderBType) != 0) return false;
303    if ((shaderAType | shaderBType) != kCompose_SkiaShaderType) return false;
304
305    mat4 transform;
306    computeScreenSpaceMatrix(transform, SkMatrix::I(), shader.getLocalMatrix(), modelViewMatrix);
307    if (shaderAType == kBitmap_SkiaShaderType) {
308        description->isBitmapFirst = true;
309        storeCompose(caches, *rec.fShaderA, *rec.fShaderB,
310                transform, textureUnit, description, outData);
311    } else {
312        description->isBitmapFirst = false;
313        storeCompose(caches, *rec.fShaderB, *rec.fShaderA,
314                transform, textureUnit, description, outData);
315    }
316    description->shadersMode = rec.fBlendMode;
317    return true;
318}
319
320bool tryStoreLayer(Caches& caches, const SkShader& shader, const Matrix4& modelViewMatrix,
321        GLuint* textureUnit, ProgramDescription* description,
322        SkiaShaderData::LayerShaderData* outData) {
323    Layer* layer;
324    if (!shader.asACustomShader(reinterpret_cast<void**>(&layer))) {
325        return false;
326    }
327
328    description->hasBitmap = true;
329    outData->layer = layer;
330    outData->bitmapSampler = (*textureUnit)++;
331
332    const float width = layer->getWidth();
333    const float height = layer->getHeight();
334
335    computeScreenSpaceMatrix(outData->textureTransform, SkMatrix::I(), shader.getLocalMatrix(),
336            modelViewMatrix);
337
338    outData->textureDimension[0] = 1.0f / width;
339    outData->textureDimension[1] = 1.0f / height;
340    return true;
341}
342
343void applyLayer(Caches& caches, const SkiaShaderData::LayerShaderData& data) {
344    caches.textureState().activateTexture(data.bitmapSampler);
345
346    data.layer->bindTexture();
347    data.layer->setWrap(GL_CLAMP_TO_EDGE);
348    data.layer->setFilter(GL_LINEAR);
349
350    glUniform1i(caches.program().getUniform("bitmapSampler"), data.bitmapSampler);
351    glUniformMatrix4fv(caches.program().getUniform("textureTransform"), 1,
352            GL_FALSE, &data.textureTransform.data[0]);
353    glUniform2fv(caches.program().getUniform("textureDimension"), 1, &data.textureDimension[0]);
354}
355
356void SkiaShader::store(Caches& caches, const SkShader& shader, const Matrix4& modelViewMatrix,
357        GLuint* textureUnit, ProgramDescription* description,
358        SkiaShaderData* outData) {
359    if (tryStoreGradient(caches, shader, modelViewMatrix,
360            textureUnit, description, &outData->gradientData)) {
361        outData->skiaShaderType = kGradient_SkiaShaderType;
362        return;
363    }
364
365    if (tryStoreBitmap(caches, shader, modelViewMatrix,
366            textureUnit, description, &outData->bitmapData)) {
367        outData->skiaShaderType = kBitmap_SkiaShaderType;
368        return;
369    }
370
371    if (tryStoreCompose(caches, shader, modelViewMatrix,
372            textureUnit, description, outData)) {
373        outData->skiaShaderType = kCompose_SkiaShaderType;
374        return;
375    }
376
377    if (tryStoreLayer(caches, shader, modelViewMatrix,
378            textureUnit, description, &outData->layerData)) {
379        outData->skiaShaderType = kLayer_SkiaShaderType;
380        return;
381    }
382
383    // Unknown/unsupported type, so explicitly ignore shader
384    outData->skiaShaderType = kNone_SkiaShaderType;
385}
386
387void SkiaShader::apply(Caches& caches, const SkiaShaderData& data,
388        const GLsizei width, const GLsizei height) {
389    if (!data.skiaShaderType) return;
390
391    if (data.skiaShaderType & kGradient_SkiaShaderType) {
392        applyGradient(caches, data.gradientData, width, height);
393    }
394    if (data.skiaShaderType & kBitmap_SkiaShaderType) {
395        applyBitmap(caches, data.bitmapData);
396    }
397
398    if (data.skiaShaderType == kLayer_SkiaShaderType) {
399        applyLayer(caches, data.layerData);
400    }
401}
402
403}; // namespace uirenderer
404}; // namespace android
405