Welcome to mirror list, hosted at ThFree Co, Russian Federation.

git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
Diffstat (limited to 'source/blender/python')
-rw-r--r--source/blender/python/BPY_extern.h6
-rw-r--r--source/blender/python/CMakeLists.txt1
-rw-r--r--source/blender/python/Makefile2
-rw-r--r--source/blender/python/SConscript7
-rw-r--r--source/blender/python/doc/epy/Geometry.py4
-rw-r--r--source/blender/python/doc/epy/Mathutils.py2
-rw-r--r--source/blender/python/doc/examples/Mathutils.Euler.py3
-rw-r--r--source/blender/python/doc/examples/Mathutils.Matrix.py3
-rw-r--r--source/blender/python/doc/examples/Mathutils.Quaternion.py3
-rw-r--r--source/blender/python/doc/examples/Mathutils.py17
-rw-r--r--source/blender/python/doc/examples/bpy.data.py29
-rw-r--r--source/blender/python/doc/examples/mathutils.Euler.py3
-rw-r--r--source/blender/python/doc/examples/mathutils.Matrix.py3
-rw-r--r--source/blender/python/doc/examples/mathutils.Quaternion.py3
-rw-r--r--source/blender/python/doc/examples/mathutils.Vector.py (renamed from source/blender/python/doc/examples/Mathutils.Vector.py)14
-rw-r--r--source/blender/python/doc/examples/mathutils.py18
-rw-r--r--source/blender/python/doc/sphinx_doc_gen.py464
-rwxr-xr-xsource/blender/python/doc/sphinx_doc_gen.sh7
-rw-r--r--source/blender/python/generic/CMakeLists.txt2
-rw-r--r--source/blender/python/generic/Makefile2
-rw-r--r--source/blender/python/generic/Mathutils.c721
-rw-r--r--source/blender/python/generic/bgl.c34
-rw-r--r--source/blender/python/generic/bgl.h4
-rw-r--r--source/blender/python/generic/blf_api.c (renamed from source/blender/python/generic/blf.c)180
-rw-r--r--source/blender/python/generic/blf_api.h (renamed from source/blender/python/generic/blf.h)0
-rw-r--r--source/blender/python/generic/bpy_internal_import.c59
-rw-r--r--source/blender/python/generic/bpy_internal_import.h5
-rw-r--r--source/blender/python/generic/geometry.c (renamed from source/blender/python/generic/Geometry.c)32
-rw-r--r--source/blender/python/generic/geometry.h (renamed from source/blender/python/generic/Geometry.h)2
-rw-r--r--source/blender/python/generic/mathutils.c273
-rw-r--r--source/blender/python/generic/mathutils.h (renamed from source/blender/python/generic/Mathutils.h)65
-rw-r--r--source/blender/python/generic/mathutils_color.c560
-rw-r--r--source/blender/python/generic/mathutils_color.h52
-rw-r--r--source/blender/python/generic/mathutils_euler.c (renamed from source/blender/python/generic/euler.c)345
-rw-r--r--source/blender/python/generic/mathutils_euler.h (renamed from source/blender/python/generic/euler.h)9
-rw-r--r--source/blender/python/generic/mathutils_matrix.c (renamed from source/blender/python/generic/matrix.c)567
-rw-r--r--source/blender/python/generic/mathutils_matrix.h (renamed from source/blender/python/generic/matrix.h)15
-rw-r--r--source/blender/python/generic/mathutils_quat.c (renamed from source/blender/python/generic/quat.c)531
-rw-r--r--source/blender/python/generic/mathutils_quat.h (renamed from source/blender/python/generic/quat.h)11
-rw-r--r--source/blender/python/generic/mathutils_vector.c (renamed from source/blender/python/generic/vector.c)501
-rw-r--r--source/blender/python/generic/mathutils_vector.h (renamed from source/blender/python/generic/vector.h)13
-rw-r--r--source/blender/python/generic/noise.c760
-rw-r--r--source/blender/python/intern/Makefile3
-rw-r--r--source/blender/python/intern/bpy.c111
-rw-r--r--source/blender/python/intern/bpy_app.c6
-rw-r--r--source/blender/python/intern/bpy_driver.c43
-rw-r--r--source/blender/python/intern/bpy_interface.c117
-rw-r--r--source/blender/python/intern/bpy_operator.c4
-rw-r--r--source/blender/python/intern/bpy_operator_wrap.c23
-rw-r--r--source/blender/python/intern/bpy_props.c135
-rw-r--r--source/blender/python/intern/bpy_props.h14
-rw-r--r--source/blender/python/intern/bpy_rna.c1346
-rw-r--r--source/blender/python/intern/bpy_rna.h6
-rw-r--r--source/blender/python/intern/bpy_rna_callback.c29
-rw-r--r--source/blender/python/intern/bpy_util.c26
-rw-r--r--source/blender/python/intern/bpy_util.h2
56 files changed, 4906 insertions, 2291 deletions
diff --git a/source/blender/python/BPY_extern.h b/source/blender/python/BPY_extern.h
index 11208d54a73..40d544ac17e 100644
--- a/source/blender/python/BPY_extern.h
+++ b/source/blender/python/BPY_extern.h
@@ -119,9 +119,11 @@ extern "C" {
// short eventValue, unsigned short space_event);
//
// void BPY_pydriver_update(void);
- float BPY_pydriver_eval(struct ChannelDriver *driver);
+ float BPY_eval_driver(struct ChannelDriver *driver);
//
- int BPY_button_eval(struct bContext *C, char *expr, double *value);
+ int BPY_eval_button(struct bContext *C, const char *expr, double *value);
+
+ int BPY_eval_string(struct bContext *C, const char *expr);
/* format importer hook */
int BPY_call_importloader( char *name );
diff --git a/source/blender/python/CMakeLists.txt b/source/blender/python/CMakeLists.txt
index 3c79e9d3056..dcfc8678faa 100644
--- a/source/blender/python/CMakeLists.txt
+++ b/source/blender/python/CMakeLists.txt
@@ -36,6 +36,7 @@ SET(INC
../windowmanager
../editors/include
../../../intern/guardedalloc
+ ../../../intern/audaspace/intern
${PYTHON_INC}
)
diff --git a/source/blender/python/Makefile b/source/blender/python/Makefile
index 8e2a04b8449..43b6f91369b 100644
--- a/source/blender/python/Makefile
+++ b/source/blender/python/Makefile
@@ -15,7 +15,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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# The Original Code is Copyright (C) Blender Foundation.
# All rights reserved.
diff --git a/source/blender/python/SConscript b/source/blender/python/SConscript
index ca742a3646a..097f69155d5 100644
--- a/source/blender/python/SConscript
+++ b/source/blender/python/SConscript
@@ -6,10 +6,13 @@ sources = env.Glob('intern/*.c')
incs = '. ../editors/include ../makesdna ../makesrna ../blenlib ../blenkernel ../nodes'
incs += ' ../imbuf ../blenloader ../render/extern/include ../windowmanager'
incs += ' #intern/guardedalloc #intern/memutil #extern/glew/include'
-incs += ' ' + env['BF_PYTHON_INC']
+incs += ' #intern/audaspace/intern ' + env['BF_PYTHON_INC']
defs = []
+if env['BF_BUILDINFO']:
+ defs.append('BUILD_DATE')
+
if env['OURPLATFORM'] in ('win32-mingw', 'win32-vc','win64-vc') and env['BF_DEBUG']:
defs.append('_DEBUG')
@@ -18,4 +21,4 @@ env.BlenderLib( libname = 'bf_python', sources = Split(sources), includes = Spli
# generic
sources = env.Glob('generic/*.c')
-env.BlenderLib( libname = 'bf_gen_python', sources = Split(sources), includes = Split(incs), defines = defs, libtype = ['core','player'], priority = [362,165]) # ketsji is 360
+env.BlenderLib( libname = 'bf_python_ext', sources = Split(sources), includes = Split(incs), defines = defs, libtype = ['core','player'], priority = [362,165]) # ketsji is 360
diff --git a/source/blender/python/doc/epy/Geometry.py b/source/blender/python/doc/epy/Geometry.py
index 237cd8c3443..f8752a135c3 100644
--- a/source/blender/python/doc/epy/Geometry.py
+++ b/source/blender/python/doc/epy/Geometry.py
@@ -90,7 +90,7 @@ def LineIntersect(vec1, vec2, vec3, vec4):
def PolyFill(polylines):
"""
Takes a list of polylines and calculates triangles that would fill in the polylines.
- Multiple lines can be used to make holes inside a polyline, or fill in 2 seperate lines at once.
+ Multiple lines can be used to make holes inside a polyline, or fill in 2 separate lines at once.
@type polylines: List of lists containing vectors, each representing a closed polyline.
@rtype: list
@return: a list if tuples each a tuple of 3 ints representing a triangle indexing the points given.
@@ -101,7 +101,7 @@ def PolyFill(polylines):
The example below creates 2 polylines and fills them in with faces, then makes a mesh in the current scene::
import Blender
- Vector= Blender.Mathutils.Vector
+ Vector= Blender.mathutils.Vector
# Outline of 5 points
polyline1= [Vector(-2.0, 1.0, 1.0), Vector(-1.0, 2.0, 1.0), Vector(1.0, 2.0, 1.0), Vector(1.0, -1.0, 1.0), Vector(-1.0, -1.0, 1.0)]
diff --git a/source/blender/python/doc/epy/Mathutils.py b/source/blender/python/doc/epy/Mathutils.py
index b1bb039debe..17a227f729a 100644
--- a/source/blender/python/doc/epy/Mathutils.py
+++ b/source/blender/python/doc/epy/Mathutils.py
@@ -1,4 +1,4 @@
-# Blender.Mathutils module and its subtypes
+# Blender.mathutils module and its subtypes
diff --git a/source/blender/python/doc/examples/Mathutils.Euler.py b/source/blender/python/doc/examples/Mathutils.Euler.py
deleted file mode 100644
index 0e7a62162d9..00000000000
--- a/source/blender/python/doc/examples/Mathutils.Euler.py
+++ /dev/null
@@ -1,3 +0,0 @@
-import Mathutils
-
-# todo \ No newline at end of file
diff --git a/source/blender/python/doc/examples/Mathutils.Matrix.py b/source/blender/python/doc/examples/Mathutils.Matrix.py
deleted file mode 100644
index 0e7a62162d9..00000000000
--- a/source/blender/python/doc/examples/Mathutils.Matrix.py
+++ /dev/null
@@ -1,3 +0,0 @@
-import Mathutils
-
-# todo \ No newline at end of file
diff --git a/source/blender/python/doc/examples/Mathutils.Quaternion.py b/source/blender/python/doc/examples/Mathutils.Quaternion.py
deleted file mode 100644
index 0e7a62162d9..00000000000
--- a/source/blender/python/doc/examples/Mathutils.Quaternion.py
+++ /dev/null
@@ -1,3 +0,0 @@
-import Mathutils
-
-# todo \ No newline at end of file
diff --git a/source/blender/python/doc/examples/Mathutils.py b/source/blender/python/doc/examples/Mathutils.py
deleted file mode 100644
index a00ca3dd1c8..00000000000
--- a/source/blender/python/doc/examples/Mathutils.py
+++ /dev/null
@@ -1,17 +0,0 @@
-import Mathutils
-
-vec = Mathutils.Vector(1.0, 2.0, 3.0)
-
-mat_rot = Mathutils.RotationMatrix(90, 4, 'X')
-mat_trans = Mathutils.TranslationMatrix(vec)
-
-mat = mat_trans * mat_rot
-mat.invert()
-
-mat3 = mat.rotation_part()
-quat1 = mat.to_quat()
-quat2 = mat3.to_quat()
-
-angle = quat1.difference(quat2)
-
-print(angle) \ No newline at end of file
diff --git a/source/blender/python/doc/examples/bpy.data.py b/source/blender/python/doc/examples/bpy.data.py
new file mode 100644
index 00000000000..fc1145a523f
--- /dev/null
+++ b/source/blender/python/doc/examples/bpy.data.py
@@ -0,0 +1,29 @@
+import bpy
+
+
+# print all objects
+for obj in bpy.data.objects:
+ print(obj.name)
+
+
+# print all scene names in a list
+print(bpy.data.scenes.keys())
+
+
+# remove mesh Cube
+if "Cube" in bpy.data.meshes:
+ mesh = bpy.data.meshes["Cube"]
+ print("removing mesh", mesh)
+ bpy.data.meshes.unlink(mesh)
+
+
+# write images into a file next to the blend
+import os
+file = open(os.path.splitext(bpy.data.filepath)[0] + ".txt", 'w')
+
+for image in bpy.data.images:
+ file.write("%s %dx%d\n" % (image.filepath, image.size[0], image.size[1]))
+
+file.close()
+
+
diff --git a/source/blender/python/doc/examples/mathutils.Euler.py b/source/blender/python/doc/examples/mathutils.Euler.py
new file mode 100644
index 00000000000..f8294ce5545
--- /dev/null
+++ b/source/blender/python/doc/examples/mathutils.Euler.py
@@ -0,0 +1,3 @@
+import mathutils
+
+# todo \ No newline at end of file
diff --git a/source/blender/python/doc/examples/mathutils.Matrix.py b/source/blender/python/doc/examples/mathutils.Matrix.py
new file mode 100644
index 00000000000..f8294ce5545
--- /dev/null
+++ b/source/blender/python/doc/examples/mathutils.Matrix.py
@@ -0,0 +1,3 @@
+import mathutils
+
+# todo \ No newline at end of file
diff --git a/source/blender/python/doc/examples/mathutils.Quaternion.py b/source/blender/python/doc/examples/mathutils.Quaternion.py
new file mode 100644
index 00000000000..f8294ce5545
--- /dev/null
+++ b/source/blender/python/doc/examples/mathutils.Quaternion.py
@@ -0,0 +1,3 @@
+import mathutils
+
+# todo \ No newline at end of file
diff --git a/source/blender/python/doc/examples/Mathutils.Vector.py b/source/blender/python/doc/examples/mathutils.Vector.py
index 8b3dbfa5ee8..fb00e8aead6 100644
--- a/source/blender/python/doc/examples/Mathutils.Vector.py
+++ b/source/blender/python/doc/examples/mathutils.Vector.py
@@ -1,20 +1,20 @@
-import Mathutils
+import mathutils
# zero length vector
-vec = Mathutils.Vector(0, 0, 1)
+vec = mathutils.Vector((0, 0, 1))
# unit length vector
vec_a = vec.copy().normalize()
-vec_b = Mathutils.Vector(0, 1, 2)
+vec_b = mathutils.Vector((0, 1, 2))
-vec2d = Mathutils.Vector(1, 2)
-vec3d = Mathutils.Vector([1, 0, 0])
+vec2d = mathutils.Vector((1, 2))
+vec3d = mathutils.Vector((1, 0, 0))
vec4d = vec_a.copy().resize4D()
# other mathutuls types
-quat = Mathutils.Quaternion()
-matrix = Mathutils.Matrix()
+quat = mathutils.Quaternion()
+matrix = mathutils.Matrix()
# Comparison operators can be done on Vector classes:
diff --git a/source/blender/python/doc/examples/mathutils.py b/source/blender/python/doc/examples/mathutils.py
new file mode 100644
index 00000000000..0b30a0f4505
--- /dev/null
+++ b/source/blender/python/doc/examples/mathutils.py
@@ -0,0 +1,18 @@
+import mathutils
+from math import radians
+
+vec = mathutils.Vector((1.0, 2.0, 3.0))
+
+mat_rot = mathutils.Matrix.Rotation(radians(90), 4, 'X')
+mat_trans = mathutils.Matrix.Translation(vec)
+
+mat = mat_trans * mat_rot
+mat.invert()
+
+mat3 = mat.rotation_part()
+quat1 = mat.to_quat()
+quat2 = mat3.to_quat()
+
+angle = quat1.difference(quat2)
+
+print(angle) \ No newline at end of file
diff --git a/source/blender/python/doc/sphinx_doc_gen.py b/source/blender/python/doc/sphinx_doc_gen.py
index 944dbb082a6..06d1a9021b8 100644
--- a/source/blender/python/doc/sphinx_doc_gen.py
+++ b/source/blender/python/doc/sphinx_doc_gen.py
@@ -24,7 +24,7 @@ run this script from blenders root path once you have compiled blender
./blender.bin -b -P /b/source/blender/python/doc/sphinx_doc_gen.py
This will generate python files in "./source/blender/python/doc/sphinx-in"
-Generate html docs by running...
+Generate html docs by running...
sphinx-build source/blender/python/doc/sphinx-in source/blender/python/doc/sphinx-out
@@ -36,6 +36,7 @@ For PDF generation
make
'''
+# import rpdb2; rpdb2.start_embedded_debugger('test')
import os
import inspect
@@ -43,10 +44,30 @@ import bpy
import rna_info
reload(rna_info)
+# lame, python wont give some access
+ClassMethodDescriptorType = type(dict.__dict__['fromkeys'])
+MethodDescriptorType = type(dict.get)
+GetSetDescriptorType = type(int.real)
+
EXAMPLE_SET = set()
EXAMPLE_SET_USED = set()
+_BPY_STRUCT_FAKE = "bpy_struct"
+_BPY_FULL_REBUILD = False
+
+def undocumented_message(module_name, type_name, identifier):
+ message = "Undocumented (`contribute " \
+ "<http://wiki.blender.org/index.php/Dev:2.5/Py/API/Documentation/Contribute" \
+ "?action=edit&section=new&preload=Dev:2.5/Py/API/Documentation/Contribute/Howto-message" \
+ "&preloadtitle=%s.%s.%s>`_)\n\n" % (module_name, type_name, identifier)
+ return message
+
+
def range_str(val):
+ '''
+ Converts values to strings for the range directive.
+ (unused function it seems)
+ '''
if val < -10000000: return '-inf'
if val > 10000000: return 'inf'
if type(val)==float:
@@ -55,9 +76,9 @@ def range_str(val):
return str(val)
-def write_example_ref(ident, fw, example_id, ext=".py"):
+def write_example_ref(ident, fw, example_id, ext="py"):
if example_id in EXAMPLE_SET:
- fw("%s.. literalinclude:: ../examples/%s%s\n\n" % (ident, example_id, ext))
+ fw("%s.. literalinclude:: ../examples/%s.%s\n\n" % (ident, example_id, ext))
EXAMPLE_SET_USED.add(example_id)
else:
if bpy.app.debug:
@@ -65,6 +86,9 @@ def write_example_ref(ident, fw, example_id, ext=".py"):
def write_indented_lines(ident, fn, text, strip=True):
+ '''
+ Apply same indentation to all lines in a multilines text.
+ '''
if text is None:
return
for l in text.split("\n"):
@@ -118,7 +142,28 @@ def pyfunc2sphinx(ident, fw, identifier, py_func, is_class=True):
write_indented_lines(ident + " ", fw, py_func.__doc__.strip())
fw("\n")
-def py_c_func2sphinx(ident, fw, identifier, py_func, is_class=True):
+
+def py_descr2sphinx(ident, fw, descr, module_name, type_name, identifier):
+ if identifier.startswith("_"):
+ return
+
+ doc = descr.__doc__
+ if not doc:
+ doc = undocumented_message(module_name, type_name, identifier)
+
+ if type(descr) == GetSetDescriptorType:
+ fw(ident + ".. attribute:: %s\n\n" % identifier)
+ write_indented_lines(ident + " ", fw, doc, False)
+ elif type(descr) in (MethodDescriptorType, ClassMethodDescriptorType):
+ write_indented_lines(ident, fw, doc, False)
+ else:
+ raise TypeError("type was not GetSetDescriptorType, MethodDescriptorType or ClassMethodDescriptorType")
+
+ write_example_ref(ident, fw, module_name + "." + type_name + "." + identifier)
+ fw("\n")
+
+
+def py_c_func2sphinx(ident, fw, module_name, type_name, identifier, py_func, is_class=True):
'''
c defined function to sphinx.
'''
@@ -129,14 +174,18 @@ def py_c_func2sphinx(ident, fw, identifier, py_func, is_class=True):
fw("\n")
else:
fw(ident + ".. function:: %s()\n\n" % identifier)
- fw(ident + " Undocumented function.\n\n" % identifier)
+ fw(ident + " " + undocumented_message(module_name, type_name, identifier))
def pyprop2sphinx(ident, fw, identifier, py_prop):
'''
python property to sphinx
'''
- fw(ident + ".. attribute:: %s\n\n" % identifier)
+ # readonly properties use "data" directive, variables use "attribute" directive
+ if py_prop.fset is None:
+ fw(ident + ".. data:: %s\n\n" % identifier)
+ else:
+ fw(ident + ".. attribute:: %s\n\n" % identifier)
write_indented_lines(ident + " ", fw, py_prop.__doc__)
if py_prop.fset is None:
fw(ident + " (readonly)\n\n")
@@ -144,12 +193,7 @@ def pyprop2sphinx(ident, fw, identifier, py_prop):
def pymodule2sphinx(BASEPATH, module_name, module, title):
import types
- # lame, python wont give some access
- MethodDescriptorType = type(dict.get)
- GetSetDescriptorType = type(int.real)
-
-
-
+ attribute_set = set()
filepath = os.path.join(BASEPATH, module_name + ".rst")
file = open(filepath, "w")
@@ -170,18 +214,26 @@ def pymodule2sphinx(BASEPATH, module_name, module, title):
# write members of the module
# only tested with PyStructs which are not exactly modules
- for attribute, descr in sorted(type(module).__dict__.items()):
+ for key, descr in sorted(type(module).__dict__.items()):
if type(descr) == types.MemberDescriptorType:
if descr.__doc__:
- fw(".. data:: %s\n\n" % attribute)
+ fw(".. data:: %s\n\n" % key)
write_indented_lines(" ", fw, descr.__doc__, False)
+ attribute_set.add(key)
fw("\n")
-
+ del key, descr
classes = []
- for attribute in dir(module):
+ for attribute in sorted(dir(module)):
if not attribute.startswith("_"):
+
+ if attribute in attribute_set:
+ continue
+
+ if attribute.startswith("n_"): # annoying exception, needed for bpy.app
+ continue
+
value = getattr(module, attribute)
value_type = type(value)
@@ -191,41 +243,45 @@ def pymodule2sphinx(BASEPATH, module_name, module, title):
elif value_type in (types.BuiltinMethodType, types.BuiltinFunctionType): # both the same at the moment but to be future proof
# note: can't get args from these, so dump the string as is
# this means any module used like this must have fully formatted docstrings.
- py_c_func2sphinx("", fw, attribute, value, is_class=False)
+ py_c_func2sphinx("", fw, module_name, module, attribute, value, is_class=False)
elif value_type == type:
classes.append((attribute, value))
+ elif value_type in (bool, int, float, str, tuple):
+ # constant, not much fun we can do here except to list it.
+ # TODO, figure out some way to document these!
+ fw(".. data:: %s\n\n" % attribute)
+ write_indented_lines(" ", fw, "constant value %s" % repr(value), False)
+ fw("\n")
+ else:
+ print("\tnot documenting %s.%s" % (module_name, attribute))
+ continue
+
+ attribute_set.add(attribute)
# TODO, more types...
-
+
# write collected classes now
- for (attribute, value) in classes:
+ for (type_name, value) in classes:
# May need to be its own function
- fw(".. class:: %s\n\n" % attribute)
+ fw(".. class:: %s\n\n" % type_name)
if value.__doc__:
write_indented_lines(" ", fw, value.__doc__, False)
fw("\n")
- write_example_ref(" ", fw, module_name + "." + attribute)
+ write_example_ref(" ", fw, module_name + "." + type_name)
- for key in sorted(value.__dict__.keys()):
- if key.startswith("__"):
- continue
- descr = value.__dict__[key]
+ descr_items = [(key, descr) for key, descr in sorted(value.__dict__.items()) if not key.startswith("__")]
+
+ for key, descr in descr_items:
+ if type(descr) == ClassMethodDescriptorType:
+ py_descr2sphinx(" ", fw, descr, module_name, type_name, key)
+
+ for key, descr in descr_items:
+ if type(descr) == MethodDescriptorType:
+ py_descr2sphinx(" ", fw, descr, module_name, type_name, key)
+
+ for key, descr in descr_items:
if type(descr) == GetSetDescriptorType:
- if descr.__doc__:
- fw(" .. attribute:: %s\n\n" % key)
- write_indented_lines(" ", fw, descr.__doc__, False)
- write_example_ref(" ", fw, module_name + "." + attribute + "." + key)
- fw("\n")
-
- for key in sorted(value.__dict__.keys()):
- if key.startswith("__"):
- continue
- descr = value.__dict__[key]
- if type(descr) == MethodDescriptorType: # GetSetDescriptorType, GetSetDescriptorType's are not documented yet
- if descr.__doc__:
- write_indented_lines(" ", fw, descr.__doc__, False)
- write_example_ref(" ", fw, module_name + "." + attribute + "." + key)
- fw("\n")
-
+ py_descr2sphinx(" ", fw, descr, module_name, type_name, key)
+
fw("\n\n")
file.close()
@@ -251,11 +307,14 @@ def rna2sphinx(BASEPATH):
if bpy.app.build_revision != "Unknown":
version_string = version_string + " r" + bpy.app.build_revision
- fw("project = 'Blender 3D'\n")
+ fw("project = 'Blender'\n")
# fw("master_doc = 'index'\n")
fw("copyright = u'Blender Foundation'\n")
fw("version = '%s - UNSTABLE API'\n" % version_string)
fw("release = '%s - UNSTABLE API'\n" % version_string)
+ fw("html_theme = 'blender-org'\n")
+ fw("html_theme_path = ['../']\n")
+ fw("html_favicon = 'favicon.ico'\n")
# not helpful since the source us generated, adds to upload size.
fw("html_copy_source = False\n")
fw("\n")
@@ -275,7 +334,7 @@ def rna2sphinx(BASEPATH):
fw("\n")
fw("This document is an API reference for Blender %s. built %s.\n" % (version_string, bpy.app.build_date))
fw("\n")
- fw("An introduction to blender and python can be found at <http://wiki.blender.org/index.php/Dev:2.5/Py/API/Intro>\n")
+ fw("An introduction to Blender and Python can be found at <http://wiki.blender.org/index.php/Dev:2.5/Py/API/Intro>\n")
fw("\n")
fw("`A PDF version of this document is also available <blender_python_reference_250.pdf>`__\n")
fw("\n")
@@ -283,6 +342,7 @@ def rna2sphinx(BASEPATH):
fw(" \n")
fw(" The following areas are subject to change.\n")
fw(" * operator names and arguments\n")
+ fw(" * render api\n")
fw(" * function calls with the data api (any function calls with values accessed from bpy.data), including functions for importing and exporting meshes\n")
fw(" * class registration (Operator, Panels, Menus, Headers)\n")
fw(" * modules: bpy.props, blf)\n")
@@ -292,22 +352,52 @@ def rna2sphinx(BASEPATH):
fw(" These parts of the API are relatively stable and are unlikely to change significantly\n")
fw(" * data API, access to attributes of blender data such as mesh verts, material color, timeline frames and scene objects\n")
fw(" * user interface functions for defining buttons, creation of menus, headers, panels\n")
- fw(" * modules: bgl, Mathutils and Geometry\n")
+ fw(" * modules: bgl, mathutils and geometry\n")
+ fw(" * game engine modules\n")
+ fw("\n")
+
+ fw("===================\n")
+ fw("Application Modules\n")
+ fw("===================\n")
fw("\n")
fw(".. toctree::\n")
fw(" :maxdepth: 1\n\n")
+ fw(" bpy.data.rst\n\n") # note: not actually a module
fw(" bpy.ops.rst\n\n")
fw(" bpy.types.rst\n\n")
# py modules
fw(" bpy.utils.rst\n\n")
+ fw(" bpy.path.rst\n\n")
fw(" bpy.app.rst\n\n")
# C modules
fw(" bpy.props.rst\n\n")
-
- fw(" Mathutils.rst\n\n")
+
+ fw("==================\n")
+ fw("Standalone Modules\n")
+ fw("==================\n")
+ fw("\n")
+ fw(".. toctree::\n")
+ fw(" :maxdepth: 1\n\n")
+
+
+ fw(" mathutils.rst\n\n")
fw(" blf.rst\n\n")
+ fw(" aud.rst\n\n")
+
+ # game engine
+ fw("===================\n")
+ fw("Game Engine Modules\n")
+ fw("===================\n")
+ fw("\n")
+ fw(".. toctree::\n")
+ fw(" :maxdepth: 1\n\n")
+ fw(" bge.types.rst\n\n")
+ fw(" bge.logic.rst\n\n")
+ fw(" bge.render.rst\n\n")
+ fw(" bge.events.rst\n\n")
+
file.close()
@@ -315,8 +405,8 @@ def rna2sphinx(BASEPATH):
filepath = os.path.join(BASEPATH, "bpy.ops.rst")
file = open(filepath, "w")
fw = file.write
- fw("Blender Operators (bpy.ops)\n")
- fw("===========================\n\n")
+ fw("Operators (bpy.ops)\n")
+ fw("===================\n\n")
fw(".. toctree::\n")
fw(" :glob:\n\n")
fw(" bpy.ops.*\n\n")
@@ -325,19 +415,44 @@ def rna2sphinx(BASEPATH):
filepath = os.path.join(BASEPATH, "bpy.types.rst")
file = open(filepath, "w")
fw = file.write
- fw("Blender Types (bpy.types)\n")
- fw("=========================\n\n")
+ fw("Types (bpy.types)\n")
+ fw("=================\n\n")
fw(".. toctree::\n")
fw(" :glob:\n\n")
fw(" bpy.types.*\n\n")
file.close()
+ # not actually a module, only write this file so we
+ # can reference in the TOC
+ filepath = os.path.join(BASEPATH, "bpy.data.rst")
+ file = open(filepath, "w")
+ fw = file.write
+ fw("Data Access (bpy.data)\n")
+ fw("======================\n\n")
+ fw(".. module:: bpy\n")
+ fw("\n")
+ fw("This module is used for all blender/python access.\n")
+ fw("\n")
+ fw(".. literalinclude:: ../examples/bpy.data.py\n")
+ fw("\n")
+ fw(".. data:: data\n")
+ fw("\n")
+ fw(" Access to blenders internal data\n")
+ fw("\n")
+ fw(" :type: :class:`bpy.types.Main`\n")
+ file.close()
+
+ EXAMPLE_SET_USED.add("bpy.data")
+
# python modules
from bpy import utils as module
pymodule2sphinx(BASEPATH, "bpy.utils", module, "Utilities (bpy.utils)")
+ from bpy import path as module
+ pymodule2sphinx(BASEPATH, "bpy.path", module, "Path Utilities (bpy.path)")
+
# C modules
from bpy import app as module
pymodule2sphinx(BASEPATH, "bpy.app", module, "Application Data (bpy.app)")
@@ -345,14 +460,27 @@ def rna2sphinx(BASEPATH):
from bpy import props as module
pymodule2sphinx(BASEPATH, "bpy.props", module, "Property Definitions (bpy.props)")
- import Mathutils as module
- pymodule2sphinx(BASEPATH, "Mathutils", module, "Math Types & Utilities (Mathutils)")
+ import mathutils as module
+ pymodule2sphinx(BASEPATH, "mathutils", module, "Math Types & Utilities (mathutils)")
del module
import blf as module
- pymodule2sphinx(BASEPATH, "blf", module, "Blender Font Drawing (blf)")
+ pymodule2sphinx(BASEPATH, "blf", module, "Font Drawing (blf)")
+ del module
+
+ import aud as module
+ pymodule2sphinx(BASEPATH, "aud", module, "Audio System (aud)")
del module
+ # game engine
+ import shutil
+ # copy2 keeps time/date stamps
+ shutil.copy2(os.path.join(BASEPATH, "../../../../gameengine/PyDoc/bge.types.rst"), BASEPATH)
+ shutil.copy2(os.path.join(BASEPATH, "../../../../gameengine/PyDoc/bge.logic.rst"), BASEPATH)
+ shutil.copy2(os.path.join(BASEPATH, "../../../../gameengine/PyDoc/bge.render.rst"), BASEPATH)
+ shutil.copy2(os.path.join(BASEPATH, "../../../../gameengine/PyDoc/bge.events.rst"), BASEPATH)
+
+
if 0:
filepath = os.path.join(BASEPATH, "bpy.rst")
file = open(filepath, "w")
@@ -393,8 +521,14 @@ def rna2sphinx(BASEPATH):
file = open(filepath, "w")
fw = file.write
- if struct.base:
- title = "%s(%s)" % (struct.identifier, struct.base.identifier)
+ base_id = getattr(struct.base, "identifier", "")
+
+ if _BPY_STRUCT_FAKE:
+ if not base_id:
+ base_id = _BPY_STRUCT_FAKE
+
+ if base_id:
+ title = "%s(%s)" % (struct.identifier, base_id)
else:
title = struct.identifier
@@ -402,37 +536,53 @@ def rna2sphinx(BASEPATH):
fw(".. module:: bpy.types\n\n")
- bases = struct.get_bases()
- if bases:
- if len(bases) > 1:
+ base_ids = [base.identifier for base in struct.get_bases()]
+
+ if _BPY_STRUCT_FAKE:
+ base_ids.append(_BPY_STRUCT_FAKE)
+
+ base_ids.reverse()
+
+ if base_ids:
+ if len(base_ids) > 1:
fw("base classes --- ")
else:
fw("base class --- ")
- fw(", ".join([(":class:`%s`" % base.identifier) for base in reversed(bases)]))
+ fw(", ".join([(":class:`%s`" % base_id) for base_id in base_ids]))
fw("\n\n")
- subclasses = [s for s in structs.values() if s.base is struct]
+ subclass_ids = [s.identifier for s in structs.values() if s.base is struct if not rna_info.rna_id_ignore(s.identifier)]
+ if subclass_ids:
+ fw("subclasses --- \n" + ", ".join([(":class:`%s`" % s) for s in subclass_ids]) + "\n\n")
- if subclasses:
- fw("subclasses --- \n")
- fw(", ".join([(":class:`%s`" % s.identifier) for s in subclasses]))
- fw("\n\n")
-
+ base_id = getattr(struct.base, "identifier", "")
+
+ if _BPY_STRUCT_FAKE:
+ if not base_id:
+ base_id = _BPY_STRUCT_FAKE
- if struct.base:
- fw(".. class:: %s(%s)\n\n" % (struct.identifier, struct.base.identifier))
+ if base_id:
+ fw(".. class:: %s(%s)\n\n" % (struct.identifier, base_id))
else:
fw(".. class:: %s\n\n" % struct.identifier)
fw(" %s\n\n" % struct.description)
+
+ # properties sorted in alphabetical order
+ sorted_struct_properties = struct.properties[:]
+ sorted_struct_properties.sort(key=lambda prop: prop.identifier)
- for prop in struct.properties:
- fw(" .. attribute:: %s\n\n" % prop.identifier)
+ for prop in sorted_struct_properties:
+ type_descr = prop.get_type_description(class_fmt=":class:`%s`")
+ # readonly properties use "data" directive, variables properties use "attribute" directive
+ if 'readonly' in type_descr:
+ fw(" .. data:: %s\n\n" % prop.identifier)
+ else:
+ fw(" .. attribute:: %s\n\n" % prop.identifier)
if prop.description:
fw(" %s\n\n" % prop.description)
- type_descr = prop.get_type_description(class_fmt=":class:`%s`")
- fw(" *type* %s\n\n" % type_descr)
+ fw(" :type: %s\n\n" % type_descr)
# python attributes
py_properties = struct.get_py_properties()
@@ -444,7 +594,7 @@ def rna2sphinx(BASEPATH):
for func in struct.functions:
args_str = ", ".join([prop.get_arg_default(force=False) for prop in func.args])
- fw(" .. method:: %s(%s)\n\n" % (func.identifier, args_str))
+ fw(" .. %s:: %s(%s)\n\n" % ("classmethod" if func.is_classmethod else "method", func.identifier, args_str))
fw(" %s\n\n" % func.description)
for prop in func.args:
@@ -472,6 +622,62 @@ def rna2sphinx(BASEPATH):
pyfunc2sphinx(" ", fw, identifier, py_func, is_class=True)
del py_funcs, py_func
+ lines = []
+
+ if struct.base or _BPY_STRUCT_FAKE:
+ bases = list(reversed(struct.get_bases()))
+
+ # props
+ lines[:] = []
+
+ if _BPY_STRUCT_FAKE:
+ descr_items = [(key, descr) for key, descr in sorted(bpy.types.Struct.__bases__[0].__dict__.items()) if not key.startswith("__")]
+
+ if _BPY_STRUCT_FAKE:
+ for key, descr in descr_items:
+ if type(descr) == GetSetDescriptorType:
+ lines.append("* :class:`%s.%s`\n" % (_BPY_STRUCT_FAKE, key))
+
+ for base in bases:
+ for prop in base.properties:
+ lines.append("* :class:`%s.%s`\n" % (base.identifier, prop.identifier))
+
+ for identifier, py_prop in base.get_py_properties():
+ lines.append("* :class:`%s.%s`\n" % (base.identifier, identifier))
+
+ for identifier, py_prop in base.get_py_properties():
+ lines.append("* :class:`%s.%s`\n" % (base.identifier, identifier))
+
+ if lines:
+ fw(".. rubric:: Inherited Properties\n\n")
+ for line in lines:
+ fw(line)
+ fw("\n")
+
+
+ # funcs
+ lines[:] = []
+
+ if _BPY_STRUCT_FAKE:
+ for key, descr in descr_items:
+ if type(descr) == MethodDescriptorType:
+ lines.append("* :class:`%s.%s`\n" % (_BPY_STRUCT_FAKE, key))
+
+ for base in bases:
+ for func in base.functions:
+ lines.append("* :class:`%s.%s`\n" % (base.identifier, func.identifier))
+ for identifier, py_func in base.get_py_functions():
+ lines.append("* :class:`%s.%s`\n" % (base.identifier, identifier))
+
+ if lines:
+ fw(".. rubric:: Inherited Functions\n\n")
+ for line in lines:
+ fw(line)
+ fw("\n")
+
+ lines[:] = []
+
+
if struct.references:
# use this otherwise it gets in the index for a normal heading.
fw(".. rubric:: References\n\n")
@@ -489,11 +695,43 @@ def rna2sphinx(BASEPATH):
if "_OT_" in struct.identifier:
continue
write_struct(struct)
+
+ # special case, bpy_struct
+ if _BPY_STRUCT_FAKE:
+ filepath = os.path.join(BASEPATH, "bpy.types.%s.rst" % _BPY_STRUCT_FAKE)
+ file = open(filepath, "w")
+ fw = file.write
+
+ fw("%s\n" % _BPY_STRUCT_FAKE)
+ fw("=" * len(_BPY_STRUCT_FAKE) + "\n")
+ fw("\n")
+ fw(".. module:: bpy.types\n")
+ fw("\n")
+
+ subclass_ids = [s.identifier for s in structs.values() if s.base is None if not rna_info.rna_id_ignore(s.identifier)]
+ if subclass_ids:
+ fw("subclasses --- \n" + ", ".join([(":class:`%s`" % s) for s in sorted(subclass_ids)]) + "\n\n")
+
+ fw(".. class:: %s\n\n" % _BPY_STRUCT_FAKE)
+ fw(" built-in base class for all classes in bpy.types.\n\n")
+ fw(" .. note::\n\n")
+ fw(" Note that bpy.types.%s is not actually available from within blender, it only exists for the purpose of documentation.\n\n" % _BPY_STRUCT_FAKE)
+
+ descr_items = [(key, descr) for key, descr in sorted(bpy.types.Struct.__bases__[0].__dict__.items()) if not key.startswith("__")]
+
+ for key, descr in descr_items:
+ if type(descr) == MethodDescriptorType: # GetSetDescriptorType, GetSetDescriptorType's are not documented yet
+ py_descr2sphinx(" ", fw, descr, "bpy.types", _BPY_STRUCT_FAKE, key)
- # oeprators
+ for key, descr in descr_items:
+ if type(descr) == GetSetDescriptorType:
+ py_descr2sphinx(" ", fw, descr, "bpy.types", _BPY_STRUCT_FAKE, key)
+
+
+ # operators
def write_ops():
+ API_BASEURL='https://svn.blender.org/svnroot/bf-blender/trunk/blender/release/scripts'
fw = None
-
last_mod = ''
for op_key in sorted(ops.keys()):
@@ -509,11 +747,18 @@ def rna2sphinx(BASEPATH):
fw(".. module:: bpy.ops.%s\n\n" % op.module_name)
last_mod = op.module_name
-
+
args_str = ", ".join([prop.get_arg_default(force=True) for prop in op.args])
fw(".. function:: %s(%s)\n\n" % (op.func_name, args_str))
- if op.description:
- fw(" %s\n\n" % op.description)
+
+ # if the description isn't valid, we output the standard warning
+ # with a link to the wiki so that people can help
+ if not op.description or op.description == "(undocumented operator)":
+ operator_description = undocumented_message('bpy.ops',op.module_name,op.func_name)
+ else:
+ operator_description = op.description
+
+ fw(" %s\n\n" % operator_description)
for prop in op.args:
write_param(" ", fw, prop)
if op.args:
@@ -521,13 +766,14 @@ def rna2sphinx(BASEPATH):
location = op.get_location()
if location != (None, None):
- fw(" *python operator source --- `%s:%d`* \n\n" % location)
+ fw(" :file: `%s <%s/%s>`_:%d\n\n" % (location[0],API_BASEURL,location[0],location[1]))
write_ops()
file.close()
-if __name__ == '__main__':
+def main():
+ import bpy
if 'bpy' not in dir():
print("\nError, this script must run from inside blender2.5")
print(script_help_msg)
@@ -535,22 +781,59 @@ if __name__ == '__main__':
import shutil
path_in = 'source/blender/python/doc/sphinx-in'
- path_out = 'source/blender/python/doc/sphinx-in'
+ path_out = 'source/blender/python/doc/sphinx-out'
path_examples = 'source/blender/python/doc/examples'
+ # only for partial updates
+ path_in_tmp = path_in + "-tmp"
+
+ if not os.path.exists(path_in):
+ os.mkdir(path_in)
- shutil.rmtree(path_in, True)
- shutil.rmtree(path_out, True)
-
for f in os.listdir(path_examples):
if f.endswith(".py"):
EXAMPLE_SET.add(os.path.splitext(f)[0])
-
- rna2sphinx(path_in)
- # for fast module testing
- # os.system("rm source/blender/python/doc/sphinx-in/bpy.types.*.rst")
- # os.system("rm source/blender/python/doc/sphinx-in/bpy.ops.*.rst")
-
+
+ # only for full updates
+ if _BPY_FULL_REBUILD:
+ shutil.rmtree(path_in, True)
+ shutil.rmtree(path_out, True)
+ else:
+ # write here, then move
+ shutil.rmtree(path_in_tmp, True)
+
+ rna2sphinx(path_in_tmp)
+
+ if not _BPY_FULL_REBUILD:
+ import filecmp
+
+ # now move changed files from 'path_in_tmp' --> 'path_in'
+ file_list_path_in = set(os.listdir(path_in))
+ file_list_path_in_tmp = set(os.listdir(path_in_tmp))
+
+ # remove deprecated files that have been removed.
+ for f in sorted(file_list_path_in):
+ if f not in file_list_path_in_tmp:
+ print("\tdeprecated: %s" % f)
+ os.remove(os.path.join(path_in, f))
+
+ # freshen with new files.
+ for f in sorted(file_list_path_in_tmp):
+ f_from = os.path.join(path_in_tmp, f)
+ f_to = os.path.join(path_in, f)
+
+ do_copy = True
+ if f in file_list_path_in:
+ if filecmp.cmp(f_from, f_to):
+ do_copy = False
+
+ if do_copy:
+ print("\tupdating: %s" % f)
+ shutil.copy(f_from, f_to)
+ '''else:
+ print("\tkeeping: %s" % f) # eh, not that useful'''
+
+
EXAMPLE_SET_UNUSED = EXAMPLE_SET - EXAMPLE_SET_USED
if EXAMPLE_SET_UNUSED:
print("\nUnused examples found in '%s'..." % path_examples)
@@ -560,3 +843,6 @@ if __name__ == '__main__':
import sys
sys.exit()
+
+if __name__ == '__main__':
+ main()
diff --git a/source/blender/python/doc/sphinx_doc_gen.sh b/source/blender/python/doc/sphinx_doc_gen.sh
index 3f5460a0626..4f5f55af2bd 100755
--- a/source/blender/python/doc/sphinx_doc_gen.sh
+++ b/source/blender/python/doc/sphinx_doc_gen.sh
@@ -1,15 +1,14 @@
#!/bin/sh
# run from the blender source dir
# bash source/blender/python/doc/sphinx_doc_gen.sh
-# ssh upload means you need a login into the server
+# ssh upload means you need an account on the server
BLENDER="./blender.bin"
SSH_HOST="ideasman42@emo.blender.org"
SSH_UPLOAD="/data/www/vhosts/www.blender.org/documentation/250PythonDoc"
-# clear doc dir
-rm -rf ./source/blender/python/doc/sphinx-in ./source/blender/python/doc/sphinx-out
-$BLENDER -b -P ./source/blender/python/doc/sphinx_doc_gen.py
+# dont delete existing docs, now partial updates are used for quick builds.
+$BLENDER --background --python ./source/blender/python/doc/sphinx_doc_gen.py
# html
sphinx-build source/blender/python/doc/sphinx-in source/blender/python/doc/sphinx-out
diff --git a/source/blender/python/generic/CMakeLists.txt b/source/blender/python/generic/CMakeLists.txt
index b6985458d0c..1a91abfbec8 100644
--- a/source/blender/python/generic/CMakeLists.txt
+++ b/source/blender/python/generic/CMakeLists.txt
@@ -31,4 +31,4 @@ SET(INC
${PYTHON_INC}
)
-BLENDERLIB(bf_gen_python "${SRC}" "${INC}")
+BLENDERLIB(bf_python_ext "${SRC}" "${INC}")
diff --git a/source/blender/python/generic/Makefile b/source/blender/python/generic/Makefile
index dc674478dab..0df98046f63 100644
--- a/source/blender/python/generic/Makefile
+++ b/source/blender/python/generic/Makefile
@@ -15,7 +15,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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
# All rights reserved.
diff --git a/source/blender/python/generic/Mathutils.c b/source/blender/python/generic/Mathutils.c
deleted file mode 100644
index 542bf7a6ca9..00000000000
--- a/source/blender/python/generic/Mathutils.c
+++ /dev/null
@@ -1,721 +0,0 @@
-/*
- * $Id$
- *
- * ***** BEGIN GPL 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.
- *
- * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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): Joseph Gilbert, Campbell Barton
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/* Note: Changes to Mathutils since 2.4x
- * use radians rather then degrees
- * - Mathutils.MidpointVecs --> vector.lerp(other, fac)
- * - Mathutils.AngleBetweenVecs --> vector.angle(other)
- * - Mathutils.ProjectVecs --> vector.project(other)
- * - Mathutils.DifferenceQuats --> quat.difference(other)
- * - Mathutils.Slerp --> quat.slerp(other, fac)
- * - Mathutils.Rand: removed, use pythons random module
- * - Mathutils.RotationMatrix(angle, size, axis_flag, axis) --> Mathutils.RotationMatrix(angle, size, axis); merge axis & axis_flag args
- * - Matrix.scalePart --> Matrix.scale_part
- * - Matrix.translationPart --> Matrix.translation_part
- * - Matrix.rotationPart --> Matrix.rotation_part
- * - toMatrix --> to_matrix
- * - toEuler --> to_euler
- * - toQuat --> to_quat
- * - Vector.toTrackQuat --> Vector.to_track_quat
- *
- * Moved to Geometry module: Intersect, TriangleArea, TriangleNormal, QuadNormal, LineIntersect
- */
-
-#include "Mathutils.h"
-
-#include "BLI_math.h"
-
-//-------------------------DOC STRINGS ---------------------------
-static char M_Mathutils_doc[] =
-"This module provides access to matrices, eulers, quaternions and vectors.";
-
-//-----------------------------METHODS----------------------------
-//-----------------quat_rotation (internal)-----------
-//This function multiplies a vector/point * quat or vice versa
-//to rotate the point/vector by the quaternion
-//arguments should all be 3D
-PyObject *quat_rotation(PyObject *arg1, PyObject *arg2)
-{
- float rot[3];
- QuaternionObject *quat = NULL;
- VectorObject *vec = NULL;
-
- if(QuaternionObject_Check(arg1)){
- quat = (QuaternionObject*)arg1;
- if(!BaseMath_ReadCallback(quat))
- return NULL;
-
- if(VectorObject_Check(arg2)){
- vec = (VectorObject*)arg2;
-
- if(!BaseMath_ReadCallback(vec))
- return NULL;
-
- rot[0] = quat->quat[0]*quat->quat[0]*vec->vec[0] + 2*quat->quat[2]*quat->quat[0]*vec->vec[2] -
- 2*quat->quat[3]*quat->quat[0]*vec->vec[1] + quat->quat[1]*quat->quat[1]*vec->vec[0] +
- 2*quat->quat[2]*quat->quat[1]*vec->vec[1] + 2*quat->quat[3]*quat->quat[1]*vec->vec[2] -
- quat->quat[3]*quat->quat[3]*vec->vec[0] - quat->quat[2]*quat->quat[2]*vec->vec[0];
- rot[1] = 2*quat->quat[1]*quat->quat[2]*vec->vec[0] + quat->quat[2]*quat->quat[2]*vec->vec[1] +
- 2*quat->quat[3]*quat->quat[2]*vec->vec[2] + 2*quat->quat[0]*quat->quat[3]*vec->vec[0] -
- quat->quat[3]*quat->quat[3]*vec->vec[1] + quat->quat[0]*quat->quat[0]*vec->vec[1] -
- 2*quat->quat[1]*quat->quat[0]*vec->vec[2] - quat->quat[1]*quat->quat[1]*vec->vec[1];
- rot[2] = 2*quat->quat[1]*quat->quat[3]*vec->vec[0] + 2*quat->quat[2]*quat->quat[3]*vec->vec[1] +
- quat->quat[3]*quat->quat[3]*vec->vec[2] - 2*quat->quat[0]*quat->quat[2]*vec->vec[0] -
- quat->quat[2]*quat->quat[2]*vec->vec[2] + 2*quat->quat[0]*quat->quat[1]*vec->vec[1] -
- quat->quat[1]*quat->quat[1]*vec->vec[2] + quat->quat[0]*quat->quat[0]*vec->vec[2];
- return newVectorObject(rot, 3, Py_NEW, NULL);
- }
- }else if(VectorObject_Check(arg1)){
- vec = (VectorObject*)arg1;
-
- if(!BaseMath_ReadCallback(vec))
- return NULL;
-
- if(QuaternionObject_Check(arg2)){
- quat = (QuaternionObject*)arg2;
- if(!BaseMath_ReadCallback(quat))
- return NULL;
-
- rot[0] = quat->quat[0]*quat->quat[0]*vec->vec[0] + 2*quat->quat[2]*quat->quat[0]*vec->vec[2] -
- 2*quat->quat[3]*quat->quat[0]*vec->vec[1] + quat->quat[1]*quat->quat[1]*vec->vec[0] +
- 2*quat->quat[2]*quat->quat[1]*vec->vec[1] + 2*quat->quat[3]*quat->quat[1]*vec->vec[2] -
- quat->quat[3]*quat->quat[3]*vec->vec[0] - quat->quat[2]*quat->quat[2]*vec->vec[0];
- rot[1] = 2*quat->quat[1]*quat->quat[2]*vec->vec[0] + quat->quat[2]*quat->quat[2]*vec->vec[1] +
- 2*quat->quat[3]*quat->quat[2]*vec->vec[2] + 2*quat->quat[0]*quat->quat[3]*vec->vec[0] -
- quat->quat[3]*quat->quat[3]*vec->vec[1] + quat->quat[0]*quat->quat[0]*vec->vec[1] -
- 2*quat->quat[1]*quat->quat[0]*vec->vec[2] - quat->quat[1]*quat->quat[1]*vec->vec[1];
- rot[2] = 2*quat->quat[1]*quat->quat[3]*vec->vec[0] + 2*quat->quat[2]*quat->quat[3]*vec->vec[1] +
- quat->quat[3]*quat->quat[3]*vec->vec[2] - 2*quat->quat[0]*quat->quat[2]*vec->vec[0] -
- quat->quat[2]*quat->quat[2]*vec->vec[2] + 2*quat->quat[0]*quat->quat[1]*vec->vec[1] -
- quat->quat[1]*quat->quat[1]*vec->vec[2] + quat->quat[0]*quat->quat[0]*vec->vec[2];
- return newVectorObject(rot, 3, Py_NEW, NULL);
- }
- }
-
- PyErr_SetString(PyExc_RuntimeError, "quat_rotation(internal): internal problem rotating vector/point\n");
- return NULL;
-
-}
-
-//----------------------------------MATRIX FUNCTIONS--------------------
-//----------------------------------Mathutils.RotationMatrix() ----------
-//mat is a 1D array of floats - row[0][0],row[0][1], row[1][0], etc.
-static char M_Mathutils_RotationMatrix_doc[] =
-".. function:: RotationMatrix(angle, size, axis)\n"
-"\n"
-" Create a matrix representing a rotation.\n"
-"\n"
-" :arg angle: The angle of rotation desired.\n"
-" :type angle: float\n"
-" :arg size: The size of the rotation matrix to construct [2, 4].\n"
-" :type size: int\n"
-" :arg axis: a string in ['X', 'Y', 'Z'] or a 3D Vector Object (optional when size is 2).\n"
-" :type axis: string or :class:`Vector`\n"
-" :return: A new rotation matrix.\n"
-" :rtype: :class:`Matrix`\n";
-
-static PyObject *M_Mathutils_RotationMatrix(PyObject * self, PyObject * args)
-{
- VectorObject *vec= NULL;
- char *axis= NULL;
- int matSize;
- float angle = 0.0f;
- float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
-
- if(!PyArg_ParseTuple(args, "fi|O", &angle, &matSize, &vec)) {
- PyErr_SetString(PyExc_TypeError, "Mathutils.RotationMatrix(angle, size, axis): expected float int and a string or vector\n");
- return NULL;
- }
-
- if(vec && !VectorObject_Check(vec)) {
- axis= _PyUnicode_AsString((PyObject *)vec);
- if(axis==NULL || axis[0]=='\0' || axis[1]!='\0' || axis[0] < 'X' || axis[0] > 'Z') {
- PyErr_SetString(PyExc_TypeError, "Mathutils.RotationMatrix(): 3rd argument axis value must be a 3D vector or a string in 'X', 'Y', 'Z'\n");
- return NULL;
- }
- else {
- /* use the string */
- vec= NULL;
- }
- }
-
- while (angle<-(Py_PI*2))
- angle+=(Py_PI*2);
- while (angle>(Py_PI*2))
- angle-=(Py_PI*2);
-
- if(matSize != 2 && matSize != 3 && matSize != 4) {
- PyErr_SetString(PyExc_AttributeError, "Mathutils.RotationMatrix(): can only return a 2x2 3x3 or 4x4 matrix\n");
- return NULL;
- }
- if(matSize == 2 && (vec != NULL)) {
- PyErr_SetString(PyExc_AttributeError, "Mathutils.RotationMatrix(): cannot create a 2x2 rotation matrix around arbitrary axis\n");
- return NULL;
- }
- if((matSize == 3 || matSize == 4) && (axis == NULL) && (vec == NULL)) {
- PyErr_SetString(PyExc_AttributeError, "Mathutils.RotationMatrix(): please choose an axis of rotation for 3d and 4d matrices\n");
- return NULL;
- }
- if(vec) {
- if(vec->size != 3) {
- PyErr_SetString(PyExc_AttributeError, "Mathutils.RotationMatrix(): the vector axis must be a 3D vector\n");
- return NULL;
- }
-
- if(!BaseMath_ReadCallback(vec))
- return NULL;
-
- }
-
- /* check for valid vector/axis above */
- if(vec) {
- axis_angle_to_mat3( (float (*)[3])mat,vec->vec, angle);
- }
- else if(matSize == 2) {
- //2D rotation matrix
- mat[0] = (float) cos (angle);
- mat[1] = (float) sin (angle);
- mat[2] = -((float) sin(angle));
- mat[3] = (float) cos(angle);
- } else if(strcmp(axis, "X") == 0) {
- //rotation around X
- mat[0] = 1.0f;
- mat[4] = (float) cos(angle);
- mat[5] = (float) sin(angle);
- mat[7] = -((float) sin(angle));
- mat[8] = (float) cos(angle);
- } else if(strcmp(axis, "Y") == 0) {
- //rotation around Y
- mat[0] = (float) cos(angle);
- mat[2] = -((float) sin(angle));
- mat[4] = 1.0f;
- mat[6] = (float) sin(angle);
- mat[8] = (float) cos(angle);
- } else if(strcmp(axis, "Z") == 0) {
- //rotation around Z
- mat[0] = (float) cos(angle);
- mat[1] = (float) sin(angle);
- mat[3] = -((float) sin(angle));
- mat[4] = (float) cos(angle);
- mat[8] = 1.0f;
- }
- else {
- /* should never get here */
- PyErr_SetString(PyExc_AttributeError, "Mathutils.RotationMatrix(): unknown error\n");
- return NULL;
- }
-
- if(matSize == 4) {
- //resize matrix
- mat[10] = mat[8];
- mat[9] = mat[7];
- mat[8] = mat[6];
- mat[7] = 0.0f;
- mat[6] = mat[5];
- mat[5] = mat[4];
- mat[4] = mat[3];
- mat[3] = 0.0f;
- }
- //pass to matrix creation
- return newMatrixObject(mat, matSize, matSize, Py_NEW, NULL);
-}
-
-static char M_Mathutils_TranslationMatrix_doc[] =
-".. function:: TranslationMatrix(vector)\n"
-"\n"
-" Create a matrix representing a translation.\n"
-"\n"
-" :arg vector: The translation vector.\n"
-" :type vector: :class:`Vector`\n"
-" :return: An identity matrix with a translation.\n"
-" :rtype: :class:`Matrix`\n";
-
-static PyObject *M_Mathutils_TranslationMatrix(PyObject * self, VectorObject * vec)
-{
- float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
-
- if(!VectorObject_Check(vec)) {
- PyErr_SetString(PyExc_TypeError, "Mathutils.TranslationMatrix(): expected vector\n");
- return NULL;
- }
- if(vec->size != 3 && vec->size != 4) {
- PyErr_SetString(PyExc_TypeError, "Mathutils.TranslationMatrix(): vector must be 3D or 4D\n");
- return NULL;
- }
-
- if(!BaseMath_ReadCallback(vec))
- return NULL;
-
- //create a identity matrix and add translation
- unit_m4((float(*)[4]) mat);
- mat[12] = vec->vec[0];
- mat[13] = vec->vec[1];
- mat[14] = vec->vec[2];
-
- return newMatrixObject(mat, 4, 4, Py_NEW, NULL);
-}
-//----------------------------------Mathutils.ScaleMatrix() -------------
-//mat is a 1D array of floats - row[0][0],row[0][1], row[1][0], etc.
-static char M_Mathutils_ScaleMatrix_doc[] =
-".. function:: ScaleMatrix(factor, size, axis)\n"
-"\n"
-" Create a matrix representing a scaling.\n"
-"\n"
-" :arg factor: The factor of scaling to apply.\n"
-" :type factor: float\n"
-" :arg size: The size of the scale matrix to construct [2, 4].\n"
-" :type size: int\n"
-" :arg axis: Direction to influence scale. (optional).\n"
-" :type axis: :class:`Vector`\n"
-" :return: A new scale matrix.\n"
-" :rtype: :class:`Matrix`\n";
-
-static PyObject *M_Mathutils_ScaleMatrix(PyObject * self, PyObject * args)
-{
- VectorObject *vec = NULL;
- float norm = 0.0f, factor;
- int matSize, x;
- float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
-
- if(!PyArg_ParseTuple(args, "fi|O!", &factor, &matSize, &vector_Type, &vec)) {
- PyErr_SetString(PyExc_TypeError, "Mathutils.ScaleMatrix(): expected float int and optional vector\n");
- return NULL;
- }
- if(matSize != 2 && matSize != 3 && matSize != 4) {
- PyErr_SetString(PyExc_AttributeError, "Mathutils.ScaleMatrix(): can only return a 2x2 3x3 or 4x4 matrix\n");
- return NULL;
- }
- if(vec) {
- if(vec->size > 2 && matSize == 2) {
- PyErr_SetString(PyExc_AttributeError, "Mathutils.ScaleMatrix(): please use 2D vectors when scaling in 2D\n");
- return NULL;
- }
-
- if(!BaseMath_ReadCallback(vec))
- return NULL;
-
- }
- if(vec == NULL) { //scaling along axis
- if(matSize == 2) {
- mat[0] = factor;
- mat[3] = factor;
- } else {
- mat[0] = factor;
- mat[4] = factor;
- mat[8] = factor;
- }
- } else { //scaling in arbitrary direction
- //normalize arbitrary axis
- for(x = 0; x < vec->size; x++) {
- norm += vec->vec[x] * vec->vec[x];
- }
- norm = (float) sqrt(norm);
- for(x = 0; x < vec->size; x++) {
- vec->vec[x] /= norm;
- }
- if(matSize == 2) {
- mat[0] = 1 +((factor - 1) *(vec->vec[0] * vec->vec[0]));
- mat[1] =((factor - 1) *(vec->vec[0] * vec->vec[1]));
- mat[2] =((factor - 1) *(vec->vec[0] * vec->vec[1]));
- mat[3] = 1 + ((factor - 1) *(vec->vec[1] * vec->vec[1]));
- } else {
- mat[0] = 1 + ((factor - 1) *(vec->vec[0] * vec->vec[0]));
- mat[1] =((factor - 1) *(vec->vec[0] * vec->vec[1]));
- mat[2] =((factor - 1) *(vec->vec[0] * vec->vec[2]));
- mat[3] =((factor - 1) *(vec->vec[0] * vec->vec[1]));
- mat[4] = 1 + ((factor - 1) *(vec->vec[1] * vec->vec[1]));
- mat[5] =((factor - 1) *(vec->vec[1] * vec->vec[2]));
- mat[6] =((factor - 1) *(vec->vec[0] * vec->vec[2]));
- mat[7] =((factor - 1) *(vec->vec[1] * vec->vec[2]));
- mat[8] = 1 + ((factor - 1) *(vec->vec[2] * vec->vec[2]));
- }
- }
- if(matSize == 4) {
- //resize matrix
- mat[10] = mat[8];
- mat[9] = mat[7];
- mat[8] = mat[6];
- mat[7] = 0.0f;
- mat[6] = mat[5];
- mat[5] = mat[4];
- mat[4] = mat[3];
- mat[3] = 0.0f;
- }
- //pass to matrix creation
- return newMatrixObject(mat, matSize, matSize, Py_NEW, NULL);
-}
-//----------------------------------Mathutils.OrthoProjectionMatrix() ---
-//mat is a 1D array of floats - row[0][0],row[0][1], row[1][0], etc.
-static char M_Mathutils_OrthoProjectionMatrix_doc[] =
-".. function:: OrthoProjectionMatrix(plane, size, axis)\n"
-"\n"
-" Create a matrix to represent an orthographic projection.\n"
-"\n"
-" :arg plane: Can be any of the following: ['X', 'Y', 'XY', 'XZ', 'YZ', 'R'], where a single axis is for a 2D matrix and 'R' requires axis is given.\n"
-" :type plane: string\n"
-" :arg size: The size of the projection matrix to construct [2, 4].\n"
-" :type size: int\n"
-" :arg axis: Arbitrary perpendicular plane vector (optional).\n"
-" :type axis: :class:`Vector`\n"
-" :return: A new projection matrix.\n"
-" :rtype: :class:`Matrix`\n";
-static PyObject *M_Mathutils_OrthoProjectionMatrix(PyObject * self, PyObject * args)
-{
- VectorObject *vec = NULL;
- char *plane;
- int matSize, x;
- float norm = 0.0f;
- float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
-
- if(!PyArg_ParseTuple(args, "si|O!", &plane, &matSize, &vector_Type, &vec)) {
- PyErr_SetString(PyExc_TypeError, "Mathutils.OrthoProjectionMatrix(): expected string and int and optional vector\n");
- return NULL;
- }
- if(matSize != 2 && matSize != 3 && matSize != 4) {
- PyErr_SetString(PyExc_AttributeError,"Mathutils.OrthoProjectionMatrix(): can only return a 2x2 3x3 or 4x4 matrix\n");
- return NULL;
- }
- if(vec) {
- if(vec->size > 2 && matSize == 2) {
- PyErr_SetString(PyExc_AttributeError, "Mathutils.OrthoProjectionMatrix(): please use 2D vectors when scaling in 2D\n");
- return NULL;
- }
-
- if(!BaseMath_ReadCallback(vec))
- return NULL;
-
- }
- if(vec == NULL) { //ortho projection onto cardinal plane
- if((strcmp(plane, "X") == 0) && matSize == 2) {
- mat[0] = 1.0f;
- } else if((strcmp(plane, "Y") == 0) && matSize == 2) {
- mat[3] = 1.0f;
- } else if((strcmp(plane, "XY") == 0) && matSize > 2) {
- mat[0] = 1.0f;
- mat[4] = 1.0f;
- } else if((strcmp(plane, "XZ") == 0) && matSize > 2) {
- mat[0] = 1.0f;
- mat[8] = 1.0f;
- } else if((strcmp(plane, "YZ") == 0) && matSize > 2) {
- mat[4] = 1.0f;
- mat[8] = 1.0f;
- } else {
- PyErr_SetString(PyExc_AttributeError, "Mathutils.OrthoProjectionMatrix(): unknown plane - expected: X, Y, XY, XZ, YZ\n");
- return NULL;
- }
- } else { //arbitrary plane
- //normalize arbitrary axis
- for(x = 0; x < vec->size; x++) {
- norm += vec->vec[x] * vec->vec[x];
- }
- norm = (float) sqrt(norm);
- for(x = 0; x < vec->size; x++) {
- vec->vec[x] /= norm;
- }
- if((strcmp(plane, "R") == 0) && matSize == 2) {
- mat[0] = 1 - (vec->vec[0] * vec->vec[0]);
- mat[1] = -(vec->vec[0] * vec->vec[1]);
- mat[2] = -(vec->vec[0] * vec->vec[1]);
- mat[3] = 1 - (vec->vec[1] * vec->vec[1]);
- } else if((strcmp(plane, "R") == 0) && matSize > 2) {
- mat[0] = 1 - (vec->vec[0] * vec->vec[0]);
- mat[1] = -(vec->vec[0] * vec->vec[1]);
- mat[2] = -(vec->vec[0] * vec->vec[2]);
- mat[3] = -(vec->vec[0] * vec->vec[1]);
- mat[4] = 1 - (vec->vec[1] * vec->vec[1]);
- mat[5] = -(vec->vec[1] * vec->vec[2]);
- mat[6] = -(vec->vec[0] * vec->vec[2]);
- mat[7] = -(vec->vec[1] * vec->vec[2]);
- mat[8] = 1 - (vec->vec[2] * vec->vec[2]);
- } else {
- PyErr_SetString(PyExc_AttributeError, "Mathutils.OrthoProjectionMatrix(): unknown plane - expected: 'r' expected for axis designation\n");
- return NULL;
- }
- }
- if(matSize == 4) {
- //resize matrix
- mat[10] = mat[8];
- mat[9] = mat[7];
- mat[8] = mat[6];
- mat[7] = 0.0f;
- mat[6] = mat[5];
- mat[5] = mat[4];
- mat[4] = mat[3];
- mat[3] = 0.0f;
- }
- //pass to matrix creation
- return newMatrixObject(mat, matSize, matSize, Py_NEW, NULL);
-}
-
-static char M_Mathutils_ShearMatrix_doc[] =
-".. function:: ShearMatrix(plane, factor, size)\n"
-"\n"
-" Create a matrix to represent an shear transformation.\n"
-"\n"
-" :arg plane: Can be any of the following: ['X', 'Y', 'XY', 'XZ', 'YZ'], where a single axis is for a 2D matrix.\n"
-" :type plane: string\n"
-" :arg factor: The factor of shear to apply.\n"
-" :type factor: float\n"
-" :arg size: The size of the shear matrix to construct [2, 4].\n"
-" :type size: int\n"
-" :return: A new shear matrix.\n"
-" :rtype: :class:`Matrix`\n";
-
-static PyObject *M_Mathutils_ShearMatrix(PyObject * self, PyObject * args)
-{
- int matSize;
- char *plane;
- float factor;
- float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
- 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
-
- if(!PyArg_ParseTuple(args, "sfi", &plane, &factor, &matSize)) {
- PyErr_SetString(PyExc_TypeError,"Mathutils.ShearMatrix(): expected string float and int\n");
- return NULL;
- }
- if(matSize != 2 && matSize != 3 && matSize != 4) {
- PyErr_SetString(PyExc_AttributeError,"Mathutils.ShearMatrix(): can only return a 2x2 3x3 or 4x4 matrix\n");
- return NULL;
- }
-
- if((strcmp(plane, "X") == 0)
- && matSize == 2) {
- mat[0] = 1.0f;
- mat[2] = factor;
- mat[3] = 1.0f;
- } else if((strcmp(plane, "Y") == 0) && matSize == 2) {
- mat[0] = 1.0f;
- mat[1] = factor;
- mat[3] = 1.0f;
- } else if((strcmp(plane, "XY") == 0) && matSize > 2) {
- mat[0] = 1.0f;
- mat[4] = 1.0f;
- mat[6] = factor;
- mat[7] = factor;
- } else if((strcmp(plane, "XZ") == 0) && matSize > 2) {
- mat[0] = 1.0f;
- mat[3] = factor;
- mat[4] = 1.0f;
- mat[5] = factor;
- mat[8] = 1.0f;
- } else if((strcmp(plane, "YZ") == 0) && matSize > 2) {
- mat[0] = 1.0f;
- mat[1] = factor;
- mat[2] = factor;
- mat[4] = 1.0f;
- mat[8] = 1.0f;
- } else {
- PyErr_SetString(PyExc_AttributeError, "Mathutils.ShearMatrix(): expected: x, y, xy, xz, yz or wrong matrix size for shearing plane\n");
- return NULL;
- }
- if(matSize == 4) {
- //resize matrix
- mat[10] = mat[8];
- mat[9] = mat[7];
- mat[8] = mat[6];
- mat[7] = 0.0f;
- mat[6] = mat[5];
- mat[5] = mat[4];
- mat[4] = mat[3];
- mat[3] = 0.0f;
- }
- //pass to matrix creation
- return newMatrixObject(mat, matSize, matSize, Py_NEW, NULL);
-}
-
-/* Utility functions */
-
-// LomontRRDCompare4, Ever Faster Float Comparisons by Randy Dillon
-#define SIGNMASK(i) (-(int)(((unsigned int)(i))>>31))
-
-int EXPP_FloatsAreEqual(float af, float bf, int maxDiff)
-{ // solid, fast routine across all platforms
- // with constant time behavior
- int ai = *(int *)(&af);
- int bi = *(int *)(&bf);
- int test = SIGNMASK(ai^bi);
- int diff, v1, v2;
-
- assert((0 == test) || (0xFFFFFFFF == test));
- diff = (ai ^ (test & 0x7fffffff)) - bi;
- v1 = maxDiff + diff;
- v2 = maxDiff - diff;
- return (v1|v2) >= 0;
-}
-
-/*---------------------- EXPP_VectorsAreEqual -------------------------
- Builds on EXPP_FloatsAreEqual to test vectors */
-int EXPP_VectorsAreEqual(float *vecA, float *vecB, int size, int floatSteps)
-{
- int x;
- for (x=0; x< size; x++){
- if (EXPP_FloatsAreEqual(vecA[x], vecB[x], floatSteps) == 0)
- return 0;
- }
- return 1;
-}
-
-
-/* Mathutils Callbacks */
-
-/* for mathutils internal use only, eventually should re-alloc but to start with we only have a few users */
-Mathutils_Callback *mathutils_callbacks[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
-
-int Mathutils_RegisterCallback(Mathutils_Callback *cb)
-{
- int i;
-
- /* find the first free slot */
- for(i= 0; mathutils_callbacks[i]; i++) {
- if(mathutils_callbacks[i]==cb) /* alredy registered? */
- return i;
- }
-
- mathutils_callbacks[i] = cb;
- return i;
-}
-
-/* use macros to check for NULL */
-int _BaseMathObject_ReadCallback(BaseMathObject *self)
-{
- Mathutils_Callback *cb= mathutils_callbacks[self->cb_type];
- if(cb->get(self->cb_user, self->cb_subtype, self->data))
- return 1;
-
- PyErr_Format(PyExc_SystemError, "%s user has become invalid", Py_TYPE(self)->tp_name);
- return 0;
-}
-
-int _BaseMathObject_WriteCallback(BaseMathObject *self)
-{
- Mathutils_Callback *cb= mathutils_callbacks[self->cb_type];
- if(cb->set(self->cb_user, self->cb_subtype, self->data))
- return 1;
-
- PyErr_Format(PyExc_SystemError, "%s user has become invalid", Py_TYPE(self)->tp_name);
- return 0;
-}
-
-int _BaseMathObject_ReadIndexCallback(BaseMathObject *self, int index)
-{
- Mathutils_Callback *cb= mathutils_callbacks[self->cb_type];
- if(cb->get_index(self->cb_user, self->cb_subtype, self->data, index))
- return 1;
-
- PyErr_Format(PyExc_SystemError, "%s user has become invalid", Py_TYPE(self)->tp_name);
- return 0;
-}
-
-int _BaseMathObject_WriteIndexCallback(BaseMathObject *self, int index)
-{
- Mathutils_Callback *cb= mathutils_callbacks[self->cb_type];
- if(cb->set_index(self->cb_user, self->cb_subtype, self->data, index))
- return 1;
-
- PyErr_Format(PyExc_SystemError, "%s user has become invalid", Py_TYPE(self)->tp_name);
- return 0;
-}
-
-/* BaseMathObject generic functions for all mathutils types */
-char BaseMathObject_Owner_doc[] = "The item this is wrapping or None (readonly).";
-PyObject *BaseMathObject_getOwner( BaseMathObject * self, void *type )
-{
- PyObject *ret= self->cb_user ? self->cb_user : Py_None;
- Py_INCREF(ret);
- return ret;
-}
-
-char BaseMathObject_Wrapped_doc[] = "True when this object wraps external data (readonly). **type** boolean";
-PyObject *BaseMathObject_getWrapped( BaseMathObject *self, void *type )
-{
- return PyBool_FromLong((self->wrapped == Py_WRAP) ? 1:0);
-}
-
-void BaseMathObject_dealloc(BaseMathObject * self)
-{
- /* only free non wrapped */
- if(self->wrapped != Py_WRAP)
- PyMem_Free(self->data);
-
- Py_XDECREF(self->cb_user);
- Py_TYPE(self)->tp_free(self); // PyObject_DEL(self); // breaks subtypes
-}
-
-/*----------------------------MODULE INIT-------------------------*/
-struct PyMethodDef M_Mathutils_methods[] = {
- {"RotationMatrix", (PyCFunction) M_Mathutils_RotationMatrix, METH_VARARGS, M_Mathutils_RotationMatrix_doc},
- {"ScaleMatrix", (PyCFunction) M_Mathutils_ScaleMatrix, METH_VARARGS, M_Mathutils_ScaleMatrix_doc},
- {"ShearMatrix", (PyCFunction) M_Mathutils_ShearMatrix, METH_VARARGS, M_Mathutils_ShearMatrix_doc},
- {"TranslationMatrix", (PyCFunction) M_Mathutils_TranslationMatrix, METH_O, M_Mathutils_TranslationMatrix_doc},
- {"OrthoProjectionMatrix", (PyCFunction) M_Mathutils_OrthoProjectionMatrix, METH_VARARGS, M_Mathutils_OrthoProjectionMatrix_doc},
- {NULL, NULL, 0, NULL}
-};
-
-static struct PyModuleDef M_Mathutils_module_def = {
- PyModuleDef_HEAD_INIT,
- "Mathutils", /* m_name */
- M_Mathutils_doc, /* m_doc */
- 0, /* m_size */
- M_Mathutils_methods, /* m_methods */
- 0, /* m_reload */
- 0, /* m_traverse */
- 0, /* m_clear */
- 0, /* m_free */
-};
-
-PyObject *Mathutils_Init(void)
-{
- PyObject *submodule;
-
- if( PyType_Ready( &vector_Type ) < 0 )
- return NULL;
- if( PyType_Ready( &matrix_Type ) < 0 )
- return NULL;
- if( PyType_Ready( &euler_Type ) < 0 )
- return NULL;
- if( PyType_Ready( &quaternion_Type ) < 0 )
- return NULL;
-
- submodule = PyModule_Create(&M_Mathutils_module_def);
- PyDict_SetItemString(PySys_GetObject("modules"), M_Mathutils_module_def.m_name, submodule);
-
- /* each type has its own new() function */
- PyModule_AddObject( submodule, "Vector", (PyObject *)&vector_Type );
- PyModule_AddObject( submodule, "Matrix", (PyObject *)&matrix_Type );
- PyModule_AddObject( submodule, "Euler", (PyObject *)&euler_Type );
- PyModule_AddObject( submodule, "Quaternion", (PyObject *)&quaternion_Type );
-
- mathutils_matrix_vector_cb_index= Mathutils_RegisterCallback(&mathutils_matrix_vector_cb);
-
- return (submodule);
-}
diff --git a/source/blender/python/generic/bgl.c b/source/blender/python/generic/bgl.c
index 63c518c8721..8ac2107f8d2 100644
--- a/source/blender/python/generic/bgl.c
+++ b/source/blender/python/generic/bgl.c
@@ -27,9 +27,8 @@
* ***** END GPL LICENSE BLOCK *****
*/
-/* This file is the Blender.BGL part of opy_draw.c, from the old
- * bpython/intern dir, with minor changes to adapt it to the new Python
- * implementation. The BGL submodule "wraps" OpenGL functions and constants,
+/* This file is the 'bgl' module.
+ * The BGL submodule "wraps" OpenGL functions and constants,
* allowing script writers to make OpenGL calls in their Python scripts. */
#include "bgl.h" /*This must come first */
@@ -64,13 +63,16 @@ static int Buffer_ass_slice( PyObject * self, int begin, int end,
PyObject * seq );
static PySequenceMethods Buffer_SeqMethods = {
- ( lenfunc ) Buffer_len, /*sq_length */
- ( binaryfunc ) 0, /*sq_concat */
- ( ssizeargfunc ) 0, /*sq_repeat */
- ( ssizeargfunc ) Buffer_item, /*sq_item */
- ( ssizessizeargfunc ) Buffer_slice, /*sq_slice */
- ( ssizeobjargproc ) Buffer_ass_item, /*sq_ass_item */
- ( ssizessizeobjargproc ) Buffer_ass_slice, /*sq_ass_slice */
+ ( lenfunc ) Buffer_len, /*sq_length */
+ ( binaryfunc ) NULL, /*sq_concat */
+ ( ssizeargfunc ) NULL, /*sq_repeat */
+ ( ssizeargfunc ) Buffer_item, /*sq_item */
+ ( ssizessizeargfunc ) Buffer_slice, /*sq_slice, deprecated TODO, replace */
+ ( ssizeobjargproc ) Buffer_ass_item, /*sq_ass_item */
+ ( ssizessizeobjargproc ) Buffer_ass_slice, /*sq_ass_slice, deprecated TODO, replace */
+ (objobjproc) NULL, /* sq_contains */
+ (binaryfunc) NULL, /* sq_inplace_concat */
+ (ssizeargfunc) NULL, /* sq_inplace_repeat */
};
static void Buffer_dealloc( PyObject * self );
@@ -319,20 +321,20 @@ static int Buffer_ass_item(PyObject *self, int i, PyObject *v)
}
if (buf->type==GL_BYTE) {
- if (!PyArg_Parse(v, "b;Coordinates must be ints", &buf->buf.asbyte[i]))
+ if (!PyArg_Parse(v, "b:Coordinates must be ints", &buf->buf.asbyte[i]))
return -1;
} else if (buf->type==GL_SHORT) {
- if (!PyArg_Parse(v, "h;Coordinates must be ints", &buf->buf.asshort[i]))
+ if (!PyArg_Parse(v, "h:Coordinates must be ints", &buf->buf.asshort[i]))
return -1;
} else if (buf->type==GL_INT) {
- if (!PyArg_Parse(v, "i;Coordinates must be ints", &buf->buf.asint[i]))
+ if (!PyArg_Parse(v, "i:Coordinates must be ints", &buf->buf.asint[i]))
return -1;
} else if (buf->type==GL_FLOAT) {
- if (!PyArg_Parse(v, "f;Coordinates must be floats", &buf->buf.asfloat[i]))
+ if (!PyArg_Parse(v, "f:Coordinates must be floats", &buf->buf.asfloat[i]))
return -1;
} else if (buf->type==GL_DOUBLE) {
- if (!PyArg_Parse(v, "d;Coordinates must be floats", &buf->buf.asdouble[i]))
+ if (!PyArg_Parse(v, "d:Coordinates must be floats", &buf->buf.asdouble[i]))
return -1;
}
return 0;
@@ -1115,7 +1117,7 @@ PyObject *BGL_Init(void)
{
PyObject *mod, *dict, *item;
mod = PyModule_Create(&BGL_module_def);
- PyDict_SetItemString(PySys_GetObject("modules"), BGL_module_def.m_name, mod);
+ PyDict_SetItemString(PyImport_GetModuleDict(), BGL_module_def.m_name, mod);
dict= PyModule_GetDict(mod);
if( PyType_Ready( &BGL_bufferType) < 0)
diff --git a/source/blender/python/generic/bgl.h b/source/blender/python/generic/bgl.h
index 89bade930ce..80b0b90f643 100644
--- a/source/blender/python/generic/bgl.h
+++ b/source/blender/python/generic/bgl.h
@@ -36,10 +36,6 @@
#ifndef EXPP_BGL_H
#define EXPP_BGL_H
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
-
#include <Python.h>
PyObject *BGL_Init(void);
diff --git a/source/blender/python/generic/blf.c b/source/blender/python/generic/blf_api.c
index eda13db57b5..a5f5f8815c7 100644
--- a/source/blender/python/generic/blf.c
+++ b/source/blender/python/generic/blf_api.c
@@ -23,33 +23,45 @@
*/
#include <Python.h>
-#include "blf.h"
+#include "blf_api.h"
#include "../../blenfont/BLF_api.h"
static char py_blf_position_doc[] =
-".. function:: position(x, y, z)\n"
+".. function:: position(fontid, x, y, z)\n"
"\n"
-" Set the position for drawing text.\n";
+" Set the position for drawing text.\n"
+"\n"
+" :arg fontid: The id of the typeface as returned by :func:`blf.load`, for default font use 0.\n"
+" :type fontid: int\n"
+" :arg x: X axis position to draw the text.\n"
+" :type x: float\n"
+" :arg y: Y axis position to draw the text.\n"
+" :type y: float\n"
+" :arg z: Z axis position to draw the text.\n"
+" :type z: float\n";
static PyObject *py_blf_position(PyObject *self, PyObject *args)
{
+ int fontid;
float x, y, z;
- if (!PyArg_ParseTuple(args, "fff:BLF.position", &x, &y, &z))
+ if (!PyArg_ParseTuple(args, "ifff:blf.position", &fontid, &x, &y, &z))
return NULL;
- BLF_position(x, y, z);
+ BLF_position(fontid, x, y, z);
Py_RETURN_NONE;
}
static char py_blf_size_doc[] =
-".. function:: size(size, dpi)\n"
+".. function:: size(fontid, size, dpi)\n"
"\n"
" Set the size and dpi for drawing text.\n"
"\n"
+" :arg fontid: The id of the typeface as returned by :func:`blf.load`, for default font use 0.\n"
+" :type fontid: int\n"
" :arg size: Point size of the font.\n"
" :type size: int\n"
" :arg dpi: dots per inch value to use for drawing.\n"
@@ -57,84 +69,94 @@ static char py_blf_size_doc[] =
static PyObject *py_blf_size(PyObject *self, PyObject *args)
{
- int size, dpi;
+ int fontid, size, dpi;
- if (!PyArg_ParseTuple(args, "ii:BLF.size", &size, &dpi))
+ if (!PyArg_ParseTuple(args, "iii:blf.size", &fontid, &size, &dpi))
return NULL;
- BLF_size(size, dpi);
+ BLF_size(fontid, size, dpi);
Py_RETURN_NONE;
}
static char py_blf_aspect_doc[] =
-".. function:: aspect(aspect)\n"
+".. function:: aspect(fontid, aspect)\n"
"\n"
" Set the aspect for drawing text.\n"
"\n"
+" :arg fontid: The id of the typeface as returned by :func:`blf.load`, for default font use 0.\n"
+" :type fontid: int\n"
" :arg aspect: The aspect ratio for text drawing to use.\n"
" :type aspect: float\n";
static PyObject *py_blf_aspect(PyObject *self, PyObject *args)
{
float aspect;
+ int fontid;
- if (!PyArg_ParseTuple(args, "f:BLF.aspect", &aspect))
+ if (!PyArg_ParseTuple(args, "if:blf.aspect", &fontid, &aspect))
return NULL;
- BLF_aspect(aspect);
+ BLF_aspect(fontid, aspect);
Py_RETURN_NONE;
}
static char py_blf_blur_doc[] =
-".. function:: blur(radius)\n"
+".. function:: blur(fontid, radius)\n"
"\n"
" Set the blur radius for drawing text.\n"
"\n"
+" :arg fontid: The id of the typeface as returned by :func:`blf.load`, for default font use 0.\n"
+" :type fontid: int\n"
" :arg radius: The radius for blurring text (in pixels).\n"
" :type radius: int\n";
static PyObject *py_blf_blur(PyObject *self, PyObject *args)
{
- int blur;
+ int blur, fontid;
- if (!PyArg_ParseTuple(args, "i:BLF.blur", &blur))
+ if (!PyArg_ParseTuple(args, "ii:blf.blur", &fontid, &blur))
return NULL;
- BLF_blur(blur);
+ BLF_blur(fontid, blur);
Py_RETURN_NONE;
}
static char py_blf_draw_doc[] =
-".. function:: draw(text)\n"
+".. function:: draw(fontid, text)\n"
"\n"
" Draw text in the current context.\n"
"\n"
+" :arg fontid: The id of the typeface as returned by :func:`blf.load`, for default font use 0.\n"
+" :type fontid: int\n"
" :arg text: the text to draw.\n"
" :type text: string\n";
static PyObject *py_blf_draw(PyObject *self, PyObject *args)
{
char *text;
+ int fontid;
- if (!PyArg_ParseTuple(args, "s:BLF.draw", &text))
+ if (!PyArg_ParseTuple(args, "is:blf.draw", &fontid, &text))
return NULL;
- BLF_draw(text);
+ BLF_draw(fontid, text);
Py_RETURN_NONE;
}
static char py_blf_dimensions_doc[] =
-".. function:: dimensions(text)\n"
+".. function:: dimensions(fontid, text)\n"
"\n"
-" Return the width and hight of the text.\n"
+" Return the width and height of the text.\n"
"\n"
+" :arg fontid: The id of the typeface as returned by :func:`blf.load`, for default font use 0.\n"
+" :type fontid: int\n"
" :arg text: the text to draw.\n"
" :type text: string\n"
" :return: the width and height of the text.\n"
@@ -145,11 +167,12 @@ static PyObject *py_blf_dimensions(PyObject *self, PyObject *args)
char *text;
float r_width, r_height;
PyObject *ret;
+ int fontid;
- if (!PyArg_ParseTuple(args, "s:BLF.dimensions", &text))
+ if (!PyArg_ParseTuple(args, "is:blf.dimensions", &fontid, &text))
return NULL;
- BLF_width_and_height(text, &r_width, &r_height);
+ BLF_width_and_height(fontid, text, &r_width, &r_height);
ret= PyTuple_New(2);
PyTuple_SET_ITEM(ret, 0, PyFloat_FromDouble(r_width));
@@ -158,96 +181,125 @@ static PyObject *py_blf_dimensions(PyObject *self, PyObject *args)
}
static char py_blf_clipping_doc[] =
-".. function:: clipping(xmin, ymin, xmax, ymax)\n"
+".. function:: clipping(fontid, xmin, ymin, xmax, ymax)\n"
+"\n"
+" Set the clipping, enable/disable using CLIPPING.\n"
"\n"
-" Set the clipping, enable/disable using CLIPPING.\n";
+" :arg fontid: The id of the typeface as returned by :func:`blf.load`, for default font use 0.\n"
+" :type fontid: int\n"
+" :arg xmin: Clip the drawing area by these bounds.\n"
+" :type xmin: float\n"
+" :arg ymin: Clip the drawing area by these bounds.\n"
+" :type ymin: float\n"
+" :arg xmax: Clip the drawing area by these bounds.\n"
+" :type xmax: float\n"
+" :arg ymax: Clip the drawing area by these bounds.\n"
+" :type ymax: float\n";
static PyObject *py_blf_clipping(PyObject *self, PyObject *args)
{
float xmin, ymin, xmax, ymax;
+ int fontid;
- if (!PyArg_ParseTuple(args, "ffff:BLF.clipping", &xmin, &ymin, &xmax, &ymax))
+ if (!PyArg_ParseTuple(args, "iffff:blf.clipping", &fontid, &xmin, &ymin, &xmax, &ymax))
return NULL;
- BLF_clipping(xmin, ymin, xmax, ymax);
+ BLF_clipping(fontid, xmin, ymin, xmax, ymax);
Py_RETURN_NONE;
}
static char py_blf_disable_doc[] =
-".. function:: disable(option)\n"
+".. function:: disable(fontid, option)\n"
"\n"
" Disable option.\n"
"\n"
+" :arg fontid: The id of the typeface as returned by :func:`blf.load`, for default font use 0.\n"
+" :type fontid: int\n"
" :arg option: One of ROTATION, CLIPPING, SHADOW or KERNING_DEFAULT.\n"
" :type option: int\n";
static PyObject *py_blf_disable(PyObject *self, PyObject *args)
{
- int option;
+ int option, fontid;
- if (!PyArg_ParseTuple(args, "i:BLF.disable", &option))
+ if (!PyArg_ParseTuple(args, "ii:blf.disable", &fontid, &option))
return NULL;
- BLF_disable(option);
+ BLF_disable(fontid, option);
Py_RETURN_NONE;
}
static char py_blf_enable_doc[] =
-".. function:: enable(option)\n"
+".. function:: enable(fontid, option)\n"
"\n"
" Enable option.\n"
"\n"
+" :arg fontid: The id of the typeface as returned by :func:`blf.load`, for default font use 0.\n"
+" :type fontid: int\n"
" :arg option: One of ROTATION, CLIPPING, SHADOW or KERNING_DEFAULT.\n"
" :type option: int\n";
static PyObject *py_blf_enable(PyObject *self, PyObject *args)
{
- int option;
+ int option, fontid;
- if (!PyArg_ParseTuple(args, "i:BLF.enable", &option))
+ if (!PyArg_ParseTuple(args, "ii:blf.enable", &fontid, &option))
return NULL;
- BLF_enable(option);
+ BLF_enable(fontid, option);
Py_RETURN_NONE;
}
static char py_blf_rotation_doc[] =
-".. function:: rotation(angle)\n"
+".. function:: rotation(fontid, angle)\n"
"\n"
" Set the text rotation angle, enable/disable using ROTATION.\n"
"\n"
+" :arg fontid: The id of the typeface as returned by :func:`blf.load`, for default font use 0.\n"
+" :type fontid: int\n"
" :arg angle: The angle for text drawing to use.\n"
-" :type aspect: float\n";
+" :type angle: float\n";
static PyObject *py_blf_rotation(PyObject *self, PyObject *args)
{
float angle;
+ int fontid;
- if (!PyArg_ParseTuple(args, "f:BLF.rotation", &angle))
+ if (!PyArg_ParseTuple(args, "if:blf.rotation", &fontid, &angle))
return NULL;
- BLF_rotation(angle);
+ BLF_rotation(fontid, angle);
Py_RETURN_NONE;
}
static char py_blf_shadow_doc[] =
-".. function:: shadow(level, r, g, b, a)\n"
+".. function:: shadow(fontid, level, r, g, b, a)\n"
"\n"
" Shadow options, enable/disable using SHADOW .\n"
"\n"
+" :arg fontid: The id of the typeface as returned by :func:`blf.load`, for default font use 0.\n"
+" :type fontid: int\n"
" :arg level: The blur level, can be 3, 5 or 0.\n"
-" :type level: int\n";
+" :type level: int\n"
+" :arg r: Shadow color (red channel 0.0 - 1.0).\n"
+" :type r: float\n"
+" :arg g: Shadow color (green channel 0.0 - 1.0).\n"
+" :type g: float\n"
+" :arg b: Shadow color (blue channel 0.0 - 1.0).\n"
+" :type b: float\n"
+" :arg a: Shadow color (alpha channel 0.0 - 1.0).\n"
+" :type a: float\n";
static PyObject *py_blf_shadow(PyObject *self, PyObject *args)
{
- int level;
+ int level, fontid;
float r, g, b, a;
- if (!PyArg_ParseTuple(args, "iffff:BLF.shadow", &level, &r, &g, &b, &a))
+ if (!PyArg_ParseTuple(args, "iiffff:blf.shadow", &fontid, &level, &r, &g, &b, &a))
return NULL;
if (level != 0 && level != 3 && level != 5) {
@@ -255,28 +307,55 @@ static PyObject *py_blf_shadow(PyObject *self, PyObject *args)
return NULL;
}
- BLF_shadow(level, r, g, b, a);
+ BLF_shadow(fontid, level, r, g, b, a);
Py_RETURN_NONE;
}
static char py_blf_shadow_offset_doc[] =
-".. function:: shadow_offset(x, y)\n"
+".. function:: shadow_offset(fontid, x, y)\n"
+"\n"
+" Set the offset for shadow text.\n"
"\n"
-" Set the offset for shadow text.\n";
+" :arg fontid: The id of the typeface as returned by :func:`blf.load`, for default font use 0.\n"
+" :type fontid: int\n"
+" :arg x: Vertical shadow offset value in pixels.\n"
+" :type x: float\n"
+" :arg y: Horizontal shadow offset value in pixels.\n"
+" :type y: float\n";
static PyObject *py_blf_shadow_offset(PyObject *self, PyObject *args)
{
- int x, y;
+ int x, y, fontid;
- if (!PyArg_ParseTuple(args, "ii:BLF.shadow_offset", &x, &y))
+ if (!PyArg_ParseTuple(args, "iii:blf.shadow_offset", &fontid, &x, &y))
return NULL;
- BLF_shadow_offset(x, y);
+ BLF_shadow_offset(fontid, x, y);
Py_RETURN_NONE;
}
+static char py_blf_load_doc[] =
+".. function:: load(filename)\n"
+"\n"
+" Load a new font.\n"
+"\n"
+" :arg filename: the filename of the font.\n"
+" :type filename: string\n"
+" :return: the new font's fontid or -1 if there was an error.\n"
+" :rtype: integer\n";
+
+static PyObject *py_blf_load(PyObject *self, PyObject *args)
+{
+ char* filename;
+
+ if (!PyArg_ParseTuple(args, "s:blf.load", &filename))
+ return NULL;
+
+ return PyLong_FromLong(BLF_load(filename));
+}
+
/*----------------------------MODULE INIT-------------------------*/
struct PyMethodDef BLF_methods[] = {
{"aspect", (PyCFunction) py_blf_aspect, METH_VARARGS, py_blf_aspect_doc},
@@ -291,6 +370,7 @@ struct PyMethodDef BLF_methods[] = {
{"shadow", (PyCFunction) py_blf_shadow, METH_VARARGS, py_blf_shadow_doc},
{"shadow_offset", (PyCFunction) py_blf_shadow_offset, METH_VARARGS, py_blf_shadow_offset_doc},
{"size", (PyCFunction) py_blf_size, METH_VARARGS, py_blf_size_doc},
+ {"load", (PyCFunction) py_blf_load, METH_VARARGS, py_blf_load_doc},
{NULL, NULL, 0, NULL}
};
@@ -314,7 +394,7 @@ PyObject *BLF_Init(void)
PyObject *submodule;
submodule = PyModule_Create(&BLF_module_def);
- PyDict_SetItemString(PySys_GetObject("modules"), BLF_module_def.m_name, submodule);
+ PyDict_SetItemString(PyImport_GetModuleDict(), BLF_module_def.m_name, submodule);
PyModule_AddIntConstant(submodule, "ROTATION", BLF_ROTATION);
PyModule_AddIntConstant(submodule, "CLIPPING", BLF_CLIPPING);
diff --git a/source/blender/python/generic/blf.h b/source/blender/python/generic/blf_api.h
index fae20ace996..fae20ace996 100644
--- a/source/blender/python/generic/blf.h
+++ b/source/blender/python/generic/blf_api.h
diff --git a/source/blender/python/generic/bpy_internal_import.c b/source/blender/python/generic/bpy_internal_import.c
index 6b79945ccd8..1951e72567c 100644
--- a/source/blender/python/generic/bpy_internal_import.c
+++ b/source/blender/python/generic/bpy_internal_import.c
@@ -32,7 +32,9 @@
#include "MEM_guardedalloc.h"
#include "BKE_text.h" /* txt_to_buf */
#include "BKE_main.h"
+#include "BKE_global.h" /* grr, only for G.sce */
#include "BLI_listbase.h"
+#include "BLI_path_util.h"
#include <stddef.h>
static Main *bpy_import_main= NULL;
@@ -55,6 +57,12 @@ void bpy_import_main_set(struct Main *maggie)
bpy_import_main= maggie;
}
+/* returns a dummy filename for a textblock so we can tell what file a text block comes from */
+void bpy_text_filename_get(char *fn, Text *text)
+{
+ sprintf(fn, "%s/%s", text->id.lib ? text->id.lib->filepath : G.sce, text->id.name+2);
+}
+
PyObject *bpy_text_import( Text *text )
{
char *buf = NULL;
@@ -62,8 +70,11 @@ PyObject *bpy_text_import( Text *text )
int len;
if( !text->compiled ) {
+ char fn_dummy[256];
+ bpy_text_filename_get(fn_dummy, text);
+
buf = txt_to_buf( text );
- text->compiled = Py_CompileString( buf, text->id.name+2, Py_file_input );
+ text->compiled = Py_CompileString( buf, fn_dummy, Py_file_input );
MEM_freeN( buf );
if( PyErr_Occurred( ) ) {
@@ -119,8 +130,8 @@ PyObject *bpy_text_import_name( char *name, int *found )
PyObject *bpy_text_reimport( PyObject *module, int *found )
{
Text *text;
- const char *txtname;
const char *name;
+ char *filepath;
char *buf = NULL;
//XXX Main *maggie= bpy_import_main ? bpy_import_main:G.main;
Main *maggie= bpy_import_main;
@@ -133,14 +144,14 @@ PyObject *bpy_text_reimport( PyObject *module, int *found )
*found= 0;
/* get name, filename from the module itself */
+ if((name= PyModule_GetName(module)) == NULL)
+ return NULL;
- txtname = PyModule_GetFilename( module );
- name = PyModule_GetName( module );
- if( !txtname || !name)
+ if((filepath= (char *)PyModule_GetFilename(module)) == NULL)
return NULL;
/* look up the text object */
- text= BLI_findstring(&maggie->text, txtname, offsetof(ID, name) + 2);
+ text= BLI_findstring(&maggie->text, BLI_path_basename(filepath), offsetof(ID, name) + 2);
/* uh-oh.... didn't find it */
if( !text )
@@ -189,7 +200,7 @@ static PyObject *blender_import( PyObject * self, PyObject * args, PyObject * k
&name, &globals, &locals, &fromlist, &dummy_val) )
return NULL;
- /* import existing builtin modules or modules that have been imported alredy */
+ /* import existing builtin modules or modules that have been imported already */
newmodule = PyImport_ImportModuleEx( name, globals, locals, fromlist );
if(newmodule)
@@ -226,16 +237,11 @@ static PyObject *blender_import( PyObject * self, PyObject * args, PyObject * k
* our reload() module, to handle reloading in-memory scripts
*/
-static PyObject *blender_reload( PyObject * self, PyObject * args )
+static PyObject *blender_reload( PyObject * self, PyObject * module )
{
PyObject *exception, *err, *tb;
- PyObject *module = NULL;
PyObject *newmodule = NULL;
int found= 0;
-
- /* check for a module arg */
- if( !PyArg_ParseTuple( args, "O:bpy_reload_meth", &module ) )
- return NULL;
/* try reimporting from file */
newmodule = PyImport_ReloadModule( module );
@@ -269,7 +275,7 @@ static PyObject *blender_reload( PyObject * self, PyObject * args )
}
PyMethodDef bpy_import_meth[] = { {"bpy_import_meth", (PyCFunction)blender_import, METH_VARARGS | METH_KEYWORDS, "blenders import"} };
-PyMethodDef bpy_reload_meth[] = { {"bpy_reload_meth", (PyCFunction)blender_reload, METH_VARARGS, "blenders reload"} };
+PyMethodDef bpy_reload_meth[] = { {"bpy_reload_meth", (PyCFunction)blender_reload, METH_O, "blenders reload"} };
/* Clear user modules.
@@ -298,7 +304,7 @@ PyMethodDef bpy_reload_meth[] = { {"bpy_reload_meth", (PyCFunction)blender_reloa
void bpy_text_clear_modules(int clear_all)
{
- PyObject *modules= PySys_GetObject("modules");
+ PyObject *modules= PyImport_GetModuleDict();
char *fname;
char *file_extension;
@@ -344,3 +350,26 @@ void bpy_text_clear_modules(int clear_all)
Py_DECREF(list); /* removes all references from append */
}
#endif
+
+
+/*****************************************************************************
+* Description: This function creates a new Python dictionary object.
+* note: dict is owned by sys.modules["__main__"] module, reference is borrowed
+* note: important we use the dict from __main__, this is what python expects
+ for 'pickle' to work as well as strings like this...
+ >> foo = 10
+ >> print(__import__("__main__").foo)
+*****************************************************************************/
+PyObject *bpy_namespace_dict_new(const char *filename)
+{
+ PyInterpreterState *interp= PyThreadState_GET()->interp;
+ PyObject *mod_main= PyModule_New("__main__");
+ PyDict_SetItemString(interp->modules, "__main__", mod_main);
+ Py_DECREF(mod_main); /* sys.modules owns now */
+ PyModule_AddStringConstant(mod_main, "__name__", "__main__");
+ if(filename)
+ PyModule_AddStringConstant(mod_main, "__file__", filename); /* __file__ only for nice UI'ness */
+ PyModule_AddObject(mod_main, "__builtins__", interp->builtins);
+ Py_INCREF(interp->builtins); /* AddObject steals a reference */
+ return PyModule_GetDict(mod_main);
+}
diff --git a/source/blender/python/generic/bpy_internal_import.h b/source/blender/python/generic/bpy_internal_import.h
index 947e0dfc29d..83e05fd6ded 100644
--- a/source/blender/python/generic/bpy_internal_import.h
+++ b/source/blender/python/generic/bpy_internal_import.h
@@ -50,6 +50,9 @@ PyObject* bpy_text_import( struct Text *text );
PyObject* bpy_text_import_name( char *name, int *found );
PyObject* bpy_text_reimport( PyObject *module, int *found );
/* void bpy_text_clear_modules( int clear_all );*/ /* Clear user modules */
+
+void bpy_text_filename_get(char *fn, struct Text *text);
+
extern PyMethodDef bpy_import_meth[];
extern PyMethodDef bpy_reload_meth[];
@@ -57,5 +60,7 @@ extern PyMethodDef bpy_reload_meth[];
struct Main *bpy_import_main_get(void);
void bpy_import_main_set(struct Main *maggie);
+/* name namespace function for bpy & bge */
+PyObject *bpy_namespace_dict_new(const char *filename);
#endif /* EXPP_bpy_import_h */
diff --git a/source/blender/python/generic/Geometry.c b/source/blender/python/generic/geometry.c
index 158b07b1be5..0e98760314d 100644
--- a/source/blender/python/generic/Geometry.c
+++ b/source/blender/python/generic/geometry.c
@@ -27,7 +27,7 @@
* ***** END GPL LICENSE BLOCK *****
*/
-#include "Geometry.h"
+#include "geometry.h"
/* Used for PolyFill */
#include "BKE_displist.h"
@@ -44,7 +44,7 @@
/*-------------------------DOC STRINGS ---------------------------*/
-static char M_Geometry_doc[] = "The Blender Geometry module\n\n";
+static char M_Geometry_doc[] = "The Blender geometry module\n\n";
static char M_Geometry_Intersect_doc[] = "(v1, v2, v3, ray, orig, clip=1) - returns the intersection between a ray and a triangle, if possible, returns None otherwise";
static char M_Geometry_TriangleArea_doc[] = "(v1, v2, v3) - returns the area size of the 2D or 3D triangle defined";
static char M_Geometry_TriangleNormal_doc[] = "(v1, v2, v3) - returns the normal of the 3D triangle defined";
@@ -59,7 +59,7 @@ static char M_Geometry_BoxPack2D_doc[] = "";
static char M_Geometry_BezierInterp_doc[] = "";
//---------------------------------INTERSECTION FUNCTIONS--------------------
-//----------------------------------Mathutils.Intersect() -------------------
+//----------------------------------geometry.Intersect() -------------------
static PyObject *M_Geometry_Intersect( PyObject * self, PyObject * args )
{
VectorObject *ray, *ray_off, *vec1, *vec2, *vec3;
@@ -131,7 +131,7 @@ static PyObject *M_Geometry_Intersect( PyObject * self, PyObject * args )
return newVectorObject(pvec, 3, Py_NEW, NULL);
}
-//----------------------------------Mathutils.LineIntersect() -------------------
+//----------------------------------geometry.LineIntersect() -------------------
/* Line-Line intersection using algorithm from mathworld.wolfram.com */
static PyObject *M_Geometry_LineIntersect( PyObject * self, PyObject * args )
{
@@ -200,7 +200,7 @@ static PyObject *M_Geometry_LineIntersect( PyObject * self, PyObject * args )
//---------------------------------NORMALS FUNCTIONS--------------------
-//----------------------------------Mathutils.QuadNormal() -------------------
+//----------------------------------geometry.QuadNormal() -------------------
static PyObject *M_Geometry_QuadNormal( PyObject * self, PyObject * args )
{
VectorObject *vec1;
@@ -251,7 +251,7 @@ static PyObject *M_Geometry_QuadNormal( PyObject * self, PyObject * args )
return newVectorObject(n1, 3, Py_NEW, NULL);
}
-//----------------------------Mathutils.TriangleNormal() -------------------
+//----------------------------geometry.TriangleNormal() -------------------
static PyObject *M_Geometry_TriangleNormal( PyObject * self, PyObject * args )
{
VectorObject *vec1, *vec2, *vec3;
@@ -288,7 +288,7 @@ static PyObject *M_Geometry_TriangleNormal( PyObject * self, PyObject * args )
}
//--------------------------------- AREA FUNCTIONS--------------------
-//----------------------------------Mathutils.TriangleArea() -------------------
+//----------------------------------geometry.TriangleArea() -------------------
static PyObject *M_Geometry_TriangleArea( PyObject * self, PyObject * args )
{
VectorObject *vec1, *vec2, *vec3;
@@ -333,7 +333,7 @@ static PyObject *M_Geometry_TriangleArea( PyObject * self, PyObject * args )
}
}
-/*----------------------------------Geometry.PolyFill() -------------------*/
+/*----------------------------------geometry.PolyFill() -------------------*/
/* PolyFill function, uses Blenders scanfill to fill multiple poly lines */
static PyObject *M_Geometry_PolyFill( PyObject * self, PyObject * polyLineSeq )
{
@@ -363,7 +363,7 @@ static PyObject *M_Geometry_PolyFill( PyObject * self, PyObject * polyLineSeq )
if (!PySequence_Check(polyLine)) {
freedisplist(&dispbase);
Py_XDECREF(polyLine); /* may be null so use Py_XDECREF*/
- PyErr_SetString( PyExc_TypeError, "One or more of the polylines is not a sequence of Mathutils.Vector's" );
+ PyErr_SetString( PyExc_TypeError, "One or more of the polylines is not a sequence of mathutils.Vector's" );
return NULL;
}
@@ -373,7 +373,7 @@ static PyObject *M_Geometry_PolyFill( PyObject * self, PyObject * polyLineSeq )
if (EXPP_check_sequence_consistency( polyLine, &vector_Type ) != 1) {
freedisplist(&dispbase);
Py_DECREF(polyLine);
- PyErr_SetString( PyExc_TypeError, "A point in one of the polylines is not a Mathutils.Vector type" );
+ PyErr_SetString( PyExc_TypeError, "A point in one of the polylines is not a mathutils.Vector type" );
return NULL;
}
#endif
@@ -414,12 +414,12 @@ static PyObject *M_Geometry_PolyFill( PyObject * self, PyObject * polyLineSeq )
if(ls_error) {
freedisplist(&dispbase); /* possible some dl was allocated */
- PyErr_SetString( PyExc_TypeError, "A point in one of the polylines is not a Mathutils.Vector type" );
+ PyErr_SetString( PyExc_TypeError, "A point in one of the polylines is not a mathutils.Vector type" );
return NULL;
}
else if (totpoints) {
/* now make the list to return */
- filldisplist(&dispbase, &dispbase);
+ filldisplist(&dispbase, &dispbase, 0);
/* The faces are stored in a new DisplayList
thats added to the head of the listbase */
@@ -428,7 +428,7 @@ static PyObject *M_Geometry_PolyFill( PyObject * self, PyObject * polyLineSeq )
tri_list= PyList_New(dl->parts);
if( !tri_list ) {
freedisplist(&dispbase);
- PyErr_SetString( PyExc_RuntimeError, "Geometry.PolyFill failed to make a new list" );
+ PyErr_SetString( PyExc_RuntimeError, "geometry.PolyFill failed to make a new list" );
return NULL;
}
@@ -634,7 +634,7 @@ static int boxPack_FromPyObject(PyObject * value, boxPack **boxarray )
boxPack *box;
- /* Error checking must alredy be done */
+ /* Error checking must already be done */
if( !PyList_Check( value ) ) {
PyErr_SetString( PyExc_TypeError, "can only back a list of [x,y,x,w]" );
return -1;
@@ -819,7 +819,7 @@ struct PyMethodDef M_Geometry_methods[] = {
static struct PyModuleDef M_Geometry_module_def = {
PyModuleDef_HEAD_INIT,
- "Geometry", /* m_name */
+ "geometry", /* m_name */
M_Geometry_doc, /* m_doc */
0, /* m_size */
M_Geometry_methods, /* m_methods */
@@ -835,7 +835,7 @@ PyObject *Geometry_Init(void)
PyObject *submodule;
submodule = PyModule_Create(&M_Geometry_module_def);
- PyDict_SetItemString(PySys_GetObject("modules"), M_Geometry_module_def.m_name, submodule);
+ PyDict_SetItemString(PyImport_GetModuleDict(), M_Geometry_module_def.m_name, submodule);
return (submodule);
}
diff --git a/source/blender/python/generic/Geometry.h b/source/blender/python/generic/geometry.h
index 1e17ca6bf27..401efcc7888 100644
--- a/source/blender/python/generic/Geometry.h
+++ b/source/blender/python/generic/geometry.h
@@ -32,7 +32,7 @@
#define EXPP_Geometry_H
#include <Python.h>
-#include "Mathutils.h"
+#include "mathutils.h"
PyObject *Geometry_Init(void);
diff --git a/source/blender/python/generic/mathutils.c b/source/blender/python/generic/mathutils.c
new file mode 100644
index 00000000000..a643e6621b2
--- /dev/null
+++ b/source/blender/python/generic/mathutils.c
@@ -0,0 +1,273 @@
+/*
+ * $Id$
+ *
+ * ***** BEGIN GPL 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.
+ *
+ * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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): Joseph Gilbert, Campbell Barton
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/* Note: Changes to Mathutils since 2.4x
+ * use radians rather then degrees
+ * - Mathutils.Vector/Euler/Quaternion(), now only take single sequence arguments.
+ * - Mathutils.MidpointVecs --> vector.lerp(other, fac)
+ * - Mathutils.AngleBetweenVecs --> vector.angle(other)
+ * - Mathutils.ProjectVecs --> vector.project(other)
+ * - Mathutils.DifferenceQuats --> quat.difference(other)
+ * - Mathutils.Slerp --> quat.slerp(other, fac)
+ * - Mathutils.Rand: removed, use pythons random module
+ * - Mathutils.RotationMatrix(angle, size, axis_flag, axis) --> Mathutils.RotationMatrix(angle, size, axis); merge axis & axis_flag args
+ * - Matrix.scalePart --> Matrix.scale_part
+ * - Matrix.translationPart --> Matrix.translation_part
+ * - Matrix.rotationPart --> Matrix.rotation_part
+ * - toMatrix --> to_matrix
+ * - toEuler --> to_euler
+ * - toQuat --> to_quat
+ * - Vector.toTrackQuat --> Vector.to_track_quat
+ * - Quaternion * Quaternion --> cross product (not dot product)
+ *
+ * moved into class functions.
+ * - Mathutils.RotationMatrix -> mathutils.Matrix.Rotation
+ * - Mathutils.ScaleMatrix -> mathutils.Matrix.Scale
+ * - Mathutils.ShearMatrix -> mathutils.Matrix.Shear
+ * - Mathutils.TranslationMatrix -> mathutils.Matrix.Translation
+ * - Mathutils.OrthoProjectionMatrix -> mathutils.Matrix.OrthoProjection
+ *
+ * Moved to Geometry module: Intersect, TriangleArea, TriangleNormal, QuadNormal, LineIntersect
+ */
+
+#include "mathutils.h"
+
+#include "BLI_math.h"
+
+//-------------------------DOC STRINGS ---------------------------
+static char M_Mathutils_doc[] =
+"This module provides access to matrices, eulers, quaternions and vectors.";
+
+/* helper functionm returns length of the 'value', -1 on error */
+int mathutils_array_parse(float *array, int array_min, int array_max, PyObject *value, const char *error_prefix)
+{
+ PyObject *value_fast= NULL;
+
+ int i, size;
+
+ /* non list/tuple cases */
+ if(!(value_fast=PySequence_Fast(value, error_prefix))) {
+ /* PySequence_Fast sets the error */
+ return -1;
+ }
+
+ size= PySequence_Fast_GET_SIZE(value_fast);
+
+ if(size > array_max || size < array_min) {
+ if (array_max == array_min) PyErr_Format(PyExc_ValueError, "%.200s: sequence size is %d, expected %d", error_prefix, size, array_max);
+ else PyErr_Format(PyExc_ValueError, "%.200s: sequence size is %d, expected [%d - %d]", error_prefix, size, array_min, array_max);
+ Py_DECREF(value_fast);
+ return -1;
+ }
+
+ i= size;
+ do {
+ i--;
+ if(((array[i]= PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value_fast, i))) == -1.0) && PyErr_Occurred()) {
+ PyErr_Format(PyExc_ValueError, "%.200s: sequence index %d is not a float", error_prefix, i);
+ Py_DECREF(value_fast);
+ return -1;
+ }
+ } while(i);
+
+ Py_XDECREF(value_fast);
+ return size;
+}
+
+//----------------------------------MATRIX FUNCTIONS--------------------
+
+
+/* Utility functions */
+
+// LomontRRDCompare4, Ever Faster Float Comparisons by Randy Dillon
+#define SIGNMASK(i) (-(int)(((unsigned int)(i))>>31))
+
+int EXPP_FloatsAreEqual(float af, float bf, int maxDiff)
+{ // solid, fast routine across all platforms
+ // with constant time behavior
+ int ai = *(int *)(&af);
+ int bi = *(int *)(&bf);
+ int test = SIGNMASK(ai^bi);
+ int diff, v1, v2;
+
+ assert((0 == test) || (0xFFFFFFFF == test));
+ diff = (ai ^ (test & 0x7fffffff)) - bi;
+ v1 = maxDiff + diff;
+ v2 = maxDiff - diff;
+ return (v1|v2) >= 0;
+}
+
+/*---------------------- EXPP_VectorsAreEqual -------------------------
+ Builds on EXPP_FloatsAreEqual to test vectors */
+int EXPP_VectorsAreEqual(float *vecA, float *vecB, int size, int floatSteps)
+{
+ int x;
+ for (x=0; x< size; x++){
+ if (EXPP_FloatsAreEqual(vecA[x], vecB[x], floatSteps) == 0)
+ return 0;
+ }
+ return 1;
+}
+
+
+/* Mathutils Callbacks */
+
+/* for mathutils internal use only, eventually should re-alloc but to start with we only have a few users */
+Mathutils_Callback *mathutils_callbacks[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
+
+int Mathutils_RegisterCallback(Mathutils_Callback *cb)
+{
+ int i;
+
+ /* find the first free slot */
+ for(i= 0; mathutils_callbacks[i]; i++) {
+ if(mathutils_callbacks[i]==cb) /* already registered? */
+ return i;
+ }
+
+ mathutils_callbacks[i] = cb;
+ return i;
+}
+
+/* use macros to check for NULL */
+int _BaseMathObject_ReadCallback(BaseMathObject *self)
+{
+ Mathutils_Callback *cb= mathutils_callbacks[self->cb_type];
+ if(cb->get(self, self->cb_subtype))
+ return 1;
+
+ if(!PyErr_Occurred())
+ PyErr_Format(PyExc_SystemError, "%s user has become invalid", Py_TYPE(self)->tp_name);
+ return 0;
+}
+
+int _BaseMathObject_WriteCallback(BaseMathObject *self)
+{
+ Mathutils_Callback *cb= mathutils_callbacks[self->cb_type];
+ if(cb->set(self, self->cb_subtype))
+ return 1;
+
+ if(!PyErr_Occurred())
+ PyErr_Format(PyExc_SystemError, "%s user has become invalid", Py_TYPE(self)->tp_name);
+ return 0;
+}
+
+int _BaseMathObject_ReadIndexCallback(BaseMathObject *self, int index)
+{
+ Mathutils_Callback *cb= mathutils_callbacks[self->cb_type];
+ if(cb->get_index(self, self->cb_subtype, index))
+ return 1;
+
+ if(!PyErr_Occurred())
+ PyErr_Format(PyExc_SystemError, "%s user has become invalid", Py_TYPE(self)->tp_name);
+ return 0;
+}
+
+int _BaseMathObject_WriteIndexCallback(BaseMathObject *self, int index)
+{
+ Mathutils_Callback *cb= mathutils_callbacks[self->cb_type];
+ if(cb->set_index(self, self->cb_subtype, index))
+ return 1;
+
+ if(!PyErr_Occurred())
+ PyErr_Format(PyExc_SystemError, "%s user has become invalid", Py_TYPE(self)->tp_name);
+ return 0;
+}
+
+/* BaseMathObject generic functions for all mathutils types */
+char BaseMathObject_Owner_doc[] = "The item this is wrapping or None (readonly).";
+PyObject *BaseMathObject_getOwner( BaseMathObject * self, void *type )
+{
+ PyObject *ret= self->cb_user ? self->cb_user : Py_None;
+ Py_INCREF(ret);
+ return ret;
+}
+
+char BaseMathObject_Wrapped_doc[] = "True when this object wraps external data (readonly).\n\n:type: boolean";
+PyObject *BaseMathObject_getWrapped( BaseMathObject *self, void *type )
+{
+ return PyBool_FromLong((self->wrapped == Py_WRAP) ? 1:0);
+}
+
+void BaseMathObject_dealloc(BaseMathObject * self)
+{
+ /* only free non wrapped */
+ if(self->wrapped != Py_WRAP)
+ PyMem_Free(self->data);
+
+ Py_XDECREF(self->cb_user);
+ Py_TYPE(self)->tp_free(self); // PyObject_DEL(self); // breaks subtypes
+}
+
+/*----------------------------MODULE INIT-------------------------*/
+struct PyMethodDef M_Mathutils_methods[] = {
+ {NULL, NULL, 0, NULL}
+};
+
+static struct PyModuleDef M_Mathutils_module_def = {
+ PyModuleDef_HEAD_INIT,
+ "mathutils", /* m_name */
+ M_Mathutils_doc, /* m_doc */
+ 0, /* m_size */
+ M_Mathutils_methods, /* m_methods */
+ 0, /* m_reload */
+ 0, /* m_traverse */
+ 0, /* m_clear */
+ 0, /* m_free */
+};
+
+PyObject *Mathutils_Init(void)
+{
+ PyObject *submodule;
+
+ if( PyType_Ready( &vector_Type ) < 0 )
+ return NULL;
+ if( PyType_Ready( &matrix_Type ) < 0 )
+ return NULL;
+ if( PyType_Ready( &euler_Type ) < 0 )
+ return NULL;
+ if( PyType_Ready( &quaternion_Type ) < 0 )
+ return NULL;
+ if( PyType_Ready( &color_Type ) < 0 )
+ return NULL;
+
+ submodule = PyModule_Create(&M_Mathutils_module_def);
+ PyDict_SetItemString(PyImport_GetModuleDict(), M_Mathutils_module_def.m_name, submodule);
+
+ /* each type has its own new() function */
+ PyModule_AddObject( submodule, "Vector", (PyObject *)&vector_Type );
+ PyModule_AddObject( submodule, "Matrix", (PyObject *)&matrix_Type );
+ PyModule_AddObject( submodule, "Euler", (PyObject *)&euler_Type );
+ PyModule_AddObject( submodule, "Quaternion", (PyObject *)&quaternion_Type );
+ PyModule_AddObject( submodule, "Color", (PyObject *)&color_Type );
+
+ mathutils_matrix_vector_cb_index= Mathutils_RegisterCallback(&mathutils_matrix_vector_cb);
+
+ return (submodule);
+}
diff --git a/source/blender/python/generic/Mathutils.h b/source/blender/python/generic/mathutils.h
index 869ac4d70df..85fbe3225ba 100644
--- a/source/blender/python/generic/Mathutils.h
+++ b/source/blender/python/generic/mathutils.h
@@ -33,32 +33,35 @@
#include <Python.h>
-#include "vector.h"
-#include "matrix.h"
-#include "quat.h"
-#include "euler.h"
-
/* Can cast different mathutils types to this, use for generic funcs */
extern char BaseMathObject_Wrapped_doc[];
extern char BaseMathObject_Owner_doc[];
+#define BASE_MATH_MEMBERS(_data) \
+ PyObject_VAR_HEAD \
+ float *_data; /* array of data (alias), wrapped status depends on wrapped status */ \
+ PyObject *cb_user; /* if this vector references another object, otherwise NULL, *Note* this owns its reference */ \
+ unsigned char cb_type; /* which user funcs do we adhere to, RNA, GameObject, etc */ \
+ unsigned char cb_subtype; /* subtype: location, rotation... to avoid defining many new functions for every attribute of the same type */ \
+ unsigned char wrapped; /* wrapped data type? */ \
+
typedef struct {
- PyObject_VAR_HEAD
- float *data; /*array of data (alias), wrapped status depends on wrapped status */
- PyObject *cb_user; /* if this vector references another object, otherwise NULL, *Note* this owns its reference */
- unsigned char cb_type; /* which user funcs do we adhere to, RNA, GameObject, etc */
- unsigned char cb_subtype; /* subtype: location, rotation... to avoid defining many new functions for every attribute of the same type */
- unsigned char wrapped; /* wrapped data type? */
+ BASE_MATH_MEMBERS(data)
} BaseMathObject;
+#include "mathutils_vector.h"
+#include "mathutils_matrix.h"
+#include "mathutils_quat.h"
+#include "mathutils_euler.h"
+#include "mathutils_color.h"
+
PyObject *BaseMathObject_getOwner( BaseMathObject * self, void * );
PyObject *BaseMathObject_getWrapped( BaseMathObject *self, void * );
void BaseMathObject_dealloc(BaseMathObject * self);
PyObject *Mathutils_Init(void);
-
-PyObject *quat_rotation(PyObject *arg1, PyObject *arg2);
+PyObject *Noise_Init(void); /* lazy, saves having own header */
int EXPP_FloatsAreEqual(float A, float B, int floatSteps);
int EXPP_VectorsAreEqual(float *vecA, float *vecB, int size, int floatSteps);
@@ -69,33 +72,20 @@ int EXPP_VectorsAreEqual(float *vecA, float *vecB, int size, int floatSteps);
#define Py_NEW 1
#define Py_WRAP 2
-
-/* Mathutils is used by the BGE and Blender so have to define
- * some things here for luddite mac users of py2.3 */
-#ifndef Py_RETURN_NONE
-#define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None
-#endif
-#ifndef Py_RETURN_FALSE
-#define Py_RETURN_FALSE return Py_INCREF(Py_False), Py_False
-#endif
-#ifndef Py_RETURN_TRUE
-#define Py_RETURN_TRUE return Py_INCREF(Py_True), Py_True
-#endif
-
typedef struct Mathutils_Callback Mathutils_Callback;
-typedef int (*BaseMathCheckFunc)(PyObject *);
-typedef int (*BaseMathGetFunc)(PyObject *, int, float *);
-typedef int (*BaseMathSetFunc)(PyObject *, int, float *);
-typedef int (*BaseMathGetIndexFunc)(PyObject *, int, float *, int);
-typedef int (*BaseMathSetIndexFunc)(PyObject *, int, float *, int);
+typedef int (*BaseMathCheckFunc)(BaseMathObject *); /* checks the user is still valid */
+typedef int (*BaseMathGetFunc)(BaseMathObject *, int); /* gets the vector from the user */
+typedef int (*BaseMathSetFunc)(BaseMathObject *, int); /* sets the users vector values once the vector is modified */
+typedef int (*BaseMathGetIndexFunc)(BaseMathObject *, int, int); /* same as above but only for an index */
+typedef int (*BaseMathSetIndexFunc)(BaseMathObject *, int, int); /* same as above but only for an index */
struct Mathutils_Callback {
- int (*check)(PyObject *user); /* checks the user is still valid */
- int (*get)(PyObject *user, int subtype, float *from); /* gets the vector from the user */
- int (*set)(PyObject *user, int subtype, float *to); /* sets the users vector values once the vector is modified */
- int (*get_index)(PyObject *user, int subtype, float *from,int index); /* same as above but only for an index */
- int (*set_index)(PyObject *user, int subtype, float *to, int index); /* same as above but only for an index */
+ BaseMathCheckFunc check;
+ BaseMathGetFunc get;
+ BaseMathSetFunc set;
+ BaseMathGetIndexFunc get_index;
+ BaseMathSetIndexFunc set_index;
};
int Mathutils_RegisterCallback(Mathutils_Callback *cb);
@@ -111,4 +101,7 @@ int _BaseMathObject_WriteIndexCallback(BaseMathObject *self, int index);
#define BaseMath_ReadIndexCallback(_self, _index) (((_self)->cb_user ? _BaseMathObject_ReadIndexCallback((BaseMathObject *)_self, _index):1))
#define BaseMath_WriteIndexCallback(_self, _index) (((_self)->cb_user ? _BaseMathObject_WriteIndexCallback((BaseMathObject *)_self, _index):1))
+/* utility func */
+int mathutils_array_parse(float *array, int array_min, int array_max, PyObject *value, const char *error_prefix);
+
#endif /* EXPP_Mathutils_H */
diff --git a/source/blender/python/generic/mathutils_color.c b/source/blender/python/generic/mathutils_color.c
new file mode 100644
index 00000000000..57d2838238c
--- /dev/null
+++ b/source/blender/python/generic/mathutils_color.c
@@ -0,0 +1,560 @@
+/*
+ * $Id$
+ *
+ * ***** BEGIN GPL 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.
+ *
+ * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor(s): Campbell Barton
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "mathutils.h"
+
+#include "BLI_math.h"
+#include "BKE_utildefines.h"
+
+#define COLOR_SIZE 3
+
+//----------------------------------mathutils.Color() -------------------
+//makes a new color for you to play with
+static PyObject *Color_new(PyTypeObject * type, PyObject * args, PyObject * kwargs)
+{
+ float col[3]= {0.0f, 0.0f, 0.0f};
+
+ switch(PyTuple_GET_SIZE(args)) {
+ case 0:
+ break;
+ case 1:
+ if((mathutils_array_parse(col, COLOR_SIZE, COLOR_SIZE, PyTuple_GET_ITEM(args, 0), "mathutils.Color()")) == -1)
+ return NULL;
+ break;
+ default:
+ PyErr_SetString(PyExc_TypeError, "mathutils.Color(): more then a single arg given");
+ return NULL;
+ }
+ return newColorObject(col, Py_NEW, type);
+}
+
+//-----------------------------METHODS----------------------------
+
+/* note: BaseMath_ReadCallback must be called beforehand */
+static PyObject *Color_ToTupleExt(ColorObject *self, int ndigits)
+{
+ PyObject *ret;
+ int i;
+
+ ret= PyTuple_New(COLOR_SIZE);
+
+ if(ndigits >= 0) {
+ for(i= 0; i < COLOR_SIZE; i++) {
+ PyTuple_SET_ITEM(ret, i, PyFloat_FromDouble(double_round((double)self->col[i], ndigits)));
+ }
+ }
+ else {
+ for(i= 0; i < COLOR_SIZE; i++) {
+ PyTuple_SET_ITEM(ret, i, PyFloat_FromDouble(self->col[i]));
+ }
+ }
+
+ return ret;
+}
+
+static char Color_copy_doc[] =
+".. function:: copy()\n"
+"\n"
+" Returns a copy of this color.\n"
+"\n"
+" :return: A copy of the color.\n"
+" :rtype: :class:`Color`\n"
+"\n"
+" .. note:: use this to get a copy of a wrapped color with no reference to the original data.\n";
+
+static PyObject *Color_copy(ColorObject * self, PyObject *args)
+{
+ if(!BaseMath_ReadCallback(self))
+ return NULL;
+
+ return newColorObject(self->col, Py_NEW, Py_TYPE(self));
+}
+
+//----------------------------print object (internal)--------------
+//print the object to screen
+
+static PyObject *Color_repr(ColorObject * self)
+{
+ PyObject *ret, *tuple;
+
+ if(!BaseMath_ReadCallback(self))
+ return NULL;
+
+ tuple= Color_ToTupleExt(self, -1);
+
+ ret= PyUnicode_FromFormat("Color(%R)", tuple);
+
+ Py_DECREF(tuple);
+ return ret;
+}
+
+//------------------------tp_richcmpr
+//returns -1 execption, 0 false, 1 true
+static PyObject* Color_richcmpr(PyObject *objectA, PyObject *objectB, int comparison_type)
+{
+ ColorObject *colA = NULL, *colB = NULL;
+ int result = 0;
+
+ if(ColorObject_Check(objectA)) {
+ colA = (ColorObject*)objectA;
+ if(!BaseMath_ReadCallback(colA))
+ return NULL;
+ }
+ if(ColorObject_Check(objectB)) {
+ colB = (ColorObject*)objectB;
+ if(!BaseMath_ReadCallback(colB))
+ return NULL;
+ }
+
+ if (!colA || !colB){
+ if (comparison_type == Py_NE){
+ Py_RETURN_TRUE;
+ }else{
+ Py_RETURN_FALSE;
+ }
+ }
+ colA = (ColorObject*)objectA;
+ colB = (ColorObject*)objectB;
+
+ switch (comparison_type){
+ case Py_EQ:
+ result = EXPP_VectorsAreEqual(colA->col, colB->col, COLOR_SIZE, 1);
+ break;
+ case Py_NE:
+ result = !EXPP_VectorsAreEqual(colA->col, colB->col, COLOR_SIZE, 1);
+ break;
+ default:
+ printf("The result of the comparison could not be evaluated");
+ break;
+ }
+ if (result == 1){
+ Py_RETURN_TRUE;
+ }else{
+ Py_RETURN_FALSE;
+ }
+}
+
+//---------------------SEQUENCE PROTOCOLS------------------------
+//----------------------------len(object)------------------------
+//sequence length
+static int Color_len(ColorObject * self)
+{
+ return COLOR_SIZE;
+}
+//----------------------------object[]---------------------------
+//sequence accessor (get)
+static PyObject *Color_item(ColorObject * self, int i)
+{
+ if(i<0) i= COLOR_SIZE-i;
+
+ if(i < 0 || i >= COLOR_SIZE) {
+ PyErr_SetString(PyExc_IndexError, "color[attribute]: array index out of range");
+ return NULL;
+ }
+
+ if(!BaseMath_ReadIndexCallback(self, i))
+ return NULL;
+
+ return PyFloat_FromDouble(self->col[i]);
+
+}
+//----------------------------object[]-------------------------
+//sequence accessor (set)
+static int Color_ass_item(ColorObject * self, int i, PyObject * value)
+{
+ float f = PyFloat_AsDouble(value);
+
+ if(f == -1 && PyErr_Occurred()) { // parsed item not a number
+ PyErr_SetString(PyExc_TypeError, "color[attribute] = x: argument not a number");
+ return -1;
+ }
+
+ if(i<0) i= COLOR_SIZE-i;
+
+ if(i < 0 || i >= COLOR_SIZE){
+ PyErr_SetString(PyExc_IndexError, "color[attribute] = x: array assignment index out of range\n");
+ return -1;
+ }
+
+ self->col[i] = f;
+
+ if(!BaseMath_WriteIndexCallback(self, i))
+ return -1;
+
+ return 0;
+}
+//----------------------------object[z:y]------------------------
+//sequence slice (get)
+static PyObject *Color_slice(ColorObject * self, int begin, int end)
+{
+ PyObject *list = NULL;
+ int count;
+
+ if(!BaseMath_ReadCallback(self))
+ return NULL;
+
+ CLAMP(begin, 0, COLOR_SIZE);
+ if (end<0) end= (COLOR_SIZE + 1) + end;
+ CLAMP(end, 0, COLOR_SIZE);
+ begin = MIN2(begin,end);
+
+ list = PyList_New(end - begin);
+ for(count = begin; count < end; count++) {
+ PyList_SetItem(list, count - begin,
+ PyFloat_FromDouble(self->col[count]));
+ }
+
+ return list;
+}
+//----------------------------object[z:y]------------------------
+//sequence slice (set)
+static int Color_ass_slice(ColorObject * self, int begin, int end, PyObject * seq)
+{
+ int i, size;
+ float col[COLOR_SIZE];
+
+ if(!BaseMath_ReadCallback(self))
+ return -1;
+
+ CLAMP(begin, 0, COLOR_SIZE);
+ if (end<0) end= (COLOR_SIZE + 1) + end;
+ CLAMP(end, 0, COLOR_SIZE);
+ begin = MIN2(begin,end);
+
+ if((size=mathutils_array_parse(col, 0, COLOR_SIZE, seq, "mathutils.Color[begin:end] = []")) == -1)
+ return -1;
+
+ if(size != (end - begin)){
+ PyErr_SetString(PyExc_TypeError, "color[begin:end] = []: size mismatch in slice assignment");
+ return -1;
+ }
+
+ for(i= 0; i < COLOR_SIZE; i++)
+ self->col[begin + i] = col[i];
+
+ BaseMath_WriteCallback(self);
+ return 0;
+}
+
+static PyObject *Color_subscript(ColorObject *self, PyObject *item)
+{
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i;
+ i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred())
+ return NULL;
+ if (i < 0)
+ i += COLOR_SIZE;
+ return Color_item(self, i);
+ } else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelength;
+
+ if (PySlice_GetIndicesEx((PySliceObject*)item, COLOR_SIZE, &start, &stop, &step, &slicelength) < 0)
+ return NULL;
+
+ if (slicelength <= 0) {
+ return PyList_New(0);
+ }
+ else if (step == 1) {
+ return Color_slice(self, start, stop);
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError, "slice steps not supported with color");
+ return NULL;
+ }
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "color indices must be integers, not %.200s",
+ item->ob_type->tp_name);
+ return NULL;
+ }
+}
+
+static int Color_ass_subscript(ColorObject *self, PyObject *item, PyObject *value)
+{
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred())
+ return -1;
+ if (i < 0)
+ i += COLOR_SIZE;
+ return Color_ass_item(self, i, value);
+ }
+ else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelength;
+
+ if (PySlice_GetIndicesEx((PySliceObject*)item, COLOR_SIZE, &start, &stop, &step, &slicelength) < 0)
+ return -1;
+
+ if (step == 1)
+ return Color_ass_slice(self, start, stop, value);
+ else {
+ PyErr_SetString(PyExc_TypeError, "slice steps not supported with color");
+ return -1;
+ }
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "color indices must be integers, not %.200s",
+ item->ob_type->tp_name);
+ return -1;
+ }
+}
+
+//-----------------PROTCOL DECLARATIONS--------------------------
+static PySequenceMethods Color_SeqMethods = {
+ (lenfunc) Color_len, /* sq_length */
+ (binaryfunc) NULL, /* sq_concat */
+ (ssizeargfunc) NULL, /* sq_repeat */
+ (ssizeargfunc) Color_item, /* sq_item */
+ (ssizessizeargfunc) NULL, /* sq_slice, deprecated */
+ (ssizeobjargproc) Color_ass_item, /* sq_ass_item */
+ (ssizessizeobjargproc) NULL, /* sq_ass_slice, deprecated */
+ (objobjproc) NULL, /* sq_contains */
+ (binaryfunc) NULL, /* sq_inplace_concat */
+ (ssizeargfunc) NULL, /* sq_inplace_repeat */
+};
+
+static PyMappingMethods Color_AsMapping = {
+ (lenfunc)Color_len,
+ (binaryfunc)Color_subscript,
+ (objobjargproc)Color_ass_subscript
+};
+
+/* color channel, vector.r/g/b */
+static PyObject *Color_getChannel( ColorObject * self, void *type )
+{
+ return Color_item(self, GET_INT_FROM_POINTER(type));
+}
+
+static int Color_setChannel(ColorObject * self, PyObject * value, void * type)
+{
+ return Color_ass_item(self, GET_INT_FROM_POINTER(type), value);
+}
+
+/* color channel (HSV), color.h/s/v */
+static PyObject *Color_getChannelHSV( ColorObject * self, void *type )
+{
+ float hsv[3];
+ int i= GET_INT_FROM_POINTER(type);
+
+ if(!BaseMath_ReadCallback(self))
+ return NULL;
+
+ rgb_to_hsv(self->col[0], self->col[1], self->col[2], &(hsv[0]), &(hsv[1]), &(hsv[2]));
+
+ return PyFloat_FromDouble(hsv[i]);
+}
+
+static int Color_setChannelHSV(ColorObject * self, PyObject * value, void * type)
+{
+ float hsv[3];
+ int i= GET_INT_FROM_POINTER(type);
+ float f = PyFloat_AsDouble(value);
+
+ if(f == -1 && PyErr_Occurred()) {
+ PyErr_SetString(PyExc_TypeError, "color.h/s/v = value: argument not a number");
+ return -1;
+ }
+
+ if(!BaseMath_ReadCallback(self))
+ return -1;
+
+ rgb_to_hsv(self->col[0], self->col[1], self->col[2], &(hsv[0]), &(hsv[1]), &(hsv[2]));
+ CLAMP(f, 0.0f, 1.0f);
+ hsv[i] = f;
+ hsv_to_rgb(hsv[0], hsv[1], hsv[2], &(self->col[0]), &(self->col[1]), &(self->col[2]));
+
+ if(!BaseMath_WriteCallback(self))
+ return -1;
+
+ return 0;
+}
+
+/* color channel (HSV), color.h/s/v */
+static PyObject *Color_getHSV(ColorObject * self, void *type)
+{
+ float hsv[3];
+ PyObject *ret;
+
+ if(!BaseMath_ReadCallback(self))
+ return NULL;
+
+ rgb_to_hsv(self->col[0], self->col[1], self->col[2], &(hsv[0]), &(hsv[1]), &(hsv[2]));
+
+ ret= PyTuple_New(3);
+ PyTuple_SET_ITEM(ret, 0, PyFloat_FromDouble(hsv[0]));
+ PyTuple_SET_ITEM(ret, 1, PyFloat_FromDouble(hsv[1]));
+ PyTuple_SET_ITEM(ret, 2, PyFloat_FromDouble(hsv[2]));
+ return ret;
+}
+
+static int Color_setHSV(ColorObject * self, PyObject * value, void * type)
+{
+ float hsv[3];
+
+ if(mathutils_array_parse(hsv, 3, 3, value, "mathutils.Color.hsv = value") == -1)
+ return -1;
+
+ CLAMP(hsv[0], 0.0f, 1.0f);
+ CLAMP(hsv[1], 0.0f, 1.0f);
+ CLAMP(hsv[2], 0.0f, 1.0f);
+
+ hsv_to_rgb(hsv[0], hsv[1], hsv[2], &(self->col[0]), &(self->col[1]), &(self->col[2]));
+
+ if(!BaseMath_WriteCallback(self))
+ return -1;
+
+ return 0;
+}
+
+/*****************************************************************************/
+/* Python attributes get/set structure: */
+/*****************************************************************************/
+static PyGetSetDef Color_getseters[] = {
+ {"r", (getter)Color_getChannel, (setter)Color_setChannel, "Red color channel.\n\n:type: float", (void *)0},
+ {"g", (getter)Color_getChannel, (setter)Color_setChannel, "Green color channel.\n\n:type: float", (void *)1},
+ {"b", (getter)Color_getChannel, (setter)Color_setChannel, "Blue color channel.\n\n:type: float", (void *)2},
+
+ {"h", (getter)Color_getChannelHSV, (setter)Color_setChannelHSV, "HSV Hue component in [0, 1].\n\n:type: float", (void *)0},
+ {"s", (getter)Color_getChannelHSV, (setter)Color_setChannelHSV, "HSV Saturation component in [0, 1].\n\n:type: float", (void *)1},
+ {"v", (getter)Color_getChannelHSV, (setter)Color_setChannelHSV, "HSV Value component in [0, 1].\n\n:type: float", (void *)2},
+
+ {"hsv", (getter)Color_getHSV, (setter)Color_setHSV, "HSV Values in [0, 1].\n\n:type: float triplet", (void *)0},
+
+ {"is_wrapped", (getter)BaseMathObject_getWrapped, (setter)NULL, BaseMathObject_Wrapped_doc, NULL},
+ {"owner", (getter)BaseMathObject_getOwner, (setter)NULL, BaseMathObject_Owner_doc, NULL},
+ {NULL,NULL,NULL,NULL,NULL} /* Sentinel */
+};
+
+
+//-----------------------METHOD DEFINITIONS ----------------------
+static struct PyMethodDef Color_methods[] = {
+ {"__copy__", (PyCFunction) Color_copy, METH_VARARGS, Color_copy_doc},
+ {"copy", (PyCFunction) Color_copy, METH_VARARGS, Color_copy_doc},
+ {NULL, NULL, 0, NULL}
+};
+
+//------------------PY_OBECT DEFINITION--------------------------
+static char color_doc[] =
+"This object gives access to Colors in Blender.";
+
+PyTypeObject color_Type = {
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "color", //tp_name
+ sizeof(ColorObject), //tp_basicsize
+ 0, //tp_itemsize
+ (destructor)BaseMathObject_dealloc, //tp_dealloc
+ 0, //tp_print
+ 0, //tp_getattr
+ 0, //tp_setattr
+ 0, //tp_compare
+ (reprfunc) Color_repr, //tp_repr
+ 0, //tp_as_number
+ &Color_SeqMethods, //tp_as_sequence
+ &Color_AsMapping, //tp_as_mapping
+ 0, //tp_hash
+ 0, //tp_call
+ 0, //tp_str
+ 0, //tp_getattro
+ 0, //tp_setattro
+ 0, //tp_as_buffer
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, //tp_flags
+ color_doc, //tp_doc
+ 0, //tp_traverse
+ 0, //tp_clear
+ (richcmpfunc)Color_richcmpr, //tp_richcompare
+ 0, //tp_weaklistoffset
+ 0, //tp_iter
+ 0, //tp_iternext
+ Color_methods, //tp_methods
+ 0, //tp_members
+ Color_getseters, //tp_getset
+ 0, //tp_base
+ 0, //tp_dict
+ 0, //tp_descr_get
+ 0, //tp_descr_set
+ 0, //tp_dictoffset
+ 0, //tp_init
+ 0, //tp_alloc
+ Color_new, //tp_new
+ 0, //tp_free
+ 0, //tp_is_gc
+ 0, //tp_bases
+ 0, //tp_mro
+ 0, //tp_cache
+ 0, //tp_subclasses
+ 0, //tp_weaklist
+ 0 //tp_del
+};
+//------------------------newColorObject (internal)-------------
+//creates a new color object
+/*pass Py_WRAP - if vector is a WRAPPER for data allocated by BLENDER
+ (i.e. it was allocated elsewhere by MEM_mallocN())
+ pass Py_NEW - if vector is not a WRAPPER and managed by PYTHON
+ (i.e. it must be created here with PyMEM_malloc())*/
+PyObject *newColorObject(float *col, int type, PyTypeObject *base_type)
+{
+ ColorObject *self;
+
+ if(base_type) self = (ColorObject *)base_type->tp_alloc(base_type, 0);
+ else self = PyObject_NEW(ColorObject, &color_Type);
+
+ /* init callbacks as NULL */
+ self->cb_user= NULL;
+ self->cb_type= self->cb_subtype= 0;
+
+ if(type == Py_WRAP){
+ self->col = col;
+ self->wrapped = Py_WRAP;
+ }
+ else if (type == Py_NEW){
+ self->col = PyMem_Malloc(COLOR_SIZE * sizeof(float));
+ if(col)
+ copy_v3_v3(self->col, col);
+ else
+ zero_v3(self->col);
+
+ self->wrapped = Py_NEW;
+ }
+ else {
+ return NULL;
+ }
+
+ return (PyObject *)self;
+}
+
+PyObject *newColorObject_cb(PyObject *cb_user, int cb_type, int cb_subtype)
+{
+ ColorObject *self= (ColorObject *)newColorObject(NULL, Py_NEW, NULL);
+ if(self) {
+ Py_INCREF(cb_user);
+ self->cb_user= cb_user;
+ self->cb_type= (unsigned char)cb_type;
+ self->cb_subtype= (unsigned char)cb_subtype;
+ }
+
+ return (PyObject *)self;
+}
diff --git a/source/blender/python/generic/mathutils_color.h b/source/blender/python/generic/mathutils_color.h
new file mode 100644
index 00000000000..02b27d86817
--- /dev/null
+++ b/source/blender/python/generic/mathutils_color.h
@@ -0,0 +1,52 @@
+/*
+ * $Id$
+ *
+ * ***** BEGIN GPL 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.
+ *
+ * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): Joseph Gilbert
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ *
+ */
+
+#ifndef EXPP_color_h
+#define EXPP_color_h
+
+#include <Python.h>
+
+extern PyTypeObject color_Type;
+#define ColorObject_Check(_v) PyObject_TypeCheck((_v), &color_Type)
+
+typedef struct {
+ BASE_MATH_MEMBERS(col)
+} ColorObject;
+
+/*struct data contains a pointer to the actual data that the
+object uses. It can use either PyMem allocated data (which will
+be stored in py_data) or be a wrapper for data allocated through
+blender (stored in blend_data). This is an either/or struct not both*/
+
+//prototypes
+PyObject *newColorObject( float *col, int type, PyTypeObject *base_type);
+PyObject *newColorObject_cb(PyObject *cb_user, int cb_type, int cb_subtype);
+
+#endif /* EXPP_color_h */
diff --git a/source/blender/python/generic/euler.c b/source/blender/python/generic/mathutils_euler.c
index 892e42657b7..b36eb7803f1 100644
--- a/source/blender/python/generic/euler.c
+++ b/source/blender/python/generic/mathutils_euler.c
@@ -26,7 +26,7 @@
* ***** END GPL LICENSE BLOCK *****
*/
-#include "Mathutils.h"
+#include "mathutils.h"
#include "BLI_math.h"
#include "BKE_utildefines.h"
@@ -35,52 +35,32 @@
#include "BLO_sys_types.h"
#endif
-//----------------------------------Mathutils.Euler() -------------------
+#define EULER_SIZE 3
+
+//----------------------------------mathutils.Euler() -------------------
//makes a new euler for you to play with
static PyObject *Euler_new(PyTypeObject * type, PyObject * args, PyObject * kwargs)
{
- PyObject *listObject = NULL;
- int size, i;
- float eul[3];
- PyObject *e;
- short order= 0; // TODO, add order option
-
- size = PyTuple_GET_SIZE(args);
- if (size == 1) {
- listObject = PyTuple_GET_ITEM(args, 0);
- if (PySequence_Check(listObject)) {
- size = PySequence_Length(listObject);
- } else { // Single argument was not a sequence
- PyErr_SetString(PyExc_TypeError, "Mathutils.Euler(): 3d numeric sequence expected\n");
- return NULL;
- }
- } else if (size == 0) {
- //returns a new empty 3d euler
- return newEulerObject(NULL, order, Py_NEW, NULL);
- } else {
- listObject = args;
- }
+ PyObject *seq= NULL;
+ char *order_str= NULL;
- if (size != 3) { // Invalid euler size
- PyErr_SetString(PyExc_AttributeError, "Mathutils.Euler(): 3d numeric sequence expected\n");
+ float eul[EULER_SIZE]= {0.0f, 0.0f, 0.0f};
+ short order= EULER_ORDER_XYZ;
+
+ if(!PyArg_ParseTuple(args, "|Os:mathutils.Euler", &seq, &order_str))
return NULL;
- }
- for (i=0; i<size; i++) {
- e = PySequence_GetItem(listObject, i);
- if (e == NULL) { // Failed to read sequence
- Py_DECREF(listObject);
- PyErr_SetString(PyExc_RuntimeError, "Mathutils.Euler(): 3d numeric sequence expected\n");
+ switch(PyTuple_GET_SIZE(args)) {
+ case 0:
+ break;
+ case 2:
+ if((order=euler_order_from_string(order_str, "mathutils.Euler()")) == -1)
return NULL;
- }
-
- eul[i]= (float)PyFloat_AsDouble(e);
- Py_DECREF(e);
-
- if(eul[i]==-1 && PyErr_Occurred()) { // parsed item is not a number
- PyErr_SetString(PyExc_TypeError, "Mathutils.Euler(): 3d numeric sequence expected\n");
+ /* intentionally pass through */
+ case 1:
+ if (mathutils_array_parse(eul, EULER_SIZE, EULER_SIZE, seq, "mathutils.Euler()") == -1)
return NULL;
- }
+ break;
}
return newEulerObject(eul, order, Py_NEW, NULL);
}
@@ -89,12 +69,12 @@ short euler_order_from_string(const char *str, const char *error_prefix)
{
if((str[0] && str[1] && str[2] && str[3]=='\0')) {
switch(*((int32_t *)str)) {
- case 'X'|'Y'<<8|'Z'<<16: return 0;
- case 'X'|'Z'<<8|'Y'<<16: return 1;
- case 'Y'|'X'<<8|'Z'<<16: return 2;
- case 'Y'|'Z'<<8|'X'<<16: return 3;
- case 'Z'|'X'<<8|'Y'<<16: return 4;
- case 'Z'|'Y'<<8|'X'<<16: return 5;
+ case 'X'|'Y'<<8|'Z'<<16: return EULER_ORDER_XYZ;
+ case 'X'|'Z'<<8|'Y'<<16: return EULER_ORDER_XZY;
+ case 'Y'|'X'<<8|'Z'<<16: return EULER_ORDER_YXZ;
+ case 'Y'|'Z'<<8|'X'<<16: return EULER_ORDER_YZX;
+ case 'Z'|'X'<<8|'Y'<<16: return EULER_ORDER_ZXY;
+ case 'Z'|'Y'<<8|'X'<<16: return EULER_ORDER_ZYX;
}
}
@@ -102,8 +82,29 @@ short euler_order_from_string(const char *str, const char *error_prefix)
return -1;
}
+/* note: BaseMath_ReadCallback must be called beforehand */
+static PyObject *Euler_ToTupleExt(EulerObject *self, int ndigits)
+{
+ PyObject *ret;
+ int i;
+
+ ret= PyTuple_New(EULER_SIZE);
+
+ if(ndigits >= 0) {
+ for(i= 0; i < EULER_SIZE; i++) {
+ PyTuple_SET_ITEM(ret, i, PyFloat_FromDouble(double_round((double)self->eul[i], ndigits)));
+ }
+ }
+ else {
+ for(i= 0; i < EULER_SIZE; i++) {
+ PyTuple_SET_ITEM(ret, i, PyFloat_FromDouble(self->eul[i]));
+ }
+ }
+
+ return ret;
+}
+
//-----------------------------METHODS----------------------------
-//----------------------------Euler.toQuat()----------------------
//return a quaternion representation of the euler
static char Euler_ToQuat_doc[] =
@@ -121,12 +122,12 @@ static PyObject *Euler_ToQuat(EulerObject * self)
if(!BaseMath_ReadCallback(self))
return NULL;
- if(self->order==0) eul_to_quat(quat, self->eul);
- else eulO_to_quat(quat, self->eul, self->order);
+ if(self->order==EULER_ORDER_XYZ) eul_to_quat(quat, self->eul);
+ else eulO_to_quat(quat, self->eul, self->order);
return newQuaternionObject(quat, Py_NEW, NULL);
}
-//----------------------------Euler.toMatrix()---------------------
+
//return a matrix representation of the euler
static char Euler_ToMatrix_doc[] =
".. method:: to_matrix()\n"
@@ -143,12 +144,12 @@ static PyObject *Euler_ToMatrix(EulerObject * self)
if(!BaseMath_ReadCallback(self))
return NULL;
- if(self->order==0) eul_to_mat3((float (*)[3])mat, self->eul);
- else eulO_to_mat3((float (*)[3])mat, self->eul, self->order);
+ if(self->order==EULER_ORDER_XYZ) eul_to_mat3((float (*)[3])mat, self->eul);
+ else eulO_to_mat3((float (*)[3])mat, self->eul, self->order);
return newMatrixObject(mat, 3, 3 , Py_NEW, NULL);
}
-//----------------------------Euler.unique()-----------------------
+
//sets the x,y,z values to a unique euler rotation
// TODO, check if this works with rotation order!!!
static char Euler_Unique_doc[] =
@@ -207,7 +208,7 @@ static PyObject *Euler_Unique(EulerObject * self)
Py_INCREF(self);
return (PyObject *)self;
}
-//----------------------------Euler.zero()-------------------------
+
//sets the euler to 0,0,0
static char Euler_Zero_doc[] =
".. method:: zero()\n"
@@ -227,28 +228,38 @@ static PyObject *Euler_Zero(EulerObject * self)
Py_INCREF(self);
return (PyObject *)self;
}
-//----------------------------Euler.rotate()-----------------------
-//rotates a euler a certain amount and returns the result
-//should return a unique euler rotation (i.e. no 720 degree pitches :)
+
+static char Euler_Rotate_doc[] =
+".. method:: rotate(angle, axis)\n"
+"\n"
+" Rotates the euler a certain amount and returning a unique euler rotation (no 720 degree pitches).\n"
+"\n"
+" :arg angle: angle in radians.\n"
+" :type angle: float\n"
+" :arg axis: single character in ['X, 'Y', 'Z'].\n"
+" :type axis: string\n"
+" :return: an instance of itself\n"
+" :rtype: :class:`Euler`";
+
static PyObject *Euler_Rotate(EulerObject * self, PyObject *args)
{
float angle = 0.0f;
char *axis;
- if(!PyArg_ParseTuple(args, "fs", &angle, &axis)){
- PyErr_SetString(PyExc_TypeError, "euler.rotate():expected angle (float) and axis (x,y,z)");
+ if(!PyArg_ParseTuple(args, "fs:rotate", &angle, &axis)){
+ PyErr_SetString(PyExc_TypeError, "euler.rotate(): expected angle (float) and axis (x,y,z)");
return NULL;
}
- if(ELEM3(*axis, 'x', 'y', 'z') && axis[1]=='\0'){
- PyErr_SetString(PyExc_TypeError, "euler.rotate(): expected axis to be 'x', 'y' or 'z'");
+ if(ELEM3(*axis, 'X', 'Y', 'Z') && axis[1]=='\0'){
+ PyErr_SetString(PyExc_TypeError, "euler.rotate(): expected axis to be 'X', 'Y' or 'Z'");
return NULL;
}
if(!BaseMath_ReadCallback(self))
return NULL;
- if(self->order == 0) rotate_eul(self->eul, *axis, angle);
- else rotate_eulO(self->eul, self->order, *axis, angle);
+ if(self->order == EULER_ORDER_XYZ) rotate_eul(self->eul, *axis, angle);
+ else rotate_eulO(self->eul, self->order, *axis, angle);
BaseMath_WriteCallback(self);
Py_INCREF(self);
@@ -312,16 +323,22 @@ static PyObject *Euler_copy(EulerObject * self, PyObject *args)
//----------------------------print object (internal)--------------
//print the object to screen
+
static PyObject *Euler_repr(EulerObject * self)
{
- char str[64];
-
+ PyObject *ret, *tuple;
+
if(!BaseMath_ReadCallback(self))
return NULL;
- sprintf(str, "[%.6f, %.6f, %.6f](euler)", self->eul[0], self->eul[1], self->eul[2]);
- return PyUnicode_FromString(str);
+ tuple= Euler_ToTupleExt(self, -1);
+
+ ret= PyUnicode_FromFormat("Euler(%R)", tuple);
+
+ Py_DECREF(tuple);
+ return ret;
}
+
//------------------------tp_richcmpr
//returns -1 execption, 0 false, 1 true
static PyObject* Euler_richcmpr(PyObject *objectA, PyObject *objectB, int comparison_type)
@@ -352,10 +369,10 @@ static PyObject* Euler_richcmpr(PyObject *objectA, PyObject *objectB, int compar
switch (comparison_type){
case Py_EQ:
- result = EXPP_VectorsAreEqual(eulA->eul, eulB->eul, 3, 1);
+ result = EXPP_VectorsAreEqual(eulA->eul, eulB->eul, EULER_SIZE, 1);
break;
case Py_NE:
- result = !EXPP_VectorsAreEqual(eulA->eul, eulB->eul, 3, 1);
+ result = !EXPP_VectorsAreEqual(eulA->eul, eulB->eul, EULER_SIZE, 1);
break;
default:
printf("The result of the comparison could not be evaluated");
@@ -373,15 +390,15 @@ static PyObject* Euler_richcmpr(PyObject *objectA, PyObject *objectB, int compar
//sequence length
static int Euler_len(EulerObject * self)
{
- return 3;
+ return EULER_SIZE;
}
//----------------------------object[]---------------------------
//sequence accessor (get)
static PyObject *Euler_item(EulerObject * self, int i)
{
- if(i<0) i= 3-i;
+ if(i<0) i= EULER_SIZE-i;
- if(i < 0 || i >= 3) {
+ if(i < 0 || i >= EULER_SIZE) {
PyErr_SetString(PyExc_IndexError, "euler[attribute]: array index out of range");
return NULL;
}
@@ -403,9 +420,9 @@ static int Euler_ass_item(EulerObject * self, int i, PyObject * value)
return -1;
}
- if(i<0) i= 3-i;
+ if(i<0) i= EULER_SIZE-i;
- if(i < 0 || i >= 3){
+ if(i < 0 || i >= EULER_SIZE){
PyErr_SetString(PyExc_IndexError, "euler[attribute] = x: array assignment index out of range\n");
return -1;
}
@@ -427,9 +444,9 @@ static PyObject *Euler_slice(EulerObject * self, int begin, int end)
if(!BaseMath_ReadCallback(self))
return NULL;
- CLAMP(begin, 0, 3);
- if (end<0) end= 4+end;
- CLAMP(end, 0, 3);
+ CLAMP(begin, 0, EULER_SIZE);
+ if (end<0) end= (EULER_SIZE + 1) + end;
+ CLAMP(end, 0, EULER_SIZE);
begin = MIN2(begin,end);
list = PyList_New(end - begin);
@@ -442,64 +459,123 @@ static PyObject *Euler_slice(EulerObject * self, int begin, int end)
}
//----------------------------object[z:y]------------------------
//sequence slice (set)
-static int Euler_ass_slice(EulerObject * self, int begin, int end,
- PyObject * seq)
+static int Euler_ass_slice(EulerObject * self, int begin, int end, PyObject * seq)
{
- int i, y, size = 0;
- float eul[3];
- PyObject *e;
+ int i, size;
+ float eul[EULER_SIZE];
if(!BaseMath_ReadCallback(self))
return -1;
- CLAMP(begin, 0, 3);
- if (end<0) end= 4+end;
- CLAMP(end, 0, 3);
+ CLAMP(begin, 0, EULER_SIZE);
+ if (end<0) end= (EULER_SIZE + 1) + end;
+ CLAMP(end, 0, EULER_SIZE);
begin = MIN2(begin,end);
- size = PySequence_Length(seq);
+ if((size=mathutils_array_parse(eul, 0, EULER_SIZE, seq, "mathutils.Euler[begin:end] = []")) == -1)
+ return -1;
+
if(size != (end - begin)){
PyErr_SetString(PyExc_TypeError, "euler[begin:end] = []: size mismatch in slice assignment");
return -1;
}
- for (i = 0; i < size; i++) {
- e = PySequence_GetItem(seq, i);
- if (e == NULL) { // Failed to read sequence
- PyErr_SetString(PyExc_RuntimeError, "euler[begin:end] = []: unable to read sequence");
- return -1;
+ for(i= 0; i < EULER_SIZE; i++)
+ self->eul[begin + i] = eul[i];
+
+ BaseMath_WriteCallback(self);
+ return 0;
+}
+
+static PyObject *Euler_subscript(EulerObject *self, PyObject *item)
+{
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i;
+ i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred())
+ return NULL;
+ if (i < 0)
+ i += EULER_SIZE;
+ return Euler_item(self, i);
+ } else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelength;
+
+ if (PySlice_GetIndicesEx((PySliceObject*)item, EULER_SIZE, &start, &stop, &step, &slicelength) < 0)
+ return NULL;
+
+ if (slicelength <= 0) {
+ return PyList_New(0);
+ }
+ else if (step == 1) {
+ return Euler_slice(self, start, stop);
}
+ else {
+ PyErr_SetString(PyExc_TypeError, "slice steps not supported with eulers");
+ return NULL;
+ }
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "euler indices must be integers, not %.200s",
+ item->ob_type->tp_name);
+ return NULL;
+ }
+}
+
- eul[i] = (float)PyFloat_AsDouble(e);
- Py_DECREF(e);
+static int Euler_ass_subscript(EulerObject *self, PyObject *item, PyObject *value)
+{
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred())
+ return -1;
+ if (i < 0)
+ i += EULER_SIZE;
+ return Euler_ass_item(self, i, value);
+ }
+ else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelength;
- if(eul[i]==-1 && PyErr_Occurred()) { // parsed item not a number
- PyErr_SetString(PyExc_TypeError, "euler[begin:end] = []: sequence argument not a number");
+ if (PySlice_GetIndicesEx((PySliceObject*)item, EULER_SIZE, &start, &stop, &step, &slicelength) < 0)
+ return -1;
+
+ if (step == 1)
+ return Euler_ass_slice(self, start, stop, value);
+ else {
+ PyErr_SetString(PyExc_TypeError, "slice steps not supported with euler");
return -1;
}
}
- //parsed well - now set in vector
- for(y = 0; y < 3; y++){
- self->eul[begin + y] = eul[y];
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "euler indices must be integers, not %.200s",
+ item->ob_type->tp_name);
+ return -1;
}
-
- BaseMath_WriteCallback(self);
- return 0;
}
+
//-----------------PROTCOL DECLARATIONS--------------------------
static PySequenceMethods Euler_SeqMethods = {
- (lenfunc) Euler_len, /* sq_length */
- (binaryfunc) 0, /* sq_concat */
- (ssizeargfunc) 0, /* sq_repeat */
- (ssizeargfunc) Euler_item, /* sq_item */
- (ssizessizeargfunc) Euler_slice, /* sq_slice */
- (ssizeobjargproc) Euler_ass_item, /* sq_ass_item */
- (ssizessizeobjargproc) Euler_ass_slice, /* sq_ass_slice */
+ (lenfunc) Euler_len, /* sq_length */
+ (binaryfunc) NULL, /* sq_concat */
+ (ssizeargfunc) NULL, /* sq_repeat */
+ (ssizeargfunc) Euler_item, /* sq_item */
+ (ssizessizeargfunc) NULL, /* sq_slice, deprecated */
+ (ssizeobjargproc) Euler_ass_item, /* sq_ass_item */
+ (ssizessizeobjargproc) NULL, /* sq_ass_slice, deprecated */
+ (objobjproc) NULL, /* sq_contains */
+ (binaryfunc) NULL, /* sq_inplace_concat */
+ (ssizeargfunc) NULL, /* sq_inplace_repeat */
};
+static PyMappingMethods Euler_AsMapping = {
+ (lenfunc)Euler_len,
+ (binaryfunc)Euler_subscript,
+ (objobjargproc)Euler_ass_subscript
+};
/*
- * vector axis, vector.x/y/z/w
+ * euler axis, euler.x/y/z
*/
static PyObject *Euler_getAxis( EulerObject * self, void *type )
{
@@ -514,8 +590,12 @@ static int Euler_setAxis( EulerObject * self, PyObject * value, void * type )
/* rotation order */
static PyObject *Euler_getOrder(EulerObject *self, void *type)
{
- static char order[][4] = {"XYZ", "XZY", "YXZ", "YZX", "ZXY", "ZYX"};
- return PyUnicode_FromString(order[self->order]);
+ const char order[][4] = {"XYZ", "XZY", "YXZ", "YZX", "ZXY", "ZYX"};
+
+ if(!BaseMath_ReadCallback(self)) /* can read order too */
+ return NULL;
+
+ return PyUnicode_FromString(order[self->order-EULER_ORDER_XYZ]);
}
static int Euler_setOrder( EulerObject * self, PyObject * value, void * type )
@@ -523,15 +603,11 @@ static int Euler_setOrder( EulerObject * self, PyObject * value, void * type )
char *order_str= _PyUnicode_AsString(value);
short order= euler_order_from_string(order_str, "euler.order");
- if(order < 0)
+ if(order == -1)
return -1;
- if(self->cb_user) {
- PyErr_SetString(PyExc_TypeError, "euler.order: assignment is not allowed on eulers with an owner");
- return -1;
- }
-
self->order= order;
+ BaseMath_WriteCallback(self); /* order can be written back */
return 0;
}
@@ -539,13 +615,13 @@ static int Euler_setOrder( EulerObject * self, PyObject * value, void * type )
/* Python attributes get/set structure: */
/*****************************************************************************/
static PyGetSetDef Euler_getseters[] = {
- {"x", (getter)Euler_getAxis, (setter)Euler_setAxis, "Euler X axis in radians. **type** float", (void *)0},
- {"y", (getter)Euler_getAxis, (setter)Euler_setAxis, "Euler Y axis in radians. **type** float", (void *)1},
- {"z", (getter)Euler_getAxis, (setter)Euler_setAxis, "Euler Z axis in radians. **type** float", (void *)2},
- {"order", (getter)Euler_getOrder, (setter)Euler_setOrder, "Euler rotation order. **type** string in ['XYZ', 'XZY', 'YXZ', 'YZX', 'ZXY', 'ZYX']", (void *)NULL},
+ {"x", (getter)Euler_getAxis, (setter)Euler_setAxis, "Euler X axis in radians.\n\n:type: float", (void *)0},
+ {"y", (getter)Euler_getAxis, (setter)Euler_setAxis, "Euler Y axis in radians.\n\n:type: float", (void *)1},
+ {"z", (getter)Euler_getAxis, (setter)Euler_setAxis, "Euler Z axis in radians.\n\n:type: float", (void *)2},
+ {"order", (getter)Euler_getOrder, (setter)Euler_setOrder, "Euler rotation order.\n\n:type: string in ['XYZ', 'XZY', 'YXZ', 'YZX', 'ZXY', 'ZYX']", (void *)NULL},
{"is_wrapped", (getter)BaseMathObject_getWrapped, (setter)NULL, BaseMathObject_Wrapped_doc, NULL},
- {"_owner", (getter)BaseMathObject_getOwner, (setter)NULL, BaseMathObject_Owner_doc, NULL},
+ {"owner", (getter)BaseMathObject_getOwner, (setter)NULL, BaseMathObject_Owner_doc, NULL},
{NULL,NULL,NULL,NULL,NULL} /* Sentinel */
};
@@ -556,7 +632,7 @@ static struct PyMethodDef Euler_methods[] = {
{"unique", (PyCFunction) Euler_Unique, METH_NOARGS, Euler_Unique_doc},
{"to_matrix", (PyCFunction) Euler_ToMatrix, METH_NOARGS, Euler_ToMatrix_doc},
{"to_quat", (PyCFunction) Euler_ToQuat, METH_NOARGS, Euler_ToQuat_doc},
- {"rotate", (PyCFunction) Euler_Rotate, METH_VARARGS, NULL},
+ {"rotate", (PyCFunction) Euler_Rotate, METH_VARARGS, Euler_Rotate_doc},
{"make_compatible", (PyCFunction) Euler_MakeCompatible, METH_O, Euler_MakeCompatible_doc},
{"__copy__", (PyCFunction) Euler_copy, METH_VARARGS, Euler_copy_doc},
{"copy", (PyCFunction) Euler_copy, METH_VARARGS, Euler_copy_doc},
@@ -580,7 +656,7 @@ PyTypeObject euler_Type = {
(reprfunc) Euler_repr, //tp_repr
0, //tp_as_number
&Euler_SeqMethods, //tp_as_sequence
- 0, //tp_as_mapping
+ &Euler_AsMapping, //tp_as_mapping
0, //tp_hash
0, //tp_call
0, //tp_str
@@ -624,7 +700,6 @@ PyTypeObject euler_Type = {
PyObject *newEulerObject(float *eul, short order, int type, PyTypeObject *base_type)
{
EulerObject *self;
- int x;
if(base_type) self = (EulerObject *)base_type->tp_alloc(base_type, 0);
else self = PyObject_NEW(EulerObject, &euler_Type);
@@ -633,20 +708,20 @@ PyObject *newEulerObject(float *eul, short order, int type, PyTypeObject *base_t
self->cb_user= NULL;
self->cb_type= self->cb_subtype= 0;
- if(type == Py_WRAP){
+ if(type == Py_WRAP) {
self->eul = eul;
self->wrapped = Py_WRAP;
- }else if (type == Py_NEW){
- self->eul = PyMem_Malloc(3 * sizeof(float));
- if(!eul) { //new empty
- for(x = 0; x < 3; x++) {
- self->eul[x] = 0.0f;
- }
- }else{
- VECCOPY(self->eul, eul);
- }
+ }
+ else if (type == Py_NEW){
+ self->eul = PyMem_Malloc(EULER_SIZE * sizeof(float));
+ if(eul)
+ copy_v3_v3(self->eul, eul);
+ else
+ zero_v3(self->eul);
+
self->wrapped = Py_NEW;
- }else{ //bad type
+ }
+ else{
return NULL;
}
diff --git a/source/blender/python/generic/euler.h b/source/blender/python/generic/mathutils_euler.h
index 994a5f1780e..b8523c3b661 100644
--- a/source/blender/python/generic/euler.h
+++ b/source/blender/python/generic/mathutils_euler.h
@@ -37,14 +37,7 @@ extern PyTypeObject euler_Type;
#define EulerObject_Check(_v) PyObject_TypeCheck((_v), &euler_Type)
typedef struct {
- PyObject_VAR_HEAD
- float *eul; /*1D array of data */
- PyObject *cb_user; /* if this vector references another object, otherwise NULL, *Note* this owns its reference */
- unsigned char cb_type; /* which user funcs do we adhere to, RNA, GameObject, etc */
- unsigned char cb_subtype; /* subtype: location, rotation... to avoid defining many new functions for every attribute of the same type */
- unsigned char wrapped; /* wrapped data type? */
- /* end BaseMathObject */
-
+ BASE_MATH_MEMBERS(eul)
unsigned char order; /* rotation order */
} EulerObject;
diff --git a/source/blender/python/generic/matrix.c b/source/blender/python/generic/mathutils_matrix.c
index 216139dc44f..3b8c7d3122a 100644
--- a/source/blender/python/generic/matrix.c
+++ b/source/blender/python/generic/mathutils_matrix.c
@@ -25,7 +25,7 @@
* ***** END GPL LICENSE BLOCK *****
*/
-#include "Mathutils.h"
+#include "mathutils.h"
#include "BKE_utildefines.h"
#include "BLI_math.h"
@@ -37,60 +37,60 @@ static PyObject *column_vector_multiplication(MatrixObject * mat, VectorObject*
/* matrix vector callbacks */
int mathutils_matrix_vector_cb_index= -1;
-static int mathutils_matrix_vector_check(PyObject *self_p)
+static int mathutils_matrix_vector_check(BaseMathObject *bmo)
{
- MatrixObject *self= (MatrixObject*)self_p;
+ MatrixObject *self= (MatrixObject *)bmo->cb_user;
return BaseMath_ReadCallback(self);
}
-static int mathutils_matrix_vector_get(PyObject *self_p, int subtype, float *vec_from)
+static int mathutils_matrix_vector_get(BaseMathObject *bmo, int subtype)
{
- MatrixObject *self= (MatrixObject*)self_p;
+ MatrixObject *self= (MatrixObject *)bmo->cb_user;
int i;
if(!BaseMath_ReadCallback(self))
return 0;
- for(i=0; i<self->colSize; i++)
- vec_from[i]= self->matrix[subtype][i];
+ for(i=0; i < self->colSize; i++)
+ bmo->data[i]= self->matrix[subtype][i];
return 1;
}
-static int mathutils_matrix_vector_set(PyObject *self_p, int subtype, float *vec_to)
+static int mathutils_matrix_vector_set(BaseMathObject *bmo, int subtype)
{
- MatrixObject *self= (MatrixObject*)self_p;
+ MatrixObject *self= (MatrixObject *)bmo->cb_user;
int i;
if(!BaseMath_ReadCallback(self))
return 0;
- for(i=0; i<self->colSize; i++)
- self->matrix[subtype][i]= vec_to[i];
+ for(i=0; i < self->colSize; i++)
+ self->matrix[subtype][i]= bmo->data[i];
BaseMath_WriteCallback(self);
return 1;
}
-static int mathutils_matrix_vector_get_index(PyObject *self_p, int subtype, float *vec_from, int index)
+static int mathutils_matrix_vector_get_index(BaseMathObject *bmo, int subtype, int index)
{
- MatrixObject *self= (MatrixObject*)self_p;
+ MatrixObject *self= (MatrixObject *)bmo->cb_user;
if(!BaseMath_ReadCallback(self))
return 0;
- vec_from[index]= self->matrix[subtype][index];
+ bmo->data[index]= self->matrix[subtype][index];
return 1;
}
-static int mathutils_matrix_vector_set_index(PyObject *self_p, int subtype, float *vec_to, int index)
+static int mathutils_matrix_vector_set_index(BaseMathObject *bmo, int subtype, int index)
{
- MatrixObject *self= (MatrixObject*)self_p;
+ MatrixObject *self= (MatrixObject *)bmo->cb_user;
if(!BaseMath_ReadCallback(self))
return 0;
- self->matrix[subtype][index]= vec_to[index];
+ self->matrix[subtype][index]= bmo->data[index];
BaseMath_WriteCallback(self);
return 1;
@@ -105,7 +105,7 @@ Mathutils_Callback mathutils_matrix_vector_cb = {
};
/* matrix vector callbacks, this is so you can do matrix[i][j] = val */
-//----------------------------------Mathutils.Matrix() -----------------
+//----------------------------------mathutils.Matrix() -----------------
//mat is a 1D array of floats - row[0][0],row[0][1], row[1][0], etc.
//create a new matrix type
static PyObject *Matrix_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
@@ -118,8 +118,8 @@ static PyObject *Matrix_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
float scalar;
argSize = PyTuple_GET_SIZE(args);
- if(argSize > 4){ //bad arg nums
- PyErr_SetString(PyExc_AttributeError, "Mathutils.Matrix(): expects 0-4 numeric sequences of the same size\n");
+ if(argSize > MATRIX_MAX_DIM) { //bad arg nums
+ PyErr_SetString(PyExc_AttributeError, "mathutils.Matrix(): expects 0-4 numeric sequences of the same size\n");
return NULL;
} else if (argSize == 0) { //return empty 4D matrix
return (PyObject *) newMatrixObject(NULL, 4, 4, Py_NEW, NULL);
@@ -141,13 +141,13 @@ static PyObject *Matrix_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
if (PySequence_Check(argObject)) { //seq?
if(seqSize){ //0 at first
if(PySequence_Length(argObject) != seqSize){ //seq size not same
- PyErr_SetString(PyExc_AttributeError, "Mathutils.Matrix(): expects 0-4 numeric sequences of the same size\n");
+ PyErr_SetString(PyExc_AttributeError, "mathutils.Matrix(): expects 0-4 numeric sequences of the same size\n");
return NULL;
}
}
seqSize = PySequence_Length(argObject);
}else{ //arg not a sequence
- PyErr_SetString(PyExc_TypeError, "Mathutils.Matrix(): expects 0-4 numeric sequences of the same size\n");
+ PyErr_SetString(PyExc_TypeError, "mathutils.Matrix(): expects 0-4 numeric sequences of the same size\n");
return NULL;
}
}
@@ -155,14 +155,14 @@ static PyObject *Matrix_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
for (i = 0; i < argSize; i++){
m = PyTuple_GET_ITEM(args, i);
if (m == NULL) { // Failed to read sequence
- PyErr_SetString(PyExc_RuntimeError, "Mathutils.Matrix(): failed to parse arguments...\n");
+ PyErr_SetString(PyExc_RuntimeError, "mathutils.Matrix(): failed to parse arguments...\n");
return NULL;
}
for (j = 0; j < seqSize; j++) {
s = PySequence_GetItem(m, j);
if (s == NULL) { // Failed to read sequence
- PyErr_SetString(PyExc_RuntimeError, "Mathutils.Matrix(): failed to parse arguments...\n");
+ PyErr_SetString(PyExc_RuntimeError, "mathutils.Matrix(): failed to parse arguments...\n");
return NULL;
}
@@ -170,7 +170,7 @@ static PyObject *Matrix_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
Py_DECREF(s);
if(scalar==-1 && PyErr_Occurred()) { // parsed item is not a number
- PyErr_SetString(PyExc_AttributeError, "Mathutils.Matrix(): expects 0-4 numeric sequences of the same size\n");
+ PyErr_SetString(PyExc_AttributeError, "mathutils.Matrix(): expects 0-4 numeric sequences of the same size\n");
return NULL;
}
@@ -181,6 +181,438 @@ static PyObject *Matrix_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
return newMatrixObject(matrix, argSize, seqSize, Py_NEW, NULL);
}
+/*-----------------------CLASS-METHODS----------------------------*/
+
+//----------------------------------mathutils.RotationMatrix() ----------
+//mat is a 1D array of floats - row[0][0],row[0][1], row[1][0], etc.
+static char C_Matrix_Rotation_doc[] =
+".. classmethod:: Rotation(angle, size, axis)\n"
+"\n"
+" Create a matrix representing a rotation.\n"
+"\n"
+" :arg angle: The angle of rotation desired, in radians.\n"
+" :type angle: float\n"
+" :arg size: The size of the rotation matrix to construct [2, 4].\n"
+" :type size: int\n"
+" :arg axis: a string in ['X', 'Y', 'Z'] or a 3D Vector Object (optional when size is 2).\n"
+" :type axis: string or :class:`Vector`\n"
+" :return: A new rotation matrix.\n"
+" :rtype: :class:`Matrix`\n";
+
+static PyObject *C_Matrix_Rotation(PyObject *cls, PyObject *args)
+{
+ VectorObject *vec= NULL;
+ char *axis= NULL;
+ int matSize;
+ float angle = 0.0f;
+ float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
+ 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
+
+ if(!PyArg_ParseTuple(args, "fi|O", &angle, &matSize, &vec)) {
+ PyErr_SetString(PyExc_TypeError, "mathutils.RotationMatrix(angle, size, axis): expected float int and a string or vector\n");
+ return NULL;
+ }
+
+ if(vec && !VectorObject_Check(vec)) {
+ axis= _PyUnicode_AsString((PyObject *)vec);
+ if(axis==NULL || axis[0]=='\0' || axis[1]!='\0' || axis[0] < 'X' || axis[0] > 'Z') {
+ PyErr_SetString(PyExc_TypeError, "mathutils.RotationMatrix(): 3rd argument axis value must be a 3D vector or a string in 'X', 'Y', 'Z'\n");
+ return NULL;
+ }
+ else {
+ /* use the string */
+ vec= NULL;
+ }
+ }
+
+ while (angle<-(Py_PI*2))
+ angle+=(Py_PI*2);
+ while (angle>(Py_PI*2))
+ angle-=(Py_PI*2);
+
+ if(matSize != 2 && matSize != 3 && matSize != 4) {
+ PyErr_SetString(PyExc_AttributeError, "mathutils.RotationMatrix(): can only return a 2x2 3x3 or 4x4 matrix\n");
+ return NULL;
+ }
+ if(matSize == 2 && (vec != NULL)) {
+ PyErr_SetString(PyExc_AttributeError, "mathutils.RotationMatrix(): cannot create a 2x2 rotation matrix around arbitrary axis\n");
+ return NULL;
+ }
+ if((matSize == 3 || matSize == 4) && (axis == NULL) && (vec == NULL)) {
+ PyErr_SetString(PyExc_AttributeError, "mathutils.RotationMatrix(): please choose an axis of rotation for 3d and 4d matrices\n");
+ return NULL;
+ }
+ if(vec) {
+ if(vec->size != 3) {
+ PyErr_SetString(PyExc_AttributeError, "mathutils.RotationMatrix(): the vector axis must be a 3D vector\n");
+ return NULL;
+ }
+
+ if(!BaseMath_ReadCallback(vec))
+ return NULL;
+
+ }
+
+ /* check for valid vector/axis above */
+ if(vec) {
+ axis_angle_to_mat3( (float (*)[3])mat,vec->vec, angle);
+ }
+ else if(matSize == 2) {
+ //2D rotation matrix
+ mat[0] = (float) cos (angle);
+ mat[1] = (float) sin (angle);
+ mat[2] = -((float) sin(angle));
+ mat[3] = (float) cos(angle);
+ } else if(strcmp(axis, "X") == 0) {
+ //rotation around X
+ mat[0] = 1.0f;
+ mat[4] = (float) cos(angle);
+ mat[5] = (float) sin(angle);
+ mat[7] = -((float) sin(angle));
+ mat[8] = (float) cos(angle);
+ } else if(strcmp(axis, "Y") == 0) {
+ //rotation around Y
+ mat[0] = (float) cos(angle);
+ mat[2] = -((float) sin(angle));
+ mat[4] = 1.0f;
+ mat[6] = (float) sin(angle);
+ mat[8] = (float) cos(angle);
+ } else if(strcmp(axis, "Z") == 0) {
+ //rotation around Z
+ mat[0] = (float) cos(angle);
+ mat[1] = (float) sin(angle);
+ mat[3] = -((float) sin(angle));
+ mat[4] = (float) cos(angle);
+ mat[8] = 1.0f;
+ }
+ else {
+ /* should never get here */
+ PyErr_SetString(PyExc_AttributeError, "mathutils.RotationMatrix(): unknown error\n");
+ return NULL;
+ }
+
+ if(matSize == 4) {
+ //resize matrix
+ mat[10] = mat[8];
+ mat[9] = mat[7];
+ mat[8] = mat[6];
+ mat[7] = 0.0f;
+ mat[6] = mat[5];
+ mat[5] = mat[4];
+ mat[4] = mat[3];
+ mat[3] = 0.0f;
+ }
+ //pass to matrix creation
+ return newMatrixObject(mat, matSize, matSize, Py_NEW, (PyTypeObject *)cls);
+}
+
+
+static char C_Matrix_Translation_doc[] =
+".. classmethod:: Translation(vector)\n"
+"\n"
+" Create a matrix representing a translation.\n"
+"\n"
+" :arg vector: The translation vector.\n"
+" :type vector: :class:`Vector`\n"
+" :return: An identity matrix with a translation.\n"
+" :rtype: :class:`Matrix`\n";
+
+static PyObject *C_Matrix_Translation(PyObject *cls, VectorObject * vec)
+{
+ float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
+ 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
+
+ if(!VectorObject_Check(vec)) {
+ PyErr_SetString(PyExc_TypeError, "mathutils.TranslationMatrix(): expected vector\n");
+ return NULL;
+ }
+ if(vec->size != 3 && vec->size != 4) {
+ PyErr_SetString(PyExc_TypeError, "mathutils.TranslationMatrix(): vector must be 3D or 4D\n");
+ return NULL;
+ }
+
+ if(!BaseMath_ReadCallback(vec))
+ return NULL;
+
+ //create a identity matrix and add translation
+ unit_m4((float(*)[4]) mat);
+ mat[12] = vec->vec[0];
+ mat[13] = vec->vec[1];
+ mat[14] = vec->vec[2];
+
+ return newMatrixObject(mat, 4, 4, Py_NEW, (PyTypeObject *)cls);
+}
+//----------------------------------mathutils.ScaleMatrix() -------------
+//mat is a 1D array of floats - row[0][0],row[0][1], row[1][0], etc.
+static char C_Matrix_Scale_doc[] =
+".. classmethod:: Scale(factor, size, axis)\n"
+"\n"
+" Create a matrix representing a scaling.\n"
+"\n"
+" :arg factor: The factor of scaling to apply.\n"
+" :type factor: float\n"
+" :arg size: The size of the scale matrix to construct [2, 4].\n"
+" :type size: int\n"
+" :arg axis: Direction to influence scale. (optional).\n"
+" :type axis: :class:`Vector`\n"
+" :return: A new scale matrix.\n"
+" :rtype: :class:`Matrix`\n";
+
+static PyObject *C_Matrix_Scale(PyObject *cls, PyObject *args)
+{
+ VectorObject *vec = NULL;
+ float norm = 0.0f, factor;
+ int matSize, x;
+ float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
+ 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
+
+ if(!PyArg_ParseTuple(args, "fi|O!", &factor, &matSize, &vector_Type, &vec)) {
+ PyErr_SetString(PyExc_TypeError, "mathutils.ScaleMatrix(): expected float int and optional vector\n");
+ return NULL;
+ }
+ if(matSize != 2 && matSize != 3 && matSize != 4) {
+ PyErr_SetString(PyExc_AttributeError, "mathutils.ScaleMatrix(): can only return a 2x2 3x3 or 4x4 matrix\n");
+ return NULL;
+ }
+ if(vec) {
+ if(vec->size > 2 && matSize == 2) {
+ PyErr_SetString(PyExc_AttributeError, "mathutils.ScaleMatrix(): please use 2D vectors when scaling in 2D\n");
+ return NULL;
+ }
+
+ if(!BaseMath_ReadCallback(vec))
+ return NULL;
+
+ }
+ if(vec == NULL) { //scaling along axis
+ if(matSize == 2) {
+ mat[0] = factor;
+ mat[3] = factor;
+ } else {
+ mat[0] = factor;
+ mat[4] = factor;
+ mat[8] = factor;
+ }
+ } else { //scaling in arbitrary direction
+ //normalize arbitrary axis
+ for(x = 0; x < vec->size; x++) {
+ norm += vec->vec[x] * vec->vec[x];
+ }
+ norm = (float) sqrt(norm);
+ for(x = 0; x < vec->size; x++) {
+ vec->vec[x] /= norm;
+ }
+ if(matSize == 2) {
+ mat[0] = 1 +((factor - 1) *(vec->vec[0] * vec->vec[0]));
+ mat[1] =((factor - 1) *(vec->vec[0] * vec->vec[1]));
+ mat[2] =((factor - 1) *(vec->vec[0] * vec->vec[1]));
+ mat[3] = 1 + ((factor - 1) *(vec->vec[1] * vec->vec[1]));
+ } else {
+ mat[0] = 1 + ((factor - 1) *(vec->vec[0] * vec->vec[0]));
+ mat[1] =((factor - 1) *(vec->vec[0] * vec->vec[1]));
+ mat[2] =((factor - 1) *(vec->vec[0] * vec->vec[2]));
+ mat[3] =((factor - 1) *(vec->vec[0] * vec->vec[1]));
+ mat[4] = 1 + ((factor - 1) *(vec->vec[1] * vec->vec[1]));
+ mat[5] =((factor - 1) *(vec->vec[1] * vec->vec[2]));
+ mat[6] =((factor - 1) *(vec->vec[0] * vec->vec[2]));
+ mat[7] =((factor - 1) *(vec->vec[1] * vec->vec[2]));
+ mat[8] = 1 + ((factor - 1) *(vec->vec[2] * vec->vec[2]));
+ }
+ }
+ if(matSize == 4) {
+ //resize matrix
+ mat[10] = mat[8];
+ mat[9] = mat[7];
+ mat[8] = mat[6];
+ mat[7] = 0.0f;
+ mat[6] = mat[5];
+ mat[5] = mat[4];
+ mat[4] = mat[3];
+ mat[3] = 0.0f;
+ }
+ //pass to matrix creation
+ return newMatrixObject(mat, matSize, matSize, Py_NEW, (PyTypeObject *)cls);
+}
+//----------------------------------mathutils.OrthoProjectionMatrix() ---
+//mat is a 1D array of floats - row[0][0],row[0][1], row[1][0], etc.
+static char C_Matrix_OrthoProjection_doc[] =
+".. classmethod:: OrthoProjection(plane, size, axis)\n"
+"\n"
+" Create a matrix to represent an orthographic projection.\n"
+"\n"
+" :arg plane: Can be any of the following: ['X', 'Y', 'XY', 'XZ', 'YZ', 'R'], where a single axis is for a 2D matrix and 'R' requires axis is given.\n"
+" :type plane: string\n"
+" :arg size: The size of the projection matrix to construct [2, 4].\n"
+" :type size: int\n"
+" :arg axis: Arbitrary perpendicular plane vector (optional).\n"
+" :type axis: :class:`Vector`\n"
+" :return: A new projection matrix.\n"
+" :rtype: :class:`Matrix`\n";
+static PyObject *C_Matrix_OrthoProjection(PyObject *cls, PyObject *args)
+{
+ VectorObject *vec = NULL;
+ char *plane;
+ int matSize, x;
+ float norm = 0.0f;
+ float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
+ 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
+
+ if(!PyArg_ParseTuple(args, "si|O!", &plane, &matSize, &vector_Type, &vec)) {
+ PyErr_SetString(PyExc_TypeError, "mathutils.OrthoProjectionMatrix(): expected string and int and optional vector\n");
+ return NULL;
+ }
+ if(matSize != 2 && matSize != 3 && matSize != 4) {
+ PyErr_SetString(PyExc_AttributeError,"mathutils.OrthoProjectionMatrix(): can only return a 2x2 3x3 or 4x4 matrix\n");
+ return NULL;
+ }
+ if(vec) {
+ if(vec->size > 2 && matSize == 2) {
+ PyErr_SetString(PyExc_AttributeError, "mathutils.OrthoProjectionMatrix(): please use 2D vectors when scaling in 2D\n");
+ return NULL;
+ }
+
+ if(!BaseMath_ReadCallback(vec))
+ return NULL;
+
+ }
+ if(vec == NULL) { //ortho projection onto cardinal plane
+ if((strcmp(plane, "X") == 0) && matSize == 2) {
+ mat[0] = 1.0f;
+ } else if((strcmp(plane, "Y") == 0) && matSize == 2) {
+ mat[3] = 1.0f;
+ } else if((strcmp(plane, "XY") == 0) && matSize > 2) {
+ mat[0] = 1.0f;
+ mat[4] = 1.0f;
+ } else if((strcmp(plane, "XZ") == 0) && matSize > 2) {
+ mat[0] = 1.0f;
+ mat[8] = 1.0f;
+ } else if((strcmp(plane, "YZ") == 0) && matSize > 2) {
+ mat[4] = 1.0f;
+ mat[8] = 1.0f;
+ } else {
+ PyErr_SetString(PyExc_AttributeError, "mathutils.OrthoProjectionMatrix(): unknown plane - expected: X, Y, XY, XZ, YZ\n");
+ return NULL;
+ }
+ } else { //arbitrary plane
+ //normalize arbitrary axis
+ for(x = 0; x < vec->size; x++) {
+ norm += vec->vec[x] * vec->vec[x];
+ }
+ norm = (float) sqrt(norm);
+ for(x = 0; x < vec->size; x++) {
+ vec->vec[x] /= norm;
+ }
+ if((strcmp(plane, "R") == 0) && matSize == 2) {
+ mat[0] = 1 - (vec->vec[0] * vec->vec[0]);
+ mat[1] = -(vec->vec[0] * vec->vec[1]);
+ mat[2] = -(vec->vec[0] * vec->vec[1]);
+ mat[3] = 1 - (vec->vec[1] * vec->vec[1]);
+ } else if((strcmp(plane, "R") == 0) && matSize > 2) {
+ mat[0] = 1 - (vec->vec[0] * vec->vec[0]);
+ mat[1] = -(vec->vec[0] * vec->vec[1]);
+ mat[2] = -(vec->vec[0] * vec->vec[2]);
+ mat[3] = -(vec->vec[0] * vec->vec[1]);
+ mat[4] = 1 - (vec->vec[1] * vec->vec[1]);
+ mat[5] = -(vec->vec[1] * vec->vec[2]);
+ mat[6] = -(vec->vec[0] * vec->vec[2]);
+ mat[7] = -(vec->vec[1] * vec->vec[2]);
+ mat[8] = 1 - (vec->vec[2] * vec->vec[2]);
+ } else {
+ PyErr_SetString(PyExc_AttributeError, "mathutils.OrthoProjectionMatrix(): unknown plane - expected: 'r' expected for axis designation\n");
+ return NULL;
+ }
+ }
+ if(matSize == 4) {
+ //resize matrix
+ mat[10] = mat[8];
+ mat[9] = mat[7];
+ mat[8] = mat[6];
+ mat[7] = 0.0f;
+ mat[6] = mat[5];
+ mat[5] = mat[4];
+ mat[4] = mat[3];
+ mat[3] = 0.0f;
+ }
+ //pass to matrix creation
+ return newMatrixObject(mat, matSize, matSize, Py_NEW, (PyTypeObject *)cls);
+}
+
+static char C_Matrix_Shear_doc[] =
+".. classmethod:: Shear(plane, factor, size)\n"
+"\n"
+" Create a matrix to represent an shear transformation.\n"
+"\n"
+" :arg plane: Can be any of the following: ['X', 'Y', 'XY', 'XZ', 'YZ'], where a single axis is for a 2D matrix.\n"
+" :type plane: string\n"
+" :arg factor: The factor of shear to apply.\n"
+" :type factor: float\n"
+" :arg size: The size of the shear matrix to construct [2, 4].\n"
+" :type size: int\n"
+" :return: A new shear matrix.\n"
+" :rtype: :class:`Matrix`\n";
+
+static PyObject *C_Matrix_Shear(PyObject *cls, PyObject *args)
+{
+ int matSize;
+ char *plane;
+ float factor;
+ float mat[16] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
+ 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
+
+ if(!PyArg_ParseTuple(args, "sfi", &plane, &factor, &matSize)) {
+ PyErr_SetString(PyExc_TypeError,"mathutils.ShearMatrix(): expected string float and int\n");
+ return NULL;
+ }
+ if(matSize != 2 && matSize != 3 && matSize != 4) {
+ PyErr_SetString(PyExc_AttributeError,"mathutils.ShearMatrix(): can only return a 2x2 3x3 or 4x4 matrix\n");
+ return NULL;
+ }
+
+ if((strcmp(plane, "X") == 0)
+ && matSize == 2) {
+ mat[0] = 1.0f;
+ mat[2] = factor;
+ mat[3] = 1.0f;
+ } else if((strcmp(plane, "Y") == 0) && matSize == 2) {
+ mat[0] = 1.0f;
+ mat[1] = factor;
+ mat[3] = 1.0f;
+ } else if((strcmp(plane, "XY") == 0) && matSize > 2) {
+ mat[0] = 1.0f;
+ mat[4] = 1.0f;
+ mat[6] = factor;
+ mat[7] = factor;
+ } else if((strcmp(plane, "XZ") == 0) && matSize > 2) {
+ mat[0] = 1.0f;
+ mat[3] = factor;
+ mat[4] = 1.0f;
+ mat[5] = factor;
+ mat[8] = 1.0f;
+ } else if((strcmp(plane, "YZ") == 0) && matSize > 2) {
+ mat[0] = 1.0f;
+ mat[1] = factor;
+ mat[2] = factor;
+ mat[4] = 1.0f;
+ mat[8] = 1.0f;
+ } else {
+ PyErr_SetString(PyExc_AttributeError, "mathutils.ShearMatrix(): expected: x, y, xy, xz, yz or wrong matrix size for shearing plane\n");
+ return NULL;
+ }
+ if(matSize == 4) {
+ //resize matrix
+ mat[10] = mat[8];
+ mat[9] = mat[7];
+ mat[8] = mat[6];
+ mat[7] = 0.0f;
+ mat[6] = mat[5];
+ mat[5] = mat[4];
+ mat[4] = mat[3];
+ mat[3] = 0.0f;
+ }
+ //pass to matrix creation
+ return newMatrixObject(mat, matSize, matSize, Py_NEW, (PyTypeObject *)cls);
+}
+
/* assumes rowsize == colsize is checked and the read callback has run */
static float matrix_determinant(MatrixObject * self)
{
@@ -245,7 +677,7 @@ static char Matrix_toEuler_doc[] =
PyObject *Matrix_toEuler(MatrixObject * self, PyObject *args)
{
char *order_str= NULL;
- short order= 0;
+ short order= EULER_ORDER_XYZ;
float eul[3], eul_compatf[3];
EulerObject *eul_compat = NULL;
@@ -262,7 +694,7 @@ PyObject *Matrix_toEuler(MatrixObject * self, PyObject *args)
if(!BaseMath_ReadCallback(eul_compat))
return NULL;
- VECCOPY(eul_compatf, eul_compat->eul);
+ copy_v3_v3(eul_compatf, eul_compat->eul);
}
/*must be 3-4 cols, 3-4 rows, square matrix*/
@@ -279,16 +711,16 @@ PyObject *Matrix_toEuler(MatrixObject * self, PyObject *args)
if(order_str) {
order= euler_order_from_string(order_str, "Matrix.to_euler()");
- if(order < 0)
+ if(order == -1)
return NULL;
}
if(eul_compat) {
- if(order == 0) mat3_to_compatible_eul( eul, eul_compatf, mat);
+ if(order == 1) mat3_to_compatible_eul( eul, eul_compatf, mat);
else mat3_to_compatible_eulO(eul, eul_compatf, order, mat);
}
else {
- if(order == 0) mat3_to_eul(eul, mat);
+ if(order == 1) mat3_to_eul(eul, mat);
else mat3_to_eulO(eul, order, mat);
}
@@ -321,11 +753,6 @@ PyObject *Matrix_Resize4x4(MatrixObject * self)
PyErr_SetString(PyExc_MemoryError, "matrix.resize4x4(): problem allocating pointer space");
return NULL;
}
- self->matrix = PyMem_Realloc(self->matrix, (sizeof(float *) * 4));
- if(self->matrix == NULL) {
- PyErr_SetString(PyExc_MemoryError, "matrix.resize4x4(): problem allocating pointer space");
- return NULL;
- }
/*set row pointers*/
for(x = 0; x < 4; x++) {
self->matrix[x] = self->contigPtr + (x * 4);
@@ -728,27 +1155,25 @@ PyObject *Matrix_copy(MatrixObject * self)
static PyObject *Matrix_repr(MatrixObject * self)
{
int x, y;
- char buffer[48], str[1024];
+ char str[1024]="Matrix((", *str_p;
if(!BaseMath_ReadCallback(self))
return NULL;
-
- BLI_strncpy(str,"",1024);
+
+ str_p= &str[8];
+
for(x = 0; x < self->colSize; x++){
- sprintf(buffer, "[");
- strcat(str,buffer);
for(y = 0; y < (self->rowSize - 1); y++) {
- sprintf(buffer, "%.6f, ", self->matrix[y][x]);
- strcat(str,buffer);
+ str_p += sprintf(str_p, "%f, ", self->matrix[y][x]);
}
if(x < (self->colSize-1)){
- sprintf(buffer, "%.6f](matrix [row %d])\n", self->matrix[y][x], x);
- strcat(str,buffer);
- }else{
- sprintf(buffer, "%.6f](matrix [row %d])", self->matrix[y][x], x);
- strcat(str,buffer);
+ str_p += sprintf(str_p, "%f), (", self->matrix[y][x]);
+ }
+ else{
+ str_p += sprintf(str_p, "%f)", self->matrix[y][x]);
}
}
+ strcat(str_p, ")");
return PyUnicode_FromString(str);
}
@@ -1101,7 +1526,6 @@ static PyObject *Matrix_mul(PyObject * m1, PyObject * m2)
return NULL;
}
else /* if(mat1) { */ {
-
if(VectorObject_Check(m2)) { /* MATRIX*VECTOR */
return column_vector_multiplication(mat1, (VectorObject *)m2); /* vector update done inside the function */
}
@@ -1133,13 +1557,16 @@ static PyObject* Matrix_inv(MatrixObject *self)
/*-----------------PROTOCOL DECLARATIONS--------------------------*/
static PySequenceMethods Matrix_SeqMethods = {
- (lenfunc) Matrix_len, /* sq_length */
- (binaryfunc) 0, /* sq_concat */
- (ssizeargfunc) 0, /* sq_repeat */
- (ssizeargfunc) Matrix_item, /* sq_item */
- (ssizessizeargfunc) Matrix_slice, /* sq_slice */
- (ssizeobjargproc) Matrix_ass_item, /* sq_ass_item */
- (ssizessizeobjargproc) Matrix_ass_slice, /* sq_ass_slice */
+ (lenfunc) Matrix_len, /* sq_length */
+ (binaryfunc) NULL, /* sq_concat */
+ (ssizeargfunc) NULL, /* sq_repeat */
+ (ssizeargfunc) Matrix_item, /* sq_item */
+ (ssizessizeargfunc) Matrix_slice, /* sq_slice, deprecated TODO, replace */
+ (ssizeobjargproc) Matrix_ass_item, /* sq_ass_item */
+ (ssizessizeobjargproc) Matrix_ass_slice, /* sq_ass_slice, deprecated TODO, replace */
+ (objobjproc) NULL, /* sq_contains */
+ (binaryfunc) NULL, /* sq_inplace_concat */
+ (ssizeargfunc) NULL, /* sq_inplace_repeat */
};
@@ -1304,12 +1731,12 @@ static PyObject *Matrix_getIsNegative( MatrixObject * self, void *type )
/* Python attributes get/set structure: */
/*****************************************************************************/
static PyGetSetDef Matrix_getseters[] = {
- {"row_size", (getter)Matrix_getRowSize, (setter)NULL, "The row size of the matrix (readonly). **type** int", NULL},
- {"col_size", (getter)Matrix_getColSize, (setter)NULL, "The column size of the matrix (readonly). **type** int", NULL},
- {"median_scale", (getter)Matrix_getMedianScale, (setter)NULL, "The average scale applied to each axis (readonly). **type** float", NULL},
- {"is_negative", (getter)Matrix_getIsNegative, (setter)NULL, "True if this matrix results in a negative scale, 3x3 and 4x4 only, (readonly). **type** bool", NULL},
+ {"row_size", (getter)Matrix_getRowSize, (setter)NULL, "The row size of the matrix (readonly).\n\n:type: int", NULL},
+ {"col_size", (getter)Matrix_getColSize, (setter)NULL, "The column size of the matrix (readonly).\n\n:type: int", NULL},
+ {"median_scale", (getter)Matrix_getMedianScale, (setter)NULL, "The average scale applied to each axis (readonly).\n\n:type: float", NULL},
+ {"is_negative", (getter)Matrix_getIsNegative, (setter)NULL, "True if this matrix results in a negative scale, 3x3 and 4x4 only, (readonly).\n\n:type: bool", NULL},
{"is_wrapped", (getter)BaseMathObject_getWrapped, (setter)NULL, BaseMathObject_Wrapped_doc, NULL},
- {"_owner",(getter)BaseMathObject_getOwner, (setter)NULL, BaseMathObject_Owner_doc, NULL},
+ {"owner",(getter)BaseMathObject_getOwner, (setter)NULL, BaseMathObject_Owner_doc, NULL},
{NULL,NULL,NULL,NULL,NULL} /* Sentinel */
};
@@ -1330,6 +1757,13 @@ static struct PyMethodDef Matrix_methods[] = {
{"to_quat", (PyCFunction) Matrix_toQuat, METH_NOARGS, Matrix_toQuat_doc},
{"copy", (PyCFunction) Matrix_copy, METH_NOARGS, Matrix_copy_doc},
{"__copy__", (PyCFunction) Matrix_copy, METH_NOARGS, Matrix_copy_doc},
+
+ /* class methods */
+ {"Rotation", (PyCFunction) C_Matrix_Rotation, METH_VARARGS | METH_CLASS, C_Matrix_Rotation_doc},
+ {"Scale", (PyCFunction) C_Matrix_Scale, METH_VARARGS | METH_CLASS, C_Matrix_Scale_doc},
+ {"Shear", (PyCFunction) C_Matrix_Shear, METH_VARARGS | METH_CLASS, C_Matrix_Shear_doc},
+ {"Translation", (PyCFunction) C_Matrix_Translation, METH_O | METH_CLASS, C_Matrix_Translation_doc},
+ {"OrthoProjection", (PyCFunction) C_Matrix_OrthoProjection, METH_VARARGS | METH_CLASS, C_Matrix_OrthoProjection_doc},
{NULL, NULL, 0, NULL}
};
@@ -1425,12 +1859,6 @@ PyObject *newMatrixObject(float *mat, int rowSize, int colSize, int type, PyType
if(type == Py_WRAP){
self->contigPtr = mat;
- /*create pointer array*/
- self->matrix = PyMem_Malloc(rowSize * sizeof(float *));
- if(self->matrix == NULL) { /*allocation failure*/
- PyErr_SetString( PyExc_MemoryError, "matrix(): problem allocating pointer space");
- return NULL;
- }
/*pointer array points to contigous memory*/
for(x = 0; x < rowSize; x++) {
self->matrix[x] = self->contigPtr + (x * colSize);
@@ -1442,13 +1870,6 @@ PyObject *newMatrixObject(float *mat, int rowSize, int colSize, int type, PyType
PyErr_SetString( PyExc_MemoryError, "matrix(): problem allocating pointer space\n");
return NULL;
}
- /*create pointer array*/
- self->matrix = PyMem_Malloc(rowSize * sizeof(float *));
- if(self->matrix == NULL) { /*allocation failure*/
- PyMem_Free(self->contigPtr);
- PyErr_SetString( PyExc_MemoryError, "matrix(): problem allocating pointer space");
- return NULL;
- }
/*pointer array points to contigous memory*/
for(x = 0; x < rowSize; x++) {
self->matrix[x] = self->contigPtr + (x * colSize);
diff --git a/source/blender/python/generic/matrix.h b/source/blender/python/generic/mathutils_matrix.h
index b18a3e8e6fe..21538f8168e 100644
--- a/source/blender/python/generic/matrix.h
+++ b/source/blender/python/generic/mathutils_matrix.h
@@ -34,21 +34,14 @@
extern PyTypeObject matrix_Type;
#define MatrixObject_Check(_v) PyObject_TypeCheck((_v), &matrix_Type)
+#define MATRIX_MAX_DIM 4
-typedef float **ptRow;
-typedef struct _Matrix { /* keep aligned with BaseMathObject in Mathutils.h */
- PyObject_VAR_HEAD
- float *contigPtr; /*1D array of data (alias)*/
- PyObject *cb_user; /* if this vector references another object, otherwise NULL, *Note* this owns its reference */
- unsigned char cb_type; /* which user funcs do we adhere to, RNA, GameObject, etc */
- unsigned char cb_subtype; /* subtype: location, rotation... to avoid defining many new functions for every attribute of the same type */
- unsigned char wrapped; /*is wrapped data?*/
- /* end BaseMathObject */
+typedef struct {
+ BASE_MATH_MEMBERS(contigPtr)
unsigned char rowSize;
unsigned int colSize;
- ptRow matrix; /*ptr to the contigPtr (accessor)*/
-
+ float *matrix[MATRIX_MAX_DIM]; /* ptr to the contigPtr (accessor) */
} MatrixObject;
/*struct data contains a pointer to the actual data that the
diff --git a/source/blender/python/generic/quat.c b/source/blender/python/generic/mathutils_quat.c
index 36d01e7aa9f..553844b6ee5 100644
--- a/source/blender/python/generic/quat.c
+++ b/source/blender/python/generic/mathutils_quat.c
@@ -26,12 +26,37 @@
* ***** END GPL LICENSE BLOCK *****
*/
-#include "Mathutils.h"
+#include "mathutils.h"
#include "BLI_math.h"
#include "BKE_utildefines.h"
+#define QUAT_SIZE 4
+
//-----------------------------METHODS------------------------------
+
+/* note: BaseMath_ReadCallback must be called beforehand */
+static PyObject *Quaternion_ToTupleExt(QuaternionObject *self, int ndigits)
+{
+ PyObject *ret;
+ int i;
+
+ ret= PyTuple_New(QUAT_SIZE);
+
+ if(ndigits >= 0) {
+ for(i= 0; i < QUAT_SIZE; i++) {
+ PyTuple_SET_ITEM(ret, i, PyFloat_FromDouble(double_round((double)self->quat[i], ndigits)));
+ }
+ }
+ else {
+ for(i= 0; i < QUAT_SIZE; i++) {
+ PyTuple_SET_ITEM(ret, i, PyFloat_FromDouble(self->quat[i]));
+ }
+ }
+
+ return ret;
+}
+
static char Quaternion_ToEuler_doc[] =
".. method:: to_euler(order, euler_compat)\n"
"\n"
@@ -48,7 +73,7 @@ static PyObject *Quaternion_ToEuler(QuaternionObject * self, PyObject *args)
{
float eul[3];
char *order_str= NULL;
- short order= 0;
+ short order= EULER_ORDER_XYZ;
EulerObject *eul_compat = NULL;
if(!PyArg_ParseTuple(args, "|sO!:to_euler", &order_str, &euler_Type, &eul_compat))
@@ -60,7 +85,7 @@ static PyObject *Quaternion_ToEuler(QuaternionObject * self, PyObject *args)
if(order_str) {
order= euler_order_from_string(order_str, "Matrix.to_euler()");
- if(order < 0)
+ if(order == -1)
return NULL;
}
@@ -72,19 +97,19 @@ static PyObject *Quaternion_ToEuler(QuaternionObject * self, PyObject *args)
quat_to_mat3(mat, self->quat);
- if(order == 0) mat3_to_compatible_eul(eul, eul_compat->eul, mat);
- else mat3_to_compatible_eulO(eul, eul_compat->eul, order, mat);
+ if(order == EULER_ORDER_XYZ) mat3_to_compatible_eul(eul, eul_compat->eul, mat);
+ else mat3_to_compatible_eulO(eul, eul_compat->eul, order, mat);
}
else {
- if(order == 0) quat_to_eul(eul, self->quat);
- else quat_to_eulO(eul, order, self->quat);
+ if(order == EULER_ORDER_XYZ) quat_to_eul(eul, self->quat);
+ else quat_to_eulO(eul, order, self->quat);
}
return newEulerObject(eul, order, Py_NEW, NULL);
}
//----------------------------Quaternion.toMatrix()------------------
static char Quaternion_ToMatrix_doc[] =
-".. method:: to_matrix(other)\n"
+".. method:: to_matrix()\n"
"\n"
" Return a matrix representation of the quaternion.\n"
"\n"
@@ -115,7 +140,7 @@ static char Quaternion_Cross_doc[] =
static PyObject *Quaternion_Cross(QuaternionObject * self, QuaternionObject * value)
{
- float quat[4];
+ float quat[QUAT_SIZE];
if (!QuaternionObject_Check(value)) {
PyErr_SetString( PyExc_TypeError, "quat.cross(value): expected a quaternion argument" );
@@ -165,9 +190,7 @@ static char Quaternion_Difference_doc[] =
static PyObject *Quaternion_Difference(QuaternionObject * self, QuaternionObject * value)
{
- float quat[4], tempQuat[4];
- double dot = 0.0f;
- int x;
+ float quat[QUAT_SIZE];
if (!QuaternionObject_Check(value)) {
PyErr_SetString( PyExc_TypeError, "quat.difference(value): expected a quaternion argument" );
@@ -177,18 +200,8 @@ static PyObject *Quaternion_Difference(QuaternionObject * self, QuaternionObject
if(!BaseMath_ReadCallback(self) || !BaseMath_ReadCallback(value))
return NULL;
- tempQuat[0] = self->quat[0];
- tempQuat[1] = - self->quat[1];
- tempQuat[2] = - self->quat[2];
- tempQuat[3] = - self->quat[3];
+ rotation_between_quats_to_quat(quat, self->quat, value->quat);
- dot = sqrt(tempQuat[0] * tempQuat[0] + tempQuat[1] * tempQuat[1] +
- tempQuat[2] * tempQuat[2] + tempQuat[3] * tempQuat[3]);
-
- for(x = 0; x < 4; x++) {
- tempQuat[x] /= (float)(dot * dot);
- }
- mul_qt_qtqt(quat, tempQuat, value->quat);
return newQuaternionObject(quat, Py_NEW, NULL);
}
@@ -207,7 +220,7 @@ static char Quaternion_Slerp_doc[] =
static PyObject *Quaternion_Slerp(QuaternionObject *self, PyObject *args)
{
QuaternionObject *value;
- float quat[4], fac;
+ float quat[QUAT_SIZE], fac;
if(!PyArg_ParseTuple(args, "O!f:slerp", &quaternion_Type, &value, &fac)) {
PyErr_SetString(PyExc_TypeError, "quat.slerp(): expected Quaternion types and float");
@@ -351,14 +364,19 @@ static PyObject *Quaternion_copy(QuaternionObject * self)
//print the object to screen
static PyObject *Quaternion_repr(QuaternionObject * self)
{
- char str[64];
-
+ PyObject *ret, *tuple;
+
if(!BaseMath_ReadCallback(self))
return NULL;
- sprintf(str, "[%.6f, %.6f, %.6f, %.6f](quaternion)", self->quat[0], self->quat[1], self->quat[2], self->quat[3]);
- return PyUnicode_FromString(str);
+ tuple= Quaternion_ToTupleExt(self, -1);
+
+ ret= PyUnicode_FromFormat("Quaternion(%R)", tuple);
+
+ Py_DECREF(tuple);
+ return ret;
}
+
//------------------------tp_richcmpr
//returns -1 execption, 0 false, 1 true
static PyObject* Quaternion_richcmpr(PyObject *objectA, PyObject *objectB, int comparison_type)
@@ -387,10 +405,10 @@ static PyObject* Quaternion_richcmpr(PyObject *objectA, PyObject *objectB, int c
switch (comparison_type){
case Py_EQ:
- result = EXPP_VectorsAreEqual(quatA->quat, quatB->quat, 4, 1);
+ result = EXPP_VectorsAreEqual(quatA->quat, quatB->quat, QUAT_SIZE, 1);
break;
case Py_NE:
- result = EXPP_VectorsAreEqual(quatA->quat, quatB->quat, 4, 1);
+ result = EXPP_VectorsAreEqual(quatA->quat, quatB->quat, QUAT_SIZE, 1);
if (result == 0){
result = 1;
}else{
@@ -413,15 +431,15 @@ static PyObject* Quaternion_richcmpr(PyObject *objectA, PyObject *objectB, int c
//sequence length
static int Quaternion_len(QuaternionObject * self)
{
- return 4;
+ return QUAT_SIZE;
}
//----------------------------object[]---------------------------
//sequence accessor (get)
static PyObject *Quaternion_item(QuaternionObject * self, int i)
{
- if(i<0) i= 4-i;
+ if(i<0) i= QUAT_SIZE-i;
- if(i < 0 || i >= 4) {
+ if(i < 0 || i >= QUAT_SIZE) {
PyErr_SetString(PyExc_IndexError, "quaternion[attribute]: array index out of range\n");
return NULL;
}
@@ -442,9 +460,9 @@ static int Quaternion_ass_item(QuaternionObject * self, int i, PyObject * ob)
return -1;
}
- if(i<0) i= 4-i;
+ if(i<0) i= QUAT_SIZE-i;
- if(i < 0 || i >= 4){
+ if(i < 0 || i >= QUAT_SIZE){
PyErr_SetString(PyExc_IndexError, "quaternion[attribute] = x: array assignment index out of range\n");
return -1;
}
@@ -465,9 +483,9 @@ static PyObject *Quaternion_slice(QuaternionObject * self, int begin, int end)
if(!BaseMath_ReadCallback(self))
return NULL;
- CLAMP(begin, 0, 4);
- if (end<0) end= 5+end;
- CLAMP(end, 0, 4);
+ CLAMP(begin, 0, QUAT_SIZE);
+ if (end<0) end= (QUAT_SIZE + 1) + end;
+ CLAMP(end, 0, QUAT_SIZE);
begin = MIN2(begin,end);
list = PyList_New(end - begin);
@@ -482,52 +500,107 @@ static PyObject *Quaternion_slice(QuaternionObject * self, int begin, int end)
//sequence slice (set)
static int Quaternion_ass_slice(QuaternionObject * self, int begin, int end, PyObject * seq)
{
- int i, y, size = 0;
- float quat[4];
- PyObject *q;
+ int i, size;
+ float quat[QUAT_SIZE];
if(!BaseMath_ReadCallback(self))
return -1;
- CLAMP(begin, 0, 4);
- if (end<0) end= 5+end;
- CLAMP(end, 0, 4);
+ CLAMP(begin, 0, QUAT_SIZE);
+ if (end<0) end= (QUAT_SIZE + 1) + end;
+ CLAMP(end, 0, QUAT_SIZE);
begin = MIN2(begin,end);
- size = PySequence_Length(seq);
+ if((size=mathutils_array_parse(quat, 0, QUAT_SIZE, seq, "mathutils.Quaternion[begin:end] = []")) == -1)
+ return -1;
+
if(size != (end - begin)){
- PyErr_SetString(PyExc_TypeError, "quaternion[begin:end] = []: size mismatch in slice assignment\n");
+ PyErr_SetString(PyExc_TypeError, "quaternion[begin:end] = []: size mismatch in slice assignment");
return -1;
}
- for (i = 0; i < size; i++) {
- q = PySequence_GetItem(seq, i);
- if (q == NULL) { // Failed to read sequence
- PyErr_SetString(PyExc_RuntimeError, "quaternion[begin:end] = []: unable to read sequence\n");
- return -1;
+ /* parsed well - now set in vector */
+ for(i= 0; i < size; i++)
+ self->quat[begin + i] = quat[i];
+
+ BaseMath_WriteCallback(self);
+ return 0;
+}
+
+
+static PyObject *Quaternion_subscript(QuaternionObject *self, PyObject *item)
+{
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i;
+ i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred())
+ return NULL;
+ if (i < 0)
+ i += QUAT_SIZE;
+ return Quaternion_item(self, i);
+ } else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelength;
+
+ if (PySlice_GetIndicesEx((PySliceObject*)item, QUAT_SIZE, &start, &stop, &step, &slicelength) < 0)
+ return NULL;
+
+ if (slicelength <= 0) {
+ return PyList_New(0);
+ }
+ else if (step == 1) {
+ return Quaternion_slice(self, start, stop);
}
+ else {
+ PyErr_SetString(PyExc_TypeError, "slice steps not supported with quaternions");
+ return NULL;
+ }
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "quaternion indices must be integers, not %.200s",
+ item->ob_type->tp_name);
+ return NULL;
+ }
+}
- quat[i]= (float)PyFloat_AsDouble(q);
- Py_DECREF(q);
- if(quat[i]==-1.0f && PyErr_Occurred()) { /* parsed item not a number */
- PyErr_SetString(PyExc_TypeError, "quaternion[begin:end] = []: sequence argument not a number\n");
+static int Quaternion_ass_subscript(QuaternionObject *self, PyObject *item, PyObject *value)
+{
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred())
return -1;
- }
+ if (i < 0)
+ i += QUAT_SIZE;
+ return Quaternion_ass_item(self, i, value);
}
- //parsed well - now set in vector
- for(y = 0; y < size; y++)
- self->quat[begin + y] = quat[y];
+ else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelength;
- BaseMath_WriteCallback(self);
- return 0;
+ if (PySlice_GetIndicesEx((PySliceObject*)item, QUAT_SIZE, &start, &stop, &step, &slicelength) < 0)
+ return -1;
+
+ if (step == 1)
+ return Quaternion_ass_slice(self, start, stop, value);
+ else {
+ PyErr_SetString(PyExc_TypeError, "slice steps not supported with quaternion");
+ return -1;
+ }
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "quaternion indices must be integers, not %.200s",
+ item->ob_type->tp_name);
+ return -1;
+ }
}
+
//------------------------NUMERIC PROTOCOLS----------------------
//------------------------obj + obj------------------------------
//addition
static PyObject *Quaternion_add(PyObject * q1, PyObject * q2)
{
- float quat[4];
+ float quat[QUAT_SIZE];
QuaternionObject *quat1 = NULL, *quat2 = NULL;
if(!QuaternionObject_Check(q1) || !QuaternionObject_Check(q2)) {
@@ -548,7 +621,7 @@ static PyObject *Quaternion_add(PyObject * q1, PyObject * q2)
static PyObject *Quaternion_sub(PyObject * q1, PyObject * q2)
{
int x;
- float quat[4];
+ float quat[QUAT_SIZE];
QuaternionObject *quat1 = NULL, *quat2 = NULL;
if(!QuaternionObject_Check(q1) || !QuaternionObject_Check(q2)) {
@@ -562,7 +635,7 @@ static PyObject *Quaternion_sub(PyObject * q1, PyObject * q2)
if(!BaseMath_ReadCallback(quat1) || !BaseMath_ReadCallback(quat2))
return NULL;
- for(x = 0; x < 4; x++) {
+ for(x = 0; x < QUAT_SIZE; x++) {
quat[x] = quat1->quat[x] - quat2->quat[x];
}
@@ -572,7 +645,7 @@ static PyObject *Quaternion_sub(PyObject * q1, PyObject * q2)
//mulplication
static PyObject *Quaternion_mul(PyObject * q1, PyObject * q2)
{
- float quat[4], scalar;
+ float quat[QUAT_SIZE], scalar;
QuaternionObject *quat1 = NULL, *quat2 = NULL;
VectorObject *vec = NULL;
@@ -587,8 +660,9 @@ static PyObject *Quaternion_mul(PyObject * q1, PyObject * q2)
return NULL;
}
- if(quat1 && quat2) { /* QUAT*QUAT (dot product) */
- return PyFloat_FromDouble(dot_qtqt(quat1->quat, quat2->quat));
+ if(quat1 && quat2) { /* QUAT*QUAT (cross product) */
+ mul_qt_qtqt(quat, quat1->quat, quat2->quat);
+ return newQuaternionObject(quat, Py_NEW, NULL);
}
/* the only case this can happen (for a supported type is "FLOAT*QUAT" ) */
@@ -604,12 +678,19 @@ static PyObject *Quaternion_mul(PyObject * q1, PyObject * q2)
}
else { /* QUAT*SOMETHING */
if(VectorObject_Check(q2)){ /* QUAT*VEC */
+ float tvec[3];
vec = (VectorObject*)q2;
if(vec->size != 3){
PyErr_SetString(PyExc_TypeError, "Quaternion multiplication: only 3D vector rotations currently supported\n");
return NULL;
}
- return quat_rotation((PyObject*)quat1, (PyObject*)vec); /* vector updating done inside the func */
+ if(!BaseMath_ReadCallback(vec)) {
+ return NULL;
+ }
+
+ copy_v3_v3(tvec, vec->vec);
+ mul_qt_v3(quat1->quat, tvec);
+ return newVectorObject(tvec, 3, Py_NEW, NULL);
}
scalar= PyFloat_AsDouble(q2);
@@ -626,50 +707,59 @@ static PyObject *Quaternion_mul(PyObject * q1, PyObject * q2)
//-----------------PROTOCOL DECLARATIONS--------------------------
static PySequenceMethods Quaternion_SeqMethods = {
- (lenfunc) Quaternion_len, /* sq_length */
- (binaryfunc) 0, /* sq_concat */
- (ssizeargfunc) 0, /* sq_repeat */
- (ssizeargfunc) Quaternion_item, /* sq_item */
- (ssizessizeargfunc) Quaternion_slice, /* sq_slice */
- (ssizeobjargproc) Quaternion_ass_item, /* sq_ass_item */
- (ssizessizeobjargproc) Quaternion_ass_slice, /* sq_ass_slice */
+ (lenfunc) Quaternion_len, /* sq_length */
+ (binaryfunc) NULL, /* sq_concat */
+ (ssizeargfunc) NULL, /* sq_repeat */
+ (ssizeargfunc) Quaternion_item, /* sq_item */
+ (ssizessizeargfunc) NULL, /* sq_slice, deprecated */
+ (ssizeobjargproc) Quaternion_ass_item, /* sq_ass_item */
+ (ssizessizeobjargproc) NULL, /* sq_ass_slice, deprecated */
+ (objobjproc) NULL, /* sq_contains */
+ (binaryfunc) NULL, /* sq_inplace_concat */
+ (ssizeargfunc) NULL, /* sq_inplace_repeat */
+};
+
+static PyMappingMethods Quaternion_AsMapping = {
+ (lenfunc)Quaternion_len,
+ (binaryfunc)Quaternion_subscript,
+ (objobjargproc)Quaternion_ass_subscript
};
static PyNumberMethods Quaternion_NumMethods = {
- (binaryfunc) Quaternion_add, /*nb_add*/
- (binaryfunc) Quaternion_sub, /*nb_subtract*/
- (binaryfunc) Quaternion_mul, /*nb_multiply*/
- 0, /*nb_remainder*/
- 0, /*nb_divmod*/
- 0, /*nb_power*/
- (unaryfunc) 0, /*nb_negative*/
- (unaryfunc) 0, /*tp_positive*/
- (unaryfunc) 0, /*tp_absolute*/
- (inquiry) 0, /*tp_bool*/
- (unaryfunc) 0, /*nb_invert*/
- 0, /*nb_lshift*/
- (binaryfunc)0, /*nb_rshift*/
- 0, /*nb_and*/
- 0, /*nb_xor*/
- 0, /*nb_or*/
- 0, /*nb_int*/
- 0, /*nb_reserved*/
- 0, /*nb_float*/
- 0, /* nb_inplace_add */
- 0, /* nb_inplace_subtract */
- 0, /* nb_inplace_multiply */
- 0, /* nb_inplace_remainder */
- 0, /* nb_inplace_power */
- 0, /* nb_inplace_lshift */
- 0, /* nb_inplace_rshift */
- 0, /* nb_inplace_and */
- 0, /* nb_inplace_xor */
- 0, /* nb_inplace_or */
- 0, /* nb_floor_divide */
- 0, /* nb_true_divide */
- 0, /* nb_inplace_floor_divide */
- 0, /* nb_inplace_true_divide */
- 0, /* nb_index */
+ (binaryfunc) Quaternion_add, /*nb_add*/
+ (binaryfunc) Quaternion_sub, /*nb_subtract*/
+ (binaryfunc) Quaternion_mul, /*nb_multiply*/
+ 0, /*nb_remainder*/
+ 0, /*nb_divmod*/
+ 0, /*nb_power*/
+ (unaryfunc) 0, /*nb_negative*/
+ (unaryfunc) 0, /*tp_positive*/
+ (unaryfunc) 0, /*tp_absolute*/
+ (inquiry) 0, /*tp_bool*/
+ (unaryfunc) 0, /*nb_invert*/
+ 0, /*nb_lshift*/
+ (binaryfunc)0, /*nb_rshift*/
+ 0, /*nb_and*/
+ 0, /*nb_xor*/
+ 0, /*nb_or*/
+ 0, /*nb_int*/
+ 0, /*nb_reserved*/
+ 0, /*nb_float*/
+ 0, /* nb_inplace_add */
+ 0, /* nb_inplace_subtract */
+ 0, /* nb_inplace_multiply */
+ 0, /* nb_inplace_remainder */
+ 0, /* nb_inplace_power */
+ 0, /* nb_inplace_lshift */
+ 0, /* nb_inplace_rshift */
+ 0, /* nb_inplace_and */
+ 0, /* nb_inplace_xor */
+ 0, /* nb_inplace_or */
+ 0, /* nb_floor_divide */
+ 0, /* nb_true_divide */
+ 0, /* nb_inplace_floor_divide */
+ 0, /* nb_inplace_true_divide */
+ 0, /* nb_index */
};
static PyObject *Quaternion_getAxis( QuaternionObject * self, void *type )
@@ -684,125 +774,128 @@ static int Quaternion_setAxis( QuaternionObject * self, PyObject * value, void *
static PyObject *Quaternion_getMagnitude( QuaternionObject * self, void *type )
{
+ if(!BaseMath_ReadCallback(self))
+ return NULL;
+
return PyFloat_FromDouble(sqrt(dot_qtqt(self->quat, self->quat)));
}
static PyObject *Quaternion_getAngle( QuaternionObject * self, void *type )
{
+ if(!BaseMath_ReadCallback(self))
+ return NULL;
+
return PyFloat_FromDouble(2.0 * (saacos(self->quat[0])));
}
-static PyObject *Quaternion_getAxisVec( QuaternionObject * self, void *type )
+static int Quaternion_setAngle(QuaternionObject * self, PyObject * value, void * type)
{
- int i;
- float vec[3];
- double mag = self->quat[0] * (Py_PI / 180);
- mag = 2 * (saacos(mag));
- mag = sin(mag / 2);
- for(i = 0; i < 3; i++)
- vec[i] = (float)(self->quat[i + 1] / mag);
-
- normalize_v3(vec);
- //If the axis of rotation is 0,0,0 set it to 1,0,0 - for zero-degree rotations
- if( EXPP_FloatsAreEqual(vec[0], 0.0f, 10) &&
- EXPP_FloatsAreEqual(vec[1], 0.0f, 10) &&
- EXPP_FloatsAreEqual(vec[2], 0.0f, 10) ){
- vec[0] = 1.0f;
+ float axis[3];
+ float angle;
+
+ if(!BaseMath_ReadCallback(self))
+ return -1;
+
+ quat_to_axis_angle(axis, &angle, self->quat);
+
+ angle = PyFloat_AsDouble(value);
+
+ if(angle==-1.0f && PyErr_Occurred()) { /* parsed item not a number */
+ PyErr_SetString(PyExc_TypeError, "quaternion.angle = value: float expected");
+ return -1;
}
- return (PyObject *) newVectorObject(vec, 3, Py_NEW, NULL);
+
+ /* If the axis of rotation is 0,0,0 set it to 1,0,0 - for zero-degree rotations */
+ if( EXPP_FloatsAreEqual(axis[0], 0.0f, 10) &&
+ EXPP_FloatsAreEqual(axis[1], 0.0f, 10) &&
+ EXPP_FloatsAreEqual(axis[2], 0.0f, 10)
+ ) {
+ axis[0] = 1.0f;
+ }
+
+ axis_angle_to_quat(self->quat, axis, angle);
+
+ if(!BaseMath_WriteCallback(self))
+ return -1;
+
+ return 0;
}
-//----------------------------------Mathutils.Quaternion() --------------
-static PyObject *Quaternion_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
+static PyObject *Quaternion_getAxisVec(QuaternionObject *self, void *type)
{
- PyObject *listObject = NULL, *n, *q;
- int size, i;
- float quat[4];
- double angle = 0.0f;
-
- size = PyTuple_GET_SIZE(args);
- if (size == 1 || size == 2) { //seq?
- listObject = PyTuple_GET_ITEM(args, 0);
- if (PySequence_Check(listObject)) {
- size = PySequence_Length(listObject);
- if ((size == 4 && PySequence_Length(args) !=1) ||
- (size == 3 && PySequence_Length(args) !=2) || (size >4 || size < 3)) {
- // invalid args/size
- PyErr_SetString(PyExc_AttributeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
- return NULL;
- }
- if(size == 3){ //get angle in axis/angle
- n = PySequence_GetItem(args, 1);
- if(n == NULL) { // parsed item not a number or getItem fail
- PyErr_SetString(PyExc_TypeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
- return NULL;
- }
-
- angle = PyFloat_AsDouble(n);
- Py_DECREF(n);
-
- if (angle==-1 && PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
- return NULL;
- }
- }
- }else{
- listObject = PyTuple_GET_ITEM(args, 1);
- if (size>1 && PySequence_Check(listObject)) {
- size = PySequence_Length(listObject);
- if (size != 3) {
- // invalid args/size
- PyErr_SetString(PyExc_AttributeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
- return NULL;
- }
- angle = PyFloat_AsDouble(PyTuple_GET_ITEM(args, 0));
-
- if (angle==-1 && PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
- return NULL;
- }
- } else { // argument was not a sequence
- PyErr_SetString(PyExc_TypeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
- return NULL;
- }
- }
- } else if (size == 0) { //returns a new empty quat
- return newQuaternionObject(NULL, Py_NEW, NULL);
- } else {
- listObject = args;
+ float axis[3];
+ float angle;
+
+ if(!BaseMath_ReadCallback(self))
+ return NULL;
+
+ quat_to_axis_angle(axis, &angle, self->quat);
+
+ /* If the axis of rotation is 0,0,0 set it to 1,0,0 - for zero-degree rotations */
+ if( EXPP_FloatsAreEqual(axis[0], 0.0f, 10) &&
+ EXPP_FloatsAreEqual(axis[1], 0.0f, 10) &&
+ EXPP_FloatsAreEqual(axis[2], 0.0f, 10)
+ ) {
+ axis[0] = 1.0f;
}
- if (size == 3) { // invalid quat size
- if(PySequence_Length(args) != 2){
- PyErr_SetString(PyExc_AttributeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
- return NULL;
- }
- }else{
- if(size != 4){
- PyErr_SetString(PyExc_AttributeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
- return NULL;
- }
+ return (PyObject *) newVectorObject(axis, 3, Py_NEW, NULL);
+}
+
+static int Quaternion_setAxisVec(QuaternionObject *self, PyObject *value, void *type)
+{
+ float axis[3];
+ float angle;
+
+ VectorObject *vec;
+
+ if(!BaseMath_ReadCallback(self))
+ return -1;
+
+ quat_to_axis_angle(axis, &angle, self->quat);
+
+ if(!VectorObject_Check(value)) {
+ PyErr_SetString(PyExc_TypeError, "quaternion.axis = value: expected a 3D Vector");
+ return -1;
}
+
+ vec= (VectorObject *)value;
+ if(!BaseMath_ReadCallback(vec))
+ return -1;
- for (i=0; i<size; i++) { //parse
- q = PySequence_GetItem(listObject, i);
- if (q == NULL) { // Failed to read sequence
- PyErr_SetString(PyExc_RuntimeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
- return NULL;
- }
+ axis_angle_to_quat(self->quat, vec->vec, angle);
+
+ if(!BaseMath_WriteCallback(self))
+ return -1;
+
+ return 0;
+}
+
+//----------------------------------mathutils.Quaternion() --------------
+static PyObject *Quaternion_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
+{
+ PyObject *seq= NULL;
+ float angle = 0.0f;
+ float quat[QUAT_SIZE]= {0.0f, 0.0f, 0.0f, 0.0f};
- quat[i] = PyFloat_AsDouble(q);
- Py_DECREF(q);
+ if(!PyArg_ParseTuple(args, "|Of:mathutils.Quaternion", &seq, &angle))
+ return NULL;
- if (quat[i]==-1 && PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError, "Mathutils.Quaternion(): 4d numeric sequence expected or 3d vector and number\n");
+ switch(PyTuple_GET_SIZE(args)) {
+ case 0:
+ break;
+ case 1:
+ if (mathutils_array_parse(quat, QUAT_SIZE, QUAT_SIZE, seq, "mathutils.Quaternion()") == -1)
+ return NULL;
+ break;
+ case 2:
+ if (mathutils_array_parse(quat, 3, 3, seq, "mathutils.Quaternion()") == -1)
return NULL;
- }
- }
- if(size == 3) //calculate the quat based on axis/angle
axis_angle_to_quat(quat, quat, angle);
-
+ break;
+ /* PyArg_ParseTuple assures no more then 2 */
+ }
return newQuaternionObject(quat, Py_NEW, NULL);
}
@@ -829,15 +922,15 @@ static struct PyMethodDef Quaternion_methods[] = {
/* Python attributes get/set structure: */
/*****************************************************************************/
static PyGetSetDef Quaternion_getseters[] = {
- {"w", (getter)Quaternion_getAxis, (setter)Quaternion_setAxis, "Quaternion W value. **type** float", (void *)0},
- {"x", (getter)Quaternion_getAxis, (setter)Quaternion_setAxis, "Quaternion X axis. **type** float", (void *)1},
- {"y", (getter)Quaternion_getAxis, (setter)Quaternion_setAxis, "Quaternion Y axis. **type** float", (void *)2},
- {"z", (getter)Quaternion_getAxis, (setter)Quaternion_setAxis, "Quaternion Z axis. **type** float", (void *)3},
- {"magnitude", (getter)Quaternion_getMagnitude, (setter)NULL, "Size of the quaternion (readonly). **type** float", NULL},
- {"angle", (getter)Quaternion_getAngle, (setter)NULL, "angle of the quaternion (readonly). **type** float", NULL},
- {"axis",(getter)Quaternion_getAxisVec, (setter)NULL, "quaternion axis as a vector (readonly). **type** :class:`Vector`", NULL},
+ {"w", (getter)Quaternion_getAxis, (setter)Quaternion_setAxis, "Quaternion W value.\n\n:type: float", (void *)0},
+ {"x", (getter)Quaternion_getAxis, (setter)Quaternion_setAxis, "Quaternion X axis.\n\n:type: float", (void *)1},
+ {"y", (getter)Quaternion_getAxis, (setter)Quaternion_setAxis, "Quaternion Y axis.\n\n:type: float", (void *)2},
+ {"z", (getter)Quaternion_getAxis, (setter)Quaternion_setAxis, "Quaternion Z axis.\n\n:type: float", (void *)3},
+ {"magnitude", (getter)Quaternion_getMagnitude, (setter)NULL, "Size of the quaternion (readonly).\n\n:type: float", NULL},
+ {"angle", (getter)Quaternion_getAngle, (setter)Quaternion_setAngle, "angle of the quaternion.\n\n:type: float", NULL},
+ {"axis",(getter)Quaternion_getAxisVec, (setter)Quaternion_setAxisVec, "quaternion axis as a vector.\n\n:type: :class:`Vector`", NULL},
{"is_wrapped", (getter)BaseMathObject_getWrapped, (setter)NULL, BaseMathObject_Wrapped_doc, NULL},
- {"_owner", (getter)BaseMathObject_getOwner, (setter)NULL, BaseMathObject_Owner_doc, NULL},
+ {"owner", (getter)BaseMathObject_getOwner, (setter)NULL, BaseMathObject_Owner_doc, NULL},
{NULL,NULL,NULL,NULL,NULL} /* Sentinel */
};
@@ -855,10 +948,10 @@ PyTypeObject quaternion_Type = {
0, //tp_getattr
0, //tp_setattr
0, //tp_compare
- (reprfunc) Quaternion_repr, //tp_repr
- &Quaternion_NumMethods, //tp_as_number
- &Quaternion_SeqMethods, //tp_as_sequence
- 0, //tp_as_mapping
+ (reprfunc) Quaternion_repr, //tp_repr
+ &Quaternion_NumMethods, //tp_as_number
+ &Quaternion_SeqMethods, //tp_as_sequence
+ &Quaternion_AsMapping, //tp_as_mapping
0, //tp_hash
0, //tp_call
0, //tp_str
@@ -914,7 +1007,7 @@ PyObject *newQuaternionObject(float *quat, int type, PyTypeObject *base_type)
self->quat = quat;
self->wrapped = Py_WRAP;
}else if (type == Py_NEW){
- self->quat = PyMem_Malloc(4 * sizeof(float));
+ self->quat = PyMem_Malloc(QUAT_SIZE * sizeof(float));
if(!quat) { //new empty
unit_qt(self->quat);
}else{
diff --git a/source/blender/python/generic/quat.h b/source/blender/python/generic/mathutils_quat.h
index 6e0c9d6dd1f..c9ec12d6152 100644
--- a/source/blender/python/generic/quat.h
+++ b/source/blender/python/generic/mathutils_quat.h
@@ -36,15 +36,8 @@
extern PyTypeObject quaternion_Type;
#define QuaternionObject_Check(_v) PyObject_TypeCheck((_v), &quaternion_Type)
-typedef struct { /* keep aligned with BaseMathObject in Mathutils.h */
- PyObject_VAR_HEAD
- float *quat; /* 1D array of data (alias) */
- PyObject *cb_user; /* if this vector references another object, otherwise NULL, *Note* this owns its reference */
- unsigned char cb_type; /* which user funcs do we adhere to, RNA, GameObject, etc */
- unsigned char cb_subtype; /* subtype: location, rotation... to avoid defining many new functions for every attribute of the same type */
- unsigned char wrapped; /* wrapped data type? */
- /* end BaseMathObject */
-
+typedef struct {
+ BASE_MATH_MEMBERS(quat)
} QuaternionObject;
/*struct data contains a pointer to the actual data that the
diff --git a/source/blender/python/generic/vector.c b/source/blender/python/generic/mathutils_vector.c
index fa26946a682..7b73a7501bb 100644
--- a/source/blender/python/generic/vector.c
+++ b/source/blender/python/generic/mathutils_vector.c
@@ -25,7 +25,7 @@
* ***** END GPL LICENSE BLOCK *****
*/
-#include "Mathutils.h"
+#include "mathutils.h"
#include "BLI_blenlib.h"
#include "BKE_utildefines.h"
@@ -39,56 +39,28 @@
#define SWIZZLE_VALID_AXIS 0x4
#define SWIZZLE_AXIS 0x3
-static PyObject *row_vector_multiplication(VectorObject* vec, MatrixObject * mat); /* utility func */
+static int row_vector_multiplication(float rvec[4], VectorObject* vec, MatrixObject * mat); /* utility func */
+static PyObject *Vector_ToTupleExt(VectorObject *self, int ndigits);
-//----------------------------------Mathutils.Vector() ------------------
+//----------------------------------mathutils.Vector() ------------------
// Supports 2D, 3D, and 4D vector objects both int and float values
// accepted. Mixed float and int values accepted. Ints are parsed to float
static PyObject *Vector_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *listObject = NULL;
- int size, i;
- float vec[4], f;
- PyObject *v;
-
- size = PyTuple_GET_SIZE(args); /* we know its a tuple because its an arg */
- if (size == 1) {
- listObject = PyTuple_GET_ITEM(args, 0);
- if (PySequence_Check(listObject)) {
- size = PySequence_Length(listObject);
- } else { // Single argument was not a sequence
- PyErr_SetString(PyExc_TypeError, "Mathutils.Vector(): 2-4 floats or ints expected (optionally in a sequence)\n");
+ float vec[4]= {0.0f, 0.0f, 0.0f, 0.0f};
+ int size= 3; /* default to a 3D vector */
+
+ switch(PyTuple_GET_SIZE(args)) {
+ case 0:
+ break;
+ case 1:
+ if((size=mathutils_array_parse(vec, 2, 4, PyTuple_GET_ITEM(args, 0), "mathutils.Vector()")) == -1)
return NULL;
- }
- } else if (size == 0) {
- //returns a new empty 3d vector
- return newVectorObject(NULL, 3, Py_NEW, type);
- } else {
- listObject = args;
- }
-
- if (size<2 || size>4) { // Invalid vector size
- PyErr_SetString(PyExc_AttributeError, "Mathutils.Vector(): 2-4 floats or ints expected (optionally in a sequence)\n");
+ break;
+ default:
+ PyErr_SetString(PyExc_TypeError, "mathutils.Vector(): more then a single arg given");
return NULL;
}
-
- for (i=0; i<size; i++) {
- v=PySequence_GetItem(listObject, i);
- if (v==NULL) { // Failed to read sequence
- PyErr_SetString(PyExc_RuntimeError, "Mathutils.Vector(): 2-4 floats or ints expected (optionally in a sequence)\n");
- return NULL;
- }
-
- f= PyFloat_AsDouble(v);
- if(f==-1 && PyErr_Occurred()) { // parsed item not a number
- Py_DECREF(v);
- PyErr_SetString(PyExc_TypeError, "Mathutils.Vector(): 2-4 floats or ints expected (optionally in a sequence)\n");
- return NULL;
- }
-
- vec[i]= f;
- Py_DECREF(v);
- }
return newVectorObject(vec, size, Py_NEW, type);
}
@@ -101,7 +73,7 @@ static char Vector_Zero_doc[] =
" :return: an instance of itself\n"
" :rtype: :class:`Vector`\n";
-static PyObject *Vector_Zero(VectorObject * self)
+static PyObject *Vector_Zero(VectorObject *self)
{
int i;
for(i = 0; i < self->size; i++) {
@@ -125,7 +97,7 @@ static char Vector_Normalize_doc[] =
"\n"
" .. note:: Normalize works for vectors of all sizes, however 4D Vectors w axis is left untouched.\n";
-static PyObject *Vector_Normalize(VectorObject * self)
+static PyObject *Vector_Normalize(VectorObject *self)
{
int i;
float norm = 0.0f;
@@ -156,7 +128,7 @@ static char Vector_Resize2D_doc[] =
" :return: an instance of itself\n"
" :rtype: :class:`Vector`\n";
-static PyObject *Vector_Resize2D(VectorObject * self)
+static PyObject *Vector_Resize2D(VectorObject *self)
{
if(self->wrapped==Py_WRAP) {
PyErr_SetString(PyExc_TypeError, "vector.resize2D(): cannot resize wrapped data - only python vectors\n");
@@ -186,7 +158,7 @@ static char Vector_Resize3D_doc[] =
" :return: an instance of itself\n"
" :rtype: :class:`Vector`\n";
-static PyObject *Vector_Resize3D(VectorObject * self)
+static PyObject *Vector_Resize3D(VectorObject *self)
{
if (self->wrapped==Py_WRAP) {
PyErr_SetString(PyExc_TypeError, "vector.resize3D(): cannot resize wrapped data - only python vectors\n");
@@ -219,7 +191,7 @@ static char Vector_Resize4D_doc[] =
" :return: an instance of itself\n"
" :rtype: :class:`Vector`\n";
-static PyObject *Vector_Resize4D(VectorObject * self)
+static PyObject *Vector_Resize4D(VectorObject *self)
{
if(self->wrapped==Py_WRAP) {
PyErr_SetString(PyExc_TypeError, "vector.resize4D(): cannot resize wrapped data - only python vectors");
@@ -248,37 +220,56 @@ static PyObject *Vector_Resize4D(VectorObject * self)
/*----------------------------Vector.toTuple() ------------------ */
static char Vector_ToTuple_doc[] =
-".. method:: to_tuple(precision)\n"
+".. method:: to_tuple(precision=-1)\n"
"\n"
" Return this vector as a tuple with.\n"
"\n"
-" :arg precision: The number to round the value to in [0, 21].\n"
+" :arg precision: The number to round the value to in [-1, 21].\n"
" :type precision: int\n"
" :return: the values of the vector rounded by *precision*\n"
" :rtype: tuple\n";
-static PyObject *Vector_ToTuple(VectorObject * self, PyObject *value)
+/* note: BaseMath_ReadCallback must be called beforehand */
+static PyObject *Vector_ToTupleExt(VectorObject *self, int ndigits)
{
- int ndigits= PyLong_AsSsize_t(value);
- int x;
-
PyObject *ret;
+ int i;
- if(ndigits > 22 || ndigits < 0) { /* accounts for non ints */
- PyErr_SetString(PyExc_TypeError, "vector.to_tuple(ndigits): ndigits must be between 0 and 21");
- return NULL;
+ ret= PyTuple_New(self->size);
+
+ if(ndigits >= 0) {
+ for(i = 0; i < self->size; i++) {
+ PyTuple_SET_ITEM(ret, i, PyFloat_FromDouble(double_round((double)self->vec[i], ndigits)));
+ }
+ }
+ else {
+ for(i = 0; i < self->size; i++) {
+ PyTuple_SET_ITEM(ret, i, PyFloat_FromDouble(self->vec[i]));
+ }
}
- if(!BaseMath_ReadCallback(self))
- return NULL;
+ return ret;
+}
- ret= PyTuple_New(self->size);
+static PyObject *Vector_ToTuple(VectorObject *self, PyObject *args)
+{
+ int ndigits= 0;
- for(x = 0; x < self->size; x++) {
- PyTuple_SET_ITEM(ret, x, PyFloat_FromDouble(double_round((double)self->vec[x], ndigits)));
+ if(!PyArg_ParseTuple(args, "|i:to_tuple", &ndigits))
+ return NULL;
+
+ if(ndigits > 22 || ndigits < 0) {
+ PyErr_SetString(PyExc_ValueError, "vector.to_tuple(ndigits): ndigits must be between 0 and 21");
+ return NULL;
}
- return ret;
+ if(PyTuple_GET_SIZE(args)==0)
+ ndigits= -1;
+
+ if(!BaseMath_ReadCallback(self))
+ return NULL;
+
+ return Vector_ToTupleExt(self, ndigits);
}
/*----------------------------Vector.toTrackQuat(track, up) ---------------------- */
@@ -291,19 +282,18 @@ static char Vector_ToTrackQuat_doc[] =
" :type track: string\n"
" :arg up: Up axis in ['X', 'Y', 'Z'].\n"
" :type up: string\n"
-" :return: rotation from the vector and the track and up axis."
+" :return: rotation from the vector and the track and up axis.\n"
" :rtype: :class:`Quaternion`\n";
-static PyObject *Vector_ToTrackQuat( VectorObject * self, PyObject * args )
+static PyObject *Vector_ToTrackQuat(VectorObject *self, PyObject *args )
{
float vec[3], quat[4];
char *strack, *sup;
short track = 2, up = 1;
- if(!PyArg_ParseTuple( args, "|ss:to_track_quat", &strack, &sup)) {
- PyErr_SetString( PyExc_TypeError, "expected optional two strings\n" );
+ if(!PyArg_ParseTuple( args, "|ss:to_track_quat", &strack, &sup))
return NULL;
- }
+
if (self->size != 3) {
PyErr_SetString( PyExc_TypeError, "only for 3D vectors\n" );
return NULL;
@@ -413,7 +403,7 @@ static char Vector_Reflect_doc[] =
" :return: The reflected vector matching the size of this vector.\n"
" :rtype: :class:`Vector`\n";
-static PyObject *Vector_Reflect( VectorObject * self, VectorObject * value )
+static PyObject *Vector_Reflect(VectorObject *self, VectorObject *value )
{
float mirror[3], vec[3];
float reflect[3] = {0.0f, 0.0f, 0.0f};
@@ -454,7 +444,7 @@ static char Vector_Cross_doc[] =
"\n"
" .. note:: both vectors must be 3D\n";
-static PyObject *Vector_Cross( VectorObject * self, VectorObject * value )
+static PyObject *Vector_Cross(VectorObject *self, VectorObject *value )
{
VectorObject *vecCross = NULL;
@@ -486,7 +476,7 @@ static char Vector_Dot_doc[] =
" :return: The dot product.\n"
" :rtype: :class:`Vector`\n";
-static PyObject *Vector_Dot( VectorObject * self, VectorObject * value )
+static PyObject *Vector_Dot(VectorObject *self, VectorObject *value )
{
double dot = 0.0;
int x;
@@ -510,21 +500,29 @@ static PyObject *Vector_Dot( VectorObject * self, VectorObject * value )
return PyFloat_FromDouble(dot);
}
-static char Vector_Angle_doc[] =
-".. function:: angle(other)\n"
+static char Vector_angle_doc[] =
+".. function:: angle(other, fallback)\n"
"\n"
" Return the angle between two vectors.\n"
"\n"
+" :arg other: another vector to compare the angle with\n"
" :type other: :class:`Vector`\n"
-" :return angle: angle in radians\n"
+" :arg fallback: return this value when the angle cant be calculated (zero length vector)\n"
+" :type fallback: any\n"
+" :return: angle in radians or fallback when given\n"
" :rtype: float\n"
"\n"
" .. note:: Zero length vectors raise an :exc:`AttributeError`.\n";
-static PyObject *Vector_Angle(VectorObject * self, VectorObject * value)
+static PyObject *Vector_angle(VectorObject *self, PyObject *args)
{
+ VectorObject *value;
double dot = 0.0f, angleRads, test_v1 = 0.0f, test_v2 = 0.0f;
int x, size;
+ PyObject *fallback= NULL;
+ if(!PyArg_ParseTuple(args, "O!|O:angle", &vector_Type, &value, &fallback))
+ return NULL;
+
if (!VectorObject_Check(value)) {
PyErr_SetString( PyExc_TypeError, "vec.angle(value): expected a vector argument" );
return NULL;
@@ -546,8 +544,15 @@ static PyObject *Vector_Angle(VectorObject * self, VectorObject * value)
test_v2 += value->vec[x] * value->vec[x];
}
if (!test_v1 || !test_v2){
- PyErr_SetString(PyExc_AttributeError, "vector.angle(other): zero length vectors are not acceptable arguments\n");
- return NULL;
+ /* avoid exception */
+ if(fallback) {
+ Py_INCREF(fallback);
+ return fallback;
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError, "vector.angle(other): zero length vectors have no valid angle\n");
+ return NULL;
+ }
}
//dot product
@@ -573,7 +578,7 @@ static char Vector_Difference_doc[] =
"\n"
" .. note:: 2D vectors raise an :exc:`AttributeError`.\n";;
-static PyObject *Vector_Difference( VectorObject * self, VectorObject * value )
+static PyObject *Vector_Difference(VectorObject *self, VectorObject *value )
{
float quat[4], vec_a[3], vec_b[3];
@@ -603,11 +608,12 @@ static char Vector_Project_doc[] =
"\n"
" Return the projection of this vector onto the *other*.\n"
"\n"
+" :arg other: second vector.\n"
" :type other: :class:`Vector`\n"
-" :return projection: the parallel projection vector\n"
+" :return: the parallel projection vector\n"
" :rtype: :class:`Vector`\n";
-static PyObject *Vector_Project(VectorObject * self, VectorObject * value)
+static PyObject *Vector_Project(VectorObject *self, VectorObject *value)
{
float vec[4];
double dot = 0.0f, dot2 = 0.0f;
@@ -643,7 +649,6 @@ static PyObject *Vector_Project(VectorObject * self, VectorObject * value)
return newVectorObject(vec, size, Py_NEW, NULL);
}
-//----------------------------------Mathutils.MidpointVecs() -------------
static char Vector_Lerp_doc[] =
".. function:: lerp(other, factor)\n"
"\n"
@@ -656,16 +661,15 @@ static char Vector_Lerp_doc[] =
" :return: The interpolated rotation.\n"
" :rtype: :class:`Vector`\n";
-static PyObject *Vector_Lerp(VectorObject * self, PyObject * args)
+static PyObject *Vector_Lerp(VectorObject *self, PyObject *args)
{
VectorObject *vec2 = NULL;
float fac, ifac, vec[4];
int x;
- if(!PyArg_ParseTuple(args, "O!f:lerp", &vector_Type, &vec2, &fac)) {
- PyErr_SetString(PyExc_TypeError, "vector.lerp(): expects a vector of the same size and float");
+ if(!PyArg_ParseTuple(args, "O!f:lerp", &vector_Type, &vec2, &fac))
return NULL;
- }
+
if(self->size != vec2->size) {
PyErr_SetString(PyExc_AttributeError, "vector.lerp(): expects (2) vector objects of the same size");
return NULL;
@@ -693,7 +697,7 @@ static char Vector_copy_doc[] =
"\n"
" .. note:: use this to get a copy of a wrapped vector with no reference to the original data.\n";
-static PyObject *Vector_copy(VectorObject * self)
+static PyObject *Vector_copy(VectorObject *self)
{
if(!BaseMath_ReadCallback(self))
return NULL;
@@ -703,38 +707,29 @@ static PyObject *Vector_copy(VectorObject * self)
/*----------------------------print object (internal)-------------
print the object to screen */
-static PyObject *Vector_repr(VectorObject * self)
+static PyObject *Vector_repr(VectorObject *self)
{
- int i;
- char buffer[48], str[1024];
+ PyObject *ret, *tuple;
if(!BaseMath_ReadCallback(self))
return NULL;
-
- BLI_strncpy(str,"[",1024);
- for(i = 0; i < self->size; i++){
- if(i < (self->size - 1)){
- sprintf(buffer, "%.6f, ", self->vec[i]);
- strcat(str,buffer);
- }else{
- sprintf(buffer, "%.6f", self->vec[i]);
- strcat(str,buffer);
- }
- }
- strcat(str, "](vector)");
- return PyUnicode_FromString(str);
+ tuple= Vector_ToTupleExt(self, -1);
+ ret= PyUnicode_FromFormat("Vector(%R)", tuple);
+ Py_DECREF(tuple);
+ return ret;
}
+
/*---------------------SEQUENCE PROTOCOLS------------------------
----------------------------len(object)------------------------
sequence length*/
-static int Vector_len(VectorObject * self)
+static int Vector_len(VectorObject *self)
{
return self->size;
}
/*----------------------------object[]---------------------------
sequence accessor (get)*/
-static PyObject *Vector_item(VectorObject * self, int i)
+static PyObject *Vector_item(VectorObject *self, int i)
{
if(i<0) i= self->size-i;
@@ -751,10 +746,10 @@ static PyObject *Vector_item(VectorObject * self, int i)
}
/*----------------------------object[]-------------------------
sequence accessor (set)*/
-static int Vector_ass_item(VectorObject * self, int i, PyObject * ob)
+static int Vector_ass_item(VectorObject *self, int i, PyObject * ob)
{
- float scalar= (float)PyFloat_AsDouble(ob);
- if(scalar==-1.0f && PyErr_Occurred()) { /* parsed item not a number */
+ float scalar;
+ if((scalar=PyFloat_AsDouble(ob))==-1.0f && PyErr_Occurred()) { /* parsed item not a number */
PyErr_SetString(PyExc_TypeError, "vector[index] = x: index argument not a number\n");
return -1;
}
@@ -774,7 +769,7 @@ static int Vector_ass_item(VectorObject * self, int i, PyObject * ob)
/*----------------------------object[z:y]------------------------
sequence slice (get) */
-static PyObject *Vector_slice(VectorObject * self, int begin, int end)
+static PyObject *Vector_slice(VectorObject *self, int begin, int end)
{
PyObject *list = NULL;
int count;
@@ -796,7 +791,7 @@ static PyObject *Vector_slice(VectorObject * self, int begin, int end)
}
/*----------------------------object[z:y]------------------------
sequence slice (set) */
-static int Vector_ass_slice(VectorObject * self, int begin, int end,
+static int Vector_ass_slice(VectorObject *self, int begin, int end,
PyObject * seq)
{
int i, y, size = 0;
@@ -824,8 +819,7 @@ static int Vector_ass_slice(VectorObject * self, int begin, int end,
return -1;
}
- scalar= (float)PyFloat_AsDouble(v);
- if(scalar==-1.0f && PyErr_Occurred()) { /* parsed item not a number */
+ if((scalar=PyFloat_AsDouble(v)) == -1.0f && PyErr_Occurred()) { /* parsed item not a number */
Py_DECREF(v);
PyErr_SetString(PyExc_TypeError, "vector[begin:end] = []: sequence argument not a number\n");
return -1;
@@ -1008,7 +1002,11 @@ static PyObject *Vector_mul(PyObject * v1, PyObject * v2)
return PyFloat_FromDouble(dot);
}
- /*swap so vec1 is always the vector */
+ /* swap so vec1 is always the vector */
+ /* note: it would seem from this code that the matrix multiplication below
+ * is communicative. however the matrix class will always handle the
+ * (matrix * vector) case so we can ignore it here.
+ * This is NOT so for Quaternions: TODO, check if communicative (vec * quat) is correct */
if (vec2) {
vec1= vec2;
v2= v1;
@@ -1016,15 +1014,25 @@ static PyObject *Vector_mul(PyObject * v1, PyObject * v2)
if (MatrixObject_Check(v2)) {
/* VEC * MATRIX */
- return row_vector_multiplication(vec1, (MatrixObject*)v2);
+ float tvec[4];
+ if(row_vector_multiplication(tvec, vec1, (MatrixObject*)v2) == -1)
+ return NULL;
+ return newVectorObject(tvec, vec1->size, Py_NEW, NULL);
} else if (QuaternionObject_Check(v2)) {
- QuaternionObject *quat = (QuaternionObject*)v2; /* quat_rotation validates */
+ /* VEC * QUAT */
+ QuaternionObject *quat2 = (QuaternionObject*)v2;
+ float tvec[4];
if(vec1->size != 3) {
PyErr_SetString(PyExc_TypeError, "Vector multiplication: only 3D vector rotations (with quats) currently supported\n");
return NULL;
}
- return quat_rotation((PyObject*)vec1, (PyObject*)quat);
+ if(!BaseMath_ReadCallback(quat2)) {
+ return NULL;
+ }
+ copy_v3_v3(tvec, vec1->vec);
+ mul_qt_v3(quat2->quat, tvec);
+ return newVectorObject(tvec, 3, Py_NEW, NULL);
}
else if (((scalar= PyFloat_AsDouble(v2)) == -1.0 && PyErr_Occurred())==0) { /* VEC*FLOAT */
int i;
@@ -1055,42 +1063,20 @@ static PyObject *Vector_imul(PyObject * v1, PyObject * v2)
/* only support vec*=float and vec*=mat
vec*=vec result is a float so that wont work */
if (MatrixObject_Check(v2)) {
- float vecCopy[4];
- int x,y, size = vec->size;
- MatrixObject *mat= (MatrixObject*)v2;
-
- if(!BaseMath_ReadCallback(mat))
+ float tvec[4];
+ if(row_vector_multiplication(tvec, vec, (MatrixObject*)v2) == -1)
return NULL;
-
- if(mat->colSize != size){
- if(mat->rowSize == 4 && vec->size != 3){
- PyErr_SetString(PyExc_AttributeError, "vector * matrix: matrix column size and the vector size must be the same");
- return NULL;
- } else {
- vecCopy[3] = 1.0f;
- }
- }
-
- for(i = 0; i < size; i++){
- vecCopy[i] = vec->vec[i];
- }
-
- size = MIN2(size, mat->colSize);
-
- /*muliplication*/
- for(x = 0, i = 0; x < size; x++, i++) {
- double dot = 0.0f;
- for(y = 0; y < mat->rowSize; y++) {
- dot += mat->matrix[y][x] * vecCopy[y];
- }
- vec->vec[i] = (float)dot;
- }
+
+ i= vec->size - 1;
+ do {
+ vec->vec[i] = tvec[i];
+ } while(i--);
}
else if (((scalar= PyFloat_AsDouble(v2)) == -1.0 && PyErr_Occurred())==0) { /* VEC*=FLOAT */
-
- for(i = 0; i < vec->size; i++) {
+ i= vec->size - 1;
+ do {
vec->vec[i] *= scalar;
- }
+ } while(i--);
}
else {
PyErr_SetString(PyExc_TypeError, "Vector multiplication: arguments not acceptable for this operation\n");
@@ -1118,14 +1104,13 @@ static PyObject *Vector_div(PyObject * v1, PyObject * v2)
if(!BaseMath_ReadCallback(vec1))
return NULL;
-
- scalar = (float)PyFloat_AsDouble(v2);
- if(scalar== -1.0f && PyErr_Occurred()) { /* parsed item not a number */
+
+ if((scalar=PyFloat_AsDouble(v2)) == -1.0f && PyErr_Occurred()) { /* parsed item not a number */
PyErr_SetString(PyExc_TypeError, "Vector division: Vector must be divided by a float\n");
return NULL;
}
- if(scalar==0.0) { /* not a vector */
+ if(scalar==0.0) {
PyErr_SetString(PyExc_ZeroDivisionError, "Vector division: divide by zero error.\n");
return NULL;
}
@@ -1147,13 +1132,12 @@ static PyObject *Vector_idiv(PyObject * v1, PyObject * v2)
if(!BaseMath_ReadCallback(vec1))
return NULL;
- scalar = (float)PyFloat_AsDouble(v2);
- if(scalar==-1.0f && PyErr_Occurred()) { /* parsed item not a number */
+ if((scalar=PyFloat_AsDouble(v2)) == -1.0f && PyErr_Occurred()) { /* parsed item not a number */
PyErr_SetString(PyExc_TypeError, "Vector division: Vector must be divided by a float\n");
return NULL;
}
-
- if(scalar==0.0) { /* not a vector */
+
+ if(scalar==0.0) {
PyErr_SetString(PyExc_ZeroDivisionError, "Vector division: divide by zero error.\n");
return NULL;
}
@@ -1283,13 +1267,16 @@ static PyObject* Vector_richcmpr(PyObject *objectA, PyObject *objectB, int compa
/*-----------------PROTCOL DECLARATIONS--------------------------*/
static PySequenceMethods Vector_SeqMethods = {
- (lenfunc) Vector_len, /* sq_length */
- (binaryfunc) 0, /* sq_concat */
- (ssizeargfunc) 0, /* sq_repeat */
- (ssizeargfunc) Vector_item, /* sq_item */
- NULL, /* py3 deprecated slice func */
- (ssizeobjargproc) Vector_ass_item, /* sq_ass_item */
- NULL, /* py3 deprecated slice assign func */
+ (lenfunc) Vector_len, /* sq_length */
+ (binaryfunc) 0, /* sq_concat */
+ (ssizeargfunc) 0, /* sq_repeat */
+ (ssizeargfunc) Vector_item, /* sq_item */
+ NULL, /* py3 deprecated slice func */
+ (ssizeobjargproc) Vector_ass_item, /* sq_ass_item */
+ NULL, /* py3 deprecated slice assign func */
+ (objobjproc) NULL, /* sq_contains */
+ (binaryfunc) NULL, /* sq_inplace_concat */
+ (ssizeargfunc) NULL, /* sq_inplace_repeat */
};
static PyObject *Vector_subscript(VectorObject* self, PyObject* item)
@@ -1408,18 +1395,18 @@ static PyNumberMethods Vector_NumMethods = {
* vector axis, vector.x/y/z/w
*/
-static PyObject *Vector_getAxis( VectorObject * self, void *type )
+static PyObject *Vector_getAxis(VectorObject *self, void *type )
{
return Vector_item(self, GET_INT_FROM_POINTER(type));
}
-static int Vector_setAxis( VectorObject * self, PyObject * value, void * type )
+static int Vector_setAxis(VectorObject *self, PyObject * value, void * type )
{
return Vector_ass_item(self, GET_INT_FROM_POINTER(type), value);
}
/* vector.length */
-static PyObject *Vector_getLength( VectorObject * self, void *type )
+static PyObject *Vector_getLength(VectorObject *self, void *type )
{
double dot = 0.0f;
int i;
@@ -1433,25 +1420,24 @@ static PyObject *Vector_getLength( VectorObject * self, void *type )
return PyFloat_FromDouble(sqrt(dot));
}
-static int Vector_setLength( VectorObject * self, PyObject * value )
+static int Vector_setLength(VectorObject *self, PyObject * value )
{
double dot = 0.0f, param;
int i;
if(!BaseMath_ReadCallback(self))
return -1;
-
- param= PyFloat_AsDouble( value );
- if(param==-1.0 && PyErr_Occurred()) {
+
+ if((param=PyFloat_AsDouble(value)) == -1.0 && PyErr_Occurred()) {
PyErr_SetString(PyExc_TypeError, "length must be set to a number");
return -1;
}
- if (param < 0) {
+ if (param < 0.0f) {
PyErr_SetString( PyExc_TypeError, "cannot set a vectors length to a negative value" );
return -1;
}
- if (param==0) {
+ if (param == 0.0f) {
for(i = 0; i < self->size; i++){
self->vec[i]= 0;
}
@@ -1476,7 +1462,7 @@ static int Vector_setLength( VectorObject * self, PyObject * value )
self->vec[i]= self->vec[i] / (float)dot;
}
- BaseMath_WriteCallback(self); /* checked alredy */
+ BaseMath_WriteCallback(self); /* checked already */
return 0;
}
@@ -1484,10 +1470,10 @@ static int Vector_setLength( VectorObject * self, PyObject * value )
/* Get a new Vector according to the provided swizzle. This function has little
error checking, as we are in control of the inputs: the closure is set by us
in Vector_createSwizzleGetSeter. */
-static PyObject *Vector_getSwizzle(VectorObject * self, void *closure)
+static PyObject *Vector_getSwizzle(VectorObject *self, void *closure)
{
- size_t axisA;
- size_t axisB;
+ size_t axis_to;
+ size_t axis_from;
float vec[MAX_DIMENSIONS];
unsigned int swizzleClosure;
@@ -1495,22 +1481,22 @@ static PyObject *Vector_getSwizzle(VectorObject * self, void *closure)
return NULL;
/* Unpack the axes from the closure into an array. */
- axisA = 0;
+ axis_to = 0;
swizzleClosure = GET_INT_FROM_POINTER(closure);
while (swizzleClosure & SWIZZLE_VALID_AXIS)
{
- axisB = swizzleClosure & SWIZZLE_AXIS;
- if(axisB >= self->size) {
+ axis_from = swizzleClosure & SWIZZLE_AXIS;
+ if(axis_from >= self->size) {
PyErr_SetString(PyExc_AttributeError, "Error: vector does not have specified axis.");
return NULL;
}
- vec[axisA] = self->vec[axisB];
+ vec[axis_to] = self->vec[axis_from];
swizzleClosure = swizzleClosure >> SWIZZLE_BITS_PER_AXIS;
- axisA++;
+ axis_to++;
}
- return newVectorObject(vec, axisA, Py_NEW, Py_TYPE(self));
+ return newVectorObject(vec, axis_to, Py_NEW, Py_TYPE(self));
}
/* Set the items of this vector using a swizzle.
@@ -1523,18 +1509,18 @@ static PyObject *Vector_getSwizzle(VectorObject * self, void *closure)
Returns 0 on success and -1 on failure. On failure, the vector will be
unchanged. */
-static int Vector_setSwizzle(VectorObject * self, PyObject * value, void *closure)
+static int Vector_setSwizzle(VectorObject *self, PyObject * value, void *closure)
{
- VectorObject *vecVal = NULL;
- PyObject *item;
- size_t listLen;
+ size_t size_from;
float scalarVal;
- size_t axisB;
- size_t axisA;
+ size_t axis_from;
+ size_t axis_to;
+
unsigned int swizzleClosure;
- float vecTemp[MAX_DIMENSIONS];
+ float tvec[MAX_DIMENSIONS];
+ float vec_assign[MAX_DIMENSIONS];
if(!BaseMath_ReadCallback(self))
return -1;
@@ -1542,95 +1528,48 @@ static int Vector_setSwizzle(VectorObject * self, PyObject * value, void *closur
/* Check that the closure can be used with this vector: even 2D vectors have
swizzles defined for axes z and w, but they would be invalid. */
swizzleClosure = GET_INT_FROM_POINTER(closure);
+ axis_from= 0;
while (swizzleClosure & SWIZZLE_VALID_AXIS)
{
- axisA = swizzleClosure & SWIZZLE_AXIS;
- if (axisA >= self->size)
+ axis_to = swizzleClosure & SWIZZLE_AXIS;
+ if (axis_to >= self->size)
{
PyErr_SetString(PyExc_AttributeError, "Error: vector does not have specified axis.\n");
return -1;
}
swizzleClosure = swizzleClosure >> SWIZZLE_BITS_PER_AXIS;
+ axis_from++;
}
-
- if (VectorObject_Check(value))
- {
- /* Copy vector contents onto swizzled axes. */
- vecVal = (VectorObject*) value;
- axisB = 0;
- swizzleClosure = GET_INT_FROM_POINTER(closure);
- while (swizzleClosure & SWIZZLE_VALID_AXIS && axisB < vecVal->size)
- {
- axisA = swizzleClosure & SWIZZLE_AXIS;
-
- if(axisB >= vecVal->size) {
- PyErr_SetString(PyExc_AttributeError, "Error: vector does not have specified axis.");
- return -1;
- }
-
- vecTemp[axisA] = vecVal->vec[axisB];
-
- swizzleClosure = swizzleClosure >> SWIZZLE_BITS_PER_AXIS;
- axisB++;
- }
- if(axisB != vecVal->size) {
- PyErr_SetString(PyExc_AttributeError, "Error: vector size does not match swizzle.\n");
- return -1;
- }
+ if (((scalarVal=PyFloat_AsDouble(value)) == -1 && PyErr_Occurred())==0) {
+ int i;
+ for(i=0; i < MAX_DIMENSIONS; i++)
+ vec_assign[i]= scalarVal;
- memcpy(self->vec, vecTemp, axisB * sizeof(float));
- /* continue with BaseMathObject_WriteCallback at the end */
+ size_from= axis_from;
+ }
+ else if((size_from=mathutils_array_parse(vec_assign, 2, 4, value, "mathutils.Vector.**** = swizzle assignment")) == -1) {
+ return -1;
}
- else if (PyList_Check(value))
- {
- /* Copy list contents onto swizzled axes. */
- listLen = PyList_Size(value);
- swizzleClosure = GET_INT_FROM_POINTER(closure);
- axisB = 0;
- while (swizzleClosure & SWIZZLE_VALID_AXIS && axisB < listLen)
- {
- item = PyList_GetItem(value, axisB);
- scalarVal = (float)PyFloat_AsDouble(item);
-
- if (scalarVal==-1.0 && PyErr_Occurred()) {
- PyErr_SetString(PyExc_AttributeError, "Error: list item could not be used as a float.\n");
- return -1;
- }
-
-
- axisA = swizzleClosure & SWIZZLE_AXIS;
- vecTemp[axisA] = scalarVal;
-
- swizzleClosure = swizzleClosure >> SWIZZLE_BITS_PER_AXIS;
- axisB++;
- }
-
- if(axisB != listLen) {
- PyErr_SetString(PyExc_AttributeError, "Error: list size does not match swizzle.\n");
- return -1;
- }
- memcpy(self->vec, vecTemp, axisB * sizeof(float));
- /* continue with BaseMathObject_WriteCallback at the end */
+ if(axis_from != size_from) {
+ PyErr_SetString(PyExc_AttributeError, "Error: vector size does not match swizzle.\n");
+ return -1;
}
- else if (((scalarVal = (float)PyFloat_AsDouble(value)) == -1.0 && PyErr_Occurred())==0)
+
+ /* Copy vector contents onto swizzled axes. */
+ axis_from = 0;
+ swizzleClosure = GET_INT_FROM_POINTER(closure);
+ while (swizzleClosure & SWIZZLE_VALID_AXIS)
{
- /* Assign the same value to each axis. */
- swizzleClosure = GET_INT_FROM_POINTER(closure);
- while (swizzleClosure & SWIZZLE_VALID_AXIS)
- {
- axisA = swizzleClosure & SWIZZLE_AXIS;
- self->vec[axisA] = scalarVal;
-
- swizzleClosure = swizzleClosure >> SWIZZLE_BITS_PER_AXIS;
- }
- /* continue with BaseMathObject_WriteCallback at the end */
- }
- else {
- PyErr_SetString( PyExc_TypeError, "Expected a Vector, list or scalar value." );
- return -1;
+ axis_to = swizzleClosure & SWIZZLE_AXIS;
+ tvec[axis_to] = vec_assign[axis_from];
+ swizzleClosure = swizzleClosure >> SWIZZLE_BITS_PER_AXIS;
+ axis_from++;
}
+
+ memcpy(self->vec, tvec, axis_from * sizeof(float));
+ /* continue with BaseMathObject_WriteCallback at the end */
if(!BaseMath_WriteCallback(self))
return -1;
@@ -1642,14 +1581,14 @@ static int Vector_setSwizzle(VectorObject * self, PyObject * value, void *closur
/* Python attributes get/set structure: */
/*****************************************************************************/
static PyGetSetDef Vector_getseters[] = {
- {"x", (getter)Vector_getAxis, (setter)Vector_setAxis, "Vector X axis. **type** float", (void *)0},
- {"y", (getter)Vector_getAxis, (setter)Vector_setAxis, "Vector Y axis. **type** float", (void *)1},
- {"z", (getter)Vector_getAxis, (setter)Vector_setAxis, "Vector Z axis (3D Vectors only). **type** float", (void *)2},
- {"w", (getter)Vector_getAxis, (setter)Vector_setAxis, "Vector W axis (4D Vectors only). **type** float", (void *)3},
- {"length", (getter)Vector_getLength, (setter)Vector_setLength, "Vector Length. **type** float", NULL},
- {"magnitude", (getter)Vector_getLength, (setter)Vector_setLength, "Vector Length. **type** float", NULL},
+ {"x", (getter)Vector_getAxis, (setter)Vector_setAxis, "Vector X axis.\n\n:type: float", (void *)0},
+ {"y", (getter)Vector_getAxis, (setter)Vector_setAxis, "Vector Y axis.\n\n:type: float", (void *)1},
+ {"z", (getter)Vector_getAxis, (setter)Vector_setAxis, "Vector Z axis (3D Vectors only).\n\n:type: float", (void *)2},
+ {"w", (getter)Vector_getAxis, (setter)Vector_setAxis, "Vector W axis (4D Vectors only).\n\n:type: float", (void *)3},
+ {"length", (getter)Vector_getLength, (setter)Vector_setLength, "Vector Length.\n\n:type: float", NULL},
+ {"magnitude", (getter)Vector_getLength, (setter)Vector_setLength, "Vector Length.\n\n:type: float", NULL},
{"is_wrapped", (getter)BaseMathObject_getWrapped, (setter)NULL, BaseMathObject_Wrapped_doc, NULL},
- {"_owner", (getter)BaseMathObject_getOwner, (setter)NULL, BaseMathObject_Owner_doc, NULL},
+ {"owner", (getter)BaseMathObject_getOwner, (setter)NULL, BaseMathObject_Owner_doc, NULL},
/* autogenerated swizzle attrs, see python script below */
{"xx", (getter)Vector_getSwizzle, (setter)NULL, NULL, SET_INT_IN_POINTER(((0|SWIZZLE_VALID_AXIS) | ((0|SWIZZLE_VALID_AXIS)<<SWIZZLE_BITS_PER_AXIS)))}, // 36
@@ -2038,37 +1977,37 @@ if len(unique) != len(items):
// [2][5][8]
// [3][6][9]
//vector/matrix multiplication IS NOT COMMUTATIVE!!!!
-static PyObject *row_vector_multiplication(VectorObject* vec, MatrixObject * mat)
+static int row_vector_multiplication(float rvec[4], VectorObject* vec, MatrixObject * mat)
{
- float vecNew[4], vecCopy[4];
+ float vecCopy[4];
double dot = 0.0f;
int x, y, z = 0, vec_size = vec->size;
if(mat->colSize != vec_size){
if(mat->colSize == 4 && vec_size != 3){
PyErr_SetString(PyExc_AttributeError, "vector * matrix: matrix column size and the vector size must be the same");
- return NULL;
+ return -1;
}else{
vecCopy[3] = 1.0f;
}
}
if(!BaseMath_ReadCallback(vec) || !BaseMath_ReadCallback(mat))
- return NULL;
+ return -1;
for(x = 0; x < vec_size; x++){
vecCopy[x] = vec->vec[x];
}
- vecNew[3] = 1.0f;
+ rvec[3] = 1.0f;
//muliplication
for(x = 0; x < mat->rowSize; x++) {
for(y = 0; y < mat->colSize; y++) {
dot += mat->matrix[x][y] * vecCopy[y];
}
- vecNew[z++] = (float)dot;
+ rvec[z++] = (float)dot;
dot = 0.0f;
}
- return newVectorObject(vecNew, vec_size, Py_NEW, NULL);
+ return 0;
}
/*----------------------------Vector.negate() -------------------- */
@@ -2080,7 +2019,7 @@ static char Vector_Negate_doc[] =
" :return: an instance of itself\n"
" :rtype: :class:`Vector`\n";
-static PyObject *Vector_Negate(VectorObject * self)
+static PyObject *Vector_Negate(VectorObject *self)
{
int i;
if(!BaseMath_ReadCallback(self))
@@ -2089,7 +2028,7 @@ static PyObject *Vector_Negate(VectorObject * self)
for(i = 0; i < self->size; i++)
self->vec[i] = -(self->vec[i]);
- BaseMath_WriteCallback(self); // alredy checked for error
+ BaseMath_WriteCallback(self); // already checked for error
Py_INCREF(self);
return (PyObject*)self;
@@ -2102,12 +2041,12 @@ static struct PyMethodDef Vector_methods[] = {
{"resize2D", (PyCFunction) Vector_Resize2D, METH_NOARGS, Vector_Resize2D_doc},
{"resize3D", (PyCFunction) Vector_Resize3D, METH_NOARGS, Vector_Resize3D_doc},
{"resize4D", (PyCFunction) Vector_Resize4D, METH_NOARGS, Vector_Resize4D_doc},
- {"to_tuple", (PyCFunction) Vector_ToTuple, METH_O, Vector_ToTuple_doc},
+ {"to_tuple", (PyCFunction) Vector_ToTuple, METH_VARARGS, Vector_ToTuple_doc},
{"to_track_quat", ( PyCFunction ) Vector_ToTrackQuat, METH_VARARGS, Vector_ToTrackQuat_doc},
{"reflect", ( PyCFunction ) Vector_Reflect, METH_O, Vector_Reflect_doc},
{"cross", ( PyCFunction ) Vector_Cross, METH_O, Vector_Cross_doc},
{"dot", ( PyCFunction ) Vector_Dot, METH_O, Vector_Dot_doc},
- {"angle", ( PyCFunction ) Vector_Angle, METH_O, Vector_Angle_doc},
+ {"angle", ( PyCFunction ) Vector_angle, METH_VARARGS, Vector_angle_doc},
{"difference", ( PyCFunction ) Vector_Difference, METH_O, Vector_Difference_doc},
{"project", ( PyCFunction ) Vector_Project, METH_O, Vector_Project_doc},
{"lerp", ( PyCFunction ) Vector_Lerp, METH_VARARGS, Vector_Lerp_doc},
@@ -2130,7 +2069,7 @@ PyTypeObject vector_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
/* For printing, in format "<module>.<name>" */
"vector", /* char *tp_name; */
- sizeof( VectorObject ), /* int tp_basicsize; */
+ sizeof(VectorObject), /* int tp_basicsize; */
0, /* tp_itemsize; For allocation */
/* Methods to implement standard operations */
diff --git a/source/blender/python/generic/vector.h b/source/blender/python/generic/mathutils_vector.h
index fd95f5a6750..42b9849dd3f 100644
--- a/source/blender/python/generic/vector.h
+++ b/source/blender/python/generic/mathutils_vector.h
@@ -1,4 +1,5 @@
-/* $Id$
+/*
+ * $Id$
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
@@ -35,14 +36,8 @@
extern PyTypeObject vector_Type;
#define VectorObject_Check(_v) PyObject_TypeCheck((_v), &vector_Type)
-typedef struct { /* keep aligned with BaseMathObject in Mathutils.h */
- PyObject_VAR_HEAD
- float *vec; /*1D array of data (alias), wrapped status depends on wrapped status */
- PyObject *cb_user; /* if this vector references another object, otherwise NULL, *Note* this owns its reference */
- unsigned char cb_type; /* which user funcs do we adhere to, RNA, GameObject, etc */
- unsigned char cb_subtype; /* subtype: location, rotation... to avoid defining many new functions for every attribute of the same type */
- unsigned char wrapped; /* wrapped data type? */
- /* end BaseMathObject */
+typedef struct {
+ BASE_MATH_MEMBERS(vec)
unsigned char size; /* vec size 2,3 or 4 */
} VectorObject;
diff --git a/source/blender/python/generic/noise.c b/source/blender/python/generic/noise.c
new file mode 100644
index 00000000000..4a09cbb58d8
--- /dev/null
+++ b/source/blender/python/generic/noise.c
@@ -0,0 +1,760 @@
+/**
+ * $Id$
+ *
+ * Blender.Noise BPython module implementation.
+ * This submodule has functions to generate noise of various types.
+ *
+ * ***** BEGIN GPL 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.
+ *
+ * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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 LICENSE BLOCK *****
+*/
+
+/************************/
+/* Blender Noise Module */
+/************************/
+
+#include <Python.h>
+#include "structseq.h"
+
+#include "BLI_blenlib.h"
+#include "DNA_texture_types.h"
+/*-----------------------------------------*/
+/* 'mersenne twister' random number generator */
+
+/*
+ A C-program for MT19937, with initialization improved 2002/2/10.
+ Coded by Takuji Nishimura and Makoto Matsumoto.
+ This is a faster version by taking Shawn Cokus's optimization,
+ Matthe Bellew's simplification, Isaku Wada's real version.
+
+ Before using, initialize the state by using init_genrand(seed)
+ or init_by_array(init_key, key_length).
+
+ Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+ 3. The names of its contributors may not be used to endorse or promote
+ products derived from this software without specific prior written
+ permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+
+ Any feedback is very welcome.
+ http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
+ email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
+*/
+
+/* 2.5 update
+ * Noise.setRandomSeed --> seed_set
+ * Noise.randuvec --> random_unit_vector
+ * Noise.vNoise --> noise_vector
+ * Noise.vTurbulence --> turbulence_vector
+ * Noise.multiFractal --> multi_fractal
+ * Noise.cellNoise --> cell
+ * Noise.cellNoiseV --> cell_vector
+ * Noise.vlNoise --> vl_vector
+ * Noise.heteroTerrain --> hetero_terrain
+ * Noise.hybridMFractal --> hybrid_multi_fractal
+ * Noise.fBm --> fractal
+ * Noise.ridgedMFractal --> ridged_multi_fractal
+ *
+ * Const's *
+ * Noise.NoiseTypes --> types
+ * Noise.DistanceMetrics --> distance_metrics
+ */
+
+/* Period parameters */
+#define N 624
+#define M 397
+#define MATRIX_A 0x9908b0dfUL /* constant vector a */
+#define UMASK 0x80000000UL /* most significant w-r bits */
+#define LMASK 0x7fffffffUL /* least significant r bits */
+#define MIXBITS(u,v) (((u) & UMASK) | ((v) & LMASK))
+#define TWIST(u,v) ((MIXBITS(u,v) >> 1) ^ ((v)&1UL ? MATRIX_A : 0UL))
+
+static unsigned long state[N]; /* the array for the state vector */
+static int left = 1;
+static int initf = 0;
+static unsigned long *next;
+
+PyObject *Noise_Init(void);
+
+/* initializes state[N] with a seed */
+static void init_genrand(unsigned long s)
+{
+ int j;
+ state[0] = s & 0xffffffffUL;
+ for(j = 1; j < N; j++) {
+ state[j] =
+ (1812433253UL *
+ (state[j - 1] ^ (state[j - 1] >> 30)) + j);
+ /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
+ /* In the previous versions, MSBs of the seed affect */
+ /* only MSBs of the array state[]. */
+ /* 2002/01/09 modified by Makoto Matsumoto */
+ state[j] &= 0xffffffffUL; /* for >32 bit machines */
+ }
+ left = 1;
+ initf = 1;
+}
+
+static void next_state(void)
+{
+ unsigned long *p = state;
+ int j;
+
+ /* if init_genrand() has not been called, */
+ /* a default initial seed is used */
+ if(initf == 0)
+ init_genrand(5489UL);
+
+ left = N;
+ next = state;
+
+ for(j = N - M + 1; --j; p++)
+ *p = p[M] ^ TWIST(p[0], p[1]);
+
+ for(j = M; --j; p++)
+ *p = p[M - N] ^ TWIST(p[0], p[1]);
+
+ *p = p[M - N] ^ TWIST(p[0], state[0]);
+}
+
+/*------------------------------------------------------------*/
+
+static void setRndSeed(int seed)
+{
+ if(seed == 0)
+ init_genrand(time(NULL));
+ else
+ init_genrand(seed);
+}
+
+/* float number in range [0, 1) using the mersenne twister rng */
+static float frand()
+{
+ unsigned long y;
+
+ if(--left == 0)
+ next_state();
+ y = *next++;
+
+ /* Tempering */
+ y ^= (y >> 11);
+ y ^= (y << 7) & 0x9d2c5680UL;
+ y ^= (y << 15) & 0xefc60000UL;
+ y ^= (y >> 18);
+
+ return (float) y / 4294967296.f;
+}
+
+/*------------------------------------------------------------*/
+
+/* returns random unit vector */
+static void randuvec(float v[3])
+{
+ float r;
+ v[2] = 2.f * frand() - 1.f;
+ if((r = 1.f - v[2] * v[2]) > 0.f) {
+ float a = (float)(6.283185307f * frand());
+ r = (float)sqrt(r);
+ v[0] = (float)(r * cos(a));
+ v[1] = (float)(r * sin(a));
+ } else
+ v[2] = 1.f;
+}
+
+static PyObject *Noise_random(PyObject * self)
+{
+ return PyFloat_FromDouble(frand());
+}
+
+static PyObject *Noise_random_unit_vector(PyObject * self)
+{
+ float v[3] = {0.0f, 0.0f, 0.0f};
+ randuvec(v);
+ return Py_BuildValue("[fff]", v[0], v[1], v[2]);
+}
+
+/*---------------------------------------------------------------------*/
+
+/* Random seed init. Only used for MT random() & randuvec() */
+
+static PyObject *Noise_seed_set(PyObject * self, PyObject * args)
+{
+ int s;
+ if(!PyArg_ParseTuple(args, "i:seed_set", &s))
+ return NULL;
+ setRndSeed(s);
+ Py_RETURN_NONE;
+}
+
+/*-------------------------------------------------------------------------*/
+
+/* General noise */
+
+static PyObject *Noise_noise(PyObject * self, PyObject * args)
+{
+ float x, y, z;
+ int nb = 1;
+ if(!PyArg_ParseTuple(args, "(fff)|i:noise", &x, &y, &z, &nb))
+ return NULL;
+
+ return PyFloat_FromDouble((2.0 * BLI_gNoise(1.0, x, y, z, 0, nb) - 1.0));
+}
+
+/*-------------------------------------------------------------------------*/
+
+/* General Vector noise */
+
+static void noise_vector(float x, float y, float z, int nb, float v[3])
+{
+ /* Simply evaluate noise at 3 different positions */
+ v[0] = (float)(2.0 * BLI_gNoise(1.f, x + 9.321f, y - 1.531f, z - 7.951f, 0,
+ nb) - 1.0);
+ v[1] = (float)(2.0 * BLI_gNoise(1.f, x, y, z, 0, nb) - 1.0);
+ v[2] = (float)(2.0 * BLI_gNoise(1.f, x + 6.327f, y + 0.1671f, z - 2.672f, 0,
+ nb) - 1.0);
+}
+
+static PyObject *Noise_vector(PyObject * self, PyObject * args)
+{
+ float x, y, z, v[3];
+ int nb = 1;
+ if(!PyArg_ParseTuple(args, "(fff)|i:vector", &x, &y, &z, &nb))
+ return NULL;
+ noise_vector(x, y, z, nb, v);
+ return Py_BuildValue("[fff]", v[0], v[1], v[2]);
+}
+
+/*---------------------------------------------------------------------------*/
+
+/* General turbulence */
+
+static float turb(float x, float y, float z, int oct, int hard, int nb,
+ float ampscale, float freqscale)
+{
+ float amp, out, t;
+ int i;
+ amp = 1.f;
+ out = (float)(2.0 * BLI_gNoise(1.f, x, y, z, 0, nb) - 1.0);
+ if(hard)
+ out = (float)fabs(out);
+ for(i = 1; i < oct; i++) {
+ amp *= ampscale;
+ x *= freqscale;
+ y *= freqscale;
+ z *= freqscale;
+ t = (float)(amp * (2.0 * BLI_gNoise(1.f, x, y, z, 0, nb) - 1.0));
+ if(hard)
+ t = (float)fabs(t);
+ out += t;
+ }
+ return out;
+}
+
+static PyObject *Noise_turbulence(PyObject * self, PyObject * args)
+{
+ float x, y, z;
+ int oct, hd, nb = 1;
+ float as = 0.5, fs = 2.0;
+ if(!PyArg_ParseTuple(args, "(fff)ii|iff:turbulence", &x, &y, &z, &oct, &hd, &nb, &as, &fs))
+ return NULL;
+
+ return PyFloat_FromDouble(turb(x, y, z, oct, hd, nb, as, fs));
+}
+
+/*--------------------------------------------------------------------------*/
+
+/* Turbulence Vector */
+
+static void vTurb(float x, float y, float z, int oct, int hard, int nb,
+ float ampscale, float freqscale, float v[3])
+{
+ float amp, t[3];
+ int i;
+ amp = 1.f;
+ noise_vector(x, y, z, nb, v);
+ if(hard) {
+ v[0] = (float)fabs(v[0]);
+ v[1] = (float)fabs(v[1]);
+ v[2] = (float)fabs(v[2]);
+ }
+ for(i = 1; i < oct; i++) {
+ amp *= ampscale;
+ x *= freqscale;
+ y *= freqscale;
+ z *= freqscale;
+ noise_vector(x, y, z, nb, t);
+ if(hard) {
+ t[0] = (float)fabs(t[0]);
+ t[1] = (float)fabs(t[1]);
+ t[2] = (float)fabs(t[2]);
+ }
+ v[0] += amp * t[0];
+ v[1] += amp * t[1];
+ v[2] += amp * t[2];
+ }
+}
+
+static PyObject *Noise_turbulence_vector(PyObject * self, PyObject * args)
+{
+ float x, y, z, v[3];
+ int oct, hd, nb = 1;
+ float as = 0.5, fs = 2.0;
+ if(!PyArg_ParseTuple(args, "(fff)ii|iff:turbulence_vector", &x, &y, &z, &oct, &hd, &nb, &as, &fs))
+ return NULL;
+ vTurb(x, y, z, oct, hd, nb, as, fs, v);
+ return Py_BuildValue("[fff]", v[0], v[1], v[2]);
+}
+
+/*---------------------------------------------------------------------*/
+
+/* F. Kenton Musgrave's fractal functions */
+
+static PyObject *Noise_fractal(PyObject * self, PyObject * args)
+{
+ float x, y, z, H, lac, oct;
+ int nb = 1;
+ if(!PyArg_ParseTuple(args, "(fff)fff|i:fractal", &x, &y, &z, &H, &lac, &oct, &nb))
+ return NULL;
+ return PyFloat_FromDouble(mg_fBm(x, y, z, H, lac, oct, nb));
+}
+
+/*------------------------------------------------------------------------*/
+
+static PyObject *Noise_multi_fractal(PyObject * self, PyObject * args)
+{
+ float x, y, z, H, lac, oct;
+ int nb = 1;
+ if(!PyArg_ParseTuple(args, "(fff)fff|i:multi_fractal", &x, &y, &z, &H, &lac, &oct, &nb))
+ return NULL;
+
+ return PyFloat_FromDouble(mg_MultiFractal(x, y, z, H, lac, oct, nb));
+}
+
+/*------------------------------------------------------------------------*/
+
+static PyObject *Noise_vl_vector(PyObject * self, PyObject * args)
+{
+ float x, y, z, d;
+ int nt1 = 1, nt2 = 1;
+ if(!PyArg_ParseTuple(args, "(fff)f|ii:vl_vector", &x, &y, &z, &d, &nt1, &nt2))
+ return NULL;
+ return PyFloat_FromDouble(mg_VLNoise(x, y, z, d, nt1, nt2));
+}
+
+/*-------------------------------------------------------------------------*/
+
+static PyObject *Noise_hetero_terrain(PyObject * self, PyObject * args)
+{
+ float x, y, z, H, lac, oct, ofs;
+ int nb = 1;
+ if(!PyArg_ParseTuple(args, "(fff)ffff|i:hetero_terrain", &x, &y, &z, &H, &lac, &oct, &ofs, &nb))
+ return NULL;
+
+ return PyFloat_FromDouble(mg_HeteroTerrain(x, y, z, H, lac, oct, ofs, nb));
+}
+
+/*-------------------------------------------------------------------------*/
+
+static PyObject *Noise_hybrid_multi_fractal(PyObject * self, PyObject * args)
+{
+ float x, y, z, H, lac, oct, ofs, gn;
+ int nb = 1;
+ if(!PyArg_ParseTuple(args, "(fff)fffff|i:hybrid_multi_fractal", &x, &y, &z, &H, &lac, &oct, &ofs, &gn, &nb))
+ return NULL;
+
+ return PyFloat_FromDouble(mg_HybridMultiFractal(x, y, z, H, lac, oct, ofs, gn, nb));
+}
+
+/*------------------------------------------------------------------------*/
+
+static PyObject *Noise_ridged_multi_fractal(PyObject * self, PyObject * args)
+{
+ float x, y, z, H, lac, oct, ofs, gn;
+ int nb = 1;
+ if(!PyArg_ParseTuple(args, "(fff)fffff|i:ridged_multi_fractal", &x, &y, &z, &H, &lac, &oct, &ofs, &gn, &nb))
+ return NULL;
+ return PyFloat_FromDouble(mg_RidgedMultiFractal(x, y, z, H, lac, oct, ofs, gn, nb));
+}
+
+/*-------------------------------------------------------------------------*/
+
+static PyObject *Noise_voronoi(PyObject * self, PyObject * args)
+{
+ float x, y, z, da[4], pa[12];
+ int dtype = 0;
+ float me = 2.5; /* default minkovsky exponent */
+ if(!PyArg_ParseTuple(args, "(fff)|if:voronoi", &x, &y, &z, &dtype, &me))
+ return NULL;
+ voronoi(x, y, z, da, pa, me, dtype);
+ return Py_BuildValue("[[ffff][[fff][fff][fff][fff]]]",
+ da[0], da[1], da[2], da[3],
+ pa[0], pa[1], pa[2],
+ pa[3], pa[4], pa[5],
+ pa[6], pa[7], pa[8], pa[9], pa[10], pa[11]);
+}
+
+/*-------------------------------------------------------------------------*/
+
+static PyObject *Noise_cell(PyObject * self, PyObject * args)
+{
+ float x, y, z;
+ if(!PyArg_ParseTuple(args, "(fff):cell", &x, &y, &z))
+ return NULL;
+
+ return PyFloat_FromDouble(cellNoise(x, y, z));
+}
+
+/*--------------------------------------------------------------------------*/
+
+static PyObject *Noise_cell_vector(PyObject * self, PyObject * args)
+{
+ float x, y, z, ca[3];
+ if(!PyArg_ParseTuple(args, "(fff):cell_vector", &x, &y, &z))
+ return NULL;
+ cellNoiseV(x, y, z, ca);
+ return Py_BuildValue("[fff]", ca[0], ca[1], ca[2]);
+}
+
+/*--------------------------------------------------------------------------*/
+/* For all other Blender modules, this stuff seems to be put in a header file.
+ This doesn't seem really appropriate to me, so I just put it here, feel free to change it.
+ In the original module I actually kept the docs stings with the functions themselves,
+ but I grouped them here so that it can easily be moved to a header if anyone thinks that is necessary. */
+
+static char random__doc__[] = "() No arguments.\n\n\
+Returns a random floating point number in the range [0, 1)";
+
+static char random_unit_vector__doc__[] =
+ "() No arguments.\n\nReturns a random unit vector (3-float list).";
+
+static char seed_set__doc__[] = "(seed value)\n\n\
+Initializes random number generator.\n\
+if seed is zero, the current time will be used instead.";
+
+static char noise__doc__[] = "((x,y,z) tuple, [noisetype])\n\n\
+Returns general noise of the optional specified type.\n\
+Optional argument noisetype determines the type of noise, STDPERLIN by default, see NoiseTypes.";
+
+static char noise_vector__doc__[] = "((x,y,z) tuple, [noisetype])\n\n\
+Returns noise vector (3-float list) of the optional specified type.\
+Optional argument noisetype determines the type of noise, STDPERLIN by default, see NoiseTypes.";
+
+static char turbulence__doc__[] =
+ "((x,y,z) tuple, octaves, hard, [noisebasis], [ampscale], [freqscale])\n\n\
+Returns general turbulence value using the optional specified noisebasis function.\n\
+octaves (integer) is the number of noise values added.\n\
+hard (bool), when false (0) returns 'soft' noise, when true (1) returns 'hard' noise (returned value always positive).\n\
+Optional arguments:\n\
+noisebasis determines the type of noise used for the turbulence, STDPERLIN by default, see NoiseTypes.\n\
+ampscale sets the amplitude scale value of the noise frequencies added, 0.5 by default.\n\
+freqscale sets the frequency scale factor, 2.0 by default.";
+
+static char turbulence_vector__doc__[] =
+ "((x,y,z) tuple, octaves, hard, [noisebasis], [ampscale], [freqscale])\n\n\
+Returns general turbulence vector (3-float list) using the optional specified noisebasis function.\n\
+octaves (integer) is the number of noise values added.\n\
+hard (bool), when false (0) returns 'soft' noise, when true (1) returns 'hard' noise (returned vector always positive).\n\
+Optional arguments:\n\
+noisebasis determines the type of noise used for the turbulence, STDPERLIN by default, see NoiseTypes.\n\
+ampscale sets the amplitude scale value of the noise frequencies added, 0.5 by default.\n\
+freqscale sets the frequency scale factor, 2.0 by default.";
+
+static char fractal__doc__[] =
+ "((x,y,z) tuple, H, lacunarity, octaves, [noisebasis])\n\n\
+Returns Fractal Brownian Motion noise value(fBm).\n\
+H is the fractal increment parameter.\n\
+lacunarity is the gap between successive frequencies.\n\
+octaves is the number of frequencies in the fBm.\n\
+Optional argument noisebasis determines the type of noise used for the turbulence, STDPERLIN by default, see NoiseTypes.";
+
+static char multi_fractal__doc__[] =
+ "((x,y,z) tuple, H, lacunarity, octaves, [noisebasis])\n\n\
+Returns Multifractal noise value.\n\
+H determines the highest fractal dimension.\n\
+lacunarity is gap between successive frequencies.\n\
+octaves is the number of frequencies in the fBm.\n\
+Optional argument noisebasis determines the type of noise used for the turbulence, STDPERLIN by default, see NoiseTypes.";
+
+static char vl_vector__doc__[] =
+ "((x,y,z) tuple, distortion, [noisetype1], [noisetype2])\n\n\
+Returns Variable Lacunarity Noise value, a distorted variety of noise.\n\
+distortion sets the amount of distortion.\n\
+Optional arguments noisetype1 and noisetype2 set the noisetype to distort and the noisetype used for the distortion respectively.\n\
+See NoiseTypes, both are STDPERLIN by default.";
+
+static char hetero_terrain__doc__[] =
+ "((x,y,z) tuple, H, lacunarity, octaves, offset, [noisebasis])\n\n\
+returns Heterogeneous Terrain value\n\
+H determines the fractal dimension of the roughest areas.\n\
+lacunarity is the gap between successive frequencies.\n\
+octaves is the number of frequencies in the fBm.\n\
+offset raises the terrain from 'sea level'.\n\
+Optional argument noisebasis determines the type of noise used for the turbulence, STDPERLIN by default, see NoiseTypes.";
+
+static char hybrid_multi_fractal__doc__[] =
+ "((x,y,z) tuple, H, lacunarity, octaves, offset, gain, [noisebasis])\n\n\
+returns Hybrid Multifractal value.\n\
+H determines the fractal dimension of the roughest areas.\n\
+lacunarity is the gap between successive frequencies.\n\
+octaves is the number of frequencies in the fBm.\n\
+offset raises the terrain from 'sea level'.\n\
+gain scales the values.\n\
+Optional argument noisebasis determines the type of noise used for the turbulence, STDPERLIN by default, see NoiseTypes.";
+
+static char ridged_multi_fractal__doc__[] =
+ "((x,y,z) tuple, H, lacunarity, octaves, offset, gain [noisebasis])\n\n\
+returns Ridged Multifractal value.\n\
+H determines the fractal dimension of the roughest areas.\n\
+lacunarity is the gap between successive frequencies.\n\
+octaves is the number of frequencies in the fBm.\n\
+offset raises the terrain from 'sea level'.\n\
+gain scales the values.\n\
+Optional argument noisebasis determines the type of noise used for the turbulence, STDPERLIN by default, see NoiseTypes.";
+
+static char voronoi__doc__[] =
+ "((x,y,z) tuple, distance_metric, [exponent])\n\n\
+returns a list, containing a list of distances in order of closest feature,\n\
+and a list containing the positions of the four closest features\n\
+Optional arguments:\n\
+distance_metric: see DistanceMetrics, default is DISTANCE\n\
+exponent is only used with MINKOVSKY, default is 2.5.";
+
+static char cell__doc__[] = "((x,y,z) tuple)\n\n\
+returns cellnoise float value.";
+
+static char cell_vector__doc__[] = "((x,y,z) tuple)\n\n\
+returns cellnoise vector/point/color (3-float list).";
+
+static char Noise__doc__[] = "Blender Noise and Turbulence Module\n\n\
+This module can be used to generate noise of various types.\n\
+This can be used for terrain generation, to create textures,\n\
+make animations more 'animated', object deformation, etc.\n\
+As an example, this code segment when scriptlinked to a framechanged event,\n\
+will make the camera sway randomly about, by changing parameters this can\n\
+look like anything from an earthquake to a very nervous or maybe even drunk cameraman...\n\
+(the camera needs an ipo with at least one Loc & Rot key for this to work!):\n\
+\n\
+\tfrom Blender import Get, Scene, Noise\n\
+\n\
+\t####################################################\n\
+\t# This controls jitter speed\n\
+\tsl = 0.025\n\
+\t# This controls the amount of position jitter\n\
+\tsp = 0.1\n\
+\t# This controls the amount of rotation jitter\n\
+\tsr = 0.25\n\
+\t####################################################\n\
+\n\
+\ttime = Get('curtime')\n\
+\tob = Scene.GetCurrent().getCurrentCamera()\n\
+\tps = (sl*time, sl*time, sl*time)\n\
+\t# To add jitter only when the camera moves, use this next line instead\n\
+\t#ps = (sl*ob.LocX, sl*ob.LocY, sl*ob.LocZ)\n\
+\trv = Noise.turbulence_vector(ps, 3, 0, Noise.NoiseTypes.NEWPERLIN)\n\
+\tob.dloc = (sp*rv[0], sp*rv[1], sp*rv[2])\n\
+\tob.drot = (sr*rv[0], sr*rv[1], sr*rv[2])\n\
+\n";
+
+/* Just in case, declarations for a header file */
+/*
+static PyObject *Noise_random(PyObject *self);
+static PyObject *Noise_random_unit_vector(PyObject *self);
+static PyObject *Noise_seed_set(PyObject *self, PyObject *args);
+static PyObject *Noise_noise(PyObject *self, PyObject *args);
+static PyObject *Noise_vector(PyObject *self, PyObject *args);
+static PyObject *Noise_turbulence(PyObject *self, PyObject *args);
+static PyObject *Noise_turbulence_vector(PyObject *self, PyObject *args);
+static PyObject *Noise_fractal(PyObject *self, PyObject *args);
+static PyObject *Noise_multi_fractal(PyObject *self, PyObject *args);
+static PyObject *Noise_vl_vector(PyObject *self, PyObject *args);
+static PyObject *Noise_hetero_terrain(PyObject *self, PyObject *args);
+static PyObject *Noise_hybrid_multi_fractal(PyObject *self, PyObject *args);
+static PyObject *Noise_ridged_multi_fractal(PyObject *self, PyObject *args);
+static PyObject *Noise_voronoi(PyObject *self, PyObject *args);
+static PyObject *Noise_cell(PyObject *self, PyObject *args);
+static PyObject *Noise_cell_vector(PyObject *self, PyObject *args);
+*/
+
+static PyMethodDef NoiseMethods[] = {
+ {"seed_set", (PyCFunction) Noise_seed_set, METH_VARARGS, seed_set__doc__},
+ {"random", (PyCFunction) Noise_random, METH_NOARGS, random__doc__},
+ {"random_unit_vector", (PyCFunction) Noise_random_unit_vector, METH_NOARGS, random_unit_vector__doc__},
+ {"noise", (PyCFunction) Noise_noise, METH_VARARGS, noise__doc__},
+ {"vector", (PyCFunction) Noise_vector, METH_VARARGS, noise_vector__doc__},
+ {"turbulence", (PyCFunction) Noise_turbulence, METH_VARARGS, turbulence__doc__},
+ {"turbulence_vector", (PyCFunction) Noise_turbulence_vector, METH_VARARGS, turbulence_vector__doc__},
+ {"fractal", (PyCFunction) Noise_fractal, METH_VARARGS, fractal__doc__},
+ {"multi_fractal", (PyCFunction) Noise_multi_fractal, METH_VARARGS, multi_fractal__doc__},
+ {"vl_vector", (PyCFunction) Noise_vl_vector, METH_VARARGS, vl_vector__doc__},
+ {"hetero_terrain", (PyCFunction) Noise_hetero_terrain, METH_VARARGS, hetero_terrain__doc__},
+ {"hybrid_multi_fractal", (PyCFunction) Noise_hybrid_multi_fractal, METH_VARARGS, hybrid_multi_fractal__doc__},
+ {"ridged_multi_fractal", (PyCFunction) Noise_ridged_multi_fractal, METH_VARARGS, ridged_multi_fractal__doc__},
+ {"voronoi", (PyCFunction) Noise_voronoi, METH_VARARGS, voronoi__doc__},
+ {"cell", (PyCFunction) Noise_cell, METH_VARARGS, cell__doc__},
+ {"cell_vector", (PyCFunction) Noise_cell_vector, METH_VARARGS, cell_vector__doc__},
+ {NULL, NULL, 0, NULL}
+};
+
+/*----------------------------------------------------------------------*/
+
+static struct PyModuleDef noise_module_def = {
+ PyModuleDef_HEAD_INIT,
+ "noise", /* m_name */
+ Noise__doc__, /* m_doc */
+ 0, /* m_size */
+ NoiseMethods, /* m_methods */
+ 0, /* m_reload */
+ 0, /* m_traverse */
+ 0, /* m_clear */
+ 0, /* m_free */
+};
+
+PyObject *Noise_Init(void)
+{
+ PyObject *submodule = PyModule_Create(&noise_module_def);
+ PyDict_SetItemString(PyImport_GetModuleDict(), noise_module_def.m_name, submodule);
+
+ /* use current time as seed for random number generator by default */
+ setRndSeed(0);
+
+ /* Constant noisetype dictionary */
+ if(submodule) {
+ static PyStructSequence_Field noise_types_fields[] = {
+ {"BLENDER", ""},
+ {"STDPERLIN", ""},
+ {"NEWPERLIN", ""},
+ {"VORONOI_F1", ""},
+ {"VORONOI_F2", ""},
+ {"VORONOI_F3", ""},
+ {"VORONOI_F4", ""},
+ {"VORONOI_F2F1", ""},
+ {"VORONOI_CRACKLE", ""},
+ {"CELLNOISE", ""},
+ {0}
+ };
+
+ static PyStructSequence_Desc noise_types_info_desc = {
+ "noise.types", /* name */
+ "Noise type", /* doc */
+ noise_types_fields, /* fields */
+ (sizeof(noise_types_fields)/sizeof(PyStructSequence_Field)) - 1
+ };
+
+ static PyTypeObject NoiseType;
+
+ PyObject *noise_types;
+
+ int pos = 0;
+
+ PyStructSequence_InitType(&NoiseType, &noise_types_info_desc);
+
+ noise_types = PyStructSequence_New(&NoiseType);
+ if (noise_types == NULL) {
+ return NULL;
+ }
+
+ PyStructSequence_SET_ITEM(noise_types, pos++, PyLong_FromLong(TEX_BLENDER));
+ PyStructSequence_SET_ITEM(noise_types, pos++, PyLong_FromLong(TEX_STDPERLIN));
+ PyStructSequence_SET_ITEM(noise_types, pos++, PyLong_FromLong(TEX_NEWPERLIN));
+ PyStructSequence_SET_ITEM(noise_types, pos++, PyLong_FromLong(TEX_VORONOI_F1));
+ PyStructSequence_SET_ITEM(noise_types, pos++, PyLong_FromLong(TEX_VORONOI_F2));
+ PyStructSequence_SET_ITEM(noise_types, pos++, PyLong_FromLong(TEX_VORONOI_F3));
+ PyStructSequence_SET_ITEM(noise_types, pos++, PyLong_FromLong(TEX_VORONOI_F4));
+ PyStructSequence_SET_ITEM(noise_types, pos++, PyLong_FromLong(TEX_VORONOI_F2F1));
+ PyStructSequence_SET_ITEM(noise_types, pos++, PyLong_FromLong(TEX_VORONOI_CRACKLE));
+ PyStructSequence_SET_ITEM(noise_types, pos++, PyLong_FromLong(TEX_CELLNOISE));
+
+ PyModule_AddObject(submodule, "types", noise_types);
+ }
+
+ if(submodule) {
+ static PyStructSequence_Field distance_metrics_fields[] = {
+ {"DISTANCE", ""},
+ {"DISTANCE_SQUARED", ""},
+ {"MANHATTAN", ""},
+ {"CHEBYCHEV", ""},
+ {"MINKOVSKY_HALF", ""},
+ {"MINKOVSKY_FOUR", ""},
+ {"MINKOVSKY", ""},
+ {0}
+ };
+
+ static PyStructSequence_Desc noise_types_info_desc = {
+ "noise.distance_metrics", /* name */
+ "Distance Metrics for noise module.", /* doc */
+ distance_metrics_fields, /* fields */
+ (sizeof(distance_metrics_fields)/sizeof(PyStructSequence_Field)) - 1
+ };
+
+ static PyTypeObject DistanceMetrics;
+
+ PyObject *distance_metrics;
+
+ int pos = 0;
+
+ PyStructSequence_InitType(&DistanceMetrics, &noise_types_info_desc);
+
+ distance_metrics = PyStructSequence_New(&DistanceMetrics);
+ if (distance_metrics == NULL) {
+ return NULL;
+ }
+
+ PyStructSequence_SET_ITEM(distance_metrics, pos++, PyLong_FromLong(TEX_DISTANCE));
+ PyStructSequence_SET_ITEM(distance_metrics, pos++, PyLong_FromLong(TEX_DISTANCE_SQUARED));
+ PyStructSequence_SET_ITEM(distance_metrics, pos++, PyLong_FromLong(TEX_MANHATTAN));
+ PyStructSequence_SET_ITEM(distance_metrics, pos++, PyLong_FromLong(TEX_CHEBYCHEV));
+ PyStructSequence_SET_ITEM(distance_metrics, pos++, PyLong_FromLong(TEX_MINKOVSKY_HALF));
+ PyStructSequence_SET_ITEM(distance_metrics, pos++, PyLong_FromLong(TEX_MINKOVSKY_FOUR));
+ PyStructSequence_SET_ITEM(distance_metrics, pos++, PyLong_FromLong(TEX_MINKOVSKY));
+
+ PyModule_AddObject(submodule, "distance_metrics", distance_metrics);
+ }
+
+ return submodule;
+}
diff --git a/source/blender/python/intern/Makefile b/source/blender/python/intern/Makefile
index 419092cbe21..6c0b7b4d14e 100644
--- a/source/blender/python/intern/Makefile
+++ b/source/blender/python/intern/Makefile
@@ -15,7 +15,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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
# All rights reserved.
@@ -57,6 +57,7 @@ CPPFLAGS += -I../../imbuf
CPPFLAGS += -I../../blenloader
CPPFLAGS += -I../../windowmanager
CPPFLAGS += -I../../render/extern/include
+CPPFLAGS += -I$(NAN_AUDASPACE)/include
# path to the guarded memory allocator
CPPFLAGS += -I$(NAN_GUARDEDALLOC)/include
diff --git a/source/blender/python/intern/bpy.c b/source/blender/python/intern/bpy.c
index 3f8daec0161..03c1a012575 100644
--- a/source/blender/python/intern/bpy.c
+++ b/source/blender/python/intern/bpy.c
@@ -31,47 +31,89 @@
#include "bpy_app.h"
#include "bpy_props.h"
#include "bpy_operator.h"
-
+
#include "BLI_path_util.h"
+#include "BLI_bpath.h"
/* external util modules */
-#include "../generic/Geometry.h"
+#include "../generic/geometry.h"
#include "../generic/bgl.h"
-#include "../generic/blf.h"
+#include "../generic/blf_api.h"
#include "../generic/IDProp.h"
-static char bpy_home_paths_doc[] =
-".. function:: home_paths(subfolder)\n"
+#include "AUD_PyInit.h"
+
+static char bpy_script_paths_doc[] =
+".. function:: script_paths()\n"
"\n"
-" return 3 paths to blender home directories.\n"
+" Return 2 paths to blender scripts directories.\n"
"\n"
-" :arg subfolder: The name of a subfolder to find within the blenders home directory.\n"
-" :type subfolder: string\n"
-" :return: (system, local, user) strings will be empty when not found.\n"
+" :return: (system, user) strings will be empty when not found.\n"
" :rtype: tuple of strigs\n";
-PyObject *bpy_home_paths(PyObject *self, PyObject *args)
+PyObject *bpy_script_paths(PyObject *self)
{
- PyObject *ret= PyTuple_New(3);
+ PyObject *ret= PyTuple_New(2);
char *path;
- char *subfolder= "";
- if (!PyArg_ParseTuple(args, "|s:blender_homes", &subfolder))
- return NULL;
-
- path= BLI_gethome_folder(subfolder, BLI_GETHOME_SYSTEM);
+ path= BLI_get_folder(BLENDER_USER_SCRIPTS, NULL);
PyTuple_SET_ITEM(ret, 0, PyUnicode_FromString(path?path:""));
-
- path= BLI_gethome_folder(subfolder, BLI_GETHOME_LOCAL);
+ path= BLI_get_folder(BLENDER_SYSTEM_SCRIPTS, NULL);
PyTuple_SET_ITEM(ret, 1, PyUnicode_FromString(path?path:""));
-
- path= BLI_gethome_folder(subfolder, BLI_GETHOME_USER);
- PyTuple_SET_ITEM(ret, 2, PyUnicode_FromString(path?path:""));
return ret;
}
-static PyMethodDef meth_bpy_home_paths[] = {{ "home_paths", (PyCFunction)bpy_home_paths, METH_VARARGS, bpy_home_paths_doc}};
+static char bpy_blend_paths_doc[] =
+".. function:: blend_paths(absolute=False)\n"
+"\n"
+" Returns a list of paths to external files referenced by the loaded .blend file.\n"
+"\n"
+" :arg absolute: When true the paths returned are made absolute.\n"
+" :type absolute: boolean\n"
+" :return: path list.\n"
+" :rtype: list of strigs\n";
+static PyObject *bpy_blend_paths(PyObject * self, PyObject *args, PyObject *kw)
+{
+ struct BPathIterator bpi;
+ PyObject *list = PyList_New(0), *st; /* stupidly big string to be safe */
+ /* be sure there is low chance of the path being too short */
+ char filepath_expanded[1024];
+ char *lib;
+
+ int absolute = 0;
+ static char *kwlist[] = {"absolute", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kw, "|i:blend_paths", kwlist, &absolute))
+ return NULL;
+
+ for(BLI_bpathIterator_init(&bpi, NULL); !BLI_bpathIterator_isDone(&bpi); BLI_bpathIterator_step(&bpi)) {
+ /* build the list */
+ if (absolute) {
+ BLI_bpathIterator_getPathExpanded(&bpi, filepath_expanded);
+ }
+ else {
+ lib = BLI_bpathIterator_getLib(&bpi);
+ if (lib && (strcmp(lib, bpi.base_path))) { /* relative path to the library is NOT the same as our blendfile path, return an absolute path */
+ BLI_bpathIterator_getPathExpanded(&bpi, filepath_expanded);
+ }
+ else {
+ BLI_bpathIterator_getPath(&bpi, filepath_expanded);
+ }
+ }
+ st = PyUnicode_FromString(filepath_expanded);
+
+ PyList_Append(list, st);
+ Py_DECREF(st);
+ }
+
+ BLI_bpathIterator_free(&bpi);
+
+ return list;
+}
+
+static PyMethodDef meth_bpy_script_paths[] = {{ "script_paths", (PyCFunction)bpy_script_paths, METH_NOARGS, bpy_script_paths_doc}};
+static PyMethodDef meth_bpy_blend_paths[] = {{ "blend_paths", (PyCFunction)bpy_blend_paths, METH_VARARGS|METH_KEYWORDS, bpy_blend_paths_doc}};
static void bpy_import_test(char *modname)
{
@@ -91,29 +133,34 @@ static void bpy_import_test(char *modname)
void BPy_init_modules( void )
{
extern BPy_StructRNA *bpy_context_module;
+ PointerRNA ctx_ptr;
PyObject *mod;
/* Needs to be first since this dir is needed for future modules */
- char *modpath= BLI_gethome_folder("scripts/modules", BLI_GETHOME_ALL);
+ char *modpath= BLI_get_folder(BLENDER_SCRIPTS, "modules");
if(modpath) {
+ // printf("bpy: found module path '%s'.\n", modpath);
PyObject *sys_path= PySys_GetObject("path"); /* borrow */
PyObject *py_modpath= PyUnicode_FromString(modpath);
PyList_Insert(sys_path, 0, py_modpath); /* add first */
Py_DECREF(py_modpath);
}
-
+ else {
+ printf("bpy: couldnt find 'scripts/modules', blender probably wont start.\n");
+ }
/* stand alone utility modules not related to blender directly */
Geometry_Init();
Mathutils_Init();
+ Noise_Init();
BGL_Init();
BLF_Init();
IDProp_Init_Types();
-
+ AUD_initPython();
mod = PyModule_New("_bpy");
/* add the module so we can import it */
- PyDict_SetItemString(PySys_GetObject("modules"), "_bpy", mod);
+ PyDict_SetItemString(PyImport_GetModuleDict(), "_bpy", mod);
Py_DECREF(mod);
/* run first, initializes rna types */
@@ -128,13 +175,17 @@ void BPy_init_modules( void )
PyModule_AddObject( mod, "app", BPY_app_struct() );
/* bpy context */
- bpy_context_module= ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
- RNA_pointer_create(NULL, &RNA_Context, BPy_GetContext(), &bpy_context_module->ptr);
- bpy_context_module->freeptr= 0;
+ RNA_pointer_create(NULL, &RNA_Context, BPy_GetContext(), &ctx_ptr);
+ bpy_context_module= (BPy_StructRNA *)pyrna_struct_CreatePyObject(&ctx_ptr);
+ /* odd that this is needed, 1 ref on creation and another for the module
+ * but without we get a crash on exit */
+ Py_INCREF(bpy_context_module);
+
PyModule_AddObject(mod, "context", (PyObject *)bpy_context_module);
/* utility func's that have nowhere else to go */
- PyModule_AddObject(mod, meth_bpy_home_paths->ml_name, (PyObject *)PyCFunction_New(meth_bpy_home_paths, NULL));
+ PyModule_AddObject(mod, meth_bpy_script_paths->ml_name, (PyObject *)PyCFunction_New(meth_bpy_script_paths, NULL));
+ PyModule_AddObject(mod, meth_bpy_blend_paths->ml_name, (PyObject *)PyCFunction_New(meth_bpy_blend_paths, NULL));
/* add our own modules dir, this is a python package */
bpy_import_test("bpy");
diff --git a/source/blender/python/intern/bpy_app.c b/source/blender/python/intern/bpy_app.c
index 15c6ad09e69..78658a611a3 100644
--- a/source/blender/python/intern/bpy_app.c
+++ b/source/blender/python/intern/bpy_app.c
@@ -43,9 +43,9 @@ static PyTypeObject BlenderAppType;
static PyStructSequence_Field app_info_fields[] = {
{"version", "The Blender version as a tuple of 3 numbers. eg. (2, 50, 11)"},
{"version_string", "The Blender version formatted as a string"},
- {"home", "The blender home directory, normally matching $HOME"},
{"binary_path", "The location of blenders executable, useful for utilities that spawn new instances"},
{"debug", "Boolean, set when blender is running in debug mode (started with -d)"},
+ {"background", "Boolean, True when blender is running without a user interface (started with -b)"},
/* buildinfo */
{"build_date", "The date this blender instance was built"},
@@ -60,7 +60,7 @@ static PyStructSequence_Desc app_info_desc = {
"bpy.app", /* name */
"This module contains application values that remain unchanged during runtime.", /* doc */
app_info_fields, /* fields */
- 10
+ (sizeof(app_info_fields)/sizeof(PyStructSequence_Field)) - 1
};
static PyObject *make_app_info(void)
@@ -84,9 +84,9 @@ static PyObject *make_app_info(void)
SetObjItem(Py_BuildValue("(iii)", BLENDER_VERSION/100, BLENDER_VERSION%100, BLENDER_SUBVERSION));
SetObjItem(PyUnicode_FromFormat("%d.%02d (sub %d)", BLENDER_VERSION/100, BLENDER_VERSION%100, BLENDER_SUBVERSION));
- SetStrItem(BLI_gethome());
SetStrItem(bprogname);
SetObjItem(PyBool_FromLong(G.f & G_DEBUG));
+ SetObjItem(PyBool_FromLong(G.background));
/* build info */
#ifdef BUILD_DATE
diff --git a/source/blender/python/intern/bpy_driver.c b/source/blender/python/intern/bpy_driver.c
index 00ea556792e..e5719a84fdd 100644
--- a/source/blender/python/intern/bpy_driver.c
+++ b/source/blender/python/intern/bpy_driver.c
@@ -24,6 +24,8 @@
/* ****************************************** */
/* Drivers - PyExpression Evaluation */
+#include <Python.h>
+
#include "DNA_anim_types.h"
#include "BLI_listbase.h"
@@ -32,8 +34,6 @@
#include "BKE_fcurve.h"
#include "BKE_global.h"
-#include <Python.h>
-
/* for pydrivers (drivers using one-line Python expressions to express relationships between targets) */
PyObject *bpy_pydriver_Dict = NULL;
@@ -59,10 +59,6 @@ static int bpy_pydriver_create_dict(void)
mod = PyImport_ImportModule("math");
if (mod) {
PyDict_Merge(d, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
-
- /* Only keep for backwards compat! - just import all math into root, they are standard */
- PyDict_SetItemString(d, "math", mod);
- PyDict_SetItemString(d, "m", mod);
Py_DECREF(mod);
}
@@ -103,13 +99,17 @@ static int bpy_pydriver_create_dict(void)
}
/* Update function, it gets rid of pydrivers global dictionary, forcing
- * BPY_pydriver_eval to recreate it. This function is used to force
+ * BPY_eval_driver to recreate it. This function is used to force
* reloading the Blender text module "pydrivers.py", if available, so
* updates in it reach pydriver evaluation.
*/
void BPY_pydriver_update(void)
{
- PyGILState_STATE gilstate = PyGILState_Ensure();
+ PyGILState_STATE gilstate;
+ int use_gil= 1; // (PyThreadState_Get()==NULL);
+
+ if(use_gil)
+ gilstate = PyGILState_Ensure();
if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
PyDict_Clear(bpy_pydriver_Dict);
@@ -117,7 +117,8 @@ void BPY_pydriver_update(void)
bpy_pydriver_Dict = NULL;
}
- PyGILState_Release(gilstate);
+ if(use_gil)
+ PyGILState_Release(gilstate);
return;
}
@@ -143,14 +144,19 @@ static float pydriver_error(ChannelDriver *driver)
/* This evals py driver expressions, 'expr' is a Python expression that
* should evaluate to a float number, which is returned.
+ *
+ * note: PyGILState_Ensure() isnt always called because python can call the
+ * bake operator which intern starts a thread which calls scene update which
+ * does a driver update. to avoid a deadlock check PyThreadState_Get() if PyGILState_Ensure() is needed.
*/
-float BPY_pydriver_eval (ChannelDriver *driver)
+float BPY_eval_driver (ChannelDriver *driver)
{
PyObject *driver_vars=NULL;
PyObject *retval= NULL;
PyObject *expr_vars; /* speed up by pre-hashing string & avoids re-converting unicode strings for every execution */
PyObject *expr_code;
PyGILState_STATE gilstate;
+ int use_gil;
DriverVar *dvar;
double result = 0.0; /* default return */
@@ -168,13 +174,17 @@ float BPY_pydriver_eval (ChannelDriver *driver)
return 0.0f;
}
- gilstate = PyGILState_Ensure();
+ use_gil= 1; //(PyThreadState_Get()==NULL);
+
+ if(use_gil)
+ gilstate = PyGILState_Ensure();
/* init global dictionary for py-driver evaluation settings */
if (!bpy_pydriver_Dict) {
if (bpy_pydriver_create_dict() != 0) {
fprintf(stderr, "Pydriver error: couldn't create Python dictionary");
- PyGILState_Release(gilstate);
+ if(use_gil)
+ PyGILState_Release(gilstate);
return 0.0f;
}
}
@@ -232,11 +242,11 @@ float BPY_pydriver_eval (ChannelDriver *driver)
/* this target failed - bad name */
if (targets_ok) {
/* first one - print some extra info for easier identification */
- fprintf(stderr, "\nBPY_pydriver_eval() - Error while evaluating PyDriver:\n");
+ fprintf(stderr, "\nBPY_eval_driver() - Error while evaluating PyDriver:\n");
targets_ok= 0;
}
- fprintf(stderr, "\tBPY_pydriver_eval() - couldn't add variable '%s' to namespace\n", dvar->name);
+ fprintf(stderr, "\tBPY_eval_driver() - couldn't add variable '%s' to namespace\n", dvar->name);
// BPy_errors_to_report(NULL); // TODO - reports
PyErr_Print();
PyErr_Clear();
@@ -269,13 +279,14 @@ float BPY_pydriver_eval (ChannelDriver *driver)
Py_DECREF(retval);
}
- PyGILState_Release(gilstate);
+ if(use_gil)
+ PyGILState_Release(gilstate);
if(finite(result)) {
return (float)result;
}
else {
- fprintf(stderr, "\tBPY_pydriver_eval() - driver '%s' evaluates to '%f'\n", dvar->name, result);
+ fprintf(stderr, "\tBPY_eval_driver() - driver '%s' evaluates to '%f'\n", dvar->name, result);
return 0.0f;
}
}
diff --git a/source/blender/python/intern/bpy_interface.c b/source/blender/python/intern/bpy_interface.c
index 285dbb78874..af2b5b41961 100644
--- a/source/blender/python/intern/bpy_interface.c
+++ b/source/blender/python/intern/bpy_interface.c
@@ -44,6 +44,7 @@
#include "BKE_context.h"
#include "BKE_text.h"
+#include "BKE_font.h" /* only for utf8towchar */
#include "BKE_main.h"
#include "BKE_global.h" /* only for script checking */
@@ -145,39 +146,10 @@ void BPY_update_modules( void )
bpy_context_module->ptr.data= (void *)BPy_GetContext();
}
-/*****************************************************************************
-* Description: This function creates a new Python dictionary object.
-*****************************************************************************/
-static PyObject *CreateGlobalDictionary( bContext *C, const char *filename )
-{
- PyObject *mod;
- PyObject *item;
- PyObject *dict = PyDict_New( );
- PyDict_SetItemString( dict, "__builtins__", PyEval_GetBuiltins( ) );
-
- item = PyUnicode_FromString( "__main__" );
- PyDict_SetItemString( dict, "__name__", item );
- Py_DECREF(item);
-
- /* __file__ only for nice UI'ness */
- if(filename) {
- PyObject *item = PyUnicode_FromString( filename );
- PyDict_SetItemString( dict, "__file__", item );
- Py_DECREF(item);
- }
-
- /* add bpy to global namespace */
- mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
- PyDict_SetItemString( dict, "bpy", mod );
- Py_DECREF(mod);
-
- return dict;
-}
-
/* must be called before Py_Initialize */
void BPY_start_python_path(void)
{
- char *py_path_bundle= BLI_gethome_folder("python", BLI_GETHOME_ALL);
+ char *py_path_bundle= BLI_get_folder(BLENDER_PYTHON, NULL);
if(py_path_bundle==NULL)
return;
@@ -210,10 +182,15 @@ void BPY_start_python_path(void)
#endif
{
- static wchar_t py_path_bundle_wchar[FILE_MAXDIR];
+ static wchar_t py_path_bundle_wchar[FILE_MAX];
+
+ /* cant use this, on linux gives bug: #23018, TODO: try LANG="en_US.UTF-8" /usr/bin/blender, suggested 22008 */
+ /* mbstowcs(py_path_bundle_wchar, py_path_bundle, FILE_MAXDIR); */
+
+ utf8towchar(py_path_bundle_wchar, py_path_bundle);
- mbstowcs(py_path_bundle_wchar, py_path_bundle, FILE_MAXDIR);
Py_SetPythonHome(py_path_bundle_wchar);
+ // printf("found python (wchar_t) '%ls'\n", py_path_bundle_wchar);
}
}
@@ -229,6 +206,11 @@ void BPY_start_python( int argc, char **argv )
{
PyThreadState *py_tstate = NULL;
+ /* not essential but nice to set our name */
+ static wchar_t bprogname_wchar[FILE_MAXDIR+FILE_MAXFILE]; /* python holds a reference */
+ utf8towchar(bprogname_wchar, bprogname);
+ Py_SetProgramName(bprogname_wchar);
+
BPY_start_python_path(); /* allow to use our own included python */
Py_Initialize( );
@@ -325,18 +307,19 @@ int BPY_run_python_script( bContext *C, const char *fn, struct Text *text, struc
if (fn==NULL && text==NULL) {
return 0;
}
-
+
bpy_context_set(C, &gilstate);
-
- py_dict = CreateGlobalDictionary(C, text?text->id.name+2:fn);
if (text) {
+ char fn_dummy[FILE_MAXDIR];
+ bpy_text_filename_get(fn_dummy, text);
+ py_dict = bpy_namespace_dict_new(fn_dummy);
if( !text->compiled ) { /* if it wasn't already compiled, do it now */
char *buf = txt_to_buf( text );
text->compiled =
- Py_CompileString( buf, text->id.name+2, Py_file_input );
+ Py_CompileString( buf, fn_dummy, Py_file_input );
MEM_freeN( buf );
@@ -347,8 +330,12 @@ int BPY_run_python_script( bContext *C, const char *fn, struct Text *text, struc
if(text->compiled)
py_result = PyEval_EvalCode( text->compiled, py_dict, py_dict );
- } else {
- FILE *fp= fopen(fn, "r");
+ }
+ else {
+ FILE *fp= fopen(fn, "r");
+
+ py_dict = bpy_namespace_dict_new(fn);
+
if(fp) {
#ifdef _WIN32
/* Previously we used PyRun_File to run directly the code on a FILE
@@ -382,7 +369,7 @@ int BPY_run_python_script( bContext *C, const char *fn, struct Text *text, struc
Py_DECREF( py_result );
}
- Py_DECREF(py_dict);
+ PyDict_SetItemString(PyThreadState_GET()->interp->modules, "__main__", Py_None);
bpy_context_clear(C, &gilstate);
@@ -491,7 +478,7 @@ int BPY_run_python_script_space(const char *modulename, const char *func)
gilstate = PyGILState_Ensure();
- py_dict = CreateGlobalDictionary(C);
+ py_dict = bpy_namespace_dict_new("<dummy>");
PyObject *module = PyImport_ImportModule(scpt->script.filename);
if (module==NULL) {
@@ -520,7 +507,7 @@ int BPY_run_python_script_space(const char *modulename, const char *func)
Py_XDECREF(module);
- Py_DECREF(py_dict);
+ PyDict_SetItemString(PyThreadState_GET()->interp->modules, "__main__", Py_None);
PyGILState_Release(gilstate);
return 1;
@@ -528,10 +515,10 @@ int BPY_run_python_script_space(const char *modulename, const char *func)
#endif
-int BPY_button_eval(bContext *C, char *expr, double *value)
+int BPY_eval_button(bContext *C, const char *expr, double *value)
{
PyGILState_STATE gilstate;
- PyObject *dict, *mod, *retval;
+ PyObject *py_dict, *mod, *retval;
int error_ret = 0;
if (!value || !expr) return -1;
@@ -543,11 +530,11 @@ int BPY_button_eval(bContext *C, char *expr, double *value)
bpy_context_set(C, &gilstate);
- dict= CreateGlobalDictionary(C, NULL);
+ py_dict= bpy_namespace_dict_new("<blender button>");
mod = PyImport_ImportModule("math");
if (mod) {
- PyDict_Merge(dict, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
+ PyDict_Merge(py_dict, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
Py_DECREF(mod);
}
else { /* highly unlikely but possibly */
@@ -555,7 +542,7 @@ int BPY_button_eval(bContext *C, char *expr, double *value)
PyErr_Clear();
}
- retval = PyRun_String(expr, Py_eval_input, dict, dict);
+ retval = PyRun_String(expr, Py_eval_input, py_dict, py_dict);
if (retval == NULL) {
error_ret= -1;
@@ -592,13 +579,49 @@ int BPY_button_eval(bContext *C, char *expr, double *value)
if(error_ret) {
BPy_errors_to_report(CTX_wm_reports(C));
}
+
+ PyDict_SetItemString(PyThreadState_GET()->interp->modules, "__main__", Py_None);
- Py_DECREF(dict);
bpy_context_clear(C, &gilstate);
return error_ret;
}
+int BPY_eval_string(bContext *C, const char *expr)
+{
+ PyGILState_STATE gilstate;
+ PyObject *py_dict, *retval;
+ int error_ret = 0;
+
+ if (!expr) return -1;
+
+ if(expr[0]=='\0') {
+ return error_ret;
+ }
+
+ bpy_context_set(C, &gilstate);
+
+ py_dict= bpy_namespace_dict_new("<blender string>");
+
+ retval = PyRun_String(expr, Py_eval_input, py_dict, py_dict);
+
+ if (retval == NULL) {
+ error_ret= -1;
+
+ BPy_errors_to_report(CTX_wm_reports(C));
+ }
+ else {
+ Py_DECREF(retval);
+ }
+
+ PyDict_SetItemString(PyThreadState_GET()->interp->modules, "__main__", Py_None);
+
+ bpy_context_clear(C, &gilstate);
+
+ return error_ret;
+}
+
+
void BPY_load_user_modules(bContext *C)
{
PyGILState_STATE gilstate;
diff --git a/source/blender/python/intern/bpy_operator.c b/source/blender/python/intern/bpy_operator.c
index 0e54f158ac4..c6c34fbcaf5 100644
--- a/source/blender/python/intern/bpy_operator.c
+++ b/source/blender/python/intern/bpy_operator.c
@@ -63,7 +63,7 @@ static PyObject *pyop_call( PyObject * self, PyObject * args)
if (!PyArg_ParseTuple(args, "sO|O!s:_bpy.ops.call", &opname, &context_dict, &PyDict_Type, &kw, &context_str))
return NULL;
- ot= WM_operatortype_exists(opname);
+ ot= WM_operatortype_find(opname, TRUE);
if (ot == NULL) {
PyErr_Format( PyExc_SystemError, "Calling operator \"bpy.ops.%s\" error, could not be found", opname);
@@ -259,7 +259,7 @@ PyObject *BPY_operator_module( void )
static PyMethodDef pyop_macro_def_meth ={"macro_define", (PyCFunction) PYOP_wrap_macro_define, METH_VARARGS, NULL};
PyObject *submodule = PyModule_New("_bpy.ops");
- PyDict_SetItemString(PySys_GetObject("modules"), "_bpy.ops", submodule);
+ PyDict_SetItemString(PyImport_GetModuleDict(), "_bpy.ops", submodule);
PyModule_AddObject( submodule, "call", PyCFunction_New(&pyop_call_meth, NULL) );
PyModule_AddObject( submodule, "as_string",PyCFunction_New(&pyop_as_string_meth,NULL) );
diff --git a/source/blender/python/intern/bpy_operator_wrap.c b/source/blender/python/intern/bpy_operator_wrap.c
index 0c1eafb4948..6d16896fb16 100644
--- a/source/blender/python/intern/bpy_operator_wrap.c
+++ b/source/blender/python/intern/bpy_operator_wrap.c
@@ -34,22 +34,15 @@
static void operator_properties_init(wmOperatorType *ot)
{
PyObject *py_class = ot->ext.data;
- PyObject *item= ((PyTypeObject*)py_class)->tp_dict; /* getattr(..., "__dict__") returns a proxy */
-
RNA_struct_blender_type_set(ot->ext.srna, ot);
- if(item) {
- /* only call this so pyrna_deferred_register_props gives a useful error
- * WM_operatortype_append_ptr will call RNA_def_struct_identifier
- * later */
- RNA_def_struct_identifier(ot->srna, ot->idname);
+ /* only call this so pyrna_deferred_register_class gives a useful error
+ * WM_operatortype_append_ptr will call RNA_def_struct_identifier
+ * later */
+ RNA_def_struct_identifier(ot->srna, ot->idname);
- if(pyrna_deferred_register_props(ot->srna, item) != 0) {
- PyErr_Print(); /* failed to register operator props */
- PyErr_Clear();
- }
- }
- else {
+ if(pyrna_deferred_register_class(ot->srna, py_class) != 0) {
+ PyErr_Print(); /* failed to register operator props */
PyErr_Clear();
}
}
@@ -105,7 +98,7 @@ PyObject *PYOP_wrap_macro_define(PyObject *self, PyObject *args)
if (!PyArg_ParseTuple(args, "Os:_bpy.ops.macro_define", &macro, &opname))
return NULL;
- if (WM_operatortype_exists(opname) == NULL) {
+ if (WM_operatortype_find(opname, TRUE) == NULL) {
PyErr_Format(PyExc_ValueError, "Macro Define: '%s' is not a valid operator id", opname);
return NULL;
}
@@ -114,7 +107,7 @@ PyObject *PYOP_wrap_macro_define(PyObject *self, PyObject *args)
srna= srna_from_self(macro, "Macro Define:");
macroname = RNA_struct_identifier(srna);
- ot = WM_operatortype_exists(macroname);
+ ot = WM_operatortype_find(macroname, TRUE);
if (!ot) {
PyErr_Format(PyExc_ValueError, "Macro Define: '%s' is not a valid macro or hasn't been registered yet", macroname);
diff --git a/source/blender/python/intern/bpy_props.c b/source/blender/python/intern/bpy_props.c
index 85935c05cb1..9afe638908c 100644
--- a/source/blender/python/intern/bpy_props.c
+++ b/source/blender/python/intern/bpy_props.c
@@ -86,17 +86,19 @@ static PyObject *bpy_prop_deferred_return(void *func, PyObject *kw)
return ret;
}
+#if 0
static int bpy_struct_id_used(StructRNA *srna, char *identifier)
{
PointerRNA ptr;
RNA_pointer_create(NULL, srna, NULL, &ptr);
return (RNA_struct_find_property(&ptr, identifier) != NULL);
}
+#endif
/* Function that sets RNA, NOTE - self is NULL when called from python, but being abused from C so we can pass the srna allong
* This isnt incorrect since its a python object - but be careful */
-static char BPy_BoolProperty_doc[] =
+char BPy_BoolProperty_doc[] =
".. function:: BoolProperty(name=\"\", description=\"\", default=False, options={'ANIMATABLE'}, subtype='NONE')\n"
"\n"
" Returns a new boolean property definition.\n"
@@ -132,10 +134,9 @@ PyObject *BPy_BoolProperty(PyObject *self, PyObject *args, PyObject *kw)
if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssiO!s:BoolProperty", (char **)kwlist, &id, &name, &description, &def, &PySet_Type, &pyopts, &pysubtype))
return NULL;
- if(bpy_struct_id_used(srna, id)) {
- // PyErr_Format(PyExc_TypeError, "BoolProperty(): '%s' already defined.", id);
- // return NULL;
- Py_RETURN_NONE;
+ if(RNA_def_property_free_identifier(srna, id) == -1) {
+ PyErr_Format(PyExc_TypeError, "BoolProperty(): '%s' is defined as a non-dynamic type.", id);
+ return NULL;
}
if(pyopts && pyrna_set_to_enum_bitfield(property_flag_items, pyopts, &opts, "BoolProperty(options={...}):"))
@@ -163,7 +164,7 @@ PyObject *BPy_BoolProperty(PyObject *self, PyObject *args, PyObject *kw)
}
}
-static char BPy_BoolVectorProperty_doc[] =
+char BPy_BoolVectorProperty_doc[] =
".. function:: BoolVectorProperty(name=\"\", description=\"\", default=(False, False, False), options={'ANIMATABLE'}, subtype='NONE', size=3)\n"
"\n"
" Returns a new vector boolean property definition.\n"
@@ -200,10 +201,9 @@ PyObject *BPy_BoolVectorProperty(PyObject *self, PyObject *args, PyObject *kw)
if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssOO!si:BoolVectorProperty", (char **)kwlist, &id, &name, &description, &pydef, &PySet_Type, &pyopts, &pysubtype, &size))
return NULL;
- if(bpy_struct_id_used(srna, id)) {
- // PyErr_Format(PyExc_TypeError, "BoolVectorProperty(): '%s' already defined.", id);
- // return NULL;
- Py_RETURN_NONE;
+ if(RNA_def_property_free_identifier(srna, id) == -1) {
+ PyErr_Format(PyExc_TypeError, "BoolVectorProperty(): '%s' is defined as a non-dynamic type.", id);
+ return NULL;
}
if(pyopts && pyrna_set_to_enum_bitfield(property_flag_items, pyopts, &opts, "BoolVectorProperty(options={...}):"))
@@ -240,7 +240,7 @@ PyObject *BPy_BoolVectorProperty(PyObject *self, PyObject *args, PyObject *kw)
}
}
-static char BPy_IntProperty_doc[] =
+char BPy_IntProperty_doc[] =
".. function:: IntProperty(name=\"\", description=\"\", default=0, min=-sys.maxint, max=sys.maxint, soft_min=-sys.maxint, soft_max=sys.maxint, step=1, options={'ANIMATABLE'}, subtype='NONE')\n"
"\n"
" Returns a new int property definition.\n"
@@ -275,10 +275,9 @@ PyObject *BPy_IntProperty(PyObject *self, PyObject *args, PyObject *kw)
if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssiiiiiiO!s:IntProperty", (char **)kwlist, &id, &name, &description, &def, &min, &max, &soft_min, &soft_max, &step, &PySet_Type, &pyopts, &pysubtype))
return NULL;
- if(bpy_struct_id_used(srna, id)) {
- // PyErr_Format(PyExc_TypeError, "IntProperty(): '%s' already defined.", id);
- // return NULL;
- Py_RETURN_NONE;
+ if(RNA_def_property_free_identifier(srna, id) == -1) {
+ PyErr_Format(PyExc_TypeError, "IntProperty(): '%s' is defined as a non-dynamic type.", id);
+ return NULL;
}
if(pyopts && pyrna_set_to_enum_bitfield(property_flag_items, pyopts, &opts, "IntProperty(options={...}):"))
@@ -307,7 +306,7 @@ PyObject *BPy_IntProperty(PyObject *self, PyObject *args, PyObject *kw)
}
}
-static char BPy_IntVectorProperty_doc[] =
+char BPy_IntVectorProperty_doc[] =
".. function:: IntVectorProperty(name=\"\", description=\"\", default=(0, 0, 0), min=-sys.maxint, max=sys.maxint, soft_min=-sys.maxint, soft_max=sys.maxint, options={'ANIMATABLE'}, subtype='NONE', size=3)\n"
"\n"
" Returns a new vector int property definition.\n"
@@ -344,10 +343,9 @@ PyObject *BPy_IntVectorProperty(PyObject *self, PyObject *args, PyObject *kw)
if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssOiiiiO!si:IntVectorProperty", (char **)kwlist, &id, &name, &description, &pydef, &min, &max, &soft_min, &soft_max, &PySet_Type, &pyopts, &pysubtype, &size))
return NULL;
- if(bpy_struct_id_used(srna, id)) {
- // PyErr_Format(PyExc_TypeError, "IntVectorProperty(): '%s' already defined.", id);
- // return NULL;
- Py_RETURN_NONE;
+ if(RNA_def_property_free_identifier(srna, id) == -1) {
+ PyErr_Format(PyExc_TypeError, "IntVectorProperty(): '%s' is defined as a non-dynamic type.", id);
+ return NULL;
}
if(pyopts && pyrna_set_to_enum_bitfield(property_flag_items, pyopts, &opts, "IntVectorProperty(options={...}):"))
@@ -386,7 +384,7 @@ PyObject *BPy_IntVectorProperty(PyObject *self, PyObject *args, PyObject *kw)
}
-static char BPy_FloatProperty_doc[] =
+char BPy_FloatProperty_doc[] =
".. function:: FloatProperty(name=\"\", description=\"\", default=0.0, min=sys.float_info.min, max=sys.float_info.max, soft_min=sys.float_info.min, soft_max=sys.float_info.max, step=3, precision=2, options={'ANIMATABLE'}, subtype='NONE', unit='NONE')\n"
"\n"
" Returns a new float property definition.\n"
@@ -426,10 +424,9 @@ PyObject *BPy_FloatProperty(PyObject *self, PyObject *args, PyObject *kw)
if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssffffffiO!ss:FloatProperty", (char **)kwlist, &id, &name, &description, &def, &min, &max, &soft_min, &soft_max, &step, &precision, &PySet_Type, &pyopts, &pysubtype, &pyunit))
return NULL;
- if(bpy_struct_id_used(srna, id)) {
- // PyErr_Format(PyExc_TypeError, "FloatProperty(): '%s' already defined.", id);
- // return NULL;
- Py_RETURN_NONE;
+ if(RNA_def_property_free_identifier(srna, id) == -1) {
+ PyErr_Format(PyExc_TypeError, "FloatProperty(): '%s' is defined as a non-dynamic type.", id);
+ return NULL;
}
if(pyopts && pyrna_set_to_enum_bitfield(property_flag_items, pyopts, &opts, "FloatProperty(options={...}):"))
@@ -463,7 +460,7 @@ PyObject *BPy_FloatProperty(PyObject *self, PyObject *args, PyObject *kw)
}
}
-static char BPy_FloatVectorProperty_doc[] =
+char BPy_FloatVectorProperty_doc[] =
".. function:: FloatVectorProperty(name=\"\", description=\"\", default=(0.0, 0.0, 0.0), min=sys.float_info.min, max=sys.float_info.max, soft_min=sys.float_info.min, soft_max=sys.float_info.max, step=3, precision=2, options={'ANIMATABLE'}, subtype='NONE', size=3)\n"
"\n"
" Returns a new vector float property definition.\n"
@@ -500,10 +497,9 @@ PyObject *BPy_FloatVectorProperty(PyObject *self, PyObject *args, PyObject *kw)
if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssOfffffiO!si:FloatVectorProperty", (char **)kwlist, &id, &name, &description, &pydef, &min, &max, &soft_min, &soft_max, &step, &precision, &PySet_Type, &pyopts, &pysubtype, &size))
return NULL;
- if(bpy_struct_id_used(srna, id)) {
- // PyErr_Format(PyExc_TypeError, "FloatVectorProperty(): '%s' already defined.", id);
- // return NULL;
- Py_RETURN_NONE;
+ if(RNA_def_property_free_identifier(srna, id) == -1) {
+ PyErr_Format(PyExc_TypeError, "FloatVectorProperty(): '%s' is defined as a non-dynamic type.", id);
+ return NULL;
}
if(pyopts && pyrna_set_to_enum_bitfield(property_flag_items, pyopts, &opts, "FloatVectorProperty(options={...}):"))
@@ -541,7 +537,7 @@ PyObject *BPy_FloatVectorProperty(PyObject *self, PyObject *args, PyObject *kw)
}
}
-static char BPy_StringProperty_doc[] =
+char BPy_StringProperty_doc[] =
".. function:: StringProperty(name=\"\", description=\"\", default=\"\", maxlen=0, options={'ANIMATABLE'}, subtype='NONE')\n"
"\n"
" Returns a new string property definition.\n"
@@ -576,10 +572,9 @@ PyObject *BPy_StringProperty(PyObject *self, PyObject *args, PyObject *kw)
if (!PyArg_ParseTupleAndKeywords(args, kw, "s|sssiO!s:StringProperty", (char **)kwlist, &id, &name, &description, &def, &maxlen, &PySet_Type, &pyopts, &pysubtype))
return NULL;
- if(bpy_struct_id_used(srna, id)) {
- // PyErr_Format(PyExc_TypeError, "StringProperty(): '%s' already defined.", id);
- // return NULL;
- Py_RETURN_NONE;
+ if(RNA_def_property_free_identifier(srna, id) == -1) {
+ PyErr_Format(PyExc_TypeError, "StringProperty(): '%s' is defined as a non-dynamic type.", id);
+ return NULL;
}
if(pyopts && pyrna_set_to_enum_bitfield(property_flag_items, pyopts, &opts, "StringProperty(options={...}):"))
@@ -591,7 +586,7 @@ PyObject *BPy_StringProperty(PyObject *self, PyObject *args, PyObject *kw)
}
prop= RNA_def_property(srna, id, PROP_STRING, subtype);
- if(maxlen != 0) RNA_def_property_string_maxlength(prop, maxlen);
+ if(maxlen != 0) RNA_def_property_string_maxlength(prop, maxlen + 1); /* +1 since it includes null terminator */
if(def) RNA_def_property_string_default(prop, def);
RNA_def_property_ui_text(prop, name, description);
@@ -653,7 +648,7 @@ static EnumPropertyItem *enum_items_from_py(PyObject *value, const char *def, in
return items;
}
-static char BPy_EnumProperty_doc[] =
+char BPy_EnumProperty_doc[] =
".. function:: EnumProperty(items, name=\"\", description=\"\", default=\"\", options={'ANIMATABLE'})\n"
"\n"
" Returns a new enumerator property definition.\n"
@@ -688,10 +683,9 @@ PyObject *BPy_EnumProperty(PyObject *self, PyObject *args, PyObject *kw)
if (!PyArg_ParseTupleAndKeywords(args, kw, "sO|sssO!:EnumProperty", (char **)kwlist, &id, &items, &name, &description, &def, &PySet_Type, &pyopts))
return NULL;
- if(bpy_struct_id_used(srna, id)) {
- // PyErr_Format(PyExc_TypeError, "EnumProperty(): '%s' already defined.", id);
- // return NULL;
- Py_RETURN_NONE;
+ if(RNA_def_property_free_identifier(srna, id) == -1) {
+ PyErr_Format(PyExc_TypeError, "EnumProperty(): '%s' is defined as a non-dynamic type.", id);
+ return NULL;
}
if(pyopts && pyrna_set_to_enum_bitfield(property_flag_items, pyopts, &opts, "EnumProperty(options={...}):"))
@@ -738,7 +732,7 @@ static StructRNA *pointer_type_from_py(PyObject *value, const char *error_prefix
return srna;
}
-static char BPy_PointerProperty_doc[] =
+char BPy_PointerProperty_doc[] =
".. function:: PointerProperty(items, type=\"\", description=\"\", default=\"\", options={'ANIMATABLE'})\n"
"\n"
" Returns a new pointer property definition.\n"
@@ -772,10 +766,9 @@ PyObject *BPy_PointerProperty(PyObject *self, PyObject *args, PyObject *kw)
if (!PyArg_ParseTupleAndKeywords(args, kw, "sO|ssO!:PointerProperty", (char **)kwlist, &id, &type, &name, &description, &PySet_Type, &pyopts))
return NULL;
- if(bpy_struct_id_used(srna, id)) {
- // PyErr_Format(PyExc_TypeError, "PointerProperty(): '%s' already defined.", id);
- // return NULL;
- Py_RETURN_NONE;
+ if(RNA_def_property_free_identifier(srna, id) == -1) {
+ PyErr_Format(PyExc_TypeError, "PointerProperty(): '%s' is defined as a non-dynamic type.", id);
+ return NULL;
}
if(pyopts && pyrna_set_to_enum_bitfield(property_flag_items, pyopts, &opts, "PointerProperty(options={...}):"))
@@ -799,7 +792,7 @@ PyObject *BPy_PointerProperty(PyObject *self, PyObject *args, PyObject *kw)
return NULL;
}
-static char BPy_CollectionProperty_doc[] =
+char BPy_CollectionProperty_doc[] =
".. function:: CollectionProperty(items, type=\"\", description=\"\", default=\"\", options={'ANIMATABLE'})\n"
"\n"
" Returns a new collection property definition.\n"
@@ -833,10 +826,9 @@ PyObject *BPy_CollectionProperty(PyObject *self, PyObject *args, PyObject *kw)
if (!PyArg_ParseTupleAndKeywords(args, kw, "sO|ssO!:CollectionProperty", (char **)kwlist, &id, &type, &name, &description, &PySet_Type, &pyopts))
return NULL;
- if(bpy_struct_id_used(srna, id)) {
- // PyErr_Format(PyExc_TypeError, "CollectionProperty(): '%s' already defined.", id);
- // return NULL;
- Py_RETURN_NONE;
+ if(RNA_def_property_free_identifier(srna, id) == -1) {
+ PyErr_Format(PyExc_TypeError, "CollectionProperty(): '%s' is defined as a non-dynamic type.", id);
+ return NULL;
}
if(pyopts && pyrna_set_to_enum_bitfield(property_flag_items, pyopts, &opts, "CollectionProperty(options={...}):"))
@@ -860,6 +852,42 @@ PyObject *BPy_CollectionProperty(PyObject *self, PyObject *args, PyObject *kw)
return NULL;
}
+char BPy_RemoveProperty_doc[] =
+".. function:: RemoveProperty(attr)\n"
+"\n"
+" Removes a dynamically defined property.\n"
+"\n"
+" :arg attr: Property name.\n"
+" :type attr: string";
+PyObject *BPy_RemoveProperty(PyObject *self, PyObject *args, PyObject *kw)
+{
+ StructRNA *srna;
+
+ srna= srna_from_self(self, "RemoveProperty(...):");
+ if(srna==NULL && PyErr_Occurred()) {
+ return NULL; /* self's type was compatible but error getting the srna */
+ }
+ else if(srna==NULL) {
+ PyErr_SetString(PyExc_TypeError, "RemoveProperty(): struct rna not available for this type.");
+ return NULL;
+ }
+ else {
+ static const char *kwlist[] = {"attr", NULL};
+
+ char *id=NULL;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kw, "s:RemoveProperty", (char **)kwlist, &id))
+ return NULL;
+
+ if(RNA_def_property_free_identifier(srna, id) != 1) {
+ PyErr_Format(PyExc_TypeError, "RemoveProperty(): '%s' not a defined dynamic property.", id);
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
+ }
+}
+
static struct PyMethodDef props_methods[] = {
{"BoolProperty", (PyCFunction)BPy_BoolProperty, METH_VARARGS|METH_KEYWORDS, BPy_BoolProperty_doc},
{"BoolVectorProperty", (PyCFunction)BPy_BoolVectorProperty, METH_VARARGS|METH_KEYWORDS, BPy_BoolVectorProperty_doc},
@@ -871,6 +899,9 @@ static struct PyMethodDef props_methods[] = {
{"EnumProperty", (PyCFunction)BPy_EnumProperty, METH_VARARGS|METH_KEYWORDS, BPy_EnumProperty_doc},
{"PointerProperty", (PyCFunction)BPy_PointerProperty, METH_VARARGS|METH_KEYWORDS, BPy_PointerProperty_doc},
{"CollectionProperty", (PyCFunction)BPy_CollectionProperty, METH_VARARGS|METH_KEYWORDS, BPy_CollectionProperty_doc},
+
+ /* only useful as a bpy_struct method */
+ /* {"RemoveProperty", (PyCFunction)BPy_RemoveProperty, METH_VARARGS|METH_KEYWORDS, BPy_RemoveProperty_doc}, */
{NULL, NULL, 0, NULL}
};
@@ -888,7 +919,7 @@ PyObject *BPY_rna_props( void )
{
PyObject *submodule;
submodule= PyModule_Create(&props_module);
- PyDict_SetItemString(PySys_GetObject("modules"), props_module.m_name, submodule);
+ PyDict_SetItemString(PyImport_GetModuleDict(), props_module.m_name, submodule);
/* INCREF since its its assumed that all these functions return the
* module with a new ref like PyDict_New, since they are passed to
diff --git a/source/blender/python/intern/bpy_props.h b/source/blender/python/intern/bpy_props.h
index 5fb62ac56d3..d90b12c0f91 100644
--- a/source/blender/python/intern/bpy_props.h
+++ b/source/blender/python/intern/bpy_props.h
@@ -41,6 +41,20 @@ PyObject *BPy_EnumProperty(PyObject *self, PyObject *args, PyObject *kw);
PyObject *BPy_PointerProperty(PyObject *self, PyObject *args, PyObject *kw);
PyObject *BPy_CollectionProperty(PyObject *self, PyObject *args, PyObject *kw);
+PyObject *BPy_RemoveProperty(PyObject *self, PyObject *args, PyObject *kw);
+
+extern char BPy_BoolProperty_doc[];
+extern char BPy_BoolVectorProperty_doc[];
+extern char BPy_IntProperty_doc[];
+extern char BPy_IntVectorProperty_doc[];
+extern char BPy_FloatProperty_doc[];
+extern char BPy_FloatVectorProperty_doc[];
+extern char BPy_StringProperty_doc[];
+extern char BPy_EnumProperty_doc[];
+extern char BPy_PointerProperty_doc[];
+extern char BPy_CollectionProperty_doc[];\
+extern char BPy_RemoveProperty_doc[];
+
#define PYRNA_STACK_ARRAY 32
#endif
diff --git a/source/blender/python/intern/bpy_rna.c b/source/blender/python/intern/bpy_rna.c
index 4792d284ca7..3bce1f83d6e 100644
--- a/source/blender/python/intern/bpy_rna.c
+++ b/source/blender/python/intern/bpy_rna.c
@@ -1,4 +1,3 @@
-
/**
* $Id$
*
@@ -36,6 +35,7 @@
#include "MEM_guardedalloc.h"
#include "BKE_utildefines.h"
+#include "BKE_idcode.h"
#include "BKE_context.h"
#include "BKE_global.h" /* evil G.* */
#include "BKE_report.h"
@@ -51,63 +51,100 @@
#define USE_MATHUTILS
#ifdef USE_MATHUTILS
-#include "../generic/Mathutils.h" /* so we can have mathutils callbacks */
+#include "../generic/mathutils.h" /* so we can have mathutils callbacks */
#include "../generic/IDProp.h" /* for IDprop lookups */
static PyObject *pyrna_prop_array_subscript_slice(BPy_PropertyRNA *self, PointerRNA *ptr, PropertyRNA *prop, int start, int stop, int length);
static Py_ssize_t pyrna_prop_array_length(BPy_PropertyRNA *self);
-static Py_ssize_t pyrna_prop_collection_length( BPy_PropertyRNA *self );
-
+static Py_ssize_t pyrna_prop_collection_length(BPy_PropertyRNA *self);
+static short pyrna_rotation_euler_order_get(PointerRNA *ptr, PropertyRNA **prop_eul_order, short order_fallback);
/* bpyrna vector/euler/quat callbacks */
static int mathutils_rna_array_cb_index= -1; /* index for our callbacks */
-/* not used yet but may want to use the subtype below */
+/* subtype not used much yet */
#define MATHUTILS_CB_SUBTYPE_EUL 0
#define MATHUTILS_CB_SUBTYPE_VEC 1
#define MATHUTILS_CB_SUBTYPE_QUAT 2
+#define MATHUTILS_CB_SUBTYPE_COLOR 3
-static int mathutils_rna_generic_check(BPy_PropertyRNA *self)
+static int mathutils_rna_generic_check(BaseMathObject *bmo)
{
- return self->prop?1:0;
+ BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
+ return self->prop ? 1:0;
}
-static int mathutils_rna_vector_get(BPy_PropertyRNA *self, int subtype, float *vec_from)
+static int mathutils_rna_vector_get(BaseMathObject *bmo, int subtype)
{
+ BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
if(self->prop==NULL)
return 0;
- RNA_property_float_get_array(&self->ptr, self->prop, vec_from);
+ RNA_property_float_get_array(&self->ptr, self->prop, bmo->data);
+
+ /* Euler order exception */
+ if(subtype==MATHUTILS_CB_SUBTYPE_EUL) {
+ EulerObject *eul= (EulerObject *)bmo;
+ PropertyRNA *prop_eul_order= NULL;
+ eul->order= pyrna_rotation_euler_order_get(&self->ptr, &prop_eul_order, eul->order);
+ }
+
return 1;
}
-static int mathutils_rna_vector_set(BPy_PropertyRNA *self, int subtype, float *vec_to)
+static int mathutils_rna_vector_set(BaseMathObject *bmo, int subtype)
{
+ BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
+ float min, max;
if(self->prop==NULL)
return 0;
- /* TODO, clamp */
- RNA_property_float_set_array(&self->ptr, self->prop, vec_to);
+
+ RNA_property_float_range(&self->ptr, self->prop, &min, &max);
+
+ if(min != FLT_MIN || max != FLT_MAX) {
+ int i, len= RNA_property_array_length(&self->ptr, self->prop);
+ for(i=0; i<len; i++) {
+ CLAMP(bmo->data[i], min, max);
+ }
+ }
+
+ RNA_property_float_set_array(&self->ptr, self->prop, bmo->data);
RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
+
+ /* Euler order exception */
+ if(subtype==MATHUTILS_CB_SUBTYPE_EUL) {
+ EulerObject *eul= (EulerObject *)bmo;
+ PropertyRNA *prop_eul_order= NULL;
+ short order= pyrna_rotation_euler_order_get(&self->ptr, &prop_eul_order, eul->order);
+ if(order != eul->order) {
+ RNA_property_enum_set(&self->ptr, prop_eul_order, eul->order);
+ RNA_property_update(BPy_GetContext(), &self->ptr, prop_eul_order);
+ }
+ }
return 1;
}
-static int mathutils_rna_vector_get_index(BPy_PropertyRNA *self, int subtype, float *vec_from, int index)
+static int mathutils_rna_vector_get_index(BaseMathObject *bmo, int subtype, int index)
{
+ BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
+
if(self->prop==NULL)
return 0;
- vec_from[index]= RNA_property_float_get_index(&self->ptr, self->prop, index);
+ bmo->data[index]= RNA_property_float_get_index(&self->ptr, self->prop, index);
return 1;
}
-static int mathutils_rna_vector_set_index(BPy_PropertyRNA *self, int subtype, float *vec_to, int index)
+static int mathutils_rna_vector_set_index(BaseMathObject *bmo, int subtype, int index)
{
+ BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
+
if(self->prop==NULL)
return 0;
- RNA_property_float_clamp(&self->ptr, self->prop, &vec_to[index]);
- RNA_property_float_set_index(&self->ptr, self->prop, index, vec_to[index]);
+ RNA_property_float_clamp(&self->ptr, self->prop, &bmo->data[index]);
+ RNA_property_float_set_index(&self->ptr, self->prop, index, bmo->data[index]);
RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
return 1;
}
@@ -124,31 +161,35 @@ Mathutils_Callback mathutils_rna_array_cb = {
/* bpyrna matrix callbacks */
static int mathutils_rna_matrix_cb_index= -1; /* index for our callbacks */
-static int mathutils_rna_matrix_get(BPy_PropertyRNA *self, int subtype, float *mat_from)
+static int mathutils_rna_matrix_get(BaseMathObject *bmo, int subtype)
{
+ BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
+
if(self->prop==NULL)
return 0;
- RNA_property_float_get_array(&self->ptr, self->prop, mat_from);
+ RNA_property_float_get_array(&self->ptr, self->prop, bmo->data);
return 1;
}
-static int mathutils_rna_matrix_set(BPy_PropertyRNA *self, int subtype, float *mat_to)
+static int mathutils_rna_matrix_set(BaseMathObject *bmo, int subtype)
{
+ BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
+
if(self->prop==NULL)
return 0;
/* can ignore clamping here */
- RNA_property_float_set_array(&self->ptr, self->prop, mat_to);
+ RNA_property_float_set_array(&self->ptr, self->prop, bmo->data);
RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
return 1;
}
Mathutils_Callback mathutils_rna_matrix_cb = {
- (BaseMathCheckFunc) mathutils_rna_generic_check,
- (BaseMathGetFunc) mathutils_rna_matrix_get,
- (BaseMathSetFunc) mathutils_rna_matrix_set,
- (BaseMathGetIndexFunc) NULL,
- (BaseMathSetIndexFunc) NULL
+ mathutils_rna_generic_check,
+ mathutils_rna_matrix_get,
+ mathutils_rna_matrix_set,
+ NULL,
+ NULL
};
/* same as RNA_enum_value_from_id but raises an exception */
@@ -164,7 +205,7 @@ int pyrna_enum_value_from_id(EnumPropertyItem *item, const char *identifier, int
return 0;
}
-#define PROP_ALL_VECTOR_SUBTYPES PROP_TRANSLATION: case PROP_DIRECTION: case PROP_VELOCITY: case PROP_ACCELERATION: case PROP_XYZ: case PROP_XYZ|PROP_UNIT_LENGTH
+#define PROP_ALL_VECTOR_SUBTYPES PROP_TRANSLATION: case PROP_DIRECTION: case PROP_VELOCITY: case PROP_ACCELERATION: case PROP_XYZ: case PROP_XYZ_LENGTH
PyObject *pyrna_math_object_from_array(PointerRNA *ptr, PropertyRNA *prop)
{
@@ -232,13 +273,18 @@ PyObject *pyrna_math_object_from_array(PointerRNA *ptr, PropertyRNA *prop)
case PROP_QUATERNION:
if(len==3) { /* euler */
if(is_thick) {
- ret= newEulerObject(NULL, 0, Py_NEW, NULL); // TODO, get order from RNA
+ /* attempt to get order, only needed for thixk types since wrapped with update via callbacks */
+ PropertyRNA *prop_eul_order= NULL;
+ short order= pyrna_rotation_euler_order_get(ptr, &prop_eul_order, ROT_MODE_XYZ);
+
+ ret= newEulerObject(NULL, order, Py_NEW, NULL); // TODO, get order from RNA
RNA_property_float_get_array(ptr, prop, ((EulerObject *)ret)->eul);
}
else {
- PyObject *eul_cb= newEulerObject_cb(ret, 0, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_EUL); // TODO, get order from RNA
- Py_DECREF(ret); /* the matrix owns now */
- ret= eul_cb; /* return the matrix instead */
+ /* order will be updated from callback on use */
+ PyObject *eul_cb= newEulerObject_cb(ret, ROT_MODE_XYZ, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_EUL); // TODO, get order from RNA
+ Py_DECREF(ret); /* the euler owns now */
+ ret= eul_cb; /* return the euler instead */
}
}
else if (len==4) {
@@ -248,11 +294,23 @@ PyObject *pyrna_math_object_from_array(PointerRNA *ptr, PropertyRNA *prop)
}
else {
PyObject *quat_cb= newQuaternionObject_cb(ret, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_QUAT);
- Py_DECREF(ret); /* the matrix owns now */
- ret= quat_cb; /* return the matrix instead */
+ Py_DECREF(ret); /* the quat owns now */
+ ret= quat_cb; /* return the quat instead */
}
}
break;
+ case PROP_COLOR:
+ if(len==3) { /* color */
+ if(is_thick) {
+ ret= newColorObject(NULL, Py_NEW, NULL); // TODO, get order from RNA
+ RNA_property_float_get_array(ptr, prop, ((ColorObject *)ret)->col);
+ }
+ else {
+ PyObject *col_cb= newColorObject_cb(ret, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_COLOR);
+ Py_DECREF(ret); /* the color owns now */
+ ret= col_cb; /* return the color instead */
+ }
+ }
default:
break;
}
@@ -275,6 +333,21 @@ PyObject *pyrna_math_object_from_array(PointerRNA *ptr, PropertyRNA *prop)
#endif
+static short pyrna_rotation_euler_order_get(PointerRNA *ptr, PropertyRNA **prop_eul_order, short order_fallback)
+{
+ /* attempt to get order */
+ if(*prop_eul_order==NULL)
+ *prop_eul_order= RNA_struct_find_property(ptr, "rotation_mode");
+
+ if(*prop_eul_order) {
+ short order= RNA_property_enum_get(ptr, *prop_eul_order);
+ if (order >= ROT_MODE_XYZ && order <= ROT_MODE_ZYX) /* could be quat or axisangle */
+ return order;
+ }
+
+ return order_fallback;
+}
+
static int pyrna_struct_compare( BPy_StructRNA * a, BPy_StructRNA * b )
{
return (a->ptr.data==b->ptr.data) ? 0 : -1;
@@ -346,25 +419,50 @@ static PyObject *pyrna_prop_richcmp(PyObject *a, PyObject *b, int op)
}
/*----------------------repr--------------------------------------------*/
-static PyObject *pyrna_struct_repr( BPy_StructRNA *self )
+static PyObject *pyrna_struct_str( BPy_StructRNA *self )
{
- PyObject *pyob;
+ PyObject *ret;
char *name;
/* print name if available */
name= RNA_struct_name_get_alloc(&self->ptr, NULL, FALSE);
if(name) {
- pyob= PyUnicode_FromFormat( "<bpy_struct, %.200s(\"%.200s\")>", RNA_struct_identifier(self->ptr.type), name);
+ ret= PyUnicode_FromFormat( "<bpy_struct, %.200s(\"%.200s\")>", RNA_struct_identifier(self->ptr.type), name);
MEM_freeN(name);
- return pyob;
+ return ret;
}
return PyUnicode_FromFormat( "<bpy_struct, %.200s at %p>", RNA_struct_identifier(self->ptr.type), self->ptr.data);
}
-static PyObject *pyrna_prop_repr( BPy_PropertyRNA *self )
+static PyObject *pyrna_struct_repr(BPy_StructRNA *self)
+{
+ ID *id= self->ptr.id.data;
+ if(id == NULL)
+ return pyrna_struct_str(self); /* fallback */
+
+ if(RNA_struct_is_ID(self->ptr.type)) {
+ return PyUnicode_FromFormat( "bpy.data.%s[\"%s\"]", BKE_idcode_to_name_plural(GS(id->name)), id->name+2);
+ }
+ else {
+ PyObject *ret;
+ char *path;
+ path= RNA_path_from_ID_to_struct(&self->ptr);
+ if(path) {
+ ret= PyUnicode_FromFormat( "bpy.data.%s[\"%s\"].%s", BKE_idcode_to_name_plural(GS(id->name)), id->name+2, path);
+ MEM_freeN(path);
+ }
+ else { /* cant find, print something sane */
+ ret= PyUnicode_FromFormat( "bpy.data.%s[\"%s\"]...%s", BKE_idcode_to_name_plural(GS(id->name)), id->name+2, RNA_struct_identifier(self->ptr.type));
+ }
+
+ return ret;
+ }
+}
+
+static PyObject *pyrna_prop_str( BPy_PropertyRNA *self )
{
- PyObject *pyob;
+ PyObject *ret;
PointerRNA ptr;
char *name;
const char *type_id= NULL;
@@ -398,18 +496,59 @@ static PyObject *pyrna_prop_repr( BPy_PropertyRNA *self )
name= RNA_struct_name_get_alloc(&ptr, NULL, FALSE);
if(name) {
- pyob= PyUnicode_FromFormat( "<bpy_%.200s, %.200s.%.200s(\"%.200s\")>", type_fmt, RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop), name);
+ ret= PyUnicode_FromFormat( "<bpy_%.200s, %.200s.%.200s(\"%.200s\")>", type_fmt, RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop), name);
MEM_freeN(name);
- return pyob;
+ return ret;
}
}
return PyUnicode_FromFormat( "<bpy_%.200s, %.200s.%.200s>", type_fmt, RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
}
+static PyObject *pyrna_prop_repr(BPy_PropertyRNA *self)
+{
+ ID *id= self->ptr.id.data;
+ PyObject *ret;
+ char *path;
+
+ if(id == NULL)
+ return pyrna_prop_str(self); /* fallback */
+
+ path= RNA_path_from_ID_to_property(&self->ptr, self->prop);
+ if(path) {
+ ret= PyUnicode_FromFormat( "bpy.data.%s[\"%s\"].%s", BKE_idcode_to_name_plural(GS(id->name)), id->name+2, path);
+ MEM_freeN(path);
+ }
+ else { /* cant find, print something sane */
+ ret= PyUnicode_FromFormat( "bpy.data.%s[\"%s\"]...%s", BKE_idcode_to_name_plural(GS(id->name)), id->name+2, RNA_property_identifier(self->prop));
+ }
+
+ return ret;
+}
+
static long pyrna_struct_hash( BPy_StructRNA *self )
{
- return (long)self->ptr.data;
+ return _Py_HashPointer(self->ptr.data);
+}
+
+/* from python's meth_hash v3.1.2 */
+static long pyrna_prop_hash(BPy_PropertyRNA *self)
+{
+ long x,y;
+ if (self->ptr.data == NULL)
+ x = 0;
+ else {
+ x = _Py_HashPointer(self->ptr.data);
+ if (x == -1)
+ return -1;
+ }
+ y = _Py_HashPointer((void*)(self->prop));
+ if (y == -1)
+ return -1;
+ x ^= y;
+ if (x == -1)
+ x = -2;
+ return x;
}
/* use our own dealloc so we can free a property if we use one */
@@ -833,11 +972,12 @@ int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, ParameterList *parms, v
case PROP_STRING:
{
char *param = _PyUnicode_AsString(value);
-
+
if (param==NULL) {
PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s expected a string type", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop));
return -1;
- } else {
+ }
+ else {
if(data) *((char**)data)= param;
else RNA_property_string_set(ptr, prop, param);
}
@@ -876,6 +1016,8 @@ int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, ParameterList *parms, v
}
case PROP_POINTER:
{
+ PyObject *value_new= NULL;
+
StructRNA *ptype= RNA_property_pointer_type(ptr, prop);
int flag = RNA_property_flag(prop);
@@ -885,15 +1027,29 @@ int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, ParameterList *parms, v
return pyrna_pydict_to_props(&opptr, value, 0, error_prefix);
}
+ /* another exception, allow to pass a collection as an RNA property */
+ if(Py_TYPE(value)==&pyrna_prop_collection_Type) {
+ PointerRNA c_ptr;
+ BPy_PropertyRNA *value_prop= (BPy_PropertyRNA *)value;
+ if(RNA_property_collection_type_get(&value_prop->ptr, value_prop->prop, &c_ptr)) {
+ value= pyrna_struct_CreatePyObject(&c_ptr);
+ value_new= value;
+ }
+ else {
+ PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s collection has no type, cant be used as a %.200s type", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), RNA_struct_identifier(ptype));
+ return -1;
+ }
+ }
+
if(!BPy_StructRNA_Check(value) && value != Py_None) {
PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s expected a %.200s type", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), RNA_struct_identifier(ptype));
- return -1;
+ Py_XDECREF(value_new); return -1;
} else if((flag & PROP_NEVER_NULL) && value == Py_None) {
PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s does not support a 'None' assignment %.200s type", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), RNA_struct_identifier(ptype));
- return -1;
+ Py_XDECREF(value_new); return -1;
} else if(value != Py_None && ((flag & PROP_ID_SELF_CHECK) && ptr->id.data == ((BPy_StructRNA*)value)->ptr.id.data)) {
PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s ID type does not support assignment to its self", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop));
- return -1;
+ Py_XDECREF(value_new); return -1;
} else {
BPy_StructRNA *param= (BPy_StructRNA*)value;
int raise_error= FALSE;
@@ -929,7 +1085,7 @@ int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, ParameterList *parms, v
PointerRNA tmp;
RNA_pointer_create(NULL, ptype, NULL, &tmp);
PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s expected a %.200s type", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), RNA_struct_identifier(tmp.type));
- return -1;
+ Py_XDECREF(value_new); return -1;
}
}
@@ -937,9 +1093,10 @@ int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, ParameterList *parms, v
PointerRNA tmp;
RNA_pointer_create(NULL, ptype, NULL, &tmp);
PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s expected a %.200s type", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), RNA_struct_identifier(tmp.type));
- return -1;
+ Py_XDECREF(value_new); return -1;
}
}
+
break;
}
case PROP_COLLECTION:
@@ -1077,6 +1234,9 @@ static int pyrna_py_to_prop_index(BPy_PropertyRNA *self, int index, PyObject *va
break;
}
}
+
+ /* Run rna property functions */
+ RNA_property_update(BPy_GetContext(), ptr, prop);
return ret;
}
@@ -1095,22 +1255,42 @@ static Py_ssize_t pyrna_prop_collection_length( BPy_PropertyRNA *self )
return RNA_property_collection_length(&self->ptr, self->prop);
}
+/* bool funcs are for speed, so we can avoid getting the length
+ * of 1000's of items in a linked list for eg. */
+static int pyrna_prop_array_bool(BPy_PropertyRNA *self)
+{
+ return RNA_property_array_length(&self->ptr, self->prop) ? 1 : 0;
+}
+
+static int pyrna_prop_collection_bool( BPy_PropertyRNA *self )
+{
+ /* no callback defined, just iterate and find the nth item */
+ CollectionPropertyIterator iter;
+ int test;
+
+ RNA_property_collection_begin(&self->ptr, self->prop, &iter);
+ test = iter.valid;
+ RNA_property_collection_end(&iter);
+ return test;
+}
+
/* internal use only */
static PyObject *pyrna_prop_collection_subscript_int(BPy_PropertyRNA *self, Py_ssize_t keynum)
{
PointerRNA newptr;
- int len= RNA_property_collection_length(&self->ptr, self->prop);
+ int len= RNA_property_collection_length(&self->ptr, self->prop);
if(keynum < 0) keynum += len;
- if(keynum >= 0 && keynum < len) {
- if(RNA_property_collection_lookup_int(&self->ptr, self->prop, keynum, &newptr)) {
- return pyrna_struct_CreatePyObject(&newptr);
- }
- PyErr_Format(PyExc_IndexError, "bpy_prop_collection[index]: index %d could not be found", keynum);
- return NULL;
- }
- PyErr_Format(PyExc_IndexError, "bpy_prop_collection[index]: index %d out of range", keynum);
+ if(keynum >= 0 && keynum < len) {
+ if(RNA_property_collection_lookup_int(&self->ptr, self->prop, keynum, &newptr)) {
+ return pyrna_struct_CreatePyObject(&newptr);
+ }
+ else { /* fail's if ptr.data == NULL, valid for mesh.materials */
+ Py_RETURN_NONE;
+ }
+ }
+ PyErr_Format(PyExc_IndexError, "bpy_prop_collection[index]: index %d out of range, size %d", keynum, len);
return NULL;
}
@@ -1321,7 +1501,7 @@ static int prop_subscript_ass_array_slice(PointerRNA *ptr, PropertyRNA *prop, in
return -1;
}
- if(!(value=PySequence_Fast(value_orig, "bpy_prop_array[slice] = value: type is not a sequence"))) {
+ if(!(value=PySequence_Fast(value_orig, "bpy_prop_array[slice] = value: assignment is not a sequence type"))) {
return -1;
}
@@ -1427,43 +1607,50 @@ static int prop_subscript_ass_array_int(BPy_PropertyRNA *self, Py_ssize_t keynum
static int pyrna_prop_array_ass_subscript( BPy_PropertyRNA *self, PyObject *key, PyObject *value )
{
/* char *keyname = NULL; */ /* not supported yet */
-
+ int ret= -1;
+
if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
PyErr_Format(PyExc_AttributeError, "bpy_prop_collection: attribute \"%.200s\" from \"%.200s\" is read-only", RNA_property_identifier(self->prop), RNA_struct_identifier(self->ptr.type) );
- return -1;
+ ret= -1;
}
- if (PyIndex_Check(key)) {
+ else if (PyIndex_Check(key)) {
Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
- if (i == -1 && PyErr_Occurred())
- return -1;
-
- return prop_subscript_ass_array_int(self, i, value);
+ if (i == -1 && PyErr_Occurred()) {
+ ret= -1;
+ }
+ else {
+ ret= prop_subscript_ass_array_int(self, i, value);
+ }
}
else if (PySlice_Check(key)) {
int len= RNA_property_array_length(&self->ptr, self->prop);
Py_ssize_t start, stop, step, slicelength;
- if (PySlice_GetIndicesEx((PySliceObject*)key, len, &start, &stop, &step, &slicelength) < 0)
- return -1;
-
- if (slicelength <= 0) {
- return 0;
+ if (PySlice_GetIndicesEx((PySliceObject*)key, len, &start, &stop, &step, &slicelength) < 0) {
+ ret= -1;
+ }
+ else if (slicelength <= 0) {
+ ret= 0; /* do nothing */
}
else if (step == 1) {
- return prop_subscript_ass_array_slice(&self->ptr, self->prop, start, stop, len, value);
+ ret= prop_subscript_ass_array_slice(&self->ptr, self->prop, start, stop, len, value);
}
else {
PyErr_SetString(PyExc_TypeError, "slice steps not supported with rna");
- return -1;
+ ret= -1;
}
}
else {
PyErr_SetString(PyExc_AttributeError, "invalid key, key must be an int");
- return -1;
+ ret= -1;
}
- RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
+ if(ret != -1) {
+ RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
+ }
+
+ return ret;
}
/* for slice only */
@@ -1479,6 +1666,31 @@ static PyMappingMethods pyrna_prop_collection_as_mapping = {
( objobjargproc ) NULL, /* mp_ass_subscript */
};
+/* only for fast bool's, large structs, assign nb_bool on init */
+static PyNumberMethods pyrna_prop_array_as_number = {
+ NULL, /* nb_add */
+ NULL, /* nb_subtract */
+ NULL, /* nb_multiply */
+ NULL, /* nb_remainder */
+ NULL, /* nb_divmod */
+ NULL, /* nb_power */
+ NULL, /* nb_negative */
+ NULL, /* nb_positive */
+ NULL, /* nb_absolute */
+ (inquiry) pyrna_prop_array_bool, /* nb_bool */
+};
+static PyNumberMethods pyrna_prop_collection_as_number = {
+ NULL, /* nb_add */
+ NULL, /* nb_subtract */
+ NULL, /* nb_multiply */
+ NULL, /* nb_remainder */
+ NULL, /* nb_divmod */
+ NULL, /* nb_power */
+ NULL, /* nb_negative */
+ NULL, /* nb_positive */
+ NULL, /* nb_absolute */
+ (inquiry) pyrna_prop_collection_bool, /* nb_bool */
+};
static int pyrna_prop_array_contains(BPy_PropertyRNA *self, PyObject *value)
{
@@ -1513,12 +1725,12 @@ static int pyrna_struct_contains(BPy_StructRNA *self, PyObject *value)
return -1;
}
- if(RNA_struct_idproperties_check(self->ptr.type)==0) {
+ if(RNA_struct_idprops_check(self->ptr.type)==0) {
PyErr_SetString( PyExc_TypeError, "bpy_struct: this type doesnt support IDProperties");
return -1;
}
- group= RNA_struct_idproperties(&self->ptr, 0);
+ group= RNA_struct_idprops(&self->ptr, 0);
if(!group)
return 0;
@@ -1535,6 +1747,8 @@ static PySequenceMethods pyrna_prop_array_as_sequence = {
(ssizeobjargproc)prop_subscript_ass_array_int, /* sq_ass_item */
NULL, /* *was* sq_ass_slice */
(objobjproc)pyrna_prop_array_contains, /* sq_contains */
+ (binaryfunc) NULL, /* sq_inplace_concat */
+ (ssizeargfunc) NULL, /* sq_inplace_repeat */
};
static PySequenceMethods pyrna_prop_collection_as_sequence = {
@@ -1546,6 +1760,8 @@ static PySequenceMethods pyrna_prop_collection_as_sequence = {
NULL, /* sq_ass_item */
NULL, /* *was* sq_ass_slice */
(objobjproc)pyrna_prop_collection_contains, /* sq_contains */
+ (binaryfunc) NULL, /* sq_inplace_concat */
+ (ssizeargfunc) NULL, /* sq_inplace_repeat */
};
static PySequenceMethods pyrna_struct_as_sequence = {
@@ -1557,6 +1773,8 @@ static PySequenceMethods pyrna_struct_as_sequence = {
NULL, /* sq_ass_item */
NULL, /* *was* sq_ass_slice */
(objobjproc)pyrna_struct_contains, /* sq_contains */
+ (binaryfunc) NULL, /* sq_inplace_concat */
+ (ssizeargfunc) NULL, /* sq_inplace_repeat */
};
static PyObject *pyrna_struct_subscript( BPy_StructRNA *self, PyObject *key )
@@ -1565,7 +1783,7 @@ static PyObject *pyrna_struct_subscript( BPy_StructRNA *self, PyObject *key )
IDProperty *group, *idprop;
char *name= _PyUnicode_AsString(key);
- if(RNA_struct_idproperties_check(self->ptr.type)==0) {
+ if(RNA_struct_idprops_check(self->ptr.type)==0) {
PyErr_SetString( PyExc_TypeError, "this type doesn't support IDProperties");
return NULL;
}
@@ -1575,7 +1793,7 @@ static PyObject *pyrna_struct_subscript( BPy_StructRNA *self, PyObject *key )
return NULL;
}
- group= RNA_struct_idproperties(&self->ptr, 0);
+ group= RNA_struct_idprops(&self->ptr, 0);
if(group==NULL) {
PyErr_Format( PyExc_KeyError, "bpy_struct[key]: key \"%s\" not found", name);
@@ -1594,7 +1812,7 @@ static PyObject *pyrna_struct_subscript( BPy_StructRNA *self, PyObject *key )
static int pyrna_struct_ass_subscript( BPy_StructRNA *self, PyObject *key, PyObject *value )
{
- IDProperty *group= RNA_struct_idproperties(&self->ptr, 1);
+ IDProperty *group= RNA_struct_idprops(&self->ptr, 1);
if(group==NULL) {
PyErr_SetString(PyExc_TypeError, "bpy_struct[key] = val: id properties not supported for this type");
@@ -1610,16 +1828,26 @@ static PyMappingMethods pyrna_struct_as_mapping = {
( objobjargproc ) pyrna_struct_ass_subscript, /* mp_ass_subscript */
};
+static char pyrna_struct_keys_doc[] =
+".. method:: keys()\n"
+"\n"
+" Returns the keys of this objects custom properties (matches pythons dictionary function of the same name).\n"
+"\n"
+" :return: custom property keys.\n"
+" :rtype: list of strings\n"
+"\n"
+" .. note:: Only :class:`ID`, :class:`Bone` and :class:`PoseBone` classes support custom properties.\n";
+
static PyObject *pyrna_struct_keys(BPy_PropertyRNA *self)
{
IDProperty *group;
- if(RNA_struct_idproperties_check(self->ptr.type)==0) {
+ if(RNA_struct_idprops_check(self->ptr.type)==0) {
PyErr_SetString( PyExc_TypeError, "bpy_struct.keys(): this type doesn't support IDProperties");
return NULL;
}
- group= RNA_struct_idproperties(&self->ptr, 0);
+ group= RNA_struct_idprops(&self->ptr, 0);
if(group==NULL)
return PyList_New(0);
@@ -1627,16 +1855,26 @@ static PyObject *pyrna_struct_keys(BPy_PropertyRNA *self)
return BPy_Wrap_GetKeys(group);
}
+static char pyrna_struct_items_doc[] =
+".. method:: items()\n"
+"\n"
+" Returns the items of this objects custom properties (matches pythons dictionary function of the same name).\n"
+"\n"
+" :return: custom property key, value pairs.\n"
+" :rtype: list of key, value tuples\n"
+"\n"
+" .. note:: Only :class:`ID`, :class:`Bone` and :class:`PoseBone` classes support custom properties.\n";
+
static PyObject *pyrna_struct_items(BPy_PropertyRNA *self)
{
IDProperty *group;
- if(RNA_struct_idproperties_check(self->ptr.type)==0) {
+ if(RNA_struct_idprops_check(self->ptr.type)==0) {
PyErr_SetString( PyExc_TypeError, "bpy_struct.items(): this type doesn't support IDProperties");
return NULL;
}
- group= RNA_struct_idproperties(&self->ptr, 0);
+ group= RNA_struct_idprops(&self->ptr, 0);
if(group==NULL)
return PyList_New(0);
@@ -1644,17 +1882,26 @@ static PyObject *pyrna_struct_items(BPy_PropertyRNA *self)
return BPy_Wrap_GetItems(self->ptr.id.data, group);
}
+static char pyrna_struct_values_doc[] =
+".. method:: values()\n"
+"\n"
+" Returns the values of this objects custom properties (matches pythons dictionary function of the same name).\n"
+"\n"
+" :return: custom property values.\n"
+" :rtype: list\n"
+"\n"
+" .. note:: Only :class:`ID`, :class:`Bone` and :class:`PoseBone` classes support custom properties.\n";
static PyObject *pyrna_struct_values(BPy_PropertyRNA *self)
{
IDProperty *group;
- if(RNA_struct_idproperties_check(self->ptr.type)==0) {
+ if(RNA_struct_idprops_check(self->ptr.type)==0) {
PyErr_SetString( PyExc_TypeError, "bpy_struct.values(): this type doesn't support IDProperties");
return NULL;
}
- group= RNA_struct_idproperties(&self->ptr, 0);
+ group= RNA_struct_idprops(&self->ptr, 0);
if(group==NULL)
return PyList_New(0);
@@ -1662,36 +1909,46 @@ static PyObject *pyrna_struct_values(BPy_PropertyRNA *self)
return BPy_Wrap_GetValues(self->ptr.id.data, group);
}
-/* internal use for insert and delete */
-int pyrna_struct_keyframe_parse(PointerRNA *ptr, PyObject *args, char *error_prefix,
- char **path_full, int *index, float *cfra) /* return values */
+/* for keyframes and drivers */
+static int pyrna_struct_anim_args_parse(PointerRNA *ptr, const char *error_prefix, const char *path,
+ char **path_full, int *index)
{
- char *path;
PropertyRNA *prop;
- int array_len;
-
- if (!PyArg_ParseTuple(args, "s|if", &path, index, cfra)) {
- PyErr_Format(PyExc_TypeError, "%.200s expected a string and optionally an int and float arguments", error_prefix);
- return -1;
- }
-
+
if (ptr->data==NULL) {
PyErr_Format(PyExc_TypeError, "%.200s this struct has no data, can't be animated", error_prefix);
return -1;
}
-
+
prop = RNA_struct_find_property(ptr, path);
-
+
if (prop==NULL) {
PyErr_Format( PyExc_TypeError, "%.200s property \"%s\" not found", error_prefix, path);
return -1;
}
if (!RNA_property_animateable(ptr, prop)) {
- PyErr_Format( PyExc_TypeError, "%.200s property \"%s\" not animatable", error_prefix, path);
+ PyErr_Format(PyExc_TypeError, "%.200s property \"%s\" not animatable", error_prefix, path);
return -1;
}
+ if(RNA_property_array_check(ptr, prop) == 0) {
+ if((*index) == -1) {
+ *index= 0;
+ }
+ else {
+ PyErr_Format(PyExc_TypeError, "%.200s index %d was given while property \"%s\" is not an array", error_prefix, *index, path);
+ return -1;
+ }
+ }
+ else {
+ int array_len= RNA_property_array_length(ptr, prop);
+ if((*index) < -1 || (*index) >= array_len) {
+ PyErr_Format( PyExc_TypeError, "%.200s index out of range \"%s\", given %d, array length is %d", error_prefix, path, *index, array_len);
+ return -1;
+ }
+ }
+
*path_full= RNA_path_from_ID_to_property(ptr, prop);
if (*path_full==NULL) {
@@ -1699,85 +1956,120 @@ int pyrna_struct_keyframe_parse(PointerRNA *ptr, PyObject *args, char *error_pre
return -1;
}
- array_len= RNA_property_array_length(ptr, prop);
- if((*index) != -1 && (*index) >= array_len) {
- PyErr_Format( PyExc_TypeError, "%.200s index out of range \"%s\", given %d, array length is %d", error_prefix, path, *index, array_len);
+ return 0;
+}
+
+/* internal use for insert and delete */
+static int pyrna_struct_keyframe_parse(PointerRNA *ptr, PyObject *args, PyObject *kw, const char *parse_str, const char *error_prefix,
+ char **path_full, int *index, float *cfra, char **group_name) /* return values */
+{
+ static char *kwlist[] = {"data_path", "index", "frame", "group", NULL};
+ char *path;
+
+ /* note, parse_str MUST start with 's|ifs' */
+ if (!PyArg_ParseTupleAndKeywords(args, kw, parse_str, (char **)kwlist, &path, index, cfra, group_name))
return -1;
- }
+ if(pyrna_struct_anim_args_parse(ptr, error_prefix, path, path_full, index) < 0)
+ return -1;
+
if(*cfra==FLT_MAX)
*cfra= CTX_data_scene(BPy_GetContext())->r.cfra;
return 0; /* success */
}
-static PyObject *pyrna_struct_keyframe_insert(BPy_StructRNA *self, PyObject *args)
+static char pyrna_struct_keyframe_insert_doc[] =
+".. method:: keyframe_insert(data_path, index=-1, frame=bpy.context.scene.frame_current, group=\"\")\n"
+"\n"
+" Insert a keyframe on the property given, adding fcurves and animation data when necessary.\n"
+"\n"
+" :arg data_path: path to the property to key, analogous to the fcurve's data path.\n"
+" :type data_path: string\n"
+" :arg index: array index of the property to key. Defaults to -1 which will key all indicies or a single channel if the property is not an array.\n"
+" :type index: int\n"
+" :arg frame: The frame on which the keyframe is inserted, defaulting to the current frame.\n"
+" :type frame: float\n"
+" :arg group: The name of the group the F-Curve should be added to if it doesn't exist yet.\n"
+" :type group: str\n"
+" :return: Success of keyframe insertion.\n"
+" :rtype: boolean";
+
+static PyObject *pyrna_struct_keyframe_insert(BPy_StructRNA *self, PyObject *args, PyObject *kw)
{
PyObject *result;
/* args, pyrna_struct_keyframe_parse handles these */
char *path_full= NULL;
int index= -1;
float cfra= FLT_MAX;
+ char *group_name= NULL;
- if(pyrna_struct_keyframe_parse(&self->ptr, args, "bpy_struct.keyframe_insert():", &path_full, &index, &cfra) == -1)
+ if(pyrna_struct_keyframe_parse(&self->ptr, args, kw, "s|ifs:bpy_struct.keyframe_insert()", "bpy_struct.keyframe_insert()", &path_full, &index, &cfra, &group_name) == -1)
return NULL;
- result= PyBool_FromLong(insert_keyframe((ID *)self->ptr.id.data, NULL, NULL, path_full, index, cfra, 0));
+ result= PyBool_FromLong(insert_keyframe((ID *)self->ptr.id.data, NULL, group_name, path_full, index, cfra, 0));
MEM_freeN(path_full);
return result;
}
-static PyObject *pyrna_struct_keyframe_delete(BPy_StructRNA *self, PyObject *args)
+static char pyrna_struct_keyframe_delete_doc[] =
+".. method:: keyframe_delete(data_path, index=-1, frame=bpy.context.scene.frame_current, group=\"\")\n"
+"\n"
+" Remove a keyframe from this properties fcurve.\n"
+"\n"
+" :arg data_path: path to the property to remove a key, analogous to the fcurve's data path.\n"
+" :type data_path: string\n"
+" :arg index: array index of the property to remove a key. Defaults to -1 removing all indicies or a single channel if the property is not an array.\n"
+" :type index: int\n"
+" :arg frame: The frame on which the keyframe is deleted, defaulting to the current frame.\n"
+" :type frame: float\n"
+" :arg group: The name of the group the F-Curve should be added to if it doesn't exist yet.\n"
+" :type group: str\n"
+" :return: Success of keyframe deleation.\n"
+" :rtype: boolean";
+
+static PyObject *pyrna_struct_keyframe_delete(BPy_StructRNA *self, PyObject *args, PyObject *kw)
{
PyObject *result;
/* args, pyrna_struct_keyframe_parse handles these */
char *path_full= NULL;
int index= -1;
float cfra= FLT_MAX;
+ char *group_name= NULL;
- if(pyrna_struct_keyframe_parse(&self->ptr, args, "bpy_struct.keyframe_delete():", &path_full, &index, &cfra) == -1)
+ if(pyrna_struct_keyframe_parse(&self->ptr, args, kw, "s|ifs:bpy_struct.keyframe_delete()", "bpy_struct.keyframe_insert()", &path_full, &index, &cfra, &group_name) == -1)
return NULL;
- result= PyBool_FromLong(delete_keyframe((ID *)self->ptr.id.data, NULL, NULL, path_full, index, cfra, 0));
+ result= PyBool_FromLong(delete_keyframe((ID *)self->ptr.id.data, NULL, group_name, path_full, index, cfra, 0));
MEM_freeN(path_full);
return result;
}
+static char pyrna_struct_driver_add_doc[] =
+".. method:: driver_add(path, index=-1)\n"
+"\n"
+" Adds driver(s) to the given property\n"
+"\n"
+" :arg path: path to the property to drive, analogous to the fcurve's data path.\n"
+" :type path: string\n"
+" :arg index: array index of the property drive. Defaults to -1 for all indicies or a single channel if the property is not an array.\n"
+" :type index: int\n"
+" :return: The driver(s) added.\n"
+" :rtype: :class:`FCurve` or list if index is -1 with an array property.";
+
static PyObject *pyrna_struct_driver_add(BPy_StructRNA *self, PyObject *args)
{
char *path, *path_full;
- int index= -1; /* default to all */
- PropertyRNA *prop;
+ int index= -1;
PyObject *ret;
if (!PyArg_ParseTuple(args, "s|i:driver_add", &path, &index))
return NULL;
- if (self->ptr.data==NULL) {
- PyErr_Format( PyExc_TypeError, "bpy_struct.driver_add(): this struct has no data, cant be animated", path);
- return NULL;
- }
-
- prop = RNA_struct_find_property(&self->ptr, path);
-
- if (prop==NULL) {
- PyErr_Format( PyExc_TypeError, "bpy_struct.driver_add(): property \"%s\" not found", path);
- return NULL;
- }
-
- if (!RNA_property_animateable(&self->ptr, prop)) {
- PyErr_Format( PyExc_TypeError, "bpy_struct.driver_add(): property \"%s\" not animatable", path);
- return NULL;
- }
-
- path_full= RNA_path_from_ID_to_property(&self->ptr, prop);
-
- if (path_full==NULL) {
- PyErr_Format( PyExc_TypeError, "bpy_struct.driver_add(): could not make path to \"%s\"", path);
+ if(pyrna_struct_anim_args_parse(&self->ptr, "bpy_struct.driver_add():", path, &path_full, &index) < 0)
return NULL;
- }
if(ANIM_add_driver((ID *)self->ptr.id.data, path_full, index, 0, DRIVER_TYPE_PYTHON)) {
ID *id= self->ptr.id.data;
@@ -1804,8 +2096,8 @@ static PyObject *pyrna_struct_driver_add(BPy_StructRNA *self, PyObject *args)
}
}
else {
- ret= Py_None;
- Py_INCREF(ret);
+ PyErr_SetString(PyExc_TypeError, "bpy_struct.driver_add(): failed because of an internal error");
+ return NULL;
}
MEM_freeN(path_full);
@@ -1813,62 +2105,161 @@ static PyObject *pyrna_struct_driver_add(BPy_StructRNA *self, PyObject *args)
return ret;
}
+
+static char pyrna_struct_driver_remove_doc[] =
+".. method:: driver_remove(path, index=-1)\n"
+"\n"
+" Remove driver(s) from the given property\n"
+"\n"
+" :arg path: path to the property to drive, analogous to the fcurve's data path.\n"
+" :type path: string\n"
+" :arg index: array index of the property drive. Defaults to -1 for all indicies or a single channel if the property is not an array.\n"
+" :type index: int\n"
+" :return: Success of driver removal.\n"
+" :rtype: boolean";
+
+static PyObject *pyrna_struct_driver_remove(BPy_StructRNA *self, PyObject *args)
+{
+ char *path, *path_full;
+ int index= -1;
+ PyObject *ret;
+
+ if (!PyArg_ParseTuple(args, "s|i:driver_remove", &path, &index))
+ return NULL;
+
+ if(pyrna_struct_anim_args_parse(&self->ptr, "bpy_struct.driver_remove():", path, &path_full, &index) < 0)
+ return NULL;
+
+ ret= PyBool_FromLong(ANIM_remove_driver((ID *)self->ptr.id.data, path_full, index, 0));
+
+ MEM_freeN(path_full);
+
+ return ret;
+}
+
+
+static char pyrna_struct_is_property_set_doc[] =
+".. method:: is_property_set(property)\n"
+"\n"
+" Check if a property is set, use for testing operator properties.\n"
+"\n"
+" :return: True when the property has been set.\n"
+" :rtype: boolean";
+
static PyObject *pyrna_struct_is_property_set(BPy_StructRNA *self, PyObject *args)
{
+ PropertyRNA *prop;
char *name;
+ int ret;
if (!PyArg_ParseTuple(args, "s:is_property_set", &name))
return NULL;
- return PyBool_FromLong(RNA_property_is_set(&self->ptr, name));
+ if((prop= RNA_struct_find_property(&self->ptr, name)) == NULL) {
+ PyErr_Format(PyExc_TypeError, "%.200s.is_property_set(\"%.200s\") not found", RNA_struct_identifier(self->ptr.type), name);
+ return NULL;
+ }
+
+ /* double property lookup, could speed up */
+ /* return PyBool_FromLong(RNA_property_is_set(&self->ptr, name)); */
+ if(RNA_property_flag(prop) & PROP_IDPROPERTY) {
+ IDProperty *group= RNA_struct_idprops(&self->ptr, 0);
+ if(group) {
+ ret= IDP_GetPropertyFromGroup(group, name) ? 1:0;
+ }
+ else {
+ ret= 0;
+ }
+ }
+ else {
+ ret= 1;
+ }
+
+ return PyBool_FromLong(ret);
}
+static char pyrna_struct_is_property_hidden_doc[] =
+".. method:: is_property_hidden(property)\n"
+"\n"
+" Check if a property is hidden.\n"
+"\n"
+" :return: True when the property is hidden.\n"
+" :rtype: boolean";
+
static PyObject *pyrna_struct_is_property_hidden(BPy_StructRNA *self, PyObject *args)
{
PropertyRNA *prop;
char *name;
- int hidden;
if (!PyArg_ParseTuple(args, "s:is_property_hidden", &name))
return NULL;
-
- prop= RNA_struct_find_property(&self->ptr, name);
- hidden= (prop)? (RNA_property_flag(prop) & PROP_HIDDEN): 1;
- return PyBool_FromLong(hidden);
+ if((prop= RNA_struct_find_property(&self->ptr, name)) == NULL) {
+ PyErr_Format(PyExc_TypeError, "%.200s.is_property_hidden(\"%.200s\") not found", RNA_struct_identifier(self->ptr.type), name);
+ return NULL;
+ }
+
+ return PyBool_FromLong(RNA_property_flag(prop) & PROP_HIDDEN);
}
-static PyObject *pyrna_struct_path_resolve(BPy_StructRNA *self, PyObject *value)
+static char pyrna_struct_path_resolve_doc[] =
+".. method:: path_resolve(path, coerce=True)\n"
+"\n"
+" Returns the property from the path, raise an exception when not found.\n"
+"\n"
+" :arg path: path which this property resolves.\n"
+" :type path: string\n"
+" :arg coerce: optional argument, when True, the property will be converted into its python representation.\n"
+" :type coerce: boolean\n";
+
+static PyObject *pyrna_struct_path_resolve(BPy_StructRNA *self, PyObject *args)
{
- char *path= _PyUnicode_AsString(value);
+ char *path;
+ PyObject *coerce= Py_True;
PointerRNA r_ptr;
PropertyRNA *r_prop;
- if(path==NULL) {
- PyErr_SetString( PyExc_TypeError, "bpy_struct.items(): is only valid for collection types" );
+ if (!PyArg_ParseTuple(args, "s|O!:path_resolve", &path, &PyBool_Type, &coerce))
return NULL;
- }
- if (RNA_path_resolve(&self->ptr, path, &r_ptr, &r_prop))
- return pyrna_prop_CreatePyObject(&r_ptr, r_prop);
-
- Py_RETURN_NONE;
+ if (RNA_path_resolve(&self->ptr, path, &r_ptr, &r_prop)) {
+ if(coerce == Py_False) {
+ return pyrna_prop_CreatePyObject(&r_ptr, r_prop);
+ }
+ else {
+ return pyrna_prop_to_py(&r_ptr, r_prop);
+ }
+ }
+ else {
+ PyErr_Format(PyExc_TypeError, "%.200s.path_resolve(\"%.200s\") could not be resolved", RNA_struct_identifier(self->ptr.type), path);
+ return NULL;
+ }
}
-static PyObject *pyrna_struct_path_to_id(BPy_StructRNA *self, PyObject *args)
+static char pyrna_struct_path_from_id_doc[] =
+".. method:: path_from_id(property=\"\")\n"
+"\n"
+" Returns the data path from the ID to this object (string).\n"
+"\n"
+" :arg property: Optional property name which can be used if the path is to a property of this object.\n"
+" :type property: string\n"
+" :return: The path from :class:`bpy_struct.id_data` to this struct and property (when given).\n"
+" :rtype: str";
+
+static PyObject *pyrna_struct_path_from_id(BPy_StructRNA *self, PyObject *args)
{
char *name= NULL;
char *path;
PropertyRNA *prop;
PyObject *ret;
- if (!PyArg_ParseTuple(args, "|s:path_to_id", &name))
+ if (!PyArg_ParseTuple(args, "|s:path_from_id", &name))
return NULL;
if(name) {
prop= RNA_struct_find_property(&self->ptr, name);
if(prop==NULL) {
- PyErr_Format(PyExc_TypeError, "%.200s.path_to_id(\"%.200s\") not found", RNA_struct_identifier(self->ptr.type), name);
+ PyErr_Format(PyExc_TypeError, "%.200s.path_from_id(\"%.200s\") not found", RNA_struct_identifier(self->ptr.type), name);
return NULL;
}
@@ -1879,8 +2270,8 @@ static PyObject *pyrna_struct_path_to_id(BPy_StructRNA *self, PyObject *args)
}
if(path==NULL) {
- if(name) PyErr_Format(PyExc_TypeError, "%.200s.path_to_id(\"%s\") found but does not support path creation", RNA_struct_identifier(self->ptr.type), name);
- else PyErr_Format(PyExc_TypeError, "%.200s.path_to_id() does not support path creation for this type", RNA_struct_identifier(self->ptr.type));
+ if(name) PyErr_Format(PyExc_TypeError, "%.200s.path_from_id(\"%s\") found but does not support path creation", RNA_struct_identifier(self->ptr.type), name);
+ else PyErr_Format(PyExc_TypeError, "%.200s.path_from_id() does not support path creation for this type", RNA_struct_identifier(self->ptr.type));
return NULL;
}
@@ -1890,14 +2281,15 @@ static PyObject *pyrna_struct_path_to_id(BPy_StructRNA *self, PyObject *args)
return ret;
}
-static PyObject *pyrna_struct_recast_type(BPy_StructRNA *self, PyObject *args)
-{
- PointerRNA r_ptr;
- RNA_pointer_recast(&self->ptr, &r_ptr);
- return pyrna_struct_CreatePyObject(&r_ptr);
-}
+static char pyrna_prop_path_from_id_doc[] =
+".. method:: path_from_id()\n"
+"\n"
+" Returns the data path from the ID to this property (string).\n"
+"\n"
+" :return: The path from :class:`bpy_struct.id_data` to this property.\n"
+" :rtype: str";
-static PyObject *pyrna_prop_path_to_id(BPy_PropertyRNA *self)
+static PyObject *pyrna_prop_path_from_id(BPy_PropertyRNA *self)
{
char *path;
PropertyRNA *prop = self->prop;
@@ -1906,7 +2298,7 @@ static PyObject *pyrna_prop_path_to_id(BPy_PropertyRNA *self)
path= RNA_path_from_ID_to_property(&self->ptr, self->prop);
if(path==NULL) {
- PyErr_Format(PyExc_TypeError, "%.200s.%.200s.path_to_id() does not support path creation for this type", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(prop));
+ PyErr_Format(PyExc_TypeError, "%.200s.%.200s.path_from_id() does not support path creation for this type", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(prop));
return NULL;
}
@@ -1916,6 +2308,21 @@ static PyObject *pyrna_prop_path_to_id(BPy_PropertyRNA *self)
return ret;
}
+static char pyrna_struct_type_recast_doc[] =
+".. method:: type_recast()\n"
+"\n"
+" Return a new instance, this is needed because types such as textures can be changed at runtime.\n"
+"\n"
+" :return: a new instance of this object with the type initialized again.\n"
+" :rtype: subclass of :class:`bpy_struct`";
+
+static PyObject *pyrna_struct_type_recast(BPy_StructRNA *self, PyObject *args)
+{
+ PointerRNA r_ptr;
+ RNA_pointer_recast(&self->ptr, &r_ptr);
+ return pyrna_struct_CreatePyObject(&r_ptr);
+}
+
static void pyrna_dir_members_py(PyObject *list, PyObject *self)
{
PyObject *dict;
@@ -2026,7 +2433,7 @@ static PyObject *pyrna_struct_getattro( BPy_StructRNA *self, PyObject *pyname )
if(name[0]=='_') { // rna can't start with a "_", so for __dict__ and similar we can skip using rna lookups
/* annoying exception, maybe we need to have different types for this... */
- if((strcmp(name, "__getitem__")==0 || strcmp(name, "__setitem__")==0) && !RNA_struct_idproperties_check(self->ptr.type)) {
+ if((strcmp(name, "__getitem__")==0 || strcmp(name, "__setitem__")==0) && !RNA_struct_idprops_check(self->ptr.type)) {
PyErr_SetString(PyExc_AttributeError, "bpy_struct: no __getitem__ support for this type");
ret = NULL;
}
@@ -2036,7 +2443,7 @@ static PyObject *pyrna_struct_getattro( BPy_StructRNA *self, PyObject *pyname )
}
else if ((prop = RNA_struct_find_property(&self->ptr, name))) {
ret = pyrna_prop_to_py(&self->ptr, prop);
- }
+ }
/* RNA function only if callback is declared (no optional functions) */
else if ((func = RNA_struct_find_function(&self->ptr, name)) && RNA_function_defined(func)) {
ret = pyrna_func_to_py((BPy_DummyPointerRNA *)self, func);
@@ -2050,28 +2457,39 @@ static PyObject *pyrna_struct_getattro( BPy_StructRNA *self, PyObject *pyname )
else {
PointerRNA newptr;
ListBase newlb;
+ short newtype;
- int done= CTX_data_get(C, name, &newptr, &newlb);
+ int done= CTX_data_get(C, name, &newptr, &newlb, &newtype);
if(done==1) { /* found */
- if (newptr.data) {
- ret = pyrna_struct_CreatePyObject(&newptr);
- }
- else if (newlb.first) {
- CollectionPointerLink *link;
- PyObject *linkptr;
-
- ret = PyList_New(0);
-
- for(link=newlb.first; link; link=link->next) {
- linkptr= pyrna_struct_CreatePyObject(&link->ptr);
- PyList_Append(ret, linkptr);
- Py_DECREF(linkptr);
+ switch(newtype) {
+ case CTX_DATA_TYPE_POINTER:
+ if(newptr.data == NULL) {
+ ret= Py_None;
+ Py_INCREF(ret);
}
- }
- else {
- ret = Py_None;
- Py_INCREF(ret);
+ else {
+ ret= pyrna_struct_CreatePyObject(&newptr);
+ }
+ break;
+ case CTX_DATA_TYPE_COLLECTION:
+ {
+ CollectionPointerLink *link;
+ PyObject *linkptr;
+
+ ret = PyList_New(0);
+
+ for(link=newlb.first; link; link=link->next) {
+ linkptr= pyrna_struct_CreatePyObject(&link->ptr);
+ PyList_Append(ret, linkptr);
+ Py_DECREF(linkptr);
+ }
+ }
+ break;
+ default:
+ /* should never happen */
+ PyErr_Format(PyExc_AttributeError, "bpy_struct: Context type invalid %d, can't get \"%.200s\" from context", newtype, name);
+ ret= NULL;
}
}
else if (done==-1) { /* found but not set */
@@ -2119,17 +2537,49 @@ static int pyrna_struct_pydict_contains(PyObject *self, PyObject *pyname)
static int pyrna_struct_setattro( BPy_StructRNA *self, PyObject *pyname, PyObject *value )
{
char *name = _PyUnicode_AsString(pyname);
- PropertyRNA *prop = RNA_struct_find_property(&self->ptr, name);
-
- if (prop==NULL) {
- return PyObject_GenericSetAttr((PyObject *)self, pyname, value);
- } else if (!RNA_property_editable_flag(&self->ptr, prop)) {
- PyErr_Format( PyExc_AttributeError, "bpy_struct: attribute \"%.200s\" from \"%.200s\" is read-only", RNA_property_identifier(prop), RNA_struct_identifier(self->ptr.type) );
- return -1;
+ PropertyRNA *prop= NULL;
+
+ if (name[0] != '_' && (prop= RNA_struct_find_property(&self->ptr, name))) {
+ if (!RNA_property_editable_flag(&self->ptr, prop)) {
+ PyErr_Format( PyExc_AttributeError, "bpy_struct: attribute \"%.200s\" from \"%.200s\" is read-only", RNA_property_identifier(prop), RNA_struct_identifier(self->ptr.type) );
+ return -1;
+ }
}
-
+ else if (self->ptr.type == &RNA_Context) {
+ /* code just raises correct error, context prop's cant be set, unless its apart of the py class */
+ bContext *C = self->ptr.data;
+ if(C==NULL) {
+ PyErr_Format(PyExc_AttributeError, "bpy_struct: Context is 'NULL', can't set \"%.200s\" from context", name);
+ return -1;
+ }
+ else {
+ PointerRNA newptr;
+ ListBase newlb;
+ short newtype;
+
+ int done= CTX_data_get(C, name, &newptr, &newlb, &newtype);
+
+ if(done==1) {
+ PyErr_Format(PyExc_AttributeError, "bpy_struct: Context property \"%.200s\" is read-only", name);
+ BLI_freelistN(&newlb);
+ return -1;
+ }
+
+ BLI_freelistN(&newlb);
+ }
+ }
+
/* pyrna_py_to_prop sets its own exceptions */
- return pyrna_py_to_prop(&self->ptr, prop, NULL, NULL, value, "bpy_struct: item.attr = val:");
+ if(prop) {
+ if(value == NULL) {
+ PyErr_SetString(PyExc_AttributeError, "bpy_struct: del not supported");
+ return -1;
+ }
+ return pyrna_py_to_prop(&self->ptr, prop, NULL, NULL, value, "bpy_struct: item.attr = val:");
+ }
+ else {
+ return PyObject_GenericSetAttr((PyObject *)self, pyname, value);
+ }
}
static PyObject *pyrna_prop_dir(BPy_PropertyRNA *self)
@@ -2194,6 +2644,11 @@ static int pyrna_prop_collection_setattro( BPy_PropertyRNA *self, PyObject *pyna
PropertyRNA *prop;
PointerRNA r_ptr;
+ if(value == NULL) {
+ PyErr_SetString(PyExc_AttributeError, "bpy_prop: del not supported");
+ return -1;
+ }
+
if(RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
if ((prop = RNA_struct_find_property(&r_ptr, name))) {
/* pyrna_py_to_prop sets its own exceptions */
@@ -2262,8 +2717,9 @@ static PyObject *pyrna_prop_move(BPy_PropertyRNA *self, PyObject *args)
return ret;
}
-static PyObject *pyrna_struct_get_id_data(BPy_StructRNA *self)
+static PyObject *pyrna_struct_get_id_data(BPy_DummyPointerRNA *self)
{
+ /* used for struct and pointer since both have a ptr */
if(self->ptr.id.data) {
PointerRNA id_ptr;
RNA_id_pointer_create((ID *)self->ptr.id.data, &id_ptr);
@@ -2276,15 +2732,15 @@ static PyObject *pyrna_struct_get_id_data(BPy_StructRNA *self)
/*****************************************************************************/
/* Python attributes get/set structure: */
/*****************************************************************************/
-#if 0
+
static PyGetSetDef pyrna_prop_getseters[] = {
- {"active", (getter)pyrna_prop_get_active, (setter)pyrna_prop_set_active, "", NULL},
+ {"id_data", (getter)pyrna_struct_get_id_data, (setter)NULL, "The :class:`ID` object this datablock is from or None, (not available for all data types)", NULL},
{NULL,NULL,NULL,NULL,NULL} /* Sentinel */
};
-#endif
+
static PyGetSetDef pyrna_struct_getseters[] = {
- {"id_data", (getter)pyrna_struct_get_id_data, (setter)NULL, "The ID data this datablock is from, (not available for all data)", NULL},
+ {"id_data", (getter)pyrna_struct_get_id_data, (setter)NULL, "The :class:`ID` object this datablock is from or None, (not available for all data types)", NULL},
{NULL,NULL,NULL,NULL,NULL} /* Sentinel */
};
@@ -2361,6 +2817,18 @@ static PyObject *pyrna_prop_values(BPy_PropertyRNA *self)
return ret;
}
+static char pyrna_struct_get_doc[] =
+".. method:: get(key, default=None)\n"
+"\n"
+" Returns the value of the custom property assigned to key or default when not found (matches pythons dictionary function of the same name).\n"
+"\n"
+" :arg key: The key assosiated with the custom property.\n"
+" :type key: string\n"
+" :arg default: Optional argument for the value to return if *key* is not found.\n"
+// " :type default: Undefined\n"
+"\n"
+" .. note:: Only :class:`ID`, :class:`Bone` and :class:`PoseBone` classes support custom properties.\n";
+
static PyObject *pyrna_struct_get(BPy_StructRNA *self, PyObject *args)
{
IDProperty *group, *idprop;
@@ -2372,12 +2840,12 @@ static PyObject *pyrna_struct_get(BPy_StructRNA *self, PyObject *args)
return NULL;
/* mostly copied from BPy_IDGroup_Map_GetItem */
- if(RNA_struct_idproperties_check(self->ptr.type)==0) {
+ if(RNA_struct_idprops_check(self->ptr.type)==0) {
PyErr_SetString( PyExc_TypeError, "this type doesn't support IDProperties");
return NULL;
}
- group= RNA_struct_idproperties(&self->ptr, 0);
+ group= RNA_struct_idprops(&self->ptr, 0);
if(group) {
idprop= IDP_GetPropertyFromGroup(group, key);
@@ -2389,6 +2857,16 @@ static PyObject *pyrna_struct_get(BPy_StructRNA *self, PyObject *args)
return def;
}
+static char pyrna_struct_as_pointer_doc[] =
+".. method:: as_pointer()\n"
+"\n"
+" Returns capsule which holds a pointer to blenders internal data\n"
+"\n"
+" :return: capsule with a name set from the struct type.\n"
+" :rtype: PyCapsule\n"
+"\n"
+" .. note:: This is intended only for advanced script writers who need to pass blender data to their own C/Python modules.\n";
+
static PyObject *pyrna_struct_as_pointer(BPy_StructRNA *self)
{
if(self->ptr.data)
@@ -2705,41 +3183,53 @@ PyObject *pyrna_prop_collection_iter(BPy_PropertyRNA *self)
static struct PyMethodDef pyrna_struct_methods[] = {
/* only for PointerRNA's with ID'props */
- {"keys", (PyCFunction)pyrna_struct_keys, METH_NOARGS, NULL},
- {"values", (PyCFunction)pyrna_struct_values, METH_NOARGS, NULL},
- {"items", (PyCFunction)pyrna_struct_items, METH_NOARGS, NULL},
-
- {"get", (PyCFunction)pyrna_struct_get, METH_VARARGS, NULL},
-
- {"as_pointer", (PyCFunction)pyrna_struct_as_pointer, METH_NOARGS, NULL},
-
- /* maybe this become and ID function */
- {"keyframe_insert", (PyCFunction)pyrna_struct_keyframe_insert, METH_VARARGS, NULL},
- {"keyframe_delete", (PyCFunction)pyrna_struct_keyframe_delete, METH_VARARGS, NULL},
- {"driver_add", (PyCFunction)pyrna_struct_driver_add, METH_VARARGS, NULL},
- {"is_property_set", (PyCFunction)pyrna_struct_is_property_set, METH_VARARGS, NULL},
- {"is_property_hidden", (PyCFunction)pyrna_struct_is_property_hidden, METH_VARARGS, NULL},
- {"path_resolve", (PyCFunction)pyrna_struct_path_resolve, METH_O, NULL},
- {"path_to_id", (PyCFunction)pyrna_struct_path_to_id, METH_VARARGS, NULL},
- {"recast_type", (PyCFunction)pyrna_struct_recast_type, METH_NOARGS, NULL},
+ {"keys", (PyCFunction)pyrna_struct_keys, METH_NOARGS, pyrna_struct_keys_doc},
+ {"values", (PyCFunction)pyrna_struct_values, METH_NOARGS, pyrna_struct_values_doc},
+ {"items", (PyCFunction)pyrna_struct_items, METH_NOARGS, pyrna_struct_items_doc},
+
+ {"get", (PyCFunction)pyrna_struct_get, METH_VARARGS, pyrna_struct_get_doc},
+
+ {"as_pointer", (PyCFunction)pyrna_struct_as_pointer, METH_NOARGS, pyrna_struct_as_pointer_doc},
+
+ {"keyframe_insert", (PyCFunction)pyrna_struct_keyframe_insert, METH_VARARGS|METH_KEYWORDS, pyrna_struct_keyframe_insert_doc},
+ {"keyframe_delete", (PyCFunction)pyrna_struct_keyframe_delete, METH_VARARGS|METH_KEYWORDS, pyrna_struct_keyframe_delete_doc},
+ {"driver_add", (PyCFunction)pyrna_struct_driver_add, METH_VARARGS, pyrna_struct_driver_add_doc},
+ {"driver_remove", (PyCFunction)pyrna_struct_driver_remove, METH_VARARGS, pyrna_struct_driver_remove_doc},
+ {"is_property_set", (PyCFunction)pyrna_struct_is_property_set, METH_VARARGS, pyrna_struct_is_property_set_doc},
+ {"is_property_hidden", (PyCFunction)pyrna_struct_is_property_hidden, METH_VARARGS, pyrna_struct_is_property_hidden_doc},
+ {"path_resolve", (PyCFunction)pyrna_struct_path_resolve, METH_VARARGS, pyrna_struct_path_resolve_doc},
+ {"path_from_id", (PyCFunction)pyrna_struct_path_from_id, METH_VARARGS, pyrna_struct_path_from_id_doc},
+ {"type_recast", (PyCFunction)pyrna_struct_type_recast, METH_NOARGS, pyrna_struct_type_recast_doc},
{"__dir__", (PyCFunction)pyrna_struct_dir, METH_NOARGS, NULL},
/* experemental */
{"callback_add", (PyCFunction)pyrna_callback_add, METH_VARARGS, NULL},
{"callback_remove", (PyCFunction)pyrna_callback_remove, METH_VARARGS, NULL},
+ /* class methods, only valid for subclasses */
+ {"BoolProperty", (PyCFunction)BPy_BoolProperty, METH_VARARGS|METH_KEYWORDS|METH_CLASS, BPy_BoolProperty_doc},
+ {"BoolVectorProperty", (PyCFunction)BPy_BoolVectorProperty, METH_VARARGS|METH_KEYWORDS|METH_CLASS, BPy_BoolVectorProperty_doc},
+ {"IntProperty", (PyCFunction)BPy_IntProperty, METH_VARARGS|METH_KEYWORDS|METH_CLASS, BPy_IntProperty_doc},
+ {"IntVectorProperty", (PyCFunction)BPy_IntVectorProperty, METH_VARARGS|METH_KEYWORDS|METH_CLASS, BPy_IntVectorProperty_doc},
+ {"FloatProperty", (PyCFunction)BPy_FloatProperty, METH_VARARGS|METH_KEYWORDS|METH_CLASS, BPy_FloatProperty_doc},
+ {"FloatVectorProperty", (PyCFunction)BPy_FloatVectorProperty, METH_VARARGS|METH_KEYWORDS|METH_CLASS, BPy_FloatVectorProperty_doc},
+ {"StringProperty", (PyCFunction)BPy_StringProperty, METH_VARARGS|METH_KEYWORDS|METH_CLASS, BPy_StringProperty_doc},
+ {"EnumProperty", (PyCFunction)BPy_EnumProperty, METH_VARARGS|METH_KEYWORDS|METH_CLASS, BPy_EnumProperty_doc},
+ {"PointerProperty", (PyCFunction)BPy_PointerProperty, METH_VARARGS|METH_KEYWORDS|METH_CLASS, BPy_PointerProperty_doc},
+ {"CollectionProperty", (PyCFunction)BPy_CollectionProperty, METH_VARARGS|METH_KEYWORDS|METH_CLASS, BPy_CollectionProperty_doc},
+
+ {"RemoveProperty", (PyCFunction)BPy_RemoveProperty, METH_VARARGS|METH_KEYWORDS|METH_CLASS, BPy_RemoveProperty_doc},
+
{NULL, NULL, 0, NULL}
};
static struct PyMethodDef pyrna_prop_methods[] = {
- {"path_to_id", (PyCFunction)pyrna_prop_path_to_id, METH_NOARGS, NULL},
+ {"path_from_id", (PyCFunction)pyrna_prop_path_from_id, METH_NOARGS, pyrna_prop_path_from_id_doc},
{"__dir__", (PyCFunction)pyrna_prop_dir, METH_NOARGS, NULL},
{NULL, NULL, 0, NULL}
};
static struct PyMethodDef pyrna_prop_array_methods[] = {
- {"foreach_get", (PyCFunction)pyrna_prop_foreach_get, METH_VARARGS, NULL},
- {"foreach_set", (PyCFunction)pyrna_prop_foreach_set, METH_VARARGS, NULL},
{NULL, NULL, 0, NULL}
};
@@ -2764,37 +3254,47 @@ static struct PyMethodDef pyrna_prop_collection_methods[] = {
* todo - also accept useful args */
static PyObject * pyrna_struct_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
- BPy_StructRNA *base = NULL;
+ BPy_StructRNA *base;
if (!PyArg_ParseTuple(args, "O!:bpy_struct.__new__", &pyrna_struct_Type, &base))
return NULL;
-
- if (type == &pyrna_struct_Type) {
- return pyrna_struct_CreatePyObject(&base->ptr);
- } else {
+
+ if (type == Py_TYPE(base)) {
+ Py_INCREF(base);
+ return (PyObject *)base;
+ } else if (PyType_IsSubtype(type, &pyrna_struct_Type)) {
BPy_StructRNA *ret = (BPy_StructRNA *) type->tp_alloc(type, 0);
ret->ptr = base->ptr;
return (PyObject *)ret;
}
+ else {
+ PyErr_Format(PyExc_TypeError, "bpy_struct.__new__(type): type '%.200s' is not a subtype of bpy_struct.", type->tp_name);
+ return NULL;
+ }
}
/* only needed for subtyping, so a new class gets a valid BPy_StructRNA
* todo - also accept useful args */
static PyObject * pyrna_prop_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
- BPy_PropertyRNA *base = NULL;
+ BPy_PropertyRNA *base;
- if (!PyArg_ParseTuple(args, "O!:Base BPy_PropertyRNA", &pyrna_prop_Type, &base))
+ if (!PyArg_ParseTuple(args, "O!:bpy_prop.__new__", &pyrna_prop_Type, &base))
return NULL;
- if (ELEM3(type, &pyrna_prop_Type, &pyrna_prop_array_Type, &pyrna_prop_collection_Type)) {
- return pyrna_prop_CreatePyObject(&base->ptr, base->prop);
- } else {
+ if (type == Py_TYPE(base)) {
+ Py_INCREF(base);
+ return (PyObject *)base;
+ } else if (PyType_IsSubtype(type, &pyrna_prop_Type)) {
BPy_PropertyRNA *ret = (BPy_PropertyRNA *) type->tp_alloc(type, 0);
ret->ptr = base->ptr;
ret->prop = base->prop;
return (PyObject *)ret;
}
+ else {
+ PyErr_Format(PyExc_TypeError, "bpy_prop.__new__(type): type '%.200s' is not a subtype of bpy_prop.", type->tp_name);
+ return NULL;
+ }
}
PyObject *pyrna_param_to_py(PointerRNA *ptr, ParameterList *parms, PropertyRNA *prop, void *data)
@@ -3198,7 +3698,7 @@ PyTypeObject pyrna_struct_Type = {
( hashfunc )pyrna_struct_hash, /* hashfunc tp_hash; */
NULL, /* ternaryfunc tp_call; */
- NULL, /* reprfunc tp_str; */
+ (reprfunc) pyrna_struct_str, /* reprfunc tp_str; */
( getattrofunc ) pyrna_struct_getattro, /* getattrofunc tp_getattro; */
( setattrofunc ) pyrna_struct_setattro, /* setattrofunc tp_setattro; */
@@ -3261,11 +3761,11 @@ PyTypeObject pyrna_prop_Type = {
0, /* tp_itemsize */
/* methods */
NULL, /* tp_dealloc */
- NULL, /* printfunc tp_print; */
+ NULL, /* printfunc tp_print; */
NULL, /* getattrfunc tp_getattr; */
NULL, /* setattrfunc tp_setattr; */
NULL, /* tp_compare */ /* DEPRECATED in python 3.0! */
- ( reprfunc ) pyrna_prop_repr, /* tp_repr */
+ (reprfunc) pyrna_prop_repr, /* tp_repr */
/* Method suites for standard classes */
@@ -3275,9 +3775,9 @@ PyTypeObject pyrna_prop_Type = {
/* More standard operations (here for binary compatibility) */
- NULL, /* hashfunc tp_hash; */
+ ( hashfunc ) pyrna_prop_hash, /* hashfunc tp_hash; */
NULL, /* ternaryfunc tp_call; */
- NULL, /* reprfunc tp_str; */
+ (reprfunc) pyrna_prop_str, /* reprfunc tp_str; */
/* will only use these if this is a subtype of a py class */
NULL, /* getattrofunc tp_getattro; */
@@ -3312,7 +3812,7 @@ PyTypeObject pyrna_prop_Type = {
/*** Attribute descriptor and subclassing stuff ***/
pyrna_prop_methods, /* struct PyMethodDef *tp_methods; */
NULL, /* struct PyMemberDef *tp_members; */
- NULL /*pyrna_prop_getseters*/, /* struct PyGetSetDef *tp_getset; */
+ pyrna_prop_getseters, /* struct PyGetSetDef *tp_getset; */
NULL, /* struct _typeobject *tp_base; */
NULL, /* PyObject *tp_dict; */
NULL, /* descrgetfunc tp_descr_get; */
@@ -3349,7 +3849,7 @@ PyTypeObject pyrna_prop_array_Type = {
/* Method suites for standard classes */
- NULL, /* PyNumberMethods *tp_as_number; */
+ &pyrna_prop_array_as_number, /* PyNumberMethods *tp_as_number; */
&pyrna_prop_array_as_sequence, /* PySequenceMethods *tp_as_sequence; */
&pyrna_prop_array_as_mapping, /* PyMappingMethods *tp_as_mapping; */
@@ -3429,7 +3929,7 @@ PyTypeObject pyrna_prop_collection_Type = {
/* Method suites for standard classes */
- NULL, /* PyNumberMethods *tp_as_number; */
+ &pyrna_prop_collection_as_number, /* PyNumberMethods *tp_as_number; */
&pyrna_prop_collection_as_sequence, /* PySequenceMethods *tp_as_sequence; */
&pyrna_prop_collection_as_mapping, /* PyMappingMethods *tp_as_mapping; */
@@ -3494,26 +3994,11 @@ PyTypeObject pyrna_prop_collection_Type = {
NULL
};
-static struct PyMethodDef pyrna_struct_subtype_methods[] = {
- {"BoolProperty", (PyCFunction)BPy_BoolProperty, METH_VARARGS|METH_KEYWORDS, ""},
- {"BoolVectorProperty", (PyCFunction)BPy_BoolVectorProperty, METH_VARARGS|METH_KEYWORDS, ""},
- {"IntProperty", (PyCFunction)BPy_IntProperty, METH_VARARGS|METH_KEYWORDS, ""},
- {"IntVectorProperty", (PyCFunction)BPy_IntVectorProperty, METH_VARARGS|METH_KEYWORDS, ""},
- {"FloatProperty", (PyCFunction)BPy_FloatProperty, METH_VARARGS|METH_KEYWORDS, ""},
- {"FloatVectorProperty", (PyCFunction)BPy_FloatVectorProperty, METH_VARARGS|METH_KEYWORDS, ""},
- {"StringProperty", (PyCFunction)BPy_StringProperty, METH_VARARGS|METH_KEYWORDS, ""},
- {"EnumProperty", (PyCFunction)BPy_EnumProperty, METH_VARARGS|METH_KEYWORDS, ""},
- {"PointerProperty", (PyCFunction)BPy_PointerProperty, METH_VARARGS|METH_KEYWORDS, ""},
- {"CollectionProperty", (PyCFunction)BPy_CollectionProperty, METH_VARARGS|METH_KEYWORDS, ""},
-
-// {"__get_rna", (PyCFunction)BPy_GetStructRNA, METH_NOARGS, ""},
- {NULL, NULL, 0, NULL}
-};
-
static void pyrna_subtype_set_rna(PyObject *newclass, StructRNA *srna)
{
PointerRNA ptr;
PyObject *item;
+ PyObject *newclass_dict= ((PyTypeObject *)newclass)->tp_dict;
Py_INCREF(newclass);
@@ -3532,20 +4017,9 @@ static void pyrna_subtype_set_rna(PyObject *newclass, StructRNA *srna)
item = pyrna_struct_CreatePyObject(&ptr);
//item = PyCapsule_New(srna, NULL, NULL);
- PyDict_SetItemString(((PyTypeObject *)newclass)->tp_dict, "bl_rna", item);
+ PyDict_SetItemString(newclass_dict, "bl_rna", item);
Py_DECREF(item);
/* done with rna instance */
-
- /* attach functions into the class
- * so you can do... bpy.types.Scene.SomeFunction()
- */
- {
- PyMethodDef *ml;
-
- for(ml= pyrna_struct_subtype_methods; ml->ml_name; ml++){
- PyObject_SetAttrString(newclass, ml->ml_name, PyCFunction_New(ml, newclass));
- }
- }
}
static PyObject* pyrna_srna_Subtype(StructRNA *srna);
@@ -3632,30 +4106,37 @@ static PyObject* pyrna_srna_Subtype(StructRNA *srna)
{
PyObject *newclass = NULL;
+ /* stupid/simple case */
if (srna == NULL) {
newclass= NULL; /* Nothing to do */
- } else if ((newclass= RNA_struct_py_type_get(srna))) {
+ } /* the class may have alredy been declared & allocated */
+ else if ((newclass= RNA_struct_py_type_get(srna))) {
Py_INCREF(newclass);
- } else if ((newclass= pyrna_srna_ExternalType(srna))) {
+ } /* check if bpy_types.py module has the class defined in it */
+ else if ((newclass= pyrna_srna_ExternalType(srna))) {
pyrna_subtype_set_rna(newclass, srna);
Py_INCREF(newclass);
- } else {
+ } /* create a new class instance with the C api
+ * maintly for the purposing of matching the C/rna type hierarchy */
+ else {
/* subclass equivelents
- class myClass(myBase):
some='value' # or ...
- myClass = type(name='myClass', bases=(myBase,), dict={'__module__':'bpy.types'})
*/
- /* Assume RNA_struct_py_type_get(srna) was alredy checked */
+ /* Assume RNA_struct_py_type_get(srna) was already checked */
PyObject *py_base= pyrna_srna_PyBase(srna);
const char *idname= RNA_struct_identifier(srna);
- const char *descr= RNA_struct_ui_description(srna);
-
- if(!descr) descr= "(no docs)";
+
+ /* remove __doc__ for now */
+ // const char *descr= RNA_struct_ui_description(srna);
+ // if(!descr) descr= "(no docs)";
+ // "__doc__",descr
/* always use O not N when calling, N causes refcount errors */
- newclass = PyObject_CallFunction( (PyObject*)&PyType_Type, "s(O){sssss()}", idname, py_base, "__module__","bpy.types", "__doc__",descr, "__slots__");
+ newclass = PyObject_CallFunction((PyObject*)&PyType_Type, "s(O){sss()}", idname, py_base, "__module__","bpy.types", "__slots__");
/* newclass will now have 2 ref's, ???, probably 1 is internal since decrefing here segfaults */
/* PyObSpit("new class ref", newclass); */
@@ -3664,7 +4145,8 @@ static PyObject* pyrna_srna_Subtype(StructRNA *srna)
/* srna owns one, and the other is owned by the caller */
pyrna_subtype_set_rna(newclass, srna);
- Py_DECREF(newclass); /* let srna own */
+ // XXX, adding this back segfaults blender on load.
+ // Py_DECREF(newclass); /* let srna own */
}
else {
/* this should not happen */
@@ -3697,7 +4179,8 @@ static PyObject* pyrna_struct_Subtype(PointerRNA *ptr)
PyObject *pyrna_struct_CreatePyObject( PointerRNA *ptr )
{
BPy_StructRNA *pyrna= NULL;
-
+
+ /* note: don't rely on this to return None since NULL data with a valid type can often crash */
if (ptr->data==NULL && ptr->type==NULL) { /* Operator RNA has NULL data */
Py_RETURN_NONE;
}
@@ -3838,6 +4321,9 @@ static PyObject *pyrna_basetype_getattro( BPy_BaseTypeRNA *self, PyObject *pynam
}
static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self);
+static PyObject *pyrna_basetype_register(PyObject *self, PyObject *py_class);
+static PyObject *pyrna_basetype_unregister(PyObject *self, PyObject *py_class);
+
static struct PyMethodDef pyrna_basetype_methods[] = {
{"__dir__", (PyCFunction)pyrna_basetype_dir, METH_NOARGS, ""},
{"register", (PyCFunction)pyrna_basetype_register, METH_O, ""},
@@ -3907,18 +4393,18 @@ StructRNA *pyrna_struct_as_srna(PyObject *self, int parent, const char *error_pr
}
if(py_srna==NULL) {
- PyErr_Format(PyExc_SystemError, "%.200s internal error, self of type '%.200s' had no bl_rna attribute, should never happen", error_prefix, Py_TYPE(self)->tp_name);
+ PyErr_Format(PyExc_SystemError, "%.200s, missing bl_rna attribute from '%.200s' instance (may not be registered)", error_prefix, Py_TYPE(self)->tp_name);
return NULL;
}
if(!BPy_StructRNA_Check(py_srna)) {
- PyErr_Format(PyExc_SystemError, "%.200s internal error, bl_rna was of type '%.200s', instead of %.200s instance", error_prefix, Py_TYPE(py_srna)->tp_name, pyrna_struct_Type.tp_name);
+ PyErr_Format(PyExc_SystemError, "%.200s, bl_rna attribute wrong type '%.200s' on '%.200s'' instance", error_prefix, Py_TYPE(py_srna)->tp_name, Py_TYPE(self)->tp_name);
Py_DECREF(py_srna);
return NULL;
}
if(py_srna->ptr.type != &RNA_Struct) {
- PyErr_Format(PyExc_SystemError, "%.200s internal error, bl_rna was not a RNA_Struct type of rna struct", error_prefix);
+ PyErr_Format(PyExc_SystemError, "%.200s, bl_rna attribute not a RNA_Struct, on '%.200s'' instance", error_prefix, Py_TYPE(self)->tp_name);
Py_DECREF(py_srna);
return NULL;
}
@@ -3966,7 +4452,6 @@ static int deferred_register_prop(StructRNA *srna, PyObject *item, PyObject *key
if(*_PyUnicode_AsString(key)=='_') {
PyErr_Format(PyExc_ValueError, "bpy_struct \"%.200s\" registration error: %.200s could not register because the property starts with an '_'\n", RNA_struct_identifier(srna), _PyUnicode_AsString(key));
- Py_DECREF(dummy_args);
return -1;
}
pyfunc = PyCapsule_GetPointer(py_func_ptr, NULL);
@@ -3987,8 +4472,6 @@ static int deferred_register_prop(StructRNA *srna, PyObject *item, PyObject *key
// PyLineSpit();
PyErr_Format(PyExc_ValueError, "bpy_struct \"%.200s\" registration error: %.200s could not register\n", RNA_struct_identifier(srna), _PyUnicode_AsString(key));
-
- Py_DECREF(dummy_args);
return -1;
}
}
@@ -4005,7 +4488,7 @@ static int deferred_register_prop(StructRNA *srna, PyObject *item, PyObject *key
return 0;
}
-int pyrna_deferred_register_props(StructRNA *srna, PyObject *class_dict)
+static int pyrna_deferred_register_props(StructRNA *srna, PyObject *class_dict)
{
PyObject *item, *key;
PyObject *order;
@@ -4015,12 +4498,10 @@ int pyrna_deferred_register_props(StructRNA *srna, PyObject *class_dict)
dummy_args = PyTuple_New(0);
- order= PyDict_GetItemString(class_dict, "order");
-
- if(order==NULL)
- PyErr_Clear();
-
- if(order && PyList_Check(order)) {
+ if( !PyDict_CheckExact(class_dict) &&
+ (order= PyDict_GetItemString(class_dict, "order")) &&
+ PyList_CheckExact(order)
+ ) {
for(pos= 0; pos<PyList_GET_SIZE(order); pos++) {
key= PyList_GET_ITEM(order, pos);
item= PyDict_GetItem(class_dict, key);
@@ -4043,6 +4524,49 @@ int pyrna_deferred_register_props(StructRNA *srna, PyObject *class_dict)
return 0;
}
+static int pyrna_deferred_register_class_recursive(StructRNA *srna, PyTypeObject *py_class)
+{
+ const int len= PyTuple_GET_SIZE(py_class->tp_bases);
+ int i, ret;
+
+ /* first scan base classes for registerable properties */
+ for(i=0; i<len; i++) {
+ PyTypeObject *py_superclass= (PyTypeObject *)PyTuple_GET_ITEM(py_class->tp_bases, i);
+
+ /* the rules for using these base classes are not clear,
+ * 'object' is ofcourse not worth looking into and
+ * existing subclasses of RNA would cause a lot more dictionary
+ * looping then is needed (SomeOperator would scan Operator.__dict__)
+ * which is harmless but not at all useful.
+ *
+ * So only scan base classes which are not subclasses if blender types.
+ * This best fits having 'mix-in' classes for operators and render engines.
+ * */
+ if( py_superclass != &PyBaseObject_Type &&
+ !PyObject_IsSubclass((PyObject *)py_superclass, (PyObject *)&pyrna_struct_Type)
+ ) {
+ ret= pyrna_deferred_register_class_recursive(srna, py_superclass);
+
+ if(ret != 0) {
+ return ret;
+ }
+ }
+ }
+
+ /* not register out own properties */
+ return pyrna_deferred_register_props(srna, py_class->tp_dict); /* getattr(..., "__dict__") returns a proxy */
+}
+
+int pyrna_deferred_register_class(StructRNA *srna, PyObject *py_class)
+{
+ /* Panels and Menus dont need this
+ * save some time and skip the checks here */
+ if(!RNA_struct_idprops_register_check(srna))
+ return 0;
+
+ return pyrna_deferred_register_class_recursive(srna, (PyTypeObject *)py_class);
+}
+
/*-------------------- Type Registration ------------------------*/
static int rna_function_arg_count(FunctionRNA *func)
@@ -4050,7 +4574,7 @@ static int rna_function_arg_count(FunctionRNA *func)
const ListBase *lb= RNA_function_defined_parameters(func);
PropertyRNA *parm;
Link *link;
- int count= 1;
+ int count= (RNA_function_flag(func) & FUNC_NO_SELF) ? 0 : 1;
for(link=lb->first; link; link=link->next) {
parm= (PropertyRNA*)link;
@@ -4071,7 +4595,7 @@ static int bpy_class_validate(PointerRNA *dummyptr, void *py_data, int *have_fun
const char *class_type= RNA_struct_identifier(srna);
PyObject *py_class= (PyObject*)py_data;
PyObject *base_class= RNA_struct_py_type_get(srna);
- PyObject *item, *fitem;
+ PyObject *item;
PyObject *py_arg_count;
int i, flag, arg_count, func_arg_count;
const char *py_class_name = ((PyTypeObject *)py_class)->tp_name; // __name__
@@ -4108,25 +4632,33 @@ static int bpy_class_validate(PointerRNA *dummyptr, void *py_data, int *have_fun
PyErr_Clear();
}
else {
- Py_DECREF(item); /* no need to keep a ref, the class owns it */
-
- if (PyMethod_Check(item))
- fitem= PyMethod_Function(item); /* py 2.x */
- else
- fitem= item; /* py 3.x */
-
- if (PyFunction_Check(fitem)==0) {
- PyErr_Format( PyExc_TypeError, "expected %.200s, %.200s class \"%.200s\" attribute to be a function", class_type, py_class_name, RNA_function_identifier(func));
- return -1;
+ Py_DECREF(item); /* no need to keep a ref, the class owns it (technically we should keep a ref but...) */
+ if(flag & FUNC_NO_SELF) {
+ if (PyMethod_Check(item)==0) {
+ PyErr_Format( PyExc_TypeError, "expected %.200s, %.200s class \"%.200s\" attribute to be a method, not a %.200s", class_type, py_class_name, RNA_function_identifier(func), Py_TYPE(item)->tp_name);
+ return -1;
+ }
+ item= ((PyMethodObject *)item)->im_func;
+ }
+ else {
+ if (PyFunction_Check(item)==0) {
+ PyErr_Format( PyExc_TypeError, "expected %.200s, %.200s class \"%.200s\" attribute to be a function, not a %.200s", class_type, py_class_name, RNA_function_identifier(func), Py_TYPE(item)->tp_name);
+ return -1;
+ }
}
func_arg_count= rna_function_arg_count(func);
if (func_arg_count >= 0) { /* -1 if we dont care*/
- py_arg_count = PyObject_GetAttrString(PyFunction_GET_CODE(fitem), "co_argcount");
+ py_arg_count = PyObject_GetAttrString(PyFunction_GET_CODE(item), "co_argcount");
arg_count = PyLong_AsSsize_t(py_arg_count);
Py_DECREF(py_arg_count);
+ /* note, the number of args we check for and the number of args we give to
+ * @classmethods are different (quirk of python), this is why rna_function_arg_count() doesn't return the value -1*/
+ if(flag & FUNC_NO_SELF)
+ func_arg_count++;
+
if (arg_count != func_arg_count) {
PyErr_Format( PyExc_AttributeError, "expected %.200s, %.200s class \"%.200s\" function to have %d args, found %d", class_type, py_class_name, RNA_function_identifier(func), func_arg_count, arg_count);
return -1;
@@ -4199,6 +4731,7 @@ static int bpy_class_call(PointerRNA *ptr, FunctionRNA *func, ParameterList *par
ParameterIterator iter;
PointerRNA funcptr;
int err= 0, i, flag, ret_len=0;
+ int is_static = RNA_function_flag(func) & FUNC_NO_SELF;
PropertyRNA *pret_single= NULL;
void *retdata_single= NULL;
@@ -4206,52 +4739,64 @@ static int bpy_class_call(PointerRNA *ptr, FunctionRNA *func, ParameterList *par
PyGILState_STATE gilstate;
bContext *C= BPy_GetContext(); // XXX - NEEDS FIXING, QUITE BAD.
- bpy_context_set(C, &gilstate);
-
+
py_class= RNA_struct_py_type_get(ptr->type);
- /* exception, operators store their PyObjects for re-use */
- if(ptr->data) {
- if(RNA_struct_is_a(ptr->type, &RNA_Operator)) {
- wmOperator *op= ptr->data;
- if(op->py_instance) {
- py_class_instance= op->py_instance;
- Py_INCREF(py_class_instance);
- }
- else {
- /* store the instance here once its created */
- py_class_instance_store= &op->py_instance;
- }
- }
+ /* rare case. can happen when registering subclasses */
+ if(py_class==NULL) {
+ fprintf(stderr, "bpy_class_call(): unable to get python class for rna struct '%.200s'\n", RNA_struct_identifier(ptr->type));
+ return -1;
}
- /* end exception */
-
- if(py_class_instance==NULL)
- py_srna= pyrna_struct_CreatePyObject(ptr);
- if(py_class_instance) {
- /* special case, instance is cached */
- }
- else if(py_srna == NULL) {
- py_class_instance = NULL;
- }
- else if(py_srna == Py_None) { /* probably wont ever happen but possible */
- Py_DECREF(py_srna);
- py_class_instance = NULL;
- }
- else {
- args = PyTuple_New(1);
- PyTuple_SET_ITEM(args, 0, py_srna);
- py_class_instance = PyObject_Call(py_class, args, NULL);
- Py_DECREF(args);
+ bpy_context_set(C, &gilstate);
- if(py_class_instance_store) {
- *py_class_instance_store = py_class_instance;
- Py_INCREF(py_class_instance);
+ if (!is_static) {
+ /* exception, operators store their PyObjects for re-use */
+ if(ptr->data) {
+ if(RNA_struct_is_a(ptr->type, &RNA_Operator)) {
+ wmOperator *op= ptr->data;
+ if(op->py_instance) {
+ py_class_instance= op->py_instance;
+ Py_INCREF(py_class_instance);
+ }
+ else {
+ /* store the instance here once its created */
+ py_class_instance_store= &op->py_instance;
+ }
+ }
+ }
+ /* end exception */
+
+ if(py_class_instance==NULL)
+ py_srna= pyrna_struct_CreatePyObject(ptr);
+
+ if(py_class_instance) {
+ /* special case, instance is cached */
+ }
+ else if(py_srna == NULL) {
+ py_class_instance = NULL;
+ }
+ else if(py_srna == Py_None) { /* probably wont ever happen but possible */
+ Py_DECREF(py_srna);
+ py_class_instance = NULL;
+ }
+ else {
+ args = PyTuple_New(1);
+ PyTuple_SET_ITEM(args, 0, py_srna);
+ py_class_instance= PyObject_Call(py_class, args, NULL);
+ Py_DECREF(args);
+
+ if(py_class_instance == NULL) {
+ err= -1; /* so the error is not overridden below */
+ }
+ else if(py_class_instance_store) {
+ *py_class_instance_store = py_class_instance;
+ Py_INCREF(py_class_instance);
+ }
}
}
- if (py_class_instance) { /* Initializing the class worked, now run its invoke function */
+ if (is_static || py_class_instance) { /* Initializing the class worked, now run its invoke function */
PyObject *item= PyObject_GetAttrString(py_class, RNA_function_identifier(func));
// flag= RNA_function_flag(func);
@@ -4259,12 +4804,19 @@ static int bpy_class_call(PointerRNA *ptr, FunctionRNA *func, ParameterList *par
RNA_pointer_create(NULL, &RNA_Function, func, &funcptr);
args = PyTuple_New(rna_function_arg_count(func)); /* first arg is included in 'item' */
- PyTuple_SET_ITEM(args, 0, py_class_instance);
+
+ if(is_static) {
+ i= 0;
+ }
+ else {
+ PyTuple_SET_ITEM(args, 0, py_class_instance);
+ i= 1;
+ }
RNA_parameter_list_begin(parms, &iter);
/* parse function parameters */
- for (i= 1; iter.valid; RNA_parameter_list_next(&iter)) {
+ for (; iter.valid; RNA_parameter_list_next(&iter)) {
parm= iter.parm;
flag= RNA_property_flag(parm);
@@ -4298,8 +4850,11 @@ static int bpy_class_call(PointerRNA *ptr, FunctionRNA *func, ParameterList *par
}
}
else {
- PyErr_Format(PyExc_RuntimeError, "could not create instance of %.200s to call callback function %.200s.", RNA_struct_identifier(ptr->type), RNA_function_identifier(func));
- err= -1;
+ /* the error may be alredy set if the class instance couldnt be created */
+ if(err != -1) {
+ PyErr_Format(PyExc_RuntimeError, "could not create instance of %.200s to call callback function %.200s.", RNA_struct_identifier(ptr->type), RNA_function_identifier(func));
+ err= -1;
+ }
}
if (ret == NULL) { /* covers py_class_instance failing too */
@@ -4392,7 +4947,16 @@ void pyrna_alloc_types(void)
prop = RNA_struct_find_property(&ptr, "structs");
RNA_PROP_BEGIN(&ptr, itemptr, prop) {
- Py_DECREF(pyrna_struct_Subtype(&itemptr));
+ PyObject *item= pyrna_struct_Subtype(&itemptr);
+ if(item == NULL) {
+ if(PyErr_Occurred()) {
+ PyErr_Print();
+ PyErr_Clear();
+ }
+ }
+ else {
+ Py_DECREF(item);
+ }
}
RNA_PROP_END;
@@ -4435,15 +4999,14 @@ void pyrna_free_types(void)
* - Should still be fixed - Campbell
* */
-PyObject *pyrna_basetype_register(PyObject *self, PyObject *py_class)
+static PyObject *pyrna_basetype_register(PyObject *self, PyObject *py_class)
{
bContext *C= NULL;
ReportList reports;
StructRegisterFunc reg;
StructRNA *srna;
StructRNA *srna_new;
- PyObject *item;
- const char *identifier= "";
+ const char *identifier;
if(PyDict_GetItemString(((PyTypeObject*)py_class)->tp_dict, "bl_rna")) {
PyErr_SetString(PyExc_AttributeError, "bpy.types.register(...): already registered as a subclass.");
@@ -4455,11 +5018,19 @@ PyObject *pyrna_basetype_register(PyObject *self, PyObject *py_class)
if(srna==NULL)
return NULL;
+ /* fails in cases, cant use this check but would like to :| */
+ /*
+ if(RNA_struct_py_type_get(srna)) {
+ PyErr_Format(PyExc_ValueError, "bpy.types.register(...): %.200s's parent class %.200s is alredy registered, this is not allowed.", ((PyTypeObject*)py_class)->tp_name, RNA_struct_identifier(srna));
+ return NULL;
+ }
+ */
+
/* check that we have a register callback for this type */
reg= RNA_struct_register(srna);
if(!reg) {
- PyErr_SetString(PyExc_ValueError, "bpy.types.register(...): expected a Type subclassed from a registerable rna type (no register supported).");
+ PyErr_Format(PyExc_ValueError, "bpy.types.register(...): expected a subclass of a registerable rna type (%.200s does not support registration).", RNA_struct_identifier(srna));
return NULL;
}
@@ -4469,12 +5040,7 @@ PyObject *pyrna_basetype_register(PyObject *self, PyObject *py_class)
/* call the register callback with reports & identifier */
BKE_reports_init(&reports, RPT_STORE);
- item= PyObject_GetAttrString(py_class, "__name__");
-
- if(item) {
- identifier= _PyUnicode_AsString(item);
- Py_DECREF(item); /* no need to keep a ref, the class owns it */
- }
+ identifier= ((PyTypeObject*)py_class)->tp_name;
srna_new= reg(C, &reports, py_class, identifier, bpy_class_validate, bpy_class_call, bpy_class_free);
@@ -4498,27 +5064,47 @@ PyObject *pyrna_basetype_register(PyObject *self, PyObject *py_class)
*
* item= PyObject_GetAttrString(py_class, "__dict__");
*/
- item= ((PyTypeObject*)py_class)->tp_dict;
- if(item) {
- if(pyrna_deferred_register_props(srna_new, item)!=0) {
- return NULL;
- }
- }
- else {
- PyErr_Clear();
- }
+ if(pyrna_deferred_register_class(srna_new, py_class)!=0)
+ return NULL;
Py_RETURN_NONE;
}
-PyObject *pyrna_basetype_unregister(PyObject *self, PyObject *py_class)
+
+static int pyrna_srna_contains_pointer_prop_srna(StructRNA *srna_props, StructRNA *srna, const char **prop_identifier)
+{
+ PointerRNA tptr;
+ PropertyRNA *iterprop;
+ RNA_pointer_create(NULL, &RNA_Struct, srna_props, &tptr);
+
+ iterprop= RNA_struct_find_property(&tptr, "properties");
+
+ RNA_PROP_BEGIN(&tptr, itemptr, iterprop) {
+ PropertyRNA *prop= itemptr.data;
+ if(RNA_property_type(prop) == PROP_POINTER) {
+ if (strcmp(RNA_property_identifier(prop), "rna_type") == 0) {
+ /* pass */
+ }
+ else if(RNA_property_pointer_type(&tptr, prop) == srna) {
+ *prop_identifier= RNA_property_identifier(prop);
+ return 1;
+ }
+ }
+ }
+ RNA_PROP_END;
+
+ return 0;
+}
+
+static PyObject *pyrna_basetype_unregister(PyObject *self, PyObject *py_class)
{
bContext *C= NULL;
StructUnregisterFunc unreg;
StructRNA *srna;
/*if(PyDict_GetItemString(((PyTypeObject*)py_class)->tp_dict, "bl_rna")==NULL) {
- PyErr_SetString(PyExc_ValueError, "bpy.types.unregister(): not a registered as a subclass.");
+ PWM_cursor_wait(0);
+yErr_SetString(PyExc_ValueError, "bpy.types.unregister(): not a registered as a subclass.");
return NULL;
}*/
@@ -4534,6 +5120,34 @@ PyObject *pyrna_basetype_unregister(PyObject *self, PyObject *py_class)
return NULL;
}
+ /* should happen all the time but very slow */
+ if(G.f & G_DEBUG) {
+ /* remove all properties using this class */
+ StructRNA *srna_iter;
+ PointerRNA ptr_rna;
+ PropertyRNA *prop_rna;
+ const char *prop_identifier= NULL;
+
+ RNA_blender_rna_pointer_create(&ptr_rna);
+ prop_rna = RNA_struct_find_property(&ptr_rna, "structs");
+
+
+
+ /* loop over all structs */
+ RNA_PROP_BEGIN(&ptr_rna, itemptr, prop_rna) {
+ srna_iter = itemptr.data;
+ if(pyrna_srna_contains_pointer_prop_srna(srna_iter, srna, &prop_identifier)) {
+ break;
+ }
+ }
+ RNA_PROP_END;
+
+ if(prop_identifier) {
+ PyErr_Format(PyExc_SystemError, "bpy.types.unregister(...): Cant unregister %s because %s.%s pointer property is using this.", RNA_struct_identifier(srna), RNA_struct_identifier(srna_iter), prop_identifier);
+ return NULL;
+ }
+ }
+
/* get the context, so register callback can do necessary refreshes */
C= BPy_GetContext();
diff --git a/source/blender/python/intern/bpy_rna.h b/source/blender/python/intern/bpy_rna.h
index 9892ed6989b..63f6997d82c 100644
--- a/source/blender/python/intern/bpy_rna.h
+++ b/source/blender/python/intern/bpy_rna.h
@@ -86,11 +86,7 @@ int pyrna_set_to_enum_bitfield(EnumPropertyItem *items, PyObject *value, int *r_
int pyrna_enum_value_from_id(EnumPropertyItem *item, const char *identifier, int *value, const char *error_prefix);
-/* function for registering types */
-PyObject *pyrna_basetype_register(PyObject *self, PyObject *args);
-PyObject *pyrna_basetype_unregister(PyObject *self, PyObject *args);
-
-int pyrna_deferred_register_props(struct StructRNA *srna, PyObject *class_dict);
+int pyrna_deferred_register_class(struct StructRNA *srna, PyObject *py_class);
/* called before stopping python */
void pyrna_alloc_types(void);
diff --git a/source/blender/python/intern/bpy_rna_callback.c b/source/blender/python/intern/bpy_rna_callback.c
index 2404442dc18..b2a7511f998 100644
--- a/source/blender/python/intern/bpy_rna_callback.c
+++ b/source/blender/python/intern/bpy_rna_callback.c
@@ -64,19 +64,28 @@ PyObject *pyrna_callback_add(BPy_StructRNA *self, PyObject *args)
char *cb_event_str= NULL;
int cb_event;
- if (!PyArg_ParseTuple(args, "OO|s:bpy_struct.callback_add", &cb_func, &cb_args, &cb_event_str))
+ if (!PyArg_ParseTuple(args, "OO!|s:bpy_struct.callback_add", &cb_func, &PyTuple_Type, &cb_args, &cb_event_str))
return NULL;
+
+ if(!PyCallable_Check(cb_func)) {
+ PyErr_SetString(PyExc_TypeError, "callback_add(): first argument isn't callable");
+ return NULL;
+ }
if(RNA_struct_is_a(self->ptr.type, &RNA_Region)) {
-
- static EnumPropertyItem region_draw_mode_items[] = {
- {REGION_DRAW_POST_VIEW, "POST_VIEW", 0, "Pose View", ""},
- {REGION_DRAW_POST_PIXEL, "POST_PIXEL", 0, "Post Pixel", ""},
- {REGION_DRAW_PRE_VIEW, "PRE_VIEW", 0, "Pre View", ""},
- {0, NULL, 0, NULL, NULL}};
-
- if(pyrna_enum_value_from_id(region_draw_mode_items, cb_event_str, &cb_event, "bpy_struct.callback_add()") < 0)
- return NULL;
+ if(cb_event_str) {
+ static EnumPropertyItem region_draw_mode_items[] = {
+ {REGION_DRAW_POST_PIXEL, "POST_PIXEL", 0, "Post Pixel", ""},
+ {REGION_DRAW_POST_VIEW, "POST_VIEW", 0, "Post View", ""},
+ {REGION_DRAW_PRE_VIEW, "PRE_VIEW", 0, "Pre View", ""},
+ {0, NULL, 0, NULL, NULL}};
+
+ if(pyrna_enum_value_from_id(region_draw_mode_items, cb_event_str, &cb_event, "bpy_struct.callback_add()") < 0)
+ return NULL;
+ }
+ else {
+ cb_event= REGION_DRAW_POST_PIXEL;
+ }
handle= ED_region_draw_cb_activate(((ARegion *)self->ptr.data)->type, cb_region_draw, (void *)args, cb_event);
Py_INCREF(args);
diff --git a/source/blender/python/intern/bpy_util.c b/source/blender/python/intern/bpy_util.c
index 38462d1b176..1d14ab67510 100644
--- a/source/blender/python/intern/bpy_util.c
+++ b/source/blender/python/intern/bpy_util.c
@@ -54,7 +54,7 @@ void PyObSpit(char *name, PyObject *var) {
}
void PyLineSpit(void) {
- char *filename;
+ const char *filename;
int lineno;
PyErr_Clear();
@@ -63,7 +63,7 @@ void PyLineSpit(void) {
fprintf(stderr, "%s:%d\n", filename, lineno);
}
-void BPY_getFileAndNum(char **filename, int *lineno)
+void BPY_getFileAndNum(const char **filename, int *lineno)
{
PyObject *getframe, *frame;
PyObject *f_lineno= NULL, *co_filename= NULL;
@@ -83,6 +83,7 @@ void BPY_getFileAndNum(char **filename, int *lineno)
return;
}
+ /* when executing a script */
if (filename) {
co_filename= PyObject_GetAttrStringArgs(frame, 1, "f_code", "co_filename");
if (co_filename==NULL) {
@@ -95,6 +96,25 @@ void BPY_getFileAndNum(char **filename, int *lineno)
Py_DECREF(co_filename);
}
+ /* when executing a module */
+ if(filename && *filename == NULL) {
+ /* try an alternative method to get the filename - module based
+ * references below are all borrowed (double checked) */
+ PyObject *mod_name= PyDict_GetItemString(PyEval_GetGlobals(), "__name__");
+ if(mod_name) {
+ PyObject *mod= PyDict_GetItem(PyImport_GetModuleDict(), mod_name);
+ if(mod) {
+ *filename= PyModule_GetFilename(mod);
+ }
+
+ /* unlikely, fallback */
+ if(*filename == NULL) {
+ *filename= _PyUnicode_AsString(mod_name);
+ }
+ }
+ }
+
+
if (lineno) {
f_lineno= PyObject_GetAttrString(frame, "f_lineno");
if (f_lineno==NULL) {
@@ -330,7 +350,7 @@ int BPy_errors_to_report(ReportList *reports)
PyObject *pystring_format= NULL; // workaround, see below
char *cstring;
- char *filename;
+ const char *filename;
int lineno;
if (!PyErr_Occurred())
diff --git a/source/blender/python/intern/bpy_util.h b/source/blender/python/intern/bpy_util.h
index e7e7bb09419..cfe820b53b0 100644
--- a/source/blender/python/intern/bpy_util.h
+++ b/source/blender/python/intern/bpy_util.h
@@ -38,7 +38,7 @@ struct ReportList;
void PyObSpit(char *name, PyObject *var);
void PyLineSpit(void);
-void BPY_getFileAndNum(char **filename, int *lineno);
+void BPY_getFileAndNum(const char **filename, int *lineno);
PyObject *BPY_exception_buffer(void);