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