Blender V5.3
usd_writer_abstract.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2019 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
8#include "usd_utils.hh"
10
11#include <pxr/base/tf/stringUtils.h>
12#include <pxr/usd/usdGeom/bboxCache.h>
13#include <pxr/usd/usdGeom/scope.h>
14#include <pxr/usd/usdUI/accessibilityAPI.h>
15
16#include "BLI_assert.hh"
17#include "BLI_bounds_types.hh"
18
19#include "DNA_material_types.h"
20#include "DNA_mesh_types.h"
21
22#include "WM_types.hh"
23
24#include "CLG_log.h"
25
26namespace blender {
27
28static CLG_LogRef LOG = {"io.usd"};
29
30/* TfToken objects are not cheap to construct, so we do it once. */
31namespace usdtokens {
32static const pxr::TfToken blender_ns("userProperties:blender", pxr::TfToken::Immortal);
33} // namespace usdtokens
34
35namespace {
36struct AccessibilityPropertyName {
37 pxr::TfToken property_namespace;
38 pxr::TfToken property_base_name;
39};
40} // anonymous namespace
41
42static std::optional<AccessibilityPropertyName> parse_accessibility_property_name(
43 IDProperty *prop, bool allow_unicode)
44{
45 std::vector<std::string> property_tokens = pxr::TfStringTokenize(prop->name, ":");
46
47 /* First check if the property name matches the UsdUIAccessibility format exactly. */
48 if (property_tokens.size() == 3) {
49 pxr::TfToken accessibility_token(property_tokens[0]);
50 pxr::TfToken basename(property_tokens[2]);
51 if (accessibility_token == pxr::UsdUITokens->accessibility &&
52 pxr::UsdUIAccessibilityAPI::IsSchemaPropertyBaseName(basename))
53 {
54 AccessibilityPropertyName property_name;
55
56 /* Sanitize the namespace since this is user-generated and might need to be conformed
57 * to the `allow_unicode` export setting. */
58 property_name.property_namespace = pxr::TfToken(
59 io::usd::make_safe_name(property_tokens[1], allow_unicode));
60 property_name.property_base_name = basename;
61 return property_name;
62 }
63 }
64
65 return std::nullopt;
66}
67
68static bool is_valid_accessibility_priority(const pxr::TfToken &token)
69{
70 return token == pxr::UsdUITokens->low || token == pxr::UsdUITokens->standard ||
71 token == pxr::UsdUITokens->high;
72}
73
81static void write_accessibility_property(const pxr::UsdPrim &prim,
82 const AccessibilityPropertyName &property_name,
83 const std::string &value)
84{
85 pxr::UsdUIAccessibilityAPI accessibility_api = pxr::UsdUIAccessibilityAPI::Apply(
86 prim, property_name.property_namespace);
87 if (!accessibility_api) {
88 return;
89 }
90
91 if (property_name.property_base_name == pxr::UsdUITokens->label) {
92 accessibility_api.CreateLabelAttr().Set(value);
93 }
94 else if (property_name.property_base_name == pxr::UsdUITokens->description) {
95 accessibility_api.CreateDescriptionAttr().Set(value);
96 }
97 else if (property_name.property_base_name == pxr::UsdUITokens->priority) {
98 pxr::TfToken priority(value);
99 if (is_valid_accessibility_priority(priority)) {
100 accessibility_api.CreatePriorityAttr().Set(priority);
101 }
102 }
103}
104
105static std::string get_mesh_active_uvlayer_name(const Object *ob)
106{
107 if (!ob || ob->type != OB_MESH || !ob->data) {
108 return "";
109 }
110
111 const Mesh *mesh = id_cast<Mesh *>(ob->data);
112 return mesh->active_uv_map_name();
113}
114
115template<typename USDT>
116bool set_vec_attrib(const pxr::UsdPrim &prim,
117 const IDProperty *prop,
118 const pxr::TfToken &prop_token,
119 const pxr::SdfValueTypeName &type_name,
120 const pxr::UsdTimeCode &time)
121{
122 if (!prim || !prop || !prop->data.pointer || prop_token.IsEmpty() || !type_name) {
123 return false;
124 }
125
126 pxr::UsdAttribute vec_attr = prim.CreateAttribute(prop_token, type_name, true);
127
128 if (!vec_attr) {
129 CLOG_WARN(&LOG,
130 "Couldn't create USD attribute for array property %s",
131 prop_token.GetString().c_str());
132 return false;
133 }
134
135 USDT vec_value(static_cast<typename USDT::ScalarType *>(prop->data.pointer));
136
137 return vec_attr.Set(vec_value, time);
138}
139
140namespace io::usd {
141
142static void create_vector_attrib(const pxr::UsdPrim &prim,
143 const IDProperty *prop,
144 const pxr::TfToken &prop_token,
145 const pxr::UsdTimeCode &time)
146{
147 if (!prim || !prop || prop_token.IsEmpty()) {
148 return;
149 }
150
151 if (prop->type != IDP_ARRAY) {
152 CLOG_WARN(&LOG,
153 "Property %s is not an array type and can't be converted to a vector attribute",
154 prop->name);
155 return;
156 }
157
158 pxr::SdfValueTypeName type_name;
159 bool success = false;
160
161 if (prop->subtype == IDP_FLOAT) {
162 if (prop->len == 2) {
163 type_name = pxr::SdfValueTypeNames->Float2;
164 success = set_vec_attrib<pxr::GfVec2f>(prim, prop, prop_token, type_name, time);
165 }
166 else if (prop->len == 3) {
167 type_name = pxr::SdfValueTypeNames->Float3;
168 success = set_vec_attrib<pxr::GfVec3f>(prim, prop, prop_token, type_name, time);
169 }
170 else if (prop->len == 4) {
171 type_name = pxr::SdfValueTypeNames->Float4;
172 success = set_vec_attrib<pxr::GfVec4f>(prim, prop, prop_token, type_name, time);
173 }
174 }
175 else if (prop->subtype == IDP_DOUBLE) {
176 if (prop->len == 2) {
177 type_name = pxr::SdfValueTypeNames->Double2;
178 success = set_vec_attrib<pxr::GfVec2d>(prim, prop, prop_token, type_name, time);
179 }
180 else if (prop->len == 3) {
181 type_name = pxr::SdfValueTypeNames->Double3;
182 success = set_vec_attrib<pxr::GfVec3d>(prim, prop, prop_token, type_name, time);
183 }
184 else if (prop->len == 4) {
185 type_name = pxr::SdfValueTypeNames->Double4;
186 success = set_vec_attrib<pxr::GfVec4d>(prim, prop, prop_token, type_name, time);
187 }
188 }
189 else if (prop->subtype == IDP_INT) {
190 if (prop->len == 2) {
191 type_name = pxr::SdfValueTypeNames->Int2;
192 success = set_vec_attrib<pxr::GfVec2i>(prim, prop, prop_token, type_name, time);
193 }
194 else if (prop->len == 3) {
195 type_name = pxr::SdfValueTypeNames->Int3;
196 success = set_vec_attrib<pxr::GfVec3i>(prim, prop, prop_token, type_name, time);
197 }
198 else if (prop->len == 4) {
199 type_name = pxr::SdfValueTypeNames->Int4;
200 success = set_vec_attrib<pxr::GfVec4i>(prim, prop, prop_token, type_name, time);
201 }
202 }
203
204 if (!type_name) {
205 CLOG_WARN(&LOG,
206 "Couldn't determine USD type name for array property %s",
207 prop_token.GetString().c_str());
208 return;
209 }
210
211 if (!success) {
212 CLOG_WARN(
213 &LOG, "Couldn't set USD attribute from array property %s", prop_token.GetString().c_str());
214 return;
215 }
216}
217
222
224{
225 return true;
226}
227
232
234{
235 if (is_animated_) {
238 }
239 /* By using the default time-code USD won't even write a single `timeSample` for non-animated
240 * data. Instead, it writes it as non-time-sampled. */
241 return pxr::UsdTimeCode::Default();
242}
243
248
250{
253 check_is_animated(context);
254 }
255 else if (!is_animated_) {
256 /* A frame has already been written, and without animation one frame is enough. */
257 return;
258 }
259
260 do_write(context);
261
263}
264
265const pxr::SdfPath &USDAbstractWriter::usd_path() const
266{
268}
269
271{
272 static std::string material_library_path("/_materials");
273
274 const std::string &root_prim_path = usd_export_context_.export_params.root_prim_path;
275
276 if (!root_prim_path.empty()) {
277 return pxr::SdfPath(root_prim_path + material_library_path);
278 }
279
280 return pxr::SdfPath(material_library_path);
281}
282
284{
285 static std::string material_library_path("/_materials");
286
287 std::string path_prefix(usd_export_context_.export_params.root_prim_path);
288
289 path_prefix += context.higher_up_export_path;
290
291 return pxr::SdfPath(path_prefix + material_library_path);
292}
293
295 const HierarchyContext &context, Material *material) const
296{
297 pxr::UsdStageRefPtr stage = usd_export_context_.stage;
298
299 /* Construct the material. */
300 pxr::TfToken material_name(
302 pxr::SdfPath usd_path = pxr::UsdGeomScope::Define(stage, get_material_library_path())
303 .GetPath()
304 .AppendChild(material_name);
305 pxr::UsdShadeMaterial usd_material = pxr::UsdShadeMaterial::Get(stage, usd_path);
306 if (usd_material) {
307 return usd_material;
308 }
309
310 std::string active_uv = get_mesh_active_uvlayer_name(context.object);
311
312 usd_material = create_usd_material(
313 usd_export_context_, usd_path, material, active_uv, reports());
314
315 auto prim = usd_material.GetPrim();
316 add_to_prim_map(prim.GetPath(), &material->id);
317 write_id_properties(prim, material->id, get_export_time_code());
319
320 return usd_material;
321}
322
323pxr::UsdShadeMaterial USDAbstractWriter::ensure_usd_material(const HierarchyContext &context,
324 Material *material) const
325{
326 pxr::UsdShadeMaterial library_material = ensure_usd_material_created(context, material);
327
328 /* If instancing is enabled and the object is an instancing prototype, create a material
329 * under the prototype root referencing the library material. This is considered a best
330 * practice and is required for certain renderers (e.g., karma). */
331
332 if (!(usd_export_context_.export_params.use_instancing && context.is_prototype())) {
333 /* We don't need to handle the material for the prototype. */
334 return library_material;
335 }
336
337 /* Create the prototype material. */
338
339 pxr::UsdStageRefPtr stage = usd_export_context_.stage;
340
341 pxr::SdfPath usd_path = pxr::UsdGeomScope::Define(stage, get_proto_material_root_path(context))
342 .GetPath()
343 .AppendChild(library_material.GetPath().GetNameToken());
344
345 pxr::UsdShadeMaterial proto_material = pxr::UsdShadeMaterial::Define(stage, usd_path);
346
347 if (!proto_material.GetPrim().GetReferences().AddInternalReference(library_material.GetPath())) {
348 CLOG_WARN(&LOG,
349 "Unable to add a material reference from %s to %s for prototype %s",
350 proto_material.GetPath().GetAsString().c_str(),
351 library_material.GetPath().GetAsString().c_str(),
352 context.export_path.c_str());
353 return library_material;
354 }
355
356 return proto_material;
357}
358
360 const pxr::UsdTimeCode time,
361 const pxr::UsdGeomImageable &usd_geometry)
362{
363 pxr::UsdAttribute attr_visibility = usd_geometry.CreateVisibilityAttr(pxr::VtValue(), true);
364
365 const bool is_visible = context.is_object_visible(
367 const pxr::TfToken visibility = is_visible ? pxr::UsdGeomTokens->inherited :
368 pxr::UsdGeomTokens->invisible;
369
370 usd_value_writer_.SetAttribute(attr_visibility, pxr::VtValue(visibility), time);
371}
372
373bool USDAbstractWriter::mark_as_instance(const HierarchyContext &context, const pxr::UsdPrim &prim)
374{
375 BLI_assert(context.is_instance());
376
377 if (context.export_path == context.original_export_path) {
379 "Reference error: export path matches reference path: %s",
380 context.export_path.c_str());
381 BLI_assert_msg(0, "USD reference error");
382 return false;
383 }
384
385 BLI_assert(!context.original_export_path.empty());
386 BLI_assert(context.original_export_path.front() == '/');
387
388 std::string ref_path_str(usd_export_context_.export_params.root_prim_path);
389 ref_path_str += context.original_export_path;
390
391 pxr::SdfPath ref_path(ref_path_str);
392
393 /* To avoid USD errors, make sure the referenced path exists. */
394 usd_export_context_.stage->DefinePrim(ref_path);
395
396 if (!prim.GetReferences().AddInternalReference(ref_path)) {
397 /* See this URL for a description for why referencing may fail:
398 * https://graphics.pixar.com/usd/docs/api/class_usd_references.html#Usd_Failing_References
399 */
400 CLOG_WARN(&LOG,
401 "Unable to add reference from %s to %s, not instancing object for export",
402 context.export_path.c_str(),
403 context.original_export_path.c_str());
404 return false;
405 }
406
407 prim.SetInstanceable(true);
408
409 return true;
410}
411
412void USDAbstractWriter::write_id_properties(const pxr::UsdPrim &prim,
413 const ID &id,
414 pxr::UsdTimeCode time) const
415{
417 return;
418 }
419
421 if (GS(id.name) == ID_OB) {
422 /* Author property of original blender Object name. */
423 prim.CreateAttribute(pxr::TfToken(usdtokens::blender_ns.GetString() + ":object_name"),
424 pxr::SdfValueTypeNames->String,
425 true)
426 .Set<std::string>(std::string(id.name + 2));
427 }
428 else {
429 prim.CreateAttribute(pxr::TfToken(usdtokens::blender_ns.GetString() + ":data_name"),
430 pxr::SdfValueTypeNames->String,
431 true)
432 .Set<std::string>(std::string(id.name + 2));
433 }
434 }
435
436 if (id.properties) {
437 write_user_properties(prim, id.properties, time);
438 }
439}
440
441void USDAbstractWriter::write_user_properties(const pxr::UsdPrim &prim,
442 IDProperty *properties,
443 pxr::UsdTimeCode time) const
444{
445 if (properties == nullptr) {
446 return;
447 }
448
449 if (properties->type != IDP_GROUP) {
450 return;
451 }
452
453 const StringRef displayName_identifier = "displayName";
454
455 const std::string default_namespace(
457
458 for (IDProperty *prop = properties->data.group.first(); prop; prop = prop->next) {
459 if (displayName_identifier == prop->name) {
460 if (prop->type == IDP_STRING && prop->data.pointer) {
461 prim.SetDisplayName(static_cast<char *>(prop->data.pointer));
462 }
463 continue;
464 }
465
466 if (auto accessibility_property_name = parse_accessibility_property_name(
468 {
469 if (prop->type == IDP_STRING && prop->data.pointer) {
471 prim, *accessibility_property_name, static_cast<char *>(prop->data.pointer));
472 }
473 continue;
474 }
475
476 std::vector<std::string> path_names = pxr::TfStringTokenize(prop->name, ":");
477
478 /* If the path does not already have a namespace prefix, prepend the default namespace
479 * specified by the user, if any. */
480 if (!default_namespace.empty() && path_names.size() < 2) {
481 path_names.insert(path_names.begin(), default_namespace);
482 }
483
484 std::vector<std::string> safe_names;
485 for (const std::string &name : path_names) {
487 }
488
489 std::string full_prop_name = pxr::SdfPath::JoinIdentifier(safe_names);
490 pxr::TfToken prop_token = pxr::TfToken(full_prop_name);
491
492 if (prim.HasAttribute(prop_token)) {
493 /* Don't overwrite existing attributes, as these may have been
494 * created by the exporter logic and shouldn't be changed. */
495 continue;
496 }
497
498 switch (prop->type) {
499 case IDP_INT:
500 if (pxr::UsdAttribute int_attr = prim.CreateAttribute(
501 prop_token, pxr::SdfValueTypeNames->Int, true))
502 {
503 int_attr.Set<int>(prop->data.val, time);
504 }
505 break;
506 case IDP_FLOAT:
507 if (pxr::UsdAttribute float_attr = prim.CreateAttribute(
508 prop_token, pxr::SdfValueTypeNames->Float, true))
509 {
510 float_attr.Set<float>(*reinterpret_cast<float *>(&prop->data.val), time);
511 }
512 break;
513 case IDP_DOUBLE:
514 if (pxr::UsdAttribute double_attr = prim.CreateAttribute(
515 prop_token, pxr::SdfValueTypeNames->Double, true))
516 {
517 double_attr.Set<double>(*reinterpret_cast<double *>(&prop->data.val), time);
518 }
519 break;
520 case IDP_STRING:
521 if (pxr::UsdAttribute str_attr = prim.CreateAttribute(
522 prop_token, pxr::SdfValueTypeNames->String, true))
523 {
524 str_attr.Set<std::string>(static_cast<const char *>(prop->data.pointer), time);
525 }
526 break;
527 case IDP_BOOLEAN:
528 if (pxr::UsdAttribute bool_attr = prim.CreateAttribute(
529 prop_token, pxr::SdfValueTypeNames->Bool, true))
530 {
531 bool_attr.Set<bool>(prop->data.val, time);
532 }
533 break;
534 case IDP_ARRAY:
535 create_vector_attrib(prim, prop, prop_token, time);
536 break;
537 case IDP_GROUP:
538 case IDP_ID:
539 case IDP_IDPARRAY:
540 /* Not supported. */
541 break;
542 }
543 }
544}
545
546void USDAbstractWriter::author_extent(const pxr::UsdGeomBoundable &boundable,
547 const pxr::UsdTimeCode time)
548{
549 /* Do not use any existing `extentsHint` that may be authored, instead recompute the extent when
550 * authoring it. */
551 const bool useExtentsHint = false;
552 const pxr::TfTokenVector includedPurposes{pxr::UsdGeomTokens->default_};
553 pxr::UsdGeomBBoxCache bboxCache(time, includedPurposes, useExtentsHint);
554 pxr::GfBBox3d bounds = bboxCache.ComputeLocalBound(boundable.GetPrim());
555
556 /* Note: An empty 'bounds' is still valid (e.g. a mesh with no vertices). */
557 pxr::VtArray<pxr::GfVec3f> extent{pxr::GfVec3f(bounds.GetRange().GetMin()),
558 pxr::GfVec3f(bounds.GetRange().GetMax())};
559
560 pxr::UsdAttribute attr_extent = boundable.CreateExtentAttr(pxr::VtValue(), true);
561 set_attribute(attr_extent, extent, time, usd_value_writer_);
562}
563
564void USDAbstractWriter::author_extent(const pxr::UsdGeomBoundable &boundable,
565 const std::optional<Bounds<float3>> &bounds,
566 const pxr::UsdTimeCode time)
567{
568 pxr::VtArray<pxr::GfVec3f> extent(2);
569 if (bounds) {
570 extent[0].Set(bounds->min);
571 extent[1].Set(bounds->max);
572 }
573
574 pxr::UsdAttribute attr_extent = boundable.CreateExtentAttr(pxr::VtValue(), true);
575 set_attribute(attr_extent, extent, time, usd_value_writer_);
576}
577
584
585} // namespace io::usd
586} // namespace blender
#define CLOG_ERROR(clg_ref,...)
Definition CLG_log.h:188
#define CLOG_WARN(clg_ref,...)
Definition CLG_log.h:189
#define BLI_assert_msg(a, msg)
virtual bool check_is_animated(const HierarchyContext &context) const
pxr::UsdShadeMaterial ensure_usd_material(const HierarchyContext &context, Material *material) const
virtual void do_write(HierarchyContext &context)=0
pxr::SdfPath get_proto_material_root_path(const HierarchyContext &context) const
void author_extent(const pxr::UsdGeomBoundable &boundable, const pxr::UsdTimeCode time)
const pxr::SdfPath & usd_path() const
void add_to_prim_map(const pxr::SdfPath &usd_path, const ID *id) const
void write_user_properties(const pxr::UsdPrim &prim, IDProperty *properties, pxr::UsdTimeCode=pxr::UsdTimeCode::Default()) const
pxr::UsdShadeMaterial ensure_usd_material_created(const HierarchyContext &context, Material *material) const
virtual bool mark_as_instance(const HierarchyContext &context, const pxr::UsdPrim &prim)
pxr::UsdTimeCode get_export_time_code() const
pxr::UsdUtilsSparseValueWriter usd_value_writer_
USDAbstractWriter(const USDExporterContext &usd_export_context)
void write_id_properties(const pxr::UsdPrim &prim, const ID &id, pxr::UsdTimeCode=pxr::UsdTimeCode::Default()) const
void write(HierarchyContext &context) override
void write_visibility(const HierarchyContext &context, const pxr::UsdTimeCode time, const pxr::UsdGeomImageable &usd_geometry)
virtual bool is_supported(const HierarchyContext *context) const
const USDExporterContext usd_export_context_
void add_to_prim_map(const pxr::SdfPath &usd_path, const ID *id) const
static void create_vector_attrib(const pxr::UsdPrim &prim, const IDProperty *prop, const pxr::TfToken &prop_token, const pxr::UsdTimeCode &time)
std::string make_safe_name(const StringRef name, bool allow_unicode)
Definition usd_utils.cc:83
void colorspace_apply_to_prim(const pxr::UsdPrim &prim)
void set_attribute(const pxr::UsdAttribute &attr, const USDT value, pxr::UsdTimeCode time, pxr::UsdUtilsSparseValueWriter &value_writer)
pxr::UsdShadeMaterial create_usd_material(const USDExporterContext &usd_export_context, pxr::SdfPath usd_path, const Material *material, const std::string &active_uvmap_name, ReportList *reports)
static const pxr::TfToken blender_ns("userProperties:blender", pxr::TfToken::Immortal)
BMesh Iterators.
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
static void write_accessibility_property(const pxr::UsdPrim &prim, const AccessibilityPropertyName &property_name, const std::string &value)
static bool is_valid_accessibility_priority(const pxr::TfToken &token)
static std::optional< AccessibilityPropertyName > parse_accessibility_property_name(IDProperty *prop, bool allow_unicode)
bool set_vec_attrib(const pxr::UsdPrim &prim, const IDProperty *prop, const pxr::TfToken &prop_token, const pxr::SdfValueTypeName &type_name, const pxr::UsdTimeCode &time)
ID_Type GS(const char *name)
Definition DNA_ID.h:410
static CLG_LogRef LOG
Definition logging.cpp:12
static std::string get_mesh_active_uvlayer_name(const Object *ob)
@ String
Definition types.hh:154
ListBaseT< struct IDProperty > group
Definition DNA_ID.h:133
eIDPropertyType type
Definition DNA_ID.h:145
IDPropertyData data
Definition DNA_ID.h:157
char custom_properties_namespace[MAX_IDPROP_NAME]
Definition usd.hh:172
enum eEvaluationMode evaluation_mode
Definition usd.hh:149
wmJobWorkerStatus * worker_status
Definition usd.hh:184
std::function< pxr::UsdTimeCode()> get_time_code