Skip to content

Instantly share code, notes, and snippets.

@CGArtPython
Last active October 31, 2022 06:01
Show Gist options
  • Save CGArtPython/50879916481933afd65746e1d05bdd9f to your computer and use it in GitHub Desktop.
Save CGArtPython/50879916481933afd65746e1d05bdd9f to your computer and use it in GitHub Desktop.
Beginner Blender Python Tutorial: Python Classes; function version example 2 (used in tutorial: https://youtu.be/t2KEolkhIoA)
import bpy
def create_mesh_data(verts, edges, faces):
"""
create a mesh from the vert, edge, and face data
"""
mesh_data = bpy.data.meshes.new("cube_data")
mesh_data.from_pydata(verts, edges, faces)
return mesh_data
def create_mesh_object_from_data(mesh_data):
"""
create a object using the mesh data
"""
return bpy.data.objects.new("cube_object", mesh_data)
def add_mesh_object_into_scene(mesh_object):
"""
add object into active scene by linking the object into the
default scene collection
"""
bpy.context.collection.objects.link(mesh_object)
def create_mesh_object(verts, edges, faces):
"""
create a mesh object from the given verts, edges, and faces
add the new mesh object into the scene
"""
mesh_data = create_mesh_data(verts, edges, faces)
mesh_obj = create_mesh_object_from_data(mesh_data)
add_mesh_object_into_scene(mesh_obj)
return mesh_obj
def create_cube_with_square_faces(verts):
"""
create a cube with square faces
"""
# define faces using the indexes of the vertices
faces = [
(0, 1, 2, 3),
(7, 6, 5, 4),
(4, 5, 1, 0),
(7, 4, 0, 3),
(6, 7, 3, 2),
(5, 6, 2, 1),
]
edges = []
mesh_object = create_mesh_object(verts, edges, faces)
return mesh_object
def create_cube_with_triangle_faces(verts):
"""
create a cube with triangle faces
"""
# define faces using the indexes of the vertices
faces = [
(0, 1, 2),
(0, 2, 3),
(6, 5, 4),
(7, 6, 4),
(4, 5, 1),
(4, 1, 0),
(7, 4, 0),
(7, 0, 3),
(6, 7, 3),
(6, 3, 2),
(5, 6, 2),
(5, 2, 1),
]
edges = []
mesh_object = create_mesh_object(verts, edges, faces)
return mesh_object
def main():
# define the coordinates of each vertex
cube_verts = [
(-1.0, -1.0, -1.0),
(-1.0, 1.0, -1.0),
(1.0, 1.0, -1.0),
(1.0, -1.0, -1.0),
(-1.0, -1.0, 1.0),
(-1.0, 1.0, 1.0),
(1.0, 1.0, 1.0),
(1.0, -1.0, 1.0),
]
create_cube_with_square_faces(cube_verts)
cube_obj = create_cube_with_triangle_faces(cube_verts)
cube_obj.location.y = 3
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment