pattern_helper.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * JavaScript code in this page
  4. *
  5. * Copyright 2022 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * JavaScript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.TilingPattern = exports.PathType = void 0;
  27. exports.getShadingPattern = getShadingPattern;
  28. var _util = require("../shared/util.js");
  29. var _display_utils = require("./display_utils.js");
  30. var _is_node = require("../shared/is_node.js");
  31. const PathType = {
  32. FILL: "Fill",
  33. STROKE: "Stroke",
  34. SHADING: "Shading"
  35. };
  36. exports.PathType = PathType;
  37. function applyBoundingBox(ctx, bbox) {
  38. if (!bbox || _is_node.isNodeJS) {
  39. return;
  40. }
  41. const width = bbox[2] - bbox[0];
  42. const height = bbox[3] - bbox[1];
  43. const region = new Path2D();
  44. region.rect(bbox[0], bbox[1], width, height);
  45. ctx.clip(region);
  46. }
  47. class BaseShadingPattern {
  48. constructor() {
  49. if (this.constructor === BaseShadingPattern) {
  50. (0, _util.unreachable)("Cannot initialize BaseShadingPattern.");
  51. }
  52. }
  53. getPattern() {
  54. (0, _util.unreachable)("Abstract method `getPattern` called.");
  55. }
  56. }
  57. class RadialAxialShadingPattern extends BaseShadingPattern {
  58. constructor(IR) {
  59. super();
  60. this._type = IR[1];
  61. this._bbox = IR[2];
  62. this._colorStops = IR[3];
  63. this._p0 = IR[4];
  64. this._p1 = IR[5];
  65. this._r0 = IR[6];
  66. this._r1 = IR[7];
  67. this.matrix = null;
  68. }
  69. _createGradient(ctx) {
  70. let grad;
  71. if (this._type === "axial") {
  72. grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
  73. } else if (this._type === "radial") {
  74. grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
  75. }
  76. for (const colorStop of this._colorStops) {
  77. grad.addColorStop(colorStop[0], colorStop[1]);
  78. }
  79. return grad;
  80. }
  81. getPattern(ctx, owner, inverse, pathType) {
  82. let pattern;
  83. if (pathType === PathType.STROKE || pathType === PathType.FILL) {
  84. const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, (0, _display_utils.getCurrentTransform)(ctx)) || [0, 0, 0, 0];
  85. const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1;
  86. const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1;
  87. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height, true);
  88. const tmpCtx = tmpCanvas.context;
  89. tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  90. tmpCtx.beginPath();
  91. tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  92. tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]);
  93. inverse = _util.Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]);
  94. tmpCtx.transform(...owner.baseTransform);
  95. if (this.matrix) {
  96. tmpCtx.transform(...this.matrix);
  97. }
  98. applyBoundingBox(tmpCtx, this._bbox);
  99. tmpCtx.fillStyle = this._createGradient(tmpCtx);
  100. tmpCtx.fill();
  101. pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat");
  102. const domMatrix = new DOMMatrix(inverse);
  103. pattern.setTransform(domMatrix);
  104. } else {
  105. applyBoundingBox(ctx, this._bbox);
  106. pattern = this._createGradient(ctx);
  107. }
  108. return pattern;
  109. }
  110. }
  111. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  112. const coords = context.coords,
  113. colors = context.colors;
  114. const bytes = data.data,
  115. rowSize = data.width * 4;
  116. let tmp;
  117. if (coords[p1 + 1] > coords[p2 + 1]) {
  118. tmp = p1;
  119. p1 = p2;
  120. p2 = tmp;
  121. tmp = c1;
  122. c1 = c2;
  123. c2 = tmp;
  124. }
  125. if (coords[p2 + 1] > coords[p3 + 1]) {
  126. tmp = p2;
  127. p2 = p3;
  128. p3 = tmp;
  129. tmp = c2;
  130. c2 = c3;
  131. c3 = tmp;
  132. }
  133. if (coords[p1 + 1] > coords[p2 + 1]) {
  134. tmp = p1;
  135. p1 = p2;
  136. p2 = tmp;
  137. tmp = c1;
  138. c1 = c2;
  139. c2 = tmp;
  140. }
  141. const x1 = (coords[p1] + context.offsetX) * context.scaleX;
  142. const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  143. const x2 = (coords[p2] + context.offsetX) * context.scaleX;
  144. const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  145. const x3 = (coords[p3] + context.offsetX) * context.scaleX;
  146. const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  147. if (y1 >= y3) {
  148. return;
  149. }
  150. const c1r = colors[c1],
  151. c1g = colors[c1 + 1],
  152. c1b = colors[c1 + 2];
  153. const c2r = colors[c2],
  154. c2g = colors[c2 + 1],
  155. c2b = colors[c2 + 2];
  156. const c3r = colors[c3],
  157. c3g = colors[c3 + 1],
  158. c3b = colors[c3 + 2];
  159. const minY = Math.round(y1),
  160. maxY = Math.round(y3);
  161. let xa, car, cag, cab;
  162. let xb, cbr, cbg, cbb;
  163. for (let y = minY; y <= maxY; y++) {
  164. if (y < y2) {
  165. let k;
  166. if (y < y1) {
  167. k = 0;
  168. } else {
  169. k = (y1 - y) / (y1 - y2);
  170. }
  171. xa = x1 - (x1 - x2) * k;
  172. car = c1r - (c1r - c2r) * k;
  173. cag = c1g - (c1g - c2g) * k;
  174. cab = c1b - (c1b - c2b) * k;
  175. } else {
  176. let k;
  177. if (y > y3) {
  178. k = 1;
  179. } else if (y2 === y3) {
  180. k = 0;
  181. } else {
  182. k = (y2 - y) / (y2 - y3);
  183. }
  184. xa = x2 - (x2 - x3) * k;
  185. car = c2r - (c2r - c3r) * k;
  186. cag = c2g - (c2g - c3g) * k;
  187. cab = c2b - (c2b - c3b) * k;
  188. }
  189. let k;
  190. if (y < y1) {
  191. k = 0;
  192. } else if (y > y3) {
  193. k = 1;
  194. } else {
  195. k = (y1 - y) / (y1 - y3);
  196. }
  197. xb = x1 - (x1 - x3) * k;
  198. cbr = c1r - (c1r - c3r) * k;
  199. cbg = c1g - (c1g - c3g) * k;
  200. cbb = c1b - (c1b - c3b) * k;
  201. const x1_ = Math.round(Math.min(xa, xb));
  202. const x2_ = Math.round(Math.max(xa, xb));
  203. let j = rowSize * y + x1_ * 4;
  204. for (let x = x1_; x <= x2_; x++) {
  205. k = (xa - x) / (xa - xb);
  206. if (k < 0) {
  207. k = 0;
  208. } else if (k > 1) {
  209. k = 1;
  210. }
  211. bytes[j++] = car - (car - cbr) * k | 0;
  212. bytes[j++] = cag - (cag - cbg) * k | 0;
  213. bytes[j++] = cab - (cab - cbb) * k | 0;
  214. bytes[j++] = 255;
  215. }
  216. }
  217. }
  218. function drawFigure(data, figure, context) {
  219. const ps = figure.coords;
  220. const cs = figure.colors;
  221. let i, ii;
  222. switch (figure.type) {
  223. case "lattice":
  224. const verticesPerRow = figure.verticesPerRow;
  225. const rows = Math.floor(ps.length / verticesPerRow) - 1;
  226. const cols = verticesPerRow - 1;
  227. for (i = 0; i < rows; i++) {
  228. let q = i * verticesPerRow;
  229. for (let j = 0; j < cols; j++, q++) {
  230. drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
  231. drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  232. }
  233. }
  234. break;
  235. case "triangles":
  236. for (i = 0, ii = ps.length; i < ii; i += 3) {
  237. drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
  238. }
  239. break;
  240. default:
  241. throw new Error("illegal figure");
  242. }
  243. }
  244. class MeshShadingPattern extends BaseShadingPattern {
  245. constructor(IR) {
  246. super();
  247. this._coords = IR[2];
  248. this._colors = IR[3];
  249. this._figures = IR[4];
  250. this._bounds = IR[5];
  251. this._bbox = IR[7];
  252. this._background = IR[8];
  253. this.matrix = null;
  254. }
  255. _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {
  256. const EXPECTED_SCALE = 1.1;
  257. const MAX_PATTERN_SIZE = 3000;
  258. const BORDER_SIZE = 2;
  259. const offsetX = Math.floor(this._bounds[0]);
  260. const offsetY = Math.floor(this._bounds[1]);
  261. const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
  262. const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;
  263. const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  264. const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  265. const scaleX = boundsWidth / width;
  266. const scaleY = boundsHeight / height;
  267. const context = {
  268. coords: this._coords,
  269. colors: this._colors,
  270. offsetX: -offsetX,
  271. offsetY: -offsetY,
  272. scaleX: 1 / scaleX,
  273. scaleY: 1 / scaleY
  274. };
  275. const paddedWidth = width + BORDER_SIZE * 2;
  276. const paddedHeight = height + BORDER_SIZE * 2;
  277. const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight, false);
  278. const tmpCtx = tmpCanvas.context;
  279. const data = tmpCtx.createImageData(width, height);
  280. if (backgroundColor) {
  281. const bytes = data.data;
  282. for (let i = 0, ii = bytes.length; i < ii; i += 4) {
  283. bytes[i] = backgroundColor[0];
  284. bytes[i + 1] = backgroundColor[1];
  285. bytes[i + 2] = backgroundColor[2];
  286. bytes[i + 3] = 255;
  287. }
  288. }
  289. for (const figure of this._figures) {
  290. drawFigure(data, figure, context);
  291. }
  292. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  293. const canvas = tmpCanvas.canvas;
  294. return {
  295. canvas,
  296. offsetX: offsetX - BORDER_SIZE * scaleX,
  297. offsetY: offsetY - BORDER_SIZE * scaleY,
  298. scaleX,
  299. scaleY
  300. };
  301. }
  302. getPattern(ctx, owner, inverse, pathType) {
  303. applyBoundingBox(ctx, this._bbox);
  304. let scale;
  305. if (pathType === PathType.SHADING) {
  306. scale = _util.Util.singularValueDecompose2dScale((0, _display_utils.getCurrentTransform)(ctx));
  307. } else {
  308. scale = _util.Util.singularValueDecompose2dScale(owner.baseTransform);
  309. if (this.matrix) {
  310. const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
  311. scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]];
  312. }
  313. }
  314. const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases);
  315. if (pathType !== PathType.SHADING) {
  316. ctx.setTransform(...owner.baseTransform);
  317. if (this.matrix) {
  318. ctx.transform(...this.matrix);
  319. }
  320. }
  321. ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  322. ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
  323. return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");
  324. }
  325. }
  326. class DummyShadingPattern extends BaseShadingPattern {
  327. getPattern() {
  328. return "hotpink";
  329. }
  330. }
  331. function getShadingPattern(IR) {
  332. switch (IR[0]) {
  333. case "RadialAxial":
  334. return new RadialAxialShadingPattern(IR);
  335. case "Mesh":
  336. return new MeshShadingPattern(IR);
  337. case "Dummy":
  338. return new DummyShadingPattern();
  339. }
  340. throw new Error(`Unknown IR type: ${IR[0]}`);
  341. }
  342. const PaintType = {
  343. COLORED: 1,
  344. UNCOLORED: 2
  345. };
  346. class TilingPattern {
  347. static get MAX_PATTERN_SIZE() {
  348. return (0, _util.shadow)(this, "MAX_PATTERN_SIZE", 3000);
  349. }
  350. constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  351. this.operatorList = IR[2];
  352. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  353. this.bbox = IR[4];
  354. this.xstep = IR[5];
  355. this.ystep = IR[6];
  356. this.paintType = IR[7];
  357. this.tilingType = IR[8];
  358. this.color = color;
  359. this.ctx = ctx;
  360. this.canvasGraphicsFactory = canvasGraphicsFactory;
  361. this.baseTransform = baseTransform;
  362. }
  363. createPatternCanvas(owner) {
  364. const operatorList = this.operatorList;
  365. const bbox = this.bbox;
  366. const xstep = this.xstep;
  367. const ystep = this.ystep;
  368. const paintType = this.paintType;
  369. const tilingType = this.tilingType;
  370. const color = this.color;
  371. const canvasGraphicsFactory = this.canvasGraphicsFactory;
  372. (0, _util.info)("TilingType: " + tilingType);
  373. const x0 = bbox[0],
  374. y0 = bbox[1],
  375. x1 = bbox[2],
  376. y1 = bbox[3];
  377. const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
  378. const curMatrixScale = _util.Util.singularValueDecompose2dScale(this.baseTransform);
  379. const combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]];
  380. const dimx = this.getSizeAndScale(xstep, this.ctx.canvas.width, combinedScale[0]);
  381. const dimy = this.getSizeAndScale(ystep, this.ctx.canvas.height, combinedScale[1]);
  382. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size, true);
  383. const tmpCtx = tmpCanvas.context;
  384. const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  385. graphics.groupLevel = owner.groupLevel;
  386. this.setFillAndStrokeStyleToContext(graphics, paintType, color);
  387. let adjustedX0 = x0;
  388. let adjustedY0 = y0;
  389. let adjustedX1 = x1;
  390. let adjustedY1 = y1;
  391. if (x0 < 0) {
  392. adjustedX0 = 0;
  393. adjustedX1 += Math.abs(x0);
  394. }
  395. if (y0 < 0) {
  396. adjustedY0 = 0;
  397. adjustedY1 += Math.abs(y0);
  398. }
  399. tmpCtx.translate(-(dimx.scale * adjustedX0), -(dimy.scale * adjustedY0));
  400. graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
  401. tmpCtx.save();
  402. this.clipBbox(graphics, adjustedX0, adjustedY0, adjustedX1, adjustedY1);
  403. graphics.baseTransform = (0, _display_utils.getCurrentTransform)(graphics.ctx);
  404. graphics.executeOperatorList(operatorList);
  405. graphics.endDrawing();
  406. return {
  407. canvas: tmpCanvas.canvas,
  408. scaleX: dimx.scale,
  409. scaleY: dimy.scale,
  410. offsetX: adjustedX0,
  411. offsetY: adjustedY0
  412. };
  413. }
  414. getSizeAndScale(step, realOutputSize, scale) {
  415. step = Math.abs(step);
  416. const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);
  417. let size = Math.ceil(step * scale);
  418. if (size >= maxSize) {
  419. size = maxSize;
  420. } else {
  421. scale = size / step;
  422. }
  423. return {
  424. scale,
  425. size
  426. };
  427. }
  428. clipBbox(graphics, x0, y0, x1, y1) {
  429. const bboxWidth = x1 - x0;
  430. const bboxHeight = y1 - y0;
  431. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  432. graphics.current.updateRectMinMax((0, _display_utils.getCurrentTransform)(graphics.ctx), [x0, y0, x1, y1]);
  433. graphics.clip();
  434. graphics.endPath();
  435. }
  436. setFillAndStrokeStyleToContext(graphics, paintType, color) {
  437. const context = graphics.ctx,
  438. current = graphics.current;
  439. switch (paintType) {
  440. case PaintType.COLORED:
  441. const ctx = this.ctx;
  442. context.fillStyle = ctx.fillStyle;
  443. context.strokeStyle = ctx.strokeStyle;
  444. current.fillColor = ctx.fillStyle;
  445. current.strokeColor = ctx.strokeStyle;
  446. break;
  447. case PaintType.UNCOLORED:
  448. const cssColor = _util.Util.makeHexColor(color[0], color[1], color[2]);
  449. context.fillStyle = cssColor;
  450. context.strokeStyle = cssColor;
  451. current.fillColor = cssColor;
  452. current.strokeColor = cssColor;
  453. break;
  454. default:
  455. throw new _util.FormatError(`Unsupported paint type: ${paintType}`);
  456. }
  457. }
  458. getPattern(ctx, owner, inverse, pathType) {
  459. let matrix = inverse;
  460. if (pathType !== PathType.SHADING) {
  461. matrix = _util.Util.transform(matrix, owner.baseTransform);
  462. if (this.matrix) {
  463. matrix = _util.Util.transform(matrix, this.matrix);
  464. }
  465. }
  466. const temporaryPatternCanvas = this.createPatternCanvas(owner);
  467. let domMatrix = new DOMMatrix(matrix);
  468. domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  469. domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);
  470. const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");
  471. pattern.setTransform(domMatrix);
  472. return pattern;
  473. }
  474. }
  475. exports.TilingPattern = TilingPattern;