blob: 62adf5811db5a3672f73f5e1a8796b6c2596b779 [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
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000213/**
214 * Returns PS function code that applies inverse perspective
215 * to a x, y point.
216 * The function assumes that the stack has at least two elements,
217 * and that the top 2 elements are numeric values.
218 * After executing this code on a PS stack, the last 2 elements are updated
219 * while the rest of the stack is preserved intact.
220 * inversePerspectiveMatrix is the inverse perspective matrix.
221 */
222static SkString apply_perspective_to_coordinates(
223 const SkMatrix& inversePerspectiveMatrix) {
224 SkString code;
225 if (!inversePerspectiveMatrix.hasPerspective()) {
226 return code;
227 }
228
229 // Perspective matrix should be:
230 // 1 0 0
231 // 0 1 0
232 // p0 p1 p2
233
234 const SkScalar p0 = inversePerspectiveMatrix[SkMatrix::kMPersp0];
235 const SkScalar p1 = inversePerspectiveMatrix[SkMatrix::kMPersp1];
236 const SkScalar p2 = inversePerspectiveMatrix[SkMatrix::kMPersp2];
237
238 // y = y / (p2 + p0 x + p1 y)
239 // x = x / (p2 + p0 x + p1 y)
240
241 // Input on stack: x y
242 code.append(" dup "); // x y y
243 code.appendScalar(p1); // x y y p1
244 code.append(" mul " // x y y*p1
245 " 2 index "); // x y y*p1 x
246 code.appendScalar(p0); // x y y p1 x p0
247 code.append(" mul "); // x y y*p1 x*p0
248 code.appendScalar(p2); // x y y p1 x*p0 p2
249 code.append(" add " // x y y*p1 x*p0+p2
250 "add " // x y y*p1+x*p0+p2
251 "3 1 roll " // y*p1+x*p0+p2 x y
252 "2 index " // z x y y*p1+x*p0+p2
253 "div " // y*p1+x*p0+p2 x y/(y*p1+x*p0+p2)
254 "3 1 roll " // y/(y*p1+x*p0+p2) y*p1+x*p0+p2 x
255 "exch " // y/(y*p1+x*p0+p2) x y*p1+x*p0+p2
256 "div " // y/(y*p1+x*p0+p2) x/(y*p1+x*p0+p2)
257 "exch\n"); // x/(y*p1+x*p0+p2) y/(y*p1+x*p0+p2)
258 return code;
259}
260
261static SkString linearCode(const SkShader::GradientInfo& info,
262 const SkMatrix& perspectiveRemover) {
263 SkString function("{");
264
265 function.append(apply_perspective_to_coordinates(perspectiveRemover));
266
267 function.append("pop\n"); // Just ditch the y value.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000268 tileModeCode(info.fTileMode, &function);
269 gradientFunctionCode(info, &function);
270 function.append("}");
271 return function;
272}
273
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000274static SkString radialCode(const SkShader::GradientInfo& info,
275 const SkMatrix& perspectiveRemover) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000276 SkString function("{");
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000277
278 function.append(apply_perspective_to_coordinates(perspectiveRemover));
279
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000280 // Find the distance from the origin.
281 function.append("dup " // x y y
282 "mul " // x y^2
283 "exch " // y^2 x
284 "dup " // y^2 x x
285 "mul " // y^2 x^2
286 "add " // y^2+x^2
287 "sqrt\n"); // sqrt(y^2+x^2)
288
289 tileModeCode(info.fTileMode, &function);
290 gradientFunctionCode(info, &function);
291 function.append("}");
292 return function;
293}
294
295/* The math here is all based on the description in Two_Point_Radial_Gradient,
296 with one simplification, the coordinate space has been scaled so that
297 Dr = 1. This means we don't need to scale the entire equation by 1/Dr^2.
298 */
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000299static SkString twoPointRadialCode(const SkShader::GradientInfo& info,
300 const SkMatrix& perspectiveRemover) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000301 SkScalar dx = info.fPoint[0].fX - info.fPoint[1].fX;
302 SkScalar dy = info.fPoint[0].fY - info.fPoint[1].fY;
303 SkScalar sr = info.fRadius[0];
304 SkScalar a = SkScalarMul(dx, dx) + SkScalarMul(dy, dy) - SK_Scalar1;
305 bool posRoot = info.fRadius[1] > info.fRadius[0];
306
307 // We start with a stack of (x y), copy it and then consume one copy in
308 // order to calculate b and the other to calculate c.
309 SkString function("{");
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000310
311 function.append(apply_perspective_to_coordinates(perspectiveRemover));
312
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000313 function.append("2 copy ");
314
315 // Calculate -b and b^2.
316 function.appendScalar(dy);
317 function.append(" mul exch ");
318 function.appendScalar(dx);
319 function.append(" mul add ");
320 function.appendScalar(sr);
321 function.append(" sub 2 mul neg dup dup mul\n");
322
323 // Calculate c
324 function.append("4 2 roll dup mul exch dup mul add ");
325 function.appendScalar(SkScalarMul(sr, sr));
326 function.append(" sub\n");
327
328 // Calculate the determinate
329 function.appendScalar(SkScalarMul(SkIntToScalar(4), a));
330 function.append(" mul sub abs sqrt\n");
331
332 // And then the final value of t.
333 if (posRoot) {
334 function.append("sub ");
335 } else {
336 function.append("add ");
337 }
338 function.appendScalar(SkScalarMul(SkIntToScalar(2), a));
339 function.append(" div\n");
340
341 tileModeCode(info.fTileMode, &function);
342 gradientFunctionCode(info, &function);
343 function.append("}");
344 return function;
345}
346
rileya@google.com62197282012-07-10 20:05:23 +0000347/* Conical gradient shader, based on the Canvas spec for radial gradients
rmistry@google.comd6176b02012-08-23 18:14:13 +0000348 See: http://www.w3.org/TR/2dcontext/#dom-context-2d-createradialgradient
rileya@google.com62197282012-07-10 20:05:23 +0000349 */
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000350static SkString twoPointConicalCode(const SkShader::GradientInfo& info,
351 const SkMatrix& perspectiveRemover) {
rileya@google.com62197282012-07-10 20:05:23 +0000352 SkScalar dx = info.fPoint[1].fX - info.fPoint[0].fX;
353 SkScalar dy = info.fPoint[1].fY - info.fPoint[0].fY;
354 SkScalar r0 = info.fRadius[0];
355 SkScalar dr = info.fRadius[1] - info.fRadius[0];
rmistry@google.comd6176b02012-08-23 18:14:13 +0000356 SkScalar a = SkScalarMul(dx, dx) + SkScalarMul(dy, dy) -
rileya@google.com62197282012-07-10 20:05:23 +0000357 SkScalarMul(dr, dr);
358
359 // First compute t, if the pixel falls outside the cone, then we'll end
360 // with 'false' on the stack, otherwise we'll push 'true' with t below it
361
362 // We start with a stack of (x y), copy it and then consume one copy in
363 // order to calculate b and the other to calculate c.
364 SkString function("{");
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000365
366 function.append(apply_perspective_to_coordinates(perspectiveRemover));
367
rileya@google.com62197282012-07-10 20:05:23 +0000368 function.append("2 copy ");
369
370 // Calculate b and b^2; b = -2 * (y * dy + x * dx + r0 * dr).
371 function.appendScalar(dy);
372 function.append(" mul exch ");
373 function.appendScalar(dx);
374 function.append(" mul add ");
375 function.appendScalar(SkScalarMul(r0, dr));
376 function.append(" add -2 mul dup dup mul\n");
377
378 // c = x^2 + y^2 + radius0^2
379 function.append("4 2 roll dup mul exch dup mul add ");
380 function.appendScalar(SkScalarMul(r0, r0));
381 function.append(" sub dup 4 1 roll\n");
382
383 // Contents of the stack at this point: c, b, b^2, c
384
385 // if a = 0, then we collapse to a simpler linear case
386 if (a == 0) {
387
388 // t = -c/b
389 function.append("pop pop div neg dup ");
390
391 // compute radius(t)
392 function.appendScalar(dr);
393 function.append(" mul ");
394 function.appendScalar(r0);
395 function.append(" add\n");
396
397 // if r(t) < 0, then it's outside the cone
rileya@google.comab2fe822012-07-10 20:41:38 +0000398 function.append("0 lt {pop false} {true} ifelse\n");
rileya@google.com62197282012-07-10 20:05:23 +0000399
400 } else {
401
402 // quadratic case: the Canvas spec wants the largest
403 // root t for which radius(t) > 0
rmistry@google.comd6176b02012-08-23 18:14:13 +0000404
rileya@google.com62197282012-07-10 20:05:23 +0000405 // compute the discriminant (b^2 - 4ac)
406 function.appendScalar(SkScalarMul(SkIntToScalar(4), a));
407 function.append(" mul sub dup\n");
408
409 // if d >= 0, proceed
410 function.append("0 ge {\n");
411
412 // an intermediate value we'll use to compute the roots:
413 // q = -0.5 * (b +/- sqrt(d))
414 function.append("sqrt exch dup 0 lt {exch -1 mul} if");
415 function.append(" add -0.5 mul dup\n");
416
417 // first root = q / a
418 function.appendScalar(a);
419 function.append(" div\n");
420
421 // second root = c / q
422 function.append("3 1 roll div\n");
423
424 // put the larger root on top of the stack
425 function.append("2 copy gt {exch} if\n");
426
427 // compute radius(t) for larger root
428 function.append("dup ");
429 function.appendScalar(dr);
430 function.append(" mul ");
431 function.appendScalar(r0);
432 function.append(" add\n");
433
434 // if r(t) > 0, we have our t, pop off the smaller root and we're done
435 function.append(" 0 gt {exch pop true}\n");
436
437 // otherwise, throw out the larger one and try the smaller root
438 function.append("{pop dup\n");
439 function.appendScalar(dr);
440 function.append(" mul ");
441 function.appendScalar(r0);
442 function.append(" add\n");
443
444 // if r(t) < 0, push false, otherwise the smaller root is our t
rileya@google.comab2fe822012-07-10 20:41:38 +0000445 function.append("0 le {pop false} {true} ifelse\n");
rileya@google.com62197282012-07-10 20:05:23 +0000446 function.append("} ifelse\n");
447
448 // d < 0, clear the stack and push false
rileya@google.comab2fe822012-07-10 20:41:38 +0000449 function.append("} {pop pop pop false} ifelse\n");
rileya@google.com62197282012-07-10 20:05:23 +0000450 }
451
452 // if the pixel is in the cone, proceed to compute a color
453 function.append("{");
454 tileModeCode(info.fTileMode, &function);
455 gradientFunctionCode(info, &function);
456
457 // otherwise, just write black
458 function.append("} {0 0 0} ifelse }");
459
460 return function;
461}
462
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000463static SkString sweepCode(const SkShader::GradientInfo& info,
464 const SkMatrix& perspectiveRemover) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000465 SkString function("{exch atan 360 div\n");
466 tileModeCode(info.fTileMode, &function);
467 gradientFunctionCode(info, &function);
468 function.append("}");
469 return function;
470}
471
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000472class SkPDFShader::State {
473public:
474 SkShader::GradientType fType;
475 SkShader::GradientInfo fInfo;
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000476 SkAutoFree fColorData; // This provides storage for arrays in fInfo.
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000477 SkMatrix fCanvasTransform;
478 SkMatrix fShaderTransform;
479 SkIRect fBBox;
480
481 SkBitmap fImage;
482 uint32_t fPixelGeneration;
483 SkShader::TileMode fImageTileModes[2];
484
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000485 State(const SkShader& shader, const SkMatrix& canvasTransform,
486 const SkIRect& bbox);
487
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000488 bool operator==(const State& b) const;
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000489
490 SkPDFShader::State* CreateAlphaToLuminosityState() const;
491 SkPDFShader::State* CreateOpaqueState() const;
492
493 bool GradientHasAlpha() const;
494
495private:
496 State(const State& other);
497 State operator=(const State& rhs);
498 void AllocateGradientInfoStorage();
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000499};
500
501class SkPDFFunctionShader : public SkPDFDict, public SkPDFShader {
commit-bot@chromium.orgab1c1382013-12-05 12:08:12 +0000502 SK_DECLARE_INST_COUNT(SkPDFFunctionShader)
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000503public:
ctguil@chromium.orga5c72342011-08-15 23:55:03 +0000504 explicit SkPDFFunctionShader(SkPDFShader::State* state);
robertphillips@google.com05141c22012-04-27 12:54:01 +0000505 virtual ~SkPDFFunctionShader() {
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000506 if (isValid()) {
507 RemoveShader(this);
508 }
509 fResources.unrefAll();
510 }
511
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000512 virtual bool isValid() { return fResources.count() > 0; }
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000513
edisonn@google.com6addb192013-04-02 15:33:08 +0000514 void getResources(const SkTSet<SkPDFObject*>& knownResourceObjects,
515 SkTSet<SkPDFObject*>* newResourceObjects) {
516 GetResourcesHelper(&fResources,
517 knownResourceObjects,
518 newResourceObjects);
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000519 }
520
521private:
522 static SkPDFObject* RangeObject();
523
524 SkTDArray<SkPDFObject*> fResources;
525 SkAutoTDelete<const SkPDFShader::State> fState;
526
527 SkPDFStream* makePSFunction(const SkString& psCode, SkPDFArray* domain);
commit-bot@chromium.orgab1c1382013-12-05 12:08:12 +0000528 typedef SkPDFDict INHERITED;
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000529};
530
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000531/**
532 * A shader for PDF gradients. This encapsulates the function shader
533 * inside a tiling pattern while providing a common pattern interface.
534 * The encapsulation allows the use of a SMask for transparency gradients.
535 */
536class SkPDFAlphaFunctionShader : public SkPDFStream, public SkPDFShader {
537public:
538 explicit SkPDFAlphaFunctionShader(SkPDFShader::State* state);
539 virtual ~SkPDFAlphaFunctionShader() {
540 if (isValid()) {
541 RemoveShader(this);
542 }
543 }
544
545 virtual bool isValid() {
546 return fColorShader.get() != NULL;
547 }
548
549private:
550 SkAutoTDelete<const SkPDFShader::State> fState;
551
552 SkPDFGraphicState* CreateSMaskGraphicState();
553
554 void getResources(const SkTSet<SkPDFObject*>& knownResourceObjects,
555 SkTSet<SkPDFObject*>* newResourceObjects) {
556 fResourceDict->getReferencedResources(knownResourceObjects,
557 newResourceObjects,
558 true);
559 }
560
561 SkAutoTUnref<SkPDFObject> fColorShader;
562 SkAutoTUnref<SkPDFResourceDict> fResourceDict;
563};
564
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000565class SkPDFImageShader : public SkPDFStream, public SkPDFShader {
566public:
ctguil@chromium.orga5c72342011-08-15 23:55:03 +0000567 explicit SkPDFImageShader(SkPDFShader::State* state);
robertphillips@google.com05141c22012-04-27 12:54:01 +0000568 virtual ~SkPDFImageShader() {
edisonn@google.com8e473762013-07-23 19:45:38 +0000569 if (isValid()) {
570 RemoveShader(this);
571 }
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000572 fResources.unrefAll();
573 }
574
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000575 virtual bool isValid() { return size() > 0; }
576
edisonn@google.com6addb192013-04-02 15:33:08 +0000577 void getResources(const SkTSet<SkPDFObject*>& knownResourceObjects,
578 SkTSet<SkPDFObject*>* newResourceObjects) {
579 GetResourcesHelper(&fResources.toArray(),
580 knownResourceObjects,
581 newResourceObjects);
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000582 }
583
584private:
edisonn@google.com6addb192013-04-02 15:33:08 +0000585 SkTSet<SkPDFObject*> fResources;
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000586 SkAutoTDelete<const SkPDFShader::State> fState;
587};
588
589SkPDFShader::SkPDFShader() {}
590
591// static
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000592SkPDFObject* SkPDFShader::GetPDFShaderByState(State* inState) {
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000593 SkPDFObject* result;
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000594
595 SkAutoTDelete<State> shaderState(inState);
vandebo@chromium.orgda6c5692012-06-28 21:37:20 +0000596 if (shaderState.get()->fType == SkShader::kNone_GradientType &&
597 shaderState.get()->fImage.isNull()) {
598 // TODO(vandebo) This drops SKComposeShader on the floor. We could
599 // handle compose shader by pulling things up to a layer, drawing with
600 // the first shader, applying the xfer mode and drawing again with the
601 // second shader, then applying the layer to the original drawing.
602 return NULL;
603 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000604
605 ShaderCanonicalEntry entry(NULL, shaderState.get());
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +0000606 int index = CanonicalShaders().find(entry);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000607 if (index >= 0) {
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000608 result = CanonicalShaders()[index].fPDFShader;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000609 result->ref();
610 return result;
611 }
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000612
613 bool valid = false;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000614 // The PDFShader takes ownership of the shaderSate.
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000615 if (shaderState.get()->fType == SkShader::kNone_GradientType) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000616 SkPDFImageShader* imageShader =
617 new SkPDFImageShader(shaderState.detach());
618 valid = imageShader->isValid();
619 result = imageShader;
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000620 } else {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000621 if (shaderState.get()->GradientHasAlpha()) {
622 SkPDFAlphaFunctionShader* gradientShader =
623 SkNEW_ARGS(SkPDFAlphaFunctionShader, (shaderState.detach()));
624 valid = gradientShader->isValid();
625 result = gradientShader;
626 } else {
627 SkPDFFunctionShader* functionShader =
628 SkNEW_ARGS(SkPDFFunctionShader, (shaderState.detach()));
629 valid = functionShader->isValid();
630 result = functionShader;
631 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000632 }
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000633 if (!valid) {
634 delete result;
635 return NULL;
636 }
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000637 entry.fPDFShader = result;
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +0000638 CanonicalShaders().push(entry);
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000639 return result; // return the reference that came from new.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000640}
641
642// static
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000643void SkPDFShader::RemoveShader(SkPDFObject* shader) {
644 SkAutoMutexAcquire lock(CanonicalShadersMutex());
645 ShaderCanonicalEntry entry(shader, NULL);
646 int index = CanonicalShaders().find(entry);
647 SkASSERT(index >= 0);
648 CanonicalShaders().removeShuffle(index);
649}
650
651// static
652SkPDFObject* SkPDFShader::GetPDFShader(const SkShader& shader,
653 const SkMatrix& matrix,
654 const SkIRect& surfaceBBox) {
655 SkAutoMutexAcquire lock(CanonicalShadersMutex());
656 return GetPDFShaderByState(
657 SkNEW_ARGS(State, (shader, matrix, surfaceBBox)));
658}
659
660// static
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +0000661SkTDArray<SkPDFShader::ShaderCanonicalEntry>& SkPDFShader::CanonicalShaders() {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000662 // This initialization is only thread safe with gcc.
663 static SkTDArray<ShaderCanonicalEntry> gCanonicalShaders;
664 return gCanonicalShaders;
665}
666
667// static
digit@google.com1771cbf2012-01-26 21:26:40 +0000668SkBaseMutex& SkPDFShader::CanonicalShadersMutex() {
669 // This initialization is only thread safe with gcc or when
670 // POD-style mutex initialization is used.
671 SK_DECLARE_STATIC_MUTEX(gCanonicalShadersMutex);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000672 return gCanonicalShadersMutex;
673}
674
675// static
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000676SkPDFObject* SkPDFFunctionShader::RangeObject() {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000677 // This initialization is only thread safe with gcc.
678 static SkPDFArray* range = NULL;
vandebo@chromium.orgb88cfe52011-07-18 18:40:32 +0000679 // This method is only used with CanonicalShadersMutex, so it's safe to
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000680 // populate domain.
681 if (range == NULL) {
682 range = new SkPDFArray;
683 range->reserve(6);
reed@google.comc789cf12011-07-20 12:14:33 +0000684 range->appendInt(0);
685 range->appendInt(1);
686 range->appendInt(0);
687 range->appendInt(1);
688 range->appendInt(0);
689 range->appendInt(1);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000690 }
691 return range;
692}
693
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +0000694static SkPDFResourceDict* get_gradient_resource_dict(
695 SkPDFObject* functionShader,
696 SkPDFObject* gState) {
697 SkPDFResourceDict* dict = new SkPDFResourceDict();
698
699 if (functionShader != NULL) {
700 dict->insertResourceAsReference(
701 SkPDFResourceDict::kPattern_ResourceType, 0, functionShader);
702 }
703 if (gState != NULL) {
704 dict->insertResourceAsReference(
705 SkPDFResourceDict::kExtGState_ResourceType, 0, gState);
706 }
707
708 return dict;
709}
710
711static void populate_tiling_pattern_dict(SkPDFDict* pattern,
712 SkRect& bbox, SkPDFDict* resources,
713 const SkMatrix& matrix) {
714 const int kTiling_PatternType = 1;
715 const int kColoredTilingPattern_PaintType = 1;
716 const int kConstantSpacing_TilingType = 1;
717
718 pattern->insertName("Type", "Pattern");
719 pattern->insertInt("PatternType", kTiling_PatternType);
720 pattern->insertInt("PaintType", kColoredTilingPattern_PaintType);
721 pattern->insertInt("TilingType", kConstantSpacing_TilingType);
722 pattern->insert("BBox", SkPDFUtils::RectToArray(bbox))->unref();
723 pattern->insertScalar("XStep", bbox.width());
724 pattern->insertScalar("YStep", bbox.height());
725 pattern->insert("Resources", resources);
726 if (!matrix.isIdentity()) {
727 pattern->insert("Matrix", SkPDFUtils::MatrixToArray(matrix))->unref();
728 }
729}
730
731/**
732 * Creates a content stream which fills the pattern P0 across bounds.
733 * @param gsIndex A graphics state resource index to apply, or <0 if no
734 * graphics state to apply.
735 */
736static SkStream* create_pattern_fill_content(int gsIndex, SkRect& bounds) {
737 SkDynamicMemoryWStream content;
738 if (gsIndex >= 0) {
739 SkPDFUtils::ApplyGraphicState(gsIndex, &content);
740 }
741 SkPDFUtils::ApplyPattern(0, &content);
742 SkPDFUtils::AppendRectangle(bounds, &content);
743 SkPDFUtils::PaintPath(SkPaint::kFill_Style, SkPath::kEvenOdd_FillType,
744 &content);
745
746 return content.detachAsStream();
747}
748
749/**
750 * Creates a ExtGState with the SMask set to the luminosityShader in
751 * luminosity mode. The shader pattern extends to the bbox.
752 */
753SkPDFGraphicState* SkPDFAlphaFunctionShader::CreateSMaskGraphicState() {
754 SkRect bbox;
755 bbox.set(fState.get()->fBBox);
756
757 SkAutoTUnref<SkPDFObject> luminosityShader(
758 SkPDFShader::GetPDFShaderByState(
759 fState->CreateAlphaToLuminosityState()));
760
761 SkAutoTUnref<SkStream> alphaStream(create_pattern_fill_content(-1, bbox));
762
763 SkAutoTUnref<SkPDFResourceDict>
764 resources(get_gradient_resource_dict(luminosityShader, NULL));
765
766 SkAutoTUnref<SkPDFFormXObject> alphaMask(
767 new SkPDFFormXObject(alphaStream.get(), bbox, resources.get()));
768
769 return SkPDFGraphicState::GetSMaskGraphicState(
770 alphaMask.get(), false,
771 SkPDFGraphicState::kLuminosity_SMaskMode);
772}
773
774SkPDFAlphaFunctionShader::SkPDFAlphaFunctionShader(SkPDFShader::State* state)
775 : fState(state) {
776 SkRect bbox;
777 bbox.set(fState.get()->fBBox);
778
779 fColorShader.reset(
780 SkPDFShader::GetPDFShaderByState(state->CreateOpaqueState()));
781
782 // Create resource dict with alpha graphics state as G0 and
783 // pattern shader as P0, then write content stream.
784 SkAutoTUnref<SkPDFGraphicState> alphaGs(CreateSMaskGraphicState());
785 fResourceDict.reset(
786 get_gradient_resource_dict(fColorShader.get(), alphaGs.get()));
787
788 SkAutoTUnref<SkStream> colorStream(
789 create_pattern_fill_content(0, bbox));
790 setData(colorStream.get());
791
792 populate_tiling_pattern_dict(this, bbox, fResourceDict.get(),
793 SkMatrix::I());
794}
795
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000796// Finds affine and persp such that in = affine * persp.
797// but it returns the inverse of perspective matrix.
798static bool split_perspective(const SkMatrix in, SkMatrix* affine,
799 SkMatrix* perspectiveInverse) {
800 const SkScalar p2 = in[SkMatrix::kMPersp2];
801
802 if (SkScalarNearlyZero(p2)) {
803 return false;
804 }
805
806 const SkScalar zero = SkIntToScalar(0);
807 const SkScalar one = SkIntToScalar(1);
808
809 const SkScalar sx = in[SkMatrix::kMScaleX];
810 const SkScalar kx = in[SkMatrix::kMSkewX];
811 const SkScalar tx = in[SkMatrix::kMTransX];
812 const SkScalar ky = in[SkMatrix::kMSkewY];
813 const SkScalar sy = in[SkMatrix::kMScaleY];
814 const SkScalar ty = in[SkMatrix::kMTransY];
815 const SkScalar p0 = in[SkMatrix::kMPersp0];
816 const SkScalar p1 = in[SkMatrix::kMPersp1];
817
818 // Perspective matrix would be:
819 // 1 0 0
820 // 0 1 0
821 // p0 p1 p2
822 // But we need the inverse of persp.
823 perspectiveInverse->setAll(one, zero, zero,
824 zero, one, zero,
825 -p0/p2, -p1/p2, 1/p2);
826
827 affine->setAll(sx - p0 * tx / p2, kx - p1 * tx / p2, tx / p2,
828 ky - p0 * ty / p2, sy - p1 * ty / p2, ty / p2,
829 zero, zero, one);
830
831 return true;
832}
833
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000834SkPDFFunctionShader::SkPDFFunctionShader(SkPDFShader::State* state)
835 : SkPDFDict("Pattern"),
836 fState(state) {
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000837 SkString (*codeFunction)(const SkShader::GradientInfo& info,
838 const SkMatrix& perspectiveRemover) = NULL;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000839 SkPoint transformPoints[2];
840
841 // Depending on the type of the gradient, we want to transform the
842 // coordinate space in different ways.
843 const SkShader::GradientInfo* info = &fState.get()->fInfo;
844 transformPoints[0] = info->fPoint[0];
845 transformPoints[1] = info->fPoint[1];
846 switch (fState.get()->fType) {
847 case SkShader::kLinear_GradientType:
848 codeFunction = &linearCode;
849 break;
850 case SkShader::kRadial_GradientType:
851 transformPoints[1] = transformPoints[0];
852 transformPoints[1].fX += info->fRadius[0];
853 codeFunction = &radialCode;
854 break;
855 case SkShader::kRadial2_GradientType: {
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000856 // Bail out if the radii are the same. Empty fResources signals
857 // an error and isValid will return false.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000858 if (info->fRadius[0] == info->fRadius[1]) {
859 return;
860 }
861 transformPoints[1] = transformPoints[0];
862 SkScalar dr = info->fRadius[1] - info->fRadius[0];
863 transformPoints[1].fX += dr;
864 codeFunction = &twoPointRadialCode;
865 break;
866 }
rileya@google.com62197282012-07-10 20:05:23 +0000867 case SkShader::kConical_GradientType: {
868 transformPoints[1] = transformPoints[0];
869 transformPoints[1].fX += SK_Scalar1;
870 codeFunction = &twoPointConicalCode;
871 break;
872 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000873 case SkShader::kSweep_GradientType:
874 transformPoints[1] = transformPoints[0];
vandebo@chromium.orgc39c8672012-04-17 21:46:18 +0000875 transformPoints[1].fX += SK_Scalar1;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000876 codeFunction = &sweepCode;
877 break;
878 case SkShader::kColor_GradientType:
879 case SkShader::kNone_GradientType:
vandebo@chromium.org020798a2011-12-21 01:49:35 +0000880 default:
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000881 return;
882 }
883
884 // Move any scaling (assuming a unit gradient) or translation
885 // (and rotation for linear gradient), of the final gradient from
886 // info->fPoints to the matrix (updating bbox appropriately). Now
887 // the gradient can be drawn on on the unit segment.
888 SkMatrix mapperMatrix;
889 unitToPointsMatrix(transformPoints, &mapperMatrix);
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000890
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000891 SkMatrix finalMatrix = fState.get()->fCanvasTransform;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000892 finalMatrix.preConcat(fState.get()->fShaderTransform);
commit-bot@chromium.orgace22692013-06-12 21:33:02 +0000893 finalMatrix.preConcat(mapperMatrix);
894
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000895 // Preserves as much as posible in the final matrix, and only removes
896 // the perspective. The inverse of the perspective is stored in
897 // perspectiveInverseOnly matrix and has 3 useful numbers
898 // (p0, p1, p2), while everything else is either 0 or 1.
899 // In this way the shader will handle it eficiently, with minimal code.
900 SkMatrix perspectiveInverseOnly = SkMatrix::I();
901 if (finalMatrix.hasPerspective()) {
902 if (!split_perspective(finalMatrix,
903 &finalMatrix, &perspectiveInverseOnly)) {
904 return;
905 }
906 }
907
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000908 SkRect bbox;
909 bbox.set(fState.get()->fBBox);
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000910 if (!inverseTransformBBox(finalMatrix, &bbox)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000911 return;
912 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000913
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +0000914 SkAutoTUnref<SkPDFArray> domain(new SkPDFArray);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000915 domain->reserve(4);
reed@google.comc789cf12011-07-20 12:14:33 +0000916 domain->appendScalar(bbox.fLeft);
917 domain->appendScalar(bbox.fRight);
918 domain->appendScalar(bbox.fTop);
919 domain->appendScalar(bbox.fBottom);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000920
921 SkString functionCode;
922 // The two point radial gradient further references fState.get()->fInfo
923 // in translating from x, y coordinates to the t parameter. So, we have
924 // to transform the points and radii according to the calculated matrix.
925 if (fState.get()->fType == SkShader::kRadial2_GradientType) {
926 SkShader::GradientInfo twoPointRadialInfo = *info;
927 SkMatrix inverseMapperMatrix;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000928 if (!mapperMatrix.invert(&inverseMapperMatrix)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000929 return;
vandebo@chromium.orgb0549902012-04-13 20:45:46 +0000930 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000931 inverseMapperMatrix.mapPoints(twoPointRadialInfo.fPoint, 2);
932 twoPointRadialInfo.fRadius[0] =
933 inverseMapperMatrix.mapRadius(info->fRadius[0]);
934 twoPointRadialInfo.fRadius[1] =
935 inverseMapperMatrix.mapRadius(info->fRadius[1]);
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000936 functionCode = codeFunction(twoPointRadialInfo, perspectiveInverseOnly);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000937 } else {
edisonn@google.com83d8eda2013-10-24 13:19:28 +0000938 functionCode = codeFunction(*info, perspectiveInverseOnly);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000939 }
940
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +0000941 SkAutoTUnref<SkPDFDict> pdfShader(new SkPDFDict);
reed@google.comc789cf12011-07-20 12:14:33 +0000942 pdfShader->insertInt("ShadingType", 1);
943 pdfShader->insertName("ColorSpace", "DeviceRGB");
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000944 pdfShader->insert("Domain", domain.get());
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +0000945
946 SkPDFStream* function = makePSFunction(functionCode, domain.get());
947 pdfShader->insert("Function", new SkPDFObjRef(function))->unref();
948 fResources.push(function); // Pass ownership to resource list.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000949
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000950 insertInt("PatternType", 2);
951 insert("Matrix", SkPDFUtils::MatrixToArray(finalMatrix))->unref();
952 insert("Shading", pdfShader.get());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000953}
954
vandebo@chromium.org421d6442011-07-20 17:39:01 +0000955SkPDFImageShader::SkPDFImageShader(SkPDFShader::State* state) : fState(state) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000956 fState.get()->fImage.lockPixels();
957
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000958 // The image shader pattern cell will be drawn into a separate device
959 // in pattern cell space (no scaling on the bitmap, though there may be
960 // translations so that all content is in the device, coordinates > 0).
961
962 // Map clip bounds to shader space to ensure the device is large enough
963 // to handle fake clamping.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000964 SkMatrix finalMatrix = fState.get()->fCanvasTransform;
965 finalMatrix.preConcat(fState.get()->fShaderTransform);
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000966 SkRect deviceBounds;
967 deviceBounds.set(fState.get()->fBBox);
968 if (!inverseTransformBBox(finalMatrix, &deviceBounds)) {
vandebo@chromium.org386dfc02012-04-17 22:31:52 +0000969 return;
970 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000971
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000972 const SkBitmap* image = &fState.get()->fImage;
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000973 SkRect bitmapBounds;
974 image->getBounds(&bitmapBounds);
975
976 // For tiling modes, the bounds should be extended to include the bitmap,
977 // otherwise the bitmap gets clipped out and the shader is empty and awful.
978 // For clamp modes, we're only interested in the clip region, whether
979 // or not the main bitmap is in it.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000980 SkShader::TileMode tileModes[2];
981 tileModes[0] = fState.get()->fImageTileModes[0];
982 tileModes[1] = fState.get()->fImageTileModes[1];
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000983 if (tileModes[0] != SkShader::kClamp_TileMode ||
984 tileModes[1] != SkShader::kClamp_TileMode) {
985 deviceBounds.join(bitmapBounds);
986 }
vandebo@chromium.orgda912d62011-03-08 18:31:02 +0000987
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000988 SkMatrix unflip;
989 unflip.setTranslate(0, SkScalarRoundToScalar(deviceBounds.height()));
990 unflip.preScale(SK_Scalar1, -SK_Scalar1);
reed@google.come1ca7052013-12-17 19:22:07 +0000991 SkISize size = SkISize::Make(SkScalarRoundToInt(deviceBounds.width()),
992 SkScalarRoundToInt(deviceBounds.height()));
commit-bot@chromium.org5e009892013-10-14 13:42:12 +0000993 // TODO(edisonn): should we pass here the DCT encoder of the destination device?
994 // TODO(edisonn): NYI Perspective, use SkPDFDeviceFlattener.
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +0000995 SkPDFDevice pattern(size, size, unflip);
996 SkCanvas canvas(&pattern);
997
998 SkRect patternBBox;
999 image->getBounds(&patternBBox);
1000
1001 // Translate the canvas so that the bitmap origin is at (0, 0).
1002 canvas.translate(-deviceBounds.left(), -deviceBounds.top());
1003 patternBBox.offset(-deviceBounds.left(), -deviceBounds.top());
1004 // Undo the translation in the final matrix
1005 finalMatrix.preTranslate(deviceBounds.left(), deviceBounds.top());
1006
1007 // If the bitmap is out of bounds (i.e. clamp mode where we only see the
1008 // stretched sides), canvas will clip this out and the extraneous data
1009 // won't be saved to the PDF.
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001010 canvas.drawBitmap(*image, 0, 0);
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +00001011
1012 SkScalar width = SkIntToScalar(image->width());
1013 SkScalar height = SkIntToScalar(image->height());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001014
1015 // Tiling is implied. First we handle mirroring.
1016 if (tileModes[0] == SkShader::kMirror_TileMode) {
1017 SkMatrix xMirror;
1018 xMirror.setScale(-1, 1);
1019 xMirror.postTranslate(2 * width, 0);
1020 canvas.drawBitmapMatrix(*image, xMirror);
1021 patternBBox.fRight += width;
1022 }
1023 if (tileModes[1] == SkShader::kMirror_TileMode) {
1024 SkMatrix yMirror;
vandebo@chromium.org663515b2012-01-05 18:45:27 +00001025 yMirror.setScale(SK_Scalar1, -SK_Scalar1);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001026 yMirror.postTranslate(0, 2 * height);
1027 canvas.drawBitmapMatrix(*image, yMirror);
1028 patternBBox.fBottom += height;
1029 }
1030 if (tileModes[0] == SkShader::kMirror_TileMode &&
1031 tileModes[1] == SkShader::kMirror_TileMode) {
1032 SkMatrix mirror;
1033 mirror.setScale(-1, -1);
1034 mirror.postTranslate(2 * width, 2 * height);
1035 canvas.drawBitmapMatrix(*image, mirror);
1036 }
1037
1038 // Then handle Clamping, which requires expanding the pattern canvas to
1039 // cover the entire surfaceBBox.
1040
1041 // If both x and y are in clamp mode, we start by filling in the corners.
1042 // (Which are just a rectangles of the corner colors.)
1043 if (tileModes[0] == SkShader::kClamp_TileMode &&
1044 tileModes[1] == SkShader::kClamp_TileMode) {
1045 SkPaint paint;
1046 SkRect rect;
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +00001047 rect = SkRect::MakeLTRB(deviceBounds.left(), deviceBounds.top(), 0, 0);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001048 if (!rect.isEmpty()) {
1049 paint.setColor(image->getColor(0, 0));
1050 canvas.drawRect(rect, paint);
1051 }
1052
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +00001053 rect = SkRect::MakeLTRB(width, deviceBounds.top(),
1054 deviceBounds.right(), 0);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001055 if (!rect.isEmpty()) {
vandebo@chromium.org54ff85c2012-03-09 17:18:50 +00001056 paint.setColor(image->getColor(image->width() - 1, 0));
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001057 canvas.drawRect(rect, paint);
1058 }
1059
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +00001060 rect = SkRect::MakeLTRB(width, height,
1061 deviceBounds.right(), deviceBounds.bottom());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001062 if (!rect.isEmpty()) {
vandebo@chromium.org54ff85c2012-03-09 17:18:50 +00001063 paint.setColor(image->getColor(image->width() - 1,
1064 image->height() - 1));
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001065 canvas.drawRect(rect, paint);
1066 }
1067
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +00001068 rect = SkRect::MakeLTRB(deviceBounds.left(), height,
1069 0, deviceBounds.bottom());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001070 if (!rect.isEmpty()) {
vandebo@chromium.org54ff85c2012-03-09 17:18:50 +00001071 paint.setColor(image->getColor(0, image->height() - 1));
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001072 canvas.drawRect(rect, paint);
1073 }
1074 }
1075
1076 // Then expand the left, right, top, then bottom.
1077 if (tileModes[0] == SkShader::kClamp_TileMode) {
vandebo@chromium.org54ff85c2012-03-09 17:18:50 +00001078 SkIRect subset = SkIRect::MakeXYWH(0, 0, 1, image->height());
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +00001079 if (deviceBounds.left() < 0) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001080 SkBitmap left;
1081 SkAssertResult(image->extractSubset(&left, subset));
1082
1083 SkMatrix leftMatrix;
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +00001084 leftMatrix.setScale(-deviceBounds.left(), 1);
1085 leftMatrix.postTranslate(deviceBounds.left(), 0);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001086 canvas.drawBitmapMatrix(left, leftMatrix);
1087
1088 if (tileModes[1] == SkShader::kMirror_TileMode) {
vandebo@chromium.org663515b2012-01-05 18:45:27 +00001089 leftMatrix.postScale(SK_Scalar1, -SK_Scalar1);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001090 leftMatrix.postTranslate(0, 2 * height);
1091 canvas.drawBitmapMatrix(left, leftMatrix);
1092 }
vandebo@chromium.orgbe2048a2011-05-02 15:24:01 +00001093 patternBBox.fLeft = 0;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001094 }
1095
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +00001096 if (deviceBounds.right() > width) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001097 SkBitmap right;
vandebo@chromium.org54ff85c2012-03-09 17:18:50 +00001098 subset.offset(image->width() - 1, 0);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001099 SkAssertResult(image->extractSubset(&right, subset));
1100
1101 SkMatrix rightMatrix;
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +00001102 rightMatrix.setScale(deviceBounds.right() - width, 1);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001103 rightMatrix.postTranslate(width, 0);
1104 canvas.drawBitmapMatrix(right, rightMatrix);
1105
1106 if (tileModes[1] == SkShader::kMirror_TileMode) {
vandebo@chromium.org663515b2012-01-05 18:45:27 +00001107 rightMatrix.postScale(SK_Scalar1, -SK_Scalar1);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001108 rightMatrix.postTranslate(0, 2 * height);
1109 canvas.drawBitmapMatrix(right, rightMatrix);
1110 }
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +00001111 patternBBox.fRight = deviceBounds.width();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001112 }
1113 }
1114
1115 if (tileModes[1] == SkShader::kClamp_TileMode) {
vandebo@chromium.org54ff85c2012-03-09 17:18:50 +00001116 SkIRect subset = SkIRect::MakeXYWH(0, 0, image->width(), 1);
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +00001117 if (deviceBounds.top() < 0) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001118 SkBitmap top;
1119 SkAssertResult(image->extractSubset(&top, subset));
1120
1121 SkMatrix topMatrix;
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +00001122 topMatrix.setScale(SK_Scalar1, -deviceBounds.top());
1123 topMatrix.postTranslate(0, deviceBounds.top());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001124 canvas.drawBitmapMatrix(top, topMatrix);
1125
1126 if (tileModes[0] == SkShader::kMirror_TileMode) {
1127 topMatrix.postScale(-1, 1);
1128 topMatrix.postTranslate(2 * width, 0);
1129 canvas.drawBitmapMatrix(top, topMatrix);
1130 }
vandebo@chromium.orgbe2048a2011-05-02 15:24:01 +00001131 patternBBox.fTop = 0;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001132 }
1133
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +00001134 if (deviceBounds.bottom() > height) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001135 SkBitmap bottom;
vandebo@chromium.org54ff85c2012-03-09 17:18:50 +00001136 subset.offset(0, image->height() - 1);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001137 SkAssertResult(image->extractSubset(&bottom, subset));
1138
1139 SkMatrix bottomMatrix;
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +00001140 bottomMatrix.setScale(SK_Scalar1, deviceBounds.bottom() - height);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001141 bottomMatrix.postTranslate(0, height);
1142 canvas.drawBitmapMatrix(bottom, bottomMatrix);
1143
1144 if (tileModes[0] == SkShader::kMirror_TileMode) {
1145 bottomMatrix.postScale(-1, 1);
1146 bottomMatrix.postTranslate(2 * width, 0);
1147 canvas.drawBitmapMatrix(bottom, bottomMatrix);
1148 }
commit-bot@chromium.orge324cc62013-08-21 23:10:45 +00001149 patternBBox.fBottom = deviceBounds.height();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001150 }
1151 }
1152
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001153 // Put the canvas into the pattern stream (fContent).
vandebo@chromium.orgd96d17b2013-01-04 19:31:24 +00001154 SkAutoTUnref<SkStream> content(pattern.content());
1155 setData(content.get());
commit-bot@chromium.org47401352013-07-23 21:49:29 +00001156 SkPDFResourceDict* resourceDict = pattern.getResourceDict();
1157 resourceDict->getReferencedResources(fResources, &fResources, false);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001158
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +00001159 populate_tiling_pattern_dict(this, patternBBox,
1160 pattern.getResourceDict(), finalMatrix);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001161
1162 fState.get()->fImage.unlockPixels();
1163}
1164
vandebo@chromium.org421d6442011-07-20 17:39:01 +00001165SkPDFStream* SkPDFFunctionShader::makePSFunction(const SkString& psCode,
1166 SkPDFArray* domain) {
1167 SkAutoDataUnref funcData(SkData::NewWithCopy(psCode.c_str(),
1168 psCode.size()));
1169 SkPDFStream* result = new SkPDFStream(funcData.get());
reed@google.comc789cf12011-07-20 12:14:33 +00001170 result->insertInt("FunctionType", 4);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001171 result->insert("Domain", domain);
reed@google.comf6c3ebd2011-07-20 17:20:28 +00001172 result->insert("Range", RangeObject());
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001173 return result;
1174}
1175
vandebo@chromium.org421d6442011-07-20 17:39:01 +00001176SkPDFShader::ShaderCanonicalEntry::ShaderCanonicalEntry(SkPDFObject* pdfShader,
1177 const State* state)
1178 : fPDFShader(pdfShader),
1179 fState(state) {
1180}
1181
1182bool SkPDFShader::ShaderCanonicalEntry::operator==(
1183 const ShaderCanonicalEntry& b) const {
1184 return fPDFShader == b.fPDFShader ||
1185 (fState != NULL && b.fState != NULL && *fState == *b.fState);
1186}
1187
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001188bool SkPDFShader::State::operator==(const SkPDFShader::State& b) const {
1189 if (fType != b.fType ||
1190 fCanvasTransform != b.fCanvasTransform ||
1191 fShaderTransform != b.fShaderTransform ||
1192 fBBox != b.fBBox) {
1193 return false;
1194 }
1195
1196 if (fType == SkShader::kNone_GradientType) {
1197 if (fPixelGeneration != b.fPixelGeneration ||
1198 fPixelGeneration == 0 ||
1199 fImageTileModes[0] != b.fImageTileModes[0] ||
1200 fImageTileModes[1] != b.fImageTileModes[1]) {
1201 return false;
1202 }
1203 } else {
1204 if (fInfo.fColorCount != b.fInfo.fColorCount ||
1205 memcmp(fInfo.fColors, b.fInfo.fColors,
1206 sizeof(SkColor) * fInfo.fColorCount) != 0 ||
1207 memcmp(fInfo.fColorOffsets, b.fInfo.fColorOffsets,
1208 sizeof(SkScalar) * fInfo.fColorCount) != 0 ||
1209 fInfo.fPoint[0] != b.fInfo.fPoint[0] ||
1210 fInfo.fTileMode != b.fInfo.fTileMode) {
1211 return false;
1212 }
1213
1214 switch (fType) {
1215 case SkShader::kLinear_GradientType:
1216 if (fInfo.fPoint[1] != b.fInfo.fPoint[1]) {
1217 return false;
1218 }
1219 break;
1220 case SkShader::kRadial_GradientType:
1221 if (fInfo.fRadius[0] != b.fInfo.fRadius[0]) {
1222 return false;
1223 }
1224 break;
1225 case SkShader::kRadial2_GradientType:
reed@google.com49085332012-06-11 18:54:07 +00001226 case SkShader::kConical_GradientType:
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001227 if (fInfo.fPoint[1] != b.fInfo.fPoint[1] ||
1228 fInfo.fRadius[0] != b.fInfo.fRadius[0] ||
1229 fInfo.fRadius[1] != b.fInfo.fRadius[1]) {
1230 return false;
1231 }
1232 break;
1233 case SkShader::kSweep_GradientType:
1234 case SkShader::kNone_GradientType:
1235 case SkShader::kColor_GradientType:
1236 break;
1237 }
1238 }
1239 return true;
1240}
1241
1242SkPDFShader::State::State(const SkShader& shader,
1243 const SkMatrix& canvasTransform, const SkIRect& bbox)
1244 : fCanvasTransform(canvasTransform),
vandebo@chromium.orge1bc2742011-06-21 22:26:39 +00001245 fBBox(bbox),
1246 fPixelGeneration(0) {
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001247 fInfo.fColorCount = 0;
1248 fInfo.fColors = NULL;
1249 fInfo.fColorOffsets = NULL;
bsalomon@google.comf94b3a42012-10-31 18:09:01 +00001250 fShaderTransform = shader.getLocalMatrix();
vandebo@chromium.orge1bc2742011-06-21 22:26:39 +00001251 fImageTileModes[0] = fImageTileModes[1] = SkShader::kClamp_TileMode;
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001252
1253 fType = shader.asAGradient(&fInfo);
1254
1255 if (fType == SkShader::kNone_GradientType) {
1256 SkShader::BitmapType bitmapType;
1257 SkMatrix matrix;
rileya@google.com91f319c2012-07-25 17:18:31 +00001258 bitmapType = shader.asABitmap(&fImage, &matrix, fImageTileModes);
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001259 if (bitmapType != SkShader::kDefault_BitmapType) {
1260 fImage.reset();
1261 return;
1262 }
1263 SkASSERT(matrix.isIdentity());
1264 fPixelGeneration = fImage.getGenerationID();
1265 } else {
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +00001266 AllocateGradientInfoStorage();
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001267 shader.asAGradient(&fInfo);
1268 }
1269}
commit-bot@chromium.org93a2e212013-07-23 23:16:03 +00001270
1271SkPDFShader::State::State(const SkPDFShader::State& other)
1272 : fType(other.fType),
1273 fCanvasTransform(other.fCanvasTransform),
1274 fShaderTransform(other.fShaderTransform),
1275 fBBox(other.fBBox)
1276{
1277 // Only gradients supported for now, since that is all that is used.
1278 // If needed, image state copy constructor can be added here later.
1279 SkASSERT(fType != SkShader::kNone_GradientType);
1280
1281 if (fType != SkShader::kNone_GradientType) {
1282 fInfo = other.fInfo;
1283
1284 AllocateGradientInfoStorage();
1285 for (int i = 0; i < fInfo.fColorCount; i++) {
1286 fInfo.fColors[i] = other.fInfo.fColors[i];
1287 fInfo.fColorOffsets[i] = other.fInfo.fColorOffsets[i];
1288 }
1289 }
1290}
1291
1292/**
1293 * Create a copy of this gradient state with alpha assigned to RGB luminousity.
1294 * Only valid for gradient states.
1295 */
1296SkPDFShader::State* SkPDFShader::State::CreateAlphaToLuminosityState() const {
1297 SkASSERT(fType != SkShader::kNone_GradientType);
1298
1299 SkPDFShader::State* newState = new SkPDFShader::State(*this);
1300
1301 for (int i = 0; i < fInfo.fColorCount; i++) {
1302 SkAlpha alpha = SkColorGetA(fInfo.fColors[i]);
1303 newState->fInfo.fColors[i] = SkColorSetARGB(255, alpha, alpha, alpha);
1304 }
1305
1306 return newState;
1307}
1308
1309/**
1310 * Create a copy of this gradient state with alpha set to fully opaque
1311 * Only valid for gradient states.
1312 */
1313SkPDFShader::State* SkPDFShader::State::CreateOpaqueState() const {
1314 SkASSERT(fType != SkShader::kNone_GradientType);
1315
1316 SkPDFShader::State* newState = new SkPDFShader::State(*this);
1317 for (int i = 0; i < fInfo.fColorCount; i++) {
1318 newState->fInfo.fColors[i] = SkColorSetA(fInfo.fColors[i],
1319 SK_AlphaOPAQUE);
1320 }
1321
1322 return newState;
1323}
1324
1325/**
1326 * Returns true if state is a gradient and the gradient has alpha.
1327 */
1328bool SkPDFShader::State::GradientHasAlpha() const {
1329 if (fType == SkShader::kNone_GradientType) {
1330 return false;
1331 }
1332
1333 for (int i = 0; i < fInfo.fColorCount; i++) {
1334 SkAlpha alpha = SkColorGetA(fInfo.fColors[i]);
1335 if (alpha != SK_AlphaOPAQUE) {
1336 return true;
1337 }
1338 }
1339 return false;
1340}
1341
1342void SkPDFShader::State::AllocateGradientInfoStorage() {
1343 fColorData.set(sk_malloc_throw(
1344 fInfo.fColorCount * (sizeof(SkColor) + sizeof(SkScalar))));
1345 fInfo.fColors = reinterpret_cast<SkColor*>(fColorData.get());
1346 fInfo.fColorOffsets =
1347 reinterpret_cast<SkScalar*>(fInfo.fColors + fInfo.fColorCount);
1348}