3a754f1f466d82b2b0297eb6269b21dcc4605e3e
[blender.git] / source / gameengine / Ketsji / KX_PythonInit.cpp
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  * Initialize Python thingies.
29  */
30
31 #include "GL/glew.h"
32
33 #if defined(WIN32) && !defined(FREE_WINDOWS)
34 #pragma warning (disable : 4786)
35 #endif //WIN32
36
37 #ifndef DISABLE_PYTHON
38
39 extern "C" {
40         #include "bpy_internal_import.h"  /* from the blender python api, but we want to import text too! */
41         #include "py_capi_utils.h"
42         #include "mathutils.h" // Blender.Mathutils module copied here so the blenderlayer can use.
43         #include "geometry.h" // Blender.Geometry module copied here so the blenderlayer can use.
44         #include "bgl.h"
45         #include "blf_api.h"
46
47         #include "marshal.h" /* python header for loading/saving dicts */
48 }
49
50 #define WITH_PYTHON
51 #include "AUD_PyInit.h"
52
53 #endif
54
55 #include "KX_PythonInit.h"
56
57 // directory header for py function getBlendFileList
58 #ifndef WIN32
59   #include <dirent.h>
60   #include <stdlib.h>
61 #else
62   #include <io.h>
63   #include "BLI_winstuff.h"
64 #endif
65
66 //python physics binding
67 #include "KX_PyConstraintBinding.h"
68
69 #include "KX_KetsjiEngine.h"
70 #include "KX_RadarSensor.h"
71 #include "KX_RaySensor.h"
72 #include "KX_ArmatureSensor.h"
73 #include "KX_SceneActuator.h"
74 #include "KX_GameActuator.h"
75 #include "KX_ParentActuator.h"
76 #include "KX_SCA_DynamicActuator.h"
77
78 #include "SCA_IInputDevice.h"
79 #include "SCA_PropertySensor.h"
80 #include "SCA_RandomActuator.h"
81 #include "SCA_KeyboardSensor.h" /* IsPrintable, ToCharacter */
82 #include "SCA_PythonKeyboard.h"
83 #include "SCA_PythonMouse.h"
84 #include "KX_ConstraintActuator.h"
85 #include "KX_IpoActuator.h"
86 #include "KX_SoundActuator.h"
87 #include "KX_StateActuator.h"
88 #include "BL_ActionActuator.h"
89 #include "BL_ArmatureObject.h"
90 #include "RAS_IRasterizer.h"
91 #include "RAS_ICanvas.h"
92 #include "RAS_BucketManager.h"
93 #include "RAS_2DFilterManager.h"
94 #include "MT_Vector3.h"
95 #include "MT_Point3.h"
96 #include "ListValue.h"
97 #include "InputParser.h"
98 #include "KX_Scene.h"
99
100 #include "NG_NetworkScene.h" //Needed for sendMessage()
101
102 #include "BL_Shader.h"
103
104 #include "KX_PyMath.h"
105
106 #include "PyObjectPlus.h"
107
108 #include "KX_PythonInitTypes.h" 
109
110 /* we only need this to get a list of libraries from the main struct */
111 #include "DNA_ID.h"
112 #include "DNA_scene_types.h"
113
114 #include "PHY_IPhysicsEnvironment.h"
115 #include "BKE_main.h"
116 #include "BKE_utildefines.h"
117 #include "BKE_global.h"
118 #include "BLI_blenlib.h"
119 #include "GPU_material.h"
120 #include "MEM_guardedalloc.h"
121
122 /* for converting new scenes */
123 #include "KX_BlenderSceneConverter.h"
124 #include "KX_MeshProxy.h" /* for creating a new library of mesh objects */
125 extern "C" {
126         #include "BKE_idcode.h"
127 }
128
129 #include "NG_NetworkScene.h" //Needed for sendMessage()
130
131 // 'local' copy of canvas ptr, for window height/width python scripts
132
133 #ifndef DISABLE_PYTHON
134
135 static RAS_ICanvas* gp_Canvas = NULL;
136 static char gp_GamePythonPath[FILE_MAXDIR + FILE_MAXFILE] = "";
137 static char gp_GamePythonPathOrig[FILE_MAXDIR + FILE_MAXFILE] = ""; // not super happy about this, but we need to remember the first loaded file for the global/dict load save
138
139 #endif // DISABLE_PYTHON
140
141 static KX_Scene*        gp_KetsjiScene = NULL;
142 static KX_KetsjiEngine* gp_KetsjiEngine = NULL;
143 static RAS_IRasterizer* gp_Rasterizer = NULL;
144
145 void KX_SetActiveScene(class KX_Scene* scene)
146 {
147         gp_KetsjiScene = scene;
148 }
149
150 class KX_Scene* KX_GetActiveScene()
151 {
152         return gp_KetsjiScene;
153 }
154
155 class KX_KetsjiEngine* KX_GetActiveEngine()
156 {
157         return gp_KetsjiEngine;
158 }
159
160 /* why is this in python? */
161 void    KX_RasterizerDrawDebugLine(const MT_Vector3& from,const MT_Vector3& to,const MT_Vector3& color)
162 {
163         if (gp_Rasterizer)
164                 gp_Rasterizer->DrawDebugLine(from,to,color);
165 }
166
167 #ifndef DISABLE_PYTHON
168
169 static PyObject *gp_OrigPythonSysPath= NULL;
170 static PyObject *gp_OrigPythonSysModules= NULL;
171
172 /* Macro for building the keyboard translation */
173 //#define KX_MACRO_addToDict(dict, name) PyDict_SetItemString(dict, #name, PyLong_FromSsize_t(SCA_IInputDevice::KX_##name))
174 #define KX_MACRO_addToDict(dict, name) PyDict_SetItemString(dict, #name, item=PyLong_FromSsize_t(name)); Py_DECREF(item)
175 /* For the defines for types from logic bricks, we do stuff explicitly... */
176 #define KX_MACRO_addTypesToDict(dict, name, name2) PyDict_SetItemString(dict, #name, item=PyLong_FromSsize_t(name2)); Py_DECREF(item)
177
178
179 // temporarily python stuff, will be put in another place later !
180 #include "KX_Python.h"
181 #include "SCA_PythonController.h"
182 // List of methods defined in the module
183
184 static PyObject* ErrorObject;
185 static const char *gPyGetRandomFloat_doc="getRandomFloat returns a random floating point value in the range [0..1]";
186
187 static PyObject* gPyGetRandomFloat(PyObject*)
188 {
189         return PyFloat_FromDouble(MT_random());
190 }
191
192 static PyObject* gPySetGravity(PyObject*, PyObject* value)
193 {
194         MT_Vector3 vec;
195         if (!PyVecTo(value, vec))
196                 return NULL;
197
198         if (gp_KetsjiScene)
199                 gp_KetsjiScene->SetGravity(vec);
200         
201         Py_RETURN_NONE;
202 }
203
204 static char gPyExpandPath_doc[] =
205 "(path) - Converts a blender internal path into a proper file system path.\n\
206 path - the string path to convert.\n\n\
207 Use / as directory separator in path\n\
208 You can use '//' at the start of the string to define a relative path;\n\
209 Blender replaces that string by the directory of the startup .blend or runtime\n\
210 file to make a full path name (doesn't change during the game, even if you load\n\
211 other .blend).\n\
212 The function also converts the directory separator to the local file system format.";
213
214 static PyObject* gPyExpandPath(PyObject*, PyObject* args)
215 {
216         char expanded[FILE_MAXDIR + FILE_MAXFILE];
217         char* filename;
218         
219         if (!PyArg_ParseTuple(args,"s:ExpandPath",&filename))
220                 return NULL;
221
222         BLI_strncpy(expanded, filename, FILE_MAXDIR + FILE_MAXFILE);
223         BLI_path_abs(expanded, gp_GamePythonPath);
224         return PyUnicode_FromString(expanded);
225 }
226
227 static char gPyStartGame_doc[] =
228 "startGame(blend)\n\
229 Loads the blend file";
230
231 static PyObject* gPyStartGame(PyObject*, PyObject* args)
232 {
233         char* blendfile;
234
235         if (!PyArg_ParseTuple(args, "s:startGame", &blendfile))
236                 return NULL;
237
238         gp_KetsjiEngine->RequestExit(KX_EXIT_REQUEST_START_OTHER_GAME);
239         gp_KetsjiEngine->SetNameNextGame(blendfile);
240
241         Py_RETURN_NONE;
242 }
243
244 static char gPyEndGame_doc[] =
245 "endGame()\n\
246 Ends the current game";
247
248 static PyObject* gPyEndGame(PyObject*)
249 {
250         gp_KetsjiEngine->RequestExit(KX_EXIT_REQUEST_QUIT_GAME);
251
252         //printf("%s\n", gp_GamePythonPath);
253
254         Py_RETURN_NONE;
255 }
256
257 static char gPyRestartGame_doc[] =
258 "restartGame()\n\
259 Restarts the current game by reloading the .blend file";
260
261 static PyObject* gPyRestartGame(PyObject*)
262 {
263         gp_KetsjiEngine->RequestExit(KX_EXIT_REQUEST_RESTART_GAME);
264         gp_KetsjiEngine->SetNameNextGame(gp_GamePythonPath);
265
266         Py_RETURN_NONE;
267 }
268
269 static char gPySaveGlobalDict_doc[] =
270         "saveGlobalDict()\n"
271         "Saves bge.logic.globalDict to a file";
272
273 static PyObject* gPySaveGlobalDict(PyObject*)
274 {
275         char marshal_path[512];
276         char *marshal_buffer = NULL;
277         unsigned int marshal_length;
278         FILE *fp = NULL;
279
280         pathGamePythonConfig(marshal_path);
281         marshal_length = saveGamePythonConfig(&marshal_buffer);
282
283         if (marshal_length && marshal_buffer)
284         {
285                 fp = fopen(marshal_path, "wb");
286
287                 if (fp)
288                 {
289                         if (fwrite(marshal_buffer, 1, marshal_length, fp) != marshal_length)
290                                 printf("Warning: could not write marshal data\n");
291
292                         fclose(fp);
293                 } else {
294                         printf("Warning: could not open marshal file\n");
295                 }
296         } else {
297                 printf("Warning: could not create marshal buffer\n");
298         }
299
300         if (marshal_buffer)
301                 delete [] marshal_buffer;
302
303         Py_RETURN_NONE;
304 }
305
306 static char gPyLoadGlobalDict_doc[] =
307         "LoadGlobalDict()\n"
308         "Loads bge.logic.globalDict from a file";
309
310 static PyObject* gPyLoadGlobalDict(PyObject*)
311 {
312         char marshal_path[512];
313         char *marshal_buffer = NULL;
314         unsigned int marshal_length;
315         FILE *fp = NULL;
316         int result;
317
318         pathGamePythonConfig(marshal_path);
319
320         fp = fopen(marshal_path, "rb");
321
322         if (fp) {
323                 // obtain file size:
324                 fseek (fp, 0, SEEK_END);
325                 marshal_length = ftell(fp);
326                 rewind(fp);
327
328                 marshal_buffer = (char*)malloc (sizeof(char)*marshal_length);
329
330                 result = fread(marshal_buffer, 1, marshal_length, fp);
331
332                 if (result == marshal_length) {
333                         loadGamePythonConfig(marshal_buffer, marshal_length);
334                 } else {
335                         printf("Warning: could not read all of '%s'\n", marshal_path);
336                 }
337
338                 free(marshal_buffer);
339                 fclose(fp);
340         } else {
341                 printf("Warning: could not open '%s'\n", marshal_path);
342         }
343
344         Py_RETURN_NONE;
345 }
346
347 static char gPySendMessage_doc[] = 
348 "sendMessage(subject, [body, to, from])\n\
349 sends a message in same manner as a message actuator\
350 subject = Subject of the message\
351 body = Message body\
352 to = Name of object to send the message to\
353 from = Name of object to send the string from";
354
355 static PyObject* gPySendMessage(PyObject*, PyObject* args)
356 {
357         char* subject;
358         char* body = (char *)"";
359         char* to = (char *)"";
360         char* from = (char *)"";
361
362         if (!PyArg_ParseTuple(args, "s|sss:sendMessage", &subject, &body, &to, &from))
363                 return NULL;
364
365         gp_KetsjiScene->GetNetworkScene()->SendMessage(to, from, subject, body);
366
367         Py_RETURN_NONE;
368 }
369
370 // this gets a pointer to an array filled with floats
371 static PyObject* gPyGetSpectrum(PyObject*)
372 {
373         PyObject* resultlist = PyList_New(512);
374
375         for (int index = 0; index < 512; index++)
376         {
377                 PyList_SET_ITEM(resultlist, index, PyFloat_FromDouble(0.0));
378         }
379
380         return resultlist;
381 }
382
383 static PyObject* gPySetLogicTicRate(PyObject*, PyObject* args)
384 {
385         float ticrate;
386         if (!PyArg_ParseTuple(args, "f:setLogicTicRate", &ticrate))
387                 return NULL;
388         
389         KX_KetsjiEngine::SetTicRate(ticrate);
390         Py_RETURN_NONE;
391 }
392
393 static PyObject* gPyGetLogicTicRate(PyObject*)
394 {
395         return PyFloat_FromDouble(KX_KetsjiEngine::GetTicRate());
396 }
397
398 static PyObject* gPySetMaxLogicFrame(PyObject*, PyObject* args)
399 {
400         int frame;
401         if (!PyArg_ParseTuple(args, "i:setMaxLogicFrame", &frame))
402                 return NULL;
403         
404         KX_KetsjiEngine::SetMaxLogicFrame(frame);
405         Py_RETURN_NONE;
406 }
407
408 static PyObject* gPyGetMaxLogicFrame(PyObject*)
409 {
410         return PyLong_FromSsize_t(KX_KetsjiEngine::GetMaxLogicFrame());
411 }
412
413 static PyObject* gPySetMaxPhysicsFrame(PyObject*, PyObject* args)
414 {
415         int frame;
416         if (!PyArg_ParseTuple(args, "i:setMaxPhysicsFrame", &frame))
417                 return NULL;
418         
419         KX_KetsjiEngine::SetMaxPhysicsFrame(frame);
420         Py_RETURN_NONE;
421 }
422
423 static PyObject* gPyGetMaxPhysicsFrame(PyObject*)
424 {
425         return PyLong_FromSsize_t(KX_KetsjiEngine::GetMaxPhysicsFrame());
426 }
427
428 static PyObject* gPySetPhysicsTicRate(PyObject*, PyObject* args)
429 {
430         float ticrate;
431         if (!PyArg_ParseTuple(args, "f:setPhysicsTicRate", &ticrate))
432                 return NULL;
433         
434         PHY_GetActiveEnvironment()->setFixedTimeStep(true,ticrate);
435         Py_RETURN_NONE;
436 }
437 #if 0 // unused
438 static PyObject* gPySetPhysicsDebug(PyObject*, PyObject* args)
439 {
440         int debugMode;
441         if (!PyArg_ParseTuple(args, "i:setPhysicsDebug", &debugMode))
442                 return NULL;
443         
444         PHY_GetActiveEnvironment()->setDebugMode(debugMode);
445         Py_RETURN_NONE;
446 }
447 #endif
448
449
450 static PyObject* gPyGetPhysicsTicRate(PyObject*)
451 {
452         return PyFloat_FromDouble(PHY_GetActiveEnvironment()->getFixedTimeStep());
453 }
454
455 static PyObject* gPyGetAverageFrameRate(PyObject*)
456 {
457         return PyFloat_FromDouble(KX_KetsjiEngine::GetAverageFrameRate());
458 }
459
460 static PyObject* gPyGetBlendFileList(PyObject*, PyObject* args)
461 {
462         char cpath[sizeof(gp_GamePythonPath)];
463         char *searchpath = NULL;
464         PyObject* list, *value;
465         
466     DIR *dp;
467     struct dirent *dirp;
468         
469         if (!PyArg_ParseTuple(args, "|s:getBlendFileList", &searchpath))
470                 return NULL;
471         
472         list = PyList_New(0);
473         
474         if (searchpath) {
475                 BLI_strncpy(cpath, searchpath, FILE_MAXDIR + FILE_MAXFILE);
476                 BLI_path_abs(cpath, gp_GamePythonPath);
477         } else {
478                 /* Get the dir only */
479                 BLI_split_dirfile(gp_GamePythonPath, cpath, NULL);
480         }
481         
482     if((dp  = opendir(cpath)) == NULL) {
483                 /* todo, show the errno, this shouldnt happen anyway if the blendfile is readable */
484                 fprintf(stderr, "Could not read directoty (%s) failed, code %d (%s)\n", cpath, errno, strerror(errno));
485                 return list;
486     }
487         
488     while ((dirp = readdir(dp)) != NULL) {
489                 if (BLI_testextensie(dirp->d_name, ".blend")) {
490                         value = PyUnicode_FromString(dirp->d_name);
491                         PyList_Append(list, value);
492                         Py_DECREF(value);
493                 }
494     }
495         
496     closedir(dp);
497     return list;
498 }
499
500 static char gPyAddScene_doc[] = 
501 "addScene(name, [overlay])\n\
502 adds a scene to the game engine\n\
503 name = Name of the scene\n\
504 overlay = Overlay or underlay";
505 static PyObject* gPyAddScene(PyObject*, PyObject* args)
506 {
507         char* name;
508         int overlay = 1;
509         
510         if (!PyArg_ParseTuple(args, "s|i:addScene", &name , &overlay))
511                 return NULL;
512         
513         gp_KetsjiEngine->ConvertAndAddScene(name, (overlay != 0));
514
515         Py_RETURN_NONE;
516 }
517
518 static const char *gPyGetCurrentScene_doc =
519 "getCurrentScene()\n"
520 "Gets a reference to the current scene.\n";
521 static PyObject* gPyGetCurrentScene(PyObject* self)
522 {
523         return gp_KetsjiScene->GetProxy();
524 }
525
526 static const char *gPyGetSceneList_doc =
527 "getSceneList()\n"
528 "Return a list of converted scenes.\n";
529 static PyObject* gPyGetSceneList(PyObject* self)
530 {
531         KX_KetsjiEngine* m_engine = KX_GetActiveEngine();
532         PyObject* list;
533         KX_SceneList* scenes = m_engine->CurrentScenes();
534         int numScenes = scenes->size();
535         int i;
536         
537         list = PyList_New(numScenes);
538         
539         for (i=0;i<numScenes;i++)
540         {
541                 KX_Scene* scene = scenes->at(i);
542                 PyList_SET_ITEM(list, i, scene->GetProxy());
543         }
544
545         return list;
546 }
547
548 static PyObject *pyPrintStats(PyObject *,PyObject *,PyObject *)
549 {
550         gp_KetsjiScene->GetSceneConverter()->PrintStats();
551         Py_RETURN_NONE;
552 }
553
554 static PyObject *pyPrintExt(PyObject *,PyObject *,PyObject *)
555 {
556 #define pprint(x) std::cout << x << std::endl;
557         bool count=0;
558         bool support=0;
559         pprint("Supported Extensions...");
560         pprint(" GL_ARB_shader_objects supported?       "<< (GLEW_ARB_shader_objects?"yes.":"no."));
561         count = 1;
562
563         support= GLEW_ARB_vertex_shader;
564         pprint(" GL_ARB_vertex_shader supported?        "<< (support?"yes.":"no."));
565         count = 1;
566         if(support){
567                 pprint(" ----------Details----------");
568                 int max=0;
569                 glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB, (GLint*)&max);
570                 pprint("  Max uniform components." << max);
571
572                 glGetIntegerv(GL_MAX_VARYING_FLOATS_ARB, (GLint*)&max);
573                 pprint("  Max varying floats." << max);
574
575                 glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB, (GLint*)&max);
576                 pprint("  Max vertex texture units." << max);
577         
578                 glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB, (GLint*)&max);
579                 pprint("  Max combined texture units." << max);
580                 pprint("");
581         }
582
583         support=GLEW_ARB_fragment_shader;
584         pprint(" GL_ARB_fragment_shader supported?      "<< (support?"yes.":"no."));
585         count = 1;
586         if(support){
587                 pprint(" ----------Details----------");
588                 int max=0;
589                 glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB, (GLint*)&max);
590                 pprint("  Max uniform components." << max);
591                 pprint("");
592         }
593
594         support = GLEW_ARB_texture_cube_map;
595         pprint(" GL_ARB_texture_cube_map supported?     "<< (support?"yes.":"no."));
596         count = 1;
597         if(support){
598                 pprint(" ----------Details----------");
599                 int size=0;
600                 glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB, (GLint*)&size);
601                 pprint("  Max cubemap size." << size);
602                 pprint("");
603         }
604
605         support = GLEW_ARB_multitexture;
606         count = 1;
607         pprint(" GL_ARB_multitexture supported?         "<< (support?"yes.":"no."));
608         if(support){
609                 pprint(" ----------Details----------");
610                 int units=0;
611                 glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, (GLint*)&units);
612                 pprint("  Max texture units available.  " << units);
613                 pprint("");
614         }
615
616         pprint(" GL_ARB_texture_env_combine supported?  "<< (GLEW_ARB_texture_env_combine?"yes.":"no."));
617         count = 1;
618
619         if(!count)
620                 pprint("No extenstions are used in this build");
621
622         Py_RETURN_NONE;
623 }
624
625 static PyObject *gLibLoad(PyObject*, PyObject* args)
626 {
627         KX_Scene *kx_scene= gp_KetsjiScene;
628         char *path;
629         char *group;
630         Py_buffer py_buffer;
631         py_buffer.buf = NULL;
632         char *err_str= NULL;
633         
634         if (!PyArg_ParseTuple(args,"ss|y*:LibLoad",&path, &group, &py_buffer))
635                 return NULL;
636
637         if (!py_buffer.buf)
638         {
639                 if(kx_scene->GetSceneConverter()->LinkBlendFilePath(path, group, kx_scene, &err_str)) {
640                         Py_RETURN_TRUE;
641                 }
642         }
643         else
644         {
645
646                 if(kx_scene->GetSceneConverter()->LinkBlendFileMemory(py_buffer.buf, py_buffer.len, path, group, kx_scene, &err_str))   {
647                         PyBuffer_Release(&py_buffer);
648                         Py_RETURN_TRUE;
649                 }
650
651                 PyBuffer_Release(&py_buffer);
652         }
653         
654         if(err_str) {
655                 PyErr_SetString(PyExc_ValueError, err_str);
656                 return NULL;
657         }
658         
659         Py_RETURN_FALSE;
660 }
661
662 static PyObject *gLibNew(PyObject*, PyObject* args)
663 {
664         KX_Scene *kx_scene= gp_KetsjiScene;
665         char *path;
666         char *group;
667         char *name;
668         PyObject *names;
669         int idcode;
670
671         if (!PyArg_ParseTuple(args,"ssO!:LibNew",&path, &group, &PyList_Type, &names))
672                 return NULL;
673         
674         if(kx_scene->GetSceneConverter()->GetMainDynamicPath(path))
675         {
676                 PyErr_SetString(PyExc_KeyError, "the name of the path given exists");
677                 return NULL;
678         }
679         
680         idcode= BKE_idcode_from_name(group);
681         if(idcode==0) {
682                 PyErr_Format(PyExc_ValueError, "invalid group given \"%s\"", group);
683                 return NULL;
684         }
685         
686         Main *maggie= (Main *)MEM_callocN( sizeof(Main), "BgeMain");
687         kx_scene->GetSceneConverter()->GetMainDynamic().push_back(maggie);
688         strncpy(maggie->name, path, sizeof(maggie->name)-1);
689         
690         /* Copy the object into main */
691         if(idcode==ID_ME) {
692                 PyObject *ret= PyList_New(0);
693                 PyObject *item;
694                 for(int i= 0; i < PyList_GET_SIZE(names); i++) {
695                         name= _PyUnicode_AsString(PyList_GET_ITEM(names, i));
696                         if(name) {
697                                 RAS_MeshObject *meshobj= kx_scene->GetSceneConverter()->ConvertMeshSpecial(kx_scene, maggie, name);
698                                 if(meshobj) {
699                                         KX_MeshProxy* meshproxy = new KX_MeshProxy(meshobj);
700                                         item= meshproxy->NewProxy(true);
701                                         PyList_Append(ret, item);
702                                         Py_DECREF(item);
703                                 }
704                         }
705                         else {
706                                 PyErr_Clear(); /* wasnt a string, ignore for now */
707                         }
708                 }
709                 
710                 return ret;
711         }
712         else {
713                 PyErr_Format(PyExc_ValueError, "only \"Mesh\" group currently supported");
714                 return NULL;
715         }
716         
717         Py_RETURN_NONE;
718 }
719
720 static PyObject *gLibFree(PyObject*, PyObject* args)
721 {
722         KX_Scene *kx_scene= gp_KetsjiScene;
723         char *path;
724
725         if (!PyArg_ParseTuple(args,"s:LibFree",&path))
726                 return NULL;
727
728         if (kx_scene->GetSceneConverter()->FreeBlendFile(path))
729         {
730                 Py_RETURN_TRUE;
731         }
732         else {
733                 Py_RETURN_FALSE;
734         }
735 }
736
737 static PyObject *gLibList(PyObject*, PyObject* args)
738 {
739         vector<Main*> &dynMaggie = gp_KetsjiScene->GetSceneConverter()->GetMainDynamic();
740         int i= 0;
741         PyObject *list= PyList_New(dynMaggie.size());
742         
743         for (vector<Main*>::iterator it=dynMaggie.begin(); !(it==dynMaggie.end()); it++)
744         {
745                 PyList_SET_ITEM(list, i++, PyUnicode_FromString( (*it)->name) );
746         }
747         
748         return list;
749 }
750
751 static struct PyMethodDef game_methods[] = {
752         {"expandPath", (PyCFunction)gPyExpandPath, METH_VARARGS, (const char *)gPyExpandPath_doc},
753         {"startGame", (PyCFunction)gPyStartGame, METH_VARARGS, (const char *)gPyStartGame_doc},
754         {"endGame", (PyCFunction)gPyEndGame, METH_NOARGS, (const char *)gPyEndGame_doc},
755         {"restartGame", (PyCFunction)gPyRestartGame, METH_NOARGS, (const char *)gPyRestartGame_doc},
756         {"saveGlobalDict", (PyCFunction)gPySaveGlobalDict, METH_NOARGS, (const char *)gPySaveGlobalDict_doc},
757         {"loadGlobalDict", (PyCFunction)gPyLoadGlobalDict, METH_NOARGS, (const char *)gPyLoadGlobalDict_doc},
758         {"sendMessage", (PyCFunction)gPySendMessage, METH_VARARGS, (const char *)gPySendMessage_doc},
759         {"getCurrentController", (PyCFunction) SCA_PythonController::sPyGetCurrentController, METH_NOARGS, SCA_PythonController::sPyGetCurrentController__doc__},
760         {"getCurrentScene", (PyCFunction) gPyGetCurrentScene, METH_NOARGS, gPyGetCurrentScene_doc},
761         {"getSceneList", (PyCFunction) gPyGetSceneList, METH_NOARGS, (const char *)gPyGetSceneList_doc},
762         {"addScene", (PyCFunction)gPyAddScene, METH_VARARGS, (const char *)gPyAddScene_doc},
763         {"getRandomFloat",(PyCFunction) gPyGetRandomFloat, METH_NOARGS, (const char *)gPyGetRandomFloat_doc},
764         {"setGravity",(PyCFunction) gPySetGravity, METH_O, (const char *)"set Gravitation"},
765         {"getSpectrum",(PyCFunction) gPyGetSpectrum, METH_NOARGS, (const char *)"get audio spectrum"},
766         {"getMaxLogicFrame", (PyCFunction) gPyGetMaxLogicFrame, METH_NOARGS, (const char *)"Gets the max number of logic frame per render frame"},
767         {"setMaxLogicFrame", (PyCFunction) gPySetMaxLogicFrame, METH_VARARGS, (const char *)"Sets the max number of logic frame per render frame"},
768         {"getMaxPhysicsFrame", (PyCFunction) gPyGetMaxPhysicsFrame, METH_NOARGS, (const char *)"Gets the max number of physics frame per render frame"},
769         {"setMaxPhysicsFrame", (PyCFunction) gPySetMaxPhysicsFrame, METH_VARARGS, (const char *)"Sets the max number of physics farme per render frame"},
770         {"getLogicTicRate", (PyCFunction) gPyGetLogicTicRate, METH_NOARGS, (const char *)"Gets the logic tic rate"},
771         {"setLogicTicRate", (PyCFunction) gPySetLogicTicRate, METH_VARARGS, (const char *)"Sets the logic tic rate"},
772         {"getPhysicsTicRate", (PyCFunction) gPyGetPhysicsTicRate, METH_NOARGS, (const char *)"Gets the physics tic rate"},
773         {"setPhysicsTicRate", (PyCFunction) gPySetPhysicsTicRate, METH_VARARGS, (const char *)"Sets the physics tic rate"},
774         {"getAverageFrameRate", (PyCFunction) gPyGetAverageFrameRate, METH_NOARGS, (const char *)"Gets the estimated average frame rate"},
775         {"getBlendFileList", (PyCFunction)gPyGetBlendFileList, METH_VARARGS, (const char *)"Gets a list of blend files in the same directory as the current blend file"},
776         {"PrintGLInfo", (PyCFunction)pyPrintExt, METH_NOARGS, (const char *)"Prints GL Extension Info"},
777         {"PrintMemInfo", (PyCFunction)pyPrintStats, METH_NOARGS, (const char *)"Print engine stastics"},
778         
779         /* library functions */
780         {"LibLoad", (PyCFunction)gLibLoad, METH_VARARGS, (const char *)""},
781         {"LibNew", (PyCFunction)gLibNew, METH_VARARGS, (const char *)""},
782         {"LibFree", (PyCFunction)gLibFree, METH_VARARGS, (const char *)""},
783         {"LibList", (PyCFunction)gLibList, METH_VARARGS, (const char *)""},
784         
785         {NULL, (PyCFunction) NULL, 0, NULL }
786 };
787
788 static PyObject* gPyGetWindowHeight(PyObject*, PyObject* args)
789 {
790         return PyLong_FromSsize_t((gp_Canvas ? gp_Canvas->GetHeight() : 0));
791 }
792
793
794
795 static PyObject* gPyGetWindowWidth(PyObject*, PyObject* args)
796 {
797         return PyLong_FromSsize_t((gp_Canvas ? gp_Canvas->GetWidth() : 0));
798 }
799
800
801
802 // temporarility visibility thing, will be moved to rasterizer/renderer later
803 bool gUseVisibilityTemp = false;
804
805 static PyObject* gPyEnableVisibility(PyObject*, PyObject* args)
806 {
807         int visible;
808         if (!PyArg_ParseTuple(args,"i:enableVisibility",&visible))
809                 return NULL;
810         
811         gUseVisibilityTemp = (visible != 0);
812         Py_RETURN_NONE;
813 }
814
815
816
817 static PyObject* gPyShowMouse(PyObject*, PyObject* args)
818 {
819         int visible;
820         if (!PyArg_ParseTuple(args,"i:showMouse",&visible))
821                 return NULL;
822         
823         if (visible)
824         {
825                 if (gp_Canvas)
826                         gp_Canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
827         } else
828         {
829                 if (gp_Canvas)
830                         gp_Canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE);
831         }
832         
833         Py_RETURN_NONE;
834 }
835
836
837
838 static PyObject* gPySetMousePosition(PyObject*, PyObject* args)
839 {
840         int x,y;
841         if (!PyArg_ParseTuple(args,"ii:setMousePosition",&x,&y))
842                 return NULL;
843         
844         if (gp_Canvas)
845                 gp_Canvas->SetMousePosition(x,y);
846         
847         Py_RETURN_NONE;
848 }
849
850 static PyObject* gPySetEyeSeparation(PyObject*, PyObject* args)
851 {
852         float sep;
853         if (!PyArg_ParseTuple(args, "f:setEyeSeparation", &sep))
854                 return NULL;
855
856         if (!gp_Rasterizer) {
857                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setEyeSeparation(float), Rasterizer not available");
858                 return NULL;
859         }
860         
861         gp_Rasterizer->SetEyeSeparation(sep);
862         
863         Py_RETURN_NONE;
864 }
865
866 static PyObject* gPyGetEyeSeparation(PyObject*)
867 {
868         if (!gp_Rasterizer) {
869                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.getEyeSeparation(), Rasterizer not available");
870                 return NULL;
871         }
872         
873         return PyFloat_FromDouble(gp_Rasterizer->GetEyeSeparation());
874 }
875
876 static PyObject* gPySetFocalLength(PyObject*, PyObject* args)
877 {
878         float focus;
879         if (!PyArg_ParseTuple(args, "f:setFocalLength", &focus))
880                 return NULL;
881         
882         if (!gp_Rasterizer) {
883                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setFocalLength(float), Rasterizer not available");
884                 return NULL;
885         }
886
887         gp_Rasterizer->SetFocalLength(focus);
888         
889         Py_RETURN_NONE;
890 }
891
892 static PyObject* gPyGetFocalLength(PyObject*, PyObject*, PyObject*)
893 {
894         if (!gp_Rasterizer) {
895                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.getFocalLength(), Rasterizer not available");
896                 return NULL;
897         }
898         
899         return PyFloat_FromDouble(gp_Rasterizer->GetFocalLength());
900         
901         Py_RETURN_NONE;
902 }
903
904 static PyObject* gPySetBackgroundColor(PyObject*, PyObject* value)
905 {
906         
907         MT_Vector4 vec;
908         if (!PyVecTo(value, vec))
909                 return NULL;
910         
911         if (gp_Canvas)
912         {
913                 gp_Rasterizer->SetBackColor(vec[0], vec[1], vec[2], vec[3]);
914         }
915         Py_RETURN_NONE;
916 }
917
918
919
920 static PyObject* gPySetMistColor(PyObject*, PyObject* value)
921 {
922         
923         MT_Vector3 vec;
924         if (!PyVecTo(value, vec))
925                 return NULL;
926         
927         if (!gp_Rasterizer) {
928                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setMistColor(color), Rasterizer not available");
929                 return NULL;
930         }       
931         gp_Rasterizer->SetFogColor(vec[0], vec[1], vec[2]);
932         
933         Py_RETURN_NONE;
934 }
935
936 static PyObject* gPyDisableMist(PyObject*)
937 {
938         
939         if (!gp_Rasterizer) {
940                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setMistColor(color), Rasterizer not available");
941                 return NULL;
942         }       
943         gp_Rasterizer->DisableFog();
944         
945         Py_RETURN_NONE;
946 }
947
948 static PyObject* gPySetMistStart(PyObject*, PyObject* args)
949 {
950
951         float miststart;
952         if (!PyArg_ParseTuple(args,"f:setMistStart",&miststart))
953                 return NULL;
954         
955         if (!gp_Rasterizer) {
956                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setMistStart(float), Rasterizer not available");
957                 return NULL;
958         }
959         
960         gp_Rasterizer->SetFogStart(miststart);
961         
962         Py_RETURN_NONE;
963 }
964
965
966
967 static PyObject* gPySetMistEnd(PyObject*, PyObject* args)
968 {
969
970         float mistend;
971         if (!PyArg_ParseTuple(args,"f:setMistEnd",&mistend))
972                 return NULL;
973         
974         if (!gp_Rasterizer) {
975                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setMistEnd(float), Rasterizer not available");
976                 return NULL;
977         }
978         
979         gp_Rasterizer->SetFogEnd(mistend);
980         
981         Py_RETURN_NONE;
982 }
983
984
985 static PyObject* gPySetAmbientColor(PyObject*, PyObject* value)
986 {
987         
988         MT_Vector3 vec;
989         if (!PyVecTo(value, vec))
990                 return NULL;
991         
992         if (!gp_Rasterizer) {
993                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setAmbientColor(color), Rasterizer not available");
994                 return NULL;
995         }       
996         gp_Rasterizer->SetAmbientColor(vec[0], vec[1], vec[2]);
997         
998         Py_RETURN_NONE;
999 }
1000
1001
1002
1003
1004 static PyObject* gPyMakeScreenshot(PyObject*, PyObject* args)
1005 {
1006         char* filename;
1007         if (!PyArg_ParseTuple(args,"s:makeScreenshot",&filename))
1008                 return NULL;
1009         
1010         if (gp_Canvas)
1011         {
1012                 gp_Canvas->MakeScreenShot(filename);
1013         }
1014         
1015         Py_RETURN_NONE;
1016 }
1017
1018 static PyObject* gPyEnableMotionBlur(PyObject*, PyObject* args)
1019 {
1020         float motionblurvalue;
1021         if (!PyArg_ParseTuple(args,"f:enableMotionBlur",&motionblurvalue))
1022                 return NULL;
1023         
1024         if (!gp_Rasterizer) {
1025                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.enableMotionBlur(float), Rasterizer not available");
1026                 return NULL;
1027         }
1028         
1029         gp_Rasterizer->EnableMotionBlur(motionblurvalue);
1030         
1031         Py_RETURN_NONE;
1032 }
1033
1034 static PyObject* gPyDisableMotionBlur(PyObject*)
1035 {
1036         if (!gp_Rasterizer) {
1037                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.disableMotionBlur(), Rasterizer not available");
1038                 return NULL;
1039         }
1040         
1041         gp_Rasterizer->DisableMotionBlur();
1042         
1043         Py_RETURN_NONE;
1044 }
1045
1046 int getGLSLSettingFlag(char *setting)
1047 {
1048         if(strcmp(setting, "lights") == 0)
1049                 return GAME_GLSL_NO_LIGHTS;
1050         else if(strcmp(setting, "shaders") == 0)
1051                 return GAME_GLSL_NO_SHADERS;
1052         else if(strcmp(setting, "shadows") == 0)
1053                 return GAME_GLSL_NO_SHADOWS;
1054         else if(strcmp(setting, "ramps") == 0)
1055                 return GAME_GLSL_NO_RAMPS;
1056         else if(strcmp(setting, "nodes") == 0)
1057                 return GAME_GLSL_NO_NODES;
1058         else if(strcmp(setting, "extra_textures") == 0)
1059                 return GAME_GLSL_NO_EXTRA_TEX;
1060         else
1061                 return -1;
1062 }
1063
1064 static PyObject* gPySetGLSLMaterialSetting(PyObject*,
1065                                                                                         PyObject* args,
1066                                                                                         PyObject*)
1067 {
1068         GameData *gm= &(gp_KetsjiScene->GetBlenderScene()->gm);
1069         char *setting;
1070         int enable, flag, sceneflag;
1071
1072         if (!PyArg_ParseTuple(args,"si:setGLSLMaterialSetting",&setting,&enable))
1073                 return NULL;
1074         
1075         flag = getGLSLSettingFlag(setting);
1076         
1077         if  (flag==-1) {
1078                 PyErr_SetString(PyExc_ValueError, "Rasterizer.setGLSLMaterialSetting(string): glsl setting is not known");
1079                 return NULL;
1080         }
1081
1082         sceneflag= gm->flag;
1083         
1084         if (enable)
1085                 gm->flag &= ~flag;
1086         else
1087                 gm->flag |= flag;
1088
1089         /* display lists and GLSL materials need to be remade */
1090         if(sceneflag != gm->flag) {
1091                 GPU_materials_free();
1092                 if(gp_KetsjiEngine) {
1093                         KX_SceneList *scenes = gp_KetsjiEngine->CurrentScenes();
1094                         KX_SceneList::iterator it;
1095
1096                         for(it=scenes->begin(); it!=scenes->end(); it++)
1097                                 if((*it)->GetBucketManager()) {
1098                                         (*it)->GetBucketManager()->ReleaseDisplayLists();
1099                                         (*it)->GetBucketManager()->ReleaseMaterials();
1100                                 }
1101                 }
1102         }
1103
1104         Py_RETURN_NONE;
1105 }
1106
1107 static PyObject* gPyGetGLSLMaterialSetting(PyObject*, 
1108                                                                          PyObject* args, 
1109                                                                          PyObject*)
1110 {
1111         GameData *gm= &(gp_KetsjiScene->GetBlenderScene()->gm);
1112         char *setting;
1113         int enabled = 0, flag;
1114
1115         if (!PyArg_ParseTuple(args,"s:getGLSLMaterialSetting",&setting))
1116                 return NULL;
1117         
1118         flag = getGLSLSettingFlag(setting);
1119         
1120         if  (flag==-1) {
1121                 PyErr_SetString(PyExc_ValueError, "Rasterizer.getGLSLMaterialSetting(string): glsl setting is not known");
1122                 return NULL;
1123         }
1124
1125         enabled = ((gm->flag & flag) != 0);
1126         return PyLong_FromSsize_t(enabled);
1127 }
1128
1129 #define KX_TEXFACE_MATERIAL                             0
1130 #define KX_BLENDER_MULTITEX_MATERIAL    1
1131 #define KX_BLENDER_GLSL_MATERIAL                2
1132
1133 static PyObject* gPySetMaterialType(PyObject*,
1134                                                                         PyObject* args,
1135                                                                         PyObject*)
1136 {
1137         GameData *gm= &(gp_KetsjiScene->GetBlenderScene()->gm);
1138         int type;
1139
1140         if (!PyArg_ParseTuple(args,"i:setMaterialType",&type))
1141                 return NULL;
1142
1143         if(type == KX_BLENDER_GLSL_MATERIAL)
1144                 gm->matmode= GAME_MAT_GLSL;
1145         else if(type == KX_BLENDER_MULTITEX_MATERIAL)
1146                 gm->matmode= GAME_MAT_MULTITEX;
1147         else if(type == KX_TEXFACE_MATERIAL)
1148                 gm->matmode= GAME_MAT_TEXFACE;
1149         else {
1150                 PyErr_SetString(PyExc_ValueError, "Rasterizer.setMaterialType(int): material type is not known");
1151                 return NULL;
1152         }
1153
1154         Py_RETURN_NONE;
1155 }
1156
1157 static PyObject* gPyGetMaterialType(PyObject*)
1158 {
1159         GameData *gm= &(gp_KetsjiScene->GetBlenderScene()->gm);
1160         int flag;
1161
1162         if(gm->matmode == GAME_MAT_GLSL)
1163                 flag = KX_BLENDER_GLSL_MATERIAL;
1164         else if(gm->matmode == GAME_MAT_MULTITEX)
1165                 flag = KX_BLENDER_MULTITEX_MATERIAL;
1166         else
1167                 flag = KX_TEXFACE_MATERIAL;
1168         
1169         return PyLong_FromSsize_t(flag);
1170 }
1171
1172 static PyObject* gPyDrawLine(PyObject*, PyObject* args)
1173 {
1174         PyObject* ob_from;
1175         PyObject* ob_to;
1176         PyObject* ob_color;
1177
1178         if (!gp_Rasterizer) {
1179                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.drawLine(obFrom, obTo, color): Rasterizer not available");
1180                 return NULL;
1181         }
1182
1183         if (!PyArg_ParseTuple(args,"OOO:drawLine",&ob_from,&ob_to,&ob_color))
1184                 return NULL;
1185
1186         MT_Vector3 from;
1187         MT_Vector3 to;
1188         MT_Vector3 color;
1189         if (!PyVecTo(ob_from, from))
1190                 return NULL;
1191         if (!PyVecTo(ob_to, to))
1192                 return NULL;
1193         if (!PyVecTo(ob_color, color))
1194                 return NULL;
1195
1196         gp_Rasterizer->DrawDebugLine(from,to,color);
1197         
1198         Py_RETURN_NONE;
1199 }
1200
1201 static struct PyMethodDef rasterizer_methods[] = {
1202   {"getWindowWidth",(PyCFunction) gPyGetWindowWidth,
1203    METH_VARARGS, "getWindowWidth doc"},
1204    {"getWindowHeight",(PyCFunction) gPyGetWindowHeight,
1205    METH_VARARGS, "getWindowHeight doc"},
1206   {"makeScreenshot",(PyCFunction)gPyMakeScreenshot,
1207         METH_VARARGS, "make Screenshot doc"},
1208    {"enableVisibility",(PyCFunction) gPyEnableVisibility,
1209    METH_VARARGS, "enableVisibility doc"},
1210         {"showMouse",(PyCFunction) gPyShowMouse,
1211    METH_VARARGS, "showMouse(bool visible)"},
1212    {"setMousePosition",(PyCFunction) gPySetMousePosition,
1213    METH_VARARGS, "setMousePosition(int x,int y)"},
1214   {"setBackgroundColor",(PyCFunction)gPySetBackgroundColor,METH_O,"set Background Color (rgb)"},
1215         {"setAmbientColor",(PyCFunction)gPySetAmbientColor,METH_O,"set Ambient Color (rgb)"},
1216  {"disableMist",(PyCFunction)gPyDisableMist,METH_NOARGS,"turn off mist"},
1217  {"setMistColor",(PyCFunction)gPySetMistColor,METH_O,"set Mist Color (rgb)"},
1218   {"setMistStart",(PyCFunction)gPySetMistStart,METH_VARARGS,"set Mist Start(rgb)"},
1219   {"setMistEnd",(PyCFunction)gPySetMistEnd,METH_VARARGS,"set Mist End(rgb)"},
1220   {"enableMotionBlur",(PyCFunction)gPyEnableMotionBlur,METH_VARARGS,"enable motion blur"},
1221   {"disableMotionBlur",(PyCFunction)gPyDisableMotionBlur,METH_NOARGS,"disable motion blur"},
1222
1223   
1224   {"setEyeSeparation", (PyCFunction) gPySetEyeSeparation, METH_VARARGS, "set the eye separation for stereo mode"},
1225   {"getEyeSeparation", (PyCFunction) gPyGetEyeSeparation, METH_NOARGS, "get the eye separation for stereo mode"},
1226   {"setFocalLength", (PyCFunction) gPySetFocalLength, METH_VARARGS, "set the focal length for stereo mode"},
1227   {"getFocalLength", (PyCFunction) gPyGetFocalLength, METH_VARARGS, "get the focal length for stereo mode"},
1228   {"setMaterialMode",(PyCFunction) gPySetMaterialType,
1229    METH_VARARGS, "set the material mode to use for OpenGL rendering"},
1230   {"getMaterialMode",(PyCFunction) gPyGetMaterialType,
1231    METH_NOARGS, "get the material mode being used for OpenGL rendering"},
1232   {"setGLSLMaterialSetting",(PyCFunction) gPySetGLSLMaterialSetting,
1233    METH_VARARGS, "set the state of a GLSL material setting"},
1234   {"getGLSLMaterialSetting",(PyCFunction) gPyGetGLSLMaterialSetting,
1235    METH_VARARGS, "get the state of a GLSL material setting"},
1236   {"drawLine", (PyCFunction) gPyDrawLine,
1237    METH_VARARGS, "draw a line on the screen"},
1238   { NULL, (PyCFunction) NULL, 0, NULL }
1239 };
1240
1241 // Initialization function for the module (*must* be called initGameLogic)
1242
1243 static char GameLogic_module_documentation[] =
1244 "This is the Python API for the game engine of bge.logic"
1245 ;
1246
1247 static char Rasterizer_module_documentation[] =
1248 "This is the Python API for the game engine of Rasterizer"
1249 ;
1250
1251 static struct PyModuleDef GameLogic_module_def = {
1252         {}, /* m_base */
1253         "GameLogic",  /* m_name */
1254         GameLogic_module_documentation,  /* m_doc */
1255         0,  /* m_size */
1256         game_methods,  /* m_methods */
1257         0,  /* m_reload */
1258         0,  /* m_traverse */
1259         0,  /* m_clear */
1260         0,  /* m_free */
1261 };
1262
1263 PyObject* initGameLogic(KX_KetsjiEngine *engine, KX_Scene* scene) // quick hack to get gravity hook
1264 {
1265         PyObject* m;
1266         PyObject* d;
1267         PyObject* item; /* temp PyObject* storage */
1268         
1269         gp_KetsjiEngine = engine;
1270         gp_KetsjiScene = scene;
1271
1272         gUseVisibilityTemp=false;
1273         
1274         PyObjectPlus::ClearDeprecationWarning(); /* Not that nice to call here but makes sure warnings are reset between loading scenes */
1275         
1276         /* Use existing module where possible
1277          * be careful not to init any runtime vars after this */
1278         m = PyImport_ImportModule( "GameLogic" );
1279         if(m) {
1280                 Py_DECREF(m);
1281                 return m;
1282         }
1283         else {
1284                 PyErr_Clear();
1285                 // Create the module and add the functions      
1286                 m = PyModule_Create(&GameLogic_module_def);
1287                 PyDict_SetItemString(PySys_GetObject("modules"), GameLogic_module_def.m_name, m);
1288         }
1289         
1290         // Add some symbolic constants to the module
1291         d = PyModule_GetDict(m);
1292         
1293         // can be overwritten later for gameEngine instances that can load new blend files and re-initialize this module
1294         // for now its safe to make sure it exists for other areas such as the web plugin
1295         
1296         PyDict_SetItemString(d, "globalDict", item=PyDict_New()); Py_DECREF(item);
1297
1298         // Add keyboard and mouse attributes to this module
1299         SCA_PythonKeyboard* pykeyb = new SCA_PythonKeyboard(gp_KetsjiEngine->GetKeyboardDevice());
1300         PyDict_SetItemString(d, "keyboard", pykeyb->NewProxy(true));
1301
1302         SCA_PythonMouse* pymouse = new SCA_PythonMouse(gp_KetsjiEngine->GetMouseDevice(), gp_Canvas);
1303         PyDict_SetItemString(d, "mouse", pymouse->NewProxy(true));
1304
1305         ErrorObject = PyUnicode_FromString("GameLogic.error");
1306         PyDict_SetItemString(d, "error", ErrorObject);
1307         Py_DECREF(ErrorObject);
1308         
1309         // XXXX Add constants here
1310         /* To use logic bricks, we need some sort of constants. Here, we associate */
1311         /* constants and sumbolic names. Add them to dictionary d.                 */
1312
1313         /* 1. true and false: needed for everyone                                  */
1314         KX_MACRO_addTypesToDict(d, KX_TRUE,  SCA_ILogicBrick::KX_TRUE);
1315         KX_MACRO_addTypesToDict(d, KX_FALSE, SCA_ILogicBrick::KX_FALSE);
1316
1317         /* 2. Property sensor                                                      */
1318         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_EQUAL,      SCA_PropertySensor::KX_PROPSENSOR_EQUAL);
1319         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_NOTEQUAL,   SCA_PropertySensor::KX_PROPSENSOR_NOTEQUAL);
1320         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_INTERVAL,   SCA_PropertySensor::KX_PROPSENSOR_INTERVAL);
1321         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_CHANGED,    SCA_PropertySensor::KX_PROPSENSOR_CHANGED);
1322         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_EXPRESSION, SCA_PropertySensor::KX_PROPSENSOR_EXPRESSION);
1323
1324         /* 3. Constraint actuator                                                  */
1325         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCX);
1326         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCY);
1327         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCZ);
1328         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTX);
1329         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTY);
1330         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTZ);
1331         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPX);
1332         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPY);
1333         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPZ);
1334         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNX);
1335         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNY);
1336         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNZ);
1337         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIX);
1338         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIY);
1339         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIZ);
1340         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHPX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPX);
1341         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHPY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPY);
1342         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHPZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPZ);
1343         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHNX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNX);
1344         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHNY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNY);
1345         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHNZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNZ);
1346         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_NORMAL, KX_ConstraintActuator::KX_ACT_CONSTRAINT_NORMAL);
1347         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_MATERIAL, KX_ConstraintActuator::KX_ACT_CONSTRAINT_MATERIAL);
1348         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_PERMANENT, KX_ConstraintActuator::KX_ACT_CONSTRAINT_PERMANENT);
1349         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DISTANCE, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DISTANCE);
1350         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCAL, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCAL);
1351         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DOROTFH, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DOROTFH);
1352
1353         /* 4. Ipo actuator, simple part                                            */
1354         KX_MACRO_addTypesToDict(d, KX_IPOACT_PLAY,     KX_IpoActuator::KX_ACT_IPO_PLAY);
1355         KX_MACRO_addTypesToDict(d, KX_IPOACT_PINGPONG, KX_IpoActuator::KX_ACT_IPO_PINGPONG);
1356         KX_MACRO_addTypesToDict(d, KX_IPOACT_FLIPPER,  KX_IpoActuator::KX_ACT_IPO_FLIPPER);
1357         KX_MACRO_addTypesToDict(d, KX_IPOACT_LOOPSTOP, KX_IpoActuator::KX_ACT_IPO_LOOPSTOP);
1358         KX_MACRO_addTypesToDict(d, KX_IPOACT_LOOPEND,  KX_IpoActuator::KX_ACT_IPO_LOOPEND);
1359         KX_MACRO_addTypesToDict(d, KX_IPOACT_FROM_PROP,KX_IpoActuator::KX_ACT_IPO_FROM_PROP);
1360
1361         /* 5. Random distribution types                                            */
1362         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_CONST,      SCA_RandomActuator::KX_RANDOMACT_BOOL_CONST);
1363         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_UNIFORM,    SCA_RandomActuator::KX_RANDOMACT_BOOL_UNIFORM);
1364         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_BERNOUILLI, SCA_RandomActuator::KX_RANDOMACT_BOOL_BERNOUILLI);
1365         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_CONST,       SCA_RandomActuator::KX_RANDOMACT_INT_CONST);
1366         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_UNIFORM,     SCA_RandomActuator::KX_RANDOMACT_INT_UNIFORM);
1367         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_POISSON,     SCA_RandomActuator::KX_RANDOMACT_INT_POISSON);
1368         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_CONST,     SCA_RandomActuator::KX_RANDOMACT_FLOAT_CONST);
1369         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_UNIFORM,   SCA_RandomActuator::KX_RANDOMACT_FLOAT_UNIFORM);
1370         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_NORMAL,    SCA_RandomActuator::KX_RANDOMACT_FLOAT_NORMAL);
1371         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL, SCA_RandomActuator::KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL);
1372
1373         /* 6. Sound actuator                                                      */
1374         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYSTOP,              KX_SoundActuator::KX_SOUNDACT_PLAYSTOP);
1375         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYEND,               KX_SoundActuator::KX_SOUNDACT_PLAYEND);
1376         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPSTOP,              KX_SoundActuator::KX_SOUNDACT_LOOPSTOP);
1377         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPEND,               KX_SoundActuator::KX_SOUNDACT_LOOPEND);
1378         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL,     KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL);
1379         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP,     KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP);
1380
1381         /* 7. Action actuator                                                                                                      */
1382         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_PLAY,        ACT_ACTION_PLAY);
1383         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_FLIPPER,     ACT_ACTION_FLIPPER);
1384         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_LOOPSTOP,    ACT_ACTION_LOOP_STOP);
1385         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_LOOPEND,     ACT_ACTION_LOOP_END);
1386         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_PROPERTY,    ACT_ACTION_FROM_PROP);
1387         
1388         /*8. GL_BlendFunc */
1389         KX_MACRO_addTypesToDict(d, BL_ZERO, GL_ZERO);
1390         KX_MACRO_addTypesToDict(d, BL_ONE, GL_ONE);
1391         KX_MACRO_addTypesToDict(d, BL_SRC_COLOR, GL_SRC_COLOR);
1392         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR);
1393         KX_MACRO_addTypesToDict(d, BL_DST_COLOR, GL_DST_COLOR);
1394         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_DST_COLOR);
1395         KX_MACRO_addTypesToDict(d, BL_SRC_ALPHA, GL_SRC_ALPHA);
1396         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1397         KX_MACRO_addTypesToDict(d, BL_DST_ALPHA, GL_DST_ALPHA);
1398         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA);
1399         KX_MACRO_addTypesToDict(d, BL_SRC_ALPHA_SATURATE, GL_SRC_ALPHA_SATURATE);
1400
1401
1402         /* 9. UniformTypes */
1403         KX_MACRO_addTypesToDict(d, SHD_TANGENT, BL_Shader::SHD_TANGENT);
1404         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX, BL_Shader::MODELVIEWMATRIX);
1405         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_TRANSPOSE, BL_Shader::MODELVIEWMATRIX_TRANSPOSE);
1406         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_INVERSE, BL_Shader::MODELVIEWMATRIX_INVERSE);
1407         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_INVERSETRANSPOSE, BL_Shader::MODELVIEWMATRIX_INVERSETRANSPOSE);
1408         KX_MACRO_addTypesToDict(d, MODELMATRIX, BL_Shader::MODELMATRIX);
1409         KX_MACRO_addTypesToDict(d, MODELMATRIX_TRANSPOSE, BL_Shader::MODELMATRIX_TRANSPOSE);
1410         KX_MACRO_addTypesToDict(d, MODELMATRIX_INVERSE, BL_Shader::MODELMATRIX_INVERSE);
1411         KX_MACRO_addTypesToDict(d, MODELMATRIX_INVERSETRANSPOSE, BL_Shader::MODELMATRIX_INVERSETRANSPOSE);
1412         KX_MACRO_addTypesToDict(d, VIEWMATRIX, BL_Shader::VIEWMATRIX);
1413         KX_MACRO_addTypesToDict(d, VIEWMATRIX_TRANSPOSE, BL_Shader::VIEWMATRIX_TRANSPOSE);
1414         KX_MACRO_addTypesToDict(d, VIEWMATRIX_INVERSE, BL_Shader::VIEWMATRIX_INVERSE);
1415         KX_MACRO_addTypesToDict(d, VIEWMATRIX_INVERSETRANSPOSE, BL_Shader::VIEWMATRIX_INVERSETRANSPOSE);
1416         KX_MACRO_addTypesToDict(d, CAM_POS, BL_Shader::CAM_POS);
1417         KX_MACRO_addTypesToDict(d, CONSTANT_TIMER, BL_Shader::CONSTANT_TIMER);
1418
1419         /* 10 state actuator */
1420         KX_MACRO_addTypesToDict(d, KX_STATE1, (1<<0));
1421         KX_MACRO_addTypesToDict(d, KX_STATE2, (1<<1));
1422         KX_MACRO_addTypesToDict(d, KX_STATE3, (1<<2));
1423         KX_MACRO_addTypesToDict(d, KX_STATE4, (1<<3));
1424         KX_MACRO_addTypesToDict(d, KX_STATE5, (1<<4));
1425         KX_MACRO_addTypesToDict(d, KX_STATE6, (1<<5));
1426         KX_MACRO_addTypesToDict(d, KX_STATE7, (1<<6));
1427         KX_MACRO_addTypesToDict(d, KX_STATE8, (1<<7));
1428         KX_MACRO_addTypesToDict(d, KX_STATE9, (1<<8));
1429         KX_MACRO_addTypesToDict(d, KX_STATE10, (1<<9));
1430         KX_MACRO_addTypesToDict(d, KX_STATE11, (1<<10));
1431         KX_MACRO_addTypesToDict(d, KX_STATE12, (1<<11));
1432         KX_MACRO_addTypesToDict(d, KX_STATE13, (1<<12));
1433         KX_MACRO_addTypesToDict(d, KX_STATE14, (1<<13));
1434         KX_MACRO_addTypesToDict(d, KX_STATE15, (1<<14));
1435         KX_MACRO_addTypesToDict(d, KX_STATE16, (1<<15));
1436         KX_MACRO_addTypesToDict(d, KX_STATE17, (1<<16));
1437         KX_MACRO_addTypesToDict(d, KX_STATE18, (1<<17));
1438         KX_MACRO_addTypesToDict(d, KX_STATE19, (1<<18));
1439         KX_MACRO_addTypesToDict(d, KX_STATE20, (1<<19));
1440         KX_MACRO_addTypesToDict(d, KX_STATE21, (1<<20));
1441         KX_MACRO_addTypesToDict(d, KX_STATE22, (1<<21));
1442         KX_MACRO_addTypesToDict(d, KX_STATE23, (1<<22));
1443         KX_MACRO_addTypesToDict(d, KX_STATE24, (1<<23));
1444         KX_MACRO_addTypesToDict(d, KX_STATE25, (1<<24));
1445         KX_MACRO_addTypesToDict(d, KX_STATE26, (1<<25));
1446         KX_MACRO_addTypesToDict(d, KX_STATE27, (1<<26));
1447         KX_MACRO_addTypesToDict(d, KX_STATE28, (1<<27));
1448         KX_MACRO_addTypesToDict(d, KX_STATE29, (1<<28));
1449         KX_MACRO_addTypesToDict(d, KX_STATE30, (1<<29));
1450         
1451         /* All Sensors */
1452         KX_MACRO_addTypesToDict(d, KX_SENSOR_JUST_ACTIVATED, SCA_ISensor::KX_SENSOR_JUST_ACTIVATED);
1453         KX_MACRO_addTypesToDict(d, KX_SENSOR_ACTIVE, SCA_ISensor::KX_SENSOR_ACTIVE);
1454         KX_MACRO_addTypesToDict(d, KX_SENSOR_JUST_DEACTIVATED, SCA_ISensor::KX_SENSOR_JUST_DEACTIVATED);
1455         KX_MACRO_addTypesToDict(d, KX_SENSOR_INACTIVE, SCA_ISensor::KX_SENSOR_INACTIVE);
1456         
1457         /* Radar Sensor */
1458         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_POS_X, KX_RadarSensor::KX_RADAR_AXIS_POS_X);
1459         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_POS_Y, KX_RadarSensor::KX_RADAR_AXIS_POS_Y);
1460         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_POS_Z, KX_RadarSensor::KX_RADAR_AXIS_POS_Z);
1461         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_NEG_X, KX_RadarSensor::KX_RADAR_AXIS_NEG_Y);
1462         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_NEG_Y, KX_RadarSensor::KX_RADAR_AXIS_NEG_X);
1463         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_NEG_Z, KX_RadarSensor::KX_RADAR_AXIS_NEG_Z);
1464
1465         /* Ray Sensor */
1466         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_POS_X, KX_RaySensor::KX_RAY_AXIS_POS_X);
1467         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_POS_Y, KX_RaySensor::KX_RAY_AXIS_POS_Y);
1468         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_POS_Z, KX_RaySensor::KX_RAY_AXIS_POS_Z);
1469         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_NEG_X, KX_RaySensor::KX_RAY_AXIS_NEG_Y);
1470         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_NEG_Y, KX_RaySensor::KX_RAY_AXIS_NEG_X);
1471         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_NEG_Z, KX_RaySensor::KX_RAY_AXIS_NEG_Z);
1472
1473         /* Dynamic actuator */
1474         KX_MACRO_addTypesToDict(d, KX_DYN_RESTORE_DYNAMICS, KX_SCA_DynamicActuator::KX_DYN_RESTORE_DYNAMICS);
1475         KX_MACRO_addTypesToDict(d, KX_DYN_DISABLE_DYNAMICS, KX_SCA_DynamicActuator::KX_DYN_DISABLE_DYNAMICS);
1476         KX_MACRO_addTypesToDict(d, KX_DYN_ENABLE_RIGID_BODY, KX_SCA_DynamicActuator::KX_DYN_ENABLE_RIGID_BODY);
1477         KX_MACRO_addTypesToDict(d, KX_DYN_DISABLE_RIGID_BODY, KX_SCA_DynamicActuator::KX_DYN_DISABLE_RIGID_BODY);
1478         KX_MACRO_addTypesToDict(d, KX_DYN_SET_MASS, KX_SCA_DynamicActuator::KX_DYN_SET_MASS);
1479
1480         /* Input & Mouse Sensor */
1481         KX_MACRO_addTypesToDict(d, KX_INPUT_NONE, SCA_InputEvent::KX_NO_INPUTSTATUS);
1482         KX_MACRO_addTypesToDict(d, KX_INPUT_JUST_ACTIVATED, SCA_InputEvent::KX_JUSTACTIVATED);
1483         KX_MACRO_addTypesToDict(d, KX_INPUT_ACTIVE, SCA_InputEvent::KX_ACTIVE);
1484         KX_MACRO_addTypesToDict(d, KX_INPUT_JUST_RELEASED, SCA_InputEvent::KX_JUSTRELEASED);
1485         
1486         KX_MACRO_addTypesToDict(d, KX_MOUSE_BUT_LEFT, SCA_IInputDevice::KX_LEFTMOUSE);
1487         KX_MACRO_addTypesToDict(d, KX_MOUSE_BUT_MIDDLE, SCA_IInputDevice::KX_MIDDLEMOUSE);
1488         KX_MACRO_addTypesToDict(d, KX_MOUSE_BUT_RIGHT, SCA_IInputDevice::KX_RIGHTMOUSE);
1489
1490         /* 2D Filter Actuator */
1491         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_ENABLED, RAS_2DFilterManager::RAS_2DFILTER_ENABLED);
1492         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_DISABLED, RAS_2DFilterManager::RAS_2DFILTER_DISABLED);
1493         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_NOFILTER, RAS_2DFilterManager::RAS_2DFILTER_NOFILTER);
1494         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_MOTIONBLUR, RAS_2DFilterManager::RAS_2DFILTER_MOTIONBLUR);
1495         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_BLUR, RAS_2DFilterManager::RAS_2DFILTER_BLUR);
1496         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_SHARPEN, RAS_2DFilterManager::RAS_2DFILTER_SHARPEN);
1497         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_DILATION, RAS_2DFilterManager::RAS_2DFILTER_DILATION);
1498         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_EROSION, RAS_2DFilterManager::RAS_2DFILTER_EROSION);
1499         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_LAPLACIAN, RAS_2DFilterManager::RAS_2DFILTER_LAPLACIAN);
1500         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_SOBEL, RAS_2DFilterManager::RAS_2DFILTER_SOBEL);
1501         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_PREWITT, RAS_2DFilterManager::RAS_2DFILTER_PREWITT);
1502         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_GRAYSCALE, RAS_2DFilterManager::RAS_2DFILTER_GRAYSCALE);
1503         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_SEPIA, RAS_2DFilterManager::RAS_2DFILTER_SEPIA);
1504         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_INVERT, RAS_2DFilterManager::RAS_2DFILTER_INVERT);
1505         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_CUSTOMFILTER, RAS_2DFilterManager::RAS_2DFILTER_CUSTOMFILTER);
1506
1507         /* Sound Actuator */
1508         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYSTOP, KX_SoundActuator::KX_SOUNDACT_PLAYSTOP);
1509         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYEND, KX_SoundActuator::KX_SOUNDACT_PLAYEND);
1510         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPSTOP, KX_SoundActuator::KX_SOUNDACT_LOOPSTOP);
1511         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPEND, KX_SoundActuator:: KX_SOUNDACT_LOOPEND);
1512         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL, KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL);
1513         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP, KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP);
1514
1515         /* State Actuator */
1516         KX_MACRO_addTypesToDict(d, KX_STATE_OP_CPY, KX_StateActuator::OP_CPY);
1517         KX_MACRO_addTypesToDict(d, KX_STATE_OP_SET, KX_StateActuator::OP_SET);
1518         KX_MACRO_addTypesToDict(d, KX_STATE_OP_CLR, KX_StateActuator::OP_CLR);
1519         KX_MACRO_addTypesToDict(d, KX_STATE_OP_NEG, KX_StateActuator::OP_NEG);
1520
1521         /* Game Actuator Modes */
1522         KX_MACRO_addTypesToDict(d, KX_GAME_LOAD, KX_GameActuator::KX_GAME_LOAD);
1523         KX_MACRO_addTypesToDict(d, KX_GAME_START, KX_GameActuator::KX_GAME_START);
1524         KX_MACRO_addTypesToDict(d, KX_GAME_RESTART, KX_GameActuator::KX_GAME_RESTART);
1525         KX_MACRO_addTypesToDict(d, KX_GAME_QUIT, KX_GameActuator::KX_GAME_QUIT);
1526         KX_MACRO_addTypesToDict(d, KX_GAME_SAVECFG, KX_GameActuator::KX_GAME_SAVECFG);
1527         KX_MACRO_addTypesToDict(d, KX_GAME_LOADCFG, KX_GameActuator::KX_GAME_LOADCFG);
1528
1529         /* Scene Actuator Modes */
1530         KX_MACRO_addTypesToDict(d, KX_SCENE_RESTART, KX_SceneActuator::KX_SCENE_RESTART);
1531         KX_MACRO_addTypesToDict(d, KX_SCENE_SET_SCENE, KX_SceneActuator::KX_SCENE_SET_SCENE);
1532         KX_MACRO_addTypesToDict(d, KX_SCENE_SET_CAMERA, KX_SceneActuator::KX_SCENE_SET_CAMERA);
1533         KX_MACRO_addTypesToDict(d, KX_SCENE_ADD_FRONT_SCENE, KX_SceneActuator::KX_SCENE_ADD_FRONT_SCENE);
1534         KX_MACRO_addTypesToDict(d, KX_SCENE_ADD_BACK_SCENE, KX_SceneActuator::KX_SCENE_ADD_BACK_SCENE);
1535         KX_MACRO_addTypesToDict(d, KX_SCENE_REMOVE_SCENE, KX_SceneActuator::KX_SCENE_REMOVE_SCENE);
1536         KX_MACRO_addTypesToDict(d, KX_SCENE_SUSPEND, KX_SceneActuator::KX_SCENE_SUSPEND);
1537         KX_MACRO_addTypesToDict(d, KX_SCENE_RESUME, KX_SceneActuator::KX_SCENE_RESUME);
1538
1539         /* Parent Actuator Modes */
1540         KX_MACRO_addTypesToDict(d, KX_PARENT_SET, KX_ParentActuator::KX_PARENT_SET);
1541         KX_MACRO_addTypesToDict(d, KX_PARENT_REMOVE, KX_ParentActuator::KX_PARENT_REMOVE);
1542
1543         /* BL_ArmatureConstraint type */
1544         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_TRACKTO, CONSTRAINT_TYPE_TRACKTO);
1545         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_KINEMATIC, CONSTRAINT_TYPE_KINEMATIC);
1546         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_ROTLIKE, CONSTRAINT_TYPE_ROTLIKE);
1547         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_LOCLIKE, CONSTRAINT_TYPE_LOCLIKE);
1548         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_MINMAX, CONSTRAINT_TYPE_MINMAX);
1549         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_SIZELIKE, CONSTRAINT_TYPE_SIZELIKE);
1550         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_LOCKTRACK, CONSTRAINT_TYPE_LOCKTRACK);
1551         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_STRETCHTO, CONSTRAINT_TYPE_STRETCHTO);
1552         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_CLAMPTO, CONSTRAINT_TYPE_CLAMPTO);
1553         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_TRANSFORM, CONSTRAINT_TYPE_TRANSFORM);
1554         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_DISTLIMIT, CONSTRAINT_TYPE_DISTLIMIT);
1555         /* BL_ArmatureConstraint ik_type */
1556         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_COPYPOSE, CONSTRAINT_IK_COPYPOSE);
1557         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_DISTANCE, CONSTRAINT_IK_DISTANCE);
1558         /* BL_ArmatureConstraint ik_mode */
1559         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_MODE_INSIDE, LIMITDIST_INSIDE);
1560         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_MODE_OUTSIDE, LIMITDIST_OUTSIDE);
1561         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_MODE_ONSURFACE, LIMITDIST_ONSURFACE);
1562         /* BL_ArmatureConstraint ik_flag */
1563         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_FLAG_TIP, CONSTRAINT_IK_TIP);
1564         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_FLAG_ROT, CONSTRAINT_IK_ROT);
1565         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_FLAG_STRETCH, CONSTRAINT_IK_STRETCH);
1566         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_FLAG_POS, CONSTRAINT_IK_POS);
1567         /* KX_ArmatureSensor type */
1568         KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_STATE_CHANGED, SENS_ARM_STATE_CHANGED);
1569         KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_LIN_ERROR_BELOW, SENS_ARM_LIN_ERROR_BELOW);
1570         KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_LIN_ERROR_ABOVE, SENS_ARM_LIN_ERROR_ABOVE);
1571         KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_ROT_ERROR_BELOW, SENS_ARM_ROT_ERROR_BELOW);
1572         KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_ROT_ERROR_ABOVE, SENS_ARM_ROT_ERROR_ABOVE);
1573
1574         /* BL_ArmatureActuator type */
1575         KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_RUN, ACT_ARM_RUN);
1576         KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_ENABLE, ACT_ARM_ENABLE);
1577         KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_DISABLE, ACT_ARM_DISABLE);
1578         KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_SETTARGET, ACT_ARM_SETTARGET);
1579         KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_SETWEIGHT, ACT_ARM_SETWEIGHT);
1580
1581         /* BL_Armature Channel rotation_mode */
1582         KX_MACRO_addTypesToDict(d, ROT_MODE_QUAT, ROT_MODE_QUAT);
1583         KX_MACRO_addTypesToDict(d, ROT_MODE_XYZ, ROT_MODE_XYZ);
1584         KX_MACRO_addTypesToDict(d, ROT_MODE_XZY, ROT_MODE_XZY);
1585         KX_MACRO_addTypesToDict(d, ROT_MODE_YXZ, ROT_MODE_YXZ);
1586         KX_MACRO_addTypesToDict(d, ROT_MODE_YZX, ROT_MODE_YZX);
1587         KX_MACRO_addTypesToDict(d, ROT_MODE_ZXY, ROT_MODE_ZXY);
1588         KX_MACRO_addTypesToDict(d, ROT_MODE_ZYX, ROT_MODE_ZYX);
1589
1590         // Check for errors
1591         if (PyErr_Occurred())
1592     {
1593                 Py_FatalError("can't initialize module bge.logic");
1594     }
1595
1596         return m;
1597 }
1598
1599 // Python Sandbox code
1600 // override builtin functions import() and open()
1601
1602
1603 PyObject *KXpy_open(PyObject *self, PyObject *args) {
1604         PyErr_SetString(PyExc_RuntimeError, "Sandbox: open() function disabled!\nGame Scripts should not use this function.");
1605         return NULL;
1606 }
1607
1608 PyObject *KXpy_file(PyObject *self, PyObject *args) {
1609         PyErr_SetString(PyExc_RuntimeError, "Sandbox: file() function disabled!\nGame Scripts should not use this function.");
1610         return NULL;
1611 }
1612
1613 PyObject *KXpy_execfile(PyObject *self, PyObject *args) {
1614         PyErr_SetString(PyExc_RuntimeError, "Sandbox: execfile() function disabled!\nGame Scripts should not use this function.");
1615         return NULL;
1616 }
1617
1618 PyObject *KXpy_compile(PyObject *self, PyObject *args) {
1619         PyErr_SetString(PyExc_RuntimeError, "Sandbox: compile() function disabled!\nGame Scripts should not use this function.");
1620         return NULL;
1621 }
1622
1623 PyObject *KXpy_import(PyObject *self, PyObject *args)
1624 {
1625         char *name;
1626         int found;
1627         PyObject *globals = NULL;
1628         PyObject *locals = NULL;
1629         PyObject *fromlist = NULL;
1630         PyObject *l, *m, *n;
1631         int level; /* not used yet */
1632         
1633         if (!PyArg_ParseTuple(args, "s|OOOi:m_import",
1634                 &name, &globals, &locals, &fromlist, &level))
1635             return NULL;
1636
1637         /* check for builtin modules */
1638         m = PyImport_AddModule("sys");
1639         l = PyObject_GetAttrString(m, "builtin_module_names");
1640         n = PyUnicode_FromString(name);
1641         
1642         if (PySequence_Contains(l, n)) {
1643                 return PyImport_ImportModuleEx(name, globals, locals, fromlist);
1644         }
1645
1646         /* quick hack for GamePython modules 
1647                 TODO: register builtin modules properly by ExtendInittab */
1648         if (!strcmp(name, "GameLogic") || !strcmp(name, "GameKeys") || !strcmp(name, "PhysicsConstraints") ||
1649                 !strcmp(name, "Rasterizer") || !strcmp(name, "mathutils") || !strcmp(name, "bgl") || !strcmp(name, "geometry")) {
1650                 return PyImport_ImportModuleEx(name, globals, locals, fromlist);
1651         }
1652         
1653         /* Import blender texts as python modules */
1654         m= bpy_text_import_name(name, &found);
1655         if (m)
1656                 return m;
1657         
1658         if(found==0) /* if its found but could not import then it has its own error */
1659                 PyErr_Format(PyExc_ImportError, "Import of external Module %.20s not allowed.", name);
1660         
1661         return NULL;
1662
1663 }
1664
1665 PyObject *KXpy_reload(PyObject *self, PyObject *args) {
1666         
1667         /* Used to be sandboxed, bettet to allow importing of internal text only */ 
1668 #if 0
1669         PyErr_SetString(PyExc_RuntimeError, "Sandbox: reload() function disabled!\nGame Scripts should not use this function.");
1670         return NULL;
1671 #endif
1672         int found;
1673         PyObject *module = NULL;
1674         PyObject *newmodule = NULL;
1675
1676         /* check for a module arg */
1677         if( !PyArg_ParseTuple( args, "O:bpy_reload_meth", &module ) )
1678                 return NULL;
1679         
1680         newmodule= bpy_text_reimport( module, &found );
1681         if (newmodule)
1682                 return newmodule;
1683         
1684         if (found==0) /* if its found but could not import then it has its own error */
1685                 PyErr_SetString(PyExc_ImportError, "reload(module): failed to reload from blenders internal text");
1686         
1687         return newmodule;
1688 }
1689
1690 /* override python file type functions */
1691 #if 0
1692 static int
1693 file_init(PyObject *self, PyObject *args, PyObject *kwds)
1694 {
1695         KXpy_file(NULL, NULL);
1696         return -1;
1697 }
1698
1699 static PyObject *
1700 file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1701 {
1702         return KXpy_file(NULL, NULL);
1703 }
1704 #endif
1705
1706 static PyMethodDef meth_open[] = {{ "open", KXpy_open, METH_VARARGS, "(disabled)"}};
1707 static PyMethodDef meth_reload[] = {{ "reload", KXpy_reload, METH_VARARGS, "(disabled)"}};
1708 static PyMethodDef meth_file[] = {{ "file", KXpy_file, METH_VARARGS, "(disabled)"}};
1709 static PyMethodDef meth_execfile[] = {{ "execfile", KXpy_execfile, METH_VARARGS, "(disabled)"}};
1710 static PyMethodDef meth_compile[] = {{ "compile", KXpy_compile, METH_VARARGS, "(disabled)"}};
1711
1712 static PyMethodDef meth_import[] = {{ "import", KXpy_import, METH_VARARGS, "our own import"}};
1713
1714 //static PyObject *g_oldopen = 0;
1715 //static PyObject *g_oldimport = 0;
1716 //static int g_security = 0;
1717
1718 static void setSandbox(TPythonSecurityLevel level)
1719 {
1720     PyObject *m = PyImport_AddModule("__builtin__");
1721     PyObject *d = PyModule_GetDict(m);
1722         PyObject *item;
1723         switch (level) {
1724         case psl_Highest:
1725                 //if (!g_security) {
1726                         //g_oldopen = PyDict_GetItemString(d, "open");
1727         
1728                         // functions we cant trust
1729                         PyDict_SetItemString(d, "open", item=PyCFunction_New(meth_open, NULL));                 Py_DECREF(item);
1730                         PyDict_SetItemString(d, "reload", item=PyCFunction_New(meth_reload, NULL));             Py_DECREF(item);
1731                         PyDict_SetItemString(d, "file", item=PyCFunction_New(meth_file, NULL));                 Py_DECREF(item);
1732                         PyDict_SetItemString(d, "execfile", item=PyCFunction_New(meth_execfile, NULL)); Py_DECREF(item);
1733                         PyDict_SetItemString(d, "compile", item=PyCFunction_New(meth_compile, NULL));           Py_DECREF(item);
1734                         
1735                         // our own import
1736                         PyDict_SetItemString(d, "__import__", PyCFunction_New(meth_import, NULL));
1737                         //g_security = level;
1738                         
1739                         // Overiding file dosnt stop it being accessed if your sneaky
1740                         //    f =  [ t for t in (1).__class__.__mro__[-1].__subclasses__() if t.__name__ == 'file'][0]('/some_file.txt', 'w')
1741                         //    f.write('...')
1742                         // so overwrite the file types functions. be very careful here still, since python uses python.
1743                         // ps - python devs frown deeply upon this.
1744         
1745                         /* this could mess up pythons internals, if we are serious about sandboxing
1746                          * issues like the one above need to be solved, possibly modify __subclasses__ is safer? */
1747 #if 0
1748                         PyFile_Type.tp_init = file_init;
1749                         PyFile_Type.tp_new = file_new;
1750 #endif
1751                 //}
1752                 break;
1753         /*
1754         case psl_Lowest:
1755                 if (g_security) {
1756                         PyDict_SetItemString(d, "open", g_oldopen);
1757                         PyDict_SetItemString(d, "__import__", g_oldimport);
1758                         g_security = level;
1759                 }
1760         */
1761         default:
1762                         /* Allow importing internal text, from bpy_internal_import.py */
1763                         PyDict_SetItemString(d, "reload", item=PyCFunction_New(bpy_reload_meth, NULL));         Py_DECREF(item);
1764                         PyDict_SetItemString(d, "__import__", item=PyCFunction_New(bpy_import_meth, NULL));     Py_DECREF(item);
1765                 break;
1766         }
1767 }
1768
1769 /* Explanation of 
1770  * 
1771  * - backupPySysObjects()               : stores sys.path in gp_OrigPythonSysPath
1772  * - initPySysObjects(main)     : initializes the blendfile and library paths
1773  * - restorePySysObjects()              : restores sys.path from gp_OrigPythonSysPath
1774  * 
1775  * These exist so the current blend dir "//" can always be used to import modules from.
1776  * the reason we need a few functions for this is that python is not only used by the game engine
1777  * so we cant just add to sys.path all the time, it would leave pythons state in a mess.
1778  * It would also be incorrect since loading blend files for new levels etc would alwasy add to sys.path
1779  * 
1780  * To play nice with blenders python, the sys.path is backed up and the current blendfile along
1781  * with all its lib paths are added to the sys path.
1782  * When loading a new blendfile, the original sys.path is restored and the new paths are added over the top.
1783  */
1784
1785 /**
1786  * So we can have external modules mixed with our blend files.
1787  */
1788 static void backupPySysObjects(void)
1789 {
1790         PyObject *sys_path= PySys_GetObject("path"); /* should never fail */
1791         PyObject *sys_mods= PySys_GetObject("modules"); /* should never fail */
1792         
1793         /* paths */
1794         Py_XDECREF(gp_OrigPythonSysPath); /* just incase its set */
1795         gp_OrigPythonSysPath = PyList_GetSlice(sys_path, 0, INT_MAX); /* copy the list */
1796         
1797         /* modules */
1798         Py_XDECREF(gp_OrigPythonSysModules); /* just incase its set */
1799         gp_OrigPythonSysModules = PyDict_Copy(sys_mods); /* copy the list */
1800         
1801 }
1802
1803 /* for initPySysObjects only,
1804  * takes a blend path and adds a scripts dir from it
1805  *
1806  * "/home/me/foo.blend" -> "/home/me/scripts"
1807  */
1808 static void initPySysObjects__append(PyObject *sys_path, char *filename)
1809 {
1810         PyObject *item;
1811         char expanded[FILE_MAXDIR + FILE_MAXFILE];
1812         
1813         BLI_split_dirfile(filename, expanded, NULL); /* get the dir part of filename only */
1814         BLI_path_abs(expanded, gp_GamePythonPath); /* filename from lib->filename is (always?) absolute, so this may not be needed but it wont hurt */
1815         BLI_cleanup_file(gp_GamePythonPath, expanded); /* Dont use BLI_cleanup_dir because it adds a slash - BREAKS WIN32 ONLY */
1816         item= PyUnicode_FromString(expanded);
1817         
1818 //      printf("SysPath - '%s', '%s', '%s'\n", expanded, filename, gp_GamePythonPath);
1819         
1820         if(PySequence_Index(sys_path, item) == -1) {
1821                 PyErr_Clear(); /* PySequence_Index sets a ValueError */
1822                 PyList_Insert(sys_path, 0, item);
1823         }
1824         
1825         Py_DECREF(item);
1826 }
1827 static void initPySysObjects(Main *maggie)
1828 {
1829         PyObject *sys_path= PySys_GetObject("path"); /* should never fail */
1830         
1831         if (gp_OrigPythonSysPath==NULL) {
1832                 /* backup */
1833                 backupPySysObjects();
1834         }
1835         else {
1836                 /* get the original sys path when the BGE started */
1837                 PyList_SetSlice(sys_path, 0, INT_MAX, gp_OrigPythonSysPath);
1838         }
1839         
1840         Library *lib= (Library *)maggie->library.first;
1841         
1842         while(lib) {
1843                 /* lib->name wont work in some cases (on win32),
1844                  * even when expanding with gp_GamePythonPath, using lib->filename is less trouble */
1845                 initPySysObjects__append(sys_path, lib->filepath);
1846                 lib= (Library *)lib->id.next;
1847         }
1848         
1849         initPySysObjects__append(sys_path, gp_GamePythonPath);
1850         
1851 //      fprintf(stderr, "\nNew Path: %d ", PyList_Size(sys_path));
1852 //      PyObject_Print(sys_path, stderr, 0);
1853 }
1854
1855 static void restorePySysObjects(void)
1856 {
1857         if (gp_OrigPythonSysPath==NULL)
1858                 return;
1859         
1860         PyObject *sys_path= PySys_GetObject("path"); /* should never fail */
1861         PyObject *sys_mods= PySys_GetObject("modules"); /* should never fail */
1862
1863         /* paths */
1864         PyList_SetSlice(sys_path, 0, INT_MAX, gp_OrigPythonSysPath);
1865         Py_DECREF(gp_OrigPythonSysPath);
1866         gp_OrigPythonSysPath= NULL;
1867         
1868         /* modules */
1869         PyDict_Clear(sys_mods);
1870         PyDict_Update(sys_mods, gp_OrigPythonSysModules);
1871         Py_DECREF(gp_OrigPythonSysModules);
1872         gp_OrigPythonSysModules= NULL;  
1873         
1874         
1875 //      fprintf(stderr, "\nRestore Path: %d ", PyList_Size(sys_path));
1876 //      PyObject_Print(sys_path, stderr, 0);
1877 }
1878
1879 /**
1880  * Python is not initialised.
1881  */
1882 PyObject* initGamePlayerPythonScripting(const STR_String& progname, TPythonSecurityLevel level, Main *maggie, int argc, char** argv)
1883 {
1884         /* Yet another gotcha in the py api
1885          * Cant run PySys_SetArgv more then once because this adds the
1886          * binary dir to the sys.path each time.
1887          * Id have thaught python being totally restarted would make this ok but
1888          * somehow it remembers the sys.path - Campbell
1889          */
1890         static bool first_time = true;
1891         
1892 #if 0 // TODO - py3
1893         STR_String pname = progname;
1894         Py_SetProgramName(pname.Ptr());
1895 #endif
1896         Py_NoSiteFlag=1;
1897         Py_FrozenFlag=1;
1898         Py_Initialize();
1899         
1900         if(argv && first_time) { /* browser plugins dont currently set this */
1901                 // Until python support ascii again, we use our own.
1902                 // PySys_SetArgv(argc, argv);
1903                 int i;
1904                 PyObject *py_argv= PyList_New(argc);
1905
1906                 for (i=0; i<argc; i++)
1907                         PyList_SET_ITEM(py_argv, i, PyUnicode_FromString(argv[i]));
1908
1909                 PySys_SetObject("argv", py_argv);
1910                 Py_DECREF(py_argv);
1911         }
1912         
1913         setSandbox(level);
1914         initPyTypes();
1915         
1916         bpy_import_main_set(maggie);
1917         
1918         initPySysObjects(maggie);
1919         
1920         first_time = false;
1921         
1922         PyObjectPlus::ClearDeprecationWarning();
1923
1924         return PyC_DefaultNameSpace(NULL);
1925 }
1926
1927 void exitGamePlayerPythonScripting()
1928 {       
1929         /* since python restarts we cant let the python backup of the sys.path hang around in a global pointer */
1930         restorePySysObjects(); /* get back the original sys.path and clear the backup */
1931         
1932         Py_Finalize();
1933         bpy_import_main_set(NULL);
1934         PyObjectPlus::ClearDeprecationWarning();
1935 }
1936
1937
1938
1939 /**
1940  * Python is already initialized.
1941  */
1942 PyObject* initGamePythonScripting(const STR_String& progname, TPythonSecurityLevel level, Main *maggie)
1943 {
1944 #if 0 // XXX TODO Py3
1945         STR_String pname = progname;
1946         Py_SetProgramName(pname.Ptr());
1947 #endif
1948         Py_NoSiteFlag=1;
1949         Py_FrozenFlag=1;
1950
1951         setSandbox(level);
1952         initPyTypes();
1953         
1954         bpy_import_main_set(maggie);
1955         
1956         initPySysObjects(maggie);
1957
1958         PyObjectPlus::NullDeprecationWarning();
1959
1960         return PyC_DefaultNameSpace(NULL);
1961 }
1962
1963 void exitGamePythonScripting()
1964 {
1965         restorePySysObjects(); /* get back the original sys.path and clear the backup */
1966         bpy_import_main_set(NULL);
1967         PyObjectPlus::ClearDeprecationWarning();
1968 }
1969
1970 /* similar to the above functions except it sets up the namespace
1971  * and other more general things */
1972 void setupGamePython(KX_KetsjiEngine* ketsjiengine, KX_Scene* startscene, Main *blenderdata, PyObject * pyGlobalDict, PyObject **gameLogic, PyObject **gameLogic_keys, int argc, char** argv)
1973 {
1974         PyObject* dictionaryobject;
1975
1976         if(argv) /* player only */
1977                 dictionaryobject= initGamePlayerPythonScripting("Ketsji", psl_Lowest, blenderdata, argc, argv);
1978         else
1979                 dictionaryobject= initGamePythonScripting("Ketsji", psl_Lowest, blenderdata);
1980
1981         ketsjiengine->SetPyNamespace(dictionaryobject);
1982         initRasterizer(ketsjiengine->GetRasterizer(), ketsjiengine->GetCanvas());
1983         *gameLogic = initGameLogic(ketsjiengine, startscene);
1984
1985         /* is set in initGameLogic so only set here if we want it to persist between scenes */
1986         if(pyGlobalDict)
1987                 PyDict_SetItemString(PyModule_GetDict(*gameLogic), "globalDict", pyGlobalDict); // Same as importing the module.
1988
1989         *gameLogic_keys = PyDict_Keys(PyModule_GetDict(*gameLogic));
1990
1991         initGameKeys();
1992         initPythonConstraintBinding();
1993         initMathutils();
1994         initGeometry();
1995         initBGL();
1996         initBLF();
1997         AUD_initPython();
1998         initVideoTexture();
1999
2000         /* could be done a lot more nicely, but for now a quick way to get bge.* working */
2001         PyRun_SimpleString("sys = __import__('sys');mod = sys.modules['bge'] = type(sys)('bge');mod.__dict__.update({'logic':__import__('GameLogic'), 'render':__import__('Rasterizer'), 'events':__import__('GameKeys'), 'constraints':__import__('PhysicsConstraints'), 'types':__import__('GameTypes'), 'texture':__import__('VideoTexture')});");
2002 }
2003
2004 static struct PyModuleDef Rasterizer_module_def = {
2005         {}, /* m_base */
2006         "Rasterizer",  /* m_name */
2007         Rasterizer_module_documentation,  /* m_doc */
2008         0,  /* m_size */
2009         rasterizer_methods,  /* m_methods */
2010         0,  /* m_reload */
2011         0,  /* m_traverse */
2012         0,  /* m_clear */
2013         0,  /* m_free */
2014 };
2015
2016 PyObject* initRasterizer(RAS_IRasterizer* rasty,RAS_ICanvas* canvas)
2017 {
2018         gp_Canvas = canvas;
2019         gp_Rasterizer = rasty;
2020
2021
2022   PyObject* m;
2023   PyObject* d;
2024   PyObject* item;
2025
2026         /* Use existing module where possible
2027          * be careful not to init any runtime vars after this */
2028         m = PyImport_ImportModule( "Rasterizer" );
2029         if(m) {
2030                 Py_DECREF(m);
2031                 return m;
2032         }
2033         else {
2034                 PyErr_Clear();
2035         
2036                 // Create the module and add the functions
2037                 m = PyModule_Create(&Rasterizer_module_def);
2038                 PyDict_SetItemString(PySys_GetObject("modules"), Rasterizer_module_def.m_name, m);
2039         }
2040
2041   // Add some symbolic constants to the module
2042   d = PyModule_GetDict(m);
2043   ErrorObject = PyUnicode_FromString("Rasterizer.error");
2044   PyDict_SetItemString(d, "error", ErrorObject);
2045   Py_DECREF(ErrorObject);
2046
2047   /* needed for get/setMaterialType */
2048   KX_MACRO_addTypesToDict(d, KX_TEXFACE_MATERIAL, KX_TEXFACE_MATERIAL);
2049   KX_MACRO_addTypesToDict(d, KX_BLENDER_MULTITEX_MATERIAL, KX_BLENDER_MULTITEX_MATERIAL);
2050   KX_MACRO_addTypesToDict(d, KX_BLENDER_GLSL_MATERIAL, KX_BLENDER_GLSL_MATERIAL);
2051
2052   // XXXX Add constants here
2053
2054   // Check for errors
2055   if (PyErr_Occurred())
2056     {
2057       Py_FatalError("can't initialize module Rasterizer");
2058     }
2059
2060   return d;
2061 }
2062
2063
2064
2065 /* ------------------------------------------------------------------------- */
2066 /* GameKeys: symbolic constants for key mapping                              */
2067 /* ------------------------------------------------------------------------- */
2068
2069 static char GameKeys_module_documentation[] =
2070 "This modules provides defines for key-codes"
2071 ;
2072
2073 static char gPyEventToString_doc[] =
2074 "EventToString(event) - Take a valid event from the GameKeys module or Keyboard Sensor and return a name"
2075 ;
2076
2077 static PyObject* gPyEventToString(PyObject*, PyObject* value)
2078 {
2079         PyObject* mod, *dict, *key, *val, *ret = NULL;
2080         Py_ssize_t pos = 0;
2081         
2082         mod = PyImport_ImportModule( "GameKeys" );
2083         if (!mod)
2084                 return NULL;
2085         
2086         dict = PyModule_GetDict(mod);
2087         
2088         while (PyDict_Next(dict, &pos, &key, &val)) {
2089                 if (PyObject_RichCompareBool(value, val, Py_EQ)) {
2090                         ret = key;
2091                         break;
2092                 }
2093         }
2094         
2095         PyErr_Clear(); // incase there was an error clearing
2096         Py_DECREF(mod);
2097         if (!ret)       PyErr_SetString(PyExc_ValueError, "GameKeys.EventToString(int): expected a valid int keyboard event");
2098         else            Py_INCREF(ret);
2099         
2100         return ret;
2101 }
2102
2103 static char gPyEventToCharacter_doc[] =
2104 "EventToCharacter(event, is_shift) - Take a valid event from the GameKeys module or Keyboard Sensor and return a character"
2105 ;
2106
2107 static PyObject* gPyEventToCharacter(PyObject*, PyObject* args)
2108 {
2109         int event, shift;
2110         if (!PyArg_ParseTuple(args,"ii:EventToCharacter", &event, &shift))
2111                 return NULL;
2112         
2113         if(IsPrintable(event)) {
2114                 char ch[2] = {'\0', '\0'};
2115                 ch[0] = ToCharacter(event, (bool)shift);
2116                 return PyUnicode_FromString(ch);
2117         }
2118         else {
2119                 return PyUnicode_FromString("");
2120         }
2121 }
2122
2123
2124 static struct PyMethodDef gamekeys_methods[] = {
2125         {"EventToCharacter", (PyCFunction)gPyEventToCharacter, METH_VARARGS, (const char *)gPyEventToCharacter_doc},
2126         {"EventToString", (PyCFunction)gPyEventToString, METH_O, (const char *)gPyEventToString_doc},
2127         { NULL, (PyCFunction) NULL, 0, NULL }
2128 };
2129
2130 static struct PyModuleDef GameKeys_module_def = {
2131         {}, /* m_base */
2132         "GameKeys",  /* m_name */
2133         GameKeys_module_documentation,  /* m_doc */
2134         0,  /* m_size */
2135         gamekeys_methods,  /* m_methods */
2136         0,  /* m_reload */
2137         0,  /* m_traverse */
2138         0,  /* m_clear */
2139         0,  /* m_free */
2140 };
2141
2142 PyObject* initGameKeys()
2143 {
2144         PyObject* m;
2145         PyObject* d;
2146         PyObject* item;
2147         
2148         /* Use existing module where possible */
2149         m = PyImport_ImportModule( "GameKeys" );
2150         if(m) {
2151                 Py_DECREF(m);
2152                 return m;
2153         }
2154         else {
2155                 PyErr_Clear();
2156         
2157                 // Create the module and add the functions
2158                 m = PyModule_Create(&GameKeys_module_def);
2159                 PyDict_SetItemString(PySys_GetObject("modules"), GameKeys_module_def.m_name, m);
2160         }
2161
2162         // Add some symbolic constants to the module
2163         d = PyModule_GetDict(m);
2164
2165         // XXXX Add constants here
2166
2167         KX_MACRO_addTypesToDict(d, AKEY, SCA_IInputDevice::KX_AKEY);
2168         KX_MACRO_addTypesToDict(d, BKEY, SCA_IInputDevice::KX_BKEY);
2169         KX_MACRO_addTypesToDict(d, CKEY, SCA_IInputDevice::KX_CKEY);
2170         KX_MACRO_addTypesToDict(d, DKEY, SCA_IInputDevice::KX_DKEY);
2171         KX_MACRO_addTypesToDict(d, EKEY, SCA_IInputDevice::KX_EKEY);
2172         KX_MACRO_addTypesToDict(d, FKEY, SCA_IInputDevice::KX_FKEY);
2173         KX_MACRO_addTypesToDict(d, GKEY, SCA_IInputDevice::KX_GKEY);
2174         KX_MACRO_addTypesToDict(d, HKEY, SCA_IInputDevice::KX_HKEY);
2175         KX_MACRO_addTypesToDict(d, IKEY, SCA_IInputDevice::KX_IKEY);
2176         KX_MACRO_addTypesToDict(d, JKEY, SCA_IInputDevice::KX_JKEY);
2177         KX_MACRO_addTypesToDict(d, KKEY, SCA_IInputDevice::KX_KKEY);
2178         KX_MACRO_addTypesToDict(d, LKEY, SCA_IInputDevice::KX_LKEY);
2179         KX_MACRO_addTypesToDict(d, MKEY, SCA_IInputDevice::KX_MKEY);
2180         KX_MACRO_addTypesToDict(d, NKEY, SCA_IInputDevice::KX_NKEY);
2181         KX_MACRO_addTypesToDict(d, OKEY, SCA_IInputDevice::KX_OKEY);
2182         KX_MACRO_addTypesToDict(d, PKEY, SCA_IInputDevice::KX_PKEY);
2183         KX_MACRO_addTypesToDict(d, QKEY, SCA_IInputDevice::KX_QKEY);
2184         KX_MACRO_addTypesToDict(d, RKEY, SCA_IInputDevice::KX_RKEY);
2185         KX_MACRO_addTypesToDict(d, SKEY, SCA_IInputDevice::KX_SKEY);
2186         KX_MACRO_addTypesToDict(d, TKEY, SCA_IInputDevice::KX_TKEY);
2187         KX_MACRO_addTypesToDict(d, UKEY, SCA_IInputDevice::KX_UKEY);
2188         KX_MACRO_addTypesToDict(d, VKEY, SCA_IInputDevice::KX_VKEY);
2189         KX_MACRO_addTypesToDict(d, WKEY, SCA_IInputDevice::KX_WKEY);
2190         KX_MACRO_addTypesToDict(d, XKEY, SCA_IInputDevice::KX_XKEY);
2191         KX_MACRO_addTypesToDict(d, YKEY, SCA_IInputDevice::KX_YKEY);
2192         KX_MACRO_addTypesToDict(d, ZKEY, SCA_IInputDevice::KX_ZKEY);
2193         
2194         KX_MACRO_addTypesToDict(d, ZEROKEY, SCA_IInputDevice::KX_ZEROKEY);              
2195         KX_MACRO_addTypesToDict(d, ONEKEY, SCA_IInputDevice::KX_ONEKEY);                
2196         KX_MACRO_addTypesToDict(d, TWOKEY, SCA_IInputDevice::KX_TWOKEY);                
2197         KX_MACRO_addTypesToDict(d, THREEKEY, SCA_IInputDevice::KX_THREEKEY);
2198         KX_MACRO_addTypesToDict(d, FOURKEY, SCA_IInputDevice::KX_FOURKEY);              
2199         KX_MACRO_addTypesToDict(d, FIVEKEY, SCA_IInputDevice::KX_FIVEKEY);              
2200         KX_MACRO_addTypesToDict(d, SIXKEY, SCA_IInputDevice::KX_SIXKEY);                
2201         KX_MACRO_addTypesToDict(d, SEVENKEY, SCA_IInputDevice::KX_SEVENKEY);
2202         KX_MACRO_addTypesToDict(d, EIGHTKEY, SCA_IInputDevice::KX_EIGHTKEY);
2203         KX_MACRO_addTypesToDict(d, NINEKEY, SCA_IInputDevice::KX_NINEKEY);              
2204                 
2205         KX_MACRO_addTypesToDict(d, CAPSLOCKKEY, SCA_IInputDevice::KX_CAPSLOCKKEY);
2206                 
2207         KX_MACRO_addTypesToDict(d, LEFTCTRLKEY, SCA_IInputDevice::KX_LEFTCTRLKEY);      
2208         KX_MACRO_addTypesToDict(d, LEFTALTKEY, SCA_IInputDevice::KX_LEFTALTKEY);                
2209         KX_MACRO_addTypesToDict(d, RIGHTALTKEY, SCA_IInputDevice::KX_RIGHTALTKEY);      
2210         KX_MACRO_addTypesToDict(d, RIGHTCTRLKEY, SCA_IInputDevice::KX_RIGHTCTRLKEY);    
2211         KX_MACRO_addTypesToDict(d, RIGHTSHIFTKEY, SCA_IInputDevice::KX_RIGHTSHIFTKEY);  
2212         KX_MACRO_addTypesToDict(d, LEFTSHIFTKEY, SCA_IInputDevice::KX_LEFTSHIFTKEY);
2213                 
2214         KX_MACRO_addTypesToDict(d, ESCKEY, SCA_IInputDevice::KX_ESCKEY);
2215         KX_MACRO_addTypesToDict(d, TABKEY, SCA_IInputDevice::KX_TABKEY);
2216         KX_MACRO_addTypesToDict(d, RETKEY, SCA_IInputDevice::KX_RETKEY);
2217         KX_MACRO_addTypesToDict(d, SPACEKEY, SCA_IInputDevice::KX_SPACEKEY);
2218         KX_MACRO_addTypesToDict(d, LINEFEEDKEY, SCA_IInputDevice::KX_LINEFEEDKEY);              
2219         KX_MACRO_addTypesToDict(d, BACKSPACEKEY, SCA_IInputDevice::KX_BACKSPACEKEY);
2220         KX_MACRO_addTypesToDict(d, DELKEY, SCA_IInputDevice::KX_DELKEY);
2221         KX_MACRO_addTypesToDict(d, SEMICOLONKEY, SCA_IInputDevice::KX_SEMICOLONKEY);
2222         KX_MACRO_addTypesToDict(d, PERIODKEY, SCA_IInputDevice::KX_PERIODKEY);          
2223         KX_MACRO_addTypesToDict(d, COMMAKEY, SCA_IInputDevice::KX_COMMAKEY);            
2224         KX_MACRO_addTypesToDict(d, QUOTEKEY, SCA_IInputDevice::KX_QUOTEKEY);            
2225         KX_MACRO_addTypesToDict(d, ACCENTGRAVEKEY, SCA_IInputDevice::KX_ACCENTGRAVEKEY);        
2226         KX_MACRO_addTypesToDict(d, MINUSKEY, SCA_IInputDevice::KX_MINUSKEY);            
2227         KX_MACRO_addTypesToDict(d, SLASHKEY, SCA_IInputDevice::KX_SLASHKEY);            
2228         KX_MACRO_addTypesToDict(d, BACKSLASHKEY, SCA_IInputDevice::KX_BACKSLASHKEY);
2229         KX_MACRO_addTypesToDict(d, EQUALKEY, SCA_IInputDevice::KX_EQUALKEY);            
2230         KX_MACRO_addTypesToDict(d, LEFTBRACKETKEY, SCA_IInputDevice::KX_LEFTBRACKETKEY);        
2231         KX_MACRO_addTypesToDict(d, RIGHTBRACKETKEY, SCA_IInputDevice::KX_RIGHTBRACKETKEY);      
2232                 
2233         KX_MACRO_addTypesToDict(d, LEFTARROWKEY, SCA_IInputDevice::KX_LEFTARROWKEY);
2234         KX_MACRO_addTypesToDict(d, DOWNARROWKEY, SCA_IInputDevice::KX_DOWNARROWKEY);
2235         KX_MACRO_addTypesToDict(d, RIGHTARROWKEY, SCA_IInputDevice::KX_RIGHTARROWKEY);  
2236         KX_MACRO_addTypesToDict(d, UPARROWKEY, SCA_IInputDevice::KX_UPARROWKEY);                
2237         
2238         KX_MACRO_addTypesToDict(d, PAD2 , SCA_IInputDevice::KX_PAD2);
2239         KX_MACRO_addTypesToDict(d, PAD4 , SCA_IInputDevice::KX_PAD4);
2240         KX_MACRO_addTypesToDict(d, PAD6 , SCA_IInputDevice::KX_PAD6);
2241         KX_MACRO_addTypesToDict(d, PAD8 , SCA_IInputDevice::KX_PAD8);
2242                 
2243         KX_MACRO_addTypesToDict(d, PAD1 , SCA_IInputDevice::KX_PAD1);
2244         KX_MACRO_addTypesToDict(d, PAD3 , SCA_IInputDevice::KX_PAD3);
2245         KX_MACRO_addTypesToDict(d, PAD5 , SCA_IInputDevice::KX_PAD5);
2246         KX_MACRO_addTypesToDict(d, PAD7 , SCA_IInputDevice::KX_PAD7);
2247         KX_MACRO_addTypesToDict(d, PAD9 , SCA_IInputDevice::KX_PAD9);
2248                 
2249         KX_MACRO_addTypesToDict(d, PADPERIOD, SCA_IInputDevice::KX_PADPERIOD);
2250         KX_MACRO_addTypesToDict(d, PADSLASHKEY, SCA_IInputDevice::KX_PADSLASHKEY);
2251         KX_MACRO_addTypesToDict(d, PADASTERKEY, SCA_IInputDevice::KX_PADASTERKEY);
2252                 
2253                 
2254         KX_MACRO_addTypesToDict(d, PAD0, SCA_IInputDevice::KX_PAD0);
2255         KX_MACRO_addTypesToDict(d, PADMINUS, SCA_IInputDevice::KX_PADMINUS);
2256         KX_MACRO_addTypesToDict(d, PADENTER, SCA_IInputDevice::KX_PADENTER);
2257         KX_MACRO_addTypesToDict(d, PADPLUSKEY, SCA_IInputDevice::KX_PADPLUSKEY);
2258                 
2259                 
2260         KX_MACRO_addTypesToDict(d, F1KEY , SCA_IInputDevice::KX_F1KEY);
2261         KX_MACRO_addTypesToDict(d, F2KEY , SCA_IInputDevice::KX_F2KEY);
2262         KX_MACRO_addTypesToDict(d, F3KEY , SCA_IInputDevice::KX_F3KEY);
2263         KX_MACRO_addTypesToDict(d, F4KEY , SCA_IInputDevice::KX_F4KEY);
2264         KX_MACRO_addTypesToDict(d, F5KEY , SCA_IInputDevice::KX_F5KEY);
2265         KX_MACRO_addTypesToDict(d, F6KEY , SCA_IInputDevice::KX_F6KEY);
2266         KX_MACRO_addTypesToDict(d, F7KEY , SCA_IInputDevice::KX_F7KEY);
2267         KX_MACRO_addTypesToDict(d, F8KEY , SCA_IInputDevice::KX_F8KEY);
2268         KX_MACRO_addTypesToDict(d, F9KEY , SCA_IInputDevice::KX_F9KEY);
2269         KX_MACRO_addTypesToDict(d, F10KEY, SCA_IInputDevice::KX_F10KEY);
2270         KX_MACRO_addTypesToDict(d, F11KEY, SCA_IInputDevice::KX_F11KEY);
2271         KX_MACRO_addTypesToDict(d, F12KEY, SCA_IInputDevice::KX_F12KEY);
2272         KX_MACRO_addTypesToDict(d, F13KEY, SCA_IInputDevice::KX_F13KEY);
2273         KX_MACRO_addTypesToDict(d, F14KEY, SCA_IInputDevice::KX_F14KEY);
2274         KX_MACRO_addTypesToDict(d, F15KEY, SCA_IInputDevice::KX_F15KEY);
2275         KX_MACRO_addTypesToDict(d, F16KEY, SCA_IInputDevice::KX_F16KEY);
2276         KX_MACRO_addTypesToDict(d, F17KEY, SCA_IInputDevice::KX_F17KEY);
2277         KX_MACRO_addTypesToDict(d, F18KEY, SCA_IInputDevice::KX_F18KEY);
2278         KX_MACRO_addTypesToDict(d, F19KEY, SCA_IInputDevice::KX_F19KEY);
2279                 
2280         KX_MACRO_addTypesToDict(d, PAUSEKEY, SCA_IInputDevice::KX_PAUSEKEY);
2281         KX_MACRO_addTypesToDict(d, INSERTKEY, SCA_IInputDevice::KX_INSERTKEY);
2282         KX_MACRO_addTypesToDict(d, HOMEKEY , SCA_IInputDevice::KX_HOMEKEY);
2283         KX_MACRO_addTypesToDict(d, PAGEUPKEY, SCA_IInputDevice::KX_PAGEUPKEY);
2284         KX_MACRO_addTypesToDict(d, PAGEDOWNKEY, SCA_IInputDevice::KX_PAGEDOWNKEY);
2285         KX_MACRO_addTypesToDict(d, ENDKEY, SCA_IInputDevice::KX_ENDKEY);
2286
2287         // MOUSE
2288         KX_MACRO_addTypesToDict(d, LEFTMOUSE, SCA_IInputDevice::KX_LEFTMOUSE);
2289         KX_MACRO_addTypesToDict(d, MIDDLEMOUSE, SCA_IInputDevice::KX_MIDDLEMOUSE);
2290         KX_MACRO_addTypesToDict(d, RIGHTMOUSE, SCA_IInputDevice::KX_RIGHTMOUSE);
2291         KX_MACRO_addTypesToDict(d, WHEELUPMOUSE, SCA_IInputDevice::KX_WHEELUPMOUSE);
2292         KX_MACRO_addTypesToDict(d, WHEELDOWNMOUSE, SCA_IInputDevice::KX_WHEELDOWNMOUSE);
2293         KX_MACRO_addTypesToDict(d, MOUSEX, SCA_IInputDevice::KX_MOUSEX);
2294         KX_MACRO_addTypesToDict(d, MOUSEY, SCA_IInputDevice::KX_MOUSEY);
2295
2296         // Check for errors
2297         if (PyErr_Occurred())
2298     {
2299                 Py_FatalError("can't initialize module GameKeys");
2300     }
2301
2302         return d;
2303 }
2304
2305 PyObject* initMathutils()
2306 {
2307         return Mathutils_Init();
2308 }
2309
2310 PyObject* initGeometry()
2311 {
2312         return Geometry_Init();
2313 }
2314
2315 PyObject* initBGL()
2316 {
2317         return BGL_Init();
2318 }
2319
2320 PyObject* initBLF()
2321 {
2322         return BLF_Init();
2323 }
2324
2325 // utility function for loading and saving the globalDict
2326 int saveGamePythonConfig( char **marshal_buffer)
2327 {
2328         int marshal_length = 0;
2329         PyObject* gameLogic = PyImport_ImportModule("GameLogic");
2330         if (gameLogic) {
2331                 PyObject* pyGlobalDict = PyDict_GetItemString(PyModule_GetDict(gameLogic), "globalDict"); // Same as importing the module
2332                 if (pyGlobalDict) {
2333 #ifdef Py_MARSHAL_VERSION       
2334                         PyObject* pyGlobalDictMarshal = PyMarshal_WriteObjectToString(  pyGlobalDict, 2); // Py_MARSHAL_VERSION == 2 as of Py2.5
2335 #else
2336                         PyObject* pyGlobalDictMarshal = PyMarshal_WriteObjectToString(  pyGlobalDict ); 
2337 #endif
2338                         if (pyGlobalDictMarshal) {
2339                                 // for testing only
2340                                 // PyObject_Print(pyGlobalDictMarshal, stderr, 0);
2341                                 char *marshal_cstring;
2342                                 
2343                                 marshal_cstring = PyBytes_AsString(pyGlobalDictMarshal); // py3 uses byte arrays
2344                                 marshal_length= PyBytes_Size(pyGlobalDictMarshal);
2345                                 *marshal_buffer = new char[marshal_length + 1];
2346                                 memcpy(*marshal_buffer, marshal_cstring, marshal_length);
2347                                 Py_DECREF(pyGlobalDictMarshal);
2348                         } else {
2349                                 printf("Error, bge.logic.globalDict could not be marshal'd\n");
2350                         }
2351                 } else {
2352                         printf("Error, bge.logic.globalDict was removed\n");
2353                 }
2354                 Py_DECREF(gameLogic);
2355         } else {
2356                 PyErr_Clear();
2357                 printf("Error, bge.logic failed to import bge.logic.globalDict will be lost\n");
2358         }
2359         return marshal_length;
2360 }
2361
2362 int loadGamePythonConfig(char *marshal_buffer, int marshal_length)
2363 {
2364         /* Restore the dict */
2365         if (marshal_buffer) {
2366                 PyObject* gameLogic = PyImport_ImportModule("GameLogic");
2367
2368                 if (gameLogic) {
2369                         PyObject* pyGlobalDict = PyMarshal_ReadObjectFromString(marshal_buffer, marshal_length);
2370                         if (pyGlobalDict) {
2371                                 PyObject* pyGlobalDict_orig = PyDict_GetItemString(PyModule_GetDict(gameLogic), "globalDict"); // Same as importing the module.
2372                                 if (pyGlobalDict_orig) {
2373                                         PyDict_Clear(pyGlobalDict_orig);
2374                                         PyDict_Update(pyGlobalDict_orig, pyGlobalDict);
2375                                 } else {
2376                                         /* this should not happen, but cant find the original globalDict, just assign it then */
2377                                         PyDict_SetItemString(PyModule_GetDict(gameLogic), "globalDict", pyGlobalDict); // Same as importing the module.
2378                                 }
2379                                 Py_DECREF(gameLogic);
2380                                 Py_DECREF(pyGlobalDict);
2381                                 return 1;
2382                         } else {
2383                                 Py_DECREF(gameLogic);
2384                                 PyErr_Clear();
2385                                 printf("Error could not marshall string\n");
2386                         }
2387                 } else {
2388                         PyErr_Clear();
2389                         printf("Error, bge.logic failed to import bge.logic.globalDict will be lost\n");
2390                 }       
2391         }
2392         return 0;
2393 }
2394
2395 void pathGamePythonConfig( char *path )
2396 {
2397         int len = strlen(gp_GamePythonPathOrig); // Always use the first loaded blend filename
2398         
2399         BLI_strncpy(path, gp_GamePythonPathOrig, sizeof(gp_GamePythonPathOrig));
2400
2401         /* replace extension */
2402         if (BLI_testextensie(path, ".blend")) {
2403                 strcpy(path+(len-6), ".bgeconf");
2404         } else {
2405                 strcpy(path+len, ".bgeconf");
2406         }
2407 }
2408
2409 void setGamePythonPath(char *path)
2410 {
2411         BLI_strncpy(gp_GamePythonPath, path, sizeof(gp_GamePythonPath));
2412         BLI_cleanup_file(NULL, gp_GamePythonPath); /* not absolutely needed but makes resolving path problems less confusing later */
2413         
2414         if (gp_GamePythonPathOrig[0] == '\0')
2415                 BLI_strncpy(gp_GamePythonPathOrig, path, sizeof(gp_GamePythonPathOrig));
2416 }
2417
2418 // we need this so while blender is open (not blenderplayer)
2419 // loading new blendfiles will reset this on starting the
2420 // engine but loading blend files within the BGE wont overwrite gp_GamePythonPathOrig
2421 void resetGamePythonPath()
2422 {
2423         gp_GamePythonPathOrig[0] = '\0';
2424 }
2425
2426 #endif // DISABLE_PYTHON