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