Skip to content

Instantly share code, notes, and snippets.

@CGArtPython
Last active October 31, 2022 06:01
Show Gist options
  • Save CGArtPython/a182133d17d3e3da23bc845702fd0664 to your computer and use it in GitHub Desktop.
Save CGArtPython/a182133d17d3e3da23bc845702fd0664 to your computer and use it in GitHub Desktop.
Beginner Blender Python Tutorial: Python Classes; function version example 1 (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():
"""
create a cube with square faces
"""
# define the coordinates of each vertex
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),
]
# 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 main():
create_cube_with_square_faces()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment