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.83 by root, Mon Dec 11 01:30:41 2006 UTC vs.
Revision 1.95 by root, Fri Dec 22 02:04:20 2006 UTC

16# work around bug in YAML::Syck - bad news for perl6, will it be as broken wrt. unicode? 16# work around bug in YAML::Syck - bad news for perl6, will it be as broken wrt. unicode?
17$YAML::Syck::ImplicitUnicode = 1; 17$YAML::Syck::ImplicitUnicode = 1;
18 18
19use strict; 19use strict;
20 20
21sub WF_AUTOCANCEL () { 1 } # automatically cancel this watcher on reload
22
23our %COMMAND = ();
24our %COMMAND_TIME = ();
25our %EXTCMD = ();
26
21_init_vars; 27_init_vars;
22 28
23our %COMMAND = ();
24our @EVENT; 29our @EVENT;
25our $LIBDIR = maps_directory "perl"; 30our $LIBDIR = datadir . "/ext";
26 31
27our $TICK = MAX_TIME * 1e-6; 32our $TICK = MAX_TIME * 1e-6;
28our $TICK_WATCHER; 33our $TICK_WATCHER;
29our $NEXT_TICK; 34our $NEXT_TICK;
30 35
31our %CFG; 36our %CFG;
32 37
33our $uptime;#d# 38our $UPTIME; $UPTIME ||= time;
34our $UPTIME;
35$UPTIME ||= $uptime;#d#
36$UPTIME ||= time;
37 39
38############################################################################# 40#############################################################################
39 41
40=head2 GLOBAL VARIABLES 42=head2 GLOBAL VARIABLES
41 43
72 print STDERR "cfperl: $msg"; 74 print STDERR "cfperl: $msg";
73 LOG llevError, "cfperl: $msg"; 75 LOG llevError, "cfperl: $msg";
74 }; 76 };
75} 77}
76 78
79@safe::cf::global::ISA = @cf::global::ISA = 'cf::attachable';
80@safe::cf::object::ISA = @cf::object::ISA = 'cf::attachable';
81@safe::cf::player::ISA = @cf::player::ISA = 'cf::attachable';
82@safe::cf::client::ISA = @cf::client::ISA = 'cf::attachable';
83@safe::cf::map::ISA = @cf::map::ISA = 'cf::attachable';
77@safe::cf::object::player::ISA = @cf::object::player::ISA = 'cf::object'; 84@safe::cf::object::player::ISA = @cf::object::player::ISA = 'cf::object';
78 85
79# we bless all objects into (empty) derived classes to force a method lookup 86# we bless all objects into (empty) derived classes to force a method lookup
80# within the Safe compartment. 87# within the Safe compartment.
81for my $pkg (qw(cf::object cf::object::player cf::player cf::map cf::party cf::region cf::arch cf::living)) { 88for my $pkg (qw(
89 cf::global
90 cf::object cf::object::player
91 cf::client cf::player
92 cf::arch cf::living
93 cf::map cf::party cf::region
94)) {
82 no strict 'refs'; 95 no strict 'refs';
83 @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg; 96 @{"safe::$pkg\::wrap::ISA"} = @{"$pkg\::wrap::ISA"} = $pkg;
84} 97}
85 98
86$Event::DIED = sub { 99$Event::DIED = sub {
88}; 101};
89 102
90my %ext_pkg; 103my %ext_pkg;
91my @exts; 104my @exts;
92my @hook; 105my @hook;
93my %command;
94my %extcmd;
95 106
96=head2 UTILITY FUNCTIONS 107=head2 UTILITY FUNCTIONS
97 108
98=over 4 109=over 4
99 110
127 138
128=cut 139=cut
129 140
130############################################################################# 141#############################################################################
131 142
132=head2 EVENTS AND OBJECT ATTACHMENTS 143=head2 ATTACHABLE OBJECTS
144
145Many objects in crossfire are so-called attachable objects. That means you can
146attach callbacks/event handlers (a collection of which is called an "attachment")
147to it. All such attachable objects support the following methods.
148
149In the following description, CLASS can be any of C<global>, C<object>
150C<player>, C<client> or C<map> (i.e. the attachable objects in
151crossfire+).
133 152
134=over 4 153=over 4
135 154
136=item $object->attach ($attachment, key => $value...)
137
138=item $object->detach ($attachment)
139
140Attach/detach a pre-registered attachment to an object.
141
142=item $player->attach ($attachment, key => $value...)
143
144=item $player->detach ($attachment)
145
146Attach/detach a pre-registered attachment to a player.
147
148=item $map->attach ($attachment, key => $value...) 155=item $attachable->attach ($attachment, key => $value...)
149 156
150=item $map->detach ($attachment) 157=item $attachable->detach ($attachment)
151 158
152Attach/detach a pre-registered attachment to a map. 159Attach/detach a pre-registered attachment to a specific object and give it
160the specified key/value pairs as arguments.
153 161
154=item $bool = $object->attached ($name) 162Example, attach a minesweeper attachment to the given object, making it a
16310x10 minesweeper game:
155 164
156=item $bool = $player->attached ($name) 165 $obj->attach (minesweeper => width => 10, height => 10);
157 166
158=item $bool = $map->attached ($name) 167=item $bool = $attachable->attached ($name)
159 168
160Checks wether the named attachment is currently attached to the object. 169Checks wether the named attachment is currently attached to the object.
161 170
162=item cf::attach_global ... 171=item cf::CLASS->attach ...
163 172
164Attach handlers for global events. 173=item cf::CLASS->detach ...
165 174
166This and all following C<attach_*>-functions expect any number of the 175Define an anonymous attachment and attach it to all objects of the given
167following handler/hook descriptions: 176CLASS. See the next function for an explanation of its arguments.
177
178You can attach to global events by using the C<cf::global> class.
179
180Example, log all player logins:
181
182 cf::player->attach (
183 on_login => sub {
184 my ($pl) = @_;
185 ...
186 },
187 );
188
189Example, attach to the jeweler skill:
190
191 cf::object->attach (
192 type => cf::SKILL,
193 subtype => cf::SK_JEWELER,
194 on_use_skill => sub {
195 my ($sk, $ob, $part, $dir, $msg) = @_;
196 ...
197 },
198 );
199
200=item cf::CLASS::attachment $name, ...
201
202Register an attachment by C<$name> through which attachable objects of the
203given CLASS can refer to this attachment.
204
205Some classes such as crossfire maps and objects can specify attachments
206that are attached at load/instantiate time, thus the need for a name.
207
208These calls expect any number of the following handler/hook descriptions:
168 209
169=over 4 210=over 4
170 211
171=item prio => $number 212=item prio => $number
172 213
174by another C<prio> setting). Lower priority handlers get executed 215by another C<prio> setting). Lower priority handlers get executed
175earlier. The default priority is C<0>, and many built-in handlers are 216earlier. The default priority is C<0>, and many built-in handlers are
176registered at priority C<-1000>, so lower priorities should not be used 217registered at priority C<-1000>, so lower priorities should not be used
177unless you know what you are doing. 218unless you know what you are doing.
178 219
220=item type => $type
221
222(Only for C<< cf::object->attach >> calls), limits the attachment to the
223given type of objects only (the additional parameter C<subtype> can be
224used to further limit to the given subtype).
225
179=item on_I<event> => \&cb 226=item on_I<event> => \&cb
180 227
181Call the given code reference whenever the named event happens (event is 228Call the given code reference whenever the named event happens (event is
182something like C<instantiate>, C<apply>, C<use_skill> and so on, and which 229something like C<instantiate>, C<apply>, C<use_skill> and so on, and which
183handlers are recognised generally depends on the type of object these 230handlers are recognised generally depends on the type of object these
192package and register them. Only handlers for eevents supported by the 239package and register them. Only handlers for eevents supported by the
193object/class are recognised. 240object/class are recognised.
194 241
195=back 242=back
196 243
197=item cf::attach_to_type $object_type, $subtype, ... 244Example, define an attachment called "sockpuppet" that calls the given
245event handler when a monster attacks:
198 246
199Attach handlers for a specific object type (e.g. TRANSPORT) and 247 cf::object::attachment sockpuppet =>
200subtype. If C<$subtype> is zero or undef, matches all objects of the given 248 on_skill_attack => sub {
201type. 249 my ($self, $victim) = @_;
202 250 ...
203=item cf::attach_to_objects ... 251 }
204 252 }
205Attach handlers to all objects. Do not use this except for debugging or
206very rare events, as handlers are (obviously) called for I<all> objects in
207the game.
208
209=item cf::attach_to_players ...
210
211Attach handlers to all players.
212
213=item cf::attach_to_maps ...
214
215Attach handlers to all maps.
216
217=item cf:register_attachment $name, ...
218
219Register an attachment by name through which objects can refer to this
220attachment.
221
222=item cf:register_player_attachment $name, ...
223
224Register an attachment by name through which players can refer to this
225attachment.
226
227=item cf:register_map_attachment $name, ...
228
229Register an attachment by name through which maps can refer to this
230attachment.
231 253
232=cut 254=cut
233 255
234# the following variables are defined in .xs and must not be re-created 256# the following variables are defined in .xs and must not be re-created
235our @CB_GLOBAL = (); # registry for all global events 257our @CB_GLOBAL = (); # registry for all global events
236our @CB_OBJECT = (); # all objects (should not be used except in emergency) 258our @CB_OBJECT = (); # all objects (should not be used except in emergency)
237our @CB_PLAYER = (); 259our @CB_PLAYER = ();
260our @CB_CLIENT = ();
238our @CB_TYPE = (); # registry for type (cf-object class) based events 261our @CB_TYPE = (); # registry for type (cf-object class) based events
239our @CB_MAP = (); 262our @CB_MAP = ();
240 263
241my %attachment; 264my %attachment;
242 265
243sub _attach_cb($\%$$$) { 266sub _attach_cb($$$$) {
244 my ($registry, $undo, $event, $prio, $cb) = @_; 267 my ($registry, $event, $prio, $cb) = @_;
245 268
246 use sort 'stable'; 269 use sort 'stable';
247 270
248 $cb = [$prio, $cb]; 271 $cb = [$prio, $cb];
249 272
250 @{$registry->[$event]} = sort 273 @{$registry->[$event]} = sort
251 { $a->[0] cmp $b->[0] } 274 { $a->[0] cmp $b->[0] }
252 @{$registry->[$event] || []}, $cb; 275 @{$registry->[$event] || []}, $cb;
253
254 push @{$undo->{cb}}, [$event, $cb];
255} 276}
256 277
257# attach handles attaching event callbacks 278# attach handles attaching event callbacks
258# the only thing the caller has to do is pass the correct 279# the only thing the caller has to do is pass the correct
259# registry (== where the callback attaches to). 280# registry (== where the callback attaches to).
260sub _attach(\@$@) { 281sub _attach {
261 my ($registry, $klass, @arg) = @_; 282 my ($registry, $klass, @arg) = @_;
262 283
284 my $object_type;
263 my $prio = 0; 285 my $prio = 0;
264
265 my %undo = (
266 registry => $registry,
267 cb => [],
268 );
269
270 my %cb_id = map +("on_" . lc $EVENT[$_][0], $_) , grep $EVENT[$_][1] == $klass, 0 .. $#EVENT; 286 my %cb_id = map +("on_" . lc $EVENT[$_][0], $_) , grep $EVENT[$_][1] == $klass, 0 .. $#EVENT;
271 287
272 while (@arg) { 288 while (@arg) {
273 my $type = shift @arg; 289 my $type = shift @arg;
274 290
275 if ($type eq "prio") { 291 if ($type eq "prio") {
276 $prio = shift @arg; 292 $prio = shift @arg;
277 293
294 } elsif ($type eq "type") {
295 $object_type = shift @arg;
296 $registry = $CB_TYPE[$object_type] ||= [];
297
298 } elsif ($type eq "subtype") {
299 defined $object_type or Carp::croak "subtype specified without type";
300 my $object_subtype = shift @arg;
301 $registry = $CB_TYPE[$object_type + $object_subtype * NUM_SUBTYPES] ||= [];
302
278 } elsif ($type eq "package") { 303 } elsif ($type eq "package") {
279 my $pkg = shift @arg; 304 my $pkg = shift @arg;
280 305
281 while (my ($name, $id) = each %cb_id) { 306 while (my ($name, $id) = each %cb_id) {
282 if (my $cb = $pkg->can ($name)) { 307 if (my $cb = $pkg->can ($name)) {
283 _attach_cb $registry, %undo, $id, $prio, $cb; 308 _attach_cb $registry, $id, $prio, $cb;
284 } 309 }
285 } 310 }
286 311
287 } elsif (exists $cb_id{$type}) { 312 } elsif (exists $cb_id{$type}) {
288 _attach_cb $registry, %undo, $cb_id{$type}, $prio, shift @arg; 313 _attach_cb $registry, $cb_id{$type}, $prio, shift @arg;
289 314
290 } elsif (ref $type) { 315 } elsif (ref $type) {
291 warn "attaching objects not supported, ignoring.\n"; 316 warn "attaching objects not supported, ignoring.\n";
292 317
293 } else { 318 } else {
294 shift @arg; 319 shift @arg;
295 warn "attach argument '$type' not supported, ignoring.\n"; 320 warn "attach argument '$type' not supported, ignoring.\n";
296 } 321 }
297 } 322 }
298
299 \%undo
300} 323}
301 324
302sub _attach_attachment { 325sub _object_attach {
303 my ($obj, $name, %arg) = @_; 326 my ($obj, $name, %arg) = @_;
304 327
305 return if exists $obj->{_attachment}{$name}; 328 return if exists $obj->{_attachment}{$name};
306
307 my $res;
308 329
309 if (my $attach = $attachment{$name}) { 330 if (my $attach = $attachment{$name}) {
310 my $registry = $obj->registry; 331 my $registry = $obj->registry;
311 332
312 for (@$attach) { 333 for (@$attach) {
313 my ($klass, @attach) = @$_; 334 my ($klass, @attach) = @$_;
314 $res = _attach @$registry, $klass, @attach; 335 _attach $registry, $klass, @attach;
315 } 336 }
316 337
317 $obj->{$name} = \%arg; 338 $obj->{$name} = \%arg;
318 } else { 339 } else {
319 warn "object uses attachment '$name' that is not available, postponing.\n"; 340 warn "object uses attachment '$name' that is not available, postponing.\n";
320 } 341 }
321 342
322 $obj->{_attachment}{$name} = undef; 343 $obj->{_attachment}{$name} = undef;
323
324 $res->{attachment} = $name;
325 $res
326} 344}
327 345
328*cf::object::attach = 346sub cf::attachable::attach {
329*cf::player::attach = 347 if (ref $_[0]) {
330*cf::map::attach = sub { 348 _object_attach @_;
331 my ($obj, $name, %arg) = @_; 349 } else {
332 350 _attach shift->_attach_registry, @_;
333 _attach_attachment $obj, $name, %arg; 351 }
334}; 352};
335 353
336# all those should be optimised 354# all those should be optimised
337*cf::object::detach = 355sub cf::attachable::detach {
338*cf::player::detach =
339*cf::map::detach = sub {
340 my ($obj, $name) = @_; 356 my ($obj, $name) = @_;
341 357
358 if (ref $obj) {
342 delete $obj->{_attachment}{$name}; 359 delete $obj->{_attachment}{$name};
343 reattach ($obj); 360 reattach ($obj);
361 } else {
362 Carp::croak "cannot, currently, detach class attachments";
363 }
344}; 364};
345 365
346*cf::object::attached = 366sub cf::attachable::attached {
347*cf::player::attached =
348*cf::map::attached = sub {
349 my ($obj, $name) = @_; 367 my ($obj, $name) = @_;
350 368
351 exists $obj->{_attachment}{$name} 369 exists $obj->{_attachment}{$name}
352};
353
354sub attach_global {
355 _attach @CB_GLOBAL, KLASS_GLOBAL, @_
356} 370}
357 371
358sub attach_to_type { 372for my $klass (qw(GLOBAL OBJECT PLAYER CLIENT MAP)) {
359 my $type = shift; 373 eval "#line " . __LINE__ . " 'cf.pm'
360 my $subtype = shift; 374 sub cf::\L$klass\E::_attach_registry {
375 (\\\@CB_$klass, KLASS_$klass)
376 }
361 377
362 _attach @{$CB_TYPE[$type + $subtype * NUM_SUBTYPES]}, KLASS_OBJECT, @_ 378 sub cf::\L$klass\E::attachment {
363}
364
365sub attach_to_objects {
366 _attach @CB_OBJECT, KLASS_OBJECT, @_
367}
368
369sub attach_to_players {
370 _attach @CB_PLAYER, KLASS_PLAYER, @_
371}
372
373sub attach_to_maps {
374 _attach @CB_MAP, KLASS_MAP, @_
375}
376
377sub register_attachment {
378 my $name = shift; 379 my \$name = shift;
379 380
380 $attachment{$name} = [[KLASS_OBJECT, @_]];
381}
382
383sub register_player_attachment {
384 my $name = shift;
385
386 $attachment{$name} = [[KLASS_PLAYER, @_]];
387}
388
389sub register_map_attachment {
390 my $name = shift;
391
392 $attachment{$name} = [[KLASS_MAP, @_]]; 381 \$attachment{\$name} = [[KLASS_$klass, \@_]];
382 }
383 ";
384 die if $@;
393} 385}
394 386
395our $override; 387our $override;
396our @invoke_results = (); # referenced from .xs code. TODO: play tricks with reify and mortals? 388our @invoke_results = (); # referenced from .xs code. TODO: play tricks with reify and mortals?
397 389
427 419
428=item $bool = $object->invoke (EVENT_OBJECT_XXX, ...) 420=item $bool = $object->invoke (EVENT_OBJECT_XXX, ...)
429 421
430=item $bool = $player->invoke (EVENT_PLAYER_XXX, ...) 422=item $bool = $player->invoke (EVENT_PLAYER_XXX, ...)
431 423
424=item $bool = $client->invoke (EVENT_CLIENT_XXX, ...)
425
432=item $bool = $map->invoke (EVENT_MAP_XXX, ...) 426=item $bool = $map->invoke (EVENT_MAP_XXX, ...)
433 427
434Generate a global/object/player/map-specific event with the given arguments. 428Generate a global/object/player/map-specific event with the given arguments.
435 429
436This API is preliminary (most likely, the EVENT_KLASS_xxx prefix will be 430This API is preliminary (most likely, the EVENT_KLASS_xxx prefix will be
441 435
442=cut 436=cut
443 437
444############################################################################# 438#############################################################################
445 439
446=head2 METHODS VALID FOR ALL CORE OBJECTS 440=head2 METHODS VALID FOR ALL ATTACHABLE OBJECTS
441
442Attachable objects includes objects, players, clients and maps.
447 443
448=over 4 444=over 4
449 445
450=item $object->valid, $player->valid, $map->valid 446=item $object->valid
451 447
452Just because you have a perl object does not mean that the corresponding 448Just because you have a perl object does not mean that the corresponding
453C-level object still exists. If you try to access an object that has no 449C-level object still exists. If you try to access an object that has no
454valid C counterpart anymore you get an exception at runtime. This method 450valid C counterpart anymore you get an exception at runtime. This method
455can be used to test for existence of the C object part without causing an 451can be used to test for existence of the C object part without causing an
457 453
458=back 454=back
459 455
460=cut 456=cut
461 457
462*cf::object::valid =
463*cf::player::valid =
464*cf::map::valid = \&cf::_valid;
465
466############################################################################# 458#############################################################################
467# object support 459# object support
468 460
469sub instantiate { 461sub instantiate {
470 my ($obj, $data) = @_; 462 my ($obj, $data) = @_;
489 481
490 for my $name (keys %{ $obj->{_attachment} || {} }) { 482 for my $name (keys %{ $obj->{_attachment} || {} }) {
491 if (my $attach = $attachment{$name}) { 483 if (my $attach = $attachment{$name}) {
492 for (@$attach) { 484 for (@$attach) {
493 my ($klass, @attach) = @$_; 485 my ($klass, @attach) = @$_;
494 _attach @$registry, $klass, @attach; 486 _attach $registry, $klass, @attach;
495 } 487 }
496 } else { 488 } else {
497 warn "object uses attachment '$name' that is not available, postponing.\n"; 489 warn "object uses attachment '$name' that is not available, postponing.\n";
498 } 490 }
499 } 491 }
555 } 547 }
556 548
557 () 549 ()
558} 550}
559 551
560attach_to_objects 552cf::object->attach (
561 prio => -1000000, 553 prio => -1000000,
562 on_clone => sub { 554 on_clone => sub {
563 my ($src, $dst) = @_; 555 my ($src, $dst) = @_;
564 556
565 @{$dst->registry} = @{$src->registry}; 557 @{$dst->registry} = @{$src->registry};
567 %$dst = %$src; 559 %$dst = %$src;
568 560
569 %{$dst->{_attachment}} = %{$src->{_attachment}} 561 %{$dst->{_attachment}} = %{$src->{_attachment}}
570 if exists $src->{_attachment}; 562 if exists $src->{_attachment};
571 }, 563 },
572; 564);
573 565
574############################################################################# 566#############################################################################
575# old plug-in events 567# command handling &c
576 568
577sub inject_event { 569=item cf::register_command $name => \&callback($ob,$args);
578 my $extension = shift;
579 my $event_code = shift;
580 570
581 my $cb = $hook[$event_code]{$extension} 571Register a callback for execution when the client sends the user command
582 or return; 572$name.
583 573
584 &$cb 574=cut
585}
586
587sub inject_global_event {
588 my $event = shift;
589
590 my $cb = $hook[$event]
591 or return;
592
593 List::Util::max map &$_, values %$cb
594}
595
596sub inject_command {
597 my ($name, $obj, $params) = @_;
598
599 for my $cmd (@{ $command{$name} }) {
600 $cmd->[1]->($obj, $params);
601 }
602
603 -1
604}
605 575
606sub register_command { 576sub register_command {
607 my ($name, $time, $cb) = @_; 577 my ($name, $cb) = @_;
608 578
609 my $caller = caller; 579 my $caller = caller;
610 #warn "registering command '$name/$time' to '$caller'"; 580 #warn "registering command '$name/$time' to '$caller'";
611 581
612 push @{ $command{$name} }, [$time, $cb, $caller]; 582 push @{ $COMMAND{$name} }, [$caller, $cb];
613 $COMMAND{"$name\000"} = List::Util::max map $_->[0], @{ $command{$name} };
614} 583}
584
585=item cf::register_extcmd $name => \&callback($pl,$packet);
586
587Register a callbackf ro execution when the client sends an extcmd packet.
588
589If the callback returns something, it is sent back as if reply was being
590called.
591
592=cut
615 593
616sub register_extcmd { 594sub register_extcmd {
617 my ($name, $cb) = @_; 595 my ($name, $cb) = @_;
618 596
619 my $caller = caller; 597 my $caller = caller;
620 #warn "registering extcmd '$name' to '$caller'"; 598 #warn "registering extcmd '$name' to '$caller'";
621 599
622 $extcmd{$name} = [$cb, $caller]; 600 $EXTCMD{$name} = [$cb, $caller];
623} 601}
602
603cf::player->attach (
604 on_command => sub {
605 my ($pl, $name, $params) = @_;
606
607 my $cb = $COMMAND{$name}
608 or return;
609
610 for my $cmd (@$cb) {
611 $cmd->[1]->($pl->ob, $params);
612 }
613
614 cf::override;
615 },
616 on_extcmd => sub {
617 my ($pl, $buf) = @_;
618
619 my $msg = eval { from_json $buf };
620
621 if (ref $msg) {
622 if (my $cb = $EXTCMD{$msg->{msgtype}}) {
623 if (my %reply = $cb->[0]->($pl, $msg)) {
624 $pl->ext_reply ($msg->{msgid}, %reply);
625 }
626 }
627 } else {
628 warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n";
629 }
630
631 cf::override;
632 },
633);
624 634
625sub register { 635sub register {
626 my ($base, $pkg) = @_; 636 my ($base, $pkg) = @_;
627 637
628 #TODO 638 #TODO
671# for my $idx (0 .. $#PLUGIN_EVENT) { 681# for my $idx (0 .. $#PLUGIN_EVENT) {
672# delete $hook[$idx]{$pkg}; 682# delete $hook[$idx]{$pkg};
673# } 683# }
674 684
675 # remove commands 685 # remove commands
676 for my $name (keys %command) { 686 for my $name (keys %COMMAND) {
677 my @cb = grep $_->[2] ne $pkg, @{ $command{$name} }; 687 my @cb = grep $_->[0] ne $pkg, @{ $COMMAND{$name} };
678 688
679 if (@cb) { 689 if (@cb) {
680 $command{$name} = \@cb; 690 $COMMAND{$name} = \@cb;
681 $COMMAND{"$name\000"} = List::Util::max map $_->[0], @cb;
682 } else { 691 } else {
683 delete $command{$name};
684 delete $COMMAND{"$name\000"}; 692 delete $COMMAND{$name};
685 } 693 }
686 } 694 }
687 695
688 # remove extcmds 696 # remove extcmds
689 for my $name (grep $extcmd{$_}[1] eq $pkg, keys %extcmd) { 697 for my $name (grep $EXTCMD{$_}[1] eq $pkg, keys %EXTCMD) {
690 delete $extcmd{$name}; 698 delete $EXTCMD{$name};
691 } 699 }
692 700
693 if (my $cb = $pkg->can ("unload")) { 701 if (my $cb = $pkg->can ("unload")) {
694 eval { 702 eval {
695 $cb->($pkg); 703 $cb->($pkg);
699 707
700 Symbol::delete_package $pkg; 708 Symbol::delete_package $pkg;
701} 709}
702 710
703sub load_extensions { 711sub load_extensions {
704 my $LIBDIR = maps_directory "perl";
705
706 for my $ext (<$LIBDIR/*.ext>) { 712 for my $ext (<$LIBDIR/*.ext>) {
707 next unless -r $ext; 713 next unless -r $ext;
708 eval { 714 eval {
709 load_extension $ext; 715 load_extension $ext;
710 1 716 1
711 } or warn "$ext not loaded: $@"; 717 } or warn "$ext not loaded: $@";
712 } 718 }
713} 719}
714 720
715############################################################################# 721#############################################################################
716# extcmd framework, basically convert ext <msg>
717# into pkg::->on_extcmd_arg1 (...) while shortcutting a few
718
719attach_to_players
720 on_extcmd => sub {
721 my ($pl, $buf) = @_;
722
723 my $msg = eval { from_json $buf };
724
725 if (ref $msg) {
726 if (my $cb = $extcmd{$msg->{msgtype}}) {
727 if (my %reply = $cb->[0]->($pl, $msg)) {
728 $pl->ext_reply ($msg->{msgid}, %reply);
729 }
730 }
731 } else {
732 warn "player " . ($pl->ob->name) . " sent unparseable ext message: <$buf>\n";
733 }
734
735 cf::override;
736 },
737;
738
739#############################################################################
740# load/save/clean perl data associated with a map 722# load/save/clean perl data associated with a map
741 723
742*cf::mapsupport::on_clean = sub { 724*cf::mapsupport::on_clean = sub {
743 my ($map) = @_; 725 my ($map) = @_;
744 726
746 defined $path or return; 728 defined $path or return;
747 729
748 unlink "$path.pst"; 730 unlink "$path.pst";
749}; 731};
750 732
751attach_to_maps prio => -10000, package => cf::mapsupport::; 733cf::map->attach (prio => -10000, package => cf::mapsupport::);
752 734
753############################################################################# 735#############################################################################
754# load/save perl data associated with player->ob objects 736# load/save perl data associated with player->ob objects
755 737
756sub all_objects(@) { 738sub all_objects(@) {
757 @_, map all_objects ($_->inv), @_ 739 @_, map all_objects ($_->inv), @_
758} 740}
759 741
760# TODO: compatibility cruft, remove when no longer needed 742# TODO: compatibility cruft, remove when no longer needed
761attach_to_players 743cf::player->attach (
762 on_load => sub { 744 on_load => sub {
763 my ($pl, $path) = @_; 745 my ($pl, $path) = @_;
764 746
765 for my $o (all_objects $pl->ob) { 747 for my $o (all_objects $pl->ob) {
766 if (my $value = $o->get_ob_key_value ("_perl_data")) { 748 if (my $value = $o->get_ob_key_value ("_perl_data")) {
768 750
769 %$o = %{ Storable::thaw pack "H*", $value }; 751 %$o = %{ Storable::thaw pack "H*", $value };
770 } 752 }
771 } 753 }
772 }, 754 },
773; 755);
774 756
775############################################################################# 757#############################################################################
776 758
777=head2 CORE EXTENSIONS 759=head2 CORE EXTENSIONS
778 760
779Functions and methods that extend core crossfire objects. 761Functions and methods that extend core crossfire objects.
762
763=head3 cf::player
780 764
781=over 4 765=over 4
782 766
783=item cf::player::exists $login 767=item cf::player::exists $login
784 768
789sub cf::player::exists($) { 773sub cf::player::exists($) {
790 cf::player::find $_[0] 774 cf::player::find $_[0]
791 or -f sprintf "%s/%s/%s/%s.pl", cf::localdir, cf::playerdir, ($_[0]) x 2; 775 or -f sprintf "%s/%s/%s/%s.pl", cf::localdir, cf::playerdir, ($_[0]) x 2;
792} 776}
793 777
778=item $player->ext_reply ($msgid, $msgtype, %msg)
779
780Sends an ext reply to the player.
781
782=cut
783
784sub cf::player::ext_reply($$$%) {
785 my ($self, $id, %msg) = @_;
786
787 $msg{msgid} = $id;
788
789 $self->send ("ext " . to_json \%msg);
790}
791
792=back
793
794=head3 cf::object::player
795
796=over 4
797
794=item $player_object->reply ($npc, $msg[, $flags]) 798=item $player_object->reply ($npc, $msg[, $flags])
795 799
796Sends a message to the player, as if the npc C<$npc> replied. C<$npc> 800Sends a message to the player, as if the npc C<$npc> replied. C<$npc>
797can be C<undef>. Does the right thing when the player is currently in a 801can be C<undef>. Does the right thing when the player is currently in a
798dialogue with the given NPC character. 802dialogue with the given NPC character.
799 803
800=cut 804=cut
801 805
802# rough implementation of a future "reply" method that works 806# rough implementation of a future "reply" method that works
803# with dialog boxes. 807# with dialog boxes.
808#TODO: the first argument must go, split into a $npc->reply_to ( method
804sub cf::object::player::reply($$$;$) { 809sub cf::object::player::reply($$$;$) {
805 my ($self, $npc, $msg, $flags) = @_; 810 my ($self, $npc, $msg, $flags) = @_;
806 811
807 $flags = cf::NDI_BROWN | cf::NDI_UNIQUE unless @_ >= 4; 812 $flags = cf::NDI_BROWN | cf::NDI_UNIQUE unless @_ >= 4;
808 813
812 $msg = $npc->name . " says: $msg" if $npc; 817 $msg = $npc->name . " says: $msg" if $npc;
813 $self->message ($msg, $flags); 818 $self->message ($msg, $flags);
814 } 819 }
815} 820}
816 821
817=item $player->ext_reply ($msgid, $msgtype, %msg)
818
819Sends an ext reply to the player.
820
821=cut
822
823sub cf::player::ext_reply($$$%) {
824 my ($self, $id, %msg) = @_;
825
826 $msg{msgid} = $id;
827
828 $self->send ("ext " . to_json \%msg);
829}
830
831=item $player_object->may ("access") 822=item $player_object->may ("access")
832 823
833Returns wether the given player is authorized to access resource "access" 824Returns wether the given player is authorized to access resource "access"
834(e.g. "command_wizcast"). 825(e.g. "command_wizcast").
835 826
842 (ref $cf::CFG{"may_$access"} 833 (ref $cf::CFG{"may_$access"}
843 ? scalar grep $self->name eq $_, @{$cf::CFG{"may_$access"}} 834 ? scalar grep $self->name eq $_, @{$cf::CFG{"may_$access"}}
844 : $cf::CFG{"may_$access"}) 835 : $cf::CFG{"may_$access"})
845} 836}
846 837
847=cut 838=head3 cf::client
848 839
849############################################################################# 840=over 4
841
842=item $client->send_drawinfo ($text, $flags)
843
844Sends a drawinfo packet to the client. Circumvents output buffering so
845should not be used under normal circumstances.
846
847=cut
848
849sub cf::client::send_drawinfo {
850 my ($self, $text, $flags) = @_;
851
852 utf8::encode $text;
853 $self->send_packet (sprintf "drawinfo %d %s", $flags, $text);
854}
855
856
857=item $success = $client->query ($flags, "text", \&cb)
858
859Queues a query to the client, calling the given callback with
860the reply text on a reply. flags can be C<cf::CS_QUERY_YESNO>,
861C<cf::CS_QUERY_SINGLECHAR> or C<cf::CS_QUERY_HIDEINPUT> or C<0>.
862
863Queries can fail, so check the return code. Or don't, as queries will become
864reliable at some point in the future.
865
866=cut
867
868sub cf::client::query {
869 my ($self, $flags, $text, $cb) = @_;
870
871 return unless $self->state == ST_PLAYING
872 || $self->state == ST_SETUP
873 || $self->state == ST_CUSTOM;
874
875 $self->state (ST_CUSTOM);
876
877 utf8::encode $text;
878 push @{ $self->{query_queue} }, [(sprintf "query %d %s", $flags, $text), $cb];
879
880 $self->send_packet ($self->{query_queue}[0][0])
881 if @{ $self->{query_queue} } == 1;
882}
883
884cf::client->attach (
885 on_reply => sub {
886 my ($ns, $msg) = @_;
887
888 # this weird shuffling is so that direct followup queries
889 # get handled first
890 my $queue = delete $ns->{query_queue};
891
892 (shift @$queue)->[1]->($msg);
893
894 push @{ $ns->{query_queue} }, @$queue;
895
896 if (@{ $ns->{query_queue} } == @$queue) {
897 if (@$queue) {
898 $ns->send_packet ($ns->{query_queue}[0][0]);
899 } else {
900 $ns->state (ST_PLAYING);
901 }
902 }
903 },
904);
905
906=back
907
850 908
851=head2 SAFE SCRIPTING 909=head2 SAFE SCRIPTING
852 910
853Functions that provide a safe environment to compile and execute 911Functions that provide a safe environment to compile and execute
854snippets of perl code without them endangering the safety of the server 912snippets of perl code without them endangering the safety of the server
869 927
870=pod 928=pod
871 929
872The following fucntions and emthods are available within a safe environment: 930The following fucntions and emthods are available within a safe environment:
873 931
874 cf::object contr pay_amount pay_player 932 cf::object contr pay_amount pay_player map
875 cf::object::player player 933 cf::object::player player
876 cf::player peaceful 934 cf::player peaceful
935 cf::map trigger
877 936
878=cut 937=cut
879 938
880for ( 939for (
881 ["cf::object" => qw(contr pay_amount pay_player)], 940 ["cf::object" => qw(contr pay_amount pay_player map)],
882 ["cf::object::player" => qw(player)], 941 ["cf::object::player" => qw(player)],
883 ["cf::player" => qw(peaceful)], 942 ["cf::player" => qw(peaceful)],
943 ["cf::map" => qw(trigger)],
884) { 944) {
885 no strict 'refs'; 945 no strict 'refs';
886 my ($pkg, @funs) = @$_; 946 my ($pkg, @funs) = @$_;
887 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"}) 947 *{"safe::$pkg\::$_"} = $safe_hole->wrap (\&{"$pkg\::$_"})
888 for @funs; 948 for @funs;
1028 sub db_sync() { 1088 sub db_sync() {
1029 db_save if $dirty; 1089 db_save if $dirty;
1030 undef $dirty; 1090 undef $dirty;
1031 } 1091 }
1032 1092
1033 my $idle = Event->idle (min => $TICK * 2.8, max => 10, repeat => 0, cb => sub { 1093 my $idle = Event->idle (min => $TICK * 2.8, max => 10, repeat => 0, data => WF_AUTOCANCEL, cb => sub {
1034 db_sync; 1094 db_sync;
1035 }); 1095 });
1036 1096
1037 sub db_dirty() { 1097 sub db_dirty() {
1038 $dirty = 1; 1098 $dirty = 1;
1052 $DB->{$_[0]} = $_[1]; 1112 $DB->{$_[0]} = $_[1];
1053 } 1113 }
1054 db_dirty; 1114 db_dirty;
1055 } 1115 }
1056 1116
1057 attach_global 1117 cf::global->attach (
1058 prio => 10000, 1118 prio => 10000,
1059 on_cleanup => sub { 1119 on_cleanup => sub {
1060 db_sync; 1120 db_sync;
1061 }, 1121 },
1062 ; 1122 );
1063} 1123}
1064 1124
1065############################################################################# 1125#############################################################################
1066# the server's main() 1126# the server's main()
1067 1127
1088 1148
1089 $msg->("reloading..."); 1149 $msg->("reloading...");
1090 1150
1091 eval { 1151 eval {
1092 # cancel all watchers 1152 # cancel all watchers
1093 $_->cancel for Event::all_watchers; 1153 for (Event::all_watchers) {
1154 $_->cancel if $_->data & WF_AUTOCANCEL;
1155 }
1094 1156
1095 # unload all extensions 1157 # unload all extensions
1096 for (@exts) { 1158 for (@exts) {
1097 $msg->("unloading <$_>"); 1159 $msg->("unloading <$_>");
1098 unload_extension $_; 1160 unload_extension $_;
1158 warn $_[0]; 1220 warn $_[0];
1159 print "$_[0]\n"; 1221 print "$_[0]\n";
1160 }; 1222 };
1161} 1223}
1162 1224
1225register "<global>", __PACKAGE__;
1226
1163register_command "perl-reload", 0, sub { 1227register_command "perl-reload" => sub {
1164 my ($who, $arg) = @_; 1228 my ($who, $arg) = @_;
1165 1229
1166 if ($who->flag (FLAG_WIZ)) { 1230 if ($who->flag (FLAG_WIZ)) {
1167 _perl_reload { 1231 _perl_reload {
1168 warn $_[0]; 1232 warn $_[0];
1169 $who->message ($_[0]); 1233 $who->message ($_[0]);
1170 }; 1234 };
1171 } 1235 }
1172}; 1236};
1173 1237
1174register "<global>", __PACKAGE__;
1175
1176unshift @INC, $LIBDIR; 1238unshift @INC, $LIBDIR;
1177 1239
1178$TICK_WATCHER = Event->timer ( 1240$TICK_WATCHER = Event->timer (
1179 prio => 1, 1241 prio => 0,
1180 async => 1,
1181 at => $NEXT_TICK || 1, 1242 at => $NEXT_TICK || 1,
1243 data => WF_AUTOCANCEL,
1182 cb => sub { 1244 cb => sub {
1183 cf::server_tick; # one server iteration 1245 cf::server_tick; # one server iteration
1184 1246
1185 my $NOW = Event::time; 1247 my $NOW = Event::time;
1186 $NEXT_TICK += $TICK; 1248 $NEXT_TICK += $TICK;
1196IO::AIO::max_poll_time $TICK * 0.2; 1258IO::AIO::max_poll_time $TICK * 0.2;
1197 1259
1198Event->io (fd => IO::AIO::poll_fileno, 1260Event->io (fd => IO::AIO::poll_fileno,
1199 poll => 'r', 1261 poll => 'r',
1200 prio => 5, 1262 prio => 5,
1263 data => WF_AUTOCANCEL,
1201 cb => \&IO::AIO::poll_cb); 1264 cb => \&IO::AIO::poll_cb);
1202 1265
12031 12661
1204 1267

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines