blob: cdfd1df49604e26e0c2a6b2998465be06ebf6b8b [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
reed93bb0802016-03-08 10:09:18 -080018static void transpose(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
24 for (int i = 0; i < 20; 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 }
30}
31
bsalomonf267c1e2016-02-01 13:16:14 -080032void SkColorMatrixFilterRowMajor255::initState() {
reed93bb0802016-03-08 10:09:18 -080033 transpose(fTranspose, fMatrix);
bsalomon86100022016-02-01 12:09:07 -080034
35 const float* array = fMatrix;
36
37 // check if we have to munge Alpha
38 bool changesAlpha = (array[15] || array[16] || array[17] || (array[18] - 1) || array[19]);
39 bool usesAlpha = (array[3] || array[8] || array[13]);
40
41 if (changesAlpha || usesAlpha) {
42 fFlags = changesAlpha ? 0 : kAlphaUnchanged_Flag;
43 } else {
44 fFlags = kAlphaUnchanged_Flag;
45 }
bsalomon86100022016-02-01 12:09:07 -080046}
47
48///////////////////////////////////////////////////////////////////////////////
49
50SkColorMatrixFilterRowMajor255::SkColorMatrixFilterRowMajor255(const SkScalar array[20]) {
51 memcpy(fMatrix, array, 20 * sizeof(SkScalar));
bsalomonf267c1e2016-02-01 13:16:14 -080052 this->initState();
bsalomon86100022016-02-01 12:09:07 -080053}
54
55uint32_t SkColorMatrixFilterRowMajor255::getFlags() const {
56 return this->INHERITED::getFlags() | fFlags;
57}
58
59static Sk4f scale_rgb(float scale) {
60 static_assert(SkPM4f::A == 3, "Alpha is lane 3");
61 return Sk4f(scale, scale, scale, 1);
62}
63
64static Sk4f premul(const Sk4f& x) {
mtklein7c249e52016-02-21 10:54:19 -080065 return x * scale_rgb(x[SkPM4f::A]);
bsalomon86100022016-02-01 12:09:07 -080066}
67
68static Sk4f unpremul(const Sk4f& x) {
mtklein7c249e52016-02-21 10:54:19 -080069 return x * scale_rgb(1 / x[SkPM4f::A]); // TODO: fast/approx invert?
bsalomon86100022016-02-01 12:09:07 -080070}
71
72static Sk4f clamp_0_1(const Sk4f& x) {
73 return Sk4f::Max(Sk4f::Min(x, Sk4f(1)), Sk4f(0));
74}
75
76static SkPMColor round(const Sk4f& x) {
77 SkPMColor c;
78 SkNx_cast<uint8_t>(x * Sk4f(255) + Sk4f(0.5f)).store(&c);
79 return c;
80}
81
82template <typename Adaptor, typename T>
83void filter_span(const float array[], const T src[], int count, T dst[]) {
84 // c0-c3 are already in [0,1].
85 const Sk4f c0 = Sk4f::Load(array + 0);
86 const Sk4f c1 = Sk4f::Load(array + 4);
87 const Sk4f c2 = Sk4f::Load(array + 8);
88 const Sk4f c3 = Sk4f::Load(array + 12);
89 // c4 (the translate vector) is in [0, 255]. Bring it back to [0,1].
90 const Sk4f c4 = Sk4f::Load(array + 16)*Sk4f(1.0f/255);
91
92 // todo: we could cache this in the constructor...
93 T matrix_translate_pmcolor = Adaptor::From4f(premul(clamp_0_1(c4)));
94
95 for (int i = 0; i < count; i++) {
96 Sk4f srcf = Adaptor::To4f(src[i]);
mtklein7c249e52016-02-21 10:54:19 -080097 float srcA = srcf[SkPM4f::A];
bsalomon86100022016-02-01 12:09:07 -080098
99 if (0 == srcA) {
100 dst[i] = matrix_translate_pmcolor;
101 continue;
102 }
103 if (1 != srcA) {
104 srcf = unpremul(srcf);
105 }
106
reed93bb0802016-03-08 10:09:18 -0800107 Sk4f r4 = srcf[Adaptor::R];
108 Sk4f g4 = srcf[Adaptor::G];
109 Sk4f b4 = srcf[Adaptor::B];
110 Sk4f a4 = srcf[Adaptor::A];
bsalomon86100022016-02-01 12:09:07 -0800111 // apply matrix
112 Sk4f dst4 = c0 * r4 + c1 * g4 + c2 * b4 + c3 * a4 + c4;
113
114 dst[i] = Adaptor::From4f(premul(clamp_0_1(dst4)));
115 }
116}
117
118struct SkPMColorAdaptor {
reed93bb0802016-03-08 10:09:18 -0800119 enum {
120 R = SK_R_INDEX,
121 G = SK_G_INDEX,
122 B = SK_B_INDEX,
123 A = SK_A_INDEX,
124 };
bsalomon86100022016-02-01 12:09:07 -0800125 static SkPMColor From4f(const Sk4f& c4) {
reed93bb0802016-03-08 10:09:18 -0800126 return round(swizzle_rb_if_bgra(c4));
bsalomon86100022016-02-01 12:09:07 -0800127 }
128 static Sk4f To4f(SkPMColor c) {
reed93bb0802016-03-08 10:09:18 -0800129 return to_4f(c) * Sk4f(1.0f/255);
bsalomon86100022016-02-01 12:09:07 -0800130 }
131};
132void SkColorMatrixFilterRowMajor255::filterSpan(const SkPMColor src[], int count, SkPMColor dst[]) const {
133 filter_span<SkPMColorAdaptor>(fTranspose, src, count, dst);
134}
135
136struct SkPM4fAdaptor {
reed93bb0802016-03-08 10:09:18 -0800137 enum {
138 R = SkPM4f::R,
139 G = SkPM4f::G,
140 B = SkPM4f::B,
141 A = SkPM4f::A,
142 };
bsalomon86100022016-02-01 12:09:07 -0800143 static SkPM4f From4f(const Sk4f& c4) {
reed93bb0802016-03-08 10:09:18 -0800144 return SkPM4f::From4f(c4);
bsalomon86100022016-02-01 12:09:07 -0800145 }
146 static Sk4f To4f(const SkPM4f& c) {
reed93bb0802016-03-08 10:09:18 -0800147 return c.to4f();
bsalomon86100022016-02-01 12:09:07 -0800148 }
149};
150void SkColorMatrixFilterRowMajor255::filterSpan4f(const SkPM4f src[], int count, SkPM4f dst[]) const {
151 filter_span<SkPM4fAdaptor>(fTranspose, src, count, dst);
152}
153
154///////////////////////////////////////////////////////////////////////////////
155
156void SkColorMatrixFilterRowMajor255::flatten(SkWriteBuffer& buffer) const {
157 SkASSERT(sizeof(fMatrix)/sizeof(SkScalar) == 20);
158 buffer.writeScalarArray(fMatrix, 20);
159}
160
reed60c9b582016-04-03 09:11:13 -0700161sk_sp<SkFlattenable> SkColorMatrixFilterRowMajor255::CreateProc(SkReadBuffer& buffer) {
bsalomon86100022016-02-01 12:09:07 -0800162 SkScalar matrix[20];
163 if (buffer.readScalarArray(matrix, 20)) {
reed60c9b582016-04-03 09:11:13 -0700164 return sk_make_sp<SkColorMatrixFilterRowMajor255>(matrix);
bsalomon86100022016-02-01 12:09:07 -0800165 }
166 return nullptr;
167}
168
169bool SkColorMatrixFilterRowMajor255::asColorMatrix(SkScalar matrix[20]) const {
170 if (matrix) {
171 memcpy(matrix, fMatrix, 20 * sizeof(SkScalar));
172 }
173 return true;
174}
175
176///////////////////////////////////////////////////////////////////////////////
177// This code was duplicated from src/effects/SkColorMatrixc.cpp in order to be used in core.
178//////
179
180// To detect if we need to apply clamping after applying a matrix, we check if
181// any output component might go outside of [0, 255] for any combination of
182// input components in [0..255].
183// Each output component is an affine transformation of the input component, so
184// the minimum and maximum values are for any combination of minimum or maximum
185// values of input components (i.e. 0 or 255).
186// E.g. if R' = x*R + y*G + z*B + w*A + t
187// Then the maximum value will be for R=255 if x>0 or R=0 if x<0, and the
188// minimum value will be for R=0 if x>0 or R=255 if x<0.
189// Same goes for all components.
190static bool component_needs_clamping(const SkScalar row[5]) {
191 SkScalar maxValue = row[4] / 255;
192 SkScalar minValue = row[4] / 255;
193 for (int i = 0; i < 4; ++i) {
194 if (row[i] > 0)
195 maxValue += row[i];
196 else
197 minValue += row[i];
198 }
199 return (maxValue > 1) || (minValue < 0);
200}
201
202static bool needs_clamping(const SkScalar matrix[20]) {
203 return component_needs_clamping(matrix)
204 || component_needs_clamping(matrix+5)
205 || component_needs_clamping(matrix+10)
206 || component_needs_clamping(matrix+15);
207}
208
209static void set_concat(SkScalar result[20], const SkScalar outer[20], const SkScalar inner[20]) {
210 int index = 0;
211 for (int j = 0; j < 20; j += 5) {
212 for (int i = 0; i < 4; i++) {
213 result[index++] = outer[j + 0] * inner[i + 0] +
214 outer[j + 1] * inner[i + 5] +
215 outer[j + 2] * inner[i + 10] +
216 outer[j + 3] * inner[i + 15];
217 }
218 result[index++] = outer[j + 0] * inner[4] +
219 outer[j + 1] * inner[9] +
220 outer[j + 2] * inner[14] +
221 outer[j + 3] * inner[19] +
222 outer[j + 4];
223 }
224}
225
226///////////////////////////////////////////////////////////////////////////////
227// End duplication
228//////
229
reedd053ce92016-03-22 10:17:23 -0700230sk_sp<SkColorFilter>
231SkColorMatrixFilterRowMajor255::makeComposed(sk_sp<SkColorFilter> innerFilter) const {
bsalomon86100022016-02-01 12:09:07 -0800232 SkScalar innerMatrix[20];
233 if (innerFilter->asColorMatrix(innerMatrix) && !needs_clamping(innerMatrix)) {
234 SkScalar concat[20];
235 set_concat(concat, fMatrix, innerMatrix);
reedd053ce92016-03-22 10:17:23 -0700236 return sk_make_sp<SkColorMatrixFilterRowMajor255>(concat);
bsalomon86100022016-02-01 12:09:07 -0800237 }
238 return nullptr;
239}
240
241#if SK_SUPPORT_GPU
242#include "GrFragmentProcessor.h"
243#include "GrInvariantOutput.h"
244#include "glsl/GrGLSLFragmentProcessor.h"
245#include "glsl/GrGLSLFragmentShaderBuilder.h"
246#include "glsl/GrGLSLProgramDataManager.h"
247#include "glsl/GrGLSLUniformHandler.h"
248
249class ColorMatrixEffect : public GrFragmentProcessor {
250public:
bungeman06ca8ec2016-06-09 08:01:03 -0700251 static sk_sp<GrFragmentProcessor> Make(const SkScalar matrix[20]) {
252 return sk_sp<GrFragmentProcessor>(new ColorMatrixEffect(matrix));
bsalomon86100022016-02-01 12:09:07 -0800253 }
254
255 const char* name() const override { return "Color Matrix"; }
256
257 GR_DECLARE_FRAGMENT_PROCESSOR_TEST;
258
259 class GLSLProcessor : public GrGLSLFragmentProcessor {
260 public:
261 // this class always generates the same code.
robertphillips9cdb9922016-02-03 12:25:40 -0800262 static void GenKey(const GrProcessor&, const GrGLSLCaps&, GrProcessorKeyBuilder*) {}
bsalomon86100022016-02-01 12:09:07 -0800263
robertphillips9cdb9922016-02-03 12:25:40 -0800264 void emitCode(EmitArgs& args) override {
bsalomon86100022016-02-01 12:09:07 -0800265 GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
cdalton5e58cee2016-02-11 12:49:47 -0800266 fMatrixHandle = uniformHandler->addUniform(kFragment_GrShaderFlag,
bsalomon86100022016-02-01 12:09:07 -0800267 kMat44f_GrSLType, kDefault_GrSLPrecision,
268 "ColorMatrix");
cdalton5e58cee2016-02-11 12:49:47 -0800269 fVectorHandle = uniformHandler->addUniform(kFragment_GrShaderFlag,
bsalomon86100022016-02-01 12:09:07 -0800270 kVec4f_GrSLType, kDefault_GrSLPrecision,
271 "ColorMatrixVector");
272
273 if (nullptr == args.fInputColor) {
274 // could optimize this case, but we aren't for now.
275 args.fInputColor = "vec4(1)";
276 }
277 GrGLSLFragmentBuilder* fragBuilder = args.fFragBuilder;
278 // The max() is to guard against 0 / 0 during unpremul when the incoming color is
279 // transparent black.
280 fragBuilder->codeAppendf("\tfloat nonZeroAlpha = max(%s.a, 0.00001);\n",
281 args.fInputColor);
282 fragBuilder->codeAppendf("\t%s = %s * vec4(%s.rgb / nonZeroAlpha, nonZeroAlpha) + %s;\n",
283 args.fOutputColor,
284 uniformHandler->getUniformCStr(fMatrixHandle),
285 args.fInputColor,
286 uniformHandler->getUniformCStr(fVectorHandle));
287 fragBuilder->codeAppendf("\t%s = clamp(%s, 0.0, 1.0);\n",
288 args.fOutputColor, args.fOutputColor);
289 fragBuilder->codeAppendf("\t%s.rgb *= %s.a;\n", args.fOutputColor, args.fOutputColor);
290 }
291
292 protected:
robertphillips9cdb9922016-02-03 12:25:40 -0800293 void onSetData(const GrGLSLProgramDataManager& uniManager,
294 const GrProcessor& proc) override {
bsalomon86100022016-02-01 12:09:07 -0800295 const ColorMatrixEffect& cme = proc.cast<ColorMatrixEffect>();
296 const float* m = cme.fMatrix;
297 // The GL matrix is transposed from SkColorMatrix.
298 float mt[] = {
299 m[0], m[5], m[10], m[15],
300 m[1], m[6], m[11], m[16],
301 m[2], m[7], m[12], m[17],
302 m[3], m[8], m[13], m[18],
303 };
304 static const float kScale = 1.0f / 255.0f;
305 float vec[] = {
306 m[4] * kScale, m[9] * kScale, m[14] * kScale, m[19] * kScale,
307 };
308 uniManager.setMatrix4fv(fMatrixHandle, 1, mt);
309 uniManager.set4fv(fVectorHandle, 1, vec);
310 }
311
312 private:
313 GrGLSLProgramDataManager::UniformHandle fMatrixHandle;
314 GrGLSLProgramDataManager::UniformHandle fVectorHandle;
315
316 typedef GrGLSLFragmentProcessor INHERITED;
317 };
318
319private:
320 ColorMatrixEffect(const SkScalar matrix[20]) {
321 memcpy(fMatrix, matrix, sizeof(SkScalar) * 20);
322 this->initClassID<ColorMatrixEffect>();
323 }
324
325 GrGLSLFragmentProcessor* onCreateGLSLInstance() const override {
robertphillips9cdb9922016-02-03 12:25:40 -0800326 return new GLSLProcessor;
bsalomon86100022016-02-01 12:09:07 -0800327 }
328
329 virtual void onGetGLSLProcessorKey(const GrGLSLCaps& caps,
330 GrProcessorKeyBuilder* b) const override {
331 GLSLProcessor::GenKey(*this, caps, b);
332 }
333
334 bool onIsEqual(const GrFragmentProcessor& s) const override {
335 const ColorMatrixEffect& cme = s.cast<ColorMatrixEffect>();
336 return 0 == memcmp(fMatrix, cme.fMatrix, sizeof(fMatrix));
337 }
338
339 void onComputeInvariantOutput(GrInvariantOutput* inout) const override {
340 // We only bother to check whether the alpha channel will be constant. If SkColorMatrix had
341 // type flags it might be worth checking the other components.
342
343 // The matrix is defined such the 4th row determines the output alpha. The first four
344 // columns of that row multiply the input r, g, b, and a, respectively, and the last column
345 // is the "translation".
346 static const uint32_t kRGBAFlags[] = {
347 kR_GrColorComponentFlag,
348 kG_GrColorComponentFlag,
349 kB_GrColorComponentFlag,
350 kA_GrColorComponentFlag
351 };
352 static const int kShifts[] = {
353 GrColor_SHIFT_R, GrColor_SHIFT_G, GrColor_SHIFT_B, GrColor_SHIFT_A,
354 };
355 enum {
356 kAlphaRowStartIdx = 15,
357 kAlphaRowTranslateIdx = 19,
358 };
359
360 SkScalar outputA = 0;
361 for (int i = 0; i < 4; ++i) {
362 // If any relevant component of the color to be passed through the matrix is non-const
363 // then we can't know the final result.
364 if (0 != fMatrix[kAlphaRowStartIdx + i]) {
365 if (!(inout->validFlags() & kRGBAFlags[i])) {
366 inout->setToUnknown(GrInvariantOutput::kWill_ReadInput);
367 return;
368 } else {
369 uint32_t component = (inout->color() >> kShifts[i]) & 0xFF;
370 outputA += fMatrix[kAlphaRowStartIdx + i] * component;
371 }
372 }
373 }
374 outputA += fMatrix[kAlphaRowTranslateIdx];
375 // We pin the color to [0,1]. This would happen to the *final* color output from the frag
376 // shader but currently the effect does not pin its own output. So in the case of over/
377 // underflow this may deviate from the actual result. Maybe the effect should pin its
378 // result if the matrix could over/underflow for any component?
379 inout->setToOther(kA_GrColorComponentFlag,
380 static_cast<uint8_t>(SkScalarPin(outputA, 0, 255)) << GrColor_SHIFT_A,
381 GrInvariantOutput::kWill_ReadInput);
382 }
383
384 SkScalar fMatrix[20];
385
386 typedef GrFragmentProcessor INHERITED;
387};
388
389GR_DEFINE_FRAGMENT_PROCESSOR_TEST(ColorMatrixEffect);
390
bungeman06ca8ec2016-06-09 08:01:03 -0700391sk_sp<GrFragmentProcessor> ColorMatrixEffect::TestCreate(GrProcessorTestData* d) {
bsalomon86100022016-02-01 12:09:07 -0800392 SkScalar colorMatrix[20];
393 for (size_t i = 0; i < SK_ARRAY_COUNT(colorMatrix); ++i) {
394 colorMatrix[i] = d->fRandom->nextSScalar1();
395 }
bungeman06ca8ec2016-06-09 08:01:03 -0700396 return ColorMatrixEffect::Make(colorMatrix);
bsalomon86100022016-02-01 12:09:07 -0800397}
398
bungeman06ca8ec2016-06-09 08:01:03 -0700399sk_sp<GrFragmentProcessor> SkColorMatrixFilterRowMajor255::asFragmentProcessor(GrContext*) const {
400 return ColorMatrixEffect::Make(fMatrix);
bsalomon86100022016-02-01 12:09:07 -0800401}
402
403#endif
404
405#ifndef SK_IGNORE_TO_STRING
406void SkColorMatrixFilterRowMajor255::toString(SkString* str) const {
407 str->append("SkColorMatrixFilterRowMajor255: ");
408
409 str->append("matrix: (");
410 for (int i = 0; i < 20; ++i) {
411 str->appendScalar(fMatrix[i]);
412 if (i < 19) {
413 str->append(", ");
414 }
415 }
416 str->append(")");
417}
418#endif
419
420///////////////////////////////////////////////////////////////////////////////
421
reedd053ce92016-03-22 10:17:23 -0700422sk_sp<SkColorFilter> SkColorFilter::MakeMatrixFilterRowMajor255(const SkScalar array[20]) {
423 return sk_sp<SkColorFilter>(new SkColorMatrixFilterRowMajor255(array));
bsalomon86100022016-02-01 12:09:07 -0800424}
bsalomonf267c1e2016-02-01 13:16:14 -0800425
426///////////////////////////////////////////////////////////////////////////////
427
reedd053ce92016-03-22 10:17:23 -0700428sk_sp<SkColorFilter>
429SkColorMatrixFilterRowMajor255::MakeSingleChannelOutput(const SkScalar row[5]) {
bsalomonf267c1e2016-02-01 13:16:14 -0800430 SkASSERT(row);
reedd053ce92016-03-22 10:17:23 -0700431 auto cf = sk_make_sp<SkColorMatrixFilterRowMajor255>();
bsalomonf267c1e2016-02-01 13:16:14 -0800432 static_assert(sizeof(SkScalar) * 5 * 4 == sizeof(cf->fMatrix), "sizes don't match");
433 for (int i = 0; i < 4; ++i) {
434 memcpy(cf->fMatrix + 5 * i, row, sizeof(SkScalar) * 5);
435 }
436 cf->initState();
437 return cf;
438}