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#define ATRACE_TAG ATRACE_TAG_VIEW
19
20#include <utils/Trace.h>
21
22#include "Program.h"
23#include "Vertex.h"
24
25namespace android {
26namespace uirenderer {
27
28///////////////////////////////////////////////////////////////////////////////
29// Base program
30///////////////////////////////////////////////////////////////////////////////
31
32Program::Program(const ProgramDescription& description, const char* vertex, const char* fragment) {
33    mInitialized = false;
34    mHasColorUniform = false;
35    mHasSampler = false;
36    mUse = false;
37
38    // No need to cache compiled shaders, rely instead on Android's
39    // persistent shaders cache
40    mVertexShader = buildShader(vertex, GL_VERTEX_SHADER);
41    if (mVertexShader) {
42        mFragmentShader = buildShader(fragment, GL_FRAGMENT_SHADER);
43        if (mFragmentShader) {
44            mProgramId = glCreateProgram();
45
46            glAttachShader(mProgramId, mVertexShader);
47            glAttachShader(mProgramId, mFragmentShader);
48
49            bindAttrib("position", kBindingPosition);
50            if (description.hasTexture || description.hasExternalTexture) {
51                texCoords = bindAttrib("texCoords", kBindingTexCoords);
52            } else {
53                texCoords = -1;
54            }
55
56            ATRACE_BEGIN("linkProgram");
57            glLinkProgram(mProgramId);
58            ATRACE_END();
59
60            GLint status;
61            glGetProgramiv(mProgramId, GL_LINK_STATUS, &status);
62            if (status != GL_TRUE) {
63                GLint infoLen = 0;
64                glGetProgramiv(mProgramId, GL_INFO_LOG_LENGTH, &infoLen);
65                if (infoLen > 1) {
66                    GLchar log[infoLen];
67                    glGetProgramInfoLog(mProgramId, infoLen, nullptr, &log[0]);
68                    ALOGE("%s", log);
69                }
70                LOG_ALWAYS_FATAL("Error while linking shaders");
71            } else {
72                mInitialized = true;
73            }
74        } else {
75            glDeleteShader(mVertexShader);
76        }
77    }
78
79    if (mInitialized) {
80        transform = addUniform("transform");
81        projection = addUniform("projection");
82    }
83}
84
85Program::~Program() {
86    if (mInitialized) {
87        // This would ideally happen after linking the program
88        // but Tegra drivers, especially when perfhud is enabled,
89        // sometimes crash if we do so
90        glDetachShader(mProgramId, mVertexShader);
91        glDetachShader(mProgramId, mFragmentShader);
92
93        glDeleteShader(mVertexShader);
94        glDeleteShader(mFragmentShader);
95
96        glDeleteProgram(mProgramId);
97    }
98}
99
100int Program::addAttrib(const char* name) {
101    int slot = glGetAttribLocation(mProgramId, name);
102    mAttributes.add(name, slot);
103    return slot;
104}
105
106int Program::bindAttrib(const char* name, ShaderBindings bindingSlot) {
107    glBindAttribLocation(mProgramId, bindingSlot, name);
108    mAttributes.add(name, bindingSlot);
109    return bindingSlot;
110}
111
112int Program::getAttrib(const char* name) {
113    ssize_t index = mAttributes.indexOfKey(name);
114    if (index >= 0) {
115        return mAttributes.valueAt(index);
116    }
117    return addAttrib(name);
118}
119
120int Program::addUniform(const char* name) {
121    int slot = glGetUniformLocation(mProgramId, name);
122    mUniforms.add(name, slot);
123    return slot;
124}
125
126int Program::getUniform(const char* name) {
127    ssize_t index = mUniforms.indexOfKey(name);
128    if (index >= 0) {
129        return mUniforms.valueAt(index);
130    }
131    return addUniform(name);
132}
133
134GLuint Program::buildShader(const char* source, GLenum type) {
135    ATRACE_NAME("Build GL Shader");
136
137    GLuint shader = glCreateShader(type);
138    glShaderSource(shader, 1, &source, nullptr);
139    glCompileShader(shader);
140
141    GLint status;
142    glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
143    if (status != GL_TRUE) {
144        ALOGE("Error while compiling this shader:\n===\n%s\n===", source);
145        // Some drivers return wrong values for GL_INFO_LOG_LENGTH
146        // use a fixed size instead
147        GLchar log[512];
148        glGetShaderInfoLog(shader, sizeof(log), nullptr, &log[0]);
149        LOG_ALWAYS_FATAL("Shader info log: %s", log);
150        return 0;
151    }
152
153    return shader;
154}
155
156void Program::set(const mat4& projectionMatrix, const mat4& modelViewMatrix,
157        const mat4& transformMatrix, bool offset) {
158    if (projectionMatrix != mProjection || offset != mOffset) {
159        if (CC_LIKELY(!offset)) {
160            glUniformMatrix4fv(projection, 1, GL_FALSE, &projectionMatrix.data[0]);
161        } else {
162            mat4 p(projectionMatrix);
163            // offset screenspace xy by an amount that compensates for typical precision
164            // issues in GPU hardware that tends to paint hor/vert lines in pixels shifted
165            // up and to the left.
166            // This offset value is based on an assumption that some hardware may use as
167            // little as 12.4 precision, so we offset by slightly more than 1/16.
168            p.translate(Vertex::GeometryFudgeFactor(), Vertex::GeometryFudgeFactor());
169            glUniformMatrix4fv(projection, 1, GL_FALSE, &p.data[0]);
170        }
171        mProjection = projectionMatrix;
172        mOffset = offset;
173    }
174
175    mat4 t(transformMatrix);
176    t.multiply(modelViewMatrix);
177    glUniformMatrix4fv(transform, 1, GL_FALSE, &t.data[0]);
178}
179
180void Program::setColor(FloatColor color) {
181    if (!mHasColorUniform) {
182        mColorUniform = getUniform("color");
183        mHasColorUniform = true;
184    }
185    glUniform4f(mColorUniform, color.r, color.g, color.b, color.a);
186}
187
188void Program::use() {
189    glUseProgram(mProgramId);
190    if (texCoords >= 0 && !mHasSampler) {
191        glUniform1i(getUniform("baseSampler"), 0);
192        mHasSampler = true;
193    }
194    mUse = true;
195}
196
197void Program::remove() {
198    mUse = false;
199}
200
201}; // namespace uirenderer
202}; // namespace android
203