1 # ##### BEGIN GPL LICENSE BLOCK #####
3 # This program is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU General Public License
5 # as published by the Free Software Foundation; either version 2
6 # of the License, or (at your option) any later version.
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software Foundation,
15 # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 # ##### END GPL LICENSE BLOCK #####
21 # Script copyright (C) Campbell Barton, Bastien Montagne
30 from itertools
import zip_longest
, chain
34 if "encode_bin" in locals():
35 importlib
.reload(encode_bin
)
36 if "data_types" in locals():
37 importlib
.reload(data_types
)
38 if "fbx_utils" in locals():
39 importlib
.reload(fbx_utils
)
43 from bpy_extras
import node_shader_utils
44 from mathutils
import Vector
, Matrix
46 from . import encode_bin
, data_types
, fbx_utils
47 from .fbx_utils
import (
49 FBX_VERSION
, FBX_HEADER_VERSION
, FBX_SCENEINFO_VERSION
, FBX_TEMPLATES_VERSION
,
51 FBX_GEOMETRY_VERSION
, FBX_GEOMETRY_NORMAL_VERSION
, FBX_GEOMETRY_BINORMAL_VERSION
, FBX_GEOMETRY_TANGENT_VERSION
,
52 FBX_GEOMETRY_SMOOTHING_VERSION
, FBX_GEOMETRY_CREASE_VERSION
, FBX_GEOMETRY_VCOLOR_VERSION
, FBX_GEOMETRY_UV_VERSION
,
53 FBX_GEOMETRY_MATERIAL_VERSION
, FBX_GEOMETRY_LAYER_VERSION
,
54 FBX_GEOMETRY_SHAPE_VERSION
, FBX_DEFORMER_SHAPE_VERSION
, FBX_DEFORMER_SHAPECHANNEL_VERSION
,
55 FBX_POSE_BIND_VERSION
, FBX_DEFORMER_SKIN_VERSION
, FBX_DEFORMER_CLUSTER_VERSION
,
56 FBX_MATERIAL_VERSION
, FBX_TEXTURE_VERSION
,
58 FBX_ANIM_PROPSGROUP_NAME
,
60 BLENDER_OTHER_OBJECT_TYPES
, BLENDER_OBJECT_TYPES_MESHLIKE
,
61 FBX_LIGHT_TYPES
, FBX_LIGHT_DECAY_TYPES
,
62 RIGHT_HAND_AXES
, FBX_FRAMERATES
,
63 # Miscellaneous utils.
65 units_blender_to_fbx_factor
, units_convertor
, units_convertor_iter
,
66 matrix4_to_array
, similar_values
, similar_values_iter
,
67 # Mesh transform helpers.
68 vcos_transformed_gen
, nors_transformed_gen
,
70 get_fbx_uuid_from_key
,
72 get_blenderID_key
, get_blenderID_name
,
73 get_blender_mesh_shape_key
, get_blender_mesh_shape_channel_key
,
74 get_blender_empty_key
, get_blender_bone_key
,
75 get_blender_bindpose_key
, get_blender_armature_skin_key
, get_blender_bone_cluster_key
,
76 get_blender_anim_id_base
, get_blender_anim_stack_key
, get_blender_anim_layer_key
,
77 get_blender_anim_curve_node_key
, get_blender_anim_curve_key
,
78 get_blender_nodetexture_key
,
81 elem_data_single_bool
, elem_data_single_int16
, elem_data_single_int32
, elem_data_single_int64
,
82 elem_data_single_float32
, elem_data_single_float64
,
83 elem_data_single_bytes
, elem_data_single_string
, elem_data_single_string_unicode
,
84 elem_data_single_bool_array
, elem_data_single_int32_array
, elem_data_single_int64_array
,
85 elem_data_single_float32_array
, elem_data_single_float64_array
, elem_data_vec_float64
,
86 # FBX element properties.
87 elem_properties
, elem_props_set
, elem_props_compound
,
88 # FBX element properties handling templates.
89 elem_props_template_init
, elem_props_template_set
, elem_props_template_finalize
,
91 FBXTemplate
, fbx_templates_generate
,
93 AnimationCurveNodeWrapper
,
95 ObjectWrapper
, fbx_name_class
,
97 FBXExportSettingsMedia
, FBXExportSettings
, FBXExportData
,
101 convert_sec_to_ktime
= units_convertor("second", "ktime")
102 convert_sec_to_ktime_iter
= units_convertor_iter("second", "ktime")
104 convert_mm_to_inch
= units_convertor("millimeter", "inch")
106 convert_rad_to_deg
= units_convertor("radian", "degree")
107 convert_rad_to_deg_iter
= units_convertor_iter("radian", "degree")
110 # ##### Templates #####
111 # TODO: check all those "default" values, they should match Blender's default as much as possible, I guess?
113 def fbx_template_def_globalsettings(scene
, settings
, override_defaults
=None, nbr_users
=0):
115 if override_defaults
is not None:
116 props
.update(override_defaults
)
117 return FBXTemplate(b
"GlobalSettings", b
"", props
, nbr_users
, [False])
120 def fbx_template_def_model(scene
, settings
, override_defaults
=None, nbr_users
=0):
121 gscale
= settings
.global_scale
123 # Name, Value, Type, Animatable
124 b
"QuaternionInterpolate": (0, "p_enum", False), # 0 = no quat interpolation.
125 b
"RotationOffset": ((0.0, 0.0, 0.0), "p_vector_3d", False),
126 b
"RotationPivot": ((0.0, 0.0, 0.0), "p_vector_3d", False),
127 b
"ScalingOffset": ((0.0, 0.0, 0.0), "p_vector_3d", False),
128 b
"ScalingPivot": ((0.0, 0.0, 0.0), "p_vector_3d", False),
129 b
"TranslationActive": (False, "p_bool", False),
130 b
"TranslationMin": ((0.0, 0.0, 0.0), "p_vector_3d", False),
131 b
"TranslationMax": ((0.0, 0.0, 0.0), "p_vector_3d", False),
132 b
"TranslationMinX": (False, "p_bool", False),
133 b
"TranslationMinY": (False, "p_bool", False),
134 b
"TranslationMinZ": (False, "p_bool", False),
135 b
"TranslationMaxX": (False, "p_bool", False),
136 b
"TranslationMaxY": (False, "p_bool", False),
137 b
"TranslationMaxZ": (False, "p_bool", False),
138 b
"RotationOrder": (0, "p_enum", False), # we always use 'XYZ' order.
139 b
"RotationSpaceForLimitOnly": (False, "p_bool", False),
140 b
"RotationStiffnessX": (0.0, "p_double", False),
141 b
"RotationStiffnessY": (0.0, "p_double", False),
142 b
"RotationStiffnessZ": (0.0, "p_double", False),
143 b
"AxisLen": (10.0, "p_double", False),
144 b
"PreRotation": ((0.0, 0.0, 0.0), "p_vector_3d", False),
145 b
"PostRotation": ((0.0, 0.0, 0.0), "p_vector_3d", False),
146 b
"RotationActive": (False, "p_bool", False),
147 b
"RotationMin": ((0.0, 0.0, 0.0), "p_vector_3d", False),
148 b
"RotationMax": ((0.0, 0.0, 0.0), "p_vector_3d", False),
149 b
"RotationMinX": (False, "p_bool", False),
150 b
"RotationMinY": (False, "p_bool", False),
151 b
"RotationMinZ": (False, "p_bool", False),
152 b
"RotationMaxX": (False, "p_bool", False),
153 b
"RotationMaxY": (False, "p_bool", False),
154 b
"RotationMaxZ": (False, "p_bool", False),
155 b
"InheritType": (0, "p_enum", False), # RrSs
156 b
"ScalingActive": (False, "p_bool", False),
157 b
"ScalingMin": ((0.0, 0.0, 0.0), "p_vector_3d", False),
158 b
"ScalingMax": ((1.0, 1.0, 1.0), "p_vector_3d", False),
159 b
"ScalingMinX": (False, "p_bool", False),
160 b
"ScalingMinY": (False, "p_bool", False),
161 b
"ScalingMinZ": (False, "p_bool", False),
162 b
"ScalingMaxX": (False, "p_bool", False),
163 b
"ScalingMaxY": (False, "p_bool", False),
164 b
"ScalingMaxZ": (False, "p_bool", False),
165 b
"GeometricTranslation": ((0.0, 0.0, 0.0), "p_vector_3d", False),
166 b
"GeometricRotation": ((0.0, 0.0, 0.0), "p_vector_3d", False),
167 b
"GeometricScaling": ((1.0, 1.0, 1.0), "p_vector_3d", False),
168 b
"MinDampRangeX": (0.0, "p_double", False),
169 b
"MinDampRangeY": (0.0, "p_double", False),
170 b
"MinDampRangeZ": (0.0, "p_double", False),
171 b
"MaxDampRangeX": (0.0, "p_double", False),
172 b
"MaxDampRangeY": (0.0, "p_double", False),
173 b
"MaxDampRangeZ": (0.0, "p_double", False),
174 b
"MinDampStrengthX": (0.0, "p_double", False),
175 b
"MinDampStrengthY": (0.0, "p_double", False),
176 b
"MinDampStrengthZ": (0.0, "p_double", False),
177 b
"MaxDampStrengthX": (0.0, "p_double", False),
178 b
"MaxDampStrengthY": (0.0, "p_double", False),
179 b
"MaxDampStrengthZ": (0.0, "p_double", False),
180 b
"PreferedAngleX": (0.0, "p_double", False),
181 b
"PreferedAngleY": (0.0, "p_double", False),
182 b
"PreferedAngleZ": (0.0, "p_double", False),
183 b
"LookAtProperty": (None, "p_object", False),
184 b
"UpVectorProperty": (None, "p_object", False),
185 b
"Show": (True, "p_bool", False),
186 b
"NegativePercentShapeSupport": (True, "p_bool", False),
187 b
"DefaultAttributeIndex": (-1, "p_integer", False),
188 b
"Freeze": (False, "p_bool", False),
189 b
"LODBox": (False, "p_bool", False),
190 b
"Lcl Translation": ((0.0, 0.0, 0.0), "p_lcl_translation", True),
191 b
"Lcl Rotation": ((0.0, 0.0, 0.0), "p_lcl_rotation", True),
192 b
"Lcl Scaling": ((1.0, 1.0, 1.0), "p_lcl_scaling", True),
193 b
"Visibility": (1.0, "p_visibility", True),
194 b
"Visibility Inheritance": (1, "p_visibility_inheritance", False),
196 if override_defaults
is not None:
197 props
.update(override_defaults
)
198 return FBXTemplate(b
"Model", b
"FbxNode", props
, nbr_users
, [False])
201 def fbx_template_def_null(scene
, settings
, override_defaults
=None, nbr_users
=0):
203 b
"Color": ((0.8, 0.8, 0.8), "p_color_rgb", False),
204 b
"Size": (100.0, "p_double", False),
205 b
"Look": (1, "p_enum", False), # Cross (0 is None, i.e. invisible?).
207 if override_defaults
is not None:
208 props
.update(override_defaults
)
209 return FBXTemplate(b
"NodeAttribute", b
"FbxNull", props
, nbr_users
, [False])
212 def fbx_template_def_light(scene
, settings
, override_defaults
=None, nbr_users
=0):
213 gscale
= settings
.global_scale
215 b
"LightType": (0, "p_enum", False), # Point light.
216 b
"CastLight": (True, "p_bool", False),
217 b
"Color": ((1.0, 1.0, 1.0), "p_color", True),
218 b
"Intensity": (100.0, "p_number", True), # Times 100 compared to Blender values...
219 b
"DecayType": (2, "p_enum", False), # Quadratic.
220 b
"DecayStart": (30.0 * gscale
, "p_double", False),
221 b
"CastShadows": (True, "p_bool", False),
222 b
"ShadowColor": ((0.0, 0.0, 0.0), "p_color", True),
223 b
"AreaLightShape": (0, "p_enum", False), # Rectangle.
225 if override_defaults
is not None:
226 props
.update(override_defaults
)
227 return FBXTemplate(b
"NodeAttribute", b
"FbxLight", props
, nbr_users
, [False])
230 def fbx_template_def_camera(scene
, settings
, override_defaults
=None, nbr_users
=0):
233 b
"Color": ((0.8, 0.8, 0.8), "p_color_rgb", False),
234 b
"Position": ((0.0, 0.0, -50.0), "p_vector", True),
235 b
"UpVector": ((0.0, 1.0, 0.0), "p_vector", True),
236 b
"InterestPosition": ((0.0, 0.0, 0.0), "p_vector", True),
237 b
"Roll": (0.0, "p_roll", True),
238 b
"OpticalCenterX": (0.0, "p_opticalcenterx", True),
239 b
"OpticalCenterY": (0.0, "p_opticalcentery", True),
240 b
"BackgroundColor": ((0.63, 0.63, 0.63), "p_color", True),
241 b
"TurnTable": (0.0, "p_number", True),
242 b
"DisplayTurnTableIcon": (False, "p_bool", False),
243 b
"UseMotionBlur": (False, "p_bool", False),
244 b
"UseRealTimeMotionBlur": (True, "p_bool", False),
245 b
"Motion Blur Intensity": (1.0, "p_number", True),
246 b
"AspectRatioMode": (0, "p_enum", False), # WindowSize.
247 b
"AspectWidth": (320.0, "p_double", False),
248 b
"AspectHeight": (200.0, "p_double", False),
249 b
"PixelAspectRatio": (1.0, "p_double", False),
250 b
"FilmOffsetX": (0.0, "p_number", True),
251 b
"FilmOffsetY": (0.0, "p_number", True),
252 b
"FilmWidth": (0.816, "p_double", False),
253 b
"FilmHeight": (0.612, "p_double", False),
254 b
"FilmAspectRatio": (1.3333333333333333, "p_double", False),
255 b
"FilmSqueezeRatio": (1.0, "p_double", False),
256 b
"FilmFormatIndex": (0, "p_enum", False), # Assuming this is ApertureFormat, 0 = custom.
257 b
"PreScale": (1.0, "p_number", True),
258 b
"FilmTranslateX": (0.0, "p_number", True),
259 b
"FilmTranslateY": (0.0, "p_number", True),
260 b
"FilmRollPivotX": (0.0, "p_number", True),
261 b
"FilmRollPivotY": (0.0, "p_number", True),
262 b
"FilmRollValue": (0.0, "p_number", True),
263 b
"FilmRollOrder": (0, "p_enum", False), # 0 = rotate first (default).
264 b
"ApertureMode": (2, "p_enum", False), # 2 = Vertical.
265 b
"GateFit": (0, "p_enum", False), # 0 = no resolution gate fit.
266 b
"FieldOfView": (25.114999771118164, "p_fov", True),
267 b
"FieldOfViewX": (40.0, "p_fov_x", True),
268 b
"FieldOfViewY": (40.0, "p_fov_y", True),
269 b
"FocalLength": (34.89327621672628, "p_number", True),
270 b
"CameraFormat": (0, "p_enum", False), # Custom camera format.
271 b
"UseFrameColor": (False, "p_bool", False),
272 b
"FrameColor": ((0.3, 0.3, 0.3), "p_color_rgb", False),
273 b
"ShowName": (True, "p_bool", False),
274 b
"ShowInfoOnMoving": (True, "p_bool", False),
275 b
"ShowGrid": (True, "p_bool", False),
276 b
"ShowOpticalCenter": (False, "p_bool", False),
277 b
"ShowAzimut": (True, "p_bool", False),
278 b
"ShowTimeCode": (False, "p_bool", False),
279 b
"ShowAudio": (False, "p_bool", False),
280 b
"AudioColor": ((0.0, 1.0, 0.0), "p_vector_3d", False), # Yep, vector3d, not corlorgb… :cry:
281 b
"NearPlane": (10.0, "p_double", False),
282 b
"FarPlane": (4000.0, "p_double", False),
283 b
"AutoComputeClipPanes": (False, "p_bool", False),
284 b
"ViewCameraToLookAt": (True, "p_bool", False),
285 b
"ViewFrustumNearFarPlane": (False, "p_bool", False),
286 b
"ViewFrustumBackPlaneMode": (2, "p_enum", False), # 2 = show back plane if texture added.
287 b
"BackPlaneDistance": (4000.0, "p_number", True),
288 b
"BackPlaneDistanceMode": (1, "p_enum", False), # 1 = relative to camera.
289 b
"ViewFrustumFrontPlaneMode": (2, "p_enum", False), # 2 = show front plane if texture added.
290 b
"FrontPlaneDistance": (10.0, "p_number", True),
291 b
"FrontPlaneDistanceMode": (1, "p_enum", False), # 1 = relative to camera.
292 b
"LockMode": (False, "p_bool", False),
293 b
"LockInterestNavigation": (False, "p_bool", False),
294 # BackPlate... properties **arggggg!**
295 b
"FitImage": (False, "p_bool", False),
296 b
"Crop": (False, "p_bool", False),
297 b
"Center": (True, "p_bool", False),
298 b
"KeepRatio": (True, "p_bool", False),
299 # End of BackPlate...
300 b
"BackgroundAlphaTreshold": (0.5, "p_double", False),
301 b
"ShowBackplate": (True, "p_bool", False),
302 b
"BackPlaneOffsetX": (0.0, "p_number", True),
303 b
"BackPlaneOffsetY": (0.0, "p_number", True),
304 b
"BackPlaneRotation": (0.0, "p_number", True),
305 b
"BackPlaneScaleX": (1.0, "p_number", True),
306 b
"BackPlaneScaleY": (1.0, "p_number", True),
307 b
"Background Texture": (None, "p_object", False),
308 b
"FrontPlateFitImage": (True, "p_bool", False),
309 b
"FrontPlateCrop": (False, "p_bool", False),
310 b
"FrontPlateCenter": (True, "p_bool", False),
311 b
"FrontPlateKeepRatio": (True, "p_bool", False),
312 b
"Foreground Opacity": (1.0, "p_double", False),
313 b
"ShowFrontplate": (True, "p_bool", False),
314 b
"FrontPlaneOffsetX": (0.0, "p_number", True),
315 b
"FrontPlaneOffsetY": (0.0, "p_number", True),
316 b
"FrontPlaneRotation": (0.0, "p_number", True),
317 b
"FrontPlaneScaleX": (1.0, "p_number", True),
318 b
"FrontPlaneScaleY": (1.0, "p_number", True),
319 b
"Foreground Texture": (None, "p_object", False),
320 b
"DisplaySafeArea": (False, "p_bool", False),
321 b
"DisplaySafeAreaOnRender": (False, "p_bool", False),
322 b
"SafeAreaDisplayStyle": (1, "p_enum", False), # 1 = rounded corners.
323 b
"SafeAreaAspectRatio": (1.3333333333333333, "p_double", False),
324 b
"Use2DMagnifierZoom": (False, "p_bool", False),
325 b
"2D Magnifier Zoom": (100.0, "p_number", True),
326 b
"2D Magnifier X": (50.0, "p_number", True),
327 b
"2D Magnifier Y": (50.0, "p_number", True),
328 b
"CameraProjectionType": (0, "p_enum", False), # 0 = perspective, 1 = orthogonal.
329 b
"OrthoZoom": (1.0, "p_double", False),
330 b
"UseRealTimeDOFAndAA": (False, "p_bool", False),
331 b
"UseDepthOfField": (False, "p_bool", False),
332 b
"FocusSource": (0, "p_enum", False), # 0 = camera interest, 1 = distance from camera interest.
333 b
"FocusAngle": (3.5, "p_double", False), # ???
334 b
"FocusDistance": (200.0, "p_double", False),
335 b
"UseAntialiasing": (False, "p_bool", False),
336 b
"AntialiasingIntensity": (0.77777, "p_double", False),
337 b
"AntialiasingMethod": (0, "p_enum", False), # 0 = oversampling, 1 = hardware.
338 b
"UseAccumulationBuffer": (False, "p_bool", False),
339 b
"FrameSamplingCount": (7, "p_integer", False),
340 b
"FrameSamplingType": (1, "p_enum", False), # 0 = uniform, 1 = stochastic.
342 if override_defaults
is not None:
343 props
.update(override_defaults
)
344 return FBXTemplate(b
"NodeAttribute", b
"FbxCamera", props
, nbr_users
, [False])
347 def fbx_template_def_bone(scene
, settings
, override_defaults
=None, nbr_users
=0):
349 if override_defaults
is not None:
350 props
.update(override_defaults
)
351 return FBXTemplate(b
"NodeAttribute", b
"LimbNode", props
, nbr_users
, [False])
354 def fbx_template_def_geometry(scene
, settings
, override_defaults
=None, nbr_users
=0):
356 b
"Color": ((0.8, 0.8, 0.8), "p_color_rgb", False),
357 b
"BBoxMin": ((0.0, 0.0, 0.0), "p_vector_3d", False),
358 b
"BBoxMax": ((0.0, 0.0, 0.0), "p_vector_3d", False),
359 b
"Primary Visibility": (True, "p_bool", False),
360 b
"Casts Shadows": (True, "p_bool", False),
361 b
"Receive Shadows": (True, "p_bool", False),
363 if override_defaults
is not None:
364 props
.update(override_defaults
)
365 return FBXTemplate(b
"Geometry", b
"FbxMesh", props
, nbr_users
, [False])
368 def fbx_template_def_material(scene
, settings
, override_defaults
=None, nbr_users
=0):
371 b
"ShadingModel": ("Phong", "p_string", False),
372 b
"MultiLayer": (False, "p_bool", False),
374 b
"EmissiveColor": ((0.0, 0.0, 0.0), "p_color", True),
375 b
"EmissiveFactor": (1.0, "p_number", True),
376 b
"AmbientColor": ((0.2, 0.2, 0.2), "p_color", True),
377 b
"AmbientFactor": (1.0, "p_number", True),
378 b
"DiffuseColor": ((0.8, 0.8, 0.8), "p_color", True),
379 b
"DiffuseFactor": (1.0, "p_number", True),
380 b
"TransparentColor": ((0.0, 0.0, 0.0), "p_color", True),
381 b
"TransparencyFactor": (0.0, "p_number", True),
382 b
"Opacity": (1.0, "p_number", True),
383 b
"NormalMap": ((0.0, 0.0, 0.0), "p_vector_3d", False),
384 b
"Bump": ((0.0, 0.0, 0.0), "p_vector_3d", False),
385 b
"BumpFactor": (1.0, "p_double", False),
386 b
"DisplacementColor": ((0.0, 0.0, 0.0), "p_color_rgb", False),
387 b
"DisplacementFactor": (1.0, "p_double", False),
388 b
"VectorDisplacementColor": ((0.0, 0.0, 0.0), "p_color_rgb", False),
389 b
"VectorDisplacementFactor": (1.0, "p_double", False),
391 b
"SpecularColor": ((0.2, 0.2, 0.2), "p_color", True),
392 b
"SpecularFactor": (1.0, "p_number", True),
393 # Not sure about the name, importer uses this (but ShininessExponent for tex prop name!)
394 # And in fbx exported by sdk, you have one in template, the other in actual material!!! :/
395 # For now, using both.
396 b
"Shininess": (20.0, "p_number", True),
397 b
"ShininessExponent": (20.0, "p_number", True),
398 b
"ReflectionColor": ((0.0, 0.0, 0.0), "p_color", True),
399 b
"ReflectionFactor": (1.0, "p_number", True),
401 if override_defaults
is not None:
402 props
.update(override_defaults
)
403 return FBXTemplate(b
"Material", b
"FbxSurfacePhong", props
, nbr_users
, [False])
406 def fbx_template_def_texture_file(scene
, settings
, override_defaults
=None, nbr_users
=0):
408 # XXX Not sure about all names!
410 b
"TextureTypeUse": (0, "p_enum", False), # Standard.
411 b
"AlphaSource": (2, "p_enum", False), # Black (i.e. texture's alpha), XXX name guessed!.
412 b
"Texture alpha": (1.0, "p_double", False),
413 b
"PremultiplyAlpha": (True, "p_bool", False),
414 b
"CurrentTextureBlendMode": (1, "p_enum", False), # Additive...
415 b
"CurrentMappingType": (0, "p_enum", False), # UV.
416 b
"UVSet": ("default", "p_string", False), # UVMap name.
417 b
"WrapModeU": (0, "p_enum", False), # Repeat.
418 b
"WrapModeV": (0, "p_enum", False), # Repeat.
419 b
"UVSwap": (False, "p_bool", False),
420 b
"Translation": ((0.0, 0.0, 0.0), "p_vector_3d", False),
421 b
"Rotation": ((0.0, 0.0, 0.0), "p_vector_3d", False),
422 b
"Scaling": ((1.0, 1.0, 1.0), "p_vector_3d", False),
423 b
"TextureRotationPivot": ((0.0, 0.0, 0.0), "p_vector_3d", False),
424 b
"TextureScalingPivot": ((0.0, 0.0, 0.0), "p_vector_3d", False),
425 # Not sure about those two...
426 b
"UseMaterial": (False, "p_bool", False),
427 b
"UseMipMap": (False, "p_bool", False),
429 if override_defaults
is not None:
430 props
.update(override_defaults
)
431 return FBXTemplate(b
"Texture", b
"FbxFileTexture", props
, nbr_users
, [False])
434 def fbx_template_def_video(scene
, settings
, override_defaults
=None, nbr_users
=0):
438 b
"Width": (0, "p_integer", False),
439 b
"Height": (0, "p_integer", False),
440 b
"Path": ("", "p_string_url", False),
441 b
"AccessMode": (0, "p_enum", False), # Disk (0=Disk, 1=Mem, 2=DiskAsync).
443 b
"StartFrame": (0, "p_integer", False),
444 b
"StopFrame": (0, "p_integer", False),
445 b
"Offset": (0, "p_timestamp", False),
446 b
"PlaySpeed": (0.0, "p_double", False),
447 b
"FreeRunning": (False, "p_bool", False),
448 b
"Loop": (False, "p_bool", False),
449 b
"InterlaceMode": (0, "p_enum", False), # None, i.e. progressive.
451 b
"ImageSequence": (False, "p_bool", False),
452 b
"ImageSequenceOffset": (0, "p_integer", False),
453 b
"FrameRate": (0.0, "p_double", False),
454 b
"LastFrame": (0, "p_integer", False),
456 if override_defaults
is not None:
457 props
.update(override_defaults
)
458 return FBXTemplate(b
"Video", b
"FbxVideo", props
, nbr_users
, [False])
461 def fbx_template_def_pose(scene
, settings
, override_defaults
=None, nbr_users
=0):
463 if override_defaults
is not None:
464 props
.update(override_defaults
)
465 return FBXTemplate(b
"Pose", b
"", props
, nbr_users
, [False])
468 def fbx_template_def_deformer(scene
, settings
, override_defaults
=None, nbr_users
=0):
470 if override_defaults
is not None:
471 props
.update(override_defaults
)
472 return FBXTemplate(b
"Deformer", b
"", props
, nbr_users
, [False])
475 def fbx_template_def_animstack(scene
, settings
, override_defaults
=None, nbr_users
=0):
477 b
"Description": ("", "p_string", False),
478 b
"LocalStart": (0, "p_timestamp", False),
479 b
"LocalStop": (0, "p_timestamp", False),
480 b
"ReferenceStart": (0, "p_timestamp", False),
481 b
"ReferenceStop": (0, "p_timestamp", False),
483 if override_defaults
is not None:
484 props
.update(override_defaults
)
485 return FBXTemplate(b
"AnimationStack", b
"FbxAnimStack", props
, nbr_users
, [False])
488 def fbx_template_def_animlayer(scene
, settings
, override_defaults
=None, nbr_users
=0):
490 b
"Weight": (100.0, "p_number", True),
491 b
"Mute": (False, "p_bool", False),
492 b
"Solo": (False, "p_bool", False),
493 b
"Lock": (False, "p_bool", False),
494 b
"Color": ((0.8, 0.8, 0.8), "p_color_rgb", False),
495 b
"BlendMode": (0, "p_enum", False),
496 b
"RotationAccumulationMode": (0, "p_enum", False),
497 b
"ScaleAccumulationMode": (0, "p_enum", False),
498 b
"BlendModeBypass": (0, "p_ulonglong", False),
500 if override_defaults
is not None:
501 props
.update(override_defaults
)
502 return FBXTemplate(b
"AnimationLayer", b
"FbxAnimLayer", props
, nbr_users
, [False])
505 def fbx_template_def_animcurvenode(scene
, settings
, override_defaults
=None, nbr_users
=0):
507 FBX_ANIM_PROPSGROUP_NAME
.encode(): (None, "p_compound", False),
509 if override_defaults
is not None:
510 props
.update(override_defaults
)
511 return FBXTemplate(b
"AnimationCurveNode", b
"FbxAnimCurveNode", props
, nbr_users
, [False])
514 def fbx_template_def_animcurve(scene
, settings
, override_defaults
=None, nbr_users
=0):
516 if override_defaults
is not None:
517 props
.update(override_defaults
)
518 return FBXTemplate(b
"AnimationCurve", b
"", props
, nbr_users
, [False])
521 # ##### Generators for connection elements. #####
523 def elem_connection(elem
, c_type
, uid_src
, uid_dst
, prop_dst
=None):
524 e
= elem_data_single_string(elem
, b
"C", c_type
)
527 if prop_dst
is not None:
528 e
.add_string(prop_dst
)
531 # ##### FBX objects generators. #####
533 def fbx_data_element_custom_properties(props
, bid
):
535 Store custom properties of blender ID bid (any mapping-like object, in fact) into FBX properties props.
542 rna_properties
= {prop
.identifier
for prop
in bid
.bl_rna
.properties
if prop
.is_runtime
}
545 if k
== '_RNA_UI' or k
in rna_properties
:
548 list_val
= getattr(v
, "to_list", lambda: None)()
550 if isinstance(v
, str):
551 elem_props_set(props
, "p_string", k
.encode(), v
, custom
=True)
552 elif isinstance(v
, int):
553 elem_props_set(props
, "p_integer", k
.encode(), v
, custom
=True)
554 elif isinstance(v
, float):
555 elem_props_set(props
, "p_double", k
.encode(), v
, custom
=True)
557 if len(list_val
) == 3:
558 elem_props_set(props
, "p_vector", k
.encode(), list_val
, custom
=True)
560 elem_props_set(props
, "p_string", k
.encode(), str(list_val
), custom
=True)
562 elem_props_set(props
, "p_string", k
.encode(), str(v
), custom
=True)
565 def fbx_data_empty_elements(root
, empty
, scene_data
):
567 Write the Empty data block (you can control its FBX datatype with the 'fbx_type' string custom property).
569 empty_key
= scene_data
.data_empties
[empty
]
571 null
= elem_data_single_int64(root
, b
"NodeAttribute", get_fbx_uuid_from_key(empty_key
))
572 null
.add_string(fbx_name_class(empty
.name
.encode(), b
"NodeAttribute"))
573 val
= empty
.bdata
.get('fbx_type', None)
574 null
.add_string(val
.encode() if val
and isinstance(val
, str) else b
"Null")
576 elem_data_single_string(null
, b
"TypeFlags", b
"Null")
578 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Null")
579 props
= elem_properties(null
)
580 elem_props_template_finalize(tmpl
, props
)
582 # No custom properties, already saved with object (Model).
585 def fbx_data_light_elements(root
, lamp
, scene_data
):
587 Write the Lamp data block.
589 gscale
= scene_data
.settings
.global_scale
591 light_key
= scene_data
.data_lights
[lamp
]
593 decay_type
= FBX_LIGHT_DECAY_TYPES
['CONSTANT']
595 shadow_color
= Vector((0.0, 0.0, 0.0))
596 if lamp
.type not in {'HEMI'}:
597 if lamp
.type not in {'SUN', 'AREA'}:
598 decay_type
= FBX_LIGHT_DECAY_TYPES
[lamp
.falloff_type
]
600 do_shadow
= lamp
.use_shadow
601 shadow_color
= lamp
.shadow_color
603 light
= elem_data_single_int64(root
, b
"NodeAttribute", get_fbx_uuid_from_key(light_key
))
604 light
.add_string(fbx_name_class(lamp
.name
.encode(), b
"NodeAttribute"))
605 light
.add_string(b
"Light")
607 elem_data_single_int32(light
, b
"GeometryVersion", FBX_GEOMETRY_VERSION
) # Sic...
609 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Light")
610 props
= elem_properties(light
)
611 elem_props_template_set(tmpl
, props
, "p_enum", b
"LightType", FBX_LIGHT_TYPES
[lamp
.type])
612 elem_props_template_set(tmpl
, props
, "p_bool", b
"CastLight", do_light
)
613 elem_props_template_set(tmpl
, props
, "p_color", b
"Color", lamp
.color
)
614 elem_props_template_set(tmpl
, props
, "p_number", b
"Intensity", lamp
.energy
* 100.0)
615 elem_props_template_set(tmpl
, props
, "p_enum", b
"DecayType", decay_type
)
616 elem_props_template_set(tmpl
, props
, "p_double", b
"DecayStart", lamp
.distance
* gscale
)
617 elem_props_template_set(tmpl
, props
, "p_bool", b
"CastShadows", do_shadow
)
618 elem_props_template_set(tmpl
, props
, "p_color", b
"ShadowColor", shadow_color
)
619 if lamp
.type in {'SPOT'}:
620 elem_props_template_set(tmpl
, props
, "p_double", b
"OuterAngle", math
.degrees(lamp
.spot_size
))
621 elem_props_template_set(tmpl
, props
, "p_double", b
"InnerAngle",
622 math
.degrees(lamp
.spot_size
* (1.0 - lamp
.spot_blend
)))
623 elem_props_template_finalize(tmpl
, props
)
626 if scene_data
.settings
.use_custom_props
:
627 fbx_data_element_custom_properties(props
, lamp
)
630 def fbx_data_camera_elements(root
, cam_obj
, scene_data
):
632 Write the Camera data blocks.
634 gscale
= scene_data
.settings
.global_scale
638 cam_key
= scene_data
.data_cameras
[cam_obj
]
640 # Real data now, good old camera!
641 # Object transform info.
642 loc
, rot
, scale
, matrix
, matrix_rot
= cam_obj
.fbx_object_tx(scene_data
)
643 up
= matrix_rot
@ Vector((0.0, 1.0, 0.0))
644 to
= matrix_rot
@ Vector((0.0, 0.0, -1.0))
646 # TODO We could export much more...
647 render
= scene_data
.scene
.render
648 width
= render
.resolution_x
649 height
= render
.resolution_y
650 aspect
= width
/ height
651 # Film width & height from mm to inches
652 filmwidth
= convert_mm_to_inch(cam_data
.sensor_width
)
653 filmheight
= convert_mm_to_inch(cam_data
.sensor_height
)
654 filmaspect
= filmwidth
/ filmheight
656 offsetx
= filmwidth
* cam_data
.shift_x
657 offsety
= filmaspect
* filmheight
* cam_data
.shift_y
659 cam
= elem_data_single_int64(root
, b
"NodeAttribute", get_fbx_uuid_from_key(cam_key
))
660 cam
.add_string(fbx_name_class(cam_data
.name
.encode(), b
"NodeAttribute"))
661 cam
.add_string(b
"Camera")
663 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Camera")
664 props
= elem_properties(cam
)
666 elem_props_template_set(tmpl
, props
, "p_vector", b
"Position", loc
)
667 elem_props_template_set(tmpl
, props
, "p_vector", b
"UpVector", up
)
668 elem_props_template_set(tmpl
, props
, "p_vector", b
"InterestPosition", loc
+ to
) # Point, not vector!
669 # Should we use world value?
670 elem_props_template_set(tmpl
, props
, "p_color", b
"BackgroundColor", (0.0, 0.0, 0.0))
671 elem_props_template_set(tmpl
, props
, "p_bool", b
"DisplayTurnTableIcon", True)
673 elem_props_template_set(tmpl
, props
, "p_enum", b
"AspectRatioMode", 2) # FixedResolution
674 elem_props_template_set(tmpl
, props
, "p_double", b
"AspectWidth", float(render
.resolution_x
))
675 elem_props_template_set(tmpl
, props
, "p_double", b
"AspectHeight", float(render
.resolution_y
))
676 elem_props_template_set(tmpl
, props
, "p_double", b
"PixelAspectRatio",
677 float(render
.pixel_aspect_x
/ render
.pixel_aspect_y
))
679 elem_props_template_set(tmpl
, props
, "p_double", b
"FilmWidth", filmwidth
)
680 elem_props_template_set(tmpl
, props
, "p_double", b
"FilmHeight", filmheight
)
681 elem_props_template_set(tmpl
, props
, "p_double", b
"FilmAspectRatio", filmaspect
)
682 elem_props_template_set(tmpl
, props
, "p_double", b
"FilmOffsetX", offsetx
)
683 elem_props_template_set(tmpl
, props
, "p_double", b
"FilmOffsetY", offsety
)
685 elem_props_template_set(tmpl
, props
, "p_enum", b
"ApertureMode", 3) # FocalLength.
686 elem_props_template_set(tmpl
, props
, "p_enum", b
"GateFit", 2) # FitHorizontal.
687 elem_props_template_set(tmpl
, props
, "p_fov", b
"FieldOfView", math
.degrees(cam_data
.angle_x
))
688 elem_props_template_set(tmpl
, props
, "p_fov_x", b
"FieldOfViewX", math
.degrees(cam_data
.angle_x
))
689 elem_props_template_set(tmpl
, props
, "p_fov_y", b
"FieldOfViewY", math
.degrees(cam_data
.angle_y
))
690 # No need to convert to inches here...
691 elem_props_template_set(tmpl
, props
, "p_double", b
"FocalLength", cam_data
.lens
)
692 elem_props_template_set(tmpl
, props
, "p_double", b
"SafeAreaAspectRatio", aspect
)
693 # Default to perspective camera.
694 elem_props_template_set(tmpl
, props
, "p_enum", b
"CameraProjectionType", 1 if cam_data
.type == 'ORTHO' else 0)
695 elem_props_template_set(tmpl
, props
, "p_double", b
"OrthoZoom", cam_data
.ortho_scale
)
697 elem_props_template_set(tmpl
, props
, "p_double", b
"NearPlane", cam_data
.clip_start
* gscale
)
698 elem_props_template_set(tmpl
, props
, "p_double", b
"FarPlane", cam_data
.clip_end
* gscale
)
699 elem_props_template_set(tmpl
, props
, "p_enum", b
"BackPlaneDistanceMode", 1) # RelativeToCamera.
700 elem_props_template_set(tmpl
, props
, "p_double", b
"BackPlaneDistance", cam_data
.clip_end
* gscale
)
702 elem_props_template_finalize(tmpl
, props
)
705 if scene_data
.settings
.use_custom_props
:
706 fbx_data_element_custom_properties(props
, cam_data
)
708 elem_data_single_string(cam
, b
"TypeFlags", b
"Camera")
709 elem_data_single_int32(cam
, b
"GeometryVersion", 124) # Sic...
710 elem_data_vec_float64(cam
, b
"Position", loc
)
711 elem_data_vec_float64(cam
, b
"Up", up
)
712 elem_data_vec_float64(cam
, b
"LookAt", to
)
713 elem_data_single_int32(cam
, b
"ShowInfoOnMoving", 1)
714 elem_data_single_int32(cam
, b
"ShowAudio", 0)
715 elem_data_vec_float64(cam
, b
"AudioColor", (0.0, 1.0, 0.0))
716 elem_data_single_float64(cam
, b
"CameraOrthoZoom", 1.0)
719 def fbx_data_bindpose_element(root
, me_obj
, me
, scene_data
, arm_obj
=None, mat_world_arm
=None, bones
=[]):
721 Helper, since bindpose are used by both meshes shape keys and armature bones...
725 # We assume bind pose for our bones are their "Editmode" pose...
726 # All matrices are expected in global (world) space.
727 bindpose_key
= get_blender_bindpose_key(arm_obj
.bdata
, me
)
728 fbx_pose
= elem_data_single_int64(root
, b
"Pose", get_fbx_uuid_from_key(bindpose_key
))
729 fbx_pose
.add_string(fbx_name_class(me
.name
.encode(), b
"Pose"))
730 fbx_pose
.add_string(b
"BindPose")
732 elem_data_single_string(fbx_pose
, b
"Type", b
"BindPose")
733 elem_data_single_int32(fbx_pose
, b
"Version", FBX_POSE_BIND_VERSION
)
734 elem_data_single_int32(fbx_pose
, b
"NbPoseNodes", 1 + (1 if (arm_obj
!= me_obj
) else 0) + len(bones
))
736 # First node is mesh/object.
737 mat_world_obj
= me_obj
.fbx_object_matrix(scene_data
, global_space
=True)
738 fbx_posenode
= elem_empty(fbx_pose
, b
"PoseNode")
739 elem_data_single_int64(fbx_posenode
, b
"Node", me_obj
.fbx_uuid
)
740 elem_data_single_float64_array(fbx_posenode
, b
"Matrix", matrix4_to_array(mat_world_obj
))
741 # Second node is armature object itself.
742 if arm_obj
!= me_obj
:
743 fbx_posenode
= elem_empty(fbx_pose
, b
"PoseNode")
744 elem_data_single_int64(fbx_posenode
, b
"Node", arm_obj
.fbx_uuid
)
745 elem_data_single_float64_array(fbx_posenode
, b
"Matrix", matrix4_to_array(mat_world_arm
))
746 # And all bones of armature!
749 bomat
= bo_obj
.fbx_object_matrix(scene_data
, rest
=True, global_space
=True)
750 mat_world_bones
[bo_obj
] = bomat
751 fbx_posenode
= elem_empty(fbx_pose
, b
"PoseNode")
752 elem_data_single_int64(fbx_posenode
, b
"Node", bo_obj
.fbx_uuid
)
753 elem_data_single_float64_array(fbx_posenode
, b
"Matrix", matrix4_to_array(bomat
))
755 return mat_world_obj
, mat_world_bones
758 def fbx_data_mesh_shapes_elements(root
, me_obj
, me
, scene_data
, fbx_me_tmpl
, fbx_me_props
):
760 Write shape keys related data.
762 if me
not in scene_data
.data_deformers_shape
:
765 write_normals
= True # scene_data.settings.mesh_smooth_type in {'OFF'}
767 # First, write the geometry data itself (i.e. shapes).
768 _me_key
, shape_key
, shapes
= scene_data
.data_deformers_shape
[me
]
772 for shape
, (channel_key
, geom_key
, shape_verts_co
, shape_verts_idx
) in shapes
.items():
773 # Use vgroups as weights, if defined.
774 if shape
.vertex_group
and shape
.vertex_group
in me_obj
.bdata
.vertex_groups
:
775 shape_verts_weights
= [0.0] * (len(shape_verts_co
) // 3)
776 vg_idx
= me_obj
.bdata
.vertex_groups
[shape
.vertex_group
].index
777 for sk_idx
, v_idx
in enumerate(shape_verts_idx
):
778 for vg
in me
.vertices
[v_idx
].groups
:
779 if vg
.group
== vg_idx
:
780 shape_verts_weights
[sk_idx
] = vg
.weight
* 100.0
782 shape_verts_weights
= [100.0] * (len(shape_verts_co
) // 3)
783 channels
.append((channel_key
, shape
, shape_verts_weights
))
785 geom
= elem_data_single_int64(root
, b
"Geometry", get_fbx_uuid_from_key(geom_key
))
786 geom
.add_string(fbx_name_class(shape
.name
.encode(), b
"Geometry"))
787 geom
.add_string(b
"Shape")
789 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Geometry")
790 props
= elem_properties(geom
)
791 elem_props_template_finalize(tmpl
, props
)
793 elem_data_single_int32(geom
, b
"Version", FBX_GEOMETRY_SHAPE_VERSION
)
795 elem_data_single_int32_array(geom
, b
"Indexes", shape_verts_idx
)
796 elem_data_single_float64_array(geom
, b
"Vertices", shape_verts_co
)
798 elem_data_single_float64_array(geom
, b
"Normals", [0.0] * len(shape_verts_co
))
800 # Yiha! BindPose for shapekeys too! Dodecasigh...
801 # XXX Not sure yet whether several bindposes on same mesh are allowed, or not... :/
802 fbx_data_bindpose_element(root
, me_obj
, me
, scene_data
)
804 # ...and now, the deformers stuff.
805 fbx_shape
= elem_data_single_int64(root
, b
"Deformer", get_fbx_uuid_from_key(shape_key
))
806 fbx_shape
.add_string(fbx_name_class(me
.name
.encode(), b
"Deformer"))
807 fbx_shape
.add_string(b
"BlendShape")
809 elem_data_single_int32(fbx_shape
, b
"Version", FBX_DEFORMER_SHAPE_VERSION
)
811 for channel_key
, shape
, shape_verts_weights
in channels
:
812 fbx_channel
= elem_data_single_int64(root
, b
"Deformer", get_fbx_uuid_from_key(channel_key
))
813 fbx_channel
.add_string(fbx_name_class(shape
.name
.encode(), b
"SubDeformer"))
814 fbx_channel
.add_string(b
"BlendShapeChannel")
816 elem_data_single_int32(fbx_channel
, b
"Version", FBX_DEFORMER_SHAPECHANNEL_VERSION
)
817 elem_data_single_float64(fbx_channel
, b
"DeformPercent", shape
.value
* 100.0) # Percents...
818 elem_data_single_float64_array(fbx_channel
, b
"FullWeights", shape_verts_weights
)
820 # *WHY* add this in linked mesh properties too? *cry*
821 # No idea whether it’s percent here too, or more usual factor (assume percentage for now) :/
822 elem_props_template_set(fbx_me_tmpl
, fbx_me_props
, "p_number", shape
.name
.encode(), shape
.value
* 100.0,
826 def fbx_data_mesh_elements(root
, me_obj
, scene_data
, done_meshes
):
828 Write the Mesh (Geometry) data block.
831 def _infinite_gen(val
):
835 me_key
, me
, _free
= scene_data
.data_meshes
[me_obj
]
837 # In case of multiple instances of same mesh, only write it once!
838 if me_key
in done_meshes
:
841 # No gscale/gmat here, all data are supposed to be in object space.
842 smooth_type
= scene_data
.settings
.mesh_smooth_type
843 write_normals
= True # smooth_type in {'OFF'}
845 do_bake_space_transform
= me_obj
.use_bake_space_transform(scene_data
)
847 # Vertices are in object space, but we are post-multiplying all transforms with the inverse of the
848 # global matrix, so we need to apply the global matrix to the vertices to get the correct result.
849 geom_mat_co
= scene_data
.settings
.global_matrix
if do_bake_space_transform
else None
850 # We need to apply the inverse transpose of the global matrix when transforming normals.
851 geom_mat_no
= Matrix(scene_data
.settings
.global_matrix_inv_transposed
) if do_bake_space_transform
else None
852 if geom_mat_no
is not None:
853 # Remove translation & scaling!
854 geom_mat_no
.translation
= Vector()
855 geom_mat_no
.normalize()
857 geom
= elem_data_single_int64(root
, b
"Geometry", get_fbx_uuid_from_key(me_key
))
858 geom
.add_string(fbx_name_class(me
.name
.encode(), b
"Geometry"))
859 geom
.add_string(b
"Mesh")
861 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Geometry")
862 props
= elem_properties(geom
)
865 if scene_data
.settings
.use_custom_props
:
866 fbx_data_element_custom_properties(props
, me
)
868 # Subdivision levels. Take them from the first found subsurf modifier from the
869 # first object that has the mesh. Write crease information if the object has
870 # and subsurf modifier.
872 if scene_data
.settings
.use_subsurf
:
874 for mod
in me_obj
.bdata
.modifiers
:
875 if not (mod
.show_render
or mod
.show_viewport
):
877 if mod
.type == 'SUBSURF' and mod
.subdivision_type
== 'CATMULL_CLARK':
881 elem_data_single_int32(geom
, b
"Smoothness", 2) # Display control mesh and smoothed
882 elem_data_single_int32(geom
, b
"BoundaryRule", 2) # Round edges like Blender
883 elem_data_single_int32(geom
, b
"PreviewDivisionLevels", last_subsurf
.levels
)
884 elem_data_single_int32(geom
, b
"RenderDivisionLevels", last_subsurf
.render_levels
)
886 elem_data_single_int32(geom
, b
"PreserveBorders", 0)
887 elem_data_single_int32(geom
, b
"PreserveHardEdges", 0)
888 elem_data_single_int32(geom
, b
"PropagateEdgeHardness", 0)
890 write_crease
= last_subsurf
.use_creases
892 elem_data_single_int32(geom
, b
"GeometryVersion", FBX_GEOMETRY_VERSION
)
895 t_co
= array
.array(data_types
.ARRAY_FLOAT64
, (0.0,)) * len(me
.vertices
) * 3
896 me
.vertices
.foreach_get("co", t_co
)
897 elem_data_single_float64_array(geom
, b
"Vertices", chain(*vcos_transformed_gen(t_co
, geom_mat_co
)))
902 # We do loose edges as two-vertices faces, if enabled...
904 # Note we have to process Edges in the same time, as they are based on poly's loops...
905 loop_nbr
= len(me
.loops
)
906 t_pvi
= array
.array(data_types
.ARRAY_INT32
, (0,)) * loop_nbr
907 t_ls
= [None] * len(me
.polygons
)
909 me
.loops
.foreach_get("vertex_index", t_pvi
)
910 me
.polygons
.foreach_get("loop_start", t_ls
)
912 # Add "fake" faces for loose edges.
913 if scene_data
.settings
.use_mesh_edges
:
914 t_le
= tuple(e
.vertices
for e
in me
.edges
if e
.is_loose
)
915 t_pvi
.extend(chain(*t_le
))
916 t_ls
.extend(range(loop_nbr
, loop_nbr
+ len(t_le
), 2))
920 # Note: Edges are represented as a loop here: each edge uses a single index, which refers to the polygon array.
921 # The edge is made by the vertex indexed py this polygon's point and the next one on the same polygon.
922 # Advantage: Only one index per edge.
923 # Drawback: Only polygon's edges can be represented (that's why we have to add fake two-verts polygons
925 # We also have to store a mapping from real edges to their indices in this array, for edge-mapped data
926 # (like e.g. crease).
927 t_eli
= array
.array(data_types
.ARRAY_INT32
)
932 todo_edges
= [None] * len(me
.edges
) * 2
933 # Sigh, cannot access edge.key through foreach_get... :/
934 me
.edges
.foreach_get("vertices", todo_edges
)
935 todo_edges
= set((v1
, v2
) if v1
< v2
else (v2
, v1
) for v1
, v2
in zip(*(iter(todo_edges
),) * 2))
938 vi
= vi_start
= t_pvi
[0]
939 for li_next
, vi_next
in enumerate(t_pvi
[1:] + t_pvi
[:1], start
=1):
940 if li_next
in t_ls
: # End of a poly's loop.
946 e_key
= (vi
, vi2
) if vi
< vi2
else (vi2
, vi
)
947 if e_key
in todo_edges
:
949 todo_edges
.remove(e_key
)
950 edges_map
[e_key
] = edges_nbr
957 # We have to ^-1 last index of each loop.
961 # And finally we can write data!
962 elem_data_single_int32_array(geom
, b
"PolygonVertexIndex", t_pvi
)
963 elem_data_single_int32_array(geom
, b
"Edges", t_eli
)
971 if smooth_type
in {'FACE', 'EDGE'}:
974 if smooth_type
== 'FACE':
975 t_ps
= array
.array(data_types
.ARRAY_INT32
, (0,)) * len(me
.polygons
)
976 me
.polygons
.foreach_get("use_smooth", t_ps
)
979 # Write Edge Smoothing.
980 # Note edge is sharp also if it's used by more than two faces, or one of its faces is flat.
981 t_ps
= array
.array(data_types
.ARRAY_INT32
, (0,)) * edges_nbr
983 temp_sharp_edges
= {}
984 for p
in me
.polygons
:
986 sharp_edges
.update(p
.edge_keys
)
988 for k
in p
.edge_keys
:
989 if temp_sharp_edges
.setdefault(k
, 0) > 1:
992 temp_sharp_edges
[k
] += 1
995 if e
.key
not in edges_map
:
996 continue # Only loose edges, in theory!
997 t_ps
[edges_map
[e
.key
]] = not (e
.use_edge_sharp
or (e
.key
in sharp_edges
))
999 lay_smooth
= elem_data_single_int32(geom
, b
"LayerElementSmoothing", 0)
1000 elem_data_single_int32(lay_smooth
, b
"Version", FBX_GEOMETRY_SMOOTHING_VERSION
)
1001 elem_data_single_string(lay_smooth
, b
"Name", b
"")
1002 elem_data_single_string(lay_smooth
, b
"MappingInformationType", _map
)
1003 elem_data_single_string(lay_smooth
, b
"ReferenceInformationType", b
"Direct")
1004 elem_data_single_int32_array(lay_smooth
, b
"Smoothing", t_ps
) # Sight, int32 for bool...
1007 # Edge crease for subdivision
1009 t_ec
= array
.array(data_types
.ARRAY_FLOAT64
, (0.0,)) * edges_nbr
1011 if e
.key
not in edges_map
:
1012 continue # Only loose edges, in theory!
1013 # Blender squares those values before sending them to OpenSubdiv, when other softwares don't,
1014 # so we need to compensate that to get similar results through FBX...
1015 t_ec
[edges_map
[e
.key
]] = e
.crease
* e
.crease
1017 lay_crease
= elem_data_single_int32(geom
, b
"LayerElementEdgeCrease", 0)
1018 elem_data_single_int32(lay_crease
, b
"Version", FBX_GEOMETRY_CREASE_VERSION
)
1019 elem_data_single_string(lay_crease
, b
"Name", b
"")
1020 elem_data_single_string(lay_crease
, b
"MappingInformationType", b
"ByEdge")
1021 elem_data_single_string(lay_crease
, b
"ReferenceInformationType", b
"Direct")
1022 elem_data_single_float64_array(lay_crease
, b
"EdgeCrease", t_ec
)
1025 # And we are done with edges!
1031 # NOTE: this is not supported by importer currently.
1032 # XXX Official docs says normals should use IndexToDirect,
1033 # but this does not seem well supported by apps currently...
1034 me
.calc_normals_split()
1036 t_ln
= array
.array(data_types
.ARRAY_FLOAT64
, (0.0,)) * len(me
.loops
) * 3
1037 me
.loops
.foreach_get("normal", t_ln
)
1038 t_ln
= nors_transformed_gen(t_ln
, geom_mat_no
)
1040 t_ln
= tuple(t_ln
) # No choice... :/
1042 lay_nor
= elem_data_single_int32(geom
, b
"LayerElementNormal", 0)
1043 elem_data_single_int32(lay_nor
, b
"Version", FBX_GEOMETRY_NORMAL_VERSION
)
1044 elem_data_single_string(lay_nor
, b
"Name", b
"")
1045 elem_data_single_string(lay_nor
, b
"MappingInformationType", b
"ByPolygonVertex")
1046 elem_data_single_string(lay_nor
, b
"ReferenceInformationType", b
"IndexToDirect")
1048 ln2idx
= tuple(set(t_ln
))
1049 elem_data_single_float64_array(lay_nor
, b
"Normals", chain(*ln2idx
))
1050 # Normal weights, no idea what it is.
1051 # t_lnw = array.array(data_types.ARRAY_FLOAT64, (0.0,)) * len(ln2idx)
1052 # elem_data_single_float64_array(lay_nor, b"NormalsW", t_lnw)
1054 ln2idx
= {nor
: idx
for idx
, nor
in enumerate(ln2idx
)}
1055 elem_data_single_int32_array(lay_nor
, b
"NormalsIndex", (ln2idx
[n
] for n
in t_ln
))
1060 lay_nor
= elem_data_single_int32(geom
, b
"LayerElementNormal", 0)
1061 elem_data_single_int32(lay_nor
, b
"Version", FBX_GEOMETRY_NORMAL_VERSION
)
1062 elem_data_single_string(lay_nor
, b
"Name", b
"")
1063 elem_data_single_string(lay_nor
, b
"MappingInformationType", b
"ByPolygonVertex")
1064 elem_data_single_string(lay_nor
, b
"ReferenceInformationType", b
"Direct")
1065 elem_data_single_float64_array(lay_nor
, b
"Normals", chain(*t_ln
))
1066 # Normal weights, no idea what it is.
1067 # t_ln = array.array(data_types.ARRAY_FLOAT64, (0.0,)) * len(me.loops)
1068 # elem_data_single_float64_array(lay_nor, b"NormalsW", t_ln)
1072 if scene_data
.settings
.use_tspace
:
1073 tspacenumber
= len(me
.uv_layers
)
1075 # We can only compute tspace on tessellated meshes, need to check that here...
1076 t_lt
= [None] * len(me
.polygons
)
1077 me
.polygons
.foreach_get("loop_total", t_lt
)
1078 if any((lt
> 4 for lt
in t_lt
)):
1080 scene_data
.settings
.report(
1082 "Mesh '%s' has polygons with more than 4 vertices, "
1083 "cannot compute/export tangent space for it" % me
.name
)
1086 t_ln
= array
.array(data_types
.ARRAY_FLOAT64
, (0.0,)) * len(me
.loops
) * 3
1087 # t_lnw = array.array(data_types.ARRAY_FLOAT64, (0.0,)) * len(me.loops)
1088 uv_names
= [uvlayer
.name
for uvlayer
in me
.uv_layers
]
1089 for name
in uv_names
:
1090 me
.calc_tangents(uvmap
=name
)
1091 for idx
, uvlayer
in enumerate(me
.uv_layers
):
1093 # Loop bitangents (aka binormals).
1094 # NOTE: this is not supported by importer currently.
1095 me
.loops
.foreach_get("bitangent", t_ln
)
1096 lay_nor
= elem_data_single_int32(geom
, b
"LayerElementBinormal", idx
)
1097 elem_data_single_int32(lay_nor
, b
"Version", FBX_GEOMETRY_BINORMAL_VERSION
)
1098 elem_data_single_string_unicode(lay_nor
, b
"Name", name
)
1099 elem_data_single_string(lay_nor
, b
"MappingInformationType", b
"ByPolygonVertex")
1100 elem_data_single_string(lay_nor
, b
"ReferenceInformationType", b
"Direct")
1101 elem_data_single_float64_array(lay_nor
, b
"Binormals",
1102 chain(*nors_transformed_gen(t_ln
, geom_mat_no
)))
1103 # Binormal weights, no idea what it is.
1104 # elem_data_single_float64_array(lay_nor, b"BinormalsW", t_lnw)
1107 # NOTE: this is not supported by importer currently.
1108 me
.loops
.foreach_get("tangent", t_ln
)
1109 lay_nor
= elem_data_single_int32(geom
, b
"LayerElementTangent", idx
)
1110 elem_data_single_int32(lay_nor
, b
"Version", FBX_GEOMETRY_TANGENT_VERSION
)
1111 elem_data_single_string_unicode(lay_nor
, b
"Name", name
)
1112 elem_data_single_string(lay_nor
, b
"MappingInformationType", b
"ByPolygonVertex")
1113 elem_data_single_string(lay_nor
, b
"ReferenceInformationType", b
"Direct")
1114 elem_data_single_float64_array(lay_nor
, b
"Tangents",
1115 chain(*nors_transformed_gen(t_ln
, geom_mat_no
)))
1116 # Tangent weights, no idea what it is.
1117 # elem_data_single_float64_array(lay_nor, b"TangentsW", t_lnw)
1123 me
.free_normals_split()
1125 # Write VertexColor Layers.
1126 vcolnumber
= len(me
.vertex_colors
)
1128 def _coltuples_gen(raw_cols
):
1129 return zip(*(iter(raw_cols
),) * 4)
1131 t_lc
= array
.array(data_types
.ARRAY_FLOAT64
, (0.0,)) * len(me
.loops
) * 4
1132 for colindex
, collayer
in enumerate(me
.vertex_colors
):
1133 collayer
.data
.foreach_get("color", t_lc
)
1134 lay_vcol
= elem_data_single_int32(geom
, b
"LayerElementColor", colindex
)
1135 elem_data_single_int32(lay_vcol
, b
"Version", FBX_GEOMETRY_VCOLOR_VERSION
)
1136 elem_data_single_string_unicode(lay_vcol
, b
"Name", collayer
.name
)
1137 elem_data_single_string(lay_vcol
, b
"MappingInformationType", b
"ByPolygonVertex")
1138 elem_data_single_string(lay_vcol
, b
"ReferenceInformationType", b
"IndexToDirect")
1140 col2idx
= tuple(set(_coltuples_gen(t_lc
)))
1141 elem_data_single_float64_array(lay_vcol
, b
"Colors", chain(*col2idx
)) # Flatten again...
1143 col2idx
= {col
: idx
for idx
, col
in enumerate(col2idx
)}
1144 elem_data_single_int32_array(lay_vcol
, b
"ColorIndex", (col2idx
[c
] for c
in _coltuples_gen(t_lc
)))
1150 # Note: LayerElementTexture is deprecated since FBX 2011 - luckily!
1151 # Textures are now only related to materials, in FBX!
1152 uvnumber
= len(me
.uv_layers
)
1154 # Looks like this mapping is also expected to convey UV islands (arg..... :((((( ).
1155 # So we need to generate unique triplets (uv, vertex_idx) here, not only just based on UV values.
1156 def _uvtuples_gen(raw_uvs
, raw_lvidxs
):
1157 return zip(zip(*(iter(raw_uvs
),) * 2), raw_lvidxs
)
1159 t_luv
= array
.array(data_types
.ARRAY_FLOAT64
, (0.0,)) * len(me
.loops
) * 2
1160 t_lvidx
= array
.array(data_types
.ARRAY_INT32
, (0,)) * len(me
.loops
)
1161 me
.loops
.foreach_get("vertex_index", t_lvidx
)
1162 for uvindex
, uvlayer
in enumerate(me
.uv_layers
):
1163 uvlayer
.data
.foreach_get("uv", t_luv
)
1164 lay_uv
= elem_data_single_int32(geom
, b
"LayerElementUV", uvindex
)
1165 elem_data_single_int32(lay_uv
, b
"Version", FBX_GEOMETRY_UV_VERSION
)
1166 elem_data_single_string_unicode(lay_uv
, b
"Name", uvlayer
.name
)
1167 elem_data_single_string(lay_uv
, b
"MappingInformationType", b
"ByPolygonVertex")
1168 elem_data_single_string(lay_uv
, b
"ReferenceInformationType", b
"IndexToDirect")
1170 uv_ids
= tuple(set(_uvtuples_gen(t_luv
, t_lvidx
)))
1171 elem_data_single_float64_array(lay_uv
, b
"UV", chain(*(uv
for uv
, vidx
in uv_ids
))) # Flatten again...
1173 uv2idx
= {uv_id
: idx
for idx
, uv_id
in enumerate(uv_ids
)}
1174 elem_data_single_int32_array(lay_uv
, b
"UVIndex", (uv2idx
[uv_id
] for uv_id
in _uvtuples_gen(t_luv
, t_lvidx
)))
1182 me_fbxmaterials_idx
= scene_data
.mesh_material_indices
.get(me
)
1183 if me_fbxmaterials_idx
is not None:
1184 # We cannot use me.materials here, as this array is filled with None in case materials are linked to object...
1185 me_blmaterials
= [mat_slot
.material
for mat_slot
in me_obj
.material_slots
]
1186 if me_fbxmaterials_idx
and me_blmaterials
:
1187 lay_ma
= elem_data_single_int32(geom
, b
"LayerElementMaterial", 0)
1188 elem_data_single_int32(lay_ma
, b
"Version", FBX_GEOMETRY_MATERIAL_VERSION
)
1189 elem_data_single_string(lay_ma
, b
"Name", b
"")
1190 nbr_mats
= len(me_fbxmaterials_idx
)
1192 t_pm
= array
.array(data_types
.ARRAY_INT32
, (0,)) * len(me
.polygons
)
1193 me
.polygons
.foreach_get("material_index", t_pm
)
1195 # We have to validate mat indices, and map them to FBX indices.
1196 # Note a mat might not be in me_fbxmats_idx (e.g. node mats are ignored).
1197 blmaterials_to_fbxmaterials_idxs
= [me_fbxmaterials_idx
[m
]
1198 for m
in me_blmaterials
if m
in me_fbxmaterials_idx
]
1199 ma_idx_limit
= len(blmaterials_to_fbxmaterials_idxs
)
1200 def_ma
= blmaterials_to_fbxmaterials_idxs
[0]
1201 _gen
= (blmaterials_to_fbxmaterials_idxs
[m
] if m
< ma_idx_limit
else def_ma
for m
in t_pm
)
1202 t_pm
= array
.array(data_types
.ARRAY_INT32
, _gen
)
1204 elem_data_single_string(lay_ma
, b
"MappingInformationType", b
"ByPolygon")
1205 # XXX Logically, should be "Direct" reference type, since we do not have any index array, and have one
1206 # value per polygon...
1207 # But looks like FBX expects it to be IndexToDirect here (maybe because materials are already
1208 # indices??? *sigh*).
1209 elem_data_single_string(lay_ma
, b
"ReferenceInformationType", b
"IndexToDirect")
1210 elem_data_single_int32_array(lay_ma
, b
"Materials", t_pm
)
1213 elem_data_single_string(lay_ma
, b
"MappingInformationType", b
"AllSame")
1214 elem_data_single_string(lay_ma
, b
"ReferenceInformationType", b
"IndexToDirect")
1215 elem_data_single_int32_array(lay_ma
, b
"Materials", [0])
1217 # And the "layer TOC"...
1219 layer
= elem_data_single_int32(geom
, b
"Layer", 0)
1220 elem_data_single_int32(layer
, b
"Version", FBX_GEOMETRY_LAYER_VERSION
)
1222 lay_nor
= elem_empty(layer
, b
"LayerElement")
1223 elem_data_single_string(lay_nor
, b
"Type", b
"LayerElementNormal")
1224 elem_data_single_int32(lay_nor
, b
"TypedIndex", 0)
1226 lay_binor
= elem_empty(layer
, b
"LayerElement")
1227 elem_data_single_string(lay_binor
, b
"Type", b
"LayerElementBinormal")
1228 elem_data_single_int32(lay_binor
, b
"TypedIndex", 0)
1229 lay_tan
= elem_empty(layer
, b
"LayerElement")
1230 elem_data_single_string(lay_tan
, b
"Type", b
"LayerElementTangent")
1231 elem_data_single_int32(lay_tan
, b
"TypedIndex", 0)
1232 if smooth_type
in {'FACE', 'EDGE'}:
1233 lay_smooth
= elem_empty(layer
, b
"LayerElement")
1234 elem_data_single_string(lay_smooth
, b
"Type", b
"LayerElementSmoothing")
1235 elem_data_single_int32(lay_smooth
, b
"TypedIndex", 0)
1237 lay_smooth
= elem_empty(layer
, b
"LayerElement")
1238 elem_data_single_string(lay_smooth
, b
"Type", b
"LayerElementEdgeCrease")
1239 elem_data_single_int32(lay_smooth
, b
"TypedIndex", 0)
1241 lay_vcol
= elem_empty(layer
, b
"LayerElement")
1242 elem_data_single_string(lay_vcol
, b
"Type", b
"LayerElementColor")
1243 elem_data_single_int32(lay_vcol
, b
"TypedIndex", 0)
1245 lay_uv
= elem_empty(layer
, b
"LayerElement")
1246 elem_data_single_string(lay_uv
, b
"Type", b
"LayerElementUV")
1247 elem_data_single_int32(lay_uv
, b
"TypedIndex", 0)
1248 if me_fbxmaterials_idx
is not None:
1249 lay_ma
= elem_empty(layer
, b
"LayerElement")
1250 elem_data_single_string(lay_ma
, b
"Type", b
"LayerElementMaterial")
1251 elem_data_single_int32(lay_ma
, b
"TypedIndex", 0)
1253 # Add other uv and/or vcol layers...
1254 for vcolidx
, uvidx
, tspaceidx
in zip_longest(range(1, vcolnumber
), range(1, uvnumber
), range(1, tspacenumber
),
1256 layer
= elem_data_single_int32(geom
, b
"Layer", max(vcolidx
, uvidx
))
1257 elem_data_single_int32(layer
, b
"Version", FBX_GEOMETRY_LAYER_VERSION
)
1259 lay_vcol
= elem_empty(layer
, b
"LayerElement")
1260 elem_data_single_string(lay_vcol
, b
"Type", b
"LayerElementColor")
1261 elem_data_single_int32(lay_vcol
, b
"TypedIndex", vcolidx
)
1263 lay_uv
= elem_empty(layer
, b
"LayerElement")
1264 elem_data_single_string(lay_uv
, b
"Type", b
"LayerElementUV")
1265 elem_data_single_int32(lay_uv
, b
"TypedIndex", uvidx
)
1267 lay_binor
= elem_empty(layer
, b
"LayerElement")
1268 elem_data_single_string(lay_binor
, b
"Type", b
"LayerElementBinormal")
1269 elem_data_single_int32(lay_binor
, b
"TypedIndex", tspaceidx
)
1270 lay_tan
= elem_empty(layer
, b
"LayerElement")
1271 elem_data_single_string(lay_tan
, b
"Type", b
"LayerElementTangent")
1272 elem_data_single_int32(lay_tan
, b
"TypedIndex", tspaceidx
)
1275 fbx_data_mesh_shapes_elements(root
, me_obj
, me
, scene_data
, tmpl
, props
)
1277 elem_props_template_finalize(tmpl
, props
)
1278 done_meshes
.add(me_key
)
1281 def fbx_data_material_elements(root
, ma
, scene_data
):
1283 Write the Material data block.
1286 ambient_color
= (0.0, 0.0, 0.0)
1287 if scene_data
.data_world
:
1288 ambient_color
= next(iter(scene_data
.data_world
.keys())).color
1290 ma_wrap
= node_shader_utils
.PrincipledBSDFWrapper(ma
, is_readonly
=True)
1291 ma_key
, _objs
= scene_data
.data_materials
[ma
]
1294 fbx_ma
= elem_data_single_int64(root
, b
"Material", get_fbx_uuid_from_key(ma_key
))
1295 fbx_ma
.add_string(fbx_name_class(ma
.name
.encode(), b
"Material"))
1296 fbx_ma
.add_string(b
"")
1298 elem_data_single_int32(fbx_ma
, b
"Version", FBX_MATERIAL_VERSION
)
1299 # those are not yet properties, it seems...
1300 elem_data_single_string(fbx_ma
, b
"ShadingModel", ma_type
)
1301 elem_data_single_int32(fbx_ma
, b
"MultiLayer", 0) # Should be bool...
1303 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Material")
1304 props
= elem_properties(fbx_ma
)
1306 elem_props_template_set(tmpl
, props
, "p_string", b
"ShadingModel", ma_type
.decode())
1307 elem_props_template_set(tmpl
, props
, "p_color", b
"DiffuseColor", ma_wrap
.base_color
)
1308 # Not in Principled BSDF, so assuming always 1
1309 elem_props_template_set(tmpl
, props
, "p_number", b
"DiffuseFactor", 1.0)
1310 # Principled BSDF only has an emissive color, so we assume factor to be always 1.0.
1311 elem_props_template_set(tmpl
, props
, "p_color", b
"EmissiveColor", ma_wrap
.emission_color
)
1312 elem_props_template_set(tmpl
, props
, "p_number", b
"EmissiveFactor", ma_wrap
.emission_strength
)
1313 # Not in Principled BSDF, so assuming always 0
1314 elem_props_template_set(tmpl
, props
, "p_color", b
"AmbientColor", ambient_color
)
1315 elem_props_template_set(tmpl
, props
, "p_number", b
"AmbientFactor", 0.0)
1316 # Sweetness... Looks like we are not the only ones to not know exactly how FBX is supposed to work (see T59850).
1317 # According to one of its developers, Unity uses that formula to extract alpha value:
1319 # alpha = 1 - TransparencyFactor
1320 # if (alpha == 1 or alpha == 0):
1321 # alpha = 1 - TransparentColor.r
1323 # Until further info, let's assume this is correct way to do, hence the following code for TransparentColor.
1324 if ma_wrap
.alpha
< 1.0e-5 or ma_wrap
.alpha
> (1.0 - 1.0e-5):
1325 elem_props_template_set(tmpl
, props
, "p_color", b
"TransparentColor", (1.0 - ma_wrap
.alpha
,) * 3)
1327 elem_props_template_set(tmpl
, props
, "p_color", b
"TransparentColor", ma_wrap
.base_color
)
1328 elem_props_template_set(tmpl
, props
, "p_number", b
"TransparencyFactor", 1.0 - ma_wrap
.alpha
)
1329 elem_props_template_set(tmpl
, props
, "p_number", b
"Opacity", ma_wrap
.alpha
)
1330 elem_props_template_set(tmpl
, props
, "p_vector_3d", b
"NormalMap", (0.0, 0.0, 0.0))
1331 elem_props_template_set(tmpl
, props
, "p_double", b
"BumpFactor", ma_wrap
.normalmap_strength
)
1332 # Not sure about those...
1334 b"Bump": ((0.0, 0.0, 0.0), "p_vector_3d"),
1335 b"DisplacementColor": ((0.0, 0.0, 0.0), "p_color_rgb"),
1336 b"DisplacementFactor": (0.0, "p_double"),
1338 # TODO: use specular tint?
1339 elem_props_template_set(tmpl
, props
, "p_color", b
"SpecularColor", ma_wrap
.base_color
)
1340 elem_props_template_set(tmpl
, props
, "p_number", b
"SpecularFactor", ma_wrap
.specular
/ 2.0)
1341 # See Material template about those two!
1342 # XXX Totally empirical conversion, trying to adapt it
1343 # (from 0.0 - 100.0 FBX shininess range to 1.0 - 0.0 Principled BSDF range)...
1344 shininess
= (1.0 - ma_wrap
.roughness
) * 10
1345 shininess
*= shininess
1346 elem_props_template_set(tmpl
, props
, "p_number", b
"Shininess", shininess
)
1347 elem_props_template_set(tmpl
, props
, "p_number", b
"ShininessExponent", shininess
)
1348 elem_props_template_set(tmpl
, props
, "p_color", b
"ReflectionColor", ma_wrap
.base_color
)
1349 elem_props_template_set(tmpl
, props
, "p_number", b
"ReflectionFactor", ma_wrap
.metallic
)
1351 elem_props_template_finalize(tmpl
, props
)
1353 # Custom properties.
1354 if scene_data
.settings
.use_custom_props
:
1355 fbx_data_element_custom_properties(props
, ma
)
1358 def _gen_vid_path(img
, scene_data
):
1359 msetts
= scene_data
.settings
.media_settings
1360 fname_rel
= bpy_extras
.io_utils
.path_reference(img
.filepath
, msetts
.base_src
, msetts
.base_dst
, msetts
.path_mode
,
1361 msetts
.subdir
, msetts
.copy_set
, img
.library
)
1362 fname_abs
= os
.path
.normpath(os
.path
.abspath(os
.path
.join(msetts
.base_dst
, fname_rel
)))
1363 return fname_abs
, fname_rel
1366 def fbx_data_texture_file_elements(root
, blender_tex_key
, scene_data
):
1368 Write the (file) Texture data block.
1370 # XXX All this is very fuzzy to me currently...
1371 # Textures do not seem to use properties as much as they could.
1372 # For now assuming most logical and simple stuff.
1374 ma
, sock_name
= blender_tex_key
1375 ma_wrap
= node_shader_utils
.PrincipledBSDFWrapper(ma
, is_readonly
=True)
1376 tex_key
, _fbx_prop
= scene_data
.data_textures
[blender_tex_key
]
1377 tex
= getattr(ma_wrap
, sock_name
)
1379 fname_abs
, fname_rel
= _gen_vid_path(img
, scene_data
)
1381 fbx_tex
= elem_data_single_int64(root
, b
"Texture", get_fbx_uuid_from_key(tex_key
))
1382 fbx_tex
.add_string(fbx_name_class(sock_name
.encode(), b
"Texture"))
1383 fbx_tex
.add_string(b
"")
1385 elem_data_single_string(fbx_tex
, b
"Type", b
"TextureVideoClip")
1386 elem_data_single_int32(fbx_tex
, b
"Version", FBX_TEXTURE_VERSION
)
1387 elem_data_single_string(fbx_tex
, b
"TextureName", fbx_name_class(sock_name
.encode(), b
"Texture"))
1388 elem_data_single_string(fbx_tex
, b
"Media", fbx_name_class(img
.name
.encode(), b
"Video"))
1389 elem_data_single_string_unicode(fbx_tex
, b
"FileName", fname_abs
)
1390 elem_data_single_string_unicode(fbx_tex
, b
"RelativeFilename", fname_rel
)
1392 alpha_source
= 0 # None
1393 if img
.alpha_mode
!= 'NONE':
1394 # ~ if tex.texture.use_calculate_alpha:
1395 # ~ alpha_source = 1 # RGBIntensity as alpha.
1397 # ~ alpha_source = 2 # Black, i.e. alpha channel.
1398 alpha_source
= 2 # Black, i.e. alpha channel.
1399 # BlendMode not useful for now, only affects layered textures afaics.
1402 if tex
.texcoords
== 'ORCO': # XXX Others?
1403 if tex
.projection
== 'FLAT':
1404 mapping
= 1 # Planar
1405 elif tex
.projection
== 'CUBE':
1407 elif tex
.projection
== 'TUBE':
1408 mapping
= 3 # Cylindrical
1409 elif tex
.projection
== 'SPHERE':
1410 mapping
= 2 # Spherical
1411 elif tex
.texcoords
== 'UV':
1413 # Yuck, UVs are linked by mere names it seems... :/
1414 # XXX TODO how to get that now???
1415 # uvset = tex.uv_layer
1416 wrap_mode
= 1 # Clamp
1417 if tex
.extension
== 'REPEAT':
1418 wrap_mode
= 0 # Repeat
1420 tmpl
= elem_props_template_init(scene_data
.templates
, b
"TextureFile")
1421 props
= elem_properties(fbx_tex
)
1422 elem_props_template_set(tmpl
, props
, "p_enum", b
"AlphaSource", alpha_source
)
1423 elem_props_template_set(tmpl
, props
, "p_bool", b
"PremultiplyAlpha",
1424 img
.alpha_mode
in {'STRAIGHT'}) # Or is it PREMUL?
1425 elem_props_template_set(tmpl
, props
, "p_enum", b
"CurrentMappingType", mapping
)
1426 if uvset
is not None:
1427 elem_props_template_set(tmpl
, props
, "p_string", b
"UVSet", uvset
)
1428 elem_props_template_set(tmpl
, props
, "p_enum", b
"WrapModeU", wrap_mode
)
1429 elem_props_template_set(tmpl
, props
, "p_enum", b
"WrapModeV", wrap_mode
)
1430 elem_props_template_set(tmpl
, props
, "p_vector_3d", b
"Translation", tex
.translation
)
1431 elem_props_template_set(tmpl
, props
, "p_vector_3d", b
"Rotation", (-r
for r
in tex
.rotation
))
1432 elem_props_template_set(tmpl
, props
, "p_vector_3d", b
"Scaling", (((1.0 / s
) if s
!= 0.0 else 1.0) for s
in tex
.scale
))
1433 # UseMaterial should always be ON imho.
1434 elem_props_template_set(tmpl
, props
, "p_bool", b
"UseMaterial", True)
1435 elem_props_template_set(tmpl
, props
, "p_bool", b
"UseMipMap", False)
1436 elem_props_template_finalize(tmpl
, props
)
1438 # No custom properties, since that's not a data-block anymore.
1441 def fbx_data_video_elements(root
, vid
, scene_data
):
1443 Write the actual image data block.
1445 msetts
= scene_data
.settings
.media_settings
1447 vid_key
, _texs
= scene_data
.data_videos
[vid
]
1448 fname_abs
, fname_rel
= _gen_vid_path(vid
, scene_data
)
1450 fbx_vid
= elem_data_single_int64(root
, b
"Video", get_fbx_uuid_from_key(vid_key
))
1451 fbx_vid
.add_string(fbx_name_class(vid
.name
.encode(), b
"Video"))
1452 fbx_vid
.add_string(b
"Clip")
1454 elem_data_single_string(fbx_vid
, b
"Type", b
"Clip")
1457 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Video")
1458 props
= elem_properties(fbx_vid
)
1459 elem_props_template_set(tmpl
, props
, "p_string_url", b
"Path", fname_abs
)
1460 elem_props_template_finalize(tmpl
, props
)
1462 elem_data_single_int32(fbx_vid
, b
"UseMipMap", 0)
1463 elem_data_single_string_unicode(fbx_vid
, b
"Filename", fname_abs
)
1464 elem_data_single_string_unicode(fbx_vid
, b
"RelativeFilename", fname_rel
)
1466 if scene_data
.settings
.media_settings
.embed_textures
:
1467 if vid
.packed_file
is not None:
1468 # We only ever embed a given file once!
1469 if fname_abs
not in msetts
.embedded_set
:
1470 elem_data_single_bytes(fbx_vid
, b
"Content", vid
.packed_file
.data
)
1471 msetts
.embedded_set
.add(fname_abs
)
1473 filepath
= bpy
.path
.abspath(vid
.filepath
)
1474 # We only ever embed a given file once!
1475 if filepath
not in msetts
.embedded_set
:
1477 with
open(filepath
, 'br') as f
:
1478 elem_data_single_bytes(fbx_vid
, b
"Content", f
.read())
1479 except Exception as e
:
1480 print("WARNING: embedding file {} failed ({})".format(filepath
, e
))
1481 elem_data_single_bytes(fbx_vid
, b
"Content", b
"")
1482 msetts
.embedded_set
.add(filepath
)
1483 # Looks like we'd rather not write any 'Content' element in this case (see T44442).
1484 # Sounds suspect, but let's try it!
1486 #~ elem_data_single_bytes(fbx_vid, b"Content", b"")
1489 def fbx_data_armature_elements(root
, arm_obj
, scene_data
):
1492 * Bones "data" (NodeAttribute::LimbNode, contains pretty much nothing!).
1493 * Deformers (i.e. Skin), bind between an armature and a mesh.
1494 ** SubDeformers (i.e. Cluster), one per bone/vgroup pair.
1496 Note armature itself has no data, it is a mere "Null" Model...
1498 mat_world_arm
= arm_obj
.fbx_object_matrix(scene_data
, global_space
=True)
1499 bones
= tuple(bo_obj
for bo_obj
in arm_obj
.bones
if bo_obj
in scene_data
.objects
)
1501 bone_radius_scale
= 33.0
1504 for bo_obj
in bones
:
1506 bo_data_key
= scene_data
.data_bones
[bo_obj
]
1507 fbx_bo
= elem_data_single_int64(root
, b
"NodeAttribute", get_fbx_uuid_from_key(bo_data_key
))
1508 fbx_bo
.add_string(fbx_name_class(bo
.name
.encode(), b
"NodeAttribute"))
1509 fbx_bo
.add_string(b
"LimbNode")
1510 elem_data_single_string(fbx_bo
, b
"TypeFlags", b
"Skeleton")
1512 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Bone")
1513 props
= elem_properties(fbx_bo
)
1514 elem_props_template_set(tmpl
, props
, "p_double", b
"Size", bo
.head_radius
* bone_radius_scale
)
1515 elem_props_template_finalize(tmpl
, props
)
1517 # Custom properties.
1518 if scene_data
.settings
.use_custom_props
:
1519 fbx_data_element_custom_properties(props
, bo
)
1521 # Store Blender bone length - XXX Not much useful actually :/
1522 # (LimbLength can't be used because it is a scale factor 0-1 for the parent-child distance:
1523 # http://docs.autodesk.com/FBX/2014/ENU/FBX-SDK-Documentation/cpp_ref/class_fbx_skeleton.html#a9bbe2a70f4ed82cd162620259e649f0f )
1524 # elem_props_set(props, "p_double", "BlenderBoneLength".encode(), (bo.tail_local - bo.head_local).length, custom=True)
1526 # Skin deformers and BindPoses.
1527 # Note: we might also use Deformers for our "parent to vertex" stuff???
1528 deformer
= scene_data
.data_deformers_skin
.get(arm_obj
, None)
1529 if deformer
is not None:
1530 for me
, (skin_key
, ob_obj
, clusters
) in deformer
.items():
1532 mat_world_obj
, mat_world_bones
= fbx_data_bindpose_element(root
, ob_obj
, me
, scene_data
,
1533 arm_obj
, mat_world_arm
, bones
)
1536 fbx_skin
= elem_data_single_int64(root
, b
"Deformer", get_fbx_uuid_from_key(skin_key
))
1537 fbx_skin
.add_string(fbx_name_class(arm_obj
.name
.encode(), b
"Deformer"))
1538 fbx_skin
.add_string(b
"Skin")
1540 elem_data_single_int32(fbx_skin
, b
"Version", FBX_DEFORMER_SKIN_VERSION
)
1541 elem_data_single_float64(fbx_skin
, b
"Link_DeformAcuracy", 50.0) # Only vague idea what it is...
1543 # Pre-process vertex weights (also to check vertices assigned ot more than four bones).
1545 bo_vg_idx
= {bo_obj
.bdata
.name
: ob
.vertex_groups
[bo_obj
.bdata
.name
].index
1546 for bo_obj
in clusters
.keys() if bo_obj
.bdata
.name
in ob
.vertex_groups
}
1547 valid_idxs
= set(bo_vg_idx
.values())
1548 vgroups
= {vg
.index
: {} for vg
in ob
.vertex_groups
}
1549 verts_vgroups
= (sorted(((vg
.group
, vg
.weight
) for vg
in v
.groups
if vg
.weight
and vg
.group
in valid_idxs
),
1550 key
=lambda e
: e
[1], reverse
=True)
1551 for v
in me
.vertices
)
1552 for idx
, vgs
in enumerate(verts_vgroups
):
1553 for vg_idx
, w
in vgs
:
1554 vgroups
[vg_idx
][idx
] = w
1556 for bo_obj
, clstr_key
in clusters
.items():
1558 # Find which vertices are affected by this bone/vgroup pair, and matching weights.
1559 # Note we still write a cluster for bones not affecting the mesh, to get 'rest pose' data
1560 # (the TransformBlah matrices).
1561 vg_idx
= bo_vg_idx
.get(bo
.name
, None)
1562 indices
, weights
= ((), ()) if vg_idx
is None or not vgroups
[vg_idx
] else zip(*vgroups
[vg_idx
].items())
1564 # Create the cluster.
1565 fbx_clstr
= elem_data_single_int64(root
, b
"Deformer", get_fbx_uuid_from_key(clstr_key
))
1566 fbx_clstr
.add_string(fbx_name_class(bo
.name
.encode(), b
"SubDeformer"))
1567 fbx_clstr
.add_string(b
"Cluster")
1569 elem_data_single_int32(fbx_clstr
, b
"Version", FBX_DEFORMER_CLUSTER_VERSION
)
1570 # No idea what that user data might be...
1571 fbx_userdata
= elem_data_single_string(fbx_clstr
, b
"UserData", b
"")
1572 fbx_userdata
.add_string(b
"")
1574 elem_data_single_int32_array(fbx_clstr
, b
"Indexes", indices
)
1575 elem_data_single_float64_array(fbx_clstr
, b
"Weights", weights
)
1576 # Transform, TransformLink and TransformAssociateModel matrices...
1577 # They seem to be doublons of BindPose ones??? Have armature (associatemodel) in addition, though.
1578 # WARNING! Even though official FBX API presents Transform in global space,
1579 # **it is stored in bone space in FBX data!** See:
1580 # http://area.autodesk.com/forum/autodesk-fbx/fbx-sdk/why-the-values-return-
1581 # by-fbxcluster-gettransformmatrix-x-not-same-with-the-value-in-ascii-fbx-file/
1582 elem_data_single_float64_array(fbx_clstr
, b
"Transform",
1583 matrix4_to_array(mat_world_bones
[bo_obj
].inverted_safe() @ mat_world_obj
))
1584 elem_data_single_float64_array(fbx_clstr
, b
"TransformLink", matrix4_to_array(mat_world_bones
[bo_obj
]))
1585 elem_data_single_float64_array(fbx_clstr
, b
"TransformAssociateModel", matrix4_to_array(mat_world_arm
))
1588 def fbx_data_leaf_bone_elements(root
, scene_data
):
1589 # Write a dummy leaf bone that is used by applications to show the length of the last bone in a chain
1590 for (node_name
, _par_uuid
, node_uuid
, attr_uuid
, matrix
, hide
, size
) in scene_data
.data_leaf_bones
:
1592 fbx_bo
= elem_data_single_int64(root
, b
"NodeAttribute", attr_uuid
)
1593 fbx_bo
.add_string(fbx_name_class(node_name
.encode(), b
"NodeAttribute"))
1594 fbx_bo
.add_string(b
"LimbNode")
1595 elem_data_single_string(fbx_bo
, b
"TypeFlags", b
"Skeleton")
1597 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Bone")
1598 props
= elem_properties(fbx_bo
)
1599 elem_props_template_set(tmpl
, props
, "p_double", b
"Size", size
)
1600 elem_props_template_finalize(tmpl
, props
)
1603 model
= elem_data_single_int64(root
, b
"Model", node_uuid
)
1604 model
.add_string(fbx_name_class(node_name
.encode(), b
"Model"))
1605 model
.add_string(b
"LimbNode")
1607 elem_data_single_int32(model
, b
"Version", FBX_MODELS_VERSION
)
1609 # Object transform info.
1610 loc
, rot
, scale
= matrix
.decompose()
1611 rot
= rot
.to_euler('XYZ')
1612 rot
= tuple(convert_rad_to_deg_iter(rot
))
1614 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Model")
1615 # For now add only loc/rot/scale...
1616 props
= elem_properties(model
)
1617 # Generated leaf bones are obviously never animated!
1618 elem_props_template_set(tmpl
, props
, "p_lcl_translation", b
"Lcl Translation", loc
)
1619 elem_props_template_set(tmpl
, props
, "p_lcl_rotation", b
"Lcl Rotation", rot
)
1620 elem_props_template_set(tmpl
, props
, "p_lcl_scaling", b
"Lcl Scaling", scale
)
1621 elem_props_template_set(tmpl
, props
, "p_visibility", b
"Visibility", float(not hide
))
1623 # Absolutely no idea what this is, but seems mandatory for validity of the file, and defaults to
1624 # invalid -1 value...
1625 elem_props_template_set(tmpl
, props
, "p_integer", b
"DefaultAttributeIndex", 0)
1627 elem_props_template_set(tmpl
, props
, "p_enum", b
"InheritType", 1) # RSrs
1629 # Those settings would obviously need to be edited in a complete version of the exporter, may depends on
1631 elem_data_single_int32(model
, b
"MultiLayer", 0)
1632 elem_data_single_int32(model
, b
"MultiTake", 0)
1633 elem_data_single_bool(model
, b
"Shading", True)
1634 elem_data_single_string(model
, b
"Culling", b
"CullingOff")
1636 elem_props_template_finalize(tmpl
, props
)
1639 def fbx_data_object_elements(root
, ob_obj
, scene_data
):
1641 Write the Object (Model) data blocks.
1642 Note this "Model" can also be bone or dupli!
1644 obj_type
= b
"Null" # default, sort of empty...
1646 obj_type
= b
"LimbNode"
1647 elif (ob_obj
.type == 'ARMATURE'):
1648 if scene_data
.settings
.armature_nodetype
== 'ROOT':
1650 elif scene_data
.settings
.armature_nodetype
== 'LIMBNODE':
1651 obj_type
= b
"LimbNode"
1652 else: # Default, preferred option...
1654 elif (ob_obj
.type in BLENDER_OBJECT_TYPES_MESHLIKE
):
1656 elif (ob_obj
.type == 'LIGHT'):
1658 elif (ob_obj
.type == 'CAMERA'):
1659 obj_type
= b
"Camera"
1660 model
= elem_data_single_int64(root
, b
"Model", ob_obj
.fbx_uuid
)
1661 model
.add_string(fbx_name_class(ob_obj
.name
.encode(), b
"Model"))
1662 model
.add_string(obj_type
)
1664 elem_data_single_int32(model
, b
"Version", FBX_MODELS_VERSION
)
1666 # Object transform info.
1667 loc
, rot
, scale
, matrix
, matrix_rot
= ob_obj
.fbx_object_tx(scene_data
)
1668 rot
= tuple(convert_rad_to_deg_iter(rot
))
1670 tmpl
= elem_props_template_init(scene_data
.templates
, b
"Model")
1671 # For now add only loc/rot/scale...
1672 props
= elem_properties(model
)
1673 elem_props_template_set(tmpl
, props
, "p_lcl_translation", b
"Lcl Translation", loc
,
1674 animatable
=True, animated
=((ob_obj
.key
, "Lcl Translation") in scene_data
.animated
))
1675 elem_props_template_set(tmpl
, props
, "p_lcl_rotation", b
"Lcl Rotation", rot
,
1676 animatable
=True, animated
=((ob_obj
.key
, "Lcl Rotation") in scene_data
.animated
))
1677 elem_props_template_set(tmpl
, props
, "p_lcl_scaling", b
"Lcl Scaling", scale
,
1678 animatable
=True, animated
=((ob_obj
.key
, "Lcl Scaling") in scene_data
.animated
))
1679 elem_props_template_set(tmpl
, props
, "p_visibility", b
"Visibility", float(not ob_obj
.hide
))
1681 # Absolutely no idea what this is, but seems mandatory for validity of the file, and defaults to
1682 # invalid -1 value...
1683 elem_props_template_set(tmpl
, props
, "p_integer", b
"DefaultAttributeIndex", 0)
1685 elem_props_template_set(tmpl
, props
, "p_enum", b
"InheritType", 1) # RSrs
1687 # Custom properties.
1688 if scene_data
.settings
.use_custom_props
:
1689 # Here we want customprops from the 'pose' bone, not the 'edit' bone...
1690 bdata
= ob_obj
.bdata_pose_bone
if ob_obj
.is_bone
else ob_obj
.bdata
1691 fbx_data_element_custom_properties(props
, bdata
)
1693 # Those settings would obviously need to be edited in a complete version of the exporter, may depends on
1695 elem_data_single_int32(model
, b
"MultiLayer", 0)
1696 elem_data_single_int32(model
, b
"MultiTake", 0)
1697 elem_data_single_bool(model
, b
"Shading", True)
1698 elem_data_single_string(model
, b
"Culling", b
"CullingOff")
1700 if obj_type
== b
"Camera":
1701 # Why, oh why are FBX cameras such a mess???
1702 # And WHY add camera data HERE??? Not even sure this is needed...
1703 render
= scene_data
.scene
.render
1704 width
= render
.resolution_x
* 1.0
1705 height
= render
.resolution_y
* 1.0
1706 elem_props_template_set(tmpl
, props
, "p_enum", b
"ResolutionMode", 0) # Don't know what it means
1707 elem_props_template_set(tmpl
, props
, "p_double", b
"AspectW", width
)
1708 elem_props_template_set(tmpl
, props
, "p_double", b
"AspectH", height
)
1709 elem_props_template_set(tmpl
, props
, "p_bool", b
"ViewFrustum", True)
1710 elem_props_template_set(tmpl
, props
, "p_enum", b
"BackgroundMode", 0) # Don't know what it means
1711 elem_props_template_set(tmpl
, props
, "p_bool", b
"ForegroundTransparent", True)
1713 elem_props_template_finalize(tmpl
, props
)
1716 def fbx_data_animation_elements(root
, scene_data
):
1718 Write animation data.
1720 animations
= scene_data
.animations
1723 scene
= scene_data
.scene
1725 fps
= scene
.render
.fps
/ scene
.render
.fps_base
1727 def keys_to_ktimes(keys
):
1728 return (int(v
) for v
in convert_sec_to_ktime_iter((f
/ fps
for f
, _v
in keys
)))
1731 for astack_key
, alayers
, alayer_key
, name
, f_start
, f_end
in animations
:
1732 astack
= elem_data_single_int64(root
, b
"AnimationStack", get_fbx_uuid_from_key(astack_key
))
1733 astack
.add_string(fbx_name_class(name
, b
"AnimStack"))
1734 astack
.add_string(b
"")
1736 astack_tmpl
= elem_props_template_init(scene_data
.templates
, b
"AnimationStack")
1737 astack_props
= elem_properties(astack
)
1738 r
= scene_data
.scene
.render
1739 fps
= r
.fps
/ r
.fps_base
1740 start
= int(convert_sec_to_ktime(f_start
/ fps
))
1741 end
= int(convert_sec_to_ktime(f_end
/ fps
))
1742 elem_props_template_set(astack_tmpl
, astack_props
, "p_timestamp", b
"LocalStart", start
)
1743 elem_props_template_set(astack_tmpl
, astack_props
, "p_timestamp", b
"LocalStop", end
)
1744 elem_props_template_set(astack_tmpl
, astack_props
, "p_timestamp", b
"ReferenceStart", start
)
1745 elem_props_template_set(astack_tmpl
, astack_props
, "p_timestamp", b
"ReferenceStop", end
)
1746 elem_props_template_finalize(astack_tmpl
, astack_props
)
1748 # For now, only one layer for all animations.
1749 alayer
= elem_data_single_int64(root
, b
"AnimationLayer", get_fbx_uuid_from_key(alayer_key
))
1750 alayer
.add_string(fbx_name_class(name
, b
"AnimLayer"))
1751 alayer
.add_string(b
"")
1753 for ob_obj
, (alayer_key
, acurvenodes
) in alayers
.items():
1755 # alayer = elem_data_single_int64(root, b"AnimationLayer", get_fbx_uuid_from_key(alayer_key))
1756 # alayer.add_string(fbx_name_class(ob_obj.name.encode(), b"AnimLayer"))
1757 # alayer.add_string(b"")
1759 for fbx_prop
, (acurvenode_key
, acurves
, acurvenode_name
) in acurvenodes
.items():
1760 # Animation curve node.
1761 acurvenode
= elem_data_single_int64(root
, b
"AnimationCurveNode", get_fbx_uuid_from_key(acurvenode_key
))
1762 acurvenode
.add_string(fbx_name_class(acurvenode_name
.encode(), b
"AnimCurveNode"))
1763 acurvenode
.add_string(b
"")
1765 acn_tmpl
= elem_props_template_init(scene_data
.templates
, b
"AnimationCurveNode")
1766 acn_props
= elem_properties(acurvenode
)
1768 for fbx_item
, (acurve_key
, def_value
, keys
, _acurve_valid
) in acurves
.items():
1769 elem_props_template_set(acn_tmpl
, acn_props
, "p_number", fbx_item
.encode(),
1770 def_value
, animatable
=True)
1772 # Only create Animation curve if needed!
1774 acurve
= elem_data_single_int64(root
, b
"AnimationCurve", get_fbx_uuid_from_key(acurve_key
))
1775 acurve
.add_string(fbx_name_class(b
"", b
"AnimCurve"))
1776 acurve
.add_string(b
"")
1779 nbr_keys
= len(keys
)
1782 1 << 2 |
# interpolation mode, 1 = constant, 2 = linear, 3 = cubic.
1783 1 << 8 |
# tangent mode, 8 = auto, 9 = TCB, 10 = user, 11 = generic break,
1784 1 << 13 |
# tangent mode, 12 = generic clamp, 13 = generic time independent,
1785 1 << 14 |
# tangent mode, 13 + 14 = generic clamp progressive.
1788 # Maybe values controlling TCB & co???
1789 keyattr_datafloat
= (0.0, 0.0, 9.419963346924634e-30, 0.0)
1791 # And now, the *real* data!
1792 elem_data_single_float64(acurve
, b
"Default", def_value
)
1793 elem_data_single_int32(acurve
, b
"KeyVer", FBX_ANIM_KEY_VERSION
)
1794 elem_data_single_int64_array(acurve
, b
"KeyTime", keys_to_ktimes(keys
))
1795 elem_data_single_float32_array(acurve
, b
"KeyValueFloat", (v
for _f
, v
in keys
))
1796 elem_data_single_int32_array(acurve
, b
"KeyAttrFlags", keyattr_flags
)
1797 elem_data_single_float32_array(acurve
, b
"KeyAttrDataFloat", keyattr_datafloat
)
1798 elem_data_single_int32_array(acurve
, b
"KeyAttrRefCount", (nbr_keys
,))
1800 elem_props_template_finalize(acn_tmpl
, acn_props
)
1803 # ##### Top-level FBX data container. #####
1805 # Mapping Blender -> FBX (principled_socket_name, fbx_name).
1806 PRINCIPLED_TEXTURE_SOCKETS_TO_FBX
= (
1807 # ("diffuse", "diffuse", b"DiffuseFactor"),
1808 ("base_color_texture", b
"DiffuseColor"),
1809 ("alpha_texture", b
"TransparencyFactor"), # Will be inverted in fact, not much we can do really...
1810 # ("base_color_texture", b"TransparentColor"), # Uses diffuse color in Blender!
1811 ("emission_strength_texture", b
"EmissiveFactor"),
1812 ("emission_color_texture", b
"EmissiveColor"),
1813 # ("ambient", "ambient", b"AmbientFactor"),
1814 # ("", "", b"AmbientColor"), # World stuff in Blender, for now ignore...
1815 ("normalmap_texture", b
"NormalMap"),
1816 # Note: unsure about those... :/
1817 # ("", "", b"Bump"),
1818 # ("", "", b"BumpFactor"),
1819 # ("", "", b"DisplacementColor"),
1820 # ("", "", b"DisplacementFactor"),
1821 ("specular_texture", b
"SpecularFactor"),
1822 # ("base_color", b"SpecularColor"), # TODO: use tint?
1823 # See Material template about those two!
1824 ("roughness_texture", b
"Shininess"),
1825 ("roughness_texture", b
"ShininessExponent"),
1826 # ("mirror", "mirror", b"ReflectionColor"),
1827 ("metallic_texture", b
"ReflectionFactor"),
1831 def fbx_skeleton_from_armature(scene
, settings
, arm_obj
, objects
, data_meshes
,
1832 data_bones
, data_deformers_skin
, data_empties
, arm_parents
):
1834 Create skeleton from armature/bones (NodeAttribute/LimbNode and Model/LimbNode), and for each deformed mesh,
1835 create Pose/BindPose(with sub PoseNode) and Deformer/Skin(with Deformer/SubDeformer/Cluster).
1836 Also supports "parent to bone" (simple parent to Model/LimbNode).
1837 arm_parents is a set of tuples (armature, object) for all successful armature bindings.
1839 # We need some data for our armature 'object' too!!!
1840 data_empties
[arm_obj
] = get_blender_empty_key(arm_obj
.bdata
)
1842 arm_data
= arm_obj
.bdata
.data
1844 for bo
in arm_obj
.bones
:
1845 if settings
.use_armature_deform_only
:
1846 if bo
.bdata
.use_deform
:
1849 while bo_par
.is_bone
:
1850 bones
[bo_par
] = True
1851 bo_par
= bo_par
.parent
1852 elif bo
not in bones
: # Do not override if already set in the loop above!
1857 bones
= {bo
: None for bo
, use
in bones
.items() if use
}
1862 data_bones
.update((bo
, get_blender_bone_key(arm_obj
.bdata
, bo
.bdata
)) for bo
in bones
)
1864 for ob_obj
in objects
:
1865 if not ob_obj
.is_deformed_by_armature(arm_obj
):
1868 # Always handled by an Armature modifier...
1870 for mod
in ob_obj
.bdata
.modifiers
:
1871 if mod
.type not in {'ARMATURE'} or not mod
.object:
1873 # We only support vertex groups binding method, not bone envelopes one!
1874 if mod
.object in {arm_obj
.bdata
, arm_obj
.bdata
.proxy
} and mod
.use_vertex_groups
:
1881 # Now we have a mesh using this armature.
1882 # Note: bindpose have no relations at all (no connections), so no need for any preprocess for them.
1883 # Create skin & clusters relations (note skins are connected to geometry, *not* model!).
1884 _key
, me
, _free
= data_meshes
[ob_obj
]
1885 clusters
= {bo
: get_blender_bone_cluster_key(arm_obj
.bdata
, me
, bo
.bdata
) for bo
in bones
}
1886 data_deformers_skin
.setdefault(arm_obj
, {})[me
] = (get_blender_armature_skin_key(arm_obj
.bdata
, me
),
1889 # We don't want a regular parent relationship for those in FBX...
1890 arm_parents
.add((arm_obj
, ob_obj
))
1891 # Needed to handle matrices/spaces (since we do not parent them to 'armature' in FBX :/ ).
1892 ob_obj
.parented_to_armature
= True
1894 objects
.update(bones
)
1897 def fbx_generate_leaf_bones(settings
, data_bones
):
1898 # find which bons have no children
1899 child_count
= {bo
: 0 for bo
in data_bones
.keys()}
1900 for bo
in data_bones
.keys():
1901 if bo
.parent
and bo
.parent
.is_bone
:
1902 child_count
[bo
.parent
] += 1
1904 bone_radius_scale
= settings
.global_scale
* 33.0
1906 # generate bone data
1907 leaf_parents
= [bo
for bo
, count
in child_count
.items() if count
== 0]
1909 for parent
in leaf_parents
:
1910 node_name
= parent
.name
+ "_end"
1911 parent_uuid
= parent
.fbx_uuid
1912 parent_key
= parent
.key
1913 node_uuid
= get_fbx_uuid_from_key(parent_key
+ "_end_node")
1914 attr_uuid
= get_fbx_uuid_from_key(parent_key
+ "_end_nodeattr")
1917 size
= parent
.bdata
.head_radius
* bone_radius_scale
1918 bone_length
= (parent
.bdata
.tail_local
- parent
.bdata
.head_local
).length
1919 matrix
= Matrix
.Translation((0, bone_length
, 0))
1920 if settings
.bone_correction_matrix_inv
:
1921 matrix
= settings
.bone_correction_matrix_inv
@ matrix
1922 if settings
.bone_correction_matrix
:
1923 matrix
= matrix
@ settings
.bone_correction_matrix
1924 leaf_bones
.append((node_name
, parent_uuid
, node_uuid
, attr_uuid
, matrix
, hide
, size
))
1929 def fbx_animations_do(scene_data
, ref_id
, f_start
, f_end
, start_zero
, objects
=None, force_keep
=False):
1931 Generate animation data (a single AnimStack) from objects, for a given frame range.
1933 bake_step
= scene_data
.settings
.bake_anim_step
1934 simplify_fac
= scene_data
.settings
.bake_anim_simplify_factor
1935 scene
= scene_data
.scene
1936 depsgraph
= scene_data
.depsgraph
1937 force_keying
= scene_data
.settings
.bake_anim_use_all_bones
1938 force_sek
= scene_data
.settings
.bake_anim_force_startend_keying
1940 if objects
is not None:
1941 # Add bones and duplis!
1942 for ob_obj
in tuple(objects
):
1943 if not ob_obj
.is_object
:
1945 if ob_obj
.type == 'ARMATURE':
1946 objects |
= {bo_obj
for bo_obj
in ob_obj
.bones
if bo_obj
in scene_data
.objects
}
1947 for dp_obj
in ob_obj
.dupli_list_gen(depsgraph
):
1948 if dp_obj
in scene_data
.objects
:
1951 objects
= scene_data
.objects
1953 back_currframe
= scene
.frame_current
1957 for ob_obj
in objects
:
1958 if ob_obj
.parented_to_armature
:
1960 ACNW
= AnimationCurveNodeWrapper
1961 loc
, rot
, scale
, _m
, _mr
= ob_obj
.fbx_object_tx(scene_data
)
1962 rot_deg
= tuple(convert_rad_to_deg_iter(rot
))
1963 force_key
= (simplify_fac
== 0.0) or (ob_obj
.is_bone
and force_keying
)
1964 animdata_ob
[ob_obj
] = (ACNW(ob_obj
.key
, 'LCL_TRANSLATION', force_key
, force_sek
, loc
),
1965 ACNW(ob_obj
.key
, 'LCL_ROTATION', force_key
, force_sek
, rot_deg
),
1966 ACNW(ob_obj
.key
, 'LCL_SCALING', force_key
, force_sek
, scale
))
1967 p_rots
[ob_obj
] = rot
1969 force_key
= (simplify_fac
== 0.0)
1970 animdata_shapes
= {}
1972 for me
, (me_key
, _shapes_key
, shapes
) in scene_data
.data_deformers_shape
.items():
1973 # Ignore absolute shape keys for now!
1974 if not me
.shape_keys
.use_relative
:
1976 for shape
, (channel_key
, geom_key
, _shape_verts_co
, _shape_verts_idx
) in shapes
.items():
1977 acnode
= AnimationCurveNodeWrapper(channel_key
, 'SHAPE_KEY', force_key
, force_sek
, (0.0,))
1978 # Sooooo happy to have to twist again like a mad snake... Yes, we need to write those curves twice. :/
1979 acnode
.add_group(me_key
, shape
.name
, shape
.name
, (shape
.name
,))
1980 animdata_shapes
[channel_key
] = (acnode
, me
, shape
)
1982 animdata_cameras
= {}
1983 for cam_obj
, cam_key
in scene_data
.data_cameras
.items():
1984 cam
= cam_obj
.bdata
.data
1985 acnode
= AnimationCurveNodeWrapper(cam_key
, 'CAMERA_FOCAL', force_key
, force_sek
, (cam
.lens
,))
1986 animdata_cameras
[cam_key
] = (acnode
, cam
)
1989 while currframe
<= f_end
:
1990 real_currframe
= currframe
- f_start
if start_zero
else currframe
1991 scene
.frame_set(int(currframe
), subframe
=currframe
- int(currframe
))
1993 for dp_obj
in ob_obj
.dupli_list_gen(depsgraph
):
1994 pass # Merely updating dupli matrix of ObjectWrapper...
1995 for ob_obj
, (anim_loc
, anim_rot
, anim_scale
) in animdata_ob
.items():
1996 # We compute baked loc/rot/scale for all objects (rot being euler-compat with previous value!).
1997 p_rot
= p_rots
.get(ob_obj
, None)
1998 loc
, rot
, scale
, _m
, _mr
= ob_obj
.fbx_object_tx(scene_data
, rot_euler_compat
=p_rot
)
1999 p_rots
[ob_obj
] = rot
2000 anim_loc
.add_keyframe(real_currframe
, loc
)
2001 anim_rot
.add_keyframe(real_currframe
, tuple(convert_rad_to_deg_iter(rot
)))
2002 anim_scale
.add_keyframe(real_currframe
, scale
)
2003 for anim_shape
, me
, shape
in animdata_shapes
.values():
2004 anim_shape
.add_keyframe(real_currframe
, (shape
.value
* 100.0,))
2005 for anim_camera
, camera
in animdata_cameras
.values():
2006 anim_camera
.add_keyframe(real_currframe
, (camera
.lens
,))
2007 currframe
+= bake_step
2009 scene
.frame_set(back_currframe
, subframe
=0.0)
2013 # And now, produce final data (usable by FBX export code)
2014 # Objects-like loc/rot/scale...
2015 for ob_obj
, anims
in animdata_ob
.items():
2017 anim
.simplify(simplify_fac
, bake_step
, force_keep
)
2020 for obj_key
, group_key
, group
, fbx_group
, fbx_gname
in anim
.get_final_data(scene
, ref_id
, force_keep
):
2021 anim_data
= animations
.setdefault(obj_key
, ("dummy_unused_key", {}))
2022 anim_data
[1][fbx_group
] = (group_key
, group
, fbx_gname
)
2024 # And meshes' shape keys.
2025 for channel_key
, (anim_shape
, me
, shape
) in animdata_shapes
.items():
2027 anim_shape
.simplify(simplify_fac
, bake_step
, force_keep
)
2030 for elem_key
, group_key
, group
, fbx_group
, fbx_gname
in anim_shape
.get_final_data(scene
, ref_id
, force_keep
):
2031 anim_data
= animations
.setdefault(elem_key
, ("dummy_unused_key", {}))
2032 anim_data
[1][fbx_group
] = (group_key
, group
, fbx_gname
)
2034 # And cameras' lens keys.
2035 for cam_key
, (anim_camera
, camera
) in animdata_cameras
.items():
2037 anim_camera
.simplify(simplify_fac
, bake_step
, force_keep
)
2040 for elem_key
, group_key
, group
, fbx_group
, fbx_gname
in anim_camera
.get_final_data(scene
, ref_id
, force_keep
):
2041 anim_data
= animations
.setdefault(elem_key
, ("dummy_unused_key", {}))
2042 anim_data
[1][fbx_group
] = (group_key
, group
, fbx_gname
)
2044 astack_key
= get_blender_anim_stack_key(scene
, ref_id
)
2045 alayer_key
= get_blender_anim_layer_key(scene
, ref_id
)
2046 name
= (get_blenderID_name(ref_id
) if ref_id
else scene
.name
).encode()
2052 return (astack_key
, animations
, alayer_key
, name
, f_start
, f_end
) if animations
else None
2055 def fbx_animations(scene_data
):
2057 Generate global animation data from objects.
2059 scene
= scene_data
.scene
2065 def add_anim(animations
, animated
, anim
):
2066 nonlocal frame_start
, frame_end
2067 if anim
is not None:
2068 animations
.append(anim
)
2069 f_start
, f_end
= anim
[4:6]
2070 if f_start
< frame_start
:
2071 frame_start
= f_start
2072 if f_end
> frame_end
:
2075 _astack_key
, astack
, _alayer_key
, _name
, _fstart
, _fend
= anim
2076 for elem_key
, (alayer_key
, acurvenodes
) in astack
.items():
2077 for fbx_prop
, (acurvenode_key
, acurves
, acurvenode_name
) in acurvenodes
.items():
2078 animated
.add((elem_key
, fbx_prop
))
2080 # Per-NLA strip animstacks.
2081 if scene_data
.settings
.bake_anim_use_nla_strips
:
2084 for ob_obj
in scene_data
.objects
:
2085 # NLA tracks only for objects, not bones!
2086 if not ob_obj
.is_object
:
2088 ob
= ob_obj
.bdata
# Back to real Blender Object.
2089 if not ob
.animation_data
:
2091 # We have to remove active action from objects, it overwrites strips actions otherwise...
2092 ob_actions
.append((ob
, ob
.animation_data
.action
))
2093 ob
.animation_data
.action
= None
2094 for track
in ob
.animation_data
.nla_tracks
:
2097 for strip
in track
.strips
:
2100 strips
.append(strip
)
2103 for strip
in strips
:
2105 add_anim(animations
, animated
,
2106 fbx_animations_do(scene_data
, strip
, strip
.frame_start
, strip
.frame_end
, True, force_keep
=True))
2108 scene
.frame_set(scene
.frame_current
, subframe
=0.0)
2110 for strip
in strips
:
2113 for ob
, ob_act
in ob_actions
:
2114 ob
.animation_data
.action
= ob_act
2117 if scene_data
.settings
.bake_anim_use_all_actions
:
2118 def validate_actions(act
, path_resolve
):
2119 for fc
in act
.fcurves
:
2120 data_path
= fc
.data_path
2122 data_path
= data_path
+ "[%d]" % fc
.array_index
2124 path_resolve(data_path
)
2126 return False # Invalid.
2127 return True # Valid.
2129 def restore_object(ob_to
, ob_from
):
2130 # Restore org state of object (ugh :/ ).
2132 'location', 'rotation_quaternion', 'rotation_axis_angle', 'rotation_euler', 'rotation_mode', 'scale',
2133 'delta_location', 'delta_rotation_euler', 'delta_rotation_quaternion', 'delta_scale',
2134 'lock_location', 'lock_rotation', 'lock_rotation_w', 'lock_rotations_4d', 'lock_scale',
2135 'tag', 'track_axis', 'up_axis', 'active_material', 'active_material_index',
2136 'matrix_parent_inverse', 'empty_display_type', 'empty_display_size', 'empty_image_offset', 'pass_index',
2137 'color', 'hide_viewport', 'hide_select', 'hide_render', 'instance_type',
2138 'use_instance_vertices_rotation', 'use_instance_faces_scale', 'instance_faces_scale',
2139 'display_type', 'show_bounds', 'display_bounds_type', 'show_name', 'show_axis', 'show_texture_space',
2140 'show_wire', 'show_all_edges', 'show_transparent', 'show_in_front',
2141 'show_only_shape_key', 'use_shape_key_edit_mode', 'active_shape_key_index',
2144 if not ob_to
.is_property_readonly(p
):
2145 setattr(ob_to
, p
, getattr(ob_from
, p
))
2147 for ob_obj
in scene_data
.objects
:
2148 # Actions only for objects, not bones!
2149 if not ob_obj
.is_object
:
2152 ob
= ob_obj
.bdata
# Back to real Blender Object.
2154 if not ob
.animation_data
:
2155 continue # Do not export animations for objects that are absolutely not animated, see T44386.
2157 if ob
.animation_data
.is_property_readonly('action'):
2158 continue # Cannot re-assign 'active action' to this object (usually related to NLA usage, see T48089).
2160 # We can't play with animdata and actions and get back to org state easily.
2161 # So we have to add a temp copy of the object to the scene, animate it, and remove it... :/
2163 # Great, have to handle bones as well if needed...
2164 pbones_matrices
= [pbo
.matrix_basis
.copy() for pbo
in ob
.pose
.bones
] if ob
.type == 'ARMATURE' else ...
2166 org_act
= ob
.animation_data
.action
2167 path_resolve
= ob
.path_resolve
2169 for act
in bpy
.data
.actions
:
2170 # For now, *all* paths in the action must be valid for the object, to validate the action.
2171 # Unless that action was already assigned to the object!
2172 if act
!= org_act
and not validate_actions(act
, path_resolve
):
2174 ob
.animation_data
.action
= act
2175 frame_start
, frame_end
= act
.frame_range
# sic!
2176 add_anim(animations
, animated
,
2177 fbx_animations_do(scene_data
, (ob
, act
), frame_start
, frame_end
, True,
2178 objects
={ob_obj}
, force_keep
=True))
2180 if pbones_matrices
is not ...:
2181 for pbo
, mat
in zip(ob
.pose
.bones
, pbones_matrices
):
2182 pbo
.matrix_basis
= mat
.copy()
2183 ob
.animation_data
.action
= org_act
2184 restore_object(ob
, ob_copy
)
2185 scene
.frame_set(scene
.frame_current
, subframe
=0.0)
2187 if pbones_matrices
is not ...:
2188 for pbo
, mat
in zip(ob
.pose
.bones
, pbones_matrices
):
2189 pbo
.matrix_basis
= mat
.copy()
2190 ob
.animation_data
.action
= org_act
2192 bpy
.data
.objects
.remove(ob_copy
)
2193 scene
.frame_set(scene
.frame_current
, subframe
=0.0)
2195 # Global (containing everything) animstack, only if not exporting NLA strips and/or all actions.
2196 if not scene_data
.settings
.bake_anim_use_nla_strips
and not scene_data
.settings
.bake_anim_use_all_actions
:
2197 add_anim(animations
, animated
, fbx_animations_do(scene_data
, None, scene
.frame_start
, scene
.frame_end
, False))
2199 # Be sure to update all matrices back to org state!
2200 scene
.frame_set(scene
.frame_current
, subframe
=0.0)
2202 return animations
, animated
, frame_start
, frame_end
2205 def fbx_data_from_scene(scene
, depsgraph
, settings
):
2207 Do some pre-processing over scene's data...
2209 objtypes
= settings
.object_types
2210 dp_objtypes
= objtypes
- {'ARMATURE'} # Armatures are not supported as dupli instances currently...
2214 # ##### Gathering data...
2216 perfmon
.step("FBX export prepare: Wrapping Objects...")
2218 # This is rather simple for now, maybe we could end generating templates with most-used values
2219 # instead of default ones?
2220 objects
= {} # Because we do not have any ordered set...
2221 for ob
in settings
.context_objects
:
2222 if ob
.type not in objtypes
:
2224 ob_obj
= ObjectWrapper(ob
)
2225 objects
[ob_obj
] = None
2227 for dp_obj
in ob_obj
.dupli_list_gen(depsgraph
):
2228 if dp_obj
.type not in dp_objtypes
:
2230 objects
[dp_obj
] = None
2232 perfmon
.step("FBX export prepare: Wrapping Data (lamps, cameras, empties)...")
2234 data_lights
= {ob_obj
.bdata
.data
: get_blenderID_key(ob_obj
.bdata
.data
)
2235 for ob_obj
in objects
if ob_obj
.type == 'LIGHT'}
2236 # Unfortunately, FBX camera data contains object-level data (like position, orientation, etc.)...
2237 data_cameras
= {ob_obj
: get_blenderID_key(ob_obj
.bdata
.data
)
2238 for ob_obj
in objects
if ob_obj
.type == 'CAMERA'}
2239 # Yep! Contains nothing, but needed!
2240 data_empties
= {ob_obj
: get_blender_empty_key(ob_obj
.bdata
)
2241 for ob_obj
in objects
if ob_obj
.type == 'EMPTY'}
2243 perfmon
.step("FBX export prepare: Wrapping Meshes...")
2246 for ob_obj
in objects
:
2247 if ob_obj
.type not in BLENDER_OBJECT_TYPES_MESHLIKE
:
2253 # Do not want to systematically recreate a new mesh for dupliobject instances, kind of break purpose of those.
2255 org_ob_obj
= ObjectWrapper(ob
) # We get the "real" object wrapper from that dupli instance.
2256 if org_ob_obj
in data_meshes
:
2257 data_meshes
[ob_obj
] = data_meshes
[org_ob_obj
]
2260 is_ob_material
= any(ms
.link
== 'OBJECT' for ms
in ob
.material_slots
)
2262 if settings
.use_mesh_modifiers
or ob
.type in BLENDER_OTHER_OBJECT_TYPES
or is_ob_material
:
2263 # We cannot use default mesh in that case, or material would not be the right ones...
2264 use_org_data
= not (is_ob_material
or ob
.type in BLENDER_OTHER_OBJECT_TYPES
)
2265 backup_pose_positions
= []
2267 if use_org_data
and ob
.type == 'MESH':
2268 # No need to create a new mesh in this case, if no modifier is active!
2270 for mod
in ob
.modifiers
:
2271 # For meshes, when armature export is enabled, disable Armature modifiers here!
2272 # XXX Temp hacks here since currently we only have access to a viewport depsgraph...
2274 # NOTE: We put armature to the rest pose instead of disabling it so we still
2275 # have vertex groups in the evaluated mesh.
2276 if mod
.type == 'ARMATURE' and 'ARMATURE' in settings
.object_types
:
2278 if object and object.type == 'ARMATURE':
2279 armature
= object.data
2280 backup_pose_positions
.append((armature
, armature
.pose_position
))
2281 armature
.pose_position
= 'REST'
2282 elif mod
.show_render
or mod
.show_viewport
:
2283 # If exporting with subsurf collect the last Catmull-Clark subsurf modifier
2284 # and disable it. We can use the original data as long as this is the first
2285 # found applicable subsurf modifier.
2286 if settings
.use_subsurf
and mod
.type == 'SUBSURF' and mod
.subdivision_type
== 'CATMULL_CLARK':
2288 use_org_data
= False
2291 use_org_data
= False
2292 if settings
.use_subsurf
and last_subsurf
:
2293 # XXX: When exporting with subsurf information temporarily disable
2294 # the last subsurf modifier.
2295 tmp_mods
.append((last_subsurf
, last_subsurf
.show_render
, last_subsurf
.show_viewport
))
2296 last_subsurf
.show_render
= False
2297 last_subsurf
.show_viewport
= False
2298 if not use_org_data
:
2299 # If modifiers has been altered need to update dependency graph.
2300 if backup_pose_positions
or tmp_mods
:
2302 ob_to_convert
= ob
.evaluated_get(depsgraph
) if settings
.use_mesh_modifiers
else ob
2303 # NOTE: The dependency graph might be re-evaluating multiple times, which could
2304 # potentially free the mesh created early on. So we put those meshes to bmain and
2305 # free them afterwards. Not ideal but ensures correct ownerwhip.
2306 tmp_me
= bpy
.data
.meshes
.new_from_object(
2307 ob_to_convert
, preserve_all_data_layers
=True, depsgraph
=depsgraph
)
2308 data_meshes
[ob_obj
] = (get_blenderID_key(tmp_me
), tmp_me
, True)
2309 # Change armatures back.
2310 for armature
, pose_position
in backup_pose_positions
:
2311 print((armature
, pose_position
))
2312 armature
.pose_position
= pose_position
2313 # Update now, so we don't leave modified state after last object was exported.
2314 # Re-enable temporary disabled modifiers.
2315 for mod
, show_render
, show_viewport
in tmp_mods
:
2316 mod
.show_render
= show_render
2317 mod
.show_viewport
= show_viewport
2318 if backup_pose_positions
or tmp_mods
:
2321 data_meshes
[ob_obj
] = (get_blenderID_key(ob
.data
), ob
.data
, False)
2323 # In case "real" source object of that dupli did not yet still existed in data_meshes, create it now!
2324 if org_ob_obj
is not None:
2325 data_meshes
[org_ob_obj
] = data_meshes
[ob_obj
]
2327 perfmon
.step("FBX export prepare: Wrapping ShapeKeys...")
2330 data_deformers_shape
= {}
2331 geom_mat_co
= settings
.global_matrix
if settings
.bake_space_transform
else None
2332 for me_key
, me
, _free
in data_meshes
.values():
2333 if not (me
.shape_keys
and len(me
.shape_keys
.key_blocks
) > 1): # We do not want basis-only relative skeys...
2335 if me
in data_deformers_shape
:
2338 shapes_key
= get_blender_mesh_shape_key(me
)
2339 # We gather all vcos first, since some skeys may be based on others...
2340 _cos
= array
.array(data_types
.ARRAY_FLOAT64
, (0.0,)) * len(me
.vertices
) * 3
2341 me
.vertices
.foreach_get("co", _cos
)
2342 v_cos
= tuple(vcos_transformed_gen(_cos
, geom_mat_co
))
2344 for shape
in me
.shape_keys
.key_blocks
[1:]:
2345 shape
.data
.foreach_get("co", _cos
)
2346 sk_cos
[shape
] = tuple(vcos_transformed_gen(_cos
, geom_mat_co
))
2347 sk_base
= me
.shape_keys
.key_blocks
[0]
2349 for shape
in me
.shape_keys
.key_blocks
[1:]:
2350 # Only write vertices really different from org coordinates!
2352 shape_verts_idx
= []
2354 sv_cos
= sk_cos
[shape
]
2355 ref_cos
= v_cos
if shape
.relative_key
== sk_base
else sk_cos
[shape
.relative_key
]
2356 for idx
, (sv_co
, ref_co
) in enumerate(zip(sv_cos
, ref_cos
)):
2357 if similar_values_iter(sv_co
, ref_co
):
2358 # Note: Maybe this is a bit too simplistic, should we use real shape base here? Though FBX does not
2359 # have this at all... Anyway, this should cover most common cases imho.
2361 shape_verts_co
.extend(Vector(sv_co
) - Vector(ref_co
))
2362 shape_verts_idx
.append(idx
)
2364 # FBX does not like empty shapes (makes Unity crash e.g.).
2365 # To prevent this, we add a vertex that does nothing, but it keeps the shape key intact
2366 if not shape_verts_co
:
2367 shape_verts_co
.extend((0, 0, 0))
2368 shape_verts_idx
.append(0)
2370 channel_key
, geom_key
= get_blender_mesh_shape_channel_key(me
, shape
)
2371 data
= (channel_key
, geom_key
, shape_verts_co
, shape_verts_idx
)
2372 data_deformers_shape
.setdefault(me
, (me_key
, shapes_key
, {}))[2][shape
] = data
2374 perfmon
.step("FBX export prepare: Wrapping Armatures...")
2377 data_deformers_skin
= {}
2380 for ob_obj
in tuple(objects
):
2381 if not (ob_obj
.is_object
and ob_obj
.type in {'ARMATURE'}):
2383 fbx_skeleton_from_armature(scene
, settings
, ob_obj
, objects
, data_meshes
,
2384 data_bones
, data_deformers_skin
, data_empties
, arm_parents
)
2386 # Generate leaf bones
2387 data_leaf_bones
= []
2388 if settings
.add_leaf_bones
:
2389 data_leaf_bones
= fbx_generate_leaf_bones(settings
, data_bones
)
2391 perfmon
.step("FBX export prepare: Wrapping World...")
2393 # Some world settings are embedded in FBX materials...
2395 data_world
= {scene
.world
: get_blenderID_key(scene
.world
)}
2399 perfmon
.step("FBX export prepare: Wrapping Materials...")
2401 # TODO: Check all the material stuff works even when they are linked to Objects
2402 # (we can then have the same mesh used with different materials...).
2403 # *Should* work, as FBX always links its materials to Models (i.e. objects).
2404 # XXX However, material indices would probably break...
2406 for ob_obj
in objects
:
2407 # If obj is not a valid object for materials, wrapper will just return an empty tuple...
2408 for ma_s
in ob_obj
.material_slots
:
2411 continue # Empty slots!
2412 # Note theoretically, FBX supports any kind of materials, even GLSL shaders etc.
2413 # However, I doubt anything else than Lambert/Phong is really portable!
2414 # Note we want to keep a 'dummy' empty material even when we can't really support it, see T41396.
2415 ma_data
= data_materials
.setdefault(ma
, (get_blenderID_key(ma
), []))
2416 ma_data
[1].append(ob_obj
)
2418 perfmon
.step("FBX export prepare: Wrapping Textures...")
2420 # Note FBX textures also hold their mapping info.
2421 # TODO: Support layers?
2423 # FbxVideo also used to store static images...
2425 # For now, do not use world textures, don't think they can be linked to anything FBX wise...
2426 for ma
in data_materials
.keys():
2427 # Note: with nodal shaders, we'll could be generating much more textures, but that's kind of unavoidable,
2428 # given that textures actually do not exist anymore in material context in Blender...
2429 ma_wrap
= node_shader_utils
.PrincipledBSDFWrapper(ma
, is_readonly
=True)
2430 for sock_name
, fbx_name
in PRINCIPLED_TEXTURE_SOCKETS_TO_FBX
:
2431 tex
= getattr(ma_wrap
, sock_name
)
2432 if tex
is None or tex
.image
is None:
2434 blender_tex_key
= (ma
, sock_name
)
2435 data_textures
[blender_tex_key
] = (get_blender_nodetexture_key(*blender_tex_key
), fbx_name
)
2438 vid_data
= data_videos
.setdefault(img
, (get_blenderID_key(img
), []))
2439 vid_data
[1].append(blender_tex_key
)
2441 perfmon
.step("FBX export prepare: Wrapping Animations...")
2446 frame_start
= scene
.frame_start
2447 frame_end
= scene
.frame_end
2448 if settings
.bake_anim
:
2449 # From objects & bones only for a start.
2450 # Kind of hack, we need a temp scene_data for object's space handling to bake animations...
2451 tmp_scdata
= FBXExportData(
2453 settings
, scene
, depsgraph
, objects
, None, None, 0.0, 0.0,
2454 data_empties
, data_lights
, data_cameras
, data_meshes
, None,
2455 data_bones
, data_leaf_bones
, data_deformers_skin
, data_deformers_shape
,
2456 data_world
, data_materials
, data_textures
, data_videos
,
2458 animations
, animated
, frame_start
, frame_end
= fbx_animations(tmp_scdata
)
2460 # ##### Creation of templates...
2462 perfmon
.step("FBX export prepare: Generating templates...")
2465 templates
[b
"GlobalSettings"] = fbx_template_def_globalsettings(scene
, settings
, nbr_users
=1)
2468 templates
[b
"Null"] = fbx_template_def_null(scene
, settings
, nbr_users
=len(data_empties
))
2471 templates
[b
"Light"] = fbx_template_def_light(scene
, settings
, nbr_users
=len(data_lights
))
2474 templates
[b
"Camera"] = fbx_template_def_camera(scene
, settings
, nbr_users
=len(data_cameras
))
2477 templates
[b
"Bone"] = fbx_template_def_bone(scene
, settings
, nbr_users
=len(data_bones
))
2480 nbr
= len({me_key
for me_key
, _me
, _free
in data_meshes
.values()})
2481 if data_deformers_shape
:
2482 nbr
+= sum(len(shapes
[2]) for shapes
in data_deformers_shape
.values())
2483 templates
[b
"Geometry"] = fbx_template_def_geometry(scene
, settings
, nbr_users
=nbr
)
2486 templates
[b
"Model"] = fbx_template_def_model(scene
, settings
, nbr_users
=len(objects
))
2489 # Number of Pose|BindPose elements should be the same as number of meshes-parented-to-armatures
2490 templates
[b
"BindPose"] = fbx_template_def_pose(scene
, settings
, nbr_users
=len(arm_parents
))
2492 if data_deformers_skin
or data_deformers_shape
:
2494 if data_deformers_skin
:
2495 nbr
+= len(data_deformers_skin
)
2496 nbr
+= sum(len(clusters
) for def_me
in data_deformers_skin
.values() for a
, b
, clusters
in def_me
.values())
2497 if data_deformers_shape
:
2498 nbr
+= len(data_deformers_shape
)
2499 nbr
+= sum(len(shapes
[2]) for shapes
in data_deformers_shape
.values())
2501 templates
[b
"Deformers"] = fbx_template_def_deformer(scene
, settings
, nbr_users
=nbr
)
2503 # No world support in FBX...
2506 templates[b"World"] = fbx_template_def_world(scene, settings, nbr_users=len(data_world))
2510 templates
[b
"Material"] = fbx_template_def_material(scene
, settings
, nbr_users
=len(data_materials
))
2513 templates
[b
"TextureFile"] = fbx_template_def_texture_file(scene
, settings
, nbr_users
=len(data_textures
))
2516 templates
[b
"Video"] = fbx_template_def_video(scene
, settings
, nbr_users
=len(data_videos
))
2519 nbr_astacks
= len(animations
)
2522 for _astack_key
, astack
, _al
, _n
, _fs
, _fe
in animations
:
2523 for _alayer_key
, alayer
in astack
.values():
2524 for _acnode_key
, acnode
, _acnode_name
in alayer
.values():
2526 for _acurve_key
, _dval
, acurve
, acurve_valid
in acnode
.values():
2530 templates
[b
"AnimationStack"] = fbx_template_def_animstack(scene
, settings
, nbr_users
=nbr_astacks
)
2531 # Would be nice to have one layer per animated object, but this seems tricky and not that well supported.
2532 # So for now, only one layer per anim stack.
2533 templates
[b
"AnimationLayer"] = fbx_template_def_animlayer(scene
, settings
, nbr_users
=nbr_astacks
)
2534 templates
[b
"AnimationCurveNode"] = fbx_template_def_animcurvenode(scene
, settings
, nbr_users
=nbr_acnodes
)
2535 templates
[b
"AnimationCurve"] = fbx_template_def_animcurve(scene
, settings
, nbr_users
=nbr_acurves
)
2537 templates_users
= sum(tmpl
.nbr_users
for tmpl
in templates
.values())
2539 # ##### Creation of connections...
2541 perfmon
.step("FBX export prepare: Generating Connections...")
2545 # Objects (with classical parenting).
2546 for ob_obj
in objects
:
2547 # Bones are handled later.
2548 if not ob_obj
.is_bone
:
2549 par_obj
= ob_obj
.parent
2550 # Meshes parented to armature are handled separately, yet we want the 'no parent' connection (0).
2551 if par_obj
and ob_obj
.has_valid_parent(objects
) and (par_obj
, ob_obj
) not in arm_parents
:
2552 connections
.append((b
"OO", ob_obj
.fbx_uuid
, par_obj
.fbx_uuid
, None))
2554 connections
.append((b
"OO", ob_obj
.fbx_uuid
, 0, None))
2556 # Armature & Bone chains.
2557 for bo_obj
in data_bones
.keys():
2558 par_obj
= bo_obj
.parent
2559 if par_obj
not in objects
:
2561 connections
.append((b
"OO", bo_obj
.fbx_uuid
, par_obj
.fbx_uuid
, None))
2564 for ob_obj
in objects
:
2566 bo_data_key
= data_bones
[ob_obj
]
2567 connections
.append((b
"OO", get_fbx_uuid_from_key(bo_data_key
), ob_obj
.fbx_uuid
, None))
2569 if ob_obj
.type == 'LIGHT':
2570 light_key
= data_lights
[ob_obj
.bdata
.data
]
2571 connections
.append((b
"OO", get_fbx_uuid_from_key(light_key
), ob_obj
.fbx_uuid
, None))
2572 elif ob_obj
.type == 'CAMERA':
2573 cam_key
= data_cameras
[ob_obj
]
2574 connections
.append((b
"OO", get_fbx_uuid_from_key(cam_key
), ob_obj
.fbx_uuid
, None))
2575 elif ob_obj
.type == 'EMPTY' or ob_obj
.type == 'ARMATURE':
2576 empty_key
= data_empties
[ob_obj
]
2577 connections
.append((b
"OO", get_fbx_uuid_from_key(empty_key
), ob_obj
.fbx_uuid
, None))
2578 elif ob_obj
.type in BLENDER_OBJECT_TYPES_MESHLIKE
:
2579 mesh_key
, _me
, _free
= data_meshes
[ob_obj
]
2580 connections
.append((b
"OO", get_fbx_uuid_from_key(mesh_key
), ob_obj
.fbx_uuid
, None))
2583 for (_node_name
, par_uuid
, node_uuid
, attr_uuid
, _matrix
, _hide
, _size
) in data_leaf_bones
:
2584 connections
.append((b
"OO", node_uuid
, par_uuid
, None))
2585 connections
.append((b
"OO", attr_uuid
, node_uuid
, None))
2587 # 'Shape' deformers (shape keys, only for meshes currently)...
2588 for me_key
, shapes_key
, shapes
in data_deformers_shape
.values():
2590 connections
.append((b
"OO", get_fbx_uuid_from_key(shapes_key
), get_fbx_uuid_from_key(me_key
), None))
2591 for channel_key
, geom_key
, _shape_verts_co
, _shape_verts_idx
in shapes
.values():
2592 # shape channel -> shape
2593 connections
.append((b
"OO", get_fbx_uuid_from_key(channel_key
), get_fbx_uuid_from_key(shapes_key
), None))
2594 # geometry (keys) -> shape channel
2595 connections
.append((b
"OO", get_fbx_uuid_from_key(geom_key
), get_fbx_uuid_from_key(channel_key
), None))
2597 # 'Skin' deformers (armature-to-geometry, only for meshes currently)...
2598 for arm
, deformed_meshes
in data_deformers_skin
.items():
2599 for me
, (skin_key
, ob_obj
, clusters
) in deformed_meshes
.items():
2601 mesh_key
, _me
, _free
= data_meshes
[ob_obj
]
2603 connections
.append((b
"OO", get_fbx_uuid_from_key(skin_key
), get_fbx_uuid_from_key(mesh_key
), None))
2604 for bo_obj
, clstr_key
in clusters
.items():
2606 connections
.append((b
"OO", get_fbx_uuid_from_key(clstr_key
), get_fbx_uuid_from_key(skin_key
), None))
2608 connections
.append((b
"OO", bo_obj
.fbx_uuid
, get_fbx_uuid_from_key(clstr_key
), None))
2611 mesh_material_indices
= {}
2613 for ma
, (ma_key
, ob_objs
) in data_materials
.items():
2614 for ob_obj
in ob_objs
:
2615 connections
.append((b
"OO", get_fbx_uuid_from_key(ma_key
), ob_obj
.fbx_uuid
, None))
2616 # Get index of this material for this object (or dupliobject).
2617 # Material indices for mesh faces are determined by their order in 'ma to ob' connections.
2618 # Only materials for meshes currently...
2619 # Note in case of dupliobjects a same me/ma idx will be generated several times...
2620 # Should not be an issue in practice, and it's needed in case we export duplis but not the original!
2621 if ob_obj
.type not in BLENDER_OBJECT_TYPES_MESHLIKE
:
2623 _mesh_key
, me
, _free
= data_meshes
[ob_obj
]
2624 idx
= _objs_indices
[ob_obj
] = _objs_indices
.get(ob_obj
, -1) + 1
2625 mesh_material_indices
.setdefault(me
, {})[ma
] = idx
2629 for (ma
, sock_name
), (tex_key
, fbx_prop
) in data_textures
.items():
2630 ma_key
, _ob_objs
= data_materials
[ma
]
2631 # texture -> material properties
2632 connections
.append((b
"OP", get_fbx_uuid_from_key(tex_key
), get_fbx_uuid_from_key(ma_key
), fbx_prop
))
2635 for vid
, (vid_key
, blender_tex_keys
) in data_videos
.items():
2636 for blender_tex_key
in blender_tex_keys
:
2637 tex_key
, _fbx_prop
= data_textures
[blender_tex_key
]
2638 connections
.append((b
"OO", get_fbx_uuid_from_key(vid_key
), get_fbx_uuid_from_key(tex_key
), None))
2641 for astack_key
, astack
, alayer_key
, _name
, _fstart
, _fend
in animations
:
2642 # Animstack itself is linked nowhere!
2643 astack_id
= get_fbx_uuid_from_key(astack_key
)
2644 # For now, only one layer!
2645 alayer_id
= get_fbx_uuid_from_key(alayer_key
)
2646 connections
.append((b
"OO", alayer_id
, astack_id
, None))
2647 for elem_key
, (alayer_key
, acurvenodes
) in astack
.items():
2648 elem_id
= get_fbx_uuid_from_key(elem_key
)
2649 # Animlayer -> animstack.
2650 # alayer_id = get_fbx_uuid_from_key(alayer_key)
2651 # connections.append((b"OO", alayer_id, astack_id, None))
2652 for fbx_prop
, (acurvenode_key
, acurves
, acurvenode_name
) in acurvenodes
.items():
2653 # Animcurvenode -> animalayer.
2654 acurvenode_id
= get_fbx_uuid_from_key(acurvenode_key
)
2655 connections
.append((b
"OO", acurvenode_id
, alayer_id
, None))
2656 # Animcurvenode -> object property.
2657 connections
.append((b
"OP", acurvenode_id
, elem_id
, fbx_prop
.encode()))
2658 for fbx_item
, (acurve_key
, default_value
, acurve
, acurve_valid
) in acurves
.items():
2660 # Animcurve -> Animcurvenode.
2661 connections
.append((b
"OP", get_fbx_uuid_from_key(acurve_key
), acurvenode_id
, fbx_item
.encode()))
2663 perfmon
.level_down()
2665 # ##### And pack all this!
2667 return FBXExportData(
2668 templates
, templates_users
, connections
,
2669 settings
, scene
, depsgraph
, objects
, animations
, animated
, frame_start
, frame_end
,
2670 data_empties
, data_lights
, data_cameras
, data_meshes
, mesh_material_indices
,
2671 data_bones
, data_leaf_bones
, data_deformers_skin
, data_deformers_shape
,
2672 data_world
, data_materials
, data_textures
, data_videos
,
2676 def fbx_scene_data_cleanup(scene_data
):
2678 Some final cleanup...
2680 # Delete temp meshes.
2682 for me_key
, me
, free
in scene_data
.data_meshes
.values():
2683 if free
and me_key
not in done_meshes
:
2684 bpy
.data
.meshes
.remove(me
)
2685 done_meshes
.add(me_key
)
2688 # ##### Top-level FBX elements generators. #####
2690 def fbx_header_elements(root
, scene_data
, time
=None):
2692 Write boiling code of FBX root.
2693 time is expected to be a datetime.datetime object, or None (using now() in this case).
2695 app_vendor
= "Blender Foundation"
2696 app_name
= "Blender (stable FBX IO)"
2697 app_ver
= bpy
.app
.version_string
2701 addon_ver
= addon_utils
.module_bl_info(sys
.modules
[__package__
])['version']
2703 # ##### Start of FBXHeaderExtension element.
2704 header_ext
= elem_empty(root
, b
"FBXHeaderExtension")
2706 elem_data_single_int32(header_ext
, b
"FBXHeaderVersion", FBX_HEADER_VERSION
)
2708 elem_data_single_int32(header_ext
, b
"FBXVersion", FBX_VERSION
)
2711 elem_data_single_int32(header_ext
, b
"EncryptionType", 0)
2714 time
= datetime
.datetime
.now()
2715 elem
= elem_empty(header_ext
, b
"CreationTimeStamp")
2716 elem_data_single_int32(elem
, b
"Version", 1000)
2717 elem_data_single_int32(elem
, b
"Year", time
.year
)
2718 elem_data_single_int32(elem
, b
"Month", time
.month
)
2719 elem_data_single_int32(elem
, b
"Day", time
.day
)
2720 elem_data_single_int32(elem
, b
"Hour", time
.hour
)
2721 elem_data_single_int32(elem
, b
"Minute", time
.minute
)
2722 elem_data_single_int32(elem
, b
"Second", time
.second
)
2723 elem_data_single_int32(elem
, b
"Millisecond", time
.microsecond
// 1000)
2725 elem_data_single_string_unicode(header_ext
, b
"Creator", "%s - %s - %d.%d.%d"
2726 % (app_name
, app_ver
, addon_ver
[0], addon_ver
[1], addon_ver
[2]))
2728 # 'SceneInfo' seems mandatory to get a valid FBX file...
2729 # TODO use real values!
2730 # XXX Should we use scene.name.encode() here?
2731 scene_info
= elem_data_single_string(header_ext
, b
"SceneInfo", fbx_name_class(b
"GlobalInfo", b
"SceneInfo"))
2732 scene_info
.add_string(b
"UserData")
2733 elem_data_single_string(scene_info
, b
"Type", b
"UserData")
2734 elem_data_single_int32(scene_info
, b
"Version", FBX_SCENEINFO_VERSION
)
2735 meta_data
= elem_empty(scene_info
, b
"MetaData")
2736 elem_data_single_int32(meta_data
, b
"Version", FBX_SCENEINFO_VERSION
)
2737 elem_data_single_string(meta_data
, b
"Title", b
"")
2738 elem_data_single_string(meta_data
, b
"Subject", b
"")
2739 elem_data_single_string(meta_data
, b
"Author", b
"")
2740 elem_data_single_string(meta_data
, b
"Keywords", b
"")
2741 elem_data_single_string(meta_data
, b
"Revision", b
"")
2742 elem_data_single_string(meta_data
, b
"Comment", b
"")
2744 props
= elem_properties(scene_info
)
2745 elem_props_set(props
, "p_string_url", b
"DocumentUrl", "/foobar.fbx")
2746 elem_props_set(props
, "p_string_url", b
"SrcDocumentUrl", "/foobar.fbx")
2747 original
= elem_props_compound(props
, b
"Original")
2748 original("p_string", b
"ApplicationVendor", app_vendor
)
2749 original("p_string", b
"ApplicationName", app_name
)
2750 original("p_string", b
"ApplicationVersion", app_ver
)
2751 original("p_datetime", b
"DateTime_GMT", "01/01/1970 00:00:00.000")
2752 original("p_string", b
"FileName", "/foobar.fbx")
2753 lastsaved
= elem_props_compound(props
, b
"LastSaved")
2754 lastsaved("p_string", b
"ApplicationVendor", app_vendor
)
2755 lastsaved("p_string", b
"ApplicationName", app_name
)
2756 lastsaved("p_string", b
"ApplicationVersion", app_ver
)
2757 lastsaved("p_datetime", b
"DateTime_GMT", "01/01/1970 00:00:00.000")
2759 # ##### End of FBXHeaderExtension element.
2761 # FileID is replaced by dummy value currently...
2762 elem_data_single_bytes(root
, b
"FileId", b
"FooBar")
2764 # CreationTime is replaced by dummy value currently, but anyway...
2765 elem_data_single_string_unicode(root
, b
"CreationTime",
2766 "{:04}-{:02}-{:02} {:02}:{:02}:{:02}:{:03}"
2767 "".format(time
.year
, time
.month
, time
.day
, time
.hour
, time
.minute
, time
.second
,
2768 time
.microsecond
* 1000))
2770 elem_data_single_string_unicode(root
, b
"Creator", "%s - %s - %d.%d.%d"
2771 % (app_name
, app_ver
, addon_ver
[0], addon_ver
[1], addon_ver
[2]))
2773 # ##### Start of GlobalSettings element.
2774 global_settings
= elem_empty(root
, b
"GlobalSettings")
2775 scene
= scene_data
.scene
2777 elem_data_single_int32(global_settings
, b
"Version", 1000)
2779 props
= elem_properties(global_settings
)
2780 up_axis
, front_axis
, coord_axis
= RIGHT_HAND_AXES
[scene_data
.settings
.to_axes
]
2781 #~ # DO NOT take into account global scale here! That setting is applied to object transformations during export
2782 #~ # (in other words, this is pure blender-exporter feature, and has nothing to do with FBX data).
2783 #~ if scene_data.settings.apply_unit_scale:
2784 #~ # Unit scaling is applied to objects' scale, so our unit is effectively FBX one (centimeter).
2785 #~ scale_factor_org = 1.0
2786 #~ scale_factor = 1.0 / units_blender_to_fbx_factor(scene)
2788 #~ scale_factor_org = units_blender_to_fbx_factor(scene)
2789 #~ scale_factor = scale_factor_org
2790 scale_factor
= scale_factor_org
= scene_data
.settings
.unit_scale
2791 elem_props_set(props
, "p_integer", b
"UpAxis", up_axis
[0])
2792 elem_props_set(props
, "p_integer", b
"UpAxisSign", up_axis
[1])
2793 elem_props_set(props
, "p_integer", b
"FrontAxis", front_axis
[0])
2794 elem_props_set(props
, "p_integer", b
"FrontAxisSign", front_axis
[1])
2795 elem_props_set(props
, "p_integer", b
"CoordAxis", coord_axis
[0])
2796 elem_props_set(props
, "p_integer", b
"CoordAxisSign", coord_axis
[1])
2797 elem_props_set(props
, "p_integer", b
"OriginalUpAxis", -1)
2798 elem_props_set(props
, "p_integer", b
"OriginalUpAxisSign", 1)
2799 elem_props_set(props
, "p_double", b
"UnitScaleFactor", scale_factor
)
2800 elem_props_set(props
, "p_double", b
"OriginalUnitScaleFactor", scale_factor_org
)
2801 elem_props_set(props
, "p_color_rgb", b
"AmbientColor", (0.0, 0.0, 0.0))
2802 elem_props_set(props
, "p_string", b
"DefaultCamera", "Producer Perspective")
2804 # Global timing data.
2806 _
, fbx_fps_mode
= FBX_FRAMERATES
[0] # Custom framerate.
2807 fbx_fps
= fps
= r
.fps
/ r
.fps_base
2808 for ref_fps
, fps_mode
in FBX_FRAMERATES
:
2809 if similar_values(fps
, ref_fps
):
2811 fbx_fps_mode
= fps_mode
2812 elem_props_set(props
, "p_enum", b
"TimeMode", fbx_fps_mode
)
2813 elem_props_set(props
, "p_timestamp", b
"TimeSpanStart", 0)
2814 elem_props_set(props
, "p_timestamp", b
"TimeSpanStop", FBX_KTIME
)
2815 elem_props_set(props
, "p_double", b
"CustomFrameRate", fbx_fps
)
2817 # ##### End of GlobalSettings element.
2820 def fbx_documents_elements(root
, scene_data
):
2822 Write 'Document' part of FBX root.
2823 Seems like FBX support multiple documents, but until I find examples of such, we'll stick to single doc!
2824 time is expected to be a datetime.datetime object, or None (using now() in this case).
2826 name
= scene_data
.scene
.name
2828 # ##### Start of Documents element.
2829 docs
= elem_empty(root
, b
"Documents")
2831 elem_data_single_int32(docs
, b
"Count", 1)
2833 doc_uid
= get_fbx_uuid_from_key("__FBX_Document__" + name
)
2834 doc
= elem_data_single_int64(docs
, b
"Document", doc_uid
)
2835 doc
.add_string_unicode(name
)
2836 doc
.add_string_unicode(name
)
2838 props
= elem_properties(doc
)
2839 elem_props_set(props
, "p_object", b
"SourceObject")
2840 elem_props_set(props
, "p_string", b
"ActiveAnimStackName", "")
2842 # XXX Some kind of ID? Offset?
2843 # Anyway, as long as we have only one doc, probably not an issue.
2844 elem_data_single_int64(doc
, b
"RootNode", 0)
2847 def fbx_references_elements(root
, scene_data
):
2849 Have no idea what references are in FBX currently... Just writing empty element.
2851 docs
= elem_empty(root
, b
"References")
2854 def fbx_definitions_elements(root
, scene_data
):
2856 Templates definitions. Only used by Objects data afaik (apart from dummy GlobalSettings one).
2858 definitions
= elem_empty(root
, b
"Definitions")
2860 elem_data_single_int32(definitions
, b
"Version", FBX_TEMPLATES_VERSION
)
2861 elem_data_single_int32(definitions
, b
"Count", scene_data
.templates_users
)
2863 fbx_templates_generate(definitions
, scene_data
.templates
)
2866 def fbx_objects_elements(root
, scene_data
):
2868 Data (objects, geometry, material, textures, armatures, etc.).
2872 objects
= elem_empty(root
, b
"Objects")
2874 perfmon
.step("FBX export fetch empties (%d)..." % len(scene_data
.data_empties
))
2876 for empty
in scene_data
.data_empties
:
2877 fbx_data_empty_elements(objects
, empty
, scene_data
)
2879 perfmon
.step("FBX export fetch lamps (%d)..." % len(scene_data
.data_lights
))
2881 for lamp
in scene_data
.data_lights
:
2882 fbx_data_light_elements(objects
, lamp
, scene_data
)
2884 perfmon
.step("FBX export fetch cameras (%d)..." % len(scene_data
.data_cameras
))
2886 for cam
in scene_data
.data_cameras
:
2887 fbx_data_camera_elements(objects
, cam
, scene_data
)
2889 perfmon
.step("FBX export fetch meshes (%d)..."
2890 % len({me_key
for me_key
, _me
, _free
in scene_data
.data_meshes
.values()}))
2893 for me_obj
in scene_data
.data_meshes
:
2894 fbx_data_mesh_elements(objects
, me_obj
, scene_data
, done_meshes
)
2897 perfmon
.step("FBX export fetch objects (%d)..." % len(scene_data
.objects
))
2899 for ob_obj
in scene_data
.objects
:
2902 fbx_data_object_elements(objects
, ob_obj
, scene_data
)
2903 for dp_obj
in ob_obj
.dupli_list_gen(scene_data
.depsgraph
):
2904 if dp_obj
not in scene_data
.objects
:
2906 fbx_data_object_elements(objects
, dp_obj
, scene_data
)
2908 perfmon
.step("FBX export fetch remaining...")
2910 for ob_obj
in scene_data
.objects
:
2911 if not (ob_obj
.is_object
and ob_obj
.type == 'ARMATURE'):
2913 fbx_data_armature_elements(objects
, ob_obj
, scene_data
)
2915 if scene_data
.data_leaf_bones
:
2916 fbx_data_leaf_bone_elements(objects
, scene_data
)
2918 for ma
in scene_data
.data_materials
:
2919 fbx_data_material_elements(objects
, ma
, scene_data
)
2921 for blender_tex_key
in scene_data
.data_textures
:
2922 fbx_data_texture_file_elements(objects
, blender_tex_key
, scene_data
)
2924 for vid
in scene_data
.data_videos
:
2925 fbx_data_video_elements(objects
, vid
, scene_data
)
2927 perfmon
.step("FBX export fetch animations...")
2928 start_time
= time
.process_time()
2930 fbx_data_animation_elements(objects
, scene_data
)
2932 perfmon
.level_down()
2935 def fbx_connections_elements(root
, scene_data
):
2937 Relations between Objects (which material uses which texture, and so on).
2939 connections
= elem_empty(root
, b
"Connections")
2941 for c
in scene_data
.connections
:
2942 elem_connection(connections
, *c
)
2945 def fbx_takes_elements(root
, scene_data
):
2949 # XXX Pretty sure takes are no more needed...
2950 takes
= elem_empty(root
, b
"Takes")
2951 elem_data_single_string(takes
, b
"Current", b
"")
2953 animations
= scene_data
.animations
2954 for astack_key
, animations
, alayer_key
, name
, f_start
, f_end
in animations
:
2955 scene
= scene_data
.scene
2956 fps
= scene
.render
.fps
/ scene
.render
.fps_base
2957 start_ktime
= int(convert_sec_to_ktime(f_start
/ fps
))
2958 end_ktime
= int(convert_sec_to_ktime(f_end
/ fps
))
2960 take
= elem_data_single_string(takes
, b
"Take", name
)
2961 elem_data_single_string(take
, b
"FileName", name
+ b
".tak")
2962 take_loc_time
= elem_data_single_int64(take
, b
"LocalTime", start_ktime
)
2963 take_loc_time
.add_int64(end_ktime
)
2964 take_ref_time
= elem_data_single_int64(take
, b
"ReferenceTime", start_ktime
)
2965 take_ref_time
.add_int64(end_ktime
)
2968 # ##### "Main" functions. #####
2970 # This func can be called with just the filepath
2971 def save_single(operator
, scene
, depsgraph
, filepath
="",
2972 global_matrix
=Matrix(),
2973 apply_unit_scale
=False,
2975 apply_scale_options
='FBX_SCALE_NONE',
2978 context_objects
=None,
2980 use_mesh_modifiers
=True,
2981 use_mesh_modifiers_render
=True,
2982 mesh_smooth_type
='FACE',
2984 use_armature_deform_only
=False,
2986 bake_anim_use_all_bones
=True,
2987 bake_anim_use_nla_strips
=True,
2988 bake_anim_use_all_actions
=True,
2990 bake_anim_simplify_factor
=1.0,
2991 bake_anim_force_startend_keying
=True,
2992 add_leaf_bones
=False,
2993 primary_bone_axis
='Y',
2994 secondary_bone_axis
='X',
2997 use_mesh_edges
=True,
2999 embed_textures
=False,
3000 use_custom_props
=False,
3001 bake_space_transform
=False,
3002 armature_nodetype
='NULL',
3006 # Clear cached ObjectWrappers (just in case...).
3007 ObjectWrapper
.cache_clear()
3009 if object_types
is None:
3010 object_types
= {'EMPTY', 'CAMERA', 'LIGHT', 'ARMATURE', 'MESH', 'OTHER'}
3012 if 'OTHER' in object_types
:
3013 object_types |
= BLENDER_OTHER_OBJECT_TYPES
3015 # Default Blender unit is equivalent to meter, while FBX one is centimeter...
3016 unit_scale
= units_blender_to_fbx_factor(scene
) if apply_unit_scale
else 100.0
3017 if apply_scale_options
== 'FBX_SCALE_NONE':
3018 global_matrix
= Matrix
.Scale(unit_scale
* global_scale
, 4) @ global_matrix
3020 elif apply_scale_options
== 'FBX_SCALE_UNITS':
3021 global_matrix
= Matrix
.Scale(global_scale
, 4) @ global_matrix
3022 elif apply_scale_options
== 'FBX_SCALE_CUSTOM':
3023 global_matrix
= Matrix
.Scale(unit_scale
, 4) @ global_matrix
3024 unit_scale
= global_scale
3025 else: # if apply_scale_options == 'FBX_SCALE_ALL':
3026 unit_scale
= global_scale
* unit_scale
3028 global_scale
= global_matrix
.median_scale
3029 global_matrix_inv
= global_matrix
.inverted()
3030 # For transforming mesh normals.
3031 global_matrix_inv_transposed
= global_matrix_inv
.transposed()
3033 # Only embed textures in COPY mode!
3034 if embed_textures
and path_mode
!= 'COPY':
3035 embed_textures
= False
3037 # Calculate bone correction matrix
3038 bone_correction_matrix
= None # Default is None = no change
3039 bone_correction_matrix_inv
= None
3040 if (primary_bone_axis
, secondary_bone_axis
) != ('Y', 'X'):
3041 from bpy_extras
.io_utils
import axis_conversion
3042 bone_correction_matrix
= axis_conversion(from_forward
=secondary_bone_axis
,
3043 from_up
=primary_bone_axis
,
3047 bone_correction_matrix_inv
= bone_correction_matrix
.inverted()
3050 media_settings
= FBXExportSettingsMedia(
3052 os
.path
.dirname(bpy
.data
.filepath
), # base_src
3053 os
.path
.dirname(filepath
), # base_dst
3054 # Local dir where to put images (media), using FBX conventions.
3055 os
.path
.splitext(os
.path
.basename(filepath
))[0] + ".fbm", # subdir
3058 set(), # embedded_set
3061 settings
= FBXExportSettings(
3062 operator
.report
, (axis_up
, axis_forward
), global_matrix
, global_scale
, apply_unit_scale
, unit_scale
,
3063 bake_space_transform
, global_matrix_inv
, global_matrix_inv_transposed
,
3064 context_objects
, object_types
, use_mesh_modifiers
, use_mesh_modifiers_render
,
3065 mesh_smooth_type
, use_subsurf
, use_mesh_edges
, use_tspace
,
3066 armature_nodetype
, use_armature_deform_only
,
3067 add_leaf_bones
, bone_correction_matrix
, bone_correction_matrix_inv
,
3068 bake_anim
, bake_anim_use_all_bones
, bake_anim_use_nla_strips
, bake_anim_use_all_actions
,
3069 bake_anim_step
, bake_anim_simplify_factor
, bake_anim_force_startend_keying
,
3070 False, media_settings
, use_custom_props
,
3073 import bpy_extras
.io_utils
3075 print('\nFBX export starting... %r' % filepath
)
3076 start_time
= time
.process_time()
3078 # Generate some data about exported scene...
3079 scene_data
= fbx_data_from_scene(scene
, depsgraph
, settings
)
3081 root
= elem_empty(None, b
"") # Root element has no id, as it is not saved per se!
3083 # Mostly FBXHeaderExtension and GlobalSettings.
3084 fbx_header_elements(root
, scene_data
)
3086 # Documents and References are pretty much void currently.
3087 fbx_documents_elements(root
, scene_data
)
3088 fbx_references_elements(root
, scene_data
)
3090 # Templates definitions.
3091 fbx_definitions_elements(root
, scene_data
)
3094 fbx_objects_elements(root
, scene_data
)
3096 # How data are inter-connected.
3097 fbx_connections_elements(root
, scene_data
)
3100 fbx_takes_elements(root
, scene_data
)
3103 fbx_scene_data_cleanup(scene_data
)
3105 # And we are down, we can write the whole thing!
3106 encode_bin
.write(filepath
, root
, FBX_VERSION
)
3108 # Clear cached ObjectWrappers!
3109 ObjectWrapper
.cache_clear()
3111 # copy all collected files, if we did not embed them.
3112 if not media_settings
.embed_textures
:
3113 bpy_extras
.io_utils
.path_reference_copy(media_settings
.copy_set
)
3115 print('export finished in %.4f sec.' % (time
.process_time() - start_time
))
3119 # defaults for applications, currently only unity but could add others.
3120 def defaults_unity3d():
3122 # These options seem to produce the same result as the old Ascii exporter in Unity3D:
3124 "axis_forward": '-Z',
3125 "global_matrix": Matrix
.Rotation(-math
.pi
/ 2.0, 4, 'X'),
3126 # Should really be True, but it can cause problems if a model is already in a scene or prefab
3127 # with the old transforms.
3128 "bake_space_transform": False,
3130 "use_selection": False,
3132 "object_types": {'ARMATURE', 'EMPTY', 'MESH', 'OTHER'},
3133 "use_mesh_modifiers": True,
3134 "use_mesh_modifiers_render": True,
3135 "use_mesh_edges": False,
3136 "mesh_smooth_type": 'FACE',
3137 "use_subsurf": False,
3138 "use_tspace": False, # XXX Why? Unity is expected to support tspace import...
3140 "use_armature_deform_only": True,
3142 "use_custom_props": True,
3145 "bake_anim_simplify_factor": 1.0,
3146 "bake_anim_step": 1.0,
3147 "bake_anim_use_nla_strips": True,
3148 "bake_anim_use_all_actions": True,
3149 "add_leaf_bones": False, # Avoid memory/performance cost for something only useful for modelling
3150 "primary_bone_axis": 'Y', # Doesn't really matter for Unity, so leave unchanged
3151 "secondary_bone_axis": 'X',
3153 "path_mode": 'AUTO',
3154 "embed_textures": False,
3155 "batch_mode": 'OFF',
3159 def save(operator
, context
,
3161 use_selection
=False,
3162 use_active_collection
=False,
3164 use_batch_own_dir
=False,
3168 This is a wrapper around save_single, which handles multi-scenes (or collections) cases, when batch-exporting
3169 a whole .blend file.
3174 active_object
= context
.view_layer
.objects
.active
3177 if active_object
and active_object
.mode
!= 'OBJECT' and bpy
.ops
.object.mode_set
.poll():
3178 org_mode
= active_object
.mode
3179 bpy
.ops
.object.mode_set(mode
='OBJECT')
3181 if batch_mode
== 'OFF':
3182 kwargs_mod
= kwargs
.copy()
3183 if use_active_collection
:
3185 ctx_objects
= tuple(obj
3186 for obj
in context
.view_layer
.active_layer_collection
.collection
.all_objects
3187 if obj
.select_get())
3189 ctx_objects
= context
.view_layer
.active_layer_collection
.collection
.all_objects
3192 ctx_objects
= context
.selected_objects
3194 ctx_objects
= context
.view_layer
.objects
3195 kwargs_mod
["context_objects"] = ctx_objects
3197 depsgraph
= context
.evaluated_depsgraph_get()
3198 ret
= save_single(operator
, context
.scene
, depsgraph
, filepath
, **kwargs_mod
)
3200 # XXX We need a way to generate a depsgraph for inactive view_layers first...
3201 # XXX Also, what to do in case of batch-exporting scenes, when there is more than one view layer?
3202 # Scenes have no concept of 'active' view layer, that's on window level...
3205 prefix
= os
.path
.basename(fbxpath
)
3207 fbxpath
= os
.path
.dirname(fbxpath
)
3209 if batch_mode
== 'COLLECTION':
3210 data_seq
= tuple((coll
, coll
.name
, 'objects') for coll
in bpy
.data
.collections
if coll
.objects
)
3211 elif batch_mode
in {'SCENE_COLLECTION', 'ACTIVE_SCENE_COLLECTION'}:
3212 scenes
= [context
.scene
] if batch_mode
== 'ACTIVE_SCENE_COLLECTION' else bpy
.data
.scenes
3214 for scene
in scenes
:
3215 if not scene
.objects
:
3217 # Needed to avoid having tens of 'Master Collection' entries.
3218 todo_collections
= [(scene
.collection
, "_".join((scene
.name
, scene
.collection
.name
)))]
3219 while todo_collections
:
3220 coll
, coll_name
= todo_collections
.pop()
3221 todo_collections
.extend(((c
, c
.name
) for c
in coll
.children
if c
.all_objects
))
3222 data_seq
.append((coll
, coll_name
, 'all_objects'))
3224 data_seq
= tuple((scene
, scene
.name
, 'objects') for scene
in bpy
.data
.scenes
if scene
.objects
)
3226 # call this function within a loop with BATCH_ENABLE == False
3228 new_fbxpath
= fbxpath
# own dir option modifies, we need to keep an original
3229 for data
, data_name
, data_obj_propname
in data_seq
: # scene or collection
3230 newname
= "_".join((prefix
, bpy
.path
.clean_name(data_name
))) if prefix
else bpy
.path
.clean_name(data_name
)
3232 if use_batch_own_dir
:
3233 new_fbxpath
= os
.path
.join(fbxpath
, newname
)
3234 # path may already exist... and be a file.
3235 while os
.path
.isfile(new_fbxpath
):
3236 new_fbxpath
= "_".join((new_fbxpath
, "dir"))
3237 if not os
.path
.exists(new_fbxpath
):
3238 os
.makedirs(new_fbxpath
)
3240 filepath
= os
.path
.join(new_fbxpath
, newname
+ '.fbx')
3242 print('\nBatch exporting %s as...\n\t%r' % (data
, filepath
))
3244 if batch_mode
in {'COLLECTION', 'SCENE_COLLECTION', 'ACTIVE_SCENE_COLLECTION'}:
3245 # Collection, so that objects update properly, add a dummy scene.
3246 scene
= bpy
.data
.scenes
.new(name
="FBX_Temp")
3247 src_scenes
= {} # Count how much each 'source' scenes are used.
3248 for obj
in getattr(data
, data_obj_propname
):
3249 for src_sce
in obj
.users_scene
:
3250 src_scenes
[src_sce
] = src_scenes
.setdefault(src_sce
, 0) + 1
3251 scene
.collection
.objects
.link(obj
)
3253 # Find the 'most used' source scene, and use its unit settings. This is somewhat weak, but should work
3254 # fine in most cases, and avoids stupid issues like T41931.
3255 best_src_scene
= None
3256 best_src_scene_users
= -1
3257 for sce
, nbr_users
in src_scenes
.items():
3258 if (nbr_users
) > best_src_scene_users
:
3259 best_src_scene_users
= nbr_users
3260 best_src_scene
= sce
3261 scene
.unit_settings
.system
= best_src_scene
.unit_settings
.system
3262 scene
.unit_settings
.system_rotation
= best_src_scene
.unit_settings
.system_rotation
3263 scene
.unit_settings
.scale_length
= best_src_scene
.unit_settings
.scale_length
3265 # new scene [only one viewlayer to update]
3266 scene
.view_layers
[0].update()
3267 # TODO - BUMMER! Armatures not in the group wont animate the mesh
3271 kwargs_batch
= kwargs
.copy()
3272 kwargs_batch
["context_objects"] = getattr(data
, data_obj_propname
)
3274 save_single(operator
, scene
, scene
.view_layers
[0].depsgraph
, filepath
, **kwargs_batch
)
3276 if batch_mode
in {'COLLECTION', 'SCENE_COLLECTION', 'ACTIVE_SCENE_COLLECTION'}:
3277 # Remove temp collection scene.
3278 bpy
.data
.scenes
.remove(scene
)
3280 if active_object
and org_mode
:
3281 context
.view_layer
.objects
.active
= active_object
3282 if bpy
.ops
.object.mode_set
.poll():
3283 bpy
.ops
.object.mode_set(mode
=org_mode
)