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