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.3 by root, Sat Feb 4 20:38:29 2006 UTC vs.
Revision 1.39 by root, Fri Aug 25 13:24:50 2006 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines