1 /*
2 * Copyright 2012 The Android Open Source Project
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 "SkBitmap.h"
9 #include "SkMagnifierImageFilter.h"
10 #include "SkColorPriv.h"
11 #include "SkReadBuffer.h"
12 #include "SkWriteBuffer.h"
13 #include "SkValidationUtils.h"
14
15 ////////////////////////////////////////////////////////////////////////////////
16 #if SK_SUPPORT_GPU
17 #include "GrInvariantOutput.h"
18 #include "effects/GrSingleTextureEffect.h"
19 #include "gl/GrGLProcessor.h"
20 #include "gl/GrGLSL.h"
21 #include "gl/GrGLTexture.h"
22 #include "gl/builders/GrGLProgramBuilder.h"
23
24 class GrMagnifierEffect : public GrSingleTextureEffect {
25
26 public:
Create(GrTexture * texture,const SkRect & bounds,float xOffset,float yOffset,float xInvZoom,float yInvZoom,float xInvInset,float yInvInset)27 static GrFragmentProcessor* Create(GrTexture* texture,
28 const SkRect& bounds,
29 float xOffset,
30 float yOffset,
31 float xInvZoom,
32 float yInvZoom,
33 float xInvInset,
34 float yInvInset) {
35 return SkNEW_ARGS(GrMagnifierEffect, (texture,
36 bounds,
37 xOffset,
38 yOffset,
39 xInvZoom,
40 yInvZoom,
41 xInvInset,
42 yInvInset));
43 }
44
~GrMagnifierEffect()45 virtual ~GrMagnifierEffect() {};
46
name() const47 const char* name() const override { return "Magnifier"; }
48
49 void getGLProcessorKey(const GrGLSLCaps&, GrProcessorKeyBuilder*) const override;
50
51 GrGLFragmentProcessor* createGLInstance() const override;
52
bounds() const53 const SkRect& bounds() const { return fBounds; } // Bounds of source image.
54 // Offset to apply to zoomed pixels, (srcRect position / texture size).
x_offset() const55 float x_offset() const { return fXOffset; }
y_offset() const56 float y_offset() const { return fYOffset; }
57
58 // Scale to apply to zoomed pixels (srcRect size / bounds size).
x_inv_zoom() const59 float x_inv_zoom() const { return fXInvZoom; }
y_inv_zoom() const60 float y_inv_zoom() const { return fYInvZoom; }
61
62 // 1/radius over which to transition from unzoomed to zoomed pixels (bounds size / inset).
x_inv_inset() const63 float x_inv_inset() const { return fXInvInset; }
y_inv_inset() const64 float y_inv_inset() const { return fYInvInset; }
65
66 private:
GrMagnifierEffect(GrTexture * texture,const SkRect & bounds,float xOffset,float yOffset,float xInvZoom,float yInvZoom,float xInvInset,float yInvInset)67 GrMagnifierEffect(GrTexture* texture,
68 const SkRect& bounds,
69 float xOffset,
70 float yOffset,
71 float xInvZoom,
72 float yInvZoom,
73 float xInvInset,
74 float yInvInset)
75 : GrSingleTextureEffect(texture, GrCoordTransform::MakeDivByTextureWHMatrix(texture))
76 , fBounds(bounds)
77 , fXOffset(xOffset)
78 , fYOffset(yOffset)
79 , fXInvZoom(xInvZoom)
80 , fYInvZoom(yInvZoom)
81 , fXInvInset(xInvInset)
82 , fYInvInset(yInvInset) {
83 this->initClassID<GrMagnifierEffect>();
84 }
85
86 bool onIsEqual(const GrFragmentProcessor&) const override;
87
88 void onComputeInvariantOutput(GrInvariantOutput* inout) const override;
89
90 GR_DECLARE_FRAGMENT_PROCESSOR_TEST;
91
92 SkRect fBounds;
93 float fXOffset;
94 float fYOffset;
95 float fXInvZoom;
96 float fYInvZoom;
97 float fXInvInset;
98 float fYInvInset;
99
100 typedef GrSingleTextureEffect INHERITED;
101 };
102
103 // For brevity
104 typedef GrGLProgramDataManager::UniformHandle UniformHandle;
105
106 class GrGLMagnifierEffect : public GrGLFragmentProcessor {
107 public:
108 GrGLMagnifierEffect(const GrProcessor&);
109
110 virtual void emitCode(GrGLFPBuilder*,
111 const GrFragmentProcessor&,
112 const char* outputColor,
113 const char* inputColor,
114 const TransformedCoordsArray&,
115 const TextureSamplerArray&) override;
116
117 void setData(const GrGLProgramDataManager&, const GrProcessor&) override;
118
119 private:
120 UniformHandle fOffsetVar;
121 UniformHandle fInvZoomVar;
122 UniformHandle fInvInsetVar;
123 UniformHandle fBoundsVar;
124
125 typedef GrGLFragmentProcessor INHERITED;
126 };
127
GrGLMagnifierEffect(const GrProcessor &)128 GrGLMagnifierEffect::GrGLMagnifierEffect(const GrProcessor&) {
129 }
130
emitCode(GrGLFPBuilder * builder,const GrFragmentProcessor &,const char * outputColor,const char * inputColor,const TransformedCoordsArray & coords,const TextureSamplerArray & samplers)131 void GrGLMagnifierEffect::emitCode(GrGLFPBuilder* builder,
132 const GrFragmentProcessor&,
133 const char* outputColor,
134 const char* inputColor,
135 const TransformedCoordsArray& coords,
136 const TextureSamplerArray& samplers) {
137 fOffsetVar = builder->addUniform(
138 GrGLProgramBuilder::kFragment_Visibility |
139 GrGLProgramBuilder::kVertex_Visibility,
140 kVec2f_GrSLType, kDefault_GrSLPrecision, "Offset");
141 fInvZoomVar = builder->addUniform(
142 GrGLProgramBuilder::kFragment_Visibility |
143 GrGLProgramBuilder::kVertex_Visibility,
144 kVec2f_GrSLType, kDefault_GrSLPrecision, "InvZoom");
145 fInvInsetVar = builder->addUniform(
146 GrGLProgramBuilder::kFragment_Visibility |
147 GrGLProgramBuilder::kVertex_Visibility,
148 kVec2f_GrSLType, kDefault_GrSLPrecision, "InvInset");
149 fBoundsVar = builder->addUniform(
150 GrGLProgramBuilder::kFragment_Visibility |
151 GrGLProgramBuilder::kVertex_Visibility,
152 kVec4f_GrSLType, kDefault_GrSLPrecision, "Bounds");
153
154 GrGLFragmentBuilder* fsBuilder = builder->getFragmentShaderBuilder();
155 SkString coords2D = fsBuilder->ensureFSCoords2D(coords, 0);
156 fsBuilder->codeAppendf("\t\tvec2 coord = %s;\n", coords2D.c_str());
157 fsBuilder->codeAppendf("\t\tvec2 zoom_coord = %s + %s * %s;\n",
158 builder->getUniformCStr(fOffsetVar),
159 coords2D.c_str(),
160 builder->getUniformCStr(fInvZoomVar));
161 const char* bounds = builder->getUniformCStr(fBoundsVar);
162 fsBuilder->codeAppendf("\t\tvec2 delta = (coord - %s.xy) * %s.zw;\n", bounds, bounds);
163 fsBuilder->codeAppendf("\t\tdelta = min(delta, vec2(1.0, 1.0) - delta);\n");
164 fsBuilder->codeAppendf("\t\tdelta = delta * %s;\n", builder->getUniformCStr(fInvInsetVar));
165
166 fsBuilder->codeAppend("\t\tfloat weight = 0.0;\n");
167 fsBuilder->codeAppend("\t\tif (delta.s < 2.0 && delta.t < 2.0) {\n");
168 fsBuilder->codeAppend("\t\t\tdelta = vec2(2.0, 2.0) - delta;\n");
169 fsBuilder->codeAppend("\t\t\tfloat dist = length(delta);\n");
170 fsBuilder->codeAppend("\t\t\tdist = max(2.0 - dist, 0.0);\n");
171 fsBuilder->codeAppend("\t\t\tweight = min(dist * dist, 1.0);\n");
172 fsBuilder->codeAppend("\t\t} else {\n");
173 fsBuilder->codeAppend("\t\t\tvec2 delta_squared = delta * delta;\n");
174 fsBuilder->codeAppend("\t\t\tweight = min(min(delta_squared.x, delta_squared.y), 1.0);\n");
175 fsBuilder->codeAppend("\t\t}\n");
176
177 fsBuilder->codeAppend("\t\tvec2 mix_coord = mix(coord, zoom_coord, weight);\n");
178 fsBuilder->codeAppend("\t\tvec4 output_color = ");
179 fsBuilder->appendTextureLookup(samplers[0], "mix_coord");
180 fsBuilder->codeAppend(";\n");
181
182 fsBuilder->codeAppendf("\t\t%s = output_color;", outputColor);
183 SkString modulate;
184 GrGLSLMulVarBy4f(&modulate, outputColor, inputColor);
185 fsBuilder->codeAppend(modulate.c_str());
186 }
187
setData(const GrGLProgramDataManager & pdman,const GrProcessor & effect)188 void GrGLMagnifierEffect::setData(const GrGLProgramDataManager& pdman,
189 const GrProcessor& effect) {
190 const GrMagnifierEffect& zoom = effect.cast<GrMagnifierEffect>();
191 pdman.set2f(fOffsetVar, zoom.x_offset(), zoom.y_offset());
192 pdman.set2f(fInvZoomVar, zoom.x_inv_zoom(), zoom.y_inv_zoom());
193 pdman.set2f(fInvInsetVar, zoom.x_inv_inset(), zoom.y_inv_inset());
194 pdman.set4f(fBoundsVar, zoom.bounds().x(), zoom.bounds().y(),
195 zoom.bounds().width(), zoom.bounds().height());
196 }
197
198 /////////////////////////////////////////////////////////////////////
199
getGLProcessorKey(const GrGLSLCaps & caps,GrProcessorKeyBuilder * b) const200 void GrMagnifierEffect::getGLProcessorKey(const GrGLSLCaps& caps,
201 GrProcessorKeyBuilder* b) const {
202 GrGLMagnifierEffect::GenKey(*this, caps, b);
203 }
204
createGLInstance() const205 GrGLFragmentProcessor* GrMagnifierEffect::createGLInstance() const {
206 return SkNEW_ARGS(GrGLMagnifierEffect, (*this));
207 }
208
209 GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrMagnifierEffect);
210
TestCreate(SkRandom * random,GrContext * context,const GrDrawTargetCaps &,GrTexture ** textures)211 GrFragmentProcessor* GrMagnifierEffect::TestCreate(SkRandom* random,
212 GrContext* context,
213 const GrDrawTargetCaps&,
214 GrTexture** textures) {
215 GrTexture* texture = textures[0];
216 const int kMaxWidth = 200;
217 const int kMaxHeight = 200;
218 const int kMaxInset = 20;
219 uint32_t width = random->nextULessThan(kMaxWidth);
220 uint32_t height = random->nextULessThan(kMaxHeight);
221 uint32_t x = random->nextULessThan(kMaxWidth - width);
222 uint32_t y = random->nextULessThan(kMaxHeight - height);
223 uint32_t inset = random->nextULessThan(kMaxInset);
224
225 GrFragmentProcessor* effect = GrMagnifierEffect::Create(
226 texture,
227 SkRect::MakeWH(SkIntToScalar(kMaxWidth), SkIntToScalar(kMaxHeight)),
228 (float) width / texture->width(),
229 (float) height / texture->height(),
230 texture->width() / (float) x,
231 texture->height() / (float) y,
232 (float) inset / texture->width(),
233 (float) inset / texture->height());
234 SkASSERT(effect);
235 return effect;
236 }
237
238 ///////////////////////////////////////////////////////////////////////////////
239
onIsEqual(const GrFragmentProcessor & sBase) const240 bool GrMagnifierEffect::onIsEqual(const GrFragmentProcessor& sBase) const {
241 const GrMagnifierEffect& s = sBase.cast<GrMagnifierEffect>();
242 return (this->fBounds == s.fBounds &&
243 this->fXOffset == s.fXOffset &&
244 this->fYOffset == s.fYOffset &&
245 this->fXInvZoom == s.fXInvZoom &&
246 this->fYInvZoom == s.fYInvZoom &&
247 this->fXInvInset == s.fXInvInset &&
248 this->fYInvInset == s.fYInvInset);
249 }
250
onComputeInvariantOutput(GrInvariantOutput * inout) const251 void GrMagnifierEffect::onComputeInvariantOutput(GrInvariantOutput* inout) const {
252 this->updateInvariantOutputForModulation(inout);
253 }
254
255 #endif
256
257 ////////////////////////////////////////////////////////////////////////////////
258
Create(const SkRect & srcRect,SkScalar inset,SkImageFilter * input)259 SkImageFilter* SkMagnifierImageFilter::Create(const SkRect& srcRect, SkScalar inset,
260 SkImageFilter* input) {
261
262 if (!SkScalarIsFinite(inset) || !SkIsValidRect(srcRect)) {
263 return NULL;
264 }
265 // Negative numbers in src rect are not supported
266 if (srcRect.fLeft < 0 || srcRect.fTop < 0) {
267 return NULL;
268 }
269 return SkNEW_ARGS(SkMagnifierImageFilter, (srcRect, inset, input));
270 }
271
272
SkMagnifierImageFilter(const SkRect & srcRect,SkScalar inset,SkImageFilter * input)273 SkMagnifierImageFilter::SkMagnifierImageFilter(const SkRect& srcRect, SkScalar inset,
274 SkImageFilter* input)
275 : INHERITED(1, &input), fSrcRect(srcRect), fInset(inset) {
276 SkASSERT(srcRect.x() >= 0 && srcRect.y() >= 0 && inset >= 0);
277 }
278
279 #if SK_SUPPORT_GPU
asFragmentProcessor(GrFragmentProcessor ** fp,GrTexture * texture,const SkMatrix &,const SkIRect & bounds) const280 bool SkMagnifierImageFilter::asFragmentProcessor(GrFragmentProcessor** fp, GrTexture* texture,
281 const SkMatrix&, const SkIRect&bounds) const {
282 if (fp) {
283 SkScalar yOffset = texture->origin() == kTopLeft_GrSurfaceOrigin ? fSrcRect.y() :
284 texture->height() - fSrcRect.height() * texture->height() / bounds.height()
285 - fSrcRect.y();
286 int boundsY = (texture->origin() == kTopLeft_GrSurfaceOrigin) ? bounds.y() :
287 (texture->height() - bounds.height());
288 SkRect effectBounds = SkRect::MakeXYWH(
289 SkIntToScalar(bounds.x()) / texture->width(),
290 SkIntToScalar(boundsY) / texture->height(),
291 SkIntToScalar(texture->width()) / bounds.width(),
292 SkIntToScalar(texture->height()) / bounds.height());
293 SkScalar invInset = fInset > 0 ? SkScalarInvert(fInset) : SK_Scalar1;
294 *fp = GrMagnifierEffect::Create(texture,
295 effectBounds,
296 fSrcRect.x() / texture->width(),
297 yOffset / texture->height(),
298 fSrcRect.width() / bounds.width(),
299 fSrcRect.height() / bounds.height(),
300 bounds.width() * invInset,
301 bounds.height() * invInset);
302 }
303 return true;
304 }
305 #endif
306
CreateProc(SkReadBuffer & buffer)307 SkFlattenable* SkMagnifierImageFilter::CreateProc(SkReadBuffer& buffer) {
308 SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 1);
309 SkRect src;
310 buffer.readRect(&src);
311 return Create(src, buffer.readScalar(), common.getInput(0));
312 }
313
flatten(SkWriteBuffer & buffer) const314 void SkMagnifierImageFilter::flatten(SkWriteBuffer& buffer) const {
315 this->INHERITED::flatten(buffer);
316 buffer.writeRect(fSrcRect);
317 buffer.writeScalar(fInset);
318 }
319
onFilterImage(Proxy *,const SkBitmap & src,const Context &,SkBitmap * dst,SkIPoint * offset) const320 bool SkMagnifierImageFilter::onFilterImage(Proxy*, const SkBitmap& src,
321 const Context&, SkBitmap* dst,
322 SkIPoint* offset) const {
323 if ((src.colorType() != kN32_SkColorType) ||
324 (fSrcRect.width() >= src.width()) ||
325 (fSrcRect.height() >= src.height())) {
326 return false;
327 }
328
329 SkAutoLockPixels alp(src);
330 SkASSERT(src.getPixels());
331 if (!src.getPixels() || src.width() <= 0 || src.height() <= 0) {
332 return false;
333 }
334
335 if (!dst->tryAllocPixels(src.info())) {
336 return false;
337 }
338
339 SkScalar inv_inset = fInset > 0 ? SkScalarInvert(fInset) : SK_Scalar1;
340
341 SkScalar inv_x_zoom = fSrcRect.width() / src.width();
342 SkScalar inv_y_zoom = fSrcRect.height() / src.height();
343
344 SkColor* sptr = src.getAddr32(0, 0);
345 SkColor* dptr = dst->getAddr32(0, 0);
346 int width = src.width(), height = src.height();
347 for (int y = 0; y < height; ++y) {
348 for (int x = 0; x < width; ++x) {
349 SkScalar x_dist = SkMin32(x, width - x - 1) * inv_inset;
350 SkScalar y_dist = SkMin32(y, height - y - 1) * inv_inset;
351 SkScalar weight = 0;
352
353 static const SkScalar kScalar2 = SkScalar(2);
354
355 // To create a smooth curve at the corners, we need to work on
356 // a square twice the size of the inset.
357 if (x_dist < kScalar2 && y_dist < kScalar2) {
358 x_dist = kScalar2 - x_dist;
359 y_dist = kScalar2 - y_dist;
360
361 SkScalar dist = SkScalarSqrt(SkScalarSquare(x_dist) +
362 SkScalarSquare(y_dist));
363 dist = SkMaxScalar(kScalar2 - dist, 0);
364 weight = SkMinScalar(SkScalarSquare(dist), SK_Scalar1);
365 } else {
366 SkScalar sqDist = SkMinScalar(SkScalarSquare(x_dist),
367 SkScalarSquare(y_dist));
368 weight = SkMinScalar(sqDist, SK_Scalar1);
369 }
370
371 SkScalar x_interp = SkScalarMul(weight, (fSrcRect.x() + x * inv_x_zoom)) +
372 (SK_Scalar1 - weight) * x;
373 SkScalar y_interp = SkScalarMul(weight, (fSrcRect.y() + y * inv_y_zoom)) +
374 (SK_Scalar1 - weight) * y;
375
376 int x_val = SkPin32(SkScalarFloorToInt(x_interp), 0, width - 1);
377 int y_val = SkPin32(SkScalarFloorToInt(y_interp), 0, height - 1);
378
379 *dptr = sptr[y_val * width + x_val];
380 dptr++;
381 }
382 }
383 return true;
384 }
385
386 #ifndef SK_IGNORE_TO_STRING
toString(SkString * str) const387 void SkMagnifierImageFilter::toString(SkString* str) const {
388 str->appendf("SkMagnifierImageFilter: (");
389 str->appendf("src: (%f,%f,%f,%f) ",
390 fSrcRect.fLeft, fSrcRect.fTop, fSrcRect.fRight, fSrcRect.fBottom);
391 str->appendf("inset: %f", fInset);
392 str->append(")");
393 }
394 #endif
395