BGE API cleanup: apply patch from Moguri: Near, Radar, Touch sensor updated.
[blender.git] / source / gameengine / Ketsji / KX_PythonInit.cpp
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  * Initialize Python thingies.
29  */
30
31 #include "GL/glew.h"
32
33 // directory header for py function getBlendFileList
34 #include <stdlib.h>
35 #ifndef WIN32
36   #include <dirent.h>
37 #else
38   #include "BLI_winstuff.h"
39 #endif
40
41 #ifdef WIN32
42 #pragma warning (disable : 4786)
43 #endif //WIN32
44
45 #include "KX_PythonInit.h"
46 //python physics binding
47 #include "KX_PyConstraintBinding.h"
48
49 #include "KX_KetsjiEngine.h"
50 #include "KX_RadarSensor.h"
51
52 #include "SCA_IInputDevice.h"
53 #include "SCA_PropertySensor.h"
54 #include "SCA_RandomActuator.h"
55 #include "KX_ConstraintActuator.h"
56 #include "KX_IpoActuator.h"
57 #include "KX_SoundActuator.h"
58 #include "BL_ActionActuator.h"
59 #include "RAS_IRasterizer.h"
60 #include "RAS_ICanvas.h"
61 #include "RAS_BucketManager.h"
62 #include "MT_Vector3.h"
63 #include "MT_Point3.h"
64 #include "ListValue.h"
65 #include "KX_Scene.h"
66 #include "SND_DeviceManager.h"
67
68 #include "BL_Shader.h"
69
70 #include "KX_PyMath.h"
71
72 #include "PyObjectPlus.h" 
73
74 extern "C" {
75         #include "Mathutils.h" // Blender.Mathutils module copied here so the blenderlayer can use.
76 }
77
78 #include "marshal.h" /* python header for loading/saving dicts */
79
80 #include "PHY_IPhysicsEnvironment.h"
81 // FIXME: Enable for access to blender python modules.  This is disabled because
82 // python has dependencies on a lot of other modules and is a pain to link.
83 //#define USE_BLENDER_PYTHON
84 #ifdef USE_BLENDER_PYTHON
85 //#include "BPY_extern.h"
86 #endif 
87
88 #include "BKE_utildefines.h"
89 #include "BKE_global.h"
90 #include "BLI_blenlib.h"
91 #include "GPU_material.h"
92
93 static void setSandbox(TPythonSecurityLevel level);
94
95
96 // 'local' copy of canvas ptr, for window height/width python scripts
97 static RAS_ICanvas* gp_Canvas = NULL;
98 static KX_Scene*        gp_KetsjiScene = NULL;
99 static KX_KetsjiEngine* gp_KetsjiEngine = NULL;
100 static RAS_IRasterizer* gp_Rasterizer = NULL;
101 static char gp_GamePythonPath[FILE_MAXDIR + FILE_MAXFILE] = "";
102
103 void    KX_RasterizerDrawDebugLine(const MT_Vector3& from,const MT_Vector3& to,const MT_Vector3& color)
104 {
105         if (gp_Rasterizer)
106                 gp_Rasterizer->DrawDebugLine(from,to,color);
107 }
108
109 /* Macro for building the keyboard translation */
110 //#define KX_MACRO_addToDict(dict, name) PyDict_SetItemString(dict, #name, PyInt_FromLong(SCA_IInputDevice::KX_##name))
111 #define KX_MACRO_addToDict(dict, name) PyDict_SetItemString(dict, #name, PyInt_FromLong(name))
112 /* For the defines for types from logic bricks, we do stuff explicitly... */
113 #define KX_MACRO_addTypesToDict(dict, name, name2) PyDict_SetItemString(dict, #name, PyInt_FromLong(name2))
114
115
116 // temporarily python stuff, will be put in another place later !
117 #include "KX_Python.h"
118 #include "SCA_PythonController.h"
119 // List of methods defined in the module
120
121 static PyObject* ErrorObject;
122 STR_String gPyGetRandomFloat_doc="getRandomFloat returns a random floating point value in the range [0..1)";
123
124 static PyObject* gPyGetRandomFloat(PyObject*)
125 {
126         return PyFloat_FromDouble(MT_random());
127 }
128
129 static PyObject* gPySetGravity(PyObject*, PyObject* value)
130 {
131         MT_Vector3 vec;
132         if (!PyVecTo(value, vec))
133                 return NULL;
134
135         if (gp_KetsjiScene)
136                 gp_KetsjiScene->SetGravity(vec);
137         
138         Py_RETURN_NONE;
139 }
140
141 static char gPyExpandPath_doc[] =
142 "(path) - Converts a blender internal path into a proper file system path.\n\
143 path - the string path to convert.\n\n\
144 Use / as directory separator in path\n\
145 You can use '//' at the start of the string to define a relative path;\n\
146 Blender replaces that string by the directory of the startup .blend or runtime\n\
147 file to make a full path name (doesn't change during the game, even if you load\n\
148 other .blend).\n\
149 The function also converts the directory separator to the local file system format.";
150
151 static PyObject* gPyExpandPath(PyObject*, PyObject* args)
152 {
153         char expanded[FILE_MAXDIR + FILE_MAXFILE];
154         char* filename;
155         
156         if (!PyArg_ParseTuple(args,"s",&filename))
157                 return NULL;
158
159         BLI_strncpy(expanded, filename, FILE_MAXDIR + FILE_MAXFILE);
160         BLI_convertstringcode(expanded, gp_GamePythonPath);
161         return PyString_FromString(expanded);
162 }
163
164
165 static bool usedsp = false;
166
167 // this gets a pointer to an array filled with floats
168 static PyObject* gPyGetSpectrum(PyObject*)
169 {
170         SND_IAudioDevice* audiodevice = SND_DeviceManager::Instance();
171
172         PyObject* resultlist = PyList_New(512);
173
174         if (audiodevice)
175         {
176                 if (!usedsp)
177                 {
178                         audiodevice->StartUsingDSP();
179                         usedsp = true;
180                 }
181                         
182                 float* spectrum = audiodevice->GetSpectrum();
183
184                 for (int index = 0; index < 512; index++)
185                 {
186                         PyList_SetItem(resultlist, index, PyFloat_FromDouble(spectrum[index]));
187                 }
188         }
189         else {
190                 for (int index = 0; index < 512; index++)
191                 {
192                         PyList_SetItem(resultlist, index, PyFloat_FromDouble(0.0));
193                 }
194         }
195
196         return resultlist;
197 }
198
199
200 #if 0 // unused
201 static PyObject* gPyStartDSP(PyObject*, PyObject* args)
202 {
203         SND_IAudioDevice* audiodevice = SND_DeviceManager::Instance();
204
205         if (!audiodevice) {
206                 PyErr_SetString(PyExc_RuntimeError, "no audio device available");
207                 return NULL;
208         }
209         
210         if (!usedsp) {
211                 audiodevice->StartUsingDSP();
212                 usedsp = true;
213         }
214         
215         Py_RETURN_NONE;
216 }
217 #endif
218
219
220 static PyObject* gPyStopDSP(PyObject*, PyObject* args)
221 {
222         SND_IAudioDevice* audiodevice = SND_DeviceManager::Instance();
223
224         if (!audiodevice) {
225                 PyErr_SetString(PyExc_RuntimeError, "no audio device available");
226                 return NULL;
227         }
228         
229         if (usedsp) {
230                 audiodevice->StopUsingDSP();
231                 usedsp = true;
232         }
233         
234         Py_RETURN_NONE;
235 }
236
237 static PyObject* gPySetLogicTicRate(PyObject*, PyObject* args)
238 {
239         float ticrate;
240         if (!PyArg_ParseTuple(args, "f", &ticrate))
241                 return NULL;
242         
243         KX_KetsjiEngine::SetTicRate(ticrate);
244         Py_RETURN_NONE;
245 }
246
247 static PyObject* gPyGetLogicTicRate(PyObject*)
248 {
249         return PyFloat_FromDouble(KX_KetsjiEngine::GetTicRate());
250 }
251
252 static PyObject* gPySetPhysicsTicRate(PyObject*, PyObject* args)
253 {
254         float ticrate;
255         if (!PyArg_ParseTuple(args, "f", &ticrate))
256                 return NULL;
257         
258         PHY_GetActiveEnvironment()->setFixedTimeStep(true,ticrate);
259         Py_RETURN_NONE;
260 }
261 #if 0 // unused
262 static PyObject* gPySetPhysicsDebug(PyObject*, PyObject* args)
263 {
264         int debugMode;
265         if (!PyArg_ParseTuple(args, "i", &debugMode))
266                 return NULL;
267         
268         PHY_GetActiveEnvironment()->setDebugMode(debugMode);
269         Py_RETURN_NONE;
270 }
271 #endif
272
273
274 static PyObject* gPyGetPhysicsTicRate(PyObject*)
275 {
276         return PyFloat_FromDouble(PHY_GetActiveEnvironment()->getFixedTimeStep());
277 }
278
279 static PyObject* gPyGetAverageFrameRate(PyObject*)
280 {
281         return PyFloat_FromDouble(KX_KetsjiEngine::GetAverageFrameRate());
282 }
283
284 static PyObject* gPyGetBlendFileList(PyObject*, PyObject* args)
285 {
286         char cpath[sizeof(gp_GamePythonPath)];
287         char *searchpath = NULL;
288         PyObject* list, *value;
289         
290     DIR *dp;
291     struct dirent *dirp;
292         
293         if (!PyArg_ParseTuple(args, "|s", &searchpath))
294                 return NULL;
295         
296         list = PyList_New(0);
297         
298         if (searchpath) {
299                 BLI_strncpy(cpath, searchpath, FILE_MAXDIR + FILE_MAXFILE);
300                 BLI_convertstringcode(cpath, gp_GamePythonPath);
301         } else {
302                 /* Get the dir only */
303                 BLI_split_dirfile_basic(gp_GamePythonPath, cpath, NULL);
304         }
305         
306     if((dp  = opendir(cpath)) == NULL) {
307                 /* todo, show the errno, this shouldnt happen anyway if the blendfile is readable */
308                 fprintf(stderr, "Could not read directoty (%s) failed, code %d (%s)\n", cpath, errno, strerror(errno));
309                 return list;
310     }
311         
312     while ((dirp = readdir(dp)) != NULL) {
313                 if (BLI_testextensie(dirp->d_name, ".blend")) {
314                         value = PyString_FromString(dirp->d_name);
315                         PyList_Append(list, value);
316                         Py_DECREF(value);
317                 }
318     }
319         
320     closedir(dp);
321     return list;
322 }
323
324 static STR_String gPyGetCurrentScene_doc =  
325 "getCurrentScene()\n"
326 "Gets a reference to the current scene.\n";
327 static PyObject* gPyGetCurrentScene(PyObject* self)
328 {
329         Py_INCREF(gp_KetsjiScene);
330         return (PyObject*) gp_KetsjiScene;
331 }
332
333 static STR_String gPyGetSceneList_doc =  
334 "getSceneList()\n"
335 "Return a list of converted scenes.\n";
336 static PyObject* gPyGetSceneList(PyObject* self)
337 {
338         KX_KetsjiEngine* m_engine = KX_GetActiveEngine();
339         //CListValue* list = new CListValue();
340         PyObject* list;
341         KX_SceneList* scenes = m_engine->CurrentScenes();
342         int numScenes = scenes->size();
343         int i;
344         
345         list = PyList_New(numScenes);
346         
347         for (i=0;i<numScenes;i++)
348         {
349                 KX_Scene* scene = scenes->at(i);
350                 //list->Add(scene);
351                 PyList_SET_ITEM(list, i, scene);
352                 Py_INCREF(scene);
353                 
354         }
355         
356         return (PyObject*)list;
357 }
358
359 static PyObject *pyPrintExt(PyObject *,PyObject *,PyObject *)
360 {
361 #define pprint(x) std::cout << x << std::endl;
362         bool count=0;
363         bool support=0;
364         pprint("Supported Extensions...");
365         pprint(" GL_ARB_shader_objects supported?       "<< (GLEW_ARB_shader_objects?"yes.":"no."));
366         count = 1;
367
368         support= GLEW_ARB_vertex_shader;
369         pprint(" GL_ARB_vertex_shader supported?        "<< (support?"yes.":"no."));
370         count = 1;
371         if(support){
372                 pprint(" ----------Details----------");
373                 int max=0;
374                 glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB, (GLint*)&max);
375                 pprint("  Max uniform components." << max);
376
377                 glGetIntegerv(GL_MAX_VARYING_FLOATS_ARB, (GLint*)&max);
378                 pprint("  Max varying floats." << max);
379
380                 glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB, (GLint*)&max);
381                 pprint("  Max vertex texture units." << max);
382         
383                 glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB, (GLint*)&max);
384                 pprint("  Max combined texture units." << max);
385                 pprint("");
386         }
387
388         support=GLEW_ARB_fragment_shader;
389         pprint(" GL_ARB_fragment_shader supported?      "<< (support?"yes.":"no."));
390         count = 1;
391         if(support){
392                 pprint(" ----------Details----------");
393                 int max=0;
394                 glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB, (GLint*)&max);
395                 pprint("  Max uniform components." << max);
396                 pprint("");
397         }
398
399         support = GLEW_ARB_texture_cube_map;
400         pprint(" GL_ARB_texture_cube_map supported?     "<< (support?"yes.":"no."));
401         count = 1;
402         if(support){
403                 pprint(" ----------Details----------");
404                 int size=0;
405                 glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB, (GLint*)&size);
406                 pprint("  Max cubemap size." << size);
407                 pprint("");
408         }
409
410         support = GLEW_ARB_multitexture;
411         count = 1;
412         pprint(" GL_ARB_multitexture supported?         "<< (support?"yes.":"no."));
413         if(support){
414                 pprint(" ----------Details----------");
415                 int units=0;
416                 glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, (GLint*)&units);
417                 pprint("  Max texture units available.  " << units);
418                 pprint("");
419         }
420
421         pprint(" GL_ARB_texture_env_combine supported?  "<< (GLEW_ARB_texture_env_combine?"yes.":"no."));
422         count = 1;
423
424         if(!count)
425                 pprint("No extenstions are used in this build");
426
427         Py_RETURN_NONE;
428 }
429
430
431 static struct PyMethodDef game_methods[] = {
432         {"expandPath", (PyCFunction)gPyExpandPath, METH_VARARGS, (PY_METHODCHAR)gPyExpandPath_doc},
433         {"getCurrentController",
434         (PyCFunction) SCA_PythonController::sPyGetCurrentController,
435         METH_NOARGS, (PY_METHODCHAR)SCA_PythonController::sPyGetCurrentController__doc__},
436         {"getCurrentScene", (PyCFunction) gPyGetCurrentScene,
437         METH_NOARGS, (PY_METHODCHAR)gPyGetCurrentScene_doc.Ptr()},
438         {"getSceneList", (PyCFunction) gPyGetSceneList,
439         METH_NOARGS, (PY_METHODCHAR)gPyGetSceneList_doc.Ptr()},
440         {"addActiveActuator",(PyCFunction) SCA_PythonController::sPyAddActiveActuator,
441         METH_VARARGS, (PY_METHODCHAR)SCA_PythonController::sPyAddActiveActuator__doc__},
442         {"getRandomFloat",(PyCFunction) gPyGetRandomFloat,
443         METH_NOARGS, (PY_METHODCHAR)gPyGetRandomFloat_doc.Ptr()},
444         {"setGravity",(PyCFunction) gPySetGravity, METH_O, (PY_METHODCHAR)"set Gravitation"},
445         {"getSpectrum",(PyCFunction) gPyGetSpectrum, METH_NOARGS, (PY_METHODCHAR)"get audio spectrum"},
446         {"stopDSP",(PyCFunction) gPyStopDSP, METH_VARARGS, (PY_METHODCHAR)"stop using the audio dsp (for performance reasons)"},
447         {"getLogicTicRate", (PyCFunction) gPyGetLogicTicRate, METH_NOARGS, (PY_METHODCHAR)"Gets the logic tic rate"},
448         {"setLogicTicRate", (PyCFunction) gPySetLogicTicRate, METH_VARARGS, (PY_METHODCHAR)"Sets the logic tic rate"},
449         {"getPhysicsTicRate", (PyCFunction) gPyGetPhysicsTicRate, METH_NOARGS, (PY_METHODCHAR)"Gets the physics tic rate"},
450         {"setPhysicsTicRate", (PyCFunction) gPySetPhysicsTicRate, METH_VARARGS, (PY_METHODCHAR)"Sets the physics tic rate"},
451         {"getAverageFrameRate", (PyCFunction) gPyGetAverageFrameRate, METH_NOARGS, (PY_METHODCHAR)"Gets the estimated average frame rate"},
452         {"getBlendFileList", (PyCFunction)gPyGetBlendFileList, METH_VARARGS, (PY_METHODCHAR)"Gets a list of blend files in the same directory as the current blend file"},
453         {"PrintGLInfo", (PyCFunction)pyPrintExt, METH_NOARGS, (PY_METHODCHAR)"Prints GL Extension Info"},
454         {NULL, (PyCFunction) NULL, 0, NULL }
455 };
456
457
458 static PyObject* gPyGetWindowHeight(PyObject*, PyObject* args)
459 {
460         return PyInt_FromLong((gp_Canvas ? gp_Canvas->GetHeight() : 0));
461 }
462
463
464
465 static PyObject* gPyGetWindowWidth(PyObject*, PyObject* args)
466 {
467         return PyInt_FromLong((gp_Canvas ? gp_Canvas->GetWidth() : 0));
468 }
469
470
471
472 // temporarility visibility thing, will be moved to rasterizer/renderer later
473 bool gUseVisibilityTemp = false;
474
475 static PyObject* gPyEnableVisibility(PyObject*, PyObject* args)
476 {
477         int visible;
478         if (!PyArg_ParseTuple(args,"i",&visible))
479                 return NULL;
480         
481         gUseVisibilityTemp = (visible != 0);
482         Py_RETURN_NONE;
483 }
484
485
486
487 static PyObject* gPyShowMouse(PyObject*, PyObject* args)
488 {
489         int visible;
490         if (!PyArg_ParseTuple(args,"i",&visible))
491                 return NULL;
492         
493         if (visible)
494         {
495                 if (gp_Canvas)
496                         gp_Canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
497         } else
498         {
499                 if (gp_Canvas)
500                         gp_Canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE);
501         }
502         
503         Py_RETURN_NONE;
504 }
505
506
507
508 static PyObject* gPySetMousePosition(PyObject*, PyObject* args)
509 {
510         int x,y;
511         if (!PyArg_ParseTuple(args,"ii",&x,&y))
512                 return NULL;
513         
514         if (gp_Canvas)
515                 gp_Canvas->SetMousePosition(x,y);
516         
517         Py_RETURN_NONE;
518 }
519
520 static PyObject* gPySetEyeSeparation(PyObject*, PyObject* args)
521 {
522         float sep;
523         if (!PyArg_ParseTuple(args, "f", &sep))
524                 return NULL;
525
526         if (!gp_Rasterizer) {
527                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
528                 return NULL;
529         }
530         
531         gp_Rasterizer->SetEyeSeparation(sep);
532         
533         Py_RETURN_NONE;
534 }
535
536 static PyObject* gPyGetEyeSeparation(PyObject*, PyObject*, PyObject*)
537 {
538         if (!gp_Rasterizer) {
539                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
540                 return NULL;
541         }
542         
543         return PyFloat_FromDouble(gp_Rasterizer->GetEyeSeparation());
544 }
545
546 static PyObject* gPySetFocalLength(PyObject*, PyObject* args)
547 {
548         float focus;
549         if (!PyArg_ParseTuple(args, "f", &focus))
550                 return NULL;
551         
552         if (!gp_Rasterizer) {
553                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
554                 return NULL;
555         }
556
557         gp_Rasterizer->SetFocalLength(focus);
558         
559         Py_RETURN_NONE;
560 }
561
562 static PyObject* gPyGetFocalLength(PyObject*, PyObject*, PyObject*)
563 {
564         if (!gp_Rasterizer) {
565                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
566                 return NULL;
567         }
568         
569         return PyFloat_FromDouble(gp_Rasterizer->GetFocalLength());
570         
571         Py_RETURN_NONE;
572 }
573
574 static PyObject* gPySetBackgroundColor(PyObject*, PyObject* value)
575 {
576         
577         MT_Vector4 vec;
578         if (!PyVecTo(value, vec))
579                 return NULL;
580         
581         if (gp_Canvas)
582         {
583                 gp_Rasterizer->SetBackColor(vec[0], vec[1], vec[2], vec[3]);
584         }
585         Py_RETURN_NONE;
586 }
587
588
589
590 static PyObject* gPySetMistColor(PyObject*, PyObject* value)
591 {
592         
593         MT_Vector3 vec;
594         if (!PyVecTo(value, vec))
595                 return NULL;
596         
597         if (!gp_Rasterizer) {
598                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
599                 return NULL;
600         }       
601         gp_Rasterizer->SetFogColor(vec[0], vec[1], vec[2]);
602         
603         Py_RETURN_NONE;
604 }
605
606
607
608 static PyObject* gPySetMistStart(PyObject*, PyObject* args)
609 {
610
611         float miststart;
612         if (!PyArg_ParseTuple(args,"f",&miststart))
613                 return NULL;
614         
615         if (!gp_Rasterizer) {
616                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
617                 return NULL;
618         }
619         
620         gp_Rasterizer->SetFogStart(miststart);
621         
622         Py_RETURN_NONE;
623 }
624
625
626
627 static PyObject* gPySetMistEnd(PyObject*, PyObject* args)
628 {
629
630         float mistend;
631         if (!PyArg_ParseTuple(args,"f",&mistend))
632                 return NULL;
633         
634         if (!gp_Rasterizer) {
635                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
636                 return NULL;
637         }
638         
639         gp_Rasterizer->SetFogEnd(mistend);
640         
641         Py_RETURN_NONE;
642 }
643
644
645 static PyObject* gPySetAmbientColor(PyObject*, PyObject* value)
646 {
647         
648         MT_Vector3 vec;
649         if (!PyVecTo(value, vec))
650                 return NULL;
651         
652         if (!gp_Rasterizer) {
653                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
654                 return NULL;
655         }       
656         gp_Rasterizer->SetAmbientColor(vec[0], vec[1], vec[2]);
657         
658         Py_RETURN_NONE;
659 }
660
661
662
663
664 static PyObject* gPyMakeScreenshot(PyObject*, PyObject* args)
665 {
666         char* filename;
667         if (!PyArg_ParseTuple(args,"s",&filename))
668                 return NULL;
669         
670         if (gp_Canvas)
671         {
672                 gp_Canvas->MakeScreenShot(filename);
673         }
674         
675         Py_RETURN_NONE;
676 }
677
678 static PyObject* gPyEnableMotionBlur(PyObject*, PyObject* args)
679 {
680         float motionblurvalue;
681         if (!PyArg_ParseTuple(args,"f",&motionblurvalue))
682                 return NULL;
683         
684         if (!gp_Rasterizer) {
685                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
686                 return NULL;
687         }
688         
689         gp_Rasterizer->EnableMotionBlur(motionblurvalue);
690         
691         Py_RETURN_NONE;
692 }
693
694 static PyObject* gPyDisableMotionBlur(PyObject*, PyObject* args)
695 {
696         if (!gp_Rasterizer) {
697                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
698                 return NULL;
699         }
700         
701         gp_Rasterizer->DisableMotionBlur();
702         
703         Py_RETURN_NONE;
704 }
705
706 int getGLSLSettingFlag(char *setting)
707 {
708         if(strcmp(setting, "lights") == 0)
709                 return G_FILE_GLSL_NO_LIGHTS;
710         else if(strcmp(setting, "shaders") == 0)
711                 return G_FILE_GLSL_NO_SHADERS;
712         else if(strcmp(setting, "shadows") == 0)
713                 return G_FILE_GLSL_NO_SHADOWS;
714         else if(strcmp(setting, "ramps") == 0)
715                 return G_FILE_GLSL_NO_RAMPS;
716         else if(strcmp(setting, "nodes") == 0)
717                 return G_FILE_GLSL_NO_NODES;
718         else if(strcmp(setting, "extra_textures") == 0)
719                 return G_FILE_GLSL_NO_EXTRA_TEX;
720         else
721                 return -1;
722 }
723
724 static PyObject* gPySetGLSLMaterialSetting(PyObject*,
725                                                                                         PyObject* args,
726                                                                                         PyObject*)
727 {
728         char *setting;
729         int enable, flag, fileflags;
730
731         if (!PyArg_ParseTuple(args,"si",&setting,&enable))
732                 return NULL;
733         
734         flag = getGLSLSettingFlag(setting);
735         
736         if  (flag==-1) {
737                 PyErr_SetString(PyExc_ValueError, "glsl setting is not known");
738                 return NULL;
739         }
740
741         fileflags = G.fileflags;
742         
743         if (enable)
744                 G.fileflags &= ~flag;
745         else
746                 G.fileflags |= flag;
747
748         /* display lists and GLSL materials need to be remade */
749         if(G.fileflags != fileflags) {
750                 if(gp_KetsjiEngine) {
751                         KX_SceneList *scenes = gp_KetsjiEngine->CurrentScenes();
752                         KX_SceneList::iterator it;
753
754                         for(it=scenes->begin(); it!=scenes->end(); it++)
755                                 if((*it)->GetBucketManager())
756                                         (*it)->GetBucketManager()->ReleaseDisplayLists();
757                 }
758
759                 GPU_materials_free();
760         }
761
762         Py_RETURN_NONE;
763 }
764
765 static PyObject* gPyGetGLSLMaterialSetting(PyObject*, 
766                                                                          PyObject* args, 
767                                                                          PyObject*)
768 {
769         char *setting;
770         int enabled = 0, flag;
771
772         if (!PyArg_ParseTuple(args,"s",&setting))
773                 return NULL;
774         
775         flag = getGLSLSettingFlag(setting);
776         
777         if  (flag==-1) {
778                 PyErr_SetString(PyExc_ValueError, "glsl setting is not known");
779                 return NULL;
780         }
781
782         enabled = ((G.fileflags & flag) != 0);
783         return PyInt_FromLong(enabled);
784 }
785
786 #define KX_TEXFACE_MATERIAL                             0
787 #define KX_BLENDER_MULTITEX_MATERIAL    1
788 #define KX_BLENDER_GLSL_MATERIAL                2
789
790 static PyObject* gPySetMaterialType(PyObject*,
791                                                                         PyObject* args,
792                                                                         PyObject*)
793 {
794         int flag, type;
795
796         if (!PyArg_ParseTuple(args,"i",&type))
797                 return NULL;
798
799         if(type == KX_BLENDER_GLSL_MATERIAL)
800                 flag = G_FILE_GAME_MAT|G_FILE_GAME_MAT_GLSL;
801         else if(type == KX_BLENDER_MULTITEX_MATERIAL)
802                 flag = G_FILE_GAME_MAT;
803         else if(type == KX_TEXFACE_MATERIAL)
804                 flag = 0;
805         else {
806                 PyErr_SetString(PyExc_ValueError, "material type is not known");
807                 return NULL;
808         }
809
810         G.fileflags &= ~(G_FILE_GAME_MAT|G_FILE_GAME_MAT_GLSL);
811         G.fileflags |= flag;
812
813         Py_RETURN_NONE;
814 }
815
816 static PyObject* gPyGetMaterialType(PyObject*)
817 {
818         int flag;
819
820         if(G.fileflags & (G_FILE_GAME_MAT|G_FILE_GAME_MAT_GLSL))
821                 flag = KX_BLENDER_GLSL_MATERIAL;
822         else if(G.fileflags & G_FILE_GAME_MAT)
823                 flag = KX_BLENDER_MULTITEX_MATERIAL;
824         else
825                 flag = KX_TEXFACE_MATERIAL;
826         
827         return PyInt_FromLong(flag);
828 }
829
830 static PyObject* gPyDrawLine(PyObject*, PyObject* args)
831 {
832         PyObject* ob_from;
833         PyObject* ob_to;
834         PyObject* ob_color;
835
836         if (!gp_Rasterizer) {
837                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
838                 return NULL;
839         }
840
841         if (!PyArg_ParseTuple(args,"OOO",&ob_from,&ob_to,&ob_color))
842                 return NULL;
843
844         MT_Vector3 from;
845         MT_Vector3 to;
846         MT_Vector3 color;
847         if (!PyVecTo(ob_from, from))
848                 return NULL;
849         if (!PyVecTo(ob_to, to))
850                 return NULL;
851         if (!PyVecTo(ob_color, color))
852                 return NULL;
853
854         gp_Rasterizer->DrawDebugLine(from,to,color);
855         
856         Py_RETURN_NONE;
857 }
858
859 static struct PyMethodDef rasterizer_methods[] = {
860   {"getWindowWidth",(PyCFunction) gPyGetWindowWidth,
861    METH_VARARGS, "getWindowWidth doc"},
862    {"getWindowHeight",(PyCFunction) gPyGetWindowHeight,
863    METH_VARARGS, "getWindowHeight doc"},
864   {"makeScreenshot",(PyCFunction)gPyMakeScreenshot,
865         METH_VARARGS, "make Screenshot doc"},
866    {"enableVisibility",(PyCFunction) gPyEnableVisibility,
867    METH_VARARGS, "enableVisibility doc"},
868         {"showMouse",(PyCFunction) gPyShowMouse,
869    METH_VARARGS, "showMouse(bool visible)"},
870    {"setMousePosition",(PyCFunction) gPySetMousePosition,
871    METH_VARARGS, "setMousePosition(int x,int y)"},
872   {"setBackgroundColor",(PyCFunction)gPySetBackgroundColor,METH_O,"set Background Color (rgb)"},
873         {"setAmbientColor",(PyCFunction)gPySetAmbientColor,METH_O,"set Ambient Color (rgb)"},
874  {"setMistColor",(PyCFunction)gPySetMistColor,METH_O,"set Mist Color (rgb)"},
875   {"setMistStart",(PyCFunction)gPySetMistStart,METH_VARARGS,"set Mist Start(rgb)"},
876   {"setMistEnd",(PyCFunction)gPySetMistEnd,METH_VARARGS,"set Mist End(rgb)"},
877   {"enableMotionBlur",(PyCFunction)gPyEnableMotionBlur,METH_VARARGS,"enable motion blur"},
878   {"disableMotionBlur",(PyCFunction)gPyDisableMotionBlur,METH_VARARGS,"disable motion blur"},
879
880   
881   {"setEyeSeparation", (PyCFunction) gPySetEyeSeparation, METH_VARARGS, "set the eye separation for stereo mode"},
882   {"getEyeSeparation", (PyCFunction) gPyGetEyeSeparation, METH_VARARGS, "get the eye separation for stereo mode"},
883   {"setFocalLength", (PyCFunction) gPySetFocalLength, METH_VARARGS, "set the focal length for stereo mode"},
884   {"getFocalLength", (PyCFunction) gPyGetFocalLength, METH_VARARGS, "get the focal length for stereo mode"},
885   {"setMaterialMode",(PyCFunction) gPySetMaterialType,
886    METH_VARARGS, "set the material mode to use for OpenGL rendering"},
887   {"getMaterialMode",(PyCFunction) gPyGetMaterialType,
888    METH_NOARGS, "get the material mode being used for OpenGL rendering"},
889   {"setGLSLMaterialSetting",(PyCFunction) gPySetGLSLMaterialSetting,
890    METH_VARARGS, "set the state of a GLSL material setting"},
891   {"getGLSLMaterialSetting",(PyCFunction) gPyGetGLSLMaterialSetting,
892    METH_VARARGS, "get the state of a GLSL material setting"},
893   {"drawLine", (PyCFunction) gPyDrawLine,
894    METH_VARARGS, "draw a line on the screen"},
895   { NULL, (PyCFunction) NULL, 0, NULL }
896 };
897
898 // Initialization function for the module (*must* be called initGameLogic)
899
900 static char GameLogic_module_documentation[] =
901 "This is the Python API for the game engine of GameLogic"
902 ;
903
904 static char Rasterizer_module_documentation[] =
905 "This is the Python API for the game engine of Rasterizer"
906 ;
907
908
909
910 PyObject* initGameLogic(KX_KetsjiEngine *engine, KX_Scene* scene) // quick hack to get gravity hook
911 {
912         PyObject* m;
913         PyObject* d;
914
915         gp_KetsjiEngine = engine;
916         gp_KetsjiScene = scene;
917
918         gUseVisibilityTemp=false;
919
920         // Create the module and add the functions
921         m = Py_InitModule4("GameLogic", game_methods,
922                                            GameLogic_module_documentation,
923                                            (PyObject*)NULL,PYTHON_API_VERSION);
924
925         // Add some symbolic constants to the module
926         d = PyModule_GetDict(m);
927         
928         // can be overwritten later for gameEngine instances that can load new blend files and re-initialize this module
929         // for now its safe to make sure it exists for other areas such as the web plugin
930         PyDict_SetItemString(d, "globalDict", PyDict_New());
931
932         ErrorObject = PyString_FromString("GameLogic.error");
933         PyDict_SetItemString(d, "error", ErrorObject);
934         
935         // XXXX Add constants here
936         /* To use logic bricks, we need some sort of constants. Here, we associate */
937         /* constants and sumbolic names. Add them to dictionary d.                 */
938
939         /* 1. true and false: needed for everyone                                  */
940         KX_MACRO_addTypesToDict(d, KX_TRUE,  SCA_ILogicBrick::KX_TRUE);
941         KX_MACRO_addTypesToDict(d, KX_FALSE, SCA_ILogicBrick::KX_FALSE);
942
943         /* 2. Property sensor                                                      */
944         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_EQUAL,      SCA_PropertySensor::KX_PROPSENSOR_EQUAL);
945         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_NOTEQUAL,   SCA_PropertySensor::KX_PROPSENSOR_NOTEQUAL);
946         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_INTERVAL,   SCA_PropertySensor::KX_PROPSENSOR_INTERVAL);
947         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_CHANGED,    SCA_PropertySensor::KX_PROPSENSOR_CHANGED);
948         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_EXPRESSION, SCA_PropertySensor::KX_PROPSENSOR_EXPRESSION);
949
950         /* 3. Constraint actuator                                                  */
951         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCX);
952         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCY);
953         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCZ);
954         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTX);
955         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTY);
956         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTZ);
957         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPX);
958         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPY);
959         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPY);
960         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNX);
961         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNY);
962         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNY);
963         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIX);
964         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIY);
965         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIZ);
966
967         /* 4. Ipo actuator, simple part                                            */
968         KX_MACRO_addTypesToDict(d, KX_IPOACT_PLAY,     KX_IpoActuator::KX_ACT_IPO_PLAY);
969         KX_MACRO_addTypesToDict(d, KX_IPOACT_PINGPONG, KX_IpoActuator::KX_ACT_IPO_PINGPONG);
970         KX_MACRO_addTypesToDict(d, KX_IPOACT_FLIPPER,  KX_IpoActuator::KX_ACT_IPO_FLIPPER);
971         KX_MACRO_addTypesToDict(d, KX_IPOACT_LOOPSTOP, KX_IpoActuator::KX_ACT_IPO_LOOPSTOP);
972         KX_MACRO_addTypesToDict(d, KX_IPOACT_LOOPEND,  KX_IpoActuator::KX_ACT_IPO_LOOPEND);
973
974         /* 5. Random distribution types                                            */
975         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_CONST,      SCA_RandomActuator::KX_RANDOMACT_BOOL_CONST);
976         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_UNIFORM,    SCA_RandomActuator::KX_RANDOMACT_BOOL_UNIFORM);
977         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_BERNOUILLI, SCA_RandomActuator::KX_RANDOMACT_BOOL_BERNOUILLI);
978         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_CONST,       SCA_RandomActuator::KX_RANDOMACT_INT_CONST);
979         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_UNIFORM,     SCA_RandomActuator::KX_RANDOMACT_INT_UNIFORM);
980         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_POISSON,     SCA_RandomActuator::KX_RANDOMACT_INT_POISSON);
981         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_CONST,     SCA_RandomActuator::KX_RANDOMACT_FLOAT_CONST);
982         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_UNIFORM,   SCA_RandomActuator::KX_RANDOMACT_FLOAT_UNIFORM);
983         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_NORMAL,    SCA_RandomActuator::KX_RANDOMACT_FLOAT_NORMAL);
984         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL, SCA_RandomActuator::KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL);
985
986         /* 6. Sound actuator                                                      */
987         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYSTOP,              KX_SoundActuator::KX_SOUNDACT_PLAYSTOP);
988         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYEND,               KX_SoundActuator::KX_SOUNDACT_PLAYEND);
989         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPSTOP,              KX_SoundActuator::KX_SOUNDACT_LOOPSTOP);
990         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPEND,               KX_SoundActuator::KX_SOUNDACT_LOOPEND);
991         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL,     KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL);
992         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP,     KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP);
993
994         /* 7. Action actuator                                                                                                      */
995         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_PLAY,        ACT_ACTION_PLAY);
996         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_FLIPPER,     ACT_ACTION_FLIPPER);
997         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_LOOPSTOP,    ACT_ACTION_LOOP_STOP);
998         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_LOOPEND,     ACT_ACTION_LOOP_END);
999         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_PROPERTY,    ACT_ACTION_FROM_PROP);
1000         
1001         /*8. GL_BlendFunc */
1002         KX_MACRO_addTypesToDict(d, BL_ZERO, GL_ZERO);
1003         KX_MACRO_addTypesToDict(d, BL_ONE, GL_ONE);
1004         KX_MACRO_addTypesToDict(d, BL_SRC_COLOR, GL_SRC_COLOR);
1005         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR);
1006         KX_MACRO_addTypesToDict(d, BL_DST_COLOR, GL_DST_COLOR);
1007         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_DST_COLOR);
1008         KX_MACRO_addTypesToDict(d, BL_SRC_ALPHA, GL_SRC_ALPHA);
1009         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1010         KX_MACRO_addTypesToDict(d, BL_DST_ALPHA, GL_DST_ALPHA);
1011         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA);
1012         KX_MACRO_addTypesToDict(d, BL_SRC_ALPHA_SATURATE, GL_SRC_ALPHA_SATURATE);
1013
1014
1015         /* 9. UniformTypes */
1016         KX_MACRO_addTypesToDict(d, SHD_TANGENT, BL_Shader::SHD_TANGENT);
1017         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX, BL_Shader::MODELVIEWMATRIX);
1018         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_TRANSPOSE, BL_Shader::MODELVIEWMATRIX_TRANSPOSE);
1019         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_INVERSE, BL_Shader::MODELVIEWMATRIX_INVERSE);
1020         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_INVERSETRANSPOSE, BL_Shader::MODELVIEWMATRIX_INVERSETRANSPOSE);
1021         KX_MACRO_addTypesToDict(d, MODELMATRIX, BL_Shader::MODELMATRIX);
1022         KX_MACRO_addTypesToDict(d, MODELMATRIX_TRANSPOSE, BL_Shader::MODELMATRIX_TRANSPOSE);
1023         KX_MACRO_addTypesToDict(d, MODELMATRIX_INVERSE, BL_Shader::MODELMATRIX_INVERSE);
1024         KX_MACRO_addTypesToDict(d, MODELMATRIX_INVERSETRANSPOSE, BL_Shader::MODELMATRIX_INVERSETRANSPOSE);
1025         KX_MACRO_addTypesToDict(d, VIEWMATRIX, BL_Shader::VIEWMATRIX);
1026         KX_MACRO_addTypesToDict(d, VIEWMATRIX_TRANSPOSE, BL_Shader::VIEWMATRIX_TRANSPOSE);
1027         KX_MACRO_addTypesToDict(d, VIEWMATRIX_INVERSE, BL_Shader::VIEWMATRIX_INVERSE);
1028         KX_MACRO_addTypesToDict(d, VIEWMATRIX_INVERSETRANSPOSE, BL_Shader::VIEWMATRIX_INVERSETRANSPOSE);
1029         KX_MACRO_addTypesToDict(d, CAM_POS, BL_Shader::CAM_POS);
1030         KX_MACRO_addTypesToDict(d, CONSTANT_TIMER, BL_Shader::CONSTANT_TIMER);
1031
1032         /* 10 state actuator */
1033         KX_MACRO_addTypesToDict(d, KX_STATE1, (1<<0));
1034         KX_MACRO_addTypesToDict(d, KX_STATE2, (1<<1));
1035         KX_MACRO_addTypesToDict(d, KX_STATE3, (1<<2));
1036         KX_MACRO_addTypesToDict(d, KX_STATE4, (1<<3));
1037         KX_MACRO_addTypesToDict(d, KX_STATE5, (1<<4));
1038         KX_MACRO_addTypesToDict(d, KX_STATE6, (1<<5));
1039         KX_MACRO_addTypesToDict(d, KX_STATE7, (1<<6));
1040         KX_MACRO_addTypesToDict(d, KX_STATE8, (1<<7));
1041         KX_MACRO_addTypesToDict(d, KX_STATE9, (1<<8));
1042         KX_MACRO_addTypesToDict(d, KX_STATE10, (1<<9));
1043         KX_MACRO_addTypesToDict(d, KX_STATE11, (1<<10));
1044         KX_MACRO_addTypesToDict(d, KX_STATE12, (1<<11));
1045         KX_MACRO_addTypesToDict(d, KX_STATE13, (1<<12));
1046         KX_MACRO_addTypesToDict(d, KX_STATE14, (1<<13));
1047         KX_MACRO_addTypesToDict(d, KX_STATE15, (1<<14));
1048         KX_MACRO_addTypesToDict(d, KX_STATE16, (1<<15));
1049         KX_MACRO_addTypesToDict(d, KX_STATE17, (1<<16));
1050         KX_MACRO_addTypesToDict(d, KX_STATE18, (1<<17));
1051         KX_MACRO_addTypesToDict(d, KX_STATE19, (1<<18));
1052         KX_MACRO_addTypesToDict(d, KX_STATE20, (1<<19));
1053         KX_MACRO_addTypesToDict(d, KX_STATE21, (1<<20));
1054         KX_MACRO_addTypesToDict(d, KX_STATE22, (1<<21));
1055         KX_MACRO_addTypesToDict(d, KX_STATE23, (1<<22));
1056         KX_MACRO_addTypesToDict(d, KX_STATE24, (1<<23));
1057         KX_MACRO_addTypesToDict(d, KX_STATE25, (1<<24));
1058         KX_MACRO_addTypesToDict(d, KX_STATE26, (1<<25));
1059         KX_MACRO_addTypesToDict(d, KX_STATE27, (1<<26));
1060         KX_MACRO_addTypesToDict(d, KX_STATE28, (1<<27));
1061         KX_MACRO_addTypesToDict(d, KX_STATE29, (1<<28));
1062         KX_MACRO_addTypesToDict(d, KX_STATE30, (1<<29));
1063
1064         /* Radar Sensor */
1065         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_POS_X, KX_RadarSensor::KX_RADAR_AXIS_POS_X);
1066         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_POS_Y, KX_RadarSensor::KX_RADAR_AXIS_POS_Y);
1067         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_POS_Z, KX_RadarSensor::KX_RADAR_AXIS_POS_Z);
1068         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_NEG_X, KX_RadarSensor::KX_RADAR_AXIS_NEG_Y);
1069         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_NEG_Y, KX_RadarSensor::KX_RADAR_AXIS_NEG_X);
1070         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_NEG_Z, KX_RadarSensor::KX_RADAR_AXIS_NEG_Z);
1071
1072         // Check for errors
1073         if (PyErr_Occurred())
1074     {
1075                 Py_FatalError("can't initialize module GameLogic");
1076     }
1077
1078         return m;
1079 }
1080
1081 // Python Sandbox code
1082 // override builtin functions import() and open()
1083
1084
1085 PyObject *KXpy_open(PyObject *self, PyObject *args) {
1086         PyErr_SetString(PyExc_RuntimeError, "Sandbox: open() function disabled!\nGame Scripts should not use this function.");
1087         return NULL;
1088 }
1089
1090 PyObject *KXpy_reload(PyObject *self, PyObject *args) {
1091         PyErr_SetString(PyExc_RuntimeError, "Sandbox: reload() function disabled!\nGame Scripts should not use this function.");
1092         return NULL;
1093 }
1094
1095 PyObject *KXpy_file(PyObject *self, PyObject *args) {
1096         PyErr_SetString(PyExc_RuntimeError, "Sandbox: file() function disabled!\nGame Scripts should not use this function.");
1097         return NULL;
1098 }
1099
1100 PyObject *KXpy_execfile(PyObject *self, PyObject *args) {
1101         PyErr_SetString(PyExc_RuntimeError, "Sandbox: execfile() function disabled!\nGame Scripts should not use this function.");
1102         return NULL;
1103 }
1104
1105 PyObject *KXpy_compile(PyObject *self, PyObject *args) {
1106         PyErr_SetString(PyExc_RuntimeError, "Sandbox: compile() function disabled!\nGame Scripts should not use this function.");
1107         return NULL;
1108 }
1109
1110 PyObject *KXpy_import(PyObject *self, PyObject *args)
1111 {
1112         char *name;
1113         PyObject *globals = NULL;
1114         PyObject *locals = NULL;
1115         PyObject *fromlist = NULL;
1116         PyObject *l, *m, *n;
1117
1118 #if (PY_VERSION_HEX >= 0x02060000)
1119         int dummy_val; /* what does this do?*/
1120         
1121         if (!PyArg_ParseTuple(args, "s|OOOi:m_import",
1122                 &name, &globals, &locals, &fromlist, &dummy_val))
1123             return NULL;
1124 #else
1125         if (!PyArg_ParseTuple(args, "s|OOO:m_import",
1126                 &name, &globals, &locals, &fromlist))
1127             return NULL;
1128 #endif
1129
1130         /* check for builtin modules */
1131         m = PyImport_AddModule("sys");
1132         l = PyObject_GetAttrString(m, "builtin_module_names");
1133         n = PyString_FromString(name);
1134         
1135         if (PySequence_Contains(l, n)) {
1136                 return PyImport_ImportModuleEx(name, globals, locals, fromlist);
1137         }
1138
1139         /* quick hack for GamePython modules 
1140                 TODO: register builtin modules properly by ExtendInittab */
1141         if (!strcmp(name, "GameLogic") || !strcmp(name, "GameKeys") || !strcmp(name, "PhysicsConstraints") ||
1142                 !strcmp(name, "Rasterizer") || !strcmp(name, "Mathutils")) {
1143                 return PyImport_ImportModuleEx(name, globals, locals, fromlist);
1144         }
1145                 
1146         PyErr_Format(PyExc_ImportError,
1147                  "Import of external Module %.20s not allowed.", name);
1148         return NULL;
1149
1150 }
1151
1152 /* override python file type functions */
1153 #if 0
1154 static int
1155 file_init(PyObject *self, PyObject *args, PyObject *kwds)
1156 {
1157         KXpy_file(NULL, NULL);
1158         return -1;
1159 }
1160
1161 static PyObject *
1162 file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1163 {
1164         return KXpy_file(NULL, NULL);
1165 }
1166 #endif
1167
1168 static PyMethodDef meth_open[] = {{ "open", KXpy_open, METH_VARARGS, "(disabled)"}};
1169 static PyMethodDef meth_reload[] = {{ "reload", KXpy_reload, METH_VARARGS, "(disabled)"}};
1170 static PyMethodDef meth_file[] = {{ "file", KXpy_file, METH_VARARGS, "(disabled)"}};
1171 static PyMethodDef meth_execfile[] = {{ "execfile", KXpy_execfile, METH_VARARGS, "(disabled)"}};
1172 static PyMethodDef meth_compile[] = {{ "compile", KXpy_compile, METH_VARARGS, "(disabled)"}};
1173
1174 static PyMethodDef meth_import[] = {{ "import", KXpy_import, METH_VARARGS, "our own import"}};
1175
1176 //static PyObject *g_oldopen = 0;
1177 //static PyObject *g_oldimport = 0;
1178 //static int g_security = 0;
1179
1180 void setSandbox(TPythonSecurityLevel level)
1181 {
1182     PyObject *m = PyImport_AddModule("__builtin__");
1183     PyObject *d = PyModule_GetDict(m);
1184
1185         switch (level) {
1186         case psl_Highest:
1187                 //if (!g_security) {
1188                         //g_oldopen = PyDict_GetItemString(d, "open");
1189         
1190                         // functions we cant trust
1191                         PyDict_SetItemString(d, "open", PyCFunction_New(meth_open, NULL));
1192                         PyDict_SetItemString(d, "reload", PyCFunction_New(meth_reload, NULL));
1193                         PyDict_SetItemString(d, "file", PyCFunction_New(meth_file, NULL));
1194                         PyDict_SetItemString(d, "execfile", PyCFunction_New(meth_execfile, NULL));
1195                         PyDict_SetItemString(d, "compile", PyCFunction_New(meth_compile, NULL));
1196                         
1197                         // our own import
1198                         PyDict_SetItemString(d, "__import__", PyCFunction_New(meth_import, NULL));
1199                         //g_security = level;
1200                         
1201                         // Overiding file dosnt stop it being accessed if your sneaky
1202                         //    f =  [ t for t in (1).__class__.__mro__[-1].__subclasses__() if t.__name__ == 'file'][0]('/some_file.txt', 'w')
1203                         //    f.write('...')
1204                         // so overwrite the file types functions. be very careful here still, since python uses python.
1205                         // ps - python devs frown deeply upon this.
1206         
1207                         /* this could mess up pythons internals, if we are serious about sandboxing
1208                          * issues like the one above need to be solved, possibly modify __subclasses__ is safer? */
1209 #if 0
1210                         PyFile_Type.tp_init = file_init;
1211                         PyFile_Type.tp_new = file_new;
1212 #endif
1213                 //}
1214                 break;
1215         /*
1216         case psl_Lowest:
1217                 if (g_security) {
1218                         PyDict_SetItemString(d, "open", g_oldopen);
1219                         PyDict_SetItemString(d, "__import__", g_oldimport);
1220                         g_security = level;
1221                 }
1222         */
1223         default:
1224                 break;
1225         }
1226 }
1227
1228 /**
1229  * Python is not initialised.
1230  */
1231 PyObject* initGamePlayerPythonScripting(const STR_String& progname, TPythonSecurityLevel level)
1232 {
1233         STR_String pname = progname;
1234         Py_SetProgramName(pname.Ptr());
1235         Py_NoSiteFlag=1;
1236         Py_FrozenFlag=1;
1237         Py_Initialize();
1238
1239         //importBlenderModules()
1240         
1241         setSandbox(level);
1242
1243         PyObject* moduleobj = PyImport_AddModule("__main__");
1244         return PyModule_GetDict(moduleobj);
1245 }
1246
1247 void exitGamePlayerPythonScripting()
1248 {
1249         Py_Finalize();
1250 }
1251
1252 /**
1253  * Python is already initialized.
1254  */
1255 PyObject* initGamePythonScripting(const STR_String& progname, TPythonSecurityLevel level)
1256 {
1257         STR_String pname = progname;
1258         Py_SetProgramName(pname.Ptr());
1259         Py_NoSiteFlag=1;
1260         Py_FrozenFlag=1;
1261
1262         setSandbox(level);
1263
1264         PyObject* moduleobj = PyImport_AddModule("__main__");
1265         return PyModule_GetDict(moduleobj);
1266 }
1267
1268
1269
1270 void exitGamePythonScripting()
1271 {
1272 }
1273
1274
1275
1276 PyObject* initRasterizer(RAS_IRasterizer* rasty,RAS_ICanvas* canvas)
1277 {
1278         gp_Canvas = canvas;
1279         gp_Rasterizer = rasty;
1280
1281
1282   PyObject* m;
1283   PyObject* d;
1284
1285   // Create the module and add the functions
1286   m = Py_InitModule4("Rasterizer", rasterizer_methods,
1287                      Rasterizer_module_documentation,
1288                      (PyObject*)NULL,PYTHON_API_VERSION);
1289
1290   // Add some symbolic constants to the module
1291   d = PyModule_GetDict(m);
1292   ErrorObject = PyString_FromString("Rasterizer.error");
1293   PyDict_SetItemString(d, "error", ErrorObject);
1294
1295   /* needed for get/setMaterialType */
1296   KX_MACRO_addTypesToDict(d, KX_TEXFACE_MATERIAL, KX_TEXFACE_MATERIAL);
1297   KX_MACRO_addTypesToDict(d, KX_BLENDER_MULTITEX_MATERIAL, KX_BLENDER_MULTITEX_MATERIAL);
1298   KX_MACRO_addTypesToDict(d, KX_BLENDER_GLSL_MATERIAL, KX_BLENDER_GLSL_MATERIAL);
1299
1300   // XXXX Add constants here
1301
1302   // Check for errors
1303   if (PyErr_Occurred())
1304     {
1305       Py_FatalError("can't initialize module Rasterizer");
1306     }
1307
1308   return d;
1309 }
1310
1311
1312
1313 /* ------------------------------------------------------------------------- */
1314 /* GameKeys: symbolic constants for key mapping                              */
1315 /* ------------------------------------------------------------------------- */
1316
1317 static char GameKeys_module_documentation[] =
1318 "This modules provides defines for key-codes"
1319 ;
1320
1321 static char gPyEventToString_doc[] =
1322 "Take a valid event from the GameKeys module or Keyboard Sensor and return a name"
1323 ;
1324
1325 static PyObject* gPyEventToString(PyObject*, PyObject* value)
1326 {
1327         PyObject* mod, *dict, *key, *val, *ret = NULL;
1328         Py_ssize_t pos = 0;
1329         
1330         mod = PyImport_ImportModule( "GameKeys" );
1331         if (!mod)
1332                 return NULL;
1333         
1334         dict = PyModule_GetDict(mod);
1335         
1336         while (PyDict_Next(dict, &pos, &key, &val)) {
1337                 if (PyObject_Compare(value, val)==0) {
1338                         ret = key;
1339                         break;
1340                 }
1341         }
1342         
1343         PyErr_Clear(); // incase there was an error clearing
1344         Py_DECREF(mod);
1345         if (!ret)       PyErr_SetString(PyExc_ValueError, "expected a valid int keyboard event");
1346         else            Py_INCREF(ret);
1347         
1348         return ret;
1349 }
1350
1351 static struct PyMethodDef gamekeys_methods[] = {
1352         {"EventToString", (PyCFunction)gPyEventToString, METH_O, (PY_METHODCHAR)gPyEventToString_doc},
1353         { NULL, (PyCFunction) NULL, 0, NULL }
1354 };
1355
1356
1357
1358 PyObject* initGameKeys()
1359 {
1360         PyObject* m;
1361         PyObject* d;
1362
1363         // Create the module and add the functions
1364         m = Py_InitModule4("GameKeys", gamekeys_methods,
1365                                            GameKeys_module_documentation,
1366                                            (PyObject*)NULL,PYTHON_API_VERSION);
1367
1368         // Add some symbolic constants to the module
1369         d = PyModule_GetDict(m);
1370
1371         // XXXX Add constants here
1372
1373         KX_MACRO_addTypesToDict(d, AKEY, SCA_IInputDevice::KX_AKEY);
1374         KX_MACRO_addTypesToDict(d, BKEY, SCA_IInputDevice::KX_BKEY);
1375         KX_MACRO_addTypesToDict(d, CKEY, SCA_IInputDevice::KX_CKEY);
1376         KX_MACRO_addTypesToDict(d, DKEY, SCA_IInputDevice::KX_DKEY);
1377         KX_MACRO_addTypesToDict(d, EKEY, SCA_IInputDevice::KX_EKEY);
1378         KX_MACRO_addTypesToDict(d, FKEY, SCA_IInputDevice::KX_FKEY);
1379         KX_MACRO_addTypesToDict(d, GKEY, SCA_IInputDevice::KX_GKEY);
1380         KX_MACRO_addTypesToDict(d, HKEY, SCA_IInputDevice::KX_HKEY);
1381         KX_MACRO_addTypesToDict(d, IKEY, SCA_IInputDevice::KX_IKEY);
1382         KX_MACRO_addTypesToDict(d, JKEY, SCA_IInputDevice::KX_JKEY);
1383         KX_MACRO_addTypesToDict(d, KKEY, SCA_IInputDevice::KX_KKEY);
1384         KX_MACRO_addTypesToDict(d, LKEY, SCA_IInputDevice::KX_LKEY);
1385         KX_MACRO_addTypesToDict(d, MKEY, SCA_IInputDevice::KX_MKEY);
1386         KX_MACRO_addTypesToDict(d, NKEY, SCA_IInputDevice::KX_NKEY);
1387         KX_MACRO_addTypesToDict(d, OKEY, SCA_IInputDevice::KX_OKEY);
1388         KX_MACRO_addTypesToDict(d, PKEY, SCA_IInputDevice::KX_PKEY);
1389         KX_MACRO_addTypesToDict(d, QKEY, SCA_IInputDevice::KX_QKEY);
1390         KX_MACRO_addTypesToDict(d, RKEY, SCA_IInputDevice::KX_RKEY);
1391         KX_MACRO_addTypesToDict(d, SKEY, SCA_IInputDevice::KX_SKEY);
1392         KX_MACRO_addTypesToDict(d, TKEY, SCA_IInputDevice::KX_TKEY);
1393         KX_MACRO_addTypesToDict(d, UKEY, SCA_IInputDevice::KX_UKEY);
1394         KX_MACRO_addTypesToDict(d, VKEY, SCA_IInputDevice::KX_VKEY);
1395         KX_MACRO_addTypesToDict(d, WKEY, SCA_IInputDevice::KX_WKEY);
1396         KX_MACRO_addTypesToDict(d, XKEY, SCA_IInputDevice::KX_XKEY);
1397         KX_MACRO_addTypesToDict(d, YKEY, SCA_IInputDevice::KX_YKEY);
1398         KX_MACRO_addTypesToDict(d, ZKEY, SCA_IInputDevice::KX_ZKEY);
1399         
1400         KX_MACRO_addTypesToDict(d, ZEROKEY, SCA_IInputDevice::KX_ZEROKEY);              
1401         KX_MACRO_addTypesToDict(d, ONEKEY, SCA_IInputDevice::KX_ONEKEY);                
1402         KX_MACRO_addTypesToDict(d, TWOKEY, SCA_IInputDevice::KX_TWOKEY);                
1403         KX_MACRO_addTypesToDict(d, THREEKEY, SCA_IInputDevice::KX_THREEKEY);
1404         KX_MACRO_addTypesToDict(d, FOURKEY, SCA_IInputDevice::KX_FOURKEY);              
1405         KX_MACRO_addTypesToDict(d, FIVEKEY, SCA_IInputDevice::KX_FIVEKEY);              
1406         KX_MACRO_addTypesToDict(d, SIXKEY, SCA_IInputDevice::KX_SIXKEY);                
1407         KX_MACRO_addTypesToDict(d, SEVENKEY, SCA_IInputDevice::KX_SEVENKEY);
1408         KX_MACRO_addTypesToDict(d, EIGHTKEY, SCA_IInputDevice::KX_EIGHTKEY);
1409         KX_MACRO_addTypesToDict(d, NINEKEY, SCA_IInputDevice::KX_NINEKEY);              
1410                 
1411         KX_MACRO_addTypesToDict(d, CAPSLOCKKEY, SCA_IInputDevice::KX_CAPSLOCKKEY);
1412                 
1413         KX_MACRO_addTypesToDict(d, LEFTCTRLKEY, SCA_IInputDevice::KX_LEFTCTRLKEY);      
1414         KX_MACRO_addTypesToDict(d, LEFTALTKEY, SCA_IInputDevice::KX_LEFTALTKEY);                
1415         KX_MACRO_addTypesToDict(d, RIGHTALTKEY, SCA_IInputDevice::KX_RIGHTALTKEY);      
1416         KX_MACRO_addTypesToDict(d, RIGHTCTRLKEY, SCA_IInputDevice::KX_RIGHTCTRLKEY);    
1417         KX_MACRO_addTypesToDict(d, RIGHTSHIFTKEY, SCA_IInputDevice::KX_RIGHTSHIFTKEY);  
1418         KX_MACRO_addTypesToDict(d, LEFTSHIFTKEY, SCA_IInputDevice::KX_LEFTSHIFTKEY);
1419                 
1420         KX_MACRO_addTypesToDict(d, ESCKEY, SCA_IInputDevice::KX_ESCKEY);
1421         KX_MACRO_addTypesToDict(d, TABKEY, SCA_IInputDevice::KX_TABKEY);
1422         KX_MACRO_addTypesToDict(d, RETKEY, SCA_IInputDevice::KX_RETKEY);
1423         KX_MACRO_addTypesToDict(d, SPACEKEY, SCA_IInputDevice::KX_SPACEKEY);
1424         KX_MACRO_addTypesToDict(d, LINEFEEDKEY, SCA_IInputDevice::KX_LINEFEEDKEY);              
1425         KX_MACRO_addTypesToDict(d, BACKSPACEKEY, SCA_IInputDevice::KX_BACKSPACEKEY);
1426         KX_MACRO_addTypesToDict(d, DELKEY, SCA_IInputDevice::KX_DELKEY);
1427         KX_MACRO_addTypesToDict(d, SEMICOLONKEY, SCA_IInputDevice::KX_SEMICOLONKEY);
1428         KX_MACRO_addTypesToDict(d, PERIODKEY, SCA_IInputDevice::KX_PERIODKEY);          
1429         KX_MACRO_addTypesToDict(d, COMMAKEY, SCA_IInputDevice::KX_COMMAKEY);            
1430         KX_MACRO_addTypesToDict(d, QUOTEKEY, SCA_IInputDevice::KX_QUOTEKEY);            
1431         KX_MACRO_addTypesToDict(d, ACCENTGRAVEKEY, SCA_IInputDevice::KX_ACCENTGRAVEKEY);        
1432         KX_MACRO_addTypesToDict(d, MINUSKEY, SCA_IInputDevice::KX_MINUSKEY);            
1433         KX_MACRO_addTypesToDict(d, SLASHKEY, SCA_IInputDevice::KX_SLASHKEY);            
1434         KX_MACRO_addTypesToDict(d, BACKSLASHKEY, SCA_IInputDevice::KX_BACKSLASHKEY);
1435         KX_MACRO_addTypesToDict(d, EQUALKEY, SCA_IInputDevice::KX_EQUALKEY);            
1436         KX_MACRO_addTypesToDict(d, LEFTBRACKETKEY, SCA_IInputDevice::KX_LEFTBRACKETKEY);        
1437         KX_MACRO_addTypesToDict(d, RIGHTBRACKETKEY, SCA_IInputDevice::KX_RIGHTBRACKETKEY);      
1438                 
1439         KX_MACRO_addTypesToDict(d, LEFTARROWKEY, SCA_IInputDevice::KX_LEFTARROWKEY);
1440         KX_MACRO_addTypesToDict(d, DOWNARROWKEY, SCA_IInputDevice::KX_DOWNARROWKEY);
1441         KX_MACRO_addTypesToDict(d, RIGHTARROWKEY, SCA_IInputDevice::KX_RIGHTARROWKEY);  
1442         KX_MACRO_addTypesToDict(d, UPARROWKEY, SCA_IInputDevice::KX_UPARROWKEY);                
1443         
1444         KX_MACRO_addTypesToDict(d, PAD2 , SCA_IInputDevice::KX_PAD2);
1445         KX_MACRO_addTypesToDict(d, PAD4 , SCA_IInputDevice::KX_PAD4);
1446         KX_MACRO_addTypesToDict(d, PAD6 , SCA_IInputDevice::KX_PAD6);
1447         KX_MACRO_addTypesToDict(d, PAD8 , SCA_IInputDevice::KX_PAD8);
1448                 
1449         KX_MACRO_addTypesToDict(d, PAD1 , SCA_IInputDevice::KX_PAD1);
1450         KX_MACRO_addTypesToDict(d, PAD3 , SCA_IInputDevice::KX_PAD3);
1451         KX_MACRO_addTypesToDict(d, PAD5 , SCA_IInputDevice::KX_PAD5);
1452         KX_MACRO_addTypesToDict(d, PAD7 , SCA_IInputDevice::KX_PAD7);
1453         KX_MACRO_addTypesToDict(d, PAD9 , SCA_IInputDevice::KX_PAD9);
1454                 
1455         KX_MACRO_addTypesToDict(d, PADPERIOD, SCA_IInputDevice::KX_PADPERIOD);
1456         KX_MACRO_addTypesToDict(d, PADSLASHKEY, SCA_IInputDevice::KX_PADSLASHKEY);
1457         KX_MACRO_addTypesToDict(d, PADASTERKEY, SCA_IInputDevice::KX_PADASTERKEY);
1458                 
1459                 
1460         KX_MACRO_addTypesToDict(d, PAD0, SCA_IInputDevice::KX_PAD0);
1461         KX_MACRO_addTypesToDict(d, PADMINUS, SCA_IInputDevice::KX_PADMINUS);
1462         KX_MACRO_addTypesToDict(d, PADENTER, SCA_IInputDevice::KX_PADENTER);
1463         KX_MACRO_addTypesToDict(d, PADPLUSKEY, SCA_IInputDevice::KX_PADPLUSKEY);
1464                 
1465                 
1466         KX_MACRO_addTypesToDict(d, F1KEY , SCA_IInputDevice::KX_F1KEY);
1467         KX_MACRO_addTypesToDict(d, F2KEY , SCA_IInputDevice::KX_F2KEY);
1468         KX_MACRO_addTypesToDict(d, F3KEY , SCA_IInputDevice::KX_F3KEY);
1469         KX_MACRO_addTypesToDict(d, F4KEY , SCA_IInputDevice::KX_F4KEY);
1470         KX_MACRO_addTypesToDict(d, F5KEY , SCA_IInputDevice::KX_F5KEY);
1471         KX_MACRO_addTypesToDict(d, F6KEY , SCA_IInputDevice::KX_F6KEY);
1472         KX_MACRO_addTypesToDict(d, F7KEY , SCA_IInputDevice::KX_F7KEY);
1473         KX_MACRO_addTypesToDict(d, F8KEY , SCA_IInputDevice::KX_F8KEY);
1474         KX_MACRO_addTypesToDict(d, F9KEY , SCA_IInputDevice::KX_F9KEY);
1475         KX_MACRO_addTypesToDict(d, F10KEY, SCA_IInputDevice::KX_F10KEY);
1476         KX_MACRO_addTypesToDict(d, F11KEY, SCA_IInputDevice::KX_F11KEY);
1477         KX_MACRO_addTypesToDict(d, F12KEY, SCA_IInputDevice::KX_F12KEY);
1478                 
1479         KX_MACRO_addTypesToDict(d, PAUSEKEY, SCA_IInputDevice::KX_PAUSEKEY);
1480         KX_MACRO_addTypesToDict(d, INSERTKEY, SCA_IInputDevice::KX_INSERTKEY);
1481         KX_MACRO_addTypesToDict(d, HOMEKEY , SCA_IInputDevice::KX_HOMEKEY);
1482         KX_MACRO_addTypesToDict(d, PAGEUPKEY, SCA_IInputDevice::KX_PAGEUPKEY);
1483         KX_MACRO_addTypesToDict(d, PAGEDOWNKEY, SCA_IInputDevice::KX_PAGEDOWNKEY);
1484         KX_MACRO_addTypesToDict(d, ENDKEY, SCA_IInputDevice::KX_ENDKEY);
1485
1486
1487         // Check for errors
1488         if (PyErr_Occurred())
1489     {
1490                 Py_FatalError("can't initialize module GameKeys");
1491     }
1492
1493         return d;
1494 }
1495
1496 PyObject* initMathutils()
1497 {
1498         return Mathutils_Init("Mathutils"); // Use as a top level module in BGE
1499 }
1500
1501 void KX_SetActiveScene(class KX_Scene* scene)
1502 {
1503         gp_KetsjiScene = scene;
1504 }
1505
1506 class KX_Scene* KX_GetActiveScene()
1507 {
1508         return gp_KetsjiScene;
1509 }
1510
1511 class KX_KetsjiEngine* KX_GetActiveEngine()
1512 {
1513         return gp_KetsjiEngine;
1514 }
1515
1516 // utility function for loading and saving the globalDict
1517 int saveGamePythonConfig( char **marshal_buffer)
1518 {
1519         int marshal_length = 0;
1520         PyObject* gameLogic = PyImport_ImportModule("GameLogic");
1521         if (gameLogic) {
1522                 PyObject* pyGlobalDict = PyDict_GetItemString(PyModule_GetDict(gameLogic), "globalDict"); // Same as importing the module
1523                 if (pyGlobalDict) {
1524 #ifdef Py_MARSHAL_VERSION       
1525                         PyObject* pyGlobalDictMarshal = PyMarshal_WriteObjectToString(  pyGlobalDict, 2); // Py_MARSHAL_VERSION == 2 as of Py2.5
1526 #else
1527                         PyObject* pyGlobalDictMarshal = PyMarshal_WriteObjectToString(  pyGlobalDict ); 
1528 #endif
1529                         if (pyGlobalDictMarshal) {
1530                                 // for testing only
1531                                 // PyObject_Print(pyGlobalDictMarshal, stderr, 0);
1532
1533                                 marshal_length= PyString_Size(pyGlobalDictMarshal);
1534                                 *marshal_buffer = new char[marshal_length + 1];
1535                                 memcpy(*marshal_buffer, PyString_AsString(pyGlobalDictMarshal), marshal_length);
1536
1537                                 Py_DECREF(pyGlobalDictMarshal);
1538                         } else {
1539                                 printf("Error, GameLogic.globalDict could not be marshal'd\n");
1540                         }
1541                 } else {
1542                         printf("Error, GameLogic.globalDict was removed\n");
1543                 }
1544                 Py_DECREF(gameLogic);
1545         } else {
1546                 PyErr_Clear();
1547                 printf("Error, GameLogic failed to import GameLogic.globalDict will be lost\n");
1548         }
1549         return marshal_length;
1550 }
1551
1552 int loadGamePythonConfig(char *marshal_buffer, int marshal_length)
1553 {
1554         /* Restore the dict */
1555         if (marshal_buffer) {
1556                 PyObject* gameLogic = PyImport_ImportModule("GameLogic");
1557
1558                 if (gameLogic) {
1559                         PyObject* pyGlobalDict = PyMarshal_ReadObjectFromString(marshal_buffer, marshal_length);
1560                         if (pyGlobalDict) {
1561                                 PyObject* pyGlobalDict_orig = PyDict_GetItemString(PyModule_GetDict(gameLogic), "globalDict"); // Same as importing the module.
1562                                 if (pyGlobalDict_orig) {
1563                                         PyDict_Clear(pyGlobalDict_orig);
1564                                         PyDict_Update(pyGlobalDict_orig, pyGlobalDict);
1565                                 } else {
1566                                         /* this should not happen, but cant find the original globalDict, just assign it then */
1567                                         PyDict_SetItemString(PyModule_GetDict(gameLogic), "globalDict", pyGlobalDict); // Same as importing the module.
1568                                 }
1569                                 Py_DECREF(gameLogic);
1570                                 Py_DECREF(pyGlobalDict);
1571                                 return 1;
1572                         } else {
1573                                 Py_DECREF(gameLogic);
1574                                 PyErr_Clear();
1575                                 printf("Error could not marshall string\n");
1576                         }
1577                 } else {
1578                         PyErr_Clear();
1579                         printf("Error, GameLogic failed to import GameLogic.globalDict will be lost\n");
1580                 }       
1581         }
1582         return 0;
1583 }
1584
1585 void pathGamePythonConfig( char *path )
1586 {
1587         int len = strlen(gp_GamePythonPath);
1588         
1589         BLI_strncpy(path, gp_GamePythonPath, sizeof(gp_GamePythonPath));
1590
1591         /* replace extension */
1592         if (BLI_testextensie(path, ".blend")) {
1593                 strcpy(path+(len-6), ".bgeconf");
1594         } else {
1595                 strcpy(path+len, ".bgeconf");
1596         }
1597 }
1598
1599 void setGamePythonPath(char *path)
1600 {
1601         BLI_strncpy(gp_GamePythonPath, path, sizeof(gp_GamePythonPath));
1602 }
1603