この前はBlenderで面を描画するSurfacePlotをやってみました. 今回は3次元の曲線を描画するPlot3Dをやっていきます.
とはいえやることは簡単で, 下のスクリプトをダウンロードしてBlender2.8で実行するだけです.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This script is based on the following discussion. | |
# https://blenderartists.org/t/how-do-i-create-a-simple-curve-in-python/477260/5 | |
import bpy | |
import numpy as np | |
import math | |
import mathutils | |
def Lissajous(t, a=1, b=2, delta=0): | |
x = np.cos(a * t) | |
y = np.sin(b * t + delta) | |
return (x, y) | |
def makeSpline(cu, typ, points): | |
spline = cu.splines.new(typ) | |
npoints = len(points) | |
if typ == 'BEZIER' or typ == 'BSPLINE': | |
spline.bezier_points.add(npoints – 1) | |
for (n, pt) in enumerate(points): | |
bez = spline.bezier_points[n] | |
(bez.co, bez.handle1, bez.handle1_type, | |
bez.handle2, bez.handle2_type) = pt | |
else: | |
spline.points.add(npoints – 1) # One point already exists? | |
for (n, pt) in enumerate(points): | |
spline.points[n].co = pt | |
return | |
cu = bpy.data.curves.new("MyCurve", "CURVE") | |
ob = bpy.data.objects.new("MyCurveObject", cu) | |
bpy.context.scene.collection.objects.link(ob) | |
ps = [] | |
for t in np.linspace(0, 2.0 * np.pi, endpoint=True): | |
x, y = Lissajous(t, a=1, b=2) | |
ps.append((x, y, np.sin(t), 1)) | |
print(ps) | |
# scn = bpy.context.scene | |
# scn.objects.link(ob) | |
# scn.objects.active = ob | |
cu.dimensions = "3D" | |
# makeSpline(cu, "NURBS", [(0, 0, 0, 1), (0, 0, 1, 1), | |
# (0, 1, 1, 1), (1, 4, 1, 1)]) | |
makeSpline(cu, "NURBS", ps) |
実行すると画像のようなカーブが描画されます. 一見するとなんの形かわかりませんが, 真上からみるとちゃんとリサジュー曲線になっていることがわかります(トップの画像がそれです).
スクリプトを実行しただけではカーブは閉じていませんが, 右下にあるカーブの設定の中のActive Spline -> Cyclic U をチェックすればパスは閉じられます.
42行目のps.append()
の値を変えれば描画される曲線も変わるので, いろいろ試してみてください.
コメント