Commit Graph

233 Commits

Author SHA1 Message Date
Brecht Van Lommel
f165c75e14 Refactor: Add various DNA_*_enums.h and DNA_*_types.h files
* Move colorband and theme DNA to own headers
* Move some anim, curve, modifier and space enums to new headers
* Move data transfer enums to DNA
* Duplicate imbuf proxy and GPU backend enums

For a few reasons:
* Reduce number of includes in DNA headers
* Don't define enums used in DNA outside of DNA
* Move theme settings to separate header for userdef_default_theme.c
* Prepare for using default initializers in DNA headers. (#134531)

Pull Request: https://projects.blender.org/blender/blender/pulls/138831
2025-05-20 13:26:43 +02:00
Hans Goudey
bb8719030d Geometry: Initial replacement of CustomData with AttributeStorage
As described in #122398, implement read and write support for a new
attribute storage system. Currently this is only implemented to support
forward compatibility; the format used at runtime isn't changed at all.
That can be done one step at a time during the 4.5 and 5.0 development
cycles. A new experimental option for testing tells Blender to always
save with the new format.

The main benefit of the new structure is that it matches the attribute
system design, it allows for future attribute storage optimization, and
each attribute is an allocated struct, which will give pointer stability
for the Python API.

The next step is to connect the attribute API and the RNA API to
AttributeStorage for the simplest geometry type, point clouds.

Pull Request: https://projects.blender.org/blender/blender/pulls/133874
2025-05-09 17:27:07 +02:00
Campbell Barton
720b00ae50 Cleanup: use doxygen comments in BKE, consistent comment blocks
Also remove doxygen comment use for comments in the functions body.
2025-04-22 06:13:33 +00:00
Brecht Van Lommel
d061b00455 Refactor: Eliminate various unsafe memcpy and memset
Some of these already have warnings with clang-tidy, others are more
safe in case these structs get (copy) constructors in the future.

Pull Request: https://projects.blender.org/blender/blender/pulls/137404
2025-04-21 17:59:41 +02:00
Brecht Van Lommel
388a21e260 Refactor: Eliminate various void pointers passed to MEM_freeN
It's safer to pass a type so that it can be checked if delete should be
used instead. Also changes a few void pointer casts to const_cast so that
if the data becomes typed it's an error.

Pull Request: https://projects.blender.org/blender/blender/pulls/137404
2025-04-21 17:59:41 +02:00
Brecht Van Lommel
637c6497e9 Refactor: Use more typed MEM_calloc<>, avoid unnecessary size_t cast
Handle some cases that were missed in previous refactor. And eliminate
unnecessary size_t casts as these could hide issues.

Pull Request: https://projects.blender.org/blender/blender/pulls/137404
2025-04-21 17:59:41 +02:00
Hans Goudey
378f949510 Fix: Remove incorrect assert in CustomData validation
The arrays for CustomData layers aren't necessarily allocated with the guarded
allocator. Their ownership is managed by the implicit sharing system which is
required for CustomData layer data.
2025-04-18 14:02:25 -04:00
Hans Goudey
07333adc72 Cleanup: Make CustomData function private 2025-04-16 13:56:02 -04:00
Hans Goudey
63957cf541 Cleanup: Move CustomData_blend_write_prepare to proper section 2025-04-16 13:56:02 -04:00
Jacques Lucke
b92fdff697 Refactor: BLI: use FunctionRef in BLI_uniquename api
This simplifies the API usage, removes the need for intermediate structs
and reduces the overall amount of code.

Pull Request: https://projects.blender.org/blender/blender/pulls/137300
2025-04-10 20:30:45 +02:00
Bastien Montagne
7aced80eec Cleanup: blenkernel: Replace 'void' MEM_[cm]allocN with templated, type-safe MEM_[cm]allocN<T>.
The main issue of 'type-less' standard C allocations is that there is no check on
allocated type possible.

This is a serious source of annoyance (and crashes) when making some
low-level structs non-trivial, as tracking down all usages of these
structs in higher-level other structs and their allocation is... really
painful.

MEM_[cm]allocN<T> templates on the other hand do check that the
given type is trivial, at build time (static assert), which makes such issue...
trivial to catch.

NOTE: New code should strive to use MEM_new (i.e. allocation and
construction) as much as possible, even for trivial PoD types.

Pull Request: https://projects.blender.org/blender/blender/pulls/136134
2025-03-20 11:25:19 +01:00
Bastien Montagne
dd168a35c5 Refactor: Replace MEM_cnew with a type-aware template version of MEM_callocN.
The general idea is to keep the 'old', C-style MEM_callocN signature, and slowly
replace most of its usages with the new, C++-style type-safer template version.

* `MEM_cnew<T>` allocation version is renamed to `MEM_callocN<T>`.
* `MEM_cnew_array<T>` allocation version is renamed to `MEM_calloc_arrayN<T>`.
* `MEM_cnew<T>` duplicate version is renamed to `MEM_dupallocN<T>`.

Similar templates type-safe version of `MEM_mallocN` will be added soon
as well.

Following discussions in !134452.

NOTE: For now static type checking in `MEM_callocN` and related are slightly
different for Windows MSVC. This compiler seems to consider structs using the
`DNA_DEFINE_CXX_METHODS` macro as non-trivial (likely because their default
copy constructors are deleted). So using checks on trivially
constructible/destructible instead on this compiler/system.

Pull Request: https://projects.blender.org/blender/blender/pulls/134771
2025-03-05 16:35:09 +01:00
Sean Kim
0dec2b829f Cleanup: Update LayerTypeInfo#free docstring
Pull Request: https://projects.blender.org/blender/blender/pulls/135419
2025-03-04 17:29:28 +01:00
Hans Goudey
6a379f218f Cleanup: Correct comment in customdata.cc 2025-03-03 22:38:47 -05:00
Hans Goudey
947658d1b2 Refactor: Simplify CustomData functions by requiring ImplicitSharingInfo
Previously we generally expected CustomData layers to have implicit
sharing info, but we didn't require it. This PR clarifies that we do
require layers with non-null data to have implicit sharing info. This
generally makes code simpler because we don't have to have a separate
code path for non-shared layers. For example, it makes the "totelem"
arguments for layer freeing functions unnecessary, since shared data
knows how to free itself. Those arguments are removed in this PR.

Pull Request: https://projects.blender.org/blender/blender/pulls/134578
2025-02-17 19:44:54 +01:00
Hans Goudey
7c3a3669b6 Cleanup: Remove unused CustomData functions 2025-02-14 12:45:39 -05:00
Bastien Montagne
87a4c0d3a8 Refactor: Make Library.runtime an allocated pointer.
Move `Library.runtime` to be a pointer, move the related
`LibraryRuntime` struct to `BKE_library.hh`. Similar to e.g.
Mesh.runtime, that pointer is expected to always be valid, and is
allocated at readtime or when creating a new Library ID.

Related smaller changes:
* Write code now uses standard ID writing codepath for Library IDs too.
  * Runtime pointer is reset to nullptr before writing.
* Looking up a library by its absolute path is now handled through a
  dedicated utils, `search_filepath_abs`, instead of using
  `BLI_findstring`.

Pull Request: https://projects.blender.org/blender/blender/pulls/134188
2025-02-07 17:47:16 +01:00
Brecht Van Lommel
478426c937 Cleanup: Various clang-tidy warnings in blenkernel
Pull Request: https://projects.blender.org/blender/blender/pulls/133734
2025-01-31 17:03:17 +01:00
Jacques Lucke
e1753900b7 BLI: improve UTF-8 safety when copying StringRef to char buffers
Previously, there was a `StringRef.copy` method which would copy the string into
the given buffer. However, it was not defined for the case when the buffer was
too small. It moved the responsibility of making sure the buffer is large enough
to the caller.

Unfortunately, in practice that easily hides bugs in builds without asserts
which don't come up in testing much. Now, the method is replaced with
`StringRef.copy_utf8_truncated` which has much more well defined semantics and
also makes sure that the string remains valid utf-8.

This also renames `unsafe_copy` to `copy_unsafe` to make the naming more similar
to `copy_utf8_truncated`.

Pull Request: https://projects.blender.org/blender/blender/pulls/133677
2025-01-29 12:12:27 +01:00
Hans Goudey
9dd3c64c36 Cleanup: Remove unused includes in some blenkernel files
Pull Request: https://projects.blender.org/blender/blender/pulls/133067
2025-01-14 19:55:11 +01:00
Hans Goudey
973fb062a0 Cleanup: Move data_transfer_intern.h to C++
Pull Request: https://projects.blender.org/blender/blender/pulls/132461
2024-12-30 17:03:48 +01:00
Hans Goudey
f9b627d29c Mesh: Move custom normals to a generic attribute
Move `CD_CUSTOMLOOPNORMAL` to the newly added
`CD_PROP_INT16_2D` generic attribute type. This is similar to
previous commits moving specific custom data types.

The attribute name is `custom_normal`. When the attribute with
that name is on the face corner domain, the code will interpret it
as stored in the existing deformation-invariant spherical coordinate
space.

The API remains the same, with the additional opportunity to edit
custom normal data as an attribute directly (which admittedly is fairly
unintuitive currently).

See #130484.

Pull Request: https://projects.blender.org/blender/blender/pulls/130689
2024-12-04 16:06:36 +01:00
Hans Goudey
fb17e7f1a0 Fix: Incorrect size for writing new short2 attribute type 2024-11-21 15:23:32 -05:00
Hans Goudey
a4c9b691a0 Attributes: Add 2D 16 bit integer type
Add a `short2` attribute type, intended to store the existing
`CD_CUSTOMLOOPNORMAL` custom data type in order to move the custom
normal storage to generic attributes. This type probably won't get much
use besides that, but generally we don't have reasons not to add these
generic types, besides binary size. In the future we should consolidate
usage of `convert_to_static_type` to avoid large binary size increases
(about 700KB here) for this sort of addition.

This is the first step of #130484.

Pull Request: https://projects.blender.org/blender/blender/pulls/130530
2024-11-21 17:02:05 +01:00
Campbell Barton
381898b6dc Refactor: move BLI_path_util header to C++, rename to BLI_path_utils
Move to a C++ header to allow C++ features to be used there,
use the "utils" suffix as it's preferred for new files.

Ref !128147
2024-09-26 21:13:39 +10:00
Jacques Lucke
b279a6d703 Refactor: Geometry Nodes: remove AnonymousAttributeID in favor of just strings
This removes `AnonymousAttributeID` which was "attached" to every anonymous
attribute before. It adds more complexity than is justified for its
functionality.

It was originally introduced to keep the reference count of the anonymous
attribute so that it can be deleted automatically when the attribute is not
referenced anymore. For quite some time we have had deterministic attribute
life-times though which don't rely on the reference count anymore.

Anonymous attributes are sometimes shown in the UI as "friendly looking" string
like `"UV Map" from Cube`. Some information necessary for this was also stored
in `AnonymousAttributeID`. However, this can also be solved differently.
Specifically, this functionality has now been added directly to
`AttributeFieldInput`.

This refactor also allows removing `AttributeIDRef` which was mainly introduced
because we had to keep the `AnonymousAttributeID` attached with the attribute
name. Just using simple string types to identify attributes can reduce the
mental overhead quite significantly. This will be done as a separate refactor
though.

Pull Request: https://projects.blender.org/blender/blender/pulls/127081
2024-09-03 15:38:51 +02:00
Bastien Montagne
bb24677a76 Cleanup: Rename CustomData_copy to CustomData_initi_from.
And same for the `copy_layout` function. These functions do not free any
potentially existing data in destination, but expect it to be uninitialized.
Hopefully these new names will make it more clear and avoid bugs like #122160.
2024-08-26 19:11:02 +02:00
Jacques Lucke
a8667aa03f Core: introduce MemoryCounter API
We often have the situation where it would be good if we could easily estimate
the memory usage of some value (e.g. a mesh, or volume). Examples of where we
ran into this in the past:
* Undo step size.
* Caching of volume grids.
* Caching of loaded geometries for import geometry nodes.

Generally, most caching systems would benefit from the ability to know how much
memory they currently use to make better decisions about which data to free and
when. The goal of this patch is to introduce a simple general API to count the
memory usage that is independent of any specific caching system. I'm doing this
to "fix" the chicken and egg problem that caches need to know the memory usage,
but we don't really need to count the memory usage without using it for caches.
Implementing caching and memory counting at the same time make both harder than
implementing them one after another.

The main difficulty with counting memory usage is that some memory may be shared
using implicit sharing. We want to avoid double counting such memory. How
exactly shared memory is treated depends a bit on the use case, so no specific
assumptions are made about that in the API. The gathered memory usage is not
expected to be exact. It's expected to be a decent approximation. It's neither a
lower nor an upper bound unless specified by some specific type. Cache systems
generally build on top of heuristics to decide when to free what anyway.

There are two sides to this API:
1. Get the amount of memory used by one or more values. This side is used by
   caching systems and/or systems that want to present the used memory to the
   user.
2. Tell the caller how much memory is used. This side is used by all kinds of
   types that can report their memory usage such as meshes.

```cpp
/* Get how much memory is used by two meshes together. */
MemoryCounter memory;
mesh_a->count_memory(memory);
mesh_b->count_memory(memory);
int64_t bytes_used = memory.counted_bytes();

/* Tell the caller how much memory is used. */
void Mesh::count_memory(blender::MemoryCounter &memory) const
{
  memory.add_shared(this->runtime->face_offsets_sharing_info,
                    this->face_offsets().size_in_bytes());

  /* Forward memory counting to lower level types. This should be fairly common. */
  CustomData_count_memory(this->vert_data, this->verts_num, memory);
}

void CustomData_count_memory(const CustomData &data,
                             const int totelem,
                             blender::MemoryCounter &memory)
{
  for (const CustomDataLayer &layer : Span{data.layers, data.totlayer}) {
    memory.add_shared(layer.sharing_info, [&](blender::MemoryCounter &shared_memory) {
      /* Not quite correct for all types, but this is only a rough approximation anyway. */
      const int64_t elem_size = CustomData_get_elem_size(&layer);
      shared_memory.add(totelem * elem_size);
    });
  }
}
```

Pull Request: https://projects.blender.org/blender/blender/pulls/126295
2024-08-15 10:54:21 +02:00
Bastien Montagne
f9c167c1cf Refactor: CustomData: Do properly typed read/write of CD data.
Part of on-going cleanup to remove 'invalid' usages of raw data BLO API.
2024-07-31 19:52:12 +02:00
Jacques Lucke
934041e8d6 BLO: support overaligned types in SDNA
This fixes #121695. `float4x4` matrices are generally expected to be 16 byte aligned.
Currently, there is no mechanism (afaik) that allows allocating these overaligned types
when loading files from disk. This patch adds an array with alignment information for
 each type in `SDNA`. Currently, the alignment is just `__STDCPP_DEFAULT_NEW_ALIGNMENT__`
for all types and is manually set for the `mat4x4f` DNA type. The .blend file format is
not changed at all. The alignment information is purely runtime data.

In the future it would probably be good to generalize this a bit more instead of
hardcoding the alignment for `mat4x4f`, but would make it unnecessarily complex for
now because this is intended for the release branch.

Pull Request: https://projects.blender.org/blender/blender/pulls/123271
2024-06-19 12:16:24 +02:00
Jacques Lucke
f2a372b44e Fix #122870: quaternions not interpolated correctly in subdivision surface 2024-06-14 12:35:21 +02:00
Jacques Lucke
34588cd933 Fix: invalid data sharing after loading certain .blend files
This fixes a bug that happens when two drawings in the same grease pencil
data-block reference the same array. In this case, the same attribute array
pointer is written to .blend files for both drawings. However, when loading the
.blend file, it was not detected that the data is shared. Instead each drawing
would think that it was the single owner of the array even though it was shared.

The same problem can technically occur for all kinds of shared data, and not
just for grease pencil. However, only grease pencil shows this issue currently,
because it can easily happen that the same attribute is shared between different
`CustomData` within the same data-block. This very rarely happens with meshes or
curves, because different `CustomData` usually have different sizes and don't
share the same arrays.

A previous fix (cc891aa699) solved pretty much the same issues for the case
when two layers in the same `CustomData` share data. This original fix is now
generalized and is integrated with `BLO_read_shared` which makes it less error
prone. For each data-block, the `BlendDataReader` now remembers which shared
data it has loaded before so that it is not loaded again.

In the future this could be extended to support data that is shared between
data-blocks, but that's not as straight forward as one would hope currently. For
various reasons, different data-blocks could store independent data at the same
pointer. I specifically noticed that with a regression test file:
`blender/tests/data/modeling/geometry_nodes/attributes/attribute_statistics.blend`.
To support it, one solution could be to tag `BHead` in .blend files to indicate
that a specific pointer is shared and unique within the entire file. But that's
for another day.

Pull Request: https://projects.blender.org/blender/blender/pulls/122780
2024-06-07 13:22:39 +02:00
Brecht Van Lommel
15b9ae5436 Refactor: Use typed functions for blend file data reading
This makes the read and write API functions match more closely, and adds
asserts to check that the data size is as expected.

There are still a few places remaining that use BLO_read_data_address
and similar generic functions, these should eventually be replaced as well.

Pull Request: https://projects.blender.org/blender/blender/pulls/120994
2024-04-24 17:01:22 +02:00
Hans Goudey
32fc3c0c1c Fix: Resolve over-allocation for mesh tangents
For some reason, the custom data type was set as `float[4][4]`
for tangents, but they are written as `float[4]`. The overallocation
might not have been a problem, since it looks like the extra memory
was never written to. But it's still confusing and potentially bad for
performance.
2024-04-01 13:38:06 -04:00
Campbell Barton
b2e00d1285 Cleanup: use const pointer arguments 2024-03-28 20:57:50 +11:00
Jacques Lucke
b16e4bee1f Merge branch 'blender-v4.1-release' 2024-03-02 20:20:26 +01:00
Jacques Lucke
cc891aa699 Fix #115583: multiple sharing info for same data after reading file
It's possible that multiple custom data layers share the same underlying data.
This data is only written once (per data-block) currently. However, when reading
the data again, two separate `ImplicitSharingInfo` were constructed which
referenced the same underlying memory. The fix is to reuse previously created
`ImplicitSharingInfo` that manage the same data.

Pull Request: https://projects.blender.org/blender/blender/pulls/118991
2024-03-02 20:10:34 +01:00
Jacques Lucke
0e8e219d71 Undo: support implicit-sharing in memfile undo step
This adds implicit sharing support for the `MemFile` undo-step. This decreases memory
usage and increases performance.

Implicit sharing allows the undo system to take (shared) ownership of some data.
Previously, the data would always be serialized and compared to the previous undo-step.
So this turns an O(n) operation into O(1) (in terms of memory usage and time).

Read/write code that wants to make use of this has to use the new `BLO_read_shared`
and `BLO_write_shared` functions respectively. Those either make use of implicit-sharing
internally or do the "full" read/write based on a passed-in function. It seems possible to
use the same API in the future to store shared data to .blend files.

Improvements:
* Much faster undo step creation in many cases by avoiding the majority data copies
  and equality checks. This fixes #98574. I found undo step creation and undo step
  decoding to be 2-5 times faster in some demo files from the blender website and in
  some production files from the Heist project.
* Reduced memory usage when there is large data in `bmain`. For example, when
  loading the same highly subdivided mesh that I used in #106228 the memory usage
  is 1.03 GB now (compared to 1.62 GB in `main` currently). The main remaining copy
  of the data now is done by rendering code.
* Some significant performance improvements were also measured for the new grease
  pencil type (#105540).

There is one main downside of using implicit-sharing as implemented here: `MemFile`
undo steps can't be written as .blend files anymore. This has a few consequences:
* Auto-save becomes slower (up to 3x), because it can't just save the previous undo step
  anymore and does a normal save instead. This has been discussed in more detail here:
  https://devtalk.blender.org/t/remove-support-for-saving-memfile-undo-steps-as-blend-files-proposal/33544
  It would be nice to work towards asynchronous auto-save to alleviate this problem.
  Some previous work has been done to reduce the impact of this change in 41b10424c7
  and f0f304e240. This has been committed separately in efb511a76d.
* Writing `quit.blend` has to do a normal file save now. So it's a bit slower too, but it's
  less of a problem in practice.
* The `USE_WRITE_CRASH_BLEND` functionality does not work anymore. It doesn't seem
  to be used by anyone (removed in e90f5d03c4)

There are also benefits to not writing `MemFile` from undo steps to disk. It allows us to
more safely do undo-specific optimizations without risking corrupted .blend files. This
is especially useful when we want to preserve forward compatibility in some cases.
This requires converting data before writing the .blend files, but this conversion is not
necessary for undo steps. Trying to implement this kind of optimization in the past has
often lead to bugs (e.g. 43b37fbc93).

Another new problem is that it is harder to know the size of each undo step. Currently, a
heuristic is used to approximate the memory usage, but better solutions could be found
if necessary.

Pull Request: https://projects.blender.org/blender/blender/pulls/106903
2024-02-29 17:14:58 +01:00
Jacques Lucke
fac64c3378 Cleanup: extract function to read custom data layer data 2024-02-29 14:15:04 +01:00
Jacques Lucke
43b5bd02d4 Cleanup: extract function to write custom data layer data 2024-02-29 14:07:16 +01:00
Jeroen Bakker
17842d4d40 Fix: CustomData crash in debug builds with empty name
Due to a recent change the name of a layer is passed using a string ref
but the check if it is filled was done by checking if the first char
was zero. This fails as string ref first does the bound checks.

This is fixed by using `!is_empty()`. There might be more places, but this
one fired when loading production files.

Issue introduced by a39e8a4ab9

Pull Request: https://projects.blender.org/blender/blender/pulls/118605
2024-02-22 18:01:06 +01:00
Hans Goudey
77cba3d551 Geometry Nodes: Sample grid node
This simple node finds the values of a volume grid at
positions in the local space used in geometry nodes
evaluation. There are three interpolation modes to
choose how to mix values between neighboring voxels.

For the implementation, first the values are sampled
with the grid's type directly, then implicit type conversions
are used to get the final type. This makes gives us flexibility
in case there aren't exact matches in support between grid
types and Blender types.

Pull Request: https://projects.blender.org/blender/blender/pulls/118397
2024-02-22 17:58:09 +01:00
Brecht Van Lommel
0f2064bc3b Revert changes from main commits that were merged into blender-v4.1-release
The last good commit was 4bf6a2e564.
2024-02-19 15:59:59 +01:00
Hans Goudey
1cfe9dd08c Geometry Nodes: Matrix socket type, attribute type, and initial nodes
Implements the design from #116067.
The socket type is called "Matrix" but it is often referred to as "Transform"
when that's what it is semantically. The attribute type is "4x4 Matrix" since
that's a lower level choice. Currently matrix sockets are always passed
around internally as `float4x4`, but that can be optimized in the future
when smaller types would give the same behavior.

A new "Matrix" utilities category has the following set of initial nodes"
- **Combine Transform**
- **Separate Transform**
- **Multiply Matrices**
- **Transform Direction**
- **Transform Vector**
- **Invert Matrix**
- **Transpose Matrix**

The nodes and socket type are behind an experimental flag for now,
which will give us time to make sure it's the right set of initial nodes.
The viewer node overlay doesn't support matrices-- they aren't supported
for rendering in general. They also aren't supported in the modifier interface
currently. But they are supported in the spreadsheet, where the value is
displayed in a tooltip.

Pull Request: https://projects.blender.org/blender/blender/pulls/116166
2024-02-13 18:59:36 +01:00
Hans Goudey
e9b8460ebe Cleanup: Use blender::int2 instead of vec2i 2024-02-12 10:45:02 -05:00
Bastien Montagne
45e7827898 Clenup: Move BLT headers to Cpp.
Noisy but fairly straight forward.
2024-02-09 18:59:42 +01:00
Hans Goudey
30f8dfc474 Cleanup: Fix string format warning after recent commit 2024-02-08 12:21:33 -05:00
Hans Goudey
a39e8a4ab9 Cleanup: Use StringRef instead of C strings in CustomData API
This simplifies some code. It may improve performance slightly too,
because of faster string comparisons with a known length.

Pull Request: https://projects.blender.org/blender/blender/pulls/117996
2024-02-08 16:56:42 +01:00
Hans Goudey
961783c444 Cleanup: Move BKE_deform.h to C++ 2024-01-29 19:04:13 -05:00
Campbell Barton
c00cd902ce Cleanup: use usernames in code-comments
Also remove my name in a few cases where it doesn't seem necessary.
2024-01-14 11:50:02 +11:00