-- epydoc Documentation for eeshlo's Noise module + small typo fix in Noise.c
-- BPY_end_python closes .blend file opened by Library module when script doesn't do it by itself.
This commit is contained in:
Willian Padovani Germano
2004-04-25 14:43:21 +00:00
parent 395c1152c8
commit 2d24298b91
7 changed files with 754 additions and 397 deletions

View File

@@ -17,7 +17,7 @@
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
* All rights reserved.
@@ -72,216 +72,219 @@
#include "api2_2x/constant.h"
/* bpy_registryDict is declared in api2_2x/Registry.h and defined
* here. This Python dictionary will be used to store data that scripts
* here. This Python dictionary will be used to store data that scripts
* choose to preserve after they are executed, so user changes can be
* restored next time the script is used. Check the Blender.Registry module. */
extern PyObject *bpy_registryDict;
/*****************************************************************************/
/* Structure definitions */
/* Structure definitions */
/*****************************************************************************/
#define FILENAME_LENGTH 24
typedef struct _ScriptError {
char filename[FILENAME_LENGTH];
int lineno;
char filename[FILENAME_LENGTH];
int lineno;
} ScriptError;
/*****************************************************************************/
/* Global variables */
/* Global variables */
/*****************************************************************************/
ScriptError g_script_error;
/*****************************************************************************/
/* Function prototypes */
/* Function prototypes */
/*****************************************************************************/
PyObject *RunPython(Text *text, PyObject *globaldict);
char *GetName(Text *text);
char *GetName(Text *text);
PyObject *CreateGlobalDictionary (void);
void ReleaseGlobalDictionary (PyObject * dict);
void DoAllScriptsFromList (ListBase * list, short event);
void ReleaseGlobalDictionary (PyObject * dict);
void DoAllScriptsFromList (ListBase * list, short event);
PyObject *importText(char *name);
void init_ourImport(void);
PyObject *blender_import(PyObject *self, PyObject *args);
/*****************************************************************************/
/* Description: This function will initialise Python and all the implemented */
/* api variations. */
/* Notes: Currently only the api for 2.2x will be initialised. */
/* api variations. */
/* Notes: Currently only the api for 2.2x will be initialised. */
/*****************************************************************************/
void BPY_start_python(void)
{
bpy_registryDict = PyDict_New(); /* check comment at start of this file */
bpy_registryDict = PyDict_New(); /* check comment at start of this file */
if (!bpy_registryDict)
printf("Error: Couldn't create the Registry Python Dictionary!");
if (!bpy_registryDict)
printf("Error: Couldn't create the Registry Python Dictionary!");
/* TODO: Shouldn't "blender" be replaced by PACKAGE ?? (config.h) */
Py_SetProgramName("blender");
Py_SetProgramName("blender");
Py_Initialize ();
Py_Initialize ();
init_ourImport ();
init_ourImport ();
initBlenderApi2_2x ();
initBlenderApi2_2x ();
init_syspath();
init_syspath();
return;
return;
}
/*****************************************************************************/
/* Description: This function will terminate the Python interpreter */
/* Description: This function will terminate the Python interpreter */
/*****************************************************************************/
void BPY_end_python(void)
{
if (bpy_registryDict) {
Py_DECREF (bpy_registryDict);
bpy_registryDict = NULL;
}
if (bpy_registryDict) {
Py_DECREF (bpy_registryDict);
bpy_registryDict = NULL;
}
Py_Finalize();
Py_Finalize();
BPyMenu_RemoveAllEntries(); /* freeing bpymenu mem */
return;
/* a script might've opened a .blend file but didn't close it, so: */
EXPP_Library_Close();
return;
}
void syspath_append(char *dirname)
{
PyObject *mod_sys, *dict, *path, *dir;
PyObject *mod_sys, *dict, *path, *dir;
PyErr_Clear();
PyErr_Clear();
dir = Py_BuildValue("s", dirname);
mod_sys = PyImport_ImportModule("sys"); /* new ref */
dict = PyModule_GetDict(mod_sys); /* borrowed ref */
path = PyDict_GetItemString(dict, "path"); /* borrowed ref */
mod_sys = PyImport_ImportModule("sys"); /* new ref */
dict = PyModule_GetDict(mod_sys); /* borrowed ref */
path = PyDict_GetItemString(dict, "path"); /* borrowed ref */
if (!PyList_Check(path)) return;
if (!PyList_Check(path)) return;
PyList_Append(path, dir);
PyList_Append(path, dir);
if (PyErr_Occurred()) Py_FatalError("could not build sys.path");
if (PyErr_Occurred()) Py_FatalError("could not build sys.path");
Py_DECREF(mod_sys);
Py_DECREF(mod_sys);
}
void init_syspath(void)
{
PyObject *path;
PyObject *mod, *d;
PyObject *p;
char *c, *progname;
char execdir[FILE_MAXDIR + FILE_MAXFILE];/*defines from DNA_space_types.h*/
PyObject *path;
PyObject *mod, *d;
PyObject *p;
char *c, *progname;
char execdir[FILE_MAXDIR + FILE_MAXFILE];/*defines from DNA_space_types.h*/
int n;
int n;
path = Py_BuildValue("s", bprogname);
path = Py_BuildValue("s", bprogname);
mod = PyImport_ImportModule("Blender.sys");
mod = PyImport_ImportModule("Blender.sys");
if (mod) {
d = PyModule_GetDict(mod);
PyDict_SetItemString(d, "progname", path);
Py_DECREF(mod);
}
else
printf("Warning: could not set Blender.sys.progname\n");
if (mod) {
d = PyModule_GetDict(mod);
PyDict_SetItemString(d, "progname", path);
Py_DECREF(mod);
}
else
printf("Warning: could not set Blender.sys.progname\n");
progname = BLI_last_slash(bprogname); /* looks for the last dir separator */
progname = BLI_last_slash(bprogname); /* looks for the last dir separator */
c = Py_GetPath(); /* get python system path */
PySys_SetPath(c); /* initialize */
c = Py_GetPath(); /* get python system path */
PySys_SetPath(c); /* initialize */
n = progname - bprogname;
if (n > 0) {
strncpy(execdir, bprogname, n);
if (execdir[n-1] == '.') n--; /*fix for when run as ./blender */
execdir[n] = '\0';
n = progname - bprogname;
if (n > 0) {
strncpy(execdir, bprogname, n);
if (execdir[n-1] == '.') n--; /*fix for when run as ./blender */
execdir[n] = '\0';
syspath_append(execdir); /* append to module search path */
syspath_append(execdir); /* append to module search path */
/* set Blender.sys.progname */
}
else
printf ("Warning: could not determine argv[0] path\n");
/* set Blender.sys.progname */
}
else
printf ("Warning: could not determine argv[0] path\n");
/*
* bring in the site module so we can add
* site-package dirs to sys.path
*/
/*
* bring in the site module so we can add
* site-package dirs to sys.path
*/
mod = PyImport_ImportModule("site"); /* new ref */
mod = PyImport_ImportModule("site"); /* new ref */
if (mod) {
PyObject* item;
int size = 0;
int index;
if (mod) {
PyObject* item;
int size = 0;
int index;
/* get the value of 'sitedirs' from the module */
/* get the value of 'sitedirs' from the module */
/* the ref man says GetDict() never fails!!! */
d = PyModule_GetDict (mod); /* borrowed ref */
p = PyDict_GetItemString (d, "sitedirs"); /* borrowed ref */
/* the ref man says GetDict() never fails!!! */
d = PyModule_GetDict (mod); /* borrowed ref */
p = PyDict_GetItemString (d, "sitedirs"); /* borrowed ref */
if( p ) { /* we got our string */
/* append each item in sitedirs list to path */
size = PyList_Size (p);
if( p ) { /* we got our string */
/* append each item in sitedirs list to path */
size = PyList_Size (p);
for (index = 0; index < size; index++) {
item = PySequence_GetItem (p, index); /* new ref */
for (index = 0; index < size; index++) {
item = PySequence_GetItem (p, index); /* new ref */
if( item )
syspath_append (PyString_AsString(item));
}
}
Py_DECREF(mod);
}
else { /* import 'site' failed */
PyErr_Clear();
printf("sys_init:warning - no sitedirs added from site module.\n");
}
syspath_append (PyString_AsString(item));
}
}
Py_DECREF(mod);
}
else { /* import 'site' failed */
PyErr_Clear();
printf("sys_init:warning - no sitedirs added from site module.\n");
}
/*
* initialize the sys module
* set sys.executable to the Blender exe
* set argv[0] to the Blender exe
*/
/*
* initialize the sys module
* set sys.executable to the Blender exe
* set argv[0] to the Blender exe
*/
mod = PyImport_ImportModule("sys"); /* new ref */
mod = PyImport_ImportModule("sys"); /* new ref */
if (mod) {
d = PyModule_GetDict(mod); /* borrowed ref */
PyDict_SetItemString(d, "executable", Py_BuildValue("s", bprogname));
/* in the future this can be extended to have more argv's if needed: */
PyDict_SetItemString(d, "argv", Py_BuildValue("[s]", bprogname));
Py_DECREF(mod);
}
if (mod) {
d = PyModule_GetDict(mod); /* borrowed ref */
PyDict_SetItemString(d, "executable", Py_BuildValue("s", bprogname));
/* in the future this can be extended to have more argv's if needed: */
PyDict_SetItemString(d, "argv", Py_BuildValue("[s]", bprogname));
Py_DECREF(mod);
}
}
/*****************************************************************************/
/* Description: This function finishes Python initialization in Blender. */
/* Because U.pythondir (user defined dir for scripts) isn't */
/* initialized when BPY_start_Python needs to be executed, we */
/* postpone adding U.pythondir to sys.path and also BPyMenus */
/* (mechanism to register scripts in Blender menus) for when */
/* that dir info is available. */
/* Description: This function finishes Python initialization in Blender. */
/* Because U.pythondir (user defined dir for scripts) isn't */
/* initialized when BPY_start_Python needs to be executed, we */
/* postpone adding U.pythondir to sys.path and also BPyMenus */
/* (mechanism to register scripts in Blender menus) for when */
/* that dir info is available. */
/*****************************************************************************/
void BPY_post_start_python(void)
{
if (U.pythondir && U.pythondir[0] != '\0')
syspath_append(U.pythondir); /* append to module search path */
if (U.pythondir && U.pythondir[0] != '\0')
syspath_append(U.pythondir); /* append to module search path */
BPyMenu_Init(0); /* get dynamic menus (registered scripts) data */
}
/*****************************************************************************/
/* Description: This function will return the linenumber on which an error */
/* has occurred in the Python script. */
/* Description: This function will return the linenumber on which an error */
/* has occurred in the Python script. */
/*****************************************************************************/
int BPY_Err_getLinenumber(void)
{
return g_script_error.lineno;
return g_script_error.lineno;
}
/*****************************************************************************/
@@ -289,112 +292,112 @@ int BPY_Err_getLinenumber(void)
/*****************************************************************************/
const char *BPY_Err_getFilename(void)
{
return g_script_error.filename;
return g_script_error.filename;
}
/*****************************************************************************/
/* Description: Return PyString filename from a traceback object */
/* Description: Return PyString filename from a traceback object */
/*****************************************************************************/
PyObject *traceback_getFilename(PyObject *tb)
{
PyObject *v;
PyObject *v;
/* co_filename is in f_code, which is in tb_frame, which is in tb */
v = PyObject_GetAttrString(tb, "tb_frame"); Py_XDECREF(v);
v = PyObject_GetAttrString(v, "f_code"); Py_XDECREF(v);
v = PyObject_GetAttrString(v, "co_filename");
v = PyObject_GetAttrString(tb, "tb_frame"); Py_XDECREF(v);
v = PyObject_GetAttrString(v, "f_code"); Py_XDECREF(v);
v = PyObject_GetAttrString(v, "co_filename");
return v;
return v;
}
/*****************************************************************************/
/* Description: Blender Python error handler. This catches the error and */
/* stores filename and line number in a global */
/* Description: Blender Python error handler. This catches the error and */
/* stores filename and line number in a global */
/*****************************************************************************/
void BPY_Err_Handle(char *script_name)
{
PyObject *exception, *err, *tb, *v;
PyObject *exception, *err, *tb, *v;
if (!script_name) {
printf("Error: script has NULL name\n");
return;
}
PyErr_Fetch(&exception, &err, &tb);
PyErr_Fetch(&exception, &err, &tb);
if (!exception && !tb) {
printf("FATAL: spurious exception\n");
return;
}
if (!exception && !tb) {
printf("FATAL: spurious exception\n");
return;
}
strcpy(g_script_error.filename, script_name);
strcpy(g_script_error.filename, script_name);
if (exception && PyErr_GivenExceptionMatches(exception, PyExc_SyntaxError)) {
/* no traceback available when SyntaxError */
PyErr_Restore(exception, err, tb); /* takes away reference! */
PyErr_Print();
v = PyObject_GetAttrString(err, "lineno");
g_script_error.lineno = PyInt_AsLong(v);
Py_XDECREF(v);
/* this avoids an abort in Python 2.3's garbage collecting: */
PyErr_Clear();
return;
} else {
PyErr_NormalizeException(&exception, &err, &tb);
PyErr_Restore(exception, err, tb); // takes away reference!
PyErr_Print();
tb = PySys_GetObject("last_traceback");
if (exception && PyErr_GivenExceptionMatches(exception, PyExc_SyntaxError)) {
/* no traceback available when SyntaxError */
PyErr_Restore(exception, err, tb); /* takes away reference! */
PyErr_Print();
v = PyObject_GetAttrString(err, "lineno");
g_script_error.lineno = PyInt_AsLong(v);
Py_XDECREF(v);
/* this avoids an abort in Python 2.3's garbage collecting: */
PyErr_Clear();
return;
} else {
PyErr_NormalizeException(&exception, &err, &tb);
PyErr_Restore(exception, err, tb); // takes away reference!
PyErr_Print();
tb = PySys_GetObject("last_traceback");
if (!tb) {
printf("\nCan't get traceback\n");
return;
}
if (!tb) {
printf("\nCan't get traceback\n");
return;
}
Py_INCREF(tb);
Py_INCREF(tb);
/* From old bpython BPY_main.c:
* 'check traceback objects and look for last traceback in the
* same text file. This is used to jump to the line of where the
* error occured. "If the error occured in another text file or module,
* the last frame in the current file is adressed."' */
* same text file. This is used to jump to the line of where the
* error occured. "If the error occured in another text file or module,
* the last frame in the current file is adressed."' */
while (1) {
v = PyObject_GetAttrString(tb, "tb_next");
while (1) {
v = PyObject_GetAttrString(tb, "tb_next");
if (v == Py_None || strcmp(PyString_AsString(traceback_getFilename(v)),
script_name)) {
break;
}
if (v == Py_None || strcmp(PyString_AsString(traceback_getFilename(v)),
script_name)) {
break;
}
Py_DECREF(tb);
tb = v;
}
Py_DECREF(tb);
tb = v;
}
v = PyObject_GetAttrString(tb, "tb_lineno");
g_script_error.lineno = PyInt_AsLong(v);
Py_XDECREF(v);
v = traceback_getFilename(tb);
strncpy(g_script_error.filename, PyString_AsString(v), FILENAME_LENGTH);
Py_XDECREF(v);
Py_DECREF(tb);
}
v = PyObject_GetAttrString(tb, "tb_lineno");
g_script_error.lineno = PyInt_AsLong(v);
Py_XDECREF(v);
v = traceback_getFilename(tb);
strncpy(g_script_error.filename, PyString_AsString(v), FILENAME_LENGTH);
Py_XDECREF(v);
Py_DECREF(tb);
}
return;
return;
}
/*****************************************************************************/
/* Description: This function executes the script passed by st. */
/* Notes: It is called by blender/src/drawtext.c when a Blender user */
/* presses ALT+PKEY in the script's text window. */
/* Description: This function executes the script passed by st. */
/* Notes: It is called by blender/src/drawtext.c when a Blender user */
/* presses ALT+PKEY in the script's text window. */
/*****************************************************************************/
int BPY_txt_do_python_Text(struct Text* text)
{
PyObject *py_dict, *py_result;
PyObject *py_dict, *py_result;
BPy_constant *info;
Script *script = G.main->script.first;
if (!text) return 0;
if (!text) return 0;
/* check if this text is already running */
while (script) {
@@ -435,19 +438,19 @@ int BPY_txt_do_python_Text(struct Text* text)
PyDict_SetItemString(py_dict, "__script__", (PyObject *)info);
}
clearScriptLinks ();
clearScriptLinks ();
py_result = RunPython (text, py_dict); /* Run the script */
py_result = RunPython (text, py_dict); /* Run the script */
if (!py_result) { /* Failed execution of the script */
BPY_Err_Handle(GetName(text));
BPY_Err_Handle(GetName(text));
ReleaseGlobalDictionary(py_dict);
free_libblock(&G.main->script, script);
//BPY_end_python();
//BPY_start_python();
//BPY_end_python();
//BPY_start_python();
return 0;
return 0;
}
else {
Py_DECREF (py_result);
@@ -459,14 +462,14 @@ int BPY_txt_do_python_Text(struct Text* text)
}
}
return 1; /* normal return */
return 1; /* normal return */
}
/*****************************************************************************/
/* Description: The original function of this name has been refactored */
/* into BPY_txt_do_python_Text. That version is needed for the command */
/* line support for Python. This is here to keep the interface the */
/* same and reduce code changes elsewhere. */
/* Description: The original function of this name has been refactored */
/* into BPY_txt_do_python_Text. That version is needed for the command */
/* line support for Python. This is here to keep the interface the */
/* same and reduce code changes elsewhere. */
/*****************************************************************************/
int BPY_txt_do_python(struct SpaceText* st)
{
@@ -486,14 +489,14 @@ void BPY_run_python_script(char *fn)
return;
}
text = add_text(fn);
if (text == NULL) {
text = add_text(fn);
if (text == NULL) {
printf("Error in BPY_run_python_script: couldn't create Blender text "
"from %s\n", fn);
// On Windows if I continue I just get a segmentation
// violation. To get a baseline file I exit here.
exit(2);
}
}
if (BPY_txt_do_python_Text(text) != 1) {
printf( "\nError executing Python script:\n"
@@ -504,15 +507,15 @@ void BPY_run_python_script(char *fn)
}
/*****************************************************************************/
/* Description: This function executes the script chosen from a menu. */
/* Notes: It is called by the ui code in src/header_???.c when a user */
/* clicks on a menu entry that refers to a script. */
/* Scripts are searched in the BPyMenuTable, using the given */
/* menutype and event values to know which one was chosen. */
/* Description: This function executes the script chosen from a menu. */
/* Notes: It is called by the ui code in src/header_???.c when a user */
/* clicks on a menu entry that refers to a script. */
/* Scripts are searched in the BPyMenuTable, using the given */
/* menutype and event values to know which one was chosen. */
/*****************************************************************************/
int BPY_menu_do_python(short menutype, int event)
{
PyObject *py_dict, *py_res, *pyarg = NULL;
PyObject *py_dict, *py_res, *pyarg = NULL;
BPy_constant *info;
BPyMenu *pym;
BPySubMenu *pysm;
@@ -596,7 +599,7 @@ int BPY_menu_do_python(short menutype, int event)
PyDict_SetItemString(py_dict, "__script__", (PyObject *)info);
}
clearScriptLinks ();
clearScriptLinks ();
/* Previously we used PyRun_File to run directly the code on a FILE object,
* but as written in the Python/C API Ref Manual, chapter 2,
@@ -643,15 +646,15 @@ int BPY_menu_do_python(short menutype, int event)
if (!py_res) { /* Failed execution of the script */
BPY_Err_Handle(script->id.name+2);
BPY_Err_Handle(script->id.name+2);
PyErr_Print();
ReleaseGlobalDictionary(py_dict);
free_libblock(&G.main->script, script);
// BPY_end_python();
// BPY_start_python();
// BPY_end_python();
// BPY_start_python();
error ("Python script error: check console");
return 0;
return 0;
}
else {
Py_DECREF (py_res);
@@ -673,24 +676,24 @@ int BPY_menu_do_python(short menutype, int event)
}
}
return 1; /* normal return */
return 1; /* normal return */
}
/*****************************************************************************/
/* Description: */
/* Notes: */
/* Description: */
/* Notes: */
/*****************************************************************************/
void BPY_free_compiled_text(struct Text* text)
{
if (!text->compiled) return;
Py_DECREF((PyObject*) text->compiled);
text->compiled = NULL;
if (!text->compiled) return;
Py_DECREF((PyObject*) text->compiled);
text->compiled = NULL;
return;
return;
}
/*****************************************************************************/
/* Description: This function frees a finished (flags == 0) script. */
/* Description: This function frees a finished (flags == 0) script. */
/*****************************************************************************/
void BPY_free_finished_script(Script *script)
{
@@ -743,8 +746,8 @@ void BPY_clear_script (Script *script)
dict = script->py_globaldict;
if (dict) {
PyDict_Clear (dict);
Py_DECREF (dict); /* Release dictionary. */
PyDict_Clear (dict);
Py_DECREF (dict); /* Release dictionary. */
script->py_globaldict = NULL;
}
@@ -752,305 +755,305 @@ void BPY_clear_script (Script *script)
}
/*****************************************************************************/
/* ScriptLinks */
/* ScriptLinks */
/*****************************************************************************/
/*****************************************************************************/
/* Description: */
/* Notes: Not implemented yet */
/* Description: */
/* Notes: Not implemented yet */
/*****************************************************************************/
void BPY_clear_bad_scriptlinks(struct Text *byebye)
{
/*
BPY_clear_bad_scriptlist(getObjectList(), byebye);
BPY_clear_bad_scriptlist(getLampList(), byebye);
BPY_clear_bad_scriptlist(getCameraList(), byebye);
BPY_clear_bad_scriptlist(getMaterialList(), byebye);
BPY_clear_bad_scriptlist(getWorldList(), byebye);
BPY_clear_bad_scriptlink(&scene_getCurrent()->id, byebye);
BPY_clear_bad_scriptlist(getObjectList(), byebye);
BPY_clear_bad_scriptlist(getLampList(), byebye);
BPY_clear_bad_scriptlist(getCameraList(), byebye);
BPY_clear_bad_scriptlist(getMaterialList(), byebye);
BPY_clear_bad_scriptlist(getWorldList(), byebye);
BPY_clear_bad_scriptlink(&scene_getCurrent()->id, byebye);
allqueue(REDRAWBUTSSCRIPT, 0);
allqueue(REDRAWBUTSSCRIPT, 0);
*/
return;
return;
}
/*****************************************************************************/
/* Description: Loop through all scripts of a list of object types, and */
/* execute these scripts. */
/* For the scene, only the current active scene the scripts are */
/* executed (if any). */
/* Description: Loop through all scripts of a list of object types, and */
/* execute these scripts. */
/* For the scene, only the current active scene the scripts are */
/* executed (if any). */
/*****************************************************************************/
void BPY_do_all_scripts(short event)
{
DoAllScriptsFromList (&(G.main->object), event);
DoAllScriptsFromList (&(G.main->lamp), event);
DoAllScriptsFromList (&(G.main->camera), event);
DoAllScriptsFromList (&(G.main->mat), event);
DoAllScriptsFromList (&(G.main->world), event);
DoAllScriptsFromList (&(G.main->object), event);
DoAllScriptsFromList (&(G.main->lamp), event);
DoAllScriptsFromList (&(G.main->camera), event);
DoAllScriptsFromList (&(G.main->mat), event);
DoAllScriptsFromList (&(G.main->world), event);
BPY_do_pyscript (&(G.scene->id), event);
BPY_do_pyscript (&(G.scene->id), event);
return;
return;
}
/*****************************************************************************/
/* Description: Execute a Python script when an event occurs. The following */
/* events are possible: frame changed, load script and redraw. */
/* Only events happening to one of the following object types */
/* are handled: Object, Lamp, Camera, Material, World and */
/* Scene. */
/* events are possible: frame changed, load script and redraw. */
/* Only events happening to one of the following object types */
/* are handled: Object, Lamp, Camera, Material, World and */
/* Scene. */
/*****************************************************************************/
void BPY_do_pyscript(struct ID *id, short event)
{
ScriptLink * scriptlink;
int index;
PyObject * dict;
PyObject * ret;
ScriptLink * scriptlink;
int index;
PyObject * dict;
PyObject * ret;
scriptlink = setScriptLinks (id, event);
scriptlink = setScriptLinks (id, event);
if (scriptlink == NULL) return;
if (scriptlink == NULL) return;
for (index = 0; index < scriptlink->totscript; index++)
{
if ((scriptlink->flag[index] == event) &&
(scriptlink->scripts[index] != NULL))
{
dict = CreateGlobalDictionary();
ret = RunPython ((Text*) scriptlink->scripts[index], dict);
ReleaseGlobalDictionary (dict);
if (!ret)
{
/* Failed execution of the script */
BPY_Err_Handle (scriptlink->scripts[index]->name+2);
BPY_end_python ();
BPY_start_python ();
}
else
{
Py_DECREF (ret);
}
}
}
for (index = 0; index < scriptlink->totscript; index++)
{
if ((scriptlink->flag[index] == event) &&
(scriptlink->scripts[index] != NULL))
{
dict = CreateGlobalDictionary();
ret = RunPython ((Text*) scriptlink->scripts[index], dict);
ReleaseGlobalDictionary (dict);
if (!ret)
{
/* Failed execution of the script */
BPY_Err_Handle (scriptlink->scripts[index]->name+2);
BPY_end_python ();
BPY_start_python ();
}
else
{
Py_DECREF (ret);
}
}
}
return;
return;
}
/*****************************************************************************/
/* Description: */
/* Notes: */
/* Description: */
/* Notes: */
/*****************************************************************************/
void BPY_free_scriptlink(struct ScriptLink *slink)
{
if (slink->totscript) {
if(slink->flag) MEM_freeN(slink->flag);
if(slink->scripts) MEM_freeN(slink->scripts);
}
if (slink->totscript) {
if(slink->flag) MEM_freeN(slink->flag);
if(slink->scripts) MEM_freeN(slink->scripts);
}
return;
return;
}
/*****************************************************************************/
/* Description: */
/* Notes: */
/* Description: */
/* Notes: */
/*****************************************************************************/
void BPY_copy_scriptlink(struct ScriptLink *scriptlink)
{
void *tmp;
void *tmp;
if (scriptlink->totscript) {
if (scriptlink->totscript) {
tmp = scriptlink->scripts;
scriptlink->scripts =
MEM_mallocN(sizeof(ID*)*scriptlink->totscript, "scriptlistL");
memcpy(scriptlink->scripts, tmp, sizeof(ID*)*scriptlink->totscript);
tmp = scriptlink->scripts;
scriptlink->scripts =
MEM_mallocN(sizeof(ID*)*scriptlink->totscript, "scriptlistL");
memcpy(scriptlink->scripts, tmp, sizeof(ID*)*scriptlink->totscript);
tmp = scriptlink->flag;
scriptlink->flag =
MEM_mallocN(sizeof(short)*scriptlink->totscript, "scriptlistF");
memcpy(scriptlink->flag, tmp, sizeof(short)*scriptlink->totscript);
}
tmp = scriptlink->flag;
scriptlink->flag =
MEM_mallocN(sizeof(short)*scriptlink->totscript, "scriptlistF");
memcpy(scriptlink->flag, tmp, sizeof(short)*scriptlink->totscript);
}
return;
return;
}
/*****************************************************************************/
/* Description: */
/* Notes: Not implemented yet */
/* Description: */
/* Notes: Not implemented yet */
/*****************************************************************************/
int BPY_call_importloader(char *name)
{ /* XXX Should this function go away from Blender? */
printf ("In BPY_call_importloader(name=%s)\n",name);
return (0);
printf ("In BPY_call_importloader(name=%s)\n",name);
return (0);
}
/*****************************************************************************/
/* Private functions */
/* Private functions */
/*****************************************************************************/
/*****************************************************************************/
/* Description: This function executes the python script passed by text. */
/* The Python dictionary containing global variables needs to */
/* be passed in globaldict. */
/* Description: This function executes the python script passed by text. */
/* The Python dictionary containing global variables needs to */
/* be passed in globaldict. */
/*****************************************************************************/
PyObject * RunPython(Text *text, PyObject *globaldict)
{
char *buf = NULL;
char *buf = NULL;
/* The script text is compiled to Python bytecode and saved at text->compiled
* to speed-up execution if the user executes the script multiple times */
if (!text->compiled) { /* if it wasn't already compiled, do it now */
buf = txt_to_buf(text);
if (!text->compiled) { /* if it wasn't already compiled, do it now */
buf = txt_to_buf(text);
text->compiled = Py_CompileString(buf, GetName(text), Py_file_input);
text->compiled = Py_CompileString(buf, GetName(text), Py_file_input);
MEM_freeN(buf);
MEM_freeN(buf);
if (PyErr_Occurred()) {
BPY_free_compiled_text(text);
return NULL;
}
if (PyErr_Occurred()) {
BPY_free_compiled_text(text);
return NULL;
}
}
}
return PyEval_EvalCode(text->compiled, globaldict, globaldict);
return PyEval_EvalCode(text->compiled, globaldict, globaldict);
}
/*****************************************************************************/
/* Description: This function returns the value of the name field of the */
/* given Text struct. */
/* Description: This function returns the value of the name field of the */
/* given Text struct. */
/*****************************************************************************/
char * GetName(Text *text)
{
return (text->id.name+2);
return (text->id.name+2);
}
/*****************************************************************************/
/* Description: This function creates a new Python dictionary object. */
/* Description: This function creates a new Python dictionary object. */
/*****************************************************************************/
PyObject * CreateGlobalDictionary (void)
{
PyObject *dict = PyDict_New();
PyObject *dict = PyDict_New();
PyDict_SetItemString (dict, "__builtins__", PyEval_GetBuiltins());
PyDict_SetItemString (dict, "__name__", PyString_FromString("__main__"));
PyDict_SetItemString (dict, "__builtins__", PyEval_GetBuiltins());
PyDict_SetItemString (dict, "__name__", PyString_FromString("__main__"));
return dict;
return dict;
}
/*****************************************************************************/
/* Description: This function deletes a given Python dictionary object. */
/* Description: This function deletes a given Python dictionary object. */
/*****************************************************************************/
void ReleaseGlobalDictionary (PyObject * dict)
{
PyDict_Clear (dict);
Py_DECREF (dict); /* Release dictionary. */
PyDict_Clear (dict);
Py_DECREF (dict); /* Release dictionary. */
return;
return;
}
/*****************************************************************************/
/* Description: This function runs all scripts (if any) present in the */
/* list argument. The event by which the function has been */
/* called, is passed in the event argument. */
/* Description: This function runs all scripts (if any) present in the */
/* list argument. The event by which the function has been */
/* called, is passed in the event argument. */
/*****************************************************************************/
void DoAllScriptsFromList (ListBase *list, short event)
{
ID *id;
ID *id;
id = list->first;
id = list->first;
while (id != NULL) {
BPY_do_pyscript (id, event);
id = id->next;
}
while (id != NULL) {
BPY_do_pyscript (id, event);
id = id->next;
}
return;
return;
}
PyObject *importText(char *name)
{
Text *text;
char *txtname;
char *buf = NULL;
int namelen = strlen(name);
Text *text;
char *txtname;
char *buf = NULL;
int namelen = strlen(name);
txtname = malloc(namelen+3+1);
if (!txtname) return NULL;
txtname = malloc(namelen+3+1);
if (!txtname) return NULL;
memcpy(txtname, name, namelen);
memcpy(&txtname[namelen], ".py", 4);
memcpy(txtname, name, namelen);
memcpy(&txtname[namelen], ".py", 4);
text = (Text*) &(G.main->text.first);
text = (Text*) &(G.main->text.first);
while(text) {
if (!strcmp (txtname, GetName(text)))
break;
text = text->id.next;
}
while(text) {
if (!strcmp (txtname, GetName(text)))
break;
text = text->id.next;
}
if (!text) {
free(txtname);
return NULL;
}
if (!text) {
free(txtname);
return NULL;
}
if (!text->compiled) {
buf = txt_to_buf(text);
text->compiled = Py_CompileString(buf, GetName(text), Py_file_input);
MEM_freeN(buf);
if (!text->compiled) {
buf = txt_to_buf(text);
text->compiled = Py_CompileString(buf, GetName(text), Py_file_input);
MEM_freeN(buf);
if (PyErr_Occurred()) {
PyErr_Print();
BPY_free_compiled_text(text);
free(txtname);
return NULL;
}
}
if (PyErr_Occurred()) {
PyErr_Print();
BPY_free_compiled_text(text);
free(txtname);
return NULL;
}
}
free(txtname);
return PyImport_ExecCodeModule(name, text->compiled);
free(txtname);
return PyImport_ExecCodeModule(name, text->compiled);
}
static PyMethodDef bimport[] = {
{ "blimport", blender_import, METH_VARARGS, "our own import"}
{ "blimport", blender_import, METH_VARARGS, "our own import"}
};
PyObject *blender_import(PyObject *self, PyObject *args)
{
PyObject *exception, *err, *tb;
char *name;
PyObject *globals = NULL, *locals = NULL, *fromlist = NULL;
PyObject *m;
PyObject *exception, *err, *tb;
char *name;
PyObject *globals = NULL, *locals = NULL, *fromlist = NULL;
PyObject *m;
if (!PyArg_ParseTuple(args, "s|OOO:bimport",
&name, &globals, &locals, &fromlist))
return NULL;
if (!PyArg_ParseTuple(args, "s|OOO:bimport",
&name, &globals, &locals, &fromlist))
return NULL;
m = PyImport_ImportModuleEx(name, globals, locals, fromlist);
m = PyImport_ImportModuleEx(name, globals, locals, fromlist);
if (m)
return m;
else
PyErr_Fetch(&exception, &err, &tb); /*restore for probable later use*/
m = importText(name);
if (m) { /* found module, ignore above exception*/
PyErr_Clear();
Py_XDECREF(exception); Py_XDECREF(err); Py_XDECREF(tb);
printf("imported from text buffer...\n");
} else {
PyErr_Restore(exception, err, tb);
}
return m;
if (m)
return m;
else
PyErr_Fetch(&exception, &err, &tb); /*restore for probable later use*/
m = importText(name);
if (m) { /* found module, ignore above exception*/
PyErr_Clear();
Py_XDECREF(exception); Py_XDECREF(err); Py_XDECREF(tb);
printf("imported from text buffer...\n");
} else {
PyErr_Restore(exception, err, tb);
}
return m;
}
void init_ourImport(void)
{
PyObject *m, *d;
PyObject *import = PyCFunction_New(bimport, NULL);
PyObject *m, *d;
PyObject *import = PyCFunction_New(bimport, NULL);
m = PyImport_AddModule("__builtin__");
d = PyModule_GetDict(m);
PyDict_SetItemString(d, "__import__", import);
m = PyImport_AddModule("__builtin__");
d = PyModule_GetDict(m);
PyDict_SetItemString(d, "__import__", import);
}

View File

@@ -24,7 +24,7 @@
*
* This is a new part of Blender.
*
* Contributor(s): Michel Selten
* Contributor(s): Michel Selten, Willian P. Germano
*
* ***** END GPL/BL DUAL LICENSE BLOCK *****
*/
@@ -37,3 +37,4 @@ void initBlenderApi2_2x (void);
void clearScriptLinks (void);
ScriptLink * setScriptLinks(ID *id, short event);
void discardFromBDict (char *key);
void EXPP_Library_Close (void); /* in Library.c, used by BPY_end_python */

View File

@@ -175,6 +175,23 @@ PyObject *M_Library_Close(PyObject *self)
return Py_None;
}
/**
* helper function for 'atexit' clean-ups, used by BPY_end_python,
* declared in EXPP_interface.h.
*/
void EXPP_Library_Close(void)
{
if (bpy_openlib) {
BLO_blendhandle_close(bpy_openlib);
bpy_openlib = NULL;
}
if (bpy_openlibname) {
MEM_freeN (bpy_openlibname);
bpy_openlibname = NULL;
}
}
/**
* Get the filename of the currently open library file, if any.
*/

View File

@@ -1,3 +1,38 @@
/**
* $Id$
*
* Blender.Noise BPython module implementation.
* This submodule has functions to generate noise of various types.
*
* ***** BEGIN GPL/BL DUAL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version. The Blender
* Foundation also sells licenses for use in proprietary software under
* the Blender License. See http://www.blender.org/BL/ for information
* about this.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
* All rights reserved.
*
* This is a new part of Blender.
*
* Contributor(s): eeshlo
*
* ***** END GPL/BL DUAL LICENSE BLOCK *****
*/
/************************/
/* Blender Noise Module */
/************************/
@@ -520,7 +555,7 @@ PyObject *Noise_Init()
BPy_constant *dm = (BPy_constant *)DistanceMetrics;
constant_insert(dm, "DISTANCE", PyInt_FromLong(TEX_DISTANCE));
constant_insert(dm, "DISTANCE_SQUARED", PyInt_FromLong(TEX_DISTANCE_SQUARED));
constant_insert(dm, "MAHATTAN", PyInt_FromLong(TEX_MANHATTAN));
constant_insert(dm, "MANHATTAN", PyInt_FromLong(TEX_MANHATTAN));
constant_insert(dm, "CHEBYCHEV", PyInt_FromLong(TEX_CHEBYCHEV));
constant_insert(dm, "MINKOVSKY_HALF", PyInt_FromLong(TEX_MINKOVSKY_HALF));
constant_insert(dm, "MINKOVSKY_FOUR", PyInt_FromLong(TEX_MINKOVSKY_FOUR));

View File

@@ -29,11 +29,12 @@ The Blender Python API Reference
- L{Ipo}
- L{Lamp}
- L{Lattice}
- L{Library}
- L{Library} (new)
- L{Material}
- L{Mathutils}
- L{Mathutils} (new)
- L{Metaball}
- L{NMesh}
- L{Noise} (new)
- L{Object}
- L{Registry}
- L{Scene}
@@ -42,7 +43,7 @@ The Blender Python API Reference
- L{Types}
- L{Window}
- L{World}
- L{sys<Sys>}
- L{sys<Sys>} (added time function)
Introduction:
-------------
@@ -58,8 +59,8 @@ The Blender Python API Reference
open-source language.
@author: The Blender Python Team
@requires: Blender 2.32 or newer.
@version: 0.4
@requires: Blender 2.33 or newer.
@version: 2.33
@see: U{www.blender.org<http://www.blender.org>}
@see: U{projects.blender.org<http://projects.blender.org>}
@see: U{www.python.org<http://www.python.org>}

View File

@@ -25,10 +25,10 @@ Example::
groups = Library.LinkableGroups()
for db in groups:
print "\nDATABLOCK %s:" % db
print "DATABLOCK %s:" % db
for obname in Library.Datablocks(db):
print obname
if 'Object' in groups:
for obname in Library.Datablocks('Object'):
Library.Load(obname, 'Object', 0) # note the 0...

View File

@@ -0,0 +1,300 @@
# Blender.Noise submodule
"""
The Blender.Noise submodule.
Noise and Turbulence
====================
This module can be used to generate noise of various types. This can be used
for terrain generation, to create textures, make animations more 'animated',
object deformation, etc. As an example, this code segment when scriptlinked
to a framechanged event, will make the camera sway randomly about, by changing
parameters this can look like anything from an earthquake to a very nervous or
maybe even drunk cameraman... (the camera needs an ipo with at least one Loc &
Rot key for this to work!):
Example::
from Blender import Get, Scene, Noise
####################################################
# This controls jitter speed
sl = 0.025
# This controls the amount of position jitter
sp = 0.1
# This controls the amount of rotation jitter
sr = 0.25
####################################################
time = Get('curtime')
ob = Scene.GetCurrent().getCurrentCamera()
ps = (sl*time, sl*time, sl*time)
# To add jitter only when the camera moves, use this next line instead
#ps = (sl*ob.LocX, sl*ob.LocY, sl*ob.LocZ)
rv = Noise.vTurbulence(ps, 3, 0, Noise.NoiseTypes.NEWPERLIN)
ob.dloc = (sp*rv[0], sp*rv[1], sp*rv[2])
ob.drot = (sr*rv[0], sr*rv[1], sr*rv[2])
@type NoiseTypes: readonly dictionary
@var NoiseTypes: The available noise types.
- BLENDER
- STDPERLIN
- NEWPERLIN
- VORONOI_F1
- VORONOI_F2
- VORONOI_F3
- VORONOI_F4
- VORONOI_F2F1
- VORONOI_CRACKLE
- CELLNOISE
@type DistanceMetrics: readonly dictionary
@var DistanceMetrics: The available distance metrics values for Voronoi.
- DISTANCE
- DISTANCE_SQUARED
- MANHATTAN
- CHEBYCHEV
- MINKOVSKY_HALF
- MINKOVSKY_FOUR
- MINKOVISKY
"""
NoiseTypes = {'BLENDER':0, 'STDPERLIN':1}
DistanceMetrics = {'DISTANCE':0}
def random ():
"""
Returns a random floating point number."
@rtype: float
@return: a random number in [0, 1).
"""
def randuvec ():
"""
Returns a random unit vector.
@rtype: 3-float list
@return: a list of three floats.
"""
def setRandomSeed (seed):
"""
Initializes the random number generator.
@type seed: int
@param seed: the seed for the random number generator. If seed = 0, the
current time will be used as seed, instead.
"""
def noise (xyz, type = NoiseTypes['STDPERLIN']):
"""
Returns general noise of the optional specified type.
@type xyz: tuple of 3 floats
@param xyz: (x,y,z) float values.
@type type: int
@param type: the type of noise to return. See L{NoiseTypes}.
@rtype: float
@return: the generated noise value.
"""
def vNoise (xyz, type = NoiseTypes['STDPERLIN']):
"""
Returns noise vector of the optional specified type.
@type xyz: tuple of 3 floats
@param xyz: (x,y,z) float values.
@type type: int
@param type: the type of noise to return. See L{NoiseTypes}.
@rtype: 3-float list
@return: the generated noise vector.
"""
def turbulence (xyz, octaves, hard, basis = NoiseTypes['STDPERLIN'],
ampscale = 0.5, freqscale = 2.0):
"""
Returns general turbulence value using the optional specified noise 'basis'
function.
@type xyz: 3-float tuple
@param xyz: (x,y,z) float values.
@type octaves: int
@param octaves: number of noise values added.
@type hard: bool
@param hard: noise hardness: 0 - soft noise; 1 - hard noise. (Returned value
is always positive.)
@type basis: int
@param basis: type of noise used for turbulence, see L{NoiseTypes}.
@type ampscale: float
@param ampscale: amplitude scale value of the noise frequencies added.
@type freqscale: float
@param freqscale: frequency scale factor.
@rtype: float
@return: the generated turbulence value.
"""
def vTurbulence (xyz, octaves, hard, basis = NoiseTypes['STDPERLIN'],
ampscale = 0.5, freqscale = 2.0):
"""
Returns general turbulence vector using the optional specified noise basis
function.
@type xyz: 3-float tuple
@param xyz: (x,y,z) float values.
@type octaves: int
@param octaves: number of noise values added.
@type hard: bool
@param hard: noise hardness: 0 - soft noise; 1 - hard noise. (Returned
vector is always positive.)
@type basis: int
@param basis: type of noise used for turbulence, see L{NoiseTypes}.
@type ampscale: float
@param ampscale: amplitude scale value of the noise frequencies added.
@type freqscale: float
@param freqscale: frequency scale factor.
@rtype: 3-float list
@return: the generated turbulence vector.
"""
def fBm (xyz, H, lacunarity, octaves, basis = NoiseTypes['STDPERLIN']):
"""
Returns Fractal Brownian Motion noise value (fBm).
@type xyz: 3-float tuple
@param xyz: (x,y,z) float values.
@type H: float
@param H: the fractal increment parameter.
@type lacunarity: float
@param lacunarity: the gap between successive frequencies.
@type octaves: float
@param octaves: the number of frequencies in the fBm.
@type basis: int
@param basis: type of noise used for the turbulence, see L{NoiseTypes}.
@rtype: float
@return: the generated noise value.
"""
def multiFractal (xyz, H, lacunarity, octaves, basis = NoiseTypes['STDPERLIN']):
"""
Returns Multifractal noise value.
@type xyz: 3-float tuple
@param xyz: (x,y,z) float values.
@type H: float
@param H: the highest fractal dimension.
@type lacunarity: float
@param lacunarity: the gap between successive frequencies.
@type octaves: float
@param octaves: the number of frequencies in the fBm.
@type basis: int
@param basis: type of noise used for the turbulence, see L{NoiseTypes}.
@rtype: float
@return: the generated noise value.
"""
def vlNoise (xyz, distortion, type1 = NoiseTypes['STDPERLIN'],
type2 = NoiseTypes['STDPERLIN']):
"""
Returns Variable Lacunarity Noise value, a distorted variety of noise.
@type xyz: 3-float tuple
@param xyz: (x,y,z) float values.
@type distortion: float
@param distortion: the amount of distortion.
@type type1: int
@type type2: int
@param type1: sets the noise type to distort.
@param type2: sets the noise type used for the distortion.
@rtype: float
@return: the generated noise value.
"""
def heteroTerrain (xyz, H, lacunarity, octaves, offset,
basis = NoiseTypes['STDPERLIN']):
"""
Returns Heterogeneous Terrain value.
@type xyz: 3-float tuple
@param xyz: (x,y,z) float values.
@type H: float
@param H: fractal dimension of the roughest areas.
@type lacunarity: float
@param lacunarity: gap between successive frequencies.
@type octaves: float
@param octaves: number of frequencies in the fBm.
@type offset: float
@param offset: it raises the terrain from 'sea level'.
@type basis: int
@param basis: noise basis determines the type of noise used for the
turbulence, see L{NoiseTypes}.
@rtype: float
@return: the generated value.
"""
def hybridMFractal (xyz, H, lacunarity, octaves, offset, gain,
basis = NoiseTypes['STDPERLIN']):
"""
Returns Hybrid Multifractal value.
@type xyz: 3-float tuple
@param xyz: (x,y,z) float values.
@type H: float
@param H: fractal dimension of the roughest areas.
@type lacunarity: float
@param lacunarity: gap between successive frequencies.
@type octaves: float
@param octaves: number of frequencies in the fBm.
@type offset: float
@param offset: it raises the terrain from 'sea level'.
@type gain: float
@param gain: scale factor.
@type basis: int
@param basis: noise basis determines the type of noise used for the
turbulence, see L{NoiseTypes}.
@rtype: float
@return: the generated value.
"""
def ridgedMFractal (xyz, H, lacunarity, octaves, offset, gain,
basis = NoiseTypes['STDPERLIN']):
"""
Returns Ridged Multifractal value.
@type xyz: 3-float tuple
@param xyz: (x,y,z) float values.
@type H: float
@param H: fractal dimension of the roughest areas.
@type lacunarity: float
@param lacunarity: gap between successive frequencies.
@type octaves: float
@param octaves: number of frequencies in the fBm.
@type offset: float
@param offset: it raises the terrain from 'sea level'.
@type gain: float
@param gain: scale factor.
@type basis: int
@param basis: noise basis determines the type of noise used for the
turbulence, see L{NoiseTypes}.
@rtype: float
@return: the generated value.
"""
def voronoi(xyz, distance_metric = DistanceMetrics['DISTANCE'], exponent = 2.5):
"""
Returns Voronoi diagrams-related data.
@type xyz: 3-float tuple
@param xyz: (x,y,z) float values.
@type distance_metric: int
@param distance_metric: see L{DistanceMetrics}
@type exponent: float
@param exponent: only used with MINKOVSKY, default is 2.5.
@rtype: list
@return: a list containing a list of distances in order of closest feature,
and a list containing the positions of the four closest features.
"""
def cellNoise (xyz):
"""
Returns cellnoise.
@type xyz: 3-float tuple
@param xyz: (x,y,z) float values.
@rtype: float
@return: the generated value.
"""
def cellNoiseV (xyz):
"""
Returns cellnoise vector/point/color.
@type xyz: 3-float tuple
@param xyz: (x,y,z) float values.
@rtype: 3-float list
@return: the generated vector.
"""