chiark / gitweb /
remove comments for debugging silent layer problem
[trains.git] / layout / layout
1 #!/usr/bin/perl -w
2
3 use POSIX;
4 use strict;
5 no strict 'subs';
6
7 our $scale= 7.0;
8 our $ptscale= 72/25.4 / $scale;
9
10 our $psu_ulen= 4.5;
11 our $psu_edgelw= 0.5;
12 our $psu_ticklw= 0.1;
13 our $psu_ticksperu= 1;
14 our $psu_ticklen= 5.0;
15 our $psu_gauge= 9;
16 our $psu_sleeperlen= 17;
17 our $psu_sleeperlw= 15;
18 our $psu_raillw= 1.0;
19 our $psu_thinlw= 1.0;
20
21 our $lmu_marklw= 4;
22 our $lmu_marktpt= 11;
23 our $lmu_txtboxtxty= $lmu_marktpt * 0.300;
24 our $lmu_txtboxh= $lmu_marktpt * 1.100;
25 our $lmu_txtboxpadx= $lmu_marktpt * 0.335;
26 our $lmu_txtboxoff= $lmu_marklw / 2;
27 our $lmu_txtboxlw= 1;
28
29 our $olu_left= 10 * $scale;
30 our $olu_right= 217 * $scale - $olu_left;
31 our $olu_bottom= 20 * $scale;
32 our $olu_top= 270 * $scale - $olu_bottom;
33 our $olu_gap_x= 30;
34 our $olu_gap_y= 30;
35 our $olu_textheight= 15;
36 our $olu_textallowperc= $lmu_marktpt * 5.0/11;
37
38 our $pi= atan2(0,-1);
39 our $output_layer= '*';
40
41 sub allwidth2 ($) {
42     my ($radius)= @_;
43     return 27 unless defined $radius;
44     $radius= abs($radius);
45     return ($radius >= 450 ? 33 :
46             $radius >= 400 ? 35 :
47             37);
48 }
49 sub allwidth ($) { return allwidth2($_[0]) * 0.5; }
50
51 our $allwidthmax= allwidth(0);
52 our $allwidthmin= allwidth(undef);
53
54 # Data structures:
55 #  $ctx->{CmdLog}= undef                  } not in defobj
56 #  $ctx->{CmdLog}[]= [ command args ]     } in defobj
57 #  $ctx->{LocsMade}[]{Id}= $id
58 #  $ctx->{LocsMade}[]{Neg}= 1 or 0
59 #  $ctx->{Loc}{$id}{X}
60 #  $ctx->{Loc}{$id}{Y}
61 #  $ctx->{Loc}{$id}{A}
62 #  $ctx->{Loc}{$id}{LayerKind}
63 #  $ctx->{Trans}{X}       # transformation.  is ev representing
64 #  $ctx->{Trans}{Y}       # new origin.  (is applied at _input_
65 #  $ctx->{Trans}{A}       # not at plot-time)
66 #  $ctx->{Trans}{R}       # but multiply all y coords by this!
67 #  $ctx->{Draw}           # sequence of one or more chrs from uc $drawers
68 #                         #  possibly including X meaning never draw
69 #                         #  anything now (eg in defobj)
70 #  $ctx->{DrawMap}        # =$fn s.t.
71 #                         #  &$fn($drawchrs_spec_by_layer_cmdline)
72 #                         #   = $drawchrs_we_should_use_due_to_obj_etc
73 #  $ctx->{Layer}{Level}
74 #  $ctx->{Layer}{Kind}
75 #
76 #  $objs{$id}{CmdLog}
77 #  $objs{$id}{Loc}
78 #  $objs{$id}{Part}       # 1 iff object is a part
79 #
80 #  $eopts[]{GlobRe}       # regexp for K
81 #  $eopts[]{LayerCheck}   # =$fn where &$fn($l) is true iff layer matches
82 #  $eopts[]{DrawMods}     # modifier chars for drawing
83
84 our $ctx;
85 our %objs;
86 our @eopts;
87 our @al; # current cmd
88
89 our $o='';
90 our $ol='';
91
92 our $param; # for parametric_curve
93 our $debug=0;
94
95 # ev_... functions
96 #
97 # Operate on Enhanced Vectors which are a location (coordinates) and a
98 # direction at that location.  Representation is a hash with members X
99 # Y and A (angle of the direction in radians, anticlockwise from
100 # East).  May be absolute, or interpreted as relative, according to
101 # context.
102 #
103 # Each function's first argument is a hashref whose X Y A members will
104 # be created or overwritten; this hashref will be returned (so you can
105 # use it `functionally' by passing {}).  The other arguments may be ev
106 # hashrefs, or other info.  The results are in general undefined if
107 # one of the arguments is the same hash as the result.
108
109 sub ev_byang ($$;$) {
110     # ev_byang(R, ANG,[LEN])
111     # result is evec LEN (default=1.0) from origin pointing in direction ANG
112     my ($res,$ang,$len)=@_;
113     $len=1.0 unless defined $len;
114     $res->{X}= $len * cos($ang);
115     $res->{Y}= $len * sin($ang);
116     $res->{A}= $ang;
117     $res;
118 }
119 sub ev_compose ($$$) {
120     # ev_compose(SUM_R, A,B);
121     # appends B to A, result is end of new B
122     # (B's X is forwards from end of A, Y is translating left from end of A)
123     # A may have a member R, which if provided then it should be 1.0 or -1.0,
124     # and B's Y and A will be multiplied by R first (ie, we can reflect);
125     my ($sum,$a,$b) = @_;
126     my ($r);
127     $r= defined $a->{R} ? $a->{R} : 1.0;
128     $sum->{X}= $a->{X} + $b->{X} * cos($a->{A}) - $r * $b->{Y} * sin($a->{A});
129     $sum->{Y}= $a->{Y} + $r * $b->{Y} * cos($a->{A}) + $b->{X} * sin($a->{A});
130     $sum->{A}= $a->{A} + $r * $b->{A};
131     $sum;
132 }
133 sub ev_decompose ($$$) {
134     # ev_decompose(B_R, A,SUM)
135     # computes B_R s.t. ev_compose({}, A, B_R) gives SUM
136     my ($b,$a,$sum)=@_;
137     my ($r,$brx,$bry);
138     $r= defined $a->{R} ? $a->{R} : 1.0;
139     $brx= $sum->{X} - $a->{X};
140     $bry= $r * ($sum->{Y} - $a->{Y});
141     $b->{X}= $brx * cos($a->{A}) + $bry * sin($a->{A});
142     $b->{Y}= $bry * cos($a->{A}) - $brx * sin($a->{A});
143     $b->{A}= $r * ($sum->{A} - $a->{A});
144     $b;
145 }
146 sub ev_lincomb ($$$$) {
147     # ev_linkcomb(RES,A,B,P)
148     # gives P*A + (1-P)*B
149     my ($r,$a,$b,$p) = @_;
150     my ($q) = 1.0-$p;
151     map { $r->{$_} = $q * $a->{$_} + $p * $b->{$_} } qw(X Y A);
152     $r;
153 }
154 sub a_normalise ($$) {
155     # a_normalise(A,Z)
156     # adds or subtracts 2*$pi to/from A until it is in [ Z , Z+2*$pi >
157     my ($a,$z)=@_;
158     my ($r);
159     $r= $z + fmod($a - $z, 2.0*$pi);
160     $r += 2*$pi if $r < $z;
161     return $r;
162 }
163 sub ev_bearing ($$) {
164     # ev_bearing(A,B)
165     # returns bearing of B from A
166     # value returned is in [ A->{A}, A->{A} + 2*$pi >
167     # A->{A} and B->{A} are otherwise ignored
168     my ($a,$b)= @_;
169     my ($r);
170     $r= atan2($b->{Y} - $a->{Y},
171               $b->{X} - $a->{X});
172     $r= a_normalise($r,$a->{A});
173     return $r;
174 }
175
176 sub v_rotateright ($) {
177     # v_rotateright(A)
178     # returns image of A rotated 90 deg clockwise
179     my ($a)= @_;
180     return { X => $a->{Y}, Y => -$a->{X} };
181 }
182 sub v_dotproduct ($$) {
183     # v_dotproduct(A,B)
184     my ($a,$b)= @_;
185     return $a->{X} * $b->{X} + $a->{Y} * $b->{Y};
186 }
187 sub v_scalarmult ($$) {
188     # v_scalarmult(S,V)
189     # multiplies V by scalar S and returns product
190     my ($s,$v)=@_;
191     return { X => $s * $v->{X}, Y => $s * $v->{Y} };
192 }
193 sub v_add ($;@) {
194     # v_add(A,B,...)
195     # vector sum of all inputs
196     my (@i) = @_;
197     my ($r,$i);
198     $r= { X => 0.0, Y => 0.0 };
199     foreach $i (@i) { $r->{X} += $i->{X}; $r->{Y} += $i->{Y}; }
200     return $r;
201 }    
202 sub v_subtract ($$) {
203     # v_subtract(A,B)
204     # returns vector from A to B, ie B - A
205     my ($a,$b)= @_;
206     return { X => $b->{X} - $a->{X},
207              Y => $b->{Y} - $a->{Y} };
208 }
209 sub v_len ($) {
210     # v_len(V)
211     # scalar length of V
212     my ($v)=@_;
213     my ($x,$y) = ($v->{X}, $v->{Y});
214     return sqrt($x*$x + $y*$y);
215 }
216 sub v_dist ($$) {
217     # v_dist(A,B)
218     # returns distance from A to B
219     return v_len(v_subtract($_[0],$_[1]));
220 }
221
222 sub upd_min ($$) {
223     my ($limr,$now)=@_;
224     $$limr= $now unless defined $$limr && $$limr <= $now;
225 }
226 sub upd_max ($$) {
227     my ($limr,$now)=@_;
228     $$limr= $now unless defined $$limr && $$limr >= $now;
229 }
230
231 sub canf ($$) {
232     my ($converter,$defaulter)=@_;
233     my ($spec,$v);
234     return &$defaulter unless @al;
235     $spec= shift @al;
236     $v= &$converter($spec);
237     dv('canf ','$spec',$spec, '$v',$v);
238     return $v;
239 }
240 sub can ($) { my ($c)=@_; canf($c, sub { die "too few args"; }); }
241 sub cano ($$) { my ($c,$def)=@_; canf($c, sub { return $def }); }
242
243 sub signum ($) { return ($_[0] > 0) - ($_[0] < 0); }
244
245 sub bbox ($) {
246     my ($objhash) = @_;
247     my ($min_x, $max_x, $min_y, $max_y);
248     my ($loc);
249     foreach $loc (values %$objhash) {
250         upd_min(\$min_x, $loc->{X} - abs($allwidthmax * sin($loc->{A})));
251         upd_max(\$max_x, $loc->{X} + abs($allwidthmax * sin($loc->{A})));
252         upd_min(\$min_y, $loc->{Y} - abs($allwidthmax * cos($loc->{A})));
253         upd_max(\$max_y, $loc->{Y} + abs($allwidthmax * cos($loc->{A})));
254     }
255     return ($min_x, $max_x, $min_y, $max_y);
256 }
257
258 our %units_len= qw(- mm  mm 1  cm 10  m 1000);
259 our %units_ang= qw(- d   r 1); $units_ang{'d'}= 2*$pi / 360;
260
261 sub cva_len ($) { my ($sp)=@_; cva_units($sp,\%units_len); }
262 sub cva_identity ($) { my ($sp)=@_; $sp; }
263 sub cva_ang ($) { my ($sp)=@_; cva_units($sp,\%units_ang); }
264 sub cva_absang ($) { input_absang(cva_ang($_[0])) }
265 sub cva_units ($$) {
266     my ($sp,$ua)=@_;
267     my ($n,$u,$r);
268     $sp =~ m/^([-0-9eE.]*[0-9.])([A-Za-z]*)$/
269         or die "lexically invalid quantity";
270     ($n,$u)= ($1,$2);
271     $u=$ua->{'-'} unless length $u;
272     defined $ua->{$u} or die "unknown unit $u";
273     $r= $n * $ua->{$u};
274     print DEBUG "cva_units($sp,)=$r ($n $u $ua->{$u})\n";
275     return $r;
276 }
277 sub cva_idstr ($) {
278     my ($sp)=@_;
279     die "invalid id" unless $sp =~ m/^[a-z][_0-9A-Za-z]*$/;
280     return $&;
281 }
282 sub cva_idex ($) {
283     my ($sp)=@_;
284     my ($id,$r,$d,$k,$neg,$na,$obj_id,$vflip,$locs);
285     if ($sp =~ s/^(\^?)(\w+)\!//) {
286         $vflip= length($1);
287         $obj_id= $2;
288         die "invalid obj $obj_id in loc" unless exists $objs{$obj_id};
289         $locs= $objs{$obj_id}{Loc};
290     } else {
291         $locs= $ctx->{Loc};
292         $vflip= 0;
293     }
294     $neg= $sp =~ s/^\-//;
295     $id= cva_idstr($sp);
296     die "unknown $id" unless defined $locs->{$id};
297     $r= $locs->{$id};
298     $d= "idex $id";
299     foreach $k (sort keys %$r) { $d .= " $k=$r->{$k}"; }
300     printf DEBUG "%s\n", $d;
301     if ($vflip) {
302         $r= { X => $r->{X}, Y => -$r->{Y}, A => -$r->{A} };
303     }
304     if ($neg) {
305         $na= $r->{A} + $pi;
306         $na= a_normalise($na,0);
307         $r= { X => $r->{X}, Y => $r->{Y}, A => $na };
308     }
309     return $r;
310 }
311 sub cva_idnew ($) {
312     my ($sp)=@_;
313     my ($id, $neg);
314     $neg = $sp =~ s/^\-//;
315     $id=cva_idstr($sp);
316     die "duplicate $id" if exists $ctx->{Loc}{$id};
317     $ctx->{Loc}{$id}{LayerKind}= $ctx->{Layer}{Kind};
318     push @{ $ctx->{LocsMade} }, {
319         Id => $id,
320         Neg => $neg,
321     };
322     return $ctx->{Loc}{$id};
323 }
324 sub cva_cmd ($) { return cva_idstr($_[0]); }
325 sub cva__enum ($$) {
326     my ($sp,$el)=@_;
327     return $sp if grep { $_ eq $sp } @$el;
328     die "invalid option (permitted: @$el)";
329 }
330 sub cvam_enum { my (@e) = @_; return sub { cva__enum($_[0],\@e); }; }
331
332 sub cmd_abs {
333     my ($i,$nl);
334     $nl= can(\&cva_idnew);
335     $i->{X}= can(\&cva_len);
336     $i->{Y}= can(\&cva_len);
337     $i->{A}= can(\&cva_ang);
338     ev_compose($nl, $ctx->{Trans}, $i);
339 }
340 sub cmd_rel {
341     my ($from,$to,$len,$right,$turn);
342     $from= can(\&cva_idex);
343     $to= can(\&cva_idnew);
344     $len= cano(\&cva_len,0);
345     $right= cano(\&cva_len,0) * $ctx->{Trans}{R};
346     $turn= cano(\&cva_ang, 0) * $ctx->{Trans}{R};
347     my ($u)= ev_compose({}, $from, { X => $len, Y => -$right, A => 0 });
348     ev_compose($to, $u, { X => 0, Y => 0, A => $turn });
349 }
350
351 sub dv__evreff ($) {
352     my ($pfx) = @_;
353     $pfx . ($pfx =~ m/\}$|\]$/ ? '' : '->');
354 }
355 sub dv__evr ($) {
356     my ($v) = @_;
357     return 'undef' if !defined $v;
358     return $v if $v !~ m/\W/ && $v =~ m/[A-Z]/ && $v =~ m/^[a-z_]/i;
359     return $v if $v =~ m/^[0-9.]+/;
360     $v =~ s/[\\\']/\\$&/g;
361     return "'$v'";
362 }
363 sub dv1 ($$$);
364 sub dv1_kind ($$$$$$$) {
365     my ($pfx,$expr,$ref,$ref_exp,$ixfmt,$ixesfn,$ixmapfn) = @_;
366     my ($ix,$any);
367     return 0 if $ref ne $ref_exp;
368     $any=0;
369     foreach $ix (&$ixesfn) {
370         $any=1;
371         my ($v)= &$ixmapfn($ix);
372 #print STDERR "dv1_kind($pfx,$expr,$ref,$ref_exp,$ixmapfn) ix=$ix v=$v\n";
373         dv1($pfx,$expr.sprintf($ixfmt,dv__evr($ix)),$v);
374     }
375     if (!$any) {
376         printf DEBUG "%s%s= $ixfmt\n", $pfx, $expr, ' ';
377     }
378     1;
379 }    
380 sub dv1 ($$$) {
381     return 0 unless $debug;
382     my ($pfx,$expr,$v) = @_;
383     my ($ref);
384     $ref= ref $v;
385 #print STDERR "dv1 >$pfx|$ref<\n";
386     if (!$ref) {
387         printf DEBUG "%s%s= %s\n", $pfx,$expr, dv__evr($v);
388         return;
389     } elsif ($ref eq 'SCALAR') {
390         dv1($pfx, ($expr =~ m/^\$/ ? "\$$expr" : '${'.$expr.'}'), $$v);
391         return;
392     }
393     $expr.='->' unless $expr =~ m/\]$|\}$/;
394     return if dv1_kind($pfx,$expr,$ref,'ARRAY','[%s]',
395                        sub { ($[ .. $#$v) },
396                        sub { $v->[$_[0]] });
397     return if dv1_kind($pfx,$expr,$ref,'HASH','{%s}',
398                        sub { sort keys %$v },
399                        sub { $v->{$_[0]} });
400     printf DEBUG "%s%s is %s\n", $pfx, $expr, $ref;
401 }
402     
403 sub dv {
404     my ($pfx,@l) = @_;
405     my ($expr,$v,$ref);
406     while (@l) {
407         ($expr,$v,@l)=@l;
408         dv1($pfx,$expr,$v);
409     }
410 }                   
411
412 sub o ($) { $o .= $_[0]; }
413 sub ol ($) { $ol .= $_[0]; }
414 sub oflushpage () {
415     print $o, $ol, "  showpage\n"
416         or die $!;
417     $o=$ol='';
418 }
419
420 our $o_path_verb;
421
422 sub o_path_begin () {
423     o("      newpath\n");
424     $o_path_verb= 'moveto';
425 }
426 sub o_path_point ($) {
427     my ($pt)=@_;
428     o("        $pt $o_path_verb\n");
429     $o_path_verb= 'lineto';
430 }
431 sub o_path_stroke ($) {
432     my ($width)=@_;
433     o("        $width setlinewidth stroke\n");
434 }    
435
436 sub o_line ($$$) {
437     my ($a,$b,$width)=@_;
438     o_path_begin();
439     o_path_point($a);
440     o_path_point($b);
441     o_path_stroke($width);
442 }
443
444 sub current_draw () {
445     my ($r);
446     $r= $ctx->{Draw} =~ m/X/ ? '' : $ctx->{Draw};
447     $r;
448 }
449
450 sub psu_coords ($$$) {
451     my ($ends,$inunit,$across)=@_;
452     # $ends->[0]{X} etc.; $inunit 0 to 1 (but go to 1.5);
453     # $across in mm, +ve to right.
454     my (%ea_zo, $zo, $prop);
455     $ea_zo{X}=$ea_zo{Y}=0;
456     foreach $zo (qw(0 1)) {
457         $prop= $zo ? $inunit : (1.0 - $inunit);
458         $ea_zo{X} += $prop * ($ends->[$zo]{X} - $across * sin($ends->[0]{A}));
459         $ea_zo{Y} += $prop * ($ends->[$zo]{Y} + $across * cos($ends->[0]{A}));
460     }
461 #    dv("psu_coords ", '$ends',$ends, '$inunit',$inunit, '$across',$across,
462 #       '\\%ea_zo', \%ea_zo);
463     return $ea_zo{X}." ".$ea_zo{Y};
464 }
465
466 sub parametric__o_pt ($) {
467     my ($pt)=@_;
468     o_path_point("$pt->{X} $pt->{Y}");
469 }
470
471 sub parametric_segment ($$$$$) {
472     my ($p0,$p1,$lenperp,$minradius,$calcfn) = @_;
473     # makes $p (global) go from $p0 to $p1  ($p1>$p0)
474     # $lenperp is the length of one unit p, ie the curve
475     # must have a uniform `density' in parameter space
476     # $calcfn is invoked with $p set and should return a loc
477     # (ie, ref to X =>, Y =>, A =>).
478     my ($pa,$pb,@ends,$side,$ppu,$e,$v,$tick,$draw,$allwidth);
479     return unless $ctx->{Draw} =~ m/[ARSC]/;
480     $ppu= $psu_ulen/$lenperp;
481     $allwidth= allwidth($minradius);
482     my ($railctr)=($psu_gauge + $psu_raillw)*0.5;
483     my ($tickend)=($allwidth - $psu_ticklen);
484     my ($tickpitch)=($psu_ulen / $psu_ticksperu);
485     my ($sleeperctr)=($psu_ulen*0.5);
486     my ($sleeperend)=($psu_sleeperlen*0.5);
487 print DEBUG "ps $p0 $p1 $lenperp ($ppu)\n";
488     $draw= current_draw();
489     if ($draw =~ m/C/) {
490         my ($pt);
491         o("    $psu_thinlw setlinewidth\n");
492         o_path_begin();
493         for ($param=$p0; $param<$p1; $param += $ppu) {
494             parametric__o_pt(&$calcfn);
495         }
496         $param=$p1;
497         parametric__o_pt(&$calcfn);
498         o("      stroke\n");
499     }
500     return unless $draw =~ m/[ARS]/;
501     for ($pa= $p0; $pa<$p1; $pa=$pb) {
502         $pb= $pa + $ppu;
503         $param= $pa; $ends[0]= @ends ? $ends[1] : &$calcfn;
504         $param= $pb; $ends[1]= &$calcfn;
505 #print DEBUG "pa $pa $ends[0]{X} $ends[0]{Y} $ends[0]{A}\n";
506 #print DEBUG "pb $pb $ends[1]{X} $ends[1]{Y} $ends[1]{A}\n";
507         $e= $pb<=$p1 ? 1.0 : ($p1-$pa)/$ppu;
508         o("    gsave\n");
509         o_path_begin();
510         o_path_point(psu_coords(\@ends,0,-$allwidth));
511         o_path_point(psu_coords(\@ends,0,$allwidth));
512         o_path_point(psu_coords(\@ends,$e,$allwidth));
513         o_path_point(psu_coords(\@ends,$e,-$allwidth));
514         o("        closepath clip\n");
515         foreach $side qw(-1 1) {
516             if ($draw =~ m/R/) {
517                 o_line(psu_coords(\@ends,0,$side*$railctr),
518                        psu_coords(\@ends,1.5,$side*$railctr),
519                        $psu_raillw);
520             }
521         }
522         if ($draw =~ m/S/) {
523             o_line(psu_coords(\@ends,$sleeperctr,-$sleeperend),
524                    psu_coords(\@ends,$sleeperctr,+$sleeperend),
525                    $psu_sleeperlw);
526         }
527         if ($draw =~ m/A/) {
528             o("        0.5 setgray\n");
529             foreach $side qw(-1 1) {
530                 o_line(psu_coords(\@ends,0,$side*$allwidth),
531                        psu_coords(\@ends,1.5,$side*$allwidth),
532                        $psu_edgelw);
533                 for ($tick=0; $tick<1.5; $tick+=$tickpitch/$psu_ulen) {
534                     o_line(psu_coords(\@ends,$tick,$side*$allwidth),
535                            psu_coords(\@ends,$tick,$side*$tickend),
536                            $psu_ticklw);
537                 }
538             }
539         }
540         o("      grestore\n");
541     }
542 }
543
544 sub arc ($$$$$) {
545     my ($to, $ctr,$from, $radius,$delta) = @_;
546     # does parametric_segment to draw an arc centred on $ctr
547     # ($ctr->{A} ignored)
548     # from $from with radius $radius (this must be consistent!)
549     # and directionally-subtending an angle $delta.
550     # sets $to->... to be the other end, and returns $to
551     my ($beta);
552     $to->{A}= $beta= $from->{A} + $delta;
553     $to->{X}= $ctr->{X} - $radius * sin($beta);
554     $to->{Y}= $ctr->{Y} + $radius * cos($beta);
555     return if abs($delta*$radius) < 1e-9;
556     parametric_segment(0.0,1.0, abs($radius*$delta), $radius, sub {
557         my ($beta) = $from->{A} + $delta * $param;
558         return { X => $ctr->{X} - $radius * sin($beta),
559                  Y => $ctr->{Y} + $radius * cos($beta),
560                  A => $beta }
561     });
562 }
563
564 # joins_xxx all take $results, $from, $to, $minradius
565 # where $results->[]{Path}{K} etc. and $results->[]{SolKinds}[]
566
567 sub joins_twoarcs ($$$$) {
568     my ($results, $from,$to,$minradius) = @_;
569     # two circular arcs of equal maximum possible radius
570     # algorithm courtesy of Simon Tatham (`Railway problem',
571     # pers.comm. to ijackson@chiark 23.1.2004)
572     my ($sigma,$distfact, $theta,$phi, $a,$b,$c,$d, $m,$r, $radius);
573     my ($cvec,$cfrom,$cto,$midpt, $delta1,$delta2, $path,$reverse);
574     $sigma= ev_bearing($from,$to);
575     $distfact= v_dist($from,$to);
576     $theta= 0.5 * $pi - ($from->{A} - $sigma);
577     $phi=   0.5 * $pi - ($to->{A} + $pi - $sigma);
578     $a= 2 * (1 + cos($theta - $phi));
579     $b= 2 * (cos($theta) - cos($phi));
580     $c= -1;
581     $d= sqrt($b*$b - 4*$a*$c);
582     o("%     twoarcs theta=".ang2deg($theta)." phi=".ang2deg($phi).
583       " ${a}r^2 + ${b}r + ${c} = 0\n");
584     foreach $m (qw(-1 1)) {
585         if ($a < 1e-6) {
586             o("%     twoarcs $m insoluble\n");
587             next;
588         }
589         $r= -0.5 * (-$b + $m*$d) / $a;
590         $radius= -$r * $distfact;
591         o("%     twoarcs $m radius $radius ");
592         if (abs($radius) < $minradius) { o("too-small\n"); next; }
593         $cfrom=  ev_compose({}, $from, { X=>0, Y=>-$radius, A=>-0.5*$pi });
594         $cto=    ev_compose({}, $to,   { X=>0, Y=> $radius, A=> 0.5*$pi });
595         $midpt=  ev_lincomb({}, $cfrom, $cto, 0.5);
596         $reverse= signum($r);
597         if ($reverse<0) {
598             $cfrom->{A} += $pi;
599             $cto->{A} += $pi;
600         }
601         $delta1= ev_bearing($cfrom, $midpt) - $cfrom->{A};
602         $delta2= ev_bearing($cto,   $midpt) - $cto->{A};
603         o("ok deltas ".ang2deg($delta1)." ".ang2deg($delta2)."\n");
604         if ($reverse<0) {
605             $delta1 -= 2*$pi;
606             $delta2 -= 2*$pi;
607         }
608         my ($fs);
609         $path= [{ T=>Arc, F=>$from, C=>$cfrom, R=> $radius, D=>$delta1 },
610                 { T=>Arc, F=>$to,   C=>$cto,   R=>-$radius, D=>$delta2 }];
611         push @$results, { Path => $path,
612                           SolKinds =>  [ 'twoarcs', 'cross' ] };
613     }
614 }
615     
616 sub joins_arcsline ($$$$) {
617     my ($results, $from,$to,$minradius) = @_;
618     # two circular arcs of specified radius
619     # with an intervening straight
620     my ($lr,$inv, $c,$d,$alpha,$t,$k,$l,$rpmsina,$rcosa,$linelen, $path);
621     if ($minradius<=1e-6) { o("%     arcsline no-radius\n"); return; }
622     foreach $lr (qw(-1 +1)) {
623         foreach $inv (qw(-1 +1)) {
624             $c=ev_compose({},$from,{X=>0,Y=>-$lr*$minradius, A=>0 });
625             $d=ev_compose({},$to,{X=>0, Y=>-$inv*$lr*$minradius, A=>$pi });
626             $t= v_dist($c,$d);
627             o("%     arcsline $lr $inv t=$t ");
628             if ($t < 1e-6) { o("concentric"); next; }
629             $c->{A}= $d->{A}= ev_bearing($c,$d);
630             o("bearing ".ang2deg($c->{A}));
631             if ($inv>0) {
632                 o("\n");
633                 $k= ev_compose({}, $c, { X=>0, Y=>$lr*$minradius, A=>0 });
634                 $l= ev_compose({}, $d, { X=>0, Y=>$lr*$minradius, A=>0 });
635                 $linelen= $t;
636             } else {
637                 my ($cosalpha) = 2.0 * $minradius / $t;
638                 if ($cosalpha > (1.0 - 1e-6)) { o(" too-close\n"); next; }
639                 $alpha= acos($cosalpha);
640                 $rpmsina= $lr * $minradius * sin($alpha);
641                 $rcosa= $minradius * $cosalpha;
642                 $k= ev_compose({}, $c, { X=>$rcosa, Y=>$rpmsina, A=>0 });
643                 $l= ev_compose({}, $d, { X=>-$rcosa, Y=>-$rpmsina, A=>0 });
644                 $k->{A}= $l->{A}= ev_bearing($k,$l);
645                 o(" alpha=".ang2deg($alpha)." kl^=".ang2deg($k->{A})."\n");
646                 $linelen= v_dist($k,$l);
647             }
648             $path= [{ T => Arc, F => $from, C => $c,
649                       R =>$lr*$minradius,
650                       D => -$lr * a_normalise
651                           ($lr * ($from->{A} - $k->{A}), 0) },
652                     { T => Line, A => $k, B => $l, L => $linelen },
653                     { T => Arc, F => $l, C => $d,
654                       R => $inv*$lr*$minradius,
655                       D => -$lr*$inv * a_normalise
656                           (-$lr*$inv * ($to->{A} - $l->{A}), 0) }];
657             push @$results,
658             { Path => $path,
659               SolKinds => [ 'arcsline', ($inv<0 ? 'cross' : 'loop') ] };
660         }
661     }
662 }
663
664 sub joins_arcline ($$$$) {
665     my ($results, $from,$to,$minradius) = @_;
666     # one circular arc and a straight line
667     my ($swap,$echoice,$path, $ap,$bp,$av,$bv, $e,$f, $ae,$af,$afae);
668     my ($dak,$ak,$kj,$k,$j,$aja,$jl,$l,$jc,$lc,$c,$rj,$rb);
669     foreach $swap (qw(-1 +1)) {
670         foreach $echoice (qw(0 1)) {
671             $ap= $from; $bp= { %$to }; $bp->{A} += $pi;
672             ($ap,$bp)= ($bp,$ap) if $swap<0;
673             $av= ev_byang({}, $ap->{A});
674             $bv= ev_byang({}, $bp->{A});
675             $e= ev_byang({}, 0.5 * ($ap->{A} + $bp->{A} + $echoice * $pi));
676             $f= v_rotateright($e);
677             o("%     arcline $swap $echoice e ".loc2dbg($e)."\n");
678             $ae= v_dotproduct($av,$e);
679             $af= v_dotproduct($av,$f);
680             o("%     arcline $swap $echoice a.e=$ae a.f=$af ");
681             if (abs($ae) < 1e-6) { o(" singular\n"); next; }
682             $afae= $af/$ae;
683             o("a.f/a.e=$afae\n");
684             $dak= v_dotproduct(v_subtract($ap,$bp), $e);
685             $ak= v_scalarmult($dak, $e);
686             $kj= v_scalarmult($dak * $afae, $f);
687             $k= v_add($ap, $ak);
688             $j= v_add($k, $kj);
689             $aja= v_dotproduct(v_subtract($ap,$j), $av);
690             o("%     arcline $swap $echoice d_ak=$dak aj.a=$aja ");
691             if ($aja < 0) { o(" backwards aj\n"); next; }
692             $jl= v_scalarmult(0.5, v_subtract($j, $bp));
693             $lc= v_scalarmult(-v_dotproduct($jl, $f) * $afae, $e);
694             $l= v_add($j, $jl);
695             $c= v_add($l, $lc);
696             $rj= v_dotproduct(v_subtract($j,$c), v_rotateright($av));
697             $rb= v_dotproduct(v_subtract($c,$bp), v_rotateright($bv));
698             o("r_j=$rj r_b=$rb ");
699             if ($rj * $rb < 0) { o(" backwards b\n"); next; }
700             if (abs($rj) < $minradius) { o(" too-small\n"); next; }
701             o("ok\n");
702             $j->{A}= $ap->{A};
703             $c->{A}= 0;
704             $path= [{ T => Line, A => $ap, B => $j, L => $aja },
705                     { T => Arc, F => $j, C => $c, R => $rj,
706                       D => -signum($rj) * a_normalise
707                           (-signum($rj) * ($bp->{A} + $pi - $j->{A}), 0) }];
708             $path= [ reverse @$path ] if $swap<0;
709             push @$results, { Path => $path, SolKinds =>  [ 'arcline' ] };
710         }
711     }
712 }
713
714 sub cmd_join {
715     my ($from,$to,$minradius);
716     my (@results,$result);
717     my ($path,$segment,$bestpath,$len,$scores,$bestscores,@bends,$skl);
718     my ($crit,$cs,$i,$cmp);
719     $from= can(\&cva_idex);
720     $to= can(\&cva_idex);
721     $minradius= can(\&cva_len);
722     o("%   join ".loc2dbg($from)."..".loc2dbg($to)." $minradius\n");
723     joins_twoarcs(\@results, $from,$to,$minradius);
724     joins_arcsline(\@results, $from,$to,$minradius);
725     joins_arcline(\@results, $from,$to,$minradius);
726     foreach $result (@results) {
727         $path= $result->{Path};
728         $skl= $result->{SolKinds};
729         o("%   possible path @$skl $path\n");
730         $len= 0;
731         @bends= ();
732         foreach $segment (@$path) {
733             if ($segment->{T} eq Arc) {
734                 o("%     Arc C ".loc2dbg($segment->{C}).
735                   " R $segment->{R} D ".ang2deg($segment->{D})."\n");
736                 $len += abs($segment->{R} * $segment->{D});
737                 push @bends, -abs($segment->{R}) * $segment->{D}; # right +ve
738             } elsif ($segment->{T} eq Line) {
739                 o("%     Line A ".loc2dbg($segment->{A}).
740                   " B ".loc2dbg($segment->{A})." L $segment->{L}\n");
741                 $len += abs($segment->{L});
742             } else {
743                 die "unknown segment $segment->{T}";
744             }
745         }
746         o("%    length $len bends @bends.\n");
747         $scores= [];
748         foreach $crit (@al, 'short') {
749             if ($crit eq 'long') { $cs= $len; }
750             elsif ($crit eq 'short') { $cs= -$len; }
751             elsif ($crit =~ m/^(begin|end|)(left|right)$/) {
752                 if ($1 eq 'begin') { $cs= $bends[0]; }
753                 elsif ($1 eq 'end') { $cs= $bends[$#bends]; }
754                 else { $cs=0; map { $cs += $_ } @bends; }
755                 $cs= -$cs if $2 eq 'left';
756             } elsif ($crit =~ m/^(\!?)(twoarcs|arcs?line|cross|loop)$/) {
757                 $cs= !!(grep { $2 eq $_ } @$skl) != ($1 eq '!');
758             } else {
759                 die "unknown sort criterion $crit";
760             }
761             push @$scores, $cs;
762         }
763         o("%    scores @$scores\n");
764         if (defined $bestpath) {
765             for ($i=0,$cmp=0; !$cmp && $i<@$scores; $i++) {
766                 $cmp= $scores->[$i] <=> $bestscores->[$i];
767             }
768             next if $cmp < 0;
769         }
770         $bestpath= $path;
771         $bestscores= $scores;
772     }
773     die "no solution" unless defined $bestpath;
774     o("%   chose path $bestpath @al\n");
775     @al= ();
776     foreach $segment (@$bestpath) {
777         if ($segment->{T} eq 'Arc') {
778             arc({}, $segment->{C},$segment->{F},$segment->{R},$segment->{D});
779         } elsif ($segment->{T} eq 'Line') {
780             line($segment->{A}, $segment->{B}, $segment->{L});
781         } else {
782             die "unknown segment";
783         }
784     }
785 }
786
787 sub line ($$$) {
788     my ($from,$to,$len) = @_;
789     parametric_segment(0.0, 1.0, abs($len), undef, sub {
790         ev_lincomb({}, $from, $to, $param);
791     });
792 }
793
794 sub cmd_extend {
795     my ($from,$to,$radius,$len,$upto,$ctr,$beta,$ang,$how,$sign_r);
796     $from= can(\&cva_idex);
797     $to= can(\&cva_idnew);
798     printf DEBUG "from $from->{X} $from->{Y} $from->{A}\n";
799     $how= can(cvam_enum(qw(len upto ang uptoang parallel)));
800     if ($how eq 'len') { $len= can(\&cva_len); }
801     elsif ($how =~ m/ang$/) { $ang= can(\&cva_ang); }
802     elsif ($how eq 'parallel' || $how eq 'upto') { $upto= can(\&cva_idex); }
803     $radius= cano(\&cva_len, 'Inf'); # +ve is right hand bend
804     if ($radius eq 'Inf') {
805 #       print DEBUG "extend inf $len\n";
806         if ($how eq 'upto') {
807             $len= ($upto->{X} - $from->{X}) * cos($from->{A})
808                 + ($upto->{Y} - $from->{Y}) * sin($from->{A});
809         } elsif ($how eq 'len') {
810         } else {
811             die "len of straight spec by angle";
812         }
813         printf DEBUG "len $len\n";
814         $to->{X}= $from->{X} + $len * cos($from->{A});
815         $to->{Y}= $from->{Y} + $len * sin($from->{A});
816         $to->{A}= $from->{A};
817         line($from,$to,$len);
818     } else {
819         my ($sign_r, $sign_ang, $ctr, $beta_interval, $beta, $delta);
820         print DEBUG "radius >$radius<\n";
821         $radius *= $ctx->{Trans}{R};
822         $sign_r= signum($radius);
823         $sign_ang= 1;
824         $ctr->{X}= $from->{X} + $radius * sin($from->{A});
825         $ctr->{Y}= $from->{Y} - $radius * cos($from->{A});
826         if ($how eq 'upto') {
827             $beta= atan2(-$sign_r * ($upto->{X} - $ctr->{X}),
828                          $sign_r * ($upto->{Y} - $ctr->{Y}));
829             $beta_interval= 1.0;
830         } elsif ($how eq 'parallel') {
831             $beta= $upto->{A};
832             $beta_interval= 1.0;
833         } elsif ($how eq 'uptoang') {
834             $beta= input_absang($ang);
835             $beta_interval= 2.0;
836         } elsif ($how eq 'len') {
837             $sign_ang= signum($len);
838             $beta= $from->{A} - $sign_r * $len / abs($radius);
839             $beta_interval= 2.0;
840         } else {
841             $sign_ang= signum($ang);
842             $beta= $from->{A} - $sign_r * $ang;
843             $beta_interval= 2.0;
844         }
845     printf DEBUG "ctr->{Y}=$ctr->{Y} radius=$radius beta=$beta\n";
846         $beta += $sign_ang * $sign_r * 4.0 * $pi;
847         for (;;) {
848             $delta= $beta - $from->{A};
849             last if $sign_ang * $sign_r * $delta <= 0;
850             $beta -= $sign_ang * $sign_r * $beta_interval * $pi;
851         }
852     printf DEBUG "ctr->{Y}=$ctr->{Y} radius=$radius beta=$beta\n";
853         arc($to, ,$ctr,$from, $radius,$delta);
854     }
855     printf DEBUG "to $to->{X} $to->{Y} $to->{A}\n";
856 }
857
858 sub loc2dbg ($) {
859     my ($loc) = @_;
860     return "$loc->{X} $loc->{Y} ".ang2deg($loc->{A});
861 }
862 sub ang2deg ($) {
863     return $_[0] * 180 / $pi;
864 }
865 sub input_absang ($) {
866     return $_[0] * $ctx->{Trans}{R} + $ctx->{Trans}{A};
867 }
868 sub input_abscoords ($$) {
869     my ($in,$out);
870     ($in->{X}, $in->{Y}) = @_;
871     $in->{A}= 0.0;
872     $out= ev_compose({}, $ctx->{Trans}, $in);
873     return ($out->{X}, $out->{Y});
874 }
875
876 sub newctx (;$) {
877     my ($ctx_save) = @_;
878     $ctx= {
879         Trans => { X => 0.0, Y => 0.0, A => 0.0, R => 1.0 },
880         InRunObj => "",
881         DrawMap => sub { $_[0]; }
882         };
883     %{ $ctx->{Layer} }= %{ $ctx_save->{Layer} }
884         if defined $ctx_save;
885 }
886
887 our $defobj_save;
888 our $defobj_ispart;
889
890 sub cmd_defobj { cmd__defobj(0); }
891 sub cmd_defpart { cmd__defobj(1); }
892 sub cmd__defobj ($) {
893     my ($ispart) = @_;
894     my ($id);
895     $id= can(\&cva_idstr);
896     die "nested defobj" if $defobj_save;
897     die "repeated defobj" if exists $objs{$id};
898     $defobj_save= $ctx;
899     $defobj_ispart= $ispart;
900     newctx($defobj_save);
901     $ctx->{CmdLog}= [ ];
902     $ctx->{InDefObj}= $id;
903     $ctx->{Draw}= $defobj_save->{Draw}.'X';
904     $ctx->{DrawMap}= sub { ''; };
905     $ctx->{Layer}= { Level => 5, Kind => '' };
906 }
907
908 sub cmd_enddef {
909     my ($bit,$id);
910     $id= $ctx->{InDefObj};
911     die "unmatched enddef" unless defined $id;
912     foreach $bit (qw(CmdLog Loc)) {
913         $objs{$id}{$bit}= $ctx->{$bit};
914     }
915     $objs{$id}{Part}= $defobj_ispart;
916     $ctx= $defobj_save;
917     $defobj_save= undef;
918     $defobj_ispart= undef;
919 }
920
921 sub cmd__runobj ($) {
922     my ($obj_id)=@_;
923     my ($c);
924     local (@al);
925     dv("cmd__runobj $obj_id ",'$ctx',$ctx);
926     foreach $c (@{ $objs{$obj_id}{CmdLog} }) {
927         @al= @$c;
928         next if $al[0] eq 'enddef';
929         cmd__one();
930     }
931 }
932
933 sub layer_draw ($$) {
934     my ($k,$l) = @_;
935     my ($eo,$cc, $r);
936     if ($output_layer ne '*' && $l != $output_layer) {
937         $r = '';
938     } elsif ($k eq '') {
939         $r= 'RLMN';
940     } elsif ($k eq 's') {
941         $r= '';
942     } elsif ($k eq 'l') {
943         $r= 'CLMN';
944     } else {
945         $r= 'ARSCLMNO';
946     }
947     foreach $eo (@eopts) {
948         next unless $k =~ m/^$eo->{GlobRe}$/;
949         next unless &{ $eo->{LayerCheck} }($l);
950         foreach $cc (split //, $eo->{DrawMods}) {
951             $r =~ s/$cc//ig;
952             $r .= $cc if $cc =~ m/[A-Z]/;
953         }
954     }
955     $r= &{ $ctx->{DrawMap} }($r);
956     return $r;
957 }
958
959 sub cmd_layer {
960     my ($kl, $k,$l);
961     $kl= can(\&cva_identity);
962     $kl =~ m/^([A-Za-z_]*)(\d*|\=)$/ or die "invalid layer spec";
963     ($k,$l)=($1,$2);
964     $l= $ctx->{Layer}{Level} if $l =~ m/^\=?$/;
965     $ctx->{Layer}{Kind}= $k;
966     $ctx->{Layer}{Level}= $l;
967     $ctx->{Draw}= layer_draw($k,$l);
968 }    
969
970 sub cmd_part { cmd__obj(Part); }
971 sub cmd_obj { cmd__obj(1); }
972 sub cmd_objflip { cmd__obj(-1); }
973
974 sub cmd__obj ($) {
975     my ($how)=@_;
976     my ($obj_id, $ctx_save, $pfx, $actual, $formal_id, $formal, $formcv);
977     my ($part_name, $ctx_inobj, $obj, $id, $newid, $newpt);
978     if ($how eq Part) {
979         $part_name= can(\&cva_idstr);
980         $how= (@al && $al[0] =~ s/^\^//) ? -1 : +1;
981     }
982     $obj_id= can(\&cva_idstr);
983     if (defined $part_name) {
984         $formal_id= can(\&cva_idstr);
985         $actual= cano(\&cva_idex, undef);
986         if (!defined $actual) {
987             $actual= cva_idex("${part_name}_${formal_id}");
988         }
989     } else {
990         $actual= can(\&cva_idex);
991         $formal_id= can(\&cva_idstr);
992     }
993     $obj= $objs{$obj_id};
994     dv("cmd__obj ",'$obj',$obj);
995     die "unknown obj $obj_id" unless $obj;
996     $formal= $obj->{Loc}{$formal_id};
997     die "unknown formal $formal_id" unless $formal;
998     $ctx_save= $ctx;
999     newctx($ctx_save);
1000     $how *= $ctx_save->{Trans}{R};
1001     $ctx->{Trans}{R}= $how;
1002     $ctx->{Trans}{A}= $actual->{A} - $formal->{A}/$how;
1003     $formcv= ev_compose({}, $ctx->{Trans},$formal);
1004     $ctx->{Trans}{X}= $actual->{X} - $formcv->{X};
1005     $ctx->{Trans}{Y}= $actual->{Y} - $formcv->{Y};
1006     if (defined $part_name) {
1007         $ctx->{InRunObj}= $ctx_save->{InRunObj}."${part_name}:";
1008     } else {
1009         $ctx->{InRunObj}= $ctx_save->{InRunObj}."${obj_id}::";
1010     }
1011     $ctx->{DrawMap}= sub {
1012         my ($i) = @_;
1013         $i= &{ $ctx_save->{DrawMap} }($i);
1014         if ($obj->{Part}) {
1015             $i =~ s/[LMN]//g;
1016             $i =~ s/O/MNO/;
1017         } else {
1018             $i =~ s/[LM]//g;
1019             $i =~ s/N/MN/;
1020         }
1021         return $i;
1022     };
1023     $ctx->{Draw}= &{ $ctx->{DrawMap} }($ctx_save->{Draw});
1024     cmd__runobj($obj_id);
1025     if (defined $part_name) {
1026         $pfx= $part_name.'_';
1027     } else {
1028         if (@al && $al[0] eq '=') {
1029             $pfx= ''; shift @al;
1030         } else {
1031             $pfx= cano(\&cva_idstr,undef);
1032         }
1033     }
1034     $ctx_inobj= $ctx;
1035     $ctx= $ctx_save;
1036     if (defined $pfx) {
1037         foreach $id (keys %{ $ctx_inobj->{Loc} }) {
1038             next if $id eq $formal_id;
1039             $newid= $pfx.$id;
1040             next if exists $ctx_save->{Loc}{$newid};
1041             $newpt= cva_idnew($newid);
1042             %$newpt= %{ $ctx_inobj->{Loc}{$id} };
1043         }
1044     }
1045     if (defined $part_name) {
1046         my ($formalr_id, $actualr_id, $formalr, $actualr);
1047         while (@al) {
1048             die "part results come in pairs\n" unless @al>=2;
1049             ($formalr_id, $actualr_id, @al) = @al;
1050             if ($actualr_id =~ s/^\-//) {
1051                 $formalr_id= "-$formalr_id";
1052                 $formalr_id =~ s/^\-\-//;
1053             }
1054             {
1055                 local ($ctx) = $ctx_inobj;
1056                 $formalr= cva_idex($formalr_id);
1057             }
1058             $actualr= cva_idnew($actualr_id);
1059             %$actualr= %$formalr;
1060         }
1061     }
1062 }
1063
1064 sub cmd__do {
1065     my ($cmd);
1066 dv("cmd__do $ctx @al ",'$ctx',$ctx);
1067     $cmd= can(\&cva_cmd);
1068     my ($lm,$id,$loc,$io,$ad,$draw,$thendrawre);
1069     $io= defined $ctx->{InDefObj} ? "$ctx->{InDefObj}!" : $ctx->{InRunObj};
1070     o("%L cmd   $io $cmd @al\n");
1071     $ctx->{LocsMade}= [ ];
1072     {
1073         no strict 'refs';
1074         &{ "cmd_$cmd" };
1075     };
1076     die "too many args" if @al;
1077     foreach $lm (@{ $ctx->{LocsMade} }) {
1078         $id= $lm->{Id};
1079         $loc= $ctx->{Loc}{$id};
1080         $loc->{A} += $pi if $lm->{Neg};
1081         $ad= ang2deg($loc->{A});
1082         ol("%L point $io$id ".loc2dbg($loc)." ($lm->{Neg})\n");
1083         $draw= layer_draw($loc->{LayerKind}, $ctx->{Layer}{Level});
1084         if ($draw =~ m/[LM]/) {
1085             ol("    gsave\n".
1086                "      $loc->{X} $loc->{Y} translate $ad rotate\n");
1087             if ($draw =~ m/M/) {
1088                 ol("      0 $allwidthmin newpath moveto\n".
1089                    "      0 -$allwidthmin lineto\n".
1090                    "      $lmu_marklw setlinewidth stroke\n");
1091             }
1092             if ($draw =~ m/L/) {
1093                 ol("      /s ($id) def\n".
1094                    "      lf setfont\n".
1095                    "      /sx5  s stringwidth pop\n".
1096                    "      0.5 mul $lmu_txtboxpadx add def\n".
1097                    "      -90 rotate  0 $lmu_txtboxoff translate  newpath\n".
1098                    "      sx5 neg  0             moveto\n".
1099                    "      sx5 neg  $lmu_txtboxh  lineto\n".
1100                    "      sx5      $lmu_txtboxh  lineto\n".
1101                    "      sx5      0             lineto closepath\n".
1102                    "      gsave  1 setgray fill  grestore\n".
1103                    "      $lmu_txtboxlw setlinewidth stroke\n".
1104                    "      sx5 neg $lmu_txtboxpadx add  $lmu_txtboxtxty\n".
1105                    "      moveto s show\n");
1106             }
1107             ol("      grestore\n");
1108         }
1109     }
1110 }
1111
1112 sub cmd_showlibrary {
1113     my ($obj_id, $y, $x, $ctx_save, $width, $height);
1114     my ($max_x, $min_x, $max_y, $min_y, $nxty, $obj, $loc, $pat, $got, $glob);
1115     my ($adj);
1116     $x=$olu_left; $y=$olu_bottom; undef $nxty;
1117     $ctx_save= $ctx;
1118     foreach $obj_id (sort keys %objs) {
1119         $got= 1;
1120         foreach $glob (@al) {
1121             $pat= $glob;
1122             $got= !($pat =~ s/^\!//);
1123             die "bad pat" if $pat =~ m/[^0-9a-zA-Z_*?]/;
1124             $pat =~ s/\*/\.*/g; $pat =~ s/\?/./g;
1125             last if $obj_id =~ m/^$pat$/;
1126             $got= !$got;
1127         }
1128         next unless $got;           
1129         $obj= $objs{$obj_id};
1130         next unless $obj->{Part};
1131         ($min_x, $max_x, $min_y, $max_y) = bbox($obj->{Loc});
1132         newctx($ctx_save);
1133
1134         for (;;) {
1135             $width= $max_x - $min_x;
1136             $height= $max_y - $min_y;
1137             if ($width < $height) {
1138                 $ctx->{Trans}{A}= 0;
1139                 $ctx->{Trans}{X}= $x - $min_x;
1140                 $ctx->{Trans}{Y}= $y - $min_y + $olu_textheight;
1141             } else {
1142                 ($width,$height)=($height,$width);
1143                 $ctx->{Trans}{A}= 0.5 * $pi;
1144                 $ctx->{Trans}{X}= $x + $max_y;
1145                 $ctx->{Trans}{Y}= $y - $min_x + $olu_textheight;
1146             }
1147             $adj= length($obj_id) * $olu_textallowperc - $width;
1148             $adj=0 if $adj<0;
1149             $width += $adj;
1150             $ctx->{Trans}{X} += 0.5 * $adj;
1151             if ($x + $width > $olu_right && defined $nxty) {
1152                 $x= $olu_left;
1153                 $y= $nxty;
1154                 undef $nxty;
1155             } elsif ($y + $height > $olu_top && $y > $olu_bottom) {
1156                 oflushpage();
1157                 $x= $olu_left; $y= $olu_bottom;
1158                 undef $nxty;
1159             } else {
1160                 last;
1161             }
1162         }
1163             
1164         $ctx->{InRunObj}= $ctx_save->{InRunObj}."${obj_id}//";
1165         $ctx->{Draw}= $ctx_save->{Draw};
1166         cmd__runobj($obj_id);
1167         ol("    gsave\n".
1168            "      /s ($obj_id) def\n".
1169            "      lf setfont\n      ".
1170            ($x + 0.5*$width)." ".($y - $olu_textheight)." moveto\n".
1171            "      s stringwidth pop -0.5 mul  0  rmoveto\n".
1172            "      s show grestore\n");
1173         $x += $width + $olu_gap_x;
1174         upd_max(\$nxty, $y + $height + $olu_gap_y + $olu_textheight);
1175     }
1176     @al= ();
1177     $ctx= $ctx_save;
1178 }
1179
1180 sub cmd__one {
1181     cmd__do();
1182 }
1183
1184 print
1185     "%!\n".
1186     "  /lf /Courier-New findfont $lmu_marktpt scalefont def\n".
1187     "  615 0 translate 90 rotate\n".
1188     "  $ptscale $ptscale scale\n"
1189     or die $!;
1190
1191 newctx();
1192
1193 our $drawers= 'arsclmno';
1194 our %chdraw_emap= qw(A ARSc
1195                      R aRsc
1196                      S aRSc
1197                      C arsC
1198                      c Arsc
1199                      L LM
1200                      l l
1201                      M Mno
1202                      N MNo
1203                      O MNO
1204                      m mnol);
1205
1206 our $quiet=0;
1207
1208 while (@ARGV && $ARGV[0] =~ m/^\-/) {
1209     last if $ARGV[0] eq '-';
1210     $_= shift @ARGV;
1211     last if $_ eq '--';
1212     s/^\-//;
1213     while (length) {
1214         if (s/^D(\d+)//) { $debug= $1; }
1215         elsif (s/^D//) { $debug++; }
1216         elsif (s/^q//) { $quiet=1; }
1217         elsif (s/^(e)
1218                ((?:[a-z]|\*|\?|\[[a-z][-a-z]*\])*?)
1219                (\~?) (\d*) (\=*|\-+|\++) (\d*)
1220                ([a-z]+)//ix) {
1221             my ($ee,$g,$n,$d,$c,$v,$cc) = ($1,$2,$3,$4,$5,$6,$7);
1222             my ($eo, $invert, $lfn, $ccc, $sense,$limit);
1223             $g =~ s/[?*]/\\$&/g;
1224             $d= $output_layer if !length $d;
1225             $d= 5 if $d eq '*';
1226             $invert= length $n;
1227             $c= '=' if !length $c;
1228             if (length $v) {
1229                 die '-[eE]GN[D]CCV not allowed' if length $c > 1;
1230                 $c= $c x $v;
1231             }
1232             if ($c =~ m/^[-+]/) {
1233                 $sense= ($c.'1') + 0;
1234                 $limit= ($sense * $d) + length($c) - 1;
1235                 $lfn= sub {
1236                     ($output_layer eq '*' ? $d
1237                      : $_[0]) * $sense >= $limit
1238                          xor $invert;
1239                 };
1240             } else {
1241                 $limit= length($c) - 1;
1242                 $lfn= sub {
1243                     ($output_layer eq '*' ? 1
1244                      : abs($_[0] - $d) <= $limit)
1245                         xor $invert;
1246                 };
1247             }
1248             $ccc= '';
1249             foreach $c (split //, $cc) {
1250                 if ($ee eq 'e') {
1251                     die "bad -e option $c" unless defined $chdraw_emap{$c};
1252                     $ccc .=  $chdraw_emap{$c};
1253                 } else {
1254                     die "bad -E option $c" unless $c =~ m/[$drawers]/i;
1255                     $ccc .= $c;
1256                 }
1257             }
1258             $eo->{GlobRe}= $g;
1259             $eo->{LayerCheck}= $lfn;
1260             $eo->{DrawMods}= $ccc;
1261             push @eopts, $eo;
1262         } else {
1263             die "unknown option -$_";
1264         }
1265     }
1266 }
1267
1268 open DEBUG, ($debug ? ">&2" : ">/dev/null") or die $!;
1269
1270 if ($debug) {
1271     select(DEBUG); $|=1;
1272     select(STDOUT); $|=1;
1273 }
1274
1275 $ctx->{Draw}= '';
1276
1277 @al= qw(layer 5);
1278 cmd__one();
1279
1280 while (<>) {
1281     next if m/^\s*\#/;
1282     chomp; s/^\s+//; s/\s+$//;
1283     @al= split /\s+/, $_;
1284     next unless @al;
1285     print DEBUG "=== @al\n";
1286     last if $al[0] eq 'eof';
1287     push @{ $ctx->{CmdLog} }, [ @al ] if exists $ctx->{CmdLog};
1288     cmd__one();
1289 }
1290
1291 oflushpage();
1292
1293 {
1294     my ($min_x, $max_x, $min_y, $max_y) = bbox($ctx->{Loc});
1295     my ($bboxstr);
1296     if (defined $min_x) {
1297         $bboxstr= sprintf("width  %.2d (%.2d..%2.d)\n".
1298                           "height %.2d (%.2d..%2.d)\n",
1299                           $max_x - $min_x, $min_x, $max_x,
1300                           $max_y - $min_y, $min_y, $max_y);
1301     } else {
1302         $bboxstr= "no locs, no bbox\n";
1303     }
1304     if (!$quiet) { print STDERR $bboxstr; }
1305     $bboxstr =~ s/^/\%L bbox /mg;
1306     print $bboxstr or die $!;
1307 }