1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
|
bl_info = {
"name": "Curve to Three.js Points Exporter",
"author": "Claude",
"version": (1, 0),
"blender": (3, 0, 0),
"location": "File > Export > Curve to Three.js Points",
"description": "Export curve points for Three.js CatmullRomCurve3",
"warning": "",
"doc_url": "",
"category": "Import-Export",
}
import bpy
import bmesh
from bpy.props import StringProperty, IntProperty, BoolProperty
from bpy_extras.io_utils import ExportHelper
from mathutils import Vector
import json
import os
class ExportCurveToThreeJS(bpy.types.Operator, ExportHelper):
"""Export curve points for Three.js CatmullRomCurve3"""
bl_idname = "export_curve.threejs_points"
bl_label = "Export Curve to Three.js Points"
filename_ext = ".json"
filter_glob: StringProperty(
default="*.json",
options={'HIDDEN'},
maxlen=255,
)
# 属性
sample_count: IntProperty(
name="Sample Count",
description="Number of points to sample from the curve",
default=50,
min=3,
max=1000,
)
export_format: bpy.props.EnumProperty(
name="Export Format",
description="Choose export format",
items=[
('JSON', "JSON", "Export as JSON file"),
('JS', "JavaScript", "Export as JavaScript file"),
],
default='JSON',
)
point_source: bpy.props.EnumProperty(
name="Point Source",
description="Choose what points to export",
items=[
('CONTROL', "Control Points", "Use original curve control points"),
('SAMPLED', "Sampled Points", "Sample points along the curve"),
],
default='CONTROL',
)
include_tangents: BoolProperty(
name="Include Tangents",
description="Export tangent vectors at each point",
default=False,
)
def execute(self, context):
return self.export_curve(context)
def export_curve(self, context):
# 获取活动对象
obj = context.active_object
if not obj:
self.report({'ERROR'}, "No active object selected")
return {'CANCELLED'}
if obj.type != 'CURVE':
self.report({'ERROR'}, "Selected object is not a curve")
return {'CANCELLED'}
# 获取曲线数据
curve = obj.data
# 沿着曲线采样点
points = []
tangents = []
if self.point_source == 'CONTROL':
# 直接从曲线提取控制点
for spline in curve.splines:
if spline.type == 'NURBS':
# NURBS曲线 - 使用控制点
for point in spline.points:
# 将齐次坐标转换为3D
world_pos = obj.matrix_world @ Vector((point.co[0], point.co[1], point.co[2]))
# 转换Blender (Z-up) 到 Three.js (Y-up): X, Z, -Y
points.append([world_pos.x, world_pos.z, -world_pos.y])
elif spline.type == 'BEZIER':
# Bezier曲线 - 使用控制点
for point in spline.bezier_points:
world_pos = obj.matrix_world @ point.co
points.append([world_pos.x, world_pos.z, -world_pos.y])
elif spline.type == 'POLY':
# Poly曲线 - 使用点
for point in spline.points:
world_pos = obj.matrix_world @ Vector((point.co[0], point.co[1], point.co[2]))
points.append([world_pos.x, world_pos.z, -world_pos.y])
else:
# 沿着评估曲线采样点
depsgraph = context.evaluated_depsgraph_get()
eval_obj = obj.evaluated_get(depsgraph)
mesh = eval_obj.to_mesh()
if not mesh:
self.report({'ERROR'}, "Could not convert curve to mesh")
return {'CANCELLED'}
# 从网格创建bmesh
bm = bmesh.new()
bm.from_mesh(mesh)
# 获取顶点(沿着曲线的点)
if len(bm.verts) == 0:
self.report({'ERROR'}, "Curve has no vertices")
bm.free()
return {'CANCELLED'}
# 采样均匀分布的点
for i in range(self.sample_count):
t = i / (self.sample_count - 1)
vert_index = int(t * (len(bm.verts) - 1))
vert = bm.verts[vert_index]
world_pos = obj.matrix_world @ vert.co
points.append([world_pos.x, world_pos.z, -world_pos.y])
if self.include_tangents:
world_normal = obj.matrix_world.to_3x3() @ vert.normal
tangents.append([world_normal.x, world_normal.z, -world_normal.y])
bm.free()
if len(points) == 0:
self.report({'ERROR'}, "No points found in curve")
return {'CANCELLED'}
# 准备导出数据
export_data = {
"points": points,
"count": len(points),
"curve_name": obj.name,
"blender_version": bpy.app.version_string,
}
if self.include_tangents:
export_data["tangents"] = tangents
# 基于格式导出
if self.export_format == 'JSON':
self.export_json(export_data)
else:
self.export_javascript(export_data)
self.report({'INFO'}, f"Exported {len(points)} points from curve '{obj.name}'")
return {'FINISHED'}
def export_json(self, data):
"""导出为JSON文件"""
with open(self.filepath, 'w') as f:
json.dump(data, f, indent=2)
def export_javascript(self, data):
"""导出为包含Three.js代码的JavaScript文件"""
filepath = os.path.splitext(self.filepath)[0] + '.js'
with open(filepath, 'w') as f:
f.write("// Three.js CatmullRomCurve3 from Blender\n")
f.write("// Generated by Blender Curve to Three.js Points Exporter\n")
f.write("// Coordinates converted from Blender (Z-up) to Three.js (Y-up)\n\n")
f.write("import * as THREE from 'three';\n\n")
f.write("const curvePoints = [\n")
for point in data["points"]:
f.write(f" new THREE.Vector3({point[0]:.6f}, {point[1]:.6f}, {point[2]:.6f}),\n")
f.write("];\n\n")
f.write("// Create the CatmullRomCurve3\n")
f.write("const curve = new THREE.CatmullRomCurve3(curvePoints);\n")
f.write("curve.closed = false;\n\n")
f.write("// Usage example:\n")
f.write("// const points = curve.getPoints(100);\n")
f.write("// const geometry = new THREE.BufferGeometry().setFromPoints(points);\n")
f.write("// const material = new THREE.LineBasicMaterial({ color: 0xff0000 });\n")
f.write("// const line = new THREE.Line(geometry, material);\n")
f.write("// scene.add(line);\n\n")
f.write("export { curve, curvePoints };\n")
def menu_func_export(self, context):
self.layout.operator(ExportCurveToThreeJS.bl_idname, text="Curve to Three.js Points")
def register():
bpy.utils.register_class(ExportCurveToThreeJS)
bpy.types.TOPBAR_MT_file_export.append(menu_func_export)
def unregister():
bpy.utils.unregister_class(ExportCurveToThreeJS)
bpy.types.TOPBAR_MT_file_export.remove(menu_func_export)
if __name__ == "__main__":
register()
|