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