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.26 by root, Thu Jul 20 22:03:36 2006 UTC vs.
Revision 1.59 by root, Wed Aug 30 16:30:37 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_reload_1;
17
15our %COMMAND; 18our %COMMAND = ();
16our @EVENT; 19our @EVENT;
17our %PROP_TYPE; 20our %PROP_TYPE;
18our %PROP_IDX; 21our %PROP_IDX;
22our $LIBDIR = maps_directory "perl";
23
24our $TICK = MAX_TIME * 1e-6;
25our $TICK_WATCHER;
26our $NEXT_TICK;
19 27
20BEGIN { 28BEGIN {
21 @EVENT = map lc, @EVENT;
22
23 *CORE::GLOBAL::warn = sub { 29 *CORE::GLOBAL::warn = sub {
24 my $msg = join "", @_; 30 my $msg = join "", @_;
25 $msg .= "\n" 31 $msg .= "\n"
26 unless $msg =~ /\n$/; 32 unless $msg =~ /\n$/;
27 33
62prop_gen PLAYER_PROP => "cf::object::player"; 68prop_gen PLAYER_PROP => "cf::object::player";
63 69
64prop_gen MAP_PROP => "cf::map"; 70prop_gen MAP_PROP => "cf::map";
65prop_gen ARCH_PROP => "cf::arch"; 71prop_gen ARCH_PROP => "cf::arch";
66 72
67# guessed hierarchies
68
69@ext::cf::object::player::ISA = @cf::object::player::ISA = 'cf::object'; 73@safe::cf::object::player::ISA = @cf::object::player::ISA = 'cf::object';
70@ext::cf::object::map::ISA = @cf::object::map::ISA = 'cf::object';
71 74
72# we bless all objects into derived classes to force a method lookup 75# we bless all objects into (empty) derived classes to force a method lookup
73# within the Safe compartment. 76# within the Safe compartment.
74for my $pkg (qw(cf::object cf::object::map cf::object::player cf::player cf::map cf::party cf::region)) { 77for my $pkg (qw(cf::object cf::object::player cf::player cf::map cf::party cf::region cf::arch cf::living)) {
75 no strict 'refs'; 78 no strict 'refs';
76 @{"ext::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg; 79 @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg;
77} 80}
78 81
79$Event::DIED = sub { 82$Event::DIED = sub {
80 warn "error in event callback: @_"; 83 warn "error in event callback: @_";
81}; 84};
84my @exts; 87my @exts;
85my @hook; 88my @hook;
86my %command; 89my %command;
87my %extcmd; 90my %extcmd;
88 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, $rdata, $objs) = @_;
482
483 if (open my $fh, ">:raw", "$filename~") {
484 chmod SAVE_MODE, $fh;
485 syswrite $fh, $$rdata;
486 close $fh;
487
488 if (@$objs && open my $fh, ">:raw", "$filename.pst~") {
489 chmod SAVE_MODE, $fh;
490 syswrite $fh, Storable::nfreeze { version => 1, objs => $objs };
491 close $fh;
492 rename "$filename.pst~", "$filename.pst";
493 } else {
494 unlink "$filename.pst";
495 }
496
497 rename "$filename~", $filename;
498 } else {
499 warn "FATAL: $filename~: $!\n";
500 }
501}
502
503sub object_thawer_load {
504 my ($filename) = @_;
505
506 open my $fh, "<:raw:perlio", "$filename.pst"
507 or return;
508
509 eval { local $/; (Storable::thaw <$fh>)->{objs} }
510}
511
512attach_to_objects
513 prio => -1000000,
514 on_clone => sub {
515 my ($src, $dst) = @_;
516
517 @{$dst->registry} = @{$src->registry};
518
519 %$dst = %$src;
520
521 %{$dst->{_attachment}} = %{$src->{_attachment}}
522 if exists $src->{_attachment};
523 },
524;
525
526#############################################################################
527# old plug-in events
528
89sub inject_event { 529sub inject_event {
90 my $extension = shift; 530 my $extension = shift;
91 my $event_code = shift; 531 my $event_code = shift;
92 532
93 my $cb = $hook[$event_code]{$extension} 533 my $cb = $hook[$event_code]{$extension}
135} 575}
136 576
137sub register { 577sub register {
138 my ($base, $pkg) = @_; 578 my ($base, $pkg) = @_;
139 579
140 for my $idx (0 .. $#EVENT) { 580 #TODO
141 if (my $ref = $pkg->can ("on_$EVENT[$idx]")) {
142 #warn "registering $EVENT[$idx] hook to '$pkg'\n";
143 $hook[$idx]{$base} = $ref;
144 }
145 }
146} 581}
147 582
148sub load_extension { 583sub load_extension {
149 my ($path) = @_; 584 my ($path) = @_;
150 585
151 $path =~ /([^\/\\]+)\.ext$/ or die "$path"; 586 $path =~ /([^\/\\]+)\.ext$/ or die "$path";
152 my $base = $1; 587 my $base = $1;
153 my $pkg = $1; 588 my $pkg = $1;
154 $pkg =~ s/[^[:word:]]/_/g; 589 $pkg =~ s/[^[:word:]]/_/g;
155 $pkg = "cf::ext::$pkg"; 590 $pkg = "ext::$pkg";
156 591
157 warn "loading '$path' into '$pkg'\n"; 592 warn "loading '$path' into '$pkg'\n";
158 593
159 open my $fh, "<:utf8", $path 594 open my $fh, "<:utf8", $path
160 or die "$path: $!"; 595 or die "$path: $!";
180sub unload_extension { 615sub unload_extension {
181 my ($pkg) = @_; 616 my ($pkg) = @_;
182 617
183 warn "removing extension $pkg\n"; 618 warn "removing extension $pkg\n";
184 619
185 if (my $cb = $pkg->can ("on_unload")) {
186 $cb->($pkg);
187 }
188
189 # remove hooks 620 # remove hooks
621 #TODO
190 for my $idx (0 .. $#EVENT) { 622# for my $idx (0 .. $#PLUGIN_EVENT) {
191 delete $hook[$idx]{$pkg}; 623# delete $hook[$idx]{$pkg};
192 } 624# }
193 625
194 # remove commands 626 # remove commands
195 for my $name (keys %command) { 627 for my $name (keys %command) {
196 my @cb = grep $_->[2] ne $pkg, @{ $command{$name} }; 628 my @cb = grep $_->[2] ne $pkg, @{ $command{$name} };
197 629
207 # remove extcmds 639 # remove extcmds
208 for my $name (grep $extcmd{$_}[1] eq $pkg, keys %extcmd) { 640 for my $name (grep $extcmd{$_}[1] eq $pkg, keys %extcmd) {
209 delete $extcmd{$name}; 641 delete $extcmd{$name};
210 } 642 }
211 643
644 if (my $cb = $pkg->can ("unload")) {
645 eval {
646 $cb->($pkg);
647 1
648 } or warn "$pkg unloaded, but with errors: $@";
649 }
650
212 Symbol::delete_package $pkg; 651 Symbol::delete_package $pkg;
213} 652}
214 653
215sub load_extensions { 654sub load_extensions {
216 my $LIBDIR = maps_directory "perl"; 655 my $LIBDIR = maps_directory "perl";
222 1 661 1
223 } or warn "$ext not loaded: $@"; 662 } or warn "$ext not loaded: $@";
224 } 663 }
225} 664}
226 665
666sub _perl_reload(&) {
667 my ($msg) = @_;
668
669 $msg->("reloading...");
670
671 eval {
672 # 1. cancel all watchers
673 $_->cancel for Event::all_watchers;
674
675 # 2. unload all extensions
676 for (@exts) {
677 $msg->("unloading <$_>");
678 unload_extension $_;
679 }
680
681 # 3. unload all modules loaded from $LIBDIR
682 while (my ($k, $v) = each %INC) {
683 next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/;
684
685 $msg->("removing <$k>");
686 delete $INC{$k};
687
688 $k =~ s/\.pm$//;
689 $k =~ s/\//::/g;
690
691 if (my $cb = $k->can ("unload_module")) {
692 $cb->();
693 }
694
695 Symbol::delete_package $k;
696 }
697
698 # 4. get rid of safe::, as good as possible
699 Symbol::delete_package "safe::$_"
700 for qw(cf::object cf::object::player cf::player cf::map cf::party cf::region);
701
702 # 5. remove register_script_function callbacks
703 # TODO
704
705 # 6. unload cf.pm "a bit"
706 delete $INC{"cf.pm"};
707
708 # don't, removes xs symbols, too,
709 # and global variables created in xs
710 #Symbol::delete_package __PACKAGE__;
711
712 # 7. reload cf.pm
713 $msg->("reloading cf.pm");
714 require cf;
715 };
716 $msg->($@) if $@;
717
718 $msg->("reloaded");
719};
720
721sub perl_reload() {
722 _perl_reload {
723 warn $_[0];
724 print "$_[0]\n";
725 };
726}
727
227register_command "perl-reload", 0, sub { 728register_command "perl-reload", 0, sub {
228 my ($who, $arg) = @_; 729 my ($who, $arg) = @_;
229 730
230 if ($who->flag (FLAG_WIZ)) { 731 if ($who->flag (FLAG_WIZ)) {
231 $who->message ("reloading..."); 732 _perl_reload {
232 733 warn $_[0];
233 warn "reloading...\n"; 734 $who->message ($_[0]);
234 eval {
235 $_->cancel for Event::all_watchers;
236
237 unload_extension $_ for @exts;
238 delete $INC{"cf.pm"};
239
240 # don't, removes xs symbols, too
241 #Symbol::delete_package __PACKAGE__;
242
243 require cf;
244 }; 735 };
245 warn $@ if $@;
246 $who->message ($@) if $@;
247 warn "reloaded\n";
248
249 $who->message ("reloaded");
250 } else {
251 $who->message ("Intruder Alert!");
252 } 736 }
253}; 737};
254 738
255############################################################################# 739#############################################################################
256# extcmd framework, basically convert ext <id> <pkg> arg1 args 740# extcmd framework, basically convert ext <msg>
257# into pkg::->on_extcmd_arg1 (...) while shortcutting a few 741# into pkg::->on_extcmd_arg1 (...) while shortcutting a few
258 742
259sub on_extcmd { 743attach_to_players
744 on_extcmd => sub {
260 my ($pl, $buf) = @_; 745 my ($pl, $buf) = @_;
261 746
262 my ($type) = $buf =~ s/^(\S+) // ? $1 : ""; 747 my $msg = eval { from_json $buf };
263 748
264 $extcmd{$type}[0]->($pl, $buf) 749 if (ref $msg) {
265 if $extcmd{$type}; 750 if (my $cb = $extcmd{$msg->{msgtype}}) {
266} 751 if (my %reply = $cb->[0]->($pl, $msg)) {
752 $pl->ext_reply ($msg->{msgid}, %reply);
753 }
754 }
755 } else {
756 warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n";
757 }
758
759 cf::override;
760 },
761;
267 762
268############################################################################# 763#############################################################################
269# load/save/clean perl data associated with a map 764# load/save/clean perl data associated with a map
270 765
271*on_mapclean = sub { 766*cf::mapsupport::on_clean = sub {
272 my ($map) = @_; 767 my ($map) = @_;
273 768
274 my $path = $map->tmpname; 769 my $path = $map->tmpname;
275 defined $path or return; 770 defined $path or return;
276 771
277 unlink "$path.cfperl"; 772 unlink "$path.pst";
278}; 773};
279 774
280*on_mapin = 775attach_to_maps prio => -10000, package => cf::mapsupport::;
281*on_mapload = sub {
282 my ($map) = @_;
283
284 my $path = $map->tmpname;
285 $path = $map->path unless defined $path;
286
287 open my $fh, "<:raw", "$path.cfperl"
288 or return; # no perl data
289
290 my $data = Storable::thaw do { local $/; <$fh> };
291
292 $data->{version} <= 1
293 or return; # too new
294
295 $map->_set_obs ($data->{obs});
296};
297
298*on_mapout = sub {
299 my ($map) = @_;
300
301 my $path = $map->tmpname;
302 $path = $map->path unless defined $path;
303
304 my $obs = $map->_get_obs;
305
306 if (defined $obs) {
307 open my $fh, ">:raw", "$path.cfperl"
308 or die "$path.cfperl: $!";
309
310 stat $path;
311
312 print $fh Storable::nfreeze {
313 size => (stat _)[7],
314 time => (stat _)[9],
315 version => 1,
316 obs => $obs,
317 };
318
319 chmod SAVE_MODE, "$path.cfperl"; # very racy, but cf-compatible *g*
320 } else {
321 unlink "$path.cfperl";
322 }
323};
324 776
325############################################################################# 777#############################################################################
326# load/save perl data associated with player->ob objects 778# load/save perl data associated with player->ob objects
327 779
328*on_player_load = sub { 780sub all_objects(@) {
781 @_, map all_objects ($_->inv), @_
782}
783
784attach_to_players
785 on_load => sub {
329 my ($ob, $path) = @_; 786 my ($pl, $path) = @_;
330 787
331 for my $o ($ob, $ob->inv) { 788 for my $o (all_objects $pl->ob) {
332 if (my $value = $o->get_ob_key_value ("_perl_data")) { 789 if (my $value = $o->get_ob_key_value ("_perl_data")) {
333 $o->set_ob_key_value ("_perl_data"); 790 $o->set_ob_key_value ("_perl_data");
334 791
335 %$o = %{ Storable::thaw pack "H*", $value }; 792 %$o = %{ Storable::thaw pack "H*", $value };
793 }
336 } 794 }
337 } 795 },
338}; 796;
339
340*on_player_save = sub {
341 my ($ob, $path) = @_;
342
343 $_->set_ob_key_value (_perl_data => unpack "H*", Storable::nfreeze $_)
344 for grep %$_, $ob, $ob->inv;
345};
346 797
347############################################################################# 798#############################################################################
348# core extensions - in perl 799# core extensions - in perl
349 800
350=item cf::player::exists $login 801=item cf::player::exists $login
355 806
356sub cf::player::exists($) { 807sub cf::player::exists($) {
357 cf::player::find $_[0] 808 cf::player::find $_[0]
358 or -f sprintf "%s/%s/%s/%s.pl", cf::localdir, cf::playerdir, ($_[0]) x 2; 809 or -f sprintf "%s/%s/%s/%s.pl", cf::localdir, cf::playerdir, ($_[0]) x 2;
359} 810}
811
812=item $player->reply ($npc, $msg[, $flags])
813
814Sends a message to the player, as if the npc C<$npc> replied. C<$npc>
815can be C<undef>. Does the right thing when the player is currently in a
816dialogue with the given NPC character.
817
818=cut
360 819
361# rough implementation of a future "reply" method that works 820# rough implementation of a future "reply" method that works
362# with dialog boxes. 821# with dialog boxes.
363sub cf::object::player::reply($$$;$) { 822sub cf::object::player::reply($$$;$) {
364 my ($self, $npc, $msg, $flags) = @_; 823 my ($self, $npc, $msg, $flags) = @_;
371 $msg = $npc->name . " says: $msg" if $npc; 830 $msg = $npc->name . " says: $msg" if $npc;
372 $self->message ($msg, $flags); 831 $self->message ($msg, $flags);
373 } 832 }
374} 833}
375 834
835=item $player->ext_reply ($msgid, $msgtype, %msg)
836
837Sends an ext reply to the player.
838
839=cut
840
841sub cf::player::ext_reply($$$%) {
842 my ($self, $id, %msg) = @_;
843
844 $msg{msgid} = $id;
845
846 $self->send ("ext " . to_json \%msg);
847}
848
376############################################################################# 849#############################################################################
377# map scripting support 850# map scripting support
378 851
379our $safe = new Safe "ext"; 852our $safe = new Safe "safe";
380our $safe_hole = new Safe::Hole; 853our $safe_hole = new Safe::Hole;
381 854
382$SIG{FPE} = 'IGNORE'; 855$SIG{FPE} = 'IGNORE';
383 856
384$safe->permit_only (Opcode::opset qw(:base_core :base_mem :base_orig :base_math sort time)); 857$safe->permit_only (Opcode::opset qw(:base_core :base_mem :base_orig :base_math sort time));
385 858
386# here we export the classes and methods available to script code 859# here we export the classes and methods available to script code
387 860
388for ( 861for (
389 ["cf::object" => qw(contr)], 862 ["cf::object" => qw(contr pay_amount pay_player)],
390 ["cf::object::player" => qw(player)], 863 ["cf::object::player" => qw(player)],
391 ["cf::player" => qw(peaceful)], 864 ["cf::player" => qw(peaceful)],
392) { 865) {
393 no strict 'refs'; 866 no strict 'refs';
394 my ($pkg, @funs) = @$_; 867 my ($pkg, @funs) = @$_;
395 *{"ext::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"}) 868 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"})
396 for @funs; 869 for @funs;
397} 870}
398 871
399sub safe_eval($;@) { 872sub safe_eval($;@) {
400 my ($code, %vars) = @_; 873 my ($code, %vars) = @_;
402 my $qcode = $code; 875 my $qcode = $code;
403 $qcode =~ s/"/‟/g; # not allowed in #line filenames 876 $qcode =~ s/"/‟/g; # not allowed in #line filenames
404 $qcode =~ s/\n/\\n/g; 877 $qcode =~ s/\n/\\n/g;
405 878
406 local $_; 879 local $_;
407 local @ext::cf::_safe_eval_args = values %vars; 880 local @safe::cf::_safe_eval_args = values %vars;
408 881
409 $code = 882 my $eval =
410 "do {\n" 883 "do {\n"
411 . "my (" . (join ",", map "\$$_", keys %vars) . ") = \@cf::_safe_eval_args;\n" 884 . "my (" . (join ",", map "\$$_", keys %vars) . ") = \@cf::_safe_eval_args;\n"
412 . "#line 0 \"{$qcode}\"\n" 885 . "#line 0 \"{$qcode}\"\n"
413 . $code 886 . $code
414 . "\n}" 887 . "\n}"
415 ; 888 ;
416 889
417 sub_generation_inc; 890 sub_generation_inc;
418 my @res = wantarray ? $safe->reval ($code) : scalar $safe->reval ($code); 891 my @res = wantarray ? $safe->reval ($eval) : scalar $safe->reval ($eval);
419 sub_generation_inc; 892 sub_generation_inc;
893
894 if ($@) {
895 warn "$@";
896 warn "while executing safe code '$code'\n";
897 warn "with arguments " . (join " ", %vars) . "\n";
898 }
420 899
421 wantarray ? @res : $res[0] 900 wantarray ? @res : $res[0]
422} 901}
423 902
424sub register_script_function { 903sub register_script_function {
425 my ($fun, $cb) = @_; 904 my ($fun, $cb) = @_;
426 905
427 no strict 'refs'; 906 no strict 'refs';
428 *{"ext::$fun"} = $safe_hole->wrap ($cb); 907 *{"safe::$fun"} = $safe_hole->wrap ($cb);
908}
909
910#############################################################################
911# the server's main()
912
913sub main {
914 Event::loop;
429} 915}
430 916
431############################################################################# 917#############################################################################
432# initialisation 918# initialisation
433 919
434register "<global>", __PACKAGE__; 920register "<global>", __PACKAGE__;
435 921
436unshift @INC, maps_directory "perl"; 922unshift @INC, $LIBDIR;
437 923
438load_extensions; 924load_extensions;
439 925
926$TICK_WATCHER = Event->timer (
927 prio => 1,
928 at => $NEXT_TICK || 1,
929 cb => sub {
930 cf::server_tick; # one server iteration
931
932 my $NOW = Event::time;
933 $NEXT_TICK += $TICK;
934
935 # if we are delayed by four ticks, skip them all
936 $NEXT_TICK = $NOW if $NOW >= $NEXT_TICK + $TICK * 4;
937
938 $TICK_WATCHER->at ($NEXT_TICK);
939 $TICK_WATCHER->start;
940 },
941);
942
943_reload_2;
944
4401 9451
441 946

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines