ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/deliantra/server/lib/cf.pm
(Generate patch)

Comparing deliantra/server/lib/cf.pm (file contents):
Revision 1.517 by root, Thu Apr 15 06:07:51 2010 UTC vs.
Revision 1.581 by root, Fri Feb 3 02:04:11 2012 UTC

1# 1#
2# This file is part of Deliantra, the Roguelike Realtime MMORPG. 2# This file is part of Deliantra, the Roguelike Realtime MMORPG.
3# 3#
4# Copyright (©) 2006,2007,2008,2009,2010 Marc Alexander Lehmann / Robin Redeker / the Deliantra team 4# Copyright (©) 2006,2007,2008,2009,2010,2011,2012 Marc Alexander Lehmann / Robin Redeker / the Deliantra team
5# 5#
6# Deliantra is free software: you can redistribute it and/or modify it under 6# Deliantra is free software: you can redistribute it and/or modify it under
7# the terms of the Affero GNU General Public License as published by the 7# the terms of the Affero GNU General Public License as published by the
8# Free Software Foundation, either version 3 of the License, or (at your 8# Free Software Foundation, either version 3 of the License, or (at your
9# option) any later version. 9# option) any later version.
20# The authors can be reached via e-mail to <support@deliantra.net> 20# The authors can be reached via e-mail to <support@deliantra.net>
21# 21#
22 22
23package cf; 23package cf;
24 24
25use 5.10.0; 25use common::sense;
26use utf8;
27use strict qw(vars subs);
28 26
29use Symbol; 27use Symbol;
30use List::Util; 28use List::Util;
31use Socket; 29use Socket;
32use EV; 30use EV;
78# strictly for debugging 76# strictly for debugging
79$SIG{QUIT} = sub { Carp::cluck "SIGQUIT" }; 77$SIG{QUIT} = sub { Carp::cluck "SIGQUIT" };
80 78
81sub WF_AUTOCANCEL () { 1 } # automatically cancel this watcher on reload 79sub WF_AUTOCANCEL () { 1 } # automatically cancel this watcher on reload
82 80
81our @ORIG_INC;
82
83our %COMMAND = (); 83our %COMMAND = ();
84our %COMMAND_TIME = (); 84our %COMMAND_TIME = ();
85 85
86our @EXTS = (); # list of extension package names 86our @EXTS = (); # list of extension package names
87our %EXTCMD = (); 87our %EXTCMD = ();
93our @EVENT; 93our @EVENT;
94our @REFLECT; # set by XS 94our @REFLECT; # set by XS
95our %REFLECT; # set by us 95our %REFLECT; # set by us
96 96
97our $CONFDIR = confdir; 97our $CONFDIR = confdir;
98
98our $DATADIR = datadir; 99our $DATADIR = datadir;
99our $LIBDIR = "$DATADIR/ext"; 100our $LIBDIR = "$DATADIR/ext";
100our $PODDIR = "$DATADIR/pod"; 101our $PODDIR = "$DATADIR/pod";
101our $MAPDIR = "$DATADIR/" . mapdir; 102our $MAPDIR = "$DATADIR/" . mapdir;
103
102our $LOCALDIR = localdir; 104our $LOCALDIR = localdir;
103our $TMPDIR = "$LOCALDIR/" . tmpdir; 105our $TMPDIR = "$LOCALDIR/" . tmpdir;
104our $UNIQUEDIR = "$LOCALDIR/" . uniquedir; 106our $UNIQUEDIR = "$LOCALDIR/" . uniquedir;
105our $PLAYERDIR = "$LOCALDIR/" . playerdir; 107our $PLAYERDIR = "$LOCALDIR/" . playerdir;
106our $RANDOMDIR = "$LOCALDIR/random"; 108our $RANDOMDIR = "$LOCALDIR/random";
107our $BDBDIR = "$LOCALDIR/db"; 109our $BDBDIR = "$LOCALDIR/db";
108our $PIDFILE = "$LOCALDIR/pid"; 110our $PIDFILE = "$LOCALDIR/pid";
109our $RUNTIMEFILE = "$LOCALDIR/runtime"; 111our $RUNTIMEFILE = "$LOCALDIR/runtime";
110 112
111our %RESOURCE; 113#our %RESOURCE; # unused
112 114
113our $OUTPUT_RATE_MIN = 4000; 115our $OUTPUT_RATE_MIN = 3000;
114our $OUTPUT_RATE_MAX = 100000; 116our $OUTPUT_RATE_MAX = 1000000;
117
118our $MAX_LINKS = 32; # how many chained exits to follow
119our $VERBOSE_IO = 1;
115 120
116our $TICK = MAX_TIME * 1e-6; # this is a CONSTANT(!) 121our $TICK = MAX_TIME * 1e-6; # this is a CONSTANT(!)
117our $NEXT_RUNTIME_WRITE; # when should the runtime file be written 122our $NEXT_RUNTIME_WRITE; # when should the runtime file be written
118our $NEXT_TICK; 123our $NEXT_TICK;
119our $USE_FSYNC = 1; # use fsync to write maps - default on 124our $USE_FSYNC = 1; # use fsync to write maps - default on
121our $BDB_DEADLOCK_WATCHER; 126our $BDB_DEADLOCK_WATCHER;
122our $BDB_CHECKPOINT_WATCHER; 127our $BDB_CHECKPOINT_WATCHER;
123our $BDB_TRICKLE_WATCHER; 128our $BDB_TRICKLE_WATCHER;
124our $DB_ENV; 129our $DB_ENV;
125 130
126our @EXTRA_MODULES = qw(pod match mapscript); 131our @EXTRA_MODULES = qw(pod match mapscript incloader);
127 132
128our %CFG; 133our %CFG;
129 134
130our $UPTIME; $UPTIME ||= time; 135our $UPTIME; $UPTIME ||= time;
131our $RUNTIME; 136our $RUNTIME = 0;
137our $SERVER_TICK = 0;
132our $NOW; 138our $NOW;
133 139
134our (%PLAYER, %PLAYER_LOADING); # all users 140our (%PLAYER, %PLAYER_LOADING); # all users
135our (%MAP, %MAP_LOADING ); # all maps 141our (%MAP, %MAP_LOADING ); # all maps
136our $LINK_MAP; # the special {link} map, which is always available 142our $LINK_MAP; # the special {link} map, which is always available
145 151
146our @POST_INIT; 152our @POST_INIT;
147 153
148our $REATTACH_ON_RELOAD; # set to true to force object reattach on reload (slow) 154our $REATTACH_ON_RELOAD; # set to true to force object reattach on reload (slow)
149our $REALLY_UNLOOP; # never set to true, please :) 155our $REALLY_UNLOOP; # never set to true, please :)
156
157our $WAIT_FOR_TICK = new Coro::Signal;
158our @WAIT_FOR_TICK_BEGIN;
150 159
151binmode STDOUT; 160binmode STDOUT;
152binmode STDERR; 161binmode STDERR;
153 162
154# read virtual server time, if available 163# read virtual server time, if available
165 174
166our $EMERGENCY_POSITION; 175our $EMERGENCY_POSITION;
167 176
168sub cf::map::normalise; 177sub cf::map::normalise;
169 178
179sub in_main() {
180 $Coro::current == $Coro::main
181}
182
170############################################################################# 183#############################################################################
171 184
172%REFLECT = (); 185%REFLECT = ();
173for (@REFLECT) { 186for (@REFLECT) {
174 my $reflect = JSON::XS::decode_json $_; 187 my $reflect = JSON::XS::decode_json $_;
184 197
185=over 4 198=over 4
186 199
187=item $cf::UPTIME 200=item $cf::UPTIME
188 201
189The timestamp of the server start (so not actually an uptime). 202The timestamp of the server start (so not actually an "uptime").
203
204=item $cf::SERVER_TICK
205
206An unsigned integer that starts at zero when the server is started and is
207incremented on every tick.
208
209=item $cf::NOW
210
211The (real) time of the last (current) server tick - updated before and
212after tick processing, so this is useful only as a rough "what time is it
213now" estimate.
214
215=item $cf::TICK
216
217The interval between each server tick, in seconds.
190 218
191=item $cf::RUNTIME 219=item $cf::RUNTIME
192 220
193The time this server has run, starts at 0 and is increased by $cf::TICK on 221The time this server has run, starts at 0 and is increased by $cf::TICK on
194every server tick. 222every server tick.
200Various directories - "/etc", read-only install directory, perl-library 228Various directories - "/etc", read-only install directory, perl-library
201directory, pod-directory, read-only maps directory, "/var", "/var/tmp", 229directory, pod-directory, read-only maps directory, "/var", "/var/tmp",
202unique-items directory, player file directory, random maps directory and 230unique-items directory, player file directory, random maps directory and
203database environment. 231database environment.
204 232
205=item $cf::NOW
206
207The time of the last (current) server tick.
208
209=item $cf::TICK
210
211The interval between server ticks, in seconds.
212
213=item $cf::LOADAVG 233=item $cf::LOADAVG
214 234
215The current CPU load on the server (alpha-smoothed), as a value between 0 235The current CPU load on the server (alpha-smoothed), as a value between 0
216(none) and 1 (overloaded), indicating how much time is spent on processing 236(none) and 1 (overloaded), indicating how much time is spent on processing
217objects per tick. Healthy values are < 0.5. 237objects per tick. Healthy values are < 0.5.
226from wherever your confdir points to. 246from wherever your confdir points to.
227 247
228=item cf::wait_for_tick, cf::wait_for_tick_begin 248=item cf::wait_for_tick, cf::wait_for_tick_begin
229 249
230These are functions that inhibit the current coroutine one tick. cf::wait_for_tick_begin only 250These are functions that inhibit the current coroutine one tick. cf::wait_for_tick_begin only
231returns directly I<after> the tick processing (and consequently, can only wake one process 251returns directly I<after> the tick processing (and consequently, can only wake one thread
232per tick), while cf::wait_for_tick wakes up all waiters after tick processing. 252per tick), while cf::wait_for_tick wakes up all waiters after tick processing.
253
254Note that cf::Wait_for_tick will immediately return when the server is not
255ticking, making it suitable for small pauses in threads that need to run
256when the server is paused. If that is not applicable (i.e. you I<really>
257want to wait, use C<$cf::WAIT_FOR_TICK>).
258
259=item $cf::WAIT_FOR_TICK
260
261Note that C<cf::wait_for_tick> is probably the correct thing to use. This
262variable contains a L<Coro::Signal> that is broadcats after every server
263tick. Calling C<< ->wait >> on it will suspend the caller until after the
264next server tick.
265
266=cut
267
268sub wait_for_tick();
269sub wait_for_tick_begin();
233 270
234=item @cf::INVOKE_RESULTS 271=item @cf::INVOKE_RESULTS
235 272
236This array contains the results of the last C<invoke ()> call. When 273This array contains the results of the last C<invoke ()> call. When
237C<cf::override> is called C<@cf::INVOKE_RESULTS> is set to the parameters of 274C<cf::override> is called C<@cf::INVOKE_RESULTS> is set to the parameters of
245 282
246=back 283=back
247 284
248=cut 285=cut
249 286
287sub error(@) { LOG llevError, join "", @_ }
288sub warn (@) { LOG llevWarn , join "", @_ }
289sub info (@) { LOG llevInfo , join "", @_ }
290sub debug(@) { LOG llevDebug, join "", @_ }
291sub trace(@) { LOG llevTrace, join "", @_ }
292
250$Coro::State::WARNHOOK = sub { 293$Coro::State::WARNHOOK = sub {
251 my $msg = join "", @_; 294 my $msg = join "", @_;
252 295
253 $msg .= "\n" 296 $msg .= "\n"
254 unless $msg =~ /\n$/; 297 unless $msg =~ /\n$/;
255 298
256 $msg =~ s/([\x00-\x08\x0b-\x1f])/sprintf "\\x%02x", ord $1/ge; 299 $msg =~ s/([\x00-\x08\x0b-\x1f])/sprintf "\\x%02x", ord $1/ge;
257 300
258 LOG llevError, $msg; 301 LOG llevWarn, $msg;
259}; 302};
260 303
261$Coro::State::DIEHOOK = sub { 304$Coro::State::DIEHOOK = sub {
262 return unless $^S eq 0; # "eq", not "==" 305 return unless $^S eq 0; # "eq", not "=="
263 306
264 warn Carp::longmess $_[0]; 307 error Carp::longmess $_[0];
265 308
266 if ($Coro::current == $Coro::main) {#d# 309 if (in_main) {#d#
267 warn "DIEHOOK called in main context, Coro bug?\n";#d# 310 error "DIEHOOK called in main context, Coro bug?\n";#d#
268 return;#d# 311 return;#d#
269 }#d# 312 }#d#
270 313
271 # kill coroutine otherwise 314 # kill coroutine otherwise
272 Coro::terminate 315 Coro::terminate
294} 337}
295 338
296$EV::DIED = sub { 339$EV::DIED = sub {
297 Carp::cluck "error in event callback: @_"; 340 Carp::cluck "error in event callback: @_";
298}; 341};
342
343#############################################################################
344
345sub fork_call(&@);
346sub get_slot($;$$);
299 347
300############################################################################# 348#############################################################################
301 349
302=head2 UTILITY FUNCTIONS 350=head2 UTILITY FUNCTIONS
303 351
324 $d =~ s/([\x00-\x07\x09\x0b\x0c\x0e-\x1f])/sprintf "\\x%02x", ord($1)/ge; 372 $d =~ s/([\x00-\x07\x09\x0b\x0c\x0e-\x1f])/sprintf "\\x%02x", ord($1)/ge;
325 $d 373 $d
326 } || "[unable to dump $_[0]: '$@']"; 374 } || "[unable to dump $_[0]: '$@']";
327} 375}
328 376
377=item $scalar = cf::load_file $path
378
379Loads the given file from path and returns its contents. Croaks on error
380and can block.
381
382=cut
383
384sub load_file($) {
385 0 <= aio_load $_[0], my $data
386 or Carp::croak "$_[0]: $!";
387
388 $data
389}
390
391=item $success = cf::replace_file $path, $data, $sync
392
393Atomically replaces the file at the given $path with new $data, and
394optionally $sync the data to disk before replacing the file.
395
396=cut
397
398sub replace_file($$;$) {
399 my ($path, $data, $sync) = @_;
400
401 my $lock = cf::lock_acquire ("replace_file:$path");
402
403 my $fh = aio_open "$path~", Fcntl::O_WRONLY | Fcntl::O_CREAT | Fcntl::O_TRUNC, 0644
404 or return;
405
406 $data = $data->() if ref $data;
407
408 length $data == aio_write $fh, 0, (length $data), $data, 0
409 or return;
410
411 !$sync
412 or !aio_fsync $fh
413 or return;
414
415 aio_close $fh
416 and return;
417
418 aio_rename "$path~", $path
419 and return;
420
421 if ($sync) {
422 $path =~ s%/[^/]*$%%;
423 aio_pathsync $path;
424 }
425
426 1
427}
428
329=item $ref = cf::decode_json $json 429=item $ref = cf::decode_json $json
330 430
331Converts a JSON string into the corresponding perl data structure. 431Converts a JSON string into the corresponding perl data structure.
332 432
333=item $json = cf::encode_json $ref 433=item $json = cf::encode_json $ref
339our $json_coder = JSON::XS->new->utf8->max_size (1e6); # accept ~1mb max 439our $json_coder = JSON::XS->new->utf8->max_size (1e6); # accept ~1mb max
340 440
341sub encode_json($) { $json_coder->encode ($_[0]) } 441sub encode_json($) { $json_coder->encode ($_[0]) }
342sub decode_json($) { $json_coder->decode ($_[0]) } 442sub decode_json($) { $json_coder->decode ($_[0]) }
343 443
444=item $ref = cf::decode_storable $scalar
445
446Same as Coro::Storable::thaw, so blocks.
447
448=cut
449
450BEGIN { *decode_storable = \&Coro::Storable::thaw }
451
452=item $ref = cf::decode_yaml $scalar
453
454Same as YAML::XS::Load, but doesn't leak, because it forks (and thus blocks).
455
456=cut
457
458sub decode_yaml($) {
459 fork_call { YAML::XS::Load $_[0] } @_
460}
461
462=item $scalar = cf::unlzf $scalar
463
464Same as Compress::LZF::compress, but takes server ticks into account, so
465blocks.
466
467=cut
468
469sub unlzf($) {
470 # we assume 100mb/s minimum decompression speed (noncompressible data on a ~2ghz machine)
471 cf::get_slot +(length $_[0]) / 100_000_000, 0, "unlzf";
472 Compress::LZF::decompress $_[0]
473}
474
344=item cf::post_init { BLOCK } 475=item cf::post_init { BLOCK }
345 476
346Execute the given codeblock, I<after> all extensions have been (re-)loaded, 477Execute the given codeblock, I<after> all extensions have been (re-)loaded,
347but I<before> the server starts ticking again. 478but I<before> the server starts ticking again.
348 479
349The cdoeblock will have a single boolean argument to indicate whether this 480The codeblock will have a single boolean argument to indicate whether this
350is a reload or not. 481is a reload or not.
351 482
352=cut 483=cut
353 484
354sub post_init(&) { 485sub post_init(&) {
355 push @POST_INIT, shift; 486 push @POST_INIT, shift;
487}
488
489sub _post_init {
490 trace "running post_init jobs";
491
492 # run them in parallel...
493
494 my @join;
495
496 while () {
497 push @join, map &Coro::async ($_, 0), @POST_INIT;
498 @POST_INIT = ();
499
500 @join or last;
501
502 (pop @join)->join;
503 }
356} 504}
357 505
358=item cf::lock_wait $string 506=item cf::lock_wait $string
359 507
360Wait until the given lock is available. See cf::lock_acquire. 508Wait until the given lock is available. See cf::lock_acquire.
413 EV::periodic $start, $interval, 0, $cb 561 EV::periodic $start, $interval, 0, $cb
414} 562}
415 563
416=item cf::get_slot $time[, $priority[, $name]] 564=item cf::get_slot $time[, $priority[, $name]]
417 565
418Allocate $time seconds of blocking CPU time at priority C<$priority>: 566Allocate $time seconds of blocking CPU time at priority C<$priority>
419This call blocks and returns only when you have at least C<$time> seconds 567(default: 0): This call blocks and returns only when you have at least
420of cpu time till the next tick. The slot is only valid till the next cede. 568C<$time> seconds of cpu time till the next tick. The slot is only valid
569till the next cede.
570
571Background jobs should use a priority les than zero, interactive jobs
572should use 100 or more.
421 573
422The optional C<$name> can be used to identify the job to run. It might be 574The optional C<$name> can be used to identify the job to run. It might be
423used for statistical purposes and should identify the same time-class. 575used for statistical purposes and should identify the same time-class.
424 576
425Useful for short background jobs. 577Useful for short background jobs.
454 } 606 }
455 } 607 }
456 608
457 if (@SLOT_QUEUE) { 609 if (@SLOT_QUEUE) {
458 # we do not use wait_for_tick() as it returns immediately when tick is inactive 610 # we do not use wait_for_tick() as it returns immediately when tick is inactive
459 push @cf::WAIT_FOR_TICK, $signal; 611 $WAIT_FOR_TICK->wait;
460 $signal->wait;
461 } else { 612 } else {
462 $busy = 0; 613 $busy = 0;
463 Coro::schedule; 614 Coro::schedule;
464 } 615 }
465 } 616 }
505=cut 656=cut
506 657
507sub sync_job(&) { 658sub sync_job(&) {
508 my ($job) = @_; 659 my ($job) = @_;
509 660
510 if ($Coro::current == $Coro::main) { 661 if (in_main) {
511 my $time = AE::time; 662 my $time = AE::time;
512 663
513 # this is the main coro, too bad, we have to block 664 # this is the main coro, too bad, we have to block
514 # till the operation succeeds, freezing the server :/ 665 # till the operation succeeds, freezing the server :/
515 666
516 LOG llevError, Carp::longmess "sync job";#d# 667 #LOG llevError, Carp::longmess "sync job";#d#
517 668
518 my $freeze_guard = freeze_mainloop; 669 my $freeze_guard = freeze_mainloop;
519 670
520 my $busy = 1; 671 my $busy = 1;
521 my @res; 672 my @res;
522 673
523 (async { 674 (async {
524 $Coro::current->desc ("sync job coro"); 675 $Coro::current->desc ("sync job coro");
525 @res = eval { $job->() }; 676 @res = eval { $job->() };
526 warn $@ if $@; 677 error $@ if $@;
527 undef $busy; 678 undef $busy;
528 })->prio (Coro::PRIO_MAX); 679 })->prio (Coro::PRIO_MAX);
529 680
530 while ($busy) { 681 while ($busy) {
531 if (Coro::nready) { 682 if (Coro::nready) {
565 $EXT_CORO{$coro+0} = $coro; 716 $EXT_CORO{$coro+0} = $coro;
566 717
567 $coro 718 $coro
568} 719}
569 720
570=item fork_call { }, $args 721=item fork_call { }, @args
571 722
572Executes the given code block with the given arguments in a seperate 723Executes the given code block with the given arguments in a seperate
573process, returning the results. Everything must be serialisable with 724process, returning the results. Everything must be serialisable with
574Coro::Storable. May, of course, block. Note that the executed sub may 725Coro::Storable. May, of course, block. Note that the executed sub may
575never block itself or use any form of event handling. 726never block itself or use any form of event handling.
576 727
577=cut 728=cut
578 729
730sub post_fork {
731 reset_signals;
732}
733
579sub fork_call(&@) { 734sub fork_call(&@) {
580 my ($cb, @args) = @_; 735 my ($cb, @args) = @_;
581 736
582 # we seemingly have to make a local copy of the whole thing, 737 # we seemingly have to make a local copy of the whole thing,
583 # otherwise perl prematurely frees the stuff :/ 738 # otherwise perl prematurely frees the stuff :/
584 # TODO: investigate and fix (likely this will be rather laborious) 739 # TODO: investigate and fix (likely this will be rather laborious)
585 740
586 my @res = Coro::Util::fork_eval { 741 my @res = Coro::Util::fork_eval {
587 reset_signals; 742 cf::post_fork;
588 &$cb 743 &$cb
589 }, @args; 744 } @args;
590 745
591 wantarray ? @res : $res[-1] 746 wantarray ? @res : $res[-1]
592} 747}
593 748
594sub objinfo { 749sub objinfo {
644within each server. 799within each server.
645 800
646=cut 801=cut
647 802
648sub db_table($) { 803sub db_table($) {
804 cf::error "db_get called from main context"
805 if $Coro::current == $Coro::main;
806
649 my ($name) = @_; 807 my ($name) = @_;
650 my $db = BDB::db_create $DB_ENV; 808 my $db = BDB::db_create $DB_ENV;
651 809
652 eval { 810 eval {
653 $db->set_flags (BDB::CHKSUM); 811 $db->set_flags (BDB::CHKSUM);
663} 821}
664 822
665our $DB; 823our $DB;
666 824
667sub db_init { 825sub db_init {
668 cf::sync_job {
669 $DB ||= db_table "db"; 826 $DB ||= db_table "db";
670 };
671} 827}
672 828
673sub db_get($$) { 829sub db_get($$) {
674 my $key = "$_[0]/$_[1]"; 830 my $key = "$_[0]/$_[1]";
675 831
676 cf::sync_job { 832 cf::error "db_get called from main context"
833 if $Coro::current == $Coro::main;
834
677 BDB::db_get $DB, undef, $key, my $data; 835 BDB::db_get $DB, undef, $key, my $data;
678 836
679 $! ? () 837 $! ? ()
680 : $data 838 : $data
681 }
682} 839}
683 840
684sub db_put($$$) { 841sub db_put($$$) {
685 BDB::dbreq_pri 4; 842 BDB::dbreq_pri 4;
686 BDB::db_put $DB, undef, "$_[0]/$_[1]", $_[2], 0, sub { }; 843 BDB::db_put $DB, undef, "$_[0]/$_[1]", $_[2], 0, sub { };
714 871
715 my @data; 872 my @data;
716 my $md5; 873 my $md5;
717 874
718 for (0 .. $#$src) { 875 for (0 .. $#$src) {
719 0 <= aio_load $src->[$_], $data[$_] 876 $data[$_] = load_file $src->[$_];
720 or Carp::croak "$src->[$_]: $!";
721 } 877 }
722 878
723 # if processing is expensive, check 879 # if processing is expensive, check
724 # checksum first 880 # checksum first
725 if (1) { 881 if (1) {
742 898
743 my $t1 = Time::HiRes::time; 899 my $t1 = Time::HiRes::time;
744 my $data = $process->(\@data); 900 my $data = $process->(\@data);
745 my $t2 = Time::HiRes::time; 901 my $t2 = Time::HiRes::time;
746 902
747 warn "cache: '$id' processed in ", $t2 - $t1, "s\n"; 903 info "cache: '$id' processed in ", $t2 - $t1, "s\n";
748 904
749 db_put cache => "$id/data", $data; 905 db_put cache => "$id/data", $data;
750 db_put cache => "$id/md5" , $md5; 906 db_put cache => "$id/md5" , $md5;
751 db_put cache => "$id/meta", $meta; 907 db_put cache => "$id/meta", $meta;
752 908
762 918
763=cut 919=cut
764 920
765sub datalog($@) { 921sub datalog($@) {
766 my ($type, %kv) = @_; 922 my ($type, %kv) = @_;
767 warn "DATALOG ", JSON::XS->new->ascii->encode ({ %kv, type => $type }); 923 info "DATALOG ", JSON::XS->new->ascii->encode ({ %kv, type => $type });
768} 924}
769 925
770=back 926=back
771 927
772=cut 928=cut
967 1123
968 } elsif (exists $cb_id{$type}) { 1124 } elsif (exists $cb_id{$type}) {
969 _attach_cb $registry, $cb_id{$type}, $prio, shift @arg; 1125 _attach_cb $registry, $cb_id{$type}, $prio, shift @arg;
970 1126
971 } elsif (ref $type) { 1127 } elsif (ref $type) {
972 warn "attaching objects not supported, ignoring.\n"; 1128 error "attaching objects not supported, ignoring.\n";
973 1129
974 } else { 1130 } else {
975 shift @arg; 1131 shift @arg;
976 warn "attach argument '$type' not supported, ignoring.\n"; 1132 error "attach argument '$type' not supported, ignoring.\n";
977 } 1133 }
978 } 1134 }
979} 1135}
980 1136
981sub _object_attach { 1137sub _object_attach {
991 _attach $registry, $klass, @attach; 1147 _attach $registry, $klass, @attach;
992 } 1148 }
993 1149
994 $obj->{$name} = \%arg; 1150 $obj->{$name} = \%arg;
995 } else { 1151 } else {
996 warn "object uses attachment '$name' which is not available, postponing.\n"; 1152 info "object uses attachment '$name' which is not available, postponing.\n";
997 } 1153 }
998 1154
999 $obj->{_attachment}{$name} = undef; 1155 $obj->{_attachment}{$name} = undef;
1000} 1156}
1001 1157
1060 1216
1061 for (@$callbacks) { 1217 for (@$callbacks) {
1062 eval { &{$_->[1]} }; 1218 eval { &{$_->[1]} };
1063 1219
1064 if ($@) { 1220 if ($@) {
1065 warn "$@";
1066 warn "... while processing $EVENT[$event][0](@_) event, skipping processing altogether.\n"; 1221 error "$@", "... while processing $EVENT[$event][0](@_) event, skipping processing altogether.\n";
1067 override; 1222 override;
1068 } 1223 }
1069 1224
1070 return 1 if $override; 1225 return 1 if $override;
1071 } 1226 }
1150 for (@$attach) { 1305 for (@$attach) {
1151 my ($klass, @attach) = @$_; 1306 my ($klass, @attach) = @$_;
1152 _attach $registry, $klass, @attach; 1307 _attach $registry, $klass, @attach;
1153 } 1308 }
1154 } else { 1309 } else {
1155 warn "object uses attachment '$name' that is not available, postponing.\n"; 1310 info "object uses attachment '$name' that is not available, postponing.\n";
1156 } 1311 }
1157 } 1312 }
1158} 1313}
1159 1314
1160cf::attachable->attach ( 1315cf::attachable->attach (
1187 my ($filename, $rdata, $objs) = @_; 1342 my ($filename, $rdata, $objs) = @_;
1188 1343
1189 sync_job { 1344 sync_job {
1190 if (length $$rdata) { 1345 if (length $$rdata) {
1191 utf8::decode (my $decname = $filename); 1346 utf8::decode (my $decname = $filename);
1192 warn sprintf "saving %s (%d,%d)\n", 1347 trace sprintf "saving %s (%d,%d)\n",
1193 $decname, length $$rdata, scalar @$objs; 1348 $decname, length $$rdata, scalar @$objs
1349 if $VERBOSE_IO;
1194 1350
1195 if (my $fh = aio_open "$filename~", O_WRONLY | O_CREAT, 0600) { 1351 if (my $fh = aio_open "$filename~", O_WRONLY | O_CREAT, 0600) {
1196 aio_chmod $fh, SAVE_MODE; 1352 aio_chmod $fh, SAVE_MODE;
1197 aio_write $fh, 0, (length $$rdata), $$rdata, 0; 1353 aio_write $fh, 0, (length $$rdata), $$rdata, 0;
1198 if ($cf::USE_FSYNC) { 1354 if ($cf::USE_FSYNC) {
1220 aio_rename "$filename~", $filename; 1376 aio_rename "$filename~", $filename;
1221 1377
1222 $filename =~ s%/[^/]+$%%; 1378 $filename =~ s%/[^/]+$%%;
1223 aio_pathsync $filename if $cf::USE_FSYNC; 1379 aio_pathsync $filename if $cf::USE_FSYNC;
1224 } else { 1380 } else {
1225 warn "unable to save objects: $filename~: $!\n"; 1381 error "unable to save objects: $filename~: $!\n";
1226 } 1382 }
1227 } else { 1383 } else {
1228 aio_unlink $filename; 1384 aio_unlink $filename;
1229 aio_unlink "$filename.pst"; 1385 aio_unlink "$filename.pst";
1230 } 1386 }
1254 my $st = eval { Coro::Storable::thaw $av }; 1410 my $st = eval { Coro::Storable::thaw $av };
1255 $av = $st->{objs}; 1411 $av = $st->{objs};
1256 } 1412 }
1257 1413
1258 utf8::decode (my $decname = $filename); 1414 utf8::decode (my $decname = $filename);
1259 warn sprintf "loading %s (%d,%d)\n", 1415 trace sprintf "loading %s (%d,%d)\n",
1260 $decname, length $data, scalar @{$av || []}; 1416 $decname, length $data, scalar @{$av || []}
1417 if $VERBOSE_IO;
1261 1418
1262 ($data, $av) 1419 ($data, $av)
1263} 1420}
1264 1421
1265=head2 COMMAND CALLBACKS 1422=head2 COMMAND CALLBACKS
1342 my ($pl, $buf) = @_; 1499 my ($pl, $buf) = @_;
1343 1500
1344 my $msg = eval { $pl->ns->{json_coder}->decode ($buf) }; 1501 my $msg = eval { $pl->ns->{json_coder}->decode ($buf) };
1345 1502
1346 if (ref $msg) { 1503 if (ref $msg) {
1347 my ($type, $reply, @payload) = 1504 my ($type, $reply, @payload) = @$msg; # version 1 used %type, $id, %$hash
1348 "ARRAY" eq ref $msg
1349 ? @$msg
1350 : ($msg->{msgtype}, $msg->{msgid}, %$msg); # TODO: version 1, remove
1351 1505
1352 my @reply; 1506 my @reply;
1353 1507
1354 if (my $cb = $EXTCMD{$type}) { 1508 if (my $cb = $EXTCMD{$type}) {
1355 @reply = $cb->($pl, @payload); 1509 @reply = $cb->($pl, @payload);
1357 1511
1358 $pl->ext_reply ($reply, @reply) 1512 $pl->ext_reply ($reply, @reply)
1359 if $reply; 1513 if $reply;
1360 1514
1361 } else { 1515 } else {
1362 warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n"; 1516 error "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n";
1363 } 1517 }
1364 1518
1365 cf::override; 1519 cf::override;
1366 }, 1520 },
1367); 1521);
1378 1532
1379 $grp 1533 $grp
1380} 1534}
1381 1535
1382sub load_extensions { 1536sub load_extensions {
1537 info "loading extensions...";
1538
1383 cf::sync_job { 1539 cf::sync_job {
1384 my %todo; 1540 my %todo;
1385 1541
1386 for my $path (<$LIBDIR/*.ext>) { 1542 for my $path (<$LIBDIR/*.ext>) {
1387 next unless -r $path; 1543 next unless -r $path;
1405 1561
1406 $ext{meta} = { map { (split /=/, $_, 2)[0, 1] } split /\s+/, $1 } 1562 $ext{meta} = { map { (split /=/, $_, 2)[0, 1] } split /\s+/, $1 }
1407 if $source =~ /\A#!.*?perl.*?#\s*(.*)$/m; 1563 if $source =~ /\A#!.*?perl.*?#\s*(.*)$/m;
1408 1564
1409 $ext{source} = 1565 $ext{source} =
1410 "package $pkg; use 5.10.0; use strict 'vars', 'subs'; use utf8;\n" 1566 "package $pkg; use common::sense;\n"
1411 . "#line 1 \"$path\"\n{\n" 1567 . "#line 1 \"$path\"\n{\n"
1412 . $source 1568 . $source
1413 . "\n};\n1"; 1569 . "\n};\n1";
1414 1570
1415 $todo{$base} = \%ext; 1571 $todo{$base} = \%ext;
1427 for (split /,\s*/, $v->{meta}{depends}) { 1583 for (split /,\s*/, $v->{meta}{depends}) {
1428 next ext 1584 next ext
1429 unless exists $done{$_}; 1585 unless exists $done{$_};
1430 } 1586 }
1431 1587
1432 warn "... pass $pass, loading '$k' into '$v->{pkg}'\n"; 1588 trace "... pass $pass, loading '$k' into '$v->{pkg}'\n";
1433 1589
1434 my $active = eval $v->{source}; 1590 my $active = eval $v->{source};
1435 1591
1436 if (length $@) { 1592 if (length $@) {
1437 warn "$v->{path}: $@\n"; 1593 error "$v->{path}: $@\n";
1438 1594
1439 cf::cleanup "mandatory extension '$k' failed to load, exiting." 1595 cf::cleanup "mandatory extension '$k' failed to load, exiting."
1440 if exists $v->{meta}{mandatory}; 1596 if exists $v->{meta}{mandatory};
1597
1598 warn "$v->{base}: optional extension cannot be loaded, skipping.\n";
1599 delete $todo{$k};
1441 } else { 1600 } else {
1442 $done{$k} = delete $todo{$k}; 1601 $done{$k} = delete $todo{$k};
1443 push @EXTS, $v->{pkg}; 1602 push @EXTS, $v->{pkg};
1444 $progress = 1; 1603 $progress = 1;
1445 1604
1446 warn "$v->{base}: extension inactive.\n" 1605 info "$v->{base}: extension inactive.\n"
1447 unless $active; 1606 unless $active;
1448 } 1607 }
1449 } 1608 }
1450 1609
1451 unless ($progress) { 1610 unless ($progress) {
1453 1612
1454 while (my ($k, $v) = each %todo) { 1613 while (my ($k, $v) = each %todo) {
1455 cf::cleanup "mandatory extension '$k' has unresolved dependencies, exiting." 1614 cf::cleanup "mandatory extension '$k' has unresolved dependencies, exiting."
1456 if exists $v->{meta}{mandatory}; 1615 if exists $v->{meta}{mandatory};
1457 } 1616 }
1617
1618 last;
1458 } 1619 }
1459 } 1620 }
1460 }; 1621 };
1461} 1622}
1462 1623
1620 my $name = $pl->ob->name; 1781 my $name = $pl->ob->name;
1621 1782
1622 $pl->{deny_save} = 1; 1783 $pl->{deny_save} = 1;
1623 $pl->password ("*"); # this should lock out the player until we have nuked the dir 1784 $pl->password ("*"); # this should lock out the player until we have nuked the dir
1624 1785
1625 $pl->invoke (cf::EVENT_PLAYER_LOGOUT, 1) if $pl->active; 1786 $pl->invoke (cf::EVENT_PLAYER_LOGOUT, 1) if $pl->ns;
1626 $pl->deactivate; 1787 $pl->deactivate;
1788
1627 my $killer = cf::arch::get "killer_quit"; $pl->killer ($killer); $killer->destroy; 1789 my $killer = cf::arch::get "killer_quit"; $pl->killer ($killer); $killer->destroy;
1628 $pl->ob->check_score;
1629 $pl->invoke (cf::EVENT_PLAYER_QUIT); 1790 $pl->invoke (cf::EVENT_PLAYER_QUIT) if $pl->ns;
1791 ext::highscore::check ($pl->ob);
1792
1630 $pl->ns->destroy if $pl->ns; 1793 $pl->ns->destroy if $pl->ns;
1631 1794
1632 my $path = playerdir $pl; 1795 my $path = playerdir $pl;
1633 my $temp = "$path~$cf::RUNTIME~deleting~"; 1796 my $temp = "$path~$cf::RUNTIME~deleting~";
1634 aio_rename $path, $temp; 1797 aio_rename $path, $temp;
1688 \@logins 1851 \@logins
1689} 1852}
1690 1853
1691=item $player->maps 1854=item $player->maps
1692 1855
1856=item cf::player::maps $login
1857
1693Returns an arrayref of map paths that are private for this 1858Returns an arrayref of map paths that are private for this
1694player. May block. 1859player. May block.
1695 1860
1696=cut 1861=cut
1697 1862
1759=cut 1924=cut
1760 1925
1761sub find_by_path($) { 1926sub find_by_path($) {
1762 my ($path) = @_; 1927 my ($path) = @_;
1763 1928
1929 $path =~ s/^~[^\/]*//; # skip ~login
1930
1764 my ($match, $specificity); 1931 my ($match, $specificity);
1765 1932
1766 for my $region (list) { 1933 for my $region (list) {
1767 if ($region->{match} && $path =~ $region->{match}) { 1934 if ($region->{match} && $path =~ $region->{match}) {
1768 ($match, $specificity) = ($region, $region->specificity) 1935 ($match, $specificity) = ($region, $region->specificity)
1796sub generate_random_map { 1963sub generate_random_map {
1797 my ($self, $rmp) = @_; 1964 my ($self, $rmp) = @_;
1798 1965
1799 my $lock = cf::lock_acquire "generate_random_map"; # the random map generator is NOT reentrant ATM 1966 my $lock = cf::lock_acquire "generate_random_map"; # the random map generator is NOT reentrant ATM
1800 1967
1801 # mit "rum" bekleckern, nicht
1802 $self->_create_random_map ( 1968 $self->_create_random_map ($rmp);
1803 $rmp->{wallstyle}, $rmp->{wall_name}, $rmp->{floorstyle}, $rmp->{monsterstyle},
1804 $rmp->{treasurestyle}, $rmp->{layoutstyle}, $rmp->{doorstyle}, $rmp->{decorstyle}, $rmp->{miningstyle},
1805 $rmp->{origin_map}, $rmp->{final_map}, $rmp->{exitstyle}, $rmp->{this_map},
1806 $rmp->{exit_on_final_map},
1807 $rmp->{xsize}, $rmp->{ysize},
1808 $rmp->{expand2x}, $rmp->{layoutoptions1}, $rmp->{layoutoptions2}, $rmp->{layoutoptions3},
1809 $rmp->{symmetry}, $rmp->{difficulty}, $rmp->{difficulty_given}, $rmp->{difficulty_increase},
1810 $rmp->{dungeon_level}, $rmp->{dungeon_depth}, $rmp->{decoroptions}, $rmp->{orientation},
1811 $rmp->{origin_y}, $rmp->{origin_x}, $rmp->{random_seed}, $rmp->{total_map_hp},
1812 $rmp->{map_layout_style}, $rmp->{treasureoptions}, $rmp->{symmetry_used},
1813 (cf::region::find $rmp->{region}), $rmp->{custom}
1814 )
1815} 1969}
1816 1970
1817=item cf::map->register ($regex, $prio) 1971=item cf::map->register ($regex, $prio)
1818 1972
1819Register a handler for the map path matching the given regex at the 1973Register a handler for the map path matching the given regex at the
1824 1978
1825sub register { 1979sub register {
1826 my (undef, $regex, $prio) = @_; 1980 my (undef, $regex, $prio) = @_;
1827 my $pkg = caller; 1981 my $pkg = caller;
1828 1982
1829 no strict;
1830 push @{"$pkg\::ISA"}, __PACKAGE__; 1983 push @{"$pkg\::ISA"}, __PACKAGE__;
1831 1984
1832 $EXT_MAP{$pkg} = [$prio, qr<$regex>]; 1985 $EXT_MAP{$pkg} = [$prio, qr<$regex>];
1833} 1986}
1834 1987
1835# also paths starting with '/' 1988# also paths starting with '/'
1836$EXT_MAP{"cf::map"} = [0, qr{^(?=/)}]; 1989$EXT_MAP{"cf::map::wrap"} = [0, qr{^(?=/)}];
1837 1990
1838sub thawer_merge { 1991sub thawer_merge {
1839 my ($self, $merge) = @_; 1992 my ($self, $merge) = @_;
1840 1993
1841 # we have to keep some variables in memory intact 1994 # we have to keep some variables in memory intact
1846} 1999}
1847 2000
1848sub normalise { 2001sub normalise {
1849 my ($path, $base) = @_; 2002 my ($path, $base) = @_;
1850 2003
1851 $path = "$path"; # make sure its a string 2004 $path = "$path"; # make sure it's a string
1852 2005
1853 $path =~ s/\.map$//; 2006 $path =~ s/\.map$//;
1854 2007
1855 # map plan: 2008 # map plan:
1856 # 2009 #
1871 $base =~ s{[^/]+/?$}{}; 2024 $base =~ s{[^/]+/?$}{};
1872 $path = "$base/$path"; 2025 $path = "$base/$path";
1873 } 2026 }
1874 2027
1875 for ($path) { 2028 for ($path) {
1876 redo if s{//}{/};
1877 redo if s{/\.?/}{/}; 2029 redo if s{/\.?/}{/};
1878 redo if s{/[^/]+/\.\./}{/}; 2030 redo if s{/[^/]+/\.\./}{/};
1879 } 2031 }
1880 2032
1881 $path 2033 $path
1895 $self->init; # pass $1 etc. 2047 $self->init; # pass $1 etc.
1896 return $self; 2048 return $self;
1897 } 2049 }
1898 } 2050 }
1899 2051
1900 Carp::cluck "unable to resolve path '$path' (base '$base')."; 2052 Carp::cluck "unable to resolve path '$path' (base '$base')";
1901 () 2053 ()
1902} 2054}
1903 2055
2056# may re-bless or do other evil things
1904sub init { 2057sub init {
1905 my ($self) = @_; 2058 my ($self) = @_;
1906 2059
1907 $self 2060 $self
1908} 2061}
1973 $self->{load_path} = $path; 2126 $self->{load_path} = $path;
1974 2127
1975 1 2128 1
1976} 2129}
1977 2130
2131# used to laod the header of an original map
1978sub load_header_orig { 2132sub load_header_orig {
1979 my ($self) = @_; 2133 my ($self) = @_;
1980 2134
1981 $self->load_header_from ($self->load_path) 2135 $self->load_header_from ($self->load_path)
1982} 2136}
1983 2137
2138# used to laod the header of an instantiated map
1984sub load_header_temp { 2139sub load_header_temp {
1985 my ($self) = @_; 2140 my ($self) = @_;
1986 2141
1987 $self->load_header_from ($self->save_path) 2142 $self->load_header_from ($self->save_path)
1988} 2143}
1989 2144
2145# called after loading the header from an instantiated map
1990sub prepare_temp { 2146sub prepare_temp {
1991 my ($self) = @_; 2147 my ($self) = @_;
1992 2148
1993 $self->last_access ((delete $self->{last_access}) 2149 $self->last_access ((delete $self->{last_access})
1994 || $cf::RUNTIME); #d# 2150 || $cf::RUNTIME); #d#
1995 # safety 2151 # safety
1996 $self->{instantiate_time} = $cf::RUNTIME 2152 $self->{instantiate_time} = $cf::RUNTIME
1997 if $self->{instantiate_time} > $cf::RUNTIME; 2153 if $self->{instantiate_time} > $cf::RUNTIME;
1998} 2154}
1999 2155
2156# called after loading the header from an original map
2000sub prepare_orig { 2157sub prepare_orig {
2001 my ($self) = @_; 2158 my ($self) = @_;
2002 2159
2003 $self->{load_original} = 1; 2160 $self->{load_original} = 1;
2004 $self->{instantiate_time} = $cf::RUNTIME; 2161 $self->{instantiate_time} = $cf::RUNTIME;
2028 2185
2029sub find; 2186sub find;
2030sub find { 2187sub find {
2031 my ($path, $origin) = @_; 2188 my ($path, $origin) = @_;
2032 2189
2190 cf::cede_to_tick;
2191
2033 $path = normalise $path, $origin && $origin->path; 2192 $path = normalise $path, $origin;
2034 2193
2035 my $guard1 = cf::lock_acquire "map_data:$path";#d#remove 2194 my $guard1 = cf::lock_acquire "map_data:$path";#d#remove
2036 my $guard2 = cf::lock_acquire "map_find:$path"; 2195 my $guard2 = cf::lock_acquire "map_find:$path";
2037 2196
2038 $cf::MAP{$path} || do { 2197 $cf::MAP{$path} || do {
2069 2228
2070 { 2229 {
2071 my $guard = cf::lock_acquire "map_data:$path"; 2230 my $guard = cf::lock_acquire "map_data:$path";
2072 2231
2073 return unless $self->valid; 2232 return unless $self->valid;
2074 return unless $self->in_memory == cf::MAP_SWAPPED; 2233 return unless $self->state == cf::MAP_SWAPPED;
2075
2076 $self->in_memory (cf::MAP_LOADING);
2077 2234
2078 $self->alloc; 2235 $self->alloc;
2079 2236
2080 $self->pre_load; 2237 $self->pre_load;
2081 cf::cede_to_tick; 2238 cf::cede_to_tick;
2082 2239
2240 if (exists $self->{load_path}) {
2083 my $f = new_from_file cf::object::thawer $self->{load_path}; 2241 my $f = new_from_file cf::object::thawer $self->{load_path};
2084 $f->skip_block; 2242 $f->skip_block;
2085 $self->_load_objects ($f) 2243 $self->_load_objects ($f)
2086 or return; 2244 or return;
2087 2245
2088 $self->post_load_original 2246 $self->post_load_original
2089 if delete $self->{load_original}; 2247 if delete $self->{load_original};
2090 2248
2091 if (my $uniq = $self->uniq_path) { 2249 if (my $uniq = $self->uniq_path) {
2092 utf8::encode $uniq; 2250 utf8::encode $uniq;
2093 unless (aio_stat $uniq) { 2251 unless (aio_stat $uniq) {
2094 if (my $f = new_from_file cf::object::thawer $uniq) { 2252 if (my $f = new_from_file cf::object::thawer $uniq) {
2095 $self->clear_unique_items; 2253 $self->clear_unique_items;
2096 $self->_load_objects ($f); 2254 $self->_load_objects ($f);
2097 $f->resolve_delayed_derefs; 2255 $f->resolve_delayed_derefs;
2256 }
2098 } 2257 }
2099 } 2258 }
2100 }
2101 2259
2102 $f->resolve_delayed_derefs; 2260 $f->resolve_delayed_derefs;
2261 } else {
2262 $self->post_load_original
2263 if delete $self->{load_original};
2264 }
2265
2266 $self->state (cf::MAP_INACTIVE);
2103 2267
2104 cf::cede_to_tick; 2268 cf::cede_to_tick;
2105 # now do the right thing for maps 2269 # now do the right thing for maps
2106 $self->link_multipart_objects; 2270 $self->link_multipart_objects;
2107 $self->difficulty ($self->estimate_difficulty) 2271 $self->difficulty ($self->estimate_difficulty)
2111 unless ($self->{deny_activate}) { 2275 unless ($self->{deny_activate}) {
2112 $self->decay_objects; 2276 $self->decay_objects;
2113 $self->fix_auto_apply; 2277 $self->fix_auto_apply;
2114 $self->update_buttons; 2278 $self->update_buttons;
2115 cf::cede_to_tick; 2279 cf::cede_to_tick;
2116 $self->activate; 2280 #$self->activate; # no longer activate maps automatically
2117 } 2281 }
2118 2282
2119 $self->{last_save} = $cf::RUNTIME; 2283 $self->{last_save} = $cf::RUNTIME;
2120 $self->last_access ($cf::RUNTIME); 2284 $self->last_access ($cf::RUNTIME);
2121
2122 $self->in_memory (cf::MAP_ACTIVE);
2123 } 2285 }
2124 2286
2125 $self->post_load; 2287 $self->post_load;
2288
2289 1
2126} 2290}
2127 2291
2128# customize the map for a given player, i.e. 2292# customize the map for a given player, i.e.
2129# return the _real_ map. used by e.g. per-player 2293# return the _real_ map. used by e.g. per-player
2130# maps to change the path to ~playername/mappath 2294# maps to change the path to ~playername/mappath
2138# if $self->per_party; 2302# if $self->per_party;
2139 2303
2140 $self 2304 $self
2141} 2305}
2142 2306
2143# find and load all maps in the 3x3 area around a map
2144sub load_neighbours {
2145 my ($map) = @_;
2146
2147 my @neigh; # diagonal neighbours
2148
2149 for (0 .. 3) {
2150 my $neigh = $map->tile_path ($_)
2151 or next;
2152 $neigh = find $neigh, $map
2153 or next;
2154 $neigh->load;
2155
2156 push @neigh,
2157 [$neigh->tile_path (($_ + 3) % 4), $neigh],
2158 [$neigh->tile_path (($_ + 1) % 4), $neigh];
2159 }
2160
2161 for (grep defined $_->[0], @neigh) {
2162 my ($path, $origin) = @$_;
2163 my $neigh = find $path, $origin
2164 or next;
2165 $neigh->load;
2166 }
2167}
2168
2169sub find_sync { 2307sub find_sync {
2170 my ($path, $origin) = @_; 2308 my ($path, $origin) = @_;
2171 2309
2172 cf::sync_job { find $path, $origin } 2310 # it's a bug to call this from the main context
2311 return cf::LOG cf::llevError | cf::logBacktrace, "do_find_sync"
2312 if $Coro::current == $Coro::main;
2313
2314 find $path, $origin
2173} 2315}
2174 2316
2175sub do_load_sync { 2317sub do_load_sync {
2176 my ($map) = @_; 2318 my ($map) = @_;
2177 2319
2320 # it's a bug to call this from the main context
2178 cf::LOG cf::llevDebug | cf::logBacktrace, "do_load_sync" 2321 return cf::LOG cf::llevError | cf::logBacktrace, "do_load_sync"
2179 if $Coro::current == $Coro::main; 2322 if $Coro::current == $Coro::main;
2180 2323
2181 cf::sync_job { $map->load }; 2324 $map->load;
2182} 2325}
2183 2326
2184our %MAP_PREFETCH; 2327our %MAP_PREFETCH;
2185our $MAP_PREFETCHER = undef; 2328our $MAP_PREFETCHER = undef;
2186 2329
2187sub find_async { 2330sub find_async {
2188 my ($path, $origin, $load) = @_; 2331 my ($path, $origin, $load) = @_;
2189 2332
2190 $path = normalise $path, $origin && $origin->{path}; 2333 $path = normalise $path, $origin;
2191 2334
2192 if (my $map = $cf::MAP{$path}) { 2335 if (my $map = $cf::MAP{$path}) {
2193 return $map if !$load || $map->in_memory == cf::MAP_ACTIVE; 2336 return $map if !$load || $map->linkable;
2194 } 2337 }
2195 2338
2196 $MAP_PREFETCH{$path} |= $load; 2339 $MAP_PREFETCH{$path} |= $load;
2197 2340
2198 $MAP_PREFETCHER ||= cf::async { 2341 $MAP_PREFETCHER ||= cf::async {
2212 $MAP_PREFETCHER->prio (6); 2355 $MAP_PREFETCHER->prio (6);
2213 2356
2214 () 2357 ()
2215} 2358}
2216 2359
2360# common code, used by both ->save and ->swapout
2217sub save { 2361sub _save {
2218 my ($self) = @_; 2362 my ($self) = @_;
2219
2220 my $lock = cf::lock_acquire "map_data:$self->{path}";
2221 2363
2222 $self->{last_save} = $cf::RUNTIME; 2364 $self->{last_save} = $cf::RUNTIME;
2223 2365
2224 return unless $self->dirty; 2366 return unless $self->dirty;
2225 2367
2245 } else { 2387 } else {
2246 $self->_save_objects ($save, cf::IO_HEADER | cf::IO_OBJECTS | cf::IO_UNIQUES); 2388 $self->_save_objects ($save, cf::IO_HEADER | cf::IO_OBJECTS | cf::IO_UNIQUES);
2247 } 2389 }
2248} 2390}
2249 2391
2392sub save {
2393 my ($self) = @_;
2394
2395 my $lock = cf::lock_acquire "map_data:$self->{path}";
2396
2397 $self->_save;
2398}
2399
2250sub swap_out { 2400sub swap_out {
2251 my ($self) = @_; 2401 my ($self) = @_;
2252 2402
2253 # save first because save cedes
2254 $self->save;
2255
2256 my $lock = cf::lock_acquire "map_data:$self->{path}"; 2403 my $lock = cf::lock_acquire "map_data:$self->{path}";
2257 2404
2405 return if !$self->linkable;
2406 return if $self->{deny_save};
2258 return if $self->players; 2407 return if $self->players;
2259 return if $self->in_memory != cf::MAP_ACTIVE; 2408
2409 # first deactivate the map and "unlink" it from the core
2410 $self->deactivate;
2411 $_->clear_links_to ($self) for values %cf::MAP;
2412 $self->state (cf::MAP_SWAPPED);
2413
2414 # then atomically save
2415 $self->_save;
2416
2417 # then free the map
2418 $self->clear;
2419}
2420
2421sub reset_at {
2422 my ($self) = @_;
2423
2424 # TODO: safety, remove and allow resettable per-player maps
2260 return if $self->{deny_save}; 2425 return 1e99 if $self->{deny_reset};
2261 2426
2427 my $time = $self->fixed_resettime ? $self->{instantiate_time} : $self->last_access;
2428 my $to = List::Util::min $MAX_RESET, $self->reset_timeout || $DEFAULT_RESET;
2429
2430 $time + $to
2431}
2432
2433sub should_reset {
2434 my ($self) = @_;
2435
2436 $self->reset_at <= $cf::RUNTIME
2437}
2438
2439sub reset {
2440 my ($self) = @_;
2441
2442 my $lock = cf::lock_acquire "map_data:$self->{path}";
2443
2444 return if $self->players;
2445
2446 cf::trace "resetting map ", $self->path, "\n";
2447
2262 $self->in_memory (cf::MAP_SWAPPED); 2448 $self->state (cf::MAP_SWAPPED);
2449
2450 # need to save uniques path
2451 unless ($self->{deny_save}) {
2452 my $uniq = $self->uniq_path; utf8::encode $uniq;
2453
2454 $self->_save_objects ($uniq, cf::IO_UNIQUES)
2455 if $uniq;
2456 }
2457
2458 delete $cf::MAP{$self->path};
2263 2459
2264 $self->deactivate; 2460 $self->deactivate;
2265 $_->clear_links_to ($self) for values %cf::MAP; 2461 $_->clear_links_to ($self) for values %cf::MAP;
2266 $self->clear; 2462 $self->clear;
2267}
2268
2269sub reset_at {
2270 my ($self) = @_;
2271
2272 # TODO: safety, remove and allow resettable per-player maps
2273 return 1e99 if $self->{deny_reset};
2274
2275 my $time = $self->fixed_resettime ? $self->{instantiate_time} : $self->last_access;
2276 my $to = List::Util::min $MAX_RESET, $self->reset_timeout || $DEFAULT_RESET;
2277
2278 $time + $to
2279}
2280
2281sub should_reset {
2282 my ($self) = @_;
2283
2284 $self->reset_at <= $cf::RUNTIME
2285}
2286
2287sub reset {
2288 my ($self) = @_;
2289
2290 my $lock = cf::lock_acquire "map_data:$self->{path}";
2291
2292 return if $self->players;
2293
2294 warn "resetting map ", $self->path, "\n";
2295
2296 $self->in_memory (cf::MAP_SWAPPED);
2297
2298 # need to save uniques path
2299 unless ($self->{deny_save}) {
2300 my $uniq = $self->uniq_path; utf8::encode $uniq;
2301
2302 $self->_save_objects ($uniq, cf::IO_UNIQUES)
2303 if $uniq;
2304 }
2305
2306 delete $cf::MAP{$self->path};
2307
2308 $self->deactivate;
2309 $_->clear_links_to ($self) for values %cf::MAP;
2310 $self->clear;
2311 2463
2312 $self->unlink_save; 2464 $self->unlink_save;
2313 $self->destroy; 2465 $self->destroy;
2314} 2466}
2315 2467
2323 2475
2324 delete $cf::MAP{$self->path}; 2476 delete $cf::MAP{$self->path};
2325 2477
2326 $self->unlink_save; 2478 $self->unlink_save;
2327 2479
2328 bless $self, "cf::map"; 2480 bless $self, "cf::map::wrap";
2329 delete $self->{deny_reset}; 2481 delete $self->{deny_reset};
2330 $self->{deny_save} = 1; 2482 $self->{deny_save} = 1;
2331 $self->reset_timeout (1); 2483 $self->reset_timeout (1);
2332 $self->path ($self->{path} = "{nuke}/" . ($nuke_counter++)); 2484 $self->path ($self->{path} = "{nuke}/" . ($nuke_counter++));
2333 2485
2563 2715
2564Freezes the player and moves him/her to a special map (C<{link}>). 2716Freezes the player and moves him/her to a special map (C<{link}>).
2565 2717
2566The player should be reasonably safe there for short amounts of time (e.g. 2718The player should be reasonably safe there for short amounts of time (e.g.
2567for loading a map). You I<MUST> call C<leave_link> as soon as possible, 2719for loading a map). You I<MUST> call C<leave_link> as soon as possible,
2568though, as the palyer cannot control the character while it is on the link 2720though, as the player cannot control the character while it is on the link
2569map. 2721map.
2570 2722
2571Will never block. 2723Will never block.
2572 2724
2573=item $player_object->leave_link ($map, $x, $y) 2725=item $player_object->leave_link ($map, $x, $y)
2594sub cf::object::player::enter_link { 2746sub cf::object::player::enter_link {
2595 my ($self) = @_; 2747 my ($self) = @_;
2596 2748
2597 $self->deactivate_recursive; 2749 $self->deactivate_recursive;
2598 2750
2751 ++$self->{_link_recursion};
2752
2599 return if UNIVERSAL::isa $self->map, "ext::map_link"; 2753 return if UNIVERSAL::isa $self->map, "ext::map_link";
2600 2754
2601 $self->{_link_pos} ||= [$self->map->{path}, $self->x, $self->y] 2755 $self->{_link_pos} ||= [$self->map->{path}, $self->x, $self->y]
2602 if $self->map && $self->map->{path} ne "{link}"; 2756 if $self->map && $self->map->{path} ne "{link}";
2603 2757
2604 $self->enter_map ($LINK_MAP || link_map, 10, 10); 2758 $self->enter_map ($LINK_MAP || link_map, 3, 3);
2605} 2759}
2606 2760
2607sub cf::object::player::leave_link { 2761sub cf::object::player::leave_link {
2608 my ($self, $map, $x, $y) = @_; 2762 my ($self, $map, $x, $y) = @_;
2609 2763
2629 # use -1 or undef as default coordinates, not 0, 0 2783 # use -1 or undef as default coordinates, not 0, 0
2630 ($x, $y) = ($map->enter_x, $map->enter_y) 2784 ($x, $y) = ($map->enter_x, $map->enter_y)
2631 if $x <= 0 && $y <= 0; 2785 if $x <= 0 && $y <= 0;
2632 2786
2633 $map->load; 2787 $map->load;
2634 $map->load_neighbours;
2635 2788
2636 return unless $self->contr->active; 2789 return unless $self->contr->active;
2637 2790
2638 local $self->{_prev_pos} = $link_pos; # ugly hack for rent.ext 2791 local $self->{_prev_pos} = $link_pos; # ugly hack for rent.ext
2639 $self->enter_map ($map, $x, $y); 2792 if ($self->enter_map ($map, $x, $y)) {
2640 2793 # entering was successful
2794 delete $self->{_link_recursion};
2641 # only activate afterwards, to support waiting in hooks 2795 # only activate afterwards, to support waiting in hooks
2642 $self->activate_recursive; 2796 $self->activate_recursive;
2643} 2797 }
2644 2798
2799}
2800
2645=item $player_object->goto ($path, $x, $y[, $check->($map)[, $done->()]]) 2801=item $player_object->goto ($path, $x, $y[, $check->($map, $x, $y, $player)[, $done->($player)]])
2646 2802
2647Moves the player to the given map-path and coordinates by first freezing 2803Moves the player to the given map-path and coordinates by first freezing
2648her, loading and preparing them map, calling the provided $check callback 2804her, loading and preparing them map, calling the provided $check callback
2649that has to return the map if sucecssful, and then unfreezes the player on 2805that has to return the map if sucecssful, and then unfreezes the player on
2650the new (success) or old (failed) map position. In either case, $done will 2806the new (success) or old (failed) map position. In either case, $done will
2657 2813
2658our $GOTOGEN; 2814our $GOTOGEN;
2659 2815
2660sub cf::object::player::goto { 2816sub cf::object::player::goto {
2661 my ($self, $path, $x, $y, $check, $done) = @_; 2817 my ($self, $path, $x, $y, $check, $done) = @_;
2818
2819 if ($self->{_link_recursion} >= $MAX_LINKS) {
2820 error "FATAL: link recursion exceeded, ", $self->name, " goto $path $x $y, redirecting.";
2821 $self->failmsg ("Something went wrong inside the server - please contact an administrator!");
2822 ($path, $x, $y) = @$EMERGENCY_POSITION;
2823 }
2662 2824
2663 # do generation counting so two concurrent goto's will be executed in-order 2825 # do generation counting so two concurrent goto's will be executed in-order
2664 my $gen = $self->{_goto_generation} = ++$GOTOGEN; 2826 my $gen = $self->{_goto_generation} = ++$GOTOGEN;
2665 2827
2666 $self->enter_link; 2828 $self->enter_link;
2686 ($path, $x, $y) = (undef, undef, undef); 2848 ($path, $x, $y) = (undef, undef, undef);
2687 } 2849 }
2688 } 2850 }
2689 2851
2690 my $map = eval { 2852 my $map = eval {
2691 my $map = defined $path ? cf::map::find $path : undef; 2853 my $map = defined $path ? cf::map::find $path, $self->map : undef;
2692 2854
2693 if ($map) { 2855 if ($map) {
2694 $map = $map->customise_for ($self); 2856 $map = $map->customise_for ($self);
2695 $map = $check->($map) if $check && $map; 2857 $map = $check->($map, $x, $y, $self) if $check && $map;
2696 } else { 2858 } else {
2697 $self->message ("The exit to '$path' is closed.", cf::NDI_UNIQUE | cf::NDI_RED); 2859 $self->message ("The exit to '$path' is closed.", cf::NDI_UNIQUE | cf::NDI_RED);
2698 } 2860 }
2699 2861
2700 $map 2862 $map
2708 if ($gen == $self->{_goto_generation}) { 2870 if ($gen == $self->{_goto_generation}) {
2709 delete $self->{_goto_generation}; 2871 delete $self->{_goto_generation};
2710 $self->leave_link ($map, $x, $y); 2872 $self->leave_link ($map, $x, $y);
2711 } 2873 }
2712 2874
2713 $done->() if $done; 2875 $done->($self) if $done;
2714 })->prio (1); 2876 })->prio (1);
2715} 2877}
2716 2878
2717=item $player_object->enter_exit ($exit_object) 2879=item $player_object->enter_exit ($exit_object)
2718 2880
2786 $Coro::current->{desc} = "enter_exit"; 2948 $Coro::current->{desc} = "enter_exit";
2787 2949
2788 unless (eval { 2950 unless (eval {
2789 $self->deactivate_recursive; # just to be sure 2951 $self->deactivate_recursive; # just to be sure
2790 2952
2791 # random map handling
2792 {
2793 my $guard = cf::lock_acquire "exit_prepare:$exit";
2794
2795 prepare_random_map $exit
2796 if $exit->slaying eq "/!";
2797 }
2798
2799 my $map = cf::map::normalise $exit->slaying, $exit->map && $exit->map->path; 2953 my $map = cf::map::normalise $exit->slaying, $exit->map;
2800 my $x = $exit->stats->hp; 2954 my $x = $exit->stats->hp;
2801 my $y = $exit->stats->sp; 2955 my $y = $exit->stats->sp;
2956
2957 # special map handling
2958 my $slaying = $exit->slaying;
2959
2960 # special map handling
2961 if ($slaying eq "/!") {
2962 my $guard = cf::lock_acquire "exit_prepare:$exit";
2963
2964 prepare_random_map $exit
2965 if $exit->slaying eq "/!"; # need to re-check after getting the lock
2966
2967 $map = $exit->slaying;
2968
2969 } elsif ($slaying eq '!up') {
2970 $map = $exit->map->tile_path (cf::TILE_UP);
2971 $x = $exit->x;
2972 $y = $exit->y;
2973
2974 } elsif ($slaying eq '!down') {
2975 $map = $exit->map->tile_path (cf::TILE_DOWN);
2976 $x = $exit->x;
2977 $y = $exit->y;
2978 }
2802 2979
2803 $self->goto ($map, $x, $y); 2980 $self->goto ($map, $x, $y);
2804 2981
2805 # if exit is damned, update players death & WoR home-position 2982 # if exit is damned, update players death & WoR home-position
2806 $self->contr->savebed ($map, $x, $y) 2983 $self->contr->savebed ($map, $x, $y)
2811 $self->message ("Something went wrong deep within the deliantra server. " 2988 $self->message ("Something went wrong deep within the deliantra server. "
2812 . "I'll try to bring you back to the map you were before. " 2989 . "I'll try to bring you back to the map you were before. "
2813 . "Please report this to the dungeon master!", 2990 . "Please report this to the dungeon master!",
2814 cf::NDI_UNIQUE | cf::NDI_RED); 2991 cf::NDI_UNIQUE | cf::NDI_RED);
2815 2992
2816 warn "ERROR in enter_exit: $@"; 2993 error "ERROR in enter_exit: $@";
2817 $self->leave_link; 2994 $self->leave_link;
2818 } 2995 }
2819 })->prio (1); 2996 })->prio (1);
2820} 2997}
2821 2998
3048=cut 3225=cut
3049 3226
3050sub cf::client::ext_reply($$@) { 3227sub cf::client::ext_reply($$@) {
3051 my ($self, $id, @msg) = @_; 3228 my ($self, $id, @msg) = @_;
3052 3229
3053 if ($self->extcmd == 2) { 3230 return unless $self->extcmd == 2;
3231
3054 $self->send_big_packet ("ext " . $self->{json_coder}->encode (["reply-$id", @msg])); 3232 $self->send_big_packet ("ext " . $self->{json_coder}->encode (["reply-$id", @msg]));
3055 } elsif ($self->extcmd == 1) {
3056 #TODO: version 1, remove
3057 unshift @msg, msgtype => "reply", msgid => $id;
3058 $self->send_big_packet ("ext " . $self->{json_coder}->encode ({@msg}));
3059 }
3060} 3233}
3061 3234
3062=item $success = $client->query ($flags, "text", \&cb) 3235=item $success = $client->query ($flags, "text", \&cb)
3063 3236
3064Queues a query to the client, calling the given callback with 3237Queues a query to the client, calling the given callback with
3119 my ($ns, $buf) = @_; 3292 my ($ns, $buf) = @_;
3120 3293
3121 my $msg = eval { $ns->{json_coder}->decode ($buf) }; 3294 my $msg = eval { $ns->{json_coder}->decode ($buf) };
3122 3295
3123 if (ref $msg) { 3296 if (ref $msg) {
3124 my ($type, $reply, @payload) = 3297 my ($type, $reply, @payload) = @$msg; # version 1 used %type, $id, %$hash
3125 "ARRAY" eq ref $msg
3126 ? @$msg
3127 : ($msg->{msgtype}, $msg->{msgid}, %$msg); # TODO: version 1, remove
3128 3298
3129 my @reply; 3299 my @reply;
3130 3300
3131 if (my $cb = $EXTICMD{$type}) { 3301 if (my $cb = $EXTICMD{$type}) {
3132 @reply = $cb->($ns, @payload); 3302 @reply = $cb->($ns, @payload);
3134 3304
3135 $ns->ext_reply ($reply, @reply) 3305 $ns->ext_reply ($reply, @reply)
3136 if $reply; 3306 if $reply;
3137 3307
3138 } else { 3308 } else {
3139 warn "client " . ($ns->pl ? $ns->pl->ob->name : $ns->host) . " sent unparseable exti message: <$buf>\n"; 3309 error "client " . ($ns->pl ? $ns->pl->ob->name : $ns->host) . " sent unparseable exti message: <$buf>\n";
3140 } 3310 }
3141 3311
3142 cf::override; 3312 cf::override;
3143 }, 3313 },
3144); 3314);
3225 decrease split destroy change_exp value msg lore send_msg)], 3395 decrease split destroy change_exp value msg lore send_msg)],
3226 ["cf::object::player" => qw(player)], 3396 ["cf::object::player" => qw(player)],
3227 ["cf::player" => qw(peaceful send_msg)], 3397 ["cf::player" => qw(peaceful send_msg)],
3228 ["cf::map" => qw(trigger)], 3398 ["cf::map" => qw(trigger)],
3229) { 3399) {
3230 no strict 'refs';
3231 my ($pkg, @funs) = @$_; 3400 my ($pkg, @funs) = @$_;
3232 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"}) 3401 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"})
3233 for @funs; 3402 for @funs;
3234} 3403}
3235 3404
3274 local @cf::_safe_eval_args = values %vars; 3443 local @cf::_safe_eval_args = values %vars;
3275 @res = wantarray ? eval eval : scalar eval $eval; 3444 @res = wantarray ? eval eval : scalar eval $eval;
3276 } 3445 }
3277 3446
3278 if ($@) { 3447 if ($@) {
3279 warn "$@"; 3448 warn "$@",
3280 warn "while executing safe code '$code'\n"; 3449 "while executing safe code '$code'\n",
3281 warn "with arguments " . (join " ", %vars) . "\n"; 3450 "with arguments " . (join " ", %vars) . "\n";
3282 } 3451 }
3283 3452
3284 wantarray ? @res : $res[0] 3453 wantarray ? @res : $res[0]
3285} 3454}
3286 3455
3320 # for this (global event?) 3489 # for this (global event?)
3321 %ext::player_env::MUSIC_FACE_CACHE = (); 3490 %ext::player_env::MUSIC_FACE_CACHE = ();
3322 3491
3323 my $enc = JSON::XS->new->utf8->canonical->relaxed; 3492 my $enc = JSON::XS->new->utf8->canonical->relaxed;
3324 3493
3325 warn "loading facedata from $path\n"; 3494 trace "loading facedata from $path\n";
3326 3495
3327 my $facedata; 3496 my $facedata = decode_storable load_file $path;
3328 0 < aio_load $path, $facedata
3329 or die "$path: $!";
3330
3331 $facedata = Coro::Storable::thaw $facedata;
3332 3497
3333 $facedata->{version} == 2 3498 $facedata->{version} == 2
3334 or cf::cleanup "$path: version mismatch, cannot proceed."; 3499 or cf::cleanup "$path: version mismatch, cannot proceed.";
3335 3500
3336 # patch in the exptable 3501 # patch in the exptable
3350 3515
3351 cf::face::set_visibility $idx, $info->{visibility}; 3516 cf::face::set_visibility $idx, $info->{visibility};
3352 cf::face::set_magicmap $idx, $info->{magicmap}; 3517 cf::face::set_magicmap $idx, $info->{magicmap};
3353 cf::face::set_data $idx, 0, $info->{data32}, $info->{hash32}; 3518 cf::face::set_data $idx, 0, $info->{data32}, $info->{hash32};
3354 cf::face::set_data $idx, 1, $info->{data64}, $info->{hash64}; 3519 cf::face::set_data $idx, 1, $info->{data64}, $info->{hash64};
3520 cf::face::set_data $idx, 2, $info->{glyph} , $info->{glyph} ;
3355 3521
3356 cf::cede_to_tick; 3522 cf::cede_to_tick;
3357 } 3523 }
3358 3524
3359 while (my ($face, $info) = each %$faces) { 3525 while (my ($face, $info) = each %$faces) {
3364 3530
3365 if (my $smooth = cf::face::find $info->{smooth}) { 3531 if (my $smooth = cf::face::find $info->{smooth}) {
3366 cf::face::set_smooth $idx, $smooth; 3532 cf::face::set_smooth $idx, $smooth;
3367 cf::face::set_smoothlevel $idx, $info->{smoothlevel}; 3533 cf::face::set_smoothlevel $idx, $info->{smoothlevel};
3368 } else { 3534 } else {
3369 warn "smooth face '$info->{smooth}' not found for face '$face'"; 3535 error "smooth face '$info->{smooth}' not found for face '$face'";
3370 } 3536 }
3371 3537
3372 cf::cede_to_tick; 3538 cf::cede_to_tick;
3373 } 3539 }
3374 } 3540 }
3386 3552
3387 { 3553 {
3388 my $res = $facedata->{resource}; 3554 my $res = $facedata->{resource};
3389 3555
3390 while (my ($name, $info) = each %$res) { 3556 while (my ($name, $info) = each %$res) {
3391 if (defined $info->{type}) { 3557 if (defined (my $type = $info->{type})) {
3558 # TODO: different hash - must free and use new index, or cache ixface data queue
3392 my $idx = (cf::face::find $name) || cf::face::alloc $name; 3559 my $idx = (cf::face::find $name) || cf::face::alloc $name;
3393 3560
3394 cf::face::set_data $idx, 0, $info->{data}, $info->{hash}; 3561 cf::face::set_data $idx, 0, $info->{data}, $info->{hash};
3395 cf::face::set_type $idx, $info->{type}; 3562 cf::face::set_type $idx, $type;
3563 cf::face::set_meta $idx, $type & 1 ? undef : $info->{meta}; # preserve meta unless prepended already
3396 } else { 3564 } else {
3397 $RESOURCE{$name} = $info; 3565# $RESOURCE{$name} = $info; # unused
3398 } 3566 }
3399 3567
3400 cf::cede_to_tick; 3568 cf::cede_to_tick;
3401 } 3569 }
3402 } 3570 }
3403 3571
3404 cf::global->invoke (EVENT_GLOBAL_RESOURCE_UPDATE); 3572 cf::global->invoke (EVENT_GLOBAL_RESOURCE_UPDATE);
3405 3573
3406 1 3574 1
3407} 3575}
3408
3409cf::global->attach (on_resource_update => sub {
3410 if (my $soundconf = $RESOURCE{"res/sound.conf"}) {
3411 $soundconf = JSON::XS->new->utf8->relaxed->decode ($soundconf->{data});
3412
3413 for (0 .. SOUND_CAST_SPELL_0 - 1) {
3414 my $sound = $soundconf->{compat}[$_]
3415 or next;
3416
3417 my $face = cf::face::find "sound/$sound->[1]";
3418 cf::sound::set $sound->[0] => $face;
3419 cf::sound::old_sound_index $_, $face; # gcfclient-compat
3420 }
3421
3422 while (my ($k, $v) = each %{$soundconf->{event}}) {
3423 my $face = cf::face::find "sound/$v";
3424 cf::sound::set $k => $face;
3425 }
3426 }
3427});
3428 3576
3429register_exticmd fx_want => sub { 3577register_exticmd fx_want => sub {
3430 my ($ns, $want) = @_; 3578 my ($ns, $want) = @_;
3431 3579
3432 while (my ($k, $v) = each %$want) { 3580 while (my ($k, $v) = each %$want) {
3471sub reload_treasures { 3619sub reload_treasures {
3472 load_resource_file "$DATADIR/treasures" 3620 load_resource_file "$DATADIR/treasures"
3473 or die "unable to load treasurelists\n"; 3621 or die "unable to load treasurelists\n";
3474} 3622}
3475 3623
3624sub reload_sound {
3625 trace "loading sound config from $DATADIR/sound\n";
3626
3627 my $soundconf = JSON::XS->new->utf8->relaxed->decode (load_file "$DATADIR/sound");
3628
3629 for (0 .. SOUND_CAST_SPELL_0 - 1) {
3630 my $sound = $soundconf->{compat}[$_]
3631 or next;
3632
3633 my $face = cf::face::find "sound/$sound->[1]";
3634 cf::sound::set $sound->[0] => $face;
3635 cf::sound::old_sound_index $_, $face; # gcfclient-compat
3636 }
3637
3638 while (my ($k, $v) = each %{$soundconf->{event}}) {
3639 my $face = cf::face::find "sound/$v";
3640 cf::sound::set $k => $face;
3641 }
3642}
3643
3476sub reload_resources { 3644sub reload_resources {
3477 warn "reloading resource files...\n"; 3645 trace "reloading resource files...\n";
3478 3646
3647 reload_exp_table;
3648 reload_materials;
3479 reload_facedata; 3649 reload_facedata;
3650 reload_sound;
3480 reload_archetypes; 3651 reload_archetypes;
3481 reload_regions; 3652 reload_regions;
3482 reload_treasures; 3653 reload_treasures;
3483 3654
3484 warn "finished reloading resource files\n"; 3655 trace "finished reloading resource files\n";
3485} 3656}
3486 3657
3487sub reload_config { 3658sub reload_config {
3488 warn "reloading config file...\n"; 3659 trace "reloading config file...\n";
3489 3660
3490 open my $fh, "<:utf8", "$CONFDIR/config" 3661 my $config = load_file "$CONFDIR/config";
3491 or return; 3662 utf8::decode $config;
3663 *CFG = decode_yaml $config;
3492 3664
3493 local $/;
3494 *CFG = YAML::XS::Load scalar <$fh>;
3495
3496 $EMERGENCY_POSITION = $CFG{emergency_position} || ["/world/world_105_115", 5, 37]; 3665 $EMERGENCY_POSITION = $CFG{emergency_position} || ["/world/world_104_115", 49, 38];
3497 3666
3498 $cf::map::MAX_RESET = $CFG{map_max_reset} if exists $CFG{map_max_reset}; 3667 $cf::map::MAX_RESET = $CFG{map_max_reset} if exists $CFG{map_max_reset};
3499 $cf::map::DEFAULT_RESET = $CFG{map_default_reset} if exists $CFG{map_default_reset}; 3668 $cf::map::DEFAULT_RESET = $CFG{map_default_reset} if exists $CFG{map_default_reset};
3500 3669
3501 if (exists $CFG{mlockall}) { 3670 if (exists $CFG{mlockall}) {
3503 $CFG{mlockall} ? eval "mlockall()" : eval "munlockall()" 3672 $CFG{mlockall} ? eval "mlockall()" : eval "munlockall()"
3504 and die "WARNING: m(un)lockall failed: $!\n"; 3673 and die "WARNING: m(un)lockall failed: $!\n";
3505 }; 3674 };
3506 warn $@ if $@; 3675 warn $@ if $@;
3507 } 3676 }
3508
3509 warn "finished reloading resource files\n";
3510} 3677}
3511 3678
3512sub pidfile() { 3679sub pidfile() {
3513 sysopen my $fh, $PIDFILE, O_RDWR | O_CREAT 3680 sysopen my $fh, $PIDFILE, O_RDWR | O_CREAT
3514 or die "$PIDFILE: $!"; 3681 or die "$PIDFILE: $!";
3527 seek $fh, 0, 0; 3694 seek $fh, 0, 0;
3528 print $fh $$; 3695 print $fh $$;
3529} 3696}
3530 3697
3531sub main_loop { 3698sub main_loop {
3532 warn "EV::loop starting\n"; 3699 trace "EV::loop starting\n";
3533 if (1) { 3700 if (1) {
3534 EV::loop; 3701 EV::loop;
3535 } 3702 }
3536 warn "EV::loop returned\n"; 3703 trace "EV::loop returned\n";
3537 goto &main_loop unless $REALLY_UNLOOP; 3704 goto &main_loop unless $REALLY_UNLOOP;
3538} 3705}
3539 3706
3540sub main { 3707sub main {
3541 cf::init_globals; # initialise logging 3708 cf::init_globals; # initialise logging
3542 3709
3543 LOG llevInfo, "Welcome to Deliantra, v" . VERSION; 3710 LOG llevInfo, "Welcome to Deliantra, v" . VERSION;
3544 LOG llevInfo, "Copyright (C) 2005-2008 Marc Alexander Lehmann / Robin Redeker / the Deliantra team."; 3711 LOG llevInfo, "Copyright (C) 2005-2012 Marc Alexander Lehmann / Robin Redeker / the Deliantra team.";
3545 LOG llevInfo, "Copyright (C) 1994 Mark Wedel."; 3712 LOG llevInfo, "Copyright (C) 1994 Mark Wedel.";
3546 LOG llevInfo, "Copyright (C) 1992 Frank Tore Johansen."; 3713 LOG llevInfo, "Copyright (C) 1992 Frank Tore Johansen.";
3547 3714
3548 $Coro::current->prio (Coro::PRIO_MAX); # give the main loop max. priority 3715 $Coro::current->prio (Coro::PRIO_MAX); # give the main loop max. priority
3549 3716
3557 }; 3724 };
3558 3725
3559 evthread_start IO::AIO::poll_fileno; 3726 evthread_start IO::AIO::poll_fileno;
3560 3727
3561 cf::sync_job { 3728 cf::sync_job {
3562 cf::init_experience; 3729 cf::incloader::init ();
3730
3563 cf::init_anim; 3731 cf::init_anim;
3564 cf::init_attackmess; 3732 cf::init_attackmess;
3565 cf::init_dynamic; 3733 cf::init_dynamic;
3566 3734
3567 cf::load_settings; 3735 cf::load_settings;
3568 cf::load_materials;
3569 3736
3570 reload_resources; 3737 reload_resources;
3571 reload_config; 3738 reload_config;
3572 db_init; 3739 db_init;
3573 3740
3585 3752
3586 # no (long-running) fork's whatsoever before this point(!) 3753 # no (long-running) fork's whatsoever before this point(!)
3587 use POSIX (); 3754 use POSIX ();
3588 POSIX::close delete $ENV{LOCKUTIL_LOCK_FD} if exists $ENV{LOCKUTIL_LOCK_FD}; 3755 POSIX::close delete $ENV{LOCKUTIL_LOCK_FD} if exists $ENV{LOCKUTIL_LOCK_FD};
3589 3756
3590 (pop @POST_INIT)->(0) while @POST_INIT; 3757 cf::_post_init 0;
3591 }; 3758 };
3592 3759
3593 cf::object::thawer::errors_are_fatal 0; 3760 cf::object::thawer::errors_are_fatal 0;
3594 warn "parse errors in files are no longer fatal from this point on.\n"; 3761 info "parse errors in files are no longer fatal from this point on.\n";
3595 3762
3763 AE::postpone {
3764 undef &main; # free gobs of memory :)
3765 };
3766
3596 main_loop; 3767 goto &main_loop;
3597} 3768}
3598 3769
3599############################################################################# 3770#############################################################################
3600# initialisation and cleanup 3771# initialisation and cleanup
3601 3772
3640 or return; 3811 or return;
3641 3812
3642 aio_rename "$RUNTIMEFILE~", $RUNTIMEFILE 3813 aio_rename "$RUNTIMEFILE~", $RUNTIMEFILE
3643 and return; 3814 and return;
3644 3815
3645 warn sprintf "runtime file written (%gs).\n", AE::time - $t0; 3816 trace sprintf "runtime file written (%gs).\n", AE::time - $t0;
3646 3817
3647 1 3818 1
3648} 3819}
3649 3820
3650our $uuid_lock; 3821our $uuid_lock;
3662 or return; 3833 or return;
3663 3834
3664 my $value = uuid_seq uuid_cur; 3835 my $value = uuid_seq uuid_cur;
3665 3836
3666 unless ($value) { 3837 unless ($value) {
3667 warn "cowardly refusing to write zero uuid value!\n"; 3838 info "cowardly refusing to write zero uuid value!\n";
3668 return; 3839 return;
3669 } 3840 }
3670 3841
3671 my $value = uuid_str $value + $uuid_skip; 3842 my $value = uuid_str $value + $uuid_skip;
3672 $uuid_skip = 0; 3843 $uuid_skip = 0;
3682 or return; 3853 or return;
3683 3854
3684 aio_rename "$uuid~", $uuid 3855 aio_rename "$uuid~", $uuid
3685 and return; 3856 and return;
3686 3857
3687 warn "uuid file written ($value).\n"; 3858 trace "uuid file written ($value).\n";
3688 3859
3689 1 3860 1
3690 3861
3691} 3862}
3692 3863
3698} 3869}
3699 3870
3700sub emergency_save() { 3871sub emergency_save() {
3701 my $freeze_guard = cf::freeze_mainloop; 3872 my $freeze_guard = cf::freeze_mainloop;
3702 3873
3703 warn "emergency_perl_save: enter\n"; 3874 info "emergency_perl_save: enter\n";
3875
3876 # this is a trade-off: we want to be very quick here, so
3877 # save all maps without fsync, and later call a global sync
3878 # (which in turn might be very very slow)
3879 local $USE_FSYNC = 0;
3704 3880
3705 cf::sync_job { 3881 cf::sync_job {
3706 # this is a trade-off: we want to be very quick here, so 3882 cf::write_runtime_sync; # external watchdog should not bark
3707 # save all maps without fsync, and later call a global sync
3708 # (which in turn might be very very slow)
3709 local $USE_FSYNC = 0;
3710 3883
3711 # use a peculiar iteration method to avoid tripping on perl 3884 # use a peculiar iteration method to avoid tripping on perl
3712 # refcount bugs in for. also avoids problems with players 3885 # refcount bugs in for. also avoids problems with players
3713 # and maps saved/destroyed asynchronously. 3886 # and maps saved/destroyed asynchronously.
3714 warn "emergency_perl_save: begin player save\n"; 3887 info "emergency_perl_save: begin player save\n";
3715 for my $login (keys %cf::PLAYER) { 3888 for my $login (keys %cf::PLAYER) {
3716 my $pl = $cf::PLAYER{$login} or next; 3889 my $pl = $cf::PLAYER{$login} or next;
3717 $pl->valid or next; 3890 $pl->valid or next;
3718 delete $pl->{unclean_save}; # not strictly necessary, but cannot hurt 3891 delete $pl->{unclean_save}; # not strictly necessary, but cannot hurt
3719 $pl->save; 3892 $pl->save;
3720 } 3893 }
3721 warn "emergency_perl_save: end player save\n"; 3894 info "emergency_perl_save: end player save\n";
3722 3895
3896 cf::write_runtime_sync; # external watchdog should not bark
3897
3723 warn "emergency_perl_save: begin map save\n"; 3898 info "emergency_perl_save: begin map save\n";
3724 for my $path (keys %cf::MAP) { 3899 for my $path (keys %cf::MAP) {
3725 my $map = $cf::MAP{$path} or next; 3900 my $map = $cf::MAP{$path} or next;
3726 $map->valid or next; 3901 $map->valid or next;
3727 $map->save; 3902 $map->save;
3728 } 3903 }
3729 warn "emergency_perl_save: end map save\n"; 3904 info "emergency_perl_save: end map save\n";
3730 3905
3906 cf::write_runtime_sync; # external watchdog should not bark
3907
3731 warn "emergency_perl_save: begin database checkpoint\n"; 3908 info "emergency_perl_save: begin database checkpoint\n";
3732 BDB::db_env_txn_checkpoint $DB_ENV; 3909 BDB::db_env_txn_checkpoint $DB_ENV;
3733 warn "emergency_perl_save: end database checkpoint\n"; 3910 info "emergency_perl_save: end database checkpoint\n";
3734 3911
3735 warn "emergency_perl_save: begin write uuid\n"; 3912 info "emergency_perl_save: begin write uuid\n";
3736 write_uuid_sync 1; 3913 write_uuid_sync 1;
3737 warn "emergency_perl_save: end write uuid\n"; 3914 info "emergency_perl_save: end write uuid\n";
3915
3916 cf::write_runtime_sync; # external watchdog should not bark
3917
3918 trace "emergency_perl_save: syncing database to disk";
3919 BDB::db_env_txn_checkpoint $DB_ENV;
3920
3921 info "emergency_perl_save: starting sync\n";
3922 IO::AIO::aio_sync sub {
3923 info "emergency_perl_save: finished sync\n";
3924 };
3925
3926 cf::write_runtime_sync; # external watchdog should not bark
3927
3928 trace "emergency_perl_save: flushing outstanding aio requests";
3929 while (IO::AIO::nreqs || BDB::nreqs) {
3930 Coro::AnyEvent::sleep 0.01; # let the sync_job do it's thing
3931 }
3932
3933 cf::write_runtime_sync; # external watchdog should not bark
3738 }; 3934 };
3739 3935
3740 warn "emergency_perl_save: starting sync()\n";
3741 IO::AIO::aio_sync sub {
3742 warn "emergency_perl_save: finished sync()\n";
3743 };
3744
3745 warn "emergency_perl_save: leave\n"; 3936 info "emergency_perl_save: leave\n";
3746} 3937}
3747 3938
3748sub post_cleanup { 3939sub post_cleanup {
3749 my ($make_core) = @_; 3940 my ($make_core) = @_;
3750 3941
3942 IO::AIO::flush;
3943
3751 warn Carp::longmess "post_cleanup backtrace" 3944 error Carp::longmess "post_cleanup backtrace"
3752 if $make_core; 3945 if $make_core;
3753 3946
3754 my $fh = pidfile; 3947 my $fh = pidfile;
3755 unlink $PIDFILE if <$fh> == $$; 3948 unlink $PIDFILE if <$fh> == $$;
3756} 3949}
3776 my $leaf_symtab = *{$stem_symtab->{$leaf}}{HASH}; 3969 my $leaf_symtab = *{$stem_symtab->{$leaf}}{HASH};
3777 for my $name (keys %$leaf_symtab) { 3970 for my $name (keys %$leaf_symtab) {
3778 _gv_clear *{"$pkg$name"}; 3971 _gv_clear *{"$pkg$name"};
3779# use PApp::Util; PApp::Util::sv_dump *{"$pkg$name"}; 3972# use PApp::Util; PApp::Util::sv_dump *{"$pkg$name"};
3780 } 3973 }
3781 warn "cleared package $pkg\n";#d#
3782} 3974}
3783 3975
3784sub do_reload_perl() { 3976sub do_reload_perl() {
3785 # can/must only be called in main 3977 # can/must only be called in main
3786 if ($Coro::current != $Coro::main) { 3978 unless (in_main) {
3787 warn "can only reload from main coroutine"; 3979 error "can only reload from main coroutine";
3788 return; 3980 return;
3789 } 3981 }
3790 3982
3791 return if $RELOAD++; 3983 return if $RELOAD++;
3792 3984
3793 my $t1 = AE::time; 3985 my $t1 = AE::time;
3794 3986
3795 while ($RELOAD) { 3987 while ($RELOAD) {
3796 warn "reloading..."; 3988 cf::get_slot 0.1, -1, "reload_perl";
3989 info "perl_reload: reloading...";
3797 3990
3798 warn "entering sync_job"; 3991 trace "perl_reload: entering sync_job";
3799 3992
3800 cf::sync_job { 3993 cf::sync_job {
3801 cf::write_runtime_sync; # external watchdog should not bark
3802 cf::emergency_save; 3994 #cf::emergency_save;
3803 cf::write_runtime_sync; # external watchdog should not bark
3804 3995
3805 warn "syncing database to disk";
3806 BDB::db_env_txn_checkpoint $DB_ENV;
3807
3808 # if anything goes wrong in here, we should simply crash as we already saved
3809
3810 warn "flushing outstanding aio requests";
3811 while (IO::AIO::nreqs || BDB::nreqs) {
3812 Coro::EV::timer_once 0.01; # let the sync_job do it's thing
3813 }
3814
3815 warn "cancelling all extension coros"; 3996 trace "perl_reload: cancelling all extension coros";
3816 $_->cancel for values %EXT_CORO; 3997 $_->cancel for values %EXT_CORO;
3817 %EXT_CORO = (); 3998 %EXT_CORO = ();
3818 3999
3819 warn "removing commands"; 4000 trace "perl_reload: removing commands";
3820 %COMMAND = (); 4001 %COMMAND = ();
3821 4002
3822 warn "removing ext/exti commands"; 4003 trace "perl_reload: removing ext/exti commands";
3823 %EXTCMD = (); 4004 %EXTCMD = ();
3824 %EXTICMD = (); 4005 %EXTICMD = ();
3825 4006
3826 warn "unloading/nuking all extensions"; 4007 trace "perl_reload: unloading/nuking all extensions";
3827 for my $pkg (@EXTS) { 4008 for my $pkg (@EXTS) {
3828 warn "... unloading $pkg"; 4009 trace "... unloading $pkg";
3829 4010
3830 if (my $cb = $pkg->can ("unload")) { 4011 if (my $cb = $pkg->can ("unload")) {
3831 eval { 4012 eval {
3832 $cb->($pkg); 4013 $cb->($pkg);
3833 1 4014 1
3834 } or warn "$pkg unloaded, but with errors: $@"; 4015 } or error "$pkg unloaded, but with errors: $@";
3835 } 4016 }
3836 4017
3837 warn "... clearing $pkg"; 4018 trace "... clearing $pkg";
3838 clear_package $pkg; 4019 clear_package $pkg;
3839 } 4020 }
3840 4021
3841 warn "unloading all perl modules loaded from $LIBDIR"; 4022 trace "perl_reload: unloading all perl modules loaded from $LIBDIR";
3842 while (my ($k, $v) = each %INC) { 4023 while (my ($k, $v) = each %INC) {
3843 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/; 4024 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
3844 4025
3845 warn "... unloading $k"; 4026 trace "... unloading $k";
3846 delete $INC{$k}; 4027 delete $INC{$k};
3847 4028
3848 $k =~ s/\.pm$//; 4029 $k =~ s/\.pm$//;
3849 $k =~ s/\//::/g; 4030 $k =~ s/\//::/g;
3850 4031
3853 } 4034 }
3854 4035
3855 clear_package $k; 4036 clear_package $k;
3856 } 4037 }
3857 4038
3858 warn "getting rid of safe::, as good as possible"; 4039 trace "perl_reload: getting rid of safe::, as good as possible";
3859 clear_package "safe::$_" 4040 clear_package "safe::$_"
3860 for qw(cf::attachable cf::object cf::object::player cf::client cf::player cf::map cf::party cf::region); 4041 for qw(cf::attachable cf::object cf::object::player cf::client cf::player cf::map cf::party cf::region);
3861 4042
3862 warn "unloading cf.pm \"a bit\""; 4043 trace "perl_reload: unloading cf.pm \"a bit\"";
3863 delete $INC{"cf.pm"}; 4044 delete $INC{"cf.pm"};
3864 delete $INC{"cf/$_.pm"} for @EXTRA_MODULES; 4045 delete $INC{"cf/$_.pm"} for @EXTRA_MODULES;
3865 4046
3866 # don't, removes xs symbols, too, 4047 # don't, removes xs symbols, too,
3867 # and global variables created in xs 4048 # and global variables created in xs
3868 #clear_package __PACKAGE__; 4049 #clear_package __PACKAGE__;
3869 4050
3870 warn "unload completed, starting to reload now"; 4051 info "perl_reload: unload completed, starting to reload now";
3871 4052
3872 warn "reloading cf.pm"; 4053 trace "perl_reload: reloading cf.pm";
3873 require cf; 4054 require cf;
3874 cf::_connect_to_perl_1; 4055 cf::_connect_to_perl_1;
3875 4056
3876 warn "loading config and database again"; 4057 trace "perl_reload: loading config and database again";
3877 cf::reload_config; 4058 cf::reload_config;
3878 4059
3879 warn "loading extensions"; 4060 trace "perl_reload: loading extensions";
3880 cf::load_extensions; 4061 cf::load_extensions;
3881 4062
3882 if ($REATTACH_ON_RELOAD) { 4063 if ($REATTACH_ON_RELOAD) {
3883 warn "reattaching attachments to objects/players"; 4064 trace "perl_reload: reattaching attachments to objects/players";
3884 _global_reattach; # objects, sockets 4065 _global_reattach; # objects, sockets
3885 warn "reattaching attachments to maps"; 4066 trace "perl_reload: reattaching attachments to maps";
3886 reattach $_ for values %MAP; 4067 reattach $_ for values %MAP;
3887 warn "reattaching attachments to players"; 4068 trace "perl_reload: reattaching attachments to players";
3888 reattach $_ for values %PLAYER; 4069 reattach $_ for values %PLAYER;
3889 } 4070 }
3890 4071
3891 warn "running post_init jobs"; 4072 cf::_post_init 1;
3892 (pop @POST_INIT)->(1) while @POST_INIT;
3893 4073
3894 warn "leaving sync_job"; 4074 trace "perl_reload: leaving sync_job";
3895 4075
3896 1 4076 1
3897 } or do { 4077 } or do {
3898 warn $@; 4078 error $@;
3899 cf::cleanup "error while reloading, exiting."; 4079 cf::cleanup "perl_reload: error, exiting.";
3900 }; 4080 };
3901 4081
3902 warn "reloaded";
3903 --$RELOAD; 4082 --$RELOAD;
3904 } 4083 }
3905 4084
3906 $t1 = AE::time - $t1; 4085 $t1 = AE::time - $t1;
3907 warn "reload completed in ${t1}s\n"; 4086 info "perl_reload: completed in ${t1}s\n";
3908}; 4087};
3909 4088
3910our $RELOAD_WATCHER; # used only during reload 4089our $RELOAD_WATCHER; # used only during reload
3911 4090
3912sub reload_perl() { 4091sub reload_perl() {
3933 reload_perl; 4112 reload_perl;
3934 }; 4113 };
3935 } 4114 }
3936}; 4115};
3937 4116
3938unshift @INC, $LIBDIR; 4117#############################################################################
3939 4118
3940my $bug_warning = 0; 4119my $bug_warning = 0;
3941 4120
3942our @WAIT_FOR_TICK;
3943our @WAIT_FOR_TICK_BEGIN;
3944
3945sub wait_for_tick { 4121sub wait_for_tick() {
3946 return Coro::cede if tick_inhibit || $Coro::current == $Coro::main; 4122 return Coro::AnyEvent::poll if tick_inhibit || $Coro::current == $Coro::main;
3947 4123
3948 my $signal = new Coro::Signal; 4124 $WAIT_FOR_TICK->wait;
3949 push @WAIT_FOR_TICK, $signal;
3950 $signal->wait;
3951} 4125}
3952 4126
3953sub wait_for_tick_begin { 4127sub wait_for_tick_begin() {
3954 return Coro::cede if tick_inhibit || $Coro::current == $Coro::main; 4128 return Coro::AnyEvent::poll if tick_inhibit || $Coro::current == $Coro::main;
3955 4129
3956 my $signal = new Coro::Signal; 4130 my $signal = new Coro::Signal;
3957 push @WAIT_FOR_TICK_BEGIN, $signal; 4131 push @WAIT_FOR_TICK_BEGIN, $signal;
3958 $signal->wait; 4132 $signal->wait;
3959} 4133}
3963 Carp::cluck "major BUG: server tick called outside of main coro, skipping it" 4137 Carp::cluck "major BUG: server tick called outside of main coro, skipping it"
3964 unless ++$bug_warning > 10; 4138 unless ++$bug_warning > 10;
3965 return; 4139 return;
3966 } 4140 }
3967 4141
3968 cf::server_tick; # one server iteration 4142 cf::one_tick; # one server iteration
3969 4143
3970 #for(1..3e6){} AE::now_update; $NOW=AE::now; # generate load #d# 4144 #for(1..3e6){} AE::now_update; $NOW=AE::now; # generate load #d#
3971 4145
3972 if ($NOW >= $NEXT_RUNTIME_WRITE) { 4146 if ($NOW >= $NEXT_RUNTIME_WRITE) {
3973 $NEXT_RUNTIME_WRITE = List::Util::max $NEXT_RUNTIME_WRITE + 10, $NOW + 5.; 4147 $NEXT_RUNTIME_WRITE = List::Util::max $NEXT_RUNTIME_WRITE + 10, $NOW + 5.;
3974 Coro::async_pool { 4148 Coro::async_pool {
3975 $Coro::current->{desc} = "runtime saver"; 4149 $Coro::current->{desc} = "runtime saver";
3976 write_runtime_sync 4150 write_runtime_sync
3977 or warn "ERROR: unable to write runtime file: $!"; 4151 or error "ERROR: unable to write runtime file: $!";
3978 }; 4152 };
3979 } 4153 }
3980 4154
3981 if (my $sig = shift @WAIT_FOR_TICK_BEGIN) { 4155 if (my $sig = shift @WAIT_FOR_TICK_BEGIN) {
3982 $sig->send; 4156 $sig->send;
3983 } 4157 }
3984 while (my $sig = shift @WAIT_FOR_TICK) { 4158 $WAIT_FOR_TICK->broadcast;
3985 $sig->send;
3986 }
3987 4159
3988 $LOAD = ($NOW - $TICK_START) / $TICK; 4160 $LOAD = ($NOW - $TICK_START) / $TICK;
3989 $LOADAVG = $LOADAVG * 0.75 + $LOAD * 0.25; 4161 $LOADAVG = $LOADAVG * 0.75 + $LOAD * 0.25;
3990 4162
3991 if (0) { 4163 if (0) {
3992 if ($NEXT_TICK) { 4164 if ($NEXT_TICK) {
3993 my $jitter = $TICK_START - $NEXT_TICK; 4165 my $jitter = $TICK_START - $NEXT_TICK;
3994 $JITTER = $JITTER * 0.75 + $jitter * 0.25; 4166 $JITTER = $JITTER * 0.75 + $jitter * 0.25;
3995 warn "jitter $JITTER\n";#d# 4167 debug "jitter $JITTER\n";#d#
3996 } 4168 }
3997 } 4169 }
3998} 4170}
3999 4171
4000{ 4172{
4001 # configure BDB 4173 # configure BDB
4002 4174
4003 BDB::min_parallel 16; 4175 BDB::min_parallel 16;
4004 BDB::max_poll_reqs $TICK * 0.1; 4176 BDB::max_poll_reqs $TICK * 0.1;
4005 $AnyEvent::BDB::WATCHER->priority (1); 4177 #$AnyEvent::BDB::WATCHER->priority (1);
4006 4178
4007 unless ($DB_ENV) { 4179 unless ($DB_ENV) {
4008 $DB_ENV = BDB::db_env_create; 4180 $DB_ENV = BDB::db_env_create;
4009 $DB_ENV->set_flags (BDB::AUTO_COMMIT | BDB::REGION_INIT); 4181 $DB_ENV->set_flags (BDB::AUTO_COMMIT | BDB::REGION_INIT);
4010 $DB_ENV->set_flags (&BDB::LOG_AUTOREMOVE ) if BDB::VERSION v0, v4.7; 4182 $DB_ENV->set_flags (&BDB::LOG_AUTOREMOVE ) if BDB::VERSION v0, v4.7;
4045 IO::AIO::min_parallel 8; 4217 IO::AIO::min_parallel 8;
4046 IO::AIO::max_poll_time $TICK * 0.1; 4218 IO::AIO::max_poll_time $TICK * 0.1;
4047 undef $AnyEvent::AIO::WATCHER; 4219 undef $AnyEvent::AIO::WATCHER;
4048} 4220}
4049 4221
4050my $_log_backtrace; 4222our $_log_backtrace;
4223our $_log_backtrace_last;
4051 4224
4052sub _log_backtrace { 4225sub _log_backtrace {
4053 my ($msg, @addr) = @_; 4226 my ($msg, @addr) = @_;
4054 4227
4055 $msg =~ s/\n//; 4228 $msg =~ s/\n$//;
4056 4229
4230 if ($_log_backtrace_last eq $msg) {
4231 LOG llevInfo, "[ABT] $msg\n";
4232 LOG llevInfo, "[ABT] [duplicate, suppressed]\n";
4057 # limit the # of concurrent backtraces 4233 # limit the # of concurrent backtraces
4058 if ($_log_backtrace < 2) { 4234 } elsif ($_log_backtrace < 2) {
4235 $_log_backtrace_last = $msg;
4059 ++$_log_backtrace; 4236 ++$_log_backtrace;
4060 my $perl_bt = Carp::longmess $msg; 4237 my $perl_bt = Carp::longmess $msg;
4061 async { 4238 async {
4062 $Coro::current->{desc} = "abt $msg"; 4239 $Coro::current->{desc} = "abt $msg";
4063 4240
4083 LOG llevInfo, "[ABT] $_\n" for @bt; 4260 LOG llevInfo, "[ABT] $_\n" for @bt;
4084 --$_log_backtrace; 4261 --$_log_backtrace;
4085 }; 4262 };
4086 } else { 4263 } else {
4087 LOG llevInfo, "[ABT] $msg\n"; 4264 LOG llevInfo, "[ABT] $msg\n";
4088 LOG llevInfo, "[ABT] [suppressed]\n"; 4265 LOG llevInfo, "[ABT] [overload, suppressed]\n";
4089 } 4266 }
4090} 4267}
4091 4268
4092# load additional modules 4269# load additional modules
4093require "cf/$_.pm" for @EXTRA_MODULES; 4270require "cf/$_.pm" for @EXTRA_MODULES;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines