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