Blender V4.5
obj_exporter.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include <cstdio>
10#include <memory>
11#include <system_error>
12
13#include "BKE_context.hh"
14#include "BKE_lib_id.hh"
15#include "BKE_report.hh"
16#include "BKE_scene.hh"
17
18#include "BLI_path_utils.hh"
19#include "BLI_string.h"
20#include "BLI_task.hh"
21#include "BLI_vector.hh"
22
24
26#include "DNA_scene_types.h"
27
28#include "ED_object.hh"
29
30#include "obj_export_mesh.hh"
31#include "obj_export_nurbs.hh"
32#include "obj_exporter.hh"
33
35
36#include "CLG_log.h"
37static CLG_LogRef LOG = {"io.obj"};
38
39namespace blender::io::obj {
40
42 const eEvaluationMode eval_mode,
43 Collection *collection)
44{
45 Scene *scene = CTX_data_scene(C);
46 Main *bmain = CTX_data_main(C);
47 ViewLayer *view_layer = CTX_data_view_layer(C);
48
49 /* If a collection was provided, use it. */
50 if (collection) {
51 depsgraph_ = DEG_graph_new(bmain, scene, view_layer, eval_mode);
52 needs_free_ = true;
53 DEG_graph_build_from_collection(depsgraph_, collection);
54 BKE_scene_graph_evaluated_ensure(depsgraph_, bmain);
55 }
56 else if (eval_mode == DAG_EVAL_RENDER) {
57 depsgraph_ = DEG_graph_new(bmain, scene, view_layer, eval_mode);
58 needs_free_ = true;
60 BKE_scene_graph_evaluated_ensure(depsgraph_, bmain);
61 }
62 else {
64 needs_free_ = false;
65 }
66}
67
69{
70 if (needs_free_) {
71 DEG_graph_free(depsgraph_);
72 }
73}
74
76{
77 return depsgraph_;
78}
79
84
85static void print_exception_error(const std::system_error &ex)
86{
87 CLOG_ERROR(&LOG, "[%s] %s", ex.code().category().name(), ex.what());
88}
89
90static bool is_curve_nurbs_compatible(const Nurb *nurb)
91{
92 while (nurb) {
93 if (nurb->type == CU_BEZIER || nurb->pntsv != 1) {
94 return false;
95 }
96 nurb = nurb->next;
97 }
98 return true;
99}
100
106std::pair<Vector<std::unique_ptr<OBJMesh>>, Vector<std::unique_ptr<OBJCurve>>>
107filter_supported_objects(Depsgraph *depsgraph, const OBJExportParams &export_params)
108{
109 Vector<std::unique_ptr<OBJMesh>> r_exportable_meshes;
110 Vector<std::unique_ptr<OBJCurve>> r_exportable_nurbs;
111 DEGObjectIterSettings deg_iter_settings{};
112 deg_iter_settings.depsgraph = depsgraph;
113 deg_iter_settings.flags = DEG_ITER_OBJECT_FLAG_LINKED_DIRECTLY |
116 DEG_OBJECT_ITER_BEGIN (&deg_iter_settings, object) {
117 if (export_params.export_selected_objects && !(object->base_flag & BASE_SELECTED)) {
118 continue;
119 }
120 switch (object->type) {
121 case OB_SURF:
122 /* Evaluated surface objects appear as mesh objects from the iterator. */
123 break;
124 case OB_MESH:
125 r_exportable_meshes.append(std::make_unique<OBJMesh>(depsgraph, export_params, object));
126 break;
127 case OB_CURVES_LEGACY: {
128 Curve *curve = static_cast<Curve *>(object->data);
129 Nurb *nurb{static_cast<Nurb *>(curve->nurb.first)};
130 if (!nurb) {
131 /* An empty curve. Not yet supported to export these as meshes. */
132 if (export_params.export_curves_as_nurbs) {
133 r_exportable_nurbs.append(
134 std::make_unique<OBJCurve>(depsgraph, export_params, object));
135 }
136 break;
137 }
138 if (export_params.export_curves_as_nurbs && is_curve_nurbs_compatible(nurb)) {
139 /* Export in parameter form: control points. */
140 r_exportable_nurbs.append(std::make_unique<OBJCurve>(depsgraph, export_params, object));
141 }
142 else {
143 /* Export in mesh form: edges and vertices. */
144 r_exportable_meshes.append(std::make_unique<OBJMesh>(depsgraph, export_params, object));
145 }
146 break;
147 }
148 default:
149 /* Other object types are not supported. */
150 break;
151 }
152 }
154 return {std::move(r_exportable_meshes), std::move(r_exportable_nurbs)};
155}
156
157static void write_mesh_objects(const Span<std::unique_ptr<OBJMesh>> exportable_as_mesh,
158 OBJWriter &obj_writer,
159 MTLWriter *mtl_writer,
160 const OBJExportParams &export_params)
161{
162 /* Parallelization is over meshes/objects, which means
163 * we have to have the output text buffer for each object,
164 * and write them all into the file at the end. */
165 size_t count = exportable_as_mesh.size();
167
168 /* Serial: gather material indices, ensure normals & edges. */
169 Vector<Vector<int>> mtlindices;
170 if (mtl_writer) {
171 if (export_params.export_materials) {
172 obj_writer.write_mtllib_name(mtl_writer->mtl_file_path());
173 }
174 mtlindices.reserve(count);
175 }
176 for (const auto &obj_mesh : exportable_as_mesh) {
177 OBJMesh &obj = *obj_mesh;
178 if (mtl_writer) {
179 mtlindices.append(mtl_writer->add_materials(obj));
180 }
181 }
182
183 /* Parallel over meshes: store normal coords & indices, uv coords and indices. */
185 for (const int i : range) {
186 OBJMesh &obj = *exportable_as_mesh[i];
187 if (export_params.export_normals) {
188 obj.store_normal_coords_and_indices();
189 }
190 if (export_params.export_uv) {
191 obj.store_uv_coords_and_indices();
192 }
193 }
194 });
195
196 /* Serial: calculate index offsets; these are sequentially added
197 * over all meshes, and requite normal/uv indices to be calculated. */
198 Vector<IndexOffsets> index_offsets;
199 index_offsets.reserve(count);
200 IndexOffsets offsets{0, 0, 0};
201 for (const auto &obj_mesh : exportable_as_mesh) {
202 OBJMesh &obj = *obj_mesh;
203 index_offsets.append(offsets);
204 offsets.vertex_offset += obj.tot_vertices();
205 offsets.uv_vertex_offset += obj.tot_uv_vertices();
206 offsets.normal_offset += obj.get_normal_coords().size();
207 }
208
209 /* Parallel over meshes: main result writing. */
211 for (const int i : range) {
212 OBJMesh &obj = *exportable_as_mesh[i];
213 auto &fh = buffers[i];
214
215 obj_writer.write_object_name(fh, obj);
216 obj_writer.write_vertex_coords(fh, obj, export_params.export_colors);
217
218 if (obj.tot_faces() > 0) {
219 if (export_params.export_smooth_groups) {
220 obj.calc_smooth_groups(export_params.smooth_groups_bitflags);
221 }
222 if (export_params.export_materials) {
223 obj.calc_face_order();
224 }
225 if (export_params.export_normals) {
226 obj_writer.write_normals(fh, obj);
227 }
228 if (export_params.export_uv) {
229 obj_writer.write_uv_coords(fh, obj);
230 }
231 /* This function takes a 0-indexed slot index for the obj_mesh object and
232 * returns the material name that we are using in the `.obj` file for it. */
233 const auto *obj_mtlindices = mtlindices.is_empty() ? nullptr : &mtlindices[i];
234 auto matname_fn = [&](int s) -> const char * {
235 if (!obj_mtlindices || s < 0 || s >= obj_mtlindices->size()) {
236 return nullptr;
237 }
238 return mtl_writer->mtlmaterial_name((*obj_mtlindices)[s]);
239 };
240 obj_writer.write_face_elements(fh, index_offsets[i], obj, matname_fn);
241 }
242 obj_writer.write_edges_indices(fh, index_offsets[i], obj);
243
244 /* Nothing will need this object's data after this point, release
245 * various arrays here. */
246 obj.clear();
247 }
248 });
249
250 /* Write all the object text buffers into the output file. */
251 FILE *f = obj_writer.get_outfile();
252 for (auto &b : buffers) {
253 b.write_to_file(f);
254 }
255}
256
260static void write_nurbs_curve_objects(const Span<std::unique_ptr<OBJCurve>> exportable_as_nurbs,
261 const OBJWriter &obj_writer)
262{
263 FormatHandler fh;
264 /* #OBJCurve doesn't have any dynamically allocated memory, so it's fine
265 * to wait for #blender::Vector to clean the objects up. */
266 for (const std::unique_ptr<OBJCurve> &obj_curve : exportable_as_nurbs) {
267 obj_writer.write_nurbs_curve(fh, *obj_curve);
268 }
269 fh.write_to_file(obj_writer.get_outfile());
270}
271
272void export_frame(Depsgraph *depsgraph, const OBJExportParams &export_params, const char *filepath)
273{
274 std::unique_ptr<OBJWriter> frame_writer = nullptr;
275 try {
276 frame_writer = std::make_unique<OBJWriter>(filepath, export_params);
277 }
278 catch (const std::system_error &ex) {
280 BKE_reportf(export_params.reports, RPT_ERROR, "OBJ Export: Cannot open file '%s'", filepath);
281 return;
282 }
283 if (!frame_writer) {
284 BLI_assert_msg(false, "File should be writable by now.");
285 return;
286 }
287 std::unique_ptr<MTLWriter> mtl_writer = nullptr;
288 if (export_params.export_materials || export_params.export_material_groups) {
289 try {
290 mtl_writer = std::make_unique<MTLWriter>(filepath, export_params.export_materials);
291 }
292 catch (const std::system_error &ex) {
294 BKE_reportf(export_params.reports,
296 "OBJ Export: Cannot create mtl file for '%s'",
297 filepath);
298 }
299 }
300
301 frame_writer->write_header();
302
303 auto [exportable_as_mesh, exportable_as_nurbs] = filter_supported_objects(depsgraph,
304 export_params);
305
306 write_mesh_objects(exportable_as_mesh, *frame_writer, mtl_writer.get(), export_params);
307 if (mtl_writer && export_params.export_materials) {
308 mtl_writer->write_header(export_params.blen_filepath);
309 char dest_dir[FILE_MAX];
310 if (export_params.file_base_for_tests[0] == '\0') {
311 BLI_path_split_dir_part(export_params.filepath, dest_dir, sizeof(dest_dir));
312 }
313 else {
314 STRNCPY(dest_dir, export_params.file_base_for_tests);
315 }
316 BLI_path_slash_native(dest_dir);
317 BLI_path_normalize(dest_dir);
318 mtl_writer->write_materials(export_params.blen_filepath,
319 export_params.path_mode,
320 dest_dir,
321 export_params.export_pbr_extensions);
322 }
323 write_nurbs_curve_objects(exportable_as_nurbs, *frame_writer);
324}
325
326bool append_frame_to_filename(const char *filepath,
327 const int frame,
328 char r_filepath_with_frames[1024])
329{
330 BLI_strncpy(r_filepath_with_frames, filepath, FILE_MAX);
331 BLI_path_extension_strip(r_filepath_with_frames);
332 BLI_path_frame(r_filepath_with_frames, FILE_MAX, frame, 4);
333 return BLI_path_extension_replace(r_filepath_with_frames, FILE_MAX, ".obj");
334}
335
336void exporter_main(bContext *C, const OBJExportParams &export_params)
337{
339
340 Collection *collection = nullptr;
341 if (export_params.collection[0]) {
342 Main *bmain = CTX_data_main(C);
343 collection = reinterpret_cast<Collection *>(
344 BKE_libblock_find_name(bmain, ID_GR, export_params.collection));
345 if (!collection) {
346 BKE_reportf(export_params.reports,
347 RPT_ERROR,
348 "OBJ Export: Unable to find collection '%s'",
349 export_params.collection);
350 return;
351 }
352 }
353
354 OBJDepsgraph obj_depsgraph(C, export_params.export_eval_mode, collection);
355 Scene *scene = DEG_get_input_scene(obj_depsgraph.get());
356 const char *filepath = export_params.filepath;
357
358 /* Single frame export, i.e. no animation. */
359 if (!export_params.export_animation) {
360 fmt::println("Writing to {}", filepath);
361 export_frame(obj_depsgraph.get(), export_params, filepath);
362 return;
363 }
364
365 char filepath_with_frames[FILE_MAX];
366 /* Used to reset the Scene to its original state. */
367 const int original_frame = scene->r.cfra;
368
369 for (int frame = export_params.start_frame; frame <= export_params.end_frame; frame++) {
370 const bool filepath_ok = append_frame_to_filename(filepath, frame, filepath_with_frames);
371 if (!filepath_ok) {
372 CLOG_ERROR(&LOG, "File Path too long: %s", filepath_with_frames);
373 return;
374 }
375
376 scene->r.cfra = frame;
377 obj_depsgraph.update_for_newframe();
378 fmt::println("Writing to {}", filepath_with_frames);
379 export_frame(obj_depsgraph.get(), export_params, filepath_with_frames);
380 }
381 scene->r.cfra = original_frame;
382}
383} // namespace blender::io::obj
Depsgraph * CTX_data_ensure_evaluated_depsgraph(const bContext *C)
Scene * CTX_data_scene(const bContext *C)
Main * CTX_data_main(const bContext *C)
ViewLayer * CTX_data_view_layer(const bContext *C)
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:1679
void BKE_reportf(ReportList *reports, eReportType type, const char *format,...) ATTR_PRINTF_FORMAT(3
void BKE_scene_graph_evaluated_ensure(Depsgraph *depsgraph, Main *bmain)
Definition scene.cc:2623
void BKE_scene_graph_update_for_newframe(Depsgraph *depsgraph)
Definition scene.cc:2697
#define BLI_assert_msg(a, msg)
Definition BLI_assert.h:53
bool bool BLI_path_extension_strip(char *path) ATTR_NONNULL(1)
#define FILE_MAX
bool BLI_path_extension_replace(char *path, size_t path_maxncpy, const char *ext) ATTR_NONNULL(1
void BLI_path_slash_native(char *path) ATTR_NONNULL(1)
int BLI_path_normalize(char *path) ATTR_NONNULL(1)
void void BLI_path_split_dir_part(const char *filepath, char *dir, size_t dir_maxncpy) ATTR_NONNULL(1
bool BLI_path_frame(char *path, size_t path_maxncpy, int frame, int digits) ATTR_NONNULL(1)
char * STRNCPY(char(&dst)[N], const char *src)
Definition BLI_string.h:688
char * BLI_strncpy(char *__restrict dst, const char *__restrict src, size_t dst_maxncpy) ATTR_NONNULL(1
#define CLOG_ERROR(clg_ref,...)
Definition CLG_log.h:182
eEvaluationMode
@ DAG_EVAL_RENDER
Depsgraph * DEG_graph_new(Main *bmain, Scene *scene, ViewLayer *view_layer, eEvaluationMode mode)
Definition depsgraph.cc:278
void DEG_graph_free(Depsgraph *graph)
Definition depsgraph.cc:306
void DEG_graph_build_from_collection(Depsgraph *graph, Collection *collection)
void DEG_graph_build_for_all_objects(Depsgraph *graph)
#define DEG_OBJECT_ITER_BEGIN(settings_, instance_)
#define DEG_OBJECT_ITER_END
Scene * DEG_get_input_scene(const Depsgraph *graph)
@ DEG_ITER_OBJECT_FLAG_LINKED_DIRECTLY
@ DEG_ITER_OBJECT_FLAG_VISIBLE
@ DEG_ITER_OBJECT_FLAG_DUPLI
@ DEG_ITER_OBJECT_FLAG_LINKED_VIA_SET
@ ID_GR
Object groups, one object can be in many groups at once.
@ CU_BEZIER
@ OB_MODE_OBJECT
@ OB_SURF
@ OB_MESH
@ OB_CURVES_LEGACY
#define BASE_SELECTED(v3d, base)
#define C
Definition RandGen.cpp:29
BPy_StructRNA * depsgraph
void append(const T &value)
bool is_empty() const
void reserve(const int64_t min_capacity)
Vector< int > add_materials(const OBJMesh &mesh_to_export)
const char * mtlmaterial_name(int index)
OBJDepsgraph(const bContext *C, eEvaluationMode eval_mode, Collection *collection)
void write_normals(FormatHandler &fh, OBJMesh &obj_mesh_data)
void write_mtllib_name(StringRefNull mtl_filepath) const
void write_uv_coords(FormatHandler &fh, OBJMesh &obj_mesh_data) const
void write_nurbs_curve(FormatHandler &fh, const OBJCurve &obj_nurbs_data) const
void write_face_elements(FormatHandler &fh, const IndexOffsets &offsets, const OBJMesh &obj_mesh_data, FunctionRef< const char *(int)> matname_fn)
void write_vertex_coords(FormatHandler &fh, const OBJMesh &obj_mesh_data, bool write_colors) const
void write_edges_indices(FormatHandler &fh, const IndexOffsets &offsets, const OBJMesh &obj_mesh_data) const
void write_object_name(FormatHandler &fh, const OBJMesh &obj_mesh_data) const
int count
#define LOG(severity)
Definition log.h:32
bool mode_set(bContext *C, eObjectMode mode)
static void print_exception_error(const std::system_error &ex)
bool append_frame_to_filename(const char *filepath, const int frame, char r_filepath_with_frames[1024])
static bool is_curve_nurbs_compatible(const Nurb *nurb)
static void write_mesh_objects(const Span< std::unique_ptr< OBJMesh > > exportable_as_mesh, OBJWriter &obj_writer, MTLWriter *mtl_writer, const OBJExportParams &export_params)
static void write_nurbs_curve_objects(const Span< std::unique_ptr< OBJCurve > > exportable_as_nurbs, const OBJWriter &obj_writer)
std::pair< Vector< std::unique_ptr< OBJMesh > >, Vector< std::unique_ptr< OBJCurve > > > filter_supported_objects(Depsgraph *depsgraph, const OBJExportParams &export_params)
void exporter_main(bContext *C, const OBJExportParams &export_params)
void export_frame(Depsgraph *depsgraph, const OBJExportParams &export_params, const char *filepath)
void parallel_for(const IndexRange range, const int64_t grain_size, const Function &function, const TaskSizeHints &size_hints=detail::TaskSizeHints_Static(1))
Definition BLI_task.hh:93
ListBase nurb
void * first
struct Nurb * next
short type
char collection[MAX_IDPROP_NAME]
eEvaluationMode export_eval_mode
const char * blen_filepath
char file_base_for_tests[FILE_MAX]
ReportList * reports
ePathReferenceMode path_mode
char filepath[FILE_MAX]
struct RenderData r
i
Definition text_draw.cc:230
char * buffers[2]