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