Blender V5.3
obj_export_mtl.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 "BKE_image.hh"
10#include "BKE_node.hh"
12#include "BKE_node_runtime.hh"
13
14#include "BLI_math_vector_c.hh"
15#include "BLI_path_utils.hh"
16#include "BLI_string.hh"
17
18#include "DNA_material_types.h"
19#include "DNA_node_types.h"
20
21#include "obj_export_mtl.hh"
22
23#include "CLG_log.h"
24
25namespace blender {
26
27static CLG_LogRef LOG = {"io.obj"};
28
29namespace io::obj {
30
32 "Base Color",
33 "Metallic",
34 "Specular IOR Level",
35 "Roughness", /* Map specular exponent to roughness. */
36 "Roughness",
37 "Sheen Weight",
38 "Metallic", /* Map reflection to metallic. */
39 "Emission Color",
40 "Alpha",
41 "Normal",
42};
44 "array size mismatch");
45
49static void copy_property_from_node(const eNodeSocketDatatype property_type,
50 const bNode *node,
51 const char *identifier,
52 MutableSpan<float> r_property)
53{
54 if (!node) {
55 return;
56 }
57 const bNodeSocket *socket = bke::node_find_socket(
58 *const_cast<bNode *>(node), SOCK_IN, UString(identifier));
59 BLI_assert(socket && socket->type == property_type);
60 if (!socket) {
61 return;
62 }
63 switch (property_type) {
64 case SOCK_FLOAT: {
65 BLI_assert(r_property.size() == 1);
66 const bNodeSocketValueFloat *socket_def_value = static_cast<const bNodeSocketValueFloat *>(
67 socket->default_value);
68 r_property[0] = socket_def_value->value;
69 break;
70 }
71 case SOCK_RGBA: {
72 BLI_assert(r_property.size() == 3);
73 const bNodeSocketValueRGBA *socket_def_value = static_cast<const bNodeSocketValueRGBA *>(
74 socket->default_value);
75 copy_v3_v3(r_property.data(), socket_def_value->value);
76 break;
77 }
78 case SOCK_VECTOR: {
79 BLI_assert(r_property.size() == 3);
80 const bNodeSocketValueVector *socket_def_value = static_cast<const bNodeSocketValueVector *>(
81 socket->default_value);
82 copy_v3_v3(r_property.data(), socket_def_value->value);
83 break;
84 }
85 default: {
86 /* Other socket types are not handled here. */
87 BLI_assert(0);
88 break;
89 }
90 }
91}
92
96static void linked_sockets_to_dest_id(const bNode *dest_node,
97 const bNodeTree &node_tree,
98 const char *dest_socket_id,
99 Vector<const bNodeSocket *> &r_linked_sockets)
100{
101 r_linked_sockets.clear();
102 if (!dest_node) {
103 return;
104 }
105 Span<const bNode *> object_dest_nodes = node_tree.nodes_by_type(UString(dest_node->idname));
106 Span<const bNodeSocket *> dest_inputs = object_dest_nodes.first()->input_sockets();
107 const bNodeSocket *dest_socket = nullptr;
108 for (const bNodeSocket *curr_socket : dest_inputs) {
109 if (STREQ(curr_socket->identifier, dest_socket_id)) {
110 dest_socket = curr_socket;
111 break;
112 }
113 }
114 if (dest_socket) {
115 Span<const bNodeSocket *> linked_sockets = dest_socket->directly_linked_sockets();
116 r_linked_sockets.resize(linked_sockets.size());
117 r_linked_sockets = linked_sockets;
118 }
119}
120
124static const bNode *get_node_of_type(Span<const bNodeSocket *> sockets_list, const int node_type)
125{
126 for (const bNodeSocket *socket : sockets_list) {
127 const bNode &parent_node = socket->owner_node();
128 if (parent_node.typeinfo->type_legacy == node_type) {
129 return &parent_node;
130 }
131 }
132 return nullptr;
133}
134
135/*
136 * From a texture image shader node, get the image's filepath.
137 * If packed image is found, only the file "name" is returned.
138 */
139static std::string get_image_filepath(const bNode *tex_node)
140{
141 if (!tex_node) {
142 return "";
143 }
144 Image *tex_image = reinterpret_cast<Image *>(tex_node->id);
145 if (!tex_image || !BKE_image_has_filepath(tex_image)) {
146 return "";
147 }
148
149 if (BKE_image_has_packedfile(tex_image)) {
150 /* Put image in the same directory as the `.MTL` file. */
151 const char *filename = BLI_path_basename(tex_image->filepath);
152 CLOG_INFO(&LOG,
153 "Packed image found:'%s'. Unpack and place the image in the same "
154 "directory as the .MTL file.",
155 filename);
156 return filename;
157 }
158
159 char filepath[FILE_MAX];
160 STRNCPY(filepath, tex_image->filepath);
161
162 if (tex_image->source == IMA_SRC_SEQUENCE) {
163 char head[FILE_MAX], tail[FILE_MAX];
164 ushort numlen;
165 int framenr = static_cast<NodeTexImage *>(tex_node->storage)->iuser.framenr;
166 BLI_path_sequence_decode(filepath, head, sizeof(head), tail, sizeof(tail), &numlen);
167 BLI_path_sequence_encode(filepath, sizeof(filepath), head, tail, numlen, framenr);
168 }
169
170 return filepath;
171}
172
178static const bNode *find_bsdf_node(const bNodeTree *nodetree)
179{
180 if (!nodetree) {
181 return nullptr;
182 }
183 for (const bNode *node : nodetree->nodes_by_type("ShaderNodeOutputMaterial"_ustr)) {
184 const bNodeSocket &node_input_socket0 = node->input_socket(0);
185 for (const bNodeSocket *out_sock : node_input_socket0.directly_linked_sockets()) {
186 const bNode &in_node = out_sock->owner_node();
188 return &in_node;
189 }
190 }
191 }
192 return nullptr;
193}
194
198static void store_bsdf_properties(const bNode *bsdf_node,
199 const Material *material,
200 MTLMaterial &r_mtl_mat)
201{
202 float roughness = material->roughness;
203 if (bsdf_node) {
204 copy_property_from_node(SOCK_FLOAT, bsdf_node, "Roughness", {&roughness, 1});
205 }
206 /* Empirical approximation. Importer should use the inverse of this method. */
207 float spec_exponent = (1.0f - roughness);
208 spec_exponent *= spec_exponent * 1000.0f;
209
210 float specular = material->spec;
211 if (bsdf_node) {
212 copy_property_from_node(SOCK_FLOAT, bsdf_node, "Specular IOR Level", {&specular, 1});
213 }
214
215 float metallic = material->metallic;
216 if (bsdf_node) {
217 copy_property_from_node(SOCK_FLOAT, bsdf_node, "Metallic", {&metallic, 1});
218 }
219
220 float refraction_index = 1.0f;
221 if (bsdf_node) {
222 copy_property_from_node(SOCK_FLOAT, bsdf_node, "IOR", {&refraction_index, 1});
223 }
224
225 float alpha = material->a;
226 if (bsdf_node) {
227 copy_property_from_node(SOCK_FLOAT, bsdf_node, "Alpha", {&alpha, 1});
228 }
229 const bool transparent = alpha != 1.0f;
230
231 float3 diffuse_col = {material->r, material->g, material->b};
232 if (bsdf_node) {
233 copy_property_from_node(SOCK_RGBA, bsdf_node, "Base Color", {diffuse_col, 3});
234 }
235
236 float3 emission_col{0.0f};
237 float emission_strength = 0.0f;
238 if (bsdf_node) {
239 copy_property_from_node(SOCK_FLOAT, bsdf_node, "Emission Strength", {&emission_strength, 1});
240 copy_property_from_node(SOCK_RGBA, bsdf_node, "Emission Color", {emission_col, 3});
241 }
242 mul_v3_fl(emission_col, emission_strength);
243
244 float sheen = -1.0f;
245 float coat = -1.0f;
246 float coat_roughness = -1.0f;
247 float aniso = -1.0f;
248 float aniso_rot = -1.0f;
249 float transmission = -1.0f;
250 if (bsdf_node) {
251 copy_property_from_node(SOCK_FLOAT, bsdf_node, "Sheen Weight", {&sheen, 1});
252 copy_property_from_node(SOCK_FLOAT, bsdf_node, "Coat Weight", {&coat, 1});
253 copy_property_from_node(SOCK_FLOAT, bsdf_node, "Coat Roughness", {&coat_roughness, 1});
254 copy_property_from_node(SOCK_FLOAT, bsdf_node, "Anisotropic", {&aniso, 1});
255 copy_property_from_node(SOCK_FLOAT, bsdf_node, "Anisotropic Rotation", {&aniso_rot, 1});
256 copy_property_from_node(SOCK_FLOAT, bsdf_node, "Transmission Weight", {&transmission, 1});
257
258 /* Clearcoat used to include an implicit 0.25 factor, so stay compatible to old versions. */
259 coat *= 4.0f;
260 }
261
262 /* See https://wikipedia.org/wiki/Wavefront_.obj_file for all possible values of `illum`. */
263 /* Highlight on. */
264 int illum = 2;
265 if (specular == 0.0f) {
266 /* Color on and Ambient on. */
267 illum = 1;
268 }
269 else if (metallic > 0.0f) {
270 /* Metallic ~= Reflection. */
271 if (transparent) {
272 /* Transparency: Refraction on, Reflection: ~~Fresnel off and Ray trace~~ on. */
273 illum = 6;
274 }
275 else {
276 /* Reflection on and Ray trace on. */
277 illum = 3;
278 }
279 }
280 else if (transparent) {
281 /* Transparency: Glass on, Reflection: Ray trace off */
282 illum = 9;
283 }
284 r_mtl_mat.spec_exponent = spec_exponent;
285 if (metallic != 0.0f) {
286 r_mtl_mat.ambient_color = {metallic, metallic, metallic};
287 }
288 else {
289 r_mtl_mat.ambient_color = {1.0f, 1.0f, 1.0f};
290 }
291 r_mtl_mat.color = diffuse_col;
292 r_mtl_mat.spec_color = {specular, specular, specular};
293 r_mtl_mat.emission_color = emission_col;
294 r_mtl_mat.ior = refraction_index;
295 r_mtl_mat.alpha = alpha;
296 r_mtl_mat.illum_mode = illum;
297 r_mtl_mat.roughness = roughness;
298 r_mtl_mat.metallic = metallic;
299 r_mtl_mat.sheen = sheen;
300 r_mtl_mat.cc_thickness = coat;
301 r_mtl_mat.cc_roughness = coat_roughness;
302 r_mtl_mat.aniso = aniso;
303 r_mtl_mat.aniso_rot = aniso_rot;
304 r_mtl_mat.transmit_color = {transmission, transmission, transmission};
305}
306
310static void store_image_textures(const bNode *bsdf_node,
311 const bNodeTree *node_tree,
312 const Material *material,
313 MTLMaterial &r_mtl_mat)
314{
315 if (!material || !node_tree || !bsdf_node) {
316 /* No nodetree, no images, or no Principled BSDF node. */
317 return;
318 }
319
320 /* Normal Map Texture has two extra tasks of:
321 * - finding a Normal Map node before finding a texture node.
322 * - finding "Strength" property of the node for `-bm` option.
323 */
324
325 for (int key = 0; key < int(MTLTexMapType::Count); ++key) {
326 MTLTexMap &value = r_mtl_mat.texture_maps[key];
327 Vector<const bNodeSocket *> linked_sockets;
328 const bNode *normal_map_node{nullptr};
329
330 if (key == int(MTLTexMapType::Normal)) {
331 /* Find sockets linked to destination "Normal" socket in P-BSDF node. */
332 linked_sockets_to_dest_id(bsdf_node, *node_tree, "Normal", linked_sockets);
333 /* Among the linked sockets, find Normal Map shader node. */
334 normal_map_node = get_node_of_type(linked_sockets, SH_NODE_NORMAL_MAP);
335
336 /* Find sockets linked to "Color" socket in normal map node. */
337 linked_sockets_to_dest_id(normal_map_node, *node_tree, "Color", linked_sockets);
338 }
339 else {
340 /* Skip emission map if emission strength is zero. */
341 if (key == int(MTLTexMapType::Emission)) {
342 float emission_strength = 0.0f;
344 SOCK_FLOAT, bsdf_node, "Emission Strength", {&emission_strength, 1});
345 if (emission_strength == 0.0f) {
346 continue;
347 }
348 }
349 /* Find sockets linked to the destination socket of interest, in P-BSDF node. */
351 bsdf_node, *node_tree, tex_map_type_to_socket_id[key], linked_sockets);
352 }
353
354 /* Among the linked sockets, find Image Texture shader node. */
355 const bNode *tex_node{get_node_of_type(linked_sockets, SH_NODE_TEX_IMAGE)};
356 if (!tex_node) {
357 continue;
358 }
359 const std::string tex_image_filepath = get_image_filepath(tex_node);
360 if (tex_image_filepath.empty()) {
361 continue;
362 }
363
364 /* Find "Mapping" node if connected to texture node. */
365 linked_sockets_to_dest_id(tex_node, *node_tree, "Vector", linked_sockets);
366 const bNode *mapping = get_node_of_type(linked_sockets, SH_NODE_MAPPING);
367
368 if (normal_map_node) {
370 SOCK_FLOAT, normal_map_node, "Strength", {&r_mtl_mat.normal_strength, 1});
371 }
372 /* Texture transform options. Only translation (origin offset, "-o") and scale
373 * ("-o") are supported. */
374 copy_property_from_node(SOCK_VECTOR, mapping, "Location", {value.translation, 3});
375 copy_property_from_node(SOCK_VECTOR, mapping, "Scale", {value.scale, 3});
376
377 value.image_path = tex_image_filepath;
378 }
379}
380
382{
383 BLI_assert(material != nullptr);
384 MTLMaterial mtlmat;
385 mtlmat.name = std::string(material->id.name + 2);
386 std::replace(mtlmat.name.begin(), mtlmat.name.end(), ' ', '_');
387 const bNodeTree *nodetree = material->nodetree;
388 if (nodetree != nullptr) {
389 nodetree->ensure_topology_cache();
390 }
391
392 const bNode *bsdf_node = find_bsdf_node(nodetree);
393 store_bsdf_properties(bsdf_node, material, mtlmat);
394 store_image_textures(bsdf_node, nodetree, material, mtlmat);
395 return mtlmat;
396}
397
398} // namespace io::obj
399} // namespace blender
#define SH_NODE_TEX_IMAGE
#define SH_NODE_BSDF_PRINCIPLED
#define SH_NODE_NORMAL_MAP
#define SH_NODE_MAPPING
#define FILE_MAX
#define CLOG_INFO(clg_ref,...)
Definition CLG_log.h:190
#define STREQ(a, b)
constexpr int64_t size() const
Definition BLI_span.hh:499
constexpr T * data() const
Definition BLI_span.hh:545
constexpr const T & first() const
Definition BLI_span.hh:319
constexpr int64_t size() const
Definition BLI_span.hh:256
UString()=default
void resize(const int64_t new_size)
bNodeSocket * node_find_socket(bNode &node, eNodeSocketInOut in_out, UString identifier)
Definition node.cc:3036
std::string filename(const std::string_view &str, size_t pos)
const char * tex_map_type_to_socket_id[]
static const bNode * get_node_of_type(Span< const bNodeSocket * > sockets_list, const int node_type)
static std::string get_image_filepath(const bNode *tex_node)
static const bNode * find_bsdf_node(const bNodeTree *nodetree)
static void store_bsdf_properties(const bNode *bsdf_node, const Material *material, MTLMaterial &r_mtl_mat)
MTLMaterial mtlmaterial_for_material(const Material *material)
BLI_STATIC_ASSERT(ARRAY_SIZE(tex_map_type_to_string)==int(MTLTexMapType::Count), "array size mismatch")
static void copy_property_from_node(const eNodeSocketDatatype property_type, const bNode *node, const char *identifier, MutableSpan< float > r_property)
static void store_image_textures(const bNode *bsdf_node, const bNodeTree *node_tree, const Material *material, MTLMaterial &r_mtl_mat)
static void linked_sockets_to_dest_id(const bNode *dest_node, const bNodeTree &node_tree, const char *dest_socket_id, Vector< const bNodeSocket * > &r_linked_sockets)
BMesh Iterators.
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
char * STRNCPY(char(&dst)[N], const char *src)
MINLINE void copy_v3_v3(float r[3], const float a[3])
bool BKE_image_has_filepath(const Image *ima)
unsigned short ushort
Definition BKE_text.h:56
MINLINE void mul_v3_fl(float r[3], float f)
void void void const char * BLI_path_basename(const char *path) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT
constexpr size_t ARRAY_SIZE(const T(&arg)[N]) noexcept
int BLI_path_sequence_decode(const char *path, char *head, size_t head_maxncpy, char *tail, size_t tail_maxncpy, unsigned short *r_digits_len)
Definition path_utils.cc:61
void BLI_path_sequence_encode(char *path, size_t path_maxncpy, const char *head, const char *tail, unsigned short numlen, int pic)
static CLG_LogRef LOG
Definition logging.cpp:12
VecBase< float, 3 > float3
bool BKE_image_has_packedfile(const Image *image)
closure color sheen(normal N, float roughness)
Definition stdcycles.h:96
eNodeSocketDatatype type
bke::bNodeType * typeinfo
MTLTexMap texture_maps[int(MTLTexMapType::Count)]