13
$\begingroup$

I'm trying to create curves from a list of points, I have the xyz coordinates in text files. I could make it manually via the python console for a single curve, but I have to do it many times and I don't know how to correctly implement a loop.

How can I do that?

$\endgroup$

1 Answer 1

27
$\begingroup$

This should work:

import bpy

# sample data
coords = [(1,1,1), (2,2,2), (1,2,1)]

# create the Curve Datablock
curveData = bpy.data.curves.new('myCurve', type='CURVE')
curveData.dimensions = '3D'
curveData.resolution_u = 2

# map coords to spline
polyline = curveData.splines.new('NURBS')
polyline.points.add(len(coords))
for i, coord in enumerate(coords):
    x,y,z = coord
    polyline.points[i].co = (x, y, z, 1)

# create Object
curveOB = bpy.data.objects.new('myCurve', curveData)

# attach to scene and validate context
scn = bpy.context.scene
scn.objects.link(curveOB)
scn.objects.active = curveOB
curveOB.select = True
$\endgroup$
7
  • 5
    $\begingroup$ It creates a NURBS curve. The type for curveData.splines.new(type) can be chosen from ('POLY', 'BEZIER', 'BSPLINE', 'CARDINAL', 'NURBS'). $\endgroup$ Commented Feb 4, 2014 at 17:44
  • 1
    $\begingroup$ If you install NumPy (which comes bundled with the Linux version), you could replace the fourth line with coords=np.loadtxt('filename.txt'), and add import numpy at the top... otherwise there's certainly other ways to read in a text file in Python. $\endgroup$
    – Garrett
    Commented Feb 4, 2014 at 21:05
  • 13
    $\begingroup$ Note for anyone who finds this later, if you choose 'BEZIER' for the curveData.spline type you'll need to use .bezier_points.add() and .bezier_points[i].co instead of .points.add() and points[i].co. $\endgroup$ Commented Dec 23, 2014 at 0:02
  • 2
    $\begingroup$ For Bezier, the default (0,0,0) handles won't be adequate, you may want to set them to the points as well: .bezier_points[i].handle_left = .bezier_points[i].handle_right = .bezier_points[i].co $\endgroup$
    – rfabbri
    Commented Jun 16, 2016 at 22:52
  • 1
    $\begingroup$ If you get AttributeError: 'bpy_prop_collection' object has no attribute 'link' in Blender 2.8 or newer, then check this answer blender.stackexchange.com/a/162417/131771 $\endgroup$ Commented Apr 29, 2022 at 19:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .