Skip to content

Instantly share code, notes, and snippets.

@tamask
Last active June 28, 2018 13:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tamask/68f9aea4772dafc25953659361d8e22a to your computer and use it in GitHub Desktop.
Save tamask/68f9aea4772dafc25953659361d8e22a to your computer and use it in GitHub Desktop.
simple graph/plotter for blender
import bpy
import bmesh
NAME = '(Plot)'
def line(gen):
scene = bpy.context.scene
objects = bpy.data.objects
if NAME in objects:
obj = objects[NAME]
data = obj.data
else:
data = bpy.data.meshes.new(NAME)
obj = objects.new(NAME, data)
mesh = bmesh.new()
mesh.from_mesh(data)
mesh.clear()
last = None
for x, y in gen:
vert = mesh.verts.new((x, 0, y))
if last is not None:
mesh.edges.new((last, vert))
last = vert
mesh.to_mesh(data)
mesh.free()
obj.data.update()
if obj.name not in scene.objects:
scene.objects.link(obj)
scene.update()
return obj
def plot(fn, res=1024, extents=1):
scene = bpy.context.scene
objects = bpy.data.objects
if NAME in objects:
obj = objects[NAME]
data = obj.data
else:
data = bpy.data.meshes.new(NAME)
obj = objects.new(NAME, data)
mesh = bmesh.new()
mesh.from_mesh(data)
mesh.clear()
last = None
for x in range(res * (extents * 2 + 1) + 1):
x -= res * extents
x = float(x) / float(res)
try:
y = fn(x)
except ZeroDivisionError:
last = None
continue
except ValueError as e:
if str(e) == 'math domain error':
last = None
continue
else:
raise e
vert = mesh.verts.new((x, 0, y))
if last is not None:
mesh.edges.new((last, vert))
last = vert
mesh.to_mesh(data)
mesh.free()
obj.data.update()
if obj.name not in scene.objects:
scene.objects.link(obj)
scene.update()
return obj
__all__ = ('line', 'plot')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment