RenderState.cpp revision 12efe649d3f5df8e81f4b78179939c1d488673a0
1/*
2 * Copyright (C) 2014 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#include "renderstate/RenderState.h"
17
18#include "renderthread/CanvasContext.h"
19#include "renderthread/EglManager.h"
20#include "utils/GLUtils.h"
21
22#include <algorithm>
23
24namespace android {
25namespace uirenderer {
26
27RenderState::RenderState(renderthread::RenderThread& thread)
28        : mRenderThread(thread)
29        , mViewportWidth(0)
30        , mViewportHeight(0)
31        , mFramebuffer(0) {
32    mThreadId = pthread_self();
33}
34
35RenderState::~RenderState() {
36    LOG_ALWAYS_FATAL_IF(mBlend || mMeshState || mScissor || mStencil,
37            "State object lifecycle not managed correctly");
38}
39
40void RenderState::onGLContextCreated() {
41    LOG_ALWAYS_FATAL_IF(mBlend || mMeshState || mScissor || mStencil,
42            "State object lifecycle not managed correctly");
43    mBlend = new Blend();
44    mMeshState = new MeshState();
45    mScissor = new Scissor();
46    mStencil = new Stencil();
47
48    // This is delayed because the first access of Caches makes GL calls
49    if (!mCaches) {
50        mCaches = &Caches::createInstance(*this);
51    }
52    mCaches->init();
53    mCaches->textureCache.setAssetAtlas(&mAssetAtlas);
54}
55
56static void layerLostGlContext(Layer* layer) {
57    layer->onGlContextLost();
58}
59
60void RenderState::onGLContextDestroyed() {
61/*
62    size_t size = mActiveLayers.size();
63    if (CC_UNLIKELY(size != 0)) {
64        ALOGE("Crashing, have %d contexts and %d layers at context destruction. isempty %d",
65                mRegisteredContexts.size(), size, mActiveLayers.empty());
66        mCaches->dumpMemoryUsage();
67        for (std::set<renderthread::CanvasContext*>::iterator cit = mRegisteredContexts.begin();
68                cit != mRegisteredContexts.end(); cit++) {
69            renderthread::CanvasContext* context = *cit;
70            ALOGE("Context: %p (root = %p)", context, context->mRootRenderNode.get());
71            ALOGE("  Prefeteched layers: %zu", context->mPrefetechedLayers.size());
72            for (std::set<RenderNode*>::iterator pit = context->mPrefetechedLayers.begin();
73                    pit != context->mPrefetechedLayers.end(); pit++) {
74                (*pit)->debugDumpLayers("    ");
75            }
76            context->mRootRenderNode->debugDumpLayers("  ");
77        }
78
79
80        if (mActiveLayers.begin() == mActiveLayers.end()) {
81            ALOGE("set has become empty. wat.");
82        }
83        for (std::set<const Layer*>::iterator lit = mActiveLayers.begin();
84             lit != mActiveLayers.end(); lit++) {
85            const Layer* layer = *(lit);
86            ALOGE("Layer %p, state %d, texlayer %d, fbo %d, buildlayered %d",
87                    layer, layer->state, layer->isTextureLayer(), layer->getFbo(), layer->wasBuildLayered);
88        }
89        LOG_ALWAYS_FATAL("%d layers have survived gl context destruction", size);
90    }
91*/
92
93    // TODO: reset all cached state in state objects
94    std::for_each(mActiveLayers.begin(), mActiveLayers.end(), layerLostGlContext);
95    mAssetAtlas.terminate();
96
97    mCaches->terminate();
98
99    delete mBlend;
100    mBlend = nullptr;
101    delete mMeshState;
102    mMeshState = nullptr;
103    delete mScissor;
104    mScissor = nullptr;
105    delete mStencil;
106    mStencil = nullptr;
107}
108
109void RenderState::setViewport(GLsizei width, GLsizei height) {
110    mViewportWidth = width;
111    mViewportHeight = height;
112    glViewport(0, 0, mViewportWidth, mViewportHeight);
113}
114
115
116void RenderState::getViewport(GLsizei* outWidth, GLsizei* outHeight) {
117    *outWidth = mViewportWidth;
118    *outHeight = mViewportHeight;
119}
120
121void RenderState::bindFramebuffer(GLuint fbo) {
122    if (mFramebuffer != fbo) {
123        mFramebuffer = fbo;
124        glBindFramebuffer(GL_FRAMEBUFFER, mFramebuffer);
125    }
126}
127
128void RenderState::invokeFunctor(Functor* functor, DrawGlInfo::Mode mode, DrawGlInfo* info) {
129    if (mode == DrawGlInfo::kModeProcessNoContext) {
130        // If there's no context we don't need to interrupt as there's
131        // no gl state to save/restore
132        (*functor)(mode, info);
133    } else {
134        interruptForFunctorInvoke();
135        (*functor)(mode, info);
136        resumeFromFunctorInvoke();
137    }
138}
139
140void RenderState::interruptForFunctorInvoke() {
141    mCaches->setProgram(nullptr);
142    mCaches->textureState().resetActiveTexture();
143    meshState().unbindMeshBuffer();
144    meshState().unbindIndicesBuffer();
145    meshState().resetVertexPointers();
146    meshState().disableTexCoordsVertexArray();
147    debugOverdraw(false, false);
148}
149
150void RenderState::resumeFromFunctorInvoke() {
151    glViewport(0, 0, mViewportWidth, mViewportHeight);
152    glBindFramebuffer(GL_FRAMEBUFFER, mFramebuffer);
153    debugOverdraw(false, false);
154
155    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
156
157    scissor().invalidate();
158    blend().invalidate();
159
160    mCaches->textureState().activateTexture(0);
161    mCaches->textureState().resetBoundTextures();
162}
163
164void RenderState::debugOverdraw(bool enable, bool clear) {
165    if (Properties::debugOverdraw && mFramebuffer == 0) {
166        if (clear) {
167            scissor().setEnabled(false);
168            stencil().clear();
169        }
170        if (enable) {
171            stencil().enableDebugWrite();
172        } else {
173            stencil().disable();
174        }
175    }
176}
177
178void RenderState::requireGLContext() {
179    assertOnGLThread();
180    LOG_ALWAYS_FATAL_IF(!mRenderThread.eglManager().hasEglContext(),
181            "No GL context!");
182}
183
184void RenderState::assertOnGLThread() {
185    pthread_t curr = pthread_self();
186    LOG_ALWAYS_FATAL_IF(!pthread_equal(mThreadId, curr), "Wrong thread!");
187}
188
189class DecStrongTask : public renderthread::RenderTask {
190public:
191    DecStrongTask(VirtualLightRefBase* object) : mObject(object) {}
192
193    virtual void run() override {
194        mObject->decStrong(nullptr);
195        mObject = nullptr;
196        delete this;
197    }
198
199private:
200    VirtualLightRefBase* mObject;
201};
202
203void RenderState::postDecStrong(VirtualLightRefBase* object) {
204    mRenderThread.queue(new DecStrongTask(object));
205}
206
207///////////////////////////////////////////////////////////////////////////////
208// Render
209///////////////////////////////////////////////////////////////////////////////
210
211void RenderState::render(const Glop& glop, const Matrix4& orthoMatrix) {
212    const Glop::Mesh& mesh = glop.mesh;
213    const Glop::Mesh::Vertices& vertices = mesh.vertices;
214    const Glop::Mesh::Indices& indices = mesh.indices;
215    const Glop::Fill& fill = glop.fill;
216
217    // ---------------------------------------------
218    // ---------- Program + uniform setup ----------
219    // ---------------------------------------------
220    mCaches->setProgram(fill.program);
221
222    if (fill.colorEnabled) {
223        fill.program->setColor(fill.color);
224    }
225
226    fill.program->set(orthoMatrix,
227            glop.transform.modelView,
228            glop.transform.meshTransform(),
229            glop.transform.transformFlags & TransformFlags::OffsetByFudgeFactor);
230
231    // Color filter uniforms
232    if (fill.filterMode == ProgramDescription::ColorFilterMode::Blend) {
233        const FloatColor& color = fill.filter.color;
234        glUniform4f(mCaches->program().getUniform("colorBlend"),
235                color.r, color.g, color.b, color.a);
236    } else if (fill.filterMode == ProgramDescription::ColorFilterMode::Matrix) {
237        glUniformMatrix4fv(mCaches->program().getUniform("colorMatrix"), 1, GL_FALSE,
238                fill.filter.matrix.matrix);
239        glUniform4fv(mCaches->program().getUniform("colorMatrixVector"), 1,
240                fill.filter.matrix.vector);
241    }
242
243    // Round rect clipping uniforms
244    if (glop.roundRectClipState) {
245        // TODO: avoid query, and cache values (or RRCS ptr) in program
246        const RoundRectClipState* state = glop.roundRectClipState;
247        const Rect& innerRect = state->innerRect;
248        glUniform4f(fill.program->getUniform("roundRectInnerRectLTRB"),
249                innerRect.left, innerRect.top,
250                innerRect.right, innerRect.bottom);
251        glUniformMatrix4fv(fill.program->getUniform("roundRectInvTransform"),
252                1, GL_FALSE, &state->matrix.data[0]);
253
254        // add half pixel to round out integer rect space to cover pixel centers
255        float roundedOutRadius = state->radius + 0.5f;
256        glUniform1f(fill.program->getUniform("roundRectRadius"),
257                roundedOutRadius);
258    }
259
260    // --------------------------------
261    // ---------- Mesh setup ----------
262    // --------------------------------
263    // vertices
264    const bool force = meshState().bindMeshBufferInternal(vertices.bufferObject)
265            || (vertices.position != nullptr);
266    meshState().bindPositionVertexPointer(force, vertices.position, vertices.stride);
267
268    // indices
269    meshState().bindIndicesBufferInternal(indices.bufferObject);
270
271    if (vertices.attribFlags & VertexAttribFlags::TextureCoord) {
272        const Glop::Fill::TextureData& texture = fill.texture;
273        // texture always takes slot 0, shader samplers increment from there
274        mCaches->textureState().activateTexture(0);
275
276        if (texture.clamp != GL_INVALID_ENUM) {
277            texture.texture->setWrap(texture.clamp, true, false, texture.target);
278        }
279        if (texture.filter != GL_INVALID_ENUM) {
280            texture.texture->setFilter(texture.filter, true, false, texture.target);
281        }
282
283        mCaches->textureState().bindTexture(texture.target, texture.texture->id);
284        meshState().enableTexCoordsVertexArray();
285        meshState().bindTexCoordsVertexPointer(force, vertices.texCoord, vertices.stride);
286
287        if (texture.textureTransform) {
288            glUniformMatrix4fv(fill.program->getUniform("mainTextureTransform"), 1,
289                    GL_FALSE, &texture.textureTransform->data[0]);
290        }
291    } else {
292        meshState().disableTexCoordsVertexArray();
293    }
294    int colorLocation = -1;
295    if (vertices.attribFlags & VertexAttribFlags::Color) {
296        colorLocation = fill.program->getAttrib("colors");
297        glEnableVertexAttribArray(colorLocation);
298        glVertexAttribPointer(colorLocation, 4, GL_FLOAT, GL_FALSE, vertices.stride, vertices.color);
299    }
300    int alphaLocation = -1;
301    if (vertices.attribFlags & VertexAttribFlags::Alpha) {
302        // NOTE: alpha vertex position is computed assuming no VBO
303        const void* alphaCoords = ((const GLbyte*) vertices.position) + kVertexAlphaOffset;
304        alphaLocation = fill.program->getAttrib("vtxAlpha");
305        glEnableVertexAttribArray(alphaLocation);
306        glVertexAttribPointer(alphaLocation, 1, GL_FLOAT, GL_FALSE, vertices.stride, alphaCoords);
307    }
308    // Shader uniforms
309    SkiaShader::apply(*mCaches, fill.skiaShaderData);
310
311    // ------------------------------------
312    // ---------- GL state setup ----------
313    // ------------------------------------
314    blend().setFactors(glop.blend.src, glop.blend.dst);
315
316    // ------------------------------------
317    // ---------- Actual drawing ----------
318    // ------------------------------------
319    if (indices.bufferObject == meshState().getQuadListIBO()) {
320        // Since the indexed quad list is of limited length, we loop over
321        // the glDrawXXX method while updating the vertex pointer
322        GLsizei elementsCount = mesh.elementCount;
323        const GLbyte* vertexData = static_cast<const GLbyte*>(vertices.position);
324        while (elementsCount > 0) {
325            GLsizei drawCount = std::min(elementsCount, (GLsizei) kMaxNumberOfQuads * 6);
326
327            // rebind pointers without forcing, since initial bind handled above
328            meshState().bindPositionVertexPointer(false, vertexData, vertices.stride);
329            if (vertices.attribFlags & VertexAttribFlags::TextureCoord) {
330                meshState().bindTexCoordsVertexPointer(false,
331                        vertexData + kMeshTextureOffset, vertices.stride);
332            }
333
334            glDrawElements(mesh.primitiveMode, drawCount, GL_UNSIGNED_SHORT, nullptr);
335            elementsCount -= drawCount;
336            vertexData += (drawCount / 6) * 4 * vertices.stride;
337        }
338    } else if (indices.bufferObject || indices.indices) {
339        glDrawElements(mesh.primitiveMode, mesh.elementCount, GL_UNSIGNED_SHORT, indices.indices);
340    } else {
341        glDrawArrays(mesh.primitiveMode, 0, mesh.elementCount);
342    }
343
344    // -----------------------------------
345    // ---------- Mesh teardown ----------
346    // -----------------------------------
347    if (vertices.attribFlags & VertexAttribFlags::Alpha) {
348        glDisableVertexAttribArray(alphaLocation);
349    }
350    if (vertices.attribFlags & VertexAttribFlags::Color) {
351        glDisableVertexAttribArray(colorLocation);
352    }
353}
354
355void RenderState::dump() {
356    blend().dump();
357    meshState().dump();
358    scissor().dump();
359    stencil().dump();
360}
361
362} /* namespace uirenderer */
363} /* namespace android */
364