4
$\begingroup$

I am new to Blender scripting and I am getting some unexpected behavior when trying to add a curve through a Python script. I am using this code:

import bpy
import math
import pdb
from mathutils import Vector

# print all objects
for obj in bpy.data.objects:
    print(obj.name)
    if("Curve" in obj.name):
        print("found")
        bpy.data.scenes["Scene"].objects.unlink(obj)
        bpy.data.objects.remove(obj)

for cur in bpy.data.curves:
    print(cur.name)
    bpy.data.curves.remove(cur)

# sample data
coords = [(1,0,1), (2,0,0), (3,0,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('POLY')
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)
curveData.bevel_depth = 0.01

# attach to scene and validate context
scn = bpy.context.scene
scn.objects.link(curveOB)
scn.objects.active = curveOB

And this is the result I get.

enter image description here

I am confused why there are four coordinates. Blender seems to create one additional point at the coordinate origin (0,0,0), connecting it with the last point from my data. Why is this happening and how can I avoid it?

$\endgroup$
5
$\begingroup$

The solution was simple enough. I changed

polyline.points.add(len(coords))

to

polyline.points.add(len(coords)-1)

as found here:

http://blenderscripting.blogspot.de/2011/05/blender-25-python-bezier-from-list-of.html

$\endgroup$
  • $\begingroup$ Can you elaborate, eg splines.new(...) returns a spline with one point. $\endgroup$ – batFINGER Aug 19 '16 at 9:48
  • $\begingroup$ That's strange, because output of for i in range(len(polyline.points)): print(polyline.points[i].co.xy) does not contain (0,0) $\endgroup$ – Oleg Skripnyak Jul 27 '18 at 12:37
  • $\begingroup$ However this code polyline = curveData.splines.new('POLY') for i in range(len(polyline.points)): print(polyline.points[i].co.xy) prints only one point (0,0) ! So by creation, there is always one point in the array, and you even can access it polyline.points[0].co = (1, 1, 1, 1) but nothing changes. That's strange behavior, seem a bug $\endgroup$ – Oleg Skripnyak Jul 27 '18 at 13:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.