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