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