Debian Codegraph @

plugins/cfpython/cfpython.c

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