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