95
95
PyObject *bpy_pydriver_Dict = NULL;
96
96
PyObject *bpy_orig_syspath_List = NULL;
99
100
* set up a weakref list for Armatures
100
101
* creates list in __main__ module dict
103
int setup_armature_weakrefs()
104
static int setup_armature_weakrefs()
105
106
PyObject *maindict;
106
107
PyObject *main_module;
159
160
/***************************************************************************
160
161
* Function prototypes
161
162
***************************************************************************/
162
PyObject *RunPython( Text * text, PyObject * globaldict );
163
char *GetName( Text * text );
164
PyObject *CreateGlobalDictionary( void );
165
void ReleaseGlobalDictionary( PyObject * dict );
166
void DoAllScriptsFromList( ListBase * list, short event );
167
PyObject *importText( char *name );
168
void init_ourImport( void );
169
void init_ourReload( void );
170
PyObject *blender_import( PyObject * self, PyObject * args );
171
PyObject *RunPython2( Text * text, PyObject * globaldict, PyObject *localdict );
174
void BPY_Err_Handle( char *script_name );
175
PyObject *traceback_getFilename( PyObject * tb );
163
static PyObject *RunPython( Text * text, PyObject * globaldict );
164
static PyObject *CreateGlobalDictionary( void );
165
static void ReleaseGlobalDictionary( PyObject * dict );
166
static void DoAllScriptsFromList( ListBase * list, short event );
167
static PyObject *importText( char *name );
168
static void init_ourImport( void );
169
static void init_ourReload( void );
170
static PyObject *blender_import( PyObject * self, PyObject * args );
173
static void BPY_Err_Handle( char *script_name );
174
static PyObject *traceback_getFilename( PyObject * tb );
177
176
/****************************************************************************
178
177
* Description: This function will start the interpreter and load all modules
196
195
//stuff for Registry module
197
196
bpy_registryDict = PyDict_New( );/* check comment at start of this file */
198
197
if( !bpy_registryDict )
199
printf( "Error: Couldn't create the Registry Python Dictionary!" );
198
printf( "Warning: Couldn't create the Registry Python Dictionary!" );
200
199
Py_SetProgramName( "blender" );
202
201
/* Py_Initialize() will attempt to import the site module and
225
224
//Start the interpreter
226
225
Py_Initialize( );
227
227
PySys_SetArgv( argc_copy, argv_copy );
229
228
/* Initialize thread support (also acquires lock) */
230
229
PyEval_InitThreads();
232
/* Don't allow the Python Interpreter to release the GIL on
233
* its own, to guarantee PyNodes work properly. For Blender this
234
* is currently the best default behavior.
235
* The following code in C is equivalent in Python to:
236
* "import sys; sys.setcheckinterval(sys.maxint)" */
237
_Py_CheckInterval = PyInt_GetMax();
239
231
//Overrides __import__
240
232
init_ourImport( );
241
233
init_ourReload( );
299
290
PyObject *mod_sys= NULL, *dict= NULL, *path= NULL, *dir= NULL;
303
dir = Py_BuildValue( "s", dirname );
305
293
mod_sys = PyImport_ImportModule( "sys" ); /* new ref */
314
302
/* cant get the sys module */
303
/* PyErr_Clear(); is called below */
318
if (PySequence_Contains(path, dir)==0) { /* Only add if we need to */
319
if (ok && PyList_Append( path, dir ) != 0)
307
dir = PyString_FromString( dirname );
309
if (ok && PySequence_Contains(path, dir)==0) { /* Only add if we need to */
310
if (PyList_Append( path, dir ) != 0) /* decref below */
320
311
ok = 0; /* append failed */
322
if( (ok==0) || PyErr_Occurred( ) )
323
Py_FatalError( "could import or build sys.path, can't continue" );
314
if( (ok==0) || PyErr_Occurred( ) )
315
fprintf(stderr, "Warning: could import or build sys.path\n" );
325
319
Py_XDECREF( mod_sys );
328
322
void init_syspath( int first_time )
331
324
PyObject *mod, *d;
333
326
char execdir[FILE_MAXDIR]; /*defines from DNA_space_types.h */
338
path = Py_BuildValue( "s", bprogname );
340
330
mod = PyImport_ImportModule( "Blender.sys" );
343
333
d = PyModule_GetDict( mod );
344
EXPP_dict_set_item_str( d, "progname", path );
334
EXPP_dict_set_item_str( d, "progname", PyString_FromString( bprogname ) );
345
335
Py_DECREF( mod );
347
printf( "Warning: could not set Blender.sys.progname\n" );
337
printf( "Warning: could not set Blender.sys\n" );
349
341
progname = BLI_last_slash( bprogname ); /* looks for the last dir separator */
417
410
mod = PyImport_ImportModule( "sys" );
419
printf("error: could not import python sys module. some modules may not import.\n");
412
printf("Warning: could not import python sys module. some modules may not import.\n");
414
PyGILState_Release(gilstate);
423
418
if (!bpy_orig_syspath_List) { /* should never happen */
424
printf("error refershing python path\n");
419
printf("Warning: cant refresh python path, bpy_orig_syspath_List is NULL\n");
421
PyGILState_Release(gilstate);
516
512
/*****************************************************************************/
517
513
/* Description: Return PyString filename from a traceback object */
518
514
/*****************************************************************************/
519
PyObject *traceback_getFilename( PyObject * tb )
515
static PyObject *traceback_getFilename( PyObject * tb )
521
517
PyObject *v = NULL;
536
532
else return PyString_FromString("unknown");
535
static void BPY_Err_Clear(void)
537
/* Added in 2.48a, the last_traceback can reference Objects for example, increasing
538
* their user count. Not to mention holding references to wrapped data.
539
* This is especially bad when the PyObject for the wrapped data is free'd, after blender
540
* has alredy dealocated the pointer */
541
PySys_SetObject( "last_traceback", Py_None);
539
545
/****************************************************************************
540
546
* Description: Blender Python error handler. This catches the error and
541
547
* stores filename and line number in a global
542
548
*****************************************************************************/
543
void BPY_Err_Handle( char *script_name )
549
static void BPY_Err_Handle( char *script_name )
545
551
PyObject *exception, *err, *tb, *v;
547
553
if( !script_name ) {
548
554
printf( "Error: script has NULL name\n" );
563
570
&& PyErr_GivenExceptionMatches( exception, PyExc_SyntaxError ) ) {
564
571
/* no traceback available when SyntaxError */
572
PyErr_NormalizeException( &exception, &err, &tb );
565
573
PyErr_Restore( exception, err, tb ); /* takes away reference! */
567
575
v = PyObject_GetAttrString( err, "lineno" );
572
580
g_script_error.lineno = -1;
574
/* this avoids an abort in Python 2.3's garbage collecting: */
582
/* this avoids an abort in Python 2.3's garbage collecting:
584
BPY_Err_Clear(); /* Calls PyErr_Clear as well */
578
587
PyErr_NormalizeException( &exception, &err, &tb );
658
669
/* Create a new script structure and initialize it: */
659
script = alloc_libblock( &G.main->script, ID_SCRIPT, GetName( text ) );
670
script = alloc_libblock( &G.main->script, ID_SCRIPT, text->id.name+2 );
662
673
printf( "couldn't allocate memory for Script struct!" );
667
678
* an error after it will call BPY_Err_Handle below, but the text struct
668
679
* will have been deallocated already, so we need to copy its name here.
670
BLI_strncpy( textname, GetName( text ),
671
strlen( GetName( text ) ) + 1 );
681
BLI_strncpy( textname, text->id.name+2, 21 );
673
683
script->id.us = 1;
674
684
script->flags = SCRIPT_RUNNING;
729
739
* automatically. The script can be a file or a Blender Text in the current
731
741
****************************************************************************/
732
void BPY_run_python_script( char *fn )
742
void BPY_run_python_script( const char *fn )
744
char filename[FILE_MAXDIR + FILE_MAXFILE];
734
745
Text *text = NULL;
735
746
int is_blender_text = 0;
737
if (!BLI_exists(fn)) { /* if there's no such filename ... */
738
text = G.main->text.first; /* try an already existing Blender Text */
748
BLI_strncpy(filename, fn, FILE_MAXDIR + FILE_MAXFILE);
750
if (!BLI_exists(filename))
751
BLI_convertstringcwd(filename);
753
if (!BLI_exists(filename)) { /* if there's no such filename ... */
754
/* try an already existing Blender Text.
755
* use 'fn' rather then filename for this since were looking for
758
text = G.main->text.first;
741
761
if (!strcmp(fn, text->id.name + 2)) break;
773
/* use filename here since we know it exists,
774
* 'fn' may have been a relative path
776
text = add_text(filename);
755
778
if (text == NULL) {
756
779
printf("\nError in BPY_run_python_script:\n"
757
"couldn't create Blender text from %s\n", fn);
780
"couldn't create Blender text from \"%s\"\n", filename);
758
781
/* Chris: On Windows if I continue I just get a segmentation
759
782
* violation. To get a baseline file I exit here. */
771
794
/* We can't simply free the text, since the script might have called
772
795
* Blender.Load() to load a new .blend, freeing previous data.
773
796
* So we check if the pointer is still valid. */
774
Text *txtptr = G.main->text.first;
776
if (txtptr == text) {
777
free_libblock(&G.main->text, text);
780
txtptr = txtptr->id.next;
797
if (BLI_findindex(&G.main->text, text) != -1) {
798
free_libblock(&G.main->text, text);
834
849
Py_INCREF( Py_None );
837
if (BLI_exists(script->scriptname)) {
838
fp = fopen( script->scriptname, "rb" );
842
printf( "Error loading script: couldn't open file %s\n", script->scriptname );
852
if (!BLI_exists(script->scriptname)) {
853
printf( "Script does not exit %s\n", script->scriptname );
843
854
free_libblock( &G.main->script, script );
844
855
PyGILState_Release(gilstate);
885
896
py_res = RunPython( text, py_dict );
898
char pystring[sizeof(script->scriptname) + 15];
899
sprintf(pystring, "execfile(r'%s')", script->scriptname);
900
py_res = PyRun_String( pystring, Py_file_input, py_dict, py_dict );
903
if( !py_res ) { /* Failed execution of the script */
887
904
/* Previously we used PyRun_File to run directly the code on a FILE
888
905
* object, but as written in the Python/C API Ref Manual, chapter 2,
889
906
* 'FILE structs for different C libraries can be different and
891
908
* So now we load the script file data to a buffer */
892
char *buffer=NULL, *buffer_ofs=NULL, *b_to, *b_from;
894
fseek( fp, 0L, SEEK_END );
896
fseek( fp, 0L, SEEK_SET );
898
buffer = buffer_ofs = MEM_mallocN( len + 2, "pyfilebuf" ); /* len+2 to add '\n\0' */
899
len = fread( buffer, 1, len, fp );
901
buffer[len] = '\n'; /* fix syntax error in files w/o eol */
902
buffer[len + 1] = '\0';
905
/* fast clean-up of dos cr/lf line endings, remove convert '\r\n's to '\n' */
906
if (*buffer_ofs == '\r' && *(buffer_ofs+1) == '\n') {
909
b_from = b_to = buffer_ofs;
911
while(*b_from != '\0') {
912
if (*b_from == '\r' && *( b_from+1 ) == '\n') {
915
if (b_from != b_to) {
922
/* done cleaning the string */
926
py_res = PyRun_String( buffer_ofs, Py_file_input, py_dict, py_dict );
930
if( !py_res ) { /* Failed execution of the script */
932
909
BPY_Err_Handle( script->id.name + 2 );
933
910
ReleaseGlobalDictionary( py_dict );
934
911
script->py_globaldict = NULL;
972
949
*****************************************************************************/
973
950
int BPY_menu_do_python( short menutype, int event )
953
pym = BPyMenu_GetEntry( menutype, ( short ) event );
954
return BPY_menu_invoke( pym, menutype );
957
/****************************************************************************
958
* Description: This function executes the script by its shortcut.
959
* Notes: It is called by the ui code in src/???.c when a user presses an
960
* unassigned key combination. Scripts are searched in the BPyMenuTable,
961
* using the given menutype and event values to know which one to invoke.
962
*****************************************************************************/
963
int BPY_menu_do_shortcut( short menutype, unsigned short key, unsigned short qual )
966
pym = BPyMenu_GetEntry( menutype, 0 );
969
if ( pym->key && pym->key == key && pym->qual == qual ) {
970
return BPY_menu_invoke( pym, menutype );
978
/****************************************************************************
979
* Description: This function executes the script described by a menu item.
980
*****************************************************************************/
981
int BPY_menu_invoke( BPyMenu *pym, short menutype )
975
983
char *argstr = NULL;
977
984
BPySubMenu *pysm;
978
985
char scriptname[21];
979
986
Script *script = NULL;
1111
1117
*****************************************************************************/
1112
1118
void BPY_free_compiled_text( struct Text *text )
1114
if( !text->compiled )
1116
Py_DECREF( ( PyObject * ) text->compiled );
1117
text->compiled = NULL;
1120
if( text->compiled ) {
1121
Py_DECREF( ( PyObject * ) text->compiled );
1122
text->compiled = NULL;
1122
1126
/*****************************************************************************
1154
1158
if( sl->spacetype == SPACE_SCRIPT ) {
1155
1159
SpaceScript *sc = ( SpaceScript * ) sl;
1157
if( sc->script == script ) {
1161
if( sc->script == script ) {
1158
1162
sc->script = NULL;
1161
area->spacedata.first ) {
1162
scrarea_queue_redraw
1164
if( sc == area->spacedata.first ) {
1165
scrarea_queue_redraw( area );
1169
BPy_Set_DrawButtonsList(sc->but_refs);
1170
BPy_Free_DrawButtonsList();
1171
sc->but_refs = NULL;
1238
1246
PyDict_SetItemString(d, "Blender", mod);
1239
1247
PyDict_SetItemString(d, "b", mod);
1240
1248
Py_DECREF(mod);
1243
1253
mod = PyImport_ImportModule("math");
1255
1265
PyDict_SetItemString(d, "noise", mod);
1256
1266
PyDict_SetItemString(d, "n", mod);
1257
1267
Py_DECREF(mod);
1260
1272
/* If there's a Blender text called pydrivers.py, import it.
1261
1273
* Users can add their own functions to this module. */
1262
mod = importText("pydrivers"); /* can also use PyImport_Import() */
1264
PyDict_SetItemString(d, "pydrivers", mod);
1265
PyDict_SetItemString(d, "p", mod);
1274
if (G.f&G_DOSCRIPTLINKS) {
1275
mod = importText("pydrivers"); /* can also use PyImport_Import() */
1277
PyDict_SetItemString(d, "pydrivers", mod);
1278
PyDict_SetItemString(d, "p", mod);
1271
1284
/* short aliases for some Get() functions: */
1273
1286
/* ob(obname) == Blender.Object.Get(obname) */
1998
2017
int setitem_retval;
1999
2018
PyGILState_STATE gilstate;
2001
if (!driver) return result;
2020
if (!driver || (G.f&G_DOSCRIPTLINKS)==0) return result;
2003
2022
expr = driver->name; /* the py expression to be evaluated */
2004
2023
if (!expr || expr[0]=='\0') return result;
2103
2122
if (!bpy_pydriver_Dict) {
2104
2123
if (bpy_pydriver_create_dict() != 0) {
2105
2124
fprintf(stderr,
2106
"Button Python Eval error: couldn't create Python dictionary");
2125
"Button Python Eval error: couldn't create Python dictionary \n");
2107
2126
PyGILState_Release(gilstate);
2173
2192
* For the scene, only the current active scene the scripts are
2174
2193
* executed (if any).
2175
2194
*****************************************************************************/
2176
void BPY_do_all_scripts( short event )
2195
void BPY_do_all_scripts( short event, short anim )
2197
/* during stills rendering we disable FRAMECHANGED events */
2198
static char disable_frame_changed = 0;
2200
if ((event == SCRIPT_FRAMECHANGED) && disable_frame_changed)
2178
2203
DoAllScriptsFromList( &( G.main->object ), event );
2179
2204
DoAllScriptsFromList( &( G.main->lamp ), event );
2180
2205
DoAllScriptsFromList( &( G.main->camera ), event );
2184
2209
BPY_do_pyscript( &( G.scene->id ), event );
2211
/* Don't allow the Python Interpreter to release the GIL on
2212
* its own, to guarantee PyNodes work properly. For Blender this
2213
* is currently the best default behavior.
2214
* The following code in C is equivalent in Python to:
2215
* "import sys; sys.setcheckinterval(sys.maxint)" */
2216
if (event == SCRIPT_RENDER) {
2217
_Py_CheckInterval = PyInt_GetMax();
2219
disable_frame_changed = 1;
2221
else if (event == SCRIPT_POSTRENDER) {
2222
_Py_CheckInterval = 100; /* Python default */
2223
disable_frame_changed = 0;
2268
/* tell we're running a scriptlink. The sum also tells if this script
2269
* is running nested inside another. Blender.Load needs this info to
2270
* avoid trouble with invalid slink pointers. */
2308
/* tell we're running a scriptlink. The sum also tells if this
2309
* script is running nested inside another. Blender.Load needs
2310
* this info to avoid trouble with invalid slink pointers. */
2271
2311
during_slink++;
2272
2312
disable_where_scriptlink( (short)during_slink );
2466
2506
int BPY_do_spacehandlers( ScrArea *sa, unsigned short event,
2467
unsigned short space_event )
2507
short eventValue, unsigned short space_event )
2469
2509
ScriptLink *scriptlink;
2470
2510
int retval = 0;
2504
2544
PyDict_SetItemString(g_blenderdict, "bylink", Py_True);
2505
2545
/* unlike normal scriptlinks, here Blender.link is int (space event type) */
2506
2546
EXPP_dict_set_item_str(g_blenderdict, "link", PyInt_FromLong(space_event));
2507
/* note: DRAW space_events set event to 0 */
2547
/* note: DRAW space_events set event and val to 0 */
2508
2548
EXPP_dict_set_item_str(g_blenderdict, "event", PyInt_FromLong(event));
2549
EXPP_dict_set_item_str(g_blenderdict, "eventValue", PyInt_FromLong(eventValue));
2509
2550
/* now run all assigned space handlers for this space and space_event */
2510
2551
for( index = 0; index < scriptlink->totscript; index++ ) {
2700
2741
* Description: This function executes the python script passed by text.
2701
2742
* The Python dictionary containing global variables needs to
2702
2743
* be passed in globaldict.
2744
* NOTE: Make sure BPY_Err_Handle() runs if this returns NULL
2745
* otherwise pointers can be left in sys.last_traceback that become invalid.
2703
2746
*****************************************************************************/
2704
PyObject *RunPython( Text * text, PyObject * globaldict )
2747
static PyObject *RunPython( Text * text, PyObject * globaldict )
2706
2749
char *buf = NULL;
2712
2755
buf = txt_to_buf( text );
2714
2757
text->compiled =
2715
Py_CompileString( buf, GetName( text ),
2758
Py_CompileString( buf, text->id.name+2, Py_file_input );
2718
2760
MEM_freeN( buf );
2730
2772
/*****************************************************************************
2731
* Description: This function returns the value of the name field of the
2732
* given Text struct.
2733
*****************************************************************************/
2734
char *GetName( Text * text )
2736
return ( text->id.name + 2 );
2739
/*****************************************************************************
2740
2773
* Description: This function creates a new Python dictionary object.
2741
2774
*****************************************************************************/
2742
PyObject *CreateGlobalDictionary( void )
2775
static PyObject *CreateGlobalDictionary( void )
2744
2777
PyObject *dict = PyDict_New( );
2753
2786
/*****************************************************************************
2754
2787
* Description: This function deletes a given Python dictionary object.
2755
2788
*****************************************************************************/
2756
void ReleaseGlobalDictionary( PyObject * dict )
2789
static void ReleaseGlobalDictionary( PyObject * dict )
2758
2791
PyDict_Clear( dict );
2759
2792
Py_DECREF( dict ); /* Release dictionary. */
2766
2799
* list argument. The event by which the function has been
2767
2800
* called, is passed in the event argument.
2768
2801
*****************************************************************************/
2769
void DoAllScriptsFromList( ListBase * list, short event )
2802
static void DoAllScriptsFromList( ListBase * list, short event )
2783
PyObject *importText( char *name )
2816
static PyObject *importText( char *name )
2819
char txtname[22]; /* 21+NULL */
2787
2820
char *buf = NULL;
2788
2821
int namelen = strlen( name );
2790
txtname = malloc( namelen + 3 + 1 );
2823
if (namelen>21-3) return NULL; /* we know this cant be importable, the name is too long for blender! */
2794
2825
memcpy( txtname, name, namelen );
2795
2826
memcpy( &txtname[namelen], ".py", 4 );
2797
text = ( Text * ) & ( G.main->text.first );
2800
if( !strcmp( txtname, GetName( text ) ) )
2828
for(text = G.main->text.first; text; text = text->id.next) {
2829
if( !strcmp( txtname, text->id.name+2 ) )
2802
text = text->id.next;
2810
2836
if( !text->compiled ) {
2811
2837
buf = txt_to_buf( text );
2813
Py_CompileString( buf, GetName( text ),
2838
text->compiled = Py_CompileString( buf, text->id.name+2, Py_file_input );
2815
2839
MEM_freeN( buf );
2817
2841
if( PyErr_Occurred( ) ) {
2818
2842
PyErr_Print( );
2819
2843
BPY_free_compiled_text( text );
2826
2848
return PyImport_ExecCodeModule( name, text->compiled );
2830
2852
{"blimport", blender_import, METH_VARARGS, "our own import"}
2833
PyObject *blender_import( PyObject * self, PyObject * args )
2855
static PyObject *blender_import( PyObject * self, PyObject * args )
2835
2857
PyObject *exception, *err, *tb;
2837
2859
PyObject *globals = NULL, *locals = NULL, *fromlist = NULL;
2861
//PyObject_Print(args, stderr, 0);
2862
#if (PY_VERSION_HEX >= 0x02060000)
2863
int dummy_val; /* what does this do?*/
2865
if( !PyArg_ParseTuple( args, "s|OOOi:bimport",
2866
&name, &globals, &locals, &fromlist, &dummy_val) )
2840
2869
if( !PyArg_ParseTuple( args, "s|OOO:bimport",
2841
2870
&name, &globals, &locals, &fromlist ) )
2844
2873
m = PyImport_ImportModuleEx( name, globals, locals, fromlist );
2893
2922
/* look up the text object */
2894
2923
text = ( Text * ) & ( G.main->text.first );
2895
2924
while( text ) {
2896
if( !strcmp( txtname, GetName( text ) ) )
2925
if( !strcmp( txtname, text->id.name+2 ) )
2898
2927
text = text->id.next;
2911
2940
/* compile the buffer */
2912
2941
buf = txt_to_buf( text );
2913
text->compiled = Py_CompileString( buf, GetName( text ),
2942
text->compiled = Py_CompileString( buf, text->id.name+2, Py_file_input );
2915
2943
MEM_freeN( buf );
2917
2945
/* if compile failed.... return this error */
2963
2991
{"blreload", blender_reload, METH_VARARGS, "our own reload"}
2966
void init_ourReload( void )
2994
static void init_ourReload( void )
2968
2996
PyObject *m, *d;
2969
2997
PyObject *reload = PyCFunction_New( breload, NULL );