parse-wormedit: peaworm level variant for v90 strings
[wormy.git] / parse-wormedit
index 4fd22e701e2cf9c7628522f88eb7387d61ffff10..43593a87a3eded5412303800578b063ea276589c 100755 (executable)
@@ -6,7 +6,7 @@ use 5.010;
 use Data::Dumper;
 use Getopt::Long 2.33 qw(HelpMessage :config bundling);
 
-our $VERSION = '1.03';
+our $VERSION = '1.04';
 
 GetOptions(\my %opt,
        'raw|r',  # full output
@@ -19,6 +19,8 @@ package Shiar_Parse::WormEdit;
 use strict;
 use warnings;
 
+use Parse::Binary::Nested qw(unpackf);
+
 our %MAGICID = (
        "WormEdit053\000LVL" => 53,
        "WormEdit\34195\000LVL" => 95,
@@ -29,8 +31,8 @@ our %MAGICID = (
 my @FORMAT = (
        magic       => 'a15',
        version     => 'C',
-       name        => 'Ca32',
-       description => 'Ca64x256',
+       name        => 'C/a32',
+       description => 'C/a64x256',
        levelcount  => [1,
                single => 'C',
                multi  => 'C',
@@ -48,7 +50,8 @@ my @FORMAT = (
                        multifood  => 'C',
                        timematch  => 'C',
                        race       => 'C',
-                       ctf        => 'Cx',
+                       ctf        => 'C',
+                       reserved   => 'x',
                ],
        ],
        sprite     => ['8C',
@@ -56,13 +59,14 @@ my @FORMAT = (
        ],
        finish      => [1,
                type    => 's',
-               message => 'Ca255',
-               code    => 'Ca255x256',
+               message => 'C/a255',
+               code    => 'C/a255',
+               reserved=> 'x256',
        ],
        hiname      => 'a3',
        levels      => ['*', # levelcount->total actually
-               id         => 'Ca22',
-               name       => 'Ca22',
+               id         => 'C/a22',
+               name       => 'C/a22',
                size       => 'C',
                peas       => 'C',
                delay      => 'C',
@@ -127,13 +131,12 @@ sub read {
        $fileversion += 100 if $fileversion < 90;  # 93..95 came before 50..53
        given ($fileversion) {
                when (153) { } # current @FORMAT
-                       $FORMAT[7] = 'Ca64'; # no reserved space after description
-                       $FORMAT[15]->[-1] = 'Ca255'; # enddata
+                       $FORMAT[7] = 'C/a64'; # no reserved space after description
+                       splice @{ $FORMAT[15] }, -2; # finish reserve
                        $FORMAT[-1]->[-1]->[0] = '32C'; # less objects
-               when ($version == 96) {
-                       ref $_ and $_->[-1] = 'C' for @{ $FORMAT[11] }; # 9 moderefs
-               }
-                       ref $_ and pop @$_ for @{ $FORMAT[11] }; # only 8 moderefs
+                       ref $_ and pop @$_ for @{ $FORMAT[11] }; # 9 moderefs
+               when ($version == 96) { }
+                       ref $_ and pop @$_ for @{ $FORMAT[11] }; # only 8 moderefs (no ctf)
                        splice @FORMAT, 6, 2 if $version <= 94;  # earlier version without description
                when (95) { }
                        splice @{ $FORMAT[7] }, 4, 2;  # no race
@@ -149,9 +152,9 @@ sub read {
        }
 
        # convert to an easily accessible hash
-       my @values = unpack Shiar_Parse::Nested->template(\@FORMAT).'a*', $input;
-       my $data = Shiar_Parse::Nested->convert(\@FORMAT, \@values);
-       warn "Trailing data left unparsed\n" if grep {length} @values;
+       push @FORMAT, -trail => 'a*';
+       my $data = unpackf(\@FORMAT, $input);
+       warn "Trailing data left unparsed\n" if length delete $data->{-trail};
        $data->{format} = 'WormEdit';
        return $data;
 }
@@ -163,10 +166,12 @@ use strict;
 use warnings;
 
 use List::Util qw(sum min max);
+use Data::Dumper;
+use Parse::Binary::Nested qw(unpackf);
 
 sub read {
        my ($self, $input) = @_;
-       my ($psize, $ptype, $size, $type, $vsize, $dsize, $id, $subid) = unpack q{
+       my ($psize, $ptype, $size, $type, $vsize, $dsize, $id, $version) = unpack q{
                x11 x42    # file signature and comment
                S a2 S a2  # file size, type; data size, type
                x8         # var name
@@ -186,6 +191,17 @@ sub read {
        $input = substr $input, 73, -2;
        $id eq ord 'w'
                or die "Wormy level identifier not found\n";
+
+       if ($opt{version}) {
+               warn "Override version $version to $opt{version}\n";
+               $version = $opt{version};
+       }
+       elsif ($version == 95) {
+               # level offset instead of description byte
+               $version-- if (unpack('x2Z*x2xC', $input))[1] == 0xF4;
+               warn "Ambiguous file version 95; guessing subversion $version\n";
+       }
+
        my @FORMAT = (
                magic       => 'a1',
                version     => 'C',
@@ -201,11 +217,15 @@ sub read {
                        ) }
                        [qw/single peaworm tron deathmatch foodmatch multifood timematch race ctf/]
                ],
-               theanswer => 'C', # 42
+               theanswer => 'x', # 42
                sprite     => ['C',
                        line => 'B8',
                ],
                leveldata => 'a*',
+               #levels
+               #finish code
+               #levels-multi
+               #hinames
        );
        my @LEVELFORM = (
                peas       => 'C',
@@ -231,39 +251,65 @@ sub read {
                        y => 'C',
                        x => 'C',
                ],
-               #levels
-               #finish code
-               #levels-multi
-               #hinames
-       );
-       my @OBJECTFORM = (
+               objects    => ['?0',
                        type => 'C',
                        x1   => 'C',
                        y1   => 'C',
                        x2   => 'C',
                        y2   => 'C',
+               ],
        );
+       my $offsetbase = 0xF080;
 
-       given ($subid) {
+       my @VARMODES = (
+               [qw'single  single'],
+               [qw'multi   peaworm tron deathmatch foodmatch multifood timematch'],
+               [qw'race    race'],
+               [qw'ctf     ctf'],
+       );
+
+       given ($version) {
                when (97) {
                        # current @FORMAT
                }
-               when (95) {
-                       ref $_ and splice @$_, -2 for @{ $FORMAT[11] }; # only 8 moderefs
+                       $offsetbase = 0xF400;
+               when (96) {}
+                       ref $_ and splice(@$_, -8, 2) for @{ $FORMAT[11] }; # no multifood
                        splice @FORMAT, 12, 2;  # no reserved byte
+               when (95) {}
+                       splice @FORMAT, 6, 2;  # no description
+               when (94) {}
+               when (90) {
+                       $FORMAT[5] = 'C/a';  # length-preceding name
+                       splice @FORMAT, 10, 2;  # no default sprite
+                       ref $_ and do {
+                               $_->[5] = $_->[7];  # no tron; deathmatch instead
+                               $_->[7] = $_->[9];  # foodmatch instead
+                               $_->[9] = 'linkmatch';  # replaces timematch
+                               $_->[11] = $_->[13];  # race
+                               $_->[13] = $_->[15];  # ctf
+                               $_->[15] = 'domination';
+                       } for @{ $FORMAT[9] }; # no multifood
+                       splice @LEVELFORM, -2;
+                       push @LEVELFORM, "objects$_" => ['C',
+                               type => "=$_",
+                               map {$_ => 'C'} qw(x1 y1 x2 y2)
+                       ] for 2, 3;
+                       # peaworm/tron mode do not take multiplayer levels
+                       splice @VARMODES, 1, 0, ['peaworm', splice @{ $VARMODES[1] }, 1, 2];
                }
                default {
-                       die "Unsupported level version $subid\n";
+                       die "Unsupported level version $version\n";
                }
        }
 
-       my $data = Shiar_Parse::Nested->unpack(\@FORMAT, $input);
+       my $data = unpackf(\@FORMAT, $input);
        my $offset = 0;
-       my $offsetbase = 0xF080 + @{ $data->{sprite} } + 1;
+       $offsetbase += 1 + @{ $data->{sprite} } if $data->{sprite};
        $data->{moderef}->{offset}->{single} == $offsetbase
                or warn "First singleplayer level is not in front\n";
 
-       my $slots = sum(
+       my $slots = sum(grep {defined}
                $data->{moderef}->{end}->{single} > 0,  # singleplayer slot if any levels
                $data->{moderef}->{end}->{peaworm},     # one for each peaworm arena
                $data->{moderef}->{end}->{tron},        # idem for tron
@@ -271,26 +317,25 @@ sub read {
        $data->{hinames} = [ unpack '(x2a3)*', substr($data->{leveldata}, -5 * $slots) ];
        $data->{format} = '86s';
 
-       my @VARMODES = (
-               [qw'single  single'],
-               [qw'multi   peaworm tron deathmatch foodmatch multifood timematch'],
-               [qw'race    race'],
-               [qw'ctf     ctf'],
-       );
-
        $data->{levels} = [];
        for my $modes (@VARMODES) {
                my $variant = shift @$modes;
-               $offset = min(grep {$_} map { $data->{moderef}->{offset}->{$_} } @$modes)
-                       or next;
+               my @modeoffsets = grep {defined} #TODO: comment
+                       map { $data->{moderef}->{offset}->{$_} } @$modes;
+               @modeoffsets or next;
+               $data->{levelcount}->{$variant} = 0;
+               $offset = min(grep {$_} @modeoffsets) or next;
                $offset -= $offsetbase;
-               my $amount = $variant eq 'single' ? 100 : max(map { $data->{moderef}->{end}->{$_} } @$modes);
+               my $amount = $variant eq 'single' ? 100
+                       : max(grep {defined} map { $data->{moderef}->{end}->{$_} } @$modes);
 
                my @varform = @LEVELFORM;
-               $varform[13]->[0] = $variant eq 'single' ? 1 : 4;
-               unshift @varform, name => 'Z*' unless $variant eq 'single';
-               $varform[-1]->[0] = 1 if $variant eq 'race';
-               $varform[-1]->[0] = 2 if $variant eq 'ctf';
+               $varform[13]->[0] = $variant ~~ ['single', 'peaworm'] ? 1 : 4; # worms
+               unshift @varform, name => 'Z*' unless $variant eq 'single' or $version <= 91;
+               $varform[-3]->[0] = 1 if $variant eq 'race' and $version > 91;
+               $varform[-3]->[0] = 2 if $variant eq 'ctf';
+               push @varform, size => '=.';
+               my $parselevel = Parse::Binary::Nested->new(\@varform);
 
                while ($offset < length $data->{leveldata}) {
                        last if substr($data->{leveldata}, $offset, 1) eq chr(255);
@@ -301,37 +346,26 @@ sub read {
                                $data->{moderef}->{start}->{$mode} = 1 + scalar @{ $data->{levels} };
                        }
 
-                       my $level = Shiar_Parse::Nested->unpack(
-                               [@varform], substr $data->{leveldata}, $offset
-                       );
-                       my $size = 8  # unpack length (ugh, ugly recalculation)
-                               + (defined $level->{name} ? 1 + length $level->{name} : 0)
-                               + 3 * (ref $level->{worms} eq 'ARRAY' ? scalar @{$level->{worms}} : 1)
-                               + 2 * ($level->{flags} ? ref $level->{flags} eq 'ARRAY' ? scalar @{$level->{flags}} : 1 : 0)
-                               + ($level->{sprite} ? scalar @{$level->{sprite}} : 0)
-                               + ($level->{balls} ? 3 * scalar @{$level->{balls}} : 0);
-                       $level->{size} = $size;
+                       my $level = $parselevel->unpackf(substr $data->{leveldata}, $offset);
                        $level->{offset} = $offset + $offsetbase;
 
                        # add objects until terminator
                        $level->{objects} = [];
-                       while (my $object = ord substr($data->{leveldata}, $offset+$size, 1)) {
-                               push @{ $level->{objects} }, Shiar_Parse::Nested->unpack(
-                                       [@OBJECTFORM], substr($data->{leveldata}, $offset+$size, 5)
-                               );
-                               $size += 5;
-                       }
+               if ($version <= 91) {
+                       ref $_ eq 'ARRAY' and push @{ $level->{objects} }, @$_
+                               for map { delete $level->{"objects$_"} } 2, 3;
+               }
 
                        # add parsed level and advance
                        push @{ $data->{levels} }, $level;
-                       $offset += ++$size;
+                       $offset += $level->{size};
                        last if ++$data->{levelcount}->{$variant} >= $amount;
                }
 
                if ($variant eq 'single') {
                        $offset++;
                        $data->{finish}->{code} =
-                       my $code = substr delete($data->{leveldata}), $offset, -5*$slots;
+                       my $code = substr $data->{leveldata}, $offset, -5*$slots;
 
                        my %FINISHCODE = (
                                0 => chr 0xC9, # ret
@@ -358,7 +392,7 @@ sub read {
                        );
                        while (my ($finish, $match) = each %FINISHCODE) {
                                $match eq substr $code, 0, length $match or next;
-                               $data->{finish}->{type} = $finish or last;
+                               $data->{finish}->{type} = $finish and
                                $data->{finish}->{message} = unpack 'Z*', substr($code, length $match);
                                last;
                        }
@@ -369,56 +403,6 @@ sub read {
 }
 
 
-package Shiar_Parse::Nested;
-
-sub template {
-       my ($self, $format) = @_;
-       # total (flattened) unpack template from nested format definitions
-       return join '', map {
-               my $value = $format->[-($_ << 1) - 1];
-               if (ref $value eq 'ARRAY') {
-                       my $count = $value->[0];
-                       $value = $self->template($value);
-                       $value = $count =~ s/^([*\d]+)// ? "$count($value)$1"
-                               : $count."X[$count]$count/($value)";
-               }
-               else {
-                       $value =~ s/^C(a)(\d+)/$1 . ($2 + 1)/e;  # length prefix
-               }
-               $value;
-       } reverse 0 .. ($#$format - 1) >> 1;
-}
-
-sub convert {
-       my ($self, $format, $data) = @_;
-       # map flat results into a named and nested hash
-       my %res;
-       while (my ($field, $template) = splice @$format, 0, 2) {
-               if (ref $template eq 'ARRAY') {
-                       my ($count, @subformat) = @$template;
-                       my $max = $count =~ s/^(\d+)// ? $1 : 0;
-                       $count = !$count ? $max
-                               : $count eq '*' ? $res{levelcount}->{total} : shift @$data;
-                       $res{$field}->[$_] = $self->convert([@subformat], $data) for 0 .. ($max || $count)-1;
-                       splice @{ $res{$field} }, $count if $max > $count;
-                       $res{$field} = $res{$field}->[0] if $max == 1;
-                       next;
-               }
-               elsif ($template =~ /^Ca/) {
-                       $data->[0] = CORE::unpack 'C/a', $data->[0];
-               }
-               $res{$field} = shift @$data;
-       }
-       return \%res;
-}
-
-sub unpack {
-       my ($self, $format, $input) = @_;
-       my @data = CORE::unpack $self->template($format), $input;
-       return $self->convert($format, \@data);
-}
-
-
 package main;
 
 my @OBJTYPE = ('none', 'line', 'fat line', 'bar', 'circle');
@@ -480,15 +464,16 @@ else {
        print "\n";
        printf "File version: %s\n", "$data->{format} v$data->{version}";
        printf "Defaults: %s\n", join('; ',
-               'sprite ' . scalar @{ $data->{sprite} },
+               $data->{sprite} ? 'sprite ' . scalar @{ $data->{sprite} } : (),
                defined $data->{hiname} ? 'hiscore by ' . $data->{hiname} : (),
        );
 
        my $startnr = 0;
-       for my $variant (qw/single multi race ctf/) {
+       for my $variant (qw/single peaworm multi race ctf/) {
                my $count = $data->{levelcount}->{$variant};
+               defined $count or next;
                print "\n";
-               printf '%s (%s)', ucfirst $variant, $count // 'invalid';
+               printf '%s (%s)', ucfirst $variant, $count;
                $count or next;
                print ":";
                for (0 .. $count - 1) {
@@ -513,8 +498,7 @@ else {
                        );
                }
                $startnr += $count;
-       }
-       continue {
+
                print "\n";
                printf("-- %-21s%4s: %s (%s)\n",
                        '(ending)',
@@ -525,6 +509,7 @@ else {
                        $data->{finish}->{message} // '?',
                ) if $variant eq 'single';
        }
+       print "\n";
 }
 
 __END__