Debian Codegraph @

texk/web2c/mfluadir/mfluatrap/mflua.lua

raw symbols SCIP
1 print("MFLua version: " .. mflua.MFbuiltin.mflua_version())
2 print("MFLua banner: ".. mflua.MFbuiltin.mflua_banner())
3
4 local function PRINTDBG(s) print(tostring(s)) end
5 local function PRINTDBG(s) end
6 local function chMF(t,k) if t[k] then print(k.." already inserted") os.exit(1) end end
7
8 PRINTDBG("mflua.lua")
9
10 --------------------------------------------------------------------------------
11 --
12 -- kpse
13 --
14 --------------------------------------------------------------------------------
15 -- "new"
16 -- "set_program_name"
17 -- "init_prog"
18 -- "readable_file"
19 -- "find_file"
20 -- "expand_path"
21 -- "expand_var"
22 -- "expand_braces"
23 -- "var_value"
24 -- "show_path"
25 -- "lookup"
26 -- "version"
27 -- "default_texmfcnf"
28
29
30 --------------------------------------------------------------------------------
31 --
32 -- These are hardcoded into mflua.MFbuiltin table:
33 --
34 --------------------------------------------------------------------------------
35 MFbuiltin = mflua.MFbuiltin or {}
36 -- function: link
37 -- function: info
38 -- function: x_coord
39 -- function: y_coord
40 -- function: left_type
41 -- function: right_type
42 -- function: left_x
43 -- function: left_y
44 -- function: right_x
45 -- function: right_y
46 -- function: n_sin_cos
47 --
48 -- function: LUAGLOBALGET_boundary_char
49 -- function: LUAGLOBALGET_char_code
50 -- function: LUAGLOBALGET_char_dp
51 -- function: LUAGLOBALGET_char_dx
52 -- function: LUAGLOBALGET_char_dy
53 -- function: LUAGLOBALGET_char_ext
54 -- function: LUAGLOBALGET_char_ht
55 -- function: LUAGLOBALGET_char_ic
56 -- function: LUAGLOBALGET_char_wd
57 -- function: LUAGLOBALGET_cur_edges
58 -- function: LUAGLOBALGET_cur_exp
59 -- function: LUAGLOBALGET_cur_pen
60 -- function: LUAGLOBALGET_designsize
61 -- function: LUAGLOBALGET_fillin
62 -- function: LUAGLOBALGET_granularity
63 -- function: LUAGLOBALGET_hppp
64 -- function: LUAGLOBALGET_mem_top
65 -- function: LUAGLOBALGET_octant
66 -- function: LUAGLOBALGET_turning_check
67 -- function: LUAGLOBALGET_vppp
68 -- function: LUAGLOBALGET_x_offset
69 -- function: LUAGLOBALGET_y_offset
70
71 --
72 -- It's handy to have them as local
73 --
74
75 local link = MFbuiltin.link
76 local info = MFbuiltin.info
77 local x_coord = MFbuiltin.x_coord
78 local y_coord = MFbuiltin.y_coord
79 local left_type = MFbuiltin.left_type
80 local right_type = MFbuiltin.right_type
81 local left_x = MFbuiltin.left_x
82 local left_y = MFbuiltin.left_y
83 local right_x = MFbuiltin.right_x
84 local right_y = MFbuiltin.right_y
85 local n_sin_cos = MFbuiltin.n_sin_cos
86
87
88
89 --------------------------------------------------------------------------------
90 -- Global table mflua.
91 -- Important subtable:
92 -- * mflua.MFbuiltin that stores the hardwired functions;
93 -- * mflua.MF that stores some constants from MetaFont, as also some functions
94 -- from PascalWEB rewritten in Lua (almost 1:1 translation).
95 -- Use them with care !
96 --------------------------------------------------------------------------------
97
98 mflua = mflua or {}
99 mflua.MF = mflua.MF or {}
100
101
102 --------------------------------------------------------------------------------
103 --
104 -- As in MetaFont:
105 --
106 --------------------------------------------------------------------------------
107
108 local min_quarterword = 0 --{smallest allowable value in a |quarterword|}
109 local max_quarterword = 255 --{largest allowable value in a |quarterword|}
110 local min_halfword = 0 --{smallest allowable value in a |halfword|}
111 local max_halfword = 65535 --{largest allowable value in a |halfword|}
112
113 local mem_min = 0 -- {smallest index in the |mem| array, must not be less than |min_halfword|}
114
115 local quarter_unit = 2^14 -- {$2^{14}$, represents 0.250000}
116 local half_unit = 2^15 -- {$2^{15}$, represents 0.50000}
117 local three_quarter_unit = 3*(2^14) -- {$3\cdot2^{14}$, represents 0.75000}
118 local unity = 2^16 -- {$2^{16}$, represents 1.00000}
119 local two = 2^17 -- {$2^{17}$, represents 2.00000}
120 local three = 2^16+2^16 -- {$2^{17}+2^{16}$, represents 3.00000}
121
122
123 chMF(mflua.MF,min_quarterword);mflua.MF.min_quarterword = min_quarterword
124 chMF(mflua.MF,max_quarterword);mflua.MF.max_quarterword = max_quarterword
125 chMF(mflua.MF,min_halfword);mflua.MF.min_halfword = min_halfword
126 chMF(mflua.MF,max_halfword);mflua.MF.max_halfword = max_halfword
127 chMF(mflua.MF,mem_min);mflua.MF.mem_min = mem_min
128 chMF(mflua.MF,quarter_unit);mflua.MF.quarter_unit = quarter_unit
129 chMF(mflua.MF,half_unit);mflua.MF.half_unit = half_unit
130 chMF(mflua.MF,three_quarter_unit);mflua.MF.three_quarter_unit = three_quarter_unit
131 chMF(mflua.MF,unity);mflua.MF.unity = unity
132 chMF(mflua.MF,two);mflua.MF.two = two
133 chMF(mflua.MF,three);mflua.MF.three = three
134
135
136
137 -- @ Given integers |x| and |y|, not both zero, the |n_arg| function
138 -- returns the |angle| whose tangent points in the direction $(x,y)$.
139 -- This subroutine first determines the correct octant, then solves the
140 -- problem for |0<=y<=x|, then converts the result appropriately to
141 -- return an answer in the range |-one_eighty_deg<=@t$\theta$@><=one_eighty_deg|.
142 -- (The answer is |+one_eighty_deg| if |y=0| and |x<0|, but an answer of
143 -- |-one_eighty_deg| is possible if, for example, |y=-1| and $x=-2^{30}$.)
144
145 -- The octants are represented in a ``Gray code,'' since that turns out
146 -- to be computationally simplest.
147
148 negate_x=1
149 negate_y=2
150 switch_x_and_y=4
151 first_octant=1
152 second_octant=first_octant+switch_x_and_y
153 third_octant=first_octant+switch_x_and_y+negate_x
154 fourth_octant=first_octant+negate_x
155 fifth_octant=first_octant+negate_x+negate_y
156 sixth_octant=first_octant+switch_x_and_y+negate_x+negate_y
157 seventh_octant=first_octant+switch_x_and_y+negate_y
158 eighth_octant=first_octant+negate_y
159
160
161 local negate_x=1
162 local negate_y=2
163 local switch_x_and_y=4
164 local first_octant=1
165 local second_octant=first_octant+switch_x_and_y
166 local third_octant=first_octant+switch_x_and_y+negate_x
167 local fourth_octant=first_octant+negate_x
168 local fifth_octant=first_octant+negate_x+negate_y
169 local sixth_octant=first_octant+switch_x_and_y+negate_x+negate_y
170 local seventh_octant=first_octant+switch_x_and_y+negate_y
171 local eighth_octant=first_octant+negate_y
172
173 chMF(mflua.MF,negate_x);mflua.MF.negate_x = negate_x
174 chMF(mflua.MF,negate_y);mflua.MF.negate_y = negate_y
175 chMF(mflua.MF,switch_x_and_y);mflua.MF.switch_x_and_y = switch_x_and_y
176 chMF(mflua.MF,first_octant);mflua.MF.first_octant = first_octant
177 chMF(mflua.MF,second_octant);mflua.MF.second_octant = second_octant
178 chMF(mflua.MF,third_octant);mflua.MF.third_octant = third_octant
179 chMF(mflua.MF,fourth_octant);mflua.MF.fourth_octant = fourth_octant
180 chMF(mflua.MF,fifth_octant);mflua.MF.fifth_octant = fifth_octant
181 chMF(mflua.MF,sixth_octant);mflua.MF.sixth_octant = sixth_octant
182 chMF(mflua.MF,seventh_octant);mflua.MF.seventh_octant = seventh_octant
183 chMF(mflua.MF,eighth_octant);mflua.MF.eighth_octant = eighth_octant
184
185
186 local octant_dir = {}
187 octant_dir[first_octant]="ENE-1"
188 octant_dir[second_octant]="NNE-2"
189 octant_dir[third_octant]="NNW-3"
190 octant_dir[fourth_octant]="WNW-4"
191 octant_dir[fifth_octant]="WSW-5"
192 octant_dir[sixth_octant]="SSW-6"
193 octant_dir[seventh_octant]="SSE-7"
194 octant_dir[eighth_octant]="ESE-8"
195
196 chMF(mflua.MF,octant_dir);mflua.MF.octant_dir = octant_dir
197
198 -- @ Finally we come to the last steps of |make_spec|, when boundary nodes
199 -- are inserted between cubics that move in different octants. The main
200 -- complication remaining arises from consecutive cubics whose octants
201 -- are not adjacent; we should insert more than one octant boundary
202 -- at such sharp turns, so that the envelope-forming routine will work.
203 -- For this purpose, conversion tables between numeric and Gray codes for
204 -- octants are desirable.
205 -- @<Glob...@>=
206 -- @!octant_number:array[first_octant..sixth_octant] of 1..8;
207 -- @!octant_code:array[1..8] of first_octant..sixth_octant;
208
209 local octant_code = {}
210 octant_code[1]=first_octant;
211 octant_code[2]=second_octant;
212 octant_code[3]=third_octant;
213 octant_code[4]=fourth_octant;
214 octant_code[5]=fifth_octant;
215 octant_code[6]=sixth_octant;
216 octant_code[7]=seventh_octant;
217 octant_code[8]=eighth_octant;
218 chMF(mflua.MF,octant_code);mflua.MF.octant_code = octant_code
219
220
221 local octant_number = {}
222 for k=1, 8 do octant_number[octant_code[k]]=k; end
223 chMF(mflua.MF,octant_number);mflua.MF.octant_number = octant_number
224
225
226 -- It is convenient to define a \.{WEB} macro |t_of_the_way| such that
227 -- |t_of_the_way(a)(b)| expands to |a-(a-b)*t|, i.e., to |t[a,b]|.
228 -- @d t_of_the_way_end(#)==#,t@=)@>
229 -- @d t_of_the_way(#)==#-take_fraction@=(@>#-t_of_the_way_end
230 --
231 -- TO implement !!
232 -- function t_of_the_way(a,b,t)
233 -- return take_fraction(a-b,t)
234 -- end
235
236 local endpoint = 0 -- {|left_type| at path beginning and |right_type| at path end}
237 local knot_node_size = 7 -- {number of words in a knot node} */
238
239 local left_curl=left_x -- {curl information when entering this knot}
240 local left_given=left_x -- {given direction when entering this knot}
241 local left_tension=left_y -- {tension information when entering this knot}
242 local right_curl=right_x -- {curl information when leaving this knot}
243 local right_given=right_x -- {given direction when leaving this knot}
244 local right_tension=right_y -- {tension information when leaving this knot}
245 local explicit =1 -- {|left_type| or |right_type| when control points are known}
246 local given = 2 -- {|left_type| or |right_type| when a direction is given}
247 local curl = 3 -- {|left_type| or |right_type| when a curl is desired}
248 local open = 4 -- {|left_type| or |right_type| when \MF\ should choose the direction}
249
250 local right_octant=right_x -- {the octant code before a transition}
251 local left_octant=left_x -- {the octant after a transition}
252 local right_transition=right_y -- {the type of transition}
253 local left_transition=left_y -- {ditto, either |axis| or |diagonal|}
254 local axis=0 -- {a transition across the $x'$- or $y'$-axis}
255 local diagonal=1 -- {a transition where $y'=\pm x'$}
256
257 local mem_top = MFbuiltin.mem_top()
258 local sentinel= mem_top --{end of sorted lists}
259 local null = mem_min -- {the null pointer}
260 local knil=info -- {inverse of the |link| field, in a doubly linked list}
261 local zero_w=4
262 local void=null+1
263
264 local zero_field=4096 -- {amount added to coordinates to make them positive}
265
266
267 chMF(mflua.MF,endpoint);mflua.MF.endpoint = endpoint
268 chMF(mflua.MF,knot_node_size);mflua.MF.knot_node_size = knot_node_size
269
270 chMF(mflua.MF,left_curl);mflua.MF.left_curl = left_curl
271 chMF(mflua.MF,left_given);mflua.MF.left_given = left_given
272 chMF(mflua.MF,left_tension);mflua.MF.left_tension = left_tension
273 chMF(mflua.MF,right_curl);mflua.MF.right_curl = right_curl
274 chMF(mflua.MF,right_given);mflua.MF.right_given = right_given
275 chMF(mflua.MF,right_tension);mflua.MF.right_tension = right_tension
276 chMF(mflua.MF,explicit);mflua.MF.explicit = explicit
277 chMF(mflua.MF,given);mflua.MF.given = given
278 chMF(mflua.MF,curl);mflua.MF.curl = curl
279 chMF(mflua.MF,open);mflua.MF.open = open
280
281 chMF(mflua.MF,right_octant);mflua.MF.right_octant = right_octant
282 chMF(mflua.MF,left_octant);mflua.MF.left_octant = left_octant
283 chMF(mflua.MF,right_transition);mflua.MF.right_transition = right_transition
284 chMF(mflua.MF,left_transition);mflua.MF.left_transition = left_transition
285 chMF(mflua.MF,axis);mflua.MF.axis = axis
286 chMF(mflua.MF,diagonal);mflua.MF.diagonal = diagonal
287
288 chMF(mflua.MF,mem_top);mflua.MF.mem_top = mem_top
289 chMF(mflua.MF,sentinel);mflua.MF.sentinel = sentinel
290 chMF(mflua.MF,null);mflua.MF.null = null
291 chMF(mflua.MF,knil);mflua.MF.knil = knil
292 chMF(mflua.MF,zero_w);mflua.MF.zero_w = zero_w
293 chMF(mflua.MF,void);mflua.MF.void = void
294
295 chMF(mflua.MF,zero_field);mflua.MF.zero_field = zero_field
296
297
298 -- @d incr(#) == #:=#+1 {increase a variable by unity}
299 local function incr(p)
300 return p+1
301 end
302 chMF(mflua.MF,incr);mflua.MF.incr = incr
303
304 -- decr(#) == #:=#-1 {decrease a variable by unity}
305 local function decr(p)
306 return p-1
307 end
308 chMF(mflua.MF,decr);mflua.MF.decr = decr
309
310 -- double(#) == #:=#+# {multiply a variable by two}
311 local function double(p)
312 return 2*p
313 end
314 chMF(mflua.MF,double);mflua.MF.double = double
315
316
317
318 -- @ An array of digits in the range |0..9| is printed by |print_the_digs|.
319 -- @<Basic print...@>=
320 -- procedure print_the_digs(@!k:eight_bits);
321 -- {prints |dig[k-1]|$\,\ldots\,$|dig[0]|}
322 -- begin while k>0 do
323 -- begin decr(k); print_char("0"+dig[k]);
324 -- end;
325 -- end;
326 local function print_the_digs(k,dig)
327 local res = ''
328 while k > 0 do
329 k=k-1
330 res= res .. dig[k+1]
331 end
332 return res
333 end
334 chMF(mflua.MF,print_the_digs);mflua.MF.print_the_digs = print_the_digs
335
336
337 -- @<Basic print...@>=
338 -- procedure print_int(@!n:integer); {prints an integer in decimal form}
339 -- var k:0..23; {index to current digit; we assume that $|n|<10^{23}$}
340 -- @!m:integer; {used to negate |n| in possibly dangerous cases}
341 -- begin k:=0;
342 -- if n<0 then
343 -- begin print_char("-");
344 -- if n>-100000000 then negate(n)
345 -- else begin m:=-1-n; n:=m div 10; m:=(m mod 10)+1; k:=1;
346 -- if m<10 then dig[0]:=m
347 -- else begin dig[0]:=0; incr(n);
348 -- end;
349 -- end;
350 -- end;
351 -- repeat dig[k]:=n mod 10; n:=n div 10; incr(k);
352 -- until n=0;
353 -- print_the_digs(k);
354 -- end;
355 local function print_int(n) -- {prints an integer in decimal form}
356 local k -- 0..23; {index to current digit; we assume that $|n|<10^{23}$}
357 local m -- {used to negate |n| in possibly dangerous cases}
358 local dig = {}
359 local done
360 local res
361 local sign=''
362 k=0
363 if n<0 then
364 --begin print_char("-");
365 sign='-'
366 if n>-100000000
367 then
368 n=-n
369 else
370 m=-1-n; n=math.floor(m/10) ; m=math.fmod(m,10)+1; k=1;
371 if m<10
372 then
373 dig[1]=m
374 else
375 dig[1]=0; n=n+1
376 end
377 end
378 end
379 done=false
380 while not done do
381 dig[k+1]=math.fmod(n,10); n=math.floor(n/10); k=k+1;
382 if n==0 then done=true end
383 end
384 res = print_the_digs(k,dig)
385 return sign .. res
386 end
387 chMF(mflua.MF,print_int);mflua.MF.print_int = print_int
388
389
390
391 -- @<Basic printing...@>=
392 -- procedure print_scaled(@!s:scaled); {prints scaled real, rounded to five
393 -- digits}
394 -- var @!delta:scaled; {amount of allowable inaccuracy}
395 -- begin if s<0 then
396 -- begin print_char("-"); negate(s); {print the sign, if negative}
397 -- end;
398 -- print_int(s div unity); {print the integer part}
399 -- s:=10*(s mod unity)+5;
400 -- if s<>5 then
401 -- begin delta:=10; print_char(".");
402 -- repeat if delta>unity then
403 -- s:=s+@'100000-(delta div 2); {round the final digit '}
404 -- print_char("0"+(s div unity)); s:=10*(s mod unity); delta:=delta*10;
405 -- until s<=delta;
406 -- end;
407 -- end;
408 local function print_scaled(s)
409 local delta
410 local res = ''
411 local done
412 if s== nil then print("\nWarning: print_scale called with nil argument."); return res end
413 if s<0 then
414 res = '-'
415 s=-s
416 end
417 res = res .. print_int(math.floor(s/unity)) -- {print the integer part}
418 s=10*(math.fmod(s,unity))+5
419 if s ~= 5 then
420 delta=10; res = res .. '.'
421 done = false
422 while not done do
423 if delta>unity then
424 s=s+half_unit-(math.floor(delta/2)) -- {round the final digit}
425 end
426 res = res .. math.floor(s/unity); s=10*math.fmod(s,unity); delta=delta*10;
427 if s<=delta then done = true end
428 end;
429 end
430 return res
431 end
432 chMF(mflua.MF,print_scaled);mflua.MF.print_scaled = print_scaled
433
434
435
436 -- @<Basic printing...@>=
437 -- procedure print_two(@!x,@!y:scaled); {prints `|(x,y)|''}
438 -- begin print_char("("); print_scaled(x); print_char(","); print_scaled(y);
439 -- print_char(")");
440 -- end;
441 local function print_two(x,y) -- {prints `|(x,y)|'}
442 local res
443 -- debug
444 res = '(' .. print_scaled(x) .. ',' .. print_scaled(y) .. ')'
445 return res
446 end
447 chMF(mflua.MF,print_two);mflua.MF.print_two = print_two
448
449 -- procedure unskew(@!x,@!y:scaled;@!octant:small_number);
450 -- begin case octant of
451 -- first_octant: set_two(x+y)(y);
452 -- second_octant: set_two(y)(x+y);
453 -- third_octant: set_two(-y)(x+y);
454 -- fourth_octant: set_two(-x-y)(y);
455 -- fifth_octant: set_two(-x-y)(-y);
456 -- sixth_octant: set_two(-y)(-x-y);
457 -- seventh_octant: set_two(y)(-x-y);
458 -- eighth_octant: set_two(x+y)(-y);
459 -- end; {there are no other cases}
460 -- end;
461 local function unskew ( x , y , octant )
462 local curx,cury
463 if octant == 1 then
464 curx = x + y ;
465 cury = y ;
466 elseif octant == 5 then
467 curx = y ;
468 cury = x + y ;
469 elseif octant == 6 then
470 curx = -y ;
471 cury = x + y ;
472 elseif octant == 2 then
473 curx = -x - y ;
474 cury = y ;
475 elseif octant == 4 then
476 curx = -x - y ;
477 cury = -y ;
478 elseif octant == 8 then
479 curx = -y ;
480 cury = -x - y ;
481 elseif octant == 7 then
482 curx = y ;
483 cury = -x - y ;
484 elseif octant == 3 then
485 curx = x + y ;
486 cury = -y ;
487 end
488 return curx,cury
489 end
490 chMF(mflua.MF,unskew);mflua.MF.unskew = unskew
491
492 -- print_two_true(#)==unskew(#,octant); print_two(cur_x,cur_y)
493 local function print_two_true(x,y,octant)
494 local cur_x,cur_y ,res
495 cur_x,cur_y = unskew ( x , y , octant )
496 res = print_two(cur_x,cur_y)
497 return res
498 end
499 chMF(mflua.MF,print_two_true);mflua.MF.print_two_true = print_two_true
500 --
501 -- Debug only
502 --
503 -- function mflua_print_path(h)
504 -- print("mflua_print_path")
505 -- local p,q
506 -- local res
507 -- local done
508 -- local done1
509 -- local f
510 -- done = false
511 -- done1 = false
512 -- p = h
513 -- res = ''
514 -- while not done do
515 -- q = link(p)
516 -- if (p==0) or (q==0) then
517 -- res = "???"
518 -- -- do something with res --
519 -- return 0
520 -- end
521 -- res = res .. print_two(x_coord(p),y_coord(p)); -- print("res=",res)
522 -- if right_type(p) == endpoint then
523 -- if left_type(p)== open then print("{open?}") end -- {can't happen}
524 -- if (left_type(q) ~= endpoint) or (q ~= h) then q=null end -- {force an error}
525 -- done1 = true -- goto done1;
526 -- elseif right_type(p) == explicit then
527 -- -- begin "@<Print control points between |p| and |q|, then |goto done1|@>"
528 -- res = res .. "..controls " .. print_two(right_x(p),right_y(p)) .. " and ";
529 -- if left_type(q) ~= explicit then print("??") -- {can't happen}
530 -- else res = res .. print_two(left_x(q),left_y(q));
531 -- done1 = true -- goto done1;
532 -- end
533 -- -- end "@<Print control points between |p| and |q|, then |goto done1|@>"
534 -- elseif right_type(p) == open then
535 -- -- begin "@<Print information for a curve that begins |open|@>"
536 -- if (left_type(p) ~= explicit) and (left_type(p)~=open) then
537 -- res = res .. "{open?}" -- {can't happen}
538 -- end
539 -- -- end "@<Print information for a curve that begins |open|@>"
540 -- elseif (right_type(p) == curl) or (right_type(p) == given) then
541 -- -- @ A curl of 1 is shown explicitly, so that the user sees clearly that
542 -- -- \MF's default curl is present.
543 -- -- begin @<Print information for a curve that begins |curl|...@>=
544 -- if left_type(p)==open then res = res .. "??" end -- {can't happen}
545 -- if right_type(p)==curl then
546 -- res = res .. "{curl ".. print_scaled(right_curl(p))
547 -- else n_sin_cos(right_given(p)); res = res .."{"
548 -- res = res .. print_scaled(n_cos) .. "," .. print_scaled(n_sin)
549 -- end
550 -- res = res .."}"
551 -- -- end @<Print information for a curve that begins |curl|...@>=
552 -- else res = res .. "???" -- {can't happen}
553 -- end
554 -- if not done1 then -- mimic label done 1
555 -- if left_type(q)~=explicit then res = res .. "..control?" -- {can't happen}
556 -- else if (right_tension(p) ~= unity) or (left_tension(q) ~= unity) then
557 -- -- begin "@<Print tension between |p| and |q|@>;"
558 -- res = res .. "..tension "
559 -- if right_tension(p)<0 then res = res .. "atleast" end
560 -- res = res .. print_scaled(math.abs(right_tension(p)))
561 -- if right_tension(p) ~= left_tension(q) then
562 -- res = res .. " and "
563 -- if left_tension(q)<0 then res = res .. "atleast" end
564 -- res = res .. print_scaled(math.abs(left_tension(q)))
565 -- end
566 -- end -- "@<Print tension between |p| and |q|@>;"
567 -- end
568 -- end --- LABEL: done1
569 -- -- begin @<Print two dots...@>=
570 -- p = q
571 -- res = res .. " .."
572 -- if left_type(p)==given then
573 -- n_sin_cos(left_given(p)); res = res .. "{"
574 -- res = res .. print_scaled(n_cos); res = res .. ",";
575 -- res = res .. print_scaled(n_sin); res = res .. "}";
576 -- else if left_type(p)==curl then
577 -- res = res .. "{curl "; res = res .. print_scaled(left_curl(p)) .. "}";
578 -- end;
579 -- end
580 -- -- end @<Print two dots...@>=
581 -- -- end "@<Print information for adjacent knots |p| and |q|@>"
582 -- if p == h then done =true end
583 -- end
584 -- if left_type(h) ~= endpoint then
585 -- res = res .. "cycle"
586 -- else
587 -- res = res
588 -- end
589 -- -- do something with res --
590 -- return res
591 -- end
592
593
594
595 -- n_max(#)==link(#+1) {maximum row number present, plus |zero_field|}
596 local function n_max(p)
597 return link(p+1)
598 end
599 chMF(mflua.MF,n_max);mflua.MF.n_max = n_max
600
601
602 -- sorted_loc(#)==#+1 {where the |sorted| link field resides}
603 local function sorted_loc(p)
604 return p+1
605 end
606 chMF(mflua.MF,sorted_loc);mflua.MF.sorted_loc = sorted_loc
607
608
609 -- @d sorted(#)==link(sorted_loc(#)) {beginning of the list of sorted edge weights}
610 local function sorted(p)
611 return link(sorted_loc(p))
612 end
613 chMF(mflua.MF,sorted);mflua.MF.sorted = sorted
614
615
616 -- @d unsorted(#)==info(#+1) {beginning of the list of unsorted edge weights}
617 local function unsorted(p)
618 return info(p+1)
619 end
620 chMF(mflua.MF,unsorted);mflua.MF.unsorted = unsorted
621
622 -- @d ho(#)==#-min_halfword
623 -- {to take a sixteen-bit item from a halfword}
624 -- See mf.ch
625 -- ho(#) == #
626 local function ho(p)
627 return p
628 end
629 chMF(mflua.MF,ho);mflua.MF.ho = ho
630 --
631 -- @d m_offset(#)==info(#+3) {translation of $m$ data in edge-weight nodes}
632 --
633 function m_offset(p)
634 return info(p+3)
635 end
636
637
638
639 -- @ @<Declare the procedure called |print_weight|@>=
640 -- procedure print_weight(@!q:pointer;@!x_off:integer);
641 -- var @!w,@!m:integer; {unpacked weight and coordinate}
642 -- @!d:integer; {temporary data register}
643 -- begin d:=ho(info(q)); w:=d mod 8; m:=(d div 8)-m_offset(cur_edges);
644 -- if file_offset>max_print_line-9 then print_nl(" ")
645 -- else print_char(" ");
646 -- print_int(m+x_off);
647 -- while w>zero_w do
648 -- begin print_char("+"); decr(w);
649 -- end;
650 -- while w<zero_w do
651 -- begin print_char("-"); incr(w);
652 -- end;
653 -- end;
654 local function print_weight(q,x_off)
655 local w,m -- {unpacked weight and coordinate}
656 local d --{temporary data register}
657 local cur_edges = MFbuiltin.cur_edges()
658 local res = ''
659 local temp
660 d=ho(info(q)); w=math.fmod(d,8); m=math.floor(d/8)-m_offset(cur_edges);
661 res = tostring(print_int(m+x_off))
662 while w>zero_w do
663 --print(tostring(print_int(m+x_off)) .. " w=" .. w.. " " .. zero_w .. " " .. (w-zero_w))
664 res = res .. "+" ; w=decr(w);
665 end
666 while w<zero_w do
667 --print(tostring(print_int(m+x_off)) .. " w=" .. w.. " " .. zero_w .. " " .. (w-zero_w))
668 res = res .. "-" ; w=incr(w)
669 end
670 --print("res=" .. res .. "w=" .. math.fmod(d,8)-zero_w)
671 return res, math.fmod(d,8)-zero_w,tostring(print_int(m+x_off))
672 end
673 chMF(mflua.MF,print_weight);mflua.MF.print_weight = print_weight
674
675 -- Others utilities functions
676 local function odd(n)
677 return math.fmod(n,2) == 1
678 end
679 chMF(mflua.MF,odd);mflua.MF.odd = odd
680
681 --------------------------------------------------------------------------------
682 --
683 -- Read-only callbacs aka Sensors
684 --
685 --------------------------------------------------------------------------------
686
687 local function begin_program()
688 PRINTDBG("begin_program")
689 end
690
691 local function PRE_start_of_MF()
692 PRINTDBG("PRE_start_of_MF")
693 end
694
695 local function PRE_main_control()
696 PRINTDBG("PRE_main_control")
697 end
698
699 local function POST_main_control()
700 PRINTDBG("POST_main_control")
701 end
702
703 local function mflua_initialize()
704 PRINTDBG("mflua_initialize")
705 end
706
707 local function POST_final_cleanup()
708 PRINTDBG("POST_final_cleanup")
709 end
710
711 local function printpath(h,s,nuline)
712 PRINTDBG("printpath")
713 local p,q
714 local res
715 local done
716 local done1
717 local f
718 done = false
719 done1 = false
720 p = h
721 res = ''
722 while not done do
723 q = link(p)
724 if (p==0) or (q==0) then
725 res = "???"
726 -- do something with res --
727 return 0
728 end
729 -- We can choose to follow the pascal-web way
730 -- or to follow the C-web2c way
731 -- begin "@<Print information for adjacent knots |p| and |q|@>"
732 res = res .. print_two(x_coord(p),y_coord(p)); -- print("res=",res)
733 if right_type(p) == endpoint then
734 if left_type(p)== open then print("{open?}") end -- {can't happen}
735 if (left_type(q) ~= endpoint) or (q ~= h) then q=null end -- {force an error}
736 done1 = true -- goto done1;
737 elseif right_type(p) == explicit then
738 -- begin "@<Print control points between |p| and |q|, then |goto done1|@>"
739 res = res .. "..controls " .. print_two(right_x(p),right_y(p)) .. " and ";
740 if left_type(q) ~= explicit then print("??") -- {can't happen}
741 else res = res .. print_two(left_x(q),left_y(q));
742 done1 = true -- goto done1;
743 end
744 -- end "@<Print control points between |p| and |q|, then |goto done1|@>"
745 elseif right_type(p) == open then
746 -- begin "@<Print information for a curve that begins |open|@>"
747 if (left_type(p) ~= explicit) and (left_type(p)~=open) then
748 res = res .. "{open?}" -- {can't happen}
749 end
750 -- end "@<Print information for a curve that begins |open|@>"
751 elseif (right_type(p) == curl) or (right_type(p) == given) then
752 -- @ A curl of 1 is shown explicitly, so that the user sees clearly that
753 -- \MF's default curl is present.
754 -- begin @<Print information for a curve that begins |curl|...@>=
755 if left_type(p)==open then res = res .. "??" end -- {can't happen}
756 if right_type(p)==curl then
757 res = res .. "{curl ".. print_scaled(right_curl(p))
758 else n_sin_cos(right_given(p)); res = res .."{"
759 res = res .. print_scaled(n_cos) .. "," .. print_scaled(n_sin)
760 end
761 res = res .."}"
762 -- end @<Print information for a curve that begins |curl|...@>=
763 else res = res .. "???" -- {can't happen}
764 end
765 if not done1 then -- mimic label done 1
766 if left_type(q)~=explicit then res = res .. "..control?" -- {can't happen}
767 else if (right_tension(p) ~= unity) or (left_tension(q) ~= unity) then
768 -- begin "@<Print tension between |p| and |q|@>;"
769 res = res .. "..tension "
770 if right_tension(p)<0 then res = res .. "atleast" end
771 res = res .. print_scaled(math.abs(right_tension(p)))
772 if right_tension(p) ~= left_tension(q) then
773 res = res .. " and "
774 if left_tension(q)<0 then res = res .. "atleast" end
775 res = res .. print_scaled(math.abs(left_tension(q)))
776 end
777 end -- "@<Print tension between |p| and |q|@>;"
778 end
779 end --- LABEL: done1
780 -- begin @<Print two dots...@>=
781 p = q
782 res = res .. " .."
783 if left_type(p)==given then
784 n_sin_cos(left_given(p)); res = res .. "{"
785 res = res .. print_scaled(n_cos); res = res .. ",";
786 res = res .. print_scaled(n_sin); res = res .. "}";
787 else if left_type(p)==curl then
788 res = res .. "{curl "; res = res .. print_scaled(left_curl(p)) .. "}";
789 end;
790 end
791 -- end @<Print two dots...@>=
792 -- end "@<Print information for adjacent knots |p| and |q|@>"
793 if p == h then done =true end
794 end
795 if left_type(h) ~= endpoint then res = res .. "cycle" end
796 -- do something with res --
797 res = "%%Print path\n" .. "drawoptions(withcolor black withpen pencircle scaled 1pt);\n" .. "draw " .. res .. " ;\n"
798 --print(res)
799 -- local index = (0+print_int(MFbuiltin.char_code())) + (0+print_int(MFbuiltin.char_ext()))*256
800 -- local char = mflua.chartable[index] or {}
801 -- char['char_wd'] = print_scaled(MFbuiltin.char_wd())
802 -- char['char_ht'] = print_scaled(MFbuiltin.char_ht())
803 -- char['char_dp'] = print_scaled(MFbuiltin.char_dp())
804 -- char['char_ic'] = print_scaled(MFbuiltin.char_ic())
805 -- char['res'] = char['res'] or ""
806 -- char['res'] = char['res'] .. res
807 -- mflua.chartable[index] = char
808 end
809
810
811 -- @ The |print_edges| subroutine gives a symbolic rendition of an edge
812 -- structure, for use in `\&{show}\' commands. A rather terse output
813 -- format has been chosen since edge structures can grow quite large.
814
815 -- @<Declare subroutines for printing expressions@>=
816 -- @t\4@>@<Declare the procedure called |print_weight|@>@;@/
817 -- procedure print_edges(@!s:str_number;@!nuline:boolean;@!x_off,@!y_off:integer);
818 -- var @!p,@!q,@!r:pointer; {for list traversal}
819 -- @!n:integer; {row number}
820 -- begin
821 -- mflua_printedges(s,nuline,x_off,y_off);
822 -- print_diagnostic("Edge structure",s,nuline);
823 -- p:=knil(cur_edges); n:=n_max(cur_edges)-zero_field;
824 -- while p<>cur_edges do
825 -- begin q:=unsorted(p); r:=sorted(p);
826 -- if(q>void)or(r<>sentinel) then
827 -- begin print_nl("row "); print_int(n+y_off); print_char(":");
828 -- while q>void do
829 -- begin print_weight(q,x_off); q:=link(q);
830 -- end;
831 -- print(" |");
832 -- while r<>sentinel do
833 -- begin print_weight(r,x_off); r:=link(r);
834 -- end;
835 -- end;
836 -- p:=knil(p); decr(n);
837 -- end;
838 -- end_diagnostic(true);
839 -- end;
840 local function printedges(s,nuline,x_off,y_off)
841 PRINTDBG("printedges")
842 local p,q,r -- for list traversal
843 local n=0 -- row number
844 local cur_edges = MFbuiltin.cur_edges()
845 local res =''
846 local y = {}
847 local xr = {}
848 local xq = {}
849 local f, start_row, end_row ,start_row_1, end_row_1
850 local edge
851 local w,w_integer,row_weight,xoff
852 local chartable = mflua.chartable
853 local index
854 local char
855 p = knil(cur_edges)
856 n = n_max(cur_edges)-zero_field
857 while p ~= cur_edges do
858 xq = {}; xr = {}
859 q=unsorted(p); r=sorted(p)
860 if(q>void)or(r~=sentinel) then
861 res = "mflua row " .. print_int(n+y_off) ..":"
862 while (q>void) do
863 w, w_integer,xoff = print_weight(q,x_off)
864 xq[#xq+1] = {xoff,w_integer}
865 res = res .. w; q=link(q);
866 end
867 res = res .. " |"
868 while r~=sentinel do
869 w,w_integer,xoff = print_weight(r,x_off)
870 xr[#xr+1]= {xoff,w_integer}
871 res = res .. w .. ' '; r=link(r)
872 end
873 y[#y+1] = {print_int(n+y_off),xq,xr}
874 end
875 -- print(res)
876 p=knil(p);n=decr(n);
877 end
878 --
879 -- local management of y, xq, xr
880 --
881 index = (0+print_int(MFbuiltin.char_code())) + (0+print_int(MFbuiltin.char_ext()))*256
882 char = chartable[index] or {}
883 --print("#xq=".. #xq)
884 for i,v in ipairs(y) do
885 xq,xr = v[2],v[3]
886 -- for j=1, #xq, 2 do end ??
887 row_weight=0
888 for j=1, #xr, 1 do
889 local xb = xr[j][1]
890 local xwb = xr[j][2]
891 row_weight=row_weight+xwb
892 xr[j][3]=row_weight
893 --print(v[1],xr[j][1],xr[j][2],xr[j][3])
894 end
895 end
896 char['edges'] = char['edges'] or {}
897 char['edges'][#char['edges']+1] = {y,x_off,y_off}
898
899 char['pre_res'] = char['pre_res'] or ""
900 for i,v in ipairs(y) do
901 xq,xr = v[2],v[3]
902 -- for j=1, #xq, 2 do end ??
903 row_weight=0
904 char['pre_res'] = char['pre_res'] .. "%% print edges " .. v[1] .. "\n"
905 for j=1, #xr-1, 1 do
906 local xb,xe = xr[j][1],xr[j+1][1]
907 local xsb,xse = xr[j][3],xr[j+1][3]
908 res = ""
909 if xsb>0 then
910 local color = {'0.7white','0.5white','0.4white'}
911 local col = color[xsb] or 'black'
912 res = res .. "drawoptions(withcolor " .. col .. " withpen pencircle scaled 0.1pt);\n"
913 edge = string.format("fill (%s,%s) -- (%s,%s) -- (%s,%s+1) -- (%s,%s+1) -- cycle shifted (-(%s),-(%s));\n",
914 xb,v[1],xe,v[1],xe,v[1],xb,v[1],x_off,y_off)
915 res = res .. edge
916 --
917 res = res .. "drawoptions(withcolor black withpen pencircle scaled 0.1pt);\n"
918 edge = string.format("draw (%s,%s) -- (%s,%s) -- (%s,%s+1) -- (%s,%s+1) -- cycle shifted (-(%s),-(%s));\n",
919 xb,v[1],xe,v[1],xe,v[1],xb,v[1],x_off,y_off)
920 res = res .. edge
921 end
922 -- print(v[1],xr[j][1],xr[j][2],xr[j][3])
923 char['pre_res'] = char['pre_res'] .. res
924 end
925 end
926 end
927 mflua.MF.printedges = printedges
928
929
930
931
932 -- @ The |print_pen| subroutine illustrates these conventions by
933 -- reconstructing the vertices of a polygon from \MF\'s complicated
934 -- internal offset representation.
935 -- @<Declare subroutines for printing expressions@>=
936
937 local function print_pen(p,s,nuline)
938 local nothing_printed -- {:boolean has there been any action yet?}
939 local k --1..8; {octant number}
940 local h -- pointer; {offset list head}
941 local m,n -- integer; {offset indices}
942 local w,ww -- :pointer; {pointers that traverse the offset list}
943 local res = ''
944 -- begin print_diagnostic("Pen polygon",s,nuline);
945 nothing_printed=true; -- print()
946 for k=1,8 do
947 local octant=octant_code[k]; h=p+octant; n=info(h); w=link(h);
948 -- print("%% octant",octant_dir[octant],n,w)
949 if not(odd(k)==true) then w=knil(w) end -- {in even octants, start at $w_{n+1}$}
950 for m=1, n+1 do
951 if odd(k)==true then ww=link(w) else ww=knil(w) end
952 -- print("%% ".. m .. "/" .. n+1 .. " w=" .. print_two_true(x_coord(w),y_coord(w),octant) .. " ww=" .. print_two_true(x_coord(ww),y_coord(ww),octant))
953 if (x_coord(ww)~=x_coord(w)) or (y_coord(ww)~=y_coord(w)) then
954 ---@<Print the unskewed and unrotated coordinates of node |ww|@>;
955 if nothing_printed then nothing_printed=false else -- print(" .. ")
956 end
957 -- print(print_two_true(x_coord(ww),y_coord(ww),octant))
958 res = res .. print_two_true(x_coord(ww),y_coord(ww),octant)
959 end
960 w=ww;
961 end -- for m=1, n+1 do
962 end -- for k=1,8 do
963 if nothing_printed==true then
964 w=link(p+first_octant); print(print_two(x_coord(w)+y_coord(w),y_coord(w)));
965 res = res .. print_two(x_coord(w)+y_coord(w),y_coord(w))
966 end;
967 res = res .. " .. cycle"; --end_diagnostic(true);
968 return res
969 end -- function
970 mflua.MF.print_pen = print_pen
971
972 mflua.offset_prep = mflua.offset_prep or {}
973
974 local function _get_pen(p)
975 local nothing_printed -- {:boolean has there been any action yet?}
976 local k --1..8; {octant number}
977 local h -- pointer; {offset list head}
978 local m,n -- integer; {offset indices}
979 local w,ww -- :pointer; {pointers that traverse the offset list}
980 local res = {}
981 nothing_printed=true;
982 for k=1,8 do
983 local octant=octant_code[k]; h=p+octant; n=info(h); w=link(h);
984 if not(odd(k)==true) then w=knil(w) end -- {in even octants, start at $w_{n+1}$}
985 for m=1, n+1 do
986 if odd(k)==true then ww=link(w) else ww=knil(w) end
987 if (x_coord(ww)~=x_coord(w)) or (y_coord(ww)~=y_coord(w)) then
988 ---@<Print the unskewed and unrotated coordinates of node |ww|@>;
989 if nothing_printed then nothing_printed=false else -- print(" .. ")
990 end
991 -- print(print_two_true(x_coord(ww),y_coord(ww),octant))
992 res[#res+1] = print_two_true(x_coord(ww),y_coord(ww),octant)
993 end
994 w=ww;
995 end -- for m=1, n+1 do
996 end -- for k=1,8 do
997 if nothing_printed==true then
998 w=link(p+first_octant);
999 res[#res+1] = print_two(x_coord(w)+y_coord(w),y_coord(w))
1000 end;
1001 -- print(" .. cycle"); --end_diagnostic(true);
1002 return res
1003 end
1004 mflua.offset_prep._get_pen = _get_pen
1005
1006 local function _get_offset_coords(p,octant)
1007 local nothing_printed -- {:boolean has there been any action yet?}
1008 local k --1..8; {octant number}
1009 local h -- pointer; {offset list head}
1010 local m,n -- integer; {offset indices}
1011 local w,ww -- :pointer; {pointers that traverse the offset list}
1012 local res ={}
1013 nothing_printed=true; --print()
1014 k=octant_number[octant];
1015 h=p+octant; n=info(h); w=link(h);
1016 if not(odd(k)==true) then w=knil(w) end -- {in even octants, start at $w_{n+1}$}
1017 for m=1, n+1 do
1018 if odd(k)==true then ww=link(w) else ww=knil(w) end
1019 res[m] = print_two_true(x_coord(w),y_coord(w),octant)
1020 w=ww;
1021 end -- for m=1, n+1 do
1022 return res
1023 end -- function
1024 mflua.offset_prep._get_offset_coords = _get_offset_coords
1025
1026
1027 -- @ Given a pointer |c| to a nonempty list of cubics,
1028 -- and a pointer~|h| to the header information of a pen polygon segment,
1029 -- the |offset_prep| routine changes the list into cubics that are
1030 -- associated with particular pen offsets. Namely, the cubic between |p|
1031 -- and~|q| should be associated with the |k|th offset when |right_type(p)=k|.
1032
1033 -- List |c| is actually part of a cycle spec, so it terminates at the
1034 -- first node whose |right_type| is |endpoint|. The cubics all have
1035 -- monotone-nondecreasing $x(t)$ and $y(t)$.
1036
1037 mflua.do_add_to = mflua.do_add_to or {}
1038 mflua.do_add_to.bezier_octant = {}
1039 mflua.do_add_to.bezier_octant_envelope = {}
1040 mflua.do_add_to.bezier_octant_I = {}
1041 mflua.do_add_to.bezier_octant_contour = {}
1042
1043
1044 local function print_specification(c,h)
1045 local p,q,n,nh
1046 local octant
1047 local cur_spec
1048 local res,res1 = "",""
1049 local offsets = {}
1050 local cubic,cubics ={},{}
1051 local f
1052 local first_point, first_point_offset
1053
1054 local bezier,beziers ={},{}
1055 local offset_list = {}
1056 local path_list ={}
1057 local bezier_octant
1058 local pen_key = ''
1059 local temp1 = mflua.print_specification.temp1
1060
1061 cur_spec=c
1062 p=cur_spec
1063 --n=info(h)
1064 --lh=link(h) --{now |lh| points to $w_0$}
1065 octant = left_octant(p)
1066 offsets = mflua.offset_prep._get_offset_coords(MFbuiltin.cur_pen(),octant)
1067
1068 -- for l=1,#offsets do print("SPEC " .. offsets[l] )end
1069
1070 cubics['offsets'] = offsets
1071 cubics['octant_number'] = octant_number[octant]
1072
1073 beziers['offsets'] = offsets
1074 beziers['octant_number'] = octant_number[octant]
1075 beziers['pen'] = mflua.offset_prep._get_pen(MFbuiltin.cur_pen())
1076
1077 for i,v in ipairs(beziers['pen']) do
1078 --print( "BEZ pen=",i,v)
1079 pen_key = pen_key..v
1080 end
1081 --if not(mflua.pen[pen_key] == nil) then
1082 --table.foreach(mflua.pen[pen_key],print)
1083 --end
1084 --
1085 --res = res .. "%% cur_pen " .. tostring(MFbuiltin.cur_pen()) .."\n"
1086 --res = res .. string.format("%%%% current octant %s, octant number %s, offset %s\n",octant_dir[MFbuiltin.octant()],octant_number[octant],print_int(n))
1087 --res = res .. "pair offset[];\n"
1088 --for i,v in ipairs(offsets) do
1089 -- res = res .. string.format("offset%s:=%s;\n",i-1,v)
1090 --end
1091 --res = res .. "pair OffSet; OffSet:=offset"..print_int(n) ..";\n"
1092 --res = res .. "path p; p:= " .. print_two_true(x_coord(p),y_coord(p),octant) .. "\n"
1093 --cubic['p'] = print_two_true(x_coord(p),y_coord(p),octant)
1094 first_point = print_two_true(x_coord(p),y_coord(p),octant)
1095 first_point_offset = print_int(right_type(p))
1096 --
1097 --print(res);
1098 local end_loop_1 = false
1099 while end_loop_1 == false do
1100 local end_loop_2 = false
1101 while end_loop_2 == false do
1102 q=link(p);
1103 if right_type(p)==endpoint then
1104 end_loop_2=true
1105 else
1106 cubic['p'] = print_two_true(x_coord(p),y_coord(p),octant);
1107 cubic['control1'] = print_two_true(right_x(p),right_y(p),octant)
1108 cubic['control2'] = print_two_true(left_x(q),left_y(q),octant)
1109 cubic['q'] = print_two_true(x_coord(q),y_coord(q),octant)
1110 cubic['offset'] = print_int(right_type(p))
1111 cubic['segment'] = print_int(left_type(q)-1)
1112 cubics[#cubics+1] = cubic
1113 cubic = {}
1114 bezier['p'] = print_two_true(x_coord(p),y_coord(p),octant);
1115 bezier['control1'] = print_two_true(right_x(p),right_y(p),octant)
1116 bezier['control2'] = print_two_true(left_x(q),left_y(q),octant)
1117 bezier['q'] = print_two_true(x_coord(q),y_coord(q),octant)
1118 bezier['offset'] = print_int(right_type(p))
1119 bezier['segment'] = print_int(left_type(q)-1)
1120 beziers[#beziers+1] = bezier
1121 bezier = {}
1122 p=q
1123 end
1124 end
1125 -- not_found label
1126 if q==cur_spec then
1127 end_loop_1=true
1128 else
1129 p=q; octant=left_octant(p); -- print("% entering octant `");
1130 end
1131 -- We don't want all the octans of the cubic
1132 -- only the pieces of the current octant
1133 end_loop_1 = not(MFbuiltin.octant() == octant)
1134 end
1135 if #cubics == 0 then
1136 cubics['single_point'] = first_point
1137 cubics['single_point_offset'] = first_point_offset
1138 end
1139 -- done label:
1140 -- We can now use the results
1141 --
1142 -- No curves stored
1143 if #beziers == 0 then
1144 beziers['single_point'] = first_point
1145 beziers['single_point_offset'] = first_point_offset
1146 end
1147 if #beziers['offsets'] == 1 then
1148 offset_list[#offset_list+1] = {0,beziers['offsets'][1]}
1149 offset_list[#offset_list+1] = {1,beziers['offsets'][1]}
1150 else
1151 for i,v in ipairs(beziers['offsets']) do
1152 if odd(beziers['octant_number']) == true then
1153 offset_list[#offset_list+1] = {(i-1),v}
1154 else
1155 offset_list[#offset_list+1] = {#beziers['offsets']-i+1,v}
1156 end
1157 end
1158 end
1159 beziers['offset_list']=offset_list
1160 beziers['path_list'] = {}
1161 if #beziers == 0 then
1162 path_list['p'] = beziers['single_point']
1163 if odd(beziers['octant_number']) == true then
1164 path_list['offset'] = beziers['single_point_offset']
1165 else
1166 path_list['offset'] = #beziers['offsets']-beziers['single_point_offset']
1167 end
1168 beziers['path_list'][#beziers['path_list']+1] = path_list
1169 path_list={}
1170 else
1171 for i,v in ipairs(beziers) do
1172 bezier = v
1173 path_list['p'] = bezier['p']
1174 path_list['control1'] = bezier['control1']
1175 path_list['control2'] = bezier['control2']
1176 path_list['q'] = bezier['q']
1177 path_list['offset'] = bezier['offset']
1178 beziers['path_list'][#beziers['path_list']+1] = path_list
1179 path_list={}
1180 end
1181 end
1182 bezier_octant =mflua.do_add_to.bezier_octant
1183 bezier_octant[#bezier_octant+1] = beziers
1184 res = ""
1185 res = res .. "%% cur_pen " .. tostring(MFbuiltin.cur_pen()) .."\n"
1186 --res = res .. string.format("%%%% current octant %s, offset %s\n",octant_dir[MFbuiltin.octant()],print_int(n))
1187 res = res .. string.format("%%%% current octant %s\n",octant_dir[MFbuiltin.octant()])
1188 res = res .. "pair offset[];\n"
1189 if #cubics['offsets'] == 1 then
1190 res = res .."%% Only one offset\n"
1191 res = res ..string.format("offset%s:=%s;\n",0,cubics['offsets'][1])
1192 res = res ..string.format("offset%s:=%s;\n",1,cubics['offsets'][1])
1193 else
1194 for i,v in ipairs(cubics['offsets']) do
1195 if odd(cubics['octant_number']) == true then
1196 res = res .. string.format("offset%s:=%s;\n",(i-1),v)
1197 else
1198 res = res .. string.format("offset%s:=%s;\n",#cubics['offsets']-i+1,v)
1199 end
1200 end
1201 end
1202 res = res .. "%% cubics['octant_number'])=" .. cubics['octant_number'] .. "\n"
1203 res = res .. "%% #cubics=" .. #cubics .. "\n"
1204 if #cubics == 0 then
1205 res = res .. "path p; p:=" .. cubics['single_point'] .. ";\n"
1206 res = res .. "drawoptions(withcolor red withpen pencircle scaled 0.1pt);\n"
1207 temp1 = temp1 +1
1208 if odd(cubics['octant_number']) == true then
1209 res = res .. "draw p shifted offset" .. cubics['single_point_offset'] .. ";\n"
1210 res = res .. string.format("pickup pencircle scaled 0.2pt;drawdot(%s) shifted offset%s withcolor 0.75white;label(\"%s\",%s+(-0.5,-0.5)) shifted offset%s;\n",
1211 cubics['single_point'],cubics['single_point_offset'],temp1,cubics['single_point'],cubics['single_point_offset'])
1212 else
1213 res = res .. "draw p shifted offset" .. #cubics['offsets']-cubics['single_point_offset'] .. ";\n"
1214 res = res .. string.format("pickup pencircle scaled 0.2pt;drawdot(%s) shifted offset%s withcolor 0.75white;label(\"%s\",%s+(-0.5,-0.5)) shifted offset%s;\n",
1215 cubics['single_point'],#cubics['offsets']-cubics['single_point_offset'],temp1,cubics['single_point'],#cubics['offsets']-cubics['single_point_offset'])
1216 end
1217 end
1218 -- if #cubics == 0 then this for loop is never executed
1219 for i,v in ipairs(cubics) do
1220 cubic = v
1221 res = res .. "path p; p:= " .. cubic['p'] .."\n"
1222 res = res .. " .. controls " .. cubic['control1'] .." and " .. cubic['control2']
1223 res = res .. " .. " .. cubic['q'] .."\n ;\n"
1224 res = res .. 'label("'.. octant_dir[MFbuiltin.octant()] ..'"' .. ",0.5[" .. cubic['p'] .. "," .. cubic['q'] .."]) shifted offset" .. cubic['offset'] .. ";\n"
1225 res = res .. "drawoptions(withcolor black withpen pencircle scaled 0.2pt);\n"
1226 res = res .. "draw p shifted offset" .. cubic['offset'] .. ";\n"
1227 temp1 = temp1 +1
1228 res = res .. string.format("pickup pencircle scaled 0.2pt;drawdot(%s) shifted offset%s withcolor 0.75white;label(\"%s\",%s+(-0.5,-0.5)) shifted offset%s;\n",
1229 cubic['p'],cubic['offset'],temp1,cubic['p'],cubic['offset'])
1230 temp1 = temp1 +1
1231 res = res .. string.format("pickup pencircle scaled 0.2pt;drawdot(%s) shifted offset%s withcolor 0.75white;label(\"%s\",%s+(0.5,0.5)) shifted offset%s;\n",
1232 cubic['q'],cubic['offset'],temp1,cubic['q'],cubic['offset'])
1233
1234 end
1235 mflua.print_specification.temp1 = temp1
1236 res = res .. string.format("%%%%mflua.print_specification.temp1 = %s\n" ,mflua.print_specification.temp1)
1237 --print("\n%%POST START\n".. res .. "%%POST END\n")
1238 -- f = io.open("envelope.tex",'a')
1239 -- f = mflua.print_specification.outfile1
1240 -- f:write("\n%%POST START\n".. res .. "\n%%POST END\n")
1241 --f:close()
1242 return res
1243 end
1244 mflua.MF.print_specification = print_specification
1245
1246
1247
1248 local function PRE_offset_prep(c,h)
1249 PRINTDBG("PRE_offset_prep")
1250 -- local p = c
1251 -- print("\nBEZ TEST".. print_int(right_type(p)))
1252 -- print ("BEZ TEST".. print_two(x_coord(p),y_coord(p)))
1253 -- print ("BEZ TEST".. print_two(right_x(p),right_y(p)))
1254 -- p = link(p)
1255 -- print ("BEZ TEST".. print_two(left_x(p),left_y(p)))
1256 end
1257
1258 local function POST_offset_prep(c,h)
1259 PRINTDBG("POST_offset_prep")
1260 -- print("\nPOST print pen"); mflua.MF.print_pen(MFbuiltin.cur_pen(),"" , "")
1261 -- print("\nPOST print specification")
1262 --res = print_pen(MFbuiltin.cur_pen(),"" , "")
1263 --print(" PRINT PEN " .. res )
1264 mflua.MF.print_specification(c,h)
1265 end
1266
1267
1268 mflua.do_add_to = mflua.do_add_to or {}
1269
1270 local function _get_cycle(h)
1271 local p,q
1272 local res = ''
1273 local done
1274 local done1
1275 local f
1276 local cycle = {}
1277 done = false
1278 done1 = false
1279 p = h
1280 while not done do
1281 q = link(p)
1282 if (p==0) or (q==0) then
1283 return '???'
1284 end
1285 cycle[#cycle+1] = {tonumber(print_scaled(x_coord(p))), tonumber(print_scaled(y_coord(p)))} -- p
1286 --res = res .. print_two(x_coord(p),y_coord(p)); -- print("res=",res)
1287 if right_type(p) == endpoint then
1288 if left_type(p)== open then return "{open?}" end -- {can't happen}
1289 if (left_type(q) ~= endpoint) or (q ~= h) then q=null end -- {force an error}
1290 done1 = true -- goto done1;
1291 elseif right_type(p) == explicit then
1292 -- begin "@<Print control points between |p| and |q|, then |goto done1|@>"
1293 --res = res .. "..controls " .. print_two(right_x(p),right_y(p)) .. " and ";
1294 cycle[#cycle+1] = {tonumber(print_scaled(right_x(p))), tonumber(print_scaled(right_y(p)))} -- c1
1295 if left_type(q) ~= explicit then return "??" -- {can't happen}
1296 else
1297 --res = res .. print_two(left_x(q),left_y(q));
1298 cycle[#cycle+1] = {tonumber(print_scaled(left_x(q))), tonumber(print_scaled(left_y(q)))} -- c2
1299 done1 = true -- goto done1;
1300 end
1301 -- end "@<Print control points between |p| and |q|, then |goto done1|@>"
1302 elseif right_type(p) == open then
1303 -- begin "@<Print information for a curve that begins |open|@>"
1304 if (left_type(p) ~= explicit) and (left_type(p)~=open) then
1305 return "{open?}" -- {can't happen}
1306 end
1307 -- end "@<Print information for a curve that begins |open|@>"
1308 elseif (right_type(p) == curl) or (right_type(p) == given) then
1309 -- @ A curl of 1 is shown explicitly, so that the user sees clearly that
1310 -- \MF's default curl is present.
1311 -- begin @<Print information for a curve that begins |curl|...@>=
1312 if left_type(p)==open then res = res .. "??" end -- {can't happen}
1313 if right_type(p)==curl then
1314 res = res .. "{curl ".. print_scaled(right_curl(p))
1315 else n_sin_cos(right_given(p)); res = res .."{"
1316 res = res .. print_scaled(n_cos) .. "," .. print_scaled(n_sin)
1317 end
1318 res = res .."}"
1319 -- end @<Print information for a curve that begins |curl|...@>=
1320 else return "???" -- {can't happen}
1321 end
1322 if not done1 then -- mimic label done 1
1323 if left_type(q)~=explicit then return "..control?" -- {can't happen}
1324 else if (right_tension(p) ~= unity) or (left_tension(q) ~= unity) then
1325 -- begin "@<Print tension between |p| and |q|@>;"
1326 res = res .. "..tension "
1327 if right_tension(p)<0 then res = res .. "atleast" end
1328 res = res .. print_scaled(math.abs(right_tension(p)))
1329 if right_tension(p) ~= left_tension(q) then
1330 res = res .. " and "
1331 if left_tension(q)<0 then res = res .. "atleast" end
1332 res = res .. print_scaled(math.abs(left_tension(q)))
1333 end
1334 end -- "@<Print tension between |p| and |q|@>;"
1335 end
1336 end --- LABEL: done1
1337 -- begin @<Print two dots...@>=
1338 p = q
1339 --res = res .. " .."
1340 if left_type(p)==given then
1341 n_sin_cos(left_given(p)); res = res .. "{"
1342 res = res .. print_scaled(n_cos); res = res .. ",";
1343 res = res .. print_scaled(n_sin); res = res .. "}";
1344 else if left_type(p)==curl then
1345 res = res .. "{curl "; res = res .. print_scaled(left_curl(p)) .. "}";
1346 end;
1347 end
1348 -- end @<Print two dots...@>=
1349 -- end "@<Print information for adjacent knots |p| and |q|@>"
1350 if p == h then done =true end
1351 end
1352 if left_type(h) ~= endpoint then
1353 res = res .. "cycle"
1354 end
1355 -- do something with res --
1356 return res ,cycle
1357 end
1358 mflua.do_add_to._get_cycle = _get_cycle
1359
1360
1361 -- @p procedure print_spec(@!s:str_number);
1362 -- label not_found,done;
1363 -- var @!p,@!q:pointer; {for list traversal}
1364 -- @!octant:small_number; {the current octant code}
1365 -- begin print_diagnostic("Cycle spec",s,true);
1366 -- @.Cycle spec at line...@>
1367 -- p:=cur_spec; octant:=left_octant(p); print_ln;
1368 -- print_two_true(x_coord(cur_spec),y_coord(cur_spec));
1369 -- print(" % beginning in octant `");
1370 -- loop@+ begin print(octant_dir[octant]); print_char("'");
1371 -- loop@+ begin q:=link(p);
1372 -- if right_type(p)=endpoint then goto not_found;
1373 -- @<Print the cubic between |p| and |q|@>;
1374 -- p:=q;
1375 -- end;
1376 -- not_found: if q=cur_spec then goto done;
1377 -- p:=q; octant:=left_octant(p); print_nl("% entering octant `");
1378 -- end;
1379 -- @.entering the nth octant@>
1380 -- done: print_nl(" & cycle"); end_diagnostic(true);
1381 -- end;
1382 local function _print_spec(cur_spec)
1383 --print("\n.....Hello world from _print_spec!.....")
1384 local p,q
1385 local octant
1386 --local res = ''
1387 local knot = {}
1388 local knots = {}
1389 -- local res = {}
1390 local endloop1 = false
1391 local endloop2 = false
1392
1393 p=cur_spec; octant=left_octant(p); --print()
1394 -- res = res .. print_two_true(x_coord(cur_spec),y_coord(cur_spec),octant)
1395 knot[#knot+1] = print_two_true(x_coord(cur_spec),y_coord(cur_spec),octant)
1396 while (endloop1 == false) do
1397 -- print('%%' .. octant_dir[octant])
1398 endloop2 = false
1399 while (endloop2 == false) do
1400 q = link(p)
1401 if right_type(p)==endpoint then
1402 endloop2 = true -- goto not_found;
1403 else
1404 -- print(' @<Print the cubic between |p| and |q|@>;')
1405 -- c1
1406 knot[#knot+1] = print_two_true(right_x(p),right_y(p),octant)
1407 -- c2
1408 knot[#knot+1] = print_two_true(left_x(q),left_y(q),octant)
1409 -- q
1410 knot[#knot+1] = print_two_true(x_coord(q),y_coord(q),octant)
1411 -- segment
1412 knot[#knot+1] = print_int(left_type(q)-1)
1413 knots[#knots+1] = knot
1414 knot = {}
1415 -- res = res .." ..controls "
1416 -- res = res .. print_two_true(right_x(p),right_y(p),octant)
1417 -- res = res .." and "
1418 -- res = res ..print_two_true(left_x(q),left_y(q),octant)
1419 -- res = res .. "\n .."
1420 -- res = res .. print_two_true(x_coord(q),y_coord(q),octant)
1421 -- res = res .." % segment " ..print_int(left_type(q)-1) .. "\n";
1422 p=q;
1423 knot[#knot+1] = print_two_true(x_coord(p),y_coord(p),octant)
1424 end
1425 end -- endloop2
1426 -- not_found
1427 if q == cur_spec then
1428 endloop1 = true
1429 else
1430 p=q; octant=left_octant(p) -- print("% entering octant `");
1431 end
1432 end -- endloop1
1433 --done:
1434 -- print(" & cycle") ; end_diagnostic(true);
1435 -- print("%BEZ TEST\ndraw "..res .. ";\n")
1436 -- table.foreach(knots,function (k) table.foreach(knots[k],print) end)
1437 return knots
1438 end
1439 mflua.do_add_to._print_spec = _print_spec
1440
1441
1442 local function _store_current_envelope()
1443 local bezier_octant_envelope = mflua.do_add_to.bezier_octant_envelope
1444 local bezier_octant = mflua.do_add_to.bezier_octant
1445 if (#bezier_octant_envelope == 0) then
1446 local _t = {}
1447 for i,v in ipairs(bezier_octant) do _t[i] = v end
1448 bezier_octant_envelope[1] = _t
1449 else
1450 local _cnt=0
1451 for i,v in ipairs(bezier_octant_envelope) do _cnt=_cnt+#v end
1452 local _t = {}
1453 for i,v in ipairs(bezier_octant) do if i>_cnt then _t[#_t+1] = v end end
1454 bezier_octant_envelope[#bezier_octant_envelope+1] = _t
1455 end
1456 mflua.do_add_to.bezier_octant_envelope = bezier_octant_envelope
1457 return 0
1458 end
1459 mflua.do_add_to._store_current_envelope = _store_current_envelope
1460
1461
1462 local function _postprocessing()
1463 local bezier_octant
1464 local beziers,offsets
1465
1466 local path_list
1467 local prev_point
1468 local path_cnt
1469 local res = "%% postprocessing envelope\n"
1470 local f
1471 local chartable = mflua.chartable
1472 local index
1473 local char
1474
1475 index = (0+print_int(MFbuiltin.char_code())) + (0+print_int(MFbuiltin.char_ext()))*256
1476 --print("CHAR " .. index)
1477 --print("%% postprocessing envelope "..index.. ' ' .. #chartable)
1478
1479 res = res .. "path p[];\n"
1480
1481 -- The last part of envelope added
1482 bezier_octant = mflua.do_add_to.bezier_octant_envelope[#mflua.do_add_to.bezier_octant_envelope]
1483
1484 path_cnt = 1
1485 for i,v in ipairs(bezier_octant) do
1486 beziers = v
1487 offsets = beziers['offsets']
1488 path_list = beziers['path_list']
1489 local offset_list = beziers['offset_list']
1490 for i,path in ipairs(path_list) do
1491 local shifted
1492 local p,c1,c2,q,offset =
1493 path['p'],path['control1'],path['control2'],path['q'],path['offset']
1494 for i,v in ipairs(offset_list) do
1495 if v[1] == (0+offset) then
1496 shifted = v[2]
1497 break
1498 end
1499 end
1500 if (q == nil) then
1501 res = res .. string.format("p%d:=(%s) shifted %s;%% shifted 1\n",
1502 path_cnt,p,shifted)
1503 else
1504 res = res .. string.format("p%d:=(%s .. controls %s and %s .. %s) shifted %s;%% shifted 2\n",
1505 path_cnt,p,c1,c2,q,shifted)
1506 end
1507 path_cnt = path_cnt +1
1508 end
1509 end
1510 res = res .. "%% path_cnt=" .. path_cnt .. " char_code=" .. print_int(MFbuiltin.char_code()) .. " char_ext=" .. print_int(MFbuiltin.char_ext())
1511 res = res .. " char_wd=" .. print_scaled(MFbuiltin.char_wd())
1512 res = res .. " char_ht=" .. print_scaled(MFbuiltin.char_ht())
1513 res = res .. " char_dp=" .. print_scaled(MFbuiltin.char_dp())
1514 res = res .. " char_ic=" .. print_scaled(MFbuiltin.char_ic())
1515 res = res .. " \n"
1516
1517 res = res .. "drawoptions(withcolor (" .. math.random().."," .. math.random()..",".. math.random().. ") withpen pencircle scaled 0.4pt);\n"
1518 res = res .. "draw p1"
1519 for i=2,path_cnt-1 do
1520 res = res .. string.format(" -- p%d",i)
1521 end
1522 res = res .. " --cycle;\n"
1523
1524 index = (0+print_int(MFbuiltin.char_code())) + (0+print_int(MFbuiltin.char_ext()))*256
1525 char = chartable[index] or {}
1526 char['char_wd'] = print_scaled(MFbuiltin.char_wd())
1527 char['char_ht'] = print_scaled(MFbuiltin.char_ht())
1528 char['char_dp'] = print_scaled(MFbuiltin.char_dp())
1529 char['char_ic'] = print_scaled(MFbuiltin.char_ic())
1530 char['envelope'] = char['envelope'] or {}
1531 char['envelope'][#char['envelope']+1] = bezier_octant
1532 char['res'] = char['res'] or ""
1533 char['res'] = char['res'] .. res
1534 char['index'] = index
1535 chartable[index] = char
1536 end
1537 mflua.do_add_to._postprocessing = _postprocessing
1538
1539
1540 local function _store_current_contour()
1541 local bezier_octant_contour = mflua.do_add_to.bezier_octant_contour
1542 local bezier_octant_I = mflua.do_add_to.bezier_octant_I
1543 if (#bezier_octant_contour == 0) then
1544 local _t = {}
1545 for i,v in ipairs(bezier_octant_I) do _t[i] = v end
1546 bezier_octant_contour[1] = _t;
1547 else
1548 local _cnt=0
1549 for i,v in ipairs(bezier_octant_contour) do _cnt=_cnt+#v end
1550 local _t = {}
1551 for i,v in ipairs(bezier_octant_I) do if i>_cnt then _t[#_t+1] = v; end end
1552 bezier_octant_contour[#bezier_octant_contour+1] = _t
1553 end
1554 mflua.do_add_to.bezier_octant_contour = bezier_octant_contour
1555 return 0
1556 end
1557 mflua.do_add_to._store_current_contour = _store_current_contour
1558
1559
1560 local function _postprocessing_contour()
1561 local bezier_octant_contour,contour,path_list
1562 local chartable = mflua.chartable
1563 local index
1564 local char
1565 local res = ""
1566 index = (0+print_int(MFbuiltin.char_code())) + (0+print_int(MFbuiltin.char_ext()))*256
1567 res = res .. "%% postprocessing contour for " .. index ..";\n"
1568 res = res .. "path p[];\n"
1569 --print("\n_postprocessing_contour CHAR " .. index)
1570 bezier_octant_contour = mflua.do_add_to.bezier_octant_contour[#mflua.do_add_to.bezier_octant_contour]
1571
1572 path_cnt = 1
1573 for i,v in ipairs(bezier_octant_contour) do
1574 contour = v
1575 path_list = contour['path_list']
1576 for i,path in ipairs(path_list) do
1577 local p,c1,c2,q = path['p'],path['control1'],path['control2'],path['q']
1578 if (q == nil) then
1579 res = res .. string.format("p%d:=(%s);\n", path_cnt,p)
1580 else
1581 res = res .. string.format("p%d:=(%s .. controls %s and %s .. %s);\n",path_cnt,p,c1,c2,q)
1582 end
1583 path_cnt = path_cnt +1
1584 end
1585 end
1586 if path_cnt > 1 then
1587 res = res .. "drawoptions(withcolor black withpen pencircle scaled 0.3pt);\n"
1588 res = res .. "draw p1"
1589 for i=2,path_cnt-1 do
1590 res = res .. string.format(" -- p%d",i)
1591 end
1592 res = res .. " --cycle ;\n"
1593 end
1594
1595
1596 index = (0+print_int(MFbuiltin.char_code())) + (0+print_int(MFbuiltin.char_ext()))*256
1597 --print("BEZ index="..index)
1598 char = chartable[index] or {}
1599 char['char_wd'] = print_scaled(MFbuiltin.char_wd())
1600 char['char_ht'] = print_scaled(MFbuiltin.char_ht())
1601 char['char_dp'] = print_scaled(MFbuiltin.char_dp())
1602 char['char_ic'] = print_scaled(MFbuiltin.char_ic())
1603 char['contour'] = char['contour'] or {}
1604 char['contour'][#char['contour']+1] = bezier_octant_contour
1605 char['res'] = char['res'] or ""
1606 char['res'] = char['res'] .. res ;
1607 char['index'] = index
1608 chartable[index] = char
1609 return 0
1610 end
1611 mflua.do_add_to._postprocessing_contour = _postprocessing_contour
1612
1613 -- local function _circular_list_geti(l,i)
1614 -- local size = #l
1615 -- if size==0 then
1616 -- return nil
1617 -- end
1618 -- return l[1+(i-1)%size]
1619 -- end
1620
1621
1622 local function _store_current_cycle(hs)
1623 local res, current_cycle
1624 res, current_cycle = mflua.do_add_to._get_cycle(hs)
1625 if res=='cycle' then
1626 local index = (0+print_int(MFbuiltin.char_code())) + (0+print_int(MFbuiltin.char_ext()))*256
1627 local char = mflua.chartable[index] or {}
1628 char['cycle'] = char['cycle'] or {}
1629 char['cycle'][#char['cycle']+1] = current_cycle
1630
1631 mflua.chartable[index] = char
1632 else
1633 print("Error:"..res)
1634 end
1635 end
1636 mflua.do_add_to._store_current_cycle = _store_current_cycle
1637
1638
1639 local function PRE_make_spec_rhs(rhs)
1640 PRINTDBG("PRE_make_spec_rhs")
1641 mflua.do_add_to._store_current_cycle(rhs)
1642 end
1643
1644 local function POST_make_spec_rhs(rhs)
1645 PRINTDBG("POST_make_spec_rhs")
1646 --mflua.do_add_to._store_current_cycle(rhs)
1647 --print("post rhs MFbuiltin.turning_number=",MFbuiltin.turning_number() ) ;
1648 end
1649
1650
1651 local function PRE_make_spec_lhs(lhs)
1652 PRINTDBG("PRE_make_spec_lhs")
1653 mflua.do_add_to._store_current_cycle(lhs)
1654 end
1655
1656 local function POST_make_spec_lhs(lhs)
1657 PRINTDBG("PRE_make_spec_lhs")
1658 --mflua.do_add_to._store_current_cycle(lhs)
1659 --print("post lhs MFbuiltin.turning_number=",MFbuiltin.turning_number() ) ;
1660 end
1661
1662 local function PRE_fill_envelope_rhs(rhs)
1663 PRINTDBG("PRE_fill_envelope_rhs")
1664 local knots ,knots_list
1665 local index,char
1666 local chartable = mflua.chartable
1667 knots = mflua.do_add_to._print_spec(rhs)
1668 index = (0+print_int(MFbuiltin.char_code())) + (0+print_int(MFbuiltin.char_ext()))*256
1669 char = chartable[index] or {}
1670 knots_list = char['knots'] or {}
1671 knots_list[#knots_list+1] = knots
1672 char['knots'] = knots_list
1673 chartable[index] = char
1674 end
1675
1676 local function POST_fill_envelope_rhs(rhs)
1677 PRINTDBG("POST_fill_envelope_rhs")
1678 mflua.do_add_to._store_current_envelope()
1679 mflua.do_add_to._postprocessing()
1680 end
1681
1682 local function PRE_fill_envelope_lhs(lhs)
1683 PRINTDBG("PRE_fill_envelope_lhs")
1684 end
1685
1686 local function POST_fill_envelope_lhs(lhs)
1687 PRINTDBG("POST_fill_envelope_lhs")
1688 mflua.do_add_to._store_current_envelope()
1689 mflua.do_add_to._postprocessing()
1690 end
1691
1692 local function PRE_fill_spec_rhs(rhs)
1693 PRINTDBG("PRE_fill_spec_rhs")
1694 --print_specification_contour(rhs)
1695 end
1696
1697 local function POST_fill_spec_rhs(rhs)
1698 PRINTDBG("POST_fill_spec_rhs")
1699 mflua.do_add_to._store_current_contour()
1700 mflua.do_add_to._postprocessing_contour()
1701 end
1702
1703 local function PRE_fill_spec_lhs(lhs)
1704 PRINTDBG("PRE_fill_spec_lhs")
1705 --print_specification_contour(lhs)
1706 end
1707
1708 local function POST_fill_spec_lhs(lhs)
1709 PRINTDBG("POST_fill_spec_lhs")
1710 mflua.do_add_to._store_current_contour()
1711 mflua.do_add_to._postprocessing_contour()
1712 end
1713
1714
1715 --------------------------------------------------------------------------------
1716 --
1717 -- fill_spec
1718 --
1719 --------------------------------------------------------------------------------
1720
1721 mflua.fill_spec = mflua.fill_spec or {}
1722
1723 -- @ Here's a routine that prints a cycle spec in symbolic form, so that it
1724 -- is possible to see what subdivision has been made. The point coordinates
1725 -- are converted back from \MF's internal ``rotated'' form to the external
1726 -- ``true'' form. The global variable~|cur_spec| should point to a knot just
1727 -- after the beginning of an octant boundary, i.e., such that
1728 -- |left_type(cur_spec)=endpoint|.
1729 local function print_specification_contour(h)
1730 local p,q,n,nh
1731 local octant
1732 local cur_spec
1733 local res = ""
1734 local f
1735 local first_point, first_point_offset
1736 local path_cnt
1737 local bezier_contour,beziers_contour ={},{}
1738 local offset_list = {}
1739 local path_list ={}
1740 local bezier_octant_I
1741 cur_spec=h
1742 p=cur_spec
1743 octant = left_octant(p)
1744 beziers_contour['octant_number'] = octant_number[octant]
1745 first_point = print_two_true(x_coord(p),y_coord(p),octant)
1746 first_point_offset = print_int(right_type(p))
1747 local end_loop_1 = false
1748 while end_loop_1 == false do
1749 local end_loop_2 = false
1750 while end_loop_2 == false do
1751 q=link(p);
1752 if right_type(p)==endpoint then
1753 end_loop_2=true
1754 else
1755 bezier_contour['p'] = print_two_true(x_coord(p),y_coord(p),octant);
1756 bezier_contour['control1'] = print_two_true(right_x(p),right_y(p),octant)
1757 bezier_contour['control2'] = print_two_true(left_x(q),left_y(q),octant)
1758 bezier_contour['q'] = print_two_true(x_coord(q),y_coord(q),octant)
1759 beziers_contour[#beziers_contour+1] = bezier_contour
1760 bezier_contour = {}
1761 p=q
1762 end
1763 end
1764 -- not_found label
1765 if q==cur_spec then
1766 end_loop_1=true
1767 else
1768 p=q; octant=left_octant(p); -- print("% entering octant `");
1769 end
1770 -- We don't want all the octans of the cycle
1771 -- only the pieces of the current octant
1772 end_loop_1 = not(MFbuiltin.octant() == octant)
1773 end
1774 -- done label:
1775 -- We can now use the results
1776 -- No curves stored
1777 if #beziers_contour == 0 then
1778 beziers_contour['single_point'] = first_point
1779 end
1780 beziers_contour['path_list'] = {}
1781 if #beziers_contour == 0 then
1782 path_list['p'] = beziers_contour['single_point']
1783 beziers_contour['path_list'][#beziers_contour['path_list']+1] = path_list
1784 path_list={}
1785 else
1786 for i,v in ipairs(beziers_contour) do
1787 bezier_contour = v
1788 path_list['p'] = bezier_contour['p']
1789 path_list['control1'] = bezier_contour['control1']
1790 path_list['control2'] = bezier_contour['control2']
1791 path_list['q'] = bezier_contour['q']
1792 beziers_contour['path_list'][#beziers_contour['path_list']+1] = path_list
1793 path_list={}
1794 end
1795 end
1796 bezier_octant_I =mflua.do_add_to.bezier_octant_I
1797 bezier_octant_I[#bezier_octant_I+1] = beziers_contour
1798 return 0
1799 end
1800 mflua.MF.print_specification_contour = print_specification_contour
1801
1802
1803 local function PRE_move_to_edges(p)
1804 PRINTDBG("PRE_move_to_edges")
1805 mflua.MF.print_specification_contour(p)
1806 end
1807
1808
1809 local function POST_move_to_edges(p)
1810 PRINTDBG("POST_move_to_edges")
1811 end
1812
1813
1814 --
1815 -- scan_direction
1816 --
1817
1818 mflua.scan_direction = mflua.scan_direction or {}
1819
1820 local function _print_path(h,s,nuline)
1821 local p,q
1822 local res
1823 local done
1824 local done1
1825 local f
1826 done = false
1827 done1 = false
1828 p = h
1829 res = ''
1830 while not done do
1831 q = link(p)
1832 if (p==0) or (q==0) then
1833 res = "???"
1834 -- do something with res --
1835 return 0
1836 end
1837 res = res .. print_two(x_coord(p),y_coord(p)); -- print("res=",res)
1838 if right_type(p) == endpoint then
1839 if left_type(p)== open then print("{open?}") end -- {can't happen}
1840 if (left_type(q) ~= endpoint) or (q ~= h) then q=null end -- {force an error}
1841 done1 = true -- goto done1;
1842 elseif right_type(p) == explicit then
1843 -- begin "@<Print control points between |p| and |q|, then |goto done1|@>"
1844 res = res .. "..controls " .. print_two(right_x(p),right_y(p)) .. " and ";
1845 if left_type(q) ~= explicit then print("??") -- {can't happen}
1846 else res = res .. print_two(left_x(q),left_y(q));
1847 done1 = true -- goto done1;
1848 end
1849 -- end "@<Print control points between |p| and |q|, then |goto done1|@>"
1850 elseif right_type(p) == open then
1851 -- begin "@<Print information for a curve that begins |open|@>"
1852 if (left_type(p) ~= explicit) and (left_type(p)~=open) then
1853 res = res .. "{open?}" -- {can't happen}
1854 end
1855 -- end "@<Print information for a curve that begins |open|@>"
1856 elseif (right_type(p) == curl) or (right_type(p) == given) then
1857 -- @ A curl of 1 is shown explicitly, so that the user sees clearly that
1858 -- \MF's default curl is present.
1859 -- begin @<Print information for a curve that begins |curl|...@>=
1860 if left_type(p)==open then res = res .. "??" end -- {can't happen}
1861 if right_type(p)==curl then
1862 res = res .. "{curl ".. print_scaled(right_curl(p))
1863 else n_sin_cos(right_given(p)); res = res .."{"
1864 res = res .. print_scaled(n_cos) .. "," .. print_scaled(n_sin)
1865 end
1866 res = res .."}"
1867 -- end @<Print information for a curve that begins |curl|...@>=
1868 else res = res .. "???" -- {can't happen}
1869 end
1870 if not done1 then -- mimic label done 1
1871 if left_type(q)~=explicit then res = res .. "..control?" -- {can't happen}
1872 else if (right_tension(p) ~= unity) or (left_tension(q) ~= unity) then
1873 -- begin "@<Print tension between |p| and |q|@>;"
1874 res = res .. "..tension "
1875 if right_tension(p)<0 then res = res .. "atleast" end
1876 res = res .. print_scaled(math.abs(right_tension(p)))
1877 if right_tension(p) ~= left_tension(q) then
1878 res = res .. " and "
1879 if left_tension(q)<0 then res = res .. "atleast" end
1880 res = res .. print_scaled(math.abs(left_tension(q)))
1881 end
1882 end -- "@<Print tension between |p| and |q|@>;"
1883 end
1884 end --- LABEL: done1
1885 -- begin @<Print two dots...@>=
1886 p = q
1887 res = res .. " .."
1888 if left_type(p)==given then
1889 n_sin_cos(left_given(p)); res = res .. "{"
1890 res = res .. print_scaled(n_cos); res = res .. ",";
1891 res = res .. print_scaled(n_sin); res = res .. "}";
1892 else if left_type(p)==curl then
1893 res = res .. "{curl "; res = res .. print_scaled(left_curl(p)) .. "}";
1894 end;
1895 end
1896 -- end @<Print two dots...@>=
1897 -- end "@<Print information for adjacent knots |p| and |q|@>"
1898 if p == h then done =true end
1899 end
1900 if left_type(h) ~= endpoint then
1901 res = res .. "cycle"
1902 else
1903 res = res
1904 end
1905 -- do something with res --
1906 return res
1907 --res = "drawoptions(withcolor black withpen pencircle scaled 1pt);\n" .. "draw " .. res .. " ;\n"
1908 --print(res)
1909 -- local index = (0+print_int(MFbuiltin.char_code())) + (0+print_int(MFbuiltin.char_ext()))*256
1910 -- local char = mflua.chartable[index] or {}
1911 -- char['char_wd'] = print_scaled(MFbuiltin.char_wd())
1912 -- char['char_ht'] = print_scaled(MFbuiltin.char_ht())
1913 -- char['char_dp'] = print_scaled(MFbuiltin.char_dp())
1914 -- char['char_ic'] = print_scaled(MFbuiltin.char_ic())
1915 -- char['res'] = char['res'] or ""
1916 -- char['res'] = char['res'] .. res
1917 -- mflua.chartable[index] = char
1918 -- return 0
1919 end
1920 mflua.scan_direction.print_path = _print_path
1921
1922 local function PRE_make_choices(p)
1923 PRINTDBG("PRE_make_choices")
1924 -- _print_path(p,"PRE make choice",false)
1925 end
1926
1927 local function POST_make_choices(p)
1928 PRINTDBG("POST_make_choices")
1929 --local res = ''
1930 --res = _print_path(p,"POST make choice",false)
1931 --print(res)
1932 end
1933
1934 local function print_retrograde_line(x0,y0,cur_x,cur_y)
1935 PRINTDBG("print_retrograde_line")
1936 local chartable = mflua.chartable
1937 local index = (0+print_int(MFbuiltin.char_code())) + (0+print_int(MFbuiltin.char_ext()))*256
1938 local char = chartable[index] or {}
1939 local tab = char['retrograde_line'] or {}
1940 tab[#tab+1] = {print_two(x0,y0),print_two(cur_x,cur_y)}
1941 char['retrograde_line'] = tab
1942 --print("%%Retrograde line")
1943 --print("drawoptions(withcolor (0,0.6,0) withpen pencircle scaled 0.09pt);")
1944 --print("draw ".. print_two(x0,y0) .. " -- " .. print_two(cur_x,cur_y) ..";")
1945 end
1946
1947
1948 local function PRE_make_ellipse(major_axis,minor_axis,theta,tx,ty,q)
1949 PRINTDBG("PRE_make_ellipse")
1950 --print("major_axis,minor_axis,theta,tx,ty,q=",major_axis,minor_axis,theta,tx,ty,q)
1951 end
1952
1953 local function POST_make_ellipse(major_axis,minor_axis,theta,tx,ty,q)
1954 PRINTDBG("POST_make_ellipse")
1955 --print("major_axis,minor_axis,theta,tx,ty,q=",print_two(major_axis,minor_axis),theta*(2^-20),print_two(tx,ty),print_two(x_coord(q),y_coord(q)))
1956 local flag=true
1957 local p=q
1958 local res = ''
1959 local xy
1960 local i = 0
1961 while flag do
1962 i=i+1
1963 res = res ..print_two(x_coord(p),y_coord(p))
1964 p=link(p)
1965 if p==q then flag=false end
1966 end
1967 mflua.pen[res] = {print_two(major_axis,minor_axis),
1968 theta*(2^-20),print_two(tx,ty)}
1969
1970 end
1971
1972
1973
1974 local function print_transition_line_from(x,y)
1975 PRINTDBG("print_transition_line_from")
1976 local octant = MFbuiltin.octant()
1977 --local res = ""
1978 local index = (0+print_int(MFbuiltin.char_code())) + (0+print_int(MFbuiltin.char_ext()))*256
1979 local chartable = mflua.chartable
1980 local char = chartable[index] or {}
1981 local p = print_two_true(x,y,octant)
1982 local c1 = p
1983 char['transition_lines'] = char['transition_lines'] or {}
1984 char['transition_lines'][#char['transition_lines']+1]={p,p}
1985 return 0
1986 end
1987
1988
1989 local function print_transition_line_to(x,y)
1990 PRINTDBG("print_transition_line_to")
1991 local octant = MFbuiltin.octant()
1992 local index = (0+print_int(MFbuiltin.char_code())) + (0+print_int(MFbuiltin.char_ext()))*256
1993 local chartable = mflua.chartable
1994 local char = chartable[index] or {}
1995 local q = print_two_true(x,y,octant)
1996 local c2 = q
1997 char['transition_lines_set'] = char['transition_lines_set'] or {}
1998 char['transition_lines'] = char['transition_lines'] or {}
1999 local _t = char['transition_lines'][#char['transition_lines']]
2000 local p = _t[1]
2001 --
2002 -- avoid multiple lines
2003 --
2004 --print("BEZ char['transition_lines_set'][p..q]=",char['transition_lines_set'][p..q])
2005 if char['transition_lines_set'][p..q]==true or char['transition_lines_set'][q..p]==true then
2006 char['transition_lines'][#char['transition_lines']]=nil
2007 return 0
2008 end
2009 char['transition_lines_set'][p..q]=true
2010 char['transition_lines_set'][q..p]=true
2011 --
2012 -- remove curves that degenerate into points
2013 --
2014 if p~=q then
2015 _t[#_t+1] = c2
2016 _t[#_t+1] = q
2017 _t[#_t+1] = '(0,0)'
2018 _t[#_t+1] = 'transition_line'
2019 else
2020 char['transition_lines'][#char['transition_lines']]=nil
2021 end
2022 return 0
2023 end
2024
2025
2026 local function end_program()
2027 PRINTDBG("end_program")
2028 local f = kpse.find_file('end_program.lua','lua')
2029 if f==nil then
2030 print("Warning: end_program.lua not found")
2031 return
2032 end
2033 local func,errmsg = loadfile(f)
2034 if not(func) then
2035 print(errmsg)
2036 os.exit(1)
2037 end
2038 status, msg = pcall(func)
2039 if not(status) then
2040 print(msg)
2041 os.exit(status)
2042 end
2043 end
2044
2045
2046 --
2047 -- Add local function to mflua
2048 --
2049
2050 mflua.begin_program = begin_program
2051 mflua.PRE_start_of_MF = PRE_start_of_MF
2052 mflua.PRE_main_control = PRE_main_control
2053 mflua.POST_main_control = POST_main_control
2054 mflua.mflua_initialize = mflua_initialize
2055 mflua.POST_final_cleanup = POST_final_cleanup
2056 mflua.printpath = printpath
2057 mflua.printedges = printedges
2058 mflua.PRE_offset_prep = PRE_offset_prep
2059 mflua.POST_offset_prep = POST_offset_prep
2060
2061 mflua.PRE_make_spec_rhs = PRE_make_spec_rhs
2062 mflua.POST_make_spec_rhs = POST_make_spec_rhs
2063 mflua.PRE_make_spec_lhs = PRE_make_spec_lhs
2064 mflua.POST_make_spec_lhs = POST_make_spec_lhs
2065 mflua.PRE_fill_envelope_rhs = PRE_fill_envelope_rhs
2066 mflua.POST_fill_envelope_rhs = POST_fill_envelope_rhs
2067 mflua.PRE_fill_envelope_lhs = PRE_fill_envelope_lhs
2068 mflua.POST_fill_envelope_lhs = POST_fill_envelope_lhs
2069 mflua.PRE_fill_spec_rhs = PRE_fill_spec_rhs
2070 mflua.POST_fill_spec_rhs = POST_fill_spec_rhs
2071 mflua.PRE_fill_spec_lhs = PRE_fill_spec_lhs
2072 mflua.POST_fill_spec_lhs = POST_fill_spec_lhs
2073
2074 mflua.PRE_move_to_edges = PRE_move_to_edges
2075 mflua.POST_move_to_edges = POST_move_to_edges
2076
2077 mflua.PRE_make_choices = PRE_make_choices
2078 mflua.POST_make_choices = POST_make_choices
2079
2080 mflua.print_retrograde_line = print_retrograde_line
2081
2082 mflua.PRE_make_ellipse = PRE_make_ellipse
2083 mflua.POST_make_ellipse = POST_make_ellipse
2084
2085 mflua.print_transition_line_from = print_transition_line_from
2086 mflua.print_transition_line_to = print_transition_line_to
2087
2088 mflua.end_program = end_program
2089
2090
2091 --------------------------------------------------------------------------------
2092 --
2093 -- Other setups, mostly depend on old routines
2094 --
2095 --------------------------------------------------------------------------------
2096
2097 mflua.max_recursion_level = 32
2098
2099
2100 mflua.bit = 7 -- should be 4
2101
2102 mflua.pi = 2*math.atan2(1,0)
2103 mflua.print_specification = mflua.print_specification or {}
2104 mflua.print_specification.temp1 = 0
2105 mflua.print_specification.p = ""
2106 mflua.print_specification.q = ""
2107 mflua.threshold_path_removed = 4 -- how many path we can safely remove
2108 mflua.threshold_extra_step = 2 -- add values/mflua.threshold_extra_step time values
2109 mflua.threshold_small_path_check_point = 3 -- check 3 pixels for horiz/vert. paths
2110 mflua.threshold_small_pen_path = 0.001 -- _fix_wrong_pending_path
2111 mflua.threshold_fix = 1 -- _fix_wrong_pending_path
2112 mflua.threshold = 1 -- _remove_small_path
2113 mflua.threshold_degree = 2 -- _remove_small_path
2114 mflua.threshold_degree_1 = 90 -- _remove_small_path
2115 mflua.threshold_degree_2 = 270 -- _remove_small_path
2116 mflua.threshold_small_curve = 2 -- _remove_reduntant_curves
2117 mflua.threshold_normal_curve = 4 -- _remove_reduntant_curves
2118 mflua.threshold_min_dist = 0.5 -- _remove_reduntant_curves
2119 mflua.threshold_pending_path = 0.002 -- _remove_reduntant_curves
2120 mflua.threshold_pen = 5 -- _remove_redundant_segments
2121 mflua.threshold_bug = 4 -- _fix_intersection_bug
2122 mflua.threshold_min_bug = 0.03 -- _fix_intersection_bug
2123 mflua.threshold_equal_path=0.03 -- _remove_duplicate_pen_path
2124 mflua.threshold_straight_line = 0.125 -- _is_a_straight_line
2125 mflua.threshold_fix_knots = 0.125 -- _fix_knots
2126 mflua.threshold_fix_knots_1 = 0.0005 -- _fix_knots
2127 mflua.threshold_fix_knots_2 = 0.4 -- _fix_knots
2128 mflua.threshold_remove_redundant_pen = 0.02 -- remove_redundant_pen
2129 mflua.threshold_remove_redundant_curves = 3 -- _remove_redundant_curves
2130 mflua.threshold_merge_segments = 5e-5 -- _merge_segments
2131 mflua.threshold_join_curves = 0.049 -- _build_cycles try and error
2132 mflua.set_poly_done={}
2133 mflua.mflua_exe = 'mflua'
2134 mflua.turningnumber_file='mflua_tn'
2135 mflua.fill_envelope = {}
2136 mflua.fill_envelope.temp_transition = ""
2137 mflua.pen = {} -- collect bezier curves of the pens
2138
2139 --
2140
2141 mflua.chartable ={}
2142 mflua.max_curves =1e4
2143
2144
2145 function mflua.lock(params)
2146 if params ==nil then
2147 return io.open('LOCK1','w')
2148 else
2149 return io.open(tostring(params),'w')
2150 end
2151 end
2152
2153 function mflua.unlock(params)
2154 if params == nil then
2155 return os.remove('LOCK1')
2156 else
2157 return os.remove(tostring(params))
2158 end
2159 end
2160
2161 function mflua.checklock(params)
2162 if params == nil then
2163 if io.open("LOCK1") ~= nil then return true else return false end
2164 else
2165 if io.open(tostring(params)) ~= nil then return true else return false end
2166 end
2167 end
2168
2169
2170 function mflua.dot(P1,P2)
2171 return P1[1]*P2[1]+P1[2]*P2[2]
2172 end
2173
2174 function mflua.angle(p,q)
2175 local dot = mflua.dot
2176 if math.abs(1 - dot(p,q)/(math.sqrt(dot(p,p))*math.sqrt(dot(q,q)))) <0.0001 then
2177 return 0
2178 else
2179 return math.acos(dot(p,q)/(math.sqrt(dot(p,p))*math.sqrt(dot(q,q))))
2180 end
2181 end
2182
2183 -- function mflua.vec(a,w,b1) if b1 == nil then b=w else b = b1 end ; return {b[1]-a[1],b[2]-a[2]} end
2184 -- mflua.vec(a,b) == mflua.vec(a,'->',b)
2185 function mflua.round(p)
2186 local w=string.gmatch(p,"[-0-9.]+");
2187 local p p={w(),w()};
2188 return string.format("(%6.5f,%6.5f)",tostring(p[1]),tostring(p[2]) )
2189 end
2190
2191 function mflua.round5(p)
2192 local w=string.gmatch(p,"[-0-9.]+");
2193 local p; p={w(),w()};
2194 return string.format("(%6.5f,%6.5f)",tostring(p[1]),tostring(p[2]) )
2195 end
2196
2197 function mflua.round2(p)
2198 local w=string.gmatch(p,"[-0-9.]+");
2199 local p; p={w(),w()};
2200 return string.format("(%6.2f,%6.2f)",tostring(p[1]),tostring(p[2]) )
2201 end
2202
2203 function mflua.round1(p)
2204 local w=string.gmatch(p,"[-0-9.]+");
2205 local p; p={w(),w()};
2206 return string.format("(%6.1f,%6.1f)",tostring(p[1]),tostring(p[2]) )
2207 end
2208
2209 function mflua.round0(p)
2210 local w=string.gmatch(p,"[-0-9.]+");
2211 local p; p={w(),w()};
2212 return string.format("(%6.0f,%6.0f)",tostring(p[1]),tostring(p[2]) )
2213 end
2214
2215 function mflua.floor(p)
2216 local w=string.gmatch(p,"[-0-9.]+");
2217 local p; p={w(),w()};
2218 return string.format("(%d,%d)",math.floor(p[1]),math.floor(p[2]) )
2219 end
2220
2221 function mflua.round5_table(p)
2222 return {tonumber(string.format("%6.5f",tostring(p[1]))),tonumber(string.format("%6.5f",tostring(p[2])))}
2223 end
2224
2225 function mflua.number_to_string_round5(p)
2226 return string.format("(%6.5f,%6.5f)",p[1],p[2])
2227 end
2228
2229
2230 function mflua.vec(a,b)
2231 return {b[1]-a[1],b[2]-a[2]}
2232 end
2233
2234 function mflua.modul_vec(a,b)
2235 local dot = mflua.dot
2236 local P ={b[1]-a[1],b[2]-a[2]}
2237 return math.sqrt(dot(P,P))
2238 end
2239
2240 function mflua.approx_curve_lenght(p,c1,c2,q)
2241 return mflua.modul_vec(p,c1) + mflua.modul_vec(c1,c2) + mflua.modul_vec(c2,q) + mflua.modul_vec(p,q)
2242 end
2243
2244
2245 -- for multiple instances of mflua one can define a LOCK like this
2246 -- if io.open('LOCK1')==nil and io.open('LOCK_ELLIPSE')==nil then
2247 -- mflua.print_specification.filename = "envelope.tex"
2248 -- mflua.print_specification.outfile1 = io.open(mflua.print_specification.filename,'w')
2249 -- end
2250
2251
2252
2253 --------------------------------------------------------------------------------
2254 --
2255 -- tfm module
2256 --
2257 --------------------------------------------------------------------------------
2258 local tfm = {}
2259 tfm.bits =
2260 function(a,l)
2261 local bita = {}
2262 local a = a
2263 for k=1,l do
2264 local r=math.fmod(a,2)
2265 a=math.floor(a/2)
2266 bita[k]=r
2267 end
2268 return bita
2269 end
2270 tfm.bitand =
2271 function(a,b,l)
2272 local bita,bitb,bitc = tfm.bits(a,l), tfm.bits(b,l),{}
2273 local c= 0
2274 for k=1,l do
2275 bit1,bit2 = bita[k],bitb[k]
2276 if (bit1==1) and (bit2==1) then
2277 bitc[k]=1
2278 else
2279 bitc[k]=0
2280 end
2281 c = c+2^(k-1)*bitc[k]
2282 end
2283 return c,bitc
2284 end
2285 tfm.bitor =
2286 function(a,b,l)
2287 local bita,bitb,bitc = tfm.bits(a,l), tfm.bits(b,l),{}
2288 local c= 0
2289 for k=1,l do
2290 bit1,bit2 = bita[k],bitb[k]
2291 if (bit1==1) or (bit2==1) then
2292 bitc[k]=1
2293 else
2294 bitc[k]=0
2295 end
2296 c = c+ 2^(k-1)*bitc[k]
2297 end
2298 return c,bitc
2299 end
2300 tfm.bitnot =
2301 function(a,l)
2302 local bita,bitb = tfm.bits(a,l),{}
2303 local b= 0
2304 for k=1,l do
2305 bit1 = bita[k]
2306 if (bit1==1) then
2307 bitb[k]=0
2308 else
2309 bitb[k]=1
2310 end
2311 b = b+ 2^(k-1)*bitb[k]
2312 end
2313 return b,bitb
2314 end
2315 tfm.printbits=
2316 function(t,l)
2317 local r = ''
2318 local l = l or #t
2319 if l==0 then return '' end
2320 for k=l,1,-1 do
2321 local v = t[k] or '0'
2322 r=r..v
2323 end
2324 return r
2325 end
2326
2327 tfm.stop_flag = 128
2328 tfm.kern_flag = 128
2329
2330 tfm.parameters = {}
2331 tfm.parameters.init =
2332 function()
2333 -- 8. The first 24 bytes (6 words) of a TFM file contain twelve 16-bit integers that give the lengths of the
2334 -- various subsequent portions of the file. These twelve integers are, in order:
2335 -- lf = length of the entire file, in words;
2336 -- lh = length of the header data, in words;
2337 -- bc = smallest character code in the font;
2338 -- ec = largest character code in the font;
2339 -- nw = number of words in the width table;
2340 -- nh = number of words in the height table;
2341 -- nd = number of words in the depth table;
2342 -- ni = number of words in the italic correction table;
2343 -- nl = number of words in the lig/kern table;
2344 -- nk = number of words in the kern table;
2345 -- ne = number of words in the extensible character table;
2346 -- np = number of font parameter words.
2347 -- They are all nonnegative and less than 2^15 . We must have bc - 1<= ec <= 255, ne<= 256, and
2348 -- lf = 6 + lh + (ec - bc + 1) + nw + nh + nd + ni + nl + nk + ne + np .
2349 -- When two or more 8-bit bytes are combined to form an integer of 16 or more bits, the most
2350 -- significant bytes appear first in the file. This is called BigEndian order.
2351
2352 if tfm.content ==nil or type(tfm.content)~= 'string' then
2353 return false, 'Error on file content'
2354 end
2355 tfm.parameters.w = string.gmatch(tfm.content,"[%z%Z]")
2356 local w = tfm.parameters.w
2357 local W1,W2
2358
2359 W1,W2=w(),w();if W1==nil or W2==nil then return false, 'Error on parsing content (lf)' end
2360 tfm.parameters.lf = 256*string.byte(W1)+string.byte(W2) -- length of the entire file, in words;
2361
2362 W1,W2=w(),w();if W1==nil or W2==nil then return false, 'Error on parsing content (lh)' end
2363 tfm.parameters.lh = 256*string.byte(W1)+string.byte(W2) -- length of the header data, in words;
2364
2365 W1,W2=w(),w();if W1==nil or W2==nil then return false, 'Error on parsing content (bc)' end
2366 tfm.parameters.bc = 256*string.byte(W1)+string.byte(W2) -- smallest character code in the font;
2367
2368 W1,W2=w(),w();if W1==nil or W2==nil then return false, 'Error on parsing content (ec)' end
2369 tfm.parameters.ec = 256*string.byte(W1)+string.byte(W2) -- largest character code in the font;
2370
2371 W1,W2=w(),w();if W1==nil or W2==nil then return false, 'Error on parsing content (nw)' end
2372 tfm.parameters.nw = 256*string.byte(W1)+string.byte(W2) -- number of words in the width table;
2373
2374 W1,W2=w(),w();if W1==nil or W2==nil then return false, 'Error on parsing content (nh)' end
2375 tfm.parameters.nh = 256*string.byte(W1)+string.byte(W2) -- number of words in the height table;
2376
2377 W1,W2=w(),w();if W1==nil or W2==nil then return false, 'Error on parsing content (nd)' end
2378 tfm.parameters.nd = 256*string.byte(W1)+string.byte(W2) -- number of words in the depth table;
2379
2380 W1,W2=w(),w();if W1==nil or W2==nil then return false, 'Error on parsing content (ni)' end
2381 tfm.parameters.ni = 256*string.byte(W1)+string.byte(W2) -- number of words in the italic correction table;
2382
2383 W1,W2=w(),w();if W1==nil or W2==nil then return false, 'Error on parsing content (nl)' end
2384 tfm.parameters.nl = 256*string.byte(W1)+string.byte(W2) -- number of words in the lig/kern table;
2385
2386 W1,W2=w(),w();if W1==nil or W2==nil then return false, 'Error on parsing content (nk)' end
2387 tfm.parameters.nk = 256*string.byte(W1)+string.byte(W2) -- number of words in the kern table;
2388
2389 W1,W2=w(),w();if W1==nil or W2==nil then return false, 'Error on parsing content (ne)' end
2390 tfm.parameters.ne = 256*string.byte(W1)+string.byte(W2) -- number of words in the extensible character table;
2391
2392 W1,W2=w(),w();if W1==nil or W2==nil then return false, 'Error on parsing content (np)' end
2393 tfm.parameters.np = 256*string.byte(W1)+string.byte(W2) -- number of font parameter words.
2394 return
2395 end
2396
2397 tfm.parameters.check =
2398 function()
2399 local w = tfm.parameters.w
2400 local lf = tfm.parameters.lf
2401 local lh = tfm.parameters.lh
2402 local bc = tfm.parameters.bc
2403 local ec = tfm.parameters.ec
2404 local nw = tfm.parameters.nw
2405 local nh = tfm.parameters.nh
2406 local nd = tfm.parameters.nd
2407 local ni = tfm.parameters.ni
2408 local nl = tfm.parameters.nl
2409 local nk = tfm.parameters.nk
2410 local ne = tfm.parameters.ne
2411 local np = tfm.parameters.np
2412 local status = true
2413 local status_cnt = 0
2414 local status_msg = 'OK'
2415 local function _assert(cond,msg)
2416 if cond==false then
2417 --print(msg)
2418 status_msg = msg
2419 status_cnt = status_cnt +1
2420 end
2421 end
2422 if status_cnt == 0 then _assert(lf == 6 + lh + (ec - bc + 1) + nw + nh + nd + ni + nl + nk + ne + np ,"Error on lf") end
2423 if status_cnt == 0 then _assert(0<=lf and lf <2^15,"lf out of range") end
2424 if status_cnt == 0 then _assert(0<=lh and lh <2^15,"lh out of range") end
2425 if status_cnt == 0 then _assert(0<=bc and bc <2^15,"bc out of range") end
2426 if status_cnt == 0 then _assert(0<=ec and ec <2^15,"ec out of range") end
2427 if status_cnt == 0 then _assert(0<=nw and nw <2^15,"nw out of range") end
2428 if status_cnt == 0 then _assert(0<=nh and nh <2^15,"nh out of range") end
2429 if status_cnt == 0 then _assert(0<=nd and nd <2^15,"nd out of range") end
2430 if status_cnt == 0 then _assert(0<=ni and ni <2^15,"ni out of range") end
2431 if status_cnt == 0 then _assert(0<=nl and nl <2^15,"nl out of range") end
2432 if status_cnt == 0 then _assert(0<=nk and nk <2^15,"nk out of range") end
2433 if status_cnt == 0 then _assert(0<=ne and ne <2^15,"ne out of range") end
2434 if status_cnt == 0 then _assert(0<=np and np <2^15,"np out of range") end
2435 if status_cnt == 0 then _assert( (bc-1)<=ec and ec<= 255, "Error on bc and ec") end
2436 if status_cnt == 0 then _assert(ne<= 256, "ne >256") end
2437 if status_cnt > 0 then status=false end
2438 return status,status_msg
2439 end
2440
2441
2442 tfm.int_to_frac =
2443 function(d)
2444 if not (0<=d and d<2^32) then
2445 return nil, string.format("Error: %s out of range (-%s,%s-2^-20)",d,2^31,2^31)
2446 else
2447 if d<=2147483647 then
2448 return d/2^20,'ok'
2449 else
2450 return (d-2^32)/2^20,'ok'
2451 end
2452 end
2453
2454 end
2455 tfm.tag_meaning =
2456 function(d)
2457 local t = {'vanilla character','character has a ligature/kerning program',
2458 'character has a successor in a charlist','character is extensible'}
2459 local d = tonumber(d) or -1
2460 if d<0 or d>3 then return '' end
2461 return t[tonumber(d+1)]
2462 end
2463
2464 tfm.getface =
2465 function(d)
2466 --If the value is less than 18, it has the following
2467 --interpretation as a "weight, slope, and expansion": Add 0 or 2 or 4 (for medium or bold or light) to
2468 --0 or 1 (for roman or italic) to 0 or 6 or 12 (for regular or condensed or extended). For example, 13 is
2469 --0+1+12, so it represents medium italic extended. A three-letter code (e.g., MIE) can be used for such
2470 --face data.
2471 -- d = 3⋅rce_bit⋅2^{2,1} + ri_bit + mbl_bit⋅2^{2,1} , rce_bit,ri_bit,mbl_bit ∈ {0,1}
2472 -- d%2 = ri_bit := ri
2473 -- d%3 - d%2 = mblâ‹…2^{2,1} := mbl
2474 -- d - d%3 = 3â‹…rceâ‹…2^{2,1} := rce
2475 if d>17 then return '' end
2476 local mbl,ri, rce = '*','*','*'
2477 local _ri = d % 2
2478 if _ri==0 then ri ='R' else ri ='I' end
2479 local _mbl = (d%3) -(d%2)
2480 if _mbl == 0 then mbl='M' end
2481 if _mbl == 2 then mbl='B' end
2482 if _mbl == 4 then mbl='E' end
2483 local _rce = d - (d%3)
2484 if _rce == 0 then rce = 'M' end
2485 if _rce == 1 then rce = 'I' end
2486 if _rce == 12 then rce = 'E' end
2487 return mbl..ri..rce, {_mbl,_ri,_rce}
2488 end
2489
2490 tfm.printfloat =
2491 function(d,p)
2492 if d then
2493 local d,p = d, tonumber(p) or 6
2494 local f = string.format("%%.%df",p)
2495 return string.format(f,d)
2496 else
2497 return tostring(d)
2498 end
2499 end
2500
2501 tfm.array = {}
2502 tfm.array.check =
2503 function()
2504 local width = tfm.array.width
2505 local height = tfm.array.height
2506 local depth = tfm.array.depth
2507 local italic = tfm.array.italic
2508 local status = true
2509 local status_cnt = 0
2510 local status_msg = 'OK'
2511 local function _assert(cond,msg)
2512 if cond==false then
2513 --print(msg)
2514 status_msg = msg
2515 status_cnt = status_cnt +1
2516 end
2517 end
2518 _assert(width[0]==0,'Error in width[0]')
2519 _assert(height[0]==0,'Error in height[0]')
2520 _assert(depth[0]==0,'Error in depth[0]')
2521 _assert(italic[0]==0,'Error in italic[0]')
2522 if status_cnt > 0 then status=false end
2523 return status,status_msg
2524
2525 end
2526
2527 tfm.dump={}
2528 tfm.dump.kernprogram =
2529 function(d,c)
2530 local char_info = tfm.array.char_info
2531 local lig_kern = tfm.array.lig_kern
2532 local kern = tfm.array.kern
2533 local current_step = d
2534 local current_char = c
2535 local skip_byte=lig_kern[current_step][1]
2536 local next_char=lig_kern[current_step][2]
2537 local op_byte=lig_kern[current_step][3]
2538 local remainder=lig_kern[current_step][4]
2539 local _print = tfm.printdebug()
2540 _print("-------")
2541 _print("skip_byte=",skip_byte)
2542 _print("next_char=",next_char,'C '..string.char(next_char),'O '..string.format("%o",next_char))
2543 _print("op_byte=",op_byte)
2544 _print("remainder=",remainder,string.format("O %o",remainder))
2545 if op_byte <tfm.kern_flag then -- a ligature step
2546 -- op_byte= 4a+2b+c where 0<=a<=b+c and 0<=b,c<=1.
2547 local a,b,c
2548 c= op_byte%2
2549 b = ((op_byte-c)%4)/2
2550 a = (op_byte-2*b-c)/4
2551 _print("ligature step: a,b,c=",a,b,c)
2552 if b==0 then
2553 _print("current char: deleted")
2554 else
2555 _print("current char: not deleted" )
2556 end
2557 if c==0 then
2558 _print("next char: deleted")
2559 else
2560 _print("next char: not deleted ")
2561 end
2562 if a==0 then
2563 _print("no next char")
2564 else
2565 -- we must pass over the next a characters
2566 -- local _,_remainder,_,_,_tag,_ = char_info[current_char+a]
2567 -- if _tag==1 then
2568 -- local kern_program = tfm.dump.kernprogram(_remainder,current_char+a)
2569 -- end
2570 end
2571 tfm.chars[current_char] = tfm.chars[current_char] or {}
2572 tfm.chars[current_char].ligature = tfm.chars[current_char].ligature or {}
2573 tfm.chars[current_char].ligature[#tfm.chars[current_char].ligature+1]=
2574 {['next_char']=next_char,['a']=a,['b']=b,['c']=c}
2575
2576 else -- a kern step
2577 local additional_space = kern[256*(op_byte-128)+remainder]
2578 _print("kern step:additional_space=",tfm.printfloat(additional_space))
2579 tfm.chars[current_char] = tfm.chars[current_char] or {}
2580 tfm.chars[current_char].kern = tfm.chars[current_char].kern or {}
2581 tfm.chars[current_char].kern[#tfm.chars[current_char].kern+1] =
2582 {['next_char']=next_char,['additional_space']=additional_space}
2583 end
2584
2585 if skip_byte>=tfm.stop_flag then
2586 -- end
2587 return
2588 else
2589 -- take next instruction
2590 tfm.dump.kernprogram(current_step+1+skip_byte,current_char)
2591 end
2592 end
2593
2594
2595 tfm.build = {}
2596 tfm.build.header =
2597 function(i,j,w)
2598 local _i,_j,_a = i,j,{}
2599 for i=_i,_j do
2600 if i<=1 or i>17 then
2601 _a[i] =2^24*string.byte(w())+2^16*string.byte(w())+2^8*string.byte(w())+string.byte(w())
2602 elseif 2<=i and i<=16 then
2603 _a[i] =w()..w()..w()..w()
2604 elseif i==17 then
2605 _a[i] ={string.byte(w()),string.byte(w()),string.byte(w()),string.byte(w())}
2606 end
2607 end
2608 return _a
2609 end
2610
2611 tfm.build._bytearray =
2612 function(i,j,w)
2613 local _i,_j,_a = i,j,{}
2614 for i=_i,_j do
2615 _a[i] ={string.byte(w()),string.byte(w()),string.byte(w()),string.byte(w())}
2616 end
2617 return _a
2618 end
2619 tfm.build.char_info = tfm.build._bytearray
2620 tfm.build.lig_kern = tfm.build._bytearray
2621 tfm.build.exten = tfm.build._bytearray
2622
2623 tfm.build._dimension =
2624 function(i,j,w)
2625 local _i,_j,_a = i,j,{}
2626 for i=_i,_j do
2627 _a[i] = tfm.int_to_frac(2^24*string.byte(w())+2^16*string.byte(w())+2^8*string.byte(w())+string.byte(w()))
2628 end
2629 return _a
2630 end
2631 tfm.build.width = tfm.build._dimension
2632 tfm.build.height = tfm.build._dimension
2633 tfm.build.depth = tfm.build._dimension
2634 tfm.build.italic = tfm.build._dimension
2635 tfm.build.kern = tfm.build._dimension
2636 tfm.build.param = tfm.build._dimension
2637
2638 tfm.build.all =
2639 function()
2640 local w = tfm.parameters.w
2641 local lf = tfm.parameters.lf
2642 local lh = tfm.parameters.lh
2643 local bc = tfm.parameters.bc
2644 local ec = tfm.parameters.ec
2645 local nw = tfm.parameters.nw
2646 local nh = tfm.parameters.nh
2647 local nd = tfm.parameters.nd
2648 local ni = tfm.parameters.ni
2649 local nl = tfm.parameters.nl
2650 local nk = tfm.parameters.nk
2651 local ne = tfm.parameters.ne
2652 local np = tfm.parameters.np
2653 tfm.array.header = tfm.build.header(0,lh-1,w)
2654 tfm.array.char_info = tfm.build.char_info(bc,ec,w)
2655 tfm.array.width = tfm.build.width( 0,nw-1,w)
2656 tfm.array.height = tfm.build.height(0,nh-1,w)
2657 tfm.array.depth = tfm.build.depth( 0,nd-1,w)
2658 tfm.array.italic = tfm.build.italic(0,ni-1,w)
2659 tfm.array.lig_kern = tfm.build.lig_kern(0,nl-1,w)
2660 tfm.array.kern = tfm.build.kern(0,nk-1,w)
2661 tfm.array.exten = tfm.build.exten(0,ne-1,w)
2662 tfm.array.param = tfm.build.param(1,np,w)
2663 end
2664
2665 tfm.debug = 0
2666 tfm.printdebug =
2667 function()
2668 if tfm.debug==1 then
2669 return print
2670 else
2671 return function(...) end
2672 end
2673 end
2674
2675 tfm.getdata={}
2676 tfm.getdata.char_info =
2677 function(i)
2678 local char_info = tfm.array.char_info
2679 local width_index = char_info[i][1]
2680 local height_index_plus_depth_index = char_info[i][2]
2681 local italic_index_plus_tag = char_info[i][3]
2682 local remainder = char_info[i][4]
2683 local depth_index = height_index_plus_depth_index % 16
2684 local height_index= (height_index_plus_depth_index -depth_index)/16
2685 local tag = italic_index_plus_tag % 4
2686 local italic_index = (italic_index_plus_tag -tag)/4
2687 return width_index,remainder,depth_index,height_index,tag,italic_index
2688 end
2689 tfm.chars = {}
2690 tfm.font = {}
2691
2692 tfm.run=
2693 function(name)
2694 local name = name
2695 local _print = tfm.printdebug()
2696 local header ={}
2697 local char_info ={}
2698 local width ={}
2699 local height ={}
2700 local depth ={}
2701 local italic ={}
2702 local lig_kern ={}
2703 local kern ={}
2704 local exten ={}
2705 local param ={}
2706 local w
2707 local lf
2708 local lh
2709 local bc
2710 local ec
2711 local nw
2712 local nh
2713 local nd
2714 local ni
2715 local nl
2716 local nk
2717 local ne
2718 local np
2719
2720 if kpse.find_file(name)==nil then
2721 name = name .. ".tfm"
2722 end
2723 if kpse.find_file(name)==nil then
2724 return false, "Error: file "..tostring(name).." not found"
2725 end
2726 tfm.name = name
2727 tfm.file = io.open(tfm.name,'rb')
2728 if tfm.file == nil then
2729 return false, "Error on opening file "..tostring(tfm.name)
2730 end
2731 tfm.content = tfm.file:read("*a")
2732 status,status_msg = tfm.parameters.init()
2733 if status== false then
2734 _print("ERROR="..tostring(status_msg))
2735 return false, tostring(status_msg)
2736 end
2737
2738 status,status_msg = tfm.parameters.check()
2739 if status == false then
2740 _print("ERROR="..tostring(status_msg))
2741 return false, tostring(status_msg)
2742 end
2743 -- Build all arrays
2744 tfm.build.all()
2745 header = tfm.array.header
2746 char_info = tfm.array.char_info
2747 width = tfm.array.width
2748 height = tfm.array.height
2749 depth = tfm.array.depth
2750 italic = tfm.array.italic
2751 lig_kern = tfm.array.lig_kern
2752 kern = tfm.array.kern
2753 exten = tfm.array.exten
2754 param = tfm.array.param
2755
2756 w = tfm.parameters.w
2757 lf = tfm.parameters.lf
2758 lh = tfm.parameters.lh
2759 bc = tfm.parameters.bc
2760 ec = tfm.parameters.ec
2761 nw = tfm.parameters.nw
2762 nh = tfm.parameters.nh
2763 nd = tfm.parameters.nd
2764 ni = tfm.parameters.ni
2765 nl = tfm.parameters.nl
2766 nk = tfm.parameters.nk
2767 ne = tfm.parameters.ne
2768 np = tfm.parameters.np
2769
2770 status,status_msg = tfm.array.check()
2771 if status == false then
2772 _print("ERROR="..tostring(status_msg))
2773 return false, tostring(status_msg)
2774 end
2775 tfm.font.checksum =header[0]
2776 tfm.font.designsize = tfm.int_to_frac(header[1])
2777 local coding_scheme
2778 if header[2]~= nil then
2779 coding_scheme = ''
2780 for j=2,11 do coding_scheme=coding_scheme..tostring(header[j]) end
2781 tfm.font.coding_scheme=coding_scheme
2782 _print(string.format("CODING SCHEME:%s",tfm.font.coding_scheme))
2783 end
2784 local font_identifier
2785 if header[12]~= nil then
2786 font_identifier = ''
2787 for j=12,16 do font_identifier=font_identifier..tostring(header[j]) end
2788 tfm.font.font_identifier=font_identifier
2789 _print(string.format("FONT IDENTIFIER:%s",tfm.font.font_identifier))
2790 end
2791 local seven_bit_safe_flag ,face
2792 if header[17]~= nil then
2793 seven_bit_safe_flag ,face = header[17][1],header[17][4]
2794 tfm.font.seven_bit_safe_flag = seven_bit_safe_flag
2795 tfm.font.face = face
2796 _print(string.format("SEVEN_BIT_SAFE_FLAG=%x",seven_bit_safe_flag))
2797 local f,t = tfm.getface(face)
2798 face = f
2799 _print(string.format("FACE=%s (mbl=%d,ri=%d,rce=%d)",face,t[1],t[2],t[3]))
2800 end
2801 local _pf = tfm.printfloat
2802 for current_char=bc,ec do
2803 --for current_char=102,102 do
2804 local width_index,remainder,depth_index,height_index,tag,italic_index = tfm.getdata.char_info(current_char)
2805 tfm.chars[current_char] = tfm.chars[current_char] or {}
2806 tfm.chars[current_char].width = width[width_index]
2807 tfm.chars[current_char].height = height[height_index]
2808 tfm.chars[current_char].depth = depth[depth_index]
2809 tfm.chars[current_char].italic = italic[italic_index]
2810 tfm.chars[current_char].tag = tag
2811 _print(string.format("O %o",current_char),string.char(current_char),
2812 'WIDTH='.._pf(width[width_index]),
2813 'HEIGHT='.._pf(height[height_index]),
2814 'DEPTH='.._pf(depth[depth_index]),
2815 'ITALIC='.._pf(italic[italic_index]),
2816 'TAG='..tfm.tag_meaning(tag)
2817 )
2818 if tag==1 then -- character has a ligature/kerning program
2819 local kern_program = tfm.dump.kernprogram(remainder,current_char)
2820 end
2821 end
2822
2823 tfm.font.slant = param[1]
2824 _print("SLANT=".._pf(tfm.font.slant))
2825
2826 tfm.font.space = param[2]
2827 _print("SPACE=".._pf(tfm.font.space))
2828
2829 tfm.font.space_stretch = param[3]
2830 _print("SPACE_STRETCH=".._pf(tfm.font.space_stretch))
2831
2832 tfm.font.space_shrink = param[4]
2833 _print("SPACE_SHRINK=".._pf(tfm.font.space_shrink))
2834
2835 tfm.font.x_height = param[5]
2836 _print("X_HEIGHT=".._pf(tfm.font.x_height))
2837
2838 tfm.font.quad = param[6]
2839 _print("QUAD=".._pf(tfm.font.quad))
2840
2841 tfm.font.extra_space = param[7]
2842 _print("EXTRA_SPACE=".._pf(tfm.font.extra_space))
2843
2844 return true,'ok'
2845
2846 end
2847 --------------------------------------------------------------------------------
2848
2849 -- Add tfm to the mflua table
2850 mflua.tfm = tfm
2851
2852
2853
2854 --------------------------------------------------------------------------------
2855 --
2856 -- gf module
2857 --
2858 --------------------------------------------------------------------------------
2859 --
2860 -- In-memory parser, i.e. reads all the gf into memory
2861 -- and then parses the byte stream
2862 --
2863
2864 local GF = {}
2865 do
2866
2867 local sub = string.sub
2868 local len = string.len
2869 local byte = string.byte
2870 local format = string.format
2871 local rep = string.rep
2872
2873 local gfdata=''
2874 local gfdata_index
2875 local gfdata_len
2876
2877 local chars={}
2878 local current_char
2879 local current_row -- aka n
2880 local current_col -- aka m
2881 local white=0
2882 local black=white+1
2883 local paint_switch
2884 chars.xxx1 = {}
2885 chars.xxx2 = {}
2886 chars.xxx3 = {}
2887 chars.xxx4 = {}
2888 chars.yyy = {}
2889 chars.nop = {}
2890 chars.all_nop = {} -- collect a xxx1 or xxx2 or xxx3 or xxx4 or yyy or nop
2891 chars.locators = {}
2892
2893
2894
2895
2896 local defDEBUG = false
2897 local function DEBUG(k,s)
2898 print("DEBUG:"..tostring(k).."="..tostring(s))
2899 end
2900
2901
2902 local function error_msg(msg)
2903 io.write(format("! mflua GF: char %s: %s",current_char, msg))
2904 io.write(format(" position=%s ",gfdata_index))
2905 print()
2906 end
2907 GF.error = error_msg
2908
2909 local function warning_msg(msg)
2910 print(format("\n! mflua GF: char %s: %s.",current_char, msg))
2911 end
2912 GF.warning = warning_msg
2913
2914
2915
2916 --
2917 -- read n bytes starting from from gfdata_index included
2918 -- and move gfdata_index
2919 --
2920 local function readbytes(n)
2921 if (gfdata_index+n-1)<1 then
2922 GF.warning("attempt to read before the beginning of the file")
2923 return nil
2924 end
2925 if (gfdata_index+n-1)>gfdata_len then
2926 GF.warning("attempt to read beyond the end of the file")
2927 return nil
2928 end
2929 local s
2930 if (n<0) then
2931 s = sub(gfdata,gfdata_index+n+1,gfdata_index)
2932 elseif n>0 then
2933 s = sub(gfdata,gfdata_index,gfdata_index+n-1)
2934 else
2935 s =''
2936 end
2937 gfdata_index = gfdata_index+n
2938 return s
2939 end
2940
2941
2942 local function read4bytes()
2943 local b0 = byte(readbytes(1))
2944 local b1 = byte(readbytes(1))
2945 local b2 = byte(readbytes(1))
2946 local b3 = byte(readbytes(1))
2947 local v = (b3+b2*256+b1*65536+b0*16777216)
2948 if v >2147483647 then
2949 v = v -4294967296
2950 end
2951 return v
2952 end
2953
2954
2955 local function readrev4bytes()
2956 local b3 = byte(readbytes(-1))
2957 local b2 = byte(readbytes(-1))
2958 local b1 = byte(readbytes(-1))
2959 local b0 = byte(readbytes(-1))
2960 local v = (b3+b2*256+b1*65536+b0*16777216)
2961 if v >2147483647 then
2962 v = v -4294967296
2963 end
2964 return v
2965 end
2966
2967
2968 local function readuntileof()
2969 if gfdata_index>gfdata_len then
2970 GF.warning("wrong index: gfdata_index="..tostring(gfdata_index).."> gfdata_len="..tostring(gfdata_len) )
2971 return nil
2972 end
2973 local s = sub(gfdata,gfdata_index,gfdata_len)
2974 gfdata_index = gfdata_len +1
2975 return s
2976 end
2977
2978
2979 local function datanotfinished()
2980 return (gfdata_index <= gfdata_len)
2981 end
2982
2983
2984 local function moveindex_after(p)
2985 gfdata_index = p+1
2986 end
2987
2988
2989
2990 error = {}
2991 error.ok = 0
2992 error.base = error.ok
2993 error.pre = error.base +1
2994 error.parse = error.base +2
2995 error.post = error.base +3
2996 error.boc = error.base +4
2997 error.load = error.base +127
2998 error.parse = error.base +128
2999 error.parsechar = error.base +129
3000 error.paint = {}
3001 for j=0,63 do
3002 error.paint[j] = error.base +130+j
3003 end
3004 error.paint_switch=error.base +130+64
3005 error.paint1 = error.base +130+64+1
3006 error.paint2 = error.base +130+64+2
3007 error.paint3 = error.base +130+64+3
3008 error.eoc = error.base +130+64+6
3009 error.skip0 = error.base +130+64+7
3010 error.skip1 = error.base +130+64+8
3011 error.skip2 = error.base +130+64+9
3012 error.skip3 = error.base +130+64+10
3013 error.new_row = {}
3014 for j=0,164 do
3015 error.new_row[j]= error.base +130+64+10+1+j
3016 end
3017
3018 error.post_post=error.base +130+64+10+1+165
3019
3020 error.skip223=error.base +130+64+10+1+166
3021
3022
3023 error_name_t = {}
3024 for k,v in pairs(error) do
3025 error_name_t[v] = k
3026 end
3027 local function error_name(res)
3028 if res==nil then
3029 return "unknown error code"
3030 elseif error_name_t[res] == nil then
3031 return "unknown error code"
3032 else
3033 return error_name_t[res]
3034 end
3035 end
3036
3037 local opcodes = {}
3038
3039 -- {beginning of the \\{paint} commands}
3040 for j=0,63 do
3041 local s = format("paint_%d",j)
3042 opcodes[s] = j
3043 end
3044 opcodes.paint1=64 -- {move right a given number of columns, then black${}\swap{}$white}
3045 opcodes.paint2=65
3046 opcodes.paint3=66
3047 opcodes.boc=67 -- {beginning of a character}
3048 opcodes.boc1=68 -- {short form of |boc|}
3049 opcodes.eoc=69 -- {end of a character}
3050 opcodes.skip0=70 -- {skip no blank rows}
3051 opcodes.skip1=71 -- {skip over blank rows}
3052 opcodes.skip2=72
3053 opcodes.skip3=73
3054 --opcodes.new_row_0=74 -- {move down one row and then right}
3055 --:
3056 --opcodes.new_row_164=238
3057 for j=0,164 do
3058 local s = format("new_row_%d",j)
3059 opcodes[s] = j+74
3060 end
3061
3062 --opcodes.max_new_row=164 -- {the largest \\{new\_row} command is |new_row_164|}
3063 opcodes.xxx1=239 -- {for \&{special} strings}
3064 opcodes.xxx2=240
3065 opcodes.xxx3=241 -- {for long \&{special} strings}
3066 opcodes.xxx4=242
3067 opcodes.yyy=243 -- {for \&{numspecial} numbers}
3068 opcodes.nop=244 -- no operation
3069 opcodes.char_loc=245 -- {character locators in the postamble}
3070 opcodes.char_loc0=246
3071 opcodes.pre=247 -- {preamble}
3072 opcodes.post=248 -- {postamble beginning}
3073 opcodes.post_post=249 -- {postamble ending}
3074
3075 opcodes.undefined_1=250
3076 opcodes.undefined_2=251
3077 opcodes.undefined_3=252
3078 opcodes.undefined_4=253
3079 opcodes.undefined_5=254
3080 opcodes.undefined_6=255
3081
3082 local revopcode = {}
3083 for k,v in pairs(opcodes) do revopcode[v] = k end
3084
3085
3086
3087 complement_paint_switch = function()
3088 local res = error.ok
3089 if( paint_switch==black or paint_switch==white) then
3090 paint_switch=(paint_switch+1)%2
3091 else
3092 GF.error("wrong value for paint_switch")
3093 res = error.paint_switch
3094 end
3095 return res
3096 end
3097
3098 local paint = function(n)
3099 local res = error.ok
3100 local c = chars[current_char]
3101 local row = c[current_row]
3102 if row==nil then
3103 GF.error("error in paint_"..tostring(n)..", row is nil")
3104 end
3105 if paint_switch==black then
3106 for i=current_col,current_col+n-1 do
3107 row[i]=true
3108 end
3109 end
3110 res = complement_paint_switch()
3111 current_col = current_col + n
3112 if res~=error.ok then
3113 if n<64 then
3114 GF.error("error in paint_"..tostring(n))
3115 res = error.paint[n]
3116 elseif (64<=n and n<256) then
3117 GF.error("error in paint1")
3118 res = error.paint1
3119 elseif (256<=n and n<65536) then
3120 GF.error("error in paint2")
3121 res = error.paint2
3122 elseif (65536<=n and n<16777216) then
3123 GF.error("error in paint3")
3124 res = error.paint3
3125 end
3126 end
3127 return res
3128 end
3129
3130
3131 opcodes.func = {}
3132
3133
3134 opcodes.func[opcodes.paint_0]= function()
3135 local res = error.ok
3136 res = complement_paint_switch()
3137 if res~=error.ok then
3138 GF.error("error in paint_0")
3139 res = error.paint[0]
3140 end
3141 return res
3142 end
3143
3144 --opcodes.func[opcodes.paint_1]= function() return paint(1) end
3145 --:
3146 --opcodes.func[opcodes.paint_63]= function() return paint(63) end
3147 for i=1, 63 do
3148 local key = format("paint_%d",i)
3149 local index = opcodes[key]
3150 opcodes.func[index] = function() return paint(i) end
3151 end
3152
3153 opcodes.func[opcodes.paint1]= function()
3154 local res = error.ok
3155 local b = byte(readbytes(1))
3156 if (64<=b and b<256) then
3157 paint(b)
3158 else
3159 GF.error("wrong value " ..tostring(b) .. " in paint1")
3160 res = error.paint1
3161 end
3162 return res
3163 end
3164
3165
3166 opcodes.func[opcodes.paint2]= function()
3167 local res = error.ok
3168 local b1 = byte(readbytes(1))
3169 local b2 = byte(readbytes(1))
3170 local b = b2+b1*256
3171 if (256<=b and b<65536) then
3172 paint(b)
3173 else
3174 GF.error("wrong value " ..tostring(b) .. " in paint2")
3175 res = error.paint2
3176 end
3177 return res
3178 end
3179
3180
3181
3182 opcodes.func[opcodes.paint3]= function()
3183 local res = error.ok
3184 local b1 = byte(readbytes(1))
3185 local b2 = byte(readbytes(1))
3186 local b3 = byte(readbytes(1))
3187 local b = b3+b2*256+ (b1*65536)
3188 if (65536<=b and b<16777216) then
3189 paint(b)
3190 else
3191 GF.error("wrong value " ..tostring(b) .. " in paint3")
3192 res = error.paint3
3193 end
3194 return res
3195 end
3196
3197
3198 opcodes.func[opcodes.boc]= function()
3199 local pos = gfdata_index
3200 local c = read4bytes()
3201 local p = read4bytes()
3202 local min_m = read4bytes()
3203 local max_m = read4bytes()
3204 local min_n = read4bytes()
3205 local max_n = read4bytes()
3206 current_char = c
3207 chars[current_char] = chars[current_char] or {}
3208 chars[current_char]['p'] = p
3209 chars[current_char]['max_m'] = max_m
3210 chars[current_char]['min_m'] = min_m
3211 chars[current_char]['max_n'] = max_n
3212 chars[current_char]['min_n'] = min_n
3213 chars[current_char]['opened'] = true
3214 chars[current_char]['stream_pos'] = gfdata_index
3215 chars[current_char]['max_col'] = max_m
3216 chars[current_char]['min_col'] = min_m
3217 chars[current_char]['max_row'] = max_n
3218 chars[current_char]['min_row'] = min_n
3219 current_col = min_m
3220 current_row = max_n
3221 chars[current_char][current_row]={}
3222 paint_switch = white
3223 return error.ok
3224 end
3225
3226
3227 opcodes.func[opcodes.boc1]= function()
3228 local pos = gfdata_index
3229 local c = byte(readbytes(1))
3230 local del_m = byte(readbytes(1))
3231 local max_m = byte(readbytes(1))
3232 local del_n = byte(readbytes(1))
3233 local max_n = byte(readbytes(1))
3234 local p = -1
3235 local min_m = max_m - del_m
3236 local min_n = max_n - del_n
3237 current_char = c
3238 chars[current_char] = chars[current_char] or {}
3239 chars[current_char]['p'] = p
3240 chars[current_char]['max_m'] = max_m
3241 chars[current_char]['min_m'] = min_m
3242 chars[current_char]['max_n'] = max_n
3243 chars[current_char]['min_n'] = min_n
3244 chars[current_char]['opened'] = true
3245 chars[current_char]['stream_pos'] = gfdata_index
3246 chars[current_char]['max_col'] = max_m
3247 chars[current_char]['min_col'] = min_m
3248 chars[current_char]['max_row'] = max_n
3249 chars[current_char]['min_row'] = min_n
3250 current_col = min_m
3251 current_row = max_n
3252 chars[current_char][current_row]={}
3253 paint_switch = white
3254 return error.ok
3255 end
3256
3257
3258 opcodes.func[opcodes.eoc]= function()
3259 local res = error.ok
3260 if chars[current_char].opened == true then
3261 chars[current_char].opened = false
3262 res = error.ok
3263 else
3264 GF.error("error closing char")
3265 res = error.eoc
3266 end
3267 --
3268 -- use them as stack to tie the nop
3269 -- opcodes to current_char
3270 table.insert(chars.xxx1,{current_char,-1})
3271 table.insert(chars.xxx2,{current_char,-1})
3272 table.insert(chars.xxx3,{current_char,-1})
3273 table.insert(chars.xxx4,{current_char,-1})
3274 table.insert(chars.yyy,{current_char,-1})
3275 table.insert(chars.nop,{current_char,-1})
3276 table.insert(chars.all_nop,{'eoc',current_char,-1})
3277 return res
3278 end
3279
3280
3281 opcodes.func[opcodes.skip0]= function()
3282 if chars[current_char]==nil or chars[current_char].min_m==nil then
3283 GF.error("error in skip0")
3284 return error.skip0
3285 end
3286 current_row = current_row -1
3287 current_col = chars[current_char].min_m
3288 paint_switch = white
3289 chars[current_char][current_row]={}
3290 return error.ok
3291 end
3292
3293
3294 opcodes.func[opcodes.skip1]= function()
3295 if chars[current_char]==nil or chars[current_char].min_m==nil then
3296 GF.error("error in skip1")
3297 return error.skip1
3298 end
3299 local b = byte(readbytes(1))
3300 current_row = current_row -(b+1)
3301 current_col = chars[current_char].min_m
3302 paint_switch = white
3303 chars[current_char][current_row]={}
3304 return error.ok
3305 end
3306
3307
3308 opcodes.func[opcodes.skip2]= function()
3309 if chars[current_char]==nil or chars[current_char].min_m==nil then
3310 GF.error("error in skip2")
3311 return error.skip2
3312 end
3313 local b0 = byte(readbytes(1))
3314 local b1 = byte(readbytes(1))
3315 local b = b1+256*b0
3316 current_row = current_row - (b+1)
3317 current_col = chars[current_char].min_m
3318 paint_switch = white
3319 chars[current_char][current_row]={}
3320 return error.ok
3321 end
3322
3323
3324 opcodes.func[opcodes.skip3]= function()
3325 if chars[current_char]==nil or chars[current_char].min_m==nil then
3326 GF.error("error in skip3 ")
3327 return error.skip3
3328 end
3329 local b0 = byte(readbytes(1))
3330 local b1 = byte(readbytes(1))
3331 local b2 = byte(readbytes(1))
3332 local b = b2+b1*256+b3*65536
3333 current_row = current_row - (b+1)
3334 current_col = chars[current_char].min_m
3335 paint_switch = white
3336 chars[current_char][current_row]={}
3337 return error.ok
3338 end
3339
3340
3341 local function new_row(n)
3342 if chars[current_char]==nil or chars[current_char].min_m==nil then
3343 GF.error("error in new_row_"..n)
3344 return error.new_row[n]
3345 end
3346 current_row = current_row - 1
3347 current_col = chars[current_char].min_m+n
3348 paint_switch = black
3349 chars[current_char][current_row]={}
3350 return error.ok
3351
3352 end
3353
3354 opcodes.func[opcodes.new_row_0]= function()
3355 if chars[current_char]==nil or chars[current_char].min_m==nil then
3356 GF.error("error in new_row_0")
3357 return error.new_row[0]
3358 end
3359 current_row = current_row - 1
3360 current_col = chars[current_char].min_m
3361 paint_switch = black
3362 chars[current_char][current_row]={}
3363 return error.ok
3364 end
3365
3366 --opcodes.func[opcodes.new_row_1]= function() new_row(1) end
3367 --:
3368 --opcodes.func[opcodes.new_row_164]= function() new_row(i)end
3369 for i=1, 164 do
3370 local key = format("new_row_%d",i)
3371 local index = opcodes[key]
3372 opcodes.func[index] = function() return new_row(i) end
3373 end
3374
3375 --opcodes.func[opcodes.max_new_row]= function()
3376 -- return new_row(opcodes.max_new_row)
3377 --end
3378
3379 opcodes.func[opcodes.xxx1]= function()
3380 local stream_pos = gfdata_index
3381 local b = byte(readbytes(1))
3382 local k = readbytes(b)
3383 table.insert(chars.xxx1,{k,stream_pos})
3384 table.insert(chars.all_nop,{'xxx1',k,stream_pos})
3385 return error.ok
3386 end
3387
3388 opcodes.func[opcodes.xxx2]= function()
3389 local stream_pos = gfdata_index
3390 local b0 = byte(readbytes(1))
3391 local b1 = byte(readbytes(1))
3392 local k = readbytes(b1+ b0*256)
3393 table.insert(chars.xxx2,{k,stream_pos})
3394 table.insert(chars.all_nop,{'xxx2',k,stream_pos})
3395 return error.ok
3396 end
3397
3398
3399 opcodes.func[opcodes.xxx3]= function()
3400 local stream_pos = gfdata_index
3401 local b0 = byte(readbytes(1))
3402 local b1 = byte(readbytes(1))
3403 local b2 = byte(readbytes(1))
3404 local k = readbytes(b2+ b1*256+b0*65536)
3405 table.insert(chars.xxx3,{k,stream_pos})
3406 table.insert(chars.all_nop,{'xxx3', k,stream_pos})
3407 return error.ok
3408 end
3409
3410 opcodes.func[opcodes.xxx4]= function()
3411 local stream_pos = gfdata_index
3412 local k = readbytes(read4bytes())
3413 -- k must be positive
3414 if k<=0 then
3415 k = k +4294967296
3416 end
3417 table.insert(chars.xxx4,{k,stream_pos})
3418 table.insert(chars.all_nop,{'xxx4',k,stream_pos})
3419 return error.ok
3420 end
3421
3422 opcodes.func[opcodes.yyy]= function()
3423 local stream_pos = gfdata_index
3424 local v = read4bytes()
3425 table.insert(chars.yyy,{v,stream_pos})
3426 table.insert(chars.all_nop,{'yyy',v,stream_pos})
3427 return error.ok
3428 end
3429
3430 opcodes.func[opcodes.nop]= function()
3431 table.insert(chars.nop,gfdata_index)
3432 table.insert(chars.all_nop,{'nop','',gfdata_index})
3433 return error.ok
3434 end
3435
3436 opcodes.func[opcodes.char_loc]= function()
3437 local c = byte(readbytes(1))
3438 local dx = read4bytes()
3439 local dy = read4bytes()
3440 local w = read4bytes()
3441 local p = read4bytes()
3442 local char_locator = {}
3443 char_locator['c'] = c
3444 char_locator['dx'] = dx
3445 char_locator['dy'] = dy
3446 char_locator['w'] = w
3447 char_locator['p'] = p
3448 table.insert(chars.locators,char_locator)
3449 return error.ok
3450 end
3451
3452
3453 opcodes.func[opcodes.char_loc0]= function()
3454 local c = byte(readbytes(1))
3455 local dm = byte(readbytes(1))
3456 local w = read4bytes()
3457 local p = read4bytes()
3458 local dy = 0
3459 local dx = 65536*dm
3460 local char_locator = {}
3461 char_locator['c'] = c
3462 char_locator['dx'] = dx
3463 char_locator['dy'] = dy
3464 char_locator['w'] = w
3465 char_locator['p'] = p
3466 table.insert(chars.locators,char_locator)
3467 return error.ok
3468 end
3469
3470
3471 opcodes.func[opcodes.pre]= function()
3472 local i = byte(readbytes(1))
3473 local k = byte(readbytes(1))
3474 local x = readbytes(k)
3475 chars.GF_format = i
3476 chars.GF_comment = x
3477 return error.ok
3478 end
3479
3480 opcodes.func[opcodes.post]= function()
3481 local p = read4bytes()
3482 local ds = read4bytes()
3483 local cs = read4bytes()
3484 local hppp = read4bytes()
3485 local vppp = read4bytes()
3486 local min_m = read4bytes()
3487 local max_m = read4bytes()
3488 local min_n = read4bytes()
3489 local max_n = read4bytes()
3490 chars['ds'] = ds
3491 chars['cs'] = cs
3492 chars['hppp'] = hppp
3493 chars['vppp'] = vppp
3494 chars['min_m'] = min_m
3495 chars['max_m'] = max_m
3496 chars['min_n'] = min_n
3497 chars['max_n'] = max_n
3498 return error.ok
3499 end
3500
3501 opcodes.func[opcodes.post_post]= function()
3502 local q = read4bytes()
3503 local i = byte(readbytes(1))
3504 local pad223 = readbytes(4)
3505 if ( pad223~='\223\223\223\223' ) then
3506 GF.error("error post_post_1 "..pad223)
3507 return error.post_post
3508 end
3509 if gfdata_index <=gfdata_len then
3510 local s = readuntileof()
3511 local ctr223 = rep('\223',len(s))
3512 if ctr223 ~= s then
3513 GF.error("error post_post_2 "..pad223)
3514 return error.post_post
3515 end
3516 end
3517 chars.GF_format_post = i
3518 return error.ok
3519 end
3520
3521 opcodes.func[opcodes.undefined_1]= function()
3522 GF.warning("undefined command 1")
3523 return error.ok
3524 end
3525 opcodes.func[opcodes.undefined_2]= function()
3526 GF.warning("undefined command 2")
3527 return error.ok
3528 end
3529 opcodes.func[opcodes.undefined_3]= function()
3530 GF.warning("undefined command 3")
3531 return error.ok
3532 end
3533 opcodes.func[opcodes.undefined_4]= function()
3534 GF.warning("undefined command 4")
3535 return error.ok
3536 end
3537 opcodes.func[opcodes.undefined_5]= function()
3538 GF.warning("undefined command 5")
3539 return error.ok
3540 end
3541 opcodes.func[opcodes.undefined_6]= function()
3542 GF.warning("undefined command 6")
3543 return error.ok
3544 end
3545
3546
3547
3548 --------------------------------------------------------------------------------
3549 --
3550 --------------------------------------------------------------------------------
3551
3552 local function load(gffile)
3553 gfdata = ''
3554 local f,res = io.open(gffile,'rb')
3555 if f==nil then
3556 GF.error(res)
3557 gfdata_index=0
3558 return error.load
3559 else
3560 gfdata = f:read("*a")
3561 gfdata_len = len(gfdata)
3562 gfdata_index =1
3563 end
3564 f:close()
3565 return error.ok
3566 end
3567
3568
3569 local function parse_pre()
3570 gfdata_index=1
3571 local res = error.ok
3572 local b = byte(readbytes(1))
3573 if b==opcodes.pre then
3574 local i=byte(readbytes(1))
3575 local k=byte(readbytes(1))
3576 local x=readbytes(k)
3577 chars.GF_format=i
3578 chars.comments=x
3579 else
3580 GF.error("error parsing pre")
3581 res = error.pre
3582 end
3583 return res
3584 end
3585
3586
3587 local function parse_rest()
3588 local b = byte(readbytes(1))
3589 local func = opcodes.func
3590 local res = error.ok
3591 local cond = true
3592 while (cond) do
3593 if func[b] then
3594 res = (func[b])()
3595 if res~=error.ok then
3596 cond = false
3597 elseif datanotfinished() then
3598 b = byte(readbytes(1))
3599 else
3600 res = error.ok
3601 cond = false
3602 end
3603 else
3604 cond = false
3605 GF.error("wrong opcode while parsing char")
3606 res = error.parsechar
3607 end
3608 end
3609 return res
3610 end
3611
3612
3613 local function parse()
3614 if gfdata_len == 0 then
3615 GF.error("no data")
3616 return error.parse
3617 end
3618 local res
3619 res = parse_pre()
3620 if res~=error.ok then
3621 GF.error("wrong preamble")
3622 return res
3623 end
3624 res = parse_rest()
3625 if not(res==error.ok) then
3626 GF.error("error while reading characters")
3627 return res
3628 end
3629 return res
3630 end
3631
3632
3633 ----------------------------------------------------------------------------------
3634 -- Parse from the end
3635 ----------------------------------------------------------------------------------
3636
3637 local function skip223()
3638 local i = gfdata_len
3639 local cond = true
3640 while cond do
3641 local c = byte(sub(gfdata,i,i))
3642 if c==223 then
3643 i=i-1
3644 else
3645 cond=false
3646 end
3647 end
3648 if i<3 then
3649 GF.error("error skip suffix ")
3650 res = error.skip223
3651 else
3652 res = error.ok
3653 gfdata_index = i
3654 end
3655 return res
3656 end
3657
3658
3659 local function parse_char_fromlocator()
3660 local cond = true
3661 local func = opcodes.func
3662 local b,res
3663 while cond do
3664 b = byte(readbytes(1))
3665 if func[b] then
3666 res = (func[b])()
3667 if res ~= error.ok then
3668 cond = false
3669 return res
3670 elseif b==opcodes.eoc then
3671 cond = false
3672 else
3673 cond = true
3674 end
3675 else
3676 GF.error("wrong char from locator")
3677 cond = false
3678 return error.parse
3679 end
3680 end
3681 if chars[current_char] and chars[current_char].p == -1 then
3682 return error.ok
3683 end
3684 moveindex_after(chars[current_char].p)
3685 return parse_char_fromlocator()
3686
3687 end
3688
3689 local function parse_from_end()
3690 if gfdata_len == 0 then
3691 GF.error("no data")
3692 return error.parse
3693 end
3694 local res = error.ok
3695 gfdata_index = gfdata_len
3696 res = skip223()
3697 if res ~= error.ok then
3698 return res
3699 end
3700 --
3701 -- read identification byte
3702 --
3703 chars.GF_format_post = byte(readbytes(-1))
3704 --
3705 -- read post_post
3706 --
3707 local q = readrev4bytes()
3708 if q<=0 then
3709 q = q +4294967296
3710 end
3711 if q<1 or q>gfdata_len then
3712 GF.error("wrong pointer to post")
3713 return error.parse
3714 end
3715 --
3716 -- reading post
3717 --
3718 moveindex_after(q)
3719 q = byte(readbytes(1))
3720 if q~=opcodes.post then
3721 GF.error("expected post opcode")
3722 return error.parse
3723 end
3724 --
3725 res = opcodes.func[opcodes.post]()
3726 if res~=error.ok then
3727 GF.error("reading postamble")
3728 return error.parse
3729 end
3730 --
3731 -- read char locators
3732 --
3733 local cond = true
3734 local char_loc = opcodes.char_loc
3735 local char_loc0 = opcodes.char_loc0
3736 local post_post = opcodes.post_post
3737 local f = opcodes.func
3738 while cond do
3739 q = byte(readbytes(1))
3740 if q==char_loc or q==char_loc0 then
3741 f[q]()
3742 elseif q==post_post then
3743 cond = false
3744 res = error.ok
3745 else
3746 GF.error("reading char locators")
3747 cond = false
3748 return error.parse
3749 end
3750 end
3751 --
3752 -- read chars
3753 --
3754 if #chars.locators == 0 then
3755 GF.error("no char locators")
3756 return error.parse
3757 end
3758 for i,v in ipairs(chars.locators) do
3759 local p = v.p
3760 if p>-1 then
3761 moveindex_after(p)
3762 res = parse_char_fromlocator()
3763 if res ~= error.ok then
3764 break;
3765 end
3766 end
3767 end
3768 return res
3769 end
3770
3771
3772 --------------------------------------------------------------------------------
3773
3774 -- Already assigned before:
3775 -- GF.warning = warning_msg
3776 -- GF.error = error_msg
3777 GF.load = load
3778 GF.parse = parse
3779 GF.chars = chars
3780 GF.errorcode = error
3781 GF.error_name = error_name
3782 GF.parse_from_end = parse_from_end
3783 --
3784 -- TODO: parsing by reading a file
3785 --
3786
3787
3788 end
3789 -- Add GF to the mflua table
3790 mflua.GF = GF