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