RenderState.cpp revision c3f131696111a066d9efd9c7c3e37566a2a9fb89
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 "DeferredLayerUpdater.h"
17#include "GlLayer.h"
18#include "VkLayer.h"
19#include <GpuMemoryTracker.h>
20#include "renderstate/RenderState.h"
21
22#include "renderthread/CanvasContext.h"
23#include "renderthread/EglManager.h"
24#include "utils/GLUtils.h"
25#include <algorithm>
26
27namespace android {
28namespace uirenderer {
29
30RenderState::RenderState(renderthread::RenderThread& thread)
31        : mRenderThread(thread)
32        , mViewportWidth(0)
33        , mViewportHeight(0)
34        , mFramebuffer(0) {
35    mThreadId = pthread_self();
36}
37
38RenderState::~RenderState() {
39    LOG_ALWAYS_FATAL_IF(mBlend || mMeshState || mScissor || mStencil,
40            "State object lifecycle not managed correctly");
41}
42
43void RenderState::onGLContextCreated() {
44    LOG_ALWAYS_FATAL_IF(mBlend || mMeshState || mScissor || mStencil,
45            "State object lifecycle not managed correctly");
46    GpuMemoryTracker::onGpuContextCreated();
47
48    mBlend = new Blend();
49    mMeshState = new MeshState();
50    mScissor = new Scissor();
51    mStencil = new Stencil();
52
53    // This is delayed because the first access of Caches makes GL calls
54    if (!mCaches) {
55        mCaches = &Caches::createInstance(*this);
56    }
57    mCaches->init();
58}
59
60static void layerLostGlContext(Layer* layer) {
61    LOG_ALWAYS_FATAL_IF(layer->getApi() != Layer::Api::OpenGL,
62            "layerLostGlContext on non GL layer");
63    static_cast<GlLayer*>(layer)->onGlContextLost();
64}
65
66void RenderState::onGLContextDestroyed() {
67    mLayerPool.clear();
68
69    // TODO: reset all cached state in state objects
70    std::for_each(mActiveLayers.begin(), mActiveLayers.end(), layerLostGlContext);
71
72    mCaches->terminate();
73
74    delete mBlend;
75    mBlend = nullptr;
76    delete mMeshState;
77    mMeshState = nullptr;
78    delete mScissor;
79    mScissor = nullptr;
80    delete mStencil;
81    mStencil = nullptr;
82
83    destroyLayersInUpdater();
84    GpuMemoryTracker::onGpuContextDestroyed();
85}
86
87void RenderState::onVkContextCreated() {
88    LOG_ALWAYS_FATAL_IF(mBlend || mMeshState || mScissor || mStencil,
89            "State object lifecycle not managed correctly");
90    GpuMemoryTracker::onGpuContextCreated();
91}
92
93static void layerDestroyedVkContext(Layer* layer) {
94    LOG_ALWAYS_FATAL_IF(layer->getApi() != Layer::Api::Vulkan,
95                        "layerLostVkContext on non Vulkan layer");
96    static_cast<VkLayer*>(layer)->onVkContextDestroyed();
97}
98
99void RenderState::onVkContextDestroyed() {
100    mLayerPool.clear();
101    std::for_each(mActiveLayers.begin(), mActiveLayers.end(), layerDestroyedVkContext);
102    GpuMemoryTracker::onGpuContextDestroyed();
103}
104
105GrContext* RenderState::getGrContext() const {
106    return mRenderThread.getGrContext();
107}
108
109void RenderState::flush(Caches::FlushMode mode) {
110    switch (mode) {
111        case Caches::FlushMode::Full:
112            // fall through
113        case Caches::FlushMode::Moderate:
114            // fall through
115        case Caches::FlushMode::Layers:
116            mLayerPool.clear();
117            break;
118    }
119    mCaches->flush(mode);
120}
121
122void RenderState::setViewport(GLsizei width, GLsizei height) {
123    mViewportWidth = width;
124    mViewportHeight = height;
125    glViewport(0, 0, mViewportWidth, mViewportHeight);
126}
127
128
129void RenderState::getViewport(GLsizei* outWidth, GLsizei* outHeight) {
130    *outWidth = mViewportWidth;
131    *outHeight = mViewportHeight;
132}
133
134void RenderState::bindFramebuffer(GLuint fbo) {
135    if (mFramebuffer != fbo) {
136        mFramebuffer = fbo;
137        glBindFramebuffer(GL_FRAMEBUFFER, mFramebuffer);
138    }
139}
140
141GLuint RenderState::createFramebuffer() {
142    GLuint ret;
143    glGenFramebuffers(1, &ret);
144    return ret;
145}
146
147void RenderState::deleteFramebuffer(GLuint fbo) {
148    if (mFramebuffer == fbo) {
149        // GL defines that deleting the currently bound FBO rebinds FBO 0.
150        // Reflect this in our cached value.
151        mFramebuffer = 0;
152    }
153    glDeleteFramebuffers(1, &fbo);
154}
155
156void RenderState::invokeFunctor(Functor* functor, DrawGlInfo::Mode mode, DrawGlInfo* info) {
157    if (mode == DrawGlInfo::kModeProcessNoContext) {
158        // If there's no context we don't need to interrupt as there's
159        // no gl state to save/restore
160        (*functor)(mode, info);
161    } else {
162        interruptForFunctorInvoke();
163        (*functor)(mode, info);
164        resumeFromFunctorInvoke();
165    }
166}
167
168void RenderState::interruptForFunctorInvoke() {
169    mCaches->setProgram(nullptr);
170    mCaches->textureState().resetActiveTexture();
171    meshState().unbindMeshBuffer();
172    meshState().unbindIndicesBuffer();
173    meshState().resetVertexPointers();
174    meshState().disableTexCoordsVertexArray();
175    debugOverdraw(false, false);
176    // TODO: We need a way to know whether the functor is sRGB aware (b/32072673)
177    if (mCaches->extensions().hasSRGBWriteControl()) {
178        glDisable(GL_FRAMEBUFFER_SRGB_EXT);
179    }
180}
181
182void RenderState::resumeFromFunctorInvoke() {
183    if (mCaches->extensions().hasSRGBWriteControl()) {
184        glEnable(GL_FRAMEBUFFER_SRGB_EXT);
185    }
186
187    glViewport(0, 0, mViewportWidth, mViewportHeight);
188    glBindFramebuffer(GL_FRAMEBUFFER, mFramebuffer);
189    debugOverdraw(false, false);
190
191    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
192
193    scissor().invalidate();
194    blend().invalidate();
195
196    mCaches->textureState().activateTexture(0);
197    mCaches->textureState().resetBoundTextures();
198}
199
200void RenderState::debugOverdraw(bool enable, bool clear) {
201    if (Properties::debugOverdraw && mFramebuffer == 0) {
202        if (clear) {
203            scissor().setEnabled(false);
204            stencil().clear();
205        }
206        if (enable) {
207            stencil().enableDebugWrite();
208        } else {
209            stencil().disable();
210        }
211    }
212}
213
214static void destroyLayerInUpdater(DeferredLayerUpdater* layerUpdater) {
215    layerUpdater->destroyLayer();
216}
217
218void RenderState::destroyLayersInUpdater() {
219    std::for_each(mActiveLayerUpdaters.begin(), mActiveLayerUpdaters.end(), destroyLayerInUpdater);
220}
221
222class DecStrongTask : public renderthread::RenderTask {
223public:
224    explicit DecStrongTask(VirtualLightRefBase* object) : mObject(object) {}
225
226    virtual void run() override {
227        mObject->decStrong(nullptr);
228        mObject = nullptr;
229        delete this;
230    }
231
232private:
233    VirtualLightRefBase* mObject;
234};
235
236void RenderState::postDecStrong(VirtualLightRefBase* object) {
237    if (pthread_equal(mThreadId, pthread_self())) {
238        object->decStrong(nullptr);
239    } else {
240        mRenderThread.queue(new DecStrongTask(object));
241    }
242}
243
244///////////////////////////////////////////////////////////////////////////////
245// Render
246///////////////////////////////////////////////////////////////////////////////
247
248void RenderState::render(const Glop& glop, const Matrix4& orthoMatrix) {
249    const Glop::Mesh& mesh = glop.mesh;
250    const Glop::Mesh::Vertices& vertices = mesh.vertices;
251    const Glop::Mesh::Indices& indices = mesh.indices;
252    const Glop::Fill& fill = glop.fill;
253
254    GL_CHECKPOINT(MODERATE);
255
256    // ---------------------------------------------
257    // ---------- Program + uniform setup ----------
258    // ---------------------------------------------
259    mCaches->setProgram(fill.program);
260
261    if (fill.colorEnabled) {
262        fill.program->setColor(fill.color);
263    }
264
265    fill.program->set(orthoMatrix,
266            glop.transform.modelView,
267            glop.transform.meshTransform(),
268            glop.transform.transformFlags & TransformFlags::OffsetByFudgeFactor);
269
270    // Color filter uniforms
271    if (fill.filterMode == ProgramDescription::ColorFilterMode::Blend) {
272        const FloatColor& color = fill.filter.color;
273        glUniform4f(mCaches->program().getUniform("colorBlend"),
274                color.r, color.g, color.b, color.a);
275    } else if (fill.filterMode == ProgramDescription::ColorFilterMode::Matrix) {
276        glUniformMatrix4fv(mCaches->program().getUniform("colorMatrix"), 1, GL_FALSE,
277                fill.filter.matrix.matrix);
278        glUniform4fv(mCaches->program().getUniform("colorMatrixVector"), 1,
279                fill.filter.matrix.vector);
280    }
281
282    // Round rect clipping uniforms
283    if (glop.roundRectClipState) {
284        // TODO: avoid query, and cache values (or RRCS ptr) in program
285        const RoundRectClipState* state = glop.roundRectClipState;
286        const Rect& innerRect = state->innerRect;
287        glUniform4f(fill.program->getUniform("roundRectInnerRectLTRB"),
288                innerRect.left, innerRect.top,
289                innerRect.right, innerRect.bottom);
290        glUniformMatrix4fv(fill.program->getUniform("roundRectInvTransform"),
291                1, GL_FALSE, &state->matrix.data[0]);
292
293        // add half pixel to round out integer rect space to cover pixel centers
294        float roundedOutRadius = state->radius + 0.5f;
295        glUniform1f(fill.program->getUniform("roundRectRadius"),
296                roundedOutRadius);
297    }
298
299    GL_CHECKPOINT(MODERATE);
300
301    // --------------------------------
302    // ---------- Mesh setup ----------
303    // --------------------------------
304    // vertices
305    meshState().bindMeshBuffer(vertices.bufferObject);
306    meshState().bindPositionVertexPointer(vertices.position, vertices.stride);
307
308    // indices
309    meshState().bindIndicesBuffer(indices.bufferObject);
310
311    // texture
312    if (fill.texture.texture != nullptr) {
313        const Glop::Fill::TextureData& texture = fill.texture;
314        // texture always takes slot 0, shader samplers increment from there
315        mCaches->textureState().activateTexture(0);
316
317        mCaches->textureState().bindTexture(texture.texture->target(), texture.texture->id());
318        if (texture.clamp != GL_INVALID_ENUM) {
319            texture.texture->setWrap(texture.clamp, false, false);
320        }
321        if (texture.filter != GL_INVALID_ENUM) {
322            texture.texture->setFilter(texture.filter, false, false);
323        }
324
325        if (texture.textureTransform) {
326            glUniformMatrix4fv(fill.program->getUniform("mainTextureTransform"), 1,
327                    GL_FALSE, &texture.textureTransform->data[0]);
328        }
329    }
330
331    // vertex attributes (tex coord, color, alpha)
332    if (vertices.attribFlags & VertexAttribFlags::TextureCoord) {
333        meshState().enableTexCoordsVertexArray();
334        meshState().bindTexCoordsVertexPointer(vertices.texCoord, vertices.stride);
335    } else {
336        meshState().disableTexCoordsVertexArray();
337    }
338    int colorLocation = -1;
339    if (vertices.attribFlags & VertexAttribFlags::Color) {
340        colorLocation = fill.program->getAttrib("colors");
341        glEnableVertexAttribArray(colorLocation);
342        glVertexAttribPointer(colorLocation, 4, GL_FLOAT, GL_FALSE, vertices.stride, vertices.color);
343    }
344    int alphaLocation = -1;
345    if (vertices.attribFlags & VertexAttribFlags::Alpha) {
346        // NOTE: alpha vertex position is computed assuming no VBO
347        const void* alphaCoords = ((const GLbyte*) vertices.position) + kVertexAlphaOffset;
348        alphaLocation = fill.program->getAttrib("vtxAlpha");
349        glEnableVertexAttribArray(alphaLocation);
350        glVertexAttribPointer(alphaLocation, 1, GL_FLOAT, GL_FALSE, vertices.stride, alphaCoords);
351    }
352    // Shader uniforms
353    SkiaShader::apply(*mCaches, fill.skiaShaderData, mViewportWidth, mViewportHeight);
354
355    GL_CHECKPOINT(MODERATE);
356    Texture* texture = (fill.skiaShaderData.skiaShaderType & kBitmap_SkiaShaderType) ?
357            fill.skiaShaderData.bitmapData.bitmapTexture : nullptr;
358    const AutoTexture autoCleanup(texture);
359
360    // ------------------------------------
361    // ---------- GL state setup ----------
362    // ------------------------------------
363    blend().setFactors(glop.blend.src, glop.blend.dst);
364
365    GL_CHECKPOINT(MODERATE);
366
367    // ------------------------------------
368    // ---------- Actual drawing ----------
369    // ------------------------------------
370    if (indices.bufferObject == meshState().getQuadListIBO()) {
371        // Since the indexed quad list is of limited length, we loop over
372        // the glDrawXXX method while updating the vertex pointer
373        GLsizei elementsCount = mesh.elementCount;
374        const GLbyte* vertexData = static_cast<const GLbyte*>(vertices.position);
375        while (elementsCount > 0) {
376            GLsizei drawCount = std::min(elementsCount, (GLsizei) kMaxNumberOfQuads * 6);
377            meshState().bindPositionVertexPointer(vertexData, vertices.stride);
378            if (vertices.attribFlags & VertexAttribFlags::TextureCoord) {
379                meshState().bindTexCoordsVertexPointer(
380                        vertexData + kMeshTextureOffset, vertices.stride);
381            }
382
383            glDrawElements(mesh.primitiveMode, drawCount, GL_UNSIGNED_SHORT, nullptr);
384            elementsCount -= drawCount;
385            vertexData += (drawCount / 6) * 4 * vertices.stride;
386        }
387    } else if (indices.bufferObject || indices.indices) {
388        glDrawElements(mesh.primitiveMode, mesh.elementCount, GL_UNSIGNED_SHORT, indices.indices);
389    } else {
390        glDrawArrays(mesh.primitiveMode, 0, mesh.elementCount);
391    }
392
393    GL_CHECKPOINT(MODERATE);
394
395    // -----------------------------------
396    // ---------- Mesh teardown ----------
397    // -----------------------------------
398    if (vertices.attribFlags & VertexAttribFlags::Alpha) {
399        glDisableVertexAttribArray(alphaLocation);
400    }
401    if (vertices.attribFlags & VertexAttribFlags::Color) {
402        glDisableVertexAttribArray(colorLocation);
403    }
404
405    GL_CHECKPOINT(MODERATE);
406}
407
408void RenderState::dump() {
409    blend().dump();
410    meshState().dump();
411    scissor().dump();
412    stencil().dump();
413}
414
415} /* namespace uirenderer */
416} /* namespace android */
417