初学者创意开发与情感设计技术指南

本文详细介绍了如何通过Three.js和Blender技术栈开发创意项目,包含情感设计原则、技术实现细节、Blender插件开发和3D场景构建,帮助初学者掌握创意编程与情感化设计技能。

技术实现

2.1 使用AI创建Blender Python脚本选择所有对象并添加名为"SimpleBake"的第二UV贴图

对于SimpleBake Blender插件,有一个选项允许您使用名为"SimpleBake"的预存在UV贴图。手动选择每个对象并创建该UV贴图非常繁琐,因此我让ChatGPT生成一个自动执行此操作的脚本。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import bpy

# 遍历场景中的所有网格对象
for obj in bpy.data.objects:
    if obj.type == 'MESH':
        uv_layers = obj.data.uv_layers

        # 如果"SimpleBake"不存在则添加
        if "SimpleBake" not in uv_layers:
            new_uv = uv_layers.new(name="SimpleBake")
            print(f"Added 'SimpleBake' UV map to: {obj.name}")
        else:
            new_uv = uv_layers["SimpleBake"]
            print(f"'SimpleBake' UV map already exists in: {obj.name}")

        # 将"SimpleBake"设置为活动UV贴图
        uv_layers.active = new_uv

2.2 使用AI创建Blender插件将曲线导出为JSON或three.js曲线

基本上如标题所述,我使用Claude AI通过三个提示创建了这个插件。第一个是创建可以导出曲线点的插件,然后要求它只导出控制点而不是采样点,第三个提示是将其放入three.js曲线格式并更新坐标系。

  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()

插件外观和工作方式

选择曲线对象,文件 > 导出 > 插件 > 选择控制点并格式化为JavaScript。

2.3 大量条件渲染

对于场景转换,没有复杂的渲染目标或任何类似的东西,它只是预定位的3D对象根据相机沿曲线的进度值切换其可见性。对于像这样更复杂的场景来说,这不是一个好的做法,因为如果一次条件渲染大量内容可能会导致崩溃,但至少适用于大多数台式机/笔记本电脑上的演示。

Blender中的模型设置方式

2.4 使用Figma为SVG创建不可见边界框

当我想为夜间船只场景制作睡觉的Miffy和Panda Boris时,我没有将它们设计成与白天版本相同的大小。这意味着当我用夜间版本替换图像纹理时,默认的UV贴图看起来不再好看。虽然我可以通过代码调整UV或平面的位置,但更容易的方法是在Figma中创建一个与白天角色相同宽度和高度的不可见边界框,并让夜间角色适合该边界框。

睡着的Boris角色与边界框分组在一起

comments powered by Disqus
使用 Hugo 构建
主题 StackJimmy 设计