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