5761a30107a585d2af0f172d9e607c9a05b1fb26
[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        => 'C',
54                         reserved   => 'x',
55                 ],
56         ],
57         sprite     => ['8C',
58                 line => 'B8',
59         ],
60         finish      => [1,
61                 type    => 's',
62                 message => 'Ca255',
63                 code    => 'Ca255',
64                 reserved=> 'x256',
65         ],
66         hiname      => 'a3',
67         levels      => ['*', # levelcount->total actually
68                 id         => 'Ca22',
69                 name       => 'Ca22',
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] = 'Ca64'; # 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 = Parse::Binary::Nested->new(\@FORMAT)->unpackf($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;
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         );
226         my @LEVELFORM = (
227                 peas       => 'C',
228                 delay      => 'C',
229                 growth     => 'C',
230                 bsize      => 'C',
231                 sprite     => ['C',
232                         line => 'B8',
233                 ],
234                 balls      => ['C',
235                         y   => 'C',
236                         x   => 'C',
237                         dir => 'C',
238                 ],
239                 worms      => [1,
240                         d => 'C',
241                         y => 'C',
242                         x => 'C',
243                 ],
244                 width      => 'C',
245                 height     => 'C',
246                 flags      => [0,
247                         y => 'C',
248                         x => 'C',
249                 ],
250                 #levels
251                 #finish code
252                 #levels-multi
253                 #hinames
254         );
255         my @OBJECTFORM = (
256                         type => 'C',
257                         x1   => 'C',
258                         y1   => 'C',
259                         x2   => 'C',
260                         y2   => 'C',
261         );
262         my $offsetbase = 0xF080;
263
264         given ($version) {
265                 when (97) {
266                         # current @FORMAT
267                 }
268                         $offsetbase = 0xF400;
269                 when (96) {}
270                         ref $_ and splice(@$_, -8, 2) for @{ $FORMAT[11] }; # no multifood
271                         splice @FORMAT, 12, 2;  # no reserved byte
272                 when (95) {}
273                         splice @FORMAT, 6, 2;  # no description
274                 when (94) {}
275                 when (90) {
276                         $FORMAT[5] = 'C/a';  # length-preceding name
277                         splice @FORMAT, 10, 2;  # no default sprite
278                         ref $_ and do {
279                                 $_->[5] = $_->[7];  # no tron; deathmatch instead
280                                 $_->[7] = $_->[9];  # foodmatch instead
281                                 $_->[9] = 'linkmatch';  # replaces timematch
282                                 $_->[11] = $_->[13];  # race
283                                 $_->[13] = $_->[15];  # ctf
284                                 $_->[15] = 'domination';
285                         } for @{ $FORMAT[9] }; # no multifood
286                         push @LEVELFORM, "objects$_" => ['C',
287                                 type => "=$_",
288                                 map {$_ => 'C'} qw(x1 y1 x2 y2)
289                         ] for 2, 3;
290                 }
291                 default {
292                         die "Unsupported level version $version\n";
293                 }
294         }
295
296         my $data = Parse::Binary::Nested->new(\@FORMAT)->unpackf($input);
297         my $offset = 0;
298         $offsetbase += 1 + @{ $data->{sprite} } if $data->{sprite};
299         $data->{moderef}->{offset}->{single} == $offsetbase
300                 or warn "First singleplayer level is not in front\n";
301
302         my $slots = sum(
303                 $data->{moderef}->{end}->{single} > 0,  # singleplayer slot if any levels
304                 $data->{moderef}->{end}->{peaworm},     # one for each peaworm arena
305                 $data->{moderef}->{end}->{tron},        # idem for tron
306         );
307         $data->{hinames} = [ unpack '(x2a3)*', substr($data->{leveldata}, -5 * $slots) ];
308         $data->{format} = '86s';
309
310         my @VARMODES = (
311                 [qw'single  single'],
312                 [qw'multi   peaworm tron deathmatch foodmatch multifood timematch'],
313                 [qw'race    race'],
314                 [qw'ctf     ctf'],
315         );
316
317         $data->{levels} = [];
318         for my $modes (@VARMODES) {
319                 my $variant = shift @$modes;
320                 my @modeoffsets = grep {defined} #TODO: comment
321                         map { $data->{moderef}->{offset}->{$_} } @$modes;
322                 @modeoffsets or next;
323                 $data->{levelcount}->{$variant} = 0;
324                 $offset = min(grep {$_} @modeoffsets) or next;
325                 $offset -= $offsetbase;
326                 my $amount = $variant eq 'single' ? 100
327                         : max(grep {defined} map { $data->{moderef}->{end}->{$_} } @$modes);
328
329                 my @varform = @LEVELFORM;
330                 $varform[13]->[0] = $variant eq 'single' ? 1 : 4;
331                 unshift @varform, name => 'Z*' unless $variant eq 'single' or $version <= 91;
332                 $varform[-1]->[0] = 1 if $variant eq 'race' and $version > 91;
333                 $varform[-1]->[0] = 2 if $variant eq 'ctf';
334                 my $parselevel = Parse::Binary::Nested->new(\@varform);
335
336                 while ($offset < length $data->{leveldata}) {
337                         last if substr($data->{leveldata}, $offset, 1) eq chr(255);
338
339                         # find references to this level offset, and set start number to matching modes
340                         while (my ($mode, $location) = each %{ $data->{moderef}->{offset} }) {
341                                 $location == $offset + $offsetbase or next;
342                                 $data->{moderef}->{start}->{$mode} = 1 + scalar @{ $data->{levels} };
343                         }
344
345                         my $level = $parselevel->unpackf(substr $data->{leveldata}, $offset);
346                         my $size = 8  # unpack length (ugh, ugly recalculation)
347                                 + (defined $level->{name} ? 1 + length $level->{name} : 0)
348                                 + 3 * (ref $level->{worms} eq 'ARRAY' ? scalar @{$level->{worms}} : 1)
349                                 + 2 * ($level->{flags} ? ref $level->{flags} eq 'ARRAY' ? scalar @{$level->{flags}} : 1 : 0)
350                                 + ($level->{sprite} ? scalar @{$level->{sprite}} : 0)
351                                 + ($level->{balls} ? 3 * scalar @{$level->{balls}} : 0);
352                         $level->{size} = $size;
353                         $level->{offset} = $offset + $offsetbase;
354
355                         # add objects until terminator
356                         $level->{objects} = [];
357                 if ($version <= 91) {
358                         ref $_ eq 'ARRAY' and push @{ $level->{objects} }, @$_
359                                 for map { delete $level->{"objects$_"} } 2, 3;
360                         $size += 1 + 4 * scalar @{ $level->{objects} };
361                 }
362                 else {
363                         while (my $object = ord substr($data->{leveldata}, $offset+$size, 1)) {
364                                 push @{ $level->{objects} }, Parse::Binary::Nested->new([@OBJECTFORM])->unpackf(
365                                         substr $data->{leveldata}, $offset+$size, 5
366                                 );
367                                 $size += 5;
368                         }
369                 }
370
371                         # add parsed level and advance
372                         push @{ $data->{levels} }, $level;
373                         $offset += ++$size;
374                         last if ++$data->{levelcount}->{$variant} >= $amount;
375                 }
376
377                 if ($variant eq 'single') {
378                         $offset++;
379                         $data->{finish}->{code} =
380                         my $code = substr $data->{leveldata}, $offset, -5*$slots;
381
382                         my %FINISHCODE = (
383                                 0 => chr 0xC9, # ret
384                                 1 => join('',
385                                         chr 0x21,  # ld hl, MESSAGE
386                                         pack('v', $offsetbase + $offset + 9),
387                                         (map {chr}
388                                                 0xCD, 0x37, 0x4A,  # call _puts
389                                                 0xC3, 0xAA, 0x55,  # jp _getkey
390                                         ),
391                                 ),
392                                 2 => join('',
393                                         (map {chr}
394                                                 0x21, 0, 0x1C,  # ld hl, $POS
395                                                 0x22, 0x7C, 0xC3, # ld (_penCol), hl
396                                                 0x21,  # ld hl, MESSAGE
397                                         ),
398                                         pack('v', $offsetbase + $offset + 15),
399                                         (map {chr}
400                                                 0xCD, 0xA5, 0x4A, # call _vputs
401                                                 0xC3, 0xAA, 0x55, # jp _getkey
402                                         ),
403                                 ),
404                         );
405                         while (my ($finish, $match) = each %FINISHCODE) {
406                                 $match eq substr $code, 0, length $match or next;
407                                 $data->{finish}->{type} = $finish and
408                                 $data->{finish}->{message} = unpack 'Z*', substr($code, length $match);
409                                 last;
410                         }
411                 }
412         }
413
414         return $data;
415 }
416
417
418 package main;
419
420 my @OBJTYPE = ('none', 'line', 'fat line', 'bar', 'circle');
421 my @ENDTYPE = ('none', 'message', 'small message');
422
423 sub objsummary {
424         my ($objects) = @_;
425         my @objtypes = map { $_->{type} } @$objects;
426         my %count;
427         $count{$_}++ for @objtypes;
428         return (@objtypes > 1 && keys %count == 1 && 'all ') . join(', ',
429                 map { $OBJTYPE[$_] ? $OBJTYPE[$_] . ($count{$_} > 1 && 's') : $_ }
430                 sort keys %count
431         );
432 }
433
434 # read and parse all input data
435 my $data;
436 local $/;
437 my $rawdata = readline;
438 if (substr($rawdata, 0, 11) eq "**TI86**\032\012\000") {
439         # compiled calculator file
440         $data = Shiar_Parse::WormyLevel->read($rawdata);
441 }
442 elsif (substr($rawdata, 0, 8) eq 'WormEdit') {
443         # original wormedit source
444         $data = Shiar_Parse::WormEdit->read($rawdata);
445 }
446 else {
447         die "Unrecognised file type\n";
448 }
449
450 # output with user-preferred formatting
451 if ($opt{raw}) {
452         # full data in yaml (human-readable) formatting
453         require YAML;
454         local $YAML::CompressSeries;
455               $YAML::CompressSeries = 0;
456         my $yml = "# Wormy levelset\n" . YAML::Dump($data);
457
458         # inline format of short hashes
459         $yml =~ s{
460                 ^(\ *) - \n                          # array indicator
461                 ((?:\1\ \ [a-z0-9]{1,5}:\ *\d+\n)+)  # simple hash declaration
462                 (?!\1\ )                             # no further children
463         }[
464                 my ($indent, $value) = ($1, $2);
465                 chop $value;
466                 $value =~ s/^ +//gm;
467                 $value =~ s/\n/, /g;
468                 "$indent- {$value}\n";
469         ]egmx;
470
471         print $yml;
472 }
473 else {
474         print $data->{name};
475         print " ($data->{description})" if defined $data->{description};
476         print "\n";
477         printf "File version: %s\n", "$data->{format} v$data->{version}";
478         printf "Defaults: %s\n", join('; ',
479                 $data->{sprite} ? 'sprite ' . scalar @{ $data->{sprite} } : (),
480                 defined $data->{hiname} ? 'hiscore by ' . $data->{hiname} : (),
481         );
482
483         my $startnr = 0;
484         for my $variant (qw/single multi race ctf/) {
485                 my $count = $data->{levelcount}->{$variant};
486                 print "\n";
487                 printf '%s (%s)', ucfirst $variant, $count // 'invalid';
488                 $count or next;
489                 print ":";
490                 for (0 .. $count - 1) {
491                         my $level = $data->{levels}->[$_ + $startnr];
492                         printf("\n- %-22s%4s:%3s+%2s%3s %3sx%-3s%s",
493                                 $level->{id} || $level->{name} || '#'.($_+1),
494                                 @$level{qw/size bsize growth/},
495                                 $variant eq 'single' && "x$level->{peas}",
496                                 @$level{qw/width height/},
497                                 join(';', map {" $_"} grep {$_}
498                                         @{$level->{objects}} && sprintf('%2d object%s (%s)',
499                                                 scalar @{$level->{objects}}, @{$level->{objects}} != 1 && 's',
500                                                 objsummary($level->{objects}),
501                                         ),
502                                         $level->{sprite} && @{$level->{sprite}} && sprintf('sprite %d',
503                                                 scalar @{$level->{sprite}},
504                                         ),
505                                         $level->{balls} && @{$level->{balls}} && sprintf('%d bounc%s',
506                                                 scalar @{$level->{balls}}, @{$level->{balls}} == 1 ? 'y' : 'ies',
507                                         ),
508                                 ),
509                         );
510                 }
511                 $startnr += $count;
512         }
513         continue {
514                 print "\n";
515                 printf("-- %-21s%4s: %s (%s)\n",
516                         '(ending)',
517                         defined $data->{finish}->{code}
518                                 ? length $data->{finish}->{code} : '?',
519                         defined $data->{finish}->{type}
520                                 ? $ENDTYPE[$data->{finish}->{type}] || 'unknown' : 'code',
521                         $data->{finish}->{message} // '?',
522                 ) if $variant eq 'single';
523         }
524 }
525
526 __END__
527
528 =head1 NAME
529
530 parse-wormedit - Wormy level data parser
531
532 =head1 SYNOPSIS
533
534  parse-wormedit [--raw] <input.lvl>
535
536 =head1 DESCRIPTION
537
538 Reads Wormy levels (either original WormEdit source or compiled TI-86 string)
539 from STDIN or given file, and outputs contents, summarised or in full.
540
541 =head1 AUTHOR
542
543 Mischa POSLAWSKY <wormy@shiar.org>
544
545 =head1 LICENSE
546
547 GPL version 3.
548