2 * Copyright 2010 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
9 #include "SkColorFilter.h"
10 #include "SkConfig8888.h"
12 #include "SkMessageBus.h"
13 #include "SkPixelRef.h"
14 #include "SkTextureCompressor.h"
15 #include "GrResourceCache.h"
17 #include "effects/GrDitherEffect.h"
18 #include "GrDrawTargetCaps.h"
19 #include "effects/GrYUVtoRGBEffect.h"
21 #ifndef SK_IGNORE_ETC1_SUPPORT
26 /* Fill out buffer with the compressed format Ganesh expects from a colortable
27 based bitmap. [palette (colortable) + indices].
29 At the moment Ganesh only supports 8bit version. If Ganesh allowed we others
30 we could detect that the colortable.count is <= 16, and then repack the
31 indices as nibbles to save RAM, but it would take more time (i.e. a lot
32 slower than memcpy), so skipping that for now.
34 Ganesh wants a full 256 palette entry, even though Skia's ctable is only as big
35 as the colortable.count says it is.
37 static void build_compressed_data(void* buffer, const SkBitmap& bitmap) {
38 SkASSERT(kIndex_8_SkColorType == bitmap.colorType());
40 SkAutoLockPixels alp(bitmap);
41 if (!bitmap.readyToDraw()) {
42 SkDEBUGFAIL("bitmap not ready to draw!");
46 SkColorTable* ctable = bitmap.getColorTable();
47 char* dst = (char*)buffer;
49 const int count = ctable->count();
52 dstPI.fColorType = kRGBA_8888_SkColorType;
53 dstPI.fAlphaType = kPremul_SkAlphaType;
54 dstPI.fPixels = buffer;
55 dstPI.fRowBytes = count * sizeof(SkPMColor);
58 srcPI.fColorType = kN32_SkColorType;
59 srcPI.fAlphaType = kPremul_SkAlphaType;
60 srcPI.fPixels = ctable->lockColors();
61 srcPI.fRowBytes = count * sizeof(SkPMColor);
63 srcPI.convertPixelsTo(&dstPI, count, 1);
65 ctable->unlockColors();
67 // always skip a full 256 number of entries, even if we memcpy'd fewer
68 dst += 256 * sizeof(GrColor);
70 if ((unsigned)bitmap.width() == bitmap.rowBytes()) {
71 memcpy(dst, bitmap.getPixels(), bitmap.getSize());
73 // need to trim off the extra bytes per row
74 size_t width = bitmap.width();
75 size_t rowBytes = bitmap.rowBytes();
76 const char* src = (const char*)bitmap.getPixels();
77 for (int y = 0; y < bitmap.height(); y++) {
78 memcpy(dst, src, width);
85 ////////////////////////////////////////////////////////////////////////////////
87 static void generate_bitmap_cache_id(const SkBitmap& bitmap, GrCacheID* id) {
88 // Our id includes the offset, width, and height so that bitmaps created by extractSubset()
90 uint32_t genID = bitmap.getGenerationID();
91 SkIPoint origin = bitmap.pixelRefOrigin();
92 int16_t width = SkToS16(bitmap.width());
93 int16_t height = SkToS16(bitmap.height());
96 memcpy(key.fData8 + 0, &genID, 4);
97 memcpy(key.fData8 + 4, &origin.fX, 4);
98 memcpy(key.fData8 + 8, &origin.fY, 4);
99 memcpy(key.fData8 + 12, &width, 2);
100 memcpy(key.fData8 + 14, &height, 2);
101 static const size_t kKeyDataSize = 16;
102 memset(key.fData8 + kKeyDataSize, 0, sizeof(key) - kKeyDataSize);
103 GR_STATIC_ASSERT(sizeof(key) >= kKeyDataSize);
104 static const GrCacheID::Domain gBitmapTextureDomain = GrCacheID::GenerateDomain();
105 id->reset(gBitmapTextureDomain, key);
108 static void generate_bitmap_texture_desc(const SkBitmap& bitmap, GrTextureDesc* desc) {
109 desc->fFlags = kNone_GrTextureFlags;
110 desc->fWidth = bitmap.width();
111 desc->fHeight = bitmap.height();
112 desc->fConfig = SkImageInfo2GrPixelConfig(bitmap.info());
113 desc->fSampleCnt = 0;
118 // When the SkPixelRef genID changes, invalidate a corresponding GrResource described by key.
119 class GrResourceInvalidator : public SkPixelRef::GenIDChangeListener {
121 explicit GrResourceInvalidator(GrResourceKey key) : fKey(key) {}
125 virtual void onChange() SK_OVERRIDE {
126 const GrResourceInvalidatedMessage message = { fKey };
127 SkMessageBus<GrResourceInvalidatedMessage>::Post(message);
133 static void add_genID_listener(GrResourceKey key, SkPixelRef* pixelRef) {
134 SkASSERT(NULL != pixelRef);
135 pixelRef->addGenIDChangeListener(SkNEW_ARGS(GrResourceInvalidator, (key)));
138 #ifndef SK_IGNORE_ETC1_SUPPORT
139 static GrTexture *load_etc1_texture(GrContext* ctx,
140 const GrTextureParams* params,
141 const SkBitmap &bm, GrTextureDesc desc) {
142 SkAutoTUnref<SkData> data(bm.pixelRef()->refEncodedData());
144 // Is this even encoded data?
149 // Is this a valid PKM encoded data?
150 const uint8_t *bytes = data->bytes();
151 if (etc1_pkm_is_valid(bytes)) {
152 uint32_t encodedWidth = etc1_pkm_get_width(bytes);
153 uint32_t encodedHeight = etc1_pkm_get_height(bytes);
155 // Does the data match the dimensions of the bitmap? If not,
156 // then we don't know how to scale the image to match it...
157 if (encodedWidth != static_cast<uint32_t>(bm.width()) ||
158 encodedHeight != static_cast<uint32_t>(bm.height())) {
162 // Everything seems good... skip ahead to the data.
163 bytes += ETC_PKM_HEADER_SIZE;
164 desc.fConfig = kETC1_GrPixelConfig;
165 } else if (SkKTXFile::is_ktx(bytes)) {
168 // Is it actually an ETC1 texture?
169 if (!ktx.isCompressedFormat(SkTextureCompressor::kETC1_Format)) {
173 // Does the data match the dimensions of the bitmap? If not,
174 // then we don't know how to scale the image to match it...
175 if (ktx.width() != bm.width() || ktx.height() != bm.height()) {
179 bytes = ktx.pixelData();
180 desc.fConfig = kETC1_GrPixelConfig;
185 // This texture is likely to be used again so leave it in the cache
187 generate_bitmap_cache_id(bm, &cacheID);
190 GrTexture* result = ctx->createTexture(params, desc, cacheID, bytes, 0, &key);
191 if (NULL != result) {
192 add_genID_listener(key, bm.pixelRef());
196 #endif // SK_IGNORE_ETC1_SUPPORT
198 static GrTexture *load_yuv_texture(GrContext* ctx, const GrTextureParams* params,
199 const SkBitmap& bm, const GrTextureDesc& desc) {
200 GrTexture* result = NULL;
202 SkPixelRef* pixelRef = bm.pixelRef();
204 if ((NULL == pixelRef) || !pixelRef->getYUV8Planes(yuvSizes, NULL, NULL)) {
208 // Allocate the memory for YUV
210 size_t sizes[3], rowBytes[3];
211 for (int i = 0; i < 3; ++i) {
212 rowBytes[i] = yuvSizes[i].fWidth;
213 totalSize += sizes[i] = rowBytes[i] * yuvSizes[i].fHeight;
215 SkAutoMalloc storage(totalSize);
217 planes[0] = storage.get();
218 planes[1] = (uint8_t*)planes[0] + sizes[0];
219 planes[2] = (uint8_t*)planes[1] + sizes[1];
221 // Get the YUV planes
222 if (!pixelRef->getYUV8Planes(yuvSizes, planes, rowBytes)) {
226 GrTextureDesc yuvDesc;
227 yuvDesc.fConfig = kAlpha_8_GrPixelConfig;
228 GrAutoScratchTexture yuvTextures[3];
229 for (int i = 0; i < 3; ++i) {
230 yuvDesc.fWidth = yuvSizes[i].fWidth;
231 yuvDesc.fHeight = yuvSizes[i].fHeight;
232 yuvTextures[i].set(ctx, yuvDesc);
233 if ((NULL == yuvTextures[i].texture()) ||
234 !ctx->writeTexturePixels(yuvTextures[i].texture(),
235 0, 0, yuvDesc.fWidth, yuvDesc.fHeight,
236 yuvDesc.fConfig, planes[i], rowBytes[i])) {
241 GrTextureDesc rtDesc = desc;
242 rtDesc.fFlags = rtDesc.fFlags |
243 kRenderTarget_GrTextureFlagBit |
244 kNoStencil_GrTextureFlagBit;
246 // This texture is likely to be used again so leave it in the cache
248 generate_bitmap_cache_id(bm, &cacheID);
251 result = ctx->createTexture(params, rtDesc, cacheID, NULL, 0, &key);
252 GrRenderTarget* renderTarget = result ? result->asRenderTarget() : NULL;
253 if (NULL != renderTarget) {
254 add_genID_listener(key, bm.pixelRef());
255 SkAutoTUnref<GrEffect> yuvToRgbEffect(GrYUVtoRGBEffect::Create(
256 yuvTextures[0].texture(), yuvTextures[1].texture(), yuvTextures[2].texture()));
258 paint.addColorEffect(yuvToRgbEffect);
259 SkRect r = SkRect::MakeWH(SkIntToScalar(yuvSizes[0].fWidth),
260 SkIntToScalar(yuvSizes[0].fHeight));
261 GrContext::AutoRenderTarget autoRT(ctx, renderTarget);
262 GrContext::AutoMatrix am;
264 GrContext::AutoClip ac(ctx, GrContext::AutoClip::kWideOpen_InitialClip);
265 ctx->drawRect(paint, r);
267 SkSafeSetNull(result);
273 static GrTexture* sk_gr_create_bitmap_texture(GrContext* ctx,
275 const GrTextureParams* params,
276 const SkBitmap& origBitmap) {
279 const SkBitmap* bitmap = &origBitmap;
282 generate_bitmap_texture_desc(*bitmap, &desc);
284 if (kIndex_8_SkColorType == bitmap->colorType()) {
285 // build_compressed_data doesn't do npot->pot expansion
286 // and paletted textures can't be sub-updated
287 if (ctx->supportsIndex8PixelConfig(params, bitmap->width(), bitmap->height())) {
288 size_t imageSize = GrCompressedFormatDataSize(kIndex_8_GrPixelConfig,
289 bitmap->width(), bitmap->height());
290 SkAutoMalloc storage(imageSize);
292 build_compressed_data(storage.get(), origBitmap);
294 // our compressed data will be trimmed, so pass width() for its
295 // "rowBytes", since they are the same now.
299 generate_bitmap_cache_id(origBitmap, &cacheID);
302 GrTexture* result = ctx->createTexture(params, desc, cacheID,
303 storage.get(), bitmap->width(), &key);
304 if (NULL != result) {
305 add_genID_listener(key, origBitmap.pixelRef());
309 GrTexture* result = ctx->lockAndRefScratchTexture(desc,
310 GrContext::kExact_ScratchTexMatch);
311 result->writePixels(0, 0, bitmap->width(),
312 bitmap->height(), desc.fConfig,
317 origBitmap.copyTo(&tmpBitmap, kN32_SkColorType);
318 // now bitmap points to our temp, which has been promoted to 32bits
320 desc.fConfig = SkImageInfo2GrPixelConfig(bitmap->info());
324 // Is this an ETC1 encoded texture?
325 #ifndef SK_IGNORE_ETC1_SUPPORT
327 // We do not support scratch ETC1 textures, hence they should all be at least
328 // trying to go to the cache.
330 // Make sure that the underlying device supports ETC1 textures before we go ahead
331 // and check the data.
332 && ctx->getGpu()->caps()->isConfigTexturable(kETC1_GrPixelConfig)
333 // If the bitmap had compressed data and was then uncompressed, it'll still return
334 // compressed data on 'refEncodedData' and upload it. Probably not good, since if
335 // the bitmap has available pixels, then they might not be what the decompressed
337 && !(bitmap->readyToDraw())) {
338 GrTexture *texture = load_etc1_texture(ctx, params, *bitmap, desc);
339 if (NULL != texture) {
343 #endif // SK_IGNORE_ETC1_SUPPORT
346 GrTexture *texture = load_yuv_texture(ctx, params, *bitmap, desc);
347 if (NULL != texture) {
351 SkAutoLockPixels alp(*bitmap);
352 if (!bitmap->readyToDraw()) {
356 // This texture is likely to be used again so leave it in the cache
358 generate_bitmap_cache_id(origBitmap, &cacheID);
361 GrTexture* result = ctx->createTexture(params, desc, cacheID,
362 bitmap->getPixels(), bitmap->rowBytes(), &key);
363 if (NULL != result) {
364 add_genID_listener(key, origBitmap.pixelRef());
368 // This texture is unlikely to be used again (in its present form) so
369 // just use a scratch texture. This will remove the texture from the
370 // cache so no one else can find it. Additionally, once unlocked, the
371 // scratch texture will go to the end of the list for purging so will
372 // likely be available for this volatile bitmap the next time around.
373 GrTexture* result = ctx->lockAndRefScratchTexture(desc, GrContext::kExact_ScratchTexMatch);
374 result->writePixels(0, 0,
375 bitmap->width(), bitmap->height(),
383 bool GrIsBitmapInCache(const GrContext* ctx,
384 const SkBitmap& bitmap,
385 const GrTextureParams* params) {
387 generate_bitmap_cache_id(bitmap, &cacheID);
390 generate_bitmap_texture_desc(bitmap, &desc);
391 return ctx->isTextureInCache(desc, cacheID, params);
394 GrTexture* GrLockAndRefCachedBitmapTexture(GrContext* ctx,
395 const SkBitmap& bitmap,
396 const GrTextureParams* params) {
397 GrTexture* result = NULL;
399 bool cache = !bitmap.isVolatile();
402 // If the bitmap isn't changing try to find a cached copy first.
405 generate_bitmap_cache_id(bitmap, &cacheID);
408 generate_bitmap_texture_desc(bitmap, &desc);
410 result = ctx->findAndRefTexture(desc, cacheID, params);
412 if (NULL == result) {
413 result = sk_gr_create_bitmap_texture(ctx, cache, params, bitmap);
415 if (NULL == result) {
416 GrPrintf("---- failed to create texture for cache [%d %d]\n",
417 bitmap.width(), bitmap.height());
422 void GrUnlockAndUnrefCachedBitmapTexture(GrTexture* texture) {
423 SkASSERT(NULL != texture->getContext());
425 texture->getContext()->unlockScratchTexture(texture);
429 ///////////////////////////////////////////////////////////////////////////////
431 #ifdef SK_SUPPORT_LEGACY_BITMAP_CONFIG
432 GrPixelConfig SkBitmapConfig2GrPixelConfig(SkBitmap::Config config) {
434 case SkBitmap::kA8_Config:
435 return kAlpha_8_GrPixelConfig;
436 case SkBitmap::kIndex8_Config:
437 return kIndex_8_GrPixelConfig;
438 case SkBitmap::kRGB_565_Config:
439 return kRGB_565_GrPixelConfig;
440 case SkBitmap::kARGB_4444_Config:
441 return kRGBA_4444_GrPixelConfig;
442 case SkBitmap::kARGB_8888_Config:
443 return kSkia8888_GrPixelConfig;
445 // kNo_Config, kA1_Config missing
446 return kUnknown_GrPixelConfig;
451 // alphatype is ignore for now, but if GrPixelConfig is expanded to encompass
452 // alpha info, that will be considered.
453 GrPixelConfig SkImageInfo2GrPixelConfig(SkColorType ct, SkAlphaType) {
455 case kUnknown_SkColorType:
456 return kUnknown_GrPixelConfig;
457 case kAlpha_8_SkColorType:
458 return kAlpha_8_GrPixelConfig;
459 case kRGB_565_SkColorType:
460 return kRGB_565_GrPixelConfig;
461 case kARGB_4444_SkColorType:
462 return kRGBA_4444_GrPixelConfig;
463 case kRGBA_8888_SkColorType:
464 return kRGBA_8888_GrPixelConfig;
465 case kBGRA_8888_SkColorType:
466 return kBGRA_8888_GrPixelConfig;
467 case kIndex_8_SkColorType:
468 return kIndex_8_GrPixelConfig;
470 SkASSERT(0); // shouldn't get here
471 return kUnknown_GrPixelConfig;
474 bool GrPixelConfig2ColorType(GrPixelConfig config, SkColorType* ctOut) {
477 case kAlpha_8_GrPixelConfig:
478 ct = kAlpha_8_SkColorType;
480 case kIndex_8_GrPixelConfig:
481 ct = kIndex_8_SkColorType;
483 case kRGB_565_GrPixelConfig:
484 ct = kRGB_565_SkColorType;
486 case kRGBA_4444_GrPixelConfig:
487 ct = kARGB_4444_SkColorType;
489 case kRGBA_8888_GrPixelConfig:
490 ct = kRGBA_8888_SkColorType;
492 case kBGRA_8888_GrPixelConfig:
493 ct = kBGRA_8888_SkColorType;
504 ///////////////////////////////////////////////////////////////////////////////
506 void SkPaint2GrPaintNoShader(GrContext* context, const SkPaint& skPaint, GrColor paintColor,
507 bool constantColor, GrPaint* grPaint) {
509 grPaint->setDither(skPaint.isDither());
510 grPaint->setAntiAlias(skPaint.isAntiAlias());
512 SkXfermode::Coeff sm;
513 SkXfermode::Coeff dm;
515 SkXfermode* mode = skPaint.getXfermode();
516 GrEffect* xferEffect = NULL;
517 if (SkXfermode::AsNewEffectOrCoeff(mode, &xferEffect, &sm, &dm)) {
518 if (NULL != xferEffect) {
519 grPaint->addColorEffect(xferEffect)->unref();
520 sm = SkXfermode::kOne_Coeff;
521 dm = SkXfermode::kZero_Coeff;
524 //SkDEBUGCODE(SkDebugf("Unsupported xfer mode.\n");)
525 // Fall back to src-over
526 sm = SkXfermode::kOne_Coeff;
527 dm = SkXfermode::kISA_Coeff;
529 grPaint->setBlendFunc(sk_blend_to_grblend(sm), sk_blend_to_grblend(dm));
531 //set the color of the paint to the one of the parameter
532 grPaint->setColor(paintColor);
534 SkColorFilter* colorFilter = skPaint.getColorFilter();
535 if (NULL != colorFilter) {
536 // if the source color is a constant then apply the filter here once rather than per pixel
539 SkColor filtered = colorFilter->filterColor(skPaint.getColor());
540 grPaint->setColor(SkColor2GrColor(filtered));
542 SkAutoTUnref<GrEffect> effect(colorFilter->asNewEffect(context));
543 if (NULL != effect.get()) {
544 grPaint->addColorEffect(effect);
549 #ifndef SK_IGNORE_GPU_DITHER
550 // If the dither flag is set, then we need to see if the underlying context
551 // supports it. If not, then install a dither effect.
552 if (skPaint.isDither() && grPaint->numColorStages() > 0) {
553 // What are we rendering into?
554 const GrRenderTarget *target = context->getRenderTarget();
555 SkASSERT(NULL != target);
557 // Suspect the dithering flag has no effect on these configs, otherwise
558 // fall back on setting the appropriate state.
559 if (target->config() == kRGBA_8888_GrPixelConfig ||
560 target->config() == kBGRA_8888_GrPixelConfig) {
561 // The dither flag is set and the target is likely
562 // not going to be dithered by the GPU.
563 SkAutoTUnref<GrEffect> effect(GrDitherEffect::Create());
564 if (NULL != effect.get()) {
565 grPaint->addColorEffect(effect);
566 grPaint->setDither(false);
574 * Unlike GrContext::AutoMatrix, this doesn't require setting a new matrix. GrContext::AutoMatrix
575 * likes to set the new matrix in its constructor because it is usually necessary to simulataneously
576 * update a GrPaint. This AutoMatrix is used while initially setting up GrPaint, however.
580 AutoMatrix(GrContext* context) {
581 fMatrix = context->getMatrix();
585 SkASSERT(NULL != fContext);
586 fContext->setMatrix(fMatrix);
593 void SkPaint2GrPaintShader(GrContext* context, const SkPaint& skPaint,
594 bool constantColor, GrPaint* grPaint) {
595 SkShader* shader = skPaint.getShader();
596 if (NULL == shader) {
597 SkPaint2GrPaintNoShader(context, skPaint, SkColor2GrColor(skPaint.getColor()),
598 constantColor, grPaint);
602 GrColor paintColor = SkColor2GrColor(skPaint.getColor());
604 // Start a new block here in order to preserve our context state after calling
605 // asNewEffect(). Since these calls get passed back to the client, we don't really
606 // want them messing around with the context.
608 // SkShader::asNewEffect() may do offscreen rendering. Save off the current RT, clip, and
609 // matrix. We don't reset the matrix on the context because SkShader::asNewEffect may use
610 // GrContext::getMatrix() to know the transformation from local coords to device space.
611 GrContext::AutoRenderTarget art(context, NULL);
612 GrContext::AutoClip ac(context, GrContext::AutoClip::kWideOpen_InitialClip);
613 AutoMatrix am(context);
615 // Allow the shader to modify paintColor and also create an effect to be installed as
616 // the first color effect on the GrPaint.
617 GrEffect* effect = NULL;
618 if (shader->asNewEffect(context, skPaint, NULL, &paintColor, &effect) && NULL != effect) {
619 grPaint->addColorEffect(effect)->unref();
620 constantColor = false;
624 // The grcolor is automatically set when calling asneweffect.
625 // If the shader can be seen as an effect it returns true and adds its effect to the grpaint.
626 SkPaint2GrPaintNoShader(context, skPaint, paintColor, constantColor, grPaint);