Commit Graph

46 Commits

Author SHA1 Message Date
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 06eda2a484 Cleanup: Remove most indirect includes of BKE_customdata.hh
Some common headers were including this. Separating the includes
will ideally lead to better conceptual separation between CustomData
and the attribute API too. Mostly the change is adding the file to
places where it was included indirectly before. But some code is
shuffled around to hopefully better places as well.
2023-12-26 23:59:44 -05:00
Hans Goudey 9a28852494 Cleanup: Generalize some attribute propagation functions
Add a function that copies selected values to groups of values in the
result array. Add a runtime-typed version and a version for affecting
all attributes. Also make the "gather_group_to_group" follow the
same pattern.
2023-11-22 15:48:42 -05:00
Hans Goudey 3d57bc4397 Cleanup: Move several blenkernel headers to C++
Mostly focus on areas where we're already using C++ features,
where combining C and C++ APIs is getting in the way.

Pull Request: https://projects.blender.org/blender/blender/pulls/114972
2023-11-16 11:41:55 +01:00
Campbell Barton e955c94ed3 License Headers: Set copyright to "Blender Authors", add AUTHORS
Listing the "Blender Foundation" as copyright holder implied the Blender
Foundation holds copyright to files which may include work from many
developers.

While keeping copyright on headers makes sense for isolated libraries,
Blender's own code may be refactored or moved between files in a way
that makes the per file copyright holders less meaningful.

Copyright references to the "Blender Foundation" have been replaced with
"Blender Authors", with the exception of `./extern/` since these this
contains libraries which are more isolated, any changed to license
headers there can be handled on a case-by-case basis.

Some directories in `./intern/` have also been excluded:

- `./intern/cycles/` it's own `AUTHORS` file is planned.
- `./intern/opensubdiv/`.

An "AUTHORS" file has been added, using the chromium projects authors
file as a template.

Design task: #110784

Ref !110783.
2023-08-16 00:20:26 +10:00
Hans Goudey 1e4b80fed9 Attributes: Add quaternion rotation type
Add a quaternion attribute type that will be used in combination with
rotation sockets for geometry nodes to give a more intuitive experience
and better performance when using rotations.

The most interesting part is probably the interpolation, the rest is
the same as the last attribute type addition, 988f23cec3.
We need to interpolate multiple values with different weights.
Based on Sybren's suggestion, this uses the `expmap` methods from
4805a54525 for that.

This also refactors `SimpleMixerWithAccumulationType` to use a
function rather than a cast to convert to the accumulation type.

See #92967

Pull Request: https://projects.blender.org/blender/blender/pulls/108678
2023-06-12 15:49:50 +02:00
Sergey Sharybin c1bc70b711 Cleanup: Add a copyright notice to files and use SPDX format
A lot of files were missing copyright field in the header and
the Blender Foundation contributed to them in a sense of bug
fixing and general maintenance.

This change makes it explicit that those files are at least
partially copyrighted by the Blender Foundation.

Note that this does not make it so the Blender Foundation is
the only holder of the copyright in those files, and developers
who do not have a signed contract with the foundation still
hold the copyright as well.

Another aspect of this change is using SPDX format for the
header. We already used it for the license specification,
and now we state it for the copyright as well, following the
FAQ:

    https://reuse.software/faq/
2023-05-31 16:19:06 +02:00
Jacques Lucke 2cfcb8b0b8 BLI: refactor IndexMask for better performance and memory usage
Goals of this refactor:
* Reduce memory consumption of `IndexMask`. The old `IndexMask` uses an
  `int64_t` for each index which is more than necessary in pretty much all
  practical cases currently. Using `int32_t` might still become limiting
  in the future in case we use this to index e.g. byte buffers larger than
  a few gigabytes. We also don't want to template `IndexMask`, because
  that would cause a split in the "ecosystem", or everything would have to
  be implemented twice or templated.
* Allow for more multi-threading. The old `IndexMask` contains a single
  array. This is generally good but has the problem that it is hard to fill
  from multiple-threads when the final size is not known from the beginning.
  This is commonly the case when e.g. converting an array of bool to an
  index mask. Currently, this kind of code only runs on a single thread.
* Allow for efficient set operations like join, intersect and difference.
  It should be possible to multi-thread those operations.
* It should be possible to iterate over an `IndexMask` very efficiently.
  The most important part of that is to avoid all memory access when iterating
  over continuous ranges. For some core nodes (e.g. math nodes), we generate
  optimized code for the cases of irregular index masks and simple index ranges.

To achieve these goals, a few compromises had to made:
* Slicing of the mask (at specific indices) and random element access is
  `O(log #indices)` now, but with a low constant factor. It should be possible
  to split a mask into n approximately equally sized parts in `O(n)` though,
  making the time per split `O(1)`.
* Using range-based for loops does not work well when iterating over a nested
  data structure like the new `IndexMask`. Therefor, `foreach_*` functions with
  callbacks have to be used. To avoid extra code complexity at the call site,
  the `foreach_*` methods support multi-threading out of the box.

The new data structure splits an `IndexMask` into an arbitrary number of ordered
`IndexMaskSegment`. Each segment can contain at most `2^14 = 16384` indices. The
indices within a segment are stored as `int16_t`. Each segment has an additional
`int64_t` offset which allows storing arbitrary `int64_t` indices. This approach
has the main benefits that segments can be processed/constructed individually on
multiple threads without a serial bottleneck. Also it reduces the memory
requirements significantly.

For more details see comments in `BLI_index_mask.hh`.

I did a few tests to verify that the data structure generally improves
performance and does not cause regressions:
* Our field evaluation benchmarks take about as much as before. This is to be
  expected because we already made sure that e.g. add node evaluation is
  vectorized. The important thing here is to check that changes to the way we
  iterate over the indices still allows for auto-vectorization.
* Memory usage by a mask is about 1/4 of what it was before in the average case.
  That's mainly caused by the switch from `int64_t` to `int16_t` for indices.
  In the worst case, the memory requirements can be larger when there are many
  indices that are very far away. However, when they are far away from each other,
  that indicates that there aren't many indices in total. In common cases, memory
  usage can be way lower than 1/4 of before, because sub-ranges use static memory.
* For some more specific numbers I benchmarked `IndexMask::from_bools` in
  `index_mask_from_selection` on 10.000.000 elements at various probabilities for
  `true` at every index:
  ```
  Probability      Old        New
  0              4.6 ms     0.8 ms
  0.001          5.1 ms     1.3 ms
  0.2            8.4 ms     1.8 ms
  0.5           15.3 ms     3.0 ms
  0.8           20.1 ms     3.0 ms
  0.999         25.1 ms     1.7 ms
  1             13.5 ms     1.1 ms
  ```

Pull Request: https://projects.blender.org/blender/blender/pulls/104629
2023-05-24 18:11:41 +02:00
Hans Goudey 4f2ac09886 Cleanup: Reduce binary size by deduplicating attribute processing
This makes the Blender binary 350 KB smaller. The largest change comes
from using `FunctionRef` instead of a template when gathering indices to
mix in the extrude node (which has no performance cost). The rest of the
change comes from consolidating uses of code generation for all
attribute types. This brings us a bit further in the direction of
unifying attribute propagation.

Pull Request: https://projects.blender.org/blender/blender/pulls/107823
2023-05-12 14:44:39 +02:00
Hans Goudey 367145209c Cleanup: Move attribute_math to proper blenkernel namespace
The fact that blenlib doesn't know about the set of attribute types is
actually an important detail right now that can influence how things
are designed. Longer term it would be good to consolidate many of
these attribute propagation algorithms anyway.
2023-05-03 12:10:54 -04:00
Hans Goudey 988f23cec3 Attributes: Add 2D integer vector attribute type
This type will be used to store mesh edges in #106638, but it could
be used for anything else too. This commit adds support for:
- The new type in the Python API
- Editing the type in the edit mode "Attribute Set" operator
- Rendering the type in EEVEE and Cycles for all geometry types
- Geometry nodes attribute interpolation and mixing
- Viewing the type in the spreadsheet and using row filters

The attribute uses the `blender::int2` type in most code, and
the `vec2i` DNA type in C code when necessary. The enum names
are based on `INT32_2D` for consistency with `INT8` and `INT32`.

Pull Request: https://projects.blender.org/blender/blender/pulls/106677
2023-04-14 16:08:05 +02:00
Sergey Sharybin d32d787f5f Clang-Format: Allow empty functions to be single-line
For example

```
OIIOOutputDriver::~OIIOOutputDriver()
{
}
```

becomes

```
OIIOOutputDriver::~OIIOOutputDriver() {}
```

Saves quite some vertical space, which is especially handy for
constructors.

Pull Request: https://projects.blender.org/blender/blender/pulls/105594
2023-03-29 16:50:54 +02:00
Iliya Katueshenock 18e386613c Attributes: Remove asserts for DefaultMixer negative weight
The attribute smoothing node asks for the ability to have a factor
outside the range of 0 and 1. The problem with this is that there is a
negative weight assertion for some of the mixers. If mixing between 0
and 1, then at a factor of 2, one of the elements will be negative.

Differential Revision: https://developer.blender.org/D16351
2022-12-02 14:44:54 -06:00
Campbell Barton 333e41eac6 Cleanup: replace C-style casts with functional casts for numeric types
Use function style casts in C++ headers & source.
2022-09-26 17:58:36 +10:00
Mattias Fredriksson 095516403c Curves: Correct and improve Catmull Rom interpolation
Correct interpolation of integer POD types for Catmull Rom
interpolation as implemented in eaf416693d.

**Problem description**
`attribute_math::DefaultMixer<T>::mix_in()` assumes/asserts positive
weights but the basis function for Catmull-Rom splines generates
negative weights (see image in revision). Passing negative weights will
yield correct result as sum(weights) = 1 (after multiplication by 0.5)
but the assert is still triggered in debug builds. This patch adjusts
the behavior by extending the mix functions with mix4(). The benefit
of using mix#() over a DefaultMixer is that the result no longer needs
to be divided by the weight sum, instead utilizing that the basis weight
sum is constant (see plot).

**Changes**
 * Added mix4() and updated catmull_rom::interpolate() to use it.
 * Removed TODOs from catmull_rom functions.
 * Moved mix definitions to be ordered as 2, 3, 4 in the header.

**Implementation specifics**
`catmull_rom::interpolate()` uses a constexpr to differentiate between
POD types which multiplies the result with 0.5 after weighting the
values, this reduces the number of multiplications for 1D, 2D, 3D
vectors (https://godbolt.org/z/8M1z9Pxx6). While this could be
considered unnecessary, I didn't want to change the original behavior
as it could influence performance (did not measure performance here
as this should ensure the logic is ~identical for FP types).

Differential Revision: https://developer.blender.org/D15997
2022-09-17 21:53:58 -05:00
Erik Abrahamsson 6e8709caa3 Cleanup: Fix typo Propatation -> Propagation
Fixes the typo in the struct `DefaultPropatationMixerStruct`.
2022-08-07 19:48:28 +02:00
Iliay Katueshenock 55a332da64 Attribute Math: Improve performance of mixer in some cases
The `DefaultMixer` for mixing generic data types has some issues:
1. The full buffer is always zeroed, even if only some is used.
2. Finalizing also works on all values, even if only some are used.
3. "mixing" doesn't allow setting the first value, requiring that
everything is cleared beforehand.

This commit adds the following functionality:
1. Constructor with the specified `IndexMask` for preliminary zeroing.
2. `set` method to overwrite the value.
3. `finalize` with the specified mask to process a subset of values.

This is useful in situations where you want to use the
DefaultMixer without having to overwrite all the values many times.

A performance improvement was observed for NURBS curve evaluation and
attribute interpolation from the point to curve domain of about 15% and
35% respectively (100,000 curves).

Differential Revision: https://developer.blender.org/D15434
2022-08-03 10:18:02 -05:00
Campbell Barton 44bac4c8cc Cleanup: use 'e' prefix for enum types
- CustomDataType -> eCustomDataType
- CustomDataMask -> eCustomDataMask
- AttributeDomain -> eAttrDomain
- NamedAttributeUsage -> eNamedAttrUsage
2022-06-01 15:38:48 +10:00
Jacques Lucke 2e70af5cd5 Fix T97761: incorrect mixing of integers
Sometimes integers are mixed using float weights. In those cases
the mixed result has to be converted from into float again.
Previously, this was done using a simple cast, which was unexpected
because e.g. 14.999 would be cast to 14 instead of 15.
Now, the values are rounded properly.

This can affect existing files unfortunately without a good option
for versioning. Gladly, very few files seem to depend on the details
of the old behavior.

Differential Revision: https://developer.blender.org/D14892
2022-05-18 17:00:38 +02:00
Jacques Lucke b9799dfb8a Geometry Nodes: better support for byte color attributes
Since {rBeae36be372a6b16ee3e76eff0485a47da4f3c230} the distinction
between float and byte colors is more explicit in the ui. So far, geometry
nodes couldn't really deal with byte colors in general. This patch fixes that.
There is still only one color socket, which contains float colors. Conversion
to and from byte colors is done when read from or writing to attributes.

* Support writing to byte color attributes in Store Named Attribute node.
* Support converting to/from byte color in attribute conversion operator.
* Support propagating byte color attributes.
* Add all the implicit conversions from byte colors to the other types.
* Display byte colors as integers in spreadsheet.

Differential Revision: https://developer.blender.org/D14705
2022-04-21 16:11:26 +02:00
Hans Goudey 6d61cf4e80 Cleanup: Typo, improve variable names
`accumulate_counts_to_offsets` wasn't just used for the point domain.
2022-03-23 23:50:10 -05:00
Jacques Lucke 8711483632 BLI: generalize converting CPPType to static type
Previously, the conversion was done manually for a fixed set of types.
Now, there is a more general utility that can be used in other contexts
(outside of geometry nodes attribute processing) as well.
2022-03-19 10:57:40 +01:00
Jacques Lucke 2252bc6a55 BLI: move CPPType to blenlib
For more detail about `CPPType`, see `BLI_cpp_type.hh` and D14367.

Differential Revision: https://developer.blender.org/D14367
2022-03-18 10:57:45 +01:00
Hans Goudey a9f023e226 BLI: Change dependencies in vector math files
This patch reverses the dependency between `BLI_math_vec_types.hh` and
`BLI_math_vector.hh`. Now the higher level `blender::math` functions
depend on the header that defines the types they work with, rather than
the other way around.

The initial goal was to allow defining an `enable_if` in the types header
and using it in the math header. But I also think this operations to types
dependency is more natural anyway.

This required changing the includes some files used from the type
header to the math implementation header. I took that change a bit
further removing the C vector math header from the C++ header;
I think that helps to make the transition between the two systems
clearer.

Differential Revision: https://developer.blender.org/D14112
2022-02-15 10:27:03 -06:00
Campbell Barton c434782e3a File headers: SPDX License migration
Use a shorter/simpler license convention, stops the header taking so
much space.

Follow the SPDX license specification: https://spdx.org/licenses

- C/C++/objc/objc++
- Python
- Shell Scripts
- CMake, GNUmakefile

While most of the source tree has been included

- `./extern/` was left out.
- `./intern/cycles` & `./intern/atomic` are also excluded because they
  use different header conventions.

doc/license/SPDX-license-identifiers.txt has been added to list SPDX all
used identifiers.

See P2788 for the script that automated these edits.

Reviewed By: brecht, mont29, sergey

Ref D14069
2022-02-11 09:14:36 +11:00
Hans Goudey e7912dfa19 Attributes: Infrastructure for generic 8-bit integer data type
This commit adds infrastructure for 8 bit signed integer attributes.
This can be useful given the discussion in T94193, where we want to
store spline type, Bezier handle type, and other small enums as
attributes.

This is only exposed in the interface in the attribute lists, so it
shouldn't be an option in geometry nodes, at least for now.
I expect that this type won't be used directly very often, it
should mostly be cast to an enum type. However, with support
for 8 bit integers, it also makes sense to add things like mixing
implementations for consistency.

Differential Revision: https://developer.blender.org/D13721
2022-02-04 10:29:11 -06:00
Hans Goudey 95981c9876 Geometry Nodes: Extrude Mesh Node
This patch introduces an extrude node with three modes. The vertex mode
is quite simple, and just attaches new edges to the selected vertices.
The edge mode attaches new faces to the selected edges. The faces mode
extrudes patches of selected faces, or each selected face individually,
depending on the "Individual" boolean input.

The default value of the "Offset" input is the mesh's normals, which
can be scaled with the "Offset Scale" input.

**Attribute Propagation**
Attributes are transferred to the new elements with specific rules.
Attributes will never change domains for interpolations. Generally
boolean attributes are propagated with "or", meaning any connected
"true" value that is mixed in for other types will cause the new value
to be "true" as well. The `"id"` attribute does not have any special
handling currently.

Vertex Mode
 - Vertex: Copied values of selected vertices.
 - Edge: Averaged values of selected edges. For booleans, edges are
   selected if any connected edges are selected.
Edge Mode
 - Vertex: Copied values of extruded vertices.
 - Connecting edges (vertical): Average values of connected extruded
   edges. For booleans, the edges are selected if any connected
   extruded edges are selected.
 - Duplicate edges: Copied values of selected edges.
 - Face: Averaged values of all faces connected to the selected edge.
   For booleans, faces are selected if any connected original faces
   are selected.
 - Corner: Averaged values of corresponding corners in all faces
   connected to selected edges. For booleans, corners are selected
   if one of those corners are selected.
Face Mode
 - Vertex: Copied values of extruded vertices.
 - Connecting edges (vertical): Average values of connected selected
   edges, not including the edges "on top" of extruded regions.
   For booleans, edges are selected when any connected extruded edges
   were selected.
 - Duplicate edges: Copied values of extruded edges.
 - Face: Copied values of the corresponding selected faces.
 - Corner: Copied values of corresponding corners in selected faces.
Individual Face Mode
 - Vertex: Copied values of extruded vertices.
 - Connecting edges (vertical): Average values of the two neighboring
   edges on each extruded face. For booleans, edges are selected
   when at least one neighbor on the extruded face was selected.
 - Duplicate edges: Copied values of extruded edges.
 - Face: Copied values of the corresponding selected faces.
 - Corner: Copied values of corresponding corners in selected faces.

**Differences from edit mode**
In face mode (non-individual), the behavior can be different than the
extrude tools in edit mode-- this node doesn't handle keeping the back-
faces around in the cases that the edit mode tools do. The planned
"Solidify" node will handle that use case instead. Keeping this node
simpler and faster is preferable at this point, especially because that
sort of "smart" behavior is not that predictable and makes less sense
in a procedural context.

In the future, an "Even Offset" option could be added to this node
hopefully fairly simply. For now it is left out in order to keep
the patch simpler.

**Implementation**
For the implementation, the `Mesh` data structure is used directly
rather than converting to `BMesh` and back like D12224. This optimizes
for large extrusion operations rather than many sequential extrusions.
While this is potentially more verbose, it has some important benefits:
First, there is no conversion to and from `BMesh`. The code only has
to fill arrays and it can do that all at once, making each component of
the algorithm much easier to optimize. It also makes the attribute
interpolation more explicit, and likely faster. Only limited topology
maps must be created in most cases.

While there are some necessary loops and allocations with the size of
the entire mesh, I tried to keep everything I could on the order of the
size of the selection rather than the size of the mesh. In that respect,
the individual faces mode is the best, since there is no topology
information necessary, and the amount of work just depends on the size
of the selection.

Modifying an existing mesh instead of generating a new one was a bit
of a toss-up, but has a few potential benefits:
 - Avoids manually copying over attribute data for original elements.
 - Avoids some overhead of creating a new mesh.
 - Can potentially take advantage of future ammortized mesh growth.
This could be changed easily if it turns out to be the wrong choice.

Differential Revision: https://developer.blender.org/D13709
2022-01-23 22:42:49 -06:00
Clément Foucault d43b5791e0 BLI: Refactor vector types & functions to use templates
This patch implements the vector types (i.e:`float2`) by making heavy
usage of templating. All vector functions are now outside of the vector
classes (inside the `blender::math` namespace) and are not vector size
dependent for the most part.

In the ongoing effort to make shaders less GL centric, we are aiming
to share more code between GLSL and C++ to avoid code duplication.

####Motivations:
- We are aiming to share UBO and SSBO structures between GLSL and C++.
This means we will use many of the existing vector types and others
we currently don't have (uintX, intX). All these variations were
asking for many more code duplication.
- Deduplicate existing code which is duplicated for each vector size.
- We also want to share small functions. Which means that vector
functions should be static and not in the class namespace.
- Reduce friction to use these types in new projects due to their
incompleteness.
- The current state of the `BLI_(float|double|mpq)(2|3|4).hh` is a
bit of a let down. Most clases are incomplete, out of sync with each
others with different codestyles, and some functions that should be
static are not (i.e: `float3::reflect()`).

####Upsides:
- Still support `.x, .y, .z, .w` for readability.
- Compact, readable and easilly extendable.
- All of the vector functions are available for all the vectors types
and can be restricted to certain types. Also template specialization
let us define exception for special class (like mpq).
- With optimization ON, the compiler unroll the loops and performance
is the same.

####Downsides:
- Might impact debugability. Though I would arge that the bugs are
rarelly caused by the vector class itself (since the operations are
quite trivial) but by the type conversions.
- Might impact compile time. I did not saw a significant impact since
the usage is not really widespread.
- Functions needs to be rewritten to support arbitrary vector length.
For instance, one can't call `len_squared_v3v3` in
`math::length_squared()` and call it a day.
- Type cast does not work with the template version of the `math::`
vector functions. Meaning you need to manually cast `float *` and
`(float *)[3]` to `float3` for the function calls.
i.e: `math::distance_squared(float3(nearest.co), positions[i]);`
- Some parts might loose in readability:
`float3::dot(v1.normalized(), v2.normalized())`
becoming
`math::dot(math::normalize(v1), math::normalize(v2))`
But I propose, when appropriate, to use
`using namespace blender::math;` on function local or file scope to
increase readability.
`dot(normalize(v1), normalize(v2))`

####Consideration:
- Include back `.length()` method. It is quite handy and is more C++
oriented.
- I considered the GLM library as a candidate for replacement. It felt
like too much for what we need and would be difficult to extend / modify
to our needs.
- I used Macros to reduce code in operators declaration and potential
copy paste bugs. This could reduce debugability and could be reverted.
- This touches `delaunay_2d.cc` and the intersection code. I would like
to know @howardt opinion on the matter.
- The `noexcept` on the copy constructor of `mpq(2|3)` is being removed.
But according to @JacquesLucke it is not a real problem for now.

I would like to give a huge thanks to @JacquesLucke who helped during this
and pushed me to reduce the duplication further.

Reviewed By: brecht, sergey, JacquesLucke

Differential Revision: https://developer.blender.org/D13791
2022-01-12 12:57:07 +01:00
Clément Foucault fb6bd88644 Revert "BLI: Refactor vector types & functions to use templates"
Includes unwanted changes

This reverts commit 46e049d0ce.
2022-01-12 12:50:02 +01:00
Clment Foucault 46e049d0ce BLI: Refactor vector types & functions to use templates
This patch implements the vector types (i.e:`float2`) by making heavy
usage of templating. All vector functions are now outside of the vector
classes (inside the `blender::math` namespace) and are not vector size
dependent for the most part.

In the ongoing effort to make shaders less GL centric, we are aiming
to share more code between GLSL and C++ to avoid code duplication.

####Motivations:
 - We are aiming to share UBO and SSBO structures between GLSL and C++.
 This means we will use many of the existing vector types and others
 we currently don't have (uintX, intX). All these variations were
 asking for many more code duplication.
 - Deduplicate existing code which is duplicated for each vector size.
 - We also want to share small functions. Which means that vector
 functions should be static and not in the class namespace.
 - Reduce friction to use these types in new projects due to their
 incompleteness.
 - The current state of the `BLI_(float|double|mpq)(2|3|4).hh` is a
 bit of a let down. Most clases are incomplete, out of sync with each
 others with different codestyles, and some functions that should be
 static are not (i.e: `float3::reflect()`).

####Upsides:
 - Still support `.x, .y, .z, .w` for readability.
 - Compact, readable and easilly extendable.
 - All of the vector functions are available for all the vectors types
 and can be restricted to certain types. Also template specialization
 let us define exception for special class (like mpq).
 - With optimization ON, the compiler unroll the loops and performance
 is the same.

####Downsides:
 - Might impact debugability. Though I would arge that the bugs are
 rarelly caused by the vector class itself (since the operations are
 quite trivial) but by the type conversions.
 - Might impact compile time. I did not saw a significant impact since
 the usage is not really widespread.
 - Functions needs to be rewritten to support arbitrary vector length.
 For instance, one can't call `len_squared_v3v3` in
 `math::length_squared()` and call it a day.
 - Type cast does not work with the template version of the `math::`
 vector functions. Meaning you need to manually cast `float *` and
 `(float *)[3]` to `float3` for the function calls.
 i.e: `math::distance_squared(float3(nearest.co), positions[i]);`
 - Some parts might loose in readability:
 `float3::dot(v1.normalized(), v2.normalized())`
 becoming
 `math::dot(math::normalize(v1), math::normalize(v2))`
 But I propose, when appropriate, to use
 `using namespace blender::math;` on function local or file scope to
 increase readability.
 `dot(normalize(v1), normalize(v2))`

####Consideration:
 - Include back `.length()` method. It is quite handy and is more C++
 oriented.
 - I considered the GLM library as a candidate for replacement. It felt
 like too much for what we need and would be difficult to extend / modify
 to our needs.
 - I used Macros to reduce code in operators declaration and potential
 copy paste bugs. This could reduce debugability and could be reverted.
 - This touches `delaunay_2d.cc` and the intersection code. I would like
 to know @howardt opinion on the matter.
 - The `noexcept` on the copy constructor of `mpq(2|3)` is being removed.
 But according to @JacquesLucke it is not a real problem for now.

I would like to give a huge thanks to @JacquesLucke who helped during this
and pushed me to reduce the duplication further.

Reviewed By: brecht, sergey, JacquesLucke

Differential Revision: https://developer.blender.org/D13791
2022-01-12 12:47:43 +01:00
Clément Foucault e5766752d0 Revert "BLI: Refactor vector types & functions to use templates"
Reverted because the commit removes a lot of commits.

This reverts commit a2c1c368af.
2022-01-12 12:44:26 +01:00
Clément Foucault a2c1c368af BLI: Refactor vector types & functions to use templates
This patch implements the vector types (i.e:float2) by making heavy
usage of templating. All vector functions are now outside of the vector
classes (inside the blender::math namespace) and are not vector size
dependent for the most part.

In the ongoing effort to make shaders less GL centric, we are aiming
to share more code between GLSL and C++ to avoid code duplication.

Motivations:
- We are aiming to share UBO and SSBO structures between GLSL and C++.
  This means we will use many of the existing vector types and others we
  currently don't have (uintX, intX). All these variations were asking
  for many more code duplication.
- Deduplicate existing code which is duplicated for each vector size.
- We also want to share small functions. Which means that vector functions
  should be static and not in the class namespace.
- Reduce friction to use these types in new projects due to their
  incompleteness.
- The current state of the BLI_(float|double|mpq)(2|3|4).hh is a bit of a
  let down. Most clases are incomplete, out of sync with each others with
  different codestyles, and some functions that should be static are not
  (i.e: float3::reflect()).

Upsides:
- Still support .x, .y, .z, .w for readability.
- Compact, readable and easilly extendable.
- All of the vector functions are available for all the vectors types and
  can be restricted to certain types. Also template specialization let us
  define exception for special class (like mpq).
- With optimization ON, the compiler unroll the loops and performance is
  the same.

Downsides:
- Might impact debugability. Though I would arge that the bugs are rarelly
  caused by the vector class itself (since the operations are quite trivial)
  but by the type conversions.
- Might impact compile time. I did not saw a significant impact since the
  usage is not really widespread.
- Functions needs to be rewritten to support arbitrary vector length. For
  instance, one can't call len_squared_v3v3 in math::length_squared() and
  call it a day.
- Type cast does not work with the template version of the math:: vector
  functions. Meaning you need to manually cast float * and (float *)[3] to
  float3 for the function calls.
  i.e: math::distance_squared(float3(nearest.co), positions[i]);
- Some parts might loose in readability:
  float3::dot(v1.normalized(), v2.normalized())
  becoming
  math::dot(math::normalize(v1), math::normalize(v2))
  But I propose, when appropriate, to use
  using namespace blender::math; on function local or file scope to
  increase readability. dot(normalize(v1), normalize(v2))

Consideration:
- Include back .length() method. It is quite handy and is more C++
  oriented.
- I considered the GLM library as a candidate for replacement.
  It felt like too much for what we need and would be difficult to
  extend / modify to our needs.
- I used Macros to reduce code in operators declaration and potential
  copy paste bugs. This could reduce debugability and could be reverted.
- This touches delaunay_2d.cc and the intersection code. I would like to
  know @Howard Trickey (howardt) opinion on the matter.
- The noexcept on the copy constructor of mpq(2|3) is being removed.
  But according to @Jacques Lucke (JacquesLucke) it is not a real problem
  for now.

I would like to give a huge thanks to @Jacques Lucke (JacquesLucke) who
helped during this and pushed me to reduce the duplication further.

Reviewed By: brecht, sergey, JacquesLucke

Differential Revision: http://developer.blender.org/D13791
2022-01-12 12:19:39 +01:00
Campbell Barton 3d3bc74884 Cleanup: remove redundant const qualifiers for POD types
MSVC used to warn about const mismatch for arguments passed by value.
Remove these as newer versions of MSVC no longer show this warning.
2022-01-07 14:16:26 +11:00
Campbell Barton 4b9ff3cd42 Cleanup: comment blocks, trailing space in comments 2021-06-24 15:59:34 +10:00
Jeroen Bakker cb8a6814fd Blenlib: Explicit Colors.
Colors are often thought of as being 4 values that make up that can make any color.
But that is of course too limited. In C we didn’t spend time to annotate what we meant
when using colors.

Recently `BLI_color.hh` was made to facilitate color structures in CPP. CPP has possibilities to
enforce annotating structures during compilation and can adds conversions between them using
function overloading and explicit constructors.

The storage structs can hold 4 channels (r, g, b and a).

Usage:

Convert a theme byte color to a linearrgb premultiplied.
```
ColorTheme4b theme_color;
ColorSceneLinear4f<eAlpha::Premultiplied> linearrgb_color =
    BLI_color_convert_to_scene_linear(theme_color).premultiply_alpha();
```

The API is structured to make most use of inlining. Most notable are space
conversions done via `BLI_color_convert_to*` functions.

- Conversions between spaces (theme <=> scene linear) should always be done by
  invoking the `BLI_color_convert_to*` methods.
- Encoding colors (compressing to store colors inside a less precision storage)
  should be done by invoking the `encode` and `decode` methods.
- Changing alpha association should be done by invoking `premultiply_alpha` or
  `unpremultiply_alpha` methods.

# Encoding.

Color encoding is used to store colors with less precision as in using `uint8_t` in
stead of `float`. This encoding is supported for `eSpace::SceneLinear`.
To make this clear to the developer the `eSpace::SceneLinearByteEncoded`
space is added.

# Precision

Colors can be stored using `uint8_t` or `float` colors. The conversion
between the two precisions are available as methods. (`to_4b` and
`to_4f`).

# Alpha conversion

Alpha conversion is only supported in SceneLinear space.

Extending:
- This file can be extended with `ColorHex/Hsl/Hsv` for different representations
  of rgb based colors. `ColorHsl4f<eSpace::SceneLinear, eAlpha::Premultiplied>`
- Add non RGB spaces/storages ColorXyz.

Reviewed By: JacquesLucke, brecht

Differential Revision: https://developer.blender.org/D10978
2021-05-25 17:16:54 +02:00
Jeroen Bakker 00955cd31e Revert "Blenlib: Explicit Colors."
This reverts commit fd94e03344.
does not compile against latest master.
2021-05-25 17:03:54 +02:00
Jeroen Bakker fd94e03344 Blenlib: Explicit Colors.
Colors are often thought of as being 4 values that make up that can make any color.
But that is of course too limited. In C we didn’t spend time to annotate what we meant
when using colors.

Recently `BLI_color.hh` was made to facilitate color structures in CPP. CPP has possibilities to
enforce annotating structures during compilation and can adds conversions between them using
function overloading and explicit constructors.

The storage structs can hold 4 channels (r, g, b and a).

Usage:

Convert a theme byte color to a linearrgb premultiplied.
```
ColorTheme4b theme_color;
ColorSceneLinear4f<eAlpha::Premultiplied> linearrgb_color =
    BLI_color_convert_to_scene_linear(theme_color).premultiply_alpha();
```

The API is structured to make most use of inlining. Most notable are space
conversions done via `BLI_color_convert_to*` functions.

- Conversions between spaces (theme <=> scene linear) should always be done by
  invoking the `BLI_color_convert_to*` methods.
- Encoding colors (compressing to store colors inside a less precision storage)
  should be done by invoking the `encode` and `decode` methods.
- Changing alpha association should be done by invoking `premultiply_alpha` or
  `unpremultiply_alpha` methods.

# Encoding.

Color encoding is used to store colors with less precision as in using `uint8_t` in
stead of `float`. This encoding is supported for `eSpace::SceneLinear`.
To make this clear to the developer the `eSpace::SceneLinearByteEncoded`
space is added.

# Precision

Colors can be stored using `uint8_t` or `float` colors. The conversion
between the two precisions are available as methods. (`to_4b` and
`to_4f`).

# Alpha conversion

Alpha conversion is only supported in SceneLinear space.

Extending:
- This file can be extended with `ColorHex/Hsl/Hsv` for different representations
  of rgb based colors. `ColorHsl4f<eSpace::SceneLinear, eAlpha::Premultiplied>`
- Add non RGB spaces/storages ColorXyz.

Reviewed By: JacquesLucke, brecht

Differential Revision: https://developer.blender.org/D10978
2021-05-25 17:01:26 +02:00
Campbell Barton bf23083852 Cleanup: use our own code style for doxy-gen comment blocks 2021-05-12 21:58:25 +10:00
Hans Goudey 8216b759e9 Geometry Nodes: Initial basic curve data support
This patch adds initial curve support to geometry nodes. Currently
there is only one node available, the "Curve to Mesh" node, T87428.

However, the aim of the changes here is larger than just supporting
curve data in nodes-- it also uses the opportunity to add better spline
data structures, intended to replace the existing curve evaluation code.
The curve code in Blender is quite old, and it's generally regarded as
some of the messiest, hardest-to-understand code as well. The classes
in `BKE_spline.hh` aim to be faster, more extensible, and much more
easily understandable. Further explanation can be found in comments in
that file.

Initial builtin spline attributes are supported-- reading and writing
from the `cyclic` and `resolution` attributes works with any of the
attribute nodes. Also, only Z-up normal calculation is implemented
at the moment, and tilts do not apply yet.

**Limitations**
 - For now, you must bring curves into the node tree with an "Object
   Info" node. Changes to the curve modifier stack will come later.
 - Converting to a mesh is necessary to visualize the curve data.

Further progress can be tracked in: T87245
Higher level design document: https://wiki.blender.org/wiki/Modules/Physics_Nodes/Projects/EverythingNodes/CurveNodes

Differential Revision: https://developer.blender.org/D11091
2021-05-03 12:29:17 -05:00
Hans Goudey ddaeaa4b98 Geometry Nodes: Add a template utility to mix two attribute values
This is just linear interpolation, but it's nice to have an equivalent
to `mix3` for only two values. It will be used for interpolation of
values between bezier spline control points.
2021-04-29 21:52:34 -05:00
Jacques Lucke 1dd17726f2 Geometry Nodes: extract mesh surface sampling functions to separate file 2021-04-21 17:02:19 +02:00
Jacques Lucke b9cbf7fc80 Geometry Nodes: add utility to convert CPPType to static type 2021-04-21 16:57:43 +02:00
Jacques Lucke 9a2e623372 Cleanup: use BLI_assert_unreachable in some places 2021-03-23 16:49:47 +01:00
Campbell Barton 7b84a5a370 Cleanup: spelling 2021-02-10 09:38:24 +11:00
Jacques Lucke 17672efa0e Geometry Nodes: initial attribute interpolation between domains
This patch adds support for accessing corner attributes on the point domain.
The immediate benefit of this is that now (interpolated) uv coordinates are
available on points without having to use the Point Distribute node.

This is also very useful for parts of T84297, because once we have vertex
colors, those will also be available on points, even though they are stored
per corner.

Differential Revision: https://developer.blender.org/D10305
2021-02-09 11:45:04 +01:00
Jacques Lucke a51584dc70 Geometry Nodes: transfer corner and point attributes in Point Distribute node
If the mesh has any corner or point attributes (e.g. vertex weights or
uv maps), those attributes will now be available on the generated points
as well.

Other domains can be supported as well. I just did not implement those yet,
because we don't have a use case for them.

Differential Revision: https://developer.blender.org/D10114
2021-01-15 12:00:38 +01:00