pattern_helper.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2021 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. const PathType = {
  30. FILL: "Fill",
  31. STROKE: "Stroke",
  32. SHADING: "Shading"
  33. };
  34. exports.PathType = PathType;
  35. function applyBoundingBox(ctx, bbox) {
  36. if (!bbox || typeof Path2D === "undefined") {
  37. return;
  38. }
  39. const width = bbox[2] - bbox[0];
  40. const height = bbox[3] - bbox[1];
  41. const region = new Path2D();
  42. region.rect(bbox[0], bbox[1], width, height);
  43. ctx.clip(region);
  44. }
  45. class BaseShadingPattern {
  46. constructor() {
  47. if (this.constructor === BaseShadingPattern) {
  48. (0, _util.unreachable)("Cannot initialize BaseShadingPattern.");
  49. }
  50. }
  51. getPattern() {
  52. (0, _util.unreachable)("Abstract method `getPattern` called.");
  53. }
  54. }
  55. class RadialAxialShadingPattern extends BaseShadingPattern {
  56. constructor(IR) {
  57. super();
  58. this._type = IR[1];
  59. this._bbox = IR[2];
  60. this._colorStops = IR[3];
  61. this._p0 = IR[4];
  62. this._p1 = IR[5];
  63. this._r0 = IR[6];
  64. this._r1 = IR[7];
  65. this.matrix = null;
  66. }
  67. _createGradient(ctx) {
  68. let grad;
  69. if (this._type === "axial") {
  70. grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
  71. } else if (this._type === "radial") {
  72. grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
  73. }
  74. for (const colorStop of this._colorStops) {
  75. grad.addColorStop(colorStop[0], colorStop[1]);
  76. }
  77. return grad;
  78. }
  79. getPattern(ctx, owner, inverse, pathType) {
  80. let pattern;
  81. if (pathType === PathType.STROKE || pathType === PathType.FILL) {
  82. const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, ctx.mozCurrentTransform) || [0, 0, 0, 0];
  83. const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1;
  84. const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1;
  85. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height, true);
  86. const tmpCtx = tmpCanvas.context;
  87. tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  88. tmpCtx.beginPath();
  89. tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
  90. tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]);
  91. inverse = _util.Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]);
  92. tmpCtx.transform.apply(tmpCtx, owner.baseTransform);
  93. if (this.matrix) {
  94. tmpCtx.transform.apply(tmpCtx, this.matrix);
  95. }
  96. applyBoundingBox(tmpCtx, this._bbox);
  97. tmpCtx.fillStyle = this._createGradient(tmpCtx);
  98. tmpCtx.fill();
  99. pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat");
  100. const domMatrix = new DOMMatrix(inverse);
  101. try {
  102. pattern.setTransform(domMatrix);
  103. } catch (ex) {
  104. (0, _util.warn)(`RadialAxialShadingPattern.getPattern: "${ex?.message}".`);
  105. }
  106. } else {
  107. applyBoundingBox(ctx, this._bbox);
  108. pattern = this._createGradient(ctx);
  109. }
  110. return pattern;
  111. }
  112. }
  113. function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
  114. const coords = context.coords,
  115. colors = context.colors;
  116. const bytes = data.data,
  117. rowSize = data.width * 4;
  118. let tmp;
  119. if (coords[p1 + 1] > coords[p2 + 1]) {
  120. tmp = p1;
  121. p1 = p2;
  122. p2 = tmp;
  123. tmp = c1;
  124. c1 = c2;
  125. c2 = tmp;
  126. }
  127. if (coords[p2 + 1] > coords[p3 + 1]) {
  128. tmp = p2;
  129. p2 = p3;
  130. p3 = tmp;
  131. tmp = c2;
  132. c2 = c3;
  133. c3 = tmp;
  134. }
  135. if (coords[p1 + 1] > coords[p2 + 1]) {
  136. tmp = p1;
  137. p1 = p2;
  138. p2 = tmp;
  139. tmp = c1;
  140. c1 = c2;
  141. c2 = tmp;
  142. }
  143. const x1 = (coords[p1] + context.offsetX) * context.scaleX;
  144. const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
  145. const x2 = (coords[p2] + context.offsetX) * context.scaleX;
  146. const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
  147. const x3 = (coords[p3] + context.offsetX) * context.scaleX;
  148. const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
  149. if (y1 >= y3) {
  150. return;
  151. }
  152. const c1r = colors[c1],
  153. c1g = colors[c1 + 1],
  154. c1b = colors[c1 + 2];
  155. const c2r = colors[c2],
  156. c2g = colors[c2 + 1],
  157. c2b = colors[c2 + 2];
  158. const c3r = colors[c3],
  159. c3g = colors[c3 + 1],
  160. c3b = colors[c3 + 2];
  161. const minY = Math.round(y1),
  162. maxY = Math.round(y3);
  163. let xa, car, cag, cab;
  164. let xb, cbr, cbg, cbb;
  165. for (let y = minY; y <= maxY; y++) {
  166. if (y < y2) {
  167. let k;
  168. if (y < y1) {
  169. k = 0;
  170. } else {
  171. k = (y1 - y) / (y1 - y2);
  172. }
  173. xa = x1 - (x1 - x2) * k;
  174. car = c1r - (c1r - c2r) * k;
  175. cag = c1g - (c1g - c2g) * k;
  176. cab = c1b - (c1b - c2b) * k;
  177. } else {
  178. let k;
  179. if (y > y3) {
  180. k = 1;
  181. } else if (y2 === y3) {
  182. k = 0;
  183. } else {
  184. k = (y2 - y) / (y2 - y3);
  185. }
  186. xa = x2 - (x2 - x3) * k;
  187. car = c2r - (c2r - c3r) * k;
  188. cag = c2g - (c2g - c3g) * k;
  189. cab = c2b - (c2b - c3b) * k;
  190. }
  191. let k;
  192. if (y < y1) {
  193. k = 0;
  194. } else if (y > y3) {
  195. k = 1;
  196. } else {
  197. k = (y1 - y) / (y1 - y3);
  198. }
  199. xb = x1 - (x1 - x3) * k;
  200. cbr = c1r - (c1r - c3r) * k;
  201. cbg = c1g - (c1g - c3g) * k;
  202. cbb = c1b - (c1b - c3b) * k;
  203. const x1_ = Math.round(Math.min(xa, xb));
  204. const x2_ = Math.round(Math.max(xa, xb));
  205. let j = rowSize * y + x1_ * 4;
  206. for (let x = x1_; x <= x2_; x++) {
  207. k = (xa - x) / (xa - xb);
  208. if (k < 0) {
  209. k = 0;
  210. } else if (k > 1) {
  211. k = 1;
  212. }
  213. bytes[j++] = car - (car - cbr) * k | 0;
  214. bytes[j++] = cag - (cag - cbg) * k | 0;
  215. bytes[j++] = cab - (cab - cbb) * k | 0;
  216. bytes[j++] = 255;
  217. }
  218. }
  219. }
  220. function drawFigure(data, figure, context) {
  221. const ps = figure.coords;
  222. const cs = figure.colors;
  223. let i, ii;
  224. switch (figure.type) {
  225. case "lattice":
  226. const verticesPerRow = figure.verticesPerRow;
  227. const rows = Math.floor(ps.length / verticesPerRow) - 1;
  228. const cols = verticesPerRow - 1;
  229. for (i = 0; i < rows; i++) {
  230. let q = i * verticesPerRow;
  231. for (let j = 0; j < cols; j++, q++) {
  232. drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
  233. drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
  234. }
  235. }
  236. break;
  237. case "triangles":
  238. for (i = 0, ii = ps.length; i < ii; i += 3) {
  239. drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
  240. }
  241. break;
  242. default:
  243. throw new Error("illegal figure");
  244. }
  245. }
  246. class MeshShadingPattern extends BaseShadingPattern {
  247. constructor(IR) {
  248. super();
  249. this._coords = IR[2];
  250. this._colors = IR[3];
  251. this._figures = IR[4];
  252. this._bounds = IR[5];
  253. this._bbox = IR[7];
  254. this._background = IR[8];
  255. this.matrix = null;
  256. }
  257. _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {
  258. const EXPECTED_SCALE = 1.1;
  259. const MAX_PATTERN_SIZE = 3000;
  260. const BORDER_SIZE = 2;
  261. const offsetX = Math.floor(this._bounds[0]);
  262. const offsetY = Math.floor(this._bounds[1]);
  263. const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
  264. const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;
  265. const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  266. const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
  267. const scaleX = boundsWidth / width;
  268. const scaleY = boundsHeight / height;
  269. const context = {
  270. coords: this._coords,
  271. colors: this._colors,
  272. offsetX: -offsetX,
  273. offsetY: -offsetY,
  274. scaleX: 1 / scaleX,
  275. scaleY: 1 / scaleY
  276. };
  277. const paddedWidth = width + BORDER_SIZE * 2;
  278. const paddedHeight = height + BORDER_SIZE * 2;
  279. const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight, false);
  280. const tmpCtx = tmpCanvas.context;
  281. const data = tmpCtx.createImageData(width, height);
  282. if (backgroundColor) {
  283. const bytes = data.data;
  284. for (let i = 0, ii = bytes.length; i < ii; i += 4) {
  285. bytes[i] = backgroundColor[0];
  286. bytes[i + 1] = backgroundColor[1];
  287. bytes[i + 2] = backgroundColor[2];
  288. bytes[i + 3] = 255;
  289. }
  290. }
  291. for (const figure of this._figures) {
  292. drawFigure(data, figure, context);
  293. }
  294. tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
  295. const canvas = tmpCanvas.canvas;
  296. return {
  297. canvas,
  298. offsetX: offsetX - BORDER_SIZE * scaleX,
  299. offsetY: offsetY - BORDER_SIZE * scaleY,
  300. scaleX,
  301. scaleY
  302. };
  303. }
  304. getPattern(ctx, owner, inverse, pathType) {
  305. applyBoundingBox(ctx, this._bbox);
  306. let scale;
  307. if (pathType === PathType.SHADING) {
  308. scale = _util.Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
  309. } else {
  310. scale = _util.Util.singularValueDecompose2dScale(owner.baseTransform);
  311. if (this.matrix) {
  312. const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
  313. scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]];
  314. }
  315. }
  316. const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases);
  317. if (pathType !== PathType.SHADING) {
  318. ctx.setTransform.apply(ctx, owner.baseTransform);
  319. if (this.matrix) {
  320. ctx.transform.apply(ctx, this.matrix);
  321. }
  322. }
  323. ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
  324. ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
  325. return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");
  326. }
  327. }
  328. class DummyShadingPattern extends BaseShadingPattern {
  329. getPattern() {
  330. return "hotpink";
  331. }
  332. }
  333. function getShadingPattern(IR) {
  334. switch (IR[0]) {
  335. case "RadialAxial":
  336. return new RadialAxialShadingPattern(IR);
  337. case "Mesh":
  338. return new MeshShadingPattern(IR);
  339. case "Dummy":
  340. return new DummyShadingPattern();
  341. }
  342. throw new Error(`Unknown IR type: ${IR[0]}`);
  343. }
  344. const PaintType = {
  345. COLORED: 1,
  346. UNCOLORED: 2
  347. };
  348. class TilingPattern {
  349. static get MAX_PATTERN_SIZE() {
  350. return (0, _util.shadow)(this, "MAX_PATTERN_SIZE", 3000);
  351. }
  352. constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
  353. this.operatorList = IR[2];
  354. this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
  355. this.bbox = IR[4];
  356. this.xstep = IR[5];
  357. this.ystep = IR[6];
  358. this.paintType = IR[7];
  359. this.tilingType = IR[8];
  360. this.color = color;
  361. this.ctx = ctx;
  362. this.canvasGraphicsFactory = canvasGraphicsFactory;
  363. this.baseTransform = baseTransform;
  364. }
  365. createPatternCanvas(owner) {
  366. const operatorList = this.operatorList;
  367. const bbox = this.bbox;
  368. const xstep = this.xstep;
  369. const ystep = this.ystep;
  370. const paintType = this.paintType;
  371. const tilingType = this.tilingType;
  372. const color = this.color;
  373. const canvasGraphicsFactory = this.canvasGraphicsFactory;
  374. (0, _util.info)("TilingType: " + tilingType);
  375. const x0 = bbox[0],
  376. y0 = bbox[1],
  377. x1 = bbox[2],
  378. y1 = bbox[3];
  379. const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
  380. const curMatrixScale = _util.Util.singularValueDecompose2dScale(this.baseTransform);
  381. const combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]];
  382. const dimx = this.getSizeAndScale(xstep, this.ctx.canvas.width, combinedScale[0]);
  383. const dimy = this.getSizeAndScale(ystep, this.ctx.canvas.height, combinedScale[1]);
  384. const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size, true);
  385. const tmpCtx = tmpCanvas.context;
  386. const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
  387. graphics.groupLevel = owner.groupLevel;
  388. this.setFillAndStrokeStyleToContext(graphics, paintType, color);
  389. let adjustedX0 = x0;
  390. let adjustedY0 = y0;
  391. let adjustedX1 = x1;
  392. let adjustedY1 = y1;
  393. if (x0 < 0) {
  394. adjustedX0 = 0;
  395. adjustedX1 += Math.abs(x0);
  396. }
  397. if (y0 < 0) {
  398. adjustedY0 = 0;
  399. adjustedY1 += Math.abs(y0);
  400. }
  401. tmpCtx.translate(-(dimx.scale * adjustedX0), -(dimy.scale * adjustedY0));
  402. graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
  403. this.clipBbox(graphics, adjustedX0, adjustedY0, adjustedX1, adjustedY1);
  404. graphics.baseTransform = graphics.ctx.mozCurrentTransform.slice();
  405. graphics.executeOperatorList(operatorList);
  406. graphics.endDrawing();
  407. return {
  408. canvas: tmpCanvas.canvas,
  409. scaleX: dimx.scale,
  410. scaleY: dimy.scale,
  411. offsetX: adjustedX0,
  412. offsetY: adjustedY0
  413. };
  414. }
  415. getSizeAndScale(step, realOutputSize, scale) {
  416. step = Math.abs(step);
  417. const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);
  418. let size = Math.ceil(step * scale);
  419. if (size >= maxSize) {
  420. size = maxSize;
  421. } else {
  422. scale = size / step;
  423. }
  424. return {
  425. scale,
  426. size
  427. };
  428. }
  429. clipBbox(graphics, x0, y0, x1, y1) {
  430. const bboxWidth = x1 - x0;
  431. const bboxHeight = y1 - y0;
  432. graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
  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. try {
  472. pattern.setTransform(domMatrix);
  473. } catch (ex) {
  474. (0, _util.warn)(`TilingPattern.getPattern: "${ex?.message}".`);
  475. }
  476. return pattern;
  477. }
  478. }
  479. exports.TilingPattern = TilingPattern;