| reed@android.com | 2ee7c64 | 2009-10-28 14:25:34 +0000 | [diff] [blame] | 1 | #include "SkMeshUtils.h" |
| 2 | #include "SkCanvas.h" |
| 3 | #include "SkPaint.h" |
| 4 | |
| 5 | SkMeshIndices::SkMeshIndices() { |
| 6 | sk_bzero(this, sizeof(*this)); |
| 7 | } |
| 8 | |
| 9 | SkMeshIndices::~SkMeshIndices() { |
| 10 | sk_free(fStorage); |
| 11 | } |
| 12 | |
| 13 | bool SkMeshIndices::init(SkPoint tex[], uint16_t indices[], |
| 14 | int texW, int texH, int rows, int cols) { |
| 15 | if (rows < 2 || cols < 2) { |
| 16 | sk_free(fStorage); |
| 17 | fStorage = NULL; |
| 18 | fTex = NULL; |
| 19 | fIndices = NULL; |
| 20 | fTexCount = fIndexCount = 0; |
| 21 | return false; |
| 22 | } |
| 23 | |
| 24 | sk_free(fStorage); |
| 25 | fStorage = NULL; |
| 26 | |
| 27 | fTexCount = rows * cols; |
| 28 | rows -= 1; |
| 29 | cols -= 1; |
| 30 | fIndexCount = rows * cols * 6; |
| 31 | |
| 32 | if (tex) { |
| 33 | fTex = tex; |
| 34 | fIndices = indices; |
| 35 | } else { |
| 36 | fStorage = sk_malloc_throw(fTexCount * sizeof(SkPoint) + |
| 37 | fIndexCount * sizeof(uint16_t)); |
| 38 | fTex = (SkPoint*)fStorage; |
| 39 | fIndices = (uint16_t*)(fTex + fTexCount); |
| 40 | } |
| 41 | |
| 42 | // compute the indices |
| 43 | { |
| 44 | uint16_t* idx = fIndices; |
| 45 | int index = 0; |
| 46 | for (int y = 0; y < cols; y++) { |
| 47 | for (int x = 0; x < rows; x++) { |
| 48 | *idx++ = index; |
| 49 | *idx++ = index + rows + 1; |
| 50 | *idx++ = index + 1; |
| 51 | |
| 52 | *idx++ = index + 1; |
| 53 | *idx++ = index + rows + 1; |
| 54 | *idx++ = index + rows + 2; |
| 55 | |
| 56 | index += 1; |
| 57 | } |
| 58 | index += 1; |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | // compute texture coordinates |
| 63 | { |
| 64 | SkPoint* tex = fTex; |
| 65 | const SkScalar dx = SkIntToScalar(texW) / rows; |
| 66 | const SkScalar dy = SkIntToScalar(texH) / cols; |
| 67 | for (int y = 0; y <= cols; y++) { |
| 68 | for (int x = 0; x <= rows; x++) { |
| 69 | tex->set(x*dx, y*dy); |
| 70 | tex += 1; |
| 71 | } |
| 72 | } |
| 73 | } |
| 74 | return true; |
| 75 | } |
| 76 | |
| 77 | /////////////////////////////////////////////////////////////////////////////// |
| 78 | |
| 79 | #include "SkShader.h" |
| 80 | |
| 81 | void SkMeshUtils::Draw(SkCanvas* canvas, const SkBitmap& bitmap, |
| 82 | int rows, int cols, const SkPoint verts[], |
| 83 | const SkColor colors[], const SkPaint& paint) { |
| 84 | SkMeshIndices idx; |
| 85 | |
| 86 | if (idx.init(bitmap.width(), bitmap.height(), rows, cols)) { |
| 87 | SkPaint p(paint); |
| 88 | p.setShader(SkShader::CreateBitmapShader(bitmap, |
| 89 | SkShader::kClamp_TileMode, |
| 90 | SkShader::kClamp_TileMode))->unref(); |
| 91 | canvas->drawVertices(SkCanvas::kTriangles_VertexMode, |
| 92 | rows * cols, verts, idx.tex(), colors, NULL, |
| 93 | idx.indices(), idx.indexCount(), p); |
| 94 | } |
| 95 | } |
| 96 | |