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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines