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