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