function.js 32 KB

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