84e4e31c0140810983205359b0b05df2d3a54283
[wormy.git] / parse-wormedit
1 #!/usr/bin/env perl
2 use strict;
3 use warnings;
4 use 5.010;
5
6 use Data::Dumper;
7 use Getopt::Long 2.33 qw(HelpMessage :config bundling);
8
9 our $VERSION = '1.03';
10
11 GetOptions(\my %opt,
12         'raw|r',  # full output
13         'version=i',  # force version
14 ) or HelpMessage(-exitval => 2);
15
16
17 package Shiar_Parse::WormEdit;
18
19 use strict;
20 use warnings;
21
22 our %MAGICID = (
23         "WormEdit053\000LVL" => 53,
24         "WormEdit\34195\000LVL" => 95,
25         "WormEdit\34194\000LVL" => 94,
26         "WormEdit\34193\000LVL" => 93,
27 );
28
29 my @FORMAT = (
30         magic       => 'a15',
31         version     => 'C',
32         name        => 'Ca32',
33         description => 'Ca64x256',
34         levelcount  => [1,
35                 single => 'C',
36                 multi  => 'C',
37                 race   => 'C',
38                 ctf    => 'C',
39                 total  => 'C',
40         ],
41         moderef     => [1,
42                 map { (start => $_, end => $_) } [1,
43                         single     => 'C',
44                         peaworm    => 'C',
45                         tron       => 'C',
46                         deathmatch => 'C',
47                         foodmatch  => 'C',
48                         multifood  => 'C',
49                         timematch  => 'C',
50                         race       => 'C',
51                         ctf        => 'Cx',
52                 ],
53         ],
54         sprite     => ['8C',
55                 line => 'B8',
56         ],
57         finish      => [1,
58                 type    => 's',
59                 message => 'Ca255',
60                 code    => 'Ca255x256',
61         ],
62         hiname      => 'a3',
63         levels      => ['*', # levelcount->total actually
64                 id         => 'Ca22',
65                 name       => 'Ca22',
66                 size       => 'C',
67                 peas       => 'C',
68                 delay      => 'C',
69                 growth     => 'C',
70                 bsize      => 'C',
71                 sprite     => ['8C',
72                         line => 'B8',
73                 ],
74                 balls      => ['32C',
75                         y   => 'C',
76                         x   => 'C',
77                         dir => 'C',
78                 ],
79                 worms      => [4,
80                         d => 'C',
81                         y => 'C',
82                         x => 'C',
83                 ],
84                 width      => 'C',
85                 height     => 'C',
86                 flags      => [2,
87                         y => 'C',
88                         x => 'C',
89                 ],
90                 objects    => ['128C',
91                         type => 'C',
92                         x1   => 'C',
93                         y1   => 'C',
94                         x2   => 'C',
95                         y2   => 'C',
96                 ],
97         ],
98 );
99
100 sub read {
101         my ($self, $input) = @_;
102         my ($id, $version) = (substr($input, 0, 15), ord substr($input, 15, 1));
103         my $fileversion = $MAGICID{$id}
104                 or die "File does not match any known WormEdit level header\n";
105
106         if ($opt{version}) {
107                 warn "Override version $version to $opt{version}\n";
108                 $version = $opt{version};
109         }
110         elsif ($version != $fileversion) {
111                 warn "Unexpected version $version (expecting $fileversion)\n";
112         }
113         elsif ($version == 95) {
114                 # auto-detect exact variant
115                 if (ord substr($input, 70, 1) ~~ [1 .. 8]) {
116                         # valid sprite length instead of description byte
117                         # (which is usually a letter or nul)
118                         $version = 94;
119                 }
120                 elsif (ord substr($input, 147, 1) == 0) {
121                         # nul of finish type is 2 bytes later (unlike first char of message)
122                         $version = 96;
123                 }
124                 warn "Ambiguous file version 95; guessing subversion $version\n";
125         };
126
127         $fileversion += 100 if $fileversion < 90;  # 93..95 came before 50..53
128         given ($fileversion) {
129                 when (153) { } # current @FORMAT
130                         $FORMAT[7] = 'Ca64'; # no reserved space after description
131                         $FORMAT[15]->[-1] = 'Ca255'; # enddata
132                         $FORMAT[-1]->[-1]->[0] = '32C'; # less objects
133                 when ($version == 96) {
134                         ref $_ and $_->[-1] = 'C' for @{ $FORMAT[11] }; # 9 moderefs
135                 }
136                         ref $_ and pop @$_ for @{ $FORMAT[11] }; # only 8 moderefs
137                         splice @FORMAT, 6, 2 if $version <= 94;  # earlier version without description
138                 when (95) { }
139                         splice @{ $FORMAT[7] }, 4, 2;  # no race
140                         splice @{ $FORMAT[13] }, 4, 2; # no enddata
141                         splice @{ $FORMAT[-1] }, 1, 2; # no name
142                 when (94) { }
143                         splice @FORMAT, 14, 2; # no hiname
144                         $FORMAT[-1]->[0] = 64; # constant amount of levels
145                 when (93) { }
146                 default {
147                         die "Cannot parse data for Wormedit $fileversion/$version\n";
148                 }
149         }
150
151         # convert to an easily accessible hash
152         my @values = unpack Shiar_Parse::Nested->template(\@FORMAT).'a*', $input;
153         my $data = Shiar_Parse::Nested->convert(\@FORMAT, \@values);
154         warn "Trailing data left unparsed\n" if grep {length} @values;
155         $data->{format} = 'WormEdit';
156         return $data;
157 }
158
159
160 package Shiar_Parse::WormyLevel;
161
162 use strict;
163 use warnings;
164
165 use List::Util qw(sum min max);
166 use Data::Dumper;
167
168 sub read {
169         my ($self, $input) = @_;
170         my ($psize, $ptype, $size, $type, $vsize, $dsize, $id, $version) = unpack q{
171                 x11 x42    # file signature and comment
172                 S a2 S a2  # file size, type; data size, type
173                 x8         # var name
174                 S S        # var size; content size
175                 CC         # wormy header
176         }, $input;
177         $ptype eq "\014\000"
178                 or die "Not a calculator string, thus cannot be a Wormy level file\n";
179         $size == $psize - 16
180                 or warn "File size ($size) does not correspond with data size ($psize)\n";
181         $type eq "\014\010"
182                 or die "Not a calculator string, thus cannot be a Wormy level file\n";
183         $size == $vsize and $vsize == $dsize+2
184                 or warn "Mismatch in string data size declarations\n";
185 #       substr($input, -2) eq $CHECKSUM
186
187         $input = substr $input, 73, -2;
188         $id eq ord 'w'
189                 or die "Wormy level identifier not found\n";
190
191         if ($opt{version}) {
192                 warn "Override version $version to $opt{version}\n";
193                 $version = $opt{version};
194         }
195         elsif ($version == 95) {
196                 # level offset instead of description byte
197                 $version-- if (unpack('x2Z*x2xC', $input))[1] == 0xF4;
198                 warn "Ambiguous file version 95; guessing subversion $version\n";
199         }
200
201         my @FORMAT = (
202                 magic       => 'a1',
203                 version     => 'C',
204                 name        => 'Z*',
205                 description => 'Z*',
206                 levelcount  => [1,
207                         total  => 'S',
208                 ],
209                 moderef     => [1,
210                         map { (
211                                 offset => [1, map {$_ => 'S'} @$_], # byte location of start
212                                 end    => [1, map {$_ => 'C'} @$_],
213                         ) }
214                         [qw/single peaworm tron deathmatch foodmatch multifood timematch race ctf/]
215                 ],
216                 theanswer => 'C', # 42
217                 sprite     => ['C',
218                         line => 'B8',
219                 ],
220                 leveldata => 'a*',
221         );
222         my @LEVELFORM = (
223                 peas       => 'C',
224                 delay      => 'C',
225                 growth     => 'C',
226                 bsize      => 'C',
227                 sprite     => ['C',
228                         line => 'B8',
229                 ],
230                 balls      => ['C',
231                         y   => 'C',
232                         x   => 'C',
233                         dir => 'C',
234                 ],
235                 worms      => [1,
236                         d => 'C',
237                         y => 'C',
238                         x => 'C',
239                 ],
240                 width      => 'C',
241                 height     => 'C',
242                 flags      => [0,
243                         y => 'C',
244                         x => 'C',
245                 ],
246                 #levels
247                 #finish code
248                 #levels-multi
249                 #hinames
250         );
251         my @OBJECTFORM = (
252                         type => 'C',
253                         x1   => 'C',
254                         y1   => 'C',
255                         x2   => 'C',
256                         y2   => 'C',
257         );
258         my $offsetbase = 0xF080;
259
260         given ($version) {
261                 when (97) {
262                         # current @FORMAT
263                 }
264                         $offsetbase = 0xF400;
265                 when (96) {}
266                         ref $_ and splice(@$_, -8, 2) for @{ $FORMAT[11] }; # no multifood
267                         splice @FORMAT, 12, 2;  # no reserved byte
268                 when (95) {}
269                         splice @FORMAT, 6, 2;  # no description
270                 when (94) {}
271                 when (90) {
272                         $FORMAT[5] = 'C/a';  # length-preceding name
273                         splice @FORMAT, 10, 2;  # no default sprite
274                         ref $_ and do {
275                                 $_->[5] = $_->[7];  # no tron; deathmatch instead
276                                 $_->[7] = $_->[9];  # foodmatch instead
277                                 $_->[9] = 'linkmatch';  # replaces timematch
278                                 $_->[11] = $_->[13];  # race
279                                 $_->[13] = $_->[15];  # ctf
280                                 $_->[15] = 'domination';
281                         } for @{ $FORMAT[9] }; # no multifood
282                         push @LEVELFORM, "object$_" => ['C',
283                                 map {$_ => 'C'} qw(x1 y1 x2 y2)
284                         ] for qw(lines boxes);
285                 }
286                 default {
287                         die "Unsupported level version $version\n";
288                 }
289         }
290
291         my $data = Shiar_Parse::Nested->unpack(\@FORMAT, $input);
292         my $offset = 0;
293         $offsetbase += 1 + @{ $data->{sprite} } if $data->{sprite};
294         $data->{moderef}->{offset}->{single} == $offsetbase
295                 or warn "First singleplayer level is not in front\n";
296
297         my $slots = sum(
298                 $data->{moderef}->{end}->{single} > 0,  # singleplayer slot if any levels
299                 $data->{moderef}->{end}->{peaworm},     # one for each peaworm arena
300                 $data->{moderef}->{end}->{tron},        # idem for tron
301         );
302         $data->{hinames} = [ unpack '(x2a3)*', substr($data->{leveldata}, -5 * $slots) ];
303         $data->{format} = '86s';
304
305         my @VARMODES = (
306                 [qw'single  single'],
307                 [qw'multi   peaworm tron deathmatch foodmatch multifood timematch'],
308                 [qw'race    race'],
309                 [qw'ctf     ctf'],
310         );
311
312         $data->{levels} = [];
313         for my $modes (@VARMODES) {
314                 my $variant = shift @$modes;
315                 my @modeoffsets = grep {defined} #TODO: comment
316                         map { $data->{moderef}->{offset}->{$_} } @$modes;
317                 @modeoffsets or next;
318                 $data->{levelcount}->{$variant} = 0;
319                 $offset = min(grep {$_} @modeoffsets) or next;
320                 $offset -= $offsetbase;
321                 my $amount = $variant eq 'single' ? 100
322                         : max(grep {defined} map { $data->{moderef}->{end}->{$_} } @$modes);
323
324                 my @varform = @LEVELFORM;
325                 $varform[13]->[0] = $variant eq 'single' ? 1 : 4;
326                 unshift @varform, name => 'Z*' unless $variant eq 'single' or $version <= 91;
327                 $varform[-1]->[0] = 1 if $variant eq 'race' and $version > 91;
328                 $varform[-1]->[0] = 2 if $variant eq 'ctf';
329
330                 while ($offset < length $data->{leveldata}) {
331                         last if substr($data->{leveldata}, $offset, 1) eq chr(255);
332
333                         # find references to this level offset, and set start number to matching modes
334                         while (my ($mode, $location) = each %{ $data->{moderef}->{offset} }) {
335                                 $location == $offset + $offsetbase or next;
336                                 $data->{moderef}->{start}->{$mode} = 1 + scalar @{ $data->{levels} };
337                         }
338
339                         my $level = Shiar_Parse::Nested->unpack(
340                                 [@varform], substr $data->{leveldata}, $offset
341                         );
342                         my $size = 8  # unpack length (ugh, ugly recalculation)
343                                 + (defined $level->{name} ? 1 + length $level->{name} : 0)
344                                 + 3 * (ref $level->{worms} eq 'ARRAY' ? scalar @{$level->{worms}} : 1)
345                                 + 2 * ($level->{flags} ? ref $level->{flags} eq 'ARRAY' ? scalar @{$level->{flags}} : 1 : 0)
346                                 + ($level->{sprite} ? scalar @{$level->{sprite}} : 0)
347                                 + ($level->{balls} ? 3 * scalar @{$level->{balls}} : 0);
348                         $level->{size} = $size;
349                         $level->{offset} = $offset + $offsetbase;
350
351                         # add objects until terminator
352                         $level->{objects} = [];
353                 if ($version <= 91) {
354                         push @{ $level->{objects} }, { %$_, type => 2 } for map { $level->{$_} ? @{ $level->{$_} } : () } qw(objectlines);
355                         push @{ $level->{objects} }, { %$_, type => 3 } for map { $level->{$_} ? @{ $level->{$_} } : () } qw(objectboxes);
356                         $size += 1 + 4 * scalar @{ $level->{objects} };
357                 }
358                 else {
359                         while (my $object = ord substr($data->{leveldata}, $offset+$size, 1)) {
360                                 push @{ $level->{objects} }, Shiar_Parse::Nested->unpack(
361                                         [@OBJECTFORM], substr($data->{leveldata}, $offset+$size, 5)
362                                 );
363                                 $size += 5;
364                         }
365                 }
366
367                         # add parsed level and advance
368                         push @{ $data->{levels} }, $level;
369                         $offset += ++$size;
370                         last if ++$data->{levelcount}->{$variant} >= $amount;
371                 }
372
373                 if ($variant eq 'single') {
374                         $offset++;
375                         $data->{finish}->{code} =
376                         my $code = substr $data->{leveldata}, $offset, -5*$slots;
377
378                         my %FINISHCODE = (
379                                 0 => chr 0xC9, # ret
380                                 1 => join('',
381                                         chr 0x21,  # ld hl, MESSAGE
382                                         pack('v', $offsetbase + $offset + 9),
383                                         (map {chr}
384                                                 0xCD, 0x37, 0x4A,  # call _puts
385                                                 0xC3, 0xAA, 0x55,  # jp _getkey
386                                         ),
387                                 ),
388                                 2 => join('',
389                                         (map {chr}
390                                                 0x21, 0, 0x1C,  # ld hl, $POS
391                                                 0x22, 0x7C, 0xC3, # ld (_penCol), hl
392                                                 0x21,  # ld hl, MESSAGE
393                                         ),
394                                         pack('v', $offsetbase + $offset + 15),
395                                         (map {chr}
396                                                 0xCD, 0xA5, 0x4A, # call _vputs
397                                                 0xC3, 0xAA, 0x55, # jp _getkey
398                                         ),
399                                 ),
400                         );
401                         while (my ($finish, $match) = each %FINISHCODE) {
402                                 $match eq substr $code, 0, length $match or next;
403                                 $data->{finish}->{type} = $finish and
404                                 $data->{finish}->{message} = unpack 'Z*', substr($code, length $match);
405                                 last;
406                         }
407                 }
408         }
409
410         return $data;
411 }
412
413
414 package Shiar_Parse::Nested;
415
416 sub template {
417         my ($self, $format) = @_;
418         # total (flattened) unpack template from nested format definitions
419         return join '', map {
420                 my $value = $format->[-($_ << 1) - 1];
421                 if (ref $value eq 'ARRAY') {
422                         my $count = $value->[0];
423                         $value = $self->template($value);
424                         $value = $count =~ s/^([*\d]+)// ? "$count($value)$1"
425                                 : $count."X[$count]$count/($value)";
426                 }
427                 else {
428                         $value =~ s/^C(a)(\d+)/$1 . ($2 + 1)/e;  # length prefix
429                 }
430                 $value;
431         } reverse 0 .. ($#$format - 1) >> 1;
432 }
433
434 sub convert {
435         my ($self, $format, $data) = @_;
436         # map flat results into a named and nested hash
437         my %res;
438         while (my ($field, $template) = splice @$format, 0, 2) {
439                 if (ref $template eq 'ARRAY') {
440                         my ($count, @subformat) = @$template;
441                         my $max = $count =~ s/^(\d+)// ? $1 : 0;
442                         $count = !$count ? $max
443                                 : $count eq '*' ? $res{levelcount}->{total} : shift @$data;
444                         $res{$field}->[$_] = $self->convert([@subformat], $data) for 0 .. ($max || $count)-1;
445                         splice @{ $res{$field} }, $count if $max > $count;
446                         $res{$field} = $res{$field}->[0] if $max == 1;
447                         next;
448                 }
449                 elsif ($template =~ /^Ca/) {
450                         $data->[0] = CORE::unpack 'C/a', $data->[0];
451                 }
452                 $res{$field} = shift @$data;
453         }
454         return \%res;
455 }
456
457 sub unpack {
458         my ($self, $format, $input) = @_;
459         my @data = CORE::unpack $self->template($format), $input;
460         return $self->convert($format, \@data);
461 }
462
463
464 package main;
465
466 my @OBJTYPE = ('none', 'line', 'fat line', 'bar', 'circle');
467 my @ENDTYPE = ('none', 'message', 'small message');
468
469 sub objsummary {
470         my ($objects) = @_;
471         my @objtypes = map { $_->{type} } @$objects;
472         my %count;
473         $count{$_}++ for @objtypes;
474         return (@objtypes > 1 && keys %count == 1 && 'all ') . join(', ',
475                 map { $OBJTYPE[$_] ? $OBJTYPE[$_] . ($count{$_} > 1 && 's') : $_ }
476                 sort keys %count
477         );
478 }
479
480 # read and parse all input data
481 my $data;
482 local $/;
483 my $rawdata = readline;
484 if (substr($rawdata, 0, 11) eq "**TI86**\032\012\000") {
485         # compiled calculator file
486         $data = Shiar_Parse::WormyLevel->read($rawdata);
487 }
488 elsif (substr($rawdata, 0, 8) eq 'WormEdit') {
489         # original wormedit source
490         $data = Shiar_Parse::WormEdit->read($rawdata);
491 }
492 else {
493         die "Unrecognised file type\n";
494 }
495
496 # output with user-preferred formatting
497 if ($opt{raw}) {
498         # full data in yaml (human-readable) formatting
499         require YAML;
500         local $YAML::CompressSeries;
501               $YAML::CompressSeries = 0;
502         my $yml = "# Wormy levelset\n" . YAML::Dump($data);
503
504         # inline format of short hashes
505         $yml =~ s{
506                 ^(\ *) - \n                          # array indicator
507                 ((?:\1\ \ [a-z0-9]{1,5}:\ *\d+\n)+)  # simple hash declaration
508                 (?!\1\ )                             # no further children
509         }[
510                 my ($indent, $value) = ($1, $2);
511                 chop $value;
512                 $value =~ s/^ +//gm;
513                 $value =~ s/\n/, /g;
514                 "$indent- {$value}\n";
515         ]egmx;
516
517         print $yml;
518 }
519 else {
520         print $data->{name};
521         print " ($data->{description})" if defined $data->{description};
522         print "\n";
523         printf "File version: %s\n", "$data->{format} v$data->{version}";
524         printf "Defaults: %s\n", join('; ',
525                 $data->{sprite} ? 'sprite ' . scalar @{ $data->{sprite} } : (),
526                 defined $data->{hiname} ? 'hiscore by ' . $data->{hiname} : (),
527         );
528
529         my $startnr = 0;
530         for my $variant (qw/single multi race ctf/) {
531                 my $count = $data->{levelcount}->{$variant};
532                 print "\n";
533                 printf '%s (%s)', ucfirst $variant, $count // 'invalid';
534                 $count or next;
535                 print ":";
536                 for (0 .. $count - 1) {
537                         my $level = $data->{levels}->[$_ + $startnr];
538                         printf("\n- %-22s%4s:%3s+%2s%3s %3sx%-3s%s",
539                                 $level->{id} || $level->{name} || '#'.($_+1),
540                                 @$level{qw/size bsize growth/},
541                                 $variant eq 'single' && "x$level->{peas}",
542                                 @$level{qw/width height/},
543                                 join(';', map {" $_"} grep {$_}
544                                         @{$level->{objects}} && sprintf('%2d object%s (%s)',
545                                                 scalar @{$level->{objects}}, @{$level->{objects}} != 1 && 's',
546                                                 objsummary($level->{objects}),
547                                         ),
548                                         $level->{sprite} && @{$level->{sprite}} && sprintf('sprite %d',
549                                                 scalar @{$level->{sprite}},
550                                         ),
551                                         $level->{balls} && @{$level->{balls}} && sprintf('%d bounc%s',
552                                                 scalar @{$level->{balls}}, @{$level->{balls}} == 1 ? 'y' : 'ies',
553                                         ),
554                                 ),
555                         );
556                 }
557                 $startnr += $count;
558         }
559         continue {
560                 print "\n";
561                 printf("-- %-21s%4s: %s (%s)\n",
562                         '(ending)',
563                         defined $data->{finish}->{code}
564                                 ? length $data->{finish}->{code} : '?',
565                         defined $data->{finish}->{type}
566                                 ? $ENDTYPE[$data->{finish}->{type}] || 'unknown' : 'code',
567                         $data->{finish}->{message} // '?',
568                 ) if $variant eq 'single';
569         }
570 }
571
572 __END__
573
574 =head1 NAME
575
576 parse-wormedit - Wormy level data parser
577
578 =head1 SYNOPSIS
579
580  parse-wormedit [--raw] <input.lvl>
581
582 =head1 DESCRIPTION
583
584 Reads Wormy levels (either original WormEdit source or compiled TI-86 string)
585 from STDIN or given file, and outputs contents, summarised or in full.
586
587 =head1 AUTHOR
588
589 Mischa POSLAWSKY <wormy@shiar.org>
590
591 =head1 LICENSE
592
593 GPL version 3.
594