-
Notifications
You must be signed in to change notification settings - Fork 106
/
blender-to-unity-fbx-exporter.py
391 lines (302 loc) · 12.7 KB
/
blender-to-unity-fbx-exporter.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
bl_info = {
"name": "Unity FBX format",
"author": "Angel 'Edy' Garcia (@VehiclePhysics)",
"version": (1, 4, 1),
"blender": (3, 0, 0),
"location": "File > Export > Unity FBX",
"description": "FBX exporter compatible with Unity's coordinate and scaling system.",
"warning": "",
"wiki_url": "",
"category": "Import-Export",
}
import bpy
import mathutils
import math
# Multi-user datablocks are preserved here. Unique copies are made for applying the rotation.
# Eventually multi-user datablocks become single-user and gets processed.
# Therefore restoring the multi-user data assigns a shared but already processed datablock.
shared_data = dict()
# All objects and collections in this view layer must be visible while being processed.
# apply_rotation and matrix changes don't have effect otherwise.
# Visibility will be restored right before saving the FBX.
hidden_collections = []
hidden_objects = []
disabled_collections = []
disabled_objects = []
def unhide_collections(col):
global hidden_collections
global disabled_collections
# No need to unhide excluded collections. Their objects aren't included in current view layer.
if col.exclude:
return
# Find hidden child collections and unhide them
hidden = [item for item in col.children if not item.exclude and item.hide_viewport]
for item in hidden:
item.hide_viewport = False
# Add them to the list so they could be restored later
hidden_collections.extend(hidden)
# Same with the disabled collections
disabled = [item for item in col.children if not item.exclude and item.collection.hide_viewport]
for item in disabled:
item.collection.hide_viewport = False
disabled_collections.extend(disabled)
# Recursively unhide child collections
for item in col.children:
unhide_collections(item)
def unhide_objects():
global hidden_objects
global disabled_objects
view_layer_objects = [ob for ob in bpy.data.objects if ob.name in bpy.context.view_layer.objects]
for ob in view_layer_objects:
if ob.hide_get():
hidden_objects.append(ob)
ob.hide_set(False)
if ob.hide_viewport:
disabled_objects.append(ob)
ob.hide_viewport = False
def make_single_user_data():
global shared_data
for ob in bpy.data.objects:
if ob.data and ob.data.users > 1:
# Figure out actual users of this datablock (not counting fake users)
users = [user for user in bpy.data.objects if user.data == ob.data]
if len(users) > 1:
# Store shared mesh data (MESH objects only).
# Other shared datablocks (CURVE, FONT, etc) are always exported as separate meshes
# by the built-in FBX exporter.
if ob.type == 'MESH':
# Shared mesh data will be restored if users have no active modifiers
modifiers = 0
for user in users:
modifiers += len([mod for mod in user.modifiers if mod.show_viewport])
if modifiers == 0:
shared_data[ob.name] = ob.data
# Single-user data is mandatory in all object types, otherwise we can't apply the rotation.
ob.data = ob.data.copy()
def apply_object_modifiers():
# Select objects in current view layer not using an armature modifier
bpy.ops.object.select_all(action='DESELECT')
for ob in bpy.data.objects:
if ob.name in bpy.context.view_layer.objects:
bypass_modifiers = False
for mod in ob.modifiers:
if mod.type == 'ARMATURE':
bypass_modifiers = True
if not bypass_modifiers:
ob.select_set(True)
# Conversion to mesh may not be available depending on the remaining objects
if bpy.ops.object.convert.poll():
print("Converting to meshes:", bpy.context.selected_objects)
bpy.ops.object.convert(target='MESH')
def reset_parent_inverse(ob):
if (ob.parent):
mat_world = ob.matrix_world.copy()
ob.matrix_parent_inverse.identity()
ob.matrix_basis = ob.parent.matrix_world.inverted() @ mat_world
def apply_rotation(ob):
bpy.ops.object.select_all(action='DESELECT')
ob.select_set(True)
bpy.ops.object.transform_apply(location = False, rotation = True, scale = False)
def fix_object(ob):
# Only fix objects in current view layer
if ob.name in bpy.context.view_layer.objects:
# Reset parent's inverse so we can work with local transform directly
reset_parent_inverse(ob)
# Create a copy of the local matrix and set a pure X-90 matrix
mat_original = ob.matrix_local.copy()
ob.matrix_local = mathutils.Matrix.Rotation(math.radians(-90.0), 4, 'X')
# Apply the rotation to the object
apply_rotation(ob)
# Reapply the previous local transform with an X+90 rotation
ob.matrix_local = mat_original @ mathutils.Matrix.Rotation(math.radians(90.0), 4, 'X')
# Recursively fix child objects in current view layer.
# Children may be in the current view layer even if their parent isn't.
for child in ob.children:
fix_object(child)
def export_unity_fbx(context, filepath, active_collection, selected_objects, deform_bones, leaf_bones, primary_bone_axis, secondary_bone_axis, tangent_space, triangulate_faces):
global shared_data
global hidden_collections
global hidden_objects
global disabled_collections
global disabled_objects
print("Preparing 3D model for Unity...")
# Root objects: Empty, Mesh, Curve, Surface, Font or Armature without parent
root_objects = [item for item in bpy.data.objects if (item.type == "EMPTY" or item.type == "MESH" or item.type == "ARMATURE" or item.type == "FONT" or item.type == "CURVE" or item.type == "SURFACE") and not item.parent]
# Preserve current scene
# undo_push examples, including exporters' execute:
# https://programtalk.com/python-examples/bpy.ops.ed.undo_push (Examples 4, 5 and 6)
# https://sourcecodequery.com/example-method/bpy.ops.ed.undo (Examples 1 and 2)
bpy.ops.ed.undo_push(message="Prepare Unity FBX")
shared_data = dict()
hidden_collections = []
hidden_objects = []
disabled_collections = []
disabled_objects = []
selection = bpy.context.selected_objects
# Object mode
if bpy.ops.object.mode_set.poll():
bpy.ops.object.mode_set(mode="OBJECT")
# Ensure all the collections and objects in this view layer are visible
unhide_collections(bpy.context.view_layer.layer_collection)
unhide_objects()
# Create a single copy in multi-user datablocks. Will be restored after fixing rotations.
make_single_user_data()
# Apply modifiers to objects (except those affected by an armature)
apply_object_modifiers()
try:
# Fix rotations
for ob in root_objects:
print(ob.name, ob.type)
fix_object(ob)
# Restore multi-user meshes
for item in shared_data:
bpy.data.objects[item].data = shared_data[item]
# Recompute the transforms out of the changed matrices
bpy.context.view_layer.update()
# Restore hidden and disabled objects
for ob in hidden_objects:
ob.hide_set(True)
for ob in disabled_objects:
ob.hide_viewport = True
# Restore hidden and disabled collections
for col in hidden_collections:
col.hide_viewport = True
for col in disabled_collections:
col.collection.hide_viewport = True
# Restore selection
bpy.ops.object.select_all(action='DESELECT')
for ob in selection:
ob.select_set(True)
# Export FBX file
params = dict(filepath=filepath, apply_scale_options='FBX_SCALE_UNITS', object_types={'EMPTY', 'MESH', 'ARMATURE'}, use_active_collection=active_collection, use_selection=selected_objects, use_armature_deform_only=deform_bones, add_leaf_bones=leaf_bones, primary_bone_axis=primary_bone_axis, secondary_bone_axis=secondary_bone_axis, use_tspace=tangent_space, use_triangles=triangulate_faces)
print("Invoking default FBX Exporter:", params)
bpy.ops.export_scene.fbx(**params)
except Exception as e:
bpy.ops.ed.undo_push(message="")
bpy.ops.ed.undo()
bpy.ops.ed.undo_push(message="Export Unity FBX")
print(e)
print("File not saved.")
# Always finish with 'FINISHED' so Undo is handled properly
return {'FINISHED'}
# Restore scene and finish
bpy.ops.ed.undo_push(message="")
bpy.ops.ed.undo()
bpy.ops.ed.undo_push(message="Export Unity FBX")
print("FBX file for Unity saved.")
return {'FINISHED'}
#---------------------------------------------------------------------------------------------------
# Exporter stuff (from the Operator File Export template)
# ExportHelper is a helper class, defines filename and
# invoke() function which calls the file selector.
from bpy_extras.io_utils import ExportHelper
from bpy.props import StringProperty, BoolProperty, EnumProperty
from bpy.types import Operator
class ExportUnityFbx(Operator, ExportHelper):
"""FBX exporter compatible with Unity's coordinate and scaling system"""
bl_idname = "export_scene.unity_fbx"
bl_label = "Export Unity FBX"
bl_options = {'UNDO_GROUPED'}
# ExportHelper mixin class uses this
filename_ext = ".fbx"
filter_glob: StringProperty(
default="*.fbx",
options={'HIDDEN'},
maxlen=255, # Max internal buffer length, longer would be clamped.
)
# List of operator properties, the attributes will be assigned
# to the class instance from the operator settings before calling.
active_collection: BoolProperty(
name="Active Collection Only",
description="Export objects in the active collection only (and its children). May be combined with Selected Objects Only",
default=False,
)
selected_objects: BoolProperty(
name="Selected Objects Only",
description="Export selected objects only. May be combined with Active Collection Only",
default=False,
)
deform_bones: BoolProperty(
name="Only Deform Bones",
description="Only write deforming bones (and non-deforming ones when they have deforming children)",
default=False,
)
leaf_bones: BoolProperty(
name="Add Leaf Bones",
description="Append a final bone to the end of each chain to specify last bone length (use this when you intend to edit the armature from exported data)",
default=False,
)
primary_bone_axis: EnumProperty(
name="Primary",
items=(('X', "X Axis", ""),
('Y', "Y Axis", ""),
('Z', "Z Axis", ""),
('-X', "-X Axis", ""),
('-Y', "-Y Axis", ""),
('-Z', "-Z Axis", ""),
),
default='Y',
)
secondary_bone_axis: EnumProperty(
name="Secondary",
items=(('X', "X Axis", ""),
('Y', "Y Axis", ""),
('Z', "Z Axis", ""),
('-X', "-X Axis", ""),
('-Y', "-Y Axis", ""),
('-Z', "-Z Axis", ""),
),
default='X',
)
tangent_space: BoolProperty(
name="Export tangents",
description="Add binormal and tangent vectors, together with normal they form the tangent space (tris/quads only). Meshes with N-gons won't export tangents unless the option Triangulate Faces is enabled",
default=False,
)
triangulate_faces: BoolProperty(
name="Triangulate Faces",
description="Convert all faces to triangles. This is necessary for exporting tangents in meshes with N-gons. Otherwise Unity will show a warning when importing tangents in these meshes",
default=False,
)
# Custom draw method
# https://blender.stackexchange.com/questions/55437/add-gui-elements-to-exporter-window
# https://docs.blender.org/api/current/bpy.types.UILayout.html
def draw(self, context):
layout = self.layout
layout.row().label(text = "Selection")
layout.row().prop(self, "active_collection")
layout.row().prop(self, "selected_objects")
layout.separator()
layout.row().label(text = "Meshes")
layout.row().prop(self, "tangent_space")
layout.row().prop(self, "triangulate_faces")
layout.separator()
layout.row().label(text = "Armatures")
layout.row().prop(self, "deform_bones")
layout.row().prop(self, "leaf_bones")
layout.row().label(text = "Bone Axes")
split = layout.split(factor=0.4)
col = split.column()
col.alignment = 'RIGHT'
col.label(text = "Primary")
split.column().prop(self, "primary_bone_axis", text="")
split = layout.split(factor=0.4)
col = split.column()
col.alignment = 'RIGHT'
col.label(text = "Secondary")
split.column().prop(self, "secondary_bone_axis", text="")
def execute(self, context):
return export_unity_fbx(context, self.filepath, self.active_collection, self.selected_objects, self.deform_bones, self.leaf_bones, self.primary_bone_axis, self.secondary_bone_axis, self.tangent_space, self.triangulate_faces)
# Only needed if you want to add into a dynamic menu
def menu_func_export(self, context):
self.layout.operator(ExportUnityFbx.bl_idname, text="Unity FBX (.fbx)")
def register():
bpy.utils.register_class(ExportUnityFbx)
bpy.types.TOPBAR_MT_file_export.append(menu_func_export)
def unregister():
bpy.utils.unregister_class(ExportUnityFbx)
bpy.types.TOPBAR_MT_file_export.remove(menu_func_export)
if __name__ == "__main__":
register()
# test call
bpy.ops.export_scene.unity_fbx('INVOKE_DEFAULT')