function.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353
  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.PostScriptEvaluator = exports.PostScriptCompiler = exports.PDFFunctionFactory = void 0;
  27. exports.isPDFFunction = isPDFFunction;
  28. var _primitives = require("./primitives.js");
  29. var _util = require("../shared/util.js");
  30. var _ps_parser = require("./ps_parser.js");
  31. var _base_stream = require("./base_stream.js");
  32. var _image_utils = require("./image_utils.js");
  33. class PDFFunctionFactory {
  34. constructor({
  35. xref,
  36. isEvalSupported = true
  37. }) {
  38. this.xref = xref;
  39. this.isEvalSupported = isEvalSupported !== false;
  40. }
  41. create(fn) {
  42. const cachedFunction = this.getCached(fn);
  43. if (cachedFunction) {
  44. return cachedFunction;
  45. }
  46. const parsedFunction = PDFFunction.parse({
  47. xref: this.xref,
  48. isEvalSupported: this.isEvalSupported,
  49. fn: fn instanceof _primitives.Ref ? this.xref.fetch(fn) : fn
  50. });
  51. this._cache(fn, parsedFunction);
  52. return parsedFunction;
  53. }
  54. createFromArray(fnObj) {
  55. const cachedFunction = this.getCached(fnObj);
  56. if (cachedFunction) {
  57. return cachedFunction;
  58. }
  59. const parsedFunction = PDFFunction.parseArray({
  60. xref: this.xref,
  61. isEvalSupported: this.isEvalSupported,
  62. fnObj: fnObj instanceof _primitives.Ref ? this.xref.fetch(fnObj) : fnObj
  63. });
  64. this._cache(fnObj, parsedFunction);
  65. return parsedFunction;
  66. }
  67. getCached(cacheKey) {
  68. let fnRef;
  69. if (cacheKey instanceof _primitives.Ref) {
  70. fnRef = cacheKey;
  71. } else if (cacheKey instanceof _primitives.Dict) {
  72. fnRef = cacheKey.objId;
  73. } else if (cacheKey instanceof _base_stream.BaseStream) {
  74. fnRef = cacheKey.dict && cacheKey.dict.objId;
  75. }
  76. if (fnRef) {
  77. const localFunction = this._localFunctionCache.getByRef(fnRef);
  78. if (localFunction) {
  79. return localFunction;
  80. }
  81. }
  82. return null;
  83. }
  84. _cache(cacheKey, parsedFunction) {
  85. if (!parsedFunction) {
  86. throw new Error('PDFFunctionFactory._cache - expected "parsedFunction" argument.');
  87. }
  88. let fnRef;
  89. if (cacheKey instanceof _primitives.Ref) {
  90. fnRef = cacheKey;
  91. } else if (cacheKey instanceof _primitives.Dict) {
  92. fnRef = cacheKey.objId;
  93. } else if (cacheKey instanceof _base_stream.BaseStream) {
  94. fnRef = cacheKey.dict && cacheKey.dict.objId;
  95. }
  96. if (fnRef) {
  97. this._localFunctionCache.set(null, fnRef, parsedFunction);
  98. }
  99. }
  100. get _localFunctionCache() {
  101. return (0, _util.shadow)(this, "_localFunctionCache", new _image_utils.LocalFunctionCache());
  102. }
  103. }
  104. exports.PDFFunctionFactory = PDFFunctionFactory;
  105. function toNumberArray(arr) {
  106. if (!Array.isArray(arr)) {
  107. return null;
  108. }
  109. const length = arr.length;
  110. for (let i = 0; i < length; i++) {
  111. if (typeof arr[i] !== "number") {
  112. const result = new Array(length);
  113. for (let j = 0; j < length; j++) {
  114. result[j] = +arr[j];
  115. }
  116. return result;
  117. }
  118. }
  119. return arr;
  120. }
  121. class PDFFunction {
  122. static getSampleArray(size, outputSize, bps, stream) {
  123. let i, ii;
  124. let length = 1;
  125. for (i = 0, ii = size.length; i < ii; i++) {
  126. length *= size[i];
  127. }
  128. length *= outputSize;
  129. const array = new Array(length);
  130. let codeSize = 0;
  131. let codeBuf = 0;
  132. const sampleMul = 1.0 / (2.0 ** bps - 1);
  133. const strBytes = stream.getBytes((length * bps + 7) / 8);
  134. let strIdx = 0;
  135. for (i = 0; i < length; i++) {
  136. while (codeSize < bps) {
  137. codeBuf <<= 8;
  138. codeBuf |= strBytes[strIdx++];
  139. codeSize += 8;
  140. }
  141. codeSize -= bps;
  142. array[i] = (codeBuf >> codeSize) * sampleMul;
  143. codeBuf &= (1 << codeSize) - 1;
  144. }
  145. return array;
  146. }
  147. static parse({
  148. xref,
  149. isEvalSupported,
  150. fn
  151. }) {
  152. const dict = fn.dict || fn;
  153. const typeNum = dict.get("FunctionType");
  154. switch (typeNum) {
  155. case 0:
  156. return this.constructSampled({
  157. xref,
  158. isEvalSupported,
  159. fn,
  160. dict
  161. });
  162. case 1:
  163. break;
  164. case 2:
  165. return this.constructInterpolated({
  166. xref,
  167. isEvalSupported,
  168. dict
  169. });
  170. case 3:
  171. return this.constructStiched({
  172. xref,
  173. isEvalSupported,
  174. dict
  175. });
  176. case 4:
  177. return this.constructPostScript({
  178. xref,
  179. isEvalSupported,
  180. fn,
  181. dict
  182. });
  183. }
  184. throw new _util.FormatError("Unknown type of function");
  185. }
  186. static parseArray({
  187. xref,
  188. isEvalSupported,
  189. fnObj
  190. }) {
  191. if (!Array.isArray(fnObj)) {
  192. return this.parse({
  193. xref,
  194. isEvalSupported,
  195. fn: fnObj
  196. });
  197. }
  198. const fnArray = [];
  199. for (let j = 0, jj = fnObj.length; j < jj; j++) {
  200. fnArray.push(this.parse({
  201. xref,
  202. isEvalSupported,
  203. fn: xref.fetchIfRef(fnObj[j])
  204. }));
  205. }
  206. return function (src, srcOffset, dest, destOffset) {
  207. for (let i = 0, ii = fnArray.length; i < ii; i++) {
  208. fnArray[i](src, srcOffset, dest, destOffset + i);
  209. }
  210. };
  211. }
  212. static constructSampled({
  213. xref,
  214. isEvalSupported,
  215. fn,
  216. dict
  217. }) {
  218. function toMultiArray(arr) {
  219. const inputLength = arr.length;
  220. const out = [];
  221. let index = 0;
  222. for (let i = 0; i < inputLength; i += 2) {
  223. out[index++] = [arr[i], arr[i + 1]];
  224. }
  225. return out;
  226. }
  227. function interpolate(x, xmin, xmax, ymin, ymax) {
  228. return ymin + (x - xmin) * ((ymax - ymin) / (xmax - xmin));
  229. }
  230. let domain = toNumberArray(dict.getArray("Domain"));
  231. let range = toNumberArray(dict.getArray("Range"));
  232. if (!domain || !range) {
  233. throw new _util.FormatError("No domain or range");
  234. }
  235. const inputSize = domain.length / 2;
  236. const outputSize = range.length / 2;
  237. domain = toMultiArray(domain);
  238. range = toMultiArray(range);
  239. const size = toNumberArray(dict.getArray("Size"));
  240. const bps = dict.get("BitsPerSample");
  241. const order = dict.get("Order") || 1;
  242. if (order !== 1) {
  243. (0, _util.info)("No support for cubic spline interpolation: " + order);
  244. }
  245. let encode = toNumberArray(dict.getArray("Encode"));
  246. if (!encode) {
  247. encode = [];
  248. for (let i = 0; i < inputSize; ++i) {
  249. encode.push([0, size[i] - 1]);
  250. }
  251. } else {
  252. encode = toMultiArray(encode);
  253. }
  254. let decode = toNumberArray(dict.getArray("Decode"));
  255. if (!decode) {
  256. decode = range;
  257. } else {
  258. decode = toMultiArray(decode);
  259. }
  260. const samples = this.getSampleArray(size, outputSize, bps, fn);
  261. return function constructSampledFn(src, srcOffset, dest, destOffset) {
  262. const cubeVertices = 1 << inputSize;
  263. const cubeN = new Float64Array(cubeVertices);
  264. const cubeVertex = new Uint32Array(cubeVertices);
  265. let i, j;
  266. for (j = 0; j < cubeVertices; j++) {
  267. cubeN[j] = 1;
  268. }
  269. let k = outputSize,
  270. pos = 1;
  271. for (i = 0; i < inputSize; ++i) {
  272. const domain_2i = domain[i][0];
  273. const domain_2i_1 = domain[i][1];
  274. const xi = Math.min(Math.max(src[srcOffset + i], domain_2i), domain_2i_1);
  275. let e = interpolate(xi, domain_2i, domain_2i_1, encode[i][0], encode[i][1]);
  276. const size_i = size[i];
  277. e = Math.min(Math.max(e, 0), size_i - 1);
  278. const e0 = e < size_i - 1 ? Math.floor(e) : e - 1;
  279. const n0 = e0 + 1 - e;
  280. const n1 = e - e0;
  281. const offset0 = e0 * k;
  282. const offset1 = offset0 + k;
  283. for (j = 0; j < cubeVertices; j++) {
  284. if (j & pos) {
  285. cubeN[j] *= n1;
  286. cubeVertex[j] += offset1;
  287. } else {
  288. cubeN[j] *= n0;
  289. cubeVertex[j] += offset0;
  290. }
  291. }
  292. k *= size_i;
  293. pos <<= 1;
  294. }
  295. for (j = 0; j < outputSize; ++j) {
  296. let rj = 0;
  297. for (i = 0; i < cubeVertices; i++) {
  298. rj += samples[cubeVertex[i] + j] * cubeN[i];
  299. }
  300. rj = interpolate(rj, 0, 1, decode[j][0], decode[j][1]);
  301. dest[destOffset + j] = Math.min(Math.max(rj, range[j][0]), range[j][1]);
  302. }
  303. };
  304. }
  305. static constructInterpolated({
  306. xref,
  307. isEvalSupported,
  308. dict
  309. }) {
  310. const c0 = toNumberArray(dict.getArray("C0")) || [0];
  311. const c1 = toNumberArray(dict.getArray("C1")) || [1];
  312. const n = dict.get("N");
  313. const diff = [];
  314. for (let i = 0, ii = c0.length; i < ii; ++i) {
  315. diff.push(c1[i] - c0[i]);
  316. }
  317. const length = diff.length;
  318. return function constructInterpolatedFn(src, srcOffset, dest, destOffset) {
  319. const x = n === 1 ? src[srcOffset] : src[srcOffset] ** n;
  320. for (let j = 0; j < length; ++j) {
  321. dest[destOffset + j] = c0[j] + x * diff[j];
  322. }
  323. };
  324. }
  325. static constructStiched({
  326. xref,
  327. isEvalSupported,
  328. dict
  329. }) {
  330. const domain = toNumberArray(dict.getArray("Domain"));
  331. if (!domain) {
  332. throw new _util.FormatError("No domain");
  333. }
  334. const inputSize = domain.length / 2;
  335. if (inputSize !== 1) {
  336. throw new _util.FormatError("Bad domain for stiched function");
  337. }
  338. const fnRefs = dict.get("Functions");
  339. const fns = [];
  340. for (let i = 0, ii = fnRefs.length; i < ii; ++i) {
  341. fns.push(this.parse({
  342. xref,
  343. isEvalSupported,
  344. fn: xref.fetchIfRef(fnRefs[i])
  345. }));
  346. }
  347. const bounds = toNumberArray(dict.getArray("Bounds"));
  348. const encode = toNumberArray(dict.getArray("Encode"));
  349. const tmpBuf = new Float32Array(1);
  350. return function constructStichedFn(src, srcOffset, dest, destOffset) {
  351. const clip = function constructStichedFromIRClip(v, min, max) {
  352. if (v > max) {
  353. v = max;
  354. } else if (v < min) {
  355. v = min;
  356. }
  357. return v;
  358. };
  359. const v = clip(src[srcOffset], domain[0], domain[1]);
  360. const length = bounds.length;
  361. let i;
  362. for (i = 0; i < length; ++i) {
  363. if (v < bounds[i]) {
  364. break;
  365. }
  366. }
  367. let dmin = domain[0];
  368. if (i > 0) {
  369. dmin = bounds[i - 1];
  370. }
  371. let dmax = domain[1];
  372. if (i < bounds.length) {
  373. dmax = bounds[i];
  374. }
  375. const rmin = encode[2 * i];
  376. const rmax = encode[2 * i + 1];
  377. tmpBuf[0] = dmin === dmax ? rmin : rmin + (v - dmin) * (rmax - rmin) / (dmax - dmin);
  378. fns[i](tmpBuf, 0, dest, destOffset);
  379. };
  380. }
  381. static constructPostScript({
  382. xref,
  383. isEvalSupported,
  384. fn,
  385. dict
  386. }) {
  387. const domain = toNumberArray(dict.getArray("Domain"));
  388. const range = toNumberArray(dict.getArray("Range"));
  389. if (!domain) {
  390. throw new _util.FormatError("No domain.");
  391. }
  392. if (!range) {
  393. throw new _util.FormatError("No range.");
  394. }
  395. const lexer = new _ps_parser.PostScriptLexer(fn);
  396. const parser = new _ps_parser.PostScriptParser(lexer);
  397. const code = parser.parse();
  398. if (isEvalSupported && _util.FeatureTest.isEvalSupported) {
  399. const compiled = new PostScriptCompiler().compile(code, domain, range);
  400. if (compiled) {
  401. return new Function("src", "srcOffset", "dest", "destOffset", compiled);
  402. }
  403. }
  404. (0, _util.info)("Unable to compile PS function");
  405. const numOutputs = range.length >> 1;
  406. const numInputs = domain.length >> 1;
  407. const evaluator = new PostScriptEvaluator(code);
  408. const cache = Object.create(null);
  409. const MAX_CACHE_SIZE = 2048 * 4;
  410. let cache_available = MAX_CACHE_SIZE;
  411. const tmpBuf = new Float32Array(numInputs);
  412. return function constructPostScriptFn(src, srcOffset, dest, destOffset) {
  413. let i, value;
  414. let key = "";
  415. const input = tmpBuf;
  416. for (i = 0; i < numInputs; i++) {
  417. value = src[srcOffset + i];
  418. input[i] = value;
  419. key += value + "_";
  420. }
  421. const cachedValue = cache[key];
  422. if (cachedValue !== undefined) {
  423. dest.set(cachedValue, destOffset);
  424. return;
  425. }
  426. const output = new Float32Array(numOutputs);
  427. const stack = evaluator.execute(input);
  428. const stackIndex = stack.length - numOutputs;
  429. for (i = 0; i < numOutputs; i++) {
  430. value = stack[stackIndex + i];
  431. let bound = range[i * 2];
  432. if (value < bound) {
  433. value = bound;
  434. } else {
  435. bound = range[i * 2 + 1];
  436. if (value > bound) {
  437. value = bound;
  438. }
  439. }
  440. output[i] = value;
  441. }
  442. if (cache_available > 0) {
  443. cache_available--;
  444. cache[key] = output;
  445. }
  446. dest.set(output, destOffset);
  447. };
  448. }
  449. }
  450. function isPDFFunction(v) {
  451. let fnDict;
  452. if (typeof v !== "object") {
  453. return false;
  454. } else if (v instanceof _primitives.Dict) {
  455. fnDict = v;
  456. } else if (v instanceof _base_stream.BaseStream) {
  457. fnDict = v.dict;
  458. } else {
  459. return false;
  460. }
  461. return fnDict.has("FunctionType");
  462. }
  463. class PostScriptStack {
  464. static get MAX_STACK_SIZE() {
  465. return (0, _util.shadow)(this, "MAX_STACK_SIZE", 100);
  466. }
  467. constructor(initialStack) {
  468. this.stack = !initialStack ? [] : Array.prototype.slice.call(initialStack, 0);
  469. }
  470. push(value) {
  471. if (this.stack.length >= PostScriptStack.MAX_STACK_SIZE) {
  472. throw new Error("PostScript function stack overflow.");
  473. }
  474. this.stack.push(value);
  475. }
  476. pop() {
  477. if (this.stack.length <= 0) {
  478. throw new Error("PostScript function stack underflow.");
  479. }
  480. return this.stack.pop();
  481. }
  482. copy(n) {
  483. if (this.stack.length + n >= PostScriptStack.MAX_STACK_SIZE) {
  484. throw new Error("PostScript function stack overflow.");
  485. }
  486. const stack = this.stack;
  487. for (let i = stack.length - n, j = n - 1; j >= 0; j--, i++) {
  488. stack.push(stack[i]);
  489. }
  490. }
  491. index(n) {
  492. this.push(this.stack[this.stack.length - n - 1]);
  493. }
  494. roll(n, p) {
  495. const stack = this.stack;
  496. const l = stack.length - n;
  497. const r = stack.length - 1;
  498. const c = l + (p - Math.floor(p / n) * n);
  499. for (let i = l, j = r; i < j; i++, j--) {
  500. const t = stack[i];
  501. stack[i] = stack[j];
  502. stack[j] = t;
  503. }
  504. for (let i = l, j = c - 1; i < j; i++, j--) {
  505. const t = stack[i];
  506. stack[i] = stack[j];
  507. stack[j] = t;
  508. }
  509. for (let i = c, j = r; i < j; i++, j--) {
  510. const t = stack[i];
  511. stack[i] = stack[j];
  512. stack[j] = t;
  513. }
  514. }
  515. }
  516. class PostScriptEvaluator {
  517. constructor(operators) {
  518. this.operators = operators;
  519. }
  520. execute(initialStack) {
  521. const stack = new PostScriptStack(initialStack);
  522. let counter = 0;
  523. const operators = this.operators;
  524. const length = operators.length;
  525. let operator, a, b;
  526. while (counter < length) {
  527. operator = operators[counter++];
  528. if (typeof operator === "number") {
  529. stack.push(operator);
  530. continue;
  531. }
  532. switch (operator) {
  533. case "jz":
  534. b = stack.pop();
  535. a = stack.pop();
  536. if (!a) {
  537. counter = b;
  538. }
  539. break;
  540. case "j":
  541. a = stack.pop();
  542. counter = a;
  543. break;
  544. case "abs":
  545. a = stack.pop();
  546. stack.push(Math.abs(a));
  547. break;
  548. case "add":
  549. b = stack.pop();
  550. a = stack.pop();
  551. stack.push(a + b);
  552. break;
  553. case "and":
  554. b = stack.pop();
  555. a = stack.pop();
  556. if (typeof a === "boolean" && typeof b === "boolean") {
  557. stack.push(a && b);
  558. } else {
  559. stack.push(a & b);
  560. }
  561. break;
  562. case "atan":
  563. a = stack.pop();
  564. stack.push(Math.atan(a));
  565. break;
  566. case "bitshift":
  567. b = stack.pop();
  568. a = stack.pop();
  569. if (a > 0) {
  570. stack.push(a << b);
  571. } else {
  572. stack.push(a >> b);
  573. }
  574. break;
  575. case "ceiling":
  576. a = stack.pop();
  577. stack.push(Math.ceil(a));
  578. break;
  579. case "copy":
  580. a = stack.pop();
  581. stack.copy(a);
  582. break;
  583. case "cos":
  584. a = stack.pop();
  585. stack.push(Math.cos(a));
  586. break;
  587. case "cvi":
  588. a = stack.pop() | 0;
  589. stack.push(a);
  590. break;
  591. case "cvr":
  592. break;
  593. case "div":
  594. b = stack.pop();
  595. a = stack.pop();
  596. stack.push(a / b);
  597. break;
  598. case "dup":
  599. stack.copy(1);
  600. break;
  601. case "eq":
  602. b = stack.pop();
  603. a = stack.pop();
  604. stack.push(a === b);
  605. break;
  606. case "exch":
  607. stack.roll(2, 1);
  608. break;
  609. case "exp":
  610. b = stack.pop();
  611. a = stack.pop();
  612. stack.push(a ** b);
  613. break;
  614. case "false":
  615. stack.push(false);
  616. break;
  617. case "floor":
  618. a = stack.pop();
  619. stack.push(Math.floor(a));
  620. break;
  621. case "ge":
  622. b = stack.pop();
  623. a = stack.pop();
  624. stack.push(a >= b);
  625. break;
  626. case "gt":
  627. b = stack.pop();
  628. a = stack.pop();
  629. stack.push(a > b);
  630. break;
  631. case "idiv":
  632. b = stack.pop();
  633. a = stack.pop();
  634. stack.push(a / b | 0);
  635. break;
  636. case "index":
  637. a = stack.pop();
  638. stack.index(a);
  639. break;
  640. case "le":
  641. b = stack.pop();
  642. a = stack.pop();
  643. stack.push(a <= b);
  644. break;
  645. case "ln":
  646. a = stack.pop();
  647. stack.push(Math.log(a));
  648. break;
  649. case "log":
  650. a = stack.pop();
  651. stack.push(Math.log(a) / Math.LN10);
  652. break;
  653. case "lt":
  654. b = stack.pop();
  655. a = stack.pop();
  656. stack.push(a < b);
  657. break;
  658. case "mod":
  659. b = stack.pop();
  660. a = stack.pop();
  661. stack.push(a % b);
  662. break;
  663. case "mul":
  664. b = stack.pop();
  665. a = stack.pop();
  666. stack.push(a * b);
  667. break;
  668. case "ne":
  669. b = stack.pop();
  670. a = stack.pop();
  671. stack.push(a !== b);
  672. break;
  673. case "neg":
  674. a = stack.pop();
  675. stack.push(-a);
  676. break;
  677. case "not":
  678. a = stack.pop();
  679. if (typeof a === "boolean") {
  680. stack.push(!a);
  681. } else {
  682. stack.push(~a);
  683. }
  684. break;
  685. case "or":
  686. b = stack.pop();
  687. a = stack.pop();
  688. if (typeof a === "boolean" && typeof b === "boolean") {
  689. stack.push(a || b);
  690. } else {
  691. stack.push(a | b);
  692. }
  693. break;
  694. case "pop":
  695. stack.pop();
  696. break;
  697. case "roll":
  698. b = stack.pop();
  699. a = stack.pop();
  700. stack.roll(a, b);
  701. break;
  702. case "round":
  703. a = stack.pop();
  704. stack.push(Math.round(a));
  705. break;
  706. case "sin":
  707. a = stack.pop();
  708. stack.push(Math.sin(a));
  709. break;
  710. case "sqrt":
  711. a = stack.pop();
  712. stack.push(Math.sqrt(a));
  713. break;
  714. case "sub":
  715. b = stack.pop();
  716. a = stack.pop();
  717. stack.push(a - b);
  718. break;
  719. case "true":
  720. stack.push(true);
  721. break;
  722. case "truncate":
  723. a = stack.pop();
  724. a = a < 0 ? Math.ceil(a) : Math.floor(a);
  725. stack.push(a);
  726. break;
  727. case "xor":
  728. b = stack.pop();
  729. a = stack.pop();
  730. if (typeof a === "boolean" && typeof b === "boolean") {
  731. stack.push(a !== b);
  732. } else {
  733. stack.push(a ^ b);
  734. }
  735. break;
  736. default:
  737. throw new _util.FormatError(`Unknown operator ${operator}`);
  738. }
  739. }
  740. return stack.stack;
  741. }
  742. }
  743. exports.PostScriptEvaluator = PostScriptEvaluator;
  744. const PostScriptCompiler = function PostScriptCompilerClosure() {
  745. class AstNode {
  746. constructor(type) {
  747. this.type = type;
  748. }
  749. visit(visitor) {
  750. (0, _util.unreachable)("abstract method");
  751. }
  752. }
  753. class AstArgument extends AstNode {
  754. constructor(index, min, max) {
  755. super("args");
  756. this.index = index;
  757. this.min = min;
  758. this.max = max;
  759. }
  760. visit(visitor) {
  761. visitor.visitArgument(this);
  762. }
  763. }
  764. class AstLiteral extends AstNode {
  765. constructor(number) {
  766. super("literal");
  767. this.number = number;
  768. this.min = number;
  769. this.max = number;
  770. }
  771. visit(visitor) {
  772. visitor.visitLiteral(this);
  773. }
  774. }
  775. class AstBinaryOperation extends AstNode {
  776. constructor(op, arg1, arg2, min, max) {
  777. super("binary");
  778. this.op = op;
  779. this.arg1 = arg1;
  780. this.arg2 = arg2;
  781. this.min = min;
  782. this.max = max;
  783. }
  784. visit(visitor) {
  785. visitor.visitBinaryOperation(this);
  786. }
  787. }
  788. class AstMin extends AstNode {
  789. constructor(arg, max) {
  790. super("max");
  791. this.arg = arg;
  792. this.min = arg.min;
  793. this.max = max;
  794. }
  795. visit(visitor) {
  796. visitor.visitMin(this);
  797. }
  798. }
  799. class AstVariable extends AstNode {
  800. constructor(index, min, max) {
  801. super("var");
  802. this.index = index;
  803. this.min = min;
  804. this.max = max;
  805. }
  806. visit(visitor) {
  807. visitor.visitVariable(this);
  808. }
  809. }
  810. class AstVariableDefinition extends AstNode {
  811. constructor(variable, arg) {
  812. super("definition");
  813. this.variable = variable;
  814. this.arg = arg;
  815. }
  816. visit(visitor) {
  817. visitor.visitVariableDefinition(this);
  818. }
  819. }
  820. class ExpressionBuilderVisitor {
  821. constructor() {
  822. this.parts = [];
  823. }
  824. visitArgument(arg) {
  825. this.parts.push("Math.max(", arg.min, ", Math.min(", arg.max, ", src[srcOffset + ", arg.index, "]))");
  826. }
  827. visitVariable(variable) {
  828. this.parts.push("v", variable.index);
  829. }
  830. visitLiteral(literal) {
  831. this.parts.push(literal.number);
  832. }
  833. visitBinaryOperation(operation) {
  834. this.parts.push("(");
  835. operation.arg1.visit(this);
  836. this.parts.push(" ", operation.op, " ");
  837. operation.arg2.visit(this);
  838. this.parts.push(")");
  839. }
  840. visitVariableDefinition(definition) {
  841. this.parts.push("var ");
  842. definition.variable.visit(this);
  843. this.parts.push(" = ");
  844. definition.arg.visit(this);
  845. this.parts.push(";");
  846. }
  847. visitMin(max) {
  848. this.parts.push("Math.min(");
  849. max.arg.visit(this);
  850. this.parts.push(", ", max.max, ")");
  851. }
  852. toString() {
  853. return this.parts.join("");
  854. }
  855. }
  856. function buildAddOperation(num1, num2) {
  857. if (num2.type === "literal" && num2.number === 0) {
  858. return num1;
  859. }
  860. if (num1.type === "literal" && num1.number === 0) {
  861. return num2;
  862. }
  863. if (num2.type === "literal" && num1.type === "literal") {
  864. return new AstLiteral(num1.number + num2.number);
  865. }
  866. return new AstBinaryOperation("+", num1, num2, num1.min + num2.min, num1.max + num2.max);
  867. }
  868. function buildMulOperation(num1, num2) {
  869. if (num2.type === "literal") {
  870. if (num2.number === 0) {
  871. return new AstLiteral(0);
  872. } else if (num2.number === 1) {
  873. return num1;
  874. } else if (num1.type === "literal") {
  875. return new AstLiteral(num1.number * num2.number);
  876. }
  877. }
  878. if (num1.type === "literal") {
  879. if (num1.number === 0) {
  880. return new AstLiteral(0);
  881. } else if (num1.number === 1) {
  882. return num2;
  883. }
  884. }
  885. const min = Math.min(num1.min * num2.min, num1.min * num2.max, num1.max * num2.min, num1.max * num2.max);
  886. const max = Math.max(num1.min * num2.min, num1.min * num2.max, num1.max * num2.min, num1.max * num2.max);
  887. return new AstBinaryOperation("*", num1, num2, min, max);
  888. }
  889. function buildSubOperation(num1, num2) {
  890. if (num2.type === "literal") {
  891. if (num2.number === 0) {
  892. return num1;
  893. } else if (num1.type === "literal") {
  894. return new AstLiteral(num1.number - num2.number);
  895. }
  896. }
  897. if (num2.type === "binary" && num2.op === "-" && num1.type === "literal" && num1.number === 1 && num2.arg1.type === "literal" && num2.arg1.number === 1) {
  898. return num2.arg2;
  899. }
  900. return new AstBinaryOperation("-", num1, num2, num1.min - num2.max, num1.max - num2.min);
  901. }
  902. function buildMinOperation(num1, max) {
  903. if (num1.min >= max) {
  904. return new AstLiteral(max);
  905. } else if (num1.max <= max) {
  906. return num1;
  907. }
  908. return new AstMin(num1, max);
  909. }
  910. class PostScriptCompiler {
  911. compile(code, domain, range) {
  912. const stack = [];
  913. const instructions = [];
  914. const inputSize = domain.length >> 1,
  915. outputSize = range.length >> 1;
  916. let lastRegister = 0;
  917. let n, j;
  918. let num1, num2, ast1, ast2, tmpVar, item;
  919. for (let i = 0; i < inputSize; i++) {
  920. stack.push(new AstArgument(i, domain[i * 2], domain[i * 2 + 1]));
  921. }
  922. for (let i = 0, ii = code.length; i < ii; i++) {
  923. item = code[i];
  924. if (typeof item === "number") {
  925. stack.push(new AstLiteral(item));
  926. continue;
  927. }
  928. switch (item) {
  929. case "add":
  930. if (stack.length < 2) {
  931. return null;
  932. }
  933. num2 = stack.pop();
  934. num1 = stack.pop();
  935. stack.push(buildAddOperation(num1, num2));
  936. break;
  937. case "cvr":
  938. if (stack.length < 1) {
  939. return null;
  940. }
  941. break;
  942. case "mul":
  943. if (stack.length < 2) {
  944. return null;
  945. }
  946. num2 = stack.pop();
  947. num1 = stack.pop();
  948. stack.push(buildMulOperation(num1, num2));
  949. break;
  950. case "sub":
  951. if (stack.length < 2) {
  952. return null;
  953. }
  954. num2 = stack.pop();
  955. num1 = stack.pop();
  956. stack.push(buildSubOperation(num1, num2));
  957. break;
  958. case "exch":
  959. if (stack.length < 2) {
  960. return null;
  961. }
  962. ast1 = stack.pop();
  963. ast2 = stack.pop();
  964. stack.push(ast1, ast2);
  965. break;
  966. case "pop":
  967. if (stack.length < 1) {
  968. return null;
  969. }
  970. stack.pop();
  971. break;
  972. case "index":
  973. if (stack.length < 1) {
  974. return null;
  975. }
  976. num1 = stack.pop();
  977. if (num1.type !== "literal") {
  978. return null;
  979. }
  980. n = num1.number;
  981. if (n < 0 || !Number.isInteger(n) || stack.length < n) {
  982. return null;
  983. }
  984. ast1 = stack[stack.length - n - 1];
  985. if (ast1.type === "literal" || ast1.type === "var") {
  986. stack.push(ast1);
  987. break;
  988. }
  989. tmpVar = new AstVariable(lastRegister++, ast1.min, ast1.max);
  990. stack[stack.length - n - 1] = tmpVar;
  991. stack.push(tmpVar);
  992. instructions.push(new AstVariableDefinition(tmpVar, ast1));
  993. break;
  994. case "dup":
  995. if (stack.length < 1) {
  996. return null;
  997. }
  998. if (typeof code[i + 1] === "number" && code[i + 2] === "gt" && code[i + 3] === i + 7 && code[i + 4] === "jz" && code[i + 5] === "pop" && code[i + 6] === code[i + 1]) {
  999. num1 = stack.pop();
  1000. stack.push(buildMinOperation(num1, code[i + 1]));
  1001. i += 6;
  1002. break;
  1003. }
  1004. ast1 = stack.at(-1);
  1005. if (ast1.type === "literal" || ast1.type === "var") {
  1006. stack.push(ast1);
  1007. break;
  1008. }
  1009. tmpVar = new AstVariable(lastRegister++, ast1.min, ast1.max);
  1010. stack[stack.length - 1] = tmpVar;
  1011. stack.push(tmpVar);
  1012. instructions.push(new AstVariableDefinition(tmpVar, ast1));
  1013. break;
  1014. case "roll":
  1015. if (stack.length < 2) {
  1016. return null;
  1017. }
  1018. num2 = stack.pop();
  1019. num1 = stack.pop();
  1020. if (num2.type !== "literal" || num1.type !== "literal") {
  1021. return null;
  1022. }
  1023. j = num2.number;
  1024. n = num1.number;
  1025. if (n <= 0 || !Number.isInteger(n) || !Number.isInteger(j) || stack.length < n) {
  1026. return null;
  1027. }
  1028. j = (j % n + n) % n;
  1029. if (j === 0) {
  1030. break;
  1031. }
  1032. Array.prototype.push.apply(stack, stack.splice(stack.length - n, n - j));
  1033. break;
  1034. default:
  1035. return null;
  1036. }
  1037. }
  1038. if (stack.length !== outputSize) {
  1039. return null;
  1040. }
  1041. const result = [];
  1042. for (const instruction of instructions) {
  1043. const statementBuilder = new ExpressionBuilderVisitor();
  1044. instruction.visit(statementBuilder);
  1045. result.push(statementBuilder.toString());
  1046. }
  1047. for (let i = 0, ii = stack.length; i < ii; i++) {
  1048. const expr = stack[i],
  1049. statementBuilder = new ExpressionBuilderVisitor();
  1050. expr.visit(statementBuilder);
  1051. const min = range[i * 2],
  1052. max = range[i * 2 + 1];
  1053. const out = [statementBuilder.toString()];
  1054. if (min > expr.min) {
  1055. out.unshift("Math.max(", min, ", ");
  1056. out.push(")");
  1057. }
  1058. if (max < expr.max) {
  1059. out.unshift("Math.min(", max, ", ");
  1060. out.push(")");
  1061. }
  1062. out.unshift("dest[destOffset + ", i, "] = ");
  1063. out.push(";");
  1064. result.push(out.join(""));
  1065. }
  1066. return result.join("\n");
  1067. }
  1068. }
  1069. return PostScriptCompiler;
  1070. }();
  1071. exports.PostScriptCompiler = PostScriptCompiler;