BGE: Multitexture world (mist, ambient) fix
[blender.git] / source / gameengine / Ketsji / KX_PythonInit.cpp
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  * Initialize Python thingies.
27  */
28
29 /** \file gameengine/Ketsji/KX_PythonInit.cpp
30  *  \ingroup ketsji
31  */
32
33 #include "glew-mx.h"
34
35 #ifdef _MSC_VER
36 #  pragma warning (disable:4786)
37 #endif
38
39 #ifdef WITH_PYTHON
40 #  ifdef   _POSIX_C_SOURCE
41 #    undef _POSIX_C_SOURCE
42 #  endif
43 #  ifdef   _XOPEN_SOURCE
44 #    undef _XOPEN_SOURCE
45 #  endif
46 #  if defined(__sun) || defined(sun)
47 #    if defined(_XPG4)
48 #      undef _XPG4
49 #    endif
50 #  endif
51 #  include <Python.h>
52
53 extern "C" {
54         #  include "bpy_internal_import.h"  /* from the blender python api, but we want to import text too! */
55         #  include "py_capi_utils.h"
56         #  include "mathutils.h" // 'mathutils' module copied here so the blenderlayer can use.
57         #  include "bgl.h"
58         #  include "blf_py_api.h"
59
60         #  include "marshal.h" /* python header for loading/saving dicts */
61 }
62 #include "AUD_PyInit.h"
63
64 #endif  /* WITH_PYTHON */
65
66 #include "KX_PythonInit.h"
67
68 // directory header for py function getBlendFileList
69 #ifndef WIN32
70 #  include <dirent.h>
71 #  include <stdlib.h>
72 #else
73 #  include <io.h>
74 #  include "BLI_winstuff.h"
75 #endif
76
77 //python physics binding
78 #include "KX_PyConstraintBinding.h"
79
80 #include "KX_KetsjiEngine.h"
81 #include "KX_RadarSensor.h"
82 #include "KX_RaySensor.h"
83 #include "KX_ArmatureSensor.h"
84 #include "KX_SceneActuator.h"
85 #include "KX_GameActuator.h"
86 #include "KX_ParentActuator.h"
87 #include "KX_SCA_DynamicActuator.h"
88 #include "KX_SteeringActuator.h"
89 #include "KX_NavMeshObject.h"
90 #include "KX_MouseActuator.h"
91 #include "KX_TrackToActuator.h"
92
93 #include "SCA_IInputDevice.h"
94 #include "SCA_PropertySensor.h"
95 #include "SCA_RandomActuator.h"
96 #include "SCA_KeyboardSensor.h" /* IsPrintable, ToCharacter */
97 #include "SCA_JoystickManager.h" /* JOYINDEX_MAX */
98 #include "SCA_PythonJoystick.h"
99 #include "SCA_PythonKeyboard.h"
100 #include "SCA_PythonMouse.h"
101 #include "KX_ConstraintActuator.h"
102 #include "KX_IpoActuator.h"
103 #include "KX_SoundActuator.h"
104 #include "KX_StateActuator.h"
105 #include "BL_ActionActuator.h"
106 #include "BL_ArmatureObject.h"
107 #include "RAS_IRasterizer.h"
108 #include "RAS_ICanvas.h"
109 #include "RAS_BucketManager.h"
110 #include "RAS_2DFilterManager.h"
111 #include "MT_Vector3.h"
112 #include "MT_Point3.h"
113 #include "ListValue.h"
114 #include "InputParser.h"
115 #include "KX_Scene.h"
116
117 #include "NG_NetworkScene.h" //Needed for sendMessage()
118
119 #include "BL_Shader.h"
120 #include "BL_Action.h"
121
122 #include "KX_PyMath.h"
123
124 #include "PyObjectPlus.h"
125
126 #include "KX_PythonInitTypes.h" 
127
128 /* we only need this to get a list of libraries from the main struct */
129 #include "DNA_ID.h"
130 #include "DNA_scene_types.h"
131
132 #include "PHY_IPhysicsEnvironment.h"
133
134 extern "C" {
135 #include "BKE_main.h"
136 #include "BKE_global.h"
137 #include "BKE_library.h"
138 #include "BKE_appdir.h"
139 #include "BLI_blenlib.h"
140 #include "GPU_material.h"
141 #include "MEM_guardedalloc.h"
142 }
143
144 /* for converting new scenes */
145 #include "KX_BlenderSceneConverter.h"
146 #include "KX_LibLoadStatus.h"
147 #include "KX_MeshProxy.h" /* for creating a new library of mesh objects */
148 extern "C" {
149         #include "BKE_idcode.h"
150 }
151
152 // 'local' copy of canvas ptr, for window height/width python scripts
153
154 #ifdef WITH_PYTHON
155
156 static RAS_ICanvas* gp_Canvas = NULL;
157 static char gp_GamePythonPath[FILE_MAX] = "";
158 static char gp_GamePythonPathOrig[FILE_MAX] = ""; // not super happy about this, but we need to remember the first loaded file for the global/dict load save
159
160 static SCA_PythonKeyboard* gp_PythonKeyboard = NULL;
161 static SCA_PythonMouse* gp_PythonMouse = NULL;
162 static SCA_PythonJoystick* gp_PythonJoysticks[JOYINDEX_MAX] = {NULL};
163 #endif // WITH_PYTHON
164
165 static KX_Scene*        gp_KetsjiScene = NULL;
166 static KX_KetsjiEngine* gp_KetsjiEngine = NULL;
167 static RAS_IRasterizer* gp_Rasterizer = NULL;
168
169
170 void KX_SetActiveScene(class KX_Scene* scene)
171 {
172         gp_KetsjiScene = scene;
173 }
174
175 class KX_Scene* KX_GetActiveScene()
176 {
177         return gp_KetsjiScene;
178 }
179
180 class KX_KetsjiEngine* KX_GetActiveEngine()
181 {
182         return gp_KetsjiEngine;
183 }
184
185 /* why is this in python? */
186 void    KX_RasterizerDrawDebugLine(const MT_Vector3& from,const MT_Vector3& to,const MT_Vector3& color)
187 {
188         if (gp_Rasterizer)
189                 gp_Rasterizer->DrawDebugLine(from,to,color);
190 }
191
192 void KX_RasterizerDrawDebugCircle(const MT_Vector3& center, const MT_Scalar radius, const MT_Vector3& color,
193                                   const MT_Vector3& normal, int nsector)
194 {
195         if (gp_Rasterizer)
196                 gp_Rasterizer->DrawDebugCircle(center, radius, color, normal, nsector);
197 }
198
199 #ifdef WITH_PYTHON
200
201 static PyObject *gp_OrigPythonSysPath= NULL;
202 static PyObject *gp_OrigPythonSysModules= NULL;
203
204 /* Macro for building the keyboard translation */
205 //#define KX_MACRO_addToDict(dict, name) PyDict_SetItemString(dict, #name, PyLong_FromLong(SCA_IInputDevice::KX_##name))
206 //#define KX_MACRO_addToDict(dict, name) PyDict_SetItemString(dict, #name, item=PyLong_FromLong(name)); Py_DECREF(item)
207 /* For the defines for types from logic bricks, we do stuff explicitly... */
208 #define KX_MACRO_addTypesToDict(dict, name, value) KX_MACRO_addTypesToDict_fn(dict, #name, value)
209 static void KX_MACRO_addTypesToDict_fn(PyObject *dict, const char *name, long value)
210 {
211         PyObject *item;
212
213         item = PyLong_FromLong(value);
214         PyDict_SetItemString(dict, name, item);
215         Py_DECREF(item);
216 }
217
218
219
220 // temporarily python stuff, will be put in another place later !
221 #include "KX_Python.h"
222 #include "SCA_PythonController.h"
223 // List of methods defined in the module
224
225 static PyObject *ErrorObject;
226
227 PyDoc_STRVAR(gPyGetRandomFloat_doc,
228 "getRandomFloat()\n"
229 "returns a random floating point value in the range [0..1]"
230 );
231 static PyObject *gPyGetRandomFloat(PyObject *)
232 {
233         return PyFloat_FromDouble(MT_random());
234 }
235
236 static PyObject *gPySetGravity(PyObject *, PyObject *value)
237 {
238         MT_Vector3 vec;
239         if (!PyVecTo(value, vec))
240                 return NULL;
241
242         if (gp_KetsjiScene)
243                 gp_KetsjiScene->SetGravity(vec);
244         
245         Py_RETURN_NONE;
246 }
247
248 PyDoc_STRVAR(gPyExpandPath_doc,
249 "expandPath(path)\n"
250 "Converts a blender internal path into a proper file system path.\n"
251 " path - the string path to convert.\n"
252 "Use / as directory separator in path\n"
253 "You can use '//' at the start of the string to define a relative path."
254 "Blender replaces that string by the directory of the current .blend or runtime file to make a full path name.\n"
255 "The function also converts the directory separator to the local file system format."
256 );
257 static PyObject *gPyExpandPath(PyObject *, PyObject *args)
258 {
259         char expanded[FILE_MAX];
260         char* filename;
261         
262         if (!PyArg_ParseTuple(args,"s:ExpandPath",&filename))
263                 return NULL;
264
265         BLI_strncpy(expanded, filename, FILE_MAX);
266         BLI_path_abs(expanded, gp_GamePythonPath);
267         return PyC_UnicodeFromByte(expanded);
268 }
269
270 PyDoc_STRVAR(gPyStartGame_doc,
271 "startGame(blend)\n"
272 "Loads the blend file"
273 );
274 static PyObject *gPyStartGame(PyObject *, PyObject *args)
275 {
276         char* blendfile;
277
278         if (!PyArg_ParseTuple(args, "s:startGame", &blendfile))
279                 return NULL;
280
281         gp_KetsjiEngine->RequestExit(KX_EXIT_REQUEST_START_OTHER_GAME);
282         gp_KetsjiEngine->SetNameNextGame(blendfile);
283
284         Py_RETURN_NONE;
285 }
286
287 PyDoc_STRVAR(gPyEndGame_doc,
288 "endGame()\n"
289 "Ends the current game"
290 );
291 static PyObject *gPyEndGame(PyObject *)
292 {
293         gp_KetsjiEngine->RequestExit(KX_EXIT_REQUEST_QUIT_GAME);
294
295         //printf("%s\n", gp_GamePythonPath);
296
297         Py_RETURN_NONE;
298 }
299
300 PyDoc_STRVAR(gPyRestartGame_doc,
301 "restartGame()\n"
302 "Restarts the current game by reloading the .blend file"
303 );
304 static PyObject *gPyRestartGame(PyObject *)
305 {
306         gp_KetsjiEngine->RequestExit(KX_EXIT_REQUEST_RESTART_GAME);
307         gp_KetsjiEngine->SetNameNextGame(gp_GamePythonPath);
308
309         Py_RETURN_NONE;
310 }
311
312 PyDoc_STRVAR(gPySaveGlobalDict_doc,
313 "saveGlobalDict()\n"
314 "Saves bge.logic.globalDict to a file"
315 );
316 static PyObject *gPySaveGlobalDict(PyObject *)
317 {
318         char marshal_path[512];
319         char *marshal_buffer = NULL;
320         unsigned int marshal_length;
321         FILE *fp = NULL;
322
323         pathGamePythonConfig(marshal_path);
324         marshal_length = saveGamePythonConfig(&marshal_buffer);
325
326         if (marshal_length && marshal_buffer)
327         {
328                 fp = fopen(marshal_path, "wb");
329
330                 if (fp)
331                 {
332                         if (fwrite(marshal_buffer, 1, marshal_length, fp) != marshal_length)
333                                 printf("Warning: could not write marshal data\n");
334
335                         fclose(fp);
336                 } else {
337                         printf("Warning: could not open marshal file\n");
338                 }
339         } else {
340                 printf("Warning: could not create marshal buffer\n");
341         }
342
343         if (marshal_buffer)
344                 delete [] marshal_buffer;
345
346         Py_RETURN_NONE;
347 }
348
349 PyDoc_STRVAR(gPyLoadGlobalDict_doc,
350 "LoadGlobalDict()\n"
351 "Loads bge.logic.globalDict from a file"
352 );
353 static PyObject *gPyLoadGlobalDict(PyObject *)
354 {
355         char marshal_path[512];
356         char *marshal_buffer = NULL;
357         size_t marshal_length;
358         FILE *fp = NULL;
359         int result;
360
361         pathGamePythonConfig(marshal_path);
362
363         fp = fopen(marshal_path, "rb");
364
365         if (fp) {
366                 // obtain file size:
367                 fseek (fp, 0, SEEK_END);
368                 marshal_length = (size_t)ftell(fp);
369                 rewind(fp);
370
371                 marshal_buffer = (char*)malloc (sizeof(char)*marshal_length);
372
373                 result = fread(marshal_buffer, 1, marshal_length, fp);
374
375                 if (result == marshal_length) {
376                         loadGamePythonConfig(marshal_buffer, marshal_length);
377                 } else {
378                         printf("Warning: could not read all of '%s'\n", marshal_path);
379                 }
380
381                 free(marshal_buffer);
382                 fclose(fp);
383         } else {
384                 printf("Warning: could not open '%s'\n", marshal_path);
385         }
386
387         Py_RETURN_NONE;
388 }
389
390 PyDoc_STRVAR(gPyGetProfileInfo_doc,
391 "getProfileInfo()\n"
392 "returns a dictionary with profiling information"
393 );
394 static PyObject *gPyGetProfileInfo(PyObject *)
395 {
396         return gp_KetsjiEngine->GetPyProfileDict();
397 }
398
399 PyDoc_STRVAR(gPySendMessage_doc,
400 "sendMessage(subject, [body, to, from])\n"
401 "sends a message in same manner as a message actuator"
402 " subject = Subject of the message"
403 " body = Message body"
404 " to = Name of object to send the message to"
405 " from = Name of object to send the string from"
406 );
407 static PyObject *gPySendMessage(PyObject *, PyObject *args)
408 {
409         char* subject;
410         char* body = (char *)"";
411         char* to = (char *)"";
412         char* from = (char *)"";
413
414         if (!PyArg_ParseTuple(args, "s|sss:sendMessage", &subject, &body, &to, &from))
415                 return NULL;
416
417         gp_KetsjiScene->GetNetworkScene()->SendMessage(to, from, subject, body);
418
419         Py_RETURN_NONE;
420 }
421
422 // this gets a pointer to an array filled with floats
423 static PyObject *gPyGetSpectrum(PyObject *)
424 {
425         PyObject *resultlist = PyList_New(512);
426
427         for (int index = 0; index < 512; index++)
428         {
429                 PyList_SET_ITEM(resultlist, index, PyFloat_FromDouble(0.0));
430         }
431
432         return resultlist;
433 }
434
435 static PyObject *gPySetLogicTicRate(PyObject *, PyObject *args)
436 {
437         float ticrate;
438         if (!PyArg_ParseTuple(args, "f:setLogicTicRate", &ticrate))
439                 return NULL;
440         
441         KX_KetsjiEngine::SetTicRate(ticrate);
442         Py_RETURN_NONE;
443 }
444
445 static PyObject *gPyGetLogicTicRate(PyObject *)
446 {
447         return PyFloat_FromDouble(KX_KetsjiEngine::GetTicRate());
448 }
449
450 static PyObject *gPySetExitKey(PyObject *, PyObject *args)
451 {
452         short exitkey;
453         if (!PyArg_ParseTuple(args, "h:setExitKey", &exitkey))
454                 return NULL;
455         KX_KetsjiEngine::SetExitKey(exitkey);
456         Py_RETURN_NONE;
457 }
458
459 static PyObject *gPyGetExitKey(PyObject *)
460 {
461         return PyLong_FromLong(KX_KetsjiEngine::GetExitKey());
462 }
463
464 static PyObject *gPySetMaxLogicFrame(PyObject *, PyObject *args)
465 {
466         int frame;
467         if (!PyArg_ParseTuple(args, "i:setMaxLogicFrame", &frame))
468                 return NULL;
469         
470         KX_KetsjiEngine::SetMaxLogicFrame(frame);
471         Py_RETURN_NONE;
472 }
473
474 static PyObject *gPyGetMaxLogicFrame(PyObject *)
475 {
476         return PyLong_FromLong(KX_KetsjiEngine::GetMaxLogicFrame());
477 }
478
479 static PyObject *gPySetMaxPhysicsFrame(PyObject *, PyObject *args)
480 {
481         int frame;
482         if (!PyArg_ParseTuple(args, "i:setMaxPhysicsFrame", &frame))
483                 return NULL;
484         
485         KX_KetsjiEngine::SetMaxPhysicsFrame(frame);
486         Py_RETURN_NONE;
487 }
488
489 static PyObject *gPyGetMaxPhysicsFrame(PyObject *)
490 {
491         return PyLong_FromLong(KX_KetsjiEngine::GetMaxPhysicsFrame());
492 }
493
494 static PyObject *gPySetPhysicsTicRate(PyObject *, PyObject *args)
495 {
496         float ticrate;
497         if (!PyArg_ParseTuple(args, "f:setPhysicsTicRate", &ticrate))
498                 return NULL;
499         
500         PHY_GetActiveEnvironment()->SetFixedTimeStep(true,ticrate);
501         Py_RETURN_NONE;
502 }
503 #if 0 // unused
504 static PyObject *gPySetPhysicsDebug(PyObject *, PyObject *args)
505 {
506         int debugMode;
507         if (!PyArg_ParseTuple(args, "i:setPhysicsDebug", &debugMode))
508                 return NULL;
509         
510         PHY_GetActiveEnvironment()->setDebugMode(debugMode);
511         Py_RETURN_NONE;
512 }
513 #endif
514
515
516 static PyObject *gPyGetPhysicsTicRate(PyObject *)
517 {
518         return PyFloat_FromDouble(PHY_GetActiveEnvironment()->GetFixedTimeStep());
519 }
520
521 static PyObject *gPyGetAverageFrameRate(PyObject *)
522 {
523         return PyFloat_FromDouble(KX_KetsjiEngine::GetAverageFrameRate());
524 }
525
526 static PyObject *gPyGetBlendFileList(PyObject *, PyObject *args)
527 {
528         char cpath[sizeof(gp_GamePythonPath)];
529         char *searchpath = NULL;
530         PyObject *list, *value;
531
532         DIR *dp;
533         struct dirent *dirp;
534
535         if (!PyArg_ParseTuple(args, "|s:getBlendFileList", &searchpath))
536                 return NULL;
537
538         list = PyList_New(0);
539         
540         if (searchpath) {
541                 BLI_strncpy(cpath, searchpath, FILE_MAX);
542                 BLI_path_abs(cpath, gp_GamePythonPath);
543         } else {
544                 /* Get the dir only */
545                 BLI_split_dir_part(gp_GamePythonPath, cpath, sizeof(cpath));
546         }
547
548         if ((dp  = opendir(cpath)) == NULL) {
549                 /* todo, show the errno, this shouldnt happen anyway if the blendfile is readable */
550                 fprintf(stderr, "Could not read directory (%s) failed, code %d (%s)\n", cpath, errno, strerror(errno));
551                 return list;
552         }
553         
554         while ((dirp = readdir(dp)) != NULL) {
555                 if (BLI_testextensie(dirp->d_name, ".blend")) {
556                         value = PyC_UnicodeFromByte(dirp->d_name);
557                         PyList_Append(list, value);
558                         Py_DECREF(value);
559                 }
560         }
561         
562         closedir(dp);
563         return list;
564 }
565
566 PyDoc_STRVAR(gPyAddScene_doc,
567 "addScene(name, [overlay])\n"
568 "Adds a scene to the game engine.\n"
569 " name = Name of the scene\n"
570 " overlay = Overlay or underlay"
571 );
572 static PyObject *gPyAddScene(PyObject *, PyObject *args)
573 {
574         char* name;
575         int overlay = 1;
576         
577         if (!PyArg_ParseTuple(args, "s|i:addScene", &name , &overlay))
578                 return NULL;
579         
580         gp_KetsjiEngine->ConvertAndAddScene(name, (overlay != 0));
581
582         Py_RETURN_NONE;
583 }
584
585 PyDoc_STRVAR(gPyGetCurrentScene_doc,
586 "getCurrentScene()\n"
587 "Gets a reference to the current scene."
588 );
589 static PyObject *gPyGetCurrentScene(PyObject *self)
590 {
591         return gp_KetsjiScene->GetProxy();
592 }
593
594 PyDoc_STRVAR(gPyGetSceneList_doc,
595 "getSceneList()\n"
596 "Return a list of converted scenes."
597 );
598 static PyObject *gPyGetSceneList(PyObject *self)
599 {
600         KX_KetsjiEngine* m_engine = KX_GetActiveEngine();
601         PyObject *list;
602         KX_SceneList* scenes = m_engine->CurrentScenes();
603         int numScenes = scenes->size();
604         int i;
605         
606         list = PyList_New(numScenes);
607         
608         for (i=0;i<numScenes;i++)
609         {
610                 KX_Scene* scene = scenes->at(i);
611                 PyList_SET_ITEM(list, i, scene->GetProxy());
612         }
613
614         return list;
615 }
616
617 static PyObject *pyPrintStats(PyObject *,PyObject *,PyObject *)
618 {
619         gp_KetsjiScene->GetSceneConverter()->PrintStats();
620         Py_RETURN_NONE;
621 }
622
623 static PyObject *pyPrintExt(PyObject *,PyObject *,PyObject *)
624 {
625 #define pprint(x) std::cout << x << std::endl;
626         bool count=0;
627         bool support=0;
628         pprint("Supported Extensions...");
629         pprint(" GL_ARB_shader_objects supported?       "<< (GLEW_ARB_shader_objects?"yes.":"no."));
630         count = 1;
631
632         support= GLEW_ARB_vertex_shader;
633         pprint(" GL_ARB_vertex_shader supported?        "<< (support?"yes.":"no."));
634         count = 1;
635         if (support) {
636                 pprint(" ----------Details----------");
637                 int max=0;
638                 glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB, (GLint*)&max);
639                 pprint("  Max uniform components." << max);
640
641                 glGetIntegerv(GL_MAX_VARYING_FLOATS_ARB, (GLint*)&max);
642                 pprint("  Max varying floats." << max);
643
644                 glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB, (GLint*)&max);
645                 pprint("  Max vertex texture units." << max);
646         
647                 glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB, (GLint*)&max);
648                 pprint("  Max combined texture units." << max);
649                 pprint("");
650         }
651
652         support=GLEW_ARB_fragment_shader;
653         pprint(" GL_ARB_fragment_shader supported?      "<< (support?"yes.":"no."));
654         count = 1;
655         if (support) {
656                 pprint(" ----------Details----------");
657                 int max=0;
658                 glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB, (GLint*)&max);
659                 pprint("  Max uniform components." << max);
660                 pprint("");
661         }
662
663         support = GLEW_ARB_texture_cube_map;
664         pprint(" GL_ARB_texture_cube_map supported?     "<< (support?"yes.":"no."));
665         count = 1;
666         if (support) {
667                 pprint(" ----------Details----------");
668                 int size=0;
669                 glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB, (GLint*)&size);
670                 pprint("  Max cubemap size." << size);
671                 pprint("");
672         }
673
674         support = GLEW_ARB_multitexture;
675         count = 1;
676         pprint(" GL_ARB_multitexture supported?         "<< (support?"yes.":"no."));
677         if (support) {
678                 pprint(" ----------Details----------");
679                 int units=0;
680                 glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, (GLint*)&units);
681                 pprint("  Max texture units available.  " << units);
682                 pprint("");
683         }
684
685         pprint(" GL_ARB_texture_env_combine supported?  "<< (GLEW_ARB_texture_env_combine?"yes.":"no."));
686         count = 1;
687
688         if (!count)
689                 pprint("No extenstions are used in this build");
690
691         Py_RETURN_NONE;
692 }
693
694 static PyObject *gLibLoad(PyObject *, PyObject *args, PyObject *kwds)
695 {
696         KX_Scene *kx_scene= gp_KetsjiScene;
697         char *path;
698         char *group;
699         Py_buffer py_buffer;
700         py_buffer.buf = NULL;
701         char *err_str= NULL;
702         KX_LibLoadStatus *status = NULL;
703
704         short options=0;
705         int load_actions=0, verbose=0, load_scripts=1, async=0;
706
707         static const char *kwlist[] = {"path", "group", "buffer", "load_actions", "verbose", "load_scripts", "async", NULL};
708         
709         if (!PyArg_ParseTupleAndKeywords(args, kwds, "ss|y*iiIi:LibLoad", const_cast<char**>(kwlist),
710                                                                         &path, &group, &py_buffer, &load_actions, &verbose, &load_scripts, &async))
711                 return NULL;
712
713         /* setup options */
714         if (load_actions != 0)
715                 options |= KX_BlenderSceneConverter::LIB_LOAD_LOAD_ACTIONS;
716         if (verbose != 0)
717                 options |= KX_BlenderSceneConverter::LIB_LOAD_VERBOSE;
718         if (load_scripts != 0)
719                 options |= KX_BlenderSceneConverter::LIB_LOAD_LOAD_SCRIPTS;
720         if (async != 0)
721                 options |= KX_BlenderSceneConverter::LIB_LOAD_ASYNC;
722
723         if (!py_buffer.buf)
724         {
725                 char abs_path[FILE_MAX];
726                 // Make the path absolute
727                 BLI_strncpy(abs_path, path, sizeof(abs_path));
728                 BLI_path_abs(abs_path, gp_GamePythonPath);
729
730                 if ((status=kx_scene->GetSceneConverter()->LinkBlendFilePath(abs_path, group, kx_scene, &err_str, options))) {
731                         return status->GetProxy();
732                 }
733         }
734         else
735         {
736
737                 if ((status=kx_scene->GetSceneConverter()->LinkBlendFileMemory(py_buffer.buf, py_buffer.len, path, group, kx_scene, &err_str, options)))        {
738                         PyBuffer_Release(&py_buffer);
739                         return status->GetProxy();
740                 }
741
742                 PyBuffer_Release(&py_buffer);
743         }
744         
745         if (err_str) {
746                 PyErr_SetString(PyExc_ValueError, err_str);
747                 return NULL;
748         }
749         
750         Py_RETURN_FALSE;
751 }
752
753 static PyObject *gLibNew(PyObject *, PyObject *args)
754 {
755         KX_Scene *kx_scene= gp_KetsjiScene;
756         char *path;
757         char *group;
758         const char *name;
759         PyObject *names;
760         int idcode;
761
762         if (!PyArg_ParseTuple(args,"ssO!:LibNew",&path, &group, &PyList_Type, &names))
763                 return NULL;
764         
765         if (kx_scene->GetSceneConverter()->GetMainDynamicPath(path))
766         {
767                 PyErr_SetString(PyExc_KeyError, "the name of the path given exists");
768                 return NULL;
769         }
770         
771         idcode= BKE_idcode_from_name(group);
772         if (idcode==0) {
773                 PyErr_Format(PyExc_ValueError, "invalid group given \"%s\"", group);
774                 return NULL;
775         }
776         
777         Main *maggie=BKE_main_new();
778         kx_scene->GetSceneConverter()->GetMainDynamic().push_back(maggie);
779         strncpy(maggie->name, path, sizeof(maggie->name)-1);
780         
781         /* Copy the object into main */
782         if (idcode==ID_ME) {
783                 PyObject *ret= PyList_New(0);
784                 PyObject *item;
785                 for (Py_ssize_t i= 0; i < PyList_GET_SIZE(names); i++) {
786                         name= _PyUnicode_AsString(PyList_GET_ITEM(names, i));
787                         if (name) {
788                                 RAS_MeshObject *meshobj= kx_scene->GetSceneConverter()->ConvertMeshSpecial(kx_scene, maggie, name);
789                                 if (meshobj) {
790                                         KX_MeshProxy* meshproxy = new KX_MeshProxy(meshobj);
791                                         item= meshproxy->NewProxy(true);
792                                         PyList_Append(ret, item);
793                                         Py_DECREF(item);
794                                 }
795                         }
796                         else {
797                                 PyErr_Clear(); /* wasnt a string, ignore for now */
798                         }
799                 }
800                 
801                 return ret;
802         }
803         else {
804                 PyErr_Format(PyExc_ValueError, "only \"Mesh\" group currently supported");
805                 return NULL;
806         }
807         
808         Py_RETURN_NONE;
809 }
810
811 static PyObject *gLibFree(PyObject *, PyObject *args)
812 {
813         KX_Scene *kx_scene= gp_KetsjiScene;
814         char *path;
815
816         if (!PyArg_ParseTuple(args,"s:LibFree",&path))
817                 return NULL;
818
819         if (kx_scene->GetSceneConverter()->FreeBlendFile(path))
820         {
821                 Py_RETURN_TRUE;
822         }
823         else {
824                 Py_RETURN_FALSE;
825         }
826 }
827
828 static PyObject *gLibList(PyObject *, PyObject *args)
829 {
830         vector<Main*> &dynMaggie = gp_KetsjiScene->GetSceneConverter()->GetMainDynamic();
831         int i= 0;
832         PyObject *list= PyList_New(dynMaggie.size());
833         
834         for (vector<Main*>::iterator it=dynMaggie.begin(); !(it==dynMaggie.end()); it++)
835         {
836                 PyList_SET_ITEM(list, i++, PyUnicode_FromString( (*it)->name) );
837         }
838         
839         return list;
840 }
841
842 struct PyNextFrameState pynextframestate;
843 static PyObject *gPyNextFrame(PyObject *)
844 {
845         if (pynextframestate.func == NULL) Py_RETURN_NONE;
846         if (pynextframestate.state == NULL) Py_RETURN_NONE; //should never happen; raise exception instead?
847
848         if (pynextframestate.func(pynextframestate.state)) //nonzero = stop
849         { 
850                 Py_RETURN_TRUE;
851         }
852         else // 0 = go on
853         {
854                 Py_RETURN_FALSE;
855         }
856 }
857
858
859 static struct PyMethodDef game_methods[] = {
860         {"expandPath", (PyCFunction)gPyExpandPath, METH_VARARGS, (const char *)gPyExpandPath_doc},
861         {"startGame", (PyCFunction)gPyStartGame, METH_VARARGS, (const char *)gPyStartGame_doc},
862         {"endGame", (PyCFunction)gPyEndGame, METH_NOARGS, (const char *)gPyEndGame_doc},
863         {"restartGame", (PyCFunction)gPyRestartGame, METH_NOARGS, (const char *)gPyRestartGame_doc},
864         {"saveGlobalDict", (PyCFunction)gPySaveGlobalDict, METH_NOARGS, (const char *)gPySaveGlobalDict_doc},
865         {"loadGlobalDict", (PyCFunction)gPyLoadGlobalDict, METH_NOARGS, (const char *)gPyLoadGlobalDict_doc},
866         {"sendMessage", (PyCFunction)gPySendMessage, METH_VARARGS, (const char *)gPySendMessage_doc},
867         {"getCurrentController", (PyCFunction) SCA_PythonController::sPyGetCurrentController, METH_NOARGS, SCA_PythonController::sPyGetCurrentController__doc__},
868         {"getCurrentScene", (PyCFunction) gPyGetCurrentScene, METH_NOARGS, gPyGetCurrentScene_doc},
869         {"getSceneList", (PyCFunction) gPyGetSceneList, METH_NOARGS, (const char *)gPyGetSceneList_doc},
870         {"addScene", (PyCFunction)gPyAddScene, METH_VARARGS, (const char *)gPyAddScene_doc},
871         {"getRandomFloat",(PyCFunction) gPyGetRandomFloat, METH_NOARGS, (const char *)gPyGetRandomFloat_doc},
872         {"setGravity",(PyCFunction) gPySetGravity, METH_O, (const char *)"set Gravitation"},
873         {"getSpectrum",(PyCFunction) gPyGetSpectrum, METH_NOARGS, (const char *)"get audio spectrum"},
874         {"getMaxLogicFrame", (PyCFunction) gPyGetMaxLogicFrame, METH_NOARGS, (const char *)"Gets the max number of logic frame per render frame"},
875         {"setMaxLogicFrame", (PyCFunction) gPySetMaxLogicFrame, METH_VARARGS, (const char *)"Sets the max number of logic frame per render frame"},
876         {"getMaxPhysicsFrame", (PyCFunction) gPyGetMaxPhysicsFrame, METH_NOARGS, (const char *)"Gets the max number of physics frame per render frame"},
877         {"setMaxPhysicsFrame", (PyCFunction) gPySetMaxPhysicsFrame, METH_VARARGS, (const char *)"Sets the max number of physics farme per render frame"},
878         {"getLogicTicRate", (PyCFunction) gPyGetLogicTicRate, METH_NOARGS, (const char *)"Gets the logic tic rate"},
879         {"setLogicTicRate", (PyCFunction) gPySetLogicTicRate, METH_VARARGS, (const char *)"Sets the logic tic rate"},
880         {"getPhysicsTicRate", (PyCFunction) gPyGetPhysicsTicRate, METH_NOARGS, (const char *)"Gets the physics tic rate"},
881         {"setPhysicsTicRate", (PyCFunction) gPySetPhysicsTicRate, METH_VARARGS, (const char *)"Sets the physics tic rate"},
882         {"getExitKey", (PyCFunction) gPyGetExitKey, METH_NOARGS, (const char *)"Gets the key used to exit the game engine"},
883         {"setExitKey", (PyCFunction) gPySetExitKey, METH_VARARGS, (const char *)"Sets the key used to exit the game engine"},
884         {"getAverageFrameRate", (PyCFunction) gPyGetAverageFrameRate, METH_NOARGS, (const char *)"Gets the estimated average frame rate"},
885         {"getBlendFileList", (PyCFunction)gPyGetBlendFileList, METH_VARARGS, (const char *)"Gets a list of blend files in the same directory as the current blend file"},
886         {"PrintGLInfo", (PyCFunction)pyPrintExt, METH_NOARGS, (const char *)"Prints GL Extension Info"},
887         {"PrintMemInfo", (PyCFunction)pyPrintStats, METH_NOARGS, (const char *)"Print engine statistics"},
888         {"NextFrame", (PyCFunction)gPyNextFrame, METH_NOARGS, (const char *)"Render next frame (if Python has control)"},
889         {"getProfileInfo", (PyCFunction)gPyGetProfileInfo, METH_NOARGS, gPyGetProfileInfo_doc},
890         /* library functions */
891         {"LibLoad", (PyCFunction)gLibLoad, METH_VARARGS|METH_KEYWORDS, (const char *)""},
892         {"LibNew", (PyCFunction)gLibNew, METH_VARARGS, (const char *)""},
893         {"LibFree", (PyCFunction)gLibFree, METH_VARARGS, (const char *)""},
894         {"LibList", (PyCFunction)gLibList, METH_VARARGS, (const char *)""},
895         
896         {NULL, (PyCFunction) NULL, 0, NULL }
897 };
898
899 static PyObject *gPyGetWindowHeight(PyObject *, PyObject *args)
900 {
901         return PyLong_FromLong((gp_Canvas ? gp_Canvas->GetHeight() : 0));
902 }
903
904
905
906 static PyObject *gPyGetWindowWidth(PyObject *, PyObject *args)
907 {
908         return PyLong_FromLong((gp_Canvas ? gp_Canvas->GetWidth() : 0));
909 }
910
911
912
913 // temporarility visibility thing, will be moved to rasterizer/renderer later
914 bool gUseVisibilityTemp = false;
915
916 static PyObject *gPyEnableVisibility(PyObject *, PyObject *args)
917 {
918         int visible;
919         if (!PyArg_ParseTuple(args,"i:enableVisibility",&visible))
920                 return NULL;
921         
922         gUseVisibilityTemp = (visible != 0);
923         Py_RETURN_NONE;
924 }
925
926
927
928 static PyObject *gPyShowMouse(PyObject *, PyObject *args)
929 {
930         int visible;
931         if (!PyArg_ParseTuple(args,"i:showMouse",&visible))
932                 return NULL;
933         
934         if (visible)
935         {
936                 if (gp_Canvas)
937                         gp_Canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
938         } else
939         {
940                 if (gp_Canvas)
941                         gp_Canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE);
942         }
943         
944         Py_RETURN_NONE;
945 }
946
947
948
949 static PyObject *gPySetMousePosition(PyObject *, PyObject *args)
950 {
951         int x,y;
952         if (!PyArg_ParseTuple(args,"ii:setMousePosition",&x,&y))
953                 return NULL;
954         
955         if (gp_Canvas)
956                 gp_Canvas->SetMousePosition(x,y);
957         
958         Py_RETURN_NONE;
959 }
960
961 static PyObject *gPySetEyeSeparation(PyObject *, PyObject *args)
962 {
963         float sep;
964         if (!PyArg_ParseTuple(args, "f:setEyeSeparation", &sep))
965                 return NULL;
966
967         if (!gp_Rasterizer) {
968                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setEyeSeparation(float), Rasterizer not available");
969                 return NULL;
970         }
971         
972         gp_Rasterizer->SetEyeSeparation(sep);
973         
974         Py_RETURN_NONE;
975 }
976
977 static PyObject *gPyGetEyeSeparation(PyObject *)
978 {
979         if (!gp_Rasterizer) {
980                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.getEyeSeparation(), Rasterizer not available");
981                 return NULL;
982         }
983         
984         return PyFloat_FromDouble(gp_Rasterizer->GetEyeSeparation());
985 }
986
987 static PyObject *gPySetFocalLength(PyObject *, PyObject *args)
988 {
989         float focus;
990         if (!PyArg_ParseTuple(args, "f:setFocalLength", &focus))
991                 return NULL;
992         
993         if (!gp_Rasterizer) {
994                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setFocalLength(float), Rasterizer not available");
995                 return NULL;
996         }
997
998         gp_Rasterizer->SetFocalLength(focus);
999         
1000         Py_RETURN_NONE;
1001 }
1002
1003 static PyObject *gPyGetFocalLength(PyObject *, PyObject *, PyObject *)
1004 {
1005         if (!gp_Rasterizer) {
1006                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.getFocalLength(), Rasterizer not available");
1007                 return NULL;
1008         }
1009         
1010         return PyFloat_FromDouble(gp_Rasterizer->GetFocalLength());
1011         
1012         Py_RETURN_NONE;
1013 }
1014
1015 static PyObject *gPyGetStereoEye(PyObject *, PyObject *, PyObject *)
1016 {
1017         int flag = RAS_IRasterizer::RAS_STEREO_LEFTEYE;
1018
1019         if (!gp_Rasterizer) {
1020                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.getStereoEye(), Rasterizer not available");
1021                 return NULL;
1022         }
1023
1024         if (gp_Rasterizer->Stereo())
1025                 flag = gp_Rasterizer->GetEye();
1026
1027         return PyLong_FromLong(flag);
1028 }
1029
1030 static PyObject *gPySetBackgroundColor(PyObject *, PyObject *value)
1031 {
1032         MT_Vector4 vec;
1033         if (!PyVecTo(value, vec))
1034                 return NULL;
1035
1036         KX_WorldInfo *wi = gp_KetsjiScene->GetWorldInfo();
1037         if (!wi->hasWorld()) {
1038                 PyErr_SetString(PyExc_RuntimeError, "bge.render.SetBackgroundColor(color), World not available");
1039                 return NULL;
1040         }
1041
1042         wi->setBackColor((float)vec[0], (float)vec[1], (float)vec[2]);
1043
1044         Py_RETURN_NONE;
1045 }
1046
1047 static PyObject *gPySetMistColor(PyObject *, PyObject *value)
1048 {
1049         MT_Vector3 vec;
1050         if (!PyVecTo(value, vec))
1051                 return NULL;
1052
1053         KX_WorldInfo *wi = gp_KetsjiScene->GetWorldInfo();
1054         if (!wi->hasWorld()) {
1055                 PyErr_SetString(PyExc_RuntimeError, "bge.render.setMistColor(color), World not available");
1056                 return NULL;
1057         }
1058
1059         wi->setMistColor((float)vec[0], (float)vec[1], (float)vec[2]);
1060
1061         Py_RETURN_NONE;
1062 }
1063
1064 static PyObject *gPyDisableMist(PyObject *)
1065 {
1066         KX_WorldInfo *wi = gp_KetsjiScene->GetWorldInfo();
1067         if (!wi->hasWorld()) {
1068                 PyErr_SetString(PyExc_RuntimeError, "bge.render.DisableMist(), World not available");
1069                 return NULL;
1070         }
1071         ShowDeprecationWarning("DisableMist()", "setUseMist(false)");
1072         wi->setUseMist(false);
1073
1074         Py_RETURN_NONE;
1075 }
1076
1077 static PyObject *gPySetUseMist(PyObject *, PyObject *args)
1078 {
1079         int enable;
1080         if (!PyArg_ParseTuple(args,"i:setUseMist",&enable))
1081                 return NULL;
1082
1083         KX_WorldInfo *wi = gp_KetsjiScene->GetWorldInfo();
1084         if (!wi->hasWorld()) {
1085                 PyErr_SetString(PyExc_RuntimeError, "bge.render.setUseMist(enable), World not available");
1086                 return NULL;
1087         }
1088
1089         wi->setUseMist(enable);
1090
1091         Py_RETURN_NONE;
1092 }
1093
1094 static PyObject *gPySetMistStart(PyObject *, PyObject *args)
1095 {
1096         float miststart;
1097         if (!PyArg_ParseTuple(args,"f:setMistStart",&miststart))
1098                 return NULL;
1099
1100         KX_WorldInfo *wi = gp_KetsjiScene->GetWorldInfo();
1101         if (!wi->hasWorld()) {
1102                 PyErr_SetString(PyExc_RuntimeError, "bge.render.setMistStart(float), World not available");
1103                 return NULL;
1104         }
1105
1106         wi->setMistStart(miststart);
1107
1108         Py_RETURN_NONE;
1109 }
1110
1111 static PyObject *gPySetMistEnd(PyObject *, PyObject *args)
1112 {
1113         float mistdist;
1114         if (!PyArg_ParseTuple(args,"f:setMistEnd",&mistdist))
1115                 return NULL;
1116
1117         KX_WorldInfo *wi = gp_KetsjiScene->GetWorldInfo();
1118         if (!wi->hasWorld()) {
1119                 PyErr_SetString(PyExc_RuntimeError, "bge.render.setMistEnd(float), World not available");
1120                 return NULL;
1121         }
1122
1123         wi->setMistDistance(mistdist);
1124
1125         Py_RETURN_NONE;
1126 }
1127
1128 static PyObject *gPySetAmbientColor(PyObject *, PyObject *value)
1129 {
1130         MT_Vector3 vec;
1131         if (!PyVecTo(value, vec))
1132                 return NULL;
1133
1134         KX_WorldInfo *wi = gp_KetsjiScene->GetWorldInfo();
1135         if (!wi->hasWorld()) {
1136                 PyErr_SetString(PyExc_RuntimeError, "bge.render.setAmbientColor(color), World not available");
1137                 return NULL;
1138         }
1139
1140         wi->setAmbientColor((float)vec[0], (float)vec[1], (float)vec[2]);
1141
1142         Py_RETURN_NONE;
1143 }
1144
1145 static PyObject *gPyMakeScreenshot(PyObject *, PyObject *args)
1146 {
1147         char* filename;
1148         if (!PyArg_ParseTuple(args,"s:makeScreenshot",&filename))
1149                 return NULL;
1150         
1151         if (gp_Canvas)
1152         {
1153                 gp_Canvas->MakeScreenShot(filename);
1154         }
1155         
1156         Py_RETURN_NONE;
1157 }
1158
1159 static PyObject *gPyEnableMotionBlur(PyObject *, PyObject *args)
1160 {
1161         float motionblurvalue;
1162         if (!PyArg_ParseTuple(args,"f:enableMotionBlur",&motionblurvalue))
1163                 return NULL;
1164         
1165         if (!gp_Rasterizer) {
1166                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.enableMotionBlur(float), Rasterizer not available");
1167                 return NULL;
1168         }
1169         
1170         gp_Rasterizer->EnableMotionBlur(motionblurvalue);
1171         
1172         Py_RETURN_NONE;
1173 }
1174
1175 static PyObject *gPyDisableMotionBlur(PyObject *)
1176 {
1177         if (!gp_Rasterizer) {
1178                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.disableMotionBlur(), Rasterizer not available");
1179                 return NULL;
1180         }
1181         
1182         gp_Rasterizer->DisableMotionBlur();
1183         
1184         Py_RETURN_NONE;
1185 }
1186
1187 static int getGLSLSettingFlag(const char *setting)
1188 {
1189         if (strcmp(setting, "lights") == 0)
1190                 return GAME_GLSL_NO_LIGHTS;
1191         else if (strcmp(setting, "shaders") == 0)
1192                 return GAME_GLSL_NO_SHADERS;
1193         else if (strcmp(setting, "shadows") == 0)
1194                 return GAME_GLSL_NO_SHADOWS;
1195         else if (strcmp(setting, "ramps") == 0)
1196                 return GAME_GLSL_NO_RAMPS;
1197         else if (strcmp(setting, "nodes") == 0)
1198                 return GAME_GLSL_NO_NODES;
1199         else if (strcmp(setting, "extra_textures") == 0)
1200                 return GAME_GLSL_NO_EXTRA_TEX;
1201         else
1202                 return -1;
1203 }
1204
1205 static PyObject *gPySetGLSLMaterialSetting(PyObject *,
1206                                            PyObject *args,
1207                                            PyObject *)
1208 {
1209         GlobalSettings *gs= gp_KetsjiEngine->GetGlobalSettings();
1210         char *setting;
1211         int enable, flag, sceneflag;
1212
1213         if (!PyArg_ParseTuple(args,"si:setGLSLMaterialSetting",&setting,&enable))
1214                 return NULL;
1215         
1216         flag = getGLSLSettingFlag(setting);
1217         
1218         if (flag == -1) {
1219                 PyErr_SetString(PyExc_ValueError, "Rasterizer.setGLSLMaterialSetting(string): glsl setting is not known");
1220                 return NULL;
1221         }
1222
1223         sceneflag= gs->glslflag;
1224         
1225         if (enable)
1226                 gs->glslflag &= ~flag;
1227         else
1228                 gs->glslflag |= flag;
1229
1230         /* temporarily store the glsl settings in the scene for the GLSL materials */
1231         GameData *gm= &(gp_KetsjiScene->GetBlenderScene()->gm);
1232         gm->flag = gs->glslflag;
1233
1234         /* display lists and GLSL materials need to be remade */
1235         if (sceneflag != gs->glslflag) {
1236                 GPU_materials_free();
1237                 if (gp_KetsjiEngine) {
1238                         KX_SceneList *scenes = gp_KetsjiEngine->CurrentScenes();
1239                         KX_SceneList::iterator it;
1240
1241                         for (it=scenes->begin(); it!=scenes->end(); it++)
1242                                 if ((*it)->GetBucketManager()) {
1243                                         (*it)->GetBucketManager()->ReleaseDisplayLists();
1244                                         (*it)->GetBucketManager()->ReleaseMaterials();
1245                                 }
1246                 }
1247         }
1248
1249         Py_RETURN_NONE;
1250 }
1251
1252 static PyObject *gPyGetGLSLMaterialSetting(PyObject *,
1253                                            PyObject *args,
1254                                            PyObject *)
1255 {
1256         GlobalSettings *gs= gp_KetsjiEngine->GetGlobalSettings();
1257         char *setting;
1258         int enabled = 0, flag;
1259
1260         if (!PyArg_ParseTuple(args,"s:getGLSLMaterialSetting",&setting))
1261                 return NULL;
1262         
1263         flag = getGLSLSettingFlag(setting);
1264         
1265         if (flag == -1) {
1266                 PyErr_SetString(PyExc_ValueError, "Rasterizer.getGLSLMaterialSetting(string): glsl setting is not known");
1267                 return NULL;
1268         }
1269
1270         enabled = ((gs->glslflag & flag) != 0);
1271         return PyLong_FromLong(enabled);
1272 }
1273
1274 #define KX_BLENDER_MULTITEX_MATERIAL    1
1275 #define KX_BLENDER_GLSL_MATERIAL                2
1276
1277 static PyObject *gPySetMaterialType(PyObject *,
1278                                     PyObject *args,
1279                                     PyObject *)
1280 {
1281         GlobalSettings *gs= gp_KetsjiEngine->GetGlobalSettings();
1282         int type;
1283
1284         if (!PyArg_ParseTuple(args,"i:setMaterialType",&type))
1285                 return NULL;
1286
1287         if (type == KX_BLENDER_GLSL_MATERIAL)
1288                 gs->matmode= GAME_MAT_GLSL;
1289         else if (type == KX_BLENDER_MULTITEX_MATERIAL)
1290                 gs->matmode= GAME_MAT_MULTITEX;
1291         else {
1292                 PyErr_SetString(PyExc_ValueError, "Rasterizer.setMaterialType(int): material type is not known");
1293                 return NULL;
1294         }
1295
1296         Py_RETURN_NONE;
1297 }
1298
1299 static PyObject *gPyGetMaterialType(PyObject *)
1300 {
1301         GlobalSettings *gs= gp_KetsjiEngine->GetGlobalSettings();
1302         int flag;
1303
1304         if (gs->matmode == GAME_MAT_GLSL)
1305                 flag = KX_BLENDER_GLSL_MATERIAL;
1306         else
1307                 flag = KX_BLENDER_MULTITEX_MATERIAL;
1308         
1309         return PyLong_FromLong(flag);
1310 }
1311
1312 static PyObject *gPySetAnisotropicFiltering(PyObject *, PyObject *args)
1313 {
1314         short level;
1315
1316         if (!PyArg_ParseTuple(args, "h:setAnisotropicFiltering", &level))
1317                 return NULL;
1318
1319         if (level != 1 && level != 2 && level != 4 && level != 8 && level != 16) {
1320                 PyErr_SetString(PyExc_ValueError, "Rasterizer.setAnisotropicFiltering(level): Expected value of 1, 2, 4, 8, or 16 for value");
1321                 return NULL;
1322         }
1323
1324         gp_Rasterizer->SetAnisotropicFiltering(level);
1325
1326         Py_RETURN_NONE;
1327 }
1328
1329 static PyObject *gPyGetAnisotropicFiltering(PyObject *, PyObject *args)
1330 {
1331         return PyLong_FromLong(gp_Rasterizer->GetAnisotropicFiltering());
1332 }
1333
1334 static PyObject *gPyDrawLine(PyObject *, PyObject *args)
1335 {
1336         PyObject *ob_from;
1337         PyObject *ob_to;
1338         PyObject *ob_color;
1339
1340         if (!gp_Rasterizer) {
1341                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.drawLine(obFrom, obTo, color): Rasterizer not available");
1342                 return NULL;
1343         }
1344
1345         if (!PyArg_ParseTuple(args,"OOO:drawLine",&ob_from,&ob_to,&ob_color))
1346                 return NULL;
1347
1348         MT_Vector3 from;
1349         MT_Vector3 to;
1350         MT_Vector3 color;
1351         if (!PyVecTo(ob_from, from))
1352                 return NULL;
1353         if (!PyVecTo(ob_to, to))
1354                 return NULL;
1355         if (!PyVecTo(ob_color, color))
1356                 return NULL;
1357
1358         gp_Rasterizer->DrawDebugLine(from,to,color);
1359         
1360         Py_RETURN_NONE;
1361 }
1362
1363 static PyObject *gPySetWindowSize(PyObject *, PyObject *args)
1364 {
1365         int width, height;
1366         if (!PyArg_ParseTuple(args, "ii:resize", &width, &height))
1367                 return NULL;
1368
1369         gp_Canvas->ResizeWindow(width, height);
1370         Py_RETURN_NONE;
1371 }
1372
1373 static PyObject *gPySetFullScreen(PyObject *, PyObject *value)
1374 {
1375         gp_Canvas->SetFullScreen(PyObject_IsTrue(value));
1376         Py_RETURN_NONE;
1377 }
1378
1379 static PyObject *gPyGetFullScreen(PyObject *)
1380 {
1381         return PyBool_FromLong(gp_Canvas->GetFullScreen());
1382 }
1383
1384 static PyObject *gPySetMipmapping(PyObject *, PyObject *args)
1385 {
1386         int val = 0;
1387
1388         if (!PyArg_ParseTuple(args, "i:setMipmapping", &val))
1389                 return NULL;
1390
1391         if (val < 0 || val > RAS_IRasterizer::RAS_MIPMAP_MAX) {
1392                 PyErr_SetString(PyExc_ValueError, "Rasterizer.setMipmapping(val): invalid mipmaping option");
1393                 return NULL;
1394         }
1395
1396         if (!gp_Rasterizer) {
1397                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setMipmapping(val): Rasterizer not available");
1398                 return NULL;
1399         }
1400
1401         gp_Rasterizer->SetMipmapping((RAS_IRasterizer::MipmapOption)val);
1402         Py_RETURN_NONE;
1403 }
1404
1405 static PyObject *gPyGetMipmapping(PyObject *)
1406 {
1407         if (!gp_Rasterizer) {
1408                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.getMipmapping(): Rasterizer not available");
1409                 return NULL;
1410         }
1411         return PyLong_FromLong(gp_Rasterizer->GetMipmapping());
1412 }
1413
1414 static PyObject *gPySetVsync(PyObject *, PyObject *args)
1415 {
1416         int interval;
1417
1418         if (!PyArg_ParseTuple(args, "i:setVsync", &interval))
1419                 return NULL;
1420
1421         if (interval < 0 || interval > VSYNC_ADAPTIVE) {
1422                 PyErr_SetString(PyExc_ValueError, "Rasterizer.setVsync(value): value must be VSYNC_OFF, VSYNC_ON, or VSYNC_ADAPTIVE");
1423                 return NULL;
1424         }
1425
1426         if (interval == VSYNC_ADAPTIVE)
1427                 interval = -1;
1428         gp_Canvas->SetSwapInterval((interval == VSYNC_ON) ? 1 : 0);
1429         Py_RETURN_NONE;
1430 }
1431
1432 static PyObject *gPyGetVsync(PyObject *)
1433 {
1434         int interval = 0;
1435         gp_Canvas->GetSwapInterval(interval);
1436         return PyLong_FromLong(interval);
1437 }
1438
1439 static PyObject *gPyShowFramerate(PyObject *, PyObject *args)
1440 {
1441         int visible;
1442         if (!PyArg_ParseTuple(args,"i:showFramerate",&visible))
1443                 return NULL;
1444
1445         if (visible && gp_KetsjiEngine)
1446                 gp_KetsjiEngine->SetShowFramerate(true);
1447         else
1448                 gp_KetsjiEngine->SetShowFramerate(false);
1449
1450         Py_RETURN_NONE;
1451 }
1452
1453 static PyObject *gPyShowProfile(PyObject *, PyObject *args)
1454 {
1455         int visible;
1456         if (!PyArg_ParseTuple(args,"i:showProfile",&visible))
1457                 return NULL;
1458
1459         if (visible && gp_KetsjiEngine)
1460                 gp_KetsjiEngine->SetShowProfile(true);
1461         else
1462                 gp_KetsjiEngine->SetShowProfile(false);
1463
1464         Py_RETURN_NONE;
1465 }
1466
1467 static PyObject *gPyShowProperties(PyObject *, PyObject *args)
1468 {
1469         int visible;
1470         if (!PyArg_ParseTuple(args,"i:showProperties",&visible))
1471                 return NULL;
1472
1473         if (visible && gp_KetsjiEngine)
1474                 gp_KetsjiEngine->SetShowProperties(true);
1475         else
1476                 gp_KetsjiEngine->SetShowProperties(false);
1477
1478         Py_RETURN_NONE;
1479 }
1480
1481 static PyObject *gPyAutoDebugList(PyObject *, PyObject *args)
1482 {
1483         int add;
1484         if (!PyArg_ParseTuple(args,"i:autoAddProperties",&add))
1485                 return NULL;
1486
1487         if (add && gp_KetsjiEngine)
1488                 gp_KetsjiEngine->SetAutoAddDebugProperties(true);
1489         else
1490                 gp_KetsjiEngine->SetAutoAddDebugProperties(false);
1491
1492         Py_RETURN_NONE;
1493 }
1494
1495 static PyObject *gPyClearDebugList(PyObject *)
1496 {
1497         if (gp_KetsjiScene)
1498                 gp_KetsjiScene->RemoveAllDebugProperties();
1499
1500         Py_RETURN_NONE;
1501 }
1502
1503 PyDoc_STRVAR(Rasterizer_module_documentation,
1504 "This is the Python API for the game engine of Rasterizer"
1505 );
1506
1507 static struct PyMethodDef rasterizer_methods[] = {
1508         {"getWindowWidth",(PyCFunction) gPyGetWindowWidth,
1509          METH_VARARGS, "getWindowWidth doc"},
1510         {"getWindowHeight",(PyCFunction) gPyGetWindowHeight,
1511          METH_VARARGS, "getWindowHeight doc"},
1512         {"makeScreenshot",(PyCFunction)gPyMakeScreenshot,
1513          METH_VARARGS, "make Screenshot doc"},
1514         {"enableVisibility",(PyCFunction) gPyEnableVisibility,
1515          METH_VARARGS, "enableVisibility doc"},
1516         {"showMouse",(PyCFunction) gPyShowMouse,
1517          METH_VARARGS, "showMouse(bool visible)"},
1518         {"setMousePosition",(PyCFunction) gPySetMousePosition,
1519          METH_VARARGS, "setMousePosition(int x,int y)"},
1520         {"setBackgroundColor",(PyCFunction)gPySetBackgroundColor,METH_O,"set Background Color (rgb)"},
1521         {"setAmbientColor",(PyCFunction)gPySetAmbientColor,METH_O,"set Ambient Color (rgb)"},
1522         {"disableMist",(PyCFunction)gPyDisableMist,METH_NOARGS,"turn off mist"},
1523         {"setUseMist",(PyCFunction)gPySetUseMist,METH_VARARGS,"enable or disable mist"},
1524         {"setMistColor",(PyCFunction)gPySetMistColor,METH_O,"set Mist Color (rgb)"},
1525         {"setMistStart",(PyCFunction)gPySetMistStart,METH_VARARGS,"set Mist Start"},
1526         {"setMistEnd",(PyCFunction)gPySetMistEnd,METH_VARARGS,"set Mist End"},
1527         {"enableMotionBlur",(PyCFunction)gPyEnableMotionBlur,METH_VARARGS,"enable motion blur"},
1528         {"disableMotionBlur",(PyCFunction)gPyDisableMotionBlur,METH_NOARGS,"disable motion blur"},
1529
1530         {"setEyeSeparation", (PyCFunction) gPySetEyeSeparation, METH_VARARGS, "set the eye separation for stereo mode"},
1531         {"getEyeSeparation", (PyCFunction) gPyGetEyeSeparation, METH_NOARGS, "get the eye separation for stereo mode"},
1532         {"setFocalLength", (PyCFunction) gPySetFocalLength, METH_VARARGS, "set the focal length for stereo mode"},
1533         {"getFocalLength", (PyCFunction) gPyGetFocalLength, METH_VARARGS, "get the focal length for stereo mode"},
1534         {"getStereoEye", (PyCFunction) gPyGetStereoEye, METH_VARARGS, "get the current stereoscopy eye being rendered"},
1535         {"setMaterialMode",(PyCFunction) gPySetMaterialType,
1536          METH_VARARGS, "set the material mode to use for OpenGL rendering"},
1537         {"getMaterialMode",(PyCFunction) gPyGetMaterialType,
1538          METH_NOARGS, "get the material mode being used for OpenGL rendering"},
1539         {"setGLSLMaterialSetting",(PyCFunction) gPySetGLSLMaterialSetting,
1540          METH_VARARGS, "set the state of a GLSL material setting"},
1541         {"getGLSLMaterialSetting",(PyCFunction) gPyGetGLSLMaterialSetting,
1542          METH_VARARGS, "get the state of a GLSL material setting"},
1543         {"setAnisotropicFiltering", (PyCFunction) gPySetAnisotropicFiltering,
1544          METH_VARARGS, "set the anisotropic filtering level (must be one of 1, 2, 4, 8, 16)"},
1545         {"getAnisotropicFiltering", (PyCFunction) gPyGetAnisotropicFiltering,
1546          METH_VARARGS, "get the anisotropic filtering level"},
1547         {"drawLine", (PyCFunction) gPyDrawLine,
1548          METH_VARARGS, "draw a line on the screen"},
1549         {"setWindowSize", (PyCFunction) gPySetWindowSize, METH_VARARGS, ""},
1550         {"setFullScreen", (PyCFunction) gPySetFullScreen, METH_O, ""},
1551         {"getFullScreen", (PyCFunction) gPyGetFullScreen, METH_NOARGS, ""},
1552         {"setMipmapping", (PyCFunction) gPySetMipmapping, METH_VARARGS, ""},
1553         {"getMipmapping", (PyCFunction) gPyGetMipmapping, METH_NOARGS, ""},
1554         {"setVsync", (PyCFunction) gPySetVsync, METH_VARARGS, ""},
1555         {"getVsync", (PyCFunction) gPyGetVsync, METH_NOARGS, ""},
1556         {"showFramerate",(PyCFunction) gPyShowFramerate, METH_VARARGS, "show or hide the framerate"},
1557         {"showProfile",(PyCFunction) gPyShowProfile, METH_VARARGS, "show or hide the profile"},
1558         {"showProperties",(PyCFunction) gPyShowProperties, METH_VARARGS, "show or hide the debug properties"},
1559         {"autoDebugList",(PyCFunction) gPyAutoDebugList, METH_VARARGS, "enable or disable auto adding debug properties to the debug  list"},
1560         {"clearDebugList",(PyCFunction) gPyClearDebugList, METH_NOARGS, "clears the debug property list"},
1561         { NULL, (PyCFunction) NULL, 0, NULL }
1562 };
1563
1564
1565
1566 PyDoc_STRVAR(GameLogic_module_documentation,
1567 "This is the Python API for the game engine of bge.logic"
1568 );
1569
1570 static struct PyModuleDef GameLogic_module_def = {
1571         {}, /* m_base */
1572         "GameLogic",  /* m_name */
1573         GameLogic_module_documentation,  /* m_doc */
1574         0,  /* m_size */
1575         game_methods,  /* m_methods */
1576         0,  /* m_reload */
1577         0,  /* m_traverse */
1578         0,  /* m_clear */
1579         0,  /* m_free */
1580 };
1581
1582 PyMODINIT_FUNC initGameLogicPythonBinding()
1583 {
1584         PyObject *m;
1585         PyObject *d;
1586         PyObject *item; /* temp PyObject *storage */
1587
1588         gUseVisibilityTemp=false;
1589
1590         PyObjectPlus::ClearDeprecationWarning(); /* Not that nice to call here but makes sure warnings are reset between loading scenes */
1591
1592         m = PyModule_Create(&GameLogic_module_def);
1593         PyDict_SetItemString(PySys_GetObject("modules"), GameLogic_module_def.m_name, m);
1594
1595
1596         // Add some symbolic constants to the module
1597         d = PyModule_GetDict(m);
1598         
1599         // can be overwritten later for gameEngine instances that can load new blend files and re-initialize this module
1600         // for now its safe to make sure it exists for other areas such as the web plugin
1601         
1602         PyDict_SetItemString(d, "globalDict", item=PyDict_New()); Py_DECREF(item);
1603
1604         // Add keyboard and mouse attributes to this module
1605         MT_assert(!gp_PythonKeyboard);
1606         gp_PythonKeyboard = new SCA_PythonKeyboard(gp_KetsjiEngine->GetKeyboardDevice());
1607         PyDict_SetItemString(d, "keyboard", gp_PythonKeyboard->NewProxy(true));
1608
1609         MT_assert(!gp_PythonMouse);
1610         gp_PythonMouse = new SCA_PythonMouse(gp_KetsjiEngine->GetMouseDevice(), gp_Canvas);
1611         PyDict_SetItemString(d, "mouse", gp_PythonMouse->NewProxy(true));
1612
1613         PyObject* joylist = PyList_New(JOYINDEX_MAX);
1614         for (int i=0; i<JOYINDEX_MAX; ++i) {
1615                 SCA_Joystick *joy = SCA_Joystick::GetInstance(i);
1616                 PyObject *item;
1617
1618                 if (joy && joy->Connected()) {
1619                         gp_PythonJoysticks[i] = new SCA_PythonJoystick(joy);
1620                         item = gp_PythonJoysticks[i]->NewProxy(true);
1621                 }
1622                 else {
1623                         if (joy) {
1624                                 joy->ReleaseInstance();
1625                         }
1626                         item = Py_None;
1627                 }
1628
1629                 Py_INCREF(item);
1630                 PyList_SET_ITEM(joylist, i, item);
1631         }
1632         PyDict_SetItemString(d, "joysticks", joylist);
1633
1634         ErrorObject = PyUnicode_FromString("GameLogic.error");
1635         PyDict_SetItemString(d, "error", ErrorObject);
1636         Py_DECREF(ErrorObject);
1637         
1638         // XXXX Add constants here
1639         /* To use logic bricks, we need some sort of constants. Here, we associate */
1640         /* constants and sumbolic names. Add them to dictionary d.                 */
1641
1642         /* 1. true and false: needed for everyone                                  */
1643         KX_MACRO_addTypesToDict(d, KX_TRUE,  SCA_ILogicBrick::KX_TRUE);
1644         KX_MACRO_addTypesToDict(d, KX_FALSE, SCA_ILogicBrick::KX_FALSE);
1645
1646         /* 2. Property sensor                                                      */
1647         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_EQUAL,      SCA_PropertySensor::KX_PROPSENSOR_EQUAL);
1648         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_NOTEQUAL,   SCA_PropertySensor::KX_PROPSENSOR_NOTEQUAL);
1649         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_INTERVAL,   SCA_PropertySensor::KX_PROPSENSOR_INTERVAL);
1650         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_CHANGED,    SCA_PropertySensor::KX_PROPSENSOR_CHANGED);
1651         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_EXPRESSION, SCA_PropertySensor::KX_PROPSENSOR_EXPRESSION);
1652         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_LESSTHAN,   SCA_PropertySensor::KX_PROPSENSOR_LESSTHAN);
1653         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_GREATERTHAN, SCA_PropertySensor::KX_PROPSENSOR_GREATERTHAN);
1654
1655         /* 3. Constraint actuator                                                  */
1656         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCX);
1657         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCY);
1658         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCZ);
1659         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTX);
1660         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTY);
1661         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTZ);
1662         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPX);
1663         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPY);
1664         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPZ);
1665         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNX);
1666         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNY);
1667         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNZ);
1668         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIX);
1669         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIY);
1670         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIZ);
1671         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHPX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPX);
1672         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHPY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPY);
1673         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHPZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPZ);
1674         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHNX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNX);
1675         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHNY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNY);
1676         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHNZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNZ);
1677         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_NORMAL, KX_ConstraintActuator::KX_ACT_CONSTRAINT_NORMAL);
1678         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_MATERIAL, KX_ConstraintActuator::KX_ACT_CONSTRAINT_MATERIAL);
1679         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_PERMANENT, KX_ConstraintActuator::KX_ACT_CONSTRAINT_PERMANENT);
1680         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DISTANCE, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DISTANCE);
1681         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCAL, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCAL);
1682         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DOROTFH, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DOROTFH);
1683
1684         /* 4. Random distribution types                                            */
1685         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_CONST,      SCA_RandomActuator::KX_RANDOMACT_BOOL_CONST);
1686         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_UNIFORM,    SCA_RandomActuator::KX_RANDOMACT_BOOL_UNIFORM);
1687         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_BERNOUILLI, SCA_RandomActuator::KX_RANDOMACT_BOOL_BERNOUILLI);
1688         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_CONST,       SCA_RandomActuator::KX_RANDOMACT_INT_CONST);
1689         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_UNIFORM,     SCA_RandomActuator::KX_RANDOMACT_INT_UNIFORM);
1690         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_POISSON,     SCA_RandomActuator::KX_RANDOMACT_INT_POISSON);
1691         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_CONST,     SCA_RandomActuator::KX_RANDOMACT_FLOAT_CONST);
1692         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_UNIFORM,   SCA_RandomActuator::KX_RANDOMACT_FLOAT_UNIFORM);
1693         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_NORMAL,    SCA_RandomActuator::KX_RANDOMACT_FLOAT_NORMAL);
1694         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL, SCA_RandomActuator::KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL);
1695
1696         /* 5. Sound actuator                                                      */
1697         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYSTOP,              KX_SoundActuator::KX_SOUNDACT_PLAYSTOP);
1698         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYEND,               KX_SoundActuator::KX_SOUNDACT_PLAYEND);
1699         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPSTOP,              KX_SoundActuator::KX_SOUNDACT_LOOPSTOP);
1700         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPEND,               KX_SoundActuator::KX_SOUNDACT_LOOPEND);
1701         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL,     KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL);
1702         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP,     KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP);
1703
1704         /* 6. Action actuator                                                                                                      */
1705         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_PLAY,        ACT_ACTION_PLAY);
1706         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_PINGPONG,    ACT_ACTION_PINGPONG);
1707         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_FLIPPER,     ACT_ACTION_FLIPPER);
1708         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_LOOPSTOP,    ACT_ACTION_LOOP_STOP);
1709         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_LOOPEND,     ACT_ACTION_LOOP_END);
1710         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_PROPERTY,    ACT_ACTION_FROM_PROP);
1711         
1712         /* 7. GL_BlendFunc */
1713         KX_MACRO_addTypesToDict(d, BL_ZERO, GL_ZERO);
1714         KX_MACRO_addTypesToDict(d, BL_ONE, GL_ONE);
1715         KX_MACRO_addTypesToDict(d, BL_SRC_COLOR, GL_SRC_COLOR);
1716         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR);
1717         KX_MACRO_addTypesToDict(d, BL_DST_COLOR, GL_DST_COLOR);
1718         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_DST_COLOR);
1719         KX_MACRO_addTypesToDict(d, BL_SRC_ALPHA, GL_SRC_ALPHA);
1720         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1721         KX_MACRO_addTypesToDict(d, BL_DST_ALPHA, GL_DST_ALPHA);
1722         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA);
1723         KX_MACRO_addTypesToDict(d, BL_SRC_ALPHA_SATURATE, GL_SRC_ALPHA_SATURATE);
1724
1725
1726         /* 8. UniformTypes */
1727         KX_MACRO_addTypesToDict(d, SHD_TANGENT, BL_Shader::SHD_TANGENT);
1728         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX, BL_Shader::MODELVIEWMATRIX);
1729         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_TRANSPOSE, BL_Shader::MODELVIEWMATRIX_TRANSPOSE);
1730         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_INVERSE, BL_Shader::MODELVIEWMATRIX_INVERSE);
1731         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_INVERSETRANSPOSE, BL_Shader::MODELVIEWMATRIX_INVERSETRANSPOSE);
1732         KX_MACRO_addTypesToDict(d, MODELMATRIX, BL_Shader::MODELMATRIX);
1733         KX_MACRO_addTypesToDict(d, MODELMATRIX_TRANSPOSE, BL_Shader::MODELMATRIX_TRANSPOSE);
1734         KX_MACRO_addTypesToDict(d, MODELMATRIX_INVERSE, BL_Shader::MODELMATRIX_INVERSE);
1735         KX_MACRO_addTypesToDict(d, MODELMATRIX_INVERSETRANSPOSE, BL_Shader::MODELMATRIX_INVERSETRANSPOSE);
1736         KX_MACRO_addTypesToDict(d, VIEWMATRIX, BL_Shader::VIEWMATRIX);
1737         KX_MACRO_addTypesToDict(d, VIEWMATRIX_TRANSPOSE, BL_Shader::VIEWMATRIX_TRANSPOSE);
1738         KX_MACRO_addTypesToDict(d, VIEWMATRIX_INVERSE, BL_Shader::VIEWMATRIX_INVERSE);
1739         KX_MACRO_addTypesToDict(d, VIEWMATRIX_INVERSETRANSPOSE, BL_Shader::VIEWMATRIX_INVERSETRANSPOSE);
1740         KX_MACRO_addTypesToDict(d, CAM_POS, BL_Shader::CAM_POS);
1741         KX_MACRO_addTypesToDict(d, CONSTANT_TIMER, BL_Shader::CONSTANT_TIMER);
1742
1743         /* 9. state actuator */
1744         KX_MACRO_addTypesToDict(d, KX_STATE1, (1<<0));
1745         KX_MACRO_addTypesToDict(d, KX_STATE2, (1<<1));
1746         KX_MACRO_addTypesToDict(d, KX_STATE3, (1<<2));
1747         KX_MACRO_addTypesToDict(d, KX_STATE4, (1<<3));
1748         KX_MACRO_addTypesToDict(d, KX_STATE5, (1<<4));
1749         KX_MACRO_addTypesToDict(d, KX_STATE6, (1<<5));
1750         KX_MACRO_addTypesToDict(d, KX_STATE7, (1<<6));
1751         KX_MACRO_addTypesToDict(d, KX_STATE8, (1<<7));
1752         KX_MACRO_addTypesToDict(d, KX_STATE9, (1<<8));
1753         KX_MACRO_addTypesToDict(d, KX_STATE10, (1<<9));
1754         KX_MACRO_addTypesToDict(d, KX_STATE11, (1<<10));
1755         KX_MACRO_addTypesToDict(d, KX_STATE12, (1<<11));
1756         KX_MACRO_addTypesToDict(d, KX_STATE13, (1<<12));
1757         KX_MACRO_addTypesToDict(d, KX_STATE14, (1<<13));
1758         KX_MACRO_addTypesToDict(d, KX_STATE15, (1<<14));
1759         KX_MACRO_addTypesToDict(d, KX_STATE16, (1<<15));
1760         KX_MACRO_addTypesToDict(d, KX_STATE17, (1<<16));
1761         KX_MACRO_addTypesToDict(d, KX_STATE18, (1<<17));
1762         KX_MACRO_addTypesToDict(d, KX_STATE19, (1<<18));
1763         KX_MACRO_addTypesToDict(d, KX_STATE20, (1<<19));
1764         KX_MACRO_addTypesToDict(d, KX_STATE21, (1<<20));
1765         KX_MACRO_addTypesToDict(d, KX_STATE22, (1<<21));
1766         KX_MACRO_addTypesToDict(d, KX_STATE23, (1<<22));
1767         KX_MACRO_addTypesToDict(d, KX_STATE24, (1<<23));
1768         KX_MACRO_addTypesToDict(d, KX_STATE25, (1<<24));
1769         KX_MACRO_addTypesToDict(d, KX_STATE26, (1<<25));
1770         KX_MACRO_addTypesToDict(d, KX_STATE27, (1<<26));
1771         KX_MACRO_addTypesToDict(d, KX_STATE28, (1<<27));
1772         KX_MACRO_addTypesToDict(d, KX_STATE29, (1<<28));
1773         KX_MACRO_addTypesToDict(d, KX_STATE30, (1<<29));
1774         
1775         /* All Sensors */
1776         KX_MACRO_addTypesToDict(d, KX_SENSOR_JUST_ACTIVATED, SCA_ISensor::KX_SENSOR_JUST_ACTIVATED);
1777         KX_MACRO_addTypesToDict(d, KX_SENSOR_ACTIVE, SCA_ISensor::KX_SENSOR_ACTIVE);
1778         KX_MACRO_addTypesToDict(d, KX_SENSOR_JUST_DEACTIVATED, SCA_ISensor::KX_SENSOR_JUST_DEACTIVATED);
1779         KX_MACRO_addTypesToDict(d, KX_SENSOR_INACTIVE, SCA_ISensor::KX_SENSOR_INACTIVE);
1780         
1781         /* Radar Sensor */
1782         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_POS_X, KX_RadarSensor::KX_RADAR_AXIS_POS_X);
1783         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_POS_Y, KX_RadarSensor::KX_RADAR_AXIS_POS_Y);
1784         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_POS_Z, KX_RadarSensor::KX_RADAR_AXIS_POS_Z);
1785         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_NEG_X, KX_RadarSensor::KX_RADAR_AXIS_NEG_X);
1786         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_NEG_Y, KX_RadarSensor::KX_RADAR_AXIS_NEG_Y);
1787         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_NEG_Z, KX_RadarSensor::KX_RADAR_AXIS_NEG_Z);
1788
1789         /* Ray Sensor */
1790         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_POS_X, KX_RaySensor::KX_RAY_AXIS_POS_X);
1791         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_POS_Y, KX_RaySensor::KX_RAY_AXIS_POS_Y);
1792         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_POS_Z, KX_RaySensor::KX_RAY_AXIS_POS_Z);
1793         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_NEG_X, KX_RaySensor::KX_RAY_AXIS_NEG_X);
1794         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_NEG_Y, KX_RaySensor::KX_RAY_AXIS_NEG_Y);
1795         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_NEG_Z, KX_RaySensor::KX_RAY_AXIS_NEG_Z);
1796
1797         /* TrackTo Actuator */
1798         KX_MACRO_addTypesToDict(d, KX_TRACK_UPAXIS_POS_X, KX_TrackToActuator::KX_TRACK_UPAXIS_POS_X);
1799         KX_MACRO_addTypesToDict(d, KX_TRACK_UPAXIS_POS_Y, KX_TrackToActuator::KX_TRACK_UPAXIS_POS_Y);
1800         KX_MACRO_addTypesToDict(d, KX_TRACK_UPAXIS_POS_Z, KX_TrackToActuator::KX_TRACK_UPAXIS_POS_Z);
1801         KX_MACRO_addTypesToDict(d, KX_TRACK_TRAXIS_POS_X, KX_TrackToActuator::KX_TRACK_TRAXIS_POS_X);
1802         KX_MACRO_addTypesToDict(d, KX_TRACK_TRAXIS_POS_Y, KX_TrackToActuator::KX_TRACK_TRAXIS_POS_Y);
1803         KX_MACRO_addTypesToDict(d, KX_TRACK_TRAXIS_POS_Z, KX_TrackToActuator::KX_TRACK_TRAXIS_POS_Z);
1804         KX_MACRO_addTypesToDict(d, KX_TRACK_TRAXIS_NEG_X, KX_TrackToActuator::KX_TRACK_TRAXIS_NEG_X);
1805         KX_MACRO_addTypesToDict(d, KX_TRACK_TRAXIS_NEG_Y, KX_TrackToActuator::KX_TRACK_TRAXIS_NEG_Y);
1806         KX_MACRO_addTypesToDict(d, KX_TRACK_TRAXIS_NEG_Z, KX_TrackToActuator::KX_TRACK_TRAXIS_NEG_Z);
1807
1808         /* Dynamic actuator */
1809         KX_MACRO_addTypesToDict(d, KX_DYN_RESTORE_DYNAMICS, KX_SCA_DynamicActuator::KX_DYN_RESTORE_DYNAMICS);
1810         KX_MACRO_addTypesToDict(d, KX_DYN_DISABLE_DYNAMICS, KX_SCA_DynamicActuator::KX_DYN_DISABLE_DYNAMICS);
1811         KX_MACRO_addTypesToDict(d, KX_DYN_ENABLE_RIGID_BODY, KX_SCA_DynamicActuator::KX_DYN_ENABLE_RIGID_BODY);
1812         KX_MACRO_addTypesToDict(d, KX_DYN_DISABLE_RIGID_BODY, KX_SCA_DynamicActuator::KX_DYN_DISABLE_RIGID_BODY);
1813         KX_MACRO_addTypesToDict(d, KX_DYN_SET_MASS, KX_SCA_DynamicActuator::KX_DYN_SET_MASS);
1814
1815         /* Input & Mouse Sensor */
1816         KX_MACRO_addTypesToDict(d, KX_INPUT_NONE, SCA_InputEvent::KX_NO_INPUTSTATUS);
1817         KX_MACRO_addTypesToDict(d, KX_INPUT_JUST_ACTIVATED, SCA_InputEvent::KX_JUSTACTIVATED);
1818         KX_MACRO_addTypesToDict(d, KX_INPUT_ACTIVE, SCA_InputEvent::KX_ACTIVE);
1819         KX_MACRO_addTypesToDict(d, KX_INPUT_JUST_RELEASED, SCA_InputEvent::KX_JUSTRELEASED);
1820         
1821         KX_MACRO_addTypesToDict(d, KX_MOUSE_BUT_LEFT, SCA_IInputDevice::KX_LEFTMOUSE);
1822         KX_MACRO_addTypesToDict(d, KX_MOUSE_BUT_MIDDLE, SCA_IInputDevice::KX_MIDDLEMOUSE);
1823         KX_MACRO_addTypesToDict(d, KX_MOUSE_BUT_RIGHT, SCA_IInputDevice::KX_RIGHTMOUSE);
1824
1825         /* 2D Filter Actuator */
1826         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_ENABLED, RAS_2DFilterManager::RAS_2DFILTER_ENABLED);
1827         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_DISABLED, RAS_2DFilterManager::RAS_2DFILTER_DISABLED);
1828         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_NOFILTER, RAS_2DFilterManager::RAS_2DFILTER_NOFILTER);
1829         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_MOTIONBLUR, RAS_2DFilterManager::RAS_2DFILTER_MOTIONBLUR);
1830         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_BLUR, RAS_2DFilterManager::RAS_2DFILTER_BLUR);
1831         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_SHARPEN, RAS_2DFilterManager::RAS_2DFILTER_SHARPEN);
1832         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_DILATION, RAS_2DFilterManager::RAS_2DFILTER_DILATION);
1833         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_EROSION, RAS_2DFilterManager::RAS_2DFILTER_EROSION);
1834         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_LAPLACIAN, RAS_2DFilterManager::RAS_2DFILTER_LAPLACIAN);
1835         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_SOBEL, RAS_2DFilterManager::RAS_2DFILTER_SOBEL);
1836         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_PREWITT, RAS_2DFilterManager::RAS_2DFILTER_PREWITT);
1837         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_GRAYSCALE, RAS_2DFilterManager::RAS_2DFILTER_GRAYSCALE);
1838         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_SEPIA, RAS_2DFilterManager::RAS_2DFILTER_SEPIA);
1839         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_INVERT, RAS_2DFilterManager::RAS_2DFILTER_INVERT);
1840         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_CUSTOMFILTER, RAS_2DFilterManager::RAS_2DFILTER_CUSTOMFILTER);
1841
1842         /* Sound Actuator */
1843         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYSTOP, KX_SoundActuator::KX_SOUNDACT_PLAYSTOP);
1844         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYEND, KX_SoundActuator::KX_SOUNDACT_PLAYEND);
1845         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPSTOP, KX_SoundActuator::KX_SOUNDACT_LOOPSTOP);
1846         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPEND, KX_SoundActuator:: KX_SOUNDACT_LOOPEND);
1847         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL, KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL);
1848         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP, KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP);
1849
1850         /* State Actuator */
1851         KX_MACRO_addTypesToDict(d, KX_STATE_OP_CPY, KX_StateActuator::OP_CPY);
1852         KX_MACRO_addTypesToDict(d, KX_STATE_OP_SET, KX_StateActuator::OP_SET);
1853         KX_MACRO_addTypesToDict(d, KX_STATE_OP_CLR, KX_StateActuator::OP_CLR);
1854         KX_MACRO_addTypesToDict(d, KX_STATE_OP_NEG, KX_StateActuator::OP_NEG);
1855
1856         /* Game Actuator Modes */
1857         KX_MACRO_addTypesToDict(d, KX_GAME_LOAD, KX_GameActuator::KX_GAME_LOAD);
1858         KX_MACRO_addTypesToDict(d, KX_GAME_START, KX_GameActuator::KX_GAME_START);
1859         KX_MACRO_addTypesToDict(d, KX_GAME_RESTART, KX_GameActuator::KX_GAME_RESTART);
1860         KX_MACRO_addTypesToDict(d, KX_GAME_QUIT, KX_GameActuator::KX_GAME_QUIT);
1861         KX_MACRO_addTypesToDict(d, KX_GAME_SAVECFG, KX_GameActuator::KX_GAME_SAVECFG);
1862         KX_MACRO_addTypesToDict(d, KX_GAME_LOADCFG, KX_GameActuator::KX_GAME_LOADCFG);
1863
1864         /* Scene Actuator Modes */
1865         KX_MACRO_addTypesToDict(d, KX_SCENE_RESTART, KX_SceneActuator::KX_SCENE_RESTART);
1866         KX_MACRO_addTypesToDict(d, KX_SCENE_SET_SCENE, KX_SceneActuator::KX_SCENE_SET_SCENE);
1867         KX_MACRO_addTypesToDict(d, KX_SCENE_SET_CAMERA, KX_SceneActuator::KX_SCENE_SET_CAMERA);
1868         KX_MACRO_addTypesToDict(d, KX_SCENE_ADD_FRONT_SCENE, KX_SceneActuator::KX_SCENE_ADD_FRONT_SCENE);
1869         KX_MACRO_addTypesToDict(d, KX_SCENE_ADD_BACK_SCENE, KX_SceneActuator::KX_SCENE_ADD_BACK_SCENE);
1870         KX_MACRO_addTypesToDict(d, KX_SCENE_REMOVE_SCENE, KX_SceneActuator::KX_SCENE_REMOVE_SCENE);
1871         KX_MACRO_addTypesToDict(d, KX_SCENE_SUSPEND, KX_SceneActuator::KX_SCENE_SUSPEND);
1872         KX_MACRO_addTypesToDict(d, KX_SCENE_RESUME, KX_SceneActuator::KX_SCENE_RESUME);
1873
1874         /* Parent Actuator Modes */
1875         KX_MACRO_addTypesToDict(d, KX_PARENT_SET, KX_ParentActuator::KX_PARENT_SET);
1876         KX_MACRO_addTypesToDict(d, KX_PARENT_REMOVE, KX_ParentActuator::KX_PARENT_REMOVE);
1877
1878         /* BL_ArmatureConstraint type */
1879         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_TRACKTO, CONSTRAINT_TYPE_TRACKTO);
1880         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_KINEMATIC, CONSTRAINT_TYPE_KINEMATIC);
1881         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_ROTLIKE, CONSTRAINT_TYPE_ROTLIKE);
1882         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_LOCLIKE, CONSTRAINT_TYPE_LOCLIKE);
1883         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_MINMAX, CONSTRAINT_TYPE_MINMAX);
1884         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_SIZELIKE, CONSTRAINT_TYPE_SIZELIKE);
1885         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_LOCKTRACK, CONSTRAINT_TYPE_LOCKTRACK);
1886         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_STRETCHTO, CONSTRAINT_TYPE_STRETCHTO);
1887         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_CLAMPTO, CONSTRAINT_TYPE_CLAMPTO);
1888         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_TRANSFORM, CONSTRAINT_TYPE_TRANSFORM);
1889         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_DISTLIMIT, CONSTRAINT_TYPE_DISTLIMIT);
1890         /* BL_ArmatureConstraint ik_type */
1891         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_COPYPOSE, CONSTRAINT_IK_COPYPOSE);
1892         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_DISTANCE, CONSTRAINT_IK_DISTANCE);
1893         /* BL_ArmatureConstraint ik_mode */
1894         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_MODE_INSIDE, LIMITDIST_INSIDE);
1895         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_MODE_OUTSIDE, LIMITDIST_OUTSIDE);
1896         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_MODE_ONSURFACE, LIMITDIST_ONSURFACE);
1897         /* BL_ArmatureConstraint ik_flag */
1898         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_FLAG_TIP, CONSTRAINT_IK_TIP);
1899         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_FLAG_ROT, CONSTRAINT_IK_ROT);
1900         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_FLAG_STRETCH, CONSTRAINT_IK_STRETCH);
1901         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_FLAG_POS, CONSTRAINT_IK_POS);
1902         /* KX_ArmatureSensor type */
1903         KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_STATE_CHANGED, SENS_ARM_STATE_CHANGED);
1904         KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_LIN_ERROR_BELOW, SENS_ARM_LIN_ERROR_BELOW);
1905         KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_LIN_ERROR_ABOVE, SENS_ARM_LIN_ERROR_ABOVE);
1906         KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_ROT_ERROR_BELOW, SENS_ARM_ROT_ERROR_BELOW);
1907         KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_ROT_ERROR_ABOVE, SENS_ARM_ROT_ERROR_ABOVE);
1908
1909         /* BL_ArmatureActuator type */
1910         KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_RUN, ACT_ARM_RUN);
1911         KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_ENABLE, ACT_ARM_ENABLE);
1912         KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_DISABLE, ACT_ARM_DISABLE);
1913         KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_SETTARGET, ACT_ARM_SETTARGET);
1914         KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_SETWEIGHT, ACT_ARM_SETWEIGHT);
1915         KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_SETINFLUENCE, ACT_ARM_SETINFLUENCE);
1916
1917         /* BL_Armature Channel rotation_mode */
1918         KX_MACRO_addTypesToDict(d, ROT_MODE_QUAT, ROT_MODE_QUAT);
1919         KX_MACRO_addTypesToDict(d, ROT_MODE_XYZ, ROT_MODE_XYZ);
1920         KX_MACRO_addTypesToDict(d, ROT_MODE_XZY, ROT_MODE_XZY);
1921         KX_MACRO_addTypesToDict(d, ROT_MODE_YXZ, ROT_MODE_YXZ);
1922         KX_MACRO_addTypesToDict(d, ROT_MODE_YZX, ROT_MODE_YZX);
1923         KX_MACRO_addTypesToDict(d, ROT_MODE_ZXY, ROT_MODE_ZXY);
1924         KX_MACRO_addTypesToDict(d, ROT_MODE_ZYX, ROT_MODE_ZYX);
1925
1926         /* Steering actuator */
1927         KX_MACRO_addTypesToDict(d, KX_STEERING_SEEK, KX_SteeringActuator::KX_STEERING_SEEK);
1928         KX_MACRO_addTypesToDict(d, KX_STEERING_FLEE, KX_SteeringActuator::KX_STEERING_FLEE);
1929         KX_MACRO_addTypesToDict(d, KX_STEERING_PATHFOLLOWING, KX_SteeringActuator::KX_STEERING_PATHFOLLOWING);
1930
1931         /* KX_NavMeshObject render mode */
1932         KX_MACRO_addTypesToDict(d, RM_WALLS, KX_NavMeshObject::RM_WALLS);
1933         KX_MACRO_addTypesToDict(d, RM_POLYS, KX_NavMeshObject::RM_POLYS);
1934         KX_MACRO_addTypesToDict(d, RM_TRIS, KX_NavMeshObject::RM_TRIS);
1935
1936         /* BL_Action play modes */
1937         KX_MACRO_addTypesToDict(d, KX_ACTION_MODE_PLAY, BL_Action::ACT_MODE_PLAY);
1938         KX_MACRO_addTypesToDict(d, KX_ACTION_MODE_LOOP, BL_Action::ACT_MODE_LOOP);
1939         KX_MACRO_addTypesToDict(d, KX_ACTION_MODE_PING_PONG, BL_Action::ACT_MODE_PING_PONG);
1940
1941         /* BL_Action blend modes */
1942         KX_MACRO_addTypesToDict(d, KX_ACTION_BLEND_BLEND, BL_Action::ACT_BLEND_BLEND);
1943         KX_MACRO_addTypesToDict(d, KX_ACTION_BLEND_ADD, BL_Action::ACT_BLEND_ADD);
1944
1945         /* Mouse Actuator object axis*/
1946         KX_MACRO_addTypesToDict(d, KX_ACT_MOUSE_OBJECT_AXIS_X, KX_MouseActuator::KX_ACT_MOUSE_OBJECT_AXIS_X);
1947         KX_MACRO_addTypesToDict(d, KX_ACT_MOUSE_OBJECT_AXIS_Y, KX_MouseActuator::KX_ACT_MOUSE_OBJECT_AXIS_Y);
1948         KX_MACRO_addTypesToDict(d, KX_ACT_MOUSE_OBJECT_AXIS_Z, KX_MouseActuator::KX_ACT_MOUSE_OBJECT_AXIS_Z);
1949
1950
1951         // Check for errors
1952         if (PyErr_Occurred())
1953         {
1954                 Py_FatalError("can't initialize module bge.logic");
1955         }
1956
1957         return m;
1958 }
1959
1960 /* Explanation of 
1961  * 
1962  * - backupPySysObjects()               : stores sys.path in gp_OrigPythonSysPath
1963  * - initPySysObjects(main)     : initializes the blendfile and library paths
1964  * - restorePySysObjects()              : restores sys.path from gp_OrigPythonSysPath
1965  * 
1966  * These exist so the current blend dir "//" can always be used to import modules from.
1967  * the reason we need a few functions for this is that python is not only used by the game engine
1968  * so we cant just add to sys.path all the time, it would leave pythons state in a mess.
1969  * It would also be incorrect since loading blend files for new levels etc would always add to sys.path
1970  * 
1971  * To play nice with blenders python, the sys.path is backed up and the current blendfile along
1972  * with all its lib paths are added to the sys path.
1973  * When loading a new blendfile, the original sys.path is restored and the new paths are added over the top.
1974  */
1975
1976 /**
1977  * So we can have external modules mixed with our blend files.
1978  */
1979 static void backupPySysObjects(void)
1980 {
1981         PyObject *sys_path= PySys_GetObject("path"); /* should never fail */
1982         PyObject *sys_mods= PySys_GetObject("modules"); /* should never fail */
1983         
1984         /* paths */
1985         Py_XDECREF(gp_OrigPythonSysPath); /* just in case its set */
1986         gp_OrigPythonSysPath = PyList_GetSlice(sys_path, 0, INT_MAX); /* copy the list */
1987         
1988         /* modules */
1989         Py_XDECREF(gp_OrigPythonSysModules); /* just in case its set */
1990         gp_OrigPythonSysModules = PyDict_Copy(sys_mods); /* copy the list */
1991         
1992 }
1993
1994 /* for initPySysObjects only,
1995  * takes a blend path and adds a scripts dir from it
1996  *
1997  * "/home/me/foo.blend" -> "/home/me/scripts"
1998  */
1999 static void initPySysObjects__append(PyObject *sys_path, const char *filename)
2000 {
2001         PyObject *item;
2002         char expanded[FILE_MAX];
2003         
2004         BLI_split_dir_part(filename, expanded, sizeof(expanded)); /* get the dir part of filename only */
2005         BLI_path_abs(expanded, gp_GamePythonPath); /* filename from lib->filename is (always?) absolute, so this may not be needed but it wont hurt */
2006         BLI_cleanup_file(gp_GamePythonPath, expanded); /* Don't use BLI_cleanup_dir because it adds a slash - BREAKS WIN32 ONLY */
2007         item = PyC_UnicodeFromByte(expanded);
2008         
2009 //      printf("SysPath - '%s', '%s', '%s'\n", expanded, filename, gp_GamePythonPath);
2010         
2011         if (PySequence_Index(sys_path, item) == -1) {
2012                 PyErr_Clear(); /* PySequence_Index sets a ValueError */
2013                 PyList_Insert(sys_path, 0, item);
2014         }
2015         
2016         Py_DECREF(item);
2017 }
2018 static void initPySysObjects(Main *maggie)
2019 {
2020         PyObject *sys_path= PySys_GetObject("path"); /* should never fail */
2021         
2022         if (gp_OrigPythonSysPath==NULL) {
2023                 /* backup */
2024                 backupPySysObjects();
2025         }
2026         else {
2027                 /* get the original sys path when the BGE started */
2028                 PyList_SetSlice(sys_path, 0, INT_MAX, gp_OrigPythonSysPath);
2029         }
2030         
2031         Library *lib= (Library *)maggie->library.first;
2032         
2033         while (lib) {
2034                 /* lib->name wont work in some cases (on win32),
2035                  * even when expanding with gp_GamePythonPath, using lib->filename is less trouble */
2036                 initPySysObjects__append(sys_path, lib->filepath);
2037                 lib= (Library *)lib->id.next;
2038         }
2039         
2040         initPySysObjects__append(sys_path, gp_GamePythonPath);
2041         
2042 //      fprintf(stderr, "\nNew Path: %d ", PyList_GET_SIZE(sys_path));
2043 //      PyObject_Print(sys_path, stderr, 0);
2044 }
2045
2046 static void restorePySysObjects(void)
2047 {
2048         if (gp_OrigPythonSysPath==NULL)
2049                 return;
2050         
2051         PyObject *sys_path= PySys_GetObject("path"); /* should never fail */
2052         PyObject *sys_mods= PySys_GetObject("modules"); /* should never fail */
2053
2054         /* paths */
2055         PyList_SetSlice(sys_path, 0, INT_MAX, gp_OrigPythonSysPath);
2056         Py_DECREF(gp_OrigPythonSysPath);
2057         gp_OrigPythonSysPath= NULL;
2058         
2059         /* modules */
2060         PyDict_Clear(sys_mods);
2061         PyDict_Update(sys_mods, gp_OrigPythonSysModules);
2062         Py_DECREF(gp_OrigPythonSysModules);
2063         gp_OrigPythonSysModules= NULL;
2064         
2065         
2066 //      fprintf(stderr, "\nRestore Path: %d ", PyList_GET_SIZE(sys_path));
2067 //      PyObject_Print(sys_path, stderr, 0);
2068 }
2069
2070 void addImportMain(struct Main *maggie)
2071 {
2072         bpy_import_main_extra_add(maggie);
2073 }
2074
2075 void removeImportMain(struct Main *maggie)
2076 {
2077         bpy_import_main_extra_remove(maggie);
2078 }
2079
2080
2081 PyDoc_STRVAR(BGE_module_documentation,
2082         "This module contains submodules for the Blender Game Engine.\n"
2083 );
2084
2085 static struct PyModuleDef BGE_module_def = {
2086         PyModuleDef_HEAD_INIT,
2087         "bge",  /* m_name */
2088         BGE_module_documentation,  /* m_doc */
2089         0,  /* m_size */
2090         NULL,  /* m_methods */
2091         NULL,  /* m_reload */
2092         NULL,  /* m_traverse */
2093         NULL,  /* m_clear */
2094         NULL,  /* m_free */
2095 };
2096
2097 PyMODINIT_FUNC initBGE(void)
2098 {
2099         PyObject *mod;
2100         PyObject *submodule;
2101         PyObject *sys_modules = PyThreadState_GET()->interp->modules;
2102
2103         mod = PyModule_Create(&BGE_module_def);
2104
2105         PyModule_AddObject(mod, "constraints", (submodule = initConstraintPythonBinding()));
2106         PyDict_SetItemString(sys_modules, PyModule_GetName(submodule), submodule);
2107         Py_INCREF(submodule);
2108
2109         PyModule_AddObject(mod, "events", (submodule = initGameKeysPythonBinding()));
2110         PyDict_SetItemString(sys_modules, PyModule_GetName(submodule), submodule);
2111         Py_INCREF(submodule);
2112
2113         PyModule_AddObject(mod, "logic", (submodule = initGameLogicPythonBinding()));
2114         PyDict_SetItemString(sys_modules, PyModule_GetName(submodule), submodule);
2115         Py_INCREF(submodule);
2116
2117         PyModule_AddObject(mod, "render", (submodule = initRasterizerPythonBinding()));
2118         PyDict_SetItemString(sys_modules, PyModule_GetName(submodule), submodule);
2119         Py_INCREF(submodule);
2120
2121         PyModule_AddObject(mod, "texture", (submodule = initVideoTexturePythonBinding()));
2122         PyDict_SetItemString(sys_modules, PyModule_GetName(submodule), submodule);
2123         Py_INCREF(submodule);
2124
2125         PyModule_AddObject(mod, "types", (submodule = initGameTypesPythonBinding()));
2126         PyDict_SetItemString(sys_modules, PyModule_GetName(submodule), submodule);
2127         Py_INCREF(submodule);
2128
2129         return mod;
2130 }
2131
2132
2133 /* minimal required blender modules to run blenderplayer */
2134 static struct _inittab bge_internal_modules[] = {
2135         {"mathutils", PyInit_mathutils},
2136         {"bgl", BPyInit_bgl},
2137         {"blf", BPyInit_blf},
2138         {"aud", AUD_initPython},
2139         {NULL, NULL}
2140 };
2141
2142 /**
2143  * Python is not initialized.
2144  * see bpy_interface.c's BPY_python_start() which shares the same functionality in blender.
2145  */
2146 PyObject *initGamePlayerPythonScripting(Main *maggie, int argc, char** argv)
2147 {
2148         /* Yet another gotcha in the py api
2149          * Cant run PySys_SetArgv more than once because this adds the
2150          * binary dir to the sys.path each time.
2151          * Id have thought python being totally restarted would make this ok but
2152          * somehow it remembers the sys.path - Campbell
2153          */
2154         static bool first_time = true;
2155         const char * const py_path_bundle = BKE_appdir_folder_id(BLENDER_SYSTEM_PYTHON, NULL);
2156
2157         /* not essential but nice to set our name */
2158         static wchar_t program_path_wchar[FILE_MAX]; /* python holds a reference */
2159         BLI_strncpy_wchar_from_utf8(program_path_wchar, BKE_appdir_program_path(), ARRAY_SIZE(program_path_wchar));
2160         Py_SetProgramName(program_path_wchar);
2161
2162         /* Update, Py3.3 resolves attempting to parse non-existing header */
2163         #if 0
2164         /* Python 3.2 now looks for '2.xx/python/include/python3.2d/pyconfig.h' to
2165          * parse from the 'sysconfig' module which is used by 'site',
2166          * so for now disable site. alternatively we could copy the file. */
2167         if (py_path_bundle != NULL) {
2168                 Py_NoSiteFlag = 1; /* inhibits the automatic importing of 'site' */
2169         }
2170         #endif
2171
2172         Py_FrozenFlag = 1;
2173
2174         /* must run before python initializes */
2175         PyImport_ExtendInittab(bge_internal_modules);
2176
2177         /* find local python installation */
2178         PyC_SetHomePath(py_path_bundle);
2179
2180         Py_Initialize();
2181         
2182         if (argv && first_time) { /* browser plugins don't currently set this */
2183                 // Until python support ascii again, we use our own.
2184                 // PySys_SetArgv(argc, argv);
2185                 int i;
2186                 PyObject *py_argv= PyList_New(argc);
2187
2188                 for (i=0; i<argc; i++)
2189                         PyList_SET_ITEM(py_argv, i, PyC_UnicodeFromByte(argv[i]));
2190
2191                 PySys_SetObject("argv", py_argv);
2192                 Py_DECREF(py_argv);
2193         }
2194
2195         /* Initialize thread support (also acquires lock) */
2196         PyEval_InitThreads();
2197
2198         bpy_import_init(PyEval_GetBuiltins());
2199
2200         bpy_import_main_set(maggie);
2201
2202         initPySysObjects(maggie);
2203
2204         /* mathutils types are used by the BGE even if we don't import them */
2205         {
2206                 PyObject *mod = PyImport_ImportModuleLevel("mathutils", NULL, NULL, NULL, 0);
2207                 Py_DECREF(mod);
2208         }
2209
2210 #ifdef WITH_AUDASPACE
2211         /* accessing a SoundActuator's sound results in a crash if aud is not initialized... */
2212         {
2213                 PyObject *mod = PyImport_ImportModuleLevel("aud", NULL, NULL, NULL, 0);
2214                 Py_DECREF(mod);
2215         }
2216 #endif
2217
2218         PyDict_SetItemString(PyImport_GetModuleDict(), "bge", initBGE());
2219
2220         first_time = false;
2221         
2222         PyObjectPlus::ClearDeprecationWarning();
2223
2224         return PyC_DefaultNameSpace(NULL);
2225 }
2226
2227 void exitGamePlayerPythonScripting()
2228 {
2229         /* Clean up the Python mouse and keyboard */
2230         delete gp_PythonKeyboard;
2231         gp_PythonKeyboard = NULL;
2232
2233         delete gp_PythonMouse;
2234         gp_PythonMouse = NULL;
2235
2236         for (int i=0; i<JOYINDEX_MAX; ++i) {
2237                 if (gp_PythonJoysticks[i]) {
2238                         delete gp_PythonJoysticks[i];
2239                         gp_PythonJoysticks[i] = NULL;
2240                 }
2241         }
2242
2243         /* since python restarts we cant let the python backup of the sys.path hang around in a global pointer */
2244         restorePySysObjects(); /* get back the original sys.path and clear the backup */
2245         
2246         Py_Finalize();
2247         bpy_import_main_set(NULL);
2248         PyObjectPlus::ClearDeprecationWarning();
2249 }
2250
2251
2252
2253 /**
2254  * Python is already initialized.
2255  */
2256 PyObject *initGamePythonScripting(Main *maggie)
2257 {
2258         /* no need to Py_SetProgramName, it was already taken care of in BPY_python_start */
2259
2260         bpy_import_main_set(maggie);
2261
2262         initPySysObjects(maggie);
2263
2264 #ifdef WITH_AUDASPACE
2265         /* accessing a SoundActuator's sound results in a crash if aud is not initialized... */
2266         {
2267                 PyObject *mod= PyImport_ImportModuleLevel("aud", NULL, NULL, NULL, 0);
2268                 Py_DECREF(mod);
2269         }
2270 #endif
2271
2272         PyDict_SetItemString(PyImport_GetModuleDict(), "bge", initBGE());
2273
2274         PyObjectPlus::NullDeprecationWarning();
2275
2276         return PyC_DefaultNameSpace(NULL);
2277 }
2278
2279 void exitGamePythonScripting()
2280 {
2281         /* Clean up the Python mouse and keyboard */
2282         delete gp_PythonKeyboard;
2283         gp_PythonKeyboard = NULL;
2284
2285         delete gp_PythonMouse;
2286         gp_PythonMouse = NULL;
2287
2288         for (int i=0; i<JOYINDEX_MAX; ++i) {
2289                 if (gp_PythonJoysticks[i]) {
2290                         delete gp_PythonJoysticks[i];
2291                         gp_PythonJoysticks[i] = NULL;
2292                 }
2293         }
2294
2295         restorePySysObjects(); /* get back the original sys.path and clear the backup */
2296         bpy_import_main_set(NULL);
2297         PyObjectPlus::ClearDeprecationWarning();
2298 }
2299
2300 /* similar to the above functions except it sets up the namespace
2301  * and other more general things */
2302 void setupGamePython(KX_KetsjiEngine* ketsjiengine, KX_Scene *startscene, Main *blenderdata,
2303                      PyObject *pyGlobalDict, PyObject **gameLogic, PyObject **gameLogic_keys, int argc, char** argv)
2304 {
2305         PyObject *modules, *dictionaryobject;
2306
2307         gp_Canvas = ketsjiengine->GetCanvas();
2308         gp_Rasterizer = ketsjiengine->GetRasterizer();
2309         gp_KetsjiEngine = ketsjiengine;
2310         gp_KetsjiScene = startscene;
2311
2312         if (argv) /* player only */
2313                 dictionaryobject= initGamePlayerPythonScripting(blenderdata, argc, argv);
2314         else
2315                 dictionaryobject= initGamePythonScripting(blenderdata);
2316
2317         ketsjiengine->SetPyNamespace(dictionaryobject);
2318
2319         modules = PyImport_GetModuleDict();
2320
2321         *gameLogic = PyDict_GetItemString(modules, "GameLogic");
2322         /* is set in initGameLogicPythonBinding so only set here if we want it to persist between scenes */
2323         if (pyGlobalDict)
2324                 PyDict_SetItemString(PyModule_GetDict(*gameLogic), "globalDict", pyGlobalDict); // Same as importing the module.
2325
2326         *gameLogic_keys = PyDict_Keys(PyModule_GetDict(*gameLogic));
2327 }
2328
2329 static struct PyModuleDef Rasterizer_module_def = {
2330         PyModuleDef_HEAD_INIT,
2331         "Rasterizer",  /* m_name */
2332         Rasterizer_module_documentation,  /* m_doc */
2333         0,  /* m_size */
2334         rasterizer_methods,  /* m_methods */
2335         0,  /* m_reload */
2336         0,  /* m_traverse */
2337         0,  /* m_clear */
2338         0,  /* m_free */
2339 };
2340
2341 PyMODINIT_FUNC initRasterizerPythonBinding()
2342 {
2343         PyObject *m;
2344         PyObject *d;
2345
2346         m = PyModule_Create(&Rasterizer_module_def);
2347         PyDict_SetItemString(PySys_GetObject("modules"), Rasterizer_module_def.m_name, m);
2348
2349
2350         // Add some symbolic constants to the module
2351         d = PyModule_GetDict(m);
2352         ErrorObject = PyUnicode_FromString("Rasterizer.error");
2353         PyDict_SetItemString(d, "error", ErrorObject);
2354         Py_DECREF(ErrorObject);
2355
2356         /* needed for get/setMaterialType */
2357         KX_MACRO_addTypesToDict(d, KX_BLENDER_MULTITEX_MATERIAL, KX_BLENDER_MULTITEX_MATERIAL);
2358         KX_MACRO_addTypesToDict(d, KX_BLENDER_GLSL_MATERIAL, KX_BLENDER_GLSL_MATERIAL);
2359
2360         KX_MACRO_addTypesToDict(d, RAS_MIPMAP_NONE, RAS_IRasterizer::RAS_MIPMAP_NONE);
2361         KX_MACRO_addTypesToDict(d, RAS_MIPMAP_NEAREST, RAS_IRasterizer::RAS_MIPMAP_NEAREST);
2362         KX_MACRO_addTypesToDict(d, RAS_MIPMAP_LINEAR, RAS_IRasterizer::RAS_MIPMAP_LINEAR);
2363
2364         /* for get/setVsync */
2365         KX_MACRO_addTypesToDict(d, VSYNC_OFF, VSYNC_OFF);
2366         KX_MACRO_addTypesToDict(d, VSYNC_ON, VSYNC_ON);
2367         KX_MACRO_addTypesToDict(d, VSYNC_ADAPTIVE, VSYNC_ADAPTIVE);
2368
2369         /* stereoscopy */
2370         KX_MACRO_addTypesToDict(d, LEFT_EYE, RAS_IRasterizer::RAS_STEREO_LEFTEYE);
2371         KX_MACRO_addTypesToDict(d, RIGHT_EYE, RAS_IRasterizer::RAS_STEREO_RIGHTEYE);
2372
2373         // XXXX Add constants here
2374
2375         // Check for errors
2376         if (PyErr_Occurred())
2377         {
2378                 Py_FatalError("can't initialize module Rasterizer");
2379         }
2380
2381         return m;
2382 }
2383
2384
2385
2386 /* ------------------------------------------------------------------------- */
2387 /* GameKeys: symbolic constants for key mapping                              */
2388 /* ------------------------------------------------------------------------- */
2389
2390 PyDoc_STRVAR(GameKeys_module_documentation,
2391 "This modules provides defines for key-codes"
2392 );
2393
2394 PyDoc_STRVAR(gPyEventToString_doc,
2395 "EventToString(event)\n"
2396 "Take a valid event from the GameKeys module or Keyboard Sensor and return a name"
2397 );
2398
2399 static PyObject *gPyEventToString(PyObject *, PyObject *value)
2400 {
2401         PyObject *mod, *dict, *key, *val, *ret = NULL;
2402         Py_ssize_t pos = 0;
2403         
2404         mod = PyImport_ImportModule( "GameKeys" );
2405         if (!mod)
2406                 return NULL;
2407         
2408         dict = PyModule_GetDict(mod);
2409         
2410         while (PyDict_Next(dict, &pos, &key, &val)) {
2411                 if (PyObject_RichCompareBool(value, val, Py_EQ)) {
2412                         ret = key;
2413                         break;
2414                 }
2415         }
2416         
2417         PyErr_Clear(); // in case there was an error clearing
2418         Py_DECREF(mod);
2419         if (!ret)       PyErr_SetString(PyExc_ValueError, "GameKeys.EventToString(int): expected a valid int keyboard event");
2420         else            Py_INCREF(ret);
2421         
2422         return ret;
2423 }
2424
2425
2426 PyDoc_STRVAR(gPyEventToCharacter_doc,
2427 "EventToCharacter(event, is_shift)\n"
2428 "Take a valid event from the GameKeys module or Keyboard Sensor and return a character"
2429 );
2430
2431 static PyObject *gPyEventToCharacter(PyObject *, PyObject *args)
2432 {
2433         int event, shift;
2434         if (!PyArg_ParseTuple(args,"ii:EventToCharacter", &event, &shift))
2435                 return NULL;
2436         
2437         if (IsPrintable(event)) {
2438                 char ch[2] = {'\0', '\0'};
2439                 ch[0] = ToCharacter(event, (bool)shift);
2440                 return PyUnicode_FromString(ch);
2441         }
2442         else {
2443                 return PyUnicode_FromString("");
2444         }
2445 }
2446
2447
2448 static struct PyMethodDef gamekeys_methods[] = {
2449         {"EventToCharacter", (PyCFunction)gPyEventToCharacter, METH_VARARGS, (const char *)gPyEventToCharacter_doc},
2450         {"EventToString", (PyCFunction)gPyEventToString, METH_O, (const char *)gPyEventToString_doc},
2451         { NULL, (PyCFunction) NULL, 0, NULL }
2452 };
2453
2454 static struct PyModuleDef GameKeys_module_def = {
2455         PyModuleDef_HEAD_INIT,
2456         "GameKeys",  /* m_name */
2457         GameKeys_module_documentation,  /* m_doc */
2458         0,  /* m_size */
2459         gamekeys_methods,  /* m_methods */
2460         0,  /* m_reload */
2461         0,  /* m_traverse */
2462         0,  /* m_clear */
2463         0,  /* m_free */
2464 };
2465
2466 PyMODINIT_FUNC initGameKeysPythonBinding()
2467 {
2468         PyObject *m;
2469         PyObject *d;
2470
2471         m = PyModule_Create(&GameKeys_module_def);
2472         PyDict_SetItemString(PySys_GetObject("modules"), GameKeys_module_def.m_name, m);
2473
2474         // Add some symbolic constants to the module
2475         d = PyModule_GetDict(m);
2476
2477         // XXXX Add constants here
2478
2479         KX_MACRO_addTypesToDict(d, AKEY, SCA_IInputDevice::KX_AKEY);
2480         KX_MACRO_addTypesToDict(d, BKEY, SCA_IInputDevice::KX_BKEY);
2481         KX_MACRO_addTypesToDict(d, CKEY, SCA_IInputDevice::KX_CKEY);
2482         KX_MACRO_addTypesToDict(d, DKEY, SCA_IInputDevice::KX_DKEY);
2483         KX_MACRO_addTypesToDict(d, EKEY, SCA_IInputDevice::KX_EKEY);
2484         KX_MACRO_addTypesToDict(d, FKEY, SCA_IInputDevice::KX_FKEY);
2485         KX_MACRO_addTypesToDict(d, GKEY, SCA_IInputDevice::KX_GKEY);
2486         KX_MACRO_addTypesToDict(d, HKEY, SCA_IInputDevice::KX_HKEY);
2487         KX_MACRO_addTypesToDict(d, IKEY, SCA_IInputDevice::KX_IKEY);
2488         KX_MACRO_addTypesToDict(d, JKEY, SCA_IInputDevice::KX_JKEY);
2489         KX_MACRO_addTypesToDict(d, KKEY, SCA_IInputDevice::KX_KKEY);
2490         KX_MACRO_addTypesToDict(d, LKEY, SCA_IInputDevice::KX_LKEY);
2491         KX_MACRO_addTypesToDict(d, MKEY, SCA_IInputDevice::KX_MKEY);
2492         KX_MACRO_addTypesToDict(d, NKEY, SCA_IInputDevice::KX_NKEY);
2493         KX_MACRO_addTypesToDict(d, OKEY, SCA_IInputDevice::KX_OKEY);
2494         KX_MACRO_addTypesToDict(d, PKEY, SCA_IInputDevice::KX_PKEY);
2495         KX_MACRO_addTypesToDict(d, QKEY, SCA_IInputDevice::KX_QKEY);
2496         KX_MACRO_addTypesToDict(d, RKEY, SCA_IInputDevice::KX_RKEY);
2497         KX_MACRO_addTypesToDict(d, SKEY, SCA_IInputDevice::KX_SKEY);
2498         KX_MACRO_addTypesToDict(d, TKEY, SCA_IInputDevice::KX_TKEY);
2499         KX_MACRO_addTypesToDict(d, UKEY, SCA_IInputDevice::KX_UKEY);
2500         KX_MACRO_addTypesToDict(d, VKEY, SCA_IInputDevice::KX_VKEY);
2501         KX_MACRO_addTypesToDict(d, WKEY, SCA_IInputDevice::KX_WKEY);
2502         KX_MACRO_addTypesToDict(d, XKEY, SCA_IInputDevice::KX_XKEY);
2503         KX_MACRO_addTypesToDict(d, YKEY, SCA_IInputDevice::KX_YKEY);
2504         KX_MACRO_addTypesToDict(d, ZKEY, SCA_IInputDevice::KX_ZKEY);
2505         
2506         KX_MACRO_addTypesToDict(d, ZEROKEY, SCA_IInputDevice::KX_ZEROKEY);
2507         KX_MACRO_addTypesToDict(d, ONEKEY, SCA_IInputDevice::KX_ONEKEY);
2508         KX_MACRO_addTypesToDict(d, TWOKEY, SCA_IInputDevice::KX_TWOKEY);
2509         KX_MACRO_addTypesToDict(d, THREEKEY, SCA_IInputDevice::KX_THREEKEY);
2510         KX_MACRO_addTypesToDict(d, FOURKEY, SCA_IInputDevice::KX_FOURKEY);
2511         KX_MACRO_addTypesToDict(d, FIVEKEY, SCA_IInputDevice::KX_FIVEKEY);
2512         KX_MACRO_addTypesToDict(d, SIXKEY, SCA_IInputDevice::KX_SIXKEY);
2513         KX_MACRO_addTypesToDict(d, SEVENKEY, SCA_IInputDevice::KX_SEVENKEY);
2514         KX_MACRO_addTypesToDict(d, EIGHTKEY, SCA_IInputDevice::KX_EIGHTKEY);
2515         KX_MACRO_addTypesToDict(d, NINEKEY, SCA_IInputDevice::KX_NINEKEY);
2516                 
2517         KX_MACRO_addTypesToDict(d, CAPSLOCKKEY, SCA_IInputDevice::KX_CAPSLOCKKEY);
2518                 
2519         KX_MACRO_addTypesToDict(d, LEFTCTRLKEY, SCA_IInputDevice::KX_LEFTCTRLKEY);
2520         KX_MACRO_addTypesToDict(d, LEFTALTKEY, SCA_IInputDevice::KX_LEFTALTKEY);
2521         KX_MACRO_addTypesToDict(d, RIGHTALTKEY, SCA_IInputDevice::KX_RIGHTALTKEY);
2522         KX_MACRO_addTypesToDict(d, RIGHTCTRLKEY, SCA_IInputDevice::KX_RIGHTCTRLKEY);
2523         KX_MACRO_addTypesToDict(d, RIGHTSHIFTKEY, SCA_IInputDevice::KX_RIGHTSHIFTKEY);
2524         KX_MACRO_addTypesToDict(d, LEFTSHIFTKEY, SCA_IInputDevice::KX_LEFTSHIFTKEY);
2525                 
2526         KX_MACRO_addTypesToDict(d, ESCKEY, SCA_IInputDevice::KX_ESCKEY);
2527         KX_MACRO_addTypesToDict(d, TABKEY, SCA_IInputDevice::KX_TABKEY);
2528         KX_MACRO_addTypesToDict(d, RETKEY, SCA_IInputDevice::KX_RETKEY);
2529         KX_MACRO_addTypesToDict(d, ENTERKEY, SCA_IInputDevice::KX_RETKEY);
2530         KX_MACRO_addTypesToDict(d, SPACEKEY, SCA_IInputDevice::KX_SPACEKEY);
2531         KX_MACRO_addTypesToDict(d, LINEFEEDKEY, SCA_IInputDevice::KX_LINEFEEDKEY);
2532         KX_MACRO_addTypesToDict(d, BACKSPACEKEY, SCA_IInputDevice::KX_BACKSPACEKEY);
2533         KX_MACRO_addTypesToDict(d, DELKEY, SCA_IInputDevice::KX_DELKEY);
2534         KX_MACRO_addTypesToDict(d, SEMICOLONKEY, SCA_IInputDevice::KX_SEMICOLONKEY);
2535         KX_MACRO_addTypesToDict(d, PERIODKEY, SCA_IInputDevice::KX_PERIODKEY);
2536         KX_MACRO_addTypesToDict(d, COMMAKEY, SCA_IInputDevice::KX_COMMAKEY);
2537         KX_MACRO_addTypesToDict(d, QUOTEKEY, SCA_IInputDevice::KX_QUOTEKEY);
2538         KX_MACRO_addTypesToDict(d, ACCENTGRAVEKEY, SCA_IInputDevice::KX_ACCENTGRAVEKEY);
2539         KX_MACRO_addTypesToDict(d, MINUSKEY, SCA_IInputDevice::KX_MINUSKEY);
2540         KX_MACRO_addTypesToDict(d, SLASHKEY, SCA_IInputDevice::KX_SLASHKEY);
2541         KX_MACRO_addTypesToDict(d, BACKSLASHKEY, SCA_IInputDevice::KX_BACKSLASHKEY);
2542         KX_MACRO_addTypesToDict(d, EQUALKEY, SCA_IInputDevice::KX_EQUALKEY);
2543         KX_MACRO_addTypesToDict(d, LEFTBRACKETKEY, SCA_IInputDevice::KX_LEFTBRACKETKEY);
2544         KX_MACRO_addTypesToDict(d, RIGHTBRACKETKEY, SCA_IInputDevice::KX_RIGHTBRACKETKEY);
2545                 
2546         KX_MACRO_addTypesToDict(d, LEFTARROWKEY, SCA_IInputDevice::KX_LEFTARROWKEY);
2547         KX_MACRO_addTypesToDict(d, DOWNARROWKEY, SCA_IInputDevice::KX_DOWNARROWKEY);
2548         KX_MACRO_addTypesToDict(d, RIGHTARROWKEY, SCA_IInputDevice::KX_RIGHTARROWKEY);
2549         KX_MACRO_addTypesToDict(d, UPARROWKEY, SCA_IInputDevice::KX_UPARROWKEY);
2550         
2551         KX_MACRO_addTypesToDict(d, PAD2 , SCA_IInputDevice::KX_PAD2);
2552         KX_MACRO_addTypesToDict(d, PAD4 , SCA_IInputDevice::KX_PAD4);
2553         KX_MACRO_addTypesToDict(d, PAD6 , SCA_IInputDevice::KX_PAD6);
2554         KX_MACRO_addTypesToDict(d, PAD8 , SCA_IInputDevice::KX_PAD8);
2555                 
2556         KX_MACRO_addTypesToDict(d, PAD1 , SCA_IInputDevice::KX_PAD1);
2557         KX_MACRO_addTypesToDict(d, PAD3 , SCA_IInputDevice::KX_PAD3);
2558         KX_MACRO_addTypesToDict(d, PAD5 , SCA_IInputDevice::KX_PAD5);
2559         KX_MACRO_addTypesToDict(d, PAD7 , SCA_IInputDevice::KX_PAD7);
2560         KX_MACRO_addTypesToDict(d, PAD9 , SCA_IInputDevice::KX_PAD9);
2561                 
2562         KX_MACRO_addTypesToDict(d, PADPERIOD, SCA_IInputDevice::KX_PADPERIOD);
2563         KX_MACRO_addTypesToDict(d, PADSLASHKEY, SCA_IInputDevice::KX_PADSLASHKEY);
2564         KX_MACRO_addTypesToDict(d, PADASTERKEY, SCA_IInputDevice::KX_PADASTERKEY);
2565                 
2566                 
2567         KX_MACRO_addTypesToDict(d, PAD0, SCA_IInputDevice::KX_PAD0);
2568         KX_MACRO_addTypesToDict(d, PADMINUS, SCA_IInputDevice::KX_PADMINUS);
2569         KX_MACRO_addTypesToDict(d, PADENTER, SCA_IInputDevice::KX_PADENTER);
2570         KX_MACRO_addTypesToDict(d, PADPLUSKEY, SCA_IInputDevice::KX_PADPLUSKEY);
2571                 
2572                 
2573         KX_MACRO_addTypesToDict(d, F1KEY,  SCA_IInputDevice::KX_F1KEY);
2574         KX_MACRO_addTypesToDict(d, F2KEY,  SCA_IInputDevice::KX_F2KEY);
2575         KX_MACRO_addTypesToDict(d, F3KEY,  SCA_IInputDevice::KX_F3KEY);
2576         KX_MACRO_addTypesToDict(d, F4KEY,  SCA_IInputDevice::KX_F4KEY);
2577         KX_MACRO_addTypesToDict(d, F5KEY,  SCA_IInputDevice::KX_F5KEY);
2578         KX_MACRO_addTypesToDict(d, F6KEY,  SCA_IInputDevice::KX_F6KEY);
2579         KX_MACRO_addTypesToDict(d, F7KEY,  SCA_IInputDevice::KX_F7KEY);
2580         KX_MACRO_addTypesToDict(d, F8KEY,  SCA_IInputDevice::KX_F8KEY);
2581         KX_MACRO_addTypesToDict(d, F9KEY,  SCA_IInputDevice::KX_F9KEY);
2582         KX_MACRO_addTypesToDict(d, F10KEY, SCA_IInputDevice::KX_F10KEY);
2583         KX_MACRO_addTypesToDict(d, F11KEY, SCA_IInputDevice::KX_F11KEY);
2584         KX_MACRO_addTypesToDict(d, F12KEY, SCA_IInputDevice::KX_F12KEY);
2585         KX_MACRO_addTypesToDict(d, F13KEY, SCA_IInputDevice::KX_F13KEY);
2586         KX_MACRO_addTypesToDict(d, F14KEY, SCA_IInputDevice::KX_F14KEY);
2587         KX_MACRO_addTypesToDict(d, F15KEY, SCA_IInputDevice::KX_F15KEY);
2588         KX_MACRO_addTypesToDict(d, F16KEY, SCA_IInputDevice::KX_F16KEY);
2589         KX_MACRO_addTypesToDict(d, F17KEY, SCA_IInputDevice::KX_F17KEY);
2590         KX_MACRO_addTypesToDict(d, F18KEY, SCA_IInputDevice::KX_F18KEY);
2591         KX_MACRO_addTypesToDict(d, F19KEY, SCA_IInputDevice::KX_F19KEY);
2592
2593         KX_MACRO_addTypesToDict(d, OSKEY, SCA_IInputDevice::KX_OSKEY);
2594                 
2595         KX_MACRO_addTypesToDict(d, PAUSEKEY,  SCA_IInputDevice::KX_PAUSEKEY);
2596         KX_MACRO_addTypesToDict(d, INSERTKEY, SCA_IInputDevice::KX_INSERTKEY);
2597         KX_MACRO_addTypesToDict(d, HOMEKEY,   SCA_IInputDevice::KX_HOMEKEY);
2598         KX_MACRO_addTypesToDict(d, PAGEUPKEY, SCA_IInputDevice::KX_PAGEUPKEY);
2599         KX_MACRO_addTypesToDict(d, PAGEDOWNKEY, SCA_IInputDevice::KX_PAGEDOWNKEY);
2600         KX_MACRO_addTypesToDict(d, ENDKEY, SCA_IInputDevice::KX_ENDKEY);
2601
2602         // MOUSE
2603         KX_MACRO_addTypesToDict(d, LEFTMOUSE, SCA_IInputDevice::KX_LEFTMOUSE);
2604         KX_MACRO_addTypesToDict(d, MIDDLEMOUSE, SCA_IInputDevice::KX_MIDDLEMOUSE);
2605         KX_MACRO_addTypesToDict(d, RIGHTMOUSE, SCA_IInputDevice::KX_RIGHTMOUSE);
2606         KX_MACRO_addTypesToDict(d, WHEELUPMOUSE, SCA_IInputDevice::KX_WHEELUPMOUSE);
2607         KX_MACRO_addTypesToDict(d, WHEELDOWNMOUSE, SCA_IInputDevice::KX_WHEELDOWNMOUSE);
2608         KX_MACRO_addTypesToDict(d, MOUSEX, SCA_IInputDevice::KX_MOUSEX);
2609         KX_MACRO_addTypesToDict(d, MOUSEY, SCA_IInputDevice::KX_MOUSEY);
2610
2611         // Check for errors
2612         if (PyErr_Occurred())
2613         {
2614                 Py_FatalError("can't initialize module GameKeys");
2615         }
2616
2617         return m;
2618 }
2619
2620 // utility function for loading and saving the globalDict
2621 int saveGamePythonConfig( char **marshal_buffer)
2622 {
2623         int marshal_length = 0;
2624         PyObject *gameLogic = PyImport_ImportModule("GameLogic");
2625         if (gameLogic) {
2626                 PyObject *pyGlobalDict = PyDict_GetItemString(PyModule_GetDict(gameLogic), "globalDict"); // Same as importing the module
2627                 if (pyGlobalDict) {
2628 #ifdef Py_MARSHAL_VERSION
2629                         PyObject *pyGlobalDictMarshal = PyMarshal_WriteObjectToString(  pyGlobalDict, 2); // Py_MARSHAL_VERSION == 2 as of Py2.5
2630 #else
2631                         PyObject *pyGlobalDictMarshal = PyMarshal_WriteObjectToString(  pyGlobalDict );
2632 #endif
2633                         if (pyGlobalDictMarshal) {
2634                                 // for testing only
2635                                 // PyObject_Print(pyGlobalDictMarshal, stderr, 0);
2636                                 char *marshal_cstring;
2637                                 
2638                                 marshal_cstring = PyBytes_AsString(pyGlobalDictMarshal); // py3 uses byte arrays
2639                                 marshal_length= PyBytes_Size(pyGlobalDictMarshal);
2640                                 *marshal_buffer = new char[marshal_length + 1];
2641                                 memcpy(*marshal_buffer, marshal_cstring, marshal_length);
2642                                 Py_DECREF(pyGlobalDictMarshal);
2643                         } else {
2644                                 printf("Error, bge.logic.globalDict could not be marshal'd\n");
2645                         }
2646                 } else {
2647                         printf("Error, bge.logic.globalDict was removed\n");
2648                 }
2649                 Py_DECREF(gameLogic);
2650         } else {
2651                 PyErr_Clear();
2652                 printf("Error, bge.logic failed to import bge.logic.globalDict will be lost\n");
2653         }
2654         return marshal_length;
2655 }
2656
2657 int loadGamePythonConfig(char *marshal_buffer, int marshal_length)
2658 {
2659         /* Restore the dict */
2660         if (marshal_buffer) {
2661                 PyObject *gameLogic = PyImport_ImportModule("GameLogic");
2662
2663                 if (gameLogic) {
2664                         PyObject *pyGlobalDict = PyMarshal_ReadObjectFromString(marshal_buffer, marshal_length);
2665                         if (pyGlobalDict) {
2666                                 PyObject *pyGlobalDict_orig = PyDict_GetItemString(PyModule_GetDict(gameLogic), "globalDict"); // Same as importing the module.
2667                                 if (pyGlobalDict_orig) {
2668                                         PyDict_Clear(pyGlobalDict_orig);
2669                                         PyDict_Update(pyGlobalDict_orig, pyGlobalDict);
2670                                 } else {
2671                                         /* this should not happen, but cant find the original globalDict, just assign it then */
2672                                         PyDict_SetItemString(PyModule_GetDict(gameLogic), "globalDict", pyGlobalDict); // Same as importing the module.
2673                                 }
2674                                 Py_DECREF(gameLogic);
2675                                 Py_DECREF(pyGlobalDict);
2676                                 return 1;
2677                         } else {
2678                                 Py_DECREF(gameLogic);
2679                                 PyErr_Clear();
2680                                 printf("Error could not marshall string\n");
2681                         }
2682                 }
2683                 else {
2684                         PyErr_Clear();
2685                         printf("Error, bge.logic failed to import bge.logic.globalDict will be lost\n");
2686                 }
2687         }
2688         return 0;
2689 }
2690
2691 void pathGamePythonConfig(char *path)
2692 {
2693         int len = strlen(gp_GamePythonPathOrig); // Always use the first loaded blend filename
2694         
2695         BLI_strncpy(path, gp_GamePythonPathOrig, sizeof(gp_GamePythonPathOrig));
2696
2697         /* replace extension */
2698         if (BLI_testextensie(path, ".blend")) {
2699                 strcpy(path+(len-6), ".bgeconf");
2700         } else {
2701                 strcpy(path+len, ".bgeconf");
2702         }
2703 }
2704
2705 void setGamePythonPath(const char *path)
2706 {
2707         BLI_strncpy(gp_GamePythonPath, path, sizeof(gp_GamePythonPath));
2708         BLI_cleanup_file(NULL, gp_GamePythonPath); /* not absolutely needed but makes resolving path problems less confusing later */
2709         
2710         if (gp_GamePythonPathOrig[0] == '\0')
2711                 BLI_strncpy(gp_GamePythonPathOrig, path, sizeof(gp_GamePythonPathOrig));
2712 }
2713
2714 // we need this so while blender is open (not blenderplayer)
2715 // loading new blendfiles will reset this on starting the
2716 // engine but loading blend files within the BGE wont overwrite gp_GamePythonPathOrig
2717 void resetGamePythonPath()
2718 {
2719         gp_GamePythonPathOrig[0] = '\0';
2720 }
2721
2722 #endif // WITH_PYTHON