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.69 by root, Mon Sep 18 01:10:35 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
16_init_vars;
17
15our %COMMAND; 18our %COMMAND = ();
16our @EVENT; 19our @EVENT;
17our %PROP_TYPE;
18our %PROP_IDX;
19our $LIBDIR = maps_directory "perl"; 20our $LIBDIR = maps_directory "perl";
20 21
22our $TICK = MAX_TIME * 1e-6;
23our $TICK_WATCHER;
24our $NEXT_TICK;
25
21BEGIN { 26BEGIN {
22 @EVENT = map lc, @EVENT;
23
24 *CORE::GLOBAL::warn = sub { 27 *CORE::GLOBAL::warn = sub {
25 my $msg = join "", @_; 28 my $msg = join "", @_;
26 $msg .= "\n" 29 $msg .= "\n"
27 unless $msg =~ /\n$/; 30 unless $msg =~ /\n$/;
28 31
29 print STDERR "cfperl: $msg"; 32 print STDERR "cfperl: $msg";
30 LOG llevError, "cfperl: $msg"; 33 LOG llevError, "cfperl: $msg";
31 }; 34 };
32} 35}
33 36
34my %ignore_set = (MAP_PROP_PATH => 1); # I hate the plug-in api. Deeply! 37@safe::cf::object::player::ISA = @cf::object::player::ISA = 'cf::object';
35 38
36# generate property mutators 39# we bless all objects into (empty) derived classes to force a method lookup
37sub prop_gen { 40# within the Safe compartment.
38 my ($prefix, $class) = @_; 41for my $pkg (qw(cf::object cf::object::player cf::player cf::map cf::party cf::region cf::arch cf::living)) {
39
40 no strict 'refs'; 42 no strict 'refs';
41
42 for my $prop (keys %PROP_TYPE) {
43 $prop =~ /^\Q$prefix\E_(.*$)/ or next;
44 my $sub = lc $1;
45
46 my $type = $PROP_TYPE{$prop};
47 my $idx = $PROP_IDX {$prop};
48
49 *{"$class\::get_$sub"} = *{"$class\::$sub"} = sub {
50 $_[0]->get_property ($type, $idx)
51 };
52
53 *{"$class\::set_$sub"} = sub {
54 $_[0]->set_property ($type, $idx, $_[1]);
55 } unless $ignore_set{$prop};
56 }
57}
58
59# auto-generate most of the API
60
61prop_gen OBJECT_PROP => "cf::object";
62# CFAPI_OBJECT_ANIMATION?
63prop_gen PLAYER_PROP => "cf::object::player";
64
65prop_gen MAP_PROP => "cf::map";
66prop_gen ARCH_PROP => "cf::arch";
67
68# guessed hierarchies
69
70@ext::cf::object::player::ISA = @cf::object::player::ISA = 'cf::object';
71@ext::cf::object::map::ISA = @cf::object::map::ISA = 'cf::object';
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; 43 @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg;
78} 44}
79 45
80$Event::DIED = sub { 46$Event::DIED = sub {
81 warn "error in event callback: @_"; 47 warn "error in event callback: @_";
82}; 48};
85my @exts; 51my @exts;
86my @hook; 52my @hook;
87my %command; 53my %command;
88my %extcmd; 54my %extcmd;
89 55
56#############################################################################
57# utility functions
58
59use JSON::Syck (); # TODO# replace by JSON::PC once working
60
61sub from_json($) {
62 $JSON::Syck::ImplicitUnicode = 1; # work around JSON::Syck bugs
63 JSON::Syck::Load $_[0]
64}
65
66sub to_json($) {
67 $JSON::Syck::ImplicitUnicode = 0; # work around JSON::Syck bugs
68 JSON::Syck::Dump $_[0]
69}
70
71#############################################################################
72# "new" plug-in system
73
74=head3 EVENTS AND OBJECT ATTACHMENTS
75
76=over 4
77
78=item $object->attach ($attachment, key => $value...)
79
80=item $object->detach ($attachment)
81
82Attach/detach a pre-registered attachment to an object.
83
84=item $player->attach ($attachment, key => $value...)
85
86=item $player->detach ($attachment)
87
88Attach/detach a pre-registered attachment to a player.
89
90=item $map->attach ($attachment, key => $value...)
91
92=item $map->detach ($attachment)
93
94Attach/detach a pre-registered attachment to a map.
95
96=item $bool = $object->attached ($name)
97
98=item $bool = $player->attached ($name)
99
100=item $bool = $map->attached ($name)
101
102Checks wether the named attachment is currently attached to the object.
103
104=item cf::attach_global ...
105
106Attach handlers for global events.
107
108This and all following C<attach_*>-functions expect any number of the
109following handler/hook descriptions:
110
111=over 4
112
113=item prio => $number
114
115Set the priority for all following handlers/hooks (unless overwritten
116by another C<prio> setting). Lower priority handlers get executed
117earlier. The default priority is C<0>, and many built-in handlers are
118registered at priority C<-1000>, so lower priorities should not be used
119unless you know what you are doing.
120
121=item on_I<event> => \&cb
122
123Call the given code reference whenever the named event happens (event is
124something like C<instantiate>, C<apply>, C<use_skill> and so on, and which
125handlers are recognised generally depends on the type of object these
126handlers attach to).
127
128See F<include/eventinc.h> for the full list of events supported, and their
129class.
130
131=item package => package::
132
133Look for sub functions of the name C<< on_I<event> >> in the given
134package and register them. Only handlers for eevents supported by the
135object/class are recognised.
136
137=back
138
139=item cf::attach_to_type $object_type, $subtype, ...
140
141Attach handlers for a specific object type (e.g. TRANSPORT) and
142subtype. If C<$subtype> is zero or undef, matches all objects of the given
143type.
144
145=item cf::attach_to_objects ...
146
147Attach handlers to all objects. Do not use this except for debugging or
148very rare events, as handlers are (obviously) called for I<all> objects in
149the game.
150
151=item cf::attach_to_players ...
152
153Attach handlers to all players.
154
155=item cf::attach_to_maps ...
156
157Attach handlers to all maps.
158
159=item cf:register_attachment $name, ...
160
161Register an attachment by name through which objects can refer to this
162attachment.
163
164=item cf:register_player_attachment $name, ...
165
166Register an attachment by name through which players can refer to this
167attachment.
168
169=item cf:register_map_attachment $name, ...
170
171Register an attachment by name through which maps can refer to this
172attachment.
173
174=cut
175
176# the following variables are defined in .xs and must not be re-created
177our @CB_GLOBAL = (); # registry for all global events
178our @CB_OBJECT = (); # all objects (should not be used except in emergency)
179our @CB_PLAYER = ();
180our @CB_TYPE = (); # registry for type (cf-object class) based events
181our @CB_MAP = ();
182
183my %attachment;
184
185sub _attach_cb($\%$$$) {
186 my ($registry, $undo, $event, $prio, $cb) = @_;
187
188 use sort 'stable';
189
190 $cb = [$prio, $cb];
191
192 @{$registry->[$event]} = sort
193 { $a->[0] cmp $b->[0] }
194 @{$registry->[$event] || []}, $cb;
195
196 push @{$undo->{cb}}, [$event, $cb];
197}
198
199# attach handles attaching event callbacks
200# the only thing the caller has to do is pass the correct
201# registry (== where the callback attaches to).
202sub _attach(\@$@) {
203 my ($registry, $klass, @arg) = @_;
204
205 my $prio = 0;
206
207 my %undo = (
208 registry => $registry,
209 cb => [],
210 );
211
212 my %cb_id = map +("on_" . lc $EVENT[$_][0], $_) , grep $EVENT[$_][1] == $klass, 0 .. $#EVENT;
213
214 while (@arg) {
215 my $type = shift @arg;
216
217 if ($type eq "prio") {
218 $prio = shift @arg;
219
220 } elsif ($type eq "package") {
221 my $pkg = shift @arg;
222
223 while (my ($name, $id) = each %cb_id) {
224 if (my $cb = $pkg->can ($name)) {
225 _attach_cb $registry, %undo, $id, $prio, $cb;
226 }
227 }
228
229 } elsif (exists $cb_id{$type}) {
230 _attach_cb $registry, %undo, $cb_id{$type}, $prio, shift @arg;
231
232 } elsif (ref $type) {
233 warn "attaching objects not supported, ignoring.\n";
234
235 } else {
236 shift @arg;
237 warn "attach argument '$type' not supported, ignoring.\n";
238 }
239 }
240
241 \%undo
242}
243
244sub _attach_attachment {
245 my ($obj, $name, %arg) = @_;
246
247 return if exists $obj->{_attachment}{$name};
248
249 my $res;
250
251 if (my $attach = $attachment{$name}) {
252 my $registry = $obj->registry;
253
254 for (@$attach) {
255 my ($klass, @attach) = @$_;
256 $res = _attach @$registry, $klass, @attach;
257 }
258
259 $obj->{$name} = \%arg;
260 } else {
261 warn "object uses attachment '$name' that is not available, postponing.\n";
262 }
263
264 $obj->{_attachment}{$name} = undef;
265
266 $res->{attachment} = $name;
267 $res
268}
269
270*cf::object::attach =
271*cf::player::attach =
272*cf::map::attach = sub {
273 my ($obj, $name, %arg) = @_;
274
275 _attach_attachment $obj, $name, %arg;
276};
277
278# all those should be optimised
279*cf::object::detach =
280*cf::player::detach =
281*cf::map::detach = sub {
282 my ($obj, $name) = @_;
283
284 delete $obj->{_attachment}{$name};
285 reattach ($obj);
286};
287
288*cf::object::attached =
289*cf::player::attached =
290*cf::map::attached = sub {
291 my ($obj, $name) = @_;
292
293 exists $obj->{_attachment}{$name}
294};
295
296sub attach_global {
297 _attach @CB_GLOBAL, KLASS_GLOBAL, @_
298}
299
300sub attach_to_type {
301 my $type = shift;
302 my $subtype = shift;
303
304 _attach @{$CB_TYPE[$type + $subtype * NUM_SUBTYPES]}, KLASS_OBJECT, @_
305}
306
307sub attach_to_objects {
308 _attach @CB_OBJECT, KLASS_OBJECT, @_
309}
310
311sub attach_to_players {
312 _attach @CB_PLAYER, KLASS_PLAYER, @_
313}
314
315sub attach_to_maps {
316 _attach @CB_MAP, KLASS_MAP, @_
317}
318
319sub register_attachment {
320 my $name = shift;
321
322 $attachment{$name} = [[KLASS_OBJECT, @_]];
323}
324
325sub register_player_attachment {
326 my $name = shift;
327
328 $attachment{$name} = [[KLASS_PLAYER, @_]];
329}
330
331sub register_map_attachment {
332 my $name = shift;
333
334 $attachment{$name} = [[KLASS_MAP, @_]];
335}
336
337our $override;
338our @invoke_results = (); # referenced from .xs code. TODO: play tricks with reify and mortals?
339
340sub override {
341 $override = 1;
342 @invoke_results = ();
343}
344
345sub do_invoke {
346 my $event = shift;
347 my $callbacks = shift;
348
349 @invoke_results = ();
350
351 local $override;
352
353 for (@$callbacks) {
354 eval { &{$_->[1]} };
355
356 if ($@) {
357 warn "$@";
358 warn "... while processing $EVENT[$event][0](@_) event, skipping processing altogether.\n";
359 override;
360 }
361
362 return 1 if $override;
363 }
364
365 0
366}
367
368=item $bool = cf::invoke EVENT_GLOBAL_XXX, ...
369
370=item $bool = $object->invoke (EVENT_OBJECT_XXX, ...)
371
372=item $bool = $player->invoke (EVENT_PLAYER_XXX, ...)
373
374=item $bool = $map->invoke (EVENT_MAP_XXX, ...)
375
376Generate a global/object/player/map-specific event with the given arguments.
377
378This API is preliminary (most likely, the EVENT_KLASS_xxx prefix will be
379removed in future versions), and there is no public API to access override
380results (if you must, access C<@cf::invoke_results> directly).
381
382=back
383
384=head2 methods valid for all pointers
385
386=over 4
387
388=item $object->valid
389
390=item $player->valid
391
392=item $map->valid
393
394Just because you have a perl object does not mean that the corresponding
395C-level object still exists. If you try to access an object that has no
396valid C counterpart anymore you get an exception at runtime. This method
397can be used to test for existence of the C object part without causing an
398exception.
399
400=back
401
402=cut
403
404*cf::object::valid =
405*cf::player::valid =
406*cf::map::valid = \&cf::_valid;
407
408#############################################################################
409# object support
410
411sub instantiate {
412 my ($obj, $data) = @_;
413
414 $data = from_json $data;
415
416 for (@$data) {
417 my ($name, $args) = @$_;
418
419 $obj->attach ($name, %{$args || {} });
420 }
421}
422
423# basically do the same as instantiate, without calling instantiate
424sub reattach {
425 my ($obj) = @_;
426 my $registry = $obj->registry;
427
428 @$registry = ();
429
430 delete $obj->{_attachment} unless scalar keys %{ $obj->{_attachment} || {} };
431
432 for my $name (keys %{ $obj->{_attachment} || {} }) {
433 if (my $attach = $attachment{$name}) {
434 for (@$attach) {
435 my ($klass, @attach) = @$_;
436 _attach @$registry, $klass, @attach;
437 }
438 } else {
439 warn "object uses attachment '$name' that is not available, postponing.\n";
440 }
441 }
442}
443
444sub object_freezer_save {
445 my ($filename, $rdata, $objs) = @_;
446
447 if (length $$rdata) {
448 warn sprintf "saving %s (%d,%d)\n",
449 $filename, length $$rdata, scalar @$objs;
450
451 if (open my $fh, ">:raw", "$filename~") {
452 chmod SAVE_MODE, $fh;
453 syswrite $fh, $$rdata;
454 close $fh;
455
456 if (@$objs && open my $fh, ">:raw", "$filename.pst~") {
457 chmod SAVE_MODE, $fh;
458 syswrite $fh, Storable::nfreeze { version => 1, objs => $objs };
459 close $fh;
460 rename "$filename.pst~", "$filename.pst";
461 } else {
462 unlink "$filename.pst";
463 }
464
465 rename "$filename~", $filename;
466 } else {
467 warn "FATAL: $filename~: $!\n";
468 }
469 } else {
470 unlink $filename;
471 unlink "$filename.pst";
472 }
473}
474
475sub object_thawer_load {
476 my ($filename) = @_;
477
478 local $/;
479
480 my $av;
481
482 #TODO: use sysread etc.
483 if (open my $data, "<:raw:perlio", $filename) {
484 $data = <$data>;
485 if (open my $pst, "<:raw:perlio", "$filename.pst") {
486 $av = eval { (Storable::thaw <$pst>)->{objs} };
487 }
488 return ($data, $av);
489 }
490
491 ()
492}
493
494attach_to_objects
495 prio => -1000000,
496 on_clone => sub {
497 my ($src, $dst) = @_;
498
499 @{$dst->registry} = @{$src->registry};
500
501 %$dst = %$src;
502
503 %{$dst->{_attachment}} = %{$src->{_attachment}}
504 if exists $src->{_attachment};
505 },
506;
507
508#############################################################################
509# old plug-in events
510
90sub inject_event { 511sub inject_event {
91 my $extension = shift; 512 my $extension = shift;
92 my $event_code = shift; 513 my $event_code = shift;
93 514
94 my $cb = $hook[$event_code]{$extension} 515 my $cb = $hook[$event_code]{$extension}
136} 557}
137 558
138sub register { 559sub register {
139 my ($base, $pkg) = @_; 560 my ($base, $pkg) = @_;
140 561
141 for my $idx (0 .. $#EVENT) { 562 #TODO
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} 563}
148 564
149sub load_extension { 565sub load_extension {
150 my ($path) = @_; 566 my ($path) = @_;
151 567
152 $path =~ /([^\/\\]+)\.ext$/ or die "$path"; 568 $path =~ /([^\/\\]+)\.ext$/ or die "$path";
153 my $base = $1; 569 my $base = $1;
154 my $pkg = $1; 570 my $pkg = $1;
155 $pkg =~ s/[^[:word:]]/_/g; 571 $pkg =~ s/[^[:word:]]/_/g;
156 $pkg = "cf::ext::$pkg"; 572 $pkg = "ext::$pkg";
157 573
158 warn "loading '$path' into '$pkg'\n"; 574 warn "loading '$path' into '$pkg'\n";
159 575
160 open my $fh, "<:utf8", $path 576 open my $fh, "<:utf8", $path
161 or die "$path: $!"; 577 or die "$path: $!";
181sub unload_extension { 597sub unload_extension {
182 my ($pkg) = @_; 598 my ($pkg) = @_;
183 599
184 warn "removing extension $pkg\n"; 600 warn "removing extension $pkg\n";
185 601
186 if (my $cb = $pkg->can ("on_unload")) {
187 $cb->($pkg);
188 }
189
190 # remove hooks 602 # remove hooks
603 #TODO
191 for my $idx (0 .. $#EVENT) { 604# for my $idx (0 .. $#PLUGIN_EVENT) {
192 delete $hook[$idx]{$pkg}; 605# delete $hook[$idx]{$pkg};
193 } 606# }
194 607
195 # remove commands 608 # remove commands
196 for my $name (keys %command) { 609 for my $name (keys %command) {
197 my @cb = grep $_->[2] ne $pkg, @{ $command{$name} }; 610 my @cb = grep $_->[2] ne $pkg, @{ $command{$name} };
198 611
208 # remove extcmds 621 # remove extcmds
209 for my $name (grep $extcmd{$_}[1] eq $pkg, keys %extcmd) { 622 for my $name (grep $extcmd{$_}[1] eq $pkg, keys %extcmd) {
210 delete $extcmd{$name}; 623 delete $extcmd{$name};
211 } 624 }
212 625
626 if (my $cb = $pkg->can ("unload")) {
627 eval {
628 $cb->($pkg);
629 1
630 } or warn "$pkg unloaded, but with errors: $@";
631 }
632
213 Symbol::delete_package $pkg; 633 Symbol::delete_package $pkg;
214} 634}
215 635
216sub load_extensions { 636sub load_extensions {
217 my $LIBDIR = maps_directory "perl"; 637 my $LIBDIR = maps_directory "perl";
223 1 643 1
224 } or warn "$ext not loaded: $@"; 644 } or warn "$ext not loaded: $@";
225 } 645 }
226} 646}
227 647
228register_command "perl-reload", 0, sub {
229 my ($who, $arg) = @_;
230
231 if ($who->flag (FLAG_WIZ)) {
232 $who->message ("reloading...");
233
234 warn "reloading...\n";
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 };
279 warn $@ if $@;
280 $who->message ($@) if $@;
281 warn "reloaded\n";
282
283 $who->message ("reloaded");
284 } else {
285 $who->message ("Intruder Alert!");
286 }
287};
288
289#############################################################################
290# utility functions
291
292use JSON::Syck (); # TODO# replace by JSON::PC once working
293
294sub from_json($) {
295 $JSON::Syck::ImplicitUnicode = 1; # work around JSON::Syck bugs
296 JSON::Syck::Load $_[0]
297}
298
299sub to_json($) {
300 $JSON::Syck::ImplicitUnicode = 0; # work around JSON::Syck bugs
301 JSON::Syck::Dump $_[0]
302}
303
304############################################################################# 648#############################################################################
305# extcmd framework, basically convert ext <msg> 649# extcmd framework, basically convert ext <msg>
306# into pkg::->on_extcmd_arg1 (...) while shortcutting a few 650# into pkg::->on_extcmd_arg1 (...) while shortcutting a few
307 651
308sub on_extcmd { 652attach_to_players
653 on_extcmd => sub {
309 my ($pl, $buf) = @_; 654 my ($pl, $buf) = @_;
310 655
311 my $msg = eval { from_json $buf }; 656 my $msg = eval { from_json $buf };
312 657
313 if (ref $msg) { 658 if (ref $msg) {
314 if (my $cb = $extcmd{$msg->{msgtype}}) { 659 if (my $cb = $extcmd{$msg->{msgtype}}) {
315 if (my %reply = $cb->[0]->($pl, $msg)) { 660 if (my %reply = $cb->[0]->($pl, $msg)) {
316 $pl->ext_reply ($msg->{msgid}, %reply); 661 $pl->ext_reply ($msg->{msgid}, %reply);
662 }
317 } 663 }
318 }
319 } else { 664 } else {
320 warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n"; 665 warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n";
666 }
667
668 cf::override;
321 } 669 },
322 670;
323 1
324}
325 671
326############################################################################# 672#############################################################################
327# load/save/clean perl data associated with a map 673# load/save/clean perl data associated with a map
328 674
329*on_mapclean = sub { 675*cf::mapsupport::on_clean = sub {
330 my ($map) = @_; 676 my ($map) = @_;
331 677
332 my $path = $map->tmpname; 678 my $path = $map->tmpname;
333 defined $path or return; 679 defined $path or return;
334 680
335 unlink "$path.cfperl"; 681 unlink "$path.pst";
336}; 682};
337 683
338*on_mapin = 684attach_to_maps prio => -10000, package => cf::mapsupport::;
339*on_mapload = sub {
340 my ($map) = @_;
341
342 my $path = $map->tmpname;
343 $path = $map->path unless defined $path;
344
345 open my $fh, "<:raw", "$path.cfperl"
346 or return; # no perl data
347
348 my $data = Storable::thaw do { local $/; <$fh> };
349
350 $data->{version} <= 1
351 or return; # too new
352
353 $map->_set_obs ($data->{obs});
354};
355
356*on_mapout = sub {
357 my ($map) = @_;
358
359 my $path = $map->tmpname;
360 $path = $map->path unless defined $path;
361
362 my $obs = $map->_get_obs;
363
364 if (defined $obs) {
365 open my $fh, ">:raw", "$path.cfperl"
366 or die "$path.cfperl: $!";
367
368 stat $path;
369
370 print $fh Storable::nfreeze {
371 size => (stat _)[7],
372 time => (stat _)[9],
373 version => 1,
374 obs => $obs,
375 };
376
377 chmod SAVE_MODE, "$path.cfperl"; # very racy, but cf-compatible *g*
378 } else {
379 unlink "$path.cfperl";
380 }
381};
382 685
383############################################################################# 686#############################################################################
384# load/save perl data associated with player->ob objects 687# load/save perl data associated with player->ob objects
385 688
386*on_player_load = sub { 689sub all_objects(@) {
690 @_, map all_objects ($_->inv), @_
691}
692
693# TODO: compatibility cruft, remove when no longer needed
694attach_to_players
695 on_load => sub {
387 my ($ob, $path) = @_; 696 my ($pl, $path) = @_;
388 697
389 for my $o ($ob, $ob->inv) { 698 for my $o (all_objects $pl->ob) {
390 if (my $value = $o->get_ob_key_value ("_perl_data")) { 699 if (my $value = $o->get_ob_key_value ("_perl_data")) {
391 $o->set_ob_key_value ("_perl_data"); 700 $o->set_ob_key_value ("_perl_data");
392 701
393 %$o = %{ Storable::thaw pack "H*", $value }; 702 %$o = %{ Storable::thaw pack "H*", $value };
394 } 703 }
704 }
395 } 705 },
396}; 706;
397
398*on_player_save = sub {
399 my ($ob, $path) = @_;
400
401 $_->set_ob_key_value (_perl_data => unpack "H*", Storable::nfreeze $_)
402 for grep %$_, $ob, $ob->inv;
403};
404 707
405############################################################################# 708#############################################################################
406# core extensions - in perl 709# core extensions - in perl
407 710
408=item cf::player::exists $login 711=item cf::player::exists $login
454} 757}
455 758
456############################################################################# 759#############################################################################
457# map scripting support 760# map scripting support
458 761
459our $safe = new Safe "ext"; 762our $safe = new Safe "safe";
460our $safe_hole = new Safe::Hole; 763our $safe_hole = new Safe::Hole;
461 764
462$SIG{FPE} = 'IGNORE'; 765$SIG{FPE} = 'IGNORE';
463 766
464$safe->permit_only (Opcode::opset qw(:base_core :base_mem :base_orig :base_math sort time)); 767$safe->permit_only (Opcode::opset qw(:base_core :base_mem :base_orig :base_math sort time));
470 ["cf::object::player" => qw(player)], 773 ["cf::object::player" => qw(player)],
471 ["cf::player" => qw(peaceful)], 774 ["cf::player" => qw(peaceful)],
472) { 775) {
473 no strict 'refs'; 776 no strict 'refs';
474 my ($pkg, @funs) = @$_; 777 my ($pkg, @funs) = @$_;
475 *{"ext::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"}) 778 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"})
476 for @funs; 779 for @funs;
477} 780}
478 781
479sub safe_eval($;@) { 782sub safe_eval($;@) {
480 my ($code, %vars) = @_; 783 my ($code, %vars) = @_;
482 my $qcode = $code; 785 my $qcode = $code;
483 $qcode =~ s/"/‟/g; # not allowed in #line filenames 786 $qcode =~ s/"/‟/g; # not allowed in #line filenames
484 $qcode =~ s/\n/\\n/g; 787 $qcode =~ s/\n/\\n/g;
485 788
486 local $_; 789 local $_;
487 local @ext::cf::_safe_eval_args = values %vars; 790 local @safe::cf::_safe_eval_args = values %vars;
488 791
489 $code = 792 my $eval =
490 "do {\n" 793 "do {\n"
491 . "my (" . (join ",", map "\$$_", keys %vars) . ") = \@cf::_safe_eval_args;\n" 794 . "my (" . (join ",", map "\$$_", keys %vars) . ") = \@cf::_safe_eval_args;\n"
492 . "#line 0 \"{$qcode}\"\n" 795 . "#line 0 \"{$qcode}\"\n"
493 . $code 796 . $code
494 . "\n}" 797 . "\n}"
495 ; 798 ;
496 799
497 sub_generation_inc; 800 sub_generation_inc;
498 my @res = wantarray ? $safe->reval ($code) : scalar $safe->reval ($code); 801 my @res = wantarray ? $safe->reval ($eval) : scalar $safe->reval ($eval);
499 sub_generation_inc; 802 sub_generation_inc;
500 803
804 if ($@) {
805 warn "$@";
806 warn "while executing safe code '$code'\n";
807 warn "with arguments " . (join " ", %vars) . "\n";
808 }
809
501 wantarray ? @res : $res[0] 810 wantarray ? @res : $res[0]
502} 811}
812
813=item cf::register_script_function $function => $cb
814
815Register a function that can be called from within map/npc scripts. The
816function should be reasonably secure and should be put into a package name
817like the extension.
818
819Example: register a function that gets called whenever a map script calls
820C<rent::overview>, as used by the C<rent> extension.
821
822 cf::register_script_function "rent::overview" => sub {
823 ...
824 };
825
826=cut
503 827
504sub register_script_function { 828sub register_script_function {
505 my ($fun, $cb) = @_; 829 my ($fun, $cb) = @_;
506 830
507 no strict 'refs'; 831 no strict 'refs';
508 *{"ext::$fun"} = $safe_hole->wrap ($cb); 832 *{"safe::$fun"} = $safe_hole->wrap ($cb);
833}
834
835#############################################################################
836
837=head2 EXTENSION DATABASE SUPPORT
838
839Crossfire maintains a very simple database for extension use. It can
840currently store anything that can be serialised using Storable, which
841excludes objects.
842
843The parameter C<$family> should best start with the name of the extension
844using it, it should be unique.
845
846=over 4
847
848=item $hashref = cf::db_get $family
849
850Return a hashref for use by the extension C<$family>, which can be
851modified. After modifications, you have to call C<cf::db_dirty> or
852C<cf::db_sync>.
853
854=item $value = cf::db_get $family => $key
855
856Returns a single value from the database
857
858=item cf::db_put $family => $hashref
859
860Stores the given family hashref into the database. Updates are delayed, if
861you want the data to be synced to disk immediately, use C<cf::db_sync>.
862
863=item cf::db_put $family => $key => $value
864
865Stores the given C<$value> in the family hash. Updates are delayed, if you
866want the data to be synced to disk immediately, use C<cf::db_sync>.
867
868=item cf::db_dirty
869
870Marks the database as dirty, to be updated at a later time.
871
872=item cf::db_sync
873
874Immediately write the database to disk I<if it is dirty>.
875
876=cut
877
878{
879 my $db;
880 my $path = cf::localdir . "/database.pst";
881
882 sub db_load() {
883 warn "loading database $path\n";#d# remove later
884 $db = stat $path ? Storable::retrieve $path : { };
885 }
886
887 my $pid;
888
889 sub db_save() {
890 warn "saving database $path\n";#d# remove later
891 waitpid $pid, 0 if $pid;
892 if (0 == ($pid = fork)) {
893 $db->{_meta}{version} = 1;
894 Storable::nstore $db, "$path~";
895 rename "$path~", $path;
896 cf::_exit 0 if defined $pid;
897 }
898 }
899
900 my $dirty;
901
902 sub db_sync() {
903 db_save if $dirty;
904 undef $dirty;
905 }
906
907 my $idle = Event->idle (min => $TICK * 2.8, max => 10, repeat => 0, cb => sub {
908 db_sync;
909 });
910
911 sub db_dirty() {
912 $dirty = 1;
913 $idle->start;
914 }
915
916 sub db_get($;$) {
917 @_ >= 2
918 ? $db->{$_[0]}{$_[1]}
919 : ($db->{$_[0]} ||= { })
920 }
921
922 sub db_put($$;$) {
923 if (@_ >= 3) {
924 $db->{$_[0]}{$_[1]} = $_[2];
925 } else {
926 $db->{$_[0]} = $_[1];
927 }
928 db_dirty;
929 }
930
931 attach_global
932 prio => 10000,
933 on_cleanup => sub {
934 db_sync;
935 },
936 ;
937}
938
939#############################################################################
940# the server's main()
941
942sub main {
943 db_load;
944 load_extensions;
945 Event::loop;
509} 946}
510 947
511############################################################################# 948#############################################################################
512# initialisation 949# initialisation
513 950
951sub _perl_reload(&) {
952 my ($msg) = @_;
953
954 $msg->("reloading...");
955
956 eval {
957 # cancel all watchers
958 $_->cancel for Event::all_watchers;
959
960 # unload all extensions
961 for (@exts) {
962 $msg->("unloading <$_>");
963 unload_extension $_;
964 }
965
966 # unload all modules loaded from $LIBDIR
967 while (my ($k, $v) = each %INC) {
968 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
969
970 $msg->("removing <$k>");
971 delete $INC{$k};
972
973 $k =~ s/\.pm$//;
974 $k =~ s/\//::/g;
975
976 if (my $cb = $k->can ("unload_module")) {
977 $cb->();
978 }
979
980 Symbol::delete_package $k;
981 }
982
983 # sync database to disk
984 cf::db_sync;
985
986 # get rid of safe::, as good as possible
987 Symbol::delete_package "safe::$_"
988 for qw(cf::object cf::object::player cf::player cf::map cf::party cf::region);
989
990 # remove register_script_function callbacks
991 # TODO
992
993 # unload cf.pm "a bit"
994 delete $INC{"cf.pm"};
995
996 # don't, removes xs symbols, too,
997 # and global variables created in xs
998 #Symbol::delete_package __PACKAGE__;
999
1000 # reload cf.pm
1001 $msg->("reloading cf.pm");
1002 require cf;
1003
1004 # load database again
1005 cf::db_load;
1006
1007 # load extensions
1008 $msg->("load extensions");
1009 cf::load_extensions;
1010
1011 # reattach attachments to objects
1012 $msg->("reattach");
1013 _global_reattach;
1014 };
1015 $msg->($@) if $@;
1016
1017 $msg->("reloaded");
1018};
1019
1020sub perl_reload() {
1021 _perl_reload {
1022 warn $_[0];
1023 print "$_[0]\n";
1024 };
1025}
1026
1027register_command "perl-reload", 0, sub {
1028 my ($who, $arg) = @_;
1029
1030 if ($who->flag (FLAG_WIZ)) {
1031 _perl_reload {
1032 warn $_[0];
1033 $who->message ($_[0]);
1034 };
1035 }
1036};
1037
514register "<global>", __PACKAGE__; 1038register "<global>", __PACKAGE__;
515 1039
516unshift @INC, $LIBDIR; 1040unshift @INC, $LIBDIR;
517 1041
518load_extensions; 1042$TICK_WATCHER = Event->timer (
1043 prio => 1,
1044 at => $NEXT_TICK || 1,
1045 cb => sub {
1046 cf::server_tick; # one server iteration
1047
1048 my $NOW = Event::time;
1049 $NEXT_TICK += $TICK;
1050
1051 # if we are delayed by four ticks, skip them all
1052 $NEXT_TICK = $NOW if $NOW >= $NEXT_TICK + $TICK * 4;
1053
1054 $TICK_WATCHER->at ($NEXT_TICK);
1055 $TICK_WATCHER->start;
1056 },
1057);
519 1058
5201 10591
521 1060

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines