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.479 by root, Thu Oct 8 05:04:27 2009 UTC vs.
Revision 1.546 by root, Thu May 6 22:57:49 2010 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 Marc Alexander Lehmann / Robin Redeker / the Deliantra team 4# Copyright (©) 2006,2007,2008,2009,2010 Marc Alexander Lehmann / Robin Redeker / the Deliantra team
5# 5#
6# Deliantra is free software: you can redistribute it and/or modify 6# Deliantra is free software: you can redistribute it and/or modify it under
7# it under the terms of the GNU General Public License as published by 7# the terms of the Affero GNU General Public License as published by the
8# the Free Software Foundation, either version 3 of the License, or 8# Free Software Foundation, either version 3 of the License, or (at your
9# (at your option) any later version. 9# option) any later version.
10# 10#
11# This program is distributed in the hope that it will be useful, 11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of 12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14# GNU General Public License for more details. 14# GNU General Public License for more details.
15# 15#
16# You should have received a copy of the GNU General Public License 16# You should have received a copy of the Affero GNU General Public License
17# along with this program. If not, see <http://www.gnu.org/licenses/>. 17# and the GNU General Public License along with this program. If not, see
18# <http://www.gnu.org/licenses/>.
18# 19#
19# 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>
20# 21#
21 22
22package cf; 23package cf;
23 24
24use 5.10.0; 25use common::sense;
25use utf8;
26use strict qw(vars subs);
27 26
28use Symbol; 27use Symbol;
29use List::Util; 28use List::Util;
30use Socket; 29use Socket;
31use EV; 30use EV;
32use Opcode; 31use Opcode;
33use Safe; 32use Safe;
34use Safe::Hole; 33use Safe::Hole;
35use Storable (); 34use Storable ();
35use Carp ();
36 36
37use Guard (); 37use Guard ();
38use Coro (); 38use Coro ();
39use Coro::State; 39use Coro::State;
40use Coro::Handle; 40use Coro::Handle;
51use Coro::Util (); 51use Coro::Util ();
52 52
53use JSON::XS 2.01 (); 53use JSON::XS 2.01 ();
54use BDB (); 54use BDB ();
55use Data::Dumper; 55use Data::Dumper;
56use Digest::MD5;
57use Fcntl; 56use Fcntl;
58use YAML (); 57use YAML::XS ();
59use IO::AIO (); 58use IO::AIO ();
60use Time::HiRes; 59use Time::HiRes;
61use Compress::LZF; 60use Compress::LZF;
62use Digest::MD5 (); 61use Digest::MD5 ();
63 62
76 75
77# strictly for debugging 76# strictly for debugging
78$SIG{QUIT} = sub { Carp::cluck "SIGQUIT" }; 77$SIG{QUIT} = sub { Carp::cluck "SIGQUIT" };
79 78
80sub WF_AUTOCANCEL () { 1 } # automatically cancel this watcher on reload 79sub WF_AUTOCANCEL () { 1 } # automatically cancel this watcher on reload
80
81our @ORIG_INC;
81 82
82our %COMMAND = (); 83our %COMMAND = ();
83our %COMMAND_TIME = (); 84our %COMMAND_TIME = ();
84 85
85our @EXTS = (); # list of extension package names 86our @EXTS = (); # list of extension package names
105our $RANDOMDIR = "$LOCALDIR/random"; 106our $RANDOMDIR = "$LOCALDIR/random";
106our $BDBDIR = "$LOCALDIR/db"; 107our $BDBDIR = "$LOCALDIR/db";
107our $PIDFILE = "$LOCALDIR/pid"; 108our $PIDFILE = "$LOCALDIR/pid";
108our $RUNTIMEFILE = "$LOCALDIR/runtime"; 109our $RUNTIMEFILE = "$LOCALDIR/runtime";
109 110
110our %RESOURCE; 111our %RESOURCE; # unused
112
113our $OUTPUT_RATE_MIN = 3000;
114our $OUTPUT_RATE_MAX = 1000000;
115
116our $MAX_LINKS = 32; # how many chained exits to follow
117our $VERBOSE_IO = 1;
111 118
112our $TICK = MAX_TIME * 1e-6; # this is a CONSTANT(!) 119our $TICK = MAX_TIME * 1e-6; # this is a CONSTANT(!)
113our $NEXT_RUNTIME_WRITE; # when should the runtime file be written 120our $NEXT_RUNTIME_WRITE; # when should the runtime file be written
114our $NEXT_TICK; 121our $NEXT_TICK;
115our $USE_FSYNC = 1; # use fsync to write maps - default on 122our $USE_FSYNC = 1; # use fsync to write maps - default on
117our $BDB_DEADLOCK_WATCHER; 124our $BDB_DEADLOCK_WATCHER;
118our $BDB_CHECKPOINT_WATCHER; 125our $BDB_CHECKPOINT_WATCHER;
119our $BDB_TRICKLE_WATCHER; 126our $BDB_TRICKLE_WATCHER;
120our $DB_ENV; 127our $DB_ENV;
121 128
122our @EXTRA_MODULES = qw(pod mapscript); 129our @EXTRA_MODULES = qw(pod match mapscript incloader);
123 130
124our %CFG; 131our %CFG;
125 132
126our $UPTIME; $UPTIME ||= time; 133our $UPTIME; $UPTIME ||= time;
127our $RUNTIME; 134our $RUNTIME;
161 168
162our $EMERGENCY_POSITION; 169our $EMERGENCY_POSITION;
163 170
164sub cf::map::normalise; 171sub cf::map::normalise;
165 172
173sub in_main() {
174 $Coro::current == $Coro::main
175}
176
166############################################################################# 177#############################################################################
167 178
168%REFLECT = (); 179%REFLECT = ();
169for (@REFLECT) { 180for (@REFLECT) {
170 my $reflect = JSON::XS::decode_json $_; 181 my $reflect = JSON::XS::decode_json $_;
171 $REFLECT{$reflect->{class}} = $reflect; 182 $REFLECT{$reflect->{class}} = $reflect;
172} 183}
173 184
185# this is decidedly evil
186$REFLECT{object}{flags} = { map +($_ => undef), grep $_, map /^FLAG_([A-Z0-9_]+)$/ && lc $1, keys %{"cf::"} };
187
174############################################################################# 188#############################################################################
175 189
176=head2 GLOBAL VARIABLES 190=head2 GLOBAL VARIABLES
177 191
178=over 4 192=over 4
219from wherever your confdir points to. 233from wherever your confdir points to.
220 234
221=item cf::wait_for_tick, cf::wait_for_tick_begin 235=item cf::wait_for_tick, cf::wait_for_tick_begin
222 236
223These are functions that inhibit the current coroutine one tick. cf::wait_for_tick_begin only 237These are functions that inhibit the current coroutine one tick. cf::wait_for_tick_begin only
224returns directly I<after> the tick processing (and consequently, can only wake one process 238returns directly I<after> the tick processing (and consequently, can only wake one thread
225per tick), while cf::wait_for_tick wakes up all waiters after tick processing. 239per tick), while cf::wait_for_tick wakes up all waiters after tick processing.
226 240
241=cut
242
243sub wait_for_tick();
244sub wait_for_tick_begin();
245
227=item @cf::INVOKE_RESULTS 246=item @cf::INVOKE_RESULTS
228 247
229This array contains the results of the last C<invoke ()> call. When 248This array contains the results of the last C<invoke ()> call. When
230C<cf::override> is called C<@cf::INVOKE_RESULTS> is set to the parameters of 249C<cf::override> is called C<@cf::INVOKE_RESULTS> is set to the parameters of
231that call. 250that call.
232 251
233=item %cf::REFLECT 252=item %cf::REFLECT
234 253
235Contains, for each (C++) class name, a hash reference with information 254Contains, for each (C++) class name, a hash reference with information
236about object members (methods, scalars and arrays) and other metadata, 255about object members (methods, scalars, arrays and flags) and other
237which is useful for introspection. 256metadata, which is useful for introspection.
238 257
239=back 258=back
240 259
241=cut 260=cut
261
262sub error(@) { LOG llevError, join "", @_ }
263sub warn (@) { LOG llevWarn , join "", @_ }
264sub info (@) { LOG llevInfo , join "", @_ }
265sub debug(@) { LOG llevDebug, join "", @_ }
266sub trace(@) { LOG llevTrace, join "", @_ }
242 267
243$Coro::State::WARNHOOK = sub { 268$Coro::State::WARNHOOK = sub {
244 my $msg = join "", @_; 269 my $msg = join "", @_;
245 270
246 $msg .= "\n" 271 $msg .= "\n"
247 unless $msg =~ /\n$/; 272 unless $msg =~ /\n$/;
248 273
249 $msg =~ s/([\x00-\x08\x0b-\x1f])/sprintf "\\x%02x", ord $1/ge; 274 $msg =~ s/([\x00-\x08\x0b-\x1f])/sprintf "\\x%02x", ord $1/ge;
250 275
251 LOG llevError, $msg; 276 LOG llevWarn, $msg;
252}; 277};
253 278
254$Coro::State::DIEHOOK = sub { 279$Coro::State::DIEHOOK = sub {
255 return unless $^S eq 0; # "eq", not "==" 280 return unless $^S eq 0; # "eq", not "=="
256 281
257 warn Carp::longmess $_[0]; 282 error Carp::longmess $_[0];
258 283
259 if ($Coro::current == $Coro::main) {#d# 284 if (in_main) {#d#
260 warn "DIEHOOK called in main context, Coro bug?\n";#d# 285 error "DIEHOOK called in main context, Coro bug?\n";#d#
261 return;#d# 286 return;#d#
262 }#d# 287 }#d#
263 288
264 # kill coroutine otherwise 289 # kill coroutine otherwise
265 Coro::terminate 290 Coro::terminate
285)) { 310)) {
286 @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg; 311 @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg;
287} 312}
288 313
289$EV::DIED = sub { 314$EV::DIED = sub {
290 warn "error in event callback: @_"; 315 Carp::cluck "error in event callback: @_";
291}; 316};
292 317
293############################################################################# 318#############################################################################
294 319
295=head2 UTILITY FUNCTIONS 320=head2 UTILITY FUNCTIONS
392} 417}
393 418
394=item cf::periodic $interval, $cb 419=item cf::periodic $interval, $cb
395 420
396Like EV::periodic, but randomly selects a starting point so that the actions 421Like EV::periodic, but randomly selects a starting point so that the actions
397get spread over timer. 422get spread over time.
398 423
399=cut 424=cut
400 425
401sub periodic($$) { 426sub periodic($$) {
402 my ($interval, $cb) = @_; 427 my ($interval, $cb) = @_;
419 444
420=cut 445=cut
421 446
422our @SLOT_QUEUE; 447our @SLOT_QUEUE;
423our $SLOT_QUEUE; 448our $SLOT_QUEUE;
449our $SLOT_DECAY = 0.9;
424 450
425$SLOT_QUEUE->cancel if $SLOT_QUEUE; 451$SLOT_QUEUE->cancel if $SLOT_QUEUE;
426$SLOT_QUEUE = Coro::async { 452$SLOT_QUEUE = Coro::async {
427 $Coro::current->desc ("timeslot manager"); 453 $Coro::current->desc ("timeslot manager");
428 454
429 my $signal = new Coro::Signal; 455 my $signal = new Coro::Signal;
456 my $busy;
430 457
431 while () { 458 while () {
432 next_job: 459 next_job:
460
433 my $avail = cf::till_tick; 461 my $avail = cf::till_tick;
434 if ($avail > 0.01) { 462
435 for (0 .. $#SLOT_QUEUE) { 463 for (0 .. $#SLOT_QUEUE) {
436 if ($SLOT_QUEUE[$_][0] < $avail) { 464 if ($SLOT_QUEUE[$_][0] <= $avail) {
465 $busy = 0;
437 my $job = splice @SLOT_QUEUE, $_, 1, (); 466 my $job = splice @SLOT_QUEUE, $_, 1, ();
438 $job->[2]->send; 467 $job->[2]->send;
439 Coro::cede; 468 Coro::cede;
440 goto next_job; 469 goto next_job;
441 } 470 } else {
471 $SLOT_QUEUE[$_][0] *= $SLOT_DECAY;
442 } 472 }
443 } 473 }
444 474
445 if (@SLOT_QUEUE) { 475 if (@SLOT_QUEUE) {
446 # we do not use wait_for_tick() as it returns immediately when tick is inactive 476 # we do not use wait_for_tick() as it returns immediately when tick is inactive
447 push @cf::WAIT_FOR_TICK, $signal; 477 push @cf::WAIT_FOR_TICK, $signal;
448 $signal->wait; 478 $signal->wait;
449 } else { 479 } else {
480 $busy = 0;
450 Coro::schedule; 481 Coro::schedule;
451 } 482 }
452 } 483 }
453}; 484};
454 485
455sub get_slot($;$$) { 486sub get_slot($;$$) {
456 return if tick_inhibit || $Coro::current == $Coro::main; 487 return if tick_inhibit || $Coro::current == $Coro::main;
457 488
458 my ($time, $pri, $name) = @_; 489 my ($time, $pri, $name) = @_;
459 490
460 $time = $TICK * .6 if $time > $TICK * .6; 491 $time = clamp $time, 0.01, $TICK * .6;
492
461 my $sig = new Coro::Signal; 493 my $sig = new Coro::Signal;
462 494
463 push @SLOT_QUEUE, [$time, $pri, $sig, $name]; 495 push @SLOT_QUEUE, [$time, $pri, $sig, $name];
464 @SLOT_QUEUE = sort { $b->[1] <=> $a->[1] } @SLOT_QUEUE; 496 @SLOT_QUEUE = sort { $b->[1] <=> $a->[1] } @SLOT_QUEUE;
465 $SLOT_QUEUE->ready; 497 $SLOT_QUEUE->ready;
491=cut 523=cut
492 524
493sub sync_job(&) { 525sub sync_job(&) {
494 my ($job) = @_; 526 my ($job) = @_;
495 527
496 if ($Coro::current == $Coro::main) { 528 if (in_main) {
497 my $time = EV::time; 529 my $time = AE::time;
498 530
499 # this is the main coro, too bad, we have to block 531 # this is the main coro, too bad, we have to block
500 # till the operation succeeds, freezing the server :/ 532 # till the operation succeeds, freezing the server :/
501 533
502 LOG llevError, Carp::longmess "sync job";#d# 534 #LOG llevError, Carp::longmess "sync job";#d#
503 535
504 my $freeze_guard = freeze_mainloop; 536 my $freeze_guard = freeze_mainloop;
505 537
506 my $busy = 1; 538 my $busy = 1;
507 my @res; 539 my @res;
508 540
509 (async { 541 (async {
510 $Coro::current->desc ("sync job coro"); 542 $Coro::current->desc ("sync job coro");
511 @res = eval { $job->() }; 543 @res = eval { $job->() };
512 warn $@ if $@; 544 error $@ if $@;
513 undef $busy; 545 undef $busy;
514 })->prio (Coro::PRIO_MAX); 546 })->prio (Coro::PRIO_MAX);
515 547
516 while ($busy) { 548 while ($busy) {
517 if (Coro::nready) { 549 if (Coro::nready) {
519 } else { 551 } else {
520 EV::loop EV::LOOP_ONESHOT; 552 EV::loop EV::LOOP_ONESHOT;
521 } 553 }
522 } 554 }
523 555
524 my $time = EV::time - $time; 556 my $time = AE::time - $time;
525 557
526 $TICK_START += $time; # do not account sync jobs to server load 558 $TICK_START += $time; # do not account sync jobs to server load
527 559
528 wantarray ? @res : $res[0] 560 wantarray ? @res : $res[0]
529 } else { 561 } else {
573 reset_signals; 605 reset_signals;
574 &$cb 606 &$cb
575 }, @args; 607 }, @args;
576 608
577 wantarray ? @res : $res[-1] 609 wantarray ? @res : $res[-1]
610}
611
612sub objinfo {
613 (
614 "counter value" => cf::object::object_count,
615 "objects created" => cf::object::create_count,
616 "objects destroyed" => cf::object::destroy_count,
617 "freelist size" => cf::object::free_count,
618 "allocated objects" => cf::object::objects_size,
619 "active objects" => cf::object::actives_size,
620 )
578} 621}
579 622
580=item $coin = coin_from_name $name 623=item $coin = coin_from_name $name
581 624
582=cut 625=cut
619within each server. 662within each server.
620 663
621=cut 664=cut
622 665
623sub db_table($) { 666sub db_table($) {
667 cf::error "db_get called from main context"
668 if $Coro::current == $Coro::main;
669
624 my ($name) = @_; 670 my ($name) = @_;
625 my $db = BDB::db_create $DB_ENV; 671 my $db = BDB::db_create $DB_ENV;
626 672
627 eval { 673 eval {
628 $db->set_flags (BDB::CHKSUM); 674 $db->set_flags (BDB::CHKSUM);
638} 684}
639 685
640our $DB; 686our $DB;
641 687
642sub db_init { 688sub db_init {
643 cf::sync_job {
644 $DB ||= db_table "db"; 689 $DB ||= db_table "db";
645 };
646} 690}
647 691
648sub db_get($$) { 692sub db_get($$) {
649 my $key = "$_[0]/$_[1]"; 693 my $key = "$_[0]/$_[1]";
650 694
651 cf::sync_job { 695 cf::error "db_get called from main context"
696 if $Coro::current == $Coro::main;
697
652 BDB::db_get $DB, undef, $key, my $data; 698 BDB::db_get $DB, undef, $key, my $data;
653 699
654 $! ? () 700 $! ? ()
655 : $data 701 : $data
656 }
657} 702}
658 703
659sub db_put($$$) { 704sub db_put($$$) {
660 BDB::dbreq_pri 4; 705 BDB::dbreq_pri 4;
661 BDB::db_put $DB, undef, "$_[0]/$_[1]", $_[2], 0, sub { }; 706 BDB::db_put $DB, undef, "$_[0]/$_[1]", $_[2], 0, sub { };
717 762
718 my $t1 = Time::HiRes::time; 763 my $t1 = Time::HiRes::time;
719 my $data = $process->(\@data); 764 my $data = $process->(\@data);
720 my $t2 = Time::HiRes::time; 765 my $t2 = Time::HiRes::time;
721 766
722 warn "cache: '$id' processed in ", $t2 - $t1, "s\n"; 767 info "cache: '$id' processed in ", $t2 - $t1, "s\n";
723 768
724 db_put cache => "$id/data", $data; 769 db_put cache => "$id/data", $data;
725 db_put cache => "$id/md5" , $md5; 770 db_put cache => "$id/md5" , $md5;
726 db_put cache => "$id/meta", $meta; 771 db_put cache => "$id/meta", $meta;
727 772
737 782
738=cut 783=cut
739 784
740sub datalog($@) { 785sub datalog($@) {
741 my ($type, %kv) = @_; 786 my ($type, %kv) = @_;
742 warn "DATALOG ", JSON::XS->new->ascii->encode ({ %kv, type => $type }); 787 info "DATALOG ", JSON::XS->new->ascii->encode ({ %kv, type => $type });
743} 788}
744 789
745=back 790=back
746 791
747=cut 792=cut
942 987
943 } elsif (exists $cb_id{$type}) { 988 } elsif (exists $cb_id{$type}) {
944 _attach_cb $registry, $cb_id{$type}, $prio, shift @arg; 989 _attach_cb $registry, $cb_id{$type}, $prio, shift @arg;
945 990
946 } elsif (ref $type) { 991 } elsif (ref $type) {
947 warn "attaching objects not supported, ignoring.\n"; 992 error "attaching objects not supported, ignoring.\n";
948 993
949 } else { 994 } else {
950 shift @arg; 995 shift @arg;
951 warn "attach argument '$type' not supported, ignoring.\n"; 996 error "attach argument '$type' not supported, ignoring.\n";
952 } 997 }
953 } 998 }
954} 999}
955 1000
956sub _object_attach { 1001sub _object_attach {
966 _attach $registry, $klass, @attach; 1011 _attach $registry, $klass, @attach;
967 } 1012 }
968 1013
969 $obj->{$name} = \%arg; 1014 $obj->{$name} = \%arg;
970 } else { 1015 } else {
971 warn "object uses attachment '$name' which is not available, postponing.\n"; 1016 info "object uses attachment '$name' which is not available, postponing.\n";
972 } 1017 }
973 1018
974 $obj->{_attachment}{$name} = undef; 1019 $obj->{_attachment}{$name} = undef;
975} 1020}
976 1021
1035 1080
1036 for (@$callbacks) { 1081 for (@$callbacks) {
1037 eval { &{$_->[1]} }; 1082 eval { &{$_->[1]} };
1038 1083
1039 if ($@) { 1084 if ($@) {
1040 warn "$@";
1041 warn "... while processing $EVENT[$event][0](@_) event, skipping processing altogether.\n"; 1085 error "$@", "... while processing $EVENT[$event][0](@_) event, skipping processing altogether.\n";
1042 override; 1086 override;
1043 } 1087 }
1044 1088
1045 return 1 if $override; 1089 return 1 if $override;
1046 } 1090 }
1125 for (@$attach) { 1169 for (@$attach) {
1126 my ($klass, @attach) = @$_; 1170 my ($klass, @attach) = @$_;
1127 _attach $registry, $klass, @attach; 1171 _attach $registry, $klass, @attach;
1128 } 1172 }
1129 } else { 1173 } else {
1130 warn "object uses attachment '$name' that is not available, postponing.\n"; 1174 info "object uses attachment '$name' that is not available, postponing.\n";
1131 } 1175 }
1132 } 1176 }
1133} 1177}
1134 1178
1135cf::attachable->attach ( 1179cf::attachable->attach (
1162 my ($filename, $rdata, $objs) = @_; 1206 my ($filename, $rdata, $objs) = @_;
1163 1207
1164 sync_job { 1208 sync_job {
1165 if (length $$rdata) { 1209 if (length $$rdata) {
1166 utf8::decode (my $decname = $filename); 1210 utf8::decode (my $decname = $filename);
1167 warn sprintf "saving %s (%d,%d)\n", 1211 trace sprintf "saving %s (%d,%d)\n",
1168 $decname, length $$rdata, scalar @$objs; 1212 $decname, length $$rdata, scalar @$objs
1213 if $VERBOSE_IO;
1169 1214
1170 if (my $fh = aio_open "$filename~", O_WRONLY | O_CREAT, 0600) { 1215 if (my $fh = aio_open "$filename~", O_WRONLY | O_CREAT, 0600) {
1171 aio_chmod $fh, SAVE_MODE; 1216 aio_chmod $fh, SAVE_MODE;
1172 aio_write $fh, 0, (length $$rdata), $$rdata, 0; 1217 aio_write $fh, 0, (length $$rdata), $$rdata, 0;
1173 if ($cf::USE_FSYNC) { 1218 if ($cf::USE_FSYNC) {
1195 aio_rename "$filename~", $filename; 1240 aio_rename "$filename~", $filename;
1196 1241
1197 $filename =~ s%/[^/]+$%%; 1242 $filename =~ s%/[^/]+$%%;
1198 aio_pathsync $filename if $cf::USE_FSYNC; 1243 aio_pathsync $filename if $cf::USE_FSYNC;
1199 } else { 1244 } else {
1200 warn "unable to save objects: $filename~: $!\n"; 1245 error "unable to save objects: $filename~: $!\n";
1201 } 1246 }
1202 } else { 1247 } else {
1203 aio_unlink $filename; 1248 aio_unlink $filename;
1204 aio_unlink "$filename.pst"; 1249 aio_unlink "$filename.pst";
1205 } 1250 }
1229 my $st = eval { Coro::Storable::thaw $av }; 1274 my $st = eval { Coro::Storable::thaw $av };
1230 $av = $st->{objs}; 1275 $av = $st->{objs};
1231 } 1276 }
1232 1277
1233 utf8::decode (my $decname = $filename); 1278 utf8::decode (my $decname = $filename);
1234 warn sprintf "loading %s (%d,%d)\n", 1279 trace sprintf "loading %s (%d,%d)\n",
1235 $decname, length $data, scalar @{$av || []}; 1280 $decname, length $data, scalar @{$av || []}
1281 if $VERBOSE_IO;
1236 1282
1237 ($data, $av) 1283 ($data, $av)
1238} 1284}
1239 1285
1240=head2 COMMAND CALLBACKS 1286=head2 COMMAND CALLBACKS
1299} 1345}
1300 1346
1301use File::Glob (); 1347use File::Glob ();
1302 1348
1303cf::player->attach ( 1349cf::player->attach (
1304 on_command => sub { 1350 on_unknown_command => sub {
1305 my ($pl, $name, $params) = @_; 1351 my ($pl, $name, $params) = @_;
1306 1352
1307 my $cb = $COMMAND{$name} 1353 my $cb = $COMMAND{$name}
1308 or return; 1354 or return;
1309 1355
1332 1378
1333 $pl->ext_reply ($reply, @reply) 1379 $pl->ext_reply ($reply, @reply)
1334 if $reply; 1380 if $reply;
1335 1381
1336 } else { 1382 } else {
1337 warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n"; 1383 error "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n";
1338 } 1384 }
1339 1385
1340 cf::override; 1386 cf::override;
1341 }, 1387 },
1342); 1388);
1353 1399
1354 $grp 1400 $grp
1355} 1401}
1356 1402
1357sub load_extensions { 1403sub load_extensions {
1404 info "loading extensions...";
1405
1358 cf::sync_job { 1406 cf::sync_job {
1359 my %todo; 1407 my %todo;
1360 1408
1361 for my $path (<$LIBDIR/*.ext>) { 1409 for my $path (<$LIBDIR/*.ext>) {
1362 next unless -r $path; 1410 next unless -r $path;
1380 1428
1381 $ext{meta} = { map { (split /=/, $_, 2)[0, 1] } split /\s+/, $1 } 1429 $ext{meta} = { map { (split /=/, $_, 2)[0, 1] } split /\s+/, $1 }
1382 if $source =~ /\A#!.*?perl.*?#\s*(.*)$/m; 1430 if $source =~ /\A#!.*?perl.*?#\s*(.*)$/m;
1383 1431
1384 $ext{source} = 1432 $ext{source} =
1385 "package $pkg; use 5.10.0; use strict 'vars', 'subs'; use utf8;\n" 1433 "package $pkg; use common::sense;\n"
1386 . "#line 1 \"$path\"\n{\n" 1434 . "#line 1 \"$path\"\n{\n"
1387 . $source 1435 . $source
1388 . "\n};\n1"; 1436 . "\n};\n1";
1389 1437
1390 $todo{$base} = \%ext; 1438 $todo{$base} = \%ext;
1391 } 1439 }
1392 1440
1441 my $pass = 0;
1393 my %done; 1442 my %done;
1394 while (%todo) { 1443 while (%todo) {
1395 my $progress; 1444 my $progress;
1396 1445
1446 ++$pass;
1447
1448 ext:
1397 while (my ($k, $v) = each %todo) { 1449 while (my ($k, $v) = each %todo) {
1398 for (split /,\s*/, $v->{meta}{depends}) { 1450 for (split /,\s*/, $v->{meta}{depends}) {
1399 goto skip 1451 next ext
1400 unless exists $done{$_}; 1452 unless exists $done{$_};
1401 } 1453 }
1402 1454
1403 warn "... loading '$k' into '$v->{pkg}'\n"; 1455 trace "... pass $pass, loading '$k' into '$v->{pkg}'\n";
1404 1456
1405 unless (eval $v->{source}) { 1457 my $active = eval $v->{source};
1458
1459 if (length $@) {
1406 my $msg = $@ ? "$v->{path}: $@\n" 1460 error "$v->{path}: $@\n";
1407 : "$v->{base}: extension inactive.\n";
1408 1461
1409 if (exists $v->{meta}{mandatory}) {
1410 warn $msg;
1411 cf::cleanup "mandatory extension failed to load, exiting."; 1462 cf::cleanup "mandatory extension '$k' failed to load, exiting."
1412 } 1463 if exists $v->{meta}{mandatory};
1413 1464
1414 warn $msg; 1465 warn "$v->{base}: optional extension cannot be loaded, skipping.\n";
1466 delete $todo{$k};
1467 } else {
1468 $done{$k} = delete $todo{$k};
1469 push @EXTS, $v->{pkg};
1470 $progress = 1;
1471
1472 info "$v->{base}: extension inactive.\n"
1473 unless $active;
1415 } 1474 }
1416
1417 $done{$k} = delete $todo{$k};
1418 push @EXTS, $v->{pkg};
1419 $progress = 1;
1420 } 1475 }
1421 1476
1422 skip: 1477 unless ($progress) {
1423 die "cannot load " . (join ", ", keys %todo) . ": unable to resolve dependencies\n" 1478 warn "cannot load " . (join ", ", keys %todo) . ": unable to resolve dependencies\n";
1424 unless $progress; 1479
1480 while (my ($k, $v) = each %todo) {
1481 cf::cleanup "mandatory extension '$k' has unresolved dependencies, exiting."
1482 if exists $v->{meta}{mandatory};
1483 }
1484 }
1425 } 1485 }
1426 }; 1486 };
1427} 1487}
1428 1488
1429############################################################################# 1489#############################################################################
1513 $cf::PLAYER{$login} = $pl 1573 $cf::PLAYER{$login} = $pl
1514 } 1574 }
1515 } 1575 }
1516} 1576}
1517 1577
1578cf::player->attach (
1579 on_load => sub {
1580 my ($pl, $path) = @_;
1581
1582 # restore slots saved in save, below
1583 my $slots = delete $pl->{_slots};
1584
1585 $pl->ob->current_weapon ($slots->[0]);
1586 $pl->combat_ob ($slots->[1]);
1587 $pl->ranged_ob ($slots->[2]);
1588 },
1589);
1590
1518sub save($) { 1591sub save($) {
1519 my ($pl) = @_; 1592 my ($pl) = @_;
1520 1593
1521 return if $pl->{deny_save}; 1594 return if $pl->{deny_save};
1522 1595
1527 1600
1528 aio_mkdir playerdir $pl, 0770; 1601 aio_mkdir playerdir $pl, 0770;
1529 $pl->{last_save} = $cf::RUNTIME; 1602 $pl->{last_save} = $cf::RUNTIME;
1530 1603
1531 cf::get_slot 0.01; 1604 cf::get_slot 0.01;
1605
1606 # save slots, to be restored later
1607 local $pl->{_slots} = [$pl->ob->current_weapon, $pl->combat_ob, $pl->ranged_ob];
1532 1608
1533 $pl->save_pl ($path); 1609 $pl->save_pl ($path);
1534 cf::cede_to_tick; 1610 cf::cede_to_tick;
1535} 1611}
1536 1612
1573 $pl->password ("*"); # this should lock out the player until we have nuked the dir 1649 $pl->password ("*"); # this should lock out the player until we have nuked the dir
1574 1650
1575 $pl->invoke (cf::EVENT_PLAYER_LOGOUT, 1) if $pl->active; 1651 $pl->invoke (cf::EVENT_PLAYER_LOGOUT, 1) if $pl->active;
1576 $pl->deactivate; 1652 $pl->deactivate;
1577 my $killer = cf::arch::get "killer_quit"; $pl->killer ($killer); $killer->destroy; 1653 my $killer = cf::arch::get "killer_quit"; $pl->killer ($killer); $killer->destroy;
1578 $pl->ob->check_score;
1579 $pl->invoke (cf::EVENT_PLAYER_QUIT); 1654 $pl->invoke (cf::EVENT_PLAYER_QUIT);
1580 $pl->ns->destroy if $pl->ns; 1655 $pl->ns->destroy if $pl->ns;
1581 1656
1582 my $path = playerdir $pl; 1657 my $path = playerdir $pl;
1583 my $temp = "$path~$cf::RUNTIME~deleting~"; 1658 my $temp = "$path~$cf::RUNTIME~deleting~";
1638 \@logins 1713 \@logins
1639} 1714}
1640 1715
1641=item $player->maps 1716=item $player->maps
1642 1717
1718=item cf::player::maps $login
1719
1643Returns an arrayref of map paths that are private for this 1720Returns an arrayref of map paths that are private for this
1644player. May block. 1721player. May block.
1645 1722
1646=cut 1723=cut
1647 1724
1709=cut 1786=cut
1710 1787
1711sub find_by_path($) { 1788sub find_by_path($) {
1712 my ($path) = @_; 1789 my ($path) = @_;
1713 1790
1791 $path =~ s/^~[^\/]*//; # skip ~login
1792
1714 my ($match, $specificity); 1793 my ($match, $specificity);
1715 1794
1716 for my $region (list) { 1795 for my $region (list) {
1717 if ($region->{match} && $path =~ $region->{match}) { 1796 if ($region->{match} && $path =~ $region->{match}) {
1718 ($match, $specificity) = ($region, $region->specificity) 1797 ($match, $specificity) = ($region, $region->specificity)
1749 my $lock = cf::lock_acquire "generate_random_map"; # the random map generator is NOT reentrant ATM 1828 my $lock = cf::lock_acquire "generate_random_map"; # the random map generator is NOT reentrant ATM
1750 1829
1751 # mit "rum" bekleckern, nicht 1830 # mit "rum" bekleckern, nicht
1752 $self->_create_random_map ( 1831 $self->_create_random_map (
1753 $rmp->{wallstyle}, $rmp->{wall_name}, $rmp->{floorstyle}, $rmp->{monsterstyle}, 1832 $rmp->{wallstyle}, $rmp->{wall_name}, $rmp->{floorstyle}, $rmp->{monsterstyle},
1754 $rmp->{treasurestyle}, $rmp->{layoutstyle}, $rmp->{doorstyle}, $rmp->{decorstyle}, 1833 $rmp->{treasurestyle}, $rmp->{layoutstyle}, $rmp->{doorstyle}, $rmp->{decorstyle}, $rmp->{miningstyle},
1755 $rmp->{origin_map}, $rmp->{final_map}, $rmp->{exitstyle}, $rmp->{this_map}, 1834 $rmp->{origin_map}, $rmp->{final_map}, $rmp->{exitstyle}, $rmp->{this_map},
1756 $rmp->{exit_on_final_map}, 1835 $rmp->{exit_on_final_map},
1757 $rmp->{xsize}, $rmp->{ysize}, 1836 $rmp->{xsize}, $rmp->{ysize},
1758 $rmp->{expand2x}, $rmp->{layoutoptions1}, $rmp->{layoutoptions2}, $rmp->{layoutoptions3}, 1837 $rmp->{expand2x}, $rmp->{layoutoptions1}, $rmp->{layoutoptions2}, $rmp->{layoutoptions3},
1759 $rmp->{symmetry}, $rmp->{difficulty}, $rmp->{difficulty_given}, $rmp->{difficulty_increase}, 1838 $rmp->{symmetry}, $rmp->{difficulty}, $rmp->{difficulty_given}, $rmp->{difficulty_increase},
1774 1853
1775sub register { 1854sub register {
1776 my (undef, $regex, $prio) = @_; 1855 my (undef, $regex, $prio) = @_;
1777 my $pkg = caller; 1856 my $pkg = caller;
1778 1857
1779 no strict;
1780 push @{"$pkg\::ISA"}, __PACKAGE__; 1858 push @{"$pkg\::ISA"}, __PACKAGE__;
1781 1859
1782 $EXT_MAP{$pkg} = [$prio, qr<$regex>]; 1860 $EXT_MAP{$pkg} = [$prio, qr<$regex>];
1783} 1861}
1784 1862
1785# also paths starting with '/' 1863# also paths starting with '/'
1786$EXT_MAP{"cf::map"} = [0, qr{^(?=/)}]; 1864$EXT_MAP{"cf::map::wrap"} = [0, qr{^(?=/)}];
1787 1865
1788sub thawer_merge { 1866sub thawer_merge {
1789 my ($self, $merge) = @_; 1867 my ($self, $merge) = @_;
1790 1868
1791 # we have to keep some variables in memory intact 1869 # we have to keep some variables in memory intact
1796} 1874}
1797 1875
1798sub normalise { 1876sub normalise {
1799 my ($path, $base) = @_; 1877 my ($path, $base) = @_;
1800 1878
1801 $path = "$path"; # make sure its a string 1879 $path = "$path"; # make sure it's a string
1802 1880
1803 $path =~ s/\.map$//; 1881 $path =~ s/\.map$//;
1804 1882
1805 # map plan: 1883 # map plan:
1806 # 1884 #
1845 $self->init; # pass $1 etc. 1923 $self->init; # pass $1 etc.
1846 return $self; 1924 return $self;
1847 } 1925 }
1848 } 1926 }
1849 1927
1850 Carp::cluck "unable to resolve path '$path' (base '$base')."; 1928 Carp::cluck "unable to resolve path '$path' (base '$base')";
1851 () 1929 ()
1852} 1930}
1853 1931
1854sub init { 1932sub init {
1855 my ($self) = @_; 1933 my ($self) = @_;
1977} 2055}
1978 2056
1979sub find; 2057sub find;
1980sub find { 2058sub find {
1981 my ($path, $origin) = @_; 2059 my ($path, $origin) = @_;
2060
2061 cf::cede_to_tick;
1982 2062
1983 $path = normalise $path, $origin && $origin->path; 2063 $path = normalise $path, $origin && $origin->path;
1984 2064
1985 my $guard1 = cf::lock_acquire "map_data:$path";#d#remove 2065 my $guard1 = cf::lock_acquire "map_data:$path";#d#remove
1986 my $guard2 = cf::lock_acquire "map_find:$path"; 2066 my $guard2 = cf::lock_acquire "map_find:$path";
2005 2085
2006 $cf::MAP{$path} = $map 2086 $cf::MAP{$path} = $map
2007 } 2087 }
2008} 2088}
2009 2089
2010sub pre_load { } 2090sub pre_load { }
2011sub post_load { } 2091#sub post_load { } # XS
2012 2092
2013sub load { 2093sub load {
2014 my ($self) = @_; 2094 my ($self) = @_;
2015 2095
2016 local $self->{deny_reset} = 1; # loading can take a long time 2096 local $self->{deny_reset} = 1; # loading can take a long time
2073 } 2153 }
2074 2154
2075 $self->post_load; 2155 $self->post_load;
2076} 2156}
2077 2157
2158# customize the map for a given player, i.e.
2159# return the _real_ map. used by e.g. per-player
2160# maps to change the path to ~playername/mappath
2078sub customise_for { 2161sub customise_for {
2079 my ($self, $ob) = @_; 2162 my ($self, $ob) = @_;
2080 2163
2081 return find "~" . $ob->name . "/" . $self->{path} 2164 return find "~" . $ob->name . "/" . $self->{path}
2082 if $self->per_player; 2165 if $self->per_player;
2098 or next; 2181 or next;
2099 $neigh = find $neigh, $map 2182 $neigh = find $neigh, $map
2100 or next; 2183 or next;
2101 $neigh->load; 2184 $neigh->load;
2102 2185
2186 # now find the diagonal neighbours
2103 push @neigh, 2187 push @neigh,
2104 [$neigh->tile_path (($_ + 3) % 4), $neigh], 2188 [$neigh->tile_path (($_ + 3) % 4), $neigh],
2105 [$neigh->tile_path (($_ + 1) % 4), $neigh]; 2189 [$neigh->tile_path (($_ + 1) % 4), $neigh];
2106 } 2190 }
2107 2191
2114} 2198}
2115 2199
2116sub find_sync { 2200sub find_sync {
2117 my ($path, $origin) = @_; 2201 my ($path, $origin) = @_;
2118 2202
2119 cf::sync_job { find $path, $origin } 2203 return cf::LOG cf::llevError | cf::logBacktrace, "do_find_sync"
2204 if $Coro::current == $Coro::main;
2205
2206 find $path, $origin
2120} 2207}
2121 2208
2122sub do_load_sync { 2209sub do_load_sync {
2123 my ($map) = @_; 2210 my ($map) = @_;
2124 2211
2125 cf::LOG cf::llevDebug | cf::logBacktrace, "do_load_sync" 2212 return cf::LOG cf::llevError | cf::logBacktrace, "do_load_sync"
2126 if $Coro::current == $Coro::main; 2213 if $Coro::current == $Coro::main;
2127 2214
2128 cf::sync_job { $map->load }; 2215 $map->load;
2129} 2216}
2130 2217
2131our %MAP_PREFETCH; 2218our %MAP_PREFETCH;
2132our $MAP_PREFETCHER = undef; 2219our $MAP_PREFETCHER = undef;
2133 2220
2159 $MAP_PREFETCHER->prio (6); 2246 $MAP_PREFETCHER->prio (6);
2160 2247
2161 () 2248 ()
2162} 2249}
2163 2250
2251# common code, used by both ->save and ->swapout
2164sub save { 2252sub _save {
2165 my ($self) = @_; 2253 my ($self) = @_;
2166
2167 my $lock = cf::lock_acquire "map_data:$self->{path}";
2168 2254
2169 $self->{last_save} = $cf::RUNTIME; 2255 $self->{last_save} = $cf::RUNTIME;
2170 2256
2171 return unless $self->dirty; 2257 return unless $self->dirty;
2172 2258
2192 } else { 2278 } else {
2193 $self->_save_objects ($save, cf::IO_HEADER | cf::IO_OBJECTS | cf::IO_UNIQUES); 2279 $self->_save_objects ($save, cf::IO_HEADER | cf::IO_OBJECTS | cf::IO_UNIQUES);
2194 } 2280 }
2195} 2281}
2196 2282
2283sub save {
2284 my ($self) = @_;
2285
2286 my $lock = cf::lock_acquire "map_data:$self->{path}";
2287
2288 $self->_save;
2289}
2290
2197sub swap_out { 2291sub swap_out {
2198 my ($self) = @_; 2292 my ($self) = @_;
2199 2293
2200 # save first because save cedes
2201 $self->save;
2202
2203 my $lock = cf::lock_acquire "map_data:$self->{path}"; 2294 my $lock = cf::lock_acquire "map_data:$self->{path}";
2204 2295
2205 return if $self->players;
2206 return if $self->in_memory != cf::MAP_ACTIVE; 2296 return if $self->in_memory != cf::MAP_ACTIVE;
2207 return if $self->{deny_save}; 2297 return if $self->{deny_save};
2298 return if $self->players;
2208 2299
2300 # first deactivate the map and "unlink" it from the core
2301 $self->deactivate;
2302 $_->clear_links_to ($self) for values %cf::MAP;
2209 $self->in_memory (cf::MAP_SWAPPED); 2303 $self->in_memory (cf::MAP_SWAPPED);
2304
2305 # then atomically save
2306 $self->_save;
2307
2308 # then free the map
2309 $self->clear;
2310}
2311
2312sub reset_at {
2313 my ($self) = @_;
2314
2315 # TODO: safety, remove and allow resettable per-player maps
2316 return 1e99 if $self->{deny_reset};
2317
2318 my $time = $self->fixed_resettime ? $self->{instantiate_time} : $self->last_access;
2319 my $to = List::Util::min $MAX_RESET, $self->reset_timeout || $DEFAULT_RESET;
2320
2321 $time + $to
2322}
2323
2324sub should_reset {
2325 my ($self) = @_;
2326
2327 $self->reset_at <= $cf::RUNTIME
2328}
2329
2330sub reset {
2331 my ($self) = @_;
2332
2333 my $lock = cf::lock_acquire "map_data:$self->{path}";
2334
2335 return if $self->players;
2336
2337 cf::trace "resetting map ", $self->path, "\n";
2338
2339 $self->in_memory (cf::MAP_SWAPPED);
2340
2341 # need to save uniques path
2342 unless ($self->{deny_save}) {
2343 my $uniq = $self->uniq_path; utf8::encode $uniq;
2344
2345 $self->_save_objects ($uniq, cf::IO_UNIQUES)
2346 if $uniq;
2347 }
2348
2349 delete $cf::MAP{$self->path};
2210 2350
2211 $self->deactivate; 2351 $self->deactivate;
2212 $_->clear_links_to ($self) for values %cf::MAP; 2352 $_->clear_links_to ($self) for values %cf::MAP;
2213 $self->clear; 2353 $self->clear;
2214}
2215
2216sub reset_at {
2217 my ($self) = @_;
2218
2219 # TODO: safety, remove and allow resettable per-player maps
2220 return 1e99 if $self->{deny_reset};
2221
2222 my $time = $self->fixed_resettime ? $self->{instantiate_time} : $self->last_access;
2223 my $to = List::Util::min $MAX_RESET, $self->reset_timeout || $DEFAULT_RESET;
2224
2225 $time + $to
2226}
2227
2228sub should_reset {
2229 my ($self) = @_;
2230
2231 $self->reset_at <= $cf::RUNTIME
2232}
2233
2234sub reset {
2235 my ($self) = @_;
2236
2237 my $lock = cf::lock_acquire "map_data:$self->{path}";
2238
2239 return if $self->players;
2240
2241 warn "resetting map ", $self->path, "\n";
2242
2243 $self->in_memory (cf::MAP_SWAPPED);
2244
2245 # need to save uniques path
2246 unless ($self->{deny_save}) {
2247 my $uniq = $self->uniq_path; utf8::encode $uniq;
2248
2249 $self->_save_objects ($uniq, cf::IO_UNIQUES)
2250 if $uniq;
2251 }
2252
2253 delete $cf::MAP{$self->path};
2254
2255 $self->deactivate;
2256 $_->clear_links_to ($self) for values %cf::MAP;
2257 $self->clear;
2258 2354
2259 $self->unlink_save; 2355 $self->unlink_save;
2260 $self->destroy; 2356 $self->destroy;
2261} 2357}
2262 2358
2270 2366
2271 delete $cf::MAP{$self->path}; 2367 delete $cf::MAP{$self->path};
2272 2368
2273 $self->unlink_save; 2369 $self->unlink_save;
2274 2370
2275 bless $self, "cf::map"; 2371 bless $self, "cf::map::wrap";
2276 delete $self->{deny_reset}; 2372 delete $self->{deny_reset};
2277 $self->{deny_save} = 1; 2373 $self->{deny_save} = 1;
2278 $self->reset_timeout (1); 2374 $self->reset_timeout (1);
2279 $self->path ($self->{path} = "{nuke}/" . ($nuke_counter++)); 2375 $self->path ($self->{path} = "{nuke}/" . ($nuke_counter++));
2280 2376
2337 : normalise $_ 2433 : normalise $_
2338 } @{ aio_readdir $UNIQUEDIR or [] } 2434 } @{ aio_readdir $UNIQUEDIR or [] }
2339 ] 2435 ]
2340} 2436}
2341 2437
2438=item cf::map::static_maps
2439
2440Returns an arrayref if paths of all static maps (all preinstalled F<.map>
2441file in the shared directory excluding F</styles> and F</editor>). May
2442block.
2443
2444=cut
2445
2446sub static_maps() {
2447 my @dirs = "";
2448 my @maps;
2449
2450 while (@dirs) {
2451 my $dir = shift @dirs;
2452
2453 next if $dir eq "/styles" || $dir eq "/editor";
2454
2455 my ($dirs, $files) = Coro::AIO::aio_scandir "$MAPDIR$dir", 2
2456 or return;
2457
2458 for (@$files) {
2459 s/\.map$// or next;
2460 utf8::decode $_;
2461 push @maps, "$dir/$_";
2462 }
2463
2464 push @dirs, map "$dir/$_", @$dirs;
2465 }
2466
2467 \@maps
2468}
2469
2342=back 2470=back
2343 2471
2344=head3 cf::object 2472=head3 cf::object
2345 2473
2346=cut 2474=cut
2478 2606
2479Freezes the player and moves him/her to a special map (C<{link}>). 2607Freezes the player and moves him/her to a special map (C<{link}>).
2480 2608
2481The player should be reasonably safe there for short amounts of time (e.g. 2609The player should be reasonably safe there for short amounts of time (e.g.
2482for loading a map). You I<MUST> call C<leave_link> as soon as possible, 2610for loading a map). You I<MUST> call C<leave_link> as soon as possible,
2483though, as the palyer cannot control the character while it is on the link 2611though, as the player cannot control the character while it is on the link
2484map. 2612map.
2485 2613
2486Will never block. 2614Will never block.
2487 2615
2488=item $player_object->leave_link ($map, $x, $y) 2616=item $player_object->leave_link ($map, $x, $y)
2509sub cf::object::player::enter_link { 2637sub cf::object::player::enter_link {
2510 my ($self) = @_; 2638 my ($self) = @_;
2511 2639
2512 $self->deactivate_recursive; 2640 $self->deactivate_recursive;
2513 2641
2642 ++$self->{_link_recursion};
2643
2514 return if UNIVERSAL::isa $self->map, "ext::map_link"; 2644 return if UNIVERSAL::isa $self->map, "ext::map_link";
2515 2645
2516 $self->{_link_pos} ||= [$self->map->{path}, $self->x, $self->y] 2646 $self->{_link_pos} ||= [$self->map->{path}, $self->x, $self->y]
2517 if $self->map && $self->map->{path} ne "{link}"; 2647 if $self->map && $self->map->{path} ne "{link}";
2518 2648
2519 $self->enter_map ($LINK_MAP || link_map, 10, 10); 2649 $self->enter_map ($LINK_MAP || link_map, 3, 3);
2520} 2650}
2521 2651
2522sub cf::object::player::leave_link { 2652sub cf::object::player::leave_link {
2523 my ($self, $map, $x, $y) = @_; 2653 my ($self, $map, $x, $y) = @_;
2524 2654
2541 ($x, $y) = (-1, -1) 2671 ($x, $y) = (-1, -1)
2542 unless (defined $x) && (defined $y); 2672 unless (defined $x) && (defined $y);
2543 2673
2544 # use -1 or undef as default coordinates, not 0, 0 2674 # use -1 or undef as default coordinates, not 0, 0
2545 ($x, $y) = ($map->enter_x, $map->enter_y) 2675 ($x, $y) = ($map->enter_x, $map->enter_y)
2546 if $x <=0 && $y <= 0; 2676 if $x <= 0 && $y <= 0;
2547 2677
2548 $map->load; 2678 $map->load;
2549 $map->load_neighbours; 2679 $map->load_neighbours;
2550 2680
2551 return unless $self->contr->active; 2681 return unless $self->contr->active;
2552 2682
2553 local $self->{_prev_pos} = $link_pos; # ugly hack for rent.ext 2683 local $self->{_prev_pos} = $link_pos; # ugly hack for rent.ext
2554 $self->enter_map ($map, $x, $y); 2684 if ($self->enter_map ($map, $x, $y)) {
2555 2685 # entering was successful
2686 delete $self->{_link_recursion};
2556 # only activate afterwards, to support waiting in hooks 2687 # only activate afterwards, to support waiting in hooks
2557 $self->activate_recursive; 2688 $self->activate_recursive;
2558} 2689 }
2559 2690
2691}
2692
2560=item $player_object->goto ($path, $x, $y[, $check->($map)[, $done->()]]) 2693=item $player_object->goto ($path, $x, $y[, $check->($map, $x, $y, $player)[, $done->($player)]])
2561 2694
2562Moves the player to the given map-path and coordinates by first freezing 2695Moves the player to the given map-path and coordinates by first freezing
2563her, loading and preparing them map, calling the provided $check callback 2696her, loading and preparing them map, calling the provided $check callback
2564that has to return the map if sucecssful, and then unfreezes the player on 2697that has to return the map if sucecssful, and then unfreezes the player on
2565the new (success) or old (failed) map position. In either case, $done will 2698the new (success) or old (failed) map position. In either case, $done will
2572 2705
2573our $GOTOGEN; 2706our $GOTOGEN;
2574 2707
2575sub cf::object::player::goto { 2708sub cf::object::player::goto {
2576 my ($self, $path, $x, $y, $check, $done) = @_; 2709 my ($self, $path, $x, $y, $check, $done) = @_;
2710
2711 if ($self->{_link_recursion} >= $MAX_LINKS) {
2712 error "FATAL: link recursion exceeded, ", $self->name, " goto $path $x $y, redirecting.";
2713 $self->failmsg ("Something went wrong inside the server - please contact an administrator!");
2714 ($path, $x, $y) = @$EMERGENCY_POSITION;
2715 }
2577 2716
2578 # do generation counting so two concurrent goto's will be executed in-order 2717 # do generation counting so two concurrent goto's will be executed in-order
2579 my $gen = $self->{_goto_generation} = ++$GOTOGEN; 2718 my $gen = $self->{_goto_generation} = ++$GOTOGEN;
2580 2719
2581 $self->enter_link; 2720 $self->enter_link;
2605 my $map = eval { 2744 my $map = eval {
2606 my $map = defined $path ? cf::map::find $path : undef; 2745 my $map = defined $path ? cf::map::find $path : undef;
2607 2746
2608 if ($map) { 2747 if ($map) {
2609 $map = $map->customise_for ($self); 2748 $map = $map->customise_for ($self);
2610 $map = $check->($map) if $check && $map; 2749 $map = $check->($map, $x, $y, $self) if $check && $map;
2611 } else { 2750 } else {
2612 $self->message ("The exit to '$path' is closed.", cf::NDI_UNIQUE | cf::NDI_RED); 2751 $self->message ("The exit to '$path' is closed.", cf::NDI_UNIQUE | cf::NDI_RED);
2613 } 2752 }
2614 2753
2615 $map 2754 $map
2623 if ($gen == $self->{_goto_generation}) { 2762 if ($gen == $self->{_goto_generation}) {
2624 delete $self->{_goto_generation}; 2763 delete $self->{_goto_generation};
2625 $self->leave_link ($map, $x, $y); 2764 $self->leave_link ($map, $x, $y);
2626 } 2765 }
2627 2766
2628 $done->() if $done; 2767 $done->($self) if $done;
2629 })->prio (1); 2768 })->prio (1);
2630} 2769}
2631 2770
2632=item $player_object->enter_exit ($exit_object) 2771=item $player_object->enter_exit ($exit_object)
2633 2772
2726 $self->message ("Something went wrong deep within the deliantra server. " 2865 $self->message ("Something went wrong deep within the deliantra server. "
2727 . "I'll try to bring you back to the map you were before. " 2866 . "I'll try to bring you back to the map you were before. "
2728 . "Please report this to the dungeon master!", 2867 . "Please report this to the dungeon master!",
2729 cf::NDI_UNIQUE | cf::NDI_RED); 2868 cf::NDI_UNIQUE | cf::NDI_RED);
2730 2869
2731 warn "ERROR in enter_exit: $@"; 2870 error "ERROR in enter_exit: $@";
2732 $self->leave_link; 2871 $self->leave_link;
2733 } 2872 }
2734 })->prio (1); 2873 })->prio (1);
2735} 2874}
2736 2875
2748sub cf::client::send_drawinfo { 2887sub cf::client::send_drawinfo {
2749 my ($self, $text, $flags) = @_; 2888 my ($self, $text, $flags) = @_;
2750 2889
2751 utf8::encode $text; 2890 utf8::encode $text;
2752 $self->send_packet (sprintf "drawinfo %d %s", $flags || cf::NDI_BLACK, $text); 2891 $self->send_packet (sprintf "drawinfo %d %s", $flags || cf::NDI_BLACK, $text);
2892}
2893
2894=item $client->send_big_packet ($pkt)
2895
2896Like C<send_packet>, but tries to compress large packets, and fragments
2897them as required.
2898
2899=cut
2900
2901our $MAXFRAGSIZE = cf::MAXSOCKBUF - 64;
2902
2903sub cf::client::send_big_packet {
2904 my ($self, $pkt) = @_;
2905
2906 # try lzf for large packets
2907 $pkt = "lzf " . Compress::LZF::compress $pkt
2908 if 1024 <= length $pkt and $self->{can_lzf};
2909
2910 # split very large packets
2911 if ($MAXFRAGSIZE < length $pkt and $self->{can_lzf}) {
2912 $self->send_packet ("frag $_") for unpack "(a$MAXFRAGSIZE)*", $pkt;
2913 $pkt = "frag";
2914 }
2915
2916 $self->send_packet ($pkt);
2753} 2917}
2754 2918
2755=item $client->send_msg ($channel, $msg, $color, [extra...]) 2919=item $client->send_msg ($channel, $msg, $color, [extra...])
2756 2920
2757Send a drawinfo or msg packet to the client, formatting the msg for the 2921Send a drawinfo or msg packet to the client, formatting the msg for the
2761 2925
2762=cut 2926=cut
2763 2927
2764# non-persistent channels (usually the info channel) 2928# non-persistent channels (usually the info channel)
2765our %CHANNEL = ( 2929our %CHANNEL = (
2930 "c/motd" => {
2931 id => "infobox",
2932 title => "MOTD",
2933 reply => undef,
2934 tooltip => "The message of the day",
2935 },
2766 "c/identify" => { 2936 "c/identify" => {
2767 id => "infobox", 2937 id => "infobox",
2768 title => "Identify", 2938 title => "Identify",
2769 reply => undef, 2939 reply => undef,
2770 tooltip => "Items recently identified", 2940 tooltip => "Items recently identified",
2772 "c/examine" => { 2942 "c/examine" => {
2773 id => "infobox", 2943 id => "infobox",
2774 title => "Examine", 2944 title => "Examine",
2775 reply => undef, 2945 reply => undef,
2776 tooltip => "Signs and other items you examined", 2946 tooltip => "Signs and other items you examined",
2947 },
2948 "c/shopinfo" => {
2949 id => "infobox",
2950 title => "Shop Info",
2951 reply => undef,
2952 tooltip => "What your bargaining skill tells you about the shop",
2777 }, 2953 },
2778 "c/book" => { 2954 "c/book" => {
2779 id => "infobox", 2955 id => "infobox",
2780 title => "Book", 2956 title => "Book",
2781 reply => undef, 2957 reply => undef,
2897 my $pkt = "msg " 3073 my $pkt = "msg "
2898 . $self->{json_coder}->encode ( 3074 . $self->{json_coder}->encode (
2899 [$color & cf::NDI_CLIENT_MASK, $channel, $msg, @extra] 3075 [$color & cf::NDI_CLIENT_MASK, $channel, $msg, @extra]
2900 ); 3076 );
2901 3077
2902 # try lzf for large packets
2903 $pkt = "lzf " . Compress::LZF::compress $pkt
2904 if 1024 <= length $pkt and $self->{can_lzf};
2905
2906 # split very large packets
2907 if (8192 < length $pkt and $self->{can_lzf}) {
2908 $self->send_packet ("frag $_") for unpack "(a8192)*", $pkt;
2909 $pkt = "frag";
2910 }
2911
2912 $self->send_packet ($pkt); 3078 $self->send_big_packet ($pkt);
2913} 3079}
2914 3080
2915=item $client->ext_msg ($type, @msg) 3081=item $client->ext_msg ($type, @msg)
2916 3082
2917Sends an ext event to the client. 3083Sends an ext event to the client.
2920 3086
2921sub cf::client::ext_msg($$@) { 3087sub cf::client::ext_msg($$@) {
2922 my ($self, $type, @msg) = @_; 3088 my ($self, $type, @msg) = @_;
2923 3089
2924 if ($self->extcmd == 2) { 3090 if ($self->extcmd == 2) {
2925 $self->send_packet ("ext " . $self->{json_coder}->encode ([$type, @msg])); 3091 $self->send_big_packet ("ext " . $self->{json_coder}->encode ([$type, @msg]));
2926 } elsif ($self->extcmd == 1) { # TODO: remove 3092 } elsif ($self->extcmd == 1) { # TODO: remove
2927 push @msg, msgtype => "event_$type"; 3093 push @msg, msgtype => "event_$type";
2928 $self->send_packet ("ext " . $self->{json_coder}->encode ({@msg})); 3094 $self->send_big_packet ("ext " . $self->{json_coder}->encode ({@msg}));
2929 } 3095 }
2930} 3096}
2931 3097
2932=item $client->ext_reply ($msgid, @msg) 3098=item $client->ext_reply ($msgid, @msg)
2933 3099
2937 3103
2938sub cf::client::ext_reply($$@) { 3104sub cf::client::ext_reply($$@) {
2939 my ($self, $id, @msg) = @_; 3105 my ($self, $id, @msg) = @_;
2940 3106
2941 if ($self->extcmd == 2) { 3107 if ($self->extcmd == 2) {
2942 $self->send_packet ("ext " . $self->{json_coder}->encode (["reply-$id", @msg])); 3108 $self->send_big_packet ("ext " . $self->{json_coder}->encode (["reply-$id", @msg]));
2943 } elsif ($self->extcmd == 1) { 3109 } elsif ($self->extcmd == 1) {
2944 #TODO: version 1, remove 3110 #TODO: version 1, remove
2945 unshift @msg, msgtype => "reply", msgid => $id; 3111 unshift @msg, msgtype => "reply", msgid => $id;
2946 $self->send_packet ("ext " . $self->{json_coder}->encode ({@msg})); 3112 $self->send_big_packet ("ext " . $self->{json_coder}->encode ({@msg}));
2947 } 3113 }
2948} 3114}
2949 3115
2950=item $success = $client->query ($flags, "text", \&cb) 3116=item $success = $client->query ($flags, "text", \&cb)
2951 3117
3022 3188
3023 $ns->ext_reply ($reply, @reply) 3189 $ns->ext_reply ($reply, @reply)
3024 if $reply; 3190 if $reply;
3025 3191
3026 } else { 3192 } else {
3027 warn "client " . ($ns->pl ? $ns->pl->ob->name : $ns->host) . " sent unparseable exti message: <$buf>\n"; 3193 error "client " . ($ns->pl ? $ns->pl->ob->name : $ns->host) . " sent unparseable exti message: <$buf>\n";
3028 } 3194 }
3029 3195
3030 cf::override; 3196 cf::override;
3031 }, 3197 },
3032); 3198);
3052 3218
3053 $coro 3219 $coro
3054} 3220}
3055 3221
3056cf::client->attach ( 3222cf::client->attach (
3057 on_destroy => sub { 3223 on_client_destroy => sub {
3058 my ($ns) = @_; 3224 my ($ns) = @_;
3059 3225
3060 $_->cancel for values %{ (delete $ns->{_coro}) || {} }; 3226 $_->cancel for values %{ (delete $ns->{_coro}) || {} };
3061 }, 3227 },
3062); 3228);
3078our $safe_hole = new Safe::Hole; 3244our $safe_hole = new Safe::Hole;
3079 3245
3080$SIG{FPE} = 'IGNORE'; 3246$SIG{FPE} = 'IGNORE';
3081 3247
3082$safe->permit_only (Opcode::opset qw( 3248$safe->permit_only (Opcode::opset qw(
3083 :base_core :base_mem :base_orig :base_math 3249 :base_core :base_mem :base_orig :base_math :base_loop
3084 grepstart grepwhile mapstart mapwhile 3250 grepstart grepwhile mapstart mapwhile
3085 sort time 3251 sort time
3086)); 3252));
3087 3253
3088# here we export the classes and methods available to script code 3254# here we export the classes and methods available to script code
3113 decrease split destroy change_exp value msg lore send_msg)], 3279 decrease split destroy change_exp value msg lore send_msg)],
3114 ["cf::object::player" => qw(player)], 3280 ["cf::object::player" => qw(player)],
3115 ["cf::player" => qw(peaceful send_msg)], 3281 ["cf::player" => qw(peaceful send_msg)],
3116 ["cf::map" => qw(trigger)], 3282 ["cf::map" => qw(trigger)],
3117) { 3283) {
3118 no strict 'refs';
3119 my ($pkg, @funs) = @$_; 3284 my ($pkg, @funs) = @$_;
3120 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"}) 3285 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"})
3121 for @funs; 3286 for @funs;
3122} 3287}
3123 3288
3140 $qcode =~ s/"/‟/g; # not allowed in #line filenames 3305 $qcode =~ s/"/‟/g; # not allowed in #line filenames
3141 $qcode =~ s/\n/\\n/g; 3306 $qcode =~ s/\n/\\n/g;
3142 3307
3143 %vars = (_dummy => 0) unless %vars; 3308 %vars = (_dummy => 0) unless %vars;
3144 3309
3310 my @res;
3145 local $_; 3311 local $_;
3146 local @safe::cf::_safe_eval_args = values %vars;
3147 3312
3148 my $eval = 3313 my $eval =
3149 "do {\n" 3314 "do {\n"
3150 . "my (" . (join ",", map "\$$_", keys %vars) . ") = \@cf::_safe_eval_args;\n" 3315 . "my (" . (join ",", map "\$$_", keys %vars) . ") = \@cf::_safe_eval_args;\n"
3151 . "#line 0 \"{$qcode}\"\n" 3316 . "#line 0 \"{$qcode}\"\n"
3152 . $code 3317 . $code
3153 . "\n}" 3318 . "\n}"
3154 ; 3319 ;
3155 3320
3321 if ($CFG{safe_eval}) {
3156 sub_generation_inc; 3322 sub_generation_inc;
3323 local @safe::cf::_safe_eval_args = values %vars;
3157 my @res = wantarray ? $safe->reval ($eval) : scalar $safe->reval ($eval); 3324 @res = wantarray ? $safe->reval ($eval) : scalar $safe->reval ($eval);
3158 sub_generation_inc; 3325 sub_generation_inc;
3326 } else {
3327 local @cf::_safe_eval_args = values %vars;
3328 @res = wantarray ? eval eval : scalar eval $eval;
3329 }
3159 3330
3160 if ($@) { 3331 if ($@) {
3161 warn "$@"; 3332 warn "$@",
3162 warn "while executing safe code '$code'\n"; 3333 "while executing safe code '$code'\n",
3163 warn "with arguments " . (join " ", %vars) . "\n"; 3334 "with arguments " . (join " ", %vars) . "\n";
3164 } 3335 }
3165 3336
3166 wantarray ? @res : $res[0] 3337 wantarray ? @res : $res[0]
3167} 3338}
3168 3339
3182=cut 3353=cut
3183 3354
3184sub register_script_function { 3355sub register_script_function {
3185 my ($fun, $cb) = @_; 3356 my ($fun, $cb) = @_;
3186 3357
3187 no strict 'refs'; 3358 $fun = "safe::$fun" if $CFG{safe_eval};
3188 *{"safe::$fun"} = $safe_hole->wrap ($cb); 3359 *$fun = $safe_hole->wrap ($cb);
3189} 3360}
3190 3361
3191=back 3362=back
3192 3363
3193=cut 3364=cut
3202 # for this (global event?) 3373 # for this (global event?)
3203 %ext::player_env::MUSIC_FACE_CACHE = (); 3374 %ext::player_env::MUSIC_FACE_CACHE = ();
3204 3375
3205 my $enc = JSON::XS->new->utf8->canonical->relaxed; 3376 my $enc = JSON::XS->new->utf8->canonical->relaxed;
3206 3377
3207 warn "loading facedata from $path\n"; 3378 trace "loading facedata from $path\n";
3208 3379
3209 my $facedata;
3210 0 < aio_load $path, $facedata 3380 0 < aio_load $path, my $facedata
3211 or die "$path: $!"; 3381 or die "$path: $!";
3212 3382
3213 $facedata = Coro::Storable::thaw $facedata; 3383 $facedata = Coro::Storable::thaw $facedata;
3214 3384
3215 $facedata->{version} == 2 3385 $facedata->{version} == 2
3216 or cf::cleanup "$path: version mismatch, cannot proceed."; 3386 or cf::cleanup "$path: version mismatch, cannot proceed.";
3217 3387
3218 # patch in the exptable 3388 # patch in the exptable
3389 my $exp_table = $enc->encode ([map cf::level_to_min_exp $_, 1 .. cf::settings->max_level]);
3219 $facedata->{resource}{"res/exp_table"} = { 3390 $facedata->{resource}{"res/exp_table"} = {
3220 type => FT_RSRC, 3391 type => FT_RSRC,
3221 data => $enc->encode ([map cf::level_to_min_exp $_, 1 .. cf::settings->max_level]), 3392 data => $exp_table,
3393 hash => (Digest::MD5::md5 $exp_table),
3222 }; 3394 };
3223 cf::cede_to_tick; 3395 cf::cede_to_tick;
3224 3396
3225 { 3397 {
3226 my $faces = $facedata->{faceinfo}; 3398 my $faces = $facedata->{faceinfo};
3228 while (my ($face, $info) = each %$faces) { 3400 while (my ($face, $info) = each %$faces) {
3229 my $idx = (cf::face::find $face) || cf::face::alloc $face; 3401 my $idx = (cf::face::find $face) || cf::face::alloc $face;
3230 3402
3231 cf::face::set_visibility $idx, $info->{visibility}; 3403 cf::face::set_visibility $idx, $info->{visibility};
3232 cf::face::set_magicmap $idx, $info->{magicmap}; 3404 cf::face::set_magicmap $idx, $info->{magicmap};
3233 cf::face::set_data $idx, 0, $info->{data32}, Digest::MD5::md5 $info->{data32}; 3405 cf::face::set_data $idx, 0, $info->{data32}, $info->{hash32};
3234 cf::face::set_data $idx, 1, $info->{data64}, Digest::MD5::md5 $info->{data64}; 3406 cf::face::set_data $idx, 1, $info->{data64}, $info->{hash64};
3235 3407
3236 cf::cede_to_tick; 3408 cf::cede_to_tick;
3237 } 3409 }
3238 3410
3239 while (my ($face, $info) = each %$faces) { 3411 while (my ($face, $info) = each %$faces) {
3244 3416
3245 if (my $smooth = cf::face::find $info->{smooth}) { 3417 if (my $smooth = cf::face::find $info->{smooth}) {
3246 cf::face::set_smooth $idx, $smooth; 3418 cf::face::set_smooth $idx, $smooth;
3247 cf::face::set_smoothlevel $idx, $info->{smoothlevel}; 3419 cf::face::set_smoothlevel $idx, $info->{smoothlevel};
3248 } else { 3420 } else {
3249 warn "smooth face '$info->{smooth}' not found for face '$face'"; 3421 error "smooth face '$info->{smooth}' not found for face '$face'";
3250 } 3422 }
3251 3423
3252 cf::cede_to_tick; 3424 cf::cede_to_tick;
3253 } 3425 }
3254 } 3426 }
3263 3435
3264 cf::anim::invalidate_all; # d'oh 3436 cf::anim::invalidate_all; # d'oh
3265 } 3437 }
3266 3438
3267 { 3439 {
3268 # TODO: for gcfclient pleasure, we should give resources
3269 # that gcfclient doesn't grok a >10000 face index.
3270 my $res = $facedata->{resource}; 3440 my $res = $facedata->{resource};
3271 3441
3272 while (my ($name, $info) = each %$res) { 3442 while (my ($name, $info) = each %$res) {
3273 if (defined $info->{type}) { 3443 if (defined $info->{type}) {
3274 my $idx = (cf::face::find $name) || cf::face::alloc $name; 3444 my $idx = (cf::face::find $name) || cf::face::alloc $name;
3275 my $data;
3276 3445
3277 if ($info->{type} & 1) { 3446 cf::face::set_data $idx, 0, $info->{data}, $info->{hash};
3278 # prepend meta info
3279
3280 my $meta = $enc->encode ({
3281 name => $name,
3282 %{ $info->{meta} || {} },
3283 });
3284
3285 $data = pack "(w/a*)*", $meta, $info->{data};
3286 } else {
3287 $data = $info->{data};
3288 }
3289
3290 cf::face::set_data $idx, 0, $data, Digest::MD5::md5 $data;
3291 cf::face::set_type $idx, $info->{type}; 3447 cf::face::set_type $idx, $info->{type};
3292 } else { 3448 } else {
3293 $RESOURCE{$name} = $info; 3449 $RESOURCE{$name} = $info; # unused
3294 } 3450 }
3295 3451
3296 cf::cede_to_tick; 3452 cf::cede_to_tick;
3297 } 3453 }
3298 } 3454 }
3299 3455
3300 cf::global->invoke (EVENT_GLOBAL_RESOURCE_UPDATE); 3456 cf::global->invoke (EVENT_GLOBAL_RESOURCE_UPDATE);
3301 3457
3302 1 3458 1
3303} 3459}
3304
3305cf::global->attach (on_resource_update => sub {
3306 if (my $soundconf = $RESOURCE{"res/sound.conf"}) {
3307 $soundconf = JSON::XS->new->utf8->relaxed->decode ($soundconf->{data});
3308
3309 for (0 .. SOUND_CAST_SPELL_0 - 1) {
3310 my $sound = $soundconf->{compat}[$_]
3311 or next;
3312
3313 my $face = cf::face::find "sound/$sound->[1]";
3314 cf::sound::set $sound->[0] => $face;
3315 cf::sound::old_sound_index $_, $face; # gcfclient-compat
3316 }
3317
3318 while (my ($k, $v) = each %{$soundconf->{event}}) {
3319 my $face = cf::face::find "sound/$v";
3320 cf::sound::set $k => $face;
3321 }
3322 }
3323});
3324 3460
3325register_exticmd fx_want => sub { 3461register_exticmd fx_want => sub {
3326 my ($ns, $want) = @_; 3462 my ($ns, $want) = @_;
3327 3463
3328 while (my ($k, $v) = each %$want) { 3464 while (my ($k, $v) = each %$want) {
3367sub reload_treasures { 3503sub reload_treasures {
3368 load_resource_file "$DATADIR/treasures" 3504 load_resource_file "$DATADIR/treasures"
3369 or die "unable to load treasurelists\n"; 3505 or die "unable to load treasurelists\n";
3370} 3506}
3371 3507
3508sub reload_sound {
3509 trace "loading sound config from $DATADIR/sound\n";
3510
3511 0 < Coro::AIO::aio_load "$DATADIR/sound", my $data
3512 or die "$DATADIR/sound $!";
3513
3514 my $soundconf = JSON::XS->new->utf8->relaxed->decode ($data);
3515
3516 for (0 .. SOUND_CAST_SPELL_0 - 1) {
3517 my $sound = $soundconf->{compat}[$_]
3518 or next;
3519
3520 my $face = cf::face::find "sound/$sound->[1]";
3521 cf::sound::set $sound->[0] => $face;
3522 cf::sound::old_sound_index $_, $face; # gcfclient-compat
3523 }
3524
3525 while (my ($k, $v) = each %{$soundconf->{event}}) {
3526 my $face = cf::face::find "sound/$v";
3527 cf::sound::set $k => $face;
3528 }
3529}
3530
3372sub reload_resources { 3531sub reload_resources {
3373 warn "reloading resource files...\n"; 3532 trace "reloading resource files...\n";
3374 3533
3534 reload_exp_table;
3535 reload_materials;
3375 reload_facedata; 3536 reload_facedata;
3537 reload_sound;
3376 reload_archetypes; 3538 reload_archetypes;
3377 reload_regions; 3539 reload_regions;
3378 reload_treasures; 3540 reload_treasures;
3379 3541
3380 warn "finished reloading resource files\n"; 3542 trace "finished reloading resource files\n";
3381} 3543}
3382 3544
3383sub reload_config { 3545sub reload_config {
3384 open my $fh, "<:utf8", "$CONFDIR/config" 3546 trace "reloading config file...\n";
3385 or return;
3386 3547
3387 local $/; 3548 0 < aio_load "$CONFDIR/config", my $config
3549 or die "$CONFDIR/config: $!";
3550
3551 utf8::decode $config;
3552
3553 cf::get_slot 0.1, 10, "reload_config"; # yaml might be slow...
3388 *CFG = YAML::Load <$fh>; 3554 *CFG = YAML::XS::Load $config;
3389 3555
3390 $EMERGENCY_POSITION = $CFG{emergency_position} || ["/world/world_105_115", 5, 37]; 3556 $EMERGENCY_POSITION = $CFG{emergency_position} || ["/world/world_104_115", 49, 38];
3391 3557
3392 $cf::map::MAX_RESET = $CFG{map_max_reset} if exists $CFG{map_max_reset}; 3558 $cf::map::MAX_RESET = $CFG{map_max_reset} if exists $CFG{map_max_reset};
3393 $cf::map::DEFAULT_RESET = $CFG{map_default_reset} if exists $CFG{map_default_reset}; 3559 $cf::map::DEFAULT_RESET = $CFG{map_default_reset} if exists $CFG{map_default_reset};
3394 3560
3395 if (exists $CFG{mlockall}) { 3561 if (exists $CFG{mlockall}) {
3419 seek $fh, 0, 0; 3585 seek $fh, 0, 0;
3420 print $fh $$; 3586 print $fh $$;
3421} 3587}
3422 3588
3423sub main_loop { 3589sub main_loop {
3424 warn "EV::loop starting\n"; 3590 trace "EV::loop starting\n";
3425 if (1) { 3591 if (1) {
3426 EV::loop; 3592 EV::loop;
3427 } 3593 }
3428 warn "EV::loop returned\n"; 3594 trace "EV::loop returned\n";
3429 goto &main_loop unless $REALLY_UNLOOP; 3595 goto &main_loop unless $REALLY_UNLOOP;
3430} 3596}
3431 3597
3432sub main { 3598sub main {
3433 cf::init_globals; # initialise logging 3599 cf::init_globals; # initialise logging
3434 3600
3435 LOG llevInfo, "Welcome to Deliantra, v" . VERSION; 3601 LOG llevInfo, "Welcome to Deliantra, v" . VERSION;
3436 LOG llevInfo, "Copyright (C) 2005-2008 Marc Alexander Lehmann / Robin Redeker / the Deliantra team."; 3602 LOG llevInfo, "Copyright (C) 2005-2010 Marc Alexander Lehmann / Robin Redeker / the Deliantra team.";
3437 LOG llevInfo, "Copyright (C) 1994 Mark Wedel."; 3603 LOG llevInfo, "Copyright (C) 1994 Mark Wedel.";
3438 LOG llevInfo, "Copyright (C) 1992 Frank Tore Johansen."; 3604 LOG llevInfo, "Copyright (C) 1992 Frank Tore Johansen.";
3439
3440 cf::init_experience;
3441 cf::init_anim;
3442 cf::init_attackmess;
3443 cf::init_dynamic;
3444 3605
3445 $Coro::current->prio (Coro::PRIO_MAX); # give the main loop max. priority 3606 $Coro::current->prio (Coro::PRIO_MAX); # give the main loop max. priority
3446 3607
3447 # we must not ever block the main coroutine 3608 # we must not ever block the main coroutine
3448 local $Coro::idle = sub { 3609 local $Coro::idle = sub {
3454 }; 3615 };
3455 3616
3456 evthread_start IO::AIO::poll_fileno; 3617 evthread_start IO::AIO::poll_fileno;
3457 3618
3458 cf::sync_job { 3619 cf::sync_job {
3620 cf::incloader::init ();
3621
3622 cf::init_anim;
3623 cf::init_attackmess;
3624 cf::init_dynamic;
3625
3626 cf::load_settings;
3627
3459 reload_resources; 3628 reload_resources;
3460 reload_config; 3629 reload_config;
3461 db_init; 3630 db_init;
3462 3631
3463 cf::load_settings;
3464 cf::load_materials;
3465 cf::init_uuid; 3632 cf::init_uuid;
3466 cf::init_signals; 3633 cf::init_signals;
3467 cf::init_commands;
3468 cf::init_skills; 3634 cf::init_skills;
3469 3635
3470 cf::init_beforeplay; 3636 cf::init_beforeplay;
3471 3637
3472 atomic; 3638 atomic;
3480 POSIX::close delete $ENV{LOCKUTIL_LOCK_FD} if exists $ENV{LOCKUTIL_LOCK_FD}; 3646 POSIX::close delete $ENV{LOCKUTIL_LOCK_FD} if exists $ENV{LOCKUTIL_LOCK_FD};
3481 3647
3482 (pop @POST_INIT)->(0) while @POST_INIT; 3648 (pop @POST_INIT)->(0) while @POST_INIT;
3483 }; 3649 };
3484 3650
3651 cf::object::thawer::errors_are_fatal 0;
3652 info "parse errors in files are no longer fatal from this point on.\n";
3653
3654 my $free_main; $free_main = EV::idle sub {
3655 undef $free_main;
3656 undef &main; # free gobs of memory :)
3657 };
3658
3485 main_loop; 3659 goto &main_loop;
3486} 3660}
3487 3661
3488############################################################################# 3662#############################################################################
3489# initialisation and cleanup 3663# initialisation and cleanup
3490 3664
3491# install some emergency cleanup handlers 3665# install some emergency cleanup handlers
3492BEGIN { 3666BEGIN {
3493 our %SIGWATCHER = (); 3667 our %SIGWATCHER = ();
3494 for my $signal (qw(INT HUP TERM)) { 3668 for my $signal (qw(INT HUP TERM)) {
3495 $SIGWATCHER{$signal} = EV::signal $signal, sub { 3669 $SIGWATCHER{$signal} = AE::signal $signal, sub {
3496 cf::cleanup "SIG$signal"; 3670 cf::cleanup "SIG$signal";
3497 }; 3671 };
3498 } 3672 }
3499} 3673}
3500 3674
3501sub write_runtime_sync { 3675sub write_runtime_sync {
3676 my $t0 = AE::time;
3677
3502 # first touch the runtime file to show we are still running: 3678 # first touch the runtime file to show we are still running:
3503 # the fsync below can take a very very long time. 3679 # the fsync below can take a very very long time.
3504 3680
3505 IO::AIO::aio_utime $RUNTIMEFILE, undef, undef; 3681 IO::AIO::aio_utime $RUNTIMEFILE, undef, undef;
3506 3682
3507 my $guard = cf::lock_acquire "write_runtime"; 3683 my $guard = cf::lock_acquire "write_runtime";
3508 3684
3509 my $fh = aio_open "$RUNTIMEFILE~", O_WRONLY | O_CREAT, 0644 3685 my $fh = aio_open "$RUNTIMEFILE~", O_WRONLY | O_CREAT | O_TRUNC, 0644
3510 or return; 3686 or return;
3511 3687
3512 my $value = $cf::RUNTIME + 90 + 10; 3688 my $value = $cf::RUNTIME + 90 + 10;
3513 # 10 is the runtime save interval, for a monotonic clock 3689 # 10 is the runtime save interval, for a monotonic clock
3514 # 60 allows for the watchdog to kill the server. 3690 # 60 allows for the watchdog to kill the server.
3527 or return; 3703 or return;
3528 3704
3529 aio_rename "$RUNTIMEFILE~", $RUNTIMEFILE 3705 aio_rename "$RUNTIMEFILE~", $RUNTIMEFILE
3530 and return; 3706 and return;
3531 3707
3532 warn "runtime file written.\n"; 3708 trace sprintf "runtime file written (%gs).\n", AE::time - $t0;
3533 3709
3534 1 3710 1
3535} 3711}
3536 3712
3537our $uuid_lock; 3713our $uuid_lock;
3549 or return; 3725 or return;
3550 3726
3551 my $value = uuid_seq uuid_cur; 3727 my $value = uuid_seq uuid_cur;
3552 3728
3553 unless ($value) { 3729 unless ($value) {
3554 warn "cowardly refusing to write zero uuid value!\n"; 3730 info "cowardly refusing to write zero uuid value!\n";
3555 return; 3731 return;
3556 } 3732 }
3557 3733
3558 my $value = uuid_str $value + $uuid_skip; 3734 my $value = uuid_str $value + $uuid_skip;
3559 $uuid_skip = 0; 3735 $uuid_skip = 0;
3569 or return; 3745 or return;
3570 3746
3571 aio_rename "$uuid~", $uuid 3747 aio_rename "$uuid~", $uuid
3572 and return; 3748 and return;
3573 3749
3574 warn "uuid file written ($value).\n"; 3750 trace "uuid file written ($value).\n";
3575 3751
3576 1 3752 1
3577 3753
3578} 3754}
3579 3755
3585} 3761}
3586 3762
3587sub emergency_save() { 3763sub emergency_save() {
3588 my $freeze_guard = cf::freeze_mainloop; 3764 my $freeze_guard = cf::freeze_mainloop;
3589 3765
3590 warn "emergency_perl_save: enter\n"; 3766 info "emergency_perl_save: enter\n";
3767
3768 # this is a trade-off: we want to be very quick here, so
3769 # save all maps without fsync, and later call a global sync
3770 # (which in turn might be very very slow)
3771 local $USE_FSYNC = 0;
3591 3772
3592 cf::sync_job { 3773 cf::sync_job {
3593 # this is a trade-off: we want to be very quick here, so 3774 cf::write_runtime_sync; # external watchdog should not bark
3594 # save all maps without fsync, and later call a global sync
3595 # (which in turn might be very very slow)
3596 local $USE_FSYNC = 0;
3597 3775
3598 # use a peculiar iteration method to avoid tripping on perl 3776 # use a peculiar iteration method to avoid tripping on perl
3599 # refcount bugs in for. also avoids problems with players 3777 # refcount bugs in for. also avoids problems with players
3600 # and maps saved/destroyed asynchronously. 3778 # and maps saved/destroyed asynchronously.
3601 warn "emergency_perl_save: begin player save\n"; 3779 info "emergency_perl_save: begin player save\n";
3602 for my $login (keys %cf::PLAYER) { 3780 for my $login (keys %cf::PLAYER) {
3603 my $pl = $cf::PLAYER{$login} or next; 3781 my $pl = $cf::PLAYER{$login} or next;
3604 $pl->valid or next; 3782 $pl->valid or next;
3605 delete $pl->{unclean_save}; # not strictly necessary, but cannot hurt 3783 delete $pl->{unclean_save}; # not strictly necessary, but cannot hurt
3606 $pl->save; 3784 $pl->save;
3607 } 3785 }
3608 warn "emergency_perl_save: end player save\n"; 3786 info "emergency_perl_save: end player save\n";
3609 3787
3788 cf::write_runtime_sync; # external watchdog should not bark
3789
3610 warn "emergency_perl_save: begin map save\n"; 3790 info "emergency_perl_save: begin map save\n";
3611 for my $path (keys %cf::MAP) { 3791 for my $path (keys %cf::MAP) {
3612 my $map = $cf::MAP{$path} or next; 3792 my $map = $cf::MAP{$path} or next;
3613 $map->valid or next; 3793 $map->valid or next;
3614 $map->save; 3794 $map->save;
3615 } 3795 }
3616 warn "emergency_perl_save: end map save\n"; 3796 info "emergency_perl_save: end map save\n";
3617 3797
3798 cf::write_runtime_sync; # external watchdog should not bark
3799
3618 warn "emergency_perl_save: begin database checkpoint\n"; 3800 info "emergency_perl_save: begin database checkpoint\n";
3619 BDB::db_env_txn_checkpoint $DB_ENV; 3801 BDB::db_env_txn_checkpoint $DB_ENV;
3620 warn "emergency_perl_save: end database checkpoint\n"; 3802 info "emergency_perl_save: end database checkpoint\n";
3621 3803
3622 warn "emergency_perl_save: begin write uuid\n"; 3804 info "emergency_perl_save: begin write uuid\n";
3623 write_uuid_sync 1; 3805 write_uuid_sync 1;
3624 warn "emergency_perl_save: end write uuid\n"; 3806 info "emergency_perl_save: end write uuid\n";
3807
3808 cf::write_runtime_sync; # external watchdog should not bark
3809
3810 trace "emergency_perl_save: syncing database to disk";
3811 BDB::db_env_txn_checkpoint $DB_ENV;
3812
3813 info "emergency_perl_save: starting sync\n";
3814 IO::AIO::aio_sync sub {
3815 info "emergency_perl_save: finished sync\n";
3816 };
3817
3818 cf::write_runtime_sync; # external watchdog should not bark
3819
3820 trace "emergency_perl_save: flushing outstanding aio requests";
3821 while (IO::AIO::nreqs || BDB::nreqs) {
3822 Coro::EV::timer_once 0.01; # let the sync_job do it's thing
3823 }
3824
3825 cf::write_runtime_sync; # external watchdog should not bark
3625 }; 3826 };
3626 3827
3627 warn "emergency_perl_save: starting sync()\n";
3628 IO::AIO::aio_sync sub {
3629 warn "emergency_perl_save: finished sync()\n";
3630 };
3631
3632 warn "emergency_perl_save: leave\n"; 3828 info "emergency_perl_save: leave\n";
3633} 3829}
3634 3830
3635sub post_cleanup { 3831sub post_cleanup {
3636 my ($make_core) = @_; 3832 my ($make_core) = @_;
3637 3833
3834 IO::AIO::flush;
3835
3638 warn Carp::longmess "post_cleanup backtrace" 3836 error Carp::longmess "post_cleanup backtrace"
3639 if $make_core; 3837 if $make_core;
3640 3838
3641 my $fh = pidfile; 3839 my $fh = pidfile;
3642 unlink $PIDFILE if <$fh> == $$; 3840 unlink $PIDFILE if <$fh> == $$;
3643} 3841}
3663 my $leaf_symtab = *{$stem_symtab->{$leaf}}{HASH}; 3861 my $leaf_symtab = *{$stem_symtab->{$leaf}}{HASH};
3664 for my $name (keys %$leaf_symtab) { 3862 for my $name (keys %$leaf_symtab) {
3665 _gv_clear *{"$pkg$name"}; 3863 _gv_clear *{"$pkg$name"};
3666# use PApp::Util; PApp::Util::sv_dump *{"$pkg$name"}; 3864# use PApp::Util; PApp::Util::sv_dump *{"$pkg$name"};
3667 } 3865 }
3668 warn "cleared package $pkg\n";#d#
3669} 3866}
3670 3867
3671sub do_reload_perl() { 3868sub do_reload_perl() {
3672 # can/must only be called in main 3869 # can/must only be called in main
3673 if ($Coro::current != $Coro::main) { 3870 unless (in_main) {
3674 warn "can only reload from main coroutine"; 3871 error "can only reload from main coroutine";
3675 return; 3872 return;
3676 } 3873 }
3677 3874
3678 return if $RELOAD++; 3875 return if $RELOAD++;
3679 3876
3680 my $t1 = EV::time; 3877 my $t1 = AE::time;
3681 3878
3682 while ($RELOAD) { 3879 while ($RELOAD) {
3880 cf::get_slot 0.1, -1, "reload_perl";
3683 warn "reloading..."; 3881 info "reloading...";
3684 3882
3685 warn "entering sync_job"; 3883 trace "entering sync_job";
3686 3884
3687 cf::sync_job { 3885 cf::sync_job {
3688 cf::write_runtime_sync; # external watchdog should not bark
3689 cf::emergency_save; 3886 #cf::emergency_save;
3690 cf::write_runtime_sync; # external watchdog should not bark
3691 3887
3692 warn "syncing database to disk";
3693 BDB::db_env_txn_checkpoint $DB_ENV;
3694
3695 # if anything goes wrong in here, we should simply crash as we already saved
3696
3697 warn "flushing outstanding aio requests";
3698 while (IO::AIO::nreqs || BDB::nreqs) {
3699 Coro::EV::timer_once 0.01; # let the sync_job do it's thing
3700 }
3701
3702 warn "cancelling all extension coros"; 3888 trace "cancelling all extension coros";
3703 $_->cancel for values %EXT_CORO; 3889 $_->cancel for values %EXT_CORO;
3704 %EXT_CORO = (); 3890 %EXT_CORO = ();
3705 3891
3706 warn "removing commands"; 3892 trace "removing commands";
3707 %COMMAND = (); 3893 %COMMAND = ();
3708 3894
3709 warn "removing ext/exti commands"; 3895 trace "removing ext/exti commands";
3710 %EXTCMD = (); 3896 %EXTCMD = ();
3711 %EXTICMD = (); 3897 %EXTICMD = ();
3712 3898
3713 warn "unloading/nuking all extensions"; 3899 trace "unloading/nuking all extensions";
3714 for my $pkg (@EXTS) { 3900 for my $pkg (@EXTS) {
3715 warn "... unloading $pkg"; 3901 trace "... unloading $pkg";
3716 3902
3717 if (my $cb = $pkg->can ("unload")) { 3903 if (my $cb = $pkg->can ("unload")) {
3718 eval { 3904 eval {
3719 $cb->($pkg); 3905 $cb->($pkg);
3720 1 3906 1
3721 } or warn "$pkg unloaded, but with errors: $@"; 3907 } or error "$pkg unloaded, but with errors: $@";
3722 } 3908 }
3723 3909
3724 warn "... clearing $pkg"; 3910 trace "... clearing $pkg";
3725 clear_package $pkg; 3911 clear_package $pkg;
3726 } 3912 }
3727 3913
3728 warn "unloading all perl modules loaded from $LIBDIR"; 3914 trace "unloading all perl modules loaded from $LIBDIR";
3729 while (my ($k, $v) = each %INC) { 3915 while (my ($k, $v) = each %INC) {
3730 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/; 3916 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
3731 3917
3732 warn "... unloading $k"; 3918 trace "... unloading $k";
3733 delete $INC{$k}; 3919 delete $INC{$k};
3734 3920
3735 $k =~ s/\.pm$//; 3921 $k =~ s/\.pm$//;
3736 $k =~ s/\//::/g; 3922 $k =~ s/\//::/g;
3737 3923
3740 } 3926 }
3741 3927
3742 clear_package $k; 3928 clear_package $k;
3743 } 3929 }
3744 3930
3745 warn "getting rid of safe::, as good as possible"; 3931 trace "getting rid of safe::, as good as possible";
3746 clear_package "safe::$_" 3932 clear_package "safe::$_"
3747 for qw(cf::attachable cf::object cf::object::player cf::client cf::player cf::map cf::party cf::region); 3933 for qw(cf::attachable cf::object cf::object::player cf::client cf::player cf::map cf::party cf::region);
3748 3934
3749 warn "unloading cf.pm \"a bit\""; 3935 trace "unloading cf.pm \"a bit\"";
3750 delete $INC{"cf.pm"}; 3936 delete $INC{"cf.pm"};
3751 delete $INC{"cf/$_.pm"} for @EXTRA_MODULES; 3937 delete $INC{"cf/$_.pm"} for @EXTRA_MODULES;
3752 3938
3753 # don't, removes xs symbols, too, 3939 # don't, removes xs symbols, too,
3754 # and global variables created in xs 3940 # and global variables created in xs
3755 #clear_package __PACKAGE__; 3941 #clear_package __PACKAGE__;
3756 3942
3757 warn "unload completed, starting to reload now"; 3943 info "unload completed, starting to reload now";
3758 3944
3759 warn "reloading cf.pm"; 3945 trace "reloading cf.pm";
3760 require cf; 3946 require cf;
3761 cf::_connect_to_perl; # nominally unnecessary, but cannot hurt 3947 cf::_connect_to_perl_1;
3762 3948
3763 warn "loading config and database again"; 3949 trace "loading config and database again";
3764 cf::reload_config; 3950 cf::reload_config;
3765 3951
3766 warn "loading extensions"; 3952 trace "loading extensions";
3767 cf::load_extensions; 3953 cf::load_extensions;
3768 3954
3769 if ($REATTACH_ON_RELOAD) { 3955 if ($REATTACH_ON_RELOAD) {
3770 warn "reattaching attachments to objects/players"; 3956 trace "reattaching attachments to objects/players";
3771 _global_reattach; # objects, sockets 3957 _global_reattach; # objects, sockets
3772 warn "reattaching attachments to maps"; 3958 trace "reattaching attachments to maps";
3773 reattach $_ for values %MAP; 3959 reattach $_ for values %MAP;
3774 warn "reattaching attachments to players"; 3960 trace "reattaching attachments to players";
3775 reattach $_ for values %PLAYER; 3961 reattach $_ for values %PLAYER;
3776 } 3962 }
3777 3963
3778 warn "running post_init jobs"; 3964 trace "running post_init jobs";
3779 (pop @POST_INIT)->(1) while @POST_INIT; 3965 (pop @POST_INIT)->(1) while @POST_INIT;
3780 3966
3781 warn "leaving sync_job"; 3967 trace "leaving sync_job";
3782 3968
3783 1 3969 1
3784 } or do { 3970 } or do {
3785 warn $@; 3971 error $@;
3786 cf::cleanup "error while reloading, exiting."; 3972 cf::cleanup "error while reloading, exiting.";
3787 }; 3973 };
3788 3974
3789 warn "reloaded"; 3975 info "reloaded";
3790 --$RELOAD; 3976 --$RELOAD;
3791 } 3977 }
3792 3978
3793 $t1 = EV::time - $t1; 3979 $t1 = AE::time - $t1;
3794 warn "reload completed in ${t1}s\n"; 3980 info "reload completed in ${t1}s\n";
3795}; 3981};
3796 3982
3797our $RELOAD_WATCHER; # used only during reload 3983our $RELOAD_WATCHER; # used only during reload
3798 3984
3799sub reload_perl() { 3985sub reload_perl() {
3801 # coro crashes during coro_state_free->destroy here. 3987 # coro crashes during coro_state_free->destroy here.
3802 3988
3803 $RELOAD_WATCHER ||= cf::async { 3989 $RELOAD_WATCHER ||= cf::async {
3804 Coro::AIO::aio_wait cache_extensions; 3990 Coro::AIO::aio_wait cache_extensions;
3805 3991
3806 $RELOAD_WATCHER = EV::timer $TICK * 1.5, 0, sub { 3992 $RELOAD_WATCHER = AE::timer $TICK * 1.5, 0, sub {
3807 do_reload_perl; 3993 do_reload_perl;
3808 undef $RELOAD_WATCHER; 3994 undef $RELOAD_WATCHER;
3809 }; 3995 };
3810 }; 3996 };
3811} 3997}
3820 reload_perl; 4006 reload_perl;
3821 }; 4007 };
3822 } 4008 }
3823}; 4009};
3824 4010
3825unshift @INC, $LIBDIR; 4011#############################################################################
3826 4012
3827my $bug_warning = 0; 4013my $bug_warning = 0;
3828 4014
3829our @WAIT_FOR_TICK; 4015our @WAIT_FOR_TICK;
3830our @WAIT_FOR_TICK_BEGIN; 4016our @WAIT_FOR_TICK_BEGIN;
3831 4017
3832sub wait_for_tick { 4018sub wait_for_tick() {
3833 return if tick_inhibit || $Coro::current == $Coro::main; 4019 return Coro::cede if tick_inhibit || $Coro::current == $Coro::main;
3834 4020
3835 my $signal = new Coro::Signal; 4021 my $signal = new Coro::Signal;
3836 push @WAIT_FOR_TICK, $signal; 4022 push @WAIT_FOR_TICK, $signal;
3837 $signal->wait; 4023 $signal->wait;
3838} 4024}
3839 4025
3840sub wait_for_tick_begin { 4026sub wait_for_tick_begin() {
3841 return if tick_inhibit || $Coro::current == $Coro::main; 4027 return Coro::cede if tick_inhibit || $Coro::current == $Coro::main;
3842 4028
3843 my $signal = new Coro::Signal; 4029 my $signal = new Coro::Signal;
3844 push @WAIT_FOR_TICK_BEGIN, $signal; 4030 push @WAIT_FOR_TICK_BEGIN, $signal;
3845 $signal->wait; 4031 $signal->wait;
3846} 4032}
3852 return; 4038 return;
3853 } 4039 }
3854 4040
3855 cf::server_tick; # one server iteration 4041 cf::server_tick; # one server iteration
3856 4042
4043 #for(1..3e6){} AE::now_update; $NOW=AE::now; # generate load #d#
4044
3857 if ($NOW >= $NEXT_RUNTIME_WRITE) { 4045 if ($NOW >= $NEXT_RUNTIME_WRITE) {
3858 $NEXT_RUNTIME_WRITE = List::Util::max $NEXT_RUNTIME_WRITE + 10, $NOW + 5.; 4046 $NEXT_RUNTIME_WRITE = List::Util::max $NEXT_RUNTIME_WRITE + 10, $NOW + 5.;
3859 Coro::async_pool { 4047 Coro::async_pool {
3860 $Coro::current->{desc} = "runtime saver"; 4048 $Coro::current->{desc} = "runtime saver";
3861 write_runtime_sync 4049 write_runtime_sync
3862 or warn "ERROR: unable to write runtime file: $!"; 4050 or error "ERROR: unable to write runtime file: $!";
3863 }; 4051 };
3864 } 4052 }
3865 4053
3866 if (my $sig = shift @WAIT_FOR_TICK_BEGIN) { 4054 if (my $sig = shift @WAIT_FOR_TICK_BEGIN) {
3867 $sig->send; 4055 $sig->send;
3875 4063
3876 if (0) { 4064 if (0) {
3877 if ($NEXT_TICK) { 4065 if ($NEXT_TICK) {
3878 my $jitter = $TICK_START - $NEXT_TICK; 4066 my $jitter = $TICK_START - $NEXT_TICK;
3879 $JITTER = $JITTER * 0.75 + $jitter * 0.25; 4067 $JITTER = $JITTER * 0.75 + $jitter * 0.25;
3880 warn "jitter $JITTER\n";#d# 4068 debug "jitter $JITTER\n";#d#
3881 } 4069 }
3882 } 4070 }
3883} 4071}
3884 4072
3885{ 4073{
3886 # configure BDB 4074 # configure BDB
3887 4075
3888 BDB::min_parallel 8; 4076 BDB::min_parallel 16;
3889 BDB::max_poll_reqs $TICK * 0.1; 4077 BDB::max_poll_reqs $TICK * 0.1;
3890 $AnyEvent::BDB::WATCHER->priority (1); 4078 $AnyEvent::BDB::WATCHER->priority (1);
3891 4079
3892 unless ($DB_ENV) { 4080 unless ($DB_ENV) {
3893 $DB_ENV = BDB::db_env_create; 4081 $DB_ENV = BDB::db_env_create;
3974 } 4162 }
3975} 4163}
3976 4164
3977# load additional modules 4165# load additional modules
3978require "cf/$_.pm" for @EXTRA_MODULES; 4166require "cf/$_.pm" for @EXTRA_MODULES;
4167cf::_connect_to_perl_2;
3979 4168
3980END { cf::emergency_save } 4169END { cf::emergency_save }
3981 4170
39821 41711
3983 4172

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines