diff options
Diffstat (limited to 'source/blender/blenkernel')
135 files changed, 2807 insertions, 2231 deletions
diff --git a/source/blender/blenkernel/BKE_DerivedMesh.h b/source/blender/blenkernel/BKE_DerivedMesh.h index fea5f515db8..59f0c86684d 100644 --- a/source/blender/blenkernel/BKE_DerivedMesh.h +++ b/source/blender/blenkernel/BKE_DerivedMesh.h @@ -46,14 +46,9 @@ * as it is and stick with using BMesh and CDDM. */ -#include "DNA_customdata_types.h" -#include "DNA_defs.h" -#include "DNA_meshdata_types.h" - #include "BLI_compiler_attrs.h" -#include "BKE_bvhutils.h" -#include "BKE_customdata.h" +#include "DNA_customdata_types.h" #ifdef __cplusplus extern "C" { @@ -125,7 +120,6 @@ struct DerivedMesh { /* Also called in Editmode */ int (*getNumVerts)(DerivedMesh *dm); int (*getNumEdges)(DerivedMesh *dm); - int (*getNumTessFaces)(DerivedMesh *dm); int (*getNumLoops)(DerivedMesh *dm); int (*getNumPolys)(DerivedMesh *dm); @@ -233,15 +227,6 @@ bool DM_release(DerivedMesh *dm); */ void DM_set_only_copy(DerivedMesh *dm, const struct CustomData_MeshMasks *mask); -/* Adds a vertex/edge/face custom data layer to a DerivedMesh, optionally - * backed by an external data array - * alloctype defines how the layer is allocated or copied, and how it is - * freed, see BKE_customdata.h for the different options. */ - -void DM_add_vert_layer(struct DerivedMesh *dm, int type, eCDAllocType alloctype, void *layer); -void DM_add_edge_layer(struct DerivedMesh *dm, int type, eCDAllocType alloctype, void *layer); -void DM_add_poly_layer(struct DerivedMesh *dm, int type, eCDAllocType alloctype, void *layer); - /* -------------------------------------------------------------------- */ /** \name Custom Data Layer Access Functions * diff --git a/source/blender/blenkernel/BKE_attribute.h b/source/blender/blenkernel/BKE_attribute.h index f3a29736bc8..ebc95c4247c 100644 --- a/source/blender/blenkernel/BKE_attribute.h +++ b/source/blender/blenkernel/BKE_attribute.h @@ -30,9 +30,8 @@ typedef enum AttributeDomain { ATTR_DOMAIN_CORNER = 3, /* Mesh Corner */ ATTR_DOMAIN_CURVE = 4, /* A single curve in a larger curve data-block */ ATTR_DOMAIN_INSTANCE = 5, /* Instance */ - - ATTR_DOMAIN_NUM } AttributeDomain; +#define ATTR_DOMAIN_NUM 6 typedef enum AttributeDomainMask { ATTR_DOMAIN_MASK_POINT = (1 << 0), @@ -50,6 +49,7 @@ typedef enum AttributeDomainMask { /* Attributes. */ bool BKE_id_attributes_supported(struct ID *id); +bool BKE_attribute_allow_procedural_access(const char *attribute_name); /** * Create a new attribute layer. diff --git a/source/blender/blenkernel/BKE_attribute_access.hh b/source/blender/blenkernel/BKE_attribute_access.hh index 8d449a124ec..c8c7c4c6808 100644 --- a/source/blender/blenkernel/BKE_attribute_access.hh +++ b/source/blender/blenkernel/BKE_attribute_access.hh @@ -77,6 +77,9 @@ class AttributeIDRef { friend std::ostream &operator<<(std::ostream &stream, const AttributeIDRef &attribute_id); }; +bool allow_procedural_attribute_access(StringRef attribute_name); +extern const char *no_procedural_access_message; + } // namespace blender::bke /** diff --git a/source/blender/blenkernel/BKE_blender_version.h b/source/blender/blenkernel/BKE_blender_version.h index 15fdc73adeb..ab13a2e85d0 100644 --- a/source/blender/blenkernel/BKE_blender_version.h +++ b/source/blender/blenkernel/BKE_blender_version.h @@ -17,15 +17,15 @@ extern "C" { */ /* Blender major and minor version. */ -#define BLENDER_VERSION 302 +#define BLENDER_VERSION 303 /* Blender patch version for bugfix releases. */ #define BLENDER_VERSION_PATCH 0 /** Blender release cycle stage: alpha/beta/rc/release. */ -#define BLENDER_VERSION_CYCLE beta +#define BLENDER_VERSION_CYCLE alpha /* Blender file format version. */ #define BLENDER_FILE_VERSION BLENDER_VERSION -#define BLENDER_FILE_SUBVERSION 14 +#define BLENDER_FILE_SUBVERSION 0 /* Minimum Blender version that supports reading file written with the current * version. Older Blender versions will test this and show a warning if the file diff --git a/source/blender/blenkernel/BKE_bvhutils.h b/source/blender/blenkernel/BKE_bvhutils.h index 8f33003fa9d..d22abd235df 100644 --- a/source/blender/blenkernel/BKE_bvhutils.h +++ b/source/blender/blenkernel/BKE_bvhutils.h @@ -157,25 +157,6 @@ BVHTree *bvhtree_from_mesh_edges_ex(struct BVHTreeFromMesh *data, int tree_type, int axis); -/** - * Builds a BVH-tree where nodes are the given tessellated faces - * (NOTE: does not copy given mfaces!). - * \param vert_allocated: if true, vert freeing will be done when freeing data. - * \param face_allocated: if true, face freeing will be done when freeing data. - * \param faces_mask: if not null, true elements give which faces to add to BVH-tree. - * \param faces_num_active: if >= 0, number of active faces to add to BVH-tree - * (else will be computed from mask). - */ -BVHTree *bvhtree_from_mesh_faces_ex(struct BVHTreeFromMesh *data, - const struct MVert *vert, - const struct MFace *face, - int numFaces, - const BLI_bitmap *faces_mask, - int faces_num_active, - float epsilon, - int tree_type, - int axis); - BVHTree *bvhtree_from_editmesh_looptri( BVHTreeFromEditMesh *data, struct BMEditMesh *em, float epsilon, int tree_type, int axis); @@ -192,8 +173,6 @@ BVHTree *bvhtree_from_editmesh_looptri_ex(BVHTreeFromEditMesh *data, /** * Builds a BVH-tree where nodes are the looptri faces of the given mesh. - * - * \note for edit-mesh this is currently a duplicate of #bvhtree_from_mesh_faces_ex */ BVHTree *bvhtree_from_mesh_looptri_ex(struct BVHTreeFromMesh *data, const struct MVert *vert, diff --git a/source/blender/blenkernel/BKE_camera.h b/source/blender/blenkernel/BKE_camera.h index 57dc1e288dc..b7aa1c09e04 100644 --- a/source/blender/blenkernel/BKE_camera.h +++ b/source/blender/blenkernel/BKE_camera.h @@ -79,7 +79,7 @@ typedef struct CameraParams { void BKE_camera_params_init(CameraParams *params); void BKE_camera_params_from_object(CameraParams *params, const struct Object *cam_ob); void BKE_camera_params_from_view3d(CameraParams *params, - struct Depsgraph *depsgraph, + const struct Depsgraph *depsgraph, const struct View3D *v3d, const struct RegionView3D *rv3d); @@ -164,6 +164,14 @@ bool BKE_camera_multiview_spherical_stereo(const struct RenderData *rd, /* Camera background image API */ struct CameraBGImage *BKE_camera_background_image_new(struct Camera *cam); +/** + * Duplicate a background image, in a ID management compatible way. + * + * \param copy_flag The usual ID copying flags, see `LIB_ID_CREATE_`/`LIB_ID_COPY_` enums in + * `BKE_lib_id.h`. + */ +struct CameraBGImage *BKE_camera_background_image_copy(struct CameraBGImage *bgpic_src, + const int copy_flag); void BKE_camera_background_image_remove(struct Camera *cam, struct CameraBGImage *bgpic); void BKE_camera_background_image_clear(struct Camera *cam); diff --git a/source/blender/blenkernel/BKE_colortools.h b/source/blender/blenkernel/BKE_colortools.h index 0d4560207ea..d52fd91ccdd 100644 --- a/source/blender/blenkernel/BKE_colortools.h +++ b/source/blender/blenkernel/BKE_colortools.h @@ -129,6 +129,36 @@ bool BKE_curvemapping_RGBA_does_something(const struct CurveMapping *cumap); void BKE_curvemapping_table_F(const struct CurveMapping *cumap, float **array, int *size); void BKE_curvemapping_table_RGBA(const struct CurveMapping *cumap, float **array, int *size); +/** Get the minimum x value of each curve map table. */ +void BKE_curvemapping_get_range_minimums(const struct CurveMapping *curve_mapping, + float minimums[4]); + +/** Get the reciprocal of the difference between the maximum and the minimum x value of each curve + * map table. Evaluation parameters can be multiplied by this value to be normalized. If the + * difference is zero, 1^8 is returned. */ +void BKE_curvemapping_compute_range_dividers(const struct CurveMapping *curve_mapping, + float dividers[4]); + +/** Compute the slopes at the start and end points of each curve map. The slopes are multiplied by + * the range of the curve map to compensate for parameter normalization. If the slope is vertical, + * 1^8 is returned. */ +void BKE_curvemapping_compute_slopes(const struct CurveMapping *curve_mapping, + float start_slopes[4], + float end_slopes[4]); + +/** Check if the curve map at the index is identity, that is, does nothing. A curve map is said to + * be identity if: + * - The curve mapping uses extrapolation. + * - Its range is 1. + * - The slope at its start point is 1. + * - The slope at its end point is 1. + * - The number of points is 2. + * - The start point is at (0, 0). + * - The end point is at (1, 1). + * Note that this could return false even if the curve map is identity, this happens in the case + * when more than 2 points exist in the curve map but all points are collinear. */ +bool BKE_curvemapping_is_map_identity(const struct CurveMapping *curve_mapping, int index); + /** * Call when you do images etc, needs restore too. also verifies tables. * non-const (these modify the curve). diff --git a/source/blender/blenkernel/BKE_constraint.h b/source/blender/blenkernel/BKE_constraint.h index b3119666f0a..ce1f4c2b98c 100644 --- a/source/blender/blenkernel/BKE_constraint.h +++ b/source/blender/blenkernel/BKE_constraint.h @@ -67,7 +67,7 @@ typedef void (*ConstraintIDFunc)(struct bConstraint *con, * Callers of these functions must check that they actually point to something useful, * as some constraints don't define some of these. * - * Warning: + * WARNING: * it is not too advisable to reorder order of members of this struct, * as you'll have to edit quite a few #NUM_CONSTRAINT_TYPES of these * structs. diff --git a/source/blender/blenkernel/BKE_curves.hh b/source/blender/blenkernel/BKE_curves.hh index 1e96c0e4c41..cc056dab248 100644 --- a/source/blender/blenkernel/BKE_curves.hh +++ b/source/blender/blenkernel/BKE_curves.hh @@ -48,6 +48,13 @@ struct BasisCache { * In other words, the index of the first control point that influences this evaluated point. */ Vector<int> start_indices; + + /** + * The result of #check_valid_num_and_order, to avoid retrieving its inputs later on. + * If this is true, the data above will be invalid, and original data should be copied + * to the evaluated result. + */ + bool invalid = false; }; } // namespace curves::nurbs @@ -120,7 +127,7 @@ class CurvesGeometry : public ::CurvesGeometry { * Create curves with the given size. Only the position attribute is created, along with the * offsets. */ - CurvesGeometry(int point_size, int curve_size); + CurvesGeometry(int point_num, int curve_num); CurvesGeometry(const CurvesGeometry &other); CurvesGeometry(CurvesGeometry &&other); CurvesGeometry &operator=(const CurvesGeometry &other); @@ -174,11 +181,18 @@ class CurvesGeometry : public ::CurvesGeometry { /** Update the cached count of curves of each type, necessary after #curve_types_for_write. */ void update_curve_types(); - bool has_curve_with_type(const CurveType type) const; + bool has_curve_with_type(CurveType type) const; /** Return true if all of the curves have the provided type. */ bool is_single_type(CurveType type) const; /** Return the number of curves with each type. */ const std::array<int, CURVE_TYPES_NUM> &curve_type_counts() const; + /** + * All of the curve indices for curves with a specific type. + */ + IndexMask indices_for_curve_type(CurveType type, Vector<int64_t> &r_indices) const; + IndexMask indices_for_curve_type(CurveType type, + IndexMask selection, + Vector<int64_t> &r_indices) const; Span<float3> positions() const; MutableSpan<float3> positions_for_write(); @@ -276,11 +290,6 @@ class CurvesGeometry : public ::CurvesGeometry { bool bounds_min_max(float3 &min, float3 &max) const; private: - /** - * All of the curve indices for curves with a specific type. - */ - IndexMask indices_for_curve_type(CurveType type, Vector<int64_t> &r_indices) const; - /* -------------------------------------------------------------------- * Evaluation. */ @@ -409,7 +418,7 @@ namespace curves { * The number of segments between control points, accounting for the last segment of cyclic * curves. The logic is simple, but this function should be used to make intentions clearer. */ -inline int curve_segment_size(const int points_num, const bool cyclic) +inline int curve_segment_num(const int points_num, const bool cyclic) { BLI_assert(points_num > 0); return (cyclic && points_num > 1) ? points_num : points_num - 1; @@ -444,7 +453,7 @@ void calculate_tangents(Span<float3> positions, bool is_cyclic, MutableSpan<floa /** * Calculate directions perpendicular to the tangent at every point by rotating an arbitrary - * starting vector by the same rotation of each tangent. If the curve is cylic, propagate a + * starting vector by the same rotation of each tangent. If the curve is cyclic, propagate a * correction through the entire to make sure the first and last normal align. */ void calculate_normals_minimum(Span<float3> tangents, bool cyclic, MutableSpan<float3> normals); @@ -474,10 +483,11 @@ bool segment_is_vector(Span<int8_t> handle_types_left, int segment_index); /** - * Return true if the curve's last cylic segment has a vector type. + * Return true if the curve's last cyclic segment has a vector type. * This only makes a difference in the shape of cyclic curves. */ -bool last_cylic_segment_is_vector(Span<int8_t> handle_types_left, Span<int8_t> handle_types_right); +bool last_cyclic_segment_is_vector(Span<int8_t> handle_types_left, + Span<int8_t> handle_types_right); /** * Return true if the handle types at the index are free (#BEZIER_HANDLE_FREE) or vector @@ -576,11 +586,11 @@ namespace catmull_rom { * \param points_num: The number of points in the curve. * \param resolution: The resolution for each segment. */ -int calculate_evaluated_size(int points_num, bool cyclic, int resolution); +int calculate_evaluated_num(int points_num, bool cyclic, int resolution); /** * Evaluate the Catmull Rom curve. The length of the #dst span should be calculated with - * #calculate_evaluated_size and is expected to divide evenly by the #src span's segment size. + * #calculate_evaluated_num and is expected to divide evenly by the #src span's segment size. */ void interpolate_to_evaluated(GSpan src, bool cyclic, int resolution, GMutableSpan dst); @@ -597,7 +607,7 @@ namespace nurbs { /** * Checks the conditions that a NURBS curve needs to evaluate. */ -bool check_valid_size_and_order(int points_num, int8_t order, bool cyclic, KnotsMode knots_mode); +bool check_valid_num_and_order(int points_num, int8_t order, bool cyclic, KnotsMode knots_mode); /** * Calculate the standard evaluated size for a NURBS curve, using the standard that @@ -607,7 +617,7 @@ bool check_valid_size_and_order(int points_num, int8_t order, bool cyclic, Knots * for predictability and so that cached basis weights of NURBS curves with these properties can be * shared. */ -int calculate_evaluated_size( +int calculate_evaluated_num( int points_num, int8_t order, bool cyclic, int resolution, KnotsMode knots_mode); /** @@ -615,7 +625,7 @@ int calculate_evaluated_size( * The knots must be longer for a cyclic curve, for example, in order to provide weights for the * last evaluated points that are also influenced by the first control points. */ -int knots_size(int points_num, int8_t order, bool cyclic); +int knots_num(int points_num, int8_t order, bool cyclic); /** * Calculate the knots for a curve given its properties, based on built-in standards defined by @@ -635,7 +645,7 @@ void calculate_knots( * and a weight for each control point. */ void calculate_basis_cache(int points_num, - int evaluated_size, + int evaluated_num, int8_t order, bool cyclic, Span<float> knots, @@ -662,6 +672,7 @@ void interpolate_to_evaluated(const BasisCache &basis_cache, } // namespace curves Curves *curves_new_nomain(int points_num, int curves_num); +Curves *curves_new_nomain(CurvesGeometry curves); /** * Create a new curves data-block containing a single curve with the given length and type. @@ -676,11 +687,11 @@ std::array<int, CURVE_TYPES_NUM> calculate_type_counts(const VArray<int8_t> &typ inline int CurvesGeometry::points_num() const { - return this->point_size; + return this->point_num; } inline int CurvesGeometry::curves_num() const { - return this->curve_size; + return this->curve_num; } inline IndexRange CurvesGeometry::points_range() const { @@ -710,7 +721,7 @@ inline const std::array<int, CURVE_TYPES_NUM> &CurvesGeometry::curve_type_counts inline IndexRange CurvesGeometry::points_for_curve(const int index) const { /* Offsets are not allocated when there are no curves. */ - BLI_assert(this->curve_size > 0); + BLI_assert(this->curve_num > 0); BLI_assert(this->curve_offsets != nullptr); const int offset = this->curve_offsets[index]; const int offset_next = this->curve_offsets[index + 1]; @@ -720,7 +731,7 @@ inline IndexRange CurvesGeometry::points_for_curve(const int index) const inline IndexRange CurvesGeometry::points_for_curves(const IndexRange curves) const { /* Offsets are not allocated when there are no curves. */ - BLI_assert(this->curve_size > 0); + BLI_assert(this->curve_num > 0); BLI_assert(this->curve_offsets != nullptr); const int offset = this->curve_offsets[curves.start()]; const int offset_next = this->curve_offsets[curves.one_after_last()]; @@ -742,7 +753,7 @@ inline IndexRange CurvesGeometry::evaluated_points_for_curve(int index) const inline IndexRange CurvesGeometry::evaluated_points_for_curves(const IndexRange curves) const { BLI_assert(!this->runtime->offsets_cache_dirty); - BLI_assert(this->curve_size > 0); + BLI_assert(this->curve_num > 0); const int offset = this->runtime->evaluated_offsets_cache[curves.start()]; const int offset_next = this->runtime->evaluated_offsets_cache[curves.one_after_last()]; return {offset, offset_next - offset}; @@ -760,7 +771,7 @@ inline IndexRange CurvesGeometry::lengths_range_for_curve(const int curve_index, BLI_assert(cyclic == this->cyclic()[curve_index]); const IndexRange points = this->evaluated_points_for_curve(curve_index); const int start = points.start() + curve_index; - return {start, points.is_empty() ? 0 : curves::curve_segment_size(points.size(), cyclic)}; + return {start, curves::curve_segment_num(points.size(), cyclic)}; } inline Span<float> CurvesGeometry::evaluated_lengths_for_curve(const int curve_index, @@ -775,8 +786,10 @@ inline float CurvesGeometry::evaluated_length_total_for_curve(const int curve_in const bool cyclic) const { const Span<float> lengths = this->evaluated_lengths_for_curve(curve_index, cyclic); - /* Check for curves that have no evaluated segments. */ - return lengths.is_empty() ? 0.0f : lengths.last(); + if (lengths.is_empty()) { + return 0.0f; + } + return lengths.last(); } /** \} */ diff --git a/source/blender/blenkernel/BKE_curves_utils.hh b/source/blender/blenkernel/BKE_curves_utils.hh new file mode 100644 index 00000000000..62b060093e9 --- /dev/null +++ b/source/blender/blenkernel/BKE_curves_utils.hh @@ -0,0 +1,26 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ + +#pragma once + +#include "BKE_curves.hh" + +/** \file + * \ingroup bke + * \brief Low-level operations for curves. + */ + +namespace blender::bke::curves { + +/** + * Copy the size of every curve in #curve_ranges to the corresponding index in #counts. + */ +void fill_curve_counts(const bke::CurvesGeometry &curves, + Span<IndexRange> curve_ranges, + MutableSpan<int> counts); + +/** + * Turn an array of sizes into the offset at each index including all previous sizes. + */ +void accumulate_counts_to_offsets(MutableSpan<int> counts_to_offsets, int start_offset = 0); + +} // namespace blender::bke::curves diff --git a/source/blender/blenkernel/BKE_customdata.h b/source/blender/blenkernel/BKE_customdata.h index f05dfb164cf..64c49830dc5 100644 --- a/source/blender/blenkernel/BKE_customdata.h +++ b/source/blender/blenkernel/BKE_customdata.h @@ -10,6 +10,10 @@ #include "BLI_sys_types.h" #include "BLI_utildefines.h" +#ifdef __cplusplus +# include "BLI_span.hh" +# include "BLI_vector.hh" +#endif #include "DNA_customdata_types.h" @@ -700,39 +704,33 @@ void CustomData_data_transfer(const struct MeshPairRemap *me_remap, /* .blend file I/O */ +#ifdef __cplusplus + /** * Prepare given custom data for file writing. * - * \param data: the custom-data to tweak for .blend file writing (modified in place). - * \param r_write_layers: contains a reduced set of layers to be written to file, - * use it with #writestruct_at_address() - * (caller must free it if != \a write_layers_buff). - * - * \param write_layers_buff: An optional buffer for r_write_layers (to avoid allocating it). - * \param write_layers_size: The size of pre-allocated \a write_layer_buff. + * \param data: The custom-data to tweak for .blend file writing (modified in place). + * \param layers_to_write: A reduced set of layers to be written to file. * - * \warning After this function has ran, given custom data is no more valid from Blender POV - * (its `totlayer` is invalid). This function shall always be called with localized data - * (as it is in write_meshes()). - * - * \note `data->typemap` is not updated here, since it is always rebuilt on file read anyway. - * This means written `typemap` does not match written layers (as returned by \a r_write_layers). - * Trivial to fix is ever needed. + * \warning This function invalidates the custom data struct by changing the layer counts and the + * #layers pointer, and by invalidating the type map. It expects to work on a shallow copy of + * the struct. */ -void CustomData_blend_write_prepare(struct CustomData *data, - struct CustomDataLayer **r_write_layers, - struct CustomDataLayer *write_layers_buff, - size_t write_layers_size); +void CustomData_blend_write_prepare(CustomData &data, + blender::Vector<CustomDataLayer, 16> &layers_to_write); /** - * \param layers: The layers argument assigned by #CustomData_blend_write_prepare. + * \param layers_to_write: Layers created by #CustomData_blend_write_prepare. */ -void CustomData_blend_write(struct BlendWriter *writer, - struct CustomData *data, - CustomDataLayer *layers, +void CustomData_blend_write(BlendWriter *writer, + CustomData *data, + blender::Span<CustomDataLayer> layers_to_write, int count, CustomDataMask cddata_mask, - struct ID *id); + ID *id); + +#endif + void CustomData_blend_read(struct BlendDataReader *reader, struct CustomData *data, int count); #ifndef NDEBUG diff --git a/source/blender/blenkernel/BKE_customdata_file.h b/source/blender/blenkernel/BKE_customdata_file.h index 9d45d28bd18..6972dcb8681 100644 --- a/source/blender/blenkernel/BKE_customdata_file.h +++ b/source/blender/blenkernel/BKE_customdata_file.h @@ -25,17 +25,17 @@ void cdf_free(CDataFile *cdf); /* File read/write/remove */ -bool cdf_read_open(CDataFile *cdf, const char *filename); +bool cdf_read_open(CDataFile *cdf, const char *filepath); bool cdf_read_layer(CDataFile *cdf, CDataFileLayer *blay); bool cdf_read_data(CDataFile *cdf, unsigned int size, void *data); void cdf_read_close(CDataFile *cdf); -bool cdf_write_open(CDataFile *cdf, const char *filename); +bool cdf_write_open(CDataFile *cdf, const char *filepath); bool cdf_write_layer(CDataFile *cdf, CDataFileLayer *blay); bool cdf_write_data(CDataFile *cdf, unsigned int size, void *data); void cdf_write_close(CDataFile *cdf); -void cdf_remove(const char *filename); +void cdf_remove(const char *filepath); /* Layers */ diff --git a/source/blender/blenkernel/BKE_deform.h b/source/blender/blenkernel/BKE_deform.h index 1b225884b14..a21d9141ac0 100644 --- a/source/blender/blenkernel/BKE_deform.h +++ b/source/blender/blenkernel/BKE_deform.h @@ -228,39 +228,44 @@ void BKE_defvert_normalize_lock_map(struct MDeformVert *dvert, /* Utilities to 'extract' a given vgroup into a simple float array, * for verts, but also edges/polys/loops. */ -void BKE_defvert_extract_vgroup_to_vertweights( - struct MDeformVert *dvert, int defgroup, int num_verts, float *r_weights, bool invert_vgroup); +void BKE_defvert_extract_vgroup_to_vertweights(const struct MDeformVert *dvert, + int defgroup, + int num_verts, + bool invert_vgroup, + float *r_weights); /** * The following three make basic interpolation, * using temp vert_weights array to avoid looking up same weight several times. */ -void BKE_defvert_extract_vgroup_to_edgeweights(struct MDeformVert *dvert, +void BKE_defvert_extract_vgroup_to_edgeweights(const struct MDeformVert *dvert, int defgroup, int num_verts, struct MEdge *edges, int num_edges, - float *r_weights, - bool invert_vgroup); -void BKE_defvert_extract_vgroup_to_loopweights(struct MDeformVert *dvert, + bool invert_vgroup, + float *r_weights); +void BKE_defvert_extract_vgroup_to_loopweights(const struct MDeformVert *dvert, int defgroup, int num_verts, struct MLoop *loops, int num_loops, - float *r_weights, - bool invert_vgroup); -void BKE_defvert_extract_vgroup_to_polyweights(struct MDeformVert *dvert, + bool invert_vgroup, + float *r_weights); +void BKE_defvert_extract_vgroup_to_polyweights(const struct MDeformVert *dvert, int defgroup, int num_verts, struct MLoop *loops, int num_loops, struct MPoly *polys, int num_polys, - float *r_weights, - bool invert_vgroup); + bool invert_vgroup, + float *r_weights); void BKE_defvert_weight_to_rgb(float r_rgb[3], float weight); -void BKE_defvert_blend_write(struct BlendWriter *writer, int count, struct MDeformVert *dvlist); +void BKE_defvert_blend_write(struct BlendWriter *writer, + int count, + const struct MDeformVert *dvlist); void BKE_defvert_blend_read(struct BlendDataReader *reader, int count, struct MDeformVert *mdverts); diff --git a/source/blender/blenkernel/BKE_fcurve.h b/source/blender/blenkernel/BKE_fcurve.h index 6784a1296e9..78d80ce200e 100644 --- a/source/blender/blenkernel/BKE_fcurve.h +++ b/source/blender/blenkernel/BKE_fcurve.h @@ -293,7 +293,7 @@ struct FCurve *BKE_fcurve_find_by_rna(struct PointerRNA *ptr, * temp hack needed for complex paths like texture ones. */ struct FCurve *BKE_fcurve_find_by_rna_context_ui(struct bContext *C, - struct PointerRNA *ptr, + const struct PointerRNA *ptr, struct PropertyRNA *prop, int rnaindex, struct AnimData **r_animdata, diff --git a/source/blender/blenkernel/BKE_geometry_fields.hh b/source/blender/blenkernel/BKE_geometry_fields.hh index 36b382feb5f..9c86ab262ef 100644 --- a/source/blender/blenkernel/BKE_geometry_fields.hh +++ b/source/blender/blenkernel/BKE_geometry_fields.hh @@ -162,4 +162,14 @@ class AnonymousAttributeFieldInput : public GeometryFieldInput { bool is_equal_to(const fn::FieldNode &other) const override; }; +class CurveLengthFieldInput final : public GeometryFieldInput { + public: + CurveLengthFieldInput(); + GVArray get_varray_for_context(const GeometryComponent &component, + AttributeDomain domain, + IndexMask mask) const final; + uint64_t hash() const override; + bool is_equal_to(const fn::FieldNode &other) const override; +}; + } // namespace blender::bke diff --git a/source/blender/blenkernel/BKE_geometry_set.hh b/source/blender/blenkernel/BKE_geometry_set.hh index dfd9fccebbd..c58420efceb 100644 --- a/source/blender/blenkernel/BKE_geometry_set.hh +++ b/source/blender/blenkernel/BKE_geometry_set.hh @@ -98,7 +98,7 @@ class GeometryComponent { /** * Return the length of a specific domain, or 0 if the domain is not supported. */ - virtual int attribute_domain_size(AttributeDomain domain) const; + virtual int attribute_domain_num(AttributeDomain domain) const; /** * Return true if the attribute name corresponds to a built-in attribute with a hardcoded domain @@ -521,11 +521,11 @@ struct GeometrySet { }; /** - * A geometry component that can store a mesh, storing the #Mesh data structure. + * A geometry component that can store a mesh, using the #Mesh data-block. * - * Attributes are stored in the mesh itself, on any of the four attribute domains. Generic - * attributes are stored in contiguous arrays, but often built-in attributes are stored in an - * array of structs fashion for historical reasons, requiring more complex attribute access. + * Attributes are stored, on any of the four attribute domains. Generic attributes are stored in + * contiguous arrays, but often built-in attributes are stored in an array of structs fashion for + * historical reasons, requiring more complex attribute access. */ class MeshComponent : public GeometryComponent { private: @@ -560,7 +560,7 @@ class MeshComponent : public GeometryComponent { */ Mesh *get_for_write(); - int attribute_domain_size(AttributeDomain domain) const final; + int attribute_domain_num(AttributeDomain domain) const final; bool is_empty() const final; @@ -623,7 +623,7 @@ class PointCloudComponent : public GeometryComponent { */ PointCloud *get_for_write(); - int attribute_domain_size(AttributeDomain domain) const final; + int attribute_domain_num(AttributeDomain domain) const final; bool is_empty() const final; @@ -664,7 +664,7 @@ class CurveComponentLegacy : public GeometryComponent { const CurveEval *get_for_read() const; CurveEval *get_for_write(); - int attribute_domain_size(AttributeDomain domain) const final; + int attribute_domain_num(AttributeDomain domain) const final; bool is_empty() const final; @@ -682,8 +682,9 @@ class CurveComponentLegacy : public GeometryComponent { }; /** - * A geometry component that stores a group of curves, corresponding the #Curves and - * #CurvesGeometry types. + * A geometry component that stores a group of curves, corresponding the #Curves data-block type + * and the #CurvesGeometry type. Attributes are are stored on the control point domain and the + * curve domain. */ class CurveComponent : public GeometryComponent { private: @@ -715,7 +716,7 @@ class CurveComponent : public GeometryComponent { const Curves *get_for_read() const; Curves *get_for_write(); - int attribute_domain_size(AttributeDomain domain) const final; + int attribute_domain_num(AttributeDomain domain) const final; bool is_empty() const final; @@ -949,8 +950,8 @@ class InstancesComponent : public GeometryComponent { blender::MutableSpan<blender::float4x4> instance_transforms(); blender::Span<blender::float4x4> instance_transforms() const; - int instances_amount() const; - int references_amount() const; + int instances_num() const; + int references_num() const; /** * Remove the indices that are not contained in the mask input, and remove unused instance @@ -963,7 +964,7 @@ class InstancesComponent : public GeometryComponent { blender::bke::CustomDataAttributes &attributes(); const blender::bke::CustomDataAttributes &attributes() const; - int attribute_domain_size(AttributeDomain domain) const final; + int attribute_domain_num(AttributeDomain domain) const final; void foreach_referenced_geometry( blender::FunctionRef<void(const GeometrySet &geometry_set)> callback) const; diff --git a/source/blender/blenkernel/BKE_global.h b/source/blender/blenkernel/BKE_global.h index 06feb07aef2..96b6f7a53b0 100644 --- a/source/blender/blenkernel/BKE_global.h +++ b/source/blender/blenkernel/BKE_global.h @@ -81,6 +81,7 @@ typedef struct Global { * * 1 - 30: EEVEE debug/stats values (01/2018). * * 31: Enable the Select Debug Engine. Only available with #WITH_DRAW_DEBUG (08/2021). * * 101: Enable UI debug drawing of fullscreen area's corner widget (10/2014). + * * 102: Enable extra items in string search UI (05/2022). * * 666: Use quicker batch delete for outliners' delete hierarchy (01/2019). * * 777: Enable UI node panel's sockets polling (11/2011). * * 799: Enable some mysterious new depsgraph behavior (05/2015). diff --git a/source/blender/blenkernel/BKE_icons.h b/source/blender/blenkernel/BKE_icons.h index db45e405e79..8d9351806c4 100644 --- a/source/blender/blenkernel/BKE_icons.h +++ b/source/blender/blenkernel/BKE_icons.h @@ -172,7 +172,7 @@ bool BKE_previewimg_id_supports_jobs(const struct ID *id); /** * Trigger deferred loading of a custom image file into the preview buffer. */ -void BKE_previewimg_id_custom_set(struct ID *id, const char *path); +void BKE_previewimg_id_custom_set(struct ID *id, const char *filepath); /** * Free the preview image belonging to the id. @@ -223,11 +223,12 @@ struct PreviewImage *BKE_previewimg_cached_get(const char *name); struct PreviewImage *BKE_previewimg_cached_ensure(const char *name); /** - * Generate a #PreviewImage from given file path, using thumbnails management, if not yet existing. - * Does not actually generate the preview, #BKE_previewimg_ensure() must be called for that. + * Generate a #PreviewImage from given `filepath`, using thumbnails management, if not yet + * existing. Does not actually generate the preview, #BKE_previewimg_ensure() must be called for + * that. */ struct PreviewImage *BKE_previewimg_cached_thumbnail_read(const char *name, - const char *path, + const char *filepath, int source, bool force_update); diff --git a/source/blender/blenkernel/BKE_image.h b/source/blender/blenkernel/BKE_image.h index 0417f335d11..1f131568900 100644 --- a/source/blender/blenkernel/BKE_image.h +++ b/source/blender/blenkernel/BKE_image.h @@ -273,14 +273,6 @@ bool BKE_image_is_openexr(struct Image *ima); void BKE_image_backup_render(struct Scene *scene, struct Image *ima, bool free_current_slot); /** - * For single-layer OpenEXR saving. - */ -bool BKE_image_save_openexr_multiview(struct Image *ima, - struct ImBuf *ibuf, - const char *filepath, - int flags); - -/** * Goes over all textures that use images. */ void BKE_image_free_all_textures(struct Main *bmain); @@ -392,7 +384,7 @@ void BKE_image_ensure_tile_token(char *filename); /** * When provided with an absolute virtual `filepath`, check to see if at least * one concrete file exists. - * Note: This function requires directory traversal and may be inefficient in time-critical, + * NOTE: This function requires directory traversal and may be inefficient in time-critical, * or iterative, code paths. */ bool BKE_image_tile_filepath_exists(const char *filepath); @@ -459,7 +451,7 @@ bool BKE_image_is_dirty_writable(struct Image *image, bool *r_is_writable); int BKE_image_sequence_guess_offset(struct Image *image); bool BKE_image_has_anim(struct Image *image); bool BKE_image_has_packedfile(const struct Image *image); -bool BKE_image_has_filepath(struct Image *ima); +bool BKE_image_has_filepath(const struct Image *ima); /** * Checks the image buffer changes with time (not keyframed values). */ diff --git a/source/blender/blenkernel/BKE_image_format.h b/source/blender/blenkernel/BKE_image_format.h index 633af54ea4f..6a03d1d8df5 100644 --- a/source/blender/blenkernel/BKE_image_format.h +++ b/source/blender/blenkernel/BKE_image_format.h @@ -76,6 +76,8 @@ char BKE_imtype_from_arg(const char *arg); void BKE_image_format_from_imbuf(struct ImageFormatData *im_format, const struct ImBuf *imbuf); void BKE_image_format_to_imbuf(struct ImBuf *ibuf, const struct ImageFormatData *imf); +bool BKE_image_format_is_byte(const struct ImageFormatData *imf); + /* Color Management */ void BKE_image_format_color_management_copy(struct ImageFormatData *imf, diff --git a/source/blender/blenkernel/BKE_image_save.h b/source/blender/blenkernel/BKE_image_save.h index 052fc937af9..673a7dffb82 100644 --- a/source/blender/blenkernel/BKE_image_save.h +++ b/source/blender/blenkernel/BKE_image_save.h @@ -13,10 +13,11 @@ extern "C" { #endif struct Image; +struct ImageUser; struct Main; +struct RenderResult; struct ReportList; struct Scene; -struct RenderResult; /* Image datablock saving. */ @@ -34,11 +35,20 @@ typedef struct ImageSaveOptions { bool save_copy; bool save_as_render; bool do_newpath; + + /* Keep track of previous values for auto updates in UI. */ + bool prev_save_as_render; + int prev_imtype; } ImageSaveOptions; -void BKE_image_save_options_init(struct ImageSaveOptions *opts, +bool BKE_image_save_options_init(ImageSaveOptions *opts, struct Main *bmain, - struct Scene *scene); + struct Scene *scene, + struct Image *ima, + struct ImageUser *iuser, + const bool guess_path, + const bool save_as_render); +void BKE_image_save_options_update(struct ImageSaveOptions *opts, struct Image *ima); void BKE_image_save_options_free(struct ImageSaveOptions *opts); bool BKE_image_save(struct ReportList *reports, diff --git a/source/blender/blenkernel/BKE_lib_override.h b/source/blender/blenkernel/BKE_lib_override.h index dfb2b900b10..38de4bebdbd 100644 --- a/source/blender/blenkernel/BKE_lib_override.h +++ b/source/blender/blenkernel/BKE_lib_override.h @@ -116,6 +116,8 @@ struct ID *BKE_lib_override_library_create_from_id(struct Main *bmain, * \param do_no_main: Create the new override data outside of Main database. * Used for resyncing of linked overrides. * + * \param do_fully_editable: if true, tag all created overrides as user-editable by default. + * * \return \a true on success, \a false otherwise. */ bool BKE_lib_override_library_create_from_tag(struct Main *bmain, @@ -123,7 +125,8 @@ bool BKE_lib_override_library_create_from_tag(struct Main *bmain, const struct ID *id_root_reference, struct ID *id_hierarchy_root, const struct ID *id_hierarchy_root_reference, - bool do_no_main); + bool do_no_main, + const bool do_fully_editable); /** * Advanced 'smart' function to create fully functional overrides. * @@ -154,6 +157,8 @@ bool BKE_lib_override_library_create_from_tag(struct Main *bmain, * * \param r_id_root_override: if not NULL, the override generated for the given \a id_root. * + * \param do_fully_editable: if true, tag all created overrides as user-editable by default. + * * \return true if override was successfully created. */ bool BKE_lib_override_library_create(struct Main *bmain, @@ -163,7 +168,8 @@ bool BKE_lib_override_library_create(struct Main *bmain, struct ID *id_root_reference, struct ID *id_hierarchy_root_reference, struct ID *id_instance_hint, - struct ID **r_id_root_override); + struct ID **r_id_root_override, + const bool do_fully_editable); /** * Create a library override template. */ diff --git a/source/blender/blenkernel/BKE_lib_principle_properties.h b/source/blender/blenkernel/BKE_lib_principle_properties.h index 10d0d33a0c4..42177204efb 100644 --- a/source/blender/blenkernel/BKE_lib_principle_properties.h +++ b/source/blender/blenkernel/BKE_lib_principle_properties.h @@ -40,7 +40,7 @@ struct ReportList; struct IDPrincipleProperties *BKE_lib_principleprop_init(struct ID *id); #if 0 /** - * Shallow or deep copy of a whole princple properties from \a src_id to \a dst_id. + * Shallow or deep copy of a whole principle properties from \a src_id to \a dst_id. */ void BKE_lib_principleprop_copy(struct ID *dst_id, const struct ID *src_id, bool do_full_copy); #endif diff --git a/source/blender/blenkernel/BKE_material.h b/source/blender/blenkernel/BKE_material.h index f38f6afff7e..05e502f06c2 100644 --- a/source/blender/blenkernel/BKE_material.h +++ b/source/blender/blenkernel/BKE_material.h @@ -52,7 +52,7 @@ void BKE_object_material_remap_calc(struct Object *ob_dst, */ void BKE_object_material_from_eval_data(struct Main *bmain, struct Object *ob_orig, - struct ID *data_eval); + const struct ID *data_eval); struct Material *BKE_material_add(struct Main *bmain, const char *name); struct Material *BKE_gpencil_material_add(struct Main *bmain, const char *name); void BKE_gpencil_material_attr_init(struct Material *ma); diff --git a/source/blender/blenkernel/BKE_mesh.h b/source/blender/blenkernel/BKE_mesh.h index 091f30825ae..23ec69babc8 100644 --- a/source/blender/blenkernel/BKE_mesh.h +++ b/source/blender/blenkernel/BKE_mesh.h @@ -204,6 +204,7 @@ bool BKE_mesh_material_index_used(struct Mesh *me, short index); void BKE_mesh_material_index_clear(struct Mesh *me); void BKE_mesh_material_remap(struct Mesh *me, const unsigned int *remap, unsigned int remap_len); void BKE_mesh_smooth_flag_set(struct Mesh *me, bool use_smooth); +void BKE_mesh_auto_smooth_flag_set(struct Mesh *me, bool use_auto_smooth, float auto_smooth_angle); /** * Needed after converting a mesh with subsurf optimal display to mesh. @@ -931,13 +932,6 @@ void BKE_mesh_flush_select_from_polys_ex(struct MVert *mvert, const struct MPoly *mpoly, int totpoly); void BKE_mesh_flush_select_from_polys(struct Mesh *me); -void BKE_mesh_flush_select_from_verts_ex(const struct MVert *mvert, - int totvert, - const struct MLoop *mloop, - struct MEdge *medge, - int totedge, - struct MPoly *mpoly, - int totpoly); void BKE_mesh_flush_select_from_verts(struct Mesh *me); /* spatial evaluation */ diff --git a/source/blender/blenkernel/BKE_mesh_tangent.h b/source/blender/blenkernel/BKE_mesh_tangent.h index 27061a5766e..58142653a90 100644 --- a/source/blender/blenkernel/BKE_mesh_tangent.h +++ b/source/blender/blenkernel/BKE_mesh_tangent.h @@ -21,7 +21,7 @@ void BKE_mesh_calc_loop_tangent_single_ex(const struct MVert *mverts, int numVerts, const struct MLoop *mloops, float (*r_looptangent)[4], - float (*loopnors)[3], + const float (*loopnors)[3], const struct MLoopUV *loopuv, int numLoops, const struct MPoly *mpolys, diff --git a/source/blender/blenkernel/BKE_modifier.h b/source/blender/blenkernel/BKE_modifier.h index 881e86ccc54..866b0353d07 100644 --- a/source/blender/blenkernel/BKE_modifier.h +++ b/source/blender/blenkernel/BKE_modifier.h @@ -102,6 +102,7 @@ typedef enum { /** Accepts #BMesh input (without conversion). */ eModifierTypeFlag_AcceptsBMesh = (1 << 11), } ModifierTypeFlag; +ENUM_OPERATORS(ModifierTypeFlag, eModifierTypeFlag_AcceptsBMesh) typedef void (*IDWalkFunc)(void *userData, struct Object *ob, struct ID **idpoin, int cb_flag); typedef void (*TexWalkFunc)(void *userData, @@ -113,7 +114,7 @@ typedef enum ModifierApplyFlag { /** Render time. */ MOD_APPLY_RENDER = 1 << 0, /** Result of evaluation will be cached, so modifier might - * want to cache data for quick updates (used by subsurf) */ + * want to cache data for quick updates (used by subdivision-surface) */ MOD_APPLY_USECACHE = 1 << 1, /** Modifier evaluated for undeformed texture coordinates */ MOD_APPLY_ORCO = 1 << 2, @@ -363,7 +364,9 @@ typedef struct ModifierTypeInfo { * This method should write any additional arrays and referenced structs that should be * stored in the file. */ - void (*blendWrite)(struct BlendWriter *writer, const struct ModifierData *md); + void (*blendWrite)(struct BlendWriter *writer, + const struct ID *id_owner, + const struct ModifierData *md); /** * Is called when the modifier is read from a file. @@ -592,7 +595,9 @@ struct Mesh *BKE_modifier_get_evaluated_mesh_from_evaluated_object(struct Object void BKE_modifier_check_uuids_unique_and_report(const struct Object *object); -void BKE_modifier_blend_write(struct BlendWriter *writer, struct ListBase *modbase); +void BKE_modifier_blend_write(struct BlendWriter *writer, + const struct ID *id_owner, + struct ListBase *modbase); void BKE_modifier_blend_read_data(struct BlendDataReader *reader, struct ListBase *lb, struct Object *ob); diff --git a/source/blender/blenkernel/BKE_multires.h b/source/blender/blenkernel/BKE_multires.h index 0efe38c1e8f..dfa330ff508 100644 --- a/source/blender/blenkernel/BKE_multires.h +++ b/source/blender/blenkernel/BKE_multires.h @@ -130,7 +130,7 @@ void multiresModifier_prepare_join(struct Depsgraph *depsgraph, struct Object *ob, struct Object *to_ob); -int multires_mdisp_corners(struct MDisps *s); +int multires_mdisp_corners(const struct MDisps *s); /** * Update multi-res data after topology changing. diff --git a/source/blender/blenkernel/BKE_node.h b/source/blender/blenkernel/BKE_node.h index c9228db9ecc..1ff10d06b00 100644 --- a/source/blender/blenkernel/BKE_node.h +++ b/source/blender/blenkernel/BKE_node.h @@ -1090,8 +1090,8 @@ void BKE_nodetree_remove_layer_n(struct bNodeTree *ntree, struct Scene *scene, i #define SH_NODE_SQUEEZE 117 //#define SH_NODE_MATERIAL_EXT 118 #define SH_NODE_INVERT 119 -#define SH_NODE_SEPRGB 120 -#define SH_NODE_COMBRGB 121 +#define SH_NODE_SEPRGB_LEGACY 120 +#define SH_NODE_COMBRGB_LEGACY 121 #define SH_NODE_HUE_SAT 122 #define SH_NODE_OUTPUT_MATERIAL 124 @@ -1147,8 +1147,8 @@ void BKE_nodetree_remove_layer_n(struct bNodeTree *ntree, struct Scene *scene, i #define SH_NODE_WAVELENGTH 180 #define SH_NODE_BLACKBODY 181 #define SH_NODE_VECT_TRANSFORM 182 -#define SH_NODE_SEPHSV 183 -#define SH_NODE_COMBHSV 184 +#define SH_NODE_SEPHSV_LEGACY 183 +#define SH_NODE_COMBHSV_LEGACY 184 #define SH_NODE_BSDF_HAIR 185 // #define SH_NODE_LAMP 186 #define SH_NODE_UVMAP 187 @@ -1175,6 +1175,8 @@ void BKE_nodetree_remove_layer_n(struct bNodeTree *ntree, struct Scene *scene, i #define SH_NODE_VECTOR_ROTATE 708 #define SH_NODE_CURVE_FLOAT 709 #define SH_NODE_POINT_INFO 710 +#define SH_NODE_COMBINE_COLOR 711 +#define SH_NODE_SEPARATE_COLOR 712 /** \} */ @@ -1202,8 +1204,8 @@ void BKE_nodetree_remove_layer_n(struct bNodeTree *ntree, struct Scene *scene, i #define CMP_NODE_MAP_VALUE 213 #define CMP_NODE_TIME 214 #define CMP_NODE_VECBLUR 215 -#define CMP_NODE_SEPRGBA 216 -#define CMP_NODE_SEPHSVA 217 +#define CMP_NODE_SEPRGBA_LEGACY 216 +#define CMP_NODE_SEPHSVA_LEGACY 217 #define CMP_NODE_SETALPHA 218 #define CMP_NODE_HUE_SAT 219 #define CMP_NODE_IMAGE 220 @@ -1213,14 +1215,14 @@ void BKE_nodetree_remove_layer_n(struct bNodeTree *ntree, struct Scene *scene, i #define CMP_NODE_TEXTURE 224 #define CMP_NODE_TRANSLATE 225 #define CMP_NODE_ZCOMBINE 226 -#define CMP_NODE_COMBRGBA 227 +#define CMP_NODE_COMBRGBA_LEGACY 227 #define CMP_NODE_DILATEERODE 228 #define CMP_NODE_ROTATE 229 #define CMP_NODE_SCALE 230 -#define CMP_NODE_SEPYCCA 231 -#define CMP_NODE_COMBYCCA 232 -#define CMP_NODE_SEPYUVA 233 -#define CMP_NODE_COMBYUVA 234 +#define CMP_NODE_SEPYCCA_LEGACY 231 +#define CMP_NODE_COMBYCCA_LEGACY 232 +#define CMP_NODE_SEPYUVA_LEGACY 233 +#define CMP_NODE_COMBYUVA_LEGACY 234 #define CMP_NODE_DIFF_MATTE 235 #define CMP_NODE_COLOR_SPILL 236 #define CMP_NODE_CHROMA_MATTE 237 @@ -1232,7 +1234,7 @@ void BKE_nodetree_remove_layer_n(struct bNodeTree *ntree, struct Scene *scene, i #define CMP_NODE_ID_MASK 243 #define CMP_NODE_DEFOCUS 244 #define CMP_NODE_DISPLACE 245 -#define CMP_NODE_COMBHSVA 246 +#define CMP_NODE_COMBHSVA_LEGACY 246 #define CMP_NODE_MATH 247 #define CMP_NODE_LUMA_MATTE 248 #define CMP_NODE_BRIGHTCONTRAST 249 @@ -1289,6 +1291,8 @@ void BKE_nodetree_remove_layer_n(struct bNodeTree *ntree, struct Scene *scene, i #define CMP_NODE_SCENE_TIME 329 #define CMP_NODE_SEPARATE_XYZ 330 #define CMP_NODE_COMBINE_XYZ 331 +#define CMP_NODE_COMBINE_COLOR 332 +#define CMP_NODE_SEPARATE_COLOR 333 /* channel toggles */ #define CMP_CHAN_RGB 1 @@ -1354,11 +1358,13 @@ struct TexResult; #define TEX_NODE_TRANSLATE 416 #define TEX_NODE_COORD 417 #define TEX_NODE_DISTANCE 418 -#define TEX_NODE_COMPOSE 419 -#define TEX_NODE_DECOMPOSE 420 +#define TEX_NODE_COMPOSE_LEGACY 419 +#define TEX_NODE_DECOMPOSE_LEGACY 420 #define TEX_NODE_VALTONOR 421 #define TEX_NODE_SCALE 422 #define TEX_NODE_AT 423 +#define TEX_NODE_COMBINE_COLOR 424 +#define TEX_NODE_SEPARATE_COLOR 425 /* 501-599 reserved. Use like this: TEX_NODE_PROC + TEX_CLOUDS, etc */ #define TEX_NODE_PROC 500 @@ -1511,6 +1517,8 @@ struct TexResult; #define FN_NODE_REPLACE_STRING 1218 #define FN_NODE_INPUT_BOOL 1219 #define FN_NODE_INPUT_INT 1220 +#define FN_NODE_SEPARATE_COLOR 1221 +#define FN_NODE_COMBINE_COLOR 1222 /** \} */ diff --git a/source/blender/blenkernel/BKE_node_runtime.hh b/source/blender/blenkernel/BKE_node_runtime.hh new file mode 100644 index 00000000000..f5fb53f962b --- /dev/null +++ b/source/blender/blenkernel/BKE_node_runtime.hh @@ -0,0 +1,89 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ + +#pragma once + +#include <memory> + +#include "BLI_sys_types.h" +#include "BLI_utility_mixins.hh" + +namespace blender::nodes { +struct FieldInferencingInterface; +class NodeDeclaration; +} // namespace blender::nodes + +namespace blender::bke { + +class bNodeTreeRuntime : NonCopyable, NonMovable { + public: + /** + * Keeps track of what changed in the node tree until the next update. + * Should not be changed directly, instead use the functions in `BKE_node_tree_update.h`. + * #eNodeTreeChangedFlag. + */ + uint32_t changed_flag = 0; + /** + * A hash of the topology of the node tree leading up to the outputs. This is used to determine + * of the node tree changed in a way that requires updating geometry nodes or shaders. + */ + uint32_t output_topology_hash = 0; + + /** + * Used to cache run-time information of the node tree. + * #eNodeTreeRuntimeFlag. + */ + uint8_t runtime_flag = 0; + + /** Information about how inputs and outputs of the node group interact with fields. */ + std::unique_ptr<nodes::FieldInferencingInterface> field_inferencing_interface; +}; + +/** + * Run-time data for every socket. This should only contain data that is somewhat persistent (i.e. + * data that lives longer than a single depsgraph evaluation + redraw). Data that's only used in + * smaller scopes should generally be stored in separate arrays and/or maps. + */ +class bNodeSocketRuntime : NonCopyable, NonMovable { + public: + /** + * References a socket declaration that is owned by `node->declaration`. This is only runtime + * data. It has to be updated when the node declaration changes. + */ + const SocketDeclarationHandle *declaration = nullptr; + + /** #eNodeTreeChangedFlag. */ + uint32_t changed_flag = 0; +}; + +/** + * Run-time data for every node. This should only contain data that is somewhat persistent (i.e. + * data that lives longer than a single depsgraph evaluation + redraw). Data that's only used in + * smaller scopes should generally be stored in separate arrays and/or maps. + */ +class bNodeRuntime : NonCopyable, NonMovable { + public: + /** + * Describes the desired interface of the node. This is run-time data only. + * The actual interface of the node may deviate from the declaration temporarily. + * It's possible to sync the actual state of the node to the desired state. Currently, this is + * only done when a node is created or loaded. + * + * In the future, we may want to keep more data only in the declaration, so that it does not have + * to be synced to other places that are stored in files. That especially applies to data that + * can't be edited by users directly (e.g. min/max values of sockets, tooltips, ...). + * + * The declaration of a node can be recreated at any time when it is used. Caching it here is + * just a bit more efficient when it is used a lot. To make sure that the cache is up-to-date, + * call #nodeDeclarationEnsure before using it. + * + * Currently, the declaration is the same for every node of the same type. Going forward, that is + * intended to change though. Especially when nodes become more dynamic with respect to how many + * sockets they have. + */ + NodeDeclarationHandle *declaration = nullptr; + + /** #eNodeTreeChangedFlag. */ + uint32_t changed_flag = 0; +}; + +} // namespace blender::bke diff --git a/source/blender/blenkernel/BKE_paint.h b/source/blender/blenkernel/BKE_paint.h index 0e976f04dd1..c39ab22ce3a 100644 --- a/source/blender/blenkernel/BKE_paint.h +++ b/source/blender/blenkernel/BKE_paint.h @@ -180,6 +180,7 @@ struct Paint *BKE_paint_get_active_from_context(const struct bContext *C); ePaintMode BKE_paintmode_get_active_from_context(const struct bContext *C); ePaintMode BKE_paintmode_get_from_tool(const struct bToolRef *tref); struct Brush *BKE_paint_brush(struct Paint *paint); +const struct Brush *BKE_paint_brush_for_read(const struct Paint *p); void BKE_paint_brush_set(struct Paint *paint, struct Brush *br); struct Palette *BKE_paint_palette(struct Paint *paint); void BKE_paint_palette_set(struct Paint *p, struct Palette *palette); @@ -733,7 +734,7 @@ enum { /* paint_vertex.cc */ /** - * Fills the object's active color atribute layer with the fill color. + * Fills the object's active color attribute layer with the fill color. * * \param[in] ob: The object. * \param[in] fill_color: The fill color. diff --git a/source/blender/blenkernel/BKE_particle.h b/source/blender/blenkernel/BKE_particle.h index 123fdbb8bac..5f8b2fafdd3 100644 --- a/source/blender/blenkernel/BKE_particle.h +++ b/source/blender/blenkernel/BKE_particle.h @@ -583,7 +583,7 @@ void psys_interpolate_face(struct Mesh *mesh, const float (*vert_normals)[3], struct MFace *mface, struct MTFace *tface, - float (*orcodata)[3], + const float (*orcodata)[3], float w[4], float vec[3], float nor[3], diff --git a/source/blender/blenkernel/BKE_pbvh_pixels.hh b/source/blender/blenkernel/BKE_pbvh_pixels.hh index fdfb5fa037e..e73950e6299 100644 --- a/source/blender/blenkernel/BKE_pbvh_pixels.hh +++ b/source/blender/blenkernel/BKE_pbvh_pixels.hh @@ -132,12 +132,22 @@ struct UDIMTilePixels { } }; +struct UDIMTileUndo { + short tile_number; + rcti region; + + UDIMTileUndo(short tile_number, rcti ®ion) : tile_number(tile_number), region(region) + { + } +}; + struct NodeData { struct { bool dirty : 1; } flags; Vector<UDIMTilePixels> tiles; + Vector<UDIMTileUndo> undo_regions; Triangles triangles; NodeData() @@ -155,6 +165,23 @@ struct NodeData { return nullptr; } + void rebuild_undo_regions() + { + undo_regions.clear(); + for (UDIMTilePixels &tile : tiles) { + rcti region; + BLI_rcti_init_minmax(®ion); + for (PackedPixelRow &pixel_row : tile.pixel_rows) { + BLI_rcti_do_minmax_v( + ®ion, int2(pixel_row.start_image_coordinate.x, pixel_row.start_image_coordinate.y)); + BLI_rcti_do_minmax_v(®ion, + int2(pixel_row.start_image_coordinate.x + pixel_row.num_pixels + 1, + pixel_row.start_image_coordinate.y + 1)); + } + undo_regions.append(UDIMTileUndo(tile.tile_number, region)); + } + } + void mark_region(Image &image, const image::ImageTileWrapper &image_tile, ImBuf &image_buffer) { UDIMTilePixels *tile = find_tile_data(image_tile); diff --git a/source/blender/blenkernel/BKE_shrinkwrap.h b/source/blender/blenkernel/BKE_shrinkwrap.h index 2144419728e..3e06bd84805 100644 --- a/source/blender/blenkernel/BKE_shrinkwrap.h +++ b/source/blender/blenkernel/BKE_shrinkwrap.h @@ -73,7 +73,7 @@ typedef struct ShrinkwrapTreeData { BVHTreeFromMesh treeData; const float (*pnors)[3]; - float (*clnors)[3]; + const float (*clnors)[3]; ShrinkwrapBoundaryData *boundary; } ShrinkwrapTreeData; diff --git a/source/blender/blenkernel/BKE_sound.h b/source/blender/blenkernel/BKE_sound.h index 8931418e49c..edb301f06bf 100644 --- a/source/blender/blenkernel/BKE_sound.h +++ b/source/blender/blenkernel/BKE_sound.h @@ -20,6 +20,7 @@ struct Depsgraph; struct Main; struct Sequence; struct bSound; +struct SoundInfo; typedef struct SoundWaveform { int length; @@ -78,6 +79,7 @@ typedef enum eSoundChannels { typedef struct SoundInfo { struct { eSoundChannels channels; + int samplerate; } specs; float length; } SoundInfo; diff --git a/source/blender/blenkernel/BKE_spline.hh b/source/blender/blenkernel/BKE_spline.hh index 6cbb47dc709..28f326a4ad4 100644 --- a/source/blender/blenkernel/BKE_spline.hh +++ b/source/blender/blenkernel/BKE_spline.hh @@ -102,7 +102,7 @@ class Spline { /** Return the number of control points. */ virtual int size() const = 0; - int segments_size() const; + int segments_num() const; bool is_cyclic() const; void set_cyclic(bool value); @@ -127,8 +127,8 @@ class Spline { * change the generated positions, tangents, normals, mapping, etc. of the evaluated points. */ virtual void mark_cache_invalid() = 0; - virtual int evaluated_points_size() const = 0; - int evaluated_edges_size() const; + virtual int evaluated_points_num() const = 0; + int evaluated_edges_num() const; float length() const; @@ -164,7 +164,7 @@ class Spline { /** * The index of the evaluated point after the result location, accounting for wrapping when * the spline is cyclic. If the sampled factor/length is the very end of the spline, this will - * be the last index (#evaluated_points_size - 1). + * be the last index (#evaluated_points_num - 1). */ int next_evaluated_index; /** @@ -191,7 +191,7 @@ class Spline { * indices and factors to the next index encoded in floats. The logic for converting from the * float values to interpolation data is in #lookup_data_from_index_factor. */ - blender::Array<float> sample_uniform_index_factors(int samples_size) const; + blender::Array<float> sample_uniform_index_factors(int samples_num) const; LookupResult lookup_data_from_index_factor(float index_factor) const; /** @@ -344,7 +344,7 @@ class BezierSpline final : public Spline { bool point_is_sharp(int index) const; void mark_cache_invalid() final; - int evaluated_points_size() const final; + int evaluated_points_num() const final; /** * Returns access to a cache of offsets into the evaluated point array for each control point. @@ -472,7 +472,7 @@ class NURBSpline final : public Spline { /** * Determines where and how the control points affect the evaluated points. The length should - * always be the value returned by #knots_size(), and each value should be greater than or equal + * always be the value returned by #knots_num(), and each value should be greater than or equal * to the previous. Only invalidated when a point is added or removed. */ mutable blender::Vector<float> knots_; @@ -514,8 +514,8 @@ class NURBSpline final : public Spline { uint8_t order() const; void set_order(uint8_t value); - bool check_valid_size_and_order() const; - int knots_size() const; + bool check_valid_num_and_order() const; + int knots_num() const; void resize(int size) final; blender::MutableSpan<blender::float3> positions() final; @@ -530,7 +530,7 @@ class NURBSpline final : public Spline { blender::Span<float> weights() const; void mark_cache_invalid() final; - int evaluated_points_size() const final; + int evaluated_points_num() const final; blender::Span<blender::float3> evaluated_positions() const final; @@ -582,7 +582,7 @@ class PolySpline final : public Spline { blender::Span<float> tilts() const final; void mark_cache_invalid() final; - int evaluated_points_size() const final; + int evaluated_points_num() const final; blender::Span<blender::float3> evaluated_positions() const final; @@ -665,7 +665,7 @@ struct CurveEval { blender::Array<float> accumulated_spline_lengths() const; float total_length() const; - int total_control_point_size() const; + int total_control_point_num() const; void mark_cache_invalid(); diff --git a/source/blender/blenkernel/BKE_subdiv.h b/source/blender/blenkernel/BKE_subdiv.h index 436853fe47b..486c9430279 100644 --- a/source/blender/blenkernel/BKE_subdiv.h +++ b/source/blender/blenkernel/BKE_subdiv.h @@ -186,13 +186,17 @@ typedef struct Subdiv { } cache_; } Subdiv; -/* =================----====--===== MODULE ==========================------== */ +/* -------------------------------------------------------------------- + * Module. + */ /* (De)initialize the entire subdivision surface module. */ void BKE_subdiv_init(void); void BKE_subdiv_exit(void); -/* ========================== CONVERSION HELPERS ============================ */ +/* -------------------------------------------------------------------- + * Conversion helpers. + */ /* NOTE: uv_smooth is eSubsurfUVSmooth. */ eSubdivFVarLinearInterpolation BKE_subdiv_fvar_interpolation_from_uv_smooth(int uv_smooth); @@ -200,7 +204,9 @@ eSubdivFVarLinearInterpolation BKE_subdiv_fvar_interpolation_from_uv_smooth(int eSubdivVtxBoundaryInterpolation BKE_subdiv_vtx_boundary_interpolation_from_subsurf( int boundary_smooth); -/* =============================== STATISTICS =============================== */ +/* -------------------------------------------------------------------- + * Statistics. + */ void BKE_subdiv_stats_init(SubdivStats *stats); @@ -211,11 +217,15 @@ void BKE_subdiv_stats_reset(SubdivStats *stats, eSubdivStatsValue value); void BKE_subdiv_stats_print(const SubdivStats *stats); -/* ================================ SETTINGS ================================ */ +/* -------------------------------------------------------------------- + * Settings. + */ bool BKE_subdiv_settings_equal(const SubdivSettings *settings_a, const SubdivSettings *settings_b); -/* ============================== CONSTRUCTION ============================== */ +/* -------------------------------------------------------------------- + * Construction. + */ /* Construct new subdivision surface descriptor, from scratch, using given * settings and topology. */ @@ -240,7 +250,9 @@ Subdiv *BKE_subdiv_update_from_mesh(Subdiv *subdiv, void BKE_subdiv_free(Subdiv *subdiv); -/* ============================ DISPLACEMENT API ============================ */ +/* -------------------------------------------------------------------- + * Displacement API. + */ void BKE_subdiv_displacement_attach_from_multires(Subdiv *subdiv, struct Mesh *mesh, @@ -248,14 +260,18 @@ void BKE_subdiv_displacement_attach_from_multires(Subdiv *subdiv, void BKE_subdiv_displacement_detach(Subdiv *subdiv); -/* ============================ TOPOLOGY HELPERS ============================ */ +/* -------------------------------------------------------------------- + * Topology helpers. + */ /* For each element in the array, this stores the total number of ptex faces up to that element, * with the total number of ptex faces being the last element in the array. The array is of length * `base face count + 1`. */ int *BKE_subdiv_face_ptex_offset_get(Subdiv *subdiv); -/* =========================== PTEX FACES AND GRIDS ========================= */ +/* -------------------------------------------------------------------- + * PTex faces and grids. + */ /* For a given (ptex_u, ptex_v) within a ptex face get corresponding * (grid_u, grid_v) within a grid. */ diff --git a/source/blender/blenkernel/BKE_subdiv_ccg.h b/source/blender/blenkernel/BKE_subdiv_ccg.h index 31a1912bc68..b30b707759c 100644 --- a/source/blender/blenkernel/BKE_subdiv_ccg.h +++ b/source/blender/blenkernel/BKE_subdiv_ccg.h @@ -8,7 +8,6 @@ #pragma once #include "BKE_DerivedMesh.h" -#include "BKE_customdata.h" #include "BLI_bitmap.h" #include "BLI_sys_types.h" @@ -21,6 +20,8 @@ struct CCGFace; struct CCGKey; struct DMFlagMat; struct Mesh; +struct MPoly; +struct MLoop; struct Subdiv; /* -------------------------------------------------------------------- @@ -309,8 +310,8 @@ typedef enum SubdivCCGAdjacencyType { * adjacent to a vertex, r_v1 and r_v2 will be the index of that vertex. */ SubdivCCGAdjacencyType BKE_subdiv_ccg_coarse_mesh_adjacency_info_get(const SubdivCCG *subdiv_ccg, const SubdivCCGCoord *coord, - const MLoop *mloop, - const MPoly *mpoly, + const struct MLoop *mloop, + const struct MPoly *mpoly, int *r_v1, int *r_v2); diff --git a/source/blender/blenkernel/BKE_subdiv_eval.h b/source/blender/blenkernel/BKE_subdiv_eval.h index 7673f18317a..cb0f2ac7e32 100644 --- a/source/blender/blenkernel/BKE_subdiv_eval.h +++ b/source/blender/blenkernel/BKE_subdiv_eval.h @@ -62,7 +62,7 @@ void BKE_subdiv_eval_limit_point_and_derivatives(struct Subdiv *subdiv, void BKE_subdiv_eval_limit_point_and_normal( struct Subdiv *subdiv, int ptex_face_index, float u, float v, float r_P[3], float r_N[3]); -/* Evaluate smoothly interpolated vertex data (such as orco). */ +/* Evaluate smoothly interpolated vertex data (such as ORCO). */ void BKE_subdiv_eval_vertex_data(struct Subdiv *subdiv, const int ptex_face_index, const float u, diff --git a/source/blender/blenkernel/BKE_subsurf.h b/source/blender/blenkernel/BKE_subsurf.h index 5dd2935ad0d..f32a78c3015 100644 --- a/source/blender/blenkernel/BKE_subsurf.h +++ b/source/blender/blenkernel/BKE_subsurf.h @@ -61,27 +61,6 @@ int BKE_ccg_gridsize(int level); */ int BKE_ccg_factor(int low_level, int high_level); -/** - * Translate #GridHidden into the #ME_HIDE flag for MVerts. Assumes - * vertices are in the order output by #ccgDM_copyFinalVertArray. - */ -void subsurf_copy_grid_hidden(struct DerivedMesh *dm, - const struct MPoly *mpoly, - struct MVert *mvert, - const struct MDisps *mdisps); - -/** - * Translate #GridPaintMask into vertex paint masks. Assumes vertices - * are in the order output by #ccgDM_copyFinalVertArray. - */ -void subsurf_copy_grid_paint_mask(struct DerivedMesh *dm, - const struct MPoly *mpoly, - float *paint_mask, - const struct GridPaintMask *grid_paint_mask); - -bool subsurf_has_edges(struct DerivedMesh *dm); -bool subsurf_has_faces(struct DerivedMesh *dm); - typedef enum MultiresModifiedFlags { /* indicates the grids have been sculpted on, so MDisps * have to be updated */ diff --git a/source/blender/blenkernel/BKE_tracking.h b/source/blender/blenkernel/BKE_tracking.h index 29eb180a2ab..3f6d32e2f70 100644 --- a/source/blender/blenkernel/BKE_tracking.h +++ b/source/blender/blenkernel/BKE_tracking.h @@ -28,7 +28,22 @@ struct Scene; struct bGPDlayer; struct rcti; -/* **** Common functions **** */ +/* -------------------------------------------------------------------- + * Common types and constants. + */ + +typedef enum eTrackArea { + TRACK_AREA_POINT = (1 << 0), + TRACK_AREA_PAT = (1 << 1), + TRACK_AREA_SEARCH = (1 << 2), + + TRACK_AREA_NONE = 0, + TRACK_AREA_ALL = (TRACK_AREA_POINT | TRACK_AREA_PAT | TRACK_AREA_SEARCH), +} eTrackArea; + +/* -------------------------------------------------------------------- + * Common functions. + */ /** * Free tracking structure, only frees structure contents @@ -84,7 +99,10 @@ void BKE_tracking_get_projection_matrix(struct MovieTracking *tracking, int winy, float mat[4][4]); -/* **** Clipboard **** */ +/* -------------------------------------------------------------------- + * Clipboard. + */ + /** * Free clipboard by freeing memory used by all tracks in it. */ @@ -204,15 +222,21 @@ bool BKE_tracking_track_has_marker_at_frame(struct MovieTrackingTrack *track, in bool BKE_tracking_track_has_enabled_marker_at_frame(struct MovieTrackingTrack *track, int framenr); /** - * Clear track's path: - * - * - If action is #TRACK_CLEAR_REMAINED path from `ref_frame+1` up to end will be clear. - * - If action is #TRACK_CLEAR_UPTO path from the beginning up to `ref_frame-1` will be clear. - * - If action is #TRACK_CLEAR_ALL only marker at frame ref_frame will remain. + * Clear track's path. * * \note frame number should be in clip space, not scene space. */ -void BKE_tracking_track_path_clear(struct MovieTrackingTrack *track, int ref_frame, int action); +typedef enum eTrackClearAction { + /* Clear path from `ref_frame+1` up to the . */ + TRACK_CLEAR_UPTO, + /* Clear path from the beginning up to `ref_frame-1`. */ + TRACK_CLEAR_REMAINED, + /* Only marker at frame `ref_frame` will remain. */ + TRACK_CLEAR_ALL, +} eTrackClearAction; +void BKE_tracking_track_path_clear(struct MovieTrackingTrack *track, + int ref_frame, + eTrackClearAction action); void BKE_tracking_tracks_join(struct MovieTracking *tracking, struct MovieTrackingTrack *dst_track, @@ -240,7 +264,9 @@ float BKE_tracking_track_get_weight_for_marker(struct MovieClip *clip, struct MovieTrackingTrack *track, struct MovieTrackingMarker *marker); -/* Selection */ +/* -------------------------------------------------------------------- + * Selection. + */ /** * \param area: which part of marker should be selected. see TRACK_AREA_* constants. @@ -252,12 +278,43 @@ void BKE_tracking_track_select(struct ListBase *tracksbase, void BKE_tracking_track_deselect(struct MovieTrackingTrack *track, int area); void BKE_tracking_tracks_deselect_all(struct ListBase *tracksbase); -/* **** Marker **** */ +/* -------------------------------------------------------------------- + * Marker. + */ + struct MovieTrackingMarker *BKE_tracking_marker_insert(struct MovieTrackingTrack *track, struct MovieTrackingMarker *marker); void BKE_tracking_marker_delete(struct MovieTrackingTrack *track, int framenr); -void BKE_tracking_marker_clamp(struct MovieTrackingMarker *marker, int event); +/** + * If the pattern area is outside of the search area its position will be modified in a way that it + * is within the pattern is within the search area. + * + * If the pattern area is already within the search area nothing happens. + * + * If the pattern area is bigger than the search area the behavior is undefined. + * + * Search area is never modified. + */ +void BKE_tracking_marker_clamp_pattern_position(struct MovieTrackingMarker *marker); + +/** + * If the search size is such that pattern area is (partially) outside of the search area make the + * search area bigger so that the pattern is within the search area. + * + * Pattern area is never modified. + */ +void BKE_tracking_marker_clamp_search_size(struct MovieTrackingMarker *marker); + +/** + * If the search position is such that pattern area is (partially) outside of the search area move + * the search area so that the pattern is within the search area. + * + * If the search area is smaller than the pattern the behavior is undefined. + * + * Pattern area is never modified. + */ +void BKE_tracking_marker_clamp_search_position(struct MovieTrackingMarker *marker); /** * Get marker closest to the given frame number. @@ -296,7 +353,10 @@ void BKE_tracking_marker_get_subframe_position(struct MovieTrackingTrack *track, float framenr, float pos[2]); -/* **** Plane Track **** */ +/* -------------------------------------------------------------------- + * Plane track. + */ + /** * Creates new plane track out of selected point tracks. */ @@ -342,7 +402,10 @@ void BKE_tracking_plane_tracks_replace_point_track(struct MovieTracking *trackin struct MovieTrackingTrack *old_track, struct MovieTrackingTrack *new_track); -/* **** Plane Marker **** */ +/* -------------------------------------------------------------------- + * Plane marker. + */ + struct MovieTrackingPlaneMarker *BKE_tracking_plane_marker_insert( struct MovieTrackingPlaneTrack *plane_track, struct MovieTrackingPlaneMarker *plane_marker); void BKE_tracking_plane_marker_delete(struct MovieTrackingPlaneTrack *plane_track, int framenr); @@ -368,7 +431,10 @@ void BKE_tracking_plane_marker_get_subframe_corners(struct MovieTrackingPlaneTra float framenr, float corners[4][2]); -/* **** Object **** */ +/* -------------------------------------------------------------------- + * Object. + */ + struct MovieTrackingObject *BKE_tracking_object_add(struct MovieTracking *tracking, const char *name); bool BKE_tracking_object_delete(struct MovieTracking *tracking, @@ -390,7 +456,10 @@ struct ListBase *BKE_tracking_object_get_plane_tracks(struct MovieTracking *trac struct MovieTrackingReconstruction *BKE_tracking_object_get_reconstruction( struct MovieTracking *tracking, struct MovieTrackingObject *object); -/* **** Camera **** */ +/* -------------------------------------------------------------------- + * Camera. + */ + /** * Converts principal offset from center to offset of blender's camera. */ @@ -409,7 +478,10 @@ void BKE_tracking_camera_get_reconstructed_interpolate(struct MovieTracking *tra float framenr, float mat[4][4]); -/* **** Distortion/Undistortion **** */ +/* -------------------------------------------------------------------- + * (Un)distortion. + */ + struct MovieDistortion *BKE_tracking_distortion_new(struct MovieTracking *tracking, int calibration_width, int calibration_height); @@ -463,7 +535,10 @@ void BKE_tracking_max_distortion_delta_across_bound(struct MovieTracking *tracki bool undistort, float delta[2]); -/* **** Image sampling **** */ +/* -------------------------------------------------------------------- + * Image sampling. + */ + struct ImBuf *BKE_tracking_sample_pattern(int frame_width, int frame_height, struct ImBuf *search_ib, @@ -493,7 +568,9 @@ struct ImBuf *BKE_tracking_get_search_imbuf(struct ImBuf *ibuf, void BKE_tracking_disable_channels( struct ImBuf *ibuf, bool disable_red, bool disable_green, bool disable_blue, bool grayscale); -/* **** 2D tracking **** */ +/* -------------------------------------------------------------------- + * 2D tracking. + */ /** * Refine marker's position using previously known keyframe. @@ -505,7 +582,9 @@ void BKE_tracking_refine_marker(struct MovieClip *clip, struct MovieTrackingMarker *marker, bool backwards); -/* *** 2D auto track *** */ +/* -------------------------------------------------------------------- + * 2D tracking using auto-track pipeline. + */ struct AutoTrackContext *BKE_autotrack_context_new(struct MovieClip *clip, struct MovieClipUser *user, @@ -517,7 +596,9 @@ void BKE_autotrack_context_sync_user(struct AutoTrackContext *context, struct Mo void BKE_autotrack_context_finish(struct AutoTrackContext *context); void BKE_autotrack_context_free(struct AutoTrackContext *context); -/* **** Plane tracking **** */ +/* -------------------------------------------------------------------- + * Plane tracking. + */ /** * \note frame number should be in clip space, not scene space. @@ -530,7 +611,9 @@ void BKE_tracking_homography_between_two_quads(/*const*/ float reference_corners /*const*/ float corners[4][2], float H[3][3]); -/* **** Camera solving **** */ +/* -------------------------------------------------------------------- + * Camera solving. + */ /** * Perform early check on whether everything is fine to start reconstruction. @@ -617,7 +700,9 @@ void BKE_tracking_detect_harris(struct MovieTracking *tracking, struct bGPDlayer *layer, bool place_outside_layer); -/* **** 2D stabilization **** */ +/* -------------------------------------------------------------------- + * 2D stabilization. + */ /** * Get stabilization data (translation, scaling and angle) for a given frame. @@ -686,7 +771,9 @@ void BKE_tracking_dopesheet_tag_update(struct MovieTracking *tracking); */ void BKE_tracking_dopesheet_update(struct MovieTracking *tracking); -/* **** Query/search **** */ +/* -------------------------------------------------------------------- + * Query and search. + */ /** * \note Returns NULL if the track comes from camera object,. @@ -722,7 +809,9 @@ void BKE_tracking_get_rna_path_prefix_for_plane_track( char *rna_path, size_t rna_path_len); -/* **** Utility macros **** */ +/* -------------------------------------------------------------------- + * Utility macros. + */ #define TRACK_SELECTED(track) \ ((track)->flag & SELECT || (track)->pat_flag & SELECT || (track)->search_flag & SELECT) @@ -745,22 +834,6 @@ void BKE_tracking_get_rna_path_prefix_for_plane_track( (((marker)->flag & MARKER_DISABLED) == 0 || ((sc)->flag & SC_HIDE_DISABLED) == 0 || \ ((sc)->clip->tracking.act_track == track)) -#define TRACK_CLEAR_UPTO 0 -#define TRACK_CLEAR_REMAINED 1 -#define TRACK_CLEAR_ALL 2 - -#define CLAMP_PAT_DIM 1 -#define CLAMP_PAT_POS 2 -#define CLAMP_SEARCH_DIM 3 -#define CLAMP_SEARCH_POS 4 - -#define TRACK_AREA_NONE -1 -#define TRACK_AREA_POINT 1 -#define TRACK_AREA_PAT 2 -#define TRACK_AREA_SEARCH 4 - -#define TRACK_AREA_ALL (TRACK_AREA_POINT | TRACK_AREA_PAT | TRACK_AREA_SEARCH) - #ifdef __cplusplus } #endif diff --git a/source/blender/blenkernel/CMakeLists.txt b/source/blender/blenkernel/CMakeLists.txt index a57d4d0a2bf..8dc6f711fae 100644 --- a/source/blender/blenkernel/CMakeLists.txt +++ b/source/blender/blenkernel/CMakeLists.txt @@ -76,7 +76,7 @@ set(SRC intern/asset_catalog_path.cc intern/asset_library.cc intern/asset_library_service.cc - intern/attribute.c + intern/attribute.cc intern/attribute_access.cc intern/attribute_math.cc intern/autoexec.c @@ -117,6 +117,7 @@ set(SRC intern/curveprofile.cc intern/curves.cc intern/curves_geometry.cc + intern/curves_utils.cc intern/customdata.cc intern/customdata_file.c intern/data_transfer.c @@ -173,7 +174,7 @@ set(SRC intern/lib_id_delete.c intern/lib_id_eval.c intern/lib_id_remapper.cc - intern/lib_override.c + intern/lib_override.cc intern/lib_override_proxy_conversion.c intern/lib_query.c intern/lib_remap.c @@ -242,8 +243,8 @@ set(SRC intern/particle_child.c intern/particle_distribute.c intern/particle_system.c - intern/pbvh.cc intern/pbvh.c + intern/pbvh.cc intern/pbvh_bmesh.c intern/pbvh_pixels.cc intern/pointcache.c @@ -356,6 +357,7 @@ set(SRC BKE_curveprofile.h BKE_curves.h BKE_curves.hh + BKE_curves_utils.hh BKE_customdata.h BKE_customdata_file.h BKE_data_transfer.h @@ -429,6 +431,7 @@ set(SRC BKE_multires.h BKE_nla.h BKE_node.h + BKE_node_runtime.hh BKE_node_tree_update.h BKE_object.h BKE_object_deform.h @@ -608,7 +611,7 @@ if(WITH_IMAGE_HDR) endif() if(WITH_IMAGE_WEBP) - add_definitions(-DWITH_WEBP) + add_definitions(-DWITH_WEBP) endif() if(WITH_CODEC_AVI) diff --git a/source/blender/blenkernel/intern/DerivedMesh.cc b/source/blender/blenkernel/intern/DerivedMesh.cc index 6b43fe57e93..5cf0ca6e062 100644 --- a/source/blender/blenkernel/intern/DerivedMesh.cc +++ b/source/blender/blenkernel/intern/DerivedMesh.cc @@ -423,21 +423,6 @@ static void mesh_set_only_copy(Mesh *mesh, const CustomData_MeshMasks *mask) #endif } -void DM_add_vert_layer(DerivedMesh *dm, int type, eCDAllocType alloctype, void *layer) -{ - CustomData_add_layer(&dm->vertData, type, alloctype, layer, dm->numVertData); -} - -void DM_add_edge_layer(DerivedMesh *dm, int type, eCDAllocType alloctype, void *layer) -{ - CustomData_add_layer(&dm->edgeData, type, alloctype, layer, dm->numEdgeData); -} - -void DM_add_poly_layer(DerivedMesh *dm, int type, eCDAllocType alloctype, void *layer) -{ - CustomData_add_layer(&dm->polyData, type, alloctype, layer, dm->numPolyData); -} - void *DM_get_vert_data_layer(DerivedMesh *dm, int type) { if (type == CD_MVERT) { diff --git a/source/blender/blenkernel/intern/anim_sys.c b/source/blender/blenkernel/intern/anim_sys.c index b886722676b..94b85e42f96 100644 --- a/source/blender/blenkernel/intern/anim_sys.c +++ b/source/blender/blenkernel/intern/anim_sys.c @@ -2868,7 +2868,7 @@ static void nlastrip_evaluate_meta(const int evaluation_mode, /* Assert currently supported modes. If new mode added, then assertion marks potentially missed * area. * - * Note: In the future if support is ever added to metastrips to support nested tracks, then + * NOTE: In the future if support is ever added to metastrips to support nested tracks, then * STRIP_EVAL_BLEND and STRIP_EVAL_BLEND_GET_INVERTED_LOWER_SNAPSHOT cases are no longer * equivalent. The output of nlastrips_ctime_get_strip() may return a list of strips. The only * case difference should be the evaluation order. diff --git a/source/blender/blenkernel/intern/anonymous_attribute.cc b/source/blender/blenkernel/intern/anonymous_attribute.cc index 6ce6bee547c..636e0af0edf 100644 --- a/source/blender/blenkernel/intern/anonymous_attribute.cc +++ b/source/blender/blenkernel/intern/anonymous_attribute.cc @@ -41,7 +41,7 @@ static std::string get_new_internal_name() { static std::atomic<int> index = 0; const int next_index = index.fetch_add(1); - return "anonymous_attribute_" + std::to_string(next_index); + return ".a_" + std::to_string(next_index); } AnonymousAttributeID *BKE_anonymous_attribute_id_new_weak(const char *debug_name) diff --git a/source/blender/blenkernel/intern/appdir.c b/source/blender/blenkernel/intern/appdir.c index 8d3649fef08..031d3647878 100644 --- a/source/blender/blenkernel/intern/appdir.c +++ b/source/blender/blenkernel/intern/appdir.c @@ -61,7 +61,7 @@ static CLG_LogRef LOG = {"bke.appdir"}; static struct { /** Full path to program executable. */ - char program_filename[FILE_MAX]; + char program_filepath[FILE_MAX]; /** Full path to directory in which executable is located. */ char program_dirname[FILE_MAX]; /** Persistent temporary directory (defined by the preferences or OS). */ @@ -860,14 +860,14 @@ static void where_am_i(char *fullname, const size_t maxlen, const char *name) void BKE_appdir_program_path_init(const char *argv0) { - where_am_i(g_app.program_filename, sizeof(g_app.program_filename), argv0); - BLI_split_dir_part(g_app.program_filename, g_app.program_dirname, sizeof(g_app.program_dirname)); + where_am_i(g_app.program_filepath, sizeof(g_app.program_filepath), argv0); + BLI_split_dir_part(g_app.program_filepath, g_app.program_dirname, sizeof(g_app.program_dirname)); } const char *BKE_appdir_program_path(void) { - BLI_assert(g_app.program_filename[0]); - return g_app.program_filename; + BLI_assert(g_app.program_filepath[0]); + return g_app.program_filepath; } const char *BKE_appdir_program_dir(void) diff --git a/source/blender/blenkernel/intern/asset_catalog_test.cc b/source/blender/blenkernel/intern/asset_catalog_test.cc index 11f36e32b74..81eb1786322 100644 --- a/source/blender/blenkernel/intern/asset_catalog_test.cc +++ b/source/blender/blenkernel/intern/asset_catalog_test.cc @@ -318,7 +318,7 @@ TEST_F(AssetCatalogTest, load_catalog_path_backslashes) const AssetCatalog *found_by_id = service.find_catalog(UUID_POSES_ELLIE_BACKSLASHES); ASSERT_NE(nullptr, found_by_id); EXPECT_EQ(AssetCatalogPath("character/Ellie/backslashes"), found_by_id->path) - << "Backslashes should be normalised when loading from disk."; + << "Backslashes should be normalized when loading from disk."; EXPECT_EQ(StringRefNull("Windows For Life!"), found_by_id->simple_name); const AssetCatalog *found_by_path = service.find_catalog_by_path("character/Ellie/backslashes"); diff --git a/source/blender/blenkernel/intern/attribute.c b/source/blender/blenkernel/intern/attribute.cc index 0cb0704ff80..cfddae7721b 100644 --- a/source/blender/blenkernel/intern/attribute.c +++ b/source/blender/blenkernel/intern/attribute.cc @@ -7,7 +7,7 @@ * on top of CustomData, which manages individual domains. */ -#include <string.h> +#include <cstring> #include "MEM_guardedalloc.h" @@ -18,10 +18,12 @@ #include "DNA_meshdata_types.h" #include "DNA_pointcloud_types.h" +#include "BLI_index_range.hh" #include "BLI_string_utf8.h" #include "BLI_string_utils.h" #include "BKE_attribute.h" +#include "BKE_attribute_access.hh" #include "BKE_curves.h" #include "BKE_customdata.h" #include "BKE_editmesh.h" @@ -30,10 +32,12 @@ #include "RNA_access.h" -typedef struct DomainInfo { +using blender::IndexRange; + +struct DomainInfo { CustomData *customdata; int length; -} DomainInfo; +}; static void get_domains(const ID *id, DomainInfo info[ATTR_DOMAIN_NUM]) { @@ -49,7 +53,7 @@ static void get_domains(const ID *id, DomainInfo info[ATTR_DOMAIN_NUM]) case ID_ME: { Mesh *mesh = (Mesh *)id; BMEditMesh *em = mesh->edit_mesh; - if (em != NULL) { + if (em != nullptr) { BMesh *bm = em->bm; info[ATTR_DOMAIN_POINT].customdata = &bm->vdata; info[ATTR_DOMAIN_POINT].length = bm->totvert; @@ -75,9 +79,9 @@ static void get_domains(const ID *id, DomainInfo info[ATTR_DOMAIN_NUM]) case ID_CV: { Curves *curves = (Curves *)id; info[ATTR_DOMAIN_POINT].customdata = &curves->geometry.point_data; - info[ATTR_DOMAIN_POINT].length = curves->geometry.point_size; + info[ATTR_DOMAIN_POINT].length = curves->geometry.point_num; info[ATTR_DOMAIN_CURVE].customdata = &curves->geometry.curve_data; - info[ATTR_DOMAIN_CURVE].length = curves->geometry.curve_size; + info[ATTR_DOMAIN_CURVE].length = curves->geometry.curve_num; break; } default: @@ -90,7 +94,7 @@ static CustomData *attribute_customdata_find(ID *id, CustomDataLayer *layer) DomainInfo info[ATTR_DOMAIN_NUM]; get_domains(id, info); - for (AttributeDomain domain = 0; domain < ATTR_DOMAIN_NUM; domain++) { + for (const int domain : IndexRange(ATTR_DOMAIN_NUM)) { CustomData *customdata = info[domain].customdata; if (customdata && ARRAY_HAS_ITEM((CustomDataLayer *)layer, customdata->layers, customdata->totlayer)) { @@ -98,14 +102,14 @@ static CustomData *attribute_customdata_find(ID *id, CustomDataLayer *layer) } } - return NULL; + return nullptr; } -bool BKE_id_attributes_supported(struct ID *id) +bool BKE_id_attributes_supported(ID *id) { DomainInfo info[ATTR_DOMAIN_NUM]; get_domains(id, info); - for (AttributeDomain domain = 0; domain < ATTR_DOMAIN_NUM; domain++) { + for (const int domain : IndexRange(ATTR_DOMAIN_NUM)) { if (info[domain].customdata) { return true; } @@ -113,6 +117,11 @@ bool BKE_id_attributes_supported(struct ID *id) return false; } +bool BKE_attribute_allow_procedural_access(const char *attribute_name) +{ + return blender::bke::allow_procedural_attribute_access(attribute_name); +} + bool BKE_id_attribute_rename(ID *id, CustomDataLayer *layer, const char *new_name, @@ -124,7 +133,7 @@ bool BKE_id_attribute_rename(ID *id, } CustomData *customdata = attribute_customdata_find(id, layer); - if (customdata == NULL) { + if (customdata == nullptr) { BKE_report(reports, RPT_ERROR, "Attribute is not part of this geometry"); return false; } @@ -134,9 +143,9 @@ bool BKE_id_attribute_rename(ID *id, return true; } -typedef struct AttrUniqueData { +struct AttrUniqueData { ID *id; -} AttrUniqueData; +}; static bool unique_name_cb(void *arg, const char *name) { @@ -145,7 +154,7 @@ static bool unique_name_cb(void *arg, const char *name) DomainInfo info[ATTR_DOMAIN_NUM]; get_domains(data->id, info); - for (AttributeDomain domain = ATTR_DOMAIN_POINT; domain < ATTR_DOMAIN_NUM; domain++) { + for (const int domain : IndexRange(ATTR_DOMAIN_NUM)) { if (!info[domain].customdata) { continue; } @@ -165,11 +174,12 @@ static bool unique_name_cb(void *arg, const char *name) bool BKE_id_attribute_calc_unique_name(ID *id, const char *name, char *outname) { - AttrUniqueData data = {.id = id}; + AttrUniqueData data{id}; BLI_strncpy_utf8(outname, name, MAX_CUSTOMDATA_LAYER_NAME); - return BLI_uniquename_cb(unique_name_cb, &data, NULL, '.', outname, MAX_CUSTOMDATA_LAYER_NAME); + return BLI_uniquename_cb( + unique_name_cb, &data, nullptr, '.', outname, MAX_CUSTOMDATA_LAYER_NAME); } CustomDataLayer *BKE_id_attribute_new( @@ -179,9 +189,9 @@ CustomDataLayer *BKE_id_attribute_new( get_domains(id, info); CustomData *customdata = info[domain].customdata; - if (customdata == NULL) { + if (customdata == nullptr) { BKE_report(reports, RPT_ERROR, "Attribute domain not supported by this geometry type"); - return NULL; + return nullptr; } char uniquename[MAX_CUSTOMDATA_LAYER_NAME]; @@ -191,24 +201,24 @@ CustomDataLayer *BKE_id_attribute_new( case ID_ME: { Mesh *me = (Mesh *)id; BMEditMesh *em = me->edit_mesh; - if (em != NULL) { + if (em != nullptr) { BM_data_layer_add_named(em->bm, customdata, type, uniquename); } else { CustomData_add_layer_named( - customdata, type, CD_DEFAULT, NULL, info[domain].length, uniquename); + customdata, type, CD_DEFAULT, nullptr, info[domain].length, uniquename); } break; } default: { CustomData_add_layer_named( - customdata, type, CD_DEFAULT, NULL, info[domain].length, uniquename); + customdata, type, CD_DEFAULT, nullptr, info[domain].length, uniquename); break; } } const int index = CustomData_get_named_layer_index(customdata, type, uniquename); - return (index == -1) ? NULL : &(customdata->layers[index]); + return (index == -1) ? nullptr : &(customdata->layers[index]); } bool BKE_id_attribute_remove(ID *id, CustomDataLayer *layer, ReportList *reports) @@ -232,7 +242,7 @@ bool BKE_id_attribute_remove(ID *id, CustomDataLayer *layer, ReportList *reports case ID_ME: { Mesh *me = (Mesh *)id; BMEditMesh *em = me->edit_mesh; - if (em != NULL) { + if (em != nullptr) { BM_data_layer_free(em->bm, customdata, layer->type); } else { @@ -260,8 +270,8 @@ CustomDataLayer *BKE_id_attribute_find(const ID *id, get_domains(id, info); CustomData *customdata = info[domain].customdata; - if (customdata == NULL) { - return NULL; + if (customdata == nullptr) { + return nullptr; } for (int i = 0; i < customdata->totlayer; i++) { @@ -271,7 +281,7 @@ CustomDataLayer *BKE_id_attribute_find(const ID *id, } } - return NULL; + return nullptr; } int BKE_id_attributes_length(const ID *id, AttributeDomainMask domain_mask, CustomDataMask mask) @@ -281,7 +291,7 @@ int BKE_id_attributes_length(const ID *id, AttributeDomainMask domain_mask, Cust int length = 0; - for (AttributeDomain domain = 0; domain < ATTR_DOMAIN_NUM; domain++) { + for (const int domain : IndexRange(ATTR_DOMAIN_NUM)) { CustomData *customdata = info[domain].customdata; if (customdata && ((1 << (int)domain) & domain_mask)) { @@ -297,16 +307,16 @@ AttributeDomain BKE_id_attribute_domain(const ID *id, const CustomDataLayer *lay DomainInfo info[ATTR_DOMAIN_NUM]; get_domains(id, info); - for (AttributeDomain domain = 0; domain < ATTR_DOMAIN_NUM; domain++) { + for (const int domain : IndexRange(ATTR_DOMAIN_NUM)) { CustomData *customdata = info[domain].customdata; if (customdata && ARRAY_HAS_ITEM((CustomDataLayer *)layer, customdata->layers, customdata->totlayer)) { - return domain; + return static_cast<AttributeDomain>(domain); } } BLI_assert_msg(0, "Custom data layer not found in geometry"); - return ATTR_DOMAIN_NUM; + return static_cast<AttributeDomain>(ATTR_DOMAIN_POINT); } int BKE_id_attribute_data_length(ID *id, CustomDataLayer *layer) @@ -317,7 +327,7 @@ int BKE_id_attribute_data_length(ID *id, CustomDataLayer *layer) switch (GS(id->name)) { case ID_ME: { Mesh *mesh = (Mesh *)id; - if (mesh->edit_mesh != NULL) { + if (mesh->edit_mesh != nullptr) { return 0; } } @@ -328,7 +338,7 @@ int BKE_id_attribute_data_length(ID *id, CustomDataLayer *layer) DomainInfo info[ATTR_DOMAIN_NUM]; get_domains(id, info); - for (AttributeDomain domain = 0; domain < ATTR_DOMAIN_NUM; domain++) { + for (const int domain : IndexRange(ATTR_DOMAIN_NUM)) { CustomData *customdata = info[domain].customdata; if (customdata && ARRAY_HAS_ITEM((CustomDataLayer *)layer, customdata->layers, customdata->totlayer)) { @@ -366,7 +376,7 @@ CustomDataLayer *BKE_id_attributes_active_get(ID *id) int index = 0; - for (AttributeDomain domain = 0; domain < ATTR_DOMAIN_NUM; domain++) { + for (const int domain : IndexRange(ATTR_DOMAIN_NUM)) { CustomData *customdata = info[domain].customdata; if (customdata) { for (int i = 0; i < customdata->totlayer; i++) { @@ -381,7 +391,7 @@ CustomDataLayer *BKE_id_attributes_active_get(ID *id) } } - return NULL; + return nullptr; } void BKE_id_attributes_active_set(ID *id, CustomDataLayer *active_layer) @@ -391,7 +401,7 @@ void BKE_id_attributes_active_set(ID *id, CustomDataLayer *active_layer) int index = 0; - for (AttributeDomain domain = 0; domain < ATTR_DOMAIN_NUM; domain++) { + for (const int domain : IndexRange(ATTR_DOMAIN_NUM)) { CustomData *customdata = info[domain].customdata; if (customdata) { for (int i = 0; i < customdata->totlayer; i++) { @@ -421,7 +431,7 @@ int *BKE_id_attributes_active_index_p(ID *id) return &((Curves *)id)->attributes_active_index; } default: - return NULL; + return nullptr; } } @@ -430,9 +440,9 @@ CustomData *BKE_id_attributes_iterator_next_domain(ID *id, CustomDataLayer *laye DomainInfo info[ATTR_DOMAIN_NUM]; get_domains(id, info); - bool use_next = (layers == NULL); + bool use_next = (layers == nullptr); - for (AttributeDomain domain = 0; domain < ATTR_DOMAIN_NUM; domain++) { + for (const int domain : IndexRange(ATTR_DOMAIN_NUM)) { CustomData *customdata = info[domain].customdata; if (customdata && customdata->layers && customdata->totlayer) { if (customdata->layers == layers) { @@ -444,7 +454,7 @@ CustomData *BKE_id_attributes_iterator_next_domain(ID *id, CustomDataLayer *laye } } - return NULL; + return nullptr; } CustomDataLayer *BKE_id_attribute_from_index(ID *id, @@ -456,7 +466,7 @@ CustomDataLayer *BKE_id_attribute_from_index(ID *id, get_domains(id, info); int index = 0; - for (AttributeDomain domain = 0; domain < ATTR_DOMAIN_NUM; domain++) { + for (const int domain : IndexRange(ATTR_DOMAIN_NUM)) { CustomData *customdata = info[domain].customdata; if (!customdata || !((1 << (int)domain) & domain_mask)) { @@ -477,7 +487,7 @@ CustomDataLayer *BKE_id_attribute_from_index(ID *id, } } - return NULL; + return nullptr; } /** Get list of domain types but with ATTR_DOMAIN_FACE and @@ -485,15 +495,15 @@ CustomDataLayer *BKE_id_attribute_from_index(ID *id, */ static void get_domains_types(AttributeDomain domains[ATTR_DOMAIN_NUM]) { - for (AttributeDomain i = 0; i < ATTR_DOMAIN_NUM; i++) { - domains[i] = i; + for (const int i : IndexRange(ATTR_DOMAIN_NUM)) { + domains[i] = static_cast<AttributeDomain>(i); } /* Swap corner and face. */ SWAP(AttributeDomain, domains[ATTR_DOMAIN_FACE], domains[ATTR_DOMAIN_CORNER]); } -int BKE_id_attribute_to_index(const struct ID *id, +int BKE_id_attribute_to_index(const ID *id, const CustomDataLayer *layer, AttributeDomainMask domain_mask, CustomDataMask layer_mask) @@ -544,7 +554,7 @@ CustomDataLayer *BKE_id_attribute_subset_active_get(const ID *id, get_domains_types(domains); get_domains(id, info); - CustomDataLayer *candidate = NULL; + CustomDataLayer *candidate = nullptr; for (int i = 0; i < ARRAY_SIZE(domains); i++) { if (!((1 << domains[i]) & domain_mask) || !info[domains[i]].customdata) { continue; @@ -632,13 +642,13 @@ void BKE_id_attributes_render_color_set(ID *id, CustomDataLayer *active_layer) CustomDataLayer *BKE_id_attributes_color_find(const ID *id, const char *name) { CustomDataLayer *layer = BKE_id_attribute_find(id, name, CD_PROP_COLOR, ATTR_DOMAIN_POINT); - if (layer == NULL) { + if (layer == nullptr) { layer = BKE_id_attribute_find(id, name, CD_PROP_COLOR, ATTR_DOMAIN_CORNER); } - if (layer == NULL) { + if (layer == nullptr) { layer = BKE_id_attribute_find(id, name, CD_PROP_BYTE_COLOR, ATTR_DOMAIN_POINT); } - if (layer == NULL) { + if (layer == nullptr) { layer = BKE_id_attribute_find(id, name, CD_PROP_BYTE_COLOR, ATTR_DOMAIN_CORNER); } return layer; @@ -661,7 +671,7 @@ void BKE_id_attribute_copy_domains_temp(short id_type, Mesh *me = (Mesh *)r_id; memset((void *)me, 0, sizeof(*me)); - me->edit_mesh = NULL; + me->edit_mesh = nullptr; me->vdata = vdata ? *vdata : reset; me->edata = edata ? *edata : reset; diff --git a/source/blender/blenkernel/intern/attribute_access.cc b/source/blender/blenkernel/intern/attribute_access.cc index d33b64c493b..e487bf4acf6 100644 --- a/source/blender/blenkernel/intern/attribute_access.cc +++ b/source/blender/blenkernel/intern/attribute_access.cc @@ -55,6 +55,14 @@ std::ostream &operator<<(std::ostream &stream, const AttributeIDRef &attribute_i return stream; } +const char *no_procedural_access_message = + "This attribute can not be accessed in a procedural context"; + +bool allow_procedural_attribute_access(StringRef attribute_name) +{ + return !attribute_name.startswith(".selection"); +} + static int attribute_data_type_complexity(const CustomDataType data_type) { switch (data_type) { @@ -184,16 +192,16 @@ static AttributeIDRef attribute_id_from_custom_data_layer(const CustomDataLayer static bool add_builtin_type_custom_data_layer_from_init(CustomData &custom_data, const CustomDataType data_type, - const int domain_size, + const int domain_num, const AttributeInit &initializer) { switch (initializer.type) { case AttributeInit::Type::Default: { - void *data = CustomData_add_layer(&custom_data, data_type, CD_DEFAULT, nullptr, domain_size); + void *data = CustomData_add_layer(&custom_data, data_type, CD_DEFAULT, nullptr, domain_num); return data != nullptr; } case AttributeInit::Type::VArray: { - void *data = CustomData_add_layer(&custom_data, data_type, CD_DEFAULT, nullptr, domain_size); + void *data = CustomData_add_layer(&custom_data, data_type, CD_DEFAULT, nullptr, domain_num); if (data == nullptr) { return false; } @@ -204,7 +212,7 @@ static bool add_builtin_type_custom_data_layer_from_init(CustomData &custom_data case AttributeInit::Type::MoveArray: { void *source_data = static_cast<const AttributeInitMove &>(initializer).data; void *data = CustomData_add_layer( - &custom_data, data_type, CD_ASSIGN, source_data, domain_size); + &custom_data, data_type, CD_ASSIGN, source_data, domain_num); if (data == nullptr) { MEM_freeN(source_data); return false; @@ -221,35 +229,35 @@ static void *add_generic_custom_data_layer(CustomData &custom_data, const CustomDataType data_type, const eCDAllocType alloctype, void *layer_data, - const int domain_size, + const int domain_num, const AttributeIDRef &attribute_id) { if (attribute_id.is_named()) { char attribute_name_c[MAX_NAME]; attribute_id.name().copy(attribute_name_c); return CustomData_add_layer_named( - &custom_data, data_type, alloctype, layer_data, domain_size, attribute_name_c); + &custom_data, data_type, alloctype, layer_data, domain_num, attribute_name_c); } const AnonymousAttributeID &anonymous_id = attribute_id.anonymous_id(); return CustomData_add_layer_anonymous( - &custom_data, data_type, alloctype, layer_data, domain_size, &anonymous_id); + &custom_data, data_type, alloctype, layer_data, domain_num, &anonymous_id); } static bool add_custom_data_layer_from_attribute_init(const AttributeIDRef &attribute_id, CustomData &custom_data, const CustomDataType data_type, - const int domain_size, + const int domain_num, const AttributeInit &initializer) { switch (initializer.type) { case AttributeInit::Type::Default: { void *data = add_generic_custom_data_layer( - custom_data, data_type, CD_DEFAULT, nullptr, domain_size, attribute_id); + custom_data, data_type, CD_DEFAULT, nullptr, domain_num, attribute_id); return data != nullptr; } case AttributeInit::Type::VArray: { void *data = add_generic_custom_data_layer( - custom_data, data_type, CD_DEFAULT, nullptr, domain_size, attribute_id); + custom_data, data_type, CD_DEFAULT, nullptr, domain_num, attribute_id); if (data == nullptr) { return false; } @@ -260,7 +268,7 @@ static bool add_custom_data_layer_from_attribute_init(const AttributeIDRef &attr case AttributeInit::Type::MoveArray: { void *source_data = static_cast<const AttributeInitMove &>(initializer).data; void *data = add_generic_custom_data_layer( - custom_data, data_type, CD_ASSIGN, source_data, domain_size, attribute_id); + custom_data, data_type, CD_ASSIGN, source_data, domain_num, attribute_id); if (data == nullptr) { MEM_freeN(source_data); return false; @@ -303,8 +311,8 @@ GVArray BuiltinCustomDataLayerProvider::try_get_for_read(const GeometryComponent return {}; } - const int domain_size = component.attribute_domain_size(domain_); - return as_read_attribute_(data, domain_size); + const int domain_num = component.attribute_domain_num(domain_); + return as_read_attribute_(data, domain_num); } WriteAttributeLookup BuiltinCustomDataLayerProvider::try_get_for_write( @@ -317,7 +325,7 @@ WriteAttributeLookup BuiltinCustomDataLayerProvider::try_get_for_write( if (custom_data == nullptr) { return {}; } - const int domain_size = component.attribute_domain_size(domain_); + const int domain_num = component.attribute_domain_num(domain_); void *data; if (stored_as_named_attribute_) { @@ -333,10 +341,10 @@ WriteAttributeLookup BuiltinCustomDataLayerProvider::try_get_for_write( void *new_data; if (stored_as_named_attribute_) { new_data = CustomData_duplicate_referenced_layer_named( - custom_data, stored_type_, name_.c_str(), domain_size); + custom_data, stored_type_, name_.c_str(), domain_num); } else { - new_data = CustomData_duplicate_referenced_layer(custom_data, stored_type_, domain_size); + new_data = CustomData_duplicate_referenced_layer(custom_data, stored_type_, domain_num); } if (data != new_data) { @@ -353,7 +361,7 @@ WriteAttributeLookup BuiltinCustomDataLayerProvider::try_get_for_write( }; } - return {as_write_attribute_(data, domain_size), domain_, std::move(tag_modified_fn)}; + return {as_write_attribute_(data, domain_num), domain_, std::move(tag_modified_fn)}; } bool BuiltinCustomDataLayerProvider::try_delete(GeometryComponent &component) const @@ -366,7 +374,7 @@ bool BuiltinCustomDataLayerProvider::try_delete(GeometryComponent &component) co return {}; } - const int domain_size = component.attribute_domain_size(domain_); + const int domain_num = component.attribute_domain_num(domain_); int layer_index; if (stored_as_named_attribute_) { for (const int i : IndexRange(custom_data->totlayer)) { @@ -381,7 +389,7 @@ bool BuiltinCustomDataLayerProvider::try_delete(GeometryComponent &component) co } const bool delete_success = CustomData_free_layer( - custom_data, stored_type_, domain_size, layer_index); + custom_data, stored_type_, domain_num, layer_index); if (delete_success) { if (custom_data_access_.update_custom_data_pointers) { custom_data_access_.update_custom_data_pointers(component); @@ -401,7 +409,7 @@ bool BuiltinCustomDataLayerProvider::try_create(GeometryComponent &component, return false; } - const int domain_size = component.attribute_domain_size(domain_); + const int domain_num = component.attribute_domain_num(domain_); bool success; if (stored_as_named_attribute_) { if (CustomData_get_layer_named(custom_data, data_type_, name_.c_str())) { @@ -409,7 +417,7 @@ bool BuiltinCustomDataLayerProvider::try_create(GeometryComponent &component, return false; } success = add_custom_data_layer_from_attribute_init( - name_, *custom_data, stored_type_, domain_size, initializer); + name_, *custom_data, stored_type_, domain_num, initializer); } else { if (CustomData_get_layer(custom_data, stored_type_) != nullptr) { @@ -417,7 +425,7 @@ bool BuiltinCustomDataLayerProvider::try_create(GeometryComponent &component, return false; } success = add_builtin_type_custom_data_layer_from_init( - *custom_data, stored_type_, domain_size, initializer); + *custom_data, stored_type_, domain_num, initializer); } if (success) { if (custom_data_access_.update_custom_data_pointers) { @@ -446,7 +454,7 @@ ReadAttributeLookup CustomDataAttributeProvider::try_get_for_read( if (custom_data == nullptr) { return {}; } - const int domain_size = component.attribute_domain_size(domain_); + const int domain_num = component.attribute_domain_num(domain_); for (const CustomDataLayer &layer : Span(custom_data->layers, custom_data->totlayer)) { if (!custom_data_layer_matches_attribute_id(layer, attribute_id)) { continue; @@ -455,7 +463,7 @@ ReadAttributeLookup CustomDataAttributeProvider::try_get_for_read( if (type == nullptr) { continue; } - GSpan data{*type, layer.data, domain_size}; + GSpan data{*type, layer.data, domain_num}; return {GVArray::ForSpan(data), domain_}; } return {}; @@ -468,24 +476,23 @@ WriteAttributeLookup CustomDataAttributeProvider::try_get_for_write( if (custom_data == nullptr) { return {}; } - const int domain_size = component.attribute_domain_size(domain_); + const int domain_num = component.attribute_domain_num(domain_); for (CustomDataLayer &layer : MutableSpan(custom_data->layers, custom_data->totlayer)) { if (!custom_data_layer_matches_attribute_id(layer, attribute_id)) { continue; } if (attribute_id.is_named()) { - CustomData_duplicate_referenced_layer_named( - custom_data, layer.type, layer.name, domain_size); + CustomData_duplicate_referenced_layer_named(custom_data, layer.type, layer.name, domain_num); } else { CustomData_duplicate_referenced_layer_anonymous( - custom_data, layer.type, &attribute_id.anonymous_id(), domain_size); + custom_data, layer.type, &attribute_id.anonymous_id(), domain_num); } const CPPType *type = custom_data_type_to_cpp_type((CustomDataType)layer.type); if (type == nullptr) { continue; } - GMutableSpan data{*type, layer.data, domain_size}; + GMutableSpan data{*type, layer.data, domain_num}; return {GVMutableArray::ForSpan(data), domain_}; } return {}; @@ -498,12 +505,12 @@ bool CustomDataAttributeProvider::try_delete(GeometryComponent &component, if (custom_data == nullptr) { return false; } - const int domain_size = component.attribute_domain_size(domain_); + const int domain_num = component.attribute_domain_num(domain_); for (const int i : IndexRange(custom_data->totlayer)) { const CustomDataLayer &layer = custom_data->layers[i]; if (this->type_is_supported((CustomDataType)layer.type) && custom_data_layer_matches_attribute_id(layer, attribute_id)) { - CustomData_free_layer(custom_data, layer.type, domain_size, i); + CustomData_free_layer(custom_data, layer.type, domain_num, i); return true; } } @@ -531,9 +538,9 @@ bool CustomDataAttributeProvider::try_create(GeometryComponent &component, return false; } } - const int domain_size = component.attribute_domain_size(domain_); + const int domain_num = component.attribute_domain_num(domain_); add_custom_data_layer_from_attribute_init( - attribute_id, *custom_data, data_type, domain_size, initializer); + attribute_id, *custom_data, data_type, domain_num, initializer); return true; } @@ -567,8 +574,8 @@ ReadAttributeLookup NamedLegacyCustomDataProvider::try_get_for_read( for (const CustomDataLayer &layer : Span(custom_data->layers, custom_data->totlayer)) { if (layer.type == stored_type_) { if (custom_data_layer_matches_attribute_id(layer, attribute_id)) { - const int domain_size = component.attribute_domain_size(domain_); - return {as_read_attribute_(layer.data, domain_size), domain_}; + const int domain_num = component.attribute_domain_num(domain_); + return {as_read_attribute_(layer.data, domain_num), domain_}; } } } @@ -585,16 +592,16 @@ WriteAttributeLookup NamedLegacyCustomDataProvider::try_get_for_write( for (CustomDataLayer &layer : MutableSpan(custom_data->layers, custom_data->totlayer)) { if (layer.type == stored_type_) { if (custom_data_layer_matches_attribute_id(layer, attribute_id)) { - const int domain_size = component.attribute_domain_size(domain_); + const int domain_num = component.attribute_domain_num(domain_); void *data_old = layer.data; void *data_new = CustomData_duplicate_referenced_layer_named( - custom_data, stored_type_, layer.name, domain_size); + custom_data, stored_type_, layer.name, domain_num); if (data_old != data_new) { if (custom_data_access_.update_custom_data_pointers) { custom_data_access_.update_custom_data_pointers(component); } } - return {as_write_attribute_(layer.data, domain_size), domain_}; + return {as_write_attribute_(layer.data, domain_num), domain_}; } } } @@ -612,8 +619,8 @@ bool NamedLegacyCustomDataProvider::try_delete(GeometryComponent &component, const CustomDataLayer &layer = custom_data->layers[i]; if (layer.type == stored_type_) { if (custom_data_layer_matches_attribute_id(layer, attribute_id)) { - const int domain_size = component.attribute_domain_size(domain_); - CustomData_free_layer(custom_data, stored_type_, domain_size, i); + const int domain_num = component.attribute_domain_num(domain_); + CustomData_free_layer(custom_data, stored_type_, domain_num, i); if (custom_data_access_.update_custom_data_pointers) { custom_data_access_.update_custom_data_pointers(component); } @@ -702,9 +709,9 @@ GVArray CustomDataAttributes::get_for_read(const AttributeIDRef &attribute_id, std::optional<GSpan> attribute = this->get_for_read(attribute_id); if (!attribute) { - const int domain_size = this->size_; + const int domain_num = this->size_; return GVArray::ForSingle( - *type, domain_size, (default_value == nullptr) ? type->default_value() : default_value); + *type, domain_num, (default_value == nullptr) ? type->default_value() : default_value); } if (attribute->type() == *type) { @@ -822,7 +829,7 @@ bool GeometryComponent::attribute_domain_supported(const AttributeDomain domain) return providers->supported_domains().contains(domain); } -int GeometryComponent::attribute_domain_size(const AttributeDomain UNUSED(domain)) const +int GeometryComponent::attribute_domain_num(const AttributeDomain UNUSED(domain)) const { return 0; } @@ -1157,8 +1164,8 @@ blender::GVArray GeometryComponent::attribute_get_for_read(const AttributeIDRef if (default_value == nullptr) { default_value = type->default_value(); } - const int domain_size = this->attribute_domain_size(domain); - return blender::GVArray::ForSingle(*type, domain_size, default_value); + const int domain_num = this->attribute_domain_num(domain); + return blender::GVArray::ForSingle(*type, domain_num, default_value); } class GVMutableAttribute_For_OutputAttribute : public blender::GVArrayImpl_For_GSpan { @@ -1267,10 +1274,10 @@ static OutputAttribute create_output_attribute(GeometryComponent &component, WriteAttributeLookup attribute = component.attribute_try_get_for_write(attribute_name); if (!attribute) { if (default_value) { - const int64_t domain_size = component.attribute_domain_size(domain); + const int64_t domain_num = component.attribute_domain_num(domain); component.attribute_try_create_builtin( attribute_name, - AttributeInitVArray(GVArray::ForSingleRef(*cpp_type, domain_size, default_value))); + AttributeInitVArray(GVArray::ForSingleRef(*cpp_type, domain_num, default_value))); } else { component.attribute_try_create_builtin(attribute_name, AttributeInitDefault()); @@ -1301,7 +1308,7 @@ static OutputAttribute create_output_attribute(GeometryComponent &component, ignore_old_values); } - const int domain_size = component.attribute_domain_size(domain); + const int domain_num = component.attribute_domain_num(domain); WriteAttributeLookup attribute = component.attribute_try_get_for_write(attribute_id); if (!attribute) { @@ -1310,7 +1317,7 @@ static OutputAttribute create_output_attribute(GeometryComponent &component, attribute_id, domain, data_type, - AttributeInitVArray(GVArray::ForSingleRef(*cpp_type, domain_size, default_value))); + AttributeInitVArray(GVArray::ForSingleRef(*cpp_type, domain_num, default_value))); } else { component.attribute_try_create(attribute_id, domain, data_type, AttributeInitDefault()); @@ -1333,8 +1340,7 @@ static OutputAttribute create_output_attribute(GeometryComponent &component, /* Allocate a new array that lives next to the existing attribute. It will overwrite the existing * attribute after processing is done. */ - void *data = MEM_mallocN_aligned( - cpp_type->size() * domain_size, cpp_type->alignment(), __func__); + void *data = MEM_mallocN_aligned(cpp_type->size() * domain_num, cpp_type->alignment(), __func__); if (ignore_old_values) { /* This does nothing for trivially constructible types, but is necessary for correctness. */ cpp_type->default_construct_n(data, domain); @@ -1343,10 +1349,10 @@ static OutputAttribute create_output_attribute(GeometryComponent &component, /* Fill the temporary array with values from the existing attribute. */ GVArray old_varray = component.attribute_get_for_read( attribute_id, domain, data_type, default_value); - old_varray.materialize_to_uninitialized(IndexRange(domain_size), data); + old_varray.materialize_to_uninitialized(IndexRange(domain_num), data); } GVMutableArray varray = GVMutableArray::For<GVMutableAttribute_For_OutputAttribute>( - GMutableSpan{*cpp_type, data, domain_size}, component, attribute_id); + GMutableSpan{*cpp_type, data, domain_num}, component, attribute_id); return OutputAttribute(std::move(varray), domain, save_output_attribute, true); } @@ -1429,7 +1435,7 @@ GVArray IDAttributeFieldInput::get_varray_for_context(const GeometryComponent &c const StringRef name = get_random_id_attribute_name(domain); GVArray attribute = component.attribute_try_get_for_read(name, domain, CD_PROP_INT32); if (attribute) { - BLI_assert(attribute.size() == component.attribute_domain_size(domain)); + BLI_assert(attribute.size() == component.attribute_domain_num(domain)); return attribute; } diff --git a/source/blender/blenkernel/intern/attribute_access_intern.hh b/source/blender/blenkernel/intern/attribute_access_intern.hh index 8c021ed0e21..f0f47cb7a11 100644 --- a/source/blender/blenkernel/intern/attribute_access_intern.hh +++ b/source/blender/blenkernel/intern/attribute_access_intern.hh @@ -172,8 +172,8 @@ class CustomDataAttributeProvider final : public DynamicAttributesProvider { */ class NamedLegacyCustomDataProvider final : public DynamicAttributesProvider { private: - using AsReadAttribute = GVArray (*)(const void *data, int domain_size); - using AsWriteAttribute = GVMutableArray (*)(void *data, int domain_size); + using AsReadAttribute = GVArray (*)(const void *data, int domain_num); + using AsWriteAttribute = GVMutableArray (*)(void *data, int domain_num); const AttributeDomain domain_; const CustomDataType attribute_type_; const CustomDataType stored_type_; @@ -207,14 +207,14 @@ class NamedLegacyCustomDataProvider final : public DynamicAttributesProvider { void foreach_domain(const FunctionRef<void(AttributeDomain)> callback) const final; }; -template<typename T> GVArray make_array_read_attribute(const void *data, const int domain_size) +template<typename T> GVArray make_array_read_attribute(const void *data, const int domain_num) { - return VArray<T>::ForSpan(Span<T>((const T *)data, domain_size)); + return VArray<T>::ForSpan(Span<T>((const T *)data, domain_num)); } -template<typename T> GVMutableArray make_array_write_attribute(void *data, const int domain_size) +template<typename T> GVMutableArray make_array_write_attribute(void *data, const int domain_num) { - return VMutableArray<T>::ForSpan(MutableSpan<T>((T *)data, domain_size)); + return VMutableArray<T>::ForSpan(MutableSpan<T>((T *)data, domain_num)); } /** @@ -226,8 +226,8 @@ template<typename T> GVMutableArray make_array_write_attribute(void *data, const * if the stored type is the same as the attribute type. */ class BuiltinCustomDataLayerProvider final : public BuiltinAttributeProvider { - using AsReadAttribute = GVArray (*)(const void *data, int domain_size); - using AsWriteAttribute = GVMutableArray (*)(void *data, int domain_size); + using AsReadAttribute = GVArray (*)(const void *data, int domain_num); + using AsWriteAttribute = GVMutableArray (*)(void *data, int domain_num); using UpdateOnRead = void (*)(const GeometryComponent &component); using UpdateOnWrite = void (*)(GeometryComponent &component); const CustomDataType stored_type_; diff --git a/source/blender/blenkernel/intern/blender_copybuffer.c b/source/blender/blenkernel/intern/blender_copybuffer.c index f93b3efa8dd..4b507beb6b3 100644 --- a/source/blender/blenkernel/intern/blender_copybuffer.c +++ b/source/blender/blenkernel/intern/blender_copybuffer.c @@ -96,7 +96,7 @@ bool BKE_copybuffer_read(Main *bmain_dst, ReportList *reports, const uint64_t id_types_mask) { - /* Note: No recursive append here (no `BLO_LIBLINK_APPEND_RECURSIVE`), external linked data + /* NOTE: No recursive append here (no `BLO_LIBLINK_APPEND_RECURSIVE`), external linked data * should remain linked. */ const int flag = 0; const int id_tag_extra = 0; @@ -132,7 +132,7 @@ int BKE_copybuffer_paste(bContext *C, View3D *v3d = CTX_wm_view3d(C); /* may be NULL. */ const int id_tag_extra = 0; - /* Note: No recursive append here, external linked data should remain linked. */ + /* NOTE: No recursive append here, external linked data should remain linked. */ BLI_assert((flag & BLO_LIBLINK_APPEND_RECURSIVE) == 0); struct LibraryLink_Params liblink_params; diff --git a/source/blender/blenkernel/intern/blender_undo.c b/source/blender/blenkernel/intern/blender_undo.c index c32941ccbc9..a5096b4f9eb 100644 --- a/source/blender/blenkernel/intern/blender_undo.c +++ b/source/blender/blenkernel/intern/blender_undo.c @@ -65,7 +65,7 @@ bool BKE_memfile_undo_decode(MemFileUndoData *mfu, if (UNDO_DISK) { const struct BlendFileReadParams params = {0}; BlendFileReadReport bf_reports = {.reports = NULL}; - struct BlendFileData *bfd = BKE_blendfile_read(mfu->filename, ¶ms, &bf_reports); + struct BlendFileData *bfd = BKE_blendfile_read(mfu->filepath, ¶ms, &bf_reports); if (bfd != NULL) { BKE_blendfile_read_setup(C, bfd, ¶ms, &bf_reports); success = true; @@ -108,20 +108,20 @@ MemFileUndoData *BKE_memfile_undo_encode(Main *bmain, MemFileUndoData *mfu_prev) /* disk save version */ if (UNDO_DISK) { static int counter = 0; - char filename[FILE_MAX]; + char filepath[FILE_MAX]; char numstr[32]; - /* Calculate current filename. */ + /* Calculate current filepath. */ counter++; counter = counter % U.undosteps; BLI_snprintf(numstr, sizeof(numstr), "%d.blend", counter); - BLI_join_dirfile(filename, sizeof(filename), BKE_tempdir_session(), numstr); + BLI_join_dirfile(filepath, sizeof(filepath), BKE_tempdir_session(), numstr); /* success = */ /* UNUSED */ BLO_write_file( - bmain, filename, fileflags, &(const struct BlendFileWriteParams){0}, NULL); + bmain, filepath, fileflags, &(const struct BlendFileWriteParams){0}, NULL); - BLI_strncpy(mfu->filename, filename, sizeof(mfu->filename)); + BLI_strncpy(mfu->filepath, filepath, sizeof(mfu->filepath)); } else { MemFile *prevfile = (mfu_prev) ? &(mfu_prev->memfile) : NULL; diff --git a/source/blender/blenkernel/intern/blendfile_link_append.c b/source/blender/blenkernel/intern/blendfile_link_append.c index 62196ea63bd..ebf48acde0f 100644 --- a/source/blender/blenkernel/intern/blendfile_link_append.c +++ b/source/blender/blenkernel/intern/blendfile_link_append.c @@ -400,7 +400,7 @@ typedef struct LooseDataInstantiateContext { static bool object_in_any_scene(Main *bmain, Object *ob) { LISTBASE_FOREACH (Scene *, sce, &bmain->scenes) { - /* #BKE_scene_has_object checks bases cache of the scenes' viewlayer, not actual content of + /* #BKE_scene_has_object checks bases cache of the scenes' view-layer, not actual content of * their collections. */ if (BKE_collection_has_object_recursive(sce->master_collection, ob)) { return true; @@ -1114,7 +1114,7 @@ void BKE_blendfile_append(BlendfileLinkAppendContext *lapp_context, ReportList * &LOG, "Unexpected unset append action for '%s' ID, assuming 'keep link'", id->name); break; default: - BLI_assert(0); + BLI_assert_unreachable(); } if (local_appended_new_id != NULL) { @@ -1537,7 +1537,7 @@ void BKE_blendfile_library_relocate(BlendfileLinkAppendContext *lapp_context, } if (GS(old_id->name) == ID_KE) { - /* Shape Keys are handled as part of their owning obdata (see below). This implies thar + /* Shape Keys are handled as part of their owning obdata (see below). This implies that * there is no way to know when the old pointer gets invalid, so just clear it immediately. */ item->userdata = NULL; diff --git a/source/blender/blenkernel/intern/brush.c b/source/blender/blenkernel/intern/brush.c index 3f243d04965..083d5af063a 100644 --- a/source/blender/blenkernel/intern/brush.c +++ b/source/blender/blenkernel/intern/brush.c @@ -1559,6 +1559,7 @@ void BKE_brush_init_curves_sculpt_settings(Brush *brush) } BrushCurvesSculptSettings *settings = brush->curves_sculpt_settings; settings->add_amount = 1; + settings->points_per_curve = 8; settings->minimum_length = 0.01f; settings->curve_length = 0.3f; } diff --git a/source/blender/blenkernel/intern/bvhutils.cc b/source/blender/blenkernel/intern/bvhutils.cc index 37b0875db67..35c2039634a 100644 --- a/source/blender/blenkernel/intern/bvhutils.cc +++ b/source/blender/blenkernel/intern/bvhutils.cc @@ -967,31 +967,6 @@ static BVHTree *bvhtree_from_mesh_faces_create_tree(float epsilon, return tree; } -BVHTree *bvhtree_from_mesh_faces_ex(BVHTreeFromMesh *data, - const MVert *vert, - const MFace *face, - const int numFaces, - const BLI_bitmap *faces_mask, - int faces_num_active, - float epsilon, - int tree_type, - int axis) -{ - BVHTree *tree = nullptr; - tree = bvhtree_from_mesh_faces_create_tree( - epsilon, tree_type, axis, vert, face, numFaces, faces_mask, faces_num_active); - - bvhtree_balance(tree, false); - - if (data) { - /* Setup BVHTreeFromMesh */ - bvhtree_from_mesh_setup_data( - tree, BVHTREE_FROM_FACES, vert, nullptr, face, nullptr, nullptr, nullptr, data); - } - - return tree; -} - /** \} */ /* -------------------------------------------------------------------- */ @@ -1212,10 +1187,11 @@ static BLI_bitmap *looptri_no_hidden_map_get(const MPoly *mpoly, int looptri_no_hidden_len = 0; int looptri_iter = 0; - const MPoly *mp = mpoly; + int i_poly = 0; while (looptri_iter != looptri_len) { - int mp_totlooptri = mp->totloop - 2; - if (mp->flag & ME_HIDE) { + int mp_totlooptri = mpoly[i_poly].totloop - 2; + const MPoly &mp = mpoly[i_poly]; + if (mp.flag & ME_HIDE) { looptri_iter += mp_totlooptri; } else { @@ -1225,7 +1201,7 @@ static BLI_bitmap *looptri_no_hidden_map_get(const MPoly *mpoly, looptri_no_hidden_len++; } } - mp++; + i_poly++; } *r_looptri_active_len = looptri_no_hidden_len; diff --git a/source/blender/blenkernel/intern/camera.c b/source/blender/blenkernel/intern/camera.c index 32925168437..6325251647b 100644 --- a/source/blender/blenkernel/intern/camera.c +++ b/source/blender/blenkernel/intern/camera.c @@ -66,14 +66,19 @@ static void camera_init_data(ID *id) * * \param flag: Copying options (see BKE_lib_id.h's LIB_ID_COPY_... flags for more). */ -static void camera_copy_data(Main *UNUSED(bmain), - ID *id_dst, - const ID *id_src, - const int UNUSED(flag)) +static void camera_copy_data(Main *UNUSED(bmain), ID *id_dst, const ID *id_src, const int flag) { Camera *cam_dst = (Camera *)id_dst; const Camera *cam_src = (const Camera *)id_src; - BLI_duplicatelist(&cam_dst->bg_images, &cam_src->bg_images); + + /* We never handle usercount here for own data. */ + const int flag_subdata = flag | LIB_ID_CREATE_NO_USER_REFCOUNT; + + BLI_listbase_clear(&cam_dst->bg_images); + LISTBASE_FOREACH (CameraBGImage *, bgpic_src, &cam_src->bg_images) { + CameraBGImage *bgpic_dst = BKE_camera_background_image_copy(bgpic_src, flag_subdata); + BLI_addtail(&cam_dst->bg_images, bgpic_dst); + } } /** Free (or release) any data used by this camera (does not free the camera itself). */ @@ -125,6 +130,11 @@ static void camera_blend_read_data(BlendDataReader *reader, ID *id) LISTBASE_FOREACH (CameraBGImage *, bgpic, &ca->bg_images) { bgpic->iuser.scene = NULL; + + /* If linking from a library, clear 'local' library override flag. */ + if (ID_IS_LINKED(ca)) { + bgpic->flag &= ~CAM_BGIMG_FLAG_OVERRIDE_LIBRARY_LOCAL; + } } } @@ -302,7 +312,7 @@ void BKE_camera_params_from_object(CameraParams *params, const Object *cam_ob) } void BKE_camera_params_from_view3d(CameraParams *params, - Depsgraph *depsgraph, + const Depsgraph *depsgraph, const View3D *v3d, const RegionView3D *rv3d) { @@ -1119,13 +1129,31 @@ CameraBGImage *BKE_camera_background_image_new(Camera *cam) bgpic->scale = 1.0f; bgpic->alpha = 0.5f; bgpic->iuser.flag |= IMA_ANIM_ALWAYS; - bgpic->flag |= CAM_BGIMG_FLAG_EXPANDED; + bgpic->flag |= CAM_BGIMG_FLAG_EXPANDED | CAM_BGIMG_FLAG_OVERRIDE_LIBRARY_LOCAL; BLI_addtail(&cam->bg_images, bgpic); return bgpic; } +CameraBGImage *BKE_camera_background_image_copy(CameraBGImage *bgpic_src, const int flag) +{ + CameraBGImage *bgpic_dst = MEM_dupallocN(bgpic_src); + + bgpic_dst->next = bgpic_dst->prev = NULL; + + if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) { + id_us_plus((ID *)bgpic_dst->ima); + id_us_plus((ID *)bgpic_dst->clip); + } + + if ((flag & LIB_ID_COPY_NO_LIB_OVERRIDE_LOCAL_DATA_FLAG) == 0) { + bgpic_dst->flag |= CAM_BGIMG_FLAG_OVERRIDE_LIBRARY_LOCAL; + } + + return bgpic_dst; +} + void BKE_camera_background_image_remove(Camera *cam, CameraBGImage *bgpic) { BLI_remlink(&cam->bg_images, bgpic); diff --git a/source/blender/blenkernel/intern/cdderivedmesh.c b/source/blender/blenkernel/intern/cdderivedmesh.c index 2d742a103af..93286751f92 100644 --- a/source/blender/blenkernel/intern/cdderivedmesh.c +++ b/source/blender/blenkernel/intern/cdderivedmesh.c @@ -65,18 +65,6 @@ static int cdDM_getNumEdges(DerivedMesh *dm) return dm->numEdgeData; } -static int cdDM_getNumTessFaces(DerivedMesh *dm) -{ - /* uncomment and add a breakpoint on the printf() - * to help debug tessfaces issues since BMESH merge. */ -#if 0 - if (dm->numTessFaceData == 0 && dm->numPolyData != 0) { - printf("%s: has no faces!\n"); - } -#endif - return dm->numTessFaceData; -} - static int cdDM_getNumLoops(DerivedMesh *dm) { return dm->numLoopData; @@ -173,7 +161,6 @@ static CDDerivedMesh *cdDM_create(const char *desc) dm->getNumVerts = cdDM_getNumVerts; dm->getNumEdges = cdDM_getNumEdges; - dm->getNumTessFaces = cdDM_getNumTessFaces; dm->getNumLoops = cdDM_getNumLoops; dm->getNumPolys = cdDM_getNumPolys; diff --git a/source/blender/blenkernel/intern/cloth.c b/source/blender/blenkernel/intern/cloth.c index 0d6a0c045a5..ab9a27a3996 100644 --- a/source/blender/blenkernel/intern/cloth.c +++ b/source/blender/blenkernel/intern/cloth.c @@ -632,7 +632,7 @@ static void cloth_apply_vgroup(ClothModifierData *clmd, Mesh *mesh) verts->flags &= ~(CLOTH_VERT_FLAG_PINNED | CLOTH_VERT_FLAG_NOSELFCOLL | CLOTH_VERT_FLAG_NOOBJCOLL); - MDeformVert *dvert = CustomData_get(&mesh->vdata, i, CD_MDEFORMVERT); + const MDeformVert *dvert = CustomData_get(&mesh->vdata, i, CD_MDEFORMVERT); if (dvert) { for (int j = 0; j < dvert->totweight; j++) { if (dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_mass - 1)) { @@ -715,7 +715,7 @@ static bool cloth_from_object( int i = 0; MVert *mvert = NULL; ClothVertex *verts = NULL; - float(*shapekey_rest)[3] = NULL; + const float(*shapekey_rest)[3] = NULL; const float tnull[3] = {0, 0, 0}; /* If we have a clothObject, free it. */ @@ -1127,7 +1127,7 @@ static void cloth_update_springs(ClothModifierData *clmd) spring->lin_stiffness = (v1->bend_stiff + v2->bend_stiff) / 2.0f; } else if (spring->type == CLOTH_SPRING_TYPE_GOAL) { - /* Warning: Appending NEW goal springs does not work + /* WARNING: Appending NEW goal springs does not work * because implicit solver would need reset! */ /* Activate / Deactivate existing springs */ diff --git a/source/blender/blenkernel/intern/colortools.c b/source/blender/blenkernel/intern/colortools.c index c3d66d4463d..e4c46703f8a 100644 --- a/source/blender/blenkernel/intern/colortools.c +++ b/source/blender/blenkernel/intern/colortools.c @@ -1158,6 +1158,80 @@ bool BKE_curvemapping_RGBA_does_something(const CurveMapping *cumap) return false; } +void BKE_curvemapping_get_range_minimums(const CurveMapping *curve_mapping, float minimums[CM_TOT]) +{ + for (int i = 0; i < CM_TOT; i++) { + minimums[i] = curve_mapping->cm[i].mintable; + } +} + +void BKE_curvemapping_compute_range_dividers(const CurveMapping *curve_mapping, + float dividers[CM_TOT]) +{ + for (int i = 0; i < CM_TOT; i++) { + const CurveMap *curve_map = &curve_mapping->cm[i]; + dividers[i] = 1.0f / max_ff(1e-8f, curve_map->maxtable - curve_map->mintable); + } +} + +void BKE_curvemapping_compute_slopes(const CurveMapping *curve_mapping, + float start_slopes[CM_TOT], + float end_slopes[CM_TOT]) +{ + float range_dividers[CM_TOT]; + BKE_curvemapping_compute_range_dividers(curve_mapping, range_dividers); + for (int i = 0; i < CM_TOT; i++) { + const CurveMap *curve_map = &curve_mapping->cm[i]; + /* If extrapolation is not enabled, the slopes are horizontal. */ + if (!(curve_mapping->flag & CUMA_EXTEND_EXTRAPOLATE)) { + start_slopes[i] = 0.0f; + end_slopes[i] = 0.0f; + continue; + } + + if (curve_map->ext_in[0] != 0.0f) { + start_slopes[i] = curve_map->ext_in[1] / (curve_map->ext_in[0] * range_dividers[i]); + } + else { + start_slopes[i] = 1e8f; + } + + if (curve_map->ext_out[0] != 0.0f) { + end_slopes[i] = curve_map->ext_out[1] / (curve_map->ext_out[0] * range_dividers[i]); + } + else { + end_slopes[i] = 1e8f; + } + } +} + +bool BKE_curvemapping_is_map_identity(const CurveMapping *curve_mapping, int index) +{ + if (!(curve_mapping->flag & CUMA_EXTEND_EXTRAPOLATE)) { + return false; + } + const CurveMap *curve_map = &curve_mapping->cm[index]; + if (curve_map->maxtable - curve_map->mintable != 1.0f) { + return false; + } + if (curve_map->ext_in[0] != curve_map->ext_in[1]) { + return false; + } + if (curve_map->ext_out[0] != curve_map->ext_out[1]) { + return false; + } + if (curve_map->totpoint != 2) { + return false; + } + if (curve_map->curve[0].x != 0 || curve_map->curve[0].y != 0) { + return false; + } + if (curve_map->curve[1].x != 0 || curve_map->curve[1].y != 0) { + return false; + } + return true; +} + void BKE_curvemapping_init(CurveMapping *cumap) { int a; diff --git a/source/blender/blenkernel/intern/crazyspace.c b/source/blender/blenkernel/intern/crazyspace.c index 96389c44839..14e862c2377 100644 --- a/source/blender/blenkernel/intern/crazyspace.c +++ b/source/blender/blenkernel/intern/crazyspace.c @@ -13,8 +13,8 @@ #include "DNA_object_types.h" #include "DNA_scene_types.h" +#include "BLI_bitmap.h" #include "BLI_linklist.h" -#include "BLI_math.h" #include "BLI_utildefines.h" #include "BKE_DerivedMesh.h" diff --git a/source/blender/blenkernel/intern/curve_bezier.cc b/source/blender/blenkernel/intern/curve_bezier.cc index 13695525616..5ba17f1761b 100644 --- a/source/blender/blenkernel/intern/curve_bezier.cc +++ b/source/blender/blenkernel/intern/curve_bezier.cc @@ -20,8 +20,8 @@ bool segment_is_vector(const Span<int8_t> handle_types_left, handle_types_left[segment_index + 1] == BEZIER_HANDLE_VECTOR; } -bool last_cylic_segment_is_vector(const Span<int8_t> handle_types_left, - const Span<int8_t> handle_types_right) +bool last_cyclic_segment_is_vector(const Span<int8_t> handle_types_left, + const Span<int8_t> handle_types_right) { return handle_types_right.last() == BEZIER_HANDLE_VECTOR && handle_types_left.first() == BEZIER_HANDLE_VECTOR; @@ -49,7 +49,8 @@ void calculate_evaluated_offsets(const Span<int8_t> handle_types_left, } if (cyclic) { - offset += last_cylic_segment_is_vector(handle_types_left, handle_types_right) ? 1 : resolution; + offset += last_cyclic_segment_is_vector(handle_types_left, handle_types_right) ? 1 : + resolution; } else { offset++; diff --git a/source/blender/blenkernel/intern/curve_catmull_rom.cc b/source/blender/blenkernel/intern/curve_catmull_rom.cc index 2db183eea3e..4b2174c912c 100644 --- a/source/blender/blenkernel/intern/curve_catmull_rom.cc +++ b/source/blender/blenkernel/intern/curve_catmull_rom.cc @@ -9,11 +9,11 @@ namespace blender::bke::curves::catmull_rom { -int calculate_evaluated_size(const int points_num, const bool cyclic, const int resolution) +int calculate_evaluated_num(const int points_num, const bool cyclic, const int resolution) { - const int eval_size = resolution * curve_segment_size(points_num, cyclic); + const int eval_num = resolution * curve_segment_num(points_num, cyclic); /* If the curve isn't cyclic, one last point is added to the final point. */ - return cyclic ? eval_size : eval_size + 1; + return cyclic ? eval_num : eval_num + 1; } /* Adapted from Cycles #catmull_rom_basis_eval function. */ @@ -46,7 +46,7 @@ static void interpolate_to_evaluated(const Span<T> src, MutableSpan<T> dst) { - BLI_assert(dst.size() == calculate_evaluated_size(src.size(), cyclic, resolution)); + BLI_assert(dst.size() == calculate_evaluated_num(src.size(), cyclic, resolution)); /* - First deal with one and two point curves need special attention. * - Then evaluate the first and last segment(s) whose control points need to wrap around diff --git a/source/blender/blenkernel/intern/curve_eval.cc b/source/blender/blenkernel/intern/curve_eval.cc index 3d9dd3ecf31..dd2bd982506 100644 --- a/source/blender/blenkernel/intern/curve_eval.cc +++ b/source/blender/blenkernel/intern/curve_eval.cc @@ -117,7 +117,7 @@ float CurveEval::total_length() const return length; } -int CurveEval::total_control_point_size() const +int CurveEval::total_control_point_num() const { int count = 0; for (const SplinePtr &spline : this->splines()) { @@ -144,7 +144,7 @@ blender::Array<int> CurveEval::evaluated_point_offsets() const int offset = 0; for (const int i : splines_.index_range()) { offsets[i] = offset; - offset += splines_[i]->evaluated_points_size(); + offset += splines_[i]->evaluated_points_num(); } offsets.last() = offset; return offsets; @@ -373,15 +373,15 @@ static void copy_attributes_between_components(const GeometryComponent &src_comp }); } -std::unique_ptr<CurveEval> curves_to_curve_eval(const Curves &curves) +std::unique_ptr<CurveEval> curves_to_curve_eval(const Curves &curves_id) { CurveComponent src_component; - src_component.replace(&const_cast<Curves &>(curves), GeometryOwnershipType::ReadOnly); - const blender::bke::CurvesGeometry &geometry = blender::bke::CurvesGeometry::wrap( - curves.geometry); + src_component.replace(&const_cast<Curves &>(curves_id), GeometryOwnershipType::ReadOnly); + const blender::bke::CurvesGeometry &curves = blender::bke::CurvesGeometry::wrap( + curves_id.geometry); - VArray<int> resolution = geometry.resolution(); - VArray<int8_t> normal_mode = geometry.normal_mode(); + VArray<int> resolution = curves.resolution(); + VArray<int8_t> normal_mode = curves.normal_mode(); VArray_Span<float> nurbs_weights{ src_component.attribute_get_for_read<float>("nurbs_weight", ATTR_DOMAIN_POINT, 0.0f)}; @@ -396,34 +396,34 @@ std::unique_ptr<CurveEval> curves_to_curve_eval(const Curves &curves) src_component.attribute_get_for_read<int8_t>("handle_type_left", ATTR_DOMAIN_POINT, 0)}; /* Create splines with the correct size and type. */ - VArray<int8_t> curve_types = geometry.curve_types(); + VArray<int8_t> curve_types = curves.curve_types(); std::unique_ptr<CurveEval> curve_eval = std::make_unique<CurveEval>(); for (const int curve_index : curve_types.index_range()) { - const IndexRange point_range = geometry.points_for_curve(curve_index); + const IndexRange points = curves.points_for_curve(curve_index); std::unique_ptr<Spline> spline; /* #CurveEval does not support catmull rom curves, so convert those to poly splines. */ switch (std::max<int8_t>(1, curve_types[curve_index])) { case CURVE_TYPE_POLY: { spline = std::make_unique<PolySpline>(); - spline->resize(point_range.size()); + spline->resize(points.size()); break; } case CURVE_TYPE_BEZIER: { std::unique_ptr<BezierSpline> bezier_spline = std::make_unique<BezierSpline>(); - bezier_spline->resize(point_range.size()); + bezier_spline->resize(points.size()); bezier_spline->set_resolution(resolution[curve_index]); - bezier_spline->handle_types_left().copy_from(handle_types_left.slice(point_range)); - bezier_spline->handle_types_right().copy_from(handle_types_right.slice(point_range)); + bezier_spline->handle_types_left().copy_from(handle_types_left.slice(points)); + bezier_spline->handle_types_right().copy_from(handle_types_right.slice(points)); spline = std::move(bezier_spline); break; } case CURVE_TYPE_NURBS: { std::unique_ptr<NURBSpline> nurb_spline = std::make_unique<NURBSpline>(); - nurb_spline->resize(point_range.size()); + nurb_spline->resize(points.size()); nurb_spline->set_resolution(resolution[curve_index]); - nurb_spline->weights().copy_from(nurbs_weights.slice(point_range)); + nurb_spline->weights().copy_from(nurbs_weights.slice(points)); nurb_spline->set_order(nurbs_orders[curve_index]); nurb_spline->knots_mode = static_cast<KnotsMode>(nurbs_knots_modes[curve_index]); @@ -463,14 +463,14 @@ std::unique_ptr<CurveEval> curves_to_curve_eval(const Curves &curves) Curves *curve_eval_to_curves(const CurveEval &curve_eval) { - Curves *curves = blender::bke::curves_new_nomain(curve_eval.total_control_point_size(), - curve_eval.splines().size()); + Curves *curves_id = blender::bke::curves_new_nomain(curve_eval.total_control_point_num(), + curve_eval.splines().size()); CurveComponent dst_component; - dst_component.replace(curves, GeometryOwnershipType::Editable); + dst_component.replace(curves_id, GeometryOwnershipType::Editable); - blender::bke::CurvesGeometry &geometry = blender::bke::CurvesGeometry::wrap(curves->geometry); - geometry.offsets_for_write().copy_from(curve_eval.control_point_offsets()); - MutableSpan<int8_t> curve_types = geometry.curve_types_for_write(); + blender::bke::CurvesGeometry &curves = blender::bke::CurvesGeometry::wrap(curves_id->geometry); + curves.offsets_for_write().copy_from(curve_eval.control_point_offsets()); + MutableSpan<int8_t> curve_types = curves.curve_types_for_write(); OutputAttribute_Typed<int8_t> normal_mode = dst_component.attribute_try_get_for_output_only<int8_t>("normal_mode", ATTR_DOMAIN_CURVE); @@ -498,22 +498,22 @@ Curves *curve_eval_to_curves(const CurveEval &curve_eval) const Spline &spline = *curve_eval.splines()[curve_index]; curve_types[curve_index] = curve_eval.splines()[curve_index]->type(); normal_mode.as_span()[curve_index] = curve_eval.splines()[curve_index]->normal_mode; - const IndexRange point_range = geometry.points_for_curve(curve_index); + const IndexRange points = curves.points_for_curve(curve_index); switch (spline.type()) { case CURVE_TYPE_POLY: break; case CURVE_TYPE_BEZIER: { const BezierSpline &src = static_cast<const BezierSpline &>(spline); - handle_type_right.as_span().slice(point_range).copy_from(src.handle_types_right()); - handle_type_left.as_span().slice(point_range).copy_from(src.handle_types_left()); + handle_type_right.as_span().slice(points).copy_from(src.handle_types_right()); + handle_type_left.as_span().slice(points).copy_from(src.handle_types_left()); break; } case CURVE_TYPE_NURBS: { const NURBSpline &src = static_cast<const NURBSpline &>(spline); nurbs_knots_mode.as_span()[curve_index] = static_cast<int8_t>(src.knots_mode); nurbs_order.as_span()[curve_index] = src.order(); - nurbs_weight.as_span().slice(point_range).copy_from(src.weights()); + nurbs_weight.as_span().slice(points).copy_from(src.weights()); break; } case CURVE_TYPE_CATMULL_ROM: { @@ -523,7 +523,7 @@ Curves *curve_eval_to_curves(const CurveEval &curve_eval) } } - geometry.update_curve_types(); + curves.update_curve_types(); normal_mode.save(); nurbs_weight.save(); @@ -537,7 +537,7 @@ Curves *curve_eval_to_curves(const CurveEval &curve_eval) copy_attributes_between_components(src_component, dst_component, {}); - return curves; + return curves_id; } void CurveEval::assert_valid_point_attributes() const diff --git a/source/blender/blenkernel/intern/curve_nurbs.cc b/source/blender/blenkernel/intern/curve_nurbs.cc index 0114c0b45f4..cd6b64e9a03 100644 --- a/source/blender/blenkernel/intern/curve_nurbs.cc +++ b/source/blender/blenkernel/intern/curve_nurbs.cc @@ -10,10 +10,10 @@ namespace blender::bke::curves::nurbs { -bool check_valid_size_and_order(const int points_num, - const int8_t order, - const bool cyclic, - const KnotsMode knots_mode) +bool check_valid_num_and_order(const int points_num, + const int8_t order, + const bool cyclic, + const KnotsMode knots_mode) { if (points_num < order) { return false; @@ -29,19 +29,19 @@ bool check_valid_size_and_order(const int points_num, return true; } -int calculate_evaluated_size(const int points_num, - const int8_t order, - const bool cyclic, - const int resolution, - const KnotsMode knots_mode) +int calculate_evaluated_num(const int points_num, + const int8_t order, + const bool cyclic, + const int resolution, + const KnotsMode knots_mode) { - if (!check_valid_size_and_order(points_num, order, cyclic, knots_mode)) { - return 0; + if (!check_valid_num_and_order(points_num, order, cyclic, knots_mode)) { + return points_num; } - return resolution * curve_segment_size(points_num, cyclic); + return resolution * curve_segment_num(points_num, cyclic); } -int knots_size(const int points_num, const int8_t order, const bool cyclic) +int knots_num(const int points_num, const int8_t order, const bool cyclic) { if (cyclic) { return points_num + order * 2 - 1; @@ -55,7 +55,7 @@ void calculate_knots(const int points_num, const bool cyclic, MutableSpan<float> knots) { - BLI_assert(knots.size() == knots_size(points_num, order, cyclic)); + BLI_assert(knots.size() == knots_num(points_num, order, cyclic)); UNUSED_VARS_NDEBUG(points_num); const bool is_bezier = ELEM(mode, NURBS_KNOT_MODE_BEZIER, NURBS_KNOT_MODE_ENDPOINT_BEZIER); @@ -147,7 +147,7 @@ static void calculate_basis_for_point(const float parameter, } void calculate_basis_cache(const int points_num, - const int evaluated_size, + const int evaluated_num, const int8_t order, const bool cyclic, const Span<float> knots, @@ -157,10 +157,10 @@ void calculate_basis_cache(const int points_num, const int8_t degree = order - 1; - basis_cache.weights.resize(evaluated_size * order); - basis_cache.start_indices.resize(evaluated_size); + basis_cache.weights.resize(evaluated_num * order); + basis_cache.start_indices.resize(evaluated_num); - if (evaluated_size == 0) { + if (evaluated_num == 0) { return; } @@ -168,12 +168,12 @@ void calculate_basis_cache(const int points_num, MutableSpan<int> basis_start_indices(basis_cache.start_indices); const int last_control_point_index = cyclic ? points_num + degree : points_num; - const int evaluated_segment_size = curve_segment_size(evaluated_size, cyclic); + const int evaluated_segment_num = curve_segment_num(evaluated_num, cyclic); const float start = knots[degree]; const float end = knots[last_control_point_index]; - const float step = (end - start) / evaluated_segment_size; - for (const int i : IndexRange(evaluated_size)) { + const float step = (end - start) / evaluated_segment_num; + for (const int i : IndexRange(evaluated_num)) { /* Clamp parameter due to floating point inaccuracy. */ const float parameter = std::clamp(start + step * i, knots[0], knots[points_num + degree]); @@ -232,8 +232,12 @@ void interpolate_to_evaluated(const BasisCache &basis_cache, const GSpan src, GMutableSpan dst) { - BLI_assert(dst.size() == basis_cache.start_indices.size()); + if (basis_cache.invalid) { + dst.copy_from(src); + return; + } + BLI_assert(dst.size() == basis_cache.start_indices.size()); attribute_math::convert_to_static_type(src.type(), [&](auto dummy) { using T = decltype(dummy); if constexpr (!std::is_void_v<attribute_math::DefaultMixer<T>>) { diff --git a/source/blender/blenkernel/intern/curve_poly.cc b/source/blender/blenkernel/intern/curve_poly.cc index 2a546e81825..7ab92068d81 100644 --- a/source/blender/blenkernel/intern/curve_poly.cc +++ b/source/blender/blenkernel/intern/curve_poly.cc @@ -159,7 +159,7 @@ void calculate_normals_minimum(const Span<float3> tangents, normals.first() = math::normalize(float3(first_tangent.y, -first_tangent.x, 0.0f)); } - /* Forward normal with minimum twist along the entire spline. */ + /* Forward normal with minimum twist along the entire curve. */ for (const int i : IndexRange(1, normals.size() - 1)) { normals[i] = calculate_next_normal(normals[i - 1], tangents[i - 1], tangents[i]); } @@ -169,7 +169,7 @@ void calculate_normals_minimum(const Span<float3> tangents, } /* Compute how much the first normal deviates from the normal that has been forwarded along the - * entire cyclic spline. */ + * entire cyclic curve. */ const float3 uncorrected_last_normal = calculate_next_normal( normals.last(), tangents.last(), tangents.first()); float correction_angle = angle_signed_on_axis_v3v3_v3( diff --git a/source/blender/blenkernel/intern/curve_to_mesh_convert.cc b/source/blender/blenkernel/intern/curve_to_mesh_convert.cc index ef921797698..0cd324cfe2c 100644 --- a/source/blender/blenkernel/intern/curve_to_mesh_convert.cc +++ b/source/blender/blenkernel/intern/curve_to_mesh_convert.cc @@ -39,8 +39,8 @@ static void fill_mesh_topology(const int vert_offset, MutableSpan<MLoop> loops, MutableSpan<MPoly> polys) { - const int main_segment_num = curves::curve_segment_size(main_point_num, main_cyclic); - const int profile_segment_num = curves::curve_segment_size(profile_point_num, profile_cyclic); + const int main_segment_num = curves::curve_segment_num(main_point_num, main_cyclic); + const int profile_segment_num = curves::curve_segment_num(profile_point_num, profile_cyclic); if (profile_point_num == 1) { for (const int i : IndexRange(main_point_num - 1)) { @@ -134,9 +134,9 @@ static void fill_mesh_topology(const int vert_offset, const bool has_caps = fill_caps && !main_cyclic && profile_cyclic; if (has_caps) { - const int poly_size = main_segment_num * profile_segment_num; - const int cap_loop_offset = loop_offset + poly_size * 4; - const int cap_poly_offset = poly_offset + poly_size; + const int poly_num = main_segment_num * profile_segment_num; + const int cap_loop_offset = loop_offset + poly_num * 4; + const int cap_poly_offset = poly_offset + poly_num; MPoly &poly_start = polys[cap_poly_offset]; poly_start.loopstart = cap_loop_offset; @@ -273,7 +273,7 @@ static ResultOffsets calculate_result_offsets(const CurvesInfo &info, const bool for (const int i_main : info.main.curves_range()) { const bool main_cyclic = info.main_cyclic[i_main]; const int main_point_num = info.main.evaluated_points_for_curve(i_main).size(); - const int main_segment_num = curves::curve_segment_size(main_point_num, main_cyclic); + const int main_segment_num = curves::curve_segment_num(main_point_num, main_cyclic); for (const int i_profile : info.profile.curves_range()) { result.vert[mesh_index] = vert_offset; result.edge[mesh_index] = edge_offset; @@ -285,8 +285,7 @@ static ResultOffsets calculate_result_offsets(const CurvesInfo &info, const bool const bool profile_cyclic = info.profile_cyclic[i_profile]; const int profile_point_num = info.profile.evaluated_points_for_curve(i_profile).size(); - const int profile_segment_num = curves::curve_segment_size(profile_point_num, - profile_cyclic); + const int profile_segment_num = curves::curve_segment_num(profile_point_num, profile_cyclic); const bool has_caps = fill_caps && !main_cyclic && profile_cyclic; const int tube_face_num = main_segment_num * profile_segment_num; @@ -408,8 +407,8 @@ static void foreach_curve_combination(const CurvesInfo &info, profile_points, main_cyclic, profile_cyclic, - curves::curve_segment_size(main_points.size(), main_cyclic), - curves::curve_segment_size(profile_points.size(), profile_cyclic), + curves::curve_segment_num(main_points.size(), main_cyclic), + curves::curve_segment_num(profile_points.size(), profile_cyclic), offsets_to_range(offsets.vert.as_span(), i), offsets_to_range(offsets.edge.as_span(), i), offsets_to_range(offsets.poly.as_span(), i), diff --git a/source/blender/blenkernel/intern/curves.cc b/source/blender/blenkernel/intern/curves.cc index 1df1492bac1..ab9dd702630 100644 --- a/source/blender/blenkernel/intern/curves.cc +++ b/source/blender/blenkernel/intern/curves.cc @@ -23,6 +23,7 @@ #include "BLI_span.hh" #include "BLI_string.h" #include "BLI_utildefines.h" +#include "BLI_vector.hh" #include "BKE_anim_data.h" #include "BKE_curves.hh" @@ -48,6 +49,7 @@ using blender::IndexRange; using blender::MutableSpan; using blender::RandomNumberGenerator; using blender::Span; +using blender::Vector; static const char *ATTR_POSITION = "position"; @@ -78,12 +80,12 @@ static void curves_copy_data(Main *UNUSED(bmain), ID *id_dst, const ID *id_src, * shallow copy from the source to the destination, and because the copy-on-write functionality * isn't supported more generically yet. */ - dst.point_size = src.point_size; - dst.curve_size = src.curve_size; + dst.point_num = src.point_num; + dst.curve_num = src.curve_num; const eCDAllocType alloc_type = (flag & LIB_ID_COPY_CD_REFERENCE) ? CD_REFERENCE : CD_DUPLICATE; - CustomData_copy(&src.point_data, &dst.point_data, CD_MASK_ALL, alloc_type, dst.point_size); - CustomData_copy(&src.curve_data, &dst.curve_data, CD_MASK_ALL, alloc_type, dst.curve_size); + CustomData_copy(&src.point_data, &dst.point_data, CD_MASK_ALL, alloc_type, dst.point_num); + CustomData_copy(&src.curve_data, &dst.curve_data, CD_MASK_ALL, alloc_type, dst.curve_num); dst.curve_offsets = static_cast<int *>(MEM_dupallocN(src.curve_offsets)); @@ -121,12 +123,10 @@ static void curves_blend_write(BlendWriter *writer, ID *id, const void *id_addre { Curves *curves = (Curves *)id; - CustomDataLayer *players = nullptr, players_buff[CD_TEMP_CHUNK_SIZE]; - CustomDataLayer *clayers = nullptr, clayers_buff[CD_TEMP_CHUNK_SIZE]; - CustomData_blend_write_prepare( - &curves->geometry.point_data, &players, players_buff, ARRAY_SIZE(players_buff)); - CustomData_blend_write_prepare( - &curves->geometry.curve_data, &clayers, clayers_buff, ARRAY_SIZE(clayers_buff)); + Vector<CustomDataLayer, 16> point_layers; + Vector<CustomDataLayer, 16> curve_layers; + CustomData_blend_write_prepare(curves->geometry.point_data, point_layers); + CustomData_blend_write_prepare(curves->geometry.curve_data, curve_layers); /* Write LibData */ BLO_write_id_struct(writer, Curves, id_address, &curves->id); @@ -135,31 +135,23 @@ static void curves_blend_write(BlendWriter *writer, ID *id, const void *id_addre /* Direct data */ CustomData_blend_write(writer, &curves->geometry.point_data, - players, - curves->geometry.point_size, + point_layers, + curves->geometry.point_num, CD_MASK_ALL, &curves->id); CustomData_blend_write(writer, &curves->geometry.curve_data, - clayers, - curves->geometry.curve_size, + curve_layers, + curves->geometry.curve_num, CD_MASK_ALL, &curves->id); - BLO_write_int32_array(writer, curves->geometry.curve_size + 1, curves->geometry.curve_offsets); + BLO_write_int32_array(writer, curves->geometry.curve_num + 1, curves->geometry.curve_offsets); BLO_write_pointer_array(writer, curves->totcol, curves->mat); if (curves->adt) { BKE_animdata_blend_write(writer, curves->adt); } - - /* Remove temporary data. */ - if (players && players != players_buff) { - MEM_freeN(players); - } - if (clayers && clayers != clayers_buff) { - MEM_freeN(clayers); - } } static void curves_blend_read_data(BlendDataReader *reader, ID *id) @@ -169,11 +161,11 @@ static void curves_blend_read_data(BlendDataReader *reader, ID *id) BKE_animdata_blend_read_data(reader, curves->adt); /* Geometry */ - CustomData_blend_read(reader, &curves->geometry.point_data, curves->geometry.point_size); - CustomData_blend_read(reader, &curves->geometry.curve_data, curves->geometry.curve_size); + CustomData_blend_read(reader, &curves->geometry.point_data, curves->geometry.point_num); + CustomData_blend_read(reader, &curves->geometry.curve_data, curves->geometry.curve_num); update_custom_data_pointers(*curves); - BLO_read_int32_array(reader, curves->geometry.curve_size + 1, &curves->geometry.curve_offsets); + BLO_read_int32_array(reader, curves->geometry.curve_num + 1, &curves->geometry.curve_offsets); curves->geometry.runtime = MEM_new<blender::bke::CurvesGeometryRuntime>(__func__); @@ -247,7 +239,7 @@ void *BKE_curves_add(Main *bmain, const char *name) BoundBox *BKE_curves_boundbox_get(Object *ob) { BLI_assert(ob->type == OB_CURVES); - Curves *curves = static_cast<Curves *>(ob->data); + const Curves *curves_id = static_cast<const Curves *>(ob->data); if (ob->runtime.bb != nullptr && (ob->runtime.bb->flag & BOUNDBOX_DIRTY) == 0) { return ob->runtime.bb; @@ -256,11 +248,12 @@ BoundBox *BKE_curves_boundbox_get(Object *ob) if (ob->runtime.bb == nullptr) { ob->runtime.bb = MEM_cnew<BoundBox>(__func__); - blender::bke::CurvesGeometry &geometry = blender::bke::CurvesGeometry::wrap(curves->geometry); + const blender::bke::CurvesGeometry &curves = blender::bke::CurvesGeometry::wrap( + curves_id->geometry); float3 min(FLT_MAX); float3 max(-FLT_MAX); - if (!geometry.bounds_min_max(min, max)) { + if (!curves.bounds_min_max(min, max)) { min = float3(-1); max = float3(1); } @@ -364,19 +357,26 @@ namespace blender::bke { Curves *curves_new_nomain(const int points_num, const int curves_num) { - Curves *curves = static_cast<Curves *>(BKE_id_new_nomain(ID_CV, nullptr)); - CurvesGeometry &geometry = CurvesGeometry::wrap(curves->geometry); - geometry.resize(points_num, curves_num); - return curves; + Curves *curves_id = static_cast<Curves *>(BKE_id_new_nomain(ID_CV, nullptr)); + CurvesGeometry &curves = CurvesGeometry::wrap(curves_id->geometry); + curves.resize(points_num, curves_num); + return curves_id; } Curves *curves_new_nomain_single(const int points_num, const CurveType type) { - Curves *curves = curves_new_nomain(points_num, 1); - CurvesGeometry &geometry = CurvesGeometry::wrap(curves->geometry); - geometry.offsets_for_write().last() = points_num; - geometry.fill_curve_types(type); - return curves; + Curves *curves_id = curves_new_nomain(points_num, 1); + CurvesGeometry &curves = CurvesGeometry::wrap(curves_id->geometry); + curves.offsets_for_write().last() = points_num; + curves.fill_curve_types(type); + return curves_id; +} + +Curves *curves_new_nomain(CurvesGeometry curves) +{ + Curves *curves_id = static_cast<Curves *>(BKE_id_new_nomain(ID_CV, nullptr)); + bke::CurvesGeometry::wrap(curves_id->geometry) = std::move(curves); + return curves_id; } } // namespace blender::bke diff --git a/source/blender/blenkernel/intern/curves_geometry.cc b/source/blender/blenkernel/intern/curves_geometry.cc index 7a09b87490b..0fd58a52f81 100644 --- a/source/blender/blenkernel/intern/curves_geometry.cc +++ b/source/blender/blenkernel/intern/curves_geometry.cc @@ -46,10 +46,10 @@ CurvesGeometry::CurvesGeometry() : CurvesGeometry(0, 0) { } -CurvesGeometry::CurvesGeometry(const int point_size, const int curve_size) +CurvesGeometry::CurvesGeometry(const int point_num, const int curve_num) { - this->point_size = point_size; - this->curve_size = curve_size; + this->point_num = point_num; + this->curve_num = curve_num; CustomData_reset(&this->point_data); CustomData_reset(&this->curve_data); @@ -57,14 +57,16 @@ CurvesGeometry::CurvesGeometry(const int point_size, const int curve_size) CD_PROP_FLOAT3, CD_DEFAULT, nullptr, - this->point_size, + this->point_num, ATTR_POSITION.c_str()); - this->curve_offsets = (int *)MEM_calloc_arrayN(this->curve_size + 1, sizeof(int), __func__); + this->curve_offsets = (int *)MEM_calloc_arrayN(this->curve_num + 1, sizeof(int), __func__); this->update_customdata_pointers(); this->runtime = MEM_new<CurvesGeometryRuntime>(__func__); + /* Fill the type counts with the default so they're in a valid state. */ + this->runtime->type_counts[CURVE_TYPE_CATMULL_ROM] = curve_num; } /** @@ -72,15 +74,15 @@ CurvesGeometry::CurvesGeometry(const int point_size, const int curve_size) */ static void copy_curves_geometry(CurvesGeometry &dst, const CurvesGeometry &src) { - CustomData_free(&dst.point_data, dst.point_size); - CustomData_free(&dst.curve_data, dst.curve_size); - dst.point_size = src.point_size; - dst.curve_size = src.curve_size; - CustomData_copy(&src.point_data, &dst.point_data, CD_MASK_ALL, CD_DUPLICATE, dst.point_size); - CustomData_copy(&src.curve_data, &dst.curve_data, CD_MASK_ALL, CD_DUPLICATE, dst.curve_size); + CustomData_free(&dst.point_data, dst.point_num); + CustomData_free(&dst.curve_data, dst.curve_num); + dst.point_num = src.point_num; + dst.curve_num = src.curve_num; + CustomData_copy(&src.point_data, &dst.point_data, CD_MASK_ALL, CD_DUPLICATE, dst.point_num); + CustomData_copy(&src.curve_data, &dst.curve_data, CD_MASK_ALL, CD_DUPLICATE, dst.curve_num); MEM_SAFE_FREE(dst.curve_offsets); - dst.curve_offsets = (int *)MEM_calloc_arrayN(dst.point_size + 1, sizeof(int), __func__); + dst.curve_offsets = (int *)MEM_calloc_arrayN(dst.point_num + 1, sizeof(int), __func__); dst.offsets_for_write().copy_from(src.offsets()); dst.tag_topology_changed(); @@ -92,7 +94,7 @@ static void copy_curves_geometry(CurvesGeometry &dst, const CurvesGeometry &src) } CurvesGeometry::CurvesGeometry(const CurvesGeometry &other) - : CurvesGeometry(other.point_size, other.curve_size) + : CurvesGeometry(other.point_num, other.curve_num) { copy_curves_geometry(*this, other); } @@ -108,15 +110,15 @@ CurvesGeometry &CurvesGeometry::operator=(const CurvesGeometry &other) /* The source should be empty, but in a valid state so that using it further will work. */ static void move_curves_geometry(CurvesGeometry &dst, CurvesGeometry &src) { - dst.point_size = src.point_size; + dst.point_num = src.point_num; std::swap(dst.point_data, src.point_data); - CustomData_free(&src.point_data, src.point_size); - src.point_size = 0; + CustomData_free(&src.point_data, src.point_num); + src.point_num = 0; - dst.curve_size = src.curve_size; + dst.curve_num = src.curve_num; std::swap(dst.curve_data, src.curve_data); - CustomData_free(&src.curve_data, src.curve_size); - src.curve_size = 0; + CustomData_free(&src.curve_data, src.curve_num); + src.curve_num = 0; std::swap(dst.curve_offsets, src.curve_offsets); MEM_SAFE_FREE(src.curve_offsets); @@ -128,7 +130,7 @@ static void move_curves_geometry(CurvesGeometry &dst, CurvesGeometry &src) } CurvesGeometry::CurvesGeometry(CurvesGeometry &&other) - : CurvesGeometry(other.point_size, other.curve_size) + : CurvesGeometry(other.point_num, other.curve_num) { move_curves_geometry(*this, other); } @@ -143,8 +145,8 @@ CurvesGeometry &CurvesGeometry::operator=(CurvesGeometry &&other) CurvesGeometry::~CurvesGeometry() { - CustomData_free(&this->point_data, this->point_size); - CustomData_free(&this->curve_data, this->curve_size); + CustomData_free(&this->point_data, this->point_num); + CustomData_free(&this->curve_data, this->curve_num); MEM_SAFE_FREE(this->curve_offsets); MEM_delete(this->runtime); this->runtime = nullptr; @@ -156,7 +158,7 @@ CurvesGeometry::~CurvesGeometry() /** \name Accessors * \{ */ -static int domain_size(const CurvesGeometry &curves, const AttributeDomain domain) +static int domain_num(const CurvesGeometry &curves, const AttributeDomain domain) { return domain == ATTR_DOMAIN_POINT ? curves.points_num() : curves.curves_num(); } @@ -178,15 +180,15 @@ static VArray<T> get_varray_attribute(const CurvesGeometry &curves, const StringRefNull name, const T default_value) { - const int size = domain_size(curves, domain); + const int num = domain_num(curves, domain); const CustomDataType type = cpp_type_to_custom_data_type(CPPType::get<T>()); const CustomData &custom_data = domain_custom_data(curves, domain); const T *data = (const T *)CustomData_get_layer_named(&custom_data, type, name.c_str()); if (data != nullptr) { - return VArray<T>::ForSpan(Span<T>(data, size)); + return VArray<T>::ForSpan(Span<T>(data, num)); } - return VArray<T>::ForSingle(default_value, size); + return VArray<T>::ForSingle(default_value, num); } template<typename T> @@ -194,7 +196,7 @@ static Span<T> get_span_attribute(const CurvesGeometry &curves, const AttributeDomain domain, const StringRefNull name) { - const int size = domain_size(curves, domain); + const int num = domain_num(curves, domain); const CustomData &custom_data = domain_custom_data(curves, domain); const CustomDataType type = cpp_type_to_custom_data_type(CPPType::get<T>()); @@ -202,7 +204,7 @@ static Span<T> get_span_attribute(const CurvesGeometry &curves, if (data == nullptr) { return {}; } - return {data, size}; + return {data, num}; } template<typename T> @@ -211,19 +213,19 @@ static MutableSpan<T> get_mutable_attribute(CurvesGeometry &curves, const StringRefNull name, const T default_value = T()) { - const int size = domain_size(curves, domain); + const int num = domain_num(curves, domain); const CustomDataType type = cpp_type_to_custom_data_type(CPPType::get<T>()); CustomData &custom_data = domain_custom_data(curves, domain); T *data = (T *)CustomData_duplicate_referenced_layer_named( - &custom_data, type, name.c_str(), size); + &custom_data, type, name.c_str(), num); if (data != nullptr) { - return {data, size}; + return {data, num}; } data = (T *)CustomData_add_layer_named( - &custom_data, type, CD_CALLOC, nullptr, size, name.c_str()); - MutableSpan<T> span = {data, size}; - if (size > 0 && span.first() != default_value) { + &custom_data, type, CD_CALLOC, nullptr, num, name.c_str()); + MutableSpan<T> span = {data, num}; + if (num > 0 && span.first() != default_value) { span.fill(default_value); } return span; @@ -250,6 +252,10 @@ void CurvesGeometry::fill_curve_types(const CurveType type) void CurvesGeometry::fill_curve_types(const IndexMask selection, const CurveType type) { + if (selection.size() == this->curves_num()) { + this->fill_curve_types(type); + return; + } /* A potential performance optimization is only counting the changed indices. */ this->curve_types_for_write().fill_indices(selection, type); this->update_curve_types(); @@ -295,22 +301,22 @@ void CurvesGeometry::update_curve_types() Span<float3> CurvesGeometry::positions() const { - return {(const float3 *)this->position, this->point_size}; + return {(const float3 *)this->position, this->point_num}; } MutableSpan<float3> CurvesGeometry::positions_for_write() { this->position = (float(*)[3])CustomData_duplicate_referenced_layer_named( - &this->point_data, CD_PROP_FLOAT3, ATTR_POSITION.c_str(), this->point_size); - return {(float3 *)this->position, this->point_size}; + &this->point_data, CD_PROP_FLOAT3, ATTR_POSITION.c_str(), this->point_num); + return {(float3 *)this->position, this->point_num}; } Span<int> CurvesGeometry::offsets() const { - return {this->curve_offsets, this->curve_size + 1}; + return {this->curve_offsets, this->curve_num + 1}; } MutableSpan<int> CurvesGeometry::offsets_for_write() { - return {this->curve_offsets, this->curve_size + 1}; + return {this->curve_offsets, this->curve_num + 1}; } VArray<bool> CurvesGeometry::cyclic() const @@ -438,12 +444,12 @@ MutableSpan<float2> CurvesGeometry::surface_triangle_coords_for_write() /** \name Evaluation * \{ */ -template<typename SizeFn> void build_offsets(MutableSpan<int> offsets, const SizeFn &size_fn) +template<typename CountFn> void build_offsets(MutableSpan<int> offsets, const CountFn &count_fn) { int offset = 0; for (const int i : offsets.drop_back(1).index_range()) { offsets[i] = offset; - offset += size_fn(i); + offset += count_fn(i); } offsets.last() = offset; } @@ -466,7 +472,7 @@ static void calculate_evaluated_offsets(const CurvesGeometry &curves, const IndexRange points = curves.points_for_curve(curve_index); switch (types[curve_index]) { case CURVE_TYPE_CATMULL_ROM: - return curves::catmull_rom::calculate_evaluated_size( + return curves::catmull_rom::calculate_evaluated_num( points.size(), cyclic[curve_index], resolution[curve_index]); case CURVE_TYPE_POLY: return points.size(); @@ -478,11 +484,11 @@ static void calculate_evaluated_offsets(const CurvesGeometry &curves, bezier_evaluated_offsets.slice(points)); return bezier_evaluated_offsets[points.last()]; case CURVE_TYPE_NURBS: - return curves::nurbs::calculate_evaluated_size(points.size(), - nurbs_orders[curve_index], - cyclic[curve_index], - resolution[curve_index], - KnotsMode(nurbs_knots_modes[curve_index])); + return curves::nurbs::calculate_evaluated_num(points.size(), + nurbs_orders[curve_index], + cyclic[curve_index], + resolution[curve_index], + KnotsMode(nurbs_knots_modes[curve_index])); } BLI_assert_unreachable(); return 0; @@ -527,19 +533,23 @@ Span<int> CurvesGeometry::evaluated_offsets() const IndexMask CurvesGeometry::indices_for_curve_type(const CurveType type, Vector<int64_t> &r_indices) const { + return this->indices_for_curve_type(type, this->curves_range(), r_indices); +} - VArray<int8_t> types = this->curve_types(); +IndexMask CurvesGeometry::indices_for_curve_type(const CurveType type, + const IndexMask selection, + Vector<int64_t> &r_indices) const +{ + if (this->curve_type_counts()[type] == this->curves_num()) { + return selection; + } + const VArray<int8_t> types = this->curve_types(); if (types.is_single()) { - if (types.get_internal_single() == type) { - return IndexMask(types.size()); - } - return {}; + return types.get_internal_single() == type ? IndexMask(this->curves_num()) : IndexMask(0); } Span<int8_t> types_span = types.get_internal_span(); return index_mask_ops::find_indices_based_on_predicate( - IndexMask(types.size()), 1024, r_indices, [&](const int index) { - return types_span[index] == type; - }); + selection, 1024, r_indices, [&](const int index) { return types_span[index] == type; }); } void CurvesGeometry::ensure_nurbs_basis_cache() const @@ -577,8 +587,13 @@ void CurvesGeometry::ensure_nurbs_basis_cache() const const bool is_cyclic = cyclic[curve_index]; const KnotsMode mode = KnotsMode(knots_modes[curve_index]); - const int knots_size = curves::nurbs::knots_size(points.size(), order, is_cyclic); - Array<float> knots(knots_size); + if (!curves::nurbs::check_valid_num_and_order(points.size(), order, is_cyclic, mode)) { + basis_caches[curve_index].invalid = true; + continue; + } + + const int knots_num = curves::nurbs::knots_num(points.size(), order, is_cyclic); + Array<float> knots(knots_num); curves::nurbs::calculate_knots(points.size(), mode, order, is_cyclic, knots); curves::nurbs::calculate_basis_cache(points.size(), evaluated_points.size(), @@ -696,9 +711,6 @@ Span<float3> CurvesGeometry::evaluated_tangents() const threading::parallel_for(this->curves_range(), 128, [&](IndexRange curves_range) { for (const int curve_index : curves_range) { const IndexRange evaluated_points = this->evaluated_points_for_curve(curve_index); - if (UNLIKELY(evaluated_points.is_empty())) { - continue; - } curves::poly::calculate_tangents(evaluated_positions.slice(evaluated_points), cyclic[curve_index], tangents.slice(evaluated_points)); @@ -773,9 +785,6 @@ Span<float3> CurvesGeometry::evaluated_normals() const for (const int curve_index : curves_range) { const IndexRange evaluated_points = this->evaluated_points_for_curve(curve_index); - if (UNLIKELY(evaluated_points.is_empty())) { - continue; - } switch (normal_mode[curve_index]) { case NORMAL_MODE_Z_UP: curves::poly::calculate_normals_z_up(evaluated_tangents.slice(evaluated_points), @@ -905,8 +914,8 @@ void CurvesGeometry::ensure_evaluated_lengths() const threading::isolate_task([&]() { /* Use an extra length value for the final cyclic segment for a consistent size * (see comment on #evaluated_length_cache). */ - const int total_size = this->evaluated_points_num() + this->curves_num(); - this->runtime->evaluated_length_cache.resize(total_size); + const int total_num = this->evaluated_points_num() + this->curves_num(); + this->runtime->evaluated_length_cache.resize(total_num); MutableSpan<float> evaluated_lengths = this->runtime->evaluated_length_cache; Span<float3> evaluated_positions = this->evaluated_positions(); @@ -916,9 +925,6 @@ void CurvesGeometry::ensure_evaluated_lengths() const for (const int curve_index : curves_range) { const bool cyclic = curves_cyclic[curve_index]; const IndexRange evaluated_points = this->evaluated_points_for_curve(curve_index); - if (UNLIKELY(evaluated_points.is_empty())) { - continue; - } const IndexRange lengths_range = this->lengths_range_for_curve(curve_index, cyclic); length_parameterize::accumulate_lengths(evaluated_positions.slice(evaluated_points), cyclic, @@ -938,13 +944,13 @@ void CurvesGeometry::ensure_evaluated_lengths() const void CurvesGeometry::resize(const int points_num, const int curves_num) { - if (points_num != this->point_size) { + if (points_num != this->point_num) { CustomData_realloc(&this->point_data, points_num); - this->point_size = points_num; + this->point_num = points_num; } - if (curves_num != this->curve_size) { + if (curves_num != this->curve_num) { CustomData_realloc(&this->curve_data, curves_num); - this->curve_size = curves_num; + this->curve_num = curves_num; this->curve_offsets = (int *)MEM_reallocN(this->curve_offsets, sizeof(int) * (curves_num + 1)); } this->tag_topology_changed(); @@ -1196,6 +1202,8 @@ static CurvesGeometry copy_with_removed_curves(const CurvesGeometry &curves, } }); + new_curves.update_curve_types(); + return new_curves; } diff --git a/source/blender/blenkernel/intern/curves_utils.cc b/source/blender/blenkernel/intern/curves_utils.cc new file mode 100644 index 00000000000..78c2382b62f --- /dev/null +++ b/source/blender/blenkernel/intern/curves_utils.cc @@ -0,0 +1,38 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ + +/** \file + * \ingroup bke + */ + +#include "BKE_curves_utils.hh" + +namespace blender::bke::curves { + +void fill_curve_counts(const bke::CurvesGeometry &curves, + const Span<IndexRange> curve_ranges, + MutableSpan<int> counts) +{ + threading::parallel_for(curve_ranges.index_range(), 512, [&](IndexRange ranges_range) { + for (const IndexRange curves_range : curve_ranges.slice(ranges_range)) { + threading::parallel_for(curves_range, 4096, [&](IndexRange range) { + for (const int i : range) { + counts[i] = curves.points_for_curve(i).size(); + } + }); + } + }); +} + +void accumulate_counts_to_offsets(MutableSpan<int> counts_to_offsets, const int start_offset) +{ + int offset = start_offset; + for (const int i : counts_to_offsets.index_range().drop_back(1)) { + const int count = counts_to_offsets[i]; + BLI_assert(count > 0); + counts_to_offsets[i] = offset; + offset += count; + } + counts_to_offsets.last() = offset; +} + +} // namespace blender::bke::curves diff --git a/source/blender/blenkernel/intern/customdata.cc b/source/blender/blenkernel/intern/customdata.cc index 62351a31042..da5c8389be2 100644 --- a/source/blender/blenkernel/intern/customdata.cc +++ b/source/blender/blenkernel/intern/customdata.cc @@ -25,6 +25,7 @@ #include "BLI_math_vector.hh" #include "BLI_mempool.h" #include "BLI_path_util.h" +#include "BLI_span.hh" #include "BLI_string.h" #include "BLI_string_utils.h" #include "BLI_utildefines.h" @@ -54,6 +55,9 @@ /* only for customdata_data_transfer_interp_normal_normals */ #include "data_transfer_intern.h" +using blender::Span; +using blender::Vector; + /* number of layers to add when growing a CustomData object */ #define CUSTOMDATA_GROW 5 @@ -2575,36 +2579,48 @@ void CustomData_set_layer_stencil(CustomData *data, int type, int n) void CustomData_set_layer_active_index(CustomData *data, int type, int n) { + const int layer_index = data->typemap[type]; + BLI_assert(customdata_typemap_is_valid(data)); + for (int i = 0; i < data->totlayer; i++) { if (data->layers[i].type == type) { - data->layers[i].active = n - i; + data->layers[i].active = n - layer_index; } } } void CustomData_set_layer_render_index(CustomData *data, int type, int n) { + const int layer_index = data->typemap[type]; + BLI_assert(customdata_typemap_is_valid(data)); + for (int i = 0; i < data->totlayer; i++) { if (data->layers[i].type == type) { - data->layers[i].active_rnd = n - i; + data->layers[i].active_rnd = n - layer_index; } } } void CustomData_set_layer_clone_index(CustomData *data, int type, int n) { + const int layer_index = data->typemap[type]; + BLI_assert(customdata_typemap_is_valid(data)); + for (int i = 0; i < data->totlayer; i++) { if (data->layers[i].type == type) { - data->layers[i].active_clone = n - i; + data->layers[i].active_clone = n - layer_index; } } } void CustomData_set_layer_stencil_index(CustomData *data, int type, int n) { + const int layer_index = data->typemap[type]; + BLI_assert(customdata_typemap_is_valid(data)); + for (int i = 0; i < data->totlayer; i++) { if (data->layers[i].type == type) { - data->layers[i].active_mask = n - i; + data->layers[i].active_mask = n - layer_index; } } } @@ -3646,7 +3662,7 @@ void CustomData_bmesh_init_pool(CustomData *data, int totelem, const char htype) chunksize = bm_mesh_chunksize_default.totface; break; default: - BLI_assert(0); + BLI_assert_unreachable(); chunksize = 512; break; } @@ -4337,45 +4353,19 @@ void CustomData_file_write_info(int type, const char **r_struct_name, int *r_str *r_struct_num = typeInfo->structnum; } -void CustomData_blend_write_prepare(CustomData *data, - CustomDataLayer **r_write_layers, - CustomDataLayer *write_layers_buff, - size_t write_layers_size) +void CustomData_blend_write_prepare(CustomData &data, Vector<CustomDataLayer, 16> &layers_to_write) { - CustomDataLayer *write_layers = write_layers_buff; - const size_t chunk_size = (write_layers_size > 0) ? write_layers_size : CD_TEMP_CHUNK_SIZE; - - const int totlayer = data->totlayer; - int i, j; - - for (i = 0, j = 0; i < totlayer; i++) { - CustomDataLayer *layer = &data->layers[i]; - /* Layers with this flag set are not written to file. */ - if ((layer->flag & CD_FLAG_NOCOPY) || layer->anonymous_id != nullptr) { - data->totlayer--; - // CLOG_WARN(&LOG, "skipping layer %p (%s)", layer, layer->name); + for (const CustomDataLayer &layer : Span(data.layers, data.totlayer)) { + if (layer.flag & CD_FLAG_NOCOPY) { + continue; } - else { - if (UNLIKELY((size_t)j >= write_layers_size)) { - if (write_layers == write_layers_buff) { - write_layers = (CustomDataLayer *)MEM_malloc_arrayN( - (write_layers_size + chunk_size), sizeof(*write_layers), __func__); - if (write_layers_buff) { - memcpy(write_layers, write_layers_buff, sizeof(*write_layers) * write_layers_size); - } - } - else { - write_layers = (CustomDataLayer *)MEM_reallocN( - write_layers, sizeof(*write_layers) * (write_layers_size + chunk_size)); - } - write_layers_size += chunk_size; - } - write_layers[j++] = *layer; + if (layer.anonymous_id != nullptr) { + continue; } + layers_to_write.append(layer); } - BLI_assert(j == data->totlayer); - data->maxlayer = data->totlayer; /* We only write that much of data! */ - *r_write_layers = write_layers; + data.totlayer = layers_to_write.size(); + data.maxlayer = data.totlayer; } int CustomData_sizeof(int type) @@ -5137,12 +5127,12 @@ void CustomData_data_transfer(const MeshPairRemap *me_remap, /** \name Custom Data IO * \{ */ -static void write_mdisps(BlendWriter *writer, int count, MDisps *mdlist, int external) +static void write_mdisps(BlendWriter *writer, int count, const MDisps *mdlist, int external) { if (mdlist) { BLO_write_struct_array(writer, MDisps, count, mdlist); for (int i = 0; i < count; i++) { - MDisps *md = &mdlist[i]; + const MDisps *md = &mdlist[i]; if (md->disps) { if (!external) { BLO_write_float3_array(writer, md->totdisp, &md->disps[0][0]); @@ -5156,12 +5146,14 @@ static void write_mdisps(BlendWriter *writer, int count, MDisps *mdlist, int ext } } -static void write_grid_paint_mask(BlendWriter *writer, int count, GridPaintMask *grid_paint_mask) +static void write_grid_paint_mask(BlendWriter *writer, + int count, + const GridPaintMask *grid_paint_mask) { if (grid_paint_mask) { BLO_write_struct_array(writer, GridPaintMask, count, grid_paint_mask); for (int i = 0; i < count; i++) { - GridPaintMask *gpm = &grid_paint_mask[i]; + const GridPaintMask *gpm = &grid_paint_mask[i]; if (gpm->data) { const int gridsize = BKE_ccg_gridsize(gpm->level); BLO_write_raw(writer, sizeof(*gpm->data) * gridsize * gridsize, gpm->data); @@ -5172,7 +5164,7 @@ static void write_grid_paint_mask(BlendWriter *writer, int count, GridPaintMask void CustomData_blend_write(BlendWriter *writer, CustomData *data, - CustomDataLayer *layers, + Span<CustomDataLayer> layers_to_write, int count, CustomDataMask cddata_mask, ID *id) @@ -5182,55 +5174,50 @@ void CustomData_blend_write(BlendWriter *writer, CustomData_external_write(data, id, cddata_mask, count, 0); } - BLO_write_struct_array_at_address(writer, CustomDataLayer, data->totlayer, data->layers, layers); - - for (int i = 0; i < data->totlayer; i++) { - CustomDataLayer *layer = &layers[i]; + BLO_write_struct_array_at_address( + writer, CustomDataLayer, data->totlayer, data->layers, layers_to_write.data()); - if (layer->type == CD_MDEFORMVERT) { - /* layer types that allocate own memory need special handling */ - BKE_defvert_blend_write(writer, count, static_cast<struct MDeformVert *>(layer->data)); - } - else if (layer->type == CD_MDISPS) { - write_mdisps( - writer, count, static_cast<MDisps *>(layer->data), layer->flag & CD_FLAG_EXTERNAL); - } - else if (layer->type == CD_PAINT_MASK) { - const float *layer_data = static_cast<const float *>(layer->data); - BLO_write_raw(writer, sizeof(*layer_data) * count, layer_data); - } - else if (layer->type == CD_SCULPT_FACE_SETS) { - const float *layer_data = static_cast<const float *>(layer->data); - BLO_write_raw(writer, sizeof(*layer_data) * count, layer_data); - } - else if (layer->type == CD_GRID_PAINT_MASK) { - write_grid_paint_mask(writer, count, static_cast<GridPaintMask *>(layer->data)); - } - else if (layer->type == CD_FACEMAP) { - const int *layer_data = static_cast<const int *>(layer->data); - BLO_write_raw(writer, sizeof(*layer_data) * count, layer_data); - } - else if (layer->type == CD_PROP_BOOL) { - const bool *layer_data = static_cast<const bool *>(layer->data); - BLO_write_raw(writer, sizeof(*layer_data) * count, layer_data); - } - else if (layer->type == CD_CREASE) { - const float *layer_data = static_cast<const float *>(layer->data); - BLO_write_raw(writer, sizeof(*layer_data) * count, layer_data); - } - else { - const char *structname; - int structnum; - CustomData_file_write_info(layer->type, &structname, &structnum); - if (structnum) { - int datasize = structnum * count; - BLO_write_struct_array_by_name(writer, structname, datasize, layer->data); - } - else if (!BLO_write_is_undo(writer)) { /* Do not warn on undo. */ - printf("%s error: layer '%s':%d - can't be written to file\n", - __func__, - structname, - layer->type); + for (const CustomDataLayer &layer : layers_to_write) { + switch (layer.type) { + case CD_MDEFORMVERT: + BKE_defvert_blend_write(writer, count, static_cast<const MDeformVert *>(layer.data)); + break; + case CD_MDISPS: + write_mdisps( + writer, count, static_cast<const MDisps *>(layer.data), layer.flag & CD_FLAG_EXTERNAL); + break; + case CD_PAINT_MASK: + BLO_write_raw(writer, sizeof(float) * count, static_cast<const float *>(layer.data)); + break; + case CD_SCULPT_FACE_SETS: + BLO_write_raw(writer, sizeof(float) * count, static_cast<const float *>(layer.data)); + break; + case CD_GRID_PAINT_MASK: + write_grid_paint_mask(writer, count, static_cast<const GridPaintMask *>(layer.data)); + break; + case CD_FACEMAP: + BLO_write_raw(writer, sizeof(int) * count, static_cast<const int *>(layer.data)); + break; + case CD_PROP_BOOL: + BLO_write_raw(writer, sizeof(bool) * count, static_cast<const bool *>(layer.data)); + break; + case CD_CREASE: + BLO_write_raw(writer, sizeof(float) * count, static_cast<const float *>(layer.data)); + break; + default: { + const char *structname; + int structnum; + CustomData_file_write_info(layer.type, &structname, &structnum); + if (structnum) { + int datasize = structnum * count; + BLO_write_struct_array_by_name(writer, structname, datasize, layer.data); + } + else if (!BLO_write_is_undo(writer)) { /* Do not warn on undo. */ + printf("%s error: layer '%s':%d - can't be written to file\n", + __func__, + structname, + layer.type); + } } } } diff --git a/source/blender/blenkernel/intern/customdata_file.c b/source/blender/blenkernel/intern/customdata_file.c index 9716b4909b2..cbfaf2831d1 100644 --- a/source/blender/blenkernel/intern/customdata_file.c +++ b/source/blender/blenkernel/intern/customdata_file.c @@ -268,11 +268,11 @@ static bool cdf_write_header(CDataFile *cdf) return true; } -bool cdf_read_open(CDataFile *cdf, const char *filename) +bool cdf_read_open(CDataFile *cdf, const char *filepath) { FILE *f; - f = BLI_fopen(filename, "rb"); + f = BLI_fopen(filepath, "rb"); if (!f) { return false; } @@ -333,14 +333,14 @@ void cdf_read_close(CDataFile *cdf) } } -bool cdf_write_open(CDataFile *cdf, const char *filename) +bool cdf_write_open(CDataFile *cdf, const char *filepath) { CDataFileHeader *header; CDataFileImageHeader *image; CDataFileMeshHeader *mesh; FILE *f; - f = BLI_fopen(filename, "wb"); + f = BLI_fopen(filepath, "wb"); if (!f) { return false; } @@ -402,9 +402,9 @@ void cdf_write_close(CDataFile *cdf) } } -void cdf_remove(const char *filename) +void cdf_remove(const char *filepath) { - BLI_delete(filename, false, false); + BLI_delete(filepath, false, false); } /********************************** Layers ***********************************/ diff --git a/source/blender/blenkernel/intern/data_transfer.c b/source/blender/blenkernel/intern/data_transfer.c index 6a3f6a47f5e..196a6a00ade 100644 --- a/source/blender/blenkernel/intern/data_transfer.c +++ b/source/blender/blenkernel/intern/data_transfer.c @@ -222,7 +222,7 @@ int BKE_object_data_transfer_dttype_to_cdtype(const int dtdata_type) case DT_TYPE_MPROPCOL_LOOP: return CD_PROP_COLOR; default: - BLI_assert(0); + BLI_assert_unreachable(); } return 0; /* Should never be reached! */ } @@ -477,7 +477,7 @@ static void data_transfer_layersmapping_add_item_cd(ListBase *r_map, const int mix_mode, const float mix_factor, const float *mix_weights, - void *data_src, + const void *data_src, void *data_dst, cd_datatransfer_interp interp, void *interp_data) @@ -532,7 +532,8 @@ static bool data_transfer_layersmapping_cdlayers_multisrc_to_dst(ListBase *r_map cd_datatransfer_interp interp, void *interp_data) { - void *data_src, *data_dst = NULL; + const void *data_src; + void *data_dst = NULL; int idx_src = num_layers_src; int idx_dst, tot_dst = CustomData_number_of_layers(cd_dst, cddata_type); bool *data_dst_to_delete = NULL; @@ -695,7 +696,8 @@ static bool data_transfer_layersmapping_cdlayers(ListBase *r_map, void *interp_data) { int idx_src, idx_dst; - void *data_src, *data_dst = NULL; + const void *data_src; + void *data_dst = NULL; if (CustomData_layertype_is_singleton(cddata_type)) { if (!(data_src = CustomData_get_layer(cd_src, cddata_type))) { @@ -1369,7 +1371,7 @@ bool BKE_object_data_transfer_ex(struct Depsgraph *depsgraph, /* Assumed always true if not using an evaluated mesh as destination. */ bool dirty_nors_dst = true; - MDeformVert *mdef = NULL; + const MDeformVert *mdef = NULL; int vg_idx = -1; float *weights[DATAMAX] = {NULL}; @@ -1509,7 +1511,7 @@ bool BKE_object_data_transfer_ex(struct Depsgraph *depsgraph, if (mdef && vg_idx != -1 && !weights[VDATA]) { weights[VDATA] = MEM_mallocN(sizeof(*(weights[VDATA])) * (size_t)num_verts_dst, __func__); BKE_defvert_extract_vgroup_to_vertweights( - mdef, vg_idx, num_verts_dst, weights[VDATA], invert_vgroup); + mdef, vg_idx, num_verts_dst, invert_vgroup, weights[VDATA]); } if (data_transfer_layersmapping_generate(&lay_map, @@ -1588,7 +1590,7 @@ bool BKE_object_data_transfer_ex(struct Depsgraph *depsgraph, if (mdef && vg_idx != -1 && !weights[EDATA]) { weights[EDATA] = MEM_mallocN(sizeof(*weights[EDATA]) * (size_t)num_edges_dst, __func__); BKE_defvert_extract_vgroup_to_edgeweights( - mdef, vg_idx, num_verts_dst, edges_dst, num_edges_dst, weights[EDATA], invert_vgroup); + mdef, vg_idx, num_verts_dst, edges_dst, num_edges_dst, invert_vgroup, weights[EDATA]); } if (data_transfer_layersmapping_generate(&lay_map, @@ -1683,7 +1685,7 @@ bool BKE_object_data_transfer_ex(struct Depsgraph *depsgraph, if (mdef && vg_idx != -1 && !weights[LDATA]) { weights[LDATA] = MEM_mallocN(sizeof(*weights[LDATA]) * (size_t)num_loops_dst, __func__); BKE_defvert_extract_vgroup_to_loopweights( - mdef, vg_idx, num_verts_dst, loops_dst, num_loops_dst, weights[LDATA], invert_vgroup); + mdef, vg_idx, num_verts_dst, loops_dst, num_loops_dst, invert_vgroup, weights[LDATA]); } if (data_transfer_layersmapping_generate(&lay_map, @@ -1769,8 +1771,8 @@ bool BKE_object_data_transfer_ex(struct Depsgraph *depsgraph, num_loops_dst, polys_dst, num_polys_dst, - weights[PDATA], - invert_vgroup); + invert_vgroup, + weights[PDATA]); } if (data_transfer_layersmapping_generate(&lay_map, diff --git a/source/blender/blenkernel/intern/deform.c b/source/blender/blenkernel/intern/deform.c index 1d276e9108c..ebe06fa85eb 100644 --- a/source/blender/blenkernel/intern/deform.c +++ b/source/blender/blenkernel/intern/deform.c @@ -147,9 +147,9 @@ void BKE_defvert_copy_index(MDeformVert *dvert_dst, const MDeformVert *dvert_src, const int defgroup_src) { - MDeformWeight *dw_src, *dw_dst; + MDeformWeight *dw_dst; - dw_src = BKE_defvert_find_index(dvert_src, defgroup_src); + const MDeformWeight *dw_src = BKE_defvert_find_index(dvert_src, defgroup_src); if (dw_src) { /* Source is valid, ensure destination is created. */ @@ -1008,11 +1008,11 @@ void BKE_defvert_array_free(MDeformVert *dvert, int totvert) MEM_freeN(dvert); } -void BKE_defvert_extract_vgroup_to_vertweights(MDeformVert *dvert, +void BKE_defvert_extract_vgroup_to_vertweights(const MDeformVert *dvert, const int defgroup, const int num_verts, - float *r_weights, - const bool invert_vgroup) + const bool invert_vgroup, + float *r_weights) { if (dvert && defgroup != -1) { int i = num_verts; @@ -1027,20 +1027,20 @@ void BKE_defvert_extract_vgroup_to_vertweights(MDeformVert *dvert, } } -void BKE_defvert_extract_vgroup_to_edgeweights(MDeformVert *dvert, +void BKE_defvert_extract_vgroup_to_edgeweights(const MDeformVert *dvert, const int defgroup, const int num_verts, MEdge *edges, const int num_edges, - float *r_weights, - const bool invert_vgroup) + const bool invert_vgroup, + float *r_weights) { if (dvert && defgroup != -1) { int i = num_edges; float *tmp_weights = MEM_mallocN(sizeof(*tmp_weights) * (size_t)num_verts, __func__); BKE_defvert_extract_vgroup_to_vertweights( - dvert, defgroup, num_verts, tmp_weights, invert_vgroup); + dvert, defgroup, num_verts, invert_vgroup, tmp_weights); while (i--) { MEdge *me = &edges[i]; @@ -1055,20 +1055,20 @@ void BKE_defvert_extract_vgroup_to_edgeweights(MDeformVert *dvert, } } -void BKE_defvert_extract_vgroup_to_loopweights(MDeformVert *dvert, +void BKE_defvert_extract_vgroup_to_loopweights(const MDeformVert *dvert, const int defgroup, const int num_verts, MLoop *loops, const int num_loops, - float *r_weights, - const bool invert_vgroup) + const bool invert_vgroup, + float *r_weights) { if (dvert && defgroup != -1) { int i = num_loops; float *tmp_weights = MEM_mallocN(sizeof(*tmp_weights) * (size_t)num_verts, __func__); BKE_defvert_extract_vgroup_to_vertweights( - dvert, defgroup, num_verts, tmp_weights, invert_vgroup); + dvert, defgroup, num_verts, invert_vgroup, tmp_weights); while (i--) { MLoop *ml = &loops[i]; @@ -1083,22 +1083,22 @@ void BKE_defvert_extract_vgroup_to_loopweights(MDeformVert *dvert, } } -void BKE_defvert_extract_vgroup_to_polyweights(MDeformVert *dvert, +void BKE_defvert_extract_vgroup_to_polyweights(const MDeformVert *dvert, const int defgroup, const int num_verts, MLoop *loops, const int UNUSED(num_loops), MPoly *polys, const int num_polys, - float *r_weights, - const bool invert_vgroup) + const bool invert_vgroup, + float *r_weights) { if (dvert && defgroup != -1) { int i = num_polys; float *tmp_weights = MEM_mallocN(sizeof(*tmp_weights) * (size_t)num_verts, __func__); BKE_defvert_extract_vgroup_to_vertweights( - dvert, defgroup, num_verts, tmp_weights, invert_vgroup); + dvert, defgroup, num_verts, invert_vgroup, tmp_weights); while (i--) { MPoly *mp = &polys[i]; @@ -1193,7 +1193,7 @@ static bool data_transfer_layersmapping_vgroups_multisrc_to_dst(ListBase *r_map, const bool use_delete, Object *ob_src, Object *ob_dst, - MDeformVert *data_src, + const MDeformVert *data_src, MDeformVert *data_dst, CustomData *UNUSED(cd_src), CustomData *cd_dst, @@ -1348,7 +1348,6 @@ bool data_transfer_layersmapping_vgroups(ListBase *r_map, const int tolayers) { int idx_src, idx_dst; - MDeformVert *data_src, *data_dst = NULL; const size_t elem_size = sizeof(*((MDeformVert *)NULL)); @@ -1370,9 +1369,9 @@ bool data_transfer_layersmapping_vgroups(ListBase *r_map, return true; } - data_src = CustomData_get_layer(cd_src, CD_MDEFORMVERT); + const MDeformVert *data_src = CustomData_get_layer(cd_src, CD_MDEFORMVERT); - data_dst = CustomData_get_layer(cd_dst, CD_MDEFORMVERT); + MDeformVert *data_dst = CustomData_get_layer(cd_dst, CD_MDEFORMVERT); if (data_dst && use_dupref_dst && r_map) { /* If dest is a derivedmesh, we do not want to overwrite cdlayers of org mesh! */ data_dst = CustomData_duplicate_referenced_layer(cd_dst, CD_MDEFORMVERT, num_elem_dst); @@ -1562,7 +1561,7 @@ void BKE_defbase_blend_write(BlendWriter *writer, const ListBase *defbase) } } -void BKE_defvert_blend_write(BlendWriter *writer, int count, MDeformVert *dvlist) +void BKE_defvert_blend_write(BlendWriter *writer, int count, const MDeformVert *dvlist) { if (dvlist == NULL) { return; diff --git a/source/blender/blenkernel/intern/dynamicpaint.c b/source/blender/blenkernel/intern/dynamicpaint.c index 22341f98375..48f2d66c1cd 100644 --- a/source/blender/blenkernel/intern/dynamicpaint.c +++ b/source/blender/blenkernel/intern/dynamicpaint.c @@ -1607,7 +1607,6 @@ static void dynamicPaint_setInitialColor(const Scene *scene, DynamicPaintSurface const MLoop *mloop = mesh->mloop; const MLoopTri *mlooptri = BKE_mesh_runtime_looptri_ensure(mesh); const int tottri = BKE_mesh_runtime_looptri_len(mesh); - const MLoopUV *mloopuv = NULL; char uvname[MAX_CUSTOMDATA_LAYER_NAME]; @@ -1617,7 +1616,7 @@ static void dynamicPaint_setInitialColor(const Scene *scene, DynamicPaintSurface /* get uv map */ CustomData_validate_layer_name(&mesh->ldata, CD_MLOOPUV, surface->init_layername, uvname); - mloopuv = CustomData_get_layer_named(&mesh->ldata, CD_MLOOPUV, uvname); + const MLoopUV *mloopuv = CustomData_get_layer_named(&mesh->ldata, CD_MLOOPUV, uvname); if (!mloopuv) { return; } @@ -1675,7 +1674,7 @@ static void dynamicPaint_setInitialColor(const Scene *scene, DynamicPaintSurface } else if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) { const MLoopTri *mlooptri = BKE_mesh_runtime_looptri_ensure(mesh); - MLoopCol *col = CustomData_get_layer_named( + const MLoopCol *col = CustomData_get_layer_named( &mesh->ldata, CD_PROP_BYTE_COLOR, surface->init_layername); if (!col) { return; diff --git a/source/blender/blenkernel/intern/editmesh.c b/source/blender/blenkernel/intern/editmesh.c index d176bf41254..a952da6fa52 100644 --- a/source/blender/blenkernel/intern/editmesh.c +++ b/source/blender/blenkernel/intern/editmesh.c @@ -15,6 +15,7 @@ #include "BLI_math.h" #include "BKE_DerivedMesh.h" +#include "BKE_customdata.h" #include "BKE_editmesh.h" #include "BKE_editmesh_cache.h" #include "BKE_lib_id.h" diff --git a/source/blender/blenkernel/intern/fcurve.c b/source/blender/blenkernel/intern/fcurve.c index 34357c3e454..952d5df299c 100644 --- a/source/blender/blenkernel/intern/fcurve.c +++ b/source/blender/blenkernel/intern/fcurve.c @@ -351,8 +351,8 @@ FCurve *BKE_fcurve_find_by_rna(PointerRNA *ptr, NULL, ptr, prop, rnaindex, r_adt, r_action, r_driven, r_special); } -FCurve *BKE_fcurve_find_by_rna_context_ui(bContext *C, - PointerRNA *ptr, +FCurve *BKE_fcurve_find_by_rna_context_ui(bContext *UNUSED(C), + const PointerRNA *ptr, PropertyRNA *prop, int rnaindex, AnimData **r_animdata, @@ -361,7 +361,6 @@ FCurve *BKE_fcurve_find_by_rna_context_ui(bContext *C, bool *r_special) { FCurve *fcu = NULL; - PointerRNA tptr = *ptr; *r_driven = false; *r_special = false; @@ -388,79 +387,51 @@ FCurve *BKE_fcurve_find_by_rna_context_ui(bContext *C, } /* There must be some RNA-pointer + property combo. */ - if (prop && tptr.owner_id && RNA_property_animateable(&tptr, prop)) { - AnimData *adt = BKE_animdata_from_id(tptr.owner_id); - int step = ( - /* Always 1 in case we have no context (can't check in 'ancestors' of given RNA ptr). */ - C ? 2 : 1); - char *path = NULL; - - if (!adt && C) { - path = RNA_path_from_ID_to_property(&tptr, prop); - adt = BKE_animdata_from_id(tptr.owner_id); - step--; - } - - /* Standard F-Curve - Animation (Action) or Drivers. */ - while (adt && step--) { - if ((adt->action == NULL || adt->action->curves.first == NULL) && - (adt->drivers.first == NULL)) { - continue; - } - - /* XXX This function call can become a performance bottleneck. */ - if (step) { - path = RNA_path_from_ID_to_property(&tptr, prop); - } - if (path == NULL) { - continue; - } + if (!prop || !ptr->owner_id || !RNA_property_animateable(ptr, prop)) { + return fcu; + } - /* XXX: The logic here is duplicated with a function up above. */ - /* animation takes priority over drivers. */ - if (adt->action && adt->action->curves.first) { - fcu = BKE_fcurve_find(&adt->action->curves, path, rnaindex); + AnimData *adt = BKE_animdata_from_id(ptr->owner_id); + if (adt == NULL) { + return fcu; + } - if (fcu && r_action) { - *r_action = adt->action; - } - } + const bool has_action_fcurves = adt->action != NULL && + !BLI_listbase_is_empty(&adt->action->curves); + const bool has_drivers = !BLI_listbase_is_empty(&adt->drivers); - /* If not animated, check if driven. */ - if (!fcu && (adt->drivers.first)) { - fcu = BKE_fcurve_find(&adt->drivers, path, rnaindex); + /* XXX This function call can become a performance bottleneck. */ + char *path = RNA_path_from_ID_to_property(ptr, prop); - if (fcu) { - if (r_animdata) { - *r_animdata = adt; - } - *r_driven = true; - } - } + /* Standard F-Curve - Animation (Action) or Drivers. */ + /* Animation takes priority over drivers. */ + /* XXX: The logic here is duplicated with a function up above. */ + if (has_action_fcurves) { + fcu = BKE_fcurve_find(&adt->action->curves, path, rnaindex); - if (fcu && r_action) { - if (r_animdata) { - *r_animdata = adt; - } + if (fcu) { + if (r_action) { *r_action = adt->action; - break; } + if (r_animdata) { + *r_animdata = adt; + } + } + } - if (step) { - char *tpath = path ? path : RNA_path_from_ID_to_property(&tptr, prop); - if (tpath && tpath != path) { - MEM_freeN(path); - path = tpath; - adt = BKE_animdata_from_id(tptr.owner_id); - } - else { - adt = NULL; - } + /* If not animated, check if driven. */ + if (fcu == NULL && has_drivers) { + fcu = BKE_fcurve_find(&adt->drivers, path, rnaindex); + + if (fcu) { + if (r_animdata) { + *r_animdata = adt; } + *r_driven = true; } - MEM_SAFE_FREE(path); } + MEM_SAFE_FREE(path); return fcu; } diff --git a/source/blender/blenkernel/intern/fluid.c b/source/blender/blenkernel/intern/fluid.c index 5de13fbdbed..06d32d5bfd4 100644 --- a/source/blender/blenkernel/intern/fluid.c +++ b/source/blender/blenkernel/intern/fluid.c @@ -1824,7 +1824,7 @@ static void sample_mesh(FluidFlowSettings *ffs, const float *vert_vel, bool has_velocity, int defgrp_index, - MDeformVert *dvert, + const MDeformVert *dvert, float x, float y, float z) @@ -2008,7 +2008,7 @@ typedef struct EmitFromDMData { const MLoop *mloop; const MLoopTri *mlooptri; const MLoopUV *mloopuv; - MDeformVert *dvert; + const MDeformVert *dvert; int defgrp_index; BVHTreeFromMesh *tree; @@ -2074,14 +2074,8 @@ static void emit_from_mesh( Object *flow_ob, FluidDomainSettings *fds, FluidFlowSettings *ffs, FluidObjectBB *bb, float dt) { if (ffs->mesh) { - Mesh *me = NULL; - MVert *mvert = NULL; - const MLoopTri *mlooptri = NULL; - const MLoop *mloop = NULL; - const MLoopUV *mloopuv = NULL; - MDeformVert *dvert = NULL; BVHTreeFromMesh tree_data = {NULL}; - int numverts, i; + int i; float *vert_vel = NULL; bool has_velocity = false; @@ -2092,7 +2086,7 @@ static void emit_from_mesh( /* Copy mesh for thread safety as we modify it. * Main issue is its VertArray being modified, then replaced and freed. */ - me = BKE_mesh_copy_for_eval(ffs->mesh, true); + Mesh *me = BKE_mesh_copy_for_eval(ffs->mesh, true); /* Duplicate vertices to modify. */ if (me->mvert) { @@ -2100,12 +2094,12 @@ static void emit_from_mesh( CustomData_set_layer(&me->vdata, CD_MVERT, me->mvert); } - mvert = me->mvert; - mloop = me->mloop; - mlooptri = BKE_mesh_runtime_looptri_ensure(me); - numverts = me->totvert; - dvert = CustomData_get_layer(&me->vdata, CD_MDEFORMVERT); - mloopuv = CustomData_get_layer_named(&me->ldata, CD_MLOOPUV, ffs->uvlayer_name); + MVert *mvert = me->mvert; + const MLoop *mloop = me->mloop; + const MLoopTri *mlooptri = BKE_mesh_runtime_looptri_ensure(me); + const int numverts = me->totvert; + const MDeformVert *dvert = CustomData_get_layer(&me->vdata, CD_MDEFORMVERT); + const MLoopUV *mloopuv = CustomData_get_layer_named(&me->ldata, CD_MLOOPUV, ffs->uvlayer_name); if (ffs->flags & FLUID_FLOW_INITVELOCITY) { vert_vel = MEM_callocN(sizeof(float[3]) * numverts, "manta_flow_velocity"); diff --git a/source/blender/blenkernel/intern/geometry_component_curve.cc b/source/blender/blenkernel/intern/geometry_component_curve.cc index f409389e463..a28afc8ddca 100644 --- a/source/blender/blenkernel/intern/geometry_component_curve.cc +++ b/source/blender/blenkernel/intern/geometry_component_curve.cc @@ -114,7 +114,7 @@ void CurveComponentLegacy::ensure_owns_direct_data() /** \name Attribute Access Helper Functions * \{ */ -int CurveComponentLegacy::attribute_domain_size(const AttributeDomain domain) const +int CurveComponentLegacy::attribute_domain_num(const AttributeDomain domain) const { if (curve_ == nullptr) { return 0; @@ -251,8 +251,8 @@ template<typename T> class VArray_For_SplineToPoint final : public VArrayImpl<T> void materialize(const IndexMask mask, MutableSpan<T> r_span) const final { - const int total_size = offsets_.last(); - if (mask.is_range() && mask.as_range() == IndexRange(total_size)) { + const int total_num = offsets_.last(); + if (mask.is_range() && mask.as_range() == IndexRange(total_num)) { for (const int spline_index : original_data_.index_range()) { const int offset = offsets_[spline_index]; const int next_offset = offsets_[spline_index + 1]; @@ -273,8 +273,8 @@ template<typename T> class VArray_For_SplineToPoint final : public VArrayImpl<T> void materialize_to_uninitialized(const IndexMask mask, MutableSpan<T> r_span) const final { T *dst = r_span.data(); - const int total_size = offsets_.last(); - if (mask.is_range() && mask.as_range() == IndexRange(total_size)) { + const int total_num = offsets_.last(); + if (mask.is_range() && mask.as_range() == IndexRange(total_num)) { for (const int spline_index : original_data_.index_range()) { const int offset = offsets_[spline_index]; const int next_offset = offsets_[spline_index + 1]; @@ -415,7 +415,7 @@ class BuiltinSplineAttributeProvider final : public BuiltinAttributeProvider { bool exists(const GeometryComponent &component) const final { - return component.attribute_domain_size(ATTR_DOMAIN_CURVE) != 0; + return component.attribute_domain_num(ATTR_DOMAIN_CURVE) != 0; } }; @@ -495,8 +495,8 @@ static void point_attribute_materialize(Span<Span<T>> data, const IndexMask mask, MutableSpan<T> r_span) { - const int total_size = offsets.last(); - if (mask.is_range() && mask.as_range() == IndexRange(total_size)) { + const int total_num = offsets.last(); + if (mask.is_range() && mask.as_range() == IndexRange(total_num)) { for (const int spline_index : data.index_range()) { const int offset = offsets[spline_index]; const int next_offset = offsets[spline_index + 1]; @@ -541,8 +541,8 @@ static void point_attribute_materialize_to_uninitialized(Span<Span<T>> data, MutableSpan<T> r_span) { T *dst = r_span.data(); - const int total_size = offsets.last(); - if (mask.is_range() && mask.as_range() == IndexRange(total_size)) { + const int total_num = offsets.last(); + if (mask.is_range() && mask.as_range() == IndexRange(total_num)) { for (const int spline_index : data.index_range()) { const int offset = offsets[spline_index]; const int next_offset = offsets[spline_index + 1]; @@ -589,13 +589,13 @@ static GVArray varray_from_initializer(const AttributeInit &initializer, case AttributeInit::Type::VArray: return static_cast<const AttributeInitVArray &>(initializer).varray; case AttributeInit::Type::MoveArray: - int total_size = 0; + int total_num = 0; for (const SplinePtr &spline : splines) { - total_size += spline->size(); + total_num += spline->size(); } return GVArray::ForSpan(GSpan(*bke::custom_data_type_to_cpp_type(data_type), static_cast<const AttributeInitMove &>(initializer).data, - total_size)); + total_num)); } BLI_assert_unreachable(); return {}; @@ -1168,7 +1168,7 @@ class BezierHandleAttributeProvider : public BuiltinAttributeProvider { } return curve->has_spline_with_type(CURVE_TYPE_BEZIER) && - component.attribute_domain_size(ATTR_DOMAIN_POINT) != 0; + component.attribute_domain_num(ATTR_DOMAIN_POINT) != 0; } }; diff --git a/source/blender/blenkernel/intern/geometry_component_curves.cc b/source/blender/blenkernel/intern/geometry_component_curves.cc index bc9bba3ee2f..9b023d12a7d 100644 --- a/source/blender/blenkernel/intern/geometry_component_curves.cc +++ b/source/blender/blenkernel/intern/geometry_component_curves.cc @@ -135,12 +135,12 @@ const Curve *CurveComponent::get_curve_for_render() const /** \} */ +namespace blender::bke { + /* -------------------------------------------------------------------- */ /** \name Curve Normals Access * \{ */ -namespace blender::bke { - static Array<float3> curve_normal_point_domain(const bke::CurvesGeometry &curves) { const VArray<int8_t> types = curves.curve_types(); @@ -237,26 +237,89 @@ VArray<float3> curve_normals_varray(const CurveComponent &component, const Attri return nullptr; } -} // namespace blender::bke +/** \} */ + +/* -------------------------------------------------------------------- */ +/** \name Curve Length Field Input + * \{ */ + +static VArray<float> construct_curve_length_gvarray(const CurveComponent &component, + const AttributeDomain domain) +{ + if (!component.has_curves()) { + return {}; + } + const Curves &curves_id = *component.get_for_read(); + const bke::CurvesGeometry &curves = bke::CurvesGeometry::wrap(curves_id.geometry); + + curves.ensure_evaluated_lengths(); + + VArray<bool> cyclic = curves.cyclic(); + VArray<float> lengths = VArray<float>::ForFunc( + curves.curves_num(), [&curves, cyclic = std::move(cyclic)](int64_t index) { + return curves.evaluated_length_total_for_curve(index, cyclic[index]); + }); + + if (domain == ATTR_DOMAIN_CURVE) { + return lengths; + } + + if (domain == ATTR_DOMAIN_POINT) { + return component.attribute_try_adapt_domain<float>( + std::move(lengths), ATTR_DOMAIN_CURVE, ATTR_DOMAIN_POINT); + } + + return {}; +} + +CurveLengthFieldInput::CurveLengthFieldInput() + : GeometryFieldInput(CPPType::get<float>(), "Spline Length node") +{ + category_ = Category::Generated; +} + +GVArray CurveLengthFieldInput::get_varray_for_context(const GeometryComponent &component, + const AttributeDomain domain, + IndexMask UNUSED(mask)) const +{ + if (component.type() == GEO_COMPONENT_TYPE_CURVE) { + const CurveComponent &curve_component = static_cast<const CurveComponent &>(component); + return construct_curve_length_gvarray(curve_component, domain); + } + return {}; +} + +uint64_t CurveLengthFieldInput::hash() const +{ + /* Some random constant hash. */ + return 3549623580; +} + +bool CurveLengthFieldInput::is_equal_to(const fn::FieldNode &other) const +{ + return dynamic_cast<const CurveLengthFieldInput *>(&other) != nullptr; +} /** \} */ +} // namespace blender::bke + /* -------------------------------------------------------------------- */ /** \name Attribute Access Helper Functions * \{ */ -int CurveComponent::attribute_domain_size(const AttributeDomain domain) const +int CurveComponent::attribute_domain_num(const AttributeDomain domain) const { if (curves_ == nullptr) { return 0; } - const blender::bke::CurvesGeometry &geometry = blender::bke::CurvesGeometry::wrap( + const blender::bke::CurvesGeometry &curves = blender::bke::CurvesGeometry::wrap( curves_->geometry); if (domain == ATTR_DOMAIN_POINT) { - return geometry.points_num(); + return curves.points_num(); } if (domain == ATTR_DOMAIN_CURVE) { - return geometry.curves_num(); + return curves.curves_num(); } return 0; } diff --git a/source/blender/blenkernel/intern/geometry_component_instances.cc b/source/blender/blenkernel/intern/geometry_component_instances.cc index 0dc6f486d28..e56a7ca4dd8 100644 --- a/source/blender/blenkernel/intern/geometry_component_instances.cc +++ b/source/blender/blenkernel/intern/geometry_component_instances.cc @@ -79,7 +79,7 @@ void InstancesComponent::add_instance(const int instance_handle, const float4x4 BLI_assert(instance_handle < references_.size()); instance_reference_handles_.append(instance_handle); instance_transforms_.append(transform); - attributes_.reallocate(this->instances_amount()); + attributes_.reallocate(this->instances_num()); } blender::Span<int> InstancesComponent::instance_reference_handles() const @@ -183,7 +183,7 @@ void InstancesComponent::remove_unused_references() using namespace blender; using namespace blender::bke; - const int tot_instances = this->instances_amount(); + const int tot_instances = this->instances_num(); const int tot_references_before = references_.size(); if (tot_instances == 0) { @@ -258,12 +258,12 @@ void InstancesComponent::remove_unused_references() }); } -int InstancesComponent::instances_amount() const +int InstancesComponent::instances_num() const { return instance_transforms_.size(); } -int InstancesComponent::references_amount() const +int InstancesComponent::references_num() const { return references_.size(); } @@ -358,7 +358,7 @@ blender::Span<int> InstancesComponent::almost_unique_ids() const } } else { - almost_unique_ids_.reinitialize(this->instances_amount()); + almost_unique_ids_.reinitialize(this->instances_num()); for (const int i : almost_unique_ids_.index_range()) { almost_unique_ids_[i] = i; } @@ -366,12 +366,12 @@ blender::Span<int> InstancesComponent::almost_unique_ids() const return almost_unique_ids_; } -int InstancesComponent::attribute_domain_size(const AttributeDomain domain) const +int InstancesComponent::attribute_domain_num(const AttributeDomain domain) const { if (domain != ATTR_DOMAIN_INSTANCE) { return 0; } - return this->instances_amount(); + return this->instances_num(); } blender::bke::CustomDataAttributes &InstancesComponent::attributes() diff --git a/source/blender/blenkernel/intern/geometry_component_mesh.cc b/source/blender/blenkernel/intern/geometry_component_mesh.cc index fb39861d3e7..5ac9a03f43c 100644 --- a/source/blender/blenkernel/intern/geometry_component_mesh.cc +++ b/source/blender/blenkernel/intern/geometry_component_mesh.cc @@ -169,7 +169,7 @@ VArray<float3> mesh_normals_varray(const MeshComponent &mesh_component, /** \name Attribute Access * \{ */ -int MeshComponent::attribute_domain_size(const AttributeDomain domain) const +int MeshComponent::attribute_domain_num(const AttributeDomain domain) const { if (mesh_ == nullptr) { return 0; @@ -839,20 +839,20 @@ static const Mesh *get_mesh_from_component_for_read(const GeometryComponent &com namespace blender::bke { template<typename StructT, typename ElemT, ElemT (*GetFunc)(const StructT &)> -static GVArray make_derived_read_attribute(const void *data, const int domain_size) +static GVArray make_derived_read_attribute(const void *data, const int domain_num) { return VArray<ElemT>::template ForDerivedSpan<StructT, GetFunc>( - Span<StructT>((const StructT *)data, domain_size)); + Span<StructT>((const StructT *)data, domain_num)); } template<typename StructT, typename ElemT, ElemT (*GetFunc)(const StructT &), void (*SetFunc)(StructT &, ElemT)> -static GVMutableArray make_derived_write_attribute(void *data, const int domain_size) +static GVMutableArray make_derived_write_attribute(void *data, const int domain_num) { return VMutableArray<ElemT>::template ForDerivedSpan<StructT, GetFunc, SetFunc>( - MutableSpan<StructT>((StructT *)data, domain_size)); + MutableSpan<StructT>((StructT *)data, domain_num)); } static float3 get_vertex_position(const MVert &vert) @@ -1160,7 +1160,7 @@ class NormalAttributeProvider final : public BuiltinAttributeProvider { bool exists(const GeometryComponent &component) const final { - return component.attribute_domain_size(ATTR_DOMAIN_FACE) != 0; + return component.attribute_domain_num(ATTR_DOMAIN_FACE) != 0; } }; diff --git a/source/blender/blenkernel/intern/geometry_component_pointcloud.cc b/source/blender/blenkernel/intern/geometry_component_pointcloud.cc index 400e0ea5e15..6de123c7cb9 100644 --- a/source/blender/blenkernel/intern/geometry_component_pointcloud.cc +++ b/source/blender/blenkernel/intern/geometry_component_pointcloud.cc @@ -104,7 +104,7 @@ void PointCloudComponent::ensure_owns_direct_data() /** \name Attribute Access * \{ */ -int PointCloudComponent::attribute_domain_size(const AttributeDomain domain) const +int PointCloudComponent::attribute_domain_num(const AttributeDomain domain) const { if (pointcloud_ == nullptr) { return 0; diff --git a/source/blender/blenkernel/intern/geometry_set.cc b/source/blender/blenkernel/intern/geometry_set.cc index 2bd8b643899..40e36ced199 100644 --- a/source/blender/blenkernel/intern/geometry_set.cc +++ b/source/blender/blenkernel/intern/geometry_set.cc @@ -272,7 +272,7 @@ bool GeometrySet::has_pointcloud() const bool GeometrySet::has_instances() const { const InstancesComponent *component = this->get_component_for_read<InstancesComponent>(); - return component != nullptr && component->instances_amount() >= 1; + return component != nullptr && component->instances_num() >= 1; } bool GeometrySet::has_volume() const diff --git a/source/blender/blenkernel/intern/gpencil.c b/source/blender/blenkernel/intern/gpencil.c index 699f8b356bd..f86e947910b 100644 --- a/source/blender/blenkernel/intern/gpencil.c +++ b/source/blender/blenkernel/intern/gpencil.c @@ -2803,7 +2803,7 @@ void BKE_gpencil_update_layer_transforms(const Depsgraph *depsgraph, Object *ob) /* Iterate over frame range. */ for (bGPDframe *gpf = gpf_start; gpf != NULL && gpf != gpf_end; gpf = gpf->next) { - /* Skip frames without a valid onion skinning id (note: active frame has one). */ + /* Skip frames without a valid onion skinning id (NOTE: active frame has one). */ if (gpf->runtime.onion_id == INT_MAX) { continue; } diff --git a/source/blender/blenkernel/intern/icons.cc b/source/blender/blenkernel/intern/icons.cc index 2ba6510ee71..f59f5352aad 100644 --- a/source/blender/blenkernel/intern/icons.cc +++ b/source/blender/blenkernel/intern/icons.cc @@ -114,32 +114,35 @@ static void icon_free(void *val) static void icon_free_data(int icon_id, Icon *icon) { - if (icon->obj_type == ICON_DATA_ID) { - ((ID *)(icon->obj))->icon_id = 0; - } - else if (icon->obj_type == ICON_DATA_IMBUF) { - ImBuf *imbuf = (ImBuf *)icon->obj; - if (imbuf) { - IMB_freeImBuf(imbuf); + switch (icon->obj_type) { + case ICON_DATA_ID: + ((ID *)(icon->obj))->icon_id = 0; + break; + case ICON_DATA_IMBUF: { + ImBuf *imbuf = (ImBuf *)icon->obj; + if (imbuf) { + IMB_freeImBuf(imbuf); + } + break; } - } - else if (icon->obj_type == ICON_DATA_PREVIEW) { - ((PreviewImage *)(icon->obj))->icon_id = 0; - } - else if (icon->obj_type == ICON_DATA_GPLAYER) { - ((bGPDlayer *)(icon->obj))->runtime.icon_id = 0; - } - else if (icon->obj_type == ICON_DATA_GEOM) { - ((struct Icon_Geom *)(icon->obj))->icon_id = 0; - } - else if (icon->obj_type == ICON_DATA_STUDIOLIGHT) { - StudioLight *sl = (StudioLight *)icon->obj; - if (sl != nullptr) { - BKE_studiolight_unset_icon_id(sl, icon_id); + case ICON_DATA_PREVIEW: + ((PreviewImage *)(icon->obj))->icon_id = 0; + break; + case ICON_DATA_GPLAYER: + ((bGPDlayer *)(icon->obj))->runtime.icon_id = 0; + break; + case ICON_DATA_GEOM: + ((struct Icon_Geom *)(icon->obj))->icon_id = 0; + break; + case ICON_DATA_STUDIOLIGHT: { + StudioLight *sl = (StudioLight *)icon->obj; + if (sl != nullptr) { + BKE_studiolight_unset_icon_id(sl, icon_id); + } + break; } - } - else { - BLI_assert(0); + default: + BLI_assert_unreachable(); } } @@ -241,16 +244,16 @@ static PreviewImage *previewimg_create_ex(size_t deferred_data_size) return prv_img; } -static PreviewImage *previewimg_deferred_create(const char *path, int source) +static PreviewImage *previewimg_deferred_create(const char *filepath, int source) { - /* We pack needed data for lazy loading (source type, in a single char, and path). */ - const size_t deferred_data_size = strlen(path) + 2; + /* We pack needed data for lazy loading (source type, in a single char, and filepath). */ + const size_t deferred_data_size = strlen(filepath) + 2; char *deferred_data; PreviewImage *prv = previewimg_create_ex(deferred_data_size); deferred_data = (char *)PRV_DEFERRED_DATA(prv); deferred_data[0] = source; - memcpy(&deferred_data[1], path, deferred_data_size - 1); + memcpy(&deferred_data[1], filepath, deferred_data_size - 1); return prv; } @@ -393,7 +396,7 @@ PreviewImage *BKE_previewimg_id_ensure(ID *id) return nullptr; } -void BKE_previewimg_id_custom_set(ID *id, const char *path) +void BKE_previewimg_id_custom_set(ID *id, const char *filepath) { PreviewImage **prv = BKE_previewimg_id_get_p(id); @@ -403,7 +406,7 @@ void BKE_previewimg_id_custom_set(ID *id, const char *path) if (*prv) { BKE_previewimg_deferred_release(*prv); } - *prv = previewimg_deferred_create(path, THB_SOURCE_IMAGE); + *prv = previewimg_deferred_create(filepath, THB_SOURCE_IMAGE); /* Can't lazy-render the preview on access. ID previews are saved to files and we want them to be * there in time. Not only if something happened to have accessed it meanwhile. */ @@ -458,7 +461,7 @@ PreviewImage *BKE_previewimg_cached_ensure(const char *name) } PreviewImage *BKE_previewimg_cached_thumbnail_read(const char *name, - const char *path, + const char *filepath, const int source, bool force_update) { @@ -476,8 +479,8 @@ PreviewImage *BKE_previewimg_cached_thumbnail_read(const char *name, if (prv && force_update) { const char *prv_deferred_data = (char *)PRV_DEFERRED_DATA(prv); - if (((int)prv_deferred_data[0] == source) && STREQ(&prv_deferred_data[1], path)) { - /* If same path, no need to re-allocate preview, just clear it up. */ + if (((int)prv_deferred_data[0] == source) && STREQ(&prv_deferred_data[1], filepath)) { + /* If same filepath, no need to re-allocate preview, just clear it up. */ BKE_previewimg_clear(prv); } else { @@ -486,7 +489,7 @@ PreviewImage *BKE_previewimg_cached_thumbnail_read(const char *name, } if (!prv) { - prv = previewimg_deferred_create(path, source); + prv = previewimg_deferred_create(filepath, source); force_update = true; } @@ -521,10 +524,10 @@ void BKE_previewimg_ensure(PreviewImage *prv, const int size) ImBuf *thumb; char *prv_deferred_data = (char *)PRV_DEFERRED_DATA(prv); int source = prv_deferred_data[0]; - char *path = &prv_deferred_data[1]; + char *filepath = &prv_deferred_data[1]; int icon_w, icon_h; - thumb = IMB_thumb_manage(path, THB_LARGE, (ThumbSource)source); + thumb = IMB_thumb_manage(filepath, THB_LARGE, (ThumbSource)source); if (thumb) { /* PreviewImage assumes premultiplied alhpa... */ diff --git a/source/blender/blenkernel/intern/idprop.c b/source/blender/blenkernel/intern/idprop.c index 7b8dfdc690c..e99230ef523 100644 --- a/source/blender/blenkernel/intern/idprop.c +++ b/source/blender/blenkernel/intern/idprop.c @@ -872,7 +872,7 @@ bool IDP_EqualsProperties_ex(IDProperty *prop1, IDProperty *prop2, const bool is case IDP_ID: return (IDP_Id(prop1) == IDP_Id(prop2)); default: - BLI_assert(0); + BLI_assert_unreachable(); break; } diff --git a/source/blender/blenkernel/intern/idprop_utils.c b/source/blender/blenkernel/intern/idprop_utils.c index 2ffa5125b1d..5b7484ab422 100644 --- a/source/blender/blenkernel/intern/idprop_utils.c +++ b/source/blender/blenkernel/intern/idprop_utils.c @@ -181,7 +181,7 @@ static void idp_repr_fn_recursive(struct ReprState *state, const IDProperty *pro break; } default: { - BLI_assert(0); + BLI_assert_unreachable(); break; } } diff --git a/source/blender/blenkernel/intern/image.cc b/source/blender/blenkernel/intern/image.cc index 4bf25c24235..06a5d877882 100644 --- a/source/blender/blenkernel/intern/image.cc +++ b/source/blender/blenkernel/intern/image.cc @@ -182,9 +182,7 @@ static void image_copy_data(Main *UNUSED(bmain), ID *id_dst, const ID *id_src, c for (int eye = 0; eye < 2; eye++) { for (int i = 0; i < TEXTARGET_COUNT; i++) { - for (int resolution = 0; resolution < IMA_TEXTURE_RESOLUTION_LEN; resolution++) { - image_dst->gputexture[i][eye][resolution] = nullptr; - } + image_dst->gputexture[i][eye] = nullptr; } } @@ -236,24 +234,21 @@ static void image_foreach_cache(ID *id, key.offset_in_ID = offsetof(Image, cache); function_callback(id, &key, (void **)&image->cache, 0, user_data); - auto gputexture_offset = [image](int target, int eye, int resolution) { + auto gputexture_offset = [image](int target, int eye) { constexpr size_t base_offset = offsetof(Image, gputexture); - struct GPUTexture **first = &image->gputexture[0][0][0]; - const size_t array_offset = sizeof(*first) * - (&image->gputexture[target][eye][resolution] - first); + struct GPUTexture **first = &image->gputexture[0][0]; + const size_t array_offset = sizeof(*first) * (&image->gputexture[target][eye] - first); return base_offset + array_offset; }; for (int eye = 0; eye < 2; eye++) { for (int a = 0; a < TEXTARGET_COUNT; a++) { - for (int resolution = 0; resolution < IMA_TEXTURE_RESOLUTION_LEN; resolution++) { - GPUTexture *texture = image->gputexture[a][eye][resolution]; - if (texture == nullptr) { - continue; - } - key.offset_in_ID = gputexture_offset(a, eye, resolution); - function_callback(id, &key, (void **)&image->gputexture[a][eye][resolution], 0, user_data); + GPUTexture *texture = image->gputexture[a][eye]; + if (texture == nullptr) { + continue; } + key.offset_in_ID = gputexture_offset(a, eye); + function_callback(id, &key, (void **)&image->gputexture[a][eye], 0, user_data); } } @@ -335,9 +330,7 @@ static void image_blend_write(BlendWriter *writer, ID *id, const void *id_addres ima->runtime.partial_update_user = nullptr; for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { - for (int resolution = 0; resolution < IMA_TEXTURE_RESOLUTION_LEN; resolution++) { - ima->gputexture[i][j][resolution] = nullptr; - } + ima->gputexture[i][j] = nullptr; } } @@ -721,6 +714,9 @@ static void copy_image_packedfiles(ListBase *lb_dst, const ListBase *lb_src) imapf_src = imapf_src->next) { ImagePackedFile *imapf_dst = static_cast<ImagePackedFile *>( MEM_mallocN(sizeof(ImagePackedFile), "Image Packed Files (copy)")); + + imapf_dst->view = imapf_src->view; + imapf_dst->tile_number = imapf_src->tile_number; STRNCPY(imapf_dst->filepath, imapf_src->filepath); if (imapf_src->packedfile) { @@ -781,10 +777,8 @@ bool BKE_image_has_opengl_texture(Image *ima) { for (int eye = 0; eye < 2; eye++) { for (int i = 0; i < TEXTARGET_COUNT; i++) { - for (int resolution = 0; resolution < IMA_TEXTURE_RESOLUTION_LEN; resolution++) { - if (ima->gputexture[i][eye][resolution] != nullptr) { - return true; - } + if (ima->gputexture[i][eye] != nullptr) { + return true; } } } @@ -1197,7 +1191,8 @@ Image *BKE_image_add_from_imbuf(Main *bmain, ImBuf *ibuf, const char *name) } /** Pack image buffer to memory as PNG or EXR. */ -static bool image_memorypack_imbuf(Image *ima, ImBuf *ibuf, const char *filepath) +static bool image_memorypack_imbuf( + Image *ima, ImBuf *ibuf, int view, int tile_number, const char *filepath) { ibuf->ftype = (ibuf->rect_float) ? IMB_FTYPE_OPENEXR : IMB_FTYPE_PNG; @@ -1219,6 +1214,8 @@ static bool image_memorypack_imbuf(Image *ima, ImBuf *ibuf, const char *filepath imapf = static_cast<ImagePackedFile *>(MEM_mallocN(sizeof(ImagePackedFile), "Image PackedFile")); STRNCPY(imapf->filepath, filepath); imapf->packedfile = pf; + imapf->view = view; + imapf->tile_number = tile_number; BLI_addtail(&ima->packedfiles, imapf); ibuf->encodedbuffer = nullptr; @@ -1234,42 +1231,47 @@ bool BKE_image_memorypack(Image *ima) image_free_packedfiles(ima); - if (BKE_image_is_multiview(ima)) { - /* Store each view as a separate packed files with R_IMF_VIEWS_INDIVIDUAL. */ - ImageView *iv; - int i; + const int tot_viewfiles = image_num_viewfiles(ima); + const bool is_tiled = (ima->source == IMA_SRC_TILED); + const bool is_multiview = BKE_image_is_multiview(ima); - for (i = 0, iv = static_cast<ImageView *>(ima->views.first); iv; - iv = static_cast<ImageView *>(iv->next), i++) { - ImBuf *ibuf = image_get_cached_ibuf_for_index_entry(ima, i, 0, nullptr); + ImageUser iuser{}; + BKE_imageuser_default(&iuser); + char tiled_filepath[FILE_MAX]; + for (int view = 0; view < tot_viewfiles; view++) { + LISTBASE_FOREACH (ImageTile *, tile, &ima->tiles) { + int index = (is_multiview || is_tiled) ? view : IMA_NO_INDEX; + int entry = is_tiled ? tile->tile_number : 0; + ImBuf *ibuf = image_get_cached_ibuf_for_index_entry(ima, index, entry, nullptr); if (!ibuf) { ok = false; break; } - /* if the image was a R_IMF_VIEWS_STEREO_3D we force _L, _R suffices */ - if (ima->views_format == R_IMF_VIEWS_STEREO_3D) { - const char *suffix[2] = {STEREO_LEFT_SUFFIX, STEREO_RIGHT_SUFFIX}; - BLI_path_suffix(iv->filepath, FILE_MAX, suffix[i], ""); + const char *filepath = ibuf->name; + if (is_tiled) { + iuser.tile = tile->tile_number; + BKE_image_user_file_path(&iuser, ima, tiled_filepath); + filepath = tiled_filepath; + } + else if (is_multiview) { + ImageView *iv = static_cast<ImageView *>(BLI_findlink(&ima->views, view)); + /* if the image was a R_IMF_VIEWS_STEREO_3D we force _L, _R suffices */ + if (ima->views_format == R_IMF_VIEWS_STEREO_3D) { + const char *suffix[2] = {STEREO_LEFT_SUFFIX, STEREO_RIGHT_SUFFIX}; + BLI_path_suffix(iv->filepath, FILE_MAX, suffix[view], ""); + } + filepath = iv->filepath; } - ok = ok && image_memorypack_imbuf(ima, ibuf, iv->filepath); + ok = ok && image_memorypack_imbuf(ima, ibuf, view, tile->tile_number, filepath); IMB_freeImBuf(ibuf); } - - ima->views_format = R_IMF_VIEWS_INDIVIDUAL; } - else { - ImBuf *ibuf = image_get_cached_ibuf_for_index_entry(ima, IMA_NO_INDEX, 0, nullptr); - if (ibuf) { - ok = ok && image_memorypack_imbuf(ima, ibuf, ibuf->name); - IMB_freeImBuf(ibuf); - } - else { - ok = false; - } + if (is_multiview) { + ima->views_format = R_IMF_VIEWS_INDIVIDUAL; } if (ok && ima->source == IMA_SRC_GENERATED) { @@ -1284,27 +1286,24 @@ void BKE_image_packfiles(ReportList *reports, Image *ima, const char *basepath) { const int tot_viewfiles = image_num_viewfiles(ima); - if (tot_viewfiles == 1) { - ImagePackedFile *imapf = static_cast<ImagePackedFile *>( - MEM_mallocN(sizeof(ImagePackedFile), "Image packed file")); - BLI_addtail(&ima->packedfiles, imapf); - imapf->packedfile = BKE_packedfile_new(reports, ima->filepath, basepath); - if (imapf->packedfile) { - STRNCPY(imapf->filepath, ima->filepath); - } - else { - BLI_freelinkN(&ima->packedfiles, imapf); - } - } - else { - for (ImageView *iv = static_cast<ImageView *>(ima->views.first); iv; iv = iv->next) { + ImageUser iuser{}; + BKE_imageuser_default(&iuser); + for (int view = 0; view < tot_viewfiles; view++) { + iuser.view = view; + LISTBASE_FOREACH (ImageTile *, tile, &ima->tiles) { + iuser.tile = tile->tile_number; + char filepath[FILE_MAX]; + BKE_image_user_file_path(&iuser, ima, filepath); + ImagePackedFile *imapf = static_cast<ImagePackedFile *>( MEM_mallocN(sizeof(ImagePackedFile), "Image packed file")); BLI_addtail(&ima->packedfiles, imapf); - imapf->packedfile = BKE_packedfile_new(reports, iv->filepath, basepath); + imapf->packedfile = BKE_packedfile_new(reports, filepath, basepath); + imapf->view = view; + imapf->tile_number = tile->tile_number; if (imapf->packedfile) { - STRNCPY(imapf->filepath, iv->filepath); + STRNCPY(imapf->filepath, filepath); } else { BLI_freelinkN(&ima->packedfiles, imapf); @@ -1323,11 +1322,16 @@ void BKE_image_packfiles_from_mem(ReportList *reports, if (tot_viewfiles != 1) { BKE_report(reports, RPT_ERROR, "Cannot pack multiview images from raw data currently..."); } + else if (ima->source == IMA_SRC_TILED) { + BKE_report(reports, RPT_ERROR, "Cannot pack tiled images from raw data currently..."); + } else { ImagePackedFile *imapf = static_cast<ImagePackedFile *>( MEM_mallocN(sizeof(ImagePackedFile), __func__)); BLI_addtail(&ima->packedfiles, imapf); imapf->packedfile = BKE_packedfile_new_from_memory(data, data_len); + imapf->view = 0; + imapf->tile_number = 1001; STRNCPY(imapf->filepath, ima->filepath); } } @@ -2851,11 +2855,9 @@ static void image_free_tile(Image *ima, ImageTile *tile) } for (int eye = 0; eye < 2; eye++) { - for (int resolution = 0; resolution < IMA_TEXTURE_RESOLUTION_LEN; resolution++) { - if (ima->gputexture[i][eye][resolution] != nullptr) { - GPU_texture_free(ima->gputexture[i][eye][resolution]); - ima->gputexture[i][eye][resolution] = nullptr; - } + if (ima->gputexture[i][eye] != nullptr) { + GPU_texture_free(ima->gputexture[i][eye]); + ima->gputexture[i][eye] = nullptr; } } } @@ -2951,8 +2953,9 @@ void BKE_image_signal(Main *bmain, Image *ima, ImageUser *iuser, int signal) /* try to repack file */ if (BKE_image_has_packedfile(ima)) { const int tot_viewfiles = image_num_viewfiles(ima); + const int tot_files = tot_viewfiles * BLI_listbase_count(&ima->tiles); - if (tot_viewfiles != BLI_listbase_count_at_most(&ima->packedfiles, tot_viewfiles + 1)) { + if (tot_files != BLI_listbase_count_at_most(&ima->packedfiles, tot_files + 1)) { /* in case there are new available files to be loaded */ image_free_packedfiles(ima); BKE_image_packfiles(nullptr, ima, ID_BLEND_PATH(bmain, &ima->id)); @@ -3194,16 +3197,14 @@ ImageTile *BKE_image_add_tile(struct Image *ima, int tile_number, const char *la } for (int eye = 0; eye < 2; eye++) { - for (int resolution = 0; resolution < IMA_TEXTURE_RESOLUTION_LEN; resolution++) { - /* Reallocate GPU tile array. */ - if (ima->gputexture[TEXTARGET_2D_ARRAY][eye][resolution] != nullptr) { - GPU_texture_free(ima->gputexture[TEXTARGET_2D_ARRAY][eye][resolution]); - ima->gputexture[TEXTARGET_2D_ARRAY][eye][resolution] = nullptr; - } - if (ima->gputexture[TEXTARGET_TILE_MAPPING][eye][resolution] != nullptr) { - GPU_texture_free(ima->gputexture[TEXTARGET_TILE_MAPPING][eye][resolution]); - ima->gputexture[TEXTARGET_TILE_MAPPING][eye][resolution] = nullptr; - } + /* Reallocate GPU tile array. */ + if (ima->gputexture[TEXTARGET_2D_ARRAY][eye] != nullptr) { + GPU_texture_free(ima->gputexture[TEXTARGET_2D_ARRAY][eye]); + ima->gputexture[TEXTARGET_2D_ARRAY][eye] = nullptr; + } + if (ima->gputexture[TEXTARGET_TILE_MAPPING][eye] != nullptr) { + GPU_texture_free(ima->gputexture[TEXTARGET_TILE_MAPPING][eye]); + ima->gputexture[TEXTARGET_TILE_MAPPING][eye] = nullptr; } } BKE_image_partial_update_mark_full_update(ima); @@ -3259,17 +3260,14 @@ void BKE_image_reassign_tile(struct Image *ima, ImageTile *tile, int new_tile_nu } for (int eye = 0; eye < 2; eye++) { - for (int resolution = 0; resolution < IMA_TEXTURE_RESOLUTION_LEN; resolution++) { - - /* Reallocate GPU tile array. */ - if (ima->gputexture[TEXTARGET_2D_ARRAY][eye][resolution] != nullptr) { - GPU_texture_free(ima->gputexture[TEXTARGET_2D_ARRAY][eye][resolution]); - ima->gputexture[TEXTARGET_2D_ARRAY][eye][resolution] = nullptr; - } - if (ima->gputexture[TEXTARGET_TILE_MAPPING][eye][resolution] != nullptr) { - GPU_texture_free(ima->gputexture[TEXTARGET_TILE_MAPPING][eye][resolution]); - ima->gputexture[TEXTARGET_TILE_MAPPING][eye][resolution] = nullptr; - } + /* Reallocate GPU tile array. */ + if (ima->gputexture[TEXTARGET_2D_ARRAY][eye] != nullptr) { + GPU_texture_free(ima->gputexture[TEXTARGET_2D_ARRAY][eye]); + ima->gputexture[TEXTARGET_2D_ARRAY][eye] = nullptr; + } + if (ima->gputexture[TEXTARGET_TILE_MAPPING][eye] != nullptr) { + GPU_texture_free(ima->gputexture[TEXTARGET_TILE_MAPPING][eye]); + ima->gputexture[TEXTARGET_TILE_MAPPING][eye] = nullptr; } } BKE_image_partial_update_mark_full_update(ima); @@ -3931,18 +3929,23 @@ static ImBuf *load_image_single(Image *ima, int flag = IB_rect | IB_multilayer; *r_cache_ibuf = true; + const int tile_number = image_get_tile_number_from_iuser(ima, iuser); /* is there a PackedFile with this image ? */ if (has_packed && !is_sequence) { - ImagePackedFile *imapf = static_cast<ImagePackedFile *>( - BLI_findlink(&ima->packedfiles, view_id)); - if (imapf->packedfile) { - flag |= imbuf_alpha_flags_for_image(ima); - ibuf = IMB_ibImageFromMemory((unsigned char *)imapf->packedfile->data, - imapf->packedfile->size, - flag, - ima->colorspace_settings.name, - "<packed data>"); + flag |= imbuf_alpha_flags_for_image(ima); + + LISTBASE_FOREACH (ImagePackedFile *, imapf, &ima->packedfiles) { + if (imapf->view == view_id && imapf->tile_number == tile_number) { + if (imapf->packedfile) { + ibuf = IMB_ibImageFromMemory((unsigned char *)imapf->packedfile->data, + imapf->packedfile->size, + flag, + ima->colorspace_settings.name, + "<packed data>"); + } + break; + } } } else { @@ -4001,6 +4004,8 @@ static ImBuf *load_image_single(Image *ima, BLI_addtail(&ima->packedfiles, imapf); STRNCPY(imapf->filepath, filepath); + imapf->view = view_id; + imapf->tile_number = tile_number; imapf->packedfile = BKE_packedfile_new( nullptr, filepath, ID_BLEND_PATH_FROM_GLOBAL(&ima->id)); } @@ -5108,7 +5113,7 @@ bool BKE_image_has_packedfile(const Image *ima) return (BLI_listbase_is_empty(&ima->packedfiles) == false); } -bool BKE_image_has_filepath(Image *ima) +bool BKE_image_has_filepath(const Image *ima) { /* This could be improved to detect cases like //../../, currently path * remapping empty file paths empty. */ diff --git a/source/blender/blenkernel/intern/image_format.cc b/source/blender/blenkernel/intern/image_format.cc index 30be1fdaba7..57763e1670f 100644 --- a/source/blender/blenkernel/intern/image_format.cc +++ b/source/blender/blenkernel/intern/image_format.cc @@ -911,6 +911,11 @@ void BKE_image_format_from_imbuf(ImageFormatData *im_format, const ImBuf *imbuf) im_format->planes = imbuf->planes; } +bool BKE_image_format_is_byte(const ImageFormatData *imf) +{ + return (imf->depth == R_IMF_CHAN_DEPTH_8) && (BKE_imtype_valid_depths(imf->imtype) & imf->depth); +} + /* Color Management */ void BKE_image_format_color_management_copy(ImageFormatData *imf, const ImageFormatData *imf_src) diff --git a/source/blender/blenkernel/intern/image_gpu.cc b/source/blender/blenkernel/intern/image_gpu.cc index 0d470c5b663..bed79a318e8 100644 --- a/source/blender/blenkernel/intern/image_gpu.cc +++ b/source/blender/blenkernel/intern/image_gpu.cc @@ -38,7 +38,6 @@ extern "C" { /* Prototypes. */ static void gpu_free_unused_buffers(); static void image_free_gpu(Image *ima, const bool immediate); -static void image_free_gpu_limited_scale(Image *ima); static void image_update_gputexture_ex( Image *ima, ImageTile *tile, ImBuf *ibuf, int x, int y, int w, int h); @@ -68,22 +67,19 @@ bool BKE_image_has_gpu_texture_premultiplied_alpha(Image *image, ImBuf *ibuf) /** \name UDIM GPU Texture * \{ */ -static bool is_over_resolution_limit(int w, int h, bool limit_gl_texture_size) +static bool is_over_resolution_limit(int w, int h) { - return (w > GPU_texture_size_with_limit(w, limit_gl_texture_size) || - h > GPU_texture_size_with_limit(h, limit_gl_texture_size)); + return (w > GPU_texture_size_with_limit(w) || h > GPU_texture_size_with_limit(h)); } -static int smaller_power_of_2_limit(int num, bool limit_gl_texture_size) +static int smaller_power_of_2_limit(int num) { - return power_of_2_min_i(GPU_texture_size_with_limit(num, limit_gl_texture_size)); + return power_of_2_min_i(GPU_texture_size_with_limit(num)); } -static GPUTexture *gpu_texture_create_tile_mapping( - Image *ima, const int multiview_eye, const eImageTextureResolution texture_resolution) +static GPUTexture *gpu_texture_create_tile_mapping(Image *ima, const int multiview_eye) { - const int resolution = (texture_resolution == IMA_TEXTURE_RESOLUTION_LIMITED) ? 1 : 0; - GPUTexture *tilearray = ima->gputexture[TEXTARGET_2D_ARRAY][multiview_eye][resolution]; + GPUTexture *tilearray = ima->gputexture[TEXTARGET_2D_ARRAY][multiview_eye]; if (tilearray == nullptr) { return nullptr; @@ -105,7 +101,7 @@ static GPUTexture *gpu_texture_create_tile_mapping( } LISTBASE_FOREACH (ImageTile *, tile, &ima->tiles) { int i = tile->tile_number - 1001; - ImageTile_RuntimeTextureSlot *tile_runtime = &tile->runtime.slots[resolution]; + ImageTile_Runtime *tile_runtime = &tile->runtime; data[4 * i] = tile_runtime->tilearray_layer; float *tile_info = &data[4 * width + 4 * i]; @@ -137,12 +133,8 @@ static int compare_packtile(const void *a, const void *b) return tile_a->pack_score < tile_b->pack_score; } -static GPUTexture *gpu_texture_create_tile_array(Image *ima, - ImBuf *main_ibuf, - const eImageTextureResolution texture_resolution) +static GPUTexture *gpu_texture_create_tile_array(Image *ima, ImBuf *main_ibuf) { - const bool limit_gl_texture_size = texture_resolution == IMA_TEXTURE_RESOLUTION_LIMITED; - const int resolution = texture_resolution == IMA_TEXTURE_RESOLUTION_LIMITED ? 1 : 0; int arraywidth = 0, arrayheight = 0; ListBase boxes = {nullptr}; @@ -158,10 +150,9 @@ static GPUTexture *gpu_texture_create_tile_array(Image *ima, packtile->boxpack.w = ibuf->x; packtile->boxpack.h = ibuf->y; - if (is_over_resolution_limit( - packtile->boxpack.w, packtile->boxpack.h, limit_gl_texture_size)) { - packtile->boxpack.w = smaller_power_of_2_limit(packtile->boxpack.w, limit_gl_texture_size); - packtile->boxpack.h = smaller_power_of_2_limit(packtile->boxpack.h, limit_gl_texture_size); + if (is_over_resolution_limit(packtile->boxpack.w, packtile->boxpack.h)) { + packtile->boxpack.w = smaller_power_of_2_limit(packtile->boxpack.w); + packtile->boxpack.h = smaller_power_of_2_limit(packtile->boxpack.h); } arraywidth = max_ii(arraywidth, packtile->boxpack.w); arrayheight = max_ii(arrayheight, packtile->boxpack.h); @@ -188,7 +179,7 @@ static GPUTexture *gpu_texture_create_tile_array(Image *ima, LISTBASE_FOREACH (PackTile *, packtile, &packed) { ImageTile *tile = packtile->tile; - ImageTile_RuntimeTextureSlot *tile_runtime = &tile->runtime.slots[resolution]; + ImageTile_Runtime *tile_runtime = &tile->runtime; int *tileoffset = tile_runtime->tilearray_offset; int *tilesize = tile_runtime->tilearray_size; @@ -210,7 +201,7 @@ static GPUTexture *gpu_texture_create_tile_array(Image *ima, /* Upload each tile one by one. */ LISTBASE_FOREACH (ImageTile *, tile, &ima->tiles) { - ImageTile_RuntimeTextureSlot *tile_runtime = &tile->runtime.slots[resolution]; + ImageTile_Runtime *tile_runtime = &tile->runtime; int tilelayer = tile_runtime->tilearray_layer; int *tileoffset = tile_runtime->tilearray_offset; int *tilesize = tile_runtime->tilearray_size; @@ -258,33 +249,16 @@ static GPUTexture *gpu_texture_create_tile_array(Image *ima, /** \name Regular gpu texture * \{ */ -static bool image_max_resolution_texture_fits_in_limited_scale(Image *ima, - eGPUTextureTarget textarget, - const int multiview_eye) -{ - BLI_assert_msg(U.glreslimit != 0, - "limited scale function called without limited scale being set."); - GPUTexture *max_resolution_texture = - ima->gputexture[textarget][multiview_eye][IMA_TEXTURE_RESOLUTION_FULL]; - if (max_resolution_texture && GPU_texture_width(max_resolution_texture) <= U.glreslimit && - GPU_texture_height(max_resolution_texture) <= U.glreslimit) { - return true; - } - return false; -} - static GPUTexture **get_image_gpu_texture_ptr(Image *ima, eGPUTextureTarget textarget, - const int multiview_eye, - const eImageTextureResolution texture_resolution) + const int multiview_eye) { const bool in_range = (textarget >= 0) && (textarget < TEXTARGET_COUNT); BLI_assert(in_range); BLI_assert(ELEM(multiview_eye, 0, 1)); - const int resolution = (texture_resolution == IMA_TEXTURE_RESOLUTION_LIMITED) ? 1 : 0; if (in_range) { - return &(ima->gputexture[textarget][multiview_eye][resolution]); + return &(ima->gputexture[textarget][multiview_eye]); } return nullptr; } @@ -303,21 +277,6 @@ static GPUTexture *image_gpu_texture_error_create(eGPUTextureTarget textarget) } } -static void image_update_reusable_textures(Image *ima, - eGPUTextureTarget textarget, - const int multiview_eye) -{ - if ((ima->gpuflag & IMA_GPU_HAS_LIMITED_SCALE_TEXTURES) == 0) { - return; - } - - if (ELEM(textarget, TEXTARGET_2D, TEXTARGET_2D_ARRAY)) { - if (image_max_resolution_texture_fits_in_limited_scale(ima, textarget, multiview_eye)) { - image_free_gpu_limited_scale(ima); - } - } -} - static void image_gpu_texture_partial_update_changes_available( Image *image, PartialUpdateChecker<ImageTileData>::CollectResult &changes) { @@ -412,14 +371,7 @@ static GPUTexture *image_get_gpu_texture(Image *ima, if (current_view >= 2) { current_view = 0; } - const bool limit_resolution = U.glreslimit != 0 && - ((iuser && (iuser->flag & IMA_SHOW_MAX_RESOLUTION) == 0) || - (iuser == nullptr)) && - ((ima->gpuflag & IMA_GPU_REUSE_MAX_RESOLUTION) == 0); - const eImageTextureResolution texture_resolution = limit_resolution ? - IMA_TEXTURE_RESOLUTION_LIMITED : - IMA_TEXTURE_RESOLUTION_FULL; - GPUTexture **tex = get_image_gpu_texture_ptr(ima, textarget, current_view, texture_resolution); + GPUTexture **tex = get_image_gpu_texture_ptr(ima, textarget, current_view); if (*tex) { return *tex; } @@ -443,11 +395,10 @@ static GPUTexture *image_get_gpu_texture(Image *ima, } if (textarget == TEXTARGET_2D_ARRAY) { - *tex = gpu_texture_create_tile_array(ima, ibuf_intern, texture_resolution); + *tex = gpu_texture_create_tile_array(ima, ibuf_intern); } else if (textarget == TEXTARGET_TILE_MAPPING) { - *tex = gpu_texture_create_tile_mapping( - ima, iuser ? iuser->multiview_eye : 0, texture_resolution); + *tex = gpu_texture_create_tile_mapping(ima, iuser ? iuser->multiview_eye : 0); } else { const bool use_high_bitdepth = (ima->flag & IMA_HIGH_BITDEPTH); @@ -455,7 +406,7 @@ static GPUTexture *image_get_gpu_texture(Image *ima, ibuf_intern); *tex = IMB_create_gpu_texture( - ima->id.name + 2, ibuf_intern, use_high_bitdepth, store_premultiplied, limit_resolution); + ima->id.name + 2, ibuf_intern, use_high_bitdepth, store_premultiplied); if (*tex) { GPU_texture_wrap_mode(*tex, true, false); @@ -473,20 +424,6 @@ static GPUTexture *image_get_gpu_texture(Image *ima, } } - switch (texture_resolution) { - case IMA_TEXTURE_RESOLUTION_LIMITED: - ima->gpuflag |= IMA_GPU_HAS_LIMITED_SCALE_TEXTURES; - break; - - case IMA_TEXTURE_RESOLUTION_FULL: - image_update_reusable_textures(ima, textarget, current_view); - break; - - case IMA_TEXTURE_RESOLUTION_LEN: - BLI_assert_unreachable(); - break; - } - if (*tex) { GPU_texture_orig_size_set(*tex, ibuf_intern->x, ibuf_intern->y); } @@ -558,39 +495,22 @@ static void image_free_gpu(Image *ima, const bool immediate) { for (int eye = 0; eye < 2; eye++) { for (int i = 0; i < TEXTARGET_COUNT; i++) { - for (int resolution = 0; resolution < IMA_TEXTURE_RESOLUTION_LEN; resolution++) { - if (ima->gputexture[i][eye][resolution] != nullptr) { - if (immediate) { - GPU_texture_free(ima->gputexture[i][eye][resolution]); - } - else { - BLI_mutex_lock(&gpu_texture_queue_mutex); - BLI_linklist_prepend(&gpu_texture_free_queue, ima->gputexture[i][eye][resolution]); - BLI_mutex_unlock(&gpu_texture_queue_mutex); - } - - ima->gputexture[i][eye][resolution] = nullptr; + if (ima->gputexture[i][eye] != nullptr) { + if (immediate) { + GPU_texture_free(ima->gputexture[i][eye]); + } + else { + BLI_mutex_lock(&gpu_texture_queue_mutex); + BLI_linklist_prepend(&gpu_texture_free_queue, ima->gputexture[i][eye]); + BLI_mutex_unlock(&gpu_texture_queue_mutex); } - } - } - } - - ima->gpuflag &= ~(IMA_GPU_MIPMAP_COMPLETE | IMA_GPU_HAS_LIMITED_SCALE_TEXTURES); -} -static void image_free_gpu_limited_scale(Image *ima) -{ - const eImageTextureResolution resolution = IMA_TEXTURE_RESOLUTION_LIMITED; - for (int eye = 0; eye < 2; eye++) { - for (int i = 0; i < TEXTARGET_COUNT; i++) { - if (ima->gputexture[i][eye][resolution] != nullptr) { - GPU_texture_free(ima->gputexture[i][eye][resolution]); - ima->gputexture[i][eye][resolution] = nullptr; + ima->gputexture[i][eye] = nullptr; } } } - ima->gpuflag &= ~(IMA_GPU_MIPMAP_COMPLETE | IMA_GPU_HAS_LIMITED_SCALE_TEXTURES); + ima->gpuflag &= ~IMA_GPU_MIPMAP_COMPLETE; } void BKE_image_free_gputextures(Image *ima) @@ -767,20 +687,12 @@ static void gpu_texture_update_unscaled(GPUTexture *tex, GPU_unpack_row_length_set(0); } -static void gpu_texture_update_from_ibuf(GPUTexture *tex, - Image *ima, - ImBuf *ibuf, - ImageTile *tile, - int x, - int y, - int w, - int h, - eImageTextureResolution texture_resolution) +static void gpu_texture_update_from_ibuf( + GPUTexture *tex, Image *ima, ImBuf *ibuf, ImageTile *tile, int x, int y, int w, int h) { - const int resolution = texture_resolution == IMA_TEXTURE_RESOLUTION_LIMITED ? 1 : 0; bool scaled; if (tile != nullptr) { - ImageTile_RuntimeTextureSlot *tile_runtime = &tile->runtime.slots[resolution]; + ImageTile_Runtime *tile_runtime = &tile->runtime; int *tilesize = tile_runtime->tilearray_size; scaled = (ibuf->x != tilesize[0]) || (ibuf->y != tilesize[1]); } @@ -845,7 +757,7 @@ static void gpu_texture_update_from_ibuf(GPUTexture *tex, if (scaled) { /* Slower update where we first have to scale the input pixels. */ if (tile != nullptr) { - ImageTile_RuntimeTextureSlot *tile_runtime = &tile->runtime.slots[resolution]; + ImageTile_Runtime *tile_runtime = &tile->runtime; int *tileoffset = tile_runtime->tilearray_offset; int *tilesize = tile_runtime->tilearray_size; int tilelayer = tile_runtime->tilearray_layer; @@ -860,7 +772,7 @@ static void gpu_texture_update_from_ibuf(GPUTexture *tex, else { /* Fast update at same resolution. */ if (tile != nullptr) { - ImageTile_RuntimeTextureSlot *tile_runtime = &tile->runtime.slots[resolution]; + ImageTile_Runtime *tile_runtime = &tile->runtime; int *tileoffset = tile_runtime->tilearray_offset; int tilelayer = tile_runtime->tilearray_layer; gpu_texture_update_unscaled( @@ -894,19 +806,16 @@ static void image_update_gputexture_ex( Image *ima, ImageTile *tile, ImBuf *ibuf, int x, int y, int w, int h) { const int eye = 0; - for (int resolution = 0; resolution < IMA_TEXTURE_RESOLUTION_LEN; resolution++) { - GPUTexture *tex = ima->gputexture[TEXTARGET_2D][eye][resolution]; - eImageTextureResolution texture_resolution = static_cast<eImageTextureResolution>(resolution); - /* Check if we need to update the main gputexture. */ - if (tex != nullptr && tile == ima->tiles.first) { - gpu_texture_update_from_ibuf(tex, ima, ibuf, nullptr, x, y, w, h, texture_resolution); - } + GPUTexture *tex = ima->gputexture[TEXTARGET_2D][eye]; + /* Check if we need to update the main gputexture. */ + if (tex != nullptr && tile == ima->tiles.first) { + gpu_texture_update_from_ibuf(tex, ima, ibuf, nullptr, x, y, w, h); + } - /* Check if we need to update the array gputexture. */ - tex = ima->gputexture[TEXTARGET_2D_ARRAY][eye][resolution]; - if (tex != nullptr) { - gpu_texture_update_from_ibuf(tex, ima, ibuf, tile, x, y, w, h, texture_resolution); - } + /* Check if we need to update the array gputexture. */ + tex = ima->gputexture[TEXTARGET_2D_ARRAY][eye]; + if (tex != nullptr) { + gpu_texture_update_from_ibuf(tex, ima, ibuf, tile, x, y, w, h); } } @@ -946,11 +855,9 @@ void BKE_image_paint_set_mipmap(Main *bmain, bool mipmap) for (int a = 0; a < TEXTARGET_COUNT; a++) { if (ELEM(a, TEXTARGET_2D, TEXTARGET_2D_ARRAY)) { for (int eye = 0; eye < 2; eye++) { - for (int resolution = 0; resolution < IMA_TEXTURE_RESOLUTION_LEN; resolution++) { - GPUTexture *tex = ima->gputexture[a][eye][resolution]; - if (tex != nullptr) { - GPU_texture_mipmap_mode(tex, mipmap, true); - } + GPUTexture *tex = ima->gputexture[a][eye]; + if (tex != nullptr) { + GPU_texture_mipmap_mode(tex, mipmap, true); } } } diff --git a/source/blender/blenkernel/intern/image_save.cc b/source/blender/blenkernel/intern/image_save.cc index 5361f234a63..6bfdaf9b522 100644 --- a/source/blender/blenkernel/intern/image_save.cc +++ b/source/blender/blenkernel/intern/image_save.cc @@ -23,6 +23,7 @@ #include "IMB_openexr.h" #include "BKE_colortools.h" +#include "BKE_global.h" #include "BKE_image.h" #include "BKE_image_format.h" #include "BKE_image_save.h" @@ -34,14 +35,217 @@ using blender::Vector; -void BKE_image_save_options_init(ImageSaveOptions *opts, Main *bmain, Scene *scene) +static char imtype_best_depth(ImBuf *ibuf, const char imtype) { + const char depth_ok = BKE_imtype_valid_depths(imtype); + + if (ibuf->rect_float) { + if (depth_ok & R_IMF_CHAN_DEPTH_32) { + return R_IMF_CHAN_DEPTH_32; + } + if (depth_ok & R_IMF_CHAN_DEPTH_24) { + return R_IMF_CHAN_DEPTH_24; + } + if (depth_ok & R_IMF_CHAN_DEPTH_16) { + return R_IMF_CHAN_DEPTH_16; + } + if (depth_ok & R_IMF_CHAN_DEPTH_12) { + return R_IMF_CHAN_DEPTH_12; + } + return R_IMF_CHAN_DEPTH_8; + } + + if (depth_ok & R_IMF_CHAN_DEPTH_8) { + return R_IMF_CHAN_DEPTH_8; + } + if (depth_ok & R_IMF_CHAN_DEPTH_12) { + return R_IMF_CHAN_DEPTH_12; + } + if (depth_ok & R_IMF_CHAN_DEPTH_16) { + return R_IMF_CHAN_DEPTH_16; + } + if (depth_ok & R_IMF_CHAN_DEPTH_24) { + return R_IMF_CHAN_DEPTH_24; + } + if (depth_ok & R_IMF_CHAN_DEPTH_32) { + return R_IMF_CHAN_DEPTH_32; + } + return R_IMF_CHAN_DEPTH_8; /* fallback, should not get here */ +} + +bool BKE_image_save_options_init(ImageSaveOptions *opts, + Main *bmain, + Scene *scene, + Image *ima, + ImageUser *iuser, + const bool guess_path, + const bool save_as_render) +{ + /* For saving a tiled image we need an iuser, so use a local one if there isn't already one. */ + ImageUser save_iuser; + if (iuser == nullptr) { + BKE_imageuser_default(&save_iuser); + iuser = &save_iuser; + iuser->scene = scene; + } + memset(opts, 0, sizeof(*opts)); opts->bmain = bmain; opts->scene = scene; + opts->save_as_render = ima->source == IMA_SRC_VIEWER || save_as_render; BKE_image_format_init(&opts->im_format, false); + + void *lock; + ImBuf *ibuf = BKE_image_acquire_ibuf(ima, iuser, &lock); + + if (ibuf) { + Scene *scene = opts->scene; + bool is_depth_set = false; + const char *ima_colorspace = ima->colorspace_settings.name; + + if (opts->save_as_render) { + /* Render/compositor output or user chose to save with render settings. */ + BKE_image_format_init_for_write(&opts->im_format, scene, nullptr); + is_depth_set = true; + if (!BKE_image_is_multiview(ima)) { + /* In case multiview is disabled, + * render settings would be invalid for render result in this area. */ + opts->im_format.stereo3d_format = *ima->stereo3d_format; + opts->im_format.views_format = ima->views_format; + } + } + else { + if (ima->source == IMA_SRC_GENERATED) { + opts->im_format.imtype = R_IMF_IMTYPE_PNG; + opts->im_format.compress = ibuf->foptions.quality; + opts->im_format.planes = ibuf->planes; + if (!IMB_colormanagement_space_name_is_data(ima_colorspace)) { + ima_colorspace = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_BYTE); + } + } + else { + BKE_image_format_from_imbuf(&opts->im_format, ibuf); + } + + /* use the multiview image settings as the default */ + opts->im_format.stereo3d_format = *ima->stereo3d_format; + opts->im_format.views_format = ima->views_format; + + /* Render output: colorspace from render settings. */ + BKE_image_format_color_management_copy_from_scene(&opts->im_format, scene); + } + + /* Default to saving in the same colorspace as the image setting. */ + if (!opts->save_as_render) { + STRNCPY(opts->im_format.linear_colorspace_settings.name, ima_colorspace); + } + + opts->im_format.color_management = R_IMF_COLOR_MANAGEMENT_FOLLOW_SCENE; + + if (ibuf->name[0] == '\0' || ima->source == IMA_SRC_TILED) { + BLI_strncpy(opts->filepath, ima->filepath, sizeof(opts->filepath)); + BLI_path_abs(opts->filepath, ID_BLEND_PATH_FROM_GLOBAL(&ima->id)); + } + else { + BLI_strncpy(opts->filepath, ibuf->name, sizeof(opts->filepath)); + } + + /* sanitize all settings */ + + /* unlikely but just in case */ + if (ELEM(opts->im_format.planes, R_IMF_PLANES_BW, R_IMF_PLANES_RGB, R_IMF_PLANES_RGBA) == 0) { + opts->im_format.planes = R_IMF_PLANES_RGBA; + } + + /* depth, account for float buffer and format support */ + if (is_depth_set == false) { + opts->im_format.depth = imtype_best_depth(ibuf, opts->im_format.imtype); + } + + /* some formats don't use quality so fallback to scenes quality */ + if (opts->im_format.quality == 0) { + opts->im_format.quality = scene->r.im_format.quality; + } + + /* check for empty path */ + if (guess_path && opts->filepath[0] == 0) { + const bool is_prev_save = !STREQ(G.ima, "//"); + if (opts->save_as_render) { + if (is_prev_save) { + BLI_strncpy(opts->filepath, G.ima, sizeof(opts->filepath)); + } + else { + BLI_strncpy(opts->filepath, "//untitled", sizeof(opts->filepath)); + BLI_path_abs(opts->filepath, BKE_main_blendfile_path(bmain)); + } + } + else { + BLI_snprintf(opts->filepath, sizeof(opts->filepath), "//%s", ima->id.name + 2); + BLI_path_make_safe(opts->filepath); + BLI_path_abs(opts->filepath, is_prev_save ? G.ima : BKE_main_blendfile_path(bmain)); + } + + /* append UDIM marker if not present */ + if (ima->source == IMA_SRC_TILED && strstr(opts->filepath, "<UDIM>") == nullptr) { + int len = strlen(opts->filepath); + STR_CONCAT(opts->filepath, len, ".<UDIM>"); + } + } + } + + /* Copy for detecting UI changes. */ + opts->prev_save_as_render = opts->save_as_render; + opts->prev_imtype = opts->im_format.imtype; + + BKE_image_release_ibuf(ima, ibuf, lock); + + return (ibuf != nullptr); +} + +void BKE_image_save_options_update(ImageSaveOptions *opts, Image *image) +{ + /* Auto update color space when changing save as render and file type. */ + if (opts->save_as_render) { + if (!opts->prev_save_as_render) { + if (ELEM(image->type, IMA_TYPE_R_RESULT, IMA_TYPE_COMPOSITE)) { + BKE_image_format_init_for_write(&opts->im_format, opts->scene, nullptr); + } + else { + BKE_image_format_color_management_copy_from_scene(&opts->im_format, opts->scene); + } + } + } + else { + if (opts->prev_save_as_render) { + /* Copy colorspace from image settings. */ + BKE_color_managed_colorspace_settings_copy(&opts->im_format.linear_colorspace_settings, + &image->colorspace_settings); + } + else if (opts->im_format.imtype != opts->prev_imtype && + !IMB_colormanagement_space_name_is_data( + opts->im_format.linear_colorspace_settings.name)) { + const bool linear_float_output = BKE_imtype_requires_linear_float(opts->im_format.imtype); + + /* TODO: detect if the colorspace is linear, not just equal to scene linear. */ + const bool is_linear = IMB_colormanagement_space_name_is_scene_linear( + opts->im_format.linear_colorspace_settings.name); + + /* If changing to a linear float or byte format, ensure we have a compatible color space. */ + if (linear_float_output && !is_linear) { + STRNCPY(opts->im_format.linear_colorspace_settings.name, + IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_FLOAT)); + } + else if (!linear_float_output && is_linear) { + STRNCPY(opts->im_format.linear_colorspace_settings.name, + IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_BYTE)); + } + } + } + + opts->prev_save_as_render = opts->save_as_render; + opts->prev_imtype = opts->im_format.imtype; } void BKE_image_save_options_free(ImageSaveOptions *opts) @@ -105,12 +309,17 @@ static void image_save_post(ReportList *reports, BLI_path_rel(ima->filepath, relbase); /* only after saving */ } - ColorManagedColorspaceSettings old_colorspace_settings; - BKE_color_managed_colorspace_settings_copy(&old_colorspace_settings, &ima->colorspace_settings); - IMB_colormanagement_colorspace_from_ibuf_ftype(&ima->colorspace_settings, ibuf); - if (!BKE_color_managed_colorspace_settings_equals(&old_colorspace_settings, - &ima->colorspace_settings)) { - *r_colorspace_changed = true; + /* Update image file color space when saving to another color space. */ + const bool linear_float_output = BKE_imtype_requires_linear_float(opts->im_format.imtype); + + if (!opts->save_as_render || linear_float_output) { + if (opts->im_format.linear_colorspace_settings.name[0] && + !BKE_color_managed_colorspace_settings_equals( + &ima->colorspace_settings, &opts->im_format.linear_colorspace_settings)) { + BKE_color_managed_colorspace_settings_copy(&ima->colorspace_settings, + &opts->im_format.linear_colorspace_settings); + *r_colorspace_changed = true; + } } } @@ -176,12 +385,12 @@ static bool image_save_single(ReportList *reports, /* we need renderresult for exr and rendered multiview */ rr = BKE_image_acquire_renderresult(opts->scene, ima); - bool is_mono = rr ? BLI_listbase_count_at_most(&rr->views, 2) < 2 : - BLI_listbase_count_at_most(&ima->views, 2) < 2; - bool is_exr_rr = rr && ELEM(imf->imtype, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER) && - RE_HasFloatPixels(rr); - bool is_multilayer = is_exr_rr && (imf->imtype == R_IMF_IMTYPE_MULTILAYER); - int layer = (iuser && !is_multilayer) ? iuser->layer : -1; + const bool is_mono = rr ? BLI_listbase_count_at_most(&rr->views, 2) < 2 : + BLI_listbase_count_at_most(&ima->views, 2) < 2; + const bool is_exr_rr = rr && ELEM(imf->imtype, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER) && + RE_HasFloatPixels(rr); + const bool is_multilayer = is_exr_rr && (imf->imtype == R_IMF_IMTYPE_MULTILAYER); + const int layer = (iuser && !is_multilayer) ? iuser->layer : -1; /* error handling */ if (rr == nullptr) { @@ -366,7 +575,6 @@ static bool image_save_single(ReportList *reports, colormanaged_ibuf = IMB_colormanagement_imbuf_for_write(ibuf, save_as_render, true, imf); BKE_image_format_to_imbuf(colormanaged_ibuf, imf); - IMB_prepare_write_ImBuf(IMB_isfloat(colormanaged_ibuf), colormanaged_ibuf); /* duplicate buffer to prevent locker issue when using render result */ ibuf_stereo[i] = IMB_dupImBuf(colormanaged_ibuf); @@ -401,8 +609,13 @@ static bool image_save_single(ReportList *reports, bool BKE_image_save( ReportList *reports, Main *bmain, Image *ima, ImageUser *iuser, ImageSaveOptions *opts) { + /* For saving a tiled image we need an iuser, so use a local one if there isn't already one. */ ImageUser save_iuser; - BKE_imageuser_default(&save_iuser); + if (iuser == nullptr) { + BKE_imageuser_default(&save_iuser); + iuser = &save_iuser; + iuser->scene = opts->scene; + } bool colorspace_changed = false; @@ -419,12 +632,6 @@ bool BKE_image_save( opts->filepath); return false; } - - /* For saving a tiled image we need an iuser, so use a local one if there isn't already one. - */ - if (iuser == nullptr) { - iuser = &save_iuser; - } } /* Save images */ @@ -787,7 +994,6 @@ bool BKE_image_render_write(ReportList *reports, int view_id = BLI_findstringindex(&rr->views, names[i], offsetof(RenderView, name)); ibuf_arr[i] = RE_render_result_rect_to_ibuf(rr, &image_format, dither, view_id); IMB_colormanagement_imbuf_for_write(ibuf_arr[i], true, false, &image_format); - IMB_prepare_write_ImBuf(IMB_isfloat(ibuf_arr[i]), ibuf_arr[i]); } ibuf_arr[2] = IMB_stereo3d_ImBuf(&image_format, ibuf_arr[0], ibuf_arr[1]); diff --git a/source/blender/blenkernel/intern/lib_id.c b/source/blender/blenkernel/intern/lib_id.c index 27427b1fb44..528681d196e 100644 --- a/source/blender/blenkernel/intern/lib_id.c +++ b/source/blender/blenkernel/intern/lib_id.c @@ -263,7 +263,6 @@ void id_us_ensure_real(ID *id) "ID user count error: %s (from '%s')", id->name, id->lib ? id->lib->filepath_abs : "[Main]"); - BLI_assert(0); } id->us = limit + 1; id->tag |= LIB_TAG_EXTRAUSER_SET; @@ -312,7 +311,7 @@ void id_us_min(ID *id) const int limit = ID_FAKE_USERS(id); if (id->us <= limit) { - if (GS(id->name) != ID_IP) { + if (!ID_TYPE_IS_DEPRECATED(GS(id->name))) { /* Do not assert on deprecated ID types, we cannot really ensure that their ID refcounting * is valid... */ CLOG_ERROR(&LOG, @@ -321,7 +320,6 @@ void id_us_min(ID *id) id->lib ? id->lib->filepath_abs : "[Main]", id->us, limit); - BLI_assert(0); } id->us = limit; } @@ -592,11 +590,9 @@ static int id_copy_libmanagement_cb(LibraryIDLinkCallbackData *cb_data) bool BKE_id_copy_is_allowed(const ID *id) { -#define LIB_ID_TYPES_NOCOPY \ - ID_LI, ID_SCR, ID_WM, ID_WS, /* Not supported */ \ - ID_IP /* Deprecated */ +#define LIB_ID_TYPES_NOCOPY ID_LI, ID_SCR, ID_WM, ID_WS /* Not supported */ - return !ELEM(GS(id->name), LIB_ID_TYPES_NOCOPY); + return !ID_TYPE_IS_DEPRECATED(GS(id->name)) && !ELEM(GS(id->name), LIB_ID_TYPES_NOCOPY); #undef LIB_ID_TYPES_NOCOPY } diff --git a/source/blender/blenkernel/intern/lib_override.c b/source/blender/blenkernel/intern/lib_override.cc index 768ac4f606f..fb538eea415 100644 --- a/source/blender/blenkernel/intern/lib_override.c +++ b/source/blender/blenkernel/intern/lib_override.cc @@ -5,8 +5,8 @@ * \ingroup bke */ -#include <stdlib.h> -#include <string.h> +#include <cstdlib> +#include <cstring> #include "CLG_log.h" @@ -72,17 +72,32 @@ static void lib_override_library_property_clear(IDOverrideLibraryProperty *op); static void lib_override_library_property_operation_clear( IDOverrideLibraryPropertyOperation *opop); +/** Helper to preserve Pose mode on override objects. + * A bit annoying to have this special case, but not much to be done here currently, since the + * matching RNA property is read-only. */ +BLI_INLINE void lib_override_object_posemode_transfer(ID *id_dst, ID *id_src) +{ + if (GS(id_src->name) == ID_OB && GS(id_dst->name) == ID_OB) { + Object *ob_src = (Object *)id_src; + Object *ob_dst = (Object *)id_dst; + if (ob_src->type == OB_ARMATURE && (ob_src->mode & OB_MODE_POSE) != 0) { + ob_dst->restore_mode = ob_dst->mode; + ob_dst->mode |= OB_MODE_POSE; + } + } +} + /** Get override data for a given ID. Needed because of our beloved shape keys snowflake. */ BLI_INLINE IDOverrideLibrary *lib_override_get(Main *bmain, ID *id, ID **r_owner_id) { - if (r_owner_id != NULL) { + if (r_owner_id != nullptr) { *r_owner_id = id; } if (id->flag & LIB_EMBEDDED_DATA_LIB_OVERRIDE) { const IDTypeInfo *id_type = BKE_idtype_get_info_from_id(id); - if (id_type->owner_get != NULL) { + if (id_type->owner_get != nullptr) { ID *owner_id = id_type->owner_get(bmain, id); - if (r_owner_id != NULL) { + if (r_owner_id != nullptr) { *r_owner_id = owner_id; } return owner_id->override_library; @@ -94,19 +109,20 @@ BLI_INLINE IDOverrideLibrary *lib_override_get(Main *bmain, ID *id, ID **r_owner IDOverrideLibrary *BKE_lib_override_library_init(ID *local_id, ID *reference_id) { - /* If reference_id is NULL, we are creating an override template for purely local data. + /* If reference_id is nullptr, we are creating an override template for purely local data. * Else, reference *must* be linked data. */ - BLI_assert(reference_id == NULL || ID_IS_LINKED(reference_id)); - BLI_assert(local_id->override_library == NULL); + BLI_assert(reference_id == nullptr || ID_IS_LINKED(reference_id)); + BLI_assert(local_id->override_library == nullptr); ID *ancestor_id; - for (ancestor_id = reference_id; ancestor_id != NULL && ancestor_id->override_library != NULL && - ancestor_id->override_library->reference != NULL; + for (ancestor_id = reference_id; + ancestor_id != nullptr && ancestor_id->override_library != nullptr && + ancestor_id->override_library->reference != nullptr; ancestor_id = ancestor_id->override_library->reference) { /* pass */ } - if (ancestor_id != NULL && ancestor_id->override_library != NULL) { + if (ancestor_id != nullptr && ancestor_id->override_library != nullptr) { /* Original ID has a template, use it! */ BKE_lib_override_library_copy(local_id, ancestor_id, true); if (local_id->override_library->reference != reference_id) { @@ -118,7 +134,7 @@ IDOverrideLibrary *BKE_lib_override_library_init(ID *local_id, ID *reference_id) } /* Else, generate new empty override. */ - local_id->override_library = MEM_callocN(sizeof(*local_id->override_library), __func__); + local_id->override_library = MEM_cnew<IDOverrideLibrary>(__func__); local_id->override_library->reference = reference_id; id_us_plus(local_id->override_library->reference); local_id->tag &= ~LIB_TAG_OVERRIDE_LIBRARY_REFOK; @@ -133,20 +149,20 @@ void BKE_lib_override_library_copy(ID *dst_id, const ID *src_id, const bool do_f { BLI_assert(ID_IS_OVERRIDE_LIBRARY(src_id) || ID_IS_OVERRIDE_LIBRARY_TEMPLATE(src_id)); - if (dst_id->override_library != NULL) { - if (src_id->override_library == NULL) { + if (dst_id->override_library != nullptr) { + if (src_id->override_library == nullptr) { BKE_lib_override_library_free(&dst_id->override_library, true); return; } BKE_lib_override_library_clear(dst_id->override_library, true); } - else if (src_id->override_library == NULL) { + else if (src_id->override_library == nullptr) { /* Virtual overrides of embedded data does not require any extra work. */ return; } else { - BKE_lib_override_library_init(dst_id, NULL); + BKE_lib_override_library_init(dst_id, nullptr); } /* If source is already overriding data, we copy it but reuse its reference for dest ID. @@ -162,8 +178,10 @@ void BKE_lib_override_library_copy(ID *dst_id, const ID *src_id, const bool do_f if (do_full_copy) { BLI_duplicatelist(&dst_id->override_library->properties, &src_id->override_library->properties); - for (IDOverrideLibraryProperty *op_dst = dst_id->override_library->properties.first, - *op_src = src_id->override_library->properties.first; + for (IDOverrideLibraryProperty *op_dst = static_cast<IDOverrideLibraryProperty *>( + dst_id->override_library->properties.first), + *op_src = static_cast<IDOverrideLibraryProperty *>( + src_id->override_library->properties.first); op_dst; op_dst = op_dst->next, op_src = op_src->next) { lib_override_library_property_copy(op_dst, op_src); @@ -175,10 +193,10 @@ void BKE_lib_override_library_copy(ID *dst_id, const ID *src_id, const bool do_f void BKE_lib_override_library_clear(IDOverrideLibrary *override, const bool do_id_user) { - BLI_assert(override != NULL); + BLI_assert(override != nullptr); - if (!ELEM(NULL, override->runtime, override->runtime->rna_path_to_override_properties)) { - BLI_ghash_clear(override->runtime->rna_path_to_override_properties, NULL, NULL); + if (!ELEM(nullptr, override->runtime, override->runtime->rna_path_to_override_properties)) { + BLI_ghash_clear(override->runtime->rna_path_to_override_properties, nullptr, nullptr); } LISTBASE_FOREACH (IDOverrideLibraryProperty *, op, &override->properties) { @@ -192,20 +210,20 @@ void BKE_lib_override_library_clear(IDOverrideLibrary *override, const bool do_i } } -void BKE_lib_override_library_free(struct IDOverrideLibrary **override, const bool do_id_user) +void BKE_lib_override_library_free(IDOverrideLibrary **override, const bool do_id_user) { - BLI_assert(*override != NULL); + BLI_assert(*override != nullptr); - if ((*override)->runtime != NULL) { - if ((*override)->runtime->rna_path_to_override_properties != NULL) { - BLI_ghash_free((*override)->runtime->rna_path_to_override_properties, NULL, NULL); + if ((*override)->runtime != nullptr) { + if ((*override)->runtime->rna_path_to_override_properties != nullptr) { + BLI_ghash_free((*override)->runtime->rna_path_to_override_properties, nullptr, nullptr); } MEM_SAFE_FREE((*override)->runtime); } BKE_lib_override_library_clear(*override, do_id_user); MEM_freeN(*override); - *override = NULL; + *override = nullptr; } static ID *lib_override_library_create_from(Main *bmain, @@ -217,12 +235,12 @@ static ID *lib_override_library_create_from(Main *bmain, * override template, or already an override of some other ref data). */ ID *local_id = BKE_id_copy_ex(bmain, reference_id, - NULL, + nullptr, LIB_ID_COPY_DEFAULT | LIB_ID_COPY_NO_LIB_OVERRIDE | lib_id_copy_flags); - if (local_id == NULL) { - return NULL; + if (local_id == nullptr) { + return nullptr; } id_us_min(local_id); @@ -238,9 +256,9 @@ static ID *lib_override_library_create_from(Main *bmain, * data-blocks, just like root node trees or master collections. Therefore, we never need to * create overrides for them. We need a way to mark them as overrides though. */ Key *reference_key; - if ((reference_key = BKE_key_from_id(reference_id)) != NULL) { + if ((reference_key = BKE_key_from_id(reference_id)) != nullptr) { Key *local_key = BKE_key_from_id(local_id); - BLI_assert(local_key != NULL); + BLI_assert(local_key != nullptr); local_key->id.flag |= LIB_EMBEDDED_DATA_LIB_OVERRIDE; } @@ -249,7 +267,7 @@ static ID *lib_override_library_create_from(Main *bmain, /* TODO: This could be simplified by storing a flag in #IDOverrideLibrary * during the diffing process? */ -bool BKE_lib_override_library_is_user_edited(struct ID *id) +bool BKE_lib_override_library_is_user_edited(ID *id) { if (!ID_IS_OVERRIDE_LIBRARY(id)) { @@ -295,9 +313,9 @@ static int foreachid_is_hierarchy_leaf_fn(LibraryIDLinkCallbackData *cb_data) { ID *id_owner = cb_data->id_owner; ID *id = *cb_data->id_pointer; - bool *is_leaf = cb_data->user_data; + bool *is_leaf = static_cast<bool *>(cb_data->user_data); - if (id != NULL && ID_IS_OVERRIDE_LIBRARY_REAL(id) && + if (id != nullptr && ID_IS_OVERRIDE_LIBRARY_REAL(id) && id->override_library->hierarchy_root == id_owner->override_library->hierarchy_root) { *is_leaf = false; return IDWALK_RET_STOP_ITER; @@ -321,10 +339,10 @@ ID *BKE_lib_override_library_create_from_id(Main *bmain, ID *reference_id, const bool do_tagged_remap) { - BLI_assert(reference_id != NULL); + BLI_assert(reference_id != nullptr); BLI_assert(ID_IS_LINKED(reference_id)); - ID *local_id = lib_override_library_create_from(bmain, NULL, reference_id, 0); + ID *local_id = lib_override_library_create_from(bmain, nullptr, reference_id, 0); /* We cannot allow automatic hierarchy resync on this ID, it is highly likely to generate a giant * mess in case there are a lot of hidden, non-instantiated, non-properly organized dependencies. * Ref T94650. */ @@ -333,10 +351,10 @@ ID *BKE_lib_override_library_create_from_id(Main *bmain, local_id->override_library->hierarchy_root = local_id; if (do_tagged_remap) { - Key *reference_key, *local_key = NULL; - if ((reference_key = BKE_key_from_id(reference_id)) != NULL) { + Key *reference_key, *local_key = nullptr; + if ((reference_key = BKE_key_from_id(reference_id)) != nullptr) { local_key = BKE_key_from_id(local_id); - BLI_assert(local_key != NULL); + BLI_assert(local_key != nullptr); } ID *other_id; @@ -349,7 +367,7 @@ ID *BKE_lib_override_library_create_from_id(Main *bmain, reference_id, local_id, ID_REMAP_SKIP_INDIRECT_USAGE | ID_REMAP_SKIP_OVERRIDE_LIBRARY); - if (reference_key != NULL) { + if (reference_key != nullptr) { BKE_libblock_relink_ex(bmain, other_id, &reference_key->id, @@ -383,18 +401,19 @@ bool BKE_lib_override_library_create_from_tag(Main *bmain, const ID *id_root_reference, ID *id_hierarchy_root, const ID *id_hierarchy_root_reference, - const bool do_no_main) + const bool do_no_main, + const bool do_fully_editable) { - BLI_assert(id_root_reference != NULL && ID_IS_LINKED(id_root_reference)); + BLI_assert(id_root_reference != nullptr && ID_IS_LINKED(id_root_reference)); /* If we do not have any hierarchy root given, then the root reference must be tagged for * override. */ - BLI_assert(id_hierarchy_root != NULL || id_hierarchy_root_reference != NULL || + BLI_assert(id_hierarchy_root != nullptr || id_hierarchy_root_reference != nullptr || (id_root_reference->tag & LIB_TAG_DOIT) != 0); - /* At least one of the hierarchy root pointers must be NULL, passing both is useless and can + /* At least one of the hierarchy root pointers must be nullptr, passing both is useless and can * create confusion. */ - BLI_assert(ELEM(NULL, id_hierarchy_root, id_hierarchy_root_reference)); + BLI_assert(ELEM(nullptr, id_hierarchy_root, id_hierarchy_root_reference)); - if (id_hierarchy_root != NULL) { + if (id_hierarchy_root != nullptr) { /* If the hierarchy root is given, it must be a valid existing override (used during partial * resync process mainly). */ BLI_assert((ID_IS_OVERRIDE_LIBRARY_REAL(id_hierarchy_root) && @@ -407,7 +426,7 @@ bool BKE_lib_override_library_create_from_tag(Main *bmain, lib_override_prefill_newid_from_existing_overrides(bmain, id_hierarchy_root); } } - if (!ELEM(id_hierarchy_root_reference, NULL, id_root_reference)) { + if (!ELEM(id_hierarchy_root_reference, nullptr, id_root_reference)) { /* If the reference hierarchy root is given, it must be from the same library as the reference * root, and also tagged for override. */ BLI_assert((id_hierarchy_root_reference->lib == id_root_reference->lib && @@ -419,14 +438,14 @@ bool BKE_lib_override_library_create_from_tag(Main *bmain, ID *reference_id; bool success = true; - ListBase todo_ids = {NULL}; + ListBase todo_ids = {nullptr}; LinkData *todo_id_iter; /* Get all IDs we want to override. */ FOREACH_MAIN_ID_BEGIN (bmain, reference_id) { if ((reference_id->tag & LIB_TAG_DOIT) != 0 && reference_id->lib == reference_library && BKE_idtype_idcode_is_linkable(GS(reference_id->name))) { - todo_id_iter = MEM_callocN(sizeof(*todo_id_iter), __func__); + todo_id_iter = MEM_cnew<LinkData>(__func__); todo_id_iter->data = reference_id; BLI_addtail(&todo_ids, todo_id_iter); } @@ -434,31 +453,35 @@ bool BKE_lib_override_library_create_from_tag(Main *bmain, FOREACH_MAIN_ID_END; /* Override the IDs. */ - for (todo_id_iter = todo_ids.first; todo_id_iter != NULL; todo_id_iter = todo_id_iter->next) { - reference_id = todo_id_iter->data; + for (todo_id_iter = static_cast<LinkData *>(todo_ids.first); todo_id_iter != nullptr; + todo_id_iter = todo_id_iter->next) { + reference_id = static_cast<ID *>(todo_id_iter->data); /* If `newid` is already set, assume it has been handled by calling code. * Only current use case: re-using proxy ID when converting to liboverride. */ - if (reference_id->newid == NULL) { + if (reference_id->newid == nullptr) { /* NOTE: `no main` case is used during resync procedure, to support recursive resync. * This requires extra care further down the resync process, * see: #BKE_lib_override_library_resync. */ reference_id->newid = lib_override_library_create_from( bmain, owner_library, reference_id, do_no_main ? LIB_ID_CREATE_NO_MAIN : 0); - if (reference_id->newid == NULL) { + if (reference_id->newid == nullptr) { success = false; break; } + if (do_fully_editable) { + reference_id->newid->override_library->flag &= ~IDOVERRIDE_LIBRARY_FLAG_SYSTEM_DEFINED; + } } /* We also tag the new IDs so that in next step we can remap their pointers too. */ reference_id->newid->tag |= LIB_TAG_DOIT; Key *reference_key; - if ((reference_key = BKE_key_from_id(reference_id)) != NULL) { + if ((reference_key = BKE_key_from_id(reference_id)) != nullptr) { reference_key->id.tag |= LIB_TAG_DOIT; Key *local_key = BKE_key_from_id(reference_id->newid); - BLI_assert(local_key != NULL); + BLI_assert(local_key != nullptr); reference_key->id.newid = &local_key->id; /* We also tag the new IDs so that in next step we can remap their pointers too. */ local_key->id.tag |= LIB_TAG_DOIT; @@ -468,17 +491,17 @@ bool BKE_lib_override_library_create_from_tag(Main *bmain, /* Only remap new local ID's pointers, we don't want to force our new overrides onto our whole * existing linked IDs usages. */ if (success) { - if (id_hierarchy_root_reference != NULL) { + if (id_hierarchy_root_reference != nullptr) { id_hierarchy_root = id_hierarchy_root_reference->newid; } - else if (id_root_reference->newid != NULL && - (id_hierarchy_root == NULL || + else if (id_root_reference->newid != nullptr && + (id_hierarchy_root == nullptr || id_hierarchy_root->override_library->reference == id_root_reference)) { id_hierarchy_root = id_root_reference->newid; } - BLI_assert(id_hierarchy_root != NULL); + BLI_assert(id_hierarchy_root != nullptr); - LinkNode *relinked_ids = NULL; + LinkNode *relinked_ids = nullptr; /* Still checking the whole Main, that way we can tag other local IDs as needing to be * remapped to use newly created overriding IDs, if needed. */ ID *id; @@ -486,14 +509,14 @@ bool BKE_lib_override_library_create_from_tag(Main *bmain, ID *other_id; /* In case we created new overrides as 'no main', they are not accessible directly in this * loop, but we can get to them through their reference's `newid` pointer. */ - if (do_no_main && id->lib == id_root_reference->lib && id->newid != NULL) { + if (do_no_main && id->lib == id_root_reference->lib && id->newid != nullptr) { other_id = id->newid; /* Otherwise we cannot properly distinguish between IDs that are actually from the * linked library (and should not be remapped), and IDs that are overrides re-generated * from the reference from the linked library, and must therefore be remapped. * * This is reset afterwards at the end of this loop. */ - other_id->lib = NULL; + other_id->lib = nullptr; } else { other_id = id; @@ -510,12 +533,13 @@ bool BKE_lib_override_library_create_from_tag(Main *bmain, } FOREACH_MAIN_ID_END; - struct IDRemapper *id_remapper = BKE_id_remapper_create(); - for (todo_id_iter = todo_ids.first; todo_id_iter != NULL; todo_id_iter = todo_id_iter->next) { - reference_id = todo_id_iter->data; + IDRemapper *id_remapper = BKE_id_remapper_create(); + for (todo_id_iter = static_cast<LinkData *>(todo_ids.first); todo_id_iter != nullptr; + todo_id_iter = todo_id_iter->next) { + reference_id = static_cast<ID *>(todo_id_iter->data); ID *local_id = reference_id->newid; - if (local_id == NULL) { + if (local_id == nullptr) { continue; } @@ -523,10 +547,10 @@ bool BKE_lib_override_library_create_from_tag(Main *bmain, BKE_id_remapper_add(id_remapper, reference_id, local_id); - Key *reference_key, *local_key = NULL; - if ((reference_key = BKE_key_from_id(reference_id)) != NULL) { + Key *reference_key, *local_key = nullptr; + if ((reference_key = BKE_key_from_id(reference_id)) != nullptr) { local_key = BKE_key_from_id(reference_id->newid); - BLI_assert(local_key != NULL); + BLI_assert(local_key != nullptr); BKE_id_remapper_add(id_remapper, &reference_key->id, &local_key->id); } @@ -539,14 +563,15 @@ bool BKE_lib_override_library_create_from_tag(Main *bmain, ID_REMAP_SKIP_OVERRIDE_LIBRARY | ID_REMAP_FORCE_USER_REFCOUNT); BKE_id_remapper_free(id_remapper); - BLI_linklist_free(relinked_ids, NULL); + BLI_linklist_free(relinked_ids, nullptr); } else { /* We need to cleanup potentially already created data. */ - for (todo_id_iter = todo_ids.first; todo_id_iter != NULL; todo_id_iter = todo_id_iter->next) { - reference_id = todo_id_iter->data; + for (todo_id_iter = static_cast<LinkData *>(todo_ids.first); todo_id_iter != nullptr; + todo_id_iter = todo_id_iter->next) { + reference_id = static_cast<ID *>(todo_id_iter->data); BKE_id_delete(bmain, reference_id->newid); - reference_id->newid = NULL; + reference_id->newid = nullptr; } } @@ -555,7 +580,7 @@ bool BKE_lib_override_library_create_from_tag(Main *bmain, return success; } -typedef struct LibOverrideGroupTagData { +struct LibOverrideGroupTagData { Main *bmain; Scene *scene; ID *id_root; @@ -571,7 +596,7 @@ typedef struct LibOverrideGroupTagData { * Avoids calling #BKE_collection_object_find over and over, this function is very expansive. */ GHash *linked_object_to_instantiating_collections; MemArena *mem_arena; -} LibOverrideGroupTagData; +}; static void lib_override_group_tag_data_object_to_collection_init_collection_process( LibOverrideGroupTagData *data, Collection *collection) @@ -586,8 +611,8 @@ static void lib_override_group_tag_data_object_to_collection_init_collection_pro if (!BLI_ghash_ensure_p(data->linked_object_to_instantiating_collections, ob, (void ***)&collections_linkedlist_p)) { - *collections_linkedlist_p = BLI_memarena_calloc(data->mem_arena, - sizeof(**collections_linkedlist_p)); + *collections_linkedlist_p = static_cast<LinkNodePair *>( + BLI_memarena_calloc(data->mem_arena, sizeof(**collections_linkedlist_p))); } BLI_linklist_append_arena(*collections_linkedlist_p, collection, data->mem_arena); } @@ -604,7 +629,7 @@ static void lib_override_group_tag_data_object_to_collection_init(LibOverrideGro data->linked_object_to_instantiating_collections = BLI_ghash_new( BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, __func__); - if (data->scene != NULL) { + if (data->scene != nullptr) { lib_override_group_tag_data_object_to_collection_init_collection_process( data, data->scene->master_collection); } @@ -615,7 +640,7 @@ static void lib_override_group_tag_data_object_to_collection_init(LibOverrideGro static void lib_override_group_tag_data_clear(LibOverrideGroupTagData *data) { - BLI_ghash_free(data->linked_object_to_instantiating_collections, NULL, NULL); + BLI_ghash_free(data->linked_object_to_instantiating_collections, nullptr, nullptr); BLI_memarena_free(data->mem_arena); memset(data, 0, sizeof(*data)); } @@ -632,8 +657,9 @@ static bool lib_override_hierarchy_dependencies_recursive_tag(LibOverrideGroupTa ID *id = data->id_root; const bool is_override = data->is_override; - MainIDRelationsEntry *entry = BLI_ghash_lookup(bmain->relations->relations_from_pointers, id); - BLI_assert(entry != NULL); + MainIDRelationsEntry *entry = static_cast<MainIDRelationsEntry *>( + BLI_ghash_lookup(bmain->relations->relations_from_pointers, id)); + BLI_assert(entry != nullptr); if (entry->tags & MAINIDRELATIONS_ENTRY_TAGS_PROCESSED) { /* This ID has already been processed. */ @@ -643,7 +669,7 @@ static bool lib_override_hierarchy_dependencies_recursive_tag(LibOverrideGroupTa * relationship hierarchy. */ entry->tags |= MAINIDRELATIONS_ENTRY_TAGS_PROCESSED; - for (MainIDRelationsEntryItem *to_id_entry = entry->to_ids; to_id_entry != NULL; + for (MainIDRelationsEntryItem *to_id_entry = entry->to_ids; to_id_entry != nullptr; to_id_entry = to_id_entry->next) { if ((to_id_entry->usage_flag & IDWALK_CB_OVERRIDE_LIBRARY_NOT_OVERRIDABLE) != 0) { /* Never consider non-overridable relationships ('from', 'parents', 'owner' etc. pointers) as @@ -652,7 +678,7 @@ static bool lib_override_hierarchy_dependencies_recursive_tag(LibOverrideGroupTa } /* We only consider IDs from the same library. */ ID *to_id = *to_id_entry->id_pointer.to; - if (to_id == NULL || to_id->lib != id->lib || + if (to_id == nullptr || to_id->lib != id->lib || (is_override && !ID_IS_OVERRIDE_LIBRARY(to_id))) { /* IDs from different libraries, or non-override IDs in case we are processing overrides, are * both barriers of dependency. */ @@ -677,9 +703,9 @@ static void lib_override_linked_group_tag_recursive(LibOverrideGroupTagData *dat const uint tag = data->tag; const uint missing_tag = data->missing_tag; - MainIDRelationsEntry *entry = BLI_ghash_lookup(bmain->relations->relations_from_pointers, - id_owner); - BLI_assert(entry != NULL); + MainIDRelationsEntry *entry = static_cast<MainIDRelationsEntry *>( + BLI_ghash_lookup(bmain->relations->relations_from_pointers, id_owner)); + BLI_assert(entry != nullptr); if (entry->tags & MAINIDRELATIONS_ENTRY_TAGS_PROCESSED) { /* This ID has already been processed. */ @@ -689,7 +715,7 @@ static void lib_override_linked_group_tag_recursive(LibOverrideGroupTagData *dat * relationship hierarchy. */ entry->tags |= MAINIDRELATIONS_ENTRY_TAGS_PROCESSED; - for (MainIDRelationsEntryItem *to_id_entry = entry->to_ids; to_id_entry != NULL; + for (MainIDRelationsEntryItem *to_id_entry = entry->to_ids; to_id_entry != nullptr; to_id_entry = to_id_entry->next) { if ((to_id_entry->usage_flag & IDWALK_CB_OVERRIDE_LIBRARY_NOT_OVERRIDABLE) != 0) { /* Never consider non-overridable relationships as actual dependencies. */ @@ -697,7 +723,7 @@ static void lib_override_linked_group_tag_recursive(LibOverrideGroupTagData *dat } ID *to_id = *to_id_entry->id_pointer.to; - if (ELEM(to_id, NULL, id_owner)) { + if (ELEM(to_id, nullptr, id_owner)) { continue; } /* We only consider IDs from the same library. */ @@ -732,10 +758,12 @@ static bool lib_override_linked_group_tag_collections_keep_tagged_check_recursiv * is not usable here, as it may have become invalid from some previous operation and it should * not be updated here. So instead only use collections' reliable 'raw' data to check if some * object in the hierarchy of the given collection is still tagged for override. */ - for (CollectionObject *collection_object = collection->gobject.first; collection_object != NULL; + for (CollectionObject *collection_object = + static_cast<CollectionObject *>(collection->gobject.first); + collection_object != nullptr; collection_object = collection_object->next) { Object *object = collection_object->ob; - if (object == NULL) { + if (object == nullptr) { continue; } if ((object->id.tag & data->tag) != 0) { @@ -743,7 +771,9 @@ static bool lib_override_linked_group_tag_collections_keep_tagged_check_recursiv } } - for (CollectionChild *collection_child = collection->children.first; collection_child != NULL; + for (CollectionChild *collection_child = + static_cast<CollectionChild *>(collection->children.first); + collection_child != nullptr; collection_child = collection_child->next) { if (lib_override_linked_group_tag_collections_keep_tagged_check_recursive( data, collection_child->collection)) { @@ -762,9 +792,11 @@ static void lib_override_linked_group_tag_clear_boneshapes_objects(LibOverrideGr /* Remove (untag) bone shape objects, they shall never need to be to directly/explicitly * overridden. */ LISTBASE_FOREACH (Object *, ob, &bmain->objects) { - if (ob->type == OB_ARMATURE && ob->pose != NULL && (ob->id.tag & data->tag)) { - for (bPoseChannel *pchan = ob->pose->chanbase.first; pchan != NULL; pchan = pchan->next) { - if (pchan->custom != NULL && &pchan->custom->id != id_root) { + if (ob->type == OB_ARMATURE && ob->pose != nullptr && (ob->id.tag & data->tag)) { + for (bPoseChannel *pchan = static_cast<bPoseChannel *>(ob->pose->chanbase.first); + pchan != nullptr; + pchan = pchan->next) { + if (pchan->custom != nullptr && &pchan->custom->id != id_root) { pchan->custom->id.tag &= ~data->tag; } } @@ -841,17 +873,18 @@ static void lib_override_linked_group_tag(LibOverrideGroupTagData *data) } LISTBASE_FOREACH (Object *, ob, &bmain->objects) { if (ID_IS_LINKED(ob) && (ob->id.tag & data->tag) != 0) { - Collection *instantiating_collection = NULL; - Collection *instantiating_collection_override_candidate = NULL; + Collection *instantiating_collection = nullptr; + Collection *instantiating_collection_override_candidate = nullptr; /* Loop over all collections instantiating the object, if we already have a 'locale' one we * have nothing to do, otherwise try to find a 'linked' one that we can override too. */ - LinkNodePair *instantiating_collection_linklist = BLI_ghash_lookup( - data->linked_object_to_instantiating_collections, ob); - if (instantiating_collection_linklist != NULL) { + LinkNodePair *instantiating_collection_linklist = static_cast<LinkNodePair *>( + BLI_ghash_lookup(data->linked_object_to_instantiating_collections, ob)); + if (instantiating_collection_linklist != nullptr) { for (LinkNode *instantiating_collection_linknode = instantiating_collection_linklist->list; - instantiating_collection_linknode != NULL; + instantiating_collection_linknode != nullptr; instantiating_collection_linknode = instantiating_collection_linknode->next) { - instantiating_collection = instantiating_collection_linknode->link; + instantiating_collection = static_cast<Collection *>( + instantiating_collection_linknode->link); if (!ID_IS_LINKED(instantiating_collection)) { /* There is a local collection instantiating the linked object to override, nothing * else to be done here. */ @@ -863,12 +896,12 @@ static void lib_override_linked_group_tag(LibOverrideGroupTagData *data) break; } instantiating_collection_override_candidate = instantiating_collection; - instantiating_collection = NULL; + instantiating_collection = nullptr; } } - if (instantiating_collection == NULL && - instantiating_collection_override_candidate != NULL) { + if (instantiating_collection == nullptr && + instantiating_collection_override_candidate != nullptr) { if (instantiating_collection_override_candidate->id.tag & LIB_TAG_MISSING) { instantiating_collection_override_candidate->id.tag |= data->missing_tag; } @@ -897,9 +930,9 @@ static void lib_override_overrides_group_tag_recursive(LibOverrideGroupTagData * const uint tag = data->tag; const uint missing_tag = data->missing_tag; - MainIDRelationsEntry *entry = BLI_ghash_lookup(bmain->relations->relations_from_pointers, - id_owner); - BLI_assert(entry != NULL); + MainIDRelationsEntry *entry = static_cast<MainIDRelationsEntry *>( + BLI_ghash_lookup(bmain->relations->relations_from_pointers, id_owner)); + BLI_assert(entry != nullptr); if (entry->tags & MAINIDRELATIONS_ENTRY_TAGS_PROCESSED) { /* This ID has already been processed. */ @@ -909,7 +942,7 @@ static void lib_override_overrides_group_tag_recursive(LibOverrideGroupTagData * * relationship hierarchy. */ entry->tags |= MAINIDRELATIONS_ENTRY_TAGS_PROCESSED; - for (MainIDRelationsEntryItem *to_id_entry = entry->to_ids; to_id_entry != NULL; + for (MainIDRelationsEntryItem *to_id_entry = entry->to_ids; to_id_entry != nullptr; to_id_entry = to_id_entry->next) { if ((to_id_entry->usage_flag & IDWALK_CB_OVERRIDE_LIBRARY_NOT_OVERRIDABLE) != 0) { /* Never consider non-overridable relationships as actual dependencies. */ @@ -917,7 +950,7 @@ static void lib_override_overrides_group_tag_recursive(LibOverrideGroupTagData * } ID *to_id = *to_id_entry->id_pointer.to; - if (ELEM(to_id, NULL, id_owner)) { + if (ELEM(to_id, nullptr, id_owner)) { continue; } /* Different libraries or different hierarchy roots are break points in override hierarchies. @@ -930,8 +963,8 @@ static void lib_override_overrides_group_tag_recursive(LibOverrideGroupTagData * continue; } - Library *reference_lib = lib_override_get(bmain, id_owner, NULL)->reference->lib; - ID *to_id_reference = lib_override_get(bmain, to_id, NULL)->reference; + Library *reference_lib = lib_override_get(bmain, id_owner, nullptr)->reference->lib; + ID *to_id_reference = lib_override_get(bmain, to_id, nullptr)->reference; if (to_id_reference->lib != reference_lib) { /* We do not override data-blocks from other libraries, nor do we process them. */ continue; @@ -959,7 +992,7 @@ static void lib_override_overrides_group_tag(LibOverrideGroupTagData *data) BLI_assert(data->is_override); ID *id_hierarchy_root = data->hierarchy_root_id; - BLI_assert(id_hierarchy_root != NULL); + BLI_assert(id_hierarchy_root != nullptr); BLI_assert(ID_IS_OVERRIDE_LIBRARY_REAL(id_hierarchy_root)); UNUSED_VARS_NDEBUG(id_hierarchy_root); @@ -978,16 +1011,18 @@ static bool lib_override_library_create_do(Main *bmain, Scene *scene, Library *owner_library, ID *id_root_reference, - ID *id_hierarchy_root_reference) + ID *id_hierarchy_root_reference, + const bool do_fully_editable) { BKE_main_relations_create(bmain, 0); - LibOverrideGroupTagData data = {.bmain = bmain, - .scene = scene, - .id_root = id_root_reference, - .tag = LIB_TAG_DOIT, - .missing_tag = LIB_TAG_MISSING, - .is_override = false, - .is_resync = false}; + LibOverrideGroupTagData data{}; + data.bmain = bmain; + data.scene = scene; + data.id_root = id_root_reference; + data.tag = LIB_TAG_DOIT; + data.missing_tag = LIB_TAG_MISSING; + data.is_override = false; + data.is_resync = false; lib_override_group_tag_data_object_to_collection_init(&data); lib_override_linked_group_tag(&data); @@ -1002,12 +1037,22 @@ static bool lib_override_library_create_do(Main *bmain, BLI_assert(ID_IS_OVERRIDE_LIBRARY_REAL(id_hierarchy_root_reference)); BLI_assert(id_hierarchy_root_reference->override_library->reference->lib == id_root_reference->lib); - success = BKE_lib_override_library_create_from_tag( - bmain, owner_library, id_root_reference, id_hierarchy_root_reference, NULL, false); + success = BKE_lib_override_library_create_from_tag(bmain, + owner_library, + id_root_reference, + id_hierarchy_root_reference, + nullptr, + false, + do_fully_editable); } else { - success = BKE_lib_override_library_create_from_tag( - bmain, owner_library, id_root_reference, NULL, id_hierarchy_root_reference, false); + success = BKE_lib_override_library_create_from_tag(bmain, + owner_library, + id_root_reference, + nullptr, + id_hierarchy_root_reference, + false, + do_fully_editable); } return success; @@ -1034,25 +1079,25 @@ static void lib_override_library_create_post_process(Main *bmain, /* We create a set of all objects referenced into the scene by its hierarchy of collections. * NOTE: This is different that the list of bases, since objects in excluded collections etc. * won't have a base, but are still considered as instanced from our point of view. */ - GSet *all_objects_in_scene = BKE_scene_objects_as_gset(scene, NULL); + GSet *all_objects_in_scene = BKE_scene_objects_as_gset(scene, nullptr); /* Instantiating the root collection or object should never be needed in resync case, since the * old override would be remapped to the new one. */ - if (!is_resync && id_root != NULL && id_root->newid != NULL && + if (!is_resync && id_root != nullptr && id_root->newid != nullptr && (!ID_IS_LINKED(id_root->newid) || id_root->newid->lib == owner_library)) { switch (GS(id_root->name)) { case ID_GR: { - Object *ob_reference = id_instance_hint != NULL && GS(id_instance_hint->name) == ID_OB ? + Object *ob_reference = id_instance_hint != nullptr && GS(id_instance_hint->name) == ID_OB ? (Object *)id_instance_hint : - NULL; + nullptr; Collection *collection_new = ((Collection *)id_root->newid); if (is_resync && BKE_collection_is_in_scene(collection_new)) { break; } - if (ob_reference != NULL) { + if (ob_reference != nullptr) { BKE_collection_add_from_object(bmain, scene, ob_reference, collection_new); } - else if (id_instance_hint != NULL) { + else if (id_instance_hint != nullptr) { BLI_assert(GS(id_instance_hint->name) == ID_GR); BKE_collection_add_from_collection( bmain, scene, ((Collection *)id_instance_hint), collection_new); @@ -1069,7 +1114,7 @@ static void lib_override_library_create_post_process(Main *bmain, } case ID_OB: { Object *ob_new = (Object *)id_root->newid; - if (BLI_gset_lookup(all_objects_in_scene, ob_new) == NULL) { + if (BLI_gset_lookup(all_objects_in_scene, ob_new) == nullptr) { BKE_collection_object_add_from(bmain, scene, (Object *)id_root, ob_new); all_objects_in_scene = BKE_scene_objects_as_gset(scene, all_objects_in_scene); } @@ -1084,16 +1129,16 @@ static void lib_override_library_create_post_process(Main *bmain, Collection *default_instantiating_collection = residual_storage; LISTBASE_FOREACH (Object *, ob, &bmain->objects) { Object *ob_new = (Object *)ob->id.newid; - if (ob_new == NULL || (ID_IS_LINKED(ob_new) && ob_new->id.lib != owner_library)) { + if (ob_new == nullptr || (ID_IS_LINKED(ob_new) && ob_new->id.lib != owner_library)) { continue; } - BLI_assert(ob_new->id.override_library != NULL && + BLI_assert(ob_new->id.override_library != nullptr && ob_new->id.override_library->reference == &ob->id); - if (BLI_gset_lookup(all_objects_in_scene, ob_new) == NULL) { - if (id_root != NULL && default_instantiating_collection == NULL) { - ID *id_ref = id_root->newid != NULL ? id_root->newid : id_root; + if (BLI_gset_lookup(all_objects_in_scene, ob_new) == nullptr) { + if (id_root != nullptr && default_instantiating_collection == nullptr) { + ID *id_ref = id_root->newid != nullptr ? id_root->newid : id_root; switch (GS(id_ref->name)) { case ID_GR: { /* Adding the object to a specific collection outside of the root overridden one is a @@ -1106,7 +1151,8 @@ static void lib_override_library_create_post_process(Main *bmain, if (ID_REAL_USERS(ob_new) != 0) { continue; } - default_instantiating_collection = BKE_id_new(bmain, ID_GR, "OVERRIDE_HIDDEN"); + default_instantiating_collection = static_cast<Collection *>( + BKE_id_new(bmain, ID_GR, "OVERRIDE_HIDDEN")); id_us_min(&default_instantiating_collection->id); /* Hide the collection from viewport and render. */ default_instantiating_collection->flag |= COLLECTION_HIDE_VIEWPORT | @@ -1119,7 +1165,7 @@ static void lib_override_library_create_post_process(Main *bmain, Object *ob_ref = (Object *)id_ref; LISTBASE_FOREACH (Collection *, collection, &bmain->collections) { if (BKE_collection_has_object(collection, ob_ref) && - (view_layer != NULL ? + (view_layer != nullptr ? BKE_view_layer_has_collection(view_layer, collection) : BKE_collection_has_collection(scene->master_collection, collection)) && !ID_IS_LINKED(collection) && !ID_IS_OVERRIDE_LIBRARY(collection)) { @@ -1132,7 +1178,7 @@ static void lib_override_library_create_post_process(Main *bmain, break; } } - if (default_instantiating_collection == NULL) { + if (default_instantiating_collection == nullptr) { default_instantiating_collection = scene->master_collection; } @@ -1141,8 +1187,9 @@ static void lib_override_library_create_post_process(Main *bmain, } } - if (id_root != NULL && !ELEM(default_instantiating_collection, NULL, scene->master_collection)) { - ID *id_ref = id_root->newid != NULL ? id_root->newid : id_root; + if (id_root != nullptr && + !ELEM(default_instantiating_collection, nullptr, scene->master_collection)) { + ID *id_ref = id_root->newid != nullptr ? id_root->newid : id_root; switch (GS(id_ref->name)) { case ID_GR: BKE_collection_add_from_collection( @@ -1150,12 +1197,13 @@ static void lib_override_library_create_post_process(Main *bmain, break; default: /* Add to master collection. */ - BKE_collection_add_from_collection(bmain, scene, NULL, default_instantiating_collection); + BKE_collection_add_from_collection( + bmain, scene, nullptr, default_instantiating_collection); break; } } - BLI_gset_free(all_objects_in_scene, NULL); + BLI_gset_free(all_objects_in_scene, nullptr); } bool BKE_lib_override_library_create(Main *bmain, @@ -1165,29 +1213,40 @@ bool BKE_lib_override_library_create(Main *bmain, ID *id_root_reference, ID *id_hierarchy_root_reference, ID *id_instance_hint, - ID **r_id_root_override) + ID **r_id_root_override, + const bool do_fully_editable) { - if (r_id_root_override != NULL) { - *r_id_root_override = NULL; + if (r_id_root_override != nullptr) { + *r_id_root_override = nullptr; } - if (id_hierarchy_root_reference == NULL) { + if (id_hierarchy_root_reference == nullptr) { id_hierarchy_root_reference = id_root_reference; } - const bool success = lib_override_library_create_do( - bmain, scene, owner_library, id_root_reference, id_hierarchy_root_reference); + const bool success = lib_override_library_create_do(bmain, + scene, + owner_library, + id_root_reference, + id_hierarchy_root_reference, + do_fully_editable); if (!success) { return success; } - if (r_id_root_override != NULL) { + if (r_id_root_override != nullptr) { *r_id_root_override = id_root_reference->newid; } - lib_override_library_create_post_process( - bmain, scene, view_layer, owner_library, id_root_reference, id_instance_hint, NULL, false); + lib_override_library_create_post_process(bmain, + scene, + view_layer, + owner_library, + id_root_reference, + id_instance_hint, + nullptr, + false); /* Cleanup. */ BKE_main_id_newptr_and_tag_clear(bmain); @@ -1199,7 +1258,7 @@ bool BKE_lib_override_library_create(Main *bmain, return success; } -bool BKE_lib_override_library_template_create(struct ID *id) +bool BKE_lib_override_library_template_create(ID *id) { if (ID_IS_LINKED(id)) { return false; @@ -1208,7 +1267,7 @@ bool BKE_lib_override_library_template_create(struct ID *id) return false; } - BKE_lib_override_library_init(id, NULL); + BKE_lib_override_library_init(id, nullptr); return true; } @@ -1219,17 +1278,17 @@ static ID *lib_override_root_find(Main *bmain, ID *id, const int curr_level, int "Levels of dependency relationships between library overrides IDs is way too high, " "skipping further processing loops (involves at least '%s')", id->name); - BLI_assert(0); - return NULL; + return nullptr; } if (!ID_IS_OVERRIDE_LIBRARY(id)) { - BLI_assert(0); - return NULL; + BLI_assert_unreachable(); + return nullptr; } - MainIDRelationsEntry *entry = BLI_ghash_lookup(bmain->relations->relations_from_pointers, id); - BLI_assert(entry != NULL); + MainIDRelationsEntry *entry = static_cast<MainIDRelationsEntry *>( + BLI_ghash_lookup(bmain->relations->relations_from_pointers, id)); + BLI_assert(entry != nullptr); if (entry->tags & MAINIDRELATIONS_ENTRY_TAGS_PROCESSED) { if (ID_IS_OVERRIDE_LIBRARY_REAL(id)) { @@ -1251,7 +1310,7 @@ static ID *lib_override_root_find(Main *bmain, ID *id, const int curr_level, int int best_level_candidate = curr_level; ID *best_root_id_candidate = id; - for (MainIDRelationsEntryItem *from_id_entry = entry->from_ids; from_id_entry != NULL; + for (MainIDRelationsEntryItem *from_id_entry = entry->from_ids; from_id_entry != nullptr; from_id_entry = from_id_entry->next) { if ((from_id_entry->usage_flag & IDWALK_CB_OVERRIDE_LIBRARY_NOT_OVERRIDABLE) != 0) { /* Never consider non-overridable relationships as actual dependencies. */ @@ -1259,7 +1318,7 @@ static ID *lib_override_root_find(Main *bmain, ID *id, const int curr_level, int } ID *from_id = from_id_entry->id_pointer.from; - if (ELEM(from_id, NULL, id)) { + if (ELEM(from_id, nullptr, id)) { continue; } if (!ID_IS_OVERRIDE_LIBRARY(from_id) || (from_id->lib != id->lib)) { @@ -1270,7 +1329,7 @@ static ID *lib_override_root_find(Main *bmain, ID *id, const int curr_level, int /* Recursively process the parent. */ ID *root_id_candidate = lib_override_root_find( bmain, from_id, curr_level + 1, &level_candidate); - if (level_candidate > best_level_candidate && root_id_candidate != NULL) { + if (level_candidate > best_level_candidate && root_id_candidate != nullptr) { best_root_id_candidate = root_id_candidate; best_level_candidate = level_candidate; } @@ -1285,7 +1344,7 @@ static ID *lib_override_root_find(Main *bmain, ID *id, const int curr_level, int bmain, id_owner, curr_level + 1, &best_level_placeholder); } - BLI_assert(best_root_id_candidate != NULL); + BLI_assert(best_root_id_candidate != nullptr); BLI_assert((best_root_id_candidate->flag & LIB_EMBEDDED_DATA_LIB_OVERRIDE) == 0); *r_best_level = best_level_candidate; @@ -1303,14 +1362,14 @@ static void lib_override_root_hierarchy_set(Main *bmain, ID *id_root, ID *id, ID /* Hierarchy root already set, and not matching currently proposed one, try to find which is * best. */ - if (id->override_library->hierarchy_root != NULL) { + if (id->override_library->hierarchy_root != nullptr) { /* Check if given `id_from` matches with the hierarchy of the linked reference ID, in which * case we assume that the given hierarchy root is the 'real' one. * * NOTE: This can fail if user mixed dependencies between several overrides of a same * reference linked hierarchy. Not much to be done in that case, it's virtually impossible to * fix this automatically in a reliable way. */ - if (id_from == NULL || !ID_IS_OVERRIDE_LIBRARY_REAL(id_from)) { + if (id_from == nullptr || !ID_IS_OVERRIDE_LIBRARY_REAL(id_from)) { /* Too complicated to deal with for now. */ CLOG_WARN(&LOG, "Inconsistency in library override hierarchy of ID '%s'.\n" @@ -1323,12 +1382,12 @@ static void lib_override_root_hierarchy_set(Main *bmain, ID *id_root, ID *id, ID } ID *id_from_ref = id_from->override_library->reference; - MainIDRelationsEntry *entry = BLI_ghash_lookup(bmain->relations->relations_from_pointers, - id->override_library->reference); - BLI_assert(entry != NULL); + MainIDRelationsEntry *entry = static_cast<MainIDRelationsEntry *>(BLI_ghash_lookup( + bmain->relations->relations_from_pointers, id->override_library->reference)); + BLI_assert(entry != nullptr); bool do_replace_root = false; - for (MainIDRelationsEntryItem *from_id_entry = entry->from_ids; from_id_entry != NULL; + for (MainIDRelationsEntryItem *from_id_entry = entry->from_ids; from_id_entry != nullptr; from_id_entry = from_id_entry->next) { if ((from_id_entry->usage_flag & IDWALK_CB_OVERRIDE_LIBRARY_NOT_OVERRIDABLE) != 0) { /* Never consider non-overridable relationships as actual dependencies. */ @@ -1365,10 +1424,11 @@ static void lib_override_root_hierarchy_set(Main *bmain, ID *id_root, ID *id, ID id->override_library->hierarchy_root = id_root; } - MainIDRelationsEntry *entry = BLI_ghash_lookup(bmain->relations->relations_from_pointers, id); - BLI_assert(entry != NULL); + MainIDRelationsEntry *entry = static_cast<MainIDRelationsEntry *>( + BLI_ghash_lookup(bmain->relations->relations_from_pointers, id)); + BLI_assert(entry != nullptr); - for (MainIDRelationsEntryItem *to_id_entry = entry->to_ids; to_id_entry != NULL; + for (MainIDRelationsEntryItem *to_id_entry = entry->to_ids; to_id_entry != nullptr; to_id_entry = to_id_entry->next) { if ((to_id_entry->usage_flag & IDWALK_CB_OVERRIDE_LIBRARY_NOT_OVERRIDABLE) != 0) { /* Never consider non-overridable relationships as actual dependencies. */ @@ -1376,7 +1436,7 @@ static void lib_override_root_hierarchy_set(Main *bmain, ID *id_root, ID *id, ID } ID *to_id = *to_id_entry->id_pointer.to; - if (ELEM(to_id, NULL, id)) { + if (ELEM(to_id, nullptr, id)) { continue; } if (!ID_IS_OVERRIDE_LIBRARY(to_id) || (to_id->lib != id->lib)) { @@ -1398,18 +1458,18 @@ void BKE_lib_override_library_main_hierarchy_root_ensure(Main *bmain) if (!ID_IS_OVERRIDE_LIBRARY_REAL(id)) { continue; } - if (id->override_library->hierarchy_root != NULL) { + if (id->override_library->hierarchy_root != nullptr) { if (!ID_IS_OVERRIDE_LIBRARY_REAL(id->override_library->hierarchy_root) || id->override_library->hierarchy_root->lib != id->lib) { CLOG_ERROR( &LOG, "Existing override hierarchy root ('%s') for ID '%s' is invalid, will try to find a " "new valid one", - id->override_library->hierarchy_root != NULL ? + id->override_library->hierarchy_root != nullptr ? id->override_library->hierarchy_root->name : "<NONE>", id->name); - id->override_library->hierarchy_root = NULL; + id->override_library->hierarchy_root = nullptr; } else { continue; @@ -1421,7 +1481,7 @@ void BKE_lib_override_library_main_hierarchy_root_ensure(Main *bmain) int best_level = 0; ID *id_root = lib_override_root_find(bmain, id, best_level, &best_level); - if (!ELEM(id_root->override_library->hierarchy_root, id_root, NULL)) { + if (!ELEM(id_root->override_library->hierarchy_root, id_root, nullptr)) { CLOG_WARN(&LOG, "Potential inconsistency in library override hierarchy of ID '%s', detected as " "part of the hierarchy of '%s', which has a different root '%s'", @@ -1431,9 +1491,9 @@ void BKE_lib_override_library_main_hierarchy_root_ensure(Main *bmain) continue; } - lib_override_root_hierarchy_set(bmain, id_root, id, NULL); + lib_override_root_hierarchy_set(bmain, id_root, id, nullptr); - BLI_assert(id->override_library->hierarchy_root != NULL); + BLI_assert(id->override_library->hierarchy_root != nullptr); } FOREACH_MAIN_ID_END; @@ -1445,14 +1505,14 @@ static void lib_override_library_remap(Main *bmain, GHash *linkedref_to_old_override) { ID *id; - struct IDRemapper *remapper = BKE_id_remapper_create(); - LinkNode *nomain_ids = NULL; + IDRemapper *remapper = BKE_id_remapper_create(); + LinkNode *nomain_ids = nullptr; FOREACH_MAIN_ID_BEGIN (bmain, id) { - if (id->tag & LIB_TAG_DOIT && id->newid != NULL && id->lib == id_root_reference->lib) { + if (id->tag & LIB_TAG_DOIT && id->newid != nullptr && id->lib == id_root_reference->lib) { ID *id_override_new = id->newid; - ID *id_override_old = BLI_ghash_lookup(linkedref_to_old_override, id); - if (id_override_old == NULL) { + ID *id_override_old = static_cast<ID *>(BLI_ghash_lookup(linkedref_to_old_override, id)); + if (id_override_old == nullptr) { continue; } @@ -1464,7 +1524,8 @@ static void lib_override_library_remap(Main *bmain, /* Remap no-main override IDs we just created too. */ GHashIterator linkedref_to_old_override_iter; GHASH_ITER (linkedref_to_old_override_iter, linkedref_to_old_override) { - ID *id_override_old_iter = BLI_ghashIterator_getValue(&linkedref_to_old_override_iter); + ID *id_override_old_iter = static_cast<ID *>( + BLI_ghashIterator_getValue(&linkedref_to_old_override_iter)); if ((id_override_old_iter->tag & LIB_TAG_NO_MAIN) == 0) { continue; } @@ -1480,7 +1541,7 @@ static void lib_override_library_remap(Main *bmain, remapper, ID_REMAP_FORCE_USER_REFCOUNT | ID_REMAP_FORCE_NEVER_NULL_USAGE); BKE_id_remapper_free(remapper); - BLI_linklist_free(nomain_ids, NULL); + BLI_linklist_free(nomain_ids, nullptr); } static bool lib_override_library_resync(Main *bmain, @@ -1500,7 +1561,7 @@ static bool lib_override_library_resync(Main *bmain, ID *id; if (id_root_reference->tag & LIB_TAG_MISSING) { - BKE_reportf(reports != NULL ? reports->reports : NULL, + BKE_reportf(reports != nullptr ? reports->reports : nullptr, RPT_ERROR, "Impossible to resync data-block %s and its dependencies, as its linked reference " "is missing", @@ -1509,14 +1570,15 @@ static bool lib_override_library_resync(Main *bmain, } BKE_main_relations_create(bmain, 0); - LibOverrideGroupTagData data = {.bmain = bmain, - .scene = scene, - .id_root = id_root, - .hierarchy_root_id = id_root->override_library->hierarchy_root, - .tag = LIB_TAG_DOIT, - .missing_tag = LIB_TAG_MISSING, - .is_override = true, - .is_resync = true}; + LibOverrideGroupTagData data{}; + data.bmain = bmain; + data.scene = scene; + data.id_root = id_root; + data.hierarchy_root_id = id_root->override_library->hierarchy_root; + data.tag = LIB_TAG_DOIT; + data.missing_tag = LIB_TAG_MISSING; + data.is_override = true; + data.is_resync = true; lib_override_group_tag_data_object_to_collection_init(&data); /* Mapping 'linked reference IDs' -> 'Local override IDs' of existing overrides, populated from @@ -1526,9 +1588,9 @@ static bool lib_override_library_resync(Main *bmain, /* Only tag linked IDs from related linked reference hierarchy that are actually part of * the sub-trees of each detected sub-roots needing resync. */ - for (LinkNode *resync_root_link = id_resync_roots; resync_root_link != NULL; + for (LinkNode *resync_root_link = id_resync_roots; resync_root_link != nullptr; resync_root_link = resync_root_link->next) { - ID *id_resync_root = resync_root_link->link; + ID *id_resync_root = static_cast<ID *>(resync_root_link->link); BLI_assert(ID_IS_OVERRIDE_LIBRARY_REAL(id_resync_root)); if ((id_resync_root->tag & LIB_TAG_NO_MAIN) != 0) { @@ -1550,12 +1612,12 @@ static bool lib_override_library_resync(Main *bmain, if (id_resync_root_reference->tag & LIB_TAG_MISSING) { BKE_reportf( - reports != NULL ? reports->reports : NULL, + reports != nullptr ? reports->reports : nullptr, RPT_ERROR, "Impossible to resync data-block %s and its dependencies, as its linked reference " "is missing", id_root->name + 2); - BLI_ghash_free(linkedref_to_old_override, NULL, NULL); + BLI_ghash_free(linkedref_to_old_override, nullptr, nullptr); BKE_main_relations_free(bmain); lib_override_group_tag_data_clear(&data); return false; @@ -1594,7 +1656,7 @@ static bool lib_override_library_resync(Main *bmain, /* While this should not happen in typical cases (and won't be properly supported here), * user is free to do all kind of very bad things, including having different local * overrides of a same linked ID in a same hierarchy. */ - IDOverrideLibrary *id_override_library = lib_override_get(bmain, id, NULL); + IDOverrideLibrary *id_override_library = lib_override_get(bmain, id, nullptr); ID *reference_id = id_override_library->reference; if (GS(reference_id->name) != GS(id->name)) { switch (GS(id->name)) { @@ -1666,19 +1728,25 @@ static bool lib_override_library_resync(Main *bmain, * override IDs (including within the old overrides themselves, since those are tagged too * above). */ const bool success = BKE_lib_override_library_create_from_tag( - bmain, NULL, id_root_reference, id_root->override_library->hierarchy_root, NULL, true); + bmain, + nullptr, + id_root_reference, + id_root->override_library->hierarchy_root, + nullptr, + true, + false); if (!success) { - BLI_ghash_free(linkedref_to_old_override, NULL, NULL); + BLI_ghash_free(linkedref_to_old_override, nullptr, nullptr); return success; } ListBase *lb; FOREACH_MAIN_LISTBASE_BEGIN (bmain, lb) { FOREACH_MAIN_LISTBASE_ID_BEGIN (lb, id) { - if (id->tag & LIB_TAG_DOIT && id->newid != NULL && id->lib == id_root_reference->lib) { + if (id->tag & LIB_TAG_DOIT && id->newid != nullptr && id->lib == id_root_reference->lib) { ID *id_override_new = id->newid; - ID *id_override_old = BLI_ghash_lookup(linkedref_to_old_override, id); + ID *id_override_old = static_cast<ID *>(BLI_ghash_lookup(linkedref_to_old_override, id)); BLI_assert((id_override_new->tag & LIB_TAG_LIB_OVERRIDE_NEED_RESYNC) == 0); @@ -1686,14 +1754,14 @@ static bool lib_override_library_resync(Main *bmain, * duplicated from the reference ID with 'no main' option, it should currently be the same * as the reference ID one). */ BLI_assert(/*!ID_IS_LINKED(id_override_new) || */ id_override_new->lib == id->lib); - BLI_assert(id_override_old == NULL || id_override_old->lib == id_root->lib); + BLI_assert(id_override_old == nullptr || id_override_old->lib == id_root->lib); id_override_new->lib = id_root->lib; /* Remap step below will tag directly linked ones properly as needed. */ if (ID_IS_LINKED(id_override_new)) { id_override_new->tag |= LIB_TAG_INDIRECT; } - if (id_override_old != NULL) { + if (id_override_old != nullptr) { /* Swap the names between old override ID and new one. */ char id_name_buf[MAX_ID_NAME]; memcpy(id_name_buf, id_override_old->name, sizeof(id_name_buf)); @@ -1704,6 +1772,8 @@ static bool lib_override_library_resync(Main *bmain, id_override_old->tag |= LIB_TAG_NO_MAIN; id_override_new->tag &= ~LIB_TAG_NO_MAIN; + lib_override_object_posemode_transfer(id_override_new, id_override_old); + if (ID_IS_OVERRIDE_LIBRARY_REAL(id_override_new)) { BLI_assert(ID_IS_OVERRIDE_LIBRARY_REAL(id_override_old)); @@ -1712,10 +1782,10 @@ static bool lib_override_library_resync(Main *bmain, /* Copy over overrides rules from old override ID to new one. */ BLI_duplicatelist(&id_override_new->override_library->properties, &id_override_old->override_library->properties); - IDOverrideLibraryProperty *op_new = - id_override_new->override_library->properties.first; - IDOverrideLibraryProperty *op_old = - id_override_old->override_library->properties.first; + IDOverrideLibraryProperty *op_new = static_cast<IDOverrideLibraryProperty *>( + id_override_new->override_library->properties.first); + IDOverrideLibraryProperty *op_old = static_cast<IDOverrideLibraryProperty *>( + id_override_old->override_library->properties.first); for (; op_new; op_new = op_new->next, op_old = op_old->next) { lib_override_library_property_copy(op_new, op_old); } @@ -1740,20 +1810,20 @@ static bool lib_override_library_resync(Main *bmain, BKE_main_collection_sync(bmain); - LinkNode *id_override_old_list = NULL; + LinkNode *id_override_old_list = nullptr; /* We need to apply override rules in a separate loop, after all ID pointers have been properly * remapped, and all new local override IDs have gotten their proper original names, otherwise * override operations based on those ID names would fail. */ FOREACH_MAIN_ID_BEGIN (bmain, id) { - if (id->tag & LIB_TAG_DOIT && id->newid != NULL && id->lib == id_root_reference->lib) { + if (id->tag & LIB_TAG_DOIT && id->newid != nullptr && id->lib == id_root_reference->lib) { ID *id_override_new = id->newid; if (!ID_IS_OVERRIDE_LIBRARY_REAL(id_override_new)) { continue; } - ID *id_override_old = BLI_ghash_lookup(linkedref_to_old_override, id); + ID *id_override_old = static_cast<ID *>(BLI_ghash_lookup(linkedref_to_old_override, id)); - if (id_override_old == NULL) { + if (id_override_old == nullptr) { continue; } if (ID_IS_OVERRIDE_LIBRARY_REAL(id_override_old)) { @@ -1784,7 +1854,7 @@ static bool lib_override_library_resync(Main *bmain, RNA_struct_override_apply(bmain, &rnaptr_dst, &rnaptr_src, - NULL, + nullptr, id_override_new->override_library, do_hierarchy_enforce ? RNA_OVERRIDE_APPLY_FLAG_IGNORE_ID_POINTERS : @@ -1799,18 +1869,18 @@ static bool lib_override_library_resync(Main *bmain, /* Once overrides have been properly 'transferred' from old to new ID, we can clear ID usages * of the old one. * This is necessary in case said old ID is not in Main anymore. */ - struct IDRemapper *id_remapper = BKE_id_remapper_create(); + IDRemapper *id_remapper = BKE_id_remapper_create(); BKE_libblock_relink_multiple(bmain, id_override_old_list, ID_REMAP_TYPE_CLEANUP, id_remapper, ID_REMAP_FORCE_USER_REFCOUNT | ID_REMAP_FORCE_NEVER_NULL_USAGE); - for (LinkNode *ln_iter = id_override_old_list; ln_iter != NULL; ln_iter = ln_iter->next) { - ID *id_override_old = ln_iter->link; + for (LinkNode *ln_iter = id_override_old_list; ln_iter != nullptr; ln_iter = ln_iter->next) { + ID *id_override_old = static_cast<ID *>(ln_iter->link); id_override_old->tag |= LIB_TAG_NO_USER_REFCOUNT; } BKE_id_remapper_free(id_remapper); - BLI_linklist_free(id_override_old_list, NULL); + BLI_linklist_free(id_override_old_list, nullptr); /* Delete old override IDs. * Note that we have to use tagged group deletion here, since ID deletion also uses @@ -1821,10 +1891,10 @@ static bool lib_override_library_resync(Main *bmain, /* Note that this works because linked IDs are always after local ones (including * overrides), so we will only ever tag an old override ID after we have already checked it * in this loop, hence we cannot untag it later. */ - if (id->newid != NULL && id->lib == id_root_reference->lib) { - ID *id_override_old = BLI_ghash_lookup(linkedref_to_old_override, id); + if (id->newid != nullptr && id->lib == id_root_reference->lib) { + ID *id_override_old = static_cast<ID *>(BLI_ghash_lookup(linkedref_to_old_override, id)); - if (id_override_old != NULL) { + if (id_override_old != nullptr) { id->newid->tag &= ~LIB_TAG_DOIT; id_override_old->tag |= LIB_TAG_DOIT; if (id_override_old->tag & LIB_TAG_NO_MAIN) { @@ -1868,19 +1938,19 @@ static bool lib_override_library_resync(Main *bmain, FOREACH_MAIN_ID_END; /* Cleanup, many pointers in this GHash are already invalid now. */ - BLI_ghash_free(linkedref_to_old_override, NULL, NULL); + BLI_ghash_free(linkedref_to_old_override, nullptr, nullptr); BKE_id_multi_tagged_delete(bmain); /* At this point, `id_root` may have been resynced, therefore deleted. In that case we need to * update it to its new version. */ - if (id_root_reference->newid != NULL) { + if (id_root_reference->newid != nullptr) { id_root = id_root_reference->newid; } if (user_edited_overrides_deletion_count > 0) { - BKE_reportf(reports != NULL ? reports->reports : NULL, + BKE_reportf(reports != nullptr ? reports->reports : nullptr, RPT_WARNING, "During resync of data-block %s, %d obsolete overrides were deleted, that had " "local changes defined by user", @@ -1897,7 +1967,7 @@ static bool lib_override_library_resync(Main *bmain, lib_override_library_create_post_process(bmain, scene, view_layer, - NULL, + nullptr, id_root_reference, id_root, override_resync_residual_storage, @@ -1919,8 +1989,10 @@ bool BKE_lib_override_library_resync(Main *bmain, const bool do_hierarchy_enforce, BlendFileReadReport *reports) { - ListBase no_main_ids_list = {NULL}; - LinkNode id_resync_roots = {.link = id_root, .next = NULL}; + ListBase no_main_ids_list = {nullptr}; + LinkNode id_resync_roots{}; + id_resync_roots.link = id_root; + id_resync_roots.next = nullptr; const bool success = lib_override_library_resync(bmain, scene, @@ -1954,14 +2026,14 @@ static ID *lib_override_library_main_resync_root_get(Main *bmain, ID *id) { if (!ID_IS_OVERRIDE_LIBRARY_REAL(id)) { const IDTypeInfo *id_type = BKE_idtype_get_info_from_id(id); - if (id_type->owner_get != NULL) { + if (id_type->owner_get != nullptr) { id = id_type->owner_get(bmain, id); } BLI_assert(ID_IS_OVERRIDE_LIBRARY_REAL(id)); } ID *hierarchy_root_id = id->override_library->hierarchy_root; - BLI_assert(hierarchy_root_id != NULL); + BLI_assert(hierarchy_root_id != nullptr); BLI_assert(ID_IS_OVERRIDE_LIBRARY_REAL(hierarchy_root_id)); return hierarchy_root_id; } @@ -1996,8 +2068,9 @@ static bool lib_override_resync_tagging_finalize_recurse( return false; } - MainIDRelationsEntry *entry = BLI_ghash_lookup(bmain->relations->relations_from_pointers, id); - BLI_assert(entry != NULL); + MainIDRelationsEntry *entry = static_cast<MainIDRelationsEntry *>( + BLI_ghash_lookup(bmain->relations->relations_from_pointers, id)); + BLI_assert(entry != nullptr); if (entry->tags & MAINIDRELATIONS_ENTRY_TAGS_PROCESSED) { /* This ID has already been processed. */ @@ -2031,7 +2104,7 @@ static bool lib_override_resync_tagging_finalize_recurse( id->tag &= ~LIB_TAG_LIB_OVERRIDE_NEED_RESYNC; bool is_ancestor_tagged_for_resync = false; - for (MainIDRelationsEntryItem *entry_item = entry->from_ids; entry_item != NULL; + for (MainIDRelationsEntryItem *entry_item = entry->from_ids; entry_item != nullptr; entry_item = entry_item->next) { if (entry_item->usage_flag & (IDWALK_CB_OVERRIDE_LIBRARY_NOT_OVERRIDABLE | IDWALK_CB_LOOPBACK)) { @@ -2088,13 +2161,11 @@ static bool lib_override_resync_tagging_finalize_recurse( CLOG_INFO(&LOG, 4, "Found root ID '%s' for resync root ID '%s'", id_root->name, id->name); - if (id_root->override_library == NULL) { - BLI_assert(0); - } + BLI_assert(id_root->override_library != nullptr); LinkNodePair **id_resync_roots_p; if (!BLI_ghash_ensure_p(id_roots, id_root, (void ***)&id_resync_roots_p)) { - *id_resync_roots_p = MEM_callocN(sizeof(**id_resync_roots_p), __func__); + *id_resync_roots_p = MEM_cnew<LinkNodePair>(__func__); } BLI_linklist_append(*id_resync_roots_p, id); @@ -2129,13 +2200,14 @@ static void lib_override_library_main_resync_on_library_indirect_level( /* Detect all linked data that would need to be overridden if we had to create an override from * those used by current existing overrides. */ - LibOverrideGroupTagData data = {.bmain = bmain, - .scene = scene, - .id_root = NULL, - .tag = LIB_TAG_DOIT, - .missing_tag = LIB_TAG_MISSING, - .is_override = false, - .is_resync = true}; + LibOverrideGroupTagData data = {}; + data.bmain = bmain; + data.scene = scene; + data.id_root = nullptr; + data.tag = LIB_TAG_DOIT; + data.missing_tag = LIB_TAG_MISSING; + data.is_override = false; + data.is_resync = true; lib_override_group_tag_data_object_to_collection_init(&data); ID *id; FOREACH_MAIN_ID_BEGIN (bmain, id) { @@ -2188,10 +2260,11 @@ static void lib_override_library_main_resync_on_library_indirect_level( continue; } - MainIDRelationsEntry *entry = BLI_ghash_lookup(bmain->relations->relations_from_pointers, id); - BLI_assert(entry != NULL); + MainIDRelationsEntry *entry = static_cast<MainIDRelationsEntry *>( + BLI_ghash_lookup(bmain->relations->relations_from_pointers, id)); + BLI_assert(entry != nullptr); - for (MainIDRelationsEntryItem *entry_item = entry->to_ids; entry_item != NULL; + for (MainIDRelationsEntryItem *entry_item = entry->to_ids; entry_item != nullptr; entry_item = entry_item->next) { if (entry_item->usage_flag & IDWALK_CB_OVERRIDE_LIBRARY_NOT_OVERRIDABLE) { continue; @@ -2224,13 +2297,14 @@ static void lib_override_library_main_resync_on_library_indirect_level( BKE_main_relations_tag_set(bmain, MAINIDRELATIONS_ENTRY_TAGS_PROCESSED, false); GHashIterator *id_roots_iter = BLI_ghashIterator_new(id_roots); while (!BLI_ghashIterator_done(id_roots_iter)) { - ID *id_root = BLI_ghashIterator_getKey(id_roots_iter); - LinkNodePair *id_resync_roots = BLI_ghashIterator_getValue(id_roots_iter); + ID *id_root = static_cast<ID *>(BLI_ghashIterator_getKey(id_roots_iter)); + LinkNodePair *id_resync_roots = static_cast<LinkNodePair *>( + BLI_ghashIterator_getValue(id_roots_iter)); CLOG_INFO( &LOG, 2, "Checking validity of computed TODO data for root '%s'... \n", id_root->name); - for (LinkNode *id_resync_root_iter = id_resync_roots->list; id_resync_root_iter != NULL; + for (LinkNode *id_resync_root_iter = id_resync_roots->list; id_resync_root_iter != nullptr; id_resync_root_iter = id_resync_root_iter->next) { - ID *id_resync_root = id_resync_root_iter->link; + ID *id_resync_root = static_cast<ID *>(id_resync_root_iter->link); BLI_assert(id_resync_root == id_root || !BLI_ghash_haskey(id_roots, id_resync_root)); if (id_resync_root == id_root) { BLI_assert(id_resync_root_iter == id_resync_roots->list && @@ -2248,13 +2322,14 @@ static void lib_override_library_main_resync_on_library_indirect_level( BKE_main_relations_free(bmain); BKE_main_id_tag_all(bmain, LIB_TAG_DOIT, false); - ListBase no_main_ids_list = {NULL}; + ListBase no_main_ids_list = {nullptr}; GHashIterator *id_roots_iter = BLI_ghashIterator_new(id_roots); while (!BLI_ghashIterator_done(id_roots_iter)) { - ID *id_root = BLI_ghashIterator_getKey(id_roots_iter); + ID *id_root = static_cast<ID *>(BLI_ghashIterator_getKey(id_roots_iter)); Library *library = id_root->lib; - LinkNodePair *id_resync_roots = BLI_ghashIterator_getValue(id_roots_iter); + LinkNodePair *id_resync_roots = static_cast<LinkNodePair *>( + BLI_ghashIterator_getValue(id_roots_iter)); if (ID_IS_LINKED(id_root)) { id_root->lib->tag |= LIBRARY_TAG_RESYNC_REQUIRED; @@ -2286,7 +2361,7 @@ static void lib_override_library_main_resync_on_library_indirect_level( } } - BLI_linklist_free(id_resync_roots->list, NULL); + BLI_linklist_free(id_resync_roots->list, nullptr); BLI_ghashIterator_step(id_roots_iter); } BLI_ghashIterator_free(id_roots_iter); @@ -2314,10 +2389,10 @@ static void lib_override_library_main_resync_on_library_indirect_level( } FOREACH_MAIN_ID_END; - BLI_ghash_free(id_roots, NULL, MEM_freeN); + BLI_ghash_free(id_roots, nullptr, MEM_freeN); /* In some fairly rare (and degenerate) cases, some root ID from other liboverrides may have been - * freed, and therefore set to NULL. Attempt to fix this as best as possible. */ + * freed, and therefore set to nullptr. Attempt to fix this as best as possible. */ BKE_lib_override_library_main_hierarchy_root_ensure(bmain); if (do_reports_recursive_resync_timing) { @@ -2332,7 +2407,7 @@ static int lib_override_sort_libraries_func(LibraryIDLinkCallbackData *cb_data) } ID *id_owner = cb_data->id_owner; ID *id = *cb_data->id_pointer; - if (id != NULL && ID_IS_LINKED(id) && id->lib != id_owner->lib) { + if (id != nullptr && ID_IS_LINKED(id) && id->lib != id_owner->lib) { const int owner_library_indirect_level = ID_IS_LINKED(id_owner) ? id_owner->lib->temp_index : 0; if (owner_library_indirect_level > 200) { @@ -2344,7 +2419,6 @@ static int lib_override_sort_libraries_func(LibraryIDLinkCallbackData *cb_data) id_owner->lib->filepath, id->name, id->lib->filepath); - BLI_assert(0); return IDWALK_RET_NOP; } @@ -2394,12 +2468,13 @@ void BKE_lib_override_library_main_resync(Main *bmain, /* We use a specific collection to gather/store all 'orphaned' override collections and objects * generated by re-sync-process. This avoids putting them in scene's master collection. */ #define OVERRIDE_RESYNC_RESIDUAL_STORAGE_NAME "OVERRIDE_RESYNC_LEFTOVERS" - Collection *override_resync_residual_storage = BLI_findstring( - &bmain->collections, OVERRIDE_RESYNC_RESIDUAL_STORAGE_NAME, offsetof(ID, name) + 2); - if (override_resync_residual_storage != NULL && ID_IS_LINKED(override_resync_residual_storage)) { - override_resync_residual_storage = NULL; + Collection *override_resync_residual_storage = static_cast<Collection *>(BLI_findstring( + &bmain->collections, OVERRIDE_RESYNC_RESIDUAL_STORAGE_NAME, offsetof(ID, name) + 2)); + if (override_resync_residual_storage != nullptr && + ID_IS_LINKED(override_resync_residual_storage)) { + override_resync_residual_storage = nullptr; } - if (override_resync_residual_storage == NULL) { + if (override_resync_residual_storage == nullptr) { override_resync_residual_storage = BKE_collection_add( bmain, scene->master_collection, OVERRIDE_RESYNC_RESIDUAL_STORAGE_NAME); /* Hide the collection from viewport and render. */ @@ -2427,7 +2502,7 @@ void BKE_lib_override_library_main_resync(Main *bmain, /* Essentially ensures that potentially new overrides of new objects will be instantiated. */ lib_override_library_create_post_process( - bmain, scene, view_layer, NULL, NULL, NULL, override_resync_residual_storage, true); + bmain, scene, view_layer, nullptr, nullptr, nullptr, override_resync_residual_storage, true); if (BKE_collection_is_empty(override_resync_residual_storage)) { BKE_collection_delete(bmain, override_resync_residual_storage, true); @@ -2450,14 +2525,15 @@ void BKE_lib_override_library_delete(Main *bmain, ID *id_root) /* Tag all library overrides in the chains of dependencies from the given root one. */ BKE_main_relations_create(bmain, 0); - LibOverrideGroupTagData data = {.bmain = bmain, - .scene = NULL, - .id_root = id_root, - .hierarchy_root_id = id_root->override_library->hierarchy_root, - .tag = LIB_TAG_DOIT, - .missing_tag = LIB_TAG_MISSING, - .is_override = true, - .is_resync = false}; + LibOverrideGroupTagData data{}; + data.bmain = bmain; + data.scene = nullptr; + data.id_root = id_root; + data.hierarchy_root_id = id_root->override_library->hierarchy_root; + data.tag = LIB_TAG_DOIT; + data.missing_tag = LIB_TAG_MISSING; + data.is_override = true; + data.is_resync = false; lib_override_group_tag_data_object_to_collection_init(&data); lib_override_overrides_group_tag(&data); @@ -2499,19 +2575,19 @@ void BKE_lib_override_library_make_local(ID *id) BKE_lib_override_library_free(&id->override_library, true); Key *shape_key = BKE_key_from_id(id); - if (shape_key != NULL) { + if (shape_key != nullptr) { shape_key->id.flag &= ~LIB_EMBEDDED_DATA_LIB_OVERRIDE; } if (GS(id->name) == ID_SCE) { Collection *master_collection = ((Scene *)id)->master_collection; - if (master_collection != NULL) { + if (master_collection != nullptr) { master_collection->id.flag &= ~LIB_EMBEDDED_DATA_LIB_OVERRIDE; } } bNodeTree *node_tree = ntreeFromID(id); - if (node_tree != NULL) { + if (node_tree != nullptr) { node_tree->id.flag &= ~LIB_EMBEDDED_DATA_LIB_OVERRIDE; } } @@ -2519,8 +2595,8 @@ void BKE_lib_override_library_make_local(ID *id) BLI_INLINE IDOverrideLibraryRuntime *override_library_rna_path_runtime_ensure( IDOverrideLibrary *override) { - if (override->runtime == NULL) { - override->runtime = MEM_callocN(sizeof(*override->runtime), __func__); + if (override->runtime == nullptr) { + override->runtime = MEM_cnew<IDOverrideLibraryRuntime>(__func__); } return override->runtime; } @@ -2529,10 +2605,13 @@ BLI_INLINE IDOverrideLibraryRuntime *override_library_rna_path_runtime_ensure( BLI_INLINE GHash *override_library_rna_path_mapping_ensure(IDOverrideLibrary *override) { IDOverrideLibraryRuntime *override_runtime = override_library_rna_path_runtime_ensure(override); - if (override_runtime->rna_path_to_override_properties == NULL) { + if (override_runtime->rna_path_to_override_properties == nullptr) { override_runtime->rna_path_to_override_properties = BLI_ghash_new( BLI_ghashutil_strhash_p_murmur, BLI_ghashutil_strcmp, __func__); - for (IDOverrideLibraryProperty *op = override->properties.first; op != NULL; op = op->next) { + for (IDOverrideLibraryProperty *op = + static_cast<IDOverrideLibraryProperty *>(override->properties.first); + op != nullptr; + op = op->next) { BLI_ghash_insert(override_runtime->rna_path_to_override_properties, op->rna_path, op); } } @@ -2544,7 +2623,7 @@ IDOverrideLibraryProperty *BKE_lib_override_library_property_find(IDOverrideLibr const char *rna_path) { GHash *override_runtime = override_library_rna_path_mapping_ensure(override); - return BLI_ghash_lookup(override_runtime, rna_path); + return static_cast<IDOverrideLibraryProperty *>(BLI_ghash_lookup(override_runtime, rna_path)); } IDOverrideLibraryProperty *BKE_lib_override_library_property_get(IDOverrideLibrary *override, @@ -2553,8 +2632,8 @@ IDOverrideLibraryProperty *BKE_lib_override_library_property_get(IDOverrideLibra { IDOverrideLibraryProperty *op = BKE_lib_override_library_property_find(override, rna_path); - if (op == NULL) { - op = MEM_callocN(sizeof(IDOverrideLibraryProperty), __func__); + if (op == nullptr) { + op = MEM_cnew<IDOverrideLibraryProperty>(__func__); op->rna_path = BLI_strdup(rna_path); BLI_addtail(&override->properties, op); @@ -2588,8 +2667,9 @@ void lib_override_library_property_copy(IDOverrideLibraryProperty *op_dst, op_dst->rna_path = BLI_strdup(op_src->rna_path); BLI_duplicatelist(&op_dst->operations, &op_src->operations); - for (IDOverrideLibraryPropertyOperation *opop_dst = op_dst->operations.first, - *opop_src = op_src->operations.first; + for (IDOverrideLibraryPropertyOperation * + opop_dst = static_cast<IDOverrideLibraryPropertyOperation *>(op_dst->operations.first), + *opop_src = static_cast<IDOverrideLibraryPropertyOperation *>(op_src->operations.first); opop_dst; opop_dst = opop_dst->next, opop_src = opop_src->next) { lib_override_library_property_operation_copy(opop_dst, opop_src); @@ -2598,7 +2678,7 @@ void lib_override_library_property_copy(IDOverrideLibraryProperty *op_dst, void lib_override_library_property_clear(IDOverrideLibraryProperty *op) { - BLI_assert(op->rna_path != NULL); + BLI_assert(op->rna_path != nullptr); MEM_freeN(op->rna_path); @@ -2611,11 +2691,11 @@ void lib_override_library_property_clear(IDOverrideLibraryProperty *op) void BKE_lib_override_library_property_delete(IDOverrideLibrary *override, IDOverrideLibraryProperty *override_property) { - if (!ELEM(NULL, override->runtime, override->runtime->rna_path_to_override_properties)) { + if (!ELEM(nullptr, override->runtime, override->runtime->rna_path_to_override_properties)) { BLI_ghash_remove(override->runtime->rna_path_to_override_properties, override_property->rna_path, - NULL, - NULL); + nullptr, + nullptr); } lib_override_library_property_clear(override_property); BLI_freelinkN(&override->properties, override_property); @@ -2637,74 +2717,75 @@ IDOverrideLibraryPropertyOperation *BKE_lib_override_library_property_operation_ *r_strict = true; } - if (subitem_locname != NULL) { - opop = BLI_findstring_ptr(&override_property->operations, - subitem_locname, - offsetof(IDOverrideLibraryPropertyOperation, subitem_local_name)); + if (subitem_locname != nullptr) { + opop = static_cast<IDOverrideLibraryPropertyOperation *>( + BLI_findstring_ptr(&override_property->operations, + subitem_locname, + offsetof(IDOverrideLibraryPropertyOperation, subitem_local_name))); - if (opop == NULL) { - return NULL; + if (opop == nullptr) { + return nullptr; } - if (subitem_refname == NULL || opop->subitem_reference_name == NULL) { - return subitem_refname == opop->subitem_reference_name ? opop : NULL; + if (subitem_refname == nullptr || opop->subitem_reference_name == nullptr) { + return subitem_refname == opop->subitem_reference_name ? opop : nullptr; } - return (subitem_refname != NULL && opop->subitem_reference_name != NULL && + return (subitem_refname != nullptr && opop->subitem_reference_name != nullptr && STREQ(subitem_refname, opop->subitem_reference_name)) ? opop : - NULL; + nullptr; } - if (subitem_refname != NULL) { - opop = BLI_findstring_ptr( - &override_property->operations, - subitem_refname, - offsetof(IDOverrideLibraryPropertyOperation, subitem_reference_name)); + if (subitem_refname != nullptr) { + opop = static_cast<IDOverrideLibraryPropertyOperation *>( + BLI_findstring_ptr(&override_property->operations, + subitem_refname, + offsetof(IDOverrideLibraryPropertyOperation, subitem_reference_name))); - if (opop == NULL) { - return NULL; + if (opop == nullptr) { + return nullptr; } - if (subitem_locname == NULL || opop->subitem_local_name == NULL) { - return subitem_locname == opop->subitem_local_name ? opop : NULL; + if (subitem_locname == nullptr || opop->subitem_local_name == nullptr) { + return subitem_locname == opop->subitem_local_name ? opop : nullptr; } - return (subitem_locname != NULL && opop->subitem_local_name != NULL && + return (subitem_locname != nullptr && opop->subitem_local_name != nullptr && STREQ(subitem_locname, opop->subitem_local_name)) ? opop : - NULL; + nullptr; } - if ((opop = BLI_listbase_bytes_find( + if ((opop = static_cast<IDOverrideLibraryPropertyOperation *>(BLI_listbase_bytes_find( &override_property->operations, &subitem_locindex, sizeof(subitem_locindex), - offsetof(IDOverrideLibraryPropertyOperation, subitem_local_index)))) { - return ELEM(subitem_refindex, -1, opop->subitem_reference_index) ? opop : NULL; + offsetof(IDOverrideLibraryPropertyOperation, subitem_local_index))))) { + return ELEM(subitem_refindex, -1, opop->subitem_reference_index) ? opop : nullptr; } - if ((opop = BLI_listbase_bytes_find( + if ((opop = static_cast<IDOverrideLibraryPropertyOperation *>(BLI_listbase_bytes_find( &override_property->operations, &subitem_refindex, sizeof(subitem_refindex), - offsetof(IDOverrideLibraryPropertyOperation, subitem_reference_index)))) { - return ELEM(subitem_locindex, -1, opop->subitem_local_index) ? opop : NULL; + offsetof(IDOverrideLibraryPropertyOperation, subitem_reference_index))))) { + return ELEM(subitem_locindex, -1, opop->subitem_local_index) ? opop : nullptr; } /* `index == -1` means all indices, that is a valid fallback in case we requested specific index. */ if (!strict && (subitem_locindex != subitem_defindex) && - (opop = BLI_listbase_bytes_find( + (opop = static_cast<IDOverrideLibraryPropertyOperation *>(BLI_listbase_bytes_find( &override_property->operations, &subitem_defindex, sizeof(subitem_defindex), - offsetof(IDOverrideLibraryPropertyOperation, subitem_local_index)))) { + offsetof(IDOverrideLibraryPropertyOperation, subitem_local_index))))) { if (r_strict) { *r_strict = false; } return opop; } - return NULL; + return nullptr; } IDOverrideLibraryPropertyOperation *BKE_lib_override_library_property_operation_get( @@ -2727,8 +2808,8 @@ IDOverrideLibraryPropertyOperation *BKE_lib_override_library_property_operation_ strict, r_strict); - if (opop == NULL) { - opop = MEM_callocN(sizeof(IDOverrideLibraryPropertyOperation), __func__); + if (opop == nullptr) { + opop = MEM_cnew<IDOverrideLibraryPropertyOperation>(__func__); opop->operation = operation; if (subitem_locname) { opop->subitem_local_name = BLI_strdup(subitem_locname); @@ -2782,13 +2863,13 @@ void BKE_lib_override_library_property_operation_delete( } bool BKE_lib_override_library_property_operation_operands_validate( - struct IDOverrideLibraryPropertyOperation *override_property_operation, - struct PointerRNA *ptr_dst, - struct PointerRNA *ptr_src, - struct PointerRNA *ptr_storage, - struct PropertyRNA *prop_dst, - struct PropertyRNA *prop_src, - struct PropertyRNA *prop_storage) + IDOverrideLibraryPropertyOperation *override_property_operation, + PointerRNA *ptr_dst, + PointerRNA *ptr_src, + PointerRNA *ptr_storage, + PropertyRNA *prop_dst, + PropertyRNA *prop_src, + PropertyRNA *prop_storage) { switch (override_property_operation->operation) { case IDOVERRIDE_LIBRARY_OP_NOOP: @@ -2798,7 +2879,7 @@ bool BKE_lib_override_library_property_operation_operands_validate( case IDOVERRIDE_LIBRARY_OP_SUBTRACT: ATTR_FALLTHROUGH; case IDOVERRIDE_LIBRARY_OP_MULTIPLY: - if (ptr_storage == NULL || ptr_storage->data == NULL || prop_storage == NULL) { + if (ptr_storage == nullptr || ptr_storage->data == nullptr || prop_storage == nullptr) { BLI_assert_msg(0, "Missing data to apply differential override operation."); return false; } @@ -2808,8 +2889,8 @@ bool BKE_lib_override_library_property_operation_operands_validate( case IDOVERRIDE_LIBRARY_OP_INSERT_BEFORE: ATTR_FALLTHROUGH; case IDOVERRIDE_LIBRARY_OP_REPLACE: - if ((ptr_dst == NULL || ptr_dst->data == NULL || prop_dst == NULL) || - (ptr_src == NULL || ptr_src->data == NULL || prop_src == NULL)) { + if ((ptr_dst == nullptr || ptr_dst->data == nullptr || prop_dst == nullptr) || + (ptr_src == nullptr || ptr_src->data == nullptr || prop_src == nullptr)) { BLI_assert_msg(0, "Missing data to apply override operation."); return false; } @@ -2820,10 +2901,10 @@ bool BKE_lib_override_library_property_operation_operands_validate( void BKE_lib_override_library_validate(Main *UNUSED(bmain), ID *id, ReportList *reports) { - if (id->override_library == NULL) { + if (id->override_library == nullptr) { return; } - if (id->override_library->reference == NULL) { + if (id->override_library->reference == nullptr) { /* This is a template ID, could be linked or local, not an override. */ return; } @@ -2834,7 +2915,7 @@ void BKE_lib_override_library_validate(Main *UNUSED(bmain), ID *id, ReportList * RPT_ERROR, "Data corruption: data-block '%s' is using itself as library override reference", id->name); - id->override_library->reference = NULL; + id->override_library->reference = nullptr; return; } if (!ID_IS_LINKED(id->override_library->reference)) { @@ -2846,7 +2927,7 @@ void BKE_lib_override_library_validate(Main *UNUSED(bmain), ID *id, ReportList * "library override reference", id->name, id->override_library->reference->name); - id->override_library->reference = NULL; + id->override_library->reference = nullptr; return; } } @@ -2856,7 +2937,7 @@ void BKE_lib_override_library_main_validate(Main *bmain, ReportList *reports) ID *id; FOREACH_MAIN_ID_BEGIN (bmain, id) { - if (id->override_library != NULL) { + if (id->override_library != nullptr) { BKE_lib_override_library_validate(bmain, id, reports); } } @@ -2869,7 +2950,7 @@ bool BKE_lib_override_library_status_check_local(Main *bmain, ID *local) ID *reference = local->override_library->reference; - if (reference == NULL) { + if (reference == nullptr) { /* This is an override template, local status is always OK! */ return true; } @@ -2883,10 +2964,10 @@ bool BKE_lib_override_library_status_check_local(Main *bmain, ID *local) Object *ob_local = (Object *)local; if (ob_local->type == OB_ARMATURE) { Object *ob_reference = (Object *)local->override_library->reference; - BLI_assert(ob_local->data != NULL); - BLI_assert(ob_reference->data != NULL); - BKE_pose_ensure(bmain, ob_local, ob_local->data, true); - BKE_pose_ensure(bmain, ob_reference, ob_reference->data, true); + BLI_assert(ob_local->data != nullptr); + BLI_assert(ob_reference->data != nullptr); + BKE_pose_ensure(bmain, ob_local, static_cast<bArmature *>(ob_local->data), true); + BKE_pose_ensure(bmain, ob_reference, static_cast<bArmature *>(ob_reference->data), true); } } @@ -2896,15 +2977,16 @@ bool BKE_lib_override_library_status_check_local(Main *bmain, ID *local) RNA_id_pointer_create(local, &rnaptr_local); RNA_id_pointer_create(reference, &rnaptr_reference); - if (!RNA_struct_override_matches(bmain, - &rnaptr_local, - &rnaptr_reference, - NULL, - 0, - local->override_library, - RNA_OVERRIDE_COMPARE_IGNORE_NON_OVERRIDABLE | - RNA_OVERRIDE_COMPARE_IGNORE_OVERRIDDEN, - NULL)) { + if (!RNA_struct_override_matches( + bmain, + &rnaptr_local, + &rnaptr_reference, + nullptr, + 0, + local->override_library, + (eRNAOverrideMatch)(RNA_OVERRIDE_COMPARE_IGNORE_NON_OVERRIDABLE | + RNA_OVERRIDE_COMPARE_IGNORE_OVERRIDDEN), + nullptr)) { local->tag &= ~LIB_TAG_OVERRIDE_LIBRARY_REFOK; return false; } @@ -2918,7 +3000,7 @@ bool BKE_lib_override_library_status_check_reference(Main *bmain, ID *local) ID *reference = local->override_library->reference; - if (reference == NULL) { + if (reference == nullptr) { /* This is an override template, reference is virtual, so its status is always OK! */ return true; } @@ -2942,10 +3024,10 @@ bool BKE_lib_override_library_status_check_reference(Main *bmain, ID *local) Object *ob_local = (Object *)local; if (ob_local->type == OB_ARMATURE) { Object *ob_reference = (Object *)local->override_library->reference; - BLI_assert(ob_local->data != NULL); - BLI_assert(ob_reference->data != NULL); - BKE_pose_ensure(bmain, ob_local, ob_local->data, true); - BKE_pose_ensure(bmain, ob_reference, ob_reference->data, true); + BLI_assert(ob_local->data != nullptr); + BLI_assert(ob_reference->data != nullptr); + BKE_pose_ensure(bmain, ob_local, static_cast<bArmature *>(ob_local->data), true); + BKE_pose_ensure(bmain, ob_reference, static_cast<bArmature *>(ob_reference->data), true); } } @@ -2956,11 +3038,11 @@ bool BKE_lib_override_library_status_check_reference(Main *bmain, ID *local) if (!RNA_struct_override_matches(bmain, &rnaptr_local, &rnaptr_reference, - NULL, + nullptr, 0, local->override_library, RNA_OVERRIDE_COMPARE_IGNORE_OVERRIDDEN, - NULL)) { + nullptr)) { local->tag &= ~LIB_TAG_OVERRIDE_LIBRARY_REFOK; return false; } @@ -2971,8 +3053,8 @@ bool BKE_lib_override_library_status_check_reference(Main *bmain, ID *local) bool BKE_lib_override_library_operations_create(Main *bmain, ID *local) { BLI_assert(!ID_IS_LINKED(local)); - BLI_assert(local->override_library != NULL); - const bool is_template = (local->override_library->reference == NULL); + BLI_assert(local->override_library != nullptr); + const bool is_template = (local->override_library->reference == nullptr); bool created = false; if (!is_template) { @@ -2990,10 +3072,10 @@ bool BKE_lib_override_library_operations_create(Main *bmain, ID *local) Object *ob_local = (Object *)local; if (ob_local->type == OB_ARMATURE) { Object *ob_reference = (Object *)local->override_library->reference; - BLI_assert(ob_local->data != NULL); - BLI_assert(ob_reference->data != NULL); - BKE_pose_ensure(bmain, ob_local, ob_local->data, true); - BKE_pose_ensure(bmain, ob_reference, ob_reference->data, true); + BLI_assert(ob_local->data != nullptr); + BLI_assert(ob_reference->data != nullptr); + BKE_pose_ensure(bmain, ob_local, static_cast<bArmature *>(ob_local->data), true); + BKE_pose_ensure(bmain, ob_reference, static_cast<bArmature *>(ob_reference->data), true); } } @@ -3001,15 +3083,16 @@ bool BKE_lib_override_library_operations_create(Main *bmain, ID *local) RNA_id_pointer_create(local, &rnaptr_local); RNA_id_pointer_create(local->override_library->reference, &rnaptr_reference); - eRNAOverrideMatchResult report_flags = 0; - RNA_struct_override_matches(bmain, - &rnaptr_local, - &rnaptr_reference, - NULL, - 0, - local->override_library, - RNA_OVERRIDE_COMPARE_CREATE | RNA_OVERRIDE_COMPARE_RESTORE, - &report_flags); + eRNAOverrideMatchResult report_flags = (eRNAOverrideMatchResult)0; + RNA_struct_override_matches( + bmain, + &rnaptr_local, + &rnaptr_reference, + nullptr, + 0, + local->override_library, + (eRNAOverrideMatch)(RNA_OVERRIDE_COMPARE_CREATE | RNA_OVERRIDE_COMPARE_RESTORE), + &report_flags); if (report_flags & RNA_OVERRIDE_MATCH_RESULT_CREATED) { created = true; @@ -3035,8 +3118,9 @@ struct LibOverrideOpCreateData { static void lib_override_library_operations_create_cb(TaskPool *__restrict pool, void *taskdata) { - struct LibOverrideOpCreateData *create_data = BLI_task_pool_user_data(pool); - ID *id = taskdata; + LibOverrideOpCreateData *create_data = static_cast<LibOverrideOpCreateData *>( + BLI_task_pool_user_data(pool)); + ID *id = static_cast<ID *>(taskdata); if (BKE_lib_override_library_operations_create(create_data->bmain, id)) { /* Technically no need for atomic, all jobs write the same value and we only care if one did @@ -3065,12 +3149,14 @@ bool BKE_lib_override_library_main_operations_create(Main *bmain, const bool for * #BKE_lib_override_library_operations_create is not a problem then. */ LISTBASE_FOREACH (Object *, ob, &bmain->objects) { if (ob->type == OB_ARMATURE) { - BLI_assert(ob->data != NULL); - BKE_pose_ensure(bmain, ob, ob->data, true); + BLI_assert(ob->data != nullptr); + BKE_pose_ensure(bmain, ob, static_cast<bArmature *>(ob->data), true); } } - struct LibOverrideOpCreateData create_pool_data = {.bmain = bmain, .changed = false}; + LibOverrideOpCreateData create_pool_data{}; + create_pool_data.bmain = bmain; + create_pool_data.changed = false; TaskPool *task_pool = BLI_task_pool_create(&create_pool_data, TASK_PRIORITY_HIGH); FOREACH_MAIN_ID_BEGIN (bmain, id) { @@ -3081,14 +3167,15 @@ bool BKE_lib_override_library_main_operations_create(Main *bmain, const bool for if (GS(id->name) == ID_OB) { Object *ob = (Object *)id; if (ob->type == OB_ARMATURE) { - BLI_assert(ob->data != NULL); - BKE_pose_ensure(bmain, ob, ob->data, true); + BLI_assert(ob->data != nullptr); + BKE_pose_ensure(bmain, ob, static_cast<bArmature *>(ob->data), true); } } /* Only check overrides if we do have the real reference data available, and not some empty * 'placeholder' for missing data (broken links). */ if ((id->override_library->reference->tag & LIB_TAG_MISSING) == 0) { - BLI_task_pool_push(task_pool, lib_override_library_operations_create_cb, id, false, NULL); + BLI_task_pool_push( + task_pool, lib_override_library_operations_create_cb, id, false, nullptr); } else { BKE_lib_override_library_properties_tag( @@ -3159,10 +3246,10 @@ static bool lib_override_library_id_reset_do(Main *bmain, ptr = RNA_property_pointer_get(&ptr, prop); ptr_lib = RNA_property_pointer_get(&ptr_lib, prop_lib); } - if (ptr.owner_id != NULL && ptr_lib.owner_id != NULL) { + if (ptr.owner_id != nullptr && ptr_lib.owner_id != nullptr) { BLI_assert(ptr.type == ptr_lib.type); do_op_delete = !(RNA_struct_is_ID(ptr.type) && - ptr.owner_id->override_library != NULL && + ptr.owner_id->override_library != nullptr && ptr.owner_id->override_library->reference == ptr_lib.owner_id); } } @@ -3194,7 +3281,7 @@ void BKE_lib_override_library_id_reset(Main *bmain, } if (lib_override_library_id_reset_do(bmain, id_root, do_reset_system_override)) { - if (id_root->override_library->runtime != NULL && + if (id_root->override_library->runtime != nullptr && (id_root->override_library->runtime->tag & IDOVERRIDE_LIBRARY_RUNTIME_TAG_NEEDS_RELOAD) != 0) { BKE_lib_override_library_update(bmain, id_root); @@ -3212,13 +3299,13 @@ static void lib_override_library_id_hierarchy_recursive_reset(Main *bmain, } void **entry_vp = BLI_ghash_lookup_p(bmain->relations->relations_from_pointers, id_root); - if (entry_vp == NULL) { + if (entry_vp == nullptr) { /* This ID is not used by nor using any other ID. */ lib_override_library_id_reset_do(bmain, id_root, do_reset_system_override); return; } - MainIDRelationsEntry *entry = *entry_vp; + MainIDRelationsEntry *entry = static_cast<MainIDRelationsEntry *>(*entry_vp); if (entry->tags & MAINIDRELATIONS_ENTRY_TAGS_PROCESSED) { /* This ID has already been processed. */ return; @@ -3230,7 +3317,7 @@ static void lib_override_library_id_hierarchy_recursive_reset(Main *bmain, * relationship hierarchy. */ entry->tags |= MAINIDRELATIONS_ENTRY_TAGS_PROCESSED; - for (MainIDRelationsEntryItem *to_id_entry = entry->to_ids; to_id_entry != NULL; + for (MainIDRelationsEntryItem *to_id_entry = entry->to_ids; to_id_entry != nullptr; to_id_entry = to_id_entry->next) { if ((to_id_entry->usage_flag & IDWALK_CB_OVERRIDE_LIBRARY_NOT_OVERRIDABLE) != 0) { /* Never consider non-overridable relationships ('from', 'parents', 'owner' etc. pointers) as @@ -3238,9 +3325,9 @@ static void lib_override_library_id_hierarchy_recursive_reset(Main *bmain, continue; } /* We only consider IDs from the same library. */ - if (*to_id_entry->id_pointer.to != NULL) { + if (*to_id_entry->id_pointer.to != nullptr) { ID *to_id = *to_id_entry->id_pointer.to; - if (to_id->override_library != NULL) { + if (to_id->override_library != nullptr) { lib_override_library_id_hierarchy_recursive_reset(bmain, to_id, do_reset_system_override); } } @@ -3259,7 +3346,7 @@ void BKE_lib_override_library_id_hierarchy_reset(Main *bmain, ID *id; FOREACH_MAIN_ID_BEGIN (bmain, id) { - if (!ID_IS_OVERRIDE_LIBRARY_REAL(id) || id->override_library->runtime == NULL || + if (!ID_IS_OVERRIDE_LIBRARY_REAL(id) || id->override_library->runtime == nullptr || (id->override_library->runtime->tag & IDOVERRIDE_LIBRARY_RUNTIME_TAG_NEEDS_RELOAD) == 0) { continue; } @@ -3269,11 +3356,11 @@ void BKE_lib_override_library_id_hierarchy_reset(Main *bmain, FOREACH_MAIN_ID_END; } -void BKE_lib_override_library_operations_tag(struct IDOverrideLibraryProperty *override_property, +void BKE_lib_override_library_operations_tag(IDOverrideLibraryProperty *override_property, const short tag, const bool do_set) { - if (override_property != NULL) { + if (override_property != nullptr) { if (do_set) { override_property->tag |= tag; } @@ -3292,18 +3379,18 @@ void BKE_lib_override_library_operations_tag(struct IDOverrideLibraryProperty *o } } -void BKE_lib_override_library_properties_tag(struct IDOverrideLibrary *override, +void BKE_lib_override_library_properties_tag(IDOverrideLibrary *override, const short tag, const bool do_set) { - if (override != NULL) { + if (override != nullptr) { LISTBASE_FOREACH (IDOverrideLibraryProperty *, op, &override->properties) { BKE_lib_override_library_operations_tag(op, tag, do_set); } } } -void BKE_lib_override_library_main_tag(struct Main *bmain, const short tag, const bool do_set) +void BKE_lib_override_library_main_tag(Main *bmain, const short tag, const bool do_set) { ID *id; @@ -3315,7 +3402,7 @@ void BKE_lib_override_library_main_tag(struct Main *bmain, const short tag, cons FOREACH_MAIN_ID_END; } -void BKE_lib_override_library_id_unused_cleanup(struct ID *local) +void BKE_lib_override_library_id_unused_cleanup(ID *local) { if (ID_IS_OVERRIDE_LIBRARY_REAL(local)) { LISTBASE_FOREACH_MUTABLE ( @@ -3334,7 +3421,7 @@ void BKE_lib_override_library_id_unused_cleanup(struct ID *local) } } -void BKE_lib_override_library_main_unused_cleanup(struct Main *bmain) +void BKE_lib_override_library_main_unused_cleanup(Main *bmain) { ID *id; @@ -3390,10 +3477,10 @@ void BKE_lib_override_library_update(Main *bmain, ID *local) ID *tmp_id = BKE_id_copy_ex(bmain, local->override_library->reference, - NULL, + nullptr, LIB_ID_COPY_DEFAULT | LIB_ID_COPY_NO_LIB_OVERRIDE_LOCAL_DATA_FLAG); - if (tmp_id == NULL) { + if (tmp_id == nullptr) { return; } @@ -3409,12 +3496,12 @@ void BKE_lib_override_library_update(Main *bmain, ID *local) * collections' parents are fully runtime and reconstructed later. */ Key *local_key = BKE_key_from_id(local); Key *tmp_key = BKE_key_from_id(tmp_id); - if (local_key != NULL && tmp_key != NULL) { + if (local_key != nullptr && tmp_key != nullptr) { tmp_key->id.flag |= (local_key->id.flag & LIB_EMBEDDED_DATA_LIB_OVERRIDE); tmp_key->id.lib = local_key->id.lib; } - PointerRNA rnaptr_src, rnaptr_dst, rnaptr_storage_stack, *rnaptr_storage = NULL; + PointerRNA rnaptr_src, rnaptr_dst, rnaptr_storage_stack, *rnaptr_storage = nullptr; RNA_id_pointer_create(local, &rnaptr_src); RNA_id_pointer_create(tmp_id, &rnaptr_dst); if (local->override_library->storage) { @@ -3429,11 +3516,13 @@ void BKE_lib_override_library_update(Main *bmain, ID *local) local->override_library, RNA_OVERRIDE_APPLY_FLAG_NOP); + lib_override_object_posemode_transfer(tmp_id, local); + /* This also transfers all pointers (memory) owned by local to tmp_id, and vice-versa. * So when we'll free tmp_id, we'll actually free old, outdated data from local. */ lib_override_id_swap(bmain, local, tmp_id); - if (local_key != NULL && tmp_key != NULL) { + if (local_key != nullptr && tmp_key != nullptr) { /* This is some kind of hard-coded 'always enforced override'. */ lib_override_id_swap(bmain, &local_key->id, &tmp_key->id); tmp_key->id.flag |= (local_key->id.flag & LIB_EMBEDDED_DATA_LIB_OVERRIDE); @@ -3453,7 +3542,7 @@ void BKE_lib_override_library_update(Main *bmain, ID *local) /* Fun times again, thanks to bone pointers in pose data of objects. We keep same ID addresses, * but internal data has changed for sure, so we need to invalidate pose-bones caches. */ LISTBASE_FOREACH (Object *, ob, &bmain->objects) { - if (ob->pose != NULL && ob->data == local) { + if (ob->pose != nullptr && ob->data == local) { BLI_assert(ob->type == OB_ARMATURE); ob->pose->flag |= POSE_RECALC; /* We need to clear pose bone pointers immediately, some code may access those before pose @@ -3468,7 +3557,7 @@ void BKE_lib_override_library_update(Main *bmain, ID *local) /* XXX For until we get fully shadow copies, we still need to ensure storage releases * its usage of any ID pointers it may have. */ BKE_id_free_ex(bmain, local->override_library->storage, LIB_ID_FREE_NO_UI_USER, true); - local->override_library->storage = NULL; + local->override_library->storage = nullptr; } local->tag |= LIB_TAG_OVERRIDE_LIBRARY_REFOK; @@ -3492,7 +3581,7 @@ void BKE_lib_override_library_main_update(Main *bmain) G_MAIN = bmain; FOREACH_MAIN_ID_BEGIN (bmain, id) { - if (id->override_library != NULL) { + if (id->override_library != nullptr) { BKE_lib_override_library_update(bmain, id); } } @@ -3501,7 +3590,7 @@ void BKE_lib_override_library_main_update(Main *bmain) G_MAIN = orig_gmain; } -bool BKE_lib_override_library_id_is_user_deletable(struct Main *bmain, struct ID *id) +bool BKE_lib_override_library_id_is_user_deletable(Main *bmain, ID *id) { /* The only strong known case currently are objects used by override collections. */ /* TODO: There are most likely other cases... This may need to be addressed in a better way at @@ -3550,11 +3639,11 @@ ID *BKE_lib_override_library_operations_store_start(Main *bmain, /* This is actually purely local data with an override template, or one of those embedded IDs * (root node trees, master collections or shape-keys) that cannot have their own override. * Nothing to do here! */ - return NULL; + return nullptr; } BLI_assert(ID_IS_OVERRIDE_LIBRARY_REAL(local)); - BLI_assert(override_storage != NULL); + BLI_assert(override_storage != nullptr); UNUSED_VARS_NDEBUG(override_storage); /* Forcefully ensure we know about all needed override operations. */ @@ -3582,7 +3671,7 @@ ID *BKE_lib_override_library_operations_store_start(Main *bmain, * actually a (performances) issue here, before doing it. */ storage_id = BKE_id_copy((Main *)override_storage, local); - if (storage_id != NULL) { + if (storage_id != nullptr) { PointerRNA rnaptr_reference, rnaptr_final, rnaptr_storage; RNA_id_pointer_create(local->override_library->reference, &rnaptr_reference); RNA_id_pointer_create(local, &rnaptr_final); @@ -3591,11 +3680,11 @@ ID *BKE_lib_override_library_operations_store_start(Main *bmain, if (!RNA_struct_override_store( bmain, &rnaptr_final, &rnaptr_reference, &rnaptr_storage, local->override_library)) { BKE_id_free_ex(override_storage, storage_id, LIB_ID_FREE_NO_UI_USER, true); - storage_id = NULL; + storage_id = nullptr; } } #else - storage_id = NULL; + storage_id = nullptr; #endif local->override_library->storage = storage_id; @@ -3613,7 +3702,7 @@ void BKE_lib_override_library_operations_store_end( /* Nothing else to do here really, we need to keep all temp override storage data-blocks in * memory until whole file is written anyway (otherwise we'd get mem pointers overlap). */ - local->override_library->storage = NULL; + local->override_library->storage = nullptr; } void BKE_lib_override_library_operations_store_finalize(OverrideLibraryStorage *override_storage) diff --git a/source/blender/blenkernel/intern/lib_override_proxy_conversion.c b/source/blender/blenkernel/intern/lib_override_proxy_conversion.c index 7fa9ba5dca9..88f6fbb0ead 100644 --- a/source/blender/blenkernel/intern/lib_override_proxy_conversion.c +++ b/source/blender/blenkernel/intern/lib_override_proxy_conversion.c @@ -83,7 +83,7 @@ bool BKE_lib_override_library_proxy_convert(Main *bmain, FOREACH_MAIN_ID_END; return BKE_lib_override_library_create( - bmain, scene, view_layer, ob_proxy->id.lib, id_root, id_root, id_instance_hint, NULL); + bmain, scene, view_layer, ob_proxy->id.lib, id_root, id_root, id_instance_hint, NULL, false); } static void lib_override_library_proxy_convert_do(Main *bmain, diff --git a/source/blender/blenkernel/intern/lib_remap.c b/source/blender/blenkernel/intern/lib_remap.c index 971db852463..2600a40153c 100644 --- a/source/blender/blenkernel/intern/lib_remap.c +++ b/source/blender/blenkernel/intern/lib_remap.c @@ -75,6 +75,7 @@ static void foreach_libblock_remap_callback_skip(const ID *UNUSED(id_owner), { ID *id = *id_ptr; BLI_assert(id != NULL); + if (is_indirect) { id->runtime.remap.skipped_indirect++; } @@ -82,8 +83,9 @@ static void foreach_libblock_remap_callback_skip(const ID *UNUSED(id_owner), id->runtime.remap.skipped_direct++; } else { - BLI_assert(0); + BLI_assert_unreachable(); } + if (cb_flag & IDWALK_CB_USER) { id->runtime.remap.skipped_refcounted++; } @@ -553,7 +555,6 @@ static void libblock_remap_foreach_idpair_cb(ID *old_id, ID *new_id, void *user_ new_id ? new_id->name : "<NULL>", new_id, old_id->us - skipped_refcounted); - BLI_assert(0); } const int skipped_direct = old_id->runtime.remap.skipped_direct; diff --git a/source/blender/blenkernel/intern/main.c b/source/blender/blenkernel/intern/main.c index 03e03dacfbc..b9ed783fa8c 100644 --- a/source/blender/blenkernel/intern/main.c +++ b/source/blender/blenkernel/intern/main.c @@ -502,13 +502,13 @@ BlendThumbnail *BKE_main_thumbnail_from_imbuf(Main *bmain, ImBuf *img) } if (img) { - const size_t sz = BLEN_THUMB_MEMSIZE(img->x, img->y); - data = MEM_mallocN(sz, __func__); + const size_t data_size = BLEN_THUMB_MEMSIZE(img->x, img->y); + data = MEM_mallocN(data_size, __func__); IMB_rect_from_float(img); /* Just in case... */ data->width = img->x; data->height = img->y; - memcpy(data->rect, img->rect, sz - sizeof(*data)); + memcpy(data->rect, img->rect, data_size - sizeof(*data)); } if (bmain) { diff --git a/source/blender/blenkernel/intern/material.c b/source/blender/blenkernel/intern/material.c index 002b496393f..e5b875cadf9 100644 --- a/source/blender/blenkernel/intern/material.c +++ b/source/blender/blenkernel/intern/material.c @@ -1123,15 +1123,16 @@ void BKE_object_material_remap_calc(Object *ob_dst, Object *ob_src, short *remap BLI_ghash_free(gh_mat_map, NULL, NULL); } -void BKE_object_material_from_eval_data(Main *bmain, Object *ob_orig, ID *data_eval) +void BKE_object_material_from_eval_data(Main *bmain, Object *ob_orig, const ID *data_eval) { ID *data_orig = ob_orig->data; short *orig_totcol = BKE_id_material_len_p(data_orig); Material ***orig_mat = BKE_id_material_array_p(data_orig); - short *eval_totcol = BKE_id_material_len_p(data_eval); - Material ***eval_mat = BKE_id_material_array_p(data_eval); + /* Can cast away const, because the data is not changed. */ + const short *eval_totcol = BKE_id_material_len_p((ID *)data_eval); + Material ***eval_mat = BKE_id_material_array_p((ID *)data_eval); if (ELEM(NULL, orig_totcol, orig_mat, eval_totcol, eval_mat)) { return; @@ -1244,7 +1245,6 @@ bool BKE_object_material_slot_remove(Main *bmain, Object *ob) /* this should never happen and used to crash */ if (ob->actcol <= 0) { CLOG_ERROR(&LOG, "invalid material index %d, report a bug!", ob->actcol); - BLI_assert(0); return false; } diff --git a/source/blender/blenkernel/intern/mesh.cc b/source/blender/blenkernel/intern/mesh.cc index 628f59ae449..0becea62810 100644 --- a/source/blender/blenkernel/intern/mesh.cc +++ b/source/blender/blenkernel/intern/mesh.cc @@ -31,6 +31,7 @@ #include "BLI_string.h" #include "BLI_task.hh" #include "BLI_utildefines.h" +#include "BLI_vector.hh" #include "BLT_translation.h" @@ -60,6 +61,7 @@ #include "BLO_read_write.h" using blender::float3; +using blender::Vector; static void mesh_clear_geometry(Mesh *mesh); static void mesh_tessface_clear_intern(Mesh *mesh, int free_customdata); @@ -208,46 +210,40 @@ static void mesh_blend_write(BlendWriter *writer, ID *id, const void *id_address Mesh *mesh = (Mesh *)id; const bool is_undo = BLO_write_is_undo(writer); - CustomDataLayer *vlayers = nullptr, vlayers_buff[CD_TEMP_CHUNK_SIZE]; - CustomDataLayer *elayers = nullptr, elayers_buff[CD_TEMP_CHUNK_SIZE]; - CustomDataLayer *flayers = nullptr, flayers_buff[CD_TEMP_CHUNK_SIZE]; - CustomDataLayer *llayers = nullptr, llayers_buff[CD_TEMP_CHUNK_SIZE]; - CustomDataLayer *players = nullptr, players_buff[CD_TEMP_CHUNK_SIZE]; + Vector<CustomDataLayer, 16> vert_layers; + Vector<CustomDataLayer, 16> edge_layers; + Vector<CustomDataLayer, 16> loop_layers; + Vector<CustomDataLayer, 16> poly_layers; /* cache only - don't write */ mesh->mface = nullptr; mesh->totface = 0; memset(&mesh->fdata, 0, sizeof(mesh->fdata)); mesh->runtime = blender::dna::shallow_zero_initialize(); - flayers = flayers_buff; /* Do not store actual geometry data in case this is a library override ID. */ if (ID_IS_OVERRIDE_LIBRARY(mesh) && !is_undo) { mesh->mvert = nullptr; mesh->totvert = 0; memset(&mesh->vdata, 0, sizeof(mesh->vdata)); - vlayers = vlayers_buff; mesh->medge = nullptr; mesh->totedge = 0; memset(&mesh->edata, 0, sizeof(mesh->edata)); - elayers = elayers_buff; mesh->mloop = nullptr; mesh->totloop = 0; memset(&mesh->ldata, 0, sizeof(mesh->ldata)); - llayers = llayers_buff; mesh->mpoly = nullptr; mesh->totpoly = 0; memset(&mesh->pdata, 0, sizeof(mesh->pdata)); - players = players_buff; } else { - CustomData_blend_write_prepare(&mesh->vdata, &vlayers, vlayers_buff, ARRAY_SIZE(vlayers_buff)); - CustomData_blend_write_prepare(&mesh->edata, &elayers, elayers_buff, ARRAY_SIZE(elayers_buff)); - CustomData_blend_write_prepare(&mesh->ldata, &llayers, llayers_buff, ARRAY_SIZE(llayers_buff)); - CustomData_blend_write_prepare(&mesh->pdata, &players, players_buff, ARRAY_SIZE(players_buff)); + CustomData_blend_write_prepare(mesh->vdata, vert_layers); + CustomData_blend_write_prepare(mesh->edata, edge_layers); + CustomData_blend_write_prepare(mesh->ldata, loop_layers); + CustomData_blend_write_prepare(mesh->pdata, poly_layers); } BLO_write_id_struct(writer, Mesh, id_address, &mesh->id); @@ -264,33 +260,15 @@ static void mesh_blend_write(BlendWriter *writer, ID *id, const void *id_address BLO_write_raw(writer, sizeof(MSelect) * mesh->totselect, mesh->mselect); CustomData_blend_write( - writer, &mesh->vdata, vlayers, mesh->totvert, CD_MASK_MESH.vmask, &mesh->id); + writer, &mesh->vdata, vert_layers, mesh->totvert, CD_MASK_MESH.vmask, &mesh->id); CustomData_blend_write( - writer, &mesh->edata, elayers, mesh->totedge, CD_MASK_MESH.emask, &mesh->id); + writer, &mesh->edata, edge_layers, mesh->totedge, CD_MASK_MESH.emask, &mesh->id); /* fdata is really a dummy - written so slots align */ + CustomData_blend_write(writer, &mesh->fdata, {}, mesh->totface, CD_MASK_MESH.fmask, &mesh->id); CustomData_blend_write( - writer, &mesh->fdata, flayers, mesh->totface, CD_MASK_MESH.fmask, &mesh->id); + writer, &mesh->ldata, loop_layers, mesh->totloop, CD_MASK_MESH.lmask, &mesh->id); CustomData_blend_write( - writer, &mesh->ldata, llayers, mesh->totloop, CD_MASK_MESH.lmask, &mesh->id); - CustomData_blend_write( - writer, &mesh->pdata, players, mesh->totpoly, CD_MASK_MESH.pmask, &mesh->id); - - /* Free temporary data */ - - /* Free custom-data layers, when not assigned a buffer value. */ -#define CD_LAYERS_FREE(id) \ - if (id && id != id##_buff) { \ - MEM_freeN(id); \ - } \ - ((void)0) - - CD_LAYERS_FREE(vlayers); - CD_LAYERS_FREE(elayers); - // CD_LAYER_FREE(flayers); /* Never allocated. */ - CD_LAYERS_FREE(llayers); - CD_LAYERS_FREE(players); - -#undef CD_LAYERS_FREE + writer, &mesh->pdata, poly_layers, mesh->totpoly, CD_MASK_MESH.pmask, &mesh->id); } static void mesh_blend_read_data(BlendDataReader *reader, ID *id) @@ -1577,6 +1555,19 @@ void BKE_mesh_smooth_flag_set(Mesh *me, const bool use_smooth) } } +void BKE_mesh_auto_smooth_flag_set(Mesh *me, + const bool use_auto_smooth, + const float auto_smooth_angle) +{ + if (use_auto_smooth) { + me->flag |= ME_AUTOSMOOTH; + me->smoothresh = auto_smooth_angle; + } + else { + me->flag &= ~ME_AUTOSMOOTH; + } +} + int poly_find_loop_from_vert(const MPoly *poly, const MLoop *loopstart, uint vert) { for (int j = 0; j < poly->totloop; j++, loopstart++) { @@ -1809,7 +1800,7 @@ void BKE_mesh_mselect_validate(Mesh *me) break; } default: { - BLI_assert(0); + BLI_assert_unreachable(); break; } } diff --git a/source/blender/blenkernel/intern/mesh_convert.cc b/source/blender/blenkernel/intern/mesh_convert.cc index 0d34c8ad6b1..cc4a995b1b1 100644 --- a/source/blender/blenkernel/intern/mesh_convert.cc +++ b/source/blender/blenkernel/intern/mesh_convert.cc @@ -12,6 +12,7 @@ #include "DNA_key_types.h" #include "DNA_material_types.h" #include "DNA_mesh_types.h" +#include "DNA_meshdata_types.h" #include "DNA_meta_types.h" #include "DNA_object_types.h" #include "DNA_pointcloud_types.h" @@ -943,24 +944,9 @@ static void curve_to_mesh_eval_ensure(Object &object) BKE_object_runtime_free_data(&taper_object); } -/* Necessary because #BKE_object_get_evaluated_mesh doesn't look in the geometry set yet. */ -static const Mesh *get_evaluated_mesh_from_object(const Object *object) -{ - const Mesh *mesh = BKE_object_get_evaluated_mesh(object); - if (mesh) { - return mesh; - } - GeometrySet *geometry_set_eval = object->runtime.geometry_set_eval; - if (geometry_set_eval) { - return geometry_set_eval->get_mesh_for_read(); - } - return nullptr; -} - static const Curves *get_evaluated_curves_from_object(const Object *object) { - GeometrySet *geometry_set_eval = object->runtime.geometry_set_eval; - if (geometry_set_eval) { + if (GeometrySet *geometry_set_eval = object->runtime.geometry_set_eval) { return geometry_set_eval->get_curves_for_read(); } return nullptr; @@ -968,12 +954,10 @@ static const Curves *get_evaluated_curves_from_object(const Object *object) static Mesh *mesh_new_from_evaluated_curve_type_object(const Object *evaluated_object) { - const Mesh *mesh = get_evaluated_mesh_from_object(evaluated_object); - if (mesh) { + if (const Mesh *mesh = BKE_object_get_evaluated_mesh(evaluated_object)) { return BKE_mesh_copy_for_eval(mesh, false); } - const Curves *curves = get_evaluated_curves_from_object(evaluated_object); - if (curves) { + if (const Curves *curves = get_evaluated_curves_from_object(evaluated_object)) { return blender::bke::curve_to_wire_mesh(blender::bke::CurvesGeometry::wrap(curves->geometry)); } return nullptr; @@ -1392,7 +1376,7 @@ static void shapekey_layers_to_keyblocks(Mesh *mesh_src, Mesh *mesh_dst, int act for (i = 0; i < tot; i++) { CustomDataLayer *layer = &mesh_src->vdata.layers[CustomData_get_layer_index_n(&mesh_src->vdata, CD_SHAPEKEY, i)]; - float(*cos)[3], (*kbcos)[3]; + float(*kbcos)[3]; for (kb = (KeyBlock *)mesh_dst->key->block.first; kb; kb = kb->next) { if (kb->uid == layer->uid) { @@ -1409,7 +1393,8 @@ static void shapekey_layers_to_keyblocks(Mesh *mesh_src, Mesh *mesh_dst, int act MEM_freeN(kb->data); } - cos = (float(*)[3])CustomData_get_layer_n(&mesh_src->vdata, CD_SHAPEKEY, i); + const float(*cos)[3] = (const float(*)[3])CustomData_get_layer_n( + &mesh_src->vdata, CD_SHAPEKEY, i); kb->totelem = mesh_src->totvert; kb->data = kbcos = (float(*)[3])MEM_malloc_arrayN(kb->totelem, sizeof(float[3]), __func__); diff --git a/source/blender/blenkernel/intern/mesh_evaluate.cc b/source/blender/blenkernel/intern/mesh_evaluate.cc index ec2660a0145..de0489d668f 100644 --- a/source/blender/blenkernel/intern/mesh_evaluate.cc +++ b/source/blender/blenkernel/intern/mesh_evaluate.cc @@ -18,8 +18,9 @@ #include "BLI_alloca.h" #include "BLI_bitmap.h" #include "BLI_edgehash.h" - +#include "BLI_index_range.hh" #include "BLI_math.h" +#include "BLI_span.hh" #include "BLI_utildefines.h" #include "BKE_customdata.h" @@ -27,6 +28,10 @@ #include "BKE_mesh.h" #include "BKE_multires.h" +using blender::IndexRange; +using blender::MutableSpan; +using blender::Span; + /* -------------------------------------------------------------------- */ /** \name Polygon Calculations * \{ */ @@ -644,7 +649,7 @@ static void bm_corners_to_loops_ex(ID *id, MFace *mf = mface + findex; for (int i = 0; i < numTex; i++) { - MTFace *texface = (MTFace *)CustomData_get_n(fdata, CD_MTFACE, findex, i); + const MTFace *texface = (const MTFace *)CustomData_get_n(fdata, CD_MTFACE, findex, i); MLoopUV *mloopuv = (MLoopUV *)CustomData_get_n(ldata, CD_MLOOPUV, loopstart, i); copy_v2_v2(mloopuv->uv, texface->uv[0]); @@ -662,7 +667,7 @@ static void bm_corners_to_loops_ex(ID *id, for (int i = 0; i < numCol; i++) { MLoopCol *mloopcol = (MLoopCol *)CustomData_get_n(ldata, CD_PROP_BYTE_COLOR, loopstart, i); - MCol *mcol = (MCol *)CustomData_get_n(fdata, CD_MCOL, findex, i); + const MCol *mcol = (const MCol *)CustomData_get_n(fdata, CD_MCOL, findex, i); MESH_MLOOPCOL_FROM_MCOL(mloopcol, &mcol[0]); mloopcol++; @@ -678,7 +683,7 @@ static void bm_corners_to_loops_ex(ID *id, if (CustomData_has_layer(fdata, CD_TESSLOOPNORMAL)) { float(*lnors)[3] = (float(*)[3])CustomData_get(ldata, loopstart, CD_NORMAL); - short(*tlnors)[3] = (short(*)[3])CustomData_get(fdata, findex, CD_TESSLOOPNORMAL); + const short(*tlnors)[3] = (short(*)[3])CustomData_get(fdata, findex, CD_TESSLOOPNORMAL); const int max = mf->v4 ? 4 : 3; for (int i = 0; i < max; i++, lnors++, tlnors++) { @@ -688,8 +693,8 @@ static void bm_corners_to_loops_ex(ID *id, if (CustomData_has_layer(fdata, CD_MDISPS)) { MDisps *ld = (MDisps *)CustomData_get(ldata, loopstart, CD_MDISPS); - MDisps *fd = (MDisps *)CustomData_get(fdata, findex, CD_MDISPS); - float(*disps)[3] = fd->disps; + const MDisps *fd = (const MDisps *)CustomData_get(fdata, findex, CD_MDISPS); + const float(*disps)[3] = fd->disps; int tot = mf->v4 ? 4 : 3; int corners; @@ -1113,58 +1118,49 @@ void BKE_mesh_flush_select_from_polys(Mesh *me) me->mvert, me->totvert, me->mloop, me->medge, me->totedge, me->mpoly, me->totpoly); } -void BKE_mesh_flush_select_from_verts_ex(const MVert *mvert, - const int UNUSED(totvert), - const MLoop *mloop, - MEdge *medge, - const int totedge, - MPoly *mpoly, - const int totpoly) +static void mesh_flush_select_from_verts(const Span<MVert> verts, + const Span<MLoop> loops, + MutableSpan<MEdge> edges, + MutableSpan<MPoly> polys) { - MEdge *med; - MPoly *mp; - - /* edges */ - int i = totedge; - for (med = medge; i--; med++) { - if ((med->flag & ME_HIDE) == 0) { - if ((mvert[med->v1].flag & SELECT) && (mvert[med->v2].flag & SELECT)) { - med->flag |= SELECT; + for (const int i : edges.index_range()) { + if ((edges[i].flag & ME_HIDE) == 0) { + MEdge &edge = edges[i]; + if ((verts[edge.v1].flag & SELECT) && (verts[edge.v2].flag & SELECT)) { + edge.flag |= SELECT; } else { - med->flag &= ~SELECT; + edge.flag &= ~SELECT; } } } - /* polys */ - i = totpoly; - for (mp = mpoly; i--; mp++) { - if ((mp->flag & ME_HIDE) == 0) { - bool ok = true; - const MLoop *ml; - int j; - j = mp->totloop; - for (ml = &mloop[mp->loopstart]; j--; ml++) { - if ((mvert[ml->v].flag & SELECT) == 0) { - ok = false; - break; - } - } - - if (ok) { - mp->flag |= ME_FACE_SEL; - } - else { - mp->flag &= (char)~ME_FACE_SEL; + for (const int i : polys.index_range()) { + if (polys[i].flag & ME_HIDE) { + continue; + } + MPoly &poly = polys[i]; + bool all_verts_selected = true; + for (const MLoop &loop : loops.slice(poly.loopstart, poly.totloop)) { + if (!(verts[loop.v].flag & SELECT)) { + all_verts_selected = false; } } + if (all_verts_selected) { + poly.flag |= ME_FACE_SEL; + } + else { + poly.flag &= (char)~ME_FACE_SEL; + } } } + void BKE_mesh_flush_select_from_verts(Mesh *me) { - BKE_mesh_flush_select_from_verts_ex( - me->mvert, me->totvert, me->mloop, me->medge, me->totedge, me->mpoly, me->totpoly); + mesh_flush_select_from_verts({me->mvert, me->totvert}, + {me->mloop, me->totloop}, + {me->medge, me->totedge}, + {me->mpoly, me->totpoly}); } /** \} */ diff --git a/source/blender/blenkernel/intern/mesh_remesh_voxel.cc b/source/blender/blenkernel/intern/mesh_remesh_voxel.cc index 02c9f61957d..c960a7f35f1 100644 --- a/source/blender/blenkernel/intern/mesh_remesh_voxel.cc +++ b/source/blender/blenkernel/intern/mesh_remesh_voxel.cc @@ -290,7 +290,7 @@ void BKE_mesh_remesh_reproject_paint_mask(Mesh *target, Mesh *source) &target->vdata, CD_PAINT_MASK, CD_CALLOC, nullptr, target->totvert); } - float *source_mask; + const float *source_mask; if (CustomData_has_layer(&source->vdata, CD_PAINT_MASK)) { source_mask = (float *)CustomData_get_layer(&source->vdata, CD_PAINT_MASK); } diff --git a/source/blender/blenkernel/intern/mesh_tangent.c b/source/blender/blenkernel/intern/mesh_tangent.c index f2e46c3bd92..c0b2b33c47c 100644 --- a/source/blender/blenkernel/intern/mesh_tangent.c +++ b/source/blender/blenkernel/intern/mesh_tangent.c @@ -37,13 +37,13 @@ /* User data. */ typedef struct { - const MPoly *mpolys; /* faces */ - const MLoop *mloops; /* faces's vertices */ - const MVert *mverts; /* vertices */ - const MLoopUV *luvs; /* texture coordinates */ - float (*lnors)[3]; /* loops' normals */ - float (*tangents)[4]; /* output tangents */ - int num_polys; /* number of polygons */ + const MPoly *mpolys; /* faces */ + const MLoop *mloops; /* faces's vertices */ + const MVert *mverts; /* vertices */ + const MLoopUV *luvs; /* texture coordinates */ + const float (*lnors)[3]; /* loops' normals */ + float (*tangents)[4]; /* output tangents */ + int num_polys; /* number of polygons */ } BKEMeshToTangent; /* Mikktspace's API */ @@ -103,7 +103,7 @@ void BKE_mesh_calc_loop_tangent_single_ex(const MVert *mverts, const int UNUSED(numVerts), const MLoop *mloops, float (*r_looptangent)[4], - float (*loopnors)[3], + const float (*loopnors)[3], const MLoopUV *loopuvs, const int UNUSED(numLoops), const MPoly *mpolys, @@ -155,8 +155,7 @@ void BKE_mesh_calc_loop_tangent_single(Mesh *mesh, float (*r_looptangents)[4], ReportList *reports) { - MLoopUV *loopuvs; - float(*loopnors)[3]; + const MLoopUV *loopuvs; /* Check we have valid texture coordinates first! */ if (uvmap) { @@ -173,7 +172,7 @@ void BKE_mesh_calc_loop_tangent_single(Mesh *mesh, return; } - loopnors = CustomData_get_layer(&mesh->ldata, CD_NORMAL); + const float(*loopnors)[3] = CustomData_get_layer(&mesh->ldata, CD_NORMAL); if (!loopnors) { BKE_report( reports, RPT_ERROR, "Tangent space computation needs loop normals, none found, aborting"); @@ -205,10 +204,10 @@ typedef struct { const float (*precomputedFaceNormals)[3]; const float (*precomputedLoopNormals)[3]; const MLoopTri *looptri; - MLoopUV *mloopuv; /* texture coordinates */ - const MPoly *mpoly; /* indices */ - const MLoop *mloop; /* indices */ - const MVert *mvert; /* vertex coordinates */ + const MLoopUV *mloopuv; /* texture coordinates */ + const MPoly *mpoly; /* indices */ + const MLoop *mloop; /* indices */ + const MVert *mvert; /* vertex coordinates */ const float (*vert_normals)[3]; const float (*orco)[3]; float (*tangent)[4]; /* destination */ diff --git a/source/blender/blenkernel/intern/mesh_tessellate.c b/source/blender/blenkernel/intern/mesh_tessellate.c index ea3cc043267..7cb656d2357 100644 --- a/source/blender/blenkernel/intern/mesh_tessellate.c +++ b/source/blender/blenkernel/intern/mesh_tessellate.c @@ -69,7 +69,7 @@ static void mesh_loops_to_tessdata(CustomData *fdata, for (i = 0; i < numUV; i++) { MTFace *texface = CustomData_get_layer_n(fdata, CD_MTFACE, i); - MLoopUV *mloopuv = CustomData_get_layer_n(ldata, CD_MLOOPUV, i); + const MLoopUV *mloopuv = CustomData_get_layer_n(ldata, CD_MLOOPUV, i); for (findex = 0, pidx = polyindices, lidx = loopindices; findex < num_faces; pidx++, lidx++, findex++, texface++) { @@ -81,7 +81,7 @@ static void mesh_loops_to_tessdata(CustomData *fdata, for (i = 0; i < numCol; i++) { MCol(*mcol)[4] = CustomData_get_layer_n(fdata, CD_MCOL, i); - MLoopCol *mloopcol = CustomData_get_layer_n(ldata, CD_PROP_BYTE_COLOR, i); + const MLoopCol *mloopcol = CustomData_get_layer_n(ldata, CD_PROP_BYTE_COLOR, i); for (findex = 0, lidx = loopindices; findex < num_faces; lidx++, findex++, mcol++) { for (j = (mface ? mface[findex].v4 : (*lidx)[3]) ? 4 : 3; j--;) { @@ -92,7 +92,7 @@ static void mesh_loops_to_tessdata(CustomData *fdata, if (hasPCol) { MCol(*mcol)[4] = CustomData_get_layer(fdata, CD_PREVIEW_MCOL); - MLoopCol *mloopcol = CustomData_get_layer(ldata, CD_PREVIEW_MLOOPCOL); + const MLoopCol *mloopcol = CustomData_get_layer(ldata, CD_PREVIEW_MLOOPCOL); for (findex = 0, lidx = loopindices; findex < num_faces; lidx++, findex++, mcol++) { for (j = (mface ? mface[findex].v4 : (*lidx)[3]) ? 4 : 3; j--;) { @@ -103,7 +103,7 @@ static void mesh_loops_to_tessdata(CustomData *fdata, if (hasOrigSpace) { OrigSpaceFace *of = CustomData_get_layer(fdata, CD_ORIGSPACE); - OrigSpaceLoop *lof = CustomData_get_layer(ldata, CD_ORIGSPACE_MLOOP); + const OrigSpaceLoop *lof = CustomData_get_layer(ldata, CD_ORIGSPACE_MLOOP); for (findex = 0, lidx = loopindices; findex < num_faces; lidx++, findex++, of++) { for (j = (mface ? mface[findex].v4 : (*lidx)[3]) ? 4 : 3; j--;) { @@ -114,7 +114,7 @@ static void mesh_loops_to_tessdata(CustomData *fdata, if (hasLoopNormal) { short(*fnors)[4][3] = CustomData_get_layer(fdata, CD_TESSLOOPNORMAL); - float(*lnors)[3] = CustomData_get_layer(ldata, CD_NORMAL); + const float(*lnors)[3] = CustomData_get_layer(ldata, CD_NORMAL); for (findex = 0, lidx = loopindices; findex < num_faces; lidx++, findex++, fnors++) { for (j = (mface ? mface[findex].v4 : (*lidx)[3]) ? 4 : 3; j--;) { @@ -126,7 +126,7 @@ static void mesh_loops_to_tessdata(CustomData *fdata, if (hasLoopTangent) { /* Need to do for all UV maps at some point. */ float(*ftangents)[4] = CustomData_get_layer(fdata, CD_TANGENT); - float(*ltangents)[4] = CustomData_get_layer(ldata, CD_TANGENT); + const float(*ltangents)[4] = CustomData_get_layer(ldata, CD_TANGENT); for (findex = 0, pidx = polyindices, lidx = loopindices; findex < num_faces; pidx++, lidx++, findex++) { @@ -154,8 +154,8 @@ int BKE_mesh_tessface_calc_ex(CustomData *fdata, const int looptri_num = poly_to_tri_count(totpoly, totloop); - MPoly *mp, *mpoly; - MLoop *ml, *mloop; + const MPoly *mp, *mpoly; + const MLoop *ml, *mloop; MFace *mface, *mf; MemArena *arena = NULL; int *mface_to_poly_map; diff --git a/source/blender/blenkernel/intern/modifier.c b/source/blender/blenkernel/intern/modifier.c index 5ffd253be3b..6348d83362e 100644 --- a/source/blender/blenkernel/intern/modifier.c +++ b/source/blender/blenkernel/intern/modifier.c @@ -1067,7 +1067,7 @@ void BKE_modifier_check_uuids_unique_and_report(const Object *object) BLI_gset_free(used_uuids, NULL); } -void BKE_modifier_blend_write(BlendWriter *writer, ListBase *modbase) +void BKE_modifier_blend_write(BlendWriter *writer, const ID *id_owner, ListBase *modbase) { if (modbase == NULL) { return; @@ -1076,7 +1076,13 @@ void BKE_modifier_blend_write(BlendWriter *writer, ListBase *modbase) LISTBASE_FOREACH (ModifierData *, md, modbase) { const ModifierTypeInfo *mti = BKE_modifier_get_info(md->type); if (mti == NULL) { - return; + continue; + } + + /* If the blendWrite callback is defined, it should handle the whole writing process. */ + if (mti->blendWrite != NULL) { + mti->blendWrite(writer, id_owner, md); + continue; } BLO_write_struct_by_name(writer, mti->structName, md); @@ -1162,10 +1168,6 @@ void BKE_modifier_blend_write(BlendWriter *writer, ListBase *modbase) writestruct(wd, DATA, MFace, collmd->numfaces, collmd->mfaces); #endif } - - if (mti->blendWrite != NULL) { - mti->blendWrite(writer, md); - } } } diff --git a/source/blender/blenkernel/intern/movieclip.c b/source/blender/blenkernel/intern/movieclip.c index accbca42da6..19ee2ba6605 100644 --- a/source/blender/blenkernel/intern/movieclip.c +++ b/source/blender/blenkernel/intern/movieclip.c @@ -2085,8 +2085,7 @@ GPUTexture *BKE_movieclip_get_gpu_texture(MovieClip *clip, MovieClipUser *cuser) /* This only means RGBA16F instead of RGBA32F. */ const bool high_bitdepth = false; const bool store_premultiplied = ibuf->rect_float ? false : true; - *tex = IMB_create_gpu_texture( - clip->id.name + 2, ibuf, high_bitdepth, store_premultiplied, false); + *tex = IMB_create_gpu_texture(clip->id.name + 2, ibuf, high_bitdepth, store_premultiplied); /* Do not generate mips for movieclips... too slow. */ GPU_texture_mipmap_mode(*tex, false, true); diff --git a/source/blender/blenkernel/intern/multires.c b/source/blender/blenkernel/intern/multires.c index b0e235662cb..63945f9ed42 100644 --- a/source/blender/blenkernel/intern/multires.c +++ b/source/blender/blenkernel/intern/multires.c @@ -1021,7 +1021,7 @@ void multires_modifier_update_mdisps(struct DerivedMesh *dm, Scene *scene) CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm; Object *ob; Mesh *me; - MDisps *mdisps; + const MDisps *mdisps; MultiresModifierData *mmd; ob = ccgdm->multires.ob; @@ -1403,7 +1403,7 @@ static void multires_apply_smat(struct Depsgraph *UNUSED(depsgraph), } } -int multires_mdisp_corners(MDisps *s) +int multires_mdisp_corners(const MDisps *s) { int lvl = 13; diff --git a/source/blender/blenkernel/intern/multires_reshape_util.c b/source/blender/blenkernel/intern/multires_reshape_util.c index aed13adf56d..34aa90aa554 100644 --- a/source/blender/blenkernel/intern/multires_reshape_util.c +++ b/source/blender/blenkernel/intern/multires_reshape_util.c @@ -10,12 +10,14 @@ #include "MEM_guardedalloc.h" #include "DNA_mesh_types.h" +#include "DNA_meshdata_types.h" #include "DNA_modifier_types.h" #include "DNA_object_types.h" #include "DNA_scene_types.h" #include "BLI_task.h" +#include "BKE_customdata.h" #include "BKE_mesh.h" #include "BKE_mesh_runtime.h" #include "BKE_multires.h" diff --git a/source/blender/blenkernel/intern/node.cc b/source/blender/blenkernel/intern/node.cc index e9c8b438284..cf50e8a3b43 100644 --- a/source/blender/blenkernel/intern/node.cc +++ b/source/blender/blenkernel/intern/node.cc @@ -60,6 +60,7 @@ #include "BKE_lib_query.h" #include "BKE_main.h" #include "BKE_node.h" +#include "BKE_node_runtime.hh" #include "BKE_node_tree_update.h" #include "RNA_access.h" @@ -94,6 +95,9 @@ using blender::Stack; using blender::StringRef; using blender::Vector; using blender::VectorSet; +using blender::bke::bNodeRuntime; +using blender::bke::bNodeSocketRuntime; +using blender::bke::bNodeTreeRuntime; using blender::nodes::FieldInferencingInterface; using blender::nodes::InputSocketFieldType; using blender::nodes::NodeDeclaration; @@ -123,6 +127,7 @@ static void nodeMuteRerouteOutputLinks(struct bNodeTree *ntree, static void ntree_init_data(ID *id) { bNodeTree *ntree = (bNodeTree *)id; + ntree->runtime = MEM_new<bNodeTreeRuntime>(__func__); ntree_set_typeinfo(ntree, nullptr); } @@ -134,6 +139,8 @@ static void ntree_copy_data(Main *UNUSED(bmain), ID *id_dst, const ID *id_src, c /* We never handle usercount here for own data. */ const int flag_subdata = flag | LIB_ID_CREATE_NO_USER_REFCOUNT; + ntree_dst->runtime = MEM_new<bNodeTreeRuntime>(__func__); + /* in case a running nodetree is copied */ ntree_dst->execdata = nullptr; @@ -203,9 +210,9 @@ static void ntree_copy_data(Main *UNUSED(bmain), ID *id_dst, const ID *id_src, c /* node tree will generate its own interface type */ ntree_dst->interface_type = nullptr; - if (ntree_src->field_inferencing_interface) { - ntree_dst->field_inferencing_interface = new FieldInferencingInterface( - *ntree_src->field_inferencing_interface); + if (ntree_src->runtime->field_inferencing_interface) { + ntree_dst->runtime->field_inferencing_interface = std::make_unique<FieldInferencingInterface>( + *ntree_src->runtime->field_inferencing_interface); } if (flag & LIB_ID_COPY_NO_PREVIEW) { @@ -258,8 +265,6 @@ static void ntree_free_data(ID *id) MEM_freeN(sock); } - delete ntree->field_inferencing_interface; - /* free preview hash */ if (ntree->previews) { BKE_node_instance_hash_free(ntree->previews, (bNodeInstanceValueFP)BKE_node_preview_free); @@ -270,6 +275,7 @@ static void ntree_free_data(ID *id) } BKE_previewimg_free(&ntree->preview); + MEM_delete(ntree->runtime); } static void library_foreach_node_socket(LibraryForeachIDData *data, bNodeSocket *sock) @@ -658,7 +664,7 @@ static void direct_link_node_socket(BlendDataReader *reader, bNodeSocket *sock) BLO_read_data_address(reader, &sock->default_attribute_name); sock->total_inputs = 0; /* Clear runtime data set before drawing. */ sock->cache = nullptr; - sock->declaration = nullptr; + sock->runtime = MEM_new<bNodeSocketRuntime>(__func__); } void ntreeBlendReadData(BlendDataReader *reader, bNodeTree *ntree) @@ -670,9 +676,7 @@ void ntreeBlendReadData(BlendDataReader *reader, bNodeTree *ntree) ntree->progress = nullptr; ntree->execdata = nullptr; - ntree->runtime_flag = 0; - - ntree->field_inferencing_interface = nullptr; + ntree->runtime = MEM_new<bNodeTreeRuntime>(__func__); BKE_ntree_update_tag_missing_runtime_data(ntree); BLO_read_data_address(reader, &ntree->adt); @@ -680,8 +684,8 @@ void ntreeBlendReadData(BlendDataReader *reader, bNodeTree *ntree) BLO_read_list(reader, &ntree->nodes); LISTBASE_FOREACH (bNode *, node, &ntree->nodes) { + node->runtime = MEM_new<bNodeRuntime>(__func__); node->typeinfo = nullptr; - node->declaration = nullptr; BLO_read_list(reader, &node->inputs); BLO_read_list(reader, &node->outputs); @@ -1117,7 +1121,7 @@ static void node_init(const struct bContext *C, bNodeTree *ntree, bNode *node) PointerRNA ptr; RNA_pointer_create((ID *)ntree, &RNA_Node, node, &ptr); - /* XXX Warning: context can be nullptr in case nodes are added in do_versions. + /* XXX WARNING: context can be nullptr in case nodes are added in do_versions. * Delayed init is not supported for nodes with context-based `initfunc_api` at the moment. */ BLI_assert(C != nullptr); ntype->initfunc_api(C, &ptr); @@ -1166,7 +1170,7 @@ static void node_set_typeinfo(const struct bContext *C, } } -/* Warning: default_value must either be null or match the typeinfo at this point. +/* WARNING: default_value must either be null or match the typeinfo at this point. * This function is called both for initializing new sockets and after loading files. */ static void node_socket_set_typeinfo(bNodeTree *ntree, @@ -1512,6 +1516,7 @@ static bNodeSocket *make_socket(bNodeTree *ntree, unique_identifier_check, lb, "socket", '_', auto_identifier, sizeof(auto_identifier)); bNodeSocket *sock = MEM_cnew<bNodeSocket>("sock"); + sock->runtime = MEM_new<bNodeSocketRuntime>(__func__); sock->in_out = in_out; BLI_strncpy(sock->identifier, auto_identifier, NODE_MAXSTR); @@ -1917,6 +1922,7 @@ static void node_socket_free(bNodeSocket *sock, const bool do_id_user) } MEM_freeN(sock->default_value); } + MEM_delete(sock->runtime); } void nodeRemoveSocket(bNodeTree *ntree, bNode *node, bNodeSocket *sock) @@ -2122,6 +2128,7 @@ void nodeUniqueName(bNodeTree *ntree, bNode *node) bNode *nodeAddNode(const struct bContext *C, bNodeTree *ntree, const char *idname) { bNode *node = MEM_cnew<bNode>("new node"); + node->runtime = MEM_new<bNodeRuntime>(__func__); BLI_addtail(&ntree->nodes, node); BLI_strncpy(node->idname, idname, sizeof(node->idname)); @@ -2159,6 +2166,7 @@ bNode *nodeAddStaticNode(const struct bContext *C, bNodeTree *ntree, int type) static void node_socket_copy(bNodeSocket *sock_dst, const bNodeSocket *sock_src, const int flag) { + sock_dst->runtime = MEM_new<bNodeSocketRuntime>(__func__); if (sock_src->prop) { sock_dst->prop = IDP_CopyProperty_ex(sock_src->prop, flag); } @@ -2191,6 +2199,8 @@ bNode *node_copy_with_mapping(bNodeTree *dst_tree, bNode *node_dst = (bNode *)MEM_mallocN(sizeof(bNode), __func__); *node_dst = node_src; + node_dst->runtime = MEM_new<bNodeRuntime>(__func__); + /* Can be called for nodes outside a node tree (e.g. clipboard). */ if (dst_tree) { if (unique_name) { @@ -2251,7 +2261,6 @@ bNode *node_copy_with_mapping(bNodeTree *dst_tree, } /* Reset the declaration of the new node. */ - node_dst->declaration = nullptr; nodeDeclarationEnsure(dst_tree, node_dst); return node_dst; @@ -2668,6 +2677,7 @@ bNodeTree *ntreeAddTree(Main *bmain, const char *name, const char *idname) flag |= LIB_ID_CREATE_NO_MAIN; } bNodeTree *ntree = (bNodeTree *)BKE_libblock_alloc(bmain, ID_NT, name, flag); + BKE_libblock_init_empty(&ntree->id); if (is_embedded) { ntree->id.flag |= LIB_EMBEDDED_DATA; } @@ -2969,9 +2979,10 @@ static void node_free_node(bNodeTree *ntree, bNode *node) } if (node->typeinfo->declaration_is_dynamic) { - delete node->declaration; + delete node->runtime->declaration; } + MEM_delete(node->runtime); MEM_freeN(node); if (ntree) { @@ -3063,6 +3074,7 @@ static void node_socket_interface_free(bNodeTree *UNUSED(ntree), } MEM_freeN(sock->default_value); } + MEM_delete(sock->runtime); } static void free_localized_node_groups(bNodeTree *ntree) @@ -3289,6 +3301,7 @@ static bNodeSocket *make_socket_interface(bNodeTree *ntree, } bNodeSocket *sock = MEM_cnew<bNodeSocket>("socket template"); + sock->runtime = MEM_new<bNodeSocketRuntime>(__func__); BLI_strncpy(sock->idname, stype->idname, sizeof(sock->idname)); sock->in_out = in_out; sock->type = SOCK_CUSTOM; /* int type undefined by default */ @@ -3676,34 +3689,34 @@ static void update_socket_declarations(ListBase *sockets, int index; LISTBASE_FOREACH_INDEX (bNodeSocket *, socket, sockets, index) { const SocketDeclaration &socket_decl = *declarations[index]; - socket->declaration = &socket_decl; + socket->runtime->declaration = &socket_decl; } } void nodeSocketDeclarationsUpdate(bNode *node) { - BLI_assert(node->declaration != nullptr); - update_socket_declarations(&node->inputs, node->declaration->inputs()); - update_socket_declarations(&node->outputs, node->declaration->outputs()); + BLI_assert(node->runtime->declaration != nullptr); + update_socket_declarations(&node->inputs, node->runtime->declaration->inputs()); + update_socket_declarations(&node->outputs, node->runtime->declaration->outputs()); } bool nodeDeclarationEnsureOnOutdatedNode(bNodeTree *UNUSED(ntree), bNode *node) { - if (node->declaration != nullptr) { + if (node->runtime->declaration != nullptr) { return false; } if (node->typeinfo->declare == nullptr) { return false; } if (node->typeinfo->declaration_is_dynamic) { - node->declaration = new blender::nodes::NodeDeclaration(); - blender::nodes::NodeDeclarationBuilder builder{*node->declaration}; + node->runtime->declaration = new blender::nodes::NodeDeclaration(); + blender::nodes::NodeDeclarationBuilder builder{*node->runtime->declaration}; node->typeinfo->declare(builder); } else { /* Declaration should have been created in #nodeRegisterType. */ BLI_assert(node->typeinfo->fixed_declaration != nullptr); - node->declaration = node->typeinfo->fixed_declaration; + node->runtime->declaration = node->typeinfo->fixed_declaration; } return true; } @@ -4503,6 +4516,8 @@ static void registerCompositNodes() register_node_type_cmp_premulkey(); register_node_type_cmp_separate_xyz(); register_node_type_cmp_combine_xyz(); + register_node_type_cmp_separate_color(); + register_node_type_cmp_combine_color(); register_node_type_cmp_diff_matte(); register_node_type_cmp_distance_matte(); @@ -4575,6 +4590,8 @@ static void registerShaderNodes() register_node_type_sh_vect_transform(); register_node_type_sh_squeeze(); register_node_type_sh_invert(); + register_node_type_sh_sepcolor(); + register_node_type_sh_combcolor(); register_node_type_sh_seprgb(); register_node_type_sh_combrgb(); register_node_type_sh_sephsv(); @@ -4661,6 +4678,8 @@ static void registerTextureNodes() register_node_type_tex_distance(); register_node_type_tex_compose(); register_node_type_tex_decompose(); + register_node_type_tex_combine_color(); + register_node_type_tex_separate_color(); register_node_type_tex_output(); register_node_type_tex_viewer(); @@ -4822,6 +4841,7 @@ static void registerFunctionNodes() { register_node_type_fn_align_euler_to_vector(); register_node_type_fn_boolean_math(); + register_node_type_fn_combine_color(); register_node_type_fn_compare(); register_node_type_fn_float_to_int(); register_node_type_fn_input_bool(); @@ -4833,6 +4853,7 @@ static void registerFunctionNodes() register_node_type_fn_random_value(); register_node_type_fn_replace_string(); register_node_type_fn_rotate_euler(); + register_node_type_fn_separate_color(); register_node_type_fn_slice_string(); register_node_type_fn_string_length(); register_node_type_fn_value_to_string(); diff --git a/source/blender/blenkernel/intern/node_tree_update.cc b/source/blender/blenkernel/intern/node_tree_update.cc index 68e4cccba00..019ab114b83 100644 --- a/source/blender/blenkernel/intern/node_tree_update.cc +++ b/source/blender/blenkernel/intern/node_tree_update.cc @@ -15,6 +15,7 @@ #include "BKE_image.h" #include "BKE_main.h" #include "BKE_node.h" +#include "BKE_node_runtime.hh" #include "BKE_node_tree_update.h" #include "MOD_nodes.h" @@ -48,19 +49,19 @@ enum eNodeTreeChangedFlag { static void add_tree_tag(bNodeTree *ntree, const eNodeTreeChangedFlag flag) { - ntree->changed_flag |= flag; + ntree->runtime->changed_flag |= flag; } static void add_node_tag(bNodeTree *ntree, bNode *node, const eNodeTreeChangedFlag flag) { add_tree_tag(ntree, flag); - node->changed_flag |= flag; + node->runtime->changed_flag |= flag; } static void add_socket_tag(bNodeTree *ntree, bNodeSocket *socket, const eNodeTreeChangedFlag flag) { add_tree_tag(ntree, flag); - socket->changed_flag |= flag; + socket->runtime->changed_flag |= flag; } namespace blender::bke { @@ -172,11 +173,11 @@ static FieldInferencingInterface get_node_field_inferencing_interface(const Node /* This can happen when there is a linked node group that was not found (see T92799). */ return get_dummy_field_inferencing_interface(node); } - if (group->field_inferencing_interface == nullptr) { + if (!group->runtime->field_inferencing_interface) { /* This shouldn't happen because referenced node groups should always be updated first. */ BLI_assert_unreachable(); } - return *group->field_inferencing_interface; + return *group->runtime->field_inferencing_interface; } FieldInferencingInterface inferencing_interface; @@ -551,7 +552,8 @@ static bool update_field_inferencing(const NodeTreeRef &tree) bNodeTree &btree = *tree.btree(); /* Create new inferencing interface for this node group. */ - FieldInferencingInterface *new_inferencing_interface = new FieldInferencingInterface(); + std::unique_ptr<FieldInferencingInterface> new_inferencing_interface = + std::make_unique<FieldInferencingInterface>(); new_inferencing_interface->inputs.resize(BLI_listbase_count(&btree.inputs), InputSocketFieldType::IsSupported); new_inferencing_interface->outputs.resize(BLI_listbase_count(&btree.outputs), @@ -567,11 +569,10 @@ static bool update_field_inferencing(const NodeTreeRef &tree) update_socket_shapes(tree, field_state_by_socket_id); /* Update the previous group interface. */ - const bool group_interface_changed = btree.field_inferencing_interface == nullptr || - *btree.field_inferencing_interface != + const bool group_interface_changed = !btree.runtime->field_inferencing_interface || + *btree.runtime->field_inferencing_interface != *new_inferencing_interface; - delete btree.field_inferencing_interface; - btree.field_inferencing_interface = new_inferencing_interface; + btree.runtime->field_inferencing_interface = std::move(new_inferencing_interface); return group_interface_changed; } @@ -799,7 +800,7 @@ class NodeTreeMainUpdater { { Vector<bNodeTree *> changed_ntrees; FOREACH_NODETREE_BEGIN (bmain_, ntree, id) { - if (ntree->changed_flag != NTREE_CHANGED_NOTHING) { + if (ntree->runtime->changed_flag != NTREE_CHANGED_NOTHING) { changed_ntrees.append(ntree); } } @@ -817,7 +818,7 @@ class NodeTreeMainUpdater { if (root_ntrees.size() == 1) { bNodeTree *ntree = root_ntrees[0]; - if (ntree->changed_flag == NTREE_CHANGED_NOTHING) { + if (ntree->runtime->changed_flag == NTREE_CHANGED_NOTHING) { return; } const TreeUpdateResult result = this->update_tree(*ntree); @@ -830,7 +831,7 @@ class NodeTreeMainUpdater { if (!is_single_tree_update) { Vector<bNodeTree *> ntrees_in_order = this->get_tree_update_order(root_ntrees); for (bNodeTree *ntree : ntrees_in_order) { - if (ntree->changed_flag == NTREE_CHANGED_NOTHING) { + if (ntree->runtime->changed_flag == NTREE_CHANGED_NOTHING) { continue; } if (!update_result_by_tree_.contains(ntree)) { @@ -1002,7 +1003,8 @@ class NodeTreeMainUpdater { ntreeTexCheckCyclics(&ntree); } - if (ntree.changed_flag & NTREE_CHANGED_INTERFACE || ntree.changed_flag & NTREE_CHANGED_ANY) { + if (ntree.runtime->changed_flag & NTREE_CHANGED_INTERFACE || + ntree.runtime->changed_flag & NTREE_CHANGED_ANY) { result.interface_changed = true; } @@ -1057,18 +1059,18 @@ class NodeTreeMainUpdater { this->ensure_tree_ref(ntree, tree_ref); const NodeRef &node = *tree_ref->find_node(*bnode); if (this->should_update_individual_node(node)) { - const uint32_t old_changed_flag = ntree.changed_flag; - ntree.changed_flag = NTREE_CHANGED_NOTHING; + const uint32_t old_changed_flag = ntree.runtime->changed_flag; + ntree.runtime->changed_flag = NTREE_CHANGED_NOTHING; - /* This may set #ntree.changed_flag which is detected below. */ + /* This may set #ntree.runtime->changed_flag which is detected below. */ this->update_individual_node(node); - if (ntree.changed_flag != NTREE_CHANGED_NOTHING) { + if (ntree.runtime->changed_flag != NTREE_CHANGED_NOTHING) { /* The tree ref is outdated and needs to be rebuilt. Generally, only very few update * functions change the node. Typically zero or one nodes change after an update. */ tree_ref.reset(); } - ntree.changed_flag |= old_changed_flag; + ntree.runtime->changed_flag |= old_changed_flag; } } } @@ -1077,13 +1079,13 @@ class NodeTreeMainUpdater { { bNodeTree &ntree = *node.btree(); bNode &bnode = *node.bnode(); - if (ntree.changed_flag & NTREE_CHANGED_ANY) { + if (ntree.runtime->changed_flag & NTREE_CHANGED_ANY) { return true; } - if (bnode.changed_flag & NTREE_CHANGED_NODE_PROPERTY) { + if (bnode.runtime->changed_flag & NTREE_CHANGED_NODE_PROPERTY) { return true; } - if (ntree.changed_flag & NTREE_CHANGED_LINK) { + if (ntree.runtime->changed_flag & NTREE_CHANGED_LINK) { /* Node groups currently always rebuilt their sockets when they are updated. * So avoid calling the update method when no new link was added to it. */ if (node.is_group_input_node()) { @@ -1101,7 +1103,7 @@ class NodeTreeMainUpdater { return true; } } - if (ntree.changed_flag & NTREE_CHANGED_INTERFACE) { + if (ntree.runtime->changed_flag & NTREE_CHANGED_INTERFACE) { if (node.is_group_input_node() || node.is_group_output_node()) { return true; } @@ -1232,16 +1234,16 @@ class NodeTreeMainUpdater { } /* Reset the changed_flag to allow detecting when the update callback changed the node tree. */ - const uint32_t old_changed_flag = ntree.changed_flag; - ntree.changed_flag = NTREE_CHANGED_NOTHING; + const uint32_t old_changed_flag = ntree.runtime->changed_flag; + ntree.runtime->changed_flag = NTREE_CHANGED_NOTHING; ntree.typeinfo->update(&ntree); - if (ntree.changed_flag != NTREE_CHANGED_NOTHING) { + if (ntree.runtime->changed_flag != NTREE_CHANGED_NOTHING) { /* The tree ref is outdated and needs to be rebuilt. */ tree_ref.reset(); } - ntree.changed_flag |= old_changed_flag; + ntree.runtime->changed_flag |= old_changed_flag; } void remove_unused_previews_when_necessary(bNodeTree &ntree) @@ -1250,7 +1252,7 @@ class NodeTreeMainUpdater { const uint32_t allowed_flags = NTREE_CHANGED_LINK | NTREE_CHANGED_SOCKET_PROPERTY | NTREE_CHANGED_NODE_PROPERTY | NTREE_CHANGED_NODE_OUTPUT | NTREE_CHANGED_INTERFACE; - if ((ntree.changed_flag & allowed_flags) == ntree.changed_flag) { + if ((ntree.runtime->changed_flag & allowed_flags) == ntree.runtime->changed_flag) { return; } BKE_node_preview_remove_unused(&ntree); @@ -1259,7 +1261,7 @@ class NodeTreeMainUpdater { void propagate_runtime_flags(const NodeTreeRef &tree_ref) { bNodeTree &ntree = *tree_ref.btree(); - ntree.runtime_flag = 0; + ntree.runtime->runtime_flag = 0; if (ntree.type != NTREE_SHADER) { return; } @@ -1268,7 +1270,7 @@ class NodeTreeMainUpdater { for (const NodeRef *group_node : tree_ref.nodes_by_type("NodeGroup")) { const bNodeTree *group = reinterpret_cast<bNodeTree *>(group_node->bnode()->id); if (group != nullptr) { - ntree.runtime_flag |= group->runtime_flag; + ntree.runtime->runtime_flag |= group->runtime->runtime_flag; } } /* Check if the tree itself has an animated image. */ @@ -1276,7 +1278,7 @@ class NodeTreeMainUpdater { for (const NodeRef *node : tree_ref.nodes_by_type(idname)) { Image *image = reinterpret_cast<Image *>(node->bnode()->id); if (image != nullptr && BKE_image_is_animated(image)) { - ntree.runtime_flag |= NTREE_RUNTIME_FLAG_HAS_IMAGE_ANIMATION; + ntree.runtime->runtime_flag |= NTREE_RUNTIME_FLAG_HAS_IMAGE_ANIMATION; break; } } @@ -1288,7 +1290,7 @@ class NodeTreeMainUpdater { "ShaderNodeOutputAOV"}) { const Span<const NodeRef *> nodes = tree_ref.nodes_by_type(idname); if (!nodes.is_empty()) { - ntree.runtime_flag |= NTREE_RUNTIME_FLAG_HAS_MATERIAL_OUTPUT; + ntree.runtime->runtime_flag |= NTREE_RUNTIME_FLAG_HAS_MATERIAL_OUTPUT; break; } } @@ -1323,12 +1325,12 @@ class NodeTreeMainUpdater { /* Compute a hash that represents the node topology connected to the output. This always has to * be updated even if it is not used to detect changes right now. Otherwise - * #btree.output_topology_hash will go out of date. */ + * #btree.runtime.output_topology_hash will go out of date. */ const Vector<const SocketRef *> tree_output_sockets = this->find_output_sockets(tree); - const uint32_t old_topology_hash = btree.output_topology_hash; + const uint32_t old_topology_hash = btree.runtime->output_topology_hash; const uint32_t new_topology_hash = this->get_combined_socket_topology_hash( tree, tree_output_sockets); - btree.output_topology_hash = new_topology_hash; + btree.runtime->output_topology_hash = new_topology_hash; if (const AnimData *adt = BKE_animdata_from_id(&btree.id)) { /* Drivers may copy values in the node tree around arbitrarily and may cause the output to @@ -1352,7 +1354,7 @@ class NodeTreeMainUpdater { } } - if (btree.changed_flag & NTREE_CHANGED_ANY) { + if (btree.runtime->changed_flag & NTREE_CHANGED_ANY) { return true; } @@ -1361,8 +1363,8 @@ class NodeTreeMainUpdater { } /* The topology hash can only be used when only topology-changing operations have been done. */ - if (btree.changed_flag == - (btree.changed_flag & (NTREE_CHANGED_LINK | NTREE_CHANGED_REMOVED_NODE))) { + if (btree.runtime->changed_flag == + (btree.runtime->changed_flag & (NTREE_CHANGED_LINK | NTREE_CHANGED_REMOVED_NODE))) { if (old_topology_hash == new_topology_hash) { return false; } @@ -1404,7 +1406,7 @@ class NodeTreeMainUpdater { if (bnode.type == NODE_GROUP) { const bNodeTree *node_group = reinterpret_cast<const bNodeTree *>(bnode.id); if (node_group != nullptr && - node_group->runtime_flag & NTREE_RUNTIME_FLAG_HAS_MATERIAL_OUTPUT) { + node_group->runtime->runtime_flag & NTREE_RUNTIME_FLAG_HAS_MATERIAL_OUTPUT) { return true; } } @@ -1540,12 +1542,12 @@ class NodeTreeMainUpdater { const NodeRef &node = in_out_socket.node(); const bNode &bnode = *node.bnode(); const bNodeSocket &bsocket = *in_out_socket.bsocket(); - if (bsocket.changed_flag != NTREE_CHANGED_NOTHING) { + if (bsocket.runtime->changed_flag != NTREE_CHANGED_NOTHING) { return true; } - if (bnode.changed_flag != NTREE_CHANGED_NOTHING) { + if (bnode.runtime->changed_flag != NTREE_CHANGED_NOTHING) { const bool only_unused_internal_link_changed = (bnode.flag & NODE_MUTED) == 0 && - bnode.changed_flag == + bnode.runtime->changed_flag == NTREE_CHANGED_INTERNAL_LINK; if (!only_unused_internal_link_changed) { return true; @@ -1591,15 +1593,15 @@ class NodeTreeMainUpdater { void reset_changed_flags(bNodeTree &ntree) { - ntree.changed_flag = NTREE_CHANGED_NOTHING; + ntree.runtime->changed_flag = NTREE_CHANGED_NOTHING; LISTBASE_FOREACH (bNode *, node, &ntree.nodes) { - node->changed_flag = NTREE_CHANGED_NOTHING; + node->runtime->changed_flag = NTREE_CHANGED_NOTHING; node->update = 0; LISTBASE_FOREACH (bNodeSocket *, socket, &node->inputs) { - socket->changed_flag = NTREE_CHANGED_NOTHING; + socket->runtime->changed_flag = NTREE_CHANGED_NOTHING; } LISTBASE_FOREACH (bNodeSocket *, socket, &node->outputs) { - socket->changed_flag = NTREE_CHANGED_NOTHING; + socket->runtime->changed_flag = NTREE_CHANGED_NOTHING; } } } diff --git a/source/blender/blenkernel/intern/object.cc b/source/blender/blenkernel/intern/object.cc index 2a25d73ed87..55b9951c52d 100644 --- a/source/blender/blenkernel/intern/object.cc +++ b/source/blender/blenkernel/intern/object.cc @@ -583,7 +583,7 @@ static void object_blend_write(BlendWriter *writer, ID *id, const void *id_addre } BKE_particle_system_blend_write(writer, &ob->particlesystem); - BKE_modifier_blend_write(writer, &ob->modifiers); + BKE_modifier_blend_write(writer, &ob->id, &ob->modifiers); BKE_gpencil_modifier_blend_write(writer, &ob->greasepencil_modifiers); BKE_shaderfx_blend_write(writer, &ob->shader_fx); @@ -2114,7 +2114,7 @@ static const char *get_obdata_defname(int type) case OB_SPEAKER: return DATA_("Speaker"); case OB_CURVES: - return DATA_("HairCurves"); + return DATA_("Curves"); case OB_POINTCLOUD: return DATA_("PointCloud"); case OB_VOLUME: diff --git a/source/blender/blenkernel/intern/ocean.c b/source/blender/blenkernel/intern/ocean.c index 4dc0130366e..dec9a594938 100644 --- a/source/blender/blenkernel/intern/ocean.c +++ b/source/blender/blenkernel/intern/ocean.c @@ -48,7 +48,7 @@ static float nextfr(RNG *rng, float min, float max) static float gaussRand(RNG *rng) { /* NOTE: to avoid numerical problems with very small numbers, we make these variables - * singe-precision floats, but later we call the double-precision log() and sqrt() functions + * single-precision floats, but later we call the double-precision log() and sqrt() functions * instead of logf() and sqrtf(). */ float x; float y; diff --git a/source/blender/blenkernel/intern/packedFile.c b/source/blender/blenkernel/intern/packedFile.c index e7ed100ed03..7c96c463339 100644 --- a/source/blender/blenkernel/intern/packedFile.c +++ b/source/blender/blenkernel/intern/packedFile.c @@ -237,14 +237,14 @@ void BKE_packedfile_pack_all(Main *bmain, ReportList *reports, bool verbose) for (ima = bmain->images.first; ima; ima = ima->id.next) { if (BKE_image_has_packedfile(ima) == false && !ID_IS_LINKED(ima)) { - if (ima->source == IMA_SRC_FILE) { + if (ELEM(ima->source, IMA_SRC_FILE, IMA_SRC_TILED)) { BKE_image_packfiles(reports, ima, ID_BLEND_PATH(bmain, &ima->id)); tot++; } - else if (BKE_image_has_multiple_ibufs(ima) && verbose) { + else if (ELEM(ima->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE) && verbose) { BKE_reportf(reports, RPT_WARNING, - "Image '%s' skipped, movies, image sequences and packed files not supported", + "Image '%s' skipped, packing movies or image sequences not supported", ima->id.name + 2); } } @@ -494,15 +494,22 @@ static void unpack_generate_paths(const char *name, if (tempname[0] == '\0') { /* NOTE: we generally do not have any real way to re-create extension out of data. */ - BLI_strncpy(tempname, id->name + 2, sizeof(tempname)); + const size_t len = BLI_strncpy_rlen(tempname, id->name + 2, sizeof(tempname)); printf("%s\n", tempname); - /* For images we can add the file extension based on the file magic. */ + /* For images ensure that the temporary filename contains tile number information as well as + * a file extension based on the file magic. */ if (id_type == ID_IM) { - ImagePackedFile *imapf = ((Image *)id)->packedfiles.last; + Image *ima = (Image *)id; + ImagePackedFile *imapf = ima->packedfiles.last; if (imapf != NULL && imapf->packedfile != NULL) { const PackedFile *pf = imapf->packedfile; enum eImbFileType ftype = IMB_ispic_type_from_memory((const uchar *)pf->data, pf->size); + if (ima->source == IMA_SRC_TILED) { + char tile_number[6]; + BLI_snprintf(tile_number, sizeof(tile_number), ".%d", imapf->tile_number); + BLI_strncpy(tempname + len, tile_number, sizeof(tempname) - len); + } if (ftype != IMB_FTYPE_NONE) { const int imtype = BKE_ftype_to_imtype(ftype, NULL); BKE_image_path_ensure_ext_from_imtype(tempname, imtype); @@ -639,6 +646,11 @@ int BKE_packedfile_unpack_image(Main *bmain, /* keep the new name in the image for non-pack specific reasons */ if (how != PF_REMOVE) { BLI_strncpy(ima->filepath, new_file_path, sizeof(imapf->filepath)); + if (ima->source == IMA_SRC_TILED) { + /* Ensure that the Image filepath is kept in a tokenized format. */ + char *filename = (char *)BLI_path_basename(ima->filepath); + BKE_image_ensure_tile_token(filename); + } } MEM_freeN(new_file_path); } diff --git a/source/blender/blenkernel/intern/paint.c b/source/blender/blenkernel/intern/paint.c index 0f523d87d9b..cff7eb20b05 100644 --- a/source/blender/blenkernel/intern/paint.c +++ b/source/blender/blenkernel/intern/paint.c @@ -606,6 +606,11 @@ ePaintMode BKE_paintmode_get_from_tool(const struct bToolRef *tref) Brush *BKE_paint_brush(Paint *p) { + return (Brush *)BKE_paint_brush_for_read((const Paint *)p); +} + +const Brush *BKE_paint_brush_for_read(const Paint *p) +{ return p ? p->brush : NULL; } @@ -2051,7 +2056,7 @@ void BKE_sculpt_face_sets_ensure_from_base_mesh_visibility(Mesh *mesh) void BKE_sculpt_sync_face_sets_visibility_to_base_mesh(Mesh *mesh) { - int *face_sets = CustomData_get_layer(&mesh->pdata, CD_SCULPT_FACE_SETS); + const int *face_sets = CustomData_get_layer(&mesh->pdata, CD_SCULPT_FACE_SETS); if (!face_sets) { return; } @@ -2066,7 +2071,7 @@ void BKE_sculpt_sync_face_sets_visibility_to_base_mesh(Mesh *mesh) void BKE_sculpt_sync_face_sets_visibility_to_grids(Mesh *mesh, SubdivCCG *subdiv_ccg) { - int *face_sets = CustomData_get_layer(&mesh->pdata, CD_SCULPT_FACE_SETS); + const int *face_sets = CustomData_get_layer(&mesh->pdata, CD_SCULPT_FACE_SETS); if (!face_sets) { return; } diff --git a/source/blender/blenkernel/intern/particle.c b/source/blender/blenkernel/intern/particle.c index b935f2afaaa..a5f7f73af70 100644 --- a/source/blender/blenkernel/intern/particle.c +++ b/source/blender/blenkernel/intern/particle.c @@ -1667,7 +1667,7 @@ void psys_interpolate_face(Mesh *mesh, const float (*vert_normals)[3], MFace *mface, MTFace *tface, - float (*orcodata)[3], + const float (*orcodata)[3], float w[4], float vec[3], float nor[3], @@ -1680,7 +1680,7 @@ void psys_interpolate_face(Mesh *mesh, float *uv1, *uv2, *uv3, *uv4; float n1[3], n2[3], n3[3], n4[3]; float tuv[4][2]; - float *o1, *o2, *o3, *o4; + const float *o1, *o2, *o3, *o4; v1 = mvert[mface->v1].co; v2 = mvert[mface->v2].co; @@ -1903,9 +1903,10 @@ int psys_particle_dm_face_lookup(Mesh *mesh_final, struct LinkNode **poly_nodes) { MFace *mtessface_final; - OrigSpaceFace *osface_final; + const OrigSpaceFace *osface_final; int pindex_orig; - float uv[2], (*faceuv)[2]; + float uv[2]; + const float(*faceuv)[2]; const int *index_mf_to_mpoly_deformed = NULL; const int *index_mf_to_mpoly = NULL; @@ -2048,11 +2049,7 @@ static int psys_map_index_on_dm(Mesh *mesh, } else { /* FROM_FACE/FROM_VOLUME */ /* find a face on the derived mesh that uses this face */ - MFace *mface; - OrigSpaceFace *osface; - int i; - - i = index_dmcache; + int i = index_dmcache; if (i == DMCACHE_NOTFOUND || i >= mesh->totface) { return 0; @@ -2062,8 +2059,8 @@ static int psys_map_index_on_dm(Mesh *mesh, /* modify the original weights to become * weights for the derived mesh face */ - osface = CustomData_get_layer(&mesh->fdata, CD_ORIGSPACE); - mface = &mesh->mface[i]; + OrigSpaceFace *osface = CustomData_get_layer(&mesh->fdata, CD_ORIGSPACE); + const MFace *mface = &mesh->mface[i]; if (osface == NULL) { mapfw[0] = mapfw[1] = mapfw[2] = mapfw[3] = 0.0f; @@ -2090,7 +2087,7 @@ void psys_particle_on_dm(Mesh *mesh_final, float orco[3]) { float tmpnor[3], mapfw[4]; - float(*orcodata)[3]; + const float(*orcodata)[3]; int mapindex; if (!psys_map_index_on_dm( @@ -3628,7 +3625,7 @@ static void psys_cache_edit_paths_iter(void *__restrict iter_data_v, BKE_defvert_weight_to_rgb(ca->col, pind.hkey[1]->weight); } else { - /* warning: copied from 'do_particle_interpolation' (without 'mvert' array stepping) */ + /* WARNING: copied from 'do_particle_interpolation' (without 'mvert' array stepping) */ float real_t; if (result.time < 0.0f) { real_t = -result.time; @@ -3796,7 +3793,7 @@ void psys_get_from_key(ParticleKey *key, float loc[3], float vel[3], float rot[4 } } -static void triatomat(float *v1, float *v2, float *v3, float (*uv)[2], float mat[4][4]) +static void triatomat(float *v1, float *v2, float *v3, const float (*uv)[2], float mat[4][4]) { float det, w1, w2, d1[2], d2[2]; @@ -3842,8 +3839,7 @@ static void psys_face_mat(Object *ob, Mesh *mesh, ParticleData *pa, float mat[4] { float v[3][3]; MFace *mface; - OrigSpaceFace *osface; - float(*orcodata)[3]; + const float(*orcodata)[3]; int i = (ELEM(pa->num_dmcache, DMCACHE_ISCHILD, DMCACHE_NOTFOUND)) ? pa->num : pa->num_dmcache; if (i == -1 || i >= mesh->totface) { @@ -3852,7 +3848,7 @@ static void psys_face_mat(Object *ob, Mesh *mesh, ParticleData *pa, float mat[4] } mface = &mesh->mface[i]; - osface = CustomData_get(&mesh->fdata, i, CD_ORIGSPACE); + const OrigSpaceFace *osface = CustomData_get(&mesh->fdata, i, CD_ORIGSPACE); if (orco && (orcodata = CustomData_get_layer(&mesh->vdata, CD_ORCO))) { copy_v3_v3(v[0], orcodata[mface->v1]); @@ -4159,7 +4155,7 @@ static int get_particle_uv(Mesh *mesh, bool from_vert) { MFace *mf; - MTFace *tf; + const MTFace *tf; int i; tf = CustomData_get_layer_named(&mesh->fdata, CD_MTFACE, name); @@ -5039,7 +5035,6 @@ void psys_get_dupli_texture(ParticleSystem *psys, float uv[2], float orco[3]) { - MFace *mface; float loc[3]; int num; @@ -5063,9 +5058,9 @@ void psys_get_dupli_texture(ParticleSystem *psys, const int uv_idx = CustomData_get_render_layer(mtf_data, CD_MTFACE); if (uv_idx >= 0) { - MTFace *mtface = CustomData_get_layer_n(mtf_data, CD_MTFACE, uv_idx); + const MTFace *mtface = CustomData_get_layer_n(mtf_data, CD_MTFACE, uv_idx); if (mtface != NULL) { - mface = CustomData_get(&psmd->mesh_final->fdata, cpa->num, CD_MFACE); + const MFace *mface = CustomData_get(&psmd->mesh_final->fdata, cpa->num, CD_MFACE); mtface += cpa->num; psys_interpolate_uvs(mtface, mface->v4, cpa->fuv, uv); } @@ -5107,8 +5102,8 @@ void psys_get_dupli_texture(ParticleSystem *psys, const int uv_idx = CustomData_get_render_layer(mtf_data, CD_MTFACE); if (uv_idx >= 0) { - MTFace *mtface = CustomData_get_layer_n(mtf_data, CD_MTFACE, uv_idx); - mface = CustomData_get(&psmd->mesh_final->fdata, num, CD_MFACE); + const MTFace *mtface = CustomData_get_layer_n(mtf_data, CD_MTFACE, uv_idx); + const MFace *mface = CustomData_get(&psmd->mesh_final->fdata, num, CD_MFACE); mtface += num; psys_interpolate_uvs(mtface, mface->v4, pa->fuv, uv); } diff --git a/source/blender/blenkernel/intern/particle_distribute.c b/source/blender/blenkernel/intern/particle_distribute.c index 244396af6e6..4be48efb2b5 100644 --- a/source/blender/blenkernel/intern/particle_distribute.c +++ b/source/blender/blenkernel/intern/particle_distribute.c @@ -808,7 +808,7 @@ static void exec_distribute_child(TaskPool *__restrict UNUSED(pool), void *taskd static int distribute_compare_orig_index(const void *p1, const void *p2, void *user_data) { - int *orig_index = (int *)user_data; + const int *orig_index = (const int *)user_data; int index1 = orig_index[*(const int *)p1]; int index2 = orig_index[*(const int *)p2]; @@ -989,7 +989,7 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, if (from == PART_FROM_VERT) { MVert *mv = mesh->mvert; - float(*orcodata)[3] = CustomData_get_layer(&mesh->vdata, CD_ORCO); + const float(*orcodata)[3] = CustomData_get_layer(&mesh->vdata, CD_ORCO); int totvert = mesh->totvert; tree = BLI_kdtree_3d_new(totvert); @@ -1037,7 +1037,7 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, if ((part->flag & PART_EDISTR || children) && from != PART_FROM_VERT) { MVert *v1, *v2, *v3, *v4; float totarea = 0.0f, co1[3], co2[3], co3[3], co4[3]; - float(*orcodata)[3]; + const float(*orcodata)[3]; orcodata = CustomData_get_layer(&mesh->vdata, CD_ORCO); @@ -1219,7 +1219,7 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, /* For hair, sort by origindex (allows optimization's in rendering), */ /* however with virtual parents the children need to be in random order. */ if (part->type == PART_HAIR && !(part->childtype == PART_CHILD_FACES && part->parents != 0.0f)) { - int *orig_index = NULL; + const int *orig_index = NULL; if (from == PART_FROM_VERT) { if (mesh->totvert) { @@ -1233,8 +1233,11 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, } if (orig_index) { - BLI_qsort_r( - particle_element, totpart, sizeof(int), distribute_compare_orig_index, orig_index); + BLI_qsort_r(particle_element, + totpart, + sizeof(int), + distribute_compare_orig_index, + (void *)orig_index); } } diff --git a/source/blender/blenkernel/intern/particle_system.c b/source/blender/blenkernel/intern/particle_system.c index 7fdc60a265b..a7ab1536b1f 100644 --- a/source/blender/blenkernel/intern/particle_system.c +++ b/source/blender/blenkernel/intern/particle_system.c @@ -321,8 +321,9 @@ void psys_calc_dmcache(Object *ob, Mesh *mesh_final, Mesh *mesh_original, Partic if (!mesh_final->runtime.deformed_only) { /* Will use later to speed up subsurf/evaluated mesh. */ LinkNode *node, *nodedmelem, **nodearray; - int totdmelem, totelem, i, *origindex, *origindex_poly = NULL; - + int totdmelem, totelem, i; + const int *origindex; + const int *origindex_poly = NULL; if (psys->part->from == PART_FROM_VERT) { totdmelem = mesh_final->totvert; diff --git a/source/blender/blenkernel/intern/pbvh_intern.h b/source/blender/blenkernel/intern/pbvh_intern.h index c7c8fbe8bce..a86663a9c74 100644 --- a/source/blender/blenkernel/intern/pbvh_intern.h +++ b/source/blender/blenkernel/intern/pbvh_intern.h @@ -10,6 +10,11 @@ extern "C" { #endif +struct MLoop; +struct MLoopTri; +struct MPoly; +struct MVert; + /* Axis-aligned bounding box */ typedef struct { float bmin[3], bmax[3]; @@ -141,12 +146,12 @@ struct PBVH { /* Mesh data */ const struct Mesh *mesh; - /* Note: Normals are not const because they can be updated for drawing by sculpt code. */ + /* NOTE: Normals are not `const` because they can be updated for drawing by sculpt code. */ float (*vert_normals)[3]; - MVert *verts; - const MPoly *mpoly; - const MLoop *mloop; - const MLoopTri *looptri; + struct MVert *verts; + const struct MPoly *mpoly; + const struct MLoop *mloop; + const struct MLoopTri *looptri; CustomData *vdata; CustomData *ldata; CustomData *pdata; diff --git a/source/blender/blenkernel/intern/pbvh_pixels.cc b/source/blender/blenkernel/intern/pbvh_pixels.cc index 5623cac44ac..49397797c0d 100644 --- a/source/blender/blenkernel/intern/pbvh_pixels.cc +++ b/source/blender/blenkernel/intern/pbvh_pixels.cc @@ -71,7 +71,7 @@ static void extract_barycentric_pixels(UDIMTilePixels &tile_data, int x; for (x = minx; x < maxx; x++) { - float2 uv(float(x) / image_buffer->x, float(y) / image_buffer->y); + float2 uv((float(x) + 0.5f) / image_buffer->x, (float(y) + 0.5f) / image_buffer->y); float3 barycentric_weights; barycentric_weights_v2(uvs[0], uvs[1], uvs[2], uv, barycentric_weights); @@ -108,7 +108,7 @@ struct EncodePixelsUserData { ImageUser *image_user; PBVH *pbvh; Vector<PBVHNode *> *nodes; - MLoopUV *ldata_uv; + const MLoopUV *ldata_uv; }; static void do_encode_pixels(void *__restrict userdata, @@ -283,7 +283,8 @@ static void update_pixels(PBVH *pbvh, Mesh *mesh, Image *image, ImageUser *image return; } - MLoopUV *ldata_uv = static_cast<MLoopUV *>(CustomData_get_layer(&mesh->ldata, CD_MLOOPUV)); + const MLoopUV *ldata_uv = static_cast<const MLoopUV *>( + CustomData_get_layer(&mesh->ldata, CD_MLOOPUV)); if (ldata_uv == nullptr) { return; } @@ -307,6 +308,12 @@ static void update_pixels(PBVH *pbvh, Mesh *mesh, Image *image, ImageUser *image apply_watertight_check(pbvh, image, image_user); } + /* Rebuild the undo regions. */ + for (PBVHNode *node : nodes_to_update) { + NodeData *node_data = static_cast<NodeData *>(node->pixels.node_data); + node_data->rebuild_undo_regions(); + } + /* Clear the UpdatePixels flag. */ for (PBVHNode *node : nodes_to_update) { node->flag = static_cast<PBVHNodeFlags>(node->flag & ~PBVH_RebuildPixels); diff --git a/source/blender/blenkernel/intern/pointcache.c b/source/blender/blenkernel/intern/pointcache.c index 353f89068d8..2467ca16670 100644 --- a/source/blender/blenkernel/intern/pointcache.c +++ b/source/blender/blenkernel/intern/pointcache.c @@ -1450,7 +1450,7 @@ static PTCacheFile *ptcache_file_open(PTCacheID *pid, int mode, int cfra) { PTCacheFile *pf; FILE *fp = NULL; - char filename[MAX_PTCACHE_FILE]; + char filepath[MAX_PTCACHE_FILE]; #ifndef DURIAN_POINTCACHE_LIB_OK /* don't allow writing for linked objects */ @@ -1465,20 +1465,20 @@ static PTCacheFile *ptcache_file_open(PTCacheID *pid, int mode, int cfra) } } - ptcache_filename(pid, filename, cfra, true, true); + ptcache_filename(pid, filepath, cfra, true, true); if (mode == PTCACHE_FILE_READ) { - fp = BLI_fopen(filename, "rb"); + fp = BLI_fopen(filepath, "rb"); } else if (mode == PTCACHE_FILE_WRITE) { /* Will create the dir if needs be, same as "//textures" is created. */ - BLI_make_existing_file(filename); + BLI_make_existing_file(filepath); - fp = BLI_fopen(filename, "wb"); + fp = BLI_fopen(filepath, "wb"); } else if (mode == PTCACHE_FILE_UPDATE) { - BLI_make_existing_file(filename); - fp = BLI_fopen(filename, "rb+"); + BLI_make_existing_file(filepath); + fp = BLI_fopen(filepath, "rb+"); } if (!fp) { diff --git a/source/blender/blenkernel/intern/pointcloud.cc b/source/blender/blenkernel/intern/pointcloud.cc index 3ee46fc4f15..9720c61e3b9 100644 --- a/source/blender/blenkernel/intern/pointcloud.cc +++ b/source/blender/blenkernel/intern/pointcloud.cc @@ -20,6 +20,7 @@ #include "BLI_string.h" #include "BLI_task.hh" #include "BLI_utildefines.h" +#include "BLI_vector.hh" #include "BKE_anim_data.h" #include "BKE_customdata.h" @@ -44,6 +45,7 @@ using blender::float3; using blender::IndexRange; using blender::Span; +using blender::Vector; /* PointCloud datablock */ @@ -107,27 +109,25 @@ static void pointcloud_blend_write(BlendWriter *writer, ID *id, const void *id_a { PointCloud *pointcloud = (PointCloud *)id; - CustomDataLayer *players = nullptr, players_buff[CD_TEMP_CHUNK_SIZE]; - CustomData_blend_write_prepare( - &pointcloud->pdata, &players, players_buff, ARRAY_SIZE(players_buff)); + Vector<CustomDataLayer, 16> point_layers; + CustomData_blend_write_prepare(pointcloud->pdata, point_layers); /* Write LibData */ BLO_write_id_struct(writer, PointCloud, id_address, &pointcloud->id); BKE_id_blend_write(writer, &pointcloud->id); /* Direct data */ - CustomData_blend_write( - writer, &pointcloud->pdata, players, pointcloud->totpoint, CD_MASK_ALL, &pointcloud->id); + CustomData_blend_write(writer, + &pointcloud->pdata, + point_layers, + pointcloud->totpoint, + CD_MASK_ALL, + &pointcloud->id); BLO_write_pointer_array(writer, pointcloud->totcol, pointcloud->mat); if (pointcloud->adt) { BKE_animdata_blend_write(writer, pointcloud->adt); } - - /* Remove temporary data. */ - if (players && players != players_buff) { - MEM_freeN(players); - } } static void pointcloud_blend_read_data(BlendDataReader *reader, ID *id) diff --git a/source/blender/blenkernel/intern/sound.c b/source/blender/blenkernel/intern/sound.c index 864a4f3281b..de5589cf5dc 100644 --- a/source/blender/blenkernel/intern/sound.c +++ b/source/blender/blenkernel/intern/sound.c @@ -264,6 +264,14 @@ bSound *BKE_sound_new_file(Main *bmain, const char *filepath) BLI_strncpy(sound->filepath, filepath, FILE_MAX); /* sound->type = SOUND_TYPE_FILE; */ /* XXX unused currently */ + /* Extract sound specs for bSound */ + SoundInfo info; + bool success = BKE_sound_info_get(bmain, sound, &info); + if (success) { + sound->samplerate = info.specs.samplerate; + sound->audio_channels = info.specs.channels; + } + sound->spinlock = MEM_mallocN(sizeof(SpinLock), "sound_spinlock"); BLI_spin_init(sound->spinlock); @@ -1202,6 +1210,7 @@ static bool sound_info_from_playback_handle(void *playback_handle, SoundInfo *so AUD_SoundInfo info = AUD_getInfo(playback_handle); sound_info->specs.channels = (eSoundChannels)info.specs.channels; sound_info->length = info.length; + sound_info->specs.samplerate = info.specs.rate; return true; } diff --git a/source/blender/blenkernel/intern/spline_base.cc b/source/blender/blenkernel/intern/spline_base.cc index 7704a74841a..e8c7aff75d1 100644 --- a/source/blender/blenkernel/intern/spline_base.cc +++ b/source/blender/blenkernel/intern/spline_base.cc @@ -116,15 +116,15 @@ void Spline::reverse() this->mark_cache_invalid(); } -int Spline::evaluated_edges_size() const +int Spline::evaluated_edges_num() const { - const int eval_size = this->evaluated_points_size(); - if (eval_size < 2) { + const int eval_num = this->evaluated_points_num(); + if (eval_num < 2) { /* Two points are required for an edge. */ return 0; } - return this->is_cyclic_ ? eval_size : eval_size - 1; + return this->is_cyclic_ ? eval_num : eval_num - 1; } float Spline::length() const @@ -133,11 +133,11 @@ float Spline::length() const return lengths.is_empty() ? 0.0f : this->evaluated_lengths().last(); } -int Spline::segments_size() const +int Spline::segments_num() const { - const int size = this->size(); + const int num = this->size(); - return is_cyclic_ ? size : size - 1; + return is_cyclic_ ? num : num - 1; } bool Spline::is_cyclic() const @@ -177,7 +177,7 @@ Span<float> Spline::evaluated_lengths() const return evaluated_lengths_cache_; } - const int total = evaluated_edges_size(); + const int total = evaluated_edges_num(); evaluated_lengths_cache_.resize(total); if (total != 0) { Span<float3> positions = this->evaluated_positions(); @@ -242,8 +242,8 @@ Span<float3> Spline::evaluated_tangents() const return evaluated_tangents_cache_; } - const int eval_size = this->evaluated_points_size(); - evaluated_tangents_cache_.resize(eval_size); + const int eval_num = this->evaluated_points_num(); + evaluated_tangents_cache_.resize(eval_num); Span<float3> positions = this->evaluated_positions(); @@ -369,8 +369,8 @@ Span<float3> Spline::evaluated_normals() const return evaluated_normals_cache_; } - const int eval_size = this->evaluated_points_size(); - evaluated_normals_cache_.resize(eval_size); + const int eval_num = this->evaluated_points_num(); + evaluated_normals_cache_.resize(eval_num); Span<float3> tangents = this->evaluated_tangents(); MutableSpan<float3> normals = evaluated_normals_cache_; @@ -410,7 +410,7 @@ Spline::LookupResult Spline::lookup_evaluated_length(const float length) const const float *offset = std::lower_bound(lengths.begin(), lengths.end(), length); const int index = offset - lengths.begin(); - const int next_index = (index == this->evaluated_points_size() - 1) ? 0 : index + 1; + const int next_index = (index == this->evaluated_points_num() - 1) ? 0 : index + 1; const float previous_length = (index == 0) ? 0.0f : lengths[index - 1]; const float length_in_segment = length - previous_length; @@ -420,30 +420,30 @@ Spline::LookupResult Spline::lookup_evaluated_length(const float length) const return LookupResult{index, next_index, factor}; } -Array<float> Spline::sample_uniform_index_factors(const int samples_size) const +Array<float> Spline::sample_uniform_index_factors(const int samples_num) const { const Span<float> lengths = this->evaluated_lengths(); - BLI_assert(samples_size > 0); - Array<float> samples(samples_size); + BLI_assert(samples_num > 0); + Array<float> samples(samples_num); samples[0] = 0.0f; - if (samples_size == 1) { + if (samples_num == 1) { return samples; } const float total_length = this->length(); - const float sample_length = total_length / (samples_size - (is_cyclic_ ? 0 : 1)); + const float sample_length = total_length / (samples_num - (is_cyclic_ ? 0 : 1)); /* Store the length at the previous evaluated point in a variable so it can * start out at zero (the lengths array doesn't contain 0 for the first point). */ float prev_length = 0.0f; int i_sample = 1; - for (const int i_evaluated : IndexRange(this->evaluated_edges_size())) { + for (const int i_evaluated : IndexRange(this->evaluated_edges_num())) { const float length = lengths[i_evaluated]; /* Add every sample that fits in this evaluated edge. */ - while ((sample_length * i_sample) < length && i_sample < samples_size) { + while ((sample_length * i_sample) < length && i_sample < samples_num) { const float factor = (sample_length * i_sample - prev_length) / (length - prev_length); samples[i_sample] = i_evaluated + factor; i_sample++; @@ -454,8 +454,8 @@ Array<float> Spline::sample_uniform_index_factors(const int samples_size) const /* Zero lengths or float inaccuracies can cause invalid values, or simply * skip some, so set the values that weren't completed in the main loop. */ - for (const int i : IndexRange(i_sample, samples_size - i_sample)) { - samples[i] = float(samples_size); + for (const int i : IndexRange(i_sample, samples_num - i_sample)) { + samples[i] = float(samples_num); } if (!is_cyclic_) { @@ -468,23 +468,23 @@ Array<float> Spline::sample_uniform_index_factors(const int samples_size) const Spline::LookupResult Spline::lookup_data_from_index_factor(const float index_factor) const { - const int eval_size = this->evaluated_points_size(); + const int eval_num = this->evaluated_points_num(); if (is_cyclic_) { - if (index_factor < eval_size) { + if (index_factor < eval_num) { const int index = std::floor(index_factor); - const int next_index = (index < eval_size - 1) ? index + 1 : 0; + const int next_index = (index < eval_num - 1) ? index + 1 : 0; return LookupResult{index, next_index, index_factor - index}; } - return LookupResult{eval_size - 1, 0, 1.0f}; + return LookupResult{eval_num - 1, 0, 1.0f}; } - if (index_factor < eval_size - 1) { + if (index_factor < eval_num - 1) { const int index = std::floor(index_factor); const int next_index = index + 1; return LookupResult{index, next_index, index_factor - index}; } - return LookupResult{eval_size - 2, eval_size - 1, 1.0f}; + return LookupResult{eval_num - 2, eval_num - 1, 1.0f}; } void Spline::bounds_min_max(float3 &min, float3 &max, const bool use_evaluated) const @@ -504,7 +504,7 @@ void Spline::sample_with_index_factors(const GVArray &src, Span<float> index_factors, GMutableSpan dst) const { - BLI_assert(src.size() == this->evaluated_points_size()); + BLI_assert(src.size() == this->evaluated_points_num()); blender::attribute_math::convert_to_static_type(src.type(), [&](auto dummy) { using T = decltype(dummy); diff --git a/source/blender/blenkernel/intern/spline_bezier.cc b/source/blender/blenkernel/intern/spline_bezier.cc index 8e207f93bf5..80515d0ef37 100644 --- a/source/blender/blenkernel/intern/spline_bezier.cc +++ b/source/blender/blenkernel/intern/spline_bezier.cc @@ -335,7 +335,7 @@ void BezierSpline::mark_cache_invalid() auto_handles_dirty_ = true; } -int BezierSpline::evaluated_points_size() const +int BezierSpline::evaluated_points_num() const { BLI_assert(this->size() > 0); return this->control_point_offsets().last(); @@ -502,12 +502,12 @@ Span<float> BezierSpline::evaluated_mappings() const return evaluated_mapping_cache_; } - const int size = this->size(); - const int eval_size = this->evaluated_points_size(); - evaluated_mapping_cache_.resize(eval_size); + const int num = this->size(); + const int eval_num = this->evaluated_points_num(); + evaluated_mapping_cache_.resize(eval_num); MutableSpan<float> mappings = evaluated_mapping_cache_; - if (eval_size == 1) { + if (eval_num == 1) { mappings.first() = 0.0f; mapping_cache_dirty_ = false; return mappings; @@ -517,7 +517,7 @@ Span<float> BezierSpline::evaluated_mappings() const blender::threading::isolate_task([&]() { /* Isolate the task, since this is function is multi-threaded and holds a lock. */ - calculate_mappings_linear_resolution(offsets, size, resolution_, is_cyclic_, mappings); + calculate_mappings_linear_resolution(offsets, num, resolution_, is_cyclic_, mappings); }); mapping_cache_dirty_ = false; @@ -535,15 +535,15 @@ Span<float3> BezierSpline::evaluated_positions() const return evaluated_position_cache_; } - const int size = this->size(); - const int eval_size = this->evaluated_points_size(); - evaluated_position_cache_.resize(eval_size); + const int num = this->size(); + const int eval_num = this->evaluated_points_num(); + evaluated_position_cache_.resize(eval_num); MutableSpan<float3> positions = evaluated_position_cache_; - if (size == 1) { + if (num == 1) { /* Use a special case for single point splines to avoid checking in #evaluate_segment. */ - BLI_assert(eval_size == 1); + BLI_assert(eval_num == 1); positions.first() = positions_.first(); position_cache_dirty_ = false; return positions; @@ -556,7 +556,7 @@ Span<float3> BezierSpline::evaluated_positions() const const int grain_size = std::max(512 / resolution_, 1); blender::threading::isolate_task([&]() { /* Isolate the task, since this is function is multi-threaded and holds a lock. */ - blender::threading::parallel_for(IndexRange(size - 1), grain_size, [&](IndexRange range) { + blender::threading::parallel_for(IndexRange(num - 1), grain_size, [&](IndexRange range) { for (const int i : range) { this->evaluate_segment(i, i + 1, positions.slice(offsets[i], offsets[i + 1] - offsets[i])); } @@ -564,7 +564,7 @@ Span<float3> BezierSpline::evaluated_positions() const }); if (is_cyclic_) { this->evaluate_segment( - size - 1, 0, positions.slice(offsets[size - 1], offsets[size] - offsets[size - 1])); + num - 1, 0, positions.slice(offsets[num - 1], offsets[num] - offsets[num - 1])); } else { /* Since evaluating the bezier segment doesn't add the final point, @@ -579,23 +579,23 @@ Span<float3> BezierSpline::evaluated_positions() const BezierSpline::InterpolationData BezierSpline::interpolation_data_from_index_factor( const float index_factor) const { - const int size = this->size(); + const int num = this->size(); if (is_cyclic_) { - if (index_factor < size) { + if (index_factor < num) { const int index = std::floor(index_factor); - const int next_index = (index < size - 1) ? index + 1 : 0; + const int next_index = (index < num - 1) ? index + 1 : 0; return InterpolationData{index, next_index, index_factor - index}; } - return InterpolationData{size - 1, 0, 1.0f}; + return InterpolationData{num - 1, 0, 1.0f}; } - if (index_factor < size - 1) { + if (index_factor < num - 1) { const int index = std::floor(index_factor); const int next_index = index + 1; return InterpolationData{index, next_index, index_factor - index}; } - return InterpolationData{size - 2, size - 1, 1.0f}; + return InterpolationData{num - 2, num - 1, 1.0f}; } /* Use a spline argument to avoid adding this to the header. */ @@ -605,7 +605,7 @@ static void interpolate_to_evaluated_impl(const BezierSpline &spline, MutableSpan<T> dst) { BLI_assert(src.size() == spline.size()); - BLI_assert(dst.size() == spline.evaluated_points_size()); + BLI_assert(dst.size() == spline.evaluated_points_num()); Span<float> mappings = spline.evaluated_mappings(); for (const int i : dst.index_range()) { @@ -627,8 +627,8 @@ GVArray BezierSpline::interpolate_to_evaluated(const GVArray &src) const return src; } - const int eval_size = this->evaluated_points_size(); - if (eval_size == 1) { + const int eval_num = this->evaluated_points_num(); + if (eval_num == 1) { return src; } @@ -636,7 +636,7 @@ GVArray BezierSpline::interpolate_to_evaluated(const GVArray &src) const blender::attribute_math::convert_to_static_type(src.type(), [&](auto dummy) { using T = decltype(dummy); if constexpr (!std::is_void_v<blender::attribute_math::DefaultMixer<T>>) { - Array<T> values(eval_size); + Array<T> values(eval_num); interpolate_to_evaluated_impl<T>(*this, src.typed<T>(), values); new_varray = VArray<T>::ForContainer(std::move(values)); } diff --git a/source/blender/blenkernel/intern/spline_nurbs.cc b/source/blender/blenkernel/intern/spline_nurbs.cc index 9d1d5a53a43..a7eeb82d854 100644 --- a/source/blender/blenkernel/intern/spline_nurbs.cc +++ b/source/blender/blenkernel/intern/spline_nurbs.cc @@ -124,19 +124,19 @@ void NURBSpline::mark_cache_invalid() length_cache_dirty_ = true; } -int NURBSpline::evaluated_points_size() const +int NURBSpline::evaluated_points_num() const { - if (!this->check_valid_size_and_order()) { + if (!this->check_valid_num_and_order()) { return 0; } - return resolution_ * this->segments_size(); + return resolution_ * this->segments_num(); } void NURBSpline::correct_end_tangents() const { } -bool NURBSpline::check_valid_size_and_order() const +bool NURBSpline::check_valid_num_and_order() const { if (this->size() < order_) { return false; @@ -152,10 +152,10 @@ bool NURBSpline::check_valid_size_and_order() const return true; } -int NURBSpline::knots_size() const +int NURBSpline::knots_num() const { - const int size = this->size() + order_; - return is_cyclic_ ? size + order_ - 1 : size; + const int num = this->size() + order_; + return is_cyclic_ ? num + order_ - 1 : num; } void NURBSpline::calculate_knots() const @@ -173,7 +173,7 @@ void NURBSpline::calculate_knots() const * Covers both Cyclic and EndPoint cases. */ const int tail = is_cyclic_ ? 2 * order - 1 : (is_end_point ? order : 0); - knots_.resize(this->knots_size()); + knots_.resize(this->knots_num()); MutableSpan<float> knots = knots_; int r = head; @@ -203,13 +203,13 @@ void NURBSpline::calculate_knots() const Span<float> NURBSpline::knots() const { if (!knots_dirty_) { - BLI_assert(knots_.size() == this->knots_size()); + BLI_assert(knots_.size() == this->knots_num()); return knots_; } std::lock_guard lock{knots_mutex_}; if (!knots_dirty_) { - BLI_assert(knots_.size() == this->knots_size()); + BLI_assert(knots_.size() == this->knots_num()); return knots_; } @@ -221,7 +221,7 @@ Span<float> NURBSpline::knots() const } static void calculate_basis_for_point(const float parameter, - const int size, + const int num, const int degree, const Span<float> knots, MutableSpan<float> r_weights, @@ -231,7 +231,7 @@ static void calculate_basis_for_point(const float parameter, int start = 0; int end = 0; - for (const int i : IndexRange(size + degree)) { + for (const int i : IndexRange(num + degree)) { const bool knots_equal = knots[i] == knots[i + 1]; if (knots_equal || parameter < knots[i] || parameter > knots[i + 1]) { continue; @@ -248,7 +248,7 @@ static void calculate_basis_for_point(const float parameter, for (const int i_order : IndexRange(2, degree)) { if (end + i_order >= knots.size()) { - end = size + degree - i_order; + end = num + degree - i_order; } for (const int i : IndexRange(end - start + 1)) { const int knot_index = start + i; @@ -284,16 +284,16 @@ const NURBSpline::BasisCache &NURBSpline::calculate_basis_cache() const return basis_cache_; } - const int size = this->size(); - const int eval_size = this->evaluated_points_size(); + const int num = this->size(); + const int eval_num = this->evaluated_points_num(); const int order = this->order(); const int degree = order - 1; - basis_cache_.weights.resize(eval_size * order); - basis_cache_.start_indices.resize(eval_size); + basis_cache_.weights.resize(eval_num * order); + basis_cache_.start_indices.resize(eval_num); - if (eval_size == 0) { + if (eval_num == 0) { return basis_cache_; } @@ -303,14 +303,14 @@ const NURBSpline::BasisCache &NURBSpline::calculate_basis_cache() const const Span<float> control_weights = this->weights(); const Span<float> knots = this->knots(); - const int last_control_point_index = is_cyclic_ ? size + degree : size; + const int last_control_point_index = is_cyclic_ ? num + degree : num; const float start = knots[degree]; const float end = knots[last_control_point_index]; - const float step = (end - start) / this->evaluated_edges_size(); - for (const int i : IndexRange(eval_size)) { + const float step = (end - start) / this->evaluated_edges_num(); + for (const int i : IndexRange(eval_num)) { /* Clamp parameter due to floating point inaccuracy. */ - const float parameter = std::clamp(start + step * i, knots[0], knots[size + degree]); + const float parameter = std::clamp(start + step * i, knots[0], knots[num + degree]); MutableSpan<float> point_weights = basis_weights.slice(i * order, order); @@ -318,7 +318,7 @@ const NURBSpline::BasisCache &NURBSpline::calculate_basis_cache() const parameter, last_control_point_index, degree, knots, point_weights, basis_start_indices[i]); for (const int j : point_weights.index_range()) { - const int point_index = (basis_start_indices[i] + j) % size; + const int point_index = (basis_start_indices[i] + j) % num; point_weights[j] *= control_weights[point_index]; } } @@ -333,7 +333,7 @@ void interpolate_to_evaluated_impl(const NURBSpline::BasisCache &basis_cache, const blender::VArray<T> &src, MutableSpan<T> dst) { - const int size = src.size(); + const int num = src.size(); blender::attribute_math::DefaultMixer<T> mixer(dst); for (const int i : dst.index_range()) { @@ -341,7 +341,7 @@ void interpolate_to_evaluated_impl(const NURBSpline::BasisCache &basis_cache, const int start_index = basis_cache.start_indices[i]; for (const int j : point_weights.index_range()) { - const int point_index = (start_index + j) % size; + const int point_index = (start_index + j) % num; mixer.mix_in(i, src[point_index], point_weights[j]); } } @@ -363,7 +363,7 @@ GVArray NURBSpline::interpolate_to_evaluated(const GVArray &src) const blender::attribute_math::convert_to_static_type(src.type(), [&](auto dummy) { using T = decltype(dummy); if constexpr (!std::is_void_v<blender::attribute_math::DefaultMixer<T>>) { - Array<T> values(this->evaluated_points_size()); + Array<T> values(this->evaluated_points_num()); interpolate_to_evaluated_impl<T>(basis_cache, this->order(), src.typed<T>(), values); new_varray = VArray<T>::ForContainer(std::move(values)); } @@ -383,8 +383,8 @@ Span<float3> NURBSpline::evaluated_positions() const return evaluated_position_cache_; } - const int eval_size = this->evaluated_points_size(); - evaluated_position_cache_.resize(eval_size); + const int eval_num = this->evaluated_points_num(); + evaluated_position_cache_.resize(eval_num); /* TODO: Avoid copying the evaluated data from the temporary array. */ VArray<float3> evaluated = Spline::interpolate_to_evaluated(positions_.as_span()); diff --git a/source/blender/blenkernel/intern/spline_poly.cc b/source/blender/blenkernel/intern/spline_poly.cc index 122f7f6c059..c3cc268c81c 100644 --- a/source/blender/blenkernel/intern/spline_poly.cc +++ b/source/blender/blenkernel/intern/spline_poly.cc @@ -76,7 +76,7 @@ void PolySpline::mark_cache_invalid() length_cache_dirty_ = true; } -int PolySpline::evaluated_points_size() const +int PolySpline::evaluated_points_num() const { return this->size(); } diff --git a/source/blender/blenkernel/intern/subdiv.c b/source/blender/blenkernel/intern/subdiv.c index ee1976d5946..9098c010747 100644 --- a/source/blender/blenkernel/intern/subdiv.c +++ b/source/blender/blenkernel/intern/subdiv.c @@ -25,7 +25,9 @@ #include "opensubdiv_evaluator_capi.h" #include "opensubdiv_topology_refiner_capi.h" -/* =================----====--===== MODULE ==========================------== */ +/* -------------------------------------------------------------------- + * Module. + */ void BKE_subdiv_init() { @@ -37,7 +39,9 @@ void BKE_subdiv_exit() openSubdiv_cleanup(); } -/* ========================== CONVERSION HELPERS ============================ */ +/* -------------------------------------------------------------------- + * Conversion helpers. + */ eSubdivFVarLinearInterpolation BKE_subdiv_fvar_interpolation_from_uv_smooth(int uv_smooth) { @@ -72,7 +76,9 @@ eSubdivVtxBoundaryInterpolation BKE_subdiv_vtx_boundary_interpolation_from_subsu return SUBDIV_VTX_BOUNDARY_EDGE_ONLY; } -/* ================================ SETTINGS ================================ */ +/* -------------------------------------------------------------------- + * Settings. + */ bool BKE_subdiv_settings_equal(const SubdivSettings *settings_a, const SubdivSettings *settings_b) { @@ -83,7 +89,9 @@ bool BKE_subdiv_settings_equal(const SubdivSettings *settings_a, const SubdivSet settings_a->fvar_linear_interpolation == settings_b->fvar_linear_interpolation); } -/* ============================== CONSTRUCTION ============================== */ +/* -------------------------------------------------------------------- + * Construction. + */ /* Creation from scratch. */ @@ -194,7 +202,9 @@ void BKE_subdiv_free(Subdiv *subdiv) MEM_freeN(subdiv); } -/* =========================== PTEX FACES AND GRIDS ========================= */ +/* -------------------------------------------------------------------- + * Topology helpers. + */ int *BKE_subdiv_face_ptex_offset_get(Subdiv *subdiv) { diff --git a/source/blender/blenkernel/intern/subdiv_ccg_mask.c b/source/blender/blenkernel/intern/subdiv_ccg_mask.c index 83f76f85a67..04a274d0215 100644 --- a/source/blender/blenkernel/intern/subdiv_ccg_mask.c +++ b/source/blender/blenkernel/intern/subdiv_ccg_mask.c @@ -155,8 +155,7 @@ static void mask_init_functions(SubdivCCGMaskEvaluator *mask_evaluator) bool BKE_subdiv_ccg_mask_init_from_paint(SubdivCCGMaskEvaluator *mask_evaluator, const struct Mesh *mesh) { - GridPaintMask *grid_paint_mask = CustomData_get_layer(&mesh->ldata, CD_GRID_PAINT_MASK); - if (grid_paint_mask == NULL) { + if (CustomData_get_layer(&mesh->ldata, CD_GRID_PAINT_MASK)) { return false; } /* Allocate all required memory. */ diff --git a/source/blender/blenkernel/intern/subdiv_ccg_material.c b/source/blender/blenkernel/intern/subdiv_ccg_material.c index 9fbc99cb4f1..cf49db15b7b 100644 --- a/source/blender/blenkernel/intern/subdiv_ccg_material.c +++ b/source/blender/blenkernel/intern/subdiv_ccg_material.c @@ -10,6 +10,7 @@ #include "MEM_guardedalloc.h" #include "DNA_mesh_types.h" +#include "DNA_meshdata_types.h" typedef struct CCGMaterialFromMeshData { const Mesh *mesh; diff --git a/source/blender/blenkernel/intern/subdiv_converter_mesh.c b/source/blender/blenkernel/intern/subdiv_converter_mesh.c index 1c5078df1f3..12a5f00a68b 100644 --- a/source/blender/blenkernel/intern/subdiv_converter_mesh.c +++ b/source/blender/blenkernel/intern/subdiv_converter_mesh.c @@ -295,16 +295,16 @@ static void init_functions(OpenSubdiv_Converter *converter) static void initialize_manifold_index_array(const BLI_bitmap *used_map, const int num_elements, - int **indices_r, - int **indices_reverse_r, - int *num_manifold_elements_r) + int **r_indices, + int **r_indices_reverse, + int *r_num_manifold_elements) { int *indices = NULL; - if (indices_r != NULL) { + if (r_indices != NULL) { indices = MEM_malloc_arrayN(num_elements, sizeof(int), "manifold indices"); } int *indices_reverse = NULL; - if (indices_reverse_r != NULL) { + if (r_indices_reverse != NULL) { indices_reverse = MEM_malloc_arrayN(num_elements, sizeof(int), "manifold indices reverse"); } int offset = 0; @@ -324,13 +324,13 @@ static void initialize_manifold_index_array(const BLI_bitmap *used_map, offset++; } } - if (indices_r != NULL) { - *indices_r = indices; + if (r_indices != NULL) { + *r_indices = indices; } - if (indices_reverse_r != NULL) { - *indices_reverse_r = indices_reverse; + if (r_indices_reverse != NULL) { + *r_indices_reverse = indices_reverse; } - *num_manifold_elements_r = num_elements - offset; + *r_num_manifold_elements = num_elements - offset; } static void initialize_manifold_indices(ConverterStorage *storage) diff --git a/source/blender/blenkernel/intern/subdiv_eval.c b/source/blender/blenkernel/intern/subdiv_eval.c index b8f6dc322c5..1996273b681 100644 --- a/source/blender/blenkernel/intern/subdiv_eval.c +++ b/source/blender/blenkernel/intern/subdiv_eval.c @@ -23,7 +23,9 @@ #include "opensubdiv_evaluator_capi.h" #include "opensubdiv_topology_refiner_capi.h" -/* ============================ Helper Function ============================ */ +/* -------------------------------------------------------------------- + * Helper functions. + */ static eOpenSubdivEvaluator opensubdiv_evalutor_from_subdiv_evaluator_type( eSubdivEvaluatorType evaluator_type) @@ -40,7 +42,9 @@ static eOpenSubdivEvaluator opensubdiv_evalutor_from_subdiv_evaluator_type( return OPENSUBDIV_EVALUATOR_CPU; } -/* ====================== Main Subdivision Evaluation ====================== */ +/* -------------------------------------------------------------------- + * Main subdivision evaluation. + */ bool BKE_subdiv_eval_begin(Subdiv *subdiv, eSubdivEvaluatorType evaluator_type, @@ -269,7 +273,9 @@ void BKE_subdiv_eval_init_displacement(Subdiv *subdiv) subdiv->displacement_evaluator->initialize(subdiv->displacement_evaluator); } -/* ========================== Single point queries ========================== */ +/* -------------------------------------------------------------------- + * Single point queries. + */ void BKE_subdiv_eval_limit_point( Subdiv *subdiv, const int ptex_face_index, const float u, const float v, float r_P[3]) diff --git a/source/blender/blenkernel/intern/subsurf_ccg.c b/source/blender/blenkernel/intern/subsurf_ccg.c index 5e7a0fc116b..ba2df362b92 100644 --- a/source/blender/blenkernel/intern/subsurf_ccg.c +++ b/source/blender/blenkernel/intern/subsurf_ccg.c @@ -259,7 +259,10 @@ static void get_face_uv_map_vert( } } -static int ss_sync_from_uv(CCGSubSurf *ss, CCGSubSurf *origss, DerivedMesh *dm, MLoopUV *mloopuv) +static int ss_sync_from_uv(CCGSubSurf *ss, + CCGSubSurf *origss, + DerivedMesh *dm, + const MLoopUV *mloopuv) { MPoly *mpoly = dm->getPolyArray(dm); MLoop *mloop = dm->getLoopArray(dm); @@ -381,13 +384,9 @@ static int ss_sync_from_uv(CCGSubSurf *ss, CCGSubSurf *origss, DerivedMesh *dm, static void set_subsurf_legacy_uv(CCGSubSurf *ss, DerivedMesh *dm, DerivedMesh *result, int n) { - CCGSubSurf *uvss; - CCGFace **faceMap; - MTFace *tf; - MLoopUV *mluv; CCGFaceIterator fi; int index, gridSize, gridFaces, /*edgeSize,*/ totface, x, y, S; - MLoopUV *dmloopuv = CustomData_get_layer_n(&dm->loopData, CD_MLOOPUV, n); + const MLoopUV *dmloopuv = CustomData_get_layer_n(&dm->loopData, CD_MLOOPUV, n); /* need to update both CD_MTFACE & CD_MLOOPUV, hrmf, we could get away with * just tface except applying the modifier then looses subsurf UV */ MTFace *tface = CustomData_get_layer_n(&result->faceData, CD_MTFACE, n); @@ -398,7 +397,7 @@ static void set_subsurf_legacy_uv(CCGSubSurf *ss, DerivedMesh *dm, DerivedMesh * } /* create a CCGSubSurf from uv's */ - uvss = _getSubSurf(NULL, ccgSubSurf_getSubdivisionLevels(ss), 2, CCG_USE_ARENA); + CCGSubSurf *uvss = _getSubSurf(NULL, ccgSubSurf_getSubdivisionLevels(ss), 2, CCG_USE_ARENA); if (!ss_sync_from_uv(uvss, ss, dm, dmloopuv)) { ccgSubSurf_free(uvss); @@ -412,7 +411,7 @@ static void set_subsurf_legacy_uv(CCGSubSurf *ss, DerivedMesh *dm, DerivedMesh * gridFaces = gridSize - 1; /* make a map from original faces to CCGFaces */ - faceMap = MEM_mallocN(totface * sizeof(*faceMap), "facemapuv"); + CCGFace **faceMap = MEM_mallocN(totface * sizeof(*faceMap), "facemapuv"); for (ccgSubSurf_initFaceIterator(uvss, &fi); !ccgFaceIterator_isStopped(&fi); ccgFaceIterator_next(&fi)) { CCGFace *f = ccgFaceIterator_getCurrent(&fi); @@ -420,8 +419,8 @@ static void set_subsurf_legacy_uv(CCGSubSurf *ss, DerivedMesh *dm, DerivedMesh * } /* load coordinates from uvss into tface */ - tf = tface; - mluv = mloopuv; + MTFace *tf = tface; + MLoopUV *mluv = mloopuv; for (index = 0; index < totface; index++) { CCGFace *f = faceMap[index]; @@ -568,11 +567,8 @@ static void ss_sync_ccg_from_derivedmesh(CCGSubSurf *ss, MEdge *me; MLoop *mloop = dm->getLoopArray(dm), *ml; MPoly *mpoly = dm->getPolyArray(dm), *mp; - // MFace *mf; /* UNUSED */ int totvert = dm->getNumVerts(dm); int totedge = dm->getNumEdges(dm); - // int totface = dm->getNumTessFaces(dm); /* UNUSED */ - // int totpoly = dm->getNumFaces(dm); /* UNUSED */ int i, j; int *index; @@ -773,11 +769,6 @@ static int ccgDM_getNumPolys(DerivedMesh *dm) return ccgSubSurf_getNumFinalFaces(ccgdm->ss); } -static int ccgDM_getNumTessFaces(DerivedMesh *dm) -{ - return dm->numTessFaceData; -} - static int ccgDM_getNumLoops(DerivedMesh *dm) { CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm; @@ -883,86 +874,6 @@ static void ccgDM_getFinalVertNo(DerivedMesh *dm, int vertNum, float r_no[3]) copy_v3_v3(r_no, CCG_elem_no(&key, vd)); } -void subsurf_copy_grid_hidden(DerivedMesh *dm, - const MPoly *mpoly, - MVert *mvert, - const MDisps *mdisps) -{ - CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm; - CCGSubSurf *ss = ccgdm->ss; - int level = ccgSubSurf_getSubdivisionLevels(ss); - int gridSize = ccgSubSurf_getGridSize(ss); - int edgeSize = ccgSubSurf_getEdgeSize(ss); - int totface = ccgSubSurf_getNumFaces(ss); - int i, j, x, y; - - for (i = 0; i < totface; i++) { - CCGFace *f = ccgdm->faceMap[i].face; - - for (j = 0; j < mpoly[i].totloop; j++) { - const MDisps *md = &mdisps[mpoly[i].loopstart + j]; - int hidden_gridsize = BKE_ccg_gridsize(md->level); - int factor = BKE_ccg_factor(level, md->level); - BLI_bitmap *hidden = md->hidden; - - if (!hidden) { - continue; - } - - for (y = 0; y < gridSize; y++) { - for (x = 0; x < gridSize; x++) { - int vndx, offset; - - vndx = getFaceIndex(ss, f, j, x, y, edgeSize, gridSize); - offset = (y * factor) * hidden_gridsize + (x * factor); - if (BLI_BITMAP_TEST(hidden, offset)) { - mvert[vndx].flag |= ME_HIDE; - } - } - } - } - } -} - -void subsurf_copy_grid_paint_mask(DerivedMesh *dm, - const MPoly *mpoly, - float *paint_mask, - const GridPaintMask *grid_paint_mask) -{ - CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm; - CCGSubSurf *ss = ccgdm->ss; - int level = ccgSubSurf_getSubdivisionLevels(ss); - int gridSize = ccgSubSurf_getGridSize(ss); - int edgeSize = ccgSubSurf_getEdgeSize(ss); - int totface = ccgSubSurf_getNumFaces(ss); - int i, j, x, y, factor, gpm_gridsize; - - for (i = 0; i < totface; i++) { - CCGFace *f = ccgdm->faceMap[i].face; - const MPoly *p = &mpoly[i]; - - for (j = 0; j < p->totloop; j++) { - const GridPaintMask *gpm = &grid_paint_mask[p->loopstart + j]; - if (!gpm->data) { - continue; - } - - factor = BKE_ccg_factor(level, gpm->level); - gpm_gridsize = BKE_ccg_gridsize(gpm->level); - - for (y = 0; y < gridSize; y++) { - for (x = 0; x < gridSize; x++) { - int vndx, offset; - - vndx = getFaceIndex(ss, f, j, x, y, edgeSize, gridSize); - offset = y * factor * gpm_gridsize + x * factor; - paint_mask[vndx] = gpm->data[offset]; - } - } - } - } -} - /* utility function */ BLI_INLINE void ccgDM_to_MVert(MVert *mv, const CCGKey *key, CCGElem *elem) { @@ -1336,8 +1247,9 @@ static void *ccgDM_get_vert_data_layer(DerivedMesh *dm, int type) } BLI_rw_mutex_lock(&ccgdm->origindex_cache_rwlock, THREAD_LOCK_WRITE); - DM_add_vert_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL); - origindex = DM_get_vert_data_layer(dm, CD_ORIGINDEX); + + origindex = CustomData_add_layer( + &dm->vertData, CD_ORIGINDEX, CD_CALLOC, NULL, dm->numVertData); totorig = ccgSubSurf_getNumVerts(ss); totnone = dm->numVertData - totorig; @@ -1375,8 +1287,8 @@ static void *ccgDM_get_edge_data_layer(DerivedMesh *dm, int type) return origindex; } - DM_add_edge_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL); - origindex = DM_get_edge_data_layer(dm, CD_ORIGINDEX); + origindex = CustomData_add_layer( + &dm->edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, dm->numEdgeData); totedge = ccgSubSurf_getNumEdges(ss); totorig = totedge * (edgeSize - 1); @@ -1418,8 +1330,8 @@ static void *ccgDM_get_poly_data_layer(DerivedMesh *dm, int type) return origindex; } - DM_add_poly_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL); - origindex = DM_get_poly_data_layer(dm, CD_ORIGINDEX); + origindex = CustomData_add_layer( + &dm->polyData, CD_ORIGINDEX, CD_CALLOC, NULL, dm->numPolyData); totface = ccgSubSurf_getNumFaces(ss); @@ -1592,10 +1504,7 @@ static void set_default_ccgdm_callbacks(CCGDerivedMesh *ccgdm) ccgdm->dm.getNumVerts = ccgDM_getNumVerts; ccgdm->dm.getNumEdges = ccgDM_getNumEdges; ccgdm->dm.getNumLoops = ccgDM_getNumLoops; - /* reuse of ccgDM_getNumTessFaces is intentional here: - * subsurf polys are just created from tessfaces */ ccgdm->dm.getNumPolys = ccgDM_getNumPolys; - ccgdm->dm.getNumTessFaces = ccgDM_getNumTessFaces; ccgdm->dm.getVertCo = ccgDM_getFinalVertCo; ccgdm->dm.getVertNo = ccgDM_getFinalVertNo; @@ -1670,7 +1579,6 @@ static void set_ccgdm_all_geometry(CCGDerivedMesh *ccgdm, int index; int i; int vertNum = 0, edgeNum = 0, faceNum = 0; - int *vertOrigIndex, *polyOrigIndex, *base_polyOrigIndex, *edgeOrigIndex; short *edgeFlags = ccgdm->edgeFlags; DMFlagMat *faceFlags = ccgdm->faceFlags; int *polyidx = NULL; @@ -1687,7 +1595,6 @@ static void set_ccgdm_all_geometry(CCGDerivedMesh *ccgdm, int gridInternalEdges; WeightTable wtable = {NULL}; MEdge *medge = NULL; - MPoly *mpoly = NULL; bool has_edge_cd; edgeSize = ccgSubSurf_getEdgeSize(ss); @@ -1700,13 +1607,13 @@ static void set_ccgdm_all_geometry(CCGDerivedMesh *ccgdm, medge = dm->getEdgeArray(dm); - mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY); - base_polyOrigIndex = CustomData_get_layer(&dm->polyData, CD_ORIGINDEX); + const MPoly *mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY); + const int *base_polyOrigIndex = CustomData_get_layer(&dm->polyData, CD_ORIGINDEX); - vertOrigIndex = DM_get_vert_data_layer(&ccgdm->dm, CD_ORIGINDEX); - edgeOrigIndex = DM_get_edge_data_layer(&ccgdm->dm, CD_ORIGINDEX); + int *vertOrigIndex = DM_get_vert_data_layer(&ccgdm->dm, CD_ORIGINDEX); + int *edgeOrigIndex = DM_get_edge_data_layer(&ccgdm->dm, CD_ORIGINDEX); - polyOrigIndex = DM_get_poly_data_layer(&ccgdm->dm, CD_ORIGINDEX); + int *polyOrigIndex = DM_get_poly_data_layer(&ccgdm->dm, CD_ORIGINDEX); has_edge_cd = ((ccgdm->dm.edgeData.totlayer - (edgeOrigIndex ? 1 : 0)) != 0); @@ -2160,13 +2067,3 @@ void subsurf_calculate_limit_positions(Mesh *me, float (*r_positions)[3]) dm->release(dm); } - -bool subsurf_has_edges(DerivedMesh *dm) -{ - return dm->getNumEdges(dm) != 0; -} - -bool subsurf_has_faces(DerivedMesh *dm) -{ - return dm->getNumPolys(dm) != 0; -} diff --git a/source/blender/blenkernel/intern/tracking.c b/source/blender/blenkernel/intern/tracking.c index 348d6a91eb8..f9d3a44e5cb 100644 --- a/source/blender/blenkernel/intern/tracking.c +++ b/source/blender/blenkernel/intern/tracking.c @@ -60,7 +60,9 @@ static struct { ListBase tracks; } tracking_clipboard; -/*********************** Common functions *************************/ +/* -------------------------------------------------------------------- + * Common functions. + */ /* Free the whole list of tracks, list's head and tail are set to NULL. */ static void tracking_tracks_free(ListBase *tracks) @@ -435,7 +437,9 @@ void BKE_tracking_get_projection_matrix(MovieTracking *tracking, } } -/*********************** clipboard *************************/ +/* -------------------------------------------------------------------- + * Clipboard. + */ void BKE_tracking_clipboard_free(void) { @@ -496,7 +500,9 @@ void BKE_tracking_clipboard_paste_tracks(MovieTracking *tracking, MovieTrackingO } } -/*********************** Tracks *************************/ +/* -------------------------------------------------------------------- + * Tracks. + */ MovieTrackingTrack *BKE_tracking_track_add_empty(MovieTracking *tracking, ListBase *tracks_list) { @@ -721,67 +727,76 @@ bool BKE_tracking_track_has_enabled_marker_at_frame(MovieTrackingTrack *track, i return marker && (marker->flag & MARKER_DISABLED) == 0; } -void BKE_tracking_track_path_clear(MovieTrackingTrack *track, int ref_frame, int action) +static void path_clear_remained(MovieTrackingTrack *track, const int ref_frame) { - int a; - - if (action == TRACK_CLEAR_REMAINED) { - a = 1; - - while (a < track->markersnr) { - if (track->markers[a].framenr > ref_frame) { - track->markersnr = a; - track->markers = MEM_reallocN(track->markers, - sizeof(MovieTrackingMarker) * track->markersnr); - - break; - } - - a++; - } + for (int a = 1; a < track->markersnr; a++) { + if (track->markers[a].framenr > ref_frame) { + track->markersnr = a; + track->markers = MEM_reallocN(track->markers, + sizeof(MovieTrackingMarker) * track->markersnr); - if (track->markersnr) { - tracking_marker_insert_disabled(track, &track->markers[track->markersnr - 1], false, true); + break; } } - else if (action == TRACK_CLEAR_UPTO) { - a = track->markersnr - 1; - while (a >= 0) { - if (track->markers[a].framenr <= ref_frame) { - memmove(track->markers, - track->markers + a, - (track->markersnr - a) * sizeof(MovieTrackingMarker)); + if (track->markersnr) { + tracking_marker_insert_disabled(track, &track->markers[track->markersnr - 1], false, true); + } +} - track->markersnr = track->markersnr - a; - track->markers = MEM_reallocN(track->markers, - sizeof(MovieTrackingMarker) * track->markersnr); +static void path_clear_up_to(MovieTrackingTrack *track, const int ref_frame) +{ + for (int a = track->markersnr - 1; a >= 0; a--) { + if (track->markers[a].framenr <= ref_frame) { + memmove(track->markers, + track->markers + a, + (track->markersnr - a) * sizeof(MovieTrackingMarker)); - break; - } + track->markersnr = track->markersnr - a; + track->markers = MEM_reallocN(track->markers, + sizeof(MovieTrackingMarker) * track->markersnr); - a--; + break; } + } - if (track->markersnr) { - tracking_marker_insert_disabled(track, &track->markers[0], true, true); - } + if (track->markersnr) { + tracking_marker_insert_disabled(track, &track->markers[0], true, true); } - else if (action == TRACK_CLEAR_ALL) { - MovieTrackingMarker *marker, marker_new; +} - marker = BKE_tracking_marker_get(track, ref_frame); - marker_new = *marker; +static void path_clear_all(MovieTrackingTrack *track, const int ref_frame) +{ + MovieTrackingMarker *marker, marker_new; - MEM_freeN(track->markers); - track->markers = NULL; - track->markersnr = 0; + marker = BKE_tracking_marker_get(track, ref_frame); + marker_new = *marker; - BKE_tracking_marker_insert(track, &marker_new); + MEM_freeN(track->markers); + track->markers = NULL; + track->markersnr = 0; - tracking_marker_insert_disabled(track, &marker_new, true, true); - tracking_marker_insert_disabled(track, &marker_new, false, true); - } + BKE_tracking_marker_insert(track, &marker_new); + + tracking_marker_insert_disabled(track, &marker_new, true, true); + tracking_marker_insert_disabled(track, &marker_new, false, true); +} + +void BKE_tracking_track_path_clear(MovieTrackingTrack *track, + const int ref_frame, + const eTrackClearAction action) +{ + switch (action) { + case TRACK_CLEAR_REMAINED: + path_clear_remained(track, ref_frame); + break; + case TRACK_CLEAR_UPTO: + path_clear_up_to(track, ref_frame); + break; + case TRACK_CLEAR_ALL: + path_clear_all(track, ref_frame); + break; + }; } void BKE_tracking_tracks_join(MovieTracking *tracking, @@ -1276,7 +1291,9 @@ void BKE_tracking_tracks_deselect_all(ListBase *tracksbase) } } -/*********************** Marker *************************/ +/* -------------------------------------------------------------------- + * Marker. + */ MovieTrackingMarker *BKE_tracking_marker_insert(MovieTrackingTrack *track, MovieTrackingMarker *marker) @@ -1350,60 +1367,52 @@ void BKE_tracking_marker_delete(MovieTrackingTrack *track, int framenr) } } -void BKE_tracking_marker_clamp(MovieTrackingMarker *marker, int event) +void BKE_tracking_marker_clamp_pattern_position(MovieTrackingMarker *marker) { float pat_min[2], pat_max[2]; - BKE_tracking_marker_pattern_minmax(marker, pat_min, pat_max); - if (event == CLAMP_PAT_DIM) { - for (int a = 0; a < 2; a++) { - /* search shouldn't be resized smaller than pattern */ - marker->search_min[a] = min_ff(pat_min[a], marker->search_min[a]); - marker->search_max[a] = max_ff(pat_max[a], marker->search_max[a]); - } - } - else if (event == CLAMP_PAT_POS) { - float dim[2]; - - sub_v2_v2v2(dim, pat_max, pat_min); - - for (int a = 0; a < 2; a++) { - /* pattern shouldn't be moved outside of search */ - if (pat_min[a] < marker->search_min[a]) { - for (int b = 0; b < 4; b++) { - marker->pattern_corners[b][a] += marker->search_min[a] - pat_min[a]; - } + for (int a = 0; a < 2; a++) { + if (pat_min[a] < marker->search_min[a]) { + for (int b = 0; b < 4; b++) { + marker->pattern_corners[b][a] += marker->search_min[a] - pat_min[a]; } - if (pat_max[a] > marker->search_max[a]) { - for (int b = 0; b < 4; b++) { - marker->pattern_corners[b][a] -= pat_max[a] - marker->search_max[a]; - } + } + if (pat_max[a] > marker->search_max[a]) { + for (int b = 0; b < 4; b++) { + marker->pattern_corners[b][a] -= pat_max[a] - marker->search_max[a]; } } } - else if (event == CLAMP_SEARCH_DIM) { - for (int a = 0; a < 2; a++) { - /* search shouldn't be resized smaller than pattern */ - marker->search_min[a] = min_ff(pat_min[a], marker->search_min[a]); - marker->search_max[a] = max_ff(pat_max[a], marker->search_max[a]); - } +} + +void BKE_tracking_marker_clamp_search_size(MovieTrackingMarker *marker) +{ + float pat_min[2], pat_max[2]; + BKE_tracking_marker_pattern_minmax(marker, pat_min, pat_max); + + for (int a = 0; a < 2; a++) { + marker->search_min[a] = min_ff(pat_min[a], marker->search_min[a]); + marker->search_max[a] = max_ff(pat_max[a], marker->search_max[a]); } - else if (event == CLAMP_SEARCH_POS) { - float dim[2]; +} - sub_v2_v2v2(dim, marker->search_max, marker->search_min); +void BKE_tracking_marker_clamp_search_position(MovieTrackingMarker *marker) +{ + float pat_min[2], pat_max[2]; + BKE_tracking_marker_pattern_minmax(marker, pat_min, pat_max); - for (int a = 0; a < 2; a++) { - /* search shouldn't be moved inside pattern */ - if (marker->search_min[a] > pat_min[a]) { - marker->search_min[a] = pat_min[a]; - marker->search_max[a] = marker->search_min[a] + dim[a]; - } - if (marker->search_max[a] < pat_max[a]) { - marker->search_max[a] = pat_max[a]; - marker->search_min[a] = marker->search_max[a] - dim[a]; - } + float dim[2]; + sub_v2_v2v2(dim, marker->search_max, marker->search_min); + + for (int a = 0; a < 2; a++) { + if (marker->search_min[a] > pat_min[a]) { + marker->search_min[a] = pat_min[a]; + marker->search_max[a] = marker->search_min[a] + dim[a]; + } + if (marker->search_max[a] < pat_max[a]) { + marker->search_max[a] = pat_max[a]; + marker->search_min[a] = marker->search_max[a] - dim[a]; } } } @@ -1591,7 +1600,9 @@ void BKE_tracking_marker_get_subframe_position(MovieTrackingTrack *track, add_v2_v2(pos, track->offset); } -/*********************** Plane Track *************************/ +/* -------------------------------------------------------------------- + * Plane track. + */ MovieTrackingPlaneTrack *BKE_tracking_plane_track_add(MovieTracking *tracking, ListBase *plane_tracks_base, @@ -1796,7 +1807,9 @@ void BKE_tracking_plane_tracks_replace_point_track(MovieTracking *tracking, } } -/*********************** Plane Marker *************************/ +/* -------------------------------------------------------------------- + * Plane marker. + */ MovieTrackingPlaneMarker *BKE_tracking_plane_marker_insert(MovieTrackingPlaneTrack *plane_track, MovieTrackingPlaneMarker *plane_marker) @@ -1974,7 +1987,9 @@ void BKE_tracking_plane_marker_get_subframe_corners(MovieTrackingPlaneTrack *pla } } -/*********************** Object *************************/ +/* -------------------------------------------------------------------- + * Object. + */ MovieTrackingObject *BKE_tracking_object_add(MovieTracking *tracking, const char *name) { @@ -2119,7 +2134,9 @@ MovieTrackingReconstruction *BKE_tracking_object_get_reconstruction(MovieTrackin return &object->reconstruction; } -/*********************** Camera *************************/ +/* -------------------------------------------------------------------- + * Camera. + */ static int reconstructed_camera_index_get(MovieTrackingReconstruction *reconstruction, int framenr, @@ -2275,7 +2292,9 @@ void BKE_tracking_camera_get_reconstructed_interpolate(MovieTracking *tracking, reconstructed_camera_scale_set(object, mat); } -/*********************** Distortion/Undistortion *************************/ +/* -------------------------------------------------------------------- + * (Un)distortion. + */ MovieDistortion *BKE_tracking_distortion_new(MovieTracking *tracking, int calibration_width, @@ -2588,7 +2607,9 @@ void BKE_tracking_max_distortion_delta_across_bound(MovieTracking *tracking, } } -/*********************** Image sampling *************************/ +/* -------------------------------------------------------------------- + * Image sampling. + */ static void disable_imbuf_channels(ImBuf *ibuf, MovieTrackingTrack *track, bool grayscale) { @@ -2832,7 +2853,9 @@ void BKE_tracking_disable_channels( } } -/*********************** Dopesheet functions *************************/ +/* -------------------------------------------------------------------- + * Dopesheet functions. + */ /* ** Channels sort comparators ** */ diff --git a/source/blender/blenkernel/intern/tracking_plane_tracker.c b/source/blender/blenkernel/intern/tracking_plane_tracker.c index 5e60f6f59a9..c4379ea61bc 100644 --- a/source/blender/blenkernel/intern/tracking_plane_tracker.c +++ b/source/blender/blenkernel/intern/tracking_plane_tracker.c @@ -21,12 +21,12 @@ typedef double Vec2[2]; static int point_markers_correspondences_on_both_image( - MovieTrackingPlaneTrack *plane_track, int frame1, int frame2, Vec2 **x1_r, Vec2 **x2_r) + MovieTrackingPlaneTrack *plane_track, int frame1, int frame2, Vec2 **r_x1, Vec2 **r_x2) { Vec2 *x1, *x2; - *x1_r = x1 = MEM_mallocN(sizeof(*x1) * plane_track->point_tracksnr, "point correspondences x1"); - *x2_r = x2 = MEM_mallocN(sizeof(*x1) * plane_track->point_tracksnr, "point correspondences x2"); + *r_x1 = x1 = MEM_mallocN(sizeof(*x1) * plane_track->point_tracksnr, "point correspondences x1"); + *r_x2 = x2 = MEM_mallocN(sizeof(*x1) * plane_track->point_tracksnr, "point correspondences x2"); int correspondence_index = 0; for (int i = 0; i < plane_track->point_tracksnr; i++) { diff --git a/source/blender/blenkernel/intern/unit.c b/source/blender/blenkernel/intern/unit.c index 02134623a31..30e02e5411b 100644 --- a/source/blender/blenkernel/intern/unit.c +++ b/source/blender/blenkernel/intern/unit.c @@ -268,7 +268,7 @@ static struct bUnitCollection buImperialAclCollection = {buImperialAclDef, 0, 0, /* Time. */ static struct bUnitDef buNaturalTimeDef[] = { /* Weeks? - probably not needed for Blender. */ - {"day", "days", "d", NULL, "Days", "DAYS", 90000.0, 0.0, B_UNIT_DEF_NONE}, + {"day", "days", "d", NULL, "Days", "DAYS", 86400.0, 0.0, B_UNIT_DEF_NONE}, {"hour", "hours", "hr", "h", "Hours", "HOURS", 3600.0, 0.0, B_UNIT_DEF_NONE}, {"minute", "minutes", "min", "m", "Minutes", "MINUTES", 60.0, 0.0, B_UNIT_DEF_NONE}, {"second", "seconds", "sec", "s", "Seconds", "SECONDS", 1.0, 0.0, B_UNIT_DEF_NONE}, /* Base unit. */ diff --git a/source/blender/blenkernel/intern/volume.cc b/source/blender/blenkernel/intern/volume.cc index 307466d7dc9..82405830437 100644 --- a/source/blender/blenkernel/intern/volume.cc +++ b/source/blender/blenkernel/intern/volume.cc @@ -97,12 +97,7 @@ static struct VolumeFileCache { /* Cache Entry */ struct Entry { Entry(const std::string &filepath, const openvdb::GridBase::Ptr &grid) - : filepath(filepath), - grid_name(grid->getName()), - grid(grid), - is_loaded(false), - num_metadata_users(0), - num_tree_users(0) + : filepath(filepath), grid_name(grid->getName()), grid(grid) { } @@ -110,9 +105,7 @@ static struct VolumeFileCache { : filepath(other.filepath), grid_name(other.grid_name), grid(other.grid), - is_loaded(other.is_loaded), - num_metadata_users(0), - num_tree_users(0) + is_loaded(other.is_loaded) { } @@ -151,12 +144,12 @@ static struct VolumeFileCache { blender::Map<int, openvdb::GridBase::Ptr> simplified_grids; /* Has the grid tree been loaded? */ - mutable bool is_loaded; + mutable bool is_loaded = false; /* Error message if an error occurred while loading. */ std::string error_msg; /* User counting. */ - int num_metadata_users; - int num_tree_users; + int num_metadata_users = 0; + int num_tree_users = 0; /* Mutex for on-demand reading of tree. */ mutable std::mutex mutex; }; |