Debian Codegraph @

plugins/cfpython/cfpython.c

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 /*****************************************************************************/
2 /* CFPython - A Python module for Crossfire RPG. */
3 /*****************************************************************************/
4 /* This is the third version of the Crossfire Scripting Engine. */
5 /* The first version used Guile. It was directly integrated in the server */
6 /* code, but since Guile wasn't perceived as an easy-to-learn, easy-to-use */
7 /* language by many, it was dropped in favor of Python. */
8 /* The second version, CFPython 1.0, was included as a plugin and provided */
9 /* just about the same level of functionality the current version has. But */
10 /* it used a rather counter-intuitive, procedural way of presenting things. */
11 /* */
12 /* CFPython 2.0 aims at correcting many of the design flaws crippling the */
13 /* older version. It is also the first plugin to be implemented using the */
14 /* new interface, that doesn't need awkward stuff like the horrible CFParm */
15 /* structure. For the Python writer, things should probably be easier and */
16 /* lead to more readable code: instead of writing "CFPython.getObjectXPos(ob)*/
17 /* he/she now can simply write "ob.X". */
18 /* */
19 /*****************************************************************************/
20 /* Please note that it is still very beta - some of the functions may not */
21 /* work as expected and could even cause the server to crash. */
22 /*****************************************************************************/
23 /* Version history: */
24 /* 0.1 "Ophiuchus" - Initial Alpha release */
25 /* 0.5 "Stalingrad" - Message length overflow corrected. */
26 /* 0.6 "Kharkov" - Message and Write correctly redefined. */
27 /* 0.7 "Koursk" - Setting informations implemented. */
28 /* 1.0a "Petersburg" - Last "old-fashioned" version, never submitted to CVS.*/
29 /* 2.0 "Arkangelsk" - First release of the 2.x series. */
30 /*****************************************************************************/
31 /* Version: 2.0beta8 (also known as "Alexander") */
32 /* Contact: [email protected] */
33 /*****************************************************************************/
34 /* That code is placed under the GNU General Public Licence (GPL) */
35 /* (C)2001-2005 by Chachkoff Yann (Feel free to deliver your complaints) */
36 /*****************************************************************************/
37 /* CrossFire, A Multiplayer game for X-windows */
38 /* */
39 /* Copyright (C) 2000 Mark Wedel */
40 /* Copyright (C) 1992 Frank Tore Johansen */
41 /* */
42 /* This program is free software; you can redistribute it and/or modify */
43 /* it under the terms of the GNU General Public License as published by */
44 /* the Free Software Foundation; either version 2 of the License, or */
45 /* (at your option) any later version. */
46 /* */
47 /* This program is distributed in the hope that it will be useful, */
48 /* but WITHOUT ANY WARRANTY; without even the implied warranty of */
49 /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
50 /* GNU General Public License for more details. */
51 /* */
52 /* You should have received a copy of the GNU General Public License */
53 /* along with this program; if not, write to the Free Software */
54 /* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
55 /* */
56 /*****************************************************************************/
57
58 /* First let's include the header file needed */
59
60 #include <cfpython.h>
61 #include <fcntl.h>
62 #include <stdarg.h>
63 #include <node.h>
64 #include <svnversion.h>
65
66 CF_PLUGIN char SvnRevPlugin[] = SVN_REV;
67
68 #define PYTHON_DEBUG /* give us some general infos out */
69 #define PYTHON_CACHE_SIZE 16 /* number of python scripts to store the bytecode of at a time */
70
71 /**
72 * One compiled script, cached in memory.
73 */
74 typedef struct {
75 sstring file; /**< Script full path. */
76 PyCodeObject *code; /**< Compiled code, NULL if there was an error. */
77 time_t cached_time, /**< Time this cache entry was created. */
78 used_time; /**< Last use of this cache entry. */
79 } pycode_cache_entry;
80
81 /* This structure is used to define one python-implemented crossfire command.*/
82 typedef struct PythonCmdStruct {
83 sstring name; /* The name of the command, as known in the game. */
84 sstring script; /* The name of the script file to bind. */
85 double speed; /* The speed of the command execution. */
86 } PythonCmd;
87
88 /* This plugin allows up to 1024 custom commands. */
89 #define NR_CUSTOM_CMD 1024
90
91 /** Commands defined by scripts. */
92 static PythonCmd CustomCommand[NR_CUSTOM_CMD];
93
94 /** Cached compiled scripts. */
95 static pycode_cache_entry pycode_cache[PYTHON_CACHE_SIZE];
96
97 static PyObject *CFPythonError;
98
99 /** Set up an Python exception object. */
100 static void set_exception(const char *fmt, ...) {
101 char buf[1024];
102 va_list arg;
103
104 va_start(arg, fmt);
105 vsnprintf(buf, sizeof(buf), fmt, arg);
106 va_end(arg);
107
108 PyErr_SetString(PyExc_ValueError, buf);
109 }
110
111 CFPContext *context_stack;
112
113 CFPContext *current_context;
114
115 static int current_command = -999;
116
117 static PyObject *shared_data = NULL;
118
119 static PyObject *private_data = NULL;
120
121 static PyObject *registerGEvent(PyObject *self, PyObject *args) {
122 int eventcode;
123
124 if (!PyArg_ParseTuple(args, "i", &eventcode))
125 return NULL;
126
127 cf_system_register_global_event(eventcode, PLUGIN_NAME, cfpython_globalEventListener);
128
129 Py_INCREF(Py_None);
130 return Py_None;
131 }
132
133 static PyObject *unregisterGEvent(PyObject *self, PyObject *args) {
134 int eventcode;
135
136 if (!PyArg_ParseTuple(args, "i", &eventcode))
137 return NULL;
138
139 cf_system_unregister_global_event(EVENT_TELL, PLUGIN_NAME);
140
141 Py_INCREF(Py_None);
142 return Py_None;
143 }
144
145 static PyObject *createCFObject(PyObject *self, PyObject *args) {
146 object *op;
147
148 op = cf_create_object();
149
150 return Crossfire_Object_wrap(op);
151 }
152
153 static PyObject *createCFObjectByName(PyObject *self, PyObject *args) {
154 char *obname;
155 object *op;
156
157 if (!PyArg_ParseTuple(args, "s", &obname))
158 return NULL;
159
160 op = cf_create_object_by_name(obname);
161
162 return Crossfire_Object_wrap(op);
163 }
164
165 static PyObject *getCFPythonVersion(PyObject *self, PyObject *args) {
166 int i = 2044;
167
168 return Py_BuildValue("i", i);
169 }
170
171 static PyObject *getReturnValue(PyObject *self, PyObject *args) {
172 return Py_BuildValue("i", current_context->returnvalue);
173 }
174
175 static PyObject *setReturnValue(PyObject *self, PyObject *args) {
176 int i;
177
178 if (!PyArg_ParseTuple(args, "i", &i))
179 return NULL;
180 current_context->returnvalue = i;
181 Py_INCREF(Py_None);
182 return Py_None;
183 }
184
185 static PyObject *matchString(PyObject *self, PyObject *args) {
186 char *premiere;
187 char *seconde;
188 const char *result;
189
190 if (!PyArg_ParseTuple(args, "ss", &premiere, &seconde))
191 return NULL;
192
193 result = cf_re_cmp(premiere, seconde);
194 if (result != NULL)
195 return Py_BuildValue("i", 1);
196 else
197 return Py_BuildValue("i", 0);
198 }
199
200 static PyObject *findPlayer(PyObject *self, PyObject *args) {
201 player *foundpl;
202 char *txt;
203
204 if (!PyArg_ParseTuple(args, "s", &txt))
205 return NULL;
206
207 foundpl = cf_player_find(txt);
208
209 if (foundpl != NULL)
210 return Py_BuildValue("O", Crossfire_Object_wrap(foundpl->ob));
211 else {
212 Py_INCREF(Py_None);
213 return Py_None;
214 }
215 }
216
217 static PyObject *readyMap(PyObject *self, PyObject *args) {
218 char *mapname;
219 mapstruct *map;
220 int flags = 0;
221
222 if (!PyArg_ParseTuple(args, "s|i", &mapname, &flags))
223 return NULL;
224
225 map = cf_map_get_map(mapname, flags);
226
227 return Crossfire_Map_wrap(map);
228 }
229
230 static PyObject *createMap(PyObject *self, PyObject *args) {
231 int sizex, sizey;
232 mapstruct *map;
233
234 if (!PyArg_ParseTuple(args, "ii", &sizex, &sizey))
235 return NULL;
236
237 map = cf_get_empty_map(sizex, sizey);
238
239 return Crossfire_Map_wrap(map);
240 }
241
242 static PyObject *getMapDirectory(PyObject *self, PyObject *args) {
243 return Py_BuildValue("s", cf_get_directory(0));
244 }
245
246 static PyObject *getUniqueDirectory(PyObject *self, PyObject *args) {
247 return Py_BuildValue("s", cf_get_directory(1));
248 }
249
250 static PyObject *getTempDirectory(PyObject *self, PyObject *args) {
251 return Py_BuildValue("s", cf_get_directory(2));
252 }
253
254 static PyObject *getConfigDirectory(PyObject *self, PyObject *args) {
255 return Py_BuildValue("s", cf_get_directory(3));
256 }
257
258 static PyObject *getLocalDirectory(PyObject *self, PyObject *args) {
259 return Py_BuildValue("s", cf_get_directory(4));
260 }
261
262 static PyObject *getPlayerDirectory(PyObject *self, PyObject *args) {
263 return Py_BuildValue("s", cf_get_directory(5));
264 }
265
266 static PyObject *getDataDirectory(PyObject *self, PyObject *args) {
267 return Py_BuildValue("s", cf_get_directory(6));
268 }
269
270 static PyObject *getWhoAmI(PyObject *self, PyObject *args) {
271 if (!current_context->who) {
272 Py_INCREF(Py_None);
273 return Py_None;
274 }
275 Py_INCREF(current_context->who);
276 return current_context->who;
277 }
278
279 static PyObject *getWhoIsActivator(PyObject *self, PyObject *args) {
280 if (!current_context->activator) {
281 Py_INCREF(Py_None);
282 return Py_None;
283 }
284 Py_INCREF(current_context->activator);
285 return current_context->activator;
286 }
287
288 static PyObject *getWhoIsThird(PyObject *self, PyObject *args) {
289 if (!current_context->third) {
290 Py_INCREF(Py_None);
291 return Py_None;
292 }
293 Py_INCREF(current_context->third);
294 return current_context->third;
295 }
296
297 static PyObject *getWhatIsMessage(PyObject *self, PyObject *args) {
298 if (*current_context->message == '\0')
299 return Py_BuildValue("");
300 else
301 return Py_BuildValue("s", current_context->message);
302 }
303
304 static PyObject *getScriptName(PyObject *self, PyObject *args) {
305 return Py_BuildValue("s", current_context->script);
306 }
307
308 static PyObject *getScriptParameters(PyObject *self, PyObject *args) {
309 if (!*current_context->options) {
310 Py_INCREF(Py_None);
311 return Py_None;
312 }
313 return Py_BuildValue("s", current_context->options);
314 }
315
316 static PyObject *getEvent(PyObject *self, PyObject *args) {
317 if (!current_context->event) {
318 Py_INCREF(Py_None);
319 return Py_None;
320 }
321 Py_INCREF(current_context->event);
322 return current_context->event;
323 }
324
325 static PyObject *getPrivateDictionary(PyObject *self, PyObject *args) {
326 PyObject *data;
327
328 data = PyDict_GetItemString(private_data, current_context->script);
329 if (!data) {
330 data = PyDict_New();
331 PyDict_SetItemString(private_data, current_context->script, data);
332 Py_DECREF(data);
333 }
334 Py_INCREF(data);
335 return data;
336 }
337
338 static PyObject *getSharedDictionary(PyObject *self, PyObject *args) {
339 Py_INCREF(shared_data);
340 return shared_data;
341 }
342
343 static PyObject *getArchetypes(PyObject *self, PyObject *args) {
344 PyObject *list;
345 archetype *arch;
346
347 list = PyList_New(0);
348 arch = cf_archetype_get_first();
349 while (arch) {
350 PyList_Append(list, Crossfire_Archetype_wrap(arch));
351 arch = cf_archetype_get_next(arch);
352 }
353 return list;
354 }
355
356 static PyObject *getPlayers(PyObject *self, PyObject *args) {
357 PyObject *list;
358 object *pl;
359
360 list = PyList_New(0);
361 pl = cf_object_get_object_property(NULL, CFAPI_PLAYER_PROP_NEXT);
362 while (pl) {
363 PyList_Append(list, Crossfire_Object_wrap(pl));
364 pl = cf_object_get_object_property(pl, CFAPI_PLAYER_PROP_NEXT);
365 }
366 return list;
367 }
368
369 static PyObject *getMaps(PyObject *self, PyObject *args) {
370 PyObject *list;
371 mapstruct *map;
372
373 list = PyList_New(0);
374 map = cf_map_get_first();
375 while (map) {
376 PyList_Append(list, Crossfire_Map_wrap(map));
377 map = cf_map_get_map_property(map, CFAPI_MAP_PROP_NEXT);
378 }
379 return list;
380 }
381
382 static PyObject *getParties(PyObject *self, PyObject *args) {
383 PyObject *list;
384 partylist *party;
385
386 list = PyList_New(0);
387 party = cf_party_get_first();
388 while (party) {
389 PyList_Append(list, Crossfire_Party_wrap(party));
390 party = cf_party_get_next(party);
391 }
392 return list;
393 }
394
395 static PyObject *getRegions(PyObject *self, PyObject *args) {
396 PyObject *list;
397 region *reg;
398
399 list = PyList_New(0);
400 reg = cf_region_get_first();
401 while (reg) {
402 PyList_Append(list, Crossfire_Region_wrap(reg));
403 reg = cf_region_get_next(reg);
404 }
405 return list;
406 }
407
408 static PyObject *getFriendlyList(PyObject *self, PyObject *args) {
409 PyObject *list;
410 object *ob;
411
412 list = PyList_New(0);
413 ob = cf_friendlylist_get_first();
414 while (ob) {
415 PyList_Append(list, Crossfire_Object_wrap(ob));
416 ob = cf_friendlylist_get_next(ob);
417 }
418 return list;
419 }
420
421 static PyObject *registerCommand(PyObject *self, PyObject *args) {
422 char *cmdname;
423 char *scriptname;
424 double cmdspeed;
425 int i;
426
427 if (!PyArg_ParseTuple(args, "ssd", &cmdname, &scriptname, &cmdspeed))
428 return NULL;
429
430 if (cmdspeed < 0) {
431 set_exception("speed must not be negative");
432 return NULL;
433 }
434
435 for (i = 0; i < NR_CUSTOM_CMD; i++) {
436 if (CustomCommand[i].name != NULL) {
437 if (!strcmp(CustomCommand[i].name, cmdname)) {
438 set_exception("command '%s' is already registered", cmdname);
439 return NULL;
440 }
441 }
442 }
443 for (i = 0; i < NR_CUSTOM_CMD; i++) {
444 if (CustomCommand[i].name == NULL) {
445 CustomCommand[i].name = cf_add_string(cmdname);
446 CustomCommand[i].script = cf_add_string(scriptname);
447 CustomCommand[i].speed = cmdspeed;
448 break;
449 }
450 }
451
452 Py_INCREF(Py_None);
453 return Py_None;
454 }
455
456 static PyObject *getTime(PyObject *self, PyObject *args) {
457 PyObject *list;
458 timeofday_t tod;
459
460 cf_get_time(&tod);
461
462 list = PyList_New(0);
463 PyList_Append(list, Py_BuildValue("i", tod.year));
464 PyList_Append(list, Py_BuildValue("i", tod.month));
465 PyList_Append(list, Py_BuildValue("i", tod.day));
466 PyList_Append(list, Py_BuildValue("i", tod.hour));
467 PyList_Append(list, Py_BuildValue("i", tod.minute));
468 PyList_Append(list, Py_BuildValue("i", tod.dayofweek));
469 PyList_Append(list, Py_BuildValue("i", tod.weekofmonth));
470 PyList_Append(list, Py_BuildValue("i", tod.season));
471 PyList_Append(list, Py_BuildValue("i", tod.periodofday));
472
473 return list;
474 }
475
476 static PyObject *destroyTimer(PyObject *self, PyObject *args) {
477 int id;
478
479 if (!PyArg_ParseTuple(args, "i", &id))
480 return NULL;
481 return Py_BuildValue("i", cf_timer_destroy(id));
482 }
483
484 static PyObject *getMapHasBeenLoaded(PyObject *self, PyObject *args) {
485 char *name;
486
487 if (!PyArg_ParseTuple(args, "s", &name))
488 return NULL;
489 return Crossfire_Map_wrap(cf_map_has_been_loaded(name));
490 }
491
492 static PyObject *findFace(PyObject *self, PyObject *args) {
493 char *name;
494
495 if (!PyArg_ParseTuple(args, "s", &name))
496 return NULL;
497 return Py_BuildValue("i", cf_find_face(name, 0));
498 }
499
500 static PyObject *log_message(PyObject *self, PyObject *args) {
501 LogLevel level;
502 int intLevel;
503 char *message;
504
505 if (!PyArg_ParseTuple(args, "is", &intLevel, &message))
506 return NULL;
507
508 switch (intLevel) {
509 case llevError:
510 level = llevError;
511 break;
512
513 case llevInfo:
514 level = llevInfo;
515 break;
516
517 case llevDebug:
518 level = llevDebug;
519 break;
520
521 case llevMonster:
522 level = llevMonster;
523 break;
524
525 default:
526 return NULL;
527 }
528 if ((message != NULL) && (message[strlen(message)] == '\n'))
529 cf_log(level, "CFPython: %s", message);
530 else
531 cf_log(level, "CFPython: %s\n", message);
532 Py_INCREF(Py_None);
533 return Py_None;
534 }
535
536 static PyObject *findAnimation(PyObject *self, PyObject *args) {
537 char *name;
538
539 if (!PyArg_ParseTuple(args, "s", &name))
540 return NULL;
541 return Py_BuildValue("i", cf_find_animation(name));
542 }
543
544 static PyObject *getSeasonName(PyObject *self, PyObject *args) {
545 int i;
546
547 if (!PyArg_ParseTuple(args, "i", &i))
548 return NULL;
549 return Py_BuildValue("s", cf_get_season_name(i));
550 }
551
552 static PyObject *getMonthName(PyObject *self, PyObject *args) {
553 int i;
554
555 if (!PyArg_ParseTuple(args, "i", &i))
556 return NULL;
557 return Py_BuildValue("s", cf_get_month_name(i));
558 }
559
560 static PyObject *getWeekdayName(PyObject *self, PyObject *args) {
561 int i;
562
563 if (!PyArg_ParseTuple(args, "i", &i))
564 return NULL;
565 return Py_BuildValue("s", cf_get_weekday_name(i));
566 }
567
568 static PyObject *getPeriodofdayName(PyObject *self, PyObject *args) {
569 int i;
570
571 if (!PyArg_ParseTuple(args, "i", &i))
572 return NULL;
573 return Py_BuildValue("s", cf_get_periodofday_name(i));
574 }
575
576 static PyObject *addReply(PyObject *self, PyObject *args) {
577 char *word, *reply;
578 talk_info *talk;
579
580 if (current_context->talk == NULL) {
581 set_exception("not in a dialog context");
582 return NULL;
583 }
584 talk = current_context->talk;
585
586 if (!PyArg_ParseTuple(args, "ss", &word, &reply)) {
587 return NULL;
588 }
589
590 if (talk->replies_count == MAX_REPLIES) {
591 set_exception("too many replies");
592 return NULL;
593 }
594
595 talk->replies_words[talk->replies_count] = cf_add_string(word);
596 talk->replies[talk->replies_count] = cf_add_string(reply);
597 talk->replies_count++;
598 Py_INCREF(Py_None);
599 return Py_None;
600
601 }
602
603 static PyObject *setPlayerMessage(PyObject *self, PyObject *args) {
604 char *message;
605 int type = rt_reply;
606
607 if (current_context->talk == NULL) {
608 set_exception("not in a dialog context");
609 return NULL;
610 }
611
612 if (!PyArg_ParseTuple(args, "s|i", &message, &type)) {
613 return NULL;
614 }
615
616 if (current_context->talk->message != NULL)
617 cf_free_string(current_context->talk->message);
618 current_context->talk->message = cf_add_string(message);
619 current_context->talk->message_type = type;
620
621 Py_INCREF(Py_None);
622 return Py_None;
623 }
624
625 static PyObject *npcSay(PyObject *self, PyObject *args) {
626 Crossfire_Object *npc = NULL;
627 char *message, buf[2048];
628
629 if (!PyArg_ParseTuple(args, "O!s", &Crossfire_ObjectType, &npc, &message))
630 return NULL;
631
632 if (current_context->talk == NULL) {
633 set_exception("not in a dialog context");
634 return NULL;
635 }
636
637 if (current_context->talk->npc_msg_count == MAX_NPC) {
638 set_exception("too many NPCs");
639 return NULL;
640 }
641
642 if (strlen(message) >= sizeof(buf) - 1)
643 cf_log(llevError, "warning, too long message in npcSay, will be truncated");
644 /** @todo fix by wrapping monster_format_say() (or the whole talk structure methods) */
645 snprintf(buf, sizeof(buf), "%s says: %s", npc->obj->name, message);
646
647 current_context->talk->npc_msgs[current_context->talk->npc_msg_count] = cf_add_string(buf);
648 current_context->talk->npc_msg_count++;
649
650 Py_INCREF(Py_None);
651 return Py_None;
652 }
653
654 static PyObject *costStringFromValue(PyObject *self, PyObject *args) {
655 uint64_t value;
656 char buf[2048];
657 int largest_coin = 0;
658
659 if (!PyArg_ParseTuple(args, "L|i", &value, &largest_coin))
660 return NULL;
661
662 cf_cost_string_from_value(value, largest_coin, buf, sizeof(buf));
663 return Py_BuildValue("s", buf);
664 }
665
666 static PyMethodDef CFPythonMethods[] = {
667 { "WhoAmI", getWhoAmI, METH_NOARGS, NULL },
668 { "WhoIsActivator", getWhoIsActivator, METH_NOARGS, NULL },
669 { "WhoIsOther", getWhoIsThird, METH_NOARGS, NULL },
670 { "WhatIsMessage", getWhatIsMessage, METH_NOARGS, NULL },
671 { "ScriptName", getScriptName, METH_NOARGS, NULL },
672 { "ScriptParameters", getScriptParameters, METH_NOARGS, NULL },
673 { "WhatIsEvent", getEvent, METH_NOARGS, NULL },
674 { "MapDirectory", getMapDirectory, METH_NOARGS, NULL },
675 { "UniqueDirectory", getUniqueDirectory, METH_NOARGS, NULL },
676 { "TempDirectory", getTempDirectory, METH_NOARGS, NULL },
677 { "ConfigDirectory", getConfigDirectory, METH_NOARGS, NULL },
678 { "LocalDirectory", getLocalDirectory, METH_NOARGS, NULL },
679 { "PlayerDirectory", getPlayerDirectory, METH_NOARGS, NULL },
680 { "DataDirectory", getDataDirectory, METH_NOARGS, NULL },
681 { "ReadyMap", readyMap, METH_VARARGS, NULL },
682 { "CreateMap", createMap, METH_VARARGS, NULL },
683 { "FindPlayer", findPlayer, METH_VARARGS, NULL },
684 { "MatchString", matchString, METH_VARARGS, NULL },
685 { "GetReturnValue", getReturnValue, METH_NOARGS, NULL },
686 { "SetReturnValue", setReturnValue, METH_VARARGS, NULL },
687 { "PluginVersion", getCFPythonVersion, METH_NOARGS, NULL },
688 { "CreateObject", createCFObject, METH_NOARGS, NULL },
689 { "CreateObjectByName", createCFObjectByName, METH_VARARGS, NULL },
690 { "GetPrivateDictionary", getPrivateDictionary, METH_NOARGS, NULL },
691 { "GetSharedDictionary", getSharedDictionary, METH_NOARGS, NULL },
692 { "GetPlayers", getPlayers, METH_NOARGS, NULL },
693 { "GetArchetypes", getArchetypes, METH_NOARGS, NULL },
694 { "GetMaps", getMaps, METH_NOARGS, NULL },
695 { "GetParties", getParties, METH_NOARGS, NULL },
696 { "GetRegions", getRegions, METH_NOARGS, NULL },
697 { "GetFriendlyList", getFriendlyList, METH_NOARGS, NULL },
698 { "RegisterCommand", registerCommand, METH_VARARGS, NULL },
699 { "RegisterGlobalEvent", registerGEvent, METH_VARARGS, NULL },
700 { "UnregisterGlobalEvent", unregisterGEvent, METH_VARARGS, NULL },
701 { "GetTime", getTime, METH_NOARGS, NULL },
702 { "DestroyTimer", destroyTimer, METH_VARARGS, NULL },
703 { "MapHasBeenLoaded", getMapHasBeenLoaded, METH_VARARGS, NULL },
704 { "Log", log_message, METH_VARARGS, NULL },
705 { "FindFace", findFace, METH_VARARGS, NULL },
706 { "FindAnimation", findAnimation, METH_VARARGS, NULL },
707 { "GetSeasonName", getSeasonName, METH_VARARGS, NULL },
708 { "GetMonthName", getMonthName, METH_VARARGS, NULL },
709 { "GetWeekdayName", getWeekdayName, METH_VARARGS, NULL },
710 { "GetPeriodofdayName", getPeriodofdayName, METH_VARARGS, NULL },
711 { "AddReply", addReply, METH_VARARGS, NULL },
712 { "SetPlayerMessage", setPlayerMessage, METH_VARARGS, NULL },
713 { "NPCSay", npcSay, METH_VARARGS, NULL },
714 { "CostStringFromValue", costStringFromValue, METH_VARARGS, NULL },
715 { NULL, NULL, 0, NULL }
716 };
717
718 static void initContextStack(void) {
719 current_context = NULL;
720 context_stack = NULL;
721 }
722
723 static void pushContext(CFPContext *context) {
724 if (current_context == NULL) {
725 context_stack = context;
726 context->down = NULL;
727 } else {
728 context->down = current_context;
729 }
730 current_context = context;
731 }
732
733 static CFPContext *popContext(void) {
734 CFPContext *oldcontext;
735
736 if (current_context != NULL) {
737 oldcontext = current_context;
738 current_context = current_context->down;
739 return oldcontext;
740 }
741 else
742 return NULL;
743 }
744
745 static void freeContext(CFPContext *context) {
746 Py_XDECREF(context->event);
747 Py_XDECREF(context->third);
748 Py_XDECREF(context->who);
749 Py_XDECREF(context->activator);
750 free(context);
751 }
752
753 /**
754 * Open a file in the way we need it for compilePython() and postInitPlugin().
755 */
756 static PyObject* cfpython_openpyfile(char *filename) {
757 PyObject *scriptfile;
758 #ifdef IS_PY3K
759 {
760 int fd;
761 fd = open(filename, O_RDONLY);
762 if (fd == -1)
763 return NULL;
764 scriptfile = PyFile_FromFd(fd, filename, "r", -1, NULL, NULL, NULL, 1);
765 }
766 #else
767 if (!(scriptfile = PyFile_FromString(filename, "r"))) {
768 return NULL;
769 }
770 #endif
771 return scriptfile;
772 }
773
774 /**
775 * Return a file object from a Python file (as needed for compilePython() and
776 * postInitPlugin())
777 */
778 static FILE* cfpython_pyfile_asfile(PyObject* obj) {
779 #ifdef IS_PY3K
780 return fdopen(PyObject_AsFileDescriptor(obj), "r");
781 #else
782 return PyFile_AsFile(obj);
783 #endif
784 }
785
786 /**
787 * A Python object receiving the contents of Python's stderr, and used to output
788 * to the Crossfire log instead of stderr.
789 */
790 static PyObject *catcher = NULL;
791
792 /**
793 * Trace a Python error to the Crossfire log.
794 * This uses code from:
795 * http://stackoverflow.com/questions/4307187/how-to-catch-python-stdout-in-c-code
796 * See also in initPlugin() the parts about stdOutErr.
797 */
798 static void log_python_error(void) {
799
800 PyErr_Print();
801
802 if (catcher != NULL) {
803 PyObject *output = PyObject_GetAttrString(catcher, "value"); //get the stdout and stderr from our catchOutErr object
804 #ifdef IS_PY3K
805 PyObject* empty = PyUnicode_FromString("");
806 #else
807 PyObject* empty = PyString_FromString("");
808 #endif
809
810 #ifdef IS_PY3K
811 cf_log_plain(llevError, PyUnicode_AsUTF8(output));
812 #else
813 cf_log_plain(llevError, PyString_AsString(output));
814 #endif
815 Py_DECREF(output);
816
817 PyObject_SetAttrString(catcher, "value", empty);
818 Py_DECREF(empty);
819 }
820
821 return;
822 }
823
824
825 /** Outputs the compiled bytecode for a given python file, using in-memory caching of bytecode */
826 static PyCodeObject *compilePython(char *filename) {
827 PyObject *scriptfile = NULL;
828 sstring sh_path;
829 struct stat stat_buf;
830 struct _node *n;
831 int i;
832 pycode_cache_entry *replace = NULL, *run = NULL;
833
834 if (stat(filename, &stat_buf)) {
835 cf_log(llevDebug, "cfpython - The Script file %s can't be stat:ed\n", filename);
836 return NULL;
837 }
838
839 sh_path = cf_add_string(filename);
840
841 /* Search through cache. Three cases:
842 * 1) script in cache, but older than file -> replace cached
843 * 2) script in cache and up to date -> use cached
844 * 3) script not in cache, cache not full -> add to end of cache
845 * 4) script not in cache, cache full -> replace least recently used
846 */
847 for (i = 0; i < PYTHON_CACHE_SIZE; i++) {
848 if (pycode_cache[i].file == NULL) { /* script not in cache, cache not full */
849 replace = &pycode_cache[i]; /* add to end of cache */
850 break;
851 } else if (pycode_cache[i].file == sh_path) {
852 /* script in cache */
853 if (pycode_cache[i].code == NULL || (pycode_cache[i].cached_time < stat_buf.st_mtime)) {
854 /* cache older than file, replace cached */
855 replace = &pycode_cache[i];
856 } else {
857 /* cache uptodate, use cached*/
858 replace = NULL;
859 run = &pycode_cache[i];
860 }
861 break;
862 } else if (replace == NULL || pycode_cache[i].used_time < replace->used_time)
863 /* if we haven't found it yet, set replace to the oldest cache */
864 replace = &pycode_cache[i];
865 }
866
867 /* replace a specific cache index with the file */
868 if (replace) {
869 Py_XDECREF(replace->code); /* safe to call on NULL */
870 replace->code = NULL;
871
872 /* Need to replace path string? */
873 if (replace->file != sh_path) {
874 if (replace->file) {
875 cf_free_string(replace->file);
876 }
877 replace->file = cf_add_string(sh_path);
878 }
879
880 /* Load, parse and compile. Note: because Pyhon may have been built with a
881 * different library than Crossfire, the FILE* it uses may be incompatible.
882 * Therefore we use PyFile to open the file, then convert to FILE* and get
883 * Python's own structure. Messy, but can't be helped... */
884 if (!(scriptfile = cfpython_openpyfile(filename))) {
885 cf_log(llevDebug, "cfpython - The Script file %s can't be opened\n", filename);
886 cf_free_string(sh_path);
887 return NULL;
888 } else {
889 /* Note: FILE* being opaque, it works, but the actual structure may be different! */
890 FILE* pyfile = cfpython_pyfile_asfile(scriptfile);
891 if ((n = PyParser_SimpleParseFile(pyfile, filename, Py_file_input))) {
892 replace->code = PyNode_Compile(n, filename);
893 PyNode_Free(n);
894 }
895
896 if (PyErr_Occurred())
897 log_python_error();
898 else
899 replace->cached_time = stat_buf.st_mtime;
900 run = replace;
901 }
902 }
903
904 cf_free_string(sh_path);
905
906 if (scriptfile) {
907 Py_DECREF(scriptfile);
908 }
909
910 assert(run != NULL);
911 run->used_time = time(NULL);
912 return run->code;
913 }
914
915 static int do_script(CFPContext *context, int silent) {
916 PyCodeObject *pycode;
917 PyObject *dict;
918 PyObject *ret;
919 #if 0
920 PyObject *list;
921 int item;
922 #endif
923
924 pycode = compilePython(context->script);
925 if (pycode) {
926 pushContext(context);
927 dict = PyDict_New();
928 PyDict_SetItemString(dict, "__builtins__", PyEval_GetBuiltins());
929 #ifdef IS_PY3K
930 ret = PyEval_EvalCode((PyObject *)pycode, dict, NULL);
931 #else
932 ret = PyEval_EvalCode(pycode, dict, NULL);
933 #endif
934 if (PyErr_Occurred()) {
935 log_python_error();
936 }
937 Py_XDECREF(ret);
938 #if 0
939 printf("cfpython - %d items in heap\n", PyDict_Size(dict));
940 list = PyDict_Values(dict);
941 for (item = PyList_Size(list)-1; item >= 0; item--) {
942 dict = PyList_GET_ITEM(list, item);
943 ret = PyObject_Str(dict);
944 printf(" ref %s = %d\n", PyString_AsString(ret), dict->ob_refcnt);
945 Py_XDECREF(ret);
946 }
947 Py_DECREF(list);
948 #endif
949 Py_DECREF(dict);
950 return 1;
951 } else
952 return 0;
953 }
954
955 typedef struct {
956 const char *name;
957 const int value;
958 } CFConstant;
959
960 static void addConstants(PyObject *module, const char *name, const CFConstant *constants) {
961 int i = 0;
962 char tmp[1024];
963 PyObject *new;
964 PyObject *dict;
965
966 snprintf(tmp, sizeof(tmp), "Crossfire_%s", name);
967
968 new = PyModule_New(tmp);
969 dict = PyDict_New();
970
971 while (constants[i].name != NULL) {
972 PyModule_AddIntConstant(new, (char *)constants[i].name, constants[i].value);
973 #ifdef IS_PY3K
974 PyDict_SetItem(dict, PyLong_FromLong(constants[i].value), PyUnicode_FromString(constants[i].name));
975 #else
976 PyDict_SetItem(dict, PyLong_FromLong(constants[i].value), PyString_FromString(constants[i].name));
977 #endif
978 i++;
979 }
980 PyDict_SetItemString(PyModule_GetDict(module), name, new);
981
982 snprintf(tmp, sizeof(tmp), "%sName", name);
983 PyDict_SetItemString(PyModule_GetDict(module), tmp, dict);
984 Py_DECREF(dict);
985 }
986 /**
987 * Do half the job of addConstants. It only
988 * Set constantc, but not a hashtable to get constant
989 * names from values. To be used for collections of constants
990 * which are not unique but still are usefull for scripts
991 */
992 static void addSimpleConstants(PyObject *module, const char *name, const CFConstant *constants) {
993 int i = 0;
994 char tmp[1024];
995 PyObject *new;
996
997 snprintf(tmp, sizeof(tmp), "Crossfire_%s", name);
998
999 new = PyModule_New(tmp);
1000
1001 while (constants[i].name != NULL) {
1002 PyModule_AddIntConstant(new, (char *)constants[i].name, constants[i].value);
1003 i++;
1004 }
1005 PyDict_SetItemString(PyModule_GetDict(module), name, new);
1006 }
1007
1008 static void initConstants(PyObject *module) {
1009 static const CFConstant cstDirection[] = {
1010 { "NORTH", 1 },
1011 { "NORTHEAST", 2 },
1012 { "EAST", 3 },
1013 { "SOUTHEAST", 4 },
1014 { "SOUTH", 5 },
1015 { "SOUTHWEST", 6 },
1016 { "WEST", 7 },
1017 { "NORTHWEST", 8 },
1018 { NULL, 0 }
1019 };
1020
1021 static const CFConstant cstType[] = {
1022 { "PLAYER", PLAYER },
1023 { "TRANSPORT", TRANSPORT },
1024 { "ROD", ROD },
1025 { "TREASURE", TREASURE },
1026 { "POTION", POTION },
1027 { "FOOD", FOOD },
1028 { "POISON", POISON },
1029 { "BOOK", BOOK },
1030 { "CLOCK", CLOCK },
1031 { "ARROW", ARROW },
1032 { "BOW", BOW },
1033 { "WEAPON", WEAPON },
1034 { "ARMOUR", ARMOUR },
1035 { "PEDESTAL", PEDESTAL },
1036 { "ALTAR", ALTAR },
1037 { "LOCKED_DOOR", LOCKED_DOOR },
1038 { "SPECIAL_KEY", SPECIAL_KEY },
1039 { "MAP", MAP },
1040 { "DOOR", DOOR },
1041 { "KEY", KEY },
1042 { "TIMED_GATE", TIMED_GATE },
1043 { "TRIGGER", TRIGGER },
1044 { "GRIMREAPER", GRIMREAPER },
1045 { "MAGIC_EAR", MAGIC_EAR },
1046 { "TRIGGER_BUTTON", TRIGGER_BUTTON },
1047 { "TRIGGER_ALTAR", TRIGGER_ALTAR },
1048 { "TRIGGER_PEDESTAL", TRIGGER_PEDESTAL },
1049 { "SHIELD", SHIELD },
1050 { "HELMET", HELMET },
1051 { "MONEY", MONEY },
1052 { "CLASS", CLASS },
1053 { "AMULET", AMULET },
1054 { "PLAYERMOVER", PLAYERMOVER },
1055 { "TELEPORTER", TELEPORTER },
1056 { "CREATOR", CREATOR },
1057 { "SKILL", SKILL },
1058 { "EARTHWALL", EARTHWALL },
1059 { "GOLEM", GOLEM },
1060 { "THROWN_OBJ", THROWN_OBJ },
1061 { "BLINDNESS", BLINDNESS },
1062 { "GOD", GOD },
1063 { "DETECTOR", DETECTOR },
1064 { "TRIGGER_MARKER", TRIGGER_MARKER },
1065 { "DEAD_OBJECT", DEAD_OBJECT },
1066 { "DRINK", DRINK },
1067 { "MARKER", MARKER },
1068 { "HOLY_ALTAR", HOLY_ALTAR },
1069 { "PLAYER_CHANGER", PLAYER_CHANGER },
1070 { "BATTLEGROUND", BATTLEGROUND },
1071 { "PEACEMAKER", PEACEMAKER },
1072 { "GEM", GEM },
1073 { "FIREWALL", FIREWALL },
1074 { "CHECK_INV", CHECK_INV },
1075 { "MOOD_FLOOR", MOOD_FLOOR },
1076 { "EXIT", EXIT },
1077 { "ENCOUNTER", ENCOUNTER },
1078 { "SHOP_FLOOR", SHOP_FLOOR },
1079 { "SHOP_MAT", SHOP_MAT },
1080 { "RING", RING },
1081 { "FLOOR", FLOOR },
1082 { "FLESH", FLESH },
1083 { "INORGANIC", INORGANIC },
1084 { "SKILL_TOOL", SKILL_TOOL },
1085 { "LIGHTER", LIGHTER },
1086 { "WALL", WALL },
1087 { "MISC_OBJECT", MISC_OBJECT },
1088 { "MONSTER", MONSTER },
1089 { "LAMP", LAMP },
1090 { "DUPLICATOR", DUPLICATOR },
1091 { "SPELLBOOK", SPELLBOOK },
1092 { "CLOAK", CLOAK },
1093 { "SPINNER", SPINNER },
1094 { "GATE", GATE },
1095 { "BUTTON", BUTTON },
1096 { "CF_HANDLE", CF_HANDLE },
1097 { "HOLE", HOLE },
1098 { "TRAPDOOR", TRAPDOOR },
1099 { "SIGN", SIGN },
1100 { "BOOTS", BOOTS },
1101 { "GLOVES", GLOVES },
1102 { "SPELL", SPELL },
1103 { "SPELL_EFFECT", SPELL_EFFECT },
1104 { "CONVERTER", CONVERTER },
1105 { "BRACERS", BRACERS },
1106 { "POISONING", POISONING },
1107 { "SAVEBED", SAVEBED },
1108 { "WAND", WAND },
1109 { "SCROLL", SCROLL },
1110 { "DIRECTOR", DIRECTOR },
1111 { "GIRDLE", GIRDLE },
1112 { "FORCE", FORCE },
1113 { "POTION_RESIST_EFFECT", POTION_RESIST_EFFECT },
1114 { "EVENT_CONNECTOR", EVENT_CONNECTOR },
1115 { "CLOSE_CON", CLOSE_CON },
1116 { "CONTAINER", CONTAINER },
1117 { "ARMOUR_IMPROVER", ARMOUR_IMPROVER },
1118 { "WEAPON_IMPROVER", WEAPON_IMPROVER },
1119 { "SKILLSCROLL", SKILLSCROLL },
1120 { "DEEP_SWAMP", DEEP_SWAMP },
1121 { "IDENTIFY_ALTAR", IDENTIFY_ALTAR },
1122 { "SHOP_INVENTORY", SHOP_INVENTORY },
1123 { "RUNE", RUNE },
1124 { "TRAP", TRAP },
1125 { "POWER_CRYSTAL", POWER_CRYSTAL },
1126 { "CORPSE", CORPSE },
1127 { "DISEASE", DISEASE },
1128 { "SYMPTOM", SYMPTOM },
1129 { "BUILDER", BUILDER },
1130 { "MATERIAL", MATERIAL },
1131 { NULL, 0 }
1132 };
1133
1134 static const CFConstant cstMove[] = {
1135 { "WALK", MOVE_WALK },
1136 { "FLY_LOW", MOVE_FLY_LOW },
1137 { "FLY_HIGH", MOVE_FLY_HIGH },
1138 { "FLYING", MOVE_FLYING },
1139 { "SWIM", MOVE_SWIM },
1140 { "BOAT", MOVE_BOAT },
1141 { "ALL", MOVE_ALL },
1142 { NULL, 0 }
1143 };
1144
1145 static const CFConstant cstMessageFlag[] = {
1146 { "NDI_BLACK", NDI_BLACK },
1147 { "NDI_WHITE", NDI_WHITE },
1148 { "NDI_NAVY", NDI_NAVY },
1149 { "NDI_RED", NDI_RED },
1150 { "NDI_ORANGE", NDI_ORANGE },
1151 { "NDI_BLUE", NDI_BLUE },
1152 { "NDI_DK_ORANGE", NDI_DK_ORANGE },
1153 { "NDI_GREEN", NDI_GREEN },
1154 { "NDI_LT_GREEN", NDI_LT_GREEN },
1155 { "NDI_GREY", NDI_GREY },
1156 { "NDI_BROWN", NDI_BROWN },
1157 { "NDI_GOLD", NDI_GOLD },
1158 { "NDI_TAN", NDI_TAN },
1159 { "NDI_UNIQUE", NDI_UNIQUE },
1160 { "NDI_ALL", NDI_ALL },
1161 { "NDI_ALL_DMS", NDI_ALL_DMS },
1162 { NULL, 0 }
1163 };
1164
1165 static const CFConstant cstAttackType[] = {
1166 { "PHYSICAL", AT_PHYSICAL },
1167 { "MAGIC", AT_MAGIC },
1168 { "FIRE", AT_FIRE },
1169 { "ELECTRICITY", AT_ELECTRICITY },
1170 { "COLD", AT_COLD },
1171 { "CONFUSION", AT_CONFUSION },
1172 { "ACID", AT_ACID },
1173 { "DRAIN", AT_DRAIN },
1174 { "WEAPONMAGIC", AT_WEAPONMAGIC },
1175 { "GHOSTHIT", AT_GHOSTHIT },
1176 { "POISON", AT_POISON },
1177 { "SLOW", AT_SLOW },
1178 { "PARALYZE", AT_PARALYZE },
1179 { "TURN_UNDEAD", AT_TURN_UNDEAD },
1180 { "FEAR", AT_FEAR },
1181 { "CANCELLATION", AT_CANCELLATION },
1182 { "DEPLETE", AT_DEPLETE },
1183 { "DEATH", AT_DEATH },
1184 { "CHAOS", AT_CHAOS },
1185 { "COUNTERSPELL", AT_COUNTERSPELL },
1186 { "GODPOWER", AT_GODPOWER },
1187 { "HOLYWORD", AT_HOLYWORD },
1188 { "BLIND", AT_BLIND },
1189 { "INTERNAL", AT_INTERNAL },
1190 { "LIFE_STEALING", AT_LIFE_STEALING },
1191 { "DISEASE", AT_DISEASE },
1192 { NULL, 0 }
1193 };
1194
1195 static const CFConstant cstAttackTypeNumber[] = {
1196 { "PHYSICAL", ATNR_PHYSICAL },
1197 { "MAGIC", ATNR_MAGIC },
1198 { "FIRE", ATNR_FIRE },
1199 { "ELECTRICITY", ATNR_ELECTRICITY },
1200 { "COLD", ATNR_COLD },
1201 { "CONFUSION", ATNR_CONFUSION },
1202 { "ACID", ATNR_ACID },
1203 { "DRAIN", ATNR_DRAIN },
1204 { "WEAPONMAGIC", ATNR_WEAPONMAGIC },
1205 { "GHOSTHIT", ATNR_GHOSTHIT },
1206 { "POISON", ATNR_POISON },
1207 { "SLOW", ATNR_SLOW },
1208 { "PARALYZE", ATNR_PARALYZE },
1209 { "TURN_UNDEAD", ATNR_TURN_UNDEAD },
1210 { "FEAR", ATNR_FEAR },
1211 { "CANCELLATION", ATNR_CANCELLATION },
1212 { "DEPLETE", ATNR_DEPLETE },
1213 { "DEATH", ATNR_DEATH },
1214 { "CHAOS", ATNR_CHAOS },
1215 { "COUNTERSPELL", ATNR_COUNTERSPELL },
1216 { "GODPOWER", ATNR_GODPOWER },
1217 { "HOLYWORD", ATNR_HOLYWORD },
1218 { "BLIND", ATNR_BLIND },
1219 { "INTERNAL", ATNR_INTERNAL },
1220 { "LIFE_STEALING", ATNR_LIFE_STEALING },
1221 { "DISEASE", ATNR_DISEASE },
1222 { NULL, 0 }
1223 };
1224
1225 static const CFConstant cstEventType[] = {
1226 /** Object_specific events. */
1227 { "APPLY", EVENT_APPLY },
1228 { "ATTACK", EVENT_ATTACKED },
1229 { "ATTACKS", EVENT_ATTACKS },
1230 { "BOUGHT", EVENT_BOUGHT },
1231 { "CLOSE", EVENT_CLOSE },
1232 { "DEATH", EVENT_DEATH },
1233 { "DESTROY", EVENT_DESTROY },
1234 { "DROP", EVENT_DROP },
1235 { "PICKUP", EVENT_PICKUP },
1236 { "SAY", EVENT_SAY },
1237 { "SELLING", EVENT_SELLING },
1238 { "STOP", EVENT_STOP },
1239 { "TIME", EVENT_TIME },
1240 { "THROW", EVENT_THROW },
1241 { "TRIGGER", EVENT_TRIGGER },
1242 { "TIMER", EVENT_TIMER },
1243 { "USER", EVENT_USER },
1244
1245 /** Global events. */
1246 { "BORN", EVENT_BORN },
1247 { "CLOCK", EVENT_CLOCK },
1248 { "CRASH", EVENT_CRASH },
1249 { "GKILL", EVENT_GKILL },
1250 { "KICK", EVENT_KICK },
1251 { "LOGIN", EVENT_LOGIN },
1252 { "LOGOUT", EVENT_LOGOUT },
1253 { "MAPENTER", EVENT_MAPENTER },
1254 { "MAPLEAVE", EVENT_MAPLEAVE },
1255 { "MAPLOAD", EVENT_MAPLOAD },
1256 { "MAPRESET", EVENT_MAPRESET },
1257 { "MAPUNLOAD", EVENT_MAPUNLOAD },
1258 { "MUZZLE", EVENT_MUZZLE },
1259 { "PLAYER_DEATH", EVENT_PLAYER_DEATH },
1260 { "REMOVE", EVENT_REMOVE },
1261 { "SHOUT", EVENT_SHOUT },
1262 { "TELL", EVENT_TELL },
1263 { NULL, 0 }
1264 };
1265
1266 static const CFConstant cstTime[] = {
1267 { "HOURS_PER_DAY", HOURS_PER_DAY },
1268 { "DAYS_PER_WEEK", DAYS_PER_WEEK },
1269 { "WEEKS_PER_MONTH", WEEKS_PER_MONTH },
1270 { "MONTHS_PER_YEAR", MONTHS_PER_YEAR },
1271 { "SEASONS_PER_YEAR", SEASONS_PER_YEAR },
1272 { "PERIODS_PER_DAY", PERIODS_PER_DAY },
1273 { NULL, 0 }
1274 };
1275
1276 static const CFConstant cstReplyTypes[] = {
1277 { "SAY", rt_say },
1278 { "REPLY", rt_reply },
1279 { "QUESTION", rt_question },
1280 { NULL, 0 }
1281 };
1282
1283 static const CFConstant cstAttackMovement[] = {
1284 { "DISTATT", DISTATT },
1285 { "RUNATT", RUNATT },
1286 { "HITRUN", HITRUN },
1287 { "WAITATT", WAITATT },
1288 { "RUSH", RUSH },
1289 { "ALLRUN", ALLRUN },
1290 { "DISTHIT", DISTHIT },
1291 { "WAIT2", WAIT2 },
1292 { "PETMOVE", PETMOVE },
1293 { "CIRCLE1", CIRCLE1 },
1294 { "CIRCLE2", CIRCLE2 },
1295 { "PACEH", PACEH },
1296 { "PACEH2", PACEH2 },
1297 { "RANDO", RANDO },
1298 { "RANDO2", RANDO2 },
1299 { "PACEV", PACEV },
1300 { "PACEV2", PACEV2 },
1301 { NULL, 0 }
1302 };
1303
1304 addConstants(module, "Direction", cstDirection);
1305 addConstants(module, "Type", cstType);
1306 addConstants(module, "Move", cstMove);
1307 addConstants(module, "MessageFlag", cstMessageFlag);
1308 addConstants(module, "AttackType", cstAttackType);
1309 addConstants(module, "AttackTypeNumber", cstAttackTypeNumber);
1310 addConstants(module, "EventType", cstEventType);
1311 addSimpleConstants(module, "Time", cstTime);
1312 addSimpleConstants(module, "ReplyType", cstReplyTypes);
1313 addSimpleConstants(module, "AttackMovement", cstAttackMovement);
1314 }
1315
1316 /*
1317 * Set up the main module and handle misc plugin loading stuff and such.
1318 */
1319
1320 /**
1321 * Set up the various types (map, object, archetype and so on) as well as some
1322 * constants, and Crossfire.error.
1323 */
1324 static void cfpython_init_types(PyObject* m) {
1325 PyObject *d = PyModule_GetDict(m);
1326
1327 Crossfire_ObjectType.tp_new = PyType_GenericNew;
1328 Crossfire_MapType.tp_new = PyType_GenericNew;
1329 Crossfire_PlayerType.tp_new = PyType_GenericNew;
1330 Crossfire_ArchetypeType.tp_new = PyType_GenericNew;
1331 Crossfire_PartyType.tp_new = PyType_GenericNew;
1332 Crossfire_RegionType.tp_new = PyType_GenericNew;
1333 PyType_Ready(&Crossfire_ObjectType);
1334 PyType_Ready(&Crossfire_MapType);
1335 PyType_Ready(&Crossfire_PlayerType);
1336 PyType_Ready(&Crossfire_ArchetypeType);
1337 PyType_Ready(&Crossfire_PartyType);
1338 PyType_Ready(&Crossfire_RegionType);
1339
1340 Py_INCREF(&Crossfire_ObjectType);
1341 Py_INCREF(&Crossfire_MapType);
1342 Py_INCREF(&Crossfire_PlayerType);
1343 Py_INCREF(&Crossfire_ArchetypeType);
1344 Py_INCREF(&Crossfire_PartyType);
1345 Py_INCREF(&Crossfire_RegionType);
1346
1347 PyModule_AddObject(m, "Object", (PyObject *)&Crossfire_ObjectType);
1348 PyModule_AddObject(m, "Map", (PyObject *)&Crossfire_MapType);
1349 PyModule_AddObject(m, "Player", (PyObject *)&Crossfire_PlayerType);
1350 PyModule_AddObject(m, "Archetype", (PyObject *)&Crossfire_ArchetypeType);
1351 PyModule_AddObject(m, "Party", (PyObject *)&Crossfire_PartyType);
1352 PyModule_AddObject(m, "Region", (PyObject *)&Crossfire_RegionType);
1353
1354 PyModule_AddObject(m, "LogError", Py_BuildValue("i", llevError));
1355 PyModule_AddObject(m, "LogInfo", Py_BuildValue("i", llevInfo));
1356 PyModule_AddObject(m, "LogDebug", Py_BuildValue("i", llevDebug));
1357 PyModule_AddObject(m, "LogMonster", Py_BuildValue("i", llevMonster));
1358
1359 CFPythonError = PyErr_NewException("Crossfire.error", NULL, NULL);
1360 PyDict_SetItemString(d, "error", CFPythonError);
1361 }
1362
1363 #ifdef IS_PY3K
1364 extern PyObject* PyInit_cjson(void);
1365 #else
1366 extern PyMODINIT_FUNC initcjson(void);
1367 #endif
1368
1369 #ifdef IS_PY3K
1370 static PyModuleDef CrossfireModule = {
1371 PyModuleDef_HEAD_INIT,
1372 "Crossfire", /* m_name */
1373 NULL, /* m_doc */
1374 -1, /* m_size */
1375 CFPythonMethods, /* m_methods */
1376 NULL, /* m_reload */
1377 NULL, /* m_traverse */
1378 NULL, /* m_clear */
1379 NULL /* m_free */
1380 };
1381
1382 static PyObject* PyInit_Crossfire(void)
1383 {
1384 PyObject *m = PyModule_Create(&CrossfireModule);
1385 Py_INCREF(m);
1386 return m;
1387 }
1388 #endif
1389
1390 CF_PLUGIN int initPlugin(const char *iversion, f_plug_api gethooksptr) {
1391 PyObject *m;
1392 int i;
1393 /* Python code to redirect stdouts/stderr. */
1394 const char *stdOutErr =
1395 "import sys\n\
1396 class CatchOutErr:\n\
1397 def __init__(self):\n\
1398 self.value = ''\n\
1399 def write(self, txt):\n\
1400 self.value += txt\n\
1401 catchOutErr = CatchOutErr()\n\
1402 sys.stdout = catchOutErr\n\
1403 sys.stderr = catchOutErr\n\
1404 ";
1405
1406 cf_init_plugin(gethooksptr);
1407 cf_log(llevDebug, "CFPython 2.0a init\n");
1408
1409 init_object_assoc_table();
1410 init_map_assoc_table();
1411
1412 #ifdef IS_PY26
1413 Py_Py3kWarningFlag++;
1414 #endif
1415
1416 #ifdef IS_PY3K
1417 PyImport_AppendInittab("Crossfire", &PyInit_Crossfire);
1418 PyImport_AppendInittab("cjson", &PyInit_cjson);
1419 #endif
1420
1421 Py_Initialize();
1422
1423 #ifdef IS_PY3K
1424 m = PyImport_ImportModule("Crossfire");
1425 #else
1426 m = Py_InitModule("Crossfire", CFPythonMethods);
1427 #endif
1428
1429 cfpython_init_types(m);
1430
1431 for (i = 0; i < NR_CUSTOM_CMD; i++) {
1432 CustomCommand[i].name = NULL;
1433 CustomCommand[i].script = NULL;
1434 CustomCommand[i].speed = 0.0;
1435 }
1436 initConstants(m);
1437 private_data = PyDict_New();
1438 shared_data = PyDict_New();
1439
1440 /* Redirect Python's stderr to a special object so it can be put to
1441 * the Crossfire log. */
1442 m = PyImport_AddModule("__main__");
1443 PyRun_SimpleString(stdOutErr);
1444 catcher = PyObject_GetAttrString(m, "catchOutErr");
1445
1446 #ifndef IS_PY3K
1447 /* add cjson module*/
1448 initcjson();
1449 #endif
1450 return 0;
1451 }
1452
1453 CF_PLUGIN void *getPluginProperty(int *type, ...) {
1454 va_list args;
1455 const char *propname;
1456 int i, size;
1457 command_array_struct *rtn_cmd;
1458 char *buf;
1459
1460 va_start(args, type);
1461 propname = va_arg(args, const char *);
1462
1463 if (!strcmp(propname, "command?")) {
1464 const char *cmdname;
1465 cmdname = va_arg(args, const char *);
1466 rtn_cmd = va_arg(args, command_array_struct *);
1467 va_end(args);
1468
1469 for (i = 0; i < NR_CUSTOM_CMD; i++) {
1470 if (CustomCommand[i].name != NULL) {
1471 if (!strcmp(CustomCommand[i].name, cmdname)) {
1472 rtn_cmd->name = CustomCommand[i].name;
1473 rtn_cmd->time = (float)CustomCommand[i].speed;
1474 rtn_cmd->func = cfpython_runPluginCommand;
1475 current_command = i;
1476 return rtn_cmd;
1477 }
1478 }
1479 }
1480 return NULL;
1481 } else if (!strcmp(propname, "Identification")) {
1482 buf = va_arg(args, char *);
1483 size = va_arg(args, int);
1484 va_end(args);
1485 snprintf(buf, size, PLUGIN_NAME);
1486 return NULL;
1487 } else if (!strcmp(propname, "FullName")) {
1488 buf = va_arg(args, char *);
1489 size = va_arg(args, int);
1490 va_end(args);
1491 snprintf(buf, size, PLUGIN_VERSION);
1492 return NULL;
1493 }
1494 va_end(args);
1495 return NULL;
1496 }
1497
1498 CF_PLUGIN void cfpython_runPluginCommand(object *op, const char *params) {
1499 char buf[1024], path[1024];
1500 CFPContext *context;
1501
1502 if (current_command < 0) {
1503 cf_log(llevError, "Illegal call of cfpython_runPluginCommand, call find_plugin_command first.\n");
1504 return;
1505 }
1506 snprintf(buf, sizeof(buf), "%s.py", cf_get_maps_directory(CustomCommand[current_command].script, path, sizeof(path)));
1507
1508 context = malloc(sizeof(CFPContext));
1509 context->message[0] = 0;
1510
1511 context->who = Crossfire_Object_wrap(op);
1512 context->activator = NULL;
1513 context->third = NULL;
1514 context->fix = 0;
1515 /* We are not running from an event, so set it to NULL to avoid segfaults. */
1516 context->event = NULL;
1517 snprintf(context->script, sizeof(context->script), "%s", buf);
1518 if (params)
1519 snprintf(context->options, sizeof(context->options), "%s", params);
1520 else
1521 context->options[0] = 0;
1522 context->returnvalue = 1; /* Default is "command successful" */
1523
1524 current_command = -999;
1525 if (!do_script(context, 0)) {
1526 freeContext(context);
1527 return;
1528 }
1529
1530 context = popContext();
1531 freeContext(context);
1532 /* printf("Execution complete"); */
1533 }
1534
1535 static int GECodes[] = {
1536 EVENT_BORN,
1537 EVENT_CLOCK,
1538 EVENT_PLAYER_DEATH,
1539 EVENT_GKILL,
1540 EVENT_LOGIN,
1541 EVENT_LOGOUT,
1542 EVENT_MAPENTER,
1543 EVENT_MAPLEAVE,
1544 EVENT_MAPRESET,
1545 EVENT_REMOVE,
1546 EVENT_SHOUT,
1547 EVENT_TELL,
1548 EVENT_MUZZLE,
1549 EVENT_KICK,
1550 EVENT_MAPUNLOAD,
1551 EVENT_MAPLOAD,
1552 0
1553 };
1554
1555 static const char* GEPaths[] = {
1556 "born",
1557 "clock",
1558 "death",
1559 "gkill",
1560 "login",
1561 "logout",
1562 "mapenter",
1563 "mapleave",
1564 "mapreset",
1565 "remove",
1566 "shout",
1567 "tell",
1568 "muzzle",
1569 "kick",
1570 "mapunload",
1571 "mapload",
1572 NULL
1573 };
1574
1575 CF_PLUGIN int postInitPlugin(void) {
1576 PyObject *scriptfile;
1577 char path[1024];
1578 int i;
1579
1580 cf_log(llevDebug, "CFPython 2.0a post init\n");
1581 initContextStack();
1582 for (i = 0; GECodes[i] != 0; i++)
1583 cf_system_register_global_event(GECodes[i], PLUGIN_NAME, cfpython_globalEventListener);
1584
1585 scriptfile = cfpython_openpyfile(cf_get_maps_directory("python/events/python_init.py", path, sizeof(path)));
1586 if (scriptfile != NULL) {
1587 FILE* pyfile = cfpython_pyfile_asfile(scriptfile);
1588 PyRun_SimpleFile(pyfile, cf_get_maps_directory("python/events/python_init.py", path, sizeof(path)));
1589 Py_DECREF(scriptfile);
1590 }
1591
1592 for (i = 0; i < PYTHON_CACHE_SIZE; i++) {
1593 pycode_cache[i].code = NULL;
1594 pycode_cache[i].file = NULL;
1595 pycode_cache[i].cached_time = 0;
1596 pycode_cache[i].used_time = 0;
1597 }
1598
1599 return 0;
1600 }
1601
1602 static const char *getGlobalEventPath(int code) {
1603 for (int i = 0; GECodes[i] != 0; i++) {
1604 if (GECodes[i] == code)
1605 return GEPaths[i];
1606 }
1607 return "";
1608 }
1609
1610 CF_PLUGIN int cfpython_globalEventListener(int *type, ...) {
1611 va_list args;
1612 int rv = 0;
1613 CFPContext *context;
1614 char *buf;
1615 player *pl;
1616 object *op;
1617 context = malloc(sizeof(CFPContext));
1618
1619 va_start(args, type);
1620 context->event_code = va_arg(args, int);
1621
1622 context->message[0] = 0;
1623
1624 context->who = NULL;
1625 context->activator = NULL;
1626 context->third = NULL;
1627 context->event = NULL;
1628 context->talk = NULL;
1629 rv = context->returnvalue = 0;
1630 cf_get_maps_directory("python/events/python_event.py", context->script, sizeof(context->script));
1631 snprintf(context->options, sizeof(context->options), "%s", getGlobalEventPath(context->event_code));
1632 switch (context->event_code) {
1633 case EVENT_CRASH:
1634 cf_log(llevDebug, "Unimplemented for now\n");
1635 break;
1636
1637 case EVENT_BORN:
1638 op = va_arg(args, object *);
1639 context->activator = Crossfire_Object_wrap(op);
1640 break;
1641
1642 case EVENT_PLAYER_DEATH:
1643 op = va_arg(args, object *);
1644 context->who = Crossfire_Object_wrap(op);
1645 op = va_arg(args, object *);
1646 context->activator = Crossfire_Object_wrap(op);
1647 break;
1648
1649 case EVENT_GKILL:
1650 op = va_arg(args, object *);
1651 object* hitter = va_arg(args, object *);
1652 context->who = Crossfire_Object_wrap(op);
1653 context->activator = Crossfire_Object_wrap(hitter);
1654 break;
1655
1656 case EVENT_LOGIN:
1657 pl = va_arg(args, player *);
1658 context->activator = Crossfire_Object_wrap(pl->ob);
1659 buf = va_arg(args, char *);
1660 if (buf != NULL)
1661 snprintf(context->message, sizeof(context->message), "%s", buf);
1662 break;
1663
1664 case EVENT_LOGOUT:
1665 pl = va_arg(args, player *);
1666 context->activator = Crossfire_Object_wrap(pl->ob);
1667 buf = va_arg(args, char *);
1668 if (buf != NULL)
1669 snprintf(context->message, sizeof(context->message), "%s", buf);
1670 break;
1671
1672 case EVENT_REMOVE:
1673 op = va_arg(args, object *);
1674 context->activator = Crossfire_Object_wrap(op);
1675 break;
1676
1677 case EVENT_SHOUT:
1678 op = va_arg(args, object *);
1679 context->activator = Crossfire_Object_wrap(op);
1680 buf = va_arg(args, char *);
1681 if (buf != NULL)
1682 snprintf(context->message, sizeof(context->message), "%s", buf);
1683 break;
1684
1685 case EVENT_MUZZLE:
1686 op = va_arg(args, object *);
1687 context->activator = Crossfire_Object_wrap(op);
1688 buf = va_arg(args, char *);
1689 if (buf != NULL)
1690 snprintf(context->message, sizeof(context->message), "%s", buf);
1691 break;
1692
1693 case EVENT_KICK:
1694 op = va_arg(args, object *);
1695 context->activator = Crossfire_Object_wrap(op);
1696 buf = va_arg(args, char *);
1697 if (buf != NULL)
1698 snprintf(context->message, sizeof(context->message), "%s", buf);
1699 break;
1700
1701 case EVENT_MAPENTER:
1702 op = va_arg(args, object *);
1703 context->activator = Crossfire_Object_wrap(op);
1704 context->who = Crossfire_Map_wrap(va_arg(args, mapstruct *));
1705 break;
1706
1707 case EVENT_MAPLEAVE:
1708 op = va_arg(args, object *);
1709 context->activator = Crossfire_Object_wrap(op);
1710 context->who = Crossfire_Map_wrap(va_arg(args, mapstruct *));
1711 break;
1712
1713 case EVENT_CLOCK:
1714 break;
1715
1716 case EVENT_MAPRESET:
1717 context->who = Crossfire_Map_wrap(va_arg(args, mapstruct *));
1718 break;
1719
1720 case EVENT_TELL:
1721 op = va_arg(args, object *);
1722 buf = va_arg(args, char *);
1723 context->activator = Crossfire_Object_wrap(op);
1724 if (buf != NULL)
1725 snprintf(context->message, sizeof(context->message), "%s", buf);
1726 op = va_arg(args, object *);
1727 context->third = Crossfire_Object_wrap(op);
1728 break;
1729
1730 case EVENT_MAPUNLOAD:
1731 context->who = Crossfire_Map_wrap(va_arg(args, mapstruct *));
1732 break;
1733
1734 case EVENT_MAPLOAD:
1735 context->who = Crossfire_Map_wrap(va_arg(args, mapstruct *));
1736 break;
1737 }
1738 va_end(args);
1739 context->returnvalue = 0;
1740
1741 if (context->event_code == EVENT_CLOCK) {
1742 // Ignore EVENT_CLOCK. It is not being used in maps, but nevertheless
1743 // runs python_init.py several times per second even while idling.
1744 freeContext(context);
1745 return rv;
1746 }
1747
1748 if (!do_script(context, 1)) {
1749 freeContext(context);
1750 return rv;
1751 }
1752
1753 context = popContext();
1754 rv = context->returnvalue;
1755
1756 /* Invalidate freed map wrapper. */
1757 if (context->event_code == EVENT_MAPUNLOAD)
1758 Handle_Map_Unload_Hook((Crossfire_Map *)context->who);
1759
1760 freeContext(context);
1761
1762 return rv;
1763 }
1764
1765 CF_PLUGIN int eventListener(int *type, ...) {
1766 int rv = 0;
1767 va_list args;
1768 char *buf;
1769 CFPContext *context;
1770 object *event;
1771
1772 context = malloc(sizeof(CFPContext));
1773
1774 context->message[0] = 0;
1775
1776 va_start(args, type);
1777
1778 context->who = Crossfire_Object_wrap(va_arg(args, object *));
1779 context->activator = Crossfire_Object_wrap(va_arg(args, object *));
1780 context->third = Crossfire_Object_wrap(va_arg(args, object *));
1781 buf = va_arg(args, char *);
1782 if (buf != NULL)
1783 snprintf(context->message, sizeof(context->message), "%s", buf);
1784 context->fix = va_arg(args, int);
1785 event = va_arg(args, object *);
1786 context->talk = va_arg(args, talk_info *);
1787 context->event_code = event->subtype;
1788 context->event = Crossfire_Object_wrap(event);
1789 cf_get_maps_directory(event->slaying, context->script, sizeof(context->script));
1790 snprintf(context->options, sizeof(context->options), "%s", event->name);
1791 context->returnvalue = 0;
1792
1793 va_end(args);
1794
1795 if (!do_script(context, 0)) {
1796 freeContext(context);
1797 return rv;
1798 }
1799
1800 context = popContext();
1801 rv = context->returnvalue;
1802 freeContext(context);
1803 return rv;
1804 }
1805
1806 CF_PLUGIN int closePlugin(void) {
1807 int i;
1808
1809 cf_log(llevDebug, "CFPython 2.0a closing\n");
1810
1811 for (i = 0; i < NR_CUSTOM_CMD; i++) {
1812 if (CustomCommand[i].name != NULL)
1813 cf_free_string(CustomCommand[i].name);
1814 if (CustomCommand[i].script != NULL)
1815 cf_free_string(CustomCommand[i].script);
1816 }
1817
1818 for (i = 0; i < PYTHON_CACHE_SIZE; i++) {
1819 Py_XDECREF(pycode_cache[i].code);
1820 if (pycode_cache[i].file != NULL)
1821 cf_free_string(pycode_cache[i].file);
1822 }
1823
1824 Py_Finalize();
1825
1826 return 0;
1827 }