Blender V5.3
obj_export_file_writer.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 <algorithm>
10#include <system_error>
11
12#include "BKE_attribute.hh"
13#include "BKE_blender_version.h"
14#include "BKE_mesh.hh"
15
16#include "BLI_color_types.hh"
18#include "BLI_fileops.hh"
19#include "BLI_math_color_c.hh"
20#include "BLI_math_matrix.hh"
21#include "BLI_math_matrix_c.hh"
23#include "BLI_math_vector_c.hh"
24#include "BLI_path_utils.hh"
25#include "BLI_string.hh"
26#include "BLI_task.hh"
27
28#include "IO_path_util.hh"
29
30#include "obj_export_mesh.hh"
31#include "obj_export_mtl.hh"
32#include "obj_export_nurbs.hh"
33
35
36#include "CLG_log.h"
37
38namespace blender {
39
40static CLG_LogRef LOG = {"io.obj"};
41
42namespace io::obj {
52
53static const char *DEFORM_GROUP_DISABLED = "off";
54/* There is no deform group default name. Use what the user set in the UI. */
55
62static const char *MATERIAL_GROUP_DISABLED = "";
63
64OBJWriter::OBJWriter(const char *filepath, const OBJExportParams &export_params) noexcept(false)
65 : export_params_(export_params), outfile_path_(filepath), outfile_(nullptr)
66{
67 outfile_ = BLI_fopen(filepath, "wb");
68 if (!outfile_) {
69 throw std::system_error(errno, std::system_category(), "Cannot open file " + outfile_path_);
70 }
71}
73{
74 if (outfile_ && std::fclose(outfile_)) {
76 "Error: could not close file '%s' properly, it may be corrupted.",
77 outfile_path_.c_str());
78 }
79}
80
81void OBJWriter::write_vert_uv_normal_indices(FormatHandler &fh,
82 const IndexOffsets &offsets,
83 Span<int> vert_indices,
84 Span<int> uv_indices,
85 Span<int> normal_indices,
86 bool flip) const
87{
88 BLI_assert(vert_indices.size() == uv_indices.size() &&
89 vert_indices.size() == normal_indices.size());
90 const int vertex_offset = offsets.vertex_offset + 1;
91 const int uv_offset = offsets.uv_vertex_offset + 1;
92 const int normal_offset = offsets.normal_offset + 1;
93 const int n = vert_indices.size();
95 if (!flip) {
96 for (int j = 0; j < n; ++j) {
97 fh.write_obj_face_v_uv_normal(vert_indices[j] + vertex_offset,
98 uv_indices[j] + uv_offset,
99 normal_indices[j] + normal_offset);
100 }
101 }
102 else {
103 /* For a transform that is mirrored (negative scale on odd number of axes),
104 * we want to flip the face index order. Start from the same index, and
105 * then go backwards. Same logic in other write_*_indices functions below. */
106 for (int k = 0; k < n; ++k) {
107 int j = k == 0 ? 0 : n - k;
108 fh.write_obj_face_v_uv_normal(vert_indices[j] + vertex_offset,
109 uv_indices[j] + uv_offset,
110 normal_indices[j] + normal_offset);
111 }
112 }
114}
115
116void OBJWriter::write_vert_normal_indices(FormatHandler &fh,
117 const IndexOffsets &offsets,
118 Span<int> vert_indices,
119 Span<int> /*uv_indices*/,
120 Span<int> normal_indices,
121 bool flip) const
122{
123 BLI_assert(vert_indices.size() == normal_indices.size());
124 const int vertex_offset = offsets.vertex_offset + 1;
125 const int normal_offset = offsets.normal_offset + 1;
126 const int n = vert_indices.size();
127 fh.write_obj_face_begin();
128 if (!flip) {
129 for (int j = 0; j < n; ++j) {
130 fh.write_obj_face_v_normal(vert_indices[j] + vertex_offset,
131 normal_indices[j] + normal_offset);
132 }
133 }
134 else {
135 for (int k = 0; k < n; ++k) {
136 int j = k == 0 ? 0 : n - k;
137 fh.write_obj_face_v_normal(vert_indices[j] + vertex_offset,
138 normal_indices[j] + normal_offset);
139 }
140 }
141 fh.write_obj_face_end();
142}
143
144void OBJWriter::write_vert_uv_indices(FormatHandler &fh,
145 const IndexOffsets &offsets,
146 Span<int> vert_indices,
147 Span<int> uv_indices,
148 Span<int> /*normal_indices*/,
149 bool flip) const
150{
151 BLI_assert(vert_indices.size() == uv_indices.size());
152 const int vertex_offset = offsets.vertex_offset + 1;
153 const int uv_offset = offsets.uv_vertex_offset + 1;
154 const int n = vert_indices.size();
155 fh.write_obj_face_begin();
156 if (!flip) {
157 for (int j = 0; j < n; ++j) {
158 fh.write_obj_face_v_uv(vert_indices[j] + vertex_offset, uv_indices[j] + uv_offset);
159 }
160 }
161 else {
162 for (int k = 0; k < n; ++k) {
163 int j = k == 0 ? 0 : n - k;
164 fh.write_obj_face_v_uv(vert_indices[j] + vertex_offset, uv_indices[j] + uv_offset);
165 }
166 }
167 fh.write_obj_face_end();
168}
169
170void OBJWriter::write_vert_indices(FormatHandler &fh,
171 const IndexOffsets &offsets,
172 Span<int> vert_indices,
173 Span<int> /*uv_indices*/,
174 Span<int> /*normal_indices*/,
175 bool flip) const
176{
177 const int vertex_offset = offsets.vertex_offset + 1;
178 const int n = vert_indices.size();
179 fh.write_obj_face_begin();
180 if (!flip) {
181 for (int j = 0; j < n; ++j) {
182 fh.write_obj_face_v(vert_indices[j] + vertex_offset);
183 }
184 }
185 else {
186 for (int k = 0; k < n; ++k) {
187 int j = k == 0 ? 0 : n - k;
188 fh.write_obj_face_v(vert_indices[j] + vertex_offset);
189 }
190 }
191 fh.write_obj_face_end();
192}
193
195{
196 using namespace std::string_literals;
197 FormatHandler fh;
198 fh.write_string("# Blender "s + BKE_blender_version_string());
199 fh.write_string("# www.blender.org");
200 fh.write_to_file(outfile_);
201}
202
203void OBJWriter::write_mtllib_name(const StringRefNull mtl_filepath) const
204{
205 /* Split `.MTL` file path into parent directory and filename. */
206 char mtl_file_name[FILE_MAXFILE];
207 char mtl_dir_name[FILE_MAXDIR];
208 BLI_path_split_dir_file(mtl_filepath.data(),
209 mtl_dir_name,
210 sizeof(mtl_dir_name),
211 mtl_file_name,
212 sizeof(mtl_file_name));
213 FormatHandler fh;
214 fh.write_obj_mtllib(mtl_file_name);
215 fh.write_to_file(outfile_);
216}
217
218static void spaces_to_underscores(std::string &r_name)
219{
220 std::replace(r_name.begin(), r_name.end(), ' ', '_');
221}
222
223void OBJWriter::write_object_name(FormatHandler &fh, const OBJMesh &obj_mesh_data) const
224{
225 std::string object_name = obj_mesh_data.get_object_name();
226 spaces_to_underscores(object_name);
227 if (export_params_.export_object_groups) {
228 std::string mesh_name = obj_mesh_data.get_object_mesh_name();
229 spaces_to_underscores(mesh_name);
230 fh.write_obj_group(object_name + "_" + mesh_name);
231 return;
232 }
233 fh.write_obj_object(object_name);
234}
235
236/* Split up large meshes into multi-threaded jobs; each job processes
237 * this amount of items. */
238static const int chunk_size = 32768;
239static int calc_chunk_count(int count)
240{
241 return (count + chunk_size - 1) / chunk_size;
242}
243
244/* Write /tot_count/ items to OBJ file output. Each item is written
245 * by a /function/ that should be independent from other items.
246 * If the amount of items is large enough (> chunk_size), then writing
247 * will be done in parallel, into temporary FormatHandler buffers that
248 * will be written into the final /fh/ buffer at the end.
249 */
250template<typename Function>
251void obj_parallel_chunked_output(FormatHandler &fh, int tot_count, const Function &function)
252{
253 if (tot_count <= 0) {
254 return;
255 }
256 /* If we have just one chunk, process it directly into the output
257 * buffer - avoids all the job scheduling and temporary vector allocation
258 * overhead. */
259 const int chunk_count = calc_chunk_count(tot_count);
260 if (chunk_count == 1) {
261 for (int i = 0; i < tot_count; i++) {
262 function(fh, i);
263 }
264 return;
265 }
266 /* Give each chunk its own temporary output buffer, and process them in parallel. */
267 Array<FormatHandler> buffers(chunk_count);
268 threading::parallel_for(IndexRange(chunk_count), 1, [&](IndexRange range) {
269 for (const int r : range) {
270 int i_start = r * chunk_size;
271 int i_end = std::min(i_start + chunk_size, tot_count);
272 auto &buf = buffers[r];
273 for (int i = i_start; i < i_end; i++) {
274 function(buf, i);
275 }
276 }
277 });
278 /* Emit all temporary output buffers into the destination buffer. */
279 for (auto &buf : buffers) {
280 fh.append_from(buf);
281 }
282}
283
285 const OBJMesh &obj_mesh_data,
286 bool write_colors) const
287{
288 const int tot_count = obj_mesh_data.tot_vertices();
289
290 const Mesh *mesh = obj_mesh_data.get_mesh();
291 const StringRef name = mesh->active_color_attribute;
292
293 const float4x4 transform = obj_mesh_data.get_world_axes_transform();
294 const Span<float3> positions = obj_mesh_data.get_mesh()->vert_positions();
295
296 if (write_colors && !name.is_empty()) {
297 const bke::AttributeAccessor attributes = mesh->attributes();
299 name, bke::AttrDomain::Point, {0.0f, 0.0f, 0.0f, 0.0f});
300
301 BLI_assert(tot_count == attribute.size());
302 obj_parallel_chunked_output(fh, tot_count, [&](FormatHandler &buf, int i) {
303 const float3 vertex = math::transform_point(transform, positions[i]);
304 ColorGeometry4f linear = attribute.get(i);
305 float srgb[3];
306 linearrgb_to_srgb_v3_v3(srgb, linear);
307 buf.write_obj_vertex_color(vertex[0], vertex[1], vertex[2], srgb[0], srgb[1], srgb[2]);
308 });
309 }
310 else {
311 obj_parallel_chunked_output(fh, tot_count, [&](FormatHandler &buf, int i) {
312 const float3 vertex = math::transform_point(transform, positions[i]);
313 buf.write_obj_vertex(vertex[0], vertex[1], vertex[2]);
314 });
315 }
316}
317
318void OBJWriter::write_uv_coords(FormatHandler &fh, OBJMesh &r_obj_mesh_data) const
319{
320 const Span<float2> uv_coords = r_obj_mesh_data.get_uv_coords();
321 obj_parallel_chunked_output(fh, uv_coords.size(), [&](FormatHandler &buf, int i) {
322 const float2 &uv_vertex = uv_coords[i];
323 buf.write_obj_uv(uv_vertex[0], uv_vertex[1]);
324 });
325}
326
328{
329 /* Poly normals should be calculated earlier via store_normal_coords_and_indices. */
330 const Span<float3> normal_coords = obj_mesh_data.get_normal_coords();
331 obj_parallel_chunked_output(fh, normal_coords.size(), [&](FormatHandler &buf, int i) {
332 const float3 &normal = normal_coords[i];
333 buf.write_obj_normal(normal[0], normal[1], normal[2]);
334 });
335}
336
337OBJWriter::func_vert_uv_normal_indices OBJWriter::get_face_element_writer(
338 const int total_uv_vertices) const
339{
340 if (export_params_.export_normals) {
341 if (export_params_.export_uv && (total_uv_vertices > 0)) {
342 /* Write both normals and UV indices. */
343 return &OBJWriter::write_vert_uv_normal_indices;
344 }
345 /* Write normals indices. */
346 return &OBJWriter::write_vert_normal_indices;
347 }
348 /* Write UV indices. */
349 if (export_params_.export_uv && (total_uv_vertices > 0)) {
350 return &OBJWriter::write_vert_uv_indices;
351 }
352 /* Write neither normals nor UV indices. */
353 return &OBJWriter::write_vert_indices;
354}
355
356static int get_smooth_group(const OBJMesh &mesh, const OBJExportParams &params, int face_idx)
357{
358 if (face_idx < 0) {
359 return NEGATIVE_INIT;
360 }
361 int group = SMOOTH_GROUP_DISABLED;
362 if (mesh.is_ith_face_smooth(face_idx)) {
363 group = !params.export_smooth_groups ? SMOOTH_GROUP_DEFAULT : mesh.ith_smooth_group(face_idx);
364 }
365 return group;
366}
367
369 const IndexOffsets &offsets,
370 const OBJMesh &obj_mesh_data,
371 FunctionRef<const char *(int)> matname_fn)
372{
373 const func_vert_uv_normal_indices face_element_writer = get_face_element_writer(
374 obj_mesh_data.tot_uv_vertices());
375
376 const int tot_faces = obj_mesh_data.tot_faces();
377 const int tot_deform_groups = obj_mesh_data.tot_deform_groups();
379 const bke::AttributeAccessor attributes = obj_mesh_data.get_mesh()->attributes();
380 const VArray<int> material_indices = *attributes.lookup_or_default<int>(
381 "material_index", bke::AttrDomain::Face, 0);
382
383 obj_parallel_chunked_output(fh, tot_faces, [&](FormatHandler &buf, int idx) {
384 /* Polygon order for writing into the file is not necessarily the same
385 * as order in the mesh; it will be sorted by material indices. Remap current
386 * and previous indices here according to the order. */
387 int prev_i = obj_mesh_data.remap_face_index(idx - 1);
388 int i = obj_mesh_data.remap_face_index(idx);
389
390 const Span<int> face_vertex_indices = obj_mesh_data.calc_face_vert_indices(i);
391 const Span<int> face_uv_indices = obj_mesh_data.get_face_uv_indices(i);
392 const Span<int> face_normal_indices = obj_mesh_data.get_face_normal_indices(i);
393
394 /* Write smoothing group if different from previous. */
395 {
396 const int prev_group = get_smooth_group(obj_mesh_data, export_params_, prev_i);
397 const int group = get_smooth_group(obj_mesh_data, export_params_, i);
398 if (group != prev_group) {
399 buf.write_obj_smooth(group);
400 }
401 }
402
403 /* Write vertex group if different from previous. */
404 if (export_params_.export_vertex_groups) {
405 Vector<float> &local_weights = group_weights.local();
406 local_weights.resize(tot_deform_groups);
407 const int16_t prev_group = idx == 0 ? NEGATIVE_INIT :
408 obj_mesh_data.get_face_deform_group_index(
409 prev_i, local_weights);
410 const int16_t group = obj_mesh_data.get_face_deform_group_index(i, local_weights);
411 if (group != prev_group) {
413 obj_mesh_data.get_face_deform_group_name(group));
414 }
415 }
416
417 /* Write material name and material group if different from previous. */
418 if ((export_params_.export_materials || export_params_.export_material_groups) &&
419 obj_mesh_data.tot_materials() > 0)
420 {
421 const int16_t prev_mat = idx == 0 ? NEGATIVE_INIT : std::max(0, material_indices[prev_i]);
422 const int16_t mat = std::max(0, material_indices[i]);
423 if (mat != prev_mat) {
424 if (mat == NOT_FOUND) {
425 if (export_params_.export_materials) {
427 }
428 }
429 else {
430 const char *mat_name = matname_fn(mat);
431 if (!mat_name) {
432 mat_name = MATERIAL_GROUP_DISABLED;
433 }
434 if (export_params_.export_material_groups) {
435 std::string object_name = obj_mesh_data.get_object_name();
436 spaces_to_underscores(object_name);
437 buf.write_obj_group(object_name + "_" + mat_name);
438 }
439 if (export_params_.export_materials) {
440 buf.write_obj_usemtl(mat_name);
441 }
442 }
443 }
444 }
445
446 /* Write face elements. */
447 (this->*face_element_writer)(buf,
448 offsets,
449 face_vertex_indices,
450 face_uv_indices,
451 face_normal_indices,
452 obj_mesh_data.is_mirrored_transform());
453 });
454}
455
457 const IndexOffsets &offsets,
458 const OBJMesh &obj_mesh_data) const
459{
460 const Mesh &mesh = *obj_mesh_data.get_mesh();
461 const Span<int2> edges = mesh.edges();
462 mesh.loose_edges().foreach_index([&](const int i) {
463 const int2 obj_edge = edges[i] + offsets.vertex_offset + 1;
464 fh.write_obj_edge(obj_edge[0], obj_edge[1]);
465 });
466}
467
469 const float4x4 &object_to_world)
470{
471 float4x4 world_axes_transform;
472 float axes_transform[3][3];
473 unit_m3(axes_transform);
474 /* +Y-forward and +Z-up are the Blender's default axis settings. */
476 export_params.forward_axis, export_params.up_axis, IO_AXIS_Y, IO_AXIS_Z, axes_transform);
477 mul_m4_m3m4(world_axes_transform.ptr(), axes_transform, object_to_world.ptr());
478 /* #mul_m4_m3m4 does not transform last row of #Object.object_to_world, i.e. location data. */
479 mul_v3_m3v3(world_axes_transform[3], axes_transform, object_to_world.location());
480 world_axes_transform[3][3] = object_to_world[3][3];
481
482 /* Apply global scale transform. */
483 mul_v3_fl(world_axes_transform[0], export_params.global_scale);
484 mul_v3_fl(world_axes_transform[1], export_params.global_scale);
485 mul_v3_fl(world_axes_transform[2], export_params.global_scale);
486 mul_v3_fl(world_axes_transform[3], export_params.global_scale);
487
488 return world_axes_transform;
489}
490
491void OBJWriter::write_nurbs_curve(FormatHandler &fh, const IOBJCurve &obj_nurbs_data) const
492{
493 const int total_splines = obj_nurbs_data.total_splines();
494 for (int spline_idx = 0; spline_idx < total_splines; spline_idx++) {
495 /* Double check no surface is passed in as they are no supported (this is filtered when parsed)
496 */
497 BLI_assert(obj_nurbs_data.num_control_points_v(spline_idx) == 1);
498
499 const float4x4 world_axes_transform = compute_world_axes_transform(
500 export_params_, obj_nurbs_data.object_transform());
501
502 const char *nurbs_name = obj_nurbs_data.get_curve_name();
503 const int degree_u = obj_nurbs_data.get_nurbs_degree_u(spline_idx);
504 fh.write_obj_group(nurbs_name);
505 fh.write_obj_cstype();
506 fh.write_obj_nurbs_degree(degree_u);
507
508 const int num_points_u = obj_nurbs_data.num_control_points_u(spline_idx);
509
510 Vector<float> knot_buffer;
511 Span<float> knots_u = obj_nurbs_data.get_knots_u(spline_idx, knot_buffer);
512 IndexRange point_range(0, num_points_u);
513 knots_u = valid_nurb_control_point_range(degree_u + 1, knots_u, point_range);
514
515 /* Write coords */
516 Vector<float3> dynamic_point_buffer;
517 Span<float3> vertex_coords = obj_nurbs_data.vertex_coordinates(spline_idx,
518 dynamic_point_buffer);
519
520 /* Write only unique points. */
521 IndexRange point_loop_range = point_range.size() > vertex_coords.size() ?
522 point_range.drop_back(point_range.size() -
523 vertex_coords.size()) :
524 point_range;
525 for (const int64_t index : point_loop_range) {
526 /* Modulo will loop back to the 0:th point, not the start of the point range! */
527 float3 co = vertex_coords[index % vertex_coords.size()];
528 mul_m4_v3(world_axes_transform.ptr(), &co.x);
529 fh.write_obj_vertex(co[0], co[1], co[2]);
530 }
531
533 fh.write_obj_nurbs_parm(knots_u[degree_u]);
534 fh.write_obj_nurbs_parm(knots_u.last(degree_u));
535
536 /* Loop over the [0, N) range, not its actual interval [x, N + x).
537 * For cyclic curves, up to [0, order) will be repeated.
538 */
539 for (int64_t index : point_range.index_range()) {
540 /* Write one based (1 ==> coords[0]) relative/negative indices.
541 * TODO: Write positive indices...
542 */
543 index = -(point_loop_range.size() - (index % point_loop_range.size()));
545 }
547
548 /* Write knot vector. */
550 for (const float &u : knots_u) {
552 }
555 }
556}
557
558/* -------------------------------------------------------------------- */
561
562static const char *tex_map_type_to_string[] = {
563 "map_Kd",
564 "map_Pm",
565 "map_Ks",
566 "map_Ns",
567 "map_Pr",
568 "map_Ps",
569 "map_refl",
570 "map_Ke",
571 "map_d",
572 "map_Bump",
573};
575 "array size mismatch");
576
581static std::string float3_to_string(const float3 &numbers)
582{
583 return fmt::format("{} {} {}", numbers[0], numbers[1], numbers[2]);
584}
585
586MTLWriter::MTLWriter(const char *obj_filepath, bool write_file) noexcept(false)
587{
588 if (!write_file) {
589 return;
590 }
591 char mtl_path[FILE_MAX];
592 STRNCPY(mtl_path, obj_filepath);
593
594 const bool ok = BLI_path_extension_replace(mtl_path, sizeof(mtl_path), ".mtl");
595 if (!ok) {
596 throw std::system_error(ENAMETOOLONG, std::system_category(), "");
597 }
598
599 mtl_filepath_ = mtl_path;
600 outfile_ = BLI_fopen(mtl_filepath_.c_str(), "wb");
601 if (!outfile_) {
602 throw std::system_error(errno, std::system_category(), "Cannot open file " + mtl_filepath_);
603 }
604}
606{
607 if (outfile_) {
608 fmt_handler_.write_to_file(outfile_);
609 if (std::fclose(outfile_)) {
611 "Error: could not close file '%s' properly, it may be corrupted.",
612 mtl_filepath_.c_str());
613 }
614 }
615}
616
617void MTLWriter::write_header(const char *blen_filepath)
618{
619 using namespace std::string_literals;
620 const char *blen_basename = (blen_filepath && blen_filepath[0] != '\0') ?
621 BLI_path_basename(blen_filepath) :
622 "None";
623 fmt_handler_.write_string("# Blender "s + BKE_blender_version_string() + " MTL File: '" +
624 blen_basename + "'");
625 fmt_handler_.write_string("# www.blender.org");
626}
627
629{
630 return mtl_filepath_;
631}
632
633void MTLWriter::write_bsdf_properties(const MTLMaterial &mtl, bool write_pbr)
634{
635 /* For various material properties, we only capture information
636 * coming from the texture, or the default value of the socket.
637 * When the texture is present, do not emit the default value. */
638
639 /* Do not write Ns & Ka when writing in PBR mode. */
640 if (!write_pbr) {
642 fmt_handler_.write_mtl_float("Ns", mtl.spec_exponent);
643 }
644 fmt_handler_.write_mtl_float3(
645 "Ka", mtl.ambient_color.x, mtl.ambient_color.y, mtl.ambient_color.z);
646 }
648 fmt_handler_.write_mtl_float3("Kd", mtl.color.x, mtl.color.y, mtl.color.z);
649 }
651 fmt_handler_.write_mtl_float3("Ks", mtl.spec_color.x, mtl.spec_color.y, mtl.spec_color.z);
652 }
654 fmt_handler_.write_mtl_float3(
655 "Ke", mtl.emission_color.x, mtl.emission_color.y, mtl.emission_color.z);
656 }
657 fmt_handler_.write_mtl_float("Ni", mtl.ior);
659 fmt_handler_.write_mtl_float("d", mtl.alpha);
660 }
661 fmt_handler_.write_mtl_illum(mtl.illum_mode);
662
663 if (write_pbr) {
664 if (!mtl.tex_map_of_type(MTLTexMapType::Roughness).is_valid() && mtl.roughness >= 0.0f) {
665 fmt_handler_.write_mtl_float("Pr", mtl.roughness);
666 }
667 if (!mtl.tex_map_of_type(MTLTexMapType::Metallic).is_valid() && mtl.metallic >= 0.0f) {
668 fmt_handler_.write_mtl_float("Pm", mtl.metallic);
669 }
670 if (!mtl.tex_map_of_type(MTLTexMapType::Sheen).is_valid() && mtl.sheen >= 0.0f) {
671 fmt_handler_.write_mtl_float("Ps", mtl.sheen);
672 }
673 if (mtl.cc_thickness >= 0.0f) {
674 fmt_handler_.write_mtl_float("Pc", mtl.cc_thickness);
675 }
676 if (mtl.cc_roughness >= 0.0f) {
677 fmt_handler_.write_mtl_float("Pcr", mtl.cc_roughness);
678 }
679 if (mtl.aniso >= 0.0f) {
680 fmt_handler_.write_mtl_float("aniso", mtl.aniso);
681 }
682 if (mtl.aniso_rot >= 0.0f) {
683 fmt_handler_.write_mtl_float("anisor", mtl.aniso_rot);
684 }
685 if (mtl.transmit_color.x > 0.0f || mtl.transmit_color.y > 0.0f || mtl.transmit_color.z > 0.0f)
686 {
687 fmt_handler_.write_mtl_float3(
688 "Tf", mtl.transmit_color.x, mtl.transmit_color.y, mtl.transmit_color.z);
689 }
690 }
691}
692
693void MTLWriter::write_texture_map(const MTLMaterial &mtl_material,
694 MTLTexMapType texture_key,
695 const MTLTexMap &texture_map,
696 const char *blen_filedir,
697 const char *dest_dir,
698 ePathReferenceMode path_mode,
699 Set<std::pair<std::string, std::string>> &copy_set)
700{
701 std::string options;
702 /* Option strings should have their own leading spaces. */
703 if (texture_map.translation != float3{0.0f, 0.0f, 0.0f}) {
704 options.append(" -o ").append(float3_to_string(texture_map.translation));
705 }
706 if (texture_map.scale != float3{1.0f, 1.0f, 1.0f}) {
707 options.append(" -s ").append(float3_to_string(texture_map.scale));
708 }
709 if (texture_key == MTLTexMapType::Normal && mtl_material.normal_strength > 0.0001f) {
710 options.append(" -bm ").append(std::to_string(mtl_material.normal_strength));
711 }
712
713 std::string path = path_reference(
714 texture_map.image_path.c_str(), blen_filedir, dest_dir, path_mode, &copy_set);
715 /* Always emit forward slashes for cross-platform compatibility. */
716 std::replace(path.begin(), path.end(), '\\', '/');
717
718 fmt_handler_.write_mtl_map(tex_map_type_to_string[int(texture_key)], options, path);
719}
720
721static bool is_pbr_map(MTLTexMapType type)
722{
723 return type == MTLTexMapType::Metallic || type == MTLTexMapType::Roughness ||
724 type == MTLTexMapType::Sheen;
725}
726
728{
730}
731
732void MTLWriter::write_materials(const char *blen_filepath,
733 ePathReferenceMode path_mode,
734 const char *dest_dir,
735 bool write_pbr)
736{
737 if (mtlmaterials_.is_empty()) {
738 return;
739 }
740
741 char blen_filedir[FILE_MAX];
742 BLI_path_split_dir_part(blen_filepath, blen_filedir, sizeof(blen_filedir));
743 BLI_path_slash_native(blen_filedir);
744 BLI_path_normalize(blen_filedir);
745
746 std::ranges::sort(mtlmaterials_,
747 [](const MTLMaterial &a, const MTLMaterial &b) { return a.name < b.name; });
749 for (const MTLMaterial &mtlmat : mtlmaterials_) {
750 fmt_handler_.write_string("");
751 fmt_handler_.write_mtl_newmtl(mtlmat.name);
752 write_bsdf_properties(mtlmat, write_pbr);
753 for (int key = 0; key < int(MTLTexMapType::Count); key++) {
754 const MTLTexMap &tex = mtlmat.texture_maps[key];
755 if (!tex.is_valid()) {
756 continue;
757 }
758 if (!write_pbr && is_pbr_map((MTLTexMapType)key)) {
759 continue;
760 }
761 if (write_pbr && is_non_pbr_map((MTLTexMapType)key)) {
762 continue;
763 }
764 write_texture_map(
765 mtlmat, (MTLTexMapType)key, tex, blen_filedir, dest_dir, path_mode, copy_set);
766 }
767 }
768 path_reference_copy(copy_set);
769}
770
772{
773 Vector<int> mtl_indices;
774 mtl_indices.resize(mesh_to_export.tot_materials());
775 for (int16_t i = 0; i < mesh_to_export.tot_materials(); i++) {
776 const Material *material = mesh_to_export.materials[i];
777 if (!material) {
778 mtl_indices[i] = -1;
779 continue;
780 }
781 int mtlmat_index = material_map_.lookup_default(material, -1);
782 if (mtlmat_index != -1) {
783 mtl_indices[i] = mtlmat_index;
784 }
785 else {
786 mtlmaterials_.append(mtlmaterial_for_material(material));
787 mtl_indices[i] = mtlmaterials_.size() - 1;
788 material_map_.add_new(material, mtl_indices[i]);
789 }
790 }
791 return mtl_indices;
792}
793
795{
796 if (index < 0 || index >= mtlmaterials_.size()) {
797 return nullptr;
798 }
799 return mtlmaterials_[index].name.c_str();
800}
801
802
803} // namespace io::obj
804} // namespace blender
File and directory operations.
#define FILE_MAXFILE
#define FILE_MAX
#define FILE_MAXDIR
#define CLOG_ERROR(clg_ref,...)
Definition CLG_log.h:188
#define BLI_assert(a)
constexpr int64_t size() const
Definition BLI_span.hh:256
constexpr IndexRange drop_back(int64_t n) const
constexpr int64_t size() const
constexpr IndexRange()=default
constexpr IndexRange index_range() const
constexpr int64_t size() const
Definition BLI_span.hh:256
constexpr const T & last(const int64_t n=0) const
Definition BLI_span.hh:329
int64_t size() const
void resize(const int64_t new_size)
GAttributeReader lookup_or_default(StringRef name, AttrDomain domain, AttrType data_type, const void *default_value=nullptr) const
constexpr bool is_empty() const
constexpr const char * data() const
void write_obj_face_v_uv_normal(int v, int uv, int n)
void write_mtl_float3(const char *type, float r, float g, float b)
void write_obj_vertex(float x, float y, float z)
void write_obj_vertex_color(float x, float y, float z, float r, float g, float b)
void write_mtl_float(const char *type, float v)
void append_from(FormatHandler &v)
virtual int total_splines() const =0
virtual int num_control_points_v(int spline_index) const =0
virtual const char * get_curve_name() const =0
virtual Span< float3 > vertex_coordinates(int spline_index, Vector< float3 > &dynamic_point_buffer) const =0
virtual Span< float > get_knots_u(int spline_index, Vector< float > &buffer) const =0
virtual int num_control_points_u(int spline_index) const =0
virtual int get_nurbs_degree_u(int spline_index) const =0
virtual const float4x4 & object_transform() const =0
MTLWriter(const char *obj_filepath, bool write_file) noexcept(false)
Vector< int > add_materials(const OBJMesh &mesh_to_export)
void write_header(const char *blen_filepath)
void write_materials(const char *blen_filepath, ePathReferenceMode path_mode, const char *dest_dir, bool write_pbr)
const char * mtlmaterial_name(int index)
const char * get_face_deform_group_name(int16_t def_group_index) const
int16_t get_face_deform_group_index(int face_index, MutableSpan< float > group_weights) const
StringRef get_object_mesh_name() const
Span< int > get_face_uv_indices(const int face_index) const
int remap_face_index(int i) const
Array< const Material * > materials
Span< float3 > get_normal_coords() const
const float4x4 & get_world_axes_transform() const
StringRef get_object_name() const
Span< int > get_face_normal_indices(const int face_index) const
Span< int > calc_face_vert_indices(const int face_index) const
Span< float2 > get_uv_coords() const
const Mesh * get_mesh() const
void write_normals(FormatHandler &fh, OBJMesh &obj_mesh_data)
OBJWriter(const char *filepath, const OBJExportParams &export_params) noexcept(false)
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 IOBJCurve &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
CCL_NAMESPACE_BEGIN struct Options options
#define attribute(slot)
#define vertex
static void spaces_to_underscores(std::string &r_name)
static bool is_pbr_map(MTLTexMapType type)
static const char * tex_map_type_to_string[]
static const char * MATERIAL_GROUP_DISABLED
Span< float > valid_nurb_control_point_range(const int8_t order, const Span< float > knots, IndexRange &point_range)
MTLMaterial mtlmaterial_for_material(const Material *material)
static int get_smooth_group(const OBJMesh &mesh, const OBJExportParams &params, int face_idx)
void obj_parallel_chunked_output(FormatHandler &fh, int tot_count, const Function &function)
static float4x4 compute_world_axes_transform(const OBJExportParams &export_params, const float4x4 &object_to_world)
BLI_STATIC_ASSERT(ARRAY_SIZE(tex_map_type_to_string)==int(MTLTexMapType::Count), "array size mismatch")
static bool is_non_pbr_map(MTLTexMapType type)
static std::string float3_to_string(const float3 &numbers)
static const int chunk_size
static int calc_chunk_count(int count)
static const char * DEFORM_GROUP_DISABLED
std::string path_reference(StringRefNull filepath, StringRefNull base_src, StringRefNull base_dst, ePathReferenceMode mode, Set< std::pair< std::string, std::string > > *copy_set)
Definition path_util.cc:18
void path_reference_copy(const Set< std::pair< std::string, std::string > > &copy_set)
Definition path_util.cc:67
VecBase< T, 3 > transform_point(const CartesianBasis &basis, const VecBase< T, 3 > &v)
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:69
BMesh Iterators.
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
__int64 int64_t
Definition BKE_text.h:90
char * STRNCPY(char(&dst)[N], const char *src)
void linearrgb_to_srgb_v3_v3(float srgb[3], const float linear[3])
FILE * BLI_fopen(const char *filepath, const char *mode) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
MatBase< float, 4, 4 > float4x4
void BLI_path_slash_native(char *path) ATTR_NONNULL(1)
MINLINE void mul_v3_fl(float r[3], float f)
void mul_m4_v3(const float M[4][4], float r[3])
void void void const char * BLI_path_basename(const char *path) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT
void void BLI_path_split_dir_part(const char *filepath, char *dir, size_t dir_maxncpy) ATTR_NONNULL(1
VecBase< int32_t, 2 > int2
constexpr size_t ARRAY_SIZE(const T(&arg)[N]) noexcept
bool mat3_from_axis_conversion(int src_forward, int src_up, int dst_forward, int dst_up, float r_mat[3][3])
int BLI_path_normalize(char *path) ATTR_NONNULL(1)
bool BLI_path_extension_replace(char *path, size_t path_maxncpy, const char *ext) ATTR_NONNULL(1
void unit_m3(float m[3][3])
void BLI_path_split_dir_file(const char *filepath, char *dir, size_t dir_maxncpy, char *file, size_t file_maxncpy) ATTR_NONNULL(1
static CLG_LogRef LOG
Definition logging.cpp:12
ColorSceneLinear4f< eAlpha::Premultiplied > ColorGeometry4f
VecBase< float, 3 > float3
void mul_v3_m3v3(float r[3], const float M[3][3], const float a[3])
const char * BKE_blender_version_string()
Definition blender.cc:147
void mul_m4_m3m4(float R[4][4], const float A[3][3], const float B[4][4])
signed short int16_t
Definition BKE_text.h:77
const c_style_mat & ptr() const
const MTLTexMap & tex_map_of_type(MTLTexMapType key) const