blob: 0fcd36a02b13ae16e0d71830df33682a255dc7e8 [file] [log] [blame]
bsalomon86100022016-02-01 12:09:07 -08001/*
2 * Copyright 2011 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "SkColorMatrixFilterRowMajor255.h"
9#include "SkColorPriv.h"
10#include "SkNx.h"
reed93bb0802016-03-08 10:09:18 -080011#include "SkPM4fPriv.h"
bungeman06ca8ec2016-06-09 08:01:03 -070012#include "SkReadBuffer.h"
13#include "SkRefCnt.h"
14#include "SkString.h"
15#include "SkUnPreMultiply.h"
16#include "SkWriteBuffer.h"
bsalomon86100022016-02-01 12:09:07 -080017
Mike Klein1ec0dbe2016-11-03 09:47:18 -040018static void transpose_and_scale01(float dst[20], const float src[20]) {
bsalomon86100022016-02-01 12:09:07 -080019 const float* srcR = src + 0;
20 const float* srcG = src + 5;
21 const float* srcB = src + 10;
22 const float* srcA = src + 15;
23
Mike Klein1ec0dbe2016-11-03 09:47:18 -040024 for (int i = 0; i < 16; i += 4) {
reed93bb0802016-03-08 10:09:18 -080025 dst[i + 0] = *srcR++;
26 dst[i + 1] = *srcG++;
27 dst[i + 2] = *srcB++;
28 dst[i + 3] = *srcA++;
bsalomon86100022016-02-01 12:09:07 -080029 }
Mike Klein1ec0dbe2016-11-03 09:47:18 -040030 // Might as well scale these translates down to [0,1] here instead of every filter call.
31 dst[16] = *srcR * (1/255.0f);
32 dst[17] = *srcG * (1/255.0f);
33 dst[18] = *srcB * (1/255.0f);
34 dst[19] = *srcA * (1/255.0f);
bsalomon86100022016-02-01 12:09:07 -080035}
36
bsalomonf267c1e2016-02-01 13:16:14 -080037void SkColorMatrixFilterRowMajor255::initState() {
Mike Klein1ec0dbe2016-11-03 09:47:18 -040038 transpose_and_scale01(fTranspose, fMatrix);
bsalomon86100022016-02-01 12:09:07 -080039
40 const float* array = fMatrix;
41
42 // check if we have to munge Alpha
43 bool changesAlpha = (array[15] || array[16] || array[17] || (array[18] - 1) || array[19]);
44 bool usesAlpha = (array[3] || array[8] || array[13]);
45
46 if (changesAlpha || usesAlpha) {
47 fFlags = changesAlpha ? 0 : kAlphaUnchanged_Flag;
48 } else {
49 fFlags = kAlphaUnchanged_Flag;
50 }
bsalomon86100022016-02-01 12:09:07 -080051}
52
53///////////////////////////////////////////////////////////////////////////////
54
55SkColorMatrixFilterRowMajor255::SkColorMatrixFilterRowMajor255(const SkScalar array[20]) {
56 memcpy(fMatrix, array, 20 * sizeof(SkScalar));
bsalomonf267c1e2016-02-01 13:16:14 -080057 this->initState();
bsalomon86100022016-02-01 12:09:07 -080058}
59
60uint32_t SkColorMatrixFilterRowMajor255::getFlags() const {
61 return this->INHERITED::getFlags() | fFlags;
62}
63
64static Sk4f scale_rgb(float scale) {
65 static_assert(SkPM4f::A == 3, "Alpha is lane 3");
66 return Sk4f(scale, scale, scale, 1);
67}
68
69static Sk4f premul(const Sk4f& x) {
mtklein7c249e52016-02-21 10:54:19 -080070 return x * scale_rgb(x[SkPM4f::A]);
bsalomon86100022016-02-01 12:09:07 -080071}
72
73static Sk4f unpremul(const Sk4f& x) {
mtklein7c249e52016-02-21 10:54:19 -080074 return x * scale_rgb(1 / x[SkPM4f::A]); // TODO: fast/approx invert?
bsalomon86100022016-02-01 12:09:07 -080075}
76
77static Sk4f clamp_0_1(const Sk4f& x) {
78 return Sk4f::Max(Sk4f::Min(x, Sk4f(1)), Sk4f(0));
79}
80
81static SkPMColor round(const Sk4f& x) {
82 SkPMColor c;
83 SkNx_cast<uint8_t>(x * Sk4f(255) + Sk4f(0.5f)).store(&c);
84 return c;
85}
86
87template <typename Adaptor, typename T>
88void filter_span(const float array[], const T src[], int count, T dst[]) {
bsalomon86100022016-02-01 12:09:07 -080089 const Sk4f c0 = Sk4f::Load(array + 0);
90 const Sk4f c1 = Sk4f::Load(array + 4);
91 const Sk4f c2 = Sk4f::Load(array + 8);
92 const Sk4f c3 = Sk4f::Load(array + 12);
Mike Klein1ec0dbe2016-11-03 09:47:18 -040093 const Sk4f c4 = Sk4f::Load(array + 16);
bsalomon86100022016-02-01 12:09:07 -080094
95 // todo: we could cache this in the constructor...
96 T matrix_translate_pmcolor = Adaptor::From4f(premul(clamp_0_1(c4)));
97
98 for (int i = 0; i < count; i++) {
99 Sk4f srcf = Adaptor::To4f(src[i]);
mtklein7c249e52016-02-21 10:54:19 -0800100 float srcA = srcf[SkPM4f::A];
bsalomon86100022016-02-01 12:09:07 -0800101
102 if (0 == srcA) {
103 dst[i] = matrix_translate_pmcolor;
104 continue;
105 }
106 if (1 != srcA) {
107 srcf = unpremul(srcf);
108 }
109
reed93bb0802016-03-08 10:09:18 -0800110 Sk4f r4 = srcf[Adaptor::R];
111 Sk4f g4 = srcf[Adaptor::G];
112 Sk4f b4 = srcf[Adaptor::B];
113 Sk4f a4 = srcf[Adaptor::A];
bsalomon86100022016-02-01 12:09:07 -0800114 // apply matrix
115 Sk4f dst4 = c0 * r4 + c1 * g4 + c2 * b4 + c3 * a4 + c4;
116
117 dst[i] = Adaptor::From4f(premul(clamp_0_1(dst4)));
118 }
119}
120
121struct SkPMColorAdaptor {
reed93bb0802016-03-08 10:09:18 -0800122 enum {
123 R = SK_R_INDEX,
124 G = SK_G_INDEX,
125 B = SK_B_INDEX,
126 A = SK_A_INDEX,
127 };
bsalomon86100022016-02-01 12:09:07 -0800128 static SkPMColor From4f(const Sk4f& c4) {
reed93bb0802016-03-08 10:09:18 -0800129 return round(swizzle_rb_if_bgra(c4));
bsalomon86100022016-02-01 12:09:07 -0800130 }
131 static Sk4f To4f(SkPMColor c) {
mtklein0c902472016-07-20 18:10:07 -0700132 return Sk4f_fromL32(c);
bsalomon86100022016-02-01 12:09:07 -0800133 }
134};
135void SkColorMatrixFilterRowMajor255::filterSpan(const SkPMColor src[], int count, SkPMColor dst[]) const {
136 filter_span<SkPMColorAdaptor>(fTranspose, src, count, dst);
137}
138
139struct SkPM4fAdaptor {
reed93bb0802016-03-08 10:09:18 -0800140 enum {
141 R = SkPM4f::R,
142 G = SkPM4f::G,
143 B = SkPM4f::B,
144 A = SkPM4f::A,
145 };
bsalomon86100022016-02-01 12:09:07 -0800146 static SkPM4f From4f(const Sk4f& c4) {
reed93bb0802016-03-08 10:09:18 -0800147 return SkPM4f::From4f(c4);
bsalomon86100022016-02-01 12:09:07 -0800148 }
149 static Sk4f To4f(const SkPM4f& c) {
reed93bb0802016-03-08 10:09:18 -0800150 return c.to4f();
bsalomon86100022016-02-01 12:09:07 -0800151 }
152};
153void SkColorMatrixFilterRowMajor255::filterSpan4f(const SkPM4f src[], int count, SkPM4f dst[]) const {
154 filter_span<SkPM4fAdaptor>(fTranspose, src, count, dst);
155}
156
157///////////////////////////////////////////////////////////////////////////////
158
159void SkColorMatrixFilterRowMajor255::flatten(SkWriteBuffer& buffer) const {
160 SkASSERT(sizeof(fMatrix)/sizeof(SkScalar) == 20);
161 buffer.writeScalarArray(fMatrix, 20);
162}
163
reed60c9b582016-04-03 09:11:13 -0700164sk_sp<SkFlattenable> SkColorMatrixFilterRowMajor255::CreateProc(SkReadBuffer& buffer) {
bsalomon86100022016-02-01 12:09:07 -0800165 SkScalar matrix[20];
166 if (buffer.readScalarArray(matrix, 20)) {
reed60c9b582016-04-03 09:11:13 -0700167 return sk_make_sp<SkColorMatrixFilterRowMajor255>(matrix);
bsalomon86100022016-02-01 12:09:07 -0800168 }
169 return nullptr;
170}
171
172bool SkColorMatrixFilterRowMajor255::asColorMatrix(SkScalar matrix[20]) const {
173 if (matrix) {
174 memcpy(matrix, fMatrix, 20 * sizeof(SkScalar));
175 }
176 return true;
177}
178
179///////////////////////////////////////////////////////////////////////////////
180// This code was duplicated from src/effects/SkColorMatrixc.cpp in order to be used in core.
181//////
182
183// To detect if we need to apply clamping after applying a matrix, we check if
184// any output component might go outside of [0, 255] for any combination of
185// input components in [0..255].
186// Each output component is an affine transformation of the input component, so
187// the minimum and maximum values are for any combination of minimum or maximum
188// values of input components (i.e. 0 or 255).
189// E.g. if R' = x*R + y*G + z*B + w*A + t
190// Then the maximum value will be for R=255 if x>0 or R=0 if x<0, and the
191// minimum value will be for R=0 if x>0 or R=255 if x<0.
192// Same goes for all components.
193static bool component_needs_clamping(const SkScalar row[5]) {
194 SkScalar maxValue = row[4] / 255;
195 SkScalar minValue = row[4] / 255;
196 for (int i = 0; i < 4; ++i) {
197 if (row[i] > 0)
198 maxValue += row[i];
199 else
200 minValue += row[i];
201 }
202 return (maxValue > 1) || (minValue < 0);
203}
204
205static bool needs_clamping(const SkScalar matrix[20]) {
206 return component_needs_clamping(matrix)
207 || component_needs_clamping(matrix+5)
208 || component_needs_clamping(matrix+10)
209 || component_needs_clamping(matrix+15);
210}
211
212static void set_concat(SkScalar result[20], const SkScalar outer[20], const SkScalar inner[20]) {
213 int index = 0;
214 for (int j = 0; j < 20; j += 5) {
215 for (int i = 0; i < 4; i++) {
216 result[index++] = outer[j + 0] * inner[i + 0] +
217 outer[j + 1] * inner[i + 5] +
218 outer[j + 2] * inner[i + 10] +
219 outer[j + 3] * inner[i + 15];
220 }
221 result[index++] = outer[j + 0] * inner[4] +
222 outer[j + 1] * inner[9] +
223 outer[j + 2] * inner[14] +
224 outer[j + 3] * inner[19] +
225 outer[j + 4];
226 }
227}
228
229///////////////////////////////////////////////////////////////////////////////
230// End duplication
231//////
232
reedd053ce92016-03-22 10:17:23 -0700233sk_sp<SkColorFilter>
234SkColorMatrixFilterRowMajor255::makeComposed(sk_sp<SkColorFilter> innerFilter) const {
bsalomon86100022016-02-01 12:09:07 -0800235 SkScalar innerMatrix[20];
236 if (innerFilter->asColorMatrix(innerMatrix) && !needs_clamping(innerMatrix)) {
237 SkScalar concat[20];
238 set_concat(concat, fMatrix, innerMatrix);
reedd053ce92016-03-22 10:17:23 -0700239 return sk_make_sp<SkColorMatrixFilterRowMajor255>(concat);
bsalomon86100022016-02-01 12:09:07 -0800240 }
241 return nullptr;
242}
243
244#if SK_SUPPORT_GPU
245#include "GrFragmentProcessor.h"
246#include "GrInvariantOutput.h"
247#include "glsl/GrGLSLFragmentProcessor.h"
248#include "glsl/GrGLSLFragmentShaderBuilder.h"
249#include "glsl/GrGLSLProgramDataManager.h"
250#include "glsl/GrGLSLUniformHandler.h"
251
252class ColorMatrixEffect : public GrFragmentProcessor {
253public:
bungeman06ca8ec2016-06-09 08:01:03 -0700254 static sk_sp<GrFragmentProcessor> Make(const SkScalar matrix[20]) {
255 return sk_sp<GrFragmentProcessor>(new ColorMatrixEffect(matrix));
bsalomon86100022016-02-01 12:09:07 -0800256 }
257
258 const char* name() const override { return "Color Matrix"; }
259
260 GR_DECLARE_FRAGMENT_PROCESSOR_TEST;
261
262 class GLSLProcessor : public GrGLSLFragmentProcessor {
263 public:
264 // this class always generates the same code.
robertphillips9cdb9922016-02-03 12:25:40 -0800265 static void GenKey(const GrProcessor&, const GrGLSLCaps&, GrProcessorKeyBuilder*) {}
bsalomon86100022016-02-01 12:09:07 -0800266
robertphillips9cdb9922016-02-03 12:25:40 -0800267 void emitCode(EmitArgs& args) override {
bsalomon86100022016-02-01 12:09:07 -0800268 GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
cdalton5e58cee2016-02-11 12:49:47 -0800269 fMatrixHandle = uniformHandler->addUniform(kFragment_GrShaderFlag,
bsalomon86100022016-02-01 12:09:07 -0800270 kMat44f_GrSLType, kDefault_GrSLPrecision,
271 "ColorMatrix");
cdalton5e58cee2016-02-11 12:49:47 -0800272 fVectorHandle = uniformHandler->addUniform(kFragment_GrShaderFlag,
bsalomon86100022016-02-01 12:09:07 -0800273 kVec4f_GrSLType, kDefault_GrSLPrecision,
274 "ColorMatrixVector");
275
276 if (nullptr == args.fInputColor) {
277 // could optimize this case, but we aren't for now.
278 args.fInputColor = "vec4(1)";
279 }
280 GrGLSLFragmentBuilder* fragBuilder = args.fFragBuilder;
281 // The max() is to guard against 0 / 0 during unpremul when the incoming color is
282 // transparent black.
283 fragBuilder->codeAppendf("\tfloat nonZeroAlpha = max(%s.a, 0.00001);\n",
284 args.fInputColor);
285 fragBuilder->codeAppendf("\t%s = %s * vec4(%s.rgb / nonZeroAlpha, nonZeroAlpha) + %s;\n",
286 args.fOutputColor,
287 uniformHandler->getUniformCStr(fMatrixHandle),
288 args.fInputColor,
289 uniformHandler->getUniformCStr(fVectorHandle));
290 fragBuilder->codeAppendf("\t%s = clamp(%s, 0.0, 1.0);\n",
291 args.fOutputColor, args.fOutputColor);
292 fragBuilder->codeAppendf("\t%s.rgb *= %s.a;\n", args.fOutputColor, args.fOutputColor);
293 }
294
295 protected:
robertphillips9cdb9922016-02-03 12:25:40 -0800296 void onSetData(const GrGLSLProgramDataManager& uniManager,
297 const GrProcessor& proc) override {
bsalomon86100022016-02-01 12:09:07 -0800298 const ColorMatrixEffect& cme = proc.cast<ColorMatrixEffect>();
299 const float* m = cme.fMatrix;
300 // The GL matrix is transposed from SkColorMatrix.
301 float mt[] = {
302 m[0], m[5], m[10], m[15],
303 m[1], m[6], m[11], m[16],
304 m[2], m[7], m[12], m[17],
305 m[3], m[8], m[13], m[18],
306 };
307 static const float kScale = 1.0f / 255.0f;
308 float vec[] = {
309 m[4] * kScale, m[9] * kScale, m[14] * kScale, m[19] * kScale,
310 };
311 uniManager.setMatrix4fv(fMatrixHandle, 1, mt);
312 uniManager.set4fv(fVectorHandle, 1, vec);
313 }
314
315 private:
316 GrGLSLProgramDataManager::UniformHandle fMatrixHandle;
317 GrGLSLProgramDataManager::UniformHandle fVectorHandle;
318
319 typedef GrGLSLFragmentProcessor INHERITED;
320 };
321
322private:
323 ColorMatrixEffect(const SkScalar matrix[20]) {
324 memcpy(fMatrix, matrix, sizeof(SkScalar) * 20);
325 this->initClassID<ColorMatrixEffect>();
326 }
327
328 GrGLSLFragmentProcessor* onCreateGLSLInstance() const override {
robertphillips9cdb9922016-02-03 12:25:40 -0800329 return new GLSLProcessor;
bsalomon86100022016-02-01 12:09:07 -0800330 }
331
332 virtual void onGetGLSLProcessorKey(const GrGLSLCaps& caps,
333 GrProcessorKeyBuilder* b) const override {
334 GLSLProcessor::GenKey(*this, caps, b);
335 }
336
337 bool onIsEqual(const GrFragmentProcessor& s) const override {
338 const ColorMatrixEffect& cme = s.cast<ColorMatrixEffect>();
339 return 0 == memcmp(fMatrix, cme.fMatrix, sizeof(fMatrix));
340 }
341
342 void onComputeInvariantOutput(GrInvariantOutput* inout) const override {
343 // We only bother to check whether the alpha channel will be constant. If SkColorMatrix had
344 // type flags it might be worth checking the other components.
345
346 // The matrix is defined such the 4th row determines the output alpha. The first four
347 // columns of that row multiply the input r, g, b, and a, respectively, and the last column
348 // is the "translation".
349 static const uint32_t kRGBAFlags[] = {
350 kR_GrColorComponentFlag,
351 kG_GrColorComponentFlag,
352 kB_GrColorComponentFlag,
353 kA_GrColorComponentFlag
354 };
355 static const int kShifts[] = {
356 GrColor_SHIFT_R, GrColor_SHIFT_G, GrColor_SHIFT_B, GrColor_SHIFT_A,
357 };
358 enum {
359 kAlphaRowStartIdx = 15,
360 kAlphaRowTranslateIdx = 19,
361 };
362
363 SkScalar outputA = 0;
364 for (int i = 0; i < 4; ++i) {
365 // If any relevant component of the color to be passed through the matrix is non-const
366 // then we can't know the final result.
367 if (0 != fMatrix[kAlphaRowStartIdx + i]) {
368 if (!(inout->validFlags() & kRGBAFlags[i])) {
369 inout->setToUnknown(GrInvariantOutput::kWill_ReadInput);
370 return;
371 } else {
372 uint32_t component = (inout->color() >> kShifts[i]) & 0xFF;
373 outputA += fMatrix[kAlphaRowStartIdx + i] * component;
374 }
375 }
376 }
377 outputA += fMatrix[kAlphaRowTranslateIdx];
378 // We pin the color to [0,1]. This would happen to the *final* color output from the frag
379 // shader but currently the effect does not pin its own output. So in the case of over/
380 // underflow this may deviate from the actual result. Maybe the effect should pin its
381 // result if the matrix could over/underflow for any component?
382 inout->setToOther(kA_GrColorComponentFlag,
383 static_cast<uint8_t>(SkScalarPin(outputA, 0, 255)) << GrColor_SHIFT_A,
384 GrInvariantOutput::kWill_ReadInput);
385 }
386
387 SkScalar fMatrix[20];
388
389 typedef GrFragmentProcessor INHERITED;
390};
391
392GR_DEFINE_FRAGMENT_PROCESSOR_TEST(ColorMatrixEffect);
393
bungeman06ca8ec2016-06-09 08:01:03 -0700394sk_sp<GrFragmentProcessor> ColorMatrixEffect::TestCreate(GrProcessorTestData* d) {
bsalomon86100022016-02-01 12:09:07 -0800395 SkScalar colorMatrix[20];
396 for (size_t i = 0; i < SK_ARRAY_COUNT(colorMatrix); ++i) {
397 colorMatrix[i] = d->fRandom->nextSScalar1();
398 }
bungeman06ca8ec2016-06-09 08:01:03 -0700399 return ColorMatrixEffect::Make(colorMatrix);
bsalomon86100022016-02-01 12:09:07 -0800400}
401
Brian Osman618d3042016-10-25 10:51:28 -0400402sk_sp<GrFragmentProcessor> SkColorMatrixFilterRowMajor255::asFragmentProcessor(
403 GrContext*, SkColorSpace*) const {
bungeman06ca8ec2016-06-09 08:01:03 -0700404 return ColorMatrixEffect::Make(fMatrix);
bsalomon86100022016-02-01 12:09:07 -0800405}
406
407#endif
408
409#ifndef SK_IGNORE_TO_STRING
410void SkColorMatrixFilterRowMajor255::toString(SkString* str) const {
411 str->append("SkColorMatrixFilterRowMajor255: ");
412
413 str->append("matrix: (");
414 for (int i = 0; i < 20; ++i) {
415 str->appendScalar(fMatrix[i]);
416 if (i < 19) {
417 str->append(", ");
418 }
419 }
420 str->append(")");
421}
422#endif
423
424///////////////////////////////////////////////////////////////////////////////
425
reedd053ce92016-03-22 10:17:23 -0700426sk_sp<SkColorFilter> SkColorFilter::MakeMatrixFilterRowMajor255(const SkScalar array[20]) {
427 return sk_sp<SkColorFilter>(new SkColorMatrixFilterRowMajor255(array));
bsalomon86100022016-02-01 12:09:07 -0800428}
bsalomonf267c1e2016-02-01 13:16:14 -0800429
430///////////////////////////////////////////////////////////////////////////////
431
reedd053ce92016-03-22 10:17:23 -0700432sk_sp<SkColorFilter>
433SkColorMatrixFilterRowMajor255::MakeSingleChannelOutput(const SkScalar row[5]) {
bsalomonf267c1e2016-02-01 13:16:14 -0800434 SkASSERT(row);
reedd053ce92016-03-22 10:17:23 -0700435 auto cf = sk_make_sp<SkColorMatrixFilterRowMajor255>();
bsalomonf267c1e2016-02-01 13:16:14 -0800436 static_assert(sizeof(SkScalar) * 5 * 4 == sizeof(cf->fMatrix), "sizes don't match");
437 for (int i = 0; i < 4; ++i) {
438 memcpy(cf->fMatrix + 5 * i, row, sizeof(SkScalar) * 5);
439 }
440 cf->initState();
441 return cf;
442}