Featured post

new redirect for blender.org bpy docs.

http://www.blender.org/api/blender_python_api_current/ As of 10/11 november 2015 we can now link to the current api docs and not be worr...

June 03, 2013

Normalize and Quantive

A question on BA.org looking for a script that can scale an object to within the boundaries of -1 and 1 for all axis (called normalizing, maybe erroneously) and then placing further constraint on the geometry that it must fall within grid slices of 0.1 .. so xyz can only have values between the range (-1.0, -0.9 -0.8 ....0.8, 0.9, 1.0), i made the following scripts.

here is the development version:
here is everything chucked into one loop.
import bpy, bmesh
from mathutils import Vector
obj = bpy.context.object
''' find max x,y,z and scale factor'''
coords = obj.bound_box[:]
rotated = zip(*coords[::-1])
all_axis = []
push_axis = []
for (axis, _list) in zip('xyz', rotated):
distance = max(_list)-min(_list)
all_axis.append(distance)
adjuster_distance = min(_list) + (distance/2)
push_axis.append(adjuster_distance*-1)
long_side = max(all_axis)
scale = Vector((long_side, 0, 0)).length / 2.0
bm = bmesh.from_edit_mesh(obj.data)
for vertex in bm.verts:
# center
vertex.co.x += push_axis[0]
vertex.co.y += push_axis[1]
vertex.co.z += push_axis[2]
# rescale to -1, 1 boundary
vertex.co = vertex.co/scale
# quantize
vertex.co.x = round(vertex.co.x, 1)
vertex.co.y = round(vertex.co.y, 1)
vertex.co.z = round(vertex.co.z, 1)
bmesh.update_edit_mesh(obj.data)

Alternative code

import bpy
from mathutils import Vector, Matrix
def get_transforms(obj):
''' find max x,y,z and scale factor'''
coords = obj.bound_box[:]
rotated = zip(*coords[::-1])
all_axis, push_axis = [], []
for axis in rotated:
distance = max(axis) - min(axis)
all_axis.append(distance)
adjuster_distance = min(axis) + (distance/2)
push_axis.append(-adjuster_distance)
return max(all_axis)/2, push_axis
obj = bpy.context.active_object
scale_value, push_axis = get_transforms(obj)
# translate and scale
translation = Matrix.Translation(push_axis)
scale = Matrix.Scale(1/scale_value, 4)
mesh = obj.data
mesh.transform(scale * translation)
mesh.update()
# quantize
for vertex in mesh.vertices:
vertex.co = Vector((round(i, 1) for i in vertex.co))
view raw bridgitte.py hosted with ❤ by GitHub