ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/deliantra/server/lib/cf.pm
Revision: 1.32
Committed: Tue Aug 15 18:07:25 2006 UTC (17 years, 9 months ago) by root
Branch: MAIN
Changes since 1.31: +13 -0 lines
Log Message:
use perl's event loop as mainloop

File Contents

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