6 use Getopt::Long 2.33 qw(HelpMessage :config bundling);
12 ) or HelpMessage(-exitval => 2);
14 my $MAGICID = "WormEdit053\000LVL";
20 description => 'Ca64x256',
29 map { (start => $_, end => $_) } [1,
46 enddata => 'Ca255x256',
48 levels => ['*', # levelcount->total actually
85 # read and parse all input data
87 my @rawdata = unpack Shiar_Parse::Nested->template(\@FORMAT).'a*', readline;
88 $rawdata[0] eq $MAGICID
89 or die "File does not match WormEdit level header\n";
91 or warn "Unsupported version $rawdata[1] (expecting 53)\n";
93 # convert to an easily accessible hash
94 my $data = Shiar_Parse::Nested->convert(\@FORMAT, \@rawdata);
95 warn "Trailing data left unparsed\n" if grep {length} @rawdata;
97 # output with user-preferred formatting
100 my $output = JSON::XS->new->ascii->canonical->pretty->allow_nonref;
101 print $output->encode($data), "\n";
104 print "$data->{name} ($data->{description})\n";
106 for my $variant (qw/single multi race ctf/) {
108 my $count = $data->{levelcount}->{$variant};
109 printf "\u$variant ($count)";
112 printf("\n- %-22s (%3sx%3s, %d objects)",
113 $_->{id}, $_->{width}, $_->{height}, scalar @{ $_->{objects} },
114 ) for map { $data->{levels}->[$_ + $startnr] }
123 package Shiar_Parse::Nested;
126 my ($self, $format) = @_;
127 # total (flattened) unpack template from nested format definitions
128 return join '', map {
129 my $value = $format->[-($_ << 1) - 1];
130 if (ref $value eq 'ARRAY') {
131 my $count = $value->[0];
132 $value = $self->template($value);
133 $value = $count =~ s/^([*\d]+)// ? "$count($value)$1"
134 : $count."X[$count]$count/($value)";
137 $value =~ s/^C(a)(\d+)/$1 . ($2 + 1)/e; # length prefix
140 } reverse 0 .. ($#$format - 1) >> 1;
144 my ($self, $format, $data) = @_;
145 # map flat results into a named and nested hash
147 while (my ($field, $template) = splice @$format, 0, 2) {
148 if (ref $template eq 'ARRAY') {
149 my ($count, @subformat) = @$template;
150 my $max = $count =~ s/^(\d+)// ? $1 : 0;
151 $count = !$count ? $max
152 : $count eq '*' ? $res{levelcount}->{total} : shift @$data;
154 $res{$field}->[$_] = $self->convert([@subformat], $data) for 0 .. $max-1;
155 splice @{ $res{$field} }, $count if $max > $count;
156 $res{$field} = $res{$field}->[0] if $max == 1;
159 elsif ($template =~ /^Ca/) {
160 $data->[0] = unpack 'C/a', $data->[0];
162 $res{$field} = shift @$data;
171 parse-wormedit - WormEdit level data parser
175 parse-wormedit [--raw] <input.lvl>
179 Reads WormEdit v0.53 levels from STDIN or given file,
180 and outputs contents, summarised or in full.
184 Mischa POSLAWSKY <wormy@shiar.org>