Blender V4.3
obj_export_mesh.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
9#include "BKE_attribute.hh"
10#include "BKE_customdata.hh"
11#include "BKE_deform.hh"
12#include "BKE_lib_id.hh"
13#include "BKE_material.h"
14#include "BKE_mesh.hh"
15#include "BKE_mesh_mapping.hh"
16#include "BKE_object.hh"
17
18#include "BLI_array_utils.hh"
19#include "BLI_listbase.h"
20#include "BLI_map.hh"
21#include "BLI_math_matrix.h"
22#include "BLI_math_matrix.hh"
23#include "BLI_math_rotation.h"
24#include "BLI_sort.hh"
25#include "BLI_vector_set.hh"
26
28
29#include "DNA_material_types.h"
30#include "DNA_meshdata_types.h"
31#include "DNA_modifier_types.h"
32#include "DNA_object_types.h"
33
34#include "obj_export_mesh.hh"
35
36#include "bmesh.hh"
37#include "bmesh_tools.hh"
38
39namespace blender::io::obj {
40OBJMesh::OBJMesh(Depsgraph *depsgraph, const OBJExportParams &export_params, Object *mesh_object)
41{
42 /* We need to copy the object because it may be in temporary space. */
43 Object *obj_eval = DEG_get_evaluated_object(depsgraph, mesh_object);
44 object_name_ = obj_eval->id.name + 2;
45 export_mesh_ = nullptr;
46
47 if (obj_eval->type == OB_MESH) {
48 export_mesh_ = export_params.apply_modifiers ? BKE_object_get_evaluated_mesh(obj_eval) :
50 }
51
52 if (export_mesh_) {
53 mesh_edges_ = export_mesh_->edges();
54 mesh_faces_ = export_mesh_->faces();
55 mesh_corner_verts_ = export_mesh_->corner_verts();
56 sharp_faces_ = *export_mesh_->attributes().lookup_or_default<bool>(
57 "sharp_face", bke::AttrDomain::Face, false);
58 }
59 else {
60 /* Curves and NURBS surfaces need a new mesh when they're
61 * exported in the form of vertices and edges.
62 */
63 this->set_mesh(BKE_mesh_new_from_object(depsgraph, obj_eval, true, true));
64 }
65 if (export_params.export_triangulated_mesh && obj_eval->type == OB_MESH) {
66 this->triangulate_mesh_eval();
67 }
68
69 this->materials.reinitialize(export_mesh_->totcol);
70 for (const int i : this->materials.index_range()) {
71 this->materials[i] = BKE_object_material_get_eval(obj_eval, i + 1);
72 }
73
74 set_world_axes_transform(
75 *obj_eval, export_params.forward_axis, export_params.up_axis, export_params.global_scale);
76}
77
82{
83 clear();
84}
85
86void OBJMesh::set_mesh(Mesh *mesh)
87{
88 if (owned_export_mesh_) {
89 BKE_id_free(nullptr, owned_export_mesh_);
90 }
91 owned_export_mesh_ = mesh;
92 export_mesh_ = owned_export_mesh_;
93 mesh_edges_ = mesh->edges();
94 mesh_faces_ = mesh->faces();
95 mesh_corner_verts_ = mesh->corner_verts();
96 sharp_faces_ = *export_mesh_->attributes().lookup_or_default<bool>(
97 "sharp_face", bke::AttrDomain::Face, false);
98}
99
101{
102 if (owned_export_mesh_) {
103 BKE_id_free(nullptr, owned_export_mesh_);
104 owned_export_mesh_ = nullptr;
105 }
106 export_mesh_ = nullptr;
107 corner_to_uv_index_ = {};
108 uv_coords_.clear_and_shrink();
109 corner_to_normal_index_ = {};
110 normal_coords_ = {};
111 face_order_ = {};
112 if (face_smooth_groups_) {
113 MEM_freeN(face_smooth_groups_);
114 face_smooth_groups_ = nullptr;
115 }
116}
117
118void OBJMesh::triangulate_mesh_eval()
119{
120 if (export_mesh_->faces_num <= 0) {
121 return;
122 }
123 const BMeshCreateParams bm_create_params = {false};
124 BMeshFromMeshParams bm_convert_params{};
125 bm_convert_params.calc_face_normal = true;
126 bm_convert_params.calc_vert_normal = true;
127 bm_convert_params.add_key_index = false;
128 bm_convert_params.use_shapekey = false;
129
130 /* Lower threshold where triangulation of a face starts, i.e. a quadrilateral will be
131 * triangulated here. */
132 const int triangulate_min_verts = 4;
133
134 BMesh *bmesh = BKE_mesh_to_bmesh_ex(export_mesh_, &bm_create_params, &bm_convert_params);
138 triangulate_min_verts,
139 false,
140 nullptr,
141 nullptr,
142 nullptr);
143 Mesh *triangulated = BKE_mesh_from_bmesh_for_eval_nomain(bmesh, nullptr, export_mesh_);
144 BM_mesh_free(bmesh);
145 this->set_mesh(triangulated);
146}
147
148void OBJMesh::set_world_axes_transform(const Object &obj_eval,
149 const eIOAxis forward,
150 const eIOAxis up,
151 const float global_scale)
152{
153 float3x3 axes_transform;
154 /* +Y-forward and +Z-up are the default Blender axis settings. */
155 mat3_from_axis_conversion(forward, up, IO_AXIS_Y, IO_AXIS_Z, axes_transform.ptr());
156
157 const float4x4 &object_to_world = obj_eval.object_to_world();
158 const float3x3 transform = axes_transform * float3x3(object_to_world);
159
160 world_and_axes_transform_ = float4x4(transform);
161 world_and_axes_transform_.location() = axes_transform * object_to_world.location();
162 world_and_axes_transform_[3][3] = object_to_world[3][3];
163
164 world_and_axes_transform_ = math::from_scale<float4x4>(float3(global_scale)) *
165 world_and_axes_transform_;
166
167 /* Normals need inverse transpose of the regular matrix to handle non-uniform scale. */
168 world_and_axes_normal_transform_ = math::transpose(math::invert(transform));
169
170 mirrored_transform_ = math::is_negative(world_and_axes_normal_transform_);
171}
172
174{
175 return export_mesh_->verts_num;
176}
177
179{
180 return export_mesh_->faces_num;
181}
182
184{
185 return int(uv_coords_.size());
186}
187
189{
190 return export_mesh_->edges_num;
191}
192
194{
195 return this->materials.size();
196}
197
198int OBJMesh::ith_smooth_group(const int face_index) const
199{
200 /* Calculate smooth groups first: #OBJMesh::calc_smooth_groups. */
201 BLI_assert(tot_smooth_groups_ != -NEGATIVE_INIT);
202 BLI_assert(face_smooth_groups_);
203 return face_smooth_groups_[face_index];
204}
205
206void OBJMesh::calc_smooth_groups(const bool use_bitflags)
207{
208 const bke::AttributeAccessor attributes = export_mesh_->attributes();
209 const VArraySpan sharp_edges = *attributes.lookup<bool>("sharp_edge", bke::AttrDomain::Edge);
210 const VArraySpan sharp_faces = *attributes.lookup<bool>("sharp_face", bke::AttrDomain::Face);
211 face_smooth_groups_ = BKE_mesh_calc_smoothgroups(mesh_edges_.size(),
212 mesh_faces_,
213 export_mesh_->corner_edges(),
214 sharp_edges,
215 sharp_faces,
216 &tot_smooth_groups_,
217 use_bitflags);
218}
219
221{
222 const bke::AttributeAccessor attributes = export_mesh_->attributes();
223 const VArray<int> material_indices = *attributes.lookup_or_default<int>(
224 "material_index", bke::AttrDomain::Face, 0);
225 if (material_indices.is_single() && material_indices.get_internal_single() == 0) {
226 return;
227 }
228 const VArraySpan<int> material_indices_span(material_indices);
229
230 /* Sort faces by their material index. */
231 face_order_.reinitialize(material_indices_span.size());
233 blender::parallel_sort(face_order_.begin(), face_order_.end(), [&](int a, int b) {
234 int mat_a = material_indices_span[a];
235 int mat_b = material_indices_span[b];
236 if (mat_a != mat_b) {
237 return mat_a < mat_b;
238 }
239 return a < b;
240 });
241}
242
243bool OBJMesh::is_ith_face_smooth(const int face_index) const
244{
245 return !sharp_faces_[face_index];
246}
247
248StringRef OBJMesh::get_object_name() const
249{
250 return object_name_;
251}
252
253StringRef OBJMesh::get_object_mesh_name() const
254{
255 return export_mesh_->id.name + 2;
256}
257
258void OBJMesh::store_uv_coords_and_indices()
259{
260 const StringRef active_uv_name = CustomData_get_active_layer_name(&export_mesh_->corner_data,
262 if (active_uv_name.is_empty()) {
263 uv_coords_.clear();
264 return;
265 }
266 const bke::AttributeAccessor attributes = export_mesh_->attributes();
267 const VArraySpan uv_map = *attributes.lookup<float2>(active_uv_name, bke::AttrDomain::Corner);
268 if (uv_map.is_empty()) {
269 uv_coords_.clear();
270 return;
271 }
272
273 Map<float2, int> uv_to_index;
274
275 /* We don't know how many unique UVs there will be, but this is a guess. */
276 uv_to_index.reserve(export_mesh_->verts_num);
277 uv_coords_.reserve(export_mesh_->verts_num);
278
279 corner_to_uv_index_.reinitialize(uv_map.size());
280
281 for (int index = 0; index < int(uv_map.size()); index++) {
282 float2 uv = uv_map[index];
283 int uv_index = uv_to_index.lookup_default(uv, -1);
284 if (uv_index == -1) {
285 uv_index = uv_to_index.size();
286 uv_to_index.add(uv, uv_index);
287 uv_coords_.append(uv);
288 }
289 corner_to_uv_index_[index] = uv_index;
290 }
291}
292
294static float round_float_to_n_digits(const float f, int round_digits)
295{
296 float scale = powf(10.0, round_digits);
297 return ceilf(scale * f - 0.49999999f) / scale;
298}
299
300static float3 round_float3_to_n_digits(const float3 &v, int round_digits)
301{
302 float3 ans;
303 ans.x = round_float_to_n_digits(v.x, round_digits);
304 ans.y = round_float_to_n_digits(v.y, round_digits);
305 ans.z = round_float_to_n_digits(v.z, round_digits);
306 return ans;
307}
308
309void OBJMesh::store_normal_coords_and_indices()
310{
311 /* We'll round normal components to 4 digits.
312 * This will cover up some minor differences
313 * between floating point calculations on different platforms.
314 * Since normals are normalized, there will be no perceptible loss
315 * of precision when rounding to 4 digits. */
316 constexpr int round_digits = 4;
317 VectorSet<float3> unique_normals;
318 /* We don't know how many unique normals there will be, but this is a guess. */
319 unique_normals.reserve(export_mesh_->faces_num);
320 corner_to_normal_index_.reinitialize(export_mesh_->corners_num);
321
322 /* Normals need inverse transpose of the regular matrix to handle non-uniform scale. */
323 const float3x3 transform = world_and_axes_normal_transform_;
324 auto add_normal = [&](const float3 &normal) {
325 const float3 transformed = math::normalize(transform * normal);
326 const float3 rounded = round_float3_to_n_digits(transformed, round_digits);
327 return unique_normals.index_of_or_add(rounded);
328 };
329
330 switch (export_mesh_->normals_domain()) {
332 const Span<float3> face_normals = export_mesh_->face_normals();
333 for (const int face : mesh_faces_.index_range()) {
334 const int index = add_normal(face_normals[face]);
335 corner_to_normal_index_.as_mutable_span().slice(mesh_faces_[face]).fill(index);
336 }
337 break;
338 }
340 const Span<float3> vert_normals = export_mesh_->vert_normals();
341 Array<int> vert_normal_indices(vert_normals.size());
342 const bke::LooseVertCache &verts_no_face = export_mesh_->verts_no_face();
343 if (verts_no_face.count == 0) {
344 for (const int vert : vert_normals.index_range()) {
345 vert_normal_indices[vert] = add_normal(vert_normals[vert]);
346 }
347 }
348 else {
349 for (const int vert : vert_normals.index_range()) {
350 if (!verts_no_face.is_loose_bits[vert]) {
351 vert_normal_indices[vert] = add_normal(vert_normals[vert]);
352 }
353 }
354 }
355 array_utils::gather(vert_normal_indices.as_span(),
356 mesh_corner_verts_,
357 corner_to_normal_index_.as_mutable_span());
358 break;
359 }
361 const Span<float3> corner_normals = export_mesh_->corner_normals();
362 for (const int corner : corner_normals.index_range()) {
363 corner_to_normal_index_[corner] = add_normal(corner_normals[corner]);
364 }
365 break;
366 }
367 }
368
369 normal_coords_ = unique_normals.as_span();
370}
371
372int OBJMesh::tot_deform_groups() const
373{
374 return BLI_listbase_count(&export_mesh_->vertex_group_names);
375}
376
377int16_t OBJMesh::get_face_deform_group_index(const int face_index,
378 MutableSpan<float> group_weights) const
379{
380 BLI_assert(face_index < export_mesh_->faces_num);
381 BLI_assert(group_weights.size() == BLI_listbase_count(&export_mesh_->vertex_group_names));
382 const Span<MDeformVert> dverts = export_mesh_->deform_verts();
383 if (dverts.is_empty()) {
384 return NOT_FOUND;
385 }
386
387 group_weights.fill(0);
388 bool found_any_group = false;
389 for (const int vert : mesh_corner_verts_.slice(mesh_faces_[face_index])) {
390 const MDeformVert &dv = dverts[vert];
391 for (int weight_i = 0; weight_i < dv.totweight; ++weight_i) {
392 const auto group = dv.dw[weight_i].def_nr;
393 if (group < group_weights.size()) {
394 group_weights[group] += dv.dw[weight_i].weight;
395 found_any_group = true;
396 }
397 }
398 }
399
400 if (!found_any_group) {
401 return NOT_FOUND;
402 }
403 /* Index of the group with maximum vertices. */
404 int16_t max_idx = std::max_element(group_weights.begin(), group_weights.end()) -
405 group_weights.begin();
406 return max_idx;
407}
408
409const char *OBJMesh::get_face_deform_group_name(const int16_t def_group_index) const
410{
411 const bDeformGroup &vertex_group = *(static_cast<bDeformGroup *>(
412 BLI_findlink(&export_mesh_->vertex_group_names, def_group_index)));
413 return vertex_group.name;
414}
415
416} // namespace blender::io::obj
CustomData interface, see also DNA_customdata_types.h.
const char * CustomData_get_active_layer_name(const CustomData *data, eCustomDataType type)
support for deformation groups and hooks.
void BKE_id_free(Main *bmain, void *idv)
General operations, lookup, etc. for materials.
struct Material * BKE_object_material_get_eval(struct Object *ob, short act)
Mesh * BKE_mesh_new_from_object(Depsgraph *depsgraph, Object *object, bool preserve_all_data_layers, bool preserve_origindex)
Mesh * BKE_mesh_from_bmesh_for_eval_nomain(BMesh *bm, const CustomData_MeshMasks *cd_mask_extra, const Mesh *me_settings)
BMesh * BKE_mesh_to_bmesh_ex(const Mesh *mesh, const BMeshCreateParams *create_params, const BMeshFromMeshParams *convert_params)
int * BKE_mesh_calc_smoothgroups(int edges_num, blender::OffsetIndices< int > faces, blender::Span< int > corner_edges, blender::Span< bool > sharp_edges, blender::Span< bool > sharp_faces, int *r_totgroup, bool use_bitflags)
General operations, lookup, etc. for blender objects.
Mesh * BKE_object_get_evaluated_mesh(const Object *object_eval)
Mesh * BKE_object_get_pre_modified_mesh(const Object *object)
#define BLI_assert(a)
Definition BLI_assert.h:50
void * BLI_findlink(const struct ListBase *listbase, int number) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
int BLI_listbase_count(const struct ListBase *listbase) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
bool mat3_from_axis_conversion(int src_forward, int src_up, int dst_forward, int dst_up, float r_mat[3][3])
Object * DEG_get_evaluated_object(const Depsgraph *depsgraph, Object *object)
@ CD_PROP_FLOAT2
@ MOD_TRIANGULATE_QUAD_SHORTEDGE
@ MOD_TRIANGULATE_NGON_BEAUTY
Object is a sort of wrapper for general info.
@ OB_MESH
eIOAxis
@ IO_AXIS_Y
@ IO_AXIS_Z
void BM_mesh_free(BMesh *bm)
BMesh Free Mesh.
ATTR_WARN_UNUSED_RESULT const BMVert * v
void BM_mesh_triangulate(BMesh *bm, const int quad_method, const int ngon_method, const int min_vertices, const bool tag_only, BMOperator *op, BMOpSlot *slot_facemap_out, BMOpSlot *slot_facemap_double_out)
AttributeSet attributes
Span< T > as_span() const
Definition BLI_array.hh:232
MutableSpan< T > as_mutable_span()
Definition BLI_array.hh:237
const T * end() const
Definition BLI_array.hh:314
void reinitialize(const int64_t new_size)
Definition BLI_array.hh:388
const T * begin() const
Definition BLI_array.hh:310
bool add(const Key &key, const Value &value)
Definition BLI_map.hh:271
Value lookup_default(const Key &key, const Value &default_value) const
Definition BLI_map.hh:531
int64_t size() const
Definition BLI_map.hh:927
void reserve(int64_t n)
Definition BLI_map.hh:979
constexpr int64_t size() const
Definition BLI_span.hh:494
constexpr void fill(const T &value) const
Definition BLI_span.hh:518
constexpr T * end() const
Definition BLI_span.hh:549
constexpr T * begin() const
Definition BLI_span.hh:545
constexpr int64_t size() const
Definition BLI_span.hh:253
constexpr IndexRange index_range() const
Definition BLI_span.hh:402
constexpr bool is_empty() const
Definition BLI_span.hh:261
constexpr bool is_empty() const
void reserve(const int64_t n)
Span< Key > as_span() const
int64_t index_of_or_add(const Key &key)
void calc_smooth_groups(bool use_bitflags)
OBJMesh(Depsgraph *depsgraph, const OBJExportParams &export_params, Object *mesh_object)
int ith_smooth_group(int face_index) const
local_group_size(16, 16) .push_constant(Type b
const Depsgraph * depsgraph
#define powf(x, y)
#define ceilf(x)
#define NOT_FOUND
draw_view push_constant(Type::INT, "radiance_src") .push_constant(Type capture_info_buf storage_buf(1, Qualifier::READ, "ObjectBounds", "bounds_buf[]") .push_constant(Type draw_view int
void MEM_freeN(void *vmemh)
Definition mallocn.cc:105
void gather(const GVArray &src, const IndexMask &indices, GMutableSpan dst, int64_t grain_size=4096)
void fill_index_range(MutableSpan< T > span, const T start=0)
static float round_float_to_n_digits(const float f, int round_digits)
static float3 round_float3_to_n_digits(const float3 &v, int round_digits)
MatBase< T, NumCol, NumRow > transpose(const MatBase< T, NumRow, NumCol > &mat)
bool is_negative(const MatBase< T, Size, Size > &mat)
CartesianBasis invert(const CartesianBasis &basis)
MatT from_scale(const VecBase< typename MatT::base_type, ScaleDim > &scale)
MatBase< T, NumCol, NumRow > normalize(const MatBase< T, NumCol, NumRow > &a)
MatBase< float, 4, 4 > float4x4
void parallel_sort(RandomAccessIterator begin, RandomAccessIterator end)
Definition BLI_sort.hh:23
MatBase< float, 3, 3 > float3x3
VecBase< float, 3 > float3
signed short int16_t
Definition stdint.h:76
char name[66]
Definition DNA_ID.h:425
struct MDeformWeight * dw
unsigned int def_nr
int edges_num
short totcol
int faces_num
int verts_num
blender::BitVector is_loose_bits