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