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