Blender V5.3
fbx_import.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2025 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include "BKE_camera.h"
10#include "BKE_layer.hh"
11#include "BKE_lib_id.hh"
12#include "BKE_library.hh"
13#include "BKE_light.h"
14#include "BKE_object.hh"
15#include "BKE_report.hh"
16
17#include "BLI_fileops.hh"
19#include "BLI_task.hh"
20
21#include "DEG_depsgraph.hh"
23
24#include "DNA_camera_types.h"
26#include "DNA_light_types.h"
27#include "DNA_material_types.h"
28#include "DNA_scene_types.h"
29
30#include "IO_fbx.hh"
31
32#include "fbx_import.hh"
33#include "fbx_import_anim.hh"
36#include "fbx_import_mesh.hh"
37#include "fbx_import_util.hh"
38
39#include "CLG_log.h"
40
41namespace blender {
42
43static CLG_LogRef LOG = {"io.fbx"};
44
45namespace io::fbx {
46
49 const ufbx_scene &fbx;
51 std::string base_dir;
53
54 FbxImportContext(Main *main, const ufbx_scene *fbx, const FBXImportParams &params)
56 {
57 char basedir[FILE_MAX];
58 BLI_path_split_dir_part(params.filepath, basedir, sizeof(basedir));
59 base_dir = basedir;
60
61 ufbx_transform root_tr;
62 root_tr.translation = ufbx_zero_vec3;
63 root_tr.rotation = this->fbx.metadata.root_rotation;
64 root_tr.scale.x = root_tr.scale.y = root_tr.scale.z = this->fbx.metadata.root_scale;
65 this->mapping.global_conv_matrix = ufbx_transform_to_matrix(&root_tr);
66
67#ifdef FBX_DEBUG_PRINT
68 std::string debug_file_path = params.filepath;
69 debug_file_path = debug_file_path.substr(0, debug_file_path.size() - 4) + "-dbg-b.txt";
70 g_debug_file = BLI_fopen(debug_file_path.c_str(), "wb");
71#endif
72 }
73
75 {
76#ifdef FBX_DEBUG_PRINT
77 if (g_debug_file) {
78 fclose(g_debug_file);
79 }
80#endif
81 }
82
83 void import_globals(Scene *scene) const;
84 void import_materials();
85 void import_meshes();
86 void import_cameras();
87 void import_lights();
88 void import_empties();
89 void import_armatures();
90 void import_animation(double fps);
91
92 void setup_hierarchy();
93};
94
96{
97 /* Set scene frame-rate to that of FBX file. */
98 double fps = this->fbx.settings.frames_per_second;
99 scene->r.frs_sec = roundf(fps);
100 scene->r.frs_sec_base = scene->r.frs_sec / fps;
101}
102
104{
105 for (const ufbx_material *fmat : this->fbx.materials) {
106 Material *mat = nullptr;
107 /* Check if a material with this name already exists in the main database */
109 mat = (Material *)BKE_libblock_find_name(this->bmain, ID_MA, fmat->name.data);
110 }
111
112 if (mat == nullptr) {
113 mat = io::fbx::import_material(this->bmain, this->base_dir, *fmat);
114 if (this->params.use_custom_props) {
115 read_custom_properties(fmat->props, mat->id, this->params.props_enum_as_string);
116 }
117 }
118 this->mapping.mat_to_material.add(fmat, mat);
119 }
120}
121
123{
124 io::fbx::import_meshes(*this->bmain, this->fbx, this->mapping, this->params);
125}
126
127static bool should_import_camera(const ufbx_scene &fbx, const ufbx_camera *camera)
128{
129 BLI_assert(camera->instances.count > 0);
130 const ufbx_node *node = camera->instances[0];
131 /* Files produced by MotionBuilder have several cameras at the root,
132 * which just map to "viewports" and should not get imported. */
133 if (node->node_depth == 1 && node->children.count == 0 &&
134 STREQ("MotionBuilder", fbx.metadata.original_application.name.data))
135 {
136 if (STREQ(node->name.data, camera->name.data)) {
137 if (STREQ("Producer Perspective", node->name.data) ||
138 STREQ("Producer Front", node->name.data) || STREQ("Producer Back", node->name.data) ||
139 STREQ("Producer Right", node->name.data) || STREQ("Producer Left", node->name.data) ||
140 STREQ("Producer Top", node->name.data) || STREQ("Producer Bottom", node->name.data))
141 {
142 return false;
143 }
144 }
145 }
146 return true;
147}
148
150{
151 for (const ufbx_camera *fcam : this->fbx.cameras) {
152 if (fcam->instances.count == 0) {
153 continue; /* Ignore if not used by any objects. */
154 }
155 if (!should_import_camera(this->fbx, fcam)) {
156 continue;
157 }
158 const ufbx_node *node = fcam->instances[0];
159
160 Camera *bcam = BKE_camera_add(this->bmain, get_fbx_name(fcam->name, "Camera"));
161 if (this->params.use_custom_props) {
162 read_custom_properties(fcam->props, bcam->id, this->params.props_enum_as_string);
163 }
164
165 bcam->type = fcam->projection_mode == UFBX_PROJECTION_MODE_ORTHOGRAPHIC ? CAM_ORTHO :
166 CAM_PERSP;
167 bcam->dof.focus_distance = ufbx_find_real(&fcam->props, "FocusDistance", 10.0f) *
168 this->fbx.metadata.geometry_scale * this->fbx.metadata.root_scale;
169 if (ufbx_find_bool(&fcam->props, "UseDepthOfField", false)) {
170 bcam->dof.flag |= CAM_DOF_ENABLED;
171 }
172 bcam->lens = fcam->focal_length_mm;
173 constexpr double m_to_in = 0.0393700787;
174 bcam->sensor_x = fcam->film_size_inch.x / m_to_in;
175 bcam->sensor_y = fcam->film_size_inch.y / m_to_in;
176
177 /* Note: do not use `fcam->orthographic_extent` to match Python importer behavior, which was
178 * not taking ortho units into account. */
179 bcam->ortho_scale = ufbx_find_real(&fcam->props, "OrthoZoom", 1.0);
180
181 bcam->shiftx = ufbx_find_real(&fcam->props, "FilmOffsetX", 0.0) / (m_to_in * bcam->sensor_x);
182 bcam->shifty = ufbx_find_real(&fcam->props, "FilmOffsetY", 0.0) / (m_to_in * bcam->sensor_x);
183 bcam->clip_start = fcam->near_plane * this->fbx.metadata.root_scale;
184 bcam->clip_end = fcam->far_plane * this->fbx.metadata.root_scale;
185
187 obj->data = id_cast<ID *>(bcam);
188 if (!node->visible) {
189 obj->visibility_flag |= OB_HIDE_VIEWPORT;
190 }
191 if (this->params.use_custom_props) {
192 read_custom_properties(node->props, obj->id, this->params.props_enum_as_string);
193 }
195 this->mapping.el_to_object.add(&node->element, obj);
196 this->mapping.imported_objects.add(obj);
197 }
198}
199
201{
202 for (const ufbx_light *flight : this->fbx.lights) {
203 if (flight->instances.count == 0) {
204 continue; /* Ignore if not used by any objects. */
205 }
206 const ufbx_node *node = flight->instances[0];
207
208 Light *lamp = BKE_light_add(this->bmain, get_fbx_name(flight->name, "Light"));
209 if (this->params.use_custom_props) {
210 read_custom_properties(flight->props, lamp->id, this->params.props_enum_as_string);
211 }
212 switch (flight->type) {
213 case UFBX_LIGHT_POINT:
214 lamp->type = LA_LOCAL;
215 break;
216 case UFBX_LIGHT_DIRECTIONAL:
217 lamp->type = LA_SUN;
218 break;
219 case UFBX_LIGHT_SPOT:
220 lamp->type = LA_SPOT;
221 lamp->spotsize = DEG2RAD(flight->outer_angle);
222 lamp->spotblend = 1.0f - flight->inner_angle / flight->outer_angle;
223 break;
224 default:
225 break;
226 }
227
228 lamp->r = flight->color.x;
229 lamp->g = flight->color.y;
230 lamp->b = flight->color.z;
231 lamp->energy = flight->intensity;
232 lamp->exposure = ufbx_find_real(&flight->props, "Exposure", 0.0);
233 lamp->mode = flight->cast_shadows ? (lamp->mode | LA_SHADOW) : (lamp->mode & ~LA_SHADOW);
234
236 obj->data = id_cast<ID *>(lamp);
237 if (!node->visible) {
238 obj->visibility_flag |= OB_HIDE_VIEWPORT;
239 }
240
241 if (this->params.use_custom_props) {
242 read_custom_properties(node->props, obj->id, this->params.props_enum_as_string);
243 }
245 this->mapping.el_to_object.add(&node->element, obj);
246 this->mapping.imported_objects.add(obj);
247 }
248}
249
251{
252 io::fbx::import_armatures(*this->bmain, this->fbx, this->mapping, this->params);
253}
254
256{
257 /* Create empties for fbx nodes. */
258 for (const ufbx_node *node : this->fbx.nodes) {
259 /* Ignore root, bones and nodes for which we have created objects already. */
260 if (node->is_root || this->mapping.node_is_blender_bone.contains(node) ||
261 this->mapping.el_to_object.contains(&node->element))
262 {
263 continue;
264 }
265 /* Ignore nodes at root for cameras (normally already imported, except for ignored cameras)
266 * and camera switchers. */
267 if (ELEM(node->attrib_type, UFBX_ELEMENT_CAMERA, UFBX_ELEMENT_CAMERA_SWITCHER) &&
268 node->node_depth == 1 && node->children.count == 0)
269 {
270 continue;
271 }
273 obj->data = nullptr;
274 if (!node->visible) {
275 obj->visibility_flag |= OB_HIDE_VIEWPORT;
276 }
277 if (this->params.use_custom_props) {
278 read_custom_properties(node->props, obj->id, this->params.props_enum_as_string);
279 }
281 this->mapping.el_to_object.add(&node->element, obj);
282 this->mapping.imported_objects.add(obj);
283 }
284}
285
287{
288 if (this->params.use_anim) {
290 *this->bmain, this->fbx, this->mapping, fps, this->params.anim_offset);
291 }
292}
293
295{
296 for (const auto &item : this->mapping.el_to_object.items()) {
297 if (item.value->parent != nullptr) {
298 continue; /* Parent is already set up (e.g. armature). */
299 }
300 const ufbx_node *node = ufbx_as_node(item.key);
301 if (node == nullptr) {
302 continue;
303 }
304 if (node->parent) {
305 Object *obj_par = this->mapping.el_to_object.lookup_default(&node->parent->element, nullptr);
306 if (!ELEM(obj_par, nullptr, item.value)) {
307 item.value->parent = obj_par;
308 }
309 }
310 }
311}
312
313static void fbx_task_run_fn(void * /* user */,
314 ufbx_thread_pool_context ctx,
315 uint32_t /* group */,
316 uint32_t start_index,
317 uint32_t count)
318{
319 threading::parallel_for_each(IndexRange(start_index, count), [&](const int64_t index) {
320 ufbx_thread_pool_run_task(ctx, index);
321 });
322}
323
324static void fbx_task_wait_fn(void * /* user */,
325 ufbx_thread_pool_context /* ctx */,
326 uint32_t /* group */,
327 uint32_t /* max_index */)
328{
329 /* Empty implementation; #fbx_task_run_fn already waits for the tasks.
330 * This means that only one fbx "task group" is effectively scheduled at once. */
331}
332
333void importer_main(Main *bmain, Scene *scene, ViewLayer *view_layer, const FBXImportParams &params)
334{
335 FILE *file = BLI_fopen(params.filepath, "rb");
336 if (!file) {
337 CLOG_ERROR(&LOG, "Failed to open FBX file '%s'", params.filepath);
338 BKE_reportf(params.reports, RPT_ERROR, "FBX Import: Cannot open file '%s'", params.filepath);
339 return;
340 }
341
342 ufbx_load_opts opts = {};
343 opts.filename.data = params.filepath;
344 opts.filename.length = strlen(params.filepath);
345 opts.evaluate_skinning = false;
346 opts.evaluate_caches = false;
347 opts.load_external_files = false;
348 opts.clean_skin_weights = true;
349 opts.use_blender_pbr_material = true;
350
351 opts.geometry_transform_handling = UFBX_GEOMETRY_TRANSFORM_HANDLING_MODIFY_GEOMETRY;
352 opts.pivot_handling = UFBX_PIVOT_HANDLING_ADJUST_TO_ROTATION_PIVOT;
353
354 opts.space_conversion = UFBX_SPACE_CONVERSION_ADJUST_TRANSFORMS;
355 opts.target_axes.right = UFBX_COORDINATE_AXIS_POSITIVE_X;
356 opts.target_axes.up = UFBX_COORDINATE_AXIS_POSITIVE_Z;
357 opts.target_axes.front = UFBX_COORDINATE_AXIS_NEGATIVE_Y;
358 opts.target_unit_meters = 1.0f / params.global_scale;
359
360 opts.target_camera_axes.right = UFBX_COORDINATE_AXIS_POSITIVE_X;
361 opts.target_camera_axes.up = UFBX_COORDINATE_AXIS_POSITIVE_Y;
362 opts.target_camera_axes.front = UFBX_COORDINATE_AXIS_POSITIVE_Z;
363 opts.target_light_axes.right = UFBX_COORDINATE_AXIS_POSITIVE_X;
364 opts.target_light_axes.up = UFBX_COORDINATE_AXIS_POSITIVE_Y;
365 opts.target_light_axes.front = UFBX_COORDINATE_AXIS_POSITIVE_Z;
366
367 /* Setup ufbx threading to go through our own task system. */
368 opts.thread_opts.pool.run_fn = fbx_task_run_fn;
369 opts.thread_opts.pool.wait_fn = fbx_task_wait_fn;
370
371 ufbx_error fbx_error;
372 ufbx_scene *fbx = ufbx_load_stdio(file, &opts, &fbx_error);
373 fclose(file);
374
375 if (!fbx) {
377 "Failed to import FBX file '%s': '%s'\n",
378 params.filepath,
379 fbx_error.description.data);
380 BKE_reportf(params.reports,
381 RPT_ERROR,
382 "FBX Import: Cannot import file '%s': '%s'",
383 params.filepath,
384 fbx_error.description.data);
385 return;
386 }
387
389 if (!ID_IS_EDITABLE(lc->collection)) {
390 BKE_report(params.reports,
392 "Could not find an editable collection in current scene, imported data will not be "
393 "instantiated");
394 }
395 //@TODO: do we need to sort objects by name? (faster to create within blender)
396
397 FbxImportContext ctx(bmain, fbx, params);
398 ctx.import_globals(scene);
399
400#ifdef FBX_DEBUG_PRINT
401 {
402 fprintf(g_debug_file, "Initial NODE local matrices:\n");
404 for (const ufbx_node *node : ctx.fbx.nodes) {
405 if (node->is_root) {
406 continue;
407 }
408 nodes.append(node);
409 }
410 std::ranges::sort(nodes, [](const ufbx_node *a, const ufbx_node *b) {
411 int ncmp = strcmp(a->name.data, b->name.data);
412 if (ncmp != 0) {
413 return ncmp < 0;
414 }
415 return a->attrib_type > b->attrib_type;
416 });
417 for (const ufbx_node *node : nodes) {
418 ufbx_matrix mtx = ufbx_matrix_mul(node->node_depth < 2 ? &node->node_to_world :
419 &node->node_to_parent,
420 &node->geometry_to_node);
421 fprintf(g_debug_file, "init NODE %s self.matrix:\n", node->name.data);
422 print_matrix(mtx);
423 }
424 fprintf(g_debug_file, "\n");
425 }
426#endif
427
428 ctx.import_materials();
429 ctx.import_armatures();
430 ctx.import_meshes();
431 ctx.import_cameras();
432 ctx.import_lights();
433 ctx.import_empties();
434 ctx.import_animation(scene->frames_per_second());
435 ctx.setup_hierarchy();
436
437 ufbx_free_scene(fbx);
438
439 /* Add objects to collection. */
440 for (Object *obj : ctx.mapping.imported_objects) {
442 }
443
444 /* Select objects, sync layers etc. */
445 BKE_view_layer_base_deselect_all(*bmain, scene, view_layer);
446 BKE_view_layer_synced_ensure(*bmain, scene, view_layer);
447 bool has_instantiated_object = false;
448 bool has_uninstantiated_object = false;
449 for (Object *obj : ctx.mapping.imported_objects) {
450 Base *base = BKE_view_layer_base_find(view_layer, obj);
451 if (!base) {
452 /* Object not instantiated in current viewlayer. */
453 has_uninstantiated_object = true;
454 continue;
455 }
456 has_instantiated_object = true;
458
461 DEG_id_tag_update_ex(bmain, &obj->id, flags);
462 }
463
464 if (has_instantiated_object && has_uninstantiated_object) {
465 CLOG_ERROR(&LOG, "Some imported objects were not instantiated, while others were");
466 }
467
469
472}
473
474} // namespace io::fbx
475} // namespace blender
Camera data-block and utility functions.
General operations, lookup, etc. for blender lights.
General operations, lookup, etc. for blender objects.
File and directory operations.
#define DEG2RAD(_deg)
#define FILE_MAX
#define CLOG_ERROR(clg_ref,...)
Definition CLG_log.h:188
#define ID_IS_EDITABLE(_id)
Definition DNA_ID.h:708
Object groups, one object can be in many groups at once.
#define ELEM(...)
#define STREQ(a, b)
constexpr IndexRange()=default
#define roundf(x)
#define main()
void camera(KernelGlobals &kg, const ShadingData &sd, float3 &outview, float &outdepth, float &outdist)
static void fbx_task_run_fn(void *, ufbx_thread_pool_context ctx, uint32_t, uint32_t start_index, uint32_t count)
const char * get_fbx_name(const ufbx_string &name, const char *def)
static bool should_import_camera(const ufbx_scene &fbx, const ufbx_camera *camera)
void read_custom_properties(const ufbx_props &props, ID &id, bool enums_as_strings)
void node_matrix_to_obj(const ufbx_node *node, Object *obj, const FbxElementMapping &mapping)
Material * import_material(Main *bmain, const std::string &base_dir, const ufbx_material &fmat)
void importer_main(Main *bmain, Scene *scene, ViewLayer *view_layer, const FBXImportParams &params)
void import_animations(Main &bmain, const ufbx_scene &fbx, const FbxElementMapping &mapping, const double fps, const float anim_offset)
static void fbx_task_wait_fn(void *, ufbx_thread_pool_context, uint32_t, uint32_t)
void import_armatures(Main &bmain, const ufbx_scene &fbx, FbxElementMapping &mapping, const FBXImportParams &params)
void import_meshes(Main &bmain, const ufbx_scene &fbx, FbxElementMapping &mapping, const FBXImportParams &params)
void parallel_for_each(Range &&range, const Function &function)
Definition BLI_task.hh:31
BMesh Iterators.
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
__int64 int64_t
Definition BKE_text.h:90
LayerCollection * BKE_layer_collection_get_active_editable(ViewLayer *view_layer)
void BKE_view_layer_base_select_and_set_active(ViewLayer *view_layer, Base *selbase)
ID * BKE_libblock_find_name(Main *bmain, short type, const char *name, const std::optional< Library * > lib=std::nullopt) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
Definition lib_id.cc:1808
@ RPT_WARNING
Definition BKE_report.hh:40
FILE * BLI_fopen(const char *filepath, const char *mode) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
unsigned int uint32_t
Definition BKE_text.h:81
void void BLI_path_split_dir_part(const char *filepath, char *dir, size_t dir_maxncpy) ATTR_NONNULL(1
void DEG_id_tag_update_ex(Main *bmain, ID *id, unsigned int flags)
void DEG_id_tag_update(ID *id, unsigned int flags)
void BKE_report(ReportList *reports, eReportType type, const char *message)
Definition report.cc:162
struct Camera * BKE_camera_add(struct Main *bmain, const char *name)
bool BKE_view_layer_synced_ensure(const Main &bmain, const Scene *scene, ViewLayer *view_layer)
bool BKE_collection_object_add(Main *bmain, Collection *collection, Object *ob)
void BKE_view_layer_base_deselect_all(const Main &bmain, const Scene *scene, ViewLayer *view_layer)
void BKE_reportf(ReportList *reports, eReportType type, const char *format,...) ATTR_PRINTF_FORMAT(3
Definition report.cc:191
Light * BKE_light_add(Main *bmain, const char *name) ATTR_WARN_UNUSED_RESULT
@ ID_RECALC_ANIMATION
Definition DNA_ID.h:1077
@ ID_RECALC_TRANSFORM
Definition DNA_ID.h:1054
@ ID_RECALC_SYNC_TO_EVAL
Definition DNA_ID.h:1118
@ ID_RECALC_GEOMETRY
Definition DNA_ID.h:1074
@ ID_RECALC_BASE_FLAGS
Definition DNA_ID.h:1104
Base * BKE_view_layer_base_find(ViewLayer *view_layer, Object *ob)
static CLG_LogRef LOG
Definition logging.cpp:12
void DEG_relations_tag_update(Main *bmain)
Object * BKE_object_add_only_object(Main *bmain, ObjectType type, const char *name) ATTR_RETURNS_NONNULL
Definition object.cc:2265
eFBXMtlNameCollisionMode mtl_name_collision_mode
Definition IO_fbx.hh:41
ReportList * reports
Definition IO_fbx.hh:53
char filepath[FILE_MAX]
Definition IO_fbx.hh:39
struct Collection * collection
struct RenderData r
Map< const ufbx_material *, Material * > mat_to_material
Map< const ufbx_element *, Object * > el_to_object
FbxImportContext(Main *main, const ufbx_scene *fbx, const FBXImportParams &params)
Definition fbx_import.cc:54
void import_globals(Scene *scene) const
Definition fbx_import.cc:95
const FBXImportParams & params
Definition fbx_import.cc:50