blob: 4cbd4efb5215808566a19c9a0400c17a7f414b0f [file] [log] [blame]
vandebo@chromium.orgda912d62011-03-08 18:31:02 +00001/*
2 * Copyright (C) 2011 Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "SkPDFShader.h"
18
19#include "SkCanvas.h"
20#include "SkPDFCatalog.h"
21#include "SkPDFDevice.h"
22#include "SkPDFTypes.h"
23#include "SkPDFUtils.h"
24#include "SkScalar.h"
25#include "SkStream.h"
26#include "SkThread.h"
27#include "SkTypes.h"
28
29static void transformBBox(const SkMatrix& matrix, SkRect* bbox) {
30 SkMatrix inverse;
31 inverse.reset();
32 matrix.invert(&inverse);
33 inverse.mapRect(bbox);
34}
35
36static void unitToPointsMatrix(const SkPoint pts[2], SkMatrix* matrix) {
37 SkVector vec = pts[1] - pts[0];
38 SkScalar mag = vec.length();
39 SkScalar inv = mag ? SkScalarInvert(mag) : 0;
40
41 vec.scale(inv);
42 matrix->setSinCos(vec.fY, vec.fX);
43 matrix->preTranslate(pts[0].fX, pts[0].fY);
44 matrix->preScale(mag, mag);
45}
46
47/* Assumes t + startOffset is on the stack and does a linear interpolation on t
48 between startOffset and endOffset from prevColor to curColor (for each color
49 component), leaving the result in component order on the stack.
50 @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,
56 SkScalar* prevColor, int components,
57 SkString* result) {
58 // Figure out how to scale each color component.
59 SkScalar multiplier[components];
60 for (int i = 0; i < components; i++) {
61 multiplier[i] = SkScalarDiv(curColor[i] - prevColor[i], range);
62 }
63
64 // Calculate when we no longer need to keep a copy of the input parameter t.
65 // If the last component to use t is i, then dupInput[0..i - 1] = true
66 // and dupInput[i .. components] = false.
67 bool dupInput[components];
68 dupInput[components - 1] = false;
69 for (int i = components - 2; i >= 0; i--) {
70 dupInput[i] = dupInput[i + 1] || multiplier[i + 1] != 0;
71 }
72
73 if (!dupInput[0] && multiplier[0] == 0) {
74 result->append("pop ");
75 }
76
77 for (int i = 0; i < components; i++) {
78 // If the next components needs t, make a copy.
79 if (dupInput[i]) {
80 result->append("dup ");
81 }
82
83 if (multiplier[i] == 0) {
84 result->appendScalar(prevColor[i]);
85 result->append(" ");
86 } else {
87 if (multiplier[i] != 1) {
88 result->appendScalar(multiplier[i]);
89 result->append(" mul ");
90 }
91 if (prevColor[i] != 0) {
92 result->appendScalar(prevColor[i]);
93 result->append(" add ");
94 }
95 }
96
97 if (dupInput[i]) {
98 result->append("exch\n");
99 }
100 }
101}
102
103/* Generate Type 4 function code to map t=[0,1) to the passed gradient,
104 clamping at the edges of the range. The generated code will be of the form:
105 if (t < 0) {
106 return colorData[0][r,g,b];
107 } else {
108 if (t < info.fColorOffsets[1]) {
109 return linearinterpolation(colorData[0][r,g,b],
110 colorData[1][r,g,b]);
111 } else {
112 if (t < info.fColorOffsets[2]) {
113 return linearinterpolation(colorData[1][r,g,b],
114 colorData[2][r,g,b]);
115 } else {
116
117 ... } else {
118 return colorData[info.fColorCount - 1][r,g,b];
119 }
120 ...
121 }
122 }
123 */
124static void gradientFunctionCode(const SkShader::GradientInfo& info,
125 SkString* result) {
126 /* We want to linearly interpolate from the previous color to the next.
127 Scale the colors from 0..255 to 0..1 and determine the multipliers
128 for interpolation.
129 C{r,g,b}(t, section) = t - offset_(section-1) + t * Multiplier{r,g,b}.
130 */
131 static const int kColorComponents = 3;
132 SkScalar colorData[info.fColorCount][kColorComponents];
133
134 const SkScalar scale = SkScalarInvert(SkIntToScalar(255));
135 for (int i = 0; i < info.fColorCount; i++) {
136 colorData[i][0] = SkScalarMul(SkColorGetR(info.fColors[i]), scale);
137 colorData[i][1] = SkScalarMul(SkColorGetG(info.fColors[i]), scale);
138 colorData[i][2] = SkScalarMul(SkColorGetB(info.fColors[i]), scale);
139 }
140
141 // Clamp the initial color.
142 result->append("dup 0 le {pop ");
143 result->appendScalar(colorData[0][0]);
144 result->append(" ");
145 result->appendScalar(colorData[0][1]);
146 result->append(" ");
147 result->appendScalar(colorData[0][2]);
148 result->append(" }\n");
149
150 // The gradient colors.
151 for (int i = 1 ; i < info.fColorCount; i++) {
152 result->append("{dup ");
153 result->appendScalar(info.fColorOffsets[i]);
154 result->append(" le {");
155 if (info.fColorOffsets[i - 1] != 0) {
156 result->appendScalar(info.fColorOffsets[i - 1]);
157 result->append(" sub\n");
158 }
159
160 interpolateColorCode(info.fColorOffsets[i] - info.fColorOffsets[i - 1],
161 colorData[i], colorData[i - 1], kColorComponents,
162 result);
163 result->append("}\n");
164 }
165
166 // Clamp the final color.
167 result->append("{pop ");
168 result->appendScalar(colorData[info.fColorCount - 1][0]);
169 result->append(" ");
170 result->appendScalar(colorData[info.fColorCount - 1][1]);
171 result->append(" ");
172 result->appendScalar(colorData[info.fColorCount - 1][2]);
173
174 for (int i = 0 ; i < info.fColorCount; i++) {
175 result->append("} ifelse\n");
176 }
177}
178
179/* Map a value of t on the stack into [0, 1) for Repeat or Mirror tile mode. */
180static void tileModeCode(SkShader::TileMode mode, SkString* result) {
181 if (mode == SkShader::kRepeat_TileMode) {
182 result->append("dup truncate sub\n"); // Get the fractional part.
183 result->append("dup 0 le {1 add} if\n"); // Map (-1,0) => (0,1)
184 return;
185 }
186
187 if (mode == SkShader::kMirror_TileMode) {
188 // Map t mod 2 into [0, 1, 1, 0].
189 // Code Stack
190 result->append("abs " // Map negative to positive.
191 "dup " // t.s t.s
192 "truncate " // t.s t
193 "dup " // t.s t t
194 "cvi " // t.s t T
195 "2 mod " // t.s t (i mod 2)
196 "1 eq " // t.s t true|false
197 "3 1 roll " // true|false t.s t
198 "sub " // true|false 0.s
199 "exch " // 0.s true|false
200 "{1 exch sub} if\n"); // 1 - 0.s|0.s
201 }
202}
203
204static SkString linearCode(const SkShader::GradientInfo& info) {
205 SkString function("{pop\n"); // Just ditch the y value.
206 tileModeCode(info.fTileMode, &function);
207 gradientFunctionCode(info, &function);
208 function.append("}");
209 return function;
210}
211
212static SkString radialCode(const SkShader::GradientInfo& info) {
213 SkString function("{");
214 // Find the distance from the origin.
215 function.append("dup " // x y y
216 "mul " // x y^2
217 "exch " // y^2 x
218 "dup " // y^2 x x
219 "mul " // y^2 x^2
220 "add " // y^2+x^2
221 "sqrt\n"); // sqrt(y^2+x^2)
222
223 tileModeCode(info.fTileMode, &function);
224 gradientFunctionCode(info, &function);
225 function.append("}");
226 return function;
227}
228
229/* The math here is all based on the description in Two_Point_Radial_Gradient,
230 with one simplification, the coordinate space has been scaled so that
231 Dr = 1. This means we don't need to scale the entire equation by 1/Dr^2.
232 */
233static SkString twoPointRadialCode(const SkShader::GradientInfo& info) {
234 SkScalar dx = info.fPoint[0].fX - info.fPoint[1].fX;
235 SkScalar dy = info.fPoint[0].fY - info.fPoint[1].fY;
236 SkScalar sr = info.fRadius[0];
237 SkScalar a = SkScalarMul(dx, dx) + SkScalarMul(dy, dy) - SK_Scalar1;
238 bool posRoot = info.fRadius[1] > info.fRadius[0];
239
240 // We start with a stack of (x y), copy it and then consume one copy in
241 // order to calculate b and the other to calculate c.
242 SkString function("{");
243 function.append("2 copy ");
244
245 // Calculate -b and b^2.
246 function.appendScalar(dy);
247 function.append(" mul exch ");
248 function.appendScalar(dx);
249 function.append(" mul add ");
250 function.appendScalar(sr);
251 function.append(" sub 2 mul neg dup dup mul\n");
252
253 // Calculate c
254 function.append("4 2 roll dup mul exch dup mul add ");
255 function.appendScalar(SkScalarMul(sr, sr));
256 function.append(" sub\n");
257
258 // Calculate the determinate
259 function.appendScalar(SkScalarMul(SkIntToScalar(4), a));
260 function.append(" mul sub abs sqrt\n");
261
262 // And then the final value of t.
263 if (posRoot) {
264 function.append("sub ");
265 } else {
266 function.append("add ");
267 }
268 function.appendScalar(SkScalarMul(SkIntToScalar(2), a));
269 function.append(" div\n");
270
271 tileModeCode(info.fTileMode, &function);
272 gradientFunctionCode(info, &function);
273 function.append("}");
274 return function;
275}
276
277static SkString sweepCode(const SkShader::GradientInfo& info) {
278 SkString function("{exch atan 360 div\n");
279 tileModeCode(info.fTileMode, &function);
280 gradientFunctionCode(info, &function);
281 function.append("}");
282 return function;
283}
284
285SkPDFShader::~SkPDFShader() {
286 SkAutoMutexAcquire lock(canonicalShadersMutex());
287 ShaderCanonicalEntry entry(this, fState.get());
288 int index = canonicalShaders().find(entry);
289 SkASSERT(index >= 0);
290 canonicalShaders().removeShuffle(index);
291 fResources.unrefAll();
292}
293
294void SkPDFShader::emitObject(SkWStream* stream, SkPDFCatalog* catalog,
295 bool indirect) {
296 if (indirect)
297 return emitIndirectObject(stream, catalog);
298
299 fContent->emitObject(stream, catalog, indirect);
300}
301
302size_t SkPDFShader::getOutputSize(SkPDFCatalog* catalog, bool indirect) {
303 if (indirect)
304 return getIndirectOutputSize(catalog);
305
306 return fContent->getOutputSize(catalog, indirect);
307}
308
309void SkPDFShader::getResources(SkTDArray<SkPDFObject*>* resourceList) {
310 resourceList->setReserve(resourceList->count() + fResources.count());
311 for (int i = 0; i < fResources.count(); i++) {
312 resourceList->push(fResources[i]);
313 fResources[i]->ref();
314 }
315}
316
317// static
318SkPDFShader* SkPDFShader::getPDFShader(const SkShader& shader,
319 const SkMatrix& matrix,
320 const SkIRect& surfaceBBox) {
321 SkRefPtr<SkPDFShader> pdfShader;
322 SkAutoMutexAcquire lock(canonicalShadersMutex());
323 SkAutoTDelete<State> shaderState(new State(shader, matrix, surfaceBBox));
324
325 ShaderCanonicalEntry entry(NULL, shaderState.get());
326 int index = canonicalShaders().find(entry);
327 if (index >= 0) {
328 SkPDFShader* result = canonicalShaders()[index].fPDFShader;
329 result->ref();
330 return result;
331 }
332 // The PDFShader takes ownership of the shaderSate.
333 pdfShader = new SkPDFShader(shaderState.detach());
334 // Check for a valid shader.
335 if (pdfShader->fContent.get() == NULL) {
336 pdfShader->unref();
337 return NULL;
338 }
339 entry.fPDFShader = pdfShader.get();
340 canonicalShaders().push(entry);
341 return pdfShader.get(); // return the reference that came from new.
342}
343
344// static
345SkTDArray<SkPDFShader::ShaderCanonicalEntry>& SkPDFShader::canonicalShaders() {
346 // This initialization is only thread safe with gcc.
347 static SkTDArray<ShaderCanonicalEntry> gCanonicalShaders;
348 return gCanonicalShaders;
349}
350
351// static
352SkMutex& SkPDFShader::canonicalShadersMutex() {
353 // This initialization is only thread safe with gcc.
354 static SkMutex gCanonicalShadersMutex;
355 return gCanonicalShadersMutex;
356}
357
358// static
359SkPDFObject* SkPDFShader::rangeObject() {
360 // This initialization is only thread safe with gcc.
361 static SkPDFArray* range = NULL;
362 // This method is only used with canonicalShadersMutex, so it's safe to
363 // populate domain.
364 if (range == NULL) {
365 range = new SkPDFArray;
366 range->reserve(6);
367 range->append(new SkPDFInt(0))->unref();
368 range->append(new SkPDFInt(1))->unref();
369 range->append(new SkPDFInt(0))->unref();
370 range->append(new SkPDFInt(1))->unref();
371 range->append(new SkPDFInt(0))->unref();
372 range->append(new SkPDFInt(1))->unref();
373 }
374 return range;
375}
376
377SkPDFShader::SkPDFShader(State* state) : fState(state) {
378 if (fState.get()->fType == SkShader::kNone_GradientType) {
379 doImageShader();
380 } else {
381 doFunctionShader();
382 }
383}
384
385void SkPDFShader::doFunctionShader() {
386 SkString (*codeFunction)(const SkShader::GradientInfo& info) = NULL;
387 SkPoint transformPoints[2];
388
389 // Depending on the type of the gradient, we want to transform the
390 // coordinate space in different ways.
391 const SkShader::GradientInfo* info = &fState.get()->fInfo;
392 transformPoints[0] = info->fPoint[0];
393 transformPoints[1] = info->fPoint[1];
394 switch (fState.get()->fType) {
395 case SkShader::kLinear_GradientType:
396 codeFunction = &linearCode;
397 break;
398 case SkShader::kRadial_GradientType:
399 transformPoints[1] = transformPoints[0];
400 transformPoints[1].fX += info->fRadius[0];
401 codeFunction = &radialCode;
402 break;
403 case SkShader::kRadial2_GradientType: {
404 // Bail out if the radii are the same. Not setting fContent will
405 // cause the higher level code to detect the resulting object
406 // as invalid.
407 if (info->fRadius[0] == info->fRadius[1]) {
408 return;
409 }
410 transformPoints[1] = transformPoints[0];
411 SkScalar dr = info->fRadius[1] - info->fRadius[0];
412 transformPoints[1].fX += dr;
413 codeFunction = &twoPointRadialCode;
414 break;
415 }
416 case SkShader::kSweep_GradientType:
417 transformPoints[1] = transformPoints[0];
418 transformPoints[1].fX += 1;
419 codeFunction = &sweepCode;
420 break;
421 case SkShader::kColor_GradientType:
422 case SkShader::kNone_GradientType:
423 SkASSERT(false);
424 return;
425 }
426
427 // Move any scaling (assuming a unit gradient) or translation
428 // (and rotation for linear gradient), of the final gradient from
429 // info->fPoints to the matrix (updating bbox appropriately). Now
430 // the gradient can be drawn on on the unit segment.
431 SkMatrix mapperMatrix;
432 unitToPointsMatrix(transformPoints, &mapperMatrix);
433 SkMatrix finalMatrix = fState.get()->fCanvasTransform;
434 finalMatrix.preConcat(mapperMatrix);
435 finalMatrix.preConcat(fState.get()->fShaderTransform);
436 SkRect bbox;
437 bbox.set(fState.get()->fBBox);
438 transformBBox(finalMatrix, &bbox);
439
440 SkRefPtr<SkPDFArray> domain = new SkPDFArray;
441 domain->unref(); // SkRefPtr and new both took a reference.
442 domain->reserve(4);
443 domain->append(new SkPDFScalar(bbox.fLeft))->unref();
444 domain->append(new SkPDFScalar(bbox.fRight))->unref();
445 domain->append(new SkPDFScalar(bbox.fTop))->unref();
446 domain->append(new SkPDFScalar(bbox.fBottom))->unref();
447
448 SkString functionCode;
449 // The two point radial gradient further references fState.get()->fInfo
450 // in translating from x, y coordinates to the t parameter. So, we have
451 // to transform the points and radii according to the calculated matrix.
452 if (fState.get()->fType == SkShader::kRadial2_GradientType) {
453 SkShader::GradientInfo twoPointRadialInfo = *info;
454 SkMatrix inverseMapperMatrix;
455 mapperMatrix.invert(&inverseMapperMatrix);
456 inverseMapperMatrix.mapPoints(twoPointRadialInfo.fPoint, 2);
457 twoPointRadialInfo.fRadius[0] =
458 inverseMapperMatrix.mapRadius(info->fRadius[0]);
459 twoPointRadialInfo.fRadius[1] =
460 inverseMapperMatrix.mapRadius(info->fRadius[1]);
461 functionCode = codeFunction(twoPointRadialInfo);
462 } else {
463 functionCode = codeFunction(*info);
464 }
465
466 SkRefPtr<SkPDFStream> function = makePSFunction(functionCode, domain.get());
467 // Pass one reference to fResources, SkRefPtr and new both took a reference.
468 fResources.push(function.get());
469
470 SkRefPtr<SkPDFDict> pdfShader = new SkPDFDict;
471 pdfShader->unref(); // SkRefPtr and new both took a reference.
472 pdfShader->insert("ShadingType", new SkPDFInt(1))->unref();
473 pdfShader->insert("ColorSpace", new SkPDFName("DeviceRGB"))->unref();
474 pdfShader->insert("Domain", domain.get());
475 pdfShader->insert("Function", new SkPDFObjRef(function.get()))->unref();
476
477 fContent = new SkPDFDict("Pattern");
478 fContent->unref(); // SkRefPtr and new both took a reference.
479 fContent->insert("PatternType", new SkPDFInt(2))->unref();
480 fContent->insert("Matrix", SkPDFUtils::MatrixToArray(finalMatrix))->unref();
481 fContent->insert("Shading", pdfShader.get());
482}
483
484// SkShader* shader, SkMatrix matrix, const SkRect& surfaceBBox
485void SkPDFShader::doImageShader() {
486 fState.get()->fImage.lockPixels();
487
488 SkMatrix finalMatrix = fState.get()->fCanvasTransform;
489 finalMatrix.preConcat(fState.get()->fShaderTransform);
490 SkRect surfaceBBox;
491 surfaceBBox.set(fState.get()->fBBox);
492 transformBBox(finalMatrix, &surfaceBBox);
493
494 SkPDFDevice pattern(surfaceBBox.fRight, surfaceBBox.fBottom,
495 SkPDFDevice::kNoFlip_OriginTransform);
496 SkCanvas canvas(&pattern);
497 canvas.clipRect(surfaceBBox, SkRegion::kReplace_Op);
498
499 const SkBitmap* image = &fState.get()->fImage;
500 int width = image->width();
501 int height = image->height();
502 SkShader::TileMode tileModes[2];
503 tileModes[0] = fState.get()->fImageTileModes[0];
504 tileModes[1] = fState.get()->fImageTileModes[1];
505
506 canvas.drawBitmap(*image, 0, 0);
507 SkRect patternBBox = SkRect::MakeWH(width, height);
508
509 // Tiling is implied. First we handle mirroring.
510 if (tileModes[0] == SkShader::kMirror_TileMode) {
511 SkMatrix xMirror;
512 xMirror.setScale(-1, 1);
513 xMirror.postTranslate(2 * width, 0);
514 canvas.drawBitmapMatrix(*image, xMirror);
515 patternBBox.fRight += width;
516 }
517 if (tileModes[1] == SkShader::kMirror_TileMode) {
518 SkMatrix yMirror;
519 yMirror.setScale(1, -1);
520 yMirror.postTranslate(0, 2 * height);
521 canvas.drawBitmapMatrix(*image, yMirror);
522 patternBBox.fBottom += height;
523 }
524 if (tileModes[0] == SkShader::kMirror_TileMode &&
525 tileModes[1] == SkShader::kMirror_TileMode) {
526 SkMatrix mirror;
527 mirror.setScale(-1, -1);
528 mirror.postTranslate(2 * width, 2 * height);
529 canvas.drawBitmapMatrix(*image, mirror);
530 }
531
532 // Then handle Clamping, which requires expanding the pattern canvas to
533 // cover the entire surfaceBBox.
534
535 // If both x and y are in clamp mode, we start by filling in the corners.
536 // (Which are just a rectangles of the corner colors.)
537 if (tileModes[0] == SkShader::kClamp_TileMode &&
538 tileModes[1] == SkShader::kClamp_TileMode) {
539 SkPaint paint;
540 SkRect rect;
541 rect = SkRect::MakeLTRB(surfaceBBox.fLeft, surfaceBBox.fTop, 0, 0);
542 if (!rect.isEmpty()) {
543 paint.setColor(image->getColor(0, 0));
544 canvas.drawRect(rect, paint);
545 }
546
547 rect = SkRect::MakeLTRB(width, surfaceBBox.fTop, surfaceBBox.fRight, 0);
548 if (!rect.isEmpty()) {
549 paint.setColor(image->getColor(width - 1, 0));
550 canvas.drawRect(rect, paint);
551 }
552
553 rect = SkRect::MakeLTRB(width, height, surfaceBBox.fRight,
554 surfaceBBox.fBottom);
555 if (!rect.isEmpty()) {
556 paint.setColor(image->getColor(width - 1, height - 1));
557 canvas.drawRect(rect, paint);
558 }
559
560 rect = SkRect::MakeLTRB(surfaceBBox.fLeft, height, 0,
561 surfaceBBox.fBottom);
562 if (!rect.isEmpty()) {
563 paint.setColor(image->getColor(0, height - 1));
564 canvas.drawRect(rect, paint);
565 }
566 }
567
568 // Then expand the left, right, top, then bottom.
569 if (tileModes[0] == SkShader::kClamp_TileMode) {
570 SkIRect subset = SkIRect::MakeXYWH(0, 0, 1, height);
571 if (surfaceBBox.fLeft < 0) {
572 SkBitmap left;
573 SkAssertResult(image->extractSubset(&left, subset));
574
575 SkMatrix leftMatrix;
576 leftMatrix.setScale(-surfaceBBox.fLeft, 1);
577 leftMatrix.postTranslate(surfaceBBox.fLeft, 0);
578 canvas.drawBitmapMatrix(left, leftMatrix);
579
580 if (tileModes[1] == SkShader::kMirror_TileMode) {
581 leftMatrix.postScale(1, -1);
582 leftMatrix.postTranslate(0, 2 * height);
583 canvas.drawBitmapMatrix(left, leftMatrix);
584 }
585 patternBBox.fLeft = surfaceBBox.fLeft;
586 }
587
588 if (surfaceBBox.fRight > width) {
589 SkBitmap right;
590 subset.offset(width - 1, 0);
591 SkAssertResult(image->extractSubset(&right, subset));
592
593 SkMatrix rightMatrix;
594 rightMatrix.setScale(surfaceBBox.fRight - width, 1);
595 rightMatrix.postTranslate(width, 0);
596 canvas.drawBitmapMatrix(right, rightMatrix);
597
598 if (tileModes[1] == SkShader::kMirror_TileMode) {
599 rightMatrix.postScale(1, -1);
600 rightMatrix.postTranslate(0, 2 * height);
601 canvas.drawBitmapMatrix(right, rightMatrix);
602 }
603 patternBBox.fRight = surfaceBBox.fRight;
604 }
605 }
606
607 if (tileModes[1] == SkShader::kClamp_TileMode) {
608 SkIRect subset = SkIRect::MakeXYWH(0, 0, width, 1);
609 if (surfaceBBox.fTop < 0) {
610 SkBitmap top;
611 SkAssertResult(image->extractSubset(&top, subset));
612
613 SkMatrix topMatrix;
614 topMatrix.setScale(1, -surfaceBBox.fTop);
615 topMatrix.postTranslate(0, surfaceBBox.fTop);
616 canvas.drawBitmapMatrix(top, topMatrix);
617
618 if (tileModes[0] == SkShader::kMirror_TileMode) {
619 topMatrix.postScale(-1, 1);
620 topMatrix.postTranslate(2 * width, 0);
621 canvas.drawBitmapMatrix(top, topMatrix);
622 }
623 patternBBox.fTop = surfaceBBox.fTop;
624 }
625
626 if (surfaceBBox.fBottom > height) {
627 SkBitmap bottom;
628 subset.offset(0, height - 1);
629 SkAssertResult(image->extractSubset(&bottom, subset));
630
631 SkMatrix bottomMatrix;
632 bottomMatrix.setScale(1, surfaceBBox.fBottom - height);
633 bottomMatrix.postTranslate(0, height);
634 canvas.drawBitmapMatrix(bottom, bottomMatrix);
635
636 if (tileModes[0] == SkShader::kMirror_TileMode) {
637 bottomMatrix.postScale(-1, 1);
638 bottomMatrix.postTranslate(2 * width, 0);
639 canvas.drawBitmapMatrix(bottom, bottomMatrix);
640 }
641 patternBBox.fBottom = surfaceBBox.fBottom;
642 }
643 }
644
645 SkRefPtr<SkPDFArray> patternBBoxArray = new SkPDFArray;
646 patternBBoxArray->unref(); // SkRefPtr and new both took a reference.
647 patternBBoxArray->reserve(4);
648 patternBBoxArray->append(new SkPDFInt(patternBBox.fLeft))->unref();
649 patternBBoxArray->append(new SkPDFInt(patternBBox.fTop))->unref();
650 patternBBoxArray->append(new SkPDFInt(patternBBox.fRight))->unref();
651 patternBBoxArray->append(new SkPDFInt(patternBBox.fBottom))->unref();
652
653 // Put the canvas into the pattern stream (fContent).
654 SkRefPtr<SkStream> content = pattern.content();
655 content->unref(); // SkRefPtr and content() both took a reference.
656 pattern.getResources(&fResources);
657
658 fContent = new SkPDFStream(content.get());
659 fContent->unref(); // SkRefPtr and new both took a reference.
660 fContent->insert("Type", new SkPDFName("Pattern"))->unref();
661 fContent->insert("PatternType", new SkPDFInt(1))->unref();
662 fContent->insert("PaintType", new SkPDFInt(1))->unref();
663 fContent->insert("TilingType", new SkPDFInt(1))->unref();
664 fContent->insert("BBox", patternBBoxArray.get());
665 fContent->insert("XStep", new SkPDFInt(patternBBox.width()))->unref();
666 fContent->insert("YStep", new SkPDFInt(patternBBox.height()))->unref();
667 fContent->insert("Resources", pattern.getResourceDict().get());
668 fContent->insert("Matrix", SkPDFUtils::MatrixToArray(finalMatrix))->unref();
669
670 fState.get()->fImage.unlockPixels();
671}
672
673SkPDFStream* SkPDFShader::makePSFunction(const SkString& psCode,
674 SkPDFArray* domain) {
675 SkRefPtr<SkMemoryStream> funcStream =
676 new SkMemoryStream(psCode.c_str(), psCode.size(), true);
677 funcStream->unref(); // SkRefPtr and new both took a reference.
678
679 SkPDFStream* result = new SkPDFStream(funcStream.get());
680 result->insert("FunctionType", new SkPDFInt(4))->unref();
681 result->insert("Domain", domain);
682 result->insert("Range", rangeObject());
683 return result;
684}
685
686bool SkPDFShader::State::operator==(const SkPDFShader::State& b) const {
687 if (fType != b.fType ||
688 fCanvasTransform != b.fCanvasTransform ||
689 fShaderTransform != b.fShaderTransform ||
690 fBBox != b.fBBox) {
691 return false;
692 }
693
694 if (fType == SkShader::kNone_GradientType) {
695 if (fPixelGeneration != b.fPixelGeneration ||
696 fPixelGeneration == 0 ||
697 fImageTileModes[0] != b.fImageTileModes[0] ||
698 fImageTileModes[1] != b.fImageTileModes[1]) {
699 return false;
700 }
701 } else {
702 if (fInfo.fColorCount != b.fInfo.fColorCount ||
703 memcmp(fInfo.fColors, b.fInfo.fColors,
704 sizeof(SkColor) * fInfo.fColorCount) != 0 ||
705 memcmp(fInfo.fColorOffsets, b.fInfo.fColorOffsets,
706 sizeof(SkScalar) * fInfo.fColorCount) != 0 ||
707 fInfo.fPoint[0] != b.fInfo.fPoint[0] ||
708 fInfo.fTileMode != b.fInfo.fTileMode) {
709 return false;
710 }
711
712 switch (fType) {
713 case SkShader::kLinear_GradientType:
714 if (fInfo.fPoint[1] != b.fInfo.fPoint[1]) {
715 return false;
716 }
717 break;
718 case SkShader::kRadial_GradientType:
719 if (fInfo.fRadius[0] != b.fInfo.fRadius[0]) {
720 return false;
721 }
722 break;
723 case SkShader::kRadial2_GradientType:
724 if (fInfo.fPoint[1] != b.fInfo.fPoint[1] ||
725 fInfo.fRadius[0] != b.fInfo.fRadius[0] ||
726 fInfo.fRadius[1] != b.fInfo.fRadius[1]) {
727 return false;
728 }
729 break;
730 case SkShader::kSweep_GradientType:
731 case SkShader::kNone_GradientType:
732 case SkShader::kColor_GradientType:
733 break;
734 }
735 }
736 return true;
737}
738
739SkPDFShader::State::State(const SkShader& shader,
740 const SkMatrix& canvasTransform, const SkIRect& bbox)
741 : fCanvasTransform(canvasTransform),
742 fBBox(bbox) {
743
744 fInfo.fColorCount = 0;
745 fInfo.fColors = NULL;
746 fInfo.fColorOffsets = NULL;
747 shader.getLocalMatrix(&fShaderTransform);
748
749 fType = shader.asAGradient(&fInfo);
750
751 if (fType == SkShader::kNone_GradientType) {
752 SkShader::BitmapType bitmapType;
753 SkMatrix matrix;
754 bitmapType = shader.asABitmap(&fImage, &matrix, fImageTileModes, NULL);
755 if (bitmapType != SkShader::kDefault_BitmapType) {
756 fImage.reset();
757 return;
758 }
759 SkASSERT(matrix.isIdentity());
760 fPixelGeneration = fImage.getGenerationID();
761 } else {
762 fColorData.set(sk_malloc_throw(
763 fInfo.fColorCount * (sizeof(SkColor) + sizeof(SkScalar))));
764 fInfo.fColors = (SkColor*)fColorData.get();
765 fInfo.fColorOffsets = (SkScalar*)(fInfo.fColors + fInfo.fColorCount);
766 shader.asAGradient(&fInfo);
767 }
768}