ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/deliantra/server/utils/cfutil.in
Revision: 1.124
Committed: Sun Nov 11 05:53:12 2012 UTC (11 years, 6 months ago) by root
Branch: MAIN
Changes since 1.123: +3 -1 lines
Log Message:
move face blob manegemnt fully to perl

File Contents

# User Rev Content
1 root 1.1 #!@PERL@
2    
3 root 1.77 #
4     # This file is part of Deliantra, the Roguelike Realtime MMORPG.
5 root 1.121 #
6 root 1.118 # Copyright (©) 2007,2008,2009,2010,2011,2012 Marc Alexander Lehmann / Robin Redeker / the Deliantra team
7 root 1.121 #
8 root 1.77 # Deliantra is free software: you can redistribute it and/or modify it under
9     # the terms of the Affero GNU General Public License as published by the
10     # Free Software Foundation, either version 3 of the License, or (at your
11     # option) any later version.
12 root 1.121 #
13 root 1.77 # This program is distributed in the hope that it will be useful,
14     # but WITHOUT ANY WARRANTY; without even the implied warranty of
15     # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16     # GNU General Public License for more details.
17 root 1.121 #
18 root 1.77 # You should have received a copy of the Affero GNU General Public License
19     # and the GNU General Public License along with this program. If not, see
20     # <http://www.gnu.org/licenses/>.
21 root 1.121 #
22 root 1.77 # The authors can be reached via e-mail to <support@deliantra.net>
23     #
24    
25 root 1.84 use common::sense;
26 root 1.2
27     my $prefix = "@prefix@";
28     my $exec_prefix = "@exec_prefix@";
29     my $datarootdir = "@datarootdir@";
30     my $DATADIR = "@datadir@/@PACKAGE@";
31    
32     my $CONVERT = "@CONVERT@";
33 root 1.111 my $IDENTIFY = "@IDENTIFY@";
34 root 1.3 my $OPTIPNG = "@OPTIPNG@";
35 root 1.2 my $RSYNC = "@RSYNC@";
36 root 1.31 my $PNGNQ = "@PNGNQ@";
37 root 1.2
38     use Getopt::Long;
39 root 1.73 use File::Temp;
40     use POSIX ();
41     use Carp;
42    
43 root 1.72 use YAML::XS ();
44 root 1.111 use Digest::MD5 ();
45     use Storable ();
46 root 1.63 use JSON::XS ();
47 root 1.3 use IO::AIO ();
48 root 1.111 use Compress::LZF ();
49 root 1.73
50 root 1.111 use AnyEvent;
51 root 1.70 use Coro 5.12;
52 root 1.111 use Coro::EV;
53 root 1.3 use Coro::AIO;
54 root 1.51 use Coro::Util;
55 root 1.53 use Coro::Channel;
56 root 1.111 use Coro::AnyEvent;
57 root 1.25 use Coro::Storable; $Storable::canonical = 1;
58 root 1.2
59 root 1.73 use Deliantra;
60    
61 root 1.42 $SIG{QUIT} = sub { Carp::cluck "QUIT" };
62    
63 root 1.2 sub usage {
64     warn <<EOF;
65 root 1.3 Usage: cfutil [-v] [-q] [--force] [--cache]
66 root 1.2 [--install-arch path]
67     [--install-maps maps]
68     [--print-statedir]
69     [--print-confdir]
70     [--print-datadir]
71     [--print-libdir]
72     [--print-bindir]
73     EOF
74     exit 1;
75     }
76    
77     my $VERBOSE = 1;
78 root 1.3 my $CACHE = 0;
79 root 1.2 my $FORCE;
80 root 1.3 my $TMPDIR = "/tmp/cfutil$$~";
81     my $TMPFILE = "aaaa0";
82 root 1.83 my @COMMIT;
83 root 1.2
84 root 1.35 our %COLOR = (
85 root 1.103 # original cf colours
86 root 1.35 black => 0,
87     white => 1,
88 root 1.103 navy => 2, # "dark blue"
89 root 1.35 red => 3,
90     orange => 4,
91 root 1.103 blue => 5, # "light blue"
92 root 1.35 darkorange => 6,
93     green => 7,
94     lightgreen => 8,
95     grey => 9,
96 root 1.103 brown => 10, # "yellow"
97     gold => 11, # "light yellow"
98     tan => 12, # yellowish gray
99    
100     # new for deliantra
101     none => 13,
102    
103     # compatibility to existing archetypes
104     lightblue => 5,
105     gray => 9,
106     yellow => 11,
107     khaki => 12,
108 root 1.35 );
109    
110 root 1.2 END { system "rm", "-rf", $TMPDIR }
111    
112 root 1.116 my $s_INT = AE::signal INT => sub { exit 1 };
113     my $s_TERM = AE::signal TERM => sub { exit 1 };
114 root 1.3
115 root 1.79 our %hash;
116    
117     # here we could try to avoid collisions and reduce chksum size further
118     sub make_hash($\$\$;$) {
119     my ($id, $dataref, $hashref, $clen) = @_;
120    
121 root 1.114 my $hash = substr +(Digest::MD5::md5 $$dataref), 0, $clen || 5;
122 root 1.79
123     if (exists $hash{$hash}) {
124 root 1.92 # hash collision, but some files are simply identical
125 root 1.79 if (${$hash{$hash}[1]} ne $$dataref) {
126 root 1.116 warn "ERROR: hash collision $hash{$hash}[0] vs. $id (increase the default \$clen in make_hash?)\n";
127 root 1.79 exit 1;
128     } else {
129     print "$hash{$hash}[0] and $id are identical (which is fine).\n" if $VERBOSE >= 3;
130     }
131     }
132     $hash{$hash} = [$id, $dataref, $hashref];
133    
134     $$hashref = $hash;
135     }
136    
137 root 1.114 sub optipng($) {
138 root 1.115 system $OPTIPNG, "-o5", "-i0", "-q", $_[0];
139 root 1.114 die "$_[0] has zero size, aborting." unless -s $_[0];
140     }
141    
142 root 1.2 mkdir $TMPDIR, 0700
143     or die "$TMPDIR: $!";
144    
145 root 1.111 sub fork_exec(&) {
146 root 1.3 my ($cb) = @_;
147    
148     if (my $pid = fork) {
149     my $current = $Coro::current;
150     my $w = AnyEvent->child (pid => $pid, cb => sub { $current->ready });
151     Coro::schedule;
152     } else {
153     eval { $cb->() };
154     POSIX::_exit 0 unless $@;
155     warn $@;
156     POSIX::_exit 1;
157     }
158     }
159    
160 root 1.111 sub imgsize($) {
161     open my $fh, "-|", $IDENTIFY, qw(-ping -format %w,%h --), $_[0]
162     or die "$IDENTIFY: $!";
163    
164     Coro::AnyEvent::readable $fh;
165    
166     my ($w, $h) = split /,/, <$fh>;
167    
168     ($w+0, $h+0)
169     }
170    
171     # make $dst from $src, if not uptodate, by calling $how
172     sub make_file($$$) {
173     my ($src, $dst, $how) = @_;
174    
175     my $t = (aio_stat $dst) ? -1 : (stat _)[9];
176    
177     for (ref $src ? @$src : $src) {
178     aio_stat $_
179     and die "$_: $!";
180    
181     if ((stat _)[9] > $t) {
182     # outdated, redo
183     $how->();
184     last;
185     }
186     }
187     }
188    
189 root 1.2 sub inst_maps($) {
190     my (undef, $path) = @_;
191    
192 root 1.29 print "\nInstalling '$path' to '$DATADIR/maps'\n\n";
193 root 1.2
194     if (!-f "$path/regions") {
195 root 1.116 warn "ERROR: '$path' does not look like a maps directory ('regions' file is missing).\n";
196 root 1.2 exit 1 unless $FORCE;
197     }
198    
199 root 1.62 system $RSYNC, "-av", "--chmod=u=rwX,go=rX",
200     "$path/.", "$DATADIR/maps/.",
201     "--exclude", "CVS", "--exclude", "/world-precomposed",
202     "--delete", "--delete-excluded"
203 root 1.16 and die "map installation failed.\n";
204 root 1.13
205     print "maps installed successfully.\n";
206 root 1.2 }
207    
208 root 1.103 {
209 root 1.24 our %ANIMINFO;
210 root 1.6 our %FACEINFO;
211 root 1.37 our %RESOURCE;
212 root 1.30 our @ARC;
213 root 1.27 our %ARC;
214 root 1.12 our $TRS;
215 root 1.116 our %PNG;
216 root 1.3 our $NFILE;
217 root 1.37 our $PATH;
218 root 1.3
219 root 1.19 our $QUANTIZE = "+dither -colorspace RGB -colors 256";
220    
221 root 1.53 our $c_arc = new Coro::Channel;
222 root 1.103 our $c_any = new Coro::Channel;
223 root 1.53
224     our @c_png;
225 root 1.2
226 root 1.121 # texture catalog size, in 64x64 tiles
227     sub TC_W() { 1024 / 64 }
228     sub TC_H() { 1024 / 64 }
229    
230     our @TC = ([]); # texture catalogs
231    
232     sub commit_png($$$$$$) {
233     my ($stem, $name, $data, $T, $w, $h) = @_;
234 root 1.5
235 root 1.121 $FACEINFO{$name}{stem} = substr $stem, 1 + length $PATH;
236 root 1.19 $FACEINFO{$name}{"data$T"} = $data;
237 root 1.121 $FACEINFO{$name}{w} = $w;
238     $FACEINFO{$name}{h} = $h;
239 root 1.2 }
240    
241 root 1.3 sub process_png {
242 root 1.53 while (@c_png) {
243     my ($path, $delete) = @{pop @c_png};
244 root 1.2
245 root 1.3 my $png;
246     aio_lstat $path;
247 root 1.2 my ($size, $mtime) = (stat _)[7,9];
248    
249 root 1.3 if (0 > aio_load $path, $png) {
250 root 1.116 warn "ERROR: $path: $!, skipping.\n";
251 root 1.5 next;
252 root 1.3 }
253    
254 root 1.19 my $stem = $path;
255     my $T;
256    
257     if ($stem =~ s/\.32x32\.png~?$//) {
258     $T = 32;
259     } elsif ($stem =~ s/\.64x64\.png~?$//) {
260     $T = 64;
261     } else {
262 root 1.116 warn "ERROR: $path: weird filename, skipping.\n";
263 root 1.19 next;
264     }
265    
266 root 1.6 # quickly extract width and height of the (necessarily PNG) image
267 root 1.3 unless ($png =~ /^\x89PNG\x0d\x0a\x1a\x0a....IHDR(........)/s) {
268 root 1.116 warn "ERROR: $path: not a recognized png file, skipping.\n";
269 root 1.5 next;
270 root 1.3 }
271 root 1.2
272 root 1.3 my ($w, $h) = unpack "NN", $1;
273 root 1.2
274 root 1.3 if ($w < $T || $h < $T) {
275 root 1.116 warn "ERROR: $path: too small ($w $h), skipping.\n";
276 root 1.5 next;
277 root 1.3 }
278    
279     if ($w % $T || $h % $T) {
280 root 1.116 warn "ERROR: $path: weird png size ($w $h), skipping.\n";
281 root 1.5 next;
282 root 1.3 }
283 root 1.2
284 root 1.54 (my $base = $stem) =~ s/^.*\///;
285    
286     my $fi = $FACEINFO{$base};
287     unless ($fi) {
288 root 1.59 #warn "$path: <$base> not referenced by any archetype, skipping.\n";
289     #next;
290 root 1.54 }
291    
292 root 1.59 my $arc = $fi->{arc} || { };
293 root 1.54
294 root 1.19 unless ($path =~ /~$/) {
295     # possibly enlarge
296     if (0 > aio_stat "$stem.64x64.png") {
297     my $other = "$stem.64x64.png~";
298    
299 root 1.111 make_file $path, $other, sub {
300     fork_exec {
301 root 1.52 my $CROP;
302     my $SRC = "png:\Q$path\E";
303    
304 root 1.54 my $is_floor = $arc->{is_floor};
305     my $is_wall = 0;
306    
307     my ($wall_pfx, $wall_dir, $wall_sfx);
308    
309     if (
310     !$is_floor
311     && !$arc->{alive}
312 root 1.55 && $arc->{move_block} eq "all"
313 root 1.54 && $path =~ /^(.*_)([0-9A-F])(\.x11.*\.png)$/
314     ) {
315     ($wall_pfx, $wall_dir, $wall_sfx) = ($1, hex $2, $3);
316    
317     unless (grep { !-e sprintf "%s%X%s", $wall_pfx, $_, $wall_sfx } 0..15) {
318     $is_wall = 1;
319     }
320     }
321    
322     if ($is_wall || $is_floor) {
323     # add a 4px border and add other images around it
324     $CROP = "-shave 8x8 +repage";
325    
326     $w += 8;
327     $h += 8;
328    
329     $SRC = "-size ${w}x${h} xc:transparent";
330     $SRC .= " png:\Q$path\E -geometry +4+4 -composite";
331    
332     # 8 surrounding images
333     for (
334     # x y b r0 r1
335     [-1, -1, 0, 6],
336     [ 0, -1, 1, 10, 14],
337     [+1, -1, 0, 12],
338    
339     [-1, 0, 8, 5, 7],
340     #
341     [+1, 0, 2, 5, 13],
342    
343     [-1, +1, 0, 3],
344     [ 0, +1, 4, 10, 11],
345     [+1, +1, 0, 9],
346     ) {
347     my ($x, $y, $d, $r0, $r1) = @$_;
348    
349     my $tile = $is_floor ? $path
350     : $is_wall ? sprintf "%s%X%s", $wall_pfx, ($wall_dir & $d) ? $r1 : $r0, $wall_sfx
351     : die;
352    
353     $SRC .= sprintf " png:%s -geometry %+d%+d -composite",
354     "\Q$tile",
355     $x * ($w - 8) + 4,
356     $y * ($h - 8) + 4;
357 root 1.52 }
358     }
359    
360 root 1.121 system "$CONVERT -depth 8 $SRC rgba:-"
361 root 1.51 . "| $exec_prefix/bin/cfhq2xa $w $h 0"
362 root 1.121 . "| $CONVERT -depth 8 -size ".($w * 2)."x".($h * 2)." rgba:- $CROP $QUANTIZE -quality 00 png32:\Q$other\E~"
363 root 1.52 and die "convert/cfhq2xa pipeline error: status $? ($!)";
364 root 1.114 optipng "$other~";
365 root 1.19 rename "$other~", $other;
366     };
367 root 1.111 };
368 root 1.19
369 root 1.53 push @c_png, [$other, !$CACHE];
370 root 1.19 }
371    
372     # possibly scale down
373     if (0 > aio_stat "$stem.32x32.png") {
374     my $other = "$stem.32x32.png~";
375    
376 root 1.111 make_file $path, $other, sub {
377     fork_exec {
378 root 1.121 system "$CONVERT png:\Q$path\E -geometry 50% -filter lanczos $QUANTIZE -quality 00 png32:\Q$other\E~";
379 root 1.115 optipng "$other~";
380 root 1.31
381     # reduce smoothfaces >10000 bytes
382 root 1.71 # obsolete, no longer required
383     if (0 && $stem =~ /_S\./ && (-s "$other~") > 10000) {
384 root 1.31 my $ncolor = 256;
385     while () {
386 root 1.33 system "<\Q$other~\E $PNGNQ -s1 -n$ncolor >\Q$other~~\E";
387 root 1.115 optipng "$other~~";
388 root 1.31 last if 10000 > -s "$other~~";
389     $ncolor = int $ncolor * 0.9;
390     $ncolor > 8 or die "cannot reduce filesize to < 10000 bytes";
391     }
392    
393     printf "reduced %s from %d to %d bytes using %d colours.\n",
394     $other, -s "$other~", -s "$other~~", $ncolor
395 root 1.32 if $VERBOSE >= 2;
396 root 1.31 rename "$other~~", "$other~";
397     }
398    
399 root 1.19 die "$other~ has zero size, aborting." unless -s "$other~";
400     rename "$other~", $other;
401     };
402 root 1.111 };
403 root 1.19
404 root 1.21 #warn "scaled down $path to $other\n";#d#
405 root 1.53 push @c_png, [$other, !$CACHE];
406 root 1.19 }
407     }
408    
409     (my $face = $stem) =~ s/^.*\///;
410    
411 root 1.116 for (@{ $fi->{derive} }) {
412     my ($dir, $type) = @$_;
413    
414     my $geom = "${T}x${T}";
415     my $dpath = "$dir/$type:$face.$geom.png~";
416    
417     if ($type eq "buildmaterial") {
418     my $ov = "$PATH/mapbuilding/buildmaterial.png";
419     make_file [$path, $ov], $dpath, sub {
420     fork_exec {
421     system "$CONVERT -size 64x64 xc:transparent \\( \Q$path\E -geometry 52x52+6+6 \\) -composite \Q$ov\E -composite -geometry $geom png:\Q$dpath\E~";
422     optipng "$dpath~";
423     rename "$dpath~", $dpath;
424     };
425     };
426     } elsif ($type eq "buildmaterial-box") {
427     my $ov = "$PATH/mapbuilding/buildmaterial-box.png";
428     make_file [$path, $ov], $dpath, sub {
429     fork_exec {
430     system "$CONVERT \Q$ov\E "
431     . "\\( \Q$path\E -trim -geometry 34x31\\> "
432     . "-gravity center -background transparent -extent 37x34 +gravity "
433     . "-geometry +22+6 \\) -composite "
434     . "-geometry $geom png:\Q$dpath\E~";
435     optipng "$dpath~";
436     rename "$dpath~", $dpath;
437     };
438     };
439     } elsif ($type eq "buildmaterial-sbox") {
440     my $ov = "$PATH/mapbuilding/buildmaterial-sbox.png";
441     make_file [$path, $ov], $dpath, sub {
442     fork_exec {
443     system "$CONVERT \Q$ov\E "
444     . "\\( \Q$path\E -trim -geometry 16x24\\> "
445     . "-gravity center -background transparent -extent 18x26 +gravity "
446     . "-geometry +26+16 \\) -composite "
447     . "-geometry $geom png:\Q$dpath\E~";
448     optipng "$dpath~";
449     rename "$dpath~", $dpath;
450     };
451     };
452     } else {
453     warn "ERROR: facename $type:$face contains unsupported derivation type.\n";
454     }
455    
456     aio_load $dpath, my $png;
457     IO::AIO::aio_unlink $dpath unless $CACHE;
458 root 1.121 commit_png "$dir/$type:$face", "$type:$face", $png, $T, 1, 1;
459 root 1.116 }
460    
461 root 1.23 # split all bigfaces, but avoid smoothfaces (*_S)
462 root 1.3 if (($w > $T || $h > $T) && $face !~ /_S\./) {
463     # split
464     my @tile;
465     for my $x (0 .. (int $w / $T) - 1) {
466     for my $y (0 .. (int $h / $T) - 1) {
467     my $file = "$path+$x+$y~";
468     aio_lstat $file;
469     push @tile, [$x, $y, $file, (stat _)[9]];
470     }
471 root 1.2 }
472    
473 root 1.3 my $mtime = (lstat $path)[9];
474 root 1.116 my @todo = grep { $_->[3] < $mtime } @tile;
475 root 1.3 if (@todo) {
476 root 1.111 fork_exec {
477 root 1.3 open my $convert, "|-", $CONVERT,
478     "png:-",
479     (map {
480     (
481     "(",
482     "+clone",
483     -crop => (sprintf "%dx%d+%d+%d", $T, $T, $_->[0] * $T, $_->[1] * $T),
484 root 1.7 "+repage",
485 root 1.19 -quality => "00",
486     -write => "png32:$_->[2]~",
487 root 1.3 "+delete",
488     ")",
489     )
490     } @todo),
491     "null:";
492    
493     binmode $convert;
494     print $convert $png;
495     close $convert;
496    
497     # pass 2, optimise, and rename
498     for (@todo) {
499 root 1.115 optipng "$_->[2]~";
500 root 1.3 rename "$_->[2]~", $_->[2];
501     }
502     };
503 root 1.2 }
504    
505 root 1.3 for (@tile) {
506     my ($x, $y, $file) = @$_;
507     my $tile;
508    
509     if (0 > aio_load $file, $tile) {
510     die "$path: unable to read tile +$x+$y, aborting.\n";
511     }
512     IO::AIO::aio_unlink $file unless $CACHE;
513 root 1.121 commit_png $stem, $x|$y ? "$face+$x+$y" : $face, $tile, $T, 1, 1;
514 root 1.2 }
515 root 1.3 } else {
516     # use as-is (either small, use smooth)
517 root 1.121 commit_png $stem, $face, $png, $T, $w / $T, $h / $T;
518 root 1.3 }
519 root 1.19
520 root 1.116 IO::AIO::aio_unlink $path if $delete;
521 root 1.3 }
522 root 1.2 }
523    
524 root 1.103 sub process_faceinfo {
525     my ($dir, $file) = @_;
526     my $path = "$dir/$file";
527    
528     my $data;
529     if (0 > aio_load $path, $data) {
530 root 1.116 warn "ERROR: $path: $!, skipping.\n";
531 root 1.103 return;
532     }
533    
534     for (split /\n/, $data) {
535 root 1.106 chomp;
536 root 1.109 my ($face, $visibility, $fg, $bg, $glyph) = split /\s+/, $_, 5;
537 root 1.106 # bg not used except for text clients
538 root 1.103
539 root 1.106 utf8::decode $glyph;
540 root 1.104 $glyph =~ s/^\?(?=.)//; # remove "autoglyph" flag
541 root 1.110 $glyph =~ s/^"(.+)"$/$1/; # allow for ""-style quoting
542 root 1.103
543 root 1.105 $fg = "white" if $fg eq "none"; # lots of faces have no fg colour yet
544    
545 root 1.103 (my $fgi = $COLOR{$fg})
546 root 1.116 // warn "ERROR: $path: $face specifies unknown foreground colour '$fg'.\n";
547 root 1.103 (my $bgi = $COLOR{$bg})
548 root 1.116 // warn "ERROR: $path: $face specifies unknown background colour '$bg'.\n";
549 root 1.103
550     my $fi = $FACEINFO{$face} ||= { };
551     $fi->{visibility} = $visibility * 1;
552     $fi->{magicmap} = $fgi; # foreground colour becomes magicmap
553 root 1.106
554     $glyph .= " " if 2 > length $glyph; # TODO kanji
555 root 1.107 die "glyph $face too long" if 2 < length $glyph;
556 root 1.106
557     $fi->{glyph} = "";
558 root 1.107 for (split //, $glyph) {
559 root 1.106 utf8::encode $_;
560     $fi->{glyph} .= (chr $fgi) . (chr $bgi) . $_;
561     }
562 root 1.103 }
563     }
564    
565 root 1.3 sub process_arc {
566 root 1.103 while (my ($dir, $file) = @{ $c_arc->get }) {
567 root 1.3 my $arc;
568     aio_load "$dir/$file", $arc; # simply pre-cache, as read_arch wants a file :/
569 root 1.4
570 root 1.2 my $arc = read_arch "$dir/$file";
571 root 1.4 for my $o (values %$arc) {
572 root 1.30 push @ARC, $o;
573     for (my $m = $o; $m; $m = $m->{more}) {
574     $ARC{$m->{_name}} = $m;
575     }
576 root 1.6
577 root 1.76 $o->{editor_folder} ||= "\x00$dir"; # horrible kludge
578 root 1.10
579 root 1.6 # find upper left corner :/
580     # omg, this is sooo broken
581 root 1.4 my ($dx, $dy);
582     for (my $o = $o; $o; $o = $o->{more}) {
583     $dx = $o->{x} if $o->{x} < $dx;
584     $dy = $o->{y} if $o->{y} < $dy;
585     }
586 root 1.6
587 root 1.4 for (my $o = $o; $o; $o = $o->{more}) {
588     my $x = $o->{x} - $dx;
589     my $y = $o->{y} - $dy;
590 root 1.6
591     my $ext = $x|$y ? "+$x+$y" : "";
592    
593 root 1.26 $o->{face} .= $ext unless /^blank.x11$|^empty.x11$/ || !$o->{face};
594 root 1.6
595     my $anim = delete $o->{anim};
596    
597     if ($anim) {
598 root 1.24 # possibly add $ext to the animation name to avoid
599     # the need to specify archnames for all parts
600     # of a multipart archetype.
601 root 1.8 $o->{animation} = "$o->{_name}";
602 root 1.24 my $facings = 1;
603     my @frames;
604 root 1.6
605     for (@$anim) {
606 root 1.24 if (/^facings\s+(\d+)/) {
607     $facings = $1*1;
608     } elsif (/^blank.x11$|^empty.x11$/) {
609     push @frames, $_;
610     } else {
611     push @frames, "$_$ext";
612     }
613 root 1.6 }
614    
615 root 1.24 $ANIMINFO{$o->{animation}} = {
616     facings => $facings,
617     frames => \@frames,
618     };
619 root 1.6 }
620    
621 root 1.58 for ($o->{face} || (), @{$anim || []}) {
622     next if /^facings\s/;
623    
624     my $face = $_;
625     $face =~ s/\+\d+\+\d+$//; # remove tile offset coordinates
626 root 1.6
627 root 1.116 # handle derived faces
628     if ($face =~ /^([^:]+):(.*)/) {
629     my ($type, $base) = ($1, $2);
630     push @{ $FACEINFO{$base}{derive} }, [$dir, $type];
631     }
632    
633     $FACEINFO{$face}{arc} = $o;
634 root 1.56
635     next if $face =~ /^blank.x11$|^empty.x11$/;
636 root 1.4 }
637 root 1.12
638     if (my $smooth = delete $o->{smoothface}) {
639 root 1.54 my %kv = split /\s+/, $smooth;
640 root 1.23 my $level = $o->{smoothlevel}; #TODO: delete from $o if !gcfclient-support
641     while (my ($face, $smooth) = each %kv) {
642 root 1.54 $FACEINFO{$smooth}{arc} = $o;
643    
644 root 1.23 $FACEINFO{$face}{smooth} = $smooth;
645     $FACEINFO{$face}{smoothlevel} = $level;
646 root 1.14 }
647 root 1.12 }
648 root 1.4 }
649     }
650 root 1.3 }
651 root 1.2 }
652    
653 root 1.3 sub process_trs {
654 root 1.103 my ($dir, $file) = @_;
655     my $path = "$dir/$file";
656 root 1.12
657 root 1.103 my $trs;
658     if (0 > aio_load $path, $trs) {
659 root 1.116 warn "ERROR: $path: $!, skipping.\n";
660 root 1.103 return;
661     }
662 root 1.12
663 root 1.103 $TRS .= $trs;
664 root 1.2 }
665    
666 root 1.45 my %FILECACHE;
667    
668     sub load_cached($;$) {
669     unless (exists $FILECACHE{$_[0]}) {
670     my $data;
671     if (0 < aio_load $_[0], $data) {
672 root 1.49 if ($_[1]) {
673     $data = eval { $_[1]->($data) };
674 root 1.116 warn "ERROR: $_[0]: $@" if $@;
675 root 1.49 }
676 root 1.45 }
677    
678     $FILECACHE{$_[0]} = $data;
679     }
680    
681     $FILECACHE{$_[0]}
682     }
683    
684 root 1.111 # convert an image and a palette to some indexed 2d-matrix structure
685     sub process_plt {
686     my ($base, $plt) = @_;
687    
688     my ($w, $h) = imgsize "$base.png";
689    
690     $w * $h
691     or die "$base.png: unable to identify correct size\n";
692    
693     my @plt;
694     my %map;
695    
696     for (split /\n/, $plt) {
697     next unless /\S/;
698 root 1.112 next if /^\s*#/;
699 root 1.111
700     /^([0-9a-fA-F]{3,6})\s*(.*?)\s*$/
701     or die "unparseable palette entry for $base.plt: $_";
702    
703     my ($rgb, $name) = ($1, $2);
704    
705     $rgb =~ s/^(.)(.)(.)$/$1$1$2$2$3$3/;
706    
707     $map{pack "H*", $rgb} = chr @plt;
708     push @plt, $name;
709     }
710    
711     make_file ["$base.plt", "$base.png"], "$base.tbl~", sub {
712     warn "building $base\n" if $VERBOSE >= 3;
713    
714     fork_exec {
715     open my $png, "-|", $CONVERT, qw(-depth 8 --), "$base.png", "rgb:"
716     or die "$base.png: $!";
717    
718     local $/;
719     $png = <$png>;
720    
721     $w * $h * 3 == length $png
722     or die "$base.png: failed to read enough data from file\n";
723    
724     $png =~ s/(...)/$map{$1}/ge;
725    
726     $w * $h == length $png
727     or die "$base.png: failed to map all data - wrong palette?\n";
728    
729     {
730     open my $fh, ">:raw", "$base.tbl~~"
731     or die "$base.tbl~~: $!";
732     syswrite $fh, $png;
733     }
734    
735     rename "$base.tbl~~", "$base.tbl~";
736     };
737     };
738    
739     0 <= aio_load "$base.tbl~", my $tbl
740     or die "$base.tbl~: $!";
741    
742     IO::AIO::aio_unlink "$base.tbl~" unless $CACHE;
743    
744     Compress::LZF::compress nfreeze {
745     w => $w,
746     h => $h,
747     plt => \@plt,
748     tbl => $tbl,
749     }
750     }
751    
752 root 1.37 sub process_res {
753 root 1.103 my ($dir, $file, $type) = @_;
754 root 1.37
755 root 1.111 0 <= aio_load "$dir/$file", my $data
756     or die "$dir/$file: $!";
757 root 1.37
758 root 1.103 my $meta = load_cached "$dir/meta", sub { JSON::XS->new->utf8->relaxed->decode (shift) };
759 root 1.38
760 root 1.103 utf8::decode $dir;
761     utf8::decode $file;
762 root 1.61
763 root 1.103 # a meta file for resources is now mandatory
764     unless (exists $meta->{$file}) {
765     warn "skipping $dir/$file\n" if $VERBOSE >= 3;
766     return;
767     }
768 root 1.49
769 root 1.103 $meta = {
770     %{ $meta->{"" } || {} },
771     %{ $meta->{$file} || {} },
772     };
773 root 1.48
774 root 1.120 if (exists $meta->{license} && $meta->{license} =~ s/^#//) { # exists == avoid autovivification
775 root 1.103 $meta->{license} = ({
776     "pd" => "Public Domain",
777     "gpl" => "GNU General Public License, version 3.0 or any later",
778     "cc/by/2.0" => "Licensed under Creative Commons Attribution 2.0 http://creativecommons.org/licenses/by/2.0/",
779     "cc/by/2.1" => "Licensed under Creative Commons Attribution 2.1 http://creativecommons.org/licenses/by/2.1/",
780     "cc/by/2.5" => "Licensed under Creative Commons Attribution 2.5 http://creativecommons.org/licenses/by/2.5/",
781     "cc/by/3.0" => "Licensed under Creative Commons Attribution 3.0 http://creativecommons.org/licenses/by/3.0/",
782     })->{$meta->{license}}
783 root 1.116 || warn "ERROR: $dir/$file: license tag '$meta->{license}' not found.";
784 root 1.103 }
785    
786     if (!exists $meta->{author} && $meta->{source} =~ m%^http://www.jamendo.com/en/artist/(.*)$%) {
787     ($meta->{author} = $1) =~ s/_/ /g;
788     }
789    
790     $file =~ s/\.res$//;
791     $file =~ s/\.(ogg|wav|jpg|png)$//;
792    
793 root 1.111 if ($file =~ s/\.plt$//) {
794     $data = process_plt "$dir/$file", $data;
795 root 1.119 } elsif (my $filter = delete $meta->{cfutil_filter}) {
796 root 1.103 if ($filter eq "yaml2json") {
797     $data = JSON::XS::encode_json YAML::XS::Load $data;
798     } elsif ($filter eq "json2json") {
799     $data = JSON::XS::encode_json JSON::XS->relaxed->utf8->decode ($data);
800     } elsif ($filter eq "perl2json") {
801     $data = eval $data; die if $@;
802     $data = JSON::XS::encode_json $data;
803     } else {
804 root 1.116 warn "ERROR: $dir/$file: unknown filter $filter, skipping\n";
805 root 1.63 }
806 root 1.103 }
807    
808 root 1.111 substr $dir, 0, 1 + length $PATH, "";
809    
810 root 1.122 my %info = (
811 root 1.103 type => (exists $meta->{type} ? delete $meta->{type} : $type),
812     data => $data,
813     %$meta ? (meta => $meta) : (),
814 root 1.122 );
815    
816     $RESOURCE{"$dir/$file"} = \%info;
817 root 1.103 }
818 root 1.63
819 root 1.103 sub process_any {
820     while (my ($func, @args) = @{ $c_any->get }) {
821     $func->(@args);
822 root 1.37 }
823     }
824    
825 root 1.3 sub find_files;
826     sub find_files {
827 root 1.2 my ($path) = @_;
828    
829 root 1.103 my $grp = IO::AIO::aio_group;
830    
831     my $scandir; $scandir = sub {
832     my ($path) = @_;
833    
834     IO::AIO::aioreq_pri 4;
835     add $grp IO::AIO::aio_scandir $path, 4, sub {
836     my ($dirs, $nondirs) = @_;
837    
838     $scandir->("$path/$_")
839     for grep $_ !~ /^(?:CVS|dev|\..*)$/, @$dirs;
840    
841     my $dir = $path;
842     substr $dir, 0, 1 + length $PATH, "";
843    
844     for my $file (@$nondirs) {
845     if ($dir =~ /^music(?:\/|$)/) {
846     $c_any->put ([\&process_res, $path, $file, 3]) # FT_MUSIC
847     if $file =~ /\.(ogg)$/;
848    
849     } elsif ($dir =~ /^sound(?:\/|$)/) {
850     $c_any->put ([\&process_res, $path, $file, 5]) # FT_SOUND
851     if $file =~ /\.(wav|ogg)$/;
852    
853     } elsif ($dir =~ /^res(?:\/|$)/) {
854     if ($file =~ /\.(jpg|png)$/) {
855     $c_any->put ([\&process_res, $path, $file, 0]) # FT_FACE
856     } elsif ($file =~ /\.(res)$/) {
857     $c_any->put ([\&process_res, $path, $file, 6]) # FT_RSRC
858     } else {
859 root 1.119 $c_any->put ([\&process_res, $path, $file, 6]); # was type undef, but now meta files are mandatory, so any mentioned file surely has a purpose
860 root 1.103 }
861    
862     } elsif ($file =~ /\.png$/) {
863 root 1.116 $PNG{$file} = $path;
864 root 1.44
865 root 1.103 } elsif ($file =~ /\.faceinfo$/) {
866     $c_any->put ([\&process_faceinfo, $path, $file]);
867 root 1.44
868 root 1.103 } elsif ($file =~ /\.trs$/) {
869     $c_any->put ([\&process_trs, $path, $file]);
870 root 1.44
871 root 1.103 } elsif ($file =~ /\.arc$/) {
872     $c_arc->put ([$path, $file]);
873 root 1.44
874 root 1.103 } else {
875     warn "ignoring $path/$file\n" if $VERBOSE >= 3;
876     }
877 root 1.2 }
878 root 1.103 };
879 root 1.2 };
880 root 1.103
881     $scandir->($path);
882     aio_wait $grp;
883 root 1.2 }
884    
885 root 1.73 sub generate_plurals {
886     # use Lingua::EN::Inflect ();
887     # Lingua::EN::Inflect::classical;
888 root 1.74 # Lingua::EN::Inflect::def_noun '(.*)staff' => '$1staves'; # policy
889 root 1.73 # Lingua::EN::Inflect::def_noun '(.*)boots' => '$1boots'; # hack
890     #
891     # for my $a (@ARC) {
892     # my $name = $a->{name} || $a->{_name};
893     #
894     # next unless $a->{name_pl};
895 root 1.74 # next if $a->{invisible};
896     # next if $a->{is_floor};
897     # next if $a->{no_pick};
898 root 1.73 #
899     # my $test = Lingua::EN::Inflect::PL_N_eq $name, Lingua::EN::Inflect::PL $name;
900     # my $pl = $test =~ /^(?:eq|p:.)$/
901     # ? $name
902     # : Lingua::EN::Inflect::PL $name;
903     #
904     # if ($pl ne $a->{name_pl}) {
905     # warn "$a->{_name}: plural differs, $pl vs $a->{name_pl}\n";
906     # }
907     # }
908     }
909    
910 root 1.2 sub inst_arch($) {
911     my (undef, $path) = @_;
912    
913 root 1.37 $PATH = $path;
914    
915 root 1.29 print "\n",
916     "Installing '$path' to '$DATADIR'\n",
917 root 1.28 "\n",
918 root 1.27 "This can take a long time if you run this\n",
919     "for the first time or do not use --cache.\n",
920     "\n",
921     "Unless you run verbosely, all following warning\n",
922     "or error messages indicate serious problems.\n",
923     "\n";
924 root 1.2
925     if (!-d "$path/treasures") {
926 root 1.116 warn "FATAL: '$path' does not look like an arch directory ('treasures' directory is missing).\n";
927 root 1.2 exit 1 unless $FORCE;
928     }
929    
930 root 1.114 print "starting file scan, arc, any processing...\n" if $VERBOSE;
931 root 1.53
932     my @a_arc = map +(async \&process_arc), 1..2;
933 root 1.103 my @a_any = map +(async \&process_any), 1..4;
934 root 1.53
935 root 1.103 find_files $path;
936 root 1.2
937 root 1.70 $c_arc->shutdown;
938 root 1.103 $c_any->shutdown;
939 root 1.53
940     $_->join for @a_arc; # need to parse all archetypes before png processing
941 root 1.117 print "finished arc processing...\n" if $VERBOSE;
942 root 1.3
943 root 1.116 # fill png queue
944     for (keys %FACEINFO) {
945     # we only expect source pngs to exist for non-derived
946     # faces, i.e. no split tiles (+x+x) and no face derivates
947     # (xxx:)
948     /^[^:]+\....$/
949     or next;
950    
951     my $seen;
952    
953     if (exists $PNG{"$_.32x32.png"}) {
954     push @c_png, ["$PNG{\"$_.32x32.png\"}/$_.32x32.png"];
955     $seen = 1;
956     }
957     if (exists $PNG{"$_.64x64.png"}) {
958     push @c_png, ["$PNG{\"$_.64x64.png\"}/$_.64x64.png"];
959     $seen = 1;
960     }
961    
962     warn "ERROR: $_: face not found, expect problems.\n"
963     unless $seen;
964     }
965    
966 root 1.114 print "starting png processing...\n" if $VERBOSE;
967 root 1.53
968 root 1.69 # eight png crunchers work fine for my 4x smp machine
969     my @a_png = map +(async \&process_png), 1..8;
970 root 1.53
971 root 1.103 $_->join for @a_any;
972 root 1.117 print "finished any processing...\n" if $VERBOSE;
973 root 1.103
974     $_->join for @a_png;
975 root 1.117 print "finished png processing...\n" if $VERBOSE;
976 root 1.53
977     print "scanning done, processing results...\n" if $VERBOSE;
978 root 1.5 {
979 root 1.27 # remove path prefix from editor_folder
980 root 1.76 $_->{editor_folder} =~ /^\x00/
981     and substr $_->{editor_folder}, 0, 2 + length $path, ""
982     for values %ARC;
983 root 1.27
984 root 1.53 print "resolving inheritance tree...\n" if $VERBOSE;
985 root 1.27 # resolve inherit
986     while () {
987     my $progress;
988     my $loop;
989    
990     for my $o (values %ARC) {
991 root 1.81 for my $other (split /,/, $o->{inherit}) {
992 root 1.27 if (my $s = $ARC{$other}) {
993     if ($s->{inherit}) {
994     $loop = $s;
995     } else {
996     delete $o->{inherit};
997 root 1.30 my %s = %$s;
998     delete @s{qw(_name more name name_pl)};
999     %$o = ( %s, %$o );
1000 root 1.27 ++$progress;
1001     }
1002     } else {
1003 root 1.116 warn "ERROR: archetype '$o->{_name}' tries to inherit from undefined archetype '$other', skipping.\n";
1004 root 1.27 delete $ARC{$o->{_name}};
1005     }
1006     }
1007     }
1008    
1009     unless ($progress) {
1010     die "inheritance loop detected starting at archetype '$loop->{_name}', aborting.\n"
1011     if $loop;
1012    
1013     last;
1014     }
1015     }
1016    
1017 root 1.34 # remove base classes (by naming scheme, should use something like "baseclass xxx" to inherit
1018     @ARC = grep $_->{_name} !~ /^(?:type|class)_/, @ARC;
1019    
1020 root 1.104 # fix up archetypes without names, where the archanme doesn't work at all
1021     for (@ARC) {
1022     if (!exists $_->{name} and $_->{_name} =~ /_/) {
1023     for ($_->{name} = $_->{_name}) {
1024     s/(?:_\d+)+$//;
1025     s/_[nesw]+$//;
1026     y/_/ /;
1027     }
1028     }
1029     }
1030    
1031     #print "generating plurals...\n" if $VERBOSE;
1032     #generate_plurals;
1033 root 1.73
1034 root 1.78 printf "writing %d archetypes...\n", scalar @ARC if $VERBOSE;
1035 root 1.5 open my $fh, ">:utf8", "$DATADIR/archetypes~"
1036     or die "$DATADIR/archetypes~: $!";
1037 root 1.65 print $fh Deliantra::archlist_to_string [sort { $a->{_name} cmp $b->{_name} } @ARC];
1038 root 1.5 }
1039    
1040 root 1.6 {
1041 root 1.78 printf "writing treasures (%d octets)...\n", length $TRS if $VERBOSE;
1042 root 1.12 open my $fh, ">:utf8", "$DATADIR/treasures~"
1043     or die "$DATADIR/treasures~: $!";
1044     print $fh $TRS;
1045     }
1046    
1047     {
1048 root 1.53 print "processing facedata...\n" if $VERBOSE;
1049 root 1.121
1050     for my $k (sort keys %FACEINFO) {
1051     my $v = $FACEINFO{$k};
1052    
1053 root 1.116 length $v->{data32} or warn "ERROR: face '$k' has no png32 - this will not work.\n";
1054     length $v->{data64} or warn "ERROR: face '$k' has no png64 - this will not work.\n";
1055 root 1.5
1056 root 1.79 make_hash $k, $v->{data32}, $v->{hash32};
1057     make_hash $k, $v->{data64}, $v->{hash64};
1058    
1059 root 1.103 #length $v->{data32} <= 10000 or warn "WARNING: face '$k' has face32 larger than 10000 bytes, will not work with crossfire client.\n";
1060     #length $v->{data64} <= 10000 or warn "WARNING: face '$k' has face64 larger than 10000 bytes.\n";
1061 root 1.20
1062 root 1.116 $v->{glyph} // warn "ERROR: face '$k' has no glyph - missing faceinfo entry?\n";
1063     $v->{visibility} // warn "ERROR: face '$k' has no visibility info - missing faceinfo entry?\n";
1064     $v->{magicmap} // warn "ERROR: face '$k' has no foreground colour - missing faceinfo entry?\n";
1065 root 1.91
1066 root 1.121 if (0 && $v->{w} == 1 && $v->{h} == 1) { # texture catalogs
1067     my $id = @TC;
1068     my $n = @{ $TC[-1] };
1069     my $x = $n % TC_W;
1070     my $y = int $n / TC_W;
1071    
1072     push @{ $TC[-1] }, [$v, $x, $y];
1073    
1074     $v->{tc} = [$id, $x, $y];
1075    
1076     push @TC, [] if $n == TC_W * TC_H - 1; # start new texture if full
1077     }
1078    
1079     delete @$v{qw(w h arc stem derive)}; # not used by the server
1080 root 1.6 }
1081    
1082 root 1.121 if (0) { #d# texture catalogs
1083     print "creating texture catalogs...\n" if $VERBOSE;
1084    
1085     for my $id (0 .. $#TC) {
1086     my $tc = $TC[$id];
1087    
1088     my $cmd = "$CONVERT -depth 8 -size " . (TC_W * 64) . "x" . (TC_H * 64) . " xc:transparent";
1089     my $idx = "a";
1090    
1091     for (@$tc) {
1092     my $path = "$TMPDIR/tc" . $idx++;
1093    
1094     open my $fh, ">:perlio", $path
1095     or die "$path: $!";
1096     syswrite $fh, $_->[0]{data64};
1097    
1098     my $x = $_->[1] * 64;
1099     my $y = $_->[2] * 64;
1100    
1101     $cmd .= " png:\Q$path\E -geometry +$x+$y -composite";
1102     }
1103    
1104     system "$cmd png:\Q$TMPDIR/tc$id\E";
1105     optipng "$TMPDIR/tc$id";
1106     }
1107     }
1108    
1109 root 1.79 print "processing resources...\n" if $VERBOSE;
1110     my $enc = JSON::XS->new->utf8->canonical->relaxed;
1111 root 1.124 for my $k (sort keys %RESOURCE) {
1112     my $v = $RESOURCE{$k};
1113    
1114 root 1.83 if ($v->{meta} && $v->{meta}{datadir}) {
1115     delete $RESOURCE{$k};
1116 root 1.79
1117 root 1.83 $k =~ s/^res\/// or die "$k: datadir files must be in res/";
1118 root 1.79
1119 root 1.83 printf "writing $k (%d octets)...\n", length $v->{data} if $VERBOSE;
1120     open my $fh, ">:raw", "$DATADIR/$k~"
1121     or die "$DATADIR/$k~: $!";
1122     syswrite $fh, $v->{data};
1123     push @COMMIT, $k;
1124    
1125     } else {
1126     if ($v->{type} & 1) {
1127     # prepend meta info
1128    
1129     my $meta = $enc->encode ({
1130     name => $k,
1131     %{ $v->{meta} || {} },
1132     });
1133    
1134     $v->{data} = pack "(w/a*)*", $meta, $v->{data};
1135     }
1136    
1137     make_hash $k, $v->{data}, $v->{hash}, 6; # 6 for the benefit of existing clients
1138 root 1.79 }
1139     }
1140    
1141 root 1.123 printf "writing facedata...\n" if $VERBOSE;
1142    
1143     {
1144     open my $fh, ">:perlio", "$DATADIR/facedata~"
1145     or die "$DATADIR/facedata~: $!";
1146    
1147     print $fh "FACEDATA";
1148     my $fofs = 8;
1149    
1150     my $put = sub {
1151     my $len = length $_[0];
1152     my $ofs = $fofs;
1153    
1154     print $fh $_[0];
1155     $fofs += $len;
1156    
1157     ($len, $ofs)
1158     };
1159    
1160     for (values %FACEINFO) {
1161     ($_->{size32}, $_->{fofs32}) = $put->(delete $_->{data32});
1162     ($_->{size64}, $_->{fofs64}) = $put->(delete $_->{data64});
1163     }
1164    
1165     for (values %RESOURCE) {
1166     ($_->{size}, $_->{fofs}) = $put->(delete $_->{data});
1167     }
1168    
1169     close $fh;
1170     }
1171    
1172     printf "writing faceinfo (%d faces, %d anims, %d resources)...\n",
1173 root 1.78 scalar keys %FACEINFO,
1174     scalar keys %ANIMINFO,
1175     scalar keys %RESOURCE
1176     if $VERBOSE;
1177    
1178 root 1.123 open my $fh, ">:perlio", "$DATADIR/faceinfo~"
1179     or die "$DATADIR/faceinfo~: $!";
1180 root 1.6
1181 root 1.82 print $fh nfreeze {
1182 root 1.24 version => 2,
1183     faceinfo => \%FACEINFO,
1184     animinfo => \%ANIMINFO,
1185 root 1.37 resource => \%RESOURCE,
1186 root 1.24 };
1187 root 1.5 }
1188    
1189 root 1.53 print "committing files...\n" if $VERBOSE;
1190    
1191 root 1.123 for (qw(archetypes faceinfo facedata treasures), @COMMIT) {
1192 root 1.6 chmod 0644, "$DATADIR/$_~";
1193 root 1.13 rename "$DATADIR/$_~", "$DATADIR/$_"
1194     or die "$DATADIR/$_: $!";
1195 root 1.6 }
1196 root 1.13
1197     print "archetype data installed successfully.\n";
1198 root 1.2 }
1199     }
1200    
1201     Getopt::Long::Configure ("bundling", "no_ignore_case");
1202     GetOptions (
1203     "verbose|v:+" => \$VERBOSE,
1204 root 1.3 "cache" => \$CACHE,
1205 root 1.2 "quiet|q" => sub { $VERBOSE = 0 },
1206     "force" => sub { $FORCE = 1 },
1207     "install-arch=s" => \&inst_arch,
1208     "install-maps=s" => \&inst_maps,
1209     "print-statedir" => sub { print "@pkgstatedir@\n" },
1210     "print-datadir" => sub { print "$DATADIR\n" },
1211     "print-confdir" => sub { print "@pkgconfdir@\n" },
1212     "print-libdir" => sub { print "@libdir@/@PACKAGE@\n" },
1213     "print-bindir" => sub { print "@bindir@/@PACKAGE@\n" },
1214     ) or usage;
1215