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