1 // Copyright 2019 PDFium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
6 
7 #include "core/fpdfapi/render/cpdf_rendershading.h"
8 
9 #include <algorithm>
10 #include <array>
11 #include <cmath>
12 #include <memory>
13 #include <utility>
14 #include <vector>
15 
16 #include "core/fpdfapi/page/cpdf_colorspace.h"
17 #include "core/fpdfapi/page/cpdf_dib.h"
18 #include "core/fpdfapi/page/cpdf_function.h"
19 #include "core/fpdfapi/page/cpdf_meshstream.h"
20 #include "core/fpdfapi/parser/cpdf_array.h"
21 #include "core/fpdfapi/parser/cpdf_dictionary.h"
22 #include "core/fpdfapi/parser/cpdf_stream.h"
23 #include "core/fpdfapi/parser/fpdf_parser_utility.h"
24 #include "core/fpdfapi/render/cpdf_devicebuffer.h"
25 #include "core/fpdfapi/render/cpdf_renderoptions.h"
26 #include "core/fxcrt/fx_safe_types.h"
27 #include "core/fxcrt/fx_system.h"
28 #include "core/fxge/cfx_defaultrenderdevice.h"
29 #include "core/fxge/cfx_fillrenderoptions.h"
30 #include "core/fxge/cfx_pathdata.h"
31 #include "core/fxge/dib/cfx_dibitmap.h"
32 #include "core/fxge/dib/fx_dib.h"
33 #include "third_party/base/span.h"
34 
35 namespace {
36 
37 constexpr int kShadingSteps = 256;
38 
CountOutputsFromFunctions(const std::vector<std::unique_ptr<CPDF_Function>> & funcs)39 uint32_t CountOutputsFromFunctions(
40     const std::vector<std::unique_ptr<CPDF_Function>>& funcs) {
41   FX_SAFE_UINT32 total = 0;
42   for (const auto& func : funcs) {
43     if (func)
44       total += func->CountOutputs();
45   }
46   return total.ValueOrDefault(0);
47 }
48 
GetValidatedOutputsCount(const std::vector<std::unique_ptr<CPDF_Function>> & funcs,const RetainPtr<CPDF_ColorSpace> & pCS)49 uint32_t GetValidatedOutputsCount(
50     const std::vector<std::unique_ptr<CPDF_Function>>& funcs,
51     const RetainPtr<CPDF_ColorSpace>& pCS) {
52   uint32_t funcs_outputs = CountOutputsFromFunctions(funcs);
53   return funcs_outputs ? std::max(funcs_outputs, pCS->CountComponents()) : 0;
54 }
55 
GetShadingSteps(float t_min,float t_max,const std::vector<std::unique_ptr<CPDF_Function>> & funcs,const RetainPtr<CPDF_ColorSpace> & pCS,int alpha,size_t results_count)56 std::array<FX_ARGB, kShadingSteps> GetShadingSteps(
57     float t_min,
58     float t_max,
59     const std::vector<std::unique_ptr<CPDF_Function>>& funcs,
60     const RetainPtr<CPDF_ColorSpace>& pCS,
61     int alpha,
62     size_t results_count) {
63   ASSERT(results_count >= CountOutputsFromFunctions(funcs));
64   ASSERT(results_count >= pCS->CountComponents());
65   std::array<FX_ARGB, kShadingSteps> shading_steps;
66   std::vector<float> result_array(results_count);
67   float diff = t_max - t_min;
68   for (int i = 0; i < kShadingSteps; ++i) {
69     float input = diff * i / kShadingSteps + t_min;
70     int offset = 0;
71     for (const auto& func : funcs) {
72       if (func) {
73         int nresults = 0;
74         if (func->Call(&input, 1, &result_array[offset], &nresults))
75           offset += nresults;
76       }
77     }
78     float R = 0.0f;
79     float G = 0.0f;
80     float B = 0.0f;
81     pCS->GetRGB(result_array, &R, &G, &B);
82     shading_steps[i] = ArgbEncode(alpha, FXSYS_roundf(R * 255),
83                                   FXSYS_roundf(G * 255), FXSYS_roundf(B * 255));
84   }
85   return shading_steps;
86 }
87 
DrawAxialShading(const RetainPtr<CFX_DIBitmap> & pBitmap,const CFX_Matrix & mtObject2Bitmap,const CPDF_Dictionary * pDict,const std::vector<std::unique_ptr<CPDF_Function>> & funcs,const RetainPtr<CPDF_ColorSpace> & pCS,int alpha)88 void DrawAxialShading(const RetainPtr<CFX_DIBitmap>& pBitmap,
89                       const CFX_Matrix& mtObject2Bitmap,
90                       const CPDF_Dictionary* pDict,
91                       const std::vector<std::unique_ptr<CPDF_Function>>& funcs,
92                       const RetainPtr<CPDF_ColorSpace>& pCS,
93                       int alpha) {
94   ASSERT(pBitmap->GetFormat() == FXDIB_Format::kArgb);
95 
96   const uint32_t total_results = GetValidatedOutputsCount(funcs, pCS);
97   if (total_results == 0)
98     return;
99 
100   const CPDF_Array* pCoords = pDict->GetArrayFor("Coords");
101   if (!pCoords)
102     return;
103 
104   float start_x = pCoords->GetNumberAt(0);
105   float start_y = pCoords->GetNumberAt(1);
106   float end_x = pCoords->GetNumberAt(2);
107   float end_y = pCoords->GetNumberAt(3);
108   float t_min = 0;
109   float t_max = 1.0f;
110   const CPDF_Array* pArray = pDict->GetArrayFor("Domain");
111   if (pArray) {
112     t_min = pArray->GetNumberAt(0);
113     t_max = pArray->GetNumberAt(1);
114   }
115   pArray = pDict->GetArrayFor("Extend");
116   const bool bStartExtend = pArray && pArray->GetBooleanAt(0, false);
117   const bool bEndExtend = pArray && pArray->GetBooleanAt(1, false);
118 
119   int width = pBitmap->GetWidth();
120   int height = pBitmap->GetHeight();
121   float x_span = end_x - start_x;
122   float y_span = end_y - start_y;
123   float axis_len_square = (x_span * x_span) + (y_span * y_span);
124 
125   std::array<FX_ARGB, kShadingSteps> shading_steps =
126       GetShadingSteps(t_min, t_max, funcs, pCS, alpha, total_results);
127 
128   int pitch = pBitmap->GetPitch();
129   CFX_Matrix matrix = mtObject2Bitmap.GetInverse();
130   for (int row = 0; row < height; row++) {
131     uint32_t* dib_buf =
132         reinterpret_cast<uint32_t*>(pBitmap->GetBuffer() + row * pitch);
133     for (int column = 0; column < width; column++) {
134       CFX_PointF pos = matrix.Transform(
135           CFX_PointF(static_cast<float>(column), static_cast<float>(row)));
136       float scale =
137           (((pos.x - start_x) * x_span) + ((pos.y - start_y) * y_span)) /
138           axis_len_square;
139       int index = (int32_t)(scale * (kShadingSteps - 1));
140       if (index < 0) {
141         if (!bStartExtend)
142           continue;
143 
144         index = 0;
145       } else if (index >= kShadingSteps) {
146         if (!bEndExtend)
147           continue;
148 
149         index = kShadingSteps - 1;
150       }
151       dib_buf[column] = shading_steps[index];
152     }
153   }
154 }
155 
DrawRadialShading(const RetainPtr<CFX_DIBitmap> & pBitmap,const CFX_Matrix & mtObject2Bitmap,const CPDF_Dictionary * pDict,const std::vector<std::unique_ptr<CPDF_Function>> & funcs,const RetainPtr<CPDF_ColorSpace> & pCS,int alpha)156 void DrawRadialShading(const RetainPtr<CFX_DIBitmap>& pBitmap,
157                        const CFX_Matrix& mtObject2Bitmap,
158                        const CPDF_Dictionary* pDict,
159                        const std::vector<std::unique_ptr<CPDF_Function>>& funcs,
160                        const RetainPtr<CPDF_ColorSpace>& pCS,
161                        int alpha) {
162   ASSERT(pBitmap->GetFormat() == FXDIB_Format::kArgb);
163 
164   const uint32_t total_results = GetValidatedOutputsCount(funcs, pCS);
165   if (total_results == 0)
166     return;
167 
168   const CPDF_Array* pCoords = pDict->GetArrayFor("Coords");
169   if (!pCoords)
170     return;
171 
172   float start_x = pCoords->GetNumberAt(0);
173   float start_y = pCoords->GetNumberAt(1);
174   float start_r = pCoords->GetNumberAt(2);
175   float end_x = pCoords->GetNumberAt(3);
176   float end_y = pCoords->GetNumberAt(4);
177   float end_r = pCoords->GetNumberAt(5);
178   float t_min = 0;
179   float t_max = 1.0f;
180   const CPDF_Array* pArray = pDict->GetArrayFor("Domain");
181   if (pArray) {
182     t_min = pArray->GetNumberAt(0);
183     t_max = pArray->GetNumberAt(1);
184   }
185   pArray = pDict->GetArrayFor("Extend");
186   const bool bStartExtend = pArray && pArray->GetBooleanAt(0, false);
187   const bool bEndExtend = pArray && pArray->GetBooleanAt(1, false);
188 
189   std::array<FX_ARGB, kShadingSteps> shading_steps =
190       GetShadingSteps(t_min, t_max, funcs, pCS, alpha, total_results);
191 
192   const float dx = end_x - start_x;
193   const float dy = end_y - start_y;
194   const float dr = end_r - start_r;
195   const float a = dx * dx + dy * dy - dr * dr;
196   const bool a_is_float_zero = IsFloatZero(a);
197 
198   int width = pBitmap->GetWidth();
199   int height = pBitmap->GetHeight();
200   int pitch = pBitmap->GetPitch();
201 
202   bool bDecreasing =
203       (dr < 0 && static_cast<int>(sqrt(dx * dx + dy * dy)) < -dr);
204 
205   CFX_Matrix matrix = mtObject2Bitmap.GetInverse();
206   for (int row = 0; row < height; row++) {
207     uint32_t* dib_buf =
208         reinterpret_cast<uint32_t*>(pBitmap->GetBuffer() + row * pitch);
209     for (int column = 0; column < width; column++) {
210       CFX_PointF pos = matrix.Transform(
211           CFX_PointF(static_cast<float>(column), static_cast<float>(row)));
212       float pos_dx = pos.x - start_x;
213       float pos_dy = pos.y - start_y;
214       float b = -2 * (pos_dx * dx + pos_dy * dy + start_r * dr);
215       float c = pos_dx * pos_dx + pos_dy * pos_dy - start_r * start_r;
216       float s;
217       if (IsFloatZero(b)) {
218         s = sqrt(-c / a);
219       } else if (a_is_float_zero) {
220         s = -c / b;
221       } else {
222         float b2_4ac = (b * b) - 4 * (a * c);
223         if (b2_4ac < 0)
224           continue;
225 
226         float root = sqrt(b2_4ac);
227         float s1 = (-b - root) / (2 * a);
228         float s2 = (-b + root) / (2 * a);
229         if (a <= 0)
230           std::swap(s1, s2);
231         if (bDecreasing)
232           s = (s1 >= 0 || bStartExtend) ? s1 : s2;
233         else
234           s = (s2 <= 1.0f || bEndExtend) ? s2 : s1;
235 
236         if (start_r + s * dr < 0)
237           continue;
238       }
239 
240       int index = static_cast<int32_t>(s * (kShadingSteps - 1));
241       if (index < 0) {
242         if (!bStartExtend)
243           continue;
244         index = 0;
245       } else if (index >= kShadingSteps) {
246         if (!bEndExtend)
247           continue;
248         index = kShadingSteps - 1;
249       }
250       dib_buf[column] = shading_steps[index];
251     }
252   }
253 }
254 
DrawFuncShading(const RetainPtr<CFX_DIBitmap> & pBitmap,const CFX_Matrix & mtObject2Bitmap,const CPDF_Dictionary * pDict,const std::vector<std::unique_ptr<CPDF_Function>> & funcs,const RetainPtr<CPDF_ColorSpace> & pCS,int alpha)255 void DrawFuncShading(const RetainPtr<CFX_DIBitmap>& pBitmap,
256                      const CFX_Matrix& mtObject2Bitmap,
257                      const CPDF_Dictionary* pDict,
258                      const std::vector<std::unique_ptr<CPDF_Function>>& funcs,
259                      const RetainPtr<CPDF_ColorSpace>& pCS,
260                      int alpha) {
261   ASSERT(pBitmap->GetFormat() == FXDIB_Format::kArgb);
262 
263   const uint32_t total_results = GetValidatedOutputsCount(funcs, pCS);
264   if (total_results == 0)
265     return;
266 
267   const CPDF_Array* pDomain = pDict->GetArrayFor("Domain");
268   float xmin = 0.0f;
269   float ymin = 0.0f;
270   float xmax = 1.0f;
271   float ymax = 1.0f;
272   if (pDomain) {
273     xmin = pDomain->GetNumberAt(0);
274     xmax = pDomain->GetNumberAt(1);
275     ymin = pDomain->GetNumberAt(2);
276     ymax = pDomain->GetNumberAt(3);
277   }
278   CFX_Matrix mtDomain2Target = pDict->GetMatrixFor("Matrix");
279   CFX_Matrix matrix =
280       mtObject2Bitmap.GetInverse() * mtDomain2Target.GetInverse();
281   int width = pBitmap->GetWidth();
282   int height = pBitmap->GetHeight();
283   int pitch = pBitmap->GetPitch();
284 
285   ASSERT(total_results >= CountOutputsFromFunctions(funcs));
286   ASSERT(total_results >= pCS->CountComponents());
287   std::vector<float> result_array(total_results);
288   for (int row = 0; row < height; ++row) {
289     uint32_t* dib_buf = (uint32_t*)(pBitmap->GetBuffer() + row * pitch);
290     for (int column = 0; column < width; column++) {
291       CFX_PointF pos = matrix.Transform(
292           CFX_PointF(static_cast<float>(column), static_cast<float>(row)));
293       if (pos.x < xmin || pos.x > xmax || pos.y < ymin || pos.y > ymax)
294         continue;
295 
296       float input[] = {pos.x, pos.y};
297       int offset = 0;
298       for (const auto& func : funcs) {
299         if (func) {
300           int nresults;
301           if (func->Call(input, 2, &result_array[offset], &nresults))
302             offset += nresults;
303         }
304       }
305 
306       float R = 0.0f;
307       float G = 0.0f;
308       float B = 0.0f;
309       pCS->GetRGB(result_array, &R, &G, &B);
310       dib_buf[column] = ArgbEncode(alpha, (int32_t)(R * 255),
311                                    (int32_t)(G * 255), (int32_t)(B * 255));
312     }
313   }
314 }
315 
GetScanlineIntersect(int y,const CFX_PointF & first,const CFX_PointF & second,float * x)316 bool GetScanlineIntersect(int y,
317                           const CFX_PointF& first,
318                           const CFX_PointF& second,
319                           float* x) {
320   if (first.y == second.y)
321     return false;
322 
323   if (first.y < second.y) {
324     if (y < first.y || y > second.y)
325       return false;
326   } else if (y < second.y || y > first.y) {
327     return false;
328   }
329   *x = first.x + ((second.x - first.x) * (y - first.y) / (second.y - first.y));
330   return true;
331 }
332 
DrawGouraud(const RetainPtr<CFX_DIBitmap> & pBitmap,int alpha,CPDF_MeshVertex triangle[3])333 void DrawGouraud(const RetainPtr<CFX_DIBitmap>& pBitmap,
334                  int alpha,
335                  CPDF_MeshVertex triangle[3]) {
336   float min_y = triangle[0].position.y;
337   float max_y = triangle[0].position.y;
338   for (int i = 1; i < 3; i++) {
339     min_y = std::min(min_y, triangle[i].position.y);
340     max_y = std::max(max_y, triangle[i].position.y);
341   }
342   if (min_y == max_y)
343     return;
344 
345   int min_yi = std::max(static_cast<int>(floorf(min_y)), 0);
346   int max_yi = static_cast<int>(ceilf(max_y));
347   if (max_yi >= pBitmap->GetHeight())
348     max_yi = pBitmap->GetHeight() - 1;
349 
350   for (int y = min_yi; y <= max_yi; y++) {
351     int nIntersects = 0;
352     float inter_x[3];
353     float r[3];
354     float g[3];
355     float b[3];
356     for (int i = 0; i < 3; i++) {
357       CPDF_MeshVertex& vertex1 = triangle[i];
358       CPDF_MeshVertex& vertex2 = triangle[(i + 1) % 3];
359       CFX_PointF& position1 = vertex1.position;
360       CFX_PointF& position2 = vertex2.position;
361       bool bIntersect =
362           GetScanlineIntersect(y, position1, position2, &inter_x[nIntersects]);
363       if (!bIntersect)
364         continue;
365 
366       float y_dist = (y - position1.y) / (position2.y - position1.y);
367       r[nIntersects] = vertex1.r + ((vertex2.r - vertex1.r) * y_dist);
368       g[nIntersects] = vertex1.g + ((vertex2.g - vertex1.g) * y_dist);
369       b[nIntersects] = vertex1.b + ((vertex2.b - vertex1.b) * y_dist);
370       nIntersects++;
371     }
372     if (nIntersects != 2)
373       continue;
374 
375     int min_x;
376     int max_x;
377     int start_index;
378     int end_index;
379     if (inter_x[0] < inter_x[1]) {
380       min_x = static_cast<int>(floorf(inter_x[0]));
381       max_x = static_cast<int>(ceilf(inter_x[1]));
382       start_index = 0;
383       end_index = 1;
384     } else {
385       min_x = static_cast<int>(floorf(inter_x[1]));
386       max_x = static_cast<int>(ceilf(inter_x[0]));
387       start_index = 1;
388       end_index = 0;
389     }
390 
391     int start_x = std::max(min_x, 0);
392     int end_x = std::min(max_x, pBitmap->GetWidth());
393 
394     uint8_t* dib_buf =
395         pBitmap->GetBuffer() + y * pBitmap->GetPitch() + start_x * 4;
396     float r_unit = (r[end_index] - r[start_index]) / (max_x - min_x);
397     float g_unit = (g[end_index] - g[start_index]) / (max_x - min_x);
398     float b_unit = (b[end_index] - b[start_index]) / (max_x - min_x);
399     float r_result = r[start_index] + (start_x - min_x) * r_unit;
400     float g_result = g[start_index] + (start_x - min_x) * g_unit;
401     float b_result = b[start_index] + (start_x - min_x) * b_unit;
402     for (int x = start_x; x < end_x; x++) {
403       r_result += r_unit;
404       g_result += g_unit;
405       b_result += b_unit;
406       FXARGB_SETDIB(dib_buf, ArgbEncode(alpha, static_cast<int>(r_result * 255),
407                                         static_cast<int>(g_result * 255),
408                                         static_cast<int>(b_result * 255)));
409       dib_buf += 4;
410     }
411   }
412 }
413 
DrawFreeGouraudShading(const RetainPtr<CFX_DIBitmap> & pBitmap,const CFX_Matrix & mtObject2Bitmap,const CPDF_Stream * pShadingStream,const std::vector<std::unique_ptr<CPDF_Function>> & funcs,const RetainPtr<CPDF_ColorSpace> & pCS,int alpha)414 void DrawFreeGouraudShading(
415     const RetainPtr<CFX_DIBitmap>& pBitmap,
416     const CFX_Matrix& mtObject2Bitmap,
417     const CPDF_Stream* pShadingStream,
418     const std::vector<std::unique_ptr<CPDF_Function>>& funcs,
419     const RetainPtr<CPDF_ColorSpace>& pCS,
420     int alpha) {
421   ASSERT(pBitmap->GetFormat() == FXDIB_Format::kArgb);
422 
423   CPDF_MeshStream stream(kFreeFormGouraudTriangleMeshShading, funcs,
424                          pShadingStream, pCS);
425   if (!stream.Load())
426     return;
427 
428   CPDF_MeshVertex triangle[3];
429   while (!stream.BitStream()->IsEOF()) {
430     CPDF_MeshVertex vertex;
431     uint32_t flag;
432     if (!stream.ReadVertex(mtObject2Bitmap, &vertex, &flag))
433       return;
434 
435     if (flag == 0) {
436       triangle[0] = vertex;
437       for (int i = 1; i < 3; ++i) {
438         uint32_t dummy_flag;
439         if (!stream.ReadVertex(mtObject2Bitmap, &triangle[i], &dummy_flag))
440           return;
441       }
442     } else {
443       if (flag == 1)
444         triangle[0] = triangle[1];
445 
446       triangle[1] = triangle[2];
447       triangle[2] = vertex;
448     }
449     DrawGouraud(pBitmap, alpha, triangle);
450   }
451 }
452 
DrawLatticeGouraudShading(const RetainPtr<CFX_DIBitmap> & pBitmap,const CFX_Matrix & mtObject2Bitmap,const CPDF_Stream * pShadingStream,const std::vector<std::unique_ptr<CPDF_Function>> & funcs,const RetainPtr<CPDF_ColorSpace> & pCS,int alpha)453 void DrawLatticeGouraudShading(
454     const RetainPtr<CFX_DIBitmap>& pBitmap,
455     const CFX_Matrix& mtObject2Bitmap,
456     const CPDF_Stream* pShadingStream,
457     const std::vector<std::unique_ptr<CPDF_Function>>& funcs,
458     const RetainPtr<CPDF_ColorSpace>& pCS,
459     int alpha) {
460   ASSERT(pBitmap->GetFormat() == FXDIB_Format::kArgb);
461 
462   int row_verts = pShadingStream->GetDict()->GetIntegerFor("VerticesPerRow");
463   if (row_verts < 2)
464     return;
465 
466   CPDF_MeshStream stream(kLatticeFormGouraudTriangleMeshShading, funcs,
467                          pShadingStream, pCS);
468   if (!stream.Load())
469     return;
470 
471   std::vector<CPDF_MeshVertex> vertices[2];
472   vertices[0] = stream.ReadVertexRow(mtObject2Bitmap, row_verts);
473   if (vertices[0].empty())
474     return;
475 
476   int last_index = 0;
477   while (1) {
478     vertices[1 - last_index] = stream.ReadVertexRow(mtObject2Bitmap, row_verts);
479     if (vertices[1 - last_index].empty())
480       return;
481 
482     CPDF_MeshVertex triangle[3];
483     for (int i = 1; i < row_verts; ++i) {
484       triangle[0] = vertices[last_index][i];
485       triangle[1] = vertices[1 - last_index][i - 1];
486       triangle[2] = vertices[last_index][i - 1];
487       DrawGouraud(pBitmap, alpha, triangle);
488       triangle[2] = vertices[1 - last_index][i];
489       DrawGouraud(pBitmap, alpha, triangle);
490     }
491     last_index = 1 - last_index;
492   }
493 }
494 
495 struct Coon_BezierCoeff {
496   float a, b, c, d;
FromPoints__anond726d90d0111::Coon_BezierCoeff497   void FromPoints(float p0, float p1, float p2, float p3) {
498     a = -p0 + 3 * p1 - 3 * p2 + p3;
499     b = 3 * p0 - 6 * p1 + 3 * p2;
500     c = -3 * p0 + 3 * p1;
501     d = p0;
502   }
first_half__anond726d90d0111::Coon_BezierCoeff503   Coon_BezierCoeff first_half() {
504     Coon_BezierCoeff result;
505     result.a = a / 8;
506     result.b = b / 4;
507     result.c = c / 2;
508     result.d = d;
509     return result;
510   }
second_half__anond726d90d0111::Coon_BezierCoeff511   Coon_BezierCoeff second_half() {
512     Coon_BezierCoeff result;
513     result.a = a / 8;
514     result.b = 3 * a / 8 + b / 4;
515     result.c = 3 * a / 8 + b / 2 + c / 2;
516     result.d = a / 8 + b / 4 + c / 2 + d;
517     return result;
518   }
GetPoints__anond726d90d0111::Coon_BezierCoeff519   void GetPoints(float p[4]) {
520     p[0] = d;
521     p[1] = c / 3 + p[0];
522     p[2] = b / 3 - p[0] + 2 * p[1];
523     p[3] = a + p[0] - 3 * p[1] + 3 * p[2];
524   }
BezierInterpol__anond726d90d0111::Coon_BezierCoeff525   void BezierInterpol(Coon_BezierCoeff& C1,
526                       Coon_BezierCoeff& C2,
527                       Coon_BezierCoeff& D1,
528                       Coon_BezierCoeff& D2) {
529     a = (D1.a + D2.a) / 2;
530     b = (D1.b + D2.b) / 2;
531     c = (D1.c + D2.c) / 2 - (C1.a / 8 + C1.b / 4 + C1.c / 2) +
532         (C2.a / 8 + C2.b / 4) + (-C1.d + D2.d) / 2 - (C2.a + C2.b) / 2;
533     d = C1.a / 8 + C1.b / 4 + C1.c / 2 + C1.d;
534   }
Distance__anond726d90d0111::Coon_BezierCoeff535   float Distance() {
536     float dis = a + b + c;
537     return dis < 0 ? -dis : dis;
538   }
539 };
540 
541 struct Coon_Bezier {
542   Coon_BezierCoeff x, y;
FromPoints__anond726d90d0111::Coon_Bezier543   void FromPoints(float x0,
544                   float y0,
545                   float x1,
546                   float y1,
547                   float x2,
548                   float y2,
549                   float x3,
550                   float y3) {
551     x.FromPoints(x0, x1, x2, x3);
552     y.FromPoints(y0, y1, y2, y3);
553   }
554 
first_half__anond726d90d0111::Coon_Bezier555   Coon_Bezier first_half() {
556     Coon_Bezier result;
557     result.x = x.first_half();
558     result.y = y.first_half();
559     return result;
560   }
561 
second_half__anond726d90d0111::Coon_Bezier562   Coon_Bezier second_half() {
563     Coon_Bezier result;
564     result.x = x.second_half();
565     result.y = y.second_half();
566     return result;
567   }
568 
BezierInterpol__anond726d90d0111::Coon_Bezier569   void BezierInterpol(Coon_Bezier& C1,
570                       Coon_Bezier& C2,
571                       Coon_Bezier& D1,
572                       Coon_Bezier& D2) {
573     x.BezierInterpol(C1.x, C2.x, D1.x, D2.x);
574     y.BezierInterpol(C1.y, C2.y, D1.y, D2.y);
575   }
576 
GetPoints__anond726d90d0111::Coon_Bezier577   void GetPoints(pdfium::span<FX_PATHPOINT> path_points) {
578     constexpr size_t kPointsCount = 4;
579     float points_x[kPointsCount];
580     float points_y[kPointsCount];
581     x.GetPoints(points_x);
582     y.GetPoints(points_y);
583     for (size_t i = 0; i < kPointsCount; ++i)
584       path_points[i].m_Point = {points_x[i], points_y[i]};
585   }
586 
GetPointsReverse__anond726d90d0111::Coon_Bezier587   void GetPointsReverse(pdfium::span<FX_PATHPOINT> path_points) {
588     constexpr size_t kPointsCount = 4;
589     float points_x[kPointsCount];
590     float points_y[kPointsCount];
591     x.GetPoints(points_x);
592     y.GetPoints(points_y);
593     for (size_t i = 0; i < kPointsCount; ++i) {
594       size_t reverse_index = kPointsCount - i - 1;
595       path_points[i].m_Point = {points_x[reverse_index],
596                                 points_y[reverse_index]};
597     }
598   }
599 
Distance__anond726d90d0111::Coon_Bezier600   float Distance() { return x.Distance() + y.Distance(); }
601 };
602 
Interpolate(int p1,int p2,int delta1,int delta2,bool * overflow)603 int Interpolate(int p1, int p2, int delta1, int delta2, bool* overflow) {
604   FX_SAFE_INT32 p = p2;
605   p -= p1;
606   p *= delta1;
607   p /= delta2;
608   p += p1;
609   if (!p.IsValid())
610     *overflow = true;
611   return p.ValueOrDefault(0);
612 }
613 
BiInterpolImpl(int c0,int c1,int c2,int c3,int x,int y,int x_scale,int y_scale,bool * overflow)614 int BiInterpolImpl(int c0,
615                    int c1,
616                    int c2,
617                    int c3,
618                    int x,
619                    int y,
620                    int x_scale,
621                    int y_scale,
622                    bool* overflow) {
623   int x1 = Interpolate(c0, c3, x, x_scale, overflow);
624   int x2 = Interpolate(c1, c2, x, x_scale, overflow);
625   return Interpolate(x1, x2, y, y_scale, overflow);
626 }
627 
628 struct Coon_Color {
Coon_Color__anond726d90d0111::Coon_Color629   Coon_Color() { memset(comp, 0, sizeof(int) * 3); }
630 
631   // Returns true if successful, false if overflow detected.
BiInterpol__anond726d90d0111::Coon_Color632   bool BiInterpol(Coon_Color colors[4],
633                   int x,
634                   int y,
635                   int x_scale,
636                   int y_scale) {
637     bool overflow = false;
638     for (int i = 0; i < 3; i++) {
639       comp[i] = BiInterpolImpl(colors[0].comp[i], colors[1].comp[i],
640                                colors[2].comp[i], colors[3].comp[i], x, y,
641                                x_scale, y_scale, &overflow);
642     }
643     return !overflow;
644   }
645 
Distance__anond726d90d0111::Coon_Color646   int Distance(Coon_Color& o) {
647     return std::max({abs(comp[0] - o.comp[0]), abs(comp[1] - o.comp[1]),
648                      abs(comp[2] - o.comp[2])});
649   }
650 
651   int comp[3];
652 };
653 
654 #define COONCOLOR_THRESHOLD 4
655 struct CPDF_PatchDrawer {
Draw__anond726d90d0111::CPDF_PatchDrawer656   void Draw(int x_scale,
657             int y_scale,
658             int left,
659             int bottom,
660             Coon_Bezier C1,
661             Coon_Bezier C2,
662             Coon_Bezier D1,
663             Coon_Bezier D2) {
664     bool bSmall = C1.Distance() < 2 && C2.Distance() < 2 && D1.Distance() < 2 &&
665                   D2.Distance() < 2;
666     Coon_Color div_colors[4];
667     int d_bottom = 0;
668     int d_left = 0;
669     int d_top = 0;
670     int d_right = 0;
671     if (!div_colors[0].BiInterpol(patch_colors, left, bottom, x_scale,
672                                   y_scale)) {
673       return;
674     }
675     if (!bSmall) {
676       if (!div_colors[1].BiInterpol(patch_colors, left, bottom + 1, x_scale,
677                                     y_scale)) {
678         return;
679       }
680       if (!div_colors[2].BiInterpol(patch_colors, left + 1, bottom + 1, x_scale,
681                                     y_scale)) {
682         return;
683       }
684       if (!div_colors[3].BiInterpol(patch_colors, left + 1, bottom, x_scale,
685                                     y_scale)) {
686         return;
687       }
688       d_bottom = div_colors[3].Distance(div_colors[0]);
689       d_left = div_colors[1].Distance(div_colors[0]);
690       d_top = div_colors[1].Distance(div_colors[2]);
691       d_right = div_colors[2].Distance(div_colors[3]);
692     }
693 
694     if (bSmall ||
695         (d_bottom < COONCOLOR_THRESHOLD && d_left < COONCOLOR_THRESHOLD &&
696          d_top < COONCOLOR_THRESHOLD && d_right < COONCOLOR_THRESHOLD)) {
697       pdfium::span<FX_PATHPOINT> points = path.GetPoints();
698       C1.GetPoints(points.subspan(0, 4));
699       D2.GetPoints(points.subspan(3, 4));
700       C2.GetPointsReverse(points.subspan(6, 4));
701       D1.GetPointsReverse(points.subspan(9, 4));
702       CFX_FillRenderOptions fill_options(
703           CFX_FillRenderOptions::WindingOptions());
704       fill_options.full_cover = true;
705       if (bNoPathSmooth)
706         fill_options.aliased_path = true;
707       pDevice->DrawPath(
708           &path, nullptr, nullptr,
709           ArgbEncode(alpha, div_colors[0].comp[0], div_colors[0].comp[1],
710                      div_colors[0].comp[2]),
711           0, fill_options);
712     } else {
713       if (d_bottom < COONCOLOR_THRESHOLD && d_top < COONCOLOR_THRESHOLD) {
714         Coon_Bezier m1;
715         m1.BezierInterpol(D1, D2, C1, C2);
716         y_scale *= 2;
717         bottom *= 2;
718         Draw(x_scale, y_scale, left, bottom, C1, m1, D1.first_half(),
719              D2.first_half());
720         Draw(x_scale, y_scale, left, bottom + 1, m1, C2, D1.second_half(),
721              D2.second_half());
722       } else if (d_left < COONCOLOR_THRESHOLD &&
723                  d_right < COONCOLOR_THRESHOLD) {
724         Coon_Bezier m2;
725         m2.BezierInterpol(C1, C2, D1, D2);
726         x_scale *= 2;
727         left *= 2;
728         Draw(x_scale, y_scale, left, bottom, C1.first_half(), C2.first_half(),
729              D1, m2);
730         Draw(x_scale, y_scale, left + 1, bottom, C1.second_half(),
731              C2.second_half(), m2, D2);
732       } else {
733         Coon_Bezier m1, m2;
734         m1.BezierInterpol(D1, D2, C1, C2);
735         m2.BezierInterpol(C1, C2, D1, D2);
736         Coon_Bezier m1f = m1.first_half();
737         Coon_Bezier m1s = m1.second_half();
738         Coon_Bezier m2f = m2.first_half();
739         Coon_Bezier m2s = m2.second_half();
740         x_scale *= 2;
741         y_scale *= 2;
742         left *= 2;
743         bottom *= 2;
744         Draw(x_scale, y_scale, left, bottom, C1.first_half(), m1f,
745              D1.first_half(), m2f);
746         Draw(x_scale, y_scale, left, bottom + 1, m1f, C2.first_half(),
747              D1.second_half(), m2s);
748         Draw(x_scale, y_scale, left + 1, bottom, C1.second_half(), m1s, m2f,
749              D2.first_half());
750         Draw(x_scale, y_scale, left + 1, bottom + 1, m1s, C2.second_half(), m2s,
751              D2.second_half());
752       }
753     }
754   }
755 
756   int max_delta;
757   CFX_PathData path;
758   CFX_RenderDevice* pDevice;
759   int bNoPathSmooth;
760   int alpha;
761   Coon_Color patch_colors[4];
762 };
763 
DrawCoonPatchMeshes(ShadingType type,const RetainPtr<CFX_DIBitmap> & pBitmap,const CFX_Matrix & mtObject2Bitmap,const CPDF_Stream * pShadingStream,const std::vector<std::unique_ptr<CPDF_Function>> & funcs,const RetainPtr<CPDF_ColorSpace> & pCS,bool bNoPathSmooth,int alpha)764 void DrawCoonPatchMeshes(
765     ShadingType type,
766     const RetainPtr<CFX_DIBitmap>& pBitmap,
767     const CFX_Matrix& mtObject2Bitmap,
768     const CPDF_Stream* pShadingStream,
769     const std::vector<std::unique_ptr<CPDF_Function>>& funcs,
770     const RetainPtr<CPDF_ColorSpace>& pCS,
771     bool bNoPathSmooth,
772     int alpha) {
773   ASSERT(pBitmap->GetFormat() == FXDIB_Format::kArgb);
774   ASSERT(type == kCoonsPatchMeshShading ||
775          type == kTensorProductPatchMeshShading);
776 
777   CFX_DefaultRenderDevice device;
778   device.Attach(pBitmap, false, nullptr, false);
779   CPDF_MeshStream stream(type, funcs, pShadingStream, pCS);
780   if (!stream.Load())
781     return;
782 
783   CPDF_PatchDrawer patch;
784   patch.alpha = alpha;
785   patch.pDevice = &device;
786   patch.bNoPathSmooth = bNoPathSmooth;
787 
788   for (int i = 0; i < 13; i++) {
789     patch.path.AppendPoint(CFX_PointF(),
790                            i == 0 ? FXPT_TYPE::MoveTo : FXPT_TYPE::BezierTo);
791   }
792 
793   CFX_PointF coords[16];
794   int point_count = type == kTensorProductPatchMeshShading ? 16 : 12;
795   while (!stream.BitStream()->IsEOF()) {
796     if (!stream.CanReadFlag())
797       break;
798     uint32_t flag = stream.ReadFlag();
799     int iStartPoint = 0, iStartColor = 0, i = 0;
800     if (flag) {
801       iStartPoint = 4;
802       iStartColor = 2;
803       CFX_PointF tempCoords[4];
804       for (i = 0; i < 4; i++) {
805         tempCoords[i] = coords[(flag * 3 + i) % 12];
806       }
807       memcpy(coords, tempCoords, sizeof(tempCoords));
808       Coon_Color tempColors[2];
809       tempColors[0] = patch.patch_colors[flag];
810       tempColors[1] = patch.patch_colors[(flag + 1) % 4];
811       memcpy(patch.patch_colors, tempColors, sizeof(Coon_Color) * 2);
812     }
813     for (i = iStartPoint; i < point_count; i++) {
814       if (!stream.CanReadCoords())
815         break;
816       coords[i] = mtObject2Bitmap.Transform(stream.ReadCoords());
817     }
818 
819     for (i = iStartColor; i < 4; i++) {
820       if (!stream.CanReadColor())
821         break;
822 
823       float r;
824       float g;
825       float b;
826       std::tie(r, g, b) = stream.ReadColor();
827 
828       patch.patch_colors[i].comp[0] = (int32_t)(r * 255);
829       patch.patch_colors[i].comp[1] = (int32_t)(g * 255);
830       patch.patch_colors[i].comp[2] = (int32_t)(b * 255);
831     }
832     CFX_FloatRect bbox = CFX_FloatRect::GetBBox(coords, point_count);
833     if (bbox.right <= 0 || bbox.left >= (float)pBitmap->GetWidth() ||
834         bbox.top <= 0 || bbox.bottom >= (float)pBitmap->GetHeight()) {
835       continue;
836     }
837     Coon_Bezier C1, C2, D1, D2;
838     C1.FromPoints(coords[0].x, coords[0].y, coords[11].x, coords[11].y,
839                   coords[10].x, coords[10].y, coords[9].x, coords[9].y);
840     C2.FromPoints(coords[3].x, coords[3].y, coords[4].x, coords[4].y,
841                   coords[5].x, coords[5].y, coords[6].x, coords[6].y);
842     D1.FromPoints(coords[0].x, coords[0].y, coords[1].x, coords[1].y,
843                   coords[2].x, coords[2].y, coords[3].x, coords[3].y);
844     D2.FromPoints(coords[9].x, coords[9].y, coords[8].x, coords[8].y,
845                   coords[7].x, coords[7].y, coords[6].x, coords[6].y);
846     patch.Draw(1, 1, 0, 0, C1, C2, D1, D2);
847   }
848 }
849 
850 }  // namespace
851 
852 // static
Draw(CFX_RenderDevice * pDevice,CPDF_RenderContext * pContext,const CPDF_PageObject * pCurObj,const CPDF_ShadingPattern * pPattern,const CFX_Matrix & mtMatrix,const FX_RECT & clip_rect,int alpha,const CPDF_RenderOptions & options)853 void CPDF_RenderShading::Draw(CFX_RenderDevice* pDevice,
854                               CPDF_RenderContext* pContext,
855                               const CPDF_PageObject* pCurObj,
856                               const CPDF_ShadingPattern* pPattern,
857                               const CFX_Matrix& mtMatrix,
858                               const FX_RECT& clip_rect,
859                               int alpha,
860                               const CPDF_RenderOptions& options) {
861   const auto& funcs = pPattern->GetFuncs();
862   const CPDF_Dictionary* pDict = pPattern->GetShadingObject()->GetDict();
863   RetainPtr<CPDF_ColorSpace> pColorSpace = pPattern->GetCS();
864   if (!pColorSpace)
865     return;
866 
867   FX_ARGB background = 0;
868   if (!pPattern->IsShadingObject() && pDict->KeyExist("Background")) {
869     const CPDF_Array* pBackColor = pDict->GetArrayFor("Background");
870     if (pBackColor && pBackColor->size() >= pColorSpace->CountComponents()) {
871       std::vector<float> comps =
872           ReadArrayElementsToVector(pBackColor, pColorSpace->CountComponents());
873 
874       float R = 0.0f;
875       float G = 0.0f;
876       float B = 0.0f;
877       pColorSpace->GetRGB(comps, &R, &G, &B);
878       background = ArgbEncode(255, (int32_t)(R * 255), (int32_t)(G * 255),
879                               (int32_t)(B * 255));
880     }
881   }
882   FX_RECT clip_rect_bbox = clip_rect;
883   if (pDict->KeyExist("BBox")) {
884     clip_rect_bbox.Intersect(
885         mtMatrix.TransformRect(pDict->GetRectFor("BBox")).GetOuterRect());
886   }
887   bool bAlphaMode = options.ColorModeIs(CPDF_RenderOptions::kAlpha);
888   if (pDevice->GetDeviceCaps(FXDC_RENDER_CAPS) & FXRC_SHADING &&
889       pDevice->GetDeviceDriver()->DrawShading(
890           pPattern, &mtMatrix, clip_rect_bbox, alpha, bAlphaMode)) {
891     return;
892   }
893   CPDF_DeviceBuffer buffer(pContext, pDevice, clip_rect_bbox, pCurObj, 150);
894   if (!buffer.Initialize())
895     return;
896 
897   CFX_Matrix FinalMatrix = mtMatrix * buffer.GetMatrix();
898   RetainPtr<CFX_DIBitmap> pBitmap = buffer.GetBitmap();
899   if (!pBitmap->GetBuffer())
900     return;
901 
902   pBitmap->Clear(background);
903   switch (pPattern->GetShadingType()) {
904     case kInvalidShading:
905     case kMaxShading:
906       return;
907     case kFunctionBasedShading:
908       DrawFuncShading(pBitmap, FinalMatrix, pDict, funcs, pColorSpace, alpha);
909       break;
910     case kAxialShading:
911       DrawAxialShading(pBitmap, FinalMatrix, pDict, funcs, pColorSpace, alpha);
912       break;
913     case kRadialShading:
914       DrawRadialShading(pBitmap, FinalMatrix, pDict, funcs, pColorSpace, alpha);
915       break;
916     case kFreeFormGouraudTriangleMeshShading: {
917       // The shading object can be a stream or a dictionary. We do not handle
918       // the case of dictionary at the moment.
919       const CPDF_Stream* pStream = ToStream(pPattern->GetShadingObject());
920       if (pStream) {
921         DrawFreeGouraudShading(pBitmap, FinalMatrix, pStream, funcs,
922                                pColorSpace, alpha);
923       }
924       break;
925     }
926     case kLatticeFormGouraudTriangleMeshShading: {
927       // The shading object can be a stream or a dictionary. We do not handle
928       // the case of dictionary at the moment.
929       const CPDF_Stream* pStream = ToStream(pPattern->GetShadingObject());
930       if (pStream) {
931         DrawLatticeGouraudShading(pBitmap, FinalMatrix, pStream, funcs,
932                                   pColorSpace, alpha);
933       }
934       break;
935     }
936     case kCoonsPatchMeshShading:
937     case kTensorProductPatchMeshShading: {
938       // The shading object can be a stream or a dictionary. We do not handle
939       // the case of dictionary at the moment.
940       const CPDF_Stream* pStream = ToStream(pPattern->GetShadingObject());
941       if (pStream) {
942         DrawCoonPatchMeshes(pPattern->GetShadingType(), pBitmap, FinalMatrix,
943                             pStream, funcs, pColorSpace,
944                             options.GetOptions().bNoPathSmooth, alpha);
945       }
946       break;
947     }
948   }
949   if (bAlphaMode)
950     pBitmap->SetRedFromBitmap(pBitmap);
951 
952   if (options.ColorModeIs(CPDF_RenderOptions::kGray))
953     pBitmap->ConvertColorScale(0, 0xffffff);
954 
955   buffer.OutputToDevice();
956 }
957