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