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.24 by root, Wed Jul 19 22:51:40 2006 UTC vs.
Revision 1.41 by root, Fri Aug 25 15:25:12 2006 UTC

5use Storable; 5use Storable;
6use Opcode; 6use Opcode;
7use Safe; 7use Safe;
8use Safe::Hole; 8use Safe::Hole;
9 9
10use Time::HiRes;
10use Event; 11use Event;
11$Event::Eval = 1; # no idea why this is required, but it is 12$Event::Eval = 1; # no idea why this is required, but it is
12 13
13use strict; 14use strict;
14 15
15our %COMMAND; 16our %COMMAND = ();
16our @EVENT; 17our @EVENT;
18our @PLUGIN_EVENT;
17our %PROP_TYPE; 19our %PROP_TYPE;
18our %PROP_IDX; 20our %PROP_IDX;
21our $LIBDIR = maps_directory "perl";
22
23our $TICK = MAX_TIME * 1e-6;
24our $TICK_WATCHER;
25our $NEXT_TICK;
19 26
20BEGIN { 27BEGIN {
21 @EVENT = map lc, @EVENT; 28 @PLUGIN_EVENT = map lc, @PLUGIN_EVENT;
22 29
23 *CORE::GLOBAL::warn = sub { 30 *CORE::GLOBAL::warn = sub {
24 my $msg = join "", @_; 31 my $msg = join "", @_;
25 $msg .= "\n" 32 $msg .= "\n"
26 unless $msg =~ /\n$/; 33 unless $msg =~ /\n$/;
64prop_gen MAP_PROP => "cf::map"; 71prop_gen MAP_PROP => "cf::map";
65prop_gen ARCH_PROP => "cf::arch"; 72prop_gen ARCH_PROP => "cf::arch";
66 73
67# guessed hierarchies 74# guessed hierarchies
68 75
69@cf::object::player::ISA = 'cf::object'; 76@safe::cf::object::player::ISA = @cf::object::player::ISA = 'cf::object';
70@cf::object::map::ISA = 'cf::object'; 77@safe::cf::object::map::ISA = @cf::object::map::ISA = 'cf::object';
78
79# we bless all objects into (empty) derived classes to force a method lookup
80# within the Safe compartment.
81for my $pkg (qw(cf::object cf::object::map cf::object::player cf::player cf::map cf::party cf::region cf::arch)) {
82 no strict 'refs';
83 @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg;
84}
71 85
72$Event::DIED = sub { 86$Event::DIED = sub {
73 warn "error in event callback: @_"; 87 warn "error in event callback: @_";
74}; 88};
75 89
77my @exts; 91my @exts;
78my @hook; 92my @hook;
79my %command; 93my %command;
80my %extcmd; 94my %extcmd;
81 95
96#############################################################################
97# "new" plug-in system
98
99=item cf::object::attach ... # NYI
100
101=item cf::attach_global ...
102
103=item cf::attach_to_type ...
104
105=item cf::attach_to_objects ...
106
107=item cf::attach_to_players ...
108
109=item cf::attach_to_maps ...
110
111 prio => $number, # lower is earlier
112 on_xxx => \&cb,
113 package => package::,
114
115=cut
116
117# the following variables are defined in .xs and must not be re-created
118our @CB_GLOBAL = (); # registry for all global events
119our @CB_OBJECT = ();
120our @CB_PLAYER = ();
121our @CB_TYPE = (); # registry for type (cf-object class) based events
122our @CB_MAP = ();
123
124sub _attach_cb($\%$$$) {
125 my ($registry, $undo, $event, $prio, $cb) = @_;
126
127 use sort 'stable';
128
129 $cb = [$prio, $cb];
130
131 @{$registry->[$event]} = sort
132 { $a->[0] cmp $b->[0] }
133 @{$registry->[$event] || []}, $cb;
134
135 push @{$undo->{cb}}, [$event, $cb];
136}
137
138# attach handles attaching event callbacks
139# the only thing the caller has to do is pass the correct
140# registry (== where the callback attaches to).
141sub _attach(\@$\@) {
142 my ($registry, $klass, $arg) = @_;
143
144 my $prio = 0;
145
146 my %undo = (
147 registry => $registry,
148 cb => [],
149 );
150
151 my %cb_id = map +("on_" . lc $EVENT[$_][0], $_) , grep $EVENT[$_][1] == $klass, 0 .. $#EVENT;
152
153 while (@$arg) {
154 my $type = shift @$arg;
155
156 if ($type eq "prio") {
157 $prio = shift @$arg;
158
159 } elsif ($type eq "package") {
160 my $pkg = shift @$arg;
161
162 while (my ($name, $id) = each %cb_id) {
163 if (my $cb = $pkg->can ($name)) {
164 _attach_cb $registry, %undo, $id, $prio, $cb;
165 }
166 }
167
168 } elsif (exists $cb_id{$type}) {
169 _attach_cb $registry, %undo, $cb_id{$type}, $prio, shift @$arg;
170
171 } elsif (ref $type) {
172 warn "attaching objects not supported, ignoring.\n";
173
174 } else {
175 shift @$arg;
176 warn "attach argument '$type' not supported, ignoring.\n";
177 }
178 }
179
180 \%undo
181}
182
183sub cf::object::attach {
184 die;
185}
186
187sub attach_global {
188 _attach @CB_GLOBAL, KLASS_GLOBAL, @_
189}
190
191sub attach_to_type {
192 my $type = shift;
193 _attach @{$CB_TYPE[$type]}, KLASS_OBJECT, @_
194}
195
196sub attach_to_objects {
197 _attach @CB_OBJECT, KLASS_OBJECT, @_
198}
199
200sub attach_to_players {
201 _attach @CB_PLAYER, KLASS_PLAYER, @_
202}
203
204sub attach_to_maps {
205 _attach @CB_MAP, KLASS_MAP, @_
206}
207
208our $override;
209
210sub override() {
211 $override = 1
212}
213
214sub invoke {
215 my $event = shift;
216 my $callbacks = shift;
217
218 local $override;
219
220 for (@$callbacks) {
221 eval { &{$_->[1]} };
222
223 if ($@) {
224 warn "$@";
225 warn "... while processing $EVENT[$event][0] event, skipping processing altogether.\n";
226 override;
227 }
228
229 return 1 if $override;
230 }
231
232 0
233}
234
235#############################################################################
236# old plug-in events
237
82sub inject_event { 238sub inject_event {
83 my $extension = shift; 239 my $extension = shift;
84 my $event_code = shift; 240 my $event_code = shift;
85 241
86 my $cb = $hook[$event_code]{$extension} 242 my $cb = $hook[$event_code]{$extension}
128} 284}
129 285
130sub register { 286sub register {
131 my ($base, $pkg) = @_; 287 my ($base, $pkg) = @_;
132 288
133 for my $idx (0 .. $#EVENT) { 289 for my $idx (0 .. $#PLUGIN_EVENT) {
134 if (my $ref = $pkg->can ("on_$EVENT[$idx]")) { 290 if (my $ref = $pkg->can ("on_$PLUGIN_EVENT[$idx]")) {
135 #warn "registering $EVENT[$idx] hook to '$pkg'\n"; 291 #warn "registering $PLUGIN_EVENT[$idx] hook to '$pkg'\n";
136 $hook[$idx]{$base} = $ref; 292 $hook[$idx]{$base} = $ref;
137 } 293 }
138 } 294 }
139} 295}
140 296
143 299
144 $path =~ /([^\/\\]+)\.ext$/ or die "$path"; 300 $path =~ /([^\/\\]+)\.ext$/ or die "$path";
145 my $base = $1; 301 my $base = $1;
146 my $pkg = $1; 302 my $pkg = $1;
147 $pkg =~ s/[^[:word:]]/_/g; 303 $pkg =~ s/[^[:word:]]/_/g;
148 $pkg = "cf::ext::$pkg"; 304 $pkg = "ext::$pkg";
149 305
150 warn "loading '$path' into '$pkg'\n"; 306 warn "loading '$path' into '$pkg'\n";
151 307
152 open my $fh, "<:utf8", $path 308 open my $fh, "<:utf8", $path
153 or die "$path: $!"; 309 or die "$path: $!";
173sub unload_extension { 329sub unload_extension {
174 my ($pkg) = @_; 330 my ($pkg) = @_;
175 331
176 warn "removing extension $pkg\n"; 332 warn "removing extension $pkg\n";
177 333
178 if (my $cb = $pkg->can ("on_unload")) {
179 $cb->($pkg);
180 }
181
182 # remove hooks 334 # remove hooks
183 for my $idx (0 .. $#EVENT) { 335 for my $idx (0 .. $#PLUGIN_EVENT) {
184 delete $hook[$idx]{$pkg}; 336 delete $hook[$idx]{$pkg};
185 } 337 }
186 338
187 # remove commands 339 # remove commands
188 for my $name (keys %command) { 340 for my $name (keys %command) {
200 # remove extcmds 352 # remove extcmds
201 for my $name (grep $extcmd{$_}[1] eq $pkg, keys %extcmd) { 353 for my $name (grep $extcmd{$_}[1] eq $pkg, keys %extcmd) {
202 delete $extcmd{$name}; 354 delete $extcmd{$name};
203 } 355 }
204 356
357 if (my $cb = $pkg->can ("on_unload")) {
358 eval {
359 $cb->($pkg);
360 1
361 } or warn "$pkg unloaded, but with errors: $@";
362 }
363
205 Symbol::delete_package $pkg; 364 Symbol::delete_package $pkg;
206} 365}
207 366
208sub load_extensions { 367sub load_extensions {
209 my $LIBDIR = maps_directory "perl"; 368 my $LIBDIR = maps_directory "perl";
215 1 374 1
216 } or warn "$ext not loaded: $@"; 375 } or warn "$ext not loaded: $@";
217 } 376 }
218} 377}
219 378
379sub _perl_reload(&) {
380 my ($msg) = @_;
381
382 $msg->("reloading...");
383
384 eval {
385 # 1. cancel all watchers
386 $_->cancel for Event::all_watchers;
387
388 # 2. unload all extensions
389 for (@exts) {
390 $msg->("unloading <$_>");
391 unload_extension $_;
392 }
393
394 # 3. unload all modules loaded from $LIBDIR
395 while (my ($k, $v) = each %INC) {
396 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
397
398 $msg->("removing <$k>");
399 delete $INC{$k};
400
401 $k =~ s/\.pm$//;
402 $k =~ s/\//::/g;
403
404 if (my $cb = $k->can ("unload_module")) {
405 $cb->();
406 }
407
408 Symbol::delete_package $k;
409 }
410
411 # 4. get rid of safe::, as good as possible
412 Symbol::delete_package "safe::$_"
413 for qw(cf::object cf::object::map cf::object::player cf::player cf::map cf::party cf::region);
414
415 # 5. remove register_script_function callbacks
416 # TODO
417
418 # 6. unload cf.pm "a bit"
419 delete $INC{"cf.pm"};
420
421 # don't, removes xs symbols, too,
422 # and global variables created in xs
423 #Symbol::delete_package __PACKAGE__;
424
425 # 7. reload cf.pm
426 $msg->("reloading cf.pm");
427 require cf;
428 };
429 $msg->($@) if $@;
430
431 $msg->("reloaded");
432};
433
434sub perl_reload() {
435 _perl_reload {
436 warn $_[0];
437 print "$_[0]\n";
438 };
439}
440
220register_command "perl-reload", 0, sub { 441register_command "perl-reload", 0, sub {
221 my ($who, $arg) = @_; 442 my ($who, $arg) = @_;
222 443
223 if ($who->flag (FLAG_WIZ)) { 444 if ($who->flag (FLAG_WIZ)) {
224 $who->message ("reloading..."); 445 _perl_reload {
225 446 warn $_[0];
226 warn "reloading...\n"; 447 $who->message ($_[0]);
227 eval {
228 $_->cancel for Event::all_watchers;
229
230 unload_extension $_ for @exts;
231 delete $INC{"cf.pm"};
232
233 # don't, removes xs symbols, too
234 #Symbol::delete_package __PACKAGE__;
235
236 require cf;
237 }; 448 };
238 warn $@ if $@;
239 $who->message ($@) if $@;
240 warn "reloaded\n";
241
242 $who->message ("reloaded");
243 } else {
244 $who->message ("Intruder Alert!");
245 } 449 }
246}; 450};
247 451
248############################################################################# 452#############################################################################
453# utility functions
454
455use JSON::Syck (); # TODO# replace by JSON::PC once working
456
457sub from_json($) {
458 $JSON::Syck::ImplicitUnicode = 1; # work around JSON::Syck bugs
459 JSON::Syck::Load $_[0]
460}
461
462sub to_json($) {
463 $JSON::Syck::ImplicitUnicode = 0; # work around JSON::Syck bugs
464 JSON::Syck::Dump $_[0]
465}
466
467#############################################################################
249# extcmd framework, basically convert ext <id> <pkg> arg1 args 468# extcmd framework, basically convert ext <msg>
250# into pkg::->on_extcmd_arg1 (...) while shortcutting a few 469# into pkg::->on_extcmd_arg1 (...) while shortcutting a few
251 470
252sub on_extcmd { 471sub on_extcmd {
253 my ($pl, $buf) = @_; 472 my ($pl, $buf) = @_;
254 473
255 my ($type) = $buf =~ s/^(\S+) // ? $1 : ""; 474 my $msg = eval { from_json $buf };
256 475
257 $extcmd{$type}[0]->($pl, $buf) 476 if (ref $msg) {
258 if $extcmd{$type}; 477 if (my $cb = $extcmd{$msg->{msgtype}}) {
478 if (my %reply = $cb->[0]->($pl, $msg)) {
479 $pl->ext_reply ($msg->{msgid}, %reply);
480 }
481 }
482 } else {
483 warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n";
484 }
485
486 1
259} 487}
260 488
261############################################################################# 489#############################################################################
262# load/save/clean perl data associated with a map 490# load/save/clean perl data associated with a map
263 491
264*on_mapclean = sub { 492*cf::mapsupport::on_clean = sub {
265 my ($map) = @_; 493 my ($map) = @_;
266 494
267 my $path = $map->tmpname; 495 my $path = $map->tmpname;
268 defined $path or return; 496 defined $path or return;
269 497
270 unlink "$path.cfperl"; 498 unlink "$path.cfperl";
271}; 499};
272 500
273*on_mapin = 501*cf::mapsupport::on_swapin =
274*on_mapload = sub { 502*cf::mapsupport::on_load = sub {
275 my ($map) = @_; 503 my ($map) = @_;
276 504
277 my $path = $map->tmpname; 505 my $path = $map->tmpname;
278 $path = $map->path unless defined $path; 506 $path = $map->path unless defined $path;
279 507
286 or return; # too new 514 or return; # too new
287 515
288 $map->_set_obs ($data->{obs}); 516 $map->_set_obs ($data->{obs});
289}; 517};
290 518
291*on_mapout = sub { 519*cf::mapsupport::on_swapout = sub {
292 my ($map) = @_; 520 my ($map) = @_;
293 521
294 my $path = $map->tmpname; 522 my $path = $map->tmpname;
295 $path = $map->path unless defined $path; 523 $path = $map->path unless defined $path;
296 524
313 } else { 541 } else {
314 unlink "$path.cfperl"; 542 unlink "$path.cfperl";
315 } 543 }
316}; 544};
317 545
546attach_to_maps prio => -10000, package => cf::mapsupport::;
547
318############################################################################# 548#############################################################################
319# load/save perl data associated with player->ob objects 549# load/save perl data associated with player->ob objects
320 550
321*on_player_load = sub { 551sub all_objects(@) {
552 @_, map all_objects ($_->inv), @_
553}
554
555attach_to_players
556 on_load => sub {
322 my ($ob, $path) = @_; 557 my ($pl, $path) = @_;
323 558
324 if (open my $fh, "<:raw", "$path.cfperl") { 559 for my $o (all_objects $pl->ob) {
325
326 #d##TODO#remove
327
328 my $data = Storable::thaw do { local $/; <$fh> };
329
330 $data->{version} <= 1
331 or return; # too new
332
333 %$ob = %{$data->{ob}};
334 return;
335 }
336
337 for my $o ($ob, $ob->inv) {
338 if (my $value = $o->get_ob_key_value ("_perl_data")) { 560 if (my $value = $o->get_ob_key_value ("_perl_data")) {
339 $o->set_ob_key_value ("_perl_data"); 561 $o->set_ob_key_value ("_perl_data");
340 562
341 %$o = %{ Storable::thaw pack "H*", $value }; 563 %$o = %{ Storable::thaw pack "H*", $value };
564 }
342 } 565 }
343 } 566 },
344}; 567 on_save => sub {
345
346*on_player_save = sub {
347 my ($ob, $path) = @_; 568 my ($pl, $path) = @_;
348 569
349 $_->set_ob_key_value (_perl_data => unpack "H*", Storable::nfreeze $_) 570 $_->set_ob_key_value (_perl_data => unpack "H*", Storable::nfreeze $_)
350 for grep %$_, $ob, $ob->inv; 571 for grep %$_, all_objects $pl->ob;
351 572 },
352 unlink "$path.cfperl";#d##TODO#remove 573;
353};
354 574
355############################################################################# 575#############################################################################
356# core extensions - in perl 576# core extensions - in perl
357 577
358=item cf::player::exists $login 578=item cf::player::exists $login
363 583
364sub cf::player::exists($) { 584sub cf::player::exists($) {
365 cf::player::find $_[0] 585 cf::player::find $_[0]
366 or -f sprintf "%s/%s/%s/%s.pl", cf::localdir, cf::playerdir, ($_[0]) x 2; 586 or -f sprintf "%s/%s/%s/%s.pl", cf::localdir, cf::playerdir, ($_[0]) x 2;
367} 587}
588
589=item $player->reply ($npc, $msg[, $flags])
590
591Sends a message to the player, as if the npc C<$npc> replied. C<$npc>
592can be C<undef>. Does the right thing when the player is currently in a
593dialogue with the given NPC character.
594
595=cut
368 596
369# rough implementation of a future "reply" method that works 597# rough implementation of a future "reply" method that works
370# with dialog boxes. 598# with dialog boxes.
371sub cf::object::player::reply($$$;$) { 599sub cf::object::player::reply($$$;$) {
372 my ($self, $npc, $msg, $flags) = @_; 600 my ($self, $npc, $msg, $flags) = @_;
379 $msg = $npc->name . " says: $msg" if $npc; 607 $msg = $npc->name . " says: $msg" if $npc;
380 $self->message ($msg, $flags); 608 $self->message ($msg, $flags);
381 } 609 }
382} 610}
383 611
612=item $player->ext_reply ($msgid, $msgtype, %msg)
613
614Sends an ext reply to the player.
615
616=cut
617
618sub cf::player::ext_reply($$$%) {
619 my ($self, $id, %msg) = @_;
620
621 $msg{msgid} = $id;
622
623 $self->send ("ext " . to_json \%msg);
624}
625
384############################################################################# 626#############################################################################
385# map scripting support 627# map scripting support
386 628
387our $safe = new Safe "ext"; 629our $safe = new Safe "ext";
388our $safe_hole = new Safe::Hole; 630our $safe_hole = new Safe::Hole;
389 631
390$SIG{FPE} = 'IGNORE'; 632$SIG{FPE} = 'IGNORE';
391 633
392$safe->permit_only (Opcode::opset qw(:base_core :base_mem :base_orig :base_math sort time)); 634$safe->permit_only (Opcode::opset qw(:base_core :base_mem :base_orig :base_math sort time));
393 635
394# here we would export the classes and methods available to script code 636# here we export the classes and methods available to script code
395#@ext::cf::object::player::ISA = @cf::object::player::ISA; 637
396#@ext::cf::object::map::ISA = @cf::object::map::ISA; 638for (
639 ["cf::object" => qw(contr pay_amount pay_player)],
640 ["cf::object::player" => qw(player)],
641 ["cf::player" => qw(peaceful)],
642) {
643 no strict 'refs';
644 my ($pkg, @funs) = @$_;
645 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"})
646 for @funs;
647}
397 648
398sub safe_eval($;@) { 649sub safe_eval($;@) {
399 my ($code, %vars) = @_; 650 my ($code, %vars) = @_;
400 651
401 my $qcode = $code; 652 my $qcode = $code;
402 $qcode =~ s/"/‟/g; # not allowed in #line filenames 653 $qcode =~ s/"/‟/g; # not allowed in #line filenames
403 $qcode =~ s/\n/\\n/g; 654 $qcode =~ s/\n/\\n/g;
404 655
405 local $_; 656 local $_;
406 local @ext::cf::_safe_eval_args = values %vars; 657 local @safe::cf::_safe_eval_args = values %vars;
407 658
408 $safe->reval ( 659 $code =
409 "do {\n" 660 "do {\n"
410 . "my (" . (join ",", map "\$$_", keys %vars) . ") = \@cf::_safe_eval_args;\n" 661 . "my (" . (join ",", map "\$$_", keys %vars) . ") = \@cf::_safe_eval_args;\n"
411 . "#line 0 \"{$qcode}\"\n" 662 . "#line 0 \"{$qcode}\"\n"
412 . $code 663 . $code
413 . "\n}" 664 . "\n}"
414 ) 665 ;
666
667 sub_generation_inc;
668 my @res = wantarray ? $safe->reval ($code) : scalar $safe->reval ($code);
669 sub_generation_inc;
670
671 wantarray ? @res : $res[0]
415} 672}
416 673
417sub register_script_function { 674sub register_script_function {
418 my ($fun, $cb) = @_; 675 my ($fun, $cb) = @_;
419 676
420 no strict 'refs'; 677 no strict 'refs';
421 *{"ext::$fun"} = $safe_hole->wrap ($cb); 678 *{"safe::$fun"} = $safe_hole->wrap ($cb);
679}
680
681#############################################################################
682# the server's main()
683
684sub main {
685 Event::loop;
422} 686}
423 687
424############################################################################# 688#############################################################################
425# initialisation 689# initialisation
426 690
427register "<global>", __PACKAGE__; 691register "<global>", __PACKAGE__;
428 692
429unshift @INC, maps_directory "perl"; 693unshift @INC, $LIBDIR;
430 694
431load_extensions; 695load_extensions;
432 696
697$TICK_WATCHER = Event->timer (
698 prio => 1,
699 at => $NEXT_TICK || 1,
700 cb => sub {
701 cf::server_tick; # one server iteration
702
703 my $NOW = Event::time;
704 $NEXT_TICK += $TICK;
705
706 # if we are delayed by four ticks, skip them all
707 $NEXT_TICK = $NOW if $NOW >= $NEXT_TICK + $TICK * 4;
708
709 $TICK_WATCHER->at ($NEXT_TICK);
710 $TICK_WATCHER->start;
711 },
712);
713
4331 7141
434 715

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines