TextureCache.cpp revision ce0537b80087a6225273040a987414b1dd081aa0
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#include <GLES2/gl2.h>
18
19#include "TextureCache.h"
20
21namespace android {
22namespace uirenderer {
23
24TextureCache::TextureCache(unsigned int maxEntries): mCache(maxEntries) {
25    mCache.setOnEntryRemovedListener(this);
26}
27
28TextureCache::~TextureCache() {
29    mCache.clear();
30}
31
32void TextureCache::operator()(SkBitmap* key, Texture* value) {
33    LOGD("Entry removed");
34    if (value) {
35        glDeleteTextures(1, &value->id);
36        delete value;
37    }
38}
39
40Texture* TextureCache::get(SkBitmap* bitmap) {
41    Texture* texture = mCache.get(bitmap);
42    if (!texture) {
43        texture = generateTexture(bitmap);
44        mCache.put(bitmap, texture);
45    }
46    return texture;
47}
48
49Texture* TextureCache::remove(SkBitmap* bitmap) {
50    return mCache.remove(bitmap);
51}
52
53void TextureCache::clear() {
54    mCache.clear();
55}
56
57Texture* TextureCache::generateTexture(SkBitmap* bitmap) {
58    Texture* texture = new Texture;
59
60    texture->width = bitmap->width();
61    texture->height = bitmap->height();
62
63    glGenTextures(1, &texture->id);
64    glBindTexture(GL_TEXTURE_2D, texture->id);
65
66    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
67    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
68    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
69    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
70
71    switch (bitmap->getConfig()) {
72    case SkBitmap::kRGB_565_Config:
73        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB565, texture->width, texture->height,
74                0, GL_RGB565, GL_UNSIGNED_SHORT_5_6_5, bitmap->getPixels());
75        break;
76    case SkBitmap::kARGB_8888_Config:
77        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture->width, texture->height,
78                0, GL_RGBA, GL_UNSIGNED_BYTE, bitmap->getPixels());
79        break;
80    }
81
82    return texture;
83}
84
85}; // namespace uirenderer
86}; // namespace android
87