I'm trying to create one object from scratch using numpy (in the example, in order to make it very simple, only two vertices and one edge).
The code below works (Hurray!) but ... Could anyone give me some advice on how to approach the problem.
Is there a shorter version, or more efficient way to create object from a numpy array ?
Thank you !
import bpy
import numpy as np
# Vertices and edges (straightforward)
vertices = np.array([
0, 0, 0,
1, 1, 1
], dtype=np.float32)
edges = np.array([
0, 1
], dtype=np.int32)
# vertices and edges number (general way)
num_vertices = vertices.shape[0] // 3
num_edges = edges.shape[0] // 2
# Create mesh object based on the arrays above
mesh = bpy.data.meshes.new(name='mesh')
mesh.vertices.add(num_vertices)
mesh.vertices.foreach_set("co", vertices)
mesh.edges.add(num_edges)
mesh.edges.foreach_set("vertices", edges)
# update mesh object
mesh.update()
mesh.validate()
# create object
obj = bpy.data.objects.new('created object', mesh)
# Add obj to the scene
scene = bpy.context.scene
scene.collection.objects.link(obj)
# Select the new object and make it active
bpy.ops.object.select_all(action='DESELECT')
obj.select_set(True)
bpy.context.view_layer.objects.active = obj