BGE Py API
[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
51 #include "SCA_IInputDevice.h"
52 #include "SCA_PropertySensor.h"
53 #include "SCA_RandomActuator.h"
54 #include "KX_ConstraintActuator.h"
55 #include "KX_IpoActuator.h"
56 #include "KX_SoundActuator.h"
57 #include "BL_ActionActuator.h"
58 #include "RAS_IRasterizer.h"
59 #include "RAS_ICanvas.h"
60 #include "RAS_BucketManager.h"
61 #include "MT_Vector3.h"
62 #include "MT_Point3.h"
63 #include "ListValue.h"
64 #include "KX_Scene.h"
65 #include "SND_DeviceManager.h"
66
67 #include "BL_Shader.h"
68
69 #include "KX_PyMath.h"
70
71 extern "C" {
72         #include "Mathutils.h" // Blender.Mathutils module copied here so the blenderlayer can use.
73 }
74
75 #include "PHY_IPhysicsEnvironment.h"
76 // FIXME: Enable for access to blender python modules.  This is disabled because
77 // python has dependencies on a lot of other modules and is a pain to link.
78 //#define USE_BLENDER_PYTHON
79 #ifdef USE_BLENDER_PYTHON
80 //#include "BPY_extern.h"
81 #endif 
82
83 #include "BKE_utildefines.h"
84 #include "BKE_global.h"
85 #include "BLI_blenlib.h"
86 #include "GPU_material.h"
87
88 static void setSandbox(TPythonSecurityLevel level);
89
90
91 // 'local' copy of canvas ptr, for window height/width python scripts
92 static RAS_ICanvas* gp_Canvas = NULL;
93 static KX_Scene*        gp_KetsjiScene = NULL;
94 static KX_KetsjiEngine* gp_KetsjiEngine = NULL;
95 static RAS_IRasterizer* gp_Rasterizer = NULL;
96
97 void    KX_RasterizerDrawDebugLine(const MT_Vector3& from,const MT_Vector3& to,const MT_Vector3& color)
98 {
99         if (gp_Rasterizer)
100                 gp_Rasterizer->DrawDebugLine(from,to,color);
101 }
102
103 /* Macro for building the keyboard translation */
104 //#define KX_MACRO_addToDict(dict, name) PyDict_SetItemString(dict, #name, PyInt_FromLong(SCA_IInputDevice::KX_##name))
105 #define KX_MACRO_addToDict(dict, name) PyDict_SetItemString(dict, #name, PyInt_FromLong(name))
106 /* For the defines for types from logic bricks, we do stuff explicitly... */
107 #define KX_MACRO_addTypesToDict(dict, name, name2) PyDict_SetItemString(dict, #name, PyInt_FromLong(name2))
108
109
110 // temporarily python stuff, will be put in another place later !
111 #include "KX_Python.h"
112 #include "SCA_PythonController.h"
113 // List of methods defined in the module
114
115 static PyObject* ErrorObject;
116 STR_String gPyGetRandomFloat_doc="getRandomFloat returns a random floating point value in the range [0..1)";
117
118 static PyObject* gPyGetRandomFloat(PyObject*)
119 {
120         return PyFloat_FromDouble(MT_random());
121 }
122
123 static PyObject* gPySetGravity(PyObject*, PyObject* args)
124 {
125         MT_Vector3 vec = MT_Vector3(0., 0., 0.);
126         if (!PyVecArgTo(args, vec))
127                 return NULL;
128
129         if (gp_KetsjiScene)
130                 gp_KetsjiScene->SetGravity(vec);
131         
132         Py_RETURN_NONE;
133 }
134
135 static char gPyExpandPath_doc[] =
136 "(path) - Converts a blender internal path into a proper file system path.\n\
137 path - the string path to convert.\n\n\
138 Use / as directory separator in path\n\
139 You can use '//' at the start of the string to define a relative path;\n\
140 Blender replaces that string by the directory of the startup .blend or runtime\n\
141 file to make a full path name (doesn't change during the game, even if you load\n\
142 other .blend).\n\
143 The function also converts the directory separator to the local file system format.";
144
145 static PyObject* gPyExpandPath(PyObject*, PyObject* args)
146 {
147         char expanded[FILE_MAXDIR + FILE_MAXFILE];
148         char* filename;
149         
150         if (!PyArg_ParseTuple(args,"s",&filename))
151                 return NULL;
152
153         BLI_strncpy(expanded, filename, FILE_MAXDIR + FILE_MAXFILE);
154         BLI_convertstringcode(expanded, G.sce);
155         return PyString_FromString(expanded);
156 }
157
158
159 static bool usedsp = false;
160
161 // this gets a pointer to an array filled with floats
162 static PyObject* gPyGetSpectrum(PyObject*)
163 {
164         SND_IAudioDevice* audiodevice = SND_DeviceManager::Instance();
165
166         PyObject* resultlist = PyList_New(512);
167
168         if (audiodevice)
169         {
170                 if (!usedsp)
171                 {
172                         audiodevice->StartUsingDSP();
173                         usedsp = true;
174                 }
175                         
176                 float* spectrum = audiodevice->GetSpectrum();
177
178                 for (int index = 0; index < 512; index++)
179                 {
180                         PyList_SetItem(resultlist, index, PyFloat_FromDouble(spectrum[index]));
181                 }
182         }
183         else {
184                 for (int index = 0; index < 512; index++)
185                 {
186                         PyList_SetItem(resultlist, index, PyFloat_FromDouble(0.0));
187                 }
188         }
189
190         return resultlist;
191 }
192
193
194
195 static PyObject* gPyStartDSP(PyObject*, PyObject* args)
196 {
197         SND_IAudioDevice* audiodevice = SND_DeviceManager::Instance();
198
199         if (!audiodevice) {
200                 PyErr_SetString(PyExc_RuntimeError, "no audio device available");
201                 return NULL;
202         }
203         
204         if (!usedsp) {
205                 audiodevice->StartUsingDSP();
206                 usedsp = true;
207         }
208         
209         Py_RETURN_NONE;
210 }
211
212
213
214 static PyObject* gPyStopDSP(PyObject*, PyObject* args)
215 {
216         SND_IAudioDevice* audiodevice = SND_DeviceManager::Instance();
217
218         if (!audiodevice) {
219                 PyErr_SetString(PyExc_RuntimeError, "no audio device available");
220                 return NULL;
221         }
222         
223         if (usedsp) {
224                 audiodevice->StopUsingDSP();
225                 usedsp = true;
226         }
227         
228         Py_RETURN_NONE;
229 }
230
231 static PyObject* gPySetLogicTicRate(PyObject*, PyObject* args)
232 {
233         float ticrate;
234         if (!PyArg_ParseTuple(args, "f", &ticrate))
235                 return NULL;
236         
237         KX_KetsjiEngine::SetTicRate(ticrate);
238         Py_RETURN_NONE;
239 }
240
241 static PyObject* gPyGetLogicTicRate(PyObject*)
242 {
243         return PyFloat_FromDouble(KX_KetsjiEngine::GetTicRate());
244 }
245
246 static PyObject* gPySetPhysicsTicRate(PyObject*, PyObject* args)
247 {
248         float ticrate;
249         if (!PyArg_ParseTuple(args, "f", &ticrate))
250                 return NULL;
251         
252         PHY_GetActiveEnvironment()->setFixedTimeStep(true,ticrate);
253         Py_RETURN_NONE;
254 }
255
256 static PyObject* gPySetPhysicsDebug(PyObject*, PyObject* args)
257 {
258         int debugMode;
259         if (!PyArg_ParseTuple(args, "i", &debugMode))
260                 return NULL;
261         
262         PHY_GetActiveEnvironment()->setDebugMode(debugMode);
263         Py_RETURN_NONE;
264 }
265
266
267
268 static PyObject* gPyGetPhysicsTicRate(PyObject*)
269 {
270         return PyFloat_FromDouble(PHY_GetActiveEnvironment()->getFixedTimeStep());
271 }
272
273 static PyObject* gPyGetAverageFrameRate(PyObject*)
274 {
275         return PyFloat_FromDouble(KX_KetsjiEngine::GetAverageFrameRate());
276 }
277
278 static PyObject* gPyGetBlendFileList(PyObject*, PyObject* args)
279 {
280         char cpath[sizeof(G.sce)];
281         char *searchpath = NULL;
282         PyObject* list, *value;
283         
284     DIR *dp;
285     struct dirent *dirp;
286         
287         if (!PyArg_ParseTuple(args, "|s", &searchpath))
288                 return NULL;
289         
290         list = PyList_New(0);
291         
292         if (searchpath) {
293                 BLI_strncpy(cpath, searchpath, FILE_MAXDIR + FILE_MAXFILE);
294                 BLI_convertstringcode(cpath, G.sce);
295         } else {
296                 /* Get the dir only */
297                 BLI_split_dirfile_basic(G.sce, cpath, NULL);
298         }
299         
300     if((dp  = opendir(cpath)) == NULL) {
301                 /* todo, show the errno, this shouldnt happen anyway if the blendfile is readable */
302                 fprintf(stderr, "Could not read directoty () failed, code %d (%s)\n", cpath, errno, strerror(errno));
303                 return list;
304     }
305         
306     while ((dirp = readdir(dp)) != NULL) {
307                 if (BLI_testextensie(dirp->d_name, ".blend")) {
308                         value = PyString_FromString(dirp->d_name);
309                         PyList_Append(list, value);
310                         Py_DECREF(value);
311                 }
312     }
313         
314     closedir(dp);
315     return list;
316 }
317
318 static STR_String gPyGetCurrentScene_doc =  
319 "getCurrentScene()\n"
320 "Gets a reference to the current scene.\n";
321 static PyObject* gPyGetCurrentScene(PyObject* self)
322 {
323         Py_INCREF(gp_KetsjiScene);
324         return (PyObject*) gp_KetsjiScene;
325 }
326
327 static PyObject *pyPrintExt(PyObject *,PyObject *,PyObject *)
328 {
329 #define pprint(x) std::cout << x << std::endl;
330         bool count=0;
331         bool support=0;
332         pprint("Supported Extensions...");
333         pprint(" GL_ARB_shader_objects supported?       "<< (GLEW_ARB_shader_objects?"yes.":"no."));
334         count = 1;
335
336         support= GLEW_ARB_vertex_shader;
337         pprint(" GL_ARB_vertex_shader supported?        "<< (support?"yes.":"no."));
338         count = 1;
339         if(support){
340                 pprint(" ----------Details----------");
341                 int max=0;
342                 glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB, (GLint*)&max);
343                 pprint("  Max uniform components." << max);
344
345                 glGetIntegerv(GL_MAX_VARYING_FLOATS_ARB, (GLint*)&max);
346                 pprint("  Max varying floats." << max);
347
348                 glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB, (GLint*)&max);
349                 pprint("  Max vertex texture units." << max);
350         
351                 glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB, (GLint*)&max);
352                 pprint("  Max combined texture units." << max);
353                 pprint("");
354         }
355
356         support=GLEW_ARB_fragment_shader;
357         pprint(" GL_ARB_fragment_shader supported?      "<< (support?"yes.":"no."));
358         count = 1;
359         if(support){
360                 pprint(" ----------Details----------");
361                 int max=0;
362                 glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB, (GLint*)&max);
363                 pprint("  Max uniform components." << max);
364                 pprint("");
365         }
366
367         support = GLEW_ARB_texture_cube_map;
368         pprint(" GL_ARB_texture_cube_map supported?     "<< (support?"yes.":"no."));
369         count = 1;
370         if(support){
371                 pprint(" ----------Details----------");
372                 int size=0;
373                 glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB, (GLint*)&size);
374                 pprint("  Max cubemap size." << size);
375                 pprint("");
376         }
377
378         support = GLEW_ARB_multitexture;
379         count = 1;
380         pprint(" GL_ARB_multitexture supported?         "<< (support?"yes.":"no."));
381         if(support){
382                 pprint(" ----------Details----------");
383                 int units=0;
384                 glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, (GLint*)&units);
385                 pprint("  Max texture units available.  " << units);
386                 pprint("");
387         }
388
389         pprint(" GL_ARB_texture_env_combine supported?  "<< (GLEW_ARB_texture_env_combine?"yes.":"no."));
390         count = 1;
391
392         if(!count)
393                 pprint("No extenstions are used in this build");
394
395         Py_RETURN_NONE;
396 }
397
398
399 static struct PyMethodDef game_methods[] = {
400         {"expandPath", (PyCFunction)gPyExpandPath, METH_VARARGS, gPyExpandPath_doc},
401         {"getCurrentController",
402         (PyCFunction) SCA_PythonController::sPyGetCurrentController,
403         METH_NOARGS, SCA_PythonController::sPyGetCurrentController__doc__},
404         {"getCurrentScene", (PyCFunction) gPyGetCurrentScene,
405         METH_NOARGS, gPyGetCurrentScene_doc.Ptr()},
406         {"addActiveActuator",(PyCFunction) SCA_PythonController::sPyAddActiveActuator,
407         METH_VARARGS, SCA_PythonController::sPyAddActiveActuator__doc__},
408         {"getRandomFloat",(PyCFunction) gPyGetRandomFloat,
409         METH_NOARGS,gPyGetRandomFloat_doc.Ptr()},
410         {"setGravity",(PyCFunction) gPySetGravity, METH_VARARGS,"set Gravitation"},
411         {"getSpectrum",(PyCFunction) gPyGetSpectrum, METH_NOARGS,"get audio spectrum"},
412         {"stopDSP",(PyCFunction) gPyStopDSP, METH_VARARGS,"stop using the audio dsp (for performance reasons)"},
413         {"getLogicTicRate", (PyCFunction) gPyGetLogicTicRate, METH_NOARGS, "Gets the logic tic rate"},
414         {"setLogicTicRate", (PyCFunction) gPySetLogicTicRate, METH_VARARGS, "Sets the logic tic rate"},
415         {"getPhysicsTicRate", (PyCFunction) gPyGetPhysicsTicRate, METH_NOARGS, "Gets the physics tic rate"},
416         {"setPhysicsTicRate", (PyCFunction) gPySetPhysicsTicRate, METH_VARARGS, "Sets the physics tic rate"},
417         {"getAverageFrameRate", (PyCFunction) gPyGetAverageFrameRate, METH_NOARGS, "Gets the estimated average frame rate"},
418         {"getBlendFileList", (PyCFunction)gPyGetBlendFileList, METH_VARARGS, "Gets a list of blend files in the same directory as the current blend file"},
419         {"PrintGLInfo", (PyCFunction)pyPrintExt, METH_NOARGS, "Prints GL Extension Info"},
420         {NULL, (PyCFunction) NULL, 0, NULL }
421 };
422
423
424 static PyObject* gPyGetWindowHeight(PyObject*, PyObject* args)
425 {
426         return PyInt_FromLong((gp_Canvas ? gp_Canvas->GetHeight() : 0));
427 }
428
429
430
431 static PyObject* gPyGetWindowWidth(PyObject*, PyObject* args)
432 {
433         return PyInt_FromLong((gp_Canvas ? gp_Canvas->GetWidth() : 0));
434 }
435
436
437
438 // temporarility visibility thing, will be moved to rasterizer/renderer later
439 bool gUseVisibilityTemp = false;
440
441 static PyObject* gPyEnableVisibility(PyObject*, PyObject* args)
442 {
443         int visible;
444         if (!PyArg_ParseTuple(args,"i",&visible))
445                 return NULL;
446         
447         gUseVisibilityTemp = (visible != 0);
448         Py_RETURN_NONE;
449 }
450
451
452
453 static PyObject* gPyShowMouse(PyObject*, PyObject* args)
454 {
455         int visible;
456         if (!PyArg_ParseTuple(args,"i",&visible))
457                 return NULL;
458         
459         if (visible)
460         {
461                 if (gp_Canvas)
462                         gp_Canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
463         } else
464         {
465                 if (gp_Canvas)
466                         gp_Canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE);
467         }
468         
469         Py_RETURN_NONE;
470 }
471
472
473
474 static PyObject* gPySetMousePosition(PyObject*, PyObject* args)
475 {
476         int x,y;
477         if (!PyArg_ParseTuple(args,"ii",&x,&y))
478                 return NULL;
479         
480         if (gp_Canvas)
481                 gp_Canvas->SetMousePosition(x,y);
482         
483         Py_RETURN_NONE;
484 }
485
486 static PyObject* gPySetEyeSeparation(PyObject*, PyObject* args)
487 {
488         float sep;
489         if (!PyArg_ParseTuple(args, "f", &sep))
490                 return NULL;
491
492         if (!gp_Rasterizer) {
493                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
494                 return NULL;
495         }
496         
497         gp_Rasterizer->SetEyeSeparation(sep);
498         
499         Py_RETURN_NONE;
500 }
501
502 static PyObject* gPyGetEyeSeparation(PyObject*, PyObject*, PyObject*)
503 {
504         if (!gp_Rasterizer) {
505                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
506                 return NULL;
507         }
508         
509         return PyFloat_FromDouble(gp_Rasterizer->GetEyeSeparation());
510 }
511
512 static PyObject* gPySetFocalLength(PyObject*, PyObject* args)
513 {
514         float focus;
515         if (!PyArg_ParseTuple(args, "f", &focus))
516                 return NULL;
517         
518         if (!gp_Rasterizer) {
519                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
520                 return NULL;
521         }
522
523         gp_Rasterizer->SetFocalLength(focus);
524         
525         Py_RETURN_NONE;
526 }
527
528 static PyObject* gPyGetFocalLength(PyObject*, PyObject*, PyObject*)
529 {
530         if (!gp_Rasterizer) {
531                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
532                 return NULL;
533         }
534         
535         return PyFloat_FromDouble(gp_Rasterizer->GetFocalLength());
536         
537         Py_RETURN_NONE;
538 }
539
540 static PyObject* gPySetBackgroundColor(PyObject*, PyObject* args)
541 {
542         
543         MT_Vector4 vec = MT_Vector4(0., 0., 0.3, 0.);
544         if (!PyVecArgTo(args, vec))
545                 return NULL;
546         
547         if (gp_Canvas)
548         {
549                 gp_Rasterizer->SetBackColor(vec[0], vec[1], vec[2], vec[3]);
550         }
551         Py_RETURN_NONE;
552 }
553
554
555
556 static PyObject* gPySetMistColor(PyObject*, PyObject* args)
557 {
558         
559         MT_Vector3 vec = MT_Vector3(0., 0., 0.);
560         if (!PyVecArgTo(args, vec))
561                 return NULL;
562         
563         if (!gp_Rasterizer) {
564                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
565                 return NULL;
566         }       
567         gp_Rasterizer->SetFogColor(vec[0], vec[1], vec[2]);
568         
569         Py_RETURN_NONE;
570 }
571
572
573
574 static PyObject* gPySetMistStart(PyObject*, PyObject* args)
575 {
576
577         float miststart;
578         if (!PyArg_ParseTuple(args,"f",&miststart))
579                 return NULL;
580         
581         if (!gp_Rasterizer) {
582                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
583                 return NULL;
584         }
585         
586         gp_Rasterizer->SetFogStart(miststart);
587         
588         Py_RETURN_NONE;
589 }
590
591
592
593 static PyObject* gPySetMistEnd(PyObject*, PyObject* args)
594 {
595
596         float mistend;
597         if (!PyArg_ParseTuple(args,"f",&mistend))
598                 return NULL;
599         
600         if (!gp_Rasterizer) {
601                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
602                 return NULL;
603         }
604         
605         gp_Rasterizer->SetFogEnd(mistend);
606         
607         Py_RETURN_NONE;
608 }
609
610
611 static PyObject* gPySetAmbientColor(PyObject*, PyObject* args)
612 {
613         
614         MT_Vector3 vec = MT_Vector3(0., 0., 0.);
615         if (!PyVecArgTo(args, vec))
616                 return NULL;
617         
618         if (!gp_Rasterizer) {
619                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
620                 return NULL;
621         }       
622         gp_Rasterizer->SetAmbientColor(vec[0], vec[1], vec[2]);
623         
624         Py_RETURN_NONE;
625 }
626
627
628
629
630 static PyObject* gPyMakeScreenshot(PyObject*, PyObject* args)
631 {
632         char* filename;
633         if (!PyArg_ParseTuple(args,"s",&filename))
634                 return NULL;
635         
636         if (gp_Canvas)
637         {
638                 gp_Canvas->MakeScreenShot(filename);
639         }
640         
641         Py_RETURN_NONE;
642 }
643
644 static PyObject* gPyEnableMotionBlur(PyObject*, PyObject* args)
645 {
646         float motionblurvalue;
647         if (!PyArg_ParseTuple(args,"f",&motionblurvalue))
648                 return NULL;
649         
650         if (!gp_Rasterizer) {
651                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
652                 return NULL;
653         }
654         
655         gp_Rasterizer->EnableMotionBlur(motionblurvalue);
656         
657         Py_RETURN_NONE;
658 }
659
660 static PyObject* gPyDisableMotionBlur(PyObject*, PyObject* args)
661 {
662         if (!gp_Rasterizer) {
663                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
664                 return NULL;
665         }
666         
667         gp_Rasterizer->DisableMotionBlur();
668         
669         Py_RETURN_NONE;
670 }
671
672 int getGLSLSettingFlag(char *setting)
673 {
674         if(strcmp(setting, "lights") == 0)
675                 return G_FILE_GLSL_NO_LIGHTS;
676         else if(strcmp(setting, "shaders") == 0)
677                 return G_FILE_GLSL_NO_SHADERS;
678         else if(strcmp(setting, "shadows") == 0)
679                 return G_FILE_GLSL_NO_SHADOWS;
680         else if(strcmp(setting, "ramps") == 0)
681                 return G_FILE_GLSL_NO_RAMPS;
682         else if(strcmp(setting, "nodes") == 0)
683                 return G_FILE_GLSL_NO_NODES;
684         else if(strcmp(setting, "extra_textures") == 0)
685                 return G_FILE_GLSL_NO_EXTRA_TEX;
686         else
687                 return -1;
688 }
689
690 static PyObject* gPySetGLSLMaterialSetting(PyObject*,
691                                                                                         PyObject* args,
692                                                                                         PyObject*)
693 {
694         char *setting;
695         int enable, flag;
696
697         if (PyArg_ParseTuple(args,"si",&setting,&enable))
698                 return NULL;
699         
700         flag = getGLSLSettingFlag(setting);
701         
702         if  (flag==-1) {
703                 PyErr_SetString(PyExc_ValueError, "glsl setting is not known");
704                 return NULL;
705         }
706         
707         if (enable)
708                 G.fileflags &= ~flag;
709         else
710                 G.fileflags |= flag;
711
712         /* display lists and GLSL materials need to be remade */
713         if(gp_KetsjiEngine) {
714                 KX_SceneList *scenes = gp_KetsjiEngine->CurrentScenes();
715                 KX_SceneList::iterator it;
716
717                 for(it=scenes->begin(); it!=scenes->end(); it++)
718                         if((*it)->GetBucketManager())
719                                 (*it)->GetBucketManager()->ReleaseDisplayLists();
720         }
721
722         GPU_materials_free();
723
724         Py_RETURN_NONE;
725 }
726
727 static PyObject* gPyGetGLSLMaterialSetting(PyObject*, 
728                                                                          PyObject* args, 
729                                                                          PyObject*)
730 {
731         char *setting;
732         int enabled = 0, flag;
733
734         if (!PyArg_ParseTuple(args,"s",&setting))
735                 return NULL;
736         
737         flag = getGLSLSettingFlag(setting);
738         
739         if  (flag==-1) {
740                 PyErr_SetString(PyExc_ValueError, "glsl setting is not known");
741                 return NULL;
742         }
743
744         enabled = ((G.fileflags & flag) != 0);
745         return PyInt_FromLong(enabled);
746 }
747
748 STR_String      gPyGetWindowHeight__doc__="getWindowHeight doc";
749 STR_String      gPyGetWindowWidth__doc__="getWindowWidth doc";
750 STR_String      gPyEnableVisibility__doc__="enableVisibility doc";
751 STR_String      gPyMakeScreenshot__doc__="make Screenshot doc";
752 STR_String      gPyShowMouse__doc__="showMouse(bool visible)";
753 STR_String      gPySetMousePosition__doc__="setMousePosition(int x,int y)";
754
755 static struct PyMethodDef rasterizer_methods[] = {
756   {"getWindowWidth",(PyCFunction) gPyGetWindowWidth,
757    METH_VARARGS, gPyGetWindowWidth__doc__.Ptr()},
758    {"getWindowHeight",(PyCFunction) gPyGetWindowHeight,
759    METH_VARARGS, gPyGetWindowHeight__doc__.Ptr()},
760   {"makeScreenshot",(PyCFunction)gPyMakeScreenshot,
761         METH_VARARGS, gPyMakeScreenshot__doc__.Ptr()},
762    {"enableVisibility",(PyCFunction) gPyEnableVisibility,
763    METH_VARARGS, gPyEnableVisibility__doc__.Ptr()},
764         {"showMouse",(PyCFunction) gPyShowMouse,
765    METH_VARARGS, gPyShowMouse__doc__.Ptr()},
766    {"setMousePosition",(PyCFunction) gPySetMousePosition,
767    METH_VARARGS, gPySetMousePosition__doc__.Ptr()},
768   {"setBackgroundColor",(PyCFunction)gPySetBackgroundColor,METH_VARARGS,"set Background Color (rgb)"},
769         {"setAmbientColor",(PyCFunction)gPySetAmbientColor,METH_VARARGS,"set Ambient Color (rgb)"},
770  {"setMistColor",(PyCFunction)gPySetMistColor,METH_VARARGS,"set Mist Color (rgb)"},
771   {"setMistStart",(PyCFunction)gPySetMistStart,METH_VARARGS,"set Mist Start(rgb)"},
772   {"setMistEnd",(PyCFunction)gPySetMistEnd,METH_VARARGS,"set Mist End(rgb)"},
773   {"enableMotionBlur",(PyCFunction)gPyEnableMotionBlur,METH_VARARGS,"enable motion blur"},
774   {"disableMotionBlur",(PyCFunction)gPyDisableMotionBlur,METH_VARARGS,"disable motion blur"},
775
776   
777   {"setEyeSeparation", (PyCFunction) gPySetEyeSeparation, METH_VARARGS, "set the eye separation for stereo mode"},
778   {"getEyeSeparation", (PyCFunction) gPyGetEyeSeparation, METH_VARARGS, "get the eye separation for stereo mode"},
779   {"setFocalLength", (PyCFunction) gPySetFocalLength, METH_VARARGS, "set the focal length for stereo mode"},
780   {"getFocalLength", (PyCFunction) gPyGetFocalLength, METH_VARARGS, "get the focal length for stereo mode"},
781   {"setGLSLMaterialSetting",(PyCFunction) gPySetGLSLMaterialSetting,
782    METH_VARARGS, "set the state of a GLSL material setting"},
783   {"getGLSLMaterialSetting",(PyCFunction) gPyGetGLSLMaterialSetting,
784    METH_VARARGS, "get the state of a GLSL material setting"},
785   { NULL, (PyCFunction) NULL, 0, NULL }
786 };
787
788 // Initialization function for the module (*must* be called initGameLogic)
789
790 static char GameLogic_module_documentation[] =
791 "This is the Python API for the game engine of GameLogic"
792 ;
793
794 static char Rasterizer_module_documentation[] =
795 "This is the Python API for the game engine of Rasterizer"
796 ;
797
798
799
800 PyObject* initGameLogic(KX_KetsjiEngine *engine, KX_Scene* scene) // quick hack to get gravity hook
801 {
802         PyObject* m;
803         PyObject* d;
804
805         gp_KetsjiEngine = engine;
806         gp_KetsjiScene = scene;
807
808         gUseVisibilityTemp=false;
809
810         // Create the module and add the functions
811         m = Py_InitModule4("GameLogic", game_methods,
812                                            GameLogic_module_documentation,
813                                            (PyObject*)NULL,PYTHON_API_VERSION);
814
815         // Add some symbolic constants to the module
816         d = PyModule_GetDict(m);
817         
818         // can be overwritten later for gameEngine instances that can load new blend files and re-initialize this module
819         // for now its safe to make sure it exists for other areas such as the web plugin
820         PyDict_SetItemString(d, "globalDict", PyDict_New());
821
822         ErrorObject = PyString_FromString("GameLogic.error");
823         PyDict_SetItemString(d, "error", ErrorObject);
824         
825         // XXXX Add constants here
826         /* To use logic bricks, we need some sort of constants. Here, we associate */
827         /* constants and sumbolic names. Add them to dictionary d.                 */
828
829         /* 1. true and false: needed for everyone                                  */
830         KX_MACRO_addTypesToDict(d, KX_TRUE,  SCA_ILogicBrick::KX_TRUE);
831         KX_MACRO_addTypesToDict(d, KX_FALSE, SCA_ILogicBrick::KX_FALSE);
832
833         /* 2. Property sensor                                                      */
834         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_EQUAL,      SCA_PropertySensor::KX_PROPSENSOR_EQUAL);
835         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_NOTEQUAL,   SCA_PropertySensor::KX_PROPSENSOR_NOTEQUAL);
836         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_INTERVAL,   SCA_PropertySensor::KX_PROPSENSOR_INTERVAL);
837         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_CHANGED,    SCA_PropertySensor::KX_PROPSENSOR_CHANGED);
838         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_EXPRESSION, SCA_PropertySensor::KX_PROPSENSOR_EXPRESSION);
839
840         /* 3. Constraint actuator                                                  */
841         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCX);
842         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCY);
843         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCZ);
844         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTX);
845         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTY);
846         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTZ);
847         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPX);
848         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPY);
849         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPY);
850         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNX);
851         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNY);
852         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNY);
853         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIX);
854         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIY);
855         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIZ);
856
857         /* 4. Ipo actuator, simple part                                            */
858         KX_MACRO_addTypesToDict(d, KX_IPOACT_PLAY,     KX_IpoActuator::KX_ACT_IPO_PLAY);
859         KX_MACRO_addTypesToDict(d, KX_IPOACT_PINGPONG, KX_IpoActuator::KX_ACT_IPO_PINGPONG);
860         KX_MACRO_addTypesToDict(d, KX_IPOACT_FLIPPER,  KX_IpoActuator::KX_ACT_IPO_FLIPPER);
861         KX_MACRO_addTypesToDict(d, KX_IPOACT_LOOPSTOP, KX_IpoActuator::KX_ACT_IPO_LOOPSTOP);
862         KX_MACRO_addTypesToDict(d, KX_IPOACT_LOOPEND,  KX_IpoActuator::KX_ACT_IPO_LOOPEND);
863
864         /* 5. Random distribution types                                            */
865         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_CONST,      SCA_RandomActuator::KX_RANDOMACT_BOOL_CONST);
866         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_UNIFORM,    SCA_RandomActuator::KX_RANDOMACT_BOOL_UNIFORM);
867         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_BERNOUILLI, SCA_RandomActuator::KX_RANDOMACT_BOOL_BERNOUILLI);
868         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_CONST,       SCA_RandomActuator::KX_RANDOMACT_INT_CONST);
869         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_UNIFORM,     SCA_RandomActuator::KX_RANDOMACT_INT_UNIFORM);
870         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_POISSON,     SCA_RandomActuator::KX_RANDOMACT_INT_POISSON);
871         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_CONST,     SCA_RandomActuator::KX_RANDOMACT_FLOAT_CONST);
872         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_UNIFORM,   SCA_RandomActuator::KX_RANDOMACT_FLOAT_UNIFORM);
873         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_NORMAL,    SCA_RandomActuator::KX_RANDOMACT_FLOAT_NORMAL);
874         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL, SCA_RandomActuator::KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL);
875
876         /* 6. Sound actuator                                                      */
877         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYSTOP,              KX_SoundActuator::KX_SOUNDACT_PLAYSTOP);
878         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYEND,               KX_SoundActuator::KX_SOUNDACT_PLAYEND);
879         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPSTOP,              KX_SoundActuator::KX_SOUNDACT_LOOPSTOP);
880         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPEND,               KX_SoundActuator::KX_SOUNDACT_LOOPEND);
881         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL,     KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL);
882         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP,     KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP);
883
884         /* 7. Action actuator                                                                                                      */
885         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_PLAY,     BL_ActionActuator::KX_ACT_ACTION_PLAY);
886         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_FLIPPER,     BL_ActionActuator::KX_ACT_ACTION_FLIPPER);
887         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_LOOPSTOP,     BL_ActionActuator::KX_ACT_ACTION_LOOPSTOP);
888         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_LOOPEND,     BL_ActionActuator::KX_ACT_ACTION_LOOPEND);
889         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_PROPERTY,     BL_ActionActuator::KX_ACT_ACTION_PROPERTY);
890         
891         /*8. GL_BlendFunc */
892         KX_MACRO_addTypesToDict(d, BL_ZERO, GL_ZERO);
893         KX_MACRO_addTypesToDict(d, BL_ONE, GL_ONE);
894         KX_MACRO_addTypesToDict(d, BL_SRC_COLOR, GL_SRC_COLOR);
895         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR);
896         KX_MACRO_addTypesToDict(d, BL_DST_COLOR, GL_DST_COLOR);
897         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_DST_COLOR);
898         KX_MACRO_addTypesToDict(d, BL_SRC_ALPHA, GL_SRC_ALPHA);
899         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
900         KX_MACRO_addTypesToDict(d, BL_DST_ALPHA, GL_DST_ALPHA);
901         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA);
902         KX_MACRO_addTypesToDict(d, BL_SRC_ALPHA_SATURATE, GL_SRC_ALPHA_SATURATE);
903
904
905         /* 9. UniformTypes */
906         KX_MACRO_addTypesToDict(d, SHD_TANGENT, BL_Shader::SHD_TANGENT);
907         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX, BL_Shader::MODELVIEWMATRIX);
908         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_TRANSPOSE, BL_Shader::MODELVIEWMATRIX_TRANSPOSE);
909         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_INVERSE, BL_Shader::MODELVIEWMATRIX_INVERSE);
910         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_INVERSETRANSPOSE, BL_Shader::MODELVIEWMATRIX_INVERSETRANSPOSE);
911         KX_MACRO_addTypesToDict(d, MODELMATRIX, BL_Shader::MODELMATRIX);
912         KX_MACRO_addTypesToDict(d, MODELMATRIX_TRANSPOSE, BL_Shader::MODELMATRIX_TRANSPOSE);
913         KX_MACRO_addTypesToDict(d, MODELMATRIX_INVERSE, BL_Shader::MODELMATRIX_INVERSE);
914         KX_MACRO_addTypesToDict(d, MODELMATRIX_INVERSETRANSPOSE, BL_Shader::MODELMATRIX_INVERSETRANSPOSE);
915         KX_MACRO_addTypesToDict(d, VIEWMATRIX, BL_Shader::VIEWMATRIX);
916         KX_MACRO_addTypesToDict(d, VIEWMATRIX_TRANSPOSE, BL_Shader::VIEWMATRIX_TRANSPOSE);
917         KX_MACRO_addTypesToDict(d, VIEWMATRIX_INVERSE, BL_Shader::VIEWMATRIX_INVERSE);
918         KX_MACRO_addTypesToDict(d, VIEWMATRIX_INVERSETRANSPOSE, BL_Shader::VIEWMATRIX_INVERSETRANSPOSE);
919         KX_MACRO_addTypesToDict(d, CAM_POS, BL_Shader::CAM_POS);
920         KX_MACRO_addTypesToDict(d, CONSTANT_TIMER, BL_Shader::CONSTANT_TIMER);
921
922         // Check for errors
923         if (PyErr_Occurred())
924     {
925                 Py_FatalError("can't initialize module GameLogic");
926     }
927
928         return m;
929 }
930
931 // Python Sandbox code
932 // override builtin functions import() and open()
933
934
935 PyObject *KXpy_open(PyObject *self, PyObject *args) {
936         PyErr_SetString(PyExc_RuntimeError, "Sandbox: open() function disabled!\nGame Scripts should not use this function.");
937         return NULL;
938 }
939
940 PyObject *KXpy_reload(PyObject *self, PyObject *args) {
941         PyErr_SetString(PyExc_RuntimeError, "Sandbox: reload() function disabled!\nGame Scripts should not use this function.");
942         return NULL;
943 }
944
945 PyObject *KXpy_file(PyObject *self, PyObject *args) {
946         PyErr_SetString(PyExc_RuntimeError, "Sandbox: file() function disabled!\nGame Scripts should not use this function.");
947         return NULL;
948 }
949
950 PyObject *KXpy_execfile(PyObject *self, PyObject *args) {
951         PyErr_SetString(PyExc_RuntimeError, "Sandbox: execfile() function disabled!\nGame Scripts should not use this function.");
952         return NULL;
953 }
954
955 PyObject *KXpy_compile(PyObject *self, PyObject *args) {
956         PyErr_SetString(PyExc_RuntimeError, "Sandbox: compile() function disabled!\nGame Scripts should not use this function.");
957         return NULL;
958 }
959
960 PyObject *KXpy_import(PyObject *self, PyObject *args)
961 {
962         char *name;
963         PyObject *globals = NULL;
964         PyObject *locals = NULL;
965         PyObject *fromlist = NULL;
966         PyObject *l, *m, *n;
967
968         if (!PyArg_ParseTuple(args, "s|OOO:m_import",
969                 &name, &globals, &locals, &fromlist))
970             return NULL;
971
972         /* check for builtin modules */
973         m = PyImport_AddModule("sys");
974         l = PyObject_GetAttrString(m, "builtin_module_names");
975         n = PyString_FromString(name);
976         
977         if (PySequence_Contains(l, n)) {
978                 return PyImport_ImportModuleEx(name, globals, locals, fromlist);
979         }
980
981         /* quick hack for GamePython modules 
982                 TODO: register builtin modules properly by ExtendInittab */
983         if (!strcmp(name, "GameLogic") || !strcmp(name, "GameKeys") || !strcmp(name, "PhysicsConstraints") ||
984                 !strcmp(name, "Rasterizer") || !strcmp(name, "Mathutils")) {
985                 return PyImport_ImportModuleEx(name, globals, locals, fromlist);
986         }
987                 
988         PyErr_Format(PyExc_ImportError,
989                  "Import of external Module %.20s not allowed.", name);
990         return NULL;
991
992 }
993
994
995 static PyMethodDef meth_open[] = {{ "open", KXpy_open, METH_VARARGS, "(disabled)"}};
996 static PyMethodDef meth_reload[] = {{ "reload", KXpy_reload, METH_VARARGS, "(disabled)"}};
997 static PyMethodDef meth_file[] = {{ "file", KXpy_file, METH_VARARGS, "(disabled)"}};
998 static PyMethodDef meth_execfile[] = {{ "execfile", KXpy_execfile, METH_VARARGS, "(disabled)"}};
999 static PyMethodDef meth_compile[] = {{ "compile", KXpy_compile, METH_VARARGS, "(disabled)"}};
1000
1001 static PyMethodDef meth_import[] = {{ "import", KXpy_import, METH_VARARGS, "our own import"}};
1002
1003 //static PyObject *g_oldopen = 0;
1004 //static PyObject *g_oldimport = 0;
1005 //static int g_security = 0;
1006
1007
1008 void setSandbox(TPythonSecurityLevel level)
1009 {
1010     PyObject *m = PyImport_AddModule("__builtin__");
1011     PyObject *d = PyModule_GetDict(m);
1012
1013         switch (level) {
1014         case psl_Highest:
1015                 //if (!g_security) {
1016                         //g_oldopen = PyDict_GetItemString(d, "open");
1017         
1018                         // functions we cant trust
1019                         PyDict_SetItemString(d, "open", PyCFunction_New(meth_open, NULL));
1020                         PyDict_SetItemString(d, "reload", PyCFunction_New(meth_reload, NULL));
1021                         PyDict_SetItemString(d, "file", PyCFunction_New(meth_file, NULL));
1022                         PyDict_SetItemString(d, "execfile", PyCFunction_New(meth_execfile, NULL));
1023                         PyDict_SetItemString(d, "compile", PyCFunction_New(meth_compile, NULL));
1024                         
1025                         // our own import
1026                         PyDict_SetItemString(d, "__import__", PyCFunction_New(meth_import, NULL));
1027                         //g_security = level;
1028                 //}
1029                 break;
1030         /*
1031         case psl_Lowest:
1032                 if (g_security) {
1033                         PyDict_SetItemString(d, "open", g_oldopen);
1034                         PyDict_SetItemString(d, "__import__", g_oldimport);
1035                         g_security = level;
1036                 }
1037         */
1038         default:
1039                 break;
1040         }
1041 }
1042
1043 /**
1044  * Python is not initialised.
1045  */
1046 PyObject* initGamePlayerPythonScripting(const STR_String& progname, TPythonSecurityLevel level)
1047 {
1048         STR_String pname = progname;
1049         Py_SetProgramName(pname.Ptr());
1050         Py_NoSiteFlag=1;
1051         Py_FrozenFlag=1;
1052         Py_Initialize();
1053
1054         //importBlenderModules()
1055         
1056         setSandbox(level);
1057
1058         PyObject* moduleobj = PyImport_AddModule("__main__");
1059         return PyModule_GetDict(moduleobj);
1060 }
1061
1062 void exitGamePlayerPythonScripting()
1063 {
1064         Py_Finalize();
1065 }
1066
1067 /**
1068  * Python is already initialized.
1069  */
1070 PyObject* initGamePythonScripting(const STR_String& progname, TPythonSecurityLevel level)
1071 {
1072         STR_String pname = progname;
1073         Py_SetProgramName(pname.Ptr());
1074         Py_NoSiteFlag=1;
1075         Py_FrozenFlag=1;
1076
1077         setSandbox(level);
1078
1079         PyObject* moduleobj = PyImport_AddModule("__main__");
1080         return PyModule_GetDict(moduleobj);
1081 }
1082
1083
1084
1085 void exitGamePythonScripting()
1086 {
1087 }
1088
1089
1090
1091 PyObject* initRasterizer(RAS_IRasterizer* rasty,RAS_ICanvas* canvas)
1092 {
1093         gp_Canvas = canvas;
1094         gp_Rasterizer = rasty;
1095
1096
1097   PyObject* m;
1098   PyObject* d;
1099
1100   // Create the module and add the functions
1101   m = Py_InitModule4("Rasterizer", rasterizer_methods,
1102                      Rasterizer_module_documentation,
1103                      (PyObject*)NULL,PYTHON_API_VERSION);
1104
1105   // Add some symbolic constants to the module
1106   d = PyModule_GetDict(m);
1107   ErrorObject = PyString_FromString("Rasterizer.error");
1108   PyDict_SetItemString(d, "error", ErrorObject);
1109
1110   // XXXX Add constants here
1111
1112   // Check for errors
1113   if (PyErr_Occurred())
1114     {
1115       Py_FatalError("can't initialize module Rasterizer");
1116     }
1117
1118   return d;
1119 }
1120
1121
1122
1123 /* ------------------------------------------------------------------------- */
1124 /* GameKeys: symbolic constants for key mapping                              */
1125 /* ------------------------------------------------------------------------- */
1126
1127 static char GameKeys_module_documentation[] =
1128 "This modules provides defines for key-codes"
1129 ;
1130
1131 static char gPyEventToString_doc[] =
1132 "Take a valid event from the GameKeys module or Keyboard Sensor and return a name"
1133 ;
1134
1135 static PyObject* gPyEventToString(PyObject*, PyObject* value)
1136 {
1137         PyObject* mod, *dict, *key, *val, *ret = NULL;
1138         Py_ssize_t pos = 0;
1139         
1140         mod = PyImport_ImportModule( "GameKeys" );
1141         if (!mod)
1142                 return NULL;
1143         
1144         dict = PyModule_GetDict(mod);
1145         
1146         while (PyDict_Next(dict, &pos, &key, &val)) {
1147                 if (PyObject_Compare(value, val)==0) {
1148                         ret = key;
1149                         break;
1150                 }
1151         }
1152         
1153         PyErr_Clear(); // incase there was an error clearing
1154         Py_DECREF(mod);
1155         if (!ret)       PyErr_SetString(PyExc_ValueError, "expected a valid int keyboard event");
1156         else            Py_INCREF(ret);
1157         
1158         return ret;
1159 }
1160
1161 static struct PyMethodDef gamekeys_methods[] = {
1162         {"EventToString", (PyCFunction)gPyEventToString, METH_O, gPyEventToString_doc},
1163         { NULL, (PyCFunction) NULL, 0, NULL }
1164 };
1165
1166
1167
1168 PyObject* initGameKeys()
1169 {
1170         PyObject* m;
1171         PyObject* d;
1172
1173         // Create the module and add the functions
1174         m = Py_InitModule4("GameKeys", gamekeys_methods,
1175                                            GameKeys_module_documentation,
1176                                            (PyObject*)NULL,PYTHON_API_VERSION);
1177
1178         // Add some symbolic constants to the module
1179         d = PyModule_GetDict(m);
1180
1181         // XXXX Add constants here
1182
1183         KX_MACRO_addTypesToDict(d, AKEY, SCA_IInputDevice::KX_AKEY);
1184         KX_MACRO_addTypesToDict(d, BKEY, SCA_IInputDevice::KX_BKEY);
1185         KX_MACRO_addTypesToDict(d, CKEY, SCA_IInputDevice::KX_CKEY);
1186         KX_MACRO_addTypesToDict(d, DKEY, SCA_IInputDevice::KX_DKEY);
1187         KX_MACRO_addTypesToDict(d, EKEY, SCA_IInputDevice::KX_EKEY);
1188         KX_MACRO_addTypesToDict(d, FKEY, SCA_IInputDevice::KX_FKEY);
1189         KX_MACRO_addTypesToDict(d, GKEY, SCA_IInputDevice::KX_GKEY);
1190         KX_MACRO_addTypesToDict(d, HKEY, SCA_IInputDevice::KX_HKEY);
1191         KX_MACRO_addTypesToDict(d, IKEY, SCA_IInputDevice::KX_IKEY);
1192         KX_MACRO_addTypesToDict(d, JKEY, SCA_IInputDevice::KX_JKEY);
1193         KX_MACRO_addTypesToDict(d, KKEY, SCA_IInputDevice::KX_KKEY);
1194         KX_MACRO_addTypesToDict(d, LKEY, SCA_IInputDevice::KX_LKEY);
1195         KX_MACRO_addTypesToDict(d, MKEY, SCA_IInputDevice::KX_MKEY);
1196         KX_MACRO_addTypesToDict(d, NKEY, SCA_IInputDevice::KX_NKEY);
1197         KX_MACRO_addTypesToDict(d, OKEY, SCA_IInputDevice::KX_OKEY);
1198         KX_MACRO_addTypesToDict(d, PKEY, SCA_IInputDevice::KX_PKEY);
1199         KX_MACRO_addTypesToDict(d, QKEY, SCA_IInputDevice::KX_QKEY);
1200         KX_MACRO_addTypesToDict(d, RKEY, SCA_IInputDevice::KX_RKEY);
1201         KX_MACRO_addTypesToDict(d, SKEY, SCA_IInputDevice::KX_SKEY);
1202         KX_MACRO_addTypesToDict(d, TKEY, SCA_IInputDevice::KX_TKEY);
1203         KX_MACRO_addTypesToDict(d, UKEY, SCA_IInputDevice::KX_UKEY);
1204         KX_MACRO_addTypesToDict(d, VKEY, SCA_IInputDevice::KX_VKEY);
1205         KX_MACRO_addTypesToDict(d, WKEY, SCA_IInputDevice::KX_WKEY);
1206         KX_MACRO_addTypesToDict(d, XKEY, SCA_IInputDevice::KX_XKEY);
1207         KX_MACRO_addTypesToDict(d, YKEY, SCA_IInputDevice::KX_YKEY);
1208         KX_MACRO_addTypesToDict(d, ZKEY, SCA_IInputDevice::KX_ZKEY);
1209         
1210         KX_MACRO_addTypesToDict(d, ZEROKEY, SCA_IInputDevice::KX_ZEROKEY);              
1211         KX_MACRO_addTypesToDict(d, ONEKEY, SCA_IInputDevice::KX_ONEKEY);                
1212         KX_MACRO_addTypesToDict(d, TWOKEY, SCA_IInputDevice::KX_TWOKEY);                
1213         KX_MACRO_addTypesToDict(d, THREEKEY, SCA_IInputDevice::KX_THREEKEY);
1214         KX_MACRO_addTypesToDict(d, FOURKEY, SCA_IInputDevice::KX_FOURKEY);              
1215         KX_MACRO_addTypesToDict(d, FIVEKEY, SCA_IInputDevice::KX_FIVEKEY);              
1216         KX_MACRO_addTypesToDict(d, SIXKEY, SCA_IInputDevice::KX_SIXKEY);                
1217         KX_MACRO_addTypesToDict(d, SEVENKEY, SCA_IInputDevice::KX_SEVENKEY);
1218         KX_MACRO_addTypesToDict(d, EIGHTKEY, SCA_IInputDevice::KX_EIGHTKEY);
1219         KX_MACRO_addTypesToDict(d, NINEKEY, SCA_IInputDevice::KX_NINEKEY);              
1220                 
1221         KX_MACRO_addTypesToDict(d, CAPSLOCKKEY, SCA_IInputDevice::KX_CAPSLOCKKEY);
1222                 
1223         KX_MACRO_addTypesToDict(d, LEFTCTRLKEY, SCA_IInputDevice::KX_LEFTCTRLKEY);      
1224         KX_MACRO_addTypesToDict(d, LEFTALTKEY, SCA_IInputDevice::KX_LEFTALTKEY);                
1225         KX_MACRO_addTypesToDict(d, RIGHTALTKEY, SCA_IInputDevice::KX_RIGHTALTKEY);      
1226         KX_MACRO_addTypesToDict(d, RIGHTCTRLKEY, SCA_IInputDevice::KX_RIGHTCTRLKEY);    
1227         KX_MACRO_addTypesToDict(d, RIGHTSHIFTKEY, SCA_IInputDevice::KX_RIGHTSHIFTKEY);  
1228         KX_MACRO_addTypesToDict(d, LEFTSHIFTKEY, SCA_IInputDevice::KX_LEFTSHIFTKEY);
1229                 
1230         KX_MACRO_addTypesToDict(d, ESCKEY, SCA_IInputDevice::KX_ESCKEY);
1231         KX_MACRO_addTypesToDict(d, TABKEY, SCA_IInputDevice::KX_TABKEY);
1232         KX_MACRO_addTypesToDict(d, RETKEY, SCA_IInputDevice::KX_RETKEY);
1233         KX_MACRO_addTypesToDict(d, SPACEKEY, SCA_IInputDevice::KX_SPACEKEY);
1234         KX_MACRO_addTypesToDict(d, LINEFEEDKEY, SCA_IInputDevice::KX_LINEFEEDKEY);              
1235         KX_MACRO_addTypesToDict(d, BACKSPACEKEY, SCA_IInputDevice::KX_BACKSPACEKEY);
1236         KX_MACRO_addTypesToDict(d, DELKEY, SCA_IInputDevice::KX_DELKEY);
1237         KX_MACRO_addTypesToDict(d, SEMICOLONKEY, SCA_IInputDevice::KX_SEMICOLONKEY);
1238         KX_MACRO_addTypesToDict(d, PERIODKEY, SCA_IInputDevice::KX_PERIODKEY);          
1239         KX_MACRO_addTypesToDict(d, COMMAKEY, SCA_IInputDevice::KX_COMMAKEY);            
1240         KX_MACRO_addTypesToDict(d, QUOTEKEY, SCA_IInputDevice::KX_QUOTEKEY);            
1241         KX_MACRO_addTypesToDict(d, ACCENTGRAVEKEY, SCA_IInputDevice::KX_ACCENTGRAVEKEY);        
1242         KX_MACRO_addTypesToDict(d, MINUSKEY, SCA_IInputDevice::KX_MINUSKEY);            
1243         KX_MACRO_addTypesToDict(d, SLASHKEY, SCA_IInputDevice::KX_SLASHKEY);            
1244         KX_MACRO_addTypesToDict(d, BACKSLASHKEY, SCA_IInputDevice::KX_BACKSLASHKEY);
1245         KX_MACRO_addTypesToDict(d, EQUALKEY, SCA_IInputDevice::KX_EQUALKEY);            
1246         KX_MACRO_addTypesToDict(d, LEFTBRACKETKEY, SCA_IInputDevice::KX_LEFTBRACKETKEY);        
1247         KX_MACRO_addTypesToDict(d, RIGHTBRACKETKEY, SCA_IInputDevice::KX_RIGHTBRACKETKEY);      
1248                 
1249         KX_MACRO_addTypesToDict(d, LEFTARROWKEY, SCA_IInputDevice::KX_LEFTARROWKEY);
1250         KX_MACRO_addTypesToDict(d, DOWNARROWKEY, SCA_IInputDevice::KX_DOWNARROWKEY);
1251         KX_MACRO_addTypesToDict(d, RIGHTARROWKEY, SCA_IInputDevice::KX_RIGHTARROWKEY);  
1252         KX_MACRO_addTypesToDict(d, UPARROWKEY, SCA_IInputDevice::KX_UPARROWKEY);                
1253         
1254         KX_MACRO_addTypesToDict(d, PAD2 , SCA_IInputDevice::KX_PAD2);
1255         KX_MACRO_addTypesToDict(d, PAD4 , SCA_IInputDevice::KX_PAD4);
1256         KX_MACRO_addTypesToDict(d, PAD6 , SCA_IInputDevice::KX_PAD6);
1257         KX_MACRO_addTypesToDict(d, PAD8 , SCA_IInputDevice::KX_PAD8);
1258                 
1259         KX_MACRO_addTypesToDict(d, PAD1 , SCA_IInputDevice::KX_PAD1);
1260         KX_MACRO_addTypesToDict(d, PAD3 , SCA_IInputDevice::KX_PAD3);
1261         KX_MACRO_addTypesToDict(d, PAD5 , SCA_IInputDevice::KX_PAD5);
1262         KX_MACRO_addTypesToDict(d, PAD7 , SCA_IInputDevice::KX_PAD7);
1263         KX_MACRO_addTypesToDict(d, PAD9 , SCA_IInputDevice::KX_PAD9);
1264                 
1265         KX_MACRO_addTypesToDict(d, PADPERIOD, SCA_IInputDevice::KX_PADPERIOD);
1266         KX_MACRO_addTypesToDict(d, PADSLASHKEY, SCA_IInputDevice::KX_PADSLASHKEY);
1267         KX_MACRO_addTypesToDict(d, PADASTERKEY, SCA_IInputDevice::KX_PADASTERKEY);
1268                 
1269                 
1270         KX_MACRO_addTypesToDict(d, PAD0, SCA_IInputDevice::KX_PAD0);
1271         KX_MACRO_addTypesToDict(d, PADMINUS, SCA_IInputDevice::KX_PADMINUS);
1272         KX_MACRO_addTypesToDict(d, PADENTER, SCA_IInputDevice::KX_PADENTER);
1273         KX_MACRO_addTypesToDict(d, PADPLUSKEY, SCA_IInputDevice::KX_PADPLUSKEY);
1274                 
1275                 
1276         KX_MACRO_addTypesToDict(d, F1KEY , SCA_IInputDevice::KX_F1KEY);
1277         KX_MACRO_addTypesToDict(d, F2KEY , SCA_IInputDevice::KX_F2KEY);
1278         KX_MACRO_addTypesToDict(d, F3KEY , SCA_IInputDevice::KX_F3KEY);
1279         KX_MACRO_addTypesToDict(d, F4KEY , SCA_IInputDevice::KX_F4KEY);
1280         KX_MACRO_addTypesToDict(d, F5KEY , SCA_IInputDevice::KX_F5KEY);
1281         KX_MACRO_addTypesToDict(d, F6KEY , SCA_IInputDevice::KX_F6KEY);
1282         KX_MACRO_addTypesToDict(d, F7KEY , SCA_IInputDevice::KX_F7KEY);
1283         KX_MACRO_addTypesToDict(d, F8KEY , SCA_IInputDevice::KX_F8KEY);
1284         KX_MACRO_addTypesToDict(d, F9KEY , SCA_IInputDevice::KX_F9KEY);
1285         KX_MACRO_addTypesToDict(d, F10KEY, SCA_IInputDevice::KX_F10KEY);
1286         KX_MACRO_addTypesToDict(d, F11KEY, SCA_IInputDevice::KX_F11KEY);
1287         KX_MACRO_addTypesToDict(d, F12KEY, SCA_IInputDevice::KX_F12KEY);
1288                 
1289         KX_MACRO_addTypesToDict(d, PAUSEKEY, SCA_IInputDevice::KX_PAUSEKEY);
1290         KX_MACRO_addTypesToDict(d, INSERTKEY, SCA_IInputDevice::KX_INSERTKEY);
1291         KX_MACRO_addTypesToDict(d, HOMEKEY , SCA_IInputDevice::KX_HOMEKEY);
1292         KX_MACRO_addTypesToDict(d, PAGEUPKEY, SCA_IInputDevice::KX_PAGEUPKEY);
1293         KX_MACRO_addTypesToDict(d, PAGEDOWNKEY, SCA_IInputDevice::KX_PAGEDOWNKEY);
1294         KX_MACRO_addTypesToDict(d, ENDKEY, SCA_IInputDevice::KX_ENDKEY);
1295
1296
1297         // Check for errors
1298         if (PyErr_Occurred())
1299     {
1300                 Py_FatalError("can't initialize module GameKeys");
1301     }
1302
1303         return d;
1304 }
1305
1306 PyObject* initMathutils()
1307 {
1308         return Mathutils_Init("Mathutils"); // Use as a top level module in BGE
1309 }
1310
1311 void PHY_SetActiveScene(class KX_Scene* scene)
1312 {
1313         gp_KetsjiScene = scene;
1314 }
1315
1316 class KX_Scene* PHY_GetActiveScene()
1317 {
1318         return gp_KetsjiScene;
1319 }