blob: fa0587fc5001465dda81c2e1c99dba68dd41b2ca [file] [log] [blame]
epoger@google.comec3ed6a2011-07-28 14:26:00 +00001
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00002/*
epoger@google.comec3ed6a2011-07-28 14:26:00 +00003 * Copyright 2011 Google Inc.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00004 *
epoger@google.comec3ed6a2011-07-28 14:26:00 +00005 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00007 */
8
epoger@google.comec3ed6a2011-07-28 14:26:00 +00009
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000010#include "SkPDFShader.h"
11
12#include "SkCanvas.h"
vandebo@chromium.org421d6442011-07-20 17:39:01 +000013#include "SkData.h"
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000014#include "SkPDFCatalog.h"
15#include "SkPDFDevice.h"
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +000016#include "SkPDFFormXObject.h"
17#include "SkPDFGraphicState.h"
commit-bot@chromium.org47401352013-07-23 21:49:29 +000018#include "SkPDFResourceDict.h"
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000019#include "SkPDFUtils.h"
20#include "SkScalar.h"
21#include "SkStream.h"
twiz@google.com316338a2011-03-09 23:14:04 +000022#include "SkTemplates.h"
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000023#include "SkThread.h"
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +000024#include "SkTSet.h"
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000025#include "SkTypes.h"
26
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +000027static bool inverseTransformBBox(const SkMatrix& matrix, SkRect* bbox) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000028 SkMatrix inverse;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +000029 if (!matrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +000030 return false;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +000031 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000032 inverse.mapRect(bbox);
vandebo@chromium.org386dfc02012-04-17 22:31:52 +000033 return true;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000034}
35
36static void unitToPointsMatrix(const SkPoint pts[2], SkMatrix* matrix) {
37 SkVector vec = pts[1] - pts[0];
38 SkScalar mag = vec.length();
39 SkScalar inv = mag ? SkScalarInvert(mag) : 0;
40
41 vec.scale(inv);
42 matrix->setSinCos(vec.fY, vec.fX);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000043 matrix->preScale(mag, mag);
commit-bot@chromium.orgace22692013-06-12 21:33:02 +000044 matrix->postTranslate(pts[0].fX, pts[0].fY);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000045}
46
47/* Assumes t + startOffset is on the stack and does a linear interpolation on t
48 between startOffset and endOffset from prevColor to curColor (for each color
djsollen@google.com53648ab2013-04-03 12:34:16 +000049 component), leaving the result in component order on the stack. It assumes
50 there are always 3 components per color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000051 @param range endOffset - startOffset
52 @param curColor[components] The current color components.
53 @param prevColor[components] The previous color components.
54 @param result The result ps function.
55 */
56static void interpolateColorCode(SkScalar range, SkScalar* curColor,
djsollen@google.com53648ab2013-04-03 12:34:16 +000057 SkScalar* prevColor, SkString* result) {
58 static const int kColorComponents = 3;
59
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000060 // Figure out how to scale each color component.
djsollen@google.com53648ab2013-04-03 12:34:16 +000061 SkScalar multiplier[kColorComponents];
62 for (int i = 0; i < kColorComponents; i++) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000063 multiplier[i] = SkScalarDiv(curColor[i] - prevColor[i], range);
64 }
65
66 // Calculate when we no longer need to keep a copy of the input parameter t.
67 // If the last component to use t is i, then dupInput[0..i - 1] = true
68 // and dupInput[i .. components] = false.
djsollen@google.com53648ab2013-04-03 12:34:16 +000069 bool dupInput[kColorComponents];
70 dupInput[kColorComponents - 1] = false;
71 for (int i = kColorComponents - 2; i >= 0; i--) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000072 dupInput[i] = dupInput[i + 1] || multiplier[i + 1] != 0;
73 }
74
75 if (!dupInput[0] && multiplier[0] == 0) {
76 result->append("pop ");
77 }
78
djsollen@google.com53648ab2013-04-03 12:34:16 +000079 for (int i = 0; i < kColorComponents; i++) {
vandebo@chromium.orgb8622042012-10-22 20:12:40 +000080 // If the next components needs t and this component will consume a
81 // copy, make another copy.
82 if (dupInput[i] && multiplier[i] != 0) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000083 result->append("dup ");
84 }
85
86 if (multiplier[i] == 0) {
87 result->appendScalar(prevColor[i]);
88 result->append(" ");
89 } else {
90 if (multiplier[i] != 1) {
91 result->appendScalar(multiplier[i]);
92 result->append(" mul ");
93 }
94 if (prevColor[i] != 0) {
95 result->appendScalar(prevColor[i]);
96 result->append(" add ");
97 }
98 }
99
100 if (dupInput[i]) {
101 result->append("exch\n");
102 }
103 }
104}
105
106/* Generate Type 4 function code to map t=[0,1) to the passed gradient,
107 clamping at the edges of the range. The generated code will be of the form:
108 if (t < 0) {
109 return colorData[0][r,g,b];
110 } else {
111 if (t < info.fColorOffsets[1]) {
112 return linearinterpolation(colorData[0][r,g,b],
113 colorData[1][r,g,b]);
114 } else {
115 if (t < info.fColorOffsets[2]) {
116 return linearinterpolation(colorData[1][r,g,b],
117 colorData[2][r,g,b]);
118 } else {
119
120 ... } else {
121 return colorData[info.fColorCount - 1][r,g,b];
122 }
123 ...
124 }
125 }
126 */
127static void gradientFunctionCode(const SkShader::GradientInfo& info,
128 SkString* result) {
129 /* We want to linearly interpolate from the previous color to the next.
130 Scale the colors from 0..255 to 0..1 and determine the multipliers
131 for interpolation.
132 C{r,g,b}(t, section) = t - offset_(section-1) + t * Multiplier{r,g,b}.
133 */
134 static const int kColorComponents = 3;
twiz@google.com316338a2011-03-09 23:14:04 +0000135 typedef SkScalar ColorTuple[kColorComponents];
136 SkAutoSTMalloc<4, ColorTuple> colorDataAlloc(info.fColorCount);
137 ColorTuple *colorData = colorDataAlloc.get();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000138 const SkScalar scale = SkScalarInvert(SkIntToScalar(255));
139 for (int i = 0; i < info.fColorCount; i++) {
140 colorData[i][0] = SkScalarMul(SkColorGetR(info.fColors[i]), scale);
141 colorData[i][1] = SkScalarMul(SkColorGetG(info.fColors[i]), scale);
142 colorData[i][2] = SkScalarMul(SkColorGetB(info.fColors[i]), scale);
143 }
144
145 // Clamp the initial color.
146 result->append("dup 0 le {pop ");
147 result->appendScalar(colorData[0][0]);
148 result->append(" ");
149 result->appendScalar(colorData[0][1]);
150 result->append(" ");
151 result->appendScalar(colorData[0][2]);
152 result->append(" }\n");
153
154 // The gradient colors.
155 for (int i = 1 ; i < info.fColorCount; i++) {
156 result->append("{dup ");
157 result->appendScalar(info.fColorOffsets[i]);
158 result->append(" le {");
159 if (info.fColorOffsets[i - 1] != 0) {
160 result->appendScalar(info.fColorOffsets[i - 1]);
161 result->append(" sub\n");
162 }
163
164 interpolateColorCode(info.fColorOffsets[i] - info.fColorOffsets[i - 1],
djsollen@google.com53648ab2013-04-03 12:34:16 +0000165 colorData[i], colorData[i - 1], result);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000166 result->append("}\n");
167 }
168
169 // Clamp the final color.
170 result->append("{pop ");
171 result->appendScalar(colorData[info.fColorCount - 1][0]);
172 result->append(" ");
173 result->appendScalar(colorData[info.fColorCount - 1][1]);
174 result->append(" ");
175 result->appendScalar(colorData[info.fColorCount - 1][2]);
176
177 for (int i = 0 ; i < info.fColorCount; i++) {
178 result->append("} ifelse\n");
179 }
180}
181
182/* Map a value of t on the stack into [0, 1) for Repeat or Mirror tile mode. */
183static void tileModeCode(SkShader::TileMode mode, SkString* result) {
184 if (mode == SkShader::kRepeat_TileMode) {
185 result->append("dup truncate sub\n"); // Get the fractional part.
186 result->append("dup 0 le {1 add} if\n"); // Map (-1,0) => (0,1)
187 return;
188 }
189
190 if (mode == SkShader::kMirror_TileMode) {
191 // Map t mod 2 into [0, 1, 1, 0].
192 // Code Stack
193 result->append("abs " // Map negative to positive.
194 "dup " // t.s t.s
195 "truncate " // t.s t
196 "dup " // t.s t t
197 "cvi " // t.s t T
198 "2 mod " // t.s t (i mod 2)
199 "1 eq " // t.s t true|false
200 "3 1 roll " // true|false t.s t
201 "sub " // true|false 0.s
202 "exch " // 0.s true|false
203 "{1 exch sub} if\n"); // 1 - 0.s|0.s
204 }
205}
206
207static SkString linearCode(const SkShader::GradientInfo& info) {
ctguil@chromium.orga5c72342011-08-15 23:55:03 +0000208 SkString function("{pop\n"); // Just ditch the y value.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000209 tileModeCode(info.fTileMode, &function);
210 gradientFunctionCode(info, &function);
211 function.append("}");
212 return function;
213}
214
215static SkString radialCode(const SkShader::GradientInfo& info) {
216 SkString function("{");
217 // Find the distance from the origin.
218 function.append("dup " // x y y
219 "mul " // x y^2
220 "exch " // y^2 x
221 "dup " // y^2 x x
222 "mul " // y^2 x^2
223 "add " // y^2+x^2
224 "sqrt\n"); // sqrt(y^2+x^2)
225
226 tileModeCode(info.fTileMode, &function);
227 gradientFunctionCode(info, &function);
228 function.append("}");
229 return function;
230}
231
232/* The math here is all based on the description in Two_Point_Radial_Gradient,
233 with one simplification, the coordinate space has been scaled so that
234 Dr = 1. This means we don't need to scale the entire equation by 1/Dr^2.
235 */
236static SkString twoPointRadialCode(const SkShader::GradientInfo& info) {
237 SkScalar dx = info.fPoint[0].fX - info.fPoint[1].fX;
238 SkScalar dy = info.fPoint[0].fY - info.fPoint[1].fY;
239 SkScalar sr = info.fRadius[0];
240 SkScalar a = SkScalarMul(dx, dx) + SkScalarMul(dy, dy) - SK_Scalar1;
241 bool posRoot = info.fRadius[1] > info.fRadius[0];
242
243 // We start with a stack of (x y), copy it and then consume one copy in
244 // order to calculate b and the other to calculate c.
245 SkString function("{");
246 function.append("2 copy ");
247
248 // Calculate -b and b^2.
249 function.appendScalar(dy);
250 function.append(" mul exch ");
251 function.appendScalar(dx);
252 function.append(" mul add ");
253 function.appendScalar(sr);
254 function.append(" sub 2 mul neg dup dup mul\n");
255
256 // Calculate c
257 function.append("4 2 roll dup mul exch dup mul add ");
258 function.appendScalar(SkScalarMul(sr, sr));
259 function.append(" sub\n");
260
261 // Calculate the determinate
262 function.appendScalar(SkScalarMul(SkIntToScalar(4), a));
263 function.append(" mul sub abs sqrt\n");
264
265 // And then the final value of t.
266 if (posRoot) {
267 function.append("sub ");
268 } else {
269 function.append("add ");
270 }
271 function.appendScalar(SkScalarMul(SkIntToScalar(2), a));
272 function.append(" div\n");
273
274 tileModeCode(info.fTileMode, &function);
275 gradientFunctionCode(info, &function);
276 function.append("}");
277 return function;
278}
279
rileya@google.com62197282012-07-10 20:05:23 +0000280/* Conical gradient shader, based on the Canvas spec for radial gradients
rmistry@google.comd6176b02012-08-23 18:14:13 +0000281 See: http://www.w3.org/TR/2dcontext/#dom-context-2d-createradialgradient
rileya@google.com62197282012-07-10 20:05:23 +0000282 */
283static SkString twoPointConicalCode(const SkShader::GradientInfo& info) {
284 SkScalar dx = info.fPoint[1].fX - info.fPoint[0].fX;
285 SkScalar dy = info.fPoint[1].fY - info.fPoint[0].fY;
286 SkScalar r0 = info.fRadius[0];
287 SkScalar dr = info.fRadius[1] - info.fRadius[0];
rmistry@google.comd6176b02012-08-23 18:14:13 +0000288 SkScalar a = SkScalarMul(dx, dx) + SkScalarMul(dy, dy) -
rileya@google.com62197282012-07-10 20:05:23 +0000289 SkScalarMul(dr, dr);
290
291 // First compute t, if the pixel falls outside the cone, then we'll end
292 // with 'false' on the stack, otherwise we'll push 'true' with t below it
293
294 // We start with a stack of (x y), copy it and then consume one copy in
295 // order to calculate b and the other to calculate c.
296 SkString function("{");
297 function.append("2 copy ");
298
299 // Calculate b and b^2; b = -2 * (y * dy + x * dx + r0 * dr).
300 function.appendScalar(dy);
301 function.append(" mul exch ");
302 function.appendScalar(dx);
303 function.append(" mul add ");
304 function.appendScalar(SkScalarMul(r0, dr));
305 function.append(" add -2 mul dup dup mul\n");
306
307 // c = x^2 + y^2 + radius0^2
308 function.append("4 2 roll dup mul exch dup mul add ");
309 function.appendScalar(SkScalarMul(r0, r0));
310 function.append(" sub dup 4 1 roll\n");
311
312 // Contents of the stack at this point: c, b, b^2, c
313
314 // if a = 0, then we collapse to a simpler linear case
315 if (a == 0) {
316
317 // t = -c/b
318 function.append("pop pop div neg dup ");
319
320 // compute radius(t)
321 function.appendScalar(dr);
322 function.append(" mul ");
323 function.appendScalar(r0);
324 function.append(" add\n");
325
326 // if r(t) < 0, then it's outside the cone
rileya@google.comab2fe822012-07-10 20:41:38 +0000327 function.append("0 lt {pop false} {true} ifelse\n");
rileya@google.com62197282012-07-10 20:05:23 +0000328
329 } else {
330
331 // quadratic case: the Canvas spec wants the largest
332 // root t for which radius(t) > 0
rmistry@google.comd6176b02012-08-23 18:14:13 +0000333
rileya@google.com62197282012-07-10 20:05:23 +0000334 // compute the discriminant (b^2 - 4ac)
335 function.appendScalar(SkScalarMul(SkIntToScalar(4), a));
336 function.append(" mul sub dup\n");
337
338 // if d >= 0, proceed
339 function.append("0 ge {\n");
340
341 // an intermediate value we'll use to compute the roots:
342 // q = -0.5 * (b +/- sqrt(d))
343 function.append("sqrt exch dup 0 lt {exch -1 mul} if");
344 function.append(" add -0.5 mul dup\n");
345
346 // first root = q / a
347 function.appendScalar(a);
348 function.append(" div\n");
349
350 // second root = c / q
351 function.append("3 1 roll div\n");
352
353 // put the larger root on top of the stack
354 function.append("2 copy gt {exch} if\n");
355
356 // compute radius(t) for larger root
357 function.append("dup ");
358 function.appendScalar(dr);
359 function.append(" mul ");
360 function.appendScalar(r0);
361 function.append(" add\n");
362
363 // if r(t) > 0, we have our t, pop off the smaller root and we're done
364 function.append(" 0 gt {exch pop true}\n");
365
366 // otherwise, throw out the larger one and try the smaller root
367 function.append("{pop dup\n");
368 function.appendScalar(dr);
369 function.append(" mul ");
370 function.appendScalar(r0);
371 function.append(" add\n");
372
373 // if r(t) < 0, push false, otherwise the smaller root is our t
rileya@google.comab2fe822012-07-10 20:41:38 +0000374 function.append("0 le {pop false} {true} ifelse\n");
rileya@google.com62197282012-07-10 20:05:23 +0000375 function.append("} ifelse\n");
376
377 // d < 0, clear the stack and push false
rileya@google.comab2fe822012-07-10 20:41:38 +0000378 function.append("} {pop pop pop false} ifelse\n");
rileya@google.com62197282012-07-10 20:05:23 +0000379 }
380
381 // if the pixel is in the cone, proceed to compute a color
382 function.append("{");
383 tileModeCode(info.fTileMode, &function);
384 gradientFunctionCode(info, &function);
385
386 // otherwise, just write black
387 function.append("} {0 0 0} ifelse }");
388
389 return function;
390}
391
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000392static SkString sweepCode(const SkShader::GradientInfo& info) {
393 SkString function("{exch atan 360 div\n");
394 tileModeCode(info.fTileMode, &function);
395 gradientFunctionCode(info, &function);
396 function.append("}");
397 return function;
398}
399
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000400class SkPDFShader::State {
401public:
402 SkShader::GradientType fType;
403 SkShader::GradientInfo fInfo;
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000404 SkAutoFree fColorData; // This provides storage for arrays in fInfo.
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000405 SkMatrix fCanvasTransform;
406 SkMatrix fShaderTransform;
407 SkIRect fBBox;
408
409 SkBitmap fImage;
410 uint32_t fPixelGeneration;
411 SkShader::TileMode fImageTileModes[2];
412
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000413 State(const SkShader& shader, const SkMatrix& canvasTransform,
414 const SkIRect& bbox);
415
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000416 bool operator==(const State& b) const;
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000417
418 SkPDFShader::State* CreateAlphaToLuminosityState() const;
419 SkPDFShader::State* CreateOpaqueState() const;
420
421 bool GradientHasAlpha() const;
422
423private:
424 State(const State& other);
425 State operator=(const State& rhs);
426 void AllocateGradientInfoStorage();
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000427};
428
429class SkPDFFunctionShader : public SkPDFDict, public SkPDFShader {
430public:
ctguil@chromium.orga5c72342011-08-15 23:55:03 +0000431 explicit SkPDFFunctionShader(SkPDFShader::State* state);
robertphillips@google.com05141c22012-04-27 12:54:01 +0000432 virtual ~SkPDFFunctionShader() {
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000433 if (isValid()) {
434 RemoveShader(this);
435 }
436 fResources.unrefAll();
437 }
438
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000439 virtual bool isValid() { return fResources.count() > 0; }
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000440
edisonn@google.com6addb192013-04-02 15:33:08 +0000441 void getResources(const SkTSet<SkPDFObject*>& knownResourceObjects,
442 SkTSet<SkPDFObject*>* newResourceObjects) {
443 GetResourcesHelper(&fResources,
444 knownResourceObjects,
445 newResourceObjects);
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000446 }
447
448private:
449 static SkPDFObject* RangeObject();
450
451 SkTDArray<SkPDFObject*> fResources;
452 SkAutoTDelete<const SkPDFShader::State> fState;
453
454 SkPDFStream* makePSFunction(const SkString& psCode, SkPDFArray* domain);
455};
456
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000457/**
458 * A shader for PDF gradients. This encapsulates the function shader
459 * inside a tiling pattern while providing a common pattern interface.
460 * The encapsulation allows the use of a SMask for transparency gradients.
461 */
462class SkPDFAlphaFunctionShader : public SkPDFStream, public SkPDFShader {
463public:
464 explicit SkPDFAlphaFunctionShader(SkPDFShader::State* state);
465 virtual ~SkPDFAlphaFunctionShader() {
466 if (isValid()) {
467 RemoveShader(this);
468 }
469 }
470
471 virtual bool isValid() {
472 return fColorShader.get() != NULL;
473 }
474
475private:
476 SkAutoTDelete<const SkPDFShader::State> fState;
477
478 SkPDFGraphicState* CreateSMaskGraphicState();
479
480 void getResources(const SkTSet<SkPDFObject*>& knownResourceObjects,
481 SkTSet<SkPDFObject*>* newResourceObjects) {
482 fResourceDict->getReferencedResources(knownResourceObjects,
483 newResourceObjects,
484 true);
485 }
486
487 SkAutoTUnref<SkPDFObject> fColorShader;
488 SkAutoTUnref<SkPDFResourceDict> fResourceDict;
489};
490
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000491class SkPDFImageShader : public SkPDFStream, public SkPDFShader {
492public:
ctguil@chromium.orga5c72342011-08-15 23:55:03 +0000493 explicit SkPDFImageShader(SkPDFShader::State* state);
robertphillips@google.com05141c22012-04-27 12:54:01 +0000494 virtual ~SkPDFImageShader() {
edisonn@google.com8e473762013-07-23 19:45:38 +0000495 if (isValid()) {
496 RemoveShader(this);
497 }
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000498 fResources.unrefAll();
499 }
500
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000501 virtual bool isValid() { return size() > 0; }
502
edisonn@google.com6addb192013-04-02 15:33:08 +0000503 void getResources(const SkTSet<SkPDFObject*>& knownResourceObjects,
504 SkTSet<SkPDFObject*>* newResourceObjects) {
505 GetResourcesHelper(&fResources.toArray(),
506 knownResourceObjects,
507 newResourceObjects);
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000508 }
509
510private:
edisonn@google.com6addb192013-04-02 15:33:08 +0000511 SkTSet<SkPDFObject*> fResources;
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000512 SkAutoTDelete<const SkPDFShader::State> fState;
513};
514
515SkPDFShader::SkPDFShader() {}
516
517// static
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000518SkPDFObject* SkPDFShader::GetPDFShaderByState(State* inState) {
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000519 SkPDFObject* result;
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000520
521 SkAutoTDelete<State> shaderState(inState);
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +0000522 if (shaderState.get()->fType == SkShader::kNone_GradientType &&
523 shaderState.get()->fImage.isNull()) {
524 // TODO(vandebo) This drops SKComposeShader on the floor. We could
525 // handle compose shader by pulling things up to a layer, drawing with
526 // the first shader, applying the xfer mode and drawing again with the
527 // second shader, then applying the layer to the original drawing.
528 return NULL;
529 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000530
531 ShaderCanonicalEntry entry(NULL, shaderState.get());
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +0000532 int index = CanonicalShaders().find(entry);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000533 if (index >= 0) {
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000534 result = CanonicalShaders()[index].fPDFShader;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000535 result->ref();
536 return result;
537 }
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000538
539 bool valid = false;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000540 // The PDFShader takes ownership of the shaderSate.
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000541 if (shaderState.get()->fType == SkShader::kNone_GradientType) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000542 SkPDFImageShader* imageShader =
543 new SkPDFImageShader(shaderState.detach());
544 valid = imageShader->isValid();
545 result = imageShader;
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000546 } else {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000547 if (shaderState.get()->GradientHasAlpha()) {
548 SkPDFAlphaFunctionShader* gradientShader =
549 SkNEW_ARGS(SkPDFAlphaFunctionShader, (shaderState.detach()));
550 valid = gradientShader->isValid();
551 result = gradientShader;
552 } else {
553 SkPDFFunctionShader* functionShader =
554 SkNEW_ARGS(SkPDFFunctionShader, (shaderState.detach()));
555 valid = functionShader->isValid();
556 result = functionShader;
557 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000558 }
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000559 if (!valid) {
560 delete result;
561 return NULL;
562 }
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000563 entry.fPDFShader = result;
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +0000564 CanonicalShaders().push(entry);
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000565 return result; // return the reference that came from new.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000566}
567
568// static
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000569void SkPDFShader::RemoveShader(SkPDFObject* shader) {
570 SkAutoMutexAcquire lock(CanonicalShadersMutex());
571 ShaderCanonicalEntry entry(shader, NULL);
572 int index = CanonicalShaders().find(entry);
573 SkASSERT(index >= 0);
574 CanonicalShaders().removeShuffle(index);
575}
576
577// static
578SkPDFObject* SkPDFShader::GetPDFShader(const SkShader& shader,
579 const SkMatrix& matrix,
580 const SkIRect& surfaceBBox) {
581 SkAutoMutexAcquire lock(CanonicalShadersMutex());
582 return GetPDFShaderByState(
583 SkNEW_ARGS(State, (shader, matrix, surfaceBBox)));
584}
585
586// static
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +0000587SkTDArray<SkPDFShader::ShaderCanonicalEntry>& SkPDFShader::CanonicalShaders() {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000588 // This initialization is only thread safe with gcc.
589 static SkTDArray<ShaderCanonicalEntry> gCanonicalShaders;
590 return gCanonicalShaders;
591}
592
593// static
digit@google.com1771cbf2012-01-26 21:26:40 +0000594SkBaseMutex& SkPDFShader::CanonicalShadersMutex() {
595 // This initialization is only thread safe with gcc or when
596 // POD-style mutex initialization is used.
597 SK_DECLARE_STATIC_MUTEX(gCanonicalShadersMutex);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000598 return gCanonicalShadersMutex;
599}
600
601// static
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000602SkPDFObject* SkPDFFunctionShader::RangeObject() {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000603 // This initialization is only thread safe with gcc.
604 static SkPDFArray* range = NULL;
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +0000605 // This method is only used with CanonicalShadersMutex, so it's safe to
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000606 // populate domain.
607 if (range == NULL) {
608 range = new SkPDFArray;
609 range->reserve(6);
reed@google.comc789cf12011-07-20 12:14:33 +0000610 range->appendInt(0);
611 range->appendInt(1);
612 range->appendInt(0);
613 range->appendInt(1);
614 range->appendInt(0);
615 range->appendInt(1);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000616 }
617 return range;
618}
619
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000620static SkPDFResourceDict* get_gradient_resource_dict(
621 SkPDFObject* functionShader,
622 SkPDFObject* gState) {
623 SkPDFResourceDict* dict = new SkPDFResourceDict();
624
625 if (functionShader != NULL) {
626 dict->insertResourceAsReference(
627 SkPDFResourceDict::kPattern_ResourceType, 0, functionShader);
628 }
629 if (gState != NULL) {
630 dict->insertResourceAsReference(
631 SkPDFResourceDict::kExtGState_ResourceType, 0, gState);
632 }
633
634 return dict;
635}
636
637static void populate_tiling_pattern_dict(SkPDFDict* pattern,
638 SkRect& bbox, SkPDFDict* resources,
639 const SkMatrix& matrix) {
640 const int kTiling_PatternType = 1;
641 const int kColoredTilingPattern_PaintType = 1;
642 const int kConstantSpacing_TilingType = 1;
643
644 pattern->insertName("Type", "Pattern");
645 pattern->insertInt("PatternType", kTiling_PatternType);
646 pattern->insertInt("PaintType", kColoredTilingPattern_PaintType);
647 pattern->insertInt("TilingType", kConstantSpacing_TilingType);
648 pattern->insert("BBox", SkPDFUtils::RectToArray(bbox))->unref();
649 pattern->insertScalar("XStep", bbox.width());
650 pattern->insertScalar("YStep", bbox.height());
651 pattern->insert("Resources", resources);
652 if (!matrix.isIdentity()) {
653 pattern->insert("Matrix", SkPDFUtils::MatrixToArray(matrix))->unref();
654 }
655}
656
657/**
658 * Creates a content stream which fills the pattern P0 across bounds.
659 * @param gsIndex A graphics state resource index to apply, or <0 if no
660 * graphics state to apply.
661 */
662static SkStream* create_pattern_fill_content(int gsIndex, SkRect& bounds) {
663 SkDynamicMemoryWStream content;
664 if (gsIndex >= 0) {
665 SkPDFUtils::ApplyGraphicState(gsIndex, &content);
666 }
667 SkPDFUtils::ApplyPattern(0, &content);
668 SkPDFUtils::AppendRectangle(bounds, &content);
669 SkPDFUtils::PaintPath(SkPaint::kFill_Style, SkPath::kEvenOdd_FillType,
670 &content);
671
672 return content.detachAsStream();
673}
674
675/**
676 * Creates a ExtGState with the SMask set to the luminosityShader in
677 * luminosity mode. The shader pattern extends to the bbox.
678 */
679SkPDFGraphicState* SkPDFAlphaFunctionShader::CreateSMaskGraphicState() {
680 SkRect bbox;
681 bbox.set(fState.get()->fBBox);
682
683 SkAutoTUnref<SkPDFObject> luminosityShader(
684 SkPDFShader::GetPDFShaderByState(
685 fState->CreateAlphaToLuminosityState()));
686
687 SkAutoTUnref<SkStream> alphaStream(create_pattern_fill_content(-1, bbox));
688
689 SkAutoTUnref<SkPDFResourceDict>
690 resources(get_gradient_resource_dict(luminosityShader, NULL));
691
692 SkAutoTUnref<SkPDFFormXObject> alphaMask(
693 new SkPDFFormXObject(alphaStream.get(), bbox, resources.get()));
694
695 return SkPDFGraphicState::GetSMaskGraphicState(
696 alphaMask.get(), false,
697 SkPDFGraphicState::kLuminosity_SMaskMode);
698}
699
700SkPDFAlphaFunctionShader::SkPDFAlphaFunctionShader(SkPDFShader::State* state)
701 : fState(state) {
702 SkRect bbox;
703 bbox.set(fState.get()->fBBox);
704
705 fColorShader.reset(
706 SkPDFShader::GetPDFShaderByState(state->CreateOpaqueState()));
707
708 // Create resource dict with alpha graphics state as G0 and
709 // pattern shader as P0, then write content stream.
710 SkAutoTUnref<SkPDFGraphicState> alphaGs(CreateSMaskGraphicState());
711 fResourceDict.reset(
712 get_gradient_resource_dict(fColorShader.get(), alphaGs.get()));
713
714 SkAutoTUnref<SkStream> colorStream(
715 create_pattern_fill_content(0, bbox));
716 setData(colorStream.get());
717
718 populate_tiling_pattern_dict(this, bbox, fResourceDict.get(),
719 SkMatrix::I());
720}
721
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000722SkPDFFunctionShader::SkPDFFunctionShader(SkPDFShader::State* state)
723 : SkPDFDict("Pattern"),
724 fState(state) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000725 SkString (*codeFunction)(const SkShader::GradientInfo& info) = NULL;
726 SkPoint transformPoints[2];
727
728 // Depending on the type of the gradient, we want to transform the
729 // coordinate space in different ways.
730 const SkShader::GradientInfo* info = &fState.get()->fInfo;
731 transformPoints[0] = info->fPoint[0];
732 transformPoints[1] = info->fPoint[1];
733 switch (fState.get()->fType) {
734 case SkShader::kLinear_GradientType:
735 codeFunction = &linearCode;
736 break;
737 case SkShader::kRadial_GradientType:
738 transformPoints[1] = transformPoints[0];
739 transformPoints[1].fX += info->fRadius[0];
740 codeFunction = &radialCode;
741 break;
742 case SkShader::kRadial2_GradientType: {
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000743 // Bail out if the radii are the same. Empty fResources signals
744 // an error and isValid will return false.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000745 if (info->fRadius[0] == info->fRadius[1]) {
746 return;
747 }
748 transformPoints[1] = transformPoints[0];
749 SkScalar dr = info->fRadius[1] - info->fRadius[0];
750 transformPoints[1].fX += dr;
751 codeFunction = &twoPointRadialCode;
752 break;
753 }
rileya@google.com62197282012-07-10 20:05:23 +0000754 case SkShader::kConical_GradientType: {
755 transformPoints[1] = transformPoints[0];
756 transformPoints[1].fX += SK_Scalar1;
757 codeFunction = &twoPointConicalCode;
758 break;
759 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000760 case SkShader::kSweep_GradientType:
761 transformPoints[1] = transformPoints[0];
vandebo@chromium.orgc39c8672012-04-17 21:46:18 +0000762 transformPoints[1].fX += SK_Scalar1;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000763 codeFunction = &sweepCode;
764 break;
765 case SkShader::kColor_GradientType:
766 case SkShader::kNone_GradientType:
vandebo@chromium.org020798a2011-12-21 01:49:35 +0000767 default:
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000768 return;
769 }
770
771 // Move any scaling (assuming a unit gradient) or translation
772 // (and rotation for linear gradient), of the final gradient from
773 // info->fPoints to the matrix (updating bbox appropriately). Now
774 // the gradient can be drawn on on the unit segment.
775 SkMatrix mapperMatrix;
776 unitToPointsMatrix(transformPoints, &mapperMatrix);
777 SkMatrix finalMatrix = fState.get()->fCanvasTransform;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000778 finalMatrix.preConcat(fState.get()->fShaderTransform);
commit-bot@chromium.orgace22692013-06-12 21:33:02 +0000779 finalMatrix.preConcat(mapperMatrix);
780
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000781 SkRect bbox;
782 bbox.set(fState.get()->fBBox);
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000783 if (!inverseTransformBBox(finalMatrix, &bbox)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000784 return;
785 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000786
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +0000787 SkAutoTUnref<SkPDFArray> domain(new SkPDFArray);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000788 domain->reserve(4);
reed@google.comc789cf12011-07-20 12:14:33 +0000789 domain->appendScalar(bbox.fLeft);
790 domain->appendScalar(bbox.fRight);
791 domain->appendScalar(bbox.fTop);
792 domain->appendScalar(bbox.fBottom);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000793
794 SkString functionCode;
795 // The two point radial gradient further references fState.get()->fInfo
796 // in translating from x, y coordinates to the t parameter. So, we have
797 // to transform the points and radii according to the calculated matrix.
798 if (fState.get()->fType == SkShader::kRadial2_GradientType) {
799 SkShader::GradientInfo twoPointRadialInfo = *info;
800 SkMatrix inverseMapperMatrix;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000801 if (!mapperMatrix.invert(&inverseMapperMatrix)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000802 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000803 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000804 inverseMapperMatrix.mapPoints(twoPointRadialInfo.fPoint, 2);
805 twoPointRadialInfo.fRadius[0] =
806 inverseMapperMatrix.mapRadius(info->fRadius[0]);
807 twoPointRadialInfo.fRadius[1] =
808 inverseMapperMatrix.mapRadius(info->fRadius[1]);
809 functionCode = codeFunction(twoPointRadialInfo);
810 } else {
811 functionCode = codeFunction(*info);
812 }
813
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +0000814 SkAutoTUnref<SkPDFDict> pdfShader(new SkPDFDict);
reed@google.comc789cf12011-07-20 12:14:33 +0000815 pdfShader->insertInt("ShadingType", 1);
816 pdfShader->insertName("ColorSpace", "DeviceRGB");
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000817 pdfShader->insert("Domain", domain.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +0000818
819 SkPDFStream* function = makePSFunction(functionCode, domain.get());
820 pdfShader->insert("Function", new SkPDFObjRef(function))->unref();
821 fResources.push(function); // Pass ownership to resource list.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000822
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000823 insertInt("PatternType", 2);
824 insert("Matrix", SkPDFUtils::MatrixToArray(finalMatrix))->unref();
825 insert("Shading", pdfShader.get());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000826}
827
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000828SkPDFImageShader::SkPDFImageShader(SkPDFShader::State* state) : fState(state) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000829 fState.get()->fImage.lockPixels();
830
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000831 // The image shader pattern cell will be drawn into a separate device
832 // in pattern cell space (no scaling on the bitmap, though there may be
833 // translations so that all content is in the device, coordinates > 0).
834
835 // Map clip bounds to shader space to ensure the device is large enough
836 // to handle fake clamping.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000837 SkMatrix finalMatrix = fState.get()->fCanvasTransform;
838 finalMatrix.preConcat(fState.get()->fShaderTransform);
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000839 SkRect deviceBounds;
840 deviceBounds.set(fState.get()->fBBox);
841 if (!inverseTransformBBox(finalMatrix, &deviceBounds)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000842 return;
843 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000844
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000845 const SkBitmap* image = &fState.get()->fImage;
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000846 SkRect bitmapBounds;
847 image->getBounds(&bitmapBounds);
848
849 // For tiling modes, the bounds should be extended to include the bitmap,
850 // otherwise the bitmap gets clipped out and the shader is empty and awful.
851 // For clamp modes, we're only interested in the clip region, whether
852 // or not the main bitmap is in it.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000853 SkShader::TileMode tileModes[2];
854 tileModes[0] = fState.get()->fImageTileModes[0];
855 tileModes[1] = fState.get()->fImageTileModes[1];
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000856 if (tileModes[0] != SkShader::kClamp_TileMode ||
857 tileModes[1] != SkShader::kClamp_TileMode) {
858 deviceBounds.join(bitmapBounds);
859 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000860
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000861 SkMatrix unflip;
862 unflip.setTranslate(0, SkScalarRoundToScalar(deviceBounds.height()));
863 unflip.preScale(SK_Scalar1, -SK_Scalar1);
864 SkISize size = SkISize::Make(SkScalarRound(deviceBounds.width()),
865 SkScalarRound(deviceBounds.height()));
866 SkPDFDevice pattern(size, size, unflip);
867 SkCanvas canvas(&pattern);
868
869 SkRect patternBBox;
870 image->getBounds(&patternBBox);
871
872 // Translate the canvas so that the bitmap origin is at (0, 0).
873 canvas.translate(-deviceBounds.left(), -deviceBounds.top());
874 patternBBox.offset(-deviceBounds.left(), -deviceBounds.top());
875 // Undo the translation in the final matrix
876 finalMatrix.preTranslate(deviceBounds.left(), deviceBounds.top());
877
878 // If the bitmap is out of bounds (i.e. clamp mode where we only see the
879 // stretched sides), canvas will clip this out and the extraneous data
880 // won't be saved to the PDF.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000881 canvas.drawBitmap(*image, 0, 0);
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000882
883 SkScalar width = SkIntToScalar(image->width());
884 SkScalar height = SkIntToScalar(image->height());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000885
886 // Tiling is implied. First we handle mirroring.
887 if (tileModes[0] == SkShader::kMirror_TileMode) {
888 SkMatrix xMirror;
889 xMirror.setScale(-1, 1);
890 xMirror.postTranslate(2 * width, 0);
891 canvas.drawBitmapMatrix(*image, xMirror);
892 patternBBox.fRight += width;
893 }
894 if (tileModes[1] == SkShader::kMirror_TileMode) {
895 SkMatrix yMirror;
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000896 yMirror.setScale(SK_Scalar1, -SK_Scalar1);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000897 yMirror.postTranslate(0, 2 * height);
898 canvas.drawBitmapMatrix(*image, yMirror);
899 patternBBox.fBottom += height;
900 }
901 if (tileModes[0] == SkShader::kMirror_TileMode &&
902 tileModes[1] == SkShader::kMirror_TileMode) {
903 SkMatrix mirror;
904 mirror.setScale(-1, -1);
905 mirror.postTranslate(2 * width, 2 * height);
906 canvas.drawBitmapMatrix(*image, mirror);
907 }
908
909 // Then handle Clamping, which requires expanding the pattern canvas to
910 // cover the entire surfaceBBox.
911
912 // If both x and y are in clamp mode, we start by filling in the corners.
913 // (Which are just a rectangles of the corner colors.)
914 if (tileModes[0] == SkShader::kClamp_TileMode &&
915 tileModes[1] == SkShader::kClamp_TileMode) {
916 SkPaint paint;
917 SkRect rect;
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000918 rect = SkRect::MakeLTRB(deviceBounds.left(), deviceBounds.top(), 0, 0);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000919 if (!rect.isEmpty()) {
920 paint.setColor(image->getColor(0, 0));
921 canvas.drawRect(rect, paint);
922 }
923
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000924 rect = SkRect::MakeLTRB(width, deviceBounds.top(),
925 deviceBounds.right(), 0);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000926 if (!rect.isEmpty()) {
vandebo@chromium.org54ff85c2012-03-09 17:18:50 +0000927 paint.setColor(image->getColor(image->width() - 1, 0));
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000928 canvas.drawRect(rect, paint);
929 }
930
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000931 rect = SkRect::MakeLTRB(width, height,
932 deviceBounds.right(), deviceBounds.bottom());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000933 if (!rect.isEmpty()) {
vandebo@chromium.org54ff85c2012-03-09 17:18:50 +0000934 paint.setColor(image->getColor(image->width() - 1,
935 image->height() - 1));
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000936 canvas.drawRect(rect, paint);
937 }
938
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000939 rect = SkRect::MakeLTRB(deviceBounds.left(), height,
940 0, deviceBounds.bottom());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000941 if (!rect.isEmpty()) {
vandebo@chromium.org54ff85c2012-03-09 17:18:50 +0000942 paint.setColor(image->getColor(0, image->height() - 1));
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000943 canvas.drawRect(rect, paint);
944 }
945 }
946
947 // Then expand the left, right, top, then bottom.
948 if (tileModes[0] == SkShader::kClamp_TileMode) {
vandebo@chromium.org54ff85c2012-03-09 17:18:50 +0000949 SkIRect subset = SkIRect::MakeXYWH(0, 0, 1, image->height());
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000950 if (deviceBounds.left() < 0) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000951 SkBitmap left;
952 SkAssertResult(image->extractSubset(&left, subset));
953
954 SkMatrix leftMatrix;
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000955 leftMatrix.setScale(-deviceBounds.left(), 1);
956 leftMatrix.postTranslate(deviceBounds.left(), 0);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000957 canvas.drawBitmapMatrix(left, leftMatrix);
958
959 if (tileModes[1] == SkShader::kMirror_TileMode) {
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000960 leftMatrix.postScale(SK_Scalar1, -SK_Scalar1);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000961 leftMatrix.postTranslate(0, 2 * height);
962 canvas.drawBitmapMatrix(left, leftMatrix);
963 }
vandebo@chromium.orgbe2048a2011-05-02 15:24:01 +0000964 patternBBox.fLeft = 0;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000965 }
966
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000967 if (deviceBounds.right() > width) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000968 SkBitmap right;
vandebo@chromium.org54ff85c2012-03-09 17:18:50 +0000969 subset.offset(image->width() - 1, 0);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000970 SkAssertResult(image->extractSubset(&right, subset));
971
972 SkMatrix rightMatrix;
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000973 rightMatrix.setScale(deviceBounds.right() - width, 1);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000974 rightMatrix.postTranslate(width, 0);
975 canvas.drawBitmapMatrix(right, rightMatrix);
976
977 if (tileModes[1] == SkShader::kMirror_TileMode) {
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000978 rightMatrix.postScale(SK_Scalar1, -SK_Scalar1);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000979 rightMatrix.postTranslate(0, 2 * height);
980 canvas.drawBitmapMatrix(right, rightMatrix);
981 }
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000982 patternBBox.fRight = deviceBounds.width();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000983 }
984 }
985
986 if (tileModes[1] == SkShader::kClamp_TileMode) {
vandebo@chromium.org54ff85c2012-03-09 17:18:50 +0000987 SkIRect subset = SkIRect::MakeXYWH(0, 0, image->width(), 1);
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000988 if (deviceBounds.top() < 0) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000989 SkBitmap top;
990 SkAssertResult(image->extractSubset(&top, subset));
991
992 SkMatrix topMatrix;
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000993 topMatrix.setScale(SK_Scalar1, -deviceBounds.top());
994 topMatrix.postTranslate(0, deviceBounds.top());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000995 canvas.drawBitmapMatrix(top, topMatrix);
996
997 if (tileModes[0] == SkShader::kMirror_TileMode) {
998 topMatrix.postScale(-1, 1);
999 topMatrix.postTranslate(2 * width, 0);
1000 canvas.drawBitmapMatrix(top, topMatrix);
1001 }
vandebo@chromium.orgbe2048a2011-05-02 15:24:01 +00001002 patternBBox.fTop = 0;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001003 }
1004
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +00001005 if (deviceBounds.bottom() > height) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001006 SkBitmap bottom;
vandebo@chromium.org54ff85c2012-03-09 17:18:50 +00001007 subset.offset(0, image->height() - 1);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001008 SkAssertResult(image->extractSubset(&bottom, subset));
1009
1010 SkMatrix bottomMatrix;
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +00001011 bottomMatrix.setScale(SK_Scalar1, deviceBounds.bottom() - height);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001012 bottomMatrix.postTranslate(0, height);
1013 canvas.drawBitmapMatrix(bottom, bottomMatrix);
1014
1015 if (tileModes[0] == SkShader::kMirror_TileMode) {
1016 bottomMatrix.postScale(-1, 1);
1017 bottomMatrix.postTranslate(2 * width, 0);
1018 canvas.drawBitmapMatrix(bottom, bottomMatrix);
1019 }
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +00001020 patternBBox.fBottom = deviceBounds.height();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001021 }
1022 }
1023
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001024 // Put the canvas into the pattern stream (fContent).
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001025 SkAutoTUnref<SkStream> content(pattern.content());
1026 setData(content.get());
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001027 SkPDFResourceDict* resourceDict = pattern.getResourceDict();
1028 resourceDict->getReferencedResources(fResources, &fResources, false);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001029
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +00001030 populate_tiling_pattern_dict(this, patternBBox,
1031 pattern.getResourceDict(), finalMatrix);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001032
1033 fState.get()->fImage.unlockPixels();
1034}
1035
vandebo@chromium.org421d6442011-07-20 17:39:01 +00001036SkPDFStream* SkPDFFunctionShader::makePSFunction(const SkString& psCode,
1037 SkPDFArray* domain) {
1038 SkAutoDataUnref funcData(SkData::NewWithCopy(psCode.c_str(),
1039 psCode.size()));
1040 SkPDFStream* result = new SkPDFStream(funcData.get());
reed@google.comc789cf12011-07-20 12:14:33 +00001041 result->insertInt("FunctionType", 4);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001042 result->insert("Domain", domain);
reed@google.comf6c3ebd2011-07-20 17:20:28 +00001043 result->insert("Range", RangeObject());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001044 return result;
1045}
1046
vandebo@chromium.org421d6442011-07-20 17:39:01 +00001047SkPDFShader::ShaderCanonicalEntry::ShaderCanonicalEntry(SkPDFObject* pdfShader,
1048 const State* state)
1049 : fPDFShader(pdfShader),
1050 fState(state) {
1051}
1052
1053bool SkPDFShader::ShaderCanonicalEntry::operator==(
1054 const ShaderCanonicalEntry& b) const {
1055 return fPDFShader == b.fPDFShader ||
1056 (fState != NULL && b.fState != NULL && *fState == *b.fState);
1057}
1058
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001059bool SkPDFShader::State::operator==(const SkPDFShader::State& b) const {
1060 if (fType != b.fType ||
1061 fCanvasTransform != b.fCanvasTransform ||
1062 fShaderTransform != b.fShaderTransform ||
1063 fBBox != b.fBBox) {
1064 return false;
1065 }
1066
1067 if (fType == SkShader::kNone_GradientType) {
1068 if (fPixelGeneration != b.fPixelGeneration ||
1069 fPixelGeneration == 0 ||
1070 fImageTileModes[0] != b.fImageTileModes[0] ||
1071 fImageTileModes[1] != b.fImageTileModes[1]) {
1072 return false;
1073 }
1074 } else {
1075 if (fInfo.fColorCount != b.fInfo.fColorCount ||
1076 memcmp(fInfo.fColors, b.fInfo.fColors,
1077 sizeof(SkColor) * fInfo.fColorCount) != 0 ||
1078 memcmp(fInfo.fColorOffsets, b.fInfo.fColorOffsets,
1079 sizeof(SkScalar) * fInfo.fColorCount) != 0 ||
1080 fInfo.fPoint[0] != b.fInfo.fPoint[0] ||
1081 fInfo.fTileMode != b.fInfo.fTileMode) {
1082 return false;
1083 }
1084
1085 switch (fType) {
1086 case SkShader::kLinear_GradientType:
1087 if (fInfo.fPoint[1] != b.fInfo.fPoint[1]) {
1088 return false;
1089 }
1090 break;
1091 case SkShader::kRadial_GradientType:
1092 if (fInfo.fRadius[0] != b.fInfo.fRadius[0]) {
1093 return false;
1094 }
1095 break;
1096 case SkShader::kRadial2_GradientType:
reed@google.com49085332012-06-11 18:54:07 +00001097 case SkShader::kConical_GradientType:
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001098 if (fInfo.fPoint[1] != b.fInfo.fPoint[1] ||
1099 fInfo.fRadius[0] != b.fInfo.fRadius[0] ||
1100 fInfo.fRadius[1] != b.fInfo.fRadius[1]) {
1101 return false;
1102 }
1103 break;
1104 case SkShader::kSweep_GradientType:
1105 case SkShader::kNone_GradientType:
1106 case SkShader::kColor_GradientType:
1107 break;
1108 }
1109 }
1110 return true;
1111}
1112
1113SkPDFShader::State::State(const SkShader& shader,
1114 const SkMatrix& canvasTransform, const SkIRect& bbox)
1115 : fCanvasTransform(canvasTransform),
vandebo@chromium.orge1bc2742011-06-21 22:26:39 +00001116 fBBox(bbox),
1117 fPixelGeneration(0) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001118 fInfo.fColorCount = 0;
1119 fInfo.fColors = NULL;
1120 fInfo.fColorOffsets = NULL;
bsalomon@google.comf94b3a42012-10-31 18:09:01 +00001121 fShaderTransform = shader.getLocalMatrix();
vandebo@chromium.orge1bc2742011-06-21 22:26:39 +00001122 fImageTileModes[0] = fImageTileModes[1] = SkShader::kClamp_TileMode;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001123
1124 fType = shader.asAGradient(&fInfo);
1125
1126 if (fType == SkShader::kNone_GradientType) {
1127 SkShader::BitmapType bitmapType;
1128 SkMatrix matrix;
rileya@google.com91f319c2012-07-25 17:18:31 +00001129 bitmapType = shader.asABitmap(&fImage, &matrix, fImageTileModes);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001130 if (bitmapType != SkShader::kDefault_BitmapType) {
1131 fImage.reset();
1132 return;
1133 }
1134 SkASSERT(matrix.isIdentity());
1135 fPixelGeneration = fImage.getGenerationID();
1136 } else {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +00001137 AllocateGradientInfoStorage();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001138 shader.asAGradient(&fInfo);
1139 }
1140}
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +00001141
1142SkPDFShader::State::State(const SkPDFShader::State& other)
1143 : fType(other.fType),
1144 fCanvasTransform(other.fCanvasTransform),
1145 fShaderTransform(other.fShaderTransform),
1146 fBBox(other.fBBox)
1147{
1148 // Only gradients supported for now, since that is all that is used.
1149 // If needed, image state copy constructor can be added here later.
1150 SkASSERT(fType != SkShader::kNone_GradientType);
1151
1152 if (fType != SkShader::kNone_GradientType) {
1153 fInfo = other.fInfo;
1154
1155 AllocateGradientInfoStorage();
1156 for (int i = 0; i < fInfo.fColorCount; i++) {
1157 fInfo.fColors[i] = other.fInfo.fColors[i];
1158 fInfo.fColorOffsets[i] = other.fInfo.fColorOffsets[i];
1159 }
1160 }
1161}
1162
1163/**
1164 * Create a copy of this gradient state with alpha assigned to RGB luminousity.
1165 * Only valid for gradient states.
1166 */
1167SkPDFShader::State* SkPDFShader::State::CreateAlphaToLuminosityState() const {
1168 SkASSERT(fType != SkShader::kNone_GradientType);
1169
1170 SkPDFShader::State* newState = new SkPDFShader::State(*this);
1171
1172 for (int i = 0; i < fInfo.fColorCount; i++) {
1173 SkAlpha alpha = SkColorGetA(fInfo.fColors[i]);
1174 newState->fInfo.fColors[i] = SkColorSetARGB(255, alpha, alpha, alpha);
1175 }
1176
1177 return newState;
1178}
1179
1180/**
1181 * Create a copy of this gradient state with alpha set to fully opaque
1182 * Only valid for gradient states.
1183 */
1184SkPDFShader::State* SkPDFShader::State::CreateOpaqueState() const {
1185 SkASSERT(fType != SkShader::kNone_GradientType);
1186
1187 SkPDFShader::State* newState = new SkPDFShader::State(*this);
1188 for (int i = 0; i < fInfo.fColorCount; i++) {
1189 newState->fInfo.fColors[i] = SkColorSetA(fInfo.fColors[i],
1190 SK_AlphaOPAQUE);
1191 }
1192
1193 return newState;
1194}
1195
1196/**
1197 * Returns true if state is a gradient and the gradient has alpha.
1198 */
1199bool SkPDFShader::State::GradientHasAlpha() const {
1200 if (fType == SkShader::kNone_GradientType) {
1201 return false;
1202 }
1203
1204 for (int i = 0; i < fInfo.fColorCount; i++) {
1205 SkAlpha alpha = SkColorGetA(fInfo.fColors[i]);
1206 if (alpha != SK_AlphaOPAQUE) {
1207 return true;
1208 }
1209 }
1210 return false;
1211}
1212
1213void SkPDFShader::State::AllocateGradientInfoStorage() {
1214 fColorData.set(sk_malloc_throw(
1215 fInfo.fColorCount * (sizeof(SkColor) + sizeof(SkScalar))));
1216 fInfo.fColors = reinterpret_cast<SkColor*>(fColorData.get());
1217 fInfo.fColorOffsets =
1218 reinterpret_cast<SkScalar*>(fInfo.fColors + fInfo.fColorCount);
1219}