2 * Copyright 2017 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #include "SkArenaAlloc.h"
9 #include "SkAutoBlitterChoose.h"
10 #include "SkColorShader.h"
13 #include "SkPM4fPriv.h"
14 #include "SkRasterClip.h"
18 #include "SkVertState.h"
20 #include "SkRasterPipeline.h"
21 #include "SkArenaAlloc.h"
22 #include "SkCoreBlitters.h"
23 #include "SkColorSpaceXform.h"
24 #include "SkColorSpace_Base.h"
27 float fMat[12]; // column major
29 Sk4f map(float x, float y) const {
30 return Sk4f::Load(&fMat[0]) * x + Sk4f::Load(&fMat[4]) * y + Sk4f::Load(&fMat[8]);
33 void setConcat(const Matrix43& a, const SkMatrix& b) {
34 fMat[ 0] = a.dot(0, b.getScaleX(), b.getSkewY());
35 fMat[ 1] = a.dot(1, b.getScaleX(), b.getSkewY());
36 fMat[ 2] = a.dot(2, b.getScaleX(), b.getSkewY());
37 fMat[ 3] = a.dot(3, b.getScaleX(), b.getSkewY());
39 fMat[ 4] = a.dot(0, b.getSkewX(), b.getScaleY());
40 fMat[ 5] = a.dot(1, b.getSkewX(), b.getScaleY());
41 fMat[ 6] = a.dot(2, b.getSkewX(), b.getScaleY());
42 fMat[ 7] = a.dot(3, b.getSkewX(), b.getScaleY());
44 fMat[ 8] = a.dot(0, b.getTranslateX(), b.getTranslateY()) + a.fMat[ 8];
45 fMat[ 9] = a.dot(1, b.getTranslateX(), b.getTranslateY()) + a.fMat[ 9];
46 fMat[10] = a.dot(2, b.getTranslateX(), b.getTranslateY()) + a.fMat[10];
47 fMat[11] = a.dot(3, b.getTranslateX(), b.getTranslateY()) + a.fMat[11];
51 float dot(int index, float x, float y) const {
52 return fMat[index + 0] * x + fMat[index + 4] * y;
56 static SkScan::HairRCProc ChooseHairProc(bool doAntiAlias) {
57 return doAntiAlias ? SkScan::AntiHairLine : SkScan::HairLine;
60 static bool texture_to_matrix(const VertState& state, const SkPoint verts[],
61 const SkPoint texs[], SkMatrix* matrix) {
62 SkPoint src[3], dst[3];
64 src[0] = texs[state.f0];
65 src[1] = texs[state.f1];
66 src[2] = texs[state.f2];
67 dst[0] = verts[state.f0];
68 dst[1] = verts[state.f1];
69 dst[2] = verts[state.f2];
70 return matrix->setPolyToPoly(src, dst, 3);
73 class SkTriColorShader : public SkShader {
77 class TriColorShaderContext : public SkShader::Context {
79 TriColorShaderContext(const SkTriColorShader& shader, const ContextRec&);
80 ~TriColorShaderContext() override;
81 void shadeSpan(int x, int y, SkPMColor dstC[], int count) override;
82 void shadeSpan4f(int x, int y, SkPM4f dstC[], int count) override;
85 bool setup(const SkPoint pts[], const SkColor colors[], int, int, int);
93 typedef SkShader::Context INHERITED;
96 struct TriColorShaderData {
98 const SkColor* colors;
99 const VertState *state;
102 SK_TO_STRING_OVERRIDE()
104 // For serialization. This will never be called.
105 Factory getFactory() const override { sk_throw(); return nullptr; }
107 // Supply setup data to context from drawing setup
108 void bindSetupData(TriColorShaderData* setupData) { fSetupData = setupData; }
110 // Take the setup data from context when needed.
111 TriColorShaderData* takeSetupData() {
112 TriColorShaderData *data = fSetupData;
118 Context* onMakeContext(const ContextRec& rec, SkArenaAlloc* alloc) const override {
119 return alloc->make<TriColorShaderContext>(*this, rec);
123 TriColorShaderData *fSetupData;
125 typedef SkShader INHERITED;
128 bool SkTriColorShader::TriColorShaderContext::setup(const SkPoint pts[], const SkColor colors[],
129 int index0, int index1, int index2) {
131 fColors[0] = SkPreMultiplyColor(colors[index0]);
132 fColors[1] = SkPreMultiplyColor(colors[index1]);
133 fColors[2] = SkPreMultiplyColor(colors[index2]);
137 m.set(0, pts[index1].fX - pts[index0].fX);
138 m.set(1, pts[index2].fX - pts[index0].fX);
139 m.set(2, pts[index0].fX);
140 m.set(3, pts[index1].fY - pts[index0].fY);
141 m.set(4, pts[index2].fY - pts[index0].fY);
142 m.set(5, pts[index0].fY);
143 if (!m.invert(&im)) {
146 // We can't call getTotalInverse(), because we explicitly don't want to look at the localmatrix
147 // as our interators are intrinsically tied to the vertices, and nothing else.
149 if (!this->getCTM().invert(&ctmInv)) {
152 // TODO replace INV(m) * INV(ctm) with INV(ctm * m)
153 fDstToUnit.setConcat(im, ctmInv);
155 Sk4f alpha(this->getPaintAlpha() * (1.0f / 255)),
156 c0 = SkPM4f::FromPMColor(fColors[0]).to4f() * alpha,
157 c1 = SkPM4f::FromPMColor(fColors[1]).to4f() * alpha,
158 c2 = SkPM4f::FromPMColor(fColors[2]).to4f() * alpha;
161 (c1 - c0).store(&colorm.fMat[0]);
162 (c2 - c0).store(&colorm.fMat[4]);
163 c0.store(&colorm.fMat[8]);
164 fM43.setConcat(colorm, fDstToUnit);
169 #include "SkColorPriv.h"
170 #include "SkComposeShader.h"
172 static int ScalarTo256(SkScalar v) {
173 return static_cast<int>(SkScalarPin(v, 0, 1) * 256 + 0.5);
176 SkTriColorShader::SkTriColorShader()
178 , fSetupData(NULL) {}
180 SkTriColorShader::TriColorShaderContext::TriColorShaderContext(const SkTriColorShader& shader,
181 const ContextRec& rec)
182 : INHERITED(shader, rec)
185 SkTriColorShader::TriColorShaderContext::~TriColorShaderContext() {}
187 void SkTriColorShader::TriColorShaderContext::shadeSpan(int x, int y, SkPMColor dstC[], int count) {
188 SkTriColorShader* parent = static_cast<SkTriColorShader*>(const_cast<SkShader*>(&fShader));
189 TriColorShaderData* set = parent->takeSetupData();
191 fSetup = setup(set->pts, set->colors, set->state->f0, set->state->f1, set->state->f2);
195 // Invalid matrices. Not checked before so no need to assert.
199 const int alphaScale = Sk255To256(this->getPaintAlpha());
203 fDstToUnit.mapXY(SkIntToScalar(x) + 0.5, SkIntToScalar(y) + 0.5, &src);
204 for (int i = 0; i < count; i++) {
205 int scale1 = ScalarTo256(src.fX);
206 int scale2 = ScalarTo256(src.fY);
207 int scale0 = 256 - scale1 - scale2;
209 if (scale1 > scale2) {
210 scale2 = 256 - scale1;
212 scale1 = 256 - scale2;
217 if (256 != alphaScale) {
218 scale0 = SkAlphaMul(scale0, alphaScale);
219 scale1 = SkAlphaMul(scale1, alphaScale);
220 scale2 = SkAlphaMul(scale2, alphaScale);
223 dstC[i] = SkAlphaMulQ(fColors[0], scale0) +
224 SkAlphaMulQ(fColors[1], scale1) +
225 SkAlphaMulQ(fColors[2], scale2);
227 src.fX += fDstToUnit.getScaleX();
228 src.fY += fDstToUnit.getSkewY();
232 void SkTriColorShader::TriColorShaderContext::shadeSpan4f(int x, int y, SkPM4f dstC[], int count) {
233 SkTriColorShader* parent = static_cast<SkTriColorShader*>(const_cast<SkShader*>(&fShader));
234 TriColorShaderData* set = parent->takeSetupData();
236 fSetup = setup(set->pts, set->colors, set->state->f0, set->state->f1, set->state->f2);
240 // Invalid matrices. Not checked before so no need to assert.
244 Sk4f c = fM43.map(SkIntToScalar(x) + 0.5, SkIntToScalar(y) + 0.5),
245 dc = Sk4f::Load(&fM43.fMat[0]),
249 for (int i = 0; i < count; i++) {
250 // We don't expect to be wildly out of 0...1, but we pin just because of minor
251 // numerical imprecision.
252 Sk4f::Min(Sk4f::Max(c, zero), Sk4f::Min(c[3], one)).store(dstC + i);
257 #ifndef SK_IGNORE_TO_STRING
258 void SkTriColorShader::toString(SkString* str) const {
259 str->append("SkTriColorShader: (");
261 this->INHERITED::toString(str);
270 // Similar to SkLocalMatrixShader, but composes the local matrix with the CTM (instead
271 // of composing with the inherited local matrix):
273 // rec' = {rec.ctm x localMatrix, rec.localMatrix}
275 // (as opposed to rec' = {rec.ctm, rec.localMatrix x localMatrix})
277 class SkLocalInnerMatrixShader final : public SkShader {
279 SkLocalInnerMatrixShader(sk_sp<SkShader> proxy, const SkMatrix& localMatrix)
280 : INHERITED(&localMatrix)
281 , fProxyShader(std::move(proxy)) {}
283 Factory getFactory() const override {
289 void flatten(SkWriteBuffer&) const override {
293 Context* onMakeContext(const ContextRec& rec, SkArenaAlloc* alloc) const override {
294 SkMatrix adjustedCTM = SkMatrix::Concat(*rec.fMatrix, this->getLocalMatrix());
295 ContextRec newRec(rec);
296 newRec.fMatrix = &adjustedCTM;
297 return fProxyShader->makeContext(newRec, alloc);
300 bool onAppendStages(SkRasterPipeline* p, SkColorSpace* cs, SkArenaAlloc* alloc,
301 const SkMatrix& ctm, const SkPaint& paint,
302 const SkMatrix* localM) const override {
303 // We control the shader graph ancestors, so we know there's no local matrix being
304 // injected before this.
307 SkMatrix adjustedCTM = SkMatrix::Concat(ctm, this->getLocalMatrix());
308 return fProxyShader->appendStages(p, cs, alloc, adjustedCTM, paint);
312 sk_sp<SkShader> fProxyShader;
314 typedef SkShader INHERITED;
317 sk_sp<SkShader> MakeTextureShader(const VertState& state, const SkPoint verts[],
318 const SkPoint texs[], const SkPaint& paint,
319 SkColorSpace* dstColorSpace,
320 SkArenaAlloc* alloc) {
321 SkASSERT(paint.getShader());
323 const auto& p0 = texs[state.f0],
327 if (p0 != p1 || p0 != p2) {
328 // Common case (non-collapsed texture coordinates).
329 // Map the texture to vertices using a local transform.
331 // We cannot use a plain SkLocalMatrix shader, because we need the texture matrix
332 // to compose next to the CTM.
333 SkMatrix localMatrix;
334 return texture_to_matrix(state, verts, texs, &localMatrix)
335 ? alloc->makeSkSp<SkLocalInnerMatrixShader>(paint.refShader(), localMatrix)
339 // Collapsed texture coordinates special case.
340 // The texture is a solid color, sampled at the given point.
341 SkMatrix shaderInvLocalMatrix;
342 SkAssertResult(paint.getShader()->getLocalMatrix().invert(&shaderInvLocalMatrix));
344 const auto sample = SkPoint::Make(0.5f, 0.5f);
345 const auto mappedSample = shaderInvLocalMatrix.mapXY(sample.x(), sample.y()),
346 mappedPoint = shaderInvLocalMatrix.mapXY(p0.x(), p0.y());
347 const auto localMatrix = SkMatrix::MakeTrans(mappedSample.x() - mappedPoint.x(),
348 mappedSample.y() - mappedPoint.y());
350 SkShader::ContextRec rec(paint, SkMatrix::I(), &localMatrix,
351 SkShader::ContextRec::kPMColor_DstType, dstColorSpace);
352 auto* ctx = paint.getShader()->makeContext(rec, alloc);
358 ctx->shadeSpan(SkScalarFloorToInt(sample.x()), SkScalarFloorToInt(sample.y()), &pmColor, 1);
360 // no need to keep this temp context around.
363 return alloc->makeSkSp<SkColorShader>(SkUnPreMultiply::PMColorToColor(pmColor));
367 static bool update_tricolor_matrix(const SkMatrix& ctmInv,
368 const SkPoint pts[], const SkPM4f colors[],
369 int index0, int index1, int index2, Matrix43* result) {
372 m.set(0, pts[index1].fX - pts[index0].fX);
373 m.set(1, pts[index2].fX - pts[index0].fX);
374 m.set(2, pts[index0].fX);
375 m.set(3, pts[index1].fY - pts[index0].fY);
376 m.set(4, pts[index2].fY - pts[index0].fY);
377 m.set(5, pts[index0].fY);
378 if (!m.invert(&im)) {
383 dstToUnit.setConcat(im, ctmInv);
385 Sk4f c0 = colors[index0].to4f(),
386 c1 = colors[index1].to4f(),
387 c2 = colors[index2].to4f();
390 (c1 - c0).store(&colorm.fMat[0]);
391 (c2 - c0).store(&colorm.fMat[4]);
392 c0.store(&colorm.fMat[8]);
393 result->setConcat(colorm, dstToUnit);
397 static SkPM4f* convert_colors(const SkColor src[], int count, SkColorSpace* deviceCS,
398 SkArenaAlloc* alloc) {
399 SkPM4f* dst = alloc->makeArray<SkPM4f>(count);
401 for (int i = 0; i < count; ++i) {
402 dst[i] = SkPM4f_from_SkColor(src[i], nullptr);
405 auto srcCS = SkColorSpace::MakeSRGB();
406 auto dstCS = as_CSB(deviceCS)->makeLinearGamma();
407 SkColorSpaceXform::Apply(dstCS.get(), SkColorSpaceXform::kRGBA_F32_ColorFormat, dst,
408 srcCS.get(), SkColorSpaceXform::kBGRA_8888_ColorFormat, src,
409 count, SkColorSpaceXform::kPremul_AlphaOp);
414 static bool compute_is_opaque(const SkColor colors[], int count) {
416 for (int i = 0; i < count; ++i) {
419 return SkColorGetA(c) == 0xFF;
422 void SkDraw::drawVertices(SkVertices::VertexMode vmode, int count,
423 const SkPoint vertices[], const SkPoint textures[],
424 const SkColor colors[], SkBlendMode bmode,
425 const uint16_t indices[], int indexCount,
426 const SkPaint& paint) const {
427 SkASSERT(0 == count || vertices);
429 // abort early if there is nothing to draw
430 if (count < 3 || (indices && indexCount < 3) || fRC->isEmpty()) {
434 if (!fMatrix->invert(&ctmInv)) {
438 // transform out vertices into device coordinates
439 SkAutoSTMalloc<16, SkPoint> storage(count);
440 SkPoint* devVerts = storage.get();
441 fMatrix->mapPoints(devVerts, vertices, count);
444 We can draw the vertices in 1 of 4 ways:
446 - solid color (no shader/texture[], no colors[])
447 - just colors (no shader/texture[], has colors[])
448 - just texture (has shader/texture[], no colors[])
449 - colors * texture (has shader/texture[], has colors[])
451 Thus for texture drawing, we need both texture[] and a shader.
454 if (colors && !textures) {
455 char arenaStorage[4096];
456 SkArenaAlloc alloc(arenaStorage, sizeof(storage));
458 SkRasterPipeline shaderPipeline(&alloc);
460 // Convert the SkColors into float colors. The conversion depends on some conditions:
461 // - If the pixmap has a dst colorspace, we have to be "color-correct".
462 // Do we map into dst-colorspace before or after we interpolate?
463 // - We have to decide when to apply per-color alpha (before or after we interpolate)
465 // For now, we will take a simple approach, but recognize this is just a start:
466 // - convert colors into dst colorspace before interpolation (matches gradients)
467 // - apply per-color alpha before interpolation (matches old version of vertices)
469 SkPM4f* dstColors = convert_colors(colors, count, fDst.colorSpace(), &alloc);
472 if (paint.getAlpha() == 0xff) {
473 is_opaque = compute_is_opaque(colors, count);
476 Sk4f alpha = paint.getAlpha() * (1/255.0f);
477 for (int i = 0; i < count; i++) {
478 (dstColors[i].to4f() * alpha).store(dstColors + i);
482 shaderPipeline.append(SkRasterPipeline::matrix_4x3, &matrix43);
483 // In theory we should never need to clamp. However, either due to imprecision in our
484 // matrix43, or the scan converter passing us pixel centers that in fact are not within
485 // the triangle, we do see occasional (slightly) out-of-range values, so we add these
486 // clamp stages. It would be nice to find a way to detect when these are not needed.
487 shaderPipeline.append(SkRasterPipeline::clamp_0);
488 shaderPipeline.append(SkRasterPipeline::clamp_a);
490 bool wants_dither = paint.isDither();
491 auto blitter = SkCreateRasterPipelineBlitter(fDst, paint, shaderPipeline,
492 is_opaque, wants_dither, &alloc);
493 SkASSERT(!blitter->isNullBlitter());
495 // setup our state and function pointer for iterating triangles
496 VertState state(count, indices, indexCount);
497 VertState::Proc vertProc = state.chooseProc(vmode);
499 while (vertProc(&state)) {
501 devVerts[state.f0], devVerts[state.f1], devVerts[state.f2]
503 if (update_tricolor_matrix(ctmInv, vertices, dstColors, state.f0, state.f1, state.f2,
505 SkScan::FillTriangle(tmp, *fRC, blitter);
511 auto triShader = sk_make_sp<SkTriColorShader>();
514 SkShader* shader = p.getShader();
515 if (nullptr == shader) {
516 // if we have no shader, we ignore the texture coordinates
518 } else if (nullptr == textures) {
519 // if we don't have texture coordinates, ignore the shader
520 p.setShader(nullptr);
524 // setup the custom shader (if needed)
526 if (nullptr == textures) {
527 // just colors (no texture)
528 p.setShader(triShader);
532 p.setShader(SkShader::MakeComposeShader(triShader, sk_ref_sp(shader), bmode));
536 SkAutoBlitterChoose blitter(fDst, *fMatrix, p);
537 // Abort early if we failed to create a shader context.
538 if (blitter->isNullBlitter()) {
542 // setup our state and function pointer for iterating triangles
543 VertState state(count, indices, indexCount);
544 VertState::Proc vertProc = state.chooseProc(vmode);
546 if (textures || colors) {
547 SkTriColorShader::TriColorShaderData verticesSetup = { vertices, colors, &state };
549 while (vertProc(&state)) {
550 auto* blitterPtr = blitter.get();
552 // We're going to allocate at most
554 // * one SkLocalMatrixShader OR one SkColorShader
555 // * one SkComposeShader
556 // * one SkAutoBlitterChoose
558 static constexpr size_t kAllocSize =
559 sizeof(SkAutoBlitterChoose) + sizeof(SkComposeShader) +
560 SkTMax(sizeof(SkLocalInnerMatrixShader), sizeof(SkColorShader));
561 char allocBuffer[kAllocSize];
562 SkArenaAlloc alloc(allocBuffer);
565 sk_sp<SkShader> texShader = MakeTextureShader(state, vertices, textures, paint,
566 fDst.colorSpace(), &alloc);
568 SkPaint localPaint(p);
569 localPaint.setShader(colors
570 ? alloc.makeSkSp<SkComposeShader>(triShader, std::move(texShader), bmode)
571 : std::move(texShader));
573 blitterPtr = alloc.make<SkAutoBlitterChoose>(fDst, *fMatrix, localPaint)->get();
574 if (blitterPtr->isNullBlitter()) {
580 triShader->bindSetupData(&verticesSetup);
584 devVerts[state.f0], devVerts[state.f1], devVerts[state.f2]
586 SkScan::FillTriangle(tmp, *fRC, blitterPtr);
587 triShader->bindSetupData(nullptr);
590 // no colors[] and no texture, stroke hairlines with paint's color.
591 SkScan::HairRCProc hairProc = ChooseHairProc(paint.isAntiAlias());
592 const SkRasterClip& clip = *fRC;
593 while (vertProc(&state)) {
595 devVerts[state.f0], devVerts[state.f1], devVerts[state.f2], devVerts[state.f0]
597 hairProc(array, 4, clip, blitter.get());