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