blob: b9508ff2c7f3328b5ea32d0f4c06bb02fd414197 [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"
11#include "SkReadBuffer.h"
12#include "SkWriteBuffer.h"
13#include "SkUnPreMultiply.h"
14#include "SkString.h"
15
16#define SK_PMORDER_INDEX_A (SK_A32_SHIFT / 8)
17#define SK_PMORDER_INDEX_R (SK_R32_SHIFT / 8)
18#define SK_PMORDER_INDEX_G (SK_G32_SHIFT / 8)
19#define SK_PMORDER_INDEX_B (SK_B32_SHIFT / 8)
20
21static void transpose_to_pmorder(float dst[20], const float src[20]) {
22 const float* srcR = src + 0;
23 const float* srcG = src + 5;
24 const float* srcB = src + 10;
25 const float* srcA = src + 15;
26
27 for (int i = 0; i < 20; i += 4) {
28 dst[i + SK_PMORDER_INDEX_A] = *srcA++;
29 dst[i + SK_PMORDER_INDEX_R] = *srcR++;
30 dst[i + SK_PMORDER_INDEX_G] = *srcG++;
31 dst[i + SK_PMORDER_INDEX_B] = *srcB++;
32 }
33}
34
bsalomonf267c1e2016-02-01 13:16:14 -080035void SkColorMatrixFilterRowMajor255::initState() {
36 transpose_to_pmorder(fTranspose, fMatrix);
bsalomon86100022016-02-01 12:09:07 -080037
38 const float* array = fMatrix;
39
40 // check if we have to munge Alpha
41 bool changesAlpha = (array[15] || array[16] || array[17] || (array[18] - 1) || array[19]);
42 bool usesAlpha = (array[3] || array[8] || array[13]);
43
44 if (changesAlpha || usesAlpha) {
45 fFlags = changesAlpha ? 0 : kAlphaUnchanged_Flag;
46 } else {
47 fFlags = kAlphaUnchanged_Flag;
48 }
49 fFlags |= kSupports4f_Flag;
50}
51
52///////////////////////////////////////////////////////////////////////////////
53
54SkColorMatrixFilterRowMajor255::SkColorMatrixFilterRowMajor255(const SkScalar array[20]) {
55 memcpy(fMatrix, array, 20 * sizeof(SkScalar));
bsalomonf267c1e2016-02-01 13:16:14 -080056 this->initState();
bsalomon86100022016-02-01 12:09:07 -080057}
58
59uint32_t SkColorMatrixFilterRowMajor255::getFlags() const {
60 return this->INHERITED::getFlags() | fFlags;
61}
62
63static Sk4f scale_rgb(float scale) {
64 static_assert(SkPM4f::A == 3, "Alpha is lane 3");
65 return Sk4f(scale, scale, scale, 1);
66}
67
68static Sk4f premul(const Sk4f& x) {
69 return x * scale_rgb(x.kth<SkPM4f::A>());
70}
71
72static Sk4f unpremul(const Sk4f& x) {
73 return x * scale_rgb(1 / x.kth<SkPM4f::A>()); // TODO: fast/approx invert?
74}
75
76static Sk4f clamp_0_1(const Sk4f& x) {
77 return Sk4f::Max(Sk4f::Min(x, Sk4f(1)), Sk4f(0));
78}
79
80static SkPMColor round(const Sk4f& x) {
81 SkPMColor c;
82 SkNx_cast<uint8_t>(x * Sk4f(255) + Sk4f(0.5f)).store(&c);
83 return c;
84}
85
86template <typename Adaptor, typename T>
87void filter_span(const float array[], const T src[], int count, T dst[]) {
88 // c0-c3 are already in [0,1].
89 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);
93 // c4 (the translate vector) is in [0, 255]. Bring it back to [0,1].
94 const Sk4f c4 = Sk4f::Load(array + 16)*Sk4f(1.0f/255);
95
96 // todo: we could cache this in the constructor...
97 T matrix_translate_pmcolor = Adaptor::From4f(premul(clamp_0_1(c4)));
98
99 for (int i = 0; i < count; i++) {
100 Sk4f srcf = Adaptor::To4f(src[i]);
101 float srcA = srcf.kth<SkPM4f::A>();
102
103 if (0 == srcA) {
104 dst[i] = matrix_translate_pmcolor;
105 continue;
106 }
107 if (1 != srcA) {
108 srcf = unpremul(srcf);
109 }
110
111 Sk4f r4 = SkNx_dup<SK_R32_SHIFT/8>(srcf);
112 Sk4f g4 = SkNx_dup<SK_G32_SHIFT/8>(srcf);
113 Sk4f b4 = SkNx_dup<SK_B32_SHIFT/8>(srcf);
114 Sk4f a4 = SkNx_dup<SK_A32_SHIFT/8>(srcf);
115
116 // apply matrix
117 Sk4f dst4 = c0 * r4 + c1 * g4 + c2 * b4 + c3 * a4 + c4;
118
119 dst[i] = Adaptor::From4f(premul(clamp_0_1(dst4)));
120 }
121}
122
123struct SkPMColorAdaptor {
124 static SkPMColor From4f(const Sk4f& c4) {
125 return round(c4);
126 }
127 static Sk4f To4f(SkPMColor c) {
128 return SkNx_cast<float>(Sk4b::Load(&c)) * Sk4f(1.0f/255);
129 }
130};
131void SkColorMatrixFilterRowMajor255::filterSpan(const SkPMColor src[], int count, SkPMColor dst[]) const {
132 filter_span<SkPMColorAdaptor>(fTranspose, src, count, dst);
133}
134
135struct SkPM4fAdaptor {
136 static SkPM4f From4f(const Sk4f& c4) {
137 SkPM4f c;
138 c4.store(&c);
139 return c;
140 }
141 static Sk4f To4f(const SkPM4f& c) {
142 return Sk4f::Load(&c);
143 }
144};
145void SkColorMatrixFilterRowMajor255::filterSpan4f(const SkPM4f src[], int count, SkPM4f dst[]) const {
146 filter_span<SkPM4fAdaptor>(fTranspose, src, count, dst);
147}
148
149///////////////////////////////////////////////////////////////////////////////
150
151void SkColorMatrixFilterRowMajor255::flatten(SkWriteBuffer& buffer) const {
152 SkASSERT(sizeof(fMatrix)/sizeof(SkScalar) == 20);
153 buffer.writeScalarArray(fMatrix, 20);
154}
155
156SkFlattenable* SkColorMatrixFilterRowMajor255::CreateProc(SkReadBuffer& buffer) {
157 SkScalar matrix[20];
158 if (buffer.readScalarArray(matrix, 20)) {
159 return new SkColorMatrixFilterRowMajor255(matrix);
160 }
161 return nullptr;
162}
163
164bool SkColorMatrixFilterRowMajor255::asColorMatrix(SkScalar matrix[20]) const {
165 if (matrix) {
166 memcpy(matrix, fMatrix, 20 * sizeof(SkScalar));
167 }
168 return true;
169}
170
171///////////////////////////////////////////////////////////////////////////////
172// This code was duplicated from src/effects/SkColorMatrixc.cpp in order to be used in core.
173//////
174
175// To detect if we need to apply clamping after applying a matrix, we check if
176// any output component might go outside of [0, 255] for any combination of
177// input components in [0..255].
178// Each output component is an affine transformation of the input component, so
179// the minimum and maximum values are for any combination of minimum or maximum
180// values of input components (i.e. 0 or 255).
181// E.g. if R' = x*R + y*G + z*B + w*A + t
182// Then the maximum value will be for R=255 if x>0 or R=0 if x<0, and the
183// minimum value will be for R=0 if x>0 or R=255 if x<0.
184// Same goes for all components.
185static bool component_needs_clamping(const SkScalar row[5]) {
186 SkScalar maxValue = row[4] / 255;
187 SkScalar minValue = row[4] / 255;
188 for (int i = 0; i < 4; ++i) {
189 if (row[i] > 0)
190 maxValue += row[i];
191 else
192 minValue += row[i];
193 }
194 return (maxValue > 1) || (minValue < 0);
195}
196
197static bool needs_clamping(const SkScalar matrix[20]) {
198 return component_needs_clamping(matrix)
199 || component_needs_clamping(matrix+5)
200 || component_needs_clamping(matrix+10)
201 || component_needs_clamping(matrix+15);
202}
203
204static void set_concat(SkScalar result[20], const SkScalar outer[20], const SkScalar inner[20]) {
205 int index = 0;
206 for (int j = 0; j < 20; j += 5) {
207 for (int i = 0; i < 4; i++) {
208 result[index++] = outer[j + 0] * inner[i + 0] +
209 outer[j + 1] * inner[i + 5] +
210 outer[j + 2] * inner[i + 10] +
211 outer[j + 3] * inner[i + 15];
212 }
213 result[index++] = outer[j + 0] * inner[4] +
214 outer[j + 1] * inner[9] +
215 outer[j + 2] * inner[14] +
216 outer[j + 3] * inner[19] +
217 outer[j + 4];
218 }
219}
220
221///////////////////////////////////////////////////////////////////////////////
222// End duplication
223//////
224
225SkColorFilter* SkColorMatrixFilterRowMajor255::newComposed(const SkColorFilter* innerFilter) const {
226 SkScalar innerMatrix[20];
227 if (innerFilter->asColorMatrix(innerMatrix) && !needs_clamping(innerMatrix)) {
228 SkScalar concat[20];
229 set_concat(concat, fMatrix, innerMatrix);
230 return new SkColorMatrixFilterRowMajor255(concat);
231 }
232 return nullptr;
233}
234
235#if SK_SUPPORT_GPU
236#include "GrFragmentProcessor.h"
237#include "GrInvariantOutput.h"
238#include "glsl/GrGLSLFragmentProcessor.h"
239#include "glsl/GrGLSLFragmentShaderBuilder.h"
240#include "glsl/GrGLSLProgramDataManager.h"
241#include "glsl/GrGLSLUniformHandler.h"
242
243class ColorMatrixEffect : public GrFragmentProcessor {
244public:
245 static const GrFragmentProcessor* Create(const SkScalar matrix[20]) {
246 return new ColorMatrixEffect(matrix);
247 }
248
249 const char* name() const override { return "Color Matrix"; }
250
251 GR_DECLARE_FRAGMENT_PROCESSOR_TEST;
252
253 class GLSLProcessor : public GrGLSLFragmentProcessor {
254 public:
255 // this class always generates the same code.
robertphillips9cdb9922016-02-03 12:25:40 -0800256 static void GenKey(const GrProcessor&, const GrGLSLCaps&, GrProcessorKeyBuilder*) {}
bsalomon86100022016-02-01 12:09:07 -0800257
robertphillips9cdb9922016-02-03 12:25:40 -0800258 void emitCode(EmitArgs& args) override {
bsalomon86100022016-02-01 12:09:07 -0800259 GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
260 fMatrixHandle = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility,
261 kMat44f_GrSLType, kDefault_GrSLPrecision,
262 "ColorMatrix");
263 fVectorHandle = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility,
264 kVec4f_GrSLType, kDefault_GrSLPrecision,
265 "ColorMatrixVector");
266
267 if (nullptr == args.fInputColor) {
268 // could optimize this case, but we aren't for now.
269 args.fInputColor = "vec4(1)";
270 }
271 GrGLSLFragmentBuilder* fragBuilder = args.fFragBuilder;
272 // The max() is to guard against 0 / 0 during unpremul when the incoming color is
273 // transparent black.
274 fragBuilder->codeAppendf("\tfloat nonZeroAlpha = max(%s.a, 0.00001);\n",
275 args.fInputColor);
276 fragBuilder->codeAppendf("\t%s = %s * vec4(%s.rgb / nonZeroAlpha, nonZeroAlpha) + %s;\n",
277 args.fOutputColor,
278 uniformHandler->getUniformCStr(fMatrixHandle),
279 args.fInputColor,
280 uniformHandler->getUniformCStr(fVectorHandle));
281 fragBuilder->codeAppendf("\t%s = clamp(%s, 0.0, 1.0);\n",
282 args.fOutputColor, args.fOutputColor);
283 fragBuilder->codeAppendf("\t%s.rgb *= %s.a;\n", args.fOutputColor, args.fOutputColor);
284 }
285
286 protected:
robertphillips9cdb9922016-02-03 12:25:40 -0800287 void onSetData(const GrGLSLProgramDataManager& uniManager,
288 const GrProcessor& proc) override {
bsalomon86100022016-02-01 12:09:07 -0800289 const ColorMatrixEffect& cme = proc.cast<ColorMatrixEffect>();
290 const float* m = cme.fMatrix;
291 // The GL matrix is transposed from SkColorMatrix.
292 float mt[] = {
293 m[0], m[5], m[10], m[15],
294 m[1], m[6], m[11], m[16],
295 m[2], m[7], m[12], m[17],
296 m[3], m[8], m[13], m[18],
297 };
298 static const float kScale = 1.0f / 255.0f;
299 float vec[] = {
300 m[4] * kScale, m[9] * kScale, m[14] * kScale, m[19] * kScale,
301 };
302 uniManager.setMatrix4fv(fMatrixHandle, 1, mt);
303 uniManager.set4fv(fVectorHandle, 1, vec);
304 }
305
306 private:
307 GrGLSLProgramDataManager::UniformHandle fMatrixHandle;
308 GrGLSLProgramDataManager::UniformHandle fVectorHandle;
309
310 typedef GrGLSLFragmentProcessor INHERITED;
311 };
312
313private:
314 ColorMatrixEffect(const SkScalar matrix[20]) {
315 memcpy(fMatrix, matrix, sizeof(SkScalar) * 20);
316 this->initClassID<ColorMatrixEffect>();
317 }
318
319 GrGLSLFragmentProcessor* onCreateGLSLInstance() const override {
robertphillips9cdb9922016-02-03 12:25:40 -0800320 return new GLSLProcessor;
bsalomon86100022016-02-01 12:09:07 -0800321 }
322
323 virtual void onGetGLSLProcessorKey(const GrGLSLCaps& caps,
324 GrProcessorKeyBuilder* b) const override {
325 GLSLProcessor::GenKey(*this, caps, b);
326 }
327
328 bool onIsEqual(const GrFragmentProcessor& s) const override {
329 const ColorMatrixEffect& cme = s.cast<ColorMatrixEffect>();
330 return 0 == memcmp(fMatrix, cme.fMatrix, sizeof(fMatrix));
331 }
332
333 void onComputeInvariantOutput(GrInvariantOutput* inout) const override {
334 // We only bother to check whether the alpha channel will be constant. If SkColorMatrix had
335 // type flags it might be worth checking the other components.
336
337 // The matrix is defined such the 4th row determines the output alpha. The first four
338 // columns of that row multiply the input r, g, b, and a, respectively, and the last column
339 // is the "translation".
340 static const uint32_t kRGBAFlags[] = {
341 kR_GrColorComponentFlag,
342 kG_GrColorComponentFlag,
343 kB_GrColorComponentFlag,
344 kA_GrColorComponentFlag
345 };
346 static const int kShifts[] = {
347 GrColor_SHIFT_R, GrColor_SHIFT_G, GrColor_SHIFT_B, GrColor_SHIFT_A,
348 };
349 enum {
350 kAlphaRowStartIdx = 15,
351 kAlphaRowTranslateIdx = 19,
352 };
353
354 SkScalar outputA = 0;
355 for (int i = 0; i < 4; ++i) {
356 // If any relevant component of the color to be passed through the matrix is non-const
357 // then we can't know the final result.
358 if (0 != fMatrix[kAlphaRowStartIdx + i]) {
359 if (!(inout->validFlags() & kRGBAFlags[i])) {
360 inout->setToUnknown(GrInvariantOutput::kWill_ReadInput);
361 return;
362 } else {
363 uint32_t component = (inout->color() >> kShifts[i]) & 0xFF;
364 outputA += fMatrix[kAlphaRowStartIdx + i] * component;
365 }
366 }
367 }
368 outputA += fMatrix[kAlphaRowTranslateIdx];
369 // We pin the color to [0,1]. This would happen to the *final* color output from the frag
370 // shader but currently the effect does not pin its own output. So in the case of over/
371 // underflow this may deviate from the actual result. Maybe the effect should pin its
372 // result if the matrix could over/underflow for any component?
373 inout->setToOther(kA_GrColorComponentFlag,
374 static_cast<uint8_t>(SkScalarPin(outputA, 0, 255)) << GrColor_SHIFT_A,
375 GrInvariantOutput::kWill_ReadInput);
376 }
377
378 SkScalar fMatrix[20];
379
380 typedef GrFragmentProcessor INHERITED;
381};
382
383GR_DEFINE_FRAGMENT_PROCESSOR_TEST(ColorMatrixEffect);
384
385const GrFragmentProcessor* ColorMatrixEffect::TestCreate(GrProcessorTestData* d) {
386 SkScalar colorMatrix[20];
387 for (size_t i = 0; i < SK_ARRAY_COUNT(colorMatrix); ++i) {
388 colorMatrix[i] = d->fRandom->nextSScalar1();
389 }
390 return ColorMatrixEffect::Create(colorMatrix);
391}
392
393const GrFragmentProcessor* SkColorMatrixFilterRowMajor255::asFragmentProcessor(GrContext*) const {
394 return ColorMatrixEffect::Create(fMatrix);
395}
396
397#endif
398
399#ifndef SK_IGNORE_TO_STRING
400void SkColorMatrixFilterRowMajor255::toString(SkString* str) const {
401 str->append("SkColorMatrixFilterRowMajor255: ");
402
403 str->append("matrix: (");
404 for (int i = 0; i < 20; ++i) {
405 str->appendScalar(fMatrix[i]);
406 if (i < 19) {
407 str->append(", ");
408 }
409 }
410 str->append(")");
411}
412#endif
413
414///////////////////////////////////////////////////////////////////////////////
415
416SkColorFilter* SkColorFilter::CreateMatrixFilterRowMajor255(const SkScalar array[20]) {
417 return new SkColorMatrixFilterRowMajor255(array);
418}
bsalomonf267c1e2016-02-01 13:16:14 -0800419
420///////////////////////////////////////////////////////////////////////////////
421
422SkColorFilter* SkColorMatrixFilterRowMajor255::CreateSingleChannelOutput(const SkScalar row[5]) {
423 SkASSERT(row);
424 SkColorMatrixFilterRowMajor255* cf = new SkColorMatrixFilterRowMajor255();
425 static_assert(sizeof(SkScalar) * 5 * 4 == sizeof(cf->fMatrix), "sizes don't match");
426 for (int i = 0; i < 4; ++i) {
427 memcpy(cf->fMatrix + 5 * i, row, sizeof(SkScalar) * 5);
428 }
429 cf->initState();
430 return cf;
431}