-
Notifications
You must be signed in to change notification settings - Fork 0
/
VF_planarUV.py
324 lines (274 loc) · 9.92 KB
/
VF_planarUV.py
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
bl_info = {
"name": "VF Planar UV",
"author": "John Einselen - Vectorform LLC",
"version": (0, 5, 0),
"blender": (2, 83, 0),
"location": "Scene > VF Tools > Planar UV",
"description": "Numerical planar projection of 3D meshes into UV space",
"warning": "inexperienced developer, use at your own risk",
"doc_url": "https://github.com/jeinselenVF/VF-BlenderPlanarUV",
"tracker_url": "https://github.com/jeinselenVF/VF-BlenderPlanarUV/issues",
"category": "3D View"}
# Based in part on basic code found here:
# https://blenderartists.org/t/set-face-uv-coordinates-while-in-edit-mode/1317947
# https://blender.stackexchange.com/questions/9399/add-uv-layer-to-mesh-add-uv-coords-with-python
# https://blender.stackexchange.com/questions/30421/create-a-radio-button-via-python
# https://gifguide2code.com/2017/05/14/python-how-to-loop-through-every-vertex-in-a-mesh/
import bpy
import bmesh
from mathutils import Vector
###########################################################################
# Main class
class vf_planar_uv(bpy.types.Operator):
bl_idname = "vfplanaruv.set"
bl_label = "Set UV Map"
bl_description = "Numerical planar projection of 3D meshes into UV space"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
if not context.view_layer.objects.active.data.vertices:
return {'CANCELLED'}
# Set up local variables
axis = context.scene.vf_planar_uv_settings.projection_axis
world = True if context.scene.vf_planar_uv_settings.projection_space == "W" else False
rotation = context.scene.vf_planar_uv_settings.projection_rotation
flip = float(context.scene.vf_planar_uv_settings.projection_flip)
align = float(context.scene.vf_planar_uv_settings.projection_align)
centre = context.scene.vf_planar_uv_settings.projection_centre
size = context.scene.vf_planar_uv_settings.projection_size
# Prevent divide by zero errors
size[0] = size[0] if size[0] > 0.0 else 1.0
size[1] = size[1] if size[1] > 0.0 else 1.0
size[2] = size[2] if size[2] > 0.0 else 1.0
# Save current mode
mode = context.active_object.mode
# Switch to edit mode
bpy.ops.object.mode_set(mode='EDIT')
# Get object
obj = context.active_object
mat = obj.matrix_world
bm = bmesh.from_edit_mesh(obj.data)
# Get UV map
uv_layer = bm.loops.layers.uv.verify()
# Loop through faces
U = 0.0
V = 0.0
for f in bm.faces:
if f.select:
for l in f.loops:
# Process input coordinates
# Use copy() to prevent changes to the source vertex coordinates
pos = l.vert.co.copy()
# Convert to world space if enabled
if world:
pos = mat @ pos
pos[0] = (pos[0] - centre[0]) / size[0]
pos[1] = (pos[1] - centre[1]) / size[1]
pos[2] = (pos[2] - centre[2]) / size[2]
# Projection Axis
if axis == "X":
U = pos[1]
V = pos[2]
elif axis == "Y":
U = pos[0]
V = pos[2]
else: # axis == "Z"
U = pos[0]
V = pos[1]
# Projection Rotation
if "YX" in rotation:
U, V = V, U
U *= -1.0
if "-" in rotation:
U *= -1.0
V *= -1.0
# Projection Flip
U *= flip
# Set UV map values with image centre or zero point alignment
l[uv_layer].uv = (U + align, V + align)
# Update mesh
bmesh.update_edit_mesh(obj.data)
# Reset object mode to original
bpy.ops.object.mode_set(mode=mode)
# Done
return {'FINISHED'}
class vf_load_selection(bpy.types.Operator):
bl_idname = "vfloadselection.set"
bl_label = "Load Selection Settings"
bl_description = "Set the Centre and Size variables to the bounding box of the selected geometry"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
if not context.view_layer.objects.active.data.vertices:
return {'CANCELLED'}
# Save current mode
mode = context.active_object.mode
# Switch to edit mode
bpy.ops.object.mode_set(mode='EDIT')
# Get object data
obj = context.active_object
mat = obj.matrix_world
mesh = bmesh.from_edit_mesh(obj.data)
# Loop through selected vertices and find the minimum/maximum positions
min_co = Vector((float("inf"), float("inf"), float("inf")))
max_co = Vector((float("-inf"), float("-inf"), float("-inf")))
for vert in mesh.verts:
if vert.select:
min_co.x = min(min_co.x, vert.co.x)
min_co.y = min(min_co.y, vert.co.y)
min_co.z = min(min_co.z, vert.co.z)
max_co.x = max(max_co.x, vert.co.x)
max_co.y = max(max_co.y, vert.co.y)
max_co.z = max(max_co.z, vert.co.z)
# Convert to world space if enabled
if context.scene.vf_planar_uv_settings.projection_space == "W":
min_co = mat @ min_co
max_co = mat @ max_co
# Calculate bounding box and centre point
centr = (min_co + max_co) * 0.5
max_co = max_co - min_co
# Prevent zero scale entries
if max_co.x == 0:
max_co.x = 1.0
if max_co.y == 0:
max_co.y = 1.0
if max_co.z == 0:
max_co.z = 1.0
# Set local variables
context.scene.vf_planar_uv_settings.projection_centre = centr
context.scene.vf_planar_uv_settings.projection_size = max_co
# Reset object mode to original
bpy.ops.object.mode_set(mode=mode)
# Done
return {'FINISHED'}
###########################################################################
# Project settings and UI rendering classes
class vfPlanarUvSettings(bpy.types.PropertyGroup):
projection_axis: bpy.props.EnumProperty(
name='Axis',
description='Planar projection axis',
items=[
('X', 'X', 'X axis projection'),
('Y', 'Y', 'Y axis projection'),
('Z', 'Z', 'Z axis projection')
],
default='X')
projection_centre: bpy.props.FloatVectorProperty(
name="Centre",
description="Centre of the planar projection mapping area",
subtype="TRANSLATION",
default=[0.0, 0.0, 0.0],
step=1.25,
precision=3)
projection_size: bpy.props.FloatVectorProperty(
name="Size",
description="Size of the planar projection mapping area",
subtype="TRANSLATION",
default=[1.0, 1.0, 1.0],
step=1.25,
precision=3)
projection_space: bpy.props.EnumProperty(
name='Space',
description='Planar projection coordinate space',
items=[
('L', 'Local', 'Projection using local space'),
('W', 'World', 'Projection using world space')
],
default='L')
projection_rotation: bpy.props.EnumProperty(
name='Rotation',
description='Planar projection axis',
items=[
('+XY', '0°', 'XY orientation projection'),
('+YX', '90', 'YX orientation projection'),
('-XY', '180', '-XY orientation projection'),
('-YX', '270', '-YX orientation projection')
],
default='+XY')
projection_flip: bpy.props.EnumProperty(
name='Flip',
description='Planar projection axis',
items=[
('1.0', 'Front', 'Projection from positive direction'),
('-1.0', 'Back', 'Projection from negative direction')
],
default='1.0')
projection_align: bpy.props.EnumProperty(
name='Alignment',
description='UV map alignment',
items=[
('0.5', 'Image', 'Align mapped geometry centre to UV 0.5, 0.5'),
('0.0', 'Zero', 'Align mapped geometry centre to UV 0.0, 0.0')
],
default='0.5')
class VFTOOLS_PT_planar_uv(bpy.types.Panel):
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
bl_category = 'VF Tools'
bl_order = 10
bl_options = {'DEFAULT_CLOSED'}
@classmethod
def poll(cls, context):
return True
class VFTOOLS_PT_planar_uv_main(VFTOOLS_PT_planar_uv, bpy.types.Panel):
bl_idname = "VFTOOLS_PT_planar_uv"
bl_label = "Planar UV"
def draw_header(self, context):
try:
layout = self.layout
except Exception as exc:
print(str(exc) + " | Error in VF Planar UV panel header")
def draw(self, context):
try:
layout = self.layout
layout.use_property_split = True
layout.use_property_decorate = False # No animation
layout.prop(context.scene.vf_planar_uv_settings, 'projection_axis', expand=True)
col = layout.column()
col.prop(context.scene.vf_planar_uv_settings, 'projection_centre')
col = layout.column()
col.prop(context.scene.vf_planar_uv_settings, 'projection_size')
layout.prop(context.scene.vf_planar_uv_settings, 'projection_space', expand=True)
button = layout.row()
if not (context.view_layer.objects.active and context.view_layer.objects.active.type == "MESH"):
button.active = False
button.enabled = False
button.operator(vf_planar_uv.bl_idname, icon="GROUP_UVS")
except Exception as exc:
print(str(exc) + " | Error in VF Planar UV panel")
class VFTOOLS_PT_planar_uv_advanced(VFTOOLS_PT_planar_uv, bpy.types.Panel):
bl_idname = "VFTOOLS_PT_planar_uv_advanced"
bl_parent_id = "VFTOOLS_PT_planar_uv"
bl_label = "Advanced"
bl_options = {'DEFAULT_CLOSED'}
def draw_header(self, context):
try:
layout = self.layout
except Exception as exc:
print(str(exc) + " | Error in VF Planar UV panel header")
def draw(self, context):
try:
layout = self.layout
layout.use_property_split = True
layout.use_property_decorate = False # No animation
button = layout.row()
if not (context.view_layer.objects.active and context.view_layer.objects.active.type == "MESH"):
button.active = False
button.enabled = False
button.operator(vf_load_selection.bl_idname, icon="SHADING_BBOX")
layout.prop(context.scene.vf_planar_uv_settings, 'projection_rotation', expand=True)
layout.prop(context.scene.vf_planar_uv_settings, 'projection_flip', expand=True)
layout.prop(context.scene.vf_planar_uv_settings, 'projection_align', expand=True)
except Exception as exc:
print(str(exc) + " | Error in VF Planar UV Advanced panel")
classes = (vf_planar_uv, vf_load_selection, vfPlanarUvSettings, VFTOOLS_PT_planar_uv_main, VFTOOLS_PT_planar_uv_advanced)
###########################################################################
# Addon registration functions
def register():
for cls in classes:
bpy.utils.register_class(cls)
bpy.types.Scene.vf_planar_uv_settings = bpy.props.PointerProperty(type=vfPlanarUvSettings)
def unregister():
for cls in reversed(classes):
bpy.utils.unregister_class(cls)
del bpy.types.Scene.vf_planar_uv_settings
if __name__ == "__main__":
register()