2
0

pattern_helper.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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. try {
  104. pattern.setTransform(domMatrix);
  105. } catch (ex) {
  106. (0, _util.warn)(`RadialAxialShadingPattern.getPattern: "${ex?.message}".`);
  107. }
  108. } else {
  109. applyBoundingBox(ctx, this._bbox);
  110. pattern = this._createGradient(ctx);
  111. }
  112. return pattern;
  113. }
  114. }
  115. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  116. const coords = context.coords,
  117. colors = context.colors;
  118. const bytes = data.data,
  119. rowSize = data.width * 4;
  120. let tmp;
  121. if (coords[p1 + 1] > coords[p2 + 1]) {
  122. tmp = p1;
  123. p1 = p2;
  124. p2 = tmp;
  125. tmp = c1;
  126. c1 = c2;
  127. c2 = tmp;
  128. }
  129. if (coords[p2 + 1] > coords[p3 + 1]) {
  130. tmp = p2;
  131. p2 = p3;
  132. p3 = tmp;
  133. tmp = c2;
  134. c2 = c3;
  135. c3 = tmp;
  136. }
  137. if (coords[p1 + 1] > coords[p2 + 1]) {
  138. tmp = p1;
  139. p1 = p2;
  140. p2 = tmp;
  141. tmp = c1;
  142. c1 = c2;
  143. c2 = tmp;
  144. }
  145. const x1 = (coords[p1] + context.offsetX) * context.scaleX;
  146. const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  147. const x2 = (coords[p2] + context.offsetX) * context.scaleX;
  148. const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  149. const x3 = (coords[p3] + context.offsetX) * context.scaleX;
  150. const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  151. if (y1 >= y3) {
  152. return;
  153. }
  154. const c1r = colors[c1],
  155. c1g = colors[c1 + 1],
  156. c1b = colors[c1 + 2];
  157. const c2r = colors[c2],
  158. c2g = colors[c2 + 1],
  159. c2b = colors[c2 + 2];
  160. const c3r = colors[c3],
  161. c3g = colors[c3 + 1],
  162. c3b = colors[c3 + 2];
  163. const minY = Math.round(y1),
  164. maxY = Math.round(y3);
  165. let xa, car, cag, cab;
  166. let xb, cbr, cbg, cbb;
  167. for (let y = minY; y <= maxY; y++) {
  168. if (y < y2) {
  169. let k;
  170. if (y < y1) {
  171. k = 0;
  172. } else {
  173. k = (y1 - y) / (y1 - y2);
  174. }
  175. xa = x1 - (x1 - x2) * k;
  176. car = c1r - (c1r - c2r) * k;
  177. cag = c1g - (c1g - c2g) * k;
  178. cab = c1b - (c1b - c2b) * k;
  179. } else {
  180. let k;
  181. if (y > y3) {
  182. k = 1;
  183. } else if (y2 === y3) {
  184. k = 0;
  185. } else {
  186. k = (y2 - y) / (y2 - y3);
  187. }
  188. xa = x2 - (x2 - x3) * k;
  189. car = c2r - (c2r - c3r) * k;
  190. cag = c2g - (c2g - c3g) * k;
  191. cab = c2b - (c2b - c3b) * k;
  192. }
  193. let k;
  194. if (y < y1) {
  195. k = 0;
  196. } else if (y > y3) {
  197. k = 1;
  198. } else {
  199. k = (y1 - y) / (y1 - y3);
  200. }
  201. xb = x1 - (x1 - x3) * k;
  202. cbr = c1r - (c1r - c3r) * k;
  203. cbg = c1g - (c1g - c3g) * k;
  204. cbb = c1b - (c1b - c3b) * k;
  205. const x1_ = Math.round(Math.min(xa, xb));
  206. const x2_ = Math.round(Math.max(xa, xb));
  207. let j = rowSize * y + x1_ * 4;
  208. for (let x = x1_; x <= x2_; x++) {
  209. k = (xa - x) / (xa - xb);
  210. if (k < 0) {
  211. k = 0;
  212. } else if (k > 1) {
  213. k = 1;
  214. }
  215. bytes[j++] = car - (car - cbr) * k | 0;
  216. bytes[j++] = cag - (cag - cbg) * k | 0;
  217. bytes[j++] = cab - (cab - cbb) * k | 0;
  218. bytes[j++] = 255;
  219. }
  220. }
  221. }
  222. function drawFigure(data, figure, context) {
  223. const ps = figure.coords;
  224. const cs = figure.colors;
  225. let i, ii;
  226. switch (figure.type) {
  227. case "lattice":
  228. const verticesPerRow = figure.verticesPerRow;
  229. const rows = Math.floor(ps.length / verticesPerRow) - 1;
  230. const cols = verticesPerRow - 1;
  231. for (i = 0; i < rows; i++) {
  232. let q = i * verticesPerRow;
  233. for (let j = 0; j < cols; j++, q++) {
  234. drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
  235. drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  236. }
  237. }
  238. break;
  239. case "triangles":
  240. for (i = 0, ii = ps.length; i < ii; i += 3) {
  241. drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
  242. }
  243. break;
  244. default:
  245. throw new Error("illegal figure");
  246. }
  247. }
  248. class MeshShadingPattern extends BaseShadingPattern {
  249. constructor(IR) {
  250. super();
  251. this._coords = IR[2];
  252. this._colors = IR[3];
  253. this._figures = IR[4];
  254. this._bounds = IR[5];
  255. this._bbox = IR[7];
  256. this._background = IR[8];
  257. this.matrix = null;
  258. }
  259. _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {
  260. const EXPECTED_SCALE = 1.1;
  261. const MAX_PATTERN_SIZE = 3000;
  262. const BORDER_SIZE = 2;
  263. const offsetX = Math.floor(this._bounds[0]);
  264. const offsetY = Math.floor(this._bounds[1]);
  265. const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
  266. const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;
  267. const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  268. const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  269. const scaleX = boundsWidth / width;
  270. const scaleY = boundsHeight / height;
  271. const context = {
  272. coords: this._coords,
  273. colors: this._colors,
  274. offsetX: -offsetX,
  275. offsetY: -offsetY,
  276. scaleX: 1 / scaleX,
  277. scaleY: 1 / scaleY
  278. };
  279. const paddedWidth = width + BORDER_SIZE * 2;
  280. const paddedHeight = height + BORDER_SIZE * 2;
  281. const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight, false);
  282. const tmpCtx = tmpCanvas.context;
  283. const data = tmpCtx.createImageData(width, height);
  284. if (backgroundColor) {
  285. const bytes = data.data;
  286. for (let i = 0, ii = bytes.length; i < ii; i += 4) {
  287. bytes[i] = backgroundColor[0];
  288. bytes[i + 1] = backgroundColor[1];
  289. bytes[i + 2] = backgroundColor[2];
  290. bytes[i + 3] = 255;
  291. }
  292. }
  293. for (const figure of this._figures) {
  294. drawFigure(data, figure, context);
  295. }
  296. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  297. const canvas = tmpCanvas.canvas;
  298. return {
  299. canvas,
  300. offsetX: offsetX - BORDER_SIZE * scaleX,
  301. offsetY: offsetY - BORDER_SIZE * scaleY,
  302. scaleX,
  303. scaleY
  304. };
  305. }
  306. getPattern(ctx, owner, inverse, pathType) {
  307. applyBoundingBox(ctx, this._bbox);
  308. let scale;
  309. if (pathType === PathType.SHADING) {
  310. scale = _util.Util.singularValueDecompose2dScale((0, _display_utils.getCurrentTransform)(ctx));
  311. } else {
  312. scale = _util.Util.singularValueDecompose2dScale(owner.baseTransform);
  313. if (this.matrix) {
  314. const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
  315. scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]];
  316. }
  317. }
  318. const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases);
  319. if (pathType !== PathType.SHADING) {
  320. ctx.setTransform(...owner.baseTransform);
  321. if (this.matrix) {
  322. ctx.transform(...this.matrix);
  323. }
  324. }
  325. ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  326. ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
  327. return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");
  328. }
  329. }
  330. class DummyShadingPattern extends BaseShadingPattern {
  331. getPattern() {
  332. return "hotpink";
  333. }
  334. }
  335. function getShadingPattern(IR) {
  336. switch (IR[0]) {
  337. case "RadialAxial":
  338. return new RadialAxialShadingPattern(IR);
  339. case "Mesh":
  340. return new MeshShadingPattern(IR);
  341. case "Dummy":
  342. return new DummyShadingPattern();
  343. }
  344. throw new Error(`Unknown IR type: ${IR[0]}`);
  345. }
  346. const PaintType = {
  347. COLORED: 1,
  348. UNCOLORED: 2
  349. };
  350. class TilingPattern {
  351. static get MAX_PATTERN_SIZE() {
  352. return (0, _util.shadow)(this, "MAX_PATTERN_SIZE", 3000);
  353. }
  354. constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  355. this.operatorList = IR[2];
  356. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  357. this.bbox = IR[4];
  358. this.xstep = IR[5];
  359. this.ystep = IR[6];
  360. this.paintType = IR[7];
  361. this.tilingType = IR[8];
  362. this.color = color;
  363. this.ctx = ctx;
  364. this.canvasGraphicsFactory = canvasGraphicsFactory;
  365. this.baseTransform = baseTransform;
  366. }
  367. createPatternCanvas(owner) {
  368. const operatorList = this.operatorList;
  369. const bbox = this.bbox;
  370. const xstep = this.xstep;
  371. const ystep = this.ystep;
  372. const paintType = this.paintType;
  373. const tilingType = this.tilingType;
  374. const color = this.color;
  375. const canvasGraphicsFactory = this.canvasGraphicsFactory;
  376. (0, _util.info)("TilingType: " + tilingType);
  377. const x0 = bbox[0],
  378. y0 = bbox[1],
  379. x1 = bbox[2],
  380. y1 = bbox[3];
  381. const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
  382. const curMatrixScale = _util.Util.singularValueDecompose2dScale(this.baseTransform);
  383. const combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]];
  384. const dimx = this.getSizeAndScale(xstep, this.ctx.canvas.width, combinedScale[0]);
  385. const dimy = this.getSizeAndScale(ystep, this.ctx.canvas.height, combinedScale[1]);
  386. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size, true);
  387. const tmpCtx = tmpCanvas.context;
  388. const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  389. graphics.groupLevel = owner.groupLevel;
  390. this.setFillAndStrokeStyleToContext(graphics, paintType, color);
  391. let adjustedX0 = x0;
  392. let adjustedY0 = y0;
  393. let adjustedX1 = x1;
  394. let adjustedY1 = y1;
  395. if (x0 < 0) {
  396. adjustedX0 = 0;
  397. adjustedX1 += Math.abs(x0);
  398. }
  399. if (y0 < 0) {
  400. adjustedY0 = 0;
  401. adjustedY1 += Math.abs(y0);
  402. }
  403. tmpCtx.translate(-(dimx.scale * adjustedX0), -(dimy.scale * adjustedY0));
  404. graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
  405. tmpCtx.save();
  406. this.clipBbox(graphics, adjustedX0, adjustedY0, adjustedX1, adjustedY1);
  407. graphics.baseTransform = (0, _display_utils.getCurrentTransform)(graphics.ctx);
  408. graphics.executeOperatorList(operatorList);
  409. graphics.endDrawing();
  410. return {
  411. canvas: tmpCanvas.canvas,
  412. scaleX: dimx.scale,
  413. scaleY: dimy.scale,
  414. offsetX: adjustedX0,
  415. offsetY: adjustedY0
  416. };
  417. }
  418. getSizeAndScale(step, realOutputSize, scale) {
  419. step = Math.abs(step);
  420. const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);
  421. let size = Math.ceil(step * scale);
  422. if (size >= maxSize) {
  423. size = maxSize;
  424. } else {
  425. scale = size / step;
  426. }
  427. return {
  428. scale,
  429. size
  430. };
  431. }
  432. clipBbox(graphics, x0, y0, x1, y1) {
  433. const bboxWidth = x1 - x0;
  434. const bboxHeight = y1 - y0;
  435. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  436. graphics.current.updateRectMinMax((0, _display_utils.getCurrentTransform)(graphics.ctx), [x0, y0, x1, y1]);
  437. graphics.clip();
  438. graphics.endPath();
  439. }
  440. setFillAndStrokeStyleToContext(graphics, paintType, color) {
  441. const context = graphics.ctx,
  442. current = graphics.current;
  443. switch (paintType) {
  444. case PaintType.COLORED:
  445. const ctx = this.ctx;
  446. context.fillStyle = ctx.fillStyle;
  447. context.strokeStyle = ctx.strokeStyle;
  448. current.fillColor = ctx.fillStyle;
  449. current.strokeColor = ctx.strokeStyle;
  450. break;
  451. case PaintType.UNCOLORED:
  452. const cssColor = _util.Util.makeHexColor(color[0], color[1], color[2]);
  453. context.fillStyle = cssColor;
  454. context.strokeStyle = cssColor;
  455. current.fillColor = cssColor;
  456. current.strokeColor = cssColor;
  457. break;
  458. default:
  459. throw new _util.FormatError(`Unsupported paint type: ${paintType}`);
  460. }
  461. }
  462. getPattern(ctx, owner, inverse, pathType) {
  463. let matrix = inverse;
  464. if (pathType !== PathType.SHADING) {
  465. matrix = _util.Util.transform(matrix, owner.baseTransform);
  466. if (this.matrix) {
  467. matrix = _util.Util.transform(matrix, this.matrix);
  468. }
  469. }
  470. const temporaryPatternCanvas = this.createPatternCanvas(owner);
  471. let domMatrix = new DOMMatrix(matrix);
  472. domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  473. domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);
  474. const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");
  475. try {
  476. pattern.setTransform(domMatrix);
  477. } catch (ex) {
  478. (0, _util.warn)(`TilingPattern.getPattern: "${ex?.message}".`);
  479. }
  480. return pattern;
  481. }
  482. }
  483. exports.TilingPattern = TilingPattern;