blob: 70fb616a24f672cbf0b57603cf400defb69d0973 [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
vandebo@chromium.org421d6442011-07-20 17:39:01 +000012#include "SkData.h"
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000013#include "SkPDFCatalog.h"
14#include "SkPDFDevice.h"
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +000015#include "SkPDFFormXObject.h"
16#include "SkPDFGraphicState.h"
commit-bot@chromium.org47401352013-07-23 21:49:29 +000017#include "SkPDFResourceDict.h"
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000018#include "SkPDFUtils.h"
19#include "SkScalar.h"
20#include "SkStream.h"
twiz@google.com316338a2011-03-09 23:14:04 +000021#include "SkTemplates.h"
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000022#include "SkThread.h"
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +000023#include "SkTSet.h"
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000024#include "SkTypes.h"
25
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +000026static bool inverseTransformBBox(const SkMatrix& matrix, SkRect* bbox) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000027 SkMatrix inverse;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +000028 if (!matrix.invert(&inverse)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +000029 return false;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +000030 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000031 inverse.mapRect(bbox);
vandebo@chromium.org386dfc02012-04-17 22:31:52 +000032 return true;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000033}
34
35static void unitToPointsMatrix(const SkPoint pts[2], SkMatrix* matrix) {
36 SkVector vec = pts[1] - pts[0];
37 SkScalar mag = vec.length();
38 SkScalar inv = mag ? SkScalarInvert(mag) : 0;
39
40 vec.scale(inv);
41 matrix->setSinCos(vec.fY, vec.fX);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000042 matrix->preScale(mag, mag);
commit-bot@chromium.orgace22692013-06-12 21:33:02 +000043 matrix->postTranslate(pts[0].fX, pts[0].fY);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000044}
45
46/* Assumes t + startOffset is on the stack and does a linear interpolation on t
47 between startOffset and endOffset from prevColor to curColor (for each color
djsollen@google.com53648ab2013-04-03 12:34:16 +000048 component), leaving the result in component order on the stack. It assumes
49 there are always 3 components per color.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +000050 @param range endOffset - startOffset
51 @param curColor[components] The current color components.
52 @param prevColor[components] The previous color components.
53 @param result The result ps function.
54 */
55static void interpolateColorCode(SkScalar range, SkScalar* curColor,
djsollen@google.com53648ab2013-04-03 12:34:16 +000056 SkScalar* prevColor, SkString* result) {
edisonn@google.com81353232013-09-17 17:17:47 +000057 SkASSERT(range != SkIntToScalar(0));
djsollen@google.com53648ab2013-04-03 12:34:16 +000058 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.
edisonn@google.com81353232013-09-17 17:17:47 +0000155 int gradients = 0;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000156 for (int i = 1 ; i < info.fColorCount; i++) {
edisonn@google.com81353232013-09-17 17:17:47 +0000157 if (info.fColorOffsets[i] == info.fColorOffsets[i - 1]) {
158 continue;
159 }
160 gradients++;
161
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000162 result->append("{dup ");
163 result->appendScalar(info.fColorOffsets[i]);
164 result->append(" le {");
165 if (info.fColorOffsets[i - 1] != 0) {
166 result->appendScalar(info.fColorOffsets[i - 1]);
167 result->append(" sub\n");
168 }
169
170 interpolateColorCode(info.fColorOffsets[i] - info.fColorOffsets[i - 1],
djsollen@google.com53648ab2013-04-03 12:34:16 +0000171 colorData[i], colorData[i - 1], result);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000172 result->append("}\n");
173 }
174
175 // Clamp the final color.
176 result->append("{pop ");
177 result->appendScalar(colorData[info.fColorCount - 1][0]);
178 result->append(" ");
179 result->appendScalar(colorData[info.fColorCount - 1][1]);
180 result->append(" ");
181 result->appendScalar(colorData[info.fColorCount - 1][2]);
182
edisonn@google.com81353232013-09-17 17:17:47 +0000183 for (int i = 0 ; i < gradients + 1; i++) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000184 result->append("} ifelse\n");
185 }
186}
187
188/* Map a value of t on the stack into [0, 1) for Repeat or Mirror tile mode. */
189static void tileModeCode(SkShader::TileMode mode, SkString* result) {
190 if (mode == SkShader::kRepeat_TileMode) {
191 result->append("dup truncate sub\n"); // Get the fractional part.
192 result->append("dup 0 le {1 add} if\n"); // Map (-1,0) => (0,1)
193 return;
194 }
195
196 if (mode == SkShader::kMirror_TileMode) {
197 // Map t mod 2 into [0, 1, 1, 0].
198 // Code Stack
199 result->append("abs " // Map negative to positive.
200 "dup " // t.s t.s
201 "truncate " // t.s t
202 "dup " // t.s t t
203 "cvi " // t.s t T
204 "2 mod " // t.s t (i mod 2)
205 "1 eq " // t.s t true|false
206 "3 1 roll " // true|false t.s t
207 "sub " // true|false 0.s
208 "exch " // 0.s true|false
209 "{1 exch sub} if\n"); // 1 - 0.s|0.s
210 }
211}
212
213static SkString linearCode(const SkShader::GradientInfo& info) {
ctguil@chromium.orga5c72342011-08-15 23:55:03 +0000214 SkString function("{pop\n"); // Just ditch the y value.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000215 tileModeCode(info.fTileMode, &function);
216 gradientFunctionCode(info, &function);
217 function.append("}");
218 return function;
219}
220
221static SkString radialCode(const SkShader::GradientInfo& info) {
222 SkString function("{");
223 // Find the distance from the origin.
224 function.append("dup " // x y y
225 "mul " // x y^2
226 "exch " // y^2 x
227 "dup " // y^2 x x
228 "mul " // y^2 x^2
229 "add " // y^2+x^2
230 "sqrt\n"); // sqrt(y^2+x^2)
231
232 tileModeCode(info.fTileMode, &function);
233 gradientFunctionCode(info, &function);
234 function.append("}");
235 return function;
236}
237
238/* The math here is all based on the description in Two_Point_Radial_Gradient,
239 with one simplification, the coordinate space has been scaled so that
240 Dr = 1. This means we don't need to scale the entire equation by 1/Dr^2.
241 */
242static SkString twoPointRadialCode(const SkShader::GradientInfo& info) {
243 SkScalar dx = info.fPoint[0].fX - info.fPoint[1].fX;
244 SkScalar dy = info.fPoint[0].fY - info.fPoint[1].fY;
245 SkScalar sr = info.fRadius[0];
246 SkScalar a = SkScalarMul(dx, dx) + SkScalarMul(dy, dy) - SK_Scalar1;
247 bool posRoot = info.fRadius[1] > info.fRadius[0];
248
249 // We start with a stack of (x y), copy it and then consume one copy in
250 // order to calculate b and the other to calculate c.
251 SkString function("{");
252 function.append("2 copy ");
253
254 // Calculate -b and b^2.
255 function.appendScalar(dy);
256 function.append(" mul exch ");
257 function.appendScalar(dx);
258 function.append(" mul add ");
259 function.appendScalar(sr);
260 function.append(" sub 2 mul neg dup dup mul\n");
261
262 // Calculate c
263 function.append("4 2 roll dup mul exch dup mul add ");
264 function.appendScalar(SkScalarMul(sr, sr));
265 function.append(" sub\n");
266
267 // Calculate the determinate
268 function.appendScalar(SkScalarMul(SkIntToScalar(4), a));
269 function.append(" mul sub abs sqrt\n");
270
271 // And then the final value of t.
272 if (posRoot) {
273 function.append("sub ");
274 } else {
275 function.append("add ");
276 }
277 function.appendScalar(SkScalarMul(SkIntToScalar(2), a));
278 function.append(" div\n");
279
280 tileModeCode(info.fTileMode, &function);
281 gradientFunctionCode(info, &function);
282 function.append("}");
283 return function;
284}
285
rileya@google.com62197282012-07-10 20:05:23 +0000286/* Conical gradient shader, based on the Canvas spec for radial gradients
rmistry@google.comd6176b02012-08-23 18:14:13 +0000287 See: http://www.w3.org/TR/2dcontext/#dom-context-2d-createradialgradient
rileya@google.com62197282012-07-10 20:05:23 +0000288 */
289static SkString twoPointConicalCode(const SkShader::GradientInfo& info) {
290 SkScalar dx = info.fPoint[1].fX - info.fPoint[0].fX;
291 SkScalar dy = info.fPoint[1].fY - info.fPoint[0].fY;
292 SkScalar r0 = info.fRadius[0];
293 SkScalar dr = info.fRadius[1] - info.fRadius[0];
rmistry@google.comd6176b02012-08-23 18:14:13 +0000294 SkScalar a = SkScalarMul(dx, dx) + SkScalarMul(dy, dy) -
rileya@google.com62197282012-07-10 20:05:23 +0000295 SkScalarMul(dr, dr);
296
297 // First compute t, if the pixel falls outside the cone, then we'll end
298 // with 'false' on the stack, otherwise we'll push 'true' with t below it
299
300 // We start with a stack of (x y), copy it and then consume one copy in
301 // order to calculate b and the other to calculate c.
302 SkString function("{");
303 function.append("2 copy ");
304
305 // Calculate b and b^2; b = -2 * (y * dy + x * dx + r0 * dr).
306 function.appendScalar(dy);
307 function.append(" mul exch ");
308 function.appendScalar(dx);
309 function.append(" mul add ");
310 function.appendScalar(SkScalarMul(r0, dr));
311 function.append(" add -2 mul dup dup mul\n");
312
313 // c = x^2 + y^2 + radius0^2
314 function.append("4 2 roll dup mul exch dup mul add ");
315 function.appendScalar(SkScalarMul(r0, r0));
316 function.append(" sub dup 4 1 roll\n");
317
318 // Contents of the stack at this point: c, b, b^2, c
319
320 // if a = 0, then we collapse to a simpler linear case
321 if (a == 0) {
322
323 // t = -c/b
324 function.append("pop pop div neg dup ");
325
326 // compute radius(t)
327 function.appendScalar(dr);
328 function.append(" mul ");
329 function.appendScalar(r0);
330 function.append(" add\n");
331
332 // if r(t) < 0, then it's outside the cone
rileya@google.comab2fe822012-07-10 20:41:38 +0000333 function.append("0 lt {pop false} {true} ifelse\n");
rileya@google.com62197282012-07-10 20:05:23 +0000334
335 } else {
336
337 // quadratic case: the Canvas spec wants the largest
338 // root t for which radius(t) > 0
rmistry@google.comd6176b02012-08-23 18:14:13 +0000339
rileya@google.com62197282012-07-10 20:05:23 +0000340 // compute the discriminant (b^2 - 4ac)
341 function.appendScalar(SkScalarMul(SkIntToScalar(4), a));
342 function.append(" mul sub dup\n");
343
344 // if d >= 0, proceed
345 function.append("0 ge {\n");
346
347 // an intermediate value we'll use to compute the roots:
348 // q = -0.5 * (b +/- sqrt(d))
349 function.append("sqrt exch dup 0 lt {exch -1 mul} if");
350 function.append(" add -0.5 mul dup\n");
351
352 // first root = q / a
353 function.appendScalar(a);
354 function.append(" div\n");
355
356 // second root = c / q
357 function.append("3 1 roll div\n");
358
359 // put the larger root on top of the stack
360 function.append("2 copy gt {exch} if\n");
361
362 // compute radius(t) for larger root
363 function.append("dup ");
364 function.appendScalar(dr);
365 function.append(" mul ");
366 function.appendScalar(r0);
367 function.append(" add\n");
368
369 // if r(t) > 0, we have our t, pop off the smaller root and we're done
370 function.append(" 0 gt {exch pop true}\n");
371
372 // otherwise, throw out the larger one and try the smaller root
373 function.append("{pop dup\n");
374 function.appendScalar(dr);
375 function.append(" mul ");
376 function.appendScalar(r0);
377 function.append(" add\n");
378
379 // if r(t) < 0, push false, otherwise the smaller root is our t
rileya@google.comab2fe822012-07-10 20:41:38 +0000380 function.append("0 le {pop false} {true} ifelse\n");
rileya@google.com62197282012-07-10 20:05:23 +0000381 function.append("} ifelse\n");
382
383 // d < 0, clear the stack and push false
rileya@google.comab2fe822012-07-10 20:41:38 +0000384 function.append("} {pop pop pop false} ifelse\n");
rileya@google.com62197282012-07-10 20:05:23 +0000385 }
386
387 // if the pixel is in the cone, proceed to compute a color
388 function.append("{");
389 tileModeCode(info.fTileMode, &function);
390 gradientFunctionCode(info, &function);
391
392 // otherwise, just write black
393 function.append("} {0 0 0} ifelse }");
394
395 return function;
396}
397
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000398static SkString sweepCode(const SkShader::GradientInfo& info) {
399 SkString function("{exch atan 360 div\n");
400 tileModeCode(info.fTileMode, &function);
401 gradientFunctionCode(info, &function);
402 function.append("}");
403 return function;
404}
405
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000406class SkPDFShader::State {
407public:
408 SkShader::GradientType fType;
409 SkShader::GradientInfo fInfo;
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000410 SkAutoFree fColorData; // This provides storage for arrays in fInfo.
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000411 SkMatrix fCanvasTransform;
412 SkMatrix fShaderTransform;
413 SkIRect fBBox;
414
415 SkBitmap fImage;
416 uint32_t fPixelGeneration;
417 SkShader::TileMode fImageTileModes[2];
418
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000419 State(const SkShader& shader, const SkMatrix& canvasTransform,
420 const SkIRect& bbox);
421
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000422 bool operator==(const State& b) const;
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000423
424 SkPDFShader::State* CreateAlphaToLuminosityState() const;
425 SkPDFShader::State* CreateOpaqueState() const;
426
427 bool GradientHasAlpha() const;
428
429private:
430 State(const State& other);
431 State operator=(const State& rhs);
432 void AllocateGradientInfoStorage();
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000433};
434
435class SkPDFFunctionShader : public SkPDFDict, public SkPDFShader {
436public:
ctguil@chromium.orga5c72342011-08-15 23:55:03 +0000437 explicit SkPDFFunctionShader(SkPDFShader::State* state);
robertphillips@google.com05141c22012-04-27 12:54:01 +0000438 virtual ~SkPDFFunctionShader() {
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000439 if (isValid()) {
440 RemoveShader(this);
441 }
442 fResources.unrefAll();
443 }
444
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000445 virtual bool isValid() { return fResources.count() > 0; }
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000446
edisonn@google.com6addb192013-04-02 15:33:08 +0000447 void getResources(const SkTSet<SkPDFObject*>& knownResourceObjects,
448 SkTSet<SkPDFObject*>* newResourceObjects) {
449 GetResourcesHelper(&fResources,
450 knownResourceObjects,
451 newResourceObjects);
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000452 }
453
454private:
455 static SkPDFObject* RangeObject();
456
457 SkTDArray<SkPDFObject*> fResources;
458 SkAutoTDelete<const SkPDFShader::State> fState;
459
460 SkPDFStream* makePSFunction(const SkString& psCode, SkPDFArray* domain);
461};
462
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000463/**
464 * A shader for PDF gradients. This encapsulates the function shader
465 * inside a tiling pattern while providing a common pattern interface.
466 * The encapsulation allows the use of a SMask for transparency gradients.
467 */
468class SkPDFAlphaFunctionShader : public SkPDFStream, public SkPDFShader {
469public:
470 explicit SkPDFAlphaFunctionShader(SkPDFShader::State* state);
471 virtual ~SkPDFAlphaFunctionShader() {
472 if (isValid()) {
473 RemoveShader(this);
474 }
475 }
476
477 virtual bool isValid() {
478 return fColorShader.get() != NULL;
479 }
480
481private:
482 SkAutoTDelete<const SkPDFShader::State> fState;
483
484 SkPDFGraphicState* CreateSMaskGraphicState();
485
486 void getResources(const SkTSet<SkPDFObject*>& knownResourceObjects,
487 SkTSet<SkPDFObject*>* newResourceObjects) {
488 fResourceDict->getReferencedResources(knownResourceObjects,
489 newResourceObjects,
490 true);
491 }
492
493 SkAutoTUnref<SkPDFObject> fColorShader;
494 SkAutoTUnref<SkPDFResourceDict> fResourceDict;
495};
496
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000497class SkPDFImageShader : public SkPDFStream, public SkPDFShader {
498public:
ctguil@chromium.orga5c72342011-08-15 23:55:03 +0000499 explicit SkPDFImageShader(SkPDFShader::State* state);
robertphillips@google.com05141c22012-04-27 12:54:01 +0000500 virtual ~SkPDFImageShader() {
edisonn@google.com8e473762013-07-23 19:45:38 +0000501 if (isValid()) {
502 RemoveShader(this);
503 }
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000504 fResources.unrefAll();
505 }
506
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000507 virtual bool isValid() { return size() > 0; }
508
edisonn@google.com6addb192013-04-02 15:33:08 +0000509 void getResources(const SkTSet<SkPDFObject*>& knownResourceObjects,
510 SkTSet<SkPDFObject*>* newResourceObjects) {
511 GetResourcesHelper(&fResources.toArray(),
512 knownResourceObjects,
513 newResourceObjects);
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000514 }
515
516private:
edisonn@google.com6addb192013-04-02 15:33:08 +0000517 SkTSet<SkPDFObject*> fResources;
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000518 SkAutoTDelete<const SkPDFShader::State> fState;
519};
520
521SkPDFShader::SkPDFShader() {}
522
523// static
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000524SkPDFObject* SkPDFShader::GetPDFShaderByState(State* inState) {
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000525 SkPDFObject* result;
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000526
527 SkAutoTDelete<State> shaderState(inState);
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +0000528 if (shaderState.get()->fType == SkShader::kNone_GradientType &&
529 shaderState.get()->fImage.isNull()) {
530 // TODO(vandebo) This drops SKComposeShader on the floor. We could
531 // handle compose shader by pulling things up to a layer, drawing with
532 // the first shader, applying the xfer mode and drawing again with the
533 // second shader, then applying the layer to the original drawing.
534 return NULL;
535 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000536
537 ShaderCanonicalEntry entry(NULL, shaderState.get());
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +0000538 int index = CanonicalShaders().find(entry);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000539 if (index >= 0) {
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000540 result = CanonicalShaders()[index].fPDFShader;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000541 result->ref();
542 return result;
543 }
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000544
545 bool valid = false;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000546 // The PDFShader takes ownership of the shaderSate.
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000547 if (shaderState.get()->fType == SkShader::kNone_GradientType) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000548 SkPDFImageShader* imageShader =
549 new SkPDFImageShader(shaderState.detach());
550 valid = imageShader->isValid();
551 result = imageShader;
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000552 } else {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000553 if (shaderState.get()->GradientHasAlpha()) {
554 SkPDFAlphaFunctionShader* gradientShader =
555 SkNEW_ARGS(SkPDFAlphaFunctionShader, (shaderState.detach()));
556 valid = gradientShader->isValid();
557 result = gradientShader;
558 } else {
559 SkPDFFunctionShader* functionShader =
560 SkNEW_ARGS(SkPDFFunctionShader, (shaderState.detach()));
561 valid = functionShader->isValid();
562 result = functionShader;
563 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000564 }
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000565 if (!valid) {
566 delete result;
567 return NULL;
568 }
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000569 entry.fPDFShader = result;
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +0000570 CanonicalShaders().push(entry);
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000571 return result; // return the reference that came from new.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000572}
573
574// static
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000575void SkPDFShader::RemoveShader(SkPDFObject* shader) {
576 SkAutoMutexAcquire lock(CanonicalShadersMutex());
577 ShaderCanonicalEntry entry(shader, NULL);
578 int index = CanonicalShaders().find(entry);
579 SkASSERT(index >= 0);
580 CanonicalShaders().removeShuffle(index);
581}
582
583// static
584SkPDFObject* SkPDFShader::GetPDFShader(const SkShader& shader,
585 const SkMatrix& matrix,
586 const SkIRect& surfaceBBox) {
587 SkAutoMutexAcquire lock(CanonicalShadersMutex());
588 return GetPDFShaderByState(
589 SkNEW_ARGS(State, (shader, matrix, surfaceBBox)));
590}
591
592// static
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +0000593SkTDArray<SkPDFShader::ShaderCanonicalEntry>& SkPDFShader::CanonicalShaders() {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000594 // This initialization is only thread safe with gcc.
595 static SkTDArray<ShaderCanonicalEntry> gCanonicalShaders;
596 return gCanonicalShaders;
597}
598
599// static
digit@google.com1771cbf2012-01-26 21:26:40 +0000600SkBaseMutex& SkPDFShader::CanonicalShadersMutex() {
601 // This initialization is only thread safe with gcc or when
602 // POD-style mutex initialization is used.
603 SK_DECLARE_STATIC_MUTEX(gCanonicalShadersMutex);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000604 return gCanonicalShadersMutex;
605}
606
607// static
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000608SkPDFObject* SkPDFFunctionShader::RangeObject() {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000609 // This initialization is only thread safe with gcc.
610 static SkPDFArray* range = NULL;
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +0000611 // This method is only used with CanonicalShadersMutex, so it's safe to
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000612 // populate domain.
613 if (range == NULL) {
614 range = new SkPDFArray;
615 range->reserve(6);
reed@google.comc789cf12011-07-20 12:14:33 +0000616 range->appendInt(0);
617 range->appendInt(1);
618 range->appendInt(0);
619 range->appendInt(1);
620 range->appendInt(0);
621 range->appendInt(1);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000622 }
623 return range;
624}
625
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000626static SkPDFResourceDict* get_gradient_resource_dict(
627 SkPDFObject* functionShader,
628 SkPDFObject* gState) {
629 SkPDFResourceDict* dict = new SkPDFResourceDict();
630
631 if (functionShader != NULL) {
632 dict->insertResourceAsReference(
633 SkPDFResourceDict::kPattern_ResourceType, 0, functionShader);
634 }
635 if (gState != NULL) {
636 dict->insertResourceAsReference(
637 SkPDFResourceDict::kExtGState_ResourceType, 0, gState);
638 }
639
640 return dict;
641}
642
643static void populate_tiling_pattern_dict(SkPDFDict* pattern,
644 SkRect& bbox, SkPDFDict* resources,
645 const SkMatrix& matrix) {
646 const int kTiling_PatternType = 1;
647 const int kColoredTilingPattern_PaintType = 1;
648 const int kConstantSpacing_TilingType = 1;
649
650 pattern->insertName("Type", "Pattern");
651 pattern->insertInt("PatternType", kTiling_PatternType);
652 pattern->insertInt("PaintType", kColoredTilingPattern_PaintType);
653 pattern->insertInt("TilingType", kConstantSpacing_TilingType);
654 pattern->insert("BBox", SkPDFUtils::RectToArray(bbox))->unref();
655 pattern->insertScalar("XStep", bbox.width());
656 pattern->insertScalar("YStep", bbox.height());
657 pattern->insert("Resources", resources);
658 if (!matrix.isIdentity()) {
659 pattern->insert("Matrix", SkPDFUtils::MatrixToArray(matrix))->unref();
660 }
661}
662
663/**
664 * Creates a content stream which fills the pattern P0 across bounds.
665 * @param gsIndex A graphics state resource index to apply, or <0 if no
666 * graphics state to apply.
667 */
668static SkStream* create_pattern_fill_content(int gsIndex, SkRect& bounds) {
669 SkDynamicMemoryWStream content;
670 if (gsIndex >= 0) {
671 SkPDFUtils::ApplyGraphicState(gsIndex, &content);
672 }
673 SkPDFUtils::ApplyPattern(0, &content);
674 SkPDFUtils::AppendRectangle(bounds, &content);
675 SkPDFUtils::PaintPath(SkPaint::kFill_Style, SkPath::kEvenOdd_FillType,
676 &content);
677
678 return content.detachAsStream();
679}
680
681/**
682 * Creates a ExtGState with the SMask set to the luminosityShader in
683 * luminosity mode. The shader pattern extends to the bbox.
684 */
685SkPDFGraphicState* SkPDFAlphaFunctionShader::CreateSMaskGraphicState() {
686 SkRect bbox;
687 bbox.set(fState.get()->fBBox);
688
689 SkAutoTUnref<SkPDFObject> luminosityShader(
690 SkPDFShader::GetPDFShaderByState(
691 fState->CreateAlphaToLuminosityState()));
692
693 SkAutoTUnref<SkStream> alphaStream(create_pattern_fill_content(-1, bbox));
694
695 SkAutoTUnref<SkPDFResourceDict>
696 resources(get_gradient_resource_dict(luminosityShader, NULL));
697
698 SkAutoTUnref<SkPDFFormXObject> alphaMask(
699 new SkPDFFormXObject(alphaStream.get(), bbox, resources.get()));
700
701 return SkPDFGraphicState::GetSMaskGraphicState(
702 alphaMask.get(), false,
703 SkPDFGraphicState::kLuminosity_SMaskMode);
704}
705
706SkPDFAlphaFunctionShader::SkPDFAlphaFunctionShader(SkPDFShader::State* state)
707 : fState(state) {
708 SkRect bbox;
709 bbox.set(fState.get()->fBBox);
710
711 fColorShader.reset(
712 SkPDFShader::GetPDFShaderByState(state->CreateOpaqueState()));
713
714 // Create resource dict with alpha graphics state as G0 and
715 // pattern shader as P0, then write content stream.
716 SkAutoTUnref<SkPDFGraphicState> alphaGs(CreateSMaskGraphicState());
717 fResourceDict.reset(
718 get_gradient_resource_dict(fColorShader.get(), alphaGs.get()));
719
720 SkAutoTUnref<SkStream> colorStream(
721 create_pattern_fill_content(0, bbox));
722 setData(colorStream.get());
723
724 populate_tiling_pattern_dict(this, bbox, fResourceDict.get(),
725 SkMatrix::I());
726}
727
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000728SkPDFFunctionShader::SkPDFFunctionShader(SkPDFShader::State* state)
729 : SkPDFDict("Pattern"),
730 fState(state) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000731 SkString (*codeFunction)(const SkShader::GradientInfo& info) = NULL;
732 SkPoint transformPoints[2];
733
734 // Depending on the type of the gradient, we want to transform the
735 // coordinate space in different ways.
736 const SkShader::GradientInfo* info = &fState.get()->fInfo;
737 transformPoints[0] = info->fPoint[0];
738 transformPoints[1] = info->fPoint[1];
739 switch (fState.get()->fType) {
740 case SkShader::kLinear_GradientType:
741 codeFunction = &linearCode;
742 break;
743 case SkShader::kRadial_GradientType:
744 transformPoints[1] = transformPoints[0];
745 transformPoints[1].fX += info->fRadius[0];
746 codeFunction = &radialCode;
747 break;
748 case SkShader::kRadial2_GradientType: {
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000749 // Bail out if the radii are the same. Empty fResources signals
750 // an error and isValid will return false.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000751 if (info->fRadius[0] == info->fRadius[1]) {
752 return;
753 }
754 transformPoints[1] = transformPoints[0];
755 SkScalar dr = info->fRadius[1] - info->fRadius[0];
756 transformPoints[1].fX += dr;
757 codeFunction = &twoPointRadialCode;
758 break;
759 }
rileya@google.com62197282012-07-10 20:05:23 +0000760 case SkShader::kConical_GradientType: {
761 transformPoints[1] = transformPoints[0];
762 transformPoints[1].fX += SK_Scalar1;
763 codeFunction = &twoPointConicalCode;
764 break;
765 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000766 case SkShader::kSweep_GradientType:
767 transformPoints[1] = transformPoints[0];
vandebo@chromium.orgc39c8672012-04-17 21:46:18 +0000768 transformPoints[1].fX += SK_Scalar1;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000769 codeFunction = &sweepCode;
770 break;
771 case SkShader::kColor_GradientType:
772 case SkShader::kNone_GradientType:
vandebo@chromium.org020798a2011-12-21 01:49:35 +0000773 default:
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000774 return;
775 }
776
777 // Move any scaling (assuming a unit gradient) or translation
778 // (and rotation for linear gradient), of the final gradient from
779 // info->fPoints to the matrix (updating bbox appropriately). Now
780 // the gradient can be drawn on on the unit segment.
781 SkMatrix mapperMatrix;
782 unitToPointsMatrix(transformPoints, &mapperMatrix);
783 SkMatrix finalMatrix = fState.get()->fCanvasTransform;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000784 finalMatrix.preConcat(fState.get()->fShaderTransform);
commit-bot@chromium.orgace22692013-06-12 21:33:02 +0000785 finalMatrix.preConcat(mapperMatrix);
786
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000787 SkRect bbox;
788 bbox.set(fState.get()->fBBox);
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000789 if (!inverseTransformBBox(finalMatrix, &bbox)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000790 return;
791 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000792
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +0000793 SkAutoTUnref<SkPDFArray> domain(new SkPDFArray);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000794 domain->reserve(4);
reed@google.comc789cf12011-07-20 12:14:33 +0000795 domain->appendScalar(bbox.fLeft);
796 domain->appendScalar(bbox.fRight);
797 domain->appendScalar(bbox.fTop);
798 domain->appendScalar(bbox.fBottom);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000799
800 SkString functionCode;
801 // The two point radial gradient further references fState.get()->fInfo
802 // in translating from x, y coordinates to the t parameter. So, we have
803 // to transform the points and radii according to the calculated matrix.
804 if (fState.get()->fType == SkShader::kRadial2_GradientType) {
805 SkShader::GradientInfo twoPointRadialInfo = *info;
806 SkMatrix inverseMapperMatrix;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000807 if (!mapperMatrix.invert(&inverseMapperMatrix)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000808 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000809 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000810 inverseMapperMatrix.mapPoints(twoPointRadialInfo.fPoint, 2);
811 twoPointRadialInfo.fRadius[0] =
812 inverseMapperMatrix.mapRadius(info->fRadius[0]);
813 twoPointRadialInfo.fRadius[1] =
814 inverseMapperMatrix.mapRadius(info->fRadius[1]);
815 functionCode = codeFunction(twoPointRadialInfo);
816 } else {
817 functionCode = codeFunction(*info);
818 }
819
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +0000820 SkAutoTUnref<SkPDFDict> pdfShader(new SkPDFDict);
reed@google.comc789cf12011-07-20 12:14:33 +0000821 pdfShader->insertInt("ShadingType", 1);
822 pdfShader->insertName("ColorSpace", "DeviceRGB");
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000823 pdfShader->insert("Domain", domain.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +0000824
825 SkPDFStream* function = makePSFunction(functionCode, domain.get());
826 pdfShader->insert("Function", new SkPDFObjRef(function))->unref();
827 fResources.push(function); // Pass ownership to resource list.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000828
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000829 insertInt("PatternType", 2);
830 insert("Matrix", SkPDFUtils::MatrixToArray(finalMatrix))->unref();
831 insert("Shading", pdfShader.get());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000832}
833
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000834SkPDFImageShader::SkPDFImageShader(SkPDFShader::State* state) : fState(state) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000835 fState.get()->fImage.lockPixels();
836
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000837 // The image shader pattern cell will be drawn into a separate device
838 // in pattern cell space (no scaling on the bitmap, though there may be
839 // translations so that all content is in the device, coordinates > 0).
840
841 // Map clip bounds to shader space to ensure the device is large enough
842 // to handle fake clamping.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000843 SkMatrix finalMatrix = fState.get()->fCanvasTransform;
844 finalMatrix.preConcat(fState.get()->fShaderTransform);
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000845 SkRect deviceBounds;
846 deviceBounds.set(fState.get()->fBBox);
847 if (!inverseTransformBBox(finalMatrix, &deviceBounds)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000848 return;
849 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000850
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000851 const SkBitmap* image = &fState.get()->fImage;
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000852 SkRect bitmapBounds;
853 image->getBounds(&bitmapBounds);
854
855 // For tiling modes, the bounds should be extended to include the bitmap,
856 // otherwise the bitmap gets clipped out and the shader is empty and awful.
857 // For clamp modes, we're only interested in the clip region, whether
858 // or not the main bitmap is in it.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000859 SkShader::TileMode tileModes[2];
860 tileModes[0] = fState.get()->fImageTileModes[0];
861 tileModes[1] = fState.get()->fImageTileModes[1];
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000862 if (tileModes[0] != SkShader::kClamp_TileMode ||
863 tileModes[1] != SkShader::kClamp_TileMode) {
864 deviceBounds.join(bitmapBounds);
865 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000866
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000867 SkMatrix unflip;
868 unflip.setTranslate(0, SkScalarRoundToScalar(deviceBounds.height()));
869 unflip.preScale(SK_Scalar1, -SK_Scalar1);
870 SkISize size = SkISize::Make(SkScalarRound(deviceBounds.width()),
871 SkScalarRound(deviceBounds.height()));
commit-bot@chromium.org5e009892013-10-14 13:42:12 +0000872 // TODO(edisonn): should we pass here the DCT encoder of the destination device?
873 // TODO(edisonn): NYI Perspective, use SkPDFDeviceFlattener.
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000874 SkPDFDevice pattern(size, size, unflip);
875 SkCanvas canvas(&pattern);
876
877 SkRect patternBBox;
878 image->getBounds(&patternBBox);
879
880 // Translate the canvas so that the bitmap origin is at (0, 0).
881 canvas.translate(-deviceBounds.left(), -deviceBounds.top());
882 patternBBox.offset(-deviceBounds.left(), -deviceBounds.top());
883 // Undo the translation in the final matrix
884 finalMatrix.preTranslate(deviceBounds.left(), deviceBounds.top());
885
886 // If the bitmap is out of bounds (i.e. clamp mode where we only see the
887 // stretched sides), canvas will clip this out and the extraneous data
888 // won't be saved to the PDF.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000889 canvas.drawBitmap(*image, 0, 0);
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000890
891 SkScalar width = SkIntToScalar(image->width());
892 SkScalar height = SkIntToScalar(image->height());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000893
894 // Tiling is implied. First we handle mirroring.
895 if (tileModes[0] == SkShader::kMirror_TileMode) {
896 SkMatrix xMirror;
897 xMirror.setScale(-1, 1);
898 xMirror.postTranslate(2 * width, 0);
899 canvas.drawBitmapMatrix(*image, xMirror);
900 patternBBox.fRight += width;
901 }
902 if (tileModes[1] == SkShader::kMirror_TileMode) {
903 SkMatrix yMirror;
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000904 yMirror.setScale(SK_Scalar1, -SK_Scalar1);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000905 yMirror.postTranslate(0, 2 * height);
906 canvas.drawBitmapMatrix(*image, yMirror);
907 patternBBox.fBottom += height;
908 }
909 if (tileModes[0] == SkShader::kMirror_TileMode &&
910 tileModes[1] == SkShader::kMirror_TileMode) {
911 SkMatrix mirror;
912 mirror.setScale(-1, -1);
913 mirror.postTranslate(2 * width, 2 * height);
914 canvas.drawBitmapMatrix(*image, mirror);
915 }
916
917 // Then handle Clamping, which requires expanding the pattern canvas to
918 // cover the entire surfaceBBox.
919
920 // If both x and y are in clamp mode, we start by filling in the corners.
921 // (Which are just a rectangles of the corner colors.)
922 if (tileModes[0] == SkShader::kClamp_TileMode &&
923 tileModes[1] == SkShader::kClamp_TileMode) {
924 SkPaint paint;
925 SkRect rect;
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000926 rect = SkRect::MakeLTRB(deviceBounds.left(), deviceBounds.top(), 0, 0);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000927 if (!rect.isEmpty()) {
928 paint.setColor(image->getColor(0, 0));
929 canvas.drawRect(rect, paint);
930 }
931
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000932 rect = SkRect::MakeLTRB(width, deviceBounds.top(),
933 deviceBounds.right(), 0);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000934 if (!rect.isEmpty()) {
vandebo@chromium.org54ff85c2012-03-09 17:18:50 +0000935 paint.setColor(image->getColor(image->width() - 1, 0));
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(width, height,
940 deviceBounds.right(), 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(image->width() - 1,
943 image->height() - 1));
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000944 canvas.drawRect(rect, paint);
945 }
946
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000947 rect = SkRect::MakeLTRB(deviceBounds.left(), height,
948 0, deviceBounds.bottom());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000949 if (!rect.isEmpty()) {
vandebo@chromium.org54ff85c2012-03-09 17:18:50 +0000950 paint.setColor(image->getColor(0, image->height() - 1));
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000951 canvas.drawRect(rect, paint);
952 }
953 }
954
955 // Then expand the left, right, top, then bottom.
956 if (tileModes[0] == SkShader::kClamp_TileMode) {
vandebo@chromium.org54ff85c2012-03-09 17:18:50 +0000957 SkIRect subset = SkIRect::MakeXYWH(0, 0, 1, image->height());
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000958 if (deviceBounds.left() < 0) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000959 SkBitmap left;
960 SkAssertResult(image->extractSubset(&left, subset));
961
962 SkMatrix leftMatrix;
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000963 leftMatrix.setScale(-deviceBounds.left(), 1);
964 leftMatrix.postTranslate(deviceBounds.left(), 0);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000965 canvas.drawBitmapMatrix(left, leftMatrix);
966
967 if (tileModes[1] == SkShader::kMirror_TileMode) {
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000968 leftMatrix.postScale(SK_Scalar1, -SK_Scalar1);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000969 leftMatrix.postTranslate(0, 2 * height);
970 canvas.drawBitmapMatrix(left, leftMatrix);
971 }
vandebo@chromium.orgbe2048a2011-05-02 15:24:01 +0000972 patternBBox.fLeft = 0;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000973 }
974
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000975 if (deviceBounds.right() > width) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000976 SkBitmap right;
vandebo@chromium.org54ff85c2012-03-09 17:18:50 +0000977 subset.offset(image->width() - 1, 0);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000978 SkAssertResult(image->extractSubset(&right, subset));
979
980 SkMatrix rightMatrix;
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000981 rightMatrix.setScale(deviceBounds.right() - width, 1);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000982 rightMatrix.postTranslate(width, 0);
983 canvas.drawBitmapMatrix(right, rightMatrix);
984
985 if (tileModes[1] == SkShader::kMirror_TileMode) {
vandebo@chromium.org663515b2012-01-05 18:45:27 +0000986 rightMatrix.postScale(SK_Scalar1, -SK_Scalar1);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000987 rightMatrix.postTranslate(0, 2 * height);
988 canvas.drawBitmapMatrix(right, rightMatrix);
989 }
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000990 patternBBox.fRight = deviceBounds.width();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000991 }
992 }
993
994 if (tileModes[1] == SkShader::kClamp_TileMode) {
vandebo@chromium.org54ff85c2012-03-09 17:18:50 +0000995 SkIRect subset = SkIRect::MakeXYWH(0, 0, image->width(), 1);
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000996 if (deviceBounds.top() < 0) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000997 SkBitmap top;
998 SkAssertResult(image->extractSubset(&top, subset));
999
1000 SkMatrix topMatrix;
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +00001001 topMatrix.setScale(SK_Scalar1, -deviceBounds.top());
1002 topMatrix.postTranslate(0, deviceBounds.top());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001003 canvas.drawBitmapMatrix(top, topMatrix);
1004
1005 if (tileModes[0] == SkShader::kMirror_TileMode) {
1006 topMatrix.postScale(-1, 1);
1007 topMatrix.postTranslate(2 * width, 0);
1008 canvas.drawBitmapMatrix(top, topMatrix);
1009 }
vandebo@chromium.orgbe2048a2011-05-02 15:24:01 +00001010 patternBBox.fTop = 0;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001011 }
1012
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +00001013 if (deviceBounds.bottom() > height) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001014 SkBitmap bottom;
vandebo@chromium.org54ff85c2012-03-09 17:18:50 +00001015 subset.offset(0, image->height() - 1);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001016 SkAssertResult(image->extractSubset(&bottom, subset));
1017
1018 SkMatrix bottomMatrix;
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +00001019 bottomMatrix.setScale(SK_Scalar1, deviceBounds.bottom() - height);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001020 bottomMatrix.postTranslate(0, height);
1021 canvas.drawBitmapMatrix(bottom, bottomMatrix);
1022
1023 if (tileModes[0] == SkShader::kMirror_TileMode) {
1024 bottomMatrix.postScale(-1, 1);
1025 bottomMatrix.postTranslate(2 * width, 0);
1026 canvas.drawBitmapMatrix(bottom, bottomMatrix);
1027 }
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +00001028 patternBBox.fBottom = deviceBounds.height();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001029 }
1030 }
1031
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001032 // Put the canvas into the pattern stream (fContent).
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001033 SkAutoTUnref<SkStream> content(pattern.content());
1034 setData(content.get());
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001035 SkPDFResourceDict* resourceDict = pattern.getResourceDict();
1036 resourceDict->getReferencedResources(fResources, &fResources, false);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001037
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +00001038 populate_tiling_pattern_dict(this, patternBBox,
1039 pattern.getResourceDict(), finalMatrix);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001040
1041 fState.get()->fImage.unlockPixels();
1042}
1043
vandebo@chromium.org421d6442011-07-20 17:39:01 +00001044SkPDFStream* SkPDFFunctionShader::makePSFunction(const SkString& psCode,
1045 SkPDFArray* domain) {
1046 SkAutoDataUnref funcData(SkData::NewWithCopy(psCode.c_str(),
1047 psCode.size()));
1048 SkPDFStream* result = new SkPDFStream(funcData.get());
reed@google.comc789cf12011-07-20 12:14:33 +00001049 result->insertInt("FunctionType", 4);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001050 result->insert("Domain", domain);
reed@google.comf6c3ebd2011-07-20 17:20:28 +00001051 result->insert("Range", RangeObject());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001052 return result;
1053}
1054
vandebo@chromium.org421d6442011-07-20 17:39:01 +00001055SkPDFShader::ShaderCanonicalEntry::ShaderCanonicalEntry(SkPDFObject* pdfShader,
1056 const State* state)
1057 : fPDFShader(pdfShader),
1058 fState(state) {
1059}
1060
1061bool SkPDFShader::ShaderCanonicalEntry::operator==(
1062 const ShaderCanonicalEntry& b) const {
1063 return fPDFShader == b.fPDFShader ||
1064 (fState != NULL && b.fState != NULL && *fState == *b.fState);
1065}
1066
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001067bool SkPDFShader::State::operator==(const SkPDFShader::State& b) const {
1068 if (fType != b.fType ||
1069 fCanvasTransform != b.fCanvasTransform ||
1070 fShaderTransform != b.fShaderTransform ||
1071 fBBox != b.fBBox) {
1072 return false;
1073 }
1074
1075 if (fType == SkShader::kNone_GradientType) {
1076 if (fPixelGeneration != b.fPixelGeneration ||
1077 fPixelGeneration == 0 ||
1078 fImageTileModes[0] != b.fImageTileModes[0] ||
1079 fImageTileModes[1] != b.fImageTileModes[1]) {
1080 return false;
1081 }
1082 } else {
1083 if (fInfo.fColorCount != b.fInfo.fColorCount ||
1084 memcmp(fInfo.fColors, b.fInfo.fColors,
1085 sizeof(SkColor) * fInfo.fColorCount) != 0 ||
1086 memcmp(fInfo.fColorOffsets, b.fInfo.fColorOffsets,
1087 sizeof(SkScalar) * fInfo.fColorCount) != 0 ||
1088 fInfo.fPoint[0] != b.fInfo.fPoint[0] ||
1089 fInfo.fTileMode != b.fInfo.fTileMode) {
1090 return false;
1091 }
1092
1093 switch (fType) {
1094 case SkShader::kLinear_GradientType:
1095 if (fInfo.fPoint[1] != b.fInfo.fPoint[1]) {
1096 return false;
1097 }
1098 break;
1099 case SkShader::kRadial_GradientType:
1100 if (fInfo.fRadius[0] != b.fInfo.fRadius[0]) {
1101 return false;
1102 }
1103 break;
1104 case SkShader::kRadial2_GradientType:
reed@google.com49085332012-06-11 18:54:07 +00001105 case SkShader::kConical_GradientType:
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001106 if (fInfo.fPoint[1] != b.fInfo.fPoint[1] ||
1107 fInfo.fRadius[0] != b.fInfo.fRadius[0] ||
1108 fInfo.fRadius[1] != b.fInfo.fRadius[1]) {
1109 return false;
1110 }
1111 break;
1112 case SkShader::kSweep_GradientType:
1113 case SkShader::kNone_GradientType:
1114 case SkShader::kColor_GradientType:
1115 break;
1116 }
1117 }
1118 return true;
1119}
1120
1121SkPDFShader::State::State(const SkShader& shader,
1122 const SkMatrix& canvasTransform, const SkIRect& bbox)
1123 : fCanvasTransform(canvasTransform),
vandebo@chromium.orge1bc2742011-06-21 22:26:39 +00001124 fBBox(bbox),
1125 fPixelGeneration(0) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001126 fInfo.fColorCount = 0;
1127 fInfo.fColors = NULL;
1128 fInfo.fColorOffsets = NULL;
bsalomon@google.comf94b3a42012-10-31 18:09:01 +00001129 fShaderTransform = shader.getLocalMatrix();
vandebo@chromium.orge1bc2742011-06-21 22:26:39 +00001130 fImageTileModes[0] = fImageTileModes[1] = SkShader::kClamp_TileMode;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001131
1132 fType = shader.asAGradient(&fInfo);
1133
1134 if (fType == SkShader::kNone_GradientType) {
1135 SkShader::BitmapType bitmapType;
1136 SkMatrix matrix;
rileya@google.com91f319c2012-07-25 17:18:31 +00001137 bitmapType = shader.asABitmap(&fImage, &matrix, fImageTileModes);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001138 if (bitmapType != SkShader::kDefault_BitmapType) {
1139 fImage.reset();
1140 return;
1141 }
1142 SkASSERT(matrix.isIdentity());
1143 fPixelGeneration = fImage.getGenerationID();
1144 } else {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +00001145 AllocateGradientInfoStorage();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001146 shader.asAGradient(&fInfo);
1147 }
1148}
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +00001149
1150SkPDFShader::State::State(const SkPDFShader::State& other)
1151 : fType(other.fType),
1152 fCanvasTransform(other.fCanvasTransform),
1153 fShaderTransform(other.fShaderTransform),
1154 fBBox(other.fBBox)
1155{
1156 // Only gradients supported for now, since that is all that is used.
1157 // If needed, image state copy constructor can be added here later.
1158 SkASSERT(fType != SkShader::kNone_GradientType);
1159
1160 if (fType != SkShader::kNone_GradientType) {
1161 fInfo = other.fInfo;
1162
1163 AllocateGradientInfoStorage();
1164 for (int i = 0; i < fInfo.fColorCount; i++) {
1165 fInfo.fColors[i] = other.fInfo.fColors[i];
1166 fInfo.fColorOffsets[i] = other.fInfo.fColorOffsets[i];
1167 }
1168 }
1169}
1170
1171/**
1172 * Create a copy of this gradient state with alpha assigned to RGB luminousity.
1173 * Only valid for gradient states.
1174 */
1175SkPDFShader::State* SkPDFShader::State::CreateAlphaToLuminosityState() const {
1176 SkASSERT(fType != SkShader::kNone_GradientType);
1177
1178 SkPDFShader::State* newState = new SkPDFShader::State(*this);
1179
1180 for (int i = 0; i < fInfo.fColorCount; i++) {
1181 SkAlpha alpha = SkColorGetA(fInfo.fColors[i]);
1182 newState->fInfo.fColors[i] = SkColorSetARGB(255, alpha, alpha, alpha);
1183 }
1184
1185 return newState;
1186}
1187
1188/**
1189 * Create a copy of this gradient state with alpha set to fully opaque
1190 * Only valid for gradient states.
1191 */
1192SkPDFShader::State* SkPDFShader::State::CreateOpaqueState() const {
1193 SkASSERT(fType != SkShader::kNone_GradientType);
1194
1195 SkPDFShader::State* newState = new SkPDFShader::State(*this);
1196 for (int i = 0; i < fInfo.fColorCount; i++) {
1197 newState->fInfo.fColors[i] = SkColorSetA(fInfo.fColors[i],
1198 SK_AlphaOPAQUE);
1199 }
1200
1201 return newState;
1202}
1203
1204/**
1205 * Returns true if state is a gradient and the gradient has alpha.
1206 */
1207bool SkPDFShader::State::GradientHasAlpha() const {
1208 if (fType == SkShader::kNone_GradientType) {
1209 return false;
1210 }
1211
1212 for (int i = 0; i < fInfo.fColorCount; i++) {
1213 SkAlpha alpha = SkColorGetA(fInfo.fColors[i]);
1214 if (alpha != SK_AlphaOPAQUE) {
1215 return true;
1216 }
1217 }
1218 return false;
1219}
1220
1221void SkPDFShader::State::AllocateGradientInfoStorage() {
1222 fColorData.set(sk_malloc_throw(
1223 fInfo.fColorCount * (sizeof(SkColor) + sizeof(SkScalar))));
1224 fInfo.fColors = reinterpret_cast<SkColor*>(fColorData.get());
1225 fInfo.fColorOffsets =
1226 reinterpret_cast<SkScalar*>(fInfo.fColors + fInfo.fColorCount);
1227}