Created
June 16, 2020 10:16
-
-
Save jhidding/16d2131261295d44ec81a8053d4c6199 to your computer and use it in GitHub Desktop.
Create objects in Blender using Metaclasses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import bpy | |
import numpy as np | |
from numpy import (sin, cos, pi) | |
def remove_from(data, name): | |
if name in data: | |
data.remove(data[name]) | |
class BObjectMeta(type): | |
def __new__(cls, name, bases, dct): | |
for attr in ["vertices", "edges", "faces"]: | |
if attr not in dct: | |
dct[attr] = [] | |
x = super().__new__(cls, name, bases, dct) | |
if name == "BObject": | |
return x | |
x.name = name | |
x.mesh_name = f"{name} mesh" | |
remove_from(bpy.data.meshes, x.mesh_name) | |
remove_from(bpy.data.objects, x.name) | |
x.mesh = bpy.data.meshes.new(x.mesh_name) | |
x.object = bpy.data.objects.new(x.name, x.mesh) | |
x.mesh.from_pydata(x.vertices, x.edges, x.faces) | |
bpy.data.collections[0].objects.link(x.object) | |
return x | |
class BObject(metaclass=BObjectMeta): | |
pass | |
class Triangle(BObject): | |
vertices = [(0, 0, 0), (0, 2, 0), (0, 1, 2)] | |
faces = [(0, 1, 2)] | |
class Disc(BObject): | |
vertices = [(cos(t), sin(t), 0) for t in np.linspace(0, 2*pi, 20)] | |
faces = [range(20)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment