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