ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/deliantra/server/lib/cf.pm
Revision: 1.38
Committed: Thu Aug 24 17:29:30 2006 UTC (17 years, 9 months ago) by root
Branch: MAIN
Changes since 1.37: +6 -5 lines
Log Message:
- fix extmap protocol
- lay foundation for new event interface (not used, not tested)
- "slow down" in-game time specials

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