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.4 by root, Tue Feb 7 01:03:44 2006 UTC vs.
Revision 1.31 by elmex, Mon Aug 14 04:22:04 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 Event;
11$Event::Eval = 1; # no idea why this is required, but it is
5 12
6use strict; 13use strict;
7 14
8our %COMMAND; 15our %COMMAND;
9our @EVENT; 16our @EVENT;
10our %PROP_TYPE; 17our %PROP_TYPE;
11our %PROP_IDX; 18our %PROP_IDX;
19our $LIBDIR = maps_directory "perl";
12 20
13BEGIN { 21BEGIN {
14 @EVENT = map lc, @EVENT; 22 @EVENT = map lc, @EVENT;
15 23
16 *CORE::GLOBAL::warn = sub { 24 *CORE::GLOBAL::warn = sub {
21 print STDERR "cfperl: $msg"; 29 print STDERR "cfperl: $msg";
22 LOG llevError, "cfperl: $msg"; 30 LOG llevError, "cfperl: $msg";
23 }; 31 };
24} 32}
25 33
34my %ignore_set = (MAP_PROP_PATH => 1); # I hate the plug-in api. Deeply!
35
26# generate property mutators 36# generate property mutators
27sub prop_gen { 37sub prop_gen {
28 my ($prefix, $class) = @_; 38 my ($prefix, $class) = @_;
29 39
30 no strict 'refs'; 40 no strict 'refs';
40 $_[0]->get_property ($type, $idx) 50 $_[0]->get_property ($type, $idx)
41 }; 51 };
42 52
43 *{"$class\::set_$sub"} = sub { 53 *{"$class\::set_$sub"} = sub {
44 $_[0]->set_property ($type, $idx, $_[1]); 54 $_[0]->set_property ($type, $idx, $_[1]);
45 }; 55 } unless $ignore_set{$prop};
46 } 56 }
47} 57}
48 58
49# auto-generate most of the API 59# auto-generate most of the API
50 60
55prop_gen MAP_PROP => "cf::map"; 65prop_gen MAP_PROP => "cf::map";
56prop_gen ARCH_PROP => "cf::arch"; 66prop_gen ARCH_PROP => "cf::arch";
57 67
58# guessed hierarchies 68# guessed hierarchies
59 69
60@cf::object::player::ISA = 'cf::object'; 70@ext::cf::object::player::ISA = @cf::object::player::ISA = 'cf::object';
61@cf::object::map::ISA = 'cf::object'; 71@ext::cf::object::map::ISA = @cf::object::map::ISA = 'cf::object';
62 72
73# we bless all objects into derived classes to force a method lookup
74# 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)) {
76 no strict 'refs';
77 @{"ext::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg;
78}
79
80$Event::DIED = sub {
81 warn "error in event callback: @_";
82};
83
84my %ext_pkg;
63my @exts; 85my @exts;
64my @hook; 86my @hook;
65my %command; 87my %command;
88my %extcmd;
66 89
67sub inject_event { 90sub inject_event {
68 my ($data) = @_; 91 my $extension = shift;
92 my $event_code = shift;
69 93
70 my $cb = $hook[$data->{event_code}] 94 my $cb = $hook[$event_code]{$extension}
71 or return; 95 or return;
72 96
73 $_->($data) for values %$cb; 97 &$cb
98}
74 99
75 () 100sub inject_global_event {
101 my $event = shift;
102
103 my $cb = $hook[$event]
104 or return;
105
106 List::Util::max map &$_, values %$cb
76} 107}
77 108
78sub inject_command { 109sub inject_command {
79 my ($name, $obj, $params) = @_; 110 my ($name, $obj, $params) = @_;
80 111
87 118
88sub register_command { 119sub register_command {
89 my ($name, $time, $cb) = @_; 120 my ($name, $time, $cb) = @_;
90 121
91 my $caller = caller; 122 my $caller = caller;
92
93 warn "registering command '$name/$time' to '$caller'"; 123 #warn "registering command '$name/$time' to '$caller'";
94 124
95 push @{ $command{$name} }, [$time, $cb, $caller]; 125 push @{ $command{$name} }, [$time, $cb, $caller];
96 $COMMAND{"$name\000"} = List::Util::max map $_->[0], @{ $command{$name} }; 126 $COMMAND{"$name\000"} = List::Util::max map $_->[0], @{ $command{$name} };
97} 127}
98 128
129sub register_extcmd {
130 my ($name, $cb) = @_;
131
132 my $caller = caller;
133 #warn "registering extcmd '$name' to '$caller'";
134
135 $extcmd{$name} = [$cb, $caller];
136}
137
138sub register {
139 my ($base, $pkg) = @_;
140
141 for my $idx (0 .. $#EVENT) {
142 if (my $ref = $pkg->can ("on_$EVENT[$idx]")) {
143 #warn "registering $EVENT[$idx] hook to '$pkg'\n";
144 $hook[$idx]{$base} = $ref;
145 }
146 }
147}
148
99sub load_extension { 149sub load_extension {
100 my ($path) = @_; 150 my ($path) = @_;
101 151
102 $path =~ /([^\/\\]+)\.ext$/ or die "$path"; 152 $path =~ /([^\/\\]+)\.ext$/ or die "$path";
153 my $base = $1;
103 my $pkg = $1; 154 my $pkg = $1;
104 $pkg =~ s/[^[:word:]]/_/g; 155 $pkg =~ s/[^[:word:]]/_/g;
105 $pkg = "cf::ext::$pkg"; 156 $pkg = "cf::ext::$pkg";
106 157
107 warn "loading '$path' into '$pkg'\n"; 158 warn "loading '$path' into '$pkg'\n";
117 168
118 eval $source 169 eval $source
119 or die "$path: $@"; 170 or die "$path: $@";
120 171
121 push @exts, $pkg; 172 push @exts, $pkg;
173 $ext_pkg{$base} = $pkg;
122 174
123 no strict 'refs'; 175# no strict 'refs';
124
125# @{"$pkg\::ISA"} = cf::ext::; 176# @{"$pkg\::ISA"} = ext::;
126 177
127 for my $idx (0 .. $#EVENT) { 178 register $base, $pkg;
128 if (my $ref = $pkg->can ("on_$EVENT[$idx]")) {
129 warn "registering $EVENT[$idx] hook\n";
130 $hook[$idx]{$pkg} = $ref;
131 }
132 }
133} 179}
134 180
135sub unload_extension { 181sub unload_extension {
136 my ($pkg) = @_; 182 my ($pkg) = @_;
137 183
153 delete $command{$name}; 199 delete $command{$name};
154 delete $COMMAND{"$name\000"}; 200 delete $COMMAND{"$name\000"};
155 } 201 }
156 } 202 }
157 203
204 # remove extcmds
205 for my $name (grep $extcmd{$_}[1] eq $pkg, keys %extcmd) {
206 delete $extcmd{$name};
207 }
208
209 if (my $cb = $pkg->can ("on_unload")) {
210 eval {
211 $cb->($pkg);
212 1
213 } or warn "$pkg unloaded, but with errors: $@";
214 }
215
158 Symbol::delete_package $pkg; 216 Symbol::delete_package $pkg;
159} 217}
160 218
161sub load_extensions { 219sub load_extensions {
162 my $LIBDIR = maps_directory "perl"; 220 my $LIBDIR = maps_directory "perl";
176 if ($who->flag (FLAG_WIZ)) { 234 if ($who->flag (FLAG_WIZ)) {
177 $who->message ("reloading..."); 235 $who->message ("reloading...");
178 236
179 warn "reloading...\n"; 237 warn "reloading...\n";
180 eval { 238 eval {
239 # 1. cancel all watchers
240 $_->cancel for Event::all_watchers;
241
242 # 2. unload all extensions
243 for (@exts) {
244 $who->message ("unloading <$_>");
181 unload_extension $_ for @exts; 245 unload_extension $_;
246 }
247
248 # 3. unload all modules loaded from $LIBDIR
249 while (my ($k, $v) = each %INC) {
250 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
251
252 $who->message ("removing <$k>");
253 delete $INC{$k};
254
255 $k =~ s/\.pm$//;
256 $k =~ s/\//::/g;
257
258 if (my $cb = $k->can ("unload_module")) {
259 $cb->();
260 }
261
262 Symbol::delete_package $k;
263 }
264
265 # 4. get rid of ext::, as good as possible
266 Symbol::delete_package "ext::$_"
267 for qw(cf::object cf::object::map cf::object::player cf::player cf::map cf::party cf::region);
268
269 # 5. remove register_script_function callbacks
270 # TODO
271
272 # 6. unload cf.pm "a bit"
182 delete $INC{"cf.pm"}; 273 delete $INC{"cf.pm"};
183 274
184 # don't, removes xs symbols, too 275 # don't, removes xs symbols, too
185 #Symbol::delete_package $pkg; 276 #Symbol::delete_package __PACKAGE__;
186 277
278 # 7. reload cf.pm
279 $who->message ("reloading cf.pm");
187 require cf; 280 require cf;
188 }; 281 };
189 warn $@ if $@; 282 warn $@ if $@;
190 $who->message ($@) if $@; 283 $who->message ($@) if $@;
191 warn "reloaded\n"; 284 warn "reloaded\n";
194 } else { 287 } else {
195 $who->message ("Intruder Alert!"); 288 $who->message ("Intruder Alert!");
196 } 289 }
197}; 290};
198 291
292#############################################################################
293# utility functions
294
295use JSON::Syck (); # TODO# replace by JSON::PC once working
296
297sub from_json($) {
298 $JSON::Syck::ImplicitUnicode = 1; # work around JSON::Syck bugs
299 JSON::Syck::Load $_[0]
300}
301
302sub to_json($) {
303 $JSON::Syck::ImplicitUnicode = 0; # work around JSON::Syck bugs
304 JSON::Syck::Dump $_[0]
305}
306
307#############################################################################
308# extcmd framework, basically convert ext <msg>
309# into pkg::->on_extcmd_arg1 (...) while shortcutting a few
310
311sub on_extcmd {
312 my ($pl, $buf) = @_;
313
314 my $msg = eval { from_json $buf };
315
316 if (ref $msg) {
317 if (my $cb = $extcmd{$msg->{msgtype}}) {
318 if (my %reply = $cb->[0]->($pl, $msg)) {
319 $pl->ext_reply ($msg->{msgid}, %reply);
320 }
321 }
322 } else {
323 warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n";
324 }
325
326 1
327}
328
329#############################################################################
330# load/save/clean perl data associated with a map
331
332*on_mapclean = sub {
333 my ($map) = @_;
334
335 my $path = $map->tmpname;
336 defined $path or return;
337
338 unlink "$path.cfperl";
339};
340
341*on_mapin =
342*on_mapload = sub {
343 my ($map) = @_;
344
345 my $path = $map->tmpname;
346 $path = $map->path unless defined $path;
347
348 open my $fh, "<:raw", "$path.cfperl"
349 or return; # no perl data
350
351 my $data = Storable::thaw do { local $/; <$fh> };
352
353 $data->{version} <= 1
354 or return; # too new
355
356 $map->_set_obs ($data->{obs});
357};
358
359*on_mapout = sub {
360 my ($map) = @_;
361
362 my $path = $map->tmpname;
363 $path = $map->path unless defined $path;
364
365 my $obs = $map->_get_obs;
366
367 if (defined $obs) {
368 open my $fh, ">:raw", "$path.cfperl"
369 or die "$path.cfperl: $!";
370
371 stat $path;
372
373 print $fh Storable::nfreeze {
374 size => (stat _)[7],
375 time => (stat _)[9],
376 version => 1,
377 obs => $obs,
378 };
379
380 chmod SAVE_MODE, "$path.cfperl"; # very racy, but cf-compatible *g*
381 } else {
382 unlink "$path.cfperl";
383 }
384};
385
386#############################################################################
387# load/save perl data associated with player->ob objects
388
389*on_player_load = sub {
390 my ($ob, $path) = @_;
391
392 for my $o ($ob, $ob->inv) {
393 if (my $value = $o->get_ob_key_value ("_perl_data")) {
394 $o->set_ob_key_value ("_perl_data");
395
396 %$o = %{ Storable::thaw pack "H*", $value };
397 }
398 }
399};
400
401*on_player_save = sub {
402 my ($ob, $path) = @_;
403
404 $_->set_ob_key_value (_perl_data => unpack "H*", Storable::nfreeze $_)
405 for grep %$_, $ob, $ob->inv;
406};
407
408#############################################################################
409# core extensions - in perl
410
411=item cf::player::exists $login
412
413Returns true when the given account exists.
414
415=cut
416
417sub cf::player::exists($) {
418 cf::player::find $_[0]
419 or -f sprintf "%s/%s/%s/%s.pl", cf::localdir, cf::playerdir, ($_[0]) x 2;
420}
421
422=item $player->reply ($npc, $msg[, $flags])
423
424Sends a message to the player, as if the npc C<$npc> replied. C<$npc>
425can be C<undef>. Does the right thing when the player is currently in a
426dialogue with the given NPC character.
427
428=cut
429
430# rough implementation of a future "reply" method that works
431# with dialog boxes.
432sub cf::object::player::reply($$$;$) {
433 my ($self, $npc, $msg, $flags) = @_;
434
435 $flags = cf::NDI_BROWN | cf::NDI_UNIQUE unless @_ >= 4;
436
437 if ($self->{record_replies}) {
438 push @{ $self->{record_replies} }, [$npc, $msg, $flags];
439 } else {
440 $msg = $npc->name . " says: $msg" if $npc;
441 $self->message ($msg, $flags);
442 }
443}
444
445=item $player->ext_reply ($msgid, $msgtype, %msg)
446
447Sends an ext reply to the player.
448
449=cut
450
451sub cf::player::ext_reply($$$%) {
452 my ($self, $id, %msg) = @_;
453
454 $msg{msgid} = $id;
455
456 $self->send ("ext " . to_json \%msg);
457}
458
459#############################################################################
460# map scripting support
461
462our $safe = new Safe "ext";
463our $safe_hole = new Safe::Hole;
464
465$SIG{FPE} = 'IGNORE';
466
467$safe->permit_only (Opcode::opset qw(:base_core :base_mem :base_orig :base_math sort time));
468
469# here we export the classes and methods available to script code
470
471for (
472 ["cf::object" => qw(contr pay_amount pay_player)],
473 ["cf::object::player" => qw(player)],
474 ["cf::player" => qw(peaceful)],
475) {
476 no strict 'refs';
477 my ($pkg, @funs) = @$_;
478 *{"ext::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"})
479 for @funs;
480}
481
482sub safe_eval($;@) {
483 my ($code, %vars) = @_;
484
485 my $qcode = $code;
486 $qcode =~ s/"/‟/g; # not allowed in #line filenames
487 $qcode =~ s/\n/\\n/g;
488
489 local $_;
490 local @ext::cf::_safe_eval_args = values %vars;
491
492 $code =
493 "do {\n"
494 . "my (" . (join ",", map "\$$_", keys %vars) . ") = \@cf::_safe_eval_args;\n"
495 . "#line 0 \"{$qcode}\"\n"
496 . $code
497 . "\n}"
498 ;
499
500 sub_generation_inc;
501 my @res = wantarray ? $safe->reval ($code) : scalar $safe->reval ($code);
502 sub_generation_inc;
503
504 wantarray ? @res : $res[0]
505}
506
507sub register_script_function {
508 my ($fun, $cb) = @_;
509
510 no strict 'refs';
511 *{"ext::$fun"} = $safe_hole->wrap ($cb);
512}
513
514#############################################################################
515# initialisation
516
517register "<global>", __PACKAGE__;
518
519unshift @INC, $LIBDIR;
520
199load_extensions; 521load_extensions;
200 522
2011 5231
202 524

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines