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.8 by root, Thu Mar 16 21:08:16 2006 UTC vs.
Revision 1.57 by root, Wed Aug 30 11:21:24 2006 UTC

1package cf; 1package cf;
2 2
3use Symbol; 3use Symbol;
4use List::Util; 4use List::Util;
5use Storable; 5use Storable;
6use Opcode;
7use Safe;
8use Safe::Hole;
9
10use Time::HiRes;
11use Event;
12$Event::Eval = 1; # no idea why this is required, but it is
6 13
7use strict; 14use strict;
8 15
16_reload_1;
17
9our %COMMAND; 18our %COMMAND = ();
10our @EVENT; 19our @EVENT;
11our %PROP_TYPE; 20our %PROP_TYPE;
12our %PROP_IDX; 21our %PROP_IDX;
22our $LIBDIR = maps_directory "perl";
23
24our $TICK = MAX_TIME * 1e-6;
25our $TICK_WATCHER;
26our $NEXT_TICK;
13 27
14BEGIN { 28BEGIN {
15 @EVENT = map lc, @EVENT;
16
17 *CORE::GLOBAL::warn = sub { 29 *CORE::GLOBAL::warn = sub {
18 my $msg = join "", @_; 30 my $msg = join "", @_;
19 $msg .= "\n" 31 $msg .= "\n"
20 unless $msg =~ /\n$/; 32 unless $msg =~ /\n$/;
21 33
22 print STDERR "cfperl: $msg"; 34 print STDERR "cfperl: $msg";
23 LOG llevError, "cfperl: $msg"; 35 LOG llevError, "cfperl: $msg";
24 }; 36 };
25} 37}
26 38
39my %ignore_set = (MAP_PROP_PATH => 1); # I hate the plug-in api. Deeply!
40
27# generate property mutators 41# generate property mutators
28sub prop_gen { 42sub prop_gen {
29 my ($prefix, $class) = @_; 43 my ($prefix, $class) = @_;
30 44
31 no strict 'refs'; 45 no strict 'refs';
41 $_[0]->get_property ($type, $idx) 55 $_[0]->get_property ($type, $idx)
42 }; 56 };
43 57
44 *{"$class\::set_$sub"} = sub { 58 *{"$class\::set_$sub"} = sub {
45 $_[0]->set_property ($type, $idx, $_[1]); 59 $_[0]->set_property ($type, $idx, $_[1]);
46 }; 60 } unless $ignore_set{$prop};
47 } 61 }
48} 62}
49 63
50# auto-generate most of the API 64# auto-generate most of the API
51 65
54prop_gen PLAYER_PROP => "cf::object::player"; 68prop_gen PLAYER_PROP => "cf::object::player";
55 69
56prop_gen MAP_PROP => "cf::map"; 70prop_gen MAP_PROP => "cf::map";
57prop_gen ARCH_PROP => "cf::arch"; 71prop_gen ARCH_PROP => "cf::arch";
58 72
59# guessed hierarchies 73@safe::cf::object::player::ISA = @cf::object::player::ISA = 'cf::object';
60 74
61@cf::object::player::ISA = 'cf::object'; 75# we bless all objects into (empty) derived classes to force a method lookup
62@cf::object::map::ISA = 'cf::object'; 76# within the Safe compartment.
77for my $pkg (qw(cf::object cf::object::player cf::player cf::map cf::party cf::region cf::arch cf::living)) {
78 no strict 'refs';
79 @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg;
80}
81
82$Event::DIED = sub {
83 warn "error in event callback: @_";
84};
63 85
64my %ext_pkg; 86my %ext_pkg;
65my @exts; 87my @exts;
66my @hook; 88my @hook;
67my %command; 89my %command;
90my %extcmd;
91
92#############################################################################
93# utility functions
94
95use JSON::Syck (); # TODO# replace by JSON::PC once working
96
97sub from_json($) {
98 $JSON::Syck::ImplicitUnicode = 1; # work around JSON::Syck bugs
99 JSON::Syck::Load $_[0]
100}
101
102sub to_json($) {
103 $JSON::Syck::ImplicitUnicode = 0; # work around JSON::Syck bugs
104 JSON::Syck::Dump $_[0]
105}
106
107#############################################################################
108# "new" plug-in system
109
110=head3 EVENTS AND OBJECT ATTACHMENTS
111
112=over 4
113
114=item $object->attach ($attachment, key => $value...)
115
116=item $object->detach ($attachment)
117
118Attach/detach a pre-registered attachment to an object.
119
120=item $player->attach ($attachment, key => $value...)
121
122=item $player->detach ($attachment)
123
124Attach/detach a pre-registered attachment to a player.
125
126=item $map->attach ($attachment, key => $value...)
127
128=item $map->detach ($attachment)
129
130Attach/detach a pre-registered attachment to a map.
131
132=item $bool = $object->attached ($name)
133
134=item $bool = $player->attached ($name)
135
136=item $bool = $map->attached ($name)
137
138Checks wether the named attachment is currently attached to the object.
139
140=item cf::attach_global ...
141
142Attach handlers for global events.
143
144This and all following C<attach_*>-functions expect any number of the
145following handler/hook descriptions:
146
147=over 4
148
149=item prio => $number
150
151Set the priority for all following handlers/hooks (unless overwritten
152by another C<prio> setting). Lower priority handlers get executed
153earlier. The default priority is C<0>, and many built-in handlers are
154registered at priority C<-1000>, so lower priorities should not be used
155unless you know what you are doing.
156
157=item on_I<event> => \&cb
158
159Call the given code reference whenever the named event happens (event is
160something like C<instantiate>, C<apply>, C<use_skill> and so on, and which
161handlers are recognised generally depends on the type of object these
162handlers attach to).
163
164See F<include/eventinc.h> for the full list of events supported, and their
165class.
166
167=item package => package::
168
169Look for sub functions of the name C<< on_I<event> >> in the given
170package and register them. Only handlers for eevents supported by the
171object/class are recognised.
172
173=back
174
175=item cf::attach_to_type $object_type, $subtype, ...
176
177Attach handlers for a specific object type (e.g. TRANSPORT) and
178subtype. If C<$subtype> is zero or undef, matches all objects of the given
179type.
180
181=item cf::attach_to_objects ...
182
183Attach handlers to all objects. Do not use this except for debugging or
184very rare events, as handlers are (obviously) called for I<all> objects in
185the game.
186
187=item cf::attach_to_players ...
188
189Attach handlers to all players.
190
191=item cf::attach_to_maps ...
192
193Attach handlers to all maps.
194
195=item cf:register_attachment $name, ...
196
197Register an attachment by name through which objects can refer to this
198attachment.
199
200=item cf:register_player_attachment $name, ...
201
202Register an attachment by name through which players can refer to this
203attachment.
204
205=item cf:register_map_attachment $name, ...
206
207Register an attachment by name through which maps can refer to this
208attachment.
209
210=cut
211
212# the following variables are defined in .xs and must not be re-created
213our @CB_GLOBAL = (); # registry for all global events
214our @CB_OBJECT = (); # all objects (should not be used except in emergency)
215our @CB_PLAYER = ();
216our @CB_TYPE = (); # registry for type (cf-object class) based events
217our @CB_MAP = ();
218
219my %attachment;
220
221sub _attach_cb($\%$$$) {
222 my ($registry, $undo, $event, $prio, $cb) = @_;
223
224 use sort 'stable';
225
226 $cb = [$prio, $cb];
227
228 @{$registry->[$event]} = sort
229 { $a->[0] cmp $b->[0] }
230 @{$registry->[$event] || []}, $cb;
231
232 push @{$undo->{cb}}, [$event, $cb];
233}
234
235# attach handles attaching event callbacks
236# the only thing the caller has to do is pass the correct
237# registry (== where the callback attaches to).
238sub _attach(\@$@) {
239 my ($registry, $klass, @arg) = @_;
240
241 my $prio = 0;
242
243 my %undo = (
244 registry => $registry,
245 cb => [],
246 );
247
248 my %cb_id = map +("on_" . lc $EVENT[$_][0], $_) , grep $EVENT[$_][1] == $klass, 0 .. $#EVENT;
249
250 while (@arg) {
251 my $type = shift @arg;
252
253 if ($type eq "prio") {
254 $prio = shift @arg;
255
256 } elsif ($type eq "package") {
257 my $pkg = shift @arg;
258
259 while (my ($name, $id) = each %cb_id) {
260 if (my $cb = $pkg->can ($name)) {
261 _attach_cb $registry, %undo, $id, $prio, $cb;
262 }
263 }
264
265 } elsif (exists $cb_id{$type}) {
266 _attach_cb $registry, %undo, $cb_id{$type}, $prio, shift @arg;
267
268 } elsif (ref $type) {
269 warn "attaching objects not supported, ignoring.\n";
270
271 } else {
272 shift @arg;
273 warn "attach argument '$type' not supported, ignoring.\n";
274 }
275 }
276
277 \%undo
278}
279
280sub _attach_attachment {
281 my ($obj, $name, %arg) = @_;
282
283 return if exists $obj->{_attachment}{$name};
284
285 my $res;
286
287 if (my $attach = $attachment{$name}) {
288 my $registry = $obj->registry;
289
290 for (@$attach) {
291 my ($klass, @attach) = @$_;
292 $res = _attach @$registry, $klass, @attach;
293 }
294
295 $obj->{$name} = \%arg;
296 } else {
297 warn "object uses attachment '$name' that is not available, postponing.\n";
298 }
299
300 $obj->{_attachment}{$name} = undef;
301
302 $res->{attachment} = $name;
303 $res
304}
305
306*cf::object::attach =
307*cf::player::attach =
308*cf::map::attach = sub {
309 my ($obj, $name, %arg) = @_;
310
311 _attach_attachment $obj, $name, %arg;
312};
313
314# all those should be optimised
315*cf::object::detach =
316*cf::player::detach =
317*cf::map::detach = sub {
318 my ($obj, $name) = @_;
319
320 delete $obj->{_attachment}{$name};
321 reattach ($obj);
322};
323
324*cf::object::attached =
325*cf::player::attached =
326*cf::map::attached = sub {
327 my ($obj, $name) = @_;
328
329 exists $obj->{_attachment}{$name}
330};
331
332sub attach_global {
333 _attach @CB_GLOBAL, KLASS_GLOBAL, @_
334}
335
336sub attach_to_type {
337 my $type = shift;
338 my $subtype = shift;
339
340 _attach @{$CB_TYPE[$type + $subtype * NUM_SUBTYPES]}, KLASS_OBJECT, @_
341}
342
343sub attach_to_objects {
344 _attach @CB_OBJECT, KLASS_OBJECT, @_
345}
346
347sub attach_to_players {
348 _attach @CB_PLAYER, KLASS_PLAYER, @_
349}
350
351sub attach_to_maps {
352 _attach @CB_MAP, KLASS_MAP, @_
353}
354
355sub register_attachment {
356 my $name = shift;
357
358 $attachment{$name} = [[KLASS_OBJECT, @_]];
359}
360
361sub register_player_attachment {
362 my $name = shift;
363
364 $attachment{$name} = [[KLASS_PLAYER, @_]];
365}
366
367sub register_map_attachment {
368 my $name = shift;
369
370 $attachment{$name} = [[KLASS_MAP, @_]];
371}
372
373our $override;
374our @invoke_results = (); # referenced from .xs code. TODO: play tricks with reify and mortals?
375
376sub override {
377 $override = 1;
378 @invoke_results = ();
379}
380
381sub do_invoke {
382 my $event = shift;
383 my $callbacks = shift;
384
385 @invoke_results = ();
386
387 local $override;
388
389 for (@$callbacks) {
390 eval { &{$_->[1]} };
391
392 if ($@) {
393 warn "$@";
394 warn "... while processing $EVENT[$event][0] event, skipping processing altogether.\n";
395 override;
396 }
397
398 return 1 if $override;
399 }
400
401 0
402}
403
404=item $bool = cf::invoke EVENT_GLOBAL_XXX, ...
405
406=item $bool = $object->invoke (EVENT_OBJECT_XXX, ...)
407
408=item $bool = $player->invoke (EVENT_PLAYER_XXX, ...)
409
410=item $bool = $map->invoke (EVENT_MAP_XXX, ...)
411
412Generate a global/object/player/map-specific event with the given arguments.
413
414This API is preliminary (most likely, the EVENT_KLASS_xxx prefix will be
415removed in future versions), and there is no public API to access override
416results (if you must, access C<@cf::invoke_results> directly).
417
418=back
419
420=head2 methods valid for all pointers
421
422=over 4
423
424=item $object->valid
425
426=item $player->valid
427
428=item $map->valid
429
430Just because you have a perl object does not mean that the corresponding
431C-level object still exists. If you try to access an object that has no
432valid C counterpart anymore you get an exception at runtime. This method
433can be used to test for existence of the C object part without causing an
434exception.
435
436=back
437
438=cut
439
440*cf::object::valid =
441*cf::player::valid =
442*cf::map::valid = \&cf::_valid;
443
444#############################################################################
445# object support
446
447sub instantiate {
448 my ($obj, $data) = @_;
449
450 $data = from_json $data;
451
452 for (@$data) {
453 my ($name, $args) = @$_;
454
455 $obj->attach ($name, %{$args || {} });
456 }
457}
458
459# basically do the same as instantiate, without calling instantiate
460sub reattach {
461 my ($obj) = @_;
462 my $registry = $obj->registry;
463
464 @$registry = ();
465
466 delete $obj->{_attachment} unless scalar keys %{ $obj->{_attachment} || {} };
467
468 for my $name (keys %{ $obj->{_attachment} || {} }) {
469 if (my $attach = $attachment{$name}) {
470 for (@$attach) {
471 my ($klass, @attach) = @$_;
472 _attach @$registry, $klass, @attach;
473 }
474 } else {
475 warn "object uses attachment '$name' that is not available, postponing.\n";
476 }
477 }
478}
479
480sub object_freezer_save {
481 my ($filename, $objs) = @_;
482
483 if (@$objs) {
484 open my $fh, ">:raw", "$filename.pst~";
485 syswrite $fh, Storable::nfreeze { version => 1, objs => $objs };
486 close $fh;
487 unlink "$filename.cfperl";
488 chmod SAVE_MODE, "$filename.pst~";
489 rename "$filename.pst~", "$filename.pst";
490 } else {
491 unlink "$filename.pst";
492 }
493
494 chmod SAVE_MODE, "$filename~";
495 rename "$filename~", $filename;
496}
497
498sub object_thawer_load {
499 my ($filename) = @_;
500
501 open my $fh, "<:raw:perlio", "$filename.pst"
502 or return;
503
504 eval { local $/; (Storable::thaw <$fh>)->{objs} }
505}
506
507attach_to_objects
508 prio => -1000000,
509 on_clone => sub {
510 my ($src, $dst) = @_;
511
512 @{$dst->registry} = @{$src->registry};
513
514 %$dst = %$src;
515
516 %{$dst->{_attachment}} = %{$src->{_attachment}}
517 if exists $src->{_attachment};
518 },
519;
520
521#############################################################################
522# old plug-in events
68 523
69sub inject_event { 524sub inject_event {
70 my ($data) = @_; 525 my $extension = shift;
526 my $event_code = shift;
71 527
72 my $cb = $hook[$data->{event_code}]{$data->{extension}} 528 my $cb = $hook[$event_code]{$extension}
73 or return; 529 or return;
74 530
75 $cb->($data) 531 &$cb
76} 532}
77 533
78sub inject_global_event { 534sub inject_global_event {
79 my ($data) = @_; 535 my $event = shift;
80 536
81 my $cb = $hook[$data->{event_code}] 537 my $cb = $hook[$event]
82 or return; 538 or return;
83 539
84 $_->($data) for values %$cb; 540 List::Util::max map &$_, values %$cb
85
86 ()
87} 541}
88 542
89sub inject_command { 543sub inject_command {
90 my ($name, $obj, $params) = @_; 544 my ($name, $obj, $params) = @_;
91 545
98 552
99sub register_command { 553sub register_command {
100 my ($name, $time, $cb) = @_; 554 my ($name, $time, $cb) = @_;
101 555
102 my $caller = caller; 556 my $caller = caller;
103
104 warn "registering command '$name/$time' to '$caller'"; 557 #warn "registering command '$name/$time' to '$caller'";
105 558
106 push @{ $command{$name} }, [$time, $cb, $caller]; 559 push @{ $command{$name} }, [$time, $cb, $caller];
107 $COMMAND{"$name\000"} = List::Util::max map $_->[0], @{ $command{$name} }; 560 $COMMAND{"$name\000"} = List::Util::max map $_->[0], @{ $command{$name} };
108} 561}
109 562
563sub register_extcmd {
564 my ($name, $cb) = @_;
565
566 my $caller = caller;
567 #warn "registering extcmd '$name' to '$caller'";
568
569 $extcmd{$name} = [$cb, $caller];
570}
571
110sub register { 572sub register {
111 my ($base, $pkg) = @_; 573 my ($base, $pkg) = @_;
112 574
113 for my $idx (0 .. $#EVENT) { 575 #TODO
114 if (my $ref = $pkg->can ("on_$EVENT[$idx]")) {
115 warn "registering $EVENT[$idx] hook to '$pkg'\n";
116 $hook[$idx]{$base} = $ref;
117 }
118 }
119} 576}
120 577
121sub load_extension { 578sub load_extension {
122 my ($path) = @_; 579 my ($path) = @_;
123 580
124 $path =~ /([^\/\\]+)\.ext$/ or die "$path"; 581 $path =~ /([^\/\\]+)\.ext$/ or die "$path";
125 my $base = $1; 582 my $base = $1;
126 my $pkg = $1; 583 my $pkg = $1;
127 $pkg =~ s/[^[:word:]]/_/g; 584 $pkg =~ s/[^[:word:]]/_/g;
128 $pkg = "cf::ext::$pkg"; 585 $pkg = "ext::$pkg";
129 586
130 warn "loading '$path' into '$pkg'\n"; 587 warn "loading '$path' into '$pkg'\n";
131 588
132 open my $fh, "<:utf8", $path 589 open my $fh, "<:utf8", $path
133 or die "$path: $!"; 590 or die "$path: $!";
143 600
144 push @exts, $pkg; 601 push @exts, $pkg;
145 $ext_pkg{$base} = $pkg; 602 $ext_pkg{$base} = $pkg;
146 603
147# no strict 'refs'; 604# no strict 'refs';
148# @{"$pkg\::ISA"} = cf::ext::; 605# @{"$pkg\::ISA"} = ext::;
149 606
150 register $base, $pkg; 607 register $base, $pkg;
151} 608}
152 609
153sub unload_extension { 610sub unload_extension {
154 my ($pkg) = @_; 611 my ($pkg) = @_;
155 612
156 warn "removing extension $pkg\n"; 613 warn "removing extension $pkg\n";
157 614
158 # remove hooks 615 # remove hooks
616 #TODO
159 for my $idx (0 .. $#EVENT) { 617# for my $idx (0 .. $#PLUGIN_EVENT) {
160 delete $hook[$idx]{$pkg}; 618# delete $hook[$idx]{$pkg};
161 } 619# }
162 620
163 # remove commands 621 # remove commands
164 for my $name (keys %command) { 622 for my $name (keys %command) {
165 my @cb = grep $_->[2] ne $pkg, @{ $command{$name} }; 623 my @cb = grep $_->[2] ne $pkg, @{ $command{$name} };
166 624
171 delete $command{$name}; 629 delete $command{$name};
172 delete $COMMAND{"$name\000"}; 630 delete $COMMAND{"$name\000"};
173 } 631 }
174 } 632 }
175 633
634 # remove extcmds
635 for my $name (grep $extcmd{$_}[1] eq $pkg, keys %extcmd) {
636 delete $extcmd{$name};
637 }
638
639 if (my $cb = $pkg->can ("unload")) {
640 eval {
641 $cb->($pkg);
642 1
643 } or warn "$pkg unloaded, but with errors: $@";
644 }
645
176 Symbol::delete_package $pkg; 646 Symbol::delete_package $pkg;
177} 647}
178 648
179sub load_extensions { 649sub load_extensions {
180 my $LIBDIR = maps_directory "perl"; 650 my $LIBDIR = maps_directory "perl";
186 1 656 1
187 } or warn "$ext not loaded: $@"; 657 } or warn "$ext not loaded: $@";
188 } 658 }
189} 659}
190 660
661sub _perl_reload(&) {
662 my ($msg) = @_;
663
664 $msg->("reloading...");
665
666 eval {
667 # 1. cancel all watchers
668 $_->cancel for Event::all_watchers;
669
670 # 2. unload all extensions
671 for (@exts) {
672 $msg->("unloading <$_>");
673 unload_extension $_;
674 }
675
676 # 3. unload all modules loaded from $LIBDIR
677 while (my ($k, $v) = each %INC) {
678 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
679
680 $msg->("removing <$k>");
681 delete $INC{$k};
682
683 $k =~ s/\.pm$//;
684 $k =~ s/\//::/g;
685
686 if (my $cb = $k->can ("unload_module")) {
687 $cb->();
688 }
689
690 Symbol::delete_package $k;
691 }
692
693 # 4. get rid of safe::, as good as possible
694 Symbol::delete_package "safe::$_"
695 for qw(cf::object cf::object::player cf::player cf::map cf::party cf::region);
696
697 # 5. remove register_script_function callbacks
698 # TODO
699
700 # 6. unload cf.pm "a bit"
701 delete $INC{"cf.pm"};
702
703 # don't, removes xs symbols, too,
704 # and global variables created in xs
705 #Symbol::delete_package __PACKAGE__;
706
707 # 7. reload cf.pm
708 $msg->("reloading cf.pm");
709 require cf;
710 };
711 $msg->($@) if $@;
712
713 $msg->("reloaded");
714};
715
716sub perl_reload() {
717 _perl_reload {
718 warn $_[0];
719 print "$_[0]\n";
720 };
721}
722
191register_command "perl-reload", 0, sub { 723register_command "perl-reload", 0, sub {
192 my ($who, $arg) = @_; 724 my ($who, $arg) = @_;
193 725
194 if ($who->flag (FLAG_WIZ)) { 726 if ($who->flag (FLAG_WIZ)) {
195 $who->message ("reloading..."); 727 _perl_reload {
196 728 warn $_[0];
197 warn "reloading...\n"; 729 $who->message ($_[0]);
198 eval {
199 unload_extension $_ for @exts;
200 delete $INC{"cf.pm"};
201
202 # don't, removes xs symbols, too
203 #Symbol::delete_package $pkg;
204
205 require cf;
206 }; 730 };
207 warn $@ if $@;
208 $who->message ($@) if $@;
209 warn "reloaded\n";
210
211 $who->message ("reloaded");
212 } else {
213 $who->message ("Intruder Alert!");
214 } 731 }
215}; 732};
216 733
217############################################################################# 734#############################################################################
735# extcmd framework, basically convert ext <msg>
736# into pkg::->on_extcmd_arg1 (...) while shortcutting a few
737
738attach_to_players
739 on_extcmd => sub {
740 my ($pl, $buf) = @_;
741
742 my $msg = eval { from_json $buf };
743
744 if (ref $msg) {
745 if (my $cb = $extcmd{$msg->{msgtype}}) {
746 if (my %reply = $cb->[0]->($pl, $msg)) {
747 $pl->ext_reply ($msg->{msgid}, %reply);
748 }
749 }
750 } else {
751 warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n";
752 }
753
754 cf::override;
755 },
756;
757
758#############################################################################
218# load/save/clean perl data associated with a map 759# load/save/clean perl data associated with a map
219 760
220*on_mapclean = sub { 761*cf::mapsupport::on_clean = sub {
221 my $map = shift->{map}; 762 my ($map) = @_;
222 763
223 my $path = $map->tmpname; 764 my $path = $map->tmpname;
224 defined $path or return; 765 defined $path or return;
225 766
226 unlink "$path.cfperl"; 767 unlink "$path.pst";
227}; 768};
228 769
229*on_mapin = 770# old style persistent data, TODO: remove #d#
230*on_mapload = sub { 771*cf::mapsupport::on_swapin = sub {
231 my $map = shift->{map}; 772 my ($map) = @_;
232 773
233 my $path = $map->tmpname; 774 my $path = $map->tmpname;
234 $path = $map->path unless defined $path; 775 $path = $map->path unless defined $path;
235 776
236 open my $fh, "<:raw", "$path.cfperl" 777 open my $fh, "<:raw", "$path.cfperl"
240 781
241 $data->{version} <= 1 782 $data->{version} <= 1
242 or return; # too new 783 or return; # too new
243 784
244 $map->_set_obs ($data->{obs}); 785 $map->_set_obs ($data->{obs});
786 $map->invoke (EVENT_MAP_UPGRADE);
245}; 787};
246 788
247*on_mapout = sub { 789attach_to_maps prio => -10000, package => cf::mapsupport::;
248 my $map = shift->{map};
249 790
250 my $path = $map->tmpname; 791#############################################################################
251 $path = $map->path unless defined $path; 792# load/save perl data associated with player->ob objects
252 793
253 my $obs = $map->_get_obs; 794sub all_objects(@) {
795 @_, map all_objects ($_->inv), @_
796}
254 797
255 if (defined $obs) { 798attach_to_players
256 open my $fh, ">:raw", "$path.cfperl" 799 on_load => sub {
257 or die "$path.cfperl: $!"; 800 my ($pl, $path) = @_;
258 801
259 stat $path; 802 for my $o (all_objects $pl->ob) {
803 if (my $value = $o->get_ob_key_value ("_perl_data")) {
804 $o->set_ob_key_value ("_perl_data");
260 805
261 print $fh Storable::nfreeze { 806 %$o = %{ Storable::thaw pack "H*", $value };
262 size => (stat _)[7], 807 }
263 time => (stat _)[9],
264 version => 1,
265 obs => $obs,
266 }; 808 }
809 },
810;
267 811
268 chmod SAVE_MODE, "$path.cfperl"; # very racy, but cf-compatible *g* 812#############################################################################
813# core extensions - in perl
814
815=item cf::player::exists $login
816
817Returns true when the given account exists.
818
819=cut
820
821sub cf::player::exists($) {
822 cf::player::find $_[0]
823 or -f sprintf "%s/%s/%s/%s.pl", cf::localdir, cf::playerdir, ($_[0]) x 2;
824}
825
826=item $player->reply ($npc, $msg[, $flags])
827
828Sends a message to the player, as if the npc C<$npc> replied. C<$npc>
829can be C<undef>. Does the right thing when the player is currently in a
830dialogue with the given NPC character.
831
832=cut
833
834# rough implementation of a future "reply" method that works
835# with dialog boxes.
836sub cf::object::player::reply($$$;$) {
837 my ($self, $npc, $msg, $flags) = @_;
838
839 $flags = cf::NDI_BROWN | cf::NDI_UNIQUE unless @_ >= 4;
840
841 if ($self->{record_replies}) {
842 push @{ $self->{record_replies} }, [$npc, $msg, $flags];
269 } else { 843 } else {
270 unlink "$path.cfperl"; 844 $msg = $npc->name . " says: $msg" if $npc;
845 $self->message ($msg, $flags);
846 }
847}
848
849=item $player->ext_reply ($msgid, $msgtype, %msg)
850
851Sends an ext reply to the player.
852
853=cut
854
855sub cf::player::ext_reply($$$%) {
856 my ($self, $id, %msg) = @_;
857
858 $msg{msgid} = $id;
859
860 $self->send ("ext " . to_json \%msg);
861}
862
863#############################################################################
864# map scripting support
865
866our $safe = new Safe "safe";
867our $safe_hole = new Safe::Hole;
868
869$SIG{FPE} = 'IGNORE';
870
871$safe->permit_only (Opcode::opset qw(:base_core :base_mem :base_orig :base_math sort time));
872
873# here we export the classes and methods available to script code
874
875for (
876 ["cf::object" => qw(contr pay_amount pay_player)],
877 ["cf::object::player" => qw(player)],
878 ["cf::player" => qw(peaceful)],
879) {
880 no strict 'refs';
881 my ($pkg, @funs) = @$_;
882 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"})
883 for @funs;
884}
885
886sub safe_eval($;@) {
887 my ($code, %vars) = @_;
888
889 my $qcode = $code;
890 $qcode =~ s/"/‟/g; # not allowed in #line filenames
891 $qcode =~ s/\n/\\n/g;
892
893 local $_;
894 local @safe::cf::_safe_eval_args = values %vars;
895
896 my $eval =
897 "do {\n"
898 . "my (" . (join ",", map "\$$_", keys %vars) . ") = \@cf::_safe_eval_args;\n"
899 . "#line 0 \"{$qcode}\"\n"
900 . $code
901 . "\n}"
271 } 902 ;
272};
273 903
274############################################################################# 904 sub_generation_inc;
275# load/save perl data associated with player->ob objects 905 my @res = wantarray ? $safe->reval ($eval) : scalar $safe->reval ($eval);
906 sub_generation_inc;
276 907
277*on_player_load = sub { 908 if ($@) {
278 my ($event) = @_; 909 warn "$@";
279 my $path = $event->{message}; 910 warn "while executing safe code '$code'\n";
280 my $ob = $event->{who}; 911 warn "with arguments " . (join " ", %vars) . "\n";
281
282 open my $fh, "<:raw", "$path.cfperl"
283 or return; # no perl data
284
285 my $data = Storable::thaw do { local $/; <$fh> };
286
287 $data->{version} <= 1
288 or return; # too new
289
290 %$ob = %{$data->{ob}};
291};
292
293*on_player_save = sub {
294 my ($event) = @_;
295 my $path = $event->{message};
296 my $ob = $event->{who};
297
298 if (keys %$ob) {
299 open my $fh, ">:raw", "$path.cfperl"
300 or die "$path.cfperl: $!";
301
302 stat $path;
303
304 print $fh Storable::nfreeze {
305 size => (stat _)[7],
306 time => (stat _)[9],
307 version => 1,
308 ob => $ob,
309 };
310
311 chmod SAVE_MODE, "$path.cfperl"; # very racy, but cf-compatible *g*
312 } else {
313 unlink "$path.cfperl";
314 } 912 }
315}; 913
914 wantarray ? @res : $res[0]
915}
916
917sub register_script_function {
918 my ($fun, $cb) = @_;
919
920 no strict 'refs';
921 *{"safe::$fun"} = $safe_hole->wrap ($cb);
922}
923
924#############################################################################
925# the server's main()
926
927sub main {
928 Event::loop;
929}
930
931#############################################################################
932# initialisation
316 933
317register "<global>", __PACKAGE__; 934register "<global>", __PACKAGE__;
318 935
936unshift @INC, $LIBDIR;
937
319load_extensions; 938load_extensions;
320 939
940$TICK_WATCHER = Event->timer (
941 prio => 1,
942 at => $NEXT_TICK || 1,
943 cb => sub {
944 cf::server_tick; # one server iteration
945
946 my $NOW = Event::time;
947 $NEXT_TICK += $TICK;
948
949 # if we are delayed by four ticks, skip them all
950 $NEXT_TICK = $NOW if $NOW >= $NEXT_TICK + $TICK * 4;
951
952 $TICK_WATCHER->at ($NEXT_TICK);
953 $TICK_WATCHER->start;
954 },
955);
956
957_reload_2;
958
3211 9591
322 960

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines