--- deliantra/server/lib/cf.pm 2006/03/28 16:48:11 1.12 +++ deliantra/server/lib/cf.pm 2006/08/25 13:24:50 1.39 @@ -3,16 +3,29 @@ use Symbol; use List::Util; use Storable; +use Opcode; +use Safe; +use Safe::Hole; + +use Time::HiRes; +use Event; +$Event::Eval = 1; # no idea why this is required, but it is use strict; -our %COMMAND; +our %COMMAND = (); our @EVENT; +our @PLUGIN_EVENT; our %PROP_TYPE; our %PROP_IDX; +our $LIBDIR = maps_directory "perl"; + +our $TICK = MAX_TIME * 1e-6; +our $TICK_WATCHER; +our $NEXT_TICK; BEGIN { - @EVENT = map lc, @EVENT; + @PLUGIN_EVENT = map lc, @PLUGIN_EVENT; *CORE::GLOBAL::warn = sub { my $msg = join "", @_; @@ -60,21 +73,185 @@ # guessed hierarchies -@cf::object::player::ISA = 'cf::object'; -@cf::object::map::ISA = 'cf::object'; +@ext::cf::object::player::ISA = @cf::object::player::ISA = 'cf::object'; +@ext::cf::object::map::ISA = @cf::object::map::ISA = 'cf::object'; + +# we bless all objects into derived classes to force a method lookup +# within the Safe compartment. +for my $pkg (qw(cf::object cf::object::map cf::object::player cf::player cf::map cf::party cf::region cf::arch)) { + no strict 'refs'; + @{"ext::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg; +} + +$Event::DIED = sub { + warn "error in event callback: @_"; +}; my %ext_pkg; my @exts; my @hook; my %command; +my %extcmd; + +############################################################################# +# "new" plug-in system + +=item cf::object::attach ... # NYI + +=item cf::attach_global ... # NYI + +=item cf::attach_to_type ... # NYI + +=item cf::attach_to_objects ... # NYI + +=item cf::attach_to_players ... # NYI + +=item cf::attach_to_maps ... # NYI + + prio => $number, # higehr is earlier + on_xxx => \&cb, + package => package::, + +=cut + +our %CB_CLASS = (); # registry for class-based events +our @CB_GLOBAL = (); # registry for all global events +our @CB_TYPE = (); # registry for type (cf-object class) based events + +sub _attach_cb($\%$$$) { + my ($registry, $undo, $event, $prio, $cb) = @_; + + use sort 'stable'; + + $cb = [$prio, $cb]; + + @{$registry->[$event]} = sort + { $a->[0] cmp $b->[0] } + @{$registry->[$event] || []}, $cb; + + push @{$undo->{cb}}, [$event, $cb]; +} + +# attach handles attaching event callbacks +# the only thing the caller has to do is pass the correct +# registry (== where the callback attaches to). +sub _attach(\@$\@) { + my ($registry, $klass, $arg) = @_; + + my $prio = 0; + + my %undo = ( + registry => $registry, + cb => [], + ); + + my %cb_id = map +("on_" . lc $EVENT[$_][0], $_) , grep $EVENT[$_][1] == $klass, 0 .. $#EVENT; + + while (@$arg) { + my $type = shift @$arg; + + if ($type eq "prio") { + $prio = shift @$arg; + + } elsif ($type eq "package") { + my $pkg = shift @$arg; + + while (my ($name, $id) = each %cb_id) { + if (my $cb = $pkg->can ($name)) { + _attach_cb $registry, %undo, $id, $prio, $cb; + } + } + + } elsif (exists $cb_id{$type}) { + _attach_cb $registry, %undo, $cb_id{$type}, $prio, shift @$arg; + + } elsif (ref $type) { + warn "attaching objects not supported, ignoring.\n"; + + } else { + shift @$arg; + warn "attach argument '$type' not supported, ignoring.\n"; + } + } + + \%undo +} + +sub cf::object::attach { + die; +} + +sub attach_global { + _attach @CB_GLOBAL, KLASS_GLOBAL, @_ +} + +sub attach_type { + my $type = shift; + _attach @{$CB_TYPE[$type]}, KLASS_MAP, @_ +} + +sub attach_to_objects { + _attach @{$CB_CLASS{cf::object::wrap::}}, KLASS_OBJECT, @_ +} + +sub attach_to_players { + _attach @{$CB_CLASS{cf::player::wrap::}}, KLASS_PLAYER, @_ +} + +sub attach_to_maps { + _attach @{$CB_CLASS{cf::map::wrap::}}, KLASS_MAP, @_ +} + +our $override; + +sub override() { + $override = 1 +} + +sub invoke { + my $event = shift; + + my @cb; + + if (my $ref = ref $_[0]) { + # 1. object-specific (NYI) + # 2. class-specific + push @cb, @{$CB_CLASS{$ref}[$event] || []}; + } + + # global + push @cb, @{$CB_GLOBAL[$event] || []}; + +# warn "invoke id $EVENT[$event][0], args <@_> <=> @cb\n";#d# + + local $override; + + for (@cb) { + eval { &{$_->[1]} }; + + if ($@) { + warn "$@"; + warn "... while processing $EVENT[$event][0] event, skipping processing altogether.\n"; + override; + } + + return 1 if $override; + } + + 0 +} + +############################################################################# +# old plug-in events sub inject_event { - my ($data) = @_; + my $extension = shift; + my $event_code = shift; - my $cb = $hook[$data->{event_code}]{$data->{extension}} + my $cb = $hook[$event_code]{$extension} or return; - $cb->($data) + &$cb } sub inject_global_event { @@ -100,19 +277,27 @@ my ($name, $time, $cb) = @_; my $caller = caller; - - warn "registering command '$name/$time' to '$caller'"; + #warn "registering command '$name/$time' to '$caller'"; push @{ $command{$name} }, [$time, $cb, $caller]; $COMMAND{"$name\000"} = List::Util::max map $_->[0], @{ $command{$name} }; } +sub register_extcmd { + my ($name, $cb) = @_; + + my $caller = caller; + #warn "registering extcmd '$name' to '$caller'"; + + $extcmd{$name} = [$cb, $caller]; +} + sub register { my ($base, $pkg) = @_; - for my $idx (0 .. $#EVENT) { - if (my $ref = $pkg->can ("on_$EVENT[$idx]")) { - warn "registering $EVENT[$idx] hook to '$pkg'\n"; + for my $idx (0 .. $#PLUGIN_EVENT) { + if (my $ref = $pkg->can ("on_$PLUGIN_EVENT[$idx]")) { + #warn "registering $PLUGIN_EVENT[$idx] hook to '$pkg'\n"; $hook[$idx]{$base} = $ref; } } @@ -145,7 +330,7 @@ $ext_pkg{$base} = $pkg; # no strict 'refs'; -# @{"$pkg\::ISA"} = cf::ext::; +# @{"$pkg\::ISA"} = ext::; register $base, $pkg; } @@ -156,7 +341,7 @@ warn "removing extension $pkg\n"; # remove hooks - for my $idx (0 .. $#EVENT) { + for my $idx (0 .. $#PLUGIN_EVENT) { delete $hook[$idx]{$pkg}; } @@ -173,6 +358,18 @@ } } + # remove extcmds + for my $name (grep $extcmd{$_}[1] eq $pkg, keys %extcmd) { + delete $extcmd{$name}; + } + + if (my $cb = $pkg->can ("on_unload")) { + eval { + $cb->($pkg); + 1 + } or warn "$pkg unloaded, but with errors: $@"; + } + Symbol::delete_package $pkg; } @@ -188,37 +385,120 @@ } } +sub _perl_reload(&) { + my ($msg) = @_; + + $msg->("reloading..."); + + eval { + # 1. cancel all watchers + $_->cancel for Event::all_watchers; + + # 2. unload all extensions + for (@exts) { + $msg->("unloading <$_>"); + unload_extension $_; + } + + # 3. unload all modules loaded from $LIBDIR + while (my ($k, $v) = each %INC) { + next unless $v =~ /^\Q$LIBDIR\E\/.*\.pm$/; + + $msg->("removing <$k>"); + delete $INC{$k}; + + $k =~ s/\.pm$//; + $k =~ s/\//::/g; + + if (my $cb = $k->can ("unload_module")) { + $cb->(); + } + + Symbol::delete_package $k; + } + + # 4. get rid of ext::, as good as possible + Symbol::delete_package "ext::$_" + for qw(cf::object cf::object::map cf::object::player cf::player cf::map cf::party cf::region); + + # 5. remove register_script_function callbacks + # TODO + + # 6. unload cf.pm "a bit" + delete $INC{"cf.pm"}; + + # don't, removes xs symbols, too + #Symbol::delete_package __PACKAGE__; + + # 7. reload cf.pm + $msg->("reloading cf.pm"); + require cf; + }; + $msg->($@) if $@; + + $msg->("reloaded"); +}; + +sub perl_reload() { + _perl_reload { + warn $_[0]; + print "$_[0]\n"; + }; +} + register_command "perl-reload", 0, sub { my ($who, $arg) = @_; if ($who->flag (FLAG_WIZ)) { - $who->message ("reloading..."); + _perl_reload { + warn $_[0]; + $who->message ($_[0]); + }; + } +}; - warn "reloading...\n"; - eval { - unload_extension $_ for @exts; - delete $INC{"cf.pm"}; +############################################################################# +# utility functions - # don't, removes xs symbols, too - #Symbol::delete_package $pkg; +use JSON::Syck (); # TODO# replace by JSON::PC once working - require cf; - }; - warn $@ if $@; - $who->message ($@) if $@; - warn "reloaded\n"; +sub from_json($) { + $JSON::Syck::ImplicitUnicode = 1; # work around JSON::Syck bugs + JSON::Syck::Load $_[0] +} + +sub to_json($) { + $JSON::Syck::ImplicitUnicode = 0; # work around JSON::Syck bugs + JSON::Syck::Dump $_[0] +} + +############################################################################# +# extcmd framework, basically convert ext +# into pkg::->on_extcmd_arg1 (...) while shortcutting a few + +sub on_extcmd { + my ($pl, $buf) = @_; + + my $msg = eval { from_json $buf }; - $who->message ("reloaded"); + if (ref $msg) { + if (my $cb = $extcmd{$msg->{msgtype}}) { + if (my %reply = $cb->[0]->($pl, $msg)) { + $pl->ext_reply ($msg->{msgid}, %reply); + } + } } else { - $who->message ("Intruder Alert!"); + warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n"; } -}; + + 1 +} ############################################################################# # load/save/clean perl data associated with a map -*on_mapclean = sub { - my $map = shift->{map}; +*cf::mapsupport::on_clean = sub { + my ($map) = @_; my $path = $map->tmpname; defined $path or return; @@ -226,9 +506,9 @@ unlink "$path.cfperl"; }; -*on_mapin = -*on_mapload = sub { - my $map = shift->{map}; +*cf::mapsupport::on_swapin = +*cf::mapsupport::on_load = sub { + my ($map) = @_; my $path = $map->tmpname; $path = $map->path unless defined $path; @@ -244,8 +524,8 @@ $map->_set_obs ($data->{obs}); }; -*on_mapout = sub { - my $map = shift->{map}; +*cf::mapsupport::on_swapout = sub { + my ($map) = @_; my $path = $map->tmpname; $path = $map->path unless defined $path; @@ -271,50 +551,173 @@ } }; +attach_to_maps prio => -10000, package => cf::mapsupport::; + ############################################################################# # load/save perl data associated with player->ob objects -*on_player_load = sub { - my ($event) = @_; - my $path = $event->{message}; - my $ob = $event->{who}; +sub all_objects(@) { + @_, map all_objects ($_->inv), @_ +} - if (open my $fh, "<:raw", "$path.cfperl") { +attach_to_players + on_load => sub { + my ($pl, $path) = @_; + + for my $o (all_objects $pl->ob) { + if (my $value = $o->get_ob_key_value ("_perl_data")) { + $o->set_ob_key_value ("_perl_data"); - #d##TODO#remove + %$o = %{ Storable::thaw pack "H*", $value }; + } + } + }, + on_save => sub { + my ($pl, $path) = @_; + + $_->set_ob_key_value (_perl_data => unpack "H*", Storable::nfreeze $_) + for grep %$_, all_objects $pl->ob; + }, +; - my $data = Storable::thaw do { local $/; <$fh> }; +############################################################################# +# core extensions - in perl - $data->{version} <= 1 - or return; # too new +=item cf::player::exists $login - %$ob = %{$data->{ob}}; - return; - } +Returns true when the given account exists. - for my $o ($ob, $ob->inv) { - if (my $value = $o->get_ob_key_value ("_perl_data")) { - $o->set_ob_key_value ("_perl_data"); +=cut - %$o = %{ Storable::thaw pack "H*", $value }; - } +sub cf::player::exists($) { + cf::player::find $_[0] + or -f sprintf "%s/%s/%s/%s.pl", cf::localdir, cf::playerdir, ($_[0]) x 2; +} + +=item $player->reply ($npc, $msg[, $flags]) + +Sends a message to the player, as if the npc C<$npc> replied. C<$npc> +can be C. Does the right thing when the player is currently in a +dialogue with the given NPC character. + +=cut + +# rough implementation of a future "reply" method that works +# with dialog boxes. +sub cf::object::player::reply($$$;$) { + my ($self, $npc, $msg, $flags) = @_; + + $flags = cf::NDI_BROWN | cf::NDI_UNIQUE unless @_ >= 4; + + if ($self->{record_replies}) { + push @{ $self->{record_replies} }, [$npc, $msg, $flags]; + } else { + $msg = $npc->name . " says: $msg" if $npc; + $self->message ($msg, $flags); } -}; +} -*on_player_save = sub { - my ($event) = @_; - my $path = $event->{message}; - my $ob = $event->{who}; +=item $player->ext_reply ($msgid, $msgtype, %msg) - $_->set_ob_key_value (_perl_data => unpack "H*", Storable::nfreeze $_) - for grep %$_, $ob, $ob->inv; +Sends an ext reply to the player. - unlink "$path.cfperl";#d##TODO#remove -}; +=cut + +sub cf::player::ext_reply($$$%) { + my ($self, $id, %msg) = @_; + + $msg{msgid} = $id; + + $self->send ("ext " . to_json \%msg); +} + +############################################################################# +# map scripting support + +our $safe = new Safe "ext"; +our $safe_hole = new Safe::Hole; + +$SIG{FPE} = 'IGNORE'; + +$safe->permit_only (Opcode::opset qw(:base_core :base_mem :base_orig :base_math sort time)); + +# here we export the classes and methods available to script code + +for ( + ["cf::object" => qw(contr pay_amount pay_player)], + ["cf::object::player" => qw(player)], + ["cf::player" => qw(peaceful)], +) { + no strict 'refs'; + my ($pkg, @funs) = @$_; + *{"ext::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"}) + for @funs; +} + +sub safe_eval($;@) { + my ($code, %vars) = @_; + + my $qcode = $code; + $qcode =~ s/"/‟/g; # not allowed in #line filenames + $qcode =~ s/\n/\\n/g; + + local $_; + local @ext::cf::_safe_eval_args = values %vars; + + $code = + "do {\n" + . "my (" . (join ",", map "\$$_", keys %vars) . ") = \@cf::_safe_eval_args;\n" + . "#line 0 \"{$qcode}\"\n" + . $code + . "\n}" + ; + + sub_generation_inc; + my @res = wantarray ? $safe->reval ($code) : scalar $safe->reval ($code); + sub_generation_inc; + + wantarray ? @res : $res[0] +} + +sub register_script_function { + my ($fun, $cb) = @_; + + no strict 'refs'; + *{"ext::$fun"} = $safe_hole->wrap ($cb); +} + +############################################################################# +# the server's main() + +sub main { + Event::loop; +} + +############################################################################# +# initialisation register "", __PACKAGE__; +unshift @INC, $LIBDIR; + load_extensions; +$TICK_WATCHER = Event->timer ( + prio => 1, + at => $NEXT_TICK || 1, + cb => sub { + cf::server_tick; # one server iteration + + my $NOW = Event::time; + $NEXT_TICK += $TICK; + + # if we are delayed by four ticks, skip them all + $NEXT_TICK = $NOW if $NOW >= $NEXT_TICK + $TICK * 4; + + $TICK_WATCHER->at ($NEXT_TICK); + $TICK_WATCHER->start; + }, +); + 1