diff options
Diffstat (limited to 'source/blender/blenkernel')
182 files changed, 15677 insertions, 8768 deletions
diff --git a/source/blender/blenkernel/BKE_DerivedMesh.h b/source/blender/blenkernel/BKE_DerivedMesh.h index 4fc519ecd6d..f835f4332ed 100644 --- a/source/blender/blenkernel/BKE_DerivedMesh.h +++ b/source/blender/blenkernel/BKE_DerivedMesh.h @@ -134,8 +134,9 @@ struct DerivedMesh { * \warning Typical access is done via #getLoopTriArray, #getNumLoopTri. */ struct { - /* WARNING! swapping between array (ready-to-be-used data) and array_wip (where data is actually computed) - * shall always be protected by same lock as one used for looptris computing. */ + /* WARNING! swapping between array (ready-to-be-used data) and array_wip + * (where data is actually computed) shall always be protected by same + * lock as one used for looptris computing. */ struct MLoopTri *array, *array_wip; int num; int num_alloc; diff --git a/source/blender/blenkernel/BKE_action.h b/source/blender/blenkernel/BKE_action.h index 08237be0a21..69f3070fcba 100644 --- a/source/blender/blenkernel/BKE_action.h +++ b/source/blender/blenkernel/BKE_action.h @@ -35,6 +35,7 @@ struct bActionGroup; struct bItasc; struct bPose; struct bPoseChannel; +struct bPoseChannel_Runtime; /* Kernel prototypes */ #ifdef __cplusplus @@ -132,7 +133,10 @@ void action_groups_clear_tempflags(struct bAction *act); void BKE_pose_channel_free(struct bPoseChannel *pchan); void BKE_pose_channel_free_ex(struct bPoseChannel *pchan, bool do_id_user); -void BKE_pose_channel_free_bbone_cache(struct bPoseChannel *pchan); +void BKE_pose_channel_runtime_reset(struct bPoseChannel_Runtime *runtime); +void BKE_pose_channel_runtime_free(struct bPoseChannel_Runtime *runtime); + +void BKE_pose_channel_free_bbone_cache(struct bPoseChannel_Runtime *runtime); void BKE_pose_channels_free(struct bPose *pose); void BKE_pose_channels_free_ex(struct bPose *pose, bool do_id_user); diff --git a/source/blender/blenkernel/BKE_animsys.h b/source/blender/blenkernel/BKE_animsys.h index 0503efb1661..583a90b2dee 100644 --- a/source/blender/blenkernel/BKE_animsys.h +++ b/source/blender/blenkernel/BKE_animsys.h @@ -95,7 +95,8 @@ void BKE_animdata_merge_copy(struct Main *bmain, /* ************************************* */ /* KeyingSets API */ -/* Used to create a new 'custom' KeyingSet for the user, that will be automatically added to the stack */ +/* Used to create a new 'custom' KeyingSet for the user, + * that will be automatically added to the stack */ struct KeyingSet *BKE_keyingset_add( struct ListBase *list, const char idname[], const char name[], short flag, short keyingflag); diff --git a/source/blender/blenkernel/BKE_armature.h b/source/blender/blenkernel/BKE_armature.h index 50457c5b3f0..b5da30e725d 100644 --- a/source/blender/blenkernel/BKE_armature.h +++ b/source/blender/blenkernel/BKE_armature.h @@ -144,8 +144,9 @@ void BKE_armature_mat_pose_to_bone_ex(struct Depsgraph *depsgraph, float outmat[4][4]); void BKE_pchan_mat3_to_rot(struct bPoseChannel *pchan, float mat[3][3], bool use_compat); +void BKE_pchan_rot_to_mat3(const struct bPoseChannel *pchan, float mat[3][3]); void BKE_pchan_apply_mat4(struct bPoseChannel *pchan, float mat[4][4], bool use_comat); -void BKE_pchan_to_mat4(struct bPoseChannel *pchan, float chan_mat[4][4]); +void BKE_pchan_to_mat4(const struct bPoseChannel *pchan, float chan_mat[4][4]); void BKE_pchan_calc_mat(struct bPoseChannel *pchan); /* Simple helper, computes the offset bone matrix. */ @@ -207,8 +208,8 @@ typedef struct BBoneSplineParameters { /* Control values. */ float ease1, ease2; float roll1, roll2; - float scaleIn, scaleOut; - float curveInX, curveInY, curveOutX, curveOutY; + float scale_in_x, scale_in_y, scale_out_x, scale_out_y; + float curve_in_x, curve_in_y, curve_out_x, curve_out_y; } BBoneSplineParameters; void BKE_pchan_bbone_handles_get(struct bPoseChannel *pchan, @@ -335,17 +336,6 @@ void BKE_pose_eval_proxy_copy_bone(struct Depsgraph *depsgraph, struct Object *object, int pchan_index); -/* BBOne deformation cache. - * - * The idea here is to pre-calculate deformation queternions, matricies and such - * used by armature_deform_verts(). - */ -struct ObjectBBoneDeform; -struct ObjectBBoneDeform *BKE_armature_cached_bbone_deformation_get(struct Object *object); -void BKE_armature_cached_bbone_deformation_free_data(struct Object *object); -void BKE_armature_cached_bbone_deformation_free(struct Object *object); -void BKE_armature_cached_bbone_deformation_update(struct Object *object); - #ifdef __cplusplus } #endif diff --git a/source/blender/blenkernel/BKE_blender_version.h b/source/blender/blenkernel/BKE_blender_version.h index 0566ecf3444..e01f6a6b751 100644 --- a/source/blender/blenkernel/BKE_blender_version.h +++ b/source/blender/blenkernel/BKE_blender_version.h @@ -27,7 +27,7 @@ * \note Use #STRINGIFY() rather than defining with quotes. */ #define BLENDER_VERSION 280 -#define BLENDER_SUBVERSION 57 +#define BLENDER_SUBVERSION 60 /** Several breakages with 280, e.g. collections vs layers. */ #define BLENDER_MINVERSION 280 #define BLENDER_MINSUBVERSION 0 diff --git a/source/blender/blenkernel/BKE_bvhutils.h b/source/blender/blenkernel/BKE_bvhutils.h index 1d40ba0bc78..4b64b6fa269 100644 --- a/source/blender/blenkernel/BKE_bvhutils.h +++ b/source/blender/blenkernel/BKE_bvhutils.h @@ -84,11 +84,12 @@ typedef struct BVHTreeFromMesh { /** * Builds a bvh tree where nodes are the relevant elements of the given mesh. - * Configures BVHTreeFromMesh. + * Configures #BVHTreeFromMesh. * * The tree is build in mesh space coordinates, this means special care must be made on queries * so that the coordinates and rays are first translated on the mesh local coordinates. - * Reason for this is that bvh_from_mesh_* can use a cache in some cases and so it becomes possible to reuse a BVHTree. + * Reason for this is that bvh_from_mesh_* can use a cache in some cases and so it + * becomes possible to reuse a #BVHTree. * * free_bvhtree_from_mesh should be called when the tree is no longer needed. */ diff --git a/source/blender/blenkernel/BKE_cachefile.h b/source/blender/blenkernel/BKE_cachefile.h index b991ac24284..257975e3c17 100644 --- a/source/blender/blenkernel/BKE_cachefile.h +++ b/source/blender/blenkernel/BKE_cachefile.h @@ -29,8 +29,10 @@ extern "C" { #endif struct CacheFile; +struct CacheReader; struct Depsgraph; struct Main; +struct Object; struct Scene; void BKE_cachefiles_init(void); @@ -52,24 +54,27 @@ void BKE_cachefile_make_local(struct Main *bmain, struct CacheFile *cache_file, const bool lib_local); -void BKE_cachefile_reload(const struct Main *bmain, struct CacheFile *cache_file); +void BKE_cachefile_reload(struct Depsgraph *depsgraph, struct CacheFile *cache_file); -void BKE_cachefile_ensure_handle(const struct Main *bmain, struct CacheFile *cache_file); - -void BKE_cachefile_update_frame(struct Main *bmain, - struct Depsgraph *depsgraph, - struct Scene *scene, - const float ctime, - const float fps); +void BKE_cachefile_eval(struct Main *bmain, + struct Depsgraph *depsgraph, + struct CacheFile *cache_file); bool BKE_cachefile_filepath_get(const struct Main *bmain, + const struct Depsgraph *depsgrah, const struct CacheFile *cache_file, - float frame, char r_filename[1024]); -float BKE_cachefile_time_offset(struct CacheFile *cache_file, const float time, const float fps); +float BKE_cachefile_time_offset(const struct CacheFile *cache_file, + const float time, + const float fps); -void BKE_cachefile_clean(struct Main *bmain, struct CacheFile *cache_file); +/* Modifiers and constraints open and free readers through these. */ +void BKE_cachefile_reader_open(struct CacheFile *cache_file, + struct CacheReader **reader, + struct Object *object, + const char *object_path); +void BKE_cachefile_reader_free(struct CacheFile *cache_file, struct CacheReader **reader); #ifdef __cplusplus } diff --git a/source/blender/blenkernel/BKE_collection.h b/source/blender/blenkernel/BKE_collection.h index f06d9d1e64e..47786629aed 100644 --- a/source/blender/blenkernel/BKE_collection.h +++ b/source/blender/blenkernel/BKE_collection.h @@ -180,7 +180,8 @@ typedef void (*BKE_scene_collections_Cb)(struct Collection *ob, void *data); #define FOREACH_COLLECTION_VISIBLE_OBJECT_RECURSIVE_END \ } \ } \ - } + } \ + ((void)0) #define FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(_collection, _object) \ for (Base *_base = (Base *)BKE_collection_object_cache_get(_collection).first; _base; \ diff --git a/source/blender/blenkernel/BKE_constraint.h b/source/blender/blenkernel/BKE_constraint.h index 9ad3657284d..8fe3bd77a26 100644 --- a/source/blender/blenkernel/BKE_constraint.h +++ b/source/blender/blenkernel/BKE_constraint.h @@ -101,13 +101,22 @@ typedef struct bConstraintTypeInfo { void (*id_looper)(struct bConstraint *con, ConstraintIDFunc func, void *userdata); /** copy any special data that is allocated separately (optional) */ void (*copy_data)(struct bConstraint *con, struct bConstraint *src); - /** set settings for data that will be used for bConstraint.data (memory already allocated using MEM_callocN) */ + /** + * Set settings for data that will be used for #bConstraint.data + * (memory already allocated using #MEM_callocN). + */ void (*new_data)(void *cdata); /* target handling function pointers */ - /** for multi-target constraints: return that list; otherwise make a temporary list (returns number of targets) */ + /** + * For multi-target constraints: return that list; + * otherwise make a temporary list (returns number of targets). + */ int (*get_constraint_targets)(struct bConstraint *con, struct ListBase *list); - /** for single-target constraints only: flush data back to source data, and the free memory used */ + /** + * For single-target constraints only: + * flush data back to source data, and the free memory used. + */ void (*flush_constraint_targets)(struct bConstraint *con, struct ListBase *list, bool no_copy); /* evaluation */ diff --git a/source/blender/blenkernel/BKE_customdata.h b/source/blender/blenkernel/BKE_customdata.h index 88035e2b3d9..f354e5e6de3 100644 --- a/source/blender/blenkernel/BKE_customdata.h +++ b/source/blender/blenkernel/BKE_customdata.h @@ -61,14 +61,18 @@ extern const CustomData_MeshMasks CD_MASK_EVERYTHING; * memory space for totelem elements. mask must be an array of length * CD_NUMTYPES elements, that indicate if a layer can be copied. */ -/* add/copy/merge allocation types */ +/** Add/copy/merge allocation types. */ typedef enum eCDAllocType { - CD_ASSIGN = 0, /* use the data pointer */ - CD_CALLOC = 1, /* allocate blank memory */ - CD_DEFAULT = 2, /* allocate and set to default */ - CD_REFERENCE = 3, /* use data pointers, set layer flag NOFREE */ - CD_DUPLICATE = 4, /* do a full copy of all layers, only allowed if source - * has same number of elements */ + /** Use the data pointer. */ + CD_ASSIGN = 0, + /** Allocate blank memory. */ + CD_CALLOC = 1, + /** Allocate and set to default. */ + CD_DEFAULT = 2, + /** Use data pointers, set layer flag NOFREE. */ + CD_REFERENCE = 3, + /** Do a full copy of all layers, only allowed if source has same number of elements. */ + CD_DUPLICATE = 4, } eCDAllocType; #define CD_TYPE_AS_MASK(_type) (CustomDataMask)((CustomDataMask)1 << (CustomDataMask)(_type)) @@ -109,7 +113,8 @@ bool CustomData_has_referenced(const struct CustomData *data); * implemented for mloopuv/mloopcol, for now.*/ void CustomData_data_copy_value(int type, const void *source, void *dest); -/* Same as above, but doing advanced mixing. Only available for a few types of data (like colors...). */ +/* Same as above, but doing advanced mixing. + * Only available for a few types of data (like colors...). */ void CustomData_data_mix_value( int type, const void *source, void *dest, const int mixmode, const float mixfactor); @@ -474,8 +479,8 @@ typedef void (*cd_datatransfer_interp)(const struct CustomDataTransferLayerMap * const float mix_factor); /** - * Fake CD_LAYERS (those are actually 'real' data stored directly into elements' structs, or otherwise not (directly) - * accessible to usual CDLayer system). */ + * Fake CD_LAYERS (those are actually 'real' data stored directly into elements' structs, + * or otherwise not (directly) accessible to usual CDLayer system). */ enum { CD_FAKE = 1 << 8, @@ -527,23 +532,29 @@ typedef struct CustomDataTransferLayerMap { int data_type; int mix_mode; float mix_factor; - const float * - mix_weights; /* If non-NULL, array of weights, one for each dest item, replaces mix_factor. */ - - const void * - data_src; /* Data source array (can be regular CD data, vertices/edges/etc., keyblocks...). */ - void *data_dst; /* Data dest array (same type as dat_src). */ - int data_src_n; /* Index to affect in data_src (used e.g. for vgroups). */ - int data_dst_n; /* Index to affect in data_dst (used e.g. for vgroups). */ - size_t elem_size; /* Size of one element of data_src/data_dst. */ - - size_t data_size; /* Size of actual data we transfer. */ - size_t - data_offset; /* Offset of actual data we transfer (in element contained in data_src/dst). */ - uint64_t data_flag; /* For bitflag transfer, flag(s) to affect in transferred data. */ - - void * - interp_data; /* Opaque pointer, to be used by specific interp callback (e.g. transformspace for normals). */ + /** If non-NULL, array of weights, one for each dest item, replaces mix_factor. */ + const float *mix_weights; + + /** Data source array (can be regular CD data, vertices/edges/etc., keyblocks...). */ + const void *data_src; + /** Data dest array (same type as dat_src). */ + void *data_dst; + /** Index to affect in data_src (used e.g. for vgroups). */ + int data_src_n; + /** Index to affect in data_dst (used e.g. for vgroups). */ + int data_dst_n; + /** Size of one element of data_src/data_dst. */ + size_t elem_size; + + /** Size of actual data we transfer. */ + size_t data_size; + /** Offset of actual data we transfer (in element contained in data_src/dst). */ + size_t data_offset; + /** For bitflag transfer, flag(s) to affect in transferred data. */ + uint64_t data_flag; + + /** Opaque pointer, to be used by specific interp callback (e.g. transformspace for normals). */ + void *interp_data; cd_datatransfer_interp interp; } CustomDataTransferLayerMap; diff --git a/source/blender/blenkernel/BKE_data_transfer.h b/source/blender/blenkernel/BKE_data_transfer.h index a909328ac9c..79ef512bc1f 100644 --- a/source/blender/blenkernel/BKE_data_transfer.h +++ b/source/blender/blenkernel/BKE_data_transfer.h @@ -119,7 +119,7 @@ enum { DT_LAYERS_NAME_DST = -2, DT_LAYERS_INDEX_DST = -3, #if 0 /* TODO */ - DT_LAYERS_CREATE_DST = -4, /* Never replace existing data in dst, always create new layers. */ + DT_LAYERS_CREATE_DST = -4, /* Never replace existing data in dst, always create new layers. */ #endif }; diff --git a/source/blender/blenkernel/BKE_deform.h b/source/blender/blenkernel/BKE_deform.h index 510e989a087..fd7fa632999 100644 --- a/source/blender/blenkernel/BKE_deform.h +++ b/source/blender/blenkernel/BKE_deform.h @@ -109,7 +109,8 @@ void defvert_normalize_lock_map(struct MDeformVert *dvert, const bool *lock_flags, const int defbase_tot); -/* Utilities to 'extract' a given vgroup into a simple float array, for verts, but also edges/polys/loops. */ +/* 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, const int defgroup, const int num_verts, diff --git a/source/blender/blenkernel/BKE_dynamicpaint.h b/source/blender/blenkernel/BKE_dynamicpaint.h index 9f4f2862c95..c4f05d404ce 100644 --- a/source/blender/blenkernel/BKE_dynamicpaint.h +++ b/source/blender/blenkernel/BKE_dynamicpaint.h @@ -83,13 +83,11 @@ void dynamicPaint_freeBrush(struct DynamicPaintModifierData *pmd); void dynamicPaint_freeSurfaceData(struct DynamicPaintSurface *surface); void dynamicPaint_cacheUpdateFrames(struct DynamicPaintSurface *surface); -bool dynamicPaint_surfaceHasColorPreview(struct DynamicPaintSurface *surface); bool dynamicPaint_outputLayerExists(struct DynamicPaintSurface *surface, struct Object *ob, int output); void dynamicPaintSurface_updateType(struct DynamicPaintSurface *surface); void dynamicPaintSurface_setUniqueName(struct DynamicPaintSurface *surface, const char *basename); -void dynamicPaint_resetPreview(struct DynamicPaintCanvasSettings *canvas); struct DynamicPaintSurface *get_activeSurface(struct DynamicPaintCanvasSettings *canvas); /* image sequence baking */ diff --git a/source/blender/blenkernel/BKE_effect.h b/source/blender/blenkernel/BKE_effect.h index 15b59993d77..94e8f4304b8 100644 --- a/source/blender/blenkernel/BKE_effect.h +++ b/source/blender/blenkernel/BKE_effect.h @@ -154,8 +154,14 @@ int get_effector_data(struct EffectorCache *eff, int real_velocity); /* required for particle_system.c */ -//void do_physical_effector(struct EffectorData *eff, struct EffectorPoint *point, float *total_force); -//float effector_falloff(struct EffectorData *eff, struct EffectorPoint *point, struct EffectorWeights *weights); +#if 0 +void do_physical_effector(struct EffectorData *eff, + struct EffectorPoint *point, + float *total_force); +float effector_falloff(struct EffectorData *eff, + struct EffectorPoint *point, + struct EffectorWeights *weights); +#endif /* EffectedPoint->flag */ #define PE_WIND_AS_SPEED 1 diff --git a/source/blender/blenkernel/BKE_fcurve.h b/source/blender/blenkernel/BKE_fcurve.h index 52a4d00b117..c1232addee3 100644 --- a/source/blender/blenkernel/BKE_fcurve.h +++ b/source/blender/blenkernel/BKE_fcurve.h @@ -115,8 +115,6 @@ float evaluate_driver(struct PathResolvedRNA *anim_rna, /* ************** F-Curve Modifiers *************** */ -typedef struct GHash FModifierStackStorage; - /* F-Curve Modifier Type-Info (fmi): * This struct provides function pointers for runtime, so that functions can be * written more generally (with fewer/no special exceptions for various modifiers). @@ -130,46 +128,40 @@ typedef struct GHash FModifierStackStorage; */ typedef struct FModifierTypeInfo { /* admin/ident */ - short type; /* FMODIFIER_TYPE_### */ - short size; /* size in bytes of the struct */ - short acttype; /* eFMI_Action_Types */ - short requires; /* eFMI_Requirement_Flags */ - char name[64]; /* name of modifier in interface */ - char structName[64]; /* name of struct for SDNA */ + /** #FMODIFIER_TYPE_* */ + short type; + /** size in bytes of the struct. */ + short size; + /** #eFMI_Action_Types. */ + short acttype; + /** #eFMI_Requirement_Flags. */ + short requires; + /** name of modifier in interface. */ + char name[64]; + /** name of struct for SDNA. */ + char structName[64]; + /** Size of buffer that can be reused between time and value evaluation. */ + uint storage_size; /* data management function pointers - special handling */ - /* free any data that is allocated separately (optional) */ + /** Free any data that is allocated separately (optional). */ void (*free_data)(struct FModifier *fcm); - /* copy any special data that is allocated separately (optional) */ + /** Copy any special data that is allocated separately (optional). */ void (*copy_data)(struct FModifier *fcm, const struct FModifier *src); - /* set settings for data that will be used for FCuModifier.data (memory already allocated using MEM_callocN) */ + /** + * Set settings for data that will be used for FCuModifier.data + * (memory already allocated using #MEM_callocN). */ void (*new_data)(void *mdata); - /* verifies that the modifier settings are valid */ + /** Verifies that the modifier settings are valid */ void (*verify_data)(struct FModifier *fcm); /* evaluation */ - /* evaluate time that the modifier requires the F-Curve to be evaluated at */ - float (*evaluate_modifier_time)(struct FCurve *fcu, - struct FModifier *fcm, - float cvalue, - float evaltime); - /* evaluate the modifier for the given time and 'accumulated' value */ - void (*evaluate_modifier)(struct FCurve *fcu, - struct FModifier *fcm, - float *cvalue, - float evaltime); - - /* Same as above but for modifiers which requires storage */ - float (*evaluate_modifier_time_storage)(FModifierStackStorage *storage, - struct FCurve *fcu, - struct FModifier *fcm, - float cvalue, - float evaltime); - void (*evaluate_modifier_storage)(FModifierStackStorage *storage, - struct FCurve *fcu, - struct FModifier *fcm, - float *cvalue, - float evaltime); + /** Evaluate time that the modifier requires the F-Curve to be evaluated at */ + float (*evaluate_modifier_time)( + struct FCurve *fcu, struct FModifier *fcm, float cvalue, float evaltime, void *storage); + /** Evaluate the modifier for the given time and 'accumulated' value */ + void (*evaluate_modifier)( + struct FCurve *fcu, struct FModifier *fcm, float *cvalue, float evaltime, void *storage); } FModifierTypeInfo; /* Values which describe the behavior of a FModifier Type */ @@ -194,9 +186,6 @@ typedef enum eFMI_Requirement_Flags { FMI_REQUIRES_NOTHING = (1 << 1), /* refer to modifier instance */ FMI_REQUIRES_RUNTIME_CHECK = (1 << 2), - - /* Requires to store data shared between time and valua evaluation */ - FMI_REQUIRES_STORAGE = (1 << 3), } eFMI_Requirement_Flags; /* Function Prototypes for FModifierTypeInfo's */ @@ -216,14 +205,19 @@ void set_active_fmodifier(ListBase *modifiers, struct FModifier *fcm); bool list_has_suitable_fmodifier(ListBase *modifiers, int mtype, short acttype); -FModifierStackStorage *evaluate_fmodifiers_storage_new(ListBase *modifiers); -void evaluate_fmodifiers_storage_free(FModifierStackStorage *storage); -float evaluate_time_fmodifiers(FModifierStackStorage *storage, +typedef struct FModifiersStackStorage { + uint modifier_count; + uint size_per_modifier; + void *buffer; +} FModifiersStackStorage; + +uint evaluate_fmodifiers_storage_size_per_modifier(ListBase *modifiers); +float evaluate_time_fmodifiers(FModifiersStackStorage *storage, ListBase *modifiers, struct FCurve *fcu, float cvalue, float evaltime); -void evaluate_value_fmodifiers(FModifierStackStorage *storage, +void evaluate_value_fmodifiers(FModifiersStackStorage *storage, ListBase *modifiers, struct FCurve *fcu, float *cvalue, @@ -238,7 +232,8 @@ int BKE_fcm_envelope_find_index(struct FCM_EnvelopeData *array, /* ************** F-Curves API ******************** */ -/* threshold for binary-searching keyframes - threshold here should be good enough for now, but should become userpref */ +/* threshold for binary-searching keyframes - threshold here should be good enough for now, + * but should become userpref */ #define BEZT_BINARYSEARCH_THRESH 0.01f /* was 0.00001, but giving errors */ /* -------- Data Management -------- */ @@ -258,7 +253,8 @@ struct FCurve *iter_step_fcurve(struct FCurve *fcu_iter, const char rna_path[]); struct FCurve *id_data_find_fcurve( ID *id, void *data, struct StructRNA *type, const char *prop_name, int index, bool *r_driven); -/* Get list of LinkData's containing pointers to the F-Curves which control the types of data indicated +/* Get list of LinkData's containing pointers to the F-Curves which control the types of data + * indicated * e.g. numMatches = list_find_data_fcurves(matches, &act->curves, "pose.bones[", "MyFancyBone"); */ int list_find_data_fcurves(ListBase *dst, @@ -274,7 +270,8 @@ struct FCurve *rna_get_fcurve(struct PointerRNA *ptr, struct bAction **r_action, bool *r_driven, bool *r_special); -/* Same as above, but takes a context data, temp hack needed for complex paths like texture ones. */ +/* Same as above, but takes a context data, + * temp hack needed for complex paths like texture ones. */ struct FCurve *rna_get_fcurve_context_ui(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, diff --git a/source/blender/blenkernel/BKE_gpencil_modifier.h b/source/blender/blenkernel/BKE_gpencil_modifier.h index 128ff39de7a..4655abf6e02 100644 --- a/source/blender/blenkernel/BKE_gpencil_modifier.h +++ b/source/blender/blenkernel/BKE_gpencil_modifier.h @@ -38,8 +38,8 @@ struct Object; struct Scene; struct ViewLayer; struct bArmature; -struct - bContext; /* NOTE: bakeModifier() - called from UI - needs to create new datablocks, hence the need for this */ +/* NOTE: bakeModifier() called from UI: needs to create new datablocks, hence the need for this. */ +struct bContext; struct bGPDframe; struct bGPDlayer; struct bGPDstroke; diff --git a/source/blender/blenkernel/BKE_image.h b/source/blender/blenkernel/BKE_image.h index 4d3ad17519e..28886a5a195 100644 --- a/source/blender/blenkernel/BKE_image.h +++ b/source/blender/blenkernel/BKE_image.h @@ -233,6 +233,7 @@ struct Image *BKE_image_add_generated(struct Main *bmain, struct Image *BKE_image_add_from_imbuf(struct Main *bmain, struct ImBuf *ibuf, const char *name); /* for reload, refresh, pack */ +void BKE_imageuser_default(struct ImageUser *iuser); void BKE_image_init_imageuser(struct Image *ima, struct ImageUser *iuser); void BKE_image_signal(struct Main *bmain, struct Image *ima, struct ImageUser *iuser, int signal); @@ -293,7 +294,7 @@ void BKE_image_free_anim_ibufs(struct Image *ima, int except_frame); /* does all images with type MOVIE or SEQUENCE */ void BKE_image_all_free_anim_ibufs(struct Main *bmain, int except_frame); -void BKE_image_memorypack(struct Image *ima); +bool BKE_image_memorypack(struct Image *ima); void BKE_image_packfiles(struct ReportList *reports, struct Image *ima, const char *basepath); void BKE_image_packfiles_from_mem(struct ReportList *reports, struct Image *ima, diff --git a/source/blender/blenkernel/BKE_image_save.h b/source/blender/blenkernel/BKE_image_save.h new file mode 100644 index 00000000000..26c377a2574 --- /dev/null +++ b/source/blender/blenkernel/BKE_image_save.h @@ -0,0 +1,67 @@ +/* + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. + * All rights reserved. + */ +#ifndef __BKE_IMAGE_SAVE_H__ +#define __BKE_IMAGE_SAVE_H__ + +#include "DNA_scene_types.h" + +/** \file + * \ingroup bke + */ + +#ifdef __cplusplus +extern "C" { +#endif + +struct Image; +struct Main; +struct RenderResult; +struct ReportList; +struct Scene; + +typedef struct ImageSaveOptions { + /* Context within which image is saved. */ + struct Main *bmain; + struct Scene *scene; + + /* Format and absolute file path. */ + struct ImageFormatData im_format; + char filepath[1024]; /* 1024 = FILE_MAX */ + + /* Options. */ + bool relative; + bool save_copy; + bool save_as_render; + bool do_newpath; +} ImageSaveOptions; + +void BKE_image_save_options_init(struct ImageSaveOptions *opts, + struct Main *bmain, + struct Scene *scene); +bool BKE_image_save(struct ReportList *reports, + struct Main *bmain, + struct Image *ima, + struct ImageUser *iuser, + struct ImageSaveOptions *opts); + +#ifdef __cplusplus +} +#endif + +#endif /* __BKE_IMAGE_SAVE_H__ */ diff --git a/source/blender/blenkernel/BKE_layer.h b/source/blender/blenkernel/BKE_layer.h index 98fb59814fa..cc6c43c51f6 100644 --- a/source/blender/blenkernel/BKE_layer.h +++ b/source/blender/blenkernel/BKE_layer.h @@ -68,7 +68,6 @@ struct ViewLayer *BKE_view_layer_find_from_collection(const struct Scene *scene, struct Base *BKE_view_layer_base_find(struct ViewLayer *view_layer, struct Object *ob); void BKE_view_layer_base_deselect_all(struct ViewLayer *view_layer); -void BKE_view_layer_base_select(struct Base *selbase); void BKE_view_layer_base_select_and_set_active(struct ViewLayer *view_layer, struct Base *selbase); void BKE_view_layer_copy_data(struct Scene *scene_dst, diff --git a/source/blender/blenkernel/BKE_library.h b/source/blender/blenkernel/BKE_library.h index 82ae832c73e..54b9fdac5b4 100644 --- a/source/blender/blenkernel/BKE_library.h +++ b/source/blender/blenkernel/BKE_library.h @@ -34,13 +34,13 @@ extern "C" { * WARNING: description below is ideal goal, current status of naming does not yet * fully follow it (this is WIP). * - * BKE_id_ should be used for rather high-level operations, that involve Main database and - * relations with other IDs, and can be considered as 'safe' (as in, in themselves, they leave - * affected IDs/Main in a consistent status). + * - BKE_id_ should be used for rather high-level operations, that involve Main database and + * relations with other IDs, and can be considered as 'safe' + * (as in, in themselves, they leave affected IDs/Main in a consistent status). * - * BKE_libblock_ should be used for lower level operations, that perform some parts of BKE_id_ ones, - * but will generally not ensure caller that affected data is in a consistent state - * by their own execution alone. + * - BKE_libblock_ should be used for lower level operations, + * that perform some parts of BKE_id_ ones, but will generally not ensure caller that affected + * data is in a consistent state by their own execution alone. * * Consequently, external code should not typically use BKE_libblock_ functions, * except in some specific cases requiring advanced (and potentially dangerous) handling. @@ -72,44 +72,47 @@ void *BKE_id_new_nomain(const short type, const char *name); */ enum { /* *** Generic options (should be handled by all ID types copying, ID creation, etc.). *** */ - /* Create datablock outside of any main database - similar to 'localize' functions of materials etc. */ + /** Create datablock outside of any main database - + * similar to 'localize' functions of materials etc. */ LIB_ID_CREATE_NO_MAIN = 1 << 0, - /* Do not affect user refcount of datablocks used by new one (which also gets zero usercount then). + /** Do not affect user refcount of datablocks used by new one + * (which also gets zero usercount then). * Implies LIB_ID_CREATE_NO_MAIN. */ LIB_ID_CREATE_NO_USER_REFCOUNT = 1 << 1, - /* Assume given 'newid' already points to allocated memory for whole datablock (ID + data) - USE WITH CAUTION! + /** Assume given 'newid' already points to allocated memory for whole datablock + * (ID + data) - USE WITH CAUTION! * Implies LIB_ID_CREATE_NO_MAIN. */ LIB_ID_CREATE_NO_ALLOCATE = 1 << 2, - /* Do not tag new ID for update in depsgraph. */ + /** Do not tag new ID for update in depsgraph. */ LIB_ID_CREATE_NO_DEG_TAG = 1 << 8, /* *** Specific options to some ID types or usages. *** */ /* *** May be ignored by unrelated ID copying functions. *** */ - /* Object only, needed by make_local code. */ + /** Object only, needed by make_local code. */ LIB_ID_COPY_NO_PROXY_CLEAR = 1 << 16, - /* Do not copy preview data, when supported. */ + /** Do not copy preview data, when supported. */ LIB_ID_COPY_NO_PREVIEW = 1 << 17, - /* Copy runtime data caches. */ + /** Copy runtime data caches. */ LIB_ID_COPY_CACHES = 1 << 18, - /* Don't copy id->adt, used by ID datablock localization routines. */ + /** Don't copy id->adt, used by ID datablock localization routines. */ LIB_ID_COPY_NO_ANIMDATA = 1 << 19, - /* Mesh: Reference CD data layers instead of doing real copy - USE WITH CAUTION! */ + /** Mesh: Reference CD data layers instead of doing real copy - USE WITH CAUTION! */ LIB_ID_COPY_CD_REFERENCE = 1 << 20, /* *** XXX Hackish/not-so-nice specific behaviors needed for some corner cases. *** */ /* *** Ideally we should not have those, but we need them for now... *** */ - /* EXCEPTION! Deep-copy actions used by animdata of copied ID. */ + /** EXCEPTION! Deep-copy actions used by animdata of copied ID. */ LIB_ID_COPY_ACTIONS = 1 << 24, - /* Keep the library pointer when copying datablock outside of bmain. */ + /** Keep the library pointer when copying datablock outside of bmain. */ LIB_ID_COPY_KEEP_LIB = 1 << 25, - /* EXCEPTION! Deep-copy shapekeys used by copied obdata ID. */ + /** EXCEPTION! Deep-copy shapekeys used by copied obdata ID. */ LIB_ID_COPY_SHAPEKEY = 1 << 26, /* *** Helper 'defines' gathering most common flag sets. *** */ - /* Shapekeys are not real ID's, more like local data to geometry IDs... */ + /** Shapekeys are not real ID's, more like local data to geometry IDs... */ LIB_ID_COPY_DEFAULT = LIB_ID_COPY_SHAPEKEY, - /* Generate a local copy, outside of bmain, to work on (used by COW e.g.). */ + /** Generate a local copy, outside of bmain, to work on (used by COW e.g.). */ LIB_ID_COPY_LOCALIZE = LIB_ID_CREATE_NO_MAIN | LIB_ID_CREATE_NO_USER_REFCOUNT | LIB_ID_CREATE_NO_DEG_TAG | LIB_ID_COPY_NO_PREVIEW | LIB_ID_COPY_CACHES, }; diff --git a/source/blender/blenkernel/BKE_library_query.h b/source/blender/blenkernel/BKE_library_query.h index caa36742f76..94e7830aabe 100644 --- a/source/blender/blenkernel/BKE_library_query.h +++ b/source/blender/blenkernel/BKE_library_query.h @@ -38,9 +38,12 @@ enum { */ IDWALK_CB_INDIRECT_USAGE = (1 << 2), - /** That ID is used as mere sub-data by its owner + /** + * That ID is used as mere sub-data by its owner * (only case currently: those f***ing nodetrees in materials etc.). - * This means callback shall not *do* anything, only use this as informative data if it needs it. */ + * This means callback shall not *do* anything, + * only use this as informative data if it needs it. + */ IDWALK_CB_PRIVATE = (1 << 3), /** That ID is not really used by its owner, it's just an internal hint/helper. diff --git a/source/blender/blenkernel/BKE_library_remap.h b/source/blender/blenkernel/BKE_library_remap.h index da104c4c205..41ac8c8c8e6 100644 --- a/source/blender/blenkernel/BKE_library_remap.h +++ b/source/blender/blenkernel/BKE_library_remap.h @@ -29,29 +29,44 @@ extern "C" { /* Also IDRemap->flag. */ enum { - /* Do not remap indirect usages of IDs (that is, when user is some linked data). */ + /** Do not remap indirect usages of IDs (that is, when user is some linked data). */ ID_REMAP_SKIP_INDIRECT_USAGE = 1 << 0, - /* This flag should always be set, *except for 'unlink' scenarios* (only relevant when new_id == NULL). - * Basically, when unset, NEVER_NULL ID usages will keep pointing to old_id, but (if needed) old_id user count - * will still be decremented. This is mandatory for 'delete ID' case, but in all other situation this would lead - * to invalid user counts! */ + /** + * This flag should always be set, *except for 'unlink' scenarios* + * (only relevant when new_id == NULL). + * Basically, when unset, NEVER_NULL ID usages will keep pointing to old_id, but (if needed) + * old_id user count will still be decremented. + * This is mandatory for 'delete ID' case, + * but in all other situation this would lead to invalid user counts! + */ ID_REMAP_SKIP_NEVER_NULL_USAGE = 1 << 1, - /* This tells the callback func to flag with LIB_DOIT all IDs using target one with a 'never NULL' pointer - * (like e.g. Object->data). */ + /** + * This tells the callback func to flag with #LIB_DOIT all IDs + * using target one with a 'never NULL' pointer (like e.g. #Object.data). + */ ID_REMAP_FLAG_NEVER_NULL_USAGE = 1 << 2, - /* This tells the callback func to force setting IDs using target one with a 'never NULL' pointer to NULL. - * WARNING! Use with extreme care, this will leave database in broken state and can cause crashes very easily! */ + /** + * This tells the callback func to force setting IDs + * using target one with a 'never NULL' pointer to NULL. + * \warning Use with extreme care, this will leave database in broken state + * and can cause crashes very easily! + */ ID_REMAP_FORCE_NEVER_NULL_USAGE = 1 << 3, - /* Do not consider proxy/_group pointers of local objects as indirect usages... - * Our oh-so-beloved proxies again... Do not consider data used by local proxy object as indirect usage. - * This is needed e.g. in reload scenario, since we have to ensure remapping of Armature data of local proxy - * is also performed. Usual nightmare... */ + /** + * Do not consider proxy/_group pointers of local objects as indirect usages... + * Our oh-so-beloved proxies again... + * Do not consider data used by local proxy object as indirect usage. + * This is needed e.g. in reload scenario, + * since we have to ensure remapping of Armature data of local proxy + * is also performed. Usual nightmare... + */ ID_REMAP_NO_INDIRECT_PROXY_DATA_USAGE = 1 << 4, - /* Do not remap static override pointers. */ + /** Do not remap static override pointers. */ ID_REMAP_SKIP_STATIC_OVERRIDE = 1 << 5, }; -/* Note: Requiring new_id to be non-null, this *may* not be the case ultimately, but makes things simpler for now. */ +/* Note: Requiring new_id to be non-null, this *may* not be the case ultimately, + * but makes things simpler for now. */ void BKE_libblock_remap_locked(struct Main *bmain, void *old_idv, void *new_idv, diff --git a/source/blender/blenkernel/BKE_main.h b/source/blender/blenkernel/BKE_main.h index 84ff46aa5d0..1c987d5eb8e 100644 --- a/source/blender/blenkernel/BKE_main.h +++ b/source/blender/blenkernel/BKE_main.h @@ -57,7 +57,8 @@ typedef struct BlendThumbnail { /* Structs caching relations between data-blocks in a given Main. */ typedef struct MainIDRelationsEntry { struct MainIDRelationsEntry *next; - /* WARNING! for user_to_used, that pointer is really an ID** one, but for used_to_user, it’s only an ID* one! */ + /* WARNING! for user_to_used, + * that pointer is really an ID** one, but for used_to_user, it’s only an ID* one! */ struct ID **id_pointer; int usage_flag; /* Using IDWALK_ enums, in BKE_library_query.h */ } MainIDRelationsEntry; @@ -121,9 +122,11 @@ typedef struct Main { ListBase cachefiles; ListBase workspaces; - /* Must be generated, used and freed by same code - never assume this is valid data unless you know - * when, who and how it was created. - * Used by code doing a lot of remapping etc. at once to speed things up. */ + /** + * Must be generated, used and freed by same code - never assume this is valid data unless you + * know when, who and how it was created. + * Used by code doing a lot of remapping etc. at once to speed things up. + */ struct MainIDRelations *relations; struct MainLock *lock; @@ -165,14 +168,15 @@ struct GSet *BKE_main_gset_create(struct Main *bmain, struct GSet *gset); } \ ((void)0) -/* DO NOT use break statement with that macro, use FOREACH_MAIN_LISTBASE and FOREACH_MAIN_LISTBASE_ID instead +/** + * DO NOT use break statement with that macro, + * use #FOREACH_MAIN_LISTBASE and #FOREACH_MAIN_LISTBASE_ID instead * if you need that kind of control flow. */ #define FOREACH_MAIN_ID_BEGIN(_bmain, _id) \ { \ ListBase *_lb; \ - FOREACH_MAIN_LISTBASE_BEGIN(_bmain, _lb) \ - { \ - FOREACH_MAIN_LISTBASE_ID_BEGIN(_lb, _id) + FOREACH_MAIN_LISTBASE_BEGIN (_bmain, _lb) { \ + FOREACH_MAIN_LISTBASE_ID_BEGIN (_lb, _id) #define FOREACH_MAIN_ID_END \ FOREACH_MAIN_LISTBASE_ID_END; \ diff --git a/source/blender/blenkernel/BKE_mesh.h b/source/blender/blenkernel/BKE_mesh.h index e89e1b05029..ecee00b1b3f 100644 --- a/source/blender/blenkernel/BKE_mesh.h +++ b/source/blender/blenkernel/BKE_mesh.h @@ -123,10 +123,12 @@ struct Mesh *BKE_mesh_new_nomain_from_template(const struct Mesh *me_src, int loops_len, int polys_len); -/* Performs copy for use during evaluation, optional referencing original arrays to reduce memory. */ +/* Performs copy for use during evaluation, + * optional referencing original arrays to reduce memory. */ struct Mesh *BKE_mesh_copy_for_eval(struct Mesh *source, bool reference); -/* These functions construct a new Mesh, contrary to BKE_mesh_from_nurbs which modifies ob itself. */ +/* These functions construct a new Mesh, + * contrary to BKE_mesh_from_nurbs which modifies ob itself. */ struct Mesh *BKE_mesh_new_nomain_from_curve(struct Object *ob); struct Mesh *BKE_mesh_new_nomain_from_curve_displist(struct Object *ob, struct ListBase *dispbase); @@ -214,8 +216,8 @@ struct Mesh *BKE_mesh_new_from_object(struct Depsgraph *depsgraph, const bool calc_undeformed); struct Mesh *BKE_mesh_create_derived_for_modifier(struct Depsgraph *depsgraph, struct Scene *scene, - struct Object *ob, - struct ModifierData *md, + struct Object *ob_eval, + struct ModifierData *md_eval, int build_shapekey_layers); /* Copies a nomain-Mesh into an existing Mesh. */ @@ -325,22 +327,25 @@ void BKE_edges_sharp_from_angle_set(const struct MVert *mverts, * References a contiguous loop-fan with normal offset vars. */ typedef struct MLoopNorSpace { - float vec_lnor[3]; /* Automatically computed loop normal. */ - float vec_ref[3]; /* Reference vector, orthogonal to vec_lnor. */ - float vec_ortho[3]; /* Third vector, orthogonal to vec_lnor and vec_ref. */ - float - ref_alpha; /* Reference angle, around vec_ortho, in ]0, pi] range (0.0 marks that space as invalid). */ - float - ref_beta; /* Reference angle, around vec_lnor, in ]0, 2pi] range (0.0 marks that space as invalid). */ - /* All loops using this lnor space (i.e. smooth fan of loops), + /** Automatically computed loop normal. */ + float vec_lnor[3]; + /** Reference vector, orthogonal to vec_lnor. */ + float vec_ref[3]; + /** Third vector, orthogonal to vec_lnor and vec_ref. */ + float vec_ortho[3]; + /** Reference angle, around vec_ortho, in ]0, pi] range (0.0 marks that space as invalid). */ + float ref_alpha; + /** Reference angle, around vec_lnor, in ]0, 2pi] range (0.0 marks that space as invalid). */ + float ref_beta; + /** All loops using this lnor space (i.e. smooth fan of loops), * as (depending on owning MLoopNorSpaceArrary.data_type): * - Indices (uint_in_ptr), or * - BMLoop pointers. */ struct LinkNode *loops; char flags; - void * - user_data; /* To be used for extended processing related to loop normal spaces (aka smooth fans). */ + /** To be used for extended processing related to loop normal spaces (aka smooth fans). */ + void *user_data; } MLoopNorSpace; /** * MLoopNorSpace.flags @@ -668,6 +673,7 @@ enum { BKE_MESH_BATCH_DIRTY_ALL = 0, BKE_MESH_BATCH_DIRTY_MAYBE_ALL, BKE_MESH_BATCH_DIRTY_SELECT, + BKE_MESH_BATCH_DIRTY_SELECT_PAINT, BKE_MESH_BATCH_DIRTY_SHADING, BKE_MESH_BATCH_DIRTY_SCULPT_COORDS, BKE_MESH_BATCH_DIRTY_UVEDIT_ALL, diff --git a/source/blender/blenkernel/BKE_mesh_remap.h b/source/blender/blenkernel/BKE_mesh_remap.h index 54f263a8bfb..36cc5bedb79 100644 --- a/source/blender/blenkernel/BKE_mesh_remap.h +++ b/source/blender/blenkernel/BKE_mesh_remap.h @@ -54,10 +54,12 @@ void BKE_mesh_remap_item_define_invalid(MeshPairRemap *map, const int index); /* TODO: * Add other 'from/to' mapping sources, like e.g. using an UVMap, etc. - * http://blenderartists.org/forum/showthread.php?346458-Move-Vertices-to-the-location-of-the-Reference-Mesh-based-on-the-UV-Position + * https://blenderartists.org/t/619105 + * * We could also use similar topology mappings inside a same mesh * (cf. Campbell's 'select face islands from similar topology' wip work). - * Also, users will have to check, whether we can get rid of some modes here, not sure all will be useful! + * Also, users will have to check, whether we can get rid of some modes here, + * not sure all will be useful! */ enum { MREMAP_USE_VERT = 1 << 4, @@ -104,13 +106,15 @@ enum { /* Nearest edge of nearest poly (using mid-point). */ MREMAP_MODE_EDGE_POLY_NEAREST = MREMAP_MODE_EDGE | MREMAP_USE_POLY | MREMAP_USE_NEAREST, - /* Cast a set of rays from along dest edge, interpolating its vertices' normals, and use hit source edges. */ + /* Cast a set of rays from along dest edge, + * interpolating its vertices' normals, and use hit source edges. */ MREMAP_MODE_EDGE_EDGEINTERP_VNORPROJ = MREMAP_MODE_EDGE | MREMAP_USE_VERT | MREMAP_USE_NORPROJ | MREMAP_USE_INTERP, /* ***** Target's loops ***** */ - /* Note: when islands are given to loop mapping func, all loops from the same destination face will always be mapped - * to loops of source faces within a same island, regardless of mapping mode. */ + /* Note: when islands are given to loop mapping func, + * all loops from the same destination face will always be mapped + * to loops of source faces within a same island, regardless of mapping mode. */ MREMAP_MODE_LOOP = 1 << 26, /* Best normal-matching loop from nearest vert. */ @@ -138,7 +142,8 @@ enum { /* Source poly from best normal-matching dest poly. */ MREMAP_MODE_POLY_NOR = MREMAP_MODE_POLY | MREMAP_USE_POLY | MREMAP_USE_NORMAL, - /* Project dest poly onto source mesh using its normal, and use interpolation of all intersecting source polys. */ + /* Project dest poly onto source mesh using its normal, + * and use interpolation of all intersecting source polys. */ MREMAP_MODE_POLY_POLYINTERP_PNORPROJ = MREMAP_MODE_POLY | MREMAP_USE_POLY | MREMAP_USE_NORPROJ | MREMAP_USE_INTERP, diff --git a/source/blender/blenkernel/BKE_modifier.h b/source/blender/blenkernel/BKE_modifier.h index 68ef413b198..a34f570ad1f 100644 --- a/source/blender/blenkernel/BKE_modifier.h +++ b/source/blender/blenkernel/BKE_modifier.h @@ -83,8 +83,8 @@ typedef enum { */ eModifierTypeFlag_RequiresOriginalData = (1 << 5), - /* For modifiers that support pointcache, so we can check to see if it has files we need to deal with - */ + /* For modifiers that support pointcache, + * so we can check to see if it has files we need to deal with. */ eModifierTypeFlag_UsesPointCache = (1 << 6), /* For physics modifiers, max one per type */ @@ -110,13 +110,16 @@ typedef void (*TexWalkFunc)(void *userData, const char *propname); typedef enum ModifierApplyFlag { - MOD_APPLY_RENDER = 1 << 0, /* Render time. */ - MOD_APPLY_USECACHE = 1 << 1, /* Result of evaluation will be cached, so modifier might - * want to cache data for quick updates (used by subsurf) */ - MOD_APPLY_ORCO = 1 << 2, /* Modifier evaluated for undeformed texture coordinates */ - MOD_APPLY_IGNORE_SIMPLIFY = 1 << 3, /* Ignore scene simplification flag and use subdivisions - * level set in multires modifier. - */ + /** 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) */ + MOD_APPLY_USECACHE = 1 << 1, + /** Modifier evaluated for undeformed texture coordinates */ + MOD_APPLY_ORCO = 1 << 2, + /** Ignore scene simplification flag and use subdivisions + * level set in multires modifier. */ + MOD_APPLY_IGNORE_SIMPLIFY = 1 << 3, } ModifierApplyFlag; typedef struct ModifierUpdateDepsgraphContext { diff --git a/source/blender/blenkernel/BKE_node.h b/source/blender/blenkernel/BKE_node.h index 48b58562dd7..b760be29dae 100644 --- a/source/blender/blenkernel/BKE_node.h +++ b/source/blender/blenkernel/BKE_node.h @@ -218,7 +218,7 @@ typedef struct bNodeType { /// Called when the node is updated in the editor. void (*updatefunc)(struct bNodeTree *ntree, struct bNode *node); /// Check and update if internal ID data has changed. - void (*verifyfunc)(struct bNodeTree *ntree, struct bNode *node, struct ID *id); + void (*group_update_func)(struct bNodeTree *ntree, struct bNode *node); /// Initialize a new node instance of this type after creation. void (*initfunc)(struct bNodeTree *ntree, struct bNode *node); @@ -395,15 +395,14 @@ struct bNode *ntreeFindType(const struct bNodeTree *ntree, int type); bool ntreeHasType(const struct bNodeTree *ntree, int type); bool ntreeHasTree(const struct bNodeTree *ntree, const struct bNodeTree *lookup); void ntreeUpdateTree(struct Main *main, struct bNodeTree *ntree); -/* XXX Currently each tree update call does call to ntreeVerifyNodes too. - * Some day this should be replaced by a decent depsgraph automatism! - */ -void ntreeVerifyNodes(struct Main *main, struct ID *id); +void ntreeUpdateAllNew(struct Main *main); +void ntreeUpdateAllUsers(struct Main *main, struct ID *id); void ntreeGetDependencyList(struct bNodeTree *ntree, struct bNode ***deplist, int *totnodes); -/* XXX old trees handle output flags automatically based on special output node types and last active selection. - * new tree types have a per-output socket flag to indicate the final output to use explicitly. +/* XXX old trees handle output flags automatically based on special output + * node types and last active selection. + * New tree types have a per-output socket flag to indicate the final output to use explicitly. */ void ntreeSetOutput(struct bNodeTree *ntree); @@ -491,7 +490,8 @@ const char *nodeStaticSocketInterfaceType(int type, int subtype); #define NODE_SOCKET_TYPES_END \ } \ BLI_ghashIterator_free(__node_socket_type_iter__); \ - } + } \ + ((void)0) struct bNodeSocket *nodeFindSocket(struct bNode *node, int in_out, const char *identifier); struct bNodeSocket *nodeAddSocket(struct bNodeTree *ntree, @@ -735,10 +735,10 @@ void node_type_label( struct bNodeType *ntype, void (*labelfunc)(struct bNodeTree *ntree, struct bNode *, char *label, int maxlen)); void node_type_update(struct bNodeType *ntype, - void (*updatefunc)(struct bNodeTree *ntree, struct bNode *node), - void (*verifyfunc)(struct bNodeTree *ntree, - struct bNode *node, - struct ID *id)); + void (*updatefunc)(struct bNodeTree *ntree, struct bNode *node)); +void node_type_group_update(struct bNodeType *ntype, + void (*group_update_func)(struct bNodeTree *ntree, + struct bNode *node)); void node_type_exec(struct bNodeType *ntype, NodeInitExecFunction initexecfunc, @@ -776,16 +776,20 @@ void BKE_node_tree_unlink_id(ID *id, struct bNodeTree *ntree); /* -------------------------------------------------------------------- */ /** \name Node Tree Iterator * - * Utility macro for visiting every node tree in the library data, including local bNodeTree blocks in other IDs. - * This avoids the need for callback functions and allows executing code in a single inner code block. + * Utility macro for visiting every node tree in the library data, + * including local bNodeTree blocks in other IDs. + * This avoids the need for callback functions and allows executing code + * in a single inner code block. * * Variables: * - * nodetree: The actual bNodeTree data block. - * Check nodetree->idname or nodetree->typeinfo to use only specific types. + * - nodetree: + * The actual bNodeTree data block. + * Check nodetree->idname or nodetree->typeinfo to use only specific types. * - * id: The owner of the bNodeTree data block. - * Same as nodetree if it's a linkable node tree from the library. + * - id: + * The owner of the bNodeTree data block. + * Same as nodetree if it's a linkable node tree from the library. * * Examples: * @@ -853,7 +857,8 @@ void BKE_nodetree_remove_layer_n(struct bNodeTree *ntree, /* note: types are needed to restore callbacks, don't change values */ /* range 1 - 100 is reserved for common nodes */ -/* using toolbox, we add node groups by assuming the values below don't exceed NODE_GROUP_MENU for now */ +/* using toolbox, we add node groups by assuming the values below + * don't exceed NODE_GROUP_MENU for now. */ //#define SH_NODE_OUTPUT 1 @@ -1144,8 +1149,6 @@ void ntreeCompositExecTree(struct Scene *scene, const struct ColorManagedDisplaySettings *display_settings, const char *view_name); void ntreeCompositTagRender(struct Scene *sce); -int ntreeCompositTagAnimated(struct bNodeTree *ntree); -void ntreeCompositTagGenerators(struct bNodeTree *ntree); void ntreeCompositUpdateRLayers(struct bNodeTree *ntree); void ntreeCompositRegisterPass(struct bNodeTree *ntree, struct Scene *scene, @@ -1220,7 +1223,6 @@ struct TexResult; #define TEX_NODE_PROC_MAX 600 /* API */ -int ntreeTexTagAnimated(struct bNodeTree *ntree); void ntreeTexCheckCyclics(struct bNodeTree *ntree); struct bNodeTreeExec *ntreeTexBeginExecTree(struct bNodeTree *ntree); diff --git a/source/blender/blenkernel/BKE_object.h b/source/blender/blenkernel/BKE_object.h index ab7ca44368c..49b35bfccc1 100644 --- a/source/blender/blenkernel/BKE_object.h +++ b/source/blender/blenkernel/BKE_object.h @@ -153,7 +153,7 @@ struct Object *BKE_object_duplicate(struct Main *bmain, void BKE_object_obdata_size_init(struct Object *ob, const float scale); void BKE_object_scale_to_mat3(struct Object *ob, float mat[3][3]); -void BKE_object_rot_to_mat3(struct Object *ob, float mat[3][3], bool use_drot); +void BKE_object_rot_to_mat3(const struct Object *ob, float mat[3][3], bool use_drot); void BKE_object_mat3_to_rot(struct Object *ob, float mat[3][3], bool use_compat); void BKE_object_to_mat3(struct Object *ob, float mat[3][3]); void BKE_object_to_mat4(struct Object *ob, float mat[4][4]); diff --git a/source/blender/blenkernel/BKE_paint.h b/source/blender/blenkernel/BKE_paint.h index b0fbf07d467..56c92b731b7 100644 --- a/source/blender/blenkernel/BKE_paint.h +++ b/source/blender/blenkernel/BKE_paint.h @@ -145,6 +145,7 @@ void BKE_paint_runtime_init(const struct ToolSettings *ts, struct Paint *paint); void BKE_paint_cavity_curve_preset(struct Paint *p, int preset); eObjectMode BKE_paint_object_mode_from_paintmode(ePaintMode mode); +bool BKE_paint_ensure_from_paintmode(struct Scene *sce, ePaintMode mode); struct Paint *BKE_paint_get_active_from_paintmode(struct Scene *sce, ePaintMode mode); const struct EnumPropertyItem *BKE_paint_get_tool_enum_from_paintmode(ePaintMode mode); const char *BKE_paint_get_tool_prop_id_from_paintmode(ePaintMode mode); diff --git a/source/blender/blenkernel/BKE_particle.h b/source/blender/blenkernel/BKE_particle.h index feb40d86151..f9bd722f8ba 100644 --- a/source/blender/blenkernel/BKE_particle.h +++ b/source/blender/blenkernel/BKE_particle.h @@ -201,21 +201,24 @@ typedef struct ParticleCollisionElement { short inv_nor, inside; } ParticleCollisionElement; -/* container for moving data between deflet_particle and particle_intersect_face */ +/** Container for moving data between deflet_particle and particle_intersect_face. */ typedef struct ParticleCollision { struct Object *current; struct Object *hit; struct Object *skip[PARTICLE_COLLISION_MAX_COLLISIONS + 1]; struct Object *emitter; - struct CollisionModifierData *md; // collision modifier for current object; + /** Collision modifier for current object. */ + struct CollisionModifierData *md; - float f; // time factor of previous collision, needed for substracting face velocity + /** Time factor of previous collision, needed for substracting face velocity. */ + float f; float fac1, fac2; float cfra, old_cfra; - float original_ray_length; //original length of co2-co1, needed for collision time evaluation + /** Original length of co2-co1, needed for collision time evaluation. */ + float original_ray_length; int skip_count; diff --git a/source/blender/blenkernel/BKE_pbvh.h b/source/blender/blenkernel/BKE_pbvh.h index 049fc585b56..f59288f54bd 100644 --- a/source/blender/blenkernel/BKE_pbvh.h +++ b/source/blender/blenkernel/BKE_pbvh.h @@ -67,6 +67,7 @@ void BKE_pbvh_build_mesh(PBVH *bvh, struct MVert *verts, int totvert, struct CustomData *vdata, + struct CustomData *ldata, const struct MLoopTri *looptri, int looptri_num); void BKE_pbvh_build_grids(PBVH *bvh, @@ -153,6 +154,7 @@ void BKE_pbvh_draw_cb(PBVH *bvh, bool fast, bool wires, bool only_mask, + bool show_vcol, void (*draw_fn)(void *user_data, struct GPUBatch *batch), void *user_data); @@ -398,8 +400,8 @@ void BKE_pbvh_node_get_bm_orco_data(PBVHNode *node, bool BKE_pbvh_node_vert_update_check_any(PBVH *bvh, PBVHNode *node); -//void BKE_pbvh_node_BB_reset(PBVHNode *node); -//void BKE_pbvh_node_BB_expand(PBVHNode *node, float co[3]); +// void BKE_pbvh_node_BB_reset(PBVHNode *node); +// void BKE_pbvh_node_BB_expand(PBVHNode *node, float co[3]); bool pbvh_has_mask(PBVH *bvh); void pbvh_show_diffuse_color_set(PBVH *bvh, bool show_diffuse_color); diff --git a/source/blender/blenkernel/BKE_pointcache.h b/source/blender/blenkernel/BKE_pointcache.h index 8a8ae3e2566..6ce60081f5b 100644 --- a/source/blender/blenkernel/BKE_pointcache.h +++ b/source/blender/blenkernel/BKE_pointcache.h @@ -167,7 +167,8 @@ typedef struct PTCacheID { void (*interpolate_extra_data)( void *calldata, struct PTCacheMem *pm, float cfra, float cfra1, float cfra2); - /* total number of simulated points (the cfra parameter is just for using same function pointer with totwrite) */ + /* Total number of simulated points + * (the cfra parameter is just for using same function pointer with totwrite). */ int (*totpoint)(void *calldata, int cfra); /* report error if number of points does not match */ void (*error)(void *calldata, const char *message); @@ -265,8 +266,8 @@ typedef struct PTCacheEdit { struct ParticleSystemModifierData *psmd; struct ParticleSystemModifierData *psmd_eval; struct KDTree_3d *emitter_field; - float * - emitter_cosnos; /* localspace face centers and normals (average of its verts), from the derived mesh */ + /* Localspace face centers and normals (average of its verts), from the derived mesh. */ + float *emitter_cosnos; int *mirror_cache; struct ParticleCacheKey **pathcache; /* path cache (runtime) */ diff --git a/source/blender/blenkernel/BKE_rigidbody.h b/source/blender/blenkernel/BKE_rigidbody.h index 72bc95028da..c940e646d95 100644 --- a/source/blender/blenkernel/BKE_rigidbody.h +++ b/source/blender/blenkernel/BKE_rigidbody.h @@ -106,7 +106,8 @@ void BKE_rigidbody_remove_constraint(struct Scene *scene, struct Object *ob); (rbo->flag & RBO_FLAG_DISABLED))) ? \ (0.0f) : \ (rbo->mass)) -/* get collision margin for Rigid Body Object, triangle mesh and cone shapes cannot embed margin, convex hull always uses custom margin */ +/* Get collision margin for Rigid Body Object, triangle mesh and cone shapes cannot embed margin, + * convex hull always uses custom margin. */ #define RBO_GET_MARGIN(rbo) \ ((rbo->flag & RBO_FLAG_USE_MARGIN || rbo->shape == RB_SHAPE_CONVEXH || \ rbo->shape == RB_SHAPE_TRIMESH || rbo->shape == RB_SHAPE_CONE) ? \ diff --git a/source/blender/blenkernel/BKE_scene.h b/source/blender/blenkernel/BKE_scene.h index 6cd71604561..75ff5eace3c 100644 --- a/source/blender/blenkernel/BKE_scene.h +++ b/source/blender/blenkernel/BKE_scene.h @@ -102,7 +102,6 @@ int BKE_scene_base_iter_next(struct Depsgraph *depsgraph, void BKE_scene_base_flag_to_objects(struct ViewLayer *view_layer); void BKE_scene_object_base_flag_sync_from_base(struct Base *base); -void BKE_scene_object_base_flag_sync_from_object(struct Base *base); void BKE_scene_set_background(struct Main *bmain, struct Scene *sce); struct Scene *BKE_scene_set_name(struct Main *bmain, const char *name); diff --git a/source/blender/blenkernel/BKE_screen.h b/source/blender/blenkernel/BKE_screen.h index 6a9711dd316..93c9c41e482 100644 --- a/source/blender/blenkernel/BKE_screen.h +++ b/source/blender/blenkernel/BKE_screen.h @@ -182,7 +182,8 @@ typedef struct ARegionType { int prefsizex, prefsizey; /* default keymaps to add */ int keymapflag; - /* return without drawing. lock is set by region definition, and copied to do_lock by render. can become flag */ + /* return without drawing. + * lock is set by region definition, and copied to do_lock by render. can become flag. */ short do_lock, lock; /* call cursor function on each move event */ short event_cursor; @@ -337,7 +338,8 @@ struct ARegion *BKE_area_region_copy(struct SpaceType *st, struct ARegion *ar); void BKE_area_region_free(struct SpaceType *st, struct ARegion *ar); void BKE_area_region_panels_free(struct ListBase *panels); void BKE_screen_area_free(struct ScrArea *sa); -/* Gizmo-maps of a region need to be freed with the region. Uses callback to avoid low-level call. */ +/* Gizmo-maps of a region need to be freed with the region. + * Uses callback to avoid low-level call. */ void BKE_region_callback_free_gizmomap_set(void (*callback)(struct wmGizmoMap *)); void BKE_region_callback_refresh_tag_gizmomap_set(void (*callback)(struct wmGizmoMap *)); diff --git a/source/blender/blenkernel/BKE_sequencer.h b/source/blender/blenkernel/BKE_sequencer.h index 820f28fb363..017c15ebe41 100644 --- a/source/blender/blenkernel/BKE_sequencer.h +++ b/source/blender/blenkernel/BKE_sequencer.h @@ -100,7 +100,6 @@ typedef struct SeqRenderData { /* special case for OpenGL render */ struct GPUOffScreen *gpu_offscreen; - struct GPUFX *gpu_fx; int gpu_samples; bool gpu_full_samples; } SeqRenderData; @@ -302,46 +301,33 @@ void BKE_sequencer_proxy_set(struct Sequence *seq, bool value); * Sequencer memory cache management functions * ********************************************************************** */ -typedef enum { - SEQ_STRIPELEM_IBUF, - SEQ_STRIPELEM_IBUF_COMP, - SEQ_STRIPELEM_IBUF_STARTSTILL, - SEQ_STRIPELEM_IBUF_ENDSTILL, -} eSeqStripElemIBuf; +#define SEQ_CACHE_COST_MAX 10.0f -void BKE_sequencer_cache_destruct(void); -void BKE_sequencer_cache_cleanup(void); - -/* returned ImBuf is properly refed and has to be freed */ struct ImBuf *BKE_sequencer_cache_get(const SeqRenderData *context, struct Sequence *seq, float cfra, - eSeqStripElemIBuf type); - -/* passed ImBuf is properly refed, so ownership is *not* - * transferred to the cache. - * you can pass the same ImBuf multiple times to the cache without problems. - */ - + int type); void BKE_sequencer_cache_put(const SeqRenderData *context, struct Sequence *seq, float cfra, - eSeqStripElemIBuf type, - struct ImBuf *nval); - -void BKE_sequencer_cache_cleanup_sequence(struct Sequence *seq); - -struct ImBuf *BKE_sequencer_preprocessed_cache_get(const SeqRenderData *context, - struct Sequence *seq, - float cfra, - eSeqStripElemIBuf type); -void BKE_sequencer_preprocessed_cache_put(const SeqRenderData *context, - struct Sequence *seq, - float cfra, - eSeqStripElemIBuf type, - struct ImBuf *ibuf); -void BKE_sequencer_preprocessed_cache_cleanup(void); -void BKE_sequencer_preprocessed_cache_cleanup_sequence(struct Sequence *seq); + int type, + struct ImBuf *nval, + float cost); +bool BKE_sequencer_cache_put_if_possible(const SeqRenderData *context, + struct Sequence *seq, + float cfra, + int type, + struct ImBuf *nval, + float cost); +void BKE_sequencer_cache_free_temp_cache(struct Scene *scene, short id, int cfra); +void BKE_sequencer_cache_destruct(struct Scene *scene); +void BKE_sequencer_cache_cleanup_all(struct Main *bmain); +void BKE_sequencer_cache_cleanup(struct Scene *scene); +void BKE_sequencer_cache_cleanup_sequence(struct Scene *scene, struct Sequence *seq); +void BKE_sequencer_cache_iterate( + struct Scene *scene, + void *userdata, + bool callback(void *userdata, struct Sequence *seq, int cfra, int cache_type, float cost)); /* ********************************************************************** * seqeffects.c @@ -500,19 +486,9 @@ struct Sequence *BKE_sequencer_add_movie_strip(struct bContext *C, ListBase *seqbasep, struct SeqLoadInfo *seq_load); -/* view3d draw callback, run when not in background view */ -/* NOTE: Keep in sync with V3D_OFSDRAW_* flags. */ -enum { - SEQ_OFSDRAW_NONE = (0), - SEQ_OFSDRAW_USE_BACKGROUND = (1 << 0), - SEQ_OFSDRAW_USE_FULL_SAMPLE = (1 << 1), - SEQ_OFSDRAW_USE_GPENCIL = (1 << 2), - SEQ_OFSDRAW_USE_SOLID_TEX = (1 << 2), - SEQ_OFSDRAW_USE_CAMERA_DOF = (1 << 3), -}; - typedef struct ImBuf *(*SequencerDrawView)(struct Depsgraph *depsgraph, struct Scene *scene, + struct View3DShading *shading_override, int drawtype, struct Object *camera, int width, @@ -590,6 +566,6 @@ void BKE_sequencer_color_balance_apply(struct StripColorBalance *cb, bool make_float, struct ImBuf *mask_input); -void BKE_sequencer_all_free_anim_ibufs(struct Main *bmain, int cfra); +void BKE_sequencer_all_free_anim_ibufs(struct Scene *scene, int cfra); #endif /* __BKE_SEQUENCER_H__ */ diff --git a/source/blender/blenkernel/BKE_shrinkwrap.h b/source/blender/blenkernel/BKE_shrinkwrap.h index d97525d4094..8993654254e 100644 --- a/source/blender/blenkernel/BKE_shrinkwrap.h +++ b/source/blender/blenkernel/BKE_shrinkwrap.h @@ -112,7 +112,8 @@ void shrinkwrapModifier_deform(struct ShrinkwrapModifierData *smd, int numVerts); /* - * This function casts a ray in the given BVHTree.. but it takes into consideration the space_transform, that is: + * This function casts a ray in the given BVHTree. + * but it takes into consideration the space_transform, that is: * * if transf was configured with "SPACE_TRANSFORM_SETUP( &transf, ob1, ob2 )" * then the input (vert, dir, BVHTreeRayHit) must be defined in ob1 coordinates space @@ -129,7 +130,8 @@ bool BKE_shrinkwrap_project_normal(char options, struct ShrinkwrapTreeData *tree, BVHTreeRayHit *hit); -/* Maps the point to the nearest surface, either by simple nearest, or by target normal projection. */ +/* Maps the point to the nearest surface, either by simple nearest, + * or by target normal projection. */ void BKE_shrinkwrap_find_nearest_surface(struct ShrinkwrapTreeData *tree, struct BVHTreeNearest *nearest, float co[3], diff --git a/source/blender/blenkernel/BKE_softbody.h b/source/blender/blenkernel/BKE_softbody.h index 049950f2a03..e0a8b7f9d5d 100644 --- a/source/blender/blenkernel/BKE_softbody.h +++ b/source/blender/blenkernel/BKE_softbody.h @@ -37,8 +37,8 @@ typedef struct BodyPoint { int *springs; float choke, choke2, frozen; float colball; - short loc_flag; //reserved by locale module specific states - //char octantflag; + short loc_flag; // reserved by locale module specific states + // char octantflag; float mass; float springweight; } BodyPoint; diff --git a/source/blender/blenkernel/BKE_sound.h b/source/blender/blenkernel/BKE_sound.h index 9d917f0e420..91e23d35f0e 100644 --- a/source/blender/blenkernel/BKE_sound.h +++ b/source/blender/blenkernel/BKE_sound.h @@ -61,7 +61,10 @@ struct bSound *BKE_sound_new_file_exists(struct Main *bmain, const char *filepat #if 0 struct bSound *BKE_sound_new_buffer(struct Main *bmain, struct bSound *source); -struct bSound *BKE_sound_new_limiter(struct Main *bmain, struct bSound *source, float start, float end); +struct bSound *BKE_sound_new_limiter(struct Main *bmain, + struct bSound *source, + float start, + float end); #endif void BKE_sound_cache(struct bSound *sound); diff --git a/source/blender/blenkernel/BKE_undo_system.h b/source/blender/blenkernel/BKE_undo_system.h index 6852c3ee970..d4cb9331605 100644 --- a/source/blender/blenkernel/BKE_undo_system.h +++ b/source/blender/blenkernel/BKE_undo_system.h @@ -92,7 +92,8 @@ typedef struct UndoType { /** * When NULL, we don't consider this undo type for context checks. * Operators must explicitly set the undo type and handle adding the undo step. - * This is needed when tools operate on data which isn't the primary mode (eg, paint-curve in sculpt mode). + * This is needed when tools operate on data which isn't the primary mode + * (eg, paint-curve in sculpt mode). */ bool (*poll)(struct bContext *C); @@ -187,7 +188,9 @@ void BKE_undosys_type_free_all(void); /* ID Accessor */ #if 0 /* functionality is only used internally for now. */ -void BKE_undosys_foreach_ID_ref(UndoStack *ustack, UndoTypeForEachIDRefFn foreach_ID_ref_fn, void *user_data); +void BKE_undosys_foreach_ID_ref(UndoStack *ustack, + UndoTypeForEachIDRefFn foreach_ID_ref_fn, + void *user_data); #endif /* Use when the undo step stores many arbitrary pointers. */ diff --git a/source/blender/blenkernel/BKE_unit.h b/source/blender/blenkernel/BKE_unit.h index 17973265390..4f9ff61c9a6 100644 --- a/source/blender/blenkernel/BKE_unit.h +++ b/source/blender/blenkernel/BKE_unit.h @@ -63,7 +63,7 @@ double bUnit_BaseScalar(int system, int type); bool bUnit_IsValid(int system, int type); /* loop over scales, could add names later */ -//double bUnit_Iter(void **unit, char **name, int system, int type); +// double bUnit_Iter(void **unit, char **name, int system, int type); void bUnit_GetSystem(int system, int type, void const **r_usys_pt, int *r_len); int bUnit_GetBaseUnit(const void *usys_pt); diff --git a/source/blender/blenkernel/CMakeLists.txt b/source/blender/blenkernel/CMakeLists.txt index 019ab929f16..e564e91749c 100644 --- a/source/blender/blenkernel/CMakeLists.txt +++ b/source/blender/blenkernel/CMakeLists.txt @@ -24,31 +24,32 @@ set(INC ../blenlib ../blenloader ../blentranslation + ../bmesh ../depsgraph ../draw + ../gpencil_modifiers ../gpu ../ikplugin ../imbuf ../makesdna ../makesrna - ../bmesh ../modifiers - ../gpencil_modifiers - ../shader_fx ../nodes ../physics + ../shader_fx ../render/extern/include ../../../intern/ghost - ../../../intern/guardedalloc ../../../intern/glew-mx + ../../../intern/guardedalloc ../../../intern/iksolver/extern - ../../../intern/memutil - ../../../intern/mikktspace ../../../intern/atomic ../../../intern/clog ../../../intern/libmv + ../../../intern/memutil + ../../../intern/mikktspace ../../../intern/opensubdiv ../../../extern/curve_fit_nd + ../../../intern/smoke/extern ) set(INC_SYS @@ -120,6 +121,7 @@ set(SRC intern/idprop_utils.c intern/image.c intern/image_gen.c + intern/image_save.c intern/ipo.c intern/key.c intern/keyconfig.c @@ -274,6 +276,7 @@ set(SRC BKE_idcode.h BKE_idprop.h BKE_image.h + BKE_image_save.h BKE_ipo.h BKE_key.h BKE_keyconfig.h @@ -519,9 +522,6 @@ if(WITH_MOD_FLUID) endif() if(WITH_MOD_SMOKE) - list(APPEND INC - ../../../intern/smoke/extern - ) list(APPEND LIB bf_intern_smoke ) diff --git a/source/blender/blenkernel/intern/CCGSubSurf.c b/source/blender/blenkernel/intern/CCGSubSurf.c index 2ab6eb387aa..49855de0591 100644 --- a/source/blender/blenkernel/intern/CCGSubSurf.c +++ b/source/blender/blenkernel/intern/CCGSubSurf.c @@ -73,8 +73,9 @@ static CCGVert *_vert_new(CCGVertHDL vHDL, CCGSubSurf *ss) userData = ccgSubSurf_getVertUserData(ss, v); memset(userData, 0, ss->meshIFC.vertUserSize); - if (ss->useAgeCounts) + if (ss->useAgeCounts) { *((int *)&userData[ss->vertUserAgeOffset]) = ss->currentAge; + } return v; } @@ -155,8 +156,9 @@ static CCGEdge *_edge_new(CCGEdgeHDL eHDL, CCGVert *v0, CCGVert *v1, float creas userData = ccgSubSurf_getEdgeUserData(ss, e); memset(userData, 0, ss->meshIFC.edgeUserSize); - if (ss->useAgeCounts) + if (ss->useAgeCounts) { *((int *)&userData[ss->edgeUserAgeOffset]) = ss->currentAge; + } return e; } @@ -229,8 +231,9 @@ static CCGFace *_face_new( userData = ccgSubSurf_getFaceUserData(ss, f); memset(userData, 0, ss->meshIFC.faceUserSize); - if (ss->useAgeCounts) + if (ss->useAgeCounts) { *((int *)&userData[ss->faceUserAgeOffset]) = ss->currentAge; + } return f; } @@ -354,8 +357,9 @@ void ccgSubSurf_free(CCGSubSurf *ss) CCGSUBSURF_free(ss, ss->r); CCGSUBSURF_free(ss, ss->q); - if (ss->defaultEdgeUserData) + if (ss->defaultEdgeUserData) { CCGSUBSURF_free(ss, ss->defaultEdgeUserData); + } ccg_ehash_free(ss->fMap, (EHEntryFreeFP)_face_free, ss); ccg_ehash_free(ss->eMap, (EHEntryFreeFP)_edge_free, ss); @@ -395,13 +399,16 @@ void ccgSubSurf_getAllowEdgeCreation(CCGSubSurf *ss, float *defaultCreaseValue_r, void *defaultUserData_r) { - if (allowEdgeCreation_r) + if (allowEdgeCreation_r) { *allowEdgeCreation_r = ss->allowEdgeCreation; + } if (ss->allowEdgeCreation) { - if (defaultCreaseValue_r) + if (defaultCreaseValue_r) { *defaultCreaseValue_r = ss->defaultCreaseValue; - if (defaultUserData_r) + } + if (defaultUserData_r) { memcpy(defaultUserData_r, ss->defaultEdgeUserData, ss->meshIFC.edgeUserSize); + } } } @@ -432,12 +439,15 @@ void ccgSubSurf_getUseAgeCounts(CCGSubSurf *ss, { *useAgeCounts_r = ss->useAgeCounts; - if (vertUserOffset_r) + if (vertUserOffset_r) { *vertUserOffset_r = ss->vertUserAgeOffset; - if (edgeUserOffset_r) + } + if (edgeUserOffset_r) { *edgeUserOffset_r = ss->edgeUserAgeOffset; - if (faceUserOffset_r) + } + if (faceUserOffset_r) { *faceUserOffset_r = ss->faceUserAgeOffset; + } } CCGError ccgSubSurf_setUseAgeCounts( @@ -666,8 +676,9 @@ CCGError ccgSubSurf_syncVert( #endif } - if (v_r) + if (v_r) { *v_r = v; + } return eCCGError_None; } @@ -731,8 +742,9 @@ CCGError ccgSubSurf_syncEdge(CCGSubSurf *ss, } } - if (e_r) + if (e_r) { *e_r = e; + } return eCCGError_None; } @@ -783,8 +795,9 @@ CCGError ccgSubSurf_syncFace( ccg_ehash_insert(ss->fMap, (EHEntry *)fNew); } - for (k = 0; k < numVerts; k++) + for (k = 0; k < numVerts; k++) { FACE_getVerts(fNew)[k]->flags |= Vert_eEffected; + } } } else { @@ -800,8 +813,9 @@ CCGError ccgSubSurf_syncFace( for (k = 0; k < numVerts; k++) { ss->tempVerts[k] = ccg_ehash_lookup(ss->vMap, vHDLs[k]); - if (!ss->tempVerts[k]) + if (!ss->tempVerts[k]) { return eCCGError_InvalidValue; + } } for (k = 0; k < numVerts; k++) { ss->tempEdges[k] = _vert_findEdgeTo(ss->tempVerts[k], ss->tempVerts[(k + 1) % numVerts]); @@ -841,8 +855,9 @@ CCGError ccgSubSurf_syncFace( ccg_ehash_insert(ss->fMap, (EHEntry *)f); ss->numGrids += numVerts; - for (k = 0; k < numVerts; k++) + for (k = 0; k < numVerts; k++) { FACE_getVerts(f)[k]->flags |= Vert_eEffected; + } } else { *prevp = f->next; @@ -852,8 +867,9 @@ CCGError ccgSubSurf_syncFace( for (j = 0; j < f->numVerts; j++) { if (FACE_getVerts(f)[j]->flags & Vert_eChanged) { - for (k = 0; k < f->numVerts; k++) + for (k = 0; k < f->numVerts; k++) { FACE_getVerts(f)[k]->flags |= Vert_eEffected; + } break; } } @@ -869,8 +885,9 @@ CCGError ccgSubSurf_syncFace( #endif } - if (f_r) + if (f_r) { *f_r = f; + } return eCCGError_None; } @@ -929,8 +946,9 @@ void ccgSubSurf__allFaces(CCGSubSurf *ss, CCGFace ***faces, int *numFaces, int * for (i = 0; i < ss->fMap->curSize; i++) { CCGFace *f = (CCGFace *)ss->fMap->buckets[i]; - for (; f; f = f->next) + for (; f; f = f->next) { array[num++] = f; + } } *faces = array; @@ -967,9 +985,11 @@ void ccgSubSurf__effectedFaceNeighbours(CCGSubSurf *ss, CCGVert *v = (CCGVert *)ss->vMap->buckets[i]; for (; v; v = v->next) { - for (j = 0; j < v->numFaces; j++) - if (!(v->faces[j]->flags & Face_eEffected)) + for (j = 0; j < v->numFaces; j++) { + if (!(v->faces[j]->flags & Face_eEffected)) { break; + } + } if (j == v->numFaces) { arrayV[numV++] = v; @@ -982,9 +1002,11 @@ void ccgSubSurf__effectedFaceNeighbours(CCGSubSurf *ss, CCGEdge *e = (CCGEdge *)ss->eMap->buckets[i]; for (; e; e = e->next) { - for (j = 0; j < e->numFaces; j++) - if (!(e->faces[j]->flags & Face_eEffected)) + for (j = 0; j < e->numFaces; j++) { + if (!(e->faces[j]->flags & Face_eEffected)) { break; + } + } if (j == e->numFaces) { e->flags |= Edge_eEffected; @@ -1023,8 +1045,9 @@ CCGError ccgSubSurf_updateFromFaces(CCGSubSurf *ss, int lvl, CCGFace **effectedF VertDataCopy( VERT_getCo(FACE_getVerts(f)[S], lvl), FACE_getIFCo(f, lvl, S, cornerIdx, cornerIdx), ss); - for (x = 0; x < gridSize; x++) + for (x = 0; x < gridSize; x++) { VertDataCopy(FACE_getIECo(f, lvl, S, x), FACE_getIFCo(f, lvl, S, x, 0), ss); + } for (x = 0; x < gridSize; x++) { int eI = gridSize - 1 - x; @@ -1038,8 +1061,9 @@ CCGError ccgSubSurf_updateFromFaces(CCGSubSurf *ss, int lvl, CCGFace **effectedF } } - if (freeF) + if (freeF) { MEM_freeN(effectedF); + } return eCCGError_None; } @@ -1086,8 +1110,9 @@ CCGError ccgSubSurf_updateToFaces(CCGSubSurf *ss, int lvl, CCGFace **effectedF, } } - if (freeF) + if (freeF) { MEM_freeN(effectedF); + } return eCCGError_None; } @@ -1115,16 +1140,19 @@ CCGError ccgSubSurf_stitchFaces(CCGSubSurf *ss, int lvl, CCGFace **effectedF, in /* zero */ for (i = 0; i < numEffectedV; i++) { CCGVert *v = effectedV[i]; - if (v->numFaces) + if (v->numFaces) { VertDataZero(VERT_getCo(v, lvl), ss); + } } for (i = 0; i < numEffectedE; i++) { CCGEdge *e = effectedE[i]; - if (e->numFaces) - for (x = 0; x < edgeSize; x++) + if (e->numFaces) { + for (x = 0; x < edgeSize; x++) { VertDataZero(EDGE_getCo(e, lvl, x), ss); + } + } } /* add */ @@ -1133,9 +1161,11 @@ CCGError ccgSubSurf_stitchFaces(CCGSubSurf *ss, int lvl, CCGFace **effectedF, in VertDataZero((float *)FACE_getCenterData(f), ss); - for (S = 0; S < f->numVerts; S++) - for (x = 0; x < gridSize; x++) + for (S = 0; S < f->numVerts; S++) { + for (x = 0; x < gridSize; x++) { VertDataZero(FACE_getIECo(f, lvl, S, x), ss); + } + } for (S = 0; S < f->numVerts; S++) { int prevS = (S + f->numVerts - 1) % f->numVerts; @@ -1143,10 +1173,11 @@ CCGError ccgSubSurf_stitchFaces(CCGSubSurf *ss, int lvl, CCGFace **effectedF, in CCGEdge *prevE = FACE_getEdges(f)[prevS]; VertDataAdd((float *)FACE_getCenterData(f), FACE_getIFCo(f, lvl, S, 0, 0), ss); - if (FACE_getVerts(f)[S]->flags & Vert_eEffected) + if (FACE_getVerts(f)[S]->flags & Vert_eEffected) { VertDataAdd(VERT_getCo(FACE_getVerts(f)[S], lvl), FACE_getIFCo(f, lvl, S, cornerIdx, cornerIdx), ss); + } for (x = 1; x < gridSize - 1; x++) { VertDataAdd(FACE_getIECo(f, lvl, S, x), FACE_getIFCo(f, lvl, S, x, 0), ss); @@ -1155,15 +1186,18 @@ CCGError ccgSubSurf_stitchFaces(CCGSubSurf *ss, int lvl, CCGFace **effectedF, in for (x = 0; x < gridSize - 1; x++) { int eI = gridSize - 1 - x; - if (FACE_getEdges(f)[S]->flags & Edge_eEffected) + if (FACE_getEdges(f)[S]->flags & Edge_eEffected) { VertDataAdd(_edge_getCoVert(e, FACE_getVerts(f)[S], lvl, eI, vertDataSize), FACE_getIFCo(f, lvl, S, cornerIdx, x), ss); - if (FACE_getEdges(f)[prevS]->flags & Edge_eEffected) - if (x != 0) + } + if (FACE_getEdges(f)[prevS]->flags & Edge_eEffected) { + if (x != 0) { VertDataAdd(_edge_getCoVert(prevE, FACE_getVerts(f)[S], lvl, eI, vertDataSize), FACE_getIFCo(f, lvl, S, x, cornerIdx), ss); + } + } } } } @@ -1171,8 +1205,9 @@ CCGError ccgSubSurf_stitchFaces(CCGSubSurf *ss, int lvl, CCGFace **effectedF, in /* average */ for (i = 0; i < numEffectedV; i++) { CCGVert *v = effectedV[i]; - if (v->numFaces) + if (v->numFaces) { VertDataMulN(VERT_getCo(v, lvl), 1.0f / v->numFaces, ss); + } } for (i = 0; i < numEffectedE; i++) { @@ -1181,9 +1216,11 @@ CCGError ccgSubSurf_stitchFaces(CCGSubSurf *ss, int lvl, CCGFace **effectedF, in VertDataCopy(EDGE_getCo(e, lvl, 0), VERT_getCo(e->v0, lvl), ss); VertDataCopy(EDGE_getCo(e, lvl, edgeSize - 1), VERT_getCo(e->v1, lvl), ss); - if (e->numFaces) - for (x = 1; x < edgeSize - 1; x++) + if (e->numFaces) { + for (x = 1; x < edgeSize - 1; x++) { VertDataMulN(EDGE_getCo(e, lvl, x), 1.0f / e->numFaces, ss); + } + } } /* copy */ @@ -1192,9 +1229,11 @@ CCGError ccgSubSurf_stitchFaces(CCGSubSurf *ss, int lvl, CCGFace **effectedF, in VertDataMulN((float *)FACE_getCenterData(f), 1.0f / f->numVerts, ss); - for (S = 0; S < f->numVerts; S++) - for (x = 1; x < gridSize - 1; x++) + for (S = 0; S < f->numVerts; S++) { + for (x = 1; x < gridSize - 1; x++) { VertDataMulN(FACE_getIECo(f, lvl, S, x), 0.5f, ss); + } + } for (S = 0; S < f->numVerts; S++) { int prevS = (S + f->numVerts - 1) % f->numVerts; @@ -1227,17 +1266,21 @@ CCGError ccgSubSurf_stitchFaces(CCGSubSurf *ss, int lvl, CCGFace **effectedF, in } } - for (i = 0; i < numEffectedV; i++) + for (i = 0; i < numEffectedV; i++) { effectedV[i]->flags = 0; - for (i = 0; i < numEffectedE; i++) + } + for (i = 0; i < numEffectedE; i++) { effectedE[i]->flags = 0; - for (i = 0; i < numEffectedF; i++) + } + for (i = 0; i < numEffectedF; i++) { effectedF[i]->flags = 0; + } MEM_freeN(effectedE); MEM_freeN(effectedV); - if (freeF) + if (freeF) { MEM_freeN(effectedF); + } return eCCGError_None; } @@ -1616,20 +1659,24 @@ void CCG_key(CCGKey *key, const CCGSubSurf *ss, int level) /* if normals are present, always the last three floats of an * element */ - if (key->has_normals) + if (key->has_normals) { key->normal_offset = key->elem_size - sizeof(float) * 3; - else + } + else { key->normal_offset = -1; + } key->grid_size = ccgSubSurf_getGridLevelSize(ss, level); key->grid_area = key->grid_size * key->grid_size; key->grid_bytes = key->elem_size * key->grid_area; key->has_mask = ss->allocMask; - if (key->has_mask) + if (key->has_mask) { key->mask_offset = ss->maskDataOffset; - else + } + else { key->mask_offset = -1; + } } void CCG_key_top_level(CCGKey *key, const CCGSubSurf *ss) diff --git a/source/blender/blenkernel/intern/CCGSubSurf_inline.h b/source/blender/blenkernel/intern/CCGSubSurf_inline.h index 44e27cb89da..86012bd2a43 100644 --- a/source/blender/blenkernel/intern/CCGSubSurf_inline.h +++ b/source/blender/blenkernel/intern/CCGSubSurf_inline.h @@ -144,18 +144,22 @@ BLI_INLINE float *ccg_face_getIFNo( BLI_INLINE int ccg_face_getVertIndex(CCGFace *f, CCGVert *v) { int i; - for (i = 0; i < f->numVerts; i++) - if (FACE_getVerts(f)[i] == v) + for (i = 0; i < f->numVerts; i++) { + if (FACE_getVerts(f)[i] == v) { return i; + } + } return -1; } BLI_INLINE int ccg_face_getEdgeIndex(CCGFace *f, CCGEdge *e) { int i; - for (i = 0; i < f->numVerts; i++) - if (FACE_getEdges(f)[i] == e) + for (i = 0; i < f->numVerts; i++) { + if (FACE_getEdges(f)[i] == e) { return i; + } + } return -1; } @@ -214,8 +218,9 @@ BLI_INLINE int VertDataEqual(const float a[], const float b[], const CCGSubSurf { int i; for (i = 0; i < ss->meshIFC.numLayers; i++) { - if (a[i] != b[i]) + if (a[i] != b[i]) { return 0; + } } return 1; } @@ -228,29 +233,33 @@ BLI_INLINE void VertDataZero(float v[], const CCGSubSurf *ss) BLI_INLINE void VertDataCopy(float dst[], const float src[], const CCGSubSurf *ss) { int i; - for (i = 0; i < ss->meshIFC.numLayers; i++) + for (i = 0; i < ss->meshIFC.numLayers; i++) { dst[i] = src[i]; + } } BLI_INLINE void VertDataAdd(float a[], const float b[], const CCGSubSurf *ss) { int i; - for (i = 0; i < ss->meshIFC.numLayers; i++) + for (i = 0; i < ss->meshIFC.numLayers; i++) { a[i] += b[i]; + } } BLI_INLINE void VertDataSub(float a[], const float b[], const CCGSubSurf *ss) { int i; - for (i = 0; i < ss->meshIFC.numLayers; i++) + for (i = 0; i < ss->meshIFC.numLayers; i++) { a[i] -= b[i]; + } } BLI_INLINE void VertDataMulN(float v[], float f, const CCGSubSurf *ss) { int i; - for (i = 0; i < ss->meshIFC.numLayers; i++) + for (i = 0; i < ss->meshIFC.numLayers; i++) { v[i] *= f; + } } BLI_INLINE void VertDataAvg4(float v[], @@ -261,8 +270,9 @@ BLI_INLINE void VertDataAvg4(float v[], const CCGSubSurf *ss) { int i; - for (i = 0; i < ss->meshIFC.numLayers; i++) + for (i = 0; i < ss->meshIFC.numLayers; i++) { v[i] = (a[i] + b[i] + c[i] + d[i]) * 0.25f; + } } #endif /* __CCGSUBSURF_INLINE_H__ */ diff --git a/source/blender/blenkernel/intern/CCGSubSurf_intern.h b/source/blender/blenkernel/intern/CCGSubSurf_intern.h index f89545e802e..41a34b65381 100644 --- a/source/blender/blenkernel/intern/CCGSubSurf_intern.h +++ b/source/blender/blenkernel/intern/CCGSubSurf_intern.h @@ -269,7 +269,10 @@ struct CCGSubSurf { #define EDGE_getNo(e, lvl, x) ccg_edge_getNo(e, lvl, x, vertDataSize, normalDataOffset) #define FACE_getIFNo(f, lvl, S, x, y) \ ccg_face_getIFNo(f, lvl, S, x, y, subdivLevels, vertDataSize, normalDataOffset) -//#define FACE_calcIFNo(f, lvl, S, x, y, no) _face_calcIFNo(f, lvl, S, x, y, no, subdivLevels, vertDataSize) +#if 0 +# define FACE_calcIFNo(f, lvl, S, x, y, no) \ + _face_calcIFNo(f, lvl, S, x, y, no, subdivLevels, vertDataSize) +#endif #define FACE_getIENo(f, lvl, S, x) \ ccg_face_getIENo(f, lvl, S, x, subdivLevels, vertDataSize, normalDataOffset) #define FACE_getIECo(f, lvl, S, x) ccg_face_getIECo(f, lvl, S, x, subdivLevels, vertDataSize) diff --git a/source/blender/blenkernel/intern/CCGSubSurf_legacy.c b/source/blender/blenkernel/intern/CCGSubSurf_legacy.c index 430a8ef56f5..720c828664a 100644 --- a/source/blender/blenkernel/intern/CCGSubSurf_legacy.c +++ b/source/blender/blenkernel/intern/CCGSubSurf_legacy.c @@ -52,9 +52,11 @@ static int _edge_isBoundary(const CCGEdge *e) static int _vert_isBoundary(const CCGVert *v) { int i; - for (i = 0; i < v->numEdges; i++) - if (_edge_isBoundary(v->edges[i])) + for (i = 0; i < v->numEdges; i++) { + if (_edge_isBoundary(v->edges[i])) { return 1; + } + } return 0; } @@ -106,14 +108,18 @@ static int VERT_seam(const CCGVert *v) static float EDGE_getSharpness(CCGEdge *e, int lvl) { - if (!lvl) + if (!lvl) { return e->crease; - else if (!e->crease) + } + else if (!e->crease) { return 0.0f; - else if (e->crease - lvl < 0.0f) + } + else if (e->crease - lvl < 0.0f) { return 0.0f; - else + } + else { return e->crease - lvl; + } } typedef struct CCGSubSurfCalcSubdivData { @@ -181,10 +187,12 @@ static void ccgSubSurf__calcVertNormals_faces_accumulate_cb( FACE_calcIFNo(f, lvl, S, x, y, no); NormAdd(FACE_getIFNo(f, lvl, S, x + 0, y + 0), no); - if (xPlusOk) + if (xPlusOk) { NormAdd(FACE_getIFNo(f, lvl, S, x + 1, y + 0), no); - if (yPlusOk) + } + if (yPlusOk) { NormAdd(FACE_getIFNo(f, lvl, S, x + 0, y + 1), no); + } if (xPlusOk && yPlusOk) { if (x < gridSize - 2 || y < gridSize - 2 || FACE_getVerts(f)[S]->flags & Vert_eEffected) { @@ -195,10 +203,12 @@ static void ccgSubSurf__calcVertNormals_faces_accumulate_cb( if (x == 0 && y == 0) { int K; - if (!yLimitNext || 1 < gridSize - 1) + if (!yLimitNext || 1 < gridSize - 1) { NormAdd(FACE_getIFNo(f, lvl, (S + 1) % f->numVerts, 0, 1), no); - if (!xLimitPrev || 1 < gridSize - 1) + } + if (!xLimitPrev || 1 < gridSize - 1) { NormAdd(FACE_getIFNo(f, lvl, (S - 1 + f->numVerts) % f->numVerts, 1, 0), no); + } for (K = 0; K < f->numVerts; K++) { if (K != S) { @@ -208,13 +218,15 @@ static void ccgSubSurf__calcVertNormals_faces_accumulate_cb( } else if (y == 0) { NormAdd(FACE_getIFNo(f, lvl, (S + 1) % f->numVerts, 0, x), no); - if (!yLimitNext || x < gridSize - 2) + if (!yLimitNext || x < gridSize - 2) { NormAdd(FACE_getIFNo(f, lvl, (S + 1) % f->numVerts, 0, x + 1), no); + } } else if (x == 0) { NormAdd(FACE_getIFNo(f, lvl, (S - 1 + f->numVerts) % f->numVerts, y, 0), no); - if (!xLimitPrev || y < gridSize - 2) + if (!xLimitPrev || y < gridSize - 2) { NormAdd(FACE_getIFNo(f, lvl, (S - 1 + f->numVerts) % f->numVerts, y + 1, 0), no); + } } } } @@ -390,10 +402,11 @@ static void ccgSubSurf__calcVertNormals(CCGSubSurf *ss, int x; const int f_ed_idx = ccg_face_getEdgeIndex(f, e); - for (x = 0; x < edgeSize; x++) + for (x = 0; x < edgeSize; x++) { NormCopy(EDGE_getNo(e, lvl, x), _face_getIFNoEdge( f, e, f_ed_idx, lvl, x, 0, subdivLevels, vertDataSize, normalDataOffset)); + } } else { /* set to zero here otherwise the normals are uninitialized memory @@ -763,8 +776,9 @@ static void ccgSubSurf__calcSubdivLevel(CCGSubSurf *ss, CCGEdge *e = v->edges[j]; float sharpness = EDGE_getSharpness(e, curLvl); - if (seam && _edge_isBoundary(e)) + if (seam && _edge_isBoundary(e)) { seamEdges++; + } if (sharpness != 0.0f) { sharpCount++; @@ -782,8 +796,9 @@ static void ccgSubSurf__calcSubdivLevel(CCGSubSurf *ss, } } - if (seamEdges < 2 || seamEdges != v->numEdges) + if (seamEdges < 2 || seamEdges != v->numEdges) { seam = 0; + } if (!v->numEdges || ss->meshIFC.simpleSubdiv) { VertDataCopy(nCo, co, ss); @@ -846,8 +861,9 @@ static void ccgSubSurf__calcSubdivLevel(CCGSubSurf *ss, float sharpness = EDGE_getSharpness(e, curLvl); if (seam) { - if (_edge_isBoundary(e)) + if (_edge_isBoundary(e)) { VertDataAdd(q, _edge_getCoVert(e, v, curLvl, 1, vertDataSize), ss); + } } else if (sharpness != 0.0f) { VertDataAdd(q, _edge_getCoVert(e, v, curLvl, 1, vertDataSize), ss); @@ -1104,8 +1120,9 @@ void ccgSubSurf__sync_legacy(CCGSubSurf *ss) CCGEdge *e = v->edges[i]; float sharpness = EDGE_getSharpness(e, curLvl); - if (seam && _edge_isBoundary(e)) + if (seam && _edge_isBoundary(e)) { seamEdges++; + } if (sharpness != 0.0f) { sharpCount++; @@ -1123,8 +1140,9 @@ void ccgSubSurf__sync_legacy(CCGSubSurf *ss) } } - if (seamEdges < 2 || seamEdges != v->numEdges) + if (seamEdges < 2 || seamEdges != v->numEdges) { seam = 0; + } if (!v->numEdges || ss->meshIFC.simpleSubdiv) { VertDataCopy(nCo, co, ss); @@ -1267,13 +1285,15 @@ void ccgSubSurf__sync_legacy(CCGSubSurf *ss) } } - for (curLvl = 1; curLvl < subdivLevels; curLvl++) + for (curLvl = 1; curLvl < subdivLevels; curLvl++) { ccgSubSurf__calcSubdivLevel( ss, effectedV, effectedE, effectedF, numEffectedV, numEffectedE, numEffectedF, curLvl); + } - if (ss->calcVertNormals) + if (ss->calcVertNormals) { ccgSubSurf__calcVertNormals( ss, effectedV, effectedE, effectedF, numEffectedV, numEffectedE, numEffectedF); + } for (ptrIdx = 0; ptrIdx < numEffectedV; ptrIdx++) { CCGVert *v = effectedV[ptrIdx]; @@ -1306,21 +1326,26 @@ CCGError ccgSubSurf_updateNormals(CCGSubSurf *ss, CCGFace **effectedF, int numEf ccgSubSurf__effectedFaceNeighbours( ss, effectedF, numEffectedF, &effectedV, &numEffectedV, &effectedE, &numEffectedE); - if (ss->calcVertNormals) + if (ss->calcVertNormals) { ccgSubSurf__calcVertNormals( ss, effectedV, effectedE, effectedF, numEffectedV, numEffectedE, numEffectedF); + } - for (i = 0; i < numEffectedV; i++) + for (i = 0; i < numEffectedV; i++) { effectedV[i]->flags = 0; - for (i = 0; i < numEffectedE; i++) + } + for (i = 0; i < numEffectedE; i++) { effectedE[i]->flags = 0; - for (i = 0; i < numEffectedF; i++) + } + for (i = 0; i < numEffectedF; i++) { effectedF[i]->flags = 0; + } MEM_freeN(effectedE); MEM_freeN(effectedV); - if (freeF) + if (freeF) { MEM_freeN(effectedF); + } return eCCGError_None; } @@ -1344,17 +1369,21 @@ CCGError ccgSubSurf_updateLevels(CCGSubSurf *ss, int lvl, CCGFace **effectedF, i ss, effectedV, effectedE, effectedF, numEffectedV, numEffectedE, numEffectedF, curLvl); } - for (i = 0; i < numEffectedV; i++) + for (i = 0; i < numEffectedV; i++) { effectedV[i]->flags = 0; - for (i = 0; i < numEffectedE; i++) + } + for (i = 0; i < numEffectedE; i++) { effectedE[i]->flags = 0; - for (i = 0; i < numEffectedF; i++) + } + for (i = 0; i < numEffectedF; i++) { effectedF[i]->flags = 0; + } MEM_freeN(effectedE); MEM_freeN(effectedV); - if (freeF) + if (freeF) { MEM_freeN(effectedF); + } return eCCGError_None; } diff --git a/source/blender/blenkernel/intern/CCGSubSurf_opensubdiv_converter.c b/source/blender/blenkernel/intern/CCGSubSurf_opensubdiv_converter.c index 53af82f4c0c..eb04d13d4a0 100644 --- a/source/blender/blenkernel/intern/CCGSubSurf_opensubdiv_converter.c +++ b/source/blender/blenkernel/intern/CCGSubSurf_opensubdiv_converter.c @@ -69,10 +69,12 @@ typedef struct ConvDMStorage { static OpenSubdiv_SchemeType conv_dm_get_type(const OpenSubdiv_Converter *converter) { ConvDMStorage *storage = converter->user_data; - if (storage->ss->meshIFC.simpleSubdiv) + if (storage->ss->meshIFC.simpleSubdiv) { return OSD_SCHEME_BILINEAR; - else + } + else { return OSD_SCHEME_CATMARK; + } } static OpenSubdiv_VtxBoundaryInterpolation conv_dm_get_vtx_boundary_interpolation( diff --git a/source/blender/blenkernel/intern/CCGSubSurf_util.c b/source/blender/blenkernel/intern/CCGSubSurf_util.c index 9ad1b0cf1b1..ebd4531a67b 100644 --- a/source/blender/blenkernel/intern/CCGSubSurf_util.c +++ b/source/blender/blenkernel/intern/CCGSubSurf_util.c @@ -51,8 +51,9 @@ EHash *ccg_ehash_new(int estimatedNumEntries, eh->allocator = allocator; eh->numEntries = 0; eh->curSizeIdx = 0; - while (kHashSizes[eh->curSizeIdx] < estimatedNumEntries) + while (kHashSizes[eh->curSizeIdx] < estimatedNumEntries) { eh->curSizeIdx++; + } eh->curSize = kHashSizes[eh->curSizeIdx]; eh->buckets = EHASH_alloc(eh, eh->curSize * sizeof(*eh->buckets)); memset(eh->buckets, 0, eh->curSize * sizeof(*eh->buckets)); @@ -133,8 +134,9 @@ void *ccg_ehash_lookup(EHash *eh, void *key) EHEntry *entry; for (entry = eh->buckets[hash]; entry; entry = entry->next) { - if (entry->key == key) + if (entry->key == key) { break; + } } return entry; @@ -151,8 +153,9 @@ void ccg_ehashIterator_init(EHash *eh, EHashIterator *ehi) while (!ehi->curEntry) { ehi->curBucket++; - if (ehi->curBucket == ehi->eh->curSize) + if (ehi->curBucket == ehi->eh->curSize) { break; + } ehi->curEntry = ehi->eh->buckets[ehi->curBucket]; } } @@ -168,8 +171,9 @@ void ccg_ehashIterator_next(EHashIterator *ehi) ehi->curEntry = ehi->curEntry->next; while (!ehi->curEntry) { ehi->curBucket++; - if (ehi->curBucket == ehi->eh->curSize) + if (ehi->curBucket == ehi->eh->curSize) { break; + } ehi->curEntry = ehi->eh->buckets[ehi->curBucket]; } } diff --git a/source/blender/blenkernel/intern/DerivedMesh.c b/source/blender/blenkernel/intern/DerivedMesh.c index 2c22f744125..959435ad486 100644 --- a/source/blender/blenkernel/intern/DerivedMesh.c +++ b/source/blender/blenkernel/intern/DerivedMesh.c @@ -175,8 +175,9 @@ static MVert *dm_dupVertArray(DerivedMesh *dm) { MVert *tmp = MEM_malloc_arrayN(dm->getNumVerts(dm), sizeof(*tmp), "dm_dupVertArray tmp"); - if (tmp) + if (tmp) { dm->copyVertArray(dm, tmp); + } return tmp; } @@ -185,8 +186,9 @@ static MEdge *dm_dupEdgeArray(DerivedMesh *dm) { MEdge *tmp = MEM_malloc_arrayN(dm->getNumEdges(dm), sizeof(*tmp), "dm_dupEdgeArray tmp"); - if (tmp) + if (tmp) { dm->copyEdgeArray(dm, tmp); + } return tmp; } @@ -195,8 +197,9 @@ static MFace *dm_dupFaceArray(DerivedMesh *dm) { MFace *tmp = MEM_malloc_arrayN(dm->getNumTessFaces(dm), sizeof(*tmp), "dm_dupFaceArray tmp"); - if (tmp) + if (tmp) { dm->copyTessFaceArray(dm, tmp); + } return tmp; } @@ -205,8 +208,9 @@ static MLoop *dm_dupLoopArray(DerivedMesh *dm) { MLoop *tmp = MEM_malloc_arrayN(dm->getNumLoops(dm), sizeof(*tmp), "dm_dupLoopArray tmp"); - if (tmp) + if (tmp) { dm->copyLoopArray(dm, tmp); + } return tmp; } @@ -215,8 +219,9 @@ static MPoly *dm_dupPolyArray(DerivedMesh *dm) { MPoly *tmp = MEM_malloc_arrayN(dm->getNumPolys(dm), sizeof(*tmp), "dm_dupPolyArray tmp"); - if (tmp) + if (tmp) { dm->copyPolyArray(dm, tmp); + } return tmp; } @@ -241,8 +246,8 @@ static const MLoopTri *dm_getLoopTriArray(DerivedMesh *dm) } else { BLI_rw_mutex_lock(&loops_cache_lock, THREAD_LOCK_WRITE); - /* We need to ensure array is still NULL inside mutex-protected code, some other thread might have already - * recomputed those looptris. */ + /* We need to ensure array is still NULL inside mutex-protected code, + * some other thread might have already recomputed those looptris. */ if (dm->looptris.array == NULL) { dm->recalcLoopTri(dm); } @@ -480,7 +485,8 @@ void DM_ensure_normals(DerivedMesh *dm) /** * Ensure the array is large enough * - * \note This function must always be thread-protected by caller. It should only be used by internal code. + * \note This function must always be thread-protected by caller. + * It should only be used by internal code. */ void DM_ensure_looptri_data(DerivedMesh *dm) { @@ -756,24 +762,27 @@ void *DM_get_poly_data(DerivedMesh *dm, int index, int type) void *DM_get_vert_data_layer(DerivedMesh *dm, int type) { - if (type == CD_MVERT) + if (type == CD_MVERT) { return dm->getVertArray(dm); + } return CustomData_get_layer(&dm->vertData, type); } void *DM_get_edge_data_layer(DerivedMesh *dm, int type) { - if (type == CD_MEDGE) + if (type == CD_MEDGE) { return dm->getEdgeArray(dm); + } return CustomData_get_layer(&dm->edgeData, type); } void *DM_get_tessface_data_layer(DerivedMesh *dm, int type) { - if (type == CD_MFACE) + if (type == CD_MFACE) { return dm->getTessFaceArray(dm); + } return CustomData_get_layer(&dm->faceData, type); } @@ -814,8 +823,9 @@ DerivedMesh *mesh_create_derived(Mesh *me, float (*vertCos)[3]) { DerivedMesh *dm = CDDM_from_mesh(me); - if (!dm) + if (!dm) { return NULL; + } if (vertCos) { CDDM_apply_vert_coords(dm, vertCos); @@ -852,10 +862,12 @@ static float (*get_orco_coords(Object *ob, BMEditMesh *em, int layer, int *free) /* get original coordinates */ *free = 1; - if (em) + if (em) { return get_editbmesh_orco_verts(em); - else + } + else { return BKE_mesh_orco_verts_get(ob); + } } else if (layer == CD_CLOTH_ORCO) { /* apply shape key for cloth, this should really be solved @@ -893,8 +905,9 @@ static Mesh *create_orco_mesh(Object *ob, Mesh *me, BMEditMesh *em, int layer) if (orco) { BKE_mesh_apply_vert_coords(mesh, orco); - if (free) + if (free) { MEM_freeN(orco); + } } return mesh; @@ -936,8 +949,9 @@ static void add_orco_mesh(Object *ob, BMEditMesh *em, Mesh *mesh, Mesh *mesh_orc } memcpy(layerorco, orco, sizeof(float) * 3 * totvert); - if (free) + if (free) { MEM_freeN(orco); + } } } @@ -954,8 +968,9 @@ static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape KeyBlock *kb; int i, j, tot; - if (!me->key) + if (!me->key) { return; + } tot = CustomData_number_of_layers(&dm->vertData, CD_SHAPEKEY); for (i = 0; i < tot; i++) { @@ -964,8 +979,9 @@ static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape float(*cos)[3], (*kbcos)[3]; for (kb = me->key->block.first; kb; kb = kb->next) { - if (kb->uid == layer->uid) + if (kb->uid == layer->uid) { break; + } } if (!kb) { @@ -973,8 +989,9 @@ static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape kb->uid = layer->uid; } - if (kb->data) + if (kb->data) { MEM_freeN(kb->data); + } cos = CustomData_get_layer_n(&dm->vertData, CD_SHAPEKEY, i); kb->totelem = dm->numVertData; @@ -996,8 +1013,9 @@ static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape for (kb = me->key->block.first; kb; kb = kb->next) { if (kb->totelem != dm->numVertData) { - if (kb->data) + if (kb->data) { MEM_freeN(kb->data); + } kb->totelem = dm->numVertData; kb->data = MEM_calloc_arrayN(kb->totelem, 3 * sizeof(float), "kb->data derivedmesh.c"); @@ -1022,16 +1040,28 @@ static void mesh_calc_modifier_final_normals(const Mesh *mesh_input, /* Compute normals. */ const bool do_loop_normals = ((mesh_input->flag & ME_AUTOSMOOTH) != 0 || (dataMask->lmask & CD_MASK_NORMAL) != 0); - /* Some modifiers may need this info from their target (other) object, simpler to generate it here as well. + /* Some modifiers may need this info from their target (other) object, + * simpler to generate it here as well. * Note that they will always be generated when no loop normals are comptuted, * since they are needed by drawing code. */ const bool do_poly_normals = ((dataMask->pmask & CD_MASK_NORMAL) != 0); if (do_loop_normals) { - /* In case we also need poly normals, add the layer here, then BKE_mesh_calc_normals_split() will fill it. */ + /* In case we also need poly normals, add the layer and compute them here + * (BKE_mesh_calc_normals_split() assumes that if that data exists, it is always valid). */ if (do_poly_normals) { if (!CustomData_has_layer(&mesh_final->pdata, CD_NORMAL)) { - CustomData_add_layer(&mesh_final->pdata, CD_NORMAL, CD_CALLOC, NULL, mesh_final->totpoly); + float(*polynors)[3] = CustomData_add_layer( + &mesh_final->pdata, CD_NORMAL, CD_CALLOC, NULL, mesh_final->totpoly); + BKE_mesh_calc_normals_poly(mesh_final->mvert, + NULL, + mesh_final->totvert, + mesh_final->mloop, + mesh_final->mpoly, + mesh_final->totloop, + mesh_final->totpoly, + polynors, + false); } } /* Compute loop normals (note: will compute poly and vert normals as well, if needed!) */ @@ -1059,8 +1089,9 @@ static void mesh_calc_modifier_final_normals(const Mesh *mesh_input, } } - /* Some modifiers, like datatransfer, may generate those data as temp layer, we do not want to keep them, - * as they are used by display code when available (i.e. even if autosmooth is disabled). */ + /* Some modifiers, like data-transfer, may generate those data as temp layer, + * we do not want to keep them, as they are used by display code when available + * (i.e. even if autosmooth is disabled). */ if (!do_loop_normals && CustomData_has_layer(&mesh_final->ldata, CD_NORMAL)) { CustomData_free_layers(&mesh_final->ldata, CD_NORMAL, mesh_final->totloop); } @@ -1184,8 +1215,9 @@ static void mesh_calc_modifiers(struct Depsgraph *depsgraph, } /* grab modifiers until index i */ - if ((index != -1) && (BLI_findindex(&ob->modifiers, md) >= index)) + if ((index != -1) && (BLI_findindex(&ob->modifiers, md) >= index)) { break; + } } /* Result of all leading deforming modifiers is cached for @@ -1227,19 +1259,23 @@ static void mesh_calc_modifiers(struct Depsgraph *depsgraph, } } - if (sculpt_dyntopo) + if (sculpt_dyntopo) { unsupported = true; + } - if (scene->toolsettings->sculpt->flags & SCULPT_ONLY_DEFORM) + if (scene->toolsettings->sculpt->flags & SCULPT_ONLY_DEFORM) { unsupported |= (mti->type != eModifierTypeType_OnlyDeform); + } unsupported |= multires_applied; if (unsupported) { - if (sculpt_dyntopo) + if (sculpt_dyntopo) { modifier_setError(md, "Not supported in dyntopo"); - else + } + else { modifier_setError(md, "Not supported in sculpt mode"); + } continue; } else { @@ -1294,10 +1330,12 @@ static void mesh_calc_modifiers(struct Depsgraph *depsgraph, else { /* determine which data layers are needed by following modifiers */ CustomData_MeshMasks nextmask; - if (md_datamask->next) + if (md_datamask->next) { nextmask = md_datamask->next->mask; - else + } + else { nextmask = *dataMask; + } /* apply vertex coordinates or build a Mesh as necessary */ if (mesh_final) { @@ -1330,7 +1368,8 @@ static void mesh_calc_modifiers(struct Depsgraph *depsgraph, CustomData_add_layer( &mesh_final->pdata, CD_ORIGINDEX, CD_CALLOC, NULL, mesh_final->totpoly); - /* Not worth parallelizing this, gives less than 0.1% overall speedup in best of best cases... */ + /* Not worth parallelizing this, + * gives less than 0.1% overall speedup in best of best cases... */ range_vn_i( CustomData_get_layer(&mesh_final->vdata, CD_ORIGINDEX), mesh_final->totvert, 0); range_vn_i( @@ -1456,8 +1495,9 @@ static void mesh_calc_modifiers(struct Depsgraph *depsgraph, isPrevDeform = (mti->type == eModifierTypeType_OnlyDeform); /* grab modifiers until index i */ - if ((index != -1) && (BLI_findindex(&ob->modifiers, md) >= index)) + if ((index != -1) && (BLI_findindex(&ob->modifiers, md) >= index)) { break; + } if (sculpt_mode && md->type == eModifierType_Multires) { multires_applied = true; @@ -1466,8 +1506,9 @@ static void mesh_calc_modifiers(struct Depsgraph *depsgraph, BLI_linklist_free((LinkNode *)datamasks, NULL); - for (md = firstmd; md; md = md->next) + for (md = firstmd; md; md = md->next) { modifier_freeTemporaryData(md); + } /* Yay, we are done. If we have a Mesh and deformed vertices * need to apply these back onto the Mesh. If we have no @@ -1485,8 +1526,9 @@ static void mesh_calc_modifiers(struct Depsgraph *depsgraph, if (dataMask->vmask & CD_MASK_ORCO) { add_orco_mesh(ob, NULL, mesh_final, mesh_orco, CD_ORCO); - if (mesh_deform) + if (mesh_deform) { add_orco_mesh(ob, NULL, mesh_deform, NULL, CD_ORCO); + } } if (mesh_orco) { @@ -1547,11 +1589,13 @@ static void editbmesh_calc_modifier_final_normals(const Mesh *mesh_input, { const bool do_loop_normals = ((mesh_input->flag & ME_AUTOSMOOTH) != 0 || (dataMask->lmask & CD_MASK_NORMAL) != 0); - /* Some modifiers may need this info from their target (other) object, simpler to generate it here as well. */ + /* Some modifiers may need this info from their target (other) object, + * simpler to generate it here as well. */ const bool do_poly_normals = ((dataMask->pmask & CD_MASK_NORMAL) != 0); if (do_loop_normals) { - /* In case we also need poly normals, add the layer here, then BKE_mesh_calc_normals_split() will fill it. */ + /* In case we also need poly normals, add the layer here, + * then BKE_mesh_calc_normals_split() will fill it. */ if (do_poly_normals) { if (!CustomData_has_layer(&mesh_final->pdata, CD_NORMAL)) { CustomData_add_layer(&mesh_final->pdata, CD_NORMAL, CD_CALLOC, NULL, mesh_final->totpoly); @@ -1687,11 +1731,13 @@ static void editbmesh_calc_modifiers(struct Depsgraph *depsgraph, BKE_mesh_apply_vert_coords(mesh_final, deformed_verts); } - if (mti->deformVertsEM) + if (mti->deformVertsEM) { modwrap_deformVertsEM( md, &mectx, em_input, mesh_final, deformed_verts, num_deformed_verts); - else + } + else { modwrap_deformVerts(md, &mectx, mesh_final, deformed_verts, num_deformed_verts); + } } else { /* apply vertex coordinates or build a DerivedMesh as necessary */ @@ -1980,7 +2026,10 @@ static void mesh_build_data(struct Depsgraph *depsgraph, * but this avoids waiting on first stroke) */ /* XXX Disabled for now. * This can create horrible nasty bugs by generating re-entrant call of mesh_get_eval_final! */ - // BKE_sculpt_update_mesh_elements(depsgraph, scene, scene->toolsettings->sculpt, ob, false, false); +#if 0 + BKE_sculpt_update_mesh_elements( + depsgraph, scene, scene->toolsettings->sculpt, ob, false, false); +#endif } mesh_runtime_check_normals_valid(ob->runtime.mesh_eval); @@ -2052,8 +2101,9 @@ static void object_get_datamask(const Depsgraph *depsgraph, r_mask->vmask |= CD_MASK_MDEFORMVERT; } - if (ob->mode & OB_MODE_EDIT) + if (ob->mode & OB_MODE_EDIT) { r_mask->vmask |= CD_MASK_MVERT_SKIN; + } } } @@ -2381,10 +2431,12 @@ static void mesh_init_origspace(Mesh *mesh) copy_v2_v2(vcos_2d[j], co); for (k = 0; k < 2; k++) { - if (co[k] > max[k]) + if (co[k] > max[k]) { max[k] = co[k]; - else if (co[k] < min[k]) + } + else if (co[k] < min[k]) { min[k] = co[k]; + } } } @@ -2393,13 +2445,16 @@ static void mesh_init_origspace(Mesh *mesh) /* Scale will bring max to (1, 1). */ sub_v2_v2v2(scale, max, min); - if (scale[0] == 0.0f) + if (scale[0] == 0.0f) { scale[0] = 1e-9f; - if (scale[1] == 0.0f) + } + if (scale[1] == 0.0f) { scale[1] = 1e-9f; + } invert_v2(scale); - /* Finally, transform all vcos_2d into ((0, 0), (1, 1)) square and assign them as origspace. */ + /* Finally, transform all vcos_2d into ((0, 0), (1, 1)) + * square and assign them as origspace. */ for (j = 0; j < mp->totloop; j++, lof++) { add_v2_v2v2(lof->uv, vcos_2d[j], translate); mul_v2_v2(lof->uv, scale); diff --git a/source/blender/blenkernel/intern/action.c b/source/blender/blenkernel/intern/action.c index a3b7df6b020..9b321ff4e44 100644 --- a/source/blender/blenkernel/intern/action.c +++ b/source/blender/blenkernel/intern/action.c @@ -115,8 +115,10 @@ void BKE_action_free(bAction *act) /* .................................. */ /** - * Only copy internal data of Action ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of Action ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * @@ -139,8 +141,11 @@ void BKE_action_copy_data(Main *UNUSED(bmain), for (fcu_src = act_src->curves.first; fcu_src; fcu_src = fcu_src->next) { /* duplicate F-Curve */ - fcu_dst = copy_fcurve( - fcu_src); /* XXX TODO pass subdata flag? But surprisingly does not seem to be doing any ID refcounting... */ + + /* XXX TODO pass subdata flag? + * But surprisingly does not seem to be doing any ID refcounting... */ + fcu_dst = copy_fcurve(fcu_src); + BLI_addtail(&act_dst->curves, fcu_dst); /* fix group links (kindof bad list-in-list search, but this is the most reliable way) */ @@ -177,8 +182,9 @@ bActionGroup *get_active_actiongroup(bAction *act) if (act && act->groups.first) { for (agrp = act->groups.first; agrp; agrp = agrp->next) { - if (agrp->flag & AGRP_ACTIVE) + if (agrp->flag & AGRP_ACTIVE) { break; + } } } @@ -191,15 +197,18 @@ void set_active_action_group(bAction *act, bActionGroup *agrp, short select) bActionGroup *grp; /* sanity checks */ - if (act == NULL) + if (act == NULL) { return; + } /* Deactivate all others */ for (grp = act->groups.first; grp; grp = grp->next) { - if ((grp == agrp) && (select)) + if ((grp == agrp) && (select)) { grp->flag |= AGRP_ACTIVE; - else + } + else { grp->flag &= ~AGRP_ACTIVE; + } } } @@ -240,8 +249,9 @@ bActionGroup *action_groups_add_new(bAction *act, const char name[]) bActionGroup *agrp; /* sanity check: must have action and name */ - if (ELEM(NULL, act, name)) + if (ELEM(NULL, act, name)) { return NULL; + } /* allocate a new one */ agrp = MEM_callocN(sizeof(bActionGroup), "bActionGroup"); @@ -266,8 +276,9 @@ bActionGroup *action_groups_add_new(bAction *act, const char name[]) void action_groups_add_channel(bAction *act, bActionGroup *agrp, FCurve *fcurve) { /* sanity checks */ - if (ELEM(NULL, act, agrp, fcurve)) + if (ELEM(NULL, act, agrp, fcurve)) { return; + } /* if no channels anywhere, just add to two lists at the same time */ if (BLI_listbase_is_empty(&act->curves)) { @@ -285,8 +296,9 @@ void action_groups_add_channel(bAction *act, bActionGroup *agrp, FCurve *fcurve) * then set the F-Curve as the last for the action first so that * the lists will be in sync after linking */ - if (agrp->channels.last == act->curves.last) + if (agrp->channels.last == act->curves.last) { act->curves.last = fcurve; + } /* link in the given F-Curve after the last F-Curve in the group, * which means that it should be able to fit in with the rest of the @@ -302,12 +314,13 @@ void action_groups_add_channel(bAction *act, bActionGroup *agrp, FCurve *fcurve) /* firstly, link this F-Curve to the group */ agrp->channels.first = agrp->channels.last = fcurve; - /* step through the groups preceding this one, finding the F-Curve there to attach this one after */ + /* Step through the groups preceding this one, + * finding the F-Curve there to attach this one after. */ for (grp = agrp->prev; grp; grp = grp->prev) { - /* if this group has F-Curves, we want weave the given one in right after the last channel there, - * but via the Action's list not this group's list + /* if this group has F-Curves, we want weave the given one in right after the last channel + * there, but via the Action's list not this group's list * - this is so that the F-Curve is in the right place in the Action, - * but won't be included in the previous group + * but won't be included in the previous group. */ if (grp->channels.last) { /* once we've added, break here since we don't need to search any further... */ @@ -316,12 +329,13 @@ void action_groups_add_channel(bAction *act, bActionGroup *agrp, FCurve *fcurve) } } - /* if grp is NULL, that means we fell through, and this F-Curve should be added as the new first - * since group is (effectively) the first group. Thus, the existing first F-Curve becomes the - * second in the chain, etc. etc. + /* If grp is NULL, that means we fell through, and this F-Curve should be added as the new + * first since group is (effectively) the first group. Thus, the existing first F-Curve becomes + * the second in the chain, etc. etc. */ - if (grp == NULL) + if (grp == NULL) { BLI_insertlinkbefore(&act->curves, act->curves.first, fcurve); + } } /* set the F-Curve's new group */ @@ -332,8 +346,9 @@ void action_groups_add_channel(bAction *act, bActionGroup *agrp, FCurve *fcurve) void action_groups_remove_channel(bAction *act, FCurve *fcu) { /* sanity checks */ - if (ELEM(NULL, act, fcu)) + if (ELEM(NULL, act, fcu)) { return; + } /* check if any group used this directly */ if (fcu->grp) { @@ -345,16 +360,20 @@ void action_groups_remove_channel(bAction *act, FCurve *fcu) } } else if (agrp->channels.first == fcu) { - if ((fcu->next) && (fcu->next->grp == agrp)) + if ((fcu->next) && (fcu->next->grp == agrp)) { agrp->channels.first = fcu->next; - else + } + else { agrp->channels.first = NULL; + } } else if (agrp->channels.last == fcu) { - if ((fcu->prev) && (fcu->prev->grp == agrp)) + if ((fcu->prev) && (fcu->prev->grp == agrp)) { agrp->channels.last = fcu->prev; - else + } + else { agrp->channels.last = NULL; + } } fcu->grp = NULL; @@ -368,8 +387,9 @@ void action_groups_remove_channel(bAction *act, FCurve *fcu) bActionGroup *BKE_action_group_find_name(bAction *act, const char name[]) { /* sanity checks */ - if (ELEM(NULL, act, act->groups.first, name) || (name[0] == 0)) + if (ELEM(NULL, act, act->groups.first, name) || (name[0] == 0)) { return NULL; + } /* do string comparisons */ return BLI_findstring(&act->groups, name, offsetof(bActionGroup, name)); @@ -381,12 +401,14 @@ void action_groups_clear_tempflags(bAction *act) bActionGroup *agrp; /* sanity checks */ - if (ELEM(NULL, act, act->groups.first)) + if (ELEM(NULL, act, act->groups.first)) { return; + } /* flag clearing loop */ - for (agrp = act->groups.first; agrp; agrp = agrp->next) + for (agrp = act->groups.first; agrp; agrp = agrp->next) { agrp->flag &= ~AGRP_TEMP; + } } /* *************** Pose channels *************** */ @@ -397,11 +419,13 @@ void action_groups_clear_tempflags(bAction *act) */ bPoseChannel *BKE_pose_channel_find_name(const bPose *pose, const char *name) { - if (ELEM(NULL, pose, name) || (name[0] == '\0')) + if (ELEM(NULL, pose, name) || (name[0] == '\0')) { return NULL; + } - if (pose->chanhash) + if (pose->chanhash) { return BLI_ghash_lookup(pose->chanhash, (const void *)name); + } return BLI_findstring(&((const bPose *)pose)->chanbase, name, offsetof(bPoseChannel, name)); } @@ -418,8 +442,9 @@ bPoseChannel *BKE_pose_channel_verify(bPose *pose, const char *name) { bPoseChannel *chan; - if (pose == NULL) + if (pose == NULL) { return NULL; + } /* See if this channel exists */ chan = BKE_pose_channel_find_name(pose, name); @@ -439,7 +464,8 @@ bPoseChannel *BKE_pose_channel_verify(bPose *pose, const char *name) unit_axis_angle(chan->rotAxis, &chan->rotAngle); chan->size[0] = chan->size[1] = chan->size[2] = 1.0f; - chan->scaleIn = chan->scaleOut = 1.0f; + chan->scale_in_x = chan->scale_in_y = 1.0f; + chan->scale_out_x = chan->scale_out_y = 1.0f; chan->limitmin[0] = chan->limitmin[1] = chan->limitmin[2] = -M_PI; chan->limitmax[0] = chan->limitmax[1] = chan->limitmax[2] = M_PI; @@ -490,8 +516,9 @@ bPoseChannel *BKE_pose_channel_active(Object *ob) /* find active */ for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) { - if ((pchan->bone) && (pchan->bone == arm->act_bone) && (pchan->bone->layer & arm->layer)) + if ((pchan->bone) && (pchan->bone == arm->act_bone) && (pchan->bone->layer & arm->layer)) { return pchan; + } } return NULL; @@ -585,7 +612,8 @@ void BKE_pose_copy_data_ex(bPose **dst, &listb, &pchan->constraints, flag, true); // BKE_constraints_copy NULLs listb pchan->constraints = listb; - /* XXX: This is needed for motionpath drawing to work. Dunno why it was setting to null before... */ + /* XXX: This is needed for motionpath drawing to work. + * Dunno why it was setting to null before... */ pchan->mpath = animviz_copy_motionpath(pchan->mpath); } @@ -657,15 +685,17 @@ static bool pose_channel_in_IK_chain(Object *ob, bPoseChannel *pchan, int level) if (con->type == CONSTRAINT_TYPE_KINEMATIC) { bKinematicConstraint *data = con->data; if ((data->rootbone == 0) || (data->rootbone > level)) { - if ((data->flag & CONSTRAINT_IK_AUTO) == 0) + if ((data->flag & CONSTRAINT_IK_AUTO) == 0) { return true; + } } } } for (bone = pchan->bone->childbase.first; bone; bone = bone->next) { pchan = BKE_pose_channel_find_name(ob->pose, bone->name); - if (pchan && pose_channel_in_IK_chain(ob, pchan, level + 1)) + if (pchan && pose_channel_in_IK_chain(ob, pchan, level + 1)) { return true; + } } return false; } @@ -685,8 +715,9 @@ void BKE_pose_channels_hash_make(bPose *pose) bPoseChannel *pchan; pose->chanhash = BLI_ghash_str_new("make_pose_chan gh"); - for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) + for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) { BLI_ghash_insert(pose->chanhash, pchan->name, pchan); + } } } @@ -742,23 +773,27 @@ void BKE_pose_channels_remove(Object *ob, } } - if (cti->flush_constraint_targets) + if (cti->flush_constraint_targets) { cti->flush_constraint_targets(con, &targets, 0); + } } } if (pchan->bbone_prev) { - if (filter_fn(pchan->bbone_prev->name, user_data)) + if (filter_fn(pchan->bbone_prev->name, user_data)) { pchan->bbone_prev = NULL; + } } if (pchan->bbone_next) { - if (filter_fn(pchan->bbone_next->name, user_data)) + if (filter_fn(pchan->bbone_next->name, user_data)) { pchan->bbone_next = NULL; + } } if (pchan->custom_tx) { - if (filter_fn(pchan->custom_tx->name, user_data)) + if (filter_fn(pchan->custom_tx->name, user_data)) { pchan->custom_tx = NULL; + } } } } @@ -793,15 +828,25 @@ void BKE_pose_channel_free_ex(bPoseChannel *pchan, bool do_id_user) /* Cached data, for new draw manager rendering code. */ MEM_SAFE_FREE(pchan->draw_data); - /* Cached B-Bone shape data. */ - BKE_pose_channel_free_bbone_cache(pchan); + /* Cached B-Bone shape and other data. */ + BKE_pose_channel_runtime_free(&pchan->runtime); } -/** Deallocates runtime cache of a pose channel's B-Bone shape. */ -void BKE_pose_channel_free_bbone_cache(bPoseChannel *pchan) +/** Clears the runtime cache of a pose channel without free. */ +void BKE_pose_channel_runtime_reset(bPoseChannel_Runtime *runtime) +{ + memset(runtime, 0, sizeof(*runtime)); +} + +/** Deallocates runtime cache of a pose channel */ +void BKE_pose_channel_runtime_free(bPoseChannel_Runtime *runtime) { - bPoseChannel_Runtime *runtime = &pchan->runtime; + BKE_pose_channel_free_bbone_cache(runtime); +} +/** Deallocates runtime cache of a pose channel's B-Bone shape. */ +void BKE_pose_channel_free_bbone_cache(bPoseChannel_Runtime *runtime) +{ runtime->bbone_segments = 0; MEM_SAFE_FREE(runtime->bbone_rest_mats); MEM_SAFE_FREE(runtime->bbone_pose_mats); @@ -823,8 +868,9 @@ void BKE_pose_channels_free_ex(bPose *pose, bool do_id_user) bPoseChannel *pchan; if (pose->chanbase.first) { - for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) + for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) { BKE_pose_channel_free_ex(pchan, do_id_user); + } BLI_freelistN(&pose->chanbase); } @@ -845,15 +891,17 @@ void BKE_pose_free_data_ex(bPose *pose, bool do_id_user) BKE_pose_channels_free_ex(pose, do_id_user); /* free pose-groups */ - if (pose->agroups.first) + if (pose->agroups.first) { BLI_freelistN(&pose->agroups); + } /* free IK solver state */ BIK_clear_data(pose); /* free IK solver param */ - if (pose->ikparam) + if (pose->ikparam) { MEM_freeN(pose->ikparam); + } } void BKE_pose_free_data(bPose *pose) @@ -955,22 +1003,26 @@ void BKE_pose_update_constraint_flags(bPose *pose) pchan->constflag |= PCHAN_HAS_IK; - if (data->tar == NULL || (data->tar->type == OB_ARMATURE && data->subtarget[0] == 0)) + if (data->tar == NULL || (data->tar->type == OB_ARMATURE && data->subtarget[0] == 0)) { pchan->constflag |= PCHAN_HAS_TARGET; + } /* negative rootbone = recalc rootbone index. used in do_versions */ if (data->rootbone < 0) { data->rootbone = 0; - if (data->flag & CONSTRAINT_IK_TIP) + if (data->flag & CONSTRAINT_IK_TIP) { parchan = pchan; - else + } + else { parchan = pchan->parent; + } while (parchan) { data->rootbone++; - if ((parchan->bone->flag & BONE_CONNECTED) == 0) + if ((parchan->bone->flag & BONE_CONNECTED) == 0) { break; + } parchan = parchan->parent; } } @@ -984,13 +1036,16 @@ void BKE_pose_update_constraint_flags(bPose *pose) /* if we have a valid target, make sure that this will get updated on frame-change * (needed for when there is no anim-data for this pose) */ - if ((data->tar) && (data->tar->type == OB_CURVE)) + if ((data->tar) && (data->tar->type == OB_CURVE)) { pose->flag |= POSE_CONSTRAINTS_TIMEDEPEND; + } } - else if (con->type == CONSTRAINT_TYPE_SPLINEIK) + else if (con->type == CONSTRAINT_TYPE_SPLINEIK) { pchan->constflag |= PCHAN_HAS_SPLINEIK; - else + } + else { pchan->constflag |= PCHAN_HAS_CONST; + } } } pose->flag &= ~POSE_CONSTRAINTS_NEED_UPDATE_FLAGS; @@ -1017,8 +1072,9 @@ void framechange_poses_clear_unkeyed(Main *bmain) /* we only need to do this on objects with a pose */ if ((pose = ob->pose)) { for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) { - if (pchan->bone) + if (pchan->bone) { pchan->bone->flag &= ~BONE_UNKEYED; + } } } } @@ -1063,10 +1119,12 @@ void BKE_pose_remove_group(bPose *pose, bActionGroup *grp, const int index) * - also, make sure that those after this item get corrected */ for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) { - if (pchan->agrp_index == idx) + if (pchan->agrp_index == idx) { pchan->agrp_index = 0; - else if (pchan->agrp_index > idx) + } + else if (pchan->agrp_index > idx) { pchan->agrp_index--; + } } /* now, remove it from the pose */ @@ -1105,8 +1163,9 @@ bool action_has_motion(const bAction *act) /* return on the first F-Curve that has some keyframes/samples defined */ if (act) { for (fcu = act->curves.first; fcu; fcu = fcu->next) { - if (fcu->totvert) + if (fcu->totvert) { return true; + } } } @@ -1166,10 +1225,12 @@ void calc_action_range(const bAction *act, float *start, float *end, short incl_ { FMod_Cycles *fmd = (FMod_Cycles *)fcm->data; - if (fmd->before_mode != FCM_EXTRAPOLATE_NONE) + if (fmd->before_mode != FCM_EXTRAPOLATE_NONE) { min = MINAFRAMEF; - if (fmd->after_mode != FCM_EXTRAPOLATE_NONE) + } + if (fmd->after_mode != FCM_EXTRAPOLATE_NONE) { max = MAXFRAMEF; + } break; } /* TODO: function modifier may need some special limits */ @@ -1187,8 +1248,9 @@ void calc_action_range(const bAction *act, float *start, float *end, short incl_ if (foundvert || foundmod) { /* ensure that action is at least 1 frame long (for NLA strips to have a valid length) */ - if (min == max) + if (min == max) { max += 1.0f; + } *start = min; *end = max; @@ -1210,17 +1272,21 @@ short action_get_item_transforms(bAction *act, Object *ob, bPoseChannel *pchan, short flags = 0; /* build PointerRNA from provided data to obtain the paths to use */ - if (pchan) + if (pchan) { RNA_pointer_create((ID *)ob, &RNA_PoseBone, pchan, &ptr); - else if (ob) + } + else if (ob) { RNA_id_pointer_create((ID *)ob, &ptr); - else + } + else { return 0; + } /* get the basic path to the properties of interest */ basePath = RNA_path_from_ID_to_struct(&ptr); - if (basePath == NULL) + if (basePath == NULL) { return 0; + } /* search F-Curves for the given properties * - we cannot use the groups, since they may not be grouped in that way... @@ -1228,13 +1294,16 @@ short action_get_item_transforms(bAction *act, Object *ob, bPoseChannel *pchan, for (fcu = act->curves.first; fcu; fcu = fcu->next) { const char *bPtr = NULL, *pPtr = NULL; - /* if enough flags have been found, we can stop checking unless we're also getting the curves */ - if ((flags == ACT_TRANS_ALL) && (curves == NULL)) + /* If enough flags have been found, + * we can stop checking unless we're also getting the curves. */ + if ((flags == ACT_TRANS_ALL) && (curves == NULL)) { break; + } /* just in case... */ - if (fcu->rna_path == NULL) + if (fcu->rna_path == NULL) { continue; + } /* step 1: check for matching base path */ bPtr = strstr(fcu->rna_path, basePath); @@ -1257,8 +1326,9 @@ short action_get_item_transforms(bAction *act, Object *ob, bPoseChannel *pchan, if (pPtr) { flags |= ACT_TRANS_LOC; - if (curves) + if (curves) { BLI_addtail(curves, BLI_genericNodeN(fcu)); + } continue; } } @@ -1268,8 +1338,9 @@ short action_get_item_transforms(bAction *act, Object *ob, bPoseChannel *pchan, if (pPtr) { flags |= ACT_TRANS_SCALE; - if (curves) + if (curves) { BLI_addtail(curves, BLI_genericNodeN(fcu)); + } continue; } } @@ -1279,8 +1350,9 @@ short action_get_item_transforms(bAction *act, Object *ob, bPoseChannel *pchan, if (pPtr) { flags |= ACT_TRANS_ROT; - if (curves) + if (curves) { BLI_addtail(curves, BLI_genericNodeN(fcu)); + } continue; } } @@ -1291,8 +1363,9 @@ short action_get_item_transforms(bAction *act, Object *ob, bPoseChannel *pchan, if (pPtr) { flags |= ACT_TRANS_BBONE; - if (curves) + if (curves) { BLI_addtail(curves, BLI_genericNodeN(fcu)); + } continue; } } @@ -1305,8 +1378,9 @@ short action_get_item_transforms(bAction *act, Object *ob, bPoseChannel *pchan, if (pPtr) { flags |= ACT_TRANS_PROP; - if (curves) + if (curves) { BLI_addtail(curves, BLI_genericNodeN(fcu)); + } continue; } } @@ -1327,8 +1401,9 @@ void BKE_pose_rest(bPose *pose) { bPoseChannel *pchan; - if (!pose) + if (!pose) { return; + } memset(pose->stride_offset, 0, sizeof(pose->stride_offset)); memset(pose->cyclic_offset, 0, sizeof(pose->cyclic_offset)); @@ -1341,10 +1416,11 @@ void BKE_pose_rest(bPose *pose) pchan->size[0] = pchan->size[1] = pchan->size[2] = 1.0f; pchan->roll1 = pchan->roll2 = 0.0f; - pchan->curveInX = pchan->curveInY = 0.0f; - pchan->curveOutX = pchan->curveOutY = 0.0f; + pchan->curve_in_x = pchan->curve_in_y = 0.0f; + pchan->curve_out_x = pchan->curve_out_y = 0.0f; pchan->ease1 = pchan->ease2 = 0.0f; - pchan->scaleIn = pchan->scaleOut = 1.0f; + pchan->scale_in_x = pchan->scale_in_y = 1.0f; + pchan->scale_out_x = pchan->scale_out_y = 1.0f; pchan->flag &= ~(POSE_LOC | POSE_ROT | POSE_SIZE | POSE_BBONE_SHAPE); } @@ -1366,14 +1442,16 @@ void BKE_pose_copyesult_pchan_result(bPoseChannel *pchanto, const bPoseChannel * pchanto->roll1 = pchanfrom->roll1; pchanto->roll2 = pchanfrom->roll2; - pchanto->curveInX = pchanfrom->curveInX; - pchanto->curveInY = pchanfrom->curveInY; - pchanto->curveOutX = pchanfrom->curveOutX; - pchanto->curveOutY = pchanfrom->curveOutY; + pchanto->curve_in_x = pchanfrom->curve_in_x; + pchanto->curve_in_y = pchanfrom->curve_in_y; + pchanto->curve_out_x = pchanfrom->curve_out_x; + pchanto->curve_out_y = pchanfrom->curve_out_y; pchanto->ease1 = pchanfrom->ease1; pchanto->ease2 = pchanfrom->ease2; - pchanto->scaleIn = pchanfrom->scaleIn; - pchanto->scaleOut = pchanfrom->scaleOut; + pchanto->scale_in_x = pchanfrom->scale_in_x; + pchanto->scale_in_y = pchanfrom->scale_in_y; + pchanto->scale_out_x = pchanfrom->scale_out_x; + pchanto->scale_out_y = pchanfrom->scale_out_y; pchanto->rotmode = pchanfrom->rotmode; pchanto->flag = pchanfrom->flag; @@ -1461,14 +1539,12 @@ void what_does_obaction( } BLI_strncpy(workob->parsubstr, ob->parsubstr, sizeof(workob->parsubstr)); - BLI_strncpy( - workob->id.name, - "OB<ConstrWorkOb>", - sizeof( - workob->id - .name)); /* we don't use real object name, otherwise RNA screws with the real thing */ - - /* if we're given a group to use, it's likely to be more efficient (though a bit more dangerous) */ + + /* we don't use real object name, otherwise RNA screws with the real thing */ + BLI_strncpy(workob->id.name, "OB<ConstrWorkOb>", sizeof(workob->id.name)); + + /* If we're given a group to use, it's likely to be more efficient + * (though a bit more dangerous). */ if (agrp) { /* specifically evaluate this group only */ PointerRNA id_ptr; diff --git a/source/blender/blenkernel/intern/anim.c b/source/blender/blenkernel/intern/anim.c index 0e7caca9433..6b8f8e5303e 100644 --- a/source/blender/blenkernel/intern/anim.c +++ b/source/blender/blenkernel/intern/anim.c @@ -67,8 +67,9 @@ static CLG_LogRef LOG = {"bke.anim"}; void animviz_settings_init(bAnimVizSettings *avs) { /* sanity check */ - if (avs == NULL) + if (avs == NULL) { return; + } /* path settings */ avs->path_bc = avs->path_ac = 10; @@ -89,12 +90,14 @@ void animviz_settings_init(bAnimVizSettings *avs) void animviz_free_motionpath_cache(bMotionPath *mpath) { /* sanity check */ - if (mpath == NULL) + if (mpath == NULL) { return; + } /* free the path if necessary */ - if (mpath->points) + if (mpath->points) { MEM_freeN(mpath->points); + } GPU_VERTBUF_DISCARD_SAFE(mpath->points_vbo); GPU_BATCH_DISCARD_SAFE(mpath->batch_line); @@ -111,8 +114,9 @@ void animviz_free_motionpath_cache(bMotionPath *mpath) void animviz_free_motionpath(bMotionPath *mpath) { /* sanity check */ - if (mpath == NULL) + if (mpath == NULL) { return; + } /* free the cache first */ animviz_free_motionpath_cache(mpath); @@ -128,8 +132,9 @@ bMotionPath *animviz_copy_motionpath(const bMotionPath *mpath_src) { bMotionPath *mpath_dst; - if (mpath_src == NULL) + if (mpath_src == NULL) { return NULL; + } mpath_dst = MEM_dupallocN(mpath_src); mpath_dst->points = MEM_dupallocN(mpath_src->points); @@ -161,8 +166,9 @@ bMotionPath *animviz_verify_motionpaths(ReportList *reports, bMotionPath *mpath, **dst; /* sanity checks */ - if (ELEM(NULL, scene, ob)) + if (ELEM(NULL, scene, ob)) { return NULL; + } /* get destination data */ if (pchan) { @@ -196,7 +202,8 @@ bMotionPath *animviz_verify_motionpaths(ReportList *reports, mpath = *dst; - /* path is "valid" if length is valid, but must also be of the same length as is being requested */ + /* Path is "valid" if length is valid, + * but must also be of the same length as is being requested. */ if ((mpath->start_frame != mpath->end_frame) && (mpath->length > 0)) { /* outer check ensures that we have some curve data for this path */ if (mpath->length == expected_length) { @@ -221,10 +228,12 @@ bMotionPath *animviz_verify_motionpaths(ReportList *reports, mpath->length = mpath->end_frame - mpath->start_frame; - if (avs->path_bakeflag & MOTIONPATH_BAKE_HEADS) + if (avs->path_bakeflag & MOTIONPATH_BAKE_HEADS) { mpath->flag |= MOTIONPATH_FLAG_BHEAD; - else + } + else { mpath->flag &= ~MOTIONPATH_FLAG_BHEAD; + } /* set default custom values */ mpath->color[0] = 1.0; /* Red */ @@ -253,8 +262,9 @@ bMotionPath *animviz_verify_motionpaths(ReportList *reports, */ void free_path(Path *path) { - if (path->data) + if (path->data) { MEM_freeN(path->data); + } MEM_freeN(path); } @@ -279,8 +289,9 @@ void calc_curvepath(Object *ob, ListBase *nurbs) return; } - if (ob->runtime.curve_cache->path) + if (ob->runtime.curve_cache->path) { free_path(ob->runtime.curve_cache->path); + } ob->runtime.curve_cache->path = NULL; /* weak! can only use first curve */ @@ -299,7 +310,8 @@ void calc_curvepath(Object *ob, ListBase *nurbs) tot = cycl ? bl->nr : bl->nr - 1; path->len = tot + 1; - /* exception: vector handle paths and polygon paths should be subdivided at least a factor resolu */ + /* Exception: vector handle paths and polygon paths should be subdivided + * at least a factor resolution. */ if (path->len < nu->resolu * SEGMENTSU(nu)) { path->len = nu->resolu * SEGMENTSU(nu); } @@ -312,10 +324,12 @@ void calc_curvepath(Object *ob, ListBase *nurbs) *fp = 0.0f; for (a = 0; a < tot; a++) { fp++; - if (cycl && a == tot - 1) + if (cycl && a == tot - 1) { sub_v3_v3v3(xyz, bevpfirst->vec, bevp->vec); - else + } + else { sub_v3_v3v3(xyz, (bevp + 1)->vec, bevp->vec); + } *fp = *(fp - 1) + len_v3(xyz); bevp++; @@ -346,8 +360,9 @@ void calc_curvepath(Object *ob, ListBase *nurbs) if (LIKELY(tot > 0)) { while ((fp < maxdist) && (d >= *fp)) { fp++; - if (bevp < bevplast) + if (bevp < bevplast) { bevp++; + } bevpn = bevp + 1; if (UNLIKELY(bevpn > bevplast)) { bevpn = cycl ? bevpfirst : bevplast; @@ -381,10 +396,12 @@ static int interval_test(const int min, const int max, int p1, const int cycl) p1 = mod_i(p1 - min, (max - min + 1)) + min; } else { - if (p1 < min) + if (p1 < min) { p1 = min; - else if (p1 > max) + } + else if (p1 > max) { p1 = max; + } } return p1; } @@ -414,8 +431,9 @@ int where_on_path(Object *ob, int cycl = 0, s0, s1, s2, s3; ListBase *nurbs; - if (ob == NULL || ob->type != OB_CURVE) + if (ob == NULL || ob->type != OB_CURVE) { return 0; + } cu = ob->data; if (ob->runtime.curve_cache == NULL || ob->runtime.curve_cache->path == NULL || ob->runtime.curve_cache->path->data == NULL) { @@ -427,12 +445,15 @@ int where_on_path(Object *ob, /* test for cyclic */ bl = ob->runtime.curve_cache->bev.first; - if (!bl) + if (!bl) { return 0; - if (!bl->nr) + } + if (!bl->nr) { return 0; - if (bl->poly > -1) + } + if (bl->poly > -1) { cycl = 1; + } /* values below zero for non-cyclic curves give strange results */ BLI_assert(cycl || ctime >= 0.0f); @@ -459,7 +480,7 @@ int where_on_path(Object *ob, * which used to temporary set CU_FOLLOW flag for the curve and no * longer does it (because of threading issues of such a thing. */ - //if (cu->flag & CU_FOLLOW) { + // if (cu->flag & CU_FOLLOW) { key_curve_tangent_weights(1.0f - fac, data, KEY_BSPLINE); @@ -470,19 +491,24 @@ int where_on_path(Object *ob, //} nurbs = BKE_curve_editNurbs_get(cu); - if (!nurbs) + if (!nurbs) { nurbs = &cu->nurb; + } nu = nurbs->first; /* make sure that first and last frame are included in the vectors here */ - if (nu->type == CU_POLY) + if (nu->type == CU_POLY) { key_curve_position_weights(1.0f - fac, data, KEY_LINEAR); - else if (nu->type == CU_BEZIER) + } + else if (nu->type == CU_BEZIER) { key_curve_position_weights(1.0f - fac, data, KEY_LINEAR); - else if (s0 == s1 || p2 == p3) + } + else if (s0 == s1 || p2 == p3) { key_curve_position_weights(1.0f - fac, data, KEY_CARDINAL); - else + } + else { key_curve_position_weights(1.0f - fac, data, KEY_BSPLINE); + } vec[0] = data[0] * p0->vec[0] + data[1] * p1->vec[0] + data[2] * p2->vec[0] + data[3] * p3->vec[0]; /* X */ @@ -497,31 +523,39 @@ int where_on_path(Object *ob, float totfac, q1[4], q2[4]; totfac = data[0] + data[3]; - if (totfac > FLT_EPSILON) + if (totfac > FLT_EPSILON) { interp_qt_qtqt(q1, p0->quat, p3->quat, data[3] / totfac); - else + } + else { copy_qt_qt(q1, p1->quat); + } totfac = data[1] + data[2]; - if (totfac > FLT_EPSILON) + if (totfac > FLT_EPSILON) { interp_qt_qtqt(q2, p1->quat, p2->quat, data[2] / totfac); - else + } + else { copy_qt_qt(q2, p3->quat); + } totfac = data[0] + data[1] + data[2] + data[3]; - if (totfac > FLT_EPSILON) + if (totfac > FLT_EPSILON) { interp_qt_qtqt(quat, q1, q2, (data[1] + data[2]) / totfac); - else + } + else { copy_qt_qt(quat, q2); + } } - if (radius) + if (radius) { *radius = data[0] * p0->radius + data[1] * p1->radius + data[2] * p2->radius + data[3] * p3->radius; + } - if (weight) + if (weight) { *weight = data[0] * p0->weight + data[1] * p1->weight + data[2] * p2->weight + data[3] * p3->weight; + } return 1; } diff --git a/source/blender/blenkernel/intern/anim_sys.c b/source/blender/blenkernel/intern/anim_sys.c index 75244a8ba8a..cc5cd3b03ae 100644 --- a/source/blender/blenkernel/intern/anim_sys.c +++ b/source/blender/blenkernel/intern/anim_sys.c @@ -120,8 +120,9 @@ bool id_type_can_have_animdata(const short id_type) bool id_can_have_animdata(const ID *id) { /* sanity check */ - if (id == NULL) + if (id == NULL) { return false; + } return id_type_can_have_animdata(GS(id->name)); } @@ -140,8 +141,9 @@ AnimData *BKE_animdata_from_id(ID *id) IdAdtTemplate *iat = (IdAdtTemplate *)id; return iat->adt; } - else + else { return NULL; + } } /* Add AnimData to the given ID-block. In order for this to work, we assume that @@ -170,13 +172,15 @@ AnimData *BKE_animdata_add_id(ID *id) return iat->adt; } - else + else { return NULL; + } } /* Action Setter --------------------------------------- */ -/* Called when user tries to change the active action of an AnimData block (via RNA, Outliner, etc.) */ +/** Called when user tries to change the active action of an AnimData block + * (via RNA, Outliner, etc.) */ bool BKE_animdata_set_action(ReportList *reports, ID *id, bAction *act) { AnimData *adt = BKE_animdata_from_id(id); @@ -198,8 +202,9 @@ bool BKE_animdata_set_action(ReportList *reports, ID *id, bAction *act) } /* manage usercount for current action */ - if (adt->action) + if (adt->action) { id_us_min((ID *)adt->action); + } /* assume that AnimData's action can in fact be edited... */ if (act) { @@ -247,11 +252,13 @@ void BKE_animdata_free(ID *id, const bool do_id_user) if (adt) { if (do_id_user) { /* unlink action (don't free, as it's in its own list) */ - if (adt->action) + if (adt->action) { id_us_min(&adt->action->id); + } /* same goes for the temporarily displaced action */ - if (adt->tmpact) + if (adt->tmpact) { id_us_min(&adt->tmpact->id); + } } /* free nla data */ @@ -277,7 +284,8 @@ void BKE_animdata_free(ID *id, const bool do_id_user) /** * Make a copy of the given AnimData - to be used when copying datablocks. - * \param flag: Control ID pointers management, see LIB_ID_CREATE_.../LIB_ID_COPY_... flags in BKE_library.h + * \param flag: Control ID pointers management, + * see LIB_ID_CREATE_.../LIB_ID_COPY_... flags in BKE_library.h * \return The copied animdata. */ AnimData *BKE_animdata_copy(Main *bmain, AnimData *adt, const int flag) @@ -288,8 +296,9 @@ AnimData *BKE_animdata_copy(Main *bmain, AnimData *adt, const int flag) const bool do_id_user = (flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0; /* sanity check before duplicating struct */ - if (adt == NULL) + if (adt == NULL) { return NULL; + } dadt = MEM_dupallocN(adt); /* make a copy of action - at worst, user has to delete copies... */ @@ -318,15 +327,17 @@ AnimData *BKE_animdata_copy(Main *bmain, AnimData *adt, const int flag) } /** - * \param flag: Control ID pointers management, see LIB_ID_CREATE_.../LIB_ID_COPY_... flags in BKE_library.h + * \param flag: Control ID pointers management, + * see LIB_ID_CREATE_.../LIB_ID_COPY_... flags in BKE_library.h * \return true is succesfully copied. */ bool BKE_animdata_copy_id(Main *bmain, ID *id_to, ID *id_from, const int flag) { AnimData *adt; - if ((id_to && id_from) && (GS(id_to->name) != GS(id_from->name))) + if ((id_to && id_from) && (GS(id_to->name) != GS(id_from->name))) { return false; + } BKE_animdata_free(id_to, (flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0); @@ -364,8 +375,9 @@ void BKE_animdata_merge_copy( AnimData *dst = BKE_animdata_from_id(dst_id); /* sanity checks */ - if (ELEM(NULL, dst, src)) + if (ELEM(NULL, dst, src)) { return; + } // TODO: we must unset all "tweakmode" flags if ((src->flag & ADT_NLA_EDIT_ON) || (dst->flag & ADT_NLA_EDIT_ON)) { @@ -501,10 +513,12 @@ void action_move_fcurves_by_basepath(bAction *srcAct, bAction *dstAct, const cha /* perform the migration now */ action_groups_remove_channel(srcAct, fcu); - if (agrp) + if (agrp) { action_groups_add_channel(dstAct, agrp, fcu); - else + } + else { BLI_addtail(&dstAct->curves, fcu); + } } } @@ -520,10 +534,12 @@ void action_move_fcurves_by_basepath(bAction *srcAct, bAction *dstAct, const cha /* if group is empty and tagged, then we can remove as this operation * moved out all the channels that were formerly here */ - if (BLI_listbase_is_empty(&agrp->channels)) + if (BLI_listbase_is_empty(&agrp->channels)) { BLI_freelinkN(&srcAct->groups, agrp); - else + } + else { agrp->flag &= ~AGRP_TEMP; + } } } } @@ -540,8 +556,9 @@ void BKE_animdata_separate_by_basepath(Main *bmain, ID *srcID, ID *dstID, ListBa /* sanity checks */ if (ELEM(NULL, srcID, dstID)) { - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { CLOG_ERROR(&LOG, "no source or destination ID to separate AnimData with"); + } return; } @@ -550,14 +567,16 @@ void BKE_animdata_separate_by_basepath(Main *bmain, ID *srcID, ID *dstID, ListBa dstAdt = BKE_animdata_add_id(dstID); if (ELEM(NULL, srcAdt, dstAdt)) { - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { CLOG_ERROR(&LOG, "no AnimData for this pair of ID's"); + } return; } /* active action */ if (srcAdt->action) { - /* set up an action if necessary, and name it in a similar way so that it can be easily found again */ + /* Set up an action if necessary, + * and name it in a similar way so that it can be easily found again. */ if (dstAdt->action == NULL) { dstAdt->action = BKE_action_add(bmain, srcAdt->action->id.name + 2); } @@ -614,7 +633,8 @@ void BKE_animdata_separate_by_basepath(Main *bmain, ID *srcID, ID *dstID, ListBa * they will get picked up by the dependency system. * * \param C: Context pointer - for getting active data - * \param[in,out] ptr RNA pointer for property's datablock. May be modified as result of path remapping. + * \param[in,out] ptr: RNA pointer for property's datablock. + * May be modified as result of path remapping. * \param prop: RNA definition of property to add for * \return MEM_alloc'd string representing the path to the property from the given #PointerRNA */ @@ -655,7 +675,8 @@ char *BKE_animdata_driver_path_hack(bContext *C, /* Path Validation -------------------------------------------- */ -/* Check if a given RNA Path is valid, by tracing it from the given ID, and seeing if we can resolve it */ +/* Check if a given RNA Path is valid, by tracing it from the given ID, + * and seeing if we can resolve it. */ static bool check_rna_path_is_valid(ID *owner_id, const char *path) { PointerRNA id_ptr, ptr; @@ -751,7 +772,8 @@ static bool fcurves_path_rename_fix(ID *owner_id, fcu->rna_path = rna_path_rename_fix( owner_id, prefix, oldKey, newKey, fcu->rna_path, verify_paths); /* if path changed and the F-Curve is grouped, check if its group also needs renaming - * (i.e. F-Curve is first of a bone's F-Curves; hence renaming this should also trigger rename) */ + * (i.e. F-Curve is first of a bone's F-Curves; + * hence renaming this should also trigger rename) */ if (fcu->rna_path != old_path) { bActionGroup *agrp = fcu->grp; is_changed = true; @@ -868,8 +890,9 @@ char *BKE_animsys_fix_rna_path_rename(ID *owner_id, /* if no action, no need to proceed */ if (ELEM(NULL, owner_id, old_path)) { - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { CLOG_WARN(&LOG, "early abort"); + } return old_path; } @@ -892,11 +915,13 @@ char *BKE_animsys_fix_rna_path_rename(ID *owner_id, } /* fix given path */ - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("%s | %s | oldpath = %p ", oldN, newN, old_path); + } result = rna_path_rename_fix(owner_id, prefix, oldN, newN, old_path, verify_paths); - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("path rename result = %p\n", result); + } /* free the temp names */ MEM_freeN(oldN); @@ -926,8 +951,9 @@ void BKE_action_fix_paths_rename(ID *owner_id, char *oldN, *newN; /* if no action, no need to proceed */ - if (ELEM(NULL, owner_id, act)) + if (ELEM(NULL, owner_id, act)) { return; + } /* Name sanitation logic - copied from BKE_animdata_fix_paths_rename() */ if ((oldName != NULL) && (newName != NULL)) { @@ -1031,8 +1057,9 @@ static bool fcurves_path_remove_fix(const char *prefix, ListBase *curves) { FCurve *fcu, *fcn; bool any_removed = false; - if (!prefix) + if (!prefix) { return any_removed; + } /* we need to check every curve... */ for (fcu = curves->first; fcu; fcu = fcn) { @@ -1394,8 +1421,9 @@ KS_Path *BKE_keyingset_find_path(KeyingSet *ks, KS_Path *ksp; /* sanity checks */ - if (ELEM(NULL, ks, rna_path, id)) + if (ELEM(NULL, ks, rna_path, id)) { return NULL; + } /* loop over paths in the current KeyingSet, finding the first one where all settings match * (i.e. the first one where none of the checks fail and equal 0) @@ -1404,16 +1432,19 @@ KS_Path *BKE_keyingset_find_path(KeyingSet *ks, short eq_id = 1, eq_path = 1, eq_index = 1, eq_group = 1; /* id */ - if (id != ksp->id) + if (id != ksp->id) { eq_id = 0; + } /* path */ - if ((ksp->rna_path == NULL) || !STREQ(rna_path, ksp->rna_path)) + if ((ksp->rna_path == NULL) || !STREQ(rna_path, ksp->rna_path)) { eq_path = 0; + } /* index - need to compare whole-array setting too... */ - if (ksp->array_index != array_index) + if (ksp->array_index != array_index) { eq_index = 0; + } /* group */ if (group_name) { @@ -1421,8 +1452,9 @@ KS_Path *BKE_keyingset_find_path(KeyingSet *ks, } /* if all aspects are ok, return */ - if (eq_id && eq_path && eq_index && eq_group) + if (eq_id && eq_path && eq_index && eq_group) { return ksp; + } } /* none found */ @@ -1431,7 +1463,8 @@ KS_Path *BKE_keyingset_find_path(KeyingSet *ks, /* Defining Tools --------------------------- */ -/* Used to create a new 'custom' KeyingSet for the user, that will be automatically added to the stack */ +/* Used to create a new 'custom' KeyingSet for the user, + * that will be automatically added to the stack */ KeyingSet *BKE_keyingset_add( ListBase *list, const char idname[], const char name[], short flag, short keyingflag) { @@ -1446,8 +1479,8 @@ KeyingSet *BKE_keyingset_add( ks->flag = flag; ks->keyingflag = keyingflag; - ks->keyingoverride = - keyingflag; /* NOTE: assume that if one is set one way, the other should be too, so that it'll work */ + /* NOTE: assume that if one is set one way, the other should be too, so that it'll work */ + ks->keyingoverride = keyingflag; /* add KeyingSet to list */ BLI_addtail(list, ks); @@ -1490,8 +1523,9 @@ KS_Path *BKE_keyingset_add_path(KeyingSet *ks, /* don't add if there is already a matching KS_Path in the KeyingSet */ if (BKE_keyingset_find_path(ks, id, group_name, rna_path, array_index, groupmode)) { - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { CLOG_ERROR(&LOG, "destination already exists in Keying Set"); + } return NULL; } @@ -1500,14 +1534,17 @@ KS_Path *BKE_keyingset_add_path(KeyingSet *ks, /* just store absolute info */ ksp->id = id; - if (group_name) + if (group_name) { BLI_strncpy(ksp->group, group_name, sizeof(ksp->group)); - else + } + else { ksp->group[0] = '\0'; + } /* store additional info for relative paths (just in case user makes the set relative) */ - if (id) + if (id) { ksp->idtype = GS(id->name); + } /* just copy path info */ /* TODO: should array index be checked too? */ @@ -1529,12 +1566,14 @@ KS_Path *BKE_keyingset_add_path(KeyingSet *ks, void BKE_keyingset_free_path(KeyingSet *ks, KS_Path *ksp) { /* sanity check */ - if (ELEM(NULL, ks, ksp)) + if (ELEM(NULL, ks, ksp)) { return; + } /* free RNA-path info */ - if (ksp->rna_path) + if (ksp->rna_path) { MEM_freeN(ksp->rna_path); + } /* free path itself */ BLI_freelinkN(&ks->paths, ksp); @@ -1551,8 +1590,9 @@ void BKE_keyingsets_copy(ListBase *newlist, const ListBase *list) for (ksn = newlist->first; ksn; ksn = ksn->next) { BLI_duplicatelist(&ksn->paths, &ksn->paths); - for (kspn = ksn->paths.first; kspn; kspn = kspn->next) + for (kspn = ksn->paths.first; kspn; kspn = kspn->next) { kspn->rna_path = MEM_dupallocN(kspn->rna_path); + } } } @@ -1564,8 +1604,9 @@ void BKE_keyingset_free(KeyingSet *ks) KS_Path *ksp, *kspn; /* sanity check */ - if (ks == NULL) + if (ks == NULL) { return; + } /* free each path as we go to avoid looping twice */ for (ksp = ks->paths.first; ksp; ksp = kspn) { @@ -1580,8 +1621,9 @@ void BKE_keyingsets_free(ListBase *list) KeyingSet *ks, *ksn; /* sanity check */ - if (list == NULL) + if (list == NULL) { return; + } /* loop over KeyingSets freeing them * - BKE_keyingset_free() doesn't free the set itself, but it frees its sub-data @@ -1790,31 +1832,50 @@ bool BKE_animsys_execute_fcurve(PointerRNA *ptr, FCurve *fcu, float curval) return ok; } +static bool animsys_construct_orig_pointer_rna(const PointerRNA *ptr, PointerRNA *ptr_orig) +{ + *ptr_orig = *ptr; + /* NOTE: nlastrip_evaluate_controls() creates PointerRNA with ID of NULL. Technically, this is + * not a valid pointer, but there are exceptions in various places of this file which handles + * such pointers. + * We do special trickery here as well, to quickly go from evaluated to original NlaStrip. */ + if (ptr->id.data == NULL) { + if (ptr->type != &RNA_NlaStrip) { + return false; + } + NlaStrip *strip = ((NlaStrip *)ptr_orig->data); + if (strip->orig_strip == NULL) { + return false; + } + ptr_orig->data = strip->orig_strip; + } + else { + ptr_orig->id.data = ((ID *)ptr_orig->id.data)->orig_id; + ptr_orig->data = ptr_orig->id.data; + } + return true; +} + static void animsys_write_orig_anim_rna(PointerRNA *ptr, const char *rna_path, int array_index, float value) { - /* Pointer is expected to be an ID pointer, if it's not -- we are doomed. - * - * NOTE: It is possible to have animation data on NLA strip, see T57360. - * TODO(sergey): Find solution for those cases. - */ - if (ptr->id.data == NULL) { + PointerRNA ptr_orig; + if (!animsys_construct_orig_pointer_rna(ptr, &ptr_orig)) { return; } - PointerRNA orig_ptr = *ptr; - orig_ptr.id.data = ((ID *)orig_ptr.id.data)->orig_id; - orig_ptr.data = orig_ptr.id.data; PathResolvedRNA orig_anim_rna; - /* TODO(sergey): Is there a faster way to get anim_rna of original ID? */ - if (animsys_store_rna_setting(&orig_ptr, rna_path, array_index, &orig_anim_rna)) { + /* TODO(sergey): Should be possible to cache resolved path in dependency graph somehow. */ + if (animsys_store_rna_setting(&ptr_orig, rna_path, array_index, &orig_anim_rna)) { animsys_write_rna_setting(&orig_anim_rna, value); } } -/* Evaluate all the F-Curves in the given list - * This performs a set of standard checks. If extra checks are required, separate code should be used +/** + * Evaluate all the F-Curves in the given list + * This performs a set of standard checks. If extra checks are required, + * separate code should be used. */ static void animsys_evaluate_fcurves(Depsgraph *depsgraph, PointerRNA *ptr, @@ -1864,9 +1925,8 @@ static void animsys_evaluate_drivers(PointerRNA *ptr, AnimData *adt, float ctime /* XXX driver recalc flag is not set yet by depsgraph! */ if ((driver) && !(driver->flag & DRIVER_FLAG_INVALID)) { /* evaluate this using values set already in other places - * NOTE: for 'layering' option later on, we should check if we should remove old value before adding - * new to only be done when drivers only changed */ - + * NOTE: for 'layering' option later on, we should check if we should remove old value + * before adding new to only be done when drivers only changed. */ PathResolvedRNA anim_rna; if (animsys_store_rna_setting(ptr, fcu->rna_path, fcu->array_index, &anim_rna)) { const float curval = calculate_fcurve(&anim_rna, fcu, ctime); @@ -1874,8 +1934,9 @@ static void animsys_evaluate_drivers(PointerRNA *ptr, AnimData *adt, float ctime } /* set error-flag if evaluation failed */ - if (ok == 0) + if (ok == 0) { driver->flag |= DRIVER_FLAG_INVALID; + } } } } @@ -1893,14 +1954,17 @@ static void action_idcode_patch_check(ID *id, bAction *act) int idcode = 0; /* just in case */ - if (ELEM(NULL, id, act)) + if (ELEM(NULL, id, act)) { return; - else + } + else { idcode = GS(id->name); + } /* the actual checks... hopefully not too much of a performance hit in the long run... */ if (act->idroot == 0) { - /* use the current root if not set already (i.e. newly created actions and actions from 2.50-2.57 builds) + /* use the current root if not set already + * (i.e. newly created actions and actions from 2.50-2.57 builds). * - this has problems if there are 2 users, and the first one encountered is the invalid one * in which case, the user will need to manually fix this (?) */ @@ -1927,14 +1991,16 @@ void animsys_evaluate_action_group(PointerRNA *ptr, bAction *act, bActionGroup * FCurve *fcu; /* check if mapper is appropriate for use here (we set to NULL if it's inappropriate) */ - if (ELEM(NULL, act, agrp)) + if (ELEM(NULL, act, agrp)) { return; + } action_idcode_patch_check(ptr->id.data, act); /* if group is muted, don't evaluated any of the F-Curve */ - if (agrp->flag & AGRP_MUTED) + if (agrp->flag & AGRP_MUTED) { return; + } /* calculate then execute each curve */ for (fcu = agrp->channels.first; (fcu) && (fcu->grp == agrp); fcu = fcu->next) { @@ -1956,8 +2022,9 @@ static void animsys_evaluate_action_ex(Depsgraph *depsgraph, float ctime) { /* check if mapper is appropriate for use here (we set to NULL if it's inappropriate) */ - if (act == NULL) + if (act == NULL) { return; + } action_idcode_patch_check(ptr->id.data, act); @@ -2013,8 +2080,9 @@ static void nlastrip_evaluate_controls(Depsgraph *depsgraph, NlaStrip *strip, fl * - we do this after the F-Curves have been evaluated to override the effects of those * in case the override has been turned off. */ - if ((strip->flag & NLASTRIP_FLAG_USR_INFLUENCE) == 0) + if ((strip->flag & NLASTRIP_FLAG_USR_INFLUENCE) == 0) { strip->influence = nlastrip_get_influence(strip, ctime); + } /* Bypass evaluation time computation if time mapping is disabled. */ if ((strip->flag & NLASTRIP_FLAG_NO_TIME_MAP) != 0) { @@ -2022,16 +2090,18 @@ static void nlastrip_evaluate_controls(Depsgraph *depsgraph, NlaStrip *strip, fl return; } - if ((strip->flag & NLASTRIP_FLAG_USR_TIME) == 0) + if ((strip->flag & NLASTRIP_FLAG_USR_TIME) == 0) { strip->strip_time = nlastrip_get_frame(strip, ctime, NLATIME_CONVERT_EVAL); + } - /* if user can control the evaluation time (using F-Curves), consider the option which allows this time to be clamped - * to lie within extents of the action-clip, so that a steady changing rate of progress through several cycles of the clip - * can be achieved easily + /* if user can control the evaluation time (using F-Curves), consider the option which allows + * this time to be clamped to lie within extents of the action-clip, so that a steady changing + * rate of progress through several cycles of the clip can be achieved easily. */ /* NOTE: if we add any more of these special cases, we better group them up nicely... */ - if ((strip->flag & NLASTRIP_FLAG_USR_TIME) && (strip->flag & NLASTRIP_FLAG_USR_TIME_CYCLIC)) + if ((strip->flag & NLASTRIP_FLAG_USR_TIME) && (strip->flag & NLASTRIP_FLAG_USR_TIME_CYCLIC)) { strip->strip_time = fmod(strip->strip_time - strip->actstart, strip->actend - strip->actstart); + } } /* gets the strip active at the current time for a list of strips for evaluation purposes */ @@ -2057,8 +2127,9 @@ NlaEvalStrip *nlastrips_ctime_get_strip( if (ctime < strip->start) { if (strip == strips->first) { /* before first strip - only try to use it if it extends backwards in time too */ - if (strip->extendmode == NLASTRIP_EXTEND_HOLD) + if (strip->extendmode == NLASTRIP_EXTEND_HOLD) { estrip = strip; + } /* side is 'before' regardless of whether there's a useful strip */ side = NES_TIME_BEFORE; @@ -2071,8 +2142,9 @@ NlaEvalStrip *nlastrips_ctime_get_strip( */ strip = strip->prev; - if (strip->extendmode != NLASTRIP_EXTEND_NOTHING) + if (strip->extendmode != NLASTRIP_EXTEND_NOTHING) { estrip = strip; + } side = NES_TIME_AFTER; } break; @@ -2082,8 +2154,9 @@ NlaEvalStrip *nlastrips_ctime_get_strip( if (ctime > strip->end) { /* only if this is the last strip should we do anything, and only if that is being held */ if (strip == strips->last) { - if (strip->extendmode != NLASTRIP_EXTEND_NOTHING) + if (strip->extendmode != NLASTRIP_EXTEND_NOTHING) { estrip = strip; + } side = NES_TIME_AFTER; break; @@ -2096,8 +2169,9 @@ NlaEvalStrip *nlastrips_ctime_get_strip( /* check if a valid strip was found * - must not be muted (i.e. will have contribution */ - if ((estrip == NULL) || (estrip->flag & NLASTRIP_FLAG_MUTED)) + if ((estrip == NULL) || (estrip->flag & NLASTRIP_FLAG_MUTED)) { return NULL; + } /* if ctime was not within the boundaries of the strip, clamp! */ switch (side) { @@ -2113,10 +2187,12 @@ NlaEvalStrip *nlastrips_ctime_get_strip( * - skip if no influence (i.e. same effect as muting the strip) * - negative influence is not supported yet... how would that be defined? */ - /* TODO: this sounds a bit hacky having a few isolated F-Curves stuck on some data it operates on... */ + /* TODO: this sounds a bit hacky having a few isolated F-Curves + * stuck on some data it operates on... */ nlastrip_evaluate_controls(depsgraph, estrip, ctime); - if (estrip->influence <= 0.0f) + if (estrip->influence <= 0.0f) { return NULL; + } /* check if strip has valid data to evaluate, * and/or perform any additional type-specific actions @@ -2124,13 +2200,15 @@ NlaEvalStrip *nlastrips_ctime_get_strip( switch (estrip->type) { case NLASTRIP_TYPE_CLIP: /* clip must have some action to evaluate */ - if (estrip->act == NULL) + if (estrip->act == NULL) { return NULL; + } break; case NLASTRIP_TYPE_TRANSITION: /* there must be strips to transition from and to (i.e. prev and next required) */ - if (ELEM(NULL, estrip->prev, estrip->next)) + if (ELEM(NULL, estrip->prev, estrip->next)) { return NULL; + } /* evaluate controls for the relevant extents of the bordering strips... */ nlastrip_evaluate_controls(depsgraph, estrip->prev, estrip->start); @@ -2146,8 +2224,9 @@ NlaEvalStrip *nlastrips_ctime_get_strip( nes->track_index = index; nes->strip_time = estrip->strip_time; - if (list) + if (list) { BLI_addtail(list, nes); + } return nes; } @@ -2280,7 +2359,8 @@ static NlaEvalChannelSnapshot *nlaeval_snapshot_find_channel(NlaEvalSnapshot *sn return &nec->base_snapshot; } -/* Retrieve or create the channel value snapshot, copying from the other snapshot (or default values) */ +/* Retrieve or create the channel value snapshot, copying from the other snapshot + * (or default values) */ static NlaEvalChannelSnapshot *nlaeval_snapshot_ensure_channel(NlaEvalSnapshot *snapshot, NlaEvalChannel *nec) { @@ -2541,6 +2621,9 @@ static NlaEvalChannel *nlaevalchan_verify(PointerRNA *ptr, NlaEvalData *nlaeval, return *p_path_nec; } + /* Cache NULL result for now. */ + *p_path_nec = NULL; + /* Resolve the property and look it up in the key hash. */ NlaEvalChannelKey key; @@ -2553,8 +2636,11 @@ static NlaEvalChannel *nlaevalchan_verify(PointerRNA *ptr, NlaEvalData *nlaeval, path); } - /* Cache NULL result. */ - *p_path_nec = NULL; + return NULL; + } + + /* Check that the property can be animated. */ + if (ptr->id.data != NULL && !RNA_property_animateable(&key.ptr, key.prop)) { return NULL; } @@ -2902,7 +2988,8 @@ static void nlaeval_snapshot_mix_and_free(NlaEvalData *nlaeval, } /* ---------------------- */ -/* F-Modifier stack joining/separation utilities - should we generalise these for BLI_listbase.h interface? */ +/* F-Modifier stack joining/separation utilities - + * should we generalize these for BLI_listbase.h interface? */ /* Temporarily join two lists of modifiers together, storing the result in a third list */ static void nlaeval_fmodifiers_join_stacks(ListBase *result, ListBase *list1, ListBase *list2) @@ -2922,8 +3009,9 @@ static void nlaeval_fmodifiers_join_stacks(ListBase *result, ListBase *list1, Li result->last = list1->last; } else { - /* list1 should be added first, and list2 second, with the endpoints of these being the endpoints for result - * - the original lists must be left unchanged though, as we need that fact for restoring + /* list1 should be added first, and list2 second, + * with the endpoints of these being the endpoints for result + * - the original lists must be left unchanged though, as we need that fact for restoring. */ result->first = list1->first; result->last = list2->last; @@ -2942,10 +3030,12 @@ static void nlaeval_fmodifiers_split_stacks(ListBase *list1, ListBase *list2) FModifier *fcm1, *fcm2; /* if list1/2 is invalid... just skip */ - if (ELEM(NULL, list1, list2)) + if (ELEM(NULL, list1, list2)) { return; - if (ELEM(NULL, list1->first, list2->first)) + } + if (ELEM(NULL, list1->first, list2->first)) { return; + } /* get endpoints */ fcm1 = list1->last; @@ -2965,15 +3055,15 @@ static void nlastrip_evaluate_actionclip(PointerRNA *ptr, NlaEvalStrip *nes, NlaEvalSnapshot *snapshot) { - FModifierStackStorage *storage; ListBase tmp_modifiers = {NULL, NULL}; NlaStrip *strip = nes->strip; FCurve *fcu; float evaltime; /* sanity checks for action */ - if (strip == NULL) + if (strip == NULL) { return; + } if (strip->act == NULL) { CLOG_ERROR(&LOG, "NLA-Strip Eval Error: Strip '%s' has no Action", strip->name); @@ -2986,8 +3076,12 @@ static void nlastrip_evaluate_actionclip(PointerRNA *ptr, nlaeval_fmodifiers_join_stacks(&tmp_modifiers, &strip->modifiers, modifiers); /* evaluate strip's modifiers which modify time to evaluate the base curves at */ - storage = evaluate_fmodifiers_storage_new(&tmp_modifiers); - evaltime = evaluate_time_fmodifiers(storage, &tmp_modifiers, NULL, 0.0f, strip->strip_time); + FModifiersStackStorage storage; + storage.modifier_count = BLI_listbase_count(&tmp_modifiers); + storage.size_per_modifier = evaluate_fmodifiers_storage_size_per_modifier(&tmp_modifiers); + storage.buffer = alloca(storage.modifier_count * storage.size_per_modifier); + + evaltime = evaluate_time_fmodifiers(&storage, &tmp_modifiers, NULL, 0.0f, strip->strip_time); NlaBlendData blend = { .snapshot = snapshot, @@ -2995,29 +3089,34 @@ static void nlastrip_evaluate_actionclip(PointerRNA *ptr, .influence = strip->influence, }; - /* evaluate all the F-Curves in the action, saving the relevant pointers to data that will need to be used */ + /* Evaluate all the F-Curves in the action, + * saving the relevant pointers to data that will need to be used. */ for (fcu = strip->act->curves.first; fcu; fcu = fcu->next) { float value = 0.0f; /* check if this curve should be skipped */ - if (fcu->flag & (FCURVE_MUTED | FCURVE_DISABLED)) + if (fcu->flag & (FCURVE_MUTED | FCURVE_DISABLED)) { continue; - if ((fcu->grp) && (fcu->grp->flag & AGRP_MUTED)) + } + if ((fcu->grp) && (fcu->grp->flag & AGRP_MUTED)) { continue; + } /* evaluate the F-Curve's value for the time given in the strip - * NOTE: we use the modified time here, since strip's F-Curve Modifiers are applied on top of this + * NOTE: we use the modified time here, since strip's F-Curve Modifiers + * are applied on top of this. */ value = evaluate_fcurve(fcu, evaltime); /* apply strip's F-Curve Modifiers on this value - * NOTE: we apply the strip's original evaluation time not the modified one (as per standard F-Curve eval) + * NOTE: we apply the strip's original evaluation time not the modified one + * (as per standard F-Curve eval) */ - evaluate_value_fmodifiers(storage, &tmp_modifiers, fcu, &value, strip->strip_time); + evaluate_value_fmodifiers(&storage, &tmp_modifiers, fcu, &value, strip->strip_time); - /* get an NLA evaluation channel to work with, and accumulate the evaluated value with the value(s) - * stored in this channel if it has been used already - */ + /* Get an NLA evaluation channel to work with, + * and accumulate the evaluated value with the value(s) + * stored in this channel if it has been used already. */ NlaEvalChannel *nec = nlaevalchan_verify(ptr, channels, fcu->rna_path); nlaeval_blend_value(&blend, nec, fcu->array_index, value); @@ -3025,9 +3124,6 @@ static void nlastrip_evaluate_actionclip(PointerRNA *ptr, nlaeval_blend_flush(&blend); - /* free temporary storage */ - evaluate_fmodifiers_storage_free(storage); - /* unlink this strip's modifiers from the parent's modifiers again */ nlaeval_fmodifiers_split_stacks(&strip->modifiers, modifiers); } @@ -3146,12 +3242,16 @@ void nlastrip_evaluate(Depsgraph *depsgraph, { NlaStrip *strip = nes->strip; - /* to prevent potential infinite recursion problems (i.e. transition strip, beside meta strip containing a transition - * several levels deep inside it), we tag the current strip as being evaluated, and clear this when we leave + /* To prevent potential infinite recursion problems + * (i.e. transition strip, beside meta strip containing a transition + * several levels deep inside it), + * we tag the current strip as being evaluated, and clear this when we leave. */ - /* TODO: be careful with this flag, since some edit tools may be running and have set this while animplayback was running */ - if (strip->flag & NLASTRIP_FLAG_EDIT_TOUCHED) + /* TODO: be careful with this flag, since some edit tools may be running and have + * set this while animplayback was running */ + if (strip->flag & NLASTRIP_FLAG_EDIT_TOUCHED) { return; + } strip->flag |= NLASTRIP_FLAG_EDIT_TOUCHED; /* actions to take depend on the type of strip */ @@ -3181,8 +3281,9 @@ void nladata_flush_channels(Depsgraph *depsgraph, NlaEvalSnapshot *snapshot) { /* sanity checks */ - if (channels == NULL) + if (channels == NULL) { return; + } const bool is_active_depsgraph = DEG_is_active(depsgraph); @@ -3220,10 +3321,12 @@ static void nla_eval_domain_action(PointerRNA *ptr, for (FCurve *fcu = act->curves.first; fcu; fcu = fcu->next) { /* check if this curve should be skipped */ - if (fcu->flag & (FCURVE_MUTED | FCURVE_DISABLED)) + if (fcu->flag & (FCURVE_MUTED | FCURVE_DISABLED)) { continue; - if ((fcu->grp) && (fcu->grp->flag & AGRP_MUTED)) + } + if ((fcu->grp) && (fcu->grp->flag & AGRP_MUTED)) { continue; + } NlaEvalChannel *nec = nlaevalchan_verify(ptr, channels, fcu->rna_path); @@ -3276,14 +3379,16 @@ static void animsys_evaluate_nla_domain(PointerRNA *ptr, NlaEvalData *channels, /* solo and muting are mutually exclusive... */ if (adt->flag & ADT_NLA_SOLO_TRACK) { /* skip if there is a solo track, but this isn't it */ - if ((nlt->flag & NLATRACK_SOLO) == 0) + if ((nlt->flag & NLATRACK_SOLO) == 0) { continue; + } /* else - mute doesn't matter */ } else { /* no solo tracks - skip track if muted */ - if (nlt->flag & NLATRACK_MUTED) + if (nlt->flag & NLATRACK_MUTED) { continue; + } } nla_eval_domain_strips(ptr, channels, &nlt->strips, touched_actions); @@ -3297,9 +3402,10 @@ static void animsys_evaluate_nla_domain(PointerRNA *ptr, NlaEvalData *channels, /** * NLA Evaluation function - values are calculated and stored in temporary "NlaEvalChannels" * - * \param[out] echannels Evaluation channels with calculated values - * \param[out] r_context If not NULL, data about the currently edited strip is stored here and excluded from value calculation. - * \return false if NLA evaluation isn't actually applicable + * \param[out] echannels: Evaluation channels with calculated values + * \param[out] r_context: If not NULL, + * data about the currently edited strip is stored here and excluded from value calculation. + * \return false if NLA evaluation isn't actually applicable. */ static bool animsys_evaluate_nla(Depsgraph *depsgraph, NlaEvalData *echannels, @@ -3323,33 +3429,39 @@ static bool animsys_evaluate_nla(Depsgraph *depsgraph, /* 1. get the stack of strips to evaluate at current time (influence calculated here) */ for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next, track_index++) { - /* stop here if tweaking is on and this strip is the tweaking track (it will be the first one that's 'disabled')... */ - if ((adt->flag & ADT_NLA_EDIT_ON) && (nlt->flag & NLATRACK_DISABLED)) + /* stop here if tweaking is on and this strip is the tweaking track + * (it will be the first one that's 'disabled')... */ + if ((adt->flag & ADT_NLA_EDIT_ON) && (nlt->flag & NLATRACK_DISABLED)) { break; + } /* solo and muting are mutually exclusive... */ if (adt->flag & ADT_NLA_SOLO_TRACK) { /* skip if there is a solo track, but this isn't it */ - if ((nlt->flag & NLATRACK_SOLO) == 0) + if ((nlt->flag & NLATRACK_SOLO) == 0) { continue; + } /* else - mute doesn't matter */ } else { /* no solo tracks - skip track if muted */ - if (nlt->flag & NLATRACK_MUTED) + if (nlt->flag & NLATRACK_MUTED) { continue; + } } /* if this track has strips (but maybe they won't be suitable), set has_strips * - used for mainly for still allowing normal action evaluation... */ - if (nlt->strips.first) + if (nlt->strips.first) { has_strips = true; + } /* otherwise, get strip to evaluate for this channel */ nes = nlastrips_ctime_get_strip(depsgraph, &estrips, &nlt->strips, track_index, ctime); - if (nes) + if (nes) { nes->track = nlt; + } } /* add 'active' Action (may be tweaking track) as last strip to evaluate in NLA stack @@ -3379,7 +3491,8 @@ static bool animsys_evaluate_nla(Depsgraph *depsgraph, /* set settings of dummy NLA strip from AnimData settings */ dummy_strip->act = adt->action; - /* action range is calculated taking F-Modifiers into account (which making new strips doesn't do due to the troublesome nature of that) */ + /* action range is calculated taking F-Modifiers into account + * (which making new strips doesn't do due to the troublesome nature of that) */ calc_action_range(dummy_strip->act, &dummy_strip->actstart, &dummy_strip->actend, 1); dummy_strip->start = dummy_strip->actstart; dummy_strip->end = (IS_EQF(dummy_strip->actstart, dummy_strip->actend)) ? @@ -3396,14 +3509,16 @@ static bool animsys_evaluate_nla(Depsgraph *depsgraph, dummy_strip->extendmode = adt->act_extendmode; } - /* Unless extendmode is Nothing (might be useful for flattening NLA evaluation), disable range. */ + /* Unless extendmode is Nothing (might be useful for flattening NLA evaluation), + * disable range. */ if (dummy_strip->extendmode != NLASTRIP_EXTEND_NOTHING) { dummy_strip->flag |= NLASTRIP_FLAG_NO_TIME_MAP; } dummy_strip->influence = adt->act_influence; - /* NOTE: must set this, or else the default setting overrides, and this setting doesn't work */ + /* NOTE: must set this, or else the default setting overrides, + * and this setting doesn't work. */ dummy_strip->flag |= NLASTRIP_FLAG_USR_INFLUENCE; } @@ -3413,7 +3528,8 @@ static bool animsys_evaluate_nla(Depsgraph *depsgraph, } /* If computing the context for keyframing, store data there instead of the list. */ else { - /* The extend mode here effectively controls whether it is possible to keyframe beyond the ends. */ + /* The extend mode here effectively controls + * whether it is possible to key-frame beyond the ends. */ dummy_strip->extendmode = is_inplace_tweak ? NLASTRIP_EXTEND_NOTHING : NLASTRIP_EXTEND_HOLD; @@ -3436,12 +3552,15 @@ static bool animsys_evaluate_nla(Depsgraph *depsgraph, } /* only continue if there are strips to evaluate */ - if (BLI_listbase_is_empty(&estrips)) + if (BLI_listbase_is_empty(&estrips)) { return true; + } - /* 2. for each strip, evaluate then accumulate on top of existing channels, but don't set values yet */ - for (nes = estrips.first; nes; nes = nes->next) + /* 2. for each strip, evaluate then accumulate on top of existing channels, + * but don't set values yet. */ + for (nes = estrips.first; nes; nes = nes->next) { nlastrip_evaluate(depsgraph, ptr, echannels, NULL, nes, &echannels->eval_snapshot); + } /* 3. free temporary evaluation data that's not used elsewhere */ BLI_freelistN(&estrips); @@ -3472,8 +3591,9 @@ static void animsys_calculate_nla(Depsgraph *depsgraph, else { /* special case - evaluate as if there isn't any NLA data */ /* TODO: this is really just a stop-gap measure... */ - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { CLOG_WARN(&LOG, "NLA Eval: Stopgap for active action on NLA Stack - no strips case"); + } animsys_evaluate_action(depsgraph, ptr, adt->action, ctime); } @@ -3488,9 +3608,10 @@ static void animsys_calculate_nla(Depsgraph *depsgraph, * Prepare data necessary to compute correct keyframe values for NLA strips * with non-Replace mode or influence different from 1. * - * @param cache List used to cache contexts for reuse when keying multiple channels in one operation. - * @param ptr RNA pointer to the Object with the animation. - * @return Keyframing context, or NULL if not necessary. + * \param cache List used to cache contexts for reuse when keying + * multiple channels in one operation. + * \param ptr RNA pointer to the Object with the animation. + * \return Keyframing context, or NULL if not necessary. */ NlaKeyframingContext *BKE_animsys_get_nla_keyframing_context(struct ListBase *cache, struct Depsgraph *depsgraph, @@ -3531,13 +3652,14 @@ NlaKeyframingContext *BKE_animsys_get_nla_keyframing_context(struct ListBase *ca /** * Apply correction from the NLA context to the values about to be keyframed. * - * @param context Context to use (may be NULL). - * @param prop_ptr Property about to be keyframed. - * @param[in,out] values Array of property values to adjust. - * @param count Number of values in the array. - * @param index Index of the element about to be updated, or -1. - * @param[out] r_force_all Set to true if all channels must be inserted. May be NULL. - * @return False if correction fails due to a division by zero, or null r_force_all when all channels are required. + * \param context Context to use (may be NULL). + * \param prop_ptr Property about to be keyframed. + * \param[in,out] values Array of property values to adjust. + * \param count Number of values in the array. + * \param index Index of the element about to be updated, or -1. + * \param[out] r_force_all Set to true if all channels must be inserted. May be NULL. + * \return False if correction fails due to a division by zero, + * or null r_force_all when all channels are required. */ bool BKE_animsys_nla_remap_keyframe_values(struct NlaKeyframingContext *context, struct PointerRNA *prop_ptr, @@ -3681,17 +3803,21 @@ static void animsys_evaluate_overrides(PointerRNA *ptr, AnimData *adt) * 3) Drivers/expressions are evaluated on top of this, in an order where dependencies are * resolved nicely. * Note: it may be necessary to have some tools to handle the cases where some higher-level - * drivers are added and cause some problematic dependencies that didn't exist in the local levels... + * drivers are added and cause some problematic dependencies that + * didn't exist in the local levels... * * --------------< always executed >------------------ * * Maintenance of editability of settings (XXX): - * In order to ensure that settings that are animated can still be manipulated in the UI without requiring - * that keyframes are added to prevent these values from being overwritten, we use 'overrides'. + * - In order to ensure that settings that are animated can still be manipulated in the UI without + * requiring that keyframes are added to prevent these values from being overwritten, + * we use 'overrides'. * * Unresolved things: - * - Handling of multi-user settings (i.e. time-offset, group-instancing) -> big cache grids or nodal system? but stored where? - * - Multiple-block dependencies (i.e. drivers for settings are in both local and higher levels) -> split into separate lists? + * - Handling of multi-user settings (i.e. time-offset, group-instancing) -> big cache grids + * or nodal system? but stored where? + * - Multiple-block dependencies + * (i.e. drivers for settings are in both local and higher levels) -> split into separate lists? * * Current Status: * - Currently (as of September 2009), overrides we haven't needed to (fully) implement overrides. @@ -3710,8 +3836,9 @@ void BKE_animsys_evaluate_animdata( PointerRNA id_ptr; /* sanity checks */ - if (ELEM(NULL, id, adt)) + if (ELEM(NULL, id, adt)) { return; + } /* get pointer to ID-block for RNA to use */ RNA_id_pointer_create(id, &id_ptr); @@ -3730,8 +3857,9 @@ void BKE_animsys_evaluate_animdata( animsys_calculate_nla(depsgraph, &id_ptr, adt, ctime); } /* evaluate Active Action only */ - else if (adt->action) + else if (adt->action) { animsys_evaluate_action_ex(depsgraph, &id_ptr, adt->action, ctime); + } } /* recalculate drivers @@ -3773,10 +3901,11 @@ void BKE_animsys_evaluate_all_animation(Main *main, { ID *id; - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("Evaluate all animation - %f\n", ctime); + } - /* macros for less typing + /* macros for less typing * - only evaluate animation data for id if it has users (and not just fake ones) * - whether animdata exists is checked for by the evaluation function, though taking * this outside of the function may make things slightly faster? @@ -3790,7 +3919,7 @@ void BKE_animsys_evaluate_all_animation(Main *main, } \ (void)0 - /* another macro for the "embedded" nodetree cases + /* another macro for the "embedded" nodetree cases * - this is like EVAL_ANIM_IDS, but this handles the case "embedded nodetrees" * (i.e. scene/material/texture->nodetree) which we need a special exception * for, otherwise they'd get skipped @@ -3820,8 +3949,9 @@ void BKE_animsys_evaluate_all_animation(Main *main, * set correctly, so this optimization must be skipped in that case... */ if (BLI_listbase_is_empty(&main->actions) && BLI_listbase_is_empty(&main->curves)) { - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("\tNo Actions, so no animation needs to be evaluated...\n"); + } return; } @@ -3906,9 +4036,9 @@ void BKE_animsys_eval_animdata(Depsgraph *depsgraph, ID *id) { float ctime = DEG_get_ctime(depsgraph); AnimData *adt = BKE_animdata_from_id(id); - Scene *scene = NULL; /* XXX: this is only needed for flushing RNA updates, - * which should get handled as part of the dependency graph instead... - */ + /* XXX: this is only needed for flushing RNA updates, + * which should get handled as part of the dependency graph instead. */ + Scene *scene = NULL; DEG_debug_print_eval_time(depsgraph, __func__, id->name, id, ctime); BKE_animsys_evaluate_animdata(depsgraph, scene, id, adt, ctime, ADT_RECALC_ANIM); } @@ -3964,9 +4094,9 @@ void BKE_animsys_eval_driver(Depsgraph *depsgraph, /* XXX driver recalc flag is not set yet by depsgraph! */ if ((driver_orig) && !(driver_orig->flag & DRIVER_FLAG_INVALID)) { /* evaluate this using values set already in other places - * NOTE: for 'layering' option later on, we should check if we should remove old value before adding - * new to only be done when drivers only changed */ - //printf("\told val = %f\n", fcu->curval); + * NOTE: for 'layering' option later on, we should check if we should remove old value before + * adding new to only be done when drivers only changed */ + // printf("\told val = %f\n", fcu->curval); PathResolvedRNA anim_rna; if (animsys_store_rna_setting(&id_ptr, fcu->rna_path, fcu->array_index, &anim_rna)) { diff --git a/source/blender/blenkernel/intern/appdir.c b/source/blender/blenkernel/intern/appdir.c index 5383138956e..2b4123c74e2 100644 --- a/source/blender/blenkernel/intern/appdir.c +++ b/source/blender/blenkernel/intern/appdir.c @@ -55,8 +55,9 @@ # ifdef WITH_BINRELOC # include "binreloc.h" # endif -# include <unistd.h> /* mkdtemp on OSX (and probably all *BSD?), not worth making specific check for this OS. */ -#endif /* WIN32 */ +/* mkdtemp on OSX (and probably all *BSD?), not worth making specific check for this OS. */ +# include <unistd.h> +#endif /* WIN32 */ /* local */ static CLG_LogRef LOG = {"bke.appdir"}; @@ -73,8 +74,9 @@ const char *BKE_appdir_folder_default(void) #ifndef WIN32 const char *const xdg_documents_dir = BLI_getenv("XDG_DOCUMENTS_DIR"); - if (xdg_documents_dir) + if (xdg_documents_dir) { return xdg_documents_dir; + } return BLI_getenv("HOME"); #else /* Windows */ @@ -83,8 +85,9 @@ const char *BKE_appdir_folder_default(void) /* Check for %HOME% env var */ if (uput_getenv("HOME", documentfolder, MAXPATHLEN)) { - if (BLI_is_dir(documentfolder)) + if (BLI_is_dir(documentfolder)) { return documentfolder; + } } /* add user profile support for WIN 2K / NT. @@ -95,8 +98,9 @@ const char *BKE_appdir_folder_default(void) hResult = SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, documentfolder); if (hResult == S_OK) { - if (BLI_is_dir(documentfolder)) + if (BLI_is_dir(documentfolder)) { return documentfolder; + } } return NULL; @@ -153,7 +157,7 @@ static bool test_path(char *targetpath, #ifdef PATH_DEBUG printf("\t%s missing: %s\n", __func__, targetpath); #endif - //targetpath[0] = '\0'; + // targetpath[0] = '\0'; return false; } } @@ -165,8 +169,9 @@ static bool test_path(char *targetpath, static bool test_env_path(char *path, const char *envvar) { const char *env = envvar ? BLI_getenv(envvar) : NULL; - if (!env) + if (!env) { return false; + } if (BLI_is_dir(env)) { BLI_strncpy(path, env, FILE_MAX); @@ -218,9 +223,11 @@ static bool get_path_local(char *targetpath, relfolder[0] = '\0'; } - /* try EXECUTABLE_DIR/2.5x/folder_name - new default directory for local blender installed files */ + /* Try EXECUTABLE_DIR/2.5x/folder_name - + * new default directory for local blender installed files. */ #ifdef __APPLE__ - /* due new codesign situation in OSX > 10.9.5 we must move the blender_version dir with contents to Resources */ + /* Due new codesign situation in OSX > 10.9.5 + * we must move the blender_version dir with contents to Resources. */ char osx_resourses[FILE_MAX]; BLI_snprintf(osx_resourses, sizeof(osx_resourses), "%s../Resources", bprogdir); /* Remove the '/../' added above. */ @@ -324,11 +331,13 @@ static bool get_path_user(char *targetpath, user_path[0] = '\0'; user_base_path = (const char *)GHOST_getUserDir(ver, blender_version_decimal(ver)); - if (user_base_path) + if (user_base_path) { BLI_strncpy(user_path, user_base_path, FILE_MAX); + } - if (!user_path[0]) + if (!user_path[0]) { return false; + } #ifdef PATH_DEBUG printf("%s: %s\n", __func__, user_path); @@ -375,11 +384,13 @@ static bool get_path_system(char *targetpath, system_path[0] = '\0'; system_base_path = (const char *)GHOST_getSystemDir(ver, blender_version_decimal(ver)); - if (system_base_path) + if (system_base_path) { BLI_strncpy(system_path, system_base_path, FILE_MAX); + } - if (!system_path[0]) + if (!system_path[0]) { return false; + } #ifdef PATH_DEBUG printf("%s: %s\n", __func__, system_path); @@ -411,71 +422,93 @@ const char *BKE_appdir_folder_id_ex(const int folder_id, switch (folder_id) { case BLENDER_DATAFILES: /* general case */ - if (get_path_environment(path, path_len, subfolder, "BLENDER_USER_DATAFILES")) + if (get_path_environment(path, path_len, subfolder, "BLENDER_USER_DATAFILES")) { break; - if (get_path_user(path, path_len, "datafiles", subfolder, ver)) + } + if (get_path_user(path, path_len, "datafiles", subfolder, ver)) { break; - if (get_path_environment(path, path_len, subfolder, "BLENDER_SYSTEM_DATAFILES")) + } + if (get_path_environment(path, path_len, subfolder, "BLENDER_SYSTEM_DATAFILES")) { break; - if (get_path_local(path, path_len, "datafiles", subfolder, ver)) + } + if (get_path_local(path, path_len, "datafiles", subfolder, ver)) { break; - if (get_path_system(path, path_len, "datafiles", subfolder, ver)) + } + if (get_path_system(path, path_len, "datafiles", subfolder, ver)) { break; + } return NULL; case BLENDER_USER_DATAFILES: - if (get_path_environment(path, path_len, subfolder, "BLENDER_USER_DATAFILES")) + if (get_path_environment(path, path_len, subfolder, "BLENDER_USER_DATAFILES")) { break; - if (get_path_user(path, path_len, "datafiles", subfolder, ver)) + } + if (get_path_user(path, path_len, "datafiles", subfolder, ver)) { break; + } return NULL; case BLENDER_SYSTEM_DATAFILES: - if (get_path_environment(path, path_len, subfolder, "BLENDER_SYSTEM_DATAFILES")) + if (get_path_environment(path, path_len, subfolder, "BLENDER_SYSTEM_DATAFILES")) { break; - if (get_path_system(path, path_len, "datafiles", subfolder, ver)) + } + if (get_path_system(path, path_len, "datafiles", subfolder, ver)) { break; - if (get_path_local(path, path_len, "datafiles", subfolder, ver)) + } + if (get_path_local(path, path_len, "datafiles", subfolder, ver)) { break; + } return NULL; case BLENDER_USER_AUTOSAVE: - if (get_path_environment(path, path_len, subfolder, "BLENDER_USER_DATAFILES")) + if (get_path_environment(path, path_len, subfolder, "BLENDER_USER_DATAFILES")) { break; - if (get_path_user(path, path_len, "autosave", subfolder, ver)) + } + if (get_path_user(path, path_len, "autosave", subfolder, ver)) { break; + } return NULL; case BLENDER_USER_CONFIG: - if (get_path_environment(path, path_len, subfolder, "BLENDER_USER_CONFIG")) + if (get_path_environment(path, path_len, subfolder, "BLENDER_USER_CONFIG")) { break; - if (get_path_user(path, path_len, "config", subfolder, ver)) + } + if (get_path_user(path, path_len, "config", subfolder, ver)) { break; + } return NULL; case BLENDER_USER_SCRIPTS: - if (get_path_environment(path, path_len, subfolder, "BLENDER_USER_SCRIPTS")) + if (get_path_environment(path, path_len, subfolder, "BLENDER_USER_SCRIPTS")) { break; - if (get_path_user(path, path_len, "scripts", subfolder, ver)) + } + if (get_path_user(path, path_len, "scripts", subfolder, ver)) { break; + } return NULL; case BLENDER_SYSTEM_SCRIPTS: - if (get_path_environment(path, path_len, subfolder, "BLENDER_SYSTEM_SCRIPTS")) + if (get_path_environment(path, path_len, subfolder, "BLENDER_SYSTEM_SCRIPTS")) { break; - if (get_path_system(path, path_len, "scripts", subfolder, ver)) + } + if (get_path_system(path, path_len, "scripts", subfolder, ver)) { break; - if (get_path_local(path, path_len, "scripts", subfolder, ver)) + } + if (get_path_local(path, path_len, "scripts", subfolder, ver)) { break; + } return NULL; case BLENDER_SYSTEM_PYTHON: - if (get_path_environment(path, path_len, subfolder, "BLENDER_SYSTEM_PYTHON")) + if (get_path_environment(path, path_len, subfolder, "BLENDER_SYSTEM_PYTHON")) { break; - if (get_path_system(path, path_len, "python", subfolder, ver)) + } + if (get_path_system(path, path_len, "python", subfolder, ver)) { break; - if (get_path_local(path, path_len, "python", subfolder, ver)) + } + if (get_path_local(path, path_len, "python", subfolder, ver)) { break; + } return NULL; default: @@ -502,23 +535,27 @@ const char *BKE_appdir_folder_id_user_notest(const int folder_id, const char *su switch (folder_id) { case BLENDER_USER_DATAFILES: - if (get_path_environment_notest(path, sizeof(path), subfolder, "BLENDER_USER_DATAFILES")) + if (get_path_environment_notest(path, sizeof(path), subfolder, "BLENDER_USER_DATAFILES")) { break; + } get_path_user(path, sizeof(path), "datafiles", subfolder, ver); break; case BLENDER_USER_CONFIG: - if (get_path_environment_notest(path, sizeof(path), subfolder, "BLENDER_USER_CONFIG")) + if (get_path_environment_notest(path, sizeof(path), subfolder, "BLENDER_USER_CONFIG")) { break; + } get_path_user(path, sizeof(path), "config", subfolder, ver); break; case BLENDER_USER_AUTOSAVE: - if (get_path_environment_notest(path, sizeof(path), subfolder, "BLENDER_USER_AUTOSAVE")) + if (get_path_environment_notest(path, sizeof(path), subfolder, "BLENDER_USER_AUTOSAVE")) { break; + } get_path_user(path, sizeof(path), "autosave", subfolder, ver); break; case BLENDER_USER_SCRIPTS: - if (get_path_environment_notest(path, sizeof(path), subfolder, "BLENDER_USER_SCRIPTS")) + if (get_path_environment_notest(path, sizeof(path), subfolder, "BLENDER_USER_SCRIPTS")) { break; + } get_path_user(path, sizeof(path), "scripts", subfolder, ver); break; default: @@ -544,15 +581,17 @@ const char *BKE_appdir_folder_id_create(const int folder_id, const char *subfold BLENDER_USER_DATAFILES, BLENDER_USER_CONFIG, BLENDER_USER_SCRIPTS, - BLENDER_USER_AUTOSAVE)) + BLENDER_USER_AUTOSAVE)) { return NULL; + } path = BKE_appdir_folder_id(folder_id, subfolder); if (!path) { path = BKE_appdir_folder_id_user_notest(folder_id, subfolder); - if (path) + if (path) { BLI_dir_create_recursive(path); + } } return path; diff --git a/source/blender/blenkernel/intern/armature.c b/source/blender/blenkernel/intern/armature.c index 69721651a45..60446bf60b6 100644 --- a/source/blender/blenkernel/intern/armature.c +++ b/source/blender/blenkernel/intern/armature.c @@ -89,8 +89,9 @@ bArmature *BKE_armature_add(Main *bmain, const char *name) bArmature *BKE_armature_from_object(Object *ob) { - if (ob->type == OB_ARMATURE) + if (ob->type == OB_ARMATURE) { return (bArmature *)ob->data; + } return NULL; } @@ -168,9 +169,33 @@ static void copy_bonechildren(Bone *bone_dst, } } +static void copy_bonechildren_custom_handles(Bone *bone_dst, bArmature *arm_dst, GHash **bone_hash) +{ + Bone *bone_dst_child; + + /* Lazily create the name -> bone hashtable. */ + if ((bone_dst->bbone_prev || bone_dst->bbone_next) && *bone_hash == NULL) { + *bone_hash = BKE_armature_bone_from_name_map(arm_dst); + } + + if (bone_dst->bbone_prev) { + bone_dst->bbone_prev = BLI_ghash_lookup(*bone_hash, bone_dst->bbone_prev->name); + } + if (bone_dst->bbone_next) { + bone_dst->bbone_next = BLI_ghash_lookup(*bone_hash, bone_dst->bbone_next->name); + } + + for (bone_dst_child = bone_dst->childbase.first; bone_dst_child; + bone_dst_child = bone_dst_child->next) { + copy_bonechildren_custom_handles(bone_dst_child, arm_dst, bone_hash); + } +} + /** - * Only copy internal data of Armature ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of Armature ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * @@ -199,6 +224,17 @@ void BKE_armature_copy_data(Main *UNUSED(bmain), arm_dst->act_bone = bone_dst_act; + /* Fix custom handle references. */ + GHash *bone_hash = NULL; /* lazily created */ + + for (bone_dst = arm_dst->bonebase.first; bone_dst; bone_dst = bone_dst->next) { + copy_bonechildren_custom_handles(bone_dst, arm_dst, &bone_hash); + } + + if (bone_hash) { + BLI_ghash_free(bone_hash, NULL, NULL); + } + arm_dst->edbo = NULL; arm_dst->act_edbone = NULL; } @@ -215,12 +251,14 @@ static Bone *get_named_bone_bonechildren(ListBase *lb, const char *name) Bone *curBone, *rbone; for (curBone = lb->first; curBone; curBone = curBone->next) { - if (STREQ(curBone->name, name)) + if (STREQ(curBone->name, name)) { return curBone; + } rbone = get_named_bone_bonechildren(&curBone->childbase, name); - if (rbone) + if (rbone) { return rbone; + } } return NULL; @@ -232,8 +270,9 @@ static Bone *get_named_bone_bonechildren(ListBase *lb, const char *name) */ Bone *BKE_armature_find_bone_name(bArmature *arm, const char *name) { - if (!arm) + if (!arm) { return NULL; + } return get_named_bone_bonechildren(&arm->bonebase, name); } @@ -285,8 +324,9 @@ int bone_autoside_name( char extension[5] = ""; len = strlen(name); - if (len == 0) + if (len == 0) { return 0; + } BLI_strncpy(basename, name, sizeof(basename)); /* Figure out extension to append: @@ -300,47 +340,59 @@ int bone_autoside_name( if (axis == 2) { /* z-axis - vertical (top/bottom) */ if (IS_EQF(head, 0.0f)) { - if (tail < 0) + if (tail < 0) { strcpy(extension, "Bot"); - else if (tail > 0) + } + else if (tail > 0) { strcpy(extension, "Top"); + } } else { - if (head < 0) + if (head < 0) { strcpy(extension, "Bot"); - else + } + else { strcpy(extension, "Top"); + } } } else if (axis == 1) { /* y-axis - depth (front/back) */ if (IS_EQF(head, 0.0f)) { - if (tail < 0) + if (tail < 0) { strcpy(extension, "Fr"); - else if (tail > 0) + } + else if (tail > 0) { strcpy(extension, "Bk"); + } } else { - if (head < 0) + if (head < 0) { strcpy(extension, "Fr"); - else + } + else { strcpy(extension, "Bk"); + } } } else { /* x-axis - horizontal (left/right) */ if (IS_EQF(head, 0.0f)) { - if (tail < 0) + if (tail < 0) { strcpy(extension, "R"); - else if (tail > 0) + } + else if (tail > 0) { strcpy(extension, "L"); + } } else { - if (head < 0) + if (head < 0) { strcpy(extension, "R"); - /* XXX Shouldn't this be simple else, as for z and y axes? */ - else if (head > 0) + /* XXX Shouldn't this be simple else, as for z and y axes? */ + } + else if (head > 0) { strcpy(extension, "L"); + } } } @@ -391,8 +443,9 @@ int bone_autoside_name( return 1; } - else + else { return 0; + } } /* ************* B-Bone support ******************* */ @@ -420,8 +473,9 @@ static void equalize_cubic_bezier(const float control[4][3], /* Calculate the length of the polyline at each point. */ pdist[0] = 0.0f; - for (int i = 0; i < temp_segments; i++) + for (int i = 0; i < temp_segments; i++) { pdist[i + 1] = pdist[i] + len_v3v3(coords[i], coords[i + 1]); + } /* Go over distances and calculate new parameter values. */ float dist_step = pdist[temp_segments] / final_segments; @@ -432,8 +486,9 @@ static void equalize_cubic_bezier(const float control[4][3], float dist = i * dist_step; /* We're looking for location (distance) 'dist' in the array. */ - while ((nr < temp_segments) && (dist >= pdist[nr])) + while ((nr < temp_segments) && (dist >= pdist[nr])) { nr++; + } float fac = (pdist[nr] - dist) / (pdist[nr] - pdist[nr - 1]); @@ -443,7 +498,8 @@ static void equalize_cubic_bezier(const float control[4][3], r_t_points[final_segments] = 1.0f; } -/* Evaluate bezier position and tangent at a specific parameter value using the De Casteljau algorithm. */ +/* Evaluate bezier position and tangent at a specific parameter value + * using the De Casteljau algorithm. */ static void evaluate_cubic_bezier(const float control[4][3], float t, float r_pos[3], @@ -660,15 +716,17 @@ void BKE_pchan_bbone_spline_params_get(struct bPoseChannel *pchan, } } - param->scaleIn = bone->scaleIn * (!rest ? pchan->scaleIn : 1.0f); - param->scaleOut = bone->scaleOut * (!rest ? pchan->scaleOut : 1.0f); + param->scale_in_x = bone->scale_in_x * (!rest ? pchan->scale_in_x : 1.0f); + param->scale_in_y = bone->scale_in_y * (!rest ? pchan->scale_in_y : 1.0f); + param->scale_out_x = bone->scale_out_x * (!rest ? pchan->scale_out_x : 1.0f); + param->scale_out_y = bone->scale_out_y * (!rest ? pchan->scale_out_y : 1.0f); /* Extra curve x / y */ - param->curveInX = bone->curveInX + (!rest ? pchan->curveInX : 0.0f); - param->curveInY = bone->curveInY + (!rest ? pchan->curveInY : 0.0f); + param->curve_in_x = bone->curve_in_x + (!rest ? pchan->curve_in_x : 0.0f); + param->curve_in_y = bone->curve_in_y + (!rest ? pchan->curve_in_y : 0.0f); - param->curveOutX = bone->curveOutX + (!rest ? pchan->curveOutX : 0.0f); - param->curveOutY = bone->curveOutY + (!rest ? pchan->curveOutY : 0.0f); + param->curve_out_x = bone->curve_out_x + (!rest ? pchan->curve_out_x : 0.0f); + param->curve_out_y = bone->curve_out_y + (!rest ? pchan->curve_out_y : 0.0f); } } @@ -713,8 +771,9 @@ void BKE_pchan_bbone_handles_compute(const BBoneSplineParameters *param, h1[1] -= length; } - if (normalize_v3(h1) < epsilon) + if (normalize_v3(h1) < epsilon) { copy_v3_fl3(h1, 0.0f, -1.0f, 0.0f); + } negate_v3(h1); @@ -741,8 +800,9 @@ void BKE_pchan_bbone_handles_compute(const BBoneSplineParameters *param, h2[1] -= length; } - if (normalize_v3(h2) < epsilon) + if (normalize_v3(h2) < epsilon) { copy_v3_fl3(h2, 0.0f, 1.0f, 0.0f); + } /* Find the next roll to interpolate as well. */ copy_m3_m4(mat3, param->next_mat); @@ -785,18 +845,19 @@ void BKE_pchan_bbone_handles_compute(const BBoneSplineParameters *param, *r_roll2 += param->roll2; /* Extra curve x / y */ - /* NOTE: Scale correction factors here are to compensate for some random floating-point glitches - * when scaling up the bone or it's parent by a factor of approximately 8.15/6, which results - * in the bone length getting scaled up too (from 1 to 8), causing the curve to flatten out. + /* NOTE: + * Scale correction factors here are to compensate for some random floating-point glitches + * when scaling up the bone or it's parent by a factor of approximately 8.15/6, which results + * in the bone length getting scaled up too (from 1 to 8), causing the curve to flatten out. */ const float xscale_correction = (param->do_scale) ? param->scale[0] : 1.0f; const float yscale_correction = (param->do_scale) ? param->scale[2] : 1.0f; - h1[0] += param->curveInX * xscale_correction; - h1[2] += param->curveInY * yscale_correction; + h1[0] += param->curve_in_x * xscale_correction; + h1[2] += param->curve_in_y * yscale_correction; - h2[0] += param->curveOutX * xscale_correction; - h2[2] += param->curveOutY * yscale_correction; + h2[0] += param->curve_out_x * xscale_correction; + h2[2] += param->curve_out_y * yscale_correction; } } @@ -805,7 +866,8 @@ static void make_bbone_spline_matrix(BBoneSplineParameters *param, float pos[3], float axis[3], float roll, - float scalefac, + float scalex, + float scaley, float result[4][4]) { float mat3[3][3]; @@ -821,8 +883,8 @@ static void make_bbone_spline_matrix(BBoneSplineParameters *param, } /* BBone scale... */ - mul_v3_fl(result[0], scalefac); - mul_v3_fl(result[2], scalefac); + mul_v3_fl(result[0], scalex); + mul_v3_fl(result[2], scaley); } /* Fade from first to second derivative when the handle is very short. */ @@ -886,17 +948,25 @@ int BKE_pchan_bbone_spline_compute(BBoneSplineParameters *param, /* End points require special handling to fix zero length handles. */ ease_handle_axis(bezt_deriv1[0], bezt_deriv2[0], axis); - make_bbone_spline_matrix( - param, scalemats, bezt_controls[0], axis, roll1, param->scaleIn, result_array[0].mat); + make_bbone_spline_matrix(param, + scalemats, + bezt_controls[0], + axis, + roll1, + param->scale_in_x, + param->scale_in_y, + result_array[0].mat); for (int a = 1; a < param->segments; a++) { evaluate_cubic_bezier(bezt_controls, bezt_points[a], cur, axis); float fac = ((float)a) / param->segments; float roll = interpf(roll2, roll1, fac); - float scalefac = interpf(param->scaleOut, param->scaleIn, fac); + float scalex = interpf(param->scale_out_x, param->scale_in_x, fac); + float scaley = interpf(param->scale_out_y, param->scale_in_y, fac); - make_bbone_spline_matrix(param, scalemats, cur, axis, roll, scalefac, result_array[a].mat); + make_bbone_spline_matrix( + param, scalemats, cur, axis, roll, scalex, scaley, result_array[a].mat); } negate_v3(bezt_deriv2[1]); @@ -906,7 +976,8 @@ int BKE_pchan_bbone_spline_compute(BBoneSplineParameters *param, bezt_controls[3], axis, roll2, - param->scaleOut, + param->scale_out_x, + param->scale_out_y, result_array[param->segments].mat); } /* Other code (e.g. display) uses matrices for the segments themselves. */ @@ -920,9 +991,11 @@ int BKE_pchan_bbone_spline_compute(BBoneSplineParameters *param, float fac = (a + 0.5f) / param->segments; float roll = interpf(roll2, roll1, fac); - float scalefac = interpf(param->scaleOut, param->scaleIn, fac); + float scalex = interpf(param->scale_out_x, param->scale_in_x, fac); + float scaley = interpf(param->scale_out_y, param->scale_in_y, fac); - make_bbone_spline_matrix(param, scalemats, prev, axis, roll, scalefac, result_array[a].mat); + make_bbone_spline_matrix( + param, scalemats, prev, axis, roll, scalex, scaley, result_array[a].mat); copy_v3_v3(prev, cur); } } @@ -932,25 +1005,12 @@ int BKE_pchan_bbone_spline_compute(BBoneSplineParameters *param, /* ************ Armature Deform ******************* */ -typedef struct bPoseChanDeform { - DualQuat *dual_quat; -} bPoseChanDeform; - -/* Definition of cached object bbone deformations. */ -typedef struct ObjectBBoneDeform { - DualQuat *dualquats; - bPoseChanDeform *pdef_info_array; - int num_pchan; -} ObjectBBoneDeform; - static void allocate_bbone_cache(bPoseChannel *pchan, int segments) { bPoseChannel_Runtime *runtime = &pchan->runtime; if (runtime->bbone_segments != segments) { - if (runtime->bbone_segments != 0) { - BKE_pose_channel_free_bbone_cache(pchan); - } + BKE_pose_channel_free_bbone_cache(runtime); runtime->bbone_segments = segments; runtime->bbone_rest_mats = MEM_malloc_arrayN( @@ -1020,7 +1080,7 @@ void BKE_pchan_bbone_segments_cache_copy(bPoseChannel *pchan, bPoseChannel *pcha int segments = runtime_from->bbone_segments; if (segments <= 1) { - BKE_pose_channel_free_bbone_cache(pchan); + BKE_pose_channel_free_bbone_cache(&pchan->runtime); } else { allocate_bbone_cache(pchan, segments); @@ -1036,7 +1096,8 @@ void BKE_pchan_bbone_segments_cache_copy(bPoseChannel *pchan, bPoseChannel *pcha } } -/** Calculate index and blend factor for the two B-Bone segment nodes affecting the point at 0 <= pos <= 1. */ +/** Calculate index and blend factor for the two B-Bone segment nodes + * affecting the point at 0 <= pos <= 1. */ void BKE_pchan_bbone_deform_segment_index(const bPoseChannel *pchan, float pos, int *r_index, @@ -1071,8 +1132,9 @@ static void pchan_deform_accumulate(const DualQuat *deform_dq, DualQuat *dq_accum, float mat_accum[3][3]) { - if (weight == 0.0f) + if (weight == 0.0f) { return; + } if (dq_accum) { BLI_assert(!co_accum); @@ -1154,18 +1216,21 @@ float distfactor_to_bone( rad = a / l; rad = rad * rad2 + (1.0f - rad) * rad1; } - else + else { rad = rad1; + } } a = rad * rad; - if (dist_sq < a) + if (dist_sq < a) { return 1.0f; + } else { l = rad + rdist; l *= l; - if (rdist == 0.0f || dist_sq >= l) + if (rdist == 0.0f || dist_sq >= l) { return 0.0f; + } else { a = sqrtf(dist_sq) - rad; return 1.0f - (a * a) / (rdist * rdist); @@ -1173,18 +1238,15 @@ float distfactor_to_bone( } } -static float dist_bone_deform(bPoseChannel *pchan, - const bPoseChanDeform *pdef_info, - float vec[3], - DualQuat *dq, - float mat[3][3], - const float co[3]) +static float dist_bone_deform( + bPoseChannel *pchan, float vec[3], DualQuat *dq, float mat[3][3], const float co[3]) { Bone *bone = pchan->bone; float fac, contrib = 0.0; - if (bone == NULL) + if (bone == NULL) { return 0.0f; + } fac = distfactor_to_bone( co, bone->arm_head, bone->arm_tail, bone->rad_head, bone->rad_tail, bone->dist); @@ -1193,10 +1255,13 @@ static float dist_bone_deform(bPoseChannel *pchan, fac *= bone->weight; contrib = fac; if (contrib > 0.0f) { - if (bone->segments > 1 && pchan->runtime.bbone_segments == bone->segments) + if (bone->segments > 1 && pchan->runtime.bbone_segments == bone->segments) { b_bone_deform(pchan, co, fac, vec, dq, mat); - else - pchan_deform_accumulate(pdef_info->dual_quat, pchan->chan_mat, co, fac, vec, dq, mat); + } + else { + pchan_deform_accumulate( + &pchan->runtime.deform_dual_quat, pchan->chan_mat, co, fac, vec, dq, mat); + } } } @@ -1204,7 +1269,6 @@ static float dist_bone_deform(bPoseChannel *pchan, } static void pchan_bone_deform(bPoseChannel *pchan, - const bPoseChanDeform *pdef_info, float weight, float vec[3], DualQuat *dq, @@ -1214,37 +1278,224 @@ static void pchan_bone_deform(bPoseChannel *pchan, { Bone *bone = pchan->bone; - if (!weight) + if (!weight) { return; + } - if (bone->segments > 1 && pchan->runtime.bbone_segments == bone->segments) + if (bone->segments > 1 && pchan->runtime.bbone_segments == bone->segments) { b_bone_deform(pchan, co, weight, vec, dq, mat); - else - pchan_deform_accumulate(pdef_info->dual_quat, pchan->chan_mat, co, weight, vec, dq, mat); + } + else { + pchan_deform_accumulate( + &pchan->runtime.deform_dual_quat, pchan->chan_mat, co, weight, vec, dq, mat); + } (*contrib) += weight; } -typedef struct ArmatureBBoneDefmatsData { - bPoseChanDeform *pdef_info_array; - DualQuat *dualquats; +typedef struct ArmatureUserdata { + Object *armOb; + Object *target; + const Mesh *mesh; + float (*vertexCos)[3]; + float (*defMats)[3][3]; + float (*prevCos)[3]; + + bool use_envelope; bool use_quaternion; -} ArmatureBBoneDefmatsData; + bool invert_vgroup; + bool use_dverts; + + int armature_def_nr; -static void armature_bbone_defmats_cb(void *userdata, Link *iter, int index) + int target_totvert; + MDeformVert *dverts; + + int defbase_tot; + bPoseChannel **defnrToPC; + + float premat[4][4]; + float postmat[4][4]; +} ArmatureUserdata; + +static void armature_vert_task(void *__restrict userdata, + const int i, + const ParallelRangeTLS *__restrict UNUSED(tls)) { - ArmatureBBoneDefmatsData *data = userdata; - bPoseChannel *pchan = (bPoseChannel *)iter; + const ArmatureUserdata *data = userdata; + float(*const vertexCos)[3] = data->vertexCos; + float(*const defMats)[3][3] = data->defMats; + float(*const prevCos)[3] = data->prevCos; + const bool use_envelope = data->use_envelope; + const bool use_quaternion = data->use_quaternion; + const bool use_dverts = data->use_dverts; + const int armature_def_nr = data->armature_def_nr; - if (!(pchan->bone->flag & BONE_NO_DEFORM)) { - bPoseChanDeform *pdef_info = &data->pdef_info_array[index]; - const bool use_quaternion = data->use_quaternion; + MDeformVert *dvert; + DualQuat sumdq, *dq = NULL; + bPoseChannel *pchan; + float *co, dco[3]; + float sumvec[3], summat[3][3]; + float *vec = NULL, (*smat)[3] = NULL; + float contrib = 0.0f; + float armature_weight = 1.0f; /* default to 1 if no overall def group */ + float prevco_weight = 1.0f; /* weight for optional cached vertexcos */ + if (use_quaternion) { + memset(&sumdq, 0, sizeof(DualQuat)); + dq = &sumdq; + } + else { + sumvec[0] = sumvec[1] = sumvec[2] = 0.0f; + vec = sumvec; + + if (defMats) { + zero_m3(summat); + smat = summat; + } + } + + if (use_dverts || armature_def_nr != -1) { + if (data->mesh) { + BLI_assert(i < data->mesh->totvert); + dvert = data->mesh->dvert + i; + } + else if (data->dverts && i < data->target_totvert) { + dvert = data->dverts + i; + } + else { + dvert = NULL; + } + } + else { + dvert = NULL; + } + + if (armature_def_nr != -1 && dvert) { + armature_weight = defvert_find_weight(dvert, armature_def_nr); + + if (data->invert_vgroup) { + armature_weight = 1.0f - armature_weight; + } + + /* hackish: the blending factor can be used for blending with prevCos too */ + if (prevCos) { + prevco_weight = armature_weight; + armature_weight = 1.0f; + } + } + + /* check if there's any point in calculating for this vert */ + if (armature_weight == 0.0f) { + return; + } + + /* get the coord we work on */ + co = prevCos ? prevCos[i] : vertexCos[i]; + + /* Apply the object's matrix */ + mul_m4_v3(data->premat, co); + + if (use_dverts && dvert && dvert->totweight) { /* use weight groups ? */ + MDeformWeight *dw = dvert->dw; + int deformed = 0; + unsigned int j; + float acum_weight = 0; + for (j = dvert->totweight; j != 0; j--, dw++) { + const int index = dw->def_nr; + if (index >= 0 && index < data->defbase_tot && (pchan = data->defnrToPC[index])) { + float weight = dw->weight; + Bone *bone = pchan->bone; + + deformed = 1; + + if (bone && bone->flag & BONE_MULT_VG_ENV) { + weight *= distfactor_to_bone( + co, bone->arm_head, bone->arm_tail, bone->rad_head, bone->rad_tail, bone->dist); + } + + /* check limit of weight */ + if (data->target->type == OB_GPENCIL) { + if (acum_weight + weight >= 1.0f) { + weight = 1.0f - acum_weight; + } + acum_weight += weight; + } + + pchan_bone_deform(pchan, weight, vec, dq, smat, co, &contrib); + + /* if acumulated weight limit exceed, exit loop */ + if ((data->target->type == OB_GPENCIL) && (acum_weight >= 1.0f)) { + break; + } + } + } + /* if there are vertexgroups but not groups with bones + * (like for softbody groups) */ + if (deformed == 0 && use_envelope) { + for (pchan = data->armOb->pose->chanbase.first; pchan; pchan = pchan->next) { + if (!(pchan->bone->flag & BONE_NO_DEFORM)) { + contrib += dist_bone_deform(pchan, vec, dq, smat, co); + } + } + } + } + else if (use_envelope) { + for (pchan = data->armOb->pose->chanbase.first; pchan; pchan = pchan->next) { + if (!(pchan->bone->flag & BONE_NO_DEFORM)) { + contrib += dist_bone_deform(pchan, vec, dq, smat, co); + } + } + } + + /* actually should be EPSILON? weight values and contrib can be like 10e-39 small */ + if (contrib > 0.0001f) { if (use_quaternion) { - pdef_info->dual_quat = &data->dualquats[index]; - mat4_to_dquat(pdef_info->dual_quat, pchan->bone->arm_mat, pchan->chan_mat); + normalize_dq(dq, contrib); + + if (armature_weight != 1.0f) { + copy_v3_v3(dco, co); + mul_v3m3_dq(dco, (defMats) ? summat : NULL, dq); + sub_v3_v3(dco, co); + mul_v3_fl(dco, armature_weight); + add_v3_v3(co, dco); + } + else { + mul_v3m3_dq(co, (defMats) ? summat : NULL, dq); + } + + smat = summat; + } + else { + mul_v3_fl(vec, armature_weight / contrib); + add_v3_v3v3(co, vec, co); + } + + if (defMats) { + float pre[3][3], post[3][3], tmpmat[3][3]; + + copy_m3_m4(pre, data->premat); + copy_m3_m4(post, data->postmat); + copy_m3_m3(tmpmat, defMats[i]); + + if (!use_quaternion) { /* quaternion already is scale corrected */ + mul_m3_fl(smat, armature_weight / contrib); + } + + mul_m3_series(defMats[i], post, smat, pre, tmpmat); } } + + /* always, check above code */ + mul_m4_v3(data->postmat, co); + + /* interpolate with previous modifier position using weight group */ + if (prevCos) { + float mw = 1.0f - prevco_weight; + vertexCos[i][0] = prevco_weight * vertexCos[i][0] + mw * co[0]; + vertexCos[i][1] = prevco_weight * vertexCos[i][1] + mw * co[1]; + vertexCos[i][2] = prevco_weight * vertexCos[i][2] + mw * co[2]; + } } void armature_deform_verts(Object *armOb, @@ -1258,13 +1509,10 @@ void armature_deform_verts(Object *armOb, const char *defgrp_name, bGPDstroke *gps) { - const bPoseChanDeform *pdef_info = NULL; bArmature *arm = armOb->data; - bPoseChannel *pchan, **defnrToPC = NULL; - int *defnrToPCIndex = NULL; + bPoseChannel **defnrToPC = NULL; MDeformVert *dverts = NULL; bDeformGroup *dg; - float obinv[4][4], premat[4][4], postmat[4][4]; const bool use_envelope = (deformflag & ARM_DEF_ENVELOPE) != 0; const bool use_quaternion = (deformflag & ARM_DEF_QUATERNION) != 0; const bool invert_vgroup = (deformflag & ARM_DEF_INVERT_VGROUP) != 0; @@ -1285,25 +1533,6 @@ void armature_deform_verts(Object *armOb, BLI_assert(0); } - invert_m4_m4(obinv, target->obmat); - copy_m4_m4(premat, target->obmat); - mul_m4_m4m4(postmat, obinv, armOb->obmat); - invert_m4_m4(premat, postmat); - - /* Use pre-calculated bbone deformation. - * - * TODO(sergey): Make this code robust somehow when there are dependency - * cycles involved. */ - ObjectBBoneDeform *bbone_deform = BKE_armature_cached_bbone_deformation_get(armOb); - if (bbone_deform == NULL || bbone_deform->pdef_info_array == NULL) { - CLOG_ERROR(&LOG, - "Armature does not have bbone cache %s, " - "usually happens due to a dependency cycle.\n", - armOb->id.name + 2); - return; - } - const bPoseChanDeform *pdef_info_array = bbone_deform->pdef_info_array; - /* get the def_nr for the overall armature vertex group if present */ armature_def_nr = defgroup_name_index(target, defgrp_name); @@ -1313,19 +1542,22 @@ void armature_deform_verts(Object *armOb, if (target->type == OB_MESH) { Mesh *me = target->data; dverts = me->dvert; - if (dverts) + if (dverts) { target_totvert = me->totvert; + } } else if (target->type == OB_LATTICE) { Lattice *lt = target->data; dverts = lt->dvert; - if (dverts) + if (dverts) { target_totvert = lt->pntsu * lt->pntsv * lt->pntsw; + } } else if (target->type == OB_GPENCIL) { dverts = gps->dvert; - if (dverts) + if (dverts) { target_totvert = gps->totpoints; + } } } @@ -1342,19 +1574,10 @@ void armature_deform_verts(Object *armOb, if (use_dverts) { defnrToPC = MEM_callocN(sizeof(*defnrToPC) * defbase_tot, "defnrToBone"); - defnrToPCIndex = MEM_callocN(sizeof(*defnrToPCIndex) * defbase_tot, "defnrToIndex"); /* TODO(sergey): Some considerations here: * - * - Make it more generic function, maybe even keep together with chanhash. * - Check whether keeping this consistent across frames gives speedup. - * - Don't use hash for small armatures. */ - GHash *idx_hash = BLI_ghash_ptr_new("pose channel index by name"); - int pchan_index = 0; - for (pchan = armOb->pose->chanbase.first; pchan != NULL; - pchan = pchan->next, ++pchan_index) { - BLI_ghash_insert(idx_hash, pchan, POINTER_FROM_INT(pchan_index)); - } for (i = 0, dg = target->defbase.first; dg; i++, dg = dg->next) { defnrToPC[i] = BKE_pose_channel_find_name(armOb->pose, dg->name); /* exclude non-deforming bones */ @@ -1362,181 +1585,42 @@ void armature_deform_verts(Object *armOb, if (defnrToPC[i]->bone->flag & BONE_NO_DEFORM) { defnrToPC[i] = NULL; } - else { - defnrToPCIndex[i] = POINTER_AS_INT(BLI_ghash_lookup(idx_hash, defnrToPC[i])); - } } } - BLI_ghash_free(idx_hash, NULL, NULL); } } } - for (i = 0; i < numVerts; i++) { - MDeformVert *dvert; - DualQuat sumdq, *dq = NULL; - float *co, dco[3]; - float sumvec[3], summat[3][3]; - float *vec = NULL, (*smat)[3] = NULL; - float contrib = 0.0f; - float armature_weight = 1.0f; /* default to 1 if no overall def group */ - float prevco_weight = 1.0f; /* weight for optional cached vertexcos */ - - if (use_quaternion) { - memset(&sumdq, 0, sizeof(DualQuat)); - dq = &sumdq; - } - else { - sumvec[0] = sumvec[1] = sumvec[2] = 0.0f; - vec = sumvec; - - if (defMats) { - zero_m3(summat); - smat = summat; - } - } - - if (use_dverts || armature_def_nr != -1) { - if (mesh) { - BLI_assert(i < mesh->totvert); - dvert = mesh->dvert + i; - } - else if (dverts && i < target_totvert) - dvert = dverts + i; - else - dvert = NULL; - } - else - dvert = NULL; - - if (armature_def_nr != -1 && dvert) { - armature_weight = defvert_find_weight(dvert, armature_def_nr); - - if (invert_vgroup) - armature_weight = 1.0f - armature_weight; - - /* hackish: the blending factor can be used for blending with prevCos too */ - if (prevCos) { - prevco_weight = armature_weight; - armature_weight = 1.0f; - } - } - - /* check if there's any point in calculating for this vert */ - if (armature_weight == 0.0f) - continue; - - /* get the coord we work on */ - co = prevCos ? prevCos[i] : vertexCos[i]; - - /* Apply the object's matrix */ - mul_m4_v3(premat, co); - - if (use_dverts && dvert && dvert->totweight) { /* use weight groups ? */ - MDeformWeight *dw = dvert->dw; - int deformed = 0; - unsigned int j; - float acum_weight = 0; - for (j = dvert->totweight; j != 0; j--, dw++) { - const int index = dw->def_nr; - if (index >= 0 && index < defbase_tot && (pchan = defnrToPC[index])) { - float weight = dw->weight; - Bone *bone = pchan->bone; - pdef_info = pdef_info_array + defnrToPCIndex[index]; - - deformed = 1; - - if (bone && bone->flag & BONE_MULT_VG_ENV) { - weight *= distfactor_to_bone( - co, bone->arm_head, bone->arm_tail, bone->rad_head, bone->rad_tail, bone->dist); - } - - /* check limit of weight */ - if (target->type == OB_GPENCIL) { - if (acum_weight + weight >= 1.0f) { - weight = 1.0f - acum_weight; - } - acum_weight += weight; - } - - pchan_bone_deform(pchan, pdef_info, weight, vec, dq, smat, co, &contrib); - - /* if acumulated weight limit exceed, exit loop */ - if ((target->type == OB_GPENCIL) && (acum_weight >= 1.0f)) { - break; - } - } - } - /* if there are vertexgroups but not groups with bones - * (like for softbody groups) */ - if (deformed == 0 && use_envelope) { - pdef_info = pdef_info_array; - for (pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next, pdef_info++) { - if (!(pchan->bone->flag & BONE_NO_DEFORM)) - contrib += dist_bone_deform(pchan, pdef_info, vec, dq, smat, co); - } - } - } - else if (use_envelope) { - pdef_info = pdef_info_array; - for (pchan = armOb->pose->chanbase.first; pchan; pchan = pchan->next, pdef_info++) { - if (!(pchan->bone->flag & BONE_NO_DEFORM)) - contrib += dist_bone_deform(pchan, pdef_info, vec, dq, smat, co); - } - } - - /* actually should be EPSILON? weight values and contrib can be like 10e-39 small */ - if (contrib > 0.0001f) { - if (use_quaternion) { - normalize_dq(dq, contrib); - - if (armature_weight != 1.0f) { - copy_v3_v3(dco, co); - mul_v3m3_dq(dco, (defMats) ? summat : NULL, dq); - sub_v3_v3(dco, co); - mul_v3_fl(dco, armature_weight); - add_v3_v3(co, dco); - } - else - mul_v3m3_dq(co, (defMats) ? summat : NULL, dq); - - smat = summat; - } - else { - mul_v3_fl(vec, armature_weight / contrib); - add_v3_v3v3(co, vec, co); - } - - if (defMats) { - float pre[3][3], post[3][3], tmpmat[3][3]; - - copy_m3_m4(pre, premat); - copy_m3_m4(post, postmat); - copy_m3_m3(tmpmat, defMats[i]); + ArmatureUserdata data = {.armOb = armOb, + .target = target, + .mesh = mesh, + .vertexCos = vertexCos, + .defMats = defMats, + .prevCos = prevCos, + .use_envelope = use_envelope, + .use_quaternion = use_quaternion, + .invert_vgroup = invert_vgroup, + .use_dverts = use_dverts, + .armature_def_nr = armature_def_nr, + .target_totvert = target_totvert, + .dverts = dverts, + .defbase_tot = defbase_tot, + .defnrToPC = defnrToPC}; + + float obinv[4][4]; + invert_m4_m4(obinv, target->obmat); - if (!use_quaternion) /* quaternion already is scale corrected */ - mul_m3_fl(smat, armature_weight / contrib); + mul_m4_m4m4(data.postmat, obinv, armOb->obmat); + invert_m4_m4(data.premat, data.postmat); - mul_m3_series(defMats[i], post, smat, pre, tmpmat); - } - } + ParallelRangeSettings settings; + BLI_parallel_range_settings_defaults(&settings); + settings.min_iter_per_thread = 32; + BLI_task_parallel_range(0, numVerts, &data, armature_vert_task, &settings); - /* always, check above code */ - mul_m4_v3(postmat, co); - - /* interpolate with previous modifier position using weight group */ - if (prevCos) { - float mw = 1.0f - prevco_weight; - vertexCos[i][0] = prevco_weight * vertexCos[i][0] + mw * co[0]; - vertexCos[i][1] = prevco_weight * vertexCos[i][1] + mw * co[1]; - vertexCos[i][2] = prevco_weight * vertexCos[i][2] + mw * co[2]; - } - } - - if (defnrToPC) + if (defnrToPC) { MEM_freeN(defnrToPC); - if (defnrToPCIndex) - MEM_freeN(defnrToPCIndex); + } } /* ************ END Armature Deform ******************* */ @@ -1557,8 +1641,9 @@ void BKE_armature_mat_world_to_pose(Object *ob, float inmat[4][4], float outmat[ float obmat[4][4]; /* prevent crashes */ - if (ob == NULL) + if (ob == NULL) { return; + } /* get inverse of (armature) object's matrix */ invert_m4_m4(obmat, ob->obmat); @@ -1600,13 +1685,14 @@ void BKE_bone_offset_matrix_get(const Bone *bone, float offs_bone[4][4]) offs_bone[3][1] += bone->parent->length; } -/* Construct the matrices (rot/scale and loc) to apply the PoseChannels into the armature (object) space. +/* Construct the matrices (rot/scale and loc) + * to apply the PoseChannels into the armature (object) space. * I.e. (roughly) the "pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b)" in the * pose_mat(b)= pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b) * ...function. * - * This allows to get the transformations of a bone in its object space, *before* constraints (and IK) - * get applied (used by pose evaluation code). + * This allows to get the transformations of a bone in its object space, + * *before* constraints (and IK) get applied (used by pose evaluation code). * And reverse: to find pchan transformations needed to place a bone at a given loc/rot/scale * in object space (used by interactive transform, and snapping code). * @@ -1679,8 +1765,9 @@ void BKE_bone_parent_transform_calc_from_matrices(int bone_flag, normalize_m4(tmat); mul_m4_m4m4(r_bpt->rotscale_mat, tmat, offs_bone); } - else + else { mul_m4_m4m4(r_bpt->rotscale_mat, parent_pose_mat, offs_bone); + } /* Compose the loc matrix for this bone. */ /* NOTE: That version does not modify bone's loc when HINGE/NO_SCALE options are set. */ @@ -1706,9 +1793,11 @@ void BKE_bone_parent_transform_calc_from_matrices(int bone_flag, else if (bone_flag & (BONE_HINGE | BONE_NO_SCALE)) { mul_m4_m4m4(r_bpt->loc_mat, parent_pose_mat, offs_bone); } - /* Else (i.e. default, usual case), just use the same matrix for rotation/scaling, and location. */ - else + /* Else (i.e. default, usual case), + * just use the same matrix for rotation/scaling, and location. */ + else { copy_m4_m4(r_bpt->loc_mat, r_bpt->rotscale_mat); + } } /* Root bones. */ else { @@ -1720,8 +1809,9 @@ void BKE_bone_parent_transform_calc_from_matrices(int bone_flag, unit_m4(r_bpt->loc_mat); copy_v3_v3(r_bpt->loc_mat[3], offs_bone[3]); } - else + else { copy_m4_m4(r_bpt->loc_mat, r_bpt->rotscale_mat); + } } } @@ -1831,15 +1921,44 @@ void BKE_pchan_mat3_to_rot(bPoseChannel *pchan, float mat[3][3], bool use_compat mat3_normalized_to_axis_angle(pchan->rotAxis, &pchan->rotAngle, mat); break; default: /* euler */ - if (use_compat) + if (use_compat) { mat3_normalized_to_compatible_eulO(pchan->eul, pchan->eul, pchan->rotmode, mat); - else + } + else { mat3_normalized_to_eulO(pchan->eul, pchan->rotmode, mat); + } break; } } /** + * Same as #BKE_object_rot_to_mat3(). + */ +void BKE_pchan_rot_to_mat3(const bPoseChannel *pchan, float mat[3][3]) +{ + /* rotations may either be quats, eulers (with various rotation orders), or axis-angle */ + if (pchan->rotmode > 0) { + /* euler rotations (will cause gimble lock, + * but this can be alleviated a bit with rotation orders) */ + eulO_to_mat3(mat, pchan->eul, pchan->rotmode); + } + else if (pchan->rotmode == ROT_MODE_AXISANGLE) { + /* axis-angle - not really that great for 3D-changing orientations */ + axis_angle_to_mat3(mat, pchan->rotAxis, pchan->rotAngle); + } + else { + /* quats are normalized before use to eliminate scaling issues */ + float quat[4]; + + /* NOTE: we now don't normalize the stored values anymore, + * since this was kindof evil in some cases but if this proves to be too problematic, + * switch back to the old system of operating directly on the stored copy. */ + normalize_qt_qt(quat, pchan->quat); + quat_to_mat3(mat, quat); + } +} + +/** * Apply a 4x4 matrix to the pose bone, * similar to #BKE_object_apply_mat4(). */ @@ -1909,7 +2028,8 @@ void BKE_rotMode_change_values( quat_to_axis_angle(axis, angle, quat); } - /* when converting to axis-angle, we need a special exception for the case when there is no axis */ + /* When converting to axis-angle, + * we need a special exception for the case when there is no axis. */ if (IS_EQF(axis[0], axis[1]) && IS_EQF(axis[1], axis[2])) { /* for now, rotate around y-axis then (so that it simply becomes the roll) */ axis[1] = 1.0f; @@ -1964,50 +2084,72 @@ void mat3_vec_to_roll(const float mat[3][3], const float vec[3], float *r_roll) } /* Calculates the rest matrix of a bone based on its vector and a roll around that vector. */ -/* Given v = (v.x, v.y, v.z) our (normalized) bone vector, we want the rotation matrix M - * from the Y axis (so that M * (0, 1, 0) = v). - * -> The rotation axis a lays on XZ plane, and it is orthonormal to v, hence to the projection of v onto XZ plane. - * -> a = (v.z, 0, -v.x) +/** + * Given `v = (v.x, v.y, v.z)` our (normalized) bone vector, we want the rotation matrix M + * from the Y axis (so that `M * (0, 1, 0) = v`). + * - The rotation axis a lays on XZ plane, and it is orthonormal to v, + * hence to the projection of v onto XZ plane. + * - `a = (v.z, 0, -v.x)` + * * We know a is eigenvector of M (so M * a = a). - * Finally, we have w, such that M * w = (0, 1, 0) (i.e. the vector that will be aligned with Y axis once transformed). + * Finally, we have w, such that M * w = (0, 1, 0) + * (i.e. the vector that will be aligned with Y axis once transformed). * We know w is symmetric to v by the Y axis. - * -> w = (-v.x, v.y, -v.z) + * - `w = (-v.x, v.y, -v.z)` * * Solving this, we get (x, y and z being the components of v): + * <pre> * ┌ (x^2 * y + z^2) / (x^2 + z^2), x, x * z * (y - 1) / (x^2 + z^2) ┐ * M = │ x * (y^2 - 1) / (x^2 + z^2), y, z * (y^2 - 1) / (x^2 + z^2) │ * └ x * z * (y - 1) / (x^2 + z^2), z, (x^2 + z^2 * y) / (x^2 + z^2) ┘ + * </pre> + * + * This is stable as long as v (the bone) is not too much aligned with +/-Y + * (i.e. x and z components are not too close to 0). * - * This is stable as long as v (the bone) is not too much aligned with +/-Y (i.e. x and z components - * are not too close to 0). + * Since v is normalized, we have `x^2 + y^2 + z^2 = 1`, + * hence `x^2 + z^2 = 1 - y^2 = (1 - y)(1 + y)`. * - * Since v is normalized, we have x^2 + y^2 + z^2 = 1, hence x^2 + z^2 = 1 - y^2 = (1 - y)(1 + y). * This allows to simplifies M like this: + * <pre> * ┌ 1 - x^2 / (1 + y), x, -x * z / (1 + y) ┐ * M = │ -x, y, -z │ * └ -x * z / (1 + y), z, 1 - z^2 / (1 + y) ┘ + * </pre> * - * Written this way, we see the case v = +Y is no more a singularity. The only one remaining is the bone being - * aligned with -Y. + * Written this way, we see the case v = +Y is no more a singularity. + * The only one + * remaining is the bone being aligned with -Y. * - * Let's handle the asymptotic behavior when bone vector is reaching the limit of y = -1. Each of the four corner - * elements can vary from -1 to 1, depending on the axis a chosen for doing the rotation. And the "rotation" here - * is in fact established by mirroring XZ plane by that given axis, then inversing the Y-axis. - * For sufficiently small x and z, and with y approaching -1, all elements but the four corner ones of M - * will degenerate. So let's now focus on these corner elements. + * Let's handle + * the asymptotic behavior when bone vector is reaching the limit of y = -1. + * Each of the four corner elements can vary from -1 to 1, + * depending on the axis a chosen for doing the rotation. + * And the "rotation" here is in fact established by mirroring XZ plane by that given axis, + * then inversing the Y-axis. + * For sufficiently small x and z, and with y approaching -1, + * all elements but the four corner ones of M will degenerate. + * So let's now focus on these corner elements. * - * We rewrite M so that it only contains its four corner elements, and combine the 1 / (1 + y) factor: + * We rewrite M so that it only contains its four corner elements, + * and combine the `1 / (1 + y)` factor: + * <pre> * ┌ 1 + y - x^2, -x * z ┐ * M* = 1 / (1 + y) * │ │ * └ -x * z, 1 + y - z^2 ┘ + * </pre> + * + * When y is close to -1, computing 1 / (1 + y) will cause severe numerical instability, + * so we ignore it and normalize M instead. + * We know `y^2 = 1 - (x^2 + z^2)`, and `y < 0`, hence `y = -sqrt(1 - (x^2 + z^2))`. * - * When y is close to -1, computing 1 / (1 + y) will cause severe numerical instability, so we ignore it and - * normalize M instead. We know y^2 = 1 - (x^2 + z^2), and y < 0, hence y = -sqrt(1 - (x^2 + z^2)). * Since x and z are both close to 0, we apply the binomial expansion to the first order: - * y = -sqrt(1 - (x^2 + z^2)) = -1 + (x^2 + z^2) / 2. Which gives: + * `y = -sqrt(1 - (x^2 + z^2)) = -1 + (x^2 + z^2) / 2`. Which gives: + * <pre> * ┌ z^2 - x^2, -2 * x * z ┐ * M* = 1 / (x^2 + z^2) * │ │ * └ -2 * x * z, x^2 - z^2 ┘ + * </pre> */ void vec_roll_to_mat3_normalized(const float nor[3], const float roll, float mat[3][3]) { @@ -2138,8 +2280,9 @@ static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected bConstraint *con; int error = 0; - if (frompose == NULL) + if (frompose == NULL) { return; + } /* in some cases when rigs change, we cant synchronize * to avoid crashing check for possible errors here */ @@ -2155,8 +2298,9 @@ static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected } } - if (error) + if (error) { return; + } /* clear all transformation values from library */ BKE_pose_rest(frompose); @@ -2205,13 +2349,14 @@ static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected } } - /* constraints - proxy constraints are flushed... local ones are added after - * 1. extract constraints not from proxy (CONSTRAINT_PROXY_LOCAL) from pchan's constraints - * 2. copy proxy-pchan's constraints on-to new - * 3. add extracted local constraints back on top + /* Constraints - proxy constraints are flushed... local ones are added after + * 1: extract constraints not from proxy (CONSTRAINT_PROXY_LOCAL) from pchan's constraints. + * 2: copy proxy-pchan's constraints on-to new. + * 3: add extracted local constraints back on top. * - * Note for BKE_constraints_copy: when copying constraints, disable 'do_extern' otherwise - * we get the libs direct linked in this blend. + * Note for BKE_constraints_copy: + * When copying constraints, disable 'do_extern' otherwise + * we get the libs direct linked in this blend. */ BKE_constraints_proxylocal_extract(&proxylocal_constraints, &pchan->constraints); BKE_constraints_copy(&pchanw.constraints, &pchanp->constraints, false); @@ -2227,12 +2372,14 @@ static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected cti->get_constraint_targets(con, &targets); for (ct = targets.first; ct; ct = ct->next) { - if (ct->tar == from) + if (ct->tar == from) { ct->tar = ob; + } } - if (cti->flush_constraint_targets) + if (cti->flush_constraint_targets) { cti->flush_constraint_targets(con, &targets, 0); + } } } @@ -2251,8 +2398,9 @@ static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected if (pchan->custom) { id_us_plus(&pchan->custom->id); } - if (pchanp->custom_tx) + if (pchanp->custom_tx) { pchan->custom_tx = BKE_pose_channel_find_name(pose, pchanp->custom_tx->name); + } /* ID-Property Syncing */ { @@ -2288,15 +2436,17 @@ static int rebuild_pose_bone(bPose *pose, Bone *bone, bPoseChannel *parchan, int for (bone = bone->childbase.first; bone; bone = bone->next) { counter = rebuild_pose_bone(pose, bone, pchan, counter); /* for quick detecting of next bone in chain, only b-bone uses it now */ - if (bone->flag & BONE_CONNECTED) + if (bone->flag & BONE_CONNECTED) { pchan->child = BKE_pose_channel_find_name(pose, bone->name); + } } return counter; } /** - * Clear pointers of object's pose (needed in remap case, since we cannot always wait for a complete pose rebuild). + * Clear pointers of object's pose + * (needed in remap case, since we cannot always wait for a complete pose rebuild). */ void BKE_pose_clear_pointers(bPose *pose) { @@ -2382,7 +2532,8 @@ void BKE_pose_rebuild(Main *bmain, Object *ob, bArmature *arm, const bool do_id_ /* synchronize protected layers with proxy */ /* HACK! To preserve 2.7x behavior that you always can pose even locked bones, * do not do any restoration if this is a COW temp copy! */ - /* Switched back to just NO_MAIN tag, for some reasons (c) using COW tag was working this morning, but not anymore... */ + /* Switched back to just NO_MAIN tag, for some reasons (c) + * using COW tag was working this morning, but not anymore... */ if (ob->proxy != NULL && (ob->id.tag & LIB_TAG_NO_MAIN) == 0) { BKE_object_copy_proxy_drivers(ob, ob->proxy); pose_proxy_synchronize(ob, ob->proxy, arm->layer_protected); @@ -2393,7 +2544,8 @@ void BKE_pose_rebuild(Main *bmain, Object *ob, bArmature *arm, const bool do_id_ pose->flag &= ~POSE_RECALC; pose->flag |= POSE_WAS_REBUILT; - /* Rebuilding poses forces us to also rebuild the dependency graph, since there is one node per pose/bone... */ + /* Rebuilding poses forces us to also rebuild the dependency graph, + * since there is one node per pose/bone. */ if (bmain != NULL) { DEG_relations_tag_update(bmain); } @@ -2402,7 +2554,7 @@ void BKE_pose_rebuild(Main *bmain, Object *ob, bArmature *arm, const bool do_id_ /* ********************** THE POSE SOLVER ******************* */ /* loc/rot/size to given mat4 */ -void BKE_pchan_to_mat4(bPoseChannel *pchan, float chan_mat[4][4]) +void BKE_pchan_to_mat4(const bPoseChannel *pchan, float chan_mat[4][4]) { float smat[3][3]; float rmat[3][3]; @@ -2411,26 +2563,8 @@ void BKE_pchan_to_mat4(bPoseChannel *pchan, float chan_mat[4][4]) /* get scaling matrix */ size_to_mat3(smat, pchan->size); - /* rotations may either be quats, eulers (with various rotation orders), or axis-angle */ - if (pchan->rotmode > 0) { - /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */ - eulO_to_mat3(rmat, pchan->eul, pchan->rotmode); - } - else if (pchan->rotmode == ROT_MODE_AXISANGLE) { - /* axis-angle - not really that great for 3D-changing orientations */ - axis_angle_to_mat3(rmat, pchan->rotAxis, pchan->rotAngle); - } - else { - /* quats are normalized before use to eliminate scaling issues */ - float quat[4]; - - /* NOTE: we now don't normalize the stored values anymore, since this was kindof evil in some cases - * but if this proves to be too problematic, switch back to the old system of operating directly on - * the stored copy - */ - normalize_qt_qt(quat, pchan->quat); - quat_to_mat3(rmat, quat); - } + /* get rotation matrix */ + BKE_pchan_rot_to_mat3(pchan, rmat); /* calculate matrix of bone (as 3x3 matrix, but then copy the 4x4) */ mul_m3_m3m3(tmat, rmat, smat); @@ -2475,10 +2609,12 @@ void BKE_pose_where_is_bone(struct Depsgraph *depsgraph, bool do_extra) { /* This gives a chan_mat with actions (ipos) results. */ - if (do_extra) + if (do_extra) { BKE_pchan_calc_mat(pchan); - else + } + else { unit_m4(pchan->chan_mat); + } /* Construct the posemat based on PoseChannels, that we do before applying constraints. */ /* pose_mat(b) = pose_mat(b-1) * yoffs(b-1) * d_root(b) * bone_mat(b) * chan_mat(b) */ @@ -2487,8 +2623,9 @@ void BKE_pose_where_is_bone(struct Depsgraph *depsgraph, /* Only rootbones get the cyclic offset (unless user doesn't want that). */ /* XXX That could be a problem for snapping and other "reverse transform" features... */ if (!pchan->parent) { - if ((pchan->bone->flag & BONE_NO_CYCLICOFFSET) == 0) + if ((pchan->bone->flag & BONE_NO_CYCLICOFFSET) == 0) { add_v3_v3(pchan->pose_mat[3], ob->pose->cyclic_offset); + } } if (do_extra) { @@ -2537,14 +2674,17 @@ void BKE_pose_where_is(struct Depsgraph *depsgraph, Scene *scene, Object *ob) float imat[4][4]; float ctime; - if (ob->type != OB_ARMATURE) + if (ob->type != OB_ARMATURE) { return; + } arm = ob->data; - if (ELEM(NULL, arm, scene)) + if (ELEM(NULL, arm, scene)) { return; + } if ((ob->pose == NULL) || (ob->pose->flag & POSE_RECALC)) { - /* WARNING! passing NULL bmain here means we won't tag depsgraph's as dirty - hopefully this is OK. */ + /* WARNING! passing NULL bmain here means we won't tag depsgraph's as dirty - + * hopefully this is OK. */ BKE_pose_rebuild(NULL, ob, arm, true); } @@ -2611,7 +2751,8 @@ static int minmax_armature(Object *ob, float r_min[3], float r_max[3]) { bPoseChannel *pchan; - /* For now, we assume BKE_pose_where_is has already been called (hence we have valid data in pachan). */ + /* For now, we assume BKE_pose_where_is has already been called + * (hence we have valid data in pachan). */ for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) { minmax_v3v3_v3(r_min, r_max, pchan->pose_head); minmax_v3v3_v3(r_min, r_max, pchan->pose_tail); @@ -2726,70 +2867,3 @@ bPoseChannel *BKE_armature_splineik_solver_find_root(bPoseChannel *pchan, } return rootchan; } - -/* ****************************** BBone cache ****************************** */ - -ObjectBBoneDeform *BKE_armature_cached_bbone_deformation_get(Object *object) -{ - return object->runtime.cached_bbone_deformation; -} - -void BKE_armature_cached_bbone_deformation_free_data(Object *object) -{ - ObjectBBoneDeform *bbone_deform = BKE_armature_cached_bbone_deformation_get(object); - if (bbone_deform == NULL) { - return; - } - /* Free arrays. */ - MEM_SAFE_FREE(bbone_deform->pdef_info_array); - MEM_SAFE_FREE(bbone_deform->dualquats); - /* Tag that we've got no data, so we are safe for sequential calls to - * data free. */ - bbone_deform->num_pchan = 0; -} - -void BKE_armature_cached_bbone_deformation_free(Object *object) -{ - ObjectBBoneDeform *bbone_deform = BKE_armature_cached_bbone_deformation_get(object); - if (bbone_deform == NULL) { - return; - } - BKE_armature_cached_bbone_deformation_free_data(object); - MEM_freeN(bbone_deform); - object->runtime.cached_bbone_deformation = NULL; -} - -void BKE_armature_cached_bbone_deformation_update(Object *object) -{ - BLI_assert(object->type == OB_ARMATURE); - BLI_assert(object->pose != NULL); - bPose *pose = object->pose; - const int totchan = BLI_listbase_count(&pose->chanbase); - const bool use_quaternion = true; - /* Make sure cache exists. */ - ObjectBBoneDeform *bbone_deform = BKE_armature_cached_bbone_deformation_get(object); - if (bbone_deform == NULL) { - bbone_deform = MEM_callocN(sizeof(*bbone_deform), "bbone deform cache"); - object->runtime.cached_bbone_deformation = bbone_deform; - } - /* Make sure arrays are allocateds at the proper size. */ - BKE_armature_cached_bbone_deformation_free_data(object); - DualQuat *dualquats = NULL; - if (use_quaternion) { - dualquats = MEM_calloc_arrayN(sizeof(DualQuat), totchan, "dualquats"); - } - bPoseChanDeform *pdef_info_array = MEM_calloc_arrayN( - sizeof(bPoseChanDeform), totchan, "bPoseChanDeform"); - /* Calculate deofrmation matricies. */ - ArmatureBBoneDefmatsData data = { - .pdef_info_array = pdef_info_array, - .dualquats = dualquats, - .use_quaternion = use_quaternion, - }; - BLI_task_parallel_listbase(&pose->chanbase, &data, armature_bbone_defmats_cb, totchan > 1024); - /* Store pointers. */ - bbone_deform->dualquats = dualquats; - atomic_cas_ptr( - (void **)&bbone_deform->pdef_info_array, bbone_deform->pdef_info_array, pdef_info_array); - bbone_deform->num_pchan = totchan; -} diff --git a/source/blender/blenkernel/intern/armature_update.c b/source/blender/blenkernel/intern/armature_update.c index 6d51c7f5108..c71c2dc86cf 100644 --- a/source/blender/blenkernel/intern/armature_update.c +++ b/source/blender/blenkernel/intern/armature_update.c @@ -88,18 +88,21 @@ static void splineik_init_tree_from_pchan(Scene *UNUSED(scene), ikData = con->data; /* target can only be curve */ - if ((ikData->tar == NULL) || (ikData->tar->type != OB_CURVE)) + if ((ikData->tar == NULL) || (ikData->tar->type != OB_CURVE)) { continue; + } /* skip if disabled */ - if ((con->enforce == 0.0f) || (con->flag & (CONSTRAINT_DISABLE | CONSTRAINT_OFF))) + if ((con->enforce == 0.0f) || (con->flag & (CONSTRAINT_DISABLE | CONSTRAINT_OFF))) { continue; + } /* otherwise, constraint is ok... */ break; } } - if (con == NULL) + if (con == NULL) { return; + } /* find the root bone and the chain of bones from the root to the tip * NOTE: this assumes that the bones are connected, but that may not be true... */ @@ -113,10 +116,12 @@ static void splineik_init_tree_from_pchan(Scene *UNUSED(scene), totLength += boneLengths[segcount]; } - if (segcount == 0) + if (segcount == 0) { return; - else + } + else { pchanRoot = pchanChain[segcount - 1]; + } /* perform binding step if required */ if ((ikData->flag & CONSTRAINT_SPLINEIK_BOUND) == 0) { @@ -124,8 +129,9 @@ static void splineik_init_tree_from_pchan(Scene *UNUSED(scene), int i; /* setup new empty array for the points list */ - if (ikData->points) + if (ikData->points) { MEM_freeN(ikData->points); + } ikData->numpoints = ikData->chainlen + 1; ikData->points = MEM_mallocN(sizeof(float) * ikData->numpoints, "Spline IK Binding"); @@ -159,7 +165,8 @@ static void splineik_init_tree_from_pchan(Scene *UNUSED(scene), CLAMP_MIN(ikData->points[segcount], 0.0f); /* make a new Spline-IK chain, and store it in the IK chains */ - /* TODO: we should check if there is already an IK chain on this, since that would take precedence... */ + /* TODO: we should check if there is already an IK chain on this, + * since that would take precedence... */ { /* make new tree */ tSplineIK_Tree *tree = MEM_callocN(sizeof(tSplineIK_Tree), "SplineIK Tree"); @@ -193,10 +200,12 @@ static void splineik_init_tree(Scene *scene, Object *ob, float UNUSED(ctime)) { bPoseChannel *pchan; - /* find the tips of Spline IK chains, which are simply the bones which have been tagged as such */ + /* find the tips of Spline IK chains, + * which are simply the bones which have been tagged as such */ for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) { - if (pchan->constflag & PCHAN_HAS_SPLINEIK) + if (pchan->constflag & PCHAN_HAS_SPLINEIK) { splineik_init_tree_from_pchan(scene, ob, pchan); + } } } @@ -293,8 +302,9 @@ static void splineik_evaluate_bone( /* apply curve's object-mode transforms to the position * unless the option to allow curve to be positioned elsewhere is activated (i.e. no root) */ - if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) == 0) + if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) == 0) { mul_m4_v3(ikData->tar->obmat, vec); + } /* convert the position to pose-space, then store it */ mul_m4_v3(ob->imat, vec); @@ -309,8 +319,9 @@ static void splineik_evaluate_bone( /* apply curve's object-mode transforms to the position * unless the option to allow curve to be positioned elsewhere is activated (i.e. no root) */ - if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) == 0) + if ((ikData->flag & CONSTRAINT_SPLINEIK_NO_ROOT) == 0) { mul_m4_v3(ikData->tar->obmat, vec); + } /* store the position, and convert it to pose space */ mul_m4_v3(ob->imat, vec); @@ -321,9 +332,9 @@ static void splineik_evaluate_bone( } } - /* step 2: determine the implied transform from these endpoints - * - splineVec: the vector direction that the spline applies on the bone - * - scaleFac: the factor that the bone length is scaled by to get the desired amount + /* Step 2: determine the implied transform from these endpoints. + * - splineVec: the vector direction that the spline applies on the bone. + * - scaleFac: the factor that the bone length is scaled by to get the desired amount. */ sub_v3_v3v3(splineVec, poseTail, poseHead); scaleFac = len_v3(splineVec) / pchan->bone->length; @@ -331,8 +342,10 @@ static void splineik_evaluate_bone( /* Adjust the scale factor towards the neutral state when rolling off the curve end. */ scaleFac = interpf(scaleFac, baseScale, tailBlendFac); - /* step 3: compute the shortest rotation needed to map from the bone rotation to the current axis - * - this uses the same method as is used for the Damped Track Constraint (see the code there for details) + /* Step 3: compute the shortest rotation needed + * to map from the bone rotation to the current axis. + * - this uses the same method as is used for the Damped Track Constraint + * (see the code there for details). */ { float dmat[3][3], rmat[3][3]; @@ -344,7 +357,8 @@ static void splineik_evaluate_bone( mul_m3_m4m4(basePoseMat, state->locrot_offset, pchan->pose_mat); normalize_m3_m3(rmat, basePoseMat); - /* also, normalize the orientation imposed by the bone, now that we've extracted the scale factor */ + /* Also, normalize the orientation imposed by the bone, + * now that we've extracted the scale factor. */ normalize_v3(splineVec); /* calculate smallest axis-angle rotation necessary for getting from the @@ -366,12 +380,12 @@ static void splineik_evaluate_bone( */ axis_angle_to_mat3(dmat, raxis, rangle); - /* combine these rotations so that the y-axis of the bone is now aligned as the spline dictates, - * while still maintaining roll control from the existing bone animation - */ + /* Combine these rotations so that the y-axis of the bone is now aligned as the + * spline dictates, while still maintaining roll control from the existing bone animation. */ mul_m3_m3m3(poseMat, dmat, rmat); - normalize_m3( - poseMat); /* attempt to reduce shearing, though I doubt this'll really help too much now... */ + + /* attempt to reduce shearing, though I doubt this'll really help too much now... */ + normalize_m3(poseMat); mul_m3_m3m3(basePoseMat, dmat, basePoseMat); @@ -412,8 +426,9 @@ static void splineik_evaluate_bone( /* NOTE: these should be fine for now, but should get sanitised in future */ CLAMP(scale, 0.0001f, 100000.0f); } - else + else { scale = 1.0f; + } /* apply the scaling */ mul_v3_fl(poseMat[0], scale); @@ -529,7 +544,8 @@ static void splineik_execute_tree( while ((tree = pchan_root->siktree.first) != NULL) { int i; - /* Firstly, calculate the bone matrix the standard way, since this is needed for roll control. */ + /* Firstly, calculate the bone matrix the standard way, + * since this is needed for roll control. */ for (i = tree->chainlen - 1; i >= 0; i--) { BKE_pose_where_is_bone(depsgraph, scene, ob, tree->chain[i], ctime, 1); } @@ -539,8 +555,8 @@ static void splineik_execute_tree( if (splineik_evaluate_init(tree, &state)) { /* Walk over each bone in the chain, calculating the effects of spline IK - * - the chain is traversed in the opposite order to storage order (i.e. parent to children) - * so that dependencies are correct + * - the chain is traversed in the opposite order to storage order (i.e. parent to children) + * so that dependencies are correct */ for (i = tree->chainlen - 1; i >= 0; i--) { bPoseChannel *pchan = tree->chain[i]; @@ -549,8 +565,9 @@ static void splineik_execute_tree( } /* free the tree info specific to SplineIK trees now */ - if (tree->chain) + if (tree->chain) { MEM_freeN(tree->chain); + } /* free this tree */ BLI_freelinkN(&pchan_root->siktree, tree); @@ -613,13 +630,11 @@ void BKE_pose_eval_init(struct Depsgraph *depsgraph, Scene *UNUSED(scene), Objec /* Free B-Bone shape data cache if it's not a B-Bone. */ if (pchan->bone == NULL || pchan->bone->segments <= 1) { - BKE_pose_channel_free_bbone_cache(pchan); + BKE_pose_channel_free_bbone_cache(&pchan->runtime); } } BLI_assert(pose->chan_array != NULL || BLI_listbase_is_empty(&pose->chanbase)); - - BKE_armature_cached_bbone_deformation_free_data(object); } void BKE_pose_eval_init_ik(struct Depsgraph *depsgraph, Scene *scene, Object *object) @@ -714,6 +729,9 @@ void BKE_pose_bone_done(struct Depsgraph *depsgraph, struct Object *object, int if (pchan->bone) { invert_m4_m4(imat, pchan->bone->arm_mat); mul_m4_m4m4(pchan->chan_mat, pchan->pose_mat, imat); + if (!(pchan->bone->flag & BONE_NO_DEFORM)) { + mat4_to_dquat(&pchan->runtime.deform_dual_quat, pchan->bone->arm_mat, pchan->chan_mat); + } } if (DEG_is_active(depsgraph) && armature->edbo == NULL) { bPoseChannel *pchan_orig = pchan->orig_pchan; @@ -723,7 +741,7 @@ void BKE_pose_bone_done(struct Depsgraph *depsgraph, struct Object *object, int copy_m4_m4(pchan_orig->constinv, pchan->constinv); BKE_pose_where_is_bone_tail(pchan_orig); if (pchan->bone == NULL || pchan->bone->segments <= 1) { - BKE_pose_channel_free_bbone_cache(pchan_orig); + BKE_pose_channel_free_bbone_cache(&pchan_orig->runtime); } } } @@ -798,7 +816,6 @@ static void pose_eval_done_common(struct Depsgraph *depsgraph, Object *object) bPose *pose = object->pose; UNUSED_VARS_NDEBUG(pose); BLI_assert(pose != NULL); - BKE_armature_cached_bbone_deformation_update(object); BKE_object_eval_boundbox(depsgraph, object); } static void pose_eval_cleanup_common(Object *object) @@ -806,6 +823,7 @@ static void pose_eval_cleanup_common(Object *object) bPose *pose = object->pose; BLI_assert(pose != NULL); BLI_assert(pose->chan_array != NULL || BLI_listbase_is_empty(&pose->chanbase)); + UNUSED_VARS_NDEBUG(pose); } void BKE_pose_eval_done(struct Depsgraph *depsgraph, Object *object) @@ -837,8 +855,6 @@ void BKE_pose_eval_proxy_init(struct Depsgraph *depsgraph, Object *object) DEG_debug_print_eval(depsgraph, __func__, object->id.name, object); BLI_assert(object->pose->chan_array != NULL || BLI_listbase_is_empty(&object->pose->chanbase)); - - BKE_armature_cached_bbone_deformation_free_data(object); } void BKE_pose_eval_proxy_done(struct Depsgraph *depsgraph, Object *object) @@ -869,13 +885,13 @@ void BKE_pose_eval_proxy_copy_bone(struct Depsgraph *depsgraph, Object *object, * around for the time while proxies are evaluating. */ #if 0 - bPoseChannel *pchan_from = pose_pchan_get_indexed( - object->proxy_from, pchan_index); + bPoseChannel *pchan_from = pose_pchan_get_indexed(object->proxy_from, pchan_index); #else bPoseChannel *pchan_from = BKE_pose_channel_find_name(object->proxy_from->pose, pchan->name); #endif BLI_assert(pchan != NULL); BLI_assert(pchan_from != NULL); BKE_pose_copyesult_pchan_result(pchan, pchan_from); + copy_dq_dq(&pchan->runtime.deform_dual_quat, &pchan_from->runtime.deform_dual_quat); BKE_pchan_bbone_segments_cache_copy(pchan, pchan_from); } diff --git a/source/blender/blenkernel/intern/blender.c b/source/blender/blenkernel/intern/blender.c index cf32abbb7b7..48b271cf277 100644 --- a/source/blender/blenkernel/intern/blender.c +++ b/source/blender/blenkernel/intern/blender.c @@ -75,7 +75,9 @@ void BKE_blender_free(void) { /* samples are in a global list..., also sets G_MAIN->sound->sample NULL */ - BKE_studiolight_free(); /* needs to run before main free as wm is still referenced for icons preview jobs */ + /* Needs to run before main free as wm is still referenced for icons preview jobs. */ + BKE_studiolight_free(); + BKE_main_free(G_MAIN); G_MAIN = NULL; @@ -95,7 +97,6 @@ void BKE_blender_free(void) BLI_callback_global_finalize(); - BKE_sequencer_cache_destruct(); IMB_moviecache_destruct(); free_nodesystem(); @@ -156,8 +157,9 @@ static void keymap_item_free(wmKeyMapItem *kmi) IDP_FreeProperty(kmi->properties); MEM_freeN(kmi->properties); } - if (kmi->ptr) + if (kmi->ptr) { MEM_freeN(kmi->ptr); + } } void BKE_blender_userdef_data_swap(UserDef *userdef_a, UserDef *userdef_b) diff --git a/source/blender/blenkernel/intern/blender_copybuffer.c b/source/blender/blenkernel/intern/blender_copybuffer.c index c801c1780c8..32c6f74dc2d 100644 --- a/source/blender/blenkernel/intern/blender_copybuffer.c +++ b/source/blender/blenkernel/intern/blender_copybuffer.c @@ -110,7 +110,8 @@ bool BKE_copybuffer_read(Main *bmain_dst, } /** - * \return Number of IDs directly pasted from the buffer (does not includes indirectly pulled out ones). + * \return Number of IDs directly pasted from the buffer + * (does not includes indirectly pulled out ones). */ int BKE_copybuffer_paste(bContext *C, const char *libname, diff --git a/source/blender/blenkernel/intern/blendfile.c b/source/blender/blenkernel/intern/blendfile.c index 723c8bb48bf..d1a3045a829 100644 --- a/source/blender/blenkernel/intern/blendfile.c +++ b/source/blender/blenkernel/intern/blendfile.c @@ -152,7 +152,8 @@ static void setup_app_data(bContext *C, /* no load screens? */ if (mode != LOAD_UI) { /* Logic for 'track_undo_scene' is to keep using the scene which the active screen has, - * as long as the scene associated with the undo operation is visible in one of the open windows. + * as long as the scene associated with the undo operation is visible + * in one of the open windows. * * - 'curscreen->scene' - scene the user is currently looking at. * - 'bfd->curscene' - scene undo-step was created in. @@ -278,8 +279,9 @@ static void setup_app_data(bContext *C, wmWindow *win = CTX_wm_window(C); /* in case we don't even have a local scene, add one */ - if (!bmain->scenes.first) + if (!bmain->scenes.first) { BKE_scene_add(bmain, "Empty"); + } CTX_data_scene_set(C, bmain->scenes.first); win->scene = CTX_data_scene(C); @@ -304,8 +306,9 @@ static void setup_app_data(bContext *C, /* FIXME: this version patching should really be part of the file-reading code, * but we still get too many unrelated data-corruption crashes otherwise... */ - if (bmain->versionfile < 250) + if (bmain->versionfile < 250) { do_versions_ipos_to_animato(bmain); + } bmain->recovered = 0; @@ -320,8 +323,9 @@ static void setup_app_data(bContext *C, bmain->recovered = 1; /* these are the same at times, should never copy to the same location */ - if (bmain->name != filepath) + if (bmain->name != filepath) { BLI_strncpy(bmain->name, filepath, FILE_MAX); + } } /* baseflags, groups, make depsgraph, etc */ @@ -399,8 +403,9 @@ int BKE_blendfile_read(bContext *C, setup_app_data(C, bfd, filepath, params->is_startup, reports); } } - else + else { BKE_reports_prependf(reports, "Loading '%s' failed: ", filepath); + } return (bfd ? retval : BKE_BLENDFILE_READ_FAIL); } @@ -416,8 +421,9 @@ bool BKE_blendfile_read_from_memory(bContext *C, bfd = BLO_read_from_memory(filebuf, filelength, params->skip_flags, reports); if (bfd) { - if (update_defaults) + if (update_defaults) { BLO_update_defaults_startup_blend(bfd->main, NULL); + } setup_app_data(C, bfd, "<memory2>", params->is_startup, reports); } else { @@ -440,10 +446,12 @@ bool BKE_blendfile_read_from_memfile(bContext *C, bmain, BKE_main_blendfile_path(bmain), memfile, params->skip_flags, reports); if (bfd) { /* remove the unused screens and wm */ - while (bfd->main->wm.first) + while (bfd->main->wm.first) { BKE_id_free(bfd->main, bfd->main->wm.first); - while (bfd->main->screens.first) + } + while (bfd->main->screens.first) { BKE_id_free(bfd->main, bfd->main->screens.first); + } setup_app_data(C, bfd, "<memory1>", params->is_startup, reports); } @@ -464,10 +472,8 @@ void BKE_blendfile_read_make_empty(bContext *C) ListBase *lb; ID *id; - FOREACH_MAIN_LISTBASE_BEGIN(bmain, lb) - { - FOREACH_MAIN_LISTBASE_ID_BEGIN(lb, id) - { + FOREACH_MAIN_LISTBASE_BEGIN (bmain, lb) { + FOREACH_MAIN_LISTBASE_ID_BEGIN (lb, id) { if (ELEM(GS(id->name), ID_SCE, ID_SCR, ID_WM, ID_WS)) { break; } @@ -638,11 +644,13 @@ static void blendfile_write_partial_cb(void *UNUSED(handle), Main *UNUSED(bmain) if (vid) { ID *id = vid; /* only tag for need-expand if not done, prevents eternal loops */ - if ((id->tag & LIB_TAG_DOIT) == 0) + if ((id->tag & LIB_TAG_DOIT) == 0) { id->tag |= LIB_TAG_NEED_EXPAND | LIB_TAG_DOIT; + } - if (id->lib && (id->lib->id.tag & LIB_TAG_DOIT) == 0) + if (id->lib && (id->lib->id.tag & LIB_TAG_DOIT) == 0) { id->lib->id.tag |= LIB_TAG_DOIT; + } } } diff --git a/source/blender/blenkernel/intern/boids.c b/source/blender/blenkernel/intern/boids.c index b31a283448c..becef327fab 100644 --- a/source/blender/blenkernel/intern/boids.c +++ b/source/blender/blenkernel/intern/boids.c @@ -99,7 +99,7 @@ static int rule_goal_avoid(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, pd_point_from_particle(bbd->sim, pa, &pa->state, &epoint); /* first find out goal/predator with highest priority */ - if (effectors) + if (effectors) { for (cur = effectors->first; cur; cur = cur->next) { Object *eob = cur->ob; PartDeflect *pd = cur->pd; @@ -108,11 +108,13 @@ static int rule_goal_avoid(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, if (gabr->ob == eob) { /* TODO: effectors with multiple points */ if (get_effector_data(cur, &efd, &epoint, 0)) { - if (cur->pd && cur->pd->forcefield == PFIELD_BOID) + if (cur->pd && cur->pd->forcefield == PFIELD_BOID) { priority = mul * pd->f_strength * effector_falloff(cur, &efd, &epoint, bbd->part->effector_weights); - else + } + else { priority = 1.0; + } eff = cur; } @@ -144,6 +146,7 @@ static int rule_goal_avoid(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, } } } + } /* if the object doesn't have effector data we have to fake it */ if (eff == NULL && gabr->ob) { @@ -227,7 +230,7 @@ static int rule_avoid_collision(BoidRule *rule, int n, neighbors = 0, nearest = 0; int ret = 0; - //check deflector objects first + // check deflector objects first if (acbr->options & BRULE_ACOLL_WITH_DEFLECTORS && bbd->sim->colliders) { ParticleCollision col; BVHTreeRayHit hit; @@ -246,8 +249,9 @@ static int rule_avoid_collision(BoidRule *rule, /* find out closest deflector object */ for (coll = bbd->sim->colliders->first; coll; coll = coll->next) { /* don't check with current ground object */ - if (coll->ob == bpa->ground) + if (coll->ob == bpa->ground) { continue; + } col.current = coll->ob; col.md = coll->collmd; @@ -288,7 +292,7 @@ static int rule_avoid_collision(BoidRule *rule, } } - //check boids in own system + // check boids in own system if (acbr->options & BRULE_ACOLL_WITH_BOIDS) { neighbors = BLI_kdtree_3d_range_search_with_len_squared_cb(bbd->sim->psys->tree, pa->prev_state.co, @@ -297,7 +301,7 @@ static int rule_avoid_collision(BoidRule *rule, len_v3(pa->prev_state.vel), len_squared_v3v3_with_normal_bias, pa->prev_state.ave); - if (neighbors > 1) + if (neighbors > 1) { for (n = 1; n < neighbors; n++) { copy_v3_v3(co1, pa->prev_state.co); copy_v3_v3(vel1, pa->prev_state.vel); @@ -335,6 +339,7 @@ static int rule_avoid_collision(BoidRule *rule, } } } + } } if (ptn) { MEM_freeN(ptn); @@ -355,7 +360,7 @@ static int rule_avoid_collision(BoidRule *rule, len_squared_v3v3_with_normal_bias, pa->prev_state.ave); - if (neighbors > 0) + if (neighbors > 0) { for (n = 0; n < neighbors; n++) { copy_v3_v3(co1, pa->prev_state.co); copy_v3_v3(vel1, pa->prev_state.vel); @@ -393,6 +398,7 @@ static int rule_avoid_collision(BoidRule *rule, } } } + } if (ptn) { MEM_freeN(ptn); @@ -401,8 +407,9 @@ static int rule_avoid_collision(BoidRule *rule, } } - if (ptn && nearest == 0) + if (ptn && nearest == 0) { MEM_freeN(ptn); + } return ret; } @@ -608,8 +615,9 @@ static int rule_follow_leader(BoidRule *rule, } } - if (ret) + if (ret) { return 1; + } /* not blocking so try to follow leader */ if (flbr->options & BRULE_LEADER_IN_LINE) { @@ -737,10 +745,12 @@ static int rule_fight(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, Parti enemy_pa = epars + ptn[n].index; } } - if (pt->mode == PTARGET_MODE_ENEMY) + if (pt->mode == PTARGET_MODE_ENEMY) { e_strength += epsys->part->boids->strength * health; - else if (pt->mode == PTARGET_MODE_FRIEND) + } + else if (pt->mode == PTARGET_MODE_FRIEND) { f_strength += epsys->part->boids->strength * health; + } if (ptn) { MEM_freeN(ptn); @@ -810,11 +820,11 @@ static boid_rule_cb boid_rules[] = { rule_follow_leader, rule_average_speed, rule_fight, - //rule_help, - //rule_protect, - //rule_hide, - //rule_follow_path, - //rule_follow_wall, + // rule_help, + // rule_protect, + // rule_hide, + // rule_follow_path, + // rule_follow_wall, }; static void set_boid_values(BoidValues *val, BoidSettings *boids, ParticleData *pa) @@ -869,8 +879,9 @@ static Object *boid_find_ground(BoidBrainData *bbd, BVHTreeRayHit hit; float radius = 0.0f, t, ray_dir[3]; - if (!bbd->sim->colliders) + if (!bbd->sim->colliders) { return NULL; + } memset(&col, 0, sizeof(ParticleCollision)); @@ -951,14 +962,18 @@ static int boid_rule_applies(ParticleData *pa, BoidSettings *UNUSED(boids), Boid { BoidParticle *bpa = pa->boid; - if (rule == NULL) + if (rule == NULL) { return 0; + } - if (ELEM(bpa->data.mode, eBoidMode_OnLand, eBoidMode_Climbing) && rule->flag & BOIDRULE_ON_LAND) + if (ELEM(bpa->data.mode, eBoidMode_OnLand, eBoidMode_Climbing) && + rule->flag & BOIDRULE_ON_LAND) { return 1; + } - if (bpa->data.mode == eBoidMode_InAir && rule->flag & BOIDRULE_IN_AIR) + if (bpa->data.mode == eBoidMode_InAir && rule->flag & BOIDRULE_IN_AIR) { return 1; + } return 0; } @@ -1014,21 +1029,26 @@ static float boid_goal_signed_dist(float *boid_co, float *goal_co, float *goal_n static int apply_boid_rule( BoidBrainData *bbd, BoidRule *rule, BoidValues *val, ParticleData *pa, float fuzziness) { - if (rule == NULL) + if (rule == NULL) { return 0; + } - if (boid_rule_applies(pa, bbd->part->boids, rule) == 0) + if (boid_rule_applies(pa, bbd->part->boids, rule) == 0) { return 0; + } - if (boid_rules[rule->type](rule, bbd, val, pa) == 0) + if (boid_rules[rule->type](rule, bbd, val, pa) == 0) { return 0; + } if (fuzziness < 0.0f || compare_len_v3v3(bbd->wanted_co, pa->prev_state.vel, - fuzziness * len_v3(pa->prev_state.vel)) == 0) + fuzziness * len_v3(pa->prev_state.vel)) == 0) { return 1; - else + } + else { return 0; + } } static BoidState *get_boid_state(BoidSettings *boids, ParticleData *pa) { @@ -1036,18 +1056,20 @@ static BoidState *get_boid_state(BoidSettings *boids, ParticleData *pa) BoidParticle *bpa = pa->boid; for (; state; state = state->next) { - if (state->id == bpa->data.state_id) + if (state->id == bpa->data.state_id) { return state; + } } /* for some reason particle isn't at a valid state */ state = boids->states.first; - if (state) + if (state) { bpa->data.state_id = state->id; + } return state; } -//static int boid_condition_is_true(BoidCondition *cond) +// static int boid_condition_is_true(BoidCondition *cond) //{ // /* TODO */ // return 0; @@ -1063,7 +1085,7 @@ void boid_brain(BoidBrainData *bbd, int p, ParticleData *pa) BoidParticle *bpa = pa->boid; ParticleSystem *psys = bbd->sim->psys; int rand; - //BoidCondition *cond; + // BoidCondition *cond; if (bpa->data.health <= 0.0f) { pa->alive = PARS_DYING; @@ -1071,9 +1093,9 @@ void boid_brain(BoidBrainData *bbd, int p, ParticleData *pa) return; } - //planned for near future - //cond = state->conditions.first; - //for (; cond; cond=cond->next) { + // planned for near future + // cond = state->conditions.first; + // for (; cond; cond=cond->next) { // if (boid_condition_is_true(cond)) { // pa->boid->state_id = cond->state_id; // state = get_boid_state(boids, pa); @@ -1094,8 +1116,9 @@ void boid_brain(BoidBrainData *bbd, int p, ParticleData *pa) switch (state->ruleset_type) { case eBoidRulesetType_Fuzzy: { for (rule = state->rules.first; rule; rule = rule->next) { - if (apply_boid_rule(bbd, rule, &val, pa, state->rule_fuzziness)) + if (apply_boid_rule(bbd, rule, &val, pa, state->rule_fuzziness)) { break; /* only first nonzero rule that comes through fuzzy rule is applied */ + } } break; } @@ -1146,8 +1169,9 @@ void boid_brain(BoidBrainData *bbd, int p, ParticleData *pa) copy_v3_v3(cvel, bbd->wanted_co); normalize_v2(cvel); - if (dot_v2v2(cvel, dir) > 0.95f / mul) + if (dot_v2v2(cvel, dir) > 0.95f / mul) { bpa->data.mode = eBoidMode_Liftoff; + } } else if (val.jump_speed > 0.0f) { float jump_v[3]; @@ -1229,14 +1253,16 @@ void boid_body(BoidBrainData *bbd, ParticleData *pa) /* make sure there's something in new velocity, location & rotation */ copy_particle_key(&pa->state, &pa->prev_state, 0); - if (bbd->part->flag & PART_SIZEMASS) + if (bbd->part->flag & PART_SIZEMASS) { pa_mass *= pa->size; + } /* if boids can't fly they fall to the ground */ if ((boids->options & BOID_ALLOW_FLIGHT) == 0 && ELEM(bpa->data.mode, eBoidMode_OnLand, eBoidMode_Climbing) == 0 && - psys_uses_gravity(bbd->sim)) + psys_uses_gravity(bbd->sim)) { bpa->data.mode = eBoidMode_Falling; + } if (bpa->data.mode == eBoidMode_Falling) { /* Falling boids are only effected by gravity. */ @@ -1318,10 +1344,12 @@ void boid_body(BoidBrainData *bbd, ParticleData *pa) /* constrain speed with maximum acceleration */ old_speed = len_v3(pa->prev_state.vel); - if (bbd->wanted_speed < old_speed) + if (bbd->wanted_speed < old_speed) { new_speed = MAX2(bbd->wanted_speed, old_speed - val.max_acc); - else + } + else { new_speed = MIN2(bbd->wanted_speed, old_speed + val.max_acc); + } /* combine direction and speed */ copy_v3_v3(new_vel, new_dir); @@ -1392,7 +1420,7 @@ void boid_body(BoidBrainData *bbd, ParticleData *pa) madd_v3_v3fl(pa->state.vel, acc, dtime); - //if (bpa->data.mode != eBoidMode_InAir) + // if (bpa->data.mode != eBoidMode_InAir) bpa->ground = boid_find_ground(bbd, pa, ground_co, ground_nor); /* change modes, constrain movement & keep track of down vector */ @@ -1467,29 +1495,31 @@ void boid_body(BoidBrainData *bbd, ParticleData *pa) bpa->data.mode = eBoidMode_OnLand; } /* if we're falling, can fly and want to go upwards lets fly */ - else if (boids->options & BOID_ALLOW_FLIGHT && bbd->wanted_co[2] > 0.0f) + else if (boids->options & BOID_ALLOW_FLIGHT && bbd->wanted_co[2] > 0.0f) { bpa->data.mode = eBoidMode_InAir; + } } - else + else { bpa->data.mode = eBoidMode_InAir; + } break; } case eBoidMode_Climbing: { boid_climb(boids, pa, ground_co, ground_nor); - //float nor[3]; - //copy_v3_v3(nor, ground_nor); + // float nor[3]; + // copy_v3_v3(nor, ground_nor); ///* gather apparent gravity to r_ve */ - //madd_v3_v3fl(pa->r_ve, ground_nor, -1.0); - //normalize_v3(pa->r_ve); + // madd_v3_v3fl(pa->r_ve, ground_nor, -1.0); + // normalize_v3(pa->r_ve); ///* raise boid it's size from surface */ - //mul_v3_fl(nor, pa->size * boids->height); - //add_v3_v3v3(pa->state.co, ground_co, nor); + // mul_v3_fl(nor, pa->size * boids->height); + // add_v3_v3v3(pa->state.co, ground_co, nor); ///* remove normal component from velocity */ - //project_v3_v3v3(v, pa->state.vel, ground_nor); - //sub_v3_v3v3(pa->state.vel, pa->state.vel, v); + // project_v3_v3v3(v, pa->state.vel, ground_nor); + // sub_v3_v3v3(pa->state.vel, pa->state.vel, v); break; } case eBoidMode_OnLand: { @@ -1502,8 +1532,9 @@ void boid_body(BoidBrainData *bbd, ParticleData *pa) boid_climb(boids, pa, ground_co, ground_nor); } /* ground is too far away so boid falls */ - else if (pa->state.co[2] - ground_co[2] > 1.1f * pa->size * boids->height) + else if (pa->state.co[2] - ground_co[2] > 1.1f * pa->size * boids->height) { bpa->data.mode = eBoidMode_Falling; + } else { /* constrain to surface */ pa->state.co[2] = ground_co[2] + pa->size * boids->height; @@ -1541,8 +1572,9 @@ void boid_body(BoidBrainData *bbd, ParticleData *pa) } /* apply damping */ - if (ELEM(bpa->data.mode, eBoidMode_OnLand, eBoidMode_Climbing)) + if (ELEM(bpa->data.mode, eBoidMode_OnLand, eBoidMode_Climbing)) { mul_v3_fl(pa->state.vel, 1.0f - 0.2f * bbd->part->dampfac); + } /* calculate rotation matrix based on forward & down vectors */ if (bpa->data.mode == eBoidMode_InAir) { @@ -1570,8 +1602,9 @@ void boid_body(BoidBrainData *bbd, ParticleData *pa) BoidRule *boid_new_rule(int type) { BoidRule *rule = NULL; - if (type <= 0) + if (type <= 0) { return NULL; + } switch (type) { case eBoidRuleType_Goal: @@ -1637,10 +1670,12 @@ BoidState *boid_new_state(BoidSettings *boids) BoidState *state = MEM_callocN(sizeof(BoidState), "BoidState"); state->id = boids->last_state_id++; - if (state->id) + if (state->id) { BLI_snprintf(state->name, sizeof(state->name), "State %i", state->id); - else + } + else { strcpy(state->name, "State"); + } state->rule_fuzziness = 0.5; state->volume = 1.0f; @@ -1705,8 +1740,9 @@ BoidState *boid_get_current_state(BoidSettings *boids) BoidState *state = boids->states.first; for (; state; state = state->next) { - if (state->flag & BOIDSTATE_CURRENT) + if (state->flag & BOIDSTATE_CURRENT) { break; + } } return state; diff --git a/source/blender/blenkernel/intern/bpath.c b/source/blender/blenkernel/intern/bpath.c index 25f886b815a..6f0c1891b05 100644 --- a/source/blender/blenkernel/intern/bpath.c +++ b/source/blender/blenkernel/intern/bpath.c @@ -233,21 +233,25 @@ static bool missing_files_find__recursive(char *filename_new, dir = opendir(dirname); - if (dir == NULL) + if (dir == NULL) { return found; + } - if (*r_filesize == -1) + if (*r_filesize == -1) { *r_filesize = 0; /* dir opened fine */ + } while ((de = readdir(dir)) != NULL) { - if (FILENAME_IS_CURRPAR(de->d_name)) + if (FILENAME_IS_CURRPAR(de->d_name)) { continue; + } BLI_join_dirfile(path, sizeof(path), dirname, de->d_name); - if (BLI_stat(path, &status) == -1) + if (BLI_stat(path, &status) == -1) { continue; /* cant stat, don't bother with this file, could print debug info here */ + } if (S_ISREG(status.st_mode)) { /* is file */ if (BLI_path_ncmp(filename, de->d_name, FILE_MAX) == 0) { /* name matches */ @@ -321,8 +325,9 @@ static bool missing_files_find__visit_cb(void *userdata, char *path_dst, const c BLI_strncpy(path_dst, filename_new, FILE_MAX); /* keep path relative if the previous one was relative */ - if (was_relative) + if (was_relative) { BLI_path_rel(path_dst, data->basedir); + } return true; } diff --git a/source/blender/blenkernel/intern/brush.c b/source/blender/blenkernel/intern/brush.c index 56a6de62dab..e28f1fc566f 100644 --- a/source/blender/blenkernel/intern/brush.c +++ b/source/blender/blenkernel/intern/brush.c @@ -140,12 +140,16 @@ void BKE_brush_init(Brush *brush) brush->sculpt_tool = SCULPT_TOOL_DRAW; /* sculpting defaults to the draw tool for new brushes */ + /* A kernel radius of 1 has almost no effect (T63233). */ + brush->blur_kernel_radius = 2; + /* the default alpha falloff curve */ BKE_brush_curve_preset(brush, CURVE_PRESET_SMOOTH); } /** - * \note Resulting brush will have two users: one as a fake user, another is assumed to be used by the caller. + * \note Resulting brush will have two users: one as a fake user, + * another is assumed to be used by the caller. */ Brush *BKE_brush_add(Main *bmain, const char *name, const eObjectMode ob_mode) { @@ -212,8 +216,9 @@ typedef enum eGPCurveMappingPreset { static void brush_gpencil_curvemap_reset(CurveMap *cuma, int tot, int preset) { - if (cuma->curve) + if (cuma->curve) { MEM_freeN(cuma->curve); + } cuma->totpoint = tot; cuma->curve = MEM_callocN(cuma->totpoint * sizeof(CurveMapPoint), __func__); @@ -572,15 +577,18 @@ struct Brush *BKE_brush_first_search(struct Main *bmain, const eObjectMode ob_mo Brush *brush; for (brush = bmain->brushes.first; brush; brush = brush->id.next) { - if (brush->ob_mode & ob_mode) + if (brush->ob_mode & ob_mode) { return brush; + } } return NULL; } /** - * Only copy internal data of Brush ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of Brush ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * @@ -869,8 +877,9 @@ void BKE_brush_curve_preset(Brush *b, eCurveMappingPreset preset) { CurveMap *cm = NULL; - if (!b->curve) + if (!b->curve) { b->curve = curvemapping_add(1, 0, 0, 1, 1); + } cm = b->curve->cm; cm->flag &= ~CUMA_EXTEND_EXTRAPOLATE; @@ -1156,10 +1165,12 @@ void BKE_brush_color_set(struct Scene *scene, struct Brush *brush, const float c { UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings; - if (ups->flag & UNIFIED_PAINT_COLOR) + if (ups->flag & UNIFIED_PAINT_COLOR) { copy_v3_v3(ups->rgb, color); - else + } + else { copy_v3_v3(brush->rgb, color); + } } void BKE_brush_size_set(Scene *scene, Brush *brush, int size) @@ -1169,10 +1180,12 @@ void BKE_brush_size_set(Scene *scene, Brush *brush, int size) /* make sure range is sane */ CLAMP(size, 1, MAX_BRUSH_PIXEL_RADIUS); - if (ups->flag & UNIFIED_PAINT_SIZE) + if (ups->flag & UNIFIED_PAINT_SIZE) { ups->size = size; - else + } + else { brush->size = size; + } } int BKE_brush_size_get(const Scene *scene, const Brush *brush) @@ -1228,10 +1241,12 @@ void BKE_brush_unprojected_radius_set(Scene *scene, Brush *brush, float unprojec { UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings; - if (ups->flag & UNIFIED_PAINT_SIZE) + if (ups->flag & UNIFIED_PAINT_SIZE) { ups->unprojected_radius = unprojected_radius; - else + } + else { brush->unprojected_radius = unprojected_radius; + } } float BKE_brush_unprojected_radius_get(const Scene *scene, const Brush *brush) @@ -1245,10 +1260,12 @@ void BKE_brush_alpha_set(Scene *scene, Brush *brush, float alpha) { UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings; - if (ups->flag & UNIFIED_PAINT_ALPHA) + if (ups->flag & UNIFIED_PAINT_ALPHA) { ups->alpha = alpha; - else + } + else { brush->alpha = alpha; + } } float BKE_brush_alpha_get(const Scene *scene, const Brush *brush) @@ -1269,10 +1286,12 @@ void BKE_brush_weight_set(const Scene *scene, Brush *brush, float value) { UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings; - if (ups->flag & UNIFIED_PAINT_WEIGHT) + if (ups->flag & UNIFIED_PAINT_WEIGHT) { ups->weight = value; - else + } + else { brush->weight = value; + } } /* scale unprojected radius to reflect a change in the brush's 2D size */ @@ -1282,8 +1301,9 @@ void BKE_brush_scale_unprojected_radius(float *unprojected_radius, { float scale = new_brush_size; /* avoid division by zero */ - if (old_brush_size != 0) + if (old_brush_size != 0) { scale /= (float)old_brush_size; + } (*unprojected_radius) *= scale; } @@ -1294,8 +1314,9 @@ void BKE_brush_scale_size(int *r_brush_size, { float scale = new_unprojected_radius; /* avoid division by zero */ - if (old_unprojected_radius != 0) + if (old_unprojected_radius != 0) { scale /= new_unprojected_radius; + } (*r_brush_size) = (int)((float)(*r_brush_size) * scale); } @@ -1342,10 +1363,12 @@ float BKE_brush_curve_strength(const Brush *br, float p, const float len) { float strength; - if (p >= len) + if (p >= len) { return 0; - else + } + else { p = p / len; + } strength = curvemapping_evaluateF(br->curve, 0, p); diff --git a/source/blender/blenkernel/intern/bvhutils.c b/source/blender/blenkernel/intern/bvhutils.c index 1c17408e286..8600d60c5c6 100644 --- a/source/blender/blenkernel/intern/bvhutils.c +++ b/source/blender/blenkernel/intern/bvhutils.c @@ -204,10 +204,12 @@ static void mesh_faces_spherecast(void *userdata, do { float dist; - if (ray->radius == 0.0f) + if (ray->radius == 0.0f) { dist = bvhtree_ray_tri_intersection(ray, hit->dist, t0, t1, t2); - else + } + else { dist = bvhtree_sphereray_tri_intersection(ray, ray->radius, hit->dist, t0, t1, t2); + } if (dist >= 0 && dist < hit->dist) { hit->index = index; @@ -239,10 +241,12 @@ static void mesh_looptri_spherecast(void *userdata, }; float dist; - if (ray->radius == 0.0f) + if (ray->radius == 0.0f) { dist = bvhtree_ray_tri_intersection(ray, hit->dist, UNPACK3(vtri_co)); - else + } + else { dist = bvhtree_sphereray_tri_intersection(ray, ray->radius, hit->dist, UNPACK3(vtri_co)); + } if (dist >= 0 && dist < hit->dist) { hit->index = index; @@ -269,10 +273,12 @@ static void editmesh_looptri_spherecast(void *userdata, { float dist; - if (ray->radius == 0.0f) + if (ray->radius == 0.0f) { dist = bvhtree_ray_tri_intersection(ray, hit->dist, t0, t1, t2); - else + } + else { dist = bvhtree_sphereray_tri_intersection(ray, ray->radius, hit->dist, t0, t1, t2); + } if (dist >= 0 && dist < hit->dist) { hit->index = index; @@ -562,7 +568,8 @@ BVHTree *bvhtree_from_editmesh_verts(BVHTreeFromEditMesh *data, * Builds a bvh tree where nodes are the given vertices (note: does not copy given mverts!). * \param vert_allocated: if true, vert freeing will be done when freeing data. * \param verts_mask: if not null, true elements give which vert to add to BVH tree. - * \param verts_num_active: if >= 0, number of active verts to add to BVH tree (else will be computed from mask). + * \param verts_num_active: if >= 0, number of active verts to add to BVH tree + * (else will be computed from mask). */ BVHTree *bvhtree_from_mesh_verts_ex(BVHTreeFromMesh *data, const MVert *vert, @@ -752,7 +759,8 @@ BVHTree *bvhtree_from_editmesh_edges(BVHTreeFromEditMesh *data, * \param vert, vert_allocated: if true, elem freeing will be done when freeing data. * \param edge, edge_allocated: if true, elem freeing will be done when freeing data. * \param edges_mask: if not null, true elements give which vert to add to BVH tree. - * \param edges_num_active: if >= 0, number of active edges to add to BVH tree (else will be computed from mask). + * \param edges_num_active: if >= 0, number of active edges to add to BVH tree + * (else will be computed from mask). */ BVHTree *bvhtree_from_mesh_edges_ex(BVHTreeFromMesh *data, const MVert *vert, @@ -816,8 +824,9 @@ static BVHTree *bvhtree_from_mesh_faces_create_tree(float epsilon, copy_v3_v3(co[0], vert[face[i].v1].co); copy_v3_v3(co[1], vert[face[i].v2].co); copy_v3_v3(co[2], vert[face[i].v3].co); - if (face[i].v4) + if (face[i].v4) { copy_v3_v3(co[3], vert[face[i].v4].co); + } BLI_bvhtree_insert(tree, i, co[0], face[i].v4 ? 4 : 3); } @@ -853,11 +862,13 @@ static void bvhtree_from_mesh_faces_setup_data(BVHTreeFromMesh *data, } /** - * Builds a bvh tree where nodes are the given tessellated faces (note: does not copy given mfaces!). + * 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). + * \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(BVHTreeFromMesh *data, const MVert *vert, diff --git a/source/blender/blenkernel/intern/cachefile.c b/source/blender/blenkernel/intern/cachefile.c index 4fe8cabde65..44e951a43da 100644 --- a/source/blender/blenkernel/intern/cachefile.c +++ b/source/blender/blenkernel/intern/cachefile.c @@ -21,18 +21,21 @@ * \ingroup bke */ +#include <string.h> + #include "DNA_anim_types.h" #include "DNA_cachefile_types.h" #include "DNA_constraint_types.h" #include "DNA_object_types.h" #include "DNA_scene_types.h" +#include "BLI_utildefines.h" #include "BLI_fileops.h" +#include "BLI_ghash.h" #include "BLI_listbase.h" #include "BLI_path_util.h" #include "BLI_string.h" #include "BLI_threads.h" -#include "BLI_utildefines.h" #include "BKE_animsys.h" #include "BKE_cachefile.h" @@ -41,10 +44,13 @@ #include "BKE_modifier.h" #include "BKE_scene.h" +#include "DEG_depsgraph_query.h" + #ifdef WITH_ALEMBIC # include "ABC_alembic.h" #endif +/* TODO: make this per cache file to avoid global locks. */ static SpinLock spin; void BKE_cachefiles_init(void) @@ -57,6 +63,94 @@ void BKE_cachefiles_exit(void) BLI_spin_end(&spin); } +void BKE_cachefile_reader_open(CacheFile *cache_file, + struct CacheReader **reader, + Object *object, + const char *object_path) +{ +#ifdef WITH_ALEMBIC + BLI_assert(cache_file->id.tag & LIB_TAG_COPIED_ON_WRITE); + + if (cache_file->handle == NULL) { + return; + } + + /* Open Alembic cache reader. */ + *reader = CacheReader_open_alembic_object(cache_file->handle, *reader, object, object_path); + + /* Multiple modifiers and constraints can call this function concurrently. */ + BLI_spin_lock(&spin); + if (*reader) { + /* Register in set so we can free it when the cache file changes. */ + if (cache_file->handle_readers == NULL) { + cache_file->handle_readers = BLI_gset_ptr_new("CacheFile.handle_readers"); + } + BLI_gset_reinsert(cache_file->handle_readers, reader, NULL); + } + else if (cache_file->handle_readers) { + /* Remove in case CacheReader_open_alembic_object free the existing reader. */ + BLI_gset_remove(cache_file->handle_readers, reader, NULL); + } + BLI_spin_unlock(&spin); +#else + UNUSED_VARS(cache_file, reader, object, object_path); +#endif +} + +void BKE_cachefile_reader_free(CacheFile *cache_file, struct CacheReader **reader) +{ +#ifdef WITH_ALEMBIC + BLI_assert(cache_file->id.tag & LIB_TAG_COPIED_ON_WRITE); + + if (*reader != NULL) { + CacheReader_free(*reader); + *reader = NULL; + + /* Multiple modifiers and constraints can call this function concurrently. */ + BLI_spin_lock(&spin); + if (cache_file->handle_readers) { + BLI_gset_remove(cache_file->handle_readers, reader, NULL); + } + BLI_spin_unlock(&spin); + } +#else + UNUSED_VARS(cache_file, reader); +#endif +} + +static void cachefile_handle_free(CacheFile *cache_file) +{ +#ifdef WITH_ALEMBIC + /* Free readers in all modifiers and constraints that use the handle, before + * we free the handle itself. */ + BLI_spin_lock(&spin); + if (cache_file->handle_readers) { + GSetIterator gs_iter; + GSET_ITER (gs_iter, cache_file->handle_readers) { + struct CacheReader **reader = BLI_gsetIterator_getKey(&gs_iter); + if (*reader != NULL) { + CacheReader_free(*reader); + *reader = NULL; + } + } + + BLI_gset_free(cache_file->handle_readers, NULL); + cache_file->handle_readers = NULL; + } + BLI_spin_unlock(&spin); + + /* Free handle. */ + if (cache_file->handle) { + ABC_free_handle(cache_file->handle); + cache_file->handle = NULL; + } + + cache_file->handle_filepath[0] = '\0'; +#else + UNUSED_VARS(cache_file); +#endif +} + void *BKE_cachefile_add(Main *bmain, const char *name) { CacheFile *cache_file = BKE_libblock_alloc(bmain, ID_CF, name, 0); @@ -68,43 +162,31 @@ void *BKE_cachefile_add(Main *bmain, const char *name) void BKE_cachefile_init(CacheFile *cache_file) { - cache_file->handle = NULL; cache_file->filepath[0] = '\0'; cache_file->override_frame = false; cache_file->frame = 0.0f; cache_file->is_sequence = false; cache_file->scale = 1.0f; - cache_file->handle_mutex = BLI_mutex_alloc(); BLI_listbase_clear(&cache_file->object_paths); + + cache_file->handle = NULL; + cache_file->handle_filepath[0] = '\0'; + cache_file->handle_readers = NULL; } /** Free (or release) any data used by this cachefile (does not free the cachefile itself). */ void BKE_cachefile_free(CacheFile *cache_file) { BKE_animdata_free((ID *)cache_file, false); - - if (cache_file->id.tag & LIB_TAG_NO_MAIN) { - /* CoW/no-main copies reuse the existing ArchiveReader and mutex */ - return; - } - - if (cache_file->handle) { -#ifdef WITH_ALEMBIC - ABC_free_handle(cache_file->handle); -#endif - cache_file->handle = NULL; - } - if (cache_file->handle_mutex) { - BLI_mutex_free(cache_file->handle_mutex); - cache_file->handle_mutex = NULL; - } - + cachefile_handle_free(cache_file); BLI_freelistN(&cache_file->object_paths); } /** - * Only copy internal data of CacheFile ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of CacheFile ID from source to already + * allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * @@ -115,13 +197,8 @@ void BKE_cachefile_copy_data(Main *UNUSED(bmain), const CacheFile *UNUSED(cache_file_src), const int UNUSED(flag)) { - if (cache_file_dst->id.tag & LIB_TAG_NO_MAIN) { - /* CoW/no-main copies reuse the existing ArchiveReader and mutex */ - return; - } - cache_file_dst->handle = NULL; - cache_file_dst->handle_mutex = NULL; + cache_file_dst->handle_readers = NULL; BLI_duplicatelist(&cache_file_dst->object_paths, &cache_file_dst->object_paths); } @@ -137,72 +214,51 @@ void BKE_cachefile_make_local(Main *bmain, CacheFile *cache_file, const bool lib BKE_id_make_local_generic(bmain, &cache_file->id, true, lib_local); } -void BKE_cachefile_reload(const Main *bmain, CacheFile *cache_file) +void BKE_cachefile_reload(Depsgraph *depsgraph, CacheFile *cache_file) { - char filepath[FILE_MAX]; - - BLI_strncpy(filepath, cache_file->filepath, sizeof(filepath)); - BLI_path_abs(filepath, ID_BLEND_PATH(bmain, &cache_file->id)); - -#ifdef WITH_ALEMBIC - if (cache_file->handle) { - ABC_free_handle(cache_file->handle); + /* To force reload, free the handle and tag depsgraph to load it again. */ + CacheFile *cache_file_eval = (CacheFile *)DEG_get_evaluated_id(depsgraph, &cache_file->id); + if (cache_file_eval) { + cachefile_handle_free(cache_file_eval); } - cache_file->handle = ABC_create_handle(filepath, &cache_file->object_paths); -#endif + DEG_id_tag_update(&cache_file->id, ID_RECALC_COPY_ON_WRITE); } -void BKE_cachefile_ensure_handle(const Main *bmain, CacheFile *cache_file) +void BKE_cachefile_eval(Main *bmain, Depsgraph *depsgraph, CacheFile *cache_file) { - BLI_spin_lock(&spin); - if (cache_file->handle_mutex == NULL) { - cache_file->handle_mutex = BLI_mutex_alloc(); - } - BLI_spin_unlock(&spin); - - BLI_mutex_lock(cache_file->handle_mutex); + BLI_assert(cache_file->id.tag & LIB_TAG_COPIED_ON_WRITE); - if (cache_file->handle == NULL) { - /* Assigning to a CoW copy is a bad idea; assign to the original instead. */ - BLI_assert((cache_file->id.tag & LIB_TAG_COPIED_ON_WRITE) == 0); - BKE_cachefile_reload(bmain, cache_file); + /* Compute filepath. */ + char filepath[FILE_MAX]; + if (!BKE_cachefile_filepath_get(bmain, depsgraph, cache_file, filepath)) { + return; } - BLI_mutex_unlock(cache_file->handle_mutex); -} - -void BKE_cachefile_update_frame( - Main *bmain, struct Depsgraph *depsgraph, Scene *scene, const float ctime, const float fps) -{ - CacheFile *cache_file; - char filename[FILE_MAX]; - - for (cache_file = bmain->cachefiles.first; cache_file; cache_file = cache_file->id.next) { - /* TODO: dependency graph should be updated to do drivers on cachefile. - * Execute drivers only, as animation has already been done. */ - BKE_animsys_evaluate_animdata( - depsgraph, scene, &cache_file->id, cache_file->adt, ctime, ADT_RECALC_DRIVERS); - - if (!cache_file->is_sequence) { - continue; - } + /* Test if filepath change or if we can keep the existing handle. */ + if (STREQ(cache_file->handle_filepath, filepath)) { + return; + } - const float time = BKE_cachefile_time_offset(cache_file, ctime, fps); + cachefile_handle_free(cache_file); + BLI_freelistN(&cache_file->object_paths); - if (BKE_cachefile_filepath_get(bmain, cache_file, time, filename)) { - BKE_cachefile_clean(bmain, cache_file); #ifdef WITH_ALEMBIC - ABC_free_handle(cache_file->handle); - cache_file->handle = ABC_create_handle(filename, NULL); + cache_file->handle = ABC_create_handle(filepath, &cache_file->object_paths); + BLI_strncpy(cache_file->handle_filepath, filepath, FILE_MAX); #endif - } + + if (DEG_is_active(depsgraph)) { + /* Flush object paths back to original datablock for UI. */ + CacheFile *cache_file_orig = (CacheFile *)DEG_get_original_id(&cache_file->id); + BLI_freelistN(&cache_file_orig->object_paths); + BLI_duplicatelist(&cache_file_orig->object_paths, &cache_file->object_paths); } } bool BKE_cachefile_filepath_get(const Main *bmain, + const Depsgraph *depsgraph, const CacheFile *cache_file, - float frame, char r_filepath[FILE_MAX]) { BLI_strncpy(r_filepath, cache_file->filepath, FILE_MAX); @@ -212,6 +268,11 @@ bool BKE_cachefile_filepath_get(const Main *bmain, int frame_len; if (cache_file->is_sequence && BLI_path_frame_get(r_filepath, &fframe, &frame_len)) { + Scene *scene = DEG_get_evaluated_scene(depsgraph); + const float ctime = BKE_scene_frame_get(scene); + const float fps = (((double)scene->r.frs_sec) / (double)scene->r.frs_sec_base); + const float frame = BKE_cachefile_time_offset(cache_file, ctime, fps); + char ext[32]; BLI_path_frame_strip(r_filepath, ext); BLI_path_frame(r_filepath, frame, frame_len); @@ -224,47 +285,9 @@ bool BKE_cachefile_filepath_get(const Main *bmain, return true; } -float BKE_cachefile_time_offset(CacheFile *cache_file, const float time, const float fps) +float BKE_cachefile_time_offset(const CacheFile *cache_file, const float time, const float fps) { const float time_offset = cache_file->frame_offset / fps; const float frame = (cache_file->override_frame ? cache_file->frame : time); return cache_file->is_sequence ? frame : frame / fps - time_offset; } - -/* TODO(kevin): replace this with some depsgraph mechanism, or something similar. */ -void BKE_cachefile_clean(struct Main *bmain, CacheFile *cache_file) -{ - for (Object *ob = bmain->objects.first; ob; ob = ob->id.next) { - ModifierData *md = modifiers_findByType(ob, eModifierType_MeshSequenceCache); - - if (md) { - MeshSeqCacheModifierData *mcmd = (MeshSeqCacheModifierData *)md; - - if (cache_file == mcmd->cache_file) { -#ifdef WITH_ALEMBIC - if (mcmd->reader != NULL) { - CacheReader_free(mcmd->reader); - } -#endif - mcmd->reader = NULL; - } - } - - for (bConstraint *con = ob->constraints.first; con; con = con->next) { - if (con->type != CONSTRAINT_TYPE_TRANSFORM_CACHE) { - continue; - } - - bTransformCacheConstraint *data = con->data; - - if (cache_file == data->cache_file) { -#ifdef WITH_ALEMBIC - if (data->reader != NULL) { - CacheReader_free(data->reader); - } -#endif - data->reader = NULL; - } - } - } -} diff --git a/source/blender/blenkernel/intern/camera.c b/source/blender/blenkernel/intern/camera.c index f4d09be2991..25399d342e1 100644 --- a/source/blender/blenkernel/intern/camera.c +++ b/source/blender/blenkernel/intern/camera.c @@ -88,8 +88,10 @@ void *BKE_camera_add(Main *bmain, const char *name) } /** - * Only copy internal data of Camera ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of Camera ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * @@ -129,8 +131,9 @@ void BKE_camera_free(Camera *ca) float BKE_camera_object_dof_distance(Object *ob) { Camera *cam = (Camera *)ob->data; - if (ob->type != OB_CAMERA) + if (ob->type != OB_CAMERA) { return 0.0f; + } if (cam->dof_ob) { float view_dir[3], dof_dir[3]; normalize_v3_v3(view_dir, ob->obmat[2]); @@ -143,8 +146,9 @@ float BKE_camera_object_dof_distance(Object *ob) float BKE_camera_sensor_size(int sensor_fit, float sensor_x, float sensor_y) { /* sensor size used to fit to. for auto, sensor_x is both x and y. */ - if (sensor_fit == CAMERA_SENSOR_FIT_VERT) + if (sensor_fit == CAMERA_SENSOR_FIT_VERT) { return sensor_y; + } return sensor_x; } @@ -152,10 +156,12 @@ float BKE_camera_sensor_size(int sensor_fit, float sensor_x, float sensor_y) int BKE_camera_sensor_fit(int sensor_fit, float sizex, float sizey) { if (sensor_fit == CAMERA_SENSOR_FIT_AUTO) { - if (sizex >= sizey) + if (sizex >= sizey) { return CAMERA_SENSOR_FIT_HOR; - else + } + else { return CAMERA_SENSOR_FIT_VERT; + } } return sensor_fit; @@ -181,15 +187,17 @@ void BKE_camera_params_init(CameraParams *params) void BKE_camera_params_from_object(CameraParams *params, const Object *ob) { - if (!ob) + if (!ob) { return; + } if (ob->type == OB_CAMERA) { /* camera object */ Camera *cam = ob->data; - if (cam->type == CAM_ORTHO) + if (cam->type == CAM_ORTHO) { params->is_ortho = true; + } params->lens = cam->lens; params->ortho_scale = cam->ortho_scale; @@ -207,8 +215,9 @@ void BKE_camera_params_from_object(CameraParams *params, const Object *ob) /* light object */ Light *la = ob->data; params->lens = 16.0f / tanf(la->spotsize * 0.5f); - if (params->lens == 0.0f) + if (params->lens == 0.0f) { params->lens = 35.0f; + } } else { params->lens = 35.0f; @@ -282,10 +291,12 @@ void BKE_camera_params_compute_viewplane( /* determine sensor fit */ sensor_fit = BKE_camera_sensor_fit(params->sensor_fit, xasp * winx, yasp * winy); - if (sensor_fit == CAMERA_SENSOR_FIT_HOR) + if (sensor_fit == CAMERA_SENSOR_FIT_HOR) { viewfac = winx; - else + } + else { viewfac = params->ycor * winy; + } pixsize /= viewfac; @@ -328,7 +339,7 @@ void BKE_camera_params_compute_matrix(CameraParams *params) rctf viewplane = params->viewplane; /* compute projection matrix */ - if (params->is_ortho) + if (params->is_ortho) { orthographic_m4(params->winmat, viewplane.xmin, viewplane.xmax, @@ -336,7 +347,8 @@ void BKE_camera_params_compute_matrix(CameraParams *params) viewplane.ymax, params->clip_start, params->clip_end); - else + } + else { perspective_m4(params->winmat, viewplane.xmin, viewplane.xmax, @@ -344,6 +356,7 @@ void BKE_camera_params_compute_matrix(CameraParams *params) viewplane.ymax, params->clip_start, params->clip_end); + } } /***************************** Camera View Frame *****************************/ @@ -723,8 +736,9 @@ static void camera_stereo3d_model_matrix(const Object *camera, size_to_mat4(sizemat, size); } - if (pivot == CAM_S3D_PIVOT_CENTER) + if (pivot == CAM_S3D_PIVOT_CENTER) { fac = 0.5f; + } fac_signed = is_left ? fac : -fac; @@ -865,13 +879,16 @@ bool BKE_camera_multiview_spherical_stereo(RenderData *rd, const Object *camera) Camera *cam; const bool is_multiview = (rd && rd->scemode & R_MULTIVIEW) != 0; - if (!is_multiview) + if (!is_multiview) { return false; + } - if (camera->type != OB_CAMERA) + if (camera->type != OB_CAMERA) { return false; - else + } + else { cam = camera->data; + } if ((rd->views_format == SCE_VIEWS_FORMAT_STEREO_3D) && ELEM(cam->type, CAM_PANO, CAM_PERSP) && ((cam->stereo.flag & CAM_S3D_SPHERICAL) != 0)) { @@ -895,8 +912,9 @@ static Object *camera_multiview_advanced(Scene *scene, Object *camera, const cha for (srv = scene->r.views.first; srv; srv = srv->next) { const int len_suffix = strlen(srv->suffix); - if ((len_suffix < len_suffix_max) || (len_name < len_suffix)) + if ((len_suffix < len_suffix_max) || (len_name < len_suffix)) { continue; + } if (STREQ(camera_name + (len_name - len_suffix), srv->suffix)) { BLI_snprintf(name, sizeof(name), "%.*s%s", (len_name - len_suffix), camera_name, suffix); @@ -951,15 +969,17 @@ static float camera_stereo3d_shift_x(const Object *camera, const char *viewname) convergence_mode = data->stereo.convergence_mode; pivot = data->stereo.pivot; - if (convergence_mode != CAM_S3D_OFFAXIS) + if (convergence_mode != CAM_S3D_OFFAXIS) { return shift; + } if (((pivot == CAM_S3D_PIVOT_LEFT) && is_left) || ((pivot == CAM_S3D_PIVOT_RIGHT) && !is_left)) { return shift; } - if (pivot == CAM_S3D_PIVOT_CENTER) + if (pivot == CAM_S3D_PIVOT_CENTER) { fac = 0.5f; + } fac_signed = is_left ? fac : -fac; shift += ((interocular_distance / data->sensor_x) * (data->lens / convergence_distance)) * diff --git a/source/blender/blenkernel/intern/cdderivedmesh.c b/source/blender/blenkernel/intern/cdderivedmesh.c index ada746d3fcc..667219e0eec 100644 --- a/source/blender/blenkernel/intern/cdderivedmesh.c +++ b/source/blender/blenkernel/intern/cdderivedmesh.c @@ -178,8 +178,9 @@ static void cdDM_getVertCos(DerivedMesh *dm, float (*r_cos)[3]) MVert *mv = CDDM_get_verts(dm); int i; - for (i = 0; i < dm->numVertData; i++, mv++) + for (i = 0; i < dm->numVertData; i++, mv++) { copy_v3_v3(r_cos[i], mv->co); + } } static void cdDM_getVertNo(DerivedMesh *dm, int index, float r_no[3]) @@ -248,8 +249,9 @@ static PBVH *cdDM_getPBVH(Object *ob, DerivedMesh *dm) return NULL; } - if (!ob->sculpt) + if (!ob->sculpt) { return NULL; + } if (ob->sculpt->pbvh) { cddm->pbvh = ob->sculpt->pbvh; @@ -294,6 +296,7 @@ static PBVH *cdDM_getPBVH(Object *ob, DerivedMesh *dm) me->mvert, me->totvert, &me->vdata, + &me->ldata, looptri, looptris_num); @@ -335,8 +338,9 @@ static void cdDM_foreachMappedVert(DerivedMesh *dm, for (i = 0; i < dm->numVertData; i++, mv++) { const short *no = (flag & DM_FOREACH_USE_NORMAL) ? mv->no : NULL; const int orig = *index++; - if (orig == ORIGINDEX_NONE) + if (orig == ORIGINDEX_NONE) { continue; + } func(userData, orig, mv->co, NULL, no); } } @@ -361,12 +365,14 @@ static void cdDM_foreachMappedEdge( for (i = 0; i < dm->numEdgeData; i++, med++) { if (index) { orig = *index++; - if (orig == ORIGINDEX_NONE) + if (orig == ORIGINDEX_NONE) { continue; + } func(userData, orig, mv[med->v1].co, mv[med->v2].co); } - else + else { func(userData, i, mv[med->v1].co, mv[med->v2].co); + } } } @@ -379,7 +385,8 @@ static void cdDM_foreachMappedLoop(DerivedMesh *dm, void *userData, DMForeachFlag flag) { - /* We can't use dm->getLoopDataLayout(dm) here, we want to always access dm->loopData, EditDerivedBMesh would + /* We can't use dm->getLoopDataLayout(dm) here, + * we want to always access dm->loopData, EditDerivedBMesh would * return loop data from bmesh itself. */ const float(*lnors)[3] = (flag & DM_FOREACH_USE_NORMAL) ? DM_get_loop_data_layer(dm, CD_NORMAL) : NULL; @@ -423,8 +430,9 @@ static void cdDM_foreachMappedFaceCenter( if (index) { orig = *index++; - if (orig == ORIGINDEX_NONE) + if (orig == ORIGINDEX_NONE) { continue; + } } else { orig = i; @@ -489,10 +497,12 @@ void CDDM_recalc_looptri(DerivedMesh *dm) static void cdDM_free_internal(CDDerivedMesh *cddm) { - if (cddm->pmap) + if (cddm->pmap) { MEM_freeN(cddm->pmap); - if (cddm->pmap_mem) + } + if (cddm->pmap_mem) { MEM_freeN(cddm->pmap_mem); + } } static void cdDM_release(DerivedMesh *dm) @@ -624,7 +634,8 @@ DerivedMesh *CDDM_from_mesh_ex(Mesh *mesh, if (mesh->runtime.cd_dirty_vert & CD_MASK_NORMAL) { dm->dirty |= DM_DIRTY_NORMALS; } - /* TODO DM_DIRTY_TESS_CDLAYERS ? Maybe not though, since we probably want to switch to looptris ? */ + /* TODO DM_DIRTY_TESS_CDLAYERS ? Maybe not though, + * since we probably want to switch to looptris? */ CustomData_merge(&mesh->vdata, &dm->vertData, cddata_masks.vmask, alloctype, mesh->totvert); CustomData_merge(&mesh->edata, &dm->edgeData, cddata_masks.emask, alloctype, mesh->totedge); @@ -829,11 +840,13 @@ static DerivedMesh *cddm_from_bmesh_ex(struct BMesh *bm, mv->flag = BM_vert_flag_to_mflag(eve); - if (cd_vert_bweight_offset != -1) + if (cd_vert_bweight_offset != -1) { mv->bweight = BM_ELEM_CD_GET_FLOAT_AS_UCHAR(eve, cd_vert_bweight_offset); + } - if (add_orig) + if (add_orig) { *index++ = i; + } CustomData_from_bmesh_block(&bm->vdata, &dm->vertData, eve->head.data, i); } @@ -858,14 +871,17 @@ static DerivedMesh *cddm_from_bmesh_ex(struct BMesh *bm, } } - if (cd_edge_crease_offset != -1) + if (cd_edge_crease_offset != -1) { med->crease = BM_ELEM_CD_GET_FLOAT_AS_UCHAR(eed, cd_edge_crease_offset); - if (cd_edge_bweight_offset != -1) + } + if (cd_edge_bweight_offset != -1) { med->bweight = BM_ELEM_CD_GET_FLOAT_AS_UCHAR(eed, cd_edge_bweight_offset); + } CustomData_from_bmesh_block(&bm->edata, &dm->edgeData, eed->head.data, i); - if (add_orig) + if (add_orig) { *index++ = i; + } } bm->elem_index_dirty &= ~BM_EDGE; @@ -923,8 +939,9 @@ static DerivedMesh *cddm_from_bmesh_ex(struct BMesh *bm, CustomData_from_bmesh_block(&bm->pdata, &dm->polyData, efa->head.data, i); - if (add_orig) + if (add_orig) { *index++ = i; + } } bm->elem_index_dirty &= ~(BM_FACE | BM_LOOP); @@ -1029,12 +1046,15 @@ DerivedMesh *CDDM_from_template_ex(DerivedMesh *source, CustomData_add_layer(&dm->loopData, CD_MLOOP, CD_CALLOC, NULL, numLoops); CustomData_add_layer(&dm->polyData, CD_MPOLY, CD_CALLOC, NULL, numPolys); - if (!CustomData_get_layer(&dm->vertData, CD_ORIGINDEX)) + if (!CustomData_get_layer(&dm->vertData, CD_ORIGINDEX)) { CustomData_add_layer(&dm->vertData, CD_ORIGINDEX, CD_CALLOC, NULL, numVerts); - if (!CustomData_get_layer(&dm->edgeData, CD_ORIGINDEX)) + } + if (!CustomData_get_layer(&dm->edgeData, CD_ORIGINDEX)) { CustomData_add_layer(&dm->edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges); - if (!CustomData_get_layer(&dm->faceData, CD_ORIGINDEX)) + } + if (!CustomData_get_layer(&dm->faceData, CD_ORIGINDEX)) { CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_CALLOC, NULL, numTessFaces); + } cddm->mvert = CustomData_get_layer(&dm->vertData, CD_MVERT); cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE); @@ -1061,8 +1081,9 @@ void CDDM_apply_vert_coords(DerivedMesh *dm, float (*vertCoords)[3]) vert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT, dm->numVertData); cddm->mvert = vert; - for (i = 0; i < dm->numVertData; ++i, ++vert) + for (i = 0; i < dm->numVertData; ++i, ++vert) { copy_v3_v3(vert->co, vertCoords[i]); + } cddm->dm.dirty |= DM_DIRTY_NORMALS; } @@ -1077,8 +1098,9 @@ void CDDM_apply_vert_normals(DerivedMesh *dm, short (*vertNormals)[3]) vert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT, dm->numVertData); cddm->mvert = vert; - for (i = 0; i < dm->numVertData; ++i, ++vert) + for (i = 0; i < dm->numVertData; ++i, ++vert) { copy_v3_v3_short(vert->no, vertNormals[i]); + } cddm->dm.dirty &= ~DM_DIRTY_NORMALS; } @@ -1149,9 +1171,10 @@ void CDDM_calc_normals_mapping(DerivedMesh *dm) void CDDM_calc_normals(DerivedMesh *dm) { CDDerivedMesh *cddm = (CDDerivedMesh *)dm; - float (*poly_nors)[3]; + float(*poly_nors)[3]; - if (dm->numVertData == 0) return; + if (dm->numVertData == 0) + return; /* we don't want to overwrite any referenced layers */ cddm->mvert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT, dm->numVertData); @@ -1162,8 +1185,14 @@ void CDDM_calc_normals(DerivedMesh *dm) poly_nors = CustomData_add_layer(&dm->polyData, CD_NORMAL, CD_CALLOC, NULL, dm->numPolyData); } - BKE_mesh_calc_normals_poly(cddm->mvert, dm->numVertData, CDDM_get_loops(dm), CDDM_get_polys(dm), - dm->numLoopData, dm->numPolyData, poly_nors, false); + BKE_mesh_calc_normals_poly(cddm->mvert, + dm->numVertData, + CDDM_get_loops(dm), + CDDM_get_polys(dm), + dm->numLoopData, + dm->numPolyData, + poly_nors, + false); cddm->dm.dirty &= ~DM_DIRTY_NORMALS; } @@ -1299,8 +1328,9 @@ void CDDM_calc_loop_normals_spacearr(DerivedMesh *dm, void CDDM_lower_num_verts(DerivedMesh *dm, int numVerts) { BLI_assert(numVerts >= 0); - if (numVerts < dm->numVertData) + if (numVerts < dm->numVertData) { CustomData_free_elem(&dm->vertData, numVerts, dm->numVertData - numVerts); + } dm->numVertData = numVerts; } @@ -1308,8 +1338,9 @@ void CDDM_lower_num_verts(DerivedMesh *dm, int numVerts) void CDDM_lower_num_edges(DerivedMesh *dm, int numEdges) { BLI_assert(numEdges >= 0); - if (numEdges < dm->numEdgeData) + if (numEdges < dm->numEdgeData) { CustomData_free_elem(&dm->edgeData, numEdges, dm->numEdgeData - numEdges); + } dm->numEdgeData = numEdges; } @@ -1317,8 +1348,9 @@ void CDDM_lower_num_edges(DerivedMesh *dm, int numEdges) void CDDM_lower_num_tessfaces(DerivedMesh *dm, int numTessFaces) { BLI_assert(numTessFaces >= 0); - if (numTessFaces < dm->numTessFaceData) + if (numTessFaces < dm->numTessFaceData) { CustomData_free_elem(&dm->faceData, numTessFaces, dm->numTessFaceData - numTessFaces); + } dm->numTessFaceData = numTessFaces; } @@ -1326,8 +1358,9 @@ void CDDM_lower_num_tessfaces(DerivedMesh *dm, int numTessFaces) void CDDM_lower_num_loops(DerivedMesh *dm, int numLoops) { BLI_assert(numLoops >= 0); - if (numLoops < dm->numLoopData) + if (numLoops < dm->numLoopData) { CustomData_free_elem(&dm->loopData, numLoops, dm->numLoopData - numLoops); + } dm->numLoopData = numLoops; } @@ -1335,8 +1368,9 @@ void CDDM_lower_num_loops(DerivedMesh *dm, int numLoops) void CDDM_lower_num_polys(DerivedMesh *dm, int numPolys) { BLI_assert(numPolys >= 0); - if (numPolys < dm->numPolyData) + if (numPolys < dm->numPolyData) { CustomData_free_elem(&dm->polyData, numPolys, dm->numPolyData - numPolys); + } dm->numPolyData = numPolys; } @@ -1399,8 +1433,9 @@ void CDDM_set_mvert(DerivedMesh *dm, MVert *mvert) { CDDerivedMesh *cddm = (CDDerivedMesh *)dm; - if (!CustomData_has_layer(&dm->vertData, CD_MVERT)) + if (!CustomData_has_layer(&dm->vertData, CD_MVERT)) { CustomData_add_layer(&dm->vertData, CD_MVERT, CD_ASSIGN, mvert, dm->numVertData); + } cddm->mvert = mvert; } @@ -1409,8 +1444,9 @@ void CDDM_set_medge(DerivedMesh *dm, MEdge *medge) { CDDerivedMesh *cddm = (CDDerivedMesh *)dm; - if (!CustomData_has_layer(&dm->edgeData, CD_MEDGE)) + if (!CustomData_has_layer(&dm->edgeData, CD_MEDGE)) { CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_ASSIGN, medge, dm->numEdgeData); + } cddm->medge = medge; } @@ -1419,8 +1455,9 @@ void CDDM_set_mface(DerivedMesh *dm, MFace *mface) { CDDerivedMesh *cddm = (CDDerivedMesh *)dm; - if (!CustomData_has_layer(&dm->faceData, CD_MFACE)) + if (!CustomData_has_layer(&dm->faceData, CD_MFACE)) { CustomData_add_layer(&dm->faceData, CD_MFACE, CD_ASSIGN, mface, dm->numTessFaceData); + } cddm->mface = mface; } @@ -1429,8 +1466,9 @@ void CDDM_set_mloop(DerivedMesh *dm, MLoop *mloop) { CDDerivedMesh *cddm = (CDDerivedMesh *)dm; - if (!CustomData_has_layer(&dm->loopData, CD_MLOOP)) + if (!CustomData_has_layer(&dm->loopData, CD_MLOOP)) { CustomData_add_layer(&dm->loopData, CD_MLOOP, CD_ASSIGN, mloop, dm->numLoopData); + } cddm->mloop = mloop; } @@ -1439,8 +1477,9 @@ void CDDM_set_mpoly(DerivedMesh *dm, MPoly *mpoly) { CDDerivedMesh *cddm = (CDDerivedMesh *)dm; - if (!CustomData_has_layer(&dm->polyData, CD_MPOLY)) + if (!CustomData_has_layer(&dm->polyData, CD_MPOLY)) { CustomData_add_layer(&dm->polyData, CD_MPOLY, CD_ASSIGN, mpoly, dm->numPolyData); + } cddm->mpoly = mpoly; } diff --git a/source/blender/blenkernel/intern/cloth.c b/source/blender/blenkernel/intern/cloth.c index 9f25cd14499..fcc0e1856af 100644 --- a/source/blender/blenkernel/intern/cloth.c +++ b/source/blender/blenkernel/intern/cloth.c @@ -140,11 +140,13 @@ void cloth_init(ClothModifierData *clmd) clmd->sim_parms->bending_model = CLOTH_BENDING_ANGULAR; - if (!clmd->sim_parms->effector_weights) + if (!clmd->sim_parms->effector_weights) { clmd->sim_parms->effector_weights = BKE_effector_add_weights(NULL); + } - if (clmd->point_cache) + if (clmd->point_cache) { clmd->point_cache->step = 1; + } } static BVHTree *bvhtree_build_from_cloth(ClothModifierData *clmd, float epsilon) @@ -155,20 +157,23 @@ static BVHTree *bvhtree_build_from_cloth(ClothModifierData *clmd, float epsilon) ClothVertex *verts; const MVertTri *vt; - if (!clmd) + if (!clmd) { return NULL; + } cloth = clmd->clothObject; - if (!cloth) + if (!cloth) { return NULL; + } verts = cloth->verts; vt = cloth->tri; /* in the moment, return zero if no faces there */ - if (!cloth->tri_num) + if (!cloth->tri_num) { return NULL; + } /* create quadtree with k=26 */ bvhtree = BLI_bvhtree_new(cloth->tri_num, epsilon, 4, 26); @@ -205,8 +210,9 @@ void bvhtree_update_from_cloth(ClothModifierData *clmd, bool moving, bool self) bvhtree = cloth->bvhtree; } - if (!bvhtree) + if (!bvhtree) { return; + } vt = cloth->tri; @@ -254,8 +260,9 @@ void cloth_clear_cache(Object *ob, ClothModifierData *clmd, float framenr) BKE_ptcache_id_from_cloth(&pid, ob, clmd); // don't do anything as long as we're in editmode! - if (pid.cache->edit && ob->mode & OB_MODE_PARTICLE_EDIT) + if (pid.cache->edit && ob->mode & OB_MODE_PARTICLE_EDIT) { return; + } BKE_ptcache_id_clear(&pid, PTCACHE_CLEAR_AFTER, framenr); } @@ -317,8 +324,9 @@ static int do_step_cloth( effectors = BKE_effectors_create(depsgraph, ob, NULL, clmd->sim_parms->effector_weights); - if (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_DYNAMIC_BASEMESH) + if (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_DYNAMIC_BASEMESH) { cloth_update_verts(ob, clmd, result); + } /* Support for dynamic vertex groups, changing from frame to frame */ cloth_apply_vgroup(clmd, result); @@ -387,8 +395,9 @@ void clothModifier_do(ClothModifierData *clmd, } /* initialize simulation data if it didn't exist already */ - if (!do_init_cloth(ob, clmd, mesh, framenr)) + if (!do_init_cloth(ob, clmd, mesh, framenr)) { return; + } if (framenr == startframe) { BKE_ptcache_id_reset(scene, &pid, PTCACHE_RESET_OUTDATED); @@ -412,8 +421,9 @@ void clothModifier_do(ClothModifierData *clmd, BKE_ptcache_validate(cache, framenr); - if (cache_result == PTCACHE_READ_INTERPOLATED && cache->flag & PTCACHE_REDO_NEEDED) + if (cache_result == PTCACHE_READ_INTERPOLATED && cache->flag & PTCACHE_REDO_NEEDED) { BKE_ptcache_write(&pid, framenr); + } clmd->clothObject->last_frame = framenr; @@ -422,17 +432,19 @@ void clothModifier_do(ClothModifierData *clmd, else if (cache_result == PTCACHE_READ_OLD) { BKE_cloth_solver_set_positions(clmd); } - else if (/*ob->id.lib ||*/ ( - cache->flag & - PTCACHE_BAKED)) { /* 2.4x disabled lib, but this can be used in some cases, testing further - campbell */ + else if ( + /* 2.4x disabled lib, but this can be used in some cases, testing further - campbell */ + /*ob->id.lib ||*/ (cache->flag & PTCACHE_BAKED)) { /* if baked and nothing in cache, do nothing */ BKE_ptcache_invalidate(cache); return; } /* if on second frame, write cache for first frame */ - if (cache->simframe == startframe && (cache->flag & PTCACHE_OUTDATED || cache->last_exact == 0)) + if (cache->simframe == startframe && + (cache->flag & PTCACHE_OUTDATED || cache->last_exact == 0)) { BKE_ptcache_write(&pid, startframe); + } clmd->sim_parms->timescale *= framenr - cache->simframe; @@ -442,8 +454,9 @@ void clothModifier_do(ClothModifierData *clmd, if (!do_step_cloth(depsgraph, ob, clmd, mesh, framenr)) { BKE_ptcache_invalidate(cache); } - else + else { BKE_ptcache_write(&pid, framenr); + } cloth_to_object(ob, clmd, vertexCos); clmd->clothObject->last_frame = framenr; @@ -454,8 +467,9 @@ void cloth_free_modifier(ClothModifierData *clmd) { Cloth *cloth = NULL; - if (!clmd) + if (!clmd) { return; + } cloth = clmd->clothObject; @@ -463,8 +477,9 @@ void cloth_free_modifier(ClothModifierData *clmd) BPH_cloth_solver_free(clmd); // Free the verts. - if (cloth->verts != NULL) + if (cloth->verts != NULL) { MEM_freeN(cloth->verts); + } cloth->verts = NULL; cloth->mvert_num = 0; @@ -490,18 +505,22 @@ void cloth_free_modifier(ClothModifierData *clmd) cloth->numsprings = 0; // free BVH collision tree - if (cloth->bvhtree) + if (cloth->bvhtree) { BLI_bvhtree_free(cloth->bvhtree); + } - if (cloth->bvhselftree) + if (cloth->bvhselftree) { BLI_bvhtree_free(cloth->bvhselftree); + } // we save our faces for collision objects - if (cloth->tri) + if (cloth->tri) { MEM_freeN(cloth->tri); + } - if (cloth->edgeset) + if (cloth->edgeset) { BLI_edgeset_free(cloth->edgeset); + } #if 0 if (clmd->clothObject->facemarks) { @@ -521,8 +540,9 @@ void cloth_free_modifier_extern(ClothModifierData *clmd) printf("cloth_free_modifier_extern\n"); } - if (!clmd) + if (!clmd) { return; + } cloth = clmd->clothObject; @@ -534,8 +554,9 @@ void cloth_free_modifier_extern(ClothModifierData *clmd) BPH_cloth_solver_free(clmd); // Free the verts. - if (cloth->verts != NULL) + if (cloth->verts != NULL) { MEM_freeN(cloth->verts); + } cloth->verts = NULL; cloth->mvert_num = 0; @@ -561,18 +582,22 @@ void cloth_free_modifier_extern(ClothModifierData *clmd) cloth->numsprings = 0; // free BVH collision tree - if (cloth->bvhtree) + if (cloth->bvhtree) { BLI_bvhtree_free(cloth->bvhtree); + } - if (cloth->bvhselftree) + if (cloth->bvhselftree) { BLI_bvhtree_free(cloth->bvhselftree); + } // we save our faces for collision objects - if (cloth->tri) + if (cloth->tri) { MEM_freeN(cloth->tri); + } - if (cloth->edgeset) + if (cloth->edgeset) { BLI_edgeset_free(cloth->edgeset); + } #if 0 if (clmd->clothObject->facemarks) { @@ -631,8 +656,9 @@ static void cloth_apply_vgroup(ClothModifierData *clmd, Mesh *mesh) /* float goalfac = 0; */ /* UNUSED */ ClothVertex *verts = NULL; - if (!clmd || !mesh) + if (!clmd || !mesh) { return; + } clothObj = clmd->clothObject; @@ -644,10 +670,12 @@ static void cloth_apply_vgroup(ClothModifierData *clmd, Mesh *mesh) for (i = 0; i < mvert_num; i++, verts++) { /* Reset Goal values to standard */ - if (clmd->sim_parms->vgroup_mass > 0) + if (clmd->sim_parms->vgroup_mass > 0) { verts->goal = clmd->sim_parms->defgoal; - else + } + else { verts->goal = 0.0f; + } /* Compute base cloth shrink weight */ verts->shrink_factor = 0.0f; @@ -668,8 +696,9 @@ static void cloth_apply_vgroup(ClothModifierData *clmd, Mesh *mesh) // ABS ( clmd->sim_parms->maxgoal - clmd->sim_parms->mingoal ); verts->goal = pow4f(verts->goal); - if (verts->goal >= SOFTGOALSNAP) + if (verts->goal >= SOFTGOALSNAP) { verts->flags |= CLOTH_VERT_FLAG_PINNED; + } } if (dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_struct - 1)) { @@ -693,7 +722,8 @@ static void cloth_apply_vgroup(ClothModifierData *clmd, Mesh *mesh) } if (clmd->sim_parms->vgroup_shrink > 0) { if (dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_shrink - 1)) { - /* Used for linear interpolation between min and max shrink factor based on weight. */ + /* Used for linear interpolation between min and max + * shrink factor based on weight. */ verts->shrink_factor = dvert->dw[j].weight; } } @@ -713,7 +743,7 @@ static float cloth_shrink_factor(ClothModifierData *clmd, ClothVertex *verts, in float k2 = base + delta * verts[i2].shrink_factor; /* Use geometrical mean to average two factors since it behaves better - for diagonals when a rectangle transforms into a trapezoid. */ + * for diagonals when a rectangle transforms into a trapezoid. */ return sqrtf(k1 * k2); } @@ -746,8 +776,9 @@ static int cloth_from_object( } // mesh input objects need Mesh - if (!mesh) + if (!mesh) { return 0; + } cloth_from_mesh(clmd, mesh); @@ -756,8 +787,9 @@ static int cloth_from_object( clmd->clothObject->numsprings = -1; if (clmd->sim_parms->shapekey_rest && - !(clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_DYNAMIC_BASEMESH)) + !(clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_DYNAMIC_BASEMESH)) { shapekey_rest = CustomData_get_layer(&mesh->vdata, CD_CLOTH_ORCO); + } mvert = mesh->mvert; @@ -774,18 +806,21 @@ static int cloth_from_object( copy_v3_v3(verts->xrest, shapekey_rest[i]); mul_m4_v3(ob->obmat, verts->xrest); } - else + else { copy_v3_v3(verts->xrest, verts->x); + } } /* no GUI interface yet */ verts->mass = clmd->sim_parms->mass; verts->impulse_count = 0; - if (clmd->sim_parms->vgroup_mass > 0) + if (clmd->sim_parms->vgroup_mass > 0) { verts->goal = clmd->sim_parms->defgoal; - else + } + else { verts->goal = 0.0f; + } verts->shrink_factor = 0.0f; @@ -813,8 +848,9 @@ static int cloth_from_object( // init our solver BPH_cloth_solver_init(ob, clmd); - if (!first) + if (!first) { BKE_cloth_solver_set_positions(clmd); + } clmd->clothObject->bvhtree = bvhtree_build_from_cloth(clmd, clmd->coll_parms->epsilon); clmd->clothObject->bvhselftree = bvhtree_build_from_cloth(clmd, clmd->coll_parms->selfepsilon); @@ -854,8 +890,9 @@ static void cloth_from_mesh(ClothModifierData *clmd, Mesh *mesh) /* Free the springs since they can't be correct if the vertices * changed. */ - if (clmd->clothObject->springs != NULL) + if (clmd->clothObject->springs != NULL) { MEM_freeN(clmd->clothObject->springs); + } } /*************************************************************************************** @@ -960,8 +997,9 @@ static void cloth_hair_update_bending_targets(ClothModifierData *clmd) float hair_frame[3][3], dir_old[3], dir_new[3]; int prev_mn; /* to find hair chains */ - if (!clmd->hairdata) + if (!clmd->hairdata) { return; + } /* XXX Note: we need to propagate frames from the root up, * but structural hair springs are stored in reverse order. @@ -1017,8 +1055,9 @@ static void cloth_hair_update_bending_rest_targets(ClothModifierData *clmd) float hair_frame[3][3], dir_old[3], dir_new[3]; int prev_mn; /* to find hair roots */ - if (!clmd->hairdata) + if (!clmd->hairdata) { return; + } /* XXX Note: we need to propagate frames from the root up, * but structural hair springs are stored in reverse order. @@ -1110,7 +1149,8 @@ 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 because implicit solver would need reset! */ + /* Warning: Appending NEW goal springs does not work + * because implicit solver would need reset! */ /* Activate / Deactivate existing springs */ if ((!(cloth->verts[spring->ij].flags & CLOTH_VERT_FLAG_PINNED)) && @@ -1358,8 +1398,9 @@ static int cloth_build_springs(ClothModifierData *clmd, Mesh *mesh) BendSpringRef *spring_ref = NULL; // error handling - if (numedges == 0) + if (numedges == 0) { return 0; + } /* NOTE: handling ownership of springs and edgeset is quite sloppy * currently they are never initialized but assert just to be sure */ @@ -1434,13 +1475,15 @@ static int cloth_build_springs(ClothModifierData *clmd, Mesh *mesh) } } - if (struct_springs_real > 0) + if (struct_springs_real > 0) { clmd->sim_parms->avg_spring_len /= struct_springs_real; + } for (int i = 0; i < mvert_num; i++) { - if (cloth->verts[i].spring_count > 0) + if (cloth->verts[i].spring_count > 0) { cloth->verts[i].avg_spring_len = cloth->verts[i].avg_spring_len * 0.49f / ((float)cloth->verts[i].spring_count); + } } edgeset = BLI_edgeset_new_ex(__func__, numedges); diff --git a/source/blender/blenkernel/intern/collection.c b/source/blender/blenkernel/intern/collection.c index 38094841e4a..d33d4e344b5 100644 --- a/source/blender/blenkernel/intern/collection.c +++ b/source/blender/blenkernel/intern/collection.c @@ -188,8 +188,10 @@ bool BKE_collection_delete(Main *bmain, Collection *collection, bool hierarchy) /***************************** Collection Copy *******************************/ /** - * Only copy internal data of Collection ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of Collection ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * @@ -248,7 +250,8 @@ static Collection *collection_duplicate_recursive(Main *bmain, collection_new = (Collection *)collection_old->id.newid; } - /* Optionally add to parent (we always want to do that, even if collection_old had already been duplicated). */ + /* Optionally add to parent (we always want to do that, + * even if collection_old had already been duplicated). */ if (parent != NULL) { if (collection_child_add(parent, collection_new, 0, true)) { /* Put collection right after existing one. */ @@ -263,14 +266,15 @@ static Collection *collection_duplicate_recursive(Main *bmain, } /* If we are not doing any kind of deep-copy, we can return immediately. - * False do_full_process means collection_old had already been duplicated, no need to redo some deep-copy on it. */ + * False do_full_process means collection_old had already been duplicated, + * no need to redo some deep-copy on it. */ if (!do_hierarchy || !do_full_process) { return collection_new; } if (do_objects) { - /* We can loop on collection_old's objects, that list is currently identical the collection_new' objects, - * and won't be changed here. */ + /* We can loop on collection_old's objects, that list is currently identical the collection_new + * objects, and won't be changed here. */ for (CollectionObject *cob = collection_old->gobject.first; cob; cob = cob->next) { Object *ob_old = cob->ob; Object *ob_new = (Object *)ob_old->id.newid; @@ -285,8 +289,8 @@ static Collection *collection_duplicate_recursive(Main *bmain, } } - /* We can loop on collection_old's children, that list is currently identical the collection_new' children, - * and won't be changed here. */ + /* We can loop on collection_old's children, + * that list is currently identical the collection_new' children, and won't be changed here. */ for (CollectionChild *child = collection_old->children.first; child; child = child->next) { Collection *child_collection_old = child->collection; @@ -314,13 +318,15 @@ Collection *BKE_collection_copy(Main *bmain, Collection *parent, Collection *col * * If \a do_hierarchy and \a do_deep_copy are false, this is a regular (shallow) ID copy. * - * \warning If any 'deep copy' behavior is enabled, this functions will clear all \a bmain id.idnew pointers. + * \warning If any 'deep copy' behavior is enabled, + * this functions will clear all \a bmain id.idnew pointers. * * \param do_hierarchy If true, it will recursively make shallow copies of children collections. * \param do_objects If true, it will also make duplicates of objects. * This one does nothing if \a do_hierarchy is not set. - * \param do_obdata If true, it will also make deep duplicates of objects, using behavior defined in user settings - * (U.dupflag). This one does nothing if \a do_hierarchy and \a do_objects are not set. + * \param do_obdata If true, it will also make deep duplicates of objects, + * using behavior defined in user settings (U.dupflag). + * This one does nothing if \a do_hierarchy and \a do_objects are not set. */ Collection *BKE_collection_duplicate(Main *bmain, Collection *parent, @@ -602,8 +608,9 @@ Collection *BKE_collection_object_find(Main *bmain, } while (collection) { - if (BKE_collection_has_object(collection, ob)) + if (BKE_collection_has_object(collection, ob)) { return collection; + } collection = collection_next_find(bmain, scene, collection); } return NULL; @@ -834,7 +841,8 @@ static void collection_missing_parents_remove(Collection *collection) * * \note caller must ensure #BKE_main_collection_sync_remap() is called afterwards! * - * \param collection: may be \a NULL, in which case whole \a bmain database of collections is checked. + * \param collection: may be \a NULL, + * in which case whole \a bmain database of collections is checked. */ void BKE_collections_child_remove_nulls(Main *bmain, Collection *collection) { @@ -1217,8 +1225,9 @@ static void scene_collections_array(Scene *scene, Collection ***collections_arra BLI_assert(collection != NULL); scene_collection_callback(collection, scene_collections_count, tot); - if (*tot == 0) + if (*tot == 0) { return; + } *collections_array = array = MEM_mallocN(sizeof(Collection *) * (*tot), "CollectionArray"); scene_collection_callback(collection, scene_collections_build_array, &array); diff --git a/source/blender/blenkernel/intern/collision.c b/source/blender/blenkernel/intern/collision.c index 67e1f36b222..ff6258ac339 100644 --- a/source/blender/blenkernel/intern/collision.c +++ b/source/blender/blenkernel/intern/collision.c @@ -73,8 +73,8 @@ typedef struct SelfColDetectData { } SelfColDetectData; /*********************************** -Collision modifier code start -***********************************/ + * Collision modifier code start + ***********************************/ /* step is limited from 0 (frame start position) to 1 (frame end position) */ void collision_move_object(CollisionModifierData *collmd, float step, float prevstep) @@ -178,9 +178,9 @@ void bvhtree_update_from_mvert(BVHTree *bvhtree, BLI_bvhtree_update_tree(bvhtree); } -/*********************************** -Collision modifier code end -***********************************/ +/* *************************** + * Collision modifier code end + * *************************** */ BLI_INLINE int next_ind(int i) { @@ -446,13 +446,15 @@ static void collision_compute_barycentric( w1[0] = (float)((e * c - b * f) / d); - if (w1[0] < 0) + if (w1[0] < 0) { w1[0] = 0; + } w2[0] = (float)((f - b * (double)w1[0]) / c); - if (w2[0] < 0) + if (w2[0] < 0) { w2[0] = 0; + } w3[0] = 1.0f - w1[0] - w2[0]; @@ -537,7 +539,8 @@ static int cloth_collision_response_static(ClothModifierData *clmd, sub_v3_v3v3(relativeVelocity, v2, v1); - /* Calculate the normal component of the relative velocity (actually only the magnitude - the direction is stored in 'normal'). */ + /* Calculate the normal component of the relative velocity + * (actually only the magnitude - the direction is stored in 'normal'). */ magrelVel = dot_v3v3(relativeVelocity, collpair->normal); /* If magrelVel < 0 the edges are approaching each other. */ @@ -555,7 +558,8 @@ static int cloth_collision_response_static(ClothModifierData *clmd, sub_v3_v3v3(vrel_t_pre, relativeVelocity, temp); /* Decrease in magnitude of relative tangential velocity due to coulomb friction - * in original formula "magrelVel" should be the "change of relative velocity in normal direction". */ + * in original formula "magrelVel" should be the + * "change of relative velocity in normal direction". */ magtangent = min_ff(collob->pd->pdef_cfrict * 0.01f * magrelVel, len_v3(vrel_t_pre)); /* Apply friction impulse. */ @@ -637,16 +641,19 @@ static int cloth_collision_response_static(ClothModifierData *clmd, for (int j = 0; j < 3; j++) { if (cloth1->verts[collpair->ap1].impulse_count > 0 && - ABS(cloth1->verts[collpair->ap1].impulse[j]) < ABS(i1[j])) + ABS(cloth1->verts[collpair->ap1].impulse[j]) < ABS(i1[j])) { cloth1->verts[collpair->ap1].impulse[j] = i1[j]; + } if (cloth1->verts[collpair->ap2].impulse_count > 0 && - ABS(cloth1->verts[collpair->ap2].impulse[j]) < ABS(i2[j])) + ABS(cloth1->verts[collpair->ap2].impulse[j]) < ABS(i2[j])) { cloth1->verts[collpair->ap2].impulse[j] = i2[j]; + } if (cloth1->verts[collpair->ap3].impulse_count > 0 && - ABS(cloth1->verts[collpair->ap3].impulse[j]) < ABS(i3[j])) + ABS(cloth1->verts[collpair->ap3].impulse[j]) < ABS(i3[j])) { cloth1->verts[collpair->ap3].impulse[j] = i3[j]; + } } } } @@ -715,7 +722,8 @@ static int cloth_selfcollision_response_static(ClothModifierData *clmd, sub_v3_v3v3(relativeVelocity, v2, v1); - /* Calculate the normal component of the relative velocity (actually only the magnitude - the direction is stored in 'normal'). */ + /* Calculate the normal component of the relative velocity + * (actually only the magnitude - the direction is stored in 'normal'). */ magrelVel = dot_v3v3(relativeVelocity, collpair->normal); /* TODO: Impulses should be weighed by mass as this is self col, @@ -735,7 +743,8 @@ static int cloth_selfcollision_response_static(ClothModifierData *clmd, sub_v3_v3v3(vrel_t_pre, relativeVelocity, temp); /* Decrease in magnitude of relative tangential velocity due to coulomb friction - * in original formula "magrelVel" should be the "change of relative velocity in normal direction". */ + * in original formula "magrelVel" should be the + * "change of relative velocity in normal direction". */ magtangent = min_ff(clmd->coll_parms->self_friction * 0.01f * magrelVel, len_v3(vrel_t_pre)); /* Apply friction impulse. */ @@ -816,16 +825,19 @@ static int cloth_selfcollision_response_static(ClothModifierData *clmd, for (int j = 0; j < 3; j++) { if (cloth1->verts[collpair->ap1].impulse_count > 0 && - ABS(cloth1->verts[collpair->ap1].impulse[j]) < ABS(i1[j])) + ABS(cloth1->verts[collpair->ap1].impulse[j]) < ABS(i1[j])) { cloth1->verts[collpair->ap1].impulse[j] = i1[j]; + } if (cloth1->verts[collpair->ap2].impulse_count > 0 && - ABS(cloth1->verts[collpair->ap2].impulse[j]) < ABS(i2[j])) + ABS(cloth1->verts[collpair->ap2].impulse[j]) < ABS(i2[j])) { cloth1->verts[collpair->ap2].impulse[j] = i2[j]; + } if (cloth1->verts[collpair->ap3].impulse_count > 0 && - ABS(cloth1->verts[collpair->ap3].impulse[j]) < ABS(i3[j])) + ABS(cloth1->verts[collpair->ap3].impulse[j]) < ABS(i3[j])) { cloth1->verts[collpair->ap3].impulse[j] = i3[j]; + } } } } @@ -974,8 +986,9 @@ static void add_collision_object(ListBase *relations, /* only get objects with collision modifier */ if (((modifier_type == eModifierType_Collision) && ob->pd && ob->pd->deflect) || - (modifier_type != eModifierType_Collision)) + (modifier_type != eModifierType_Collision)) { cmd = (CollisionModifierData *)modifiers_findByType(ob, modifier_type); + } if (cmd) { CollisionRelation *relation = MEM_callocN(sizeof(CollisionRelation), "CollisionRelation"); @@ -1279,8 +1292,9 @@ int cloth_bvh_collision( uint coll_count_self = 0; BVHTreeOverlap *overlap_self = NULL; - if ((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_COLLOBJ) || cloth_bvh == NULL) + if ((clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_COLLOBJ) || cloth_bvh == NULL) { return 0; + } verts = cloth->verts; mvert_num = cloth->mvert_num; @@ -1500,16 +1514,18 @@ static CollPair *cloth_point_collpair(float p1[3], float facenor[3], v1p1[3], v1p2[3]; float w[3]; - if (!cloth_point_face_collision_params(p1, p2, co1, co2, co3, facenor, &lambda, w)) + if (!cloth_point_face_collision_params(p1, p2, co1, co2, co3, facenor, &lambda, w)) { return collpair; + } sub_v3_v3v3(v1p1, p1, co1); // distance1 = dot_v3v3(v1p1, facenor); sub_v3_v3v3(v1p2, p2, co1); distance2 = dot_v3v3(v1p2, facenor); // if (distance2 > epsilon || (distance1 < 0.0f && distance2 < 0.0f)) - if (distance2 > epsilon) + if (distance2 > epsilon) { return collpair; + } collpair->face1 = index_cloth; /* XXX actually not a face, but equivalent index for point */ collpair->face2 = index_coll; @@ -1536,7 +1552,8 @@ static CollPair *cloth_point_collpair(float p1[3], return collpair; } -//Determines collisions on overlap, collisions are written to collpair[i] and collision+number_collision_found is returned +/* Determines collisions on overlap, + * collisions are written to collpair[i] and collision+number_collision_found is returned. */ static CollPair *cloth_point_collision(ModifierData *md1, ModifierData *md2, BVHTreeOverlap *overlap, @@ -1642,8 +1659,9 @@ void cloth_find_point_contacts(Depsgraph *depsgraph, Object *collob = collobjs[i]; CollisionModifierData *collmd = (CollisionModifierData *)modifiers_findByType( collob, eModifierType_Collision); - if (!collmd->bvhtree) + if (!collmd->bvhtree) { continue; + } /* move object to position (step) in time */ collision_move_object(collmd, step + dt, step); @@ -1666,8 +1684,9 @@ void cloth_find_point_contacts(Depsgraph *depsgraph, ct->collisions = NULL; ct->totcollisions = 0; - if (!collmd->bvhtree) + if (!collmd->bvhtree) { continue; + } /* search for overlapping collision pairs */ overlap = BLI_bvhtree_overlap(cloth_bvh, collmd->bvhtree, &result, NULL, NULL); @@ -1682,12 +1701,16 @@ void cloth_find_point_contacts(Depsgraph *depsgraph, clmd, collmd, &ct->collisions, &collisions_index, result, overlap, epsilon, dt); ct->totcollisions = (int)(collisions_index - ct->collisions); - // resolve nearby collisions - // ret += cloth_points_objcollisions_resolve(clmd, collmd, collob->pd, collisions[i], collisions_index[i], dt); + /* Resolve nearby collisions. */ +#if 0 + ret += cloth_points_objcollisions_resolve( + clmd, collmd, collob->pd, collisions[i], collisions_index[i], dt); +#endif } - if (overlap) + if (overlap) { MEM_freeN(overlap); + } } BKE_collision_objects_free(collobjs); diff --git a/source/blender/blenkernel/intern/colorband.c b/source/blender/blenkernel/intern/colorband.c index ffb60195f36..8701f06d9dd 100644 --- a/source/blender/blenkernel/intern/colorband.c +++ b/source/blender/blenkernel/intern/colorband.c @@ -338,38 +338,49 @@ static float colorband_hue_interp( switch (ipotype_hue) { case COLBAND_HUE_NEAR: { - if ((h1 < h2) && (h2 - h1) > +0.5f) + if ((h1 < h2) && (h2 - h1) > +0.5f) { mode = 1; - else if ((h1 > h2) && (h2 - h1) < -0.5f) + } + else if ((h1 > h2) && (h2 - h1) < -0.5f) { mode = 2; - else + } + else { mode = 0; + } break; } case COLBAND_HUE_FAR: { /* Do full loop in Hue space in case both stops are the same... */ - if (h1 == h2) + if (h1 == h2) { mode = 1; - else if ((h1 < h2) && (h2 - h1) < +0.5f) + } + else if ((h1 < h2) && (h2 - h1) < +0.5f) { mode = 1; - else if ((h1 > h2) && (h2 - h1) > -0.5f) + } + else if ((h1 > h2) && (h2 - h1) > -0.5f) { mode = 2; - else + } + else { mode = 0; + } break; } case COLBAND_HUE_CCW: { - if (h1 > h2) + if (h1 > h2) { mode = 2; - else + } + else { mode = 0; + } break; } case COLBAND_HUE_CW: { - if (h1 < h2) + if (h1 < h2) { mode = 1; - else + } + else { mode = 0; + } break; } } @@ -403,13 +414,15 @@ bool BKE_colorband_evaluate(const ColorBand *coba, float in, float out[4]) int ipotype; int a; - if (coba == NULL || coba->tot == 0) + if (coba == NULL || coba->tot == 0) { return false; + } cbd1 = coba->data; - /* Note: when ipotype >= COLBAND_INTERP_B_SPLINE, we cannot do early-out with a constant color before - * first color stop and after last one, because interpolation starts before and ends after those... */ + /* Note: when ipotype >= COLBAND_INTERP_B_SPLINE, + * we cannot do early-out with a constant color before first color stop and after last one, + * because interpolation starts before and ends after those... */ ipotype = (coba->color_mode == COLBAND_BLEND_RGB) ? coba->ipotype : COLBAND_INTERP_LINEAR; if (coba->tot == 1) { @@ -480,14 +493,18 @@ bool BKE_colorband_evaluate(const ColorBand *coba, float in, float out[4]) /* ipo from right to left: 3 2 1 0 */ float t[4]; - if (a >= coba->tot - 1) + if (a >= coba->tot - 1) { cbd0 = cbd1; - else + } + else { cbd0 = cbd1 + 1; - if (a < 2) + } + if (a < 2) { cbd3 = cbd2; - else + } + else { cbd3 = cbd2 - 1; + } CLAMP(fac, 0.0f, 1.0f); @@ -561,18 +578,21 @@ void BKE_colorband_evaluate_table_rgba(const ColorBand *coba, float **array, int *size = CM_TABLE + 1; *array = MEM_callocN(sizeof(float) * (*size) * 4, "ColorBand"); - for (a = 0; a < *size; a++) + for (a = 0; a < *size; a++) { BKE_colorband_evaluate(coba, (float)a / (float)CM_TABLE, &(*array)[a * 4]); + } } static int vergcband(const void *a1, const void *a2) { const CBData *x1 = a1, *x2 = a2; - if (x1->pos > x2->pos) + if (x1->pos > x2->pos) { return 1; - else if (x1->pos < x2->pos) + } + else if (x1->pos < x2->pos) { return -1; + } return 0; } @@ -580,11 +600,13 @@ void BKE_colorband_update_sort(ColorBand *coba) { int a; - if (coba->tot < 2) + if (coba->tot < 2) { return; + } - for (a = 0; a < coba->tot; a++) + for (a = 0; a < coba->tot; a++) { coba->data[a].cur = a; + } qsort(coba->data, coba->tot, sizeof(CBData), vergcband); @@ -627,17 +649,20 @@ int BKE_colorband_element_remove(struct ColorBand *coba, int index) { int a; - if (coba->tot < 2) + if (coba->tot < 2) { return 0; + } - if (index < 0 || index >= coba->tot) + if (index < 0 || index >= coba->tot) { return 0; + } coba->tot--; for (a = index; a < coba->tot; a++) { coba->data[a] = coba->data[a + 1]; } - if (coba->cur) + if (coba->cur) { coba->cur--; + } return 1; } diff --git a/source/blender/blenkernel/intern/colortools.c b/source/blender/blenkernel/intern/colortools.c index 96c098b37e9..45cb5e817d2 100644 --- a/source/blender/blenkernel/intern/colortools.c +++ b/source/blender/blenkernel/intern/colortools.c @@ -55,8 +55,9 @@ void curvemapping_set_defaults( float clipminx, clipminy, clipmaxx, clipmaxy; cumap->flag = CUMA_DO_CLIP; - if (tot == 4) + if (tot == 4) { cumap->cur = 3; /* rhms, hack for 'col' curve? */ + } clipminx = min_ff(minx, maxx); clipminy = min_ff(miny, maxy); @@ -129,12 +130,15 @@ void curvemapping_copy_data(CurveMapping *target, const CurveMapping *cumap) *target = *cumap; for (a = 0; a < CM_TOT; a++) { - if (cumap->cm[a].curve) + if (cumap->cm[a].curve) { target->cm[a].curve = MEM_dupallocN(cumap->cm[a].curve); - if (cumap->cm[a].table) + } + if (cumap->cm[a].table) { target->cm[a].table = MEM_dupallocN(cumap->cm[a].table); - if (cumap->cm[a].premultable) + } + if (cumap->cm[a].premultable) { target->cm[a].premultable = MEM_dupallocN(cumap->cm[a].premultable); + } } } @@ -181,8 +185,9 @@ bool curvemap_remove_point(CurveMap *cuma, CurveMapPoint *point) int a, b, removed = 0; /* must have 2 points minimum */ - if (cuma->totpoint <= 2) + if (cuma->totpoint <= 2) { return false; + } cmp = MEM_mallocN((cuma->totpoint) * sizeof(CurveMapPoint), "curve points"); @@ -263,8 +268,9 @@ CurveMapPoint *curvemap_insert(CurveMap *cuma, float x, float y) void curvemap_reset(CurveMap *cuma, const rctf *clipr, int preset, int slope) { - if (cuma->curve) + if (cuma->curve) { MEM_freeN(cuma->curve); + } switch (preset) { case CURVE_PRESET_LINE: @@ -502,10 +508,12 @@ static void calchandle_curvemap(BezTriple *bezt, const BezTriple *prev, const Be len_a = len_v2(dvec_a); len_b = len_v2(dvec_b); - if (len_a == 0.0f) + if (len_a == 0.0f) { len_a = 1.0f; - if (len_b == 0.0f) + } + if (len_b == 0.0f) { len_b = 1.0f; + } if (ELEM(bezt->h1, HD_AUTO, HD_AUTO_ANIM) || ELEM(bezt->h2, HD_AUTO, HD_AUTO_ANIM)) { /* auto */ float tvec[2]; @@ -590,10 +598,12 @@ static float curvemap_calc_extend(const CurveMap *cuma, return first[1]; } else { - if (cuma->ext_in[0] == 0.0f) + if (cuma->ext_in[0] == 0.0f) { return first[1] + cuma->ext_in[1] * 10000.0f; - else + } + else { return first[1] + cuma->ext_in[1] * (x - first[0]) / cuma->ext_in[0]; + } } } else if (x >= last[0]) { @@ -602,10 +612,12 @@ static float curvemap_calc_extend(const CurveMap *cuma, return last[1]; } else { - if (cuma->ext_out[0] == 0.0f) + if (cuma->ext_out[0] == 0.0f) { return last[1] - cuma->ext_out[1] * 10000.0f; - else + } + else { return last[1] + cuma->ext_out[1] * (x - last[0]) / cuma->ext_out[0]; + } } } return 0.0f; @@ -619,8 +631,9 @@ static void curvemap_make_table(CurveMap *cuma, const rctf *clipr) float *fp, *allpoints, *lastpoint, curf, range; int a, totpoint; - if (cuma->curve == NULL) + if (cuma->curve == NULL) { return; + } /* default rect also is table range */ cuma->mintable = clipr->xmin; @@ -662,8 +675,9 @@ static void curvemap_make_table(CurveMap *cuma, const rctf *clipr) hlen = len_v3v3(bezt[0].vec[1], bezt[0].vec[2]); /* original handle length */ /* clip handle point */ copy_v3_v3(vec, bezt[1].vec[0]); - if (vec[0] < bezt[0].vec[1][0]) + if (vec[0] < bezt[0].vec[1][0]) { vec[0] = bezt[0].vec[1][0]; + } sub_v3_v3(vec, bezt[0].vec[1]); nlen = len_v3(vec); @@ -679,8 +693,9 @@ static void curvemap_make_table(CurveMap *cuma, const rctf *clipr) hlen = len_v3v3(bezt[a].vec[1], bezt[a].vec[0]); /* original handle length */ /* clip handle point */ copy_v3_v3(vec, bezt[a - 1].vec[2]); - if (vec[0] > bezt[a].vec[1][0]) + if (vec[0] > bezt[a].vec[1][0]) { vec[0] = bezt[a].vec[1][0]; + } sub_v3_v3(vec, bezt[a].vec[1]); nlen = len_v3(vec); @@ -692,8 +707,9 @@ static void curvemap_make_table(CurveMap *cuma, const rctf *clipr) } } /* make the bezier curve */ - if (cuma->table) + if (cuma->table) { MEM_freeN(cuma->table); + } totpoint = (cuma->totpoint - 1) * CM_RESOL; fp = allpoints = MEM_callocN(totpoint * 2 * sizeof(float), "table"); @@ -748,15 +764,18 @@ static void curvemap_make_table(CurveMap *cuma, const rctf *clipr) while (curf >= fp[0] && fp != lastpoint) { fp += 2; } - if (fp == allpoints || (curf >= fp[0] && fp == lastpoint)) + if (fp == allpoints || (curf >= fp[0] && fp == lastpoint)) { cmp[a].y = curvemap_calc_extend(cuma, curf, allpoints, lastpoint); + } else { float fac1 = fp[0] - fp[-2]; float fac2 = fp[0] - curf; - if (fac1 > FLT_EPSILON) + if (fac1 > FLT_EPSILON) { fac1 = fac2 / fac1; - else + } + else { fac1 = 0.0f; + } cmp[a].y = fac1 * fp[-1] + (1.0f - fac1) * fp[1]; } } @@ -791,16 +810,18 @@ void curvemapping_premultiply(CurveMapping *cumap, int restore) if ((cumap->flag & CUMA_PREMULLED) == 0) { /* verify and copy */ for (a = 0; a < 3; a++) { - if (cumap->cm[a].table == NULL) + if (cumap->cm[a].table == NULL) { curvemap_make_table(cumap->cm + a, &cumap->clipr); + } cumap->cm[a].premultable = cumap->cm[a].table; cumap->cm[a].table = MEM_mallocN((CM_TABLE + 1) * sizeof(CurveMapPoint), "premul table"); memcpy( cumap->cm[a].table, cumap->cm[a].premultable, (CM_TABLE + 1) * sizeof(CurveMapPoint)); } - if (cumap->cm[3].table == NULL) + if (cumap->cm[3].table == NULL) { curvemap_make_table(cumap->cm + 3, &cumap->clipr); + } /* premul */ for (a = 0; a < 3; a++) { @@ -824,10 +845,12 @@ static int sort_curvepoints(const void *a1, const void *a2) { const struct CurveMapPoint *x1 = a1, *x2 = a2; - if (x1->x > x2->x) + if (x1->x > x2->x) { return 1; - else if (x1->x < x2->x) + } + else if (x1->x < x2->x) { return -1; + } return 0; } @@ -849,14 +872,18 @@ void curvemapping_changed(CurveMapping *cumap, const bool rem_doubles) if (cumap->flag & CUMA_DO_CLIP) { for (a = 0; a < cuma->totpoint; a++) { if (cmp[a].flag & CUMA_SELECT) { - if (cmp[a].x < clipr->xmin) + if (cmp[a].x < clipr->xmin) { dx = min_ff(dx, cmp[a].x - clipr->xmin); - else if (cmp[a].x > clipr->xmax) + } + else if (cmp[a].x > clipr->xmax) { dx = max_ff(dx, cmp[a].x - clipr->xmax); - if (cmp[a].y < clipr->ymin) + } + if (cmp[a].y < clipr->ymin) { dy = min_ff(dy, cmp[a].y - clipr->ymin); - else if (cmp[a].y > clipr->ymax) + } + else if (cmp[a].y > clipr->ymax) { dy = max_ff(dy, cmp[a].y - clipr->ymax); + } } } for (a = 0; a < cuma->totpoint; a++) { @@ -887,19 +914,22 @@ void curvemapping_changed(CurveMapping *cumap, const bool rem_doubles) if (sqrtf(dx * dx + dy * dy) < thresh) { if (a == 0) { cmp[a + 1].flag |= CUMA_HANDLE_VECTOR; - if (cmp[a + 1].flag & CUMA_SELECT) + if (cmp[a + 1].flag & CUMA_SELECT) { cmp[a].flag |= CUMA_SELECT; + } } else { cmp[a].flag |= CUMA_HANDLE_VECTOR; - if (cmp[a].flag & CUMA_SELECT) + if (cmp[a].flag & CUMA_SELECT) { cmp[a + 1].flag |= CUMA_SELECT; + } } break; /* we assume 1 deletion per edit is ok */ } } - if (a != cuma->totpoint - 1) + if (a != cuma->totpoint - 1) { curvemap_remove(cuma, 2); + } } curvemap_make_table(cuma, clipr); } @@ -929,13 +959,16 @@ float curvemap_evaluateF(const CurveMap *cuma, float value) i = (int)fi; /* fi is table float index and should check against table range i.e. [0.0 CM_TABLE] */ - if (fi < 0.0f || fi > CM_TABLE) + if (fi < 0.0f || fi > CM_TABLE) { return curvemap_calc_extend(cuma, value, &cuma->table[0].x, &cuma->table[CM_TABLE].x); + } else { - if (i < 0) + if (i < 0) { return cuma->table[0].y; - if (i >= CM_TABLE) + } + if (i >= CM_TABLE) { return cuma->table[CM_TABLE].y; + } fi = fi - (float)i; return (1.0f - fi) * cuma->table[i].y + (fi)*cuma->table[i + 1].y; @@ -950,10 +983,12 @@ float curvemapping_evaluateF(const CurveMapping *cumap, int cur, float value) /* account for clipping */ if (cumap->flag & CUMA_DO_CLIP) { - if (val < cumap->curr.ymin) + if (val < cumap->curr.ymin) { val = cumap->curr.ymin; - else if (val > cumap->curr.ymax) + } + else if (val > cumap->curr.ymax) { val = cumap->curr.ymax; + } } return val; @@ -1096,32 +1131,43 @@ int curvemapping_RGBA_does_something(const CurveMapping *cumap) { int a; - if (cumap->black[0] != 0.0f) + if (cumap->black[0] != 0.0f) { return 1; - if (cumap->black[1] != 0.0f) + } + if (cumap->black[1] != 0.0f) { return 1; - if (cumap->black[2] != 0.0f) + } + if (cumap->black[2] != 0.0f) { return 1; - if (cumap->white[0] != 1.0f) + } + if (cumap->white[0] != 1.0f) { return 1; - if (cumap->white[1] != 1.0f) + } + if (cumap->white[1] != 1.0f) { return 1; - if (cumap->white[2] != 1.0f) + } + if (cumap->white[2] != 1.0f) { return 1; + } for (a = 0; a < CM_TOT; a++) { if (cumap->cm[a].curve) { - if (cumap->cm[a].totpoint != 2) + if (cumap->cm[a].totpoint != 2) { return 1; + } - if (cumap->cm[a].curve[0].x != 0.0f) + if (cumap->cm[a].curve[0].x != 0.0f) { return 1; - if (cumap->cm[a].curve[0].y != 0.0f) + } + if (cumap->cm[a].curve[0].y != 0.0f) { return 1; - if (cumap->cm[a].curve[1].x != 1.0f) + } + if (cumap->cm[a].curve[1].x != 1.0f) { return 1; - if (cumap->cm[a].curve[1].y != 1.0f) + } + if (cumap->cm[a].curve[1].y != 1.0f) { return 1; + } } } return 0; @@ -1131,12 +1177,14 @@ void curvemapping_initialize(CurveMapping *cumap) { int a; - if (cumap == NULL) + if (cumap == NULL) { return; + } for (a = 0; a < CM_TOT; a++) { - if (cumap->cm[a].table == NULL) + if (cumap->cm[a].table == NULL) { curvemap_make_table(cumap->cm + a, &cumap->clipr); + } } } @@ -1148,14 +1196,18 @@ void curvemapping_table_RGBA(const CurveMapping *cumap, float **array, int *size *array = MEM_callocN(sizeof(float) * (*size) * 4, "CurveMapping"); for (a = 0; a < *size; a++) { - if (cumap->cm[0].table) + if (cumap->cm[0].table) { (*array)[a * 4 + 0] = cumap->cm[0].table[a].y; - if (cumap->cm[1].table) + } + if (cumap->cm[1].table) { (*array)[a * 4 + 1] = cumap->cm[1].table[a].y; - if (cumap->cm[2].table) + } + if (cumap->cm[2].table) { (*array)[a * 4 + 2] = cumap->cm[2].table[a].y; - if (cumap->cm[3].table) + } + if (cumap->cm[3].table) { (*array)[a * 4 + 3] = cumap->cm[3].table[a].y; + } } } @@ -1232,11 +1284,13 @@ void BKE_histogram_update_sample_line(Histogram *hist, hist->xmax = 1.0f; /* hist->ymax = 1.0f; */ /* now do this on the operator _only_ */ - if (ibuf->rect == NULL && ibuf->rect_float == NULL) + if (ibuf->rect == NULL && ibuf->rect_float == NULL) { return; + } - if (ibuf->rect_float) + if (ibuf->rect_float) { cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings); + } for (i = 0; i < 256; i++) { x = (int)(0.5f + x1 + (float)i * (x2 - x1) / 255.0f); @@ -1290,8 +1344,9 @@ void BKE_histogram_update_sample_line(Histogram *hist, } } - if (cm_processor) + if (cm_processor) { IMB_colormanagement_processor_free(cm_processor); + } } /* if view_settings, it also applies this to byte buffers */ @@ -1343,8 +1398,9 @@ static void scopes_update_cb(void *__restrict userdata, (y % rows_per_sample_line) == 0; const bool is_float = (ibuf->rect_float != NULL); - if (is_float) + if (is_float) { rf = ibuf->rect_float + ((size_t)y) * ibuf->x * ibuf->channels; + } else { rc = display_buffer + ((size_t)y) * ibuf->x * ibuf->channels; } @@ -1376,8 +1432,9 @@ static void scopes_update_cb(void *__restrict userdata, } } else { - for (int c = 4; c--;) + for (int c = 4; c--;) { rgba[c] = rc[c] * INV_255; + } } /* we still need luma for histogram */ @@ -1440,10 +1497,12 @@ static void scopes_update_finalize(void *__restrict userdata, void *__restrict u } for (int c = 3; c--;) { - if (min[c] < minmax[c][0]) + if (min[c] < minmax[c][0]) { minmax[c][0] = min[c]; - if (max[c] > minmax[c][1]) + } + if (max[c] > minmax[c][1]) { minmax[c][1] = max[c]; + } } } @@ -1456,24 +1515,27 @@ void scopes_update(Scopes *scopes, unsigned int nl, na, nr, ng, nb; double divl, diva, divr, divg, divb; const unsigned char *display_buffer = NULL; - unsigned int bin_lum[256] = {0}, bin_r[256] = {0}, bin_g[256] = {0}, bin_b[256] = {0}, - bin_a[256] = {0}; + uint bin_lum[256] = {0}, bin_r[256] = {0}, bin_g[256] = {0}, bin_b[256] = {0}, bin_a[256] = {0}; int ycc_mode = -1; void *cache_handle = NULL; struct ColormanageProcessor *cm_processor = NULL; - if (ibuf->rect == NULL && ibuf->rect_float == NULL) + if (ibuf->rect == NULL && ibuf->rect_float == NULL) { return; + } - if (scopes->ok == 1) + if (scopes->ok == 1) { return; + } - if (scopes->hist.ymax == 0.f) + if (scopes->hist.ymax == 0.f) { scopes->hist.ymax = 1.f; + } /* hmmmm */ - if (!(ELEM(ibuf->channels, 3, 4))) + if (!(ELEM(ibuf->channels, 3, 4))) { return; + } scopes->hist.channels = 3; scopes->hist.x_resolution = 256; @@ -1500,8 +1562,9 @@ void scopes_update(Scopes *scopes, scopes->sample_lines = (scopes->accuracy * 0.01f) * (scopes->accuracy * 0.01f) * ibuf->y; CLAMP_MIN(scopes->sample_lines, 1); - if (scopes->sample_full) + if (scopes->sample_full) { scopes->sample_lines = ibuf->y; + } /* scan the image */ for (a = 0; a < 3; a++) { @@ -1511,14 +1574,18 @@ void scopes_update(Scopes *scopes, scopes->waveform_tot = ibuf->x * scopes->sample_lines; - if (scopes->waveform_1) + if (scopes->waveform_1) { MEM_freeN(scopes->waveform_1); - if (scopes->waveform_2) + } + if (scopes->waveform_2) { MEM_freeN(scopes->waveform_2); - if (scopes->waveform_3) + } + if (scopes->waveform_3) { MEM_freeN(scopes->waveform_3); - if (scopes->vecscope) + } + if (scopes->vecscope) { MEM_freeN(scopes->vecscope); + } scopes->waveform_1 = MEM_callocN(scopes->waveform_tot * 2 * sizeof(float), "waveform point channel 1"); @@ -1564,16 +1631,21 @@ void scopes_update(Scopes *scopes, /* convert hist data to float (proportional to max count) */ nl = na = nr = nb = ng = 0; for (a = 0; a < 256; a++) { - if (bin_lum[a] > nl) + if (bin_lum[a] > nl) { nl = bin_lum[a]; - if (bin_r[a] > nr) + } + if (bin_r[a] > nr) { nr = bin_r[a]; - if (bin_g[a] > ng) + } + if (bin_g[a] > ng) { ng = bin_g[a]; - if (bin_b[a] > nb) + } + if (bin_b[a] > nb) { nb = bin_b[a]; - if (bin_a[a] > na) + } + if (bin_a[a] > na) { na = bin_a[a]; + } } divl = nl ? 1.0 / (double)nl : 1.0; diva = na ? 1.0 / (double)na : 1.0; @@ -1589,10 +1661,12 @@ void scopes_update(Scopes *scopes, scopes->hist.data_a[a] = bin_a[a] * diva; } - if (cm_processor) + if (cm_processor) { IMB_colormanagement_processor_free(cm_processor); - if (cache_handle) + } + if (cache_handle) { IMB_display_buffer_release(cache_handle); + } scopes->ok = 1; } @@ -1692,16 +1766,19 @@ void BKE_color_managed_view_settings_copy(ColorManagedViewSettings *new_settings new_settings->exposure = settings->exposure; new_settings->gamma = settings->gamma; - if (settings->curve_mapping) + if (settings->curve_mapping) { new_settings->curve_mapping = curvemapping_copy(settings->curve_mapping); - else + } + else { new_settings->curve_mapping = NULL; + } } void BKE_color_managed_view_settings_free(ColorManagedViewSettings *settings) { - if (settings->curve_mapping) + if (settings->curve_mapping) { curvemapping_free(settings->curve_mapping); + } } void BKE_color_managed_colorspace_settings_init( diff --git a/source/blender/blenkernel/intern/constraint.c b/source/blender/blenkernel/intern/constraint.c index 114bf5ec1e6..0e29f165992 100644 --- a/source/blender/blenkernel/intern/constraint.c +++ b/source/blender/blenkernel/intern/constraint.c @@ -120,7 +120,8 @@ void BKE_constraint_unique_name(bConstraint *con, ListBase *list) /* ----------------- Evaluation Loop Preparation --------------- */ /* package an object/bone for use in constraint evaluation */ -/* This function MEM_calloc's a bConstraintOb struct, that will need to be freed after evaluation */ +/* This function MEM_calloc's a bConstraintOb struct, + * that will need to be freed after evaluation */ bConstraintOb *BKE_constraints_make_evalob( Depsgraph *depsgraph, Scene *scene, Object *ob, void *subdata, short datatype) { @@ -156,8 +157,9 @@ bConstraintOb *BKE_constraints_make_evalob( } copy_m4_m4(cob->matrix, ob->obmat); } - else + else { unit_m4(cob->matrix); + } copy_m4_m4(cob->startmat, cob->matrix); break; @@ -181,8 +183,9 @@ bConstraintOb *BKE_constraints_make_evalob( /* matrix in world-space */ mul_m4_m4m4(cob->matrix, ob->obmat, cob->pchan->pose_mat); } - else + else { unit_m4(cob->matrix); + } copy_m4_m4(cob->startmat, cob->matrix); break; @@ -202,15 +205,16 @@ void BKE_constraints_clear_evalob(bConstraintOb *cob) float delta[4][4], imat[4][4]; /* prevent crashes */ - if (cob == NULL) + if (cob == NULL) { return; + } /* calculate delta of constraints evaluation */ invert_m4_m4(imat, cob->startmat); - /* XXX This would seem to be in wrong order. However, it does not work in 'right' order - would be nice to - * understand why premul is needed here instead of usual postmul? - * In any case, we **do not get a delta** here (e.g. startmat & matrix having same location, still gives - * a 'delta' with non-null translation component :/ ).*/ + /* XXX This would seem to be in wrong order. However, it does not work in 'right' order - + * would be nice to understand why premul is needed here instead of usual postmul? + * In any case, we **do not get a delta** here (e.g. startmat & matrix having same location, + * still gives a 'delta' with non-null translation component :/ ).*/ mul_m4_m4m4(delta, cob->matrix, imat); /* copy matrices back to source */ @@ -256,11 +260,13 @@ void BKE_constraint_mat_convertspace( float imat[4][4]; /* prevent crashes in these unlikely events */ - if (ob == NULL || mat == NULL) + if (ob == NULL || mat == NULL) { return; + } /* optimize trick - check if need to do anything */ - if (from == to) + if (from == to) { return; + } /* are we dealing with pose-channels or objects */ if (pchan) { @@ -347,8 +353,9 @@ void BKE_constraint_mat_convertspace( */ /* XXX This is actually an ugly hack, local space of a parent-less object *is* the same as * global space! - * Think what we want actually here is some kind of 'Final Space', i.e. once transformations - * are applied - users are often confused about this too, this is not consistent with bones + * Think what we want actually here is some kind of 'Final Space', i.e + * . once transformations are applied - users are often confused about this too, + * this is not consistent with bones * local space either... Meh :| * --mont29 */ @@ -513,10 +520,12 @@ static void contarget_get_lattice_mat(Object *ob, const char *substring, float m copy_m4_m4(mat, ob->obmat); /* get index of vertex group */ - if (defgroup == -1) + if (defgroup == -1) { return; - if (dv == NULL) + } + if (dv == NULL) { return; + } /* 1. Loop through control-points checking if in nominated vertex-group. * 2. If it is, add it to vec to find the average point. @@ -534,15 +543,18 @@ static void contarget_get_lattice_mat(Object *ob, const char *substring, float m } /* advance pointer to coordinate data */ - if (co) + if (co) { co += 3; - else + } + else { bp++; + } } /* find average location, then multiply by ob->obmat to find world-space location */ - if (grouped) + if (grouped) { mul_v3_fl(vec, 1.0f / grouped); + } mul_v3_m4v3(tvec, ob->obmat, vec); /* copy new location to matrix */ @@ -638,8 +650,9 @@ static void constraint_target_to_mat4(Object *ob, mul_m4_m4m4(mat, ob->obmat, tempmat); } } - else + else { copy_m4_m4(mat, ob->obmat); + } /* convert matrix space as required */ BKE_constraint_mat_convertspace(ob, pchan, mat, from, to, false); @@ -665,18 +678,18 @@ static void constraint_target_to_mat4(Object *ob, */ #if 0 static bConstraintTypeInfo CTI_CONSTRNAME = { - CONSTRAINT_TYPE_CONSTRNAME, /* type */ - sizeof(bConstrNameConstraint), /* size */ - "ConstrName", /* name */ - "bConstrNameConstraint", /* struct name */ - constrname_free, /* free data */ - constrname_id_looper, /* id looper */ - constrname_copy, /* copy data */ - constrname_new_data, /* new data */ - constrname_get_tars, /* get constraint targets */ - constrname_flush_tars, /* flush constraint targets */ - constrname_get_tarmat, /* get target matrix */ - constrname_evaluate, /* evaluate */ + CONSTRAINT_TYPE_CONSTRNAME, /* type */ + sizeof(bConstrNameConstraint), /* size */ + "ConstrName", /* name */ + "bConstrNameConstraint", /* struct name */ + constrname_free, /* free data */ + constrname_id_looper, /* id looper */ + constrname_copy, /* copy data */ + constrname_new_data, /* new data */ + constrname_get_tars, /* get constraint targets */ + constrname_flush_tars, /* flush constraint targets */ + constrname_get_tarmat, /* get target matrix */ + constrname_evaluate, /* evaluate */ }; #endif @@ -689,7 +702,7 @@ static void default_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bConstraintTarget *ct, float UNUSED(ctime)) { - if (VALID_CONS_TARGET(ct)) + if (VALID_CONS_TARGET(ct)) { constraint_target_to_mat4(ct->tar, ct->subtarget, ct->matrix, @@ -697,8 +710,10 @@ static void default_get_tarmat(struct Depsgraph *UNUSED(depsgraph), ct->space, con->flag, con->headtail); - else if (ct) + } + else if (ct) { unit_m4(ct->matrix); + } } /* This is a variant that extracts full transformation from B-Bone segments. @@ -709,7 +724,7 @@ static void default_get_tarmat_full_bbone(struct Depsgraph *UNUSED(depsgraph), bConstraintTarget *ct, float UNUSED(ctime)) { - if (VALID_CONS_TARGET(ct)) + if (VALID_CONS_TARGET(ct)) { constraint_target_to_mat4(ct->tar, ct->subtarget, ct->matrix, @@ -717,8 +732,10 @@ static void default_get_tarmat_full_bbone(struct Depsgraph *UNUSED(depsgraph), ct->space, con->flag | CONSTRAINT_BBONE_SHAPE_FULL, con->headtail); - else if (ct) + } + else if (ct) { unit_m4(ct->matrix); + } } /* This following macro should be used for all standard single-target *_get_tars functions @@ -905,24 +922,33 @@ static void childof_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar mat4_to_size(sizo, invmat); /* disable channels not enabled */ - if (!(data->flag & CHILDOF_LOCX)) + if (!(data->flag & CHILDOF_LOCX)) { loc[0] = loco[0] = 0.0f; - if (!(data->flag & CHILDOF_LOCY)) + } + if (!(data->flag & CHILDOF_LOCY)) { loc[1] = loco[1] = 0.0f; - if (!(data->flag & CHILDOF_LOCZ)) + } + if (!(data->flag & CHILDOF_LOCZ)) { loc[2] = loco[2] = 0.0f; - if (!(data->flag & CHILDOF_ROTX)) + } + if (!(data->flag & CHILDOF_ROTX)) { eul[0] = eulo[0] = 0.0f; - if (!(data->flag & CHILDOF_ROTY)) + } + if (!(data->flag & CHILDOF_ROTY)) { eul[1] = eulo[1] = 0.0f; - if (!(data->flag & CHILDOF_ROTZ)) + } + if (!(data->flag & CHILDOF_ROTZ)) { eul[2] = eulo[2] = 0.0f; - if (!(data->flag & CHILDOF_SIZEX)) + } + if (!(data->flag & CHILDOF_SIZEX)) { size[0] = sizo[0] = 1.0f; - if (!(data->flag & CHILDOF_SIZEY)) + } + if (!(data->flag & CHILDOF_SIZEY)) { size[1] = sizo[1] = 1.0f; - if (!(data->flag & CHILDOF_SIZEZ)) + } + if (!(data->flag & CHILDOF_SIZEZ)) { size[2] = sizo[2] = 1.0f; + } /* make new target mat and offset mat */ loc_eulO_size_to_mat4(ct->matrix, loc, eul, size, ct->rotOrder); @@ -942,12 +968,15 @@ static void childof_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar /* without this, changes to scale and rotation can change location * of a parentless bone or a disconnected bone. Even though its set * to zero above. */ - if (!(data->flag & CHILDOF_LOCX)) + if (!(data->flag & CHILDOF_LOCX)) { cob->matrix[3][0] = tempmat[3][0]; - if (!(data->flag & CHILDOF_LOCY)) + } + if (!(data->flag & CHILDOF_LOCY)) { cob->matrix[3][1] = tempmat[3][1]; - if (!(data->flag & CHILDOF_LOCZ)) + } + if (!(data->flag & CHILDOF_LOCZ)) { cob->matrix[3][2] = tempmat[3][2]; + } } } } @@ -1047,10 +1076,12 @@ static void vectomat(const float vec[3], n[1] = 0.0f; n[2] = 1.0f; } - if (axis > 2) + if (axis > 2) { axis -= 3; - else + } + else { negate_v3(n); + } /* n specifies the transformation of the track axis */ if (flags & TARGET_Z_UP) { @@ -1110,7 +1141,8 @@ static void trackto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar float size[3], vec[3]; float totmat[3][3]; - /* Get size property, since ob->scale is only the object's own relative size, not its global one */ + /* Get size property, since ob->scale is only the object's own relative size, + * not its global one. */ mat4_to_size(size, cob->matrix); /* Clear the object's rotation */ @@ -1210,7 +1242,7 @@ static void kinematic_get_tarmat(struct Depsgraph *UNUSED(depsgraph), { bKinematicConstraint *data = con->data; - if (VALID_CONS_TARGET(ct)) + if (VALID_CONS_TARGET(ct)) { constraint_target_to_mat4(ct->tar, ct->subtarget, ct->matrix, @@ -1218,6 +1250,7 @@ static void kinematic_get_tarmat(struct Depsgraph *UNUSED(depsgraph), ct->space, con->flag, con->headtail); + } else if (ct) { if (data->flag & CONSTRAINT_IK_AUTO) { Object *ob = cob->ob; @@ -1233,8 +1266,9 @@ static void kinematic_get_tarmat(struct Depsgraph *UNUSED(depsgraph), copy_v3_v3(ct->matrix[3], vec); } } - else + else { unit_m4(ct->matrix); + } } } @@ -1326,12 +1360,11 @@ static void followpath_get_tarmat(struct Depsgraph *UNUSED(depsgraph), Nurb *nu = cu->nurb.first; curvetime = cu->ctime - data->offset; - /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated, - * but this will only work if it actually is animated... + /* ctime is now a proper var setting of Curve which gets set by Animato like any other var + * that's animated, but this will only work if it actually is animated... * - * we divide the curvetime calculated in the previous step by the length of the path, to get a time - * factor, which then gets clamped to lie within 0.0 - 1.0 range - */ + * we divide the curvetime calculated in the previous step by the length of the path, + * to get a time factor, which then gets clamped to lie within 0.0 - 1.0 range. */ curvetime /= cu->pathlen; if (nu && nu->flagu & CU_NURB_CYCLIC) { @@ -1379,8 +1412,9 @@ static void followpath_get_tarmat(struct Depsgraph *UNUSED(depsgraph), } } } - else if (ct) + else if (ct) { unit_m4(ct->matrix); + } } static void followpath_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets) @@ -1404,17 +1438,21 @@ static void followpath_evaluate(bConstraint *con, bConstraintOb *cob, ListBase * mul_m4_m4m4(cob->matrix, ct->matrix, obmat); /* un-apply scaling caused by path */ - if ((data->followflag & FOLLOWPATH_RADIUS) == - 0) { /* XXX - assume that scale correction means that radius will have some scale error in it - Campbell */ + if ((data->followflag & FOLLOWPATH_RADIUS) == 0) { + /* XXX: Assume that scale correction means that radius + * will have some scale error in it - Campbell. */ float obsize[3]; mat4_to_size(obsize, cob->matrix); - if (obsize[0]) + if (obsize[0]) { mul_v3_fl(cob->matrix[0], size[0] / obsize[0]); - if (obsize[1]) + } + if (obsize[1]) { mul_v3_fl(cob->matrix[1], size[1] / obsize[1]); - if (obsize[2]) + } + if (obsize[2]) { mul_v3_fl(cob->matrix[2], size[2] / obsize[2]); + } } } } @@ -1441,28 +1479,34 @@ static void loclimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *UN bLocLimitConstraint *data = con->data; if (data->flag & LIMIT_XMIN) { - if (cob->matrix[3][0] < data->xmin) + if (cob->matrix[3][0] < data->xmin) { cob->matrix[3][0] = data->xmin; + } } if (data->flag & LIMIT_XMAX) { - if (cob->matrix[3][0] > data->xmax) + if (cob->matrix[3][0] > data->xmax) { cob->matrix[3][0] = data->xmax; + } } if (data->flag & LIMIT_YMIN) { - if (cob->matrix[3][1] < data->ymin) + if (cob->matrix[3][1] < data->ymin) { cob->matrix[3][1] = data->ymin; + } } if (data->flag & LIMIT_YMAX) { - if (cob->matrix[3][1] > data->ymax) + if (cob->matrix[3][1] > data->ymax) { cob->matrix[3][1] = data->ymax; + } } if (data->flag & LIMIT_ZMIN) { - if (cob->matrix[3][2] < data->zmin) + if (cob->matrix[3][2] < data->zmin) { cob->matrix[3][2] = data->zmin; + } } if (data->flag & LIMIT_ZMAX) { - if (cob->matrix[3][2] > data->zmax) + if (cob->matrix[3][2] > data->zmax) { cob->matrix[3][2] = data->zmax; + } } } @@ -1499,25 +1543,31 @@ static void rotlimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *UN /* limiting of euler values... */ if (data->flag & LIMIT_XROT) { - if (eul[0] < data->xmin) + if (eul[0] < data->xmin) { eul[0] = data->xmin; + } - if (eul[0] > data->xmax) + if (eul[0] > data->xmax) { eul[0] = data->xmax; + } } if (data->flag & LIMIT_YROT) { - if (eul[1] < data->ymin) + if (eul[1] < data->ymin) { eul[1] = data->ymin; + } - if (eul[1] > data->ymax) + if (eul[1] > data->ymax) { eul[1] = data->ymax; + } } if (data->flag & LIMIT_ZROT) { - if (eul[2] < data->zmin) + if (eul[2] < data->zmin) { eul[2] = data->zmin; + } - if (eul[2] > data->zmax) + if (eul[2] > data->zmax) { eul[2] = data->zmax; + } } loc_eulO_size_to_mat4(cob->matrix, loc, eul, size, cob->rotOrder); @@ -1549,36 +1599,45 @@ static void sizelimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *U mat4_to_size(obsize, cob->matrix); if (data->flag & LIMIT_XMIN) { - if (size[0] < data->xmin) + if (size[0] < data->xmin) { size[0] = data->xmin; + } } if (data->flag & LIMIT_XMAX) { - if (size[0] > data->xmax) + if (size[0] > data->xmax) { size[0] = data->xmax; + } } if (data->flag & LIMIT_YMIN) { - if (size[1] < data->ymin) + if (size[1] < data->ymin) { size[1] = data->ymin; + } } if (data->flag & LIMIT_YMAX) { - if (size[1] > data->ymax) + if (size[1] > data->ymax) { size[1] = data->ymax; + } } if (data->flag & LIMIT_ZMIN) { - if (size[2] < data->zmin) + if (size[2] < data->zmin) { size[2] = data->zmin; + } } if (data->flag & LIMIT_ZMAX) { - if (size[2] > data->zmax) + if (size[2] > data->zmax) { size[2] = data->zmax; + } } - if (obsize[0]) + if (obsize[0]) { mul_v3_fl(cob->matrix[0], size[0] / obsize[0]); - if (obsize[1]) + } + if (obsize[1]) { mul_v3_fl(cob->matrix[1], size[1] / obsize[1]); - if (obsize[2]) + } + if (obsize[2]) { mul_v3_fl(cob->matrix[2], size[2] / obsize[2]); + } } static bConstraintTypeInfo CTI_SIZELIMIT = { @@ -1647,28 +1706,32 @@ static void loclike_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar if (VALID_CONS_TARGET(ct)) { float offset[3] = {0.0f, 0.0f, 0.0f}; - if (data->flag & LOCLIKE_OFFSET) + if (data->flag & LOCLIKE_OFFSET) { copy_v3_v3(offset, cob->matrix[3]); + } if (data->flag & LOCLIKE_X) { cob->matrix[3][0] = ct->matrix[3][0]; - if (data->flag & LOCLIKE_X_INVERT) + if (data->flag & LOCLIKE_X_INVERT) { cob->matrix[3][0] *= -1; + } cob->matrix[3][0] += offset[0]; } if (data->flag & LOCLIKE_Y) { cob->matrix[3][1] = ct->matrix[3][1]; - if (data->flag & LOCLIKE_Y_INVERT) + if (data->flag & LOCLIKE_Y_INVERT) { cob->matrix[3][1] *= -1; + } cob->matrix[3][1] += offset[1]; } if (data->flag & LOCLIKE_Z) { cob->matrix[3][2] = ct->matrix[3][2]; - if (data->flag & LOCLIKE_Z_INVERT) + if (data->flag & LOCLIKE_Z_INVERT) { cob->matrix[3][2] *= -1; + } cob->matrix[3][2] += offset[2]; } } @@ -1745,42 +1808,53 @@ static void rotlike_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar copy_v3_v3(loc, cob->matrix[3]); mat4_to_size(size, cob->matrix); - /* to allow compatible rotations, must get both rotations in the order of the owner... */ + /* To allow compatible rotations, must get both rotations in the order of the owner... */ mat4_to_eulO(obeul, cob->rotOrder, cob->matrix); - /* we must get compatible eulers from the beginning because some of them can be modified below (see bug #21875) */ + /* We must get compatible eulers from the beginning because + * some of them can be modified below (see bug T21875). */ mat4_to_compatible_eulO(eul, obeul, cob->rotOrder, ct->matrix); - if ((data->flag & ROTLIKE_X) == 0) + if ((data->flag & ROTLIKE_X) == 0) { eul[0] = obeul[0]; + } else { - if (data->flag & ROTLIKE_OFFSET) + if (data->flag & ROTLIKE_OFFSET) { rotate_eulO(eul, cob->rotOrder, 'X', obeul[0]); + } - if (data->flag & ROTLIKE_X_INVERT) + if (data->flag & ROTLIKE_X_INVERT) { eul[0] *= -1; + } } - if ((data->flag & ROTLIKE_Y) == 0) + if ((data->flag & ROTLIKE_Y) == 0) { eul[1] = obeul[1]; + } else { - if (data->flag & ROTLIKE_OFFSET) + if (data->flag & ROTLIKE_OFFSET) { rotate_eulO(eul, cob->rotOrder, 'Y', obeul[1]); + } - if (data->flag & ROTLIKE_Y_INVERT) + if (data->flag & ROTLIKE_Y_INVERT) { eul[1] *= -1; + } } - if ((data->flag & ROTLIKE_Z) == 0) + if ((data->flag & ROTLIKE_Z) == 0) { eul[2] = obeul[2]; + } else { - if (data->flag & ROTLIKE_OFFSET) + if (data->flag & ROTLIKE_OFFSET) { rotate_eulO(eul, cob->rotOrder, 'Z', obeul[2]); + } - if (data->flag & ROTLIKE_Z_INVERT) + if (data->flag & ROTLIKE_Z_INVERT) { eul[2] *= -1; + } } - /* good to make eulers compatible again, since we don't know how much they were changed above */ + /* Good to make eulers compatible again, + * since we don't know how much they were changed above. */ compatible_eul(eul, obeul); loc_eulO_size_to_mat4(cob->matrix, loc, eul, size, cob->rotOrder); } @@ -1979,8 +2053,9 @@ static void samevolume_evaluate(bConstraint *con, bConstraintOb *cob, ListBase * /* calculate normalizing scale factor for non-essential values */ total_scale = obsize[0] * obsize[1] * obsize[2]; - if (total_scale != 0) + if (total_scale != 0) { fac = sqrtf(volume / total_scale); + } /* apply scaling factor to the channels not being kept */ switch (data->flag) { @@ -2066,8 +2141,9 @@ static void pycon_id_looper(bConstraint *con, ConstraintIDFunc func, void *userd bConstraintTarget *ct; /* targets */ - for (ct = data->targets.first; ct; ct = ct->next) + for (ct = data->targets.first; ct; ct = ct->next) { func(con, (ID **)&ct->tar, false, userdata); + } /* script */ func(con, (ID **)&data->text, true, userdata); @@ -2103,12 +2179,14 @@ static void pycon_get_tarmat(struct Depsgraph *UNUSED(depsgraph), /* only execute target calculation if allowed */ #ifdef WITH_PYTHON - if (G.f & G_FLAG_SCRIPT_AUTOEXEC) + if (G.f & G_FLAG_SCRIPT_AUTOEXEC) { BPY_pyconstraint_target(data, ct); + } #endif } - else if (ct) + else if (ct) { unit_m4(ct->matrix); + } } static void pycon_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets) @@ -2120,8 +2198,9 @@ static void pycon_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targe bPythonConstraint *data = con->data; /* only evaluate in python if we're allowed to do so */ - if ((G.f & G_FLAG_SCRIPT_AUTOEXEC) == 0) + if ((G.f & G_FLAG_SCRIPT_AUTOEXEC) == 0) { return; + } /* Now, run the actual 'constraint' function, which should only access the matrices */ BPY_pyconstraint_exec(data, cob, targets); @@ -2214,8 +2293,9 @@ static void armdef_accumulate_matrix(float obmat[4][4], float r_sum_mat[4][4], DualQuat *r_sum_dq) { - if (weight == 0.0f) + if (weight == 0.0f) { return; + } /* Convert the selected matrix into object space. */ float mat[4][4]; @@ -2478,11 +2558,12 @@ static void actcon_get_tarmat(struct Depsgraph *UNUSED(depsgraph), CLAMP(s, 0, 1); t = (s * (data->end - data->start)) + data->start; - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("do Action Constraint %s - Ob %s Pchan %s\n", con->name, cob->ob->id.name + 2, (cob->pchan) ? cob->pchan->name : NULL); + } /* Get the appropriate information from the action */ if (cob->type == CONSTRAINT_OBTYPE_OBJECT || (data->flag & ACTCON_BONE_USE_OBJECT_ACTION)) { @@ -2498,9 +2579,9 @@ static void actcon_get_tarmat(struct Depsgraph *UNUSED(depsgraph), bPose pose = {{0}}; bPoseChannel *pchan, *tchan; - /* make a copy of the bone of interest in the temp pose before evaluating action, so that it can get set - * - we need to manually copy over a few settings, including rotation order, otherwise this fails - */ + /* make a copy of the bone of interest in the temp pose before evaluating action, + * so that it can get set - we need to manually copy over a few settings, + * including rotation order, otherwise this fails. */ pchan = cob->pchan; tchan = BKE_pose_channel_verify(&pose, pchan->name); @@ -2944,8 +3025,9 @@ static void distlimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t /* if inside, then move to surface */ if (dist <= data->dist) { clamp_surf = 1; - if (dist != 0.0f) + if (dist != 0.0f) { sfac = data->dist / dist; + } } /* if soft-distance is enabled, start fading once owner is dist+softdist from the target */ else if (data->flag & LIMITDIST_USESOFT) { @@ -2958,8 +3040,9 @@ static void distlimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t /* if outside, then move to surface */ if (dist >= data->dist) { clamp_surf = 1; - if (dist != 0.0f) + if (dist != 0.0f) { sfac = data->dist / dist; + } } /* if soft-distance is enabled, start fading once owner is dist-soft from the target */ else if (data->flag & LIMITDIST_USESOFT) { @@ -2967,8 +3050,9 @@ static void distlimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t if (dist >= (data->dist - data->soft)) { sfac = (float)(data->soft * (1.0f - expf(-(dist - data->dist) / data->soft)) + data->dist); - if (dist != 0.0f) + if (dist != 0.0f) { sfac /= dist; + } clamp_surf = 1; } @@ -2977,8 +3061,9 @@ static void distlimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t else { if (IS_EQF(dist, data->dist) == 0) { clamp_surf = 1; - if (dist != 0.0f) + if (dist != 0.0f) { sfac = data->dist / dist; + } } } @@ -3409,8 +3494,9 @@ static void clampto_get_tarmat(struct Depsgraph *UNUSED(depsgraph), /* technically, this isn't really needed for evaluation, but we don't know what else * might end up calling this... */ - if (ct) + if (ct) { unit_m4(ct->matrix); + } } static void clampto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targets) @@ -3449,15 +3535,19 @@ static void clampto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar * extent. Otherwise, default to the x-axis, as that is quite * frequently used. */ - if ((size[2] > size[0]) && (size[2] > size[1])) + if ((size[2] > size[0]) && (size[2] > size[1])) { clamp_axis = CLAMPTO_Z - 1; - else if ((size[1] > size[0]) && (size[1] > size[2])) + } + else if ((size[1] > size[0]) && (size[1] > size[2])) { clamp_axis = CLAMPTO_Y - 1; - else + } + else { clamp_axis = CLAMPTO_X - 1; + } } - else + else { clamp_axis = data->flag - 1; + } /* 2. determine position relative to curve on a 0-1 scale based on bounding box */ if (data->flag2 & CLAMPTO_CYCLIC) { @@ -3473,7 +3563,8 @@ static void clampto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar offset = curveMin[clamp_axis] - ceilf((curveMin[clamp_axis] - ownLoc[clamp_axis]) / len) * len; - /* now, we calculate as per normal, except using offset instead of curveMin[clamp_axis] */ + /* Now, we calculate as per normal, + * except using offset instead of curveMin[clamp_axis]. */ curvetime = (ownLoc[clamp_axis] - offset) / (len); } else if (ownLoc[clamp_axis] > curveMax[clamp_axis]) { @@ -3481,7 +3572,8 @@ static void clampto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar offset = curveMax[clamp_axis] + (int)((ownLoc[clamp_axis] - curveMax[clamp_axis]) / len) * len; - /* now, we calculate as per normal, except using offset instead of curveMax[clamp_axis] */ + /* Now, we calculate as per normal, + * except using offset instead of curveMax[clamp_axis]. */ curvetime = (ownLoc[clamp_axis] - offset) / (len); } else { @@ -3496,15 +3588,19 @@ static void clampto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar } else { /* no cyclic, so position is clamped to within the bounding box */ - if (ownLoc[clamp_axis] <= curveMin[clamp_axis]) + if (ownLoc[clamp_axis] <= curveMin[clamp_axis]) { curvetime = 0.0f; - else if (ownLoc[clamp_axis] >= curveMax[clamp_axis]) + } + else if (ownLoc[clamp_axis] >= curveMax[clamp_axis]) { curvetime = 1.0f; - else if (IS_EQF((curveMax[clamp_axis] - curveMin[clamp_axis]), 0.0f) == false) + } + else if (IS_EQF((curveMax[clamp_axis] - curveMin[clamp_axis]), 0.0f) == false) { curvetime = (ownLoc[clamp_axis] - curveMin[clamp_axis]) / (curveMax[clamp_axis] - curveMin[clamp_axis]); - else + } + else { curvetime = 0.0f; + } } /* 3. position on curve */ @@ -3599,11 +3695,10 @@ static void transform_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t mat4_to_size(dvec, ct->matrix); if (is_negative_m4(ct->matrix)) { - /* Bugfix [#27886] - * We can't be sure which axis/axes are negative, though we know that something is negative. - * Assume we don't care about negativity of separate axes. <--- This is a limitation that - * riggers will have to live with for now. - */ + /* Bugfix T27886: (this is a limitation that riggers will have to live with for now). + * We can't be sure which axis/axes are negative, + * though we know that something is negative. + * Assume we don't care about negativity of separate axes. */ negate_v3(dvec); } from_min = data->from_min_scale; @@ -3630,20 +3725,24 @@ static void transform_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t /* determine where in range current transforms lie */ if (data->expo) { for (i = 0; i < 3; i++) { - if (from_max[i] - from_min[i]) + if (from_max[i] - from_min[i]) { sval[i] = (dvec[i] - from_min[i]) / (from_max[i] - from_min[i]); - else + } + else { sval[i] = 0.0f; + } } } else { /* clamp transforms out of range */ for (i = 0; i < 3; i++) { CLAMP(dvec[i], from_min[i], from_max[i]); - if (from_max[i] - from_min[i]) + if (from_max[i] - from_min[i]) { sval[i] = (dvec[i] - from_min[i]) / (from_max[i] - from_min[i]); - else + } + else { sval[i] = 0.0f; + } } } @@ -3838,9 +3937,10 @@ static void shrinkwrap_get_tarmat(struct Depsgraph *UNUSED(depsgraph), break; } - /* transform normal into requested space */ - /* Note that in this specific case, we need to keep scaling in non-parented 'local2world' object - * case, because SpaceTransform also takes it into account when handling normals. See T42447. */ + /* Transform normal into requested space */ + /* Note that in this specific case, we need to keep scaling in non-parented 'local2world' + * object case, because SpaceTransform also takes it into account when handling normals. + * See T42447. */ unit_m4(mat); BKE_constraint_mat_convertspace( cob->ob, cob->pchan, mat, CONSTRAINT_SPACE_LOCAL, scon->projAxisSpace, true); @@ -4100,8 +4200,9 @@ static void splineik_free(bConstraint *con) bSplineIKConstraint *data = con->data; /* binding array */ - if (data->points) + if (data->points) { MEM_freeN(data->points); + } } static void splineik_copy(bConstraint *con, bConstraint *srccon) @@ -4168,8 +4269,9 @@ static void splineik_get_tarmat(struct Depsgraph *UNUSED(depsgraph), /* technically, this isn't really needed for evaluation, but we don't know what else * might end up calling this... */ - if (ct) + if (ct) { unit_m4(ct->matrix); + } } static bConstraintTypeInfo CTI_SPLINEIK = { @@ -4244,13 +4346,15 @@ static void pivotcon_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *ta /* check which range might be violated */ if (data->rotAxis < PIVOTCON_AXIS_X) { /* negative rotations (data->rotAxis = 0 -> 2) */ - if (rot[data->rotAxis] > 0.0f) + if (rot[data->rotAxis] > 0.0f) { return; + } } else { /* positive rotations (data->rotAxis = 3 -> 5 */ - if (rot[data->rotAxis - PIVOTCON_AXIS_X] < 0.0f) + if (rot[data->rotAxis - PIVOTCON_AXIS_X] < 0.0f) { return; + } } } @@ -4345,26 +4449,32 @@ static void followtrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase float ctime = DEG_get_ctime(depsgraph); float framenr; - if (data->flag & FOLLOWTRACK_ACTIVECLIP) + if (data->flag & FOLLOWTRACK_ACTIVECLIP) { clip = scene->clip; + } - if (!clip || !data->track[0] || !camob_eval) + if (!clip || !data->track[0] || !camob_eval) { return; + } tracking = &clip->tracking; - if (data->object[0]) + if (data->object[0]) { tracking_object = BKE_tracking_object_get_named(tracking, data->object); - else + } + else { tracking_object = BKE_tracking_object_get_camera(tracking); + } - if (!tracking_object) + if (!tracking_object) { return; + } track = BKE_tracking_track_get_named(tracking, tracking_object, data->track); - if (!track) + if (!track) { return; + } framenr = BKE_movieclip_remap_scene_to_clip_frame(clip, ctime); @@ -4476,10 +4586,12 @@ static void followtrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase vec[1] = params.ortho_scale * (pos[1] - 0.5f + params.shifty); vec[2] = -len; - if (aspect > 1.0f) + if (aspect > 1.0f) { vec[1] /= aspect; - else + } + else { vec[0] *= aspect; + } mul_v3_m4v3(disp, camob_eval->obmat, vec); @@ -4496,10 +4608,12 @@ static void followtrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase vec[1] = d * (2.0f * (pos[1] + params.shifty) - 1.0f); vec[2] = -len; - if (aspect > 1.0f) + if (aspect > 1.0f) { vec[1] /= aspect; - else + } + else { vec[0] *= aspect; + } mul_v3_m4v3(disp, camob_eval->obmat, vec); @@ -4586,8 +4700,9 @@ static void camerasolver_evaluate(bConstraint *con, bConstraintOb *cob, ListBase bCameraSolverConstraint *data = con->data; MovieClip *clip = data->clip; - if (data->flag & CAMERASOLVER_ACTIVECLIP) + if (data->flag & CAMERASOLVER_ACTIVECLIP) { clip = scene->clip; + } if (clip) { float mat[4][4], obmat[4][4]; @@ -4646,11 +4761,13 @@ static void objectsolver_evaluate(bConstraint *con, bConstraintOb *cob, ListBase MovieClip *clip = data->clip; Object *camob = data->camera ? data->camera : scene->camera; - if (data->flag & OBJECTSOLVER_ACTIVECLIP) + if (data->flag & OBJECTSOLVER_ACTIVECLIP) { clip = scene->clip; + } - if (!camob || !clip) + if (!camob || !clip) { return; + } if (clip) { MovieTracking *tracking = &clip->tracking; @@ -4718,13 +4835,9 @@ static void transformcache_evaluate(bConstraint *con, bConstraintOb *cob, ListBa const float frame = DEG_get_ctime(cob->depsgraph); const float time = BKE_cachefile_time_offset(cache_file, frame, FPS); - /* Must always load ABC handle on original. */ - CacheFile *cache_file_orig = (CacheFile *)DEG_get_original_id(&cache_file->id); - BKE_cachefile_ensure_handle(G.main, cache_file_orig); - - if (!data->reader) { - data->reader = CacheReader_open_alembic_object( - cache_file_orig->handle, data->reader, cob->ob, data->object_path); + if (!data->reader || !STREQ(data->reader_object_path, data->object_path)) { + STRNCPY(data->reader_object_path, data->object_path); + BKE_cachefile_reader_open(cache_file, &data->reader, cob->ob, data->object_path); } ABC_get_transform(data->reader, cob->matrix, time, cache_file->scale); @@ -4742,12 +4855,8 @@ static void transformcache_copy(bConstraint *con, bConstraint *srccon) BLI_strncpy(dst->object_path, src->object_path, sizeof(dst->object_path)); dst->cache_file = src->cache_file; - -#ifdef WITH_ALEMBIC - if (dst->reader) { - CacheReader_incref(dst->reader); - } -#endif + dst->reader = NULL; + dst->reader_object_path[0] = '\0'; } static void transformcache_free(bConstraint *con) @@ -4755,10 +4864,8 @@ static void transformcache_free(bConstraint *con) bTransformCacheConstraint *data = con->data; if (data->reader) { -#ifdef WITH_ALEMBIC - CacheReader_free(data->reader); -#endif - data->reader = NULL; + BKE_cachefile_reader_free(data->cache_file, &data->reader); + data->reader_object_path[0] = '\0'; } } @@ -4858,10 +4965,12 @@ const bConstraintTypeInfo *BKE_constraint_typeinfo_from_type(int type) const bConstraintTypeInfo *BKE_constraint_typeinfo_get(bConstraint *con) { /* only return typeinfo for valid constraints */ - if (con) + if (con) { return BKE_constraint_typeinfo_from_type(con->type); - else + } + else { return NULL; + } } /* ************************* General Constraints API ************************** */ @@ -4879,8 +4988,9 @@ static void con_unlink_refs_cb(bConstraint *UNUSED(con), bool is_reference, void *UNUSED(userData)) { - if (*idpoin && is_reference) + if (*idpoin && is_reference) { id_us_min(*idpoin); + } } /** @@ -4895,12 +5005,14 @@ void BKE_constraint_free_data_ex(bConstraint *con, bool do_id_user) if (cti) { /* perform any special freeing constraint may have */ - if (cti->free_data) + if (cti->free_data) { cti->free_data(con); + } /* unlink the referenced resources it uses */ - if (do_id_user && cti->id_looper) + if (do_id_user && cti->id_looper) { cti->id_looper(con, con_unlink_refs_cb, NULL); + } } /* free constraint data now */ @@ -4919,8 +5031,9 @@ void BKE_constraints_free_ex(ListBase *list, bool do_id_user) bConstraint *con; /* Free constraint data and also any extra data */ - for (con = list->first; con; con = con->next) + for (con = list->first; con; con = con->next) { BKE_constraint_free_data_ex(con, do_id_user); + } /* Free the whole list */ BLI_freelistN(list); @@ -4979,8 +5092,9 @@ static bConstraint *add_new_constraint_internal(const char *name, short type) con->data = MEM_callocN(cti->size, cti->structName); /* only constraints that change any settings need this */ - if (cti->new_data) + if (cti->new_data) { cti->new_data(con->data); + } /* if no name is provided, use the type of the constraint as the name */ newName = (name && name[0]) ? name : DATA_(cti->name); @@ -5024,8 +5138,9 @@ static bConstraint *add_new_constraint(Object *ob, * Armature layer, we must tag newly added constraints with a flag which allows them * to persist after proxy syncing has been done */ - if (BKE_constraints_proxylocked_owner(ob, pchan)) + if (BKE_constraints_proxylocked_owner(ob, pchan)) { con->flag |= CONSTRAINT_PROXY_LOCAL; + } /* make this constraint the active one */ BKE_constraints_active_set(list, con); @@ -5062,8 +5177,9 @@ bConstraint *BKE_constraint_add_for_pose(Object *ob, const char *name, short type) { - if (pchan == NULL) + if (pchan == NULL) { return NULL; + } return add_new_constraint(ob, pchan, name, type); } @@ -5085,8 +5201,9 @@ void BKE_constraints_id_loop(ListBase *conlist, ConstraintIDFunc func, void *use const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con); if (cti) { - if (cti->id_looper) + if (cti->id_looper) { cti->id_looper(con, func, userdata); + } } } } @@ -5099,19 +5216,22 @@ static void con_extern_cb(bConstraint *UNUSED(con), bool UNUSED(is_reference), void *UNUSED(userData)) { - if (*idpoin && ID_IS_LINKED(*idpoin)) + if (*idpoin && ID_IS_LINKED(*idpoin)) { id_lib_extern(*idpoin); + } } -/* helper for BKE_constraints_copy(), to be used for making sure that usercounts of copied ID's are fixed up */ +/* helper for BKE_constraints_copy(), + * to be used for making sure that usercounts of copied ID's are fixed up */ static void con_fix_copied_refs_cb(bConstraint *UNUSED(con), ID **idpoin, bool is_reference, void *UNUSED(userData)) { /* increment usercount if this is a reference type */ - if ((*idpoin) && (is_reference)) + if ((*idpoin) && (is_reference)) { id_us_plus(*idpoin); + } } /** Copies a single constraint's data (\a dst must already be a shallow copy of \a src). */ @@ -5128,8 +5248,9 @@ static void constraint_copy_data_ex(bConstraint *dst, /* only do specific constraints if required */ if (cti) { /* perform custom copying operations if needed */ - if (cti->copy_data) + if (cti->copy_data) { cti->copy_data(dst, src); + } /* Fix usercounts for all referenced data that need it. */ if (cti->id_looper && (flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) { @@ -5139,8 +5260,9 @@ static void constraint_copy_data_ex(bConstraint *dst, /* for proxies we don't want to make extern */ if (do_extern) { /* go over used ID-links for this constraint to ensure that they are valid for proxies */ - if (cti->id_looper) + if (cti->id_looper) { cti->id_looper(dst, con_extern_cb, NULL); + } } } } @@ -5188,8 +5310,9 @@ bConstraint *BKE_constraints_active_get(ListBase *list) /* search for the first constraint with the 'active' flag set */ if (list) { for (con = list->first; con; con = con->next) { - if (con->flag & CONSTRAINT_ACTIVE) + if (con->flag & CONSTRAINT_ACTIVE) { return con; + } } } @@ -5204,10 +5327,12 @@ void BKE_constraints_active_set(ListBase *list, bConstraint *con) if (list) { for (c = list->first; c; c = c->next) { - if (c == con) + if (c == con) { c->flag |= CONSTRAINT_ACTIVE; - else + } + else { c->flag &= ~CONSTRAINT_ACTIVE; + } } } } @@ -5332,7 +5457,8 @@ static bConstraint *constraint_find_original_for_update(bConstraintOb *cob, bCon /* -------- Constraints and Proxies ------- */ -/* Rescue all constraints tagged as being CONSTRAINT_PROXY_LOCAL (i.e. added to bone that's proxy-synced in this file) */ +/* Rescue all constraints tagged as being CONSTRAINT_PROXY_LOCAL + * (i.e. added to bone that's proxy-synced in this file) */ void BKE_constraints_proxylocal_extract(ListBase *dst, ListBase *src) { bConstraint *con, *next; @@ -5358,8 +5484,9 @@ bool BKE_constraints_proxylocked_owner(Object *ob, bPoseChannel *pchan) bArmature *arm = ob->data; /* On bone-level, check if bone is on proxy-protected layer */ - if ((pchan->bone) && (pchan->bone->layer & arm->layer_protected)) + if ((pchan->bone) && (pchan->bone->layer & arm->layer_protected)) { return true; + } } else { /* FIXME: constraints on object-level are not handled well yet */ @@ -5373,8 +5500,8 @@ bool BKE_constraints_proxylocked_owner(Object *ob, bPoseChannel *pchan) /* -------- Target-Matrix Stuff ------- */ /* This function is a relic from the prior implementations of the constraints system, when all - * constraints either had one or no targets. It used to be called during the main constraint solving - * loop, but is now only used for the remaining cases for a few constraints. + * constraints either had one or no targets. It used to be called during the main constraint + * solving loop, but is now only used for the remaining cases for a few constraints. * * None of the actual calculations of the matrices should be done here! Also, this function is * not to be used by any new constraints, particularly any that have multiple targets. @@ -5437,14 +5564,16 @@ void BKE_constraint_target_matrix_get(struct Depsgraph *depsgraph, ct = BLI_findlink(&targets, index); if (ct) { - if (cti->get_target_matrix) + if (cti->get_target_matrix) { cti->get_target_matrix(depsgraph, con, cob, ct, ctime); + } copy_m4_m4(mat, ct->matrix); } /* free targets + 'constraint-ob' */ - if (cti->flush_constraint_targets) + if (cti->flush_constraint_targets) { cti->flush_constraint_targets(con, &targets, 1); + } MEM_freeN(cob); } else { @@ -5475,12 +5604,14 @@ void BKE_constraint_targets_for_solving_get(struct Depsgraph *depsgraph, * - calculate if possible, otherwise just initialize as identity matrix */ if (cti->get_target_matrix) { - for (ct = targets->first; ct; ct = ct->next) + for (ct = targets->first; ct; ct = ct->next) { cti->get_target_matrix(depsgraph, con, cob, ct, ctime); + } } else { - for (ct = targets->first; ct; ct = ct->next) + for (ct = targets->first; ct; ct = ct->next) { unit_m4(ct->matrix); + } } } } @@ -5503,8 +5634,9 @@ void BKE_constraints_solve(struct Depsgraph *depsgraph, float enf; /* check that there is a valid constraint object to evaluate */ - if (cob == NULL) + if (cob == NULL) { return; + } /* loop over available constraints, solving and blending them */ for (con = conlist->first; con; con = con->next) { @@ -5512,16 +5644,20 @@ void BKE_constraints_solve(struct Depsgraph *depsgraph, ListBase targets = {NULL, NULL}; /* these we can skip completely (invalid constraints...) */ - if (cti == NULL) + if (cti == NULL) { continue; - if (con->flag & (CONSTRAINT_DISABLE | CONSTRAINT_OFF)) + } + if (con->flag & (CONSTRAINT_DISABLE | CONSTRAINT_OFF)) { continue; + } /* these constraints can't be evaluated anyway */ - if (cti->evaluate_constraint == NULL) + if (cti->evaluate_constraint == NULL) { continue; + } /* influence == 0 should be ignored */ - if (con->enforce == 0.0f) + if (con->enforce == 0.0f) { continue; + } /* influence of constraint * - value should have been set from animation data already @@ -5550,14 +5686,15 @@ void BKE_constraints_solve(struct Depsgraph *depsgraph, } /* move owner back into worldspace for next constraint/other business */ - if ((con->flag & CONSTRAINT_SPACEONCE) == 0) + if ((con->flag & CONSTRAINT_SPACEONCE) == 0) { BKE_constraint_mat_convertspace( cob->ob, cob->pchan, cob->matrix, con->ownspace, CONSTRAINT_SPACE_WORLD, false); + } /* Interpolate the enforcement, to blend result of constraint into final owner transform - * - all this happens in worldspace to prevent any weirdness creeping in ([#26014] and [#25725]), - * since some constraints may not convert the solution back to the input space before blending - * but all are guaranteed to end up in good "worldspace" result + * - all this happens in worldspace to prevent any weirdness creeping in + * (T26014 and T25725), since some constraints may not convert the solution back to the input + * space before blending but all are guaranteed to end up in good "worldspace" result. */ /* Note: all kind of stuff here before (caused trouble), much easier to just interpolate, * or did I miss something? -jahka (r.32105) */ diff --git a/source/blender/blenkernel/intern/context.c b/source/blender/blenkernel/intern/context.c index d9ee3ab6d15..4383b6a1f9b 100644 --- a/source/blender/blenkernel/intern/context.c +++ b/source/blender/blenkernel/intern/context.c @@ -134,8 +134,9 @@ bContextStore *CTX_store_add(ListBase *contexts, const char *name, PointerRNA *p ctx = MEM_dupallocN(lastctx); BLI_duplicatelist(&ctx->entries, &lastctx->entries); } - else + else { ctx = MEM_callocN(sizeof(bContextStore), "bContextStore"); + } BLI_addtail(contexts, ctx); } @@ -164,8 +165,9 @@ bContextStore *CTX_store_add_all(ListBase *contexts, bContextStore *context) ctx = MEM_dupallocN(lastctx); BLI_duplicatelist(&ctx->entries, &lastctx->entries); } - else + else { ctx = MEM_callocN(sizeof(bContextStore), "bContextStore"); + } BLI_addtail(contexts, ctx); } @@ -266,8 +268,9 @@ static void *ctx_wm_python_context_get(const bContext *C, #endif /* don't allow UI context access from non-main threads */ - if (!BLI_thread_is_main()) + if (!BLI_thread_is_main()) { return NULL; + } return fall_through; } @@ -290,8 +293,9 @@ static int ctx_data_get(bContext *C, const char *member, bContextDataResult *res #endif /* don't allow UI context access from non-main threads */ - if (!BLI_thread_is_main()) + if (!BLI_thread_is_main()) { return done; + } /* we check recursion to ensure that we do not get infinite * loops requesting data from ourselves in a context callback */ @@ -317,16 +321,18 @@ static int ctx_data_get(bContext *C, const char *member, bContextDataResult *res C->data.recursion = 2; if (ar->type && ar->type->context) { ret = ar->type->context(C, member, result); - if (ret) + if (ret) { done = -(-ret | -done); + } } } if (done != 1 && recursion < 3 && (sa = CTX_wm_area(C))) { C->data.recursion = 3; if (sa->type && sa->type->context) { ret = sa->type->context(C, member, result); - if (ret) + if (ret) { done = -(-ret | -done); + } } } if (done != 1 && recursion < 4 && (sc = CTX_wm_screen(C))) { @@ -334,8 +340,9 @@ static int ctx_data_get(bContext *C, const char *member, bContextDataResult *res C->data.recursion = 4; if (cb) { ret = cb(C, member, result); - if (ret) + if (ret) { done = -(-ret | -done); + } } } @@ -464,11 +471,13 @@ static void data_dir_add(ListBase *lb, const char *member, const bool use_all) { LinkData *link; - if ((use_all == false) && STREQ(member, "scene")) /* exception */ + if ((use_all == false) && STREQ(member, "scene")) { /* exception */ return; + } - if (BLI_findstring(lb, member, offsetof(LinkData, data))) + if (BLI_findstring(lb, member, offsetof(LinkData, data))) { return; + } link = MEM_callocN(sizeof(LinkData), "LinkData"); link->data = (void *)member; @@ -519,33 +528,40 @@ ListBase CTX_data_dir_get_ex(const bContext *C, if (use_store && C->wm.store) { bContextStoreEntry *entry; - for (entry = C->wm.store->entries.first; entry; entry = entry->next) + for (entry = C->wm.store->entries.first; entry; entry = entry->next) { data_dir_add(&lb, entry->name, use_all); + } } if ((ar = CTX_wm_region(C)) && ar->type && ar->type->context) { memset(&result, 0, sizeof(result)); ar->type->context(C, "", &result); - if (result.dir) - for (a = 0; result.dir[a]; a++) + if (result.dir) { + for (a = 0; result.dir[a]; a++) { data_dir_add(&lb, result.dir[a], use_all); + } + } } if ((sa = CTX_wm_area(C)) && sa->type && sa->type->context) { memset(&result, 0, sizeof(result)); sa->type->context(C, "", &result); - if (result.dir) - for (a = 0; result.dir[a]; a++) + if (result.dir) { + for (a = 0; result.dir[a]; a++) { data_dir_add(&lb, result.dir[a], use_all); + } + } } if ((sc = CTX_wm_screen(C)) && sc->context) { bContextDataCallback cb = sc->context; memset(&result, 0, sizeof(result)); cb(C, "", &result); - if (result.dir) - for (a = 0; result.dir[a]; a++) + if (result.dir) { + for (a = 0; result.dir[a]; a++) { data_dir_add(&lb, result.dir[a], use_all); + } + } } return lb; @@ -605,8 +621,9 @@ int ctx_data_list_count(const bContext *C, int (*func)(const bContext *, ListBas BLI_freelistN(&list); return tot; } - else + else { return 0; + } } void CTX_data_dir_set(bContextDataResult *result, const char **dir) @@ -685,8 +702,9 @@ struct wmMsgBus *CTX_wm_message_bus(const bContext *C) struct ReportList *CTX_wm_reports(const bContext *C) { - if (C->wm.manager) + if (C->wm.manager) { return &(C->wm.manager->reports); + } return NULL; } @@ -694,8 +712,9 @@ struct ReportList *CTX_wm_reports(const bContext *C) View3D *CTX_wm_view3d(const bContext *C) { ScrArea *sa = CTX_wm_area(C); - if (sa && sa->spacetype == SPACE_VIEW3D) + if (sa && sa->spacetype == SPACE_VIEW3D) { return sa->spacedata.first; + } return NULL; } @@ -704,129 +723,146 @@ RegionView3D *CTX_wm_region_view3d(const bContext *C) ScrArea *sa = CTX_wm_area(C); ARegion *ar = CTX_wm_region(C); - if (sa && sa->spacetype == SPACE_VIEW3D) - if (ar) + if (sa && sa->spacetype == SPACE_VIEW3D) { + if (ar) { return ar->regiondata; + } + } return NULL; } struct SpaceText *CTX_wm_space_text(const bContext *C) { ScrArea *sa = CTX_wm_area(C); - if (sa && sa->spacetype == SPACE_TEXT) + if (sa && sa->spacetype == SPACE_TEXT) { return sa->spacedata.first; + } return NULL; } struct SpaceConsole *CTX_wm_space_console(const bContext *C) { ScrArea *sa = CTX_wm_area(C); - if (sa && sa->spacetype == SPACE_CONSOLE) + if (sa && sa->spacetype == SPACE_CONSOLE) { return sa->spacedata.first; + } return NULL; } struct SpaceImage *CTX_wm_space_image(const bContext *C) { ScrArea *sa = CTX_wm_area(C); - if (sa && sa->spacetype == SPACE_IMAGE) + if (sa && sa->spacetype == SPACE_IMAGE) { return sa->spacedata.first; + } return NULL; } struct SpaceProperties *CTX_wm_space_properties(const bContext *C) { ScrArea *sa = CTX_wm_area(C); - if (sa && sa->spacetype == SPACE_PROPERTIES) + if (sa && sa->spacetype == SPACE_PROPERTIES) { return sa->spacedata.first; + } return NULL; } struct SpaceFile *CTX_wm_space_file(const bContext *C) { ScrArea *sa = CTX_wm_area(C); - if (sa && sa->spacetype == SPACE_FILE) + if (sa && sa->spacetype == SPACE_FILE) { return sa->spacedata.first; + } return NULL; } struct SpaceSeq *CTX_wm_space_seq(const bContext *C) { ScrArea *sa = CTX_wm_area(C); - if (sa && sa->spacetype == SPACE_SEQ) + if (sa && sa->spacetype == SPACE_SEQ) { return sa->spacedata.first; + } return NULL; } struct SpaceOutliner *CTX_wm_space_outliner(const bContext *C) { ScrArea *sa = CTX_wm_area(C); - if (sa && sa->spacetype == SPACE_OUTLINER) + if (sa && sa->spacetype == SPACE_OUTLINER) { return sa->spacedata.first; + } return NULL; } struct SpaceNla *CTX_wm_space_nla(const bContext *C) { ScrArea *sa = CTX_wm_area(C); - if (sa && sa->spacetype == SPACE_NLA) + if (sa && sa->spacetype == SPACE_NLA) { return sa->spacedata.first; + } return NULL; } struct SpaceNode *CTX_wm_space_node(const bContext *C) { ScrArea *sa = CTX_wm_area(C); - if (sa && sa->spacetype == SPACE_NODE) + if (sa && sa->spacetype == SPACE_NODE) { return sa->spacedata.first; + } return NULL; } struct SpaceGraph *CTX_wm_space_graph(const bContext *C) { ScrArea *sa = CTX_wm_area(C); - if (sa && sa->spacetype == SPACE_GRAPH) + if (sa && sa->spacetype == SPACE_GRAPH) { return sa->spacedata.first; + } return NULL; } struct SpaceAction *CTX_wm_space_action(const bContext *C) { ScrArea *sa = CTX_wm_area(C); - if (sa && sa->spacetype == SPACE_ACTION) + if (sa && sa->spacetype == SPACE_ACTION) { return sa->spacedata.first; + } return NULL; } struct SpaceInfo *CTX_wm_space_info(const bContext *C) { ScrArea *sa = CTX_wm_area(C); - if (sa && sa->spacetype == SPACE_INFO) + if (sa && sa->spacetype == SPACE_INFO) { return sa->spacedata.first; + } return NULL; } struct SpaceUserPref *CTX_wm_space_userpref(const bContext *C) { ScrArea *sa = CTX_wm_area(C); - if (sa && sa->spacetype == SPACE_USERPREF) + if (sa && sa->spacetype == SPACE_USERPREF) { return sa->spacedata.first; + } return NULL; } struct SpaceClip *CTX_wm_space_clip(const bContext *C) { ScrArea *sa = CTX_wm_area(C); - if (sa && sa->spacetype == SPACE_CLIP) + if (sa && sa->spacetype == SPACE_CLIP) { return sa->spacedata.first; + } return NULL; } struct SpaceTopBar *CTX_wm_space_topbar(const bContext *C) { ScrArea *sa = CTX_wm_area(C); - if (sa && sa->spacetype == SPACE_TOPBAR) + if (sa && sa->spacetype == SPACE_TOPBAR) { return sa->spacedata.first; + } return NULL; } @@ -895,10 +931,12 @@ Main *CTX_data_main(const bContext *C) { Main *bmain; - if (ctx_data_pointer_verify(C, "blend_data", (void *)&bmain)) + if (ctx_data_pointer_verify(C, "blend_data", (void *)&bmain)) { return bmain; - else + } + else { return C->data.main; + } } void CTX_data_main_set(bContext *C, Main *bmain) @@ -911,10 +949,12 @@ Scene *CTX_data_scene(const bContext *C) { Scene *scene; - if (ctx_data_pointer_verify(C, "scene", (void *)&scene)) + if (ctx_data_pointer_verify(C, "scene", (void *)&scene)) { return scene; - else + } + else { return C->data.scene; + } } ViewLayer *CTX_data_view_layer(const bContext *C) @@ -1008,26 +1048,36 @@ enum eContextObjectMode CTX_data_mode_enum_ex(const Object *obedit, else { // Object *ob = CTX_data_active_object(C); if (ob) { - if (object_mode & OB_MODE_POSE) + if (object_mode & OB_MODE_POSE) { return CTX_MODE_POSE; - else if (object_mode & OB_MODE_SCULPT) + } + else if (object_mode & OB_MODE_SCULPT) { return CTX_MODE_SCULPT; - else if (object_mode & OB_MODE_WEIGHT_PAINT) + } + else if (object_mode & OB_MODE_WEIGHT_PAINT) { return CTX_MODE_PAINT_WEIGHT; - else if (object_mode & OB_MODE_VERTEX_PAINT) + } + else if (object_mode & OB_MODE_VERTEX_PAINT) { return CTX_MODE_PAINT_VERTEX; - else if (object_mode & OB_MODE_TEXTURE_PAINT) + } + else if (object_mode & OB_MODE_TEXTURE_PAINT) { return CTX_MODE_PAINT_TEXTURE; - else if (object_mode & OB_MODE_PARTICLE_EDIT) + } + else if (object_mode & OB_MODE_PARTICLE_EDIT) { return CTX_MODE_PARTICLE; - else if (object_mode & OB_MODE_PAINT_GPENCIL) + } + else if (object_mode & OB_MODE_PAINT_GPENCIL) { return CTX_MODE_PAINT_GPENCIL; - else if (object_mode & OB_MODE_EDIT_GPENCIL) + } + else if (object_mode & OB_MODE_EDIT_GPENCIL) { return CTX_MODE_EDIT_GPENCIL; - else if (object_mode & OB_MODE_SCULPT_GPENCIL) + } + else if (object_mode & OB_MODE_SCULPT_GPENCIL) { return CTX_MODE_SCULPT_GPENCIL; - else if (object_mode & OB_MODE_WEIGHT_GPENCIL) + } + else if (object_mode & OB_MODE_WEIGHT_GPENCIL) { return CTX_MODE_WEIGHT_GPENCIL; + } } } @@ -1080,10 +1130,12 @@ ToolSettings *CTX_data_tool_settings(const bContext *C) { Scene *scene = CTX_data_scene(C); - if (scene) + if (scene) { return scene->toolsettings; - else + } + else { return NULL; + } } int CTX_data_selected_nodes(const bContext *C, ListBase *list) diff --git a/source/blender/blenkernel/intern/crazyspace.c b/source/blender/blenkernel/intern/crazyspace.c index 465a9980579..3b46f491f11 100644 --- a/source/blender/blenkernel/intern/crazyspace.c +++ b/source/blender/blenkernel/intern/crazyspace.c @@ -86,12 +86,14 @@ static int modifiers_disable_subsurf_temporary(Object *ob) ModifierData *md; int disabled = 0; - for (md = ob->modifiers.first; md; md = md->next) - if (md->type == eModifierType_Subsurf) + for (md = ob->modifiers.first; md; md = md->next) { + if (md->type == eModifierType_Subsurf) { if (md->mode & eModifierMode_OnCage) { md->mode ^= eModifierMode_DisableTemporary; disabled = 1; } + } + } return disabled; } @@ -199,8 +201,9 @@ void BKE_crazyspace_set_quats_mesh(Mesh *me, MPoly *mp; mvert = me->mvert; - for (i = 0; i < me->totvert; i++, mvert++) + for (i = 0; i < me->totvert; i++, mvert++) { mvert->flag &= ~ME_VERT_TMP_TAG; + } /* first store two sets of tangent vectors in vertices, we derive it just from the face-edges */ mvert = me->mvert; @@ -277,8 +280,9 @@ int BKE_crazyspace_get_first_deform_matrices_editbmesh(struct Depsgraph *depsgra for (i = 0; md && i <= cageIndex; i++, md = md->next) { const ModifierTypeInfo *mti = modifierType_getInfo(md->type); - if (!editbmesh_modifier_is_enabled(scene, md, me != NULL)) + if (!editbmesh_modifier_is_enabled(scene, md, me != NULL)) { continue; + } if (mti->type == eModifierTypeType_OnlyDeform && mti->deformMatricesEM) { if (!defmats) { @@ -293,18 +297,23 @@ int BKE_crazyspace_get_first_deform_matrices_editbmesh(struct Depsgraph *depsgra deformedVerts = editbmesh_get_vertex_cos(em, &numVerts); defmats = MEM_mallocN(sizeof(*defmats) * numVerts, "defmats"); - for (a = 0; a < numVerts; a++) + for (a = 0; a < numVerts; a++) { unit_m3(defmats[a]); + } } mti->deformMatricesEM(md, &mectx, em, me, deformedVerts, defmats, numVerts); } - else + else { break; + } } - for (; md && i <= cageIndex; md = md->next, i++) - if (editbmesh_modifier_is_enabled(scene, md, me != NULL) && modifier_isCorrectableDeformed(md)) + for (; md && i <= cageIndex; md = md->next, i++) { + if (editbmesh_modifier_is_enabled(scene, md, me != NULL) && + modifier_isCorrectableDeformed(md)) { numleft++; + } + } if (me) { BKE_id_free(NULL, me); @@ -365,8 +374,9 @@ int BKE_sculpt_get_first_deform_matrices(struct Depsgraph *depsgraph, for (; md; md = md->next) { const ModifierTypeInfo *mti = modifierType_getInfo(md->type); - if (!modifier_isEnabled(scene, md, eModifierMode_Realtime)) + if (!modifier_isEnabled(scene, md, eModifierMode_Realtime)) { continue; + } if (mti->type == eModifierTypeType_OnlyDeform) { if (!defmats) { @@ -377,26 +387,30 @@ int BKE_sculpt_get_first_deform_matrices(struct Depsgraph *depsgraph, deformedVerts = BKE_mesh_vertexCos_get(me, &numVerts); defmats = MEM_callocN(sizeof(*defmats) * numVerts, "defmats"); - for (a = 0; a < numVerts; a++) + for (a = 0; a < numVerts; a++) { unit_m3(defmats[a]); + } } if (mti->deformMatrices) { mti->deformMatrices(md, &mectx, me_eval, deformedVerts, defmats, numVerts); } - else + else { break; + } } } for (; md; md = md->next) { const ModifierTypeInfo *mti = modifierType_getInfo(md->type); - if (!modifier_isEnabled(scene, md, eModifierMode_Realtime)) + if (!modifier_isEnabled(scene, md, eModifierMode_Realtime)) { continue; + } - if (mti->type == eModifierTypeType_OnlyDeform) + if (mti->type == eModifierTypeType_OnlyDeform) { numleft++; + } } if (me_eval) { @@ -436,14 +450,16 @@ void BKE_crazyspace_build_sculpt(struct Depsgraph *depsgraph, for (; md; md = md->next) { const ModifierTypeInfo *mti = modifierType_getInfo(md->type); - if (!modifier_isEnabled(scene, md, eModifierMode_Realtime)) + if (!modifier_isEnabled(scene, md, eModifierMode_Realtime)) { continue; + } if (mti->type == eModifierTypeType_OnlyDeform) { /* skip leading modifiers which have been already * handled in sculpt_get_first_deform_matrices */ - if (mti->deformMatrices && !deformed) + if (mti->deformMatrices && !deformed) { continue; + } mti->deformVerts(md, &mectx, NULL, deformedVerts, mesh->totvert); deformed = 1; @@ -473,7 +489,8 @@ void BKE_crazyspace_build_sculpt(struct Depsgraph *depsgraph, *deformcos = BKE_mesh_vertexCos_get(mesh, &numVerts); *deformmats = MEM_callocN(sizeof(*(*deformmats)) * numVerts, "defmats"); - for (a = 0; a < numVerts; a++) + for (a = 0; a < numVerts; a++) { unit_m3((*deformmats)[a]); + } } } diff --git a/source/blender/blenkernel/intern/curve.c b/source/blender/blenkernel/intern/curve.c index f28e14be512..dc677449a4c 100644 --- a/source/blender/blenkernel/intern/curve.c +++ b/source/blender/blenkernel/intern/curve.c @@ -78,12 +78,15 @@ void BKE_curve_editfont_free(Curve *cu) if (cu->editfont) { EditFont *ef = cu->editfont; - if (ef->textbuf) + if (ef->textbuf) { MEM_freeN(ef->textbuf); - if (ef->textbufinfo) + } + if (ef->textbufinfo) { MEM_freeN(ef->textbufinfo); - if (ef->selboxes) + } + if (ef->selboxes) { MEM_freeN(ef->selboxes); + } MEM_freeN(ef); cu->editfont = NULL; @@ -193,8 +196,10 @@ Curve *BKE_curve_add(Main *bmain, const char *name, int type) } /** - * Only copy internal data of Curve ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of Curve ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * @@ -281,8 +286,9 @@ void BKE_curve_curve_dimension_update(Curve *cu) BKE_nurb_test_2d(nu); /* since the handles are moved they need to be auto-located again */ - if (nu->type == CU_BEZIER) + if (nu->type == CU_BEZIER) { BKE_nurb_handles_calc(nu); + } } } } @@ -291,8 +297,9 @@ void BKE_curve_type_test(Object *ob) { ob->type = BKE_curve_type_get(ob->data); - if (ob->type == OB_CURVE) + if (ob->type == OB_CURVE) { BKE_curve_curve_dimension_update((Curve *)ob->data); + } } void BKE_curve_boundbox_calc(Curve *cu, float r_loc[3], float r_size[3]) @@ -301,14 +308,17 @@ void BKE_curve_boundbox_calc(Curve *cu, float r_loc[3], float r_size[3]) float min[3], max[3]; float mloc[3], msize[3]; - if (cu->bb == NULL) + if (cu->bb == NULL) { cu->bb = MEM_callocN(sizeof(BoundBox), "boundbox"); + } bb = cu->bb; - if (!r_loc) + if (!r_loc) { r_loc = mloc; - if (!r_size) + } + if (!r_size) { r_size = msize; + } INIT_MINMAX(min, max); if (!BKE_curve_minmax(cu, true, min, max)) { @@ -329,7 +339,8 @@ void BKE_curve_boundbox_calc(Curve *cu, float r_loc[3], float r_size[3]) BoundBox *BKE_curve_boundbox_get(Object *ob) { - /* This is Object-level data access, DO NOT touch to Mesh's bb, would be totally thread-unsafe. */ + /* This is Object-level data access, + * DO NOT touch to Mesh's bb, would be totally thread-unsafe. */ if (ob->runtime.bb == NULL || ob->runtime.bb->flag & BOUNDBOX_DIRTY) { Curve *cu = ob->data; float min[3], max[3]; @@ -356,12 +367,15 @@ void BKE_curve_texspace_calc(Curve *cu) if (cu->texflag & CU_AUTOSPACE) { for (a = 0; a < 3; a++) { - if (size[a] == 0.0f) + if (size[a] == 0.0f) { size[a] = 1.0f; - else if (size[a] > 0.0f && size[a] < 0.00001f) + } + else if (size[a] > 0.0f && size[a] < 0.00001f) { size[a] = 0.00001f; - else if (size[a] < 0.0f && size[a] > -0.00001f) + } + else if (size[a] < 0.0f && size[a] > -0.00001f) { size[a] = -0.00001f; + } } copy_v3_v3(cu->loc, loc); @@ -376,12 +390,15 @@ BoundBox *BKE_curve_texspace_get(Curve *cu, float r_loc[3], float r_rot[3], floa BKE_curve_texspace_calc(cu); } - if (r_loc) + if (r_loc) { copy_v3_v3(r_loc, cu->loc); - if (r_rot) + } + if (r_rot) { copy_v3_v3(r_rot, cu->rot); - if (r_size) + } + if (r_size) { copy_v3_v3(r_size, cu->size); + } return cu->bb; } @@ -420,10 +437,12 @@ int BKE_nurbList_verts_count(ListBase *nurb) nu = nurb->first; while (nu) { - if (nu->bezt) + if (nu->bezt) { tot += 3 * nu->pntsu; - else if (nu->bp) + } + else if (nu->bp) { tot += nu->pntsu * nu->pntsv; + } nu = nu->next; } @@ -437,10 +456,12 @@ int BKE_nurbList_verts_count_without_handles(ListBase *nurb) nu = nurb->first; while (nu) { - if (nu->bezt) + if (nu->bezt) { tot += nu->pntsu; - else if (nu->bp) + } + else if (nu->bp) { tot += nu->pntsu * nu->pntsv; + } nu = nu->next; } @@ -452,20 +473,25 @@ int BKE_nurbList_verts_count_without_handles(ListBase *nurb) void BKE_nurb_free(Nurb *nu) { - if (nu == NULL) + if (nu == NULL) { return; + } - if (nu->bezt) + if (nu->bezt) { MEM_freeN(nu->bezt); + } nu->bezt = NULL; - if (nu->bp) + if (nu->bp) { MEM_freeN(nu->bp); + } nu->bp = NULL; - if (nu->knotsu) + if (nu->knotsu) { MEM_freeN(nu->knotsu); + } nu->knotsu = NULL; - if (nu->knotsv) + if (nu->knotsv) { MEM_freeN(nu->knotsv); + } nu->knotsv = NULL; /* if (nu->trim.first) freeNurblist(&(nu->trim)); */ @@ -476,8 +502,9 @@ void BKE_nurbList_free(ListBase *lb) { Nurb *nu, *next; - if (lb == NULL) + if (lb == NULL) { return; + } nu = lb->first; while (nu) { @@ -494,8 +521,9 @@ Nurb *BKE_nurb_duplicate(const Nurb *nu) int len; newnu = (Nurb *)MEM_mallocN(sizeof(Nurb), "duplicateNurb"); - if (newnu == NULL) + if (newnu == NULL) { return NULL; + } memcpy(newnu, nu, sizeof(Nurb)); if (nu->bezt) { @@ -533,8 +561,9 @@ Nurb *BKE_nurb_copy(Nurb *src, int pntsu, int pntsv) Nurb *newnu = (Nurb *)MEM_mallocN(sizeof(Nurb), "copyNurb"); memcpy(newnu, src, sizeof(Nurb)); - if (pntsu == 1) + if (pntsu == 1) { SWAP(int, pntsu, pntsv); + } newnu->pntsu = pntsu; newnu->pntsv = pntsv; @@ -573,8 +602,9 @@ void BKE_nurb_test_2d(Nurb *nu) BPoint *bp; int a; - if ((nu->flag & CU_2D) == 0) + if ((nu->flag & CU_2D) == 0) { return; + } if (nu->type == CU_BEZIER) { a = nu->pntsu; @@ -1016,8 +1046,9 @@ static void calcknots(float *knots, const int pnts, const short order, const sho k = 0.0; for (a = 1; a <= pnts_order; a++) { knots[a - 1] = k; - if (a >= order && a <= pnts) + if (a >= order && a <= pnts) { k += 1.0f; + } } break; case CU_NURB_BEZIER: @@ -1033,8 +1064,9 @@ static void calcknots(float *knots, const int pnts, const short order, const sho else if (order == 3) { k = 0.6f; for (a = 0; a < pnts_order; a++) { - if (a >= order && a <= pnts) + if (a >= order && a <= pnts) { k += 0.5f; + } knots[a] = floorf(k); } } @@ -1055,8 +1087,9 @@ static void makecyclicknots(float *knots, int pnts, short order) { int a, b, order2, c; - if (knots == NULL) + if (knots == NULL) { return; + } order2 = order - 1; @@ -1064,11 +1097,13 @@ static void makecyclicknots(float *knots, int pnts, short order) if (order > 2) { b = pnts + order2; for (a = 1; a < order2; a++) { - if (knots[b] != knots[b - a]) + if (knots[b] != knots[b - a]) { break; + } } - if (a == order2) + if (a == order2) { knots[pnts + order - 2] += 1.0f; + } } b = order; @@ -1083,8 +1118,9 @@ static void makeknots(Nurb *nu, short uv) { if (nu->type == CU_NURBS) { if (uv == 1) { - if (nu->knotsu) + if (nu->knotsu) { MEM_freeN(nu->knotsu); + } if (BKE_nurb_check_valid_u(nu)) { nu->knotsu = MEM_calloc_arrayN(KNOTSU(nu) + 1, sizeof(float), "makeknots"); if (nu->flagu & CU_NURB_CYCLIC) { @@ -1095,12 +1131,14 @@ static void makeknots(Nurb *nu, short uv) calcknots(nu->knotsu, nu->pntsu, nu->orderu, nu->flagu); } } - else + else { nu->knotsu = NULL; + } } else if (uv == 2) { - if (nu->knotsv) + if (nu->knotsv) { MEM_freeN(nu->knotsv); + } if (BKE_nurb_check_valid_v(nu)) { nu->knotsv = MEM_calloc_arrayN(KNOTSV(nu) + 1, sizeof(float), "makeknots"); if (nu->flagv & CU_NURB_CYCLIC) { @@ -1138,10 +1176,12 @@ static void basisNurb( opp2 = orderpluspnts - 1; /* this is for float inaccuracy */ - if (t < knots[0]) + if (t < knots[0]) { t = knots[0]; - else if (t > knots[opp2]) + } + else if (t > knots[opp2]) { t = knots[opp2]; + } /* this part is order '1' */ o2 = order + 1; @@ -1149,8 +1189,9 @@ static void basisNurb( if (knots[i] != knots[i + 1] && t >= knots[i] && t <= knots[i + 1]) { basis[i] = 1.0; i1 = i - o2; - if (i1 < 0) + if (i1 < 0) { i1 = 0; + } i2 = i; i++; while (i < opp2) { @@ -1159,27 +1200,33 @@ static void basisNurb( } break; } - else + else { basis[i] = 0.0; + } } basis[i] = 0.0; /* this is order 2, 3, ... */ for (j = 2; j <= order; j++) { - if (i2 + j >= orderpluspnts) + if (i2 + j >= orderpluspnts) { i2 = opp2 - j; + } for (i = i1; i <= i2; i++) { - if (basis[i] != 0.0f) + if (basis[i] != 0.0f) { d = ((t - knots[i]) * basis[i]) / (knots[i + j - 1] - knots[i]); - else + } + else { d = 0.0f; + } - if (basis[i + 1] != 0.0f) + if (basis[i + 1] != 0.0f) { e = ((knots[i + j] - t) * basis[i + 1]) / (knots[i + j] - knots[i + 1]); - else + } + else { e = 0.0; + } basis[i] = d + e; } @@ -1191,8 +1238,9 @@ static void basisNurb( for (i = i1; i <= i2; i++) { if (basis[i] > 0.0f) { *end = i; - if (*start == 1000) + if (*start == 1000) { *start = i; + } } } } @@ -1210,19 +1258,24 @@ void BKE_nurb_makeFaces(const Nurb *nu, float *coord_array, int rowstride, int r int totu = nu->pntsu * resolu, totv = nu->pntsv * resolv; - if (nu->knotsu == NULL || nu->knotsv == NULL) + if (nu->knotsu == NULL || nu->knotsv == NULL) { return; - if (nu->orderu > nu->pntsu) + } + if (nu->orderu > nu->pntsu) { return; - if (nu->orderv > nu->pntsv) + } + if (nu->orderv > nu->pntsv) { return; - if (coord_array == NULL) + } + if (coord_array == NULL) { return; + } /* allocate and initialize */ len = totu * totv; - if (len == 0) + if (len == 0) { return; + } sum = (float *)MEM_calloc_arrayN(len, sizeof(float), "makeNurbfaces1"); @@ -1239,10 +1292,12 @@ void BKE_nurb_makeFaces(const Nurb *nu, float *coord_array, int rowstride, int r fp = nu->knotsu; ustart = fp[nu->orderu - 1]; - if (nu->flagu & CU_NURB_CYCLIC) + if (nu->flagu & CU_NURB_CYCLIC) { uend = fp[nu->pntsu + nu->orderu - 1]; - else + } + else { uend = fp[nu->pntsu]; + } ustep = (uend - ustart) / ((nu->flagu & CU_NURB_CYCLIC) ? totu : totu - 1); basisu = (float *)MEM_malloc_arrayN(KNOTSU(nu), sizeof(float), "makeNurbfaces3"); @@ -1250,10 +1305,12 @@ void BKE_nurb_makeFaces(const Nurb *nu, float *coord_array, int rowstride, int r fp = nu->knotsv; vstart = fp[nu->orderv - 1]; - if (nu->flagv & CU_NURB_CYCLIC) + if (nu->flagv & CU_NURB_CYCLIC) { vend = fp[nu->pntsv + nu->orderv - 1]; - else + } + else { vend = fp[nu->pntsv]; + } vstep = (vend - vstart) / ((nu->flagv & CU_NURB_CYCLIC) ? totv : totv - 1); len = KNOTSV(nu); @@ -1262,10 +1319,12 @@ void BKE_nurb_makeFaces(const Nurb *nu, float *coord_array, int rowstride, int r jend = (int *)MEM_malloc_arrayN(totv, sizeof(float), "makeNurbfaces5"); /* precalculation of basisv and jstart, jend */ - if (nu->flagv & CU_NURB_CYCLIC) + if (nu->flagv & CU_NURB_CYCLIC) { cycl = nu->orderv - 1; - else + } + else { cycl = 0; + } v = vstart; basis = basisv; curv = totv; @@ -1275,10 +1334,12 @@ void BKE_nurb_makeFaces(const Nurb *nu, float *coord_array, int rowstride, int r v += vstep; } - if (nu->flagu & CU_NURB_CYCLIC) + if (nu->flagu & CU_NURB_CYCLIC) { cycl = nu->orderu - 1; - else + } + else { cycl = 0; + } in = coord_array; u = ustart; curu = totu; @@ -1297,10 +1358,12 @@ void BKE_nurb_makeFaces(const Nurb *nu, float *coord_array, int rowstride, int r for (j = jsta; j <= jen; j++) { - if (j >= nu->pntsv) + if (j >= nu->pntsv) { jofs = (j - nu->pntsv); - else + } + else { jofs = j; + } bp = nu->bp + nu->pntsu * jofs + istart - 1; for (i = istart; i <= iend; i++, fp++) { @@ -1308,15 +1371,17 @@ void BKE_nurb_makeFaces(const Nurb *nu, float *coord_array, int rowstride, int r iofs = i - nu->pntsu; bp = nu->bp + nu->pntsu * jofs + iofs; } - else + else { bp++; + } if (ratcomp) { *fp = basisu[i] * basis[j] * bp->vec[3]; sumdiv += *fp; } - else + else { *fp = basisu[i] * basis[j]; + } } } @@ -1335,10 +1400,12 @@ void BKE_nurb_makeFaces(const Nurb *nu, float *coord_array, int rowstride, int r fp = sum; for (j = jsta; j <= jen; j++) { - if (j >= nu->pntsv) + if (j >= nu->pntsv) { jofs = (j - nu->pntsv); - else + } + else { jofs = j; + } bp = nu->bp + nu->pntsu * jofs + istart - 1; for (i = istart; i <= iend; i++, fp++) { @@ -1346,8 +1413,9 @@ void BKE_nurb_makeFaces(const Nurb *nu, float *coord_array, int rowstride, int r iofs = i - nu->pntsu; bp = nu->bp + nu->pntsu * jofs + iofs; } - else + else { bp++; + } if (*fp != 0.0f) { madd_v3_v3fl(in, bp->vec, *fp); @@ -1393,17 +1461,21 @@ void BKE_nurb_makeCurve(const Nurb *nu, *weight_fp = weight_array; int i, len, istart, iend, cycl; - if (nu->knotsu == NULL) + if (nu->knotsu == NULL) { return; - if (nu->orderu > nu->pntsu) + } + if (nu->orderu > nu->pntsu) { return; - if (coord_array == NULL) + } + if (coord_array == NULL) { return; + } /* allocate and initialize */ len = nu->pntsu; - if (len == 0) + if (len == 0) { return; + } sum = (float *)MEM_calloc_arrayN(len, sizeof(float), "makeNurbcurve1"); resolu = (resolu * SEGMENTSU(nu)); @@ -1415,18 +1487,22 @@ void BKE_nurb_makeCurve(const Nurb *nu, fp = nu->knotsu; ustart = fp[nu->orderu - 1]; - if (nu->flagu & CU_NURB_CYCLIC) + if (nu->flagu & CU_NURB_CYCLIC) { uend = fp[nu->pntsu + nu->orderu - 1]; - else + } + else { uend = fp[nu->pntsu]; + } ustep = (uend - ustart) / (resolu - ((nu->flagu & CU_NURB_CYCLIC) ? 0 : 1)); basisu = (float *)MEM_malloc_arrayN(KNOTSU(nu), sizeof(float), "makeNurbcurve3"); - if (nu->flagu & CU_NURB_CYCLIC) + if (nu->flagu & CU_NURB_CYCLIC) { cycl = nu->orderu - 1; - else + } + else { cycl = 0; + } u = ustart; while (resolu--) { @@ -1437,10 +1513,12 @@ void BKE_nurb_makeCurve(const Nurb *nu, fp = sum; bp = nu->bp + istart - 1; for (i = istart; i <= iend; i++, fp++) { - if (i >= nu->pntsu) + if (i >= nu->pntsu) { bp = nu->bp + (i - nu->pntsu); - else + } + else { bp++; + } *fp = basisu[i] * bp->vec[3]; sumdiv += *fp; @@ -1459,33 +1537,41 @@ void BKE_nurb_makeCurve(const Nurb *nu, fp = sum; bp = nu->bp + istart - 1; for (i = istart; i <= iend; i++, fp++) { - if (i >= nu->pntsu) + if (i >= nu->pntsu) { bp = nu->bp + (i - nu->pntsu); - else + } + else { bp++; + } if (*fp != 0.0f) { madd_v3_v3fl(coord_fp, bp->vec, *fp); - if (tilt_fp) + if (tilt_fp) { (*tilt_fp) += (*fp) * bp->tilt; + } - if (radius_fp) + if (radius_fp) { (*radius_fp) += (*fp) * bp->radius; + } - if (weight_fp) + if (weight_fp) { (*weight_fp) += (*fp) * bp->weight; + } } } coord_fp = POINTER_OFFSET(coord_fp, stride); - if (tilt_fp) + if (tilt_fp) { tilt_fp = POINTER_OFFSET(tilt_fp, stride); - if (radius_fp) + } + if (radius_fp) { radius_fp = POINTER_OFFSET(radius_fp, stride); - if (weight_fp) + } + if (weight_fp) { weight_fp = POINTER_OFFSET(weight_fp, stride); + } u += ustep; } @@ -1681,12 +1767,15 @@ float *BKE_curve_surf_make_orco(Object *ob) sizeu = nu->pntsu * resolu; sizev = nu->pntsv * resolv; - if (nu->flagu & CU_NURB_CYCLIC) + if (nu->flagu & CU_NURB_CYCLIC) { sizeu++; - if (nu->flagv & CU_NURB_CYCLIC) + } + if (nu->flagv & CU_NURB_CYCLIC) { sizev++; - if (nu->pntsv > 1) + } + if (nu->pntsv > 1) { tot += sizeu * sizev; + } nu = nu->next; } @@ -1702,24 +1791,30 @@ float *BKE_curve_surf_make_orco(Object *ob) sizeu = nu->pntsu * resolu; sizev = nu->pntsv * resolv; - if (nu->flagu & CU_NURB_CYCLIC) + if (nu->flagu & CU_NURB_CYCLIC) { sizeu++; - if (nu->flagv & CU_NURB_CYCLIC) + } + if (nu->flagv & CU_NURB_CYCLIC) { sizev++; + } if (cu->flag & CU_UV_ORCO) { for (b = 0; b < sizeu; b++) { for (a = 0; a < sizev; a++) { - if (sizev < 2) + if (sizev < 2) { fp[0] = 0.0f; - else + } + else { fp[0] = -1.0f + 2.0f * ((float)a) / (sizev - 1); + } - if (sizeu < 2) + if (sizeu < 2) { fp[1] = 0.0f; - else + } + else { fp[1] = -1.0f + 2.0f * ((float)b) / (sizeu - 1); + } fp[2] = 0.0; @@ -1736,13 +1831,15 @@ float *BKE_curve_surf_make_orco(Object *ob) for (b = 0; b < sizeu; b++) { int use_b = b; - if (b == sizeu - 1 && (nu->flagu & CU_NURB_CYCLIC)) + if (b == sizeu - 1 && (nu->flagu & CU_NURB_CYCLIC)) { use_b = false; + } for (a = 0; a < sizev; a++) { int use_a = a; - if (a == sizev - 1 && (nu->flagv & CU_NURB_CYCLIC)) + if (a == sizev - 1 && (nu->flagv & CU_NURB_CYCLIC)) { use_a = false; + } tdata = _tdata + 3 * (use_b * (nu->pntsv * resolv) + use_a); @@ -1785,21 +1882,25 @@ float *BKE_curve_make_orco(Depsgraph *depsgraph, Scene *scene, Object *ob, int * * (closed circle beveling) */ if (dl->flag & DL_CYCL_U) { - if (dl->flag & DL_CYCL_V) + if (dl->flag & DL_CYCL_V) { numVerts += (dl->parts + 1) * (dl->nr + 1); - else + } + else { numVerts += dl->parts * (dl->nr + 1); + } } else if (dl->flag & DL_CYCL_V) { numVerts += (dl->parts + 1) * dl->nr; } - else + else { numVerts += dl->parts * dl->nr; + } } } - if (r_numVerts) + if (r_numVerts) { *r_numVerts = numVerts; + } fp = coord_array = MEM_malloc_arrayN(numVerts, 3 * sizeof(float), "cu_orco"); for (dl = disp.first; dl; dl = dl->next) { @@ -1825,8 +1926,9 @@ float *BKE_curve_make_orco(Depsgraph *depsgraph, Scene *scene, Object *ob, int * /* exception as handled in convertblender.c too */ if (dl->flag & DL_CYCL_U) { sizeu++; - if (dl->flag & DL_CYCL_V) + if (dl->flag & DL_CYCL_V) { sizev++; + } } else if (dl->flag & DL_CYCL_V) { sizev++; @@ -1883,8 +1985,9 @@ void BKE_curve_bevel_make(Depsgraph *depsgraph, // XXX if ( ob == obedit && ob->type == OB_FONT ) return; if (cu->bevobj) { - if (cu->bevobj->type != OB_CURVE) + if (cu->bevobj->type != OB_CURVE) { return; + } bevcu = cu->bevobj->data; if (bevcu->ext1 == 0.0f && bevcu->ext2 == 0.0f) { @@ -1927,8 +2030,9 @@ void BKE_curve_bevel_make(Depsgraph *depsgraph, dl->parts * dl->nr, 3 * sizeof(float), "makebevelcurve1"); memcpy(dlnew->verts, dl->verts, 3 * sizeof(float) * dl->parts * dl->nr); - if (dlnew->type == DL_SEGM) + if (dlnew->type == DL_SEGM) { dlnew->flag |= (DL_FRONT_CURVE | DL_BACK_CURVE); + } BLI_addtail(disp, dlnew); fp = dlnew->verts; @@ -2101,8 +2205,9 @@ static int cu_isectLL(const float v1[3], float deler; deler = (v1[cox] - v2[cox]) * (v3[coy] - v4[coy]) - (v3[cox] - v4[cox]) * (v1[coy] - v2[coy]); - if (deler == 0.0f) + if (deler == 0.0f) { return -1; + } *lambda = (v1[coy] - v3[coy]) * (v3[cox] - v4[cox]) - (v1[cox] - v3[cox]) * (v3[coy] - v4[coy]); *lambda = -(*lambda / deler); @@ -2119,8 +2224,9 @@ static int cu_isectLL(const float v1[3], vec[coy] = *lambda * (v2[coy] - v1[coy]) + v1[coy]; if (*lambda >= 0.0f && *lambda <= 1.0f && *mu >= 0.0f && *mu <= 1.0f) { - if (*lambda == 0.0f || *lambda == 1.0f || *mu == 0.0f || *mu == 1.0f) + if (*lambda == 0.0f || *lambda == 1.0f || *mu == 0.0f || *mu == 1.0f) { return 1; + } return 2; } return 0; @@ -2165,10 +2271,12 @@ static bool bevelinside(BevList *bl1, BevList *bl2) * only allow for one situation: we choose lab= 1.0 */ if (mode >= 0 && lab != 0.0f) { - if (vec[0] < hvec1[0]) + if (vec[0] < hvec1[0]) { links++; - else + } + else { rechts++; + } } } } @@ -2189,10 +2297,12 @@ static int vergxcobev(const void *a1, const void *a2) { const struct BevelSort *x1 = a1, *x2 = a2; - if (x1->left > x2->left) + if (x1->left > x2->left) { return 1; - else if (x1->left < x2->left) + } + else if (x1->left < x2->left) { return -1; + } return 0; } @@ -2205,10 +2315,12 @@ static void calc_bevel_sin_cos( t01 = sqrtf(x1 * x1 + y1 * y1); t02 = sqrtf(x2 * x2 + y2 * y2); - if (t01 == 0.0f) + if (t01 == 0.0f) { t01 = 1.0f; - if (t02 == 0.0f) + } + if (t02 == 0.0f) { t02 = 1.0f; + } x1 /= t01; y1 /= t01; @@ -2216,14 +2328,17 @@ static void calc_bevel_sin_cos( y2 /= t02; t02 = x1 * x2 + y1 * y2; - if (fabsf(t02) >= 1.0f) + if (fabsf(t02) >= 1.0f) { t02 = M_PI_2; - else + } + else { t02 = (saacos(t02)) / 2.0f; + } t02 = sinf(t02); - if (t02 == 0.0f) + if (t02 == 0.0f) { t02 = 1.0f; + } x3 = x1 - x2; y3 = y1 - y2; @@ -2254,30 +2369,37 @@ static void tilt_bezpart(BezTriple *prevbezt, float fac, dfac, t[4]; int a; - if (tilt_array == NULL && radius_array == NULL) + if (tilt_array == NULL && radius_array == NULL) { return; + } last = nu->bezt + (nu->pntsu - 1); /* returns a point */ if (prevbezt == nu->bezt) { - if (nu->flagu & CU_NURB_CYCLIC) + if (nu->flagu & CU_NURB_CYCLIC) { pprev = last; - else + } + else { pprev = prevbezt; + } } - else + else { pprev = prevbezt - 1; + } /* next point */ if (bezt == last) { - if (nu->flagu & CU_NURB_CYCLIC) + if (nu->flagu & CU_NURB_CYCLIC) { next = nu->bezt; - else + } + else { next = bezt; + } } - else + else { next = bezt + 1; + } fac = 0.0; dfac = 1.0f / (float)resolu; @@ -2381,8 +2503,9 @@ static void bevel_list_flip_tangents(BevList *bl) nr = bl->nr; while (nr--) { - if (angle_normalized_v3v3(bevp0->tan, bevp1->tan) > DEG2RADF(90.0f)) + if (angle_normalized_v3v3(bevp0->tan, bevp1->tan) > DEG2RADF(90.0f)) { negate_v3(bevp1->tan); + } bevp0 = bevp1; bevp1 = bevp2; @@ -2563,8 +2686,9 @@ static void make_bevel_list_3D_minimum_twist(BevList *bl) /* flip rotation if needs be */ cross_v3_v3v3(cross_tmp, vec_1, vec_2); normalize_v3(cross_tmp); - if (angle_normalized_v3v3(bevp_first->dir, cross_tmp) < DEG2RADF(90.0f)) + if (angle_normalized_v3v3(bevp_first->dir, cross_tmp) < DEG2RADF(90.0f)) { angle = -angle; + } bevp2 = bl->bevpoints; bevp1 = bevp2 + (bl->nr - 1); @@ -2663,8 +2787,9 @@ static void make_bevel_list_3D(BevList *bl, int smooth_iter, int twist_mode) break; } - if (smooth_iter) + if (smooth_iter) { bevel_list_smooth(bl, smooth_iter); + } bevel_list_apply_tilt(bl); } @@ -2840,8 +2965,11 @@ void BKE_curve_bevelList_make(Object *ob, ListBase *nurbs, bool for_render) bev = &ob->runtime.curve_cache->bev; +#if 0 /* do we need to calculate the radius for each point? */ - /* do_radius = (cu->bevobj || cu->taperobj || (cu->flag & CU_FRONT) || (cu->flag & CU_BACK)) ? 0 : 1; */ + do_radius = (cu->bevobj || cu->taperobj || (cu->flag & CU_FRONT) || (cu->flag & CU_BACK)) ? 0 : + 1; +#endif /* STEP 1: MAKE POLYS */ @@ -2852,9 +2980,9 @@ void BKE_curve_bevelList_make(Object *ob, ListBase *nurbs, bool for_render) } for (; nu; nu = nu->next) { - - if (nu->hide && is_editmode) + if (nu->hide && is_editmode) { continue; + } /* check if we will calculate tilt data */ do_tilt = CU_DO_TILT(cu, nu); @@ -2874,10 +3002,12 @@ void BKE_curve_bevelList_make(Object *ob, ListBase *nurbs, bool for_render) else { BevPoint *bevp; - if (for_render && cu->resolu_ren != 0) + if (for_render && cu->resolu_ren != 0) { resolu = cu->resolu_ren; - else + } + else { resolu = nu->resolu; + } segcount = SEGMENTSU(nu); @@ -2912,10 +3042,12 @@ void BKE_curve_bevelList_make(Object *ob, ListBase *nurbs, bool for_render) *seglen = len_v3v3(bevp->vec, bp->vec); bevp++; bevp->offset = *seglen; - if (*seglen > treshold) + if (*seglen > treshold) { *segbevcount = 1; - else + } + else { *segbevcount = 0; + } seglen++; segbevcount++; } @@ -2987,8 +3119,9 @@ void BKE_curve_bevelList_make(Object *ob, ListBase *nurbs, bool for_render) bevp->offset = *seglen; seglen++; /* match segbevcount to the cleaned up bevel lists (see STEP 2) */ - if (bevp->offset > treshold) + if (bevp->offset > treshold) { *segbevcount = 1; + } segbevcount++; } } @@ -3029,14 +3162,17 @@ void BKE_curve_bevelList_make(Object *ob, ListBase *nurbs, bool for_render) /* indicate with handlecodes double points */ if (prevbezt->h1 == prevbezt->h2) { - if (prevbezt->h1 == 0 || prevbezt->h1 == HD_VECT) + if (prevbezt->h1 == 0 || prevbezt->h1 == HD_VECT) { bevp->split_tag = true; + } } else { - if (prevbezt->h1 == 0 || prevbezt->h1 == HD_VECT) + if (prevbezt->h1 == 0 || prevbezt->h1 == HD_VECT) { bevp->split_tag = true; - else if (prevbezt->h2 == 0 || prevbezt->h2 == HD_VECT) + } + else if (prevbezt->h2 == 0 || prevbezt->h2 == HD_VECT) { bevp->split_tag = true; + } } /* seglen */ @@ -3249,23 +3385,29 @@ void BKE_curve_bevelList_make(Object *ob, ListBase *nurbs, bool for_render) sd->left = min; bevp = bl->bevpoints; - if (bevp1 == bevp) + if (bevp1 == bevp) { bevp0 = bevp + (bl->nr - 1); - else + } + else { bevp0 = bevp1 - 1; + } bevp = bevp + (bl->nr - 1); - if (bevp1 == bevp) + if (bevp1 == bevp) { bevp2 = bl->bevpoints; - else + } + else { bevp2 = bevp1 + 1; + } inp = ((bevp1->vec[0] - bevp0->vec[0]) * (bevp0->vec[1] - bevp2->vec[1]) + (bevp0->vec[1] - bevp1->vec[1]) * (bevp0->vec[0] - bevp2->vec[0])); - if (inp > 0.0f) + if (inp > 0.0f) { sd->dir = 1; - else + } + else { sd->dir = 0; + } sd++; } @@ -3404,10 +3546,12 @@ static void calchandleNurb_intern(BezTriple *bezt, len_b = len_v3(dvec_b); } - if (len_a == 0.0f) + if (len_a == 0.0f) { len_a = 1.0f; - if (len_b == 0.0f) + } + if (len_b == 0.0f) { len_b = 1.0f; + } len_ratio = len_a / len_b; @@ -3437,10 +3581,12 @@ static void calchandleNurb_intern(BezTriple *bezt, bool leftviolate = false, rightviolate = false; if (!is_fcurve || fcurve_smoothing == FCURVE_SMOOTH_NONE) { - if (len_a > 5.0f * len_b) + if (len_a > 5.0f * len_b) { len_a = 5.0f * len_b; - if (len_b > 5.0f * len_a) + } + if (len_b > 5.0f * len_a) { len_b = 5.0f * len_a; + } } if (ELEM(bezt->h1, HD_AUTO, HD_AUTO_ANIM)) { @@ -3534,10 +3680,12 @@ static void calchandleNurb_intern(BezTriple *bezt, len_a = len_v3v3(p2, p2_h1); len_b = len_v3v3(p2, p2_h2); - if (len_a == 0.0f) + if (len_a == 0.0f) { len_a = 1.0f; - if (len_b == 0.0f) + } + if (len_b == 0.0f) { len_b = 1.0f; + } len_ratio = len_a / len_b; @@ -3587,30 +3735,37 @@ static void calchandlesNurb_intern(Nurb *nu, bool skip_align) BezTriple *bezt, *prev, *next; int a; - if (nu->type != CU_BEZIER) + if (nu->type != CU_BEZIER) { return; - if (nu->pntsu < 2) + } + if (nu->pntsu < 2) { return; + } a = nu->pntsu; bezt = nu->bezt; - if (nu->flagu & CU_NURB_CYCLIC) + if (nu->flagu & CU_NURB_CYCLIC) { prev = bezt + (a - 1); - else + } + else { prev = NULL; + } next = bezt + 1; while (a--) { calchandleNurb_intern(bezt, prev, next, 0, skip_align, 0); prev = bezt; if (a == 1) { - if (nu->flagu & CU_NURB_CYCLIC) + if (nu->flagu & CU_NURB_CYCLIC) { next = nu->bezt; - else + } + else { next = NULL; + } } - else + else { next++; + } bezt++; } @@ -3638,8 +3793,9 @@ static void *allocate_arrays(int count, float ***floats, char ***chars, const ch void *buffer = (float *)MEM_malloc_arrayN(count, (sizeof(float) * num_floats + num_chars), name); - if (!buffer) + if (!buffer) { return NULL; + } float *fptr = buffer; @@ -3697,8 +3853,9 @@ static bool tridiagonal_solve_with_limits( char **flagarrays[] = {&is_locked, &num_unlocks, NULL}; void *tmps = allocate_arrays(solve_count, arrays, flagarrays, "tridiagonal_solve_with_limits"); - if (!tmps) + if (!tmps) { return false; + } memcpy(a0, a, sizeof(float) * solve_count); memcpy(b0, b, sizeof(float) * solve_count); @@ -3723,8 +3880,9 @@ static bool tridiagonal_solve_with_limits( do { for (int i = 0; i < solve_count; i++) { - if (h[i] >= hmin[i] && h[i] <= hmax[i]) + if (h[i] >= hmin[i] && h[i] <= hmax[i]) { continue; + } overshoot = true; @@ -3743,12 +3901,14 @@ static bool tridiagonal_solve_with_limits( all = true; } while (overshoot && !locked); - /* if no handles overshot and were locked, see if it may be a good idea to unlock some handles */ + /* If no handles overshot and were locked, + * see if it may be a good idea to unlock some handles. */ if (!locked) { for (int i = 0; i < solve_count; i++) { // to definitely avoid infinite loops limit this to 2 times - if (!is_locked[i] || num_unlocks[i] >= 2) + if (!is_locked[i] || num_unlocks[i] >= 2) { continue; + } /* if the handle wants to move in allowable direction, release it */ float relax = bezier_relax_direction(a0, b0, c0, d0, h, i, solve_count); @@ -3768,6 +3928,8 @@ static bool tridiagonal_solve_with_limits( return true; } +/* Keep ascii art. */ +/* clang-format off */ /* * This function computes the handles of a series of auto bezier points * on the basis of 'no acceleration discontinuities' at the points. @@ -3795,30 +3957,31 @@ static bool tridiagonal_solve_with_limits( * |-------t1---------t2--------- ~ --------tN-------------------> time (co 0) * Mathematical basis: * - * 1. Handle lengths on either side of each point are connected by a factor - * ensuring continuity of the first derivative: + * 1. Handle lengths on either side of each point are connected by a factor + * ensuring continuity of the first derivative: * - * l[i] = t[i+1]/t[i] + * l[i] = t[i+1]/t[i] * - * 2. The tridiagonal system is formed by the following equation, which is derived - * by differentiating the bezier curve and specifies second derivative continuity - * at every point: + * 2. The tridiagonal system is formed by the following equation, which is derived + * by differentiating the bezier curve and specifies second derivative continuity + * at every point: * - * l[i]^2 * h[i-1] + (2*l[i]+2) * h[i] + 1/l[i+1] * h[i+1] = (y[i]-y[i-1])*l[i]^2 + y[i+1]-y[i] + * l[i]^2 * h[i-1] + (2*l[i]+2) * h[i] + 1/l[i+1] * h[i+1] = (y[i]-y[i-1])*l[i]^2 + y[i+1]-y[i] * - * 3. If this point is adjacent to a manually set handle with X size not equal to 1/3 - * of the horizontal interval, this equation becomes slightly more complex: + * 3. If this point is adjacent to a manually set handle with X size not equal to 1/3 + * of the horizontal interval, this equation becomes slightly more complex: * - * l[i]^2 * h[i-1] + (3*(1-R[i-1])*l[i] + 3*(1-L[i+1])) * h[i] + 1/l[i+1] * h[i+1] = (y[i]-y[i-1])*l[i]^2 + y[i+1]-y[i] + * l[i]^2 * h[i-1] + (3*(1-R[i-1])*l[i] + 3*(1-L[i+1])) * h[i] + 1/l[i+1] * h[i+1] = (y[i]-y[i-1])*l[i]^2 + y[i+1]-y[i] * - * The difference between equations amounts to this, and it's obvious that when R[i-1] - * and L[i+1] are both 1/3, it becomes zero: + * The difference between equations amounts to this, and it's obvious that when R[i-1] + * and L[i+1] are both 1/3, it becomes zero: * - * ( (1-3*R[i-1])*l[i] + (1-3*L[i+1]) ) * h[i] + * ( (1-3*R[i-1])*l[i] + (1-3*L[i+1]) ) * h[i] * - * 4. The equations for zero acceleration border conditions are basically the above - * equation with parts omitted, so the handle size correction also applies. + * 4. The equations for zero acceleration border conditions are basically the above + * equation with parts omitted, so the handle size correction also applies. */ +/* clang-format on */ static void bezier_eq_continuous( float *a, float *b, float *c, float *d, float *dy, float *l, int i) @@ -3852,16 +4015,20 @@ static void bezier_clamp( float *hmax, float *hmin, int i, float dy, bool no_reverse, bool no_overshoot) { if (dy > 0) { - if (no_overshoot) + if (no_overshoot) { hmax[i] = min_ff(hmax[i], dy); - if (no_reverse) + } + if (no_reverse) { hmin[i] = 0.0f; + } } else if (dy < 0) { - if (no_reverse) + if (no_reverse) { hmax[i] = 0.0f; - if (no_overshoot) + } + if (no_overshoot) { hmin[i] = max_ff(hmin[i], dy); + } } else if (no_reverse || no_overshoot) { hmax[i] = hmin[i] = 0.0f; @@ -3878,8 +4045,9 @@ static void bezier_output_handle_inner(BezTriple *bezt, bool right, float newval char hm = right ? bezt->h1 : bezt->h2; /* only assign Auto/Vector handles */ - if (!ELEM(hr, HD_AUTO, HD_AUTO_ANIM, HD_VECT)) + if (!ELEM(hr, HD_AUTO, HD_AUTO_ANIM, HD_VECT)) { return; + } copy_v3_v3(bezt->vec[idx], newval); @@ -3935,8 +4103,9 @@ static void bezier_handle_calc_smooth_fcurve( /* verify index ranges */ - if (count < 2) + if (count < 2) { return; + } BLI_assert(start < total - 1 && count <= total); BLI_assert(start + count <= total || cycle); @@ -3958,8 +4127,9 @@ static void bezier_handle_calc_smooth_fcurve( /* allocate all */ void *tmp_buffer = allocate_arrays(count, arrays, NULL, "bezier_calc_smooth_tmp"); - if (!tmp_buffer) + if (!tmp_buffer) { return; + } /* point locations */ @@ -3970,8 +4140,9 @@ static void bezier_handle_calc_smooth_fcurve( dy[i] = bezt[j].vec[1][1] - bezt[j - 1].vec[1][1]; /* when cyclic, jump from last point to first */ - if (cycle && j == total - 1) + if (cycle && j == total - 1) { j = 0; + } } /* ratio of x intervals */ @@ -4079,8 +4250,9 @@ static void bezier_handle_calc_smooth_fcurve( bezier_output_handle(&bezt[j], false, -h[i] / l[i], end); - if (end) + if (end) { j = 0; + } bezier_output_handle(&bezt[j], true, h[i], end); } @@ -4133,8 +4305,9 @@ void BKE_nurb_handle_smooth_fcurve(BezTriple *bezt, int total, bool cycle) for (int i = 1, j = start + 1; i < total; i++, j++) { /* in cyclic mode: jump from last to first point when necessary */ - if (j == total - 1 && cycle) + if (j == total - 1 && cycle) { j = 0; + } /* non auto handle closes the list (we come here at least for the last handle, see above) */ if (!is_free_auto_point(&bezt[j])) { @@ -4228,12 +4401,15 @@ void BKE_nurb_bezt_handle_test(BezTriple *bezt, const bool use_handle) #define SEL_F3 (1 << 2) if (use_handle) { - if (bezt->f1 & SELECT) + if (bezt->f1 & SELECT) { flag |= SEL_F1; - if (bezt->f2 & SELECT) + } + if (bezt->f2 & SELECT) { flag |= SEL_F2; - if (bezt->f3 & SELECT) + } + if (bezt->f3 & SELECT) { flag |= SEL_F3; + } } else { flag = (bezt->f2 & SELECT) ? (SEL_F1 | SEL_F2 | SEL_F3) : 0; @@ -4270,8 +4446,9 @@ void BKE_nurb_handles_test(Nurb *nu, const bool use_handle) BezTriple *bezt; int a; - if (nu->type != CU_BEZIER) + if (nu->type != CU_BEZIER) { return; + } bezt = nu->bezt; a = nu->pntsu; @@ -4292,8 +4469,9 @@ void BKE_nurb_handles_autocalc(Nurb *nu, int flag) BezTriple *bezt2, *bezt1, *bezt0; int i; - if (nu == NULL || nu->bezt == NULL) + if (nu == NULL || nu->bezt == NULL) { return; + } bezt2 = nu->bezt; bezt1 = bezt2 + (nu->pntsu - 1); @@ -4318,8 +4496,9 @@ void BKE_nurb_handles_autocalc(Nurb *nu, int flag) bezt1->h1 = HD_ALIGN; } /* or vector handle? */ - if (dist_squared_to_line_v3(bezt1->vec[0], bezt1->vec[1], bezt0->vec[1]) < eps_sq) + if (dist_squared_to_line_v3(bezt1->vec[0], bezt1->vec[1], bezt0->vec[1]) < eps_sq) { bezt1->h1 = HD_VECT; + } } } /* right handle: */ @@ -4332,24 +4511,30 @@ void BKE_nurb_handles_autocalc(Nurb *nu, int flag) } else { /* aligned handle? */ - if (align) + if (align) { bezt1->h2 = HD_ALIGN; + } /* or vector handle? */ - if (dist_squared_to_line_v3(bezt1->vec[2], bezt1->vec[1], bezt2->vec[1]) < eps_sq) + if (dist_squared_to_line_v3(bezt1->vec[2], bezt1->vec[1], bezt2->vec[1]) < eps_sq) { bezt1->h2 = HD_VECT; + } } } - if (leftsmall && bezt1->h2 == HD_ALIGN) + if (leftsmall && bezt1->h2 == HD_ALIGN) { bezt1->h2 = HD_FREE; - if (rightsmall && bezt1->h1 == HD_ALIGN) + } + if (rightsmall && bezt1->h1 == HD_ALIGN) { bezt1->h1 = HD_FREE; + } /* undesired combination: */ - if (bezt1->h1 == HD_ALIGN && bezt1->h2 == HD_VECT) + if (bezt1->h1 == HD_ALIGN && bezt1->h2 == HD_VECT) { bezt1->h1 = HD_FREE; - if (bezt1->h2 == HD_ALIGN && bezt1->h1 == HD_VECT) + } + if (bezt1->h2 == HD_ALIGN && bezt1->h1 == HD_VECT) { bezt1->h2 = HD_FREE; + } bezt0 = bezt1; bezt1 = bezt2; @@ -4390,15 +4575,19 @@ void BKE_nurbList_handles_set(ListBase *editnurb, const char code) a = nu->pntsu; while (a--) { if ((bezt->f1 & SELECT) || (bezt->f3 & SELECT)) { - if (bezt->f1 & SELECT) + if (bezt->f1 & SELECT) { bezt->h1 = code; - if (bezt->f3 & SELECT) + } + if (bezt->f3 & SELECT) { bezt->h2 = code; + } if (bezt->h1 != bezt->h2) { - if (ELEM(bezt->h1, HD_ALIGN, HD_AUTO)) + if (ELEM(bezt->h1, HD_ALIGN, HD_AUTO)) { bezt->h1 = HD_FREE; - if (ELEM(bezt->h2, HD_ALIGN, HD_AUTO)) + } + if (ELEM(bezt->h2, HD_ALIGN, HD_AUTO)) { bezt->h2 = HD_FREE; + } } } bezt++; @@ -4443,10 +4632,12 @@ void BKE_nurbList_handles_set(ListBase *editnurb, const char code) bezt = nu->bezt; a = nu->pntsu; while (a--) { - if (bezt->f1 & SELECT) + if (bezt->f1 & SELECT) { bezt->h1 = h_new; - if (bezt->f3 & SELECT) + } + if (bezt->f3 & SELECT) { bezt->h2 = h_new; + } bezt++; } @@ -4554,8 +4745,9 @@ void BKE_nurb_direction_switch(Nurb *nu) a = nu->pntsu; bezt1 = nu->bezt; bezt2 = bezt1 + (a - 1); - if (a & 1) + if (a & 1) { a += 1; /* if odd, also swap middle content */ + } a /= 2; while (a > 0) { if (bezt1 != bezt2) { @@ -4790,44 +4982,54 @@ void BKE_curve_nurbs_keyVertexTilts_apply(ListBase *lb, float *key) bool BKE_nurb_check_valid_u(struct Nurb *nu) { - if (nu->pntsu <= 1) + if (nu->pntsu <= 1) { return false; - if (nu->type != CU_NURBS) + } + if (nu->type != CU_NURBS) { return true; /* not a nurb, lets assume its valid */ + } - if (nu->pntsu < nu->orderu) + if (nu->pntsu < nu->orderu) { return false; + } if (((nu->flagu & CU_NURB_CYCLIC) == 0) && (nu->flagu & CU_NURB_BEZIER)) { /* Bezier U Endpoints */ if (nu->orderu == 4) { - if (nu->pntsu < 5) + if (nu->pntsu < 5) { return false; /* bezier with 4 orderu needs 5 points */ + } } else { - if (nu->orderu != 3) + if (nu->orderu != 3) { return false; /* order must be 3 or 4 */ + } } } return true; } bool BKE_nurb_check_valid_v(struct Nurb *nu) { - if (nu->pntsv <= 1) + if (nu->pntsv <= 1) { return false; - if (nu->type != CU_NURBS) + } + if (nu->type != CU_NURBS) { return true; /* not a nurb, lets assume its valid */ + } - if (nu->pntsv < nu->orderv) + if (nu->pntsv < nu->orderv) { return false; + } if (((nu->flagv & CU_NURB_CYCLIC) == 0) && (nu->flagv & CU_NURB_BEZIER)) { /* Bezier V Endpoints */ if (nu->orderv == 4) { - if (nu->pntsv < 5) + if (nu->pntsv < 5) { return false; /* bezier with 4 orderu needs 5 points */ + } } else { - if (nu->orderv != 3) + if (nu->orderv != 3) { return false; /* order must be 3 or 4 */ + } } } return true; @@ -4835,10 +5037,12 @@ bool BKE_nurb_check_valid_v(struct Nurb *nu) bool BKE_nurb_check_valid_uv(struct Nurb *nu) { - if (!BKE_nurb_check_valid_u(nu)) + if (!BKE_nurb_check_valid_u(nu)) { return false; - if ((nu->pntsv > 1) && !BKE_nurb_check_valid_v(nu)) + } + if ((nu->pntsv > 1) && !BKE_nurb_check_valid_v(nu)) { return false; + } return true; } @@ -4930,8 +5134,9 @@ bool BKE_nurb_type_convert(Nurb *nu, const short type, const bool use_handles) copy_v3_v3(bp->vec, bezt->vec[1]); bp->vec[3] = 1.0; bp->f1 = bezt->f2; - if (use_handles) + if (use_handles) { nr -= 2; + } bp->radius = bezt->radius; bp->weight = bezt->weight; bp++; @@ -4967,11 +5172,13 @@ bool BKE_nurb_type_convert(Nurb *nu, const short type, const bool use_handles) else if (nu->type == CU_NURBS) { if (type == CU_POLY) { nu->type = CU_POLY; - if (nu->knotsu) + if (nu->knotsu) { MEM_freeN(nu->knotsu); /* python created nurbs have a knotsu of zero */ + } nu->knotsu = NULL; - if (nu->knotsv) + if (nu->knotsv) { MEM_freeN(nu->knotsv); + } nu->knotsv = NULL; } else if (type == CU_BEZIER) { /* to Bezier */ diff --git a/source/blender/blenkernel/intern/customdata.c b/source/blender/blenkernel/intern/customdata.c index eff85f411ca..22bc44a88d8 100644 --- a/source/blender/blenkernel/intern/customdata.c +++ b/source/blender/blenkernel/intern/customdata.c @@ -159,7 +159,8 @@ typedef struct LayerTypeInfo { /** a function to determine file size */ size_t (*filesize)(CDataFile *cdf, const void *data, int count); - /** a function to determine max allowed number of layers, should be NULL or return -1 if no limit */ + /** a function to determine max allowed number of layers, + * should be NULL or return -1 if no limit */ int (*layers_max)(void); } LayerTypeInfo; @@ -179,8 +180,9 @@ static void layerCopy_mdeformvert(const void *source, void *dest, int count) memcpy(dw, dvert->dw, dvert->totweight * sizeof(*dw)); dvert->dw = dw; } - else + else { dvert->dw = NULL; + } } } @@ -247,8 +249,9 @@ static void layerInterp_mdeformvert(const void **sources, struct MDeformWeight_Link *node; int i, j, totweight; - if (count <= 0) + if (count <= 0) { return; + } /* build a list of unique def_nrs for dest */ totweight = 0; @@ -260,8 +263,9 @@ static void layerInterp_mdeformvert(const void **sources, MDeformWeight *dw = &source->dw[j]; float weight = dw->weight * interp_weight; - if (weight == 0.0f) + if (weight == 0.0f) { continue; + } for (node = dest_dwlink; node; node = node->next) { MDeformWeight *tmp_dw = &node->dw; @@ -321,7 +325,8 @@ static void layerInterp_normal(const void **sources, void *dest) { /* Note: This is linear interpolation, which is not optimal for vectors. - * Unfortunately, spherical interpolation of more than two values is hairy, so for now it will do... */ + * Unfortunately, spherical interpolation of more than two values is hairy, + * so for now it will do... */ float no[3] = {0.0f}; while (count--) { @@ -399,8 +404,9 @@ static void layerCopy_tface(const void *source, void *dest, int count) MTFace *dest_tf = (MTFace *)dest; int i; - for (i = 0; i < count; ++i) + for (i = 0; i < count; ++i) { dest_tf[i] = source_tf[i]; + } } static void layerInterp_tface( @@ -411,8 +417,9 @@ static void layerInterp_tface( float uv[4][2] = {{0.0f}}; const float *sub_weight; - if (count <= 0) + if (count <= 0) { return; + } sub_weight = sub_weights; for (i = 0; i < count; ++i) { @@ -456,8 +463,9 @@ static void layerDefault_tface(void *data, int count) MTFace *tf = (MTFace *)data; int i; - for (i = 0; i < count; i++) + for (i = 0; i < count; i++) { tf[i] = default_tf; + } } static int layerMaxNum_tface(void) @@ -503,8 +511,9 @@ static void layerCopy_origspace_face(const void *source, void *dest, int count) OrigSpaceFace *dest_tf = (OrigSpaceFace *)dest; int i; - for (i = 0; i < count; ++i) + for (i = 0; i < count; ++i) { dest_tf[i] = source_tf[i]; + } } static void layerInterp_origspace_face( @@ -515,8 +524,9 @@ static void layerInterp_origspace_face( float uv[4][2] = {{0.0f}}; const float *sub_weight; - if (count <= 0) + if (count <= 0) { return; + } sub_weight = sub_weights; for (i = 0; i < count; ++i) { @@ -557,8 +567,9 @@ static void layerDefault_origspace_face(void *data, int count) OrigSpaceFace *osf = (OrigSpaceFace *)data; int i; - for (i = 0; i < count; i++) + for (i = 0; i < count; i++) { osf[i] = default_osf; + } } static void layerSwap_mdisps(void *data, const int *ci) @@ -584,8 +595,9 @@ static void layerSwap_mdisps(void *data, const int *ci) d = MEM_calloc_arrayN(s->totdisp, 3 * sizeof(float), "mdisps swap"); - for (S = 0; S < corners; S++) + for (S = 0; S < corners; S++) { memcpy(d + cornersize * S, s->disps + cornersize * ci[S], cornersize * 3 * sizeof(float)); + } MEM_freeN(s->disps); s->disps = d; @@ -620,10 +632,12 @@ static void layerFree_mdisps(void *data, int count, int UNUSED(size)) MDisps *d = data; for (i = 0; i < count; ++i) { - if (d[i].disps) + if (d[i].disps) { MEM_freeN(d[i].disps); - if (d[i].hidden) + } + if (d[i].hidden) { MEM_freeN(d[i].hidden); + } d[i].disps = NULL; d[i].hidden = NULL; d[i].totdisp = 0; @@ -637,8 +651,9 @@ static int layerRead_mdisps(CDataFile *cdf, void *data, int count) int i; for (i = 0; i < count; ++i) { - if (!d[i].disps) + if (!d[i].disps) { d[i].disps = MEM_calloc_arrayN(d[i].totdisp, 3 * sizeof(float), "mdisps read"); + } if (!cdf_read_data(cdf, d[i].totdisp * 3 * sizeof(float), d[i].disps)) { CLOG_ERROR(&LOG, "failed to read multires displacement %d/%d %d", i, count, d[i].totdisp); @@ -670,8 +685,9 @@ static size_t layerFilesize_mdisps(CDataFile *UNUSED(cdf), const void *data, int size_t size = 0; int i; - for (i = 0; i < count; ++i) + for (i = 0; i < count; ++i) { size += d[i].totdisp * 3 * sizeof(float); + } return size; } @@ -700,8 +716,9 @@ static void layerFree_grid_paint_mask(void *data, int count, int UNUSED(size)) GridPaintMask *gpm = data; for (i = 0; i < count; ++i) { - if (gpm[i].data) + if (gpm[i].data) { MEM_freeN(gpm[i].data); + } gpm[i].data = NULL; gpm[i].level = 0; } @@ -803,23 +820,31 @@ static void layerDoMinMax_mloopcol(const void *data, void *vmin, void *vmax) const MLoopCol *m = data; MLoopCol *min = vmin, *max = vmax; - if (m->r < min->r) + if (m->r < min->r) { min->r = m->r; - if (m->g < min->g) + } + if (m->g < min->g) { min->g = m->g; - if (m->b < min->b) + } + if (m->b < min->b) { min->b = m->b; - if (m->a < min->a) + } + if (m->a < min->a) { min->a = m->a; + } - if (m->r > max->r) + if (m->r > max->r) { max->r = m->r; - if (m->g > max->g) + } + if (m->g > max->g) { max->g = m->g; - if (m->b > max->b) + } + if (m->b > max->b) { max->b = m->b; - if (m->a > max->a) + } + if (m->a > max->a) { max->a = m->a; + } } static void layerInitMinMax_mloopcol(void *vmin, void *vmax) @@ -842,8 +867,9 @@ static void layerDefault_mloopcol(void *data, int count) MLoopCol default_mloopcol = {255, 255, 255, 255}; MLoopCol *mlcol = (MLoopCol *)data; int i; - for (i = 0; i < count; i++) + for (i = 0; i < count; i++) { mlcol[i] = default_mloopcol; + } } static void layerInterp_mloopcol( @@ -899,7 +925,8 @@ static void layerCopyValue_mloopuv(const void *source, const MLoopUV *luv1 = source; MLoopUV *luv2 = dest; - /* We only support a limited subset of advanced mixing here - namely the mixfactor interpolation. */ + /* We only support a limited subset of advanced mixing here - + * namely the mixfactor interpolation. */ if (mixmode == CDT_MIX_NOMIX) { copy_v2_v2(luv2->uv, luv1->uv); @@ -1093,8 +1120,9 @@ static void layerInterp_mcol( const float *sub_weight; - if (count <= 0) + if (count <= 0) { return; + } sub_weight = sub_weights; for (i = 0; i < count; ++i) { @@ -1139,8 +1167,9 @@ static void layerSwap_mcol(void *data, const int *corner_indices) MCol col[4]; int j; - for (j = 0; j < 4; ++j) + for (j = 0; j < 4; ++j) { col[j] = mcol[corner_indices[j]]; + } memcpy(mcol, col, sizeof(col)); } @@ -1171,8 +1200,9 @@ static void layerInterp_bweight(const void **sources, float **in = (float **)sources; int i; - if (count <= 0) + if (count <= 0) { return; + } f = 0.0f; @@ -1201,8 +1231,9 @@ static void layerInterp_shapekey(const void **sources, float **in = (float **)sources; int i; - if (count <= 0) + if (count <= 0) { return; + } zero_v3(co); @@ -1401,7 +1432,8 @@ static const LayerTypeInfo LAYERTYPEINFO[CD_NUMTYPES] = { /* 14: CD_ORCO */ {sizeof(float) * 3, "", 0, NULL, NULL, NULL, NULL, NULL, NULL}, /* 15: CD_MTEXPOLY */ /* DEPRECATED */ - /* note, when we expose the UV Map / TexFace split to the user, change this back to face Texture */ + /* note, when we expose the UV Map / TexFace split to the user, + * change this back to face Texture. */ {sizeof(int), "", 0, NULL, NULL, NULL, NULL, NULL, NULL}, /* 16: CD_MLOOPUV */ {sizeof(MLoopUV), @@ -1720,16 +1752,18 @@ const CustomData_MeshMasks CD_MASK_EVERYTHING = { static const LayerTypeInfo *layerType_getInfo(int type) { - if (type < 0 || type >= CD_NUMTYPES) + if (type < 0 || type >= CD_NUMTYPES) { return NULL; + } return &LAYERTYPEINFO[type]; } static const char *layerType_getName(int type) { - if (type < 0 || type >= CD_NUMTYPES) + if (type < 0 || type >= CD_NUMTYPES) { return NULL; + } return LAYERTYPENAMES[type]; } @@ -1841,17 +1875,22 @@ bool CustomData_merge(const struct CustomData *source, lastmask = layer->active_mask; lasttype = type; } - else + else { number++; + } - if (flag & CD_FLAG_NOCOPY) + if (flag & CD_FLAG_NOCOPY) { continue; - else if (!(mask & CD_TYPE_AS_MASK(type))) + } + else if (!(mask & CD_TYPE_AS_MASK(type))) { continue; - else if ((maxnumber != -1) && (number >= maxnumber)) + } + else if ((maxnumber != -1) && (number >= maxnumber)) { continue; - else if (CustomData_get_layer_named(dest, type, layer->name)) + } + else if (CustomData_get_layer_named(dest, type, layer->name)) { continue; + } switch (alloctype) { case CD_ASSIGN: @@ -1911,8 +1950,9 @@ void CustomData_copy(const struct CustomData *source, { CustomData_reset(dest); - if (source->external) + if (source->external) { dest->external = MEM_dupallocN(source->external); + } CustomData_merge(source, dest, mask, alloctype, totelem); } @@ -1924,11 +1964,13 @@ static void customData_free_layer__internal(CustomDataLayer *layer, int totelem) if (!(layer->flag & CD_FLAG_NOFREE) && layer->data) { typeInfo = layerType_getInfo(layer->type); - if (typeInfo->free) + if (typeInfo->free) { typeInfo->free(layer->data, totelem, typeInfo->size); + } - if (layer->data) + if (layer->data) { MEM_freeN(layer->data); + } } } @@ -1950,11 +1992,13 @@ void CustomData_free(CustomData *data, int totelem) { int i; - for (i = 0; i < data->totlayer; ++i) + for (i = 0; i < data->totlayer; ++i) { customData_free_layer__internal(&data->layers[i], totelem); + } - if (data->layers) + if (data->layers) { MEM_freeN(data->layers); + } CustomData_external_free(data); CustomData_reset(data); @@ -1972,8 +2016,9 @@ void CustomData_free_typemask(struct CustomData *data, int totelem, CustomDataMa customData_free_layer__internal(layer, totelem); } - if (data->layers) + if (data->layers) { MEM_freeN(data->layers); + } CustomData_external_free(data); CustomData_reset(data); @@ -2000,9 +2045,11 @@ static int CustomData_get_layer_index__notypemap(const CustomData *data, int typ { int i; - for (i = 0; i < data->totlayer; ++i) - if (data->layers[i].type == type) + for (i = 0; i < data->totlayer; ++i) { + if (data->layers[i].type == type) { return i; + } + } return -1; } @@ -2032,10 +2079,13 @@ int CustomData_get_named_layer_index(const CustomData *data, int type, const cha { int i; - for (i = 0; i < data->totlayer; ++i) - if (data->layers[i].type == type) - if (STREQ(data->layers[i].name, name)) + for (i = 0; i < data->totlayer; ++i) { + if (data->layers[i].type == type) { + if (STREQ(data->layers[i].name, name)) { return i; + } + } + } return -1; } @@ -2111,82 +2161,101 @@ void CustomData_set_layer_active(CustomData *data, int type, int n) { int i; - for (i = 0; i < data->totlayer; ++i) - if (data->layers[i].type == type) + for (i = 0; i < data->totlayer; ++i) { + if (data->layers[i].type == type) { data->layers[i].active = n; + } + } } void CustomData_set_layer_render(CustomData *data, int type, int n) { int i; - for (i = 0; i < data->totlayer; ++i) - if (data->layers[i].type == type) + for (i = 0; i < data->totlayer; ++i) { + if (data->layers[i].type == type) { data->layers[i].active_rnd = n; + } + } } void CustomData_set_layer_clone(CustomData *data, int type, int n) { int i; - for (i = 0; i < data->totlayer; ++i) - if (data->layers[i].type == type) + for (i = 0; i < data->totlayer; ++i) { + if (data->layers[i].type == type) { data->layers[i].active_clone = n; + } + } } void CustomData_set_layer_stencil(CustomData *data, int type, int n) { int i; - for (i = 0; i < data->totlayer; ++i) - if (data->layers[i].type == type) + for (i = 0; i < data->totlayer; ++i) { + if (data->layers[i].type == type) { data->layers[i].active_mask = n; + } + } } -/* for using with an index from CustomData_get_active_layer_index and CustomData_get_render_layer_index */ +/* For using with an index from CustomData_get_active_layer_index and + * CustomData_get_render_layer_index. */ void CustomData_set_layer_active_index(CustomData *data, int type, int n) { int i; - for (i = 0; i < data->totlayer; ++i) - if (data->layers[i].type == type) + for (i = 0; i < data->totlayer; ++i) { + if (data->layers[i].type == type) { data->layers[i].active = n - i; + } + } } void CustomData_set_layer_render_index(CustomData *data, int type, int n) { int i; - for (i = 0; i < data->totlayer; ++i) - if (data->layers[i].type == type) + for (i = 0; i < data->totlayer; ++i) { + if (data->layers[i].type == type) { data->layers[i].active_rnd = n - i; + } + } } void CustomData_set_layer_clone_index(CustomData *data, int type, int n) { int i; - for (i = 0; i < data->totlayer; ++i) - if (data->layers[i].type == type) + for (i = 0; i < data->totlayer; ++i) { + if (data->layers[i].type == type) { data->layers[i].active_clone = n - i; + } + } } void CustomData_set_layer_stencil_index(CustomData *data, int type, int n) { int i; - for (i = 0; i < data->totlayer; ++i) - if (data->layers[i].type == type) + for (i = 0; i < data->totlayer; ++i) { + if (data->layers[i].type == type) { data->layers[i].active_mask = n - i; + } + } } void CustomData_set_layer_flag(struct CustomData *data, int type, int flag) { int i; - for (i = 0; i < data->totlayer; ++i) - if (data->layers[i].type == type) + for (i = 0; i < data->totlayer; ++i) { + if (data->layers[i].type == type) { data->layers[i].flag |= flag; + } + } } void CustomData_clear_layer_flag(struct CustomData *data, int type, int flag) @@ -2204,8 +2273,9 @@ static int customData_resize(CustomData *data, int amount) { CustomDataLayer *tmp = MEM_calloc_arrayN( (data->maxlayer + amount), sizeof(*tmp), "CustomData->layers"); - if (!tmp) + if (!tmp) { return 0; + } data->maxlayer += amount; if (data->layers) { @@ -2233,8 +2303,9 @@ static CustomDataLayer *customData_add_layer__internal(CustomData *data, BLI_assert(!layerdata || (alloctype == CD_ASSIGN) || (alloctype == CD_DUPLICATE) || (alloctype == CD_REFERENCE)); - if (!typeInfo->defaultname && CustomData_has_layer(data, type)) + if (!typeInfo->defaultname && CustomData_has_layer(data, type)) { return &data->layers[CustomData_get_layer_index(data, type)]; + } if ((alloctype == CD_ASSIGN) || (alloctype == CD_REFERENCE)) { newlayerdata = layerdata; @@ -2247,27 +2318,33 @@ static CustomDataLayer *customData_add_layer__internal(CustomData *data, newlayerdata = MEM_calloc_arrayN((size_t)totelem, typeInfo->size, layerType_getName(type)); } - if (!newlayerdata) + if (!newlayerdata) { return NULL; + } } if (alloctype == CD_DUPLICATE && layerdata) { - if (typeInfo->copy) + if (typeInfo->copy) { typeInfo->copy(layerdata, newlayerdata, totelem); - else + } + else { memcpy(newlayerdata, layerdata, (size_t)totelem * typeInfo->size); + } } else if (alloctype == CD_DEFAULT) { - if (typeInfo->set_default) + if (typeInfo->set_default) { typeInfo->set_default(newlayerdata, totelem); + } } - else if (alloctype == CD_REFERENCE) + else if (alloctype == CD_REFERENCE) { flag |= CD_FLAG_NOFREE; + } if (index >= data->maxlayer) { if (!customData_resize(data, CUSTOMDATA_GROW)) { - if (newlayerdata != layerdata) + if (newlayerdata != layerdata) { MEM_freeN(newlayerdata); + } return NULL; } } @@ -2275,8 +2352,9 @@ static CustomDataLayer *customData_add_layer__internal(CustomData *data, data->totlayer++; /* keep layers ordered by type */ - for (; index > 0 && data->layers[index - 1].type > type; --index) + for (; index > 0 && data->layers[index - 1].type > type; --index) { data->layers[index] = data->layers[index - 1]; + } data->layers[index].type = type; data->layers[index].flag = flag; @@ -2293,8 +2371,9 @@ static CustomDataLayer *customData_add_layer__internal(CustomData *data, BLI_strncpy(data->layers[index].name, name, sizeof(data->layers[index].name)); CustomData_set_layer_unique_name(data, index); } - else + else { data->layers[index].name[0] = '\0'; + } if (index > 0 && data->layers[index - 1].type == type) { data->layers[index].active = data->layers[index - 1].active; @@ -2324,8 +2403,9 @@ void *CustomData_add_layer( data, type, alloctype, layerdata, totelem, typeInfo->defaultname); CustomData_update_typemap(data); - if (layer) + if (layer) { return layer->data; + } return NULL; } @@ -2343,8 +2423,9 @@ void *CustomData_add_layer_named(CustomData *data, layer = customData_add_layer__internal(data, type, alloctype, layerdata, totelem, name); CustomData_update_typemap(data); - if (layer) + if (layer) { return layer->data; + } return NULL; } @@ -2363,8 +2444,9 @@ bool CustomData_free_layer(CustomData *data, int type, int totelem, int index) customData_free_layer__internal(&data->layers[index], totelem); - for (i = index + 1; i < data->totlayer; ++i) + for (i = index + 1; i < data->totlayer; ++i) { data->layers[i - 1] = data->layers[i]; + } data->totlayer--; @@ -2377,19 +2459,24 @@ bool CustomData_free_layer(CustomData *data, int type, int totelem, int index) CustomDataLayer *layer; for (layer = &data->layers[i]; i < data->totlayer && layer->type == type; i++, layer++) { - if (layer->active >= index_nonzero) + if (layer->active >= index_nonzero) { layer->active--; - if (layer->active_rnd >= index_nonzero) + } + if (layer->active_rnd >= index_nonzero) { layer->active_rnd--; - if (layer->active_clone >= index_nonzero) + } + if (layer->active_clone >= index_nonzero) { layer->active_clone--; - if (layer->active_mask >= index_nonzero) + } + if (layer->active_mask >= index_nonzero) { layer->active_mask--; + } } } - if (data->totlayer <= data->maxlayer - CUSTOMDATA_GROW) + if (data->totlayer <= data->maxlayer - CUSTOMDATA_GROW) { customData_resize(data, -CUSTOMDATA_GROW); + } customData_update_offsets(data); @@ -2400,8 +2487,9 @@ bool CustomData_free_layer_active(CustomData *data, int type, int totelem) { int index = 0; index = CustomData_get_active_layer_index(data, type); - if (index == -1) + if (index == -1) { return false; + } return CustomData_free_layer(data, type, totelem, index); } @@ -2422,9 +2510,11 @@ int CustomData_number_of_layers(const CustomData *data, int type) { int i, number = 0; - for (i = 0; i < data->totlayer; i++) - if (data->layers[i].type == type) + for (i = 0; i < data->totlayer; i++) { + if (data->layers[i].type == type) { number++; + } + } return number; } @@ -2433,9 +2523,11 @@ int CustomData_number_of_layers_typemask(const CustomData *data, CustomDataMask { int i, number = 0; - for (i = 0; i < data->totlayer; i++) - if (mask & CD_TYPE_AS_MASK(data->layers[i].type)) + for (i = 0; i < data->totlayer; i++) { + if (mask & CD_TYPE_AS_MASK(data->layers[i].type)) { number++; + } + } return number; } @@ -2518,8 +2610,9 @@ bool CustomData_is_referenced_layer(struct CustomData *data, int type) /* get the layer index of the first layer of type */ layer_index = CustomData_get_active_layer_index(data, type); - if (layer_index == -1) + if (layer_index == -1) { return false; + } layer = &data->layers[layer_index]; @@ -2535,15 +2628,17 @@ void CustomData_free_temporary(CustomData *data, int totelem) for (i = 0, j = 0; i < data->totlayer; ++i) { layer = &data->layers[i]; - if (i != j) + if (i != j) { data->layers[j] = data->layers[i]; + } if ((layer->flag & CD_FLAG_TEMPORARY) == CD_FLAG_TEMPORARY) { customData_free_layer__internal(layer, totelem); changed = true; } - else + else { j++; + } } data->totlayer = j; @@ -2562,19 +2657,23 @@ void CustomData_set_only_copy(const struct CustomData *data, CustomDataMask mask { int i; - for (i = 0; i < data->totlayer; ++i) - if (!(mask & CD_TYPE_AS_MASK(data->layers[i].type))) + for (i = 0; i < data->totlayer; ++i) { + if (!(mask & CD_TYPE_AS_MASK(data->layers[i].type))) { data->layers[i].flag |= CD_FLAG_NOCOPY; + } + } } void CustomData_copy_elements(int type, void *src_data_ofs, void *dst_data_ofs, int count) { const LayerTypeInfo *typeInfo = layerType_getInfo(type); - if (typeInfo->copy) + if (typeInfo->copy) { typeInfo->copy(src_data_ofs, dst_data_ofs, count); - else + } + else { memcpy(dst_data_ofs, src_data_ofs, (size_t)count * typeInfo->size); + } } static void CustomData_copy_data_layer(const CustomData *source, @@ -2652,8 +2751,9 @@ void CustomData_copy_data( } /* if there are no more dest layers, we're done */ - if (dest_i >= dest->totlayer) + if (dest_i >= dest->totlayer) { return; + } /* if we found a matching layer, copy the data */ if (dest->layers[dest_i].type == source->layers[src_i].type) { @@ -2728,15 +2828,17 @@ void CustomData_interp(const CustomData *source, /* slow fallback in case we're interpolating a ridiculous number of * elements */ - if (count > SOURCE_BUF_SIZE) + if (count > SOURCE_BUF_SIZE) { sources = MEM_malloc_arrayN(count, sizeof(*sources), __func__); + } /* interpolates a layer at a time */ dest_i = 0; for (src_i = 0; src_i < source->totlayer; ++src_i) { const LayerTypeInfo *typeInfo = layerType_getInfo(source->layers[src_i].type); - if (!typeInfo->interp) + if (!typeInfo->interp) { continue; + } /* find the first dest layer with type >= the source type * (this should work because layers are ordered by type) @@ -2746,8 +2848,9 @@ void CustomData_interp(const CustomData *source, } /* if there are no more dest layers, we're done */ - if (dest_i >= dest->totlayer) + if (dest_i >= dest->totlayer) { break; + } /* if we found a matching layer, copy the data */ if (dest->layers[dest_i].type == source->layers[src_i].type) { @@ -2772,14 +2875,15 @@ void CustomData_interp(const CustomData *source, } } - if (count > SOURCE_BUF_SIZE) + if (count > SOURCE_BUF_SIZE) { MEM_freeN((void *)sources); + } } /** * Swap data inside each item, for all layers. - * This only applies to item types that may store several sub-item data (e.g. corner data [UVs, VCol, ...] of - * tessellated faces). + * This only applies to item types that may store several sub-item data + * (e.g. corner data [UVs, VCol, ...] of tessellated faces). * * \param corner_indices: A mapping 'new_index -> old_index' of sub-item data. */ @@ -2838,8 +2942,9 @@ void *CustomData_get(const CustomData *data, int index, int type) /* get the layer index of the active layer of type */ layer_index = CustomData_get_active_layer_index(data, type); - if (layer_index == -1) + if (layer_index == -1) { return NULL; + } /* get the offset of the desired element */ const size_t offset = (size_t)index * layerType_getInfo(type)->size; @@ -2855,8 +2960,9 @@ void *CustomData_get_n(const CustomData *data, int type, int index, int n) /* get the layer index of the first layer of type */ layer_index = data->typemap[type]; - if (layer_index == -1) + if (layer_index == -1) { return NULL; + } const size_t offset = (size_t)index * layerType_getInfo(type)->size; return POINTER_OFFSET(data->layers[layer_index + n].data, offset); @@ -2866,8 +2972,9 @@ void *CustomData_get_layer(const CustomData *data, int type) { /* get the layer index of the active layer of type */ int layer_index = CustomData_get_active_layer_index(data, type); - if (layer_index == -1) + if (layer_index == -1) { return NULL; + } return data->layers[layer_index].data; } @@ -2876,8 +2983,9 @@ void *CustomData_get_layer_n(const CustomData *data, int type, int n) { /* get the layer index of the active layer of type */ int layer_index = CustomData_get_layer_index_n(data, type, n); - if (layer_index == -1) + if (layer_index == -1) { return NULL; + } return data->layers[layer_index].data; } @@ -2885,8 +2993,9 @@ void *CustomData_get_layer_n(const CustomData *data, int type, int n) void *CustomData_get_layer_named(const struct CustomData *data, int type, const char *name) { int layer_index = CustomData_get_named_layer_index(data, type, name); - if (layer_index == -1) + if (layer_index == -1) { return NULL; + } return data->layers[layer_index].data; } @@ -2895,8 +3004,9 @@ int CustomData_get_offset(const CustomData *data, int type) { /* get the layer index of the active layer of type */ int layer_index = CustomData_get_active_layer_index(data, type); - if (layer_index == -1) + if (layer_index == -1) { return -1; + } return data->layers[layer_index].offset; } @@ -2905,8 +3015,9 @@ int CustomData_get_n_offset(const CustomData *data, int type, int n) { /* get the layer index of the active layer of type */ int layer_index = CustomData_get_layer_index_n(data, type, n); - if (layer_index == -1) + if (layer_index == -1) { return -1; + } return data->layers[layer_index].offset; } @@ -2916,8 +3027,9 @@ bool CustomData_set_layer_name(const CustomData *data, int type, int n, const ch /* get the layer index of the first layer of type */ const int layer_index = CustomData_get_layer_index_n(data, type, n); - if ((layer_index == -1) || !name) + if ((layer_index == -1) || !name) { return false; + } BLI_strncpy(data->layers[layer_index].name, name, sizeof(data->layers[layer_index].name)); @@ -2936,8 +3048,9 @@ void *CustomData_set_layer(const CustomData *data, int type, void *ptr) /* get the layer index of the first layer of type */ int layer_index = CustomData_get_active_layer_index(data, type); - if (layer_index == -1) + if (layer_index == -1) { return NULL; + } data->layers[layer_index].data = ptr; @@ -2948,8 +3061,9 @@ void *CustomData_set_layer_n(const struct CustomData *data, int type, int n, voi { /* get the layer index of the first layer of type */ int layer_index = CustomData_get_layer_index_n(data, type, n); - if (layer_index == -1) + if (layer_index == -1) { return NULL; + } data->layers[layer_index].data = ptr; @@ -2961,13 +3075,16 @@ void CustomData_set(const CustomData *data, int index, int type, const void *sou void *dest = CustomData_get(data, index, type); const LayerTypeInfo *typeInfo = layerType_getInfo(type); - if (!dest) + if (!dest) { return; + } - if (typeInfo->copy) + if (typeInfo->copy) { typeInfo->copy(source, dest, 1); - else + } + else { memcpy(dest, source, typeInfo->size); + } } /* BMesh functions */ @@ -3042,18 +3159,24 @@ bool CustomData_from_bmeshpoly_test(CustomData *fdata, CustomData *ldata, bool f ((a_num += CustomData_number_of_layers(l_a, t_a)) == \ (b_num += CustomData_number_of_layers(l_b, t_b))) - if (!LAYER_CMP(ldata, CD_MLOOPUV, fdata, CD_MTFACE)) + if (!LAYER_CMP(ldata, CD_MLOOPUV, fdata, CD_MTFACE)) { return false; - if (!LAYER_CMP(ldata, CD_MLOOPCOL, fdata, CD_MCOL)) + } + if (!LAYER_CMP(ldata, CD_MLOOPCOL, fdata, CD_MCOL)) { return false; - if (!LAYER_CMP(ldata, CD_PREVIEW_MLOOPCOL, fdata, CD_PREVIEW_MCOL)) + } + if (!LAYER_CMP(ldata, CD_PREVIEW_MLOOPCOL, fdata, CD_PREVIEW_MCOL)) { return false; - if (!LAYER_CMP(ldata, CD_ORIGSPACE_MLOOP, fdata, CD_ORIGSPACE)) + } + if (!LAYER_CMP(ldata, CD_ORIGSPACE_MLOOP, fdata, CD_ORIGSPACE)) { return false; - if (!LAYER_CMP(ldata, CD_NORMAL, fdata, CD_TESSLOOPNORMAL)) + } + if (!LAYER_CMP(ldata, CD_NORMAL, fdata, CD_TESSLOOPNORMAL)) { return false; - if (!LAYER_CMP(ldata, CD_TANGENT, fdata, CD_TANGENT)) + } + if (!LAYER_CMP(ldata, CD_TANGENT, fdata, CD_TANGENT)) { return false; + } # undef LAYER_CMP @@ -3192,8 +3315,9 @@ bool CustomData_bmesh_merge(const CustomData *source, } if (CustomData_merge(source, dest, mask, alloctype, 0) == false) { - if (destold.layers) + if (destold.layers) { MEM_freeN(destold.layers); + } return false; } @@ -3249,10 +3373,12 @@ bool CustomData_bmesh_merge(const CustomData *source, } } - if (destold.pool) + if (destold.pool) { BLI_mempool_destroy(destold.pool); - if (destold.layers) + } + if (destold.layers) { MEM_freeN(destold.layers); + } return true; } @@ -3261,8 +3387,9 @@ void CustomData_bmesh_free_block(CustomData *data, void **block) const LayerTypeInfo *typeInfo; int i; - if (*block == NULL) + if (*block == NULL) { return; + } for (i = 0; i < data->totlayer; ++i) { if (!(data->layers[i].flag & CD_FLAG_NOFREE)) { @@ -3275,8 +3402,9 @@ void CustomData_bmesh_free_block(CustomData *data, void **block) } } - if (data->totsize) + if (data->totsize) { BLI_mempool_free(data->pool, *block); + } *block = NULL; } @@ -3289,8 +3417,9 @@ void CustomData_bmesh_free_block_data(CustomData *data, void *block) const LayerTypeInfo *typeInfo; int i; - if (block == NULL) + if (block == NULL) { return; + } for (i = 0; i < data->totlayer; ++i) { if (!(data->layers[i].flag & CD_FLAG_NOFREE)) { @@ -3303,20 +3432,24 @@ void CustomData_bmesh_free_block_data(CustomData *data, void *block) } } - if (data->totsize) + if (data->totsize) { memset(block, 0, data->totsize); + } } static void CustomData_bmesh_alloc_block(CustomData *data, void **block) { - if (*block) + if (*block) { CustomData_bmesh_free_block(data, block); + } - if (data->totsize > 0) + if (data->totsize > 0) { *block = BLI_mempool_alloc(data->pool); - else + } + else { *block = NULL; + } } void CustomData_bmesh_copy_data(const CustomData *source, @@ -3329,8 +3462,9 @@ void CustomData_bmesh_copy_data(const CustomData *source, if (*dest_block == NULL) { CustomData_bmesh_alloc_block(dest, dest_block); - if (*dest_block) + if (*dest_block) { memset(*dest_block, 0, dest->totsize); + } } /* copies a layer at a time */ @@ -3345,8 +3479,9 @@ void CustomData_bmesh_copy_data(const CustomData *source, } /* if there are no more dest layers, we're done */ - if (dest_i >= dest->totlayer) + if (dest_i >= dest->totlayer) { return; + } /* if we found a matching layer, copy the data */ if (dest->layers[dest_i].type == source->layers[src_i].type && @@ -3356,10 +3491,12 @@ void CustomData_bmesh_copy_data(const CustomData *source, typeInfo = layerType_getInfo(source->layers[src_i].type); - if (typeInfo->copy) + if (typeInfo->copy) { typeInfo->copy(src_data, dest_data, 1); - else + } + else { memcpy(dest_data, src_data, typeInfo->size); + } /* if there are multiple source & dest layers of the same type, * we don't want to copy all source layers to the same dest, so @@ -3370,15 +3507,18 @@ void CustomData_bmesh_copy_data(const CustomData *source, } } -/*Bmesh Custom Data Functions. Should replace editmesh ones with these as well, due to more efficient memory alloc*/ +/* BMesh Custom Data Functions. + * Should replace edit-mesh ones with these as well, due to more efficient memory alloc. + */ void *CustomData_bmesh_get(const CustomData *data, void *block, int type) { int layer_index; /* get the layer index of the first layer of type */ layer_index = CustomData_get_active_layer_index(data, type); - if (layer_index == -1) + if (layer_index == -1) { return NULL; + } return POINTER_OFFSET(block, data->layers[layer_index].offset); } @@ -3389,8 +3529,9 @@ void *CustomData_bmesh_get_n(const CustomData *data, void *block, int type, int /* get the layer index of the first layer of type */ layer_index = CustomData_get_layer_index(data, type); - if (layer_index == -1) + if (layer_index == -1) { return NULL; + } return POINTER_OFFSET(block, data->layers[layer_index + n].offset); } @@ -3398,8 +3539,9 @@ void *CustomData_bmesh_get_n(const CustomData *data, void *block, int type, int /*gets from the layer at physical index n, note: doesn't check type.*/ void *CustomData_bmesh_get_layer_n(const CustomData *data, void *block, int n) { - if (n < 0 || n >= data->totlayer) + if (n < 0 || n >= data->totlayer) { return NULL; + } return POINTER_OFFSET(block, data->layers[n].offset); } @@ -3489,13 +3631,16 @@ void CustomData_data_copy_value(int type, const void *source, void *dest) { const LayerTypeInfo *typeInfo = layerType_getInfo(type); - if (!dest) + if (!dest) { return; + } - if (typeInfo->copyvalue) + if (typeInfo->copyvalue) { typeInfo->copyvalue(source, dest, CDT_MIX_NOMIX, 0.0f); - else + } + else { memcpy(dest, source, typeInfo->size); + } } /* Mixes the "value" (e.g. mloopuv uv or mloopcol colors) from one block into @@ -3505,8 +3650,9 @@ void CustomData_data_mix_value( { const LayerTypeInfo *typeInfo = layerType_getInfo(type); - if (!dest) + if (!dest) { return; + } if (typeInfo->copyvalue) { typeInfo->copyvalue(source, dest, mixmode, mixfactor); @@ -3521,42 +3667,48 @@ bool CustomData_data_equals(int type, const void *data1, const void *data2) { const LayerTypeInfo *typeInfo = layerType_getInfo(type); - if (typeInfo->equal) + if (typeInfo->equal) { return typeInfo->equal(data1, data2); - else + } + else { return !memcmp(data1, data2, typeInfo->size); + } } void CustomData_data_initminmax(int type, void *min, void *max) { const LayerTypeInfo *typeInfo = layerType_getInfo(type); - if (typeInfo->initminmax) + if (typeInfo->initminmax) { typeInfo->initminmax(min, max); + } } void CustomData_data_dominmax(int type, const void *data, void *min, void *max) { const LayerTypeInfo *typeInfo = layerType_getInfo(type); - if (typeInfo->dominmax) + if (typeInfo->dominmax) { typeInfo->dominmax(data, min, max); + } } void CustomData_data_multiply(int type, void *data, float fac) { const LayerTypeInfo *typeInfo = layerType_getInfo(type); - if (typeInfo->multiply) + if (typeInfo->multiply) { typeInfo->multiply(data, fac); + } } void CustomData_data_add(int type, void *data1, const void *data2) { const LayerTypeInfo *typeInfo = layerType_getInfo(type); - if (typeInfo->add) + if (typeInfo->add) { typeInfo->add(data1, data2); + } } void CustomData_bmesh_set(const CustomData *data, void *block, int type, const void *source) @@ -3564,13 +3716,16 @@ void CustomData_bmesh_set(const CustomData *data, void *block, int type, const v void *dest = CustomData_bmesh_get(data, block, type); const LayerTypeInfo *typeInfo = layerType_getInfo(type); - if (!dest) + if (!dest) { return; + } - if (typeInfo->copy) + if (typeInfo->copy) { typeInfo->copy(source, dest, 1); - else + } + else { memcpy(dest, source, typeInfo->size); + } } void CustomData_bmesh_set_n(CustomData *data, void *block, int type, int n, const void *source) @@ -3578,13 +3733,16 @@ void CustomData_bmesh_set_n(CustomData *data, void *block, int type, int n, cons void *dest = CustomData_bmesh_get_n(data, block, type, n); const LayerTypeInfo *typeInfo = layerType_getInfo(type); - if (!dest) + if (!dest) { return; + } - if (typeInfo->copy) + if (typeInfo->copy) { typeInfo->copy(source, dest, 1); - else + } + else { memcpy(dest, source, typeInfo->size); + } } void CustomData_bmesh_set_layer_n(CustomData *data, void *block, int n, const void *source) @@ -3592,13 +3750,16 @@ void CustomData_bmesh_set_layer_n(CustomData *data, void *block, int n, const vo void *dest = CustomData_bmesh_get_layer_n(data, block, n); const LayerTypeInfo *typeInfo = layerType_getInfo(data->layers[n].type); - if (!dest) + if (!dest) { return; + } - if (typeInfo->copy) + if (typeInfo->copy) { typeInfo->copy(source, dest, 1); - else + } + else { memcpy(dest, source, typeInfo->size); + } } /** @@ -3633,8 +3794,9 @@ void CustomData_bmesh_interp(CustomData *data, /* slow fallback in case we're interpolating a ridiculous number of * elements */ - if (count > SOURCE_BUF_SIZE) + if (count > SOURCE_BUF_SIZE) { sources = MEM_malloc_arrayN(count, sizeof(*sources), __func__); + } /* interpolates a layer at a time */ for (i = 0; i < data->totlayer; ++i) { @@ -3649,8 +3811,9 @@ void CustomData_bmesh_interp(CustomData *data, } } - if (count > SOURCE_BUF_SIZE) + if (count > SOURCE_BUF_SIZE) { MEM_freeN((void *)sources); + } } static void CustomData_bmesh_set_default_n(CustomData *data, void **block, int n) @@ -3672,8 +3835,9 @@ void CustomData_bmesh_set_default(CustomData *data, void **block) { int i; - if (*block == NULL) + if (*block == NULL) { CustomData_bmesh_alloc_block(data, block); + } for (i = 0; i < data->totlayer; ++i) { CustomData_bmesh_set_default_n(data, block, i); @@ -3694,8 +3858,9 @@ void CustomData_to_bmesh_block(const CustomData *source, const LayerTypeInfo *typeInfo; int dest_i, src_i; - if (*dest_block == NULL) + if (*dest_block == NULL) { CustomData_bmesh_alloc_block(dest, dest_block); + } /* copies a layer at a time */ dest_i = 0; @@ -3712,8 +3877,9 @@ void CustomData_to_bmesh_block(const CustomData *source, } /* if there are no more dest layers, we're done */ - if (dest_i >= dest->totlayer) + if (dest_i >= dest->totlayer) { break; + } /* if we found a matching layer, copy the data */ if (dest->layers[dest_i].type == source->layers[src_i].type) { @@ -3724,10 +3890,12 @@ void CustomData_to_bmesh_block(const CustomData *source, typeInfo = layerType_getInfo(dest->layers[dest_i].type); const size_t src_offset = (size_t)src_index * typeInfo->size; - if (typeInfo->copy) + if (typeInfo->copy) { typeInfo->copy(POINTER_OFFSET(src_data, src_offset), dest_data, 1); - else + } + else { memcpy(dest_data, POINTER_OFFSET(src_data, src_offset), typeInfo->size); + } /* if there are multiple source & dest layers of the same type, * we don't want to copy all source layers to the same dest, so @@ -3764,8 +3932,9 @@ void CustomData_from_bmesh_block(const CustomData *source, } /* if there are no more dest layers, we're done */ - if (dest_i >= dest->totlayer) + if (dest_i >= dest->totlayer) { return; + } /* if we found a matching layer, copy the data */ if (dest->layers[dest_i].type == source->layers[src_i].type) { @@ -3775,10 +3944,12 @@ void CustomData_from_bmesh_block(const CustomData *source, void *dst_data = POINTER_OFFSET(dest->layers[dest_i].data, (size_t)dst_index * typeInfo->size); - if (typeInfo->copy) + if (typeInfo->copy) { typeInfo->copy(src_data, dst_data, 1); - else + } + else { memcpy(dst_data, src_data, typeInfo->size); + } /* if there are multiple source & dest layers of the same type, * we don't want to copy all source layers to the same dest, so @@ -3801,15 +3972,20 @@ void CustomData_file_write_info(int type, const char **r_struct_name, int *r_str * Prepare given custom data for file writing. * * \param data: the customdata 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 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. * - * \warning After this func has ran, given custom data is no more valid from Blender PoV (its totlayer is invalid). - * This func 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 After this func has ran, given custom data is no more valid from Blender PoV + * (its totlayer is invalid). This func 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. */ void CustomData_file_write_prepare(CustomData *data, CustomDataLayer **r_write_layers, @@ -3892,8 +4068,9 @@ int CustomData_layertype_layers_max(const int type) static bool CustomData_is_property_layer(int type) { - if ((type == CD_PROP_FLT) || (type == CD_PROP_INT) || (type == CD_PROP_STR)) + if ((type == CD_PROP_FLT) || (type == CD_PROP_INT) || (type == CD_PROP_STR)) { return true; + } return false; } @@ -3967,8 +4144,9 @@ void CustomData_validate_layer_name(const CustomData *data, int index = -1; /* if a layer name was given, try to find that layer */ - if (name[0]) + if (name[0]) { index = CustomData_get_named_layer_index(data, type, name); + } if (index == -1) { /* either no layer was specified, or the layer we want has been @@ -3998,9 +4176,11 @@ bool CustomData_verify_versions(struct CustomData *data, int index) if (!typeInfo->defaultname && (index > 0) && data->layers[index - 1].type == layer->type) { keeplayer = false; /* multiple layers of which we only support one */ } - /* This is a pre-emptive fix for cases that should not happen (layers that should not be written - * in .blend files), but can happen due to bugs (see e.g. T62318). - * Also for forward compatibility, in future, we may put into .blend file some currently un-written data types, + /* This is a pre-emptive fix for cases that should not happen + * (layers that should not be written in .blend files), + * but can happen due to bugs (see e.g. T62318). + * Also for forward compatibility, in future, + * we may put into `.blend` file some currently un-written data types, * this should cover that case as well. * Better to be safe here, and fix issue on the fly rather than crash... */ /* 0 structnum is used in writing code to tag layer types that should not be written. */ @@ -4013,8 +4193,9 @@ bool CustomData_verify_versions(struct CustomData *data, int index) } if (!keeplayer) { - for (i = index + 1; i < data->totlayer; ++i) + for (i = index + 1; i < data->totlayer; ++i) { data->layers[i - 1] = data->layers[i]; + } data->totlayer--; } @@ -4022,7 +4203,8 @@ bool CustomData_verify_versions(struct CustomData *data, int index) } /** - * Validate and fix data of \a layer, if possible (needs relevant callback in layer's type to be defined). + * Validate and fix data of \a layer, + * if possible (needs relevant callback in layer's type to be defined). * * \return True if some errors were found. */ @@ -4061,8 +4243,9 @@ void CustomData_external_reload(CustomData *data, ID *UNUSED(id), CustomDataMask /* pass */ } else if ((layer->flag & CD_FLAG_EXTERNAL) && (layer->flag & CD_FLAG_IN_MEMORY)) { - if (typeInfo->free) + if (typeInfo->free) { typeInfo->free(layer->data, totelem, typeInfo->size); + } layer->flag &= ~CD_FLAG_IN_MEMORY; } } @@ -4078,8 +4261,9 @@ void CustomData_external_read(CustomData *data, ID *id, CustomDataMask mask, int const LayerTypeInfo *typeInfo; int i, update = 0; - if (!external) + if (!external) { return; + } for (i = 0; i < data->totlayer; i++) { layer = &data->layers[i]; @@ -4096,8 +4280,9 @@ void CustomData_external_read(CustomData *data, ID *id, CustomDataMask mask, int } } - if (!update) + if (!update) { return; + } customdata_external_filename(filename, id, external); @@ -4131,8 +4316,9 @@ void CustomData_external_read(CustomData *data, ID *id, CustomDataMask mask, int } layer->flag |= CD_FLAG_IN_MEMORY; } - else + else { break; + } } } } @@ -4152,8 +4338,9 @@ void CustomData_external_write( int i, update = 0; char filename[FILE_MAX]; - if (!external) + if (!external) { return; + } /* test if there is anything to write */ for (i = 0; i < data->totlayer; i++) { @@ -4168,8 +4355,9 @@ void CustomData_external_write( } } - if (!update) + if (!update) { return; + } /* make sure data is read before we try to write */ CustomData_external_read(data, id, mask, totelem); @@ -4233,8 +4421,9 @@ void CustomData_external_write( if ((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write) { if (free) { - if (typeInfo->free) + if (typeInfo->free) { typeInfo->free(layer->data, totelem, typeInfo->size); + } layer->flag &= ~CD_FLAG_IN_MEMORY; } } @@ -4252,13 +4441,15 @@ void CustomData_external_add( int layer_index; layer_index = CustomData_get_active_layer_index(data, type); - if (layer_index == -1) + if (layer_index == -1) { return; + } layer = &data->layers[layer_index]; - if (layer->flag & CD_FLAG_EXTERNAL) + if (layer->flag & CD_FLAG_EXTERNAL) { return; + } if (!external) { external = MEM_callocN(sizeof(CustomDataExternal), "CustomDataExternal"); @@ -4273,21 +4464,24 @@ void CustomData_external_remove(CustomData *data, ID *id, int type, int totelem) { CustomDataExternal *external = data->external; CustomDataLayer *layer; - //char filename[FILE_MAX]; + // char filename[FILE_MAX]; int layer_index; // i, remove_file; layer_index = CustomData_get_active_layer_index(data, type); - if (layer_index == -1) + if (layer_index == -1) { return; + } layer = &data->layers[layer_index]; - if (!external) + if (!external) { return; + } if (layer->flag & CD_FLAG_EXTERNAL) { - if (!(layer->flag & CD_FLAG_IN_MEMORY)) + if (!(layer->flag & CD_FLAG_IN_MEMORY)) { CustomData_external_read(data, id, CD_TYPE_AS_MASK(layer->type), totelem); + } layer->flag &= ~CD_FLAG_EXTERNAL; } @@ -4299,8 +4493,9 @@ bool CustomData_external_test(CustomData *data, int type) int layer_index; layer_index = CustomData_get_active_layer_index(data, type); - if (layer_index == -1) + if (layer_index == -1) { return false; + } layer = &data->layers[layer_index]; return (layer->flag & CD_FLAG_EXTERNAL) != 0; @@ -4331,7 +4526,7 @@ static void copy_bit_flag(void *dst, const void *src, const size_t data_size, co COPY_BIT_FLAG(uint64_t, dst, src, flag); break; default: - //CLOG_ERROR(&LOG, "Unknown flags-container size (%zu)", datasize); + // CLOG_ERROR(&LOG, "Unknown flags-container size (%zu)", datasize); break; } @@ -4350,7 +4545,7 @@ static bool check_bit_flag(const void *data, const size_t data_size, const uint6 case 8: return ((*((uint64_t *)data) & ((uint64_t)flag)) != 0); default: - //CLOG_ERROR(&LOG, "Unknown flags-container size (%zu)", datasize); + // CLOG_ERROR(&LOG, "Unknown flags-container size (%zu)", datasize); return false; } } @@ -4363,9 +4558,9 @@ static void customdata_data_transfer_interp_generic(const CustomDataTransferLaye const float mix_factor) { /* Fake interpolation, we actually copy highest weighted source to dest. - * Note we also handle bitflags here, in which case we rather choose to transfer value of elements totaling + * Note we also handle bitflags here, + * in which case we rather choose to transfer value of elements totaling * more than 0.5 of weight. */ - int best_src_idx = 0; const int data_type = laymap->data_type; @@ -4401,7 +4596,8 @@ static void customdata_data_transfer_interp_generic(const CustomDataTransferLaye int i; if (data_flag) { - /* Boolean case, we can 'interpolate' in two groups, and choose value from highest weighted group. */ + /* Boolean case, we can 'interpolate' in two groups, + * and choose value from highest weighted group. */ float tot_weight_true = 0.0f; int item_true_idx = -1, item_false_idx = -1; @@ -4446,7 +4642,8 @@ static void customdata_data_transfer_interp_generic(const CustomDataTransferLaye } if (data_flag) { - /* Bool flags, only copy if dest data is set (resp. unset) - only 'advanced' modes we can support here! */ + /* Bool flags, only copy if dest data is set (resp. unset) - + * only 'advanced' modes we can support here! */ if (mix_factor >= 0.5f && ((mix_mode == CDT_MIX_TRANSFER) || (mix_mode == CDT_MIX_REPLACE_ABOVE_THRESHOLD && check_bit_flag(data_dst, data_size, data_flag)) || diff --git a/source/blender/blenkernel/intern/customdata_file.c b/source/blender/blenkernel/intern/customdata_file.c index 6e7d4d856d7..379da377b42 100644 --- a/source/blender/blenkernel/intern/customdata_file.c +++ b/source/blender/blenkernel/intern/customdata_file.c @@ -98,10 +98,12 @@ struct CDataFile { static int cdf_endian(void) { - if (ENDIAN_ORDER == L_ENDIAN) + if (ENDIAN_ORDER == L_ENDIAN) { return CDF_ENDIAN_LITTLE; - else + } + else { return CDF_ENDIAN_BIG; + } } CDataFile *cdf_create(int type) @@ -118,8 +120,9 @@ void cdf_free(CDataFile *cdf) cdf_read_close(cdf); cdf_write_close(cdf); - if (cdf->layer) + if (cdf->layer) { MEM_freeN(cdf->layer); + } MEM_freeN(cdf); } @@ -138,13 +141,16 @@ static int cdf_read_header(CDataFile *cdf) header = &cdf->header; - if (!fread(header, sizeof(CDataFileHeader), 1, cdf->readf)) + if (!fread(header, sizeof(CDataFileHeader), 1, cdf->readf)) { return 0; + } - if (memcmp(header->ID, "BCDF", sizeof(header->ID)) != 0) + if (memcmp(header->ID, "BCDF", sizeof(header->ID)) != 0) { return 0; - if (header->version > CDF_VERSION) + } + if (header->version > CDF_VERSION) { return 0; + } cdf->switchendian = header->endian != cdf_endian(); header->endian = cdf_endian(); @@ -155,19 +161,22 @@ static int cdf_read_header(CDataFile *cdf) BLI_endian_switch_int32(&header->structbytes); } - if (!ELEM(header->type, CDF_TYPE_IMAGE, CDF_TYPE_MESH)) + if (!ELEM(header->type, CDF_TYPE_IMAGE, CDF_TYPE_MESH)) { return 0; + } offset += header->structbytes; header->structbytes = sizeof(CDataFileHeader); - if (fseek(f, offset, SEEK_SET) != 0) + if (fseek(f, offset, SEEK_SET) != 0) { return 0; + } if (header->type == CDF_TYPE_IMAGE) { image = &cdf->btype.image; - if (!fread(image, sizeof(CDataFileImageHeader), 1, f)) + if (!fread(image, sizeof(CDataFileImageHeader), 1, f)) { return 0; + } if (cdf->switchendian) { BLI_endian_switch_int32(&image->width); @@ -181,18 +190,21 @@ static int cdf_read_header(CDataFile *cdf) } else if (header->type == CDF_TYPE_MESH) { mesh = &cdf->btype.mesh; - if (!fread(mesh, sizeof(CDataFileMeshHeader), 1, f)) + if (!fread(mesh, sizeof(CDataFileMeshHeader), 1, f)) { return 0; + } - if (cdf->switchendian) + if (cdf->switchendian) { BLI_endian_switch_int32(&mesh->structbytes); + } offset += mesh->structbytes; mesh->structbytes = sizeof(CDataFileMeshHeader); } - if (fseek(f, offset, SEEK_SET) != 0) + if (fseek(f, offset, SEEK_SET) != 0) { return 0; + } cdf->layer = MEM_calloc_arrayN(header->totlayer, sizeof(CDataFileLayer), "CDataFileLayer"); cdf->totlayer = header->totlayer; @@ -204,8 +216,9 @@ static int cdf_read_header(CDataFile *cdf) for (a = 0; a < header->totlayer; a++) { layer = &cdf->layer[a]; - if (!fread(layer, sizeof(CDataFileLayer), 1, f)) + if (!fread(layer, sizeof(CDataFileLayer), 1, f)) { return 0; + } if (cdf->switchendian) { BLI_endian_switch_int32(&layer->type); @@ -214,14 +227,16 @@ static int cdf_read_header(CDataFile *cdf) BLI_endian_switch_int32(&layer->structbytes); } - if (layer->datatype != CDF_DATA_FLOAT) + if (layer->datatype != CDF_DATA_FLOAT) { return 0; + } offset += layer->structbytes; layer->structbytes = sizeof(CDataFileLayer); - if (fseek(f, offset, SEEK_SET) != 0) + if (fseek(f, offset, SEEK_SET) != 0) { return 0; + } } cdf->dataoffset = offset; @@ -240,25 +255,29 @@ static int cdf_write_header(CDataFile *cdf) header = &cdf->header; - if (!fwrite(header, sizeof(CDataFileHeader), 1, f)) + if (!fwrite(header, sizeof(CDataFileHeader), 1, f)) { return 0; + } if (header->type == CDF_TYPE_IMAGE) { image = &cdf->btype.image; - if (!fwrite(image, sizeof(CDataFileImageHeader), 1, f)) + if (!fwrite(image, sizeof(CDataFileImageHeader), 1, f)) { return 0; + } } else if (header->type == CDF_TYPE_MESH) { mesh = &cdf->btype.mesh; - if (!fwrite(mesh, sizeof(CDataFileMeshHeader), 1, f)) + if (!fwrite(mesh, sizeof(CDataFileMeshHeader), 1, f)) { return 0; + } } for (a = 0; a < header->totlayer; a++) { layer = &cdf->layer[a]; - if (!fwrite(layer, sizeof(CDataFileLayer), 1, f)) + if (!fwrite(layer, sizeof(CDataFileLayer), 1, f)) { return 0; + } } return 1; @@ -269,8 +288,9 @@ bool cdf_read_open(CDataFile *cdf, const char *filename) FILE *f; f = BLI_fopen(filename, "rb"); - if (!f) + if (!f) { return 0; + } cdf->readf = f; @@ -295,10 +315,12 @@ bool cdf_read_layer(CDataFile *cdf, CDataFileLayer *blay) /* seek to right location in file */ offset = cdf->dataoffset; for (a = 0; a < cdf->totlayer; a++) { - if (&cdf->layer[a] == blay) + if (&cdf->layer[a] == blay) { break; - else + } + else { offset += cdf->layer[a].datasize; + } } return (fseek(cdf->readf, offset, SEEK_SET) == 0); @@ -307,8 +329,9 @@ bool cdf_read_layer(CDataFile *cdf, CDataFileLayer *blay) bool cdf_read_data(CDataFile *cdf, unsigned int size, void *data) { /* read data */ - if (!fread(data, size, 1, cdf->readf)) + if (!fread(data, size, 1, cdf->readf)) { return 0; + } /* switch endian if necessary */ if (cdf->switchendian) { @@ -334,8 +357,9 @@ bool cdf_write_open(CDataFile *cdf, const char *filename) FILE *f; f = BLI_fopen(filename, "wb"); - if (!f) + if (!f) { return 0; + } cdf->writef = f; @@ -379,8 +403,9 @@ bool cdf_write_layer(CDataFile *UNUSED(cdf), CDataFileLayer *UNUSED(blay)) bool cdf_write_data(CDataFile *cdf, unsigned int size, void *data) { /* write data */ - if (!fwrite(data, size, 1, cdf->writef)) + if (!fwrite(data, size, 1, cdf->writef)) { return 0; + } return 1; } @@ -408,8 +433,9 @@ CDataFileLayer *cdf_layer_find(CDataFile *cdf, int type, const char *name) for (a = 0; a < cdf->totlayer; a++) { layer = &cdf->layer[a]; - if (layer->type == type && STREQ(layer->name, name)) + if (layer->type == type && STREQ(layer->name, name)) { return layer; + } } return NULL; diff --git a/source/blender/blenkernel/intern/data_transfer.c b/source/blender/blenkernel/intern/data_transfer.c index 41e8cfe188d..5d9ba1bcdc7 100644 --- a/source/blender/blenkernel/intern/data_transfer.c +++ b/source/blender/blenkernel/intern/data_transfer.c @@ -90,7 +90,8 @@ void BKE_object_data_transfer_dttypes_to_cdmask(const int dtdata_types, } } -/* Check what can do each layer type (if it is actually handled by transferdata, if it supports advanced mixing... */ +/* Check what can do each layer type + * (if it is actually handled by transferdata, if it supports advanced mixing... */ bool BKE_object_data_transfer_get_dttypes_capacity(const int dtdata_types, bool *r_advanced_mixing, bool *r_threshold) @@ -340,6 +341,10 @@ static void data_transfer_dtdata_type_postprocess(Object *UNUSED(ob_src), const bool changed) { if (dtdata_type == DT_TYPE_LNOR) { + if (!changed) { + return; + } + /* Bake edited destination loop normals into custom normals again. */ MVert *verts_dst = me_dst->mvert; const int num_verts_dst = me_dst->totvert; @@ -358,10 +363,6 @@ static void data_transfer_dtdata_type_postprocess(Object *UNUSED(ob_src), BLI_assert(poly_nors_dst); - if (!changed) { - return; - } - if (!custom_nors_dst) { custom_nors_dst = CustomData_add_layer( ldata_dst, CD_CUSTOMLOOPNORMAL, CD_CALLOC, NULL, num_loops_dst); @@ -458,7 +459,8 @@ static void data_transfer_interp_char(const CustomDataTransferLayerMap *laymap, *data_dst = (char)(val_src * 255.0f); } -/* Helpers to match sources and destinations data layers (also handles 'conversions' in CD_FAKE cases). */ +/* Helpers to match sources and destinations data layers + * (also handles 'conversions' in CD_FAKE cases). */ void data_transfer_layersmapping_add_item(ListBase *r_map, const int cddata_type, @@ -537,12 +539,13 @@ static void data_transfer_layersmapping_add_item_cd(ListBase *r_map, interp_data); } -/* Note: All those layer mapping handlers return false *only* if they were given invalid parameters. - * This means that even if they do nothing, they will return true if all given parameters were OK. - * Also, r_map may be NULL, in which case they will 'only' create/delete destination layers according - * to given parameters. +/** + * \note + * All those layer mapping handlers return false *only* if they were given invalid parameters. + * This means that even if they do nothing, they will return true if all given parameters were OK. + * Also, r_map may be NULL, in which case they will 'only' create/delete destination layers + * according to given parameters. */ - static bool data_transfer_layersmapping_cdlayers_multisrc_to_dst(ListBase *r_map, const int cddata_type, const int mix_mode, @@ -581,8 +584,9 @@ static bool data_transfer_layersmapping_cdlayers_multisrc_to_dst(ListBase *r_map idx_dst = tot_dst; /* Find last source actually used! */ - while (idx_src-- && !use_layers_src[idx_src]) + while (idx_src-- && !use_layers_src[idx_src]) { ; + } idx_src++; if (idx_dst < idx_src) { @@ -608,7 +612,8 @@ static bool data_transfer_layersmapping_cdlayers_multisrc_to_dst(ListBase *r_map continue; } data_src = CustomData_get_layer_n(cd_src, cddata_type, idx_src); - /* If dest is a evaluated mesh (fro; ;odifier), we do not want to overwrite cdlayers of orig mesh! */ + /* If dest is a evaluated mesh (from modifier), + * we do not want to overwrite cdlayers of orig mesh! */ if (use_dupref_dst) { data_dst = CustomData_duplicate_referenced_layer_n( cd_dst, cddata_type, idx_src, num_elem_dst); @@ -653,7 +658,8 @@ static bool data_transfer_layersmapping_cdlayers_multisrc_to_dst(ListBase *r_map idx_dst = CustomData_get_named_layer(cd_dst, cddata_type, name); } else { - /* If we are not allowed to create missing dst data layers, just skip matching src one. */ + /* If we are not allowed to create missing dst data layers, + * just skip matching src one. */ continue; } } @@ -661,7 +667,8 @@ static bool data_transfer_layersmapping_cdlayers_multisrc_to_dst(ListBase *r_map data_dst_to_delete[idx_dst] = false; } if (r_map) { - /* If dest is a evaluated mesh (from modifier), we do not want to overwrite cdlayers of orig mesh! */ + /* If dest is a evaluated mesh (from modifier), + * we do not want to overwrite cdlayers of orig mesh! */ if (use_dupref_dst) { data_dst = CustomData_duplicate_referenced_layer_n( cd_dst, cddata_type, idx_dst, num_elem_dst); @@ -682,9 +689,10 @@ static bool data_transfer_layersmapping_cdlayers_multisrc_to_dst(ListBase *r_map } if (data_dst_to_delete) { - /* Note: This won't affect newly created layers, if any, since tot_dst has not been updated! - * Also, looping backward ensures us we do not suffer from index shifting when deleting a layer. - */ + /* Note: + * This won't affect newly created layers, if any, since tot_dst has not been updated! + * Also, looping backward ensures us we do not suffer + * from index shifting when deleting a layer. */ for (idx_dst = tot_dst; idx_dst--;) { if (data_dst_to_delete[idx_dst]) { CustomData_free_layer(cd_dst, cddata_type, num_elem_dst, idx_dst); @@ -736,7 +744,8 @@ static bool data_transfer_layersmapping_cdlayers(ListBase *r_map, data_dst = CustomData_add_layer(cd_dst, cddata_type, CD_CALLOC, NULL, num_elem_dst); } else if (use_dupref_dst && r_map) { - /* If dest is a evaluated mesh (from modifier), we do not want to overwrite cdlayers of orig mesh! */ + /* If dest is a evaluated mesh (from modifier), + * we do not want to overwrite cdlayers of orig mesh! */ data_dst = CustomData_duplicate_referenced_layer(cd_dst, cddata_type, num_elem_dst); } @@ -770,7 +779,8 @@ static bool data_transfer_layersmapping_cdlayers(ListBase *r_map, if (tolayers >= 0) { /* Real-layer index */ idx_dst = tolayers; - /* If dest is a evaluated mesh (from modifier), we do not want to overwrite cdlayers of orig mesh! */ + /* If dest is a evaluated mesh (from modifier), + * we do not want to overwrite cdlayers of orig mesh! */ if (use_dupref_dst && r_map) { data_dst = CustomData_duplicate_referenced_layer_n( cd_dst, cddata_type, idx_dst, num_elem_dst); @@ -787,7 +797,8 @@ static bool data_transfer_layersmapping_cdlayers(ListBase *r_map, data_dst = CustomData_add_layer(cd_dst, cddata_type, CD_CALLOC, NULL, num_elem_dst); } else { - /* If dest is a evaluated mesh (from modifier), we do not want to overwrite cdlayers of orig mesh! */ + /* If dest is a evaluated mesh (from modifier), + * we do not want to overwrite cdlayers of orig mesh! */ if (use_dupref_dst && r_map) { data_dst = CustomData_duplicate_referenced_layer_n( cd_dst, cddata_type, idx_dst, num_elem_dst); @@ -809,7 +820,8 @@ static bool data_transfer_layersmapping_cdlayers(ListBase *r_map, CustomData_add_layer(cd_dst, cddata_type, CD_CALLOC, NULL, num_elem_dst); } } - /* If dest is a evaluated mesh (from modifier), we do not want to overwrite cdlayers of orig mesh! */ + /* If dest is a evaluated mesh (from modifier), + * we do not want to overwrite cdlayers of orig mesh! */ if (use_dupref_dst && r_map) { data_dst = CustomData_duplicate_referenced_layer_n( cd_dst, cddata_type, idx_dst, num_elem_dst); @@ -827,7 +839,8 @@ static bool data_transfer_layersmapping_cdlayers(ListBase *r_map, CustomData_add_layer_named(cd_dst, cddata_type, CD_CALLOC, NULL, num_elem_dst, name); idx_dst = CustomData_get_named_layer(cd_dst, cddata_type, name); } - /* If dest is a evaluated mesh (from modifier), we do not want to overwrite cdlayers of orig mesh! */ + /* If dest is a evaluated mesh (from modifier), + * we do not want to overwrite cdlayers of orig mesh! */ if (use_dupref_dst && r_map) { data_dst = CustomData_duplicate_referenced_layer_n( cd_dst, cddata_type, idx_dst, num_elem_dst); @@ -1001,7 +1014,8 @@ static bool data_transfer_layersmapping_generate(ListBase *r_map, return ret; } else if (cddata_type == CD_FAKE_SHAPEKEY) { - /* TODO: leaving shapekeys aside for now, quite specific case, since we can't access them from MVert :/ */ + /* TODO: leaving shapekeys aside for now, quite specific case, + * since we can't access them from MVert :/ */ return false; } } @@ -1126,7 +1140,8 @@ static bool data_transfer_layersmapping_generate(ListBase *r_map, cddata_type = CD_MLOOPUV; } else if (cddata_type == CD_FAKE_LNOR) { - /* Preprocess should have generated it, Postprocess will convert it back to CD_CUSTOMLOOPNORMAL. */ + /* Pre-process should have generated it, + * Post-process will convert it back to CD_CUSTOMLOOPNORMAL. */ cddata_type = CD_NORMAL; interp_data = space_transform; interp = customdata_data_transfer_interp_normal_normals; @@ -1223,8 +1238,8 @@ static bool data_transfer_layersmapping_generate(ListBase *r_map, /** * Transfer data *layout* of selected types from source to destination object. * By default, it only creates new data layers if needed on \a ob_dst. - * If \a use_delete is true, it will also delete data layers on \a ob_dst that do not match those from \a ob_src, - * to get (as much as possible) exact copy of source data layout. + * If \a use_delete is true, it will also delete data layers on \a ob_dst that do not match those + * from \a ob_src, to get (as much as possible) exact copy of source data layout. */ void BKE_object_data_transfer_layout(struct Depsgraph *depsgraph, Scene *scene, diff --git a/source/blender/blenkernel/intern/deform.c b/source/blender/blenkernel/intern/deform.c index 7769f3aff86..e83e9560b02 100644 --- a/source/blender/blenkernel/intern/deform.c +++ b/source/blender/blenkernel/intern/deform.c @@ -142,17 +142,21 @@ void defvert_mirror_subset(MDeformVert *dvert_dst, void defvert_copy(MDeformVert *dvert_dst, const MDeformVert *dvert_src) { if (dvert_dst->totweight == dvert_src->totweight) { - if (dvert_src->totweight) + if (dvert_src->totweight) { memcpy(dvert_dst->dw, dvert_src->dw, dvert_src->totweight * sizeof(MDeformWeight)); + } } else { - if (dvert_dst->dw) + if (dvert_dst->dw) { MEM_freeN(dvert_dst->dw); + } - if (dvert_src->totweight) + if (dvert_src->totweight) { dvert_dst->dw = MEM_dupallocN(dvert_src->dw); - else + } + else { dvert_dst->dw = NULL; + } dvert_dst->totweight = dvert_src->totweight; } @@ -198,10 +202,12 @@ void defvert_sync(MDeformVert *dvert_dst, const MDeformVert *dvert_src, const bo MDeformWeight *dw_src; for (i = 0, dw_src = dvert_src->dw; i < dvert_src->totweight; i++, dw_src++) { MDeformWeight *dw_dst; - if (use_verify) + if (use_verify) { dw_dst = defvert_verify_index(dvert_dst, dw_src->def_nr); - else + } + else { dw_dst = defvert_find_index(dvert_dst, dw_src->def_nr); + } if (dw_dst) { dw_dst->weight = dw_src->weight; @@ -225,10 +231,12 @@ void defvert_sync_mapped(MDeformVert *dvert_dst, for (i = 0, dw_src = dvert_src->dw; i < dvert_src->totweight; i++, dw_src++) { if (dw_src->def_nr < flip_map_len) { MDeformWeight *dw_dst; - if (use_verify) + if (use_verify) { dw_dst = defvert_verify_index(dvert_dst, flip_map[dw_src->def_nr]); - else + } + else { dw_dst = defvert_find_index(dvert_dst, flip_map[dw_src->def_nr]); + } if (dw_dst) { dw_dst->weight = dw_src->weight; @@ -514,8 +522,9 @@ int *defgroup_flip_map(Object *ob, int *flip_map_len, const bool use_default) if (map[i] == -1) { /* may be calculated previously */ /* in case no valid value is found, use this */ - if (use_default) + if (use_default) { map[i] = i; + } BLI_string_flip_side_name(name_flip, dg->name, false, sizeof(name_flip)); @@ -637,11 +646,11 @@ float defvert_array_find_weight_safe(const struct MDeformVert *dvert, const int index, const int defgroup) { - /* Invalid defgroup index means the vgroup selected is invalid, does not exist, in that case it is OK to return 1.0 + /* Invalid defgroup index means the vgroup selected is invalid, + * does not exist, in that case it is OK to return 1.0 * (i.e. maximum weight, as if no vgroup was selected). * But in case of valid defgroup and NULL dvert data pointer, it means that vgroup **is** valid, - * and just totally empty, so we shall return '0.0' value then! - */ + * and just totally empty, so we shall return '0.0' value then! */ if (defgroup == -1) { return 1.0f; } @@ -687,8 +696,9 @@ MDeformWeight *defvert_verify_index(MDeformVert *dvert, const int defgroup) } dw_new = defvert_find_index(dvert, defgroup); - if (dw_new) + if (dw_new) { return dw_new; + } dw_new = MEM_mallocN(sizeof(MDeformWeight) * (dvert->totweight + 1), "deformWeight"); if (dvert->dw) { @@ -864,8 +874,9 @@ void BKE_defvert_array_copy(MDeformVert *dst, const MDeformVert *src, int copyco /* Assumes dst is already set up */ int i; - if (!src || !dst) + if (!src || !dst) { return; + } memcpy(dst, src, copycount * sizeof(MDeformVert)); @@ -884,13 +895,15 @@ void BKE_defvert_array_free_elems(MDeformVert *dvert, int totvert) * vert data */ int i; - if (!dvert) + if (!dvert) { return; + } /* Free any special data from the verts */ for (i = 0; i < totvert; i++) { - if (dvert[i].dw) + if (dvert[i].dw) { MEM_freeN(dvert[i].dw); + } } } @@ -899,8 +912,9 @@ void BKE_defvert_array_free(MDeformVert *dvert, int totvert) /* Instead of freeing the verts directly, * call this function to delete any special * vert data */ - if (!dvert) + if (!dvert) { return; + } /* Free any special data from the verts */ BKE_defvert_array_free_elems(dvert, totvert); @@ -1109,8 +1123,9 @@ static bool data_transfer_layersmapping_vgroups_multisrc_to_dst(ListBase *r_map, /* Find last source actually used! */ idx_src = num_layers_src; - while (idx_src-- && !use_layers_src[idx_src]) + while (idx_src-- && !use_layers_src[idx_src]) { ; + } idx_src++; if (idx_dst < idx_src) { @@ -1192,7 +1207,7 @@ static bool data_transfer_layersmapping_vgroups_multisrc_to_dst(ListBase *r_map, } if (r_map) { /* At this stage, we **need** a valid CD_MDEFORMVERT layer on dest! - * use_create is not relevant in this case */ + * use_create is not relevant in this case */ if (!data_dst) { data_dst = CustomData_add_layer(cd_dst, CD_MDEFORMVERT, CD_CALLOC, NULL, num_elem_dst); } @@ -1243,12 +1258,13 @@ bool data_transfer_layersmapping_vgroups(ListBase *r_map, const size_t elem_size = sizeof(*((MDeformVert *)NULL)); - /* Note: VGroups are a bit hairy, since their layout is defined on object level (ob->defbase), while their actual - * data is a (mesh) CD layer. - * This implies we may have to handle data layout itself while having NULL data itself, - * and even have to support NULL data_src in transfer data code (we always create a data_dst, though). + /* Note: + * VGroups are a bit hairy, since their layout is defined on object level (ob->defbase), + * while their actual data is a (mesh) CD layer. + * This implies we may have to handle data layout itself while having NULL data itself, + * and even have to support NULL data_src in transfer data code + * (we always create a data_dst, though). */ - if (BLI_listbase_is_empty(&ob_src->defbase)) { if (use_delete) { BKE_object_defgroup_remove_all(ob_dst); diff --git a/source/blender/blenkernel/intern/displist.c b/source/blender/blenkernel/intern/displist.c index 2794a6e36e4..c228595b6e8 100644 --- a/source/blender/blenkernel/intern/displist.c +++ b/source/blender/blenkernel/intern/displist.c @@ -64,14 +64,18 @@ static void boundbox_displist_object(Object *ob); void BKE_displist_elem_free(DispList *dl) { if (dl) { - if (dl->verts) + if (dl->verts) { MEM_freeN(dl->verts); - if (dl->nors) + } + if (dl->nors) { MEM_freeN(dl->nors); - if (dl->index) + } + if (dl->index) { MEM_freeN(dl->index); - if (dl->bevel_split) + } + if (dl->bevel_split) { MEM_freeN(dl->bevel_split); + } MEM_freeN(dl); } } @@ -91,8 +95,9 @@ DispList *BKE_displist_find_or_create(ListBase *lb, int type) dl = lb->first; while (dl) { - if (dl->type == type) + if (dl->type == type) { return dl; + } dl = dl->next; } @@ -109,8 +114,9 @@ DispList *BKE_displist_find(ListBase *lb, int type) dl = lb->first; while (dl) { - if (dl->type == type) + if (dl->type == type) { return dl; + } dl = dl->next; } @@ -184,8 +190,9 @@ void BKE_displist_normals_add(ListBase *lb) for (a = 0; a < dl->parts; a++) { - if (BKE_displist_surfindex_get(dl, a, &b, &p1, &p2, &p3, &p4) == 0) + if (BKE_displist_surfindex_get(dl, a, &b, &p1, &p2, &p3, &p4) == 0) { break; + } v1 = vdata + 3 * p1; n1 = ndata + 3 * p1; @@ -322,10 +329,12 @@ static void curve_to_displist(Curve *cu, nu = nubase->first; while (nu) { if (nu->hide == 0 || editmode == false) { - if (use_render_resolution && cu->resolu_ren != 0) + if (use_render_resolution && cu->resolu_ren != 0) { resolu = cu->resolu_ren; - else + } + else { resolu = nu->resolu; + } if (!BKE_nurb_check_valid_u(nu)) { /* pass */ @@ -334,22 +343,27 @@ static void curve_to_displist(Curve *cu, /* count */ len = 0; a = nu->pntsu - 1; - if (nu->flagu & CU_NURB_CYCLIC) + if (nu->flagu & CU_NURB_CYCLIC) { a++; + } prevbezt = nu->bezt; bezt = prevbezt + 1; while (a--) { - if (a == 0 && (nu->flagu & CU_NURB_CYCLIC)) + if (a == 0 && (nu->flagu & CU_NURB_CYCLIC)) { bezt = nu->bezt; + } - if (prevbezt->h2 == HD_VECT && bezt->h1 == HD_VECT) + if (prevbezt->h2 == HD_VECT && bezt->h1 == HD_VECT) { len++; - else + } + else { len += resolu; + } - if (a == 0 && (nu->flagu & CU_NURB_CYCLIC) == 0) + if (a == 0 && (nu->flagu & CU_NURB_CYCLIC) == 0) { len++; + } prevbezt = bezt; bezt++; @@ -380,8 +394,9 @@ static void curve_to_displist(Curve *cu, bezt = prevbezt + 1; while (a--) { - if (a == 0 && dl->type == DL_POLY) + if (a == 0 && dl->type == DL_POLY) { bezt = nu->bezt; + } if (prevbezt->h2 == HD_VECT && bezt->h1 == HD_VECT) { copy_v3_v3(data, prevbezt->vec[1]); @@ -423,10 +438,12 @@ static void curve_to_displist(Curve *cu, dl->charidx = nu->charidx; data = dl->verts; - if (nu->flagu & CU_NURB_CYCLIC) + if (nu->flagu & CU_NURB_CYCLIC) { dl->type = DL_POLY; - else + } + else { dl->type = DL_SEGM; + } BKE_nurb_makeCurve(nu, data, NULL, NULL, NULL, resolu, 3 * sizeof(float)); } else if (nu->type == CU_POLY) { @@ -481,10 +498,12 @@ void BKE_displist_fill(ListBase *dispbase, const int scanfill_flag = BLI_SCANFILL_CALC_REMOVE_DOUBLES | BLI_SCANFILL_CALC_POLYS | BLI_SCANFILL_CALC_HOLES; - if (dispbase == NULL) + if (dispbase == NULL) { return; - if (BLI_listbase_is_empty(dispbase)) + } + if (BLI_listbase_is_empty(dispbase)) { return; + } sf_arena = BLI_memarena_new(BLI_SCANFILL_ARENA_SIZE, __func__); @@ -499,8 +518,9 @@ void BKE_displist_fill(ListBase *dispbase, dl = dispbase->first; while (dl) { if (dl->type == DL_POLY) { - if (charidx < dl->charidx) + if (charidx < dl->charidx) { cont = 1; + } else if (charidx == dl->charidx) { /* character with needed index */ if (colnr == dl->col) { @@ -517,8 +537,9 @@ void BKE_displist_fill(ListBase *dispbase, sf_vert = BLI_scanfill_vert_add(&sf_ctx, f1); totvert++; - if (sf_vert_last == NULL) + if (sf_vert_last == NULL) { sf_vert_new = sf_vert; + } else { BLI_scanfill_edge_add(&sf_ctx, sf_vert_last, sf_vert); } @@ -574,8 +595,9 @@ void BKE_displist_fill(ListBase *dispbase, index[1] = sf_tri->v2->tmp.i; index[2] = sf_tri->v3->tmp.i; - if (flipnormal) + if (flipnormal) { SWAP(int, index[0], index[2]); + } index += 3; } @@ -674,8 +696,9 @@ static void bevels_to_filledpoly(Curve *cu, ListBase *dispbase) static void curve_to_filledpoly(Curve *cu, ListBase *UNUSED(nurb), ListBase *dispbase) { - if (!CU_DO_2DFILL(cu)) + if (!CU_DO_2DFILL(cu)) { return; + } if (dispbase->first && ((DispList *)dispbase->first)->type == DL_SURF) { bevels_to_filledpoly(cu, dispbase); @@ -695,8 +718,9 @@ static float displist_calc_taper(Depsgraph *depsgraph, Scene *scene, Object *tap { DispList *dl; - if (taperobj == NULL || taperobj->type != OB_CURVE) + if (taperobj == NULL || taperobj->type != OB_CURVE) { return 1.0; + } dl = taperobj->runtime.curve_cache ? taperobj->runtime.curve_cache->disp.first : NULL; if (dl == NULL) { @@ -718,8 +742,9 @@ static float displist_calc_taper(Depsgraph *depsgraph, Scene *scene, Object *tap if (a > 0) { float fac1 = (fp[-3] - minx) / dx; float fac2 = (fp[0] - minx) / dx; - if (fac1 != fac2) + if (fac1 != fac2) { return fp[1] * (fac1 - fac) / (fac1 - fac2) + fp[-2] * (fac - fac2) / (fac1 - fac2); + } } return fp[1]; } @@ -741,8 +766,9 @@ float BKE_displist_calc_taper( void BKE_displist_make_mball(Depsgraph *depsgraph, Scene *scene, Object *ob) { - if (!ob || ob->type != OB_MBALL) + if (!ob || ob->type != OB_MBALL) { return; + } if (ob == BKE_mball_basis_find(scene, ob)) { if (ob->runtime.curve_cache) { @@ -783,22 +809,27 @@ static ModifierData *curve_get_tessellate_point(Scene *scene, ModifierData *pretessellatePoint; int required_mode; - if (use_render_resolution) + if (use_render_resolution) { required_mode = eModifierMode_Render; - else + } + else { required_mode = eModifierMode_Realtime; + } - if (editmode) + if (editmode) { required_mode |= eModifierMode_Editmode; + } pretessellatePoint = NULL; for (; md; md = md->next) { const ModifierTypeInfo *mti = modifierType_getInfo(md->type); - if (!modifier_isEnabled(scene, md, required_mode)) + if (!modifier_isEnabled(scene, md, required_mode)) { continue; - if (mti->type == eModifierTypeType_Constructive) + } + if (mti->type == eModifierTypeType_Constructive) { return pretessellatePoint; + } if (ELEM(md->type, eModifierType_Hook, eModifierType_Softbody, eModifierType_MeshDeform)) { pretessellatePoint = md; @@ -837,21 +868,24 @@ static void curve_calc_modifiers_pre(Depsgraph *depsgraph, modifiers_clearErrors(ob); - if (editmode) + if (editmode) { app_flag |= MOD_APPLY_USECACHE; + } if (use_render_resolution) { app_flag |= MOD_APPLY_RENDER; required_mode = eModifierMode_Render; } - else + else { required_mode = eModifierMode_Realtime; + } const ModifierEvalContext mectx = {depsgraph, ob, app_flag}; pretessellatePoint = curve_get_tessellate_point(scene, ob, use_render_resolution, editmode); - if (editmode) + if (editmode) { required_mode |= eModifierMode_Editmode; + } if (!editmode) { keyVerts = BKE_key_evaluate_object(ob, &numElems); @@ -872,10 +906,12 @@ static void curve_calc_modifiers_pre(Depsgraph *depsgraph, for (; md; md = md->next) { const ModifierTypeInfo *mti = modifierType_getInfo(md->type); - if (!modifier_isEnabled(scene, md, required_mode)) + if (!modifier_isEnabled(scene, md, required_mode)) { continue; - if (mti->type != eModifierTypeType_OnlyDeform) + } + if (mti->type != eModifierTypeType_OnlyDeform) { continue; + } if (!deformedVerts) { deformedVerts = BKE_curve_nurbs_vertexCos_get(nurb, &numVerts); @@ -883,8 +919,9 @@ static void curve_calc_modifiers_pre(Depsgraph *depsgraph, mti->deformVerts(md, &mectx, NULL, deformedVerts, numVerts); - if (md == pretessellatePoint) + if (md == pretessellatePoint) { break; + } } } @@ -892,11 +929,13 @@ static void curve_calc_modifiers_pre(Depsgraph *depsgraph, BK_curve_nurbs_vertexCos_apply(nurb, deformedVerts); MEM_freeN(deformedVerts); } - if (keyVerts) /* these are not passed through modifier stack */ + if (keyVerts) { /* these are not passed through modifier stack */ BKE_curve_nurbs_keyVertexTilts_apply(nurb, keyVerts); + } - if (keyVerts) + if (keyVerts) { MEM_freeN(keyVerts); + } } static float (*displist_get_allverts(ListBase *dispbase, int *totvert))[3] @@ -906,8 +945,9 @@ static float (*displist_get_allverts(ListBase *dispbase, int *totvert))[3] *totvert = 0; - for (dl = dispbase->first; dl; dl = dl->next) + for (dl = dispbase->first; dl; dl = dl->next) { *totvert += (dl->type == DL_INDEX3) ? dl->nr : dl->parts * dl->nr; + } allverts = MEM_mallocN((*totvert) * sizeof(float) * 3, "displist_get_allverts allverts"); fp = (float *)allverts; @@ -957,8 +997,9 @@ static void curve_calc_modifiers_post(Depsgraph *depsgraph, app_flag |= MOD_APPLY_RENDER; required_mode = eModifierMode_Render; } - else + else { required_mode = eModifierMode_Realtime; + } const ModifierEvalContext mectx_deform = { depsgraph, ob, editmode ? app_flag | MOD_APPLY_USECACHE : app_flag}; @@ -967,8 +1008,9 @@ static void curve_calc_modifiers_post(Depsgraph *depsgraph, pretessellatePoint = curve_get_tessellate_point(scene, ob, use_render_resolution, editmode); - if (editmode) + if (editmode) { required_mode |= eModifierMode_Editmode; + } if (pretessellatePoint) { md = pretessellatePoint->next; @@ -981,11 +1023,15 @@ static void curve_calc_modifiers_post(Depsgraph *depsgraph, for (; md; md = md->next) { const ModifierTypeInfo *mti = modifierType_getInfo(md->type); - if (!modifier_isEnabled(scene, md, required_mode)) + if (!modifier_isEnabled(scene, md, required_mode)) { continue; + } /* If we need normals, no choice, have to convert to mesh now. */ - if (mti->dependsOnNormals != NULL && mti->dependsOnNormals(md) && modified == NULL) { + bool need_normal = mti->dependsOnNormals != NULL && mti->dependsOnNormals(md); + /* XXX 2.8 : now that batch cache is stored inside the ob->data + * we need to create a Mesh for each curve that uses modifiers. */ + if (modified == NULL /* && need_normal */) { if (vertCos != NULL) { displist_apply_allverts(dispbase, vertCos); } @@ -1003,7 +1049,7 @@ static void curve_calc_modifiers_post(Depsgraph *depsgraph, if (!vertCos) { vertCos = BKE_mesh_vertexCos_get(modified, &totvert); } - if (mti->dependsOnNormals != NULL && mti->dependsOnNormals(md)) { + if (need_normal) { BKE_mesh_ensure_normals(modified); } mti->deformVerts(md, &mectx_deform, modified, vertCos, totvert); @@ -1052,7 +1098,7 @@ static void curve_calc_modifiers_post(Depsgraph *depsgraph, vertCos = NULL; } - if (mti->dependsOnNormals != NULL && mti->dependsOnNormals(md)) { + if (need_normal) { BKE_mesh_ensure_normals(modified); } mesh_applied = mti->applyModifier(md, &mectx_apply, modified); @@ -1060,8 +1106,9 @@ static void curve_calc_modifiers_post(Depsgraph *depsgraph, if (mesh_applied) { /* Modifier returned a new derived mesh */ - if (modified && modified != mesh_applied) /* Modifier */ + if (modified && modified != mesh_applied) { /* Modifier */ BKE_id_free(NULL, modified); + } modified = mesh_applied; } } @@ -1132,8 +1179,9 @@ static void displist_surf_indices(DispList *dl) for (a = 0; a < dl->parts; a++) { - if (BKE_displist_surfindex_get(dl, a, &b, &p1, &p2, &p3, &p4) == 0) + if (BKE_displist_surfindex_get(dl, a, &b, &p1, &p2, &p3, &p4) == 0) { break; + } for (; b < dl->nr; b++, index += 4) { index[0] = p1; @@ -1177,10 +1225,12 @@ static void add_orco_dm(Object *ob, DerivedMesh *dm, DerivedMesh *orcodm) orco = MEM_callocN(sizeof(float) * 3 * totvert, "dm orco"); - if (orcodm->getNumVerts(orcodm) == totvert) + if (orcodm->getNumVerts(orcodm) == totvert) { orcodm->getVertCos(orcodm, orco); - else + } + else { dm->getVertCos(dm, orco); + } for (a = 0; a < totvert; a++) { float *co = orco[a]; @@ -1193,8 +1243,9 @@ static void add_orco_dm(Object *ob, DerivedMesh *dm, DerivedMesh *orcodm) memcpy(layerorco, orco, sizeof(float) * totvert); MEM_freeN(orco); } - else + else { DM_add_vert_layer(dm, CD_ORCO, CD_ASSIGN, orco); + } } #endif @@ -1223,15 +1274,17 @@ static void curve_calc_orcodm(Depsgraph *depsgraph, app_flag |= MOD_APPLY_RENDER; required_mode = eModifierMode_Render; } - else + else { required_mode = eModifierMode_Realtime; + } const ModifierEvalContext mectx = {depsgraph, ob, app_flag}; pretessellatePoint = curve_get_tessellate_point(scene, ob, use_render_resolution, editmode); - if (editmode) + if (editmode) { required_mode |= eModifierMode_Editmode; + } if (pretessellatePoint) { md = pretessellatePoint->next; @@ -1251,10 +1304,12 @@ static void curve_calc_orcodm(Depsgraph *depsgraph, md->scene = scene; - if (!modifier_isEnabled(scene, md, required_mode)) + if (!modifier_isEnabled(scene, md, required_mode)) { continue; - if (mti->type != eModifierTypeType_Constructive) + } + if (mti->type != eModifierTypeType_Constructive) { continue; + } ndm = modwrap_applyModifier(md, &mectx, orcodm); @@ -1297,18 +1352,21 @@ void BKE_displist_make_surf(Depsgraph *depsgraph, BKE_nurbList_duplicate(&nubase, &cu->nurb); } - if (!for_orco) + if (!for_orco) { curve_calc_modifiers_pre(depsgraph, scene, ob, &nubase, for_render, use_render_resolution); + } for (nu = nubase.first; nu; nu = nu->next) { if ((for_render || nu->hide == 0) && BKE_nurb_check_valid_uv(nu)) { int resolu = nu->resolu, resolv = nu->resolv; if (use_render_resolution) { - if (cu->resolu_ren) + if (cu->resolu_ren) { resolu = cu->resolu_ren; - if (cu->resolv_ren) + } + if (cu->resolv_ren) { resolv = cu->resolv_ren; + } } if (nu->pntsv == 1) { @@ -1328,10 +1386,12 @@ void BKE_displist_make_surf(Depsgraph *depsgraph, dl->rt = nu->flag & ~CU_2D; data = dl->verts; - if (nu->flagu & CU_NURB_CYCLIC) + if (nu->flagu & CU_NURB_CYCLIC) { dl->type = DL_POLY; - else + } + else { dl->type = DL_SEGM; + } BKE_nurb_makeCurve(nu, data, NULL, NULL, NULL, resolu, 3 * sizeof(float)); } @@ -1354,10 +1414,12 @@ void BKE_displist_make_surf(Depsgraph *depsgraph, dl->parts = (nu->pntsu * resolu); /* in reverse, because makeNurbfaces works that way */ dl->nr = (nu->pntsv * resolv); - if (nu->flagv & CU_NURB_CYCLIC) + if (nu->flagv & CU_NURB_CYCLIC) { dl->flag |= DL_CYCL_U; /* reverse too! */ - if (nu->flagu & CU_NURB_CYCLIC) + } + if (nu->flagu & CU_NURB_CYCLIC) { dl->flag |= DL_CYCL_V; + } BKE_nurb_makeFaces(nu, data, 0, resolu, resolv); @@ -1610,8 +1672,9 @@ static void do_makeDispListCurveTypes(Depsgraph *depsgraph, Curve *cu = ob->data; /* we do allow duplis... this is only displist on curve level */ - if (!ELEM(ob->type, OB_SURF, OB_CURVE, OB_FONT)) + if (!ELEM(ob->type, OB_SURF, OB_CURVE, OB_FONT)) { return; + } if (ob->type == OB_SURF) { BKE_displist_make_surf( @@ -1628,8 +1691,9 @@ static void do_makeDispListCurveTypes(Depsgraph *depsgraph, * was needed before and only not needed for orco calculation. */ if (!for_orco) { - if (ob->runtime.curve_cache->path) + if (ob->runtime.curve_cache->path) { free_path(ob->runtime.curve_cache->path); + } ob->runtime.curve_cache->path = NULL; } @@ -1640,8 +1704,9 @@ static void do_makeDispListCurveTypes(Depsgraph *depsgraph, BKE_nurbList_duplicate(&nubase, BKE_curve_nurbs_get(cu)); } - if (!for_orco) + if (!for_orco) { curve_calc_modifiers_pre(depsgraph, scene, ob, &nubase, for_render, use_render_resolution); + } BKE_curve_bevelList_make(ob, &nubase, use_render_resolution); @@ -1672,13 +1737,16 @@ static void do_makeDispListCurveTypes(Depsgraph *depsgraph, dl->verts = MEM_mallocN(sizeof(float[3]) * bl->nr, "dlverts"); BLI_addtail(dispbase, dl); - if (bl->poly != -1) + if (bl->poly != -1) { dl->type = DL_POLY; - else + } + else { dl->type = DL_SEGM; + } - if (dl->type == DL_SEGM) + if (dl->type == DL_SEGM) { dl->flag = (DL_FRONT_CURVE | DL_BACK_CURVE); + } dl->parts = 1; dl->nr = bl->nr; @@ -1767,21 +1835,26 @@ static void do_makeDispListCurveTypes(Depsgraph *depsgraph, if (cu->flag & CU_MAP_TAPER) { len = (steps - 3) + firstblend + lastblend; - if (a == 0) + if (a == 0) { taper_fac = 0.0f; - else if (a == steps - 1) + } + else if (a == steps - 1) { taper_fac = 1.0f; - else + } + else { taper_fac = ((float)a - (1.0f - firstblend)) / len; + } } else { len = bl->nr - 1; taper_fac = (float)i / len; - if (a == 0) + if (a == 0) { taper_fac += (1.0f - firstblend) / len; - else if (a == steps - 1) + } + else if (a == steps - 1) { taper_fac -= (1.0f - lastblend) / len; + } } fac = displist_calc_taper(depsgraph, scene, cu->taperobj, taper_fac); @@ -1867,8 +1940,9 @@ void BKE_displist_make_curveTypes(Depsgraph *depsgraph, /* The same check for duplis as in do_makeDispListCurveTypes. * Happens when curve used for constraint/bevel was converted to mesh. * check there is still needed for render displist and orco displists. */ - if (!ELEM(ob->type, OB_SURF, OB_CURVE, OB_FONT)) + if (!ELEM(ob->type, OB_SURF, OB_CURVE, OB_FONT)) { return; + } BKE_object_free_derived_caches(ob); @@ -1957,8 +2031,9 @@ static void boundbox_displist_object(Object *ob) */ /* object's BB is calculated from final displist */ - if (ob->runtime.bb == NULL) + if (ob->runtime.bb == NULL) { ob->runtime.bb = MEM_callocN(sizeof(BoundBox), "boundbox"); + } if (ob->runtime.mesh_eval) { BKE_object_boundbox_calc_from_mesh(ob, ob->runtime.mesh_eval); diff --git a/source/blender/blenkernel/intern/dynamicpaint.c b/source/blender/blenkernel/intern/dynamicpaint.c index 7bbdfa6c52d..0ee32af336d 100644 --- a/source/blender/blenkernel/intern/dynamicpaint.c +++ b/source/blender/blenkernel/intern/dynamicpaint.c @@ -153,12 +153,17 @@ typedef struct Bounds3D { typedef struct VolumeGrid { int dim[3]; - Bounds3D grid_bounds; /* whole grid bounds */ - - Bounds3D *bounds; /* (x*y*z) precalculated grid cell bounds */ - int *s_pos; /* (x*y*z) t_index begin id */ - int *s_num; /* (x*y*z) number of t_index points */ - int *t_index; /* actual surface point index, access: (s_pos + s_num) */ + /** whole grid bounds */ + Bounds3D grid_bounds; + + /** (x*y*z) precalculated grid cell bounds */ + Bounds3D *bounds; + /** (x*y*z) t_index begin id */ + int *s_pos; + /** (x*y*z) number of t_index points */ + int *s_num; + /** actual surface point index, access: (s_pos + s_num) */ + int *t_index; int *temp_t_index; } VolumeGrid; @@ -168,51 +173,67 @@ typedef struct Vec3f { } Vec3f; typedef struct BakeAdjPoint { - float dir[3]; /* vector pointing towards this neighbor */ - float dist; /* distance to */ + /** vector pointing towards this neighbor */ + float dir[3]; + /** distance to */ + float dist; } BakeAdjPoint; -/* Surface data used while processing a frame */ +/** Surface data used while processing a frame */ typedef struct PaintBakeNormal { - float invNorm[3]; /* current pixel world-space inverted normal */ - float normal_scale; /* normal directional scale for displace mapping */ + /** current pixel world-space inverted normal */ + float invNorm[3]; + /** normal directional scale for displace mapping */ + float normal_scale; } PaintBakeNormal; -/* Temp surface data used to process a frame */ +/** Temp surface data used to process a frame */ typedef struct PaintBakeData { /* point space data */ PaintBakeNormal *bNormal; - int *s_pos; /* index to start reading point sample realCoord */ - int *s_num; /* num of realCoord samples */ - Vec3f * - realCoord; /* current pixel center world-space coordinates for each sample ordered as (s_pos + s_num) */ + /** index to start reading point sample realCoord */ + int *s_pos; + /** num of realCoord samples */ + int *s_num; + /** current pixel center world-space coordinates for each sample ordered as (s_pos + s_num) */ + Vec3f *realCoord; Bounds3D mesh_bounds; float dim[3]; /* adjacency info */ - BakeAdjPoint *bNeighs; /* current global neighbor distances and directions, if required */ + /** current global neighbor distances and directions, if required */ + BakeAdjPoint *bNeighs; double average_dist; /* space partitioning */ - VolumeGrid *grid; /* space partitioning grid to optimize brush checks */ + /** space partitioning grid to optimize brush checks */ + VolumeGrid *grid; /* velocity and movement */ - Vec3f *velocity; /* speed vector in global space movement per frame, if required */ + /** speed vector in global space movement per frame, if required */ + Vec3f *velocity; Vec3f *prev_velocity; - float *brush_velocity; /* special temp data for post-p velocity based brushes like smudge - * 3 float dir vec + 1 float str */ - MVert *prev_verts; /* copy of previous frame vertices. used to observe surface movement */ - float prev_obmat[4][4]; /* previous frame object matrix */ - int clear; /* flag to check if surface was cleared/reset -> have to redo velocity etc. */ + /** special temp data for post-p velocity based brushes like smudge + * 3 float dir vec + 1 float str */ + float *brush_velocity; + /** copy of previous frame vertices. used to observe surface movement. */ + MVert *prev_verts; + /** Previous frame object matrix. */ + float prev_obmat[4][4]; + /** flag to check if surface was cleared/reset -> have to redo velocity etc. */ + int clear; } PaintBakeData; -/* UV Image sequence format point */ +/** UV Image sequence format point */ typedef struct PaintUVPoint { /* Pixel / mesh data */ - unsigned int tri_index, pixel_index; /* tri index on domain derived mesh */ - unsigned int v1, v2, v3; /* vertex indexes */ - - unsigned int - neighbour_pixel; /* If this pixel isn't uv mapped to any face, but it's neighboring pixel is */ + /** tri index on domain derived mesh */ + unsigned int tri_index; + unsigned int pixel_index; + /* vertex indexes */ + unsigned int v1, v2, v3; + + /** If this pixel isn't uv mapped to any face, but it's neighboring pixel is. */ + unsigned int neighbour_pixel; } PaintUVPoint; typedef struct ImgSeqFormatData { @@ -225,14 +246,20 @@ typedef struct ImgSeqFormatData { #define ADJ_BORDER_PIXEL (1 << 1) typedef struct PaintAdjData { - int * - n_target; /* array of neighboring point indexes, for single sample use (n_index + neigh_num) */ - int *n_index; /* index to start reading n_target for each point */ - int *n_num; /* num of neighs for each point */ - int *flags; /* vertex adjacency flags */ - int total_targets; /* size of n_target */ - int *border; /* indices of border pixels (only for texture paint) */ - int total_border; /* size of border */ + /** Array of neighboring point indexes, for single sample use (n_index + neigh_num). */ + int *n_target; + /** Index to start reading n_target for each point. */ + int *n_index; + /** Num of neighs for each point. */ + int *n_num; + /** Vertex adjacency flags. */ + int *flags; + /** Size of n_target. */ + int total_targets; + /** Indices of border pixels (only for texture paint). */ + int *border; + /** Size of border. */ + int total_border; } PaintAdjData; /************************* Runtime evaluation store ***************************/ @@ -302,64 +329,25 @@ static int dynamicPaint_surfaceNumOfPoints(DynamicPaintSurface *surface) return 0; } -/* checks whether surface's format/type has realtime preview */ -bool dynamicPaint_surfaceHasColorPreview(DynamicPaintSurface *surface) -{ - if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) { - return false; - } - else if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) { - return !ELEM(surface->type, MOD_DPAINT_SURFACE_T_DISPLACE, MOD_DPAINT_SURFACE_T_WAVE); - } - - return true; -} - /* get currently active surface (in user interface) */ DynamicPaintSurface *get_activeSurface(DynamicPaintCanvasSettings *canvas) { return BLI_findlink(&canvas->surfaces, canvas->active_sur); } -/* set preview to first previewable surface */ -void dynamicPaint_resetPreview(DynamicPaintCanvasSettings *canvas) -{ - DynamicPaintSurface *surface = canvas->surfaces.first; - bool done = false; - - for (; surface; surface = surface->next) { - if (!done && dynamicPaint_surfaceHasColorPreview(surface)) { - surface->flags |= MOD_DPAINT_PREVIEW; - done = true; - } - else { - surface->flags &= ~MOD_DPAINT_PREVIEW; - } - } -} - -/* set preview to defined surface */ -static void dynamicPaint_setPreview(DynamicPaintSurface *t_surface) -{ - DynamicPaintSurface *surface = t_surface->canvas->surfaces.first; - for (; surface; surface = surface->next) { - if (surface == t_surface) - surface->flags |= MOD_DPAINT_PREVIEW; - else - surface->flags &= ~MOD_DPAINT_PREVIEW; - } -} - bool dynamicPaint_outputLayerExists(struct DynamicPaintSurface *surface, Object *ob, int output) { const char *name; - if (output == 0) + if (output == 0) { name = surface->output_name; - else if (output == 1) + } + else if (output == 1) { name = surface->output_name2; - else + } + else { return false; + } if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) { if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) { @@ -419,8 +407,9 @@ static bool surface_duplicateNameExists(void *arg, const char *name) DynamicPaintSurface *surface = t_surface->canvas->surfaces.first; for (; surface; surface = surface->next) { - if (surface != t_surface && STREQ(name, surface->name)) + if (surface != t_surface && STREQ(name, surface->name)) { return true; + } } return false; } @@ -465,12 +454,6 @@ void dynamicPaintSurface_updateType(struct DynamicPaintSurface *surface) } surface_setUniqueOutputName(surface, surface->output_name, 0); - - /* update preview */ - if (dynamicPaint_surfaceHasColorPreview(surface)) - dynamicPaint_setPreview(surface); - else - dynamicPaint_resetPreview(surface->canvas); } static int surface_totalSamples(DynamicPaintSurface *surface) @@ -565,8 +548,9 @@ static int surface_getBrushFlags(DynamicPaintSurface *surface, Depsgraph *depsgr if (pmd2->brush) { DynamicPaintBrushSettings *brush = pmd2->brush; - if (brush->flags & MOD_DPAINT_USES_VELOCITY) + if (brush->flags & MOD_DPAINT_USES_VELOCITY) { flags |= BRUSH_USES_VELOCITY; + } } } } @@ -579,11 +563,13 @@ static int surface_getBrushFlags(DynamicPaintSurface *surface, Depsgraph *depsgr /* check whether two bounds intersect */ static bool boundsIntersect(Bounds3D *b1, Bounds3D *b2) { - if (!b1->valid || !b2->valid) + if (!b1->valid || !b2->valid) { return false; + } for (int i = 2; i--;) { - if (!(b1->min[i] <= b2->max[i] && b1->max[i] >= b2->min[i])) + if (!(b1->min[i] <= b2->max[i] && b1->max[i] >= b2->min[i])) { return false; + } } return true; } @@ -591,11 +577,13 @@ static bool boundsIntersect(Bounds3D *b1, Bounds3D *b2) /* check whether two bounds intersect inside defined proximity */ static bool boundsIntersectDist(Bounds3D *b1, Bounds3D *b2, const float dist) { - if (!b1->valid || !b2->valid) + if (!b1->valid || !b2->valid) { return false; + } for (int i = 2; i--;) { - if (!(b1->min[i] <= (b2->max[i] + dist) && b1->max[i] >= (b2->min[i] - dist))) + if (!(b1->min[i] <= (b2->max[i] + dist) && b1->max[i] >= (b2->min[i] - dist))) { return false; + } } return true; } @@ -603,11 +591,13 @@ static bool boundsIntersectDist(Bounds3D *b1, Bounds3D *b2, const float dist) /* check whether bounds intersects a point with given radius */ static bool boundIntersectPoint(Bounds3D *b, float point[3], const float radius) { - if (!b->valid) + if (!b->valid) { return false; + } for (int i = 2; i--;) { - if (!(b->min[i] <= (point[i] + radius) && b->max[i] >= (point[i] - radius))) + if (!(b->min[i] <= (point[i] + radius) && b->max[i] >= (point[i] - radius))) { return false; + } } return true; } @@ -636,14 +626,18 @@ static void freeGrid(PaintSurfaceData *data) PaintBakeData *bData = data->bData; VolumeGrid *grid = bData->grid; - if (grid->bounds) + if (grid->bounds) { MEM_freeN(grid->bounds); - if (grid->s_pos) + } + if (grid->s_pos) { MEM_freeN(grid->s_pos); - if (grid->s_num) + } + if (grid->s_num) { MEM_freeN(grid->s_num); - if (grid->t_index) + } + if (grid->t_index) { MEM_freeN(grid->t_index); + } MEM_freeN(bData->grid); bData->grid = NULL; @@ -738,8 +732,9 @@ static void surfaceGenerateGrid(struct DynamicPaintSurface *surface) int *temp_t_index = NULL; int *temp_s_num = NULL; - if (bData->grid) + if (bData->grid) { freeGrid(sData); + } bData->grid = MEM_callocN(sizeof(VolumeGrid), "Surface Grid"); grid = bData->grid; @@ -808,8 +803,9 @@ static void surfaceGenerateGrid(struct DynamicPaintSurface *surface) /* in case of an allocation failure abort here */ if (!grid->bounds || !grid->s_pos || !grid->s_num || !grid->t_index || !temp_s_num || - !temp_t_index) + !temp_t_index) { error = 1; + } if (!error) { /* calculate number of points within each cell */ @@ -845,10 +841,12 @@ static void surfaceGenerateGrid(struct DynamicPaintSurface *surface) } } - if (temp_s_num) + if (temp_s_num) { MEM_freeN(temp_s_num); - if (temp_t_index) + } + if (temp_t_index) { MEM_freeN(temp_t_index); + } grid->temp_t_index = NULL; if (error || !grid->s_num) { @@ -864,10 +862,12 @@ static void surfaceGenerateGrid(struct DynamicPaintSurface *surface) void dynamicPaint_freeBrush(struct DynamicPaintModifierData *pmd) { if (pmd->brush) { - if (pmd->brush->paint_ramp) + if (pmd->brush->paint_ramp) { MEM_freeN(pmd->brush->paint_ramp); - if (pmd->brush->vel_ramp) + } + if (pmd->brush->vel_ramp) { MEM_freeN(pmd->brush->vel_ramp); + } MEM_freeN(pmd->brush); pmd->brush = NULL; @@ -877,16 +877,21 @@ void dynamicPaint_freeBrush(struct DynamicPaintModifierData *pmd) static void dynamicPaint_freeAdjData(PaintSurfaceData *data) { if (data->adj_data) { - if (data->adj_data->n_index) + if (data->adj_data->n_index) { MEM_freeN(data->adj_data->n_index); - if (data->adj_data->n_num) + } + if (data->adj_data->n_num) { MEM_freeN(data->adj_data->n_num); - if (data->adj_data->n_target) + } + if (data->adj_data->n_target) { MEM_freeN(data->adj_data->n_target); - if (data->adj_data->flags) + } + if (data->adj_data->flags) { MEM_freeN(data->adj_data->flags); - if (data->adj_data->border) + } + if (data->adj_data->border) { MEM_freeN(data->adj_data->border); + } MEM_freeN(data->adj_data); data->adj_data = NULL; } @@ -896,24 +901,33 @@ static void free_bakeData(PaintSurfaceData *data) { PaintBakeData *bData = data->bData; if (bData) { - if (bData->bNormal) + if (bData->bNormal) { MEM_freeN(bData->bNormal); - if (bData->s_pos) + } + if (bData->s_pos) { MEM_freeN(bData->s_pos); - if (bData->s_num) + } + if (bData->s_num) { MEM_freeN(bData->s_num); - if (bData->realCoord) + } + if (bData->realCoord) { MEM_freeN(bData->realCoord); - if (bData->bNeighs) + } + if (bData->bNeighs) { MEM_freeN(bData->bNeighs); - if (bData->grid) + } + if (bData->grid) { freeGrid(data); - if (bData->prev_verts) + } + if (bData->prev_verts) { MEM_freeN(bData->prev_verts); - if (bData->velocity) + } + if (bData->velocity) { MEM_freeN(bData->velocity); - if (bData->prev_velocity) + } + if (bData->prev_velocity) { MEM_freeN(bData->prev_velocity); + } MEM_freeN(data->bData); data->bData = NULL; @@ -923,8 +937,9 @@ static void free_bakeData(PaintSurfaceData *data) /* free surface data if it's not used anymore */ static void surface_freeUnusedData(DynamicPaintSurface *surface) { - if (!surface->data) + if (!surface->data) { return; + } /* free bakedata if not active or surface is baked */ if (!(surface->flags & MOD_DPAINT_ACTIVE) || @@ -936,23 +951,27 @@ static void surface_freeUnusedData(DynamicPaintSurface *surface) void dynamicPaint_freeSurfaceData(DynamicPaintSurface *surface) { PaintSurfaceData *data = surface->data; - if (!data) + if (!data) { return; + } if (data->format_data) { /* format specific free */ if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) { ImgSeqFormatData *format_data = (ImgSeqFormatData *)data->format_data; - if (format_data->uv_p) + if (format_data->uv_p) { MEM_freeN(format_data->uv_p); - if (format_data->barycentricWeights) + } + if (format_data->barycentricWeights) { MEM_freeN(format_data->barycentricWeights); + } } MEM_freeN(data->format_data); } /* type data */ - if (data->type_data) + if (data->type_data) { MEM_freeN(data->type_data); + } dynamicPaint_freeAdjData(data); /* bake data */ free_bakeData(data); @@ -969,8 +988,9 @@ void dynamicPaint_freeSurface(const DynamicPaintModifierData *pmd, DynamicPaintS } surface->pointcache = NULL; - if (surface->effector_weights) + if (surface->effector_weights) { MEM_freeN(surface->effector_weights); + } surface->effector_weights = NULL; BLI_remlink(&(surface->canvas->surfaces), surface); @@ -1019,8 +1039,9 @@ DynamicPaintSurface *dynamicPaint_createNewSurface(DynamicPaintCanvasSettings *c Scene *scene) { DynamicPaintSurface *surface = MEM_callocN(sizeof(DynamicPaintSurface), "DynamicPaintSurface"); - if (!surface) + if (!surface) { return NULL; + } surface->canvas = canvas; surface->format = MOD_DPAINT_SURFACE_F_VERTEX; @@ -1033,8 +1054,8 @@ DynamicPaintSurface *dynamicPaint_createNewSurface(DynamicPaintCanvasSettings *c /* Set initial values */ surface->flags = MOD_DPAINT_ANTIALIAS | MOD_DPAINT_MULALPHA | MOD_DPAINT_DRY_LOG | - MOD_DPAINT_DISSOLVE_LOG | MOD_DPAINT_ACTIVE | MOD_DPAINT_PREVIEW | - MOD_DPAINT_OUT1 | MOD_DPAINT_USE_DRYING; + MOD_DPAINT_DISSOLVE_LOG | MOD_DPAINT_ACTIVE | MOD_DPAINT_OUT1 | + MOD_DPAINT_USE_DRYING; surface->effect = 0; surface->effect_ui = 1; @@ -1099,27 +1120,32 @@ bool dynamicPaint_createType(struct DynamicPaintModifierData *pmd, int type, str if (pmd) { if (type == MOD_DYNAMICPAINT_TYPE_CANVAS) { DynamicPaintCanvasSettings *canvas; - if (pmd->canvas) + if (pmd->canvas) { dynamicPaint_freeCanvas(pmd); + } canvas = pmd->canvas = MEM_callocN(sizeof(DynamicPaintCanvasSettings), "DynamicPaint Canvas"); - if (!canvas) + if (!canvas) { return false; + } canvas->pmd = pmd; /* Create one surface */ - if (!dynamicPaint_createNewSurface(canvas, scene)) + if (!dynamicPaint_createNewSurface(canvas, scene)) { return false; + } } else if (type == MOD_DYNAMICPAINT_TYPE_BRUSH) { DynamicPaintBrushSettings *brush; - if (pmd->brush) + if (pmd->brush) { dynamicPaint_freeBrush(pmd); + } brush = pmd->brush = MEM_callocN(sizeof(DynamicPaintBrushSettings), "DynamicPaint Paint"); - if (!brush) + if (!brush) { return false; + } brush->pmd = pmd; brush->psys = NULL; @@ -1150,8 +1176,9 @@ bool dynamicPaint_createType(struct DynamicPaintModifierData *pmd, int type, str CBData *ramp; brush->paint_ramp = BKE_colorband_add(false); - if (!brush->paint_ramp) + if (!brush->paint_ramp) { return false; + } ramp = brush->paint_ramp->data; /* Add default smooth-falloff ramp. */ ramp[0].r = ramp[0].g = ramp[0].b = ramp[0].a = 1.0f; @@ -1166,8 +1193,9 @@ bool dynamicPaint_createType(struct DynamicPaintModifierData *pmd, int type, str CBData *ramp; brush->vel_ramp = BKE_colorband_add(false); - if (!brush->vel_ramp) + if (!brush->vel_ramp) { return false; + } ramp = brush->vel_ramp->data; ramp[0].r = ramp[0].g = ramp[0].b = ramp[0].a = ramp[0].pos = 0.0f; ramp[1].r = ramp[1].g = ramp[1].b = ramp[1].a = ramp[1].pos = 1.0f; @@ -1188,18 +1216,21 @@ void dynamicPaint_Modifier_copy(const struct DynamicPaintModifierData *pmd, { /* Init modifier */ tpmd->type = pmd->type; - if (pmd->canvas) + if (pmd->canvas) { dynamicPaint_createType(tpmd, MOD_DYNAMICPAINT_TYPE_CANVAS, NULL); - if (pmd->brush) + } + if (pmd->brush) { dynamicPaint_createType(tpmd, MOD_DYNAMICPAINT_TYPE_BRUSH, NULL); + } /* Copy data */ if (tpmd->canvas) { DynamicPaintSurface *surface; tpmd->canvas->pmd = tpmd; /* free default surface */ - if (tpmd->canvas->surfaces.first) + if (tpmd->canvas->surfaces.first) { dynamicPaint_freeSurface(tpmd, tpmd->canvas->surfaces.first); + } /* copy existing surfaces */ for (surface = pmd->canvas->surfaces.first; surface; surface = surface->next) { @@ -1224,7 +1255,6 @@ void dynamicPaint_Modifier_copy(const struct DynamicPaintModifierData *pmd, t_surface->disp_type = surface->disp_type; t_surface->image_fileformat = surface->image_fileformat; t_surface->effect_ui = surface->effect_ui; - t_surface->preview_id = surface->preview_id; t_surface->init_color_type = surface->init_color_type; t_surface->flags = surface->flags; t_surface->effect = surface->effect; @@ -1267,7 +1297,6 @@ void dynamicPaint_Modifier_copy(const struct DynamicPaintModifierData *pmd, BLI_strncpy(t_surface->output_name, surface->output_name, sizeof(t_surface->output_name)); BLI_strncpy(t_surface->output_name2, surface->output_name2, sizeof(t_surface->output_name2)); } - dynamicPaint_resetPreview(tpmd->canvas); } else if (tpmd->brush) { DynamicPaintBrushSettings *brush = pmd->brush, *t_brush = tpmd->brush; @@ -1287,10 +1316,12 @@ void dynamicPaint_Modifier_copy(const struct DynamicPaintModifierData *pmd, t_brush->paint_distance = brush->paint_distance; t_brush->psys = brush->psys; - if (brush->paint_ramp) + if (brush->paint_ramp) { memcpy(t_brush->paint_ramp, brush->paint_ramp, sizeof(ColorBand)); - if (brush->vel_ramp) + } + if (brush->vel_ramp) { memcpy(t_brush->vel_ramp, brush->vel_ramp, sizeof(ColorBand)); + } t_brush->proximity_falloff = brush->proximity_falloff; t_brush->wave_type = brush->wave_type; @@ -1327,8 +1358,9 @@ static void dynamicPaint_allocateSurfaceType(DynamicPaintSurface *surface) break; } - if (sData->type_data == NULL) + if (sData->type_data == NULL) { setError(surface->canvas, N_("Not enough free memory")); + } } static bool surface_usesAdjDistance(DynamicPaintSurface *surface) @@ -1352,8 +1384,9 @@ static void dynamicPaint_initAdjacencyData(DynamicPaintSurface *surface, const b int *temp_data; int neigh_points = 0; - if (!force_init && !surface_usesAdjData(surface)) + if (!force_init && !surface_usesAdjData(surface)) { return; + } if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) { /* For vertex format, neighbors are connected by edges */ @@ -1363,13 +1396,15 @@ static void dynamicPaint_initAdjacencyData(DynamicPaintSurface *surface, const b neigh_points = sData->total_points * 8; } - if (!neigh_points) + if (!neigh_points) { return; + } /* allocate memory */ ad = sData->adj_data = MEM_callocN(sizeof(PaintAdjData), "Surface Adj Data"); - if (!ad) + if (!ad) { return; + } ad->n_index = MEM_callocN(sizeof(int) * sData->total_points, "Surface Adj Index"); ad->n_num = MEM_callocN(sizeof(int) * sData->total_points, "Surface Adj Counts"); temp_data = MEM_callocN(sizeof(int) * sData->total_points, "Temp Adj Data"); @@ -1382,8 +1417,9 @@ static void dynamicPaint_initAdjacencyData(DynamicPaintSurface *surface, const b /* in case of allocation error, free memory */ if (!ad->n_index || !ad->n_num || !ad->n_target || !temp_data) { dynamicPaint_freeAdjData(sData); - if (temp_data) + if (temp_data) { MEM_freeN(temp_data); + } setError(surface->canvas, N_("Not enough free memory")); return; } @@ -1579,11 +1615,13 @@ static void dynamicPaint_setInitialColor(const Scene *scene, DynamicPaintSurface int i; const bool scene_color_manage = BKE_scene_check_color_management_enabled(scene); - if (surface->type != MOD_DPAINT_SURFACE_T_PAINT) + if (surface->type != MOD_DPAINT_SURFACE_T_PAINT) { return; + } - if (surface->init_color_type == MOD_DPAINT_INITIAL_NONE) + if (surface->init_color_type == MOD_DPAINT_INITIAL_NONE) { return; + } /* Single color */ if (surface->init_color_type == MOD_DPAINT_INITIAL_COLOR) { @@ -1603,14 +1641,16 @@ static void dynamicPaint_setInitialColor(const Scene *scene, DynamicPaintSurface char uvname[MAX_CUSTOMDATA_LAYER_NAME]; - if (!tex) + if (!tex) { return; + } /* 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); - if (!mloopuv) + if (!mloopuv) { return; + } /* for vertex surface loop through tfaces and find uv color * that provides highest alpha */ @@ -1655,8 +1695,9 @@ static void dynamicPaint_setInitialColor(const Scene *scene, DynamicPaintSurface const int totloop = mesh->totloop; const MLoopCol *col = CustomData_get_layer_named( &mesh->ldata, CD_MLOOPCOL, surface->init_layername); - if (!col) + if (!col) { return; + } for (i = 0; i < totloop; i++) { rgba_uchar_to_float(pPoint[mloop[i].v].color, (const unsigned char *)&col[mloop[i].v].r); @@ -1666,8 +1707,9 @@ static void dynamicPaint_setInitialColor(const Scene *scene, DynamicPaintSurface const MLoopTri *mlooptri = BKE_mesh_runtime_looptri_ensure(mesh); MLoopCol *col = CustomData_get_layer_named( &mesh->ldata, CD_MLOOPCOL, surface->init_layername); - if (!col) + if (!col) { return; + } DynamicPaintSetInitColorData data = { .surface = surface, @@ -1690,21 +1732,26 @@ void dynamicPaint_clearSurface(const Scene *scene, DynamicPaintSurface *surface) if (sData && sData->type_data) { unsigned int data_size; - if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) + if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) { data_size = sizeof(PaintPoint); - else if (surface->type == MOD_DPAINT_SURFACE_T_WAVE) + } + else if (surface->type == MOD_DPAINT_SURFACE_T_WAVE) { data_size = sizeof(PaintWavePoint); - else + } + else { data_size = sizeof(float); + } memset(sData->type_data, 0, data_size * sData->total_points); /* set initial color */ - if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) + if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) { dynamicPaint_setInitialColor(scene, surface); + } - if (sData->bData) + if (sData->bData) { sData->bData->clear = 1; + } } } @@ -1713,19 +1760,23 @@ bool dynamicPaint_resetSurface(const Scene *scene, DynamicPaintSurface *surface) { int numOfPoints = dynamicPaint_surfaceNumOfPoints(surface); /* free existing data */ - if (surface->data) + if (surface->data) { dynamicPaint_freeSurfaceData(surface); + } /* don't reallocate for image sequence types. they get handled only on bake */ - if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) + if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) { return true; - if (numOfPoints < 1) + } + if (numOfPoints < 1) { return false; + } /* allocate memory */ surface->data = MEM_callocN(sizeof(PaintSurfaceData), "PaintSurfaceData"); - if (!surface->data) + if (!surface->data) { return false; + } /* allocate data depending on surface type and format */ surface->data->total_points = numOfPoints; @@ -1733,8 +1784,9 @@ bool dynamicPaint_resetSurface(const Scene *scene, DynamicPaintSurface *surface) dynamicPaint_initAdjacencyData(surface, false); /* set initial color */ - if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) + if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) { dynamicPaint_setInitialColor(scene, surface); + } return true; } @@ -1762,7 +1814,6 @@ typedef struct DynamicPaintModifierApplyData { float (*fcolor)[4]; MLoopCol *mloopcol; MLoopCol *mloopcol_wet; - MLoopCol *mloopcol_preview; } DynamicPaintModifierApplyData; static void dynamic_paint_apply_surface_displace_cb(void *__restrict userdata, @@ -1789,8 +1840,9 @@ static void dynamicPaint_applySurfaceDisplace(DynamicPaintSurface *surface, Mesh { PaintSurfaceData *sData = surface->data; - if (!sData || surface->format != MOD_DPAINT_SURFACE_F_VERTEX) + if (!sData || surface->format != MOD_DPAINT_SURFACE_F_VERTEX) { return; + } /* displace paint */ if (surface->type == MOD_DPAINT_SURFACE_T_DISPLACE) { @@ -1826,7 +1878,6 @@ static void dynamic_paint_apply_surface_vpaint_cb(void *__restrict userdata, const ParallelRangeTLS *__restrict UNUSED(tls)) { const DynamicPaintModifierApplyData *data = userdata; - Object *ob = data->ob; const MLoop *mloop = data->mloop; const MPoly *mpoly = data->mpoly; @@ -1837,11 +1888,6 @@ static void dynamic_paint_apply_surface_vpaint_cb(void *__restrict userdata, MLoopCol *mloopcol = data->mloopcol; MLoopCol *mloopcol_wet = data->mloopcol_wet; - MLoopCol *mloopcol_preview = data->mloopcol_preview; - - const Material *material = mloopcol_preview ? - give_current_material(ob, mpoly[p_index].mat_nr + 1) : - NULL; for (int j = 0; j < mpoly[p_index].totloop; j++) { const int l_index = mpoly[p_index].loopstart + j; @@ -1860,37 +1906,6 @@ static void dynamic_paint_apply_surface_vpaint_cb(void *__restrict userdata, mloopcol_wet[l_index].b = c; mloopcol_wet[l_index].a = 255; } - - /* viewport preview */ - if (mloopcol_preview) { - if (surface->preview_id == MOD_DPAINT_SURFACE_PREV_PAINT) { - float c[3]; - - /* Apply material color as base vertex color for preview */ - mloopcol_preview[l_index].a = 255; - if (material) { - c[0] = material->r; - c[1] = material->g; - c[2] = material->b; - } - else { /* default gray */ - c[0] = 0.65f; - c[1] = 0.65f; - c[2] = 0.65f; - } - /* mix surface color */ - interp_v3_v3v3(c, c, fcolor[v_index], fcolor[v_index][3]); - - rgb_float_to_uchar((unsigned char *)&mloopcol_preview[l_index].r, c); - } - else { - const char c = unit_float_to_uchar_clamp(pPoint[v_index].wetness); - mloopcol_preview[l_index].r = c; - mloopcol_preview[l_index].g = c; - mloopcol_preview[l_index].b = c; - mloopcol_preview[l_index].a = 255; - } - } } } @@ -1925,8 +1940,9 @@ static Mesh *dynamicPaint_Modifier_apply(DynamicPaintModifierData *pmd, Object * PaintSurfaceData *sData = surface->data; if (surface->format != MOD_DPAINT_SURFACE_F_IMAGESEQ && sData) { - if (!(surface->flags & MOD_DPAINT_ACTIVE)) + if (!(surface->flags & MOD_DPAINT_ACTIVE)) { continue; + } /* process vertex surface previews */ if (surface->format == MOD_DPAINT_SURFACE_F_VERTEX) { @@ -1975,22 +1991,11 @@ static Mesh *dynamicPaint_Modifier_apply(DynamicPaintModifierData *pmd, Object * &result->ldata, CD_MLOOPCOL, CD_CALLOC, NULL, totloop, surface->output_name2); } - /* Save preview results to weight layer to be able to share same drawing methods */ - MLoopCol *mloopcol_preview = NULL; - if (surface->flags & MOD_DPAINT_PREVIEW) { - mloopcol_preview = CustomData_get_layer(&result->ldata, CD_PREVIEW_MLOOPCOL); - if (!mloopcol_preview) { - mloopcol_preview = CustomData_add_layer( - &result->ldata, CD_PREVIEW_MLOOPCOL, CD_CALLOC, NULL, totloop); - } - } - data.ob = ob; data.mloop = mloop; data.mpoly = mpoly; data.mloopcol = mloopcol; data.mloopcol_wet = mloopcol_wet; - data.mloopcol_preview = mloopcol_preview; { ParallelRangeSettings settings; @@ -2003,7 +2008,7 @@ static Mesh *dynamicPaint_Modifier_apply(DynamicPaintModifierData *pmd, Object * MEM_freeN(fcolor); /* Mark tessellated CD layers as dirty. */ - //result->dirty |= DM_DIRTY_TESS_CDLAYERS; + // result->dirty |= DM_DIRTY_TESS_CDLAYERS; } /* vertex group paint */ else if (surface->type == MOD_DPAINT_SURFACE_T_WEIGHT) { @@ -2011,15 +2016,6 @@ static Mesh *dynamicPaint_Modifier_apply(DynamicPaintModifierData *pmd, Object * MDeformVert *dvert = CustomData_get_layer(&result->vdata, CD_MDEFORMVERT); float *weight = (float *)sData->type_data; - /* viewport preview */ - if (surface->flags & MOD_DPAINT_PREVIEW) { - /* Save preview results to weight layer to be - * able to share same drawing methods. - * Note this func also sets DM_DIRTY_TESS_CDLAYERS flag! */ - //TODO port this function - //DM_update_weight_mcol(ob, result, 0, weight, 0, NULL); - } - /* apply weights into a vertex group, if doesn't exists add a new layer */ if (defgrp_index != -1 && !dvert && (surface->output_name[0] != '\0')) { dvert = CustomData_add_layer( @@ -2070,7 +2066,7 @@ static Mesh *dynamicPaint_Modifier_apply(DynamicPaintModifierData *pmd, Object * } if (update_normals) { - //result->dirty |= DM_DIRTY_NORMALS; + // result->dirty |= DM_DIRTY_NORMALS; } } /* make a copy of mesh to use as brush data */ @@ -2121,8 +2117,9 @@ static void dynamicPaint_frameUpdate(DynamicPaintModifierData *pmd, canvas_copyMesh(canvas, mesh); /* in case image sequence baking, stop here */ - if (canvas->flags & MOD_DPAINT_BAKING) + if (canvas->flags & MOD_DPAINT_BAKING) { return; + } /* loop through surfaces */ for (; surface; surface = surface->next) { @@ -2134,13 +2131,15 @@ static void dynamicPaint_frameUpdate(DynamicPaintModifierData *pmd, /* image sequences are handled by bake operator */ if ((surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) || - !(surface->flags & MOD_DPAINT_ACTIVE)) + !(surface->flags & MOD_DPAINT_ACTIVE)) { continue; + } /* make sure surface is valid */ no_surface_data = surface->data == NULL; - if (!dynamicPaint_checkSurfaceData(scene, surface)) + if (!dynamicPaint_checkSurfaceData(scene, surface)) { continue; + } /* limit frame range */ CLAMP(current_frame, surface->start_frame, surface->end_frame); @@ -2219,11 +2218,11 @@ Mesh *dynamicPaint_Modifier_do(DynamicPaintModifierData *pmd, } } -/***************************** Image Sequence / UV Image Surface Calls ******************************/ +/* -------------------------------------------------------------------- */ +/** \name Image Sequence / UV Image Surface Calls + * \{ */ -/* - * Create a surface for uv image sequence format - */ +/* Create a surface for uv image sequence format. */ #define JITTER_SAMPLES \ { \ 0.0f, 0.0f, -0.2f, -0.4f, 0.2f, 0.4f, 0.4f, -0.2f, -0.4f, 0.3f, \ @@ -2426,8 +2425,9 @@ static void dynamic_paint_create_uv_surface_neighbor_cb( } /* Increase the final number of active surface points if relevant. */ - if (tPoint->tri_index != -1) + if (tPoint->tri_index != -1) { atomic_add_and_fetch_uint32(active_points, 1); + } } } @@ -2492,16 +2492,19 @@ static int dynamic_paint_find_neighbour_pixel(const DynamicPaintCreateUVSurfaceD const int x = px + neighX[n_index]; const int y = py + neighY[n_index]; - if (x < 0 || x >= w || y < 0 || y >= h) + if (x < 0 || x >= w || y < 0 || y >= h) { return OUT_OF_TEXTURE; + } const PaintUVPoint *tempPoints = data->tempPoints; const PaintUVPoint *tPoint = &tempPoints[x + w * y]; /* UV neighbor */ const PaintUVPoint *cPoint = &tempPoints[px + w * py]; /* Origin point */ - /* Check if shifted point is on same face -> it's a correct neighbor (and if it isn't marked as an "edge pixel") */ - if ((tPoint->tri_index == cPoint->tri_index) && (tPoint->neighbour_pixel == -1)) + /* Check if shifted point is on same face -> it's a correct neighbor + * (and if it isn't marked as an "edge pixel") */ + if ((tPoint->tri_index == cPoint->tri_index) && (tPoint->neighbour_pixel == -1)) { return (x + w * y); + } /* Even if shifted point is on another face * -> use this point. @@ -2561,8 +2564,9 @@ static void dynamic_paint_find_island_border(const DynamicPaintCreateUVSurfaceDa /* Enumerate all edges of the triangle, rotating the vertex list accordingly. */ for (int edge_idx = 0; edge_idx < 3; edge_idx++) { /* but not the edge we have just recursed through */ - if (edge_idx == in_edge) + if (edge_idx == in_edge) { continue; + } float uv0[2], uv1[2], uv2[2]; @@ -2575,22 +2579,25 @@ static void dynamic_paint_find_island_border(const DynamicPaintCreateUVSurfaceDa const float sidep = line_point_side_v2(uv0, uv1, pixel); const float side2 = line_point_side_v2(uv0, uv1, uv2); - if (side2 == 0.0f) + if (side2 == 0.0f) { continue; + } /* Hack: allow all edges of the original triangle */ const bool correct_side = (in_edge == -1) || (sidep < 0 && side2 > 0) || (sidep > 0 && side2 < 0); /* Allow exactly on edge for the non-recursive case */ - if (!correct_side && sidep != 0.0f) + if (!correct_side && sidep != 0.0f) { continue; + } /* Now find another face that is linked to that edge. */ const int vert0 = mloop[loop_idx[(edge_idx + 0)]].v; const int vert1 = mloop[loop_idx[(edge_idx + 1) % 3]].v; - /* Use a pre-computed vert-to-looptri mapping, speeds up things a lot compared to looping over all loopti. */ + /* Use a pre-computed vert-to-looptri mapping, + * speeds up things a lot compared to looping over all loopti. */ const MeshElemMap *map = &bdata->vert_to_looptri_map[vert0]; bool found_other = false; @@ -2602,8 +2609,9 @@ static void dynamic_paint_find_island_border(const DynamicPaintCreateUVSurfaceDa for (int i = 0; i < map->count && !found_other; i++) { const int lt_index = map->indices[i]; - if (lt_index == tri_index) + if (lt_index == tri_index) { continue; + } const unsigned int *other_loop_idx = mlooptri[lt_index].tri; @@ -2633,8 +2641,9 @@ static void dynamic_paint_find_island_border(const DynamicPaintCreateUVSurfaceDa } if (!found_other) { - if (bdata->best_index < 0) + if (bdata->best_index < 0) { bdata->best_index = ON_MESH_EDGE; + } continue; } @@ -2652,8 +2661,9 @@ static void dynamic_paint_find_island_border(const DynamicPaintCreateUVSurfaceDa * First check if there already is a better solution. */ const float dist_squared = dist_squared_to_line_segment_v2(pixel, uv0, uv1); - if (bdata->best_index >= 0 && dist_squared >= bdata->best_weight) + if (bdata->best_index >= 0 && dist_squared >= bdata->best_weight) { continue; + } /* * Find a point that is relatively at same edge position @@ -2673,8 +2683,9 @@ static void dynamic_paint_find_island_border(const DynamicPaintCreateUVSurfaceDa /* If current pixel uv is outside of texture */ if (final_pixel[0] < 0 || final_pixel[0] >= w || final_pixel[1] < 0 || final_pixel[1] >= h) { - if (bdata->best_index == NOT_FOUND) + if (bdata->best_index == NOT_FOUND) { bdata->best_index = OUT_OF_TEXTURE; + } continue; } @@ -2683,16 +2694,18 @@ static void dynamic_paint_find_island_border(const DynamicPaintCreateUVSurfaceDa int final_index = final_pixel[0] + w * final_pixel[1]; /* If we ended up to our origin point ( mesh has smaller than pixel sized faces) */ - if (final_index == (px + w * py)) + if (final_index == (px + w * py)) { continue; + } /* If final point is an "edge pixel", use it's "real" neighbor instead */ if (tempPoints[final_index].neighbour_pixel != -1) { final_index = tempPoints[final_index].neighbour_pixel; /* If we ended up to our origin point */ - if (final_index == (px + w * py)) + if (final_index == (px + w * py)) { continue; + } } /* If found pixel still lies on wrong face ( mesh has smaller than pixel sized faces) */ @@ -2703,8 +2716,9 @@ static void dynamic_paint_find_island_border(const DynamicPaintCreateUVSurfaceDa const float threshold = SQUARE(0.7f) / (w * h); if (dist_squared_to_looptri_uv_edges( - mlooptri, mloopuv, tempPoints[final_index].tri_index, final_pt) > threshold) + mlooptri, mloopuv, tempPoints[final_index].tri_index, final_pt) > threshold) { continue; + } } bdata->best_index = final_index; @@ -2725,7 +2739,8 @@ static bool dynamicPaint_pointHasNeighbor(PaintAdjData *ed, int index, int neigh return false; } -/* Makes the adjacency data symmetric, except for border pixels. I.e. if A is neighbor of B, B is neighbor of A. */ +/* Makes the adjacency data symmetric, except for border pixels. + * I.e. if A is neighbor of B, B is neighbor of A. */ static bool dynamicPaint_symmetrizeAdjData(PaintAdjData *ed, int active_points) { int *new_n_index = MEM_callocN(sizeof(int) * active_points, "Surface Adj Index"); @@ -2808,10 +2823,12 @@ static bool dynamicPaint_symmetrizeAdjData(PaintAdjData *ed, int active_points) } } - if (new_n_index) + if (new_n_index) { MEM_freeN(new_n_index); - if (new_n_num) + } + if (new_n_num) { MEM_freeN(new_n_num); + } return false; } @@ -2843,10 +2860,12 @@ int dynamicPaint_createUVSurface(Scene *scene, *progress = 0.0f; *do_update = true; - if (!mesh) + if (!mesh) { return setError(canvas, N_("Canvas mesh not updated")); - if (surface->format != MOD_DPAINT_SURFACE_F_IMAGESEQ) + } + if (surface->format != MOD_DPAINT_SURFACE_F_IMAGESEQ) { return setError(canvas, N_("Cannot bake non-'image sequence' formats")); + } mloop = mesh->mloop; mlooptri = BKE_mesh_runtime_looptri_ensure(mesh); @@ -2859,10 +2878,12 @@ int dynamicPaint_createUVSurface(Scene *scene, } /* Check for validity */ - if (!mloopuv) + if (!mloopuv) { return setError(canvas, N_("No UV data on canvas")); - if (surface->image_resolution < 16 || surface->image_resolution > 8192) + } + if (surface->image_resolution < 16 || surface->image_resolution > 8192) { return setError(canvas, N_("Invalid resolution")); + } const int w = surface->image_resolution; const int h = w; @@ -2873,23 +2894,28 @@ int dynamicPaint_createUVSurface(Scene *scene, CLOG_INFO(&LOG, 1, "Preparing UV surface of %ix%i pixels and %i tris.", w, h, tottri); /* Init data struct */ - if (surface->data) + if (surface->data) { dynamicPaint_freeSurfaceData(surface); + } sData = surface->data = MEM_callocN(sizeof(PaintSurfaceData), "PaintSurfaceData"); - if (!surface->data) + if (!surface->data) { return setError(canvas, N_("Not enough free memory")); + } tempPoints = MEM_callocN(w * h * sizeof(*tempPoints), "Temp PaintUVPoint"); - if (!tempPoints) + if (!tempPoints) { error = true; + } final_index = MEM_callocN(w * h * sizeof(*final_index), "Temp UV Final Indexes"); - if (!final_index) + if (!final_index) { error = true; + } tempWeights = MEM_mallocN(w * h * aa_samples * sizeof(*tempWeights), "Temp bWeights"); - if (!tempWeights) + if (!tempWeights) { error = true; + } /* * Generate a temporary bounding box array for UV faces to optimize @@ -2897,8 +2923,9 @@ int dynamicPaint_createUVSurface(Scene *scene, */ if (!error) { faceBB = MEM_mallocN(tottri * sizeof(*faceBB), "MPCanvasFaceBB"); - if (!faceBB) + if (!faceBB) { error = true; + } } *progress = 0.01f; @@ -3003,7 +3030,8 @@ int dynamicPaint_createUVSurface(Scene *scene, } for (int i = 0; i < 8; i++) { - /* Try to find a neighboring pixel in defined direction. If not found, -1 is returned */ + /* Try to find a neighboring pixel in defined direction. + * If not found, -1 is returned */ const int n_target = dynamic_paint_find_neighbour_pixel( &data, vert_to_looptri_map, w, h, tx, ty, i); @@ -3064,10 +3092,18 @@ int dynamicPaint_createUVSurface(Scene *scene, if (tempPoints[index].tri_index != -1) { int nidx = tempPoints[index].neighbour_pixel; - fprintf(dump_file, "%d\t%d,%d\t%u\t%d,%d\t%d\t", fidx, tx, h-1-ty, tempPoints[index].tri_index, nidx<0?-1:(nidx%w), nidx<0?-1:h-1-(nidx/w), ed->flags[fidx]); + fprintf(dump_file, + "%d\t%d,%d\t%u\t%d,%d\t%d\t", + fidx, + tx, + h - 1 - ty, + tempPoints[index].tri_index, + nidx < 0 ? -1 : (nidx % w), + nidx < 0 ? -1 : h - 1 - (nidx / w), + ed->flags[fidx]); for (int i = 0; i < ed->n_num[fidx]; i++) { - int tgt = tmp[ed->n_target[ed->n_index[fidx]+i]]; - fprintf(dump_file, "%s%d,%d", i?" ":"", tgt%w, h-1-tgt/w); + int tgt = tmp[ed->n_target[ed->n_index[fidx] + i]]; + fprintf(dump_file, "%s%d,%d", i ? " " : "", tgt % w, h - 1 - tgt / w); } fprintf(dump_file, "\n"); } @@ -3089,8 +3125,9 @@ int dynamicPaint_createUVSurface(Scene *scene, f_data->barycentricWeights = MEM_callocN( active_points * aa_samples * sizeof(*f_data->barycentricWeights), "PaintUVPoint"); - if (!f_data->uv_p || !f_data->barycentricWeights) + if (!f_data->uv_p || !f_data->barycentricWeights) { error = 1; + } } else { error = 1; @@ -3099,10 +3136,12 @@ int dynamicPaint_createUVSurface(Scene *scene, /* in case of allocation error, free everything */ if (error) { if (f_data) { - if (f_data->uv_p) + if (f_data->uv_p) { MEM_freeN(f_data->uv_p); - if (f_data->barycentricWeights) + } + if (f_data->barycentricWeights) { MEM_freeN(f_data->barycentricWeights); + } MEM_freeN(f_data); } sData->total_points = 0; @@ -3122,17 +3161,22 @@ int dynamicPaint_createUVSurface(Scene *scene, } } } - if (error == 1) + if (error == 1) { setError(canvas, N_("Not enough free memory")); + } - if (faceBB) + if (faceBB) { MEM_freeN(faceBB); - if (tempPoints) + } + if (tempPoints) { MEM_freeN(tempPoints); - if (tempWeights) + } + if (tempWeights) { MEM_freeN(tempWeights); - if (final_index) + } + if (final_index) { MEM_freeN(final_index); + } /* Init surface type data */ if (!error) { @@ -3211,8 +3255,9 @@ static void dynamic_paint_output_surface_image_displace_cb( /* image buffer position */ const int pos = ((ImgSeqFormatData *)(surface->data->format_data))->uv_p[index].pixel_index * 4; - if (surface->depth_clamp) + if (surface->depth_clamp) { depth /= surface->depth_clamp; + } if (surface->disp_type == MOD_DPAINT_DISP_DISPLACE) { depth = (0.5f - depth / 2.0f); @@ -3237,8 +3282,9 @@ static void dynamic_paint_output_surface_image_wave_cb( /* image buffer position */ const int pos = ((ImgSeqFormatData *)(surface->data->format_data))->uv_p[index].pixel_index * 4; - if (surface->depth_clamp) + if (surface->depth_clamp) { depth /= surface->depth_clamp; + } depth = (0.5f + depth / 2.0f); CLAMP(depth, 0.0f, 1.0f); @@ -3280,8 +3326,9 @@ void dynamicPaint_outputSurfaceImage(DynamicPaintSurface *surface, } /* if selected format is openexr, but current build doesn't support one */ #ifndef WITH_OPENEXR - if (format == R_IMF_IMTYPE_OPENEXR) + if (format == R_IMF_IMTYPE_OPENEXR) { format = R_IMF_IMTYPE_PNG; + } #endif BLI_strncpy(output_file, filename, sizeof(output_file)); BKE_image_path_ensure_ext_from_imtype(output_file, format); @@ -3394,10 +3441,13 @@ void dynamicPaint_outputSurfaceImage(DynamicPaintSurface *surface, IMB_freeImBuf(ibuf); } +/** \} */ + /***************************** Ray / Nearest Point Utils ******************************/ -/* A modified callback to bvh tree raycast. The tree must have been built using bvhtree_from_mesh_looptri. - * userdata must be a BVHMeshCallbackUserdata built from the same mesh as the tree. +/* A modified callback to bvh tree raycast. + * The tree must have been built using bvhtree_from_mesh_looptri. + * userdata must be a BVHMeshCallbackUserdata built from the same mesh as the tree. * * To optimize brush detection speed this doesn't calculate hit coordinates or normal. */ @@ -3427,7 +3477,8 @@ static void mesh_tris_spherecast_dp(void *userdata, } } -/* A modified callback to bvh tree nearest point. The tree must have been built using bvhtree_from_mesh_looptri. +/* A modified callback to bvh tree nearest point. + * The tree must have been built using bvhtree_from_mesh_looptri. * userdata must be a BVHMeshCallbackUserdata built from the same mesh as the tree. * * To optimize brush detection speed this doesn't calculate hit normal. @@ -3554,10 +3605,12 @@ static void dynamicPaint_mixWaveHeight(PaintWavePoint *wPoint, isect_height *= wave_factor; /* determine hit depending on wave_factor */ - if (wave_factor > 0.0f && wPoint->height > isect_height) + if (wave_factor > 0.0f && wPoint->height > isect_height) { hit = true; - else if (wave_factor < 0.0f && wPoint->height < isect_height) + } + else if (wave_factor < 0.0f && wPoint->height < isect_height) { hit = true; + } if (hit) { switch (brush->wave_type) { @@ -3573,8 +3626,9 @@ static void dynamicPaint_mixWaveHeight(PaintWavePoint *wPoint, wPoint->state = DPAINT_WAVE_REFLECT_ONLY; break; case MOD_DPAINT_WAVEB_CHANGE: - if (isect_change < 0.0f) + if (isect_change < 0.0f) { wPoint->height += isect_change * wave_factor; + } break; default: BLI_assert(0); @@ -3616,10 +3670,12 @@ static void dynamicPaint_updatePointData(const DynamicPaintSurface *surface, if (brush->flags & MOD_DPAINT_VELOCITY_COLOR) { copy_v3_v3(paint, coba_res); } - if (brush->flags & MOD_DPAINT_VELOCITY_ALPHA) + if (brush->flags & MOD_DPAINT_VELOCITY_ALPHA) { strength *= coba_res[3]; - if (brush->flags & MOD_DPAINT_VELOCITY_DEPTH) + } + if (brush->flags & MOD_DPAINT_VELOCITY_DEPTH) { depth *= coba_res[3]; + } } } @@ -3635,8 +3691,9 @@ static void dynamicPaint_updatePointData(const DynamicPaintSurface *surface, else if (surface->type == MOD_DPAINT_SURFACE_T_DISPLACE) { float *value = (float *)sData->type_data; - if (surface->flags & MOD_DPAINT_DISP_INCREMENTAL) + if (surface->flags & MOD_DPAINT_DISP_INCREMENTAL) { depth = value[index] + depth; + } if (surface->depth_clamp) { CLAMP(depth, 0.0f - surface->depth_clamp, surface->depth_clamp); @@ -3683,10 +3740,12 @@ static bool meshBrush_boundsIntersect(Bounds3D *b1, DynamicPaintBrushSettings *brush, float brush_radius) { - if (brush->collision == MOD_DPAINT_COL_VOLUME) + if (brush->collision == MOD_DPAINT_COL_VOLUME) { return boundsIntersect(b1, b2); - else if (brush->collision == MOD_DPAINT_COL_DIST || brush->collision == MOD_DPAINT_COL_VOLDIST) + } + else if (brush->collision == MOD_DPAINT_COL_DIST || brush->collision == MOD_DPAINT_COL_VOLDIST) { return boundsIntersectDist(b1, b2, brush_radius); + } return true; } @@ -3786,12 +3845,14 @@ static void dynamicPaint_brushMeshCalculateVelocity(Depsgraph *depsgraph, (*brushVel) = (struct Vec3f *)MEM_mallocN(numOfVerts_c * sizeof(Vec3f), "Dynamic Paint brush velocity"); - if (!(*brushVel)) + if (!(*brushVel)) { return; + } /* if mesh is constructive -> num of verts has changed, only use current frame derived mesh */ - if (numOfVerts_p != numOfVerts_c) + if (numOfVerts_p != numOfVerts_c) { mvert_p = mvert_c; + } /* calculate speed */ DynamicPaintBrushVelocityData data = { @@ -3922,8 +3983,9 @@ static void dynamic_paint_paint_mesh_cell_point_cb_ex( int numOfHits = 0; /* for image sequence anti-aliasing, use gaussian factors */ - if (samples > 1 && surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) + if (samples > 1 && surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) { total_sample = gaussianTotal; + } /* Supersampling */ for (ss = 0; ss < samples; ss++) { @@ -3947,10 +4009,12 @@ static void dynamic_paint_paint_mesh_cell_point_cb_ex( int hitTri = -1; /* Supersampling factor */ - if (samples > 1 && surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) + if (samples > 1 && surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) { sample_factor = gaussianFactors[ss]; - else + } + else { sample_factor = 1.0f; + } /* Get current sample position in world coordinates */ copy_v3_v3(ray_start, bData->realCoord[bData->s_pos[index] + ss].v); @@ -4020,8 +4084,9 @@ static void dynamic_paint_paint_mesh_cell_point_cb_ex( int tri = 0; /* if inverse prox and no hit found, skip this sample */ - if (inner_proximity && !hit_found) + if (inner_proximity && !hit_found) { continue; + } /* If pure distance proximity, find the nearest point on the mesh */ if (!(brush->flags & MOD_DPAINT_PROX_PROJECT)) { @@ -4064,8 +4129,9 @@ static void dynamic_paint_paint_mesh_cell_point_cb_ex( if (proxDist >= 0.0f && proxDist <= brush_radius) { proximity_factor = proxDist / brush_radius; CLAMP(proximity_factor, 0.0f, 1.0f); - if (!inner_proximity) + if (!inner_proximity) { proximity_factor = 1.0f - proximity_factor; + } hit_found = HIT_PROXIMITY; @@ -4082,8 +4148,9 @@ static void dynamic_paint_paint_mesh_cell_point_cb_ex( /* if "negate volume" enabled, negate all factors within volume*/ if (brush->collision == MOD_DPAINT_COL_VOLDIST && brush->flags & MOD_DPAINT_NEGATE_VOLUME) { volume_factor = 1.0f - volume_factor; - if (inner_proximity) + if (inner_proximity) { proximity_factor = 1.0f - proximity_factor; + } } /* apply final sample depending on final hit type */ @@ -4221,9 +4288,10 @@ static int dynamicPaint_paintMesh(Depsgraph *depsgraph, const MLoopTri *mlooptri = NULL; const MLoop *mloop = NULL; - if (brush->flags & MOD_DPAINT_USES_VELOCITY) + if (brush->flags & MOD_DPAINT_USES_VELOCITY) { dynamicPaint_brushMeshCalculateVelocity( depsgraph, scene, brushOb, brush, &brushVelocity, timescale); + } Mesh *brush_mesh = dynamicPaint_brush_mesh_get(brush); if (brush_mesh == NULL) { @@ -4320,8 +4388,9 @@ static int dynamicPaint_paintMesh(Depsgraph *depsgraph, } /* free brush velocity data */ - if (brushVelocity) + if (brushVelocity) { MEM_freeN(brushVelocity); + } return 1; } @@ -4370,8 +4439,9 @@ static void dynamic_paint_paint_particle_cell_point_cb_ex( /* Find nearest particle and get distance to it */ BLI_kdtree_3d_find_nearest(tree, bData->realCoord[bData->s_pos[index]].v, &nearest); /* if outside maximum range, no other particle can influence either */ - if (nearest.dist > range) + if (nearest.dist > range) { return; + } if (brush->flags & MOD_DPAINT_PART_RAD) { /* use particles individual size */ @@ -4386,8 +4456,9 @@ static void dynamic_paint_paint_particle_cell_point_cb_ex( /* distances inside solid radius has maximum influence -> dist = 0 */ smooth_range = max_ff(0.0f, (nearest.dist - part_solidradius)); /* do smoothness if enabled */ - if (smooth) + if (smooth) { smooth_range /= smooth; + } strength = 1.0f - smooth_range; disp_intersect = radius - nearest.dist; @@ -4416,14 +4487,16 @@ static void dynamic_paint_paint_particle_cell_point_cb_ex( ParticleData *pa = &psys->particles[nearest[n].index]; /* skip if out of range */ - if (nearest[n].dist > (pa->size + smooth)) + if (nearest[n].dist > (pa->size + smooth)) { continue; + } /* update hit data */ const float s_range = nearest[n].dist - pa->size; /* skip if higher influence is already found */ - if (smooth_range < s_range) + if (smooth_range < s_range) { continue; + } /* update hit data */ smooth_range = s_range; @@ -4437,8 +4510,9 @@ static void dynamic_paint_paint_particle_cell_point_cb_ex( } } - if (nearest) + if (nearest) { MEM_freeN(nearest); + } /* now calculate influence for this particle */ const float rad = radius + smooth; @@ -4449,13 +4523,15 @@ static void dynamic_paint_paint_particle_cell_point_cb_ex( /* do smoothness if enabled */ CLAMP_MIN(smooth_range, 0.0f); - if (smooth) + if (smooth) { smooth_range /= smooth; + } const float str = 1.0f - smooth_range; /* if influence is greater, use this one */ - if (str > strength) + if (str > strength) { strength = str; + } } if (strength > 0.001f) { @@ -4521,8 +4597,9 @@ static int dynamicPaint_paintParticles(DynamicPaintSurface *surface, Bounds3D part_bb = {{0}}; - if (psys->totpart < 1) + if (psys->totpart < 1) { return 1; + } /* * Build a kd-tree to optimize distance search @@ -4546,8 +4623,9 @@ static int dynamicPaint_paintParticles(DynamicPaintSurface *surface, } /* make sure particle is close enough to canvas */ - if (!boundIntersectPoint(&grid->grid_bounds, pa->state.co, range)) + if (!boundIntersectPoint(&grid->grid_bounds, pa->state.co, range)) { continue; + } BLI_kdtree_3d_insert(tree, p, pa->state.co); @@ -4556,8 +4634,9 @@ static int dynamicPaint_paintParticles(DynamicPaintSurface *surface, particlesAdded++; } - if (invalidParticles) + if (invalidParticles) { CLOG_WARN(&LOG, "Invalid particle(s) found!"); + } /* If no suitable particles were found, exit */ if (particlesAdded < 1) { @@ -4633,8 +4712,9 @@ static void dynamic_paint_paint_single_point_cb_ex(void *__restrict userdata, float colorband[4] = {0.0f}; float strength; - if (distance > brush_radius) + if (distance > brush_radius) { return; + } /* Smooth range or color ramp */ if (brush->proximity_falloff == MOD_DPAINT_PRFALL_SMOOTH || @@ -4713,8 +4793,9 @@ static int dynamicPaint_paintSinglePoint(Depsgraph *depsgraph, float brush_radius = brush->paint_distance * surface->radius_scale; Vec3f brushVel; - if (brush->flags & MOD_DPAINT_USES_VELOCITY) + if (brush->flags & MOD_DPAINT_USES_VELOCITY) { dynamicPaint_brushObjectCalculateVelocity(depsgraph, scene, brushOb, &brushVel, timescale); + } const Mesh *brush_mesh = dynamicPaint_brush_mesh_get(brush); const MVert *mvert = brush_mesh->mvert; @@ -4782,15 +4863,18 @@ static void dynamicPaint_prepareAdjacencyData(DynamicPaintSurface *surface, cons int index; - if ((!surface_usesAdjDistance(surface) && !force_init) || !sData->adj_data) + if ((!surface_usesAdjDistance(surface) && !force_init) || !sData->adj_data) { return; + } - if (bData->bNeighs) + if (bData->bNeighs) { MEM_freeN(bData->bNeighs); + } bNeighs = bData->bNeighs = MEM_mallocN(sData->adj_data->total_targets * sizeof(*bNeighs), "PaintEffectBake"); - if (!bNeighs) + if (!bNeighs) { return; + } ParallelRangeSettings settings; BLI_parallel_range_settings_defaults(&settings); @@ -4799,7 +4883,8 @@ static void dynamicPaint_prepareAdjacencyData(DynamicPaintSurface *surface, cons 0, sData->total_points, sData, dynamic_paint_prepare_adjacency_cb, &settings); /* calculate average values (single thread). - * Note: tried to put this in threaded callback (using _finalize feature), but gave ~30% slower result! */ + * Note: tried to put this in threaded callback (using _finalize feature), + * but gave ~30% slower result! */ bData->average_dist = 0.0; for (index = 0; index < sData->total_points; index++) { int numOfNeighs = adj_data->n_num[index]; @@ -4811,7 +4896,8 @@ static void dynamicPaint_prepareAdjacencyData(DynamicPaintSurface *surface, cons bData->average_dist /= adj_data->total_targets; } -/* find two adjacency points (closest_id) and influence (closest_d) to move paint towards when affected by a force */ +/* Find two adjacency points (closest_id) and influence (closest_d) + * to move paint towards when affected by a force. */ static void surface_determineForceTargetPoints(const PaintSurfaceData *sData, const int index, const float force[3], @@ -4836,15 +4922,17 @@ static void surface_determineForceTargetPoints(const PaintSurfaceData *sData, } } - if (closest_d[0] < 0.0f) + if (closest_d[0] < 0.0f) { return; + } /* find second closest neigh */ for (i = 0; i < numOfNeighs; i++) { const int n_index = sData->adj_data->n_index[index] + i; - if (n_index == closest_id[0]) + if (n_index == closest_id[0]) { continue; + } const float dir_dot = dot_v3v3(bNeighs[n_index].dir, force); const float closest_dot = dot_v3v3(bNeighs[n_index].dir, bNeighs[closest_id[0]].dir); @@ -4902,8 +4990,9 @@ static void dynamicPaint_doSmudge(DynamicPaintSurface *surface, int index, steps, step; float eff_scale, max_velocity = 0.0f; - if (!sData->adj_data) + if (!sData->adj_data) { return; + } /* find max velocity */ for (index = 0; index < sData->total_points; index++) { @@ -4919,8 +5008,9 @@ static void dynamicPaint_doSmudge(DynamicPaintSurface *surface, for (index = 0; index < sData->total_points; index++) { int i; - if (sData->adj_data->flags[index] & ADJ_BORDER_PIXEL) + if (sData->adj_data->flags[index] & ADJ_BORDER_PIXEL) { continue; + } PaintPoint *pPoint = &((PaintPoint *)sData->type_data)[index]; float smudge_str = bData->brush_velocity[index * 4 + 3]; @@ -4929,8 +5019,9 @@ static void dynamicPaint_doSmudge(DynamicPaintSurface *surface, int closest_id[2]; float closest_d[2]; - if (!smudge_str) + if (!smudge_str) { continue; + } /* get force affect points */ surface_determineForceTargetPoints( @@ -4946,8 +5037,9 @@ static void dynamicPaint_doSmudge(DynamicPaintSurface *surface, (PaintPoint *)sData->type_data)[sData->adj_data->n_target[n_index]]; /* just skip if angle is too extreme */ - if (dir_dot <= 0.0f) + if (dir_dot <= 0.0f) { continue; + } dir_factor = dir_dot * speed_scale; CLAMP_MAX(dir_factor, brush->smudge_strength); @@ -5025,18 +5117,20 @@ static void dynamic_paint_prepare_effect_cb(void *__restrict userdata, } /* if global gravity is enabled, add it too */ - if (scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) + if (scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) { /* also divide by 10 to about match default grav * with default force strength (1.0). */ madd_v3_v3fl(forc, scene->physics_settings.gravity, surface->effector_weights->global_gravity * surface->effector_weights->weight[0] / 10.f); + } /* add surface point velocity and acceleration if enabled */ if (bData->velocity) { - if (surface->drip_vel) + if (surface->drip_vel) { madd_v3_v3fl(forc, bData->velocity[index].v, surface->drip_vel * (-1.0f)); + } /* acceleration */ if (bData->prev_velocity && surface->drip_acc) { @@ -5098,10 +5192,12 @@ static int dynamicPaint_prepareEffectStep(struct Depsgraph *depsgraph, * so that just a few ultra close pixels wont up substeps to max. */ /* adjust number of required substep by fastest active effect */ - if (surface->effect & MOD_DPAINT_EFFECT_DO_SPREAD) + if (surface->effect & MOD_DPAINT_EFFECT_DO_SPREAD) { spread_speed = surface->spread_speed; - if (surface->effect & MOD_DPAINT_EFFECT_DO_SHRINK) + } + if (surface->effect & MOD_DPAINT_EFFECT_DO_SHRINK) { shrink_speed = surface->shrink_speed; + } fastest_effect = max_fff(spread_speed, shrink_speed, average_force); avg_dist = bData->average_dist * (double)CANVAS_REL_SIZE / (double)getSurfaceDimension(sData); @@ -5124,8 +5220,9 @@ static void dynamic_paint_effect_spread_cb(void *__restrict userdata, const DynamicPaintSurface *surface = data->surface; const PaintSurfaceData *sData = surface->data; - if (sData->adj_data->flags[index] & ADJ_BORDER_PIXEL) + if (sData->adj_data->flags[index] & ADJ_BORDER_PIXEL) { return; + } const int numOfNeighs = sData->adj_data->n_num[index]; BakeAdjPoint *bNeighs = sData->bData->bNeighs; @@ -5147,16 +5244,18 @@ static void dynamic_paint_effect_spread_cb(void *__restrict userdata, surface->color_spread_speed; /* do color mixing */ - if (color_mix) + if (color_mix) { mixColors(pPoint->e_color, pPoint->e_color[3], pPoint_prev->e_color, pPoint_prev->e_color[3], color_mix); + } /* Only continue if surrounding point has higher wetness */ - if (pPoint_prev->wetness < pPoint->wetness || pPoint_prev->wetness < MIN_WETNESS) + if (pPoint_prev->wetness < pPoint->wetness || pPoint_prev->wetness < MIN_WETNESS) { continue; + } w_factor = 1.0f / numOfNeighs * min_ff(pPoint_prev->wetness, 1.0f) * speed_scale; CLAMP(w_factor, 0.0f, 1.0f); @@ -5180,8 +5279,9 @@ static void dynamic_paint_effect_shrink_cb(void *__restrict userdata, const DynamicPaintSurface *surface = data->surface; const PaintSurfaceData *sData = surface->data; - if (sData->adj_data->flags[index] & ADJ_BORDER_PIXEL) + if (sData->adj_data->flags[index] & ADJ_BORDER_PIXEL) { return; + } const int numOfNeighs = sData->adj_data->n_num[index]; BakeAdjPoint *bNeighs = sData->bData->bNeighs; @@ -5205,8 +5305,9 @@ static void dynamic_paint_effect_shrink_cb(void *__restrict userdata, /* Check if neighboring point has lower alpha, * if so, decrease this point's alpha as well. */ - if (pPoint->color[3] <= 0.0f && pPoint->e_color[3] <= 0.0f && pPoint->wetness <= 0.0f) + if (pPoint->color[3] <= 0.0f && pPoint->e_color[3] <= 0.0f && pPoint->wetness <= 0.0f) { continue; + } /* decrease factor for dry paint alpha */ a_factor = max_ff((1.0f - pPoint_prev->color[3]) / numOfNeighs * @@ -5239,8 +5340,9 @@ static void dynamic_paint_effect_drip_cb(void *__restrict userdata, const DynamicPaintSurface *surface = data->surface; const PaintSurfaceData *sData = surface->data; - if (sData->adj_data->flags[index] & ADJ_BORDER_PIXEL) + if (sData->adj_data->flags[index] & ADJ_BORDER_PIXEL) { return; + } BakeAdjPoint *bNeighs = sData->bData->bNeighs; PaintPoint *pPoint = &((PaintPoint *)sData->type_data)[index]; @@ -5258,8 +5360,9 @@ static void dynamic_paint_effect_drip_cb(void *__restrict userdata, /* adjust drip speed depending on wetness */ float w_factor = pPoint_prev->wetness - 0.025f; - if (w_factor <= 0) + if (w_factor <= 0) { return; + } CLAMP(w_factor, 0.0f, 1.0f); float ppoint_wetness_diff = 0.0f; @@ -5274,8 +5377,9 @@ static void dynamic_paint_effect_drip_cb(void *__restrict userdata, const float dir_dot = closest_d[i]; /* just skip if angle is too extreme */ - if (dir_dot <= 0.0f) + if (dir_dot <= 0.0f) { continue; + } float dir_factor, a_factor; const float speed_scale = eff_scale * force[index * 4 + 3] / bNeighs[n_idx].dist; @@ -5283,13 +5387,14 @@ static void dynamic_paint_effect_drip_cb(void *__restrict userdata, const unsigned int n_trgt = (unsigned int)n_target[n_idx]; /* Sort of spinlock, but only for given ePoint. - * Since the odds a same ePoint is modified at the same time by several threads is very low, this is - * much more efficient than a global spin lock. */ + * Since the odds a same ePoint is modified at the same time by several threads is very low, + * this is much more efficient than a global spin lock. */ const unsigned int epointlock_idx = n_trgt / 8; const uint8_t epointlock_bitmask = 1 << (n_trgt & 7); /* 7 == 0b111 */ while (atomic_fetch_and_or_uint8(&point_locks[epointlock_idx], epointlock_bitmask) & - epointlock_bitmask) + epointlock_bitmask) { ; + } PaintPoint *ePoint = &((PaintPoint *)sData->type_data)[n_trgt]; const float e_wet = ePoint->wetness; @@ -5314,8 +5419,8 @@ static void dynamic_paint_effect_drip_cb(void *__restrict userdata, CLAMP_MAX(ePoint->e_color[3], pPoint_prev->e_color[3]); } - /* Decrease paint wetness on current point - * (just store diff here, that way we can only lock current point once at the end to apply it). */ + /* Decrease paint wetness on current point (just store diff here, + * that way we can only lock current point once at the end to apply it). */ ppoint_wetness_diff += (ePoint->wetness - e_wet); #ifndef NDEBUG @@ -5334,8 +5439,9 @@ static void dynamic_paint_effect_drip_cb(void *__restrict userdata, const unsigned int ppointlock_idx = index / 8; const uint8_t ppointlock_bitmask = 1 << (index & 7); /* 7 == 0b111 */ while (atomic_fetch_and_or_uint8(&point_locks[ppointlock_idx], ppointlock_bitmask) & - ppointlock_bitmask) + ppointlock_bitmask) { ; + } pPoint->wetness -= ppoint_wetness_diff; CLAMP(pPoint->wetness, 0.0f, MAX_WETNESS); @@ -5362,8 +5468,9 @@ static void dynamicPaint_doEffectStep(DynamicPaintSurface *surface, const float distance_scale = getSurfaceDimension(sData) / CANVAS_REL_SIZE; timescale /= steps; - if (!sData->adj_data) + if (!sData->adj_data) { return; + } /* * Spread Effect @@ -5503,8 +5610,9 @@ static void dynamicPaint_doBorderStep(DynamicPaintSurface *surface) { PaintSurfaceData *sData = surface->data; - if (!sData->adj_data || !sData->adj_data->border) + if (!sData->adj_data || !sData->adj_data->border) { return; + } /* Don't use prevPoint, relying on the condition that neighbors are never border pixels. */ DynamicPaintEffectData data = { @@ -5542,8 +5650,9 @@ static void dynamic_paint_wave_step_cb(void *__restrict userdata, float force = 0.0f, avg_dist = 0.0f, avg_height = 0.0f, avg_n_height = 0.0f; int numOfN = 0, numOfRN = 0; - if (wPoint->state > 0) + if (wPoint->state > 0) { return; + } const int *n_index = sData->adj_data->n_index; const int *n_target = sData->adj_data->n_target; @@ -5555,8 +5664,9 @@ static void dynamic_paint_wave_step_cb(void *__restrict userdata, float dist = bNeighs[n_idx].dist * wave_scale; const PaintWavePoint *tPoint = &prevPoint[n_target[n_idx]]; - if (!dist || tPoint->state > 0) + if (!dist || tPoint->state > 0) { continue; + } CLAMP_MIN(dist, min_dist); avg_dist += dist; @@ -5582,8 +5692,9 @@ static void dynamic_paint_wave_step_cb(void *__restrict userdata, /* else do wave eq */ else { /* add force towards zero height based on average dist */ - if (avg_dist) + if (avg_dist) { force += (0.0f - wPoint->height) * surface->wave_spring / (avg_dist * avg_dist) / 2.0f; + } /* change point velocity */ wPoint->velocity += force * dt * wave_speed * wave_speed; @@ -5596,10 +5707,12 @@ static void dynamic_paint_wave_step_cb(void *__restrict userdata, if (wave_max_slope && avg_dist) { const float max_offset = wave_max_slope * avg_dist; const float offset = (numOfN) ? (avg_height / numOfN - wPoint->height) : 0.0f; - if (offset > max_offset) + if (offset > max_offset) { wPoint->height += offset - max_offset; - else if (offset < -max_offset) + } + else if (offset < -max_offset) { wPoint->height += offset + max_offset; + } } } @@ -5629,8 +5742,9 @@ static void dynamicPaint_doWaveStep(DynamicPaintSurface *surface, float timescal /* allocate memory */ PaintWavePoint *prevPoint = MEM_mallocN(sData->total_points * sizeof(PaintWavePoint), __func__); - if (!prevPoint) + if (!prevPoint) { return; + } /* calculate average neigh distance (single thread) */ for (index = 0; index < sData->total_points; index++) { @@ -5734,10 +5848,10 @@ static void dynamic_paint_surface_pre_step_cb(void *__restrict userdata, /* reduce wet layer alpha by dry factor */ pPoint->e_color[3] *= dry_ratio; - /* now calculate new alpha for dry layer that keeps final blended color unchanged */ + /* Now calculate new alpha for dry layer that keeps final blended color unchanged. */ pPoint->color[3] = (f_color[3] - pPoint->e_color[3]) / (1.0f - pPoint->e_color[3]); - /* for each rgb component, calculate a new dry layer color that keeps the final blend color - * with these new alpha values. (wet layer color doesn't change)*/ + /* For each rgb component, calculate a new dry layer color that keeps the final blend + * color with these new alpha values. (wet layer color doesn't change). */ if (pPoint->color[3]) { for (i = 0; i < 3; i++) { pPoint->color[i] = (f_color[i] * f_color[3] - @@ -5797,12 +5911,14 @@ static bool dynamicPaint_surfaceHasMoved(DynamicPaintSurface *surface, Object *o int numOfVerts = mesh->totvert; int i; - if (!bData->prev_verts) + if (!bData->prev_verts) { return true; + } /* matrix comparison */ - if (!equals_m4m4(bData->prev_obmat, ob->obmat)) + if (!equals_m4m4(bData->prev_obmat, ob->obmat)) { return true; + } /* vertices */ for (i = 0; i < numOfVerts; i++) { @@ -5958,30 +6074,35 @@ static int dynamicPaint_generateBakeData(DynamicPaintSurface *surface, const bool surface_moved = dynamicPaint_surfaceHasMoved(surface, ob); /* get previous speed for accelertaion */ - if (do_accel_data && bData->prev_velocity && bData->velocity) + if (do_accel_data && bData->prev_velocity && bData->velocity) { memcpy(bData->prev_velocity, bData->velocity, sData->total_points * sizeof(Vec3f)); + } /* reset speed vectors */ - if (do_velocity_data && bData->velocity && (bData->clear || !surface_moved)) + if (do_velocity_data && bData->velocity && (bData->clear || !surface_moved)) { memset(bData->velocity, 0, sData->total_points * sizeof(Vec3f)); + } /* if previous data exists and mesh hasn't moved, no need to recalc */ - if (!surface_moved) + if (!surface_moved) { return 1; + } } canvas_verts = (struct Vec3f *)MEM_mallocN(canvasNumOfVerts * sizeof(struct Vec3f), "Dynamic Paint transformed canvas verts"); - if (!canvas_verts) + if (!canvas_verts) { return 0; + } /* allocate memory if required */ if (!bData) { sData->bData = bData = (struct PaintBakeData *)MEM_callocN(sizeof(struct PaintBakeData), "Dynamic Paint bake data"); if (!bData) { - if (canvas_verts) + if (canvas_verts) { MEM_freeN(canvas_verts); + } return 0; } @@ -5999,16 +6120,21 @@ static int dynamicPaint_generateBakeData(DynamicPaintSurface *surface, /* if any allocation failed, free everything */ if (!bData->bNormal || !bData->s_pos || !bData->s_num || !bData->realCoord || !canvas_verts) { - if (bData->bNormal) + if (bData->bNormal) { MEM_freeN(bData->bNormal); - if (bData->s_pos) + } + if (bData->s_pos) { MEM_freeN(bData->s_pos); - if (bData->s_num) + } + if (bData->s_num) { MEM_freeN(bData->s_num); - if (bData->realCoord) + } + if (bData->realCoord) { MEM_freeN(bData->realCoord); - if (canvas_verts) + } + if (canvas_verts) { MEM_freeN(canvas_verts); + } return setError(surface->canvas, N_("Not enough free memory")); } @@ -6024,8 +6150,9 @@ static int dynamicPaint_generateBakeData(DynamicPaintSurface *surface, bData->prev_velocity = (struct Vec3f *)MEM_mallocN(sData->total_points * sizeof(Vec3f), "Dynamic Paint prev velocity"); /* copy previous vel */ - if (bData->prev_velocity && bData->velocity) + if (bData->prev_velocity && bData->velocity) { memcpy(bData->prev_velocity, bData->velocity, sData->total_points * sizeof(Vec3f)); + } } /* @@ -6087,8 +6214,9 @@ static int dynamicPaint_doStep(Depsgraph *depsgraph, const bool for_render = (DEG_get_mode(depsgraph) == DAG_EVAL_RENDER); int ret = 1; - if (sData->total_points < 1) + if (sData->total_points < 1) { return 0; + } if (dynamic_paint_surface_needs_dry_dissolve(surface)) { DynamicPaintDissolveDryData data = { @@ -6130,10 +6258,12 @@ static int dynamicPaint_doStep(Depsgraph *depsgraph, bData->brush_velocity = MEM_callocN(sData->total_points * sizeof(float) * 4, "Dynamic Paint brush velocity"); /* init adjacency data if not already */ - if (!sData->adj_data) + if (!sData->adj_data) { dynamicPaint_initAdjacencyData(surface, true); - if (!bData->bNeighs) + } + if (!bData->bNeighs) { dynamicPaint_prepareAdjacencyData(surface, true); + } } /* update object data on this subframe */ @@ -6180,8 +6310,10 @@ static int dynamicPaint_doStep(Depsgraph *depsgraph, /* process special brush effects, like smudge */ if (bData->brush_velocity) { - if (surface->type == MOD_DPAINT_SURFACE_T_PAINT && brush->flags & MOD_DPAINT_DO_SMUDGE) + if (surface->type == MOD_DPAINT_SURFACE_T_PAINT && + brush->flags & MOD_DPAINT_DO_SMUDGE) { dynamicPaint_doSmudge(surface, brush, timescale); + } MEM_freeN(bData->brush_velocity); bData->brush_velocity = NULL; } @@ -6208,8 +6340,9 @@ static int dynamicPaint_doStep(Depsgraph *depsgraph, /* Allocate memory for surface previous points to read unchanged values from */ prevPoint = MEM_mallocN(sData->total_points * sizeof(struct PaintPoint), "PaintSurfaceDataCopy"); - if (!prevPoint) + if (!prevPoint) { return setError(canvas, N_("Not enough free memory")); + } /* Prepare effects and get number of required steps */ steps = dynamicPaint_prepareEffectStep(depsgraph, surface, scene, ob, &force, timescale); @@ -6218,10 +6351,12 @@ static int dynamicPaint_doStep(Depsgraph *depsgraph, } /* Free temporary effect data */ - if (prevPoint) + if (prevPoint) { MEM_freeN(prevPoint); - if (force) + } + if (force) { MEM_freeN(force); + } } /* paint island border pixels */ @@ -6259,8 +6394,9 @@ int dynamicPaint_calculateFrame(DynamicPaintSurface *surface, for (st = 1; st <= surface->substeps; st++) { float subframe = ((float)st) / (surface->substeps + 1); - if (!dynamicPaint_doStep(depsgraph, scene, cObject, surface, timescale, subframe)) + if (!dynamicPaint_doStep(depsgraph, scene, cObject, surface, timescale, subframe)) { return 0; + } } } diff --git a/source/blender/blenkernel/intern/editderivedmesh.c b/source/blender/blenkernel/intern/editderivedmesh.c index e2b63b650fb..06f297b23e0 100644 --- a/source/blender/blenkernel/intern/editderivedmesh.c +++ b/source/blender/blenkernel/intern/editderivedmesh.c @@ -61,10 +61,12 @@ static void axis_from_enum_v3(float v[3], const char axis) { zero_v3(v); - if (axis < 3) + if (axis < 3) { v[axis] = 1.0f; - else + } + else { v[axis - 3] = -1.0f; + } } static void statvis_calc_overhang(BMEditMesh *em, @@ -397,7 +399,7 @@ static void statvis_calc_sharp(BMEditMesh *em, BMIter iter; BMesh *bm = em->bm; BMEdge *e; - //float f_no[3]; + // float f_no[3]; const float minmax_irange = 1.0f / (max - min); int i; diff --git a/source/blender/blenkernel/intern/editmesh.c b/source/blender/blenkernel/intern/editmesh.c index 9c412c3c1b0..130f4ae88f1 100644 --- a/source/blender/blenkernel/intern/editmesh.c +++ b/source/blender/blenkernel/intern/editmesh.c @@ -115,8 +115,9 @@ static void editmesh_tessface_calc_intern(BMEditMesh *em) looptris = em->looptris; } else { - if (em->looptris) + if (em->looptris) { MEM_freeN(em->looptris); + } looptris = MEM_mallocN(sizeof(*looptris) * looptris_tot, __func__); } @@ -160,19 +161,23 @@ void BKE_editmesh_free(BMEditMesh *em) BKE_editmesh_color_free(em); - if (em->looptris) + if (em->looptris) { MEM_freeN(em->looptris); + } - if (em->bm) + if (em->bm) { BM_mesh_free(em->bm); + } } void BKE_editmesh_color_free(BMEditMesh *em) { - if (em->derivedVertColor) + if (em->derivedVertColor) { MEM_freeN(em->derivedVertColor); - if (em->derivedFaceColor) + } + if (em->derivedFaceColor) { MEM_freeN(em->derivedFaceColor); + } em->derivedVertColor = NULL; em->derivedFaceColor = NULL; @@ -228,11 +233,11 @@ void BKE_editmesh_lnorspace_update(BMEditMesh *em) BMesh *bm = em->bm; /* We need to create clnors data if none exist yet, otherwise there is no way to edit them. - * Similar code to MESH_OT_customdata_custom_splitnormals_add operator, we want to keep same shading - * in case we were using autosmooth so far... - * Note: there is a problem here, which is that if someone starts a normal editing operation on previously - * autosmooth-ed mesh, and cancel that operation, generated clnors data remain, with related sharp edges - * (and hence autosmooth is 'lost'). + * Similar code to MESH_OT_customdata_custom_splitnormals_add operator, + * we want to keep same shading in case we were using autosmooth so far. + * Note: there is a problem here, which is that if someone starts a normal editing operation on + * previously autosmooth-ed mesh, and cancel that operation, generated clnors data remain, + * with related sharp edges (and hence autosmooth is 'lost'). * Not sure how critical this is, and how to fix that issue? */ if (!CustomData_has_layer(&bm->ldata, CD_CUSTOMLOOPNORMAL)) { Mesh *me = em->ob->data; diff --git a/source/blender/blenkernel/intern/editmesh_bvh.c b/source/blender/blenkernel/intern/editmesh_bvh.c index 31ea8fe581d..f23276d7be0 100644 --- a/source/blender/blenkernel/intern/editmesh_bvh.c +++ b/source/blender/blenkernel/intern/editmesh_bvh.c @@ -316,8 +316,9 @@ BMFace *BKE_bmbvh_ray_cast(BMBVHTree *bmtree, struct RayCastUserData bmcb_data; const float dist = r_dist ? *r_dist : FLT_MAX; - if (bmtree->cos_cage) + if (bmtree->cos_cage) { BLI_assert(!(bmtree->bm->elem_index_dirty & BM_VERT)); + } hit.dist = dist; hit.index = -1; @@ -380,8 +381,9 @@ BMFace *BKE_bmbvh_ray_cast_filter(BMBVHTree *bmtree, bmcb_data_filter.filter_cb = filter_cb; bmcb_data_filter.filter_userdata = filter_userdata; - if (bmtree->cos_cage) + if (bmtree->cos_cage) { BLI_assert(!(bmtree->bm->elem_index_dirty & BM_VERT)); + } hit.dist = dist; hit.index = -1; @@ -445,8 +447,9 @@ BMVert *BKE_bmbvh_find_vert_closest(BMBVHTree *bmtree, const float co[3], const struct VertSearchUserData bmcb_data; const float dist_max_sq = dist_max * dist_max; - if (bmtree->cos_cage) + if (bmtree->cos_cage) { BLI_assert(!(bmtree->bm->elem_index_dirty & BM_VERT)); + } hit.dist_sq = dist_max_sq; hit.index = -1; @@ -505,8 +508,9 @@ struct BMFace *BKE_bmbvh_find_face_closest(BMBVHTree *bmtree, struct FaceSearchUserData bmcb_data; const float dist_max_sq = dist_max * dist_max; - if (bmtree->cos_cage) + if (bmtree->cos_cage) { BLI_assert(!(bmtree->bm->elem_index_dirty & BM_VERT)); + } hit.dist_sq = dist_max_sq; hit.index = -1; diff --git a/source/blender/blenkernel/intern/editmesh_tangent.c b/source/blender/blenkernel/intern/editmesh_tangent.c index 1bfd40c26af..df2fb8c8348 100644 --- a/source/blender/blenkernel/intern/editmesh_tangent.c +++ b/source/blender/blenkernel/intern/editmesh_tangent.c @@ -104,7 +104,7 @@ static void emdm_ts_GetPosition(const SMikkTSpaceContext *pContext, const int face_num, const int vert_index) { - //assert(vert_index >= 0 && vert_index < 4); + // assert(vert_index >= 0 && vert_index < 4); SGLSLEditMeshToTangent *pMesh = pContext->m_pUserData; const BMLoop **lt; const BMLoop *l; @@ -138,7 +138,7 @@ static void emdm_ts_GetTextureCoordinate(const SMikkTSpaceContext *pContext, const int face_num, const int vert_index) { - //assert(vert_index >= 0 && vert_index < 4); + // assert(vert_index >= 0 && vert_index < 4); SGLSLEditMeshToTangent *pMesh = pContext->m_pUserData; const BMLoop **lt; const BMLoop *l; @@ -176,7 +176,7 @@ static void emdm_ts_GetNormal(const SMikkTSpaceContext *pContext, const int face_num, const int vert_index) { - //assert(vert_index >= 0 && vert_index < 4); + // assert(vert_index >= 0 && vert_index < 4); SGLSLEditMeshToTangent *pMesh = pContext->m_pUserData; const BMLoop **lt; const BMLoop *l; @@ -221,7 +221,7 @@ static void emdm_ts_SetTSpace(const SMikkTSpaceContext *pContext, const int face_num, const int vert_index) { - //assert(vert_index >= 0 && vert_index < 4); + // assert(vert_index >= 0 && vert_index < 4); SGLSLEditMeshToTangent *pMesh = pContext->m_pUserData; const BMLoop **lt; const BMLoop *l; @@ -276,7 +276,8 @@ static void emDM_calc_loop_tangents_thread(TaskPool *__restrict UNUSED(pool), /** * \see #BKE_mesh_calc_loop_tangent, same logic but used arrays instead of #BMesh data. * - * \note This function is not so normal, its using `bm->ldata` as input, but output's to `dm->loopData`. + * \note This function is not so normal, its using `bm->ldata` as input, + * but output's to `dm->loopData`. * This is done because #CD_TANGENT is cache data used only for drawing. */ void BKE_editmesh_loop_tangent_calc(BMEditMesh *em, @@ -322,15 +323,18 @@ void BKE_editmesh_loop_tangent_calc(BMEditMesh *em, } } if ((tangent_mask & DM_TANGENT_MASK_ORCO) && - CustomData_get_named_layer_index(loopdata_out, CD_TANGENT, "") == -1) + CustomData_get_named_layer_index(loopdata_out, CD_TANGENT, "") == -1) { CustomData_add_layer_named( loopdata_out, CD_TANGENT, CD_CALLOC, NULL, (int)loopdata_out_len, ""); - if (calc_act && act_uv_name[0]) + } + if (calc_act && act_uv_name[0]) { BKE_mesh_add_loop_tangent_named_layer_for_uv( &bm->ldata, loopdata_out, (int)loopdata_out_len, act_uv_name); - if (calc_ren && ren_uv_name[0]) + } + if (calc_ren && ren_uv_name[0]) { BKE_mesh_add_loop_tangent_named_layer_for_uv( &bm->ldata, loopdata_out, (int)loopdata_out_len, ren_uv_name); + } int totface = em->tottri; #ifdef USE_LOOPTRI_DETECT_QUADS int num_face_as_quad_map; @@ -379,9 +383,8 @@ void BKE_editmesh_loop_tangent_calc(BMEditMesh *em, mesh2tangent->num_face_as_quad_map = num_face_as_quad_map; #endif mesh2tangent->precomputedFaceNormals = poly_normals; - /* Note, we assume we do have tessellated loop normals at this point (in case it is object-enabled), - * have to check this is valid... - */ + /* Note, we assume we do have tessellated loop normals at this point + * (in case it is object-enabled), have to check this is valid. */ mesh2tangent->precomputedLoopNormals = loop_normals; mesh2tangent->cd_loop_uv_offset = CustomData_get_n_offset(&bm->ldata, CD_MLOOPUV, n); @@ -389,8 +392,9 @@ void BKE_editmesh_loop_tangent_calc(BMEditMesh *em, int htype_index = BM_LOOP; if (mesh2tangent->cd_loop_uv_offset == -1) { mesh2tangent->orco = vert_orco; - if (!mesh2tangent->orco) + if (!mesh2tangent->orco) { continue; + } /* needed for orco lookups */ htype_index |= BM_VERT; tangent_mask_curr |= DM_TANGENT_MASK_ORCO; diff --git a/source/blender/blenkernel/intern/effect.c b/source/blender/blenkernel/intern/effect.c index 67b57d6f613..51715c3a223 100644 --- a/source/blender/blenkernel/intern/effect.c +++ b/source/blender/blenkernel/intern/effect.c @@ -171,8 +171,9 @@ static void precalculate_effector(struct Depsgraph *depsgraph, EffectorCache *ef Curve *cu = eff->ob->data; if (cu->flag & CU_PATH) { if (eff->ob->runtime.curve_cache == NULL || eff->ob->runtime.curve_cache->path == NULL || - eff->ob->runtime.curve_cache->path->data == NULL) + eff->ob->runtime.curve_cache->path->data == NULL) { BKE_displist_make_curveTypes(depsgraph, eff->scene, eff->ob, false, false, NULL); + } if (eff->ob->runtime.curve_cache->path && eff->ob->runtime.curve_cache->path->data) { where_on_path( @@ -184,11 +185,13 @@ static void precalculate_effector(struct Depsgraph *depsgraph, EffectorCache *ef } else if (eff->pd->shape == PFIELD_SHAPE_SURFACE) { eff->surmd = (SurfaceModifierData *)modifiers_findByType(eff->ob, eModifierType_Surface); - if (eff->ob->type == OB_CURVE) + if (eff->ob->type == OB_CURVE) { eff->flag |= PE_USE_NORMAL_DATA; + } } - else if (eff->psys) + else if (eff->psys) { psys_update_particle_tree(eff->psys, ctime); + } } static void add_effector_relation(ListBase *relations, @@ -356,11 +359,13 @@ void pd_point_from_particle(ParticleSimulationData *sim, point->size = pa->size; point->charge = 0.0f; - if (part->pd && part->pd->forcefield == PFIELD_CHARGE) + if (part->pd && part->pd->forcefield == PFIELD_CHARGE) { point->charge += part->pd->f_strength; + } - if (part->pd2 && part->pd2->forcefield == PFIELD_CHARGE) + if (part->pd2 && part->pd2->forcefield == PFIELD_CHARGE) { point->charge += part->pd2->f_strength; + } point->vel_to_sec = 1.0f; point->vel_to_frame = psys_get_timestep(sim); @@ -371,8 +376,9 @@ void pd_point_from_particle(ParticleSimulationData *sim, point->ave = state->ave; point->rot = state->rot; } - else + else { point->ave = point->rot = NULL; + } point->psys = sim->psys; } @@ -482,8 +488,9 @@ static float eff_calc_visibility(ListBase *colliders, } } - if (!colliders) + if (!colliders) { BKE_collider_cache_free(&colls); + } return visibility; } @@ -511,14 +518,17 @@ static float falloff_func( float fac, int usemin, float mindist, int usemax, float maxdist, float power) { /* first quick checks */ - if (usemax && fac > maxdist) + if (usemax && fac > maxdist) { return 0.0f; + } - if (usemin && fac < mindist) + if (usemin && fac < mindist) { return 1.0f; + } - if (!usemin) + if (!usemin) { mindist = 0.0; + } return pow((double)(1.0f + fac - mindist), (double)(-power)); } @@ -554,10 +564,12 @@ float effector_falloff(EffectorCache *eff, fac = dot_v3v3(efd->nor, efd->vec_to_point2); - if (eff->pd->zdir == PFIELD_Z_POS && fac < 0.0f) + if (eff->pd->zdir == PFIELD_Z_POS && fac < 0.0f) { falloff = 0.0f; - else if (eff->pd->zdir == PFIELD_Z_NEG && fac > 0.0f) + } + else if (eff->pd->zdir == PFIELD_Z_NEG && fac > 0.0f) { falloff = 0.0f; + } else { switch (eff->pd->falloff) { case PFIELD_FALL_SPHERE: @@ -566,8 +578,9 @@ float effector_falloff(EffectorCache *eff, case PFIELD_FALL_TUBE: falloff *= falloff_func_dist(eff->pd, ABS(fac)); - if (falloff == 0.0f) + if (falloff == 0.0f) { break; + } madd_v3_v3v3fl(temp, efd->vec_to_point2, efd->nor, -fac); r_fac = len_v3(temp); @@ -575,8 +588,9 @@ float effector_falloff(EffectorCache *eff, break; case PFIELD_FALL_CONE: falloff *= falloff_func_dist(eff->pd, ABS(fac)); - if (falloff == 0.0f) + if (falloff == 0.0f) { break; + } r_fac = RAD2DEGF(saacos(fac / len_v3(efd->vec_to_point2))); falloff *= falloff_func_rad(eff->pd, r_fac); @@ -632,8 +646,8 @@ int get_effector_data(EffectorCache *eff, float cfra = DEG_get_ctime(eff->depsgraph); int ret = 0; - /* In case surface object is in Edit mode when loading the .blend, surface modifier is never executed - * and bvhtree never built, see T48415. */ + /* In case surface object is in Edit mode when loading the .blend, + * surface modifier is never executed and bvhtree never built, see T48415. */ if (eff->pd && eff->pd->shape == PFIELD_SHAPE_SURFACE && eff->surmd && eff->surmd->bvhtree) { /* closest point in the object surface is an effector */ float vec[3]; @@ -684,7 +698,7 @@ int get_effector_data(EffectorCache *eff, ret = psys_get_particle_state(&sim, *efd->index, &state, 0); /* TODO */ - //if (eff->pd->forcefiled == PFIELD_HARMONIC && ret==0) { + // if (eff->pd->forcefiled == PFIELD_HARMONIC && ret==0) { // if (pa->dietime < eff->psys->cfra) // eff->flag |= PE_VELOCITY_TO_IMPULSE; //} @@ -736,9 +750,11 @@ int get_effector_data(EffectorCache *eff, sub_v3_v3v3(efd->vec_to_point, point->loc, efd->loc); efd->distance = len_v3(efd->vec_to_point); - /* rest length for harmonic effector, will have to see later if this could be extended to other effectors */ - if (eff->pd && eff->pd->forcefield == PFIELD_HARMONIC && eff->pd->f_size) + /* Rest length for harmonic effector, + * will have to see later if this could be extended to other effectors. */ + if (eff->pd && eff->pd->forcefield == PFIELD_HARMONIC && eff->pd->f_size) { mul_v3_fl(efd->vec_to_point, (efd->distance - eff->pd->f_size) / efd->distance); + } if (eff->flag & PE_USE_NORMAL_DATA) { copy_v3_v3(efd->vec_to_point2, efd->vec_to_point); @@ -810,8 +826,9 @@ static void do_texture_effector(EffectorCache *eff, short mode = eff->pd->tex_mode; bool scene_color_manage; - if (!eff->pd->tex) + if (!eff->pd->tex) { return; + } result[0].nor = result[1].nor = result[2].nor = result[3].nor = NULL; @@ -822,8 +839,9 @@ static void do_texture_effector(EffectorCache *eff, if (eff->pd->flag & PFIELD_TEX_OBJECT) { mul_m4_v3(eff->ob->imat, tex_co); - if (eff->pd->flag & PFIELD_TEX_2D) + if (eff->pd->flag & PFIELD_TEX_2D) { tex_co[2] = 0.0f; + } } else if (eff->pd->flag & PFIELD_TEX_2D) { float fac = -dot_v3v3(tex_co, efd->nor); @@ -955,11 +973,13 @@ static void do_physical_effector(EffectorCache *eff, } break; case PFIELD_MAGNET: - if (ELEM(eff->pd->shape, PFIELD_SHAPE_POINT, PFIELD_SHAPE_LINE)) + if (ELEM(eff->pd->shape, PFIELD_SHAPE_POINT, PFIELD_SHAPE_LINE)) { /* magnetic field of a moving charge */ cross_v3_v3v3(temp, efd->nor, efd->vec_to_point); - else + } + else { copy_v3_v3(temp, efd->nor); + } normalize_v3(temp); mul_v3_fl(temp, strength * efd->falloff); diff --git a/source/blender/blenkernel/intern/fcurve.c b/source/blender/blenkernel/intern/fcurve.c index 4a2a610918c..8c95e4c7ff3 100644 --- a/source/blender/blenkernel/intern/fcurve.c +++ b/source/blender/blenkernel/intern/fcurve.c @@ -81,8 +81,9 @@ static CLG_LogRef LOG = {"bke.fcurve"}; /* Frees the F-Curve itself too, so make sure BLI_remlink is called before calling this... */ void free_fcurve(FCurve *fcu) { - if (fcu == NULL) + if (fcu == NULL) { return; + } /* free curve data */ MEM_SAFE_FREE(fcu->bezt); @@ -105,8 +106,9 @@ void free_fcurves(ListBase *list) FCurve *fcu, *fcn; /* sanity check */ - if (list == NULL) + if (list == NULL) { return; + } /* free data - no need to call remlink before freeing each curve, * as we store reference to next, and freeing only touches the curve @@ -129,8 +131,9 @@ FCurve *copy_fcurve(const FCurve *fcu) FCurve *fcu_d; /* sanity check */ - if (fcu == NULL) + if (fcu == NULL) { return NULL; + } /* make a copy */ fcu_d = MEM_dupallocN(fcu); @@ -161,8 +164,9 @@ void copy_fcurves(ListBase *dst, ListBase *src) FCurve *dfcu, *sfcu; /* sanity checks */ - if (ELEM(NULL, dst, src)) + if (ELEM(NULL, dst, src)) { return; + } /* clear destination list first */ BLI_listbase_clear(dst); @@ -189,12 +193,14 @@ FCurve *id_data_find_fcurve( PropertyRNA *prop; char *path; - if (r_driven) + if (r_driven) { *r_driven = false; + } /* only use the current action ??? */ - if (ELEM(NULL, adt, adt->action)) + if (ELEM(NULL, adt, adt->action)) { return NULL; + } RNA_pointer_create(id, type, data, &ptr); prop = RNA_struct_find_property(&ptr, prop_name); @@ -204,14 +210,16 @@ FCurve *id_data_find_fcurve( if (path) { /* animation takes priority over drivers */ - if ((adt->action) && (adt->action->curves.first)) + if ((adt->action) && (adt->action->curves.first)) { fcu = list_find_fcurve(&adt->action->curves, path, index); + } /* if not animated, check if driven */ if ((fcu == NULL) && (adt->drivers.first)) { fcu = list_find_fcurve(&adt->drivers, path, index); - if (fcu && r_driven) + if (fcu && r_driven) { *r_driven = true; + } fcu = NULL; } @@ -222,22 +230,25 @@ FCurve *id_data_find_fcurve( return fcu; } -/* Find the F-Curve affecting the given RNA-access path + index, in the list of F-Curves provided */ +/* Find the F-Curve affecting the given RNA-access path + index, + * in the list of F-Curves provided. */ FCurve *list_find_fcurve(ListBase *list, const char rna_path[], const int array_index) { FCurve *fcu; /* sanity checks */ - if (ELEM(NULL, list, rna_path) || (array_index < 0)) + if (ELEM(NULL, list, rna_path) || (array_index < 0)) { return NULL; + } /* check paths of curves, then array indices... */ for (fcu = list->first; fcu; fcu = fcu->next) { /* simple string-compare (this assumes that they have the same root...) */ if (fcu->rna_path && STREQ(fcu->rna_path, rna_path)) { /* now check indices */ - if (fcu->array_index == array_index) + if (fcu->array_index == array_index) { return fcu; + } } } @@ -251,8 +262,9 @@ FCurve *iter_step_fcurve(FCurve *fcu_iter, const char rna_path[]) FCurve *fcu; /* sanity checks */ - if (ELEM(NULL, fcu_iter, rna_path)) + if (ELEM(NULL, fcu_iter, rna_path)) { return NULL; + } /* check paths of curves, then array indices... */ for (fcu = fcu_iter; fcu; fcu = fcu->next) { @@ -266,7 +278,10 @@ FCurve *iter_step_fcurve(FCurve *fcu_iter, const char rna_path[]) return NULL; } -/* Get list of LinkData's containing pointers to the F-Curves which control the types of data indicated +/** + * Get list of LinkData's containing pointers to the F-Curves + * which control the types of data indicated. + * * Lists... * - dst: list of LinkData's matching the criteria returned. * List must be freed after use, and is assumed to be empty when passed. @@ -284,10 +299,12 @@ int list_find_data_fcurves(ListBase *dst, int matches = 0; /* sanity checks */ - if (ELEM(NULL, dst, src, dataPrefix, dataName)) + if (ELEM(NULL, dst, src, dataPrefix, dataName)) { return 0; - else if ((dataPrefix[0] == 0) || (dataName[0] == 0)) + } + else if ((dataPrefix[0] == 0) || (dataName[0] == 0)) { return 0; + } /* search each F-Curve one by one */ for (fcu = src->first; fcu; fcu = fcu->next) { @@ -343,10 +360,12 @@ FCurve *rna_get_fcurve_context_ui(bContext *C, *r_driven = false; *r_special = false; - if (r_animdata) + if (r_animdata) { *r_animdata = NULL; - if (r_action) + } + if (r_action) { *r_action = NULL; + } /* Special case for NLA Control Curves... */ if (BKE_nlastrip_has_curves_for_property(ptr, prop)) { @@ -365,9 +384,9 @@ FCurve *rna_get_fcurve_context_ui(bContext *C, /* there must be some RNA-pointer + property combon */ if (prop && tptr.id.data && RNA_property_animateable(&tptr, prop)) { AnimData *adt = BKE_animdata_from_id(tptr.id.data); - int step = - C ? 2 : - 1; /* Always 1 in case we have no context (can't check in 'ancestors' of given RNA ptr). */ + 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) { @@ -390,8 +409,9 @@ FCurve *rna_get_fcurve_context_ui(bContext *C, if (adt->action && adt->action->curves.first) { fcu = list_find_fcurve(&adt->action->curves, path, rnaindex); - if (fcu && r_action) + if (fcu && r_action) { *r_action = adt->action; + } } /* if not animated, check if driven */ @@ -399,15 +419,17 @@ FCurve *rna_get_fcurve_context_ui(bContext *C, fcu = list_find_fcurve(&adt->drivers, path, rnaindex); if (fcu) { - if (r_animdata) + if (r_animdata) { *r_animdata = adt; + } *r_driven = true; } } if (fcu && r_action) { - if (r_animdata) + if (r_animdata) { *r_animdata = adt; + } *r_action = adt->action; break; } @@ -433,7 +455,8 @@ FCurve *rna_get_fcurve_context_ui(bContext *C, /* ----------------- Finding Keyframes/Extents -------------------------- */ -/* Binary search algorithm for finding where to insert BezTriple, with optional argument for precision required. +/* Binary search algorithm for finding where to insert BezTriple, + * with optional argument for precision required. * Returns the index to insert at (data already at that index will be offset if replace is 0) */ static int binarysearch_bezt_index_ex( @@ -463,8 +486,9 @@ static int binarysearch_bezt_index_ex( *r_replace = true; return 0; } - else if (frame < framenum) + else if (frame < framenum) { return 0; + } /* 'Last' Keyframe */ framenum = array[(arraylen - 1)].vec[1][0]; @@ -472,8 +496,9 @@ static int binarysearch_bezt_index_ex( *r_replace = true; return (arraylen - 1); } - else if (frame > framenum) + else if (frame > framenum) { return arraylen; + } } /* most of the time, this loop is just to find where to put it @@ -492,10 +517,12 @@ static int binarysearch_bezt_index_ex( } /* repeat in upper/lower half */ - if (frame > midfra) + if (frame > midfra) { start = mid + 1; - else if (frame < midfra) + } + else if (frame < midfra) { end = mid - 1; + } } /* print error if loop-limit exceeded */ @@ -539,8 +566,9 @@ static short get_fcurve_end_keyframes(FCurve *fcu, *last = NULL; /* sanity checks */ - if (fcu->bezt == NULL) + if (fcu->bezt == NULL) { return found; + } /* only include selected items? */ if (do_sel_only) { @@ -625,8 +653,8 @@ bool calc_fcurve_bounds(FCurve *fcu, if (include_handles) { /* left handle - only if applicable - * NOTE: for the very first keyframe, the left handle actually has no bearings on anything - */ + * NOTE: for the very first keyframe, + * the left handle actually has no bearings on anything. */ if (prevbezt && (prevbezt->ipo == BEZT_IPO_BEZ)) { yminv = min_ff(yminv, bezt->vec[0][1]); ymaxv = max_ff(ymaxv, bezt->vec[0][1]); @@ -656,10 +684,12 @@ bool calc_fcurve_bounds(FCurve *fcu, FPoint *fpt; for (fpt = fcu->fpt, i = 0; i < fcu->totvert; fpt++, i++) { - if (fpt->vec[1] < yminv) + if (fpt->vec[1] < yminv) { yminv = fpt->vec[1]; - if (fpt->vec[1] > ymaxv) + } + if (fpt->vec[1] > ymaxv) { ymaxv = fpt->vec[1]; + } foundvert = true; } @@ -668,29 +698,38 @@ bool calc_fcurve_bounds(FCurve *fcu, } if (foundvert) { - if (xmin) + if (xmin) { *xmin = xminv; - if (xmax) + } + if (xmax) { *xmax = xmaxv; + } - if (ymin) + if (ymin) { *ymin = yminv; - if (ymax) + } + if (ymax) { *ymax = ymaxv; + } } else { - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("F-Curve calc bounds didn't find anything, so assuming minimum bounds of 1.0\n"); + } - if (xmin) + if (xmin) { *xmin = 0.0f; - if (xmax) + } + if (xmax) { *xmax = 1.0f; + } - if (ymin) + if (ymin) { *ymin = 0.0f; - if (ymax) + } + if (ymax) { *ymax = 1.0f; + } } return foundvert; @@ -753,12 +792,14 @@ bool calc_fcurve_range( bool fcurve_are_keyframes_usable(FCurve *fcu) { /* F-Curve must exist */ - if (fcu == NULL) + if (fcu == NULL) { return false; + } /* F-Curve must not have samples - samples are mutually exclusive of keyframes */ - if (fcu->fpt) + if (fcu->fpt) { return false; + } /* if it has modifiers, none of these should "drastically" alter the curve */ if (fcu->modifiers.first) { @@ -768,8 +809,9 @@ bool fcurve_are_keyframes_usable(FCurve *fcu) /* TODO: optionally, only check modifier if it is the active one... */ for (fcm = fcu->modifiers.last; fcm; fcm = fcm->prev) { /* ignore if muted/disabled */ - if (fcm->flag & (FMODIFIER_FLAG_DISABLED | FMODIFIER_FLAG_MUTED)) + if (fcm->flag & (FMODIFIER_FLAG_DISABLED | FMODIFIER_FLAG_MUTED)) { continue; + } /* type checks */ switch (fcm->type) { @@ -783,15 +825,17 @@ bool fcurve_are_keyframes_usable(FCurve *fcu) case FMODIFIER_TYPE_GENERATOR: { FMod_Generator *data = (FMod_Generator *)fcm->data; - if ((data->flag & FCM_GENERATOR_ADDITIVE) == 0) + if ((data->flag & FCM_GENERATOR_ADDITIVE) == 0) { return false; + } break; } case FMODIFIER_TYPE_FN_GENERATOR: { FMod_FunctionGenerator *data = (FMod_FunctionGenerator *)fcm->data; - if ((data->flag & FCM_GENERATOR_ADDITIVE) == 0) + if ((data->flag & FCM_GENERATOR_ADDITIVE) == 0) { return false; + } break; } /* always harmful - cannot allow */ @@ -816,12 +860,14 @@ bool BKE_fcurve_is_protected(FCurve *fcu) bool fcurve_is_keyframable(FCurve *fcu) { /* F-Curve's keyframes must be "usable" (i.e. visible + have an effect on final result) */ - if (fcurve_are_keyframes_usable(fcu) == 0) + if (fcurve_are_keyframes_usable(fcu) == 0) { return false; + } /* F-Curve must currently be editable too */ - if (BKE_fcurve_is_protected(fcu)) + if (BKE_fcurve_is_protected(fcu)) { return false; + } /* F-Curve is keyframable */ return true; @@ -837,21 +883,25 @@ void bezt_add_to_cfra_elem(ListBase *lb, BezTriple *bezt) for (ce = lb->first; ce; ce = ce->next) { /* double key? */ if (IS_EQT(ce->cfra, bezt->vec[1][0], BEZT_BINARYSEARCH_THRESH)) { - if (bezt->f2 & SELECT) + if (bezt->f2 & SELECT) { ce->sel = bezt->f2; + } return; } /* should key be inserted before this column? */ - else if (ce->cfra > bezt->vec[1][0]) + else if (ce->cfra > bezt->vec[1][0]) { break; + } } /* create a new column */ cen = MEM_callocN(sizeof(CfraElem), "add_to_cfra_elem"); - if (ce) + if (ce) { BLI_insertlinkbefore(lb, ce, cen); - else + } + else { BLI_addtail(lb, cen); + } cen->cfra = bezt->vec[1][0]; cen->sel = bezt->f2; @@ -901,10 +951,12 @@ void fcurve_store_samples(FCurve *fcu, void *data, int start, int end, FcuSample } /* free any existing sample/keyframe data on curve */ - if (fcu->bezt) + if (fcu->bezt) { MEM_freeN(fcu->bezt); - if (fcu->fpt) + } + if (fcu->fpt) { MEM_freeN(fcu->fpt); + } /* store the samples */ fcu->bezt = NULL; @@ -952,28 +1004,32 @@ eFCU_Cycle_Type BKE_fcurve_get_cycle_type(FCurve *fcu) return FCU_CYCLE_NONE; } -/* Checks if the F-Curve has a Cycles modifier with simple settings that warrant transition smoothing */ +/* Checks if the F-Curve has a Cycles modifier with simple settings + * that warrant transition smoothing. */ bool BKE_fcurve_is_cyclic(FCurve *fcu) { return BKE_fcurve_get_cycle_type(fcu) != FCU_CYCLE_NONE; } -/* Shifts 'in' by the difference in coordinates between 'to' and 'from', using 'out' as the output buffer. +/* Shifts 'in' by the difference in coordinates between 'to' and 'from', + * using 'out' as the output buffer. * When 'to' and 'from' are end points of the loop, this moves the 'in' point one loop cycle. */ static BezTriple *cycle_offset_triple( bool cycle, BezTriple *out, const BezTriple *in, const BezTriple *from, const BezTriple *to) { - if (!cycle) + if (!cycle) { return NULL; + } memcpy(out, in, sizeof(BezTriple)); float delta[3]; sub_v3_v3v3(delta, to->vec[1], from->vec[1]); - for (int i = 0; i < 3; i++) + for (int i = 0; i < 3; i++) { add_v3_v3(out->vec[i], delta); + } return out; } @@ -991,8 +1047,9 @@ void calchandles_fcurve(FCurve *fcu) * - need bezier keys * - only bezier-interpolation has handles (for now) */ - if (ELEM(NULL, fcu, fcu->bezt) || (a < 2) /*|| ELEM(fcu->ipo, BEZT_IPO_CONST, BEZT_IPO_LIN)*/) + if (ELEM(NULL, fcu, fcu->bezt) || (a < 2) /*|| ELEM(fcu->ipo, BEZT_IPO_CONST, BEZT_IPO_LIN)*/) { return; + } /* if the first modifier is Cycles, smooth the curve through the cycle */ BezTriple *first = &fcu->bezt[0], *last = &fcu->bezt[fcu->totvert - 1]; @@ -1008,10 +1065,12 @@ void calchandles_fcurve(FCurve *fcu) /* loop over all beztriples, adjusting handles */ while (a--) { /* clamp timing of handles to be on either side of beztriple */ - if (bezt->vec[0][0] > bezt->vec[1][0]) + if (bezt->vec[0][0] > bezt->vec[1][0]) { bezt->vec[0][0] = bezt->vec[1][0]; - if (bezt->vec[2][0] < bezt->vec[1][0]) + } + if (bezt->vec[2][0] < bezt->vec[1][0]) { bezt->vec[2][0] = bezt->vec[1][0]; + } /* calculate auto-handles */ BKE_nurb_handle_calc(bezt, prev, next, true, fcu->auto_smoothing); @@ -1066,8 +1125,9 @@ void testhandles_fcurve(FCurve *fcu, const bool use_handle) unsigned int a; /* only beztriples have handles (bpoints don't though) */ - if (ELEM(NULL, fcu, fcu->bezt)) + if (ELEM(NULL, fcu, fcu->bezt)) { return; + } /* loop over beztriples */ for (a = 0, bezt = fcu->bezt; a < fcu->totvert; a++, bezt++) { @@ -1126,8 +1186,9 @@ short test_time_fcurve(FCurve *fcu) unsigned int a; /* sanity checks */ - if (fcu == NULL) + if (fcu == NULL) { return 0; + } /* currently, only need to test beztriples */ if (fcu->bezt) { @@ -1135,8 +1196,9 @@ short test_time_fcurve(FCurve *fcu) /* loop through all BezTriples, stopping when one exceeds the one after it */ for (a = 0, bezt = fcu->bezt; a < (fcu->totvert - 1); a++, bezt++) { - if (bezt->vec[1][0] > (bezt + 1)->vec[1][0]) + if (bezt->vec[1][0] > (bezt + 1)->vec[1][0]) { return 1; + } } } else if (fcu->fpt) { @@ -1144,8 +1206,9 @@ short test_time_fcurve(FCurve *fcu) /* loop through all FPoints, stopping when one exceeds the one after it */ for (a = 0, fpt = fcu->fpt; a < (fcu->totvert - 1); a++, fpt++) { - if (fpt->vec[0] > (fpt + 1)->vec[0]) + if (fpt->vec[0] > (fpt + 1)->vec[0]) { return 1; + } } } @@ -1178,12 +1241,16 @@ typedef struct DriverVarTypeInfo { static ID *dtar_id_ensure_proxy_from(ID *id) { - if (id && GS(id->name) == ID_OB && ((Object *)id)->proxy_from) + if (id && GS(id->name) == ID_OB && ((Object *)id)->proxy_from) { return (ID *)(((Object *)id)->proxy_from); + } return id; } -/* Helper function to obtain a value using RNA from the specified source (for evaluating drivers) */ +/** + * Helper function to obtain a value using RNA from the specified source + * (for evaluating drivers). + */ static float dtar_get_prop_val(ChannelDriver *driver, DriverTarget *dtar) { PointerRNA id_ptr, ptr; @@ -1193,8 +1260,9 @@ static float dtar_get_prop_val(ChannelDriver *driver, DriverTarget *dtar) float value = 0.0f; /* sanity check */ - if (ELEM(NULL, driver, dtar)) + if (ELEM(NULL, driver, dtar)) { return 0.0f; + } id = dtar_id_ensure_proxy_from(dtar->id); @@ -1301,8 +1369,9 @@ bool driver_get_variable_property(ChannelDriver *driver, int index = -1; /* sanity check */ - if (ELEM(NULL, driver, dtar)) + if (ELEM(NULL, driver, dtar)) { return false; + } id = dtar_id_ensure_proxy_from(dtar->id); @@ -1703,10 +1772,12 @@ static DriverVarTypeInfo dvar_types[MAX_DVAR_TYPES] = { static const DriverVarTypeInfo *get_dvar_typeinfo(int type) { /* check if valid type */ - if ((type >= 0) && (type < MAX_DVAR_TYPES)) + if ((type >= 0) && (type < MAX_DVAR_TYPES)) { return &dvar_types[type]; - else + } + else { return NULL; + } } /* Driver API --------------------------------- */ @@ -1715,8 +1786,9 @@ static const DriverVarTypeInfo *get_dvar_typeinfo(int type) void driver_free_variable(ListBase *variables, DriverVar *dvar) { /* sanity checks */ - if (dvar == NULL) + if (dvar == NULL) { return; + } /* free target vars * - need to go over all of them, not just up to the ones that are used @@ -1725,8 +1797,9 @@ void driver_free_variable(ListBase *variables, DriverVar *dvar) */ DRIVER_TARGETS_LOOPER_BEGIN (dvar) { /* free RNA path if applicable */ - if (dtar->rna_path) + if (dtar->rna_path) { MEM_freeN(dtar->rna_path); + } } DRIVER_TARGETS_LOOPER_END; @@ -1754,8 +1827,9 @@ void driver_variables_copy(ListBase *dst_vars, const ListBase *src_vars) /* need to go over all targets so that we don't leave any dangling paths */ DRIVER_TARGETS_LOOPER_BEGIN (dvar) { /* make a copy of target's rna path if available */ - if (dtar->rna_path) + if (dtar->rna_path) { dtar->rna_path = MEM_dupallocN(dtar->rna_path); + } } DRIVER_TARGETS_LOOPER_END; } @@ -1767,8 +1841,9 @@ void driver_change_variable_type(DriverVar *dvar, int type) const DriverVarTypeInfo *dvti = get_dvar_typeinfo(type); /* sanity check */ - if (ELEM(NULL, dvar, dvti)) + if (ELEM(NULL, dvar, dvti)) { return; + } /* set the new settings */ dvar->type = type; @@ -1784,8 +1859,9 @@ void driver_change_variable_type(DriverVar *dvar, int type) dtar->flag = flags; /* object ID types only, or idtype not yet initialized */ - if ((flags & DTAR_FLAG_ID_OB_ONLY) || (dtar->idtype == 0)) + if ((flags & DTAR_FLAG_ID_OB_ONLY) || (dtar->idtype == 0)) { dtar->idtype = ID_OB; + } } DRIVER_TARGETS_LOOPER_END; } @@ -1800,8 +1876,9 @@ void driver_variable_name_validate(DriverVar *dvar) }; /* sanity checks */ - if (dvar == NULL) + if (dvar == NULL) { return; + } /* clear all invalid-name flags */ dvar->flag &= ~DVAR_ALL_INVALID_FLAGS; @@ -1812,12 +1889,14 @@ void driver_variable_name_validate(DriverVar *dvar) } /* 1) Must start with a letter */ - /* XXX: We assume that valid unicode letters in other languages are ok too, hence the blacklisting */ + /* XXX: We assume that valid unicode letters in other languages are ok too, + * hence the blacklisting. */ if (IN_RANGE_INCL(dvar->name[0], '0', '9')) { dvar->flag |= DVAR_FLAG_INVALID_START_NUM; } else if (dvar->name[0] == '_') { - /* NOTE: We don't allow names to start with underscores (i.e. it helps when ruling out security risks) */ + /* NOTE: We don't allow names to start with underscores + * (i.e. it helps when ruling out security risks) */ dvar->flag |= DVAR_FLAG_INVALID_START_CHAR; } @@ -1833,10 +1912,12 @@ void driver_variable_name_validate(DriverVar *dvar) for (int i = 0; i < sizeof(special_char_blacklist); i++) { char *match = strchr(dvar->name, special_char_blacklist[i]); - if (match == dvar->name) + if (match == dvar->name) { dvar->flag |= DVAR_FLAG_INVALID_START_CHAR; - else if (match != NULL) + } + else if (match != NULL) { dvar->flag |= DVAR_FLAG_INVALID_HAS_SPECIAL; + } } /* 4) Check if the name is a reserved keyword @@ -1850,8 +1931,9 @@ void driver_variable_name_validate(DriverVar *dvar) #endif /* If any these conditions match, the name is invalid */ - if (dvar->flag & DVAR_ALL_INVALID_FLAGS) + if (dvar->flag & DVAR_ALL_INVALID_FLAGS) { dvar->flag |= DVAR_FLAG_INVALID_NAME; + } } /* Add a new driver variable */ @@ -1860,8 +1942,9 @@ DriverVar *driver_add_new_variable(ChannelDriver *driver) DriverVar *dvar; /* sanity checks */ - if (driver == NULL) + if (driver == NULL) { return NULL; + } /* make a new variable */ dvar = MEM_callocN(sizeof(DriverVar), "DriverVar"); @@ -1893,8 +1976,9 @@ void fcurve_free_driver(FCurve *fcu) DriverVar *dvar, *dvarn; /* sanity checks */ - if (ELEM(NULL, fcu, fcu->driver)) + if (ELEM(NULL, fcu, fcu->driver)) { return; + } driver = fcu->driver; /* free driver targets */ @@ -1905,13 +1989,15 @@ void fcurve_free_driver(FCurve *fcu) #ifdef WITH_PYTHON /* free compiled driver expression */ - if (driver->expr_comp) + if (driver->expr_comp) { BPY_DECREF(driver->expr_comp); + } #endif BLI_expr_pylike_free(driver->expr_simple); - /* free driver itself, then set F-Curve's point to this to NULL (as the curve may still be used) */ + /* Free driver itself, then set F-Curve's point to this to NULL + * (as the curve may still be used). */ MEM_freeN(driver); fcu->driver = NULL; } @@ -1922,8 +2008,9 @@ ChannelDriver *fcurve_copy_driver(const ChannelDriver *driver) ChannelDriver *ndriver; /* sanity checks */ - if (driver == NULL) + if (driver == NULL) { return NULL; + } /* copy all data */ ndriver = MEM_dupallocN(driver); @@ -1931,9 +2018,9 @@ ChannelDriver *fcurve_copy_driver(const ChannelDriver *driver) ndriver->expr_simple = NULL; /* copy variables */ - BLI_listbase_clear( - &ndriver - ->variables); /* to get rid of refs to non-copied data (that's still used on original) */ + + /* to get rid of refs to non-copied data (that's still used on original) */ + BLI_listbase_clear(&ndriver->variables); driver_variables_copy(&ndriver->variables, &driver->variables); /* return the new driver */ @@ -2074,8 +2161,9 @@ float driver_get_variable_value(ChannelDriver *driver, DriverVar *dvar) const DriverVarTypeInfo *dvti; /* sanity check */ - if (ELEM(NULL, driver, dvar)) + if (ELEM(NULL, driver, dvar)) { return 0.0f; + } /* call the relevant callbacks to get the variable value * using the variable type info, storing the obtained value @@ -2083,10 +2171,12 @@ float driver_get_variable_value(ChannelDriver *driver, DriverVar *dvar) */ dvti = get_dvar_typeinfo(dvar->type); - if (dvti && dvti->get_value) + if (dvti && dvti->get_value) { dvar->curval = dvti->get_value(driver, dvar); - else + } + else { dvar->curval = 0.0f; + } return dvar->curval; } @@ -2104,8 +2194,9 @@ float evaluate_driver(PathResolvedRNA *anim_rna, DriverVar *dvar; /* check if driver can be evaluated */ - if (driver_orig->flag & DRIVER_FLAG_INVALID) + if (driver_orig->flag & DRIVER_FLAG_INVALID) { return 0.0f; + } switch (driver->type) { case DRIVER_TYPE_AVERAGE: /* average values of driver targets */ @@ -2129,10 +2220,12 @@ float evaluate_driver(PathResolvedRNA *anim_rna, } /* perform operations on the total if appropriate */ - if (driver->type == DRIVER_TYPE_AVERAGE) + if (driver->type == DRIVER_TYPE_AVERAGE) { driver->curval = tot ? (value / (float)tot) : 0.0f; - else + } + else { driver->curval = value; + } } break; } @@ -2151,13 +2244,15 @@ float evaluate_driver(PathResolvedRNA *anim_rna, /* check if greater/smaller than the baseline */ if (driver->type == DRIVER_TYPE_MAX) { /* max? */ - if (tmp_val > value) + if (tmp_val > value) { value = tmp_val; + } } else { /* min? */ - if (tmp_val < value) + if (tmp_val < value) { value = tmp_val; + } } } else { @@ -2232,8 +2327,9 @@ void correct_bezpart(float v1[2], float v2[2], float v3[2], float v4[2]) len2 = fabsf(h2[0]); /* if the handles have no length, no need to do any corrections */ - if ((len1 + len2) == 0.0f) + if ((len1 + len2) == 0.0f) { return; + } /* the two handles cross over each other, so force them * apart using the proportion they overlap @@ -2274,23 +2370,28 @@ static int findzero(float x, float q0, float q1, float q2, float q3, float *o) t = sqrt(d); o[0] = (float)(sqrt3d(-q + t) + sqrt3d(-q - t) - a); - if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) + if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) { return 1; - else + } + else { return 0; + } } else if (d == 0.0) { t = sqrt3d(-q); o[0] = (float)(2 * t - a); - if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) + if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) { nr++; + } o[nr] = (float)(-t - a); - if ((o[nr] >= (float)SMALL) && (o[nr] <= 1.000001f)) + if ((o[nr] >= (float)SMALL) && (o[nr] <= 1.000001f)) { return nr + 1; - else + } + else { return nr; + } } else { phi = acos(-q / sqrt(-(p * p * p))); @@ -2299,18 +2400,22 @@ static int findzero(float x, float q0, float q1, float q2, float q3, float *o) q = sqrt(3 - 3 * p * p); o[0] = (float)(2 * t * p - a); - if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) + if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) { nr++; + } o[nr] = (float)(-t * (p + q) - a); - if ((o[nr] >= (float)SMALL) && (o[nr] <= 1.000001f)) + if ((o[nr] >= (float)SMALL) && (o[nr] <= 1.000001f)) { nr++; + } o[nr] = (float)(-t * (p - q) - a); - if ((o[nr] >= (float)SMALL) && (o[nr] <= 1.000001f)) + if ((o[nr] >= (float)SMALL) && (o[nr] <= 1.000001f)) { return nr + 1; - else + } + else { return nr; + } } } else { @@ -2326,30 +2431,37 @@ static int findzero(float x, float q0, float q1, float q2, float q3, float *o) p = sqrt(p); o[0] = (float)((-b - p) / (2 * a)); - if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) + if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) { nr++; + } o[nr] = (float)((-b + p) / (2 * a)); - if ((o[nr] >= (float)SMALL) && (o[nr] <= 1.000001f)) + if ((o[nr] >= (float)SMALL) && (o[nr] <= 1.000001f)) { return nr + 1; - else + } + else { return nr; + } } else if (p == 0) { o[0] = (float)(-b / (2 * a)); - if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) + if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) { return 1; - else + } + else { return 0; + } } } else if (b != 0.0) { o[0] = (float)(-c / b); - if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) + if ((o[0] >= (float)SMALL) && (o[0] <= 1.000001f)) { return 1; - else + } + else { return 0; + } } else if (c == 0.0) { o[0] = 0.0; @@ -2504,14 +2616,14 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime /* Use binary search to find appropriate keyframes... * * The threshold here has the following constraints: - * - 0.001 is too coarse -> We get artifacts with 2cm driver movements at 1BU = 1m (see T40332) - * - 0.00001 is too fine -> Weird errors, like selecting the wrong keyframe range (see T39207), occur. - * This lower bound was established in b888a32eee8147b028464336ad2404d8155c64dd + * - 0.001 is too coarse: + * We get artifacts with 2cm driver movements at 1BU = 1m (see T40332) + * + * - 0.00001 is too fine: + * Weird errors, like selecting the wrong keyframe range (see T39207), occur. + * This lower bound was established in b888a32eee8147b028464336ad2404d8155c64dd. */ a = binarysearch_bezt_index_ex(bezts, evaltime, fcu->totvert, 0.0001, &exact); - if (G.debug & G_DEBUG) - printf( - "eval fcurve '%s' - %f => %u/%u, %d\n", fcu->rna_path, evaltime, a, fcu->totvert, exact); if (exact) { /* index returned must be interpreted differently when it sits on top of an existing keyframe @@ -2528,7 +2640,8 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime prevbezt = (a > 0) ? (bezt - 1) : bezt; } - /* use if the key is directly on the frame, rare cases this is needed else we get 0.0 instead. */ + /* use if the key is directly on the frame, + * rare cases this is needed else we get 0.0 instead. */ /* XXX: consult T39207 for examples of files where failure of these checks can cause issues */ if (exact) { cvalue = prevbezt->vec[1][1]; @@ -2586,13 +2699,14 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime /* break; */ } else { - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf(" ERROR: findzero() failed at %f with %f %f %f %f\n", evaltime, v1[0], v2[0], v3[0], v4[0]); + } } } break; @@ -2795,12 +2909,13 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime } } else { - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf(" ERROR: failed eval - p=%f b=%f, t=%f (%f)\n", prevbezt->vec[1][0], bezt->vec[1][0], evaltime, fabsf(bezt->vec[1][0] - evaltime)); + } } } @@ -2834,10 +2949,12 @@ static float fcurve_eval_samples(FCurve *fcu, FPoint *fpts, float evaltime) fpt = prevfpt + ((int)evaltime - (int)prevfpt->vec[0]); /* if not exactly on the frame, perform linear interpolation with the next one */ - if ((t != 0.0f) && (t < 1.0f)) + if ((t != 0.0f) && (t < 1.0f)) { cvalue = interpf(fpt->vec[1], (fpt + 1)->vec[1], 1.0f - t); - else + } + else { cvalue = fpt->vec[1]; + } } /* return value */ @@ -2851,32 +2968,36 @@ static float fcurve_eval_samples(FCurve *fcu, FPoint *fpts, float evaltime) */ static float evaluate_fcurve_ex(FCurve *fcu, float evaltime, float cvalue) { - FModifierStackStorage *storage; float devaltime; /* evaluate modifiers which modify time to evaluate the base curve at */ - storage = evaluate_fmodifiers_storage_new(&fcu->modifiers); - devaltime = evaluate_time_fmodifiers(storage, &fcu->modifiers, fcu, cvalue, evaltime); + FModifiersStackStorage storage; + storage.modifier_count = BLI_listbase_count(&fcu->modifiers); + storage.size_per_modifier = evaluate_fmodifiers_storage_size_per_modifier(&fcu->modifiers); + storage.buffer = alloca(storage.modifier_count * storage.size_per_modifier); + + devaltime = evaluate_time_fmodifiers(&storage, &fcu->modifiers, fcu, cvalue, evaltime); /* evaluate curve-data * - 'devaltime' instead of 'evaltime', as this is the time that the last time-modifying * F-Curve modifier on the stack requested the curve to be evaluated at */ - if (fcu->bezt) + if (fcu->bezt) { cvalue = fcurve_eval_keyframes(fcu, fcu->bezt, devaltime); - else if (fcu->fpt) + } + else if (fcu->fpt) { cvalue = fcurve_eval_samples(fcu, fcu->fpt, devaltime); + } /* evaluate modifiers */ - evaluate_value_fmodifiers(storage, &fcu->modifiers, fcu, &cvalue, devaltime); - - evaluate_fmodifiers_storage_free(storage); + evaluate_value_fmodifiers(&storage, &fcu->modifiers, fcu, &cvalue, devaltime); /* if curve can only have integral values, perform truncation (i.e. drop the decimal part) * here so that the curve can be sampled correctly */ - if (fcu->flag & FCURVE_INT_VALUES) + if (fcu->flag & FCURVE_INT_VALUES) { cvalue = floorf(cvalue + 0.5f); + } /* return evaluated value */ return cvalue; @@ -2905,9 +3026,9 @@ float evaluate_fcurve_driver(PathResolvedRNA *anim_rna, BLI_assert(fcu->driver != NULL); float cvalue = 0.0f; - /* if there is a driver (only if this F-Curve is acting as 'driver'), evaluate it to find value to use as "evaltime" - * since drivers essentially act as alternative input (i.e. in place of 'time') for F-Curves - */ + /* If there is a driver (only if this F-Curve is acting as 'driver'), + * evaluate it to find value to use as "evaltime" since drivers essentially act as alternative + * input (i.e. in place of 'time') for F-Curves. */ if (fcu->driver) { /* evaltime now serves as input for the curve */ evaltime = evaluate_driver(anim_rna, fcu->driver, driver_orig, evaltime); @@ -2924,12 +3045,12 @@ float evaluate_fcurve_driver(PathResolvedRNA *anim_rna, /* if there are range-restrictions, we must definitely block [#36950] */ if ((fcm->flag & FMODIFIER_FLAG_RANGERESTRICT) == 0 || ((fcm->sfra <= evaltime) && (fcm->efra >= evaltime))) { - /* within range: here it probably doesn't matter, though we'd want to check on additive... */ + /* Within range: here it probably doesn't matter, + * though we'd want to check on additive. */ } else { - /* outside range: modifier shouldn't contribute to the curve here, though it does in other areas, - * so neither should the driver! - */ + /* Outside range: modifier shouldn't contribute to the curve here, + * though it does in other areas, so neither should the driver! */ do_linear = false; } } diff --git a/source/blender/blenkernel/intern/fmodifier.c b/source/blender/blenkernel/intern/fmodifier.c index d54a3bdaa37..c6188642e41 100644 --- a/source/blender/blenkernel/intern/fmodifier.c +++ b/source/blender/blenkernel/intern/fmodifier.c @@ -48,11 +48,6 @@ static CLG_LogRef LOG = {"bke.fmodifier"}; /* ******************************** F-Modifiers ********************************* */ -/* Forward declarations. */ -void fmodifiers_storage_put(FModifierStackStorage *storage, FModifier *fcm, void *data); -void fmodifiers_storage_remove(FModifierStackStorage *storage, FModifier *fcm); -void *fmodifiers_storage_get(FModifierStackStorage *storage, FModifier *fcm); - /* Info ------------------------------- */ /* F-Modifiers are modifiers which operate on F-Curves. However, they can also be defined @@ -75,25 +70,24 @@ void *fmodifiers_storage_get(FModifierStackStorage *storage, FModifier *fcm); * for such cases, just use NULL * - these should be defined after all the functions have been defined, so that * forward-definitions/prototypes don't need to be used! - * - keep this copy #if-def'd so that future constraints can get based off this + * - keep this copy #if-def'd so that future modifier can get based off this */ #if 0 static FModifierTypeInfo FMI_MODNAME = { - FMODIFIER_TYPE_MODNAME, /* type */ - sizeof(FMod_ModName), /* size */ - FMI_TYPE_SOME_ACTION, /* action type */ - FMI_REQUIRES_SOME_REQUIREMENT, /* requirements */ - "Modifier Name", /* name */ - "FMod_ModName", /* struct name */ - fcm_modname_free, /* free data */ - fcm_modname_relink, /* relink data */ - fcm_modname_copy, /* copy data */ - fcm_modname_new_data, /* new data */ - fcm_modname_verify, /* verify */ - fcm_modname_time, /* evaluate time */ - fcm_modname_evaluate, /* evaluate */ - fcm_modname_time_storage, /* evaluate time with storage */ - fcm_modname_evaluate_storage, /* evaluate with storage */ + FMODIFIER_TYPE_MODNAME, /* type */ + sizeof(FMod_ModName), /* size */ + FMI_TYPE_SOME_ACTION, /* action type */ + FMI_REQUIRES_SOME_REQUIREMENT, /* requirements */ + "Modifier Name", /* name */ + "FMod_ModName", /* struct name */ + 0, /* storage size */ + fcm_modname_free, /* free data */ + fcm_modname_relink, /* relink data */ + fcm_modname_copy, /* copy data */ + fcm_modname_new_data, /* new data */ + fcm_modname_verify, /* verify */ + fcm_modname_time, /* evaluate time */ + fcm_modname_evaluate, /* evaluate */ }; #endif @@ -101,8 +95,10 @@ static FModifierTypeInfo FMI_MODNAME = { /* Generators available: * 1) simple polynomial generator: - * - Expanded form - (y = C[0]*(x^(n)) + C[1]*(x^(n-1)) + ... + C[n]) - * - Factorized form - (y = (C[0][0]*x + C[0][1]) * (C[1][0]*x + C[1][1]) * ... * (C[n][0]*x + C[n][1])) + * - Expanded form: + * (y = C[0]*(x^(n)) + C[1]*(x^(n-1)) + ... + C[n]) + * - Factorized form: + * (y = (C[0][0]*x + C[0][1]) * (C[1][0]*x + C[1][1]) * ... * (C[n][0]*x + C[n][1])) */ static void fcm_generator_free(FModifier *fcm) @@ -110,8 +106,9 @@ static void fcm_generator_free(FModifier *fcm) FMod_Generator *data = (FMod_Generator *)fcm->data; /* free polynomial coefficients array */ - if (data->coefficients) + if (data->coefficients) { MEM_freeN(data->coefficients); + } } static void fcm_generator_copy(FModifier *fcm, const FModifier *src) @@ -120,8 +117,9 @@ static void fcm_generator_copy(FModifier *fcm, const FModifier *src) FMod_Generator *ogen = (FMod_Generator *)src->data; /* copy coefficients array? */ - if (ogen->coefficients) + if (ogen->coefficients) { gen->coefficients = MEM_dupallocN(ogen->coefficients); + } } static void fcm_generator_new_data(void *mdata) @@ -166,10 +164,8 @@ static void fcm_generator_verify(FModifier *fcm) } } -static void fcm_generator_evaluate(FCurve *UNUSED(fcu), - FModifier *fcm, - float *cvalue, - float evaltime) +static void fcm_generator_evaluate( + FCurve *UNUSED(fcu), FModifier *fcm, float *cvalue, float evaltime, void *UNUSED(storage)) { FMod_Generator *data = (FMod_Generator *)fcm->data; @@ -189,27 +185,33 @@ static void fcm_generator_evaluate(FCurve *UNUSED(fcu), */ for (i = 0; i < data->arraysize; i++) { /* first entry is x^0 = 1, otherwise, calculate based on previous */ - if (i) + if (i) { powers[i] = powers[i - 1] * evaltime; - else + } + else { powers[0] = 1; + } } /* for each coefficient, add to value, which we'll write to *cvalue in one go */ - for (i = 0; i < data->arraysize; i++) + for (i = 0; i < data->arraysize; i++) { value += data->coefficients[i] * powers[i]; + } /* only if something changed, write *cvalue in one go */ if (data->poly_order) { - if (data->flag & FCM_GENERATOR_ADDITIVE) + if (data->flag & FCM_GENERATOR_ADDITIVE) { *cvalue += value; - else + } + else { *cvalue = value; + } } /* cleanup */ - if (powers) + if (powers) { MEM_freeN(powers); + } break; } case FCM_GENERATOR_POLYNOMIAL_FACTORISED: /* Factorized polynomial */ @@ -217,17 +219,20 @@ static void fcm_generator_evaluate(FCurve *UNUSED(fcu), float value = 1.0f, *cp = NULL; unsigned int i; - /* for each coefficient pair, solve for that bracket before accumulating in value by multiplying */ - for (cp = data->coefficients, i = 0; (cp) && (i < (unsigned int)data->poly_order); - cp += 2, i++) + /* For each coefficient pair, + * solve for that bracket before accumulating in value by multiplying. */ + for (cp = data->coefficients, i = 0; (cp) && (i < (uint)data->poly_order); cp += 2, i++) { value *= (cp[0] * evaltime + cp[1]); + } /* only if something changed, write *cvalue in one go */ if (data->poly_order) { - if (data->flag & FCM_GENERATOR_ADDITIVE) + if (data->flag & FCM_GENERATOR_ADDITIVE) { *cvalue += value; - else + } + else { *cvalue = value; + } } break; } @@ -241,14 +246,13 @@ static FModifierTypeInfo FMI_GENERATOR = { FMI_REQUIRES_NOTHING, /* requirements */ N_("Generator"), /* name */ "FMod_Generator", /* struct name */ + 0, /* storage size */ fcm_generator_free, /* free data */ fcm_generator_copy, /* copy data */ fcm_generator_new_data, /* new data */ fcm_generator_verify, /* verify */ NULL, /* evaluate time */ fcm_generator_evaluate, /* evaluate */ - NULL, /* evaluate time with storage */ - NULL, /* evaluate with storage */ }; /* Built-In Function Generator F-Curve Modifier --------------------------- */ @@ -278,16 +282,16 @@ static void fcm_fn_generator_new_data(void *mdata) */ static double sinc(double x) { - if (fabs(x) < 0.0001) + if (fabs(x) < 0.0001) { return 1.0; - else + } + else { return sin(M_PI * x) / (M_PI * x); + } } -static void fcm_fn_generator_evaluate(FCurve *UNUSED(fcu), - FModifier *fcm, - float *cvalue, - float evaltime) +static void fcm_fn_generator_evaluate( + FCurve *UNUSED(fcu), FModifier *fcm, float *cvalue, float evaltime, void *UNUSED(storage)) { FMod_FunctionGenerator *data = (FMod_FunctionGenerator *)fcm->data; double arg = data->phase_multiplier * evaltime + data->phase_offset; @@ -313,11 +317,13 @@ static void fcm_fn_generator_evaluate(FCurve *UNUSED(fcu), { /* check that argument is not on one of the discontinuities (i.e. 90deg, 270 deg, etc) */ if (IS_EQ(fmod((arg - M_PI_2), M_PI), 0.0)) { - if ((data->flag & FCM_GENERATOR_ADDITIVE) == 0) + if ((data->flag & FCM_GENERATOR_ADDITIVE) == 0) { *cvalue = 0.0f; /* no value possible here */ + } } - else + else { fn = tan; + } break; } case FCM_GENERATOR_FN_LN: /* natural log */ @@ -327,8 +333,9 @@ static void fcm_fn_generator_evaluate(FCurve *UNUSED(fcu), fn = log; } else { - if ((data->flag & FCM_GENERATOR_ADDITIVE) == 0) + if ((data->flag & FCM_GENERATOR_ADDITIVE) == 0) { *cvalue = 0.0f; /* no value possible here */ + } } break; } @@ -339,8 +346,9 @@ static void fcm_fn_generator_evaluate(FCurve *UNUSED(fcu), fn = sqrt; } else { - if ((data->flag & FCM_GENERATOR_ADDITIVE) == 0) + if ((data->flag & FCM_GENERATOR_ADDITIVE) == 0) { *cvalue = 0.0f; /* no value possible here */ + } } break; } @@ -353,10 +361,12 @@ static void fcm_fn_generator_evaluate(FCurve *UNUSED(fcu), if (fn) { float value = (float)(data->amplitude * (float)fn(arg) + data->value_offset); - if (data->flag & FCM_GENERATOR_ADDITIVE) + if (data->flag & FCM_GENERATOR_ADDITIVE) { *cvalue += value; - else + } + else { *cvalue = value; + } } } @@ -367,14 +377,13 @@ static FModifierTypeInfo FMI_FN_GENERATOR = { FMI_REQUIRES_NOTHING, /* requirements */ N_("Built-In Function"), /* name */ "FMod_FunctionGenerator", /* struct name */ + 0, /* storage size */ NULL, /* free data */ NULL, /* copy data */ fcm_fn_generator_new_data, /* new data */ NULL, /* verify */ NULL, /* evaluate time */ fcm_fn_generator_evaluate, /* evaluate */ - NULL, /* evaluate time with storage */ - NULL, /* evaluate with storage */ }; /* Envelope F-Curve Modifier --------------------------- */ @@ -384,8 +393,9 @@ static void fcm_envelope_free(FModifier *fcm) FMod_Envelope *env = (FMod_Envelope *)fcm->data; /* free envelope data array */ - if (env->data) + if (env->data) { MEM_freeN(env->data); + } } static void fcm_envelope_copy(FModifier *fcm, const FModifier *src) @@ -394,8 +404,9 @@ static void fcm_envelope_copy(FModifier *fcm, const FModifier *src) FMod_Envelope *oenv = (FMod_Envelope *)src->data; /* copy envelope data array */ - if (oenv->data) + if (oenv->data) { env->data = MEM_dupallocN(oenv->data); + } } static void fcm_envelope_new_data(void *mdata) @@ -417,10 +428,8 @@ static void fcm_envelope_verify(FModifier *fcm) } } -static void fcm_envelope_evaluate(FCurve *UNUSED(fcu), - FModifier *fcm, - float *cvalue, - float evaltime) +static void fcm_envelope_evaluate( + FCurve *UNUSED(fcu), FModifier *fcm, float *cvalue, float evaltime, void *UNUSED(storage)) { FMod_Envelope *env = (FMod_Envelope *)fcm->data; FCM_EnvelopeData *fed, *prevfed, *lastfed; @@ -428,8 +437,9 @@ static void fcm_envelope_evaluate(FCurve *UNUSED(fcu), int a; /* get pointers */ - if (env->data == NULL) + if (env->data == NULL) { return; + } prevfed = env->data; fed = prevfed + 1; lastfed = prevfed + (env->totvert - 1); @@ -480,14 +490,13 @@ static FModifierTypeInfo FMI_ENVELOPE = { 0, /* requirements */ N_("Envelope"), /* name */ "FMod_Envelope", /* struct name */ + 0, /* storage size */ fcm_envelope_free, /* free data */ fcm_envelope_copy, /* copy data */ fcm_envelope_new_data, /* new data */ fcm_envelope_verify, /* verify */ NULL, /* evaluate time */ fcm_envelope_evaluate, /* evaluate */ - NULL, /* evaluate time with storage */ - NULL, /* evaluate with storage */ }; /* exported function for finding points */ @@ -587,14 +596,14 @@ int BKE_fcm_envelope_find_index(FCM_EnvelopeData array[], /* This modifier changes evaltime to something that exists within the curve's frame-range, * then re-evaluates modifier stack up to this point using the new time. This re-entrant behavior - * is very likely to be more time-consuming than the original approach... (which was tightly integrated into - * the calculation code...). + * is very likely to be more time-consuming than the original approach... + * (which was tightly integrated into the calculation code...). * - * NOTE: this needs to be at the start of the stack to be of use, as it needs to know the extents of the - * keyframes/sample-data. + * NOTE: this needs to be at the start of the stack to be of use, + * as it needs to know the extents of the keyframes/sample-data. * - * Possible TODO - store length of cycle information that can be initialized from the extents of the - * keyframes/sample-data, and adjusted as appropriate. + * Possible TODO - store length of cycle information that can be initialized from the extents of + * the keyframes/sample-data, and adjusted as appropriate. */ /* temp data used during evaluation */ @@ -610,18 +619,19 @@ static void fcm_cycles_new_data(void *mdata) data->before_mode = data->after_mode = FCM_EXTRAPOLATE_CYCLIC; } -static float fcm_cycles_time(FModifierStackStorage *storage, - FCurve *fcu, - FModifier *fcm, - float UNUSED(cvalue), - float evaltime) +static float fcm_cycles_time( + FCurve *fcu, FModifier *fcm, float UNUSED(cvalue), float evaltime, void *storage_) { FMod_Cycles *data = (FMod_Cycles *)fcm->data; + tFCMED_Cycles *storage = storage_; float prevkey[2], lastkey[2], cycyofs = 0.0f; short side = 0, mode = 0; int cycles = 0; float ofs = 0; + /* Initialize storage. */ + storage->cycyofs = 0; + /* check if modifier is first in stack, otherwise disable ourself... */ /* FIXME... */ if (fcm->prev) { @@ -650,8 +660,9 @@ static float fcm_cycles_time(FModifierStackStorage *storage, lastkey[0] = lastfpt->vec[0]; lastkey[1] = lastfpt->vec[1]; } - else + else { return evaltime; + } /* check if modifier will do anything * 1) if in data range, definitely don't do anything @@ -673,8 +684,9 @@ static float fcm_cycles_time(FModifierStackStorage *storage, ofs = lastkey[0]; } } - if ((ELEM(0, side, mode))) + if ((ELEM(0, side, mode))) { return evaltime; + } /* find relative place within a cycle */ { @@ -686,8 +698,9 @@ static float fcm_cycles_time(FModifierStackStorage *storage, cycdy = lastkey[1] - prevkey[1]; /* check if cycle is infinitely small, to be point of being impossible to use */ - if (cycdx == 0) + if (cycdx == 0) { return evaltime; + } /* calculate the 'number' of the cycle */ cycle = ((float)side * (evaltime - ofs) / cycdx); @@ -710,10 +723,12 @@ static float fcm_cycles_time(FModifierStackStorage *storage, /* check if 'cyclic extrapolation', and thus calculate y-offset for this cycle */ if (mode == FCM_EXTRAPOLATE_CYCLIC_OFFSET) { - if (side < 0) + if (side < 0) { cycyofs = (float)floor((evaltime - ofs) / cycdx); - else + } + else { cycyofs = (float)ceil((evaltime - ofs) / cycdx); + } cycyofs *= cycdy; } @@ -721,77 +736,66 @@ static float fcm_cycles_time(FModifierStackStorage *storage, if (cyct == 0.0f) { evaltime = (side == 1 ? lastkey[0] : prevkey[0]); - if ((mode == FCM_EXTRAPOLATE_MIRROR) && ((int)cycle % 2)) + if ((mode == FCM_EXTRAPOLATE_MIRROR) && ((int)cycle % 2)) { evaltime = (side == 1 ? prevkey[0] : lastkey[0]); + } } /* calculate where in the cycle we are (overwrite evaltime to reflect this) */ else if ((mode == FCM_EXTRAPOLATE_MIRROR) && ((int)(cycle + 1) % 2)) { - /* when 'mirror' option is used and cycle number is odd, this cycle is played in reverse + /* When 'mirror' option is used and cycle number is odd, this cycle is played in reverse * - for 'before' extrapolation, we need to flip in a different way, otherwise values past - * then end of the curve get referenced (result of fmod will be negative, and with different phase) + * then end of the curve get referenced + * (result of fmod will be negative, and with different phase). */ - if (side < 0) + if (side < 0) { evaltime = prevkey[0] - cyct; - else + } + else { evaltime = lastkey[0] - cyct; + } } else { /* the cycle is played normally... */ evaltime = prevkey[0] + cyct; } - if (evaltime < prevkey[0]) + if (evaltime < prevkey[0]) { evaltime += cycdx; + } } /* store temp data if needed */ if (mode == FCM_EXTRAPOLATE_CYCLIC_OFFSET) { - tFCMED_Cycles *edata; - - /* for now, this is just a float, but we could get more stuff... */ - edata = MEM_callocN(sizeof(tFCMED_Cycles), "tFCMED_Cycles"); - edata->cycyofs = cycyofs; - - fmodifiers_storage_put(storage, fcm, edata); + storage->cycyofs = cycyofs; } /* return the new frame to evaluate */ return evaltime; } -static void fcm_cycles_evaluate(FModifierStackStorage *storage, - FCurve *UNUSED(fcu), - FModifier *fcm, +static void fcm_cycles_evaluate(FCurve *UNUSED(fcu), + FModifier *UNUSED(fcm), float *cvalue, - float UNUSED(evaltime)) + float UNUSED(evaltime), + void *storage_) { - tFCMED_Cycles *edata = fmodifiers_storage_get(storage, fcm); - - /* use temp data */ - if (edata) { - /* add cyclic offset - no need to check for now, otherwise the data wouldn't exist! */ - *cvalue += edata->cycyofs; - - /* free temp data */ - MEM_freeN(edata); - fmodifiers_storage_remove(storage, fcm); - } + tFCMED_Cycles *storage = storage_; + *cvalue += storage->cycyofs; } static FModifierTypeInfo FMI_CYCLES = { - FMODIFIER_TYPE_CYCLES, /* type */ - sizeof(FMod_Cycles), /* size */ - FMI_TYPE_EXTRAPOLATION, /* action type */ - FMI_REQUIRES_ORIGINAL_DATA | FMI_REQUIRES_STORAGE, /* requirements */ - N_("Cycles"), /* name */ - "FMod_Cycles", /* struct name */ - NULL, /* free data */ - NULL, /* copy data */ - fcm_cycles_new_data, /* new data */ - NULL /*fcm_cycles_verify*/, /* verify */ - NULL, /* evaluate time */ - NULL, /* evaluate */ - fcm_cycles_time, /* evaluate time with storage */ - fcm_cycles_evaluate, /* evaluate with storage */ + FMODIFIER_TYPE_CYCLES, /* type */ + sizeof(FMod_Cycles), /* size */ + FMI_TYPE_EXTRAPOLATION, /* action type */ + FMI_REQUIRES_ORIGINAL_DATA, /* requirements */ + N_("Cycles"), /* name */ + "FMod_Cycles", /* struct name */ + sizeof(tFCMED_Cycles), /* storage size */ + NULL, /* free data */ + NULL, /* copy data */ + fcm_cycles_new_data, /* new data */ + NULL /*fcm_cycles_verify*/, /* verify */ + fcm_cycles_time, /* evaluate time */ + fcm_cycles_evaluate, /* evaluate */ }; /* Noise F-Curve Modifier --------------------------- */ @@ -809,7 +813,8 @@ static void fcm_noise_new_data(void *mdata) data->modification = FCM_NOISE_MODIF_REPLACE; } -static void fcm_noise_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float *cvalue, float evaltime) +static void fcm_noise_evaluate( + FCurve *UNUSED(fcu), FModifier *fcm, float *cvalue, float evaltime, void *UNUSED(storage)) { FMod_Noise *data = (FMod_Noise *)fcm->data; float noise; @@ -845,14 +850,13 @@ static FModifierTypeInfo FMI_NOISE = { 0, /* requirements */ N_("Noise"), /* name */ "FMod_Noise", /* struct name */ + 0, /* storage size */ NULL, /* free data */ NULL, /* copy data */ fcm_noise_new_data, /* new data */ NULL /*fcm_noise_verify*/, /* verify */ NULL, /* evaluate time */ fcm_noise_evaluate, /* evaluate */ - NULL, /* evaluate time with storage */ - NULL, /* evaluate with storage */ }; /* Python F-Curve Modifier --------------------------- */ @@ -886,10 +890,11 @@ static void fcm_python_copy(FModifier *fcm, const FModifier *src) static void fcm_python_evaluate(FCurve *UNUSED(fcu), FModifier *UNUSED(fcm), float *UNUSED(cvalue), - float UNUSED(evaltime)) + float UNUSED(evaltime), + void *UNUSED(storage)) { #ifdef WITH_PYTHON - //FMod_Python *data = (FMod_Python *)fcm->data; + // FMod_Python *data = (FMod_Python *)fcm->data; /* FIXME... need to implement this modifier... * It will need it execute a script using the custom properties @@ -904,14 +909,13 @@ static FModifierTypeInfo FMI_PYTHON = { FMI_REQUIRES_RUNTIME_CHECK, /* requirements */ N_("Python"), /* name */ "FMod_Python", /* struct name */ + 0, /* storage size */ fcm_python_free, /* free data */ fcm_python_copy, /* copy data */ fcm_python_new_data, /* new data */ NULL /*fcm_python_verify*/, /* verify */ NULL /*fcm_python_time*/, /* evaluate time */ fcm_python_evaluate, /* evaluate */ - NULL, /* evaluate time with storage */ - NULL, /* evaluate with storage */ }; /* Limits F-Curve Modifier --------------------------- */ @@ -919,15 +923,18 @@ static FModifierTypeInfo FMI_PYTHON = { static float fcm_limits_time(FCurve *UNUSED(fcu), FModifier *fcm, float UNUSED(cvalue), - float evaltime) + float evaltime, + void *UNUSED(storage)) { FMod_Limits *data = (FMod_Limits *)fcm->data; /* check for the time limits */ - if ((data->flag & FCM_LIMIT_XMIN) && (evaltime < data->rect.xmin)) + if ((data->flag & FCM_LIMIT_XMIN) && (evaltime < data->rect.xmin)) { return data->rect.xmin; - if ((data->flag & FCM_LIMIT_XMAX) && (evaltime > data->rect.xmax)) + } + if ((data->flag & FCM_LIMIT_XMAX) && (evaltime > data->rect.xmax)) { return data->rect.xmax; + } /* modifier doesn't change time */ return evaltime; @@ -936,15 +943,18 @@ static float fcm_limits_time(FCurve *UNUSED(fcu), static void fcm_limits_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float *cvalue, - float UNUSED(evaltime)) + float UNUSED(evaltime), + void *UNUSED(storage)) { FMod_Limits *data = (FMod_Limits *)fcm->data; /* value limits now */ - if ((data->flag & FCM_LIMIT_YMIN) && (*cvalue < data->rect.ymin)) + if ((data->flag & FCM_LIMIT_YMIN) && (*cvalue < data->rect.ymin)) { *cvalue = data->rect.ymin; - if ((data->flag & FCM_LIMIT_YMAX) && (*cvalue > data->rect.ymax)) + } + if ((data->flag & FCM_LIMIT_YMAX) && (*cvalue > data->rect.ymax)) { *cvalue = data->rect.ymax; + } } static FModifierTypeInfo FMI_LIMITS = { @@ -955,14 +965,13 @@ static FModifierTypeInfo FMI_LIMITS = { FMI_REQUIRES_RUNTIME_CHECK, /* requirements */ N_("Limits"), /* name */ "FMod_Limits", /* struct name */ + 0, /* storage size */ NULL, /* free data */ NULL, /* copy data */ NULL, /* new data */ NULL, /* verify */ fcm_limits_time, /* evaluate time */ fcm_limits_evaluate, /* evaluate */ - NULL, /* evaluate time with storage */ - NULL, /* evaluate with storage */ }; /* Stepped F-Curve Modifier --------------------------- */ @@ -979,19 +988,22 @@ static void fcm_stepped_new_data(void *mdata) static float fcm_stepped_time(FCurve *UNUSED(fcu), FModifier *fcm, float UNUSED(cvalue), - float evaltime) + float evaltime, + void *UNUSED(storage)) { FMod_Stepped *data = (FMod_Stepped *)fcm->data; int snapblock; /* check range clamping to see if we should alter the timing to achieve the desired results */ if (data->flag & FCM_STEPPED_NO_BEFORE) { - if (evaltime < data->start_frame) + if (evaltime < data->start_frame) { return evaltime; + } } if (data->flag & FCM_STEPPED_NO_AFTER) { - if (evaltime > data->end_frame) + if (evaltime > data->end_frame) { return evaltime; + } } /* we snap to the start of the previous closest block of 'step_size' frames @@ -1014,14 +1026,13 @@ static FModifierTypeInfo FMI_STEPPED = { FMI_REQUIRES_RUNTIME_CHECK, /* requirements */ N_("Stepped"), /* name */ "FMod_Stepped", /* struct name */ + 0, /* storage size */ NULL, /* free data */ NULL, /* copy data */ fcm_stepped_new_data, /* new data */ NULL, /* verify */ fcm_stepped_time, /* evaluate time */ NULL, /* evaluate */ - NULL, /* evaluate time with storage */ - NULL, /* evaluate with storage */ }; /* F-Curve Modifier API --------------------------- */ @@ -1077,10 +1088,12 @@ const FModifierTypeInfo *get_fmodifier_typeinfo(const int type) const FModifierTypeInfo *fmodifier_get_typeinfo(const FModifier *fcm) { /* only return typeinfo for valid modifiers */ - if (fcm) + if (fcm) { return get_fmodifier_typeinfo(fcm->type); - else + } + else { return NULL; + } } /* API --------------------------- */ @@ -1092,8 +1105,9 @@ FModifier *add_fmodifier(ListBase *modifiers, int type, FCurve *owner_fcu) FModifier *fcm; /* sanity checks */ - if (ELEM(NULL, modifiers, fmi)) + if (ELEM(NULL, modifiers, fmi)) { return NULL; + } /* special checks for whether modifier can be added */ if ((modifiers->first) && (type == FMODIFIER_TYPE_CYCLES)) { @@ -1114,19 +1128,22 @@ FModifier *add_fmodifier(ListBase *modifiers, int type, FCurve *owner_fcu) BLI_addtail(modifiers, fcm); /* tag modifier as "active" if no other modifiers exist in the stack yet */ - if (BLI_listbase_is_single(modifiers)) + if (BLI_listbase_is_single(modifiers)) { fcm->flag |= FMODIFIER_FLAG_ACTIVE; + } /* add modifier's data */ fcm->data = MEM_callocN(fmi->size, fmi->structName); /* init custom settings if necessary */ - if (fmi->new_data) + if (fmi->new_data) { fmi->new_data(fcm->data); + } /* update the fcurve if the Cycles modifier is added */ - if ((owner_fcu) && (type == FMODIFIER_TYPE_CYCLES)) + if ((owner_fcu) && (type == FMODIFIER_TYPE_CYCLES)) { calchandles_fcurve(owner_fcu); + } /* return modifier for further editing */ return fcm; @@ -1139,8 +1156,9 @@ FModifier *copy_fmodifier(const FModifier *src) FModifier *dst; /* sanity check */ - if (src == NULL) + if (src == NULL) { return NULL; + } /* copy the base data, clearing the links */ dst = MEM_dupallocN(src); @@ -1151,8 +1169,9 @@ FModifier *copy_fmodifier(const FModifier *src) dst->data = MEM_dupallocN(src->data); /* only do specific constraints if required */ - if (fmi && fmi->copy_data) + if (fmi && fmi->copy_data) { fmi->copy_data(dst, src); + } /* return the new modifier */ return dst; @@ -1163,8 +1182,9 @@ void copy_fmodifiers(ListBase *dst, const ListBase *src) { FModifier *fcm, *srcfcm; - if (ELEM(NULL, dst, src)) + if (ELEM(NULL, dst, src)) { return; + } BLI_listbase_clear(dst); BLI_duplicatelist(dst, src); @@ -1178,8 +1198,9 @@ void copy_fmodifiers(ListBase *dst, const ListBase *src) fcm->curve = NULL; /* only do specific constraints if required */ - if (fmi && fmi->copy_data) + if (fmi && fmi->copy_data) { fmi->copy_data(fcm, srcfcm); + } } } @@ -1189,16 +1210,18 @@ bool remove_fmodifier(ListBase *modifiers, FModifier *fcm) const FModifierTypeInfo *fmi = fmodifier_get_typeinfo(fcm); /* sanity check */ - if (fcm == NULL) + if (fcm == NULL) { return false; + } /* removing the cycles modifier requires a handle update */ FCurve *update_fcu = (fcm->type == FMODIFIER_TYPE_CYCLES) ? fcm->curve : NULL; /* free modifier's special data (stored inside fcm->data) */ if (fcm->data) { - if (fmi && fmi->free_data) + if (fmi && fmi->free_data) { fmi->free_data(fcm); + } /* free modifier's data (fcm->data) */ MEM_freeN(fcm->data); @@ -1209,8 +1232,9 @@ bool remove_fmodifier(ListBase *modifiers, FModifier *fcm) BLI_freelinkN(modifiers, fcm); /* update the fcurve if the Cycles modifier is removed */ - if (update_fcu) + if (update_fcu) { calchandles_fcurve(update_fcu); + } return true; } @@ -1228,8 +1252,9 @@ void free_fmodifiers(ListBase *modifiers) FModifier *fcm, *fmn; /* sanity check */ - if (modifiers == NULL) + if (modifiers == NULL) { return; + } /* free each modifier in order - modifier is unlinked from list and freed */ for (fcm = modifiers->first; fcm; fcm = fmn) { @@ -1244,13 +1269,15 @@ FModifier *find_active_fmodifier(ListBase *modifiers) FModifier *fcm; /* sanity checks */ - if (ELEM(NULL, modifiers, modifiers->first)) + if (ELEM(NULL, modifiers, modifiers->first)) { return NULL; + } /* loop over modifiers until 'active' one is found */ for (fcm = modifiers->first; fcm; fcm = fcm->next) { - if (fcm->flag & FMODIFIER_FLAG_ACTIVE) + if (fcm->flag & FMODIFIER_FLAG_ACTIVE) { return fcm; + } } /* no modifier is active */ @@ -1263,16 +1290,19 @@ void set_active_fmodifier(ListBase *modifiers, FModifier *fcm) FModifier *fm; /* sanity checks */ - if (ELEM(NULL, modifiers, modifiers->first)) + if (ELEM(NULL, modifiers, modifiers->first)) { return; + } /* deactivate all, and set current one active */ - for (fm = modifiers->first; fm; fm = fm->next) + for (fm = modifiers->first; fm; fm = fm->next) { fm->flag &= ~FMODIFIER_FLAG_ACTIVE; + } /* make given modifier active */ - if (fcm) + if (fcm) { fcm->flag |= FMODIFIER_FLAG_ACTIVE; + } } /* Do we have any modifiers which match certain criteria @@ -1284,12 +1314,14 @@ bool list_has_suitable_fmodifier(ListBase *modifiers, int mtype, short acttype) FModifier *fcm; /* if there are no specific filtering criteria, just skip */ - if ((mtype == 0) && (acttype == 0)) + if ((mtype == 0) && (acttype == 0)) { return (modifiers && modifiers->first); + } /* sanity checks */ - if (ELEM(NULL, modifiers, modifiers->first)) + if (ELEM(NULL, modifiers, modifiers->first)) { return false; + } /* find the first mdifier fitting these criteria */ for (fcm = modifiers->first; fcm; fcm = fcm->next) { @@ -1297,14 +1329,17 @@ bool list_has_suitable_fmodifier(ListBase *modifiers, int mtype, short acttype) short mOk = 1, aOk = 1; /* by default 1, so that when only one test, won't fail */ /* check if applicable ones are fulfilled */ - if (mtype) + if (mtype) { mOk = (fcm->type == mtype); - if (acttype > -1) + } + if (acttype > -1) { aOk = (fmi->acttype == acttype); + } /* if both are ok, we've found a hit */ - if (mOk && aOk) + if (mOk && aOk) { return true; + } } /* no matches */ @@ -1313,57 +1348,26 @@ bool list_has_suitable_fmodifier(ListBase *modifiers, int mtype, short acttype) /* Evaluation API --------------------------- */ -FModifierStackStorage *evaluate_fmodifiers_storage_new(ListBase *modifiers) +uint evaluate_fmodifiers_storage_size_per_modifier(ListBase *modifiers) { - FModifier *fcm; - /* Sanity checks. */ - if (ELEM(NULL, modifiers, modifiers->last)) { - return NULL; + if (ELEM(NULL, modifiers, modifiers->first)) { + return 0; } - for (fcm = modifiers->last; fcm; fcm = fcm->prev) { + uint max_size = 0; + + for (FModifier *fcm = modifiers->first; fcm; fcm = fcm->next) { const FModifierTypeInfo *fmi = fmodifier_get_typeinfo(fcm); if (fmi == NULL) { continue; } - if (fmi->requires & FMI_REQUIRES_STORAGE) { - return (FModifierStackStorage *)BLI_ghash_new( - BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, "fmodifier stack temp storage"); - } - } - - return NULL; -} - -void evaluate_fmodifiers_storage_free(FModifierStackStorage *storage) -{ - if (storage != NULL) { - BLI_ghash_free((GHash *)storage, NULL, NULL); + max_size = MAX2(max_size, fmi->storage_size); } -} - -void fmodifiers_storage_put(FModifierStackStorage *storage, FModifier *fcm, void *data) -{ - BLI_assert(storage != NULL); - BLI_ghash_insert((GHash *)storage, fcm, data); -} - -void fmodifiers_storage_remove(FModifierStackStorage *storage, FModifier *fcm) -{ - BLI_assert(storage != NULL); - - BLI_ghash_remove((GHash *)storage, fcm, NULL, NULL); -} - -void *fmodifiers_storage_get(FModifierStackStorage *storage, FModifier *fcm) -{ - BLI_assert(storage != NULL); - - return BLI_ghash_lookup((GHash *)storage, fcm); + return max_size; } /* helper function - calculate influence of FModifier */ @@ -1372,16 +1376,19 @@ static float eval_fmodifier_influence(FModifier *fcm, float evaltime) float influence; /* sanity check */ - if (fcm == NULL) + if (fcm == NULL) { return 0.0f; + } /* should we use influence stored in modifier or not * NOTE: this is really just a hack so that we don't need to version patch old files ;) */ - if (fcm->flag & FMODIFIER_FLAG_USEINFLUENCE) + if (fcm->flag & FMODIFIER_FLAG_USEINFLUENCE) { influence = fcm->influence; - else + } + else { influence = 1.0f; + } /* restricted range or full range? */ if (fcm->flag & FMODIFIER_FLAG_RANGERESTRICT) { @@ -1418,17 +1425,20 @@ static float eval_fmodifier_influence(FModifier *fcm, float evaltime) * * Note: *fcu might be NULL */ -float evaluate_time_fmodifiers( - FModifierStackStorage *storage, ListBase *modifiers, FCurve *fcu, float cvalue, float evaltime) +float evaluate_time_fmodifiers(FModifiersStackStorage *storage, + ListBase *modifiers, + FCurve *fcu, + float cvalue, + float evaltime) { - FModifier *fcm; - /* sanity checks */ - if (ELEM(NULL, modifiers, modifiers->last)) + if (ELEM(NULL, modifiers, modifiers->last)) { return evaltime; + } - if (fcu && fcu->flag & FCURVE_MOD_OFF) + if (fcu && fcu->flag & FCURVE_MOD_OFF) { return evaltime; + } /* Starting from the end of the stack, calculate the time effects of various stacked modifiers * on the time the F-Curve should be evaluated at. @@ -1440,30 +1450,28 @@ float evaluate_time_fmodifiers( * effect, which should get us the desired effects when using layered time manipulations * (such as multiple 'stepped' modifiers in sequence, causing different stepping rates) */ - for (fcm = modifiers->last; fcm; fcm = fcm->prev) { + uint fcm_index = storage->modifier_count - 1; + for (FModifier *fcm = modifiers->last; fcm; fcm = fcm->prev, fcm_index--) { const FModifierTypeInfo *fmi = fmodifier_get_typeinfo(fcm); - if (fmi == NULL) + if (fmi == NULL) { continue; + } - /* if modifier cannot be applied on this frame (whatever scale it is on, it won't affect the results) - * hence we shouldn't bother seeing what it would do given the chance - */ + /* If modifier cannot be applied on this frame + * (whatever scale it is on, it won't affect the results) + * hence we shouldn't bother seeing what it would do given the chance. */ if ((fcm->flag & FMODIFIER_FLAG_RANGERESTRICT) == 0 || ((fcm->sfra <= evaltime) && (fcm->efra >= evaltime))) { /* only evaluate if there's a callback for this */ - if (fmi->evaluate_modifier_time || fmi->evaluate_modifier_time_storage) { + if (fmi->evaluate_modifier_time) { if ((fcm->flag & (FMODIFIER_FLAG_DISABLED | FMODIFIER_FLAG_MUTED)) == 0) { - float influence = eval_fmodifier_influence(fcm, evaltime); - float nval; + void *storage_ptr = POINTER_OFFSET(storage->buffer, + fcm_index * storage->size_per_modifier); - if ((fmi->requires & FMI_REQUIRES_STORAGE) == 0) { - nval = fmi->evaluate_modifier_time(fcu, fcm, cvalue, evaltime); - } - else { - nval = fmi->evaluate_modifier_time_storage(storage, fcu, fcm, cvalue, evaltime); - } + float nval = fmi->evaluate_modifier_time(fcu, fcm, cvalue, evaltime, storage_ptr); + float influence = eval_fmodifier_influence(fcm, evaltime); evaltime = interpf(nval, evaltime, influence); } } @@ -1477,7 +1485,7 @@ float evaluate_time_fmodifiers( /* Evaluates the given set of F-Curve Modifiers using the given data * Should only be called after evaluate_time_fmodifiers() has been called... */ -void evaluate_value_fmodifiers(FModifierStackStorage *storage, +void evaluate_value_fmodifiers(FModifiersStackStorage *storage, ListBase *modifiers, FCurve *fcu, float *cvalue, @@ -1486,34 +1494,36 @@ void evaluate_value_fmodifiers(FModifierStackStorage *storage, FModifier *fcm; /* sanity checks */ - if (ELEM(NULL, modifiers, modifiers->first)) + if (ELEM(NULL, modifiers, modifiers->first)) { return; + } - if (fcu->flag & FCURVE_MOD_OFF) + if (fcu->flag & FCURVE_MOD_OFF) { return; + } /* evaluate modifiers */ - for (fcm = modifiers->first; fcm; fcm = fcm->next) { + uint fcm_index = 0; + for (fcm = modifiers->first; fcm; fcm = fcm->next, fcm_index++) { const FModifierTypeInfo *fmi = fmodifier_get_typeinfo(fcm); - if (fmi == NULL) + if (fmi == NULL) { continue; + } - /* only evaluate if there's a callback for this, and if F-Modifier can be evaluated on this frame */ + /* Only evaluate if there's a callback for this, + * and if F-Modifier can be evaluated on this frame. */ if ((fcm->flag & FMODIFIER_FLAG_RANGERESTRICT) == 0 || ((fcm->sfra <= evaltime) && (fcm->efra >= evaltime))) { - if (fmi->evaluate_modifier || fmi->evaluate_modifier_storage) { + if (fmi->evaluate_modifier) { if ((fcm->flag & (FMODIFIER_FLAG_DISABLED | FMODIFIER_FLAG_MUTED)) == 0) { - float influence = eval_fmodifier_influence(fcm, evaltime); - float nval = *cvalue; + void *storage_ptr = POINTER_OFFSET(storage->buffer, + fcm_index * storage->size_per_modifier); - if ((fmi->requires & FMI_REQUIRES_STORAGE) == 0) { - fmi->evaluate_modifier(fcu, fcm, &nval, evaltime); - } - else { - fmi->evaluate_modifier_storage(storage, fcu, fcm, &nval, evaltime); - } + float nval = *cvalue; + fmi->evaluate_modifier(fcu, fcm, &nval, evaltime, storage_ptr); + float influence = eval_fmodifier_influence(fcm, evaltime); *cvalue = interpf(nval, *cvalue, influence); } } diff --git a/source/blender/blenkernel/intern/font.c b/source/blender/blenkernel/intern/font.c index 4311402ef42..70a8f4f124c 100644 --- a/source/blender/blenkernel/intern/font.c +++ b/source/blender/blenkernel/intern/font.c @@ -69,8 +69,9 @@ void BKE_vfont_free_data(struct VFont *vfont) while (che->nurbsbase.first) { Nurb *nu = che->nurbsbase.first; - if (nu->bezt) + if (nu->bezt) { MEM_freeN(nu->bezt); + } BLI_freelinkN(&che->nurbsbase, nu); } @@ -306,14 +307,16 @@ VFont *BKE_vfont_load_exists_ex(struct Main *bmain, const char *filepath, bool * if (BLI_path_cmp(strtest, str) == 0) { id_us_plus(&vfont->id); /* officially should not, it doesn't link here! */ - if (r_exists) + if (r_exists) { *r_exists = true; + } return vfont; } } - if (r_exists) + if (r_exists) { *r_exists = false; + } return BKE_vfont_load(bmain, filepath); } @@ -377,8 +380,9 @@ static void build_underline(Curve *cu, nu2->knotsu = nu2->knotsv = NULL; nu2->flag = CU_2D; nu2->charidx = charidx + 1000; - if (mat_nr > 0) + if (mat_nr > 0) { nu2->mat_nr = mat_nr - 1; + } nu2->pntsu = 4; nu2->pntsv = 1; nu2->orderu = 4; @@ -444,8 +448,9 @@ static void buildchar(Curve *cu, int i; vfd = vfont_get_data(which_vfont(cu, info)); - if (!vfd) + if (!vfd) { return; + } /* make a copy at distance ofsx, ofsy with shear */ shear = cu->shear; @@ -455,16 +460,18 @@ static void buildchar(Curve *cu, che = find_vfont_char(vfd, character); /* Select the glyph data */ - if (che) + if (che) { nu1 = che->nurbsbase.first; + } /* Create the character */ while (nu1) { bezt1 = nu1->bezt; if (bezt1) { nu2 = (Nurb *)MEM_mallocN(sizeof(Nurb), "duplichar_nurb"); - if (nu2 == NULL) + if (nu2 == NULL) { break; + } memcpy(nu2, nu1, sizeof(struct Nurb)); nu2->resolu = cu->resolu; nu2->bp = NULL; @@ -558,8 +565,9 @@ int BKE_vfont_select_get(Object *ob, int *r_start, int *r_end) EditFont *ef = cu->editfont; int start, end, direction; - if ((ob->type != OB_FONT) || (ef == NULL)) + if ((ob->type != OB_FONT) || (ef == NULL)) { return 0; + } BLI_assert(ef->len >= 0); BLI_assert(ef->selstart >= 0 && ef->selstart <= ef->len + 1); @@ -666,10 +674,11 @@ enum { * Descent: the recommended distance below the baseline to fit most characters. * * We obtain ascent and descent from the font itself (FT_Face->ascender / face->height). - * And in some cases it is even the same value as FT_Face->bbox.yMax/yMin (font top and bottom respectively). + * And in some cases it is even the same value as FT_Face->bbox.yMax/yMin + * (font top and bottom respectively). * * The em_height here is relative to FT_Face->bbox. -*/ + */ #define ASCENT(vfd) ((vfd)->ascender * (vfd)->em_height) #define DESCENT(vfd) ((vfd)->em_height - ASCENT(vfd)) @@ -726,16 +735,19 @@ static bool vfont_to_curve(Object *ob, /* Set font data */ vfont = cu->vfont; - if (cu->str == NULL) + if (cu->str == NULL) { return ok; - if (vfont == NULL) + } + if (vfont == NULL) { return ok; + } vfd = vfont_get_data(vfont); /* The VFont Data can not be found */ - if (!vfd) + if (!vfd) { return ok; + } if (ef) { slen = ef->len; @@ -765,12 +777,14 @@ static bool vfont_to_curve(Object *ob, mem = mem_tmp; } - if (cu->tb == NULL) + if (cu->tb == NULL) { cu->tb = MEM_calloc_arrayN(MAXTEXTBOX, sizeof(TextBox), "TextBox compat"); + } if (ef != NULL && ob != NULL) { - if (ef->selboxes) + if (ef->selboxes) { MEM_freeN(ef->selboxes); + } if (BKE_vfont_select_get(ob, &selstart, &selend)) { ef->selboxes_len = (selend - selstart) + 1; @@ -821,8 +835,9 @@ static bool vfont_to_curve(Object *ob, vfont = which_vfont(cu, info); - if (vfont == NULL) + if (vfont == NULL) { break; + } if (vfont != oldvfont) { vfd = vfont_get_data(vfont); @@ -876,10 +891,12 @@ static bool vfont_to_curve(Object *ob, if (mem[j] == ' ' || mem[j] == '-') { ct -= (i - (j - 1)); cnr -= (i - (j - 1)); - if (mem[j] == ' ') + if (mem[j] == ' ') { wsnr--; - if (mem[j] == '-') + } + if (mem[j] == '-') { wsnr++; + } i = j - 1; xof = ct->xof; ct[1].dobreak = 1; @@ -1013,8 +1030,9 @@ static bool vfont_to_curve(Object *ob, for (i = 0; i <= slen; i++) { ascii = mem[i]; ct = &chartransdata[i]; - if (ascii == '\n' || ct->dobreak) + if (ascii == '\n' || ct->dobreak) { cu->lines++; + } } /* linedata is now: width of line */ @@ -1085,8 +1103,9 @@ static bool vfont_to_curve(Object *ob, } ct->xof += curofs; } - if (mem[i] == '\n' || chartransdata[i].dobreak) + if (mem[i] == '\n' || chartransdata[i].dobreak) { curofs = 0; + } ct++; } } @@ -1198,14 +1217,18 @@ static bool vfont_to_curve(Object *ob, maxx = maxy = -1.0e20f; ct = chartransdata; for (i = 0; i <= slen; i++, ct++) { - if (minx > ct->xof) + if (minx > ct->xof) { minx = ct->xof; - if (maxx < ct->xof) + } + if (maxx < ct->xof) { maxx = ct->xof; - if (miny > ct->yof) + } + if (miny > ct->yof) { miny = ct->yof; - if (maxy < ct->yof) + } + if (maxy < ct->yof) { maxy = ct->yof; + } } /* we put the x-coordinaat exact at the curve, the y is rotated */ @@ -1383,12 +1406,14 @@ static bool vfont_to_curve(Object *ob, } if (ob == NULL || info->mat_nr > (ob->totcol)) { - /* CLOG_ERROR(&LOG, "Illegal material index (%d) in text object, setting to 0", info->mat_nr); */ + // CLOG_ERROR( + // &LOG, "Illegal material index (%d) in text object, setting to 0", info->mat_nr); info->mat_nr = 0; } /* We do not want to see any character for \n or \r */ - if (cha != '\n') + if (cha != '\n') { buildchar(cu, r_nubase, cha, info, ct->xof, ct->yof, ct->rot, i, font_size); + } if ((info->flag & CU_CHINFO_UNDERLINE) && (cha != '\n')) { float ulwidth, uloverlap = 0.0f; @@ -1602,7 +1627,8 @@ bool BKE_vfont_to_curve_nubase(Object *ob, int mode, ListBase *r_nubase) return BKE_vfont_to_curve_ex(ob, ob->data, mode, r_nubase, NULL, NULL, NULL, NULL); } -/** Warning: expects to have access to evaluated data (i.e. passed object should be evaluated one...). */ +/** Warning: expects to have access to evaluated data + * (i.e. passed object should be evaluated one...). */ bool BKE_vfont_to_curve(Object *ob, int mode) { Curve *cu = ob->data; diff --git a/source/blender/blenkernel/intern/freestyle.c b/source/blender/blenkernel/intern/freestyle.c index 72b81651124..19c5012dc54 100644 --- a/source/blender/blenkernel/intern/freestyle.c +++ b/source/blender/blenkernel/intern/freestyle.c @@ -145,8 +145,9 @@ static void copy_module(FreestyleModuleConfig *new_module, FreestyleModuleConfig bool BKE_freestyle_module_delete(FreestyleConfig *config, FreestyleModuleConfig *module_conf) { - if (BLI_findindex(&config->modules, module_conf) == -1) + if (BLI_findindex(&config->modules, module_conf) == -1) { return false; + } BLI_freelinkN(&config->modules, module_conf); return true; } @@ -214,8 +215,9 @@ FreestyleLineSet *BKE_freestyle_lineset_add(struct Main *bmain, bool BKE_freestyle_lineset_delete(FreestyleConfig *config, FreestyleLineSet *lineset) { - if (BLI_findindex(&config->linesets, lineset) == -1) + if (BLI_findindex(&config->linesets, lineset) == -1) { return false; + } if (lineset->group) { id_us_min(&lineset->group->id); } @@ -233,8 +235,9 @@ FreestyleLineSet *BKE_freestyle_lineset_get_active(FreestyleConfig *config) FreestyleLineSet *lineset; for (lineset = (FreestyleLineSet *)config->linesets.first; lineset; lineset = lineset->next) { - if (lineset->flags & FREESTYLE_LINESET_CURRENT) + if (lineset->flags & FREESTYLE_LINESET_CURRENT) { return lineset; + } } return NULL; } @@ -246,8 +249,9 @@ short BKE_freestyle_lineset_get_active_index(FreestyleConfig *config) for (lineset = (FreestyleLineSet *)config->linesets.first, i = 0; lineset; lineset = lineset->next, i++) { - if (lineset->flags & FREESTYLE_LINESET_CURRENT) + if (lineset->flags & FREESTYLE_LINESET_CURRENT) { return i; + } } return 0; } @@ -259,9 +263,11 @@ void BKE_freestyle_lineset_set_active_index(FreestyleConfig *config, short index for (lineset = (FreestyleLineSet *)config->linesets.first, i = 0; lineset; lineset = lineset->next, i++) { - if (i == index) + if (i == index) { lineset->flags |= FREESTYLE_LINESET_CURRENT; - else + } + else { lineset->flags &= ~FREESTYLE_LINESET_CURRENT; + } } } diff --git a/source/blender/blenkernel/intern/gpencil.c b/source/blender/blenkernel/intern/gpencil.c index d1181eeb03d..c82b2c377fa 100644 --- a/source/blender/blenkernel/intern/gpencil.c +++ b/source/blender/blenkernel/intern/gpencil.c @@ -124,8 +124,9 @@ void BKE_gpencil_free_stroke(bGPDstroke *gps) BKE_gpencil_free_stroke_weights(gps); MEM_freeN(gps->dvert); } - if (gps->triangles) + if (gps->triangles) { MEM_freeN(gps->triangles); + } MEM_freeN(gps); } @@ -170,8 +171,9 @@ void BKE_gpencil_free_frames(bGPDlayer *gpl) bGPDframe *gpf_next; /* error checking */ - if (gpl == NULL) + if (gpl == NULL) { return; + } /* free frames */ for (bGPDframe *gpf = gpl->frames.first; gpf; gpf = gpf_next) { @@ -190,8 +192,9 @@ void BKE_gpencil_free_layers(ListBase *list) bGPDlayer *gpl_next; /* error checking */ - if (list == NULL) + if (list == NULL) { return; + } /* delete layers */ for (bGPDlayer *gpl = list->first; gpl; gpl = gpl_next) { @@ -232,8 +235,9 @@ bGPDframe *BKE_gpencil_frame_addnew(bGPDlayer *gpl, int cframe) short state = 0; /* error checking */ - if (gpl == NULL) + if (gpl == NULL) { return NULL; + } /* allocate memory for this frame */ gpf = MEM_callocN(sizeof(bGPDframe), "bGPDframe"); @@ -339,8 +343,9 @@ bGPDlayer *BKE_gpencil_layer_addnew(bGPdata *gpd, const char *name, bool setacti bGPDlayer *gpl_active = NULL; /* check that list is ok */ - if (gpd == NULL) + if (gpd == NULL) { return NULL; + } /* allocate memory for frame and add to end of list */ gpl = MEM_callocN(sizeof(bGPDlayer), "bGPDlayer"); @@ -387,8 +392,9 @@ bGPDlayer *BKE_gpencil_layer_addnew(bGPdata *gpd, const char *name, bool setacti sizeof(gpl->info)); /* make this one the active one */ - if (setactive) + if (setactive) { BKE_gpencil_layer_setactive(gpd, gpl); + } /* return layer */ return gpl; @@ -606,8 +612,9 @@ bGPDlayer *BKE_gpencil_layer_duplicate(const bGPDlayer *gpl_src) BLI_addtail(&gpl_dst->frames, gpf_dst); /* if source frame was the current layer's 'active' frame, reassign that too */ - if (gpf_src == gpl_dst->actframe) + if (gpf_src == gpl_dst->actframe) { gpl_dst->actframe = gpf_dst; + } } /* return new layer */ @@ -615,8 +622,10 @@ bGPDlayer *BKE_gpencil_layer_duplicate(const bGPDlayer *gpl_src) } /** - * Only copy internal data of GreasePencil ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of GreasePencil ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * @@ -693,8 +702,9 @@ void BKE_gpencil_stroke_sync_selection(bGPDstroke *gps) int i; /* error checking */ - if (gps == NULL) + if (gps == NULL) { return; + } /* we'll stop when we find the first selected point, * so initially, we must deselect @@ -719,8 +729,9 @@ void BKE_gpencil_frame_delete_laststroke(bGPDlayer *gpl, bGPDframe *gpf) int cfra = (gpf) ? gpf->framenum : 0; /* assume that the current frame was not locked */ /* error checking */ - if (ELEM(NULL, gpf, gps)) + if (ELEM(NULL, gpf, gps)) { return; + } /* free the stroke and its data */ if (gps->points) { @@ -747,8 +758,9 @@ void BKE_gpencil_frame_delete_laststroke(bGPDlayer *gpl, bGPDframe *gpf) bool gpencil_layer_is_editable(const bGPDlayer *gpl) { /* Sanity check */ - if (gpl == NULL) + if (gpl == NULL) { return false; + } /* Layer must be: Visible + Editable */ if ((gpl->flag & (GP_LAYER_HIDE | GP_LAYER_LOCKED)) == 0) { @@ -791,8 +803,9 @@ bGPDframe *BKE_gpencil_layer_getframe(bGPDlayer *gpl, int cframe, eGP_GetFrame_M short found = 0; /* error checking */ - if (gpl == NULL) + if (gpl == NULL) { return NULL; + } /* check if there is already an active frame */ if (gpl->actframe) { @@ -801,11 +814,13 @@ bGPDframe *BKE_gpencil_layer_getframe(bGPDlayer *gpl, int cframe, eGP_GetFrame_M /* do not allow any changes to layer's active frame if layer is locked from changes * or if the layer has been set to stay on the current frame */ - if (gpl->flag & GP_LAYER_FRAMELOCK) + if (gpl->flag & GP_LAYER_FRAMELOCK) { return gpf; + } /* do not allow any changes to actframe if frame has painting tag attached to it */ - if (gpf->flag & GP_FRAME_PAINT) + if (gpf->flag & GP_FRAME_PAINT) { return gpf; + } /* try to find matching frame */ if (gpf->framenum < cframe) { @@ -822,17 +837,22 @@ bGPDframe *BKE_gpencil_layer_getframe(bGPDlayer *gpl, int cframe, eGP_GetFrame_M /* set the appropriate frame */ if (addnew) { - if ((found) && (gpf->framenum == cframe)) + if ((found) && (gpf->framenum == cframe)) { gpl->actframe = gpf; - else if (addnew == GP_GETFRAME_ADD_COPY) + } + else if (addnew == GP_GETFRAME_ADD_COPY) { gpl->actframe = BKE_gpencil_frame_addcopy(gpl, cframe); - else + } + else { gpl->actframe = BKE_gpencil_frame_addnew(gpl, cframe); + } } - else if (found) + else if (found) { gpl->actframe = gpf; - else + } + else { gpl->actframe = gpl->frames.last; + } } else { for (; gpf; gpf = gpf->prev) { @@ -844,17 +864,22 @@ bGPDframe *BKE_gpencil_layer_getframe(bGPDlayer *gpl, int cframe, eGP_GetFrame_M /* set the appropriate frame */ if (addnew) { - if ((found) && (gpf->framenum == cframe)) + if ((found) && (gpf->framenum == cframe)) { gpl->actframe = gpf; - else if (addnew == GP_GETFRAME_ADD_COPY) + } + else if (addnew == GP_GETFRAME_ADD_COPY) { gpl->actframe = BKE_gpencil_frame_addcopy(gpl, cframe); - else + } + else { gpl->actframe = BKE_gpencil_frame_addnew(gpl, cframe); + } } - else if (found) + else if (found) { gpl->actframe = gpf; - else + } + else { gpl->actframe = gpl->frames.first; + } } } else if (gpl->frames.first) { @@ -883,13 +908,16 @@ bGPDframe *BKE_gpencil_layer_getframe(bGPDlayer *gpl, int cframe, eGP_GetFrame_M /* set the appropriate frame */ if (addnew) { - if ((found) && (gpf->framenum == cframe)) + if ((found) && (gpf->framenum == cframe)) { gpl->actframe = gpf; - else + } + else { gpl->actframe = BKE_gpencil_frame_addnew(gpl, cframe); + } } - else if (found) + else if (found) { gpl->actframe = gpf; + } else { /* unresolved errogenous situation! */ CLOG_STR_ERROR(&LOG, "cannot find appropriate gp-frame"); @@ -898,8 +926,9 @@ bGPDframe *BKE_gpencil_layer_getframe(bGPDlayer *gpl, int cframe, eGP_GetFrame_M } else { /* currently no frames (add if allowed to) */ - if (addnew) + if (addnew) { gpl->actframe = BKE_gpencil_frame_addnew(gpl, cframe); + } else { /* don't do anything... this may be when no frames yet! */ /* gpl->actframe should still be NULL */ @@ -916,14 +945,16 @@ bool BKE_gpencil_layer_delframe(bGPDlayer *gpl, bGPDframe *gpf) bool changed = false; /* error checking */ - if (ELEM(NULL, gpl, gpf)) + if (ELEM(NULL, gpl, gpf)) { return false; + } /* if this frame was active, make the previous frame active instead * since it's tricky to set active frame otherwise */ - if (gpl->actframe == gpf) + if (gpl->actframe == gpf) { gpl->actframe = gpf->prev; + } /* free the frame and its data */ changed = BKE_gpencil_free_strokes(gpf); @@ -938,13 +969,15 @@ bGPDlayer *BKE_gpencil_layer_getactive(bGPdata *gpd) bGPDlayer *gpl; /* error checking */ - if (ELEM(NULL, gpd, gpd->layers.first)) + if (ELEM(NULL, gpd, gpd->layers.first)) { return NULL; + } /* loop over layers until found (assume only one active) */ for (gpl = gpd->layers.first; gpl; gpl = gpl->next) { - if (gpl->flag & GP_LAYER_ACTIVE) + if (gpl->flag & GP_LAYER_ACTIVE) { return gpl; + } } /* no active layer found */ @@ -957,8 +990,9 @@ void BKE_gpencil_layer_setactive(bGPdata *gpd, bGPDlayer *active) bGPDlayer *gpl; /* error checking */ - if (ELEM(NULL, gpd, gpd->layers.first, active)) + if (ELEM(NULL, gpd, gpd->layers.first, active)) { return; + } /* loop over layers deactivating all */ for (gpl = gpd->layers.first; gpl; gpl = gpl->next) { @@ -979,8 +1013,9 @@ void BKE_gpencil_layer_setactive(bGPdata *gpd, bGPDlayer *active) void BKE_gpencil_layer_delete(bGPdata *gpd, bGPDlayer *gpl) { /* error checking */ - if (ELEM(NULL, gpd, gpl)) + if (ELEM(NULL, gpd, gpl)) { return; + } /* free layer */ BKE_gpencil_free_frames(gpl); @@ -1126,7 +1161,10 @@ Material *BKE_gpencil_object_material_ensure_from_active_input_brush(Main *bmain return BKE_gpencil_object_material_ensure_from_active_input_material(bmain, ob); } -/* Guaranteed to return a material assigned to object. Returns never NULL. Only use this for materials unrelated to user input */ +/** + * Guaranteed to return a material assigned to object. Returns never NULL. + * Only use this for materials unrelated to user input. + */ Material *BKE_gpencil_object_material_ensure_from_active_input_material(Main *bmain, Object *ob) { Material *ma = give_current_material(ob, ob->actcol); @@ -1142,8 +1180,9 @@ Material *BKE_gpencil_object_material_ensure_active(Main *bmain, Object *ob) Material *ma = NULL; /* sanity checks */ - if (ELEM(NULL, bmain, ob)) + if (ELEM(NULL, bmain, ob)) { return NULL; + } ma = BKE_gpencil_object_material_ensure_from_active_input_material(bmain, ob); if (ma->gp_style == NULL) { @@ -1169,8 +1208,9 @@ bool BKE_gpencil_stroke_minmax(const bGPDstroke *gps, int i; bool changed = false; - if (ELEM(NULL, gps, r_min, r_max)) + if (ELEM(NULL, gps, r_min, r_max)) { return false; + } for (i = 0, pt = gps->points; i < gps->totpoints; i++, pt++) { if ((use_select == false) || (pt->flag & GP_SPOINT_SELECT)) { @@ -1188,8 +1228,9 @@ bool BKE_gpencil_data_minmax(const bGPdata *gpd, float r_min[3], float r_max[3]) INIT_MINMAX(r_min, r_max); - if (gpd == NULL) + if (gpd == NULL) { return changed; + } for (bGPDlayer *gpl = gpd->layers.first; gpl; gpl = gpl->next) { bGPDframe *gpf = gpl->actframe; @@ -1254,8 +1295,9 @@ static void boundbox_gpencil(Object *ob) /* get bounding box */ BoundBox *BKE_gpencil_boundbox_get(Object *ob) { - if (ELEM(NULL, ob, ob->data)) + if (ELEM(NULL, ob, ob->data)) { return NULL; + } bGPdata *gpd = (bGPdata *)ob->data; if ((ob->runtime.bb) && ((gpd->flag & GP_DATA_CACHE_IS_DIRTY) == 0)) { @@ -1272,8 +1314,9 @@ BoundBox *BKE_gpencil_boundbox_get(Object *ob) void BKE_gpencil_transform(bGPdata *gpd, float mat[4][4]) { - if (gpd == NULL) + if (gpd == NULL) { return; + } for (bGPDlayer *gpl = gpd->layers.first; gpl; gpl = gpl->next) { /* FIXME: For now, we just skip parented layers. @@ -1378,9 +1421,11 @@ bool BKE_gpencil_smooth_stroke(bGPDstroke *gps, int i, float inf) } /* Compute smoothed coordinate by taking the ones nearby */ - /* XXX: This is potentially slow, and suffers from accumulation error as earlier points are handled before later ones */ + /* XXX: This is potentially slow, + * and suffers from accumulation error as earlier points are handled before later ones. */ { - // XXX: this is hardcoded to look at 2 points on either side of the current one (i.e. 5 items total) + /* XXX: this is hardcoded to look at 2 points on either side of the current one + * (i.e. 5 items total). */ const int steps = 2; const float average_fac = 1.0f / (float)(steps * 2 + 1); int step; @@ -1389,8 +1434,9 @@ bool BKE_gpencil_smooth_stroke(bGPDstroke *gps, int i, float inf) madd_v3_v3fl(sco, &pt->x, average_fac); /* n-steps before/after current point */ - // XXX: review how the endpoints are treated by this algorithm - // XXX: falloff measures should also introduce some weighting variations, so that further-out points get less weight + /* XXX: review how the endpoints are treated by this algorithm. */ + /* XXX: falloff measures should also introduce some weighting variations, + * so that further-out points get less weight. */ for (step = 1; step <= steps; step++) { bGPDspoint *pt1, *pt2; int before = i - step; @@ -1610,8 +1656,9 @@ void BKE_gpencil_material_index_remove(bGPdata *gpd, int index) BKE_gpencil_free_stroke_weights(gps); MEM_freeN(gps->dvert); } - if (gps->triangles) + if (gps->triangles) { MEM_freeN(gps->triangles); + } BLI_freelinkN(&gpf->strokes, gps); } else { diff --git a/source/blender/blenkernel/intern/gpencil_modifier.c b/source/blender/blenkernel/intern/gpencil_modifier.c index 63f6fc6307b..c8a45a92758 100644 --- a/source/blender/blenkernel/intern/gpencil_modifier.c +++ b/source/blender/blenkernel/intern/gpencil_modifier.c @@ -553,11 +553,13 @@ GpencilModifierData *BKE_gpencil_modifier_new(int type) eGpencilModifierMode_Expanded; md->flag = eGpencilModifierFlag_StaticOverride_Local; - if (mti->flags & eGpencilModifierTypeFlag_EnableInEditmode) + if (mti->flags & eGpencilModifierTypeFlag_EnableInEditmode) { md->mode |= eGpencilModifierMode_Editmode; + } - if (mti->initData) + if (mti->initData) { mti->initData(md); + } return md; } @@ -587,10 +589,12 @@ void BKE_gpencil_modifier_free_ex(GpencilModifierData *md, const int flag) } } - if (mti->freeData) + if (mti->freeData) { mti->freeData(md); - if (md->error) + } + if (md->error) { MEM_freeN(md->error); + } MEM_freeN(md); } @@ -695,9 +699,11 @@ GpencilModifierData *BKE_gpencil_modifiers_findByType(Object *ob, GpencilModifie { GpencilModifierData *md = ob->greasepencil_modifiers.first; - for (; md; md = md->next) - if (md->type == type) + for (; md; md = md->next) { + if (md->type == type) { break; + } + } return md; } @@ -727,8 +733,9 @@ void BKE_gpencil_modifiers_foreachTexLink(Object *ob, GreasePencilTexWalkFunc wa for (; md; md = md->next) { const GpencilModifierTypeInfo *mti = BKE_gpencil_modifierType_getInfo(md->type); - if (mti->foreachTexLink) + if (mti->foreachTexLink) { mti->foreachTexLink(md, ob, walk, userData); + } } } diff --git a/source/blender/blenkernel/intern/icons.c b/source/blender/blenkernel/intern/icons.c index 7ddd99c0fc0..8a5a36481cf 100644 --- a/source/blender/blenkernel/intern/icons.c +++ b/source/blender/blenkernel/intern/icons.c @@ -147,16 +147,19 @@ static int get_next_free_id(void) int startId = gFirstIconId; /* if we haven't used up the int number range, we just return the next int */ - if (gNextIconId >= gFirstIconId) + if (gNextIconId >= gFirstIconId) { return gNextIconId++; + } /* now we try to find the smallest icon id not stored in the gIcons hash */ - while (BLI_ghash_lookup(gIcons, POINTER_FROM_INT(startId)) && startId >= gFirstIconId) + while (BLI_ghash_lookup(gIcons, POINTER_FROM_INT(startId)) && startId >= gFirstIconId) { startId++; + } /* if we found a suitable one that isn't used yet, return it */ - if (startId >= gFirstIconId) + if (startId >= gFirstIconId) { return startId; + } /* fail */ return 0; @@ -243,8 +246,9 @@ void BKE_previewimg_freefunc(void *link) if (prv->rect[i]) { MEM_freeN(prv->rect[i]); } - if (prv->gputexture[i]) + if (prv->gputexture[i]) { GPU_texture_free(prv->gputexture[i]); + } } MEM_freeN(prv); @@ -296,7 +300,10 @@ PreviewImage *BKE_previewimg_copy(const PreviewImage *prv) return prv_img; } -/** Duplicate preview image from \a id and clear icon_id, to be used by datablock copy functions. */ +/** + * Duplicate preview image from \a id and clear icon_id, + * to be used by datablock copy functions. + */ void BKE_previewimg_id_copy(ID *new_id, const ID *old_id) { PreviewImage **old_prv_p = BKE_previewimg_id_get_p(old_id); @@ -519,8 +526,9 @@ void BKE_icon_changed(const int icon_id) Icon *icon = NULL; - if (!icon_id || G.background) + if (!icon_id || G.background) { return; + } icon = BLI_ghash_lookup(gIcons, POINTER_FROM_INT(icon_id)); @@ -529,8 +537,9 @@ void BKE_icon_changed(const int icon_id) BLI_assert(icon->id_type != 0); BLI_assert(icon->obj_type == ICON_DATA_ID); - /* Do not enforce creation of previews for valid ID types using BKE_previewimg_id_ensure() here , - * we only want to ensure *existing* preview images are properly tagged as changed/invalid, that's all. */ + /* Do not enforce creation of previews for valid ID types using BKE_previewimg_id_ensure() + * here, we only want to ensure *existing* preview images are properly tagged as + * changed/invalid, that's all. */ PreviewImage **p_prv = BKE_previewimg_id_get_p((ID *)icon->obj); /* If we have previews, they all are now invalid changed. */ @@ -582,8 +591,9 @@ int BKE_icon_id_ensure(struct ID *id) return 0; } - if (id->icon_id) + if (id->icon_id) { return id->icon_id; + } id->icon_id = get_next_free_id(); @@ -626,8 +636,9 @@ int BKE_icon_gplayer_color_ensure(bGPDlayer *gpl) return 0; } - if (gpl->runtime.icon_id) + if (gpl->runtime.icon_id) { return gpl->runtime.icon_id; + } gpl->runtime.icon_id = get_next_free_id(); @@ -644,8 +655,9 @@ int BKE_icon_gplayer_color_ensure(bGPDlayer *gpl) */ int BKE_icon_preview_ensure(ID *id, PreviewImage *preview) { - if (!preview || G.background) + if (!preview || G.background) { return 0; + } if (id) { BLI_assert(BKE_previewimg_id_ensure(id) == preview); @@ -668,7 +680,8 @@ int BKE_icon_preview_ensure(ID *id, PreviewImage *preview) return 0; } - /* Ensure we synchronize ID icon_id with its previewimage if available, and generate suitable 'ID' icon. */ + /* Ensure we synchronize ID icon_id with its previewimage if available, + * and generate suitable 'ID' icon. */ if (id) { id->icon_id = preview->icon_id; return icon_id_ensure_create_icon(id); @@ -720,8 +733,9 @@ static void icon_add_to_deferred_delete_queue(int icon_id) void BKE_icon_id_delete(struct ID *id) { const int icon_id = id->icon_id; - if (!icon_id) + if (!icon_id) { return; /* no icon defined for library object */ + } id->icon_id = 0; if (!BLI_thread_is_main()) { diff --git a/source/blender/blenkernel/intern/idcode.c b/source/blender/blenkernel/intern/idcode.c index 0e9960755d8..0a9178a8b6d 100644 --- a/source/blender/blenkernel/intern/idcode.c +++ b/source/blender/blenkernel/intern/idcode.c @@ -116,9 +116,11 @@ static IDType *idtype_from_code(short idcode) { int i = ARRAY_SIZE(idtypes); - while (i--) - if (idcode == idtypes[i].code) + while (i--) { + if (idcode == idtypes[i].code) { return &idtypes[i]; + } + } return NULL; } diff --git a/source/blender/blenkernel/intern/idprop.c b/source/blender/blenkernel/intern/idprop.c index 378d551916c..39e72d7e3a8 100644 --- a/source/blender/blenkernel/intern/idprop.c +++ b/source/blender/blenkernel/intern/idprop.c @@ -120,11 +120,13 @@ static void IDP_FreeIDPArray(IDProperty *prop, const bool do_id_user) BLI_assert(prop->type == IDP_IDPARRAY); - for (i = 0; i < prop->len; i++) + for (i = 0; i < prop->len; i++) { IDP_FreeProperty_ex(GETPROP(prop, i), do_id_user); + } - if (prop->data.pointer) + if (prop->data.pointer) { MEM_freeN(prop->data.pointer); + } } /* shallow copies item */ @@ -134,8 +136,9 @@ void IDP_SetIndexArray(IDProperty *prop, int index, IDProperty *item) BLI_assert(prop->type == IDP_IDPARRAY); - if (index >= prop->len || index < 0) + if (index >= prop->len || index < 0) { return; + } old = GETPROP(prop, index); if (item != old) { @@ -171,8 +174,9 @@ void IDP_ResizeIDPArray(IDProperty *prop, int newlen) if (newlen < prop->len && prop->totallen - newlen < IDP_ARRAY_REALLOC_LIMIT) { int i; - for (i = newlen; i < prop->len; i++) + for (i = newlen; i < prop->len; i++) { IDP_FreeProperty(GETPROP(prop, i)); + } prop->len = newlen; return; @@ -210,8 +214,9 @@ void IDP_ResizeIDPArray(IDProperty *prop, int newlen) /* ----------- Numerical Array Type ----------- */ static void idp_resize_group_array(IDProperty *prop, int newlen, void *newarr) { - if (prop->subtype != IDP_GROUP) + if (prop->subtype != IDP_GROUP) { return; + } if (newlen >= prop->len) { /* bigger */ @@ -260,14 +265,16 @@ void IDP_ResizeArray(IDProperty *prop, int newlen) newsize = newlen; newsize = (newsize >> 3) + (newsize < 9 ? 3 : 6) + newsize; - if (is_grow == false) + if (is_grow == false) { idp_resize_group_array(prop, newlen, prop->data.pointer); + } prop->data.pointer = MEM_recallocN(prop->data.pointer, idp_size_table[(int)prop->subtype] * (size_t)newsize); - if (is_grow == true) + if (is_grow == true) { idp_resize_group_array(prop, newlen, prop->data.pointer); + } prop->len = newlen; prop->totallen = newsize; @@ -305,8 +312,9 @@ static IDProperty *IDP_CopyArray(const IDProperty *prop, const int flag) IDProperty **array = newp->data.pointer; int a; - for (a = 0; a < prop->len; a++) + for (a = 0; a < prop->len; a++) { array[a] = IDP_CopyProperty_ex(array[a], flag); + } } } newp->len = prop->len; @@ -344,8 +352,9 @@ IDProperty *IDP_NewString(const char *st, const char *name, int maxlen) /* include null terminator '\0' */ int stlen = (int)strlen(st) + 1; - if (maxlen > 0 && maxlen < stlen) + if (maxlen > 0 && maxlen < stlen) { stlen = maxlen; + } prop->data.pointer = MEM_mallocN((size_t)stlen, "id property string 2"); prop->len = prop->totallen = stlen; @@ -365,8 +374,9 @@ static IDProperty *IDP_CopyString(const IDProperty *prop, const int flag) BLI_assert(prop->type == IDP_STRING); newp = idp_generic_copy(prop, flag); - if (prop->data.pointer) + if (prop->data.pointer) { newp->data.pointer = MEM_dupallocN(prop->data.pointer); + } newp->len = prop->len; newp->subtype = prop->subtype; newp->totallen = prop->totallen; @@ -380,8 +390,9 @@ void IDP_AssignString(IDProperty *prop, const char *st, int maxlen) BLI_assert(prop->type == IDP_STRING); stlen = (int)strlen(st); - if (maxlen > 0 && maxlen < stlen) + if (maxlen > 0 && maxlen < stlen) { stlen = maxlen; + } if (prop->subtype == IDP_STRING_SUB_BYTE) { IDP_ResizeArray(prop, stlen); @@ -424,8 +435,9 @@ void IDP_FreeString(IDProperty *prop) { BLI_assert(prop->type == IDP_STRING); - if (prop->data.pointer) + if (prop->data.pointer) { MEM_freeN(prop->data.pointer); + } } /** \} */ @@ -653,13 +665,14 @@ void IDP_MergeGroup(IDProperty *dest, const IDProperty *src, const bool do_overw * * The sanity check just means the property is not added to the group if another property * exists with the same name; the client code using ID properties then needs to detect this - * (the function that adds new properties to groups, IDP_AddToGroup, returns false if a property can't - * be added to the group, and true if it can) and free the property. + * (the function that adds new properties to groups, #IDP_AddToGroup, + * returns false if a property can't be added to the group, and true if it can) + * and free the property. * * Currently the code to free ID properties is designed to leave the actual struct * you pass it un-freed, this is needed for how the system works. This means - * to free an ID property, you first call IDP_FreeProperty then MEM_freeN the - * struct. In the future this will just be IDP_FreeProperty and the code will + * to free an ID property, you first call #IDP_FreeProperty then #MEM_freeN the struct. + * In the future this will just be #IDP_FreeProperty and the code will * be reorganized to work properly. */ bool IDP_AddToGroup(IDProperty *group, IDProperty *prop) @@ -775,11 +788,13 @@ IDProperty *IDP_CopyProperty(const IDProperty *prop) } /* Updates ID pointers after an object has been copied */ -/* TODO Nuke this once its only user has been correctly converted to use generic ID management from BKE_library! */ +/* TODO Nuke this once its only user has been correctly converted + * to use generic ID management from BKE_library! */ void IDP_RelinkProperty(struct IDProperty *prop) { - if (!prop) + if (!prop) { return; + } switch (prop->type) { case IDP_GROUP: { @@ -836,12 +851,15 @@ IDProperty *IDP_GetProperties(ID *id, const bool create_if_needed) * \param is_strict: When false treat missing items as a match */ bool IDP_EqualsProperties_ex(IDProperty *prop1, IDProperty *prop2, const bool is_strict) { - if (prop1 == NULL && prop2 == NULL) + if (prop1 == NULL && prop2 == NULL) { return true; - else if (prop1 == NULL || prop2 == NULL) + } + else if (prop1 == NULL || prop2 == NULL) { return is_strict ? false : true; - else if (prop1->type != prop2->type) + } + else if (prop1->type != prop2->type) { return false; + } switch (prop1->type) { case IDP_INT: @@ -881,14 +899,16 @@ bool IDP_EqualsProperties_ex(IDProperty *prop1, IDProperty *prop2, const bool is case IDP_GROUP: { IDProperty *link1, *link2; - if (is_strict && prop1->len != prop2->len) + if (is_strict && prop1->len != prop2->len) { return false; + } for (link1 = prop1->data.group.first; link1; link1 = link1->next) { link2 = IDP_GetPropertyFromGroup(prop2, link1->name); - if (!IDP_EqualsProperties_ex(link1, link2, is_strict)) + if (!IDP_EqualsProperties_ex(link1, link2, is_strict)) { return false; + } } return true; @@ -898,12 +918,14 @@ bool IDP_EqualsProperties_ex(IDProperty *prop1, IDProperty *prop2, const bool is IDProperty *array2 = IDP_IDPArray(prop2); int i; - if (prop1->len != prop2->len) + if (prop1->len != prop2->len) { return false; + } for (i = 0; i < prop1->len; i++) { - if (!IDP_EqualsProperties_ex(&array1[i], &array2[i], is_strict)) + if (!IDP_EqualsProperties_ex(&array1[i], &array2[i], is_strict)) { return false; + } } return true; } diff --git a/source/blender/blenkernel/intern/image.c b/source/blender/blenkernel/intern/image.c index 75807ebbfa3..f23c58befdf 100644 --- a/source/blender/blenkernel/intern/image.c +++ b/source/blender/blenkernel/intern/image.c @@ -304,8 +304,9 @@ static void image_init(Image *ima, short source, short type) ima->source = source; ima->type = type; - if (source == IMA_SRC_VIEWER) + if (source == IMA_SRC_VIEWER) { ima->flag |= IMA_VIEW_AS_RENDER; + } if (type == IMA_TYPE_R_RESULT) { for (int i = 0; i < 8; i++) { @@ -356,8 +357,9 @@ static ImBuf *image_get_cached_ibuf_for_index_frame(Image *ima, int index, int f static void image_assign_ibuf(Image *ima, ImBuf *ibuf, int index, int frame) { if (ibuf) { - if (index != IMA_NO_INDEX) + if (index != IMA_NO_INDEX) { index = IMA_MAKE_INDEX(frame, index); + } imagecache_put(ima, index, ibuf); } @@ -372,16 +374,19 @@ static void copy_image_packedfiles(ListBase *lb_dst, const ListBase *lb_src) ImagePackedFile *imapf_dst = MEM_mallocN(sizeof(ImagePackedFile), "Image Packed Files (copy)"); STRNCPY(imapf_dst->filepath, imapf_src->filepath); - if (imapf_src->packedfile) + if (imapf_src->packedfile) { imapf_dst->packedfile = dupPackedFile(imapf_src->packedfile); + } BLI_addtail(lb_dst, imapf_dst); } } /** - * Only copy internal data of Image ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of Image ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * @@ -494,10 +499,12 @@ static void image_init_color_management(Image *ima) ibuf = IMB_loadiffname(name, IB_test | IB_alphamode_detect, ima->colorspace_settings.name); if (ibuf) { - if (ibuf->flags & IB_alphamode_premul) + if (ibuf->flags & IB_alphamode_premul) { ima->alpha_mode = IMA_ALPHA_PREMUL; - else + } + else { ima->alpha_mode = IMA_ALPHA_STRAIGHT; + } IMB_freeImBuf(ibuf); } @@ -529,15 +536,17 @@ Image *BKE_image_load(Main *bmain, const char *filepath) /* exists? */ file = BLI_open(str, O_BINARY | O_RDONLY, 0); - if (file == -1) + if (file == -1) { return NULL; + } close(file); ima = image_alloc(bmain, BLI_path_basename(filepath), IMA_SRC_FILE, IMA_TYPE_IMAGE); STRNCPY(ima->name, filepath); - if (BLI_path_extension_check_array(filepath, imb_ext_movie)) + if (BLI_path_extension_check_array(filepath, imb_ext_movie)) { ima->source = IMA_SRC_MOVIE; + } image_init_color_management(ima); @@ -565,18 +574,21 @@ Image *BKE_image_load_exists_ex(Main *bmain, const char *filepath, bool *r_exist if (BLI_path_cmp(strtest, str) == 0) { if ((BKE_image_has_anim(ima) == false) || (ima->id.us == 0)) { id_us_plus(&ima->id); /* officially should not, it doesn't link here! */ - if (ima->ok == 0) + if (ima->ok == 0) { ima->ok = IMA_OK; - if (r_exists) + } + if (r_exists) { *r_exists = true; + } return ima; } } } } - if (r_exists) + if (r_exists) { *r_exists = false; + } return BKE_image_load(bmain, filepath); } @@ -685,8 +697,9 @@ Image *BKE_image_add_generated(Main *bmain, /* image_assign_ibuf puts buffer to the cache, which increments user counter. */ IMB_freeImBuf(ibuf); - if (!stereo3d) + if (!stereo3d) { break; + } image_add_view(ima, names[view_id], ""); } @@ -720,109 +733,88 @@ Image *BKE_image_add_from_imbuf(Main *bmain, ImBuf *ibuf, const char *name) return ima; } -/* packs rects from memory as PNG - * convert multiview images to R_IMF_VIEWS_INDIVIDUAL - */ -static void image_memorypack_multiview(Image *ima) +/* Pack image buffer to memory as PNG or EXR. */ +static bool image_memorypack_imbuf(Image *ima, ImBuf *ibuf, const char *filepath) { - ImageView *iv; - int i; - - image_free_packedfiles(ima); - - for (i = 0, iv = ima->views.first; iv; iv = iv->next, i++) { - ImBuf *ibuf = image_get_cached_ibuf_for_index_frame(ima, i, 0); - - ibuf->ftype = IMB_FTYPE_PNG; - ibuf->planes = R_IMF_PLANES_RGBA; + ibuf->ftype = (ibuf->rect_float) ? IMB_FTYPE_OPENEXR : IMB_FTYPE_PNG; - /* 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], ""); - } + IMB_saveiff(ibuf, filepath, IB_rect | IB_mem); - IMB_saveiff(ibuf, iv->filepath, IB_rect | IB_mem); + if (ibuf->encodedbuffer == NULL) { + CLOG_STR_ERROR(&LOG, "memory save for pack error"); + IMB_freeImBuf(ibuf); + image_free_packedfiles(ima); + return false; + } - if (ibuf->encodedbuffer == NULL) { - CLOG_STR_ERROR(&LOG, "memory save for pack error"); - IMB_freeImBuf(ibuf); - image_free_packedfiles(ima); - return; - } - else { - ImagePackedFile *imapf; - PackedFile *pf = MEM_callocN(sizeof(*pf), "PackedFile"); + ImagePackedFile *imapf; + PackedFile *pf = MEM_callocN(sizeof(*pf), "PackedFile"); - pf->data = ibuf->encodedbuffer; - pf->size = ibuf->encodedsize; + pf->data = ibuf->encodedbuffer; + pf->size = ibuf->encodedsize; - imapf = MEM_mallocN(sizeof(ImagePackedFile), "Image PackedFile"); - STRNCPY(imapf->filepath, iv->filepath); - imapf->packedfile = pf; - BLI_addtail(&ima->packedfiles, imapf); + imapf = MEM_mallocN(sizeof(ImagePackedFile), "Image PackedFile"); + STRNCPY(imapf->filepath, filepath); + imapf->packedfile = pf; + BLI_addtail(&ima->packedfiles, imapf); - ibuf->encodedbuffer = NULL; - ibuf->encodedsize = 0; - ibuf->userflags &= ~IB_BITMAPDIRTY; - } - IMB_freeImBuf(ibuf); - } + ibuf->encodedbuffer = NULL; + ibuf->encodedsize = 0; + ibuf->userflags &= ~IB_BITMAPDIRTY; - if (ima->source == IMA_SRC_GENERATED) { - ima->source = IMA_SRC_FILE; - ima->type = IMA_TYPE_IMAGE; - } - ima->views_format = R_IMF_VIEWS_INDIVIDUAL; + return true; } -/* packs rect from memory as PNG */ -void BKE_image_memorypack(Image *ima) +/* Pack image to memory. */ +bool BKE_image_memorypack(Image *ima) { - ImBuf *ibuf; + bool ok = true; + + image_free_packedfiles(ima); if (BKE_image_is_multiview(ima)) { - image_memorypack_multiview(ima); - return; - } + /* Store each view as a separate packed files with R_IMF_VIEWS_INDIVIDUAL. */ + ImageView *iv; + int i; - ibuf = image_get_cached_ibuf_for_index_frame(ima, IMA_NO_INDEX, 0); + for (i = 0, iv = ima->views.first; iv; iv = iv->next, i++) { + ImBuf *ibuf = image_get_cached_ibuf_for_index_frame(ima, i, 0); - if (ibuf == NULL) - return; + if (!ibuf) { + ok = false; + break; + } - image_free_packedfiles(ima); + /* 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], ""); + } - ibuf->ftype = IMB_FTYPE_PNG; - ibuf->planes = R_IMF_PLANES_RGBA; + ok = ok && image_memorypack_imbuf(ima, ibuf, iv->filepath); + IMB_freeImBuf(ibuf); + } - IMB_saveiff(ibuf, ibuf->name, IB_rect | IB_mem); - if (ibuf->encodedbuffer == NULL) { - CLOG_STR_ERROR(&LOG, "memory save for pack error"); + ima->views_format = R_IMF_VIEWS_INDIVIDUAL; } else { - ImagePackedFile *imapf; - PackedFile *pf = MEM_callocN(sizeof(*pf), "PackedFile"); - - pf->data = ibuf->encodedbuffer; - pf->size = ibuf->encodedsize; - - imapf = MEM_mallocN(sizeof(ImagePackedFile), "Image PackedFile"); - STRNCPY(imapf->filepath, ima->name); - imapf->packedfile = pf; - BLI_addtail(&ima->packedfiles, imapf); - - ibuf->encodedbuffer = NULL; - ibuf->encodedsize = 0; - ibuf->userflags &= ~IB_BITMAPDIRTY; + ImBuf *ibuf = image_get_cached_ibuf_for_index_frame(ima, IMA_NO_INDEX, 0); - if (ima->source == IMA_SRC_GENERATED) { - ima->source = IMA_SRC_FILE; - ima->type = IMA_TYPE_IMAGE; + if (ibuf) { + ok = ok && image_memorypack_imbuf(ima, ibuf, ibuf->name); + IMB_freeImBuf(ibuf); + } + else { + ok = false; } } - IMB_freeImBuf(ibuf); + if (ok && ima->source == IMA_SRC_GENERATED) { + ima->source = IMA_SRC_FILE; + ima->type = IMA_TYPE_IMAGE; + } + + return ok; } void BKE_image_packfiles(ReportList *reports, Image *ima, const char *basepath) @@ -885,8 +877,9 @@ static uintptr_t image_mem_size(Image *image) uintptr_t size = 0; /* viewers have memory depending on other rules, has no valid rect pointer */ - if (image->source == IMA_SRC_VIEWER) + if (image->source == IMA_SRC_VIEWER) { return 0; + } BLI_spin_lock(&image_spin); if (image->cache != NULL) { @@ -930,16 +923,18 @@ void BKE_image_print_memlist(Main *bmain) Image *ima; uintptr_t size, totsize = 0; - for (ima = bmain->images.first; ima; ima = ima->id.next) + for (ima = bmain->images.first; ima; ima = ima->id.next) { totsize += image_mem_size(ima); + } printf("\ntotal image memory len: %.3f MB\n", (double)totsize / (double)(1024 * 1024)); for (ima = bmain->images.first; ima; ima = ima->id.next) { size = image_mem_size(ima); - if (size) + if (size) { printf("%s len: %.3f MB\n", ima->id.name + 2, (double)size / (double)(1024 * 1024)); + } } } @@ -958,12 +953,15 @@ void BKE_image_free_all_textures(Main *bmain) uintptr_t tot_freed_size = 0; #endif - for (ima = bmain->images.first; ima; ima = ima->id.next) + for (ima = bmain->images.first; ima; ima = ima->id.next) { ima->id.tag &= ~LIB_TAG_DOIT; + } - for (tex = bmain->textures.first; tex; tex = tex->id.next) - if (tex->ima) + for (tex = bmain->textures.first; tex; tex = tex->id.next) { + if (tex->ima) { tex->ima->id.tag |= LIB_TAG_DOIT; + } + } for (ima = bmain->images.first; ima; ima = ima->id.next) { if (ima->cache && (ima->id.tag & LIB_TAG_DOIT)) { @@ -1004,9 +1002,11 @@ void BKE_image_all_free_anim_ibufs(Main *bmain, int cfra) { Image *ima; - for (ima = bmain->images.first; ima; ima = ima->id.next) - if (BKE_image_is_animated(ima)) + for (ima = bmain->images.first; ima; ima = ima->id.next) { + if (BKE_image_is_animated(ima)) { BKE_image_free_anim_ibufs(ima, cfra); + } + } } /* *********** READ AND WRITE ************** */ @@ -1193,8 +1193,9 @@ char BKE_imtype_valid_channels(const char imtype, bool write_file) /* alpha */ switch (imtype) { case R_IMF_IMTYPE_BMP: - if (write_file) + if (write_file) { break; + } ATTR_FALLTHROUGH; case R_IMF_IMTYPE_TARGA: case R_IMF_IMTYPE_RAWTGA: @@ -1255,60 +1256,81 @@ char BKE_imtype_valid_depths(const char imtype) * creator_args.c help info */ char BKE_imtype_from_arg(const char *imtype_arg) { - if (STREQ(imtype_arg, "TGA")) + if (STREQ(imtype_arg, "TGA")) { return R_IMF_IMTYPE_TARGA; - else if (STREQ(imtype_arg, "IRIS")) + } + else if (STREQ(imtype_arg, "IRIS")) { return R_IMF_IMTYPE_IRIS; + } #ifdef WITH_DDS - else if (STREQ(imtype_arg, "DDS")) + else if (STREQ(imtype_arg, "DDS")) { return R_IMF_IMTYPE_DDS; + } #endif - else if (STREQ(imtype_arg, "JPEG")) + else if (STREQ(imtype_arg, "JPEG")) { return R_IMF_IMTYPE_JPEG90; - else if (STREQ(imtype_arg, "IRIZ")) + } + else if (STREQ(imtype_arg, "IRIZ")) { return R_IMF_IMTYPE_IRIZ; - else if (STREQ(imtype_arg, "RAWTGA")) + } + else if (STREQ(imtype_arg, "RAWTGA")) { return R_IMF_IMTYPE_RAWTGA; - else if (STREQ(imtype_arg, "AVIRAW")) + } + else if (STREQ(imtype_arg, "AVIRAW")) { return R_IMF_IMTYPE_AVIRAW; - else if (STREQ(imtype_arg, "AVIJPEG")) + } + else if (STREQ(imtype_arg, "AVIJPEG")) { return R_IMF_IMTYPE_AVIJPEG; - else if (STREQ(imtype_arg, "PNG")) + } + else if (STREQ(imtype_arg, "PNG")) { return R_IMF_IMTYPE_PNG; - else if (STREQ(imtype_arg, "BMP")) + } + else if (STREQ(imtype_arg, "BMP")) { return R_IMF_IMTYPE_BMP; + } #ifdef WITH_HDR - else if (STREQ(imtype_arg, "HDR")) + else if (STREQ(imtype_arg, "HDR")) { return R_IMF_IMTYPE_RADHDR; + } #endif #ifdef WITH_TIFF - else if (STREQ(imtype_arg, "TIFF")) + else if (STREQ(imtype_arg, "TIFF")) { return R_IMF_IMTYPE_TIFF; + } #endif #ifdef WITH_OPENEXR - else if (STREQ(imtype_arg, "OPEN_EXR")) + else if (STREQ(imtype_arg, "OPEN_EXR")) { return R_IMF_IMTYPE_OPENEXR; - else if (STREQ(imtype_arg, "OPEN_EXR_MULTILAYER")) + } + else if (STREQ(imtype_arg, "OPEN_EXR_MULTILAYER")) { return R_IMF_IMTYPE_MULTILAYER; - else if (STREQ(imtype_arg, "EXR")) + } + else if (STREQ(imtype_arg, "EXR")) { return R_IMF_IMTYPE_OPENEXR; - else if (STREQ(imtype_arg, "MULTILAYER")) + } + else if (STREQ(imtype_arg, "MULTILAYER")) { return R_IMF_IMTYPE_MULTILAYER; + } #endif - else if (STREQ(imtype_arg, "FFMPEG")) + else if (STREQ(imtype_arg, "FFMPEG")) { return R_IMF_IMTYPE_FFMPEG; + } #ifdef WITH_CINEON - else if (STREQ(imtype_arg, "CINEON")) + else if (STREQ(imtype_arg, "CINEON")) { return R_IMF_IMTYPE_CINEON; - else if (STREQ(imtype_arg, "DPX")) + } + else if (STREQ(imtype_arg, "DPX")) { return R_IMF_IMTYPE_DPX; + } #endif #ifdef WITH_OPENJPEG - else if (STREQ(imtype_arg, "JP2")) + else if (STREQ(imtype_arg, "JP2")) { return R_IMF_IMTYPE_JP2; + } #endif - else + else { return R_IMF_IMTYPE_INVALID; + } } static bool do_add_image_extension(char *string, @@ -1320,17 +1342,20 @@ static bool do_add_image_extension(char *string, (void)im_format; /* may be unused, depends on build options */ if (imtype == R_IMF_IMTYPE_IRIS) { - if (!BLI_path_extension_check(string, extension_test = ".rgb")) + if (!BLI_path_extension_check(string, extension_test = ".rgb")) { extension = extension_test; + } } else if (imtype == R_IMF_IMTYPE_IRIZ) { - if (!BLI_path_extension_check(string, extension_test = ".rgb")) + if (!BLI_path_extension_check(string, extension_test = ".rgb")) { extension = extension_test; + } } #ifdef WITH_HDR else if (imtype == R_IMF_IMTYPE_RADHDR) { - if (!BLI_path_extension_check(string, extension_test = ".hdr")) + if (!BLI_path_extension_check(string, extension_test = ".hdr")) { extension = extension_test; + } } #endif else if (ELEM(imtype, @@ -1339,22 +1364,26 @@ static bool do_add_image_extension(char *string, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) { - if (!BLI_path_extension_check(string, extension_test = ".png")) + if (!BLI_path_extension_check(string, extension_test = ".png")) { extension = extension_test; + } } #ifdef WITH_DDS else if (imtype == R_IMF_IMTYPE_DDS) { - if (!BLI_path_extension_check(string, extension_test = ".dds")) + if (!BLI_path_extension_check(string, extension_test = ".dds")) { extension = extension_test; + } } #endif else if (ELEM(imtype, R_IMF_IMTYPE_TARGA, R_IMF_IMTYPE_RAWTGA)) { - if (!BLI_path_extension_check(string, extension_test = ".tga")) + if (!BLI_path_extension_check(string, extension_test = ".tga")) { extension = extension_test; + } } else if (imtype == R_IMF_IMTYPE_BMP) { - if (!BLI_path_extension_check(string, extension_test = ".bmp")) + if (!BLI_path_extension_check(string, extension_test = ".bmp")) { extension = extension_test; + } } #ifdef WITH_TIFF else if (imtype == R_IMF_IMTYPE_TIFF) { @@ -1365,49 +1394,58 @@ static bool do_add_image_extension(char *string, #endif #ifdef WITH_OPENIMAGEIO else if (imtype == R_IMF_IMTYPE_PSD) { - if (!BLI_path_extension_check(string, extension_test = ".psd")) + if (!BLI_path_extension_check(string, extension_test = ".psd")) { extension = extension_test; + } } #endif #ifdef WITH_OPENEXR else if (imtype == R_IMF_IMTYPE_OPENEXR || imtype == R_IMF_IMTYPE_MULTILAYER) { - if (!BLI_path_extension_check(string, extension_test = ".exr")) + if (!BLI_path_extension_check(string, extension_test = ".exr")) { extension = extension_test; + } } #endif #ifdef WITH_CINEON else if (imtype == R_IMF_IMTYPE_CINEON) { - if (!BLI_path_extension_check(string, extension_test = ".cin")) + if (!BLI_path_extension_check(string, extension_test = ".cin")) { extension = extension_test; + } } else if (imtype == R_IMF_IMTYPE_DPX) { - if (!BLI_path_extension_check(string, extension_test = ".dpx")) + if (!BLI_path_extension_check(string, extension_test = ".dpx")) { extension = extension_test; + } } #endif #ifdef WITH_OPENJPEG else if (imtype == R_IMF_IMTYPE_JP2) { if (im_format) { if (im_format->jp2_codec == R_IMF_JP2_CODEC_JP2) { - if (!BLI_path_extension_check(string, extension_test = ".jp2")) + if (!BLI_path_extension_check(string, extension_test = ".jp2")) { extension = extension_test; + } } else if (im_format->jp2_codec == R_IMF_JP2_CODEC_J2K) { - if (!BLI_path_extension_check(string, extension_test = ".j2c")) + if (!BLI_path_extension_check(string, extension_test = ".j2c")) { extension = extension_test; + } } - else + else { BLI_assert(!"Unsupported jp2 codec was specified in im_format->jp2_codec"); + } } else { - if (!BLI_path_extension_check(string, extension_test = ".jp2")) + if (!BLI_path_extension_check(string, extension_test = ".jp2")) { extension = extension_test; + } } } #endif else { // R_IMF_IMTYPE_AVIRAW, R_IMF_IMTYPE_AVIJPEG, R_IMF_IMTYPE_JPEG90 etc - if (!(BLI_path_extension_check_n(string, extension_test = ".jpg", ".jpeg", NULL))) + if (!(BLI_path_extension_check_n(string, extension_test = ".jpg", ".jpeg", NULL))) { extension = extension_test; + } } if (extension) { @@ -1459,97 +1497,116 @@ void BKE_imbuf_to_image_format(struct ImageFormatData *im_format, const ImBuf *i /* file type */ - if (ftype == IMB_FTYPE_IMAGIC) + if (ftype == IMB_FTYPE_IMAGIC) { im_format->imtype = R_IMF_IMTYPE_IRIS; - + } #ifdef WITH_HDR - else if (ftype == IMB_FTYPE_RADHDR) + else if (ftype == IMB_FTYPE_RADHDR) { im_format->imtype = R_IMF_IMTYPE_RADHDR; + } #endif - else if (ftype == IMB_FTYPE_PNG) { im_format->imtype = R_IMF_IMTYPE_PNG; - if (custom_flags & PNG_16BIT) + if (custom_flags & PNG_16BIT) { im_format->depth = R_IMF_CHAN_DEPTH_16; + } im_format->compress = quality; } #ifdef WITH_DDS - else if (ftype == IMB_FTYPE_DDS) + else if (ftype == IMB_FTYPE_DDS) { im_format->imtype = R_IMF_IMTYPE_DDS; + } #endif - - else if (ftype == IMB_FTYPE_BMP) + else if (ftype == IMB_FTYPE_BMP) { im_format->imtype = R_IMF_IMTYPE_BMP; - + } #ifdef WITH_TIFF else if (ftype == IMB_FTYPE_TIF) { im_format->imtype = R_IMF_IMTYPE_TIFF; - if (custom_flags & TIF_16BIT) + if (custom_flags & TIF_16BIT) { im_format->depth = R_IMF_CHAN_DEPTH_16; - if (custom_flags & TIF_COMPRESS_NONE) + } + if (custom_flags & TIF_COMPRESS_NONE) { im_format->tiff_codec = R_IMF_TIFF_CODEC_NONE; - if (custom_flags & TIF_COMPRESS_DEFLATE) + } + if (custom_flags & TIF_COMPRESS_DEFLATE) { im_format->tiff_codec = R_IMF_TIFF_CODEC_DEFLATE; - if (custom_flags & TIF_COMPRESS_LZW) + } + if (custom_flags & TIF_COMPRESS_LZW) { im_format->tiff_codec = R_IMF_TIFF_CODEC_LZW; - if (custom_flags & TIF_COMPRESS_PACKBITS) + } + if (custom_flags & TIF_COMPRESS_PACKBITS) { im_format->tiff_codec = R_IMF_TIFF_CODEC_PACKBITS; + } } #endif #ifdef WITH_OPENEXR else if (ftype == IMB_FTYPE_OPENEXR) { im_format->imtype = R_IMF_IMTYPE_OPENEXR; - if (custom_flags & OPENEXR_HALF) + if (custom_flags & OPENEXR_HALF) { im_format->depth = R_IMF_CHAN_DEPTH_16; - if (custom_flags & OPENEXR_COMPRESS) + } + if (custom_flags & OPENEXR_COMPRESS) { im_format->exr_codec = R_IMF_EXR_CODEC_ZIP; // Can't determine compression - if (imbuf->zbuf_float) + } + if (imbuf->zbuf_float) { im_format->flag |= R_IMF_FLAG_ZBUF; + } } #endif #ifdef WITH_CINEON - else if (ftype == IMB_FTYPE_CINEON) + else if (ftype == IMB_FTYPE_CINEON) { im_format->imtype = R_IMF_IMTYPE_CINEON; - else if (ftype == IMB_FTYPE_DPX) + } + else if (ftype == IMB_FTYPE_DPX) { im_format->imtype = R_IMF_IMTYPE_DPX; + } #endif - else if (ftype == IMB_FTYPE_TGA) { - if (custom_flags & RAWTGA) + if (custom_flags & RAWTGA) { im_format->imtype = R_IMF_IMTYPE_RAWTGA; - else + } + else { im_format->imtype = R_IMF_IMTYPE_TARGA; + } } #ifdef WITH_OPENJPEG else if (ftype == IMB_FTYPE_JP2) { im_format->imtype = R_IMF_IMTYPE_JP2; im_format->quality = quality; - if (custom_flags & JP2_16BIT) + if (custom_flags & JP2_16BIT) { im_format->depth = R_IMF_CHAN_DEPTH_16; - else if (custom_flags & JP2_12BIT) + } + else if (custom_flags & JP2_12BIT) { im_format->depth = R_IMF_CHAN_DEPTH_12; + } - if (custom_flags & JP2_YCC) + if (custom_flags & JP2_YCC) { im_format->jp2_flag |= R_IMF_JP2_FLAG_YCC; + } if (custom_flags & JP2_CINE) { im_format->jp2_flag |= R_IMF_JP2_FLAG_CINE_PRESET; - if (custom_flags & JP2_CINE_48FPS) + if (custom_flags & JP2_CINE_48FPS) { im_format->jp2_flag |= R_IMF_JP2_FLAG_CINE_48; + } } - if (custom_flags & JP2_JP2) + if (custom_flags & JP2_JP2) { im_format->jp2_codec = R_IMF_JP2_CODEC_JP2; - else if (custom_flags & JP2_J2K) + } + else if (custom_flags & JP2_J2K) { im_format->jp2_codec = R_IMF_JP2_CODEC_J2K; - else + } + else { BLI_assert(!"Unsupported jp2 codec was specified in file type"); + } } #endif @@ -1646,10 +1703,12 @@ static void stampdata( if (use_dynamic && scene->r.stamp & R_STAMP_MARKER) { const char *name = BKE_scene_find_last_marker_name(scene, CFRA); - if (name) + if (name) { STRNCPY(text, name); - else + } + else { STRNCPY(text, "<none>"); + } SNPRINTF(stamp_data->marker, do_prefix ? "Marker %s" : "%s", text); } @@ -1671,8 +1730,9 @@ static void stampdata( char fmtstr[32]; int digits = 1; - if (scene->r.efra > 9) + if (scene->r.efra > 9) { digits = integer_digits_i(scene->r.efra); + } SNPRINTF(fmtstr, do_prefix ? "Frame %%0%di" : "%%0%di", digits); SNPRINTF(stamp_data->frame, fmtstr, scene->r.cfra); @@ -1724,10 +1784,12 @@ static void stampdata( if (use_dynamic && scene->r.stamp & R_STAMP_SEQSTRIP) { Sequence *seq = BKE_sequencer_foreground_frame_get(scene, scene->r.cfra); - if (seq) + if (seq) { STRNCPY(text, seq->name + 2); - else + } + else { STRNCPY(text, "<none>"); + } SNPRINTF(stamp_data->strip, do_prefix ? "Strip %s" : "%s", text); } @@ -1898,8 +1960,9 @@ void BKE_image_stamp_buf(Scene *scene, #define BUFF_MARGIN_X 2 #define BUFF_MARGIN_Y 1 - if (!rect && !rectf) + if (!rect && !rectf) { return; + } display_device = scene->display_settings.display_device; display = IMB_colormanagement_display_get_named(display_device); @@ -1912,8 +1975,9 @@ void BKE_image_stamp_buf(Scene *scene, } /* TODO, do_versions */ - if (scene->r.stamp_font_id < 8) + if (scene->r.stamp_font_id < 8) { scene->r.stamp_font_id = 12; + } /* set before return */ BLF_size(mono, scene->r.stamp_font_id, 72); @@ -2237,8 +2301,9 @@ void BKE_render_result_stamp_info(Scene *scene, { struct StampData *stamp_data; - if (!(scene && (scene->r.stamp & R_STAMP_ALL)) && !allocate_only) + if (!(scene && (scene->r.stamp & R_STAMP_ALL)) && !allocate_only) { return; + } if (!rr->stamp_data) { stamp_data = MEM_callocN(sizeof(StampData), "RenderResult.stamp_data"); @@ -2247,8 +2312,9 @@ void BKE_render_result_stamp_info(Scene *scene, stamp_data = rr->stamp_data; } - if (!allocate_only) + if (!allocate_only) { stampdata(scene, camera, stamp_data, 0, true); + } if (!rr->stamp_data) { rr->stamp_data = stamp_data; @@ -2259,8 +2325,9 @@ struct StampData *BKE_stamp_info_from_scene_static(Scene *scene) { struct StampData *stamp_data; - if (!(scene && (scene->r.stamp & R_STAMP_ALL))) + if (!(scene && (scene->r.stamp & R_STAMP_ALL))) { return NULL; + } /* Memory is allocated here (instead of by the caller) so that the caller * doesn't have to know the size of the StampData struct. */ @@ -2479,8 +2546,9 @@ void BKE_imbuf_write_prepare(ImBuf *ibuf, const ImageFormatData *imf) ibuf->ftype = IMB_FTYPE_PNG; if (imtype == R_IMF_IMTYPE_PNG) { - if (imf->depth == R_IMF_CHAN_DEPTH_16) + if (imf->depth == R_IMF_CHAN_DEPTH_16) { ibuf->foptions.flag |= PNG_16BIT; + } ibuf->foptions.quality = compress; } @@ -2517,8 +2585,9 @@ void BKE_imbuf_write_prepare(ImBuf *ibuf, const ImageFormatData *imf) #ifdef WITH_OPENEXR else if (ELEM(imtype, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER)) { ibuf->ftype = IMB_FTYPE_OPENEXR; - if (imf->depth == R_IMF_CHAN_DEPTH_16) + if (imf->depth == R_IMF_CHAN_DEPTH_16) { ibuf->foptions.flag |= OPENEXR_HALF; + } ibuf->foptions.flag |= (imf->exr_codec & OPENEXR_COMPRESS); if (!(imf->flag & R_IMF_FLAG_ZBUF)) { @@ -2568,8 +2637,9 @@ void BKE_imbuf_write_prepare(ImBuf *ibuf, const ImageFormatData *imf) } #ifdef WITH_OPENJPEG else if (imtype == R_IMF_IMTYPE_JP2) { - if (quality < 10) + if (quality < 10) { quality = 90; + } ibuf->ftype = IMB_FTYPE_JP2; ibuf->foptions.quality = quality; @@ -2586,22 +2656,27 @@ void BKE_imbuf_write_prepare(ImBuf *ibuf, const ImageFormatData *imf) if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_PRESET) { ibuf->foptions.flag |= JP2_CINE; - if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_48) + if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_48) { ibuf->foptions.flag |= JP2_CINE_48FPS; + } } - if (imf->jp2_codec == R_IMF_JP2_CODEC_JP2) + if (imf->jp2_codec == R_IMF_JP2_CODEC_JP2) { ibuf->foptions.flag |= JP2_JP2; - else if (imf->jp2_codec == R_IMF_JP2_CODEC_J2K) + } + else if (imf->jp2_codec == R_IMF_JP2_CODEC_J2K) { ibuf->foptions.flag |= JP2_J2K; - else + } + else { BLI_assert(!"Unsupported jp2 codec was specified in im_format->jp2_codec"); + } } #endif else { /* R_IMF_IMTYPE_JPEG90, etc. default we save jpegs */ - if (quality < 10) + if (quality < 10) { quality = 90; + } ibuf->ftype = IMB_FTYPE_JPG; ibuf->foptions.quality = quality; } @@ -2652,8 +2727,9 @@ int BKE_imbuf_write_stamp(Scene *scene, const char *name, const struct ImageFormatData *imf) { - if (scene && scene->r.stamp & R_STAMP_ALL) + if (scene && scene->r.stamp & R_STAMP_ALL) { BKE_imbuf_stamp_info(rr, ibuf); + } return BKE_imbuf_write(ibuf, name, imf); } @@ -2668,19 +2744,23 @@ static void do_makepicstring(char *string, const short use_frames, const char *suffix) { - if (string == NULL) + if (string == NULL) { return; + } BLI_strncpy(string, base, FILE_MAX - 10); /* weak assumption */ BLI_path_abs(string, relbase); - if (use_frames) + if (use_frames) { BLI_path_frame(string, frame, 4); + } - if (suffix) + if (suffix) { BLI_path_suffix(string, FILE_MAX, suffix, ""); + } - if (use_ext) + if (use_ext) { do_add_image_extension(string, imtype, im_format); + } } void BKE_image_path_from_imformat(char *string, @@ -2726,15 +2806,18 @@ struct anim *openanim(const char *name, int flags, int streamindex, char colorsp struct ImBuf *ibuf; anim = IMB_open_anim(name, flags, streamindex, colorspace); - if (anim == NULL) + if (anim == NULL) { return NULL; + } ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE); if (ibuf == NULL) { - if (BLI_exists(name)) + if (BLI_exists(name)) { printf("not an anim: %s\n", name); - else + } + else { printf("anim file doesn't exist: %s\n", name); + } IMB_free_anim(anim); return NULL; } @@ -2768,17 +2851,22 @@ Image *BKE_image_verify_viewer(Main *bmain, int type, const char *name) { Image *ima; - for (ima = bmain->images.first; ima; ima = ima->id.next) - if (ima->source == IMA_SRC_VIEWER) - if (ima->type == type) + for (ima = bmain->images.first; ima; ima = ima->id.next) { + if (ima->source == IMA_SRC_VIEWER) { + if (ima->type == type) { break; + } + } + } - if (ima == NULL) + if (ima == NULL) { ima = image_alloc(bmain, name, IMA_SRC_VIEWER, type); + } /* happens on reload, imagewindow cannot be image user when hidden*/ - if (ima->id.us == 0) + if (ima->id.us == 0) { id_us_plus(&ima->id); + } return ima; } @@ -2791,8 +2879,9 @@ static void image_viewer_create_views(const RenderData *rd, Image *ima) else { SceneRenderView *srv; for (srv = rd->views.first; srv; srv = srv->next) { - if (BKE_scene_multiview_is_render_view_active(rd, srv) == false) + if (BKE_scene_multiview_is_render_view_active(rd, srv) == false) { continue; + } image_add_view(ima, srv->name, ""); } } @@ -2806,8 +2895,9 @@ void BKE_image_verify_viewer_views(const RenderData *rd, Image *ima, ImageUser * BLI_thread_lock(LOCK_DRAW_IMAGE); - if (!BKE_scene_multiview_is_stereo3d(rd)) + if (!BKE_scene_multiview_is_stereo3d(rd)) { iuser->flag &= ~IMA_SHOW_STEREO; + } /* see if all scene render views are in the image view list */ do_reset = (BKE_scene_multiview_num_views_get(rd) != BLI_listbase_count(&ima->views)); @@ -3029,26 +3119,31 @@ static void image_tag_reload(Image *ima, ImageUser *iuser, void *customdata) } } -static void image_init_imageuser(Image *ima, ImageUser *iuser) +void BKE_imageuser_default(ImageUser *iuser) +{ + memset(iuser, 0, sizeof(ImageUser)); + iuser->ok = true; + iuser->frames = 100; + iuser->sfra = 1; +} + +void BKE_image_init_imageuser(Image *ima, ImageUser *iuser) { RenderResult *rr = ima->rr; iuser->multi_index = 0; iuser->layer = iuser->pass = iuser->view = 0; - if (rr) + if (rr) { BKE_image_multilayer_index(rr, iuser); -} - -void BKE_image_init_imageuser(Image *ima, ImageUser *iuser) -{ - image_init_imageuser(ima, iuser); + } } void BKE_image_signal(Main *bmain, Image *ima, ImageUser *iuser, int signal) { - if (ima == NULL) + if (ima == NULL) { return; + } BLI_spin_lock(&image_spin); @@ -3064,9 +3159,11 @@ void BKE_image_signal(Main *bmain, Image *ima, ImageUser *iuser, int signal) } break; case IMA_SIGNAL_SRC_CHANGE: - if (ima->type == IMA_TYPE_UV_TEST) - if (ima->source != IMA_SRC_GENERATED) + if (ima->type == IMA_TYPE_UV_TEST) { + if (ima->source != IMA_SRC_GENERATED) { ima->type = IMA_TYPE_IMAGE; + } + } if (ima->source == IMA_SRC_GENERATED) { if (ima->gen_x == 0 || ima->gen_y == 0) { @@ -3130,11 +3227,13 @@ void BKE_image_signal(Main *bmain, Image *ima, ImageUser *iuser, int signal) } } - if (BKE_image_has_packedfile(ima)) + if (BKE_image_has_packedfile(ima)) { BKE_image_free_buffers(ima); + } } - else + else { BKE_image_free_buffers(ima); + } if (iuser) { image_tag_reload(ima, iuser, ima); @@ -3146,7 +3245,7 @@ void BKE_image_signal(Main *bmain, Image *ima, ImageUser *iuser, int signal) iuser->ok = 1; if (ima->source == IMA_SRC_FILE || ima->source == IMA_SRC_SEQUENCE) { if (ima->type == IMA_TYPE_MULTILAYER) { - image_init_imageuser(ima, iuser); + BKE_image_init_imageuser(ima, iuser); } } } @@ -3156,8 +3255,9 @@ void BKE_image_signal(Main *bmain, Image *ima, ImageUser *iuser, int signal) ima->ok = 1; - if (iuser) + if (iuser) { iuser->ok = 1; + } break; } @@ -3228,16 +3328,18 @@ RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser) RenderLayer *rl; RenderPass *rpass = NULL; - if (rr == NULL) + if (rr == NULL) { return NULL; + } if (iuser) { short index = 0, rv_index, rl_index = 0; bool is_stereo = (iuser->flag & IMA_SHOW_STEREO) && RE_RenderResult_is_stereo(rr); rv_index = is_stereo ? iuser->multiview_eye : iuser->view; - if (RE_HasCombinedLayer(rr)) + if (RE_HasCombinedLayer(rr)) { rl_index += 1; + } for (rl = rr->layers.first; rl; rl = rl->next, rl_index++) { if (iuser->layer == rl_index) { @@ -3318,8 +3420,9 @@ static void image_init_multilayer_multiview(Image *ima, RenderResult *rr) for (; rv; rv = rv->next, iv = iv->next) { modified |= !STREQ(rv->name, iv->name); } - if (!modified) + if (!modified) { return; + } } BKE_image_free_views(ima); @@ -3340,10 +3443,12 @@ RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima) rr = ima->rr; } else if (ima->type == IMA_TYPE_R_RESULT) { - if (ima->render_slot == ima->last_render_slot) + if (ima->render_slot == ima->last_render_slot) { rr = RE_AcquireResultRead(RE_GetSceneRender(scene)); - else + } + else { rr = BKE_image_get_renderslot(ima, ima->render_slot)->render; + } /* set proper views */ image_init_multilayer_multiview(ima, rr); @@ -3358,8 +3463,9 @@ void BKE_image_release_renderresult(Scene *scene, Image *ima) /* pass */ } else if (ima->type == IMA_TYPE_R_RESULT) { - if (ima->render_slot == ima->last_render_slot) + if (ima->render_slot == ima->last_render_slot) { RE_ReleaseResult(RE_GetSceneRender(scene)); + } } } @@ -3453,8 +3559,9 @@ static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr) bool predivide = (ima->alpha_mode == IMA_ALPHA_PREMUL); /* only load rr once for multiview */ - if (!ima->rr) + if (!ima->rr) { ima->rr = RE_MultilayerConvert(ibuf->userdata, colorspace, predivide, ibuf->x, ibuf->y); + } IMB_exr_close(ibuf->userdata); @@ -3488,10 +3595,12 @@ static int imbuf_alpha_flags_for_image(Image *ima) { int flag = 0; - if (ima->flag & IMA_IGNORE_ALPHA) + if (ima->flag & IMA_IGNORE_ALPHA) { flag |= IB_ignore_alpha; - else if (ima->alpha_mode == IMA_ALPHA_PREMUL) + } + else if (ima->alpha_mode == IMA_ALPHA_PREMUL) { flag |= IB_alphamode_premul; + } return flag; } @@ -3593,11 +3702,13 @@ static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame) ibuf_arr = MEM_mallocN(sizeof(ImBuf *) * totviews, "Image Views Imbufs"); - for (i = 0; i < totfiles; i++) + for (i = 0; i < totfiles; i++) { ibuf_arr[i] = load_sequence_single(ima, iuser, frame, i, &assign); + } - if (BKE_image_is_stereo(ima) && ima->views_format == R_IMF_VIEWS_STEREO_3D) + if (BKE_image_is_stereo(ima) && ima->views_format == R_IMF_VIEWS_STEREO_3D) { IMB_ImBufFromStereo3d(ima->stereo3d_format, ibuf_arr[0], &ibuf_arr[0], &ibuf_arr[1]); + } /* return the original requested ImBuf */ ibuf = ibuf_arr[(iuser ? iuser->multi_index : 0)]; @@ -3666,11 +3777,13 @@ static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int f } // else printf("pass not found\n"); } - else + else { ima->ok = 0; + } - if (iuser) + if (iuser) { iuser->ok = ima->ok; + } return ibuf; } @@ -3691,8 +3804,9 @@ static ImBuf *load_movie_single(Image *ima, ImageUser *iuser, int frame, const i flags |= IB_animdeinterlace; } - if (iuser) + if (iuser) { iuser_t = *iuser; + } iuser_t.view = view_id; @@ -3702,28 +3816,33 @@ static ImBuf *load_movie_single(Image *ima, ImageUser *iuser, int frame, const i ia->anim = openanim(str, flags, 0, ima->colorspace_settings.name); /* let's initialize this user */ - if (ia->anim && iuser && iuser->frames == 0) + if (ia->anim && iuser && iuser->frames == 0) { iuser->frames = IMB_anim_get_duration(ia->anim, IMB_TC_RECORD_RUN); + } } if (ia->anim) { int dur = IMB_anim_get_duration(ia->anim, IMB_TC_RECORD_RUN); int fra = frame - 1; - if (fra < 0) + if (fra < 0) { fra = 0; - if (fra > (dur - 1)) + } + if (fra > (dur - 1)) { fra = dur - 1; + } ibuf = IMB_makeSingleUser(IMB_anim_absolute(ia->anim, fra, IMB_TC_RECORD_RUN, IMB_PROXY_NONE)); if (ibuf) { image_initialize_after_load(ima, ibuf); } - else + else { ima->ok = 0; + } } - else + else { ima->ok = 0; + } return ibuf; } @@ -3759,8 +3878,9 @@ static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame) ibuf_arr[i] = load_movie_single(ima, iuser, frame, i); } - if (BKE_image_is_stereo(ima) && ima->views_format == R_IMF_VIEWS_STEREO_3D) + if (BKE_image_is_stereo(ima) && ima->views_format == R_IMF_VIEWS_STEREO_3D) { IMB_ImBufFromStereo3d(ima->stereo3d_format, ibuf_arr[0], &ibuf_arr[0], &ibuf_arr[1]); + } for (i = 0; i < totviews; i++) { if (ibuf_arr[i]) { @@ -3785,8 +3905,9 @@ static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame) MEM_freeN(ibuf_arr); } - if (iuser) + if (iuser) { iuser->ok = ima->ok; + } return ibuf; } @@ -3827,10 +3948,12 @@ static ImBuf *load_image_single(Image *ima, /* get the correct filepath */ BKE_image_user_frame_calc(iuser, cfra); - if (iuser) + if (iuser) { iuser_t = *iuser; - else + } + else { iuser_t.framenr = ima->lastframe; + } iuser_t.view = view_id; @@ -3911,8 +4034,9 @@ static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra) ibuf_arr = MEM_callocN(sizeof(ImBuf *) * totviews, "Image Views Imbufs"); - for (i = 0; i < totfiles; i++) + for (i = 0; i < totfiles; i++) { ibuf_arr[i] = load_image_single(ima, iuser, cfra, i, has_packed, &assign); + } /* multi-views/multi-layers OpenEXR files directly populate ima, and return NULL ibuf... */ if (BKE_image_is_stereo(ima) && ima->views_format == R_IMF_VIEWS_STEREO_3D && ibuf_arr[0] && @@ -3941,8 +4065,9 @@ static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra) MEM_freeN(ibuf_arr); } - if (iuser) + if (iuser) { iuser->ok = ima->ok; + } return ibuf; } @@ -3976,10 +4101,12 @@ static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser) } } - if (ibuf == NULL) + if (ibuf == NULL) { ima->ok = 0; - if (iuser) + } + if (iuser) { iuser->ok = ima->ok; + } return ibuf; } @@ -4001,12 +4128,14 @@ static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **r_loc int actview; bool byte_buffer_in_display_space = false; - if (!(iuser && iuser->scene)) + if (!(iuser && iuser->scene)) { return NULL; + } /* if we the caller is not going to release the lock, don't give the image */ - if (!r_lock) + if (!r_lock) { return NULL; + } re = RE_GetSceneRender(iuser->scene); @@ -4015,8 +4144,9 @@ static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **r_loc pass = iuser->pass; actview = iuser->view; - if (BKE_image_is_stereo(ima) && (iuser->flag & IMA_SHOW_STEREO)) + if (BKE_image_is_stereo(ima) && (iuser->flag & IMA_SHOW_STEREO)) { actview = iuser->multiview_eye; + } RenderSlot *slot; if (from_render) { @@ -4026,12 +4156,14 @@ static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **r_loc rres = *(slot->render); rres.have_combined = ((RenderView *)rres.views.first)->rectf != NULL; } - else + else { memset(&rres, 0, sizeof(RenderResult)); + } if (!(rres.rectx > 0 && rres.recty > 0)) { - if (from_render) + if (from_render) { RE_ReleaseResultImage(re); + } return NULL; } @@ -4043,8 +4175,9 @@ static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **r_loc } else { rv = BLI_findlink(&rres.views, actview); - if (rv == NULL) + if (rv == NULL) { rv = rres.views.first; + } } /* this gives active layer, composite or sequence result */ @@ -4094,9 +4227,11 @@ static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **r_loc } } - for (rpass = rl->passes.first; rpass; rpass = rpass->next) - if (STREQ(rpass->name, RE_PASSNAME_Z) && rpass->view_id == actview) + for (rpass = rl->passes.first; rpass; rpass = rpass->next) { + if (STREQ(rpass->name, RE_PASSNAME_Z) && rpass->view_id == actview) { rectz = rpass->rect; + } + } } } @@ -4148,8 +4283,9 @@ static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **r_loc * need check for whether byte buffer was allocated and owned by image itself * or if it's reusing buffer from render result */ - if ((ibuf->mall & IB_rect) == 0) + if ((ibuf->mall & IB_rect) == 0) { ibuf->rect = NULL; + } } if (rectf) { @@ -4262,8 +4398,9 @@ static ImBuf *image_get_cached_ibuf(Image *ima, ImageUser *iuser, int *r_frame, if (ibuf) { ima->ok = IMA_OK_LOADED; - if (iuser) + if (iuser) { iuser->ok = ima->ok; + } } } else if (ima->type == IMA_TYPE_MULTILAYER) { @@ -4272,10 +4409,12 @@ static ImBuf *image_get_cached_ibuf(Image *ima, ImageUser *iuser, int *r_frame, } } else if (ima->source == IMA_SRC_FILE) { - if (ima->type == IMA_TYPE_IMAGE) + if (ima->type == IMA_TYPE_IMAGE) { ibuf = image_get_cached_ibuf_for_index_frame(ima, index, 0); - else if (ima->type == IMA_TYPE_MULTILAYER) + } + else if (ima->type == IMA_TYPE_MULTILAYER) { ibuf = image_get_cached_ibuf_for_index_frame(ima, index, 0); + } } else if (ima->source == IMA_SRC_GENERATED) { ibuf = image_get_cached_ibuf_for_index_frame(ima, index, 0); @@ -4286,26 +4425,31 @@ static ImBuf *image_get_cached_ibuf(Image *ima, ImageUser *iuser, int *r_frame, * a big bottleneck */ } - if (r_frame) + if (r_frame) { *r_frame = frame; + } - if (r_index) + if (r_index) { *r_index = index; + } return ibuf; } BLI_INLINE bool image_quick_test(Image *ima, ImageUser *iuser) { - if (ima == NULL) + if (ima == NULL) { return false; + } if (iuser) { - if (iuser->ok == 0) + if (iuser->ok == 0) { return false; + } } - else if (ima->ok == 0) + else if (ima->ok == 0) { return false; + } return true; } @@ -4319,12 +4463,14 @@ static ImBuf *image_acquire_ibuf(Image *ima, ImageUser *iuser, void **r_lock) ImBuf *ibuf = NULL; int frame = 0, index = 0; - if (r_lock) + if (r_lock) { *r_lock = NULL; + } /* quick reject tests */ - if (!image_quick_test(ima, iuser)) + if (!image_quick_test(ima, iuser)) { return NULL; + } ibuf = image_get_cached_ibuf(ima, iuser, &frame, &index); @@ -4347,22 +4493,27 @@ static ImBuf *image_acquire_ibuf(Image *ima, ImageUser *iuser, void **r_lock) } else if (ima->source == IMA_SRC_FILE) { - if (ima->type == IMA_TYPE_IMAGE) + if (ima->type == IMA_TYPE_IMAGE) { ibuf = image_load_image_file(ima, iuser, frame); /* cfra only for '#', this global is OK */ + } /* no else; on load the ima type can change */ - if (ima->type == IMA_TYPE_MULTILAYER) + if (ima->type == IMA_TYPE_MULTILAYER) { /* keeps render result, stores ibufs in listbase, allows saving */ ibuf = image_get_ibuf_multilayer(ima, iuser); + } } else if (ima->source == IMA_SRC_GENERATED) { /* generated is: ibuf is allocated dynamically */ /* UV testgrid or black or solid etc */ - if (ima->gen_x == 0) + if (ima->gen_x == 0) { ima->gen_x = 1024; - if (ima->gen_y == 0) + } + if (ima->gen_y == 0) { ima->gen_y = 1024; - if (ima->gen_depth == 0) + } + if (ima->gen_depth == 0) { ima->gen_depth = 24; + } ibuf = add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, @@ -4458,15 +4609,17 @@ bool BKE_image_has_ibuf(Image *ima, ImageUser *iuser) ImBuf *ibuf; /* quick reject tests */ - if (!image_quick_test(ima, iuser)) + if (!image_quick_test(ima, iuser)) { return false; + } BLI_spin_lock(&image_spin); ibuf = image_get_cached_ibuf(ima, iuser, NULL, NULL); - if (!ibuf) + if (!ibuf) { ibuf = image_acquire_ibuf(ima, iuser, NULL); + } BLI_spin_unlock(&image_spin); @@ -4536,8 +4689,9 @@ ImBuf *BKE_image_pool_acquire_ibuf(Image *ima, ImageUser *iuser, ImagePool *pool int index, frame; bool found; - if (!image_quick_test(ima, iuser)) + if (!image_quick_test(ima, iuser)) { return NULL; + } if (pool == NULL) { /* pool could be NULL, in this case use general acquire function */ @@ -4547,8 +4701,9 @@ ImBuf *BKE_image_pool_acquire_ibuf(Image *ima, ImageUser *iuser, ImagePool *pool image_get_frame_and_index(ima, iuser, &frame, &index); ibuf = image_pool_find_entry(pool, ima, frame, index, &found); - if (found) + if (found) { return ibuf; + } BLI_spin_lock(&image_spin); @@ -4604,10 +4759,12 @@ int BKE_image_user_frame_get(const ImageUser *iuser, int cfra, bool *r_is_in_ran /* cyclic */ if (iuser->cycl) { cfra = ((cfra) % len); - if (cfra < 0) + if (cfra < 0) { cfra += len; - if (cfra == 0) + } + if (cfra == 0) { cfra = len; + } if (r_is_in_range) { *r_is_in_range = true; @@ -4628,15 +4785,18 @@ int BKE_image_user_frame_get(const ImageUser *iuser, int cfra, bool *r_is_in_ran /* transform to images space */ framenr = cfra; - if (framenr > iuser->frames) + if (framenr > iuser->frames) { framenr = iuser->frames; + } if (iuser->cycl) { framenr = ((framenr) % len); - while (framenr < 0) + while (framenr < 0) { framenr += len; - if (framenr == 0) + } + if (framenr == 0) { framenr = len; + } } /* important to apply after else we cant loop on frames 100 - 110 for eg. */ @@ -4660,8 +4820,9 @@ void BKE_image_user_frame_calc(ImageUser *iuser, int cfra) } iuser->framenr = framenr; - if (iuser->ok == 0) + if (iuser->ok == 0) { iuser->ok = 1; + } } } @@ -4751,10 +4912,12 @@ void BKE_image_user_file_path(ImageUser *iuser, Image *ima, char *filepath) { if (BKE_image_is_multiview(ima)) { ImageView *iv = BLI_findlink(&ima->views, iuser->view); - if (iv->filepath[0]) + if (iv->filepath[0]) { BLI_strncpy(filepath, iv->filepath, FILE_MAX); - else + } + else { BLI_strncpy(filepath, ima->name, FILE_MAX); + } } else { BLI_strncpy(filepath, ima->name, FILE_MAX); @@ -4782,10 +4945,12 @@ bool BKE_image_has_alpha(struct Image *image) planes = (ibuf ? ibuf->planes : 0); BKE_image_release_ibuf(image, ibuf, lock); - if (planes == 32) + if (planes == 32) { return true; - else + } + else { return false; + } } void BKE_image_get_size(Image *image, ImageUser *iuser, int *width, int *height) @@ -4835,10 +5000,12 @@ void BKE_image_get_aspect(Image *image, float *aspx, float *aspy) *aspx = 1.0; /* x is always 1 */ - if (image) + if (image) { *aspy = image->aspy / image->aspx; - else + } + else { *aspy = 1.0f; + } } unsigned char *BKE_image_get_pixels_for_frame(struct Image *image, int frame) @@ -4856,14 +5023,16 @@ unsigned char *BKE_image_get_pixels_for_frame(struct Image *image, int frame) if (ibuf) { pixels = (unsigned char *)ibuf->rect; - if (pixels) + if (pixels) { pixels = MEM_dupallocN(pixels); + } BKE_image_release_ibuf(image, ibuf, lock); } - if (!pixels) + if (!pixels) { return NULL; + } return pixels; } @@ -4883,14 +5052,16 @@ float *BKE_image_get_float_pixels_for_frame(struct Image *image, int frame) if (ibuf) { pixels = ibuf->rect_float; - if (pixels) + if (pixels) { pixels = MEM_dupallocN(pixels); + } BKE_image_release_ibuf(image, ibuf, lock); } - if (!pixels) + if (!pixels) { return NULL; + } return pixels; } @@ -5142,20 +5313,26 @@ bool BKE_image_remove_renderslot(Image *ima, ImageUser *iuser, int index) next_slot = current_slot; } - /* If the slot to be removed is the slot with the last render, make another slot the last render slot. */ + /* If the slot to be removed is the slot with the last render, + * make another slot the last render slot. */ if (remove_slot == current_last_slot) { - /* Choose the currently selected slot unless that one is being removed, in that case take the next one. */ + /* Choose the currently selected slot unless that one is being removed, + * in that case take the next one. */ RenderSlot *next_last_slot; - if (current_slot == remove_slot) + if (current_slot == remove_slot) { next_last_slot = next_slot; - else + } + else { next_last_slot = current_slot; + } - if (!iuser) + if (!iuser) { return false; + } Render *re = RE_GetSceneRender(iuser->scene); - if (!re) + if (!re) { return false; + } RE_SwapResult(re, ¤t_last_slot->render); RE_SwapResult(re, &next_last_slot->render); current_last_slot = next_last_slot; @@ -5179,20 +5356,24 @@ bool BKE_image_remove_renderslot(Image *ima, ImageUser *iuser, int index) bool BKE_image_clear_renderslot(Image *ima, ImageUser *iuser, int index) { if (index == ima->last_render_slot) { - if (!iuser) + if (!iuser) { return false; - if (G.is_rendering) + } + if (G.is_rendering) { return false; + } Render *re = RE_GetSceneRender(iuser->scene); - if (!re) + if (!re) { return false; + } RE_ClearResult(re); return true; } else { RenderSlot *slot = BLI_findlink(&ima->renderslots, index); - if (!slot) + if (!slot) { return false; + } if (slot->render) { RE_FreeRenderResult(slot->render); slot->render = NULL; diff --git a/source/blender/blenkernel/intern/image_gen.c b/source/blender/blenkernel/intern/image_gen.c index 9972e90dcdd..c7fdfb60a1c 100644 --- a/source/blender/blenkernel/intern/image_gen.c +++ b/source/blender/blenkernel/intern/image_gen.c @@ -123,8 +123,9 @@ static void image_buf_fill_checker_slice( dark = powf(-1.0f, floorf(y / checkerwidth)); for (x = 0; x < width; x++) { - if (x % checkerwidth == 0) + if (x % checkerwidth == 0) { dark = -dark; + } if (rect_float) { if (dark > 0) { @@ -182,10 +183,12 @@ static void image_buf_fill_checker_slice( } } - if (rect_float) + if (rect_float) { rect_float += 4; - if (rect) + } + if (rect) { rect += 4; + } } } } @@ -234,8 +237,9 @@ static void checker_board_color_fill( hsv[1] = 1.0; hue_step = power_of_2_max_i(width / 8); - if (hue_step < 8) + if (hue_step < 8) { hue_step = 8; + } for (y = offset; y < height + offset; y++) { @@ -345,10 +349,12 @@ static void checker_board_grid_fill( } } else { - if (rect_float) + if (rect_float) { rect_float += 4; - if (rect) + } + if (rect) { rect += 4; + } } } } diff --git a/source/blender/blenkernel/intern/image_save.c b/source/blender/blenkernel/intern/image_save.c new file mode 100644 index 00000000000..cc621e8468c --- /dev/null +++ b/source/blender/blenkernel/intern/image_save.c @@ -0,0 +1,394 @@ +/* + * ***** BEGIN GPL LICENSE BLOCK ***** + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. + * All rights reserved. + * + * Contributor(s): Blender Foundation, 2019 + * + * ***** END GPL LICENSE BLOCK ***** + */ + +/** \file blender/blenkernel/intern/image_save.c + * \ingroup bke + */ + +#include <errno.h> +#include <string.h> + +#include "BLI_listbase.h" +#include "BLI_path_util.h" +#include "BLI_string.h" + +#include "DNA_image_types.h" + +#include "IMB_colormanagement.h" +#include "IMB_imbuf.h" +#include "IMB_imbuf_types.h" + +#include "BKE_colortools.h" +#include "BKE_image.h" +#include "BKE_image_save.h" +#include "BKE_main.h" +#include "BKE_report.h" +#include "BKE_scene.h" + +#include "RE_pipeline.h" + +void BKE_image_save_options_init(ImageSaveOptions *opts, Main *bmain, Scene *scene) +{ + memset(opts, 0, sizeof(*opts)); + + opts->bmain = bmain; + opts->scene = scene; + + BKE_imformat_defaults(&opts->im_format); +} + +static void image_save_post(ReportList *reports, + Main *bmain, + Image *ima, + ImBuf *ibuf, + int ok, + ImageSaveOptions *opts, + int save_copy, + const char *filepath) +{ + if (!ok) { + BKE_reportf(reports, RPT_ERROR, "Could not write image: %s", strerror(errno)); + return; + } + + if (save_copy) { + return; + } + + if (opts->do_newpath) { + BLI_strncpy(ibuf->name, filepath, sizeof(ibuf->name)); + BLI_strncpy(ima->name, filepath, sizeof(ima->name)); + } + + ibuf->userflags &= ~IB_BITMAPDIRTY; + + /* change type? */ + if (ima->type == IMA_TYPE_R_RESULT) { + ima->type = IMA_TYPE_IMAGE; + + /* workaround to ensure the render result buffer is no longer used + * by this image, otherwise can crash when a new render result is + * created. */ + if (ibuf->rect && !(ibuf->mall & IB_rect)) { + imb_freerectImBuf(ibuf); + } + if (ibuf->rect_float && !(ibuf->mall & IB_rectfloat)) { + imb_freerectfloatImBuf(ibuf); + } + if (ibuf->zbuf && !(ibuf->mall & IB_zbuf)) { + IMB_freezbufImBuf(ibuf); + } + if (ibuf->zbuf_float && !(ibuf->mall & IB_zbuffloat)) { + IMB_freezbuffloatImBuf(ibuf); + } + } + if (ELEM(ima->source, IMA_SRC_GENERATED, IMA_SRC_VIEWER)) { + ima->source = IMA_SRC_FILE; + ima->type = IMA_TYPE_IMAGE; + } + + /* only image path, never ibuf */ + if (opts->relative) { + const char *relbase = ID_BLEND_PATH(opts->bmain, &ima->id); + BLI_path_rel(ima->name, 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)) { + BKE_image_signal(bmain, ima, NULL, IMA_SIGNAL_COLORMANAGE); + } +} + +static void imbuf_save_post(ImBuf *ibuf, ImBuf *colormanaged_ibuf) +{ + if (colormanaged_ibuf != ibuf) { + /* This guys might be modified by image buffer write functions, + * need to copy them back from color managed image buffer to an + * original one, so file type of image is being properly updated. + */ + ibuf->ftype = colormanaged_ibuf->ftype; + ibuf->foptions = colormanaged_ibuf->foptions; + ibuf->planes = colormanaged_ibuf->planes; + + IMB_freeImBuf(colormanaged_ibuf); + } +} + +/** + * \return success. + * \note ``ima->name`` and ``ibuf->name`` should end up the same. + * \note for multiview the first ``ibuf`` is important to get the settings. + */ +bool BKE_image_save( + ReportList *reports, Main *bmain, Image *ima, ImageUser *iuser, ImageSaveOptions *opts) +{ + void *lock; + ImBuf *ibuf = BKE_image_acquire_ibuf(ima, iuser, &lock); + RenderResult *rr = NULL; + bool ok = false; + + if (ibuf == NULL || (ibuf->rect == NULL && ibuf->rect_float == NULL)) { + BKE_image_release_ibuf(ima, ibuf, lock); + goto cleanup; + } + + ImBuf *colormanaged_ibuf = NULL; + const bool save_copy = opts->save_copy; + const bool save_as_render = opts->save_as_render; + ImageFormatData *imf = &opts->im_format; + + if (ima->type == IMA_TYPE_R_RESULT) { + /* enforce user setting for RGB or RGBA, but skip BW */ + if (opts->im_format.planes == R_IMF_PLANES_RGBA) { + ibuf->planes = R_IMF_PLANES_RGBA; + } + else if (opts->im_format.planes == R_IMF_PLANES_RGB) { + ibuf->planes = R_IMF_PLANES_RGB; + } + } + else { + /* TODO, better solution, if a 24bit image is painted onto it may contain alpha */ + if ((opts->im_format.planes == R_IMF_PLANES_RGBA) && + /* it has been painted onto */ + (ibuf->userflags & IB_BITMAPDIRTY)) { + /* checks each pixel, not ideal */ + ibuf->planes = BKE_imbuf_alpha_test(ibuf) ? R_IMF_PLANES_RGBA : R_IMF_PLANES_RGB; + } + } + + /* 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; + + /* error handling */ + if (!rr) { + if (imf->imtype == R_IMF_IMTYPE_MULTILAYER) { + BKE_report(reports, RPT_ERROR, "Did not write, no Multilayer Image"); + BKE_image_release_ibuf(ima, ibuf, lock); + goto cleanup; + } + } + else { + if (imf->views_format == R_IMF_VIEWS_STEREO_3D) { + if (!BKE_image_is_stereo(ima)) { + BKE_reportf(reports, + RPT_ERROR, + "Did not write, the image doesn't have a \"%s\" and \"%s\" views", + STEREO_LEFT_NAME, + STEREO_RIGHT_NAME); + BKE_image_release_ibuf(ima, ibuf, lock); + goto cleanup; + } + + /* it shouldn't ever happen*/ + if ((BLI_findstring(&rr->views, STEREO_LEFT_NAME, offsetof(RenderView, name)) == NULL) || + (BLI_findstring(&rr->views, STEREO_RIGHT_NAME, offsetof(RenderView, name)) == NULL)) { + BKE_reportf(reports, + RPT_ERROR, + "Did not write, the image doesn't have a \"%s\" and \"%s\" views", + STEREO_LEFT_NAME, + STEREO_RIGHT_NAME); + BKE_image_release_ibuf(ima, ibuf, lock); + goto cleanup; + } + } + BKE_imbuf_stamp_info(rr, ibuf); + } + + /* fancy multiview OpenEXR */ + if (imf->views_format == R_IMF_VIEWS_MULTIVIEW && is_exr_rr) { + /* save render result */ + ok = RE_WriteRenderResult(reports, rr, opts->filepath, imf, NULL, layer); + image_save_post(reports, bmain, ima, ibuf, ok, opts, true, opts->filepath); + BKE_image_release_ibuf(ima, ibuf, lock); + } + /* regular mono pipeline */ + else if (is_mono) { + if (is_exr_rr) { + ok = RE_WriteRenderResult(reports, rr, opts->filepath, imf, NULL, layer); + } + else { + colormanaged_ibuf = IMB_colormanagement_imbuf_for_write( + ibuf, save_as_render, true, &imf->view_settings, &imf->display_settings, imf); + ok = BKE_imbuf_write_as(colormanaged_ibuf, opts->filepath, imf, save_copy); + imbuf_save_post(ibuf, colormanaged_ibuf); + } + image_save_post( + reports, bmain, ima, ibuf, ok, opts, (is_exr_rr ? true : save_copy), opts->filepath); + BKE_image_release_ibuf(ima, ibuf, lock); + } + /* individual multiview images */ + else if (imf->views_format == R_IMF_VIEWS_INDIVIDUAL) { + int i; + unsigned char planes = ibuf->planes; + const int totviews = (rr ? BLI_listbase_count(&rr->views) : BLI_listbase_count(&ima->views)); + + if (!is_exr_rr) { + BKE_image_release_ibuf(ima, ibuf, lock); + } + + for (i = 0; i < totviews; i++) { + char filepath[FILE_MAX]; + bool ok_view = false; + const char *view = rr ? ((RenderView *)BLI_findlink(&rr->views, i))->name : + ((ImageView *)BLI_findlink(&ima->views, i))->name; + + if (is_exr_rr) { + BKE_scene_multiview_view_filepath_get(&opts->scene->r, opts->filepath, view, filepath); + ok_view = RE_WriteRenderResult(reports, rr, filepath, imf, view, layer); + image_save_post(reports, bmain, ima, ibuf, ok_view, opts, true, filepath); + } + else { + /* copy iuser to get the correct ibuf for this view */ + ImageUser view_iuser; + + if (iuser) { + /* copy iuser to get the correct ibuf for this view */ + view_iuser = *iuser; + } + else { + BKE_imageuser_default(&view_iuser); + } + + view_iuser.view = i; + view_iuser.flag &= ~IMA_SHOW_STEREO; + + if (rr) { + BKE_image_multilayer_index(rr, &view_iuser); + } + else { + BKE_image_multiview_index(ima, &view_iuser); + } + + ibuf = BKE_image_acquire_ibuf(ima, &view_iuser, &lock); + ibuf->planes = planes; + + BKE_scene_multiview_view_filepath_get(&opts->scene->r, opts->filepath, view, filepath); + + colormanaged_ibuf = IMB_colormanagement_imbuf_for_write( + ibuf, save_as_render, true, &imf->view_settings, &imf->display_settings, imf); + ok_view = BKE_imbuf_write_as(colormanaged_ibuf, filepath, &opts->im_format, save_copy); + imbuf_save_post(ibuf, colormanaged_ibuf); + image_save_post(reports, bmain, ima, ibuf, ok_view, opts, true, filepath); + BKE_image_release_ibuf(ima, ibuf, lock); + } + ok &= ok_view; + } + + if (is_exr_rr) { + BKE_image_release_ibuf(ima, ibuf, lock); + } + } + /* stereo (multiview) images */ + else if (opts->im_format.views_format == R_IMF_VIEWS_STEREO_3D) { + if (imf->imtype == R_IMF_IMTYPE_MULTILAYER) { + ok = RE_WriteRenderResult(reports, rr, opts->filepath, imf, NULL, layer); + image_save_post(reports, bmain, ima, ibuf, ok, opts, true, opts->filepath); + BKE_image_release_ibuf(ima, ibuf, lock); + } + else { + ImBuf *ibuf_stereo[2] = {NULL}; + + unsigned char planes = ibuf->planes; + const char *names[2] = {STEREO_LEFT_NAME, STEREO_RIGHT_NAME}; + int i; + + /* we need to get the specific per-view buffers */ + BKE_image_release_ibuf(ima, ibuf, lock); + + for (i = 0; i < 2; i++) { + ImageUser view_iuser; + + if (iuser) { + view_iuser = *iuser; + } + else { + BKE_imageuser_default(&view_iuser); + } + + view_iuser.flag &= ~IMA_SHOW_STEREO; + + if (rr) { + int id = BLI_findstringindex(&rr->views, names[i], offsetof(RenderView, name)); + view_iuser.view = id; + BKE_image_multilayer_index(rr, &view_iuser); + } + else { + view_iuser.view = i; + BKE_image_multiview_index(ima, &view_iuser); + } + + ibuf = BKE_image_acquire_ibuf(ima, &view_iuser, &lock); + + if (ibuf == NULL) { + BKE_report( + reports, RPT_ERROR, "Did not write, unexpected error when saving stereo image"); + goto cleanup; + } + + ibuf->planes = planes; + + /* color manage the ImBuf leaving it ready for saving */ + colormanaged_ibuf = IMB_colormanagement_imbuf_for_write( + ibuf, save_as_render, true, &imf->view_settings, &imf->display_settings, imf); + + BKE_imbuf_write_prepare(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); + + imbuf_save_post(ibuf, colormanaged_ibuf); + BKE_image_release_ibuf(ima, ibuf, lock); + } + + ibuf = IMB_stereo3d_ImBuf(imf, ibuf_stereo[0], ibuf_stereo[1]); + + /* save via traditional path */ + ok = BKE_imbuf_write_as(ibuf, opts->filepath, imf, save_copy); + + IMB_freeImBuf(ibuf); + + for (i = 0; i < 2; i++) { + IMB_freeImBuf(ibuf_stereo[i]); + } + } + } + +cleanup: + if (rr) { + BKE_image_release_renderresult(opts->scene, ima); + } + + return ok; +} diff --git a/source/blender/blenkernel/intern/ipo.c b/source/blender/blenkernel/intern/ipo.c index 8f3b1fed692..63ef1458de8 100644 --- a/source/blender/blenkernel/intern/ipo.c +++ b/source/blender/blenkernel/intern/ipo.c @@ -92,18 +92,22 @@ void BKE_ipo_free(Ipo *ipo) icn = icu->next; n++; - if (icu->bezt) + if (icu->bezt) { MEM_freeN(icu->bezt); - if (icu->bp) + } + if (icu->bp) { MEM_freeN(icu->bp); - if (icu->driver) + } + if (icu->driver) { MEM_freeN(icu->driver); + } BLI_freelinkN(&ipo->curve, icu); } - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("Freed %d (Unconverted) Ipo-Curves from IPO '%s'\n", n, ipo->id.name + 2); + } } /* *************************************************** */ @@ -235,22 +239,28 @@ static const char *ob_adrcodes_to_paths(int adrcode, int *array_index) return "color"; #if 0 case OB_PD_FSTR: - if (ob->pd) poin = &(ob->pd->f_strength); + if (ob->pd) + poin = &(ob->pd->f_strength); break; case OB_PD_FFALL: - if (ob->pd) poin = &(ob->pd->f_power); + if (ob->pd) + poin = &(ob->pd->f_power); break; case OB_PD_SDAMP: - if (ob->pd) poin = &(ob->pd->pdef_damp); + if (ob->pd) + poin = &(ob->pd->pdef_damp); break; case OB_PD_RDAMP: - if (ob->pd) poin = &(ob->pd->pdef_rdamp); + if (ob->pd) + poin = &(ob->pd->pdef_rdamp); break; case OB_PD_PERM: - if (ob->pd) poin = &(ob->pd->pdef_perm); + if (ob->pd) + poin = &(ob->pd->pdef_perm); break; case OB_PD_FMAXD: - if (ob->pd) poin = &(ob->pd->maxdist); + if (ob->pd) + poin = &(ob->pd->maxdist); break; #endif } @@ -327,7 +337,8 @@ static const char *constraint_adrcodes_to_paths(int adrcode, int *array_index) switch (adrcode) { case CO_ENFORCE: return "influence"; - case CO_HEADTAIL: // XXX this needs to be wrapped in RNA.. probably then this path will be invalid + case CO_HEADTAIL: + /* XXX this needs to be wrapped in RNA.. probably then this path will be invalid. */ return "data.head_tail"; } @@ -372,73 +383,104 @@ static const char *mtex_adrcodes_to_paths(int adrcode, int *UNUSED(array_index)) static char buf[128]; /* base part of path */ - if (adrcode & MA_MAP1) + if (adrcode & MA_MAP1) { base = "textures[0]"; - else if (adrcode & MA_MAP2) + } + else if (adrcode & MA_MAP2) { base = "textures[1]"; - else if (adrcode & MA_MAP3) + } + else if (adrcode & MA_MAP3) { base = "textures[2]"; - else if (adrcode & MA_MAP4) + } + else if (adrcode & MA_MAP4) { base = "textures[3]"; - else if (adrcode & MA_MAP5) + } + else if (adrcode & MA_MAP5) { base = "textures[4]"; - else if (adrcode & MA_MAP6) + } + else if (adrcode & MA_MAP6) { base = "textures[5]"; - else if (adrcode & MA_MAP7) + } + else if (adrcode & MA_MAP7) { base = "textures[6]"; - else if (adrcode & MA_MAP8) + } + else if (adrcode & MA_MAP8) { base = "textures[7]"; - else if (adrcode & MA_MAP9) + } + else if (adrcode & MA_MAP9) { base = "textures[8]"; - else if (adrcode & MA_MAP10) + } + else if (adrcode & MA_MAP10) { base = "textures[9]"; - else if (adrcode & MA_MAP11) + } + else if (adrcode & MA_MAP11) { base = "textures[10]"; - else if (adrcode & MA_MAP12) + } + else if (adrcode & MA_MAP12) { base = "textures[11]"; - else if (adrcode & MA_MAP13) + } + else if (adrcode & MA_MAP13) { base = "textures[12]"; - else if (adrcode & MA_MAP14) + } + else if (adrcode & MA_MAP14) { base = "textures[13]"; - else if (adrcode & MA_MAP15) + } + else if (adrcode & MA_MAP15) { base = "textures[14]"; - else if (adrcode & MA_MAP16) + } + else if (adrcode & MA_MAP16) { base = "textures[15]"; - else if (adrcode & MA_MAP17) + } + else if (adrcode & MA_MAP17) { base = "textures[16]"; - else if (adrcode & MA_MAP18) + } + else if (adrcode & MA_MAP18) { base = "textures[17]"; + } /* property identifier for path */ adrcode = (adrcode & (MA_MAP1 - 1)); switch (adrcode) { #if 0 // XXX these are not wrapped in RNA yet! case MAP_OFS_X: - poin = &(mtex->ofs[0]); break; + poin = &(mtex->ofs[0]); + break; case MAP_OFS_Y: - poin = &(mtex->ofs[1]); break; + poin = &(mtex->ofs[1]); + break; case MAP_OFS_Z: - poin = &(mtex->ofs[2]); break; + poin = &(mtex->ofs[2]); + break; case MAP_SIZE_X: - poin = &(mtex->size[0]); break; + poin = &(mtex->size[0]); + break; case MAP_SIZE_Y: - poin = &(mtex->size[1]); break; + poin = &(mtex->size[1]); + break; case MAP_SIZE_Z: - poin = &(mtex->size[2]); break; + poin = &(mtex->size[2]); + break; case MAP_R: - poin = &(mtex->r); break; + poin = &(mtex->r); + break; case MAP_G: - poin = &(mtex->g); break; + poin = &(mtex->g); + break; case MAP_B: - poin = &(mtex->b); break; + poin = &(mtex->b); + break; case MAP_DVAR: - poin = &(mtex->def_var); break; + poin = &(mtex->def_var); + break; case MAP_COLF: - poin = &(mtex->colfac); break; + poin = &(mtex->colfac); + break; case MAP_NORF: - poin = &(mtex->norfac); break; + poin = &(mtex->norfac); + break; case MAP_VARF: - poin = &(mtex->varfac); break; + poin = &(mtex->varfac); + break; #endif case MAP_DISP: prop = "warp_factor"; @@ -450,8 +492,9 @@ static const char *mtex_adrcodes_to_paths(int adrcode, int *UNUSED(array_index)) BLI_snprintf(buf, 128, "%s.%s", base, prop); return buf; } - else + else { return NULL; + } } /* Texture types */ @@ -468,10 +511,10 @@ static const char *texture_adrcodes_to_paths(int adrcode, int *array_index) return "turbulence"; case TE_NDEPTH: // XXX texture RNA undefined - //poin= &(tex->noisedepth); *type= IPO_SHORT; break; + // poin= &(tex->noisedepth); *type= IPO_SHORT; break; break; case TE_NTYPE: // XXX texture RNA undefined - //poin= &(tex->noisetype); *type= IPO_SHORT; break; + // poin= &(tex->noisetype); *type= IPO_SHORT; break; break; case TE_N_BAS1: @@ -643,12 +686,13 @@ static const char *camera_adrcodes_to_paths(int adrcode, int *array_index) /* result depends on adrcode */ switch (adrcode) { case CAM_LENS: -#if 0 // XXX this cannot be resolved easily... perhaps we assume camera is perspective (works for most cases... +#if 0 /* XXX this cannot be resolved easily... \ + * perhaps we assume camera is perspective (works for most cases... */ if (ca->type == CAM_ORTHO) return "ortho_scale"; else return "lens"; -#else // XXX lazy hack for now... +#else // XXX lazy hack for now... return "lens"; #endif // XXX this cannot be resolved easily @@ -659,9 +703,11 @@ static const char *camera_adrcodes_to_paths(int adrcode, int *array_index) #if 0 // XXX these are not defined in RNA case CAM_YF_APERT: - poin = &(ca->YF_aperture); break; + poin = &(ca->YF_aperture); + break; case CAM_YF_FDIST: - poin = &(ca->dof_distance); break; + poin = &(ca->dof_distance); + break; #endif // XXX these are not defined in RNA case CAM_SHIFT_X: @@ -731,7 +777,8 @@ static const char *sound_adrcodes_to_paths(int adrcode, int *array_index) return "volume"; case SND_PITCH: return "pitch"; - /* XXX Joshua -- I had wrapped panning in rna, but someone commented out, calling it "unused" */ + /* XXX Joshua -- I had wrapped panning in rna, + * but someone commented out, calling it "unused" */ #if 0 case SND_PANNING: return "panning"; @@ -831,28 +878,34 @@ static const char *particle_adrcodes_to_paths(int adrcode, int *array_index) return "settings.billboard_tilt"; /* PartDeflect needs to be sorted out properly in rna_object_force; - * If anyone else works on this, but is unfamiliar, these particular - * settings reference the particles of the system themselves - * being used as forces -- it will use the same rna structure - * as the similar object forces */ + * If anyone else works on this, but is unfamiliar, these particular + * settings reference the particles of the system themselves + * being used as forces -- it will use the same rna structure + * as the similar object forces */ #if 0 case PART_PD_FSTR: - if (part->pd) poin = &(part->pd->f_strength); + if (part->pd) + poin = &(part->pd->f_strength); break; case PART_PD_FFALL: - if (part->pd) poin = &(part->pd->f_power); + if (part->pd) + poin = &(part->pd->f_power); break; case PART_PD_FMAXD: - if (part->pd) poin = &(part->pd->maxdist); + if (part->pd) + poin = &(part->pd->maxdist); break; case PART_PD2_FSTR: - if (part->pd2) poin = &(part->pd2->f_strength); + if (part->pd2) + poin = &(part->pd2->f_strength); break; case PART_PD2_FFALL: - if (part->pd2) poin = &(part->pd2->f_power); + if (part->pd2) + poin = &(part->pd2->f_power); break; case PART_PD2_FMAXD: - if (part->pd2) poin = &(part->pd2->maxdist); + if (part->pd2) + poin = &(part->pd2->maxdist); break; #endif } @@ -862,14 +915,17 @@ static const char *particle_adrcodes_to_paths(int adrcode, int *array_index) /* ------- */ -/* Allocate memory for RNA-path for some property given a blocktype, adrcode, and 'root' parts of path +/* Allocate memory for RNA-path for some property given a blocktype, adrcode, + * and 'root' parts of path. + * * Input: - * - id - the datablock that the curve's IPO block is attached to and/or which the new paths will start from - * - blocktype, adrcode - determines setting to get - * - actname, constname,seq - used to build path + * - id - the datablock that the curve's IPO block + * is attached to and/or which the new paths will start from + * - blocktype, adrcode - determines setting to get + * - actname, constname, seq - used to build path * Output: - * - array_index - index in property's array (if applicable) to use - * - return - the allocated path... + * - array_index - index in property's array (if applicable) to use + * - return - the allocated path... */ static char *get_rna_access(ID *id, int blocktype, @@ -886,8 +942,9 @@ static char *get_rna_access(ID *id, int dummy_index = 0; /* hack: if constname is set, we can only be dealing with an Constraint curve */ - if (constname) + if (constname) { blocktype = ID_CO; + } /* get property name based on blocktype */ switch (blocktype) { @@ -944,7 +1001,7 @@ static char *get_rna_access(ID *id, /* XXX problematic blocktypes */ case ID_SEQ: /* sequencer strip */ - //SEQ_FAC1: + // SEQ_FAC1: switch (adrcode) { case SEQ_FAC1: propname = "effect_fader"; @@ -971,20 +1028,23 @@ static char *get_rna_access(ID *id, } /* check if any property found - * - blocktype < 0 is special case for a specific type of driver, where we don't need a property name... + * - blocktype < 0 is special case for a specific type of driver, + * where we don't need a property name... */ if ((propname == NULL) && (blocktype > 0)) { /* nothing was found, so exit */ - if (array_index) + if (array_index) { *array_index = 0; + } BLI_dynstr_free(path); return NULL; } else { - if (array_index) + if (array_index) { *array_index = dummy_index; + } } /* 'buf' _must_ be initialized in this block */ @@ -1000,7 +1060,8 @@ static char *get_rna_access(ID *id, buf[0] = '\0'; /* empty string */ } else if ((blocktype == ID_KE) && STREQ(actname, "Shape")) { - /* Actionified "Shape" IPO's - these are forced onto object level via the action container there... */ + /* Actionified "Shape" IPO's - + * these are forced onto object level via the action container there... */ strcpy(buf, "data.shape_keys"); } else { @@ -1023,8 +1084,9 @@ static char *get_rna_access(ID *id, BLI_dynstr_append(path, buf); /* need to add dot before property if there was anything precceding this */ - if (buf[0]) + if (buf[0]) { BLI_dynstr_append(path, "."); + } /* now write name of property */ BLI_dynstr_append(path, propname); @@ -1089,8 +1151,9 @@ static ChannelDriver *idriver_to_cdriver(IpoDriver *idriver) /* PyDriver only requires the expression to be copied */ // FIXME: expression will be useless due to API changes, but at least not totally lost cdriver->type = DRIVER_TYPE_PYTHON; - if (idriver->name[0]) + if (idriver->name[0]) { BLI_strncpy(cdriver->expression, idriver->name, sizeof(cdriver->expression)); + } } else { DriverVar *dvar = NULL; @@ -1110,16 +1173,18 @@ static ChannelDriver *idriver_to_cdriver(IpoDriver *idriver) dtar = &dvar->targets[0]; dtar->id = (ID *)idriver->ob; dtar->idtype = ID_OB; - if (idriver->name[0]) + if (idriver->name[0]) { BLI_strncpy(dtar->pchan_name, idriver->name, sizeof(dtar->pchan_name)); + } /* second bone target (name was stored in same var as the first one) */ dtar = &dvar->targets[1]; dtar->id = (ID *)idriver->ob; dtar->idtype = ID_OB; - if (idriver->name[0]) // xxx... for safety + if (idriver->name[0]) { // xxx... for safety BLI_strncpy( dtar->pchan_name, idriver->name + DRIVER_NAME_OFFS, sizeof(dtar->pchan_name)); + } } else { /* only a single variable, of type 'transform channel' */ @@ -1130,8 +1195,9 @@ static ChannelDriver *idriver_to_cdriver(IpoDriver *idriver) dtar = &dvar->targets[0]; dtar->id = (ID *)idriver->ob; dtar->idtype = ID_OB; - if (idriver->name[0]) + if (idriver->name[0]) { BLI_strncpy(dtar->pchan_name, idriver->name, sizeof(dtar->pchan_name)); + } dtar->transChan = adrcode_to_dtar_transchan(idriver->adrcode); dtar->flag |= DTAR_FLAG_LOCALSPACE; /* old drivers took local space */ } @@ -1183,8 +1249,9 @@ static void fcurve_add_to_list( agrp = MEM_callocN(sizeof(bActionGroup), "bActionGroup"); agrp->flag = AGRP_SELECTED; - if (muteipo) + if (muteipo) { agrp->flag |= AGRP_MUTED; + } BLI_strncpy(agrp->name, grpname, sizeof(agrp->name)); @@ -1198,11 +1265,13 @@ static void fcurve_add_to_list( } /* add F-Curve to group */ - /* WARNING: this func should only need to look at the stuff we initialized, if not, things may crash */ + /* WARNING: this func should only need to look at the stuff we initialized, + * if not, things may crash. */ action_groups_add_channel(&tmp_act, agrp, fcu); - if (agrp->flag & AGRP_MUTED) /* flush down */ + if (agrp->flag & AGRP_MUTED) { /* flush down */ fcu->flag |= FCURVE_MUTED; + } /* set the output lists based on the ones in the temp action */ groups->first = tmp_act.groups.first; @@ -1216,11 +1285,14 @@ static void fcurve_add_to_list( } } -/* Convert IPO-Curve to F-Curve (including Driver data), and free any of the old data that +/** + * Convert IPO-Curve to F-Curve (including Driver data), and free any of the old data that * is not relevant, BUT do not free the IPO-Curve itself... - * actname: name of Action-Channel (if applicable) that IPO-Curve's IPO-block belonged to - * constname: name of Constraint-Channel (if applicable) that IPO-Curve's IPO-block belonged to - * seq: sequencer-strip (if applicable) that IPO-Curve's IPO-block belonged to + * + * \param actname: name of Action-Channel (if applicable) that IPO-Curve's IPO-block belonged to. + * \param constname: name of Constraint-Channel (if applicable) + * that IPO-Curve's IPO-block belonged to \a seq. + * \param seq: sequencer-strip (if applicable) that IPO-Curve's IPO-block belonged to. */ static void icu_to_fcurves(ID *id, ListBase *groups, @@ -1239,20 +1311,26 @@ static void icu_to_fcurves(ID *id, fcu = MEM_callocN(sizeof(FCurve), "FCurve"); /* convert driver */ - if (icu->driver) + if (icu->driver) { fcu->driver = idriver_to_cdriver(icu->driver); + } /* copy flags */ - if (icu->flag & IPO_VISIBLE) + if (icu->flag & IPO_VISIBLE) { fcu->flag |= FCURVE_VISIBLE; - if (icu->flag & IPO_SELECT) + } + if (icu->flag & IPO_SELECT) { fcu->flag |= FCURVE_SELECTED; - if (icu->flag & IPO_ACTIVE) + } + if (icu->flag & IPO_ACTIVE) { fcu->flag |= FCURVE_ACTIVE; - if (icu->flag & IPO_MUTE) + } + if (icu->flag & IPO_MUTE) { fcu->flag |= FCURVE_MUTED; - if (icu->flag & IPO_PROTECT) + } + if (icu->flag & IPO_PROTECT) { fcu->flag |= FCURVE_PROTECTED; + } /* set extrapolation */ switch (icu->extrap) { @@ -1273,10 +1351,12 @@ static void icu_to_fcurves(ID *id, FMod_Cycles *data = (FMod_Cycles *)fcm->data; /* if 'offset' one is in use, set appropriate settings */ - if (icu->extrap == IPO_CYCLX) + if (icu->extrap == IPO_CYCLX) { data->before_mode = data->after_mode = FCM_EXTRAPOLATE_CYCLIC_OFFSET; - else + } + else { data->before_mode = data->after_mode = FCM_EXTRAPOLATE_CYCLIC; + } break; } } @@ -1289,8 +1369,9 @@ static void icu_to_fcurves(ID *id, FCurve *fcurve; int b; - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("\tconvert bitflag ipocurve, totbits = %d\n", totbits); + } /* add the 'only int values' flag */ fcu->flag |= (FCURVE_INT_VALUES | FCURVE_DISCRETE_VALUES); @@ -1305,18 +1386,22 @@ static void icu_to_fcurves(ID *id, unsigned int i = 0; /* make a copy of existing base-data if not the last curve */ - if (b < (totbits - 1)) + if (b < (totbits - 1)) { fcurve = copy_fcurve(fcu); - else + } + else { fcurve = fcu; + } /* set path */ fcurve->rna_path = BLI_strdup(abp->path); fcurve->array_index = abp->array_index; - /* convert keyframes - * - beztriples and bpoints are mutually exclusive, so we won't have both at the same time - * - beztriples are more likely to be encountered as they are keyframes (the other type wasn't used yet) + /* Convert keyframes: + * - Beztriples and bpoints are mutually exclusive, + * so we won't have both at the same time. + * - Beztriples are more likely to be encountered as they are keyframes + * (the other type wasn't used yet). */ fcurve->totvert = icu->totvert; @@ -1339,23 +1424,28 @@ static void icu_to_fcurves(ID *id, /* auto-handles - per curve to per handle */ if (icu->flag & IPO_AUTO_HORIZ) { - if (dst->h1 == HD_AUTO) + if (dst->h1 == HD_AUTO) { dst->h1 = HD_AUTO_ANIM; - if (dst->h2 == HD_AUTO) + } + if (dst->h2 == HD_AUTO) { dst->h2 = HD_AUTO_ANIM; + } } /* correct values, by checking if the flag of interest is set */ - if (((int)(dst->vec[1][1])) & (abp->bit)) + if (((int)(dst->vec[1][1])) & (abp->bit)) { dst->vec[0][1] = dst->vec[1][1] = dst->vec[2][1] = 1.0f; - else + } + else { dst->vec[0][1] = dst->vec[1][1] = dst->vec[2][1] = 0.0f; + } } } else if (icu->bp) { - /* TODO: need to convert from BPoint type to the more compact FPoint type... but not priority, since no data used this */ - //BPoint *bp; - //FPoint *fpt; + /* TODO: need to convert from BPoint type to the more compact FPoint type... + * but not priority, since no data used this. */ + // BPoint *bp; + // FPoint *fpt; } /* add new F-Curve to list */ @@ -1370,12 +1460,14 @@ static void icu_to_fcurves(ID *id, */ fcu->rna_path = get_rna_access( id, icu->blocktype, icu->adrcode, actname, constname, seq, &fcu->array_index); - if (fcu->rna_path == NULL) + if (fcu->rna_path == NULL) { fcu->flag |= FCURVE_DISABLED; + } - /* convert keyframes - * - beztriples and bpoints are mutually exclusive, so we won't have both at the same time - * - beztriples are more likely to be encountered as they are keyframes (the other type wasn't used yet) + /* Convert keyframes: + * - Beztriples and bpoints are mutually exclusive, so we won't have both at the same time. + * - Beztriples are more likely to be encountered as they are keyframes + * (the other type wasn't used yet). */ fcu->totvert = icu->totvert; @@ -1391,18 +1483,21 @@ static void icu_to_fcurves(ID *id, *dst = *src; /* now copy interpolation from curve (if not already set) */ - if (icu->ipo != IPO_MIXED) + if (icu->ipo != IPO_MIXED) { dst->ipo = icu->ipo; + } /* 'hide' flag is now used for keytype - only 'keyframes' existed before */ dst->hide = BEZT_KEYTYPE_KEYFRAME; /* auto-handles - per curve to per handle */ if (icu->flag & IPO_AUTO_HORIZ) { - if (dst->h1 == HD_AUTO) + if (dst->h1 == HD_AUTO) { dst->h1 = HD_AUTO_ANIM; - if (dst->h2 == HD_AUTO) + } + if (dst->h2 == HD_AUTO) { dst->h2 = HD_AUTO_ANIM; + } } /* correct values for euler rotation curves @@ -1411,7 +1506,7 @@ static void icu_to_fcurves(ID *id, */ if (((icu->blocktype == ID_OB) && ELEM(icu->adrcode, OB_ROT_X, OB_ROT_Y, OB_ROT_Z)) || ((icu->blocktype == ID_PO) && ELEM(icu->adrcode, AC_EUL_X, AC_EUL_Y, AC_EUL_Z))) { - const float fac = (float)M_PI / 18.0f; //10.0f * M_PI/180.0f; + const float fac = (float)M_PI / 18.0f; // 10.0f * M_PI/180.0f; dst->vec[0][1] *= fac; dst->vec[1][1] *= fac; @@ -1469,9 +1564,10 @@ static void icu_to_fcurves(ID *id, } } else if (icu->bp) { - /* TODO: need to convert from BPoint type to the more compact FPoint type... but not priority, since no data used this */ - //BPoint *bp; - //FPoint *fpt; + /* TODO: need to convert from BPoint type to the more compact FPoint type... + * but not priority, since no data used this */ + // BPoint *bp; + // FPoint *fpt; } /* add new F-Curve to list */ @@ -1497,11 +1593,13 @@ static void ipo_to_animato(ID *id, IpoCurve *icu; /* sanity check */ - if (ELEM(NULL, ipo, anim, drivers)) + if (ELEM(NULL, ipo, anim, drivers)) { return; + } - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("ipo_to_animato\n"); + } /* validate actname and constname * - clear actname if it was one of the generic <builtin> ones (i.e. 'Object', or 'Shapes') @@ -1510,19 +1608,22 @@ static void ipo_to_animato(ID *id, * F-Curves for bones). This may be added later... for now let's just dump without them... */ if (actname) { - if ((ipo->blocktype == ID_OB) && STREQ(actname, "Object")) + if ((ipo->blocktype == ID_OB) && STREQ(actname, "Object")) { actname = NULL; - else if ((ipo->blocktype == ID_OB) && STREQ(actname, "Shape")) + } + else if ((ipo->blocktype == ID_OB) && STREQ(actname, "Shape")) { actname = NULL; + } } /* loop over IPO-Curves, freeing as we progress */ for (icu = ipo->curve.first; icu; icu = icu->next) { /* Since an IPO-Curve may end up being made into many F-Curves (i.e. bitflag curves), - * we figure out the best place to put the channel, then tell the curve-converter to just dump there - */ + * we figure out the best place to put the channel, + * then tell the curve-converter to just dump there. */ if (icu->driver) { - /* Blender 2.4x allowed empty drivers, but we don't now, since they cause more trouble than they're worth */ + /* Blender 2.4x allowed empty drivers, + * but we don't now, since they cause more trouble than they're worth. */ if ((icu->driver->ob) || (icu->driver->type == IPO_DRIVER_TYPE_PYTHON)) { icu_to_fcurves(id, NULL, drivers, icu, actname, constname, seq, ipo->muteipo); } @@ -1531,8 +1632,9 @@ static void ipo_to_animato(ID *id, icu->driver = NULL; } } - else + else { icu_to_fcurves(id, animgroups, anim, icu, actname, constname, seq, ipo->muteipo); + } } /* if this IPO block doesn't have any users after this one, free... */ @@ -1544,14 +1646,17 @@ static void ipo_to_animato(ID *id, icn = icu->next; /* free driver */ - if (icu->driver) + if (icu->driver) { MEM_freeN(icu->driver); + } /* free old data of curve now that it's no longer needed for converting any more curves */ - if (icu->bezt) + if (icu->bezt) { MEM_freeN(icu->bezt); - if (icu->bp) + } + if (icu->bp) { MEM_freeN(icu->bezt); + } /* free this IPO-Curve */ BLI_freelinkN(&ipo->curve, icu); @@ -1571,13 +1676,15 @@ static void action_to_animato( bConstraintChannel *conchan, *conchann; /* only continue if there are Action Channels (indicating unconverted data) */ - if (BLI_listbase_is_empty(&act->chanbase)) + if (BLI_listbase_is_empty(&act->chanbase)) { return; + } /* get rid of all Action Groups */ // XXX this is risky if there's some old + some new data in the Action... - if (act->groups.first) + if (act->groups.first) { BLI_freelistN(&act->groups); + } /* loop through Action-Channels, converting data, freeing as we go */ for (achan = act->chanbase.first; achan; achan = achann) { @@ -1627,8 +1734,9 @@ static void ipo_to_animdata( ListBase drivers = {NULL, NULL}; /* sanity check */ - if (ELEM(NULL, id, ipo)) + if (ELEM(NULL, id, ipo)) { return; + } if (adt == NULL) { CLOG_ERROR(&LOG, "adt invalid"); return; @@ -1644,16 +1752,17 @@ static void ipo_to_animdata( BLI_listbase_count(&ipo->curve)); } - /* Convert curves to animato system (separated into separate lists of F-Curves for animation and drivers), - * and the try to put these lists in the right places, but do not free the lists here - */ + /* Convert curves to animato system + * (separated into separate lists of F-Curves for animation and drivers), + * and the try to put these lists in the right places, but do not free the lists here. */ // XXX there shouldn't be any need for the groups, so don't supply pointer for that now... ipo_to_animato(id, ipo, actname, constname, seq, NULL, &anim, &drivers); /* deal with animation first */ if (anim.first) { - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("\thas anim\n"); + } /* try to get action */ if (adt->action == NULL) { char nameBuf[MAX_ID_NAME]; @@ -1661,8 +1770,9 @@ static void ipo_to_animdata( BLI_snprintf(nameBuf, sizeof(nameBuf), "CDA:%s", ipo->id.name + 2); adt->action = BKE_action_add(bmain, nameBuf); - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("\t\tadded new action - '%s'\n", nameBuf); + } } /* add F-Curves to action */ @@ -1671,8 +1781,9 @@ static void ipo_to_animdata( /* deal with drivers */ if (drivers.first) { - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("\thas drivers\n"); + } /* add drivers to end of driver stack */ BLI_movelisttolist(&adt->drivers, &drivers); } @@ -1686,14 +1797,16 @@ static void action_to_animdata(ID *id, bAction *act) AnimData *adt = BKE_animdata_from_id(id); /* only continue if there are Action Channels (indicating unconverted data) */ - if (ELEM(NULL, adt, act->chanbase.first)) + if (ELEM(NULL, adt, act->chanbase.first)) { return; + } /* check if we need to set this Action as the AnimData's action */ if (adt->action == NULL) { /* set this Action as AnimData's Action */ - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("act_to_adt - set adt action to act\n"); + } adt->action = act; } @@ -1724,7 +1837,8 @@ static void nlastrips_to_animdata(ID *id, ListBase *strips) /* convert Action data (if not yet converted), storing the results in the same Action */ action_to_animato(id, as->act, &as->act->groups, &as->act->curves, &adt->drivers); - /* create a new-style NLA-strip which references this Action, then copy over relevant settings */ + /* Create a new-style NLA-strip which references this Action, + * then copy over relevant settings. */ { /* init a new strip, and assign the action to it * - no need to muck around with the user-counts, since this is just @@ -1742,31 +1856,38 @@ static void nlastrips_to_animdata(ID *id, ListBase *strips) /* action reuse */ strip->repeat = as->repeat; strip->scale = as->scale; - if (as->flag & ACTSTRIP_LOCK_ACTION) + if (as->flag & ACTSTRIP_LOCK_ACTION) { strip->flag |= NLASTRIP_FLAG_SYNC_LENGTH; + } /* blending */ strip->blendin = as->blendin; strip->blendout = as->blendout; strip->blendmode = (as->mode == ACTSTRIPMODE_ADD) ? NLASTRIP_MODE_ADD : NLASTRIP_MODE_REPLACE; - if (as->flag & ACTSTRIP_AUTO_BLENDS) + if (as->flag & ACTSTRIP_AUTO_BLENDS) { strip->flag |= NLASTRIP_FLAG_AUTO_BLENDS; + } /* assorted setting flags */ - if (as->flag & ACTSTRIP_SELECT) + if (as->flag & ACTSTRIP_SELECT) { strip->flag |= NLASTRIP_FLAG_SELECT; - if (as->flag & ACTSTRIP_ACTIVE) + } + if (as->flag & ACTSTRIP_ACTIVE) { strip->flag |= NLASTRIP_FLAG_ACTIVE; + } - if (as->flag & ACTSTRIP_MUTE) + if (as->flag & ACTSTRIP_MUTE) { strip->flag |= NLASTRIP_FLAG_MUTED; - if (as->flag & ACTSTRIP_REVERSE) + } + if (as->flag & ACTSTRIP_REVERSE) { strip->flag |= NLASTRIP_FLAG_REVERSE; + } /* by default, we now always extrapolate, while in the past this was optional */ - if ((as->flag & ACTSTRIP_HOLDLASTFRAME) == 0) + if ((as->flag & ACTSTRIP_HOLDLASTFRAME) == 0) { strip->extendmode = NLASTRIP_EXTEND_NOTHING; + } } /* try to add this strip to the current NLA-Track (i.e. the 'last' one on the stack atm) */ @@ -1784,8 +1905,9 @@ static void nlastrips_to_animdata(ID *id, ListBase *strips) /* modifiers */ // FIXME: for now, we just free them... - if (as->modifiers.first) + if (as->modifiers.first) { BLI_freelistN(&as->modifiers); + } /* free the old strip */ BLI_freelinkN(strips, as); @@ -1821,8 +1943,9 @@ void do_versions_ipos_to_animato(Main *bmain) CLOG_WARN(&LOG, "Animation data too new to convert (Version %d)", bmain->versionfile); return; } - else if (G.debug & G_DEBUG) + else if (G.debug & G_DEBUG) { printf("INFO: Converting to Animato...\n"); + } /* ----------- Animation Attached to Data -------------- */ @@ -1833,8 +1956,9 @@ void do_versions_ipos_to_animato(Main *bmain) bConstraint *con; bConstraintChannel *conchan, *conchann; - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("\tconverting ob %s\n", id->name + 2); + } /* check if object has any animation data */ if (ob->nlastrips.first) { @@ -1949,8 +2073,9 @@ void do_versions_ipos_to_animato(Main *bmain) /* object's action will always be object-rooted */ { AnimData *adt = BKE_animdata_from_id(id); - if (adt && adt->action) + if (adt && adt->action) { adt->action->idroot = ID_OB; + } } } @@ -1958,8 +2083,9 @@ void do_versions_ipos_to_animato(Main *bmain) for (id = bmain->shapekeys.first; id; id = id->next) { Key *key = (Key *)id; - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("\tconverting key %s\n", id->name + 2); + } /* we're only interested in the IPO * NOTE: for later, it might be good to port these over to Object instead, as many of these @@ -1972,8 +2098,9 @@ void do_versions_ipos_to_animato(Main *bmain) /* Convert Shapekey data... */ ipo_to_animdata(bmain, id, key->ipo, NULL, NULL, NULL); - if (adt->action) + if (adt->action) { adt->action->idroot = key->ipo->blocktype; + } id_us_min(&key->ipo->id); key->ipo = NULL; @@ -1984,8 +2111,9 @@ void do_versions_ipos_to_animato(Main *bmain) for (id = bmain->materials.first; id; id = id->next) { Material *ma = (Material *)id; - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("\tconverting material %s\n", id->name + 2); + } /* we're only interested in the IPO */ if (ma->ipo) { @@ -1995,8 +2123,9 @@ void do_versions_ipos_to_animato(Main *bmain) /* Convert Material data... */ ipo_to_animdata(bmain, id, ma->ipo, NULL, NULL, NULL); - if (adt->action) + if (adt->action) { adt->action->idroot = ma->ipo->blocktype; + } id_us_min(&ma->ipo->id); ma->ipo = NULL; @@ -2007,8 +2136,9 @@ void do_versions_ipos_to_animato(Main *bmain) for (id = bmain->worlds.first; id; id = id->next) { World *wo = (World *)id; - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("\tconverting world %s\n", id->name + 2); + } /* we're only interested in the IPO */ if (wo->ipo) { @@ -2018,8 +2148,9 @@ void do_versions_ipos_to_animato(Main *bmain) /* Convert World data... */ ipo_to_animdata(bmain, id, wo->ipo, NULL, NULL, NULL); - if (adt->action) + if (adt->action) { adt->action->idroot = wo->ipo->blocktype; + } id_us_min(&wo->ipo->id); wo->ipo = NULL; @@ -2039,8 +2170,9 @@ void do_versions_ipos_to_animato(Main *bmain) IpoCurve *icu = (seq->ipo) ? seq->ipo->curve.first : NULL; short adrcode = SEQ_FAC1; - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("\tconverting sequence strip %s\n", seq->name + 2); + } if (ELEM(NULL, seq->ipo, icu)) { seq->flag |= SEQ_USE_EFFECT_DEFAULT_FADE; @@ -2068,8 +2200,9 @@ void do_versions_ipos_to_animato(Main *bmain) /* convert IPO */ ipo_to_animdata(bmain, (ID *)scene, seq->ipo, NULL, NULL, seq); - if (adt->action) + if (adt->action) { adt->action->idroot = ID_SCE; /* scene-rooted */ + } id_us_min(&seq->ipo->id); seq->ipo = NULL; @@ -2082,8 +2215,9 @@ void do_versions_ipos_to_animato(Main *bmain) for (id = bmain->textures.first; id; id = id->next) { Tex *te = (Tex *)id; - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("\tconverting texture %s\n", id->name + 2); + } /* we're only interested in the IPO */ if (te->ipo) { @@ -2093,8 +2227,9 @@ void do_versions_ipos_to_animato(Main *bmain) /* Convert Texture data... */ ipo_to_animdata(bmain, id, te->ipo, NULL, NULL, NULL); - if (adt->action) + if (adt->action) { adt->action->idroot = te->ipo->blocktype; + } id_us_min(&te->ipo->id); te->ipo = NULL; @@ -2105,8 +2240,9 @@ void do_versions_ipos_to_animato(Main *bmain) for (id = bmain->cameras.first; id; id = id->next) { Camera *ca = (Camera *)id; - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("\tconverting camera %s\n", id->name + 2); + } /* we're only interested in the IPO */ if (ca->ipo) { @@ -2116,8 +2252,9 @@ void do_versions_ipos_to_animato(Main *bmain) /* Convert Camera data... */ ipo_to_animdata(bmain, id, ca->ipo, NULL, NULL, NULL); - if (adt->action) + if (adt->action) { adt->action->idroot = ca->ipo->blocktype; + } id_us_min(&ca->ipo->id); ca->ipo = NULL; @@ -2128,8 +2265,9 @@ void do_versions_ipos_to_animato(Main *bmain) for (id = bmain->lights.first; id; id = id->next) { Light *la = (Light *)id; - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("\tconverting light %s\n", id->name + 2); + } /* we're only interested in the IPO */ if (la->ipo) { @@ -2139,8 +2277,9 @@ void do_versions_ipos_to_animato(Main *bmain) /* Convert Light data... */ ipo_to_animdata(bmain, id, la->ipo, NULL, NULL, NULL); - if (adt->action) + if (adt->action) { adt->action->idroot = la->ipo->blocktype; + } id_us_min(&la->ipo->id); la->ipo = NULL; @@ -2151,8 +2290,9 @@ void do_versions_ipos_to_animato(Main *bmain) for (id = bmain->curves.first; id; id = id->next) { Curve *cu = (Curve *)id; - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("\tconverting curve %s\n", id->name + 2); + } /* we're only interested in the IPO */ if (cu->ipo) { @@ -2162,8 +2302,9 @@ void do_versions_ipos_to_animato(Main *bmain) /* Convert Curve data... */ ipo_to_animdata(bmain, id, cu->ipo, NULL, NULL, NULL); - if (adt->action) + if (adt->action) { adt->action->idroot = cu->ipo->blocktype; + } id_us_min(&cu->ipo->id); cu->ipo = NULL; @@ -2173,24 +2314,26 @@ void do_versions_ipos_to_animato(Main *bmain) /* --------- Unconverted Animation Data ------------------ */ /* For Animation data which may not be directly connected (i.e. not linked) to any other * data, we need to perform a separate pass to make sure that they are converted to standalone - * Actions which may then be able to be reused. This does mean that we will be going over data that's - * already been converted, but there are no problems with that. + * Actions which may then be able to be reused. This does mean that we will be going over data + * that's already been converted, but there are no problems with that. * * The most common case for this will be Action Constraints, or IPO's with Fake-Users. - * We collect all drivers that were found into a temporary collection, and free them in one go, as they're - * impossible to resolve. + * We collect all drivers that were found into a temporary collection, and free them in one go, + * as they're impossible to resolve. */ /* actions */ for (id = bmain->actions.first; id; id = id->next) { bAction *act = (bAction *)id; - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("\tconverting action %s\n", id->name + 2); + } /* if old action, it will be object-only... */ - if (act->chanbase.first) + if (act->chanbase.first) { act->idroot = ID_OB; + } /* be careful! some of the actions we encounter will be converted ones... */ action_to_animato(NULL, act, &act->groups, &act->curves, &drivers); @@ -2200,8 +2343,9 @@ void do_versions_ipos_to_animato(Main *bmain) for (id = bmain->ipo.first; id; id = id->next) { Ipo *ipo = (Ipo *)id; - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("\tconverting ipo %s\n", id->name + 2); + } /* most likely this IPO has already been processed, so check if any curves left to convert */ if (ipo->curve.first) { @@ -2221,6 +2365,7 @@ void do_versions_ipos_to_animato(Main *bmain) /* free unused drivers from actions + ipos */ free_fcurves(&drivers); - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("INFO: Animato convert done\n"); + } } diff --git a/source/blender/blenkernel/intern/key.c b/source/blender/blenkernel/intern/key.c index 1d1c04e173c..61de6a8c06a 100644 --- a/source/blender/blenkernel/intern/key.c +++ b/source/blender/blenkernel/intern/key.c @@ -79,8 +79,9 @@ void BKE_key_free(Key *key) BKE_animdata_free((ID *)key, false); while ((kb = BLI_pophead(&key->block))) { - if (kb->data) + if (kb->data) { MEM_freeN(kb->data); + } MEM_freeN(kb); } } @@ -90,8 +91,9 @@ void BKE_key_free_nolib(Key *key) KeyBlock *kb; while ((kb = BLI_pophead(&key->block))) { - if (kb->data) + if (kb->data) { MEM_freeN(kb->data); + } MEM_freeN(kb); } } @@ -149,8 +151,10 @@ Key *BKE_key_add(Main *bmain, ID *id) /* common function */ } /** - * Only copy internal data of ShapeKey ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of ShapeKey ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * @@ -198,10 +202,12 @@ Key *BKE_key_copy_nolib(Key *key) kbn = keyn->block.first; while (kbn) { - if (kbn->data) + if (kbn->data) { kbn->data = MEM_dupallocN(kbn->data); - if (kb == key->refkey) + } + if (kb == key->refkey) { keyn->refkey = kbn; + } kbn = kbn->next; kb = kb->next; @@ -221,9 +227,11 @@ void BKE_key_sort(Key *key) KeyBlock *kb2; /* locate the key which is out of position */ - for (kb = key->block.first; kb; kb = kb->next) - if ((kb->next) && (kb->pos > kb->next->pos)) + for (kb = key->block.first; kb; kb = kb->next) { + if ((kb->next) && (kb->pos > kb->next->pos)) { break; + } + } /* if we find a key, move it */ if (kb) { @@ -372,27 +380,32 @@ static int setkeys(float fac, ListBase *lb, KeyBlock *k[], float t[4], int cycl) lastpos = k1->pos; dpos = lastpos - firstkey->pos; - if (fac < firstkey->pos) + if (fac < firstkey->pos) { fac = firstkey->pos; - else if (fac > k1->pos) + } + else if (fac > k1->pos) { fac = k1->pos; + } k1 = k[0] = k[1] = k[2] = k[3] = firstkey; t[0] = t[1] = t[2] = t[3] = k1->pos; /* if (fac < 0.0 || fac > 1.0) return 1; */ - if (k1->next == NULL) + if (k1->next == NULL) { return 1; + } if (cycl) { /* pre-sort */ k[2] = k1->next; k[3] = k[2]->next; - if (k[3] == NULL) + if (k[3] == NULL) { k[3] = k1; + } while (k1) { - if (k1->next == NULL) + if (k1->next == NULL) { k[0] = k1; + } k1 = k1->next; } /* k1 = k[1]; */ /* UNUSED */ @@ -406,16 +419,18 @@ static int setkeys(float fac, ListBase *lb, KeyBlock *k[], float t[4], int cycl) t[3] += dpos; ofs = 2.0f * dpos; } - if (fac < t[1]) + if (fac < t[1]) { fac += dpos; + } k1 = k[3]; } else { /* pre-sort */ k[2] = k1->next; t[2] = k[2]->pos; k[3] = k[2]->next; - if (k[3] == NULL) + if (k[3] == NULL) { k[3] = k[2]; + } t[3] = k[3]->pos; k1 = k[3]; } @@ -443,13 +458,15 @@ static int setkeys(float fac, ListBase *lb, KeyBlock *k[], float t[4], int cycl) t[3] = k1->pos + ofs; k[3] = k1; - if (ofs > 2.1f + lastpos) + if (ofs > 2.1f + lastpos) { break; + } } bsplinetype = 0; - if (k[1]->type == KEY_BSPLINE || k[2]->type == KEY_BSPLINE) + if (k[1]->type == KEY_BSPLINE || k[2]->type == KEY_BSPLINE) { bsplinetype = 1; + } if (cycl == 0) { if (bsplinetype == 0) { /* B spline doesn't go through the control points */ @@ -597,11 +614,13 @@ static void cp_key(const int start, /* currently always 0, in future key_pointer_size may assign */ ofs[1] = 0; - if (!key_pointer_size(key, mode, &poinsize, &ofs[0], &step)) + if (!key_pointer_size(key, mode, &poinsize, &ofs[0], &step)) { return; + } - if (end > tot) + if (end > tot) { end = tot; + } if (tot != kb->totelem) { ktot = 0.0; @@ -646,8 +665,9 @@ static void cp_key(const int start, for (a = start; a < end; a += step) { cp = key->elemstr; - if (mode == KEY_MODE_BEZTRIPLE) + if (mode == KEY_MODE_BEZTRIPLE) { cp = elemstr; + } ofsp = ofs; @@ -657,9 +677,10 @@ static void cp_key(const int start, case IPO_FLOAT: if (weights) { memcpy(poin, kref, sizeof(float[KEYELEM_FLOAT_LEN_COORD])); - if (*weights != 0.0f) + if (*weights != 0.0f) { rel_flerp( KEYELEM_FLOAT_LEN_COORD, (float *)poin, (float *)kref, (float *)k1, *weights); + } weights++; } else { @@ -674,10 +695,12 @@ static void cp_key(const int start, break; default: /* should never happen */ - if (freek1) + if (freek1) { MEM_freeN(freek1); - if (freekref) + } + if (freekref) { MEM_freeN(freekref); + } BLI_assert(!"invalid 'cp[1]'"); return; } @@ -702,10 +725,12 @@ static void cp_key(const int start, } } - if (freek1) + if (freek1) { MEM_freeN(freek1); - if (freekref) + } + if (freekref) { MEM_freeN(freekref); + } } static void cp_cu_key(Curve *cu, @@ -727,8 +752,9 @@ static void cp_cu_key(Curve *cu, a1 = max_ii(a, start); a2 = min_ii(a + step, end); - if (a1 < a2) + if (a1 < a2) { cp_key(a1, a2, tot, out, key, actkb, kb, NULL, KEY_MODE_BPOINT); + } } else if (nu->bezt) { step = KEYELEM_ELEM_LEN_BEZTRIPLE * nu->pntsu; @@ -737,8 +763,9 @@ static void cp_cu_key(Curve *cu, a1 = max_ii(a, start); a2 = min_ii(a + step, end); - if (a1 < a2) + if (a1 < a2) { cp_key(a1, a2, tot, out, key, actkb, kb, NULL, KEY_MODE_BEZTRIPLE); + } } else { step = 0; @@ -763,11 +790,13 @@ static void key_evaluate_relative(const int start, /* currently always 0, in future key_pointer_size may assign */ ofs[1] = 0; - if (!key_pointer_size(key, mode, &poinsize, &ofs[0], &step)) + if (!key_pointer_size(key, mode, &poinsize, &ofs[0], &step)) { return; + } - if (end > tot) + if (end > tot) { end = tot; + } /* in case of beztriple */ elemstr[0] = 1; /* nr of ipofloats */ @@ -795,8 +824,9 @@ static void key_evaluate_relative(const int start, /* reference now can be any block */ refb = BLI_findlink(&key->block, kb->relative); - if (refb == NULL) + if (refb == NULL) { continue; + } poin = basispoin; from = key_block_get_data(key, actkb, kb, &freefrom); @@ -811,8 +841,9 @@ static void key_evaluate_relative(const int start, weight = weights ? (*weights * icuval) : icuval; cp = key->elemstr; - if (mode == KEY_MODE_BEZTRIPLE) + if (mode == KEY_MODE_BEZTRIPLE) { cp = elemstr; + } ofsp = ofs; @@ -842,10 +873,12 @@ static void key_evaluate_relative(const int start, break; default: /* should never happen */ - if (freefrom) + if (freefrom) { MEM_freeN(freefrom); - if (freereffrom) + } + if (freereffrom) { MEM_freeN(freereffrom); + } BLI_assert(!"invalid 'cp[1]'"); return; } @@ -859,14 +892,17 @@ static void key_evaluate_relative(const int start, reffrom += elemsize; from += elemsize; - if (weights) + if (weights) { weights++; + } } - if (freefrom) + if (freefrom) { MEM_freeN(freefrom); - if (freereffrom) + } + if (freereffrom) { MEM_freeN(freereffrom); + } } } } @@ -892,11 +928,13 @@ static void do_key(const int start, /* currently always 0, in future key_pointer_size may assign */ ofs[1] = 0; - if (!key_pointer_size(key, mode, &poinsize, &ofs[0], &step)) + if (!key_pointer_size(key, mode, &poinsize, &ofs[0], &step)) { return; + } - if (end > tot) + if (end > tot) { end = tot; + } k1 = key_block_get_data(key, actkb, k[0], &freek1); k2 = key_block_get_data(key, actkb, k[1], &freek2); @@ -1014,8 +1052,9 @@ static void do_key(const int start, for (a = start; a < end; a += step) { cp = key->elemstr; - if (mode == KEY_MODE_BEZTRIPLE) + if (mode == KEY_MODE_BEZTRIPLE) { cp = elemstr; + } ofsp = ofs; @@ -1051,14 +1090,18 @@ static void do_key(const int start, break; default: /* should never happen */ - if (freek1) + if (freek1) { MEM_freeN(freek1); - if (freek2) + } + if (freek2) { MEM_freeN(freek2); - if (freek3) + } + if (freek3) { MEM_freeN(freek3); - if (freek4) + } + if (freek4) { MEM_freeN(freek4); + } BLI_assert(!"invalid 'cp[1]'"); return; } @@ -1118,14 +1161,18 @@ static void do_key(const int start, } } - if (freek1) + if (freek1) { MEM_freeN(freek1); - if (freek2) + } + if (freek2) { MEM_freeN(freek2); - if (freek3) + } + if (freek3) { MEM_freeN(freek3); - if (freek4) + } + if (freek4) { MEM_freeN(freek4); + } } static float *get_weights_array(Object *ob, char *vgroup, WeightsArrayCache *cache) @@ -1137,8 +1184,9 @@ static float *get_weights_array(Object *ob, char *vgroup, WeightsArrayCache *cac int totvert = 0, defgrp_index = 0; /* no vgroup string set? */ - if (vgroup[0] == 0) + if (vgroup[0] == 0) { return NULL; + } /* gather dvert and totvert */ if (ob->type == OB_MESH) { @@ -1146,8 +1194,9 @@ static float *get_weights_array(Object *ob, char *vgroup, WeightsArrayCache *cac dvert = me->dvert; totvert = me->totvert; - if (me->edit_mesh && me->edit_mesh->bm->totvert == totvert) + if (me->edit_mesh && me->edit_mesh->bm->totvert == totvert) { em = me->edit_mesh; + } } else if (ob->type == OB_LATTICE) { Lattice *lt = ob->data; @@ -1155,8 +1204,9 @@ static float *get_weights_array(Object *ob, char *vgroup, WeightsArrayCache *cac totvert = lt->pntsu * lt->pntsv * lt->pntsw; } - if (dvert == NULL) + if (dvert == NULL) { return NULL; + } /* find the group (weak loop-in-loop) */ defgrp_index = defgroup_name_index(ob, vgroup); @@ -1366,8 +1416,9 @@ static void do_latt_key(Object *ob, Key *key, char *out, const int tot) } } - if (lt->flag & LT_OUTSIDE) + if (lt->flag & LT_OUTSIDE) { outside_lattice(lt); + } } /* returns key coordinates (+ tilt) when key applied, NULL otherwise */ @@ -1378,8 +1429,9 @@ float *BKE_key_evaluate_object_ex(Object *ob, int *r_totelem, float *arr, size_t char *out; int tot = 0, size = 0; - if (key == NULL || BLI_listbase_is_empty(&key->block)) + if (key == NULL || BLI_listbase_is_empty(&key->block)) { return NULL; + } /* compute size of output array */ if (ob->type == OB_MESH) { @@ -1402,8 +1454,9 @@ float *BKE_key_evaluate_object_ex(Object *ob, int *r_totelem, float *arr, size_t } /* if nothing to interpolate, cancel */ - if (tot == 0 || size == 0) + if (tot == 0 || size == 0) { return NULL; + } /* allocate array */ if (arr == NULL) { @@ -1421,8 +1474,9 @@ float *BKE_key_evaluate_object_ex(Object *ob, int *r_totelem, float *arr, size_t /* shape locked, copy the locked shape instead of blending */ KeyBlock *kb = BLI_findlink(&key->block, ob->shapenr - 1); - if (kb && (kb->flag & KEYBLOCK_MUTE)) + if (kb && (kb->flag & KEYBLOCK_MUTE)) { kb = key->refkey; + } if (kb == NULL) { kb = key->block.first; @@ -1434,22 +1488,28 @@ float *BKE_key_evaluate_object_ex(Object *ob, int *r_totelem, float *arr, size_t cp_key(0, tot, tot, out, key, actkb, kb, weights, 0); - if (weights) + if (weights) { MEM_freeN(weights); + } } - else if (ELEM(ob->type, OB_CURVE, OB_SURF)) + else if (ELEM(ob->type, OB_CURVE, OB_SURF)) { cp_cu_key(ob->data, key, actkb, kb, 0, tot, out, tot); + } } else { - if (ob->type == OB_MESH) + if (ob->type == OB_MESH) { do_mesh_key(ob, key, out, tot); - else if (ob->type == OB_LATTICE) + } + else if (ob->type == OB_LATTICE) { do_latt_key(ob, key, out, tot); - else if (ob->type == OB_CURVE) + } + else if (ob->type == OB_CURVE) { do_curve_key(ob, key, out, tot); - else if (ob->type == OB_SURF) + } + else if (ob->type == OB_SURF) { do_curve_key(ob, key, out, tot); + } } if (r_totelem) { @@ -1513,8 +1573,9 @@ Key *BKE_key_from_id(ID *id) Key **BKE_key_from_object_p(const Object *ob) { - if (ob == NULL || ob->data == NULL) + if (ob == NULL || ob->data == NULL) { return NULL; + } return BKE_key_from_id_p(ob->data); } @@ -1537,8 +1598,9 @@ KeyBlock *BKE_keyblock_add(Key *key, const char *name) int tot; kb = key->block.last; - if (kb) + if (kb) { curpos = kb->pos; + } kb = MEM_callocN(sizeof(KeyBlock), "Keyblock"); BLI_addtail(&key->block, kb); @@ -1549,10 +1611,12 @@ KeyBlock *BKE_keyblock_add(Key *key, const char *name) BLI_strncpy(kb->name, name, sizeof(kb->name)); } else { - if (tot == 1) + if (tot == 1) { BLI_strncpy(kb->name, DATA_("Basis"), sizeof(kb->name)); - else + } + else { BLI_snprintf(kb->name, sizeof(kb->name), DATA_("Key %d"), tot - 1); + } } BLI_uniquename(&key->block, kb, DATA_("Key"), '.', offsetof(KeyBlock, name), sizeof(kb->name)); @@ -1560,8 +1624,9 @@ KeyBlock *BKE_keyblock_add(Key *key, const char *name) kb->uid = key->uidgen++; key->totkey++; - if (key->totkey == 1) + if (key->totkey == 1) { key->refkey = kb; + } kb->slidermin = 0.0f; kb->slidermax = 1.0f; @@ -1627,8 +1692,9 @@ KeyBlock *BKE_keyblock_from_object_reference(Object *ob) { Key *key = BKE_key_from_object(ob); - if (key) + if (key) { return key->refkey; + } return NULL; } @@ -1645,8 +1711,9 @@ KeyBlock *BKE_keyblock_from_key(Key *key, int index) for (i = 1; i < key->totkey; i++) { kb = kb->next; - if (index == i) + if (index == i) { return kb; + } } } @@ -1682,8 +1749,9 @@ char *BKE_keyblock_curval_rnapath_get(Key *key, KeyBlock *kb) PropertyRNA *prop; /* sanity checks */ - if (ELEM(NULL, key, kb)) + if (ELEM(NULL, key, kb)) { return NULL; + } /* create the RNA pointer */ RNA_pointer_create(&key->id, &RNA_ShapeKey, kb, &ptr); @@ -1706,8 +1774,9 @@ void BKE_keyblock_update_from_lattice(Lattice *lt, KeyBlock *kb) BLI_assert(kb->totelem == lt->pntsu * lt->pntsv * lt->pntsw); tot = kb->totelem; - if (tot == 0) + if (tot == 0) { return; + } bp = lt->def; fp = kb->data; @@ -1721,8 +1790,9 @@ void BKE_keyblock_convert_from_lattice(Lattice *lt, KeyBlock *kb) int tot; tot = lt->pntsu * lt->pntsv * lt->pntsw; - if (tot == 0) + if (tot == 0) { return; + } MEM_SAFE_FREE(kb->data); @@ -1758,10 +1828,12 @@ int BKE_keyblock_curve_element_count(ListBase *nurb) nu = nurb->first; while (nu) { - if (nu->bezt) + if (nu->bezt) { tot += KEYELEM_ELEM_LEN_BEZTRIPLE * nu->pntsu; - else if (nu->bp) + } + else if (nu->bp) { tot += KEYELEM_ELEM_LEN_BPOINT * nu->pntsu * nu->pntsv; + } nu = nu->next; } @@ -1780,8 +1852,9 @@ void BKE_keyblock_update_from_curve(Curve *UNUSED(cu), KeyBlock *kb, ListBase *n BLI_assert(BKE_keyblock_curve_element_count(nurb) == kb->totelem); tot = kb->totelem; - if (tot == 0) + if (tot == 0) { return; + } fp = kb->data; for (nu = nurb->first; nu; nu = nu->next) { @@ -1812,8 +1885,9 @@ void BKE_keyblock_convert_from_curve(Curve *cu, KeyBlock *kb, ListBase *nurb) /* count */ tot = BKE_keyblock_curve_element_count(nurb); - if (tot == 0) + if (tot == 0) { return; + } MEM_SAFE_FREE(kb->data); @@ -1869,8 +1943,9 @@ void BKE_keyblock_update_from_mesh(Mesh *me, KeyBlock *kb) BLI_assert(me->totvert == kb->totelem); tot = me->totvert; - if (tot == 0) + if (tot == 0) { return; + } mvert = me->mvert; fp = kb->data; @@ -1883,8 +1958,9 @@ void BKE_keyblock_convert_from_mesh(Mesh *me, Key *key, KeyBlock *kb) { const int len = me->totvert; - if (me->totvert == 0) + if (me->totvert == 0) { return; + } MEM_SAFE_FREE(kb->data); @@ -2015,8 +2091,9 @@ void BKE_keyblock_update_from_vertcos(Object *ob, KeyBlock *kb, float (*vertCos) #endif tot = kb->totelem; - if (tot == 0) + if (tot == 0) { return; + } /* Copy coords to keyblock */ if (ELEM(ob->type, OB_MESH, OB_LATTICE)) { @@ -2072,8 +2149,9 @@ void BKE_keyblock_convert_from_vertcos(Object *ob, KeyBlock *kb, float (*vertCos tot = BKE_keyblock_curve_element_count(&cu->nurb); } - if (tot == 0) + if (tot == 0) { return; + } kb->data = MEM_mallocN(tot * elemsize, __func__); @@ -2101,8 +2179,9 @@ float (*BKE_keyblock_convert_to_vertcos(Object *ob, KeyBlock *kb))[3] tot = BKE_nurbList_verts_count(&cu->nurb); } - if (tot == 0) + if (tot == 0) { return NULL; + } co = vertCos = MEM_mallocN(tot * sizeof(*vertCos), __func__); @@ -2177,8 +2256,9 @@ void BKE_keyblock_update_from_offset(Object *ob, KeyBlock *kb, float (*ofs)[3]) /* ==========================================================*/ -/** Move shape key from org_index to new_index. Safe, clamps index to valid range, updates reference keys, - * the object's active shape index, the 'frame' value in case of absolute keys, etc. +/** Move shape key from org_index to new_index. Safe, clamps index to valid range, + * updates reference keys, the object's active shape index, + * the 'frame' value in case of absolute keys, etc. * Note indices are expected in real values (not 'fake' shapenr +1 ones). * * \param org_index: if < 0, current object's active shape will be used as skey to move. @@ -2206,8 +2286,8 @@ bool BKE_keyblock_move(Object *ob, int org_index, int new_index) rev = ((new_index - org_index) < 0) ? true : false; - /* We swap 'org' element with its previous/next neighbor (depending on direction of the move) repeatedly, - * until we reach final position. + /* We swap 'org' element with its previous/next neighbor (depending on direction of the move) + * repeatedly, until we reach final position. * This allows us to only loop on the list once! */ for (kb = (rev ? key->block.last : key->block.first), i = (rev ? totkey - 1 : 0); kb; kb = (rev ? kb->prev : kb->next), rev ? i-- : i++) { @@ -2244,7 +2324,8 @@ bool BKE_keyblock_move(Object *ob, int org_index, int new_index) } } - /* Need to update active shape number if it's affected, same principle as for relative indices above. */ + /* Need to update active shape number if it's affected, + * same principle as for relative indices above. */ if (org_index == act_index) { ob->shapenr = new_index + 1; } diff --git a/source/blender/blenkernel/intern/lattice.c b/source/blender/blenkernel/intern/lattice.c index d301405bdb4..b8178bec52f 100644 --- a/source/blender/blenkernel/intern/lattice.c +++ b/source/blender/blenkernel/intern/lattice.c @@ -32,6 +32,7 @@ #include "BLI_listbase.h" #include "BLI_bitmap.h" #include "BLI_math.h" +#include "BLI_task.h" #include "DNA_mesh_types.h" #include "DNA_meshdata_types.h" @@ -147,12 +148,15 @@ void BKE_lattice_resize(Lattice *lt, int uNew, int vNew, int wNew, Object *ltOb) } while (uNew * vNew * wNew > 32000) { - if (uNew >= vNew && uNew >= wNew) + if (uNew >= vNew && uNew >= wNew) { uNew--; - else if (vNew >= uNew && vNew >= wNew) + } + else if (vNew >= uNew && vNew >= wNew) { vNew--; - else + } + else { wNew--; + } } vertexCos = MEM_mallocN(sizeof(*vertexCos) * uNew * vNew * wNew, "tmp_vcos"); @@ -265,8 +269,10 @@ Lattice *BKE_lattice_add(Main *bmain, const char *name) } /** - * Only copy internal data of Lattice ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of Lattice ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * @@ -311,10 +317,12 @@ void BKE_lattice_free(Lattice *lt) if (lt->editlatt) { Lattice *editlt = lt->editlatt->latt; - if (editlt->def) + if (editlt->def) { MEM_freeN(editlt->def); - if (editlt->dvert) + } + if (editlt->dvert) { BKE_defvert_array_free(editlt->dvert, lt->pntsu * lt->pntsv * lt->pntsw); + } MEM_freeN(editlt); MEM_freeN(lt->editlatt); @@ -349,8 +357,9 @@ LatticeDeformData *init_latt_deform(Object *oblatt, Object *ob) float latmat[4][4]; LatticeDeformData *lattice_deform_data; - if (lt->editlatt) + if (lt->editlatt) { lt = lt->editlatt->latt; + } bp = lt->def; fp = latticedata = MEM_mallocN(sizeof(float) * 3 * lt->pntsu * lt->pntsv * lt->pntsw, @@ -415,10 +424,12 @@ void calc_latt_deform(LatticeDeformData *lattice_deform_data, float co[3], float MDeformVert *dvert = BKE_lattice_deform_verts_get(ob); float *__restrict latticedata = lattice_deform_data->latticedata; - if (lt->editlatt) + if (lt->editlatt) { lt = lt->editlatt->latt; - if (latticedata == NULL) + } + if (latticedata == NULL) { return; + } if (lt->vgroup[0] && dvert) { defgrp_index = defgroup_name_index(ob, lt->vgroup); @@ -471,10 +482,12 @@ void calc_latt_deform(LatticeDeformData *lattice_deform_data, float co[3], float if (w != 0.0f) { if (ww > 0) { - if (ww < lt->pntsw) + if (ww < lt->pntsw) { idx_w = ww * lt->pntsu * lt->pntsv; - else + } + else { idx_w = (lt->pntsw - 1) * lt->pntsu * lt->pntsv; + } } else { idx_w = 0; @@ -485,10 +498,12 @@ void calc_latt_deform(LatticeDeformData *lattice_deform_data, float co[3], float if (v != 0.0f) { if (vv > 0) { - if (vv < lt->pntsv) + if (vv < lt->pntsv) { idx_v = idx_w + vv * lt->pntsu; - else + } + else { idx_v = idx_w + (lt->pntsv - 1) * lt->pntsu; + } } else { idx_v = idx_w; @@ -499,10 +514,12 @@ void calc_latt_deform(LatticeDeformData *lattice_deform_data, float co[3], float if (u != 0.0f) { if (uu > 0) { - if (uu < lt->pntsu) + if (uu < lt->pntsu) { idx_u = idx_v + uu; - else + } + else { idx_u = idx_v + (lt->pntsu - 1); + } } else { idx_u = idx_v; @@ -510,8 +527,9 @@ void calc_latt_deform(LatticeDeformData *lattice_deform_data, float co[3], float madd_v3_v3fl(co, &latticedata[idx_u * 3], u); - if (defgrp_index != -1) + if (defgrp_index != -1) { weight_blend += (u * defvert_find_weight(dvert + idx_u, defgrp_index)); + } } } } @@ -519,14 +537,16 @@ void calc_latt_deform(LatticeDeformData *lattice_deform_data, float co[3], float } } - if (defgrp_index != -1) + if (defgrp_index != -1) { interp_v3_v3v3(co, co_prev, co, weight_blend); + } } void end_latt_deform(LatticeDeformData *lattice_deform_data) { - if (lattice_deform_data->latticedata) + if (lattice_deform_data->latticedata) { MEM_freeN(lattice_deform_data->latticedata); + } MEM_freeN(lattice_deform_data); } @@ -562,10 +582,12 @@ static bool where_on_path_deform( /* test for cyclic */ bl = ob->runtime.curve_cache->bev.first; - if (!bl->nr) + if (!bl->nr) { return false; - if (bl->poly > -1) + } + if (bl->poly > -1) { cycl = 1; + } if (cycl == 0) { ctime1 = CLAMPIS(ctime, 0.0f, 1.0f); @@ -585,19 +607,23 @@ static bool where_on_path_deform( sub_v3_v3v3(dvec, path->data[1].vec, path->data[0].vec); mul_v3_fl(dvec, ctime * (float)path->len); add_v3_v3(vec, dvec); - if (quat) + if (quat) { copy_qt_qt(quat, path->data[0].quat); - if (radius) + } + if (radius) { *radius = path->data[0].radius; + } } else if (ctime > 1.0f) { sub_v3_v3v3(dvec, path->data[path->len - 1].vec, path->data[path->len - 2].vec); mul_v3_fl(dvec, (ctime - 1.0f) * (float)path->len); add_v3_v3(vec, dvec); - if (quat) + if (quat) { copy_qt_qt(quat, path->data[path->len - 1].quat); - if (radius) + } + if (radius) { *radius = path->data[path->len - 1].radius; + } /* weight - not used but could be added */ } } @@ -631,10 +657,12 @@ static bool calc_curve_deform( /* options */ if (is_neg_axis) { index = axis - 3; - if (cu->flag & CU_STRETCH) + if (cu->flag & CU_STRETCH) { fac = -(co[index] - cd->dmax[index]) / (cd->dmax[index] - cd->dmin[index]); - else + } + else { fac = -(co[index] - cd->dmax[index]) / (par->runtime.curve_cache->path->totdist); + } } else { index = axis; @@ -656,8 +684,8 @@ static bool calc_curve_deform( if (cd->no_rot_axis) { /* set by caller */ - /* this is not exactly the same as 2.4x, since the axis is having rotation removed rather than - * changing the axis before calculating the tilt but serves much the same purpose */ + /* This is not exactly the same as 2.4x, since the axis is having rotation removed rather + * than changing the axis before calculating the tilt but serves much the same purpose. */ float dir_flat[3] = {0, 0, 0}, q[4]; copy_v3_v3(dir_flat, dir); dir_flat[cd->no_rot_axis - 1] = 0.0f; @@ -674,8 +702,10 @@ static bool calc_curve_deform( * * The way 'co' is copied to 'cent' may seem to have no meaning, but it does. * - * Use a curve modifier to stretch a cube out, color each side RGB, positive side light, negative dark. - * view with X up (default), from the angle that you can see 3 faces RGB colors (light), anti-clockwise + * Use a curve modifier to stretch a cube out, color each side RGB, + * positive side light, negative dark. + * view with X up (default), from the angle that you can see 3 faces RGB colors (light), + * anti-clockwise * Notice X,Y,Z Up all have light colors and each ordered CCW. * * Now for Neg Up XYZ, the colors are all dark, and ordered clockwise - Campbell @@ -695,8 +725,9 @@ static bool calc_curve_deform( cent[index] = 0.0f; /* scale if enabled */ - if (cu->flag & CU_PATH_RADIUS) + if (cu->flag & CU_PATH_RADIUS) { mul_v3_fl(cent, radius); + } /* local rotation */ normalize_qt(quat); @@ -705,8 +736,9 @@ static bool calc_curve_deform( /* translation */ add_v3_v3v3(co, cent, loc); - if (r_quat) + if (r_quat) { copy_qt_qt(r_quat, quat); + } return true; } @@ -726,8 +758,9 @@ void curve_deform_verts(Object *cuOb, CurveDeform cd; const bool is_neg_axis = (defaxis > 2); - if (cuOb->type != OB_CURVE) + if (cuOb->type != OB_CURVE) { return; + } cu = cuOb->data; @@ -839,12 +872,38 @@ void curve_deform_vector( quat_to_mat3(qmat, quat); mul_m3_m3m3(mat, qmat, cd.objectspace3); } - else + else { unit_m3(mat); + } mul_m4_v3(cd.objectspace, vec); } +typedef struct LatticeDeformUserdata { + LatticeDeformData *lattice_deform_data; + float (*vertexCos)[3]; + MDeformVert *dvert; + int defgrp_index; + float fac; +} LatticeDeformUserdata; + +static void lattice_deform_vert_task(void *__restrict userdata, + const int index, + const ParallelRangeTLS *__restrict UNUSED(tls)) +{ + const LatticeDeformUserdata *data = userdata; + + if (data->dvert != NULL) { + const float weight = defvert_find_weight(data->dvert + index, data->defgrp_index); + if (weight > 0.0f) { + calc_latt_deform(data->lattice_deform_data, data->vertexCos[index], weight * data->fac); + } + } + else { + calc_latt_deform(data->lattice_deform_data, data->vertexCos[index], data->fac); + } +} + void lattice_deform_verts(Object *laOb, Object *target, Mesh *mesh, @@ -856,10 +915,10 @@ void lattice_deform_verts(Object *laOb, LatticeDeformData *lattice_deform_data; MDeformVert *dvert = NULL; int defgrp_index = -1; - int a; - if (laOb->type != OB_LATTICE) + if (laOb->type != OB_LATTICE) { return; + } lattice_deform_data = init_latt_deform(laOb, target); @@ -882,20 +941,18 @@ void lattice_deform_verts(Object *laOb, } } } - if (dvert) { - MDeformVert *dvert_iter; - for (a = 0, dvert_iter = dvert; a < numVerts; a++, dvert_iter++) { - const float weight = defvert_find_weight(dvert_iter, defgrp_index); - if (weight > 0.0f) { - calc_latt_deform(lattice_deform_data, vertexCos[a], weight * fac); - } - } - } - else { - for (a = 0; a < numVerts; a++) { - calc_latt_deform(lattice_deform_data, vertexCos[a], fac); - } - } + + LatticeDeformUserdata data = {.lattice_deform_data = lattice_deform_data, + .vertexCos = vertexCos, + .dvert = dvert, + .defgrp_index = defgrp_index, + .fac = fac}; + + ParallelRangeSettings settings; + BLI_parallel_range_settings_defaults(&settings); + settings.min_iter_per_thread = 32; + BLI_task_parallel_range(0, numVerts, &data, lattice_deform_vert_task, &settings); + end_latt_deform(lattice_deform_data); } @@ -929,12 +986,15 @@ void outside_lattice(Lattice *lt) if (lt->flag & LT_OUTSIDE) { bp = lt->def; - if (lt->pntsu > 1) + if (lt->pntsu > 1) { du = 1.0f / ((float)lt->pntsu - 1); - if (lt->pntsv > 1) + } + if (lt->pntsv > 1) { dv = 1.0f / ((float)lt->pntsv - 1); - if (lt->pntsw > 1) + } + if (lt->pntsw > 1) { dw = 1.0f / ((float)lt->pntsw - 1); + } for (w = 0; w < lt->pntsw; w++) { @@ -985,10 +1045,13 @@ void outside_lattice(Lattice *lt) else { bp = lt->def; - for (w = 0; w < lt->pntsw; w++) - for (v = 0; v < lt->pntsv; v++) - for (u = 0; u < lt->pntsu; u++, bp++) + for (w = 0; w < lt->pntsw; w++) { + for (v = 0; v < lt->pntsv; v++) { + for (u = 0; u < lt->pntsu; u++, bp++) { bp->hide = 0; + } + } + } } } @@ -998,8 +1061,9 @@ float (*BKE_lattice_vertexcos_get(struct Object *ob, int *r_numVerts))[3] int i, numVerts; float(*vertexCos)[3]; - if (lt->editlatt) + if (lt->editlatt) { lt = lt->editlatt->latt; + } numVerts = *r_numVerts = lt->pntsu * lt->pntsv * lt->pntsw; vertexCos = MEM_mallocN(sizeof(*vertexCos) * numVerts, "lt_vcos"); @@ -1024,7 +1088,8 @@ void BKE_lattice_vertexcos_apply(struct Object *ob, float (*vertexCos)[3]) void BKE_lattice_modifiers_calc(struct Depsgraph *depsgraph, Scene *scene, Object *ob) { Lattice *lt = ob->data; - /* Get vertex coordinates from the original copy; otherwise we get already-modified coordinates. */ + /* Get vertex coordinates from the original copy; + * otherwise we get already-modified coordinates. */ Object *ob_orig = DEG_get_original_object(ob); VirtualModifierData virtualModifierData; ModifierData *md = modifiers_getVirtualModifierList(ob, &virtualModifierData); @@ -1042,19 +1107,25 @@ void BKE_lattice_modifiers_calc(struct Depsgraph *depsgraph, Scene *scene, Objec for (; md; md = md->next) { const ModifierTypeInfo *mti = modifierType_getInfo(md->type); - if (!(mti->flags & eModifierTypeFlag_AcceptsLattice)) + if (!(mti->flags & eModifierTypeFlag_AcceptsLattice)) { continue; - if (!(md->mode & eModifierMode_Realtime)) + } + if (!(md->mode & eModifierMode_Realtime)) { continue; - if (editmode && !(md->mode & eModifierMode_Editmode)) + } + if (editmode && !(md->mode & eModifierMode_Editmode)) { continue; - if (mti->isDisabled && mti->isDisabled(scene, md, 0)) + } + if (mti->isDisabled && mti->isDisabled(scene, md, 0)) { continue; - if (mti->type != eModifierTypeType_OnlyDeform) + } + if (mti->type != eModifierTypeType_OnlyDeform) { continue; + } - if (!vertexCos) + if (!vertexCos) { vertexCos = BKE_lattice_vertexcos_get(ob_orig, &numVerts); + } mti->deformVerts(md, &mectx, NULL, vertexCos, numVerts); } @@ -1066,8 +1137,9 @@ void BKE_lattice_modifiers_calc(struct Depsgraph *depsgraph, Scene *scene, Objec } else { /* Displist won't do anything; this is just for posterity's sake until we remove it. */ - if (!vertexCos) + if (!vertexCos) { vertexCos = BKE_lattice_vertexcos_get(ob_orig, &numVerts); + } DispList *dl = MEM_callocN(sizeof(*dl), "lt_dl"); dl->type = DL_VERTS; @@ -1083,8 +1155,9 @@ struct MDeformVert *BKE_lattice_deform_verts_get(struct Object *oblatt) { Lattice *lt = (Lattice *)oblatt->data; BLI_assert(oblatt->type == OB_LATTICE); - if (lt->editlatt) + if (lt->editlatt) { lt = lt->editlatt->latt; + } return lt->dvert; } @@ -1110,14 +1183,16 @@ void BKE_lattice_center_median(Lattice *lt, float cent[3]) { int i, numVerts; - if (lt->editlatt) + if (lt->editlatt) { lt = lt->editlatt->latt; + } numVerts = lt->pntsu * lt->pntsv * lt->pntsw; zero_v3(cent); - for (i = 0; i < numVerts; i++) + for (i = 0; i < numVerts; i++) { add_v3_v3(cent, lt->def[i].vec); + } mul_v3_fl(cent, 1.0f / (float)numVerts); } @@ -1161,12 +1236,14 @@ void BKE_lattice_minmax_dl(Object *ob, Lattice *lt, float min[3], float max[3]) else { int i, numVerts; - if (lt->editlatt) + if (lt->editlatt) { lt = lt->editlatt->latt; + } numVerts = lt->pntsu * lt->pntsv * lt->pntsw; - for (i = 0; i < numVerts; i++) + for (i = 0; i < numVerts; i++) { minmax_v3v3_v3(min, max, &dl->verts[i * 3]); + } } } @@ -1174,12 +1251,14 @@ void BKE_lattice_minmax(Lattice *lt, float min[3], float max[3]) { int i, numVerts; - if (lt->editlatt) + if (lt->editlatt) { lt = lt->editlatt->latt; + } numVerts = lt->pntsu * lt->pntsv * lt->pntsw; - for (i = 0; i < numVerts; i++) + for (i = 0; i < numVerts; i++) { minmax_v3v3_v3(min, max, lt->def[i].vec); + } } void BKE_lattice_center_bounds(Lattice *lt, float cent[3]) @@ -1220,13 +1299,17 @@ void BKE_lattice_translate(Lattice *lt, float offset[3], bool do_keys) numVerts = lt->pntsu * lt->pntsv * lt->pntsw; - if (lt->def) - for (i = 0; i < numVerts; i++) + if (lt->def) { + for (i = 0; i < numVerts; i++) { add_v3_v3(lt->def[i].vec, offset); + } + } - if (lt->editlatt) - for (i = 0; i < numVerts; i++) + if (lt->editlatt) { + for (i = 0; i < numVerts; i++) { add_v3_v3(lt->editlatt->latt->def[i].vec, offset); + } + } if (do_keys && lt->key) { KeyBlock *kb; diff --git a/source/blender/blenkernel/intern/layer.c b/source/blender/blenkernel/intern/layer.c index 133deb13836..fc349e62809 100644 --- a/source/blender/blenkernel/intern/layer.c +++ b/source/blender/blenkernel/intern/layer.c @@ -35,7 +35,6 @@ #include "BKE_main.h" #include "BKE_node.h" #include "BKE_object.h" -#include "BKE_scene.h" #include "DNA_ID.h" #include "DNA_space_types.h" @@ -91,7 +90,9 @@ static Base *object_base_new(Object *ob) { Base *base = MEM_callocN(sizeof(Base), "Object Base"); base->object = ob; - BKE_scene_object_base_flag_sync_from_object(base); + if (ob->base_flag & BASE_SELECTED) { + base->flag |= BASE_SELECTED; + } return base; } @@ -345,19 +346,14 @@ void BKE_view_layer_base_deselect_all(ViewLayer *view_layer) } } -void BKE_view_layer_base_select(Base *selbase) +void BKE_view_layer_base_select_and_set_active(struct ViewLayer *view_layer, Base *selbase) { + view_layer->basact = selbase; if ((selbase->flag & BASE_SELECTABLE) != 0) { selbase->flag |= BASE_SELECTED; } } -void BKE_view_layer_base_select_and_set_active(struct ViewLayer *view_layer, Base *selbase) -{ - view_layer->basact = selbase; - BKE_view_layer_base_select(selbase); -} - /**************************** Copy View Layer and Layer Collections ***********************/ static void layer_collections_copy_data(ViewLayer *view_layer_dst, @@ -450,8 +446,9 @@ void BKE_view_layer_rename(Main *bmain, Scene *scene, ViewLayer *view_layer, con for (node = scene->nodetree->nodes.first; node; node = node->next) { if (node->type == CMP_NODE_R_LAYERS && node->id == NULL) { - if (node->custom1 == index) + if (node->custom1 == index) { BLI_strncpy(node->name, view_layer->name, NODE_MAXSTR); + } } } } @@ -1099,7 +1096,8 @@ static void layer_collection_bases_hide_recursive(ViewLayer *view_layer, LayerCo /** * Hide/show all the elements of a collection. - * Don't change the collection children enable/disable state, but it may change it for the collection itself. + * Don't change the collection children enable/disable state, + * but it may change it for the collection itself. * * Return true if depsgraph needs update. */ diff --git a/source/blender/blenkernel/intern/library.c b/source/blender/blenkernel/intern/library.c index 4230ab313d0..ad0c405ab28 100644 --- a/source/blender/blenkernel/intern/library.c +++ b/source/blender/blenkernel/intern/library.c @@ -170,11 +170,14 @@ void id_lib_extern(ID *id) } } -/* ensure we have a real user */ -/* Note: Now that we have flags, we could get rid of the 'fake_user' special case, flags are enough to ensure - * we always have a real user. - * However, ID_REAL_USERS is used in several places outside of core library.c, so think we can wait later - * to make this change... */ +/** + * Ensure we have a real user + * + * \note Now that we have flags, we could get rid of the 'fake_user' special case, + * flags are enough to ensure we always have a real user. + * However, #ID_REAL_USERS is used in several places outside of core library.c, + * so think we can wait later to make this change. + */ void id_us_ensure_real(ID *id) { if (id) { @@ -254,7 +257,8 @@ void id_us_min(ID *id) } if ((id->us == limit) && (id->tag & LIB_TAG_EXTRAUSER)) { - /* We need an extra user here, but never actually incremented user count for it so far, do it now. */ + /* We need an extra user here, but never actually incremented user count for it so far, + * do it now. */ id_us_ensure_real(id); } } @@ -293,7 +297,8 @@ static int id_expand_local_callback(void *UNUSED(user_data), return IDWALK_RET_NOP; } - /* Can happen that we get unlinkable ID here, e.g. with shapekey referring to itself (through drivers)... + /* Can happen that we get un-linkable ID here, e.g. with shape-key referring to itself + * (through drivers)... * Just skip it, shape key can only be either indirectly linked, or fully local, period. * And let's curse one more time that stupid useless shapekey ID type! */ if (*id_pointer && *id_pointer != id_self && BKE_idcode_is_linkable(GS((*id_pointer)->name))) { @@ -304,7 +309,8 @@ static int id_expand_local_callback(void *UNUSED(user_data), } /** - * Expand ID usages of given id as 'extern' (and no more indirect) linked data. Used by ID copy/make_local functions. + * Expand ID usages of given id as 'extern' (and no more indirect) linked data. + * Used by ID copy/make_local functions. */ void BKE_id_expand_local(Main *bmain, ID *id) { @@ -335,7 +341,8 @@ void BKE_id_make_local_generic(Main *bmain, /* - only lib users: do nothing (unless force_local is set) * - only local users: set flag * - mixed: make copy - * In case we make a whole lib's content local, we always want to localize, and we skip remapping (done later). + * In case we make a whole lib's content local, + * we always want to localize, and we skip remapping (done later). */ if (!ID_IS_LINKED(id)) { @@ -352,7 +359,8 @@ void BKE_id_make_local_generic(Main *bmain, else { ID *id_new; - /* Should not fail in expected usecases, but a few ID types cannot be copied (LIB, WM, SCR...). */ + /* Should not fail in expected use cases, + * but a few ID types cannot be copied (LIB, WM, SCR...). */ if (BKE_id_copy(bmain, id, &id_new)) { id_new->us = 0; @@ -380,137 +388,169 @@ void BKE_id_make_local_generic(Main *bmain, * * \note Always set ID->newid pointer in case it gets duplicated... * - * \param lib_local: Special flag used when making a whole library's content local, it needs specific handling. + * \param lib_local: Special flag used when making a whole library's content local, + * it needs specific handling. * * \return true if the block can be made local. */ bool id_make_local(Main *bmain, ID *id, const bool test, const bool lib_local) { - /* We don't care whether ID is directly or indirectly linked in case we are making a whole lib local... */ + /* We don't care whether ID is directly or indirectly linked + * in case we are making a whole lib local... */ if (!lib_local && (id->tag & LIB_TAG_INDIRECT)) { return false; } switch ((ID_Type)GS(id->name)) { case ID_SCE: - if (!test) + if (!test) { BKE_scene_make_local(bmain, (Scene *)id, lib_local); + } return true; case ID_OB: - if (!test) + if (!test) { BKE_object_make_local(bmain, (Object *)id, lib_local); + } return true; case ID_ME: - if (!test) + if (!test) { BKE_mesh_make_local(bmain, (Mesh *)id, lib_local); + } return true; case ID_CU: - if (!test) + if (!test) { BKE_curve_make_local(bmain, (Curve *)id, lib_local); + } return true; case ID_MB: - if (!test) + if (!test) { BKE_mball_make_local(bmain, (MetaBall *)id, lib_local); + } return true; case ID_MA: - if (!test) + if (!test) { BKE_material_make_local(bmain, (Material *)id, lib_local); + } return true; case ID_TE: - if (!test) + if (!test) { BKE_texture_make_local(bmain, (Tex *)id, lib_local); + } return true; case ID_IM: - if (!test) + if (!test) { BKE_image_make_local(bmain, (Image *)id, lib_local); + } return true; case ID_LT: - if (!test) + if (!test) { BKE_lattice_make_local(bmain, (Lattice *)id, lib_local); + } return true; case ID_LA: - if (!test) + if (!test) { BKE_light_make_local(bmain, (Light *)id, lib_local); + } return true; case ID_CA: - if (!test) + if (!test) { BKE_camera_make_local(bmain, (Camera *)id, lib_local); + } return true; case ID_SPK: - if (!test) + if (!test) { BKE_speaker_make_local(bmain, (Speaker *)id, lib_local); + } return true; case ID_LP: - if (!test) + if (!test) { BKE_lightprobe_make_local(bmain, (LightProbe *)id, lib_local); + } return true; case ID_WO: - if (!test) + if (!test) { BKE_world_make_local(bmain, (World *)id, lib_local); + } return true; case ID_VF: - if (!test) + if (!test) { BKE_vfont_make_local(bmain, (VFont *)id, lib_local); + } return true; case ID_TXT: - if (!test) + if (!test) { BKE_text_make_local(bmain, (Text *)id, lib_local); + } return true; case ID_SO: - if (!test) + if (!test) { BKE_sound_make_local(bmain, (bSound *)id, lib_local); + } return true; case ID_GR: - if (!test) + if (!test) { BKE_collection_make_local(bmain, (Collection *)id, lib_local); + } return true; case ID_AR: - if (!test) + if (!test) { BKE_armature_make_local(bmain, (bArmature *)id, lib_local); + } return true; case ID_AC: - if (!test) + if (!test) { BKE_action_make_local(bmain, (bAction *)id, lib_local); + } return true; case ID_NT: - if (!test) + if (!test) { ntreeMakeLocal(bmain, (bNodeTree *)id, true, lib_local); + } return true; case ID_BR: - if (!test) + if (!test) { BKE_brush_make_local(bmain, (Brush *)id, lib_local); + } return true; case ID_PA: - if (!test) + if (!test) { BKE_particlesettings_make_local(bmain, (ParticleSettings *)id, lib_local); + } return true; case ID_GD: - if (!test) + if (!test) { BKE_gpencil_make_local(bmain, (bGPdata *)id, lib_local); + } return true; case ID_MC: - if (!test) + if (!test) { BKE_movieclip_make_local(bmain, (MovieClip *)id, lib_local); + } return true; case ID_MSK: - if (!test) + if (!test) { BKE_mask_make_local(bmain, (Mask *)id, lib_local); + } return true; case ID_LS: - if (!test) + if (!test) { BKE_linestyle_make_local(bmain, (FreestyleLineStyle *)id, lib_local); + } return true; case ID_PAL: - if (!test) + if (!test) { BKE_palette_make_local(bmain, (Palette *)id, lib_local); + } return true; case ID_PC: - if (!test) + if (!test) { BKE_paint_curve_make_local(bmain, (PaintCurve *)id, lib_local); + } return true; case ID_CF: - if (!test) + if (!test) { BKE_cachefile_make_local(bmain, (CacheFile *)id, lib_local); + } return true; case ID_WS: case ID_SCR: @@ -571,15 +611,18 @@ bool BKE_id_copy_is_allowed(const ID *id) /** * Generic entry point for copying a datablock (new API). * - * \note Copy is only affecting given data-block (no ID used by copied one will be affected, besides usercount). - * There is only one exception, if LIB_ID_COPY_ACTIONS is defined, actions used by animdata will be duplicated. + * \note Copy is only affecting given data-block + * (no ID used by copied one will be affected, besides usercount). + * There is only one exception, if #LIB_ID_COPY_ACTIONS is defined, + * actions used by animdata will be duplicated. * * \note Usercount of new copy is always set to 1. * * \param bmain: Main database, may be NULL only if LIB_ID_CREATE_NO_MAIN is specified. * \param id: Source datablock. * \param r_newid: Pointer to new (copied) ID pointer. - * \param flag: Set of copy options, see DNA_ID.h enum for details (leave to zero for default, full copy). + * \param flag: Set of copy options, see DNA_ID.h enum for details + * (leave to zero for default, full copy). * \return False when copying that ID type is not supported, true otherwise. */ bool BKE_id_copy_ex(Main *bmain, const ID *id, ID **r_newid, const int flag) @@ -818,7 +861,8 @@ bool id_single_user(bContext *C, ID *id, PointerRNA *ptr, PropertyRNA *prop) PointerRNA idptr; if (id) { - /* if property isn't editable, we're going to have an extra block hanging around until we save */ + /* If property isn't editable, + * we're going to have an extra block hanging around until we save. */ if (RNA_property_editable(ptr, prop)) { Main *bmain = CTX_data_main(C); /* copy animation actions too */ @@ -1004,13 +1048,15 @@ void BKE_main_id_flag_listbase(ListBase *lb, const int flag, const bool value) { ID *id; if (value) { - for (id = lb->first; id; id = id->next) + for (id = lb->first; id; id = id->next) { id->tag |= flag; + } } else { const int nflag = ~flag; - for (id = lb->first; id; id = id->next) + for (id = lb->first; id; id = id->next) { id->tag &= nflag; + } } } @@ -1340,7 +1386,9 @@ void *BKE_id_new(Main *bmain, const short type, const char *name) return id; } -/** Generic helper to create a new temporary empty datablock of given type, *outside* of any Main database. +/** + * Generic helper to create a new temporary empty datablock of given type, + * *outside* of any Main database. * * \param name: can be NULL, in which case we get default name for this ID type. */ void *BKE_id_new_nomain(const short type, const char *name) @@ -1452,8 +1500,9 @@ void *BKE_libblock_copy_for_localize(const ID *id) void BKE_library_free(Library *lib) { - if (lib->packedfile) + if (lib->packedfile) { freePackedFile(lib->packedfile); + } } /* ***************** ID ************************ */ @@ -1501,8 +1550,9 @@ static ID *is_dupid(ListBase *lb, ID *id, const char *name) /* do not test alphabetic! */ /* optimized */ if (idtest->name[2] == name[0]) { - if (STREQ(name, idtest->name + 2)) + if (STREQ(name, idtest->name + 2)) { break; + } } } } @@ -1537,8 +1587,9 @@ static bool check_for_dupid(ListBase *lb, ID *id, char *name) idtest = is_dupid(lb, id, name); /* if there is no double, done */ - if (idtest == NULL) + if (idtest == NULL) { return false; + } /* we have a dup; need to make a new name */ /* quick check so we can reuse one of first MAX_IN_USE - 1 ids if vacant */ @@ -1567,10 +1618,12 @@ static bool check_for_dupid(ListBase *lb, ID *id, char *name) STREQLEN(name, idtest->name + 2, left_len) && (BLI_split_name_num(leftest, &nrtest, idtest->name + 2, '.') == left_len)) { /* will get here at least once, otherwise is_dupid call above would have returned NULL */ - if (nrtest < MAX_IN_USE) + if (nrtest < MAX_IN_USE) { in_use[nrtest] = true; /* mark as used */ - if (nr <= nrtest) + } + if (nr <= nrtest) { nr = nrtest + 1; /* track largest unused */ + } } } /* At this point, 'nr' will typically be at least 1. (but not always) */ @@ -1578,9 +1631,10 @@ static bool check_for_dupid(ListBase *lb, ID *id, char *name) /* decide which value of nr to use */ for (a = 0; a < MAX_IN_USE; a++) { - if (a >= nr) + if (a >= nr) { break; /* stop when we've checked up to biggest */ /* redundant check */ - if (!in_use[a]) { /* found an unused value */ + } + if (!in_use[a]) { /* found an unused value */ nr = a; /* can only be zero if all potential duplicate names had * nonzero numeric suffixes, which means name itself has @@ -1610,8 +1664,9 @@ static bool check_for_dupid(ListBase *lb, ID *id, char *name) name[len--] = '\0'; idtest = is_dupid(lb, id, name); } - if (idtest == NULL) + if (idtest == NULL) { return true; + } /* otherwise just continue and use a number suffix */ } @@ -1644,13 +1699,15 @@ bool BKE_id_new_name_validate(ListBase *lb, ID *id, const char *tname) char name[MAX_ID_NAME - 2]; /* if library, don't rename */ - if (ID_IS_LINKED(id)) + if (ID_IS_LINKED(id)) { return false; + } /* if no name given, use name of current ID * else make a copy (tname args can be const) */ - if (tname == NULL) + if (tname == NULL) { tname = id->name + 2; + } BLI_strncpy(name, tname, sizeof(name)); @@ -1702,7 +1759,8 @@ void id_clear_lib_data_ex(Main *bmain, ID *id, const bool id_in_mainlist) } } - /* Internal bNodeTree blocks inside datablocks also stores id->lib, make sure this stays in sync. */ + /* Internal bNodeTree blocks inside datablocks also stores id->lib, + * make sure this stays in sync. */ if ((ntree = ntreeFromID(id))) { id_clear_lib_data_ex(bmain, &ntree->id, false); /* Datablocks' nodetree is never in Main. */ } @@ -1723,8 +1781,7 @@ void BKE_main_id_clear_newpoins(Main *bmain) { ID *id; - FOREACH_MAIN_ID_BEGIN(bmain, id) - { + FOREACH_MAIN_ID_BEGIN (bmain, id) { id->newid = NULL; id->tag &= ~LIB_TAG_NEW; } @@ -1748,14 +1805,15 @@ static void library_make_local_copying_check(ID *id, /* Our oh-so-beloved 'from' pointers... */ if (entry->usage_flag & IDWALK_CB_LOOPBACK) { - /* We totally disregard Object->proxy_from 'usage' here, this one would only generate fake positives. */ + /* We totally disregard Object->proxy_from 'usage' here, + * this one would only generate fake positives. */ if (GS(par_id->name) == ID_OB) { BLI_assert(((Object *)par_id)->proxy_from == (Object *)id); continue; } - /* Shapekeys are considered 'private' to their owner ID here, and never tagged (since they cannot be linked), - * so we have to switch effective parent to their owner. */ + /* Shapekeys are considered 'private' to their owner ID here, and never tagged + * (since they cannot be linked), * so we have to switch effective parent to their owner. */ if (GS(par_id->name) == ID_KE) { par_id = ((Key *)par_id)->from; } @@ -1769,8 +1827,9 @@ static void library_make_local_copying_check(ID *id, if (BLI_gset_haskey(loop_tags, par_id)) { /* We are in a 'dependency loop' of IDs, this does not say us anything, skip it. * Note that this is the situation that can lead to archipelagoes of linked data-blocks - * (since all of them have non-local users, they would all be duplicated, leading to a loop of unused - * linked data-blocks that cannot be freed since they all use each other...). */ + * (since all of them have non-local users, they would all be duplicated, + * leading to a loop of unused linked data-blocks that cannot be freed since they all use + * each other...). */ continue; } /* Else, recursively check that user ID. */ @@ -1778,10 +1837,12 @@ static void library_make_local_copying_check(ID *id, } if (par_id->tag & LIB_TAG_DOIT) { - /* This user will be fully local in future, so far so good, nothing to do here but check next user. */ + /* This user will be fully local in future, so far so good, + * nothing to do here but check next user. */ } else { - /* This user won't be fully local in future, so current ID won't be either. And we are done checking it. */ + /* This user won't be fully local in future, so current ID won't be either. + * And we are done checking it. */ id->tag &= ~LIB_TAG_DOIT; break; } @@ -1795,15 +1856,16 @@ static void library_make_local_copying_check(ID *id, * \param bmain: Almost certainly global main. * \param lib: If not NULL, only make local datablocks from this library. * \param untagged_only: If true, only make local datablocks not tagged with LIB_TAG_PRE_EXISTING. - * \param set_fake: If true, set fake user on all localized datablocks (except group and objects ones). + * \param set_fake: If true, set fake user on all localized data-blocks + * (except group and objects ones). */ -/* Note: Old (2.77) version was simply making (tagging) datablocks as local, without actually making any check whether - * they were also indirectly used or not... +/* Note: Old (2.77) version was simply making (tagging) data-blocks as local, + * without actually making any check whether * they were also indirectly used or not... * - * Current version uses regular id_make_local callback, with advanced pre-processing step to detect all cases of - * IDs currently indirectly used, but which will be used by local data only once this function is finished. - * This allows to avoid any unneeded duplication of IDs, and hence all time lost afterwards to remove - * orphaned linked data-blocks... + * Current version uses regular id_make_local callback, with advanced pre-processing step to detect + * all cases of IDs currently indirectly used, but which will be used by local data only once this + * function is finished. This allows to avoid any unneeded duplication of IDs, and hence all time + * lost afterwards to remove orphaned linked data-blocks... */ void BKE_library_make_local(Main *bmain, const Library *lib, @@ -1834,8 +1896,8 @@ void BKE_library_make_local(Main *bmain, for (int a = set_listbasepointers(bmain, lbarray); a--;) { ID *id = lbarray[a]->first; - /* Do not explicitly make local non-linkable IDs (shapekeys, in fact), they are assumed to be handled - * by real datablocks responsible of them. */ + /* Do not explicitly make local non-linkable IDs (shapekeys, in fact), + * they are assumed to be handled by real datablocks responsible of them. */ const bool do_skip = (id && !BKE_idcode_is_linkable(GS(id->name))); for (; id; id = id->next) { @@ -1849,14 +1911,17 @@ void BKE_library_make_local(Main *bmain, if (id->lib == NULL) { id->tag &= ~(LIB_TAG_EXTERN | LIB_TAG_INDIRECT | LIB_TAG_NEW); } - /* The check on the fourth line (LIB_TAG_PRE_EXISTING) is done so its possible to tag data you don't want to - * be made local, used for appending data, so any libdata already linked wont become local (very nasty + /* The check on the fourth line (LIB_TAG_PRE_EXISTING) is done so it's possible to tag data + * you don't want to be made local, used for appending data, + * so any libdata already linked wont become local (very nasty * to discover all your links are lost after appending). * Also, never ever make proxified objects local, would not make any sense. */ /* Some more notes: * - Shapekeys are never tagged here (since they are not linkable). - * - Nodetrees used in materials etc. have to be tagged manually, since they do not exist in Main (!). - * This is ok-ish on 'make local' side of things (since those are handled by their 'owner' IDs), + * - Nodetrees used in materials etc. have to be tagged manually, + * since they do not exist in Main (!). + * This is ok-ish on 'make local' side of things + * (since those are handled by their 'owner' IDs), * but complicates slightly the pre-processing of relations between IDs at step 2... */ else if (!do_skip && id->tag & (LIB_TAG_EXTERN | LIB_TAG_INDIRECT | LIB_TAG_NEW) && ELEM(lib, NULL, id->lib) && @@ -1865,8 +1930,9 @@ void BKE_library_make_local(Main *bmain, BLI_linklist_prepend_arena(&todo_ids, id, linklist_mem); id->tag |= LIB_TAG_DOIT; - /* Tag those nasty non-ID nodetrees, but do not add them to todo list, making them local is handled - * by 'owner' ID. This is needed for library_make_local_copying_check() to work OK at step 2. */ + /* Tag those nasty non-ID nodetrees, + * but do not add them to todo list, making them local is handled by 'owner' ID. + * This is needed for library_make_local_copying_check() to work OK at step 2. */ if (ntree != NULL) { ntree->tag |= LIB_TAG_DOIT; } @@ -1883,8 +1949,9 @@ void BKE_library_make_local(Main *bmain, TIMEIT_VALUE_PRINT(make_local); #endif - /* Step 2: Check which datablocks we can directly make local (because they are only used by already, or future, - * local data), others will need to be duplicated. */ + /* Step 2: Check which datablocks we can directly make local + * (because they are only used by already, or future, local data), + * others will need to be duplicated. */ GSet *loop_tags = BLI_gset_ptr_new(__func__); for (LinkNode *it = todo_ids; it; it = it->next) { library_make_local_copying_check(it->link, loop_tags, bmain->relations, done_ids); @@ -1902,15 +1969,17 @@ void BKE_library_make_local(Main *bmain, #endif /* Step 3: Make IDs local, either directly (quick and simple), or using generic process, - * which involves more complex checks and might instead create a local copy of original linked ID. */ + * which involves more complex checks and might instead + * create a local copy of original linked ID. */ for (LinkNode *it = todo_ids, *it_next; it; it = it_next) { it_next = it->next; ID *id = it->link; if (id->tag & LIB_TAG_DOIT) { - /* We know all users of this object are local or will be made fully local, even if currently there are - * some indirect usages. So instead of making a copy that we'll likely get rid of later, directly make - * that data block local. Saves a tremendous amount of time with complex scenes... */ + /* We know all users of this object are local or will be made fully local, even if currently + * there are some indirect usages. So instead of making a copy that we'll likely get rid of + * later, directly make that data block local. + * Saves a tremendous amount of time with complex scenes... */ id_clear_lib_data_ex(bmain, id, true); BKE_id_expand_local(bmain, id); id->tag &= ~LIB_TAG_DOIT; @@ -1946,16 +2015,19 @@ void BKE_library_make_local(Main *bmain, TIMEIT_VALUE_PRINT(make_local); #endif - /* At this point, we are done with directly made local IDs. Now we have to handle duplicated ones, since their + /* At this point, we are done with directly made local IDs. + * Now we have to handle duplicated ones, since their * remaining linked original counterpart may not be needed anymore... */ todo_ids = NULL; - /* Step 4: We have to remap local usages of old (linked) ID to new (local) ID in a separated loop, + /* Step 4: We have to remap local usages of old (linked) ID to new (local) + * ID in a separated loop, * as lbarray ordering is not enough to ensure us we did catch all dependencies * (e.g. if making local a parent object before its child...). See T48907. */ - /* TODO This is now the biggest step by far (in term of processing time). We may be able to gain here by - * using again main->relations mapping, but... this implies BKE_libblock_remap & co to be able to update - * main->relations on the fly. Have to think about it a bit more, and see whether new code is OK first, anyway. */ + /* TODO This is now the biggest step by far (in term of processing time). + * We may be able to gain here by using again main->relations mapping, but... + * this implies BKE_libblock_remap & co to be able to update main->relations on the fly. + * Have to think about it a bit more, and see whether new code is OK first, anyway. */ for (LinkNode *it = copied_ids; it; it = it->next) { ID *id = it->link; @@ -2036,10 +2108,11 @@ void BKE_library_make_local(Main *bmain, #endif /* This is probably more of a hack than something we should do here, but... - * Issue is, the whole copying + remapping done in complex cases above may leave pose channels of armatures - * in complete invalid state (more precisely, the bone pointers of the pchans - very crappy cross-datablocks - * relationship), se we tag it to be fully recomputed, but this does not seems to be enough in some cases, - * and evaluation code ends up trying to evaluate a not-yet-updated armature object's deformations. + * Issue is, the whole copying + remapping done in complex cases above may leave pose-channels of + * armatures in complete invalid state (more precisely, the bone pointers of the pose-channels - + * very crappy cross-data-blocks relationship), se we tag it to be fully recomputed, + * but this does not seems to be enough in some cases, and evaluation code ends up trying to + * evaluate a not-yet-updated armature object's deformations. * Try "make all local" in 04_01_H.lighting.blend from Agent327 without this, e.g. */ for (Object *ob = bmain->objects.first; ob; ob = ob->id.next) { if (ob->data != NULL && ob->type == OB_ARMATURE && ob->pose != NULL && @@ -2091,8 +2164,9 @@ void BLI_libblock_ensure_unique_name(Main *bmain, const char *name) ID *idtest; lb = which_libbase(bmain, GS(name)); - if (lb == NULL) + if (lb == NULL) { return; + } /* search for id */ idtest = BLI_findstring(lb, name + 2, offsetof(ID, name) + 2); @@ -2119,7 +2193,8 @@ void BKE_libblock_rename(Main *bmain, ID *id, const char *name) * * \note Result is unique to a given ID type in a given Main database. * - * \param name: An allocated string of minimal length MAX_ID_FULL_NAME, will be filled with generated string. + * \param name: An allocated string of minimal length #MAX_ID_FULL_NAME, + * will be filled with generated string. */ void BKE_id_full_name_get(char name[MAX_ID_FULL_NAME], const ID *id) { @@ -2138,12 +2213,14 @@ void BKE_id_full_name_get(char name[MAX_ID_FULL_NAME], const ID *id) } /** - * Generate full name of the data-block (without ID code, but with library if any), with a 3-character prefix prepended - * indicating whether it comes from a library, is overriding, has a fake or no user, etc. + * Generate full name of the data-block (without ID code, but with library if any), + * with a 3-character prefix prepended indicating whether it comes from a library, + * is overriding, has a fake or no user, etc. * * \note Result is unique to a given ID type in a given Main database. * - * \param name: An allocated string of minimal length MAX_ID_FULL_NAME_UI, will be filled with generated string. + * \param name: An allocated string of minimal length #MAX_ID_FULL_NAME_UI, + * will be filled with generated string. */ void BKE_id_full_name_ui_prefix_get(char name[MAX_ID_FULL_NAME_UI], const ID *id) { @@ -2191,8 +2268,8 @@ void BKE_library_filepath_set(Main *bmain, Library *lib, const char *filepath) * outliner, and its not really supported but allow from here for now * since making local could cause this to be directly linked - campbell */ - /* Never make paths relative to parent lib - reading code (blenloader) always set *all* lib->name relative to - * current main, not to their parent for indirectly linked ones. */ + /* Never make paths relative to parent lib - reading code (blenloader) always set *all* + * lib->name relative to current main, not to their parent for indirectly linked ones. */ const char *basepath = BKE_main_blendfile_path(bmain); BLI_path_abs(lib->filepath, basepath); } diff --git a/source/blender/blenkernel/intern/library_idmap.c b/source/blender/blenkernel/intern/library_idmap.c index d520df31a75..cc7e2e31d07 100644 --- a/source/blender/blenkernel/intern/library_idmap.c +++ b/source/blender/blenkernel/intern/library_idmap.c @@ -182,7 +182,8 @@ ID *BKE_main_idmap_lookup(struct IDNameLib_Map *id_map, ID *BKE_main_idmap_lookup_id(struct IDNameLib_Map *id_map, const ID *id) { /* When used during undo/redo, this function cannot assume that given id points to valid memory - * (i.e. has not been freed), so it has to check that it does exist in 'old' (aka current) Main database. + * (i.e. has not been freed), + * so it has to check that it does exist in 'old' (aka current) Main database. * Otherwise, we cannot provide new ID pointer that way (would crash accessing freed memory * when trying to get ID name). */ diff --git a/source/blender/blenkernel/intern/library_override.c b/source/blender/blenkernel/intern/library_override.c index 7a29575dffe..5ed6577e90a 100644 --- a/source/blender/blenkernel/intern/library_override.c +++ b/source/blender/blenkernel/intern/library_override.c @@ -55,7 +55,8 @@ static void bke_override_property_operation_copy(IDOverrideStaticPropertyOperati static void bke_override_property_clear(IDOverrideStaticProperty *op); static void bke_override_property_operation_clear(IDOverrideStaticPropertyOperation *opop); -/* Temp, for until static override is ready and tested enough to go 'public', we hide it by default in UI and such. */ +/* Temp, for until static override is ready and tested enough to go 'public', + * we hide it by default in UI and such. */ static bool _override_static_enabled = false; void BKE_override_static_enable(const bool do_enable) @@ -79,8 +80,9 @@ IDOverrideStatic *BKE_override_static_init(ID *local_id, ID *reference_id) ID *ancestor_id; for (ancestor_id = reference_id; ancestor_id != NULL && ancestor_id->override_static != NULL && ancestor_id->override_static->reference != NULL; - ancestor_id = ancestor_id->override_static->reference) + ancestor_id = ancestor_id->override_static->reference) { ; + } if (ancestor_id != NULL && ancestor_id->override_static != NULL) { /* Original ID has a template, use it! */ @@ -188,7 +190,8 @@ ID *BKE_override_static_create_from_id(Main *bmain, ID *reference_id) ID *local_id = override_static_create_from(bmain, reference_id); - /* Remapping, we obviously only want to affect local data (and not our own reference pointer to overridden ID). */ + /* Remapping, we obviously only want to affect local data + * (and not our own reference pointer to overridden ID). */ BKE_libblock_remap( bmain, reference_id, local_id, ID_REMAP_SKIP_INDIRECT_USAGE | ID_REMAP_SKIP_STATIC_OVERRIDE); @@ -197,8 +200,8 @@ ID *BKE_override_static_create_from_id(Main *bmain, ID *reference_id) /** Create overridden local copies of all tagged data-blocks in given Main. * - * \note Set id->newid of overridden libs with newly created overrides, caller is responsible to clean those pointers - * before/after usage as needed. + * \note Set id->newid of overridden libs with newly created overrides, + * caller is responsible to clean those pointers before/after usage as needed. * * \return \a true on success, \a false otherwise. */ @@ -207,8 +210,7 @@ bool BKE_override_static_create_from_tag(Main *bmain) ID *reference_id; bool ret = true; - FOREACH_MAIN_ID_BEGIN(bmain, reference_id) - { + FOREACH_MAIN_ID_BEGIN (bmain, reference_id) { if ((reference_id->tag & LIB_TAG_DOIT) != 0 && reference_id->lib != NULL) { if ((reference_id->newid = override_static_create_from(bmain, reference_id)) == NULL) { ret = false; @@ -217,8 +219,7 @@ bool BKE_override_static_create_from_tag(Main *bmain) } FOREACH_MAIN_ID_END; - FOREACH_MAIN_ID_BEGIN(bmain, reference_id) - { + FOREACH_MAIN_ID_BEGIN (bmain, reference_id) { if ((reference_id->tag & LIB_TAG_DOIT) != 0 && reference_id->lib != NULL && reference_id->newid != NULL) { ID *local_id = reference_id->newid; @@ -475,11 +476,11 @@ void BKE_override_static_property_operation_delete( /** * Check that status of local data-block is still valid against current reference one. * - * It means that all overridable, but not overridden, properties' local values must be equal to reference ones. - * Clears LIB_TAG_OVERRIDE_OK if they do not. + * It means that all overridable, but not overridden, properties' local values must be equal to + * reference ones. Clears #LIB_TAG_OVERRIDE_OK if they do not. * - * This is typically used to detect whether some property has been changed in local and a new IDOverrideProperty - * (of IDOverridePropertyOperation) has to be added. + * This is typically used to detect whether some property has been changed in local and a new + * #IDOverrideProperty (of #IDOverridePropertyOperation) has to be added. * * \return true if status is OK, false otherwise. */ bool BKE_override_static_status_check_local(Main *bmain, ID *local) @@ -522,7 +523,8 @@ bool BKE_override_static_status_check_local(Main *bmain, ID *local) * It means that all non-overridden properties' local values must be equal to reference ones. * Clears LIB_TAG_OVERRIDE_OK if they do not. * - * This is typically used to detect whether some reference has changed and local needs to be updated against it. + * This is typically used to detect whether some reference has changed and local + * needs to be updated against it. * * \return true if status is OK, false otherwise. */ bool BKE_override_static_status_check_reference(Main *bmain, ID *local) @@ -570,12 +572,13 @@ bool BKE_override_static_status_check_reference(Main *bmain, ID *local) * Compares local and reference data-blocks and create new override operations as needed, * or reset to reference values if overriding is not allowed. * - * \note Defining override operations is only mandatory before saving a .blend file on disk (not for undo!). + * \note Defining override operations is only mandatory before saving a `.blend` file on disk + * (not for undo!). * Knowing that info at runtime is only useful for UI/UX feedback. * - * \note This is by far the biggest operation (the more time-consuming) of the three so far, since it has to go over - * all properties in depth (all overridable ones at least). Generating diff values and applying overrides - * are much cheaper. + * \note This is by far the biggest operation (the more time-consuming) of the three so far, + * since it has to go over all properties in depth (all overridable ones at least). + * Generating diff values and applying overrides are much cheaper. * * \return true if new overriding op was created, or some local data was reset. */ bool BKE_override_static_operations_create(Main *bmain, ID *local, const bool force_auto) @@ -620,8 +623,7 @@ void BKE_main_override_static_operations_create(Main *bmain, const bool force_au { ID *id; - FOREACH_MAIN_ID_BEGIN(bmain, id) - { + FOREACH_MAIN_ID_BEGIN (bmain, id) { if (force_auto || (ID_IS_STATIC_OVERRIDE_AUTO(id) && (id->tag & LIB_TAG_OVERRIDESTATIC_AUTOREFRESH))) { BKE_override_static_operations_create(bmain, id, force_auto); @@ -644,19 +646,20 @@ void BKE_override_static_update(Main *bmain, ID *local) BKE_override_static_update(bmain, local->override_static->reference); } - /* We want to avoid having to remap here, however creating up-to-date override is much simpler if based - * on reference than on current override. + /* We want to avoid having to remap here, however creating up-to-date override is much simpler + * if based on reference than on current override. * So we work on temp copy of reference, and 'swap' its content with local. */ /* XXX We need a way to get off-Main copies of IDs (similar to localized mats/texts/ etc.)! - * However, this is whole bunch of code work in itself, so for now plain stupid ID copy will do, - * as innefficient as it is. :/ - * Actually, maybe not! Since we are swapping with original ID's local content, we want to keep - * usercount in correct state when freeing tmp_id (and that usercounts of IDs used by 'new' local data - * also remain correct). */ - /* This would imply change in handling of usercout all over RNA (and possibly all over Blender code). - * Not impossible to do, but would rather see first if extra useless usual user handling is actually - * a (performances) issue here. */ + * However, this is whole bunch of code work in itself, so for now plain stupid ID copy will + * do, as inn-efficient as it is. :/ + * Actually, maybe not! Since we are swapping with original ID's local content, we want to + * keep user-count in correct state when freeing tmp_id + * (and that user-counts of IDs used by 'new' local data also remain correct). */ + /* This would imply change in handling of usercout all over RNA + * (and possibly all over Blender code). + * Not impossible to do, but would rather see first if extra useless usual user handling + * is actually a (performances) issue here. */ ID *tmp_id; BKE_id_copy(bmain, local->override_static->reference, &tmp_id); @@ -676,11 +679,12 @@ void BKE_override_static_update(Main *bmain, ID *local) RNA_struct_override_apply( bmain, &rnaptr_dst, &rnaptr_src, rnaptr_storage, local->override_static); - /* 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. */ + /* 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. */ BKE_id_swap(bmain, local, tmp_id); - /* Again, horribly innefficient in our case, we need something off-Main (aka moar generic nolib copy/free stuff)! */ + /* Again, horribly inn-efficient in our case, we need something off-Main + * (aka more generic nolib copy/free stuff)! */ /* XXX And crashing in complex cases (e.g. because depsgraph uses same data...). */ BKE_id_free_ex(bmain, tmp_id, LIB_ID_FREE_NO_UI_USER, true); @@ -705,8 +709,7 @@ void BKE_main_override_static_update(Main *bmain) { ID *id; - FOREACH_MAIN_ID_BEGIN(bmain, id) - { + FOREACH_MAIN_ID_BEGIN (bmain, id) { if (id->override_static != NULL && id->lib == NULL) { BKE_override_static_update(bmain, id); } @@ -714,18 +717,21 @@ void BKE_main_override_static_update(Main *bmain) FOREACH_MAIN_ID_END; } -/*********************************************************************************************************************** - * Storage (how to wtore overriding data into .blend files). +/** + * Storage (how to store overriding data into `.blend` files). * * Basically: - * I) Only 'differential' storage needs special handling here. All others (replacing values or - * inserting/removing items from a collection) can be handled with simply storing current content of local data-block. - * II) We store the differential value into a second 'ghost' data-block, which is an empty ID of same type as local one, - * where we only define values that need differential data. + * 1) Only 'differential' storage needs special handling here. All others (replacing values or + * inserting/removing items from a collection) can be handled with simply storing current + * content of local data-block. + * 2) We store the differential value into a second 'ghost' data-block, + * which is an empty ID of same type as local one, + * where we only define values that need differential data. * - * This avoids us having to modify 'real' data-block at write time (and restoring it afterwards), which is inneficient, - * and potentially dangerous (in case of concurrent access...), while not using much extra memory in typical cases. - * It also ensures stored data-block always contains exact same data as "desired" ones (kind of "baked" data-blocks). + * This avoids us having to modify 'real' data-block at write time (and restoring it afterwards), + * which is inneficient, and potentially dangerous (in case of concurrent access...), while not + * using much extra memory in typical cases. It also ensures stored data-block always contains + * exact same data as "desired" ones (kind of "baked" data-blocks). */ /** Initialize an override storage. */ @@ -737,7 +743,8 @@ OverrideStaticStorage *BKE_override_static_operations_store_initialize(void) /** * Generate suitable 'write' data (this only affects differential override operations). * - * Note that \a local ID is no more modified by this call, all extra data are stored in its temp \a storage_id copy. */ + * Note that \a local ID is no more modified by this call, + * all extra data are stored in its temp \a storage_id copy. */ ID *BKE_override_static_operations_store_start(Main *bmain, OverrideStaticStorage *override_storage, ID *local) @@ -759,11 +766,13 @@ ID *BKE_override_static_operations_store_start(Main *bmain, TIMEIT_START_AVERAGED(BKE_override_operations_store_start); #endif - /* XXX TODO We may also want a specialized handling of things here too, to avoid copying heavy never-overridable - * data (like Mesh geometry etc.)? And also maybe avoid lib refcounting completely (shallow copy...). */ - /* This would imply change in handling of usercout all over RNA (and possibly all over Blender code). - * Not impossible to do, but would rather see first is extra useless usual user handling is actually - * a (performances) issue here, before doing it. */ + /* XXX TODO We may also want a specialized handling of things here too, to avoid copying heavy + * never-overridable data (like Mesh geometry etc.)? And also maybe avoid lib reference-counting + * completely (shallow copy...). */ + /* This would imply change in handling of user-count all over RNA + * (and possibly all over Blender code). + * Not impossible to do, but would rather see first is extra useless usual user handling is + * actually a (performances) issue here, before doing it. */ BKE_id_copy((Main *)override_storage, local, &storage_id); if (storage_id != NULL) { @@ -793,19 +802,18 @@ void BKE_override_static_operations_store_end(OverrideStaticStorage *UNUSED(over { BLI_assert(local->override_static != NULL); - /* 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...). */ + /* 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_static->storage = NULL; } void BKE_override_static_operations_store_finalize(OverrideStaticStorage *override_storage) { - /* We cannot just call BKE_main_free(override_storage), not until we have option to make 'ghost' copies of IDs - * without increasing usercount of used data-blocks... */ + /* We cannot just call BKE_main_free(override_storage), not until we have option to make 'ghost' + * copies of IDs without increasing usercount of used data-blocks. */ ID *id; - FOREACH_MAIN_ID_BEGIN(override_storage, id) - { + FOREACH_MAIN_ID_BEGIN (override_storage, id) { BKE_id_free_ex(override_storage, id, LIB_ID_FREE_NO_UI_USER, true); } FOREACH_MAIN_ID_END; diff --git a/source/blender/blenkernel/intern/library_query.c b/source/blender/blenkernel/intern/library_query.c index 7152c9786fb..d0515d8783d 100644 --- a/source/blender/blenkernel/intern/library_query.c +++ b/source/blender/blenkernel/intern/library_query.c @@ -161,8 +161,9 @@ static void library_foreach_idproperty_ID_link(LibraryForeachIDData *data, IDProperty *prop, int flag) { - if (!prop) + if (!prop) { return; + } switch (prop->type) { case IDP_GROUP: { @@ -351,8 +352,8 @@ static void library_foreach_ID_as_subdata_link(ID **id_pp, BLI_assert(id == *id_pp); if (flag & IDWALK_RECURSE) { - /* Defer handling into main loop, recursively calling BKE_library_foreach_ID_link in IDWALK_RECURSE case is - * troublesome, see T49553. */ + /* Defer handling into main loop, recursively calling BKE_library_foreach_ID_link in + * IDWALK_RECURSE case is troublesome, see T49553. */ if (BLI_gset_add(data->ids_handled, id)) { BLI_LINKSTACK_PUSH(data->ids_todo, id); } @@ -401,8 +402,8 @@ static void library_foreach_ID_link(Main *bmain, /* inherit_data is non-NULL when this function is called for some sub-data ID * (like root nodetree of a material). - * In that case, we do not want to generate those 'generic flags' from our current sub-data ID (the node tree), - * but re-use those generated for the 'owner' ID (the material)... */ + * In that case, we do not want to generate those 'generic flags' from our current sub-data ID + * (the node tree), but re-use those generated for the 'owner' ID (the material). */ if (inherit_data == NULL) { data.cb_flag = ID_IS_LINKED(id) ? IDWALK_CB_INDIRECT_USAGE : 0; /* When an ID is not in Main database, it should never refcount IDs it is using. @@ -415,10 +416,11 @@ static void library_foreach_ID_link(Main *bmain, } if (bmain != NULL && bmain->relations != NULL && (flag & IDWALK_READONLY)) { - /* Note that this is minor optimization, even in worst cases (like id being an object with lots of - * drivers and constraints and modifiers, or material etc. with huge node tree), - * but we might as well use it (Main->relations is always assumed valid, it's responsibility of code - * creating it to free it, especially if/when it starts modifying Main database). */ + /* Note that this is minor optimization, even in worst cases (like id being an object with + * lots of drivers and constraints and modifiers, or material etc. with huge node tree), + * but we might as well use it (Main->relations is always assumed valid, + * it's responsibility of code creating it to free it, + * especially if/when it starts modifying Main database). */ MainIDRelationsEntry *entry = BLI_ghash_lookup(bmain->relations->id_user_to_used, id); for (; entry != NULL; entry = entry->next) { FOREACH_CALLBACK_INVOKE_ID_PP(&data, entry->id_pointer, entry->usage_flag); @@ -593,8 +595,8 @@ static void library_foreach_ID_link(Main *bmain, CALLBACK_INVOKE(object->proxy_group, IDWALK_CB_NOP); /* Special case! - * Since this field is set/owned by 'user' of this ID (and not ID itself), it is only indirect usage - * if proxy object is linked... Twisted. */ + * Since this field is set/owned by 'user' of this ID (and not ID itself), + * it is only indirect usage if proxy object is linked... Twisted. */ if (object->proxy_from) { data.cb_flag = ID_IS_LINKED(object->proxy_from) ? IDWALK_CB_INDIRECT_USAGE : 0; } @@ -1017,7 +1019,8 @@ static void library_foreach_ID_link(Main *bmain, bScreen *screen = BKE_workspace_layout_screen_get(layout); /* CALLBACK_INVOKE expects an actual pointer, not a variable holding the pointer. - * However we can't access layout->screen here since we are outside the workspace project. */ + * However we can't access layout->screen here + * since we are outside the workspace project. */ CALLBACK_INVOKE(screen, IDWALK_CB_USER); /* allow callback to set a different screen */ BKE_workspace_layout_screen_set(layout, screen); @@ -1095,11 +1098,12 @@ void BKE_library_update_ID_link_user(ID *id_dst, ID *id_src, const int cb_flag) /** * Say whether given \a id_type_owner can use (in any way) a datablock of \a id_type_used. * - * This is a 'simplified' abstract version of #BKE_library_foreach_ID_link() above, quite useful to reduce - * useless iterations in some cases. + * This is a 'simplified' abstract version of #BKE_library_foreach_ID_link() above, + * quite useful to reduce* useless iterations in some cases. */ -/* XXX This has to be fully rethink, basing check on ID type is not really working anymore (and even worth once - * IDProps will support ID pointers), we'll have to do some quick checks on IDs themselves... */ +/* XXX This has to be fully rethink, basing check on ID type is not really working anymore + * (and even worth once IDProps will support ID pointers), + * we'll have to do some quick checks on IDs themselves... */ bool BKE_library_id_can_use_idtype(ID *id_owner, const short id_type_used) { /* any type of ID can be used in custom props. */ @@ -1119,7 +1123,8 @@ bool BKE_library_id_can_use_idtype(ID *id_owner, const short id_type_used) } if (BKE_animdata_from_id(id_owner)) { - return true; /* AnimationData can use virtually any kind of datablocks, through drivers especially. */ + /* AnimationData can use virtually any kind of datablocks, through drivers especially. */ + return true; } switch ((ID_Type)id_type_owner) { @@ -1240,10 +1245,16 @@ static int foreach_libblock_id_users_callback(void *user_data, if (*id_p == iter->id) { #if 0 - printf("%s uses %s (refcounted: %d, userone: %d, used_one: %d, used_one_active: %d, indirect_usage: %d)\n", - iter->curr_id->name, iter->id->name, (cb_flag & IDWALK_USER) ? 1 : 0, (cb_flag & IDWALK_USER_ONE) ? 1 : 0, - (iter->id->tag & LIB_TAG_EXTRAUSER) ? 1 : 0, (iter->id->tag & LIB_TAG_EXTRAUSER_SET) ? 1 : 0, - (cb_flag & IDWALK_INDIRECT_USAGE) ? 1 : 0); + printf( + "%s uses %s (refcounted: %d, userone: %d, used_one: %d, used_one_active: %d, " + "indirect_usage: %d)\n", + iter->curr_id->name, + iter->id->name, + (cb_flag & IDWALK_USER) ? 1 : 0, + (cb_flag & IDWALK_USER_ONE) ? 1 : 0, + (iter->id->tag & LIB_TAG_EXTRAUSER) ? 1 : 0, + (iter->id->tag & LIB_TAG_EXTRAUSER_SET) ? 1 : 0, + (cb_flag & IDWALK_INDIRECT_USAGE) ? 1 : 0); #endif if (cb_flag & IDWALK_CB_INDIRECT_USAGE) { iter->count_indirect++; @@ -1260,8 +1271,8 @@ static int foreach_libblock_id_users_callback(void *user_data, /** * Return the number of times given \a id_user uses/references \a id_used. * - * \note This only checks for pointer references of an ID, shallow usages (like e.g. by RNA paths, as done - * for FCurves) are not detected at all. + * \note This only checks for pointer references of an ID, shallow usages + * (like e.g. by RNA paths, as done for FCurves) are not detected at all. * * \param id_user: the ID which is supposed to use (reference) \a id_used. * \param id_used: the ID which is supposed to be used (referenced) by \a id_user. @@ -1332,7 +1343,8 @@ bool BKE_library_ID_is_indirectly_used(Main *bmain, void *idv) } /** - * Combine #BKE_library_ID_is_locally_used() and #BKE_library_ID_is_indirectly_used() in a single call. + * Combine #BKE_library_ID_is_locally_used() and #BKE_library_ID_is_indirectly_used() + * in a single call. */ void BKE_library_ID_test_usages(Main *bmain, void *idv, bool *is_used_local, bool *is_used_linked) { @@ -1383,7 +1395,8 @@ static int foreach_libblock_used_linked_data_tag_clear_cb(void *user_data, return IDWALK_RET_NOP; } - /* If checked id is used by an assumed used ID, then it is also used and not part of any linked archipelago. */ + /* If checked id is used by an assumed used ID, + * then it is also used and not part of any linked archipelago. */ if (!(self_id->tag & LIB_TAG_DOIT) && ((*id_p)->tag & LIB_TAG_DOIT)) { (*id_p)->tag &= ~LIB_TAG_DOIT; *is_changed = true; @@ -1394,20 +1407,20 @@ static int foreach_libblock_used_linked_data_tag_clear_cb(void *user_data, } /** - * Detect orphaned linked data blocks (i.e. linked data not used (directly or indirectly) in any way by any local data), - * including complex cases like 'linked archipelagoes', i.e. linked datablocks that use each other in loops, - * which prevents their deletion by 'basic' usage checks... + * Detect orphaned linked data blocks (i.e. linked data not used (directly or indirectly) + * in any way by any local data), including complex cases like 'linked archipelagoes', i.e. + * linked datablocks that use each other in loops, + * which prevents their deletion by 'basic' usage checks. * - * \param do_init_tag: if \a true, all linked data are checked, if \a false, only linked datablocks already tagged with - * LIB_TAG_DOIT are checked. + * \param do_init_tag: if \a true, all linked data are checked, if \a false, + * only linked datablocks already tagged with #LIB_TAG_DOIT are checked. */ void BKE_library_unused_linked_data_set_tag(Main *bmain, const bool do_init_tag) { ID *id; if (do_init_tag) { - FOREACH_MAIN_ID_BEGIN(bmain, id) - { + FOREACH_MAIN_ID_BEGIN (bmain, id) { if (id->lib && (id->tag & LIB_TAG_INDIRECT) != 0) { id->tag |= LIB_TAG_DOIT; } @@ -1420,8 +1433,7 @@ void BKE_library_unused_linked_data_set_tag(Main *bmain, const bool do_init_tag) for (bool do_loop = true; do_loop;) { do_loop = false; - FOREACH_MAIN_ID_BEGIN(bmain, id) - { + FOREACH_MAIN_ID_BEGIN (bmain, id) { /* We only want to check that ID if it is currently known as used... */ if ((id->tag & LIB_TAG_DOIT) == 0) { BKE_library_foreach_ID_link( @@ -1434,9 +1446,11 @@ void BKE_library_unused_linked_data_set_tag(Main *bmain, const bool do_init_tag) /** * Untag linked data blocks used by other untagged linked datablocks. - * Used to detect datablocks that we can forcefully make local (instead of copying them to later get rid of original): - * All datablocks we want to make local are tagged by caller, after this function has ran caller knows datablocks still - * tagged can directly be made local, since they are only used by other datablocks that will also be made fully local. + * Used to detect datablocks that we can forcefully make local + * (instead of copying them to later get rid of original): + * All datablocks we want to make local are tagged by caller, + * after this function has ran caller knows datablocks still tagged can directly be made local, + * since they are only used by other datablocks that will also be made fully local. */ void BKE_library_indirectly_used_data_tag_clear(Main *bmain) { diff --git a/source/blender/blenkernel/intern/library_remap.c b/source/blender/blenkernel/intern/library_remap.c index 9b6de945db8..3b6f11935d1 100644 --- a/source/blender/blenkernel/intern/library_remap.c +++ b/source/blender/blenkernel/intern/library_remap.c @@ -145,14 +145,18 @@ typedef struct IDRemap { Main *bmain; /* Only used to trigger depsgraph updates in the right bmain. */ ID *old_id; ID *new_id; - ID *id; /* The ID in which we are replacing old_id by new_id usages. */ + /** The ID in which we are replacing old_id by new_id usages. */ + ID *id; short flag; /* 'Output' data. */ short status; - int skipped_direct; /* Number of direct usecases that could not be remapped (e.g.: obdata when in edit mode). */ - int skipped_indirect; /* Number of indirect usecases that could not be remapped. */ - int skipped_refcounted; /* Number of skipped usecases that refcount the datablock. */ + /** Number of direct usecases that could not be remapped (e.g.: obdata when in edit mode). */ + int skipped_direct; + /** Number of indirect usecases that could not be remapped. */ + int skipped_indirect; + /** Number of skipped usecases that refcount the datablock. */ + int skipped_refcounted; } IDRemap; /* IDRemap->flag enums defined in BKE_library.h */ @@ -181,7 +185,8 @@ static int foreach_libblock_remap_callback(void *user_data, ID *id_self, ID **id } if (*id_p && (*id_p == old_id)) { - /* Better remap to NULL than not remapping at all, then we can handle it as a regular remap-to-NULL case... */ + /* Better remap to NULL than not remapping at all, + * then we can handle it as a regular remap-to-NULL case. */ if ((cb_flag & IDWALK_CB_NEVER_SELF) && (new_id == id_self)) { new_id = NULL; } @@ -190,8 +195,8 @@ static int foreach_libblock_remap_callback(void *user_data, ID *id_self, ID **id const bool is_indirect = (cb_flag & IDWALK_CB_INDIRECT_USAGE) != 0; const bool skip_indirect = (id_remap_data->flag & ID_REMAP_SKIP_INDIRECT_USAGE) != 0; /* Note: proxy usage implies LIB_TAG_EXTERN, so on this aspect it is direct, - * on the other hand since they get reset to lib data on file open/reload it is indirect too... - * Edit Mode is also a 'skip direct' case. */ + * on the other hand since they get reset to lib data on file open/reload it is indirect too. + * Edit Mode is also a 'skip direct' case. */ const bool is_obj = (GS(id->name) == ID_OB); const bool is_obj_proxy = (is_obj && (((Object *)id)->proxy || ((Object *)id)->proxy_group)); const bool is_obj_editmode = (is_obj && BKE_object_is_in_editmode((Object *)id)); @@ -276,8 +281,8 @@ static int foreach_libblock_remap_callback(void *user_data, ID *id_self, ID **id } else if (cb_flag & IDWALK_CB_USER_ONE) { id_us_ensure_real(new_id); - /* We cannot affect old_id->us directly, LIB_TAG_EXTRAUSER(_SET) are assumed to be set as needed, - * that extra user is processed in final handling... */ + /* We cannot affect old_id->us directly, LIB_TAG_EXTRAUSER(_SET) + * are assumed to be set as needed, that extra user is processed in final handling. */ } if (!is_indirect || is_obj_proxy) { id_remap_data->status |= ID_REMAP_IS_LINKED_DIRECT; @@ -296,15 +301,16 @@ static void libblock_remap_data_preprocess(IDRemap *r_id_remap_data) if (!old_id || GS(old_id->name) == ID_AR) { Object *ob = (Object *)r_id_remap_data->id; /* Object's pose holds reference to armature bones... sic */ - /* Note that in theory, we should have to bother about linked/non-linked/never-null/etc. flags/states. - * Fortunately, this is just a tag, so we can accept to 'over-tag' a bit for pose recalc, and avoid - * another complex and risky condition nightmare like the one we have in + /* Note that in theory, we should have to bother about + * linked/non-linked/never-null/etc. flags/states. + * Fortunately, this is just a tag, so we can accept to 'over-tag' a bit for pose recalc, + * and avoid another complex and risky condition nightmare like the one we have in * foreach_libblock_remap_callback()... */ if (ob->pose && (!old_id || ob->data == old_id)) { BLI_assert(ob->type == OB_ARMATURE); ob->pose->flag |= POSE_RECALC; - /* We need to clear pose bone pointers immediately, things like undo writefile may be called - * before pose is actually recomputed, can lead to segfault... */ + /* We need to clear pose bone pointers immediately, things like undo writefile may be + * called before pose is actually recomputed, can lead to segfault... */ BKE_pose_clear_pointers(ob->pose); } } @@ -315,7 +321,10 @@ static void libblock_remap_data_preprocess(IDRemap *r_id_remap_data) } } -/* Can be called with both old_ob and new_ob being NULL, this means we have to check whole Main database then. */ +/** + * Can be called with both old_ob and new_ob being NULL, + * this means we have to check whole Main database then. + */ static void libblock_remap_data_postprocess_object_update(Main *bmain, Object *old_ob, Object *new_ob) @@ -354,8 +363,8 @@ static void libblock_remap_data_postprocess_collection_update(Main *bmain, { if (new_collection == NULL) { /* XXX Complex cases can lead to NULL pointers in other collections than old_collection, - * and BKE_main_collection_sync_remap() does not tolerate any of those, so for now always check whole - * existing collections for NULL pointers. + * and BKE_main_collection_sync_remap() does not tolerate any of those, so for now always check + * whole existing collections for NULL pointers. * I'd consider optimizing that whole collection remapping process a TODO for later. */ BKE_collections_child_remove_nulls(bmain, NULL /*old_collection*/); } @@ -383,15 +392,8 @@ static void libblock_remap_data_postprocess_obdata_relink(Main *bmain, Object *o static void libblock_remap_data_postprocess_nodetree_update(Main *bmain, ID *new_id) { - /* Verify all nodetree user nodes. */ - ntreeVerifyNodes(bmain, new_id); - - /* Update node trees as necessary. */ - FOREACH_NODETREE_BEGIN (bmain, ntree, id) { - /* make an update call for the tree */ - ntreeUpdateTree(bmain, ntree); - } - FOREACH_NODETREE_END; + /* Update all group nodes using a node group. */ + ntreeUpdateAllUsers(bmain, new_id); } /** @@ -399,18 +401,22 @@ static void libblock_remap_data_postprocess_nodetree_update(Main *bmain, ID *new * * Behavior differs depending on whether given \a id is NULL or not: * - \a id NULL: \a old_id must be non-NULL, \a new_id may be NULL (unlinking \a old_id) or not - * (remapping \a old_id to \a new_id). The whole \a bmain database is checked, and all pointers to \a old_id + * (remapping \a old_id to \a new_id). + * The whole \a bmain database is checked, and all pointers to \a old_id * are remapped to \a new_id. * - \a id is non-NULL: - * + If \a old_id is NULL, \a new_id must also be NULL, and all ID pointers from \a id are cleared (i.e. \a id - * does not references any other datablock anymore). + * + If \a old_id is NULL, \a new_id must also be NULL, + * and all ID pointers from \a id are cleared + * (i.e. \a id does not references any other datablock anymore). * + If \a old_id is non-NULL, behavior is as with a NULL \a id, but only within given \a id. * * \param bmain: the Main data storage to operate on (must never be NULL). - * \param id: the datablock to operate on (can be NULL, in which case we operate over all IDs from given bmain). + * \param id: the datablock to operate on + * (can be NULL, in which case we operate over all IDs from given bmain). * \param old_id: the datablock to dereference (may be NULL if \a id is non-NULL). * \param new_id: the new datablock to replace \a old_id references with (may be NULL). - * \param r_id_remap_data: if non-NULL, the IDRemap struct to use (uselful to retrieve info about remapping process). + * \param r_id_remap_data: if non-NULL, the IDRemap struct to use + * (uselful to retrieve info about remapping process). */ ATTR_NONNULL(1) static void libblock_remap_data( @@ -444,15 +450,15 @@ static void libblock_remap_data( NULL, id, foreach_libblock_remap_callback, (void *)r_id_remap_data, foreach_id_flags); } else { - /* Note that this is a very 'brute force' approach, maybe we could use some depsgraph to only process - * objects actually using given old_id... sounds rather unlikely currently, though, so this will do for now. */ + /* Note that this is a very 'brute force' approach, + * maybe we could use some depsgraph to only process objects actually using given old_id... + * sounds rather unlikely currently, though, so this will do for now. */ ID *id_curr; - FOREACH_MAIN_ID_BEGIN(bmain, id_curr) - { + FOREACH_MAIN_ID_BEGIN (bmain, id_curr) { if (BKE_library_id_can_use_idtype(id_curr, GS(old_id->name))) { - /* Note that we cannot skip indirect usages of old_id here (if requested), we still need to check it for - * the user count handling... + /* Note that we cannot skip indirect usages of old_id here (if requested), + * we still need to check it for the user count handling... * XXX No more true (except for debug usage of those skipping counters). */ r_id_remap_data->id = id_curr; libblock_remap_data_preprocess(r_id_remap_data); @@ -466,8 +472,9 @@ static void libblock_remap_data( FOREACH_MAIN_ID_END; } - /* XXX We may not want to always 'transfer' fakeuser from old to new id... Think for now it's desired behavior - * though, we can always add an option (flag) to control this later if needed. */ + /* XXX We may not want to always 'transfer' fakeuser from old to new id... + * Think for now it's desired behavior though, + * we can always add an option (flag) to control this later if needed. */ if (old_id && (old_id->flag & LIB_FAKEUSER)) { id_fake_user_clear(old_id); id_fake_user_set(new_id); @@ -512,7 +519,8 @@ void BKE_libblock_remap_locked(Main *bmain, void *old_idv, void *new_idv, const } /* We assume editors do not hold references to their IDs... This is false in some cases - * (Image is especially tricky here), editors' code is to handle refcount (id->us) itself then. */ + * (Image is especially tricky here), + * editors' code is to handle refcount (id->us) itself then. */ if (remap_editor_id_reference_cb) { remap_editor_id_reference_cb(old_id, new_id); } @@ -520,9 +528,9 @@ void BKE_libblock_remap_locked(Main *bmain, void *old_idv, void *new_idv, const skipped_direct = id_remap_data.skipped_direct; skipped_refcounted = id_remap_data.skipped_refcounted; - /* If old_id was used by some ugly 'user_one' stuff (like Image or Clip editors...), and user count has actually - * been incremented for that, we have to decrease once more its user count... unless we had to skip - * some 'user_one' cases. */ + /* If old_id was used by some ugly 'user_one' stuff (like Image or Clip editors...), and user + * count has actually been incremented for that, we have to decrease once more its user count... + * unless we had to skip some 'user_one' cases. */ if ((old_id->tag & LIB_TAG_EXTRAUSER_SET) && !(id_remap_data.status & ID_REMAP_IS_USER_ONE_SKIPPED)) { id_us_clear_real(old_id); @@ -549,8 +557,8 @@ void BKE_libblock_remap_locked(Main *bmain, void *old_idv, void *new_idv, const } /* Some after-process updates. - * This is a bit ugly, but cannot see a way to avoid it. Maybe we should do a per-ID callback for this instead? - */ + * This is a bit ugly, but cannot see a way to avoid it. + * Maybe we should do a per-ID callback for this instead? */ switch (GS(old_id->name)) { case ID_OB: libblock_remap_data_postprocess_object_update(bmain, (Object *)old_id, (Object *)new_id); @@ -594,10 +602,11 @@ void BKE_libblock_remap(Main *bmain, void *old_idv, void *new_idv, const short r } /** - * Unlink given \a id from given \a bmain (does not touch to indirect, i.e. library, usages of the ID). + * Unlink given \a id from given \a bmain + * (does not touch to indirect, i.e. library, usages of the ID). * - * \param do_flag_never_null: If true, all IDs using \a idv in a 'non-NULL' way are flagged by \a LIB_TAG_DOIT flag - * (quite obviously, 'non-NULL' usages can never be unlinked by this function...). + * \param do_flag_never_null: If true, all IDs using \a idv in a 'non-NULL' way are flagged by + * #LIB_TAG_DOIT flag (quite obviously, 'non-NULL' usages can never be unlinked by this function). */ void BKE_libblock_unlink(Main *bmain, void *idv, @@ -652,7 +661,8 @@ void BKE_libblock_relink_ex( libblock_remap_data(bmain, id, old_id, new_id, remap_flags, NULL); /* Some after-process updates. - * This is a bit ugly, but cannot see a way to avoid it. Maybe we should do a per-ID callback for this instead? + * This is a bit ugly, but cannot see a way to avoid it. + * Maybe we should do a per-ID callback for this instead? */ switch (GS(id->name)) { case ID_SCE: { @@ -711,14 +721,18 @@ static int id_relink_to_newid_looper(void *UNUSED(user_data), return IDWALK_RET_NOP; } -/** Similar to libblock_relink_ex, but is remapping IDs to their newid value if non-NULL, in given \a id. +/** + * Similar to #libblock_relink_ex, + * but is remapping IDs to their newid value if non-NULL, in given \a id. * - * Very specific usage, not sure we'll keep it on the long run, currently only used in Object/Collection duplication code... + * Very specific usage, not sure we'll keep it on the long run, + * currently only used in Object/Collection duplication code... */ void BKE_libblock_relink_to_newid(ID *id) { - if (ID_IS_LINKED(id)) + if (ID_IS_LINKED(id)) { return; + } BKE_library_foreach_ID_link(NULL, id, id_relink_to_newid_looper, NULL, 0); } @@ -734,7 +748,8 @@ void BKE_libblock_free_data(ID *id, const bool do_id_user) BKE_override_static_free(&id->override_static); } - /* XXX TODO remove animdata handling from each type's freeing func, and do it here, like for copy! */ + /* XXX TODO remove animdata handling from each type's freeing func, + * and do it here, like for copy! */ } void BKE_libblock_free_datablock(ID *id, const int UNUSED(flag)) @@ -823,8 +838,9 @@ void BKE_libblock_free_datablock(ID *id, const int UNUSED(flag)) BKE_particlesettings_free((ParticleSettings *)id); break; case ID_WM: - if (free_windowmanager_cb) + if (free_windowmanager_cb) { free_windowmanager_cb(NULL, (wmWindowManager *)id); + } break; case ID_GD: BKE_gpencil_free((bGPdata *)id, true); @@ -860,13 +876,14 @@ void BKE_libblock_free_datablock(ID *id, const int UNUSED(flag)) * At that point, given id is assumed to not be used by any other data-block already * (might not be actually true, in case e.g. several inter-related IDs get freed together...). * However, they might still be using (referencing) other IDs, this code takes care of it if - * \a LIB_TAG_NO_USER_REFCOUNT is not defined. + * #LIB_TAG_NO_USER_REFCOUNT is not defined. * - * \param bmain: Main database containing the freed ID, can be NULL in case it's a temp ID outside of any Main. + * \param bmain: #Main database containing the freed #ID, + * can be NULL in case it's a temp ID outside of any #Main. * \param idv: Pointer to ID to be freed. * \param flag: Set of \a LIB_ID_FREE_... flags controlling/overriding usual freeing process, * 0 to get default safe behavior. - * \param use_flag_from_idtag: Still use freeing info flags from given ID datablock, + * \param use_flag_from_idtag: Still use freeing info flags from given #ID datablock, * even if some overriding ones are passed in \a flag parameter. */ void BKE_id_free_ex(Main *bmain, void *idv, int flag, const bool use_flag_from_idtag) @@ -957,7 +974,8 @@ void BKE_id_free_ex(Main *bmain, void *idv, int flag, const bool use_flag_from_i * * See #BKE_id_free_ex description for full details. * - * \param bmain: Main database containing the freed ID, can be NULL in case it's a temp ID outside of any Main. + * \param bmain: Main database containing the freed ID, + * can be NULL in case it's a temp ID outside of any Main. * \param idv: Pointer to ID to be freed. */ void BKE_id_free(Main *bmain, void *idv) @@ -966,7 +984,8 @@ void BKE_id_free(Main *bmain, void *idv) } /** - * Not really a freeing function by itself, it decrements usercount of given id, and only frees it if it reaches 0. + * Not really a freeing function by itself, + * it decrements usercount of given id, and only frees it if it reaches 0. */ void BKE_id_free_us(Main *bmain, void *idv) /* test users */ { @@ -974,12 +993,13 @@ void BKE_id_free_us(Main *bmain, void *idv) /* test users */ id_us_min(id); - /* XXX This is a temp (2.77) hack so that we keep same behavior as in 2.76 regarding collections when deleting an object. - * Since only 'user_one' usage of objects is collections, and only 'real user' usage of objects is scenes, - * removing that 'user_one' tag when there is no more real (scene) users of an object ensures it gets - * fully unlinked. + /* XXX This is a temp (2.77) hack so that we keep same behavior as in 2.76 regarding collections + * when deleting an object. Since only 'user_one' usage of objects is collections, + * and only 'real user' usage of objects is scenes, removing that 'user_one' tag when there + * is no more real (scene) users of an object ensures it gets fully unlinked. * But only for local objects, not linked ones! - * Otherwise, there is no real way to get rid of an object anymore - better handling of this is TODO. + * Otherwise, there is no real way to get rid of an object anymore - + * better handling of this is TODO. */ if ((GS(id->name) == ID_OB) && (id->us == 1) && (id->lib == NULL)) { id_us_clear_real(id); @@ -1036,8 +1056,9 @@ static void id_delete(Main *bmain, const bool do_tagged_deletion) if ((id->tag & tag) || (id->lib != NULL && (id->lib->id.tag & tag))) { BLI_remlink(lb, id); BLI_addtail(&tagged_deleted_ids, id); - /* Do not tag as no_main now, we want to unlink it first (lower-level ID management code - * has some specific handling of 'nom main' IDs that would be a problem in that case). */ + /* Do not tag as no_main now, we want to unlink it first (lower-level ID management + * code has some specific handling of 'nom main' + * IDs that would be a problem in that case). */ id->tag |= tag; keep_looping = true; } @@ -1049,24 +1070,28 @@ static void id_delete(Main *bmain, const bool do_tagged_deletion) } for (id = last_remapped_id->next; id; id = id->next) { /* Will tag 'never NULL' users of this ID too. - * Note that we cannot use BKE_libblock_unlink() here, since it would ignore indirect (and proxy!) + * Note that we cannot use BKE_libblock_unlink() here, + * since it would ignore indirect (and proxy!) * links, this can lead to nasty crashing here in second, actual deleting loop. * Also, this will also flag users of deleted data that cannot be unlinked * (object using deleted obdata, etc.), so that they also get deleted. */ BKE_libblock_remap_locked( bmain, id, NULL, ID_REMAP_FLAG_NEVER_NULL_USAGE | ID_REMAP_FORCE_NEVER_NULL_USAGE); - /* Since we removed ID from Main, we also need to unlink its own other IDs usages ourself. */ + /* Since we removed ID from Main, + * we also need to unlink its own other IDs usages ourself. */ BKE_libblock_relink_ex(bmain, id, NULL, NULL, true); /* Now we can safely mark that ID as not being in Main database anymore. */ id->tag |= LIB_TAG_NO_MAIN; - /* This is needed because we may not have remapped usages of that ID by other deleted ones. */ - // id->us = 0; /* Is it actually? */ + /* This is needed because we may not have remapped usages + * of that ID by other deleted ones. */ + // id->us = 0; /* Is it actually? */ } } } else { /* First tag all datablocks directly from target lib. - * Note that we go forward here, since we want to check dependencies before users (e.g. meshes before objects). + * Note that we go forward here, since we want to check dependencies before users + * (e.g. meshes before objects). * Avoids to have to loop twice. */ for (i = 0; i < base_count; i++) { ListBase *lb = lbarray[i]; @@ -1079,8 +1104,9 @@ static void id_delete(Main *bmain, const bool do_tagged_deletion) id->tag |= tag; /* Will tag 'never NULL' users of this ID too. - * Note that we cannot use BKE_libblock_unlink() here, since it would ignore indirect (and proxy!) - * links, this can lead to nasty crashing here in second, actual deleting loop. + * Note that we cannot use BKE_libblock_unlink() here, since it would ignore indirect + * (and proxy!) links, this can lead to nasty crashing here in second, + * actual deleting loop. * Also, this will also flag users of deleted data that cannot be unlinked * (object using deleted obdata, etc.), so that they also get deleted. */ BKE_libblock_remap_locked( @@ -1091,8 +1117,9 @@ static void id_delete(Main *bmain, const bool do_tagged_deletion) } BKE_main_unlock(bmain); - /* In usual reversed order, such that all usage of a given ID, even 'never NULL' ones, have been already cleared - * when we reach it (e.g. Objects being processed before meshes, they'll have already released their 'reference' + /* In usual reversed order, such that all usage of a given ID, even 'never NULL' ones, + * have been already cleared when we reach it + * (e.g. Objects being processed before meshes, they'll have already released their 'reference' * over meshes when we come to freeing obdata). */ for (i = do_tagged_deletion ? 1 : base_count; i--;) { ListBase *lb = lbarray[i]; diff --git a/source/blender/blenkernel/intern/light.c b/source/blender/blenkernel/intern/light.c index f0943bc2749..05b2eb82daf 100644 --- a/source/blender/blenkernel/intern/light.c +++ b/source/blender/blenkernel/intern/light.c @@ -96,8 +96,10 @@ Light *BKE_light_add(Main *bmain, const char *name) } /** - * Only copy internal data of Light ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of Light ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * @@ -144,8 +146,9 @@ Light *BKE_light_localize(Light *la) lan->curfalloff = curvemapping_copy(la->curfalloff); - if (la->nodetree) + if (la->nodetree) { lan->nodetree = ntreeLocalize(la->nodetree); + } lan->preview = NULL; diff --git a/source/blender/blenkernel/intern/lightprobe.c b/source/blender/blenkernel/intern/lightprobe.c index 6b1951498cc..5e6d298adbf 100644 --- a/source/blender/blenkernel/intern/lightprobe.c +++ b/source/blender/blenkernel/intern/lightprobe.c @@ -60,8 +60,10 @@ void *BKE_lightprobe_add(Main *bmain, const char *name) } /** - * Only copy internal data of LightProbe ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of LightProbe ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * diff --git a/source/blender/blenkernel/intern/linestyle.c b/source/blender/blenkernel/intern/linestyle.c index a0cfe7dfe41..31e6d2e89e5 100644 --- a/source/blender/blenkernel/intern/linestyle.c +++ b/source/blender/blenkernel/intern/linestyle.c @@ -136,19 +136,25 @@ void BKE_linestyle_free(FreestyleLineStyle *linestyle) linestyle->nodetree = NULL; } - while ((m = (LineStyleModifier *)linestyle->color_modifiers.first)) + while ((m = (LineStyleModifier *)linestyle->color_modifiers.first)) { BKE_linestyle_color_modifier_remove(linestyle, m); - while ((m = (LineStyleModifier *)linestyle->alpha_modifiers.first)) + } + while ((m = (LineStyleModifier *)linestyle->alpha_modifiers.first)) { BKE_linestyle_alpha_modifier_remove(linestyle, m); - while ((m = (LineStyleModifier *)linestyle->thickness_modifiers.first)) + } + while ((m = (LineStyleModifier *)linestyle->thickness_modifiers.first)) { BKE_linestyle_thickness_modifier_remove(linestyle, m); - while ((m = (LineStyleModifier *)linestyle->geometry_modifiers.first)) + } + while ((m = (LineStyleModifier *)linestyle->geometry_modifiers.first)) { BKE_linestyle_geometry_modifier_remove(linestyle, m); + } } /** - * Only copy internal data of Linestyle ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of Linestyle ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * @@ -426,8 +432,9 @@ LineStyleModifier *BKE_linestyle_color_modifier_copy(FreestyleLineStyle *linesty int BKE_linestyle_color_modifier_remove(FreestyleLineStyle *linestyle, LineStyleModifier *m) { - if (BLI_findindex(&linestyle->color_modifiers, m) == -1) + if (BLI_findindex(&linestyle->color_modifiers, m) == -1) { return -1; + } switch (m->type) { case LS_MODIFIER_ALONG_STROKE: MEM_freeN(((LineStyleColorModifier_AlongStroke *)m)->color_ramp); @@ -601,8 +608,9 @@ LineStyleModifier *BKE_linestyle_alpha_modifier_copy(FreestyleLineStyle *linesty m; LineStyleAlphaModifier_DistanceFromObject *q = (LineStyleAlphaModifier_DistanceFromObject *) new_m; - if (p->target) + if (p->target) { id_us_plus(&p->target->id); + } q->target = p->target; q->curve = curvemapping_copy(p->curve); q->flags = p->flags; @@ -663,8 +671,9 @@ LineStyleModifier *BKE_linestyle_alpha_modifier_copy(FreestyleLineStyle *linesty int BKE_linestyle_alpha_modifier_remove(FreestyleLineStyle *linestyle, LineStyleModifier *m) { - if (BLI_findindex(&linestyle->alpha_modifiers, m) == -1) + if (BLI_findindex(&linestyle->alpha_modifiers, m) == -1) { return -1; + } switch (m->type) { case LS_MODIFIER_ALONG_STROKE: curvemapping_free(((LineStyleAlphaModifier_AlongStroke *)m)->curve); @@ -835,8 +844,9 @@ LineStyleModifier *BKE_linestyle_thickness_modifier_copy(FreestyleLineStyle *lin LineStyleModifier *new_m; new_m = alloc_thickness_modifier(m->name, m->type); - if (!new_m) + if (!new_m) { return NULL; + } new_m->influence = m->influence; new_m->flags = m->flags; new_m->blend = m->blend; @@ -950,8 +960,9 @@ LineStyleModifier *BKE_linestyle_thickness_modifier_copy(FreestyleLineStyle *lin int BKE_linestyle_thickness_modifier_remove(FreestyleLineStyle *linestyle, LineStyleModifier *m) { - if (BLI_findindex(&linestyle->thickness_modifiers, m) == -1) + if (BLI_findindex(&linestyle->thickness_modifiers, m) == -1) { return -1; + } switch (m->type) { case LS_MODIFIER_ALONG_STROKE: curvemapping_free(((LineStyleThicknessModifier_AlongStroke *)m)->curve); @@ -1290,8 +1301,9 @@ LineStyleModifier *BKE_linestyle_geometry_modifier_copy(FreestyleLineStyle *line int BKE_linestyle_geometry_modifier_remove(FreestyleLineStyle *linestyle, LineStyleModifier *m) { - if (BLI_findindex(&linestyle->geometry_modifiers, m) == -1) + if (BLI_findindex(&linestyle->geometry_modifiers, m) == -1) { return -1; + } BLI_freelinkN(&linestyle->geometry_modifiers, m); return 0; } @@ -1364,36 +1376,44 @@ char *BKE_linestyle_path_to_color_ramp(FreestyleLineStyle *linestyle, ColorBand for (m = (LineStyleModifier *)linestyle->color_modifiers.first; m; m = m->next) { switch (m->type) { case LS_MODIFIER_ALONG_STROKE: - if (color_ramp == ((LineStyleColorModifier_AlongStroke *)m)->color_ramp) + if (color_ramp == ((LineStyleColorModifier_AlongStroke *)m)->color_ramp) { found = true; + } break; case LS_MODIFIER_DISTANCE_FROM_CAMERA: - if (color_ramp == ((LineStyleColorModifier_DistanceFromCamera *)m)->color_ramp) + if (color_ramp == ((LineStyleColorModifier_DistanceFromCamera *)m)->color_ramp) { found = true; + } break; case LS_MODIFIER_DISTANCE_FROM_OBJECT: - if (color_ramp == ((LineStyleColorModifier_DistanceFromObject *)m)->color_ramp) + if (color_ramp == ((LineStyleColorModifier_DistanceFromObject *)m)->color_ramp) { found = true; + } break; case LS_MODIFIER_MATERIAL: - if (color_ramp == ((LineStyleColorModifier_Material *)m)->color_ramp) + if (color_ramp == ((LineStyleColorModifier_Material *)m)->color_ramp) { found = true; + } break; case LS_MODIFIER_TANGENT: - if (color_ramp == ((LineStyleColorModifier_Tangent *)m)->color_ramp) + if (color_ramp == ((LineStyleColorModifier_Tangent *)m)->color_ramp) { found = true; + } break; case LS_MODIFIER_NOISE: - if (color_ramp == ((LineStyleColorModifier_Noise *)m)->color_ramp) + if (color_ramp == ((LineStyleColorModifier_Noise *)m)->color_ramp) { found = true; + } break; case LS_MODIFIER_CREASE_ANGLE: - if (color_ramp == ((LineStyleColorModifier_CreaseAngle *)m)->color_ramp) + if (color_ramp == ((LineStyleColorModifier_CreaseAngle *)m)->color_ramp) { found = true; + } break; case LS_MODIFIER_CURVATURE_3D: - if (color_ramp == ((LineStyleColorModifier_Curvature_3D *)m)->color_ramp) + if (color_ramp == ((LineStyleColorModifier_Curvature_3D *)m)->color_ramp) { found = true; + } break; } diff --git a/source/blender/blenkernel/intern/main.c b/source/blender/blenkernel/intern/main.c index ef196430da7..e50e37c5428 100644 --- a/source/blender/blenkernel/intern/main.c +++ b/source/blender/blenkernel/intern/main.c @@ -56,7 +56,8 @@ void BKE_main_free(Main *mainvar) ListBase *lbarray[MAX_LIBARRAY]; int a; - /* Since we are removing whole main, no need to bother 'properly' (and slowly) removing each ID from it. */ + /* Since we are removing whole main, no need to bother 'properly' + * (and slowly) removing each ID from it. */ const int free_flag = (LIB_ID_FREE_NO_MAIN | LIB_ID_FREE_NO_UI_USER | LIB_ID_FREE_NO_USER_REFCOUNT | LIB_ID_FREE_NO_DEG_TAG); @@ -260,8 +261,7 @@ void BKE_main_relations_create(Main *bmain) sizeof(MainIDRelationsEntry), 128, 128, BLI_MEMPOOL_NOP); ID *id; - FOREACH_MAIN_ID_BEGIN(bmain, id) - { + FOREACH_MAIN_ID_BEGIN (bmain, id) { BKE_library_foreach_ID_link( NULL, id, main_relations_create_idlink_cb, bmain->relations, IDWALK_READONLY); } @@ -286,7 +286,8 @@ void BKE_main_relations_free(Main *bmain) /** * Create a GSet storing all IDs present in given \a bmain, by their pointers. * - * \param gset: If not NULL, given GSet will be extended with IDs from given \a bmain, instead of creating a new one. + * \param gset: If not NULL, given GSet will be extended with IDs from given \a bmain, + * instead of creating a new one. */ GSet *BKE_main_gset_create(Main *bmain, GSet *gset) { @@ -295,8 +296,7 @@ GSet *BKE_main_gset_create(Main *bmain, GSet *gset) } ID *id; - FOREACH_MAIN_ID_BEGIN(bmain, id) - { + FOREACH_MAIN_ID_BEGIN (bmain, id) { BLI_gset_add(gset, id); } FOREACH_MAIN_ID_END; @@ -350,8 +350,8 @@ ImBuf *BKE_main_thumbnail_to_imbuf(Main *bmain, BlendThumbnail *data) } if (data) { - /* Note: we cannot use IMB_allocFromBuffer(), since it tries to dupalloc passed buffer, which will fail - * here (we do not want to pass the first two ints!). */ + /* Note: we cannot use IMB_allocFromBuffer(), since it tries to dupalloc passed buffer, + * which will fail here (we do not want to pass the first two ints!). */ img = IMB_allocImBuf( (unsigned int)data->width, (unsigned int)data->height, 32, IB_rect | IB_metadata); memcpy(img->rect, data->rect, BLEN_THUMB_MEMSIZE(data->width, data->height) - sizeof(*data)); @@ -383,7 +383,8 @@ const char *BKE_main_blendfile_path(const Main *bmain) /** * Return filepath of global main #G_MAIN. * - * \warning Usage is not recommended, you should always try to get a valid Main pointer from context... + * \warning Usage is not recommended, + * you should always try to get a valid Main pointer from context... */ const char *BKE_main_blendfile_path_from_global(void) { diff --git a/source/blender/blenkernel/intern/mask.c b/source/blender/blenkernel/intern/mask.c index e307ad6cac8..9a9b3757ef2 100644 --- a/source/blender/blenkernel/intern/mask.c +++ b/source/blender/blenkernel/intern/mask.c @@ -142,10 +142,12 @@ MaskLayer *BKE_mask_layer_new(Mask *mask, const char *name) { MaskLayer *masklay = MEM_callocN(sizeof(MaskLayer), __func__); - if (name && name[0]) + if (name && name[0]) { BLI_strncpy(masklay->name, name, sizeof(masklay->name)); - else + } + else { strcpy(masklay->name, "MaskLayer"); + } BLI_addtail(&mask->masklayers, masklay); @@ -178,8 +180,9 @@ void BKE_mask_layer_remove(Mask *mask, MaskLayer *masklay) mask->masklay_tot--; - if (mask->masklay_act >= mask->masklay_tot) + if (mask->masklay_act >= mask->masklay_tot) { mask->masklay_act = mask->masklay_tot - 1; + } } void BKE_mask_layer_unique_name(Mask *mask, MaskLayer *masklay) @@ -270,7 +273,10 @@ MaskSpline *BKE_mask_spline_add(MaskLayer *masklay) spline->tot_point = 1; /* cyclic shapes are more usually used */ - // spline->flag |= MASK_SPLINE_CYCLIC; // disable because its not so nice for drawing. could be done differently + /* Disable because its not so nice for drawing. could be done differently. */ +#if 0 + spline->flag |= MASK_SPLINE_CYCLIC; +#endif spline->weight_interp = MASK_SPLINE_INTERP_EASE; @@ -399,8 +405,9 @@ float BKE_mask_spline_project_co(MaskSpline *spline, if (len_squared_v2(v1) > proj_eps_sq) { ang1 = angle_v2v2(v1, n1); - if (ang1 > (float)M_PI / 2.0f) + if (ang1 > (float)M_PI / 2.0f) { ang1 = (float)M_PI - ang1; + } if (ang < 0.0f || ang1 < ang) { ang = ang1; @@ -424,8 +431,9 @@ float BKE_mask_spline_project_co(MaskSpline *spline, if (len_squared_v2(v2) > proj_eps_sq) { ang2 = angle_v2v2(v2, n2); - if (ang2 > (float)M_PI / 2.0f) + if (ang2 > (float)M_PI / 2.0f) { ang2 = (float)M_PI - ang2; + } if (ang2 < ang) { ang = ang2; @@ -728,10 +736,12 @@ MaskSplinePointUW *BKE_mask_point_sort_uw(MaskSplinePoint *point, MaskSplinePoin void BKE_mask_point_add_uw(MaskSplinePoint *point, float u, float w) { - if (!point->uw) + if (!point->uw) { point->uw = MEM_mallocN(sizeof(*point->uw), "mask point uw"); - else + } + else { point->uw = MEM_reallocN(point->uw, (point->tot_uw + 1) * sizeof(*point->uw)); + } point->uw[point->tot_uw].u = u; point->uw[point->tot_uw].w = w; @@ -816,10 +826,12 @@ Mask *BKE_mask_new(Main *bmain, const char *name) Mask *mask; char mask_name[MAX_ID_NAME - 2]; - if (name && name[0]) + if (name && name[0]) { BLI_strncpy(mask_name, name, sizeof(mask_name)); - else + } + else { strcpy(mask_name, "Mask"); + } mask = mask_alloc(bmain, mask_name); @@ -854,8 +866,10 @@ Mask *BKE_mask_copy_nolib(Mask *mask) } /** - * Only copy internal data of Mask ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of Mask ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * @@ -889,8 +903,9 @@ void BKE_mask_make_local(Main *bmain, Mask *mask, const bool lib_local) void BKE_mask_point_free(MaskSplinePoint *point) { - if (point->uw) + if (point->uw) { MEM_freeN(point->uw); + } } void BKE_mask_spline_free(MaskSpline *spline) @@ -940,8 +955,9 @@ static MaskSplinePoint *mask_spline_points_copy(const MaskSplinePoint *points, i for (i = 0; i < tot_point; i++) { MaskSplinePoint *point = &npoints[i]; - if (point->uw) + if (point->uw) { point->uw = MEM_dupallocN(point->uw); + } } return npoints; @@ -1212,13 +1228,15 @@ static void mask_calc_point_handle(MaskSplinePoint *point, { BezTriple *bezt = &point->bezt; BezTriple *bezt_prev = NULL, *bezt_next = NULL; - //int handle_type = bezt->h1; + // int handle_type = bezt->h1; - if (point_prev) + if (point_prev) { bezt_prev = &point_prev->bezt; + } - if (point_next) + if (point_next) { bezt_next = &point_next->bezt; + } #if 1 if (bezt_prev || bezt_next) { @@ -1699,12 +1717,15 @@ static int mask_layer_shape_sort_cb(const void *masklay_shape_a_ptr, const MaskLayerShape *masklay_shape_a = masklay_shape_a_ptr; const MaskLayerShape *masklay_shape_b = masklay_shape_b_ptr; - if (masklay_shape_a->frame < masklay_shape_b->frame) + if (masklay_shape_a->frame < masklay_shape_b->frame) { return -1; - else if (masklay_shape_a->frame > masklay_shape_b->frame) + } + else if (masklay_shape_a->frame > masklay_shape_b->frame) { return 1; - else + } + else { return 0; + } } void BKE_mask_layer_shape_sort(MaskLayer *masklay) @@ -1786,7 +1807,8 @@ void BKE_mask_layer_shape_changed_add(MaskLayer *masklay, if (BKE_mask_layer_shape_spline_from_index(masklay, index, &spline, &spline_point_index)) { /* sanity check */ - /* the point has already been removed in this array so subtract one when comparing with the shapes */ + /* The point has already been removed in this array + * so subtract one when comparing with the shapes. */ int tot = BKE_mask_layer_shape_totvert(masklay) - 1; /* for interpolation */ diff --git a/source/blender/blenkernel/intern/mask_evaluate.c b/source/blender/blenkernel/intern/mask_evaluate.c index 2b84c1f32c1..4e6ca878b7a 100644 --- a/source/blender/blenkernel/intern/mask_evaluate.c +++ b/source/blender/blenkernel/intern/mask_evaluate.c @@ -153,8 +153,9 @@ float (*BKE_mask_spline_differentiate_with_resolution(MaskSpline *spline, diff_points = fp = MEM_mallocN((tot + 1) * sizeof(*diff_points), "mask spline vets"); a = spline->tot_point - 1; - if (spline->flag & MASK_SPLINE_CYCLIC) + if (spline->flag & MASK_SPLINE_CYCLIC) { a++; + } point_prev = points_array; point_curr = point_prev + 1; @@ -164,8 +165,9 @@ float (*BKE_mask_spline_differentiate_with_resolution(MaskSpline *spline, BezTriple *bezt_curr; int j; - if (a == 0 && (spline->flag & MASK_SPLINE_CYCLIC)) + if (a == 0 && (spline->flag & MASK_SPLINE_CYCLIC)) { point_curr = points_array; + } bezt_prev = &point_prev->bezt; bezt_curr = &point_curr->bezt; @@ -250,8 +252,9 @@ static void feather_bucket_check_intersect(float (*feather_points)[2], const float *v3 = (float *)feather_points[check_a]; const float *v4 = (float *)feather_points[check_b]; - if (check_a >= cur_a - 1 || cur_b == check_a) + if (check_a >= cur_a - 1 || cur_b == check_a) { continue; + } if (isect_seg_seg_v2_simple(v1, v2, v3, v4)) { int k; @@ -302,11 +305,13 @@ static int feather_bucket_index_from_coord(const float co[2], int x = (int)((co[0] - min[0]) * bucket_scale[0]); int y = (int)((co[1] - min[1]) * bucket_scale[1]); - if (x == buckets_per_side) + if (x == buckets_per_side) { x--; + } - if (y == buckets_per_side) + if (y == buckets_per_side) { y--; + } return y * buckets_per_side + x; } @@ -364,19 +369,23 @@ void BKE_mask_spline_feather_collapse_inner_loops(MaskSpline *spline, minmax_v2v2_v2(min, max, feather_points[i]); if (next == tot_feather_point) { - if (spline->flag & MASK_SPLINE_CYCLIC) + if (spline->flag & MASK_SPLINE_CYCLIC) { next = 0; - else + } + else { break; + } } delta = fabsf(feather_points[i][0] - feather_points[next][0]); - if (delta > max_delta_x) + if (delta > max_delta_x) { max_delta_x = delta; + } delta = fabsf(feather_points[i][1] - feather_points[next][1]); - if (delta > max_delta_y) + if (delta > max_delta_y) { max_delta_y = delta; + } } /* prevent divisionsby zero by ensuring bounding box is not collapsed */ @@ -423,10 +432,12 @@ void BKE_mask_spline_feather_collapse_inner_loops(MaskSpline *spline, int start_bucket_index, end_bucket_index; if (end == tot_feather_point) { - if (spline->flag & MASK_SPLINE_CYCLIC) + if (spline->flag & MASK_SPLINE_CYCLIC) { end = 0; - else + } + else { break; + } } start_bucket_index = BUCKET_INDEX(feather_points[start]); @@ -458,8 +469,9 @@ void BKE_mask_spline_feather_collapse_inner_loops(MaskSpline *spline, FeatherEdgesBucket *start_bucket; - if (cur_b == tot_feather_point) + if (cur_b == tot_feather_point) { cur_b = 0; + } start_bucket_index = BUCKET_INDEX(feather_points[cur_a]); end_bucket_index = BUCKET_INDEX(feather_points[cur_b]); @@ -489,8 +501,9 @@ void BKE_mask_spline_feather_collapse_inner_loops(MaskSpline *spline, /* free buckets */ for (i = 0; i < tot_bucket; i++) { - if (buckets[i].segments) + if (buckets[i].segments) { MEM_freeN(buckets[i].segments); + } } MEM_freeN(buckets); @@ -516,8 +529,9 @@ static float (*mask_spline_feather_differentiated_points_with_resolution__even( feather = fp = MEM_mallocN((tot + 1) * sizeof(*feather), "mask spline feather diff points"); a = spline->tot_point - 1; - if (spline->flag & MASK_SPLINE_CYCLIC) + if (spline->flag & MASK_SPLINE_CYCLIC) { a++; + } point_prev = points_array; point_curr = point_prev + 1; @@ -527,8 +541,9 @@ static float (*mask_spline_feather_differentiated_points_with_resolution__even( /* BezTriple *bezt_curr; */ /* UNUSED */ int j; - if (a == 0 && (spline->flag & MASK_SPLINE_CYCLIC)) + if (a == 0 && (spline->flag & MASK_SPLINE_CYCLIC)) { point_curr = points_array; + } /* bezt_prev = &point_prev->bezt; */ /* bezt_curr = &point_curr->bezt; */ @@ -595,8 +610,9 @@ static float (*mask_spline_feather_differentiated_points_with_resolution__double feather = fp = MEM_mallocN((tot + 1) * sizeof(*feather), "mask spline vets"); a = spline->tot_point - 1; - if (spline->flag & MASK_SPLINE_CYCLIC) + if (spline->flag & MASK_SPLINE_CYCLIC) { a++; + } point_prev = points_array; point_curr = point_prev + 1; @@ -612,8 +628,9 @@ static float (*mask_spline_feather_differentiated_points_with_resolution__double BezTriple *bezt_curr; int j; - if (a == 0 && (spline->flag & MASK_SPLINE_CYCLIC)) + if (a == 0 && (spline->flag & MASK_SPLINE_CYCLIC)) { point_curr = points_array; + } bezt_prev = &point_prev->bezt; bezt_curr = &point_curr->bezt; @@ -823,8 +840,9 @@ float *BKE_mask_point_segment_diff(MaskSpline *spline, bezt = &point->bezt; bezt_next = BKE_mask_spline_point_next_bezt(spline, points_array, point); - if (!bezt_next) + if (!bezt_next) { return NULL; + } /* resol+1 because of 'forward_diff_bezier' function */ *tot_diff_point = resol + 1; @@ -879,7 +897,8 @@ void BKE_mask_layer_evaluate_animation(MaskLayer *masklay, const float ctime) __func__, (int)ctime, BLI_listbase_count(&masklay->splines_shapes), - masklay_shape_a->frame, masklay_shape_b->frame); + masklay_shape_a->frame, + masklay_shape_b->frame); #endif BKE_mask_layer_shape_to_mask_interp( masklay, masklay_shape_a, masklay_shape_b, (ctime - masklay_shape_a->frame) / w); diff --git a/source/blender/blenkernel/intern/mask_rasterize.c b/source/blender/blenkernel/intern/mask_rasterize.c index 24137b680ba..fe6ef2e047d 100644 --- a/source/blender/blenkernel/intern/mask_rasterize.c +++ b/source/blender/blenkernel/intern/mask_rasterize.c @@ -20,14 +20,16 @@ /** \file * \ingroup bke * - * This module exposes a rasterizer that works as a black box - implementation details are confined to this file, + * This module exposes a rasterizer that works as a black box - implementation details + * are confined to this file. * * The basic method to access is: * - create & initialize a handle from a #Mask datablock. * - execute pixel lookups. * - free the handle. * - * This file is admittedly a bit confusticated, in quite few areas speed was chosen over readability, + * This file is admittedly a bit confusticated, + * in quite few areas speed was chosen over readability, * though it is commented - so shouldn't be so hard to see what's going on. * Implementation: * @@ -35,12 +37,16 @@ * * Initially 'kdopbvh' was used but this ended up being too slow. * - * To gain some extra speed we take advantage of a few shortcuts that can be made rasterizing masks specifically. - * - all triangles are known to be completely white - so no depth check is done on triangle intersection. - * - all quads are known to be feather outlines - the 1 and 0 depths are known by the vertex order in the quad, - * - there is no color - just a value for each mask pixel. - * - the mask spacial structure always maps to space 0-1 on X and Y axis. - * - bucketing is used to speed up lookups for geometry. + * To gain some extra speed we take advantage of a few shortcuts + * that can be made rasterizing masks specifically. + * + * - All triangles are known to be completely white - + * so no depth check is done on triangle intersection. + * - All quads are known to be feather outlines - + * the 1 and 0 depths are known by the vertex order in the quad, + * - There is no color - just a value for each mask pixel. + * - The mask spacial structure always maps to space 0-1 on X and Y axis. + * - Bucketing is used to speed up lookups for geometry. * * Other Details: * - used unsigned values all over for some extra speed on some arch's. @@ -48,7 +54,8 @@ * - initializing the spacial structure doesn't need to be as optimized as pixel lookups are. * - mask lookups need not be pixel aligned so any sub-pixel values from x/y (0 - 1), can be found. * (perhaps masks can be used as a vector texture in 3D later on) - * Currently, to build the spacial structure we have to calculate the total number of faces ahead of time. + * Currently, to build the spacial structure we have to calculate + * the total number of faces ahead of time. * * This is getting a bit complicated with the addition of unfilled splines and end capping - * If large changes are needed here we would be better off using an iterable @@ -488,28 +495,34 @@ static void layer_bucket_init(MaskRasterLayer *layer, const float pixel_size) /* this should _almost_ never happen but since it can in extreme cases, * we have to clamp the values or we overrun the buffer and crash */ - if (xi_min >= layer->buckets_x) + if (xi_min >= layer->buckets_x) { xi_min = layer->buckets_x - 1; - if (xi_max >= layer->buckets_x) + } + if (xi_max >= layer->buckets_x) { xi_max = layer->buckets_x - 1; - if (yi_min >= layer->buckets_y) + } + if (yi_min >= layer->buckets_y) { yi_min = layer->buckets_y - 1; - if (yi_max >= layer->buckets_y) + } + if (yi_max >= layer->buckets_y) { yi_max = layer->buckets_y - 1; + } for (yi = yi_min; yi <= yi_max; yi++) { unsigned int bucket_index = (layer->buckets_x * yi) + xi_min; for (xi = xi_min; xi <= xi_max; xi++, bucket_index++) { - // unsigned int bucket_index = (layer->buckets_x * yi) + xi; /* correct but do in outer loop */ + /* correct but do in outer loop */ + // unsigned int bucket_index = (layer->buckets_x * yi) + xi; BLI_assert(xi < layer->buckets_x); BLI_assert(yi < layer->buckets_y); BLI_assert(bucket_index < bucket_tot); - /* check if the bucket intersects with the face */ - /* note: there is a trade off here since checking box/tri intersections isn't - * as optimal as it could be, but checking pixels against faces they will never intersect - * with is likely the greater slowdown here - so check if the cell intersects the face */ + /* Check if the bucket intersects with the face. */ + /* Note: there is a trade off here since checking box/tri intersections isn't as + * optimal as it could be, but checking pixels against faces they will never + * intersect with is likely the greater slowdown here - + * so check if the cell intersects the face. */ if (layer_bucket_isect_test(layer, face_index, xi, @@ -979,8 +992,9 @@ void BKE_maskrasterize_handle_init(MaskRasterHandle *mr_handle, /* --- end inefficient code --- */ /* main scan-fill */ - if ((masklay->flag & MASK_LAYERFLAG_FILL_DISCRETE) == 0) + if ((masklay->flag & MASK_LAYERFLAG_FILL_DISCRETE) == 0) { scanfill_flag |= BLI_SCANFILL_CALC_HOLES; + } sf_tri_tot = (unsigned int)BLI_scanfill_calc_ex(&sf_ctx, scanfill_flag, zvec); @@ -1155,7 +1169,15 @@ void BKE_maskrasterize_handle_init(MaskRasterHandle *mr_handle, MEM_freeN(open_spline_ranges); - // fprintf(stderr, "%u %u (%u %u), %u\n", face_index, sf_tri_tot + tot_feather_quads, sf_tri_tot, tot_feather_quads, tot_boundary_used - tot_boundary_found); +#if 0 + fprintf(stderr, + "%u %u (%u %u), %u\n", + face_index, + sf_tri_tot + tot_feather_quads, + sf_tri_tot, + tot_feather_quads, + tot_boundary_used - tot_boundary_found); +#endif #ifdef USE_SCANFILL_EDGE_WORKAROUND BLI_assert(face_index + (tot_boundary_used - tot_boundary_found) == @@ -1212,7 +1234,9 @@ void BKE_maskrasterize_handle_init(MaskRasterHandle *mr_handle, /* 2D ray test */ #if 0 static float maskrasterize_layer_z_depth_tri(const float pt[2], - const float v1[3], const float v2[3], const float v3[3]) + const float v1[3], + const float v2[3], + const float v3[3]) { float w[3]; barycentric_weights_v2(v1, v2, v3, pt, w); @@ -1225,7 +1249,7 @@ static float maskrasterize_layer_z_depth_quad( { float w[4]; barycentric_weights_v2_quad(v1, v2, v3, v4, pt, w); - //return (v1[2] * w[0]) + (v2[2] * w[1]) + (v3[2] * w[2]) + (v4[2] * w[3]); + // return (v1[2] * w[0]) + (v2[2] * w[1]) + (v3[2] * w[2]) + (v4[2] * w[3]); return w[2] + w[3]; /* we can make this assumption for small speedup */ } @@ -1240,10 +1264,7 @@ static float maskrasterize_layer_isect(unsigned int *face, #if 0 /* not essential but avoids unneeded extra lookups */ - if ((cos[0][2] < dist_orig) || - (cos[1][2] < dist_orig) || - (cos[2][2] < dist_orig)) - { + if ((cos[0][2] < dist_orig) || (cos[1][2] < dist_orig) || (cos[2][2] < dist_orig)) { if (isect_point_tri_v2_cw(xy, cos[face[0]], cos[face[1]], cos[face[2]])) { /* we know all tris are close for now */ return maskrasterize_layer_z_depth_tri(xy, cos[face[0]], cos[face[1]], cos[face[2]]); @@ -1266,7 +1287,7 @@ static float maskrasterize_layer_isect(unsigned int *face, /* needs work */ #if 1 /* quad check fails for bow-tie, so keep using 2 tri checks */ - //if (isect_point_quad_v2(xy, cos[face[0]], cos[face[1]], cos[face[2]], cos[face[3]])) + // if (isect_point_quad_v2(xy, cos[face[0]], cos[face[1]], cos[face[2]], cos[face[3]])) if (isect_point_tri_v2(xy, cos[face[0]], cos[face[1]], cos[face[2]]) || isect_point_tri_v2(xy, cos[face[0]], cos[face[2]], cos[face[3]])) { return maskrasterize_layer_z_depth_quad( diff --git a/source/blender/blenkernel/intern/material.c b/source/blender/blenkernel/intern/material.c index a4da6663de8..75b9e355df9 100644 --- a/source/blender/blenkernel/intern/material.c +++ b/source/blender/blenkernel/intern/material.c @@ -169,8 +169,10 @@ Material *BKE_material_add_gpencil(Main *bmain, const char *name) } /** - * Only copy internal data of Material ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of Material ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * @@ -424,10 +426,12 @@ void BKE_material_append_id(Main *bmain, ID *id, Material *ma) if ((matar = give_matarar_id(id))) { short *totcol = give_totcolp_id(id); Material **mat = MEM_callocN(sizeof(void *) * ((*totcol) + 1), "newmatar"); - if (*totcol) + if (*totcol) { memcpy(mat, *matar, sizeof(void *) * (*totcol)); - if (*matar) + } + if (*matar) { MEM_freeN(*matar); + } *matar = mat; (*matar)[(*totcol)++] = ma; @@ -457,10 +461,11 @@ Material *BKE_material_pop_id(Main *bmain, ID *id, int index_i, bool update_data *matar = NULL; } else { - if (index + 1 != (*totcol)) + if (index + 1 != (*totcol)) { memmove((*matar) + index, (*matar) + (index + 1), sizeof(void *) * ((*totcol) - (index + 1))); + } (*totcol)--; *matar = MEM_reallocN(*matar, sizeof(void *) * (*totcol)); @@ -510,17 +515,20 @@ Material **give_current_material_p(Object *ob, short act) Material ***matarar, **ma_p; const short *totcolp; - if (ob == NULL) + if (ob == NULL) { return NULL; + } /* if object cannot have material, (totcolp == NULL) */ totcolp = give_totcolp(ob); - if (totcolp == NULL || ob->totcol == 0) + if (totcolp == NULL || ob->totcol == 0) { return NULL; + } /* return NULL for invalid 'act', can happen for mesh face indices */ - if (act > ob->totcol) + if (act > ob->totcol) { return NULL; + } else if (act <= 0) { if (act < 0) { CLOG_ERROR(&LOG, "Negative material index!"); @@ -534,10 +542,12 @@ Material **give_current_material_p(Object *ob, short act) else { /* in data */ /* check for inconsistency */ - if (*totcolp < ob->totcol) + if (*totcolp < ob->totcol) { ob->totcol = *totcolp; - if (act > ob->totcol) + } + if (act > ob->totcol) { act = ob->totcol; + } matarar = give_matarar(ob); @@ -578,8 +588,9 @@ Material *give_node_material(Material *ma) if (ma && ma->use_nodes && ma->nodetree) { bNode *node = nodeGetActiveID(ma->nodetree, ID_MA); - if (node) + if (node) { return (Material *)node->id; + } } return NULL; @@ -620,10 +631,12 @@ void BKE_material_resize_object(Main *bmain, Object *ob, const short totcol, boo /* XXX, why not realloc on shrink? - campbell */ ob->totcol = totcol; - if (ob->totcol && ob->actcol == 0) + if (ob->totcol && ob->actcol == 0) { ob->actcol = 1; - if (ob->actcol > ob->totcol) + } + if (ob->actcol > ob->totcol) { ob->actcol = ob->totcol; + } DEG_id_tag_update(&ob->id, ID_RECALC_COPY_ON_WRITE | ID_RECALC_GEOMETRY); DEG_relations_tag_update(bmain); @@ -665,18 +678,21 @@ void assign_material_id(Main *bmain, ID *id, Material *ma, short act) Material *mao, **matar, ***matarar; short *totcolp; - if (act > MAXMAT) + if (act > MAXMAT) { return; - if (act < 1) + } + if (act < 1) { act = 1; + } /* test arraylens */ totcolp = give_totcolp_id(id); matarar = give_matarar_id(id); - if (totcolp == NULL || matarar == NULL) + if (totcolp == NULL || matarar == NULL) { return; + } if (act > *totcolp) { matar = MEM_callocN(sizeof(void *) * act, "matarray1"); @@ -692,12 +708,14 @@ void assign_material_id(Main *bmain, ID *id, Material *ma, short act) /* in data */ mao = (*matarar)[act - 1]; - if (mao) + if (mao) { id_us_min(&mao->id); + } (*matarar)[act - 1] = ma; - if (ma) + if (ma) { id_us_plus(&ma->id); + } test_all_objects_materials(bmain, id); } @@ -708,23 +726,27 @@ void assign_material(Main *bmain, Object *ob, Material *ma, short act, int assig short *totcolp; char bit = 0; - if (act > MAXMAT) + if (act > MAXMAT) { return; - if (act < 1) + } + if (act < 1) { act = 1; + } /* prevent crashing when using accidentally */ BLI_assert(!ID_IS_LINKED(ob)); - if (ID_IS_LINKED(ob)) + if (ID_IS_LINKED(ob)) { return; + } /* test arraylens */ totcolp = give_totcolp(ob); matarar = give_matarar(ob); - if (totcolp == NULL || matarar == NULL) + if (totcolp == NULL || matarar == NULL) { return; + } if (act > *totcolp) { matar = MEM_callocN(sizeof(void *) * act, "matarray1"); @@ -775,21 +797,24 @@ void assign_material(Main *bmain, Object *ob, Material *ma, short act, int assig ob->matbits[act - 1] = bit; if (bit == 1) { /* in object */ mao = ob->mat[act - 1]; - if (mao) + if (mao) { id_us_min(&mao->id); + } ob->mat[act - 1] = ma; test_object_materials(bmain, ob, ob->data); } else { /* in data */ mao = (*matarar)[act - 1]; - if (mao) + if (mao) { id_us_min(&mao->id); + } (*matarar)[act - 1] = ma; test_all_objects_materials(bmain, ob->data); /* Data may be used by several objects... */ } - if (ma) + if (ma) { id_us_plus(&ma->id); + } } void BKE_material_remap_object(Object *ob, const unsigned int *remap) @@ -887,11 +912,13 @@ void assign_matarar(Main *bmain, struct Object *ob, struct Material ***matar, sh } /* now we have the right number of slots */ - for (i = 0; i < totcol; i++) + for (i = 0; i < totcol; i++) { assign_material(bmain, ob, (*matar)[i], i + 1, BKE_MAT_ASSIGN_USERPREF); + } - if (actcol_orig > ob->totcol) + if (actcol_orig > ob->totcol) { actcol_orig = ob->totcol; + } ob->actcol = actcol_orig; } @@ -901,29 +928,36 @@ short BKE_object_material_slot_find_index(Object *ob, Material *ma) Material ***matarar; short a, *totcolp; - if (ma == NULL) + if (ma == NULL) { return 0; + } totcolp = give_totcolp(ob); matarar = give_matarar(ob); - if (totcolp == NULL || matarar == NULL) + if (totcolp == NULL || matarar == NULL) { return 0; + } - for (a = 0; a < *totcolp; a++) - if ((*matarar)[a] == ma) + for (a = 0; a < *totcolp; a++) { + if ((*matarar)[a] == ma) { break; - if (a < *totcolp) + } + } + if (a < *totcolp) { return a + 1; + } return 0; } bool BKE_object_material_slot_add(Main *bmain, Object *ob) { - if (ob == NULL) + if (ob == NULL) { return false; - if (ob->totcol >= MAXMAT) + } + if (ob->totcol >= MAXMAT) { return false; + } assign_material(bmain, ob, NULL, ob->totcol + 1, BKE_MAT_ASSIGN_USERPREF); ob->actcol = ob->totcol; @@ -969,11 +1003,13 @@ bool BKE_object_material_slot_remove(Main *bmain, Object *ob) /* we delete the actcol */ mao = (*matarar)[ob->actcol - 1]; - if (mao) + if (mao) { id_us_min(&mao->id); + } - for (a = ob->actcol; a < ob->totcol; a++) + for (a = ob->actcol; a < ob->totcol; a++) { (*matarar)[a - 1] = (*matarar)[a]; + } (*totcolp)--; if (*totcolp == 0) { @@ -991,16 +1027,18 @@ bool BKE_object_material_slot_remove(Main *bmain, Object *ob) } /* WATCH IT: do not use actcol from ob or from obt (can become zero) */ mao = obt->mat[actcol - 1]; - if (mao) + if (mao) { id_us_min(&mao->id); + } for (a = actcol; a < obt->totcol; a++) { obt->mat[a - 1] = obt->mat[a]; obt->matbits[a - 1] = obt->matbits[a]; } obt->totcol--; - if (obt->actcol > obt->totcol) + if (obt->actcol > obt->totcol) { obt->actcol = obt->totcol; + } if (obt->totcol == 0) { MEM_freeN(obt->mat); @@ -1102,8 +1140,9 @@ void BKE_texpaint_slot_refresh_cache(Scene *scene, Material *ma) int count = 0; int index = 0; - if (!ma) + if (!ma) { return; + } /* COW needed when adding texture slot on an object with no materials. */ DEG_id_tag_update(&ma->id, ID_RECALC_SHADING | ID_RECALC_COPY_ON_WRITE); @@ -1190,18 +1229,24 @@ void ramp_blend(int type, float r_col[3], const float fac, const float col[3]) r_col[2] = 1.0f - (facm + fac * (1.0f - col[2])) * (1.0f - r_col[2]); break; case MA_RAMP_OVERLAY: - if (r_col[0] < 0.5f) + if (r_col[0] < 0.5f) { r_col[0] *= (facm + 2.0f * fac * col[0]); - else + } + else { r_col[0] = 1.0f - (facm + 2.0f * fac * (1.0f - col[0])) * (1.0f - r_col[0]); - if (r_col[1] < 0.5f) + } + if (r_col[1] < 0.5f) { r_col[1] *= (facm + 2.0f * fac * col[1]); - else + } + else { r_col[1] = 1.0f - (facm + 2.0f * fac * (1.0f - col[1])) * (1.0f - r_col[1]); - if (r_col[2] < 0.5f) + } + if (r_col[2] < 0.5f) { r_col[2] *= (facm + 2.0f * fac * col[2]); - else + } + else { r_col[2] = 1.0f - (facm + 2.0f * fac * (1.0f - col[2])) * (1.0f - r_col[2]); + } break; case MA_RAMP_SUB: r_col[0] -= fac * col[0]; @@ -1209,12 +1254,15 @@ void ramp_blend(int type, float r_col[3], const float fac, const float col[3]) r_col[2] -= fac * col[2]; break; case MA_RAMP_DIV: - if (col[0] != 0.0f) + if (col[0] != 0.0f) { r_col[0] = facm * (r_col[0]) + fac * (r_col[0]) / col[0]; - if (col[1] != 0.0f) + } + if (col[1] != 0.0f) { r_col[1] = facm * (r_col[1]) + fac * (r_col[1]) / col[1]; - if (col[2] != 0.0f) + } + if (col[2] != 0.0f) { r_col[2] = facm * (r_col[2]) + fac * (r_col[2]) / col[2]; + } break; case MA_RAMP_DIFF: r_col[0] = facm * (r_col[0]) + fac * fabsf(r_col[0] - col[0]); @@ -1228,75 +1276,99 @@ void ramp_blend(int type, float r_col[3], const float fac, const float col[3]) break; case MA_RAMP_LIGHT: tmp = fac * col[0]; - if (tmp > r_col[0]) + if (tmp > r_col[0]) { r_col[0] = tmp; + } tmp = fac * col[1]; - if (tmp > r_col[1]) + if (tmp > r_col[1]) { r_col[1] = tmp; + } tmp = fac * col[2]; - if (tmp > r_col[2]) + if (tmp > r_col[2]) { r_col[2] = tmp; + } break; case MA_RAMP_DODGE: if (r_col[0] != 0.0f) { tmp = 1.0f - fac * col[0]; - if (tmp <= 0.0f) + if (tmp <= 0.0f) { r_col[0] = 1.0f; - else if ((tmp = (r_col[0]) / tmp) > 1.0f) + } + else if ((tmp = (r_col[0]) / tmp) > 1.0f) { r_col[0] = 1.0f; - else + } + else { r_col[0] = tmp; + } } if (r_col[1] != 0.0f) { tmp = 1.0f - fac * col[1]; - if (tmp <= 0.0f) + if (tmp <= 0.0f) { r_col[1] = 1.0f; - else if ((tmp = (r_col[1]) / tmp) > 1.0f) + } + else if ((tmp = (r_col[1]) / tmp) > 1.0f) { r_col[1] = 1.0f; - else + } + else { r_col[1] = tmp; + } } if (r_col[2] != 0.0f) { tmp = 1.0f - fac * col[2]; - if (tmp <= 0.0f) + if (tmp <= 0.0f) { r_col[2] = 1.0f; - else if ((tmp = (r_col[2]) / tmp) > 1.0f) + } + else if ((tmp = (r_col[2]) / tmp) > 1.0f) { r_col[2] = 1.0f; - else + } + else { r_col[2] = tmp; + } } break; case MA_RAMP_BURN: tmp = facm + fac * col[0]; - if (tmp <= 0.0f) + if (tmp <= 0.0f) { r_col[0] = 0.0f; - else if ((tmp = (1.0f - (1.0f - (r_col[0])) / tmp)) < 0.0f) + } + else if ((tmp = (1.0f - (1.0f - (r_col[0])) / tmp)) < 0.0f) { r_col[0] = 0.0f; - else if (tmp > 1.0f) + } + else if (tmp > 1.0f) { r_col[0] = 1.0f; - else + } + else { r_col[0] = tmp; + } tmp = facm + fac * col[1]; - if (tmp <= 0.0f) + if (tmp <= 0.0f) { r_col[1] = 0.0f; - else if ((tmp = (1.0f - (1.0f - (r_col[1])) / tmp)) < 0.0f) + } + else if ((tmp = (1.0f - (1.0f - (r_col[1])) / tmp)) < 0.0f) { r_col[1] = 0.0f; - else if (tmp > 1.0f) + } + else if (tmp > 1.0f) { r_col[1] = 1.0f; - else + } + else { r_col[1] = tmp; + } tmp = facm + fac * col[2]; - if (tmp <= 0.0f) + if (tmp <= 0.0f) { r_col[2] = 0.0f; - else if ((tmp = (1.0f - (1.0f - (r_col[2])) / tmp)) < 0.0f) + } + else if ((tmp = (1.0f - (1.0f - (r_col[2])) / tmp)) < 0.0f) { r_col[2] = 0.0f; - else if (tmp > 1.0f) + } + else if (tmp > 1.0f) { r_col[2] = 1.0f; - else + } + else { r_col[2] = tmp; + } break; case MA_RAMP_HUE: { float rH, rS, rV; @@ -1361,18 +1433,24 @@ void ramp_blend(int type, float r_col[3], const float fac, const float col[3]) break; } case MA_RAMP_LINEAR: - if (col[0] > 0.5f) + if (col[0] > 0.5f) { r_col[0] = r_col[0] + fac * (2.0f * (col[0] - 0.5f)); - else + } + else { r_col[0] = r_col[0] + fac * (2.0f * (col[0]) - 1.0f); - if (col[1] > 0.5f) + } + if (col[1] > 0.5f) { r_col[1] = r_col[1] + fac * (2.0f * (col[1] - 0.5f)); - else + } + else { r_col[1] = r_col[1] + fac * (2.0f * (col[1]) - 1.0f); - if (col[2] > 0.5f) + } + if (col[2] > 0.5f) { r_col[2] = r_col[2] + fac * (2.0f * (col[2] - 0.5f)); - else + } + else { r_col[2] = r_col[2] + fac * (2.0f * (col[2]) - 1.0f); + } break; } } @@ -1404,8 +1482,9 @@ void free_matcopybuf(void) void copy_matcopybuf(Main *bmain, Material *ma) { - if (matcopied) + if (matcopied) { free_matcopybuf(); + } memcpy(&matcopybuf, ma, sizeof(Material)); @@ -1423,8 +1502,9 @@ void paste_matcopybuf(Main *bmain, Material *ma) { ID id; - if (matcopied == 0) + if (matcopied == 0) { return; + } /* Free gpu material before the ntree */ GPU_material_free(&ma->gpumaterial); diff --git a/source/blender/blenkernel/intern/mball.c b/source/blender/blenkernel/intern/mball.c index 8ab042d5446..d6fa071009e 100644 --- a/source/blender/blenkernel/intern/mball.c +++ b/source/blender/blenkernel/intern/mball.c @@ -70,8 +70,9 @@ void BKE_mball_free(MetaBall *mb) MEM_SAFE_FREE(mb->mat); BLI_freelistN(&mb->elems); - if (mb->disp.first) + if (mb->disp.first) { BKE_displist_free(&mb->disp); + } } void BKE_mball_init(MetaBall *mb) @@ -98,8 +99,10 @@ MetaBall *BKE_mball_add(Main *bmain, const char *name) } /** - * Only copy internal data of MetaBall ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of MetaBall ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * @@ -206,8 +209,9 @@ void BKE_mball_texspace_calc(Object *ob) dl = ob->runtime.curve_cache->disp.first; while (dl) { tot = dl->nr; - if (tot) + if (tot) { do_it = true; + } data = dl->verts; while (tot--) { /* Also weird... but longer. From utildefines. */ @@ -236,7 +240,8 @@ BoundBox *BKE_mball_boundbox_get(Object *ob) return ob->runtime.bb; } - /* This should always only be called with evaluated objects, but currently RNA is a problem here... */ + /* This should always only be called with evaluated objects, + * but currently RNA is a problem here... */ if (ob->runtime.curve_cache != NULL) { BKE_mball_texspace_calc(ob); } @@ -281,12 +286,15 @@ float *BKE_mball_make_orco(Object *ob, ListBase *dispbase) /* Note on mball basis stuff 2.5x (this is a can of worms) * This really needs a rewrite/refactor its totally broken in anything other then basic cases - * Multiple Scenes + Set Scenes & mixing mball basis SHOULD work but fails to update the depsgraph on rename - * and linking into scenes or removal of basis mball. so take care when changing this code. + * Multiple Scenes + Set Scenes & mixing mball basis SHOULD work but fails to update the depsgraph + * on rename and linking into scenes or removal of basis mball. + * So take care when changing this code. * - * Main idiot thing here is that the system returns find_basis_mball() objects which fail a is_basis_mball() test. + * Main idiot thing here is that the system returns find_basis_mball() + * objects which fail a is_basis_mball() test. * - * Not only that but the depsgraph and their areas depend on this behavior!, so making small fixes here isn't worth it. + * Not only that but the depsgraph and their areas depend on this behavior!, + * so making small fixes here isn't worth it. * - Campbell */ @@ -358,8 +366,8 @@ bool BKE_mball_is_any_unselected(const MetaBall *mb) /* \brief copy some properties from object to other metaball object with same base name * - * When some properties (wiresize, threshold, update flags) of metaball are changed, then this properties - * are copied to all metaballs in same "group" (metaballs with same base name: MBall, + * When some properties (wiresize, threshold, update flags) of metaball are changed, then this + * properties are copied to all metaballs in same "group" (metaballs with same base name: MBall, * MBall.001, MBall.002, etc). The most important is to copy properties to the base metaball, * because this metaball influence polygonisation of metaballs. */ void BKE_mball_properties_copy(Scene *scene, Object *active_object) @@ -425,7 +433,8 @@ Object *BKE_mball_basis_find(Scene *scene, Object *basis) if (ob != bob) { BLI_split_name_num(obname, &obnr, ob->id.name + 2, '.'); - /* object ob has to be in same "group" ... it means, that it has to have same base of its name */ + /* Object ob has to be in same "group" ... it means, + * that it has to have same base of its name. */ if (STREQ(obname, basisname)) { if (obnr < basisnr) { basis = ob; diff --git a/source/blender/blenkernel/intern/mball_tessellate.c b/source/blender/blenkernel/intern/mball_tessellate.c index 3ca46b7be61..1218e78c6f0 100644 --- a/source/blender/blenkernel/intern/mball_tessellate.c +++ b/source/blender/blenkernel/intern/mball_tessellate.c @@ -172,13 +172,16 @@ static unsigned int partition_mainb( div *= 2.0f; while (1) { - while (i < j && div > (mainb[i]->bb->vec[6][s] + mainb[i]->bb->vec[0][s])) + while (i < j && div > (mainb[i]->bb->vec[6][s] + mainb[i]->bb->vec[0][s])) { i++; - while (j > i && div < (mainb[j]->bb->vec[6][s] + mainb[j]->bb->vec[0][s])) + } + while (j > i && div < (mainb[j]->bb->vec[6][s] + mainb[j]->bb->vec[0][s])) { j--; + } - if (i >= j) + if (i >= j) { break; + } SWAP(MetaElem *, mainb[i], mainb[j]); i++; @@ -212,10 +215,12 @@ static void build_bvh_spatial(PROCESS *process, dim[2] = allbox->max[2] - allbox->min[2]; s = 0; - if (dim[1] > dim[0] && dim[1] > dim[2]) + if (dim[1] > dim[0] && dim[1] > dim[2]) { s = 1; - else if (dim[2] > dim[1] && dim[2] > dim[0]) + } + else if (dim[2] > dim[1] && dim[2] > dim[0]) { s = 2; + } div = allbox->min[s] + (dim[s] / 2.0f); @@ -316,28 +321,37 @@ static float densfunc(const MetaElem *ball, float x, float y, float z) /* do nothing */ break; case MB_CUBE: - if (dvec[2] > ball->expz) + if (dvec[2] > ball->expz) { dvec[2] -= ball->expz; - else if (dvec[2] < -ball->expz) + } + else if (dvec[2] < -ball->expz) { dvec[2] += ball->expz; - else + } + else { dvec[2] = 0.0; + } ATTR_FALLTHROUGH; case MB_PLANE: - if (dvec[1] > ball->expy) + if (dvec[1] > ball->expy) { dvec[1] -= ball->expy; - else if (dvec[1] < -ball->expy) + } + else if (dvec[1] < -ball->expy) { dvec[1] += ball->expy; - else + } + else { dvec[1] = 0.0; + } ATTR_FALLTHROUGH; case MB_TUBE: - if (dvec[0] > ball->expx) + if (dvec[0] > ball->expx) { dvec[0] -= ball->expx; - else if (dvec[0] < -ball->expx) + } + else if (dvec[0] < -ball->expx) { dvec[0] += ball->expx; - else + } + else { dvec[0] = 0.0; + } break; case MB_ELIPSOID: dvec[0] /= ball->expx; @@ -347,28 +361,37 @@ static float densfunc(const MetaElem *ball, float x, float y, float z) /* *** deprecated, could be removed?, do-versioned at least *** */ case MB_TUBEX: - if (dvec[0] > ball->len) + if (dvec[0] > ball->len) { dvec[0] -= ball->len; - else if (dvec[0] < -ball->len) + } + else if (dvec[0] < -ball->len) { dvec[0] += ball->len; - else + } + else { dvec[0] = 0.0; + } break; case MB_TUBEY: - if (dvec[1] > ball->len) + if (dvec[1] > ball->len) { dvec[1] -= ball->len; - else if (dvec[1] < -ball->len) + } + else if (dvec[1] < -ball->len) { dvec[1] += ball->len; - else + } + else { dvec[1] = 0.0; + } break; case MB_TUBEZ: - if (dvec[2] > ball->len) + if (dvec[2] > ball->len) { dvec[2] -= ball->len; - else if (dvec[2] < -ball->len) + } + else if (dvec[2] < -ball->len) { dvec[2] += ball->len; - else + } + else { dvec[2] = 0.0; + } break; /* *** end deprecated *** */ } @@ -399,10 +422,12 @@ static float metaball(PROCESS *process, float x, float y, float z) for (i = 0; i < 2; i++) { if ((node->bb[i].min[0] <= x) && (node->bb[i].max[0] >= x) && (node->bb[i].min[1] <= y) && (node->bb[i].max[1] >= y) && (node->bb[i].min[2] <= z) && (node->bb[i].max[2] >= z)) { - if (node->child[i]) + if (node->child[i]) { process->bvh_queue[front++] = node->child[i]; - else + } + else { dens += densfunc(node->bb[i].ml, x, y, z); + } } } } @@ -466,18 +491,24 @@ static void make_face(PROCESS *process, int i1, int i2, int i3, int i4) /* Frees allocated memory */ static void freepolygonize(PROCESS *process) { - if (process->corners) + if (process->corners) { MEM_freeN(process->corners); - if (process->edges) + } + if (process->edges) { MEM_freeN(process->edges); - if (process->centers) + } + if (process->centers) { MEM_freeN(process->centers); - if (process->mainb) + } + if (process->mainb) { MEM_freeN(process->mainb); - if (process->bvh_queue) + } + if (process->bvh_queue) { MEM_freeN(process->bvh_queue); - if (process->pgn_elements) + } + if (process->pgn_elements) { BLI_memarena_free(process->pgn_elements); + } } /* **************** POLYGONIZATION ************************ */ @@ -577,18 +608,24 @@ static void docube(PROCESS *process, CUBE *cube) } /* Using faces[] table, adds neighbouring cube if surface intersects face in this direction. */ - if (MB_BIT(faces[index], 0)) + if (MB_BIT(faces[index], 0)) { add_cube(process, cube->i - 1, cube->j, cube->k); - if (MB_BIT(faces[index], 1)) + } + if (MB_BIT(faces[index], 1)) { add_cube(process, cube->i + 1, cube->j, cube->k); - if (MB_BIT(faces[index], 2)) + } + if (MB_BIT(faces[index], 2)) { add_cube(process, cube->i, cube->j - 1, cube->k); - if (MB_BIT(faces[index], 3)) + } + if (MB_BIT(faces[index], 3)) { add_cube(process, cube->i, cube->j + 1, cube->k); - if (MB_BIT(faces[index], 4)) + } + if (MB_BIT(faces[index], 4)) { add_cube(process, cube->i, cube->j, cube->k - 1); - if (MB_BIT(faces[index], 5)) + } + if (MB_BIT(faces[index], 5)) { add_cube(process, cube->i, cube->j, cube->k + 1); + } /* Using cubetable[], determines polygons for output. */ for (polys = cubetable[index]; polys; polys = polys->next) { @@ -719,15 +756,18 @@ static void makecubetable(void) static bool is_done = false; int i, e, c, done[12], pos[8]; - if (is_done) + if (is_done) { return; + } is_done = true; for (i = 0; i < 256; i++) { - for (e = 0; e < 12; e++) + for (e = 0; e < 12; e++) { done[e] = 0; - for (c = 0; c < 8; c++) + } + for (c = 0; c < 8; c++) { pos[c] = MB_BIT(i, c); + } for (e = 0; e < 12; e++) { if (!done[e] && (pos[corner1[e]] != pos[corner2[e]])) { INTLIST *ints = NULL; @@ -747,8 +787,9 @@ static void makecubetable(void) ints->i = edge; ints->next = tmp; /* add edge to head of list */ - if (edge == start) + if (edge == start) { break; + } face = otherface(edge, face); } } @@ -766,18 +807,24 @@ static void makecubetable(void) INTLIST *edges; for (edges = polys->list; edges; edges = edges->next) { - if (edges->i == LB || edges->i == LT || edges->i == LN || edges->i == LF) + if (edges->i == LB || edges->i == LT || edges->i == LN || edges->i == LF) { faces[i] |= 1 << L; - if (edges->i == RB || edges->i == RT || edges->i == RN || edges->i == RF) + } + if (edges->i == RB || edges->i == RT || edges->i == RN || edges->i == RF) { faces[i] |= 1 << R; - if (edges->i == LB || edges->i == RB || edges->i == BN || edges->i == BF) + } + if (edges->i == LB || edges->i == RB || edges->i == BN || edges->i == BF) { faces[i] |= 1 << B; - if (edges->i == LT || edges->i == RT || edges->i == TN || edges->i == TF) + } + if (edges->i == LT || edges->i == RT || edges->i == TN || edges->i == TF) { faces[i] |= 1 << T; - if (edges->i == LN || edges->i == RN || edges->i == BN || edges->i == TN) + } + if (edges->i == LN || edges->i == RN || edges->i == BN || edges->i == TN) { faces[i] |= 1 << N; - if (edges->i == LF || edges->i == RF || edges->i == BF || edges->i == TF) + } + if (edges->i == LF || edges->i == RF || edges->i == BF || edges->i == TF) { faces[i] |= 1 << F; + } } } } @@ -822,8 +869,9 @@ static int setcenter(PROCESS *process, CENTERLIST *table[], const int i, const i q = table[index]; for (l = q; l != NULL; l = l->next) { - if (l->i == i && l->j == j && l->k == k) + if (l->i == i && l->j == j && l->k == k) { return 1; + } } newc = BLI_memarena_alloc(process->pgn_elements, sizeof(CENTERLIST)); @@ -940,8 +988,9 @@ static int vertid(PROCESS *process, const CORNER *c1, const CORNER *c2) float v[3], no[3]; int vid = getedge(process->edges, c1->i, c1->j, c1->k, c2->i, c2->j, c2->k); - if (vid != -1) + if (vid != -1) { return vid; /* previously computed */ + } converge(process, c1, c2, v); /* position */ @@ -1020,9 +1069,10 @@ static void add_cube(PROCESS *process, int i, int j, int k) ncube->cube.k = k; /* set corners of initial cube: */ - for (n = 0; n < 8; n++) + for (n = 0; n < 8; n++) { ncube->cube.corners[n] = setcorner( process, i + MB_BIT(n, 2), j + MB_BIT(n, 1), k + MB_BIT(n, 0)); + } } } @@ -1157,10 +1207,12 @@ static void init_meta(Depsgraph *depsgraph, PROCESS *process, Scene *scene, Obje if (bob == ob && (base->flag_legacy & OB_FROMDUPLI) == 0) { mb = ob->data; - if (mb->editelems) + if (mb->editelems) { ml = mb->editelems->first; - else + } + else { ml = mb->elems.first; + } } else { char name[MAX_ID_NAME]; @@ -1170,10 +1222,12 @@ static void init_meta(Depsgraph *depsgraph, PROCESS *process, Scene *scene, Obje if (STREQ(obname, name)) { mb = bob->data; - if (mb->editelems) + if (mb->editelems) { ml = mb->editelems->first; - else + } + else { ml = mb->elems.first; + } } } @@ -1216,14 +1270,17 @@ static void init_meta(Depsgraph *depsgraph, PROCESS *process, Scene *scene, Obje /* too big stiffness seems only ugly due to linear interpolation * no need to have possibility for too big stiffness */ - if (ml->s > 10.0f) + if (ml->s > 10.0f) { new_ml->s = 10.0f; - else + } + else { new_ml->s = ml->s; + } /* if metaball is negative, set stiffness negative */ - if (new_ml->flag & MB_NEGATIVE) + if (new_ml->flag & MB_NEGATIVE) { new_ml->s = -new_ml->s; + } /* Translation of MetaElem */ unit_m4(pos); @@ -1234,7 +1291,14 @@ static void init_meta(Depsgraph *depsgraph, PROCESS *process, Scene *scene, Obje /* Rotation of MetaElem is stored in quat */ quat_to_mat4(rot, ml->quat); - /* basis object space -> world -> ml object space -> position -> rotation -> ml local space */ + /* Matrix multiply is as follows: + * basis object space -> + * world -> + * ml object space -> + * position -> + * rotation -> + * ml local space + */ mul_m4_series((float(*)[4])new_ml->mat, obinv, bob->obmat, pos, rot); /* ml local space -> basis object space */ invert_m4_m4((float(*)[4])new_ml->imat, (float(*)[4])new_ml->mat); @@ -1267,7 +1331,8 @@ static void init_meta(Depsgraph *depsgraph, PROCESS *process, Scene *scene, Obje } /* untransformed Bounding Box of MetaElem */ - /* TODO, its possible the elem type has been changed and the exp* values can use a fallback */ + /* TODO, its possible the elem type has been changed and the exp* + * values can use a fallback. */ copy_v3_fl3(new_ml->bb->vec[0], -expx, -expy, -expz); /* 0 */ copy_v3_fl3(new_ml->bb->vec[1], +expx, -expy, -expz); /* 1 */ copy_v3_fl3(new_ml->bb->vec[2], +expx, +expy, -expz); /* 2 */ @@ -1278,8 +1343,9 @@ static void init_meta(Depsgraph *depsgraph, PROCESS *process, Scene *scene, Obje copy_v3_fl3(new_ml->bb->vec[7], -expx, +expy, +expz); /* 7 */ /* transformation of Metalem bb */ - for (i = 0; i < 8; i++) + for (i = 0; i < 8; i++) { mul_m4_v3((float(*)[4])new_ml->mat, new_ml->bb->vec[i]); + } /* find max and min of transformed bb */ INIT_MINMAX(tempmin, tempmax); @@ -1308,8 +1374,9 @@ static void init_meta(Depsgraph *depsgraph, PROCESS *process, Scene *scene, Obje if (process->totelem > 0) { copy_v3_v3(process->allbb.min, process->mainb[0]->bb->vec[0]); copy_v3_v3(process->allbb.max, process->mainb[0]->bb->vec[6]); - for (i = 1; i < process->totelem; i++) + for (i = 1; i < process->totelem; i++) { make_box_union(process->mainb[i]->bb, &process->allbb, &process->allbb); + } } } @@ -1325,19 +1392,25 @@ void BKE_mball_polygonize(Depsgraph *depsgraph, Scene *scene, Object *ob, ListBa process.thresh = mb->thresh; - if (process.thresh < 0.001f) + if (process.thresh < 0.001f) { process.converge_res = 16; - else if (process.thresh < 0.01f) + } + else if (process.thresh < 0.01f) { process.converge_res = 8; - else if (process.thresh < 0.1f) + } + else if (process.thresh < 0.1f) { process.converge_res = 4; - else + } + else { process.converge_res = 2; + } - if (is_render && (mb->flag == MB_UPDATE_NEVER)) + if (is_render && (mb->flag == MB_UPDATE_NEVER)) { return; - if ((G.moving & (G_TRANSFORM_OBJ | G_TRANSFORM_EDIT)) && mb->flag == MB_UPDATE_FAST) + } + if ((G.moving & (G_TRANSFORM_OBJ | G_TRANSFORM_EDIT)) && mb->flag == MB_UPDATE_FAST) { return; + } if (is_render) { process.size = mb->rendersize; @@ -1359,8 +1432,9 @@ void BKE_mball_polygonize(Depsgraph *depsgraph, Scene *scene, Object *ob, ListBa if (process.totelem > 0) { build_bvh_spatial(&process, &process.metaball_bvh, 0, process.totelem, &process.allbb); - /* don't polygonize metaballs with too high resolution (base mball to small) - * note: Eps was 0.0001f but this was giving problems for blood animation for durian, using 0.00001f */ + /* Don't polygonize metaballs with too high resolution (base mball to small) + * note: Eps was 0.0001f but this was giving problems for blood animation for durian, + * using 0.00001f. */ if (ob->scale[0] > 0.00001f * (process.allbb.max[0] - process.allbb.min[0]) || ob->scale[1] > 0.00001f * (process.allbb.max[1] - process.allbb.min[1]) || ob->scale[2] > 0.00001f * (process.allbb.max[2] - process.allbb.min[2])) { diff --git a/source/blender/blenkernel/intern/mesh.c b/source/blender/blenkernel/intern/mesh.c index 5df06e61744..56832c1724a 100644 --- a/source/blender/blenkernel/intern/mesh.c +++ b/source/blender/blenkernel/intern/mesh.c @@ -128,8 +128,9 @@ static int customdata_compare( } } - if (i1 != i2) + if (i1 != i2) { return MESHCMP_CDLAYERS_MISMATCH; + } l1 = c1->layers; l2 = c2->layers; @@ -157,8 +158,9 @@ static int customdata_compare( int vtot = m1->totvert; for (j = 0; j < vtot; j++, v1++, v2++) { - if (len_squared_v3v3(v1->co, v2->co) > thresh_sq) + if (len_squared_v3v3(v1->co, v2->co) > thresh_sq) { return MESHCMP_VERTCOMISMATCH; + } /* I don't care about normals, let's just do coordinates */ } } @@ -175,8 +177,9 @@ static int customdata_compare( } for (j = 0; j < etot; j++, e2++) { - if (!BLI_edgehash_lookup(eh, e2->v1, e2->v2)) + if (!BLI_edgehash_lookup(eh, e2->v1, e2->v2)) { return MESHCMP_EDGEUNKNOWN; + } } BLI_edgehash_free(eh, NULL); } @@ -190,15 +193,17 @@ static int customdata_compare( MLoop *lp1, *lp2; int k; - if (p1->totloop != p2->totloop) + if (p1->totloop != p2->totloop) { return MESHCMP_POLYMISMATCH; + } lp1 = m1->mloop + p1->loopstart; lp2 = m2->mloop + p2->loopstart; for (k = 0; k < p1->totloop; k++, lp1++, lp2++) { - if (lp1->v != lp2->v) + if (lp1->v != lp2->v) { return MESHCMP_POLYVERTMISMATCH; + } } } } @@ -208,8 +213,9 @@ static int customdata_compare( int ltot = m1->totloop; for (j = 0; j < ltot; j++, lp1++, lp2++) { - if (lp1->v != lp2->v) + if (lp1->v != lp2->v) { return MESHCMP_LOOPMISMATCH; + } } } if (l1->type == CD_MLOOPUV) { @@ -218,8 +224,9 @@ static int customdata_compare( int ltot = m1->totloop; for (j = 0; j < ltot; j++, lp1++, lp2++) { - if (len_squared_v2v2(lp1->uv, lp2->uv) > thresh_sq) + if (len_squared_v2v2(lp1->uv, lp2->uv) > thresh_sq) { return MESHCMP_LOOPUVMISMATCH; + } } } @@ -245,14 +252,17 @@ static int customdata_compare( int k; MDeformWeight *dw1 = dv1->dw, *dw2 = dv2->dw; - if (dv1->totweight != dv2->totweight) + if (dv1->totweight != dv2->totweight) { return MESHCMP_DVERT_TOTGROUPMISMATCH; + } for (k = 0; k < dv1->totweight; k++, dw1++, dw2++) { - if (dw1->def_nr != dw2->def_nr) + if (dw1->def_nr != dw2->def_nr) { return MESHCMP_DVERT_GROUPMISMATCH; - if (fabsf(dw1->weight - dw2->weight) > thresh) + } + if (fabsf(dw1->weight - dw2->weight) > thresh) { return MESHCMP_DVERT_WEIGHTMISMATCH; + } } } } @@ -271,32 +281,41 @@ const char *BKE_mesh_cmp(Mesh *me1, Mesh *me2, float thresh) { int c; - if (!me1 || !me2) + if (!me1 || !me2) { return "Requires two input meshes"; + } - if (me1->totvert != me2->totvert) + if (me1->totvert != me2->totvert) { return "Number of verts don't match"; + } - if (me1->totedge != me2->totedge) + if (me1->totedge != me2->totedge) { return "Number of edges don't match"; + } - if (me1->totpoly != me2->totpoly) + if (me1->totpoly != me2->totpoly) { return "Number of faces don't match"; + } - if (me1->totloop != me2->totloop) + if (me1->totloop != me2->totloop) { return "Number of loops don't match"; + } - if ((c = customdata_compare(&me1->vdata, &me2->vdata, me1, me2, thresh))) + if ((c = customdata_compare(&me1->vdata, &me2->vdata, me1, me2, thresh))) { return cmpcode_to_str(c); + } - if ((c = customdata_compare(&me1->edata, &me2->edata, me1, me2, thresh))) + if ((c = customdata_compare(&me1->edata, &me2->edata, me1, me2, thresh))) { return cmpcode_to_str(c); + } - if ((c = customdata_compare(&me1->ldata, &me2->ldata, me1, me2, thresh))) + if ((c = customdata_compare(&me1->ldata, &me2->ldata, me1, me2, thresh))) { return cmpcode_to_str(c); + } - if ((c = customdata_compare(&me1->pdata, &me2->pdata, me1, me2, thresh))) + if ((c = customdata_compare(&me1->pdata, &me2->pdata, me1, me2, thresh))) { return cmpcode_to_str(c); + } return NULL; } @@ -517,8 +536,10 @@ Mesh *BKE_mesh_add(Main *bmain, const char *name) } /** - * Only copy internal data of Mesh ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of Mesh ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * @@ -573,17 +594,22 @@ void BKE_mesh_copy_data(Main *bmain, Mesh *me_dst, const Mesh *me_src, const int /* Custom data layer functions; those assume that totXXX are set correctly. */ static void mesh_ensure_cdlayers_primary(Mesh *mesh, bool do_tessface) { - if (!CustomData_get_layer(&mesh->vdata, CD_MVERT)) + if (!CustomData_get_layer(&mesh->vdata, CD_MVERT)) { CustomData_add_layer(&mesh->vdata, CD_MVERT, CD_CALLOC, NULL, mesh->totvert); - if (!CustomData_get_layer(&mesh->edata, CD_MEDGE)) + } + if (!CustomData_get_layer(&mesh->edata, CD_MEDGE)) { CustomData_add_layer(&mesh->edata, CD_MEDGE, CD_CALLOC, NULL, mesh->totedge); - if (!CustomData_get_layer(&mesh->ldata, CD_MLOOP)) + } + if (!CustomData_get_layer(&mesh->ldata, CD_MLOOP)) { CustomData_add_layer(&mesh->ldata, CD_MLOOP, CD_CALLOC, NULL, mesh->totloop); - if (!CustomData_get_layer(&mesh->pdata, CD_MPOLY)) + } + if (!CustomData_get_layer(&mesh->pdata, CD_MPOLY)) { CustomData_add_layer(&mesh->pdata, CD_MPOLY, CD_CALLOC, NULL, mesh->totpoly); + } - if (do_tessface && !CustomData_get_layer(&mesh->fdata, CD_MFACE)) + if (do_tessface && !CustomData_get_layer(&mesh->fdata, CD_MFACE)) { CustomData_add_layer(&mesh->fdata, CD_MFACE, CD_CALLOC, NULL, mesh->totface); + } } Mesh *BKE_mesh_new_nomain( @@ -831,8 +857,9 @@ bool BKE_mesh_uv_cdlayer_rename(Mesh *me, /* Go back to absolute indices! */ lidx += lidx_start; - if (fidx != -1) + if (fidx != -1) { fidx += fidx_start; + } return BKE_mesh_uv_cdlayer_rename_index(me, lidx, fidx, new_name, do_tessface); } @@ -844,14 +871,17 @@ void BKE_mesh_boundbox_calc(Mesh *me, float r_loc[3], float r_size[3]) float min[3], max[3]; float mloc[3], msize[3]; - if (me->bb == NULL) + if (me->bb == NULL) { me->bb = MEM_callocN(sizeof(BoundBox), "boundbox"); + } bb = me->bb; - if (!r_loc) + if (!r_loc) { r_loc = mloc; - if (!r_size) + } + if (!r_size) { r_size = msize; + } INIT_MINMAX(min, max); if (!BKE_mesh_minmax(me, min, max)) { @@ -879,12 +909,15 @@ void BKE_mesh_texspace_calc(Mesh *me) if (me->texflag & ME_AUTOSPACE) { for (a = 0; a < 3; a++) { - if (size[a] == 0.0f) + if (size[a] == 0.0f) { size[a] = 1.0f; - else if (size[a] > 0.0f && size[a] < 0.00001f) + } + else if (size[a] > 0.0f && size[a] < 0.00001f) { size[a] = 0.00001f; - else if (size[a] < 0.0f && size[a] > -0.00001f) + } + else if (size[a] < 0.0f && size[a] > -0.00001f) { size[a] = -0.00001f; + } } copy_v3_v3(me->loc, loc); @@ -895,7 +928,8 @@ void BKE_mesh_texspace_calc(Mesh *me) BoundBox *BKE_mesh_boundbox_get(Object *ob) { - /* This is Object-level data access, DO NOT touch to Mesh's bb, would be totally thread-unsafe. */ + /* This is Object-level data access, + * DO NOT touch to Mesh's bb, would be totally thread-unsafe. */ if (ob->runtime.bb == NULL || ob->runtime.bb->flag & BOUNDBOX_DIRTY) { Mesh *me = ob->data; float min[3], max[3]; @@ -922,12 +956,15 @@ BoundBox *BKE_mesh_texspace_get(Mesh *me, float r_loc[3], float r_rot[3], float BKE_mesh_texspace_calc(me); } - if (r_loc) + if (r_loc) { copy_v3_v3(r_loc, me->loc); - if (r_rot) + } + if (r_rot) { copy_v3_v3(r_rot, me->rot); - if (r_size) + } + if (r_size) { copy_v3_v3(r_size, me->size); + } return me->bb; } @@ -939,14 +976,18 @@ void BKE_mesh_texspace_get_reference( BKE_mesh_texspace_calc(me); } - if (r_texflag != NULL) + if (r_texflag != NULL) { *r_texflag = &me->texflag; - if (r_loc != NULL) + } + if (r_loc != NULL) { *r_loc = me->loc; - if (r_rot != NULL) + } + if (r_rot != NULL) { *r_rot = me->rot; - if (r_size != NULL) + } + if (r_size != NULL) { *r_size = me->size; + } } void BKE_mesh_texspace_copy_from_object(Mesh *me, Object *ob) @@ -1026,7 +1067,8 @@ int test_index_face(MFace *mface, CustomData *fdata, int mfindex, int nr) nr--; } - /* check corrupt cases, bow-tie geometry, cant handle these because edge data wont exist so just return 0 */ + /* Check corrupt cases, bow-tie geometry, + * cant handle these because edge data wont exist so just return 0. */ if (nr == 3) { if ( /* real edges */ @@ -1053,8 +1095,9 @@ int test_index_face(MFace *mface, CustomData *fdata, int mfindex, int nr) SWAP(unsigned int, mface->v1, mface->v2); SWAP(unsigned int, mface->v2, mface->v3); - if (fdata) + if (fdata) { CustomData_swap_corners(fdata, mfindex, corner_indices); + } } } else if (nr == 4) { @@ -1064,8 +1107,9 @@ int test_index_face(MFace *mface, CustomData *fdata, int mfindex, int nr) SWAP(unsigned int, mface->v1, mface->v3); SWAP(unsigned int, mface->v2, mface->v4); - if (fdata) + if (fdata) { CustomData_swap_corners(fdata, mfindex, corner_indices); + } } } @@ -1075,12 +1119,15 @@ int test_index_face(MFace *mface, CustomData *fdata, int mfindex, int nr) Mesh *BKE_mesh_from_object(Object *ob) { - if (ob == NULL) + if (ob == NULL) { return NULL; - if (ob->type == OB_MESH) + } + if (ob->type == OB_MESH) { return ob->data; - else + } + else { return NULL; + } } void BKE_mesh_assign_object(Main *bmain, Object *ob, Mesh *me) @@ -1089,13 +1136,15 @@ void BKE_mesh_assign_object(Main *bmain, Object *ob, Mesh *me) multires_force_update(ob); - if (ob == NULL) + if (ob == NULL) { return; + } if (ob->type == OB_MESH) { old = ob->data; - if (old) + if (old) { id_us_min(&old->id); + } ob->data = me; id_us_plus((ID *)me); } @@ -1206,10 +1255,12 @@ float (*BKE_mesh_vertexCos_get(const Mesh *me, int *r_verts_len))[3] int i, verts_len = me->totvert; float(*cos)[3] = MEM_malloc_arrayN(verts_len, sizeof(*cos), "vertexcos1"); - if (r_verts_len) + if (r_verts_len) { *r_verts_len = verts_len; - for (i = 0; i < verts_len; i++) + } + for (i = 0; i < verts_len; i++) { copy_v3_v3(cos[i], me->mvert[i].co); + } return cos; } @@ -1222,8 +1273,9 @@ int poly_find_loop_from_vert(const MPoly *poly, const MLoop *loopstart, unsigned { int j; for (j = 0; j < poly->totloop; j++, loopstart++) { - if (loopstart->v == vert) + if (loopstart->v == vert) { return j; + } } return -1; @@ -1256,12 +1308,15 @@ int poly_get_adj_loops_from_vert(const MPoly *poly, */ int BKE_mesh_edge_other_vert(const MEdge *e, int v) { - if (e->v1 == v) + if (e->v1 == v) { return e->v2; - else if (e->v2 == v) + } + else if (e->v2 == v) { return e->v1; - else + } + else { return -1; + } } /** @@ -1297,8 +1352,9 @@ void BKE_mesh_transform(Mesh *me, float mat[4][4], bool do_keys) MVert *mvert = me->mvert; float(*lnors)[3] = CustomData_get_layer(&me->ldata, CD_NORMAL); - for (i = 0; i < me->totvert; i++, mvert++) + for (i = 0; i < me->totvert; i++, mvert++) { mul_m4_v3(mat, mvert->co); + } if (do_keys && me->key) { KeyBlock *kb; @@ -1311,7 +1367,8 @@ void BKE_mesh_transform(Mesh *me, float mat[4][4], bool do_keys) } /* don't update normals, caller can do this explicitly. - * We do update loop normals though, those may not be auto-generated (see e.g. STL import script)! */ + * We do update loop normals though, those may not be auto-generated + * (see e.g. STL import script)! */ if (lnors) { float m3[3][3]; @@ -1436,8 +1493,9 @@ void BKE_mesh_mselect_validate(Mesh *me) MSelect *mselect_src, *mselect_dst; int i_src, i_dst; - if (me->totselect == 0) + if (me->totselect == 0) { return; + } mselect_src = me->mselect; mselect_dst = MEM_malloc_arrayN((me->totselect), sizeof(MSelect), "Mesh selection history"); @@ -1561,8 +1619,9 @@ void BKE_mesh_apply_vert_coords(Mesh *mesh, float (*vertCoords)[3]) vert = CustomData_duplicate_referenced_layer(&mesh->vdata, CD_MVERT, mesh->totvert); mesh->mvert = vert; - for (i = 0; i < mesh->totvert; ++i, ++vert) + for (i = 0; i < mesh->totvert; ++i, ++vert) { copy_v3_v3(vert->co, vertCoords[i]); + } mesh->runtime.cd_dirty_vert |= CD_MASK_NORMAL; } @@ -1576,8 +1635,9 @@ void BKE_mesh_apply_vert_normals(Mesh *mesh, short (*vertNormals)[3]) vert = CustomData_duplicate_referenced_layer(&mesh->vdata, CD_MVERT, mesh->totvert); mesh->mvert = vert; - for (i = 0; i < mesh->totvert; ++i, ++vert) + for (i = 0; i < mesh->totvert; ++i, ++vert) { copy_v3_v3_short(vert->no, vertNormals[i]); + } mesh->runtime.cd_dirty_vert &= ~CD_MASK_NORMAL; } @@ -1585,8 +1645,9 @@ void BKE_mesh_apply_vert_normals(Mesh *mesh, short (*vertNormals)[3]) /** * Compute 'split' (aka loop, or per face corner's) normals. * - * \param r_lnors_spacearr: Allows to get computed loop normal space array. That data, among other things, - * contains 'smooth fan' info, useful e.g. to split geometry along sharp edges... + * \param r_lnors_spacearr: Allows to get computed loop normal space array. + * That data, among other things, contains 'smooth fan' info, useful e.g. + * to split geometry along sharp edges... */ void BKE_mesh_calc_normals_split_ex(Mesh *mesh, MLoopNorSpaceArray *r_lnors_spacearr) { @@ -1596,7 +1657,8 @@ void BKE_mesh_calc_normals_split_ex(Mesh *mesh, MLoopNorSpaceArray *r_lnors_spac bool free_polynors = false; /* Note that we enforce computing clnors when the clnor space array is requested by caller here. - * However, we obviously only use the autosmooth angle threshold only in case autosmooth is enabled. */ + * However, we obviously only use the autosmooth angle threshold + * only in case autosmooth is enabled. */ const bool use_split_normals = (r_lnors_spacearr != NULL) || ((mesh->flag & ME_AUTOSMOOTH) != 0); const float split_angle = (mesh->flag & ME_AUTOSMOOTH) != 0 ? mesh->smoothresh : (float)M_PI; @@ -1613,7 +1675,8 @@ void BKE_mesh_calc_normals_split_ex(Mesh *mesh, MLoopNorSpaceArray *r_lnors_spac clnors = CustomData_get_layer(&mesh->ldata, CD_CUSTOMLOOPNORMAL); if (CustomData_has_layer(&mesh->pdata, CD_NORMAL)) { - /* This assume that layer is always up to date, not sure this is the case (esp. in Edit mode?)... */ + /* This assume that layer is always up to date, not sure this is the case + * (esp. in Edit mode?)... */ polynors = CustomData_get_layer(&mesh->pdata, CD_NORMAL); free_polynors = false; } @@ -1683,8 +1746,9 @@ static int split_faces_prepare_new_verts(const Mesh *mesh, SplitFaceNewVert **new_verts, MemArena *memarena) { - /* This is now mandatory, trying to do the job in simple way without that data is doomed to fail, even when only - * dealing with smooth/flat faces one can find cases that no simple algorithm can handle properly. */ + /* This is now mandatory, trying to do the job in simple way without that data is doomed to fail, + * even when only dealing with smooth/flat faces one can find cases that no simple algorithm + * can handle properly. */ BLI_assert(lnors_spacearr != NULL); const int loops_len = mesh->totloop; @@ -1730,8 +1794,9 @@ static int split_faces_prepare_new_verts(const Mesh *mesh, if (!vert_used) { BLI_BITMAP_ENABLE(verts_used, vert_idx); /* We need to update that vertex's normal here, we won't go over it again. */ - /* This is important! *DO NOT* set vnor to final computed lnor, vnor should always be defined to - * 'automatic normal' value computed from its polys, not some custom normal. + /* This is important! *DO NOT* set vnor to final computed lnor, + * vnor should always be defined to 'automatic normal' value computed from its polys, + * not some custom normal. * Fortunately, that's the loop normal space's 'lnor' reference vector. ;) */ normal_float_to_short_v3(mvert[vert_idx].no, (*lnor_space)->vec_lnor); } @@ -1883,8 +1948,9 @@ void BKE_mesh_split_faces(Mesh *mesh, bool free_loop_normals) mesh, &lnors_spacearr, &new_verts, memarena); if (num_new_verts > 0) { - /* Reminder: beyond this point, there is no way out, mesh is in invalid state (due to early-reassignment of - * loops' vertex and edge indices to new, to-be-created split ones). */ + /* Reminder: beyond this point, there is no way out, mesh is in invalid state + * (due to early-reassignment of loops' vertex and edge indices to new, + * to-be-created split ones). */ const int num_new_edges = split_faces_prepare_new_edges(mesh, &new_edges, memarena); /* We can have to split a vertex without having to add a single new edge... */ diff --git a/source/blender/blenkernel/intern/mesh_convert.c b/source/blender/blenkernel/intern/mesh_convert.c index 6f96267ff55..3f4e504867c 100644 --- a/source/blender/blenkernel/intern/mesh_convert.c +++ b/source/blender/blenkernel/intern/mesh_convert.c @@ -77,8 +77,9 @@ void BKE_mesh_from_metaball(ListBase *lb, Mesh *me) int a, *index; dl = lb->first; - if (dl == NULL) + if (dl == NULL) { return; + } if (dl->type == DL_INDEX4) { mvert = CustomData_add_layer(&me->vdata, CD_MVERT, CD_CALLOC, NULL, dl->nr); @@ -109,8 +110,9 @@ void BKE_mesh_from_metaball(ListBase *lb, Mesh *me) mloop[0].v = index[0]; mloop[1].v = index[1]; mloop[2].v = index[2]; - if (count == 4) + if (count == 4) { mloop[3].v = index[3]; + } mpoly->totloop = count; mpoly->loopstart = (int)(mloop - allloop); @@ -307,8 +309,9 @@ int BKE_mesh_nurbs_displist_to_mdata(Object *ob, totpoly, 4 * sizeof(MLoop), "nurbs_init mloop"); // totloop *r_allpoly = mpoly = MEM_calloc_arrayN(totpoly, sizeof(MPoly), "nurbs_init mloop"); - if (r_alluv) + if (r_alluv) { *r_alluv = mloopuv = MEM_calloc_arrayN(totpoly, 4 * sizeof(MLoopUV), "nurbs_init mloopuv"); + } /* verts and faces */ vertcount = 0; @@ -355,10 +358,12 @@ int BKE_mesh_nurbs_displist_to_mdata(Object *ob, ofs = a * dl->nr; for (b = 0; b < dl->nr; b++) { medge->v1 = startvert + ofs + b; - if (b == dl->nr - 1) + if (b == dl->nr - 1) { medge->v2 = startvert + ofs; - else + } + else { medge->v2 = startvert + ofs + b + 1; + } medge->flag = ME_LOOSEEDGE | ME_EDGERENDER | ME_EDGEDRAW; medge++; } @@ -395,8 +400,9 @@ int BKE_mesh_nurbs_displist_to_mdata(Object *ob, } } - if (is_smooth) + if (is_smooth) { mpoly->flag |= ME_SMOOTH; + } mpoly++; mloop += 3; index += 3; @@ -415,8 +421,9 @@ int BKE_mesh_nurbs_displist_to_mdata(Object *ob, for (a = 0; a < dl->parts; a++) { - if ((dl->flag & DL_CYCL_V) == 0 && a == dl->parts - 1) + if ((dl->flag & DL_CYCL_V) == 0 && a == dl->parts - 1) { break; + } if (dl->flag & DL_CYCL_U) { /* p2 -> p1 -> */ p1 = startvert + dl->nr * a; /* p4 -> p3 -> */ @@ -454,8 +461,9 @@ int BKE_mesh_nurbs_displist_to_mdata(Object *ob, /* exception as handled in convertblender.c too */ if (dl->flag & DL_CYCL_U) { orco_sizeu++; - if (dl->flag & DL_CYCL_V) + if (dl->flag & DL_CYCL_V) { orco_sizev++; + } } else if (dl->flag & DL_CYCL_V) { orco_sizev++; @@ -469,15 +477,18 @@ int BKE_mesh_nurbs_displist_to_mdata(Object *ob, mloopuv->uv[1] = (v % dl->nr) / (float)orco_sizeu; /* cyclic correction */ - if ((i == 1 || i == 2) && mloopuv->uv[0] == 0.0f) + if ((i == 1 || i == 2) && mloopuv->uv[0] == 0.0f) { mloopuv->uv[0] = 1.0f; - if ((i == 0 || i == 1) && mloopuv->uv[1] == 0.0f) + } + if ((i == 0 || i == 1) && mloopuv->uv[1] == 0.0f) { mloopuv->uv[1] = 1.0f; + } } } - if (is_smooth) + if (is_smooth) { mpoly->flag |= ME_SMOOTH; + } mpoly++; mloop += 4; @@ -645,7 +656,8 @@ void BKE_mesh_from_nurbs_displist(Main *bmain, cu->mat = NULL; cu->totcol = 0; - /* Do not decrement ob->data usercount here, it's done at end of func with BKE_id_free_us() call. */ + /* Do not decrement ob->data usercount here, + * it's done at end of func with BKE_id_free_us() call. */ ob->data = me; ob->type = OB_MESH; @@ -974,8 +986,9 @@ Mesh *BKE_mesh_new_from_object(Depsgraph *depsgraph, } /* if getting the original caged mesh, delete object modifiers */ - if (cage) + if (cage) { BKE_object_free_modifiers(tmpobj, LIB_ID_CREATE_NO_USER_REFCOUNT); + } /* copies the data, but *not* the shapekeys. */ BKE_id_copy_ex(NULL, object_for_eval.data, (ID **)©cu, LIB_ID_COPY_LOCALIZE); @@ -1024,9 +1037,10 @@ Mesh *BKE_mesh_new_from_object(Depsgraph *depsgraph, BKE_id_free(NULL, tmpobj); - /* XXX The curve to mesh conversion is convoluted... But essentially, BKE_mesh_from_nurbs_displist() - * already transfers the ownership of materials from the temp copy of the Curve ID to the new - * Mesh ID, so we do not want to increase materials' usercount later. */ + /* XXX The curve to mesh conversion is convoluted... + * But essentially, BKE_mesh_from_nurbs_displist() + * already transfers the ownership of materials from the temp copy of the Curve ID to the + * new Mesh ID, so we do not want to increase materials' usercount later. */ do_mat_id_data_us = false; break; @@ -1182,8 +1196,9 @@ static void add_shapekey_layers(Mesh *mesh_dest, Mesh *mesh_src) Key *key = mesh_src->key; int i; - if (!mesh_src->key) + if (!mesh_src->key) { return; + } /* ensure we can use mesh vertex count for derived mesh custom data */ if (mesh_src->totvert != mesh_dest->totvert) { @@ -1223,25 +1238,26 @@ static void add_shapekey_layers(Mesh *mesh_dest, Mesh *mesh_src) Mesh *BKE_mesh_create_derived_for_modifier(struct Depsgraph *depsgraph, Scene *scene, - Object *ob, - ModifierData *md, + Object *ob_eval, + ModifierData *md_eval, int build_shapekey_layers) { - Mesh *me = ob->runtime.mesh_orig ? ob->runtime.mesh_orig : ob->data; - const ModifierTypeInfo *mti = modifierType_getInfo(md->type); + Mesh *me = ob_eval->runtime.mesh_orig ? ob_eval->runtime.mesh_orig : ob_eval->data; + const ModifierTypeInfo *mti = modifierType_getInfo(md_eval->type); Mesh *result; KeyBlock *kb; - ModifierEvalContext mectx = {depsgraph, ob, 0}; + ModifierEvalContext mectx = {depsgraph, ob_eval, 0}; - if (!(md->mode & eModifierMode_Realtime)) { + if (!(md_eval->mode & eModifierMode_Realtime)) { return NULL; } - if (mti->isDisabled && mti->isDisabled(scene, md, 0)) { + if (mti->isDisabled && mti->isDisabled(scene, md_eval, 0)) { return NULL; } - if (build_shapekey_layers && me->key && (kb = BLI_findlink(&me->key->block, ob->shapenr - 1))) { + if (build_shapekey_layers && me->key && + (kb = BLI_findlink(&me->key->block, ob_eval->shapenr - 1))) { BKE_keyblock_convert_to_mesh(kb, me); } @@ -1249,12 +1265,13 @@ Mesh *BKE_mesh_create_derived_for_modifier(struct Depsgraph *depsgraph, int numVerts; float(*deformedVerts)[3] = BKE_mesh_vertexCos_get(me, &numVerts); - mti->deformVerts(md, &mectx, NULL, deformedVerts, numVerts); BKE_id_copy_ex(NULL, &me->id, (ID **)&result, LIB_ID_COPY_LOCALIZE); + mti->deformVerts(md_eval, &mectx, result, deformedVerts, numVerts); BKE_mesh_apply_vert_coords(result, deformedVerts); - if (build_shapekey_layers) + if (build_shapekey_layers) { add_shapekey_layers(result, me); + } MEM_freeN(deformedVerts); } @@ -1262,10 +1279,11 @@ Mesh *BKE_mesh_create_derived_for_modifier(struct Depsgraph *depsgraph, Mesh *mesh_temp; BKE_id_copy_ex(NULL, &me->id, (ID **)&mesh_temp, LIB_ID_COPY_LOCALIZE); - if (build_shapekey_layers) + if (build_shapekey_layers) { add_shapekey_layers(mesh_temp, me); + } - result = mti->applyModifier(md, &mectx, mesh_temp); + result = mti->applyModifier(md_eval, &mectx, mesh_temp); ASSERT_IS_VALID_MESH(result); if (mesh_temp != result) { @@ -1282,8 +1300,9 @@ static void shapekey_layers_to_keyblocks(Mesh *mesh_src, Mesh *mesh_dst, int act KeyBlock *kb; int i, j, tot; - if (!mesh_dst->key) + if (!mesh_dst->key) { return; + } tot = CustomData_number_of_layers(&mesh_src->vdata, CD_SHAPEKEY); for (i = 0; i < tot; i++) { @@ -1292,8 +1311,9 @@ static void shapekey_layers_to_keyblocks(Mesh *mesh_src, Mesh *mesh_dst, int act float(*cos)[3], (*kbcos)[3]; for (kb = mesh_dst->key->block.first; kb; kb = kb->next) { - if (kb->uid == layer->uid) + if (kb->uid == layer->uid) { break; + } } if (!kb) { @@ -1301,8 +1321,9 @@ static void shapekey_layers_to_keyblocks(Mesh *mesh_src, Mesh *mesh_dst, int act kb->uid = layer->uid; } - if (kb->data) + if (kb->data) { MEM_freeN(kb->data); + } cos = CustomData_get_layer_n(&mesh_src->vdata, CD_SHAPEKEY, i); kb->totelem = mesh_src->totvert; @@ -1324,8 +1345,9 @@ static void shapekey_layers_to_keyblocks(Mesh *mesh_src, Mesh *mesh_dst, int act for (kb = mesh_dst->key->block.first; kb; kb = kb->next) { if (kb->totelem != mesh_src->totvert) { - if (kb->data) + if (kb->data) { MEM_freeN(kb->data); + } kb->totelem = mesh_src->totvert; kb->data = MEM_calloc_arrayN(kb->totelem, 3 * sizeof(float), __func__); @@ -1342,7 +1364,8 @@ void BKE_mesh_nomain_to_mesh(Mesh *mesh_src, bool take_ownership) { /* mesh_src might depend on mesh_dst, so we need to do everything with a local copy */ - /* TODO(Sybren): the above claim came from DM_to_mesh(); check whether it is still true with Mesh */ + /* TODO(Sybren): the above claim came from DM_to_mesh(); + * check whether it is still true with Mesh */ Mesh tmp = *mesh_dst; int totvert, totedge /*, totface */ /* UNUSED */, totloop, totpoly; int did_shapekeys = 0; @@ -1410,8 +1433,8 @@ void BKE_mesh_nomain_to_mesh(Mesh *mesh_src, /* not all DerivedMeshes store their verts/edges/faces in CustomData, so * we set them here in case they are missing */ - /* TODO(Sybren): we could probably replace CD_ASSIGN with alloctype and always directly pass mesh_src->mxxx, - * instead of using a ternary operator. */ + /* TODO(Sybren): we could probably replace CD_ASSIGN with alloctype and + * always directly pass mesh_src->mxxx, instead of using a ternary operator. */ if (!CustomData_has_layer(&tmp.vdata, CD_MVERT)) { CustomData_add_layer(&tmp.vdata, CD_MVERT, @@ -1504,8 +1527,9 @@ void BKE_mesh_nomain_to_meshkey(Mesh *mesh_src, Mesh *mesh_dst, KeyBlock *kb) return; } - if (kb->data) + if (kb->data) { MEM_freeN(kb->data); + } kb->data = MEM_malloc_arrayN(mesh_dst->key->elemsize, mesh_dst->totvert, "kb->data"); kb->totelem = totvert; diff --git a/source/blender/blenkernel/intern/mesh_evaluate.c b/source/blender/blenkernel/intern/mesh_evaluate.c index 2ef1a009321..d889fca3a3a 100644 --- a/source/blender/blenkernel/intern/mesh_evaluate.c +++ b/source/blender/blenkernel/intern/mesh_evaluate.c @@ -165,9 +165,11 @@ void BKE_mesh_calc_normals_mapping_ex(MVert *mverts, return; } - if (!pnors) + if (!pnors) { pnors = MEM_calloc_arrayN((size_t)numPolys, sizeof(float[3]), __func__); - /* if (!fnors) fnors = MEM_calloc_arrayN(numFaces, sizeof(float[3]), "face nors mesh.c"); */ /* NO NEED TO ALLOC YET */ + } + /* NO NEED TO ALLOC YET */ + /* if (!fnors) fnors = MEM_calloc_arrayN(numFaces, sizeof(float[3]), "face nors mesh.c"); */ if (only_face_normals == false) { /* vertex normals are optional, they require some extra calculations, @@ -199,8 +201,9 @@ void BKE_mesh_calc_normals_mapping_ex(MVert *mverts, } } - if (pnors != r_polyNors) + if (pnors != r_polyNors) { MEM_freeN(pnors); + } /* if (fnors != r_faceNors) MEM_freeN(fnors); */ /* NO NEED TO ALLOC YET */ fnors = pnors = NULL; @@ -364,7 +367,8 @@ void BKE_mesh_calc_normals_poly(MVert *mverts, BLI_task_parallel_range(0, numPolys, &data, mesh_calc_normals_poly_prepare_cb, &settings); /* Actually accumulate weighted loop normals into vertex ones. */ - /* Unfortunately, not possible to thread that (not in a reasonable, totally lock- and barrier-free fashion), + /* Unfortunately, not possible to thread that + * (not in a reasonable, totally lock- and barrier-free fashion), * since several loops will point to the same vertex... */ for (int lidx = 0; lidx < numLoops; lidx++) { add_v3_v3(vnors[mloop[lidx].v], data.lnors_weighted[lidx]); @@ -422,7 +426,8 @@ void BKE_mesh_ensure_normals_for_display(Mesh *mesh) } } -/* Note that this does not update the CD_NORMAL layer, but does update the normals in the CD_MVERT layer. */ +/* Note that this does not update the CD_NORMAL layer, + * but does update the normals in the CD_MVERT layer. */ void BKE_mesh_calc_normals(Mesh *mesh) { #ifdef DEBUG_TIME @@ -462,11 +467,13 @@ void BKE_mesh_calc_normals_tessface( float *n4 = (mf->v4) ? tnorms[mf->v4] : NULL; const float *c4 = (mf->v4) ? mverts[mf->v4].co : NULL; - if (mf->v4) + if (mf->v4) { normal_quad_v3( f_no, mverts[mf->v1].co, mverts[mf->v2].co, mverts[mf->v3].co, mverts[mf->v4].co); - else + } + else { normal_tri_v3(f_no, mverts[mf->v1].co, mverts[mf->v2].co, mverts[mf->v3].co); + } accumulate_vertex_normals_v3(tnorms[mf->v1], tnorms[mf->v2], @@ -494,8 +501,9 @@ void BKE_mesh_calc_normals_tessface( cleanup: MEM_freeN(tnorms); - if (fnors != r_faceNors) + if (fnors != r_faceNors) { MEM_freeN(fnors); + } } void BKE_mesh_calc_normals_looptri(MVert *mverts, @@ -550,8 +558,9 @@ void BKE_mesh_calc_normals_looptri(MVert *mverts, cleanup: MEM_freeN(tnorms); - if (fnors != r_tri_nors) + if (fnors != r_tri_nors) { MEM_freeN(fnors); + } } void BKE_lnor_spacearr_init(MLoopNorSpaceArray *lnors_spacearr, @@ -603,7 +612,8 @@ MLoopNorSpace *BKE_lnor_space_create(MLoopNorSpaceArray *lnors_spacearr) /* Should only be called once. * Beware, this modifies ref_vec and other_vec in place! - * In case no valid space can be generated, ref_alpha and ref_beta are set to zero (which means 'use auto lnors'). + * In case no valid space can be generated, ref_alpha and ref_beta are set to zero + * (which means 'use auto lnors'). */ void BKE_lnor_space_define(MLoopNorSpace *lnor_space, const float lnor[3], @@ -640,8 +650,10 @@ void BKE_lnor_space_define(MLoopNorSpace *lnor_space, BLI_stack_discard(edge_vectors); nbr++; } - /* Note: In theory, this could be 'nbr > 2', but there is one case where we only have two edges for - * two loops: a smooth vertex with only two edges and two faces (our Monkey's nose has that, e.g.). */ + /* Note: In theory, this could be 'nbr > 2', + * but there is one case where we only have two edges for two loops: + * a smooth vertex with only two edges and two faces (our Monkey's nose has that, e.g.). + */ BLI_assert(nbr >= 2); /* This piece of code shall only be called for more than one loop... */ lnor_space->ref_alpha = alpha / (float)nbr; } @@ -677,10 +689,11 @@ void BKE_lnor_space_define(MLoopNorSpace *lnor_space, /** * Add a new given loop to given lnor_space. - * Depending on \a lnor_space->data_type, we expect \a bm_loop to be a pointer to BMLoop struct (in case of BMLOOP_PTR), - * or NULL (in case of LOOP_INDEX), loop index is then stored in pointer. - * If \a is_single is set, the BMLoop or loop index is directly stored in \a lnor_space->loops pointer (since there - * is only one loop in this fan), else it is added to the linked list of loops in the fan. + * Depending on \a lnor_space->data_type, we expect \a bm_loop to be a pointer to BMLoop struct + * (in case of BMLOOP_PTR), or NULL (in case of LOOP_INDEX), loop index is then stored in pointer. + * If \a is_single is set, the BMLoop or loop index is directly stored in \a lnor_space->loops + * pointer (since there is only one loop in this fan), + * else it is added to the linked list of loops in the fan. */ void BKE_lnor_space_add_loop(MLoopNorSpaceArray *lnors_spacearr, MLoopNorSpace *lnor_space, @@ -769,7 +782,8 @@ void BKE_lnor_space_custom_normal_to_data(MLoopNorSpace *lnor_space, alpha = saacosf(cos_alpha); if (alpha > lnor_space->ref_alpha) { - /* Note we could stick to [0, pi] range here, but makes decoding more complex, not worth it. */ + /* Note we could stick to [0, pi] range here, + * but makes decoding more complex, not worth it. */ r_clnor_data[0] = unit_float_to_short(-(pi2 - alpha) / (pi2 - lnor_space->ref_alpha)); } else { @@ -806,17 +820,20 @@ void BKE_lnor_space_custom_normal_to_data(MLoopNorSpace *lnor_space, typedef struct LoopSplitTaskData { /* Specific to each instance (each task). */ - MLoopNorSpace * - lnor_space; /* We have to create those outside of tasks, since afaik memarena is not threadsafe. */ + + /** We have to create those outside of tasks, since afaik memarena is not threadsafe. */ + MLoopNorSpace *lnor_space; float (*lnor)[3]; const MLoop *ml_curr; const MLoop *ml_prev; int ml_curr_index; int ml_prev_index; - const int *e2l_prev; /* Also used a flag to switch between single or fan process! */ + /** Also used a flag to switch between single or fan process! */ + const int *e2l_prev; int mp_index; - /* This one is special, it's owned and managed by worker tasks, avoid to have to create it for each fan! */ + /** This one is special, it's owned and managed by worker tasks, + * avoid to have to create it for each fan! */ BLI_Stack *edge_vectors; char pad_c; @@ -824,8 +841,8 @@ typedef struct LoopSplitTaskData { typedef struct LoopSplitTaskDataCommon { /* Read/write. - * Note we do not need to protect it, though, since two different tasks will *always* affect different - * elements in the arrays. */ + * Note we do not need to protect it, though, since two different tasks will *always* affect + * different elements in the arrays. */ MLoopNorSpaceArray *lnors_spacearr; float (*loopnors)[3]; short (*clnors_data)[2]; @@ -889,8 +906,8 @@ static void mesh_edges_sharp_tag(LoopSplitTaskDataCommon *data, loop_to_poly[ml_curr_index] = mp_index; - /* Pre-populate all loop normals as if their verts were all-smooth, this way we don't have to compute - * those later! + /* Pre-populate all loop normals as if their verts were all-smooth, + * this way we don't have to compute those later! */ if (loopnors) { normal_short_to_float_v3(loopnors[ml_curr_index], mverts[ml_curr->v].no); @@ -910,8 +927,8 @@ static void mesh_edges_sharp_tag(LoopSplitTaskDataCommon *data, /* Second loop using this edge, time to test its sharpness. * An edge is sharp if it is tagged as such, or its face is not smooth, - * or both poly have opposed (flipped) normals, i.e. both loops on the same edge share the same vertex, - * or angle between both its polys' normals is above split_angle value. + * or both poly have opposed (flipped) normals, i.e. both loops on the same edge share the + * same vertex, or angle between both its polys' normals is above split_angle value. */ if (!(mp->flag & ME_SMOOTH) || (medges[ml_curr->e].flag & ME_SHARP) || ml_curr->v == mloops[e2l[0]].v || is_angle_sharp) { @@ -958,7 +975,8 @@ static void mesh_edges_sharp_tag(LoopSplitTaskDataCommon *data, /** Define sharp edges as needed to mimic 'autosmooth' from angle threshold. * - * Used when defining an empty custom loop normals data layer, to keep same shading as with autosmooth! + * Used when defining an empty custom loop normals data layer, + * to keep same shading as with autosmooth! */ void BKE_edges_sharp_from_angle_set(const struct MVert *mverts, const int UNUSED(numVerts), @@ -1073,7 +1091,13 @@ static void split_loop_nor_single_do(LoopSplitTaskDataCommon *common_data, LoopS */ copy_v3_v3(*lnor, polynors[mp_index]); - // printf("BASIC: handling loop %d / edge %d / vert %d / poly %d\n", ml_curr_index, ml_curr->e, ml_curr->v, mp_index); +#if 0 + printf("BASIC: handling loop %d / edge %d / vert %d / poly %d\n", + ml_curr_index, + ml_curr->e, + ml_curr->v, + mp_index); +#endif /* If needed, generate this (simple!) lnor space. */ if (lnors_spacearr) { @@ -1094,7 +1118,8 @@ static void split_loop_nor_single_do(LoopSplitTaskDataCommon *common_data, LoopS normalize_v3(vec_prev); BKE_lnor_space_define(lnor_space, *lnor, vec_curr, vec_prev, NULL); - /* We know there is only one loop in this space, no need to create a linklist in this case... */ + /* We know there is only one loop in this space, + * no need to create a linklist in this case... */ BKE_lnor_space_add_loop(lnors_spacearr, lnor_space, ml_curr_index, NULL, true); if (clnors_data) { @@ -1119,7 +1144,7 @@ static void split_loop_nor_fan_do(LoopSplitTaskDataCommon *common_data, LoopSpli MLoopNorSpace *lnor_space = data->lnor_space; #if 0 /* Not needed for 'fan' loops. */ - float (*lnor)[3] = data->lnor; + float(*lnor)[3] = data->lnor; #endif const MLoop *ml_curr = data->ml_curr; const MLoop *ml_prev = data->ml_prev; @@ -1132,10 +1157,10 @@ static void split_loop_nor_fan_do(LoopSplitTaskDataCommon *common_data, LoopSpli /* Gah... We have to fan around current vertex, until we find the other non-smooth edge, * and accumulate face normals into the vertex! - * Note in case this vertex has only one sharp edges, this is a waste because the normal is the same as - * the vertex normal, but I do not see any easy way to detect that (would need to count number - * of sharp edges per vertex, I doubt the additional memory usage would be worth it, especially as - * it should not be a common case in real-life meshes anyway). + * Note in case this vertex has only one sharp edges, this is a waste because the normal is the + * same as the vertex normal, but I do not see any easy way to detect that (would need to count + * number of sharp edges per vertex, I doubt the additional memory usage would be worth it, + * especially as it should not be a common case in real-life meshes anyway). */ const unsigned int mv_pivot_index = ml_curr->v; /* The vertex we are "fanning" around! */ const MVert *mv_pivot = &mverts[mv_pivot_index]; @@ -1187,8 +1212,8 @@ static void split_loop_nor_fan_do(LoopSplitTaskDataCommon *common_data, LoopSpli while (true) { const MEdge *me_curr = &medges[mlfan_curr->e]; /* Compute edge vectors. - * NOTE: We could pre-compute those into an array, in the first iteration, instead of computing them - * twice (or more) here. However, time gained is not worth memory and time lost, + * NOTE: We could pre-compute those into an array, in the first iteration, instead of computing + * them twice (or more) here. However, time gained is not worth memory and time lost, * given the fact that this code should not be called that much in real-life meshes... */ { @@ -1287,13 +1312,14 @@ static void split_loop_nor_fan_do(LoopSplitTaskDataCommon *common_data, LoopSpli printf("Invalid clnors in this fan!\n"); } while ((clnor = BLI_SMALLSTACK_POP(clnors))) { - //print_v2("org clnor", clnor); + // print_v2("org clnor", clnor); clnor[0] = (short)clnors_avg[0]; clnor[1] = (short)clnors_avg[1]; } - //print_v2("new clnors", clnors_avg); + // print_v2("new clnors", clnors_avg); } - /* Extra bonus: since smallstack is local to this func, no more need to empty it at all cost! */ + /* Extra bonus: since smallstack is local to this func, + * no more need to empty it at all cost! */ BKE_lnor_space_custom_data_to_normal(lnor_space, *clnor_ref, lnor); } @@ -1308,7 +1334,8 @@ static void split_loop_nor_fan_do(LoopSplitTaskDataCommon *common_data, LoopSpli copy_v3_v3(nor, lnor); } } - /* Extra bonus: since smallstack is local to this func, no more need to empty it at all cost! */ + /* Extra bonus: since smallstack is local to this func, + * no more need to empty it at all cost! */ } } @@ -1361,7 +1388,8 @@ static void loop_split_worker(TaskPool *__restrict pool, void *taskdata, int UNU } /* Check whether gievn loop is part of an unknown-so-far cyclic smooth fan, or not. - * Needed because cyclic smooth fans have no obvious 'entry point', and yet we need to walk them once, and only once. */ + * Needed because cyclic smooth fans have no obvious 'entry point', + * and yet we need to walk them once, and only once. */ static bool loop_split_generator_check_cyclic_smooth_fan(const MLoop *mloops, const MPoly *mpolys, const int (*edge_to_loops)[2], @@ -1419,8 +1447,8 @@ static bool loop_split_generator_check_cyclic_smooth_fan(const MLoop *mloops, /* Smooth loop/edge... */ else if (BLI_BITMAP_TEST(skip_loops, mlfan_vert_index)) { if (mlfan_vert_index == ml_curr_index) { - /* We walked around a whole cyclic smooth fan without finding any already-processed loop, means we can - * use initial ml_curr/ml_prev edge as start for this smooth fan. */ + /* We walked around a whole cyclic smooth fan without finding any already-processed loop, + * means we can use initial ml_curr/ml_prev edge as start for this smooth fan. */ return true; } /* ... already checked in some previous looping, we can abort. */ @@ -1458,7 +1486,8 @@ static void loop_split_generator(TaskPool *pool, LoopSplitTaskDataCommon *common LoopSplitTaskData *data_buff = NULL; int data_idx = 0; - /* Temp edge vectors stack, only used when computing lnor spacearr (and we are not multi-threading). */ + /* Temp edge vectors stack, only used when computing lnor spacearr + * (and we are not multi-threading). */ BLI_Stack *edge_vectors = NULL; #ifdef DEBUG_TIME @@ -1471,8 +1500,8 @@ static void loop_split_generator(TaskPool *pool, LoopSplitTaskDataCommon *common } } - /* We now know edges that can be smoothed (with their vector, and their two loops), and edges that will be hard! - * Now, time to generate the normals. + /* We now know edges that can be smoothed (with their vector, and their two loops), + * and edges that will be hard! Now, time to generate the normals. */ for (mp = mpolys, mp_index = 0; mp_index < numPolys; mp++, mp_index++) { float(*lnors)[3]; @@ -1488,17 +1517,25 @@ static void loop_split_generator(TaskPool *pool, LoopSplitTaskDataCommon *common const int *e2l_curr = edge_to_loops[ml_curr->e]; const int *e2l_prev = edge_to_loops[ml_prev->e]; - // printf("Checking loop %d / edge %u / vert %u (sharp edge: %d, skiploop: %d)...", - // ml_curr_index, ml_curr->e, ml_curr->v, IS_EDGE_SHARP(e2l_curr), BLI_BITMAP_TEST_BOOL(skip_loops, ml_curr_index)); +#if 0 + printf("Checking loop %d / edge %u / vert %u (sharp edge: %d, skiploop: %d)...", + ml_curr_index, + ml_curr->e, + ml_curr->v, + IS_EDGE_SHARP(e2l_curr), + BLI_BITMAP_TEST_BOOL(skip_loops, ml_curr_index)); +#endif /* A smooth edge, we have to check for cyclic smooth fan case. - * If we find a new, never-processed cyclic smooth fan, we can do it now using that loop/edge as - * 'entry point', otherwise we can skip it. */ + * If we find a new, never-processed cyclic smooth fan, we can do it now using that loop/edge + * as 'entry point', otherwise we can skip it. */ + /* Note: In theory, we could make loop_split_generator_check_cyclic_smooth_fan() store - * mlfan_vert_index'es and edge indexes in two stacks, to avoid having to fan again around the vert during - * actual computation of clnor & clnorspace. However, this would complicate the code, add more memory usage, - * and despite its logical complexity, loop_manifold_fan_around_vert_next() is quite cheap in term of - * CPU cycles, so really think it's not worth it. */ + * mlfan_vert_index'es and edge indexes in two stacks, to avoid having to fan again around + * the vert during actual computation of clnor & clnorspace. However, this would complicate + * the code, add more memory usage, and despite its logical complexity, + * loop_manifold_fan_around_vert_next() is quite cheap in term of CPU cycles, + * so really think it's not worth it. */ if (!IS_EDGE_SHARP(e2l_curr) && (BLI_BITMAP_TEST(skip_loops, ml_curr_index) || !loop_split_generator_check_cyclic_smooth_fan(mloops, mpolys, @@ -1537,7 +1574,7 @@ static void loop_split_generator(TaskPool *pool, LoopSplitTaskDataCommon *common data->ml_curr_index = ml_curr_index; #if 0 /* Not needed for 'single' loop. */ data->ml_prev_index = ml_prev_index; - data->e2l_prev = NULL; /* Tag as 'single' task. */ + data->e2l_prev = NULL; /* Tag as 'single' task. */ #endif data->mp_index = mp_index; if (lnors_spacearr) { @@ -1545,10 +1582,11 @@ static void loop_split_generator(TaskPool *pool, LoopSplitTaskDataCommon *common } } /* We *do not need* to check/tag loops as already computed! - * Due to the fact a loop only links to one of its two edges, a same fan *will never be walked - * more than once!* - * Since we consider edges having neighbor polys with inverted (flipped) normals as sharp, we are sure - * that no fan will be skipped, even only considering the case (sharp curr_edge, smooth prev_edge), + * Due to the fact a loop only links to one of its two edges, + * a same fan *will never be walked more than once!* + * Since we consider edges having neighbor polys with inverted + * (flipped) normals as sharp, we are sure that no fan will be skipped, + * even only considering the case (sharp curr_edge, smooth prev_edge), * and not the alternative (smooth curr_edge, sharp prev_edge). * All this due/thanks to link between normals and loop ordering (i.e. winding). */ @@ -1584,7 +1622,8 @@ static void loop_split_generator(TaskPool *pool, LoopSplitTaskDataCommon *common } } - /* Last block of data... Since it is calloc'ed and we use first NULL item as stopper, everything is fine. */ + /* Last block of data... Since it is calloc'ed and we use first NULL item as stopper, + * everything is fine. */ if (pool && data_idx) { BLI_task_pool_push(pool, loop_split_worker, data_buff, true, TASK_PRIORITY_LOW); } @@ -1601,7 +1640,8 @@ static void loop_split_generator(TaskPool *pool, LoopSplitTaskDataCommon *common /** * Compute split normals, i.e. vertex normals associated with each poly (hence 'loop normals'). - * Useful to materialize sharp edges (or non-smooth faces) without actually modifying the geometry (splitting edges). + * Useful to materialize sharp edges (or non-smooth faces) without actually modifying the geometry + * (splitting edges). */ void BKE_mesh_normals_loop_split(const MVert *mverts, const int UNUSED(numVerts), @@ -1619,14 +1659,17 @@ void BKE_mesh_normals_loop_split(const MVert *mverts, short (*clnors_data)[2], int *r_loop_to_poly) { - /* For now this is not supported. If we do not use split normals, we do not generate anything fancy! */ + /* For now this is not supported. + * If we do not use split normals, we do not generate anything fancy! */ BLI_assert(use_split_normals || !(r_lnors_spacearr)); if (!use_split_normals) { /* In this case, we simply fill lnors with vnors (or fnors for flat faces), quite simple! * Note this is done here to keep some logic and consistency in this quite complex code, - * since we may want to use lnors even when mesh's 'autosmooth' is disabled (see e.g. mesh mapping code). - * As usual, we could handle that on case-by-case basis, but simpler to keep it well confined here. + * since we may want to use lnors even when mesh's 'autosmooth' is disabled + * (see e.g. mesh mapping code). + * As usual, we could handle that on case-by-case basis, + * but simpler to keep it well confined here. */ int mp_index; @@ -1651,15 +1694,20 @@ void BKE_mesh_normals_loop_split(const MVert *mverts, return; } - /* Mapping edge -> loops. - * If that edge is used by more than two loops (polys), it is always sharp (and tagged as such, see below). - * We also use the second loop index as a kind of flag: smooth edge: > 0, - * sharp edge: < 0 (INDEX_INVALID || INDEX_UNSET), - * unset: INDEX_UNSET - * Note that currently we only have two values for second loop of sharp edges. However, if needed, we can - * store the negated value of loop index instead of INDEX_INVALID to retrieve the real value later in code). - * Note also that lose edges always have both values set to 0! - */ + /** + * Mapping edge -> loops. + * If that edge is used by more than two loops (polys), + * it is always sharp (and tagged as such, see below). + * We also use the second loop index as a kind of flag: + * + * - smooth edge: > 0. + * - sharp edge: < 0 (INDEX_INVALID || INDEX_UNSET). + * - unset: INDEX_UNSET. + * + * Note that currently we only have two values for second loop of sharp edges. + * However, if needed, we can store the negated value of loop index instead of INDEX_INVALID + * to retrieve the real value later in code). + * Note also that lose edges always have both values set to 0! */ int(*edge_to_loops)[2] = MEM_calloc_arrayN((size_t)numEdges, sizeof(*edge_to_loops), __func__); /* Simple mapping from a loop to its polygon index. */ @@ -1744,12 +1792,12 @@ void BKE_mesh_normals_loop_split(const MVert *mverts, /** * Compute internal representation of given custom normals (as an array of float[2]). - * It also makes sure the mesh matches those custom normals, by setting sharp edges flag as needed to get a - * same custom lnor for all loops sharing a same smooth fan. + * It also makes sure the mesh matches those custom normals, by setting sharp edges flag as needed + * to get a same custom lnor for all loops sharing a same smooth fan. * If use_vertices if true, r_custom_loopnors is assumed to be per-vertex, not per-loop * (this allows to set whole vert's normals at once, useful in some cases). - * r_custom_loopnors is expected to have normalized normals, or zero ones, in which case they will be replaced - * by default loop/vertex normal. + * r_custom_loopnors is expected to have normalized normals, or zero ones, + * in which case they will be replaced by default loop/vertex normal. */ static void mesh_normals_loop_custom_set(const MVert *mverts, const int numVerts, @@ -1764,17 +1812,19 @@ static void mesh_normals_loop_custom_set(const MVert *mverts, short (*r_clnors_data)[2], const bool use_vertices) { - /* We *may* make that poor BKE_mesh_normals_loop_split() even more complex by making it handling that - * feature too, would probably be more efficient in absolute. + /* We *may* make that poor BKE_mesh_normals_loop_split() even more complex by making it handling + * that feature too, would probably be more efficient in absolute. * However, this function *is not* performance-critical, since it is mostly expected to be called - * by io addons when importing custom normals, and modifier (and perhaps from some editing tools later?). + * by io addons when importing custom normals, and modifier + * (and perhaps from some editing tools later?). * So better to keep some simplicity here, and just call BKE_mesh_normals_loop_split() twice! */ MLoopNorSpaceArray lnors_spacearr = {NULL}; BLI_bitmap *done_loops = BLI_BITMAP_NEW((size_t)numLoops, __func__); float(*lnors)[3] = MEM_calloc_arrayN((size_t)numLoops, sizeof(*lnors), __func__); int *loop_to_poly = MEM_malloc_arrayN((size_t)numLoops, sizeof(int), __func__); - /* In this case we always consider split nors as ON, and do not want to use angle to define smooth fans! */ + /* In this case we always consider split nors as ON, + * and do not want to use angle to define smooth fans! */ const bool use_split_normals = true; const float split_angle = (float)M_PI; int i; @@ -1816,12 +1866,12 @@ static void mesh_normals_loop_custom_set(const MVert *mverts, BLI_assert(lnors_spacearr.data_type == MLNOR_SPACEARR_LOOP_INDEX); - /* Now, check each current smooth fan (one lnor space per smooth fan!), and if all its matching custom lnors - * are not (enough) equal, add sharp edges as needed. - * This way, next time we run BKE_mesh_normals_loop_split(), we'll get lnor spacearr/smooth fans matching - * given custom lnors. - * Note this code *will never* unsharp edges! - * And quite obviously, when we set custom normals per vertices, running this is absolutely useless. + /* Now, check each current smooth fan (one lnor space per smooth fan!), + * and if all its matching custom lnors are not (enough) equal, add sharp edges as needed. + * This way, next time we run BKE_mesh_normals_loop_split(), we'll get lnor spacearr/smooth fans + * matching given custom lnors. + * Note this code *will never* unsharp edges! And quite obviously, + * when we set custom normals per vertices, running this is absolutely useless. */ if (!use_vertices) { for (i = 0; i < numLoops; i++) { @@ -1839,13 +1889,13 @@ static void mesh_normals_loop_custom_set(const MVert *mverts, if (!BLI_BITMAP_TEST(done_loops, i)) { /* Notes: - * * In case of mono-loop smooth fan, we have nothing to do. - * * Loops in this linklist are ordered (in reversed order compared to how they were discovered by - * BKE_mesh_normals_loop_split(), but this is not a problem). Which means if we find a - * mismatching clnor, we know all remaining loops will have to be in a new, different smooth fan/ - * lnor space. - * * In smooth fan case, we compare each clnor against a ref one, to avoid small differences adding - * up into a real big one in the end! + * * In case of mono-loop smooth fan, we have nothing to do. + * * Loops in this linklist are ordered (in reversed order compared to how they were + * discovered by BKE_mesh_normals_loop_split(), but this is not a problem). + * Which means if we find a mismatching clnor, + * we know all remaining loops will have to be in a new, different smooth fan/lnor space. + * * In smooth fan case, we compare each clnor against a ref one, + * to avoid small differences adding up into a real big one in the end! */ if (lnors_spacearr.lspacearr[i]->flags & MLNOR_SPACE_IS_SINGLE) { BLI_BITMAP_ENABLE(done_loops, i); @@ -1868,8 +1918,8 @@ static void mesh_normals_loop_custom_set(const MVert *mverts, else if (dot_v3v3(org_nor, nor) < LNOR_SPACE_TRIGO_THRESHOLD) { /* Current normal differs too much from org one, we have to tag the edge between * previous loop's face and current's one as sharp. - * We know those two loops do not point to the same edge, since we do not allow reversed winding - * in a same smooth fan. + * We know those two loops do not point to the same edge, + * since we do not allow reversed winding in a same smooth fan. */ const MPoly *mp = &mpolys[loop_to_poly[lidx]]; const MLoop *mlp = @@ -1884,7 +1934,8 @@ static void mesh_normals_loop_custom_set(const MVert *mverts, BLI_BITMAP_ENABLE(done_loops, lidx); } - /* We also have to check between last and first loops, otherwise we may miss some sharp edges here! + /* We also have to check between last and first loops, + * otherwise we may miss some sharp edges here! * This is just a simplified version of above while loop. * See T45984. */ loops = lnors_spacearr.lspacearr[i]->loops; @@ -1926,7 +1977,8 @@ static void mesh_normals_loop_custom_set(const MVert *mverts, BLI_bitmap_set_all(done_loops, true, (size_t)numLoops); } - /* And we just have to convert plain object-space custom normals to our lnor space-encoded ones. */ + /* And we just have to convert plain object-space custom normals to our + * lnor space-encoded ones. */ for (i = 0; i < numLoops; i++) { if (!lnors_spacearr.lspacearr[i]) { BLI_BITMAP_DISABLE(done_loops, i); @@ -1937,9 +1989,9 @@ static void mesh_normals_loop_custom_set(const MVert *mverts, } if (BLI_BITMAP_TEST_BOOL(done_loops, i)) { - /* Note we accumulate and average all custom normals in current smooth fan, to avoid getting different - * clnors data (tiny differences in plain custom normals can give rather huge differences in - * computed 2D factors). + /* Note we accumulate and average all custom normals in current smooth fan, + * to avoid getting different clnors data (tiny differences in plain custom normals can + * give rather huge differences in computed 2D factors). */ LinkNode *loops = lnors_spacearr.lspacearr[i]->loops; if (lnors_spacearr.lspacearr[i]->flags & MLNOR_SPACE_IS_SINGLE) { @@ -2086,7 +2138,8 @@ static void mesh_set_custom_normals(Mesh *mesh, float (*r_custom_nors)[3], const } /** - * Higher level functions hiding most of the code needed around call to #BKE_mesh_normals_loop_custom_set(). + * Higher level functions hiding most of the code needed around call to + * #BKE_mesh_normals_loop_custom_set(). * * \param r_custom_loopnors is not const, since code will replace zero_v3 normals there * with automatically computed vectors. @@ -2097,7 +2150,8 @@ void BKE_mesh_set_custom_normals(Mesh *mesh, float (*r_custom_loopnors)[3]) } /** - * Higher level functions hiding most of the code needed around call to #BKE_mesh_normals_loop_custom_from_vertices_set(). + * Higher level functions hiding most of the code needed around call to + * #BKE_mesh_normals_loop_custom_from_vertices_set(). * * \param r_custom_loopnors is not const, since code will replace zero_v3 normals there * with automatically computed vectors. @@ -2321,7 +2375,8 @@ float BKE_mesh_calc_poly_area(const MPoly *mpoly, const MLoop *loopstart, const } /** - * Calculate the volume and volume-weighted centroid of the volume formed by the polygon and the origin. + * Calculate the volume and volume-weighted centroid of the volume + * formed by the polygon and the origin. * Results will be negative if the origin is "outside" the polygon * (+ve normal side), but the polygon may be non-planar with no effect. * @@ -2333,8 +2388,8 @@ float BKE_mesh_calc_poly_area(const MPoly *mpoly, const MLoop *loopstart, const * - Volume is 6x actual volume, and centroid is 4x actual volume-weighted centroid * (so division can be done once at the end). * - Results will have bias if polygon is non-planar. - * - The resulting volume will only be correct if the mesh is manifold and has consistent face winding - * (non-contiguous face normals or holes in the mesh surface). + * - The resulting volume will only be correct if the mesh is manifold and has consistent + * face winding (non-contiguous face normals or holes in the mesh surface). */ static float mesh_calc_poly_volume_centroid(const MPoly *mpoly, const MLoop *loopstart, @@ -2363,7 +2418,8 @@ static float mesh_calc_poly_volume_centroid(const MPoly *mpoly, * of the triangle and the origin as the fourth vertex. * The centroid is simply the average of the 4 vertices. * - * Note that the vector is 4x the actual centroid so the division can be done once at the end. */ + * Note that the vector is 4x the actual centroid + * so the division can be done once at the end. */ for (uint j = 0; j < 3; j++) { r_cent[j] += tetra_volume * (v_pivot[j] + v_step1[j] + v_step2[j]); } @@ -2535,7 +2591,8 @@ bool BKE_mesh_center_of_surface(const Mesh *me, float r_cent[3]) } /** - * \note Mesh must be manifold with consistent face-winding, see #mesh_calc_poly_volume_centroid for details. + * \note Mesh must be manifold with consistent face-winding, + * see #mesh_calc_poly_volume_centroid for details. */ bool BKE_mesh_center_of_volume(const Mesh *me, float r_cent[3]) { @@ -2559,7 +2616,8 @@ bool BKE_mesh_center_of_volume(const Mesh *me, float r_cent[3]) /* otherwise we get NAN for 0 polys */ if (total_volume != 0.0f) { /* multiply by 0.25 to get the correct centroid */ - /* no need to divide volume by 6 as the centroid is weighted by 6x the volume, so it all cancels out */ + /* no need to divide volume by 6 as the centroid is weighted by 6x the volume, + * so it all cancels out. */ mul_v3_fl(r_cent, 0.25f / total_volume); } @@ -2590,8 +2648,9 @@ static bool mesh_calc_center_centroid_ex(const MVert *mverts, zero_v3(r_center); - if (looptri_num == 0) + if (looptri_num == 0) { return false; + } totweight = 0.0f; for (i = 0, lt = looptri; i < looptri_num; i++, lt++) { @@ -2606,8 +2665,9 @@ static bool mesh_calc_center_centroid_ex(const MVert *mverts, madd_v3_v3fl(r_center, v3->co, area); totweight += area; } - if (totweight == 0.0f) + if (totweight == 0.0f) { return false; + } mul_v3_fl(r_center, 1.0f / (3.0f * totweight)); @@ -2633,16 +2693,20 @@ void BKE_mesh_calc_volume(const MVert *mverts, float totvol; int i; - if (r_volume) + if (r_volume) { *r_volume = 0.0f; - if (r_center) + } + if (r_center) { zero_v3(r_center); + } - if (looptri_num == 0) + if (looptri_num == 0) { return; + } - if (!mesh_calc_center_centroid_ex(mverts, mverts_num, looptri, looptri_num, mloop, center)) + if (!mesh_calc_center_centroid_ex(mverts, mverts_num, looptri, looptri_num, mloop, center)) { return; + } totvol = 0.0f; @@ -2675,8 +2739,9 @@ void BKE_mesh_calc_volume(const MVert *mverts, /* Note: Factor 1/3 is applied once for all vertices here. * This also automatically negates the vector if totvol is negative. */ - if (totvol != 0.0f) + if (totvol != 0.0f) { mul_v3_fl(r_center, (1.0f / 3.0f) / totvol); + } } } @@ -2761,9 +2826,11 @@ void BKE_mesh_loops_to_mface_corners( /** * Convert all CD layers from loop/poly to tessface data. * - * \param loopindices: is an array of an int[4] per tessface, mapping tessface's verts to loops indices. + * \param loopindices: is an array of an int[4] per tessface, + * mapping tessface's verts to loops indices. * - * \note when mface is not NULL, mface[face_index].v4 is used to test quads, else, loopindices[face_index][3] is used. + * \note when mface is not NULL, mface[face_index].v4 + * is used to test quads, else, loopindices[face_index][3] is used. */ void BKE_mesh_loops_to_tessdata(CustomData *fdata, CustomData *ldata, @@ -2772,9 +2839,10 @@ void BKE_mesh_loops_to_tessdata(CustomData *fdata, unsigned int (*loopindices)[4], const int num_faces) { - /* Note: performances are sub-optimal when we get a NULL mface, we could be ~25% quicker with dedicated code... - * Issue is, unless having two different functions with nearly the same code, there's not much ways to solve - * this. Better imho to live with it for now. :/ --mont29 + /* Note: performances are sub-optimal when we get a NULL mface, + * we could be ~25% quicker with dedicated code... + * Issue is, unless having two different functions with nearly the same code, + * there's not much ways to solve this. Better imho to live with it for now. :/ --mont29 */ const int numUV = CustomData_number_of_layers(ldata, CD_MLOOPUV); const int numCol = CustomData_number_of_layers(ldata, CD_MLOOPCOL); @@ -2865,9 +2933,10 @@ void BKE_mesh_tangent_loops_to_tessdata(CustomData *fdata, const int num_faces, const char *layer_name) { - /* Note: performances are sub-optimal when we get a NULL mface, we could be ~25% quicker with dedicated code... - * Issue is, unless having two different functions with nearly the same code, there's not much ways to solve - * this. Better imho to live with it for now. :/ --mont29 + /* Note: performances are sub-optimal when we get a NULL mface, + * we could be ~25% quicker with dedicated code... + * Issue is, unless having two different functions with nearly the same code, + * there's not much ways to solve this. Better imho to live with it for now. :/ --mont29 */ float(*ftangents)[4] = NULL; @@ -2877,17 +2946,21 @@ void BKE_mesh_tangent_loops_to_tessdata(CustomData *fdata, const int *pidx; unsigned int(*lidx)[4]; - if (layer_name) + if (layer_name) { ltangents = CustomData_get_layer_named(ldata, CD_TANGENT, layer_name); - else + } + else { ltangents = CustomData_get_layer(ldata, CD_TANGENT); + } if (ltangents) { /* need to do for all uv maps at some point */ - if (layer_name) + if (layer_name) { ftangents = CustomData_get_layer_named(fdata, CD_TANGENT, layer_name); - else + } + else { ftangents = CustomData_get_layer(fdata, CD_TANGENT); + } if (ftangents) { for (findex = 0, pidx = polyindices, lidx = loopindices; findex < num_faces; pidx++, lidx++, findex++) { @@ -2903,7 +2976,8 @@ void BKE_mesh_tangent_loops_to_tessdata(CustomData *fdata, /** * Recreate tessellation. * - * \param do_face_nor_copy: Controls whether the normals from the poly are copied to the tessellated faces. + * \param do_face_nor_copy: Controls whether the normals from the poly + * are copied to the tessellated faces. * * \return number of tessellation faces. */ @@ -3133,9 +3207,11 @@ int BKE_mesh_recalc_tessellation(CustomData *fdata, /* NOTE: quad detection issue - fourth vertidx vs fourth loopidx: * Polygons take care of their loops ordering, hence not of their vertices ordering. - * Currently, our tfaces' fourth vertex index might be 0 even for a quad. However, we know our fourth loop index is - * never 0 for quads (because they are sorted for polygons, and our quads are still mere copies of their polygons). - * So we pass NULL as MFace pointer, and BKE_mesh_loops_to_tessdata will use the fourth loop index as quad test. + * Currently, our tfaces' fourth vertex index might be 0 even for a quad. However, + * we know our fourth loop index is never 0 for quads (because they are sorted for polygons, + * and our quads are still mere copies of their polygons). + * So we pass NULL as MFace pointer, and BKE_mesh_loops_to_tessdata + * will use the fourth loop index as quad test. * ... */ BKE_mesh_loops_to_tessdata(fdata, ldata, NULL, mface_to_poly_map, lindices, totface); @@ -3398,8 +3474,9 @@ static void bm_corners_to_loops_ex(ID *id, ld->totdisp = side_sq; ld->level = (int)(logf((float)side - 1.0f) / (float)M_LN2) + 1; - if (ld->disps) + if (ld->disps) { MEM_freeN(ld->disps); + } ld->disps = MEM_malloc_arrayN((size_t)side_sq, sizeof(float[3]), "converted loop mdisps"); if (fd->disps) { @@ -3433,15 +3510,17 @@ void BKE_mesh_convert_mfaces_to_mpolys(Mesh *mesh) BKE_mesh_update_customdata_pointers(mesh, true); } -/* the same as BKE_mesh_convert_mfaces_to_mpolys but oriented to be used in do_versions from readfile.c +/** + * The same as #BKE_mesh_convert_mfaces_to_mpolys + * but oriented to be used in #do_versions from readfile.c * the difference is how active/render/clone/stencil indices are handled here * * normally thay're being set from pdata which totally makes sense for meshes which are already * converted to bmesh structures, but when loading older files indices shall be updated in other * way around, so newly added pdata and ldata would have this indices set based on fdata layer * - * this is normally only needed when reading older files, in all other cases BKE_mesh_convert_mfaces_to_mpolys - * shall be always used + * this is normally only needed when reading older files, + * in all other cases #BKE_mesh_convert_mfaces_to_mpolys shall be always used */ void BKE_mesh_do_versions_convert_mfaces_to_mpolys(Mesh *mesh) { @@ -3526,7 +3605,8 @@ void BKE_mesh_convert_mfaces_to_mpolys_ex(ID *id, for (i = 0; i < totedge_i; i++, me++) { BLI_edgehash_insert(eh, me->v1, me->v2, POINTER_FROM_UINT(i)); - /* unrelated but avoid having the FGON flag enabled, so we can reuse it later for something else */ + /* unrelated but avoid having the FGON flag enabled, + * so we can reuse it later for something else */ me->flag &= ~ME_FGON; } @@ -3655,7 +3735,8 @@ void BKE_mesh_polygon_flip_ex(MPoly *mpoly, /* Note that we keep same start vertex for flipped face. */ /* We also have to update loops edge - * (they will get their original 'other edge', that is, the original edge of their original previous loop)... */ + * (they will get their original 'other edge', that is, + * the original edge of their original previous loop)... */ unsigned int prev_edge_index = mloop[loopstart].e; mloop[loopstart].e = mloop[loopend].e; @@ -3727,8 +3808,9 @@ void BKE_mesh_flush_hidden_from_verts_ex(const MVert *mvert, MPoly *p = &mpoly[i]; p->flag &= (char)~ME_HIDE; for (j = 0; j < p->totloop; j++) { - if (mvert[mloop[p->loopstart + j].v].flag & ME_HIDE) + if (mvert[mloop[p->loopstart + j].v].flag & ME_HIDE) { p->flag |= ME_HIDE; + } } } } diff --git a/source/blender/blenkernel/intern/mesh_iterators.c b/source/blender/blenkernel/intern/mesh_iterators.c index 1f8436408fb..df6517066b8 100644 --- a/source/blender/blenkernel/intern/mesh_iterators.c +++ b/source/blender/blenkernel/intern/mesh_iterators.c @@ -99,7 +99,8 @@ void BKE_mesh_foreach_mapped_loop(Mesh *mesh, void *userData, MeshForeachFlag flag) { - /* We can't use dm->getLoopDataLayout(dm) here, we want to always access dm->loopData, EditDerivedBMesh would + /* We can't use dm->getLoopDataLayout(dm) here, + * we want to always access dm->loopData, EditDerivedBMesh would * return loop data from bmesh itself. */ const float(*lnors)[3] = (flag & MESH_FOREACH_USE_NORMAL) ? CustomData_get_layer(&mesh->ldata, CD_NORMAL) : diff --git a/source/blender/blenkernel/intern/mesh_mapping.c b/source/blender/blenkernel/intern/mesh_mapping.c index 811b78411a3..40e300e6e2d 100644 --- a/source/blender/blenkernel/intern/mesh_mapping.c +++ b/source/blender/blenkernel/intern/mesh_mapping.c @@ -42,8 +42,8 @@ * \{ */ /* ngon version wip, based on BM_uv_vert_map_create */ -/* this replaces the non bmesh function (in trunk) which takes MTFace's, if we ever need it back we could - * but for now this replaces it because its unused. */ +/* this replaces the non bmesh function (in trunk) which takes MTFace's, + * if we ever need it back we could but for now this replaces it because its unused. */ UvVertMap *BKE_mesh_uv_vert_map_create(const MPoly *mpoly, const MLoop *mloop, @@ -67,12 +67,15 @@ UvVertMap *BKE_mesh_uv_vert_map_create(const MPoly *mpoly, /* generate UvMapVert array */ mp = mpoly; - for (a = 0; a < totpoly; a++, mp++) - if (!selected || (!(mp->flag & ME_HIDE) && (mp->flag & ME_FACE_SEL))) + for (a = 0; a < totpoly; a++, mp++) { + if (!selected || (!(mp->flag & ME_HIDE) && (mp->flag & ME_FACE_SEL))) { totuv += mp->totloop; + } + } - if (totuv == 0) + if (totuv == 0) { return NULL; + } vmap = (UvVertMap *)MEM_callocN(sizeof(*vmap), "UvVertMap"); buf = vmap->buf = (UvMapVert *)MEM_callocN(sizeof(*vmap->buf) * (size_t)totuv, "UvMapVert"); @@ -142,15 +145,18 @@ UvVertMap *BKE_mesh_uv_vert_map_create(const MPoly *mpoly, if (fabsf(uv[0] - uv2[0]) < limit[0] && fabsf(uv[1] - uv2[1]) < limit[1] && (!use_winding || winding[iterv->poly_index] == winding[v->poly_index])) { - if (lastv) + if (lastv) { lastv->next = next; - else + } + else { vlist = next; + } iterv->next = newvlist; newvlist = iterv; } - else + else { lastv = iterv; + } iterv = next; } @@ -178,10 +184,12 @@ UvMapVert *BKE_mesh_uv_vert_map_get_vert(UvVertMap *vmap, unsigned int v) void BKE_mesh_uv_vert_map_free(UvVertMap *vmap) { if (vmap) { - if (vmap->vert) + if (vmap->vert) { MEM_freeN(vmap->vert); - if (vmap->buf) + } + if (vmap->buf) { MEM_freeN(vmap->buf); + } MEM_freeN(vmap); } } @@ -212,8 +220,9 @@ static void mesh_vert_poly_or_loop_map_create(MeshElemMap **r_map, for (i = 0; i < totpoly; i++) { const MPoly *p = &mpoly[i]; - for (j = 0; j < p->totloop; j++) + for (j = 0; j < p->totloop; j++) { map[mloop[p->loopstart + j].v].count++; + } } /* Assign indices mem */ @@ -242,7 +251,8 @@ static void mesh_vert_poly_or_loop_map_create(MeshElemMap **r_map, } /** - * Generates a map where the key is the vertex and the value is a list of polys that use that vertex as a corner. + * Generates a map where the key is the vertex and the value + * is a list of polys that use that vertex as a corner. * The lists are allocated from one memory pool. */ void BKE_mesh_vert_poly_map_create(MeshElemMap **r_map, @@ -257,7 +267,8 @@ void BKE_mesh_vert_poly_map_create(MeshElemMap **r_map, } /** - * Generates a map where the key is the vertex and the value is a list of loops that use that vertex as a corner. + * Generates a map where the key is the vertex and the value + * is a list of loops that use that vertex as a corner. * The lists are allocated from one memory pool. */ void BKE_mesh_vert_loop_map_create(MeshElemMap **r_map, @@ -272,7 +283,8 @@ void BKE_mesh_vert_loop_map_create(MeshElemMap **r_map, } /** - * Generates a map where the key is the edge and the value is a list of looptris that use that edge. + * Generates a map where the key is the edge and the value + * is a list of looptris that use that edge. * The lists are allocated from one memory pool. */ void BKE_mesh_vert_looptri_map_create(MeshElemMap **r_map, @@ -320,7 +332,8 @@ void BKE_mesh_vert_looptri_map_create(MeshElemMap **r_map, } /** - * Generates a map where the key is the vertex and the value is a list of edges that use that vertex as an endpoint. + * Generates a map where the key is the vertex and the value + * is a list of edges that use that vertex as an endpoint. * The lists are allocated from one memory pool. */ void BKE_mesh_vert_edge_map_create( @@ -363,7 +376,8 @@ void BKE_mesh_vert_edge_map_create( } /** - * A version of #BKE_mesh_vert_edge_map_create that references connected vertices directly (not their edges). + * A version of #BKE_mesh_vert_edge_map_create that references connected vertices directly + * (not their edges). */ void BKE_mesh_vert_edge_vert_map_create( MeshElemMap **r_map, int **r_mem, const MEdge *medge, int totvert, int totedge) @@ -463,7 +477,8 @@ void BKE_mesh_edge_loop_map_create(MeshElemMap **r_map, } /** - * Generates a map where the key is the edge and the value is a list of polygons that use that edge. + * Generates a map where the key is the edge and the value + * is a list of polygons that use that edge. * The lists are allocated from one memory pool. */ void BKE_mesh_edge_poly_map_create(MeshElemMap **r_map, @@ -730,7 +745,8 @@ static void poly_edge_loop_islands_calc(const MEdge *medge, num_edgeborders++; } if (use_bitflags) { - /* Find contiguous smooth groups already assigned, these are the values we can't reuse! */ + /* Find contiguous smooth groups already assigned, + * these are the values we can't reuse! */ for (; i--; p++) { int bit = poly_groups[*p]; if (!ELEM(bit, 0, poly_group_id, poly_group_id_overflowed) && @@ -742,8 +758,9 @@ static void poly_edge_loop_islands_calc(const MEdge *medge, } } } - /* And now, we have all our poly from current group in poly_stack (from 0 to (ps_end_idx - 1)), as well as - * all smoothgroups bits we can't use in bit_poly_group_mask. + /* And now, we have all our poly from current group in poly_stack + * (from 0 to (ps_end_idx - 1)), + * as well as all smoothgroups bits we can't use in bit_poly_group_mask. */ if (use_bitflags) { int i, *p, gid_bit = 0; @@ -755,8 +772,9 @@ static void poly_edge_loop_islands_calc(const MEdge *medge, } if (UNLIKELY(gid_bit > 31)) { /* All bits used in contiguous smooth groups, we can't do much! - * Note: this is *very* unlikely - theoretically, four groups are enough, I don't think we can reach - * this goal with such a simple algo, but I don't think either we'll never need all 32 groups! + * Note: this is *very* unlikely - theoretically, four groups are enough, + * I don't think we can reach this goal with such a simple algo, + * but I don't think either we'll never need all 32 groups! */ printf( "Warning, could not find an available id for current smooth group, faces will me " @@ -812,7 +830,8 @@ static bool poly_is_island_boundary_smooth_cb(const MPoly *mp, const int nbr_egde_users, void *UNUSED(user_data)) { - /* Edge is sharp if its poly is sharp, or edge itself is sharp, or edge is not used by exactly two polygons. */ + /* Edge is sharp if its poly is sharp, or edge itself is sharp, + * or edge is not used by exactly two polygons. */ return (!(mp->flag & ME_SMOOTH) || (me->flag & ME_SHARP) || (nbr_egde_users != 2)); } @@ -820,9 +839,9 @@ static bool poly_is_island_boundary_smooth_cb(const MPoly *mp, * Calculate smooth groups from sharp edges. * * \param r_totgroup: The total number of groups, 1 or more. - * \return Polygon aligned array of group index values (bitflags if use_bitflags is true), starting at 1 - * (0 being used as 'invalid' flag). - * Note it's callers's responsibility to MEM_freeN returned array. + * \return Polygon aligned array of group index values (bitflags if use_bitflags is true), + * starting at 1 (0 being used as 'invalid' flag). + * Note it's callers's responsibility to MEM_freeN returned array. */ int *BKE_mesh_calc_smoothgroups(const MEdge *medge, const int totedge, @@ -963,10 +982,11 @@ void BKE_mesh_loop_islands_add(MeshIslandStore *island_store, sizeof(*innrcut->indices) * (size_t)num_innercut_items); } -/* TODO: I'm not sure edge seam flag is enough to define UV islands? Maybe we should also consider UVmaps values +/* TODO: I'm not sure edge seam flag is enough to define UV islands? + * Maybe we should also consider UVmaps values * themselves (i.e. different UV-edges for a same mesh-edge => boundary edge too?). - * Would make things much more complex though, and each UVMap would then need its own mesh mapping, - * not sure we want that at all! + * Would make things much more complex though, + * and each UVMap would then need its own mesh mapping, not sure we want that at all! */ typedef struct MeshCheckIslandBoundaryUv { const MLoop *loops; @@ -1043,8 +1063,9 @@ static bool mesh_calc_islands_loop_poly_uv(MVert *UNUSED(verts), int *loop_indices; int num_pidx, num_lidx; - /* Those are used to detect 'inner cuts', i.e. edges that are borders, and yet have two or more polys of - * a same group using them (typical case: seam used to unwrap properly a cylinder). */ + /* Those are used to detect 'inner cuts', i.e. edges that are borders, + * and yet have two or more polys of a same group using them + * (typical case: seam used to unwrap properly a cylinder). */ BLI_bitmap *edge_borders = NULL; int num_edge_borders = 0; char *edge_border_count = NULL; @@ -1166,7 +1187,8 @@ static bool mesh_calc_islands_loop_poly_uv(MVert *UNUSED(verts), } /** - * Calculate 'generic' UV islands, i.e. based only on actual geometry data (edge seams), not some UV layers coordinates. + * Calculate 'generic' UV islands, i.e. based only on actual geometry data (edge seams), + * not some UV layers coordinates. */ bool BKE_mesh_calc_islands_loop_poly_edgeseam(MVert *verts, const int totvert, @@ -1186,12 +1208,14 @@ bool BKE_mesh_calc_islands_loop_poly_edgeseam(MVert *verts, * Calculate UV islands. * * \note If no MLoopUV layer is passed, we only consider edges tagged as seams as UV boundaries. - * This has the advantages of simplicity, and being valid/common to all UV maps. - * However, it means actual UV islands without matching UV seams will not be handled correctly... - * If a valid UV layer is passed as \a luvs parameter, UV coordinates are also used to detect islands boundaries. + * This has the advantages of simplicity, and being valid/common to all UV maps. + * However, it means actual UV islands without matching UV seams will not be handled correctly... + * If a valid UV layer is passed as \a luvs parameter, + * UV coordinates are also used to detect islands boundaries. * * \note All this could be optimized... - * Not sure it would be worth the more complex code, though, those loops are supposed to be really quick to do... + * Not sure it would be worth the more complex code, though, + * those loops are supposed to be really quick to do... */ bool BKE_mesh_calc_islands_loop_poly_uvmap(MVert *verts, const int totvert, diff --git a/source/blender/blenkernel/intern/mesh_merge.c b/source/blender/blenkernel/intern/mesh_merge.c index 1d534f72842..71cc20c78b7 100644 --- a/source/blender/blenkernel/intern/mesh_merge.c +++ b/source/blender/blenkernel/intern/mesh_merge.c @@ -41,8 +41,8 @@ * Poly compare with vtargetmap * Function used by #BKE_mesh_merge_verts. * The function compares poly_source after applying vtargetmap, with poly_target. - * The two polys are identical if they share the same vertices in the same order, or in reverse order, - * but starting position loopstart may be different. + * The two polys are identical if they share the same vertices in the same order, + * or in reverse order, but starting position loopstart may be different. * The function is called with direct_reverse=1 for same order (i.e. same normal), * and may be called again with direct_reverse=-1 for reverse order. * \return 1 if polys are identical, 0 if polys are different. @@ -159,7 +159,8 @@ static int cddm_poly_compare(MLoop *mloop_array, break; } - /* Adjust i_loop_target for cycling around and for direct/reverse order defined by delta = +1 or -1 */ + /* Adjust i_loop_target for cycling around and for direct/reverse order + * defined by delta = +1 or -1 */ i_loop_target_adjusted = (i_loop_target_start + direct_reverse * i_loop_target_offset) % mpoly_target->totloop; if (i_loop_target_adjusted < 0) { @@ -213,8 +214,8 @@ static bool poly_gset_compare_fn(const void *k1, const void *k2) * \param vtargetmap: The table that maps vertices to target vertices. a value of -1 * indicates a vertex is a target, and is to be kept. * This array is aligned with 'mesh->totvert' - * \warning \a vtargetmap must **not** contain any chained mapping (v1 -> v2 -> v3 etc.), this is not supported - * and will likely generate corrupted geometry. + * \warning \a vtargetmap must **not** contain any chained mapping (v1 -> v2 -> v3 etc.), + * this is not supported and will likely generate corrupted geometry. * * \param tot_vtargetmap: The number of non '-1' values in vtargetmap. (not the size) * @@ -230,10 +231,12 @@ static bool poly_gset_compare_fn(const void *k1, const void *k2) * Indeed it could be that all of a poly's vertices are merged, * but merged to vertices that do not make up a single poly, * in which case the original poly should not be dumped. - * Actually this later behavior could apply to the Mirror Modifier as well, but the additional checks are - * costly and not necessary in the case of mirror, because each vertex is only merged to its own mirror. + * Actually this later behavior could apply to the Mirror Modifier as well, + * but the additional checks are costly and not necessary in the case of mirror, + * because each vertex is only merged to its own mirror. * - * \note #BKE_mesh_recalc_tessellation has to run on the returned DM if you want to access tessfaces. + * \note #BKE_mesh_recalc_tessellation has to run on the returned DM + * if you want to access tessfaces. */ Mesh *BKE_mesh_merge_verts(Mesh *mesh, const int *vtargetmap, @@ -258,9 +261,9 @@ Mesh *BKE_mesh_merge_verts(Mesh *mesh, STACK_DECLARE(mvert); STACK_DECLARE(oldv); - /* Note: create (totedge + totloop) elements because partially invalid polys due to merge may require - * generating new edges, and while in 99% cases we'll still end with less final edges than totedge, - * cases can be forged that would end requiring more... */ + /* Note: create (totedge + totloop) elements because partially invalid polys due to merge may + * require generating new edges, and while in 99% cases we'll still end with less final edges + * than totedge, cases can be forged that would end requiring more. */ MEdge *med, *medge = MEM_malloc_arrayN((totedge + totloop), sizeof(*medge), __func__); int *olde = MEM_malloc_arrayN((totedge + totloop), sizeof(*olde), __func__); int *newe = MEM_malloc_arrayN((totedge + totloop), sizeof(*newe), __func__); @@ -354,7 +357,8 @@ Mesh *BKE_mesh_merge_verts(Mesh *mesh, if (merge_mode == MESH_MERGE_VERTS_DUMP_IF_EQUAL) { /* In this mode, we need to determine, whenever a poly' vertices are all mapped */ /* if the targets already make up a poly, in which case the new poly is dropped */ - /* This poly equality check is rather complex. We use a BLI_ghash to speed it up with a first level check */ + /* This poly equality check is rather complex. + * We use a BLI_ghash to speed it up with a first level check */ PolyKey *mpgh; poly_keys = MEM_malloc_arrayN(totpoly, sizeof(PolyKey), __func__); poly_gset = BLI_gset_new_ex(poly_gset_hash_fn, poly_gset_compare_fn, __func__, totpoly); @@ -484,7 +488,8 @@ Mesh *BKE_mesh_merge_verts(Mesh *mesh, BLI_assert((mlv == v1 && next_mlv == v2) || (mlv == v2 && next_mlv == v1)); } #endif - /* A loop is only valid if its matching edge is, and it's not reusing a vertex already used by this poly. */ + /* A loop is only valid if its matching edge is, + * and it's not reusing a vertex already used by this poly. */ if (LIKELY((newe[ml->e] != -1) && ((mv[mlv].flag & ME_VERT_TMP_TAG) == 0))) { mv[mlv].flag |= ME_VERT_TMP_TAG; @@ -505,7 +510,8 @@ Mesh *BKE_mesh_merge_verts(Mesh *mesh, STACK_PUSH(medge, mesh->medge[last_valid_ml->e]); medge[new_eidx].v1 = last_valid_ml->v; medge[new_eidx].v2 = ml->v; - /* DO NOT change newe mapping, could break actual values due to some deleted original edges. */ + /* DO NOT change newe mapping, + * could break actual values due to some deleted original edges. */ *val_p = POINTER_FROM_INT(new_eidx); created_edges++; @@ -525,8 +531,8 @@ Mesh *BKE_mesh_merge_verts(Mesh *mesh, } c++; - /* We absolutely HAVE to handle edge index remapping here, otherwise potential newly created edges - * in that part of code make remapping later totally unreliable. */ + /* We absolutely HAVE to handle edge index remapping here, otherwise potential newly + * created edges in that part of code make remapping later totally unreliable. */ BLI_assert(newe[ml->e] != -1); last_valid_ml->e = newe[ml->e]; } @@ -558,7 +564,8 @@ Mesh *BKE_mesh_merge_verts(Mesh *mesh, STACK_PUSH(medge, mesh->medge[last_valid_ml->e]); medge[new_eidx].v1 = last_valid_ml->v; medge[new_eidx].v2 = first_valid_ml->v; - /* DO NOT change newe mapping, could break actual values due to some deleted original edges. */ + /* DO NOT change newe mapping, + * could break actual values due to some deleted original edges. */ *val_p = POINTER_FROM_INT(new_eidx); created_edges++; @@ -664,10 +671,12 @@ Mesh *BKE_mesh_merge_verts(Mesh *mesh, BLI_edgehash_free(ehash, NULL); - if (poly_map != NULL) + if (poly_map != NULL) { MEM_freeN(poly_map); - if (poly_map_mem != NULL) + } + if (poly_map_mem != NULL) { MEM_freeN(poly_map_mem); + } BKE_id_free(NULL, mesh); diff --git a/source/blender/blenkernel/intern/mesh_remap.c b/source/blender/blenkernel/intern/mesh_remap.c index b43339bf73f..db158ca8fb2 100644 --- a/source/blender/blenkernel/intern/mesh_remap.c +++ b/source/blender/blenkernel/intern/mesh_remap.c @@ -124,9 +124,11 @@ static bool mesh_remap_bvhtree_query_raycast(BVHTreeFromMesh *treedata, * Compute a value of the difference between both given meshes. * The smaller the result, the better the match. * - * We return the inverse of the average of the inversed shortest distance from each dst vertex to src ones. - * In other words, beyond a certain (relatively small) distance, all differences have more or less the same weight - * in final result, which allows to reduce influence of a few high differences, in favor of a global good matching. + * We return the inverse of the average of the inversed + * shortest distance from each dst vertex to src ones. + * In other words, beyond a certain (relatively small) distance, all differences have more or less + * the same weight in final result, which allows to reduce influence of a few high differences, + * in favor of a global good matching. */ float BKE_mesh_remap_calc_difference_from_mesh(const SpaceTransform *space_transform, const MVert *verts_dst, @@ -164,20 +166,24 @@ float BKE_mesh_remap_calc_difference_from_mesh(const SpaceTransform *space_trans result = ((float)numverts_dst / result) - 1.0f; - // printf("%s: Computed difference between meshes (the lower the better): %f\n", __func__, result); +#if 0 + printf("%s: Computed difference between meshes (the lower the better): %f\n", __func__, result); +#endif return result; } -/* This helper computes the eigen values & vectors for covariance matrix of all given vertices coordinates. +/* This helper computes the eigen values & vectors for + * covariance matrix of all given vertices coordinates. * * Those vectors define the 'average ellipsoid' of the mesh (i.e. the 'best fitting' ellipsoid * containing 50% of the vertices). * - * Note that it will not perform fantastic in case two or more eigen values are equal (e.g. a cylinder or - * parallelepiped with a square section give two identical eigenvalues, a sphere or tetrahedron give - * three identical ones, etc.), since you cannot really define all axes in those cases. We default to dummy - * generated orthogonal vectors in this case, instead of using eigen vectors. + * Note that it will not perform fantastic in case two or more eigen values are equal + * (e.g. a cylinder or parallelepiped with a square section give two identical eigenvalues, + * a sphere or tetrahedron give three identical ones, etc.), since you cannot really define all + * axes in those cases. We default to dummy generated orthogonal vectors in this case, + * instead of using eigen vectors. */ static void mesh_calc_eigen_matrix(const MVert *verts, const float (*vcos)[3], @@ -207,8 +213,8 @@ static void mesh_calc_eigen_matrix(const MVert *verts, } unit_m4(r_mat); - /* Note: here we apply sample correction to covariance matrix, since we consider the vertices as a sample - * of the whole 'surface' population of our mesh... */ + /* Note: here we apply sample correction to covariance matrix, since we consider the vertices + * as a sample of the whole 'surface' population of our mesh. */ BLI_covariance_m3_v3n(vcos, numverts, true, covmat, center); if (cos) { @@ -247,8 +253,9 @@ static void mesh_calc_eigen_matrix(const MVert *verts, float evi = eigen_val[i]; /* Protect against 1D/2D degenerated cases! */ - /* Note: not sure why we need square root of eigen values here (which are equivalent to singular values, - * as far as I have understood), but it seems to heavily reduce (if not completely nullify) + /* Note: not sure why we need square root of eigen values here + * (which are equivalent to singular values, as far as I have understood), + * but it seems to heavily reduce (if not completely nullify) * the error due to non-uniform scalings... */ evi = (evi < 1e-6f && evi > -1e-6f) ? ((evi < 0.0f) ? -1e-3f : 1e-3f) : sqrtf_signed(evi); mul_v3_fl(eigen_vec[i], evi); @@ -266,7 +273,8 @@ void BKE_mesh_remap_find_best_match_from_mesh(const MVert *verts_dst, Mesh *me_src, SpaceTransform *r_space_transform) { - /* Note that those are done so that we successively get actual mirror matrix (by multiplication of columns)... */ + /* Note that those are done so that we successively get actual mirror matrix + * (by multiplication of columns). */ const float mirrors[][3] = { {-1.0f, 1.0f, 1.0f}, /* -> -1, 1, 1 */ {1.0f, -1.0f, 1.0f}, /* -> -1, -1, 1 */ @@ -323,7 +331,7 @@ void BKE_mesh_remap_calc_source_cddata_masks_from_map_modes(const int UNUSED(ver const int UNUSED(edge_mode), const int loop_mode, const int UNUSED(poly_mode), - CustomData_MeshMasks *cddata_mask) + CustomData_MeshMasks *r_cddata_mask) { /* vert, edge and poly mapping modes never need extra cddata from source object. */ const bool need_lnors_src = (loop_mode & MREMAP_USE_LOOP) && (loop_mode & MREMAP_USE_NORMAL); @@ -331,10 +339,10 @@ void BKE_mesh_remap_calc_source_cddata_masks_from_map_modes(const int UNUSED(ver ((loop_mode & MREMAP_USE_POLY) && (loop_mode & MREMAP_USE_NORMAL)); if (need_lnors_src) { - cddata_mask->lmask |= CD_MASK_NORMAL; + r_cddata_mask->lmask |= CD_MASK_NORMAL; } if (need_pnors_src) { - cddata_mask->pmask |= CD_MASK_NORMAL; + r_cddata_mask->pmask |= CD_MASK_NORMAL; } } @@ -445,25 +453,32 @@ static int mesh_remap_interp_poly_data_get(const MPoly *mp, return sources_num; } -/* Little helper when dealing with source islands */ +/** Little helper when dealing with source islands */ typedef struct IslandResult { - float - factor; /* A factor, based on which best island for a given set of elements will be selected. */ - int index_src; /* Index of the source. */ - float hit_dist; /* The actual hit distance. */ - float hit_point[3]; /* The hit point, if relevant. */ + /** A factor, based on which best island for a given set of elements will be selected. */ + float factor; + /** Index of the source. */ + int index_src; + /** The actual hit distance. */ + float hit_dist; + /** The hit point, if relevant. */ + float hit_point[3]; } IslandResult; -/* Note about all bvh/raycasting stuff below: - * * We must use our ray radius as BVH epsilon too, else rays not hitting anything but 'passing near' an item - * would be missed (since BVH handling would not detect them, 'refining' callbacks won't be executed, - * even though they would return a valid hit). - * * However, in 'islands' case where each hit gets a weight, 'precise' hits should have a better weight than - * 'approximate' hits. To address that, we simplify things with: - * ** A first raycast with default, given rayradius; - * ** If first one fails, we do more raycasting with bigger radius, but if hit is found - * it will get smaller weight. - * This only concerns loops, currently (because of islands), and 'sampled' edges/polys norproj. +/** + * \note About all bvh/raycasting stuff below: + * + * * We must use our ray radius as BVH epsilon too, else rays not hitting anything but + * 'passing near' an item would be missed (since BVH handling would not detect them, + * 'refining' callbacks won't be executed, even though they would return a valid hit). + * * However, in 'islands' case where each hit gets a weight, 'precise' hits should have a better + * weight than 'approximate' hits. + * To address that, we simplify things with: + * * A first raycast with default, given rayradius; + * * If first one fails, we do more raycasting with bigger radius, but if hit is found + * it will get smaller weight. + * + * This only concerns loops, currently (because of islands), and 'sampled' edges/polys norproj. */ /* At most n raycasts per 'real' ray. */ @@ -791,8 +806,8 @@ void BKE_mesh_remap_calc_edges_from_mesh(const int mode, } } - /* Now, check all source edges of closest sources vertices, and select the one giving the smallest - * total verts-to-verts distance. */ + /* Now, check all source edges of closest sources vertices, + * and select the one giving the smallest total verts-to-verts distance. */ for (j = 2; j--;) { const unsigned int vidx_dst = j ? e_dst->v1 : e_dst->v2; const float first_dist = v_dst_to_src_map[vidx_dst].hit_dist; @@ -1009,8 +1024,8 @@ void BKE_mesh_remap_calc_edges_from_mesh(const int mode, w /= MREMAP_RAYCAST_APPROXIMATE_FAC; } } - /* A sampling is valid (as in, its result can be considered as valid sources) only if at least - * half of the rays found a source! */ + /* A sampling is valid (as in, its result can be considered as valid sources) + * only if at least half of the rays found a source! */ if (totweights > ((float)grid_size / 2.0f)) { for (j = 0; j < (int)numedges_src; j++) { if (!weights[j]) { @@ -1201,7 +1216,8 @@ static void mesh_island_to_astar_graph(MeshIslandStore *islands, #undef POLY_COMPLETE /* Our 'f_cost' callback func, to find shortest poly-path between two remapped-loops. - * Note we do not want to make innercuts 'walls' here, just detect when the shortest path goes by those. */ + * Note we do not want to make innercuts 'walls' here, + * just detect when the shortest path goes by those. */ static float mesh_remap_calc_loops_astar_f_cost(BLI_AStarGraph *as_graph, BLI_AStarSolution *as_solution, BLI_AStarGNLink *link, @@ -1221,8 +1237,8 @@ static float mesh_remap_calc_loops_astar_f_cost(BLI_AStarGraph *as_graph, } /* Our heuristic part of current f_cost is distance from next node to destination one. - * It is guaranteed to be less than (or equal to) actual shortest poly-path between next node and destination one. - */ + * It is guaranteed to be less than (or equal to) + * actual shortest poly-path between next node and destination one. */ co_next = (float *)as_graph->nodes[node_idx_next].custom_data; co_dest = (float *)as_graph->nodes[node_idx_dst].custom_data; return (link ? (as_solution->g_costs[node_idx_curr] + link->cost) : 0.0f) + @@ -1598,8 +1614,8 @@ void BKE_mesh_remap_calc_loops_from_mesh(const int mode, for (pidx_dst = 0, mp_dst = polys_dst; pidx_dst < numpolys_dst; pidx_dst++, mp_dst++) { float pnor_dst[3]; - /* Only in use_from_vert case, we may need polys' centers as fallback in case we cannot decide which - * corner to use from normals only. */ + /* Only in use_from_vert case, we may need polys' centers as fallback + * in case we cannot decide which corner to use from normals only. */ float pcent_dst[3]; bool pcent_dst_valid = false; @@ -1760,8 +1776,8 @@ void BKE_mesh_remap_calc_loops_from_mesh(const int mode, /* Fallback to 'nearest' hit here, loops usually comes in 'face group', not good to * have only part of one dest face's loops to map to source. * Note that since we give this a null weight, if whole weight for a given face - * is null, it means none of its loop mapped to this source island, hence we can skip it - * later. + * is null, it means none of its loop mapped to this source island, + * hence we can skip it later. */ copy_v3_v3(tmp_co, verts_dst[ml_dst->v].co); nearest.index = -1; @@ -1818,12 +1834,14 @@ void BKE_mesh_remap_calc_loops_from_mesh(const int mode, /* We have to first select the 'best source island' for given dst poly and its loops. * Then, we have to check that poly does not 'spread' across some island's limits * (like inner seams for UVs, etc.). - * Note we only still partially support that kind of situation here, i.e. polys spreading over actual cracks - * (like a narrow space without faces on src, splitting a 'tube-like' geometry). That kind of situation - * should be relatively rare, though. + * Note we only still partially support that kind of situation here, i.e. + * Polys spreading over actual cracks + * (like a narrow space without faces on src, splitting a 'tube-like' geometry). + * That kind of situation should be relatively rare, though. */ - /* XXX This block in itself is big and complex enough to be a separate function but... it uses a bunch - * of locale vars. Not worth sending all that through parameters (for now at least). */ + /* XXX This block in itself is big and complex enough to be a separate function but... + * it uses a bunch of locale vars. + * Not worth sending all that through parameters (for now at least). */ { BLI_AStarGraph *as_graph = NULL; int *poly_island_index_map = NULL; @@ -1893,7 +1911,7 @@ void BKE_mesh_remap_calc_loops_from_mesh(const int mode, if (POINTER_AS_INT(as_solution.custom_data) && (as_solution.steps > 0)) { /* Find first 'cutting edge' on path, and bring back lidx_src on poly just * before that edge. - * Note we could try to be much smarter (like e.g. storing a whole poly's indices, + * Note we could try to be much smarter, g.g. Storing a whole poly's indices, * and making decision (on which side of cutting edge(s!) to be) on the end, * but this is one more level of complexity, better to first see if * simple solution works! @@ -1919,7 +1937,8 @@ void BKE_mesh_remap_calc_loops_from_mesh(const int mode, ml_dst = &loops_dst[lidx_dst]; copy_v3_v3(tmp_co, verts_dst[ml_dst->v].co); - /* We do our transform here, since we may do several raycast/nearest queries. */ + /* We do our transform here, + * since we may do several raycast/nearest queries. */ if (space_transform) { BLI_space_transform_apply(space_transform, tmp_co); } @@ -1949,7 +1968,8 @@ void BKE_mesh_remap_calc_loops_from_mesh(const int mode, } else { /* No source for this loop in this island. */ - /* TODO: would probably be better to get a source at all cost in best island anyway? */ + /* TODO: would probably be better to get a source + * at all cost in best island anyway? */ mesh_remap_item_define(r_map, lidx_dst, FLT_MAX, best_island_index, 0, NULL, NULL); } } @@ -1982,8 +2002,8 @@ void BKE_mesh_remap_calc_loops_from_mesh(const int mode, if (POINTER_AS_INT(as_solution.custom_data) && (as_solution.steps > 0)) { /* Find first 'cutting edge' on path, and bring back lidx_src on poly just * before that edge. - * Note we could try to be much smarter (like e.g. storing a whole poly's indices, - * and making decision (one which side of cutting edge(s!) to be on the end, + * Note we could try to be much smarter: e.g. Storing a whole poly's indices, + * and making decision (one which side of cutting edge(s)!) to be on the end, * but this is one more level of complexity, better to first see if * simple solution works! */ @@ -2009,7 +2029,8 @@ void BKE_mesh_remap_calc_loops_from_mesh(const int mode, ml_dst = &loops_dst[lidx_dst]; copy_v3_v3(tmp_co, verts_dst[ml_dst->v].co); - /* We do our transform here, since we may do several raycast/nearest queries. */ + /* We do our transform here, + * since we may do several raycast/nearest queries. */ if (space_transform) { BLI_space_transform_apply(space_transform, tmp_co); } @@ -2097,7 +2118,8 @@ void BKE_mesh_remap_calc_loops_from_mesh(const int mode, } else { /* No source for this loop in this island. */ - /* TODO: would probably be better to get a source at all cost in best island anyway? */ + /* TODO: would probably be better to get a source + * at all cost in best island anyway? */ mesh_remap_item_define(r_map, lidx_dst, FLT_MAX, best_island_index, 0, NULL, NULL); } } @@ -2280,7 +2302,8 @@ void BKE_mesh_remap_calc_polys_from_mesh(const int mode, } } else if (mode == MREMAP_MODE_POLY_POLYINTERP_PNORPROJ) { - /* We cast our rays randomly, with a pseudo-even distribution (since we spread across tessellated tris, + /* We cast our rays randomly, with a pseudo-even distribution + * (since we spread across tessellated tris, * with additional weighting based on each tri's relative area). */ RNG *rng = BLI_rng_new(0); @@ -2396,8 +2419,8 @@ void BKE_mesh_remap_calc_polys_from_mesh(const int mode, float *v3 = poly_vcos_2d[tri_vidx_2d[j][2]]; int rays_num; - /* All this allows us to get 'absolute' number of rays for each tri, avoiding accumulating - * errors over iterations, and helping better even distribution. */ + /* All this allows us to get 'absolute' number of rays for each tri, + * avoiding accumulating errors over iterations, and helping better even distribution. */ done_area += area_tri_v2(v1, v2, v3); rays_num = max_ii( (int)((float)tot_rays * done_area * poly_area_2d_inv + 0.5f) - done_rays, 0); diff --git a/source/blender/blenkernel/intern/mesh_runtime.c b/source/blender/blenkernel/intern/mesh_runtime.c index dea64e64377..06abd80b86f 100644 --- a/source/blender/blenkernel/intern/mesh_runtime.c +++ b/source/blender/blenkernel/intern/mesh_runtime.c @@ -78,7 +78,8 @@ void BKE_mesh_runtime_clear_cache(Mesh *mesh) /** * Ensure the array is large enough * - * \note This function must always be thread-protected by caller. It should only be used by internal code. + * \note This function must always be thread-protected by caller. + * It should only be used by internal code. */ static void mesh_ensure_looptri_data(Mesh *mesh) { @@ -149,8 +150,8 @@ const MLoopTri *BKE_mesh_runtime_looptri_ensure(Mesh *mesh) } else { BLI_rw_mutex_lock(&loops_cache_lock, THREAD_LOCK_WRITE); - /* We need to ensure array is still NULL inside mutex-protected code, some other thread might have already - * recomputed those looptris. */ + /* We need to ensure array is still NULL inside mutex-protected code, + * some other thread might have already recomputed those looptris. */ if (mesh->runtime.looptris.array == NULL) { BKE_mesh_runtime_looptri_recalc(mesh); } @@ -190,14 +191,18 @@ bool BKE_mesh_runtime_clear_edit_data(Mesh *mesh) return false; } - if (mesh->runtime.edit_data->polyCos != NULL) + if (mesh->runtime.edit_data->polyCos != NULL) { MEM_freeN((void *)mesh->runtime.edit_data->polyCos); - if (mesh->runtime.edit_data->polyNos != NULL) + } + if (mesh->runtime.edit_data->polyNos != NULL) { MEM_freeN((void *)mesh->runtime.edit_data->polyNos); - if (mesh->runtime.edit_data->vertexCos != NULL) + } + if (mesh->runtime.edit_data->vertexCos != NULL) { MEM_freeN((void *)mesh->runtime.edit_data->vertexCos); - if (mesh->runtime.edit_data->vertexNos != NULL) + } + if (mesh->runtime.edit_data->vertexNos != NULL) { MEM_freeN((void *)mesh->runtime.edit_data->vertexNos); + } MEM_SAFE_FREE(mesh->runtime.edit_data); return true; @@ -285,9 +290,15 @@ char *BKE_mesh_runtime_debug_info(Mesh *me_eval) # if 0 const char *tstr; switch (me_eval->type) { - case DM_TYPE_CDDM: tstr = "DM_TYPE_CDDM"; break; - case DM_TYPE_CCGDM: tstr = "DM_TYPE_CCGDM"; break; - default: tstr = "UNKNOWN"; break; + case DM_TYPE_CDDM: + tstr = "DM_TYPE_CDDM"; + break; + case DM_TYPE_CCGDM: + tstr = "DM_TYPE_CCGDM"; + break; + default: + tstr = "UNKNOWN"; + break; } BLI_dynstr_appendf(dynstr, " 'type': '%s',\n", tstr); # endif diff --git a/source/blender/blenkernel/intern/mesh_tangent.c b/source/blender/blenkernel/intern/mesh_tangent.c index e6c4e9ff4be..19d94be9b6e 100644 --- a/source/blender/blenkernel/intern/mesh_tangent.c +++ b/source/blender/blenkernel/intern/mesh_tangent.c @@ -116,7 +116,8 @@ static void set_tspace(const SMikkTSpaceContext *pContext, } /** - * Compute simplified tangent space normals, i.e. tangent vector + sign of bi-tangent one, which combined with + * Compute simplified tangent space normals, i.e. + * tangent vector + sign of bi-tangent one, which combined with * split normals can be used to recreate the full tangent space. * Note: * The mesh should be made of only tris and quads! */ @@ -284,7 +285,7 @@ static void dm_ts_GetPosition(const SMikkTSpaceContext *pContext, const int face_num, const int vert_index) { - //assert(vert_index >= 0 && vert_index < 4); + // assert(vert_index >= 0 && vert_index < 4); SGLSLMeshToTangent *pMesh = pContext->m_pUserData; const MLoopTri *lt; uint loop_index; @@ -318,7 +319,7 @@ static void dm_ts_GetTextureCoordinate(const SMikkTSpaceContext *pContext, const int face_num, const int vert_index) { - //assert(vert_index >= 0 && vert_index < 4); + // assert(vert_index >= 0 && vert_index < 4); SGLSLMeshToTangent *pMesh = pContext->m_pUserData; const MLoopTri *lt; uint loop_index; @@ -357,7 +358,7 @@ static void dm_ts_GetNormal(const SMikkTSpaceContext *pContext, const int face_num, const int vert_index) { - //assert(vert_index >= 0 && vert_index < 4); + // assert(vert_index >= 0 && vert_index < 4); SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *)pContext->m_pUserData; const MLoopTri *lt; uint loop_index; @@ -420,7 +421,7 @@ static void dm_ts_SetTSpace(const SMikkTSpaceContext *pContext, const int face_num, const int vert_index) { - //assert(vert_index >= 0 && vert_index < 4); + // assert(vert_index >= 0 && vert_index < 4); SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *)pContext->m_pUserData; const MLoopTri *lt; uint loop_index; @@ -487,7 +488,8 @@ void BKE_mesh_add_loop_tangent_named_layer_for_uv(CustomData *uv_data, } /** - * Here we get some useful information such as active uv layer name and search if it is already in tangent_names. + * Here we get some useful information such as active uv layer name and + * search if it is already in tangent_names. * Also, we calculate tangent_mask that works as a descriptor of tangents state. * If tangent_mask has changed, then recalculate tangents. */ @@ -530,10 +532,12 @@ void BKE_mesh_calc_loop_tangent_step_0(const CustomData *loopData, *rcalc_act = true; *rcalc_ren = true; for (int i = 0; i < tangent_names_count; i++) { - if (STREQ(ract_uv_name, tangent_names[i])) + if (STREQ(ract_uv_name, tangent_names[i])) { *rcalc_act = false; - if (STREQ(rren_uv_name, tangent_names[i])) + } + if (STREQ(rren_uv_name, tangent_names[i])) { *rcalc_ren = false; + } } } *rtangent_mask = 0; @@ -552,12 +556,14 @@ void BKE_mesh_calc_loop_tangent_step_0(const CustomData *loopData, (*rcalc_ren && rren_uv_name[0] && STREQ(rren_uv_name, name)))) { add = true; } - if (add) + if (add) { *rtangent_mask |= (short)(1 << n); + } } - if (uv_layer_num == 0) + if (uv_layer_num == 0) { *rtangent_mask |= DM_TANGENT_MASK_ORCO; + } } /** @@ -605,20 +611,25 @@ void BKE_mesh_calc_loop_tangent_ex(const MVert *mvert, if ((tangent_mask_curr | tangent_mask) != tangent_mask_curr) { /* Check we have all the needed layers */ /* Allocate needed tangent layers */ - for (int i = 0; i < tangent_names_len; i++) - if (tangent_names[i][0]) + for (int i = 0; i < tangent_names_len; i++) { + if (tangent_names[i][0]) { BKE_mesh_add_loop_tangent_named_layer_for_uv( loopdata, loopdata_out, (int)loopdata_out_len, tangent_names[i]); + } + } if ((tangent_mask & DM_TANGENT_MASK_ORCO) && - CustomData_get_named_layer_index(loopdata, CD_TANGENT, "") == -1) + CustomData_get_named_layer_index(loopdata, CD_TANGENT, "") == -1) { CustomData_add_layer_named( loopdata_out, CD_TANGENT, CD_CALLOC, NULL, (int)loopdata_out_len, ""); - if (calc_act && act_uv_name[0]) + } + if (calc_act && act_uv_name[0]) { BKE_mesh_add_loop_tangent_named_layer_for_uv( loopdata, loopdata_out, (int)loopdata_out_len, act_uv_name); - if (calc_ren && ren_uv_name[0]) + } + if (calc_ren && ren_uv_name[0]) { BKE_mesh_add_loop_tangent_named_layer_for_uv( loopdata, loopdata_out, (int)loopdata_out_len, ren_uv_name); + } #ifdef USE_LOOPTRI_DETECT_QUADS int num_face_as_quad_map; @@ -668,9 +679,8 @@ void BKE_mesh_calc_loop_tangent_ex(const MVert *mvert, mesh2tangent->mpoly = mpoly; mesh2tangent->mloop = mloop; mesh2tangent->looptri = looptri; - /* Note, we assume we do have tessellated loop normals at this point (in case it is object-enabled), - * have to check this is valid... - */ + /* Note, we assume we do have tessellated loop normals at this point + * (in case it is object-enabled), have to check this is valid. */ mesh2tangent->precomputedLoopNormals = loop_normals; mesh2tangent->precomputedFaceNormals = poly_normals; @@ -681,8 +691,9 @@ void BKE_mesh_calc_loop_tangent_ex(const MVert *mvert, /* Fill the resulting tangent_mask */ if (!mesh2tangent->mloopuv) { mesh2tangent->orco = vert_orco; - if (!mesh2tangent->orco) + if (!mesh2tangent->orco) { continue; + } tangent_mask_curr |= DM_TANGENT_MASK_ORCO; } diff --git a/source/blender/blenkernel/intern/mesh_validate.c b/source/blender/blenkernel/intern/mesh_validate.c index d54796a66c4..dac12233539 100644 --- a/source/blender/blenkernel/intern/mesh_validate.c +++ b/source/blender/blenkernel/intern/mesh_validate.c @@ -166,8 +166,9 @@ static int search_poly_cmp(const void *v1, const void *v2) int idx; /* Reject all invalid polys at end of list! */ - if (sp1->invalid || sp2->invalid) + if (sp1->invalid || sp2->invalid) { return sp1->invalid ? (sp2->invalid ? 0 : 1) : -1; + } /* Else, sort on first non-equal verts (remember verts of valid polys are sorted). */ for (idx = 0; idx < max_idx; idx++) { const int v1_i = sp1->verts[idx]; @@ -184,8 +185,9 @@ static int search_polyloop_cmp(const void *v1, const void *v2) const SortPoly *sp1 = v1, *sp2 = v2; /* Reject all invalid polys at end of list! */ - if (sp1->invalid || sp2->invalid) + if (sp1->invalid || sp2->invalid) { return sp1->invalid && sp2->invalid ? 0 : sp1->invalid ? 1 : -1; + } /* Else, sort on loopstart. */ return sp1->loopstart > sp2->loopstart ? 1 : sp1->loopstart < sp2->loopstart ? -1 : 0; } @@ -314,8 +316,9 @@ bool BKE_mesh_validate_arrays(Mesh *mesh, } } - if (mv->no[j] != 0) + if (mv->no[j] != 0) { fix_normal = false; + } } if (fix_normal) { @@ -570,8 +573,9 @@ bool BKE_mesh_validate_arrays(Mesh *mesh, sp->numverts = mp->totloop; sp->loopstart = mp->loopstart; - /* Ideally we would only have to do that once on all vertices before we start checking each poly, but - * several polys can use same vert, so we have to ensure here all verts of current poly are cleared. */ + /* Ideally we would only have to do that once on all vertices + * before we start checking each poly, but several polys can use same vert, + * so we have to ensure here all verts of current poly are cleared. */ for (j = 0, ml = &mloops[sp->loopstart]; j < mp->totloop; j++, ml++) { if (ml->v < totvert) { mverts[ml->v].flag &= ~ME_VERT_TMP_TAG; @@ -595,8 +599,9 @@ bool BKE_mesh_validate_arrays(Mesh *mesh, *v = ml->v; } - if (sp->invalid) + if (sp->invalid) { continue; + } /* Test all poly's loops. */ for (j = 0, ml = &mloops[sp->loopstart]; j < mp->totloop; j++, ml++) { @@ -605,10 +610,12 @@ bool BKE_mesh_validate_arrays(Mesh *mesh, if (!BLI_edgehash_haskey(edge_hash, v1, v2)) { /* Edge not existing. */ PRINT_ERR("\tPoly %u needs missing edge (%d, %d)", sp->index, v1, v2); - if (do_fixes) + if (do_fixes) { recalc_flag.edges = true; - else + } + else { sp->invalid = true; + } } else if (ml->e >= totedge) { /* Invalid edge idx. @@ -632,7 +639,8 @@ bool BKE_mesh_validate_arrays(Mesh *mesh, if (IS_REMOVED_EDGE(me) || !((me->v1 == v1 && me->v2 == v2) || (me->v1 == v2 && me->v2 == v1))) { /* The pointed edge is invalid (tagged as removed, or vert idx mismatch), - * and we already know from previous test that a valid one exists, use it (if allowed)! */ + * and we already know from previous test that a valid one exists, + * use it (if allowed)! */ if (do_fixes) { int prev_e = ml->e; ml->e = POINTER_AS_INT(BLI_edgehash_lookup(edge_hash, v1, v2)); @@ -670,7 +678,8 @@ bool BKE_mesh_validate_arrays(Mesh *mesh, const int *p1_v = sp->verts, *p2_v = prev_sp->verts; if (sp->invalid) { - /* break, because all known invalid polys have been put at the end by qsort with search_poly_cmp. */ + /* Break, because all known invalid polys have been put at the end + * by qsort with search_poly_cmp. */ break; } @@ -679,8 +688,9 @@ bool BKE_mesh_validate_arrays(Mesh *mesh, if (do_verbose) { // TODO: convert list to string PRINT_ERR("\tPolys %u and %u use same vertices (%d", prev_sp->index, sp->index, *p1_v); - for (j = 1; j < p1_nv; j++) + for (j = 1; j < p1_nv; j++) { PRINT_ERR(", %d", p1_v[j]); + } PRINT_ERR("), considering poly %u as invalid.", sp->index); } else { @@ -700,8 +710,9 @@ bool BKE_mesh_validate_arrays(Mesh *mesh, prev_end = 0; for (i = 0; i < totpoly; i++, sp++) { /* Free this now, we don't need it anymore, and avoid us another loop! */ - if (sp->verts) + if (sp->verts) { MEM_freeN(sp->verts); + } /* Note above prev_sp: in following code, we make sure it is always valid poly (or NULL). */ if (sp->invalid) { @@ -720,8 +731,9 @@ bool BKE_mesh_validate_arrays(Mesh *mesh, if (prev_end < sp->loopstart) { for (j = prev_end, ml = &mloops[prev_end]; j < sp->loopstart; j++, ml++) { PRINT_ERR("\tLoop %u is unused.", j); - if (do_fixes) + if (do_fixes) { REMOVE_LOOP_TAG(ml); + } } prev_end = sp->loopstart + sp->numverts; prev_sp = sp; @@ -752,8 +764,9 @@ bool BKE_mesh_validate_arrays(Mesh *mesh, if (prev_end < totloop) { for (j = prev_end, ml = &mloops[prev_end]; j < totloop; j++, ml++) { PRINT_ERR("\tLoop %u is unused.", j); - if (do_fixes) + if (do_fixes) { REMOVE_LOOP_TAG(ml); + } } } @@ -1312,14 +1325,18 @@ static int vergedgesort(const void *v1, const void *v2) { const struct EdgeSort *x1 = v1, *x2 = v2; - if (x1->v1 > x2->v1) + if (x1->v1 > x2->v1) { return 1; - else if (x1->v1 < x2->v1) + } + else if (x1->v1 < x2->v1) { return -1; - else if (x1->v2 > x2->v2) + } + else if (x1->v2 > x2->v2) { return 1; - else if (x1->v2 < x2->v2) + } + else if (x1->v2 < x2->v2) { return -1; + } return 0; } @@ -1351,12 +1368,15 @@ static void mesh_calc_edges_mdata(MVert *UNUSED(allvert), /* we put all edges in array, sort them, and detect doubles that way */ for (a = totface, mface = allface; a > 0; a--, mface++) { - if (mface->v4) + if (mface->v4) { totedge += 4; - else if (mface->v3) + } + else if (mface->v3) { totedge += 3; - else + } + else { totedge += 1; + } } if (totedge == 0) { @@ -1386,8 +1406,9 @@ static void mesh_calc_edges_mdata(MVert *UNUSED(allvert), /* count final amount */ for (a = totedge, ed = edsort; a > 1; a--, ed++) { /* edge is unique when it differs from next edge, or is last */ - if (ed->v1 != (ed + 1)->v1 || ed->v2 != (ed + 1)->v2) + if (ed->v1 != (ed + 1)->v1 || ed->v2 != (ed + 1)->v2) { totedge_final++; + } } totedge_final++; @@ -1398,10 +1419,12 @@ static void mesh_calc_edges_mdata(MVert *UNUSED(allvert), if (ed->v1 != (ed + 1)->v1 || ed->v2 != (ed + 1)->v2) { med->v1 = ed->v1; med->v2 = ed->v2; - if (use_old == false || ed->is_draw) + if (use_old == false || ed->is_draw) { med->flag = ME_EDGEDRAW | ME_EDGERENDER; - if (ed->is_loose) + } + if (ed->is_loose) { med->flag |= ME_LOOSEEDGE; + } /* order is swapped so extruding this edge as a surface wont flip face normals * with cyclic curves */ @@ -1419,8 +1442,9 @@ static void mesh_calc_edges_mdata(MVert *UNUSED(allvert), med->v1 = ed->v1; med->v2 = ed->v2; med->flag = ME_EDGEDRAW; - if (ed->is_loose) + if (ed->is_loose) { med->flag |= ME_LOOSEEDGE; + } med->flag |= ME_EDGERENDER; MEM_freeN(edsort); @@ -1506,8 +1530,9 @@ void BKE_mesh_calc_edges(Mesh *mesh, bool update, const bool select) /* select for newly created meshes which are selected [#25595] */ const short ed_flag = (ME_EDGEDRAW | ME_EDGERENDER) | (select ? SELECT : 0); - if (mesh->totedge == 0) + if (mesh->totedge == 0) { update = false; + } eh_reserve = max_ii(update ? mesh->totedge : 0, BLI_EDGEHASH_SIZE_GUESS_FROM_POLYS(totpoly)); eh = BLI_edgehash_new_ex(__func__, eh_reserve); @@ -1516,8 +1541,9 @@ void BKE_mesh_calc_edges(Mesh *mesh, bool update, const bool select) /* assume existing edges are valid * useful when adding more faces and generating edges from them */ med = mesh->medge; - for (i = 0; i < mesh->totedge; i++, med++) + for (i = 0; i < mesh->totedge; i++, med++) { BLI_edgehash_insert(eh, med->v1, med->v2, med); + } } /* mesh loops (bmesh only) */ diff --git a/source/blender/blenkernel/intern/modifier.c b/source/blender/blenkernel/intern/modifier.c index 7d4fc15ca56..9bc9865631f 100644 --- a/source/blender/blenkernel/intern/modifier.c +++ b/source/blender/blenkernel/intern/modifier.c @@ -36,6 +36,7 @@ #include "DNA_armature_types.h" #include "DNA_mesh_types.h" #include "DNA_object_types.h" +#include "DNA_scene_types.h" #include "BLI_utildefines.h" #include "BLI_listbase.h" @@ -129,11 +130,13 @@ ModifierData *modifier_new(int type) md->mode = eModifierMode_Realtime | eModifierMode_Render | eModifierMode_Expanded; md->flag = eModifierFlag_StaticOverride_Local; - if (mti->flags & eModifierTypeFlag_EnableInEditmode) + if (mti->flags & eModifierTypeFlag_EnableInEditmode) { md->mode |= eModifierMode_Editmode; + } - if (mti->initData) + if (mti->initData) { mti->initData(md); + } return md; } @@ -162,10 +165,12 @@ void modifier_free_ex(ModifierData *md, const int flag) } } - if (mti->freeData) + if (mti->freeData) { mti->freeData(md); - if (md->error) + } + if (md->error) { MEM_freeN(md->error); + } MEM_freeN(md); } @@ -222,9 +227,11 @@ ModifierData *modifiers_findByType(Object *ob, ModifierType type) { ModifierData *md = ob->modifiers.first; - for (; md; md = md->next) - if (md->type == type) + for (; md; md = md->next) { + if (md->type == type) { break; + } + } return md; } @@ -256,8 +263,9 @@ void modifiers_foreachObjectLink(Object *ob, ObjectWalkFunc walk, void *userData for (; md; md = md->next) { const ModifierTypeInfo *mti = modifierType_getInfo(md->type); - if (mti->foreachObjectLink) + if (mti->foreachObjectLink) { mti->foreachObjectLink(md, ob, walk, userData); + } } } @@ -268,8 +276,9 @@ void modifiers_foreachIDLink(Object *ob, IDWalkFunc walk, void *userData) for (; md; md = md->next) { const ModifierTypeInfo *mti = modifierType_getInfo(md->type); - if (mti->foreachIDLink) + if (mti->foreachIDLink) { mti->foreachIDLink(md, ob, walk, userData); + } else if (mti->foreachObjectLink) { /* each Object can masquerade as an ID, so this should be OK */ ObjectWalkFunc fp = (ObjectWalkFunc)walk; @@ -285,8 +294,9 @@ void modifiers_foreachTexLink(Object *ob, TexWalkFunc walk, void *userData) for (; md; md = md->next) { const ModifierTypeInfo *mti = modifierType_getInfo(md->type); - if (mti->foreachTexLink) + if (mti->foreachTexLink) { mti->foreachTexLink(md, ob, walk, userData); + } } } @@ -391,8 +401,9 @@ void modifier_setError(ModifierData *md, const char *_format, ...) va_end(ap); buffer[sizeof(buffer) - 1] = '\0'; - if (md->error) + if (md->error) { MEM_freeN(md->error); + } md->error = BLI_strdup(buffer); @@ -426,28 +437,35 @@ int modifiers_getCageIndex(struct Scene *scene, const ModifierTypeInfo *mti = modifierType_getInfo(md->type); bool supports_mapping; - if (mti->isDisabled && mti->isDisabled(scene, md, 0)) + if (mti->isDisabled && mti->isDisabled(scene, md, 0)) { continue; - if (!(mti->flags & eModifierTypeFlag_SupportsEditmode)) + } + if (!(mti->flags & eModifierTypeFlag_SupportsEditmode)) { continue; - if (md->mode & eModifierMode_DisableTemporary) + } + if (md->mode & eModifierMode_DisableTemporary) { continue; + } supports_mapping = modifier_supportsMapping(md); if (r_lastPossibleCageIndex && supports_mapping) { *r_lastPossibleCageIndex = i; } - if (!(md->mode & eModifierMode_Realtime)) + if (!(md->mode & eModifierMode_Realtime)) { continue; - if (!(md->mode & eModifierMode_Editmode)) + } + if (!(md->mode & eModifierMode_Editmode)) { continue; + } - if (!supports_mapping) + if (!supports_mapping) { break; + } - if (md->mode & eModifierMode_OnCage) + if (md->mode & eModifierMode_OnCage) { cageIndex = i; + } } return cageIndex; @@ -484,22 +502,27 @@ bool modifiers_isParticleEnabled(Object *ob) /** * Check whether is enabled. * - * \param scene: Current scene, may be NULL, in which case isDisabled callback of the modifier is never called. + * \param scene: Current scene, may be NULL, + * in which case isDisabled callback of the modifier is never called. */ bool modifier_isEnabled(const struct Scene *scene, ModifierData *md, int required_mode) { const ModifierTypeInfo *mti = modifierType_getInfo(md->type); - if ((md->mode & required_mode) != required_mode) + if ((md->mode & required_mode) != required_mode) { return false; + } if (scene != NULL && mti->isDisabled && - mti->isDisabled(scene, md, required_mode == eModifierMode_Render)) + mti->isDisabled(scene, md, required_mode == eModifierMode_Render)) { return false; - if (md->mode & eModifierMode_DisableTemporary) + } + if (md->mode & eModifierMode_DisableTemporary) { return false; + } if ((required_mode & eModifierMode_Editmode) && - !(mti->flags & eModifierTypeFlag_SupportsEditmode)) + !(mti->flags & eModifierTypeFlag_SupportsEditmode)) { return false; + } return true; } @@ -522,8 +545,9 @@ CDMaskLink *modifiers_calcDataMasks(struct Scene *scene, curr = MEM_callocN(sizeof(CDMaskLink), "CDMaskLink"); if (modifier_isEnabled(scene, md, required_mode)) { - if (mti->requiredDataMask) + if (mti->requiredDataMask) { mti->requiredDataMask(ob, md, &curr->mask); + } if (previewmd == md && previewmask != NULL) { CustomData_MeshMasks_update(&curr->mask, previewmask); @@ -560,13 +584,15 @@ ModifierData *modifiers_getLastPreview(struct Scene *scene, ModifierData *md, in { ModifierData *tmp_md = NULL; - if ((required_mode & ~eModifierMode_Editmode) != eModifierMode_Realtime) + if ((required_mode & ~eModifierMode_Editmode) != eModifierMode_Realtime) { return tmp_md; + } /* Find the latest modifier in stack generating preview. */ for (; md; md = md->next) { - if (modifier_isEnabled(scene, md, required_mode) && modifier_isPreview(md)) + if (modifier_isEnabled(scene, md, required_mode) && modifier_isPreview(md)) { tmp_md = md; + } } return tmp_md; } @@ -605,10 +631,12 @@ ModifierData *modifiers_getVirtualModifierList(Object *ob, /* shape key modifier, not yet for curves */ if (ELEM(ob->type, OB_MESH, OB_LATTICE) && BKE_key_from_object(ob)) { - if (ob->type == OB_MESH && (ob->shapeflag & OB_SHAPE_EDIT_MODE)) + if (ob->type == OB_MESH && (ob->shapeflag & OB_SHAPE_EDIT_MODE)) { virtualModifierData->smd.modifier.mode |= eModifierMode_Editmode | eModifierMode_OnCage; - else + } + else { virtualModifierData->smd.modifier.mode &= ~eModifierMode_Editmode | eModifierMode_OnCage; + } virtualModifierData->smd.modifier.next = md; md = &virtualModifierData->smd.modifier; @@ -630,13 +658,15 @@ Object *modifiers_isDeformedByArmature(Object *ob) for (; md; md = md->next) { if (md->type == eModifierType_Armature) { amd = (ArmatureModifierData *)md; - if (amd->object && (amd->object->flag & SELECT)) + if (amd->object && (amd->object->base_flag & BASE_SELECTED)) { return amd->object; + } } } - if (amd) /* if were still here then return the last armature */ + if (amd) { /* if were still here then return the last armature */ return amd->object; + } return NULL; } @@ -651,13 +681,15 @@ Object *modifiers_isDeformedByMeshDeform(Object *ob) for (; md; md = md->next) { if (md->type == eModifierType_MeshDeform) { mdmd = (MeshDeformModifierData *)md; - if (mdmd->object && (mdmd->object->flag & SELECT)) + if (mdmd->object && (mdmd->object->base_flag & BASE_SELECTED)) { return mdmd->object; + } } } - if (mdmd) /* if were still here then return the last armature */ + if (mdmd) { /* if were still here then return the last armature */ return mdmd->object; + } return NULL; } @@ -675,13 +707,15 @@ Object *modifiers_isDeformedByLattice(Object *ob) for (; md; md = md->next) { if (md->type == eModifierType_Lattice) { lmd = (LatticeModifierData *)md; - if (lmd->object && (lmd->object->flag & SELECT)) + if (lmd->object && (lmd->object->base_flag & BASE_SELECTED)) { return lmd->object; + } } } - if (lmd) /* if were still here then return the last lattice */ + if (lmd) { /* if were still here then return the last lattice */ return lmd->object; + } return NULL; } @@ -699,13 +733,15 @@ Object *modifiers_isDeformedByCurve(Object *ob) for (; md; md = md->next) { if (md->type == eModifierType_Curve) { cmd = (CurveModifierData *)md; - if (cmd->object && (cmd->object->flag & SELECT)) + if (cmd->object && (cmd->object->base_flag & BASE_SELECTED)) { return cmd->object; + } } } - if (cmd) /* if were still here then return the last curve */ + if (cmd) { /* if were still here then return the last curve */ return cmd->object; + } return NULL; } @@ -718,8 +754,9 @@ bool modifiers_usesArmature(Object *ob, bArmature *arm) for (; md; md = md->next) { if (md->type == eModifierType_Armature) { ArmatureModifierData *amd = (ArmatureModifierData *)md; - if (amd->object && amd->object->data == arm) + if (amd->object && amd->object->data == arm) { return true; + } } } @@ -759,8 +796,9 @@ bool modifiers_isPreview(Object *ob) ModifierData *md = ob->modifiers.first; for (; md; md = md->next) { - if (modifier_isPreview(md)) + if (modifier_isPreview(md)) { return true; + } } return false; @@ -786,8 +824,9 @@ void test_object_modifiers(Object *ob) /* just multires checked for now, since only multires * modifies mesh data */ - if (ob->type != OB_MESH) + if (ob->type != OB_MESH) { return; + } for (md = ob->modifiers.first; md; md = md->next) { if (md->type == eModifierType_Multires) { @@ -892,7 +931,8 @@ void modwrap_deformVertsEM(ModifierData *md, /** * Get evaluated mesh for other evaluated object, which is used as an operand for the modifier, * e.g. second operand for boolean modifier. - * Note that modifiers in stack always get fully evaluated COW ID pointers, never original ones. Makes things simpler. + * Note that modifiers in stack always get fully evaluated COW ID pointers, + * never original ones. Makes things simpler. * * \param get_cage_mesh Return evaluated mesh with only deforming modifiers applied * (i.e. mesh topology remains the same as original one, a.k.a. 'cage' mesh). @@ -905,8 +945,8 @@ Mesh *BKE_modifier_get_evaluated_mesh_from_evaluated_object(Object *ob_eval, if ((ob_eval->type == OB_MESH) && (ob_eval->mode & OB_MODE_EDIT)) { /* In EditMode, evaluated mesh is stored in BMEditMesh, not the object... */ BMEditMesh *em = BKE_editmesh_from_object(ob_eval); - if (em != - NULL) { /* em might not exist yet in some cases, just after loading a .blend file, see T57878. */ + /* 'em' might not exist yet in some cases, just after loading a .blend file, see T57878. */ + if (em != NULL) { me = (get_cage_mesh && em->mesh_eval_cage != NULL) ? em->mesh_eval_cage : em->mesh_eval_final; } diff --git a/source/blender/blenkernel/intern/movieclip.c b/source/blender/blenkernel/intern/movieclip.c index 51f7fd2208c..8d149af6a1f 100644 --- a/source/blender/blenkernel/intern/movieclip.c +++ b/source/blender/blenkernel/intern/movieclip.c @@ -84,8 +84,9 @@ static int sequence_guess_offset(const char *full_name, int head_len, unsigned s static int rendersize_to_proxy(const MovieClipUser *user, int flag) { - if ((flag & MCLIP_USE_PROXY) == 0) + if ((flag & MCLIP_USE_PROXY) == 0) { return IMB_PROXY_NONE; + } switch (user->render_size) { case MCLIP_PROXY_RENDER_SIZE_25: @@ -131,8 +132,9 @@ static int rendersize_to_number(int render_size) static int get_timecode(MovieClip *clip, int flag) { - if ((flag & MCLIP_USE_PROXY) == 0) + if ((flag & MCLIP_USE_PROXY) == 0) { return IMB_TC_NONE; + } return clip->proxy.tc; } @@ -179,10 +181,12 @@ static void get_proxy_fname( BLI_snprintf(dir, FILE_MAX, "%s/BL_proxy", clipdir); } - if (undistorted) + if (undistorted) { BLI_snprintf(name, FILE_MAX, "%s/%s/proxy_%d_undistorted/%08d", dir, clipfile, size, proxynr); - else + } + else { BLI_snprintf(name, FILE_MAX, "%s/%s/proxy_%d/%08d", dir, clipfile, size, proxynr); + } BLI_path_abs(name, BKE_main_blendfile_path_from_global()); BLI_path_frame(name, 1, 0); @@ -378,10 +382,12 @@ static void movieclip_calc_length(MovieClip *clip) for (;;) { get_sequence_fname(clip, clip->len + clip->start_frame, name); - if (BLI_exists(name)) + if (BLI_exists(name)) { clip->len++; - else + } + else { break; + } } } } @@ -458,8 +464,9 @@ static int user_frame_to_cache_frame(MovieClip *clip, int framenr) index += clip->cache->sequence_offset; } - if (index < 0) + if (index < 0) { return framenr - index; + } return framenr; } @@ -703,8 +710,9 @@ MovieClip *BKE_movieclip_file_add(Main *bmain, const char *name) /* exists? */ file = BLI_open(str, O_BINARY | O_RDONLY, 0); - if (file == -1) + if (file == -1) { return NULL; + } close(file); /* ** add new movieclip ** */ @@ -742,14 +750,16 @@ MovieClip *BKE_movieclip_file_add_exists_ex(Main *bmain, const char *filepath, b if (BLI_path_cmp(strtest, str) == 0) { id_us_plus(&clip->id); /* officially should not, it doesn't link here! */ - if (r_exists) + if (r_exists) { *r_exists = true; + } return clip; } } - if (r_exists) + if (r_exists) { *r_exists = false; + } return BKE_movieclip_file_add(bmain, filepath); } @@ -790,11 +800,13 @@ static ImBuf *get_undistorted_ibuf(MovieClip *clip, { ImBuf *undistibuf; - if (distortion) + if (distortion) { undistibuf = BKE_tracking_distortion_exec( distortion, &clip->tracking, ibuf, ibuf->x, ibuf->y, 0.0f, 1); - else + } + else { undistibuf = BKE_tracking_undistort_frame(&clip->tracking, ibuf, ibuf->x, ibuf->y, 0.0f); + } IMB_scaleImBuf(undistibuf, ibuf->x, ibuf->y); @@ -861,26 +873,32 @@ static ImBuf *get_postprocessed_cached_frame(const MovieClip *clip, } /* no cache or no cached postprocessed image */ - if (!clip->cache || !clip->cache->postprocessed.ibuf) + if (!clip->cache || !clip->cache->postprocessed.ibuf) { return NULL; + } /* postprocessing happened for other frame */ - if (cache->postprocessed.framenr != framenr) + if (cache->postprocessed.framenr != framenr) { return NULL; + } /* cached ibuf used different proxy settings */ - if (cache->postprocessed.render_flag != render_flag || cache->postprocessed.proxy != proxy) + if (cache->postprocessed.render_flag != render_flag || cache->postprocessed.proxy != proxy) { return NULL; + } - if (cache->postprocessed.flag != postprocess_flag) + if (cache->postprocessed.flag != postprocess_flag) { return NULL; + } if (need_undistortion_postprocess(user, flag)) { - if (!check_undistortion_cache_flags(clip)) + if (!check_undistortion_cache_flags(clip)) { return NULL; + } } - else if (cache->postprocessed.undistortion_used) + else if (cache->postprocessed.undistortion_used) { return NULL; + } IMB_refImBuf(cache->postprocessed.ibuf); @@ -905,8 +923,9 @@ static ImBuf *postprocess_frame( bool disable_blue = (postprocess_flag & MOVIECLIP_DISABLE_BLUE) != 0; bool grayscale = (postprocess_flag & MOVIECLIP_PREVIEW_GRAYSCALE) != 0; - if (disable_red || disable_green || disable_blue || grayscale) + if (disable_red || disable_green || disable_blue || grayscale) { BKE_tracking_disable_channels(postproc_ibuf, disable_red, disable_green, disable_blue, 1); + } } return postproc_ibuf; @@ -943,8 +962,9 @@ static void put_postprocessed_frame_to_cache( IMB_refImBuf(ibuf); - if (cache->postprocessed.ibuf) + if (cache->postprocessed.ibuf) { IMB_freeImBuf(cache->postprocessed.ibuf); + } cache->postprocessed.ibuf = ibuf; } @@ -964,12 +984,14 @@ static ImBuf *movieclip_get_postprocessed_ibuf( if (need_postprocessed_frame(user, flag, postprocess_flag)) { ibuf = get_postprocessed_cached_frame(clip, user, flag, postprocess_flag); - if (!ibuf) + if (!ibuf) { need_postprocess = true; + } } - if (!ibuf) + if (!ibuf) { ibuf = get_imbuf_cache(clip, user, flag); + } if (!ibuf) { bool use_sequence = false; @@ -1054,25 +1076,31 @@ static ImBuf *get_stable_cached_frame( } /* there's no cached frame or it was calculated for another frame */ - if (!cache->stabilized.ibuf || cache->stabilized.framenr != framenr) + if (!cache->stabilized.ibuf || cache->stabilized.framenr != framenr) { return NULL; + } - if (cache->stabilized.reference_ibuf != reference_ibuf) + if (cache->stabilized.reference_ibuf != reference_ibuf) { return NULL; + } /* cached ibuf used different proxy settings */ - if (cache->stabilized.render_flag != render_flag || cache->stabilized.proxy != proxy) + if (cache->stabilized.render_flag != render_flag || cache->stabilized.proxy != proxy) { return NULL; + } - if (cache->stabilized.postprocess_flag != postprocess_flag) + if (cache->stabilized.postprocess_flag != postprocess_flag) { return NULL; + } /* stabilization also depends on pixel aspect ratio */ - if (cache->stabilized.aspect != tracking->camera.pixel_aspect) + if (cache->stabilized.aspect != tracking->camera.pixel_aspect) { return NULL; + } - if (cache->stabilized.filter != tracking->stabilization.filter) + if (cache->stabilized.filter != tracking->stabilization.filter) { return NULL; + } stableibuf = cache->stabilized.ibuf; @@ -1121,8 +1149,9 @@ static ImBuf *put_stabilized_frame_to_cache( cache->stabilized.postprocess_flag = postprocess_flag; - if (cache->stabilized.ibuf) + if (cache->stabilized.ibuf) { IMB_freeImBuf(cache->stabilized.ibuf); + } cache->stabilized.ibuf = stableibuf; @@ -1143,35 +1172,43 @@ ImBuf *BKE_movieclip_get_stable_ibuf(MovieClip *clip, ibuf = BKE_movieclip_get_postprocessed_ibuf(clip, user, postprocess_flag); - if (!ibuf) + if (!ibuf) { return NULL; + } if (clip->tracking.stabilization.flag & TRACKING_2D_STABILIZATION) { MovieClipCache *cache = clip->cache; stableibuf = get_stable_cached_frame(clip, user, ibuf, framenr, postprocess_flag); - if (!stableibuf) + if (!stableibuf) { stableibuf = put_stabilized_frame_to_cache(clip, user, ibuf, framenr, postprocess_flag); + } - if (loc) + if (loc) { copy_v2_v2(loc, cache->stabilized.loc); + } - if (scale) + if (scale) { *scale = cache->stabilized.scale; + } - if (angle) + if (angle) { *angle = cache->stabilized.angle; + } } else { - if (loc) + if (loc) { zero_v2(loc); + } - if (scale) + if (scale) { *scale = 1.0f; + } - if (angle) + if (angle) { *angle = 0.0f; + } stableibuf = ibuf; } @@ -1224,8 +1261,9 @@ void BKE_movieclip_get_size(MovieClip *clip, MovieClipUser *user, int *width, in *height = clip->lastsize[1]; } - if (ibuf) + if (ibuf) { IMB_freeImBuf(ibuf); + } } } void BKE_movieclip_get_size_fl(MovieClip *clip, MovieClipUser *user, float size[2]) @@ -1300,11 +1338,13 @@ static void free_buffers(MovieClip *clip) if (clip->cache) { IMB_moviecache_free(clip->cache->moviecache); - if (clip->cache->postprocessed.ibuf) + if (clip->cache->postprocessed.ibuf) { IMB_freeImBuf(clip->cache->postprocessed.ibuf); + } - if (clip->cache->stabilized.ibuf) + if (clip->cache->stabilized.ibuf) { IMB_freeImBuf(clip->cache->stabilized.ibuf); + } MEM_freeN(clip->cache); clip->cache = NULL; @@ -1356,8 +1396,9 @@ void BKE_movieclip_reload(Main *bmain, MovieClip *clip) void BKE_movieclip_update_scopes(MovieClip *clip, MovieClipUser *user, MovieClipScopes *scopes) { - if (scopes->ok) + if (scopes->ok) { return; + } if (scopes->track_preview) { IMB_freeImBuf(scopes->track_preview); @@ -1459,17 +1500,20 @@ static void movieclip_build_proxy_ibuf( scaleibuf = IMB_dupImBuf(ibuf); - if (threaded) + if (threaded) { IMB_scaleImBuf_threaded(scaleibuf, (short)rectx, (short)recty); - else + } + else { IMB_scaleImBuf(scaleibuf, (short)rectx, (short)recty); + } quality = clip->proxy.quality; scaleibuf->ftype = IMB_FTYPE_JPG; scaleibuf->foptions.quality = quality; /* unsupported feature only confuses other s/w */ - if (scaleibuf->planes == 32) + if (scaleibuf->planes == 32) { scaleibuf->planes = 24; + } /* TODO: currently the most weak part of multithreaded proxies, * could be solved in a way that thread only prepares memory @@ -1478,8 +1522,9 @@ static void movieclip_build_proxy_ibuf( BLI_thread_lock(LOCK_MOVIECLIP); BLI_make_existing_file(name); - if (IMB_saveiff(scaleibuf, name, IB_rect) == 0) + if (IMB_saveiff(scaleibuf, name, IB_rect) == 0) { perror(name); + } BLI_thread_unlock(LOCK_MOVIECLIP); @@ -1500,8 +1545,9 @@ void BKE_movieclip_build_proxy_frame(MovieClip *clip, ImBuf *ibuf; MovieClipUser user; - if (!build_count) + if (!build_count) { return; + } user.framenr = cfra; user.render_flag = 0; @@ -1513,16 +1559,19 @@ void BKE_movieclip_build_proxy_frame(MovieClip *clip, ImBuf *tmpibuf = ibuf; int i; - if (undistorted) + if (undistorted) { tmpibuf = get_undistorted_ibuf(clip, distortion, ibuf); + } - for (i = 0; i < build_count; i++) + for (i = 0; i < build_count; i++) { movieclip_build_proxy_ibuf(clip, tmpibuf, cfra, build_sizes[i], undistorted, true); + } IMB_freeImBuf(ibuf); - if (tmpibuf != ibuf) + if (tmpibuf != ibuf) { IMB_freeImBuf(tmpibuf); + } } } @@ -1537,21 +1586,25 @@ void BKE_movieclip_build_proxy_frame_for_ibuf(MovieClip *clip, int build_count, bool undistorted) { - if (!build_count) + if (!build_count) { return; + } if (ibuf) { ImBuf *tmpibuf = ibuf; int i; - if (undistorted) + if (undistorted) { tmpibuf = get_undistorted_ibuf(clip, distortion, ibuf); + } - for (i = 0; i < build_count; i++) + for (i = 0; i < build_count; i++) { movieclip_build_proxy_ibuf(clip, tmpibuf, cfra, build_sizes[i], undistorted, false); + } - if (tmpibuf != ibuf) + if (tmpibuf != ibuf) { IMB_freeImBuf(tmpibuf); + } } } @@ -1566,8 +1619,10 @@ void BKE_movieclip_free(MovieClip *clip) } /** - * Only copy internal data of MovieClip ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of MovieClip ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * diff --git a/source/blender/blenkernel/intern/multires.c b/source/blender/blenkernel/intern/multires.c index 5e404f7e264..e3953af7cbf 100644 --- a/source/blender/blenkernel/intern/multires.c +++ b/source/blender/blenkernel/intern/multires.c @@ -117,8 +117,9 @@ static BLI_bitmap *multires_mdisps_upsample_hidden(BLI_bitmap *lo_hidden, BLI_assert(lo_level <= hi_level); /* fast case */ - if (lo_level == hi_level) + if (lo_level == hi_level) { return MEM_dupallocN(lo_hidden); + } subd = BLI_BITMAP_NEW(SQUARE(hi_gridsize), "MDisps.hidden upsample"); @@ -133,13 +134,15 @@ static BLI_bitmap *multires_mdisps_upsample_hidden(BLI_bitmap *lo_hidden, /* high-res blocks */ for (yo = -offset; yo <= offset; yo++) { yh = yl * factor + yo; - if (yh < 0 || yh >= hi_gridsize) + if (yh < 0 || yh >= hi_gridsize) { continue; + } for (xo = -offset; xo <= offset; xo++) { xh = xl * factor + xo; - if (xh < 0 || xh >= hi_gridsize) + if (xh < 0 || xh >= hi_gridsize) { continue; + } hi_ndx = yh * hi_gridsize + xh; @@ -220,8 +223,9 @@ static void multires_mdisps_subdivide_hidden(MDisps *md, int new_level) BLI_assert(md->hidden); /* nothing to do if already subdivided enough */ - if (md->level >= new_level) + if (md->level >= new_level) { return; + } subd = multires_mdisps_upsample_hidden(md->hidden, md->level, new_level, NULL); @@ -247,8 +251,9 @@ static MDisps *multires_mdisps_initialize_hidden(Mesh *me, int level) } } - if (!hide) + if (!hide) { continue; + } for (j = 0; j < me->mpoly[i].totloop; j++) { MDisps *md = &mdisps[me->mpoly[i].loopstart + j]; @@ -291,8 +296,9 @@ MultiresModifierData *find_multires_modifier_before(Scene *scene, ModifierData * for (md = lastmd; md; md = md->prev) { if (md->type == eModifierType_Multires) { - if (modifier_isEnabled(scene, md, eModifierMode_Realtime)) + if (modifier_isEnabled(scene, md, eModifierMode_Realtime)) { return (MultiresModifierData *)md; + } } } @@ -310,8 +316,9 @@ MultiresModifierData *get_multires_modifier(Scene *scene, Object *ob, bool use_f /* find first active multires modifier */ for (md = ob->modifiers.first; md; md = md->next) { if (md->type == eModifierType_Multires) { - if (!firstmmd) + if (!firstmmd) { firstmmd = (MultiresModifierData *)md; + } if (modifier_isEnabled(scene, md, eModifierMode_Realtime)) { mmd = (MultiresModifierData *)md; @@ -335,23 +342,28 @@ int multires_get_level(const Scene *scene, bool render, bool ignore_simplify) { - if (render) + if (render) { return (scene != NULL) ? get_render_subsurf_level(&scene->r, mmd->renderlvl, true) : mmd->renderlvl; - else if (ob->mode == OB_MODE_SCULPT) + } + else if (ob->mode == OB_MODE_SCULPT) { return mmd->sculptlvl; - else if (ignore_simplify) + } + else if (ignore_simplify) { return mmd->lvl; - else + } + else { return (scene != NULL) ? get_render_subsurf_level(&scene->r, mmd->lvl, false) : mmd->lvl; + } } void multires_set_tot_level(Object *ob, MultiresModifierData *mmd, int lvl) { mmd->totlvl = lvl; - if (ob->mode != OB_MODE_SCULPT) + if (ob->mode != OB_MODE_SCULPT) { mmd->lvl = CLAMPIS(MAX2(mmd->lvl, lvl), 0, mmd->totlvl); + } mmd->sculptlvl = CLAMPIS(MAX2(mmd->sculptlvl, lvl), 0, mmd->totlvl); mmd->renderlvl = CLAMPIS(MAX2(mmd->renderlvl, lvl), 0, mmd->totlvl); @@ -418,8 +430,9 @@ void multires_force_external_reload(Object *ob) void multires_force_render_update(Object *ob) { - if (ob && (ob->mode & OB_MODE_SCULPT) && modifiers_findByType(ob, eModifierType_Multires)) + if (ob && (ob->mode & OB_MODE_SCULPT) && modifiers_findByType(ob, eModifierType_Multires)) { multires_force_update(ob); + } } /* reset the multires levels to match the number of mdisps */ @@ -435,18 +448,22 @@ static int get_levels_from_disps(Object *ob) md = mdisp + me->mpoly[i].loopstart; for (j = 0; j < me->mpoly[i].totloop; j++, md++) { - if (md->totdisp == 0) + if (md->totdisp == 0) { continue; + } while (1) { int side = (1 << (totlvl - 1)) + 1; int lvl_totdisp = side * side; - if (md->totdisp == lvl_totdisp) + if (md->totdisp == lvl_totdisp) { break; - else if (md->totdisp < lvl_totdisp) + } + else if (md->totdisp < lvl_totdisp) { totlvl--; - else + } + else { totlvl++; + } } break; @@ -462,10 +479,12 @@ void multiresModifier_set_levels_from_disps(MultiresModifierData *mmd, Object *o Mesh *me = ob->data; MDisps *mdisp; - if (me->edit_mesh) + if (me->edit_mesh) { mdisp = CustomData_get_layer(&me->edit_mesh->bm->ldata, CD_MDISPS); - else + } + else { mdisp = CustomData_get_layer(&me->ldata, CD_MDISPS); + } if (mdisp) { mmd->totlvl = get_levels_from_disps(ob); @@ -497,11 +516,13 @@ static void multires_reallocate_mdisps(int totloop, MDisps *mdisps, int lvl) int totdisp = multires_grid_tot[lvl]; float(*disps)[3] = MEM_calloc_arrayN(totdisp, 3 * sizeof(float), "multires disps"); - if (mdisps[i].disps) + if (mdisps[i].disps) { MEM_freeN(mdisps[i].disps); + } - if (mdisps[i].level && mdisps[i].hidden) + if (mdisps[i].level && mdisps[i].hidden) { multires_mdisps_subdivide_hidden(&mdisps[i], lvl); + } mdisps[i].disps = disps; mdisps[i].totdisp = totdisp; @@ -516,16 +537,20 @@ static void multires_copy_grid(float (*gridA)[3], float (*gridB)[3], int sizeA, if (sizeA > sizeB) { skip = (sizeA - 1) / (sizeB - 1); - for (j = 0, y = 0; y < sizeB; y++) - for (x = 0; x < sizeB; x++, j++) + for (j = 0, y = 0; y < sizeB; y++) { + for (x = 0; x < sizeB; x++, j++) { copy_v3_v3(gridA[y * skip * sizeA + x * skip], gridB[j]); + } + } } else { skip = (sizeB - 1) / (sizeA - 1); - for (j = 0, y = 0; y < sizeA; y++) - for (x = 0; x < sizeA; x++, j++) + for (j = 0, y = 0; y < sizeA; y++) { + for (x = 0; x < sizeA; x++, j++) { copy_v3_v3(gridA[j], gridB[y * skip * sizeB + x * skip]); + } + } } } @@ -536,20 +561,24 @@ static void multires_copy_dm_grid(CCGElem *gridA, CCGElem *gridB, CCGKey *keyA, if (keyA->grid_size > keyB->grid_size) { skip = (keyA->grid_size - 1) / (keyB->grid_size - 1); - for (j = 0, y = 0; y < keyB->grid_size; y++) - for (x = 0; x < keyB->grid_size; x++, j++) + for (j = 0, y = 0; y < keyB->grid_size; y++) { + for (x = 0; x < keyB->grid_size; x++, j++) { memcpy(CCG_elem_offset_co(keyA, gridA, y * skip * keyA->grid_size + x * skip), CCG_elem_offset_co(keyB, gridB, j), keyA->elem_size); + } + } } else { skip = (keyB->grid_size - 1) / (keyA->grid_size - 1); - for (j = 0, y = 0; y < keyA->grid_size; y++) - for (x = 0; x < keyA->grid_size; x++, j++) + for (j = 0, y = 0; y < keyA->grid_size; y++) { + for (x = 0; x < keyA->grid_size; x++, j++) { memcpy(CCG_elem_offset_co(keyA, gridA, j), CCG_elem_offset_co(keyB, gridB, y * skip * keyB->grid_size + x * skip), keyA->elem_size); + } + } } } @@ -679,8 +708,9 @@ static DerivedMesh *multires_dm_create_local(Scene *scene, mmd.simple = simple; flags |= MULTIRES_USE_LOCAL_MMD; - if (alloc_paint_mask) + if (alloc_paint_mask) { flags |= MULTIRES_ALLOC_PAINT_MASK; + } return multires_make_derived_from_derived(dm, &mmd, scene, ob, flags); } @@ -749,8 +779,9 @@ void multiresModifier_base_apply(MultiresModifierData *mmd, Scene *scene, Object totlvl = mmd->totlvl; /* nothing to do */ - if (!totlvl) + if (!totlvl) { return; + } /* XXX - probably not necessary to regenerate the cddm so much? */ @@ -772,8 +803,9 @@ void multiresModifier_base_apply(MultiresModifierData *mmd, Scene *scene, Object cddm = CDDM_from_mesh(me); pmap = cddm->getPolyMap(ob, cddm); origco = MEM_calloc_arrayN(me->totvert, 3 * sizeof(float), "multires apply base origco"); - for (i = 0; i < me->totvert; ++i) + for (i = 0; i < me->totvert; ++i) { copy_v3_v3(origco[i], me->mvert[i].co); + } for (i = 0; i < me->totvert; ++i) { float avg_no[3] = {0, 0, 0}, center[3] = {0, 0, 0}, push[3]; @@ -781,8 +813,9 @@ void multiresModifier_base_apply(MultiresModifierData *mmd, Scene *scene, Object int tot = 0; /* don't adjust verts not used by at least one poly */ - if (!pmap[i].count) + if (!pmap[i].count) { continue; + } /* find center */ for (j = 0; j < pmap[i].count; j++) { @@ -819,10 +852,12 @@ void multiresModifier_base_apply(MultiresModifierData *mmd, Scene *scene, Object fake_loops[k].v = k; - if (vndx == i) + if (vndx == i) { copy_v3_v3(fake_co[k], center); - else + } + else { copy_v3_v3(fake_co[k], origco[vndx]); + } } BKE_mesh_calc_poly_normal_coords(&fake_poly, fake_loops, (const float(*)[3])fake_co, no); @@ -879,16 +914,18 @@ static void multires_subdivide( MDisps *mdisps; const int lvl = mmd->totlvl; - if ((totlvl > multires_max_levels) || (me->totpoly == 0)) + if ((totlvl > multires_max_levels) || (me->totpoly == 0)) { return; + } BLI_assert(totlvl > lvl); multires_force_update(ob); mdisps = CustomData_get_layer(&me->ldata, CD_MDISPS); - if (!mdisps) + if (!mdisps) { mdisps = multires_mdisps_initialize_hidden(me, totlvl); + } if (mdisps->disps && !updateblock && lvl != 0) { /* upsample */ @@ -955,8 +992,9 @@ static void multires_subdivide( /* free */ highdm->release(highdm); - for (i = 0; i < numGrids; ++i) + for (i = 0; i < numGrids; ++i) { MEM_freeN(subGridData[i]); + } MEM_freeN(subGridData); } else { @@ -977,25 +1015,31 @@ static void grid_tangent(const CCGKey *key, int x, int y, int axis, CCGElem *gri { if (axis == 0) { if (x == key->grid_size - 1) { - if (y == key->grid_size - 1) + if (y == key->grid_size - 1) { sub_v3_v3v3( t, CCG_grid_elem_co(key, grid, x, y - 1), CCG_grid_elem_co(key, grid, x - 1, y - 1)); - else + } + else { sub_v3_v3v3(t, CCG_grid_elem_co(key, grid, x, y), CCG_grid_elem_co(key, grid, x - 1, y)); + } } - else + else { sub_v3_v3v3(t, CCG_grid_elem_co(key, grid, x + 1, y), CCG_grid_elem_co(key, grid, x, y)); + } } else if (axis == 1) { if (y == key->grid_size - 1) { - if (x == key->grid_size - 1) + if (x == key->grid_size - 1) { sub_v3_v3v3( t, CCG_grid_elem_co(key, grid, x - 1, y), CCG_grid_elem_co(key, grid, x - 1, (y - 1))); - else + } + else { sub_v3_v3v3(t, CCG_grid_elem_co(key, grid, x, y), CCG_grid_elem_co(key, grid, x, (y - 1))); + } } - else + else { sub_v3_v3v3(t, CCG_grid_elem_co(key, grid, x, (y + 1)), CCG_grid_elem_co(key, grid, x, y)); + } } } @@ -1147,10 +1191,12 @@ static void multiresModifier_disp_run( } if (!mdisps) { - if (op == CALC_DISPLACEMENTS) + if (op == CALC_DISPLACEMENTS) { mdisps = CustomData_add_layer(&me->ldata, CD_MDISPS, CD_DEFAULT, NULL, me->totloop); - else + } + else { return; + } } /*numGrids = dm->getNumGrids(dm);*/ /*UNUSED*/ @@ -1164,8 +1210,9 @@ static void multiresModifier_disp_run( dSkip = (dGridSize - 1) / (gridSize - 1); /* multires paint masks */ - if (key.has_mask) + if (key.has_mask) { grid_paint_mask = CustomData_get_layer(&me->ldata, CD_GRID_PAINT_MASK); + } /* when adding new faces in edit mode, need to allocate disps */ for (i = 0; i < totloop; ++i) { @@ -1229,10 +1276,12 @@ void multires_modifier_update_mdisps(struct DerivedMesh *dm, Scene *scene) const bool has_mask = CustomData_has_layer(&me->ldata, CD_GRID_PAINT_MASK); /* create subsurf DM from original mesh at high level */ - if (ob->derivedDeform) + if (ob->derivedDeform) { cddm = CDDM_copy(ob->derivedDeform); - else + } + else { cddm = CDDM_from_mesh(me); + } DM_set_only_copy(cddm, &CD_MASK_BAREMESH); highdm = subsurf_dm_create_local(scene, @@ -1297,18 +1346,21 @@ void multires_modifier_update_mdisps(struct DerivedMesh *dm, Scene *scene) /* free */ highdm->release(highdm); - for (i = 0; i < numGrids; ++i) + for (i = 0; i < numGrids; ++i) { MEM_freeN(subGridData[i]); + } MEM_freeN(subGridData); } else { DerivedMesh *cddm, *subdm; const bool has_mask = CustomData_has_layer(&me->ldata, CD_GRID_PAINT_MASK); - if (ob->derivedDeform) + if (ob->derivedDeform) { cddm = CDDM_copy(ob->derivedDeform); - else + } + else { cddm = CDDM_from_mesh(me); + } DM_set_only_copy(cddm, &CD_MASK_BAREMESH); subdm = subsurf_dm_create_local(scene, @@ -1353,8 +1405,9 @@ void multires_modifier_update_hidden(DerivedMesh *dm) } else if (gh) { gh = multires_mdisps_upsample_hidden(gh, lvl, totlvl, md->hidden); - if (md->hidden) + if (md->hidden) { MEM_freeN(md->hidden); + } md->hidden = gh; } @@ -1402,8 +1455,9 @@ DerivedMesh *multires_make_derived_from_derived( int lvl = multires_get_level(scene, ob, mmd, render, ignore_simplify); int i, gridSize, numGrids; - if (lvl == 0) + if (lvl == 0) { return dm; + } const int subsurf_flags = ignore_simplify ? SUBSURF_IGNORE_SIMPLIFY : 0; @@ -1448,11 +1502,13 @@ DerivedMesh *multires_make_derived_from_derived( multiresModifier_disp_run(result, ob->data, dm, APPLY_DISPLACEMENTS, subGridData, mmd->totlvl); /* copy hidden elements for this level */ - if (ccgdm) + if (ccgdm) { multires_output_hidden_to_ccgdm(ccgdm, me, lvl); + } - for (i = 0; i < numGrids; i++) + for (i = 0; i < numGrids; i++) { MEM_freeN(subGridData[i]); + } MEM_freeN(subGridData); return result; @@ -1469,27 +1525,34 @@ void old_mdisps_bilinear(float out[3], float (*disps)[3], const int st, float u, float urat, vrat, uopp; float d[4][3], d2[2][3]; - if (!disps || isnan(u) || isnan(v)) + if (!disps || isnan(u) || isnan(v)) { return; + } - if (u < 0) + if (u < 0) { u = 0; - else if (u >= st) + } + else if (u >= st) { u = st_max; - if (v < 0) + } + if (v < 0) { v = 0; - else if (v >= st) + } + else if (v >= st) { v = st_max; + } x = floor(u); y = floor(v); x2 = x + 1; y2 = y + 1; - if (x2 >= st) + if (x2 >= st) { x2 = st_max; - if (y2 >= st) + } + if (y2 >= st) { y2 = st_max; + } urat = u - x; vrat = v - y; @@ -1585,9 +1648,11 @@ void multires_load_old_250(Mesh *me) mdisps = CustomData_get_layer(&me->fdata, CD_MDISPS); if (mdisps) { - for (i = 0; i < me->totface; i++) - if (mdisps[i].totdisp) + for (i = 0; i < me->totface; i++) { + if (mdisps[i].totdisp) { old_mdisps_convert(&me->mface[i], &mdisps[i]); + } + } CustomData_add_layer(&me->ldata, CD_MDISPS, CD_CALLOC, NULL, me->totloop); mdisps2 = CustomData_get_layer(&me->ldata, CD_MDISPS); @@ -1613,12 +1678,15 @@ void multires_load_old_250(Mesh *me) static void multires_free_level(MultiresLevel *lvl) { if (lvl) { - if (lvl->faces) + if (lvl->faces) { MEM_freeN(lvl->faces); - if (lvl->edges) + } + if (lvl->edges) { MEM_freeN(lvl->edges); - if (lvl->colfaces) + } + if (lvl->colfaces) { MEM_freeN(lvl->colfaces); + } } } @@ -1631,10 +1699,12 @@ void multires_free(Multires *mr) if (lvl) { CustomData_free(&mr->vdata, lvl->totvert); CustomData_free(&mr->fdata, lvl->totface); - if (mr->edge_flags) + if (mr->edge_flags) { MEM_freeN(mr->edge_flags); - if (mr->edge_creases) + } + if (mr->edge_creases) { MEM_freeN(mr->edge_creases); + } } while (lvl) { @@ -1642,7 +1712,8 @@ void multires_free(Multires *mr) lvl = lvl->next; } - /* mr->verts may be NULL when loading old files, see direct_link_mesh() in readfile.c, and T43560. */ + /* mr->verts may be NULL when loading old files, + * see direct_link_mesh() in readfile.c, and T43560. */ MEM_SAFE_FREE(mr->verts); BLI_freelistN(&mr->levels); @@ -1716,13 +1787,15 @@ static MultiresFace *find_old_face( for (i = 0; i < 4; ++i) { for (j = 0; j < 4; ++j) { - if (v[i] == faces[n1->index].v[j]) + if (v[i] == faces[n1->index].v[j]) { fnd[i] = 1; + } } } - if (fnd[0] && fnd[1] && fnd[2] && fnd[3]) + if (fnd[0] && fnd[1] && fnd[2] && fnd[3]) { return &faces[n1->index]; + } } return NULL; @@ -1734,8 +1807,9 @@ static MultiresEdge *find_old_edge(ListBase *map, MultiresEdge *edges, int v1, i for (n1 = map[v1].first; n1; n1 = n1->next) { for (n2 = map[v2].first; n2; n2 = n2->next) { - if (n1->index == n2->index) + if (n1->index == n2->index) { return &edges[n1->index]; + } } } @@ -1941,8 +2015,9 @@ static void multires_load_old_dm(DerivedMesh *dm, Mesh *me, int totlvl) int skip = multires_side_tot[totlvl - j + 2] - 1; int st = multires_side_tot[j - 1] - 1; - for (x = 0; x < st; ++x) + for (x = 0; x < st; ++x) { vvmap[ldst + base + x * skip] = lsrc + st * i + x; + } lsrc += lvl->totvert - lvl->prev->totvert; lvl = lvl->next; @@ -1998,10 +2073,12 @@ static void multires_load_old_dm(DerivedMesh *dm, Mesh *me, int totlvl) dst += sides * (st_last - 1) * st_last; - if (sides == 4) + if (sides == 4) { ++totquad; - else + } + else { ++tottri; + } } /* calculate vert to edge/face maps for each level (except the last) */ @@ -2066,8 +2143,9 @@ static void multires_load_old_dm(DerivedMesh *dm, Mesh *me, int totlvl) } /* Transfer verts */ - for (i = 0; i < totvert; ++i) + for (i = 0; i < totvert; ++i) { copy_v3_v3(vdst[i].co, vsrc[vvmap[i]].co); + } MEM_freeN(vvmap); @@ -2083,16 +2161,19 @@ static void multires_load_old_vcols(Mesh *me) MCol *mcol; int i, j; - if (!(lvl = me->mr->levels.first)) + if (!(lvl = me->mr->levels.first)) { return; + } - if (!(colface = lvl->colfaces)) + if (!(colface = lvl->colfaces)) { return; + } /* older multires format never supported multiple vcol layers, * so we can assume the active vcol layer is the correct one */ - if (!(mcol = CustomData_get_layer(&me->fdata, CD_MCOL))) + if (!(mcol = CustomData_get_layer(&me->fdata, CD_MCOL))) { return; + } for (i = 0; i < me->totface; ++i) { for (j = 0; j < 4; ++j) { @@ -2111,14 +2192,17 @@ static void multires_load_old_face_flags(Mesh *me) MultiresFace *faces; int i; - if (!(lvl = me->mr->levels.first)) + if (!(lvl = me->mr->levels.first)) { return; + } - if (!(faces = lvl->faces)) + if (!(faces = lvl->faces)) { return; + } - for (i = 0; i < me->totface; ++i) + for (i = 0; i < me->totface; ++i) { me->mface[i].flag = faces[i].flag; + } } void multires_load_old(Object *ob, Mesh *me) @@ -2156,10 +2240,12 @@ void multires_load_old(Object *ob, Mesh *me) /* Copy the first-level data to the mesh */ /* XXX We must do this before converting tessfaces to polys/lopps! */ - for (i = 0, l = me->mr->vdata.layers; i < me->mr->vdata.totlayer; ++i, ++l) + for (i = 0, l = me->mr->vdata.layers; i < me->mr->vdata.totlayer; ++i, ++l) { CustomData_add_layer(&me->vdata, l->type, CD_REFERENCE, l->data, me->totvert); - for (i = 0, l = me->mr->fdata.layers; i < me->mr->fdata.totlayer; ++i, ++l) + } + for (i = 0, l = me->mr->fdata.layers; i < me->mr->fdata.totlayer; ++i, ++l) { CustomData_add_layer(&me->fdata, l->type, CD_REFERENCE, l->data, me->totface); + } CustomData_reset(&me->mr->vdata); CustomData_reset(&me->mr->fdata); @@ -2171,13 +2257,15 @@ void multires_load_old(Object *ob, Mesh *me) /* Add a multires modifier to the object */ md = ob->modifiers.first; - while (md && modifierType_getInfo(md->type)->type == eModifierTypeType_OnlyDeform) + while (md && modifierType_getInfo(md->type)->type == eModifierTypeType_OnlyDeform) { md = md->next; + } mmd = (MultiresModifierData *)modifier_new(eModifierType_Multires); BLI_insertlinkbefore(&ob->modifiers, md, mmd); - for (i = 0; i < me->mr->level_count - 1; ++i) + for (i = 0; i < me->mr->level_count - 1; ++i) { multiresModifier_subdivide(mmd, NULL, ob, 1, 0); + } mmd->lvl = mmd->totlvl; orig = CDDM_from_mesh(me); @@ -2283,8 +2371,9 @@ int multires_mdisp_corners(MDisps *s) while (lvl > 0) { int side = (1 << (lvl - 1)) + 1; - if ((s->totdisp % (side * side)) == 0) + if ((s->totdisp % (side * side)) == 0) { return s->totdisp / (side * side); + } lvl--; } @@ -2327,8 +2416,9 @@ void multires_topology_changed(Mesh *me) CustomData_external_read(&me->ldata, &me->id, CD_MASK_MDISPS, me->totloop); mdisp = CustomData_get_layer(&me->ldata, CD_MDISPS); - if (!mdisp) + if (!mdisp) { return; + } cur = mdisp; for (i = 0; i < me->totloop; i++, cur++) { @@ -2369,14 +2459,18 @@ int mdisp_rot_face_to_crn(struct MVert *UNUSED(mvert), int S = 0; if (mpoly->totloop == 4) { - if (u <= offset && v <= offset) + if (u <= offset && v <= offset) { S = 0; - else if (u > offset && v <= offset) + } + else if (u > offset && v <= offset) { S = 1; - else if (u > offset && v > offset) + } + else if (u > offset && v > offset) { S = 2; - else if (u <= offset && v >= offset) + } + else if (u <= offset && v >= offset) { S = 3; + } if (S == 0) { *y = offset - u; diff --git a/source/blender/blenkernel/intern/nla.c b/source/blender/blenkernel/intern/nla.c index 3b33af62073..15e53e12ece 100644 --- a/source/blender/blenkernel/intern/nla.c +++ b/source/blender/blenkernel/intern/nla.c @@ -74,8 +74,9 @@ void BKE_nlastrip_free(ListBase *strips, NlaStrip *strip, bool do_id_user) NlaStrip *cs, *csn; /* sanity checks */ - if (strip == NULL) + if (strip == NULL) { return; + } /* free child-strips */ for (cs = strip->strips.first; cs; cs = csn) { @@ -89,7 +90,7 @@ void BKE_nlastrip_free(ListBase *strips, NlaStrip *strip, bool do_id_user) } /* free remapping info */ - //if (strip->remap) + // if (strip->remap) // BKE_animremap_free(); /* free own F-Curves */ @@ -99,10 +100,12 @@ void BKE_nlastrip_free(ListBase *strips, NlaStrip *strip, bool do_id_user) free_fmodifiers(&strip->modifiers); /* free the strip itself */ - if (strips) + if (strips) { BLI_freelinkN(strips, strip); - else + } + else { MEM_freeN(strip); + } } /* Remove the given NLA track from the set of NLA tracks, free the track's data, @@ -113,8 +116,9 @@ void BKE_nlatrack_free(ListBase *tracks, NlaTrack *nlt, bool do_id_user) NlaStrip *strip, *stripn; /* sanity checks */ - if (nlt == NULL) + if (nlt == NULL) { return; + } /* free strips */ for (strip = nlt->strips.first; strip; strip = stripn) { @@ -123,10 +127,12 @@ void BKE_nlatrack_free(ListBase *tracks, NlaTrack *nlt, bool do_id_user) } /* free NLA track itself now */ - if (tracks) + if (tracks) { BLI_freelinkN(tracks, nlt); - else + } + else { MEM_freeN(nlt); + } } /* Free the elements of type NLA Tracks provided in the given list, but do not free @@ -137,8 +143,9 @@ void BKE_nla_tracks_free(ListBase *tracks, bool do_id_user) NlaTrack *nlt, *nltn; /* sanity checks */ - if (ELEM(NULL, tracks, tracks->first)) + if (ELEM(NULL, tracks, tracks->first)) { return; + } /* free tracks one by one */ for (nlt = tracks->first; nlt; nlt = nltn) { @@ -156,7 +163,8 @@ void BKE_nla_tracks_free(ListBase *tracks, bool do_id_user) * Copy NLA strip * * \param use_same_action: When true, the existing action is used (instead of being duplicated) - * \param flag: Control ID pointers management, see LIB_ID_CREATE_.../LIB_ID_COPY_... flags in BKE_library.h + * \param flag: Control ID pointers management, see LIB_ID_CREATE_.../LIB_ID_COPY_... + * flags in BKE_library.h */ NlaStrip *BKE_nlastrip_copy(Main *bmain, NlaStrip *strip, @@ -169,8 +177,9 @@ NlaStrip *BKE_nlastrip_copy(Main *bmain, const bool do_id_user = (flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0; /* sanity check */ - if (strip == NULL) + if (strip == NULL) { return NULL; + } /* make a copy */ strip_d = MEM_dupallocN(strip); @@ -208,7 +217,8 @@ NlaStrip *BKE_nlastrip_copy(Main *bmain, /** * Copy a single NLA Track. - * \param flag: Control ID pointers management, see LIB_ID_CREATE_.../LIB_ID_COPY_... flags in BKE_library.h + * \param flag: Control ID pointers management, see LIB_ID_CREATE_.../LIB_ID_COPY_... + * flags in BKE_library.h */ NlaTrack *BKE_nlatrack_copy(Main *bmain, NlaTrack *nlt, @@ -219,8 +229,9 @@ NlaTrack *BKE_nlatrack_copy(Main *bmain, NlaTrack *nlt_d; /* sanity check */ - if (nlt == NULL) + if (nlt == NULL) { return NULL; + } /* make a copy */ nlt_d = MEM_dupallocN(nlt); @@ -240,15 +251,17 @@ NlaTrack *BKE_nlatrack_copy(Main *bmain, /** * Copy all NLA data. - * \param flag: Control ID pointers management, see LIB_ID_CREATE_.../LIB_ID_COPY_... flags in BKE_library.h + * \param flag: Control ID pointers management, see LIB_ID_CREATE_.../LIB_ID_COPY_... + * flags in BKE_library.h */ void BKE_nla_tracks_copy(Main *bmain, ListBase *dst, ListBase *src, const int flag) { NlaTrack *nlt, *nlt_d; /* sanity checks */ - if (ELEM(NULL, dst, src)) + if (ELEM(NULL, dst, src)) { return; + } /* clear out the destination list first for precautions... */ BLI_listbase_clear(dst); @@ -272,8 +285,9 @@ NlaTrack *BKE_nlatrack_add(AnimData *adt, NlaTrack *prev) NlaTrack *nlt; /* sanity checks */ - if (adt == NULL) + if (adt == NULL) { return NULL; + } /* allocate new track */ nlt = MEM_callocN(sizeof(NlaTrack), "NlaTrack"); @@ -283,10 +297,12 @@ NlaTrack *BKE_nlatrack_add(AnimData *adt, NlaTrack *prev) nlt->index = BLI_listbase_count(&adt->nla_tracks); /* add track to stack, and make it the active one */ - if (prev) + if (prev) { BLI_insertlinkafter(&adt->nla_tracks, prev, nlt); - else + } + else { BLI_addtail(&adt->nla_tracks, nlt); + } BKE_nlatrack_set_active(&adt->nla_tracks, nlt); /* must have unique name, but we need to seed this */ @@ -304,8 +320,9 @@ NlaStrip *BKE_nlastrip_new(bAction *act) NlaStrip *strip; /* sanity checks */ - if (act == NULL) + if (act == NULL) { return NULL; + } /* allocate new strip */ strip = MEM_callocN(sizeof(NlaStrip), "NlaStrip"); @@ -340,20 +357,23 @@ NlaStrip *BKE_nlastrip_new(bAction *act) return strip; } -/* Add new NLA-strip to the top of the NLA stack - i.e. into the last track if space, or a new one otherwise */ +/* Add new NLA-strip to the top of the NLA stack - i.e. + * into the last track if space, or a new one otherwise. */ NlaStrip *BKE_nlastack_add_strip(AnimData *adt, bAction *act) { NlaStrip *strip; NlaTrack *nlt; /* sanity checks */ - if (ELEM(NULL, adt, act)) + if (ELEM(NULL, adt, act)) { return NULL; + } /* create a new NLA strip */ strip = BKE_nlastrip_new(act); - if (strip == NULL) + if (strip == NULL) { return NULL; + } /* firstly try adding strip to last track, but if that fails, add to a new track */ if (BKE_nlatrack_add_strip(adt->nla_tracks.last, strip) == 0) { @@ -422,20 +442,23 @@ static float nlastrip_get_frame_actionclip(NlaStrip *strip, float cframe, short // float repeat; // UNUSED /* get number of repeats */ - if (IS_EQF(strip->repeat, 0.0f)) + if (IS_EQF(strip->repeat, 0.0f)) { strip->repeat = 1.0f; + } // repeat = strip->repeat; // UNUSED /* scaling */ - if (IS_EQF(strip->scale, 0.0f)) + if (IS_EQF(strip->scale, 0.0f)) { strip->scale = 1.0f; + } scale = fabsf( strip->scale); /* scale must be positive - we've got a special flag for reversing */ /* length of referenced action */ actlength = strip->actend - strip->actstart; - if (IS_EQF(actlength, 0.0f)) + if (IS_EQF(actlength, 0.0f)) { actlength = 1.0f; + } /* reversed = play strip backwards */ if (strip->flag & NLASTRIP_FLAG_REVERSE) { @@ -448,10 +471,9 @@ static float nlastrip_get_frame_actionclip(NlaStrip *strip, float cframe, short } else { /* if (mode == NLATIME_CONVERT_EVAL) */ if (IS_EQF((float)cframe, strip->end) && IS_EQF(strip->repeat, floorf(strip->repeat))) { - /* this case prevents the motion snapping back to the first frame at the end of the strip - * by catching the case where repeats is a whole number, which means that the end of the strip - * could also be interpreted as the end of the start of a repeat - */ + /* This case prevents the motion snapping back to the first frame at the end of the strip + * by catching the case where repeats is a whole number, which means that the end of the + * strip could also be interpreted as the end of the start of a repeat. */ return strip->actstart; } else { @@ -471,10 +493,9 @@ static float nlastrip_get_frame_actionclip(NlaStrip *strip, float cframe, short } else { /* if (mode == NLATIME_CONVERT_EVAL) */ if (IS_EQF(cframe, strip->end) && IS_EQF(strip->repeat, floorf(strip->repeat))) { - /* this case prevents the motion snapping back to the first frame at the end of the strip - * by catching the case where repeats is a whole number, which means that the end of the strip - * could also be interpreted as the end of the start of a repeat - */ + /* This case prevents the motion snapping back to the first frame at the end of the strip + * by catching the case where repeats is a whole number, which means that the end of the + * strip could also be interpreted as the end of the start of a repeat. */ return strip->actend; } else { @@ -499,16 +520,20 @@ static float nlastrip_get_frame_transition(NlaStrip *strip, float cframe, short /* reversed = play strip backwards */ if (strip->flag & NLASTRIP_FLAG_REVERSE) { - if (mode == NLATIME_CONVERT_MAP) + if (mode == NLATIME_CONVERT_MAP) { return strip->end - (length * cframe); - else + } + else { return (strip->end - cframe) / length; + } } else { - if (mode == NLATIME_CONVERT_MAP) + if (mode == NLATIME_CONVERT_MAP) { return (length * cframe) + strip->start; - else + } + else { return (cframe - strip->start) / length; + } } } @@ -521,7 +546,8 @@ static float nlastrip_get_frame_transition(NlaStrip *strip, float cframe, short float nlastrip_get_frame(NlaStrip *strip, float cframe, short mode) { switch (strip->type) { - case NLASTRIP_TYPE_META: /* meta - for now, does the same as transition (is really just an empty container) */ + case NLASTRIP_TYPE_META: /* Meta - for now, does the same as transition + * (is really just an empty container). */ case NLASTRIP_TYPE_TRANSITION: /* transition */ return nlastrip_get_frame_transition(strip, cframe, mode); @@ -546,30 +572,34 @@ float BKE_nla_tweakedit_remap(AnimData *adt, float cframe, short mode) * - when not in tweakmode, the active Action does not have any scaling applied :) * - when in tweakmode, if the no-mapping flag is set, do not map */ - if ((adt == NULL) || (adt->flag & ADT_NLA_EDIT_ON) == 0 || (adt->flag & ADT_NLA_EDIT_NOMAP)) + if ((adt == NULL) || (adt->flag & ADT_NLA_EDIT_ON) == 0 || (adt->flag & ADT_NLA_EDIT_NOMAP)) { return cframe; + } /* if the active-strip info has been stored already, access this, otherwise look this up * and store for (very probable) future usage */ if (adt->act_track == NULL) { - if (adt->actstrip) + if (adt->actstrip) { adt->act_track = BKE_nlatrack_find_tweaked(adt); - else + } + else { adt->act_track = BKE_nlatrack_find_active(&adt->nla_tracks); + } } if (adt->actstrip == NULL) { adt->actstrip = BKE_nlastrip_find_active(adt->act_track); } strip = adt->actstrip; - /* sanity checks - * - in rare cases, we may not be able to find this strip for some reason (internal error) - * - for now, if the user has defined a curve to control the time, this correction cannot be performed - * reliably... + /* Sanity checks: + * - In rare cases, we may not be able to find this strip for some reason (internal error) + * - For now, if the user has defined a curve to control the time, this correction cannot be + * performed reliably. */ - if ((strip == NULL) || (strip->flag & NLASTRIP_FLAG_USR_TIME)) + if ((strip == NULL) || (strip->flag & NLASTRIP_FLAG_USR_TIME)) { return cframe; + } /* perform the correction now... */ return nlastrip_get_frame(strip, cframe, mode); @@ -587,8 +617,9 @@ bool BKE_nlastrips_has_space(ListBase *strips, float start, float end) NlaStrip *strip; /* sanity checks */ - if ((strips == NULL) || IS_EQF(start, end)) + if ((strips == NULL) || IS_EQF(start, end)) { return false; + } if (start > end) { puts("BKE_nlastrips_has_space() error... start and end arguments swapped"); SWAP(float, start, end); @@ -599,14 +630,16 @@ bool BKE_nlastrips_has_space(ListBase *strips, float start, float end) /* if start frame of strip is past the target end-frame, that means that * we've gone past the window we need to check for, so things are fine */ - if (strip->start >= end) + if (strip->start >= end) { return true; + } /* if the end of the strip is greater than either of the boundaries, the range * must fall within the extents of the strip */ - if ((strip->end > start) || (strip->end > end)) + if ((strip->end > start) || (strip->end > end)) { return false; + } } /* if we are still here, we haven't encountered any overlapping strips */ @@ -622,8 +655,9 @@ void BKE_nlastrips_sort_strips(ListBase *strips) NlaStrip *strip, *sstrip, *stripn; /* sanity checks */ - if (ELEM(NULL, strips, strips->first)) + if (ELEM(NULL, strips, strips->first)) { return; + } /* we simply perform insertion sort on this list, since it is assumed that per track, * there are only likely to be at most 5-10 strips @@ -648,8 +682,9 @@ void BKE_nlastrips_sort_strips(ListBase *strips) } /* add before first? */ - if (not_added) + if (not_added) { BLI_addhead(&tmp, strip); + } } /* reassign the start and end points of the strips */ @@ -666,12 +701,14 @@ bool BKE_nlastrips_add_strip(ListBase *strips, NlaStrip *strip) bool not_added = true; /* sanity checks */ - if (ELEM(NULL, strips, strip)) + if (ELEM(NULL, strips, strip)) { return false; + } /* check if any space to add */ - if (BKE_nlastrips_has_space(strips, strip->start, strip->end) == 0) + if (BKE_nlastrips_has_space(strips, strip->start, strip->end) == 0) { return false; + } /* find the right place to add the strip to the nominated track */ for (ns = strips->first; ns; ns = ns->next) { @@ -703,8 +740,9 @@ void BKE_nlastrips_make_metas(ListBase *strips, bool is_temp) NlaStrip *strip, *stripn; /* sanity checks */ - if (ELEM(NULL, strips, strips->first)) + if (ELEM(NULL, strips, strips->first)) { return; + } /* group all continuous chains of selected strips into meta-strips */ for (strip = strips->first; strip; strip = stripn) { @@ -722,8 +760,9 @@ void BKE_nlastrips_make_metas(ListBase *strips, bool is_temp) mstrip->flag = NLASTRIP_FLAG_SELECT; /* set temp flag if appropriate (i.e. for transform-type editing) */ - if (is_temp) + if (is_temp) { mstrip->flag |= NLASTRIP_FLAG_TEMP_META; + } /* set default repeat/scale values to prevent warnings */ mstrip->repeat = mstrip->scale = 1.0f; @@ -754,8 +793,9 @@ void BKE_nlastrips_clear_metastrip(ListBase *strips, NlaStrip *strip) NlaStrip *cs, *csn; /* sanity check */ - if (ELEM(NULL, strips, strip)) + if (ELEM(NULL, strips, strip)) { return; + } /* move each one of the meta-strip's children before the meta-strip * in the list of strips after unlinking them from the meta-strip @@ -779,8 +819,9 @@ void BKE_nlastrips_clear_metas(ListBase *strips, bool only_sel, bool only_temp) NlaStrip *strip, *stripn; /* sanity checks */ - if (ELEM(NULL, strips, strips->first)) + if (ELEM(NULL, strips, strips->first)) { return; + } /* remove meta-strips fitting the criteria of the arguments */ for (strip = strips->first; strip; strip = stripn) { @@ -804,12 +845,14 @@ void BKE_nlastrips_clear_metas(ListBase *strips, bool only_sel, bool only_temp) bool BKE_nlameta_add_strip(NlaStrip *mstrip, NlaStrip *strip) { /* sanity checks */ - if (ELEM(NULL, mstrip, strip)) + if (ELEM(NULL, mstrip, strip)) { return false; + } /* firstly, check if the meta-strip has space for this */ - if (BKE_nlastrips_has_space(&mstrip->strips, strip->start, strip->end) == 0) + if (BKE_nlastrips_has_space(&mstrip->strips, strip->start, strip->end) == 0) { return false; + } /* check if this would need to be added to the ends of the meta, * and subsequently, if the neighboring strips allow us enough room @@ -825,8 +868,9 @@ bool BKE_nlameta_add_strip(NlaStrip *mstrip, NlaStrip *strip) return true; } - else /* failed... no room before */ + else { /* failed... no room before */ return false; + } } else if (strip->end > mstrip->end) { /* check if strip to the right (if it exists) starts before the @@ -839,8 +883,9 @@ bool BKE_nlameta_add_strip(NlaStrip *mstrip, NlaStrip *strip) return true; } - else /* failed... no room after */ + else { /* failed... no room after */ return false; + } } else { /* just try to add to the meta-strip (no dimension changes needed) */ @@ -862,10 +907,12 @@ void BKE_nlameta_flush_transforms(NlaStrip *mstrip) * - strip must exist * - strip must be a meta-strip with some contents */ - if (ELEM(NULL, mstrip, mstrip->strips.first)) + if (ELEM(NULL, mstrip, mstrip->strips.first)) { return; - if (mstrip->type != NLASTRIP_TYPE_META) + } + if (mstrip->type != NLASTRIP_TYPE_META) { return; + } /* get the original start/end points, and calculate the start-frame offset * - these are simply the start/end frames of the child strips, @@ -879,14 +926,16 @@ void BKE_nlameta_flush_transforms(NlaStrip *mstrip) * don't flush if nothing changed yet * TODO: maybe we need a flag to say always flush? */ - if (IS_EQF(oStart, mstrip->start) && IS_EQF(oEnd, mstrip->end)) + if (IS_EQF(oStart, mstrip->start) && IS_EQF(oEnd, mstrip->end)) { return; + } /* check if scale changed */ oLen = oEnd - oStart; nLen = mstrip->end - mstrip->start; - if (IS_EQF(nLen, oLen) == 0) + if (IS_EQF(nLen, oLen) == 0) { scaleChanged = 1; + } /* for each child-strip, calculate new start/end points based on this new info */ for (strip = mstrip->strips.first; strip; strip = strip->next) { @@ -897,7 +946,8 @@ void BKE_nlameta_flush_transforms(NlaStrip *mstrip) p1 = (strip->start - oStart) / oLen; p2 = (strip->end - oStart) / oLen; - /* apply new strip endpoints using the proportions, then wait for second pass to flush scale properly */ + /* Apply new strip endpoints using the proportions, + * then wait for second pass to flush scale properly. */ strip->start = (p1 * nLen) + mstrip->start; strip->end = (p2 * nLen) + mstrip->start; } @@ -934,13 +984,15 @@ NlaTrack *BKE_nlatrack_find_active(ListBase *tracks) NlaTrack *nlt; /* sanity check */ - if (ELEM(NULL, tracks, tracks->first)) + if (ELEM(NULL, tracks, tracks->first)) { return NULL; + } /* try to find the first active track */ for (nlt = tracks->first; nlt; nlt = nlt->next) { - if (nlt->flag & NLATRACK_ACTIVE) + if (nlt->flag & NLATRACK_ACTIVE) { return nlt; + } } /* none found */ @@ -957,8 +1009,9 @@ NlaTrack *BKE_nlatrack_find_tweaked(AnimData *adt) NlaTrack *nlt; /* sanity check */ - if (adt == NULL) + if (adt == NULL) { return NULL; + } /* Since the track itself gets disabled, we want the first disabled... */ for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) { @@ -990,13 +1043,15 @@ void BKE_nlatrack_solo_toggle(AnimData *adt, NlaTrack *nlt) NlaTrack *nt; /* sanity check */ - if (ELEM(NULL, adt, adt->nla_tracks.first)) + if (ELEM(NULL, adt, adt->nla_tracks.first)) { return; + } /* firstly, make sure 'solo' flag for all tracks is disabled */ for (nt = adt->nla_tracks.first; nt; nt = nt->next) { - if (nt != nlt) + if (nt != nlt) { nt->flag &= ~NLATRACK_SOLO; + } } /* now, enable 'solo' for the given track if appropriate */ @@ -1005,13 +1060,16 @@ void BKE_nlatrack_solo_toggle(AnimData *adt, NlaTrack *nlt) nlt->flag ^= NLATRACK_SOLO; /* set or clear solo-status on AnimData */ - if (nlt->flag & NLATRACK_SOLO) + if (nlt->flag & NLATRACK_SOLO) { adt->flag |= ADT_NLA_SOLO_TRACK; - else + } + else { adt->flag &= ~ADT_NLA_SOLO_TRACK; + } } - else + else { adt->flag &= ~ADT_NLA_SOLO_TRACK; + } } /* Make the given NLA-track the active one for the given stack. If no track is provided, @@ -1022,16 +1080,19 @@ void BKE_nlatrack_set_active(ListBase *tracks, NlaTrack *nlt_a) NlaTrack *nlt; /* sanity check */ - if (ELEM(NULL, tracks, tracks->first)) + if (ELEM(NULL, tracks, tracks->first)) { return; + } /* deactivate all the rest */ - for (nlt = tracks->first; nlt; nlt = nlt->next) + for (nlt = tracks->first; nlt; nlt = nlt->next) { nlt->flag &= ~NLATRACK_ACTIVE; + } /* set the given one as the active one */ - if (nlt_a) + if (nlt_a) { nlt_a->flag |= NLATRACK_ACTIVE; + } } /* Check if there is any space in the given track to add a strip of the given length */ @@ -1042,8 +1103,9 @@ bool BKE_nlatrack_has_space(NlaTrack *nlt, float start, float end) * - track must be editable * - bounds cannot be equal (0-length is nasty) */ - if ((nlt == NULL) || (nlt->flag & NLATRACK_PROTECTED) || IS_EQF(start, end)) + if ((nlt == NULL) || (nlt->flag & NLATRACK_PROTECTED) || IS_EQF(start, end)) { return false; + } if (start > end) { puts("BKE_nlatrack_has_space() error... start and end arguments swapped"); @@ -1060,8 +1122,9 @@ bool BKE_nlatrack_has_space(NlaTrack *nlt, float start, float end) void BKE_nlatrack_sort_strips(NlaTrack *nlt) { /* sanity checks */ - if (ELEM(NULL, nlt, nlt->strips.first)) + if (ELEM(NULL, nlt, nlt->strips.first)) { return; + } /* sort the strips with a more generic function */ BKE_nlastrips_sort_strips(&nlt->strips); @@ -1073,12 +1136,14 @@ void BKE_nlatrack_sort_strips(NlaTrack *nlt) bool BKE_nlatrack_add_strip(NlaTrack *nlt, NlaStrip *strip) { /* sanity checks */ - if (ELEM(NULL, nlt, strip)) + if (ELEM(NULL, nlt, strip)) { return false; + } /* do not allow adding strips if this track is locked */ - if (nlt->flag & NLATRACK_PROTECTED) + if (nlt->flag & NLATRACK_PROTECTED) { return false; + } /* try to add the strip to the track using a more generic function */ return BKE_nlastrips_add_strip(&nlt->strips, strip); @@ -1092,14 +1157,17 @@ bool BKE_nlatrack_get_bounds(NlaTrack *nlt, float bounds[2]) NlaStrip *strip; /* initialize bounds */ - if (bounds) + if (bounds) { bounds[0] = bounds[1] = 0.0f; - else + } + else { return false; + } /* sanity checks */ - if (ELEM(NULL, nlt, nlt->strips.first)) + if (ELEM(NULL, nlt, nlt->strips.first)) { return false; + } /* lower bound is first strip's start frame */ strip = nlt->strips.first; @@ -1121,13 +1189,15 @@ NlaStrip *BKE_nlastrip_find_active(NlaTrack *nlt) NlaStrip *strip; /* sanity check */ - if (ELEM(NULL, nlt, nlt->strips.first)) + if (ELEM(NULL, nlt, nlt->strips.first)) { return NULL; + } /* try to find the first active strip */ for (strip = nlt->strips.first; strip; strip = strip->next) { - if (strip->flag & NLASTRIP_FLAG_ACTIVE) + if (strip->flag & NLASTRIP_FLAG_ACTIVE) { return strip; + } } /* none found */ @@ -1141,16 +1211,19 @@ void BKE_nlastrip_set_active(AnimData *adt, NlaStrip *strip) NlaStrip *nls; /* sanity checks */ - if (adt == NULL) + if (adt == NULL) { return; + } /* loop over tracks, deactivating*/ for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) { for (nls = nlt->strips.first; nls; nls = nls->next) { - if (nls != strip) + if (nls != strip) { nls->flag &= ~NLASTRIP_FLAG_ACTIVE; - else + } + else { nls->flag |= NLASTRIP_FLAG_ACTIVE; + } } } } @@ -1162,8 +1235,9 @@ bool BKE_nlastrip_within_bounds(NlaStrip *strip, float min, float max) const float boundsLen = fabsf(max - min); /* sanity checks */ - if ((strip == NULL) || IS_EQF(stripLen, 0.0f) || IS_EQF(boundsLen, 0.0f)) + if ((strip == NULL) || IS_EQF(stripLen, 0.0f) || IS_EQF(boundsLen, 0.0f)) { return false; + } /* only ok if at least part of the strip is within the bounding window * - first 2 cases cover when the strip length is less than the bounding area @@ -1182,7 +1256,8 @@ bool BKE_nlastrip_within_bounds(NlaStrip *strip, float min, float max) return true; } -/* Ensure that strip doesn't overlap those around it after resizing by offsetting those which follow */ +/* Ensure that strip doesn't overlap those around it after resizing + * by offsetting those which follow. */ static void nlastrip_fix_resize_overlaps(NlaStrip *strip) { /* next strips - do this first, since we're often just getting longer */ @@ -1294,19 +1369,22 @@ void BKE_nlastrip_recalculate_bounds(NlaStrip *strip) * - must have a strip * - can only be done for action clips */ - if ((strip == NULL) || (strip->type != NLASTRIP_TYPE_CLIP)) + if ((strip == NULL) || (strip->type != NLASTRIP_TYPE_CLIP)) { return; + } /* calculate new length factors */ actlen = strip->actend - strip->actstart; - if (IS_EQF(actlen, 0.0f)) + if (IS_EQF(actlen, 0.0f)) { actlen = 1.0f; + } mapping = strip->scale * strip->repeat; /* adjust endpoint of strip in response to this */ - if (IS_EQF(mapping, 0.0f) == 0) + if (IS_EQF(mapping, 0.0f) == 0) { strip->end = (actlen * mapping) + strip->start; + } /* make sure we don't overlap our neighbors */ nlastrip_fix_resize_overlaps(strip); @@ -1320,12 +1398,14 @@ static bool nlastrip_is_first(AnimData *adt, NlaStrip *strip) NlaStrip *ns; /* sanity checks */ - if (ELEM(NULL, adt, strip)) + if (ELEM(NULL, adt, strip)) { return false; + } /* check if strip has any strips before it */ - if (strip->prev) + if (strip->prev) { return false; + } /* check other tracks to see if they have a strip that's earlier */ /* TODO: or should we check that the strip's track is also the first? */ @@ -1333,8 +1413,9 @@ static bool nlastrip_is_first(AnimData *adt, NlaStrip *strip) /* only check the first strip, assuming that they're all in order */ ns = nlt->strips.first; if (ns) { - if (ns->start < strip->start) + if (ns->start < strip->start) { return false; + } } } @@ -1350,13 +1431,15 @@ bool BKE_nlatrack_has_animated_strips(NlaTrack *nlt) NlaStrip *strip; /* sanity checks */ - if (ELEM(NULL, nlt, nlt->strips.first)) + if (ELEM(NULL, nlt, nlt->strips.first)) { return false; + } /* check each strip for F-Curves only (don't care about whether the flags are set) */ for (strip = nlt->strips.first; strip; strip = strip->next) { - if (strip->fcurves.first) + if (strip->fcurves.first) { return true; + } } /* none found */ @@ -1369,13 +1452,15 @@ bool BKE_nlatracks_have_animated_strips(ListBase *tracks) NlaTrack *nlt; /* sanity checks */ - if (ELEM(NULL, tracks, tracks->first)) + if (ELEM(NULL, tracks, tracks->first)) { return false; + } /* check each track, stopping on the first hit */ for (nlt = tracks->first; nlt; nlt = nlt->next) { - if (BKE_nlatrack_has_animated_strips(nlt)) + if (BKE_nlatrack_has_animated_strips(nlt)) { return true; + } } /* none found */ @@ -1388,8 +1473,9 @@ void BKE_nlastrip_validate_fcurves(NlaStrip *strip) FCurve *fcu; /* sanity checks */ - if (strip == NULL) + if (strip == NULL) { return; + } /* if controlling influence... */ if (strip->flag & NLASTRIP_FLAG_USR_INFLUENCE) { @@ -1447,8 +1533,9 @@ void BKE_nlastrip_validate_fcurves(NlaStrip *strip) bool BKE_nlastrip_has_curves_for_property(const PointerRNA *ptr, const PropertyRNA *prop) { /* sanity checks */ - if (ELEM(NULL, ptr, prop)) + if (ELEM(NULL, ptr, prop)) { return false; + } /* 1) Must be NLA strip */ if (ptr->type == &RNA_NlaStrip) { @@ -1494,8 +1581,9 @@ void BKE_nlastrip_validate_name(AnimData *adt, NlaStrip *strip) NlaTrack *nlt; /* sanity checks */ - if (ELEM(NULL, adt, strip)) + if (ELEM(NULL, adt, strip)) { return; + } /* give strip a default name if none already */ if (strip->name[0] == 0) { @@ -1526,16 +1614,19 @@ void BKE_nlastrip_validate_name(AnimData *adt, NlaStrip *strip) for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) { for (tstrip = nlt->strips.first; tstrip; tstrip = tstrip->next) { /* don't add the strip of interest */ - if (tstrip == strip) + if (tstrip == strip) { continue; + } - /* use the name of the strip as the key, and the strip as the value, since we're mostly interested in the keys */ + /* Use the name of the strip as the key, and the strip as the value, + * since we're mostly interested in the keys. */ BLI_ghash_insert(gh, tstrip->name, tstrip); } } - /* if the hash-table has a match for this name, try other names... - * - in an extreme case, it might not be able to find a name, but then everything else in Blender would fail too :) + /* If the hash-table has a match for this name, try other names... + * - In an extreme case, it might not be able to find a name, + * but then everything else in Blender would fail too :). */ BLI_uniquename_cb(nla_editbone_name_check, (void *)gh, @@ -1567,7 +1658,8 @@ static void nlastrip_get_endpoint_overlaps(NlaStrip *strip, */ /* TODO: this scheme could get quite slow for doing this on many strips... */ for (nls = track->strips.first; nls; nls = nls->next) { - /* check if strip overlaps (extends over or exactly on) the entire range of the strip we're validating */ + /* Check if strip overlaps (extends over or exactly on) + * the entire range of the strip we're validating. */ if ((nls->start <= strip->start) && (nls->end >= strip->end)) { *start = NULL; *end = NULL; @@ -1575,21 +1667,25 @@ static void nlastrip_get_endpoint_overlaps(NlaStrip *strip, } /* check if strip doesn't even occur anywhere near... */ - if (nls->end < strip->start) + if (nls->end < strip->start) { continue; /* skip checking this strip... not worthy of mention */ - if (nls->start > strip->end) + } + if (nls->start > strip->end) { return; /* the range we're after has already passed */ + } /* if this strip is not part of an island of continuous strips, it can be used * - this check needs to be done for each end of the strip we try and use... */ if ((nls->next == NULL) || IS_EQF(nls->next->start, nls->end) == 0) { - if ((nls->end > strip->start) && (nls->end < strip->end)) + if ((nls->end > strip->start) && (nls->end < strip->end)) { *start = &nls->end; + } } if ((nls->prev == NULL) || IS_EQF(nls->prev->end, nls->start) == 0) { - if ((nls->start < strip->end) && (nls->start > strip->start)) + if ((nls->start < strip->end) && (nls->start > strip->start)) { *end = &nls->start; + } } } } @@ -1601,18 +1697,23 @@ static void BKE_nlastrip_validate_autoblends(NlaTrack *nlt, NlaStrip *nls) float *ns = NULL, *ne = NULL; /* sanity checks */ - if (ELEM(NULL, nls, nlt)) + if (ELEM(NULL, nls, nlt)) { return; - if ((nlt->prev == NULL) && (nlt->next == NULL)) + } + if ((nlt->prev == NULL) && (nlt->next == NULL)) { return; - if ((nls->flag & NLASTRIP_FLAG_AUTO_BLENDS) == 0) + } + if ((nls->flag & NLASTRIP_FLAG_AUTO_BLENDS) == 0) { return; + } /* get test ranges */ - if (nlt->prev) + if (nlt->prev) { nlastrip_get_endpoint_overlaps(nls, nlt->prev, &ps, &pe); - if (nlt->next) + } + if (nlt->next) { nlastrip_get_endpoint_overlaps(nls, nlt->next, &ns, &ne); + } /* set overlaps for this strip * - don't use the values obtained though if the end in question @@ -1621,23 +1722,29 @@ static void BKE_nlastrip_validate_autoblends(NlaTrack *nlt, NlaStrip *nls) */ if ((ps || ns) && ((nls->prev == NULL) || IS_EQF(nls->prev->end, nls->start) == 0)) { /* start overlaps - pick the largest overlap */ - if (((ps && ns) && (*ps > *ns)) || (ps)) + if (((ps && ns) && (*ps > *ns)) || (ps)) { nls->blendin = *ps - nls->start; - else + } + else { nls->blendin = *ns - nls->start; + } } - else /* no overlap allowed/needed */ + else { /* no overlap allowed/needed */ nls->blendin = 0.0f; + } if ((pe || ne) && ((nls->next == NULL) || IS_EQF(nls->next->start, nls->end) == 0)) { /* end overlaps - pick the largest overlap */ - if (((pe && ne) && (*pe > *ne)) || (pe)) + if (((pe && ne) && (*pe > *ne)) || (pe)) { nls->blendout = nls->end - *pe; - else + } + else { nls->blendout = nls->end - *ne; + } } - else /* no overlap allowed/needed */ + else { /* no overlap allowed/needed */ nls->blendout = 0.0f; + } } /* Ensure that auto-blending and other settings are set correctly */ @@ -1647,18 +1754,21 @@ void BKE_nla_validate_state(AnimData *adt) NlaTrack *nlt; /* sanity checks */ - if (ELEM(NULL, adt, adt->nla_tracks.first)) + if (ELEM(NULL, adt, adt->nla_tracks.first)) { return; + } - /* adjust blending values for auto-blending, and also do an initial pass to find the earliest strip */ + /* Adjust blending values for auto-blending, + * and also do an initial pass to find the earliest strip. */ for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) { for (strip = nlt->strips.first; strip; strip = strip->next) { /* auto-blending first */ BKE_nlastrip_validate_autoblends(nlt, strip); /* extend mode - find first strip */ - if ((fstrip == NULL) || (strip->start < fstrip->start)) + if ((fstrip == NULL) || (strip->start < fstrip->start)) { fstrip = strip; + } } } @@ -1678,10 +1788,12 @@ void BKE_nla_validate_state(AnimData *adt) * * Should fix problems such as [#29869] */ - if (strip == fstrip) + if (strip == fstrip) { strip->extendmode = NLASTRIP_EXTEND_HOLD; - else if (strip->blendmode == NLASTRIP_MODE_REPLACE) + } + else if (strip->blendmode == NLASTRIP_MODE_REPLACE) { strip->extendmode = NLASTRIP_EXTEND_HOLD_FORWARD; + } } } } @@ -1706,8 +1818,9 @@ bool BKE_nla_action_is_stashed(AnimData *adt, bAction *act) for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) { if (strstr(nlt->name, STASH_TRACK_NAME)) { for (strip = nlt->strips.first; strip; strip = strip->next) { - if (strip->act == act) + if (strip->act == act) { return true; + } } } } @@ -1731,8 +1844,9 @@ bool BKE_nla_action_stash(AnimData *adt) } /* do not add if it is already stashed */ - if (BKE_nla_action_is_stashed(adt, adt->action)) + if (BKE_nla_action_is_stashed(adt, adt->action)) { return false; + } /* create a new track, and add this immediately above the previous stashing track */ for (prev_track = adt->nla_tracks.last; prev_track; prev_track = prev_track->prev) { @@ -1744,7 +1858,8 @@ bool BKE_nla_action_stash(AnimData *adt) nlt = BKE_nlatrack_add(adt, prev_track); BLI_assert(nlt != NULL); - /* we need to ensure that if there wasn't any previous instance, it must go to tbe bottom of the stack */ + /* We need to ensure that if there wasn't any previous instance, + * it must go to tbe bottom of the stack. */ if (prev_track == NULL) { BLI_remlink(&adt->nla_tracks, nlt); BLI_addhead(&adt->nla_tracks, nlt); @@ -1797,8 +1912,9 @@ void BKE_nla_action_pushdown(AnimData *adt) /* sanity checks */ /* TODO: need to report the error for this */ - if (ELEM(NULL, adt, adt->action)) + if (ELEM(NULL, adt, adt->action)) { return; + } /* if the action is empty, we also shouldn't try to add to stack, * as that will cause us grief down the track @@ -1849,12 +1965,13 @@ void BKE_nla_action_pushdown(AnimData *adt) * mode accordingly */ if (nlastrip_is_first(adt, strip) == 0) { - /* not first, so extend mode can only be NLASTRIP_EXTEND_HOLD_FORWARD not NLASTRIP_EXTEND_HOLD, - * so that it doesn't override strips in previous tracks - */ + /* Not first, so extend mode can only be: + * NLASTRIP_EXTEND_HOLD_FORWARD not NLASTRIP_EXTEND_HOLD, + * so that it doesn't override strips in previous tracks. */ /* FIXME: this needs to be more automated, since user can rearrange strips */ - if (strip->extendmode == NLASTRIP_EXTEND_HOLD) + if (strip->extendmode == NLASTRIP_EXTEND_HOLD) { strip->extendmode = NLASTRIP_EXTEND_HOLD_FORWARD; + } } /* make strip the active one... */ @@ -1871,14 +1988,16 @@ bool BKE_nla_tweakmode_enter(AnimData *adt) NlaStrip *strip, *activeStrip = NULL; /* verify that data is valid */ - if (ELEM(NULL, adt, adt->nla_tracks.first)) + if (ELEM(NULL, adt, adt->nla_tracks.first)) { return false; + } /* if block is already in tweakmode, just leave, but we should report * that this block is in tweakmode (as our returncode) */ - if (adt->flag & ADT_NLA_EDIT_ON) + if (adt->flag & ADT_NLA_EDIT_ON) { return true; + } /* go over the tracks, finding the active one, and its active strip * - if we cannot find both, then there's nothing to do @@ -1895,9 +2014,10 @@ bool BKE_nla_tweakmode_enter(AnimData *adt) } } - /* There are situations where we may have multiple strips selected and we want to enter tweakmode on all - * of those at once. Usually in those cases, it will usually just be a single strip per AnimData. - * In such cases, compromise and take the last selected track and/or last selected strip [#28468] + /* There are situations where we may have multiple strips selected and we want to enter tweakmode + * on all of those at once. Usually in those cases, + * it will usually just be a single strip per AnimData. + * In such cases, compromise and take the last selected track and/or last selected strip, T28468. */ if (activeTrack == NULL) { /* try last selected track for active strip */ @@ -1913,7 +2033,8 @@ bool BKE_nla_tweakmode_enter(AnimData *adt) } } if ((activeTrack) && (activeStrip == NULL)) { - /* no active strip in active or last selected track; compromise for first selected (assuming only single)... */ + /* No active strip in active or last selected track; + * compromise for first selected (assuming only single). */ for (strip = activeTrack->strips.first; strip; strip = strip->next) { if (strip->flag & (NLASTRIP_FLAG_SELECT | NLASTRIP_FLAG_ACTIVE)) { activeStrip = strip; @@ -1935,32 +2056,39 @@ bool BKE_nla_tweakmode_enter(AnimData *adt) */ for (nlt = activeTrack->prev; nlt; nlt = nlt->prev) { for (strip = nlt->strips.first; strip; strip = strip->next) { - if (strip->act == activeStrip->act) + if (strip->act == activeStrip->act) { strip->flag |= NLASTRIP_FLAG_TWEAKUSER; - else + } + else { strip->flag &= ~NLASTRIP_FLAG_TWEAKUSER; + } } } /* tag all other strips in active track that uses the same action as the active strip */ for (strip = activeTrack->strips.first; strip; strip = strip->next) { - if ((strip->act == activeStrip->act) && (strip != activeStrip)) + if ((strip->act == activeStrip->act) && (strip != activeStrip)) { strip->flag |= NLASTRIP_FLAG_TWEAKUSER; - else + } + else { strip->flag &= ~NLASTRIP_FLAG_TWEAKUSER; + } } /* go over all the tracks after AND INCLUDING the active one, tagging them as being disabled * - the active track needs to also be tagged, otherwise, it'll overlap with the tweaks going on */ - for (nlt = activeTrack; nlt; nlt = nlt->next) + for (nlt = activeTrack; nlt; nlt = nlt->next) { nlt->flag |= NLATRACK_DISABLED; + } /* handle AnimData level changes: - * - 'real' active action to temp storage (no need to change user-counts) - * - action of active strip set to be the 'active action', and have its usercount incremented - * - editing-flag for this AnimData block should also get turned on (for more efficient restoring) - * - take note of the active strip for mapping-correction of keyframes in the action being edited + * - 'real' active action to temp storage (no need to change user-counts). + * - Action of active strip set to be the 'active action', and have its usercount incremented. + * - Editing-flag for this AnimData block should also get turned on + * (for more efficient restoring). + * - Take note of the active strip for mapping-correction of keyframes + * in the action being edited. */ adt->tmpact = adt->action; adt->action = activeStrip->act; @@ -1980,12 +2108,14 @@ void BKE_nla_tweakmode_exit(AnimData *adt) NlaTrack *nlt; /* verify that data is valid */ - if (ELEM(NULL, adt, adt->nla_tracks.first)) + if (ELEM(NULL, adt, adt->nla_tracks.first)) { return; + } /* hopefully the flag is correct - skip if not on */ - if ((adt->flag & ADT_NLA_EDIT_ON) == 0) + if ((adt->flag & ADT_NLA_EDIT_ON) == 0) { return; + } /* sync the length of the user-strip with the new state of the action * but only if the user has explicitly asked for this to happen @@ -2033,8 +2163,9 @@ void BKE_nla_tweakmode_exit(AnimData *adt) * - editing-flag for this AnimData block should also get turned off * - clear pointer to active strip */ - if (adt->action) + if (adt->action) { id_us_min(&adt->action->id); + } adt->action = adt->tmpact; adt->tmpact = NULL; adt->act_track = NULL; diff --git a/source/blender/blenkernel/intern/node.c b/source/blender/blenkernel/intern/node.c index ee6faeaee3d..3adb6cfe960 100644 --- a/source/blender/blenkernel/intern/node.c +++ b/source/blender/blenkernel/intern/node.c @@ -109,12 +109,14 @@ static void node_add_sockets_from_type(bNodeTree *ntree, bNode *node, bNodeType static void node_init(const struct bContext *C, bNodeTree *ntree, bNode *node) { bNodeType *ntype = node->typeinfo; - if (ntype == &NodeTypeUndefined) + if (ntype == &NodeTypeUndefined) { return; + } /* only do this once */ - if (node->flag & NODE_INIT) + if (node->flag & NODE_INIT) { return; + } node->flag = NODE_SELECT | NODE_OPTIONS | ntype->flag; node->width = ntype->width; @@ -124,8 +126,9 @@ static void node_init(const struct bContext *C, bNodeTree *ntree, bNode *node) /* initialize the node name with the node label. * note: do this after the initfunc so nodes get their data set which may be used in naming * (node groups for example) */ - /* XXX Do not use nodeLabel() here, it returns translated content for UI, which should *only* be used - * in UI, *never* in data... Data have their own translation option! + /* XXX Do not use nodeLabel() here, it returns translated content for UI, + * which should *only* be used in UI, *never* in data... + * Data have their own translation option! * This solution may be a bit rougher than nodeLabel()'s returned string, but it's simpler * than adding "do_translate" flags to this func (and labelfunc() as well). */ BLI_strncpy(node->name, DATA_(ntype->ui_name), NODE_MAXSTR); @@ -133,14 +136,17 @@ static void node_init(const struct bContext *C, bNodeTree *ntree, bNode *node) node_add_sockets_from_type(ntree, node, ntype); - if (ntype->initfunc != NULL) + if (ntype->initfunc != NULL) { ntype->initfunc(ntree, node); + } - if (ntree->typeinfo->node_add_init != NULL) + if (ntree->typeinfo->node_add_init != NULL) { ntree->typeinfo->node_add_init(ntree, node); + } - if (node->id) + if (node->id) { id_us_plus(node->id); + } /* extra init callback */ if (ntype->initfunc_api) { @@ -179,8 +185,9 @@ static void node_set_typeinfo(const struct bContext *C, { /* for nodes saved in older versions storage can get lost, make undefined then */ if (node->flag & NODE_INIT) { - if (typeinfo && typeinfo->storagename[0] && !node->storage) + if (typeinfo && typeinfo->storagename[0] && !node->storage) { typeinfo = NULL; + } } if (typeinfo) { @@ -229,8 +236,9 @@ static void update_typeinfo(Main *bmain, bNodeSocketType *socktype, bool unregister) { - if (!bmain) + if (!bmain) { return; + } FOREACH_NODETREE_BEGIN (bmain, ntree, id) { bNode *node; @@ -238,36 +246,47 @@ static void update_typeinfo(Main *bmain, ntree->init |= NTREE_TYPE_INIT; - if (treetype && STREQ(ntree->idname, treetype->idname)) + if (treetype && STREQ(ntree->idname, treetype->idname)) { ntree_set_typeinfo(ntree, unregister ? NULL : treetype); + } /* initialize nodes */ for (node = ntree->nodes.first; node; node = node->next) { - if (nodetype && STREQ(node->idname, nodetype->idname)) + if (nodetype && STREQ(node->idname, nodetype->idname)) { node_set_typeinfo(C, ntree, node, unregister ? NULL : nodetype); + } /* initialize node sockets */ - for (sock = node->inputs.first; sock; sock = sock->next) - if (socktype && STREQ(sock->idname, socktype->idname)) + for (sock = node->inputs.first; sock; sock = sock->next) { + if (socktype && STREQ(sock->idname, socktype->idname)) { node_socket_set_typeinfo(ntree, sock, unregister ? NULL : socktype); - for (sock = node->outputs.first; sock; sock = sock->next) - if (socktype && STREQ(sock->idname, socktype->idname)) + } + } + for (sock = node->outputs.first; sock; sock = sock->next) { + if (socktype && STREQ(sock->idname, socktype->idname)) { node_socket_set_typeinfo(ntree, sock, unregister ? NULL : socktype); + } + } } /* initialize tree sockets */ - for (sock = ntree->inputs.first; sock; sock = sock->next) - if (socktype && STREQ(sock->idname, socktype->idname)) + for (sock = ntree->inputs.first; sock; sock = sock->next) { + if (socktype && STREQ(sock->idname, socktype->idname)) { node_socket_set_typeinfo(ntree, sock, unregister ? NULL : socktype); - for (sock = ntree->outputs.first; sock; sock = sock->next) - if (socktype && STREQ(sock->idname, socktype->idname)) + } + } + for (sock = ntree->outputs.first; sock; sock = sock->next) { + if (socktype && STREQ(sock->idname, socktype->idname)) { node_socket_set_typeinfo(ntree, sock, unregister ? NULL : socktype); + } + } } FOREACH_NODETREE_END; } /* Try to initialize all typeinfo in a node tree. - * NB: In general undefined typeinfo is a perfectly valid case, the type may just be registered later. + * NB: In general undefined typeinfo is a perfectly valid case, + * the type may just be registered later. * In that case the update_typeinfo function will set typeinfo on registration * and do necessary updates. */ @@ -283,16 +302,20 @@ void ntreeSetTypes(const struct bContext *C, bNodeTree *ntree) for (node = ntree->nodes.first; node; node = node->next) { node_set_typeinfo(C, ntree, node, nodeTypeFind(node->idname)); - for (sock = node->inputs.first; sock; sock = sock->next) + for (sock = node->inputs.first; sock; sock = sock->next) { node_socket_set_typeinfo(ntree, sock, nodeSocketTypeFind(sock->idname)); - for (sock = node->outputs.first; sock; sock = sock->next) + } + for (sock = node->outputs.first; sock; sock = sock->next) { node_socket_set_typeinfo(ntree, sock, nodeSocketTypeFind(sock->idname)); + } } - for (sock = ntree->inputs.first; sock; sock = sock->next) + for (sock = ntree->inputs.first; sock; sock = sock->next) { node_socket_set_typeinfo(ntree, sock, nodeSocketTypeFind(sock->idname)); - for (sock = ntree->outputs.first; sock; sock = sock->next) + } + for (sock = ntree->outputs.first; sock; sock = sock->next) { node_socket_set_typeinfo(ntree, sock, nodeSocketTypeFind(sock->idname)); + } } static GHash *nodetreetypes_hash = NULL; @@ -306,8 +329,9 @@ bNodeTreeType *ntreeTypeFind(const char *idname) if (idname[0]) { nt = BLI_ghash_lookup(nodetreetypes_hash, idname); - if (nt) + if (nt) { return nt; + } } return NULL; @@ -317,8 +341,8 @@ void ntreeTypeAdd(bNodeTreeType *nt) { BLI_ghash_insert(nodetreetypes_hash, nt->idname, nt); /* XXX pass Main to register function? */ - /* Probably not. It is pretty much expected we want to update G_MAIN her I think - or we'd want to update *all* - * active Mains, which we cannot do anyway currently. */ + /* Probably not. It is pretty much expected we want to update G_MAIN here I think - + * or we'd want to update *all* active Mains, which we cannot do anyway currently. */ update_typeinfo(G_MAIN, NULL, nt, NULL, NULL, false); } @@ -327,8 +351,8 @@ static void ntree_free_type(void *treetype_v) { bNodeTreeType *treetype = treetype_v; /* XXX pass Main to unregister function? */ - /* Probably not. It is pretty much expected we want to update G_MAIN her I think - or we'd want to update *all* - * active Mains, which we cannot do anyway currently. */ + /* Probably not. It is pretty much expected we want to update G_MAIN here I think - + * or we'd want to update *all* active Mains, which we cannot do anyway currently. */ update_typeinfo(G_MAIN, NULL, treetype, NULL, NULL, true); MEM_freeN(treetype); } @@ -354,8 +378,9 @@ bNodeType *nodeTypeFind(const char *idname) if (idname[0]) { nt = BLI_ghash_lookup(nodetypes_hash, idname); - if (nt) + if (nt) { return nt; + } } return NULL; @@ -378,16 +403,18 @@ static void node_free_type(void *nodetype_v) { bNodeType *nodetype = nodetype_v; /* XXX pass Main to unregister function? */ - /* Probably not. It is pretty much expected we want to update G_MAIN her I think - or we'd want to update *all* - * active Mains, which we cannot do anyway currently. */ + /* Probably not. It is pretty much expected we want to update G_MAIN here I think - + * or we'd want to update *all* active Mains, which we cannot do anyway currently. */ update_typeinfo(G_MAIN, NULL, NULL, nodetype, NULL, true); /* XXX deprecated */ - if (nodetype->type == NODE_DYNAMIC) + if (nodetype->type == NODE_DYNAMIC) { free_dynamic_typeinfo(nodetype); + } - if (nodetype->needs_free) + if (nodetype->needs_free) { MEM_freeN(nodetype); + } } void nodeRegisterType(bNodeType *nt) @@ -398,8 +425,8 @@ void nodeRegisterType(bNodeType *nt) BLI_ghash_insert(nodetypes_hash, nt->idname, nt); /* XXX pass Main to register function? */ - /* Probably not. It is pretty much expected we want to update G_MAIN her I think - or we'd want to update *all* - * active Mains, which we cannot do anyway currently. */ + /* Probably not. It is pretty much expected we want to update G_MAIN here I think - + * or we'd want to update *all* active Mains, which we cannot do anyway currently. */ update_typeinfo(G_MAIN, NULL, NULL, nt, NULL, false); } @@ -424,8 +451,9 @@ bNodeSocketType *nodeSocketTypeFind(const char *idname) if (idname[0]) { st = BLI_ghash_lookup(nodesockettypes_hash, idname); - if (st) + if (st) { return st; + } } return NULL; @@ -436,8 +464,8 @@ static void node_free_socket_type(void *socktype_v) { bNodeSocketType *socktype = socktype_v; /* XXX pass Main to unregister function? */ - /* Probably not. It is pretty much expected we want to update G_MAIN her I think - or we'd want to update *all* - * active Mains, which we cannot do anyway currently. */ + /* Probably not. It is pretty much expected we want to update G_MAIN here I think - + * or we'd want to update *all* active Mains, which we cannot do anyway currently. */ update_typeinfo(G_MAIN, NULL, NULL, NULL, socktype, true); MEM_freeN(socktype); @@ -447,8 +475,8 @@ void nodeRegisterSocketType(bNodeSocketType *st) { BLI_ghash_insert(nodesockettypes_hash, (void *)st->idname, st); /* XXX pass Main to register function? */ - /* Probably not. It is pretty much expected we want to update G_MAIN her I think - or we'd want to update *all* - * active Mains, which we cannot do anyway currently. */ + /* Probably not. It is pretty much expected we want to update G_MAIN here I think - + * or we'd want to update *all* active Mains, which we cannot do anyway currently. */ update_typeinfo(G_MAIN, NULL, NULL, NULL, st, false); } @@ -471,8 +499,9 @@ struct bNodeSocket *nodeFindSocket(bNode *node, int in_out, const char *identifi { bNodeSocket *sock = (in_out == SOCK_IN ? node->inputs.first : node->outputs.first); for (; sock; sock = sock->next) { - if (STREQ(sock->identifier, identifier)) + if (STREQ(sock->identifier, identifier)) { return sock; + } } return NULL; } @@ -483,8 +512,9 @@ static bool unique_identifier_check(void *arg, const char *identifier) struct ListBase *lb = arg; bNodeSocket *sock; for (sock = lb->first; sock; sock = sock->next) { - if (STREQ(sock->identifier, identifier)) + if (STREQ(sock->identifier, identifier)) { return true; + } } return false; } @@ -761,8 +791,9 @@ static void node_socket_free(bNodeTree *UNUSED(ntree), MEM_freeN(sock->prop); } - if (sock->default_value) + if (sock->default_value) { MEM_freeN(sock->default_value); + } } void nodeRemoveSocket(bNodeTree *ntree, bNode *node, bNodeSocket *sock) @@ -832,17 +863,20 @@ int nodeFindNode(bNodeTree *ntree, bNodeSocket *sock, bNode **nodep, int *sockin for (node = ntree->nodes.first; node; node = node->next) { tsock = (in_out == SOCK_IN ? node->inputs.first : node->outputs.first); for (index = 0; tsock; tsock = tsock->next, index++) { - if (tsock == sock) + if (tsock == sock) { break; + } } - if (tsock) + if (tsock) { break; + } } if (node) { *nodep = node; - if (sockindex) + if (sockindex) { *sockindex = index; + } return 1; } @@ -899,7 +933,8 @@ void nodeChainIter(const bNodeTree *ntree, continue; } if (link->tonode && link->fromnode) { - /* is the link part of the chain meaning node_start == fromnode (or tonode for reversed case)? */ + /* Is the link part of the chain meaning node_start == fromnode + * (or tonode for reversed case)? */ if ((reversed && (link->tonode == node_start)) || (!reversed && link->fromnode == node_start)) { if (!callback(link->fromnode, link->tonode, userdata, reversed)) { @@ -913,7 +948,8 @@ void nodeChainIter(const bNodeTree *ntree, } /** - * Iterate over all parents of \a node, executing \a callback for each parent (which can return false to end iterator) + * Iterate over all parents of \a node, executing \a callback for each parent + * (which can return false to end iterator) * * \note Recursive */ @@ -1071,8 +1107,9 @@ bNodeLink *nodeAddLink( if (fromsock->in_out == SOCK_OUT && tosock->in_out == SOCK_IN) { link = MEM_callocN(sizeof(bNodeLink), "link"); - if (ntree) + if (ntree) { BLI_addtail(&ntree->links, link); + } link->fromnode = fromnode; link->fromsock = fromsock; link->tonode = tonode; @@ -1081,16 +1118,18 @@ bNodeLink *nodeAddLink( else if (fromsock->in_out == SOCK_IN && tosock->in_out == SOCK_OUT) { /* OK but flip */ link = MEM_callocN(sizeof(bNodeLink), "link"); - if (ntree) + if (ntree) { BLI_addtail(&ntree->links, link); + } link->fromnode = tonode; link->fromsock = tosock; link->tonode = fromnode; link->tosock = fromsock; } - if (ntree) + if (ntree) { ntree->update |= NTREE_UPDATE_LINKS; + } return link; } @@ -1098,15 +1137,18 @@ bNodeLink *nodeAddLink( void nodeRemLink(bNodeTree *ntree, bNodeLink *link) { /* can be called for links outside a node tree (e.g. clipboard) */ - if (ntree) + if (ntree) { BLI_remlink(&ntree->links, link); + } - if (link->tosock) + if (link->tosock) { link->tosock->link = NULL; + } MEM_freeN(link); - if (ntree) + if (ntree) { ntree->update |= NTREE_UPDATE_LINKS; + } } void nodeRemSocketLinks(bNodeTree *ntree, bNodeSocket *sock) @@ -1133,8 +1175,9 @@ void nodeInternalRelink(bNodeTree *ntree, bNode *node) bNodeLink *link, *link_next; /* store link pointers in output sockets, for efficient lookup */ - for (link = node->internal_links.first; link; link = link->next) + for (link = node->internal_links.first; link; link = link->next) { link->tosock->link = link; + } /* redirect downstream links */ for (link = ntree->links.first; link; link = link_next) { @@ -1153,16 +1196,19 @@ void nodeInternalRelink(bNodeTree *ntree, bNode *node) /* if the up- or downstream link is invalid, * the replacement link will be invalid too. */ - if (!(fromlink->flag & NODE_LINK_VALID)) + if (!(fromlink->flag & NODE_LINK_VALID)) { link->flag &= ~NODE_LINK_VALID; + } ntree->update |= NTREE_UPDATE_LINKS; } - else + else { nodeRemLink(ntree, link); + } } - else + else { nodeRemLink(ntree, link); + } } } @@ -1170,8 +1216,9 @@ void nodeInternalRelink(bNodeTree *ntree, bNode *node) for (link = ntree->links.first; link; link = link_next) { link_next = link->next; - if (link->tonode == node) + if (link->tonode == node) { nodeRemLink(ntree, link); + } } } @@ -1327,8 +1374,10 @@ bNodeTree *ntreeAddTree(Main *bmain, const char *name, const char *idname) } /** - * Only copy internal data of NodeTree ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of NodeTree ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * @@ -1389,8 +1438,7 @@ void BKE_node_tree_copy_data(Main *UNUSED(bmain), ntree_dst->previews = BKE_node_instance_hash_new("node previews"); - NODE_INSTANCE_HASH_ITER(iter, ntree_src->previews) - { + NODE_INSTANCE_HASH_ITER (iter, ntree_src->previews) { bNodeInstanceKey key = BKE_node_instance_hash_iterator_get_key(&iter); bNodePreview *preview = BKE_node_instance_hash_iterator_get_value(&iter); BKE_node_instance_hash_insert(ntree_dst->previews, key, BKE_node_preview_copy(preview)); @@ -1463,13 +1511,15 @@ bNodePreview *BKE_node_preview_verify( preview = MEM_callocN(sizeof(bNodePreview), "node preview"); BKE_node_instance_hash_insert(previews, key, preview); } - else + else { return NULL; + } } /* node previews can get added with variable size this way */ - if (xsize == 0 || ysize == 0) + if (xsize == 0 || ysize == 0) { return preview; + } /* sanity checks & initialize */ if (preview->rect) { @@ -1492,15 +1542,17 @@ bNodePreview *BKE_node_preview_verify( bNodePreview *BKE_node_preview_copy(bNodePreview *preview) { bNodePreview *new_preview = MEM_dupallocN(preview); - if (preview->rect) + if (preview->rect) { new_preview->rect = MEM_dupallocN(preview->rect); + } return new_preview; } void BKE_node_preview_free(bNodePreview *preview) { - if (preview->rect) + if (preview->rect) { MEM_freeN(preview->rect); + } MEM_freeN(preview); } @@ -1522,18 +1574,21 @@ static void node_preview_init_tree_recursive(bNodeInstanceHash *previews, BKE_node_preview_verify(previews, key, xsize, ysize, create); } - if (node->type == NODE_GROUP && node->id) + if (node->type == NODE_GROUP && node->id) { node_preview_init_tree_recursive(previews, (bNodeTree *)node->id, key, xsize, ysize, create); + } } } void BKE_node_preview_init_tree(bNodeTree *ntree, int xsize, int ysize, int create_previews) { - if (!ntree) + if (!ntree) { return; + } - if (!ntree->previews) + if (!ntree->previews) { ntree->previews = BKE_node_instance_hash_new("node previews"); + } node_preview_init_tree_recursive( ntree->previews, ntree, NODE_INSTANCE_KEY_BASE, xsize, ysize, create_previews); @@ -1547,18 +1602,21 @@ static void node_preview_tag_used_recursive(bNodeInstanceHash *previews, for (node = ntree->nodes.first; node; node = node->next) { bNodeInstanceKey key = BKE_node_instance_key(parent_key, ntree, node); - if (BKE_node_preview_used(node)) + if (BKE_node_preview_used(node)) { BKE_node_instance_hash_tag_key(previews, key); + } - if (node->type == NODE_GROUP && node->id) + if (node->type == NODE_GROUP && node->id) { node_preview_tag_used_recursive(previews, (bNodeTree *)node->id, key); + } } } void BKE_node_preview_remove_unused(bNodeTree *ntree) { - if (!ntree || !ntree->previews) + if (!ntree || !ntree->previews) { return; + } /* use the instance hash functions for tagging and removing unused previews */ BKE_node_instance_hash_clear_tags(ntree->previews); @@ -1570,8 +1628,9 @@ void BKE_node_preview_remove_unused(bNodeTree *ntree) void BKE_node_preview_free_tree(bNodeTree *ntree) { - if (!ntree) + if (!ntree) { return; + } if (ntree->previews) { BKE_node_instance_hash_free(ntree->previews, (bNodeInstanceValueFP)BKE_node_preview_free); @@ -1581,19 +1640,20 @@ void BKE_node_preview_free_tree(bNodeTree *ntree) void BKE_node_preview_clear(bNodePreview *preview) { - if (preview && preview->rect) + if (preview && preview->rect) { memset(preview->rect, 0, MEM_allocN_len(preview->rect)); + } } void BKE_node_preview_clear_tree(bNodeTree *ntree) { bNodeInstanceHashIterator iter; - if (!ntree || !ntree->previews) + if (!ntree || !ntree->previews) { return; + } - NODE_INSTANCE_HASH_ITER(iter, ntree->previews) - { + NODE_INSTANCE_HASH_ITER (iter, ntree->previews) { bNodePreview *preview = BKE_node_instance_hash_iterator_get_value(&iter); BKE_node_preview_clear(preview); } @@ -1618,17 +1678,18 @@ void BKE_node_preview_sync_tree(bNodeTree *to_ntree, bNodeTree *from_ntree) bNodeInstanceHash *to_previews = to_ntree->previews; bNodeInstanceHashIterator iter; - if (!from_previews || !to_previews) + if (!from_previews || !to_previews) { return; + } - NODE_INSTANCE_HASH_ITER(iter, from_previews) - { + NODE_INSTANCE_HASH_ITER (iter, from_previews) { bNodeInstanceKey key = BKE_node_instance_hash_iterator_get_key(&iter); bNodePreview *from = BKE_node_instance_hash_iterator_get_value(&iter); bNodePreview *to = BKE_node_instance_hash_lookup(to_previews, key); - if (from && to) + if (from && to) { node_preview_sync(to, from); + } } } @@ -1636,8 +1697,9 @@ void BKE_node_preview_merge_tree(bNodeTree *to_ntree, bNodeTree *from_ntree, boo { if (remove_old || !to_ntree->previews) { /* free old previews */ - if (to_ntree->previews) + if (to_ntree->previews) { BKE_node_instance_hash_free(to_ntree->previews, (bNodeInstanceValueFP)BKE_node_preview_free); + } /* transfer previews */ to_ntree->previews = from_ntree->previews; @@ -1650,8 +1712,7 @@ void BKE_node_preview_merge_tree(bNodeTree *to_ntree, bNodeTree *from_ntree, boo bNodeInstanceHashIterator iter; if (from_ntree->previews) { - NODE_INSTANCE_HASH_ITER(iter, from_ntree->previews) - { + NODE_INSTANCE_HASH_ITER (iter, from_ntree->previews) { bNodeInstanceKey key = BKE_node_instance_hash_iterator_get_key(&iter); bNodePreview *preview = BKE_node_instance_hash_iterator_get_value(&iter); @@ -1661,7 +1722,8 @@ void BKE_node_preview_merge_tree(bNodeTree *to_ntree, bNodeTree *from_ntree, boo BKE_node_instance_hash_insert(to_ntree->previews, key, preview); } - /* Note: NULL free function here, because pointers have already been moved over to to_ntree->previews! */ + /* Note: NULL free function here, + * because pointers have already been moved over to to_ntree->previews! */ BKE_node_instance_hash_free(from_ntree->previews, NULL); from_ntree->previews = NULL; } @@ -1686,9 +1748,9 @@ void BKE_node_preview_set_pixel( rgba_float_to_uchar(tar, col); } } - //else printf("prv out bound x y %d %d\n", x, y); + // else printf("prv out bound x y %d %d\n", x, y); } - //else printf("prv out bound x y %d %d\n", x, y); + // else printf("prv out bound x y %d %d\n", x, y); } } @@ -1706,18 +1768,22 @@ void nodeUnlinkNode(bNodeTree *ntree, bNode *node) if (link->fromnode == node) { lb = &node->outputs; - if (link->tonode) + if (link->tonode) { link->tonode->update |= NODE_UPDATE; + } } - else if (link->tonode == node) + else if (link->tonode == node) { lb = &node->inputs; - else + } + else { lb = NULL; + } if (lb) { for (sock = lb->first; sock; sock = sock->next) { - if (link->fromsock == sock || link->tosock == sock) + if (link->fromsock == sock || link->tosock == sock) { break; + } } if (sock) { nodeRemLink(ntree, link); @@ -1730,8 +1796,9 @@ static void node_unlink_attached(bNodeTree *ntree, bNode *parent) { bNode *node; for (node = ntree->nodes.first; node; node = node->next) { - if (node->parent == parent) + if (node->parent == parent) { nodeDetachNode(node); + } } } @@ -1751,8 +1818,9 @@ static void node_free_node(bNodeTree *ntree, bNode *node) BLI_remlink(&ntree->nodes, node); - if (ntree->typeinfo->free_node_cache) + if (ntree->typeinfo->free_node_cache) { ntree->typeinfo->free_node_cache(ntree, node); + } /* texture node has bad habit of keeping exec data around */ if (ntree->type == NTREE_TEXTURE && ntree->execdata) { @@ -1788,8 +1856,9 @@ static void node_free_node(bNodeTree *ntree, bNode *node) MEM_freeN(node); - if (ntree) + if (ntree) { ntree->update |= NTREE_UPDATE_NODES; + } } void ntreeFreeLocalNode(bNodeTree *ntree, bNode *node) @@ -1844,8 +1913,9 @@ static void node_socket_interface_free(bNodeTree *UNUSED(ntree), bNodeSocket *so MEM_freeN(sock->prop); } - if (sock->default_value) + if (sock->default_value) { MEM_freeN(sock->default_value); + } } static void free_localized_node_groups(bNodeTree *ntree) @@ -1857,8 +1927,9 @@ static void free_localized_node_groups(bNodeTree *ntree) * since it is a localized copy itself (no risk of accessing free'd * data in main, see [#37939]). */ - if (!(ntree->id.tag & LIB_TAG_LOCALIZED)) + if (!(ntree->id.tag & LIB_TAG_LOCALIZED)) { return; + } for (node = ntree->nodes.first; node; node = node->next) { if ((ELEM(node->type, NODE_GROUP, NODE_CUSTOM_GROUP)) && node->id) { @@ -1925,8 +1996,9 @@ void ntreeFreeTree(bNodeTree *ntree) BKE_node_instance_hash_free(ntree->previews, (bNodeInstanceValueFP)BKE_node_preview_free); } - if (ntree->duplilock) + if (ntree->duplilock) { BLI_mutex_free(ntree->duplilock); + } if (ntree->id.tag & LIB_TAG_LOCALIZED) { BKE_libblock_free_data(&ntree->id, true); @@ -1952,11 +2024,13 @@ void ntreeFreeLocalTree(bNodeTree *ntree) void ntreeFreeCache(bNodeTree *ntree) { - if (ntree == NULL) + if (ntree == NULL) { return; + } - if (ntree->typeinfo->free_cache) + if (ntree->typeinfo->free_cache) { ntree->typeinfo->free_cache(ntree); + } } void ntreeSetOutput(bNodeTree *ntree) @@ -1970,8 +2044,9 @@ void ntreeSetOutput(bNodeTree *ntree) int output = 0; /* we need a check for which output node should be tagged like this, below an exception */ - if (node->type == CMP_NODE_OUTPUT_FILE) + if (node->type == CMP_NODE_OUTPUT_FILE) { continue; + } /* there is more types having output class, each one is checked */ for (tnode = ntree->nodes.first; tnode; tnode = tnode->next) { @@ -1985,8 +2060,9 @@ void ntreeSetOutput(bNodeTree *ntree) ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))) { if (tnode->flag & NODE_DO_OUTPUT) { output++; - if (output > 1) + if (output > 1) { tnode->flag &= ~NODE_DO_OUTPUT; + } } } } @@ -1995,15 +2071,17 @@ void ntreeSetOutput(bNodeTree *ntree) if (tnode->type == node->type) { if (tnode->flag & NODE_DO_OUTPUT) { output++; - if (output > 1) + if (output > 1) { tnode->flag &= ~NODE_DO_OUTPUT; + } } } } } } - if (output == 0) + if (output == 0) { node->flag |= NODE_DO_OUTPUT; + } } /* group node outputs use this flag too */ @@ -2015,13 +2093,15 @@ void ntreeSetOutput(bNodeTree *ntree) if (tnode->type == NODE_GROUP_OUTPUT) { if (tnode->flag & NODE_DO_OUTPUT) { output++; - if (output > 1) + if (output > 1) { tnode->flag &= ~NODE_DO_OUTPUT; + } } } } - if (output == 0) + if (output == 0) { node->flag |= NODE_DO_OUTPUT; + } } } @@ -2057,18 +2137,22 @@ void ntreeMakeLocal(Main *bmain, bNodeTree *ntree, bool id_in_mainlist, const bo int ntreeNodeExists(bNodeTree *ntree, bNode *testnode) { bNode *node = ntree->nodes.first; - for (; node; node = node->next) - if (node == testnode) + for (; node; node = node->next) { + if (node == testnode) { return 1; + } + } return 0; } int ntreeOutputExists(bNode *node, bNodeSocket *testsock) { bNodeSocket *sock = node->outputs.first; - for (; sock; sock = sock->next) - if (sock == testsock) + for (; sock; sock = sock->next) { + if (sock == testsock) { return 1; + } + } return 0; } @@ -2123,15 +2207,17 @@ bNodeTree *ntreeLocalize(bNodeTree *ntree) node->new_node->original = node; } - if (ntree->typeinfo->localize) + if (ntree->typeinfo->localize) { ntree->typeinfo->localize(ltree, ntree); + } BLI_mutex_unlock(ntree->duplilock); return ltree; } - else + else { return NULL; + } } /* sync local composite with real tree */ @@ -2140,8 +2226,9 @@ bNodeTree *ntreeLocalize(bNodeTree *ntree) void ntreeLocalSync(bNodeTree *localtree, bNodeTree *ntree) { if (localtree && ntree) { - if (ntree->typeinfo->local_sync) + if (ntree->typeinfo->local_sync) { ntree->typeinfo->local_sync(localtree, ntree); + } } } @@ -2150,8 +2237,9 @@ void ntreeLocalSync(bNodeTree *localtree, bNodeTree *ntree) void ntreeLocalMerge(Main *bmain, bNodeTree *localtree, bNodeTree *ntree) { if (ntree && localtree) { - if (ntree->typeinfo->local_merge) + if (ntree->typeinfo->local_merge) { ntree->typeinfo->local_merge(bmain, localtree, ntree); + } ntreeFreeTree(localtree); MEM_freeN(localtree); @@ -2182,29 +2270,12 @@ static bNodeSocket *make_socket_interface(bNodeTree *ntree, /* assign new unique index */ own_index = ntree->cur_index++; /* use the own_index as socket identifier */ - if (in_out == SOCK_IN) + if (in_out == SOCK_IN) { BLI_snprintf(sock->identifier, MAX_NAME, "Input_%d", own_index); - else + } + else { BLI_snprintf(sock->identifier, MAX_NAME, "Output_%d", own_index); -#ifdef USE_NODE_COMPAT_CUSTOMNODES - /* XXX forward compatibility: - * own_index is deprecated, but needs to be set here. - * Node sockets generally use the identifier string instead now, - * but reconstructing own_index in writefile.c would require parsing the identifier string. - */ - -# if (defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 406)) || defined(__clang__) -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wdeprecated-declarations" -# endif - - sock->own_index = own_index; - -# if (defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 406)) || defined(__clang__) -# pragma GCC diagnostic pop -# endif - -#endif /* USE_NODE_COMPAT_CUSTOMNODES */ + } sock->limit = (in_out == SOCK_IN ? 1 : 0xFFF); @@ -2218,9 +2289,11 @@ static bNodeSocket *make_socket_interface(bNodeTree *ntree, bNodeSocket *ntreeFindSocketInterface(bNodeTree *ntree, int in_out, const char *identifier) { bNodeSocket *iosock = (in_out == SOCK_IN ? ntree->inputs.first : ntree->outputs.first); - for (; iosock; iosock = iosock->next) - if (STREQ(iosock->identifier, identifier)) + for (; iosock; iosock = iosock->next) { + if (STREQ(iosock->identifier, identifier)) { return iosock; + } + } return NULL; } @@ -2269,8 +2342,9 @@ struct bNodeSocket *ntreeAddSocketInterfaceFromSocket(bNodeTree *ntree, bNodeSocket *iosock = ntreeAddSocketInterface( ntree, from_sock->in_out, from_sock->idname, from_sock->name); if (iosock) { - if (iosock->typeinfo->interface_from_socket) + if (iosock->typeinfo->interface_from_socket) { iosock->typeinfo->interface_from_socket(ntree, iosock, from_node, from_sock); + } } return iosock; } @@ -2283,8 +2357,9 @@ struct bNodeSocket *ntreeInsertSocketInterfaceFromSocket(bNodeTree *ntree, bNodeSocket *iosock = ntreeInsertSocketInterface( ntree, from_sock->in_out, from_sock->idname, next_sock, from_sock->name); if (iosock) { - if (iosock->typeinfo->interface_from_socket) + if (iosock->typeinfo->interface_from_socket) { iosock->typeinfo->interface_from_socket(ntree, iosock, from_node, from_sock); + } } return iosock; } @@ -2358,13 +2433,15 @@ static void ntree_interface_type_create(bNodeTree *ntree) /* add socket properties */ for (sock = ntree->inputs.first; sock; sock = sock->next) { bNodeSocketType *stype = sock->typeinfo; - if (stype && stype->interface_register_properties) + if (stype && stype->interface_register_properties) { stype->interface_register_properties(ntree, sock, srna); + } } for (sock = ntree->outputs.first; sock; sock = sock->next) { bNodeSocketType *stype = sock->typeinfo; - if (stype && stype->interface_register_properties) + if (stype && stype->interface_register_properties) { stype->interface_register_properties(ntree, sock, srna); + } } } @@ -2444,13 +2521,17 @@ bool ntreeHasTree(const bNodeTree *ntree, const bNodeTree *lookup) { bNode *node; - if (ntree == lookup) + if (ntree == lookup) { return true; + } - for (node = ntree->nodes.first; node; node = node->next) - if (ELEM(node->type, NODE_GROUP, NODE_CUSTOM_GROUP) && node->id) - if (ntreeHasTree((bNodeTree *)node->id, lookup)) + for (node = ntree->nodes.first; node; node = node->next) { + if (ELEM(node->type, NODE_GROUP, NODE_CUSTOM_GROUP) && node->id) { + if (ntreeHasTree((bNodeTree *)node->id, lookup)) { return true; + } + } + } return false; } @@ -2460,10 +2541,12 @@ bNodeLink *nodeFindLink(bNodeTree *ntree, bNodeSocket *from, bNodeSocket *to) bNodeLink *link; for (link = ntree->links.first; link; link = link->next) { - if (link->fromsock == from && link->tosock == to) + if (link->fromsock == from && link->tosock == to) { return link; - if (link->fromsock == to && link->tosock == from) /* hrms? */ + } + if (link->fromsock == to && link->tosock == from) { /* hrms? */ return link; + } } return NULL; } @@ -2474,8 +2557,9 @@ int nodeCountSocketLinks(bNodeTree *ntree, bNodeSocket *sock) int tot = 0; for (link = ntree->links.first; link; link = link->next) { - if (link->fromsock == sock || link->tosock == sock) + if (link->fromsock == sock || link->tosock == sock) { tot++; + } } return tot; } @@ -2484,12 +2568,15 @@ bNode *nodeGetActive(bNodeTree *ntree) { bNode *node; - if (ntree == NULL) + if (ntree == NULL) { return NULL; + } - for (node = ntree->nodes.first; node; node = node->next) - if (node->flag & NODE_ACTIVE) + for (node = ntree->nodes.first; node; node = node->next) { + if (node->flag & NODE_ACTIVE) { break; + } + } return node; } @@ -2500,10 +2587,13 @@ static bNode *node_get_active_id_recursive(bNodeInstanceKey active_key, { if (parent_key.value == active_key.value || active_key.value == 0) { bNode *node; - for (node = ntree->nodes.first; node; node = node->next) - if (node->id && GS(node->id->name) == idtype) - if (node->flag & NODE_ACTIVE_ID) + for (node = ntree->nodes.first; node; node = node->next) { + if (node->id && GS(node->id->name) == idtype) { + if (node->flag & NODE_ACTIVE_ID) { return node; + } + } + } } else { bNode *node, *tnode; @@ -2514,8 +2604,9 @@ static bNode *node_get_active_id_recursive(bNodeInstanceKey active_key, if (group) { bNodeInstanceKey group_key = BKE_node_instance_key(parent_key, ntree, node); tnode = node_get_active_id_recursive(active_key, group_key, group, idtype); - if (tnode) + if (tnode) { return tnode; + } } } } @@ -2527,11 +2618,13 @@ static bNode *node_get_active_id_recursive(bNodeInstanceKey active_key, /* two active flags, ID nodes have special flag for buttons display */ bNode *nodeGetActiveID(bNodeTree *ntree, short idtype) { - if (ntree) + if (ntree) { return node_get_active_id_recursive( ntree->active_viewer_key, NODE_INSTANCE_KEY_BASE, ntree, idtype); - else + } + else { return NULL; + } } bool nodeSetActiveID(bNodeTree *ntree, short idtype, ID *id) @@ -2539,8 +2632,9 @@ bool nodeSetActiveID(bNodeTree *ntree, short idtype, ID *id) bNode *node; bool ok = false; - if (ntree == NULL) + if (ntree == NULL) { return ok; + } for (node = ntree->nodes.first; node; node = node->next) { if (node->id && GS(node->id->name) == idtype) { @@ -2559,8 +2653,9 @@ bool nodeSetActiveID(bNodeTree *ntree, short idtype, ID *id) * just pass NULL so other matching nodes are deactivated. */ for (node = ntree->nodes.first; node; node = node->next) { - if (node->type == NODE_GROUP) + if (node->type == NODE_GROUP) { ok |= nodeSetActiveID((bNodeTree *)node->id, idtype, (ok == false ? id : NULL)); + } } return ok; @@ -2571,12 +2666,15 @@ void nodeClearActiveID(bNodeTree *ntree, short idtype) { bNode *node; - if (ntree == NULL) + if (ntree == NULL) { return; + } - for (node = ntree->nodes.first; node; node = node->next) - if (node->id && GS(node->id->name) == idtype) + for (node = ntree->nodes.first; node; node = node->next) { + if (node->id && GS(node->id->name) == idtype) { node->flag &= ~NODE_ACTIVE_ID; + } + } } void nodeSetSelected(bNode *node, bool select) @@ -2590,10 +2688,12 @@ void nodeSetSelected(bNode *node, bool select) node->flag &= ~NODE_SELECT; /* deselect sockets too */ - for (sock = node->inputs.first; sock; sock = sock->next) + for (sock = node->inputs.first; sock; sock = sock->next) { sock->flag &= ~NODE_SELECT; - for (sock = node->outputs.first; sock; sock = sock->next) + } + for (sock = node->outputs.first; sock; sock = sock->next) { sock->flag &= ~NODE_SELECT; + } } } @@ -2601,11 +2701,13 @@ void nodeClearActive(bNodeTree *ntree) { bNode *node; - if (ntree == NULL) + if (ntree == NULL) { return; + } - for (node = ntree->nodes.first; node; node = node->next) + for (node = ntree->nodes.first; node; node = node->next) { node->flag &= ~(NODE_ACTIVE | NODE_ACTIVE_ID); + } } /* two active flags, ID nodes have special flag for buttons display */ @@ -2618,18 +2720,22 @@ void nodeSetActive(bNodeTree *ntree, bNode *node) tnode->flag &= ~NODE_ACTIVE; if (node->id && tnode->id) { - if (GS(node->id->name) == GS(tnode->id->name)) + if (GS(node->id->name) == GS(tnode->id->name)) { tnode->flag &= ~NODE_ACTIVE_ID; + } } - if (node->typeinfo->nclass == NODE_CLASS_TEXTURE) + if (node->typeinfo->nclass == NODE_CLASS_TEXTURE) { tnode->flag &= ~NODE_ACTIVE_TEXTURE; + } } node->flag |= NODE_ACTIVE; - if (node->id) + if (node->id) { node->flag |= NODE_ACTIVE_ID; - if (node->typeinfo->nclass == NODE_CLASS_TEXTURE) + } + if (node->typeinfo->nclass == NODE_CLASS_TEXTURE) { node->flag |= NODE_ACTIVE_TEXTURE; + } } int nodeSocketIsHidden(bNodeSocket *sock) @@ -2809,8 +2915,9 @@ static bNodeInstanceKey node_hash_int_str(bNodeInstanceKey hash, const char *str { char c; - while ((c = *str++)) + while ((c = *str++)) { hash.value = ((hash.value << 5) + hash.value) ^ c; /* (hash * 33) ^ c */ + } /* separator '\0' character, to avoid ambiguity from concatenated strings */ hash.value = (hash.value << 5) + hash.value; /* hash * 33 */ @@ -2824,8 +2931,9 @@ bNodeInstanceKey BKE_node_instance_key(bNodeInstanceKey parent_key, bNodeTree *n key = node_hash_int_str(parent_key, ntree->id.name + 2); - if (node) + if (node) { key = node_hash_int_str(key, node->name); + } return key; } @@ -2901,8 +3009,7 @@ void BKE_node_instance_hash_clear_tags(bNodeInstanceHash *hash) { bNodeInstanceHashIterator iter; - NODE_INSTANCE_HASH_ITER(iter, hash) - { + NODE_INSTANCE_HASH_ITER (iter, hash) { bNodeInstanceHashEntry *value = BKE_node_instance_hash_iterator_get_value(&iter); value->tag = 0; @@ -2923,8 +3030,9 @@ bool BKE_node_instance_hash_tag_key(bNodeInstanceHash *hash, bNodeInstanceKey ke entry->tag = 1; return true; } - else + else { return false; + } } void BKE_node_instance_hash_remove_untagged(bNodeInstanceHash *hash, @@ -2940,12 +3048,12 @@ void BKE_node_instance_hash_remove_untagged(bNodeInstanceHash *hash, int num_untagged, i; num_untagged = 0; - NODE_INSTANCE_HASH_ITER(iter, hash) - { + NODE_INSTANCE_HASH_ITER (iter, hash) { bNodeInstanceHashEntry *value = BKE_node_instance_hash_iterator_get_value(&iter); - if (!value->tag) + if (!value->tag) { untagged[num_untagged++] = BKE_node_instance_hash_iterator_get_key(&iter); + } } for (i = 0; i < num_untagged; ++i) { @@ -2970,19 +3078,23 @@ static int node_get_deplist_recurs(bNodeTree *ntree, bNode *node, bNode ***nsort for (link = ntree->links.first; link; link = link->next) { if (link->tonode == node) { fromnode = link->fromnode; - if (fromnode->done == 0) + if (fromnode->done == 0) { fromnode->level = node_get_deplist_recurs(ntree, fromnode, nsort); - if (fromnode->level <= level) + } + if (fromnode->level <= level) { level = fromnode->level - 1; + } } } /* check parent node */ if (node->parent) { - if (node->parent->done == 0) + if (node->parent->done == 0) { node->parent->level = node_get_deplist_recurs(ntree, node->parent, nsort); - if (node->parent->level <= level) + } + if (node->parent->level <= level) { level = node->parent->level - 1; + } } if (nsort) { @@ -3055,8 +3167,9 @@ void ntreeTagUsedSockets(bNodeTree *ntree) for (link = ntree->links.first; link; link = link->next) { /* link is unused if either side is disabled */ - if ((link->fromsock->flag & SOCK_UNAVAIL) || (link->tosock->flag & SOCK_UNAVAIL)) + if ((link->fromsock->flag & SOCK_UNAVAIL) || (link->tosock->flag & SOCK_UNAVAIL)) { continue; + } link->fromsock->flag |= SOCK_IN_USE; link->tosock->flag |= SOCK_IN_USE; @@ -3089,23 +3202,55 @@ static void ntree_validate_links(bNodeTree *ntree) for (link = ntree->links.first; link; link = link->next) { link->flag |= NODE_LINK_VALID; - if (link->fromnode && link->tonode && link->fromnode->level <= link->tonode->level) + if (link->fromnode && link->tonode && link->fromnode->level <= link->tonode->level) { link->flag &= ~NODE_LINK_VALID; + } else if (ntree->typeinfo->validate_link) { - if (!ntree->typeinfo->validate_link(ntree, link)) + if (!ntree->typeinfo->validate_link(ntree, link)) { link->flag &= ~NODE_LINK_VALID; + } } } } -void ntreeVerifyNodes(struct Main *main, struct ID *id) +void ntreeUpdateAllNew(Main *main) { + /* Update all new node trees on file read or append, to add/remove sockets + * in groups nodes if the group changed, and handle any update flags that + * might have been set in file reading or versioning. */ FOREACH_NODETREE_BEGIN (main, ntree, owner_id) { - bNode *node; + if (owner_id->tag & LIB_TAG_NEW) { + for (bNode *node = ntree->nodes.first; node; node = node->next) { + if (node->typeinfo->group_update_func) { + node->typeinfo->group_update_func(ntree, node); + } + } + + ntreeUpdateTree(NULL, ntree); + } + } + FOREACH_NODETREE_END; +} + +void ntreeUpdateAllUsers(Main *main, ID *ngroup) +{ + /* Update all users of ngroup, to add/remove sockets as needed. */ + FOREACH_NODETREE_BEGIN (main, ntree, owner_id) { + bool need_update = false; + + for (bNode *node = ntree->nodes.first; node; node = node->next) { + if (node->id == ngroup) { + if (node->typeinfo->group_update_func) { + node->typeinfo->group_update_func(ntree, node); + } - for (node = ntree->nodes.first; node; node = node->next) - if (node->typeinfo->verifyfunc) - node->typeinfo->verifyfunc(ntree, node, id); + need_update = true; + } + } + + if (need_update) { + ntreeUpdateTree(NULL, ntree); + } } FOREACH_NODETREE_END; } @@ -3114,12 +3259,14 @@ void ntreeUpdateTree(Main *bmain, bNodeTree *ntree) { bNode *node; - if (!ntree) + if (!ntree) { return; + } /* avoid reentrant updates, can be caused by RNA update callbacks */ - if (ntree->is_updating) + if (ntree->is_updating) { return; + } ntree->is_updating = true; if (ntree->update & (NTREE_UPDATE_LINKS | NTREE_UPDATE_NODES)) { @@ -3131,25 +3278,29 @@ void ntreeUpdateTree(Main *bmain, bNodeTree *ntree) for (node = ntree->nodes.first; node; node = node->next) { /* node tree update tags override individual node update flags */ if ((node->update & NODE_UPDATE) || (ntree->update & NTREE_UPDATE)) { - if (node->typeinfo->updatefunc) + if (node->typeinfo->updatefunc) { node->typeinfo->updatefunc(ntree, node); + } nodeUpdateInternalLinks(ntree, node); } } /* generic tree update callback */ - if (ntree->typeinfo->update) + if (ntree->typeinfo->update) { ntree->typeinfo->update(ntree); + } /* XXX this should be moved into the tree type update callback for tree supporting node groups. * Currently the node tree interface is still a generic feature of the base NodeTree type. */ - if (ntree->update & NTREE_UPDATE_GROUP) + if (ntree->update & NTREE_UPDATE_GROUP) { ntreeInterfaceTypeUpdate(ntree); + } /* XXX hack, should be done by depsgraph!! */ - if (bmain) - ntreeVerifyNodes(bmain, &ntree->id); + if (bmain) { + ntreeUpdateAllUsers(bmain, &ntree->id); + } if (ntree->update & (NTREE_UPDATE_LINKS | NTREE_UPDATE_NODES)) { /* node updates can change sockets or links, repeat link pointer update afterward */ @@ -3174,12 +3325,14 @@ void ntreeUpdateTree(Main *bmain, bNodeTree *ntree) void nodeUpdate(bNodeTree *ntree, bNode *node) { /* avoid reentrant updates, can be caused by RNA update callbacks */ - if (ntree->is_updating) + if (ntree->is_updating) { return; + } ntree->is_updating = true; - if (node->typeinfo->updatefunc) + if (node->typeinfo->updatefunc) { node->typeinfo->updatefunc(ntree, node); + } nodeUpdateInternalLinks(ntree, node); @@ -3194,20 +3347,23 @@ bool nodeUpdateID(bNodeTree *ntree, ID *id) bNode *node; bool changed = false; - if (ELEM(NULL, id, ntree)) + if (ELEM(NULL, id, ntree)) { return changed; + } /* avoid reentrant updates, can be caused by RNA update callbacks */ - if (ntree->is_updating) + if (ntree->is_updating) { return changed; + } ntree->is_updating = true; for (node = ntree->nodes.first; node; node = node->next) { if (node->id == id) { changed = true; node->update |= NODE_UPDATE_ID; - if (node->typeinfo->updatefunc) + if (node->typeinfo->updatefunc) { node->typeinfo->updatefunc(ntree, node); + } /* clear update flag */ node->update = 0; } @@ -3225,8 +3381,9 @@ void nodeUpdateInternalLinks(bNodeTree *ntree, bNode *node) { BLI_freelistN(&node->internal_links); - if (node->typeinfo && node->typeinfo->update_internal_links) + if (node->typeinfo && node->typeinfo->update_internal_links) { node->typeinfo->update_internal_links(ntree, node); + } } /* ************* node type access ********** */ @@ -3372,8 +3529,9 @@ void node_type_socket_templates(struct bNodeType *ntype, /* automatically generate unique identifiers */ if (inputs) { /* clear identifier strings (uninitialized memory) */ - for (ntemp = inputs; ntemp->type >= 0; ++ntemp) + for (ntemp = inputs; ntemp->type >= 0; ++ntemp) { ntemp->identifier[0] = '\0'; + } for (ntemp = inputs; ntemp->type >= 0; ++ntemp) { BLI_strncpy(ntemp->identifier, ntemp->name, sizeof(ntemp->identifier)); @@ -3382,8 +3540,9 @@ void node_type_socket_templates(struct bNodeType *ntype, } if (outputs) { /* clear identifier strings (uninitialized memory) */ - for (ntemp = outputs; ntemp->type >= 0; ++ntemp) + for (ntemp = outputs; ntemp->type >= 0; ++ntemp) { ntemp->identifier[0] = '\0'; + } for (ntemp = outputs; ntemp->type >= 0; ++ntemp) { BLI_strncpy(ntemp->identifier, ntemp->name, sizeof(ntemp->identifier)); @@ -3402,10 +3561,12 @@ void node_type_size(struct bNodeType *ntype, int width, int minwidth, int maxwid { ntype->width = width; ntype->minwidth = minwidth; - if (maxwidth <= minwidth) + if (maxwidth <= minwidth) { ntype->maxwidth = FLT_MAX; - else + } + else { ntype->maxwidth = maxwidth; + } } void node_type_size_preset(struct bNodeType *ntype, eNodeSizePreset size) @@ -3437,10 +3598,12 @@ void node_type_storage(bNodeType *ntype, struct bNode *dest_node, struct bNode *src_node)) { - if (storagename) + if (storagename) { BLI_strncpy(ntype->storagename, storagename, sizeof(ntype->storagename)); - else + } + else { ntype->storagename[0] = '\0'; + } ntype->copyfunc = copyfunc; ntype->freefunc = freefunc; } @@ -3453,13 +3616,15 @@ void node_type_label( } void node_type_update(struct bNodeType *ntype, - void (*updatefunc)(struct bNodeTree *ntree, struct bNode *node), - void (*verifyfunc)(struct bNodeTree *ntree, - struct bNode *node, - struct ID *id)) + void (*updatefunc)(struct bNodeTree *ntree, struct bNode *node)) { ntype->updatefunc = updatefunc; - ntype->verifyfunc = verifyfunc; +} + +void node_type_group_update(struct bNodeType *ntype, + void (*group_update_func)(struct bNodeTree *ntree, struct bNode *node)) +{ + ntype->group_update_func = group_update_func; } void node_type_exec(struct bNodeType *ntype, @@ -3796,10 +3961,12 @@ void free_nodesystem(void) if (nodesockettypes_hash) { NODE_SOCKET_TYPES_BEGIN (st) { - if (st->ext_socket.free) + if (st->ext_socket.free) { st->ext_socket.free(st->ext_socket.data); - if (st->ext_interface.free) + } + if (st->ext_interface.free) { st->ext_interface.free(st->ext_interface.data); + } } NODE_SOCKET_TYPES_END; diff --git a/source/blender/blenkernel/intern/object.c b/source/blender/blenkernel/intern/object.c index 303d63d6a8b..38a8ad2769a 100644 --- a/source/blender/blenkernel/intern/object.c +++ b/source/blender/blenkernel/intern/object.c @@ -223,7 +223,8 @@ void BKE_object_modifier_hook_reset(Object *ob, HookModifierData *hmd) if (hmd->subtarget[0] && pchan) { float imat[4][4], mat[4][4]; - /* calculate the world-space matrix for the pose-channel target first, then carry on as usual */ + /* Calculate the world-space matrix for the pose-channel target first, + * then carry on as usual. */ mul_m4_m4m4(mat, hmd->object->obmat, pchan->pose_mat); invert_m4_m4(imat, mat); @@ -247,7 +248,8 @@ void BKE_object_modifier_gpencil_hook_reset(Object *ob, HookGpencilModifierData if (hmd->subtarget[0] && pchan) { float imat[4][4], mat[4][4]; - /* calculate the world-space matrix for the pose-channel target first, then carry on as usual */ + /* Calculate the world-space matrix for the pose-channel target first, + * then carry on as usual. */ mul_m4_m4m4(mat, hmd->object->obmat, pchan->pose_mat); invert_m4_m4(imat, mat); @@ -300,8 +302,9 @@ void BKE_object_link_modifiers(Scene *scene, struct Object *ob_dst, const struct continue; } - if (!BKE_object_support_modifier_type_check(ob_dst, md->type)) + if (!BKE_object_support_modifier_type_check(ob_dst, md->type)) { continue; + } switch (md->type) { case eModifierType_Softbody: @@ -444,7 +447,6 @@ void BKE_object_free_derived_caches(Object *ob) object_update_from_subsurf_ccg(ob); BKE_object_free_derived_mesh_caches(ob); - BKE_armature_cached_bbone_deformation_free(ob); if (ob->runtime.mesh_eval != NULL) { Mesh *mesh_eval = ob->runtime.mesh_eval; @@ -580,8 +582,9 @@ void BKE_object_free(Object *ob) /* Free runtime curves data. */ if (ob->runtime.curve_cache) { BKE_curve_bevelList_free(&ob->runtime.curve_cache->bev); - if (ob->runtime.curve_cache->path) + if (ob->runtime.curve_cache->path) { free_path(ob->runtime.curve_cache->path); + } MEM_freeN(ob->runtime.curve_cache); ob->runtime.curve_cache = NULL; } @@ -728,13 +731,15 @@ bool BKE_object_exists_check(Main *bmain, const Object *obtest) { Object *ob; - if (obtest == NULL) + if (obtest == NULL) { return false; + } ob = bmain->objects.first; while (ob) { - if (ob == obtest) + if (ob == obtest) { return true; + } ob = ob->id.next; } return false; @@ -878,8 +883,9 @@ Object *BKE_object_add_only_object(Main *bmain, int type, const char *name) { Object *ob; - if (!name) + if (!name) { name = get_obdata_defname(type); + } ob = BKE_libblock_alloc(bmain, ID_OB, name, 0); @@ -971,8 +977,9 @@ Object *BKE_object_add_for_data( /* same as object_add_common, except we don't create new ob->data */ ob = BKE_object_add_only_object(bmain, type, name); ob->data = data; - if (do_id_user) + if (do_id_user) { id_us_plus(data); + } BKE_view_layer_base_deselect_all(view_layer); DEG_id_tag_update_ex( @@ -1016,13 +1023,15 @@ void BKE_object_copy_softbody(struct Object *ob_dst, const struct Object *ob_src sbn->bpoint = MEM_dupallocN(sbn->bpoint); for (i = 0; i < sbn->totpoint; i++) { - if (sbn->bpoint[i].springs) + if (sbn->bpoint[i].springs) { sbn->bpoint[i].springs = MEM_dupallocN(sbn->bpoint[i].springs); + } } } - if (sb->bspring) + if (sb->bspring) { sbn->bspring = MEM_dupallocN(sb->bspring); + } } sbn->keys = NULL; @@ -1036,8 +1045,9 @@ void BKE_object_copy_softbody(struct Object *ob_dst, const struct Object *ob_src &sbn->shared->ptcaches, &sb->shared->ptcaches, flag); } - if (sb->effector_weights) + if (sb->effector_weights) { sbn->effector_weights = MEM_dupallocN(sb->effector_weights); + } ob_dst->soft = sbn; } @@ -1110,8 +1120,9 @@ void BKE_object_copy_particlesystems(Object *ob_dst, const Object *ob_src, const for (md = ob_dst->modifiers.first; md; md = md->next) { if (md->type == eModifierType_ParticleSystem) { ParticleSystemModifierData *psmd = (ParticleSystemModifierData *)md; - if (psmd->psys == psys) + if (psmd->psys == psys) { psmd->psys = npsys; + } } else if (md->type == eModifierType_DynamicPaint) { DynamicPaintModifierData *pmd = (DynamicPaintModifierData *)md; @@ -1126,8 +1137,9 @@ void BKE_object_copy_particlesystems(Object *ob_dst, const Object *ob_src, const if (smd->type == MOD_SMOKE_TYPE_FLOW) { if (smd->flow) { - if (smd->flow->psys == psys) + if (smd->flow->psys == psys) { smd->flow->psys = npsys; + } } } } @@ -1149,7 +1161,8 @@ static void copy_object_pose(Object *obn, const Object *ob, const int flag) chan->flag &= ~(POSE_LOC | POSE_ROT | POSE_SIZE); - /* XXX Remapping object pointing onto itself should be handled by generic BKE_library_remap stuff, but... + /* XXX Remapping object pointing onto itself should be handled by generic + * BKE_library_remap stuff, but... * the flush_constraint_targets callback am not sure about, so will delay that for now. */ for (con = chan->constraints.first; con; con = con->next) { const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con); @@ -1160,12 +1173,14 @@ static void copy_object_pose(Object *obn, const Object *ob, const int flag) cti->get_constraint_targets(con, &targets); for (ct = targets.first; ct; ct = ct->next) { - if (ct->tar == ob) + if (ct->tar == ob) { ct->tar = obn; + } } - if (cti->flush_constraint_targets) + if (cti->flush_constraint_targets) { cti->flush_constraint_targets(con, &targets, 0); + } } } } @@ -1190,17 +1205,20 @@ bool BKE_object_pose_context_check(const Object *ob) Object *BKE_object_pose_armature_get(Object *ob) { - if (ob == NULL) + if (ob == NULL) { return NULL; + } - if (BKE_object_pose_context_check(ob)) + if (BKE_object_pose_context_check(ob)) { return ob; + } ob = modifiers_isDeformedByArmature(ob); /* Only use selected check when non-active. */ - if (BKE_object_pose_context_check(ob)) + if (BKE_object_pose_context_check(ob)) { return ob; + } return NULL; } @@ -1319,8 +1337,10 @@ void BKE_object_transform_copy(Object *ob_tar, const Object *ob_src) } /** - * Only copy internal data of Object ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of Object ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * @@ -1350,11 +1370,13 @@ void BKE_object_copy_data(Main *bmain, Object *ob_dst, const Object *ob_src, con ob_dst->matbits = NULL; } - if (ob_src->iuser) + if (ob_src->iuser) { ob_dst->iuser = MEM_dupallocN(ob_src->iuser); + } - if (ob_src->runtime.bb) + if (ob_src->runtime.bb) { ob_dst->runtime.bb = MEM_dupallocN(ob_src->runtime.bb); + } BLI_listbase_clear(&ob_dst->modifiers); @@ -1421,7 +1443,8 @@ void BKE_object_copy_data(Main *bmain, Object *ob_dst, const Object *ob_src, con copy_object_lod(ob_dst, ob_src, flag_subdata); - /* Do not copy object's preview (mostly due to the fact renderers create temp copy of objects). */ + /* Do not copy object's preview + * (mostly due to the fact renderers create temp copy of objects). */ if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0 && false) { /* XXX TODO temp hack */ BKE_previewimg_id_copy(&ob_dst->id, &ob_src->id); } @@ -1444,11 +1467,13 @@ Object *BKE_object_copy(Main *bmain, const Object *ob) /** Perform deep-copy of object and its 'children' data-blocks (obdata, materials, actions, etc.). * - * \param dupflag Controls which sub-data are also duplicated (see #eDupli_ID_Flags in DNA_userdef_types.h). + * \param dupflag Controls which sub-data are also duplicated + * (see #eDupli_ID_Flags in DNA_userdef_types.h). * - * \note This function does not do any remapping to new IDs, caller must do it (\a #BKE_libblock_relink_to_newid()). - * \note Caller MUST free \a newid pointers itself (#BKE_main_id_clear_newpoins()) and call updates of DEG too - * (#DAG_relations_tag_update()). + * \note This function does not do any remapping to new IDs, caller must do it + * (\a #BKE_libblock_relink_to_newid()). + * \note Caller MUST free \a newid pointers itself (#BKE_main_id_clear_newpoins()) and call updates + * of DEG too (#DAG_relations_tag_update()). */ Object *BKE_object_duplicate(Main *bmain, const Object *ob, const int dupflag) { @@ -1588,8 +1613,9 @@ Object *BKE_object_duplicate(Main *bmain, const Object *ob, const int dupflag) case OB_ARMATURE: if (dupflag != 0) { DEG_id_tag_update(&obn->id, ID_RECALC_GEOMETRY); - if (obn->pose) + if (obn->pose) { BKE_pose_tag_recalc(bmain, obn->pose); + } if (dupflag & USER_DUP_ARM) { ID_NEW_REMAP_US2(obn->data) else @@ -1625,7 +1651,7 @@ Object *BKE_object_duplicate(Main *bmain, const Object *ob, const int dupflag) } break; case OB_LIGHTPROBE: - if (dupflag != 0) { + if (dupflag & USER_DUP_LIGHTPROBE) { ID_NEW_REMAP_US2(obn->data) else { @@ -1647,7 +1673,7 @@ Object *BKE_object_duplicate(Main *bmain, const Object *ob, const int dupflag) } break; case OB_GPENCIL: - if (dupflag != 0) { + if (dupflag & USER_DUP_GPENCIL) { ID_NEW_REMAP_US2(obn->data) else { @@ -1713,7 +1739,8 @@ void BKE_object_make_local_ex(Main *bmain, /* - only lib users: do nothing (unless force_local is set) * - only local users: set flag * - mixed: make copy - * In case we make a whole lib's content local, we always want to localize, and we skip remapping (done later). + * In case we make a whole lib's content local, + * we always want to localize, and we skip remapping (done later). */ if (!ID_IS_LINKED(ob)) { @@ -1779,8 +1806,9 @@ static void armature_set_id_extern(Object *ob) unsigned int lay = arm->layer_protected; for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) { - if (!(pchan->bone->layer & lay)) + if (!(pchan->bone->layer & lay)) { id_lib_extern((ID *)pchan->custom); + } } } @@ -1790,8 +1818,9 @@ void BKE_object_copy_proxy_drivers(Object *ob, Object *target) FCurve *fcu; /* add new animdata block */ - if (!ob->adt) + if (!ob->adt) { ob->adt = BKE_animdata_add_id(&ob->id); + } /* make a copy of all the drivers (for now), then correct any links that need fixing */ free_fcurves(&ob->adt->drivers); @@ -1805,14 +1834,16 @@ void BKE_object_copy_proxy_drivers(Object *ob, Object *target) /* all drivers */ DRIVER_TARGETS_LOOPER_BEGIN (dvar) { if (dtar->id) { - if ((Object *)dtar->id == target) + if ((Object *)dtar->id == target) { dtar->id = (ID *)ob; + } else { /* only on local objects because this causes indirect links * 'a -> b -> c', blend to point directly to a.blend * when a.blend has a proxy thats linked into c.blend */ - if (!ID_IS_LINKED(ob)) + if (!ID_IS_LINKED(ob)) { id_lib_extern((ID *)dtar->id); + } } } } @@ -1822,10 +1853,12 @@ void BKE_object_copy_proxy_drivers(Object *ob, Object *target) } } -/* proxy rule: lib_object->proxy_from == the one we borrow from, set temporally while object_update */ -/* local_object->proxy == pointer to library object, saved in files and read */ -/* local_object->proxy_group == pointer to collection dupli-object, saved in files and read */ - +/** + * Proxy rule: + * - lib_object->proxy_from == the one we borrow from, set temporally while object_update. + * - local_object->proxy == pointer to library object, saved in files and read. + * - local_object->proxy_group == pointer to collection dupli-object, saved in files and read. + */ void BKE_object_make_proxy(Main *bmain, Object *ob, Object *target, Object *cob) { /* paranoia checks */ @@ -1879,10 +1912,12 @@ void BKE_object_make_proxy(Main *bmain, Object *ob, Object *target, Object *cob) /* copy material and index information */ ob->actcol = ob->totcol = 0; - if (ob->mat) + if (ob->mat) { MEM_freeN(ob->mat); - if (ob->matbits) + } + if (ob->matbits) { MEM_freeN(ob->matbits); + } ob->mat = NULL; ob->matbits = NULL; if ((target->totcol) && (target->mat) && OB_TYPE_SUPPORT_MATERIAL(ob->type)) { @@ -1981,7 +2016,7 @@ void BKE_object_scale_to_mat3(Object *ob, float mat[3][3]) size_to_mat3(mat, vec); } -void BKE_object_rot_to_mat3(Object *ob, float mat[3][3], bool use_drot) +void BKE_object_rot_to_mat3(const Object *ob, float mat[3][3], bool use_drot) { float rmat[3][3], dmat[3][3]; @@ -1991,7 +2026,8 @@ void BKE_object_rot_to_mat3(Object *ob, float mat[3][3], bool use_drot) /* rotations may either be quats, eulers (with various rotation orders), or axis-angle */ if (ob->rotmode > 0) { - /* euler rotations (will cause gimble lock, but this can be alleviated a bit with rotation orders) */ + /* Euler rotations + * (will cause gimble lock, but this can be alleviated a bit with rotation orders). */ eulO_to_mat3(rmat, ob->rot, ob->rotmode); eulO_to_mat3(dmat, ob->drot, ob->rotmode); } @@ -2012,10 +2048,12 @@ void BKE_object_rot_to_mat3(Object *ob, float mat[3][3], bool use_drot) } /* combine these rotations */ - if (use_drot) + if (use_drot) { mul_m3_m3m3(mat, dmat, rmat); - else + } + else { copy_m3_m3(mat, rmat); + } } void BKE_object_mat3_to_rot(Object *ob, float mat[3][3], bool use_compat) @@ -2055,10 +2093,12 @@ void BKE_object_mat3_to_rot(Object *ob, float mat[3][3], bool use_compat) mul_qt_qtqt(quat, dquat, quat); /* end drot correction */ - if (use_compat) + if (use_compat) { quat_to_compatible_eulO(ob->rot, ob->rot, ob->rotmode, quat); - else + } + else { quat_to_eulO(ob->rot, ob->rotmode, quat); + } break; } } @@ -2214,11 +2254,11 @@ static bool ob_parcurve(Object *ob, Object *par, float mat[4][4]) return false; } - /* ctime is now a proper var setting of Curve which gets set by Animato like any other var that's animated, - * but this will only work if it actually is animated... + /* ctime is now a proper var setting of Curve which gets set by Animato like any other var + * that's animated, but this will only work if it actually is animated. * - * we divide the curvetime calculated in the previous step by the length of the path, to get a time - * factor, which then gets clamped to lie within 0.0 - 1.0 range + * We divide the curvetime calculated in the previous step by the length of the path, + * to get a time factor, which then gets clamped to lie within 0.0 - 1.0 range. */ if (cu->pathlen) { ctime = cu->ctime / cu->pathlen; @@ -2375,8 +2415,9 @@ static void give_parvert(Object *par, int nr, float vec[3]) float(*co)[3] = dl ? (float(*)[3])dl->verts : NULL; int tot; - if (latt->editlatt) + if (latt->editlatt) { latt = latt->editlatt->latt; + } tot = latt->pntsu * latt->pntsv * latt->pntsw; @@ -2431,10 +2472,12 @@ void BKE_object_get_parent_matrix(Object *ob, Object *par, float parentmat[4][4] } } - if (ok) + if (ok) { mul_m4_m4m4(parentmat, par->obmat, tmat); - else + } + else { copy_m4_m4(parentmat, par->obmat); + } break; case PARBONE: @@ -2460,7 +2503,8 @@ void BKE_object_get_parent_matrix(Object *ob, Object *par, float parentmat[4][4] } /** - * \param r_originmat: Optional matrix that stores the space the object is in (without its own matrix applied) + * \param r_originmat: Optional matrix that stores the space the object is in + * (without its own matrix applied) */ static void solve_parenting( Object *ob, Object *par, float obmat[4][4], float r_originmat[3][3], const bool set_origin) @@ -2525,10 +2569,12 @@ static void object_where_is_calc_ex(Depsgraph *depsgraph, } /* set negative scale flag in object */ - if (is_negative_m4(ob->obmat)) + if (is_negative_m4(ob->obmat)) { ob->transflag |= OB_NEG_SCALE; - else + } + else { ob->transflag &= ~OB_NEG_SCALE; + } } void BKE_object_where_is_calc_time(Depsgraph *depsgraph, Scene *scene, Object *ob, float ctime) @@ -2581,7 +2627,8 @@ void BKE_object_workob_calc_parent(Depsgraph *depsgraph, Scene *scene, Object *o unit_m4(workob->parentinv); unit_m4(workob->constinv); - /* Since this is used while calculating parenting, at this moment ob_eval->parent is still NULL. */ + /* Since this is used while calculating parenting, + * at this moment ob_eval->parent is still NULL. */ workob->parent = DEG_get_evaluated_object(depsgraph, ob->parent); workob->trackflag = ob->trackflag; @@ -2603,8 +2650,10 @@ void BKE_object_workob_calc_parent(Depsgraph *depsgraph, Scene *scene, Object *o * Applies the global transformation \a mat to the \a ob using a relative parent space if supplied. * * \param mat: the global transformation mat that the object should be set object to. - * \param parent: the parent space in which this object will be set relative to (should probably always be parent_eval). - * \param use_compat: true to ensure that rotations are set using the min difference between the old and new orientation. + * \param parent: the parent space in which this object will be set relative to + * (should probably always be parent_eval). + * \param use_compat: true to ensure that rotations are set using the + * min difference between the old and new orientation. */ void BKE_object_apply_mat4_ex( Object *ob, float mat[4][4], Object *parent, float parentinv[4][4], const bool use_compat) @@ -2633,12 +2682,15 @@ void BKE_object_apply_mat4_ex( sub_v3_v3(ob->loc, ob->dloc); - if (ob->dscale[0] != 0.0f) + if (ob->dscale[0] != 0.0f) { ob->scale[0] /= ob->dscale[0]; - if (ob->dscale[1] != 0.0f) + } + if (ob->dscale[1] != 0.0f) { ob->scale[1] /= ob->dscale[1]; - if (ob->dscale[2] != 0.0f) + } + if (ob->dscale[2] != 0.0f) { ob->scale[2] /= ob->dscale[2]; + } /* BKE_object_mat3_to_rot handles delta rotations */ } @@ -2735,10 +2787,12 @@ void BKE_object_boundbox_flag(Object *ob, int flag, const bool set) { BoundBox *bb = BKE_object_boundbox_get(ob); if (bb) { - if (set) + if (set) { bb->flag |= flag; - else + } + else { bb->flag &= ~flag; + } } } @@ -3108,10 +3162,12 @@ void BKE_object_tfm_restore(Object *ob, void *obtfm_pt) bool BKE_object_parent_loop_check(const Object *par, const Object *ob) { /* test if 'ob' is a parent somewhere in par's parents */ - if (par == NULL) + if (par == NULL) { return false; - if (ob == par) + } + if (ob == par) { return true; + } return BKE_object_parent_loop_check(par->parent, ob); } @@ -3137,14 +3193,19 @@ static void object_handle_update_proxy(Depsgraph *depsgraph, } } -/* proxy rule: lib_object->proxy_from == the one we borrow from, only set temporal and cleared here */ -/* local_object->proxy == pointer to library object, saved in files and read */ - -/* function below is polluted with proxy exceptions, cleanup will follow! */ - -/* the main object update call, for object matrix, constraints, keys and displist (modifiers) */ -/* requires flags to be set! */ -/* Ideally we shouldn't have to pass the rigid body world, but need bigger restructuring to avoid id */ +/** + * Proxy rule: + * - lib_object->proxy_from == the one we borrow from, only set temporal and cleared here. + * - local_object->proxy == pointer to library object, saved in files and read. + * + * Function below is polluted with proxy exceptions, cleanup will follow! + * + * The main object update call, for object matrix, constraints, keys and displist (modifiers) + * requires flags to be set! + * + * Ideally we shouldn't have to pass the rigid body world, + * but need bigger restructuring to avoid id. + */ void BKE_object_handle_update_ex(Depsgraph *depsgraph, Scene *scene, Object *ob, @@ -3244,8 +3305,9 @@ void BKE_object_sculpt_modifiers_changed(Object *ob) BKE_pbvh_search_gather(ss->pbvh, NULL, NULL, &nodes, &totnode); - for (n = 0; n < totnode; n++) + for (n = 0; n < totnode; n++) { BKE_pbvh_node_mark_update(nodes[n]); + } MEM_freeN(nodes); } @@ -3256,8 +3318,9 @@ int BKE_object_obdata_texspace_get( Object *ob, short **r_texflag, float **r_loc, float **r_size, float **r_rot) { - if (ob->data == NULL) + if (ob->data == NULL) { return 0; + } switch (GS(((ID *)ob->data)->name)) { case ID_ME: { @@ -3269,26 +3332,34 @@ int BKE_object_obdata_texspace_get( if (cu->bb == NULL || (cu->bb->flag & BOUNDBOX_DIRTY)) { BKE_curve_texspace_calc(cu); } - if (r_texflag) + if (r_texflag) { *r_texflag = &cu->texflag; - if (r_loc) + } + if (r_loc) { *r_loc = cu->loc; - if (r_size) + } + if (r_size) { *r_size = cu->size; - if (r_rot) + } + if (r_rot) { *r_rot = cu->rot; + } break; } case ID_MB: { MetaBall *mb = ob->data; - if (r_texflag) + if (r_texflag) { *r_texflag = &mb->texflag; - if (r_loc) + } + if (r_loc) { *r_loc = mb->loc; - if (r_size) + } + if (r_size) { *r_size = mb->size; - if (r_rot) + } + if (r_rot) { *r_rot = mb->rot; + } break; } default: @@ -3363,10 +3434,12 @@ Mesh *BKE_object_get_original_mesh(Object *object) static int pc_cmp(const void *a, const void *b) { const LinkData *ad = a, *bd = b; - if (POINTER_AS_INT(ad->data) > POINTER_AS_INT(bd->data)) + if (POINTER_AS_INT(ad->data) > POINTER_AS_INT(bd->data)) { return 1; - else + } + else { return 0; + } } int BKE_object_insert_ptcache(Object *ob) @@ -3379,8 +3452,9 @@ int BKE_object_insert_ptcache(Object *ob) for (link = ob->pc_ids.first, i = 0; link; link = link->next, i++) { int index = POINTER_AS_INT(link->data); - if (i < index) + if (i < index) { break; + } } link = MEM_callocN(sizeof(LinkData), "PCLink"); @@ -3395,13 +3469,15 @@ static int pc_findindex(ListBase *listbase, int index) LinkData *link = NULL; int number = 0; - if (listbase == NULL) + if (listbase == NULL) { return -1; + } link = listbase->first; while (link) { - if (POINTER_AS_INT(link->data) == index) + if (POINTER_AS_INT(link->data) == index) { return number; + } number++; link = link->next; @@ -3667,12 +3743,14 @@ int BKE_object_is_modified(Scene *scene, Object *ob) md && (flag != (eModifierMode_Render | eModifierMode_Realtime)); md = md->next) { if ((flag & eModifierMode_Render) == 0 && - modifier_isEnabled(scene, md, eModifierMode_Render)) + modifier_isEnabled(scene, md, eModifierMode_Render)) { flag |= eModifierMode_Render; + } if ((flag & eModifierMode_Realtime) == 0 && - modifier_isEnabled(scene, md, eModifierMode_Realtime)) + modifier_isEnabled(scene, md, eModifierMode_Realtime)) { flag |= eModifierMode_Realtime; + } } } @@ -3810,12 +3888,14 @@ int BKE_object_is_deform_modified(Scene *scene, Object *ob) } if (can_deform) { - if (!(flag & eModifierMode_Render) && modifier_isEnabled(scene, md, eModifierMode_Render)) + if (!(flag & eModifierMode_Render) && modifier_isEnabled(scene, md, eModifierMode_Render)) { flag |= eModifierMode_Render; + } if (!(flag & eModifierMode_Realtime) && - modifier_isEnabled(scene, md, eModifierMode_Realtime)) + modifier_isEnabled(scene, md, eModifierMode_Realtime)) { flag |= eModifierMode_Realtime; + } } } @@ -3828,11 +3908,12 @@ bool BKE_object_is_animated(Scene *scene, Object *ob) ModifierData *md; VirtualModifierData virtualModifierData; - for (md = modifiers_getVirtualModifierList(ob, &virtualModifierData); md; md = md->next) + for (md = modifiers_getVirtualModifierList(ob, &virtualModifierData); md; md = md->next) { if (modifier_dependsOnTime(md) && (modifier_isEnabled(scene, md, eModifierMode_Realtime) || modifier_isEnabled(scene, md, eModifierMode_Render))) { return true; } + } return false; } @@ -3855,8 +3936,9 @@ MovieClip *BKE_object_movieclip_get(Scene *scene, Object *ob, bool use_default) while (con) { if (con->type == CONSTRAINT_TYPE_CAMERASOLVER) { - if (scon == NULL || (scon->flag & CONSTRAINT_OFF)) + if (scon == NULL || (scon->flag & CONSTRAINT_OFF)) { scon = con; + } } con = con->next; @@ -3864,10 +3946,12 @@ MovieClip *BKE_object_movieclip_get(Scene *scene, Object *ob, bool use_default) if (scon) { bCameraSolverConstraint *solver = scon->data; - if ((solver->flag & CAMERASOLVER_ACTIVECLIP) == 0) + if ((solver->flag & CAMERASOLVER_ACTIVECLIP) == 0) { clip = solver->clip; - else + } + else { clip = scene->clip; + } } return clip; @@ -3886,7 +3970,6 @@ void BKE_object_runtime_reset_on_copy(Object *object, const int UNUSED(flag)) runtime->mesh_deform_eval = NULL; runtime->curve_cache = NULL; runtime->gpencil_cache = NULL; - runtime->cached_bbone_deformation = NULL; } /* @@ -3954,8 +4037,9 @@ LinkNode *BKE_object_relational_superset(struct ViewLayer *view_layer, (objectSet == OB_SET_VISIBLE && BASE_EDITABLE(((View3D *)NULL), base))) { Object *ob = base->object; - if (obrel_list_test(ob)) + if (obrel_list_test(ob)) { obrel_list_add(&links, ob); + } /* parent relationship */ if (includeFilter & (OB_REL_PARENT | OB_REL_PARENT_RECURSIVE)) { @@ -4176,8 +4260,9 @@ bool BKE_object_modifier_use_time(Object *ob, ModifierData *md) /* action - check for F-Curves with paths containing 'modifiers[' */ if (adt->action) { for (fcu = (FCurve *)adt->action->curves.first; fcu != NULL; fcu = (FCurve *)fcu->next) { - if (fcu->rna_path && strstr(fcu->rna_path, pattern)) + if (fcu->rna_path && strstr(fcu->rna_path, pattern)) { return true; + } } } @@ -4188,8 +4273,9 @@ bool BKE_object_modifier_use_time(Object *ob, ModifierData *md) * by the RNA updates cache introduced in r.38649 */ for (fcu = (FCurve *)adt->drivers.first; fcu != NULL; fcu = (FCurve *)fcu->next) { - if (fcu->rna_path && strstr(fcu->rna_path, pattern)) + if (fcu->rna_path && strstr(fcu->rna_path, pattern)) { return true; + } } /* XXX: also, should check NLA strips, though for now assume that nobody uses @@ -4252,15 +4338,17 @@ bool BKE_object_shaderfx_use_time(Object *ob, ShaderFxData *fx) /* action - check for F-Curves with paths containing string[' */ if (adt->action) { for (fcu = adt->action->curves.first; fcu != NULL; fcu = fcu->next) { - if (fcu->rna_path && strstr(fcu->rna_path, pattern)) + if (fcu->rna_path && strstr(fcu->rna_path, pattern)) { return true; + } } } /* This here allows properties to get driven and still update properly */ for (fcu = adt->drivers.first; fcu != NULL; fcu = fcu->next) { - if (fcu->rna_path && strstr(fcu->rna_path, pattern)) + if (fcu->rna_path && strstr(fcu->rna_path, pattern)) { return true; + } } } @@ -4276,10 +4364,12 @@ static void object_cacheIgnoreClear(Object *ob, int state) for (pid = pidlist.first; pid; pid = pid->next) { if (pid->cache) { - if (state) + if (state) { pid->cache->flag |= PTCACHE_IGNORE_CLEAR; - else + } + else { pid->cache->flag &= ~PTCACHE_IGNORE_CLEAR; + } } } @@ -4304,31 +4394,36 @@ bool BKE_object_modifier_update_subframe(Depsgraph *depsgraph, DynamicPaintModifierData *pmd = (DynamicPaintModifierData *)md; /* if other is dynamic paint canvas, don't update */ - if (pmd && pmd->canvas) + if (pmd && pmd->canvas) { return true; + } } else if (type == eModifierType_Smoke) { SmokeModifierData *smd = (SmokeModifierData *)md; - if (smd && (smd->type & MOD_SMOKE_TYPE_DOMAIN) != 0) + if (smd && (smd->type & MOD_SMOKE_TYPE_DOMAIN) != 0) { return true; + } } /* if object has parents, update them too */ if (parent_recursion) { int recursion = parent_recursion - 1; bool no_update = false; - if (ob->parent) + if (ob->parent) { no_update |= BKE_object_modifier_update_subframe( depsgraph, scene, ob->parent, 0, recursion, frame, type); - if (ob->track) + } + if (ob->track) { no_update |= BKE_object_modifier_update_subframe( depsgraph, scene, ob->track, 0, recursion, frame, type); + } /* skip subframe if object is parented * to vertex of a dynamic paint canvas */ - if (no_update && (ob->partype == PARVERT1 || ob->partype == PARVERT3)) + if (no_update && (ob->partype == PARVERT1 || ob->partype == PARVERT3)) { return false; + } /* also update constraint targets */ for (con = ob->constraints.first; con; con = con->next) { @@ -4339,13 +4434,15 @@ bool BKE_object_modifier_update_subframe(Depsgraph *depsgraph, bConstraintTarget *ct; cti->get_constraint_targets(con, &targets); for (ct = targets.first; ct; ct = ct->next) { - if (ct->tar) + if (ct->tar) { BKE_object_modifier_update_subframe( depsgraph, scene, ct->tar, 0, recursion, frame, type); + } } /* free temp targets */ - if (cti->flush_constraint_targets) + if (cti->flush_constraint_targets) { cti->flush_constraint_targets(con, &targets, 0); + } } } } diff --git a/source/blender/blenkernel/intern/object_deform.c b/source/blender/blenkernel/intern/object_deform.c index be3dbbb1c71..0ce6094771c 100644 --- a/source/blender/blenkernel/intern/object_deform.c +++ b/source/blender/blenkernel/intern/object_deform.c @@ -116,8 +116,9 @@ bDeformGroup *BKE_object_defgroup_add_name(Object *ob, const char *name) { bDeformGroup *defgroup; - if (!ob || !OB_TYPE_SUPPORT_VGROUP(ob->type)) + if (!ob || !OB_TYPE_SUPPORT_VGROUP(ob->type)) { return NULL; + } defgroup = BKE_defgroup_new(ob, name); @@ -283,8 +284,9 @@ static void object_defgroup_remove_common(Object *ob, bDeformGroup *dg, const in BLI_freelinkN(&ob->defbase, dg); /* Update the active deform index if necessary */ - if (ob->actdef > def_nr) + if (ob->actdef > def_nr) { ob->actdef--; + } /* remove all dverts */ if (BLI_listbase_is_empty(&ob->defbase)) { @@ -345,7 +347,8 @@ static void object_defgroup_remove_edit_mode(Object *ob, bDeformGroup *dg) BLI_assert(def_nr != -1); - /* Make sure that no verts are using this group - if none were removed, we can skip next per-vert update. */ + /* Make sure that no verts are using this group - if none were removed, + * we can skip next per-vert update. */ if (!BKE_object_defgroup_clear(ob, dg, false)) { /* Nothing to do. */ } @@ -401,10 +404,12 @@ void BKE_object_defgroup_remove(Object *ob, bDeformGroup *defgroup) BKE_gpencil_vgroup_remove(ob, defgroup); } else { - if (BKE_object_is_in_editmode_vgroup(ob)) + if (BKE_object_is_in_editmode_vgroup(ob)) { object_defgroup_remove_edit_mode(ob, defgroup); - else + } + else { object_defgroup_remove_object_mode(ob, defgroup); + } BKE_object_batch_cache_dirty_tag(ob); } @@ -424,10 +429,12 @@ void BKE_object_defgroup_remove_all_ex(struct Object *ob, bool only_unlocked) bDeformGroup *next_dg = dg->next; if (!only_unlocked || (dg->flag & DG_LOCK_WEIGHT) == 0) { - if (edit_mode) + if (edit_mode) { object_defgroup_remove_edit_mode(ob, dg); - else + } + else { object_defgroup_remove_object_mode(ob, dg); + } } dg = next_dg; @@ -571,7 +578,7 @@ bool *BKE_object_defgroup_lock_flags_get(Object *ob, const int defbase_tot) { bool is_locked = false; int i; - //int defbase_tot = BLI_listbase_count(&ob->defbase); + // int defbase_tot = BLI_listbase_count(&ob->defbase); bool *lock_flags = MEM_mallocN(defbase_tot * sizeof(bool), "defflags"); bDeformGroup *defgroup; @@ -595,7 +602,7 @@ bool *BKE_object_defgroup_validmap_get(Object *ob, const int defbase_tot) bool *defgroup_validmap; GHash *gh; int i, step1 = 1; - //int defbase_tot = BLI_listbase_count(&ob->defbase); + // int defbase_tot = BLI_listbase_count(&ob->defbase); VirtualModifierData virtualModifierData; if (BLI_listbase_is_empty(&ob->defbase)) { @@ -615,8 +622,9 @@ bool *BKE_object_defgroup_validmap_get(Object *ob, const int defbase_tot) for (md = ob->modifiers.first; md; md = !md->next && step1 ? (step1 = 0), modifiers_getVirtualModifierList(ob, &virtualModifierData) : md->next) { - if (!(md->mode & (eModifierMode_Realtime | eModifierMode_Virtual))) + if (!(md->mode & (eModifierMode_Realtime | eModifierMode_Virtual))) { continue; + } if (md->type == eModifierType_Armature) { ArmatureModifierData *amd = (ArmatureModifierData *)md; @@ -627,8 +635,9 @@ bool *BKE_object_defgroup_validmap_get(Object *ob, const int defbase_tot) for (chan = pose->chanbase.first; chan; chan = chan->next) { void **val_p; - if (chan->bone->flag & BONE_NO_DEFORM) + if (chan->bone->flag & BONE_NO_DEFORM) { continue; + } val_p = BLI_ghash_lookup_p(gh, chan->name); if (val_p) { @@ -684,7 +693,9 @@ bool *BKE_object_defgroup_selected_get(Object *ob, int defbase_tot, int *r_dg_fl return dg_selection; } -/* Marks mirror vgroups in output and counts them. Output and counter assumed to be already initialized. +/** + * Marks mirror vgroups in output and counts them. + * Output and counter assumed to be already initialized. * Designed to be usable after BKE_object_defgroup_selected_get to extend selection to mirror. */ void BKE_object_defgroup_mirror_selection(struct Object *ob, diff --git a/source/blender/blenkernel/intern/object_dupli.c b/source/blender/blenkernel/intern/object_dupli.c index 2544bb6a8f0..8080834a53a 100644 --- a/source/blender/blenkernel/intern/object_dupli.c +++ b/source/blender/blenkernel/intern/object_dupli.c @@ -66,9 +66,10 @@ typedef struct DupliContext { Depsgraph *depsgraph; - Collection - *collection; /* XXX child objects are selected from this group if set, could be nicer */ - Object *obedit; /* Only to check if the object is in edit-mode. */ + /** XXX child objects are selected from this group if set, could be nicer. */ + Collection *collection; + /** Only to check if the object is in edit-mode. */ + Object *obedit; Scene *scene; ViewLayer *view_layer; @@ -80,7 +81,7 @@ typedef struct DupliContext { const struct DupliGenerator *gen; - /* result containers */ + /** Result containers. */ ListBase *duplilist; /* legacy doubly-linked list */ } DupliContext; @@ -102,10 +103,12 @@ static void init_context( r_ctx->object = ob; r_ctx->obedit = OBEDIT_FROM_OBACT(ob); - if (space_mat) + if (space_mat) { copy_m4_m4(r_ctx->space_mat, space_mat); - else + } + else { unit_m4(r_ctx->space_mat); + } r_ctx->level = 0; r_ctx->gen = get_dupli_generator(r_ctx); @@ -119,13 +122,16 @@ static void copy_dupli_context( { *r_ctx = *ctx; - /* XXX annoying, previously was done by passing an ID* argument, this at least is more explicit */ - if (ctx->gen->type == OB_DUPLICOLLECTION) + /* XXX annoying, previously was done by passing an ID* argument, + * this at least is more explicit. */ + if (ctx->gen->type == OB_DUPLICOLLECTION) { r_ctx->collection = ctx->object->instance_collection; + } r_ctx->object = ob; - if (mat) + if (mat) { mul_m4_m4m4(r_ctx->space_mat, (float(*)[4])ctx->space_mat, mat); + } r_ctx->persistent_id[r_ctx->level] = index; ++r_ctx->level; @@ -158,17 +164,20 @@ static DupliObject *make_dupli(const DupliContext *ctx, Object *ob, float mat[4] * dupli object between frames, which is needed for motion blur. last level * goes first in the array. */ dob->persistent_id[0] = index; - for (i = 1; i < ctx->level + 1; i++) + for (i = 1; i < ctx->level + 1; i++) { dob->persistent_id[i] = ctx->persistent_id[ctx->level - i]; + } /* fill rest of values with INT_MAX which index will never have as value */ - for (; i < MAX_DUPLI_RECUR; i++) + for (; i < MAX_DUPLI_RECUR; i++) { dob->persistent_id[i] = INT_MAX; + } /* metaballs never draw in duplis, they are instead merged into one by the basis * mball outside of the group. this does mean that if that mball is not in the * scene, they will not show up at all, limitation that should be solved once. */ - if (ob->type == OB_MBALL) + if (ob->type == OB_MBALL) { dob->no_draw = true; + } /* random number */ /* the logic here is designed to match Cycles */ @@ -216,8 +225,9 @@ static bool is_child(const Object *ob, const Object *parent) { const Object *ob_parent = ob->parent; while (ob_parent) { - if (ob_parent == parent) + if (ob_parent == parent) { return true; + } ob_parent = ob_parent->parent; } return false; @@ -256,8 +266,9 @@ static void make_child_duplis(const DupliContext *ctx, copy_dupli_context(&pctx, ctx, ctx->object, NULL, baseid); /* metaballs have a different dupli handling */ - if (ob->type != OB_MBALL) + if (ob->type != OB_MBALL) { ob->flag |= OB_DONE; /* doesn't render */ + } make_child_duplis_cb(&pctx, userdata, ob); } @@ -274,8 +285,9 @@ static void make_duplis_collection(const DupliContext *ctx) Collection *collection; float collection_mat[4][4]; - if (ob->instance_collection == NULL) + if (ob->instance_collection == NULL) { return; + } collection = ob->instance_collection; /* combine collection offset and obmat */ @@ -337,8 +349,9 @@ static void get_duplivert_transform(const float co[3], nor_f[2] = (float)-no[2]; vec_to_quat(quat, nor_f, axis, upflag); } - else + else { unit_qt(quat); + } loc_quat_size_to_mat4(mat, co, quat, size); } @@ -366,8 +379,9 @@ static void vertex_dupli(const VertexDupliData *vdd, dob = make_dupli(vdd->ctx, vdd->inst_ob, obmat, index); - if (vdd->orco) + if (vdd->orco) { copy_v3_v3(dob->orco, vdd->orco[index]); + } /* recursion */ make_recursive_duplis(vdd->ctx, vdd->inst_ob, space_mat, index); @@ -482,8 +496,9 @@ static void make_duplis_font(const DupliContext *ctx) bool text_free = false; /* font dupliverts not supported inside collections */ - if (ctx->collection) + if (ctx->collection) { return; + } copy_m4_m4(pmat, par->obmat); @@ -511,7 +526,8 @@ static void make_duplis_font(const DupliContext *ctx) for (a = 0; a < text_len; a++, ct++) { /* XXX That G.main is *really* ugly, but not sure what to do here... - * Definitively don't think it would be safe to put back Main *bmain pointer in DupliContext as done in 2.7x? */ + * Definitively don't think it would be safe to put back Main *bmain pointer + * in DupliContext as done in 2.7x? */ ob = find_family_object(G.main, cu->family, family_len, (unsigned int)text[a], family_gh); if (ob) { vec[0] = fsize * (ct->xof - xof); @@ -584,8 +600,9 @@ static void get_dupliface_transform( float area = BKE_mesh_calc_poly_area(mpoly, mloop, mvert); scale = sqrtf(area) * scale_fac; } - else + else { scale = 1.0f; + } size[0] = size[1] = size[2] = scale; loc_quat_size_to_mat4(mat, loc, quat, size); @@ -611,8 +628,9 @@ static void make_child_duplis_faces(const DupliContext *ctx, void *userdata, Obj MLoop *loopstart = mloop + mp->loopstart; float space_mat[4][4], obmat[4][4]; - if (UNLIKELY(mp->totloop < 3)) + if (UNLIKELY(mp->totloop < 3)) { continue; + } /* obmat is transform to face */ get_dupliface_transform( @@ -726,19 +744,23 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem int no_draw_flag = PARS_UNEXIST; - if (psys == NULL) + if (psys == NULL) { return; + } part = psys->part; - if (part == NULL) + if (part == NULL) { return; + } - if (!psys_check_enabled(par, psys, for_render)) + if (!psys_check_enabled(par, psys, for_render)) { return; + } - if (!for_render) + if (!for_render) { no_draw_flag |= PARS_NO_DISP; + } ctime = DEG_get_ctime( ctx->depsgraph); /* NOTE: in old animsys, used parent object's timeoffset... */ @@ -759,17 +781,20 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem /* first check for loops (particle system object used as dupli object) */ if (part->ren_as == PART_DRAW_OB) { - if (ELEM(part->instance_object, NULL, par)) + if (ELEM(part->instance_object, NULL, par)) { return; + } } else { /*PART_DRAW_GR */ - if (part->instance_collection == NULL) + if (part->instance_collection == NULL) { return; + } const ListBase dup_collection_objects = BKE_collection_object_cache_get( part->instance_collection); - if (BLI_listbase_is_empty(&dup_collection_objects)) + if (BLI_listbase_is_empty(&dup_collection_objects)) { return; + } if (BLI_findptr(&dup_collection_objects, par, offsetof(Base, object))) { return; @@ -778,10 +803,12 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem /* if we have a hair particle system, use the path cache */ if (part->type == PART_HAIR) { - if (psys->flag & PSYS_HAIR_DONE) + if (psys->flag & PSYS_HAIR_DONE) { hair = (totchild == 0 || psys->childcache) && psys->pathcache; - if (!hair) + } + if (!hair) { return; + } /* we use cache, update totchild according to cached data */ totchild = psys->totchildcache; @@ -850,16 +877,19 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem ob = part->instance_object; } - if (totchild == 0 || part->draw & PART_DRAW_PARENT) + if (totchild == 0 || part->draw & PART_DRAW_PARENT) { a = 0; - else + } + else { a = totpart; + } for (pa = psys->particles; a < totpart + totchild; a++, pa++) { if (a < totpart) { /* handle parent particle */ - if (pa->flag & no_draw_flag) + if (pa->flag & no_draw_flag) { continue; + } /* pa_num = pa->num; */ /* UNUSED */ size = pa->size; @@ -881,14 +911,17 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem if (part->ren_as == PART_DRAW_GR) { /* prevent divide by zero below [#28336] */ - if (totcollection == 0) + if (totcollection == 0) { continue; + } /* for collections, pick the object based on settings */ - if (part->draw & PART_DRAW_RAND_GR) + if (part->draw & PART_DRAW_RAND_GR) { b = BLI_rng_get_int(rng) % totcollection; - else + } + else { b = a % totcollection; + } ob = oblist[b]; } @@ -957,7 +990,8 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem copy_v3_v3(vec, obmat[3]); zero_v3(obmat[3]); - /* particle rotation uses x-axis as the aligned axis, so pre-rotate the object accordingly */ + /* Particle rotation uses x-axis as the aligned axis, + * so pre-rotate the object accordingly. */ if ((part->draw & PART_DRAW_ROTATE_OB) == 0) { float xvec[3], q[4], size_mat[4][4], original_size[3]; @@ -971,8 +1005,9 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem obmat[3][3] = 1.0f; /* add scaling if requested */ - if ((part->draw & PART_DRAW_NO_SCALE_OB) == 0) + if ((part->draw & PART_DRAW_NO_SCALE_OB) == 0) { mul_m4_m4m4(obmat, obmat, size_mat); + } } else if (part->draw & PART_DRAW_NO_SCALE_OB) { /* remove scaling */ @@ -990,8 +1025,9 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem copy_m4_m4(mat, tmat); - if (part->draw & PART_DRAW_GLOBAL_OB) + if (part->draw & PART_DRAW_GLOBAL_OB) { add_v3_v3v3(mat[3], mat[3], vec); + } dob = make_dupli(ctx, ob, mat, a); dob->particle_system = psys; @@ -1003,8 +1039,9 @@ static void make_duplis_particle_system(const DupliContext *ctx, ParticleSystem } /* clean up */ - if (oblist) + if (oblist) { MEM_freeN(oblist); + } if (psys->lattice_deform_data) { end_latt_deform(psys->lattice_deform_data); @@ -1039,13 +1076,15 @@ static const DupliGenerator *get_dupli_generator(const DupliContext *ctx) int transflag = ctx->object->transflag; int restrictflag = ctx->object->restrictflag; - if ((transflag & OB_DUPLI) == 0) + if ((transflag & OB_DUPLI) == 0) { return NULL; + } /* Should the dupli's be generated for this object? - Respect restrict flags */ if (DEG_get_mode(ctx->depsgraph) == DAG_EVAL_RENDER ? (restrictflag & OB_RESTRICT_RENDER) : - (restrictflag & OB_RESTRICT_VIEW)) + (restrictflag & OB_RESTRICT_VIEW)) { return NULL; + } if (transflag & OB_DUPLIPARTS) { return &gen_dupli_particles; @@ -1059,8 +1098,9 @@ static const DupliGenerator *get_dupli_generator(const DupliContext *ctx) } } else if (transflag & OB_DUPLIFACES) { - if (ctx->object->type == OB_MESH) + if (ctx->object->type == OB_MESH) { return &gen_dupli_faces; + } } else if (transflag & OB_DUPLICOLLECTION) { return &gen_dupli_collection; diff --git a/source/blender/blenkernel/intern/object_facemap.c b/source/blender/blenkernel/intern/object_facemap.c index 4548a6d6bd1..b3ebe9b5ffa 100644 --- a/source/blender/blenkernel/intern/object_facemap.c +++ b/source/blender/blenkernel/intern/object_facemap.c @@ -68,8 +68,9 @@ static bFaceMap *fmap_duplicate(bFaceMap *infmap) { bFaceMap *outfmap; - if (!infmap) + if (!infmap) { return NULL; + } outfmap = MEM_callocN(sizeof(bFaceMap), "copy facemap"); @@ -109,8 +110,9 @@ bFaceMap *BKE_object_facemap_add_name(Object *ob, const char *name) { bFaceMap *fmap; - if (!ob || ob->type != OB_MESH) + if (!ob || ob->type != OB_MESH) { return NULL; + } fmap = MEM_callocN(sizeof(bFaceMap), __func__); @@ -151,10 +153,12 @@ static void object_fmap_remove_edit_mode(Object *ob, bFaceMap *fmap, bool do_sel map = BM_ELEM_CD_GET_VOID_P(efa, cd_fmap_offset); if (map) { - if (*map == fmap_nr) + if (*map == fmap_nr) { *map = -1; - else if (*map > fmap_nr) + } + else if (*map > fmap_nr) { *map -= 1; + } } } } @@ -170,8 +174,9 @@ static void object_fmap_remove_edit_mode(Object *ob, bFaceMap *fmap, bool do_sel } } - if (ob->actfmap == BLI_listbase_count(&ob->fmaps)) + if (ob->actfmap == BLI_listbase_count(&ob->fmaps)) { ob->actfmap--; + } BLI_remlink(&ob->fmaps, fmap); MEM_freeN(fmap); @@ -192,16 +197,19 @@ static void object_fmap_remove_object_mode(Object *ob, bFaceMap *fmap, bool purg if (map) { for (i = 0; i < me->totpoly; i++) { - if (map[i] == fmap_nr) + if (map[i] == fmap_nr) { map[i] = -1; - else if (purge && map[i] > fmap_nr) + } + else if (purge && map[i] > fmap_nr) { map[i]--; + } } } } - if (ob->actfmap == BLI_listbase_count(&ob->fmaps)) + if (ob->actfmap == BLI_listbase_count(&ob->fmaps)) { ob->actfmap--; + } BLI_remlink(&ob->fmaps, fmap); MEM_freeN(fmap); @@ -210,10 +218,12 @@ static void object_fmap_remove_object_mode(Object *ob, bFaceMap *fmap, bool purg static void fmap_remove_exec(Object *ob, bFaceMap *fmap, const bool is_edit_mode, const bool purge) { - if (is_edit_mode) + if (is_edit_mode) { object_fmap_remove_edit_mode(ob, fmap, false, purge); - else + } + else { object_fmap_remove_object_mode(ob, fmap, purge); + } } void BKE_object_facemap_remove(Object *ob, bFaceMap *fmap) diff --git a/source/blender/blenkernel/intern/object_update.c b/source/blender/blenkernel/intern/object_update.c index 75c0b0b3dc0..183bc968897 100644 --- a/source/blender/blenkernel/intern/object_update.c +++ b/source/blender/blenkernel/intern/object_update.c @@ -142,10 +142,12 @@ void BKE_object_eval_transform_final(Depsgraph *depsgraph, Object *ob) * do not need to worry about relcalculating it. */ invert_m4_m4(ob->imat, ob->obmat); /* Set negative scale flag in object. */ - if (is_negative_m4(ob->obmat)) + if (is_negative_m4(ob->obmat)) { ob->transflag |= OB_NEG_SCALE; - else + } + else { ob->transflag &= ~OB_NEG_SCALE; + } } void BKE_object_handle_data_update(Depsgraph *depsgraph, Scene *scene, Object *ob) @@ -233,8 +235,9 @@ void BKE_object_handle_data_update(Depsgraph *depsgraph, Scene *scene, Object *o psys_free(ob, psys); psys = tpsys; } - else + else { psys = psys->next; + } } } BKE_object_eval_boundbox(depsgraph, ob); @@ -366,14 +369,6 @@ void BKE_object_eval_transform_all(Depsgraph *depsgraph, Scene *scene, Object *o BKE_object_eval_transform_final(depsgraph, object); } -void BKE_object_eval_update_shading(Depsgraph *depsgraph, Object *object) -{ - DEG_debug_print_eval(depsgraph, __func__, object->id.name, object); - if (object->type == OB_MESH) { - BKE_mesh_batch_cache_dirty_tag(object->data, BKE_MESH_BATCH_DIRTY_SHADING); - } -} - void BKE_object_data_select_update(Depsgraph *depsgraph, ID *object_data) { DEG_debug_print_eval(depsgraph, __func__, object_data->name, object_data); diff --git a/source/blender/blenkernel/intern/ocean.c b/source/blender/blenkernel/intern/ocean.c index f84048b502f..b5df7d5fe9b 100644 --- a/source/blender/blenkernel/intern/ocean.c +++ b/source/blender/blenkernel/intern/ocean.c @@ -116,7 +116,8 @@ typedef struct Ocean { /* two dimensional arrays of float */ double *_disp_y; /* init w sim w via plan? */ double *_N_x; /* init w sim w via plan? */ - /* all member of this array has same values, so convert this array to a float to reduce memory usage (MEM01)*/ + /* all member of this array has same values, + * so convert this array to a float to reduce memory usage (MEM01). */ /*float * _N_y; */ double _N_y; /* sim w ********* can be rearranged? */ double *_N_z; /* init w sim w via plan? */ @@ -148,9 +149,9 @@ 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 instead of logf() and sqrtf(). - */ + /* 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 + * instead of logf() and sqrtf(). */ float x; float y; float length2; @@ -295,10 +296,12 @@ void BKE_ocean_eval_uv(struct Ocean *oc, struct OceanResult *ocr, float u, float u = fmodf(u, 1.0f); v = fmodf(v, 1.0f); - if (u < 0) + if (u < 0) { u += 1.0f; - if (v < 0) + } + if (v < 0) { v += 1.0f; + } BLI_rw_mutex_lock(&oc->oceanmutex, THREAD_LOCK_READ); @@ -365,10 +368,12 @@ void BKE_ocean_eval_uv_catrom(struct Ocean *oc, struct OceanResult *ocr, float u u = fmod(u, 1.0f); v = fmod(v, 1.0f); - if (u < 0) + if (u < 0) { u += 1.0f; - if (v < 0) + } + if (v < 0) { v += 1.0f; + } BLI_rw_mutex_lock(&oc->oceanmutex, THREAD_LOCK_READ); @@ -460,9 +465,8 @@ void BKE_ocean_eval_xz_catrom(struct Ocean *oc, struct OceanResult *ocr, float x BKE_ocean_eval_uv_catrom(oc, ocr, x / oc->_Lx, z / oc->_Lz); } -/* note that this doesn't wrap properly for i, j < 0, but its not really meant for that being just a way to get - * the raw data out to save in some image format. - */ +/* note that this doesn't wrap properly for i, j < 0, but its not really meant for that being + * just a way to get the raw data out to save in some image format. */ void BKE_ocean_eval_ij(struct Ocean *oc, struct OceanResult *ocr, int i, int j) { BLI_rw_mutex_lock(&oc->oceanmutex, THREAD_LOCK_READ); @@ -515,7 +519,8 @@ static void ocean_compute_htilda(void *__restrict userdata, int j; - /* note the <= _N/2 here, see the fftw doco about the mechanics of the complex->real fft storage */ + /* note the <= _N/2 here, see the fftw doco + * about the mechanics of the complex->real fft storage. */ for (j = 0; j <= o->_N / 2; ++j) { fftw_complex exp_param1; fftw_complex exp_param2; @@ -766,11 +771,12 @@ void BKE_ocean_simulate(struct Ocean *o, float t, float scale, float chop_amount BLI_rw_mutex_lock(&o->oceanmutex, THREAD_LOCK_WRITE); - /* Note about multi-threading here: we have to run a first set of computations (htilda one) before we can run - * all others, since they all depend on it. - * So we make a first parallelized forloop run for htilda, and then pack all other computations into - * a set of parallel tasks. - * This is not optimal in all cases, but remains reasonably simple and should be OK most of the time. */ + /* Note about multi-threading here: we have to run a first set of computations (htilda one) + * before we can run all others, since they all depend on it. + * So we make a first parallelized forloop run for htilda, + * and then pack all other computations into a set of parallel tasks. + * This is not optimal in all cases, + * but remains reasonably simple and should be OK most of the time. */ /* compute a new htilda */ ParallelRangeSettings settings; @@ -813,8 +819,9 @@ static void set_height_normalize_factor(struct Ocean *oc) int i, j; - if (!oc->_do_disp_y) + if (!oc->_do_disp_y) { return; + } oc->normalize_factor = 1.0; @@ -832,8 +839,9 @@ static void set_height_normalize_factor(struct Ocean *oc) BLI_rw_mutex_unlock(&oc->oceanmutex); - if (max_h == 0.0f) + if (max_h == 0.0f) { max_h = 0.00001f; /* just in case ... */ + } res = 1.0f / (max_h); @@ -942,32 +950,40 @@ void BKE_ocean_init(struct Ocean *o, o->_kz = (float *)MEM_mallocN(o->_N * sizeof(float), "ocean_kz"); /* make this robust in the face of erroneous usage */ - if (o->_Lx == 0.0f) + if (o->_Lx == 0.0f) { o->_Lx = 0.001f; + } - if (o->_Lz == 0.0f) + if (o->_Lz == 0.0f) { o->_Lz = 0.001f; + } /* the +ve components and DC */ - for (i = 0; i <= o->_M / 2; ++i) + for (i = 0; i <= o->_M / 2; ++i) { o->_kx[i] = 2.0f * (float)M_PI * i / o->_Lx; + } /* the -ve components */ - for (i = o->_M - 1, ii = 0; i > o->_M / 2; --i, ++ii) + for (i = o->_M - 1, ii = 0; i > o->_M / 2; --i, ++ii) { o->_kx[i] = -2.0f * (float)M_PI * ii / o->_Lx; + } /* the +ve components and DC */ - for (i = 0; i <= o->_N / 2; ++i) + for (i = 0; i <= o->_N / 2; ++i) { o->_kz[i] = 2.0f * (float)M_PI * i / o->_Lz; + } /* the -ve components */ - for (i = o->_N - 1, ii = 0; i > o->_N / 2; --i, ++ii) + for (i = o->_N - 1, ii = 0; i > o->_N / 2; --i, ++ii) { o->_kz[i] = -2.0f * (float)M_PI * ii / o->_Lz; + } /* pre-calculate the k matrix */ - for (i = 0; i < o->_M; ++i) - for (j = 0; j <= o->_N / 2; ++j) + for (i = 0; i < o->_M; ++i) { + for (j = 0; j <= o->_N / 2; ++j) { o->_k[i * (1 + o->_N / 2) + j] = sqrt(o->_kx[i] * o->_kx[i] + o->_kz[j] * o->_kz[j]); + } + } /*srand(seed);*/ rng = BLI_rng_new(seed); @@ -1052,8 +1068,9 @@ void BKE_ocean_init(struct Ocean *o, void BKE_ocean_free_data(struct Ocean *oc) { - if (!oc) + if (!oc) { return; + } BLI_rw_mutex_lock(&oc->oceanmutex, THREAD_LOCK_WRITE); @@ -1097,8 +1114,9 @@ void BKE_ocean_free_data(struct Ocean *oc) BLI_thread_unlock(LOCK_FFTW); - if (oc->_fft_in) + if (oc->_fft_in) { MEM_freeN(oc->_fft_in); + } /* check that ocean data has been initialized */ if (oc->_htilda) { @@ -1115,8 +1133,9 @@ void BKE_ocean_free_data(struct Ocean *oc) void BKE_ocean_free(struct Ocean *oc) { - if (!oc) + if (!oc) { return; + } BKE_ocean_free_data(oc); BLI_rw_mutex_end(&oc->oceanmutex); @@ -1177,8 +1196,9 @@ void BKE_ocean_free_cache(struct OceanCache *och) { int i, f = 0; - if (!och) + if (!och) { return; + } if (och->ibufs_disp) { for (i = och->start, f = 0; i <= och->end; i++, f++) { @@ -1207,8 +1227,9 @@ void BKE_ocean_free_cache(struct OceanCache *och) MEM_freeN(och->ibufs_norm); } - if (och->time) + if (och->time) { MEM_freeN(och->time); + } MEM_freeN(och); } @@ -1222,10 +1243,12 @@ void BKE_ocean_cache_eval_uv( u = fmod(u, 1.0); v = fmod(v, 1.0); - if (u < 0) + if (u < 0) { u += 1.0f; - if (v < 0) + } + if (v < 0) { v += 1.0f; + } if (och->ibufs_disp[f]) { ibuf_sample(och->ibufs_disp[f], u, v, (1.0f / (float)res_x), (1.0f / (float)res_y), result); @@ -1248,10 +1271,12 @@ void BKE_ocean_cache_eval_ij(struct OceanCache *och, struct OceanResult *ocr, in const int res_x = och->resolution_x; const int res_y = och->resolution_y; - if (i < 0) + if (i < 0) { i = -i; - if (j < 0) + } + if (j < 0) { j = -j; + } i = i % res_x; j = j % res_y; @@ -1315,10 +1340,12 @@ void BKE_ocean_simulate_cache(struct OceanCache *och, int frame) f = frame - och->start; /* shift to 0 based */ /* if image is already loaded in mem, return */ - if (och->ibufs_disp[f] != NULL) + if (och->ibufs_disp[f] != NULL) { return; + } - /* use default color spaces since we know for sure cache files were saved with default settings too */ + /* Use default color spaces since we know for sure cache + * files were saved with default settings too. */ cache_filename(string, och->bakepath, och->relbase, frame, CACHE_TYPE_DISPLACE); och->ibufs_disp[f] = IMB_loadiffname(string, 0, NULL); @@ -1350,17 +1377,20 @@ void BKE_ocean_bake(struct Ocean *o, int res_x = och->resolution_x; int res_y = och->resolution_y; char string[FILE_MAX]; - //RNG *rng; + // RNG *rng; - if (!o) + if (!o) { return; + } - if (o->_do_jacobian) + if (o->_do_jacobian) { prev_foam = MEM_callocN(res_x * res_y * sizeof(float), "previous frame foam bake data"); - else + } + else { prev_foam = NULL; + } - //rng = BLI_rng_new(0); + // rng = BLI_rng_new(0); /* setup image format */ imf.imtype = R_IMF_IMTYPE_OPENEXR; @@ -1402,9 +1432,9 @@ void BKE_ocean_bake(struct Ocean *o, /* pr = pr * och->foam_fade; */ /* overall fade */ - /* remember ocean coord sys is Y up! - * break up the foam where height (Y) is low (wave valley), and X and Z displacement is greatest - */ + /* Remember ocean coord sys is Y up! + * break up the foam where height (Y) is low (wave valley), + * and X and Z displacement is greatest. */ neg_disp = ocr.disp[1] < 0.0f ? 1.0f + ocr.disp[1] : 1.0f; neg_disp = neg_disp < 0.0f ? 0.0f : neg_disp; @@ -1413,8 +1443,9 @@ void BKE_ocean_bake(struct Ocean *o, neg_eplus = ocr.Eplus[2] < 0.0f ? 1.0f + ocr.Eplus[2] : 1.0f; neg_eplus = neg_eplus < 0.0f ? 0.0f : neg_eplus; - if (pr < 1.0f) + if (pr < 1.0f) { pr *= pr; + } pr *= och->foam_fade * (0.75f + neg_eplus * 0.25f); @@ -1436,19 +1467,22 @@ void BKE_ocean_bake(struct Ocean *o, /* write the images */ cache_filename(string, och->bakepath, och->relbase, f, CACHE_TYPE_DISPLACE); - if (0 == BKE_imbuf_write(ibuf_disp, string, &imf)) + if (0 == BKE_imbuf_write(ibuf_disp, string, &imf)) { printf("Cannot save Displacement File Output to %s\n", string); + } if (o->_do_jacobian) { cache_filename(string, och->bakepath, och->relbase, f, CACHE_TYPE_FOAM); - if (0 == BKE_imbuf_write(ibuf_foam, string, &imf)) + if (0 == BKE_imbuf_write(ibuf_foam, string, &imf)) { printf("Cannot save Foam File Output to %s\n", string); + } } if (o->_do_normals) { cache_filename(string, och->bakepath, och->relbase, f, CACHE_TYPE_NORMAL); - if (0 == BKE_imbuf_write(ibuf_normal, string, &imf)) + if (0 == BKE_imbuf_write(ibuf_normal, string, &imf)) { printf("Cannot save Normal File Output to %s\n", string); + } } IMB_freeImBuf(ibuf_disp); @@ -1460,16 +1494,18 @@ void BKE_ocean_bake(struct Ocean *o, update_cb(update_cb_data, progress, &cancel); if (cancel) { - if (prev_foam) + if (prev_foam) { MEM_freeN(prev_foam); - //BLI_rng_free(rng); + } + // BLI_rng_free(rng); return; } } - //BLI_rng_free(rng); - if (prev_foam) + // BLI_rng_free(rng); + if (prev_foam) { MEM_freeN(prev_foam); + } och->baked = 1; } @@ -1563,8 +1599,9 @@ void BKE_ocean_free_data(struct Ocean *UNUSED(oc)) void BKE_ocean_free(struct Ocean *oc) { - if (!oc) + if (!oc) { return; + } MEM_freeN(oc); } @@ -1572,8 +1609,9 @@ void BKE_ocean_free(struct Ocean *oc) void BKE_ocean_free_cache(struct OceanCache *och) { - if (!och) + if (!och) { return; + } MEM_freeN(och); } diff --git a/source/blender/blenkernel/intern/packedFile.c b/source/blender/blenkernel/intern/packedFile.c index a1b315be19a..dd91878a15b 100644 --- a/source/blender/blenkernel/intern/packedFile.c +++ b/source/blender/blenkernel/intern/packedFile.c @@ -117,17 +117,23 @@ int countPackedFiles(Main *bmain) int count = 0; /* let's check if there are packed files... */ - for (ima = bmain->images.first; ima; ima = ima->id.next) - if (BKE_image_has_packedfile(ima)) + for (ima = bmain->images.first; ima; ima = ima->id.next) { + if (BKE_image_has_packedfile(ima)) { count++; + } + } - for (vf = bmain->fonts.first; vf; vf = vf->id.next) - if (vf->packedfile) + for (vf = bmain->fonts.first; vf; vf = vf->id.next) { + if (vf->packedfile) { count++; + } + } - for (sound = bmain->sounds.first; sound; sound = sound->id.next) - if (sound->packedfile) + for (sound = bmain->sounds.first; sound; sound = sound->id.next) { + if (sound->packedfile) { count++; + } + } return count; } @@ -138,8 +144,9 @@ void freePackedFile(PackedFile *pf) MEM_freeN(pf->data); MEM_freeN(pf); } - else + else { printf("freePackedFile: Trying to free a NULL pointer\n"); + } } PackedFile *dupPackedFile(const PackedFile *pf_src) @@ -170,10 +177,11 @@ PackedFile *newPackedFile(ReportList *reports, const char *filename, const char /* render result has no filename and can be ignored * any other files with no name can be ignored too */ - if (filename[0] == '\0') + if (filename[0] == '\0') { return NULL; + } - //XXX waitcursor(1); + // XXX waitcursor(1); /* convert relative filenames to absolute filenames */ @@ -208,7 +216,7 @@ PackedFile *newPackedFile(ReportList *reports, const char *filename, const char close(file); } - //XXX waitcursor(0); + // XXX waitcursor(0); return (pf); } @@ -251,10 +259,12 @@ void packAll(Main *bmain, ReportList *reports, bool verbose) } } - if (tot > 0) + if (tot > 0) { BKE_reportf(reports, RPT_INFO, "Packed %d files", tot); - else if (verbose) + } + else if (verbose) { BKE_report(reports, RPT_INFO, "No new files have been packed"); + } } int writePackedFile(ReportList *reports, @@ -271,7 +281,7 @@ int writePackedFile(ReportList *reports, /* void *data; */ if (guimode) { - } //XXX waitcursor(1); + } // XXX waitcursor(1); BLI_strncpy(name, filename, sizeof(name)); BLI_path_abs(name, ref_file_name); @@ -326,7 +336,7 @@ int writePackedFile(ReportList *reports, } if (guimode) { - } //XXX waitcursor(0); + } // XXX waitcursor(0); return (ret_value); } @@ -397,7 +407,8 @@ int checkPackedFile(const char *ref_file_name, const char *filename, PackedFile * It returns a char *to the existing file name / new file name or NULL when * there was an error or when the user decides to cancel the operation. * - * \warning 'abs_name' may be relative still! (use a "//" prefix) be sure to run #BLI_path_abs on it first. + * \warning 'abs_name' may be relative still! (use a "//" prefix) + * be sure to run #BLI_path_abs on it first. */ char *unpackFile(ReportList *reports, const char *ref_file_name, @@ -650,18 +661,22 @@ void packLibraries(Main *bmain, ReportList *reports) Library *lib; /* test for relativenss */ - for (lib = bmain->libraries.first; lib; lib = lib->id.next) - if (!BLI_path_is_rel(lib->name)) + for (lib = bmain->libraries.first; lib; lib = lib->id.next) { + if (!BLI_path_is_rel(lib->name)) { break; + } + } if (lib) { BKE_reportf(reports, RPT_ERROR, "Cannot pack absolute file: '%s'", lib->name); return; } - for (lib = bmain->libraries.first; lib; lib = lib->id.next) - if (lib->packedfile == NULL) + for (lib = bmain->libraries.first; lib; lib = lib->id.next) { + if (lib->packedfile == NULL) { lib->packedfile = newPackedFile(reports, lib->name, BKE_main_blendfile_path(bmain)); + } + } } void unpackAll(Main *bmain, ReportList *reports, int how) @@ -670,17 +685,23 @@ void unpackAll(Main *bmain, ReportList *reports, int how) VFont *vf; bSound *sound; - for (ima = bmain->images.first; ima; ima = ima->id.next) - if (BKE_image_has_packedfile(ima)) + for (ima = bmain->images.first; ima; ima = ima->id.next) { + if (BKE_image_has_packedfile(ima)) { unpackImage(bmain, reports, ima, how); + } + } - for (vf = bmain->fonts.first; vf; vf = vf->id.next) - if (vf->packedfile) + for (vf = bmain->fonts.first; vf; vf = vf->id.next) { + if (vf->packedfile) { unpackVFont(bmain, reports, vf, how); + } + } - for (sound = bmain->sounds.first; sound; sound = sound->id.next) - if (sound->packedfile) + for (sound = bmain->sounds.first; sound; sound = sound->id.next) { + if (sound->packedfile) { unpackSound(bmain, reports, sound, how); + } + } } /* ID should be not NULL, return 1 if there's a packed file */ diff --git a/source/blender/blenkernel/intern/paint.c b/source/blender/blenkernel/intern/paint.c index 22586c674db..c55cf18fcea 100644 --- a/source/blender/blenkernel/intern/paint.c +++ b/source/blender/blenkernel/intern/paint.c @@ -84,13 +84,16 @@ void BKE_paint_invalidate_overlay_tex(Scene *scene, ViewLayer *view_layer, const Paint *p = BKE_paint_get_active(scene, view_layer); Brush *br = p->brush; - if (!br) + if (!br) { return; + } - if (br->mtex.tex == tex) + if (br->mtex.tex == tex) { overlay_flags |= PAINT_OVERLAY_INVALID_TEXTURE_PRIMARY; - if (br->mask_mtex.tex == tex) + } + if (br->mask_mtex.tex == tex) { overlay_flags |= PAINT_OVERLAY_INVALID_TEXTURE_SECONDARY; + } } void BKE_paint_invalidate_cursor_overlay(Scene *scene, ViewLayer *view_layer, CurveMapping *curve) @@ -98,8 +101,9 @@ void BKE_paint_invalidate_cursor_overlay(Scene *scene, ViewLayer *view_layer, Cu Paint *p = BKE_paint_get_active(scene, view_layer); Brush *br = p->brush; - if (br && br->curve == curve) + if (br && br->curve == curve) { overlay_flags |= PAINT_OVERLAY_INVALID_CURVE; + } } void BKE_paint_invalidate_overlay_all(void) @@ -116,12 +120,15 @@ eOverlayControlFlags BKE_paint_get_overlay_flags(void) void BKE_paint_set_overlay_override(eOverlayFlags flags) { if (flags & BRUSH_OVERLAY_OVERRIDE_MASK) { - if (flags & BRUSH_OVERLAY_CURSOR_OVERRIDE_ON_STROKE) + if (flags & BRUSH_OVERLAY_CURSOR_OVERRIDE_ON_STROKE) { overlay_flags |= PAINT_OVERLAY_OVERRIDE_CURSOR; - if (flags & BRUSH_OVERLAY_PRIMARY_OVERRIDE_ON_STROKE) + } + if (flags & BRUSH_OVERLAY_PRIMARY_OVERRIDE_ON_STROKE) { overlay_flags |= PAINT_OVERLAY_OVERRIDE_PRIMARY; - if (flags & BRUSH_OVERLAY_SECONDARY_OVERRIDE_ON_STROKE) + } + if (flags & BRUSH_OVERLAY_SECONDARY_OVERRIDE_ON_STROKE) { overlay_flags |= PAINT_OVERLAY_OVERRIDE_SECONDARY; + } } else { overlay_flags &= ~(PAINT_OVERRIDE_MASK); @@ -133,6 +140,40 @@ void BKE_paint_reset_overlay_invalid(eOverlayControlFlags flag) overlay_flags &= ~(flag); } +bool BKE_paint_ensure_from_paintmode(Scene *sce, ePaintMode mode) +{ + ToolSettings *ts = sce->toolsettings; + Paint **paint_ptr = NULL; + + switch (mode) { + case PAINT_MODE_SCULPT: + paint_ptr = (Paint **)&ts->sculpt; + break; + case PAINT_MODE_VERTEX: + paint_ptr = (Paint **)&ts->vpaint; + break; + case PAINT_MODE_WEIGHT: + paint_ptr = (Paint **)&ts->wpaint; + break; + case PAINT_MODE_TEXTURE_2D: + case PAINT_MODE_TEXTURE_3D: + break; + case PAINT_MODE_SCULPT_UV: + paint_ptr = (Paint **)&ts->uvsculpt; + break; + case PAINT_MODE_GPENCIL: + paint_ptr = (Paint **)&ts->gp_paint; + break; + case PAINT_MODE_INVALID: + break; + } + if (paint_ptr && (*paint_ptr == NULL)) { + BKE_paint_ensure(ts, paint_ptr); + return true; + } + return false; +} + Paint *BKE_paint_get_active_from_paintmode(Scene *sce, ePaintMode mode) { if (sce) { @@ -175,6 +216,7 @@ const EnumPropertyItem *BKE_paint_get_tool_enum_from_paintmode(ePaintMode mode) case PAINT_MODE_TEXTURE_3D: return rna_enum_brush_image_tool_items; case PAINT_MODE_SCULPT_UV: + return rna_enum_brush_uv_sculpt_tool_items; return NULL; case PAINT_MODE_GPENCIL: return rna_enum_brush_gpencil_types_items; @@ -196,6 +238,8 @@ const char *BKE_paint_get_tool_prop_id_from_paintmode(ePaintMode mode) case PAINT_MODE_TEXTURE_2D: case PAINT_MODE_TEXTURE_3D: return "image_tool"; + case PAINT_MODE_SCULPT_UV: + return "uv_sculpt_tool"; case PAINT_MODE_GPENCIL: return "gpencil_tool"; default: @@ -222,9 +266,7 @@ Paint *BKE_paint_get_active(Scene *sce, ViewLayer *view_layer) case OB_MODE_PAINT_GPENCIL: return &ts->gp_paint->paint; case OB_MODE_EDIT: - if (ts->use_uv_sculpt) - return &ts->uvsculpt->paint; - return &ts->imapaint.paint; + return &ts->uvsculpt->paint; default: break; } @@ -247,15 +289,18 @@ Paint *BKE_paint_get_active_from_context(const bContext *C) ToolSettings *ts = sce->toolsettings; Object *obact = NULL; - if (view_layer->basact && view_layer->basact->object) + if (view_layer->basact && view_layer->basact->object) { obact = view_layer->basact->object; + } if ((sima = CTX_wm_space_image(C)) != NULL) { if (obact && obact->mode == OB_MODE_EDIT) { - if (sima->mode == SI_MODE_PAINT) + if (sima->mode == SI_MODE_PAINT) { return &ts->imapaint.paint; - else if (ts->use_uv_sculpt) + } + else if (sima->mode == SI_MODE_UV) { return &ts->uvsculpt->paint; + } } else { return &ts->imapaint.paint; @@ -276,18 +321,20 @@ ePaintMode BKE_paintmode_get_active_from_context(const bContext *C) SpaceImage *sima; if (sce && view_layer) { - ToolSettings *ts = sce->toolsettings; Object *obact = NULL; - if (view_layer->basact && view_layer->basact->object) + if (view_layer->basact && view_layer->basact->object) { obact = view_layer->basact->object; + } if ((sima = CTX_wm_space_image(C)) != NULL) { if (obact && obact->mode == OB_MODE_EDIT) { - if (sima->mode == SI_MODE_PAINT) + if (sima->mode == SI_MODE_PAINT) { return PAINT_MODE_TEXTURE_2D; - else if (ts->use_uv_sculpt) + } + else if (sima->mode == SI_MODE_UV) { return PAINT_MODE_SCULPT_UV; + } } else { return PAINT_MODE_TEXTURE_2D; @@ -304,9 +351,7 @@ ePaintMode BKE_paintmode_get_active_from_context(const bContext *C) case OB_MODE_TEXTURE_PAINT: return PAINT_MODE_TEXTURE_3D; case OB_MODE_EDIT: - if (ts->use_uv_sculpt) - return PAINT_MODE_SCULPT_UV; - return PAINT_MODE_TEXTURE_2D; + return PAINT_MODE_SCULPT_UV; default: return PAINT_MODE_TEXTURE_2D; } @@ -340,6 +385,8 @@ ePaintMode BKE_paintmode_get_from_tool(const struct bToolRef *tref) switch (tref->mode) { case SI_MODE_PAINT: return PAINT_MODE_TEXTURE_2D; + case SI_MODE_UV: + return PAINT_MODE_SCULPT_UV; } } @@ -380,15 +427,14 @@ void BKE_paint_runtime_init(const ToolSettings *ts, Paint *paint) paint->runtime.tool_offset = offsetof(Brush, weightpaint_tool); paint->runtime.ob_mode = OB_MODE_WEIGHT_PAINT; } + else if (paint == &ts->uvsculpt->paint) { + paint->runtime.tool_offset = offsetof(Brush, uv_sculpt_tool); + paint->runtime.ob_mode = OB_MODE_EDIT; + } else if (paint == &ts->gp_paint->paint) { paint->runtime.tool_offset = offsetof(Brush, gpencil_tool); paint->runtime.ob_mode = OB_MODE_PAINT_GPENCIL; } - else if (paint == &ts->uvsculpt->paint) { - /* We don't use these yet. */ - paint->runtime.tool_offset = 0; - paint->runtime.ob_mode = 0; - } else { BLI_assert(0); } @@ -406,9 +452,10 @@ uint BKE_paint_get_brush_tool_offset_from_paintmode(const ePaintMode mode) return offsetof(Brush, vertexpaint_tool); case PAINT_MODE_WEIGHT: return offsetof(Brush, weightpaint_tool); + case PAINT_MODE_SCULPT_UV: + return offsetof(Brush, uv_sculpt_tool); case PAINT_MODE_GPENCIL: return offsetof(Brush, gpencil_tool); - case PAINT_MODE_SCULPT_UV: case PAINT_MODE_INVALID: break; /* We don't use these yet. */ } @@ -432,8 +479,10 @@ PaintCurve *BKE_paint_curve_add(Main *bmain, const char *name) } /** - * Only copy internal data of PaintCurve ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of PaintCurve ID from source to + * already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * @@ -489,7 +538,7 @@ void BKE_paint_curve_clamp_endpoint_add_index(PaintCurve *pc, const int add_inde pc->add_index = (add_index || pc->tot_points == 1) ? (add_index + 1) : 0; } -/* remove colour from palette. Must be certain color is inside the palette! */ +/** Remove color from palette. Must be certain color is inside the palette! */ void BKE_palette_color_remove(Palette *palette, PaletteColor *color) { if (BLI_listbase_count_at_most(&palette->colors, palette->active_color) == @@ -519,8 +568,10 @@ Palette *BKE_palette_add(Main *bmain, const char *name) } /** - * Only copy internal data of Palette ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of Palette ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * @@ -599,8 +650,9 @@ void BKE_paint_cavity_curve_preset(Paint *p, int preset) { CurveMap *cm = NULL; - if (!p->cavity_curve) + if (!p->cavity_curve) { p->cavity_curve = curvemapping_add(1, 0, 0, 1, 1); + } cm = p->cavity_curve->cm; cm->flag &= ~CUMA_EXTEND_EXTRAPOLATE; @@ -712,8 +764,9 @@ void BKE_paint_init(Main *bmain, Scene *sce, ePaintMode mode, const char col[3]) ups->last_stroke_valid = false; zero_v3(ups->average_stroke_accum); ups->average_stroke_counter = 0; - if (!paint->cavity_curve) + if (!paint->cavity_curve) { BKE_paint_cavity_curve_preset(paint, CURVE_PRESET_LINE); + } } void BKE_paint_free(Paint *paint) @@ -805,15 +858,19 @@ float paint_grid_paint_mask(const GridPaintMask *gpm, unsigned level, unsigned x void paint_update_brush_rake_rotation(UnifiedPaintSettings *ups, Brush *brush, float rotation) { - if (brush->mtex.brush_angle_mode & MTEX_ANGLE_RAKE) + if (brush->mtex.brush_angle_mode & MTEX_ANGLE_RAKE) { ups->brush_rotation = rotation; - else + } + else { ups->brush_rotation = 0.0f; + } - if (brush->mask_mtex.brush_angle_mode & MTEX_ANGLE_RAKE) + if (brush->mask_mtex.brush_angle_mode & MTEX_ANGLE_RAKE) { ups->brush_rotation_sec = rotation; - else + } + else { ups->brush_rotation_sec = 0.0f; + } } bool paint_calculate_rake_rotation(UnifiedPaintSettings *ups, @@ -899,8 +956,9 @@ static void sculptsession_bm_to_me_update_data_only(Object *ob, bool reorder) BM_ITER_MESH (efa, &iter, ss->bm, BM_FACES_OF_MESH) { BM_elem_flag_set(efa, BM_ELEM_SMOOTH, ss->bm_smooth_shading); } - if (reorder) + if (reorder) { BM_log_mesh_elems_reorder(ss->bm, ss->bm_log); + } BM_mesh_bm_to_me(NULL, ss->bm, ob->data, @@ -916,7 +974,8 @@ void BKE_sculptsession_bm_to_me(Object *ob, bool reorder) if (ob && ob->sculpt) { sculptsession_bm_to_me_update_data_only(ob, reorder); - /* ensure the objects evaluated mesh doesn't hold onto arrays now realloc'd in the mesh [#34473] */ + /* Ensure the objects evaluated mesh doesn't hold onto arrays + * now realloc'd in the mesh T34473. */ DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); } } @@ -958,28 +1017,36 @@ void BKE_sculptsession_free(Object *ob) BM_mesh_free(ss->bm); } - if (ss->pbvh) + if (ss->pbvh) { BKE_pbvh_free(ss->pbvh); + } MEM_SAFE_FREE(ss->pmap); MEM_SAFE_FREE(ss->pmap_mem); - if (ss->bm_log) + if (ss->bm_log) { BM_log_free(ss->bm_log); + } - if (ss->texcache) + if (ss->texcache) { MEM_freeN(ss->texcache); + } - if (ss->tex_pool) + if (ss->tex_pool) { BKE_image_pool_free(ss->tex_pool); + } - if (ss->layer_co) + if (ss->layer_co) { MEM_freeN(ss->layer_co); + } - if (ss->orig_cos) + if (ss->orig_cos) { MEM_freeN(ss->orig_cos); - if (ss->deform_cos) + } + if (ss->deform_cos) { MEM_freeN(ss->deform_cos); - if (ss->deform_imats) + } + if (ss->deform_imats) { MEM_freeN(ss->deform_imats); + } BKE_sculptsession_free_vwpaint_data(ob->sculpt); @@ -1011,13 +1078,16 @@ MultiresModifierData *BKE_sculpt_multires_active(Scene *scene, Object *ob) if (md->type == eModifierType_Multires) { MultiresModifierData *mmd = (MultiresModifierData *)md; - if (!modifier_isEnabled(scene, md, eModifierMode_Realtime)) + if (!modifier_isEnabled(scene, md, eModifierMode_Realtime)) { continue; + } - if (mmd->sculptlvl > 0) + if (mmd->sculptlvl > 0) { return mmd; - else + } + else { return NULL; + } } } @@ -1032,27 +1102,33 @@ static bool sculpt_modifiers_active(Scene *scene, Sculpt *sd, Object *ob) MultiresModifierData *mmd = BKE_sculpt_multires_active(scene, ob); VirtualModifierData virtualModifierData; - if (mmd || ob->sculpt->bm) + if (mmd || ob->sculpt->bm) { return false; + } /* non-locked shape keys could be handled in the same way as deformed mesh */ - if ((ob->shapeflag & OB_SHAPE_LOCK) == 0 && me->key && ob->shapenr) + if ((ob->shapeflag & OB_SHAPE_LOCK) == 0 && me->key && ob->shapenr) { return true; + } md = modifiers_getVirtualModifierList(ob, &virtualModifierData); /* exception for shape keys because we can edit those */ for (; md; md = md->next) { const ModifierTypeInfo *mti = modifierType_getInfo(md->type); - if (!modifier_isEnabled(scene, md, eModifierMode_Realtime)) + if (!modifier_isEnabled(scene, md, eModifierMode_Realtime)) { continue; - if (ELEM(md->type, eModifierType_ShapeKey, eModifierType_Multires)) + } + if (ELEM(md->type, eModifierType_ShapeKey, eModifierType_Multires)) { continue; + } - if (mti->type == eModifierTypeType_OnlyDeform) + if (mti->type == eModifierTypeType_OnlyDeform) { return true; - else if ((sd->flags & SCULPT_ONLY_DEFORM) == 0) + } + else if ((sd->flags & SCULPT_ONLY_DEFORM) == 0) { return true; + } } return false; @@ -1095,7 +1171,10 @@ void BKE_sculpt_update_mesh_elements( if (!CustomData_has_layer(&me->ldata, CD_GRID_PAINT_MASK)) { #if 1 BKE_sculpt_mask_layers_ensure(ob, mmd); -#else /* if we wanted to support adding mask data while multi-res painting, we would need to do this */ +#else + /* If we wanted to support adding mask data while multi-res painting, + * we would need to do this. */ + if ((ED_sculpt_mask_layers_ensure(ob, mmd) & ED_SCULPT_MASK_LAYER_CALC_LOOP)) { /* remake the derived mesh */ ob->recalc |= ID_RECALC_GEOMETRY; @@ -1340,8 +1419,15 @@ static PBVH *build_pbvh_from_regular_mesh(Object *ob, Mesh *me_eval_deform) BKE_mesh_recalc_looptri(me->mloop, me->mpoly, me->mvert, me->totloop, me->totpoly, looptri); - BKE_pbvh_build_mesh( - pbvh, me->mpoly, me->mloop, me->mvert, me->totvert, &me->vdata, looptri, looptris_num); + BKE_pbvh_build_mesh(pbvh, + me->mpoly, + me->mloop, + me->mvert, + me->totvert, + &me->vdata, + &me->ldata, + looptri, + looptris_num); pbvh_show_diffuse_color_set(pbvh, ob->sculpt->show_diffuse_color); pbvh_show_mask_set(pbvh, ob->sculpt->show_mask); diff --git a/source/blender/blenkernel/intern/paint_toolslots.c b/source/blender/blenkernel/intern/paint_toolslots.c index 942d5e758f3..fbf586e3f49 100644 --- a/source/blender/blenkernel/intern/paint_toolslots.c +++ b/source/blender/blenkernel/intern/paint_toolslots.c @@ -70,6 +70,7 @@ void BKE_paint_toolslots_init_from_main(struct Main *bmain) paint_toolslots_init(bmain, &ts->sculpt->paint); paint_toolslots_init(bmain, &ts->vpaint->paint); paint_toolslots_init(bmain, &ts->wpaint->paint); + paint_toolslots_init(bmain, &ts->uvsculpt->paint); paint_toolslots_init(bmain, &ts->gp_paint->paint); } } diff --git a/source/blender/blenkernel/intern/particle.c b/source/blender/blenkernel/intern/particle.c index 9e121d279ba..c6cc72ba989 100644 --- a/source/blender/blenkernel/intern/particle.c +++ b/source/blender/blenkernel/intern/particle.c @@ -129,8 +129,9 @@ int count_particles(ParticleSystem *psys) } else if (pa->alive == PARS_DEAD && (part->flag & PART_DIED) == 0) { } - else + else { tot++; + } } return tot; } @@ -146,8 +147,9 @@ int count_particles_mod(ParticleSystem *psys, int totgr, int cur) } else if (pa->alive == PARS_DEAD && (part->flag & PART_DIED) == 0) { } - else if (p % totgr == cur) + else if (p % totgr == cur) { tot++; + } } return tot; } @@ -176,8 +178,9 @@ static ParticleCacheKey **psys_alloc_path_cache_buffers(ListBase *bufs, int tot, buf = MEM_callocN(sizeof(LinkData), "PathCacheLinkData"); buf->data = MEM_callocN(sizeof(ParticleCacheKey) * totbufkey * totkeys, "ParticleCacheKey"); - for (i = 0; i < totbufkey; i++) + for (i = 0; i < totbufkey; i++) { cache[totkey + i] = ((ParticleCacheKey *)buf->data) + i * totkeys; + } totkey += totbufkey; BLI_addtail(bufs, buf); @@ -190,11 +193,13 @@ static void psys_free_path_cache_buffers(ParticleCacheKey **cache, ListBase *buf { LinkData *buf; - if (cache) + if (cache) { MEM_freeN(cache); + } - for (buf = bufs->first; buf; buf = buf->next) + for (buf = bufs->first; buf; buf = buf->next) { MEM_freeN(buf->data); + } BLI_freelistN(bufs); } @@ -205,12 +210,14 @@ static void psys_free_path_cache_buffers(ParticleCacheKey **cache, ListBase *buf ParticleSystem *psys_get_current(Object *ob) { ParticleSystem *psys; - if (ob == NULL) + if (ob == NULL) { return NULL; + } for (psys = ob->particlesystem.first; psys; psys = psys->next) { - if (psys->flag & PSYS_CURRENT) + if (psys->flag & PSYS_CURRENT) { return psys; + } } return NULL; @@ -220,12 +227,15 @@ short psys_get_current_num(Object *ob) ParticleSystem *psys; short i; - if (ob == NULL) + if (ob == NULL) { return 0; + } - for (psys = ob->particlesystem.first, i = 0; psys; psys = psys->next, i++) - if (psys->flag & PSYS_CURRENT) + for (psys = ob->particlesystem.first, i = 0; psys; psys = psys->next, i++) { + if (psys->flag & PSYS_CURRENT) { return i; + } + } return i; } @@ -234,14 +244,17 @@ void psys_set_current_num(Object *ob, int index) ParticleSystem *psys; short i; - if (ob == NULL) + if (ob == NULL) { return; + } for (psys = ob->particlesystem.first, i = 0; psys; psys = psys->next, i++) { - if (i == index) + if (i == index) { psys->flag |= PSYS_CURRENT; - else + } + else { psys->flag &= ~PSYS_CURRENT; + } } } @@ -266,8 +279,9 @@ struct LatticeDeformData *psys_create_lattice_deform_data(ParticleSimulationData break; } } - if (lattice) + if (lattice) { lattice_deform_data = init_latt_deform(lattice, NULL); + } } return lattice_deform_data; @@ -276,15 +290,17 @@ void psys_disable_all(Object *ob) { ParticleSystem *psys = ob->particlesystem.first; - for (; psys; psys = psys->next) + for (; psys; psys = psys->next) { psys->flag |= PSYS_DISABLED; + } } void psys_enable_all(Object *ob) { ParticleSystem *psys = ob->particlesystem.first; - for (; psys; psys = psys->next) + for (; psys; psys = psys->next) { psys->flag &= ~PSYS_DISABLED; + } } ParticleSystem *psys_orig_get(ParticleSystem *psys) @@ -339,26 +355,31 @@ bool psys_check_enabled(Object *ob, ParticleSystem *psys, const bool use_render_ { ParticleSystemModifierData *psmd; - if (psys->flag & PSYS_DISABLED || psys->flag & PSYS_DELETE || !psys->part) + if (psys->flag & PSYS_DISABLED || psys->flag & PSYS_DELETE || !psys->part) { return 0; + } psmd = psys_get_modifier(ob, psys); if (use_render_params) { - if (!(psmd->modifier.mode & eModifierMode_Render)) + if (!(psmd->modifier.mode & eModifierMode_Render)) { return 0; + } } - else if (!(psmd->modifier.mode & eModifierMode_Realtime)) + else if (!(psmd->modifier.mode & eModifierMode_Realtime)) { return 0; + } return 1; } bool psys_check_edited(ParticleSystem *psys) { - if (psys->part && psys->part->type == PART_HAIR) + if (psys->part && psys->part->type == PART_HAIR) { return (psys->flag & PSYS_EDITED || (psys->edit && psys->edit->edited)); - else + } + else { return (psys->pointcache->edit && psys->pointcache->edit->edited); + } } void psys_find_group_weights(ParticleSettings *part) @@ -435,8 +456,9 @@ void psys_check_group_weights(ParticleSettings *part) if (!current) { dw = part->instance_weights.first; - if (dw) + if (dw) { dw->flag |= PART_DUPLIW_CURRENT; + } } } @@ -450,11 +472,14 @@ int psys_uses_gravity(ParticleSimulationData *sim) /************************************************/ static void fluid_free_settings(SPHFluidSettings *fluid) { - if (fluid) + if (fluid) { MEM_freeN(fluid); + } } -/** Free (or release) any data used by this particle settings (does not free the partsett itself). */ +/** + * Free (or release) any data used by this particle settings (does not free the partsett itself). + */ void BKE_particlesettings_free(ParticleSettings *part) { int a; @@ -465,12 +490,15 @@ void BKE_particlesettings_free(ParticleSettings *part) MEM_SAFE_FREE(part->mtex[a]); } - if (part->clumpcurve) + if (part->clumpcurve) { curvemapping_free(part->clumpcurve); - if (part->roughcurve) + } + if (part->roughcurve) { curvemapping_free(part->roughcurve); - if (part->twistcurve) + } + if (part->twistcurve) { curvemapping_free(part->twistcurve); + } BKE_partdeflect_free(part->pd); BKE_partdeflect_free(part->pd2); @@ -489,8 +517,9 @@ void free_hair(Object *object, ParticleSystem *psys, int dynamics) LOOP_PARTICLES { - if (pa->hair) + if (pa->hair) { MEM_freeN(pa->hair); + } pa->hair = NULL; pa->totkey = 0; } @@ -510,20 +539,23 @@ void free_hair(Object *object, ParticleSystem *psys, int dynamics) } } - if (psys->hair_in_mesh) + if (psys->hair_in_mesh) { BKE_id_free(NULL, psys->hair_in_mesh); + } psys->hair_in_mesh = NULL; - if (psys->hair_out_mesh) + if (psys->hair_out_mesh) { BKE_id_free(NULL, psys->hair_out_mesh); + } psys->hair_out_mesh = NULL; } void free_keyed_keys(ParticleSystem *psys) { PARTICLE_P; - if (psys->part->type == PART_HAIR) + if (psys->part->type == PART_HAIR) { return; + } if (psys->particles && psys->particles->keys) { MEM_freeN(psys->particles->keys); @@ -573,21 +605,25 @@ void psys_free_particles(ParticleSystem *psys) PARTICLE_P; if (psys->particles) { - /* Even though psys->part should never be NULL, this can happen as an exception during deletion. + /* Even though psys->part should never be NULL, + * this can happen as an exception during deletion. * See ID_REMAP_SKIP/FORCE/FLAG_NEVER_NULL_USAGE in BKE_library_remap. */ if (psys->part && psys->part->type == PART_HAIR) { LOOP_PARTICLES { - if (pa->hair) + if (pa->hair) { MEM_freeN(pa->hair); + } } } - if (psys->particles->keys) + if (psys->particles->keys) { MEM_freeN(psys->particles->keys); + } - if (psys->particles->boid) + if (psys->particles->boid) { MEM_freeN(psys->particles->boid); + } MEM_freeN(psys->particles); psys->particles = NULL; @@ -597,20 +633,24 @@ void psys_free_particles(ParticleSystem *psys) void psys_free_pdd(ParticleSystem *psys) { if (psys->pdd) { - if (psys->pdd->cdata) + if (psys->pdd->cdata) { MEM_freeN(psys->pdd->cdata); + } psys->pdd->cdata = NULL; - if (psys->pdd->vdata) + if (psys->pdd->vdata) { MEM_freeN(psys->pdd->vdata); + } psys->pdd->vdata = NULL; - if (psys->pdd->ndata) + if (psys->pdd->ndata) { MEM_freeN(psys->pdd->ndata); + } psys->pdd->ndata = NULL; - if (psys->pdd->vedata) + if (psys->pdd->vedata) { MEM_freeN(psys->pdd->vedata); + } psys->pdd->vedata = NULL; psys->pdd->totpoint = 0; @@ -645,8 +685,9 @@ void psys_free(Object *ob, ParticleSystem *psys) psys_free_particles(psys); - if (psys->edit && psys->free_edit) + if (psys->edit && psys->free_edit) { psys->free_edit(psys->edit); + } if (psys->child) { MEM_freeN(psys->child); @@ -664,8 +705,9 @@ void psys_free(Object *ob, ParticleSystem *psys) } } /* clear do-not-draw-flag */ - if (!nr) + if (!nr) { ob->transflag &= ~OB_DUPLIPARTS; + } psys->part = NULL; @@ -679,8 +721,9 @@ void psys_free(Object *ob, ParticleSystem *psys) BLI_bvhtree_free(psys->bvhtree); BLI_kdtree_3d_free(psys->tree); - if (psys->fluid_springs) + if (psys->fluid_springs) { MEM_freeN(psys->fluid_springs); + } BKE_effectors_free(psys->effectors); @@ -749,8 +792,9 @@ static float interpolate_particle_value( float value; value = w[0] * v1 + w[1] * v2 + w[2] * v3; - if (four) + if (four) { value += w[3] * v4; + } CLAMP(value, 0.f, 1.f); @@ -805,8 +849,12 @@ typedef struct ParticleInterpolationData { float birthtime, dietime; int bspline; } ParticleInterpolationData; -/* Assumes pointcache->mem_cache exists, so for disk cached particles call psys_make_temp_pointcache() before use */ -/* It uses ParticleInterpolationData->pm to store the current memory cache frame so it's thread safe. */ +/** + * Assumes pointcache->mem_cache exists, so for disk cached particles + * call #psys_make_temp_pointcache() before use. + * It uses #ParticleInterpolationData.pm to store the current memory cache frame + * so it's thread safe. + */ static void get_pointcache_keys_for_time(Object *UNUSED(ob), PointCache *cache, PTCacheMem **cur, @@ -821,13 +869,15 @@ static void get_pointcache_keys_for_time(Object *UNUSED(ob), if (index < 0) { /* initialize */ *cur = cache->mem_cache.first; - if (*cur) + if (*cur) { *cur = (*cur)->next; + } } else { if (*cur) { - while (*cur && (*cur)->next && (float)(*cur)->frame < t) + while (*cur && (*cur)->next && (float)(*cur)->frame < t) { *cur = (*cur)->next; + } pm = *cur; @@ -838,10 +888,12 @@ static void get_pointcache_keys_for_time(Object *UNUSED(ob), } BKE_ptcache_make_particle_key(key2, index2, pm->data, (float)pm->frame); - if (index1 < 0) + if (index1 < 0) { copy_particle_key(key1, key2, 1); - else + } + else { BKE_ptcache_make_particle_key(key1, index1, pm->prev->data, (float)pm->prev->frame); + } } else if (cache->mem_cache.first) { pm = cache->mem_cache.first; @@ -887,8 +939,9 @@ float psys_get_dietime_from_cache(PointCache *cache, int index) int dietime = 10000000; /* some max value so that we can default to pa->time+lifetime */ for (pm = cache->mem_cache.last; pm; pm = pm->prev) { - if (BKE_ptcache_mem_index_find(pm, index) >= 0) + if (BKE_ptcache_mem_index_find(pm, index) >= 0) { return (float)pm->frame; + } } return (float)dietime; @@ -979,14 +1032,17 @@ static void do_particle_interpolation(ParticleSystem *psys, /* interpret timing and find keys */ if (point) { - if (result->time < 0.0f) + if (result->time < 0.0f) { real_t = -result->time; - else + } + else { real_t = *(pind->ekey[0]->time) + t * (*(pind->ekey[0][point->totkey - 1].time) - *(pind->ekey[0]->time)); + } - while (*(pind->ekey[1]->time) < real_t) + while (*(pind->ekey[1]->time) < real_t) { pind->ekey[1]++; + } pind->ekey[0] = pind->ekey[1] - 1; } @@ -997,49 +1053,59 @@ static void do_particle_interpolation(ParticleSystem *psys, return; } - if (result->time < 0.0f) + if (result->time < 0.0f) { real_t = -result->time; - else + } + else { real_t = pind->kkey[0]->time + t * (pind->kkey[0][pa->totkey - 1].time - pind->kkey[0]->time); + } if (psys->part->phystype == PART_PHYS_KEYED && psys->flag & PSYS_KEYED_TIMING) { ParticleTarget *pt = psys->targets.first; pt = pt->next; - while (pt && pa->time + pt->time < real_t) + while (pt && pa->time + pt->time < real_t) { pt = pt->next; + } if (pt) { pt = pt->prev; - if (pa->time + pt->time + pt->duration > real_t) + if (pa->time + pt->time + pt->duration > real_t) { real_t = pa->time + pt->time; + } } - else + else { real_t = pa->time + ((ParticleTarget *)psys->targets.last)->time; + } } CLAMP(real_t, pa->time, pa->dietime); - while (pind->kkey[1]->time < real_t) + while (pind->kkey[1]->time < real_t) { pind->kkey[1]++; + } pind->kkey[0] = pind->kkey[1] - 1; } else if (pind->cache) { - if (result->time < 0.0f) /* flag for time in frames */ + if (result->time < 0.0f) { /* flag for time in frames */ real_t = -result->time; - else + } + else { real_t = pa->time + t * (pa->dietime - pa->time); + } } else { - if (result->time < 0.0f) + if (result->time < 0.0f) { real_t = -result->time; - else + } + else { real_t = pind->hkey[0]->time + t * (pind->hkey[0][pa->totkey - 1].time - pind->hkey[0]->time); + } while (pind->hkey[1]->time < real_t) { pind->hkey[1]++; @@ -1074,41 +1140,53 @@ static void do_particle_interpolation(ParticleSystem *psys, /* set secondary interpolation keys for hair */ if (!pind->keyed && !pind->cache && !point_vel) { if (point) { - if (pind->ekey[0] != point->keys) + if (pind->ekey[0] != point->keys) { edit_to_particle(keys, pind->ekey[0] - 1); - else + } + else { edit_to_particle(keys, pind->ekey[0]); + } } else if (pind->mesh) { - if (pind->hkey[0] != pa->hair) + if (pind->hkey[0] != pa->hair) { mvert_to_particle(keys, pind->mvert[0] - 1, pind->hkey[0] - 1); - else + } + else { mvert_to_particle(keys, pind->mvert[0], pind->hkey[0]); + } } else { - if (pind->hkey[0] != pa->hair) + if (pind->hkey[0] != pa->hair) { hair_to_particle(keys, pind->hkey[0] - 1); - else + } + else { hair_to_particle(keys, pind->hkey[0]); + } } if (point) { - if (pind->ekey[1] != point->keys + point->totkey - 1) + if (pind->ekey[1] != point->keys + point->totkey - 1) { edit_to_particle(keys + 3, pind->ekey[1] + 1); - else + } + else { edit_to_particle(keys + 3, pind->ekey[1]); + } } else if (pind->mesh) { - if (pind->hkey[1] != pa->hair + pa->totkey - 1) + if (pind->hkey[1] != pa->hair + pa->totkey - 1) { mvert_to_particle(keys + 3, pind->mvert[1] + 1, pind->hkey[1] + 1); - else + } + else { mvert_to_particle(keys + 3, pind->mvert[1], pind->hkey[1]); + } } else { - if (pind->hkey[1] != pa->hair + pa->totkey - 1) + if (pind->hkey[1] != pa->hair + pa->totkey - 1) { hair_to_particle(keys + 3, pind->hkey[1] + 1); - else + } + else { hair_to_particle(keys + 3, pind->hkey[1]); + } } } @@ -1123,7 +1201,8 @@ static void do_particle_interpolation(ParticleSystem *psys, interp_qt_qtqt(result->rot, keys[1].rot, keys[2].rot, keytime); } - /* now we should have in chronologiacl order k1<=k2<=t<=k3<=k4 with keytime between [0, 1]->[k2, k3] (k1 & k4 used for cardinal & bspline interpolation)*/ + /* Now we should have in chronologiacl order k1<=k2<=t<=k3<=k4 with keytime between + * [0, 1]->[k2, k3] (k1 & k4 used for cardinal & bspline interpolation). */ psys_interpolate_particle((pind->keyed || pind->cache || point_vel) ? -1 /* signal for cubic interpolation */ : @@ -1134,8 +1213,9 @@ static void do_particle_interpolation(ParticleSystem *psys, 1); /* the velocity needs to be converted back from cubic interpolation */ - if (pind->keyed || pind->cache || point_vel) + if (pind->keyed || pind->cache || point_vel) { mul_v3_fl(result->vel, 1.f / invdt); + } } static void interpolate_pathcache(ParticleCacheKey *first, float t, ParticleCacheKey *result) @@ -1146,11 +1226,13 @@ static void interpolate_pathcache(ParticleCacheKey *first, float t, ParticleCach /* scale the requested time to fit the entire path even if the path is cut early */ t *= (first + first->segments)->time; - while (i < first->segments && cur->time < t) + while (i < first->segments && cur->time < t) { cur++; + } - if (cur->time == t) + if (cur->time == t) { *result = *cur; + } else { float dt = (t - (cur - 1)->time) / (cur->time - (cur - 1)->time); interp_v3_v3v3(result->co, (cur - 1)->co, cur->co, dt); @@ -1160,10 +1242,12 @@ static void interpolate_pathcache(ParticleCacheKey *first, float t, ParticleCach } /* first is actual base rotation, others are incremental from first */ - if (cur == first || cur - 1 == first) + if (cur == first || cur - 1 == first) { copy_qt_qt(result->rot, first->rot); - else + } + else { mul_qt_qtqt(result->rot, first->rot, result->rot); + } } /************************************************/ @@ -1203,20 +1287,24 @@ void psys_interpolate_face(MVert *mvert, interp_v3_v3v3v3v3(vec, v1, v2, v3, v4, w); if (nor) { - if (mface->flag & ME_SMOOTH) + if (mface->flag & ME_SMOOTH) { interp_v3_v3v3v3v3(nor, n1, n2, n3, n4, w); - else + } + else { normal_quad_v3(nor, v1, v2, v3, v4); + } } } else { interp_v3_v3v3v3(vec, v1, v2, v3, w); if (nor) { - if (mface->flag & ME_SMOOTH) + if (mface->flag & ME_SMOOTH) { interp_v3_v3v3v3(nor, n1, n2, n3, w); - else + } + else { normal_tri_v3(nor, v1, v2, v3); + } } } @@ -1236,8 +1324,9 @@ void psys_interpolate_face(MVert *mvert, map_to_sphere(uv1, uv1 + 1, v1[0], v1[1], v1[2]); map_to_sphere(uv2, uv2 + 1, v2[0], v2[1], v2[2]); map_to_sphere(uv3, uv3 + 1, v3[0], v3[1], v3[2]); - if (v4) + if (v4) { map_to_sphere(uv4, uv4 + 1, v4[0], v4[1], v4[2]); + } } if (v4) { @@ -1342,8 +1431,9 @@ void psys_interpolate_mcol(const MCol *mcol, int quad, const float w[4], MCol *m static float psys_interpolate_value_from_verts( Mesh *mesh, short from, int index, const float fw[4], const float *values) { - if (values == 0 || index == -1) + if (values == 0 || index == -1) { return 0.0; + } switch (from) { case PART_FROM_VERT: @@ -1456,7 +1546,7 @@ int psys_particle_dm_face_lookup(Mesh *mesh_final, if (osface_final == NULL) { /* Assume we don't need osface_final data, and we get a direct 1-1 mapping... */ if (findex_orig < totface_final) { - //printf("\tNO CD_ORIGSPACE, assuming not needed\n"); + // printf("\tNO CD_ORIGSPACE, assuming not needed\n"); return findex_orig; } else { @@ -1492,7 +1582,8 @@ int psys_particle_dm_face_lookup(Mesh *mesh_final, } else { /* if we have no node, try every face */ for (int findex_dst = 0; findex_dst < totface_final; findex_dst++) { - /* If current tessface from 'final' DM and orig tessface (given by index) map to the same orig poly... */ + /* If current tessface from 'final' DM and orig tessface (given by index) + * map to the same orig poly. */ if (BKE_mesh_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, findex_dst) == pindex_orig) { faceuv = osface_final[findex_dst].uv; @@ -1523,21 +1614,24 @@ static int psys_map_index_on_dm(Mesh *mesh, int *mapindex, float mapfw[4]) { - if (index < 0) + if (index < 0) { return 0; + } if (mesh->runtime.deformed_only || index_dmcache == DMCACHE_ISCHILD) { /* for meshes that are either only deformed or for child particles, the * index and fw do not require any mapping, so we can directly use it */ if (from == PART_FROM_VERT) { - if (index >= mesh->totvert) + if (index >= mesh->totvert) { return 0; + } *mapindex = index; } else { /* FROM_FACE/FROM_VOLUME */ - if (index >= mesh->totface) + if (index >= mesh->totface) { return 0; + } *mapindex = index; copy_v4_v4(mapfw, fw); @@ -1548,8 +1642,9 @@ static int psys_map_index_on_dm(Mesh *mesh, * to their new location, which means a different index, and for faces * also a new face interpolation weights */ if (from == PART_FROM_VERT) { - if (index_dmcache == DMCACHE_NOTFOUND || index_dmcache > mesh->totvert) + if (index_dmcache == DMCACHE_NOTFOUND || index_dmcache > mesh->totvert) { return 0; + } *mapindex = index_dmcache; } @@ -1561,8 +1656,9 @@ static int psys_map_index_on_dm(Mesh *mesh, i = index_dmcache; - if (i == DMCACHE_NOTFOUND || i >= mesh->totface) + if (i == DMCACHE_NOTFOUND || i >= mesh->totface) { return 0; + } *mapindex = i; @@ -1571,10 +1667,12 @@ static int psys_map_index_on_dm(Mesh *mesh, osface = CustomData_get_layer(&mesh->fdata, CD_ORIGSPACE); mface = &mesh->mface[i]; - if (osface == NULL) + if (osface == NULL) { mapfw[0] = mapfw[1] = mapfw[2] = mapfw[3] = 0.0f; - else + } + else { psys_origspace_to_w(&osface[i], mface->v4, fw, mapfw); + } } } @@ -1653,21 +1751,24 @@ void psys_particle_on_dm(Mesh *mesh_final, mvert = mesh_final->mvert; mtface = mesh_final->mtface; - if (mtface) + if (mtface) { mtface += mapindex; + } if (from == PART_FROM_VOLUME) { psys_interpolate_face(mvert, mface, mtface, orcodata, mapfw, vec, tmpnor, utan, vtan, orco); - if (nor) + if (nor) { copy_v3_v3(nor, tmpnor); + } normalize_v3( tmpnor); /* XXX Why not normalize tmpnor before copying it into nor??? -- mont29 */ mul_v3_fl(tmpnor, -foffset); add_v3_v3(vec, tmpnor); } - else + else { psys_interpolate_face(mvert, mface, mtface, orcodata, mapfw, vec, nor, utan, vtan, orco); + } } } @@ -1677,8 +1778,9 @@ float psys_particle_value_from_verts(Mesh *mesh, short from, ParticleData *pa, f int mapindex; if (!psys_map_index_on_dm( - mesh, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, &mapindex, mapfw)) + mesh, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, &mapindex, mapfw)) { return 0.0f; + } return psys_interpolate_value_from_verts(mesh, from, mapindex, mapfw, values); } @@ -1738,17 +1840,20 @@ void psys_emitter_customdata_mask(ParticleSystem *psys, CustomData_MeshMasks *r_ MTex *mtex; int i; - if (!psys->part) + if (!psys->part) { return; + } for (i = 0; i < MAX_MTEX; i++) { mtex = psys->part->mtex[i]; - if (mtex && mtex->mapto && (mtex->texco & TEXCO_UV)) + if (mtex && mtex->mapto && (mtex->texco & TEXCO_UV)) { r_cddata_masks->fmask |= CD_MASK_MTFACE; + } } - if (psys->part->tanfac != 0.0f) + if (psys->part->tanfac != 0.0f) { r_cddata_masks->fmask |= CD_MASK_MTFACE; + } /* ask for vertexgroups if we need them */ for (i = 0; i < PSYS_TOT_VG; i++) { @@ -1783,19 +1888,22 @@ void psys_particle_on_emitter(ParticleSystemModifierData *psmd, { if (psmd && psmd->mesh_final) { if (psmd->psys->part->distr == PART_DISTR_GRID && psmd->psys->part->from != PART_FROM_VERT) { - if (vec) + if (vec) { copy_v3_v3(vec, fuv); + } - if (orco) + if (orco) { copy_v3_v3(orco, fuv); + } return; } /* we cant use the num_dmcache */ psys_particle_on_dm( psmd->mesh_final, from, index, index_dmcache, fuv, foffset, vec, nor, utan, vtan, orco); } - else + else { psys_particle_on_shape(from, index, fuv, vec, nor, utan, vtan, orco); + } } /************************************************/ /* Path Cache */ @@ -1812,8 +1920,9 @@ void precalc_guides(ParticleSimulationData *sim, ListBase *effectors) GuideEffectorData *data; PARTICLE_P; - if (!effectors) + if (!effectors) { return; + } LOOP_PARTICLES { @@ -1835,12 +1944,14 @@ void precalc_guides(ParticleSimulationData *sim, ListBase *effectors) pd_point_from_particle(sim, pa, &state, &point); for (eff = effectors->first; eff; eff = eff->next) { - if (eff->pd->forcefield != PFIELD_GUIDE) + if (eff->pd->forcefield != PFIELD_GUIDE) { continue; + } - if (!eff->guide_data) + if (!eff->guide_data) { eff->guide_data = MEM_callocN(sizeof(GuideEffectorData) * psys->totpart, "GuideEffectorData"); + } data = eff->guide_data + p; @@ -1875,34 +1986,39 @@ int do_guides(Depsgraph *depsgraph, float guidetime, radius, weight, angle, totstrength = 0.0f; float vec_to_point[3]; - if (effectors) + if (effectors) { for (eff = effectors->first; eff; eff = eff->next) { pd = eff->pd; - if (pd->forcefield != PFIELD_GUIDE) + if (pd->forcefield != PFIELD_GUIDE) { continue; + } data = eff->guide_data + index; - if (data->strength <= 0.0f) + if (data->strength <= 0.0f) { continue; + } guidetime = time / (1.0f - pd->free_end); - if (guidetime > 1.0f) + if (guidetime > 1.0f) { continue; + } cu = (Curve *)eff->ob->data; if (pd->flag & PFIELD_GUIDE_PATH_ADD) { if (where_on_path( eff->ob, data->strength * guidetime, guidevec, guidedir, NULL, &radius, &weight) == - 0) + 0) { return 0; + } } else { - if (where_on_path(eff->ob, guidetime, guidevec, guidedir, NULL, &radius, &weight) == 0) + if (where_on_path(eff->ob, guidetime, guidevec, guidedir, NULL, &radius, &weight) == 0) { return 0; + } } mul_m4_v3(eff->ob->obmat, guidevec); @@ -1926,24 +2042,26 @@ int do_guides(Depsgraph *depsgraph, } /* curve taper */ - if (cu->taperobj) + if (cu->taperobj) { mul_v3_fl(vec_to_point, BKE_displist_calc_taper(depsgraph, eff->scene, cu->taperobj, (int)(data->strength * guidetime * 100.0f), 100)); - + } else { /* curve size*/ if (cu->flag & CU_PATH_RADIUS) { mul_v3_fl(vec_to_point, radius); } } - if (clumpcurve) + if (clumpcurve) { curvemapping_changed_all(clumpcurve); - if (roughcurve) + } + if (roughcurve) { curvemapping_changed_all(roughcurve); + } { ParticleKey key; @@ -1981,20 +2099,23 @@ int do_guides(Depsgraph *depsgraph, add_v3_v3(vec_to_point, guidevec); - //sub_v3_v3v3(pa_loc, pa_loc, pa_zero); + // sub_v3_v3v3(pa_loc, pa_loc, pa_zero); madd_v3_v3fl(effect, vec_to_point, data->strength); madd_v3_v3fl(veffect, guidedir, data->strength); totstrength += data->strength; - if (pd->flag & PFIELD_GUIDE_PATH_WEIGHT) + if (pd->flag & PFIELD_GUIDE_PATH_WEIGHT) { totstrength *= weight; + } } + } if (totstrength != 0.0f) { - if (totstrength > 1.0f) + if (totstrength > 1.0f) { mul_v3_fl(effect, 1.0f / totstrength); + } CLAMP(totstrength, 0.0f, 1.0f); - //add_v3_v3(effect, pa_zero); + // add_v3_v3(effect, pa_zero); interp_v3_v3v3(state->co, state->co, effect, totstrength); normalize_v3(veffect); @@ -2022,8 +2143,9 @@ static void do_path_effectors(ParticleSimulationData *sim, EffectedPoint epoint; /* Don't apply effectors for dynamic hair, otherwise the effectors don't get applied twice. */ - if (sim->psys->flag & PSYS_HAIR_DYNAMICS) + if (sim->psys->flag & PSYS_HAIR_DYNAMICS) { return; + } copy_v3_v3(eff_key.co, (ca - 1)->co); copy_v3_v3(eff_key.vel, (ca - 1)->vel); @@ -2045,13 +2167,15 @@ static void do_path_effectors(ParticleSimulationData *sim, normalize_v3(force); - if (k < steps) + if (k < steps) { sub_v3_v3v3(vec, (ca + 1)->co, ca->co); + } madd_v3_v3v3fl(ca->co, (ca - 1)->co, force, *length); - if (k < steps) + if (k < steps) { *length = len_v3(vec); + } } static void offset_child(ChildParticle *cpa, ParticleKey *par, @@ -2071,8 +2195,9 @@ static void offset_child(ChildParticle *cpa, mul_qt_v3(par_rot, child->co); copy_qt_qt(child->rot, par_rot); } - else + else { unit_qt(child->rot); + } add_v3_v3(child->co, par->co); } @@ -2089,12 +2214,14 @@ float *psys_cache_vgroup(Mesh *mesh, ParticleSystem *psys, int vgroup) int totvert = mesh->totvert, i; vg = MEM_callocN(sizeof(float) * totvert, "vg_cache"); if (psys->vg_neg & (1 << vgroup)) { - for (i = 0; i < totvert; i++) + for (i = 0; i < totvert; i++) { vg[i] = 1.0f - defvert_find_weight(&dvert[i], psys->vgroup[vgroup] - 1); + } } else { - for (i = 0; i < totvert; i++) + for (i = 0; i < totvert; i++) { vg[i] = defvert_find_weight(&dvert[i], psys->vgroup[vgroup] - 1); + } } } } @@ -2112,8 +2239,9 @@ void psys_find_parents(ParticleSimulationData *sim, const bool use_render_params int from = PART_FROM_FACE; totparent = (int)(totchild * part->parents * 0.3f); - if (use_render_params && part->child_nbr && part->ren_child_nbr) + if (use_render_params && part->child_nbr && part->ren_child_nbr) { totparent *= (float)part->child_nbr / (float)part->ren_child_nbr; + } /* hard limit, workaround for it being ignored above */ if (sim->psys->totpart < totparent) { @@ -2126,7 +2254,8 @@ void psys_find_parents(ParticleSimulationData *sim, const bool use_render_params psys_particle_on_emitter( sim->psmd, from, cpa->num, DMCACHE_ISCHILD, cpa->fuv, cpa->foffset, co, 0, 0, 0, orco); - /* Check if particle doesn't exist because of texture influence. Insert only existing particles into kdtree. */ + /* Check if particle doesn't exist because of texture influence. + * Insert only existing particles into kdtree. */ get_cpa_texture(sim->psmd->mesh_final, psys, part, @@ -2175,8 +2304,9 @@ static bool psys_thread_context_init_path(ParticleThreadContext *ctx, ParticleEditSettings *pset = &scene->toolsettings->particle; if ((use_render_params == 0) && - (psys_orig_edit_get(psys) == NULL || pset->flag & PE_DRAW_PART) == 0) + (psys_orig_edit_get(psys) == NULL || pset->flag & PE_DRAW_PART) == 0) { totchild = 0; + } segments = 1 << pset->draw_step; } @@ -2184,30 +2314,35 @@ static bool psys_thread_context_init_path(ParticleThreadContext *ctx, if (totchild && part->childtype == PART_CHILD_FACES) { totparent = (int)(totchild * part->parents * 0.3f); - if (use_render_params && part->child_nbr && part->ren_child_nbr) + if (use_render_params && part->child_nbr && part->ren_child_nbr) { totparent *= (float)part->child_nbr / (float)part->ren_child_nbr; + } /* part->parents could still be 0 so we can't test with totparent */ between = 1; } - if (use_render_params) + if (use_render_params) { segments = 1 << part->ren_step; + } else { totchild = (int)((float)totchild * (float)part->disp / 100.0f); totparent = MIN2(totparent, totchild); } - if (totchild == 0) + if (totchild == 0) { return false; + } /* fill context values */ ctx->between = between; ctx->segments = segments; - if (ELEM(part->kink, PART_KINK_SPIRAL)) + if (ELEM(part->kink, PART_KINK_SPIRAL)) { ctx->extra_segments = max_ii(part->kink_extra_steps, 1); - else + } + else { ctx->extra_segments = 0; + } ctx->totchild = totchild; ctx->totparent = totparent; ctx->parent_pass = 0; @@ -2224,8 +2359,9 @@ static bool psys_thread_context_init_path(ParticleThreadContext *ctx, ctx->vg_rough2 = psys_cache_vgroup(ctx->mesh, psys, PSYS_VG_ROUGH2); ctx->vg_roughe = psys_cache_vgroup(ctx->mesh, psys, PSYS_VG_ROUGHE); ctx->vg_twist = psys_cache_vgroup(ctx->mesh, psys, PSYS_VG_TWIST); - if (psys->part->flag & PART_CHILD_EFFECT) + if (psys->part->flag & PART_CHILD_EFFECT) { ctx->vg_effector = psys_cache_vgroup(ctx->mesh, psys, PSYS_VG_EFFECTOR); + } /* prepare curvemapping tables */ if ((part->child_flag & PART_CHILD_USE_CLUMP_CURVE) && part->clumpcurve) { @@ -2284,8 +2420,9 @@ static void psys_thread_create_path(ParticleTask *task, int k, cpa_num; short cpa_from; - if (!pcache) + if (!pcache) { return; + } if (ctx->between) { ParticleData *pa = psys->particles + cpa->pa[0]; @@ -2308,10 +2445,12 @@ static void psys_thread_create_path(ParticleTask *task, w++; } - if (!needupdate) + if (!needupdate) { return; - else + } + else { memset(child_keys, 0, sizeof(*child_keys) * (ctx->segments + 1)); + } } /* get parent paths */ @@ -2334,7 +2473,8 @@ static void psys_thread_create_path(ParticleTask *task, const ParticleCacheKey *key_w_last = pcache_key_segment_endpoint_safe(key[w]); float d; if (part->flag & PART_CHILD_LONG_HAIR) { - /* For long hair use tip distance/root distance as parting factor instead of root to tip angle. */ + /* For long hair use tip distance/root distance as parting + * factor instead of root to tip angle. */ float d1 = len_v3v3(key[0]->co, key[w]->co); float d2 = len_v3v3(key_0_last->co, key_w_last->co); @@ -2350,20 +2490,24 @@ static void psys_thread_create_path(ParticleTask *task, d = RAD2DEGF(saacos(dot_v3v3(v1, v2))); } - if (p_max > p_min) + if (p_max > p_min) { d = (d - p_min) / (p_max - p_min); - else + } + else { d = (d - p_min) <= 0.f ? 0.f : 1.f; + } CLAMP(d, 0.f, 1.f); - if (d > 0.f) + if (d > 0.f) { weight[w] *= (1.f - d); + } } wsum += weight[w]; } - for (w = 0; w < 4; w++) + for (w = 0; w < 4; w++) { weight[w] /= wsum; + } interp_v4_v4v4(weight, cpa->w, weight, p_fac); } @@ -2380,8 +2524,9 @@ static void psys_thread_create_path(ParticleTask *task, mul_m4_v3(ob->obmat, co); - for (w = 0; w < 4; w++) + for (w = 0; w < 4; w++) { sub_v3_v3v3(off1[w], co, key[w]->co); + } psys_mat_hair_to_global(ob, ctx->sim.psmd->mesh_final, psys->part->from, pa, hairmat); } @@ -2389,8 +2534,9 @@ static void psys_thread_create_path(ParticleTask *task, ParticleData *pa = psys->particles + cpa->parent; float co[3]; if (ctx->editupdate) { - if (!(edit->points[cpa->parent].flag & PEP_EDIT_RECALC)) + if (!(edit->points[cpa->parent].flag & PEP_EDIT_RECALC)) { return; + } memset(child_keys, 0, sizeof(*child_keys) * (ctx->segments + 1)); } @@ -2413,8 +2559,9 @@ static void psys_thread_create_path(ParticleTask *task, pa->num_dmcache; /* XXX hack to avoid messed up particle num and subsequent crash (#40733) */ - if (cpa_num > ctx->sim.psmd->mesh_final->totface) + if (cpa_num > ctx->sim.psmd->mesh_final->totface) { cpa_num = 0; + } cpa_fuv = pa->fuv; psys_particle_on_emitter(ctx->sim.psmd, @@ -2456,8 +2603,9 @@ static void psys_thread_create_path(ParticleTask *task, if (part->flag & PART_CHILD_LONG_HAIR) { /* Use parent rotation (in addition to emission location) to determine child offset. */ - if (k) + if (k) { mul_qt_v3((key[w] + k)->rot, off2[w]); + } /* Fade the effect of rotation for even lengths in the end */ project_v3_v3v3(dvec, off2[w], (key[w] + k)->vel); @@ -2539,7 +2687,8 @@ static void psys_thread_create_path(ParticleTask *task, pa = &psys->particles[cpa->parent]; par = pcache[cpa->parent]; - /* If particle is unexisting, try to pick a viable parent from particles used for interpolation. */ + /* If particle is unexisting, try to pick a viable parent from particles + * used for interpolation. */ for (k = 0; k < 4 && pa && (pa->flag & PARS_UNEXIST); k++) { if (cpa->pa[k] >= 0) { pa = &psys->particles[cpa->pa[k]]; @@ -2547,8 +2696,9 @@ static void psys_thread_create_path(ParticleTask *task, } } - if (pa->flag & PARS_UNEXIST) + if (pa->flag & PARS_UNEXIST) { pa = NULL; + } } if (pa) { @@ -2570,13 +2720,15 @@ static void psys_thread_create_path(ParticleTask *task, psys_apply_child_modifiers( ctx, &modifiers, cpa, &ptex, orco, hairmat, child_keys, par, par_orco); } - else + else { zero_v3(par_orco); + } } /* Hide virtual parents */ - if (i < ctx->totparent) + if (i < ctx->totparent) { child_keys->segments = -1; + } } static void exec_child_path_cache(TaskPool *__restrict UNUSED(pool), @@ -2609,12 +2761,14 @@ void psys_cache_child_paths(ParticleSimulationData *sim, int numtasks_parent, numtasks_child; int i, totchild, totparent; - if (sim->psys->flag & PSYS_GLOBAL_HAIR) + if (sim->psys->flag & PSYS_GLOBAL_HAIR) { return; + } /* create a task pool for child path tasks */ - if (!psys_thread_context_init_path(&ctx, sim, sim->scene, cfra, editupdate, use_render_params)) + if (!psys_thread_context_init_path(&ctx, sim, sim->scene, cfra, editupdate, use_render_params)) { return; + } task_scheduler = BLI_task_scheduler_get(); task_pool = BLI_task_pool_create(task_scheduler, &ctx); @@ -2744,12 +2898,15 @@ void psys_cache_paths(ParticleSimulationData *sim, float cfra, const bool use_re int keyed, baked; /* we don't have anything valid to create paths from so let's quit here */ - if ((psys->flag & PSYS_HAIR_DONE || psys->flag & PSYS_KEYED || psys->pointcache) == 0) + if ((psys->flag & PSYS_HAIR_DONE || psys->flag & PSYS_KEYED || psys->pointcache) == 0) { return; + } - if (psys_in_edit_mode(sim->depsgraph, psys)) - if ((psys->edit == NULL || pset->flag & PE_DRAW_PART) == 0) + if (psys_in_edit_mode(sim->depsgraph, psys)) { + if ((psys->edit == NULL || pset->flag & PE_DRAW_PART) == 0) { return; + } + } keyed = psys->flag & PSYS_KEYED; baked = psys->pointcache->mem_cache.first && psys->part->type != PART_HAIR; @@ -2761,15 +2918,18 @@ void psys_cache_paths(ParticleSimulationData *sim, float cfra, const bool use_re psys->lattice_deform_data = psys_create_lattice_deform_data(sim); ma = give_current_material(sim->ob, psys->part->omat); - if (ma && (psys->part->draw_col == PART_DRAW_COL_MAT)) + if (ma && (psys->part->draw_col == PART_DRAW_COL_MAT)) { copy_v3_v3(col, &ma->r); + } if ((psys->flag & PSYS_GLOBAL_HAIR) == 0) { - if ((psys->part->flag & PART_CHILD_EFFECT) == 0) + if ((psys->part->flag & PART_CHILD_EFFECT) == 0) { vg_effector = psys_cache_vgroup(psmd->mesh_final, psys, PSYS_VG_EFFECTOR); + } - if (!psys->totchild) + if (!psys->totchild) { vg_length = psys_cache_vgroup(psmd->mesh_final, psys, PSYS_VG_LENGTH); + } } /* ensure we have tessfaces to be used for mapping */ @@ -2783,8 +2943,9 @@ void psys_cache_paths(ParticleSimulationData *sim, float cfra, const bool use_re if (!psys->totchild) { psys_get_texture(sim, pa, &ptex, PAMAP_LENGTH, 0.f); pa_length = ptex.length * (1.0f - part->randlength * psys_frand(psys, psys->seed + p)); - if (vg_length) + if (vg_length) { pa_length *= psys_particle_value_from_verts(psmd->mesh_final, part->from, pa, vg_length); + } } pind.keyed = keyed; @@ -2833,10 +2994,12 @@ void psys_cache_paths(ParticleSimulationData *sim, float cfra, const bool use_re /* dynamic hair is in object space */ /* keyed and baked are already in global space */ - if (hair_mesh) + if (hair_mesh) { mul_m4_v3(sim->ob->obmat, ca->co); - else if (!keyed && !baked && !(psys->flag & PSYS_GLOBAL_HAIR)) + } + else if (!keyed && !baked && !(psys->flag & PSYS_GLOBAL_HAIR)) { mul_m4_v3(hairmat, ca->co); + } copy_v3_v3(ca->col, col); } @@ -2855,21 +3018,23 @@ void psys_cache_paths(ParticleSimulationData *sim, float cfra, const bool use_re /* apply effectors */ if ((psys->part->flag & PART_CHILD_EFFECT) == 0) { float effector = 1.0f; - if (vg_effector) + if (vg_effector) { effector *= psys_particle_value_from_verts( psmd->mesh_final, psys->part->from, pa, vg_effector); + } sub_v3_v3v3(vec, (cache[p] + 1)->co, cache[p]->co); length = len_v3(vec); - for (k = 1, ca = cache[p] + 1; k <= segments; k++, ca++) + for (k = 1, ca = cache[p] + 1; k <= segments; k++, ca++) { do_path_effectors( sim, p, ca, k, segments, cache[p]->co, effector, dfra, cfra, &length, vec); + } } /* apply guide curves to path data */ if (sim->psys->effectors && (psys->part->flag & PART_CHILD_EFFECT) == 0) { - for (k = 0, ca = cache[p]; k <= segments; k++, ca++) + for (k = 0, ca = cache[p]; k <= segments; k++, ca++) { /* ca is safe to cast, since only co and vel are used */ do_guides(sim->depsgraph, sim->psys->part, @@ -2877,12 +3042,14 @@ void psys_cache_paths(ParticleSimulationData *sim, float cfra, const bool use_re (ParticleKey *)ca, p, (float)k / (float)segments); + } } /* lattices have to be calculated separately to avoid mixups between effector calculations */ if (psys->lattice_deform_data) { - for (k = 0, ca = cache[p]; k <= segments; k++, ca++) + for (k = 0, ca = cache[p]; k <= segments; k++, ca++) { calc_latt_deform(psys->lattice_deform_data, ca->co, psys->lattice_strength); + } } } @@ -2890,14 +3057,16 @@ void psys_cache_paths(ParticleSimulationData *sim, float cfra, const bool use_re for (k = 1, ca = cache[p] + 1; k <= segments; k++, ca++) { cache_key_incremental_rotation(ca, ca - 1, ca - 2, prev_tangent, k); - if (k == segments) + if (k == segments) { copy_qt_qt(ca->rot, (ca - 1)->rot); + } /* set velocity */ sub_v3_v3v3(ca->vel, ca->co, (ca - 1)->co); - if (k == 1) + if (k == 1) { copy_v3_v3((ca - 1)->vel, ca->vel); + } ca->time = (float)k / (float)segments; } @@ -2918,11 +3087,13 @@ void psys_cache_paths(ParticleSimulationData *sim, float cfra, const bool use_re psys->lattice_deform_data = NULL; } - if (vg_effector) + if (vg_effector) { MEM_freeN(vg_effector); + } - if (vg_length) + if (vg_length) { MEM_freeN(vg_length); + } } typedef struct CacheEditrPathsIterData { @@ -3017,14 +3188,16 @@ static void psys_cache_edit_paths_iter(void *__restrict iter_data_v, if (k) { cache_key_incremental_rotation(ca, ca - 1, ca - 2, prev_tangent, k); - if (k == segments) + if (k == segments) { copy_qt_qt(ca->rot, (ca - 1)->rot); + } /* set velocity */ sub_v3_v3v3(ca->vel, ca->co, (ca - 1)->co); - if (k == 1) + if (k == 1) { copy_v3_v3((ca - 1)->vel, ca->vel); + } } } else { @@ -3143,7 +3316,7 @@ void psys_cache_edit_paths(Depsgraph *depsgraph, iter_data.use_weight = use_weight; if (use_weight) { - ; /* use weight painting colors now... */ + /* use weight painting colors now... */ } else { iter_data.sel_col[0] = (float)edit->sel_col[0] / 255.0f; @@ -3197,14 +3370,18 @@ void copy_particle_key(ParticleKey *to, ParticleKey *from, int time) } void psys_get_from_key(ParticleKey *key, float loc[3], float vel[3], float rot[4], float *time) { - if (loc) + if (loc) { copy_v3_v3(loc, key->co); - if (vel) + } + if (vel) { copy_v3_v3(vel, key->vel); - if (rot) + } + if (rot) { copy_qt_qt(rot, key->rot); - if (time) + } + if (time) { *time = key->time; + } } static void triatomat(float *v1, float *v2, float *v3, float (*uv)[2], float mat[4][4]) @@ -3236,8 +3413,9 @@ static void triatomat(float *v1, float *v2, float *v3, float (*uv)[2], float mat mat[1][2] = w1 * (v2[2] - v1[2]) + w2 * (v3[2] - v1[2]); normalize_v3(mat[1]); } - else + else { mat[1][0] = mat[1][1] = mat[1][2] = 0.0f; + } } else { sub_v3_v3v3(mat[1], v2, v1); @@ -3271,8 +3449,9 @@ static void psys_face_mat(Object *ob, Mesh *mesh, ParticleData *pa, float mat[4] /* ugly hack to use non-transformed orcos, since only those * give symmetric results for mirroring in particle mode */ - if (CustomData_get_layer(&mesh->vdata, CD_ORIGINDEX)) + if (CustomData_get_layer(&mesh->vdata, CD_ORIGINDEX)) { BKE_mesh_orco_verts_transform(ob->data, v, 3, 1); + } } else { copy_v3_v3(v[0], mesh->mvert[mface->v1].co); @@ -3309,8 +3488,9 @@ void psys_mat_hair_to_orco( mesh, from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, vec, 0, 0, 0, orco); /* see psys_face_mat for why this function is called */ - if (CustomData_get_layer(&mesh->vdata, CD_ORIGINDEX)) + if (CustomData_get_layer(&mesh->vdata, CD_ORIGINDEX)) { BKE_mesh_orco_verts_transform(ob->data, &orco, 1, 1); + } copy_v3_v3(hairmat[3], orco); } @@ -3342,16 +3522,18 @@ ModifierData *object_add_particle_system(Main *bmain, Scene *scene, Object *ob, ModifierData *md; ParticleSystemModifierData *psmd; - if (!ob || ob->type != OB_MESH) + if (!ob || ob->type != OB_MESH) { return NULL; + } if (name == NULL) { name = DATA_("ParticleSettings"); } psys = ob->particlesystem.first; - for (; psys; psys = psys->next) + for (; psys; psys = psys->next) { psys->flag &= ~PSYS_CURRENT; + } psys = MEM_callocN(sizeof(ParticleSystem), "particle_system"); psys->pointcache = BKE_ptcache_add(&psys->ptcaches); @@ -3383,22 +3565,27 @@ void object_remove_particle_system(Main *bmain, Scene *UNUSED(scene), Object *ob ParticleSystemModifierData *psmd; ModifierData *md; - if (!psys) + if (!psys) { return; + } /* clear all other appearances of this pointer (like on smoke flow modifier) */ if ((md = modifiers_findByType(ob, eModifierType_Smoke))) { SmokeModifierData *smd = (SmokeModifierData *)md; - if ((smd->type == MOD_SMOKE_TYPE_FLOW) && smd->flow && smd->flow->psys) - if (smd->flow->psys == psys) + if ((smd->type == MOD_SMOKE_TYPE_FLOW) && smd->flow && smd->flow->psys) { + if (smd->flow->psys == psys) { smd->flow->psys = NULL; + } + } } if ((md = modifiers_findByType(ob, eModifierType_DynamicPaint))) { DynamicPaintModifierData *pmd = (DynamicPaintModifierData *)md; - if (pmd->brush && pmd->brush->psys) - if (pmd->brush->psys == psys) + if (pmd->brush && pmd->brush->psys) { + if (pmd->brush->psys == psys) { pmd->brush->psys = NULL; + } + } } /* clear modifier */ @@ -3413,10 +3600,12 @@ void object_remove_particle_system(Main *bmain, Scene *UNUSED(scene), Object *ob } psys_free(ob, psys); - if (ob->particlesystem.first) + if (ob->particlesystem.first) { ((ParticleSystem *)ob->particlesystem.first)->flag |= PSYS_CURRENT; - else + } + else { ob->mode &= ~OB_MODE_PARTICLE_EDIT; + } DEG_relations_tag_update(bmain); DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); @@ -3495,8 +3684,9 @@ static void default_particle_settings(ParticleSettings *part) part->color_vec_max = 1.f; part->draw_col = PART_DRAW_COL_MAT; - if (!part->effector_weights) + if (!part->effector_weights) { part->effector_weights = BKE_effector_add_weights(NULL); + } part->omat = 1; part->use_modifier_stack = false; @@ -3563,8 +3753,10 @@ void BKE_particlesettings_twist_curve_init(ParticleSettings *part) } /** - * Only copy internal data of ParticleSettings ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of ParticleSettings ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * @@ -3631,11 +3823,13 @@ static int get_particle_uv(Mesh *mesh, tf = CustomData_get_layer_named(&mesh->fdata, CD_MTFACE, name); - if (tf == NULL) + if (tf == NULL) { tf = mesh->mtface; + } - if (tf == NULL) + if (tf == NULL) { return 0; + } if (pa) { i = ELEM(pa->num_dmcache, DMCACHE_NOTFOUND, DMCACHE_ISCHILD) ? pa->num : pa->num_dmcache; @@ -3739,8 +3933,9 @@ static void get_cpa_texture(Mesh *mesh, if (ELEM(texco, TEXCO_UV, TEXCO_ORCO) && (ELEM(part->from, PART_FROM_FACE, PART_FROM_VOLUME) == 0 || - part->distr == PART_DISTR_GRID)) + part->distr == PART_DISTR_GRID)) { texco = TEXCO_GLOB; + } switch (texco) { case TEXCO_GLOB: @@ -3748,8 +3943,9 @@ static void get_cpa_texture(Mesh *mesh, break; case TEXCO_OBJECT: copy_v3_v3(texvec, par->state.co); - if (mtex->object) + if (mtex->object) { mul_m4_v3(mtex->object->imat, texvec); + } break; case TEXCO_UV: if (fw && get_particle_uv(mesh, @@ -3776,9 +3972,10 @@ static void get_cpa_texture(Mesh *mesh, externtex(mtex, texvec, &value, rgba, rgba + 1, rgba + 2, rgba + 3, 0, NULL, false, false); - if ((event & mtex->mapto) & PAMAP_ROUGH) + if ((event & mtex->mapto) & PAMAP_ROUGH) { ptex->rough1 = ptex->rough2 = ptex->roughe = texture_value_blend( def, ptex->rough1, value, mtex->roughfac, blend); + } SET_PARTICLE_TEXTURE(PAMAP_LENGTH, ptex->length, mtex->lengthfac); SET_PARTICLE_TEXTURE(PAMAP_CLUMP, ptex->clump, mtex->clumpfac); @@ -3824,8 +4021,9 @@ void psys_get_texture( short texco = mtex->texco; if (texco == TEXCO_UV && (ELEM(part->from, PART_FROM_FACE, PART_FROM_VOLUME) == 0 || - part->distr == PART_DISTR_GRID)) + part->distr == PART_DISTR_GRID)) { texco = TEXCO_GLOB; + } switch (texco) { case TEXCO_GLOB: @@ -3833,8 +4031,9 @@ void psys_get_texture( break; case TEXCO_OBJECT: copy_v3_v3(texvec, pa->state.co); - if (mtex->object) + if (mtex->object) { mul_m4_v3(mtex->object->imat, texvec); + } break; case TEXCO_UV: if (get_particle_uv(sim->psmd->mesh_final, @@ -3865,20 +4064,25 @@ void psys_get_texture( BKE_mesh_texspace_calc(me); } sub_v3_v3(texvec, me->loc); - if (me->size[0] != 0.0f) + if (me->size[0] != 0.0f) { texvec[0] /= me->size[0]; - if (me->size[1] != 0.0f) + } + if (me->size[1] != 0.0f) { texvec[1] /= me->size[1]; - if (me->size[2] != 0.0f) + } + if (me->size[2] != 0.0f) { texvec[2] /= me->size[2]; + } break; case TEXCO_PARTICLE: /* texture coordinates in range [-1, 1] */ texvec[0] = 2.f * (cfra - pa->time) / (pa->dietime - pa->time) - 1.f; - if (sim->psys->totpart > 0) + if (sim->psys->totpart > 0) { texvec[1] = 2.f * (float)(pa - sim->psys->particles) / (float)sim->psys->totpart - 1.f; - else + } + else { texvec[1] = 0.0f; + } texvec[2] = 0.f; break; } @@ -3894,8 +4098,9 @@ void psys_get_texture( ptex->time += timefac * ((flip) ? 1.0f - value : value); setvars |= MAP_PA_TIME; } - else + else { ptex->time = texture_value_blend(def, ptex->time, value, mtex->timefac, blend); + } } SET_PARTICLE_TEXTURE(PAMAP_LIFE, ptex->life, mtex->lifefac); SET_PARTICLE_TEXTURE(PAMAP_DENS, ptex->exist, mtex->padensfac); @@ -3949,10 +4154,12 @@ float psys_get_child_time( life = pa->lifetime; } - if (birthtime) + if (birthtime) { *birthtime = time; - if (dietime) + } + if (dietime) { *dietime = time + life; + } return (cfra - time) / life; } @@ -3978,8 +4185,9 @@ float psys_get_child_size(ParticleSystem *psys, size *= part->childsize; - if (part->childrandsize != 0.0f) + if (part->childrandsize != 0.0f) { size *= 1.0f - part->childrandsize * psys_frand(psys, cpa - psys->child + 26); + } return size; } @@ -4007,33 +4215,42 @@ static void get_child_modifier_parameters(ParticleSettings *part, PAMAP_DENS | PAMAP_CHILD, psys->cfra); - if (ptex->exist < psys_frand(psys, i + 24)) + if (ptex->exist < psys_frand(psys, i + 24)) { return; + } - if (ctx->vg_length) + if (ctx->vg_length) { ptex->length *= psys_interpolate_value_from_verts( ctx->mesh, cpa_from, cpa_num, cpa_fuv, ctx->vg_length); - if (ctx->vg_clump) + } + if (ctx->vg_clump) { ptex->clump *= psys_interpolate_value_from_verts( ctx->mesh, cpa_from, cpa_num, cpa_fuv, ctx->vg_clump); - if (ctx->vg_kink) + } + if (ctx->vg_kink) { ptex->kink_freq *= psys_interpolate_value_from_verts( ctx->mesh, cpa_from, cpa_num, cpa_fuv, ctx->vg_kink); - if (ctx->vg_rough1) + } + if (ctx->vg_rough1) { ptex->rough1 *= psys_interpolate_value_from_verts( ctx->mesh, cpa_from, cpa_num, cpa_fuv, ctx->vg_rough1); - if (ctx->vg_rough2) + } + if (ctx->vg_rough2) { ptex->rough2 *= psys_interpolate_value_from_verts( ctx->mesh, cpa_from, cpa_num, cpa_fuv, ctx->vg_rough2); - if (ctx->vg_roughe) + } + if (ctx->vg_roughe) { ptex->roughe *= psys_interpolate_value_from_verts( ctx->mesh, cpa_from, cpa_num, cpa_fuv, ctx->vg_roughe); - if (ctx->vg_effector) + } + if (ctx->vg_effector) { ptex->effector *= psys_interpolate_value_from_verts( ctx->mesh, cpa_from, cpa_num, cpa_fuv, ctx->vg_effector); - if (ctx->vg_twist) + } + if (ctx->vg_twist) { ptex->twist *= psys_interpolate_value_from_verts( ctx->mesh, cpa_from, cpa_num, cpa_fuv, ctx->vg_twist); + } } /* get's hair (or keyed) particles state at the "path time" specified in state->time */ void psys_get_particle_on_path(ParticleSimulationData *sim, @@ -4113,14 +4330,15 @@ void psys_get_particle_on_path(ParticleSimulationData *sim, /* TODO: proper velocity handling */ } - if (psys->lattice_deform_data && edit == 0) + if (psys->lattice_deform_data && edit == 0) { calc_latt_deform(psys->lattice_deform_data, state->co, psys->lattice_strength); + } } } } } else if (totchild) { - //invert_m4_m4(imat, ob->obmat); + // invert_m4_m4(imat, ob->obmat); /* interpolate childcache directly if it exists */ if (psys->childcache) { @@ -4135,8 +4353,9 @@ void psys_get_particle_on_path(ParticleSimulationData *sim, cpa = psys->child + p - totpart; - if (state->time < 0.0f) + if (state->time < 0.0f) { t = psys_get_child_time(psys, cpa, -state->time, NULL, NULL); + } if (totchild && part->childtype == PART_CHILD_FACES) { /* part->parents could still be 0 so we can't test with totparent */ @@ -4163,10 +4382,11 @@ void psys_get_particle_on_path(ParticleSimulationData *sim, psys_particle_on_emitter( psmd, cpa_from, cpa_num, DMCACHE_ISCHILD, cpa->fuv, foffset, co, 0, 0, 0, orco); - /* we need to save the actual root position of the child for positioning it accurately to the surface of the emitter */ - //copy_v3_v3(cpa_1st, co); + /* We need to save the actual root position of the child for + * positioning it accurately to the surface of the emitter. */ + // copy_v3_v3(cpa_1st, co); - //mul_m4_v3(ob->obmat, cpa_1st); + // mul_m4_v3(ob->obmat, cpa_1st); pa = psys->particles + cpa->parent; @@ -4181,10 +4401,12 @@ void psys_get_particle_on_path(ParticleSimulationData *sim, 0, 0, par_orco); - if (part->type == PART_HAIR) + if (part->type == PART_HAIR) { psys_mat_hair_to_global(sim->ob, sim->psmd->mesh_final, psys->part->from, pa, hairmat); - else + } + else { unit_m4(hairmat); + } pa = 0; } @@ -4248,7 +4470,7 @@ void psys_get_particle_on_path(ParticleSimulationData *sim, w++; } /* apply offset for correct positioning */ - //add_v3_v3(state->co, cpa_1st); + // add_v3_v3(state->co, cpa_1st); } else { /* offset the child from the parent position */ @@ -4257,8 +4479,9 @@ void psys_get_particle_on_path(ParticleSimulationData *sim, par = keys; - if (vel) + if (vel) { copy_particle_key(&tstate, state, 1); + } /* apply different deformations to the child path */ ParticleChildModifierContext modifier_ctx = {NULL}; @@ -4312,12 +4535,14 @@ int psys_get_particle_state(ParticleSimulationData *sim, int p, ParticleKey *sta cfra = state->time > 0 ? state->time : DEG_get_ctime(sim->depsgraph); if (p >= totpart) { - if (!psys->totchild) + if (!psys->totchild) { return 0; + } if (part->childtype == PART_CHILD_FACES) { - if (!(psys->flag & PSYS_KEYED)) + if (!(psys->flag & PSYS_KEYED)) { return 0; + } cpa = psys->child + p - totpart; @@ -4388,20 +4613,24 @@ int psys_get_particle_state(ParticleSimulationData *sim, int p, ParticleKey *sta do_child_modifiers(&modifier_ctx, mat, state, t); - if (psys->lattice_deform_data) + if (psys->lattice_deform_data) { calc_latt_deform(psys->lattice_deform_data, state->co, psys->lattice_strength); + } } else { - if (pa->state.time == cfra || ELEM(part->phystype, PART_PHYS_NO, PART_PHYS_KEYED)) + if (pa->state.time == cfra || ELEM(part->phystype, PART_PHYS_NO, PART_PHYS_KEYED)) { copy_particle_key(state, &pa->state, 1); - else if (pa->prev_state.time == cfra) + } + else if (pa->prev_state.time == cfra) { copy_particle_key(state, &pa->prev_state, 1); + } else { float dfra, frs_sec = sim->scene->r.frs_sec; /* let's interpolate to try to be as accurate as possible */ if (pa->state.time + 2.f >= state->time && pa->prev_state.time - 2.f <= state->time) { if (pa->prev_state.time >= pa->state.time || pa->prev_state.time < 0.f) { - /* prev_state is wrong so let's not use it, this can happen at frames 1, 0 or particle birth */ + /* prev_state is wrong so let's not use it, + * this can happen at frames 1, 0 or particle birth. */ dfra = state->time - pa->state.time; copy_particle_key(state, &pa->state, 1); @@ -4442,13 +4671,15 @@ int psys_get_particle_state(ParticleSimulationData *sim, int p, ParticleKey *sta madd_v3_v3v3fl(state->co, state->co, state->vel, dfra / frs_sec); } else { - /* extrapolating over big ranges is not accurate so let's just give something close to reasonable back */ + /* Extrapolating over big ranges is not accurate + * so let's just give something close to reasonable back. */ copy_particle_key(state, &pa->state, 0); } } - if (sim->psys->lattice_deform_data) + if (sim->psys->lattice_deform_data) { calc_latt_deform(sim->psys->lattice_deform_data, state->co, psys->lattice_strength); + } } return 1; @@ -4518,8 +4749,9 @@ void psys_get_dupli_texture(ParticleSystem *psys, num = pa->num_dmcache; - if (num == DMCACHE_NOTFOUND) + if (num == DMCACHE_NOTFOUND) { num = pa->num; + } if (num >= psmd->mesh_final->totface) { /* happens when simplify is enabled @@ -4554,10 +4786,11 @@ void psys_get_dupli_path_transform(ParticleSimulationData *sim, sub_v3_v3v3(vec, (cache + cache->segments)->co, cache->co); len = normalize_v3(vec); - if (pa == NULL && psys->part->childflat != PART_CHILD_FACES) + if (pa == NULL && psys->part->childflat != PART_CHILD_FACES) { pa = psys->particles + cpa->pa[0]; + } - if (pa) + if (pa) { psys_particle_on_emitter(psmd, sim->psys->part->from, pa->num, @@ -4569,7 +4802,8 @@ void psys_get_dupli_path_transform(ParticleSimulationData *sim, 0, 0, 0); - else + } + else { psys_particle_on_emitter(psmd, PART_FROM_FACE, cpa->num, @@ -4581,6 +4815,7 @@ void psys_get_dupli_path_transform(ParticleSimulationData *sim, 0, 0, 0); + } if (psys->part->rotmode == PART_ROT_VEL) { transpose_m3_m4(nmat, ob->imat); @@ -4607,8 +4842,9 @@ void psys_get_dupli_path_transform(ParticleSimulationData *sim, if (psys->part->phasefac != 0) { float q_phase[4]; float phasefac = psys->part->phasefac; - if (psys->part->randphasefac != 0.0f) + if (psys->part->randphasefac != 0.0f) { phasefac += psys->part->randphasefac * psys_frand(psys, (pa - psys->particles) + 20); + } axis_angle_to_quat(q_phase, vec, phasefac * (float)M_PI); mul_qt_v3(q_phase, side); diff --git a/source/blender/blenkernel/intern/particle_child.c b/source/blender/blenkernel/intern/particle_child.c index c967449248d..b74fd3ff684 100644 --- a/source/blender/blenkernel/intern/particle_child.c +++ b/source/blender/blenkernel/intern/particle_child.c @@ -56,10 +56,12 @@ static void psys_path_iter_get(ParticlePathIterator *iter, if (parent) { iter->parent_key = parent + index; - if (index > 0) + if (index > 0) { mul_qt_qtqt(iter->parent_rotation, iter->parent_key->rot, parent->rot); - else + } + else { copy_qt_qt(iter->parent_rotation, parent->rot); + } } else { iter->parent_key = NULL; @@ -110,8 +112,9 @@ static void do_kink_spiral_deform(ParticleKey *state, float radius = amplitude * expf(b * theta); /* a bit more intuitive than using negative frequency for this */ - if (amplitude < 0.0f) + if (amplitude < 0.0f) { theta = -theta; + } cross_v3_v3v3(spiral_axis, dir, kink); normalize_v3(spiral_axis); @@ -276,8 +279,9 @@ static void do_kink_spiral(ParticleThreadContext *ctx, } totlen = 0.0f; - for (k = 0, key = keys; k < end_index - 1; k++, key++) + for (k = 0, key = keys; k < end_index - 1; k++, key++) { totlen += len_v3v3((key + 1)->co, key->co); + } *r_totkeys = end_index; *r_max_length = totlen; @@ -426,16 +430,19 @@ void do_kink(ParticleKey *state, float kink[3] = {1.f, 0.f, 0.f}, par_vec[3], q1[4] = {1.f, 0.f, 0.f, 0.f}; float t, dt = 1.f, result[3]; - if (ELEM(type, PART_KINK_NO, PART_KINK_SPIRAL)) + if (ELEM(type, PART_KINK_NO, PART_KINK_SPIRAL)) { return; + } CLAMP(time, 0.f, 1.f); if (shape != 0.0f && !ELEM(type, PART_KINK_BRAID)) { - if (shape < 0.0f) + if (shape < 0.0f) { time = (float)pow(time, 1.f + shape); - else + } + else { time = (float)pow(time, 1.f / (1.f - shape)); + } } t = time * freq * (float)M_PI; @@ -452,8 +459,9 @@ void do_kink(ParticleKey *state, kink[axis] = 1.f; - if (obmat) + if (obmat) { mul_mat3_m4_v3(obmat, kink); + } mul_qt_v3(par_rot, kink); @@ -569,10 +577,12 @@ void do_kink(ParticleKey *state, } /* blend the start of the kink */ - if (dt < 1.f) + if (dt < 1.f) { interp_v3_v3v3(state->co, state->co, result, dt); - else + } + else { copy_v3_v3(state->co, result); + } } static float do_clump_level(float result[3], @@ -594,15 +604,19 @@ static float do_clump_level(float result[3], else if (clumpfac != 0.0f) { float cpow; - if (clumppow < 0.0f) + if (clumppow < 0.0f) { cpow = 1.0f + clumppow; - else + } + else { cpow = 1.0f + 9.0f * clumppow; + } - if (clumpfac < 0.0f) /* clump roots instead of tips */ + if (clumpfac < 0.0f) { /* clump roots instead of tips */ clump = -clumpfac * pa_clump * (float)pow(1.0 - (double)time, (double)cpow); - else + } + else { clump = clumpfac * pa_clump * (float)pow((double)time, (double)cpow); + } interp_v3_v3v3(result, co, par_co, clump); } @@ -696,8 +710,9 @@ static void do_rough_curve(const float loc[3], float rough[3]; float rco[3]; - if (!roughcurve) + if (!roughcurve) { return; + } fac *= clamp_f(curvemapping_evaluateF(roughcurve, 0, time), 0.0f, 1.0f); @@ -840,7 +855,7 @@ void do_child_modifiers(const ParticleChildModifierContext *modifier_ctx, do_twist(modifier_ctx, state, t); - if (part->flag & PART_CHILD_EFFECT) + if (part->flag & PART_CHILD_EFFECT) { /* state is safe to cast, since only co and vel are used */ guided = do_guides(sim->depsgraph, sim->psys->part, @@ -848,6 +863,7 @@ void do_child_modifiers(const ParticleChildModifierContext *modifier_ctx, (ParticleKey *)state, cpa->parent, t); + } if (guided == 0) { float orco_offset[3]; @@ -888,8 +904,9 @@ void do_child_modifiers(const ParticleChildModifierContext *modifier_ctx, do_rough_curve(modifier_ctx->orco, mat, t, rough1, part->rough1_size, roughcurve, state); } else { - if (rough1 > 0.f) + if (rough1 > 0.f) { do_rough(modifier_ctx->orco, mat, t, rough1, part->rough1_size, 0.0, state); + } if (rough2 > 0.f) { float vec[3]; diff --git a/source/blender/blenkernel/intern/particle_distribute.c b/source/blender/blenkernel/intern/particle_distribute.c index facfc318426..8125024585c 100644 --- a/source/blender/blenkernel/intern/particle_distribute.c +++ b/source/blender/blenkernel/intern/particle_distribute.c @@ -64,8 +64,9 @@ static void alloc_child_particles(ParticleSystem *psys, int tot) if (psys->part->childtype) { psys->totchild = tot; - if (psys->totchild) + if (psys->totchild) { psys->child = MEM_callocN(psys->totchild * sizeof(ChildParticle), "child_particles"); + } } } @@ -238,31 +239,37 @@ static void distribute_grid(Mesh *mesh, ParticleSystem *psys) bool intersects_tri = isect_ray_tri_watertight_v3( co1, &isect_precalc, v1, v2, v3, &lambda, NULL); if (intersects_tri) { - if (from == PART_FROM_FACE) + if (from == PART_FROM_FACE) { (pa + (int)(lambda * size[a]) * a0mul)->flag &= ~PARS_UNEXIST; - else /* store number of intersections */ + } + else { /* store number of intersections */ (pa + (int)(lambda * size[a]) * a0mul)->hair_index++; + } } if (mface->v4 && (!intersects_tri || from == PART_FROM_VOLUME)) { copy_v3_v3(v4, mvert[mface->v4].co); if (isect_ray_tri_watertight_v3(co1, &isect_precalc, v1, v3, v4, &lambda, NULL)) { - if (from == PART_FROM_FACE) + if (from == PART_FROM_FACE) { (pa + (int)(lambda * size[a]) * a0mul)->flag &= ~PARS_UNEXIST; - else + } + else { (pa + (int)(lambda * size[a]) * a0mul)->hair_index++; + } } } } if (from == PART_FROM_VOLUME) { int in = pa->hair_index % 2; - if (in) + if (in) { pa->hair_index++; + } for (i = 0; i < size[0]; i++) { - if (in || (pa + i * a0mul)->hair_index % 2) + if (in || (pa + i * a0mul)->hair_index % 2) { (pa + i * a0mul)->flag &= ~PARS_UNEXIST; + } /* odd intersections == in->out / out->in */ /* even intersections -> in stays same */ in = (in + (pa + i * a0mul)->hair_index) % 2; @@ -277,8 +284,9 @@ static void distribute_grid(Mesh *mesh, ParticleSystem *psys) for (i = 0, p = 0, pa = psys->particles; i < res; i++) { for (j = 0; j < res; j++) { for (k = 0; k < res; k++, p++, pa++) { - if (j % 2) + if (j % 2) { pa->fuv[0] += d / 2.f; + } if (k % 2) { pa->fuv[0] += d / 2.f; @@ -303,8 +311,9 @@ static void distribute_grid(Mesh *mesh, ParticleSystem *psys) if (psys->part->grid_rand > 0.f) { float rfac = d * psys->part->grid_rand; for (p = 0, pa = psys->particles; p < psys->totpart; p++, pa++) { - if (pa->flag & PARS_UNEXIST) + if (pa->flag & PARS_UNEXIST) { continue; + } pa->fuv[0] += rfac * (psys_frand(psys, p + 31) - 0.5f); pa->fuv[1] += rfac * (psys_frand(psys, p + 32) - 0.5f); @@ -340,8 +349,9 @@ static void init_mv_jit(float *jit, int num, int seed2, float amount) float *jit2, x, rad1, rad2, rad3; int i, num2; - if (num == 0) + if (num == 0) { return; + } rad1 = (float)(1.0f / sqrtf((float)num)); rad2 = (float)(1.0f / ((float)num)); @@ -378,10 +388,12 @@ static void psys_uv_to_w(float u, float v, int quad, float *w) float vert[4][3], co[3]; if (!quad) { - if (u + v > 1.0f) + if (u + v > 1.0f) { v = 1.0f - v; - else + } + else { u = 1.0f - u; + } } vert[0][0] = 0.0f; @@ -415,20 +427,24 @@ static int distribute_binary_search(float *sum, int n, float value) { int mid, low = 0, high = n - 1; - if (high == low) + if (high == low) { return low; + } - if (sum[low] >= value) + if (sum[low] >= value) { return low; + } - if (sum[high - 1] < value) + if (sum[high - 1] < value) { return high; + } while (low < high) { mid = (low + high) / 2; - if ((sum[mid] >= value) && (sum[mid - 1] < value)) + if ((sum[mid] >= value) && (sum[mid - 1] < value)) { return mid; + } if (sum[mid] > value) { high = mid - 1; @@ -521,10 +537,12 @@ static void distribute_from_faces_exec(ParticleTask *thread, ParticleData *pa, i switch (distr) { case PART_DISTR_JIT: if (ctx->jitlevel == 1) { - if (mface->v4) + if (mface->v4) { psys_uv_to_w(0.5f, 0.5f, mface->v4, pa->fuv); - else + } + else { psys_uv_to_w(1.0f / 3.0f, 1.0f / 3.0f, mface->v4, pa->fuv); + } } else { float offset = fmod(ctx->jitoff[i] + (float)p, (float)ctx->jitlevel); @@ -569,10 +587,12 @@ static void distribute_from_volume_exec(ParticleTask *thread, ParticleData *pa, switch (distr) { case PART_DISTR_JIT: if (ctx->jitlevel == 1) { - if (mface->v4) + if (mface->v4) { psys_uv_to_w(0.5f, 0.5f, mface->v4, pa->fuv); - else + } + else { psys_uv_to_w(1.0f / 3.0f, 1.0f / 3.0f, mface->v4, pa->fuv); + } } else { float offset = fmod(ctx->jitoff[i] + (float)p, (float)ctx->jitlevel); @@ -604,8 +624,9 @@ static void distribute_from_volume_exec(ParticleTask *thread, ParticleData *pa, intersect = 0; for (i = 0, mface = mesh->mface; i < tot; i++, mface++) { - if (i == pa->num) + if (i == pa->num) { continue; + } v1 = mvert[mface->v1].co; v2 = mvert[mface->v2].co; @@ -630,8 +651,9 @@ static void distribute_from_volume_exec(ParticleTask *thread, ParticleData *pa, } } } - if (intersect == 0) + if (intersect == 0) { pa->foffset = 0.0; + } else { switch (distr) { case PART_DISTR_JIT: @@ -736,8 +758,9 @@ static void distribute_children_exec(ParticleTask *thread, ChildParticle *cpa, i cpa->parent = cpa->pa[0]; } - if (rng_skip_tot > 0) /* should never be below zero */ + if (rng_skip_tot > 0) { /* should never be below zero */ BLI_rng_skip(thread->rng, rng_skip_tot); + } } static void exec_distribute_parent(TaskPool *__restrict UNUSED(pool), @@ -754,16 +777,19 @@ static void exec_distribute_parent(TaskPool *__restrict UNUSED(pool), pa = psys->particles + task->begin; switch (psys->part->from) { case PART_FROM_FACE: - for (p = task->begin; p < task->end; ++p, ++pa) + for (p = task->begin; p < task->end; ++p, ++pa) { distribute_from_faces_exec(task, pa, p); + } break; case PART_FROM_VOLUME: - for (p = task->begin; p < task->end; ++p, ++pa) + for (p = task->begin; p < task->end; ++p, ++pa) { distribute_from_volume_exec(task, pa, p); + } break; case PART_FROM_VERT: - for (p = task->begin; p < task->end; ++p, ++pa) + for (p = task->begin; p < task->end; ++p, ++pa) { distribute_from_verts_exec(task, pa, p); + } break; } } @@ -794,20 +820,25 @@ static int distribute_compare_orig_index(const void *p1, const void *p2, void *u int index1 = orig_index[*(const int *)p1]; int index2 = orig_index[*(const int *)p2]; - if (index1 < index2) + if (index1 < index2) { return -1; + } else if (index1 == index2) { /* this pointer comparison appears to make qsort stable for glibc, * and apparently on solaris too, makes the renders reproducible */ - if (p1 < p2) + if (p1 < p2) { return -1; - else if (p1 == p2) + } + else if (p1 == p2) { return 0; - else + } + else { return 1; + } } - else + else { return 1; + } } static void distribute_invalid(ParticleSimulationData *sim, int from) @@ -864,26 +895,28 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, float cur, maxweight = 0.0, tweight, totweight, inv_totweight, co[3], nor[3], orco[3]; RNG *rng = NULL; - if (ELEM(NULL, ob, psys, psys->part)) + if (ELEM(NULL, ob, psys, psys->part)) { return 0; + } part = psys->part; totpart = psys->totpart; - if (totpart == 0) + if (totpart == 0) { return 0; + } if (!final_mesh->runtime.deformed_only && !CustomData_get_layer(&final_mesh->fdata, CD_ORIGINDEX)) { printf( "Can't create particles with the current modifier stack, disable destructive modifiers\n"); - // XXX error("Can't paint with the current modifier stack, disable destructive modifiers"); + // XXX error("Can't paint with the current modifier stack, disable destructive modifiers"); return 0; } - /* XXX This distribution code is totally broken in case from == PART_FROM_CHILD, it's always using finaldm - * even if use_modifier_stack is unset... But making things consistent here break all existing edited - * hair systems, so better wait for complete rewrite. - */ + /* XXX This distribution code is totally broken in case from == PART_FROM_CHILD, + * it's always using finaldm even if use_modifier_stack is unset... + * But making things consistent here break all existing edited + * hair systems, so better wait for complete rewrite. */ psys_thread_context_init(ctx, sim); @@ -949,10 +982,12 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, rng = BLI_rng_new_srandom(31415926 + psys->seed); - if (psys->part->use_modifier_stack) + if (psys->part->use_modifier_stack) { mesh = final_mesh; - else + } + else { BKE_id_copy_ex(NULL, ob->data, (ID **)&mesh, LIB_ID_COPY_LOCALIZE); + } BKE_mesh_tessface_ensure(mesh); @@ -976,8 +1011,9 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, copy_v3_v3(co, orcodata[p]); BKE_mesh_orco_verts_transform(ob->data, &co, 1, 1); } - else + else { copy_v3_v3(co, mv[p].co); + } BLI_kdtree_3d_insert(tree, p, co); } @@ -991,11 +1027,13 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, if (totelem == 0) { distribute_invalid(sim, children ? PART_FROM_CHILD : 0); - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { fprintf(stderr, "Particle distribution error: Nothing to emit from!\n"); + } - if (mesh != final_mesh) + if (mesh != final_mesh) { BKE_id_free(NULL, mesh); + } BLI_kdtree_3d_free(tree); BLI_rng_free(rng); @@ -1046,22 +1084,25 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, cur = mf->v4 ? area_quad_v3(co1, co2, co3, co4) : area_tri_v3(co1, co2, co3); - if (cur > maxweight) + if (cur > maxweight) { maxweight = cur; + } element_weight[i] = cur; totarea += cur; } - for (i = 0; i < totelem; i++) + for (i = 0; i < totelem; i++) { element_weight[i] /= totarea; + } maxweight /= totarea; } else { float min = 1.0f / (float)(MIN2(totelem, totpart)); - for (i = 0; i < totelem; i++) + for (i = 0; i < totelem; i++) { element_weight[i] = min; + } maxweight = min; } @@ -1070,8 +1111,9 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, if (vweight) { if (from == PART_FROM_VERT) { - for (i = 0; i < totelem; i++) + for (i = 0; i < totelem; i++) { element_weight[i] *= vweight[i]; + } } else { /* PART_FROM_FACE / PART_FROM_VOLUME */ for (i = 0; i < totelem; i++) { @@ -1127,8 +1169,9 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, int *element_map = MEM_mallocN(sizeof(*element_map) * totmapped, __func__); int i_mapped = 0; - for (i = 0; i < totelem && element_weight[i] == 0.0f; i++) + for (i = 0; i < totelem && element_weight[i] == 0.0f; i++) { ; + } element_sum[i_mapped] = element_weight[i] * inv_totweight; element_map[i_mapped] = i; i_mapped++; @@ -1161,9 +1204,10 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, double step, pos; step = (totpart < 2) ? 0.5 : 1.0 / (double)totpart; - /* This is to address tricky issues with vertex-emitting when user tries (and expects) exact 1-1 vert/part - * distribution (see T47983 and its two example files). It allows us to consider pos as - * 'midpoint between v and v+1' (or 'p and p+1', depending whether we have more vertices than particles or not), + /* This is to address tricky issues with vertex-emitting when user tries + * (and expects) exact 1-1 vert/part distribution (see T47983 and its two example files). + * It allows us to consider pos as 'midpoint between v and v+1' + * (or 'p and p+1', depending whether we have more vertices than particles or not), * and avoid stumbling over float impression in element_sum. * Note: moved face and volume distribution to this as well (instead of starting at zero), * for the same reasons, see T52682. */ @@ -1171,8 +1215,9 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, step * 0.5; /* We choose the smaller step. */ for (i = 0, p = 0; p < totpart; p++, pos += step) { - for (; (i < totmapped - 1) && (pos > (double)element_sum[i]); i++) + for (; (i < totmapped - 1) && (pos > (double)element_sum[i]); i++) { ; + } particle_element[p] = element_map[i]; @@ -1189,12 +1234,14 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, int *orig_index = NULL; if (from == PART_FROM_VERT) { - if (mesh->totvert) + if (mesh->totvert) { orig_index = CustomData_get_layer(&mesh->vdata, CD_ORIGINDEX); + } } else { - if (mesh->totface) + if (mesh->totface) { orig_index = CustomData_get_layer(&mesh->fdata, CD_ORIGINDEX); + } } if (orig_index) { @@ -1209,10 +1256,12 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, if (jitlevel == 0) { jitlevel = totpart / totelem; - if (part->flag & PART_EDISTR) + if (part->flag & PART_EDISTR) { jitlevel *= 2; /* looks better in general, not very scientific */ - if (jitlevel < 3) + } + if (jitlevel < 3) { jitlevel = 3; + } } jit = MEM_callocN((2 + jitlevel * 2) * sizeof(float), "jit"); @@ -1220,10 +1269,12 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, /* for small amounts of particles we use regular jitter since it looks * a bit better, for larger amounts we switch to hammersley sequence * because it is much faster */ - if (jitlevel < 25) + if (jitlevel < 25) { init_mv_jit(jit, jitlevel, psys->seed, part->jitfac); - else + } + else { hammersley_create(jit, jitlevel + 1, psys->seed, part->jitfac); + } BLI_array_randomize( jit, 2 * sizeof(float), jitlevel, psys->seed); /* for custom jit or even distribution */ } @@ -1271,8 +1322,9 @@ static void distribute_particles_on_dm(ParticleSimulationData *sim, int from) int i, totpart, numtasks; /* create a task pool for distribution tasks */ - if (!psys_thread_context_init_distribute(&ctx, sim, from)) + if (!psys_thread_context_init_distribute(&ctx, sim, from)) { return; + } task_scheduler = BLI_task_scheduler_get(); task_pool = BLI_task_pool_create(task_scheduler, &ctx); @@ -1283,10 +1335,12 @@ static void distribute_particles_on_dm(ParticleSimulationData *sim, int from) ParticleTask *task = &tasks[i]; psys_task_init_distribute(task, sim); - if (from == PART_FROM_CHILD) + if (from == PART_FROM_CHILD) { BLI_task_pool_push(task_pool, exec_distribute_child, task, false, TASK_PRIORITY_LOW); - else + } + else { BLI_task_pool_push(task_pool, exec_distribute_parent, task, false, TASK_PRIORITY_LOW); + } } BLI_task_pool_work_and_wait(task_pool); @@ -1294,8 +1348,9 @@ static void distribute_particles_on_dm(ParticleSimulationData *sim, int from) psys_calc_dmcache(sim->ob, final_mesh, sim->psmd->mesh_original, sim->psys); - if (ctx.mesh != final_mesh) + if (ctx.mesh != final_mesh) { BKE_id_free(NULL, ctx.mesh); + } psys_tasks_free(tasks, numtasks); @@ -1316,13 +1371,16 @@ void distribute_particles(ParticleSimulationData *sim, int from) int distr_error = 0; if (psmd) { - if (psmd->mesh_final) + if (psmd->mesh_final) { distribute_particles_on_dm(sim, from); - else + } + else { distr_error = 1; + } } - else + else { distribute_particles_on_shape(sim, from); + } if (distr_error) { distribute_invalid(sim, from); diff --git a/source/blender/blenkernel/intern/particle_system.c b/source/blender/blenkernel/intern/particle_system.c index bf34e98c482..cba15aed55f 100644 --- a/source/blender/blenkernel/intern/particle_system.c +++ b/source/blender/blenkernel/intern/particle_system.c @@ -102,13 +102,16 @@ static ThreadRWMutex psys_bvhtree_rwlock = BLI_RWLOCK_INITIALIZER; static int particles_are_dynamic(ParticleSystem *psys) { - if (psys->pointcache->flag & PTCACHE_BAKED) + if (psys->pointcache->flag & PTCACHE_BAKED) { return 0; + } - if (psys->part->type == PART_HAIR) + if (psys->part->type == PART_HAIR) { return psys->flag & PSYS_HAIR_DYNAMICS; - else + } + else { return ELEM(psys->part->phystype, PART_PHYS_NEWTON, PART_PHYS_BOIDS, PART_PHYS_FLUID); + } } float psys_get_current_display_percentage(ParticleSystem *psys, const bool use_render_params) @@ -128,12 +131,15 @@ float psys_get_current_display_percentage(ParticleSystem *psys, const bool use_r static int tot_particles(ParticleSystem *psys, PTCacheID *pid) { - if (pid && psys->pointcache->flag & PTCACHE_EXTERNAL) + if (pid && psys->pointcache->flag & PTCACHE_EXTERNAL) { return pid->cache->totpoint; - else if (psys->part->distr == PART_DISTR_GRID && psys->part->from != PART_FROM_VERT) + } + else if (psys->part->distr == PART_DISTR_GRID && psys->part->from != PART_FROM_VERT) { return psys->part->grid_res * psys->part->grid_res * psys->part->grid_res - psys->totunexist; - else + } + else { return psys->part->totpart - psys->totunexist; + } } void psys_reset(ParticleSystem *psys, int mode) @@ -212,11 +218,13 @@ static void realloc_particles(ParticleSimulationData *sim, int new_totpart) totpart = part->grid_res; totpart *= totpart * totpart; } - else + else { totpart = part->totpart; + } } - else + else { totpart = new_totpart; + } if (totpart != psys->totpart) { if (psys->edit && psys->free_edit) { @@ -227,16 +235,18 @@ static void realloc_particles(ParticleSimulationData *sim, int new_totpart) if (totpart) { newpars = MEM_callocN(totpart * sizeof(ParticleData), "particles"); - if (newpars == NULL) + if (newpars == NULL) { return; + } if (psys->part->phystype == PART_PHYS_BOIDS) { newboids = MEM_callocN(totpart * sizeof(BoidParticle), "boid particles"); if (newboids == NULL) { /* allocation error! */ - if (newpars) + if (newpars) { MEM_freeN(newpars); + } return; } } @@ -248,15 +258,18 @@ static void realloc_particles(ParticleSimulationData *sim, int new_totpart) if (totsaved) { memcpy(newpars, psys->particles, totsaved * sizeof(ParticleData)); - if (psys->particles->boid) + if (psys->particles->boid) { memcpy(newboids, psys->particles->boid, totsaved * sizeof(BoidParticle)); + } } - if (psys->particles->keys) + if (psys->particles->keys) { MEM_freeN(psys->particles->keys); + } - if (psys->particles->boid) + if (psys->particles->boid) { MEM_freeN(psys->particles->boid); + } for (p = 0, pa = newpars; p < totsaved; p++, pa++) { if (pa->keys) { @@ -265,9 +278,11 @@ static void realloc_particles(ParticleSimulationData *sim, int new_totpart) } } - for (p = totsaved, pa = psys->particles + totsaved; p < psys->totpart; p++, pa++) - if (pa->hair) + for (p = totsaved, pa = psys->particles + totsaved; p < psys->totpart; p++, pa++) { + if (pa->hair) { MEM_freeN(pa->hair); + } + } MEM_freeN(psys->particles); psys_free_pdd(psys); @@ -295,13 +310,16 @@ int psys_get_child_number(Scene *scene, ParticleSystem *psys, const bool use_ren { int nbr; - if (!psys->part->childtype) + if (!psys->part->childtype) { return 0; + } - if (use_render_params) + if (use_render_params) { nbr = psys->part->ren_child_nbr; - else + } + else { nbr = psys->part->child_nbr; + } return get_render_child_particle_number(&scene->r, nbr, use_render_params); } @@ -406,17 +424,21 @@ void psys_calc_dmcache(Object *ob, Mesh *mesh_final, Mesh *mesh_original, Partic } if (use_modifier_stack) { - if (pa->num < totelem) + if (pa->num < totelem) { pa->num_dmcache = DMCACHE_ISCHILD; - else + } + else { pa->num_dmcache = DMCACHE_NOTFOUND; + } } else { if (psys->part->from == PART_FROM_VERT) { - if (pa->num < totelem && nodearray[pa->num]) + if (pa->num < totelem && nodearray[pa->num]) { pa->num_dmcache = POINTER_AS_INT(nodearray[pa->num]->link); - else + } + else { pa->num_dmcache = DMCACHE_NOTFOUND; + } } else { /* FROM_FACE/FROM_VOLUME */ pa->num_dmcache = psys_particle_dm_face_lookup( @@ -488,10 +510,12 @@ void psys_tasks_free(ParticleTask *tasks, int numtasks) /* threads */ for (i = 0; i < numtasks; ++i) { - if (tasks[i].rng) + if (tasks[i].rng) { BLI_rng_free(tasks[i].rng); - if (tasks[i].rng_path) + } + if (tasks[i].rng_path) { BLI_rng_free(tasks[i].rng_path); + } } MEM_freeN(tasks); @@ -500,20 +524,27 @@ void psys_tasks_free(ParticleTask *tasks, int numtasks) void psys_thread_context_free(ParticleThreadContext *ctx) { /* path caching */ - if (ctx->vg_length) + if (ctx->vg_length) { MEM_freeN(ctx->vg_length); - if (ctx->vg_clump) + } + if (ctx->vg_clump) { MEM_freeN(ctx->vg_clump); - if (ctx->vg_kink) + } + if (ctx->vg_kink) { MEM_freeN(ctx->vg_kink); - if (ctx->vg_rough1) + } + if (ctx->vg_rough1) { MEM_freeN(ctx->vg_rough1); - if (ctx->vg_rough2) + } + if (ctx->vg_rough2) { MEM_freeN(ctx->vg_rough2); - if (ctx->vg_roughe) + } + if (ctx->vg_roughe) { MEM_freeN(ctx->vg_roughe); - if (ctx->vg_twist) + } + if (ctx->vg_twist) { MEM_freeN(ctx->vg_twist); + } if (ctx->sim.psys->lattice_deform_data) { end_latt_deform(ctx->sim.psys->lattice_deform_data); @@ -521,17 +552,22 @@ void psys_thread_context_free(ParticleThreadContext *ctx) } /* distribution */ - if (ctx->jit) + if (ctx->jit) { MEM_freeN(ctx->jit); - if (ctx->jitoff) + } + if (ctx->jitoff) { MEM_freeN(ctx->jitoff); - if (ctx->weight) + } + if (ctx->weight) { MEM_freeN(ctx->weight); - if (ctx->index) + } + if (ctx->index) { MEM_freeN(ctx->index); - if (ctx->seams) + } + if (ctx->seams) { MEM_freeN(ctx->seams); - //if (ctx->vertpart) MEM_freeN(ctx->vertpart); + } + // if (ctx->vertpart) MEM_freeN(ctx->vertpart); BLI_kdtree_3d_free(ctx->tree); if (ctx->clumpcurve != NULL) { @@ -583,7 +619,7 @@ void initialize_particle(ParticleSimulationData *sim, ParticleData *pa) pa->hair_index = 0; /* we can't reset to -1 anymore since we've figured out correct index in distribute_particles */ /* usage other than straight after distribute has to handle this index by itself - jahka*/ - //pa->num_dmcache = DMCACHE_NOTFOUND; /* assume we don't have a derived mesh face */ + // pa->num_dmcache = DMCACHE_NOTFOUND; /* assume we don't have a derived mesh face */ } static void initialize_all_particles(ParticleSimulationData *sim) @@ -626,8 +662,9 @@ static void free_unexisting_particles(ParticleSimulationData *sim) } if (psys->totpart && psys->totunexist == psys->totpart) { - if (psys->particles->boid) + if (psys->particles->boid) { MEM_freeN(psys->particles->boid); + } MEM_freeN(psys->particles); psys->particles = NULL; @@ -641,14 +678,16 @@ static void free_unexisting_particles(ParticleSimulationData *sim) npa = newpars = MEM_callocN(newtotpart * sizeof(ParticleData), "particles"); for (p = 0, pa = psys->particles; p < newtotpart; p++, pa++, npa++) { - while (pa->flag & PARS_UNEXIST) + while (pa->flag & PARS_UNEXIST) { pa++; + } memcpy(npa, pa, sizeof(ParticleData)); } - if (psys->particles->boid) + if (psys->particles->boid) { MEM_freeN(psys->particles->boid); + } MEM_freeN(psys->particles); psys->particles = newpars; psys->totpart -= psys->totunexist; @@ -720,7 +759,7 @@ void psys_get_birth_coords( int p = pa - psys->particles; /* get birth location from object */ - if (use_tangents) + if (use_tangents) { psys_particle_on_emitter(sim->psmd, part->from, pa->num, @@ -732,9 +771,11 @@ void psys_get_birth_coords( utan, vtan, 0); - else + } + else { psys_particle_on_emitter( sim->psmd, part->from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, loc, nor, 0, 0, 0); + } /* get possible textural influence */ psys_get_texture(sim, pa, &ptex, PAMAP_IVEL, cfra); @@ -750,8 +791,15 @@ void psys_get_birth_coords( /* -tangent */ if (use_tangents) { - //float phase=vg_rot?2.0f*(psys_particle_value_from_verts(sim->psmd->dm,part->from,pa,vg_rot)-0.5f):0.0f; +#if 0 + float phase = vg_rot ? + 2.0f * + (psys_particle_value_from_verts(sim->psmd->dm, part->from, pa, vg_rot) - + 0.5f) : + 0.0f; +#else float phase = 0.0f; +#endif mul_v3_fl(vtan, -cosf((float)M_PI * (part->tanphase + phase))); fac = -sinf((float)M_PI * (part->tanphase + phase)); madd_v3_v3fl(vtan, utan, fac); @@ -842,12 +890,14 @@ void psys_get_birth_coords( } /* *emitter normal */ - if (part->normfac != 0.f) + if (part->normfac != 0.f) { madd_v3_v3fl(vel, nor, part->normfac); + } /* *emitter tangent */ - if (sim->psmd && part->tanfac != 0.f) + if (sim->psmd && part->tanfac != 0.f) { madd_v3_v3fl(vel, vtan, part->tanfac); + } /* *emitter object orientation */ if (part->ob_vel[0] != 0.f) { @@ -867,12 +917,14 @@ void psys_get_birth_coords( /* TODO */ /* *random */ - if (part->randfac != 0.f) + if (part->randfac != 0.f) { madd_v3_v3fl(vel, r_vel, part->randfac); + } /* *particle */ - if (part->partfac != 0.f) + if (part->partfac != 0.f) { madd_v3_v3fl(vel, p_vel, part->partfac); + } mul_v3_v3fl(state->vel, vel, ptex.ivel); @@ -990,8 +1042,9 @@ void psys_get_birth_coords( /* rotation phase */ phasefac = part->phasefac; - if (part->randphasefac != 0.0f) + if (part->randphasefac != 0.0f) { phasefac += part->randphasefac * psys_frand(psys, p + 20); + } axis_angle_to_quat(q_phase, x_vec, phasefac * (float)M_PI); /* combine base rotation & phase */ @@ -1003,10 +1056,12 @@ void psys_get_birth_coords( zero_v3(state->ave); if (part->avemode) { - if (part->avemode == PART_AVE_RAND) + if (part->avemode == PART_AVE_RAND) { copy_v3_v3(state->ave, r_ave); - else + } + else { get_angular_velocity_vector(part->avemode, state, state->ave); + } normalize_v3(state->ave); mul_v3_fl(state->ave, part->avefac); @@ -1020,8 +1075,9 @@ static void evaluate_emitter_anim(struct Depsgraph *depsgraph, Object *ob, float cfra) { - if (ob->parent) + if (ob->parent) { evaluate_emitter_anim(depsgraph, scene, ob->parent, cfra); + } BKE_object_where_is_calc_time(depsgraph, scene, ob, cfra); } @@ -1083,8 +1139,9 @@ void reset_particle(ParticleSimulationData *sim, ParticleData *pa, float dtime, pa->lifetime = part->lifetime * ptex.life; - if (part->randlife != 0.0f) + if (part->randlife != 0.0f) { pa->lifetime *= 1.0f - part->randlife * psys_frand(psys, p + 21); + } } pa->dietime = pa->time + pa->lifetime; @@ -1095,12 +1152,15 @@ void reset_particle(ParticleSimulationData *sim, ParticleData *pa, float dtime, pa->dietime = MIN2(pa->dietime, dietime); } - if (pa->time > cfra) + if (pa->time > cfra) { pa->alive = PARS_UNBORN; - else if (pa->dietime <= cfra) + } + else if (pa->dietime <= cfra) { pa->alive = PARS_DEAD; - else + } + else { pa->alive = PARS_ALIVE; + } pa->state.time = cfra; } @@ -1109,8 +1169,9 @@ static void reset_all_particles(ParticleSimulationData *sim, float dtime, float ParticleData *pa; int p, totpart = sim->psys->totpart; - for (p = from, pa = sim->psys->particles + from; p < totpart; p++, pa++) + for (p = from, pa = sim->psys->particles + from; p < totpart; p++, pa++) { reset_particle(sim, pa, dtime, cfra); + } } /************************************************/ /* Particle targets */ @@ -1119,15 +1180,19 @@ ParticleSystem *psys_get_target_system(Object *ob, ParticleTarget *pt) { ParticleSystem *psys = NULL; - if (pt->ob == NULL || pt->ob == ob) + if (pt->ob == NULL || pt->ob == ob) { psys = BLI_findlink(&ob->particlesystem, pt->psys - 1); - else + } + else { psys = BLI_findlink(&pt->ob->particlesystem, pt->psys - 1); + } - if (psys) + if (psys) { pt->flag |= PTARGET_VALID; - else + } + else { pt->flag &= ~PTARGET_VALID; + } return psys; } @@ -1147,8 +1212,9 @@ void psys_count_keyed_targets(ParticleSimulationData *sim) if (kpsys && kpsys->totpart) { psys->totkeyed += keys_valid; - if (psys->flag & PSYS_KEYED_TIMING && pt->duration != 0.0f) + if (psys->flag & PSYS_KEYED_TIMING && pt->duration != 0.0f) { psys->totkeyed += 1; + } } else { keys_valid = 0; @@ -1214,14 +1280,17 @@ static void set_keyed_keys(ParticleSimulationData *sim) (key + 1)->time = pa->time + pt->time + pt->duration; } } - else if (totkeys > 1) + else if (totkeys > 1) { key->time = pa->time + (float)k / (float)(totkeys - 1) * pa->lifetime; - else + } + else { key->time = pa->time; + } } - if (psys->flag & PSYS_KEYED_TIMING && pt->duration != 0.0f) + if (psys->flag & PSYS_KEYED_TIMING && pt->duration != 0.0f) { k++; + } ksim.psys->flag |= keyed_flag; @@ -1248,8 +1317,9 @@ void psys_make_temp_pointcache(Object *ob, ParticleSystem *psys) } static void psys_clear_temp_pointcache(ParticleSystem *psys) { - if (psys->pointcache->flag & PTCACHE_DISK_CACHE) + if (psys->pointcache->flag & PTCACHE_DISK_CACHE) { BKE_ptcache_free_mem(&psys->pointcache->mem_cache); + } } void psys_get_pointcache_start_end(Scene *scene, ParticleSystem *psys, int *sfra, int *efra) { @@ -1287,10 +1357,12 @@ static void psys_update_particle_bvhtree(ParticleSystem *psys, float cfra) LOOP_SHOWN_PARTICLES { if (pa->alive == PARS_ALIVE) { - if (pa->state.time == cfra) + if (pa->state.time == cfra) { BLI_bvhtree_insert(psys->bvhtree, p, pa->prev_state.co, 1); - else + } + else { BLI_bvhtree_insert(psys->bvhtree, p, pa->state.co, 1); + } } } BLI_bvhtree_balance(psys->bvhtree); @@ -1319,10 +1391,12 @@ void psys_update_particle_tree(ParticleSystem *psys, float cfra) LOOP_SHOWN_PARTICLES { if (pa->alive == PARS_ALIVE) { - if (pa->state.time == cfra) + if (pa->state.time == cfra) { BLI_kdtree_3d_insert(psys->tree, p, pa->prev_state.co); - else + } + else { BLI_kdtree_3d_insert(psys->tree, p, pa->state.co); + } } } BLI_kdtree_3d_balance(psys->tree); @@ -1367,8 +1441,9 @@ static void integrate_particle( copy_v3_v3(oldpos, pa->state.co); /* Verlet integration behaves strangely with moving emitters, so do first step with euler. */ - if (pa->prev_state.time < 0.f && integrator == PART_INT_VERLET) + if (pa->prev_state.time < 0.f && integrator == PART_INT_VERLET) { integrator = PART_INT_EULER; + } switch (integrator) { case PART_INT_EULER: @@ -1400,8 +1475,9 @@ static void integrate_particle( /* force to acceleration*/ mul_v3_v3fl(acceleration, force, 1.0f / pa_mass); - if (external_acceleration) + if (external_acceleration) { add_v3_v3(acceleration, external_acceleration); + } /* calculate next state */ add_v3_v3(states[i].vel, impulse); @@ -1485,12 +1561,13 @@ static void integrate_particle( } } -/********************************************************************************************************* - * SPH fluid physics +/* -------------------------------------------------------------------- */ +/** \name SPH fluid physics * * In theory, there could be unlimited implementation of SPH simulators * - * This code uses in some parts adapted algorithms from the pseudo code as outlined in the Research paper: + * This code uses in some parts adapted algorithms + * from the pseudo code as outlined in the Research paper: * * Titled: Particle-based Viscoelastic Fluid Simulation. * Authors: Simon Clavet, Philippe Beaudoin and Pierre Poulin @@ -1498,7 +1575,8 @@ static void integrate_particle( * * Presented at Siggraph, (2005) * - * ********************************************************************************************************/ + * \{ */ + #define PSYS_FLUID_SPRINGS_INITIAL_SIZE 256 static ParticleSpring *sph_spring_add(ParticleSystem *psys, ParticleSpring *spring) { @@ -1522,8 +1600,9 @@ static ParticleSpring *sph_spring_add(ParticleSystem *psys, ParticleSpring *spri } static void sph_spring_delete(ParticleSystem *psys, int j) { - if (j != psys->tot_fluidsprings - 1) + if (j != psys->tot_fluidsprings - 1) { psys->fluid_springs[j] = psys->fluid_springs[psys->tot_fluidsprings - 1]; + } psys->tot_fluidsprings--; @@ -1548,8 +1627,9 @@ static void sph_springs_modify(ParticleSystem *psys, float dtime) /* scale things according to dtime */ float timefix = 25.f * dtime; - if ((fluid->flag & SPH_VISCOELASTIC_SPRINGS) == 0 || fluid->spring_k == 0.f) + if ((fluid->flag & SPH_VISCOELASTIC_SPRINGS) == 0 || fluid->spring_k == 0.f) { return; + } /* Loop through the springs */ for (i = 0; i < psys->tot_fluidsprings; i++, spring++) { @@ -1563,21 +1643,25 @@ static void sph_springs_modify(ParticleSystem *psys, float dtime) Lij = spring->rest_length; d = yield_ratio * timefix * Lij; - if (rij > Lij + d) // Stretch + if (rij > Lij + d) { // Stretch spring->rest_length += plasticity * (rij - Lij - d) * timefix; - else if (rij < Lij - d) // Compress + } + else if (rij < Lij - d) { // Compress spring->rest_length -= plasticity * (Lij - d - rij) * timefix; + } h = 4.f * pa1->size; - if (spring->rest_length > h) + if (spring->rest_length > h) { spring->delete_flag = 1; + } } /* Loop through springs backwaqrds - for efficient delete function */ for (i = psys->tot_fluidsprings - 1; i >= 0; i--) { - if (psys->fluid_springs[i].delete_flag) + if (psys->fluid_springs[i].delete_flag) { sph_spring_delete(psys, i); + } } } static EdgeHash *sph_springhash_build(ParticleSystem *psys) @@ -1588,9 +1672,10 @@ static EdgeHash *sph_springhash_build(ParticleSystem *psys) springhash = BLI_edgehash_new_ex(__func__, psys->tot_fluidsprings); - for (i = 0, spring = psys->fluid_springs; i < psys->tot_fluidsprings; i++, spring++) + for (i = 0, spring = psys->fluid_springs; i < psys->tot_fluidsprings; i++, spring++) { BLI_edgehash_insert( springhash, spring->particle_index[0], spring->particle_index[1], POINTER_FROM_INT(i + 1)); + } return springhash; } @@ -1654,8 +1739,9 @@ static void sph_density_accum_cb(void *userdata, int index, const float co[3], f UNUSED_VARS(co); - if (npa == pfr->pa || squared_dist < FLT_EPSILON) + if (npa == pfr->pa || squared_dist < FLT_EPSILON) { return; + } /* Ugh! One particle has too many neighbors! If some aren't taken into * account, the forces will be biased by the tree search order. This @@ -1663,8 +1749,9 @@ static void sph_density_accum_cb(void *userdata, int index, const float co[3], f * But, we have to stop somewhere, and it's not the end of the world. * - jahka and z0r */ - if (pfr->tot_neighbors >= SPH_NEIGHBORS) + if (pfr->tot_neighbors >= SPH_NEIGHBORS) { return; + } pfr->neighbors[pfr->tot_neighbors].index = index; pfr->neighbors[pfr->tot_neighbors].psys = pfr->npsys; @@ -1673,8 +1760,9 @@ static void sph_density_accum_cb(void *userdata, int index, const float co[3], f dist = sqrtf(squared_dist); q = (1.f - dist / pfr->h) * pfr->massfac; - if (pfr->use_size) + if (pfr->use_size) { q *= npa->size; + } pfr->data[0] += q * q; pfr->data[1] += q * q * q; @@ -1778,8 +1866,9 @@ static void sph_force_cb(void *sphdata_v, ParticleKey *state, float *force, floa q = (1.f - rij / h) * pfn->psys->part->mass * inv_mass; - if (pfn->psys->part->flag & PART_SIZEMASS) + if (pfn->psys->part->flag & PART_SIZEMASS) { q *= npa->size; + } copy_v3_v3(vel, npa->prev_state.vel); @@ -1791,11 +1880,13 @@ static void sph_force_cb(void *sphdata_v, ParticleKey *state, float *force, floa sub_v3_v3v3(dv, vel, state->vel); u = dot_v3v3(vec, dv); - if (u < 0.f && visc > 0.f) + if (u < 0.f && visc > 0.f) { madd_v3_v3fl(force, vec, 0.5f * q * visc * u); + } - if (u > 0.f && stiff_visc > 0.f) + if (u > 0.f && stiff_visc > 0.f) { madd_v3_v3fl(force, vec, 0.5f * q * stiff_visc * u); + } } if (spring_constant > 0.f) { @@ -1829,11 +1920,13 @@ static void sph_force_cb(void *sphdata_v, ParticleKey *state, float *force, floa } /* Artificial buoyancy force in negative gravity direction */ - if (fluid->buoyancy > 0.f && gravity) + if (fluid->buoyancy > 0.f && gravity) { madd_v3_v3fl(force, gravity, fluid->buoyancy * (density - rest_density)); + } - if (sphdata->pass == 0 && psys[0]->part->time_flag & PART_TIME_AUTOSF) + if (sphdata->pass == 0 && psys[0]->part->time_flag & PART_TIME_AUTOSF) { sph_particle_courant(sphdata, &pfr); + } sphdata->pass++; } @@ -1855,8 +1948,9 @@ static void sphclassical_density_accum_cb(void *userdata, sub_v3_v3v3(vec, npa->state.co, co); rij = len_v3(vec); rij_h = rij / pfr->h; - if (rij_h > 2.0f) + if (rij_h > 2.0f) { return; + } /* Smoothing factor. Utilise the Wendland kernel. gnuplot: * q1(x) = (2.0 - x)**4 * ( 1.0 + 2.0 * x) @@ -1864,8 +1958,9 @@ static void sphclassical_density_accum_cb(void *userdata, q = qfac / pow3f(pfr->h) * pow4f(2.0f - rij_h) * (1.0f + 2.0f * rij_h); q *= pfr->npsys->part->mass; - if (pfr->use_size) + if (pfr->use_size) { q *= pfr->pa->size; + } pfr->data[0] += q; pfr->data[1] += q / npa->sphdensity; @@ -1881,8 +1976,9 @@ static void sphclassical_neighbour_accum_cb(void *userdata, float rij, rij_h; float vec[3]; - if (pfr->tot_neighbors >= SPH_NEIGHBORS) + if (pfr->tot_neighbors >= SPH_NEIGHBORS) { return; + } /* Exclude particles that are more than 2h away. Can't use squared_dist here * because it is not accurate enough. Use current state, i.e. the output of @@ -1890,8 +1986,9 @@ static void sphclassical_neighbour_accum_cb(void *userdata, sub_v3_v3v3(vec, npa->state.co, co); rij = len_v3(vec); rij_h = rij / pfr->h; - if (rij_h > 2.0f) + if (rij_h > 2.0f) { return; + } pfr->neighbors[pfr->tot_neighbors].index = index; pfr->neighbors[pfr->tot_neighbors].psys = pfr->npsys; @@ -1964,8 +2061,9 @@ static void sphclassical_force_cb(void *sphdata_v, sub_v3_v3v3(vec, co, state->co); rij = normalize_v3(vec); rij_h = rij / pfr.h; - if (rij_h > 2.0f) + if (rij_h > 2.0f) { continue; + } npressure = stiffness * (pow7f(npa->sphdensity / rest_density) - 1.0f); @@ -1976,8 +2074,9 @@ static void sphclassical_force_cb(void *sphdata_v, * Particles > 2h away are excluded above. */ dq = qfac2 * (2.0f * pow4f(2.0f - rij_h) - 4.0f * pow3f(2.0f - rij_h) * (1.0f + 2.0f * rij_h)); - if (pfn->psys->part->flag & PART_SIZEMASS) + if (pfn->psys->part->flag & PART_SIZEMASS) { dq *= npa->size; + } pressureTerm = pressure / pow2f(pa->sphdensity) + npressure / pow2f(npa->sphdensity); @@ -1996,11 +2095,13 @@ static void sphclassical_force_cb(void *sphdata_v, } /* Artificial buoyancy force in negative gravity direction */ - if (fluid->buoyancy > 0.f && gravity) + if (fluid->buoyancy > 0.f && gravity) { madd_v3_v3fl(force, gravity, fluid->buoyancy * (pa->sphdensity - rest_density)); + } - if (sphdata->pass == 0 && psys[0]->part->time_flag & PART_TIME_AUTOSF) + if (sphdata->pass == 0 && psys[0]->part->time_flag & PART_TIME_AUTOSF) { sph_particle_courant(sphdata, &pfr); + } sphdata->pass++; } @@ -2033,13 +2134,16 @@ void psys_sph_init(ParticleSimulationData *sim, SPHData *sphdata) // Add other coupled particle systems. sphdata->psys[0] = sim->psys; - for (i = 1, pt = sim->psys->targets.first; i < 10; i++, pt = (pt ? pt->next : NULL)) + for (i = 1, pt = sim->psys->targets.first; i < 10; i++, pt = (pt ? pt->next : NULL)) { sphdata->psys[i] = pt ? psys_get_target_system(sim->ob, pt) : NULL; + } - if (psys_uses_gravity(sim)) + if (psys_uses_gravity(sim)) { sphdata->gravity = sim->scene->physics_settings.gravity; - else + } + else { sphdata->gravity = NULL; + } sphdata->eh = sph_springhash_build(sim->psys); // These per-particle values should be overridden later, but just for @@ -2104,7 +2208,7 @@ static void sph_integrate(ParticleSimulationData *sim, sphdata->pa = pa; sphdata->mass = pa_mass; sphdata->pass = 0; - //sphdata.element_size and sphdata.flow are set in the callback. + // sphdata.element_size and sphdata.flow are set in the callback. /* restore previous state and treat gravity & effectors as external acceleration*/ sub_v3_v3v3(effector_acceleration, pa->state.vel, pa->prev_state.vel); @@ -2115,6 +2219,8 @@ static void sph_integrate(ParticleSimulationData *sim, integrate_particle(part, pa, dtime, effector_acceleration, sphdata->force_cb, sphdata); } +/** \} */ + /************************************************/ /* Basic physics */ /************************************************/ @@ -2134,16 +2240,18 @@ static void basic_force_cb(void *efdata_v, ParticleKey *state, float *force, flo /* add effectors */ pd_point_from_particle(efdata->sim, efdata->pa, state, &epoint); - if (part->type != PART_HAIR || part->effector_weights->flag & EFF_WEIGHT_DO_HAIR) + if (part->type != PART_HAIR || part->effector_weights->flag & EFF_WEIGHT_DO_HAIR) { BKE_effectors_apply( sim->psys->effectors, sim->colliders, part->effector_weights, &epoint, force, impulse); + } mul_v3_fl(force, efdata->ptex.field); mul_v3_fl(impulse, efdata->ptex.field); /* calculate air-particle interaction */ - if (part->dragfac != 0.0f) + if (part->dragfac != 0.0f) { madd_v3_v3fl(force, state->vel, -part->dragfac * pa->size * pa->size * len_v3(state->vel)); + } /* brownian force */ if (part->brownfac != 0.0f) { @@ -2152,8 +2260,9 @@ static void basic_force_cb(void *efdata_v, ParticleKey *state, float *force, flo force[2] += (BLI_rng_get_float(rng) - 0.5f) * part->brownfac; } - if (part->flag & PART_ROT_DYN && epoint.ave) + if (part->flag & PART_ROT_DYN && epoint.ave) { copy_v3_v3(pa->state.ave, epoint.ave); + } } /* gathers all forces that effect particles and calculates a new state for the particle */ static void basic_integrate(ParticleSimulationData *sim, int p, float dfra, float cfra) @@ -2187,10 +2296,11 @@ static void basic_integrate(ParticleSimulationData *sim, int p, float dfra, floa integrate_particle(part, pa, dtime, gravity, basic_force_cb, &efdata); /* damp affects final velocity */ - if (part->dampfac != 0.f) + if (part->dampfac != 0.f) { mul_v3_fl(pa->state.vel, 1.f - part->dampfac * efdata.ptex.damp * 25.f * dtime); + } - //copy_v3_v3(pa->state.ave, states->ave); + // copy_v3_v3(pa->state.ave, states->ave); /* finally we do guides */ time = (cfra - pa->time) / pa->lifetime; @@ -2292,10 +2402,12 @@ static float nr_signed_distance_to_plane(float *p, d = dot_v3v3(p0, nor); if (pce->inv_nor == -1) { - if (d < 0.f) + if (d < 0.f) { pce->inv_nor = 1; - else + } + else { pce->inv_nor = 0; + } } if (pce->inv_nor == 1) { @@ -2334,7 +2446,8 @@ static void collision_interpolate_element(ParticleCollisionElement *pce, { /* t is the current time for newton rhapson */ /* fac is the starting factor for current collision iteration */ - /* the col->fac's are factors for the particle subframe step start and end during collision modifier step */ + /* The col->fac's are factors for the particle subframe step start + * and end during collision modifier step. */ float f = fac + t * (1.f - fac); float mul = col->fac1 + f * (col->fac2 - col->fac1); if (pce->tot > 0) { @@ -2343,8 +2456,9 @@ static void collision_interpolate_element(ParticleCollisionElement *pce, if (pce->tot > 1) { madd_v3_v3v3fl(pce->x1, pce->x[1], pce->v[1], mul); - if (pce->tot > 2) + if (pce->tot > 2) { madd_v3_v3v3fl(pce->x2, pce->x[2], pce->v[2], mul); + } } } } @@ -2367,8 +2481,9 @@ static void collision_point_velocity(ParticleCollisionElement *pce) static float collision_point_distance_with_normal( float p[3], ParticleCollisionElement *pce, float fac, ParticleCollision *col, float *nor) { - if (fac >= 0.f) + if (fac >= 0.f) { collision_interpolate_element(pce, 0.f, fac, col); + } switch (pce->tot) { case 1: { @@ -2424,8 +2539,9 @@ static void collision_point_on_surface( cross_v3_v3v3(nor, e1, e2); normalize_v3(nor); - if (pce->inv_nor == 1) + if (pce->inv_nor == 1) { negate_v3(nor); + } madd_v3_v3v3fl(co, pce->x0, nor, col->radius); madd_v3_v3fl(co, e1, pce->uv[0]); @@ -2489,8 +2605,9 @@ static float collision_newton_rhapson(ParticleCollision *col, d1 = 0.f; continue; } - else + else { return -1.f; + } } dd = (t1 - t0) / (d1 - d0); @@ -2510,20 +2627,23 @@ static float collision_newton_rhapson(ParticleCollision *col, d1 = 0.f; continue; } - else if (iter == 1 && (t1 < -COLLISION_ZERO || t1 > 1.f)) + else if (iter == 1 && (t1 < -COLLISION_ZERO || t1 > 1.f)) { return -1.f; + } if (d1 <= COLLISION_ZERO && d1 >= -COLLISION_ZERO) { if (t1 >= -COLLISION_ZERO && t1 <= 1.f) { - if (distance_func == nr_signed_distance_to_plane) + if (distance_func == nr_signed_distance_to_plane) { copy_v3_v3(pce->nor, n); + } CLAMP(t1, 0.f, 1.f); return t1; } - else + else { return -1.f; + } } } return -1.0; @@ -2603,8 +2723,9 @@ static int collision_sphere_to_edges(ParticleCollision *col, sub_v3_v3v3(vec, cur->p, cur->x0); u = dot_v3v3(vec, e) / dot_v3v3(e, e); - if (u < 0.f || u > 1.f) + if (u < 0.f || u > 1.f) { break; + } *result = *cur; @@ -2703,8 +2824,9 @@ static int collision_detect(ParticleData *pa, ColliderCache *coll; float ray_dir[3]; - if (BLI_listbase_is_empty(colliders)) + if (BLI_listbase_is_empty(colliders)) { return 0; + } sub_v3_v3v3(ray_dir, col->co2, col->co1); hit->index = -1; @@ -2713,8 +2835,9 @@ static int collision_detect(ParticleData *pa, /* even if particle is stationary we want to check for moving colliders */ /* if hit.dist is zero the bvhtree_ray_cast will just ignore everything */ - if (hit->dist == 0.0f) + if (hit->dist == 0.0f) { hit->dist = col->original_ray_length = 0.000001f; + } for (coll = colliders->first; coll; coll = coll->next) { /* for boids: don't check with current ground object; also skip if permeated */ @@ -2727,12 +2850,14 @@ static int collision_detect(ParticleData *pa, } } - if (skip) + if (skip) { continue; + } /* particles should not collide with emitter at birth */ - if (coll->ob == col->emitter && pa->time < col->cfra && pa->time >= col->old_cfra) + if (coll->ob == col->emitter && pa->time < col->cfra && pa->time >= col->old_cfra) { continue; + } col->current = coll->ob; col->md = coll->collmd; @@ -2815,7 +2940,8 @@ static int collision_response(ParticleSimulationData *sim, /* get exact velocity right before collision */ madd_v3_v3v3fl(v0, col->ve1, col->acc, dt1); - /* convert collider velocity from 1/framestep to 1/s TODO: here we assume 1 frame step for collision modifier */ + /* Convert collider velocity from 1/framestep to 1/s TODO: + * here we assume 1 frame step for collision modifier. */ mul_v3_fl(pce->vel, col->inv_timestep); /* calculate tangential particle velocity */ @@ -2870,12 +2996,15 @@ static int collision_response(ParticleSimulationData *sim, } } - /* stickiness was possibly added before, so cancel that before calculating new normal velocity */ - /* otherwise particles go flying out of the surface because of high reversed sticky velocity */ + /* Stickiness was possibly added before, + * so cancel that before calculating new normal velocity. + * Otherwise particles go flying out of the surface + * because of high reversed sticky velocity. */ if (v0_dot < 0.0f) { v0_dot += pd->pdef_stickness; - if (v0_dot > 0.0f) + if (v0_dot > 0.0f) { v0_dot = 0.0f; + } } /* damping and flipping of velocity around normal */ @@ -2885,12 +3014,15 @@ static int collision_response(ParticleSimulationData *sim, /* calculate normal particle velocity */ /* special case for object hitting the particle from behind */ if (through == 0 && ((vc_dot > 0.0f && v0_dot > 0.0f && vc_dot > v0_dot) || - (vc_dot < 0.0f && v0_dot < 0.0f && vc_dot < v0_dot))) + (vc_dot < 0.0f && v0_dot < 0.0f && vc_dot < v0_dot))) { mul_v3_v3fl(v0_nor, pce->nor, vc_dot); - else if (v0_dot > 0.f) + } + else if (v0_dot > 0.f) { mul_v3_v3fl(v0_nor, pce->nor, vc_dot + v0_dot); - else + } + else { mul_v3_v3fl(v0_nor, pce->nor, vc_dot + (through ? 1.0f : -1.0f) * v0_dot); + } /* combine components together again */ add_v3_v3v3(v0, v0_nor, v0_tan); @@ -2913,21 +3045,25 @@ static int collision_response(ParticleSimulationData *sim, if (!through) { distance = collision_point_distance_with_normal(co, pce, -1.f, col, nor); - if (distance < col->radius + COLLISION_MIN_DISTANCE) + if (distance < col->radius + COLLISION_MIN_DISTANCE) { madd_v3_v3fl(co, nor, col->radius + COLLISION_MIN_DISTANCE - distance); + } dot = dot_v3v3(nor, v0); - if (dot < 0.f) + if (dot < 0.f) { madd_v3_v3fl(v0, nor, -dot); + } distance = collision_point_distance_with_normal(pa->state.co, pce, 1.f, col, nor); - if (distance < col->radius + COLLISION_MIN_DISTANCE) + if (distance < col->radius + COLLISION_MIN_DISTANCE) { madd_v3_v3fl(pa->state.co, nor, col->radius + COLLISION_MIN_DISTANCE - distance); + } dot = dot_v3v3(nor, pa->state.vel); - if (dot < 0.f) + if (dot < 0.f) { madd_v3_v3fl(pa->state.vel, nor, -dot); + } } /* add stickiness to surface */ @@ -3017,15 +3153,18 @@ static void collision_check(ParticleSimulationData *sim, int p, float dfra, floa collision_count++; - if (collision_count == PARTICLE_COLLISION_MAX_COLLISIONS) + if (collision_count == PARTICLE_COLLISION_MAX_COLLISIONS) { collision_fail(pa, &col); + } else if (collision_response( sim, pa, &col, &hit, part->flag & PART_DIE_ON_COL, part->flag & PART_ROT_DYN) == - 0) + 0) { return; + } } - else + else { return; + } } } /************************************************/ @@ -3043,48 +3182,58 @@ static void psys_update_path_cache(ParticleSimulationData *sim, if ((psys->part->childtype && psys->totchild != psys_get_tot_child(sim->scene, psys, use_render_params)) || - psys->recalc & ID_RECALC_PSYS_RESET) + psys->recalc & ID_RECALC_PSYS_RESET) { alloc = 1; + } if (alloc || psys->recalc & ID_RECALC_PSYS_CHILD || - (psys->vgroup[PSYS_VG_DENSITY] && (sim->ob && sim->ob->mode & OB_MODE_WEIGHT_PAINT))) + (psys->vgroup[PSYS_VG_DENSITY] && (sim->ob && sim->ob->mode & OB_MODE_WEIGHT_PAINT))) { distr = 1; + } if (distr) { - if (alloc) + if (alloc) { realloc_particles(sim, sim->psys->totpart); + } if (psys_get_tot_child(sim->scene, psys, use_render_params)) { /* don't generate children while computing the hair keys */ if (!(psys->part->type == PART_HAIR) || (psys->flag & PSYS_HAIR_DONE)) { distribute_particles(sim, PART_FROM_CHILD); - if (part->childtype == PART_CHILD_FACES && part->parents != 0.0f) + if (part->childtype == PART_CHILD_FACES && part->parents != 0.0f) { psys_find_parents(sim, use_render_params); + } } } - else + else { psys_free_children(psys); + } } if ((part->type == PART_HAIR || psys->flag & PSYS_KEYED || - psys->pointcache->flag & PTCACHE_BAKED) == 0) + psys->pointcache->flag & PTCACHE_BAKED) == 0) { skip = 1; /* only hair, keyed and baked stuff can have paths */ + } else if (part->ren_as != PART_DRAW_PATH && - !(part->type == PART_HAIR && ELEM(part->ren_as, PART_DRAW_OB, PART_DRAW_GR))) + !(part->type == PART_HAIR && ELEM(part->ren_as, PART_DRAW_OB, PART_DRAW_GR))) { skip = 1; /* particle visualization must be set as path */ + } else if (DEG_get_mode(sim->depsgraph) != DAG_EVAL_RENDER) { - if (part->draw_as != PART_DRAW_REND) + if (part->draw_as != PART_DRAW_REND) { skip = 1; /* draw visualization */ - else if (psys->pointcache->flag & PTCACHE_BAKING) + } + else if (psys->pointcache->flag & PTCACHE_BAKING) { skip = 1; /* no need to cache paths while baking dynamics */ - + } else if (psys_in_edit_mode(sim->depsgraph, psys)) { - if ((pset->flag & PE_DRAW_PART) == 0) + if ((pset->flag & PE_DRAW_PART) == 0) { skip = 1; + } else if (part->childtype == 0 && - (psys->flag & PSYS_HAIR_DYNAMICS && psys->pointcache->flag & PTCACHE_BAKED) == 0) + (psys->flag & PSYS_HAIR_DYNAMICS && psys->pointcache->flag & PTCACHE_BAKED) == 0) { skip = 1; /* in edit mode paths are needed for child particles and dynamic hair */ + } } } @@ -3093,17 +3242,21 @@ static void psys_update_path_cache(ParticleSimulationData *sim, /* for render, child particle paths are computed on the fly */ if (part->childtype) { - if (!psys->totchild) + if (!psys->totchild) { skip = 1; - else if (psys->part->type == PART_HAIR && (psys->flag & PSYS_HAIR_DONE) == 0) + } + else if (psys->part->type == PART_HAIR && (psys->flag & PSYS_HAIR_DONE) == 0) { skip = 1; + } - if (!skip) + if (!skip) { psys_cache_child_paths(sim, cfra, 0, use_render_params); + } } } - else if (psys->pathcache) + else if (psys->pathcache) { psys_free_path_cache(psys, NULL); + } } static bool psys_hair_use_simulation(ParticleData *pa, float max_length) @@ -3119,13 +3272,15 @@ static bool psys_hair_use_simulation(ParticleData *pa, float max_length) HairKey *key; int k; - if (pa->totkey < 2) + if (pa->totkey < 2) { return false; + } for (k = 1, key = pa->hair + 1; k < pa->totkey; k++, key++) { float length = len_v3v3(key->co, (key - 1)->co); - if (length < min_length) + if (length < min_length) { return false; + } } return true; @@ -3187,8 +3342,9 @@ static void hair_create_input_mesh(ParticleSimulationData *sim, if (!(pa->flag & PARS_UNEXIST)) { for (k = 1, key = pa->hair + 1; k < pa->totkey; k++, key++) { float length = len_v3v3(key->co, (key - 1)->co); - if (max_length < length) + if (max_length < length) { max_length = length; + } } } } @@ -3263,14 +3419,17 @@ static void hair_create_input_mesh(ParticleSimulationData *sim, } /* roots and disabled hairs should be 1.0, the rest can be anything from 0.0 to 1.0 */ - if (use_hair) + if (use_hair) { dvert = hair_set_pinning(dvert, key->weight); - else + } + else { dvert = hair_set_pinning(dvert, 1.0f); + } mvert++; - if (k) + if (k) { medge++; + } } hair_index += pa->totkey + 1; @@ -3327,8 +3486,9 @@ static void do_hair_dynamics(ParticleSimulationData *sim) hair_create_input_mesh(sim, totpoint, totedge, &psys->hair_in_mesh, &psys->clmd->hairdata); - if (psys->hair_out_mesh) + if (psys->hair_out_mesh) { BKE_id_free(NULL, psys->hair_out_mesh); + } psys->clmd->point_cache = psys->pointcache; /* for hair sim we replace the internal cloth effector weights temporarily @@ -3358,26 +3518,31 @@ static void hair_step(ParticleSimulationData *sim, float cfra, const bool use_re LOOP_PARTICLES { pa->size = part->size; - if (part->randsize > 0.0f) + if (part->randsize > 0.0f) { pa->size *= 1.0f - part->randsize * psys_frand(psys, p + 1); + } - if (psys_frand(psys, p) > disp) + if (psys_frand(psys, p) > disp) { pa->flag |= PARS_NO_DISP; - else + } + else { pa->flag &= ~PARS_NO_DISP; + } } if (psys->recalc & ID_RECALC_PSYS_RESET) { /* need this for changing subsurf levels */ psys_calc_dmcache(sim->ob, sim->psmd->mesh_final, sim->psmd->mesh_original, psys); - if (psys->clmd) + if (psys->clmd) { cloth_free_modifier(psys->clmd); + } } /* dynamics with cloth simulation, psys->particles can be NULL with 0 particles [#25519] */ - if (psys->part->type == PART_HAIR && psys->flag & PSYS_HAIR_DYNAMICS && psys->particles) + if (psys->part->type == PART_HAIR && psys->flag & PSYS_HAIR_DYNAMICS && psys->particles) { do_hair_dynamics(sim); + } /* following lines were removed r29079 but cause bug [#22811], see report for details */ psys_update_effectors(sim); @@ -3397,8 +3562,9 @@ static void save_hair(ParticleSimulationData *sim, float UNUSED(cfra)) psys->lattice_deform_data = psys_create_lattice_deform_data(sim); - if (psys->totpart == 0) + if (psys->totpart == 0) { return; + } /* save new keys for elements if needed */ LOOP_PARTICLES @@ -3427,7 +3593,8 @@ static void save_hair(ParticleSimulationData *sim, float UNUSED(cfra)) pa->totkey++; - /* root is always in the origin of hair space so we set it to be so after the last key is saved*/ + /* Root is always in the origin of hair space + * so we set it to be so after the last key is saved. */ if (pa->totkey == psys->part->hair_step + 1) { zero_v3(root->co); } @@ -3471,34 +3638,43 @@ static float get_base_time_step(ParticleSettings *part) static void update_timestep(ParticleSystem *psys, ParticleSimulationData *sim) { float dt_target; - if (sim->courant_num == 0.0f) + if (sim->courant_num == 0.0f) { dt_target = 1.0f; - else + } + else { dt_target = psys->dt_frac * (psys->part->courant_target / sim->courant_num); + } /* Make sure the time step is reasonable. For some reason, the CLAMP macro * doesn't work here. The time step becomes too large. - z0r */ - if (dt_target < MIN_TIMESTEP) + if (dt_target < MIN_TIMESTEP) { dt_target = MIN_TIMESTEP; - else if (dt_target > get_base_time_step(psys->part)) + } + else if (dt_target > get_base_time_step(psys->part)) { dt_target = get_base_time_step(psys->part); + } /* Decrease time step instantly, but increase slowly. */ - if (dt_target > psys->dt_frac) + if (dt_target > psys->dt_frac) { psys->dt_frac = interpf(dt_target, psys->dt_frac, TIMESTEP_EXPANSION_FACTOR); - else + } + else { psys->dt_frac = dt_target; + } } static float sync_timestep(ParticleSystem *psys, float t_frac) { /* Sync with frame end if it's close. */ - if (t_frac == 1.0f) + if (t_frac == 1.0f) { return psys->dt_frac; - else if (t_frac + (psys->dt_frac * TIMESTEP_EXPANSION_TOLERANCE) >= 1.0f) + } + else if (t_frac + (psys->dt_frac * TIMESTEP_EXPANSION_TOLERANCE) >= 1.0f) { return 1.0f - t_frac; - else + } + else { return psys->dt_frac; + } } /************************************************/ @@ -3538,8 +3714,9 @@ static void dynamics_step_sph_ddr_task_cb_ex(void *__restrict userdata, /* actual fluids calculations */ sph_integrate(sim, pa, pa->state.time, sphdata); - if (sim->colliders) + if (sim->colliders) { collision_check(sim, p, pa->state.time, data->cfra); + } /* SPH particles are not physical particles, just interpolation * particles, thus rotation has not a direct sense for them */ @@ -3603,8 +3780,9 @@ static void dynamics_step_sph_classical_integrate_task_cb_ex( /* actual fluids calculations */ sph_integrate(sim, pa, pa->state.time, sphdata); - if (sim->colliders) + if (sim->colliders) { collision_check(sim, p, pa->state.time, data->cfra); + } /* SPH particles are not physical particles, just interpolation * particles, thus rotation has not a direct sense for them */ @@ -3639,8 +3817,9 @@ static void dynamics_step(ParticleSimulationData *sim, float cfra) { psys_get_texture(sim, pa, &ptex, PAMAP_SIZE, cfra); pa->size = part->size * ptex.size; - if (part->randsize > 0.0f) + if (part->randsize > 0.0f) { pa->size *= 1.0f - part->randsize * psys_frand(psys, p + 1); + } reset_particle(sim, pa, dtime, cfra); } @@ -3652,8 +3831,9 @@ static void dynamics_step(ParticleSimulationData *sim, float cfra) psys_update_effectors(sim); - if (part->type != PART_HAIR) + if (part->type != PART_HAIR) { sim->colliders = BKE_collider_cache_create(sim->depsgraph, sim->ob, part->collision_group); + } /* initialize physics type specific stuff */ switch (part->phystype) { @@ -3684,8 +3864,9 @@ static void dynamics_step(ParticleSimulationData *sim, float cfra) for (; pt; pt = pt->next) { /* Updating others systems particle tree for fluid-fluid interaction */ - if (pt->ob) + if (pt->ob) { psys_update_particle_bvhtree(BLI_findlink(&pt->ob->particlesystem, pt->psys - 1), cfra); + } } break; } @@ -3698,8 +3879,9 @@ static void dynamics_step(ParticleSimulationData *sim, float cfra) psys_get_texture(sim, pa, &ptex, PAMAP_SIZE, cfra); pa->size = part->size * ptex.size; - if (part->randsize > 0.0f) + if (part->randsize > 0.0f) { pa->size *= 1.0f - part->randsize * psys_frand(psys, p + 1); + } birthtime = pa->time; dietime = pa->dietime; @@ -3731,8 +3913,10 @@ static void dynamics_step(ParticleSimulationData *sim, float cfra) reset_particle(sim, pa, dtime, cfra); } - if (ELEM(pa->alive, PARS_ALIVE, PARS_DYING) == 0 || (pa->flag & (PARS_UNEXIST | PARS_NO_DISP))) + if (ELEM(pa->alive, PARS_ALIVE, PARS_DYING) == 0 || + (pa->flag & (PARS_UNEXIST | PARS_NO_DISP))) { pa->state.time = -1.f; + } } switch (part->phystype) { @@ -3743,8 +3927,9 @@ static void dynamics_step(ParticleSimulationData *sim, float cfra) basic_integrate(sim, p, pa->state.time, cfra); /* deflection */ - if (sim->colliders) + if (sim->colliders) { collision_check(sim, p, pa->state.time, cfra); + } /* rotations */ basic_rotate(part, pa, pa->state.time, timestep); @@ -3762,8 +3947,9 @@ static void dynamics_step(ParticleSimulationData *sim, float cfra) boid_body(&bbd, pa); /* deflection */ - if (sim->colliders) + if (sim->colliders) { collision_check(sim, p, pa->state.time, cfra); + } } } break; @@ -3857,8 +4043,9 @@ static void dynamics_step(ParticleSimulationData *sim, float cfra) pa->alive = PARS_DEAD; pa->state.time = pa->dietime; } - else + else { pa->state.time = cfra; + } } BKE_collider_cache_free(&sim->colliders); @@ -3868,18 +4055,21 @@ static void dynamics_step(ParticleSimulationData *sim, float cfra) static void update_children(ParticleSimulationData *sim, const bool use_render_params) { - if ((sim->psys->part->type == PART_HAIR) && (sim->psys->flag & PSYS_HAIR_DONE) == 0) + if ((sim->psys->part->type == PART_HAIR) && (sim->psys->flag & PSYS_HAIR_DONE) == 0) { /* don't generate children while growing hair - waste of time */ psys_free_children(sim->psys); + } else if (sim->psys->part->childtype) { - if (sim->psys->totchild != psys_get_tot_child(sim->scene, sim->psys, use_render_params)) + if (sim->psys->totchild != psys_get_tot_child(sim->scene, sim->psys, use_render_params)) { distribute_particles(sim, PART_FROM_CHILD); + } else { /* Children are up to date, nothing to do. */ } } - else + else { psys_free_children(sim->psys); + } } /* updates cached particles' alive & other flags etc..*/ static void cached_step(ParticleSimulationData *sim, float cfra, const bool use_render_params) @@ -3898,8 +4088,9 @@ static void cached_step(ParticleSimulationData *sim, float cfra, const bool use_ { psys_get_texture(sim, pa, &ptex, PAMAP_SIZE, cfra); pa->size = part->size * ptex.size; - if (part->randsize > 0.0f) + if (part->randsize > 0.0f) { pa->size *= 1.0f - part->randsize * psys_frand(psys, p + 1); + } psys->lattice_deform_data = psys_create_lattice_deform_data(sim); @@ -3908,23 +4099,28 @@ static void cached_step(ParticleSimulationData *sim, float cfra, const bool use_ /* update alive status and push events */ if (pa->time > cfra) { pa->alive = PARS_UNBORN; - if (part->flag & PART_UNBORN && (psys->pointcache->flag & PTCACHE_EXTERNAL) == 0) + if (part->flag & PART_UNBORN && (psys->pointcache->flag & PTCACHE_EXTERNAL) == 0) { reset_particle(sim, pa, 0.0f, cfra); + } } - else if (dietime <= cfra) + else if (dietime <= cfra) { pa->alive = PARS_DEAD; - else + } + else { pa->alive = PARS_ALIVE; + } if (psys->lattice_deform_data) { end_latt_deform(psys->lattice_deform_data); psys->lattice_deform_data = NULL; } - if (psys_frand(psys, p) > disp) + if (psys_frand(psys, p) > disp) { pa->flag |= PARS_NO_DISP; - else + } + else { pa->flag &= ~PARS_NO_DISP; + } } } @@ -4005,7 +4201,7 @@ static void particles_fluid_step(ParticleSimulationData *sim, float wrf; gzread(gzf, &wrf, sizeof(wrf)); pa->state.co[j] = wrf; - //fprintf(stderr,"Rj%d ",j); + // fprintf(stderr,"Rj%d ",j); } for (j = 0; j < 3; j++) { float wrf; @@ -4020,7 +4216,18 @@ static void particles_fluid_step(ParticleSimulationData *sim, pa->dietime = sim->scene->r.efra + 1; pa->lifetime = sim->scene->r.efra; pa->alive = PARS_ALIVE; - //if (a < 25) fprintf(stderr,"FSPARTICLE debug set %s, a%d = %f,%f,%f, life=%f\n", filename, a, pa->co[0],pa->co[1],pa->co[2], pa->lifetime ); +# if 0 + if (a < 25) { + fprintf(stderr, + "FSPARTICLE debug set %s, a%d = %f,%f,%f, life=%f\n", + filename, + a, + pa->co[0], + pa->co[1], + pa->co[2], + pa->lifetime); + } +# endif } else { // skip... @@ -4057,8 +4264,9 @@ static int emit_particles(ParticleSimulationData *sim, PTCacheID *pid, float UNU int oldtotpart = psys->totpart; int totpart = tot_particles(psys, pid); - if (totpart != oldtotpart) + if (totpart != oldtotpart) { realloc_particles(sim, totpart); + } return totpart - oldtotpart; } @@ -4084,8 +4292,9 @@ static void system_step(ParticleSimulationData *sim, float cfra, const bool use_ psys_clear_temp_pointcache(psys); /* set suitable cache range automatically */ - if ((cache->flag & (PTCACHE_BAKING | PTCACHE_BAKED)) == 0) + if ((cache->flag & (PTCACHE_BAKING | PTCACHE_BAKED)) == 0) { psys_get_pointcache_start_end(sim->scene, psys, &cache->startframe, &cache->endframe); + } pid = &ptcacheid; BKE_ptcache_id_from_particles(pid, sim->ob, psys); @@ -4135,8 +4344,9 @@ static void system_step(ParticleSimulationData *sim, float cfra, const bool use_ BKE_ptcache_validate(cache, (int)cache_cfra); - if (cache_result == PTCACHE_READ_INTERPOLATED && cache->flag & PTCACHE_REDO_NEEDED) + if (cache_result == PTCACHE_READ_INTERPOLATED && cache->flag & PTCACHE_REDO_NEEDED) { BKE_ptcache_write(pid, (int)cache_cfra); + } return; } @@ -4151,11 +4361,13 @@ static void system_step(ParticleSimulationData *sim, float cfra, const bool use_ } /* if on second frame, write cache for first frame */ - if (psys->cfra == startframe && (cache->flag & PTCACHE_OUTDATED || cache->last_exact == 0)) + if (psys->cfra == startframe && (cache->flag & PTCACHE_OUTDATED || cache->last_exact == 0)) { BKE_ptcache_write(pid, startframe); + } } - else + else { BKE_ptcache_invalidate(cache); + } /* 3. do dynamics */ /* set particles to be not calculated TODO: can't work with pointcache */ @@ -4163,10 +4375,12 @@ static void system_step(ParticleSimulationData *sim, float cfra, const bool use_ LOOP_PARTICLES { - if (psys_frand(psys, p) > disp) + if (psys_frand(psys, p) > disp) { pa->flag |= PARS_NO_DISP; - else + } + else { pa->flag &= ~PARS_NO_DISP; + } } if (psys->totpart) { @@ -4175,8 +4389,9 @@ static void system_step(ParticleSimulationData *sim, float cfra, const bool use_ /* handle negative frame start at the first frame by doing * all the steps before the first frame */ - if ((int)cfra == startframe && part->sta < startframe) + if ((int)cfra == startframe && part->sta < startframe) { totframesback = (startframe - (int)part->sta); + } if (!(part->time_flag & PART_TIME_AUTOSF)) { /* Constant time step */ @@ -4199,8 +4414,9 @@ static void system_step(ParticleSimulationData *sim, float cfra, const bool use_ dynamics_step(sim, cfra + dframe + t_frac - 1.f); psys->cfra = cfra + dframe + t_frac - 1.f; - if (part->time_flag & PART_TIME_AUTOSF) + if (part->time_flag & PART_TIME_AUTOSF) { update_timestep(psys, sim); + } /* Even without AUTOSF dt_frac may not add up to 1.0 due to float precision. */ dt_frac = sync_timestep(psys, t_frac); } @@ -4210,8 +4426,9 @@ static void system_step(ParticleSimulationData *sim, float cfra, const bool use_ /* 4. only write cache starting from second frame */ if (pid) { BKE_ptcache_validate(cache, (int)cache_cfra); - if ((int)cache_cfra != startframe) + if ((int)cache_cfra != startframe) { BKE_ptcache_write(pid, (int)cache_cfra); + } } update_children(sim, use_render_params); @@ -4231,18 +4448,22 @@ void psys_changed_type(Object *ob, ParticleSystem *psys) BKE_ptcache_id_from_particles(&pid, ob, psys); - if (part->phystype != PART_PHYS_KEYED) + if (part->phystype != PART_PHYS_KEYED) { psys->flag &= ~PSYS_KEYED; + } if (part->type == PART_HAIR) { - if (ELEM(part->ren_as, PART_DRAW_NOT, PART_DRAW_PATH, PART_DRAW_OB, PART_DRAW_GR) == 0) + if (ELEM(part->ren_as, PART_DRAW_NOT, PART_DRAW_PATH, PART_DRAW_OB, PART_DRAW_GR) == 0) { part->ren_as = PART_DRAW_PATH; + } - if (part->distr == PART_DISTR_GRID) + if (part->distr == PART_DISTR_GRID) { part->distr = PART_DISTR_JIT; + } - if (ELEM(part->draw_as, PART_DRAW_NOT, PART_DRAW_REND, PART_DRAW_PATH) == 0) + if (ELEM(part->draw_as, PART_DRAW_NOT, PART_DRAW_REND, PART_DRAW_PATH) == 0) { part->draw_as = PART_DRAW_REND; + } CLAMP(part->path_start, 0.0f, 100.0f); CLAMP(part->path_end, 0.0f, 100.0f); @@ -4265,8 +4486,9 @@ void psys_check_boid_data(ParticleSystem *psys) pa = psys->particles; - if (!pa) + if (!pa) { return; + } if (psys->part && psys->part->phystype == PART_PHYS_BOIDS) { if (!pa->boid) { @@ -4371,11 +4593,13 @@ void particle_system_update(struct Depsgraph *depsgraph, ParticleSystemModifierData *psmd = psys_get_modifier(ob, psys); /* drawdata is outdated after ANY change */ - if (psys->pdd) + if (psys->pdd) { psys->pdd->flag &= ~PARTICLE_DRAW_DATA_UPDATED; + } - if (!psys_check_enabled(ob, psys, use_render_params)) + if (!psys_check_enabled(ob, psys, use_render_params)) { return; + } cfra = DEG_get_ctime(depsgraph); @@ -4389,12 +4613,14 @@ void particle_system_update(struct Depsgraph *depsgraph, if (sim.psmd->flag & eParticleSystemFlag_psys_updated) { sim.psmd->flag &= ~eParticleSystemFlag_psys_updated; /* make sure it really was updated to cfra */ - if (psys->cfra == cfra) + if (psys->cfra == cfra) { return; + } } - if (!sim.psmd->mesh_final) + if (!sim.psmd->mesh_final) { return; + } if (part->from != PART_FROM_VERT) { BKE_mesh_tessface_ensure(sim.psmd->mesh_final); @@ -4403,8 +4629,9 @@ void particle_system_update(struct Depsgraph *depsgraph, /* to verify if we need to restore object afterwards */ psys->flag &= ~PSYS_OB_ANIM_RESTORE; - if (psys->recalc & ID_RECALC_PSYS_RESET) + if (psys->recalc & ID_RECALC_PSYS_RESET) { psys->totunexist = 0; + } /* setup necessary physics type dependent additional data if it doesn't yet exist */ psys_prepare_physics(&sim); @@ -4441,9 +4668,10 @@ void particle_system_update(struct Depsgraph *depsgraph, for (i = 0; i <= part->hair_step; i++) { hcfra = 100.0f * (float)i / (float)psys->part->hair_step; - if ((part->flag & PART_HAIR_REGROW) == 0) + if ((part->flag & PART_HAIR_REGROW) == 0) { BKE_animsys_evaluate_animdata( depsgraph, scene, &part_local->id, part_local->adt, hcfra, ADT_RECALC_ANIM); + } system_step(&sim, hcfra, use_render_params); psys->cfra = hcfra; psys->recalc = 0; @@ -4458,11 +4686,13 @@ void particle_system_update(struct Depsgraph *depsgraph, psys->flag |= PSYS_HAIR_DONE; psys->recalc = recalc; } - else if (psys->flag & PSYS_EDITED) + else if (psys->flag & PSYS_EDITED) { psys->flag |= PSYS_HAIR_DONE; + } - if (psys->flag & PSYS_HAIR_DONE) + if (psys->flag & PSYS_HAIR_DONE) { hair_step(&sim, cfra, use_render_params); + } break; } case PART_FLUID: { @@ -4478,8 +4708,9 @@ void particle_system_update(struct Depsgraph *depsgraph, bool free_unexisting = false; /* Particles without dynamics haven't been reset yet because they don't use pointcache */ - if (psys->recalc & ID_RECALC_PSYS_RESET) + if (psys->recalc & ID_RECALC_PSYS_RESET) { psys_reset(psys, PSYS_RESET_ALL); + } if (emit_particles(&sim, NULL, cfra) || (psys->recalc & ID_RECALC_PSYS_RESET)) { free_keyed_keys(psys); @@ -4494,20 +4725,24 @@ void particle_system_update(struct Depsgraph *depsgraph, LOOP_EXISTING_PARTICLES { pa->size = part->size; - if (part->randsize > 0.0f) + if (part->randsize > 0.0f) { pa->size *= 1.0f - part->randsize * psys_frand(psys, p + 1); + } reset_particle(&sim, pa, 0.0, cfra); - if (psys_frand(psys, p) > disp) + if (psys_frand(psys, p) > disp) { pa->flag |= PARS_NO_DISP; - else + } + else { pa->flag &= ~PARS_NO_DISP; + } } /* free unexisting after resetting particles */ - if (free_unexisting) + if (free_unexisting) { free_unexisting_particles(&sim); + } if (part->phystype == PART_PHYS_KEYED) { psys_count_keyed_targets(&sim); @@ -4551,7 +4786,8 @@ void particle_system_update(struct Depsgraph *depsgraph, } } - /* save matrix for duplicators, at rendertime the actual dupliobject's matrix is used so don't update! */ + /* Save matrix for duplicators, + * at rendertime the actual dupliobject's matrix is used so don't update! */ invert_m4_m4(psys->imat, ob->obmat); BKE_particle_batch_cache_dirty_tag(psys, BKE_PARTICLE_BATCH_DIRTY_ALL); diff --git a/source/blender/blenkernel/intern/pbvh.c b/source/blender/blenkernel/intern/pbvh.c index 445205a513a..c186394880b 100644 --- a/source/blender/blenkernel/intern/pbvh.c +++ b/source/blender/blenkernel/intern/pbvh.c @@ -101,27 +101,33 @@ int BB_widest_axis(const BB *bb) { float dim[3]; - for (int i = 0; i < 3; ++i) + for (int i = 0; i < 3; ++i) { dim[i] = bb->bmax[i] - bb->bmin[i]; + } if (dim[0] > dim[1]) { - if (dim[0] > dim[2]) + if (dim[0] > dim[2]) { return 0; - else + } + else { return 2; + } } else { - if (dim[1] > dim[2]) + if (dim[1] > dim[2]) { return 1; - else + } + else { return 2; + } } } void BBC_update_centroid(BBC *bbc) { - for (int i = 0; i < 3; ++i) + for (int i = 0; i < 3; ++i) { bbc->bcentroid[i] = (bbc->bmin[i] + bbc->bmax[i]) * 0.5f; + } } /* Not recursive */ @@ -148,12 +154,12 @@ static void update_node_vb(PBVH *bvh, PBVHNode *node) node->vb = vb; } -//void BKE_pbvh_node_BB_reset(PBVHNode *node) +// void BKE_pbvh_node_BB_reset(PBVHNode *node) //{ // BB_reset(&node->vb); //} // -//void BKE_pbvh_node_BB_expand(PBVHNode *node, float co[3]) +// void BKE_pbvh_node_BB_expand(PBVHNode *node, float co[3]) //{ // BB_expand(&node->vb, co); //} @@ -174,13 +180,16 @@ static int partition_indices(int *prim_indices, int lo, int hi, int axis, float { int i = lo, j = hi; for (;;) { - for (; prim_bbc[prim_indices[i]].bcentroid[axis] < mid; i++) + for (; prim_bbc[prim_indices[i]].bcentroid[axis] < mid; i++) { ; - for (; mid < prim_bbc[prim_indices[j]].bcentroid[axis]; j--) + } + for (; mid < prim_bbc[prim_indices[j]].bcentroid[axis]; j--) { ; + } - if (!(i < j)) + if (!(i < j)) { return i; + } SWAP(int, prim_indices[i], prim_indices[j]); i++; @@ -197,27 +206,34 @@ static int partition_indices_material(PBVH *bvh, int lo, int hi) const void *first; int i = lo, j = hi; - if (bvh->looptri) + if (bvh->looptri) { first = &mpoly[looptri[bvh->prim_indices[lo]].poly]; - else + } + else { first = &flagmats[bvh->prim_indices[lo]]; + } for (;;) { if (bvh->looptri) { - for (; face_materials_match(first, &mpoly[looptri[indices[i]].poly]); i++) + for (; face_materials_match(first, &mpoly[looptri[indices[i]].poly]); i++) { ; - for (; !face_materials_match(first, &mpoly[looptri[indices[j]].poly]); j--) + } + for (; !face_materials_match(first, &mpoly[looptri[indices[j]].poly]); j--) { ; + } } else { - for (; grid_materials_match(first, &flagmats[indices[i]]); i++) + for (; grid_materials_match(first, &flagmats[indices[i]]); i++) { ; - for (; !grid_materials_match(first, &flagmats[indices[j]]); j--) + } + for (; !grid_materials_match(first, &flagmats[indices[j]]); j--) { ; + } } - if (!(i < j)) + if (!(i < j)) { return i; + } SWAP(int, bvh->prim_indices[i], bvh->prim_indices[j]); i++; @@ -228,8 +244,9 @@ void pbvh_grow_nodes(PBVH *bvh, int totnode) { if (UNLIKELY(totnode > bvh->node_mem_count)) { bvh->node_mem_count = bvh->node_mem_count + (bvh->node_mem_count / 3); - if (bvh->node_mem_count < totnode) + if (bvh->node_mem_count < totnode) { bvh->node_mem_count = totnode; + } bvh->nodes = MEM_recallocN(bvh->nodes, sizeof(PBVHNode) * bvh->node_mem_count); } @@ -300,8 +317,9 @@ static void build_mesh_leaf_node(PBVH *bvh, PBVHNode *node) void *value = BLI_ghashIterator_getValue(&gh_iter); int ndx = POINTER_AS_INT(value); - if (ndx < 0) + if (ndx < 0) { ndx = -ndx + node->uniq_verts - 1; + } vert_indices[ndx] = POINTER_AS_INT(BLI_ghashIterator_getKey(&gh_iter)); } @@ -310,8 +328,9 @@ static void build_mesh_leaf_node(PBVH *bvh, PBVHNode *node) const int sides = 3; for (int j = 0; j < sides; ++j) { - if (face_vert_indices[i][j] < 0) + if (face_vert_indices[i][j] < 0) { face_vert_indices[i][j] = -face_vert_indices[i][j] + node->uniq_verts - 1; + } } } @@ -350,13 +369,15 @@ int BKE_pbvh_count_grid_quads(BLI_bitmap **grid_hidden, /* grid hidden are present, have to check each element */ for (int y = 0; y < gridsize - 1; y++) { for (int x = 0; x < gridsize - 1; x++) { - if (!paint_is_grid_face_hidden(gh, gridsize, x, y)) + if (!paint_is_grid_face_hidden(gh, gridsize, x, y)) { totquad++; + } } } } - else + else { totquad += gridarea; + } } return totquad; @@ -380,8 +401,9 @@ static void build_leaf(PBVH *bvh, int node_index, BBC *prim_bbc, int offset, int /* Still need vb for searches */ update_vb(bvh, &bvh->nodes[node_index], prim_bbc, offset, count); - if (bvh->looptri) + if (bvh->looptri) { build_mesh_leaf_node(bvh, bvh->nodes + node_index); + } else { build_grid_leaf_node(bvh, bvh->nodes + node_index); } @@ -391,8 +413,9 @@ static void build_leaf(PBVH *bvh, int node_index, BBC *prim_bbc, int offset, int * same material (including flat/smooth shading), non-zero otherwise */ static bool leaf_needs_material_split(PBVH *bvh, int offset, int count) { - if (count <= 1) + if (count <= 1) { return false; + } if (bvh->looptri) { const MLoopTri *first = &bvh->looptri[bvh->prim_indices[offset]]; @@ -411,8 +434,9 @@ static bool leaf_needs_material_split(PBVH *bvh, int offset, int count) for (int i = offset + count - 1; i > offset; --i) { int prim = bvh->prim_indices[i]; - if (!grid_materials_match(first, &bvh->grid_flag_mats[prim])) + if (!grid_materials_match(first, &bvh->grid_flag_mats[prim])) { return true; + } } } @@ -456,8 +480,9 @@ static void build_sub(PBVH *bvh, int node_index, BB *cb, BBC *prim_bbc, int offs if (!cb) { cb = &cb_backing; BB_reset(cb); - for (int i = offset + count - 1; i >= offset; --i) + for (int i = offset + count - 1; i >= offset; --i) { BB_expand(cb, prim_bbc[bvh->prim_indices[i]].bcentroid); + } } const int axis = BB_widest_axis(cb); @@ -484,13 +509,16 @@ static void pbvh_build(PBVH *bvh, BB *cb, BBC *prim_bbc, int totprim) { if (totprim != bvh->totprim) { bvh->totprim = totprim; - if (bvh->nodes) + if (bvh->nodes) { MEM_freeN(bvh->nodes); - if (bvh->prim_indices) + } + if (bvh->prim_indices) { MEM_freeN(bvh->prim_indices); + } bvh->prim_indices = MEM_mallocN(sizeof(int) * totprim, "bvh prim indices"); - for (int i = 0; i < totprim; ++i) + for (int i = 0; i < totprim; ++i) { bvh->prim_indices[i] = i; + } bvh->totnode = 0; if (bvh->node_mem_count < 100) { bvh->node_mem_count = 100; @@ -505,8 +533,8 @@ static void pbvh_build(PBVH *bvh, BB *cb, BBC *prim_bbc, int totprim) /** * Do a full rebuild with on Mesh data structure. * - * \note Unlike mpoly/mloop/verts, looptri is **totally owned** by PBVH (which means it may rewrite it if needed, - * see #BKE_pbvh_apply_vertCos(). + * \note Unlike mpoly/mloop/verts, looptri is **totally owned** by PBVH + * (which means it may rewrite it if needed, see #BKE_pbvh_apply_vertCos(). */ void BKE_pbvh_build_mesh(PBVH *bvh, const MPoly *mpoly, @@ -514,6 +542,7 @@ void BKE_pbvh_build_mesh(PBVH *bvh, MVert *verts, int totvert, struct CustomData *vdata, + struct CustomData *ldata, const MLoopTri *looptri, int looptri_num) { @@ -529,6 +558,7 @@ void BKE_pbvh_build_mesh(PBVH *bvh, bvh->totvert = totvert; bvh->leaf_limit = LEAF_LIMIT; bvh->vdata = vdata; + bvh->ldata = ldata; BB_reset(&cb); @@ -542,16 +572,18 @@ void BKE_pbvh_build_mesh(PBVH *bvh, BB_reset((BB *)bbc); - for (int j = 0; j < sides; ++j) + for (int j = 0; j < sides; ++j) { BB_expand((BB *)bbc, verts[bvh->mloop[lt->tri[j]].v].co); + } BBC_update_centroid(bbc); BB_expand(&cb, bbc->bcentroid); } - if (looptri_num) + if (looptri_num) { pbvh_build(bvh, &cb, prim_bbc, looptri_num); + } MEM_freeN(prim_bbc); MEM_freeN(bvh->vert_bitmap); @@ -589,16 +621,18 @@ void BKE_pbvh_build_grids(PBVH *bvh, BB_reset((BB *)bbc); - for (int j = 0; j < gridsize * gridsize; ++j) + for (int j = 0; j < gridsize * gridsize; ++j) { BB_expand((BB *)bbc, CCG_elem_offset_co(key, grid, j)); + } BBC_update_centroid(bbc); BB_expand(&cb, bbc->bcentroid); } - if (totgrid) + if (totgrid) { pbvh_build(bvh, &cb, prim_bbc, totgrid); + } MEM_freeN(prim_bbc); } @@ -616,20 +650,26 @@ void BKE_pbvh_free(PBVH *bvh) PBVHNode *node = &bvh->nodes[i]; if (node->flag & PBVH_Leaf) { - if (node->draw_buffers) + if (node->draw_buffers) { GPU_pbvh_buffers_free(node->draw_buffers); - if (node->vert_indices) + } + if (node->vert_indices) { MEM_freeN((void *)node->vert_indices); - if (node->face_vert_indices) + } + if (node->face_vert_indices) { MEM_freeN((void *)node->face_vert_indices); + } BKE_pbvh_node_layer_disp_free(node); - if (node->bm_faces) + if (node->bm_faces) { BLI_gset_free(node->bm_faces, NULL); - if (node->bm_unique_verts) + } + if (node->bm_unique_verts) { BLI_gset_free(node->bm_unique_verts, NULL); - if (node->bm_other_verts) + } + if (node->bm_other_verts) { BLI_gset_free(node->bm_other_verts, NULL); + } } } @@ -645,19 +685,22 @@ void BKE_pbvh_free(PBVH *bvh) MEM_freeN((void *)bvh->looptri); } - if (bvh->nodes) + if (bvh->nodes) { MEM_freeN(bvh->nodes); + } - if (bvh->prim_indices) + if (bvh->prim_indices) { MEM_freeN(bvh->prim_indices); + } MEM_freeN(bvh); } void BKE_pbvh_free_layer_disp(PBVH *bvh) { - for (int i = 0; i < bvh->totnode; ++i) + for (int i = 0; i < bvh->totnode; ++i) { BKE_pbvh_node_layer_disp_free(&bvh->nodes[i]); + } } static void pbvh_iter_begin(PBVHIter *iter, @@ -679,8 +722,9 @@ static void pbvh_iter_begin(PBVHIter *iter, static void pbvh_iter_end(PBVHIter *iter) { - if (iter->stackspace > STACK_FIXED_DEPTH) + if (iter->stackspace > STACK_FIXED_DEPTH) { MEM_freeN(iter->stack); + } } static void pbvh_stack_push(PBVHIter *iter, PBVHNode *node, bool revisiting) @@ -713,17 +757,20 @@ static PBVHNode *pbvh_iter_next(PBVHIter *iter) /* on a mesh with no faces this can happen * can remove this check if we know meshes have at least 1 face */ - if (node == NULL) + if (node == NULL) { return NULL; + } bool revisiting = iter->stack[iter->stacksize].revisiting; /* revisiting node already checked */ - if (revisiting) + if (revisiting) { return node; + } - if (iter->scb && !iter->scb(node, iter->search_data)) + if (iter->scb && !iter->scb(node, iter->search_data)) { continue; /* don't traverse, outside of search zone */ + } if (node->flag & PBVH_Leaf) { /* immediately hit leaf node */ @@ -751,11 +798,13 @@ static PBVHNode *pbvh_iter_next_occluded(PBVHIter *iter) /* on a mesh with no faces this can happen * can remove this check if we know meshes have at least 1 face */ - if (node == NULL) + if (node == NULL) { return NULL; + } - if (iter->scb && !iter->scb(node, iter->search_data)) + if (iter->scb && !iter->scb(node, iter->search_data)) { continue; /* don't traverse, outside of search zone */ + } if (node->flag & PBVH_Leaf) { /* immediately hit leaf node */ @@ -814,9 +863,11 @@ void BKE_pbvh_search_callback(PBVH *bvh, pbvh_iter_begin(&iter, bvh, scb, search_data); - while ((node = pbvh_iter_next(&iter))) - if (node->flag & PBVH_Leaf) + while ((node = pbvh_iter_next(&iter))) { + if (node->flag & PBVH_Leaf) { hcb(node, hit_data); + } + } pbvh_iter_end(&iter); } @@ -853,13 +904,15 @@ static void traverse_tree(node_tree *tree, void *hit_data, float *tmin) { - if (tree->left) + if (tree->left) { traverse_tree(tree->left, hcb, hit_data, tmin); + } hcb(tree->data, hit_data, tmin); - if (tree->right) + if (tree->right) { traverse_tree(tree->right, hcb, hit_data, tmin); + } } static void free_tree(node_tree *tree) @@ -925,8 +978,9 @@ static bool update_search_cb(PBVHNode *node, void *data_v) { int flag = POINTER_AS_INT(data_v); - if (node->flag & PBVH_Leaf) + if (node->flag & PBVH_Leaf) { return (node->flag & flag) != 0; + } return true; } @@ -984,9 +1038,10 @@ static void pbvh_update_normals_accum_task_cb(void *__restrict userdata, const int v = vtri[j]; if (bvh->verts[v].flag & ME_VERT_PBVH_UPDATE) { - /* Note: This avoids `lock, add_v3_v3, unlock` and is five to ten times quicker than a spinlock. - * Not exact equivalent though, since atomicity is only ensured for one component - * of the vector at a time, but here it shall not make any sensible difference. */ + /* Note: This avoids `lock, add_v3_v3, unlock` + * and is five to ten times quicker than a spinlock. + * Not exact equivalent though, since atomicity is only ensured for one component + * of the vector at a time, but here it shall not make any sensible difference. */ for (int k = 3; k--;) { atomic_add_and_fetch_fl(&vnors[v][k], fn[k]); } @@ -1035,8 +1090,9 @@ static void pbvh_update_normals(PBVH *bvh, PBVHNode **nodes, int totnode, float return; } - if (bvh->type != PBVH_FACES) + if (bvh->type != PBVH_FACES) { return; + } /* could be per node to save some memory, but also means * we have to store for each vertex which node it is in */ @@ -1079,16 +1135,19 @@ static void pbvh_update_BB_redraw_task_cb(void *__restrict userdata, PBVHNode *node = data->nodes[n]; const int flag = data->flag; - if ((flag & PBVH_UpdateBB) && (node->flag & PBVH_UpdateBB)) + if ((flag & PBVH_UpdateBB) && (node->flag & PBVH_UpdateBB)) { /* don't clear flag yet, leave it for flushing later */ /* Note that bvh usage is read-only here, so no need to thread-protect it. */ update_node_vb(bvh, node); + } - if ((flag & PBVH_UpdateOriginalBB) && (node->flag & PBVH_UpdateOriginalBB)) + if ((flag & PBVH_UpdateOriginalBB) && (node->flag & PBVH_UpdateOriginalBB)) { node->orig_vb = node->vb; + } - if ((flag & PBVH_UpdateRedraw) && (node->flag & PBVH_UpdateRedraw)) + if ((flag & PBVH_UpdateRedraw) && (node->flag & PBVH_UpdateRedraw)) { node->flag &= ~PBVH_UpdateRedraw; + } } void pbvh_update_BB_redraw(PBVH *bvh, PBVHNode **nodes, int totnode, int flag) @@ -1106,14 +1165,15 @@ void pbvh_update_BB_redraw(PBVH *bvh, PBVHNode **nodes, int totnode, int flag) BLI_task_parallel_range(0, totnode, &data, pbvh_update_BB_redraw_task_cb, &settings); } -static int pbvh_get_buffers_update_flags(PBVH *bvh) +static int pbvh_get_buffers_update_flags(PBVH *bvh, bool show_vcol) { int update_flags = 0; update_flags |= bvh->show_mask ? GPU_PBVH_BUFFERS_SHOW_MASK : 0; + update_flags |= show_vcol ? GPU_PBVH_BUFFERS_SHOW_VCOL : 0; return update_flags; } -static void pbvh_update_draw_buffers(PBVH *bvh, PBVHNode **nodes, int totnode) +static void pbvh_update_draw_buffers(PBVH *bvh, PBVHNode **nodes, int totnode, bool show_vcol) { /* can't be done in parallel with OpenGL */ for (int n = 0; n < totnode; n++) { @@ -1144,7 +1204,7 @@ static void pbvh_update_draw_buffers(PBVH *bvh, PBVHNode **nodes, int totnode) } if (node->flag & PBVH_UpdateDrawBuffers) { - const int update_flags = pbvh_get_buffers_update_flags(bvh); + const int update_flags = pbvh_get_buffers_update_flags(bvh, show_vcol); switch (bvh->type) { case PBVH_GRIDS: GPU_pbvh_grid_buffers_update(node->draw_buffers, @@ -1161,6 +1221,7 @@ static void pbvh_update_draw_buffers(PBVH *bvh, PBVHNode **nodes, int totnode) node->vert_indices, node->uniq_verts + node->face_verts, CustomData_get_layer(bvh->vdata, CD_PAINT_MASK), + CustomData_get_layer(bvh->ldata, CD_MLOOPCOL), node->face_vert_indices, update_flags); break; @@ -1201,10 +1262,12 @@ static int pbvh_flush_bb(PBVH *bvh, PBVHNode *node, int flag) update |= pbvh_flush_bb(bvh, bvh->nodes + node->children_offset, flag); update |= pbvh_flush_bb(bvh, bvh->nodes + node->children_offset + 1, flag); - if (update & PBVH_UpdateBB) + if (update & PBVH_UpdateBB) { update_node_vb(bvh, node); - if (update & PBVH_UpdateOriginalBB) + } + if (update & PBVH_UpdateOriginalBB) { node->orig_vb = node->vb; + } } return update; @@ -1212,25 +1275,30 @@ static int pbvh_flush_bb(PBVH *bvh, PBVHNode *node, int flag) void BKE_pbvh_update(PBVH *bvh, int flag, float (*fnors)[3]) { - if (!bvh->nodes) + if (!bvh->nodes) { return; + } PBVHNode **nodes; int totnode; BKE_pbvh_search_gather(bvh, update_search_cb, POINTER_FROM_INT(flag), &nodes, &totnode); - if (flag & PBVH_UpdateNormals) + if (flag & PBVH_UpdateNormals) { pbvh_update_normals(bvh, nodes, totnode, fnors); + } - if (flag & (PBVH_UpdateBB | PBVH_UpdateOriginalBB | PBVH_UpdateRedraw)) + if (flag & (PBVH_UpdateBB | PBVH_UpdateOriginalBB | PBVH_UpdateRedraw)) { pbvh_update_BB_redraw(bvh, nodes, totnode, flag); + } - if (flag & (PBVH_UpdateBB | PBVH_UpdateOriginalBB)) + if (flag & (PBVH_UpdateBB | PBVH_UpdateOriginalBB)) { pbvh_flush_bb(bvh, bvh->nodes, flag); + } - if (nodes) + if (nodes) { MEM_freeN(nodes); + } } void BKE_pbvh_redraw_BB(PBVH *bvh, float bb_min[3], float bb_max[3]) @@ -1243,9 +1311,11 @@ void BKE_pbvh_redraw_BB(PBVH *bvh, float bb_min[3], float bb_max[3]) pbvh_iter_begin(&iter, bvh, NULL, NULL); - while ((node = pbvh_iter_next(&iter))) - if (node->flag & PBVH_UpdateRedraw) + while ((node = pbvh_iter_next(&iter))) { + if (node->flag & PBVH_UpdateRedraw) { BB_expand_with_bb(&bb, &node->vb); + } + } pbvh_iter_end(&iter); @@ -1268,8 +1338,9 @@ void BKE_pbvh_get_grid_updates(PBVH *bvh, bool clear, void ***r_gridfaces, int * BLI_gset_add(face_set, face); } - if (clear) + if (clear) { node->flag &= ~PBVH_UpdateNormals; + } } } @@ -1287,8 +1358,7 @@ void BKE_pbvh_get_grid_updates(PBVH *bvh, bool clear, void ***r_gridfaces, int * GSetIterator gs_iter; int i; - GSET_ITER_INDEX(gs_iter, face_set, i) - { + GSET_ITER_INDEX (gs_iter, face_set, i) { faces[i] = BLI_gsetIterator_getKey(&gs_iter); } @@ -1380,10 +1450,12 @@ void BKE_pbvh_node_fully_hidden_set(PBVHNode *node, int fully_hidden) { BLI_assert(node->flag & PBVH_Leaf); - if (fully_hidden) + if (fully_hidden) { node->flag |= PBVH_FullyHidden; - else + } + else { node->flag &= ~PBVH_FullyHidden; + } } void BKE_pbvh_node_get_verts(PBVH *bvh, @@ -1407,23 +1479,29 @@ void BKE_pbvh_node_num_verts(PBVH *bvh, PBVHNode *node, int *r_uniquevert, int * switch (bvh->type) { case PBVH_GRIDS: tot = node->totprim * bvh->gridkey.grid_area; - if (r_totvert) + if (r_totvert) { *r_totvert = tot; - if (r_uniquevert) + } + if (r_uniquevert) { *r_uniquevert = tot; + } break; case PBVH_FACES: - if (r_totvert) + if (r_totvert) { *r_totvert = node->uniq_verts + node->face_verts; - if (r_uniquevert) + } + if (r_uniquevert) { *r_uniquevert = node->uniq_verts; + } break; case PBVH_BMESH: tot = BLI_gset_len(node->bm_unique_verts); - if (r_totvert) + if (r_totvert) { *r_totvert = tot + BLI_gset_len(node->bm_other_verts); - if (r_uniquevert) + } + if (r_uniquevert) { *r_uniquevert = tot; + } break; } } @@ -1438,29 +1516,39 @@ void BKE_pbvh_node_get_grids(PBVH *bvh, { switch (bvh->type) { case PBVH_GRIDS: - if (r_grid_indices) + if (r_grid_indices) { *r_grid_indices = node->prim_indices; - if (r_totgrid) + } + if (r_totgrid) { *r_totgrid = node->totprim; - if (r_maxgrid) + } + if (r_maxgrid) { *r_maxgrid = bvh->totgrid; - if (r_gridsize) + } + if (r_gridsize) { *r_gridsize = bvh->gridkey.grid_size; - if (r_griddata) + } + if (r_griddata) { *r_griddata = bvh->grids; + } break; case PBVH_FACES: case PBVH_BMESH: - if (r_grid_indices) + if (r_grid_indices) { *r_grid_indices = NULL; - if (r_totgrid) + } + if (r_totgrid) { *r_totgrid = 0; - if (r_maxgrid) + } + if (r_maxgrid) { *r_maxgrid = 0; - if (r_gridsize) + } + if (r_gridsize) { *r_gridsize = 0; - if (r_griddata) + } + if (r_griddata) { *r_griddata = NULL; + } break; } } @@ -1480,16 +1568,20 @@ void BKE_pbvh_node_get_original_BB(PBVHNode *node, float bb_min[3], float bb_max void BKE_pbvh_node_get_proxies(PBVHNode *node, PBVHProxyNode **proxies, int *proxy_count) { if (node->proxy_count > 0) { - if (proxies) + if (proxies) { *proxies = node->proxies; - if (proxy_count) + } + if (proxy_count) { *proxy_count = node->proxy_count; + } } else { - if (proxies) + if (proxies) { *proxies = NULL; - if (proxy_count) + } + if (proxy_count) { *proxy_count = 0; + } } } @@ -1700,8 +1792,9 @@ static bool pbvh_faces_node_raycast(PBVH *bvh, const MLoopTri *lt = &bvh->looptri[faces[i]]; const int *face_verts = node->face_vert_indices[i]; - if (paint_is_face_hidden(lt, vert, mloop)) + if (paint_is_face_hidden(lt, vert, mloop)) { continue; + } if (origco) { /* intersect with backuped original coordinates */ @@ -1741,8 +1834,9 @@ static bool pbvh_grids_node_raycast(PBVH *bvh, CCGElem *grid = bvh->grids[node->prim_indices[i]]; BLI_bitmap *gh; - if (!grid) + if (!grid) { continue; + } gh = bvh->grid_hidden[node->prim_indices[i]]; @@ -1750,8 +1844,9 @@ static bool pbvh_grids_node_raycast(PBVH *bvh, for (int x = 0; x < gridsize - 1; ++x) { /* check if grid face is hidden */ if (gh) { - if (paint_is_grid_face_hidden(gh, gridsize, x, y)) + if (paint_is_grid_face_hidden(gh, gridsize, x, y)) { continue; + } } if (origco) { @@ -1775,8 +1870,9 @@ static bool pbvh_grids_node_raycast(PBVH *bvh, } } - if (origco) + if (origco) { origco += gridsize * gridsize; + } } return hit; @@ -1792,8 +1888,9 @@ bool BKE_pbvh_node_raycast(PBVH *bvh, { bool hit = false; - if (node->flag & PBVH_FullyHidden) + if (node->flag & PBVH_FullyHidden) { return false; + } switch (bvh->type) { case PBVH_FACES: @@ -1821,13 +1918,15 @@ void BKE_pbvh_raycast_project_ray_root( float offset = 1.0f + 1e-3f; float offset_vec[3] = {1e-3f, 1e-3f, 1e-3f}; - if (original) + if (original) { BKE_pbvh_node_get_original_BB(bvh->nodes, bb_min_root, bb_max_root); - else + } + else { BKE_pbvh_node_get_BB(bvh->nodes, bb_min_root, bb_max_root); + } - /* slightly offset min and max in case we have a zero width node (due to a plane mesh for instance), - * or faces very close to the bounding box boundary. */ + /* Slightly offset min and max in case we have a zero width node + * (due to a plane mesh for instance), or faces very close to the bounding box boundary. */ mid_v3_v3v3(bb_center, bb_max_root, bb_min_root); /* diff should be same for both min/max since it's calculated from center */ sub_v3_v3v3(bb_diff, bb_max_root, bb_center); @@ -1838,15 +1937,17 @@ void BKE_pbvh_raycast_project_ray_root( /* first project start ray */ isect_ray_aabb_v3_precalc(&ray, ray_start, ray_normal); - if (!isect_ray_aabb_v3(&ray, bb_min_root, bb_max_root, &rootmin_start)) + if (!isect_ray_aabb_v3(&ray, bb_min_root, bb_max_root, &rootmin_start)) { return; + } /* then the end ray */ mul_v3_v3fl(ray_normal_inv, ray_normal, -1.0); isect_ray_aabb_v3_precalc(&ray, ray_end, ray_normal_inv); /* unlikely to fail exiting if entering succeeded, still keep this here */ - if (!isect_ray_aabb_v3(&ray, bb_min_root, bb_max_root, &rootmin_end)) + if (!isect_ray_aabb_v3(&ray, bb_min_root, bb_max_root, &rootmin_end)) { return; + } madd_v3_v3v3fl(ray_start, ray_start, ray_normal, rootmin_start); madd_v3_v3v3fl(ray_end, ray_end, ray_normal_inv, rootmin_end); @@ -1916,8 +2017,9 @@ static bool pbvh_faces_node_nearest_to_ray(PBVH *bvh, const MLoopTri *lt = &bvh->looptri[faces[i]]; const int *face_verts = node->face_vert_indices[i]; - if (paint_is_face_hidden(lt, vert, mloop)) + if (paint_is_face_hidden(lt, vert, mloop)) { continue; + } if (origco) { /* intersect with backuped original coordinates */ @@ -1960,8 +2062,9 @@ static bool pbvh_grids_node_nearest_to_ray(PBVH *bvh, CCGElem *grid = bvh->grids[node->prim_indices[i]]; BLI_bitmap *gh; - if (!grid) + if (!grid) { continue; + } gh = bvh->grid_hidden[node->prim_indices[i]]; @@ -1969,8 +2072,9 @@ static bool pbvh_grids_node_nearest_to_ray(PBVH *bvh, for (int x = 0; x < gridsize - 1; ++x) { /* check if grid face is hidden */ if (gh) { - if (paint_is_grid_face_hidden(gh, gridsize, x, y)) + if (paint_is_grid_face_hidden(gh, gridsize, x, y)) { continue; + } } if (origco) { @@ -1996,8 +2100,9 @@ static bool pbvh_grids_node_nearest_to_ray(PBVH *bvh, } } - if (origco) + if (origco) { origco += gridsize * gridsize; + } } return hit; @@ -2014,8 +2119,9 @@ bool BKE_pbvh_node_find_nearest_to_ray(PBVH *bvh, { bool hit = false; - if (node->flag & PBVH_FullyHidden) + if (node->flag & PBVH_FullyHidden) { return false; + } switch (bvh->type) { case PBVH_FACES: @@ -2065,10 +2171,12 @@ static PlaneAABBIsect test_planes_aabb(const float bb_min[3], } } - if (dot_v3v3(planes[i], vmin) + planes[i][3] > 0) + if (dot_v3v3(planes[i], vmin) + planes[i][3] > 0) { return ISECT_OUTSIDE; - else if (dot_v3v3(planes[i], vmax) + planes[i][3] >= 0) + } + else if (dot_v3v3(planes[i], vmax) + planes[i][3] >= 0) { ret = ISECT_INTERSECT; + } } return ret; @@ -2126,6 +2234,7 @@ void BKE_pbvh_draw_cb(PBVH *bvh, bool fast, bool wires, bool only_mask, + bool show_vcol, void (*draw_fn)(void *user_data, GPUBatch *batch), void *user_data) { @@ -2146,10 +2255,11 @@ void BKE_pbvh_draw_cb(PBVH *bvh, &totnode); pbvh_update_normals(bvh, nodes, totnode, fnors); - pbvh_update_draw_buffers(bvh, nodes, totnode); + pbvh_update_draw_buffers(bvh, nodes, totnode, show_vcol); - if (nodes) + if (nodes) { MEM_freeN(nodes); + } if (planes) { BKE_pbvh_search_callback( @@ -2174,8 +2284,9 @@ void BKE_pbvh_grids_update( bvh->grid_flag_mats = flagmats; bvh->grid_hidden = grid_hidden; - for (int a = 0; a < bvh->totnode; ++a) + for (int a = 0; a < bvh->totnode; ++a) { BKE_pbvh_node_mark_rebuild_draw(&bvh->nodes[a]); + } } } @@ -2231,7 +2342,8 @@ void BKE_pbvh_apply_vertCos(PBVH *pbvh, float (*vertCos)[3], const int totvert) /* unneeded deformation -- duplicate verts/faces to avoid this */ pbvh->verts = MEM_dupallocN(pbvh->verts); - /* No need to dupalloc pbvh->looptri, this one is 'totally owned' by pbvh, it's never some mesh data. */ + /* No need to dupalloc pbvh->looptri, this one is 'totally owned' by pbvh, + * it's never some mesh data. */ pbvh->deformed = true; } @@ -2252,8 +2364,9 @@ void BKE_pbvh_apply_vertCos(PBVH *pbvh, float (*vertCos)[3], const int totvert) BKE_mesh_calc_normals_looptri( pbvh->verts, pbvh->totvert, pbvh->mloop, pbvh->looptri, pbvh->totprim, NULL); - for (int a = 0; a < pbvh->totnode; ++a) + for (int a = 0; a < pbvh->totnode; ++a) { BKE_pbvh_node_mark_update(&pbvh->nodes[a]); + } BKE_pbvh_update(pbvh, PBVH_UpdateBB, NULL); BKE_pbvh_update(pbvh, PBVH_UpdateOriginalBB, NULL); @@ -2274,10 +2387,12 @@ PBVHProxyNode *BKE_pbvh_node_add_proxy(PBVH *bvh, PBVHNode *node) node->proxy_count++; - if (node->proxies) + if (node->proxies) { node->proxies = MEM_reallocN(node->proxies, node->proxy_count * sizeof(PBVHProxyNode)); - else + } + else { node->proxies = MEM_mallocN(sizeof(PBVHProxyNode), "PBVHNodeProxy"); + } BKE_pbvh_node_num_verts(bvh, node, &totverts, NULL); node->proxies[index].co = MEM_callocN(sizeof(float[3]) * totverts, "PBVHNodeProxy.co"); @@ -2350,10 +2465,12 @@ void pbvh_vertex_iter_init(PBVH *bvh, PBVHNode *node, PBVHVertexIter *vi, int mo vi->totgrid = (grids) ? totgrid : 1; vi->gridsize = gridsize; - if (mode == PBVH_ITER_ALL) + if (mode == PBVH_ITER_ALL) { vi->totvert = totvert; - else + } + else { vi->totvert = uniq_verts; + } vi->vert_indices = vert_indices; vi->mverts = verts; @@ -2365,12 +2482,14 @@ void pbvh_vertex_iter_init(PBVH *bvh, PBVHNode *node, PBVHVertexIter *vi, int mo } vi->gh = NULL; - if (vi->grids && mode == PBVH_ITER_UNIQUE) + if (vi->grids && mode == PBVH_ITER_UNIQUE) { vi->grid_hidden = bvh->grid_hidden; + } vi->mask = NULL; - if (bvh->type == PBVH_FACES) + if (bvh->type == PBVH_FACES) { vi->vmask = CustomData_get_layer(bvh->vdata, CD_PAINT_MASK); + } } bool pbvh_has_mask(PBVH *bvh) diff --git a/source/blender/blenkernel/intern/pbvh_bmesh.c b/source/blender/blenkernel/intern/pbvh_bmesh.c index c007d5e3df7..25f9948a835 100644 --- a/source/blender/blenkernel/intern/pbvh_bmesh.c +++ b/source/blender/blenkernel/intern/pbvh_bmesh.c @@ -240,8 +240,9 @@ static void pbvh_bmesh_node_finalize(PBVH *bvh, BB_expand(&n->vb, v->co); } while ((l_iter = l_iter->next) != l_first); - if (!BM_elem_flag_test(f, BM_ELEM_HIDDEN)) + if (!BM_elem_flag_test(f, BM_ELEM_HIDDEN)) { has_visible = true; + } } BLI_assert(n->vb.bmin[0] <= n->vb.bmax[0] && n->vb.bmin[1] <= n->vb.bmax[1] && @@ -304,10 +305,12 @@ static void pbvh_bmesh_node_split(PBVH *bvh, const BBC *bbc_array, int node_inde BMFace *f = BLI_gsetIterator_getKey(&gs_iter); const BBC *bbc = &bbc_array[BM_elem_index_get(f)]; - if (bbc->bcentroid[axis] < mid) + if (bbc->bcentroid[axis] < mid) { BLI_gset_insert(c1->bm_faces, f); - else + } + else { BLI_gset_insert(c2->bm_faces, f); + } } /* Enforce at least one primitive in each node */ @@ -347,11 +350,13 @@ static void pbvh_bmesh_node_split(PBVH *bvh, const BBC *bbc_array, int node_inde } BLI_gset_free(n->bm_faces, NULL); - if (n->bm_other_verts) + if (n->bm_other_verts) { BLI_gset_free(n->bm_other_verts, NULL); + } - if (n->layer_disp) + if (n->layer_disp) { MEM_freeN(n->layer_disp); + } n->bm_faces = NULL; n->bm_unique_verts = NULL; @@ -393,8 +398,7 @@ static bool pbvh_bmesh_node_limit_ensure(PBVH *bvh, int node_index) GSetIterator gs_iter; int i; - GSET_ITER_INDEX(gs_iter, bm_faces, i) - { + GSET_ITER_INDEX (gs_iter, bm_faces, i) { BMFace *f = BLI_gsetIterator_getKey(&gs_iter); BBC *bbc = &bbc_array[i]; @@ -431,7 +435,6 @@ static int pbvh_bmesh_node_offset_from_elem(PBVH *bvh, BMElem *ele) BLI_assert(ele->head.htype == BM_FACE); return bvh->cd_face_node_offset; } - } static int pbvh_bmesh_node_index_from_elem(PBVH *bvh, void *key) @@ -543,7 +546,7 @@ static int pbvh_bmesh_node_vert_use_count(PBVH *bvh, PBVHNode *node, BMVert *v) BMFace *f; int count = 0; - BM_FACES_OF_VERT_ITER_BEGIN(f, v) { + BM_FACES_OF_VERT_ITER_BEGIN (f, v) { PBVHNode *f_node = pbvh_bmesh_node_from_face(bvh, f); if (f_node == node) { count++; @@ -709,10 +712,12 @@ static void pbvh_bmesh_edge_loops(BLI_Buffer *buf, BMEdge *e) static void pbvh_bmesh_node_drop_orig(PBVHNode *node) { - if (node->bm_orco) + if (node->bm_orco) { MEM_freeN(node->bm_orco); - if (node->bm_ortri) + } + if (node->bm_ortri) { MEM_freeN(node->bm_ortri); + } node->bm_orco = NULL; node->bm_ortri = NULL; node->bm_tot_ortri = 0; @@ -1157,8 +1162,9 @@ static void pbvh_bmesh_split_edge(EdgeQueueContext *eq_ctx, v1 = l_adj->v; v2 = l_adj->next->v; - if (ni != node_index && i == 0) + if (ni != node_index && i == 0) { pbvh_bmesh_vert_ownership_transfer(bvh, &bvh->nodes[ni], v_new); + } /** * The 2 new faces created and assigned to ``f_new`` have their @@ -1250,8 +1256,9 @@ static bool pbvh_bmesh_subdivide_long_edges(EdgeQueueContext *eq_ctx, /* At the moment edges never get shorter (subdiv will make new edges) * unlike collapse where edges can become longer. */ #if 0 - if (len_squared_v3v3(v1->co, v2->co) <= eq_ctx->q->limit_len_squared) + if (len_squared_v3v3(v1->co, v2->co) <= eq_ctx->q->limit_len_squared) { continue; + } #else BLI_assert(len_squared_v3v3(v1->co, v2->co) > eq_ctx->q->limit_len_squared); #endif @@ -1397,8 +1404,9 @@ static void pbvh_bmesh_collapse_edge(PBVH *bvh, /* Check if any of the face's edges are now unused by any * face, if so delete them */ for (int j = 0; j < 3; j++) { - if (BM_edge_is_wire(e_tri[j])) + if (BM_edge_is_wire(e_tri[j])) { BM_edge_kill(bvh->bm, e_tri[j]); + } } /* Check if any of the face's vertices are now unused, if so @@ -1473,8 +1481,9 @@ static bool pbvh_bmesh_collapse_short_edges(EdgeQueueContext *eq_ctx, EDGE_QUEUE_DISABLE(e); #endif - if (len_squared_v3v3(v1->co, v2->co) >= min_len_squared) + if (len_squared_v3v3(v1->co, v2->co) >= min_len_squared) { continue; + } /* Check that the edge's vertices are still in the PBVH. It's * possible that an edge collapse has deleted adjacent faces @@ -1542,8 +1551,9 @@ bool BKE_pbvh_bmesh_node_raycast_detail(PBVHNode *node, float *depth, float *r_edge_length) { - if (node->flag & PBVH_FullyHidden) + if (node->flag & PBVH_FullyHidden) { return 0; + } GSetIterator gs_iter; bool hit = false; @@ -1820,8 +1830,9 @@ static void pbvh_bmesh_create_nodes_fast_recursive( /* Update node bounding box */ } while ((l_iter = l_iter->next) != l_first); - if (!BM_elem_flag_test(f, BM_ELEM_HIDDEN)) + if (!BM_elem_flag_test(f, BM_ELEM_HIDDEN)) { has_visible = true; + } BB_expand_with_bb(&n->vb, (BB *)bbc); } @@ -1861,8 +1872,9 @@ void BKE_pbvh_build_bmesh(PBVH *bvh, /* TODO: choose leaf limit better */ bvh->leaf_limit = 100; - if (smooth_shading) + if (smooth_shading) { bvh->flags |= PBVH_DYNTOPO_SMOOTH_SHADING; + } /* bounding box array of all faces, no need to recalculate every time */ BBC *bbc_array = MEM_mallocN(sizeof(BBC) * bm->totface, "BBC"); @@ -1904,7 +1916,8 @@ void BKE_pbvh_build_bmesh(PBVH *bvh, /* start recursion, assign faces to nodes accordingly */ pbvh_bmesh_node_limit_ensure_fast(bvh, nodeinfo, bbc_array, &rootnode, arena); - /* we now have all faces assigned to a node, next we need to assign those to the gsets of the nodes */ + /* We now have all faces assigned to a node, + * next we need to assign those to the gsets of the nodes. */ /* Start with all faces in the root node */ bvh->nodes = MEM_callocN(sizeof(PBVHNode), "PBVHNode"); @@ -2003,8 +2016,9 @@ bool BKE_pbvh_bmesh_update_topology(PBVH *bvh, void BKE_pbvh_bmesh_node_save_orig(PBVHNode *node) { /* Skip if original coords/triangles are already saved */ - if (node->bm_orco) + if (node->bm_orco) { return; + } const int totvert = BLI_gset_len(node->bm_unique_verts) + BLI_gset_len(node->bm_other_verts); @@ -2034,8 +2048,9 @@ void BKE_pbvh_bmesh_node_save_orig(PBVHNode *node) GSET_ITER (gs_iter, node->bm_faces) { BMFace *f = BLI_gsetIterator_getKey(&gs_iter); - if (BM_elem_flag_test(f, BM_ELEM_HIDDEN)) + if (BM_elem_flag_test(f, BM_ELEM_HIDDEN)) { continue; + } #if 0 BMIter bm_iter; @@ -2105,38 +2120,32 @@ static void pbvh_bmesh_print(PBVH *bvh) BMIter iter; BMFace *f; - BM_ITER_MESH(f, &iter, bvh->bm, BM_FACES_OF_MESH) { - fprintf(stderr, " %d -> %d\n", - BM_elem_index_get(f), - pbvh_bmesh_node_index_from_face(bvh, f)); + BM_ITER_MESH (f, &iter, bvh->bm, BM_FACES_OF_MESH) { + fprintf(stderr, " %d -> %d\n", BM_elem_index_get(f), pbvh_bmesh_node_index_from_face(bvh, f)); } fprintf(stderr, "bm_vert_to_node:\n"); BMVert *v; - BM_ITER_MESH(v, &iter, bvh->bm, BM_FACES_OF_MESH) { - fprintf(stderr, " %d -> %d\n", - BM_elem_index_get(v), - pbvh_bmesh_node_index_from_vert(bvh, v)); + BM_ITER_MESH (v, &iter, bvh->bm, BM_FACES_OF_MESH) { + fprintf(stderr, " %d -> %d\n", BM_elem_index_get(v), pbvh_bmesh_node_index_from_vert(bvh, v)); } for (int n = 0; n < bvh->totnode; n++) { PBVHNode *node = &bvh->nodes[n]; - if (!(node->flag & PBVH_Leaf)) + if (!(node->flag & PBVH_Leaf)) { continue; + } GSetIterator gs_iter; fprintf(stderr, "node %d\n faces:\n", n); GSET_ITER (gs_iter, node->bm_faces) - fprintf(stderr, " %d\n", - BM_elem_index_get((BMFace *)BLI_gsetIterator_getKey(&gs_iter))); + fprintf(stderr, " %d\n", BM_elem_index_get((BMFace *)BLI_gsetIterator_getKey(&gs_iter))); fprintf(stderr, " unique verts:\n"); GSET_ITER (gs_iter, node->bm_unique_verts) - fprintf(stderr, " %d\n", - BM_elem_index_get((BMVert *)BLI_gsetIterator_getKey(&gs_iter))); + fprintf(stderr, " %d\n", BM_elem_index_get((BMVert *)BLI_gsetIterator_getKey(&gs_iter))); fprintf(stderr, " other verts:\n"); GSET_ITER (gs_iter, node->bm_other_verts) - fprintf(stderr, " %d\n", - BM_elem_index_get((BMVert *)BLI_gsetIterator_getKey(&gs_iter))); + fprintf(stderr, " %d\n", BM_elem_index_get((BMVert *)BLI_gsetIterator_getKey(&gs_iter))); } } @@ -2275,8 +2284,9 @@ static void pbvh_bmesh_verify(PBVH *bvh) bool has_unique = false; for (int i = 0; i < bvh->totnode; i++) { PBVHNode *n = &bvh->nodes[i]; - if ((n->bm_unique_verts != NULL) && BLI_gset_haskey(n->bm_unique_verts, vi)) + if ((n->bm_unique_verts != NULL) && BLI_gset_haskey(n->bm_unique_verts, vi)) { has_unique = true; + } } BLI_assert(has_unique); vert_count++; diff --git a/source/blender/blenkernel/intern/pbvh_intern.h b/source/blender/blenkernel/intern/pbvh_intern.h index 5fc41c560b2..74d7312e6a7 100644 --- a/source/blender/blenkernel/intern/pbvh_intern.h +++ b/source/blender/blenkernel/intern/pbvh_intern.h @@ -132,6 +132,7 @@ struct PBVH { const MLoop *mloop; const MLoopTri *looptri; CustomData *vdata; + CustomData *ldata; /* Grid Data */ CCGKey gridkey; diff --git a/source/blender/blenkernel/intern/pointcache.c b/source/blender/blenkernel/intern/pointcache.c index 2d3914090b1..a55d0be4f95 100644 --- a/source/blender/blenkernel/intern/pointcache.c +++ b/source/blender/blenkernel/intern/pointcache.c @@ -153,22 +153,26 @@ static int ptcache_basic_header_read(PTCacheFile *pf) int error = 0; /* Custom functions should read these basic elements too! */ - if (!error && !fread(&pf->totpoint, sizeof(unsigned int), 1, pf->fp)) + if (!error && !fread(&pf->totpoint, sizeof(unsigned int), 1, pf->fp)) { error = 1; + } - if (!error && !fread(&pf->data_types, sizeof(unsigned int), 1, pf->fp)) + if (!error && !fread(&pf->data_types, sizeof(unsigned int), 1, pf->fp)) { error = 1; + } return !error; } static int ptcache_basic_header_write(PTCacheFile *pf) { /* Custom functions should write these basic elements too! */ - if (!fwrite(&pf->totpoint, sizeof(unsigned int), 1, pf->fp)) + if (!fwrite(&pf->totpoint, sizeof(unsigned int), 1, pf->fp)) { return 0; + } - if (!fwrite(&pf->data_types, sizeof(unsigned int), 1, pf->fp)) + if (!fwrite(&pf->data_types, sizeof(unsigned int), 1, pf->fp)) { return 0; + } return 1; } @@ -206,8 +210,9 @@ static void ptcache_softbody_interpolate( ParticleKey keys[4]; float dfra; - if (cfra1 == cfra2) + if (cfra1 == cfra2) { return; + } copy_v3_v3(keys[1].co, bp->pos); copy_v3_v3(keys[1].vel, bp->vec); @@ -216,8 +221,9 @@ static void ptcache_softbody_interpolate( memcpy(keys[2].co, old_data, 3 * sizeof(float)); memcpy(keys[2].vel, old_data + 3, 3 * sizeof(float)); } - else + else { BKE_ptcache_make_particle_key(keys + 2, 0, data, cfra2); + } dfra = cfra2 - cfra1; @@ -267,8 +273,9 @@ static int ptcache_particle_write(int index, void *psys_v, void **data, int cfra int step = psys->pointcache->step; /* No need to store unborn or died particles outside cache step bounds */ - if (data[BPHYS_DATA_INDEX] && (cfra < pa->time - step || cfra > pa->dietime + step)) + if (data[BPHYS_DATA_INDEX] && (cfra < pa->time - step || cfra > pa->dietime + step)) { return 0; + } times[0] = pa->time; times[1] = pa->dietime; @@ -286,7 +293,8 @@ static int ptcache_particle_write(int index, void *psys_v, void **data, int cfra PTCACHE_DATA_FROM(data, BPHYS_DATA_BOIDS, &boid->data); } - /* return flag 1+1=2 for newly born particles to copy exact birth location to previously cached frame */ + /* Return flag 1+1=2 for newly born particles + * to copy exact birth location to previously cached frame. */ return 1 + (pa->state.time >= pa->time && pa->prev_state.time <= pa->time); } static void ptcache_particle_read( @@ -297,14 +305,16 @@ static void ptcache_particle_read( BoidParticle *boid; float timestep = 0.04f * psys->part->timetweak; - if (index >= psys->totpart) + if (index >= psys->totpart) { return; + } pa = psys->particles + index; boid = (psys->part->phystype == PART_PHYS_BOIDS) ? pa->boid : NULL; - if (cfra > pa->state.time) + if (cfra > pa->state.time) { memcpy(&pa->prev_state, &pa->state, sizeof(ParticleKey)); + } if (old_data) { /* old format cache */ @@ -315,10 +325,12 @@ static void ptcache_particle_read( BKE_ptcache_make_particle_key(&pa->state, 0, data, cfra); /* set frames cached before birth to birth time */ - if (cfra < pa->time) + if (cfra < pa->time) { pa->state.time = pa->time; - else if (cfra > pa->dietime) + } + else if (cfra > pa->dietime) { pa->state.time = pa->dietime; + } if (data[BPHYS_DATA_SIZE]) { PTCACHE_DATA_TO(data, BPHYS_DATA_SIZE, 0, &pa->size); @@ -361,28 +373,33 @@ static void ptcache_particle_interpolate( ParticleKey keys[4]; float dfra, timestep = 0.04f * psys->part->timetweak; - if (index >= psys->totpart) + if (index >= psys->totpart) { return; + } pa = psys->particles + index; /* particle wasn't read from first cache so can't interpolate */ if ((int)cfra1 < pa->time - psys->pointcache->step || - (int)cfra1 > pa->dietime + psys->pointcache->step) + (int)cfra1 > pa->dietime + psys->pointcache->step) { return; + } cfra = MIN2(cfra, pa->dietime); cfra1 = MIN2(cfra1, pa->dietime); cfra2 = MIN2(cfra2, pa->dietime); - if (cfra1 == cfra2) + if (cfra1 == cfra2) { return; + } memcpy(keys + 1, &pa->state, sizeof(ParticleKey)); - if (old_data) + if (old_data) { memcpy(keys + 2, old_data, sizeof(ParticleKey)); - else + } + else { BKE_ptcache_make_particle_key(keys + 2, 0, data, cfra2); + } /* determine velocity from previous location */ if (data[BPHYS_DATA_LOCATION] && !data[BPHYS_DATA_VELOCITY]) { @@ -401,8 +418,9 @@ static void ptcache_particle_interpolate( unit_qt(keys[2].rot); } - if (cfra > pa->time) + if (cfra > pa->time) { cfra1 = MAX2(cfra1, pa->time); + } dfra = cfra2 - cfra1; @@ -435,11 +453,13 @@ static int ptcache_particle_totwrite(void *psys_v, int cfra) int p, step = psys->pointcache->step; int totwrite = 0; - if (cfra == 0) + if (cfra == 0) { return psys->totpart; + } - for (p = 0; p < psys->totpart; p++, pa++) + for (p = 0; p < psys->totpart; p++, pa++) { totwrite += (cfra >= pa->time - step && cfra <= pa->dietime + step); + } return totwrite; } @@ -473,8 +493,9 @@ static void ptcache_particle_extra_read(void *psys_v, PTCacheMem *pm, float UNUS for (; extra; extra = extra->next) { switch (extra->type) { case BPHYS_EXTRA_FLUID_SPRINGS: { - if (psys->fluid_springs) + if (psys->fluid_springs) { MEM_freeN(psys->fluid_springs); + } psys->fluid_springs = MEM_dupallocN(extra->data); psys->tot_fluidsprings = psys->alloc_fluidsprings = extra->totdata; @@ -524,8 +545,9 @@ static void ptcache_cloth_interpolate( ParticleKey keys[4]; float dfra; - if (cfra1 == cfra2) + if (cfra1 == cfra2) { return; + } copy_v3_v3(keys[1].co, vert->x); copy_v3_v3(keys[1].vel, vert->v); @@ -534,8 +556,9 @@ static void ptcache_cloth_interpolate( memcpy(keys[2].co, old_data, 3 * sizeof(float)); memcpy(keys[2].vel, old_data + 6, 3 * sizeof(float)); } - else + else { BKE_ptcache_make_particle_key(keys + 2, 0, data, cfra2); + } dfra = cfra2 - cfra1; @@ -574,8 +597,9 @@ static int ptcache_smoke_totpoint(void *smoke_v, int UNUSED(cfra)) if (sds->fluid) { return sds->base_res[0] * sds->base_res[1] * sds->base_res[2]; } - else + else { return 0; + } } static void ptcache_smoke_error(void *smoke_v, const char *message) @@ -607,10 +631,11 @@ static int ptcache_smoke_write(PTCacheFile *pf, void *smoke_v) unsigned int in_len = sizeof(float) * (unsigned int)res; unsigned char *out = (unsigned char *)MEM_callocN(LZO_OUT_LEN(in_len) * 4, "pointcache_lzo_buffer"); - //int mode = res >= 1000000 ? 2 : 1; + // int mode = res >= 1000000 ? 2 : 1; int mode = 1; // light - if (sds->cache_comp == SM_CACHE_HEAVY) + if (sds->cache_comp == SM_CACHE_HEAVY) { mode = 2; // heavy + } smoke_export(sds->fluid, &dt, @@ -679,10 +704,11 @@ static int ptcache_smoke_write(PTCacheFile *pf, void *smoke_v) smoke_turbulence_get_res(sds->wt, res_big_array); res_big = res_big_array[0] * res_big_array[1] * res_big_array[2]; - //mode = res_big >= 1000000 ? 2 : 1; + // mode = res_big >= 1000000 ? 2 : 1; mode = 1; // light - if (sds->cache_high_comp == SM_CACHE_HEAVY) + if (sds->cache_high_comp == SM_CACHE_HEAVY) { mode = 2; // heavy + } in_len_big = sizeof(float) * (unsigned int)res_big; @@ -831,14 +857,17 @@ static int ptcache_smoke_read(PTCacheFile *pf, void *smoke_v) /* check if resolution has changed */ if (sds->res[0] != ch_res[0] || sds->res[1] != ch_res[1] || sds->res[2] != ch_res[2]) { - if (sds->flags & MOD_SMOKE_ADAPTIVE_DOMAIN) + if (sds->flags & MOD_SMOKE_ADAPTIVE_DOMAIN) { reallocate = 1; - else + } + else { return 0; + } } /* check if active fields have changed */ - if (fluid_fields != cache_fields || active_fields != sds->active_fields) + if (fluid_fields != cache_fields || active_fields != sds->active_fields) { reallocate = 1; + } /* reallocate fluid if needed*/ if (reallocate) { @@ -1323,10 +1352,12 @@ static int ptcache_dynamicpaint_totpoint(void *sd, int UNUSED(cfra)) { DynamicPaintSurface *surface = (DynamicPaintSurface *)sd; - if (!surface->data) + if (!surface->data) { return 0; - else + } + else { return surface->data->total_points; + } } static void ptcache_dynamicpaint_error(void *UNUSED(sd), const char *UNUSED(message)) @@ -1393,8 +1424,9 @@ static int ptcache_dynamicpaint_read(PTCacheFile *pf, void *dp_v) /* cache type */ ptcache_file_read(pf, &surface_type, 1, sizeof(int)); - if (surface_type != surface->type) + if (surface_type != surface->type) { return 0; + } /* read surface data */ if (surface->type == MOD_DPAINT_SURFACE_T_PAINT) { @@ -1423,8 +1455,9 @@ static int ptcache_rigidbody_write(int index, void *rb_v, void **data, int UNUSE RigidBodyWorld *rbw = rb_v; Object *ob = NULL; - if (rbw->objects) + if (rbw->objects) { ob = rbw->objects[index]; + } if (ob && ob->rigidbody_object) { RigidBodyOb *rbo = ob->rigidbody_object; @@ -1447,8 +1480,9 @@ static void ptcache_rigidbody_read( RigidBodyWorld *rbw = rb_v; Object *ob = NULL; - if (rbw->objects) + if (rbw->objects) { ob = rbw->objects[index]; + } if (ob && ob->rigidbody_object) { RigidBodyOb *rbo = ob->rigidbody_object; @@ -1472,8 +1506,9 @@ static void ptcache_rigidbody_interpolate( RigidBodyWorld *rbw = rb_v; Object *ob = NULL; - if (rbw->objects) + if (rbw->objects) { ob = rbw->objects[index]; + } if (ob && ob->rigidbody_object) { RigidBodyOb *rbo = ob->rigidbody_object; @@ -1571,8 +1606,9 @@ void BKE_ptcache_id_from_particles(PTCacheID *pid, Object *ob, ParticleSystem *p pid->cache_ptr = &psys->pointcache; pid->ptcaches = &psys->ptcaches; - if (psys->part->type != PART_HAIR) + if (psys->part->type != PART_HAIR) { pid->flag |= PTCACHE_VEL_PER_SEC; + } pid->totpoint = ptcache_particle_totpoint; pid->totwrite = ptcache_particle_totwrite; @@ -1598,9 +1634,10 @@ void BKE_ptcache_id_from_particles(PTCacheID *pid, Object *ob, ParticleSystem *p pid->data_types = (1 << BPHYS_DATA_LOCATION) | (1 << BPHYS_DATA_VELOCITY) | (1 << BPHYS_DATA_INDEX); - if (psys->part->phystype == PART_PHYS_BOIDS) + if (psys->part->phystype == PART_PHYS_BOIDS) { pid->data_types |= (1 << BPHYS_DATA_AVELOCITY) | (1 << BPHYS_DATA_ROTATION) | (1 << BPHYS_DATA_BOIDS); + } else if (psys->part->phystype == PART_PHYS_FLUID && psys->part->fluid && psys->part->fluid->flag & SPH_VISCOELASTIC_SPRINGS) { pid->write_extra_data = ptcache_particle_extra_write; @@ -1700,10 +1737,12 @@ void BKE_ptcache_id_from_smoke(PTCacheID *pid, struct Object *ob, struct SmokeMo pid->data_types = 0; pid->info_types = 0; - if (sds->fluid) + if (sds->fluid) { pid->data_types |= (1 << BPHYS_DATA_SMOKE_LOW); - if (sds->wt) + } + if (sds->wt) { pid->data_types |= (1 << BPHYS_DATA_SMOKE_HIGH); + } pid->default_step = 1; pid->max_step = 1; @@ -1838,9 +1877,7 @@ static bool foreach_object_particle_ptcache(Object *object, } /* Hair needs to be included in id-list for cache edit mode to work. */ #if 0 - if ((psys->part->type == PART_HAIR) && - (psys->flag & PSYS_HAIR_DYNAMICS) == 0) - { + if ((psys->part->type == PART_HAIR) && (psys->flag & PSYS_HAIR_DYNAMICS) == 0) { continue; } #endif @@ -2032,8 +2069,9 @@ static int ptcache_path(PTCacheID *pid, char *filename) i = strlen(file); /* remove .blend */ - if (i > 6) + if (i > 6) { file[i - 6] = '\0'; + } BLI_snprintf(filename, MAX_PTCACHE_PATH, @@ -2058,8 +2096,9 @@ static int ptcache_filename(PTCacheID *pid, char *filename, int cfra, short do_p filename[0] = '\0'; newname = filename; - if (!G.relbase_valid && (pid->cache->flag & PTCACHE_EXTERNAL) == 0) + if (!G.relbase_valid && (pid->cache->flag & PTCACHE_EXTERNAL) == 0) { return 0; /* save blend file before using disk pointcache */ + } /* start with temp dir */ if (do_path) { @@ -2083,21 +2122,24 @@ static int ptcache_filename(PTCacheID *pid, char *filename, int cfra, short do_p } if (do_ext) { - if (pid->cache->index < 0) + if (pid->cache->index < 0) { pid->cache->index = pid->stack_index = BKE_object_insert_ptcache(pid->ob); + } const char *ext = ptcache_file_extension(pid); if (pid->cache->flag & PTCACHE_EXTERNAL) { - if (pid->cache->index >= 0) + if (pid->cache->index >= 0) { BLI_snprintf(newname, MAX_PTCACHE_FILE, "_%06d_%02u%s", cfra, pid->stack_index, ext); /* always 6 chars */ - else + } + else { BLI_snprintf(newname, MAX_PTCACHE_FILE, "_%06d%s", cfra, ext); /* always 6 chars */ + } } else { BLI_snprintf(newname, @@ -2122,11 +2164,13 @@ static PTCacheFile *ptcache_file_open(PTCacheID *pid, int mode, int cfra) #ifndef DURIAN_POINTCACHE_LIB_OK /* don't allow writing for linked objects */ - if (pid->ob->id.lib && mode == PTCACHE_FILE_WRITE) + if (pid->ob->id.lib && mode == PTCACHE_FILE_WRITE) { return NULL; + } #endif - if (!G.relbase_valid && (pid->cache->flag & PTCACHE_EXTERNAL) == 0) + if (!G.relbase_valid && (pid->cache->flag & PTCACHE_EXTERNAL) == 0) { return NULL; /* save blend file before using disk pointcache */ + } ptcache_filename(pid, filename, cfra, 1, 1); @@ -2143,8 +2187,9 @@ static PTCacheFile *ptcache_file_open(PTCacheID *pid, int mode, int cfra) fp = BLI_fopen(filename, "rb+"); } - if (!fp) + if (!fp) { return NULL; + } pf = MEM_mallocN(sizeof(PTCacheFile), "PTCacheFile"); pf->fp = fp; @@ -2185,8 +2230,9 @@ static int ptcache_file_compressed_read(PTCacheFile *pf, unsigned char *result, "pointcache_compressed_buffer"); ptcache_file_read(pf, in, in_len, sizeof(unsigned char)); #ifdef WITH_LZO - if (compressed == 1) + if (compressed == 1) { r = lzo1x_decompress_safe(in, (lzo_uint)in_len, result, (lzo_uint *)&out_len, NULL); + } #endif #ifdef WITH_LZMA if (compressed == 2) { @@ -2226,10 +2272,12 @@ static int ptcache_file_compressed_write( LZO_HEAP_ALLOC(wrkmem, LZO1X_MEM_COMPRESS); r = lzo1x_1_compress(in, (lzo_uint)in_len, out, (lzo_uint *)&out_len, wrkmem); - if (!(r == LZO_E_OK) || (out_len >= in_len)) + if (!(r == LZO_E_OK) || (out_len >= in_len)) { compressed = 0; - else + } + else { compressed = 1; + } } #endif #ifdef WITH_LZMA @@ -2238,7 +2286,7 @@ static int ptcache_file_compressed_write( r = LzmaCompress(out, &out_len, in, - in_len, //assume sizeof(char)==1.... + in_len, // assume sizeof(char)==1.... props, &sizeOfIt, 5, @@ -2249,10 +2297,12 @@ static int ptcache_file_compressed_write( 32, 2); - if (!(r == SZ_OK) || (out_len >= in_len)) + if (!(r == SZ_OK) || (out_len >= in_len)) { compressed = 0; - else + } + else { compressed = 2; + } } #endif @@ -2262,8 +2312,9 @@ static int ptcache_file_compressed_write( ptcache_file_write(pf, &size, 1, sizeof(unsigned int)); ptcache_file_write(pf, out, out_len, sizeof(unsigned char)); } - else + else { ptcache_file_write(pf, in, in_len, sizeof(unsigned char)); + } if (compressed == 2) { unsigned int size = sizeOfIt; @@ -2288,8 +2339,10 @@ static int ptcache_file_data_read(PTCacheFile *pf) int i; for (i = 0; i < BPHYS_TOT_DATA; i++) { - if ((pf->data_types & (1 << i)) && !ptcache_file_read(pf, pf->cur[i], 1, ptcache_data_size[i])) + if ((pf->data_types & (1 << i)) && + !ptcache_file_read(pf, pf->cur[i], 1, ptcache_data_size[i])) { return 0; + } } return 1; @@ -2300,8 +2353,9 @@ static int ptcache_file_data_write(PTCacheFile *pf) for (i = 0; i < BPHYS_TOT_DATA; i++) { if ((pf->data_types & (1 << i)) && - !ptcache_file_write(pf, pf->cur[i], 1, ptcache_data_size[i])) + !ptcache_file_write(pf, pf->cur[i], 1, ptcache_data_size[i])) { return 0; + } } return 1; @@ -2314,21 +2368,25 @@ static int ptcache_file_header_begin_read(PTCacheFile *pf) pf->data_types = 0; - if (fread(bphysics, sizeof(char), 8, pf->fp) != 8) + if (fread(bphysics, sizeof(char), 8, pf->fp) != 8) { error = 1; + } - if (!error && !STREQLEN(bphysics, "BPHYSICS", 8)) + if (!error && !STREQLEN(bphysics, "BPHYSICS", 8)) { error = 1; + } - if (!error && !fread(&typeflag, sizeof(unsigned int), 1, pf->fp)) + if (!error && !fread(&typeflag, sizeof(unsigned int), 1, pf->fp)) { error = 1; + } pf->type = (typeflag & PTCACHE_TYPEFLAG_TYPEMASK); pf->flag = (typeflag & PTCACHE_TYPEFLAG_FLAGMASK); /* if there was an error set file as it was */ - if (error) + if (error) { fseek(pf->fp, 0, SEEK_SET); + } return !error; } @@ -2337,11 +2395,13 @@ static int ptcache_file_header_begin_write(PTCacheFile *pf) const char *bphysics = "BPHYSICS"; unsigned int typeflag = pf->type + pf->flag; - if (fwrite(bphysics, sizeof(char), 8, pf->fp) != 8) + if (fwrite(bphysics, sizeof(char), 8, pf->fp) != 8) { return 0; + } - if (!fwrite(&typeflag, sizeof(unsigned int), 1, pf->fp)) + if (!fwrite(&typeflag, sizeof(unsigned int), 1, pf->fp)) { return 0; + } return 1; } @@ -2374,22 +2434,27 @@ int BKE_ptcache_mem_index_find(PTCacheMem *pm, unsigned int index) unsigned int *data = pm->data[BPHYS_DATA_INDEX]; unsigned int mid, low = 0, high = pm->totpoint - 1; - if (index < *data || index > *(data + high)) + if (index < *data || index > *(data + high)) { return -1; + } /* check simple case for continuous indexes first */ - if (index - *data < high && data[index - *data] == index) + if (index - *data < high && data[index - *data] == index) { return index - *data; + } while (low <= high) { mid = (low + high) / 2; - if (data[mid] > index) + if (data[mid] > index) { high = mid - 1; - else if (data[mid] < index) + } + else if (data[mid] < index) { low = mid + 1; - else + } + else { return mid; + } } return -1; @@ -2404,8 +2469,9 @@ void BKE_ptcache_mem_pointers_init(PTCacheMem *pm) int data_types = pm->data_types; int i; - for (i = 0; i < BPHYS_TOT_DATA; i++) + for (i = 0; i < BPHYS_TOT_DATA; i++) { pm->cur[i] = ((data_types & (1 << i)) ? pm->data[i] : NULL); + } } void BKE_ptcache_mem_pointers_incr(PTCacheMem *pm) @@ -2413,8 +2479,9 @@ void BKE_ptcache_mem_pointers_incr(PTCacheMem *pm) int i; for (i = 0; i < BPHYS_TOT_DATA; i++) { - if (pm->cur[i]) + if (pm->cur[i]) { pm->cur[i] = (char *)pm->cur[i] + ptcache_data_size[i]; + } } } int BKE_ptcache_mem_pointers_seek(int point_index, PTCacheMem *pm) @@ -2431,8 +2498,9 @@ int BKE_ptcache_mem_pointers_seek(int point_index, PTCacheMem *pm) return 0; } - for (i = 0; i < BPHYS_TOT_DATA; i++) + for (i = 0; i < BPHYS_TOT_DATA; i++) { pm->cur[i] = data_types & (1 << i) ? (char *)pm->data[i] + index * ptcache_data_size[i] : NULL; + } return 1; } @@ -2443,8 +2511,9 @@ static void ptcache_data_alloc(PTCacheMem *pm) int i; for (i = 0; i < BPHYS_TOT_DATA; i++) { - if (data_types & (1 << i)) + if (data_types & (1 << i)) { pm->data[i] = MEM_callocN(totpoint * ptcache_data_size[i], "PTCache Data"); + } } } static void ptcache_data_free(PTCacheMem *pm) @@ -2453,8 +2522,9 @@ static void ptcache_data_free(PTCacheMem *pm) int i; for (i = 0; i < BPHYS_TOT_DATA; i++) { - if (data[i]) + if (data[i]) { MEM_freeN(data[i]); + } } } static void ptcache_data_copy(void *from[], void *to[]) @@ -2463,8 +2533,9 @@ static void ptcache_data_copy(void *from[], void *to[]) for (i = 0; i < BPHYS_TOT_DATA; i++) { /* note, durian file 03.4b_comp crashes if to[i] is not tested * its NULL, not sure if this should be fixed elsewhere but for now its needed */ - if (from[i] && to[i]) + if (from[i] && to[i]) { memcpy(to[i], from[i], ptcache_data_size[i]); + } } } @@ -2474,8 +2545,9 @@ static void ptcache_extra_free(PTCacheMem *pm) if (extra) { for (; extra; extra = extra->next) { - if (extra->data) + if (extra->data) { MEM_freeN(extra->data); + } } BLI_freelistN(&pm->extradata); @@ -2483,12 +2555,15 @@ static void ptcache_extra_free(PTCacheMem *pm) } static int ptcache_old_elemsize(PTCacheID *pid) { - if (pid->type == PTCACHE_TYPE_SOFTBODY) + if (pid->type == PTCACHE_TYPE_SOFTBODY) { return 6 * sizeof(float); - else if (pid->type == PTCACHE_TYPE_PARTICLES) + } + else if (pid->type == PTCACHE_TYPE_PARTICLES) { return sizeof(ParticleKey); - else if (pid->type == PTCACHE_TYPE_CLOTH) + } + else if (pid->type == PTCACHE_TYPE_CLOTH) { return 9 * sizeof(float); + } return 0; } @@ -2498,17 +2573,21 @@ static void ptcache_find_frames_around(PTCacheID *pid, unsigned int frame, int * if (pid->cache->flag & PTCACHE_DISK_CACHE) { int cfra1 = frame, cfra2 = frame + 1; - while (cfra1 >= pid->cache->startframe && !BKE_ptcache_id_exist(pid, cfra1)) + while (cfra1 >= pid->cache->startframe && !BKE_ptcache_id_exist(pid, cfra1)) { cfra1--; + } - if (cfra1 < pid->cache->startframe) + if (cfra1 < pid->cache->startframe) { cfra1 = 0; + } - while (cfra2 <= pid->cache->endframe && !BKE_ptcache_id_exist(pid, cfra2)) + while (cfra2 <= pid->cache->endframe && !BKE_ptcache_id_exist(pid, cfra2)) { cfra2++; + } - if (cfra2 > pid->cache->endframe) + if (cfra2 > pid->cache->endframe) { cfra2 = 0; + } if (cfra1 && !cfra2) { *fra1 = 0; @@ -2523,8 +2602,9 @@ static void ptcache_find_frames_around(PTCacheID *pid, unsigned int frame, int * PTCacheMem *pm = pid->cache->mem_cache.first; PTCacheMem *pm2 = pid->cache->mem_cache.last; - while (pm->next && pm->next->frame <= frame) + while (pm->next && pm->next->frame <= frame) { pm = pm->next; + } if (pm2->frame < frame) { pm2 = NULL; @@ -2552,14 +2632,17 @@ static PTCacheMem *ptcache_disk_frame_to_mem(PTCacheID *pid, int cfra) PTCacheMem *pm = NULL; unsigned int i, error = 0; - if (pf == NULL) + if (pf == NULL) { return NULL; + } - if (!ptcache_file_header_begin_read(pf)) + if (!ptcache_file_header_begin_read(pf)) { error = 1; + } - if (!error && (pf->type != pid->type || !pid->read_header(pf))) + if (!error && (pf->type != pid->type || !pid->read_header(pf))) { error = 1; + } if (!error) { pm = MEM_callocN(sizeof(PTCacheMem), "Pointcache mem"); @@ -2573,8 +2656,9 @@ static PTCacheMem *ptcache_disk_frame_to_mem(PTCacheID *pid, int cfra) if (pf->flag & PTCACHE_TYPEFLAG_COMPRESS) { for (i = 0; i < BPHYS_TOT_DATA; i++) { unsigned int out_len = pm->totpoint * ptcache_data_size[i]; - if (pf->data_types & (1 << i)) + if (pf->data_types & (1 << i)) { ptcache_file_compressed_read(pf, (unsigned char *)(pm->data[i]), out_len); + } } } else { @@ -2605,12 +2689,14 @@ static PTCacheMem *ptcache_disk_frame_to_mem(PTCacheID *pid, int cfra) extra->data = MEM_callocN(extra->totdata * ptcache_extra_datasize[extra->type], "Pointcache extradata->data"); - if (pf->flag & PTCACHE_TYPEFLAG_COMPRESS) + if (pf->flag & PTCACHE_TYPEFLAG_COMPRESS) { ptcache_file_compressed_read(pf, (unsigned char *)(extra->data), extra->totdata * ptcache_extra_datasize[extra->type]); - else + } + else { ptcache_file_read(pf, extra->data, extra->totdata, ptcache_extra_datasize[extra->type]); + } BLI_addtail(&pm->extradata, extra); } @@ -2625,8 +2711,9 @@ static PTCacheMem *ptcache_disk_frame_to_mem(PTCacheID *pid, int cfra) ptcache_file_close(pf); - if (error && G.debug & G_DEBUG) + if (error && G.debug & G_DEBUG) { printf("Error reading from disk cache\n"); + } return pm; } @@ -2640,8 +2727,9 @@ static int ptcache_mem_frame_to_disk(PTCacheID *pid, PTCacheMem *pm) pf = ptcache_file_open(pid, PTCACHE_FILE_WRITE, pm->frame); if (pf == NULL) { - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("Error opening disk cache file for writing\n"); + } return 0; } @@ -2650,14 +2738,17 @@ static int ptcache_mem_frame_to_disk(PTCacheID *pid, PTCacheMem *pm) pf->type = pid->type; pf->flag = 0; - if (pm->extradata.first) + if (pm->extradata.first) { pf->flag |= PTCACHE_TYPEFLAG_EXTRADATA; + } - if (pid->cache->compression) + if (pid->cache->compression) { pf->flag |= PTCACHE_TYPEFLAG_COMPRESS; + } - if (!ptcache_file_header_begin_write(pf) || !pid->write_header(pf)) + if (!ptcache_file_header_begin_write(pf) || !pid->write_header(pf)) { error = 1; + } if (!error) { if (pid->cache->compression) { @@ -2691,8 +2782,9 @@ static int ptcache_mem_frame_to_disk(PTCacheID *pid, PTCacheMem *pm) PTCacheExtra *extra = pm->extradata.first; for (; extra; extra = extra->next) { - if (extra->data == NULL || extra->totdata == 0) + if (extra->data == NULL || extra->totdata == 0) { continue; + } ptcache_file_write(pf, &extra->type, 1, sizeof(unsigned int)); ptcache_file_write(pf, &extra->totdata, 1, sizeof(unsigned int)); @@ -2713,8 +2805,9 @@ static int ptcache_mem_frame_to_disk(PTCacheID *pid, PTCacheMem *pm) ptcache_file_close(pf); - if (error && G.debug & G_DEBUG) + if (error && G.debug & G_DEBUG) { printf("Error writing to disk cache\n"); + } return error == 0; } @@ -2724,12 +2817,14 @@ static int ptcache_read_stream(PTCacheID *pid, int cfra) PTCacheFile *pf = ptcache_file_open(pid, PTCACHE_FILE_READ, cfra); int error = 0; - if (pid->read_stream == NULL) + if (pid->read_stream == NULL) { return 0; + } if (pf == NULL) { - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("Error opening disk cache file for reading\n"); + } return 0; } @@ -2771,8 +2866,9 @@ static int ptcache_read_openvdb_stream(PTCacheID *pid, int cfra) char filename[FILE_MAX * 2]; /* save blend file before using disk pointcache */ - if (!G.relbase_valid && (pid->cache->flag & PTCACHE_EXTERNAL) == 0) + if (!G.relbase_valid && (pid->cache->flag & PTCACHE_EXTERNAL) == 0) { return 0; + } ptcache_filename(pid, filename, cfra, 1, 1); @@ -2807,8 +2903,9 @@ static int ptcache_read(PTCacheID *pid, int cfra) else { pm = pid->cache->mem_cache.first; - while (pm && pm->frame != cfra) + while (pm && pm->frame != cfra) { pm = pm->next; + } } /* read the cache */ @@ -2827,16 +2924,18 @@ static int ptcache_read(PTCacheID *pid, int cfra) BKE_ptcache_mem_pointers_init(pm); for (i = 0; i < totpoint; i++) { - if (pm->data_types & (1 << BPHYS_DATA_INDEX)) + if (pm->data_types & (1 << BPHYS_DATA_INDEX)) { index = pm->cur[BPHYS_DATA_INDEX]; + } pid->read_point(*index, pid->calldata, pm->cur, (float)pm->frame, NULL); BKE_ptcache_mem_pointers_incr(pm); } - if (pid->read_extra_data && pm->extradata.first) + if (pid->read_extra_data && pm->extradata.first) { pid->read_extra_data(pid->calldata, pm, (float)pm->frame); + } /* clean up temporary memory cache */ if (pid->cache->flag & PTCACHE_DISK_CACHE) { @@ -2861,8 +2960,9 @@ static int ptcache_interpolate(PTCacheID *pid, float cfra, int cfra1, int cfra2) else { pm = pid->cache->mem_cache.first; - while (pm && pm->frame != cfra2) + while (pm && pm->frame != cfra2) { pm = pm->next; + } } /* read the cache */ @@ -2881,16 +2981,18 @@ static int ptcache_interpolate(PTCacheID *pid, float cfra, int cfra1, int cfra2) BKE_ptcache_mem_pointers_init(pm); for (i = 0; i < totpoint; i++) { - if (pm->data_types & (1 << BPHYS_DATA_INDEX)) + if (pm->data_types & (1 << BPHYS_DATA_INDEX)) { index = pm->cur[BPHYS_DATA_INDEX]; + } pid->interpolate_point( *index, pid->calldata, pm->cur, cfra, (float)cfra1, (float)cfra2, NULL); BKE_ptcache_mem_pointers_incr(pm); } - if (pid->interpolate_extra_data && pm->extradata.first) + if (pid->interpolate_extra_data && pm->extradata.first) { pid->interpolate_extra_data(pid->calldata, pm, cfra, (float)cfra1, (float)cfra2); + } /* clean up temporary memory cache */ if (pid->cache->flag & PTCACHE_DISK_CACHE) { @@ -2910,8 +3012,9 @@ int BKE_ptcache_read(PTCacheID *pid, float cfra, bool no_extrapolate_old) int ret = 0; /* nothing to read to */ - if (pid->totpoint(pid->calldata, cfrai) == 0) + if (pid->totpoint(pid->calldata, cfrai) == 0) { return 0; + } if (pid->cache->flag & PTCACHE_READ_INFO) { pid->cache->flag &= ~PTCACHE_READ_INFO; @@ -2919,27 +3022,33 @@ int BKE_ptcache_read(PTCacheID *pid, float cfra, bool no_extrapolate_old) } /* first check if we have the actual frame cached */ - if (cfra == (float)cfrai && BKE_ptcache_id_exist(pid, cfrai)) + if (cfra == (float)cfrai && BKE_ptcache_id_exist(pid, cfrai)) { cfra1 = cfrai; + } /* no exact cache frame found so try to find cached frames around cfra */ - if (cfra1 == 0) + if (cfra1 == 0) { ptcache_find_frames_around(pid, cfrai, &cfra1, &cfra2); + } - if (cfra1 == 0 && cfra2 == 0) + if (cfra1 == 0 && cfra2 == 0) { return 0; + } /* don't read old cache if already simulated past cached frame */ if (no_extrapolate_old) { - if (cfra1 == 0 && cfra2 && cfra2 <= pid->cache->simframe) + if (cfra1 == 0 && cfra2 && cfra2 <= pid->cache->simframe) { return 0; - if (cfra1 && cfra1 == cfra2) + } + if (cfra1 && cfra1 == cfra2) { return 0; + } } else { /* avoid calling interpolate between the same frame values */ - if (cfra1 && cfra1 == cfra2) + if (cfra1 && cfra1 == cfra2) { cfra1 = 0; + } } if (cfra1) { @@ -2949,11 +3058,13 @@ int BKE_ptcache_read(PTCacheID *pid, float cfra, bool no_extrapolate_old) } } else if (pid->read_stream) { - if (!ptcache_read_stream(pid, cfra1)) + if (!ptcache_read_stream(pid, cfra1)) { return 0; + } } - else if (pid->read_point) + else if (pid->read_point) { ptcache_read(pid, cfra1); + } } if (cfra2) { @@ -2963,19 +3074,23 @@ int BKE_ptcache_read(PTCacheID *pid, float cfra, bool no_extrapolate_old) } } else if (pid->read_stream) { - if (!ptcache_read_stream(pid, cfra2)) + if (!ptcache_read_stream(pid, cfra2)) { return 0; + } } else if (pid->read_point) { - if (cfra1 && cfra2 && pid->interpolate_point) + if (cfra1 && cfra2 && pid->interpolate_point) { ptcache_interpolate(pid, cfra, cfra1, cfra2); - else + } + else { ptcache_read(pid, cfra2); + } } } - if (cfra1) + if (cfra1) { ret = (cfra2 ? PTCACHE_READ_INTERPOLATED : PTCACHE_READ_EXACT); + } else if (cfra2) { ret = PTCACHE_READ_OLD; pid->cache->simframe = cfra2; @@ -2987,8 +3102,9 @@ int BKE_ptcache_read(PTCacheID *pid, float cfra, bool no_extrapolate_old) BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_AFTER, cfrai); } else if (pid->cache->flag & PTCACHE_FRAMES_SKIPPED) { - if (cfra <= pid->cache->last_exact) + if (cfra <= pid->cache->last_exact) { pid->cache->flag &= ~PTCACHE_FRAMES_SKIPPED; + } BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_AFTER, MAX2(cfrai, pid->cache->last_exact)); } @@ -3005,8 +3121,9 @@ static int ptcache_write_stream(PTCacheID *pid, int cfra, int totpoint) pf = ptcache_file_open(pid, PTCACHE_FILE_WRITE, cfra); if (pf == NULL) { - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("Error opening disk cache file for writing\n"); + } return 0; } @@ -3015,16 +3132,19 @@ static int ptcache_write_stream(PTCacheID *pid, int cfra, int totpoint) pf->type = pid->type; pf->flag = 0; - if (!error && (!ptcache_file_header_begin_write(pf) || !pid->write_header(pf))) + if (!error && (!ptcache_file_header_begin_write(pf) || !pid->write_header(pf))) { error = 1; + } - if (!error && pid->write_stream) + if (!error && pid->write_stream) { pid->write_stream(pf, pid->calldata); + } ptcache_file_close(pf); - if (error && G.debug & G_DEBUG) + if (error && G.debug & G_DEBUG) { printf("Error writing to disk cache\n"); + } return error == 0; } @@ -3069,13 +3189,15 @@ static int ptcache_write(PTCacheID *pid, int cfra, int overwrite) if (cache->flag & PTCACHE_DISK_CACHE) { int fra = cfra - 1; - while (fra >= cache->startframe && !BKE_ptcache_id_exist(pid, fra)) + while (fra >= cache->startframe && !BKE_ptcache_id_exist(pid, fra)) { fra--; + } pm2 = ptcache_disk_frame_to_mem(pid, fra); } - else + else { pm2 = cache->mem_cache.last; + } } if (pid->write_point) { @@ -3085,14 +3207,16 @@ static int ptcache_write(PTCacheID *pid, int cfra, int overwrite) BKE_ptcache_mem_pointers_incr(pm); /* newly born particles have to be copied to previous cached frame */ - if (overwrite && write == 2 && pm2 && BKE_ptcache_mem_pointers_seek(i, pm2)) + if (overwrite && write == 2 && pm2 && BKE_ptcache_mem_pointers_seek(i, pm2)) { pid->write_point(i, pid->calldata, pm2->cur, cfra); + } } } } - if (pid->write_extra_data) + if (pid->write_extra_data) { pid->write_extra_data(pid->calldata, pm, cfra); + } pm->frame = cfra; @@ -3132,26 +3256,31 @@ static int ptcache_write_needed(PTCacheID *pid, int cfra, int *overwrite) } if (pid->cache->flag & PTCACHE_DISK_CACHE) { - if (cfra == 0 && cache->startframe > 0) + if (cfra == 0 && cache->startframe > 0) { return 1; + } /* find last cached frame */ - while (efra > cache->startframe && !BKE_ptcache_id_exist(pid, efra)) + while (efra > cache->startframe && !BKE_ptcache_id_exist(pid, efra)) { efra--; + } /* find second last cached frame */ ofra = efra - 1; - while (ofra > cache->startframe && !BKE_ptcache_id_exist(pid, ofra)) + while (ofra > cache->startframe && !BKE_ptcache_id_exist(pid, ofra)) { ofra--; + } } else { PTCacheMem *pm = cache->mem_cache.last; /* don't write info file in memory */ - if (cfra == 0) + if (cfra == 0) { return 0; + } - if (pm == NULL) + if (pm == NULL) { return 1; + } efra = pm->frame; ofra = (pm->prev ? pm->prev->frame : efra - cache->step); @@ -3175,11 +3304,13 @@ int BKE_ptcache_write(PTCacheID *pid, unsigned int cfra) int totpoint = pid->totpoint(pid->calldata, cfra); int overwrite = 0, error = 0; - if (totpoint == 0 || (cfra ? pid->data_types == 0 : pid->info_types == 0)) + if (totpoint == 0 || (cfra ? pid->data_types == 0 : pid->info_types == 0)) { return 0; + } - if (ptcache_write_needed(pid, cfra, &overwrite) == 0) + if (ptcache_write_needed(pid, cfra, &overwrite) == 0) { return 0; + } if (pid->file_type == PTCACHE_FILE_OPENVDB && pid->write_openvdb_stream) { ptcache_write_openvdb_stream(pid, cfra); @@ -3197,12 +3328,14 @@ int BKE_ptcache_write(PTCacheID *pid, unsigned int cfra) cache->flag &= ~PTCACHE_FRAMES_SKIPPED; } /* Don't mark skipped when writing info file (frame 0) */ - else if (cfra) + else if (cfra) { cache->flag |= PTCACHE_FRAMES_SKIPPED; + } /* Update timeline cache display */ - if (cfra && cache->cached_frames) + if (cfra && cache->cached_frames) { cache->cached_frames[cfra - cache->startframe] = 1; + } BKE_ptcache_update_info(pid); @@ -3226,19 +3359,22 @@ void BKE_ptcache_id_clear(PTCacheID *pid, int mode, unsigned int cfra) char path_full[MAX_PTCACHE_FILE]; char ext[MAX_PTCACHE_PATH]; - if (!pid || !pid->cache || pid->cache->flag & PTCACHE_BAKED) + if (!pid || !pid->cache || pid->cache->flag & PTCACHE_BAKED) { return; + } - if (pid->cache->flag & PTCACHE_IGNORE_CLEAR) + if (pid->cache->flag & PTCACHE_IGNORE_CLEAR) { return; + } sta = pid->cache->startframe; end = pid->cache->endframe; #ifndef DURIAN_POINTCACHE_LIB_OK /* don't allow clearing for linked objects */ - if (pid->ob->id.lib) + if (pid->ob->id.lib) { return; + } #endif /*if (!G.relbase_valid) return; */ /* save blend file before using pointcache */ @@ -3254,8 +3390,9 @@ void BKE_ptcache_id_clear(PTCacheID *pid, int mode, unsigned int cfra) ptcache_path(pid, path); dir = opendir(path); - if (dir == NULL) + if (dir == NULL) { return; + } len = ptcache_filename(pid, filename, cfra, 0, 0); /* no path */ /* append underscore terminator to ensure we don't match similar names @@ -3285,8 +3422,9 @@ void BKE_ptcache_id_clear(PTCacheID *pid, int mode, unsigned int cfra) (mode == PTCACHE_CLEAR_AFTER && frame > cfra)) { BLI_join_dirfile(path_full, sizeof(path_full), path, de->d_name); BLI_delete(path_full, false, false); - if (pid->cache->cached_frames && frame >= sta && frame <= end) + if (pid->cache->cached_frames && frame >= sta && frame <= end) { pid->cache->cached_frames[frame - sta] = 0; + } } } } @@ -3295,8 +3433,9 @@ void BKE_ptcache_id_clear(PTCacheID *pid, int mode, unsigned int cfra) } closedir(dir); - if (mode == PTCACHE_CLEAR_ALL && pid->cache->cached_frames) + if (mode == PTCACHE_CLEAR_ALL && pid->cache->cached_frames) { memset(pid->cache->cached_frames, 0, MEM_allocN_len(pid->cache->cached_frames)); + } } else { PTCacheMem *pm = pid->cache->mem_cache.first; @@ -3311,23 +3450,26 @@ void BKE_ptcache_id_clear(PTCacheID *pid, int mode, unsigned int cfra) } BLI_freelistN(&pid->cache->mem_cache); - if (pid->cache->cached_frames) + if (pid->cache->cached_frames) { memset(pid->cache->cached_frames, 0, MEM_allocN_len(pid->cache->cached_frames)); + } } else { while (pm) { if ((mode == PTCACHE_CLEAR_BEFORE && pm->frame < cfra) || (mode == PTCACHE_CLEAR_AFTER && pm->frame > cfra)) { link = pm; - if (pid->cache->cached_frames && pm->frame >= sta && pm->frame <= end) + if (pid->cache->cached_frames && pm->frame >= sta && pm->frame <= end) { pid->cache->cached_frames[pm->frame - sta] = 0; + } ptcache_data_free(pm); ptcache_extra_free(pm); pm = pm->next; BLI_freelinkN(&pid->cache->mem_cache, link); } - else + else { pm = pm->next; + } } } } @@ -3352,8 +3494,9 @@ void BKE_ptcache_id_clear(PTCacheID *pid, int mode, unsigned int cfra) } } } - if (pid->cache->cached_frames && cfra >= sta && cfra <= end) + if (pid->cache->cached_frames && cfra >= sta && cfra <= end) { pid->cache->cached_frames[cfra - sta] = 0; + } break; } @@ -3361,14 +3504,17 @@ void BKE_ptcache_id_clear(PTCacheID *pid, int mode, unsigned int cfra) } int BKE_ptcache_id_exist(PTCacheID *pid, int cfra) { - if (!pid->cache) + if (!pid->cache) { return 0; + } - if (cfra < pid->cache->startframe || cfra > pid->cache->endframe) + if (cfra < pid->cache->startframe || cfra > pid->cache->endframe) { return 0; + } - if (pid->cache->cached_frames && pid->cache->cached_frames[cfra - pid->cache->startframe] == 0) + if (pid->cache->cached_frames && pid->cache->cached_frames[cfra - pid->cache->startframe] == 0) { return 0; + } if (pid->cache->flag & PTCACHE_DISK_CACHE) { char filename[MAX_PTCACHE_FILE]; @@ -3381,8 +3527,9 @@ int BKE_ptcache_id_exist(PTCacheID *pid, int cfra) PTCacheMem *pm = pid->cache->mem_cache.first; for (; pm; pm = pm->next) { - if (pm->frame == cfra) + if (pm->frame == cfra) { return 1; + } } return 0; } @@ -3453,8 +3600,9 @@ void BKE_ptcache_id_time( len = ptcache_filename(pid, filename, (int)cfra, 0, 0); /* no path */ dir = opendir(path); - if (dir == NULL) + if (dir == NULL) { return; + } const char *fext = ptcache_file_extension(pid); @@ -3478,8 +3626,9 @@ void BKE_ptcache_id_time( PTCacheMem *pm = pid->cache->mem_cache.first; while (pm) { - if (pm->frame >= sta && pm->frame <= end) + if (pm->frame >= sta && pm->frame <= end) { cache->cached_frames[pm->frame - sta] = 1; + } pm = pm->next; } } @@ -3490,8 +3639,9 @@ int BKE_ptcache_id_reset(Scene *scene, PTCacheID *pid, int mode) PointCache *cache; int reset, clear, after; - if (!pid->cache) + if (!pid->cache) { return 0; + } cache = pid->cache; reset = 0; @@ -3522,19 +3672,25 @@ int BKE_ptcache_id_reset(Scene *scene, PTCacheID *pid, int mode) BKE_ptcache_invalidate(cache); cache->flag &= ~PTCACHE_REDO_NEEDED; - if (pid->type == PTCACHE_TYPE_CLOTH) + if (pid->type == PTCACHE_TYPE_CLOTH) { cloth_free_modifier(pid->calldata); - else if (pid->type == PTCACHE_TYPE_SOFTBODY) + } + else if (pid->type == PTCACHE_TYPE_SOFTBODY) { sbFreeSimulation(pid->calldata); - else if (pid->type == PTCACHE_TYPE_PARTICLES) + } + else if (pid->type == PTCACHE_TYPE_PARTICLES) { psys_reset(pid->calldata, PSYS_RESET_DEPSGRAPH); - else if (pid->type == PTCACHE_TYPE_DYNAMICPAINT) + } + else if (pid->type == PTCACHE_TYPE_DYNAMICPAINT) { dynamicPaint_clearSurface(scene, (DynamicPaintSurface *)pid->calldata); + } } - if (clear) + if (clear) { BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_ALL, 0); - else if (after) + } + else if (after) { BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_AFTER, CFRA); + } return (reset || clear || after); } @@ -3555,17 +3711,20 @@ int BKE_ptcache_object_reset(Scene *scene, Object *ob, int mode) for (psys = ob->particlesystem.first; psys; psys = psys->next) { /* children or just redo can be calculated without resetting anything */ - if (psys->recalc & ID_RECALC_PSYS_REDO || psys->recalc & ID_RECALC_PSYS_CHILD) + if (psys->recalc & ID_RECALC_PSYS_REDO || psys->recalc & ID_RECALC_PSYS_CHILD) { skip = 1; - /* Baked cloth hair has to be checked too, because we don't want to reset */ - /* particles or cloth in that case -jahka */ + /* Baked cloth hair has to be checked too, because we don't want to reset */ + /* particles or cloth in that case -jahka */ + } else if (psys->clmd) { BKE_ptcache_id_from_cloth(&pid, ob, psys->clmd); if (mode == PSYS_RESET_ALL || - !(psys->part->type == PART_HAIR && (pid.cache->flag & PTCACHE_BAKED))) + !(psys->part->type == PART_HAIR && (pid.cache->flag & PTCACHE_BAKED))) { reset |= BKE_ptcache_id_reset(scene, &pid, mode); - else + } + else { skip = 1; + } } if (skip == 0 && psys->part) { @@ -3600,15 +3759,17 @@ int BKE_ptcache_object_reset(Scene *scene, Object *ob, int mode) } if (scene->rigidbody_world && (ob->rigidbody_object || ob->rigidbody_constraint)) { - if (ob->rigidbody_object) + if (ob->rigidbody_object) { ob->rigidbody_object->flag |= RBO_FLAG_NEEDS_RESHAPE; + } BKE_ptcache_id_from_rigidbody(&pid, ob, scene->rigidbody_world); /* only flag as outdated, resetting should happen on start frame */ pid.cache->flag |= PTCACHE_OUTDATED; } - if (ob->type == OB_ARMATURE) + if (ob->type == OB_ARMATURE) { BIK_clear_cache(ob->pose); + } return reset; } @@ -3629,8 +3790,9 @@ void BKE_ptcache_remove(void) struct dirent *de; dir = opendir(path); - if (dir == NULL) + if (dir == NULL) { return; + } while ((de = readdir(dir)) != NULL) { if (FILENAME_IS_CURRPAR(de->d_name)) { @@ -3689,10 +3851,12 @@ void BKE_ptcache_free_mem(ListBase *mem_cache) void BKE_ptcache_free(PointCache *cache) { BKE_ptcache_free_mem(&cache->mem_cache); - if (cache->edit && cache->free_edit) + if (cache->edit && cache->free_edit) { cache->free_edit(cache->edit); - if (cache->cached_frames) + } + if (cache->cached_frames) { MEM_freeN(cache->cached_frames); + } MEM_freeN(cache); } void BKE_ptcache_free_list(ListBase *ptcaches) @@ -3728,8 +3892,9 @@ static PointCache *ptcache_copy(PointCache *cache, const bool copy_data) int i; for (i = 0; i < BPHYS_TOT_DATA; i++) { - if (pmn->data[i]) + if (pmn->data[i]) { pmn->data[i] = MEM_dupallocN(pm->data[i]); + } } BKE_ptcache_mem_pointers_init(pm); @@ -3737,8 +3902,9 @@ static PointCache *ptcache_copy(PointCache *cache, const bool copy_data) BLI_addtail(&ncache->mem_cache, pmn); } - if (ncache->cached_frames) + if (ncache->cached_frames) { ncache->cached_frames = MEM_dupallocN(cache->cached_frames); + } } /* hmm, should these be copied over instead? */ @@ -3786,14 +3952,17 @@ void BKE_ptcache_quick_cache_all(Main *bmain, Scene *scene, ViewLayer *view_laye static void ptcache_dt_to_str(char *str, double dtime) { if (dtime > 60.0) { - if (dtime > 3600.0) + if (dtime > 3600.0) { sprintf( str, "%ih %im %is", (int)(dtime / 3600), ((int)(dtime / 60)) % 60, ((int)dtime) % 60); - else + } + else { sprintf(str, "%im %is", ((int)(dtime / 60)) % 60, ((int)dtime) % 60); + } } - else + else { sprintf(str, "%is", ((int)dtime) % 60); + } } /* if bake is not given run simulations to current frame */ @@ -3825,9 +3994,10 @@ void BKE_ptcache_bake(PTCacheBaker *baker) ParticleSystem *psys = pid->calldata; /* a bit confusing, could make this work better in the UI */ - if (psys->part->type == PART_EMITTER) + if (psys->part->type == PART_EMITTER) { psys_get_pointcache_start_end( scene, pid->calldata, &cache->startframe, &cache->endframe); + } } else if (pid->type == PTCACHE_TYPE_SMOKE_HIGHRES) { /* get all pids from the object and search for smoke low res */ @@ -3837,8 +4007,9 @@ void BKE_ptcache_bake(PTCacheBaker *baker) for (pid2 = pidlist2.first; pid2; pid2 = pid2->next) { if (pid2->type == PTCACHE_TYPE_SMOKE_DOMAIN) { if (pid2->cache && !(pid2->cache->flag & PTCACHE_BAKED)) { - if (bake || pid2->cache->flag & PTCACHE_REDO_NEEDED) + if (bake || pid2->cache->flag & PTCACHE_REDO_NEEDED) { BKE_ptcache_id_clear(pid2, PTCACHE_CLEAR_ALL, 0); + } if (bake) { pid2->cache->flag |= PTCACHE_BAKING; pid2->cache->flag &= ~PTCACHE_BAKED; @@ -3849,8 +4020,9 @@ void BKE_ptcache_bake(PTCacheBaker *baker) BLI_freelistN(&pidlist2); } - if (bake || cache->flag & PTCACHE_REDO_NEEDED) + if (bake || cache->flag & PTCACHE_REDO_NEEDED) { BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_ALL, 0); + } startframe = MAX2(cache->last_exact, cache->startframe); @@ -3876,8 +4048,9 @@ void BKE_ptcache_bake(PTCacheBaker *baker) if (pid->type == PTCACHE_TYPE_PARTICLES) { ParticleSystem *psys = (ParticleSystem *)pid->calldata; /* skip hair & keyed particles */ - if (psys->part->type == PART_HAIR || psys->part->phystype == PART_PHYS_KEYED) + if (psys->part->type == PART_HAIR || psys->part->phystype == PART_PHYS_KEYED) { continue; + } psys_get_pointcache_start_end( scene, pid->calldata, &cache->startframe, &cache->endframe); @@ -3900,8 +4073,9 @@ void BKE_ptcache_bake(PTCacheBaker *baker) if (bake || render) { cache->flag |= PTCACHE_BAKING; - if (bake) + if (bake) { endframe = MAX2(endframe, cache->endframe); + } } cache->flag &= ~PTCACHE_BAKED; @@ -3981,8 +4155,9 @@ void BKE_ptcache_bake(PTCacheBaker *baker) if (bake) { cache->flag |= PTCACHE_BAKED; /* write info file */ - if (cache->flag & PTCACHE_DISK_CACHE) + if (cache->flag & PTCACHE_DISK_CACHE) { BKE_ptcache_write(pid, 0); + } } } else { @@ -3992,22 +4167,26 @@ void BKE_ptcache_bake(PTCacheBaker *baker) for (pid = pidlist.first; pid; pid = pid->next) { /* skip hair particles */ if (pid->type == PTCACHE_TYPE_PARTICLES && - ((ParticleSystem *)pid->calldata)->part->type == PART_HAIR) + ((ParticleSystem *)pid->calldata)->part->type == PART_HAIR) { continue; + } cache = pid->cache; - if (baker->quick_step > 1) + if (baker->quick_step > 1) { cache->flag &= ~(PTCACHE_BAKING | PTCACHE_OUTDATED); - else + } + else { cache->flag &= ~(PTCACHE_BAKING | PTCACHE_REDO_NEEDED); + } cache->flag |= PTCACHE_SIMULATION_VALID; if (bake) { cache->flag |= PTCACHE_BAKED; - if (cache->flag & PTCACHE_DISK_CACHE) + if (cache->flag & PTCACHE_DISK_CACHE) { BKE_ptcache_write(pid, 0); + } } } BLI_freelistN(&pidlist); @@ -4043,8 +4222,9 @@ void BKE_ptcache_disk_to_mem(PTCacheID *pid) for (cfra = sfra; cfra <= efra; cfra++) { pm = ptcache_disk_frame_to_mem(pid, cfra); - if (pm) + if (pm) { BLI_addtail(&pid->cache->mem_cache, pm); + } } } void BKE_ptcache_mem_to_disk(PTCacheID *pid) @@ -4070,8 +4250,9 @@ void BKE_ptcache_mem_to_disk(PTCacheID *pid) } /* write info file */ - if (cache->flag & PTCACHE_BAKED) + if (cache->flag & PTCACHE_BAKED) { BKE_ptcache_write(pid, 0); + } } void BKE_ptcache_toggle_disk_cache(PTCacheID *pid) { @@ -4080,8 +4261,9 @@ void BKE_ptcache_toggle_disk_cache(PTCacheID *pid) if (!G.relbase_valid) { cache->flag &= ~PTCACHE_DISK_CACHE; - if (G.debug & G_DEBUG) + if (G.debug & G_DEBUG) { printf("File must be saved before using disk cache!\n"); + } return; } @@ -4091,10 +4273,12 @@ void BKE_ptcache_toggle_disk_cache(PTCacheID *pid) cache->cached_frames_len = 0; } - if (cache->flag & PTCACHE_DISK_CACHE) + if (cache->flag & PTCACHE_DISK_CACHE) { BKE_ptcache_mem_to_disk(pid); - else + } + else { BKE_ptcache_disk_to_mem(pid); + } cache->flag ^= PTCACHE_DISK_CACHE; BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_ALL, 0); @@ -4184,23 +4368,27 @@ void BKE_ptcache_load_external(PTCacheID *pid) char filename[MAX_PTCACHE_FILE]; char ext[MAX_PTCACHE_PATH]; - if (!cache) + if (!cache) { return; + } ptcache_path(pid, path); len = ptcache_filename(pid, filename, 1, 0, 0); /* no path */ dir = opendir(path); - if (dir == NULL) + if (dir == NULL) { return; + } const char *fext = ptcache_file_extension(pid); - if (cache->index >= 0) + if (cache->index >= 0) { BLI_snprintf(ext, sizeof(ext), "_%02d%s", cache->index, fext); - else + } + else { BLI_strncpy(ext, fext, sizeof(ext)); + } while ((de = readdir(dir)) != NULL) { if (strstr(de->d_name, ext)) { /* do we have the right extension?*/ @@ -4213,8 +4401,9 @@ void BKE_ptcache_load_external(PTCacheID *pid) start = MIN2(start, frame); end = MAX2(end, frame); } - else + else { info = 1; + } } } } @@ -4255,8 +4444,9 @@ void BKE_ptcache_load_external(PTCacheID *pid) pf = ptcache_file_open(pid, PTCACHE_FILE_READ, cache->startframe); if (pf) { - while (ptcache_file_read(pf, old_data, 1, elemsize)) + while (ptcache_file_read(pf, old_data, 1, elemsize)) { cache->totpoint++; + } ptcache_file_close(pf); } @@ -4285,17 +4475,21 @@ void BKE_ptcache_update_info(PTCacheID *pid) int cfra = cache->startframe; for (; cfra <= cache->endframe; cfra++) { - if (BKE_ptcache_id_exist(pid, cfra)) + if (BKE_ptcache_id_exist(pid, cfra)) { totframes++; + } } /* smoke doesn't use frame 0 as info frame so can't check based on totpoint */ - if (pid->type == PTCACHE_TYPE_SMOKE_DOMAIN && totframes) + if (pid->type == PTCACHE_TYPE_SMOKE_DOMAIN && totframes) { BLI_snprintf(cache->info, sizeof(cache->info), IFACE_("%i frames found!"), totframes); - else if (totframes && cache->totpoint) + } + else if (totframes && cache->totpoint) { BLI_snprintf(cache->info, sizeof(cache->info), IFACE_("%i points found!"), cache->totpoint); - else + } + else { BLI_strncpy(cache->info, IFACE_("No valid data to read!"), sizeof(cache->info)); + } return; } @@ -4303,18 +4497,21 @@ void BKE_ptcache_update_info(PTCacheID *pid) if (pid->type == PTCACHE_TYPE_SMOKE_DOMAIN) { int totpoint = pid->totpoint(pid->calldata, 0); - if (cache->totpoint > totpoint) + if (cache->totpoint > totpoint) { BLI_snprintf( mem_info, sizeof(mem_info), IFACE_("%i cells + High Resolution cached"), totpoint); - else + } + else { BLI_snprintf(mem_info, sizeof(mem_info), IFACE_("%i cells cached"), totpoint); + } } else { int cfra = cache->startframe; for (; cfra <= cache->endframe; cfra++) { - if (BKE_ptcache_id_exist(pid, cfra)) + if (BKE_ptcache_id_exist(pid, cfra)) { totframes++; + } } BLI_snprintf(mem_info, sizeof(mem_info), IFACE_("%i frames on disk"), totframes); @@ -4328,8 +4525,9 @@ void BKE_ptcache_update_info(PTCacheID *pid) int i; for (; pm; pm = pm->next) { - for (i = 0; i < BPHYS_TOT_DATA; i++) + for (i = 0; i < BPHYS_TOT_DATA; i++) { bytes += MEM_allocN_len(pm->data[i]); + } for (extra = pm->extradata.first; extra; extra = extra->next) { bytes += MEM_allocN_len(extra->data); diff --git a/source/blender/blenkernel/intern/report.c b/source/blender/blenkernel/intern/report.c index 1319c6de835..5db091e6a43 100644 --- a/source/blender/blenkernel/intern/report.c +++ b/source/blender/blenkernel/intern/report.c @@ -65,8 +65,9 @@ const char *BKE_report_type_str(ReportType type) void BKE_reports_init(ReportList *reports, int flag) { - if (!reports) + if (!reports) { return; + } memset(reports, 0, sizeof(ReportList)); @@ -79,8 +80,9 @@ void BKE_reports_clear(ReportList *reports) { Report *report, *report_next; - if (!reports) + if (!reports) { return; + } report = reports->list.first; @@ -163,8 +165,9 @@ void BKE_reports_prepend(ReportList *reports, const char *_prepend) DynStr *ds; const char *prepend = TIP_(_prepend); - if (!reports) + if (!reports) { return; + } for (report = reports->list.first; report; report = report->next) { ds = BLI_dynstr_new(); @@ -187,8 +190,9 @@ void BKE_reports_prependf(ReportList *reports, const char *_prepend, ...) va_list args; const char *prepend = TIP_(_prepend); - if (!reports) + if (!reports) { return; + } for (report = reports->list.first; report; report = report->next) { ds = BLI_dynstr_new(); @@ -208,32 +212,36 @@ void BKE_reports_prependf(ReportList *reports, const char *_prepend, ...) ReportType BKE_report_print_level(ReportList *reports) { - if (!reports) + if (!reports) { return RPT_ERROR; + } return reports->printlevel; } void BKE_report_print_level_set(ReportList *reports, ReportType level) { - if (!reports) + if (!reports) { return; + } reports->printlevel = level; } ReportType BKE_report_store_level(ReportList *reports) { - if (!reports) + if (!reports) { return RPT_ERROR; + } return reports->storelevel; } void BKE_report_store_level_set(ReportList *reports, ReportType level) { - if (!reports) + if (!reports) { return; + } reports->storelevel = level; } @@ -244,18 +252,23 @@ char *BKE_reports_string(ReportList *reports, ReportType level) DynStr *ds; char *cstring; - if (!reports || !reports->list.first) + if (!reports || !reports->list.first) { return NULL; + } ds = BLI_dynstr_new(); - for (report = reports->list.first; report; report = report->next) - if (report->type >= level) + for (report = reports->list.first; report; report = report->next) { + if (report->type >= level) { BLI_dynstr_appendf(ds, "%s: %s\n", report->typestr, report->message); + } + } - if (BLI_dynstr_get_len(ds)) + if (BLI_dynstr_get_len(ds)) { cstring = BLI_dynstr_get_cstring(ds); - else + } + else { cstring = NULL; + } BLI_dynstr_free(ds); return cstring; @@ -265,8 +278,9 @@ void BKE_reports_print(ReportList *reports, ReportType level) { char *cstring = BKE_reports_string(reports, level); - if (cstring == NULL) + if (cstring == NULL) { return; + } puts(cstring); fflush(stdout); @@ -278,8 +292,9 @@ Report *BKE_reports_last_displayable(ReportList *reports) Report *report; for (report = reports->list.last; report; report = report->prev) { - if (ELEM(report->type, RPT_ERROR, RPT_WARNING, RPT_INFO)) + if (ELEM(report->type, RPT_ERROR, RPT_WARNING, RPT_INFO)) { return report; + } } return NULL; @@ -289,9 +304,11 @@ bool BKE_reports_contain(ReportList *reports, ReportType level) { Report *report; if (reports != NULL) { - for (report = reports->list.first; report; report = report->next) - if (report->type >= level) + for (report = reports->list.first; report; report = report->next) { + if (report->type >= level) { return true; + } + } } return false; } diff --git a/source/blender/blenkernel/intern/rigidbody.c b/source/blender/blenkernel/intern/rigidbody.c index 78639b4ddb9..ad15214c3b8 100644 --- a/source/blender/blenkernel/intern/rigidbody.c +++ b/source/blender/blenkernel/intern/rigidbody.c @@ -109,11 +109,13 @@ void BKE_rigidbody_free_world(Scene *scene) scene->rigidbody_world = NULL; /* sanity check */ - if (!rbw) + if (!rbw) { return; + } if (is_orig && rbw->shared->physics_world) { - /* free physics references, we assume that all physics objects in will have been added to the world */ + /* Free physics references, + * we assume that all physics objects in will have been added to the world. */ if (rbw->constraints) { FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN (rbw->constraints, object) { if (object->rigidbody_constraint) { @@ -135,8 +137,9 @@ void BKE_rigidbody_free_world(Scene *scene) /* free dynamics world */ RB_dworld_delete(rbw->shared->physics_world); } - if (rbw->objects) + if (rbw->objects) { free(rbw->objects); + } if (is_orig) { /* free cache */ @@ -147,8 +150,9 @@ void BKE_rigidbody_free_world(Scene *scene) } /* free effector weights */ - if (rbw->effector_weights) + if (rbw->effector_weights) { MEM_freeN(rbw->effector_weights); + } /* free rigidbody world itself */ MEM_freeN(rbw); @@ -161,8 +165,9 @@ void BKE_rigidbody_free_object(Object *ob, RigidBodyWorld *rbw) RigidBodyOb *rbo = ob->rigidbody_object; /* sanity check */ - if (rbo == NULL) + if (rbo == NULL) { return; + } /* free physics references */ if (is_orig) { @@ -198,8 +203,9 @@ void BKE_rigidbody_free_constraint(Object *ob) RigidBodyCon *rbc = (ob) ? ob->rigidbody_constraint : NULL; /* sanity check */ - if (rbc == NULL) + if (rbc == NULL) { return; + } /* free physics reference */ if (rbc->physics_constraint) { @@ -332,8 +338,9 @@ static rbCollisionShape *rigidbody_get_shape_trimesh_from_mesh(Object *ob) mesh = rigidbody_get_mesh(ob); /* ensure mesh validity, then grab data */ - if (mesh == NULL) + if (mesh == NULL) { return NULL; + } mvert = mesh->mvert; totvert = mesh->totvert; @@ -415,12 +422,14 @@ static void rigidbody_validate_sim_shape(Object *ob, bool rebuild) bool has_volume; /* sanity check */ - if (rbo == NULL) + if (rbo == NULL) { return; + } /* don't create a new shape if we already have one and don't want to rebuild it */ - if (rbo->shared->physics_shape && !rebuild) + if (rbo->shared->physics_shape && !rebuild) { return; + } /* if automatically determining dimensions, use the Object's boundbox * - assume that all quadrics are standing upright on local z-axis @@ -472,13 +481,15 @@ static void rigidbody_validate_sim_shape(Object *ob, bool rebuild) /* try to emged collision margin */ has_volume = (MIN3(size[0], size[1], size[2]) > 0.0f); - if (!(rbo->flag & RBO_FLAG_USE_MARGIN) && has_volume) + if (!(rbo->flag & RBO_FLAG_USE_MARGIN) && has_volume) { hull_margin = 0.04f; + } new_shape = rigidbody_get_shape_convexhull_from_mesh(ob, hull_margin, &can_embed); - if (!(rbo->flag & RBO_FLAG_USE_MARGIN)) + if (!(rbo->flag & RBO_FLAG_USE_MARGIN)) { rbo->margin = (can_embed && has_volume) ? 0.04f : 0.0f; /* RB_TODO ideally we shouldn't directly change the margin here */ + } break; case RB_SHAPE_TRIMESH: new_shape = rigidbody_get_shape_trimesh_from_mesh(ob); @@ -561,8 +572,9 @@ void BKE_rigidbody_calc_volume(Object *ob, float *r_vol) const MLoop *mloop = NULL; /* ensure mesh validity, then grab data */ - if (mesh == NULL) + if (mesh == NULL) { return; + } mvert = mesh->mvert; totvert = mesh->totvert; @@ -584,8 +596,9 @@ void BKE_rigidbody_calc_volume(Object *ob, float *r_vol) } /* return the volume calculated */ - if (r_vol) + if (r_vol) { *r_vol = volume; + } } void BKE_rigidbody_calc_center_of_mass(Object *ob, float r_center[3]) @@ -633,8 +646,9 @@ void BKE_rigidbody_calc_center_of_mass(Object *ob, float r_center[3]) const MLoop *mloop; /* ensure mesh validity, then grab data */ - if (mesh == NULL) + if (mesh == NULL) { return; + } mvert = mesh->mvert; totvert = mesh->totvert; @@ -667,13 +681,16 @@ static void rigidbody_validate_sim_object(RigidBodyWorld *rbw, Object *ob, bool /* sanity checks: * - object doesn't have RigidBody info already: then why is it here? */ - if (rbo == NULL) + if (rbo == NULL) { return; + } /* make sure collision shape exists */ - /* FIXME we shouldn't always have to rebuild collision shapes when rebuilding objects, but it's needed for constraints to update correctly */ - if (rbo->shared->physics_shape == NULL || rebuild) + /* FIXME we shouldn't always have to rebuild collision shapes when rebuilding objects, + * but it's needed for constraints to update correctly. */ + if (rbo->shared->physics_shape == NULL || rebuild) { rigidbody_validate_sim_shape(ob, true); + } if (rbo->shared->physics_object) { RB_dworld_remove_body(rbw->shared->physics_world, rbo->shared->physics_object); @@ -697,8 +714,9 @@ static void rigidbody_validate_sim_object(RigidBodyWorld *rbw, Object *ob, bool RB_body_set_activation_state(rbo->shared->physics_object, rbo->flag & RBO_FLAG_USE_DEACTIVATION); - if (rbo->type == RBO_TYPE_PASSIVE || rbo->flag & RBO_FLAG_START_DEACTIVATED) + if (rbo->type == RBO_TYPE_PASSIVE || rbo->flag & RBO_FLAG_START_DEACTIVATED) { RB_body_deactivate(rbo->shared->physics_object); + } RB_body_set_linear_factor(rbo->shared->physics_object, (ob->protectflag & OB_LOCK_LOCX) == 0, @@ -714,8 +732,9 @@ static void rigidbody_validate_sim_object(RigidBodyWorld *rbw, Object *ob, bool rbo->flag & RBO_FLAG_KINEMATIC || rbo->flag & RBO_FLAG_DISABLED); } - if (rbw && rbw->shared->physics_world) + if (rbw && rbw->shared->physics_world) { RB_dworld_add_body(rbw->shared->physics_world, rbo->shared->physics_object, rbo->col_groups); + } } /* --------------------- */ @@ -753,41 +772,53 @@ static void rigidbody_constraint_init_spring(RigidBodyCon *rbc, static void rigidbody_constraint_set_limits(RigidBodyCon *rbc, void (*set_limits)(rbConstraint *, int, float, float)) { - if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X) + if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X) { set_limits( rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->limit_lin_x_lower, rbc->limit_lin_x_upper); - else + } + else { set_limits(rbc->physics_constraint, RB_LIMIT_LIN_X, 0.0f, -1.0f); + } - if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_Y) + if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_Y) { set_limits( rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->limit_lin_y_lower, rbc->limit_lin_y_upper); - else + } + else { set_limits(rbc->physics_constraint, RB_LIMIT_LIN_Y, 0.0f, -1.0f); + } - if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_Z) + if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_Z) { set_limits( rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->limit_lin_z_lower, rbc->limit_lin_z_upper); - else + } + else { set_limits(rbc->physics_constraint, RB_LIMIT_LIN_Z, 0.0f, -1.0f); + } - if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_X) + if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_X) { set_limits( rbc->physics_constraint, RB_LIMIT_ANG_X, rbc->limit_ang_x_lower, rbc->limit_ang_x_upper); - else + } + else { set_limits(rbc->physics_constraint, RB_LIMIT_ANG_X, 0.0f, -1.0f); + } - if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Y) + if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Y) { set_limits( rbc->physics_constraint, RB_LIMIT_ANG_Y, rbc->limit_ang_y_lower, rbc->limit_ang_y_upper); - else + } + else { set_limits(rbc->physics_constraint, RB_LIMIT_ANG_Y, 0.0f, -1.0f); + } - if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Z) + if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Z) { set_limits( rbc->physics_constraint, RB_LIMIT_ANG_Z, rbc->limit_ang_z_lower, rbc->limit_ang_z_upper); - else + } + else { set_limits(rbc->physics_constraint, RB_LIMIT_ANG_Z, 0.0f, -1.0f); + } } /** @@ -851,16 +882,19 @@ static void rigidbody_validate_sim_constraint(RigidBodyWorld *rbw, Object *ob, b RB_constraint_set_limits_hinge( rbc->physics_constraint, rbc->limit_ang_z_lower, rbc->limit_ang_z_upper); } - else + else { RB_constraint_set_limits_hinge(rbc->physics_constraint, 0.0f, -1.0f); + } break; case RBC_TYPE_SLIDER: rbc->physics_constraint = RB_constraint_new_slider(loc, rot, rb1, rb2); - if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X) + if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X) { RB_constraint_set_limits_slider( rbc->physics_constraint, rbc->limit_lin_x_lower, rbc->limit_lin_x_upper); - else + } + else { RB_constraint_set_limits_slider(rbc->physics_constraint, 0.0f, -1.0f); + } break; case RBC_TYPE_PISTON: rbc->physics_constraint = RB_constraint_new_piston(loc, rot, rb1, rb2); @@ -934,15 +968,19 @@ static void rigidbody_validate_sim_constraint(RigidBodyWorld *rbw, Object *ob, b RB_constraint_set_enabled(rbc->physics_constraint, rbc->flag & RBC_FLAG_ENABLED); - if (rbc->flag & RBC_FLAG_USE_BREAKING) + if (rbc->flag & RBC_FLAG_USE_BREAKING) { RB_constraint_set_breaking_threshold(rbc->physics_constraint, rbc->breaking_threshold); - else + } + else { RB_constraint_set_breaking_threshold(rbc->physics_constraint, FLT_MAX); + } - if (rbc->flag & RBC_FLAG_OVERRIDE_SOLVER_ITERATIONS) + if (rbc->flag & RBC_FLAG_OVERRIDE_SOLVER_ITERATIONS) { RB_constraint_set_solver_iterations(rbc->physics_constraint, rbc->num_solver_iterations); - else + } + else { RB_constraint_set_solver_iterations(rbc->physics_constraint, -1); + } } if (rbw && rbw->shared->physics_world && rbc->physics_constraint) { @@ -954,18 +992,24 @@ static void rigidbody_validate_sim_constraint(RigidBodyWorld *rbw, Object *ob, b /* --------------------- */ -/* Create physics sim world given RigidBody world settings */ -// NOTE: this does NOT update object references that the scene uses, in case those aren't ready yet! +/** + * Create physics sim world given RigidBody world settings + * + * \note this does NOT update object references that the scene uses, + * in case those aren't ready yet! + */ void BKE_rigidbody_validate_sim_world(Scene *scene, RigidBodyWorld *rbw, bool rebuild) { /* sanity checks */ - if (rbw == NULL) + if (rbw == NULL) { return; + } /* create new sim world */ if (rebuild || rbw->shared->physics_world == NULL) { - if (rbw->shared->physics_world) + if (rbw->shared->physics_world) { RB_dworld_delete(rbw->shared->physics_world); + } rbw->shared->physics_world = RB_dworld_new(scene->physics_settings.gravity); } @@ -986,8 +1030,9 @@ RigidBodyWorld *BKE_rigidbody_create_world(Scene *scene) * - there must be a valid scene to add world to * - there mustn't be a sim world using this group already */ - if (scene == NULL) + if (scene == NULL) { return NULL; + } /* create a new sim world */ rbw = MEM_callocN(sizeof(RigidBodyWorld), "RigidBodyWorld"); @@ -1068,8 +1113,9 @@ RigidBodyOb *BKE_rigidbody_create_object(Scene *scene, Object *ob, short type) * - object must exist * - cannot add rigid body if it already exists */ - if (ob == NULL || (ob->rigidbody_object != NULL)) + if (ob == NULL || (ob->rigidbody_object != NULL)) { return NULL; + } /* create new settings data, and link it up */ rbo = MEM_callocN(sizeof(RigidBodyOb), "RigidBodyOb"); @@ -1096,10 +1142,12 @@ RigidBodyOb *BKE_rigidbody_create_object(Scene *scene, Object *ob, short type) /* use triangle meshes for passive objects * use convex hulls for active objects since dynamic triangle meshes are very unstable */ - if (type == RBO_TYPE_ACTIVE) + if (type == RBO_TYPE_ACTIVE) { rbo->shape = RB_SHAPE_CONVEXH; - else + } + else { rbo->shape = RB_SHAPE_TRIMESH; + } rbo->mesh_source = RBO_MESH_DEFORM; @@ -1125,8 +1173,9 @@ RigidBodyCon *BKE_rigidbody_create_constraint(Scene *scene, Object *ob, short ty * - object must exist * - cannot add constraint if it already exists */ - if (ob == NULL || (ob->rigidbody_constraint != NULL)) + if (ob == NULL || (ob->rigidbody_constraint != NULL)) { return NULL; + } /* create new settings data, and link it up */ rbc = MEM_callocN(sizeof(RigidBodyCon), "RigidBodyCon"); @@ -1240,8 +1289,9 @@ void BKE_rigidbody_main_collection_object_add(Main *bmain, Collection *collectio RigidBodyWorld *BKE_rigidbody_get_world(Scene *scene) { /* sanity check */ - if (scene == NULL) + if (scene == NULL) { return NULL; + } return scene->rigidbody_world; } @@ -1363,8 +1413,13 @@ static void rigidbody_update_sim_ob( float scale[3]; /* only update if rigid body exists */ - if (rbo->shared->physics_object == NULL) + if (rbo->shared->physics_object == NULL) { return; + } + + ViewLayer *view_layer = DEG_get_input_view_layer(depsgraph); + Base *base = BKE_view_layer_base_find(view_layer, ob); + const bool is_selected = base ? (base->flag & BASE_SELECTED) != 0 : false; if (rbo->shape == RB_SHAPE_TRIMESH && rbo->flag & RBO_FLAG_USE_DEFORM) { Mesh *mesh = ob->runtime.mesh_deform_eval; @@ -1387,18 +1442,20 @@ static void rigidbody_update_sim_ob( /* update scale for all objects */ RB_body_set_scale(rbo->shared->physics_object, scale); /* compensate for embedded convex hull collision margin */ - if (!(rbo->flag & RBO_FLAG_USE_MARGIN) && rbo->shape == RB_SHAPE_CONVEXH) + if (!(rbo->flag & RBO_FLAG_USE_MARGIN) && rbo->shape == RB_SHAPE_CONVEXH) { RB_shape_set_margin(rbo->shared->physics_shape, RBO_GET_MARGIN(rbo) * MIN3(scale[0], scale[1], scale[2])); + } - /* make transformed objects temporarily kinmatic so that they can be moved by the user during simulation */ - if (ob->flag & SELECT && G.moving & G_TRANSFORM_OBJ) { + /* Make transformed objects temporarily kinmatic + * so that they can be moved by the user during simulation. */ + if (is_selected && (G.moving & G_TRANSFORM_OBJ)) { RB_body_set_kinematic_state(rbo->shared->physics_object, true); RB_body_set_mass(rbo->shared->physics_object, 0.0f); } /* update rigid body location and rotation for kinematic bodies */ - if (rbo->flag & RBO_FLAG_KINEMATIC || (ob->flag & SELECT && G.moving & G_TRANSFORM_OBJ)) { + if (rbo->flag & RBO_FLAG_KINEMATIC || (is_selected && (G.moving & G_TRANSFORM_OBJ))) { RB_body_activate(rbo->shared->physics_object); RB_body_set_loc_rot(rbo->shared->physics_object, loc, rot); } @@ -1417,29 +1474,33 @@ static void rigidbody_update_sim_ob( float eff_loc[3], eff_vel[3]; /* create dummy 'point' which represents last known position of object as result of sim */ - // XXX: this can create some inaccuracies with sim position, but is probably better than using unsimulated vals? + /* XXX: this can create some inaccuracies with sim position, + * but is probably better than using unsimulated vals? */ RB_body_get_position(rbo->shared->physics_object, eff_loc); RB_body_get_linear_velocity(rbo->shared->physics_object, eff_vel); pd_point_from_loc(scene, eff_loc, eff_vel, 0, &epoint); - /* calculate net force of effectors, and apply to sim object - * - we use 'central force' since apply force requires a "relative position" which we don't have... - */ + /* Calculate net force of effectors, and apply to sim object: + * - we use 'central force' since apply force requires a "relative position" + * which we don't have... */ BKE_effectors_apply(effectors, NULL, effector_weights, &epoint, eff_force, NULL); - if (G.f & G_DEBUG) + if (G.f & G_DEBUG) { printf("\tapplying force (%f,%f,%f) to '%s'\n", eff_force[0], eff_force[1], eff_force[2], ob->id.name + 2); + } /* activate object in case it is deactivated */ - if (!is_zero_v3(eff_force)) + if (!is_zero_v3(eff_force)) { RB_body_activate(rbo->shared->physics_object); + } RB_body_apply_central_force(rbo->shared->physics_object, eff_force); } - else if (G.f & G_DEBUG) + else if (G.f & G_DEBUG) { printf("\tno forces to apply to '%s'\n", ob->id.name + 2); + } /* cleanup */ BKE_effectors_free(effectors); @@ -1464,8 +1525,9 @@ static void rigidbody_update_simulation(Depsgraph *depsgraph, float ctime = DEG_get_ctime(depsgraph); /* update world */ - if (rebuild) + if (rebuild) { BKE_rigidbody_validate_sim_world(scene, rbw, true); + } rigidbody_update_sim_world(scene, rbw); /* XXX TODO For rebuild: remove all constraints first. @@ -1491,13 +1553,15 @@ static void rigidbody_update_simulation(Depsgraph *depsgraph, if (ob->type == OB_MESH) { /* validate that we've got valid object set up here... */ RigidBodyOb *rbo = ob->rigidbody_object; - /* update transformation matrix of the object so we don't get a frame of lag for simple animations */ + /* Update transformation matrix of the object + * so we don't get a frame of lag for simple animations. */ BKE_object_where_is_calc_time(depsgraph, scene, ob, ctime); /* TODO remove this whole block once we are sure we never get NULL rbo here anymore. */ /* This cannot be done in CoW evaluation context anymore... */ if (rbo == NULL) { - BLI_assert(!"CoW object part of RBW object collection without RB object data, should not happen.\n"); + BLI_assert(!"CoW object part of RBW object collection without RB object data, " + "should not happen.\n"); /* Since this object is included in the sim group but doesn't have * rigid body settings (perhaps it was added manually), add! * - assume object to be active? That is the default for newly added settings... @@ -1513,7 +1577,8 @@ static void rigidbody_update_simulation(Depsgraph *depsgraph, if (rebuild) { /* World has been rebuilt so rebuild object */ /* TODO(Sybren): rigidbody_validate_sim_object() can call rigidbody_validate_sim_shape(), - * but neither resets the RBO_FLAG_NEEDS_RESHAPE flag nor calls RB_body_set_collision_shape(). + * but neither resets the RBO_FLAG_NEEDS_RESHAPE flag nor + * calls RB_body_set_collision_shape(). * This results in the collision shape being created twice, which is unnecessary. */ rigidbody_validate_sim_object(rbw, ob, true); } @@ -1525,7 +1590,8 @@ static void rigidbody_update_simulation(Depsgraph *depsgraph, /* mesh/shape data changed, so force shape refresh */ rigidbody_validate_sim_shape(ob, true); /* now tell RB sim about it */ - // XXX: we assume that this can only get applied for active/passive shapes that will be included as rigidbodies + /* XXX: we assume that this can only get applied for active/passive shapes + * that will be included as rigidbodies. */ RB_body_set_collision_shape(rbo->shared->physics_object, rbo->shared->physics_shape); } } @@ -1538,19 +1604,22 @@ static void rigidbody_update_simulation(Depsgraph *depsgraph, FOREACH_COLLECTION_OBJECT_RECURSIVE_END; /* update constraints */ - if (rbw->constraints == NULL) /* no constraints, move on */ + if (rbw->constraints == NULL) { /* no constraints, move on */ return; + } FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN (rbw->constraints, ob) { /* validate that we've got valid object set up here... */ RigidBodyCon *rbc = ob->rigidbody_constraint; - /* update transformation matrix of the object so we don't get a frame of lag for simple animations */ + /* Update transformation matrix of the object + * so we don't get a frame of lag for simple animations. */ BKE_object_where_is_calc_time(depsgraph, scene, ob, ctime); /* TODO remove this whole block once we are sure we never get NULL rbo here anymore. */ /* This cannot be done in CoW evaluation context anymore... */ if (rbc == NULL) { - BLI_assert(!"CoW object part of RBW constraints collection without RB constraint data, should not happen.\n"); + BLI_assert(!"CoW object part of RBW constraints collection without RB constraint data, " + "should not happen.\n"); /* Since this object is included in the group but doesn't have * constraint settings (perhaps it was added manually), add! */ @@ -1587,8 +1656,9 @@ static void rigidbody_update_simulation_post_step(Depsgraph *depsgraph, RigidBod rbo->flag & RBO_FLAG_KINEMATIC || rbo->flag & RBO_FLAG_DISABLED); RB_body_set_mass(rbo->shared->physics_object, RBO_GET_MASS(rbo)); /* Deactivate passive objects so they don't interfere with deactivation of active objects. */ - if (rbo->type == RBO_TYPE_PASSIVE) + if (rbo->type == RBO_TYPE_PASSIVE) { RB_body_deactivate(rbo->shared->physics_object); + } } } FOREACH_COLLECTION_OBJECT_RECURSIVE_END; @@ -1605,12 +1675,13 @@ void BKE_rigidbody_sync_transforms(RigidBodyWorld *rbw, Object *ob, float ctime) RigidBodyOb *rbo = ob->rigidbody_object; /* keep original transform for kinematic and passive objects */ - if (ELEM(NULL, rbw, rbo) || rbo->flag & RBO_FLAG_KINEMATIC || rbo->type == RBO_TYPE_PASSIVE) + if (ELEM(NULL, rbw, rbo) || rbo->flag & RBO_FLAG_KINEMATIC || rbo->type == RBO_TYPE_PASSIVE) { return; + } /* use rigid body transform after cache start frame if objects is not being transformed */ if (BKE_rigidbody_check_sim_running(rbw, ctime) && - !(ob->flag & SELECT && G.moving & G_TRANSFORM_OBJ)) { + !(ob->base_flag & BASE_SELECTED && G.moving & G_TRANSFORM_OBJ)) { float mat[4][4], size_mat[4][4], size[3]; normalize_qt(rbo->orn); // RB_TODO investigate why quaternion isn't normalized at this point @@ -1690,11 +1761,13 @@ void BKE_rigidbody_aftertrans_update( if (rbo->shared->physics_object) { /* allow passive objects to return to original transform */ - if (rbo->type == RBO_TYPE_PASSIVE) + if (rbo->type == RBO_TYPE_PASSIVE) { RB_body_set_kinematic_state(rbo->shared->physics_object, true); + } RB_body_set_loc_rot(rbo->shared->physics_object, rbo->pos, rbo->orn); } - // RB_TODO update rigid body physics object's loc/rot for dynamic objects here as well (needs to be done outside bullet's update loop) + /* RB_TODO update rigid body physics object's loc/rot for dynamic objects here as well + * (needs to be done outside bullet's update loop). */ } void BKE_rigidbody_cache_reset(RigidBodyWorld *rbw) @@ -1719,7 +1792,8 @@ void BKE_rigidbody_rebuild_world(Depsgraph *depsgraph, Scene *scene, float ctime BKE_ptcache_id_time(&pid, scene, ctime, &startframe, &endframe, NULL); cache = rbw->shared->pointcache; - /* flag cache as outdated if we don't have a world or number of objects in the simulation has changed */ + /* Flag cache as outdated if we don't have a world or number of objects + * in the simulation has changed. */ int n = 0; FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN (rbw->group, object) { (void)object; @@ -1765,10 +1839,12 @@ void BKE_rigidbody_do_simulation(Depsgraph *depsgraph, Scene *scene, float ctime } /* don't try to run the simulation if we don't have a world yet but allow reading baked cache */ - if (rbw->shared->physics_world == NULL && !(cache->flag & PTCACHE_BAKED)) + if (rbw->shared->physics_world == NULL && !(cache->flag & PTCACHE_BAKED)) { return; - else if (rbw->objects == NULL) + } + else if (rbw->objects == NULL) { rigidbody_update_ob_array(rbw); + } /* try to read from cache */ // RB_TODO deal with interpolated, old and baked results @@ -1798,7 +1874,8 @@ void BKE_rigidbody_do_simulation(Depsgraph *depsgraph, Scene *scene, float ctime /* calculate how much time elapsed since last step in seconds */ timestep = 1.0f / (float)FPS * (ctime - rbw->ltime) * rbw->time_scale; - /* step simulation by the requested timestep, steps per second are adjusted to take time scale into account */ + /* Step simulation by the requested timestep, + * steps per second are adjusted to take time scale into account. */ RB_dworld_step_simulation(rbw->shared->physics_world, timestep, INT_MAX, @@ -1836,8 +1913,9 @@ void BKE_rigidbody_validate_sim_world(Scene *scene, RigidBodyWorld *rbw, bool re } void BKE_rigidbody_calc_volume(Object *ob, float *r_vol) { - if (r_vol) + if (r_vol) { *r_vol = 0.0f; + } } void BKE_rigidbody_calc_center_of_mass(Object *ob, float r_center[3]) { diff --git a/source/blender/blenkernel/intern/scene.c b/source/blender/blenkernel/intern/scene.c index 5fad95c54e2..58b36aed24f 100644 --- a/source/blender/blenkernel/intern/scene.c +++ b/source/blender/blenkernel/intern/scene.c @@ -225,8 +225,10 @@ void BKE_toolsettings_free(ToolSettings *toolsettings) } /** - * Only copy internal data of Scene ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of Scene ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * @@ -355,8 +357,9 @@ Scene *BKE_scene_copy(Main *bmain, Scene *sce, int type) sce_copy->eevee.light_cache = NULL; sce_copy->eevee.light_cache_info[0] = '\0'; - if (sce->id.properties) + if (sce->id.properties) { sce_copy->id.properties = IDP_CopyProperty(sce->id.properties); + } MEM_freeN(sce_copy->toolsettings); BKE_sound_destroy_scene(sce_copy); @@ -411,7 +414,7 @@ Scene *BKE_scene_copy(Main *bmain, Scene *sce, int type) id_us_min(&sce_copy->id); id_us_ensure_real(&sce_copy->id); - /* Extra actions, most notably SCE_FULL_COPY also duplicates several 'children' datablocks... */ + /* Extra actions, most notably SCE_FULL_COPY also duplicates several 'children' datablocks. */ if (type == SCE_COPY_FULL) { /* Copy Freestyle LineStyle datablocks. */ @@ -455,8 +458,9 @@ Scene *BKE_scene_copy(Main *bmain, Scene *sce, int type) void BKE_scene_groups_relink(Scene *sce) { - if (sce->rigidbody_world) + if (sce->rigidbody_world) { BKE_rigidbody_world_groups_relink(sce->rigidbody_world); + } } void BKE_scene_make_local(Main *bmain, Scene *sce, const bool lib_local) @@ -765,7 +769,8 @@ void BKE_scene_init(Scene *sce) BLI_rctf_init(&sce->r.safety, 0.1f, 0.9f, 0.1f, 0.9f); sce->r.osa = 8; - /* note; in header_info.c the scene copy happens..., if you add more to renderdata it has to be checked there */ + /* Note; in header_info.c the scene copy happens..., + * if you add more to renderdata it has to be checked there. */ /* multiview - stereo */ BKE_scene_add_render_view(sce, STEREO_LEFT_NAME); @@ -1004,7 +1009,8 @@ Object *BKE_scene_object_find_by_name(Scene *scene, const char *name) } /** - * Sets the active scene, mainly used when running in background mode (``--scene`` command line argument). + * Sets the active scene, mainly used when running in background mode + * (``--scene`` command line argument). * This is also called to set the scene directly, bypassing windowing code. * Otherwise #WM_window_set_active_scene is used when changing scenes by the user. */ @@ -1016,8 +1022,9 @@ void BKE_scene_set_background(Main *bmain, Scene *scene) BKE_scene_validate_setscene(bmain, scene); /* deselect objects (for dataselect) */ - for (ob = bmain->objects.first; ob; ob = ob->id.next) + for (ob = bmain->objects.first; ob; ob = ob->id.next) { ob->flag &= ~SELECT; + } /* copy layers and flags from bases to objects */ for (ViewLayer *view_layer = scene->view_layers.first; view_layer; @@ -1028,7 +1035,8 @@ void BKE_scene_set_background(Main *bmain, Scene *scene) BKE_scene_object_base_flag_sync_from_base(base); } } - /* no full animation update, this to enable render code to work (render code calls own animation updates) */ + /* No full animation update, this to enable render code to work + * (render code calls own animation updates). */ } /* called from creator_args.c */ @@ -1045,7 +1053,8 @@ Scene *BKE_scene_set_name(Main *bmain, const char *name) return NULL; } -/* Used by metaballs, return *all* objects (including duplis) existing in the scene (including scene's sets) */ +/* Used by metaballs, return *all* objects (including duplis) + * existing in the scene (including scene's sets). */ int BKE_scene_base_iter_next( Depsgraph *depsgraph, SceneBaseIter *iter, Scene **scene, int val, Base **base, Object **ob) { @@ -1204,8 +1213,9 @@ Object *BKE_scene_camera_switch_find(Scene *scene) camera = m->camera; frame = m->frame; - if (frame == cfra) + if (frame == cfra) { break; + } } if (m->frame < min_frame) { @@ -1249,14 +1259,17 @@ char *BKE_scene_find_marker_name(Scene *scene, int frame) /* search through markers for match */ for (m1 = markers->first, m2 = markers->last; m1 && m2; m1 = m1->next, m2 = m2->prev) { - if (m1->frame == frame) + if (m1->frame == frame) { return m1->name; + } - if (m1 == m2) + if (m1 == m2) { break; + } - if (m2->frame == frame) + if (m2->frame == frame) { return m2->name; + } } return NULL; @@ -1295,11 +1308,13 @@ int BKE_scene_frame_snap_by_seconds(Scene *scene, double interval_in_seconds, in void BKE_scene_remove_rigidbody_object(struct Main *bmain, Scene *scene, Object *ob) { /* remove rigid body constraint from world before removing object */ - if (ob->rigidbody_constraint) + if (ob->rigidbody_constraint) { BKE_rigidbody_remove_constraint(scene, ob); + } /* remove rigid body object from world before removing object */ - if (ob->rigidbody_object) + if (ob->rigidbody_object) { BKE_rigidbody_remove_object(bmain, scene, ob); + } } /* checks for cycle, returns 1 if it's all OK */ @@ -1308,8 +1323,9 @@ bool BKE_scene_validate_setscene(Main *bmain, Scene *sce) Scene *sce_iter; int a, totscene; - if (sce->set == NULL) + if (sce->set == NULL) { return true; + } totscene = BLI_listbase_count(&bmain->scenes); for (a = 0, sce_iter = sce; sce_iter->set; sce_iter = sce_iter->set, a++) { @@ -1324,8 +1340,10 @@ bool BKE_scene_validate_setscene(Main *bmain, Scene *sce) return true; } -/* This function is needed to cope with fractional frames - including two Blender rendering features - * mblur (motion blur that renders 'subframes' and blurs them together), and fields rendering. +/** + * This function is needed to cope with fractional frames - including two Blender rendering + * features mblur (motion blur that renders 'subframes' and blurs them together), + * and fields rendering. */ float BKE_scene_frame_get(const Scene *scene) { @@ -1547,15 +1565,6 @@ void BKE_scene_graph_update_for_newframe(Depsgraph *depsgraph, Main *bmain) BKE_image_editors_update_frame(bmain, scene->r.cfra); BKE_sound_set_cfra(scene->r.cfra); DEG_graph_relations_update(depsgraph, bmain, scene, view_layer); - /* Update animated cache files for modifiers. - * - * TODO(sergey): Make this a depsgraph node? - */ - BKE_cachefile_update_frame(bmain, - depsgraph, - scene, - ctime, - (((double)scene->r.frs_sec) / (double)scene->r.frs_sec_base)); #ifdef POSE_ANIMATION_WORKAROUND scene_armature_depsgraph_workaround(bmain, depsgraph); #endif @@ -1575,8 +1584,8 @@ void BKE_scene_graph_update_for_newframe(Depsgraph *depsgraph, Main *bmain) /** Ensures given scene/view_layer pair has a valid, up-to-date depsgraph. * - * \warning Sets matching depsgraph as active, so should only be called from the active editing context - * (usually, from operators). + * \warning Sets matching depsgraph as active, + * so should only be called from the active editing context (usually, from operators). */ void BKE_scene_view_layer_graph_evaluated_ensure(Main *bmain, Scene *scene, ViewLayer *view_layer) { @@ -1590,8 +1599,9 @@ SceneRenderView *BKE_scene_add_render_view(Scene *sce, const char *name) { SceneRenderView *srv; - if (!name) + if (!name) { name = DATA_("RenderView"); + } srv = MEM_callocN(sizeof(SceneRenderView), "new render view"); BLI_strncpy(srv->name, name, sizeof(srv->name)); @@ -1631,10 +1641,12 @@ bool BKE_scene_remove_render_view(Scene *scene, SceneRenderView *srv) int get_render_subsurf_level(const RenderData *r, int lvl, bool for_render) { if (r->mode & R_SIMPLIFY) { - if (for_render) + if (for_render) { return min_ii(r->simplify_subsurf_render, lvl); - else + } + else { return min_ii(r->simplify_subsurf, lvl); + } } else { return lvl; @@ -1644,10 +1656,12 @@ int get_render_subsurf_level(const RenderData *r, int lvl, bool for_render) int get_render_child_particle_number(const RenderData *r, int num, bool for_render) { if (r->mode & R_SIMPLIFY) { - if (for_render) + if (for_render) { return (int)(r->simplify_particles_render * num); - else + } + else { return (int)(r->simplify_particles * num); + } } else { return num; @@ -1728,31 +1742,20 @@ void BKE_scene_base_flag_to_objects(ViewLayer *view_layer) } } +/** + * Synchronize object base flags + * + * This is usually handled by the depsgraph. + * However, in rare occasions we need to use the latest object flags + * before depsgraph is fully updated. + * + * It should (ideally) only run for copy-on-written objects since this is + * runtime data generated per-viewlayer. + */ void BKE_scene_object_base_flag_sync_from_base(Base *base) { Object *ob = base->object; - - ob->flag = base->flag; - - if ((base->flag & BASE_SELECTED) != 0) { - ob->flag |= SELECT; - } - else { - ob->flag &= ~SELECT; - } -} - -void BKE_scene_object_base_flag_sync_from_object(Base *base) -{ - Object *ob = base->object; - base->flag = ob->flag; - - if ((ob->flag & SELECT) != 0 && (base->flag & BASE_SELECTABLE) != 0) { - base->flag |= BASE_SELECTED; - } - else { - base->flag &= ~BASE_SELECTED; - } + ob->base_flag = base->flag; } void BKE_scene_disable_color_management(Scene *scene) @@ -1793,14 +1796,17 @@ int BKE_render_num_threads(const RenderData *rd) /* override set from command line? */ threads = BLI_system_num_threads_override_get(); - if (threads > 0) + if (threads > 0) { return threads; + } /* fixed number of threads specified in scene? */ - if (rd->mode & R_FIXED_THREADS) + if (rd->mode & R_FIXED_THREADS) { threads = rd->threads; - else + } + else { threads = BLI_system_thread_count(); + } return max_ii(threads, 1); } @@ -1818,8 +1824,9 @@ int BKE_render_preview_pixel_size(const RenderData *r) return r->preview_pixel_size; } -/* Apply the needed correction factor to value, based on unit_type (only length-related are affected currently) - * and unit->scale_length. +/** + * Apply the needed correction factor to value, based on unit_type + * (only length-related are affected currently) and unit->scale_length. */ double BKE_scene_unit_scale(const UnitSettings *unit, const int unit_type, double value) { @@ -1851,8 +1858,9 @@ int BKE_scene_multiview_num_views_get(const RenderData *rd) SceneRenderView *srv; int totviews = 0; - if ((rd->scemode & R_MULTIVIEW) == 0) + if ((rd->scemode & R_MULTIVIEW) == 0) { return 1; + } if (rd->views_format == SCE_VIEWS_FORMAT_STEREO_3D) { srv = BLI_findstring(&rd->views, STEREO_LEFT_NAME, offsetof(SceneRenderView, name)); @@ -1879,8 +1887,9 @@ bool BKE_scene_multiview_is_stereo3d(const RenderData *rd) { SceneRenderView *srv[2]; - if ((rd->scemode & R_MULTIVIEW) == 0) + if ((rd->scemode & R_MULTIVIEW) == 0) { return false; + } srv[0] = (SceneRenderView *)BLI_findstring( &rd->views, STEREO_LEFT_NAME, offsetof(SceneRenderView, name)); @@ -1894,17 +1903,21 @@ bool BKE_scene_multiview_is_stereo3d(const RenderData *rd) /* return whether to render this SceneRenderView */ bool BKE_scene_multiview_is_render_view_active(const RenderData *rd, const SceneRenderView *srv) { - if (srv == NULL) + if (srv == NULL) { return false; + } - if ((rd->scemode & R_MULTIVIEW) == 0) + if ((rd->scemode & R_MULTIVIEW) == 0) { return false; + } - if ((srv->viewflag & SCE_VIEW_DISABLE)) + if ((srv->viewflag & SCE_VIEW_DISABLE)) { return false; + } - if (rd->views_format == SCE_VIEWS_FORMAT_MULTIVIEW) + if (rd->views_format == SCE_VIEWS_FORMAT_MULTIVIEW) { return true; + } /* SCE_VIEWS_SETUP_BASIC */ if (STREQ(srv->name, STEREO_LEFT_NAME) || STREQ(srv->name, STEREO_RIGHT_NAME)) { @@ -1919,11 +1932,13 @@ bool BKE_scene_multiview_is_render_view_first(const RenderData *rd, const char * { SceneRenderView *srv; - if ((rd->scemode & R_MULTIVIEW) == 0) + if ((rd->scemode & R_MULTIVIEW) == 0) { return true; + } - if ((!viewname) || (!viewname[0])) + if ((!viewname) || (!viewname[0])) { return true; + } for (srv = rd->views.first; srv; srv = srv->next) { if (BKE_scene_multiview_is_render_view_active(rd, srv)) { @@ -1939,11 +1954,13 @@ bool BKE_scene_multiview_is_render_view_last(const RenderData *rd, const char *v { SceneRenderView *srv; - if ((rd->scemode & R_MULTIVIEW) == 0) + if ((rd->scemode & R_MULTIVIEW) == 0) { return true; + } - if ((!viewname) || (!viewname[0])) + if ((!viewname) || (!viewname[0])) { return true; + } for (srv = rd->views.last; srv; srv = srv->prev) { if (BKE_scene_multiview_is_render_view_active(rd, srv)) { @@ -1959,13 +1976,15 @@ SceneRenderView *BKE_scene_multiview_render_view_findindex(const RenderData *rd, SceneRenderView *srv; size_t nr; - if ((rd->scemode & R_MULTIVIEW) == 0) + if ((rd->scemode & R_MULTIVIEW) == 0) { return NULL; + } for (srv = rd->views.first, nr = 0; srv; srv = srv->next) { if (BKE_scene_multiview_is_render_view_active(rd, srv)) { - if (nr++ == view_id) + if (nr++ == view_id) { return srv; + } } } return srv; @@ -1975,10 +1994,12 @@ const char *BKE_scene_multiview_render_view_name_get(const RenderData *rd, const { SceneRenderView *srv = BKE_scene_multiview_render_view_findindex(rd, view_id); - if (srv) + if (srv) { return srv->name; - else + } + else { return ""; + } } int BKE_scene_multiview_view_id_get(const RenderData *rd, const char *viewname) @@ -1986,11 +2007,13 @@ int BKE_scene_multiview_view_id_get(const RenderData *rd, const char *viewname) SceneRenderView *srv; size_t nr; - if ((!rd) || ((rd->scemode & R_MULTIVIEW) == 0)) + if ((!rd) || ((rd->scemode & R_MULTIVIEW) == 0)) { return 0; + } - if ((!viewname) || (!viewname[0])) + if ((!viewname) || (!viewname[0])) { return 0; + } for (srv = rd->views.first, nr = 0; srv; srv = srv->next) { if (BKE_scene_multiview_is_render_view_active(rd, srv)) { @@ -2027,10 +2050,12 @@ void BKE_scene_multiview_view_filepath_get(const RenderData *rd, char suffix[FILE_MAX]; srv = BLI_findstring(&rd->views, viewname, offsetof(SceneRenderView, name)); - if (srv) + if (srv) { BLI_strncpy(suffix, srv->suffix, sizeof(suffix)); - else + } + else { BLI_strncpy(suffix, viewname, sizeof(suffix)); + } BLI_strncpy(r_filepath, filepath, FILE_MAX); BLI_path_suffix(r_filepath, FILE_MAX, suffix, ""); @@ -2040,14 +2065,17 @@ const char *BKE_scene_multiview_view_suffix_get(const RenderData *rd, const char { SceneRenderView *srv; - if ((viewname == NULL) || (viewname[0] == '\0')) + if ((viewname == NULL) || (viewname[0] == '\0')) { return viewname; + } srv = BLI_findstring(&rd->views, viewname, offsetof(SceneRenderView, name)); - if (srv) + if (srv) { return srv->suffix; - else + } + else { return viewname; + } } const char *BKE_scene_multiview_view_id_suffix_get(const RenderData *rd, const int view_id) @@ -2075,8 +2103,9 @@ void BKE_scene_multiview_view_prefix_get(Scene *scene, /* begin of extension */ index_act = BLI_str_rpartition(name, delims, rext, &suf_act); - if (*rext == NULL) + if (*rext == NULL) { return; + } BLI_assert(index_act > 0); UNUSED_VARS_NDEBUG(index_act); @@ -2113,11 +2142,13 @@ void BKE_scene_multiview_videos_dimensions_get(const RenderData *rd, int BKE_scene_multiview_num_videos_get(const RenderData *rd) { - if (BKE_imtype_is_movie(rd->im_format.imtype) == false) + if (BKE_imtype_is_movie(rd->im_format.imtype) == false) { return 0; + } - if ((rd->scemode & R_MULTIVIEW) == 0) + if ((rd->scemode & R_MULTIVIEW) == 0) { return 1; + } if (rd->im_format.views_format == R_IMF_VIEWS_STEREO_3D) { return 1; @@ -2256,7 +2287,8 @@ TransformOrientation *BKE_scene_transform_orientation_find(const Scene *scene, c } /** - * \return the index that \a orientation has within \a scene's transform-orientation list or -1 if not found. + * \return the index that \a orientation has within \a scene's transform-orientation list + * or -1 if not found. */ int BKE_scene_transform_orientation_get_index(const Scene *scene, const TransformOrientation *orientation) diff --git a/source/blender/blenkernel/intern/screen.c b/source/blender/blenkernel/intern/screen.c index 9fa70d38574..9799f7c2943 100644 --- a/source/blender/blenkernel/intern/screen.c +++ b/source/blender/blenkernel/intern/screen.c @@ -99,8 +99,9 @@ SpaceType *BKE_spacetype_from_id(int spaceid) SpaceType *st; for (st = spacetypes.first; st; st = st->next) { - if (st->spaceid == spaceid) + if (st->spaceid == spaceid) { return st; + } } return NULL; } @@ -109,9 +110,11 @@ ARegionType *BKE_regiontype_from_id_or_first(SpaceType *st, int regionid) { ARegionType *art; - for (art = st->regiontypes.first; art; art = art->next) - if (art->regionid == regionid) + for (art = st->regiontypes.first; art; art = art->next) { + if (art->regionid == regionid) { return art; + } + } printf( "Error, region type %d missing in - name:\"%s\", id:%d\n", regionid, st->name, st->spaceid); @@ -166,13 +169,15 @@ void BKE_spacedata_freelist(ListBase *lb) SpaceType *st = BKE_spacetype_from_id(sl->spacetype); /* free regions for pushed spaces */ - for (ar = sl->regionbase.first; ar; ar = ar->next) + for (ar = sl->regionbase.first; ar; ar = ar->next) { BKE_area_region_free(st, ar); + } BLI_freelistN(&sl->regionbase); - if (st && st->free) + if (st && st->free) { st->free(sl); + } } BLI_freelistN(lb); @@ -235,8 +240,9 @@ ARegion *BKE_area_region_copy(SpaceType *st, ARegion *ar) } } - if (ar->v2d.tab_offset) + if (ar->v2d.tab_offset) { newar->v2d.tab_offset = MEM_dupallocN(ar->v2d.tab_offset); + } panel_list_copy(&newar->panels, &ar->panels); @@ -291,16 +297,19 @@ void BKE_spacedata_draw_locks(int set) ARegionType *art; for (art = st->regiontypes.first; art; art = art->next) { - if (set) + if (set) { art->do_lock = art->lock; - else + } + else { art->do_lock = false; + } } } } /** - * Version of #BKE_area_find_region_type that also works if \a slink is not the active space of \a sa. + * Version of #BKE_area_find_region_type that also works if \a slink + * is not the active space of \a sa. */ ARegion *BKE_spacedata_find_region_type(const SpaceLink *slink, const ScrArea *sa, int region_type) { @@ -398,14 +407,17 @@ void BKE_area_region_free(SpaceType *st, ARegion *ar) if (st) { ARegionType *art = BKE_regiontype_from_id(st, ar->regiontype); - if (art && art->free) + if (art && art->free) { art->free(ar); + } - if (ar->regiondata) + if (ar->regiondata) { printf("regiondata free error\n"); + } } - else if (ar->type && ar->type->free) + else if (ar->type && ar->type->free) { ar->type->free(ar); + } if (ar->v2d.tab_offset) { MEM_freeN(ar->v2d.tab_offset); @@ -447,8 +459,9 @@ void BKE_screen_area_free(ScrArea *sa) SpaceType *st = BKE_spacetype_from_id(sa->spacetype); ARegion *ar; - for (ar = sa->regionbase.first; ar; ar = ar->next) + for (ar = sa->regionbase.first; ar; ar = ar->next) { BKE_area_region_free(st, ar); + } MEM_SAFE_FREE(sa->global); BLI_freelistN(&sa->regionbase); @@ -477,8 +490,9 @@ void BKE_screen_free(bScreen *sc) /* No animdata here. */ - for (ar = sc->regionbase.first; ar; ar = ar->next) + for (ar = sc->regionbase.first; ar; ar = ar->next) { BKE_area_region_free(NULL, ar); + } BLI_freelistN(&sc->regionbase); @@ -543,24 +557,30 @@ void BKE_screen_remove_double_scrverts(bScreen *sc) /* replace pointers in edges and faces */ se = sc->edgebase.first; while (se) { - if (se->v1->newv) + if (se->v1->newv) { se->v1 = se->v1->newv; - if (se->v2->newv) + } + if (se->v2->newv) { se->v2 = se->v2->newv; + } /* edges changed: so.... */ BKE_screen_sort_scrvert(&(se->v1), &(se->v2)); se = se->next; } sa = sc->areabase.first; while (sa) { - if (sa->v1->newv) + if (sa->v1->newv) { sa->v1 = sa->v1->newv; - if (sa->v2->newv) + } + if (sa->v2->newv) { sa->v2 = sa->v2->newv; - if (sa->v3->newv) + } + if (sa->v3->newv) { sa->v3 = sa->v3->newv; - if (sa->v4->newv) + } + if (sa->v4->newv) { sa->v4 = sa->v4->newv; + } sa = sa->next; } @@ -606,25 +626,33 @@ void BKE_screen_remove_unused_scredges(bScreen *sc) sa = sc->areabase.first; while (sa) { se = BKE_screen_find_edge(sc, sa->v1, sa->v2); - if (se == NULL) + if (se == NULL) { printf("error: area %d edge 1 doesn't exist\n", a); - else + } + else { se->flag = 1; + } se = BKE_screen_find_edge(sc, sa->v2, sa->v3); - if (se == NULL) + if (se == NULL) { printf("error: area %d edge 2 doesn't exist\n", a); - else + } + else { se->flag = 1; + } se = BKE_screen_find_edge(sc, sa->v3, sa->v4); - if (se == NULL) + if (se == NULL) { printf("error: area %d edge 3 doesn't exist\n", a); - else + } + else { se->flag = 1; + } se = BKE_screen_find_edge(sc, sa->v4, sa->v1); - if (se == NULL) + if (se == NULL) { printf("error: area %d edge 4 doesn't exist\n", a); - else + } + else { se->flag = 1; + } sa = sa->next; a++; } @@ -682,8 +710,9 @@ ARegion *BKE_area_find_region_type(const ScrArea *sa, int region_type) { if (sa) { for (ARegion *ar = sa->regionbase.first; ar; ar = ar->next) { - if (ar->regiontype == region_type) + if (ar->regiontype == region_type) { return ar; + } } } @@ -793,8 +822,9 @@ void BKE_screen_view3d_sync(View3D *v3d, struct Scene *scene) for (ar = v3d->regionbase.first; ar; ar = ar->next) { if (ar->regiontype == RGN_TYPE_WINDOW) { RegionView3D *rv3d = ar->regiondata; - if (rv3d->persp == RV3D_CAMOB) + if (rv3d->persp == RV3D_CAMOB) { rv3d->persp = RV3D_PERSP; + } } } } @@ -868,7 +898,7 @@ void BKE_screen_header_alignment_reset(bScreen *screen) int alignment = (U.uiflag & USER_HEADER_BOTTOM) ? RGN_ALIGN_BOTTOM : RGN_ALIGN_TOP; for (ScrArea *sa = screen->areabase.first; sa; sa = sa->next) { for (ARegion *ar = sa->regionbase.first; ar; ar = ar->next) { - if (ar->regiontype == RGN_TYPE_HEADER) { + if (ELEM(ar->regiontype, RGN_TYPE_HEADER, RGN_TYPE_TOOL_HEADER)) { if (ELEM(sa->spacetype, SPACE_FILE, SPACE_USERPREF, SPACE_OUTLINER, SPACE_PROPERTIES)) { ar->alignment = RGN_ALIGN_TOP; continue; diff --git a/source/blender/blenkernel/intern/seqcache.c b/source/blender/blenkernel/intern/seqcache.c index 7024bafd988..1c0aa63f590 100644 --- a/source/blender/blenkernel/intern/seqcache.c +++ b/source/blender/blenkernel/intern/seqcache.c @@ -21,49 +21,84 @@ */ #include <stddef.h> - -#include "BLI_sys_types.h" /* for intptr_t */ +#include <memory.h> #include "MEM_guardedalloc.h" #include "DNA_sequence_types.h" #include "DNA_scene_types.h" -#include "IMB_moviecache.h" #include "IMB_imbuf.h" #include "IMB_imbuf_types.h" +#include "BLI_mempool.h" +#include "BLI_threads.h" #include "BLI_listbase.h" +#include "BLI_ghash.h" #include "BKE_sequencer.h" #include "BKE_scene.h" +#include "BKE_main.h" + +/* ***************************** Sequencer cache design notes ****************************** + * + * Cache key members: + * is_temp_cache - this cache entry will be freed before rendering next frame + * creator_id - ID of thread that created entry + * cost - In short: render time divided by playback frame rate + * link_prev/next - link to another entry created during rendering of the frame + * + * Linking: We use links to reduce number of iterations needed to manage cache. + * Entries are linked in order as they are put into cache. + * Only pernament (is_temp_cache = 0) cache entries are linked. + * Putting SEQ_CACHE_STORE_FINAL_OUT will reset linking + * + * Function: + * All images created during rendering are added to cache, even if the cache is already full. + * This is because: + * - one image may be needed multiple times during rendering. + * - keeping the last rendered frame allows us for faster re-render when user edits strip in stack + * - we can decide if we keep frame only when it's completely rendered. Otherwise we risk having + * "holes" in the cache, which can be annoying + * If the cache is full all entries for pending frame will have is_temp_cache set. + * + * Only entire frame can be freed to release resources for new entries (recycling). + * Once again, this is to reduce number of iterations, but also more controllable than removing + * entries one by one in reverse order to their creation. + * + * User can exclude caching of some images. Such entries will have is_temp_cache set. + */ + +typedef struct SeqCache { + struct GHash *hash; + ThreadMutex iterator_mutex; + struct BLI_mempool *keys_pool; + struct BLI_mempool *items_pool; + struct SeqCacheKey *last_key; + size_t memory_used; +} SeqCache; + +typedef struct SeqCacheItem { + struct SeqCache *cache_owner; + struct ImBuf *ibuf; +} SeqCacheItem; typedef struct SeqCacheKey { + struct SeqCache *cache_owner; + void *userkey; + struct SeqCacheKey *link_prev; /* Used for linking intermediate items to final frame */ + struct SeqCacheKey *link_next; /* Used for linking intermediate items to final frame */ struct Sequence *seq; SeqRenderData context; float cfra; - eSeqStripElemIBuf type; + float nfra; + float cost; + bool is_temp_cache; + short creator_id; + int type; } SeqCacheKey; -typedef struct SeqPreprocessCacheElem { - struct SeqPreprocessCacheElem *next, *prev; - - struct Sequence *seq; - SeqRenderData context; - eSeqStripElemIBuf type; - - ImBuf *ibuf; -} SeqPreprocessCacheElem; - -typedef struct SeqPreprocessCache { - int cfra; - ListBase elems; -} SeqPreprocessCache; - -static struct MovieCache *moviecache = NULL; -static struct SeqPreprocessCache *preprocess_cache = NULL; - -static void preprocessed_cache_destruct(void); +static ThreadMutex cache_create_lock = BLI_MUTEX_INITIALIZER; static bool seq_cmp_render_data(const SeqRenderData *a, const SeqRenderData *b) { @@ -88,198 +123,536 @@ static unsigned int seq_hash_render_data(const SeqRenderData *a) return rval; } -static unsigned int seqcache_hashhash(const void *key_) +static unsigned int seq_cache_hashhash(const void *key_) { const SeqCacheKey *key = key_; unsigned int rval = seq_hash_render_data(&key->context); - rval ^= *(const unsigned int *)&key->cfra; + rval ^= *(const unsigned int *)&key->nfra; rval += key->type; rval ^= ((intptr_t)key->seq) << 6; return rval; } -static bool seqcache_hashcmp(const void *a_, const void *b_) +static bool seq_cache_hashcmp(const void *a_, const void *b_) { const SeqCacheKey *a = a_; const SeqCacheKey *b = b_; - return ((a->seq != b->seq) || (a->cfra != b->cfra) || (a->type != b->type) || + return ((a->seq != b->seq) || (a->nfra != b->nfra) || (a->type != b->type) || seq_cmp_render_data(&a->context, &b->context)); } -void BKE_sequencer_cache_destruct(void) +static SeqCache *seq_cache_get_from_scene(Scene *scene) { - if (moviecache) - IMB_moviecache_free(moviecache); + if (scene && scene->ed && scene->ed->cache) { + return scene->ed->cache; + } - preprocessed_cache_destruct(); + return NULL; } -void BKE_sequencer_cache_cleanup(void) +static void seq_cache_lock(Scene *scene) { - if (moviecache) { - IMB_moviecache_free(moviecache); - moviecache = IMB_moviecache_create( - "seqcache", sizeof(SeqCacheKey), seqcache_hashhash, seqcache_hashcmp); + SeqCache *cache = seq_cache_get_from_scene(scene); + + if (cache) { + BLI_mutex_lock(&cache->iterator_mutex); } +} - BKE_sequencer_preprocessed_cache_cleanup(); +static void seq_cache_unlock(Scene *scene) +{ + SeqCache *cache = seq_cache_get_from_scene(scene); + + if (cache) { + BLI_mutex_unlock(&cache->iterator_mutex); + } +} + +static void seq_cache_keyfree(void *val) +{ + SeqCacheKey *key = val; + BLI_mempool_free(key->cache_owner->keys_pool, key); } -static bool seqcache_key_check_seq(ImBuf *UNUSED(ibuf), void *userkey, void *userdata) +static void seq_cache_valfree(void *val) { - SeqCacheKey *key = (SeqCacheKey *)userkey; - Sequence *seq = (Sequence *)userdata; + SeqCacheItem *item = (SeqCacheItem *)val; + SeqCache *cache = item->cache_owner; + + if (item->ibuf) { + cache->memory_used -= IMB_get_size_in_memory(item->ibuf); + IMB_freeImBuf(item->ibuf); + } - return key->seq == seq; + BLI_mempool_free(item->cache_owner->items_pool, item); } -void BKE_sequencer_cache_cleanup_sequence(Sequence *seq) +static void seq_cache_put(SeqCache *cache, SeqCacheKey *key, ImBuf *ibuf) { - if (moviecache) - IMB_moviecache_cleanup(moviecache, seqcache_key_check_seq, seq); + SeqCacheItem *item; + item = BLI_mempool_alloc(cache->items_pool); + item->cache_owner = cache; + item->ibuf = ibuf; + + if (BLI_ghash_reinsert(cache->hash, key, item, seq_cache_keyfree, seq_cache_valfree)) { + IMB_refImBuf(ibuf); + cache->last_key = key; + cache->memory_used += IMB_get_size_in_memory(ibuf); + } } -struct ImBuf *BKE_sequencer_cache_get(const SeqRenderData *context, - Sequence *seq, - float cfra, - eSeqStripElemIBuf type) +static ImBuf *seq_cache_get(SeqCache *cache, void *key) { - if (moviecache && seq) { - SeqCacheKey key; + SeqCacheItem *item = BLI_ghash_lookup(cache->hash, key); - key.seq = seq; - key.context = *context; - key.cfra = cfra - seq->start; - key.type = type; + if (item && item->ibuf) { + IMB_refImBuf(item->ibuf); - return IMB_moviecache_get(moviecache, &key); + return item->ibuf; } return NULL; } -void BKE_sequencer_cache_put( - const SeqRenderData *context, Sequence *seq, float cfra, eSeqStripElemIBuf type, ImBuf *i) +static void seq_cache_relink_keys(SeqCacheKey *link_next, SeqCacheKey *link_prev) { - SeqCacheKey key; + if (link_next) { + link_next->link_prev = link_prev; + } + if (link_prev) { + link_prev->link_next = link_next; + } +} - if (i == NULL || context->skip_cache) { +static SeqCacheKey *seq_cache_choose_key(Scene *scene, SeqCacheKey *lkey, SeqCacheKey *rkey) +{ + SeqCacheKey *finalkey = NULL; + + if (rkey && lkey) { + if (lkey->cfra > rkey->cfra) { + SeqCacheKey *swapkey = lkey; + lkey = rkey; + rkey = swapkey; + } + + int l_diff = scene->r.cfra - lkey->cfra; + int r_diff = rkey->cfra - scene->r.cfra; + + if (l_diff > r_diff) { + finalkey = lkey; + } + else { + finalkey = rkey; + } + } + else { + if (lkey) { + finalkey = lkey; + } + else { + finalkey = rkey; + } + } + return finalkey; +} + +static void seq_cache_recycle_linked(Scene *scene, SeqCacheKey *base) +{ + SeqCache *cache = seq_cache_get_from_scene(scene); + if (!cache) { return; } - if (!moviecache) { - moviecache = IMB_moviecache_create( - "seqcache", sizeof(SeqCacheKey), seqcache_hashhash, seqcache_hashcmp); + SeqCacheKey *next = base->link_next; + + while (base) { + SeqCacheKey *prev = base->link_prev; + BLI_ghash_remove(cache->hash, base, seq_cache_keyfree, seq_cache_valfree); + base = prev; + } + + base = next; + while (base) { + next = base->link_next; + BLI_ghash_remove(cache->hash, base, seq_cache_keyfree, seq_cache_valfree); + base = next; + } +} + +static SeqCacheKey *seq_cache_get_item_for_removal(Scene *scene) +{ + SeqCache *cache = seq_cache_get_from_scene(scene); + SeqCacheKey *finalkey = NULL; + /*leftmost key*/ + SeqCacheKey *lkey = NULL; + /*rightmost key*/ + SeqCacheKey *rkey = NULL; + SeqCacheKey *key = NULL; + + GHashIterator gh_iter; + BLI_ghashIterator_init(&gh_iter, cache->hash); + int total_count = 0; + int cheap_count = 0; + + while (!BLI_ghashIterator_done(&gh_iter)) { + key = BLI_ghashIterator_getKey(&gh_iter); + SeqCacheItem *item = BLI_ghashIterator_getValue(&gh_iter); + BLI_ghashIterator_step(&gh_iter); + + /* this shouldn't happen, but better be safe than sorry */ + if (!item->ibuf) { + seq_cache_recycle_linked(scene, key); + /* can not continue iterating after linked remove */ + BLI_ghashIterator_init(&gh_iter, cache->hash); + continue; + } + + if (key->is_temp_cache || key->link_next != NULL) { + continue; + } + + total_count++; + + if (key->cost <= scene->ed->recycle_max_cost) { + cheap_count++; + if (lkey) { + if (key->cfra < lkey->cfra) { + lkey = key; + } + } + else { + lkey = key; + } + if (rkey) { + if (key->cfra > rkey->cfra) { + rkey = key; + } + } + else { + rkey = key; + } + } + } + + finalkey = seq_cache_choose_key(scene, lkey, rkey); + return finalkey; +} + +/* Find only "base" keys + * Sources(other types) for a frame must be freed all at once + */ +static bool seq_cache_recycle_item(Scene *scene) +{ + size_t memory_total = ((size_t)U.memcachelimit) * 1024 * 1024; + SeqCache *cache = seq_cache_get_from_scene(scene); + if (!cache) { + return false; + } + + seq_cache_lock(scene); + + while (cache->memory_used > memory_total) { + SeqCacheKey *finalkey = seq_cache_get_item_for_removal(scene); + + if (finalkey) { + seq_cache_recycle_linked(scene, finalkey); + } + else { + seq_cache_unlock(scene); + return false; + } + } + seq_cache_unlock(scene); + return true; +} + +static void seq_cache_set_temp_cache_linked(Scene *scene, SeqCacheKey *base) +{ + SeqCache *cache = seq_cache_get_from_scene(scene); + + if (!cache || !base) { + return; } - key.seq = seq; - key.context = *context; - key.cfra = cfra - seq->start; - key.type = type; + SeqCacheKey *next = base->link_next; + + while (base) { + SeqCacheKey *prev = base->link_prev; + base->is_temp_cache = true; + base = prev; + } - IMB_moviecache_put(moviecache, &key, i); + base = next; + while (base) { + next = base->link_next; + base->is_temp_cache = true; + base = next; + } } -void BKE_sequencer_preprocessed_cache_cleanup(void) +static void BKE_sequencer_cache_create(Scene *scene) { - SeqPreprocessCacheElem *elem; + BLI_mutex_lock(&cache_create_lock); + if (scene->ed->cache == NULL) { + SeqCache *cache = MEM_callocN(sizeof(SeqCache), "SeqCache"); + cache->keys_pool = BLI_mempool_create(sizeof(SeqCacheKey), 0, 64, BLI_MEMPOOL_NOP); + cache->items_pool = BLI_mempool_create(sizeof(SeqCacheItem), 0, 64, BLI_MEMPOOL_NOP); + cache->hash = BLI_ghash_new(seq_cache_hashhash, seq_cache_hashcmp, "SeqCache hash"); + cache->last_key = NULL; + BLI_mutex_init(&cache->iterator_mutex); + scene->ed->cache = cache; + } + BLI_mutex_unlock(&cache_create_lock); +} + +/* ***************************** API ****************************** */ - if (!preprocess_cache) +void BKE_sequencer_cache_free_temp_cache(Scene *scene, short id, int cfra) +{ + SeqCache *cache = seq_cache_get_from_scene(scene); + if (!cache) { return; + } + + seq_cache_lock(scene); - for (elem = preprocess_cache->elems.first; elem; elem = elem->next) { - IMB_freeImBuf(elem->ibuf); + GHashIterator gh_iter; + BLI_ghashIterator_init(&gh_iter, cache->hash); + while (!BLI_ghashIterator_done(&gh_iter)) { + SeqCacheKey *key = BLI_ghashIterator_getKey(&gh_iter); + BLI_ghashIterator_step(&gh_iter); + + if (key->is_temp_cache && key->creator_id == id && key->cfra != cfra) { + BLI_ghash_remove(cache->hash, key, seq_cache_keyfree, seq_cache_valfree); + } } - BLI_freelistN(&preprocess_cache->elems); + seq_cache_unlock(scene); +} - BLI_listbase_clear(&preprocess_cache->elems); +void BKE_sequencer_cache_destruct(Scene *scene) +{ + SeqCache *cache = seq_cache_get_from_scene(scene); + if (!cache) { + return; + } + + BLI_ghash_free(cache->hash, seq_cache_keyfree, seq_cache_valfree); + BLI_mempool_destroy(cache->keys_pool); + BLI_mempool_destroy(cache->items_pool); + BLI_mutex_end(&cache->iterator_mutex); + MEM_freeN(cache); + scene->ed->cache = NULL; } -static void preprocessed_cache_destruct(void) +void BKE_sequencer_cache_cleanup_all(Main *bmain) +{ + for (Scene *scene = bmain->scenes.first; scene != NULL; scene = scene->id.next) { + BKE_sequencer_cache_cleanup(scene); + } +} +void BKE_sequencer_cache_cleanup(Scene *scene) { - if (!preprocess_cache) + SeqCache *cache = seq_cache_get_from_scene(scene); + if (!cache) { return; + } + + seq_cache_lock(scene); - BKE_sequencer_preprocessed_cache_cleanup(); + GHashIterator gh_iter; + BLI_ghashIterator_init(&gh_iter, cache->hash); + while (!BLI_ghashIterator_done(&gh_iter)) { + SeqCacheKey *key = BLI_ghashIterator_getKey(&gh_iter); - MEM_freeN(preprocess_cache); - preprocess_cache = NULL; + BLI_ghashIterator_step(&gh_iter); + BLI_ghash_remove(cache->hash, key, seq_cache_keyfree, seq_cache_valfree); + } + cache->last_key = NULL; + seq_cache_unlock(scene); } -ImBuf *BKE_sequencer_preprocessed_cache_get(const SeqRenderData *context, - Sequence *seq, - float cfra, - eSeqStripElemIBuf type) +void BKE_sequencer_cache_cleanup_sequence(Scene *scene, Sequence *seq) { - SeqPreprocessCacheElem *elem; + SeqCache *cache = seq_cache_get_from_scene(scene); + if (!cache) { + return; + } - if (!preprocess_cache) - return NULL; + seq_cache_lock(scene); + + GHashIterator gh_iter; + BLI_ghashIterator_init(&gh_iter, cache->hash); + while (!BLI_ghashIterator_done(&gh_iter)) { + SeqCacheKey *key = BLI_ghashIterator_getKey(&gh_iter); + BLI_ghashIterator_step(&gh_iter); + + if (key->seq == seq) { + /* Relink keys, so we don't end up with orphaned keys */ + if (key->link_next || key->link_prev) { + seq_cache_relink_keys(key->link_next, key->link_prev); + } + + BLI_ghash_remove(cache->hash, key, seq_cache_keyfree, seq_cache_valfree); + } + } + cache->last_key = NULL; + seq_cache_unlock(scene); +} - if (preprocess_cache->cfra != cfra) +struct ImBuf *BKE_sequencer_cache_get(const SeqRenderData *context, + Sequence *seq, + float cfra, + int type) +{ + Scene *scene = context->scene; + + if (!scene->ed->cache) { + BKE_sequencer_cache_create(scene); return NULL; + } - for (elem = preprocess_cache->elems.first; elem; elem = elem->next) { - if (elem->seq != seq) - continue; + seq_cache_lock(scene); + SeqCache *cache = seq_cache_get_from_scene(scene); + ImBuf *ibuf = NULL; - if (elem->type != type) - continue; + if (cache && seq) { + SeqCacheKey key; - if (seq_cmp_render_data(&elem->context, context) != 0) - continue; + key.seq = seq; + key.context = *context; + key.nfra = cfra - seq->start; + key.type = type; - IMB_refImBuf(elem->ibuf); - return elem->ibuf; + ibuf = seq_cache_get(cache, &key); } + seq_cache_unlock(scene); - return NULL; + return ibuf; +} + +bool BKE_sequencer_cache_put_if_possible( + const SeqRenderData *context, Sequence *seq, float cfra, int type, ImBuf *ibuf, float cost) +{ + Scene *scene = context->scene; + + if (seq_cache_recycle_item(scene)) { + BKE_sequencer_cache_put(context, seq, cfra, type, ibuf, cost); + return true; + } + else { + seq_cache_set_temp_cache_linked(scene, scene->ed->cache->last_key); + scene->ed->cache->last_key = NULL; + return false; + } } -void BKE_sequencer_preprocessed_cache_put( - const SeqRenderData *context, Sequence *seq, float cfra, eSeqStripElemIBuf type, ImBuf *ibuf) +void BKE_sequencer_cache_put( + const SeqRenderData *context, Sequence *seq, float cfra, int type, ImBuf *i, float cost) { - SeqPreprocessCacheElem *elem; + Scene *scene = context->scene; + short creator_id = 0; + + if (i == NULL || context->skip_cache || context->is_proxy_render || !seq) { + return; + } + + /* Prevent reinserting, it breaks cache key linking */ + ImBuf *test = BKE_sequencer_cache_get(context, seq, cfra, type); + if (test) { + IMB_freeImBuf(test); + return; + } - if (!preprocess_cache) { - preprocess_cache = MEM_callocN(sizeof(SeqPreprocessCache), "sequencer preprocessed cache"); + if (!scene->ed->cache) { + BKE_sequencer_cache_create(scene); + } + + seq_cache_lock(scene); + + SeqCache *cache = seq_cache_get_from_scene(scene); + int flag; + + if (seq->cache_flag & SEQ_CACHE_OVERRIDE) { + flag = seq->cache_flag; + flag |= scene->ed->cache_flag & SEQ_CACHE_STORE_FINAL_OUT; } else { - if (preprocess_cache->cfra != cfra) - BKE_sequencer_preprocessed_cache_cleanup(); + flag = scene->ed->cache_flag; + } + + if (cost > SEQ_CACHE_COST_MAX) { + cost = SEQ_CACHE_COST_MAX; } - elem = MEM_callocN(sizeof(SeqPreprocessCacheElem), "sequencer preprocessed cache element"); + SeqCacheKey *key; + key = BLI_mempool_alloc(cache->keys_pool); + key->cache_owner = cache; + key->seq = seq; + key->context = *context; + key->cfra = cfra; + key->nfra = cfra - seq->start; + key->type = type; + key->cost = cost; + key->cache_owner = cache; + key->link_prev = NULL; + key->link_next = NULL; + key->is_temp_cache = true; + key->creator_id = creator_id; + + /* Item stored for later use */ + if (flag & type) { + key->is_temp_cache = false; + key->link_prev = cache->last_key; + } - elem->seq = seq; - elem->type = type; - elem->context = *context; - elem->ibuf = ibuf; + SeqCacheKey *temp_last_key = cache->last_key; + seq_cache_put(cache, key, i); - preprocess_cache->cfra = cfra; + /* Restore pointer to previous item as this one will be freed when stack is rendered */ + if (key->is_temp_cache) { + cache->last_key = temp_last_key; + } + + /* Set last_key's reference to this key so we can look up chain backwards + * Item is already put in cache, so cache->last_key points to current key; + */ + if (flag & type && temp_last_key) { + temp_last_key->link_next = cache->last_key; + } - IMB_refImBuf(ibuf); + /* Reset linking */ + if (key->type == SEQ_CACHE_STORE_FINAL_OUT) { + cache->last_key = NULL; + } - BLI_addtail(&preprocess_cache->elems, elem); + seq_cache_unlock(scene); } -void BKE_sequencer_preprocessed_cache_cleanup_sequence(Sequence *seq) +void BKE_sequencer_cache_iterate( + struct Scene *scene, + void *userdata, + bool callback(void *userdata, struct Sequence *seq, int cfra, int cache_type, float cost)) { - SeqPreprocessCacheElem *elem, *elem_next; - - if (!preprocess_cache) + SeqCache *cache = seq_cache_get_from_scene(scene); + if (!cache) { return; + } - for (elem = preprocess_cache->elems.first; elem; elem = elem_next) { - elem_next = elem->next; + seq_cache_lock(scene); + GHashIterator gh_iter; + BLI_ghashIterator_init(&gh_iter, cache->hash); + bool interrupt = false; - if (elem->seq == seq) { - IMB_freeImBuf(elem->ibuf); + while (!BLI_ghashIterator_done(&gh_iter) && !interrupt) { + SeqCacheKey *key = BLI_ghashIterator_getKey(&gh_iter); + BLI_ghashIterator_step(&gh_iter); - BLI_freelinkN(&preprocess_cache->elems, elem); - } + interrupt = callback(userdata, key->seq, key->cfra, key->type, key->cost); } + + cache->last_key = NULL; + seq_cache_unlock(scene); } diff --git a/source/blender/blenkernel/intern/seqeffects.c b/source/blender/blenkernel/intern/seqeffects.c index fa596c875a8..b151bc7f092 100644 --- a/source/blender/blenkernel/intern/seqeffects.c +++ b/source/blender/blenkernel/intern/seqeffects.c @@ -76,11 +76,13 @@ static void slice_get_byte_buffers(const SeqRenderData *context, *rect1 = (unsigned char *)ibuf1->rect + offset; *rect_out = (unsigned char *)out->rect + offset; - if (ibuf2) + if (ibuf2) { *rect2 = (unsigned char *)ibuf2->rect + offset; + } - if (ibuf3) + if (ibuf3) { *rect3 = (unsigned char *)ibuf3->rect + offset; + } } static void slice_get_float_buffers(const SeqRenderData *context, @@ -99,11 +101,13 @@ static void slice_get_float_buffers(const SeqRenderData *context, *rect1 = ibuf1->rect_float + offset; *rect_out = out->rect_float + offset; - if (ibuf2) + if (ibuf2) { *rect2 = ibuf2->rect_float + offset; + } - if (ibuf3) + if (ibuf3) { *rect3 = ibuf3->rect_float + offset; + } } /*********************** Glow effect *************************/ @@ -219,10 +223,12 @@ static void do_alphaover_effect_byte(float facf0, fac = fac2; mfac = 1.0f - fac2 * rt1[3]; - if (fac <= 0.0f) + if (fac <= 0.0f) { *((unsigned int *)rt) = *((unsigned int *)cp2); - else if (mfac <= 0.0f) + } + else if (mfac <= 0.0f) { *((unsigned int *)rt) = *((unsigned int *)cp1); + } else { tempc[0] = fac * rt1[0] + mfac * rt2[0]; tempc[1] = fac * rt1[1] + mfac * rt2[1]; @@ -236,8 +242,9 @@ static void do_alphaover_effect_byte(float facf0, rt += 4; } - if (y == 0) + if (y == 0) { break; + } y--; x = xo; @@ -248,10 +255,12 @@ static void do_alphaover_effect_byte(float facf0, fac = fac4; mfac = 1.0f - (fac4 * rt1[3]); - if (fac <= 0.0f) + if (fac <= 0.0f) { *((unsigned int *)rt) = *((unsigned int *)cp2); - else if (mfac <= 0.0f) + } + else if (mfac <= 0.0f) { *((unsigned int *)rt) = *((unsigned int *)cp1); + } else { tempc[0] = fac * rt1[0] + mfac * rt2[0]; tempc[1] = fac * rt1[1] + mfac * rt2[1]; @@ -307,8 +316,9 @@ static void do_alphaover_effect_float( rt += 4; } - if (y == 0) + if (y == 0) { break; + } y--; x = xo; @@ -398,15 +408,18 @@ static void do_alphaunder_effect_byte(float facf0, /* this complex optimization is because the * 'skybuf' can be crossed in */ - if (rt2[3] <= 0.0f && fac2 >= 1.0f) + if (rt2[3] <= 0.0f && fac2 >= 1.0f) { *((unsigned int *)rt) = *((unsigned int *)cp1); - else if (rt2[3] >= 1.0f) + } + else if (rt2[3] >= 1.0f) { *((unsigned int *)rt) = *((unsigned int *)cp2); + } else { fac = (fac2 * (1.0f - rt2[3])); - if (fac <= 0) + if (fac <= 0) { *((unsigned int *)rt) = *((unsigned int *)cp2); + } else { tempc[0] = (fac * rt1[0] + rt2[0]); tempc[1] = (fac * rt1[1] + rt2[1]); @@ -421,8 +434,9 @@ static void do_alphaunder_effect_byte(float facf0, rt += 4; } - if (y == 0) + if (y == 0) { break; + } y--; x = xo; @@ -430,15 +444,18 @@ static void do_alphaunder_effect_byte(float facf0, straight_uchar_to_premul_float(rt1, cp1); straight_uchar_to_premul_float(rt2, cp2); - if (rt2[3] <= 0.0f && fac4 >= 1.0f) + if (rt2[3] <= 0.0f && fac4 >= 1.0f) { *((unsigned int *)rt) = *((unsigned int *)cp1); - else if (rt2[3] >= 1.0f) + } + else if (rt2[3] >= 1.0f) { *((unsigned int *)rt) = *((unsigned int *)cp2); + } else { fac = (fac4 * (1.0f - rt2[3])); - if (fac <= 0) + if (fac <= 0) { *((unsigned int *)rt) = *((unsigned int *)cp2); + } else { tempc[0] = (fac * rt1[0] + rt2[0]); tempc[1] = (fac * rt1[1] + rt2[1]); @@ -502,8 +519,9 @@ static void do_alphaunder_effect_float( rt += 4; } - if (y == 0) + if (y == 0) { break; + } y--; x = xo; @@ -601,8 +619,9 @@ static void do_cross_effect_byte(float facf0, rt += 4; } - if (y == 0) + if (y == 0) { break; + } y--; x = xo; @@ -649,8 +668,9 @@ static void do_cross_effect_float( rt += 4; } - if (y == 0) + if (y == 0) { break; + } y--; x = xo; @@ -763,12 +783,15 @@ static float gammaCorrect(float c) * may help solve that, by exchanging LUT size for the interpolation. * Negative colors are explicitly handled. */ - if (UNLIKELY(i < 0)) + if (UNLIKELY(i < 0)) { res = -powf(-c, valid_gamma); - else if (i >= RE_GAMMA_TABLE_SIZE) + } + else if (i >= RE_GAMMA_TABLE_SIZE) { res = powf(c, valid_gamma); - else + } + else { res = gamma_range_table[i] + ((c - color_domain_table[i]) * gamfactor_table[i]); + } return res; } @@ -782,12 +805,15 @@ static float invGammaCorrect(float c) i = floorf(c * inv_color_step); /* Negative colors are explicitly handled */ - if (UNLIKELY(i < 0)) + if (UNLIKELY(i < 0)) { res = -powf(-c, valid_inv_gamma); - else if (i >= RE_GAMMA_TABLE_SIZE) + } + else if (i >= RE_GAMMA_TABLE_SIZE) { res = powf(c, valid_inv_gamma); - else + } + else { res = inv_gamma_range_table[i] + ((c - color_domain_table[i]) * inv_gamfactor_table[i]); + } return res; } @@ -802,19 +828,23 @@ static void gamtabs(float gamma) val = a; val /= 65535.0f; - if (gamma == 2.0f) + if (gamma == 2.0f) { val = sqrtf(val); - else if (gamma != 1.0f) + } + else if (gamma != 1.0f) { val = powf(val, igamma); + } gamtab[a] = (65535.99f * val); } /* inverse gamtab1 : in byte, out short */ for (a = 1; a <= 256; a++) { - if (gamma == 2.0f) + if (gamma == 2.0f) { igamtab1[a - 1] = a * a - 1; - else if (gamma == 1.0f) + } + else if (gamma == 1.0f) { igamtab1[a - 1] = 256 * a - 1; + } else { val = a / 256.0f; igamtab1[a - 1] = (65535.0 * pow(val, gamma)) - 1; @@ -881,8 +911,9 @@ static void do_gammacross_effect_byte(float facf0, rt += 4; } - if (y == 0) + if (y == 0) { break; + } y--; x = xo; @@ -927,8 +958,9 @@ static void do_gammacross_effect_float( rt++; } - if (y == 0) + if (y == 0) { break; + } y--; x = xo * 4; @@ -1019,8 +1051,9 @@ static void do_add_effect_byte(float facf0, rt += 4; } - if (y == 0) + if (y == 0) { break; + } y--; x = xo; @@ -1067,8 +1100,9 @@ static void do_add_effect_float( rt += 4; } - if (y == 0) + if (y == 0) { break; + } y--; x = xo; @@ -1151,8 +1185,9 @@ static void do_sub_effect_byte(float facf0, rt += 4; } - if (y == 0) + if (y == 0) { break; + } y--; x = xo; @@ -1200,8 +1235,9 @@ static void do_sub_effect_float( rt += 4; } - if (y == 0) + if (y == 0) { break; + } y--; x = xo; @@ -1279,10 +1315,12 @@ static void do_drop_effect_byte(float facf0, rt1 = rect1i; out = outi; for (y = 0; y < height - yoff; y++) { - if (field) + if (field) { fac = fac1; - else + } + else { fac = fac2; + } field = !field; memcpy(out, rt1, sizeof(*out) * xoff * 4); @@ -1326,10 +1364,12 @@ static void do_drop_effect_float( rt1 = rect1i; out = outi; for (y = 0; y < height - yoff; y++) { - if (field) + if (field) { fac = fac1; - else + } + else { fac = fac2; + } field = !field; memcpy(out, rt1, sizeof(*out) * xoff * 4); @@ -1395,8 +1435,9 @@ static void do_mul_effect_byte(float facf0, rt += 4; } - if (y == 0) + if (y == 0) { break; + } y--; x = xo; @@ -1446,8 +1487,9 @@ static void do_mul_effect_float( rt += 4; } - if (y == 0) + if (y == 0) { break; + } y--; x = xo; @@ -1853,19 +1895,24 @@ static float in_band(float width, float dist, int side, int dir) { float alpha; - if (width == 0) + if (width == 0) { return (float)side; + } - if (width < dist) + if (width < dist) { return (float)side; + } - if (side == 1) + if (side == 1) { alpha = (dist + 0.5f * width) / (width); - else + } + else { alpha = (0.5f * width - dist) / (width); + } - if (dir == 0) + if (dir == 0) { alpha = 1 - alpha; + } return alpha; } @@ -1884,8 +1931,9 @@ static float check_zone(WipeZone *wipezone, int x, int y, Sequence *seq, float f WipeVars *wipe = (WipeVars *)seq->effectdata; int width; - if (wipezone->flip) + if (wipezone->flip) { x = xo - x; + } angle = wipezone->angle; if (wipe->forward) { @@ -1920,22 +1968,27 @@ static float check_zone(WipeZone *wipezone, int x, int y, Sequence *seq, float f } if (wipe->forward) { - if (b1 < b2) + if (b1 < b2) { output = in_band(width, hyp, 1, 1); - else + } + else { output = in_band(width, hyp, 0, 1); + } } else { - if (b1 < b2) + if (b1 < b2) { output = in_band(width, hyp, 0, 1); - else + } + else { output = in_band(width, hyp, 1, 1); + } } break; case DO_DOUBLE_WIPE: - if (!wipe->forward) + if (!wipe->forward) { facf0 = 1.0f - facf0; /* Go the other direction */ + } width = wipezone->width; /* calculate the blur width */ hwidth = width * 0.5f; @@ -1966,15 +2019,19 @@ static float check_zone(WipeZone *wipezone, int x, int y, Sequence *seq, float f output = in_band(hwidth, hyp2, 0, 1); } else { - if (hyp < hwidth && hyp2 > hwidth) + if (hyp < hwidth && hyp2 > hwidth) { output = in_band(hwidth, hyp, 1, 1); - else if (hyp > hwidth && hyp2 < hwidth) + } + else if (hyp > hwidth && hyp2 < hwidth) { output = in_band(hwidth, hyp2, 1, 1); - else + } + else { output = in_band(hwidth, hyp2, 1, 1) * in_band(hwidth, hyp, 1, 1); + } } - if (!wipe->forward) + if (!wipe->forward) { output = 1 - output; + } break; case DO_CLOCK_WIPE: /* @@ -1995,12 +2052,15 @@ static float check_zone(WipeZone *wipezone, int x, int y, Sequence *seq, float f y = y - halfy; temp2 = asin(abs(y) / hypot(x, y)); - if (x <= 0 && y >= 0) + if (x <= 0 && y >= 0) { temp2 = (float)M_PI - temp2; - else if (x <= 0 && y <= 0) + } + else if (x <= 0 && y <= 0) { temp2 += (float)M_PI; - else if (x >= 0 && y <= 0) + } + else if (x >= 0 && y <= 0) { temp2 = 2.0f * (float)M_PI - temp2; + } if (wipe->forward) { temp3 = temp1 - (widthf * 0.5f) * facf0; @@ -2010,32 +2070,43 @@ static float check_zone(WipeZone *wipezone, int x, int y, Sequence *seq, float f temp3 = temp1 - (widthf * 0.5f) * (1 - facf0); temp4 = temp1 + (widthf * 0.5f) * facf0; } - if (temp3 < 0) + if (temp3 < 0) { temp3 = 0; - if (temp4 > 2.0f * (float)M_PI) + } + if (temp4 > 2.0f * (float)M_PI) { temp4 = 2.0f * (float)M_PI; + } - if (temp2 < temp3) + if (temp2 < temp3) { output = 0; - else if (temp2 > temp4) + } + else if (temp2 > temp4) { output = 1; - else + } + else { output = (temp2 - temp3) / (temp4 - temp3); - if (x == 0 && y == 0) + } + if (x == 0 && y == 0) { output = 1; - if (output != output) + } + if (output != output) { output = 1; - if (wipe->forward) + } + if (wipe->forward) { output = 1 - output; + } break; case DO_IRIS_WIPE: - if (xo > yo) + if (xo > yo) { yo = xo; - else + } + else { xo = yo; + } - if (!wipe->forward) + if (!wipe->forward) { facf0 = 1 - facf0; + } width = wipezone->width; hwidth = width * 0.5f; @@ -2044,27 +2115,33 @@ static float check_zone(WipeZone *wipezone, int x, int y, Sequence *seq, float f pointdist = hypotf(temp1, temp1); temp2 = hypotf(halfx - x, halfy - y); - if (temp2 > pointdist) + if (temp2 > pointdist) { output = in_band(hwidth, fabsf(temp2 - pointdist), 0, 1); - else + } + else { output = in_band(hwidth, fabsf(temp2 - pointdist), 1, 1); + } - if (!wipe->forward) + if (!wipe->forward) { output = 1 - output; + } break; } - if (output < 0) + if (output < 0) { output = 0; - else if (output > 1) + } + else if (output > 1) { output = 1; + } return output; } static void init_wipe_effect(Sequence *seq) { - if (seq->effectdata) + if (seq->effectdata) { MEM_freeN(seq->effectdata); + } seq->effectdata = MEM_callocN(sizeof(WipeVars), "wipevars"); } @@ -2076,8 +2153,9 @@ static int num_inputs_wipe(void) static void free_wipe_effect(Sequence *seq, const bool UNUSED(do_id_user)) { - if (seq->effectdata) + if (seq->effectdata) { MEM_freeN(seq->effectdata); + } seq->effectdata = NULL; } @@ -2265,8 +2343,9 @@ static void init_transform_effect(Sequence *seq) { TransformVars *transform; - if (seq->effectdata) + if (seq->effectdata) { MEM_freeN(seq->effectdata); + } seq->effectdata = MEM_callocN(sizeof(TransformVars), "transformvars"); @@ -2292,8 +2371,9 @@ static int num_inputs_transform(void) static void free_transform_effect(Sequence *seq, const bool UNUSED(do_id_user)) { - if (seq->effectdata) + if (seq->effectdata) { MEM_freeN(seq->effectdata); + } seq->effectdata = NULL; } @@ -2435,13 +2515,15 @@ static void RVBlurBitmap2_float(float *map, int width, int height, float blur, i float fval, k, curColor[4], curColor2[4], weight = 0; /* If we're not really blurring, bail out */ - if (blur <= 0) + if (blur <= 0) { return; + } /* Allocate memory for the tempmap and the blur filter matrix */ temp = MEM_mallocN((width * height * 4 * sizeof(float)), "blurbitmaptemp"); - if (!temp) + if (!temp) { return; + } /* Allocate memory for the filter elements */ halfWidth = ((quality + 1) * blur); @@ -2467,11 +2549,13 @@ static void RVBlurBitmap2_float(float *map, int width, int height, float blur, i /* Normalize the array */ fval = 0; - for (ix = 0; ix < halfWidth * 2; ix++) + for (ix = 0; ix < halfWidth * 2; ix++) { fval += filter[ix]; + } - for (ix = 0; ix < halfWidth * 2; ix++) + for (ix = 0; ix < halfWidth * 2; ix++) { filter[ix] /= fval; + } /* Blur the rows */ for (y = 0; y < height; y++) { @@ -2613,8 +2697,9 @@ static void init_glow_effect(Sequence *seq) { GlowVars *glow; - if (seq->effectdata) + if (seq->effectdata) { MEM_freeN(seq->effectdata); + } seq->effectdata = MEM_callocN(sizeof(GlowVars), "glowvars"); @@ -2634,8 +2719,9 @@ static int num_inputs_glow(void) static void free_glow_effect(Sequence *seq, const bool UNUSED(do_id_user)) { - if (seq->effectdata) + if (seq->effectdata) { MEM_freeN(seq->effectdata); + } seq->effectdata = NULL; } @@ -2667,8 +2753,9 @@ static void do_glow_effect_byte(Sequence *seq, RVIsolateHighlights_float( inbuf, outbuf, x, y, glow->fMini * 3.0f, glow->fBoost * facf0, glow->fClamp); RVBlurBitmap2_float(outbuf, x, y, glow->dDist * (render_size / 100.0f), glow->dQuality); - if (!glow->bNoComp) + if (!glow->bNoComp) { RVAddBitmaps_float(inbuf, outbuf, outbuf, x, y); + } IMB_buffer_float_unpremultiply(outbuf, x, y); IMB_buffer_byte_from_float( @@ -2695,8 +2782,9 @@ static void do_glow_effect_float(Sequence *seq, RVIsolateHighlights_float( inbuf, outbuf, x, y, glow->fMini * 3.0f, glow->fBoost * facf0, glow->fClamp); RVBlurBitmap2_float(outbuf, x, y, glow->dDist * (render_size / 100.0f), glow->dQuality); - if (!glow->bNoComp) + if (!glow->bNoComp) { RVAddBitmaps_float(inbuf, outbuf, outbuf, x, y); + } } static ImBuf *do_glow_effect(const SeqRenderData *context, @@ -2744,8 +2832,9 @@ static void init_solid_color(Sequence *seq) { SolidColorVars *cv; - if (seq->effectdata) + if (seq->effectdata) { MEM_freeN(seq->effectdata); + } seq->effectdata = MEM_callocN(sizeof(SolidColorVars), "solidcolor"); @@ -2760,8 +2849,9 @@ static int num_inputs_color(void) static void free_solid_color(Sequence *seq, const bool UNUSED(do_id_user)) { - if (seq->effectdata) + if (seq->effectdata) { MEM_freeN(seq->effectdata); + } seq->effectdata = NULL; } @@ -3003,8 +3093,9 @@ static void init_speed_effect(Sequence *seq) { SpeedControlVars *v; - if (seq->effectdata) + if (seq->effectdata) { MEM_freeN(seq->effectdata); + } seq->effectdata = MEM_callocN(sizeof(SpeedControlVars), "speedcontrolvars"); @@ -3031,10 +3122,12 @@ static int num_inputs_speed(void) static void free_speed_effect(Sequence *seq, const bool UNUSED(do_id_user)) { SpeedControlVars *v = (SpeedControlVars *)seq->effectdata; - if (v->frameMap) + if (v->frameMap) { MEM_freeN(v->frameMap); - if (seq->effectdata) + } + if (seq->effectdata) { MEM_freeN(seq->effectdata); + } seq->effectdata = NULL; } @@ -3099,8 +3192,9 @@ void BKE_sequence_effect_speed_rebuild_map(Scene *scene, Sequence *seq, bool for fcu = id_data_find_fcurve(&scene->id, seq, &RNA_Sequence, "speed_factor", 0, NULL); if (!v->frameMap || v->length != seq->len) { - if (v->frameMap) + if (v->frameMap) { MEM_freeN(v->frameMap); + } v->length = seq->len; @@ -3260,8 +3354,9 @@ static void do_overdrop_effect(const SeqRenderData *context, static void init_gaussian_blur_effect(Sequence *seq) { - if (seq->effectdata) + if (seq->effectdata) { MEM_freeN(seq->effectdata); + } seq->effectdata = MEM_callocN(sizeof(WipeVars), "wipevars"); } @@ -3273,8 +3368,9 @@ static int num_inputs_gaussian_blur(void) static void free_gaussian_blur_effect(Sequence *seq, const bool UNUSED(do_id_user)) { - if (seq->effectdata) + if (seq->effectdata) { MEM_freeN(seq->effectdata); + } seq->effectdata = NULL; } @@ -3313,8 +3409,9 @@ static float *make_gaussian_blur_kernel(float rad, int size) } sum = 1.0f / sum; - for (i = 0; i < n; i++) + for (i = 0; i < n; i++) { gausstab[i] *= sum; + } return gausstab; } @@ -3680,8 +3777,9 @@ static void init_text_effect(Sequence *seq) { TextVars *data; - if (seq->effectdata) + if (seq->effectdata) { MEM_freeN(seq->effectdata); + } data = seq->effectdata = MEM_callocN(sizeof(TextVars), "textvars"); data->text_font = NULL; @@ -3914,8 +4012,9 @@ static void copy_effect_default(Sequence *dst, Sequence *src, const int UNUSED(f static void free_effect_default(Sequence *seq, const bool UNUSED(do_id_user)) { - if (seq->effectdata) + if (seq->effectdata) { MEM_freeN(seq->effectdata); + } seq->effectdata = NULL; } diff --git a/source/blender/blenkernel/intern/seqmodifier.c b/source/blender/blenkernel/intern/seqmodifier.c index 29a5d556aef..cc44cd66f23 100644 --- a/source/blender/blenkernel/intern/seqmodifier.c +++ b/source/blender/blenkernel/intern/seqmodifier.c @@ -107,18 +107,22 @@ static void modifier_init_handle(void *handle_v, int start_line, int tot_line, v handle->apply_callback = init_data->apply_callback; handle->user_data = init_data->user_data; - if (ibuf->rect) + if (ibuf->rect) { handle->rect = (unsigned char *)ibuf->rect + offset; + } - if (ibuf->rect_float) + if (ibuf->rect_float) { handle->rect_float = ibuf->rect_float + offset; + } if (mask) { - if (mask->rect) + if (mask->rect) { handle->mask_rect = (unsigned char *)mask->rect + offset; + } - if (mask->rect_float) + if (mask->rect_float) { handle->mask_rect_float = mask->rect_float + offset; + } } else { handle->mask_rect = NULL; @@ -450,10 +454,12 @@ static void hue_correct_apply_threaded(int width, float pixel[3], result[3], mask[3] = {1.0f, 1.0f, 1.0f}; float hsv[3], f; - if (rect_float) + if (rect_float) { copy_v3_v3(pixel, rect_float + pixel_index); - else + } + else { rgb_uchar_to_float(pixel, rect + pixel_index); + } rgb_to_hsv(pixel[0], pixel[1], pixel[2], hsv, hsv + 1, hsv + 2); @@ -475,19 +481,23 @@ static void hue_correct_apply_threaded(int width, /* convert back to rgb */ hsv_to_rgb(hsv[0], hsv[1], hsv[2], result, result + 1, result + 2); - if (mask_rect_float) + if (mask_rect_float) { copy_v3_v3(mask, mask_rect_float + pixel_index); - else if (mask_rect) + } + else if (mask_rect) { rgb_uchar_to_float(mask, mask_rect + pixel_index); + } result[0] = pixel[0] * (1.0f - mask[0]) + result[0] * mask[0]; result[1] = pixel[1] * (1.0f - mask[1]) + result[1] * mask[1]; result[2] = pixel[2] * (1.0f - mask[2]) + result[2] * mask[2]; - if (rect_float) + if (rect_float) { copy_v3_v3(rect_float + pixel_index, result); - else + } + else { rgb_float_to_uchar(rect + pixel_index, result); + } } } } @@ -584,8 +594,9 @@ static void brightcontrast_apply_threaded(int width, pixel[c] = pixel[c] * (1.0f - m[c]) + v * m[c]; } - else + else { pixel[c] = v; + } } } } @@ -625,11 +636,13 @@ static void maskmodifier_apply_threaded(int width, { int x, y; - if (rect && !mask_rect) + if (rect && !mask_rect) { return; + } - if (rect_float && !mask_rect_float) + if (rect_float && !mask_rect_float) { return; + } for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { @@ -655,8 +668,9 @@ static void maskmodifier_apply_threaded(int width, /* float buffers are premultiplied, so need to premul color * as well to make it easy to alpha-over masted strip. */ - for (c = 0; c < 4; c++) + for (c = 0; c < 4; c++) { pixel[c] = pixel[c] * mask; + } } } } @@ -928,25 +942,29 @@ SequenceModifierData *BKE_sequence_modifier_new(Sequence *seq, const char *name, smd->type = type; smd->flag |= SEQUENCE_MODIFIER_EXPANDED; - if (!name || !name[0]) + if (!name || !name[0]) { BLI_strncpy(smd->name, smti->name, sizeof(smd->name)); - else + } + else { BLI_strncpy(smd->name, name, sizeof(smd->name)); + } BLI_addtail(&seq->modifiers, smd); BKE_sequence_modifier_unique_name(seq, smd); - if (smti->init_data) + if (smti->init_data) { smti->init_data(smd); + } return smd; } bool BKE_sequence_modifier_remove(Sequence *seq, SequenceModifierData *smd) { - if (BLI_findindex(&seq->modifiers, smd) == -1) + if (BLI_findindex(&seq->modifiers, smd) == -1) { return false; + } BLI_remlink(&seq->modifiers, smd); BKE_sequence_modifier_free(smd); @@ -1011,12 +1029,14 @@ ImBuf *BKE_sequence_modifier_apply_stack(const SeqRenderData *context, const SequenceModifierTypeInfo *smti = BKE_sequence_modifier_type_info_get(smd->type); /* could happen if modifier is being removed or not exists in current version of blender */ - if (!smti) + if (!smti) { continue; + } /* modifier is muted, do nothing */ - if (smd->flag & SEQUENCE_MODIFIER_MUTE) + if (smd->flag & SEQUENCE_MODIFIER_MUTE) { continue; + } if (smti->apply) { int frame_offset; @@ -1029,13 +1049,15 @@ ImBuf *BKE_sequence_modifier_apply_stack(const SeqRenderData *context, ImBuf *mask = modifier_mask_get(smd, context, cfra, frame_offset, ibuf->rect_float != NULL); - if (processed_ibuf == ibuf) + if (processed_ibuf == ibuf) { processed_ibuf = IMB_dupImBuf(ibuf); + } smti->apply(smd, processed_ibuf, mask); - if (mask) + if (mask) { IMB_freeImBuf(mask); + } } } @@ -1056,8 +1078,9 @@ void BKE_sequence_modifier_list_copy(Sequence *seqn, Sequence *seq) smdn = MEM_dupallocN(smd); - if (smti && smti->copy_data) + if (smti && smti->copy_data) { smti->copy_data(smdn, smd); + } smdn->next = smdn->prev = NULL; BLI_addtail(&seqn->modifiers, smdn); diff --git a/source/blender/blenkernel/intern/sequencer.c b/source/blender/blenkernel/intern/sequencer.c index 4af06606ef0..b1a32552878 100644 --- a/source/blender/blenkernel/intern/sequencer.c +++ b/source/blender/blenkernel/intern/sequencer.c @@ -27,7 +27,7 @@ #include <stddef.h> #include <stdlib.h> #include <string.h> -#include <math.h> +#include <time.h> #include "MEM_guardedalloc.h" @@ -121,12 +121,23 @@ SequencerDrawView sequencer_view3d_cb = NULL; /* NULL in background mode */ #if 0 /* unused function */ static void printf_strip(Sequence *seq) { - fprintf(stderr, "name: '%s', len:%d, start:%d, (startofs:%d, endofs:%d), " + fprintf(stderr, + "name: '%s', len:%d, start:%d, (startofs:%d, endofs:%d), " "(startstill:%d, endstill:%d), machine:%d, (startdisp:%d, enddisp:%d)\n", - seq->name, seq->len, seq->start, seq->startofs, seq->endofs, seq->startstill, seq->endstill, seq->machine, - seq->startdisp, seq->enddisp); - - fprintf(stderr, "\tseq_tx_set_final_left: %d %d\n\n", seq_tx_get_final_left(seq, 0), + seq->name, + seq->len, + seq->start, + seq->startofs, + seq->endofs, + seq->startstill, + seq->endstill, + seq->machine, + seq->startdisp, + seq->enddisp); + + fprintf(stderr, + "\tseq_tx_set_final_left: %d %d\n\n", + seq_tx_get_final_left(seq, 0), seq_tx_get_final_right(seq, 0)); } #endif @@ -142,8 +153,9 @@ int BKE_sequencer_base_recursive_apply(ListBase *seqbase, { Sequence *iseq; for (iseq = seqbase->first; iseq; iseq = iseq->next) { - if (BKE_sequencer_recursive_apply(iseq, apply_func, arg) == -1) + if (BKE_sequencer_recursive_apply(iseq, apply_func, arg) == -1) { return -1; /* bail out */ + } } return 1; } @@ -152,11 +164,13 @@ int BKE_sequencer_recursive_apply(Sequence *seq, int (*apply_func)(Sequence *, v { int ret = apply_func(seq, arg); - if (ret == -1) + if (ret == -1) { return -1; /* bail out */ + } - if (ret && seq->seqbase.first) + if (ret && seq->seqbase.first) { ret = BKE_sequencer_base_recursive_apply(&seq->seqbase, apply_func, arg); + } return ret; } @@ -176,8 +190,9 @@ static void free_proxy_seq(Sequence *seq) static void seq_free_strip(Strip *strip) { strip->us--; - if (strip->us > 0) + if (strip->us > 0) { return; + } if (strip->us < 0) { printf("error: negative users in strip\n"); return; @@ -210,8 +225,9 @@ static void BKE_sequence_free_ex(Scene *scene, const bool do_cache, const bool do_id_user) { - if (seq->strip) + if (seq->strip) { seq_free_strip(seq->strip); + } BKE_sequence_free_anim(seq); @@ -234,11 +250,13 @@ static void BKE_sequence_free_ex(Scene *scene, if (scene) { Editing *ed = scene->ed; - if (ed->act_seq == seq) + if (ed->act_seq == seq) { ed->act_seq = NULL; + } - if (seq->scene_sound && ELEM(seq->type, SEQ_TYPE_SOUND_RAM, SEQ_TYPE_SCENE)) + if (seq->scene_sound && ELEM(seq->type, SEQ_TYPE_SOUND_RAM, SEQ_TYPE_SCENE)) { BKE_sound_remove_scene_sound(scene, seq->scene_sound); + } seq_free_animdata(scene, seq); } @@ -255,7 +273,8 @@ static void BKE_sequence_free_ex(Scene *scene, * also invalidate cache for all dependent sequences * * be _very_ careful here, invalidating cache loops over the scene sequences and - * assumes the listbase is valid for all strips, this may not be the case if lists are being freed. + * assumes the listbase is valid for all strips, + * this may not be the case if lists are being freed. * this is optional BKE_sequence_invalidate_cache */ if (do_cache) { @@ -445,6 +464,11 @@ Editing *BKE_sequencer_editing_ensure(Scene *scene) ed = scene->ed = MEM_callocN(sizeof(Editing), "addseq"); ed->seqbasep = &ed->seqbase; + ed->cache = NULL; + ed->cache_flag = SEQ_CACHE_STORE_FINAL_OUT; + ed->cache_flag |= SEQ_CACHE_VIEW_FINAL_OUT; + ed->cache_flag |= SEQ_CACHE_VIEW_ENABLE; + ed->recycle_max_cost = 10.0f; } return scene->ed; @@ -455,11 +479,11 @@ void BKE_sequencer_editing_free(Scene *scene, const bool do_id_user) Editing *ed = scene->ed; Sequence *seq; - if (ed == NULL) + if (ed == NULL) { return; + } - /* this may not be the active scene!, could be smarter about this */ - BKE_sequencer_cache_cleanup(); + BKE_sequencer_cache_destruct(scene); SEQ_BEGIN (ed, seq) { /* handle cache freeing above */ @@ -561,8 +585,9 @@ void BKE_sequencer_imbuf_from_sequencer_space(Scene *scene, ImBuf *ibuf) const char *to_colorspace = IMB_colormanagement_role_colorspace_name_get( COLOR_ROLE_SCENE_LINEAR); - if (!ibuf->rect_float) + if (!ibuf->rect_float) { return; + } if (to_colorspace && to_colorspace[0] != '\0') { IMB_colormanagement_transform_threaded( @@ -629,8 +654,9 @@ static void seq_count(ListBase *seqbase, int *tot) for (seq = seqbase->first; seq; seq = seq->next) { (*tot)++; - if (seq->seqbase.first) + if (seq->seqbase.first) { seq_count(&seq->seqbase, tot); + } } } @@ -641,8 +667,9 @@ static void seq_build_array(ListBase *seqbase, Sequence ***array, int depth) for (seq = seqbase->first; seq; seq = seq->next) { seq->depth = depth; - if (seq->seqbase.first) + if (seq->seqbase.first) { seq_build_array(&seq->seqbase, array, depth + 1); + } **array = seq; (*array)++; @@ -656,22 +683,28 @@ static void seq_array(Editing *ed, Sequence ***seqarray, int *tot, bool use_poin *seqarray = NULL; *tot = 0; - if (ed == NULL) + if (ed == NULL) { return; + } - if (use_pointer) + if (use_pointer) { seq_count(ed->seqbasep, tot); - else + } + else { seq_count(&ed->seqbase, tot); + } - if (*tot == 0) + if (*tot == 0) { return; + } *seqarray = array = MEM_mallocN(sizeof(Sequence *) * (*tot), "SeqArray"); - if (use_pointer) + if (use_pointer) { seq_build_array(ed->seqbasep, &array, 0); - else + } + else { seq_build_array(&ed->seqbase, &array, 0); + } } void BKE_sequence_iterator_begin(Editing *ed, SeqIterator *iter, bool use_pointer) @@ -688,16 +721,19 @@ void BKE_sequence_iterator_begin(Editing *ed, SeqIterator *iter, bool use_pointe void BKE_sequence_iterator_next(SeqIterator *iter) { - if (++iter->cur < iter->tot) + if (++iter->cur < iter->tot) { iter->seq = iter->array[iter->cur]; - else + } + else { iter->valid = 0; + } } void BKE_sequence_iterator_end(SeqIterator *iter) { - if (iter->array) + if (iter->array) { MEM_freeN(iter->array); + } iter->valid = 0; } @@ -730,11 +766,13 @@ static void seq_update_sound_bounds_recursive_rec(Scene *scene, if (seq->scene_sound) { int startofs = seq->startofs; int endofs = seq->endofs; - if (seq->startofs + seq->start < start) + if (seq->startofs + seq->start < start) { startofs = start - seq->start; + } - if (seq->start + seq->len - seq->endofs > end) + if (seq->start + seq->len - seq->endofs > end) { endofs = seq->start + seq->len - end; + } BKE_sound_move_scene_sound(scene, seq->scene_sound, @@ -754,10 +792,12 @@ static void seq_update_sound_bounds_recursive(Scene *scene, Sequence *metaseq) void BKE_sequence_calc_disp(Scene *scene, Sequence *seq) { - if (seq->startofs && seq->startstill) + if (seq->startofs && seq->startstill) { seq->startstill = 0; - if (seq->endofs && seq->endstill) + } + if (seq->endofs && seq->endstill) { seq->endstill = 0; + } seq->startdisp = seq->start + seq->startofs - seq->startstill; seq->enddisp = seq->start + seq->len - seq->endofs + seq->endstill; @@ -786,8 +826,9 @@ void BKE_sequence_calc(Scene *scene, Sequence *seq) /* check all metas recursively */ seqm = seq->seqbase.first; while (seqm) { - if (seqm->seqbase.first) + if (seqm->seqbase.first) { BKE_sequence_calc(scene, seqm); + } seqm = seqm->next; } @@ -795,10 +836,12 @@ void BKE_sequence_calc(Scene *scene, Sequence *seq) if (seq->type & SEQ_TYPE_EFFECT) { /* pointers */ - if (seq->seq2 == NULL) + if (seq->seq2 == NULL) { seq->seq2 = seq->seq1; - if (seq->seq3 == NULL) + } + if (seq->seq3 == NULL) { seq->seq3 = seq->seq1; + } /* effecten go from seq1 -> seq2: test */ @@ -840,10 +883,12 @@ void BKE_sequence_calc(Scene *scene, Sequence *seq) min = MAXFRAME * 2; max = -MAXFRAME * 2; while (seqm) { - if (seqm->startdisp < min) + if (seqm->startdisp < min) { min = seqm->startdisp; - if (seqm->enddisp > max) + } + if (seqm->enddisp > max) { max = seqm->enddisp; + } seqm = seqm->next; } seq->start = min + seq->anim_startofs; @@ -982,8 +1027,9 @@ void BKE_sequence_reload_new_file(Scene *scene, Sequence *seq, const bool lock_r break; } case SEQ_TYPE_MOVIECLIP: - if (seq->clip == NULL) + if (seq->clip == NULL) { return; + } seq->len = BKE_movieclip_get_duration(seq->clip); @@ -994,8 +1040,9 @@ void BKE_sequence_reload_new_file(Scene *scene, Sequence *seq, const bool lock_r } break; case SEQ_TYPE_MASK: - if (seq->mask == NULL) + if (seq->mask == NULL) { return; + } seq->len = BKE_mask_get_duration(seq->mask); seq->len -= seq->anim_startofs; seq->len -= seq->anim_endofs; @@ -1005,8 +1052,9 @@ void BKE_sequence_reload_new_file(Scene *scene, Sequence *seq, const bool lock_r break; case SEQ_TYPE_SOUND_RAM: #ifdef WITH_AUDASPACE - if (!seq->sound) + if (!seq->sound) { return; + } seq->len = ceil((double)AUD_getInfo(seq->sound->playback_handle).length * FPS); seq->len -= seq->anim_startofs; seq->len -= seq->anim_endofs; @@ -1046,8 +1094,9 @@ void BKE_sequencer_sort(Scene *scene) Editing *ed = BKE_sequencer_editing_get(scene, false); Sequence *seq, *seqt; - if (ed == NULL) + if (ed == NULL) { return; + } BLI_listbase_clear(&seqbase); BLI_listbase_clear(&effbase); @@ -1063,8 +1112,9 @@ void BKE_sequencer_sort(Scene *scene) } seqt = seqt->next; } - if (seqt == NULL) + if (seqt == NULL) { BLI_addtail(&effbase, seq); + } } else { seqt = seqbase.first; @@ -1075,8 +1125,9 @@ void BKE_sequencer_sort(Scene *scene) } seqt = seqt->next; } - if (seqt == NULL) + if (seqt == NULL) { BLI_addtail(&seqbase, seq); + } } } @@ -1095,8 +1146,9 @@ int BKE_sequencer_cmp_time_startdisp(const void *a, const void *b) static int clear_scene_in_allseqs_cb(Sequence *seq, void *arg_pt) { - if (seq->scene == (Scene *)arg_pt) + if (seq->scene == (Scene *)arg_pt) { seq->scene = NULL; + } return 1; } @@ -1140,8 +1192,9 @@ static void seqbase_unique_name(ListBase *seqbasep, SeqUniqueInfo *sui) static int seqbase_unique_name_recursive_cb(Sequence *seq, void *arg_pt) { - if (seq->seqbase.first) + if (seq->seqbase.first) { seqbase_unique_name(&seq->seqbase, (SeqUniqueInfo *)arg_pt); + } return 1; } @@ -1161,8 +1214,9 @@ void BKE_sequence_base_unique_name_recursive(ListBase *seqbasep, Sequence *seq) *dot = '\0'; dot++; - if (*dot) + if (*dot) { sui.count = atoi(dot) + 1; + } } while (sui.match) { @@ -1258,7 +1312,7 @@ ListBase *BKE_sequence_seqbase_get(Sequence *seq, int *r_offset) break; } case SEQ_TYPE_SCENE: { - if (seq->flag & SEQ_SCENE_STRIPS) { + if (seq->flag & SEQ_SCENE_STRIPS && seq->scene) { Editing *ed = BKE_sequencer_editing_get(seq->scene, false); if (ed) { seqbase = &ed->seqbase; @@ -1349,24 +1403,31 @@ static float give_stripelem_index(Sequence *seq, float cfra) if (seq->flag & SEQ_REVERSE_FRAMES) { /*reverse frame in this sequence */ - if (cfra <= sta) + if (cfra <= sta) { nr = end - sta; - else if (cfra >= end) + } + else if (cfra >= end) { nr = 0; - else + } + else { nr = end - cfra; + } } else { - if (cfra <= sta) + if (cfra <= sta) { nr = 0; - else if (cfra >= end) + } + else if (cfra >= end) { nr = end - sta; - else + } + else { nr = cfra - sta; + } } - if (seq->strobe < 1.0f) + if (seq->strobe < 1.0f) { seq->strobe = 1.0f; + } if (seq->strobe > 1.0f) { nr -= fmodf((double)nr, (double)seq->strobe); @@ -1386,8 +1447,9 @@ StripElem *BKE_sequencer_give_stripelem(Sequence *seq, int cfra) int nr = (int)give_stripelem_index(seq, cfra); - if (nr == -1 || se == NULL) + if (nr == -1 || se == NULL) { return NULL; + } se += nr + seq->anim_startofs; } @@ -1454,8 +1516,9 @@ int BKE_sequencer_evaluate_frame(Scene *scene, int cfra) Editing *ed = BKE_sequencer_editing_get(scene, false); Sequence *seq_arr[MAXSEQ + 1]; - if (ed == NULL) + if (ed == NULL) { return 0; + } return evaluate_seq_frame_gen(seq_arr, ed->seqbasep, cfra, 0); } @@ -1609,10 +1672,12 @@ static void seq_open_anim_file(Scene *scene, Sequence *seq, bool openfile) if (use_proxy) { if (ed->proxy_storage == SEQ_EDIT_PROXY_DIR_STORAGE) { - if (ed->proxy_dir[0] == 0) + if (ed->proxy_dir[0] == 0) { BLI_strncpy(dir, "//BL_proxy", sizeof(dir)); - else + } + else { BLI_strncpy(dir, ed->proxy_dir, sizeof(dir)); + } } else { BLI_strncpy(dir, seq->strip->proxy->dir, sizeof(dir)); @@ -1733,10 +1798,12 @@ static bool seq_proxy_get_fname( if (ed->proxy_storage == SEQ_EDIT_PROXY_DIR_STORAGE) { char fname[FILE_MAXFILE]; - if (ed->proxy_dir[0] == 0) + if (ed->proxy_dir[0] == 0) { BLI_strncpy(dir, "//BL_proxy", sizeof(dir)); - else + } + else { BLI_strncpy(dir, ed->proxy_dir, sizeof(dir)); + } if (sanim && sanim->anim) { IMB_anim_get_fname(sanim->anim, fname, FILE_MAXFILE); @@ -1766,17 +1833,20 @@ static bool seq_proxy_get_fname( BLI_path_append(dir, sizeof(dir), fname); } else if (seq->type == SEQ_TYPE_IMAGE) { - if (proxy->storage & SEQ_STORAGE_PROXY_CUSTOM_DIR) + if (proxy->storage & SEQ_STORAGE_PROXY_CUSTOM_DIR) { BLI_strncpy(dir, seq->strip->proxy->dir, sizeof(dir)); - else + } + else { BLI_snprintf(dir, PROXY_MAXFILE, "%s/BL_proxy", seq->strip->dir); + } } else { return false; } - if (view_id > 0) + if (view_id > 0) { BLI_snprintf(suffix, sizeof(suffix), "_%d", view_id); + } if (proxy->storage & SEQ_STORAGE_PROXY_CUSTOM_FILE && ed->proxy_storage != SEQ_EDIT_PROXY_DIR_STORAGE) { @@ -1876,8 +1946,9 @@ static ImBuf *seq_proxy_fetch(const SeqRenderData *context, Sequence *seq, int c if (BLI_exists(name)) { ImBuf *ibuf = IMB_loadiffname(name, IB_rect, NULL); - if (ibuf) + if (ibuf) { sequencer_imbuf_assign_spaces(context->scene, ibuf); + } return ibuf; } @@ -1930,8 +2001,9 @@ static void seq_proxy_build_frame(const SeqRenderData *context, ibuf->foptions.quality = quality; /* unsupported feature only confuses other s/w */ - if (ibuf->planes == 32) + if (ibuf->planes == 32) { ibuf->planes = 24; + } BLI_make_existing_file(name); @@ -1949,8 +2021,9 @@ static void seq_proxy_build_frame(const SeqRenderData *context, */ static bool seq_proxy_multiview_context_invalid(Sequence *seq, Scene *scene, const int view_id) { - if ((scene->r.scemode & R_MULTIVIEW) == 0) + if ((scene->r.scemode & R_MULTIVIEW) == 0) { return false; + } if ((seq->type == SEQ_TYPE_IMAGE) && (seq->views_format == R_IMF_VIEWS_INDIVIDUAL)) { static char prefix[FILE_MAX]; @@ -1967,15 +2040,18 @@ static bool seq_proxy_multiview_context_invalid(Sequence *seq, Scene *scene, con prefix[0] = '\0'; } - if (prefix[0] == '\0') + if (prefix[0] == '\0') { return view_id != 0; + } seq_multiview_name(scene, view_id, prefix, ext, str, FILE_MAX); - if (BLI_access(str, R_OK) == 0) + if (BLI_access(str, R_OK) == 0) { return false; - else + } + else { return view_id != 0; + } } return false; } @@ -1987,8 +2063,9 @@ static int seq_proxy_context_count(Sequence *seq, Scene *scene) { int num_views = 1; - if ((scene->r.scemode & R_MULTIVIEW) == 0) + if ((scene->r.scemode & R_MULTIVIEW) == 0) { return 1; + } switch (seq->type) { case SEQ_TYPE_MOVIE: { @@ -2040,8 +2117,9 @@ void BKE_sequencer_proxy_rebuild_context(Main *bmain, num_files = seq_proxy_context_count(seq, scene); for (i = 0; i < num_files; i++) { - if (seq_proxy_multiview_context_invalid(seq, scene, i)) + if (seq_proxy_multiview_context_invalid(seq, scene, i)) { continue; + } context = MEM_callocN(sizeof(SeqIndexBuildContext), "seq proxy rebuild context"); @@ -2146,8 +2224,9 @@ void BKE_sequencer_proxy_rebuild(SeqIndexBuildContext *context, (seq->enddisp - seq->endstill - seq->startdisp - seq->startstill); *do_update = true; - if (*stop || G.is_break) + if (*stop || G.is_break) { break; + } } } @@ -2156,11 +2235,13 @@ void BKE_sequencer_proxy_rebuild_finish(SeqIndexBuildContext *context, bool stop if (context->index_context) { StripAnim *sanim; - for (sanim = context->seq->anims.first; sanim; sanim = sanim->next) + for (sanim = context->seq->anims.first; sanim; sanim = sanim->next) { IMB_close_anim_proxies(sanim->anim); + } - for (sanim = context->orig_seq->anims.first; sanim; sanim = sanim->next) + for (sanim = context->orig_seq->anims.first; sanim; sanim = sanim->next) { IMB_close_anim_proxies(sanim->anim); + } IMB_anim_index_rebuild_finish(context->index_context, stop); } @@ -2201,8 +2282,9 @@ static StripColorBalance calc_cb(StripColorBalance *cb_) for (c = 0; c < 3; c++) { /* tweak to give more subtle results * values above 1.0 are scaled */ - if (cb.lift[c] > 1.0f) + if (cb.lift[c] > 1.0f) { cb.lift[c] = pow(cb.lift[c] - 1.0f, 2.0) + 1.0; + } cb.lift[c] = 2.0f - cb.lift[c]; } @@ -2240,8 +2322,9 @@ MINLINE float color_balance_fl( float x = (((in - 1.0f) * lift) + 1.0f) * gain; /* prevent NaN */ - if (x < 0.f) + if (x < 0.f) { x = 0.f; + } return powf(x, gamma) * mul; } @@ -2264,7 +2347,7 @@ static void color_balance_byte_byte(StripColorBalance *cb_, int height, float mul) { - //unsigned char cb_tab[3][256]; + // unsigned char cb_tab[3][256]; unsigned char *cp = rect; unsigned char *e = cp + width * 4 * height; unsigned char *m = mask_rect; @@ -2285,15 +2368,17 @@ static void color_balance_byte_byte(StripColorBalance *cb_, p[c] = p[c] * (1.0f - m_normal) + t * m_normal; } - else + else { p[c] = t; + } } premul_float_to_straight_uchar(cp, p); cp += 4; - if (m) + if (m) { m += 4; + } } } @@ -2365,15 +2450,18 @@ static void color_balance_float_float(StripColorBalance *cb_, for (c = 0; c < 3; c++) { float t = color_balance_fl(p[c], cb.lift[c], cb.gain[c], cb.gamma[c], mul); - if (m) + if (m) { p[c] = p[c] * (1.0f - m[c]) + t * m[c]; - else + } + else { p[c] = t; + } } p += 4; - if (m) + if (m) { m += 4; + } } } @@ -2417,18 +2505,22 @@ static void color_balance_init_handle(void *handle_v, handle->height = tot_line; handle->make_float = init_data->make_float; - if (ibuf->rect) + if (ibuf->rect) { handle->rect = (unsigned char *)ibuf->rect + offset; + } - if (ibuf->rect_float) + if (ibuf->rect_float) { handle->rect_float = ibuf->rect_float + offset; + } if (mask) { - if (mask->rect) + if (mask->rect) { handle->mask_rect = (unsigned char *)mask->rect + offset; + } - if (mask->rect_float) + if (mask->rect_float) { handle->mask_rect_float = mask->rect_float + offset; + } } else { handle->mask_rect = NULL; @@ -2479,12 +2571,14 @@ ImBuf *BKE_sequencer_render_mask_input(const SeqRenderData *context, mask_input = seq_render_strip(context, &state, mask_sequence, cfra); if (make_float) { - if (!mask_input->rect_float) + if (!mask_input->rect_float) { IMB_float_from_rect(mask_input); + } } else { - if (!mask_input->rect) + if (!mask_input->rect) { IMB_rect_from_float(mask_input); + } } } } @@ -2500,8 +2594,9 @@ void BKE_sequencer_color_balance_apply( { ColorBalanceInitData init_data; - if (!ibuf->rect_float && make_float) + if (!ibuf->rect_float && make_float) { imb_addrectfloatImBuf(ibuf); + } init_data.cb = cb; init_data.ibuf = ibuf; @@ -2519,8 +2614,9 @@ void BKE_sequencer_color_balance_apply( * free byte buffer if there's float buffer since float buffer would be used for * color balance in favor of byte buffer */ - if (ibuf->rect_float && ibuf->rect) + if (ibuf->rect_float && ibuf->rect) { imb_freerectImBuf(ibuf); + } } /* @@ -2547,7 +2643,7 @@ bool BKE_sequencer_input_have_to_preprocess(const SeqRenderData *context, { float mul; - if (context->is_proxy_render) { + if (context && context->is_proxy_render) { return false; } @@ -2717,54 +2813,6 @@ static ImBuf *input_preprocess(const SeqRenderData *context, return ibuf; } -static ImBuf *copy_from_ibuf_still(const SeqRenderData *context, Sequence *seq, float nr) -{ - ImBuf *rval = NULL; - ImBuf *ibuf = NULL; - - if (nr == 0) { - ibuf = BKE_sequencer_cache_get(context, seq, seq->start, SEQ_STRIPELEM_IBUF_STARTSTILL); - } - else if (nr == seq->len - 1) { - ibuf = BKE_sequencer_cache_get(context, seq, seq->start, SEQ_STRIPELEM_IBUF_ENDSTILL); - } - - if (ibuf) { - rval = IMB_dupImBuf(ibuf); - IMB_metadata_copy(rval, ibuf); - IMB_freeImBuf(ibuf); - } - - return rval; -} - -static void copy_to_ibuf_still(const SeqRenderData *context, Sequence *seq, float nr, ImBuf *ibuf) -{ - /* warning: ibuf may be NULL if the video fails to load */ - if (nr == 0 || nr == seq->len - 1) { - /* we have to store a copy, since the passed ibuf - * could be preprocessed afterwards (thereby silently - * changing the cached image... */ - ImBuf *oibuf = ibuf; - ibuf = IMB_dupImBuf(oibuf); - - if (ibuf) { - IMB_metadata_copy(ibuf, oibuf); - sequencer_imbuf_assign_spaces(context->scene, ibuf); - } - - if (nr == 0) { - BKE_sequencer_cache_put(context, seq, seq->start, SEQ_STRIPELEM_IBUF_STARTSTILL, ibuf); - } - - if (nr == seq->len - 1) { - BKE_sequencer_cache_put(context, seq, seq->start, SEQ_STRIPELEM_IBUF_ENDSTILL, ibuf); - } - - IMB_freeImBuf(ibuf); - } -} - /*********************** strip rendering functions *************************/ typedef struct RenderEffectInitData { @@ -2912,16 +2960,19 @@ static ImBuf *seq_render_effect_strip_impl(const SeqRenderData *context, break; case EARLY_DO_EFFECT: for (i = 0; i < 3; i++) { - if (input[i]) + if (input[i]) { ibuf[i] = seq_render_strip(context, state, input[i], cfra); + } } if (ibuf[0] && ibuf[1]) { - if (sh.multithreaded) + if (sh.multithreaded) { out = seq_render_effect_execute_threaded( &sh, context, seq, cfra, fac, facf, ibuf[0], ibuf[1], ibuf[2]); - else + } + else { out = sh.execute(context, seq, cfra, fac, facf, ibuf[0], ibuf[1], ibuf[2]); + } } break; case EARLY_USE_INPUT_1: @@ -2967,7 +3018,7 @@ static ImBuf *seq_render_effect_strip_impl(const SeqRenderData *context, static ImBuf *seq_render_image_strip(const SeqRenderData *context, Sequence *seq, - float nr, + float UNUSED(nr), float cfra) { ImBuf *ibuf = NULL; @@ -2983,8 +3034,9 @@ static ImBuf *seq_render_image_strip(const SeqRenderData *context, } flag = IB_rect | IB_metadata; - if (seq->alpha_mode == SEQ_ALPHA_PREMUL) + if (seq->alpha_mode == SEQ_ALPHA_PREMUL) { flag |= IB_alphamode_premul; + } if (!s_elem) { /* don't do anything */ @@ -3023,13 +3075,15 @@ static ImBuf *seq_render_image_strip(const SeqRenderData *context, if (ibufs_arr[i]) { /* we don't need both (speed reasons)! */ - if (ibufs_arr[i]->rect_float && ibufs_arr[i]->rect) + if (ibufs_arr[i]->rect_float && ibufs_arr[i]->rect) { imb_freerectImBuf(ibufs_arr[i]); + } } } - if (seq->views_format == R_IMF_VIEWS_STEREO_3D && ibufs_arr[0]) + if (seq->views_format == R_IMF_VIEWS_STEREO_3D && ibufs_arr[0]) { IMB_ImBufFromStereo3d(seq->stereo3d_format, ibufs_arr[0], &ibufs_arr[0], &ibufs_arr[1]); + } for (i = 0; i < totviews; i++) { if (ibufs_arr[i]) { @@ -3040,8 +3094,8 @@ static ImBuf *seq_render_image_strip(const SeqRenderData *context, BKE_sequencer_imbuf_to_sequencer_space(context->scene, ibufs_arr[i], false); if (i != context->view_id) { - copy_to_ibuf_still(&localcontext, seq, nr, ibufs_arr[i]); - BKE_sequencer_cache_put(&localcontext, seq, cfra, SEQ_STRIPELEM_IBUF, ibufs_arr[i]); + BKE_sequencer_cache_put( + &localcontext, seq, cfra, SEQ_CACHE_STORE_PREPROCESSED, ibufs_arr[i], 0); } } } @@ -3066,8 +3120,9 @@ static ImBuf *seq_render_image_strip(const SeqRenderData *context, monoview_image: if ((ibuf = IMB_loadiffname(name, flag, seq->strip->colorspace_settings.name))) { /* we don't need both (speed reasons)! */ - if (ibuf->rect_float && ibuf->rect) + if (ibuf->rect_float && ibuf->rect) { imb_freerectImBuf(ibuf); + } /* all sequencer color is done in SRGB space, linear gives odd crossfades */ BKE_sequencer_imbuf_to_sequencer_space(context->scene, ibuf, false); @@ -3099,8 +3154,9 @@ static ImBuf *seq_render_movie_strip(const SeqRenderData *context, int totviews; int i; - if (totfiles != BLI_listbase_count_at_most(&seq->anims, totfiles + 1)) + if (totfiles != BLI_listbase_count_at_most(&seq->anims, totfiles + 1)) { goto monoview_movie; + } totviews = BKE_scene_multiview_num_views_get(&context->scene->r); ibuf_arr = MEM_callocN(sizeof(ImBuf *) * totviews, "Sequence Image Views Imbufs"); @@ -3126,8 +3182,9 @@ static ImBuf *seq_render_movie_strip(const SeqRenderData *context, } if (ibuf_arr[i]) { /* we don't need both (speed reasons)! */ - if (ibuf_arr[i]->rect_float && ibuf_arr[i]->rect) + if (ibuf_arr[i]->rect_float && ibuf_arr[i]->rect) { imb_freerectImBuf(ibuf_arr[i]); + } } } } @@ -3152,8 +3209,8 @@ static ImBuf *seq_render_movie_strip(const SeqRenderData *context, BKE_sequencer_imbuf_to_sequencer_space(context->scene, ibuf_arr[i], false); } if (i != context->view_id) { - copy_to_ibuf_still(&localcontext, seq, nr, ibuf_arr[i]); - BKE_sequencer_cache_put(&localcontext, seq, cfra, SEQ_STRIPELEM_IBUF, ibuf_arr[i]); + BKE_sequencer_cache_put( + &localcontext, seq, cfra, SEQ_CACHE_STORE_PREPROCESSED, ibuf_arr[i], 0); } } @@ -3397,9 +3454,7 @@ static ImBuf *seq_render_scene_strip(const SeqRenderData *context, const bool is_rendering = G.is_rendering; const bool is_background = G.background; - const bool do_seq_gl = is_rendering ? 0 /* (context->scene->r.seq_flag & R_SEQ_GL_REND) */ : - (context->scene->r.seq_prev_type) != OB_RENDER; - // bool have_seq = false; /* UNUSED */ + const bool do_seq_gl = is_rendering ? 0 : (context->scene->r.seq_prev_type) != OB_RENDER; bool have_comp = false; bool use_gpencil = true; /* do we need to re-evaluate the frame after rendering? */ @@ -3415,7 +3470,9 @@ static ImBuf *seq_render_scene_strip(const SeqRenderData *context, scene = seq->scene; frame = (double)scene->r.sfra + (double)nr + (double)seq->anim_startofs; - // have_seq = (scene->r.scemode & R_DOSEQ) && scene->ed && scene->ed->seqbase.first); /* UNUSED */ +#if 0 /* UNUSED */ + have_seq = (scene->r.scemode & R_DOSEQ) && scene->ed && scene->ed->seqbase.first); +#endif have_comp = (scene->r.scemode & R_DOCOMP) && scene->use_nodes && scene->nodetree; /* Get view layer for the strip. */ @@ -3462,20 +3519,20 @@ static ImBuf *seq_render_scene_strip(const SeqRenderData *context, char err_out[256] = "unknown"; const int width = (scene->r.xsch * scene->r.size) / 100; const int height = (scene->r.ysch * scene->r.size) / 100; - const bool use_background = (scene->r.alphamode == R_ADDSKY); const char *viewname = BKE_scene_multiview_render_view_name_get(&scene->r, context->view_id); - unsigned int draw_flags = SEQ_OFSDRAW_NONE; - draw_flags |= (use_gpencil) ? SEQ_OFSDRAW_USE_GPENCIL : 0; - draw_flags |= (use_background) ? SEQ_OFSDRAW_USE_BACKGROUND : 0; - draw_flags |= (context->gpu_full_samples) ? SEQ_OFSDRAW_USE_FULL_SAMPLE : 0; - draw_flags |= (context->scene->r.seq_flag & R_SEQ_SOLID_TEX) ? SEQ_OFSDRAW_USE_SOLID_TEX : 0; - draw_flags |= (context->scene->r.seq_flag & R_SEQ_CAMERA_DOF) ? SEQ_OFSDRAW_USE_CAMERA_DOF : 0; + unsigned int draw_flags = V3D_OFSDRAW_NONE; + draw_flags |= (use_gpencil) ? V3D_OFSDRAW_SHOW_ANNOTATION : 0; + draw_flags |= (context->gpu_full_samples) ? V3D_OFSDRAW_USE_FULL_SAMPLE : 0; + draw_flags |= (context->scene->r.seq_flag & R_SEQ_OVERRIDE_SCENE_SETTINGS) ? + V3D_OFSDRAW_OVERRIDE_SCENE_SETTINGS : + 0; /* for old scene this can be uninitialized, * should probably be added to do_versions at some point if the functionality stays */ - if (context->scene->r.seq_prev_type == 0) + if (context->scene->r.seq_prev_type == 0) { context->scene->r.seq_prev_type = 3 /* == OB_SOLID */; + } /* opengl offscreen render */ depsgraph = BKE_scene_get_depsgraph(scene, view_layer, true); @@ -3484,6 +3541,7 @@ static ImBuf *seq_render_scene_strip(const SeqRenderData *context, /* set for OpenGL render (NULL when scrubbing) */ depsgraph, scene, + &context->scene->display.shading, context->scene->r.seq_prev_type, camera, width, @@ -3516,8 +3574,9 @@ static ImBuf *seq_render_scene_strip(const SeqRenderData *context, * case it's always safe to render scene here */ if (!is_thread_main || is_rendering == false || is_background || context->for_render) { - if (re == NULL) + if (re == NULL) { re = RE_NewSceneRender(scene); + } RE_BlenderFrame(re, context->bmain, scene, view_layer, camera, frame, false); @@ -3551,8 +3610,7 @@ static ImBuf *seq_render_scene_strip(const SeqRenderData *context, } if (i != context->view_id) { - copy_to_ibuf_still(&localcontext, seq, nr, ibufs_arr[i]); - BKE_sequencer_cache_put(&localcontext, seq, cfra, SEQ_STRIPELEM_IBUF, ibufs_arr[i]); + BKE_sequencer_cache_put(&localcontext, seq, cfra, SEQ_CACHE_STORE_RAW, ibufs_arr[i], 0); } RE_ReleaseResultImage(re); @@ -3582,7 +3640,7 @@ finally: #ifdef DURIAN_CAMERA_SWITCH /* stooping to new low's in hackyness :( */ - scene->r.mode &= ~(orig_data.mode & R_NO_CAMERA_SWITCH); + scene->r.mode &= orig_data.mode | ~R_NO_CAMERA_SWITCH; #endif return ibuf; @@ -3604,6 +3662,12 @@ static ImBuf *do_render_strip_seqbase(const SeqRenderData *context, seqbase = BKE_sequence_seqbase_get(seq, &offset); if (seqbase && !BLI_listbase_is_empty(seqbase)) { + + if (seq->flag & SEQ_SCENE_STRIPS && seq->scene) { + BKE_animsys_evaluate_all_animation( + context->bmain, context->depsgraph, seq->scene, nr + offset); + } + meta_ibuf = seq_render_strip_stack(context, state, seqbase, @@ -3662,6 +3726,7 @@ static ImBuf *do_render_strip_uncached(const SeqRenderData *context, */ SeqRenderData local_context = *context; local_context.scene = seq->scene; + local_context.skip_cache = true; ibuf = do_render_strip_seqbase(&local_context, state, seq, nr, use_preprocess); @@ -3672,13 +3737,11 @@ static ImBuf *do_render_strip_uncached(const SeqRenderData *context, else { /* scene can be NULL after deletions */ ibuf = seq_render_scene_strip(context, seq, nr, cfra); + } - /* Scene strips update all animation, so we need to restore original state.*/ - BKE_animsys_evaluate_all_animation( - context->bmain, context->depsgraph, context->scene, cfra); + /* Scene strips update all animation, so we need to restore original state.*/ + BKE_animsys_evaluate_all_animation(context->bmain, context->depsgraph, context->scene, cfra); - copy_to_ibuf_still(context, seq, nr, ibuf); - } break; } @@ -3715,13 +3778,11 @@ static ImBuf *do_render_strip_uncached(const SeqRenderData *context, case SEQ_TYPE_IMAGE: { ibuf = seq_render_image_strip(context, seq, nr, cfra); - copy_to_ibuf_still(context, seq, nr, ibuf); break; } case SEQ_TYPE_MOVIE: { ibuf = seq_render_movie_strip(context, seq, nr, cfra); - copy_to_ibuf_still(context, seq, nr, ibuf); break; } @@ -3734,10 +3795,9 @@ static ImBuf *do_render_strip_uncached(const SeqRenderData *context, IMB_freeImBuf(ibuf); ibuf = i; - if (ibuf->rect_float) + if (ibuf->rect_float) { BKE_sequencer_imbuf_to_sequencer_space(context->scene, ibuf, false); - - copy_to_ibuf_still(context, seq, nr, ibuf); + } } break; @@ -3746,18 +3806,37 @@ static ImBuf *do_render_strip_uncached(const SeqRenderData *context, case SEQ_TYPE_MASK: { /* ibuf is always new */ ibuf = seq_render_mask_strip(context, seq, nr); - - copy_to_ibuf_still(context, seq, nr, ibuf); break; } } - if (ibuf) + if (ibuf) { sequencer_imbuf_assign_spaces(context->scene, ibuf); + } return ibuf; } +/* Estimate time spent by the program rendering the strip */ +static clock_t seq_estimate_render_cost_begin(void) +{ + return clock(); +} + +static float seq_estimate_render_cost_end(Scene *scene, clock_t begin) +{ + clock_t end = clock(); + float time_spent = (float)(end - begin); + float time_max = (1.0f / scene->r.frs_sec) * CLOCKS_PER_SEC; + + if (time_max != 0) { + return time_spent / time_max; + } + else { + return 1; + } +} + static ImBuf *seq_render_strip(const SeqRenderData *context, SeqRenderState *state, Sequence *seq, @@ -3766,65 +3845,62 @@ static ImBuf *seq_render_strip(const SeqRenderData *context, ImBuf *ibuf = NULL; bool use_preprocess = false; bool is_proxy_image = false; - float nr = give_stripelem_index(seq, cfra); /* all effects are handled similarly with the exception of speed effect */ int type = (seq->type & SEQ_TYPE_EFFECT && seq->type != SEQ_TYPE_SPEED) ? SEQ_TYPE_EFFECT : seq->type; bool is_preprocessed = !ELEM( type, SEQ_TYPE_IMAGE, SEQ_TYPE_MOVIE, SEQ_TYPE_SCENE, SEQ_TYPE_MOVIECLIP); - ibuf = BKE_sequencer_cache_get(context, seq, cfra, SEQ_STRIPELEM_IBUF); + clock_t begin = seq_estimate_render_cost_begin(); - if (ibuf == NULL) { - ibuf = copy_from_ibuf_still(context, seq, nr); + ibuf = BKE_sequencer_cache_get(context, seq, cfra, SEQ_CACHE_STORE_PREPROCESSED); + if (ibuf == NULL) { + ibuf = BKE_sequencer_cache_get(context, seq, cfra, SEQ_CACHE_STORE_RAW); if (ibuf == NULL) { - ibuf = BKE_sequencer_preprocessed_cache_get(context, seq, cfra, SEQ_STRIPELEM_IBUF); + /* MOVIECLIPs have their own proxy management */ + if (seq->type != SEQ_TYPE_MOVIECLIP) { + ibuf = seq_proxy_fetch(context, seq, cfra); + is_proxy_image = (ibuf != NULL); + } if (ibuf == NULL) { - /* MOVIECLIPs have their own proxy management */ - if (seq->type != SEQ_TYPE_MOVIECLIP) { - ibuf = seq_proxy_fetch(context, seq, cfra); - is_proxy_image = (ibuf != NULL); - } - - if (ibuf == NULL) - ibuf = do_render_strip_uncached(context, state, seq, cfra); + ibuf = do_render_strip_uncached(context, state, seq, cfra); + } - if (ibuf) { - if (ELEM(seq->type, SEQ_TYPE_MOVIE, SEQ_TYPE_MOVIECLIP)) { - is_proxy_image = (context->preview_render_size != 100); - } - BKE_sequencer_preprocessed_cache_put(context, seq, cfra, SEQ_STRIPELEM_IBUF, ibuf); + if (ibuf) { + if (ELEM(seq->type, SEQ_TYPE_MOVIE, SEQ_TYPE_MOVIECLIP)) { + is_proxy_image = (context->preview_render_size != 100); } } } - if (ibuf) + if (ibuf) { use_preprocess = BKE_sequencer_input_have_to_preprocess(context, seq, cfra); - } - else { - /* currently, we cache preprocessed images in SEQ_STRIPELEM_IBUF, - * but not(!) on SEQ_STRIPELEM_IBUF_ENDSTILL and ..._STARTSTILL - * so, no need in check for preprocess here - */ - } + } - if (ibuf == NULL) { - ibuf = IMB_allocImBuf(context->rectx, context->recty, 32, IB_rect); - sequencer_imbuf_assign_spaces(context->scene, ibuf); - } + if (ibuf == NULL) { + ibuf = IMB_allocImBuf(context->rectx, context->recty, 32, IB_rect); + sequencer_imbuf_assign_spaces(context->scene, ibuf); + } - if (context->is_proxy_render == false && - (ibuf->x != context->rectx || ibuf->y != context->recty)) { - use_preprocess = true; - } + if (context->is_proxy_render == false && + (ibuf->x != context->rectx || ibuf->y != context->recty)) { + use_preprocess = true; + } - if (use_preprocess) - ibuf = input_preprocess(context, seq, cfra, ibuf, is_proxy_image, is_preprocessed); + if (use_preprocess) { + float cost = seq_estimate_render_cost_end(context->scene, begin); + BKE_sequencer_cache_put(context, seq, cfra, SEQ_CACHE_STORE_RAW, ibuf, cost); - BKE_sequencer_cache_put(context, seq, cfra, SEQ_STRIPELEM_IBUF, ibuf); + /* reset timer so we can get partial render time */ + begin = seq_estimate_render_cost_begin(); + ibuf = input_preprocess(context, seq, cfra, ibuf, is_proxy_image, is_preprocessed); + } + float cost = seq_estimate_render_cost_end(context->scene, begin); + BKE_sequencer_cache_put(context, seq, cfra, SEQ_CACHE_STORE_PREPROCESSED, ibuf, cost); + } return ibuf; } @@ -3874,18 +3950,22 @@ static ImBuf *seq_render_strip_stack_apply_effect( int swap_input = seq_must_swap_input_in_blend_mode(seq); if (swap_input) { - if (sh.multithreaded) + if (sh.multithreaded) { out = seq_render_effect_execute_threaded( &sh, context, seq, cfra, facf, facf, ibuf2, ibuf1, NULL); - else + } + else { out = sh.execute(context, seq, cfra, facf, facf, ibuf2, ibuf1, NULL); + } } else { - if (sh.multithreaded) + if (sh.multithreaded) { out = seq_render_effect_execute_threaded( &sh, context, seq, cfra, facf, facf, ibuf1, ibuf2, NULL); - else + } + else { out = sh.execute(context, seq, cfra, facf, facf, ibuf1, ibuf2, NULL); + } } return out; @@ -3901,6 +3981,7 @@ static ImBuf *seq_render_strip_stack(const SeqRenderData *context, int count; int i; ImBuf *out = NULL; + clock_t begin; count = get_shown_sequences(seqbasep, cfra, chanshown, (Sequence **)&seq_arr); @@ -3908,73 +3989,11 @@ static ImBuf *seq_render_strip_stack(const SeqRenderData *context, return NULL; } -#if 0 /* commentind since this breaks keyframing, since it resets the value on draw */ - if (scene->r.cfra != cfra) { - /* XXX for prefetch and overlay offset!..., very bad!!! */ - AnimData *adt = BKE_animdata_from_id(&scene->id); - BKE_animsys_evaluate_animdata(scene, &scene->id, adt, cfra, ADT_RECALC_ANIM); - } -#endif - - out = BKE_sequencer_cache_get(context, seq_arr[count - 1], cfra, SEQ_STRIPELEM_IBUF_COMP); - - if (out) { - return out; - } - - if (count == 1) { - Sequence *seq = seq_arr[0]; - - /* Some of the blend modes are unclear how to apply with only single input, - * or some of them will just produce an empty result.. - */ - if (ELEM(seq->blend_mode, SEQ_BLEND_REPLACE, SEQ_TYPE_CROSS, SEQ_TYPE_ALPHAOVER)) { - int early_out; - if (seq->blend_mode == SEQ_BLEND_REPLACE) { - early_out = EARLY_NO_INPUT; - } - else { - early_out = seq_get_early_out_for_blend_mode(seq); - } - - if (ELEM(early_out, EARLY_NO_INPUT, EARLY_USE_INPUT_2)) { - out = seq_render_strip(context, state, seq, cfra); - } - else if (early_out == EARLY_USE_INPUT_1) { - out = IMB_allocImBuf(context->rectx, context->recty, 32, IB_rect); - } - else { - out = seq_render_strip(context, state, seq, cfra); - - if (early_out == EARLY_DO_EFFECT) { - ImBuf *ibuf1 = IMB_allocImBuf( - context->rectx, context->recty, 32, out->rect_float ? IB_rectfloat : IB_rect); - ImBuf *ibuf2 = out; - - out = seq_render_strip_stack_apply_effect(context, seq, cfra, ibuf1, ibuf2); - if (out) { - IMB_metadata_copy(out, ibuf2); - } - - IMB_freeImBuf(ibuf1); - IMB_freeImBuf(ibuf2); - } - } - } - else { - out = seq_render_strip(context, state, seq, cfra); - } - - BKE_sequencer_cache_put(context, seq, cfra, SEQ_STRIPELEM_IBUF_COMP, out); - - return out; - } - for (i = count - 1; i >= 0; i--) { int early_out; Sequence *seq = seq_arr[i]; - out = BKE_sequencer_cache_get(context, seq, cfra, SEQ_STRIPELEM_IBUF_COMP); + out = BKE_sequencer_cache_get(context, seq, cfra, SEQ_CACHE_STORE_COMPOSITE); if (out) { break; @@ -3998,15 +4017,19 @@ static ImBuf *seq_render_strip_stack(const SeqRenderData *context, break; case EARLY_DO_EFFECT: if (i == 0) { + begin = seq_estimate_render_cost_begin(); + ImBuf *ibuf1 = IMB_allocImBuf(context->rectx, context->recty, 32, IB_rect); ImBuf *ibuf2 = seq_render_strip(context, state, seq, cfra); out = seq_render_strip_stack_apply_effect(context, seq, cfra, ibuf1, ibuf2); + float cost = seq_estimate_render_cost_end(context->scene, begin); + BKE_sequencer_cache_put(context, seq_arr[i], cfra, SEQ_CACHE_STORE_COMPOSITE, out, cost); + IMB_freeImBuf(ibuf1); IMB_freeImBuf(ibuf2); } - break; } if (out) { @@ -4014,11 +4037,9 @@ static ImBuf *seq_render_strip_stack(const SeqRenderData *context, } } - BKE_sequencer_cache_put(context, seq_arr[i], cfra, SEQ_STRIPELEM_IBUF_COMP, out); - i++; - for (; i < count; i++) { + begin = seq_estimate_render_cost_begin(); Sequence *seq = seq_arr[i]; if (seq_get_early_out_for_blend_mode(seq) == EARLY_DO_EFFECT) { @@ -4031,7 +4052,8 @@ static ImBuf *seq_render_strip_stack(const SeqRenderData *context, IMB_freeImBuf(ibuf2); } - BKE_sequencer_cache_put(context, seq_arr[i], cfra, SEQ_STRIPELEM_IBUF_COMP, out); + float cost = seq_estimate_render_cost_end(context->scene, begin); + BKE_sequencer_cache_put(context, seq_arr[i], cfra, SEQ_CACHE_STORE_COMPOSITE, out, cost); } return out; @@ -4044,11 +4066,13 @@ static ImBuf *seq_render_strip_stack(const SeqRenderData *context, ImBuf *BKE_sequencer_give_ibuf(const SeqRenderData *context, float cfra, int chanshown) { - Editing *ed = BKE_sequencer_editing_get(context->scene, false); + Scene *scene = context->scene; + Editing *ed = BKE_sequencer_editing_get(scene, false); ListBase *seqbasep; - if (ed == NULL) + if (ed == NULL) { return NULL; + } if ((chanshown < 0) && !BLI_listbase_is_empty(&ed->metastack)) { int count = BLI_listbase_count(&ed->metastack); @@ -4061,8 +4085,29 @@ ImBuf *BKE_sequencer_give_ibuf(const SeqRenderData *context, float cfra, int cha SeqRenderState state; sequencer_state_init(&state); + ImBuf *out = NULL; + Sequence *seq_arr[MAXSEQ + 1]; + int count; - return seq_render_strip_stack(context, &state, seqbasep, cfra, chanshown); + count = get_shown_sequences(seqbasep, cfra, chanshown, seq_arr); + + if (count) { + out = BKE_sequencer_cache_get(context, seq_arr[count - 1], cfra, SEQ_CACHE_STORE_FINAL_OUT); + } + + BKE_sequencer_cache_free_temp_cache(context->scene, 0, cfra); + + clock_t begin = seq_estimate_render_cost_begin(); + float cost = 0; + + if (count && !out) { + out = seq_render_strip_stack(context, &state, seqbasep, cfra, chanshown); + cost = seq_estimate_render_cost_end(context->scene, begin); + BKE_sequencer_cache_put_if_possible( + context, seq_arr[count - 1], cfra, SEQ_CACHE_STORE_FINAL_OUT, out, cost); + } + + return out; } ImBuf *BKE_sequencer_give_ibuf_seqbase(const SeqRenderData *context, @@ -4081,7 +4126,9 @@ ImBuf *BKE_sequencer_give_ibuf_direct(const SeqRenderData *context, float cfra, SeqRenderState state; sequencer_state_init(&state); - return seq_render_strip(context, &state, seq, cfra); + ImBuf *ibuf = seq_render_strip(context, &state, seq, cfra); + + return ibuf; } /* *********************** threading api ******************* */ @@ -4094,8 +4141,8 @@ static pthread_mutex_t queue_lock = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t wakeup_lock = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t wakeup_cond = PTHREAD_COND_INITIALIZER; -//static pthread_mutex_t prefetch_ready_lock = PTHREAD_MUTEX_INITIALIZER; -//static pthread_cond_t prefetch_ready_cond = PTHREAD_COND_INITIALIZER; +// static pthread_mutex_t prefetch_ready_lock = PTHREAD_MUTEX_INITIALIZER; +// static pthread_cond_t prefetch_ready_cond = PTHREAD_COND_INITIALIZER; static pthread_mutex_t frame_done_lock = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t frame_done_cond = PTHREAD_COND_INITIALIZER; @@ -4227,16 +4274,19 @@ ImBuf *BKE_sequencer_give_ibuf_threaded(const SeqRenderData *context, float cfra /* check whether sequence cur depends on seq */ bool BKE_sequence_check_depend(Sequence *seq, Sequence *cur) { - if (cur->seq1 == seq || cur->seq2 == seq || cur->seq3 == seq) + if (cur->seq1 == seq || cur->seq2 == seq || cur->seq3 == seq) { return true; + } /* sequences are not intersecting in time, assume no dependency exists between them */ - if (cur->enddisp < seq->startdisp || cur->startdisp > seq->enddisp) + if (cur->enddisp < seq->startdisp || cur->startdisp > seq->enddisp) { return false; + } /* checking sequence is below reference one, not dependent on it */ - if (cur->machine < seq->machine) + if (cur->machine < seq->machine) { return false; + } /* sequence is not blending with lower machines, no dependency here occurs * check for non-effects only since effect could use lower machines as input @@ -4250,28 +4300,29 @@ bool BKE_sequence_check_depend(Sequence *seq, Sequence *cur) return true; } -static void sequence_do_invalidate_dependent(Sequence *seq, ListBase *seqbase) +static void sequence_do_invalidate_dependent(Scene *scene, Sequence *seq, ListBase *seqbase) { Sequence *cur; for (cur = seqbase->first; cur; cur = cur->next) { - if (cur == seq) + if (cur == seq) { continue; + } if (BKE_sequence_check_depend(seq, cur)) { - BKE_sequencer_cache_cleanup_sequence(cur); - BKE_sequencer_preprocessed_cache_cleanup_sequence(cur); + BKE_sequencer_cache_cleanup_sequence(scene, cur); } - if (cur->seqbase.first) - sequence_do_invalidate_dependent(seq, &cur->seqbase); + if (cur->seqbase.first) { + sequence_do_invalidate_dependent(scene, seq, &cur->seqbase); + } } } static void sequence_invalidate_cache(Scene *scene, Sequence *seq, bool invalidate_self, - bool invalidate_preprocess) + bool UNUSED(invalidate_preprocess)) { Editing *ed = scene->ed; @@ -4282,22 +4333,20 @@ static void sequence_invalidate_cache(Scene *scene, * re-open the animation. */ BKE_sequence_free_anim(seq); - BKE_sequencer_cache_cleanup_sequence(seq); + BKE_sequencer_cache_cleanup_sequence(scene, seq); } /* if invalidation is invoked from sequence free routine, effectdata would be NULL here */ - if (seq->effectdata && seq->type == SEQ_TYPE_SPEED) + if (seq->effectdata && seq->type == SEQ_TYPE_SPEED) { BKE_sequence_effect_speed_rebuild_map(scene, seq, true); - - if (invalidate_preprocess) - BKE_sequencer_preprocessed_cache_cleanup_sequence(seq); + } /* invalidate cache for all dependent sequences */ /* NOTE: can not use SEQ_BEGIN/SEQ_END here because that macro will change sequence's depth, * which makes transformation routines work incorrect */ - sequence_do_invalidate_dependent(seq, &ed->seqbase); + sequence_do_invalidate_dependent(scene, seq, &ed->seqbase); } void BKE_sequence_invalidate_cache(Scene *scene, Sequence *seq) @@ -4319,7 +4368,7 @@ void BKE_sequencer_free_imbuf(Scene *scene, ListBase *seqbase, bool for_render) { Sequence *seq; - BKE_sequencer_cache_cleanup(); + BKE_sequencer_cache_cleanup(scene); for (seq = seqbase->first; seq; seq = seq->next) { if (for_render && CFRA >= seq->startdisp && CFRA <= seq->enddisp) { @@ -4352,25 +4401,35 @@ static bool update_changed_seq_recurs( /* recurs downwards to see if this seq depends on the changed seq */ - if (seq == NULL) + if (seq == NULL) { return false; + } - if (seq == changed_seq) + if (seq == changed_seq) { free_imbuf = true; + } - for (subseq = seq->seqbase.first; subseq; subseq = subseq->next) - if (update_changed_seq_recurs(scene, subseq, changed_seq, len_change, ibuf_change)) + for (subseq = seq->seqbase.first; subseq; subseq = subseq->next) { + if (update_changed_seq_recurs(scene, subseq, changed_seq, len_change, ibuf_change)) { free_imbuf = true; + } + } - if (seq->seq1) - if (update_changed_seq_recurs(scene, seq->seq1, changed_seq, len_change, ibuf_change)) + if (seq->seq1) { + if (update_changed_seq_recurs(scene, seq->seq1, changed_seq, len_change, ibuf_change)) { free_imbuf = true; - if (seq->seq2 && (seq->seq2 != seq->seq1)) - if (update_changed_seq_recurs(scene, seq->seq2, changed_seq, len_change, ibuf_change)) + } + } + if (seq->seq2 && (seq->seq2 != seq->seq1)) { + if (update_changed_seq_recurs(scene, seq->seq2, changed_seq, len_change, ibuf_change)) { free_imbuf = true; - if (seq->seq3 && (seq->seq3 != seq->seq1) && (seq->seq3 != seq->seq2)) - if (update_changed_seq_recurs(scene, seq->seq3, changed_seq, len_change, ibuf_change)) + } + } + if (seq->seq3 && (seq->seq3 != seq->seq1) && (seq->seq3 != seq->seq2)) { + if (update_changed_seq_recurs(scene, seq->seq3, changed_seq, len_change, ibuf_change)) { free_imbuf = true; + } + } if (free_imbuf) { if (ibuf_change) { @@ -4382,8 +4441,9 @@ static bool update_changed_seq_recurs( } } - if (len_change) + if (len_change) { BKE_sequence_calc(scene, seq); + } } return free_imbuf; @@ -4397,11 +4457,13 @@ void BKE_sequencer_update_changed_seq_and_deps(Scene *scene, Editing *ed = BKE_sequencer_editing_get(scene, false); Sequence *seq; - if (ed == NULL) + if (ed == NULL) { return; + } - for (seq = ed->seqbase.first; seq; seq = seq->next) + for (seq = ed->seqbase.first; seq; seq = seq->next) { update_changed_seq_recurs(scene, seq, changed_seq, len_change, ibuf_change); + } } /* seq funcs's for transforming internally @@ -4489,13 +4551,15 @@ bool BKE_sequence_base_isolated_sel_check(ListBase *seqbase) } } - if (ok == false) + if (ok == false) { return false; + } /* test relationships */ for (seq = seqbase->first; seq; seq = seq->next) { - if ((seq->type & SEQ_TYPE_EFFECT) == 0) + if ((seq->type & SEQ_TYPE_EFFECT) == 0) { continue; + } if (seq->flag & SELECT) { if ((seq->seq1 && (seq->seq1->flag & SELECT) == 0) || @@ -4565,8 +4629,9 @@ void BKE_sequence_tx_handle_xlimits(Sequence *seq, int leftflag, int rightflag) void BKE_sequence_single_fix(Sequence *seq) { int left, start, offset; - if (!BKE_sequence_single_check(seq)) + if (!BKE_sequence_single_check(seq)) { return; + } /* make sure the image is always at the start since there is only one, * adjusting its start should be ok */ @@ -4588,8 +4653,8 @@ bool BKE_sequence_tx_test(Sequence *seq) /** * Return \a true if given \a seq needs a complete cleanup of its cache when it is transformed. * - * Some (effect) strip types need a complete recache of themselves when they are transformed, because - * they do not 'contain' anything and do not have any explicit relations to other strips. + * Some (effect) strip types need a complete recache of themselves when they are transformed, + * because they do not 'contain' anything and do not have any explicit relations to other strips. */ bool BKE_sequence_tx_fullupdate_test(Sequence *seq) { @@ -4608,8 +4673,9 @@ bool BKE_sequence_test_overlap(ListBase *seqbasep, Sequence *test) seq = seqbasep->first; while (seq) { - if (seq_overlap(test, seq)) + if (seq_overlap(test, seq)) { return true; + } seq = seq->next; } @@ -4655,12 +4721,14 @@ Sequence *BKE_sequencer_foreground_frame_get(Scene *scene, int frame) Sequence *seq, *best_seq = NULL; int best_machine = -1; - if (!ed) + if (!ed) { return NULL; + } for (seq = ed->seqbasep->first; seq; seq = seq->next) { - if (seq->flag & SEQ_MUTE || seq->startdisp > frame || seq->enddisp <= frame) + if (seq->flag & SEQ_MUTE || seq->startdisp > frame || seq->enddisp <= frame) { continue; + } /* Only use strips that generate an image, not ones that combine * other strips or apply some effect. */ if (ELEM(seq->type, @@ -4709,8 +4777,9 @@ bool BKE_sequence_base_shuffle_ex(ListBase *seqbasep, int new_frame = test->enddisp; for (seq = seqbasep->first; seq; seq = seq->next) { - if (seq->machine == orig_machine) + if (seq->machine == orig_machine) { new_frame = max_ii(new_frame, seq->enddisp); + } } test->machine = orig_machine; @@ -4770,8 +4839,9 @@ static int shuffle_seq_time_offset(Scene *scene, ListBase *seqbasep, char dir) } for (seq = seqbasep->first; seq; seq = seq->next) { - if (seq->tmp) + if (seq->tmp) { BKE_sequence_calc_disp(scene, seq); /* corrects dummy startdisp/enddisp values */ + } } return tot_ofs; @@ -4891,8 +4961,9 @@ static void seq_update_muting_recursive(ListBase *seqbasep, Sequence *metaseq, i if (seq->type == SEQ_TYPE_META) { /* if this is the current meta sequence, unmute because * all sequences above this were set to mute */ - if (seq == metaseq) + if (seq == metaseq) { seqmute = 0; + } seq_update_muting_recursive(&seq->seqbase, metaseq, seqmute); } @@ -4910,10 +4981,12 @@ void BKE_sequencer_update_muting(Editing *ed) /* mute all sounds up to current metastack list */ MetaStack *ms = ed->metastack.last; - if (ms) + if (ms) { seq_update_muting_recursive(&ed->seqbase, ms->parseq, 1); - else + } + else { seq_update_muting_recursive(&ed->seqbase, NULL, 0); + } } } @@ -5051,8 +5124,9 @@ void BKE_sequencer_offset_animdata(Scene *scene, Sequence *seq, int ofs) size_t str_len; FCurve *fcu; - if (scene->adt == NULL || ofs == 0 || scene->adt->action == NULL) + if (scene->adt == NULL || ofs == 0 || scene->adt->action == NULL) { return; + } str_len = sequencer_rna_path_prefix(str, seq->name + 2); @@ -5086,8 +5160,9 @@ void BKE_sequencer_dupe_animdata(Scene *scene, const char *name_src, const char FCurve *fcu_cpy; ListBase lb = {NULL, NULL}; - if (scene->adt == NULL || scene->adt->action == NULL) + if (scene->adt == NULL || scene->adt->action == NULL) { return; + } str_from_len = sequencer_rna_path_prefix(str_from, name_src); @@ -5115,8 +5190,9 @@ static void seq_free_animdata(Scene *scene, Sequence *seq) size_t str_len; FCurve *fcu; - if (scene->adt == NULL || scene->adt->action == NULL) + if (scene->adt == NULL || scene->adt->action == NULL) { return; + } str_len = sequencer_rna_path_prefix(str, seq->name + 2); @@ -5145,8 +5221,9 @@ Sequence *BKE_sequence_get_by_name(ListBase *seqbase, const char *name, bool rec Sequence *rseq = NULL; for (iseq = seqbase->first; iseq; iseq = iseq->next) { - if (STREQ(name, iseq->name + 2)) + if (STREQ(name, iseq->name + 2)) { return iseq; + } else if (recursive && (iseq->seqbase.first) && (rseq = BKE_sequence_get_by_name(&iseq->seqbase, name, 1))) { return rseq; @@ -5183,8 +5260,9 @@ Sequence *BKE_sequencer_active_get(Scene *scene) { Editing *ed = BKE_sequencer_editing_get(scene, false); - if (ed == NULL) + if (ed == NULL) { return NULL; + } return ed->act_seq; } @@ -5193,8 +5271,9 @@ void BKE_sequencer_active_set(Scene *scene, Sequence *seq) { Editing *ed = BKE_sequencer_editing_get(scene, false); - if (ed == NULL) + if (ed == NULL) { return; + } ed->act_seq = seq; } @@ -5264,8 +5343,9 @@ static void seq_load_apply(Main *bmain, Scene *scene, Sequence *seq, SeqLoadInfo } if (seq_load->flag & SEQ_LOAD_SOUND_CACHE) { - if (seq->sound) + if (seq->sound) { BKE_sound_cache(seq->sound); + } } seq_load->tot_success++; @@ -5296,6 +5376,7 @@ Sequence *BKE_sequence_alloc(ListBase *lb, int cfra, int machine) seq->scene_sound = NULL; seq->stereo3d_format = MEM_callocN(sizeof(Stereo3dFormat), "Sequence Stereo Format"); + seq->cache_flag = SEQ_CACHE_ALL_TYPES; return seq; } @@ -5327,8 +5408,9 @@ void BKE_sequence_init_colorspace(Sequence *seq) */ seq->alpha_mode = SEQ_ALPHA_STRAIGHT; if (ibuf) { - if (ibuf->flags & IB_alphamode_premul) + if (ibuf->flags & IB_alphamode_premul) { seq->alpha_mode = IMA_ALPHA_PREMUL; + } IMB_freeImBuf(ibuf); } @@ -5378,7 +5460,7 @@ Sequence *BKE_sequencer_add_image_strip(bContext *C, ListBase *seqbasep, SeqLoad seq = BKE_sequence_alloc(seqbasep, seq_load->start_frame, seq_load->channel); seq->type = SEQ_TYPE_IMAGE; - seq->blend_mode = SEQ_TYPE_CROSS; /* so alpha adjustment fade to the strip below */ + seq->blend_mode = SEQ_TYPE_ALPHAOVER; /* basic defaults */ seq->strip = strip = MEM_callocN(sizeof(Strip), "strip"); @@ -5388,8 +5470,9 @@ Sequence *BKE_sequencer_add_image_strip(bContext *C, ListBase *seqbasep, SeqLoad strip->stripdata = MEM_callocN(seq->len * sizeof(StripElem), "stripelem"); BLI_strncpy(strip->dir, seq_load->path, sizeof(strip->dir)); - if (seq_load->stereo3d_format) + if (seq_load->stereo3d_format) { *seq->stereo3d_format = *seq_load->stereo3d_format; + } seq->views_format = seq_load->views_format; seq->flag |= seq_load->flag & SEQ_USE_VIEWS; @@ -5436,7 +5519,8 @@ Sequence *BKE_sequencer_add_sound_strip(bContext *C, ListBase *seqbasep, SeqLoad /* basic defaults */ seq->strip = strip = MEM_callocN(sizeof(Strip), "strip"); - /* We add a very small negative offset here, because ceil(132.0) == 133.0, not nice with videos, see T47135. */ + /* We add a very small negative offset here, because + * ceil(132.0) == 133.0, not nice with videos, see T47135. */ seq->len = (int)ceil((double)info.length * FPS - 1e-4); strip->us = 1; @@ -5541,7 +5625,7 @@ Sequence *BKE_sequencer_add_movie_strip(bContext *C, ListBase *seqbasep, SeqLoad seq->flag |= seq_load->flag & SEQ_USE_VIEWS; seq->type = SEQ_TYPE_MOVIE; - seq->blend_mode = SEQ_TYPE_CROSS; /* so alpha adjustment fade to the strip below */ + seq->blend_mode = SEQ_TYPE_ALPHAOVER; for (i = 0; i < totfiles; i++) { if (anim_arr[i]) { @@ -5581,8 +5665,9 @@ Sequence *BKE_sequencer_add_movie_strip(bContext *C, ListBase *seqbasep, SeqLoad BKE_sequence_calc_disp(scene, seq); - if (seq_load->name[0] == '\0') + if (seq_load->name[0] == '\0') { BLI_strncpy(seq_load->name, se->name, sizeof(seq_load->name)); + } if (seq_load->flag & SEQ_LOAD_MOVIE_SOUND) { int start_frame_back = seq_load->start_frame; @@ -5649,8 +5734,9 @@ static Sequence *seq_dupli(const Scene *scene_src, } else if (seq->type == SEQ_TYPE_SCENE) { seqn->strip->stripdata = NULL; - if (seq->scene_sound) + if (seq->scene_sound) { seqn->scene_sound = BKE_sound_scene_add_scene_sound_defaults(scene_dst, seqn); + } } else if (seq->type == SEQ_TYPE_MOVIECLIP) { /* avoid assert */ @@ -5664,8 +5750,9 @@ static Sequence *seq_dupli(const Scene *scene_src, } else if (seq->type == SEQ_TYPE_SOUND_RAM) { seqn->strip->stripdata = MEM_dupallocN(seq->strip->stripdata); - if (seq->scene_sound) + if (seq->scene_sound) { seqn->scene_sound = BKE_sound_add_scene_sound_defaults(scene_dst, seqn); + } if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) { id_us_plus((ID *)seqn->sound); @@ -5677,8 +5764,9 @@ static Sequence *seq_dupli(const Scene *scene_src, else if (seq->type & SEQ_TYPE_EFFECT) { struct SeqEffectHandle sh; sh = BKE_sequence_get_effect(seq); - if (sh.copy) + if (sh.copy) { sh.copy(seq, seqn, flag); + } seqn->strip->stripdata = NULL; } @@ -5690,9 +5778,9 @@ static Sequence *seq_dupli(const Scene *scene_src, /* When using SEQ_DUPE_UNIQUE_NAME, it is mandatory to add new sequences in relevant container * (scene or meta's one), *before* checking for unique names. Otherwise the meta's list is empty * and hence we miss all seqs in that meta that have already been duplicated (see T55668). - * Note that unique name check itslef could be done at a later step in calling code, once all seqs - * have bee duplicated (that was first, simpler solution), but then handling of animation data will - * be broken (see T60194). */ + * Note that unique name check itslef could be done at a later step in calling code, once all + * seqs have bee duplicated (that was first, simpler solution), but then handling of animation + * data will be broken (see T60194). */ if (new_seq_list != NULL) { BLI_addtail(new_seq_list, seqn); } @@ -5715,12 +5803,15 @@ static void seq_new_fix_links_recursive(Sequence *seq) SequenceModifierData *smd; if (seq->type & SEQ_TYPE_EFFECT) { - if (seq->seq1 && seq->seq1->tmp) + if (seq->seq1 && seq->seq1->tmp) { seq->seq1 = seq->seq1->tmp; - if (seq->seq2 && seq->seq2->tmp) + } + if (seq->seq2 && seq->seq2->tmp) { seq->seq2 = seq->seq2->tmp; - if (seq->seq3 && seq->seq3->tmp) + } + if (seq->seq3 && seq->seq3->tmp) { seq->seq3 = seq->seq3->tmp; + } } else if (seq->type == SEQ_TYPE_META) { Sequence *seqn; @@ -5730,8 +5821,9 @@ static void seq_new_fix_links_recursive(Sequence *seq) } for (smd = seq->modifiers.first; smd; smd = smd->next) { - if (smd->mask_sequence && smd->mask_sequence->tmp) + if (smd->mask_sequence && smd->mask_sequence->tmp) { smd->mask_sequence = smd->mask_sequence->tmp; + } } } @@ -5840,12 +5932,14 @@ int BKE_sequencer_find_next_prev_edit(Scene *scene, int dist, best_dist, best_frame = cfra; int seq_frames[2], seq_frames_tot; - /* in case where both is passed, frame just finds the nearest end while frame_left the nearest start */ + /* In case where both is passed, + * frame just finds the nearest end while frame_left the nearest start. */ best_dist = MAXFRAME * 2; - if (ed == NULL) + if (ed == NULL) { return cfra; + } for (seq = ed->seqbasep->first; seq; seq = seq->next) { int i; @@ -5854,8 +5948,9 @@ int BKE_sequencer_find_next_prev_edit(Scene *scene, continue; } - if (do_unselected && (seq->flag & SELECT)) + if (do_unselected && (seq->flag & SELECT)) { continue; + } if (do_center) { seq_frames[0] = (seq->startdisp + seq->enddisp) / 2; @@ -5911,15 +6006,12 @@ static void sequencer_all_free_anim_ibufs(ListBase *seqbase, int cfra) } } -void BKE_sequencer_all_free_anim_ibufs(Main *bmain, int cfra) +void BKE_sequencer_all_free_anim_ibufs(Scene *scene, int cfra) { - BKE_sequencer_cache_cleanup(); - for (Scene *scene = bmain->scenes.first; scene != NULL; scene = scene->id.next) { - Editing *ed = BKE_sequencer_editing_get(scene, false); - if (ed == NULL) { - /* Ignore scenes without sequencer. */ - continue; - } - sequencer_all_free_anim_ibufs(&ed->seqbase, cfra); + Editing *ed = BKE_sequencer_editing_get(scene, false); + if (ed == NULL) { + return; } + sequencer_all_free_anim_ibufs(&ed->seqbase, cfra); + BKE_sequencer_cache_cleanup(scene); } diff --git a/source/blender/blenkernel/intern/shader_fx.c b/source/blender/blenkernel/intern/shader_fx.c index 98dbc3fc989..75503b8ca10 100644 --- a/source/blender/blenkernel/intern/shader_fx.c +++ b/source/blender/blenkernel/intern/shader_fx.c @@ -85,11 +85,13 @@ ShaderFxData *BKE_shaderfx_new(int type) fx->mode = eShaderFxMode_Realtime | eShaderFxMode_Render | eShaderFxMode_Expanded; fx->flag = eShaderFxFlag_StaticOverride_Local; - if (fxi->flags & eShaderFxTypeFlag_EnableInEditmode) + if (fxi->flags & eShaderFxTypeFlag_EnableInEditmode) { fx->mode |= eShaderFxMode_Editmode; + } - if (fxi->initData) + if (fxi->initData) { fxi->initData(fx); + } return fx; } @@ -118,10 +120,12 @@ void BKE_shaderfx_free_ex(ShaderFxData *fx, const int flag) } } - if (fxi->freeData) + if (fxi->freeData) { fxi->freeData(fx); - if (fx->error) + } + if (fx->error) { MEM_freeN(fx->error); + } MEM_freeN(fx); } @@ -219,9 +223,11 @@ ShaderFxData *BKE_shaderfx_findByType(Object *ob, ShaderFxType type) { ShaderFxData *fx = ob->shader_fx.first; - for (; fx; fx = fx->next) - if (fx->type == type) + for (; fx; fx = fx->next) { + if (fx->type == type) { break; + } + } return fx; } @@ -233,8 +239,9 @@ void BKE_shaderfx_foreachIDLink(Object *ob, ShaderFxIDWalkFunc walk, void *userD for (; fx; fx = fx->next) { const ShaderFxTypeInfo *fxi = BKE_shaderfxType_getInfo(fx->type); - if (fxi->foreachIDLink) + if (fxi->foreachIDLink) { fxi->foreachIDLink(fx, ob, walk, userData); + } else if (fxi->foreachObjectLink) { /* each Object can masquerade as an ID, so this should be OK */ ShaderFxObjectWalkFunc fp = (ShaderFxObjectWalkFunc)walk; diff --git a/source/blender/blenkernel/intern/shrinkwrap.c b/source/blender/blenkernel/intern/shrinkwrap.c index 7a9ccc66824..6a72b46a8f2 100644 --- a/source/blender/blenkernel/intern/shrinkwrap.c +++ b/source/blender/blenkernel/intern/shrinkwrap.c @@ -69,25 +69,25 @@ #define OUT_OF_MEMORY() ((void)printf("Shrinkwrap: Out of memory\n")) typedef struct ShrinkwrapCalcData { - ShrinkwrapModifierData *smd; //shrinkwrap modifier data + ShrinkwrapModifierData *smd; // shrinkwrap modifier data - struct Object *ob; //object we are applying shrinkwrap to + struct Object *ob; // object we are applying shrinkwrap to - struct MVert *vert; //Array of verts being projected (to fetch normals or other data) - float (*vertexCos)[3]; //vertexs being shrinkwraped + struct MVert *vert; // Array of verts being projected (to fetch normals or other data) + float (*vertexCos)[3]; // vertexs being shrinkwraped int numVerts; - struct MDeformVert *dvert; //Pointer to mdeform array - int vgroup; //Vertex group num + struct MDeformVert *dvert; // Pointer to mdeform array + int vgroup; // Vertex group num bool invert_vgroup; /* invert vertex group influence */ - struct Mesh *target; //mesh we are shrinking to - struct SpaceTransform local2target; //transform to move between local and target space + struct Mesh *target; // mesh we are shrinking to + struct SpaceTransform local2target; // transform to move between local and target space struct ShrinkwrapTreeData *tree; // mesh BVH tree data struct Object *aux_target; - float keepDist; //Distance to keep above target surface (units are in local space) + float keepDist; // Distance to keep above target surface (units are in local space) } ShrinkwrapCalcData; typedef struct ShrinkwrapCalcCBData { @@ -375,13 +375,15 @@ static void shrinkwrap_calc_nearest_vertex_cb_ex(void *__restrict userdata, /* Use local proximity heuristics (to reduce the nearest search) * - * If we already had an hit before.. we assume this vertex is going to have a close hit to that other vertex - * so we can initiate the "nearest.dist" with the expected value to that last hit. + * If we already had an hit before.. we assume this vertex is going to have a close hit to that + * other vertex so we can initiate the "nearest.dist" with the expected value to that last hit. * This will lead in pruning of the search tree. */ - if (nearest->index != -1) + if (nearest->index != -1) { nearest->dist_sq = len_squared_v3v3(tmp_co, nearest->co); - else + } + else { nearest->dist_sq = FLT_MAX; + } BLI_bvhtree_find_nearest(treeData->tree, tmp_co, nearest, treeData->nearest_callback, treeData); @@ -536,8 +538,9 @@ static void shrinkwrap_calc_normal_projection_cb_ex(void *__restrict userdata, if (calc->vert != NULL && calc->smd->projAxis == MOD_SHRINKWRAP_PROJECT_OVER_NORMAL) { /* calc->vert contains verts from evaluated mesh. */ - /* These coordinates are deformed by vertexCos only for normal projection (to get correct normals) */ - /* for other cases calc->verts contains undeformed coordinates and vertexCos should be used */ + /* These coordinates are deformed by vertexCos only for normal projection + * (to get correct normals) for other cases calc->verts contains undeformed coordinates and + * vertexCos should be used */ copy_v3_v3(tmp_co, calc->vert[i].co); normal_short_to_float_v3(tmp_no, calc->vert[i].no); } @@ -547,8 +550,9 @@ static void shrinkwrap_calc_normal_projection_cb_ex(void *__restrict userdata, } hit->index = -1; - hit->dist = - BVH_RAYCAST_DIST_MAX; /* TODO: we should use FLT_MAX here, but sweepsphere code isn't prepared for that */ + + /* TODO: we should use FLT_MAX here, but sweepsphere code isn't prepared for that */ + hit->dist = BVH_RAYCAST_DIST_MAX; bool is_aux = false; @@ -647,23 +651,28 @@ static void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *calc) /* If the user doesn't allows to project in any direction of projection axis * then there's nothing todo. */ if ((calc->smd->shrinkOpts & - (MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR | MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR)) == 0) + (MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR | MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR)) == 0) { return; + } /* Prepare data to retrieve the direction in which we should project each vertex */ if (calc->smd->projAxis == MOD_SHRINKWRAP_PROJECT_OVER_NORMAL) { - if (calc->vert == NULL) + if (calc->vert == NULL) { return; + } } else { /* The code supports any axis that is a combination of X,Y,Z * although currently UI only allows to set the 3 different axis */ - if (calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_X_AXIS) + if (calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_X_AXIS) { proj_axis[0] = 1.0f; - if (calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_Y_AXIS) + } + if (calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_Y_AXIS) { proj_axis[1] = 1.0f; - if (calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_Z_AXIS) + } + if (calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_Z_AXIS) { proj_axis[2] = 1.0f; + } normalize_v3(proj_axis); @@ -675,8 +684,9 @@ static void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *calc) if (calc->aux_target) { auxMesh = BKE_modifier_get_evaluated_mesh_from_evaluated_object(calc->aux_target, false); - if (!auxMesh) + if (!auxMesh) { return; + } BLI_SPACE_TRANSFORM_SETUP(&local2aux, calc->ob, calc->aux_target); } @@ -930,7 +940,8 @@ static bool update_hit(BVHTreeNearest *nearest, return false; } -/* Target projection on a non-manifold boundary edge - treats it like an infinitely thin cylinder. */ +/* Target projection on a non-manifold boundary edge - + * treats it like an infinitely thin cylinder. */ static void target_project_edge(const ShrinkwrapTreeData *tree, int index, const float co[3], @@ -1036,8 +1047,9 @@ static void mesh_looptri_target_project(void *userdata, nearest->dist_sq); #endif - if (dist_sq >= nearest->dist_sq) + if (dist_sq >= nearest->dist_sq) { return; + } /* Decode normals */ normal_short_to_float_v3(vtri_no[0], vtri[0]->no); @@ -1133,8 +1145,8 @@ static void shrinkwrap_calc_nearest_surface_point_cb_ex(void *__restrict userdat /* Use local proximity heuristics (to reduce the nearest search) * - * If we already had an hit before.. we assume this vertex is going to have a close hit to that other vertex - * so we can initiate the "nearest.dist" with the expected value to that last hit. + * If we already had an hit before.. we assume this vertex is going to have a close hit to that + * other vertex so we can initiate the "nearest.dist" with the expected value to that last hit. * This will lead in pruning of the search tree. */ if (nearest->index != -1) { if (calc->smd->shrinkType == MOD_SHRINKWRAP_TARGET_PROJECT) { @@ -1146,8 +1158,9 @@ static void shrinkwrap_calc_nearest_surface_point_cb_ex(void *__restrict userdat nearest->dist_sq = len_squared_v3v3(tmp_co, nearest->co); } } - else + else { nearest->dist_sq = FLT_MAX; + } BKE_shrinkwrap_find_nearest_surface(data->tree, nearest, tmp_co, calc->smd->shrinkType); @@ -1375,10 +1388,12 @@ void shrinkwrapModifier_deform(ShrinkwrapModifierData *smd, ShrinkwrapCalcData calc = NULL_ShrinkwrapCalcData; /* remove loop dependencies on derived meshes (TODO should this be done elsewhere?) */ - if (smd->target == ob) + if (smd->target == ob) { smd->target = NULL; - if (smd->auxTarget == ob) + } + if (smd->auxTarget == ob) { smd->auxTarget = NULL; + } /* Configure Shrinkwrap calc data */ calc.smd = smd; @@ -1461,6 +1476,7 @@ void shrinkwrapModifier_deform(ShrinkwrapModifierData *smd, } /* free memory */ - if (ss_mesh) + if (ss_mesh) { ss_mesh->release(ss_mesh); + } } diff --git a/source/blender/blenkernel/intern/smoke.c b/source/blender/blenkernel/intern/smoke.c index 23cdf802c81..d6858e2d4d2 100644 --- a/source/blender/blenkernel/intern/smoke.c +++ b/source/blender/blenkernel/intern/smoke.c @@ -82,14 +82,13 @@ //#define DEBUG_TIME +#include "smoke_API.h" + #ifdef DEBUG_TIME # include "PIL_time.h" #endif #ifdef WITH_SMOKE - -# include "smoke_API.h" - # include "BLI_task.h" # include "BLI_kdtree.h" # include "BLI_voxel.h" @@ -120,7 +119,7 @@ struct WTURBULENCE *smoke_turbulence_init(int *UNUSED(res), { return NULL; } -//struct FLUID_3D *smoke_init(int *UNUSED(res), float *UNUSED(dx), float *UNUSED(dtdef), int UNUSED(use_heat), int UNUSED(use_fire), int UNUSED(use_colors)) { return NULL; } + void smoke_free(struct FLUID_3D *UNUSED(fluid)) { } @@ -173,8 +172,9 @@ void BKE_smoke_reallocate_fluid(SmokeDomainSettings *sds, float dx, int res[3], int use_fire = (sds->active_fields & SM_ACTIVE_FIRE); int use_colors = (sds->active_fields & SM_ACTIVE_COLORS); - if (free_old && sds->fluid) + if (free_old && sds->fluid) { smoke_free(sds->fluid); + } if (!min_iii(res[0], res[1], res[2])) { sds->fluid = NULL; return; @@ -194,8 +194,9 @@ void BKE_smoke_reallocate_fluid(SmokeDomainSettings *sds, float dx, int res[3], &(sds->flame_max_temp)); /* reallocate shadow buffer */ - if (sds->shadow) + if (sds->shadow) { MEM_freeN(sds->shadow); + } sds->shadow = MEM_callocN(sizeof(float) * res[0] * res[1] * res[2], "SmokeDomainShadow"); } @@ -207,8 +208,9 @@ void BKE_smoke_reallocate_highres_fluid(SmokeDomainSettings *sds, int use_fire = (sds->active_fields & (SM_ACTIVE_HEAT | SM_ACTIVE_FIRE)); int use_colors = (sds->active_fields & SM_ACTIVE_COLORS); - if (free_old && sds->wt) + if (free_old && sds->wt) { smoke_turbulence_free(sds->wt); + } if (!min_iii(res[0], res[1], res[2])) { sds->wt = NULL; return; @@ -289,8 +291,9 @@ static void smoke_set_domain_from_mesh(SmokeDomainSettings *sds, // prevent crash when initializing a plane as domain if (!init_resolution || (size[0] < FLT_EPSILON) || (size[1] < FLT_EPSILON) || - (size[2] < FLT_EPSILON)) + (size[2] < FLT_EPSILON)) { return; + } /* define grid resolutions from longest domain side */ if (size[0] >= MAX2(size[1], size[2])) { @@ -358,10 +361,10 @@ static int smokeModifier_init(SmokeModifierData *smd, Object *ob, int scene_fram BKE_smoke_reallocate_highres_fluid(sds, sds->dx, sds->res, 0); } /* allocate shadow buffer */ - if (!sds->shadow) + if (!sds->shadow) { sds->shadow = MEM_callocN(sizeof(float) * sds->res[0] * sds->res[1] * sds->res[2], "SmokeDomainShadow"); - + } return 1; } else if ((smd->type & MOD_SMOKE_TYPE_FLOW) && smd->flow) { @@ -387,21 +390,26 @@ static int smokeModifier_init(SmokeModifierData *smd, Object *ob, int scene_fram static void smokeModifier_freeDomain(SmokeModifierData *smd) { if (smd->domain) { - if (smd->domain->shadow) + if (smd->domain->shadow) { MEM_freeN(smd->domain->shadow); + } smd->domain->shadow = NULL; - if (smd->domain->fluid) + if (smd->domain->fluid) { smoke_free(smd->domain->fluid); + } - if (smd->domain->fluid_mutex) + if (smd->domain->fluid_mutex) { BLI_rw_mutex_free(smd->domain->fluid_mutex); + } - if (smd->domain->wt) + if (smd->domain->wt) { smoke_turbulence_free(smd->domain->wt); + } - if (smd->domain->effector_weights) + if (smd->domain->effector_weights) { MEM_freeN(smd->domain->effector_weights); + } smd->domain->effector_weights = NULL; if (!(smd->modifier.flag & eModifierFlag_SharedCaches)) { @@ -421,10 +429,12 @@ static void smokeModifier_freeDomain(SmokeModifierData *smd) static void smokeModifier_freeFlow(SmokeModifierData *smd) { if (smd->flow) { - if (smd->flow->mesh) + if (smd->flow->mesh) { BKE_id_free(NULL, smd->flow->mesh); - if (smd->flow->verts_old) + } + if (smd->flow->verts_old) { MEM_freeN(smd->flow->verts_old); + } MEM_freeN(smd->flow); smd->flow = NULL; } @@ -442,8 +452,9 @@ static void smokeModifier_freeCollision(SmokeModifierData *smd) } } - if (smd->coll->mesh) + if (smd->coll->mesh) { BKE_id_free(NULL, smd->coll->mesh); + } smd->coll->mesh = NULL; MEM_freeN(smd->coll); @@ -463,19 +474,22 @@ static void smokeModifier_reset_ex(struct SmokeModifierData *smd, bool need_lock { if (smd) { if (smd->domain) { - if (smd->domain->shadow) + if (smd->domain->shadow) { MEM_freeN(smd->domain->shadow); + } smd->domain->shadow = NULL; if (smd->domain->fluid) { - if (need_lock) + if (need_lock) { BLI_rw_mutex_lock(smd->domain->fluid_mutex, THREAD_LOCK_WRITE); + } smoke_free(smd->domain->fluid); smd->domain->fluid = NULL; - if (need_lock) + if (need_lock) { BLI_rw_mutex_unlock(smd->domain->fluid_mutex); + } } smokeModifier_reset_turbulence(smd); @@ -485,8 +499,9 @@ static void smokeModifier_reset_ex(struct SmokeModifierData *smd, bool need_lock smd->domain->active_fields = 0; } else if (smd->flow) { - if (smd->flow->verts_old) + if (smd->flow->verts_old) { MEM_freeN(smd->flow->verts_old); + } smd->flow->verts_old = NULL; smd->flow->numverts = 0; } @@ -519,8 +534,9 @@ void smokeModifier_createType(struct SmokeModifierData *smd) { if (smd) { if (smd->type & MOD_SMOKE_TYPE_DOMAIN) { - if (smd->domain) + if (smd->domain) { smokeModifier_freeDomain(smd); + } smd->domain = MEM_callocN(sizeof(SmokeDomainSettings), "SmokeDomain"); @@ -593,8 +609,9 @@ void smokeModifier_createType(struct SmokeModifierData *smd) smd->domain->clipping = 1e-3f; } else if (smd->type & MOD_SMOKE_TYPE_FLOW) { - if (smd->flow) + if (smd->flow) { smokeModifier_freeFlow(smd); + } smd->flow = MEM_callocN(sizeof(SmokeFlowSettings), "SmokeFlow"); @@ -621,8 +638,9 @@ void smokeModifier_createType(struct SmokeModifierData *smd) smd->flow->psys = NULL; } else if (smd->type & MOD_SMOKE_TYPE_COLL) { - if (smd->coll) + if (smd->coll) { smokeModifier_freeCollision(smd); + } smd->coll = MEM_callocN(sizeof(SmokeCollSettings), "SmokeColl"); @@ -873,8 +891,9 @@ static void obstacles_from_mesh(Object *coll_ob, int *num_obstacles, float dt) { - if (!scs->mesh) + if (!scs->mesh) { return; + } { Mesh *me = NULL; MVert *mvert = NULL; @@ -895,14 +914,16 @@ static void obstacles_from_mesh(Object *coll_ob, // DG TODO // if (scs->type > SM_COLL_STATIC) - // if line above is used, the code is in trouble if the object moves but is declared as "does not move" + // if line above is used, the code is in trouble if the object moves + // but is declared as "does not move". { vert_vel = MEM_callocN(sizeof(float) * numverts * 3, "smoke_obs_velocity"); if (scs->numverts != numverts || !scs->verts_old) { - if (scs->verts_old) + if (scs->verts_old) { MEM_freeN(scs->verts_old); + } scs->verts_old = MEM_callocN(sizeof(float) * numverts * 3, "smoke_obs_verts_old"); scs->numverts = numverts; @@ -963,8 +984,9 @@ static void obstacles_from_mesh(Object *coll_ob, free_bvhtree_from_mesh(&treeData); BKE_id_free(NULL, me); - if (vert_vel) + if (vert_vel) { MEM_freeN(vert_vel); + } } } @@ -1084,10 +1106,12 @@ static void em_boundInsert(EmissionMap *em, float point[3]) } else { for (; i < 3; i++) { - if (point[i] < em->min[i]) + if (point[i] < em->min[i]) { em->min[i] = (int)floor(point[i]); - if (point[i] > em->max[i]) + } + if (point[i] > em->max[i]) { em->max[i] = (int)ceil(point[i]); + } } } } @@ -1127,15 +1151,17 @@ static void em_allocateData(EmissionMap *em, bool use_velocity, int hires_mul) for (i = 0; i < 3; i++) { res[i] = em->max[i] - em->min[i]; - if (res[i] <= 0) + if (res[i] <= 0) { return; + } } em->total_cells = res[0] * res[1] * res[2]; copy_v3_v3_int(em->res, res); em->influence = MEM_callocN(sizeof(float) * em->total_cells, "smoke_flow_influence"); - if (use_velocity) + if (use_velocity) { em->velocity = MEM_callocN(sizeof(float) * em->total_cells * 3, "smoke_flow_velocity"); + } /* allocate high resolution map if required */ if (hires_mul > 1) { @@ -1155,12 +1181,15 @@ static void em_allocateData(EmissionMap *em, bool use_velocity, int hires_mul) static void em_freeData(EmissionMap *em) { - if (em->influence) + if (em->influence) { MEM_freeN(em->influence); - if (em->influence_high) + } + if (em->influence_high) { MEM_freeN(em->influence_high); - if (em->velocity) + } + if (em->velocity) { MEM_freeN(em->velocity); + } } static void em_combineMaps( @@ -1187,8 +1216,8 @@ static void em_combineMaps( em_allocateData(output, (em1.velocity || em2->velocity), hires_multiplier); /* base resolution inputs */ - for (x = output->min[0]; x < output->max[0]; x++) - for (y = output->min[1]; y < output->max[1]; y++) + for (x = output->min[0]; x < output->max[0]; x++) { + for (y = output->min[1]; y < output->max[1]; y++) { for (z = output->min[2]; z < output->max[2]; z++) { int index_out = smoke_get_index(x - output->min[0], output->res[0], @@ -1234,11 +1263,13 @@ static void em_combineMaps( } } } // low res loop + } + } /* initialize high resolution input if available */ if (output->influence_high) { - for (x = output->hmin[0]; x < output->hmax[0]; x++) - for (y = output->hmin[1]; y < output->hmax[1]; y++) + for (x = output->hmin[0]; x < output->hmax[0]; x++) { + for (y = output->hmin[1]; y < output->hmax[1]; y++) { for (z = output->hmin[2]; z < output->hmax[2]; z++) { int index_out = smoke_get_index(x - output->hmin[0], output->hres[0], @@ -1271,6 +1302,8 @@ static void em_combineMaps( } } } // high res loop + } + } } /* free original data */ @@ -1394,12 +1427,15 @@ static void emit_from_particles(Object *flow_ob, sim.psys->lattice_deform_data = psys_create_lattice_deform_data(&sim); /* prepare curvemapping tables */ - if ((psys->part->child_flag & PART_CHILD_USE_CLUMP_CURVE) && psys->part->clumpcurve) + if ((psys->part->child_flag & PART_CHILD_USE_CLUMP_CURVE) && psys->part->clumpcurve) { curvemapping_changed_all(psys->part->clumpcurve); - if ((psys->part->child_flag & PART_CHILD_USE_ROUGH_CURVE) && psys->part->roughcurve) + } + if ((psys->part->child_flag & PART_CHILD_USE_ROUGH_CURVE) && psys->part->roughcurve) { curvemapping_changed_all(psys->part->roughcurve); - if ((psys->part->child_flag & PART_CHILD_USE_TWIST_CURVE) && psys->part->twistcurve) + } + if ((psys->part->child_flag & PART_CHILD_USE_TWIST_CURVE) && psys->part->twistcurve) { curvemapping_changed_all(psys->part->twistcurve); + } /* initialize particle cache */ if (psys->part->type == PART_HAIR) { @@ -1430,19 +1466,22 @@ static void emit_from_particles(Object *flow_ob, ParticleKey state; float *pos; if (p < totpart) { - if (psys->particles[p].flag & (PARS_NO_DISP | PARS_UNEXIST)) + if (psys->particles[p].flag & (PARS_NO_DISP | PARS_UNEXIST)) { continue; + } } else { /* handle child particle */ ChildParticle *cpa = &psys->child[p - totpart]; - if (psys->particles[cpa->parent].flag & (PARS_NO_DISP | PARS_UNEXIST)) + if (psys->particles[cpa->parent].flag & (PARS_NO_DISP | PARS_UNEXIST)) { continue; + } } state.time = DEG_get_ctime(depsgraph); /* use depsgraph time */ - if (psys_get_particle_state(&sim, p, &state, 0) == 0) + if (psys_get_particle_state(&sim, p, &state, 0) == 0) { continue; + } /* location */ pos = &particle_pos[valid_particles * 3]; @@ -1484,8 +1523,9 @@ static void emit_from_particles(Object *flow_ob, break; } } - if (badcell) + if (badcell) { continue; + } /* get cell index */ index = smoke_get_index(cell[0], em->res[0], cell[1], em->res[1], cell[2]); /* Add influence to emission map */ @@ -1538,10 +1578,12 @@ static void emit_from_particles(Object *flow_ob, } /* free data */ - if (particle_pos) + if (particle_pos) { MEM_freeN(particle_pos); - if (particle_vel) + } + if (particle_vel) { MEM_freeN(particle_vel); + } } } @@ -1619,8 +1661,9 @@ static void sample_mesh(SmokeFlowSettings *sfs, CLAMP(sample_str, 0.0f, 1.0f); sample_str = pow(1.0f - sample_str, 0.5f); } - else + else { sample_str = 0.0f; + } /* calculate barycentric weights for nearest point */ v1 = mloop[mlooptri[f_index].tri[0]].v; @@ -1638,7 +1681,8 @@ static void sample_mesh(SmokeFlowSettings *sfs, interp_v3_v3v3v3(hit_normal, n1, n2, n3, weights); normalize_v3(hit_normal); /* apply normal directional and random velocity - * - TODO: random disabled for now since it doesn't really work well as pressure calc smoothens it out... */ + * - TODO: random disabled for now since it doesn't really work well + * as pressure calc smoothens it out. */ velocity_map[index * 3] += hit_normal[0] * sfs->vel_normal * 0.25f; velocity_map[index * 3 + 1] += hit_normal[1] * sfs->vel_normal * 0.25f; velocity_map[index * 3 + 2] += hit_normal[2] * sfs->vel_normal * 0.25f; @@ -1777,7 +1821,10 @@ static void emit_from_mesh_task_cb(void *__restrict userdata, const int index = smoke_get_index( x - data->min[0], data->res[0], y - data->min[1], data->res[1], z - data->min[2]); const float ray_start[3] = { - lx + 0.5f * data->hr, ly + 0.5f * data->hr, lz + 0.5f * data->hr}; + lx + 0.5f * data->hr, + ly + 0.5f * data->hr, + lz + 0.5f * data->hr, + }; sample_mesh(data->sfs, data->mvert, @@ -1847,8 +1894,9 @@ static void emit_from_mesh( vert_vel = MEM_callocN(sizeof(float) * numOfVerts * 3, "smoke_flow_velocity"); if (sfs->numverts != numOfVerts || !sfs->verts_old) { - if (sfs->verts_old) + if (sfs->verts_old) { MEM_freeN(sfs->verts_old); + } sfs->verts_old = MEM_callocN(sizeof(float) * numOfVerts * 3, "smoke_flow_verts_old"); sfs->numverts = numOfVerts; } @@ -1977,8 +2025,8 @@ static void adjustDomainResolution(SmokeDomainSettings *sds, INIT_MINMAX(min_vel, max_vel); /* Calculate bounds for current domain content */ - for (x = sds->res_min[0]; x < sds->res_max[0]; x++) - for (y = sds->res_min[1]; y < sds->res_max[1]; y++) + for (x = sds->res_min[0]; x < sds->res_max[0]; x++) { + for (y = sds->res_min[1]; y < sds->res_max[1]; y++) { for (z = sds->res_min[2]; z < sds->res_max[2]; z++) { int xn = x - new_shift[0]; int yn = y - new_shift[1]; @@ -1988,8 +2036,9 @@ static void adjustDomainResolution(SmokeDomainSettings *sds, /* skip if cell already belongs to new area */ if (xn >= min[0] && xn <= max[0] && yn >= min[1] && yn <= max[1] && zn >= min[2] && - zn <= max[2]) + zn <= max[2]) { continue; + } index = smoke_get_index(x - sds->res_min[0], sds->res[0], @@ -2006,8 +2055,8 @@ static void adjustDomainResolution(SmokeDomainSettings *sds, int yy = (y - sds->res_min[1]) * block_size; int zz = (z - sds->res_min[2]) * block_size; - for (i = 0; i < block_size; i++) - for (j = 0; j < block_size; j++) + for (i = 0; i < block_size; i++) { + for (j = 0; j < block_size; j++) { for (k = 0; k < block_size; k++) { int big_index = smoke_get_index(xx + i, wt_res[0], yy + j, wt_res[1], zz + k); float den = (bigfuel) ? MAX2(bigdensity[big_index], bigfuel[big_index]) : @@ -2016,45 +2065,61 @@ static void adjustDomainResolution(SmokeDomainSettings *sds, max_den = den; } } + } + } } /* content bounds (use shifted coordinates) */ if (max_den >= sds->adapt_threshold) { - if (min[0] > xn) + if (min[0] > xn) { min[0] = xn; - if (min[1] > yn) + } + if (min[1] > yn) { min[1] = yn; - if (min[2] > zn) + } + if (min[2] > zn) { min[2] = zn; - if (max[0] < xn) + } + if (max[0] < xn) { max[0] = xn; - if (max[1] < yn) + } + if (max[1] < yn) { max[1] = yn; - if (max[2] < zn) + } + if (max[2] < zn) { max[2] = zn; + } } /* velocity bounds */ - if (min_vel[0] > vx[index]) + if (min_vel[0] > vx[index]) { min_vel[0] = vx[index]; - if (min_vel[1] > vy[index]) + } + if (min_vel[1] > vy[index]) { min_vel[1] = vy[index]; - if (min_vel[2] > vz[index]) + } + if (min_vel[2] > vz[index]) { min_vel[2] = vz[index]; - if (max_vel[0] < vx[index]) + } + if (max_vel[0] < vx[index]) { max_vel[0] = vx[index]; - if (max_vel[1] < vy[index]) + } + if (max_vel[1] < vy[index]) { max_vel[1] = vy[index]; - if (max_vel[2] < vz[index]) + } + if (max_vel[2] < vz[index]) { max_vel[2] = vz[index]; + } } + } + } /* also apply emission maps */ for (int i = 0; i < numflowobj; i++) { EmissionMap *em = &emaps[i]; - for (x = em->min[0]; x < em->max[0]; x++) - for (y = em->min[1]; y < em->max[1]; y++) + for (x = em->min[0]; x < em->max[0]; x++) { + for (y = em->min[1]; y < em->max[1]; y++) { for (z = em->min[2]; z < em->max[2]; z++) { int index = smoke_get_index( x - em->min[0], em->res[0], y - em->min[1], em->res[1], z - em->min[2]); @@ -2062,20 +2127,28 @@ static void adjustDomainResolution(SmokeDomainSettings *sds, /* density bounds */ if (max_den >= sds->adapt_threshold) { - if (min[0] > x) + if (min[0] > x) { min[0] = x; - if (min[1] > y) + } + if (min[1] > y) { min[1] = y; - if (min[2] > z) + } + if (min[2] > z) { min[2] = z; - if (max[0] < x) + } + if (max[0] < x) { max[0] = x; - if (max[1] < y) + } + if (max[1] < y) { max[1] = y; - if (max[2] < z) + } + if (max[2] < z) { max[2] = z; + } } } + } + } } /* calculate new bounds based on these values */ @@ -2088,8 +2161,9 @@ static void adjustDomainResolution(SmokeDomainSettings *sds, res[i] = max[i] - min[i]; total_cells *= res[i]; - if (new_shift[i]) + if (new_shift[i]) { shift_changed = 1; + } /* if no content set minimum dimensions */ if (res[i] <= 0) { @@ -2103,8 +2177,9 @@ static void adjustDomainResolution(SmokeDomainSettings *sds, total_cells = 1; break; } - if (min[i] != sds->res_min[i] || max[i] != sds->res_max[i]) + if (min[i] != sds->res_min[i] || max[i] != sds->res_max[i]) { res_changed = 1; + } } if (res_changed || shift_changed) { @@ -2191,8 +2266,8 @@ static void adjustDomainResolution(SmokeDomainSettings *sds, &n_wt_tcw); } - for (x = sds->res_min[0]; x < sds->res_max[0]; x++) - for (y = sds->res_min[1]; y < sds->res_max[1]; y++) + for (x = sds->res_min[0]; x < sds->res_max[0]; x++) { + for (y = sds->res_min[1]; y < sds->res_max[1]; y++) { for (z = sds->res_min[2]; z < sds->res_max[2]; z++) { /* old grid index */ int xo = x - sds->res_min[0]; @@ -2206,8 +2281,9 @@ static void adjustDomainResolution(SmokeDomainSettings *sds, int index_new = smoke_get_index(xn, res[0], yn, res[1], zn); /* skip if outside new domain */ - if (xn < 0 || xn >= res[0] || yn < 0 || yn >= res[1] || zn < 0 || zn >= res[2]) + if (xn < 0 || xn >= res[0] || yn < 0 || yn >= res[1] || zn < 0 || zn >= res[2]) { continue; + } /* copy data */ n_dens[index_new] = o_dens[index_old]; @@ -2247,8 +2323,8 @@ static void adjustDomainResolution(SmokeDomainSettings *sds, n_wt_tcv[index_new] = o_wt_tcv[index_old]; n_wt_tcw[index_new] = o_wt_tcw[index_old]; - for (i = 0; i < block_size; i++) - for (j = 0; j < block_size; j++) + for (i = 0; i < block_size; i++) { + for (j = 0; j < block_size; j++) { for (k = 0; k < block_size; k++) { int big_index_old = smoke_get_index( xx_o + i, wt_res_old[0], yy_o + j, wt_res_old[1], zz_o + k); @@ -2267,12 +2343,17 @@ static void adjustDomainResolution(SmokeDomainSettings *sds, n_wt_b[big_index_new] = o_wt_b[big_index_old]; } } + } + } } } + } + } } smoke_free(fluid_old); - if (turb_old) + if (turb_old) { smoke_turbulence_free(turb_old); + } /* set new domain dimensions */ copy_v3_v3_int(sds->res_min, min); @@ -2329,12 +2410,14 @@ BLI_INLINE void apply_inflow_fields(SmokeFlowSettings *sfs, /* absolute */ if (absolute_flow) { if (sfs->type != MOD_SMOKE_FLOW_TYPE_FIRE) { - if (dens_flow > density[index]) + if (dens_flow > density[index]) { density[index] = dens_flow; + } } if (sfs->type != MOD_SMOKE_FLOW_TYPE_SMOKE && fuel && fuel_flow) { - if (fuel_flow > fuel[index]) + if (fuel_flow > fuel[index]) { fuel[index] = fuel_flow; + } } } /* additive */ @@ -2453,7 +2536,7 @@ static void update_flowsfluids( EmissionMap em_temp = {NULL}; float sample_size = 1.0f / (float)(subframes + 1); # if 0 - float prev_frame_pos = sample_size * (float)(subframe+1); + float prev_frame_pos = sample_size * (float)(subframe + 1); # endif float sdt = dt * sample_size; int hires_multiplier = 1; @@ -2593,7 +2676,7 @@ static void update_flowsfluids( float *velocity_x = smoke_get_velocity_x(sds->fluid); float *velocity_y = smoke_get_velocity_y(sds->fluid); float *velocity_z = smoke_get_velocity_z(sds->fluid); - //unsigned char *obstacle = smoke_get_obstacle(sds->fluid); + // unsigned char *obstacle = smoke_get_obstacle(sds->fluid); // DG TODO UNUSED unsigned char *obstacleAnim = smoke_get_obstacle_anim(sds->fluid); int bigres[3]; float *velocity_map = em->velocity; @@ -2604,8 +2687,8 @@ static void update_flowsfluids( size_t e_index, d_index, index_big; // loop through every emission map cell - for (gx = em->min[0]; gx < em->max[0]; gx++) - for (gy = em->min[1]; gy < em->max[1]; gy++) + for (gx = em->min[0]; gx < em->max[0]; gx++) { + for (gy = em->min[1]; gy < em->max[1]; gy++) { for (gz = em->min[2]; gz < em->max[2]; gz++) { /* get emission map index */ ex = gx - em->min[0]; @@ -2620,8 +2703,9 @@ static void update_flowsfluids( d_index = smoke_get_index(dx, sds->res[0], dy, sds->res[1], dz); /* make sure emission cell is inside the new domain boundary */ if (dx < 0 || dy < 0 || dz < 0 || dx >= sds->res[0] || dy >= sds->res[1] || - dz >= sds->res[2]) + dz >= sds->res[2]) { continue; + } if (sfs->type == MOD_SMOKE_FLOW_TYPE_OUTFLOW) { // outflow apply_outflow_fields( @@ -2652,7 +2736,8 @@ static void update_flowsfluids( /* loop through high res blocks if high res enabled */ if (bigdensity) { - // neighbor cell emission densities (for high resolution smoke smooth interpolation) + /* Neighbor cell emission densities + * (for high resolution smoke smooth interpolation). */ float c000, c001, c010, c011, c100, c101, c110, c111; smoke_turbulence_get_res(sds->wt, bigres); @@ -2687,8 +2772,8 @@ static void update_flowsfluids( c111 = emission_map[smoke_get_index( ex, em->res[0], ey, em->res[1], ez)]; // this cell - for (ii = 0; ii < block_size; ii++) - for (jj = 0; jj < block_size; jj++) + for (ii = 0; ii < block_size; ii++) { + for (jj = 0; jj < block_size; jj++) { for (kk = 0; kk < block_size; kk++) { float fx, fy, fz, interpolated_value; @@ -2770,8 +2855,12 @@ static void update_flowsfluids( bigcolor_b); } } // hires loop - } // bigdensity - } // low res loop + } + } + } // bigdensity + } // low res loop + } + } // free emission maps em_freeData(em); @@ -2781,8 +2870,9 @@ static void update_flowsfluids( } BKE_collision_objects_free(flowobjs); - if (emaps) + if (emaps) { MEM_freeN(emaps); + } } typedef struct UpdateEffectorsData { @@ -2947,12 +3037,9 @@ static void step(Depsgraph *depsgraph, update_obstacles(depsgraph, ob, sds, dtSubdiv, substep, totalSubsteps); if (sds->total_cells > 1) { - update_effectors( - depsgraph, - scene, - ob, - sds, - dtSubdiv); // DG TODO? problem --> uses forces instead of velocity, need to check how they need to be changed with variable dt + // DG TODO? problem --> uses forces instead of velocity, + // need to check how they need to be changed with variable dt. + update_effectors(depsgraph, scene, ob, sds, dtSubdiv); smoke_step(sds->fluid, gravity, dtSubdiv); } } @@ -3109,11 +3196,13 @@ static void smokeModifier_process( const int scene_framenr = (int)DEG_get_ctime(depsgraph); if ((smd->type & MOD_SMOKE_TYPE_FLOW)) { - if (scene_framenr >= smd->time) + if (scene_framenr >= smd->time) { smokeModifier_init(smd, ob, scene_framenr, me); + } - if (smd->flow->mesh) + if (smd->flow->mesh) { BKE_id_free(NULL, smd->flow->mesh); + } smd->flow->mesh = BKE_mesh_copy_for_eval(me, false); if (scene_framenr > smd->time) { @@ -3125,12 +3214,14 @@ static void smokeModifier_process( } } else if (smd->type & MOD_SMOKE_TYPE_COLL) { - if (scene_framenr >= smd->time) + if (scene_framenr >= smd->time) { smokeModifier_init(smd, ob, scene_framenr, me); + } if (smd->coll) { - if (smd->coll->mesh) + if (smd->coll->mesh) { BKE_id_free(NULL, smd->coll->mesh); + } smd->coll->mesh = BKE_mesh_copy_for_eval(me, false); } @@ -3161,15 +3252,17 @@ static void smokeModifier_process( } if (!smd->domain->fluid && (framenr != startframe) && - (smd->domain->flags & MOD_SMOKE_FILE_LOAD) == 0 && (cache->flag & PTCACHE_BAKED) == 0) + (smd->domain->flags & MOD_SMOKE_FILE_LOAD) == 0 && (cache->flag & PTCACHE_BAKED) == 0) { return; + } smd->domain->flags &= ~MOD_SMOKE_FILE_LOAD; CLAMP(framenr, startframe, endframe); /* If already viewing a pre/after frame, no need to reload */ - if ((smd->time == framenr) && (framenr != scene_framenr)) + if ((smd->time == framenr) && (framenr != scene_framenr)) { return; + } if (smokeModifier_init(smd, ob, scene_framenr, me) == 0) { printf("bad smokeModifier_init\n"); @@ -3187,8 +3280,9 @@ static void smokeModifier_process( return; } - if (!can_simulate) + if (!can_simulate) { return; + } # ifdef DEBUG_TIME double start = PIL_check_seconds_timer(); @@ -3228,8 +3322,9 @@ static void smokeModifier_process( } BKE_ptcache_validate(cache, framenr); - if (framenr != startframe) + if (framenr != startframe) { BKE_ptcache_write(&pid, framenr); + } # ifdef DEBUG_TIME double end = PIL_check_seconds_timer(); @@ -3242,13 +3337,15 @@ struct Mesh *smokeModifier_do( SmokeModifierData *smd, Depsgraph *depsgraph, Scene *scene, Object *ob, Mesh *me) { /* lock so preview render does not read smoke data while it gets modified */ - if ((smd->type & MOD_SMOKE_TYPE_DOMAIN) && smd->domain) + if ((smd->type & MOD_SMOKE_TYPE_DOMAIN) && smd->domain) { BLI_rw_mutex_lock(smd->domain->fluid_mutex, THREAD_LOCK_WRITE); + } smokeModifier_process(smd, depsgraph, scene, ob, me); - if ((smd->type & MOD_SMOKE_TYPE_DOMAIN) && smd->domain) + if ((smd->type & MOD_SMOKE_TYPE_DOMAIN) && smd->domain) { BLI_rw_mutex_unlock(smd->domain->fluid_mutex); + } /* return generated geometry for adaptive domain */ Mesh *result; @@ -3319,8 +3416,9 @@ static void bresenham_linie_3D(int x1, err_1 = dy2 - l; err_2 = dz2 - l; for (i = 0; i < l; i++) { - if (cb(result, input, res, pixel, tRay, correct) <= FLT_EPSILON) + if (cb(result, input, res, pixel, tRay, correct) <= FLT_EPSILON) { break; + } if (err_1 > 0) { pixel[1] += y_inc; err_1 -= dx2; @@ -3338,8 +3436,9 @@ static void bresenham_linie_3D(int x1, err_1 = dx2 - m; err_2 = dz2 - m; for (i = 0; i < m; i++) { - if (cb(result, input, res, pixel, tRay, correct) <= FLT_EPSILON) + if (cb(result, input, res, pixel, tRay, correct) <= FLT_EPSILON) { break; + } if (err_1 > 0) { pixel[0] += x_inc; err_1 -= dy2; @@ -3357,8 +3456,9 @@ static void bresenham_linie_3D(int x1, err_1 = dy2 - n; err_2 = dx2 - n; for (i = 0; i < n; i++) { - if (cb(result, input, res, pixel, tRay, correct) <= FLT_EPSILON) + if (cb(result, input, res, pixel, tRay, correct) <= FLT_EPSILON) { break; + } if (err_1 > 0) { pixel[1] += y_inc; err_1 -= dz2; @@ -3383,8 +3483,9 @@ static void smoke_calc_transparency(SmokeDomainSettings *sds, ViewLayer *view_la float *density = smoke_get_density(sds->fluid); float correct = -7.0f * sds->dx; - if (!get_light(view_layer, light)) + if (!get_light(view_layer, light)) { return; + } /* convert light pos to sim cell space */ mul_m4_v3(sds->imat, light); @@ -3392,8 +3493,9 @@ static void smoke_calc_transparency(SmokeDomainSettings *sds, ViewLayer *view_la light[1] = (light[1] - sds->p0[1]) / sds->cell_size[1] - 0.5f - (float)sds->res_min[1]; light[2] = (light[2] - sds->p0[2]) / sds->cell_size[2] - 0.5f - (float)sds->res_min[2]; - for (a = 0; a < size; a++) + for (a = 0; a < size; a++) { sds->shadow[a] = -1.0f; + } /* calculate domain bounds in sim cell space */ // 0,2,4 = 0.0f @@ -3405,15 +3507,16 @@ static void smoke_calc_transparency(SmokeDomainSettings *sds, ViewLayer *view_la size_t index = z * slabsize; int x, y; - for (y = 0; y < sds->res[1]; y++) + for (y = 0; y < sds->res[1]; y++) { for (x = 0; x < sds->res[0]; x++, index++) { float voxelCenter[3]; float pos[3]; int cell[3]; float tRay = 1.0; - if (sds->shadow[index] >= 0.0f) + if (sds->shadow[index] >= 0.0f) { continue; + } voxelCenter[0] = (float)x; voxelCenter[1] = (float)y; voxelCenter[2] = (float)z; @@ -3452,6 +3555,7 @@ static void smoke_calc_transparency(SmokeDomainSettings *sds, ViewLayer *view_la // convention -> from a RGBA float array, use G value for tRay sds->shadow[index] = tRay; } + } } } @@ -3475,10 +3579,12 @@ float BKE_smoke_get_velocity_at(struct Object *ob, float position[3], float velo smoke_pos_to_cell(sds, pos); /* check if point is outside domain max bounds */ - if (pos[0] < sds->res_min[0] || pos[1] < sds->res_min[1] || pos[2] < sds->res_min[2]) + if (pos[0] < sds->res_min[0] || pos[1] < sds->res_min[1] || pos[2] < sds->res_min[2]) { return -1.0f; - if (pos[0] > sds->res_max[0] || pos[1] > sds->res_max[1] || pos[2] > sds->res_max[2]) + } + if (pos[0] > sds->res_max[0] || pos[1] > sds->res_max[1] || pos[2] > sds->res_max[2]) { return -1.0f; + } /* map pos between 0.0 - 1.0 */ pos[0] = (pos[0] - sds->res_min[0]) / ((float)sds->res[0]); @@ -3487,10 +3593,12 @@ float BKE_smoke_get_velocity_at(struct Object *ob, float position[3], float velo /* check if point is outside active area */ if (smd->domain->flags & MOD_SMOKE_ADAPTIVE_DOMAIN) { - if (pos[0] < 0.0f || pos[1] < 0.0f || pos[2] < 0.0f) + if (pos[0] < 0.0f || pos[1] < 0.0f || pos[2] < 0.0f) { return 0.0f; - if (pos[0] > 1.0f || pos[1] > 1.0f || pos[2] > 1.0f) + } + if (pos[0] > 1.0f || pos[1] > 1.0f || pos[2] > 1.0f) { return 0.0f; + } } /* get interpolated velocity */ @@ -3522,12 +3630,15 @@ int BKE_smoke_get_data_flags(SmokeDomainSettings *sds) int flags = 0; if (sds->fluid) { - if (smoke_has_heat(sds->fluid)) + if (smoke_has_heat(sds->fluid)) { flags |= SM_ACTIVE_HEAT; - if (smoke_has_fuel(sds->fluid)) + } + if (smoke_has_fuel(sds->fluid)) { flags |= SM_ACTIVE_FIRE; - if (smoke_has_colors(sds->fluid)) + } + if (smoke_has_colors(sds->fluid)) { flags |= SM_ACTIVE_COLORS; + } } return flags; diff --git a/source/blender/blenkernel/intern/softbody.c b/source/blender/blenkernel/intern/softbody.c index ba7e26e817a..2a3145bee6c 100644 --- a/source/blender/blenkernel/intern/softbody.c +++ b/source/blender/blenkernel/intern/softbody.c @@ -190,8 +190,8 @@ static float sb_time_scale(Object *ob) /* hrms .. this could be IPO as well :) * estimated range [0.001 sluggish slug - 100.0 very fast (i hope ODE solver can handle that)] * 1 approx = a unit 1 pendulum at g = 9.8 [earth conditions] has period 65 frames - * theory would give a 50 frames period .. so there must be something inaccurate .. looking for that (BM) - */ + * theory would give a 50 frames period .. so there must be something inaccurate .. + * looking for that (BM). */ } return (1.0f); /* @@ -217,11 +217,13 @@ static float _final_goal(Object *ob, BodyPoint *bp) /*jow_go_for2_5 */ float f = -1999.99f; if (ob) { SoftBody *sb = ob->soft; /* is supposed to be there */ - if (!(ob->softflag & OB_SB_GOAL)) + if (!(ob->softflag & OB_SB_GOAL)) { return (0.0f); + } if (sb && bp) { - if (bp->goal < 0.0f) + if (bp->goal < 0.0f) { return (0.0f); + } f = sb->mingoal + bp->goal * fabsf(sb->maxgoal - sb->mingoal); f = pow(f, 4.0f); return (f); @@ -286,10 +288,12 @@ static ccd_Mesh *ccd_mesh_make(Object *ob) cmd = (CollisionModifierData *)modifiers_findByType(ob, eModifierType_Collision); /* first some paranoia checks */ - if (!cmd) + if (!cmd) { return NULL; - if (!cmd->mvert_num || !cmd->tri_num) + } + if (!cmd->mvert_num || !cmd->tri_num) { return NULL; + } pccd_M = MEM_mallocN(sizeof(ccd_Mesh), "ccd_Mesh"); pccd_M->mvert_num = cmd->mvert_num; @@ -370,10 +374,12 @@ static void ccd_mesh_update(Object *ob, ccd_Mesh *pccd_M) cmd = (CollisionModifierData *)modifiers_findByType(ob, eModifierType_Collision); /* first some paranoia checks */ - if (!cmd) + if (!cmd) { return; - if (!cmd->mvert_num || !cmd->tri_num) + } + if (!cmd->mvert_num || !cmd->tri_num) { return; + } if ((pccd_M->mvert_num != cmd->mvert_num) || (pccd_M->tri_num != cmd->tri_num)) { return; @@ -386,8 +392,9 @@ static void ccd_mesh_update(Object *ob, ccd_Mesh *pccd_M) hull = max_ff(ob->pd->pdef_sbift, ob->pd->pdef_sboft); /* rotate current to previous */ - if (pccd_M->mprevvert) + if (pccd_M->mprevvert) { MEM_freeN((void *)pccd_M->mprevvert); + } pccd_M->mprevvert = pccd_M->mvert; /* alloc and copy verts*/ pccd_M->mvert = MEM_dupallocN(cmd->xnew); @@ -482,8 +489,9 @@ static void ccd_mesh_free(ccd_Mesh *ccdm) if (ccdm && (ccdm->savety == CCD_SAVETY)) { /*make sure we're not nuking objects we don't know*/ MEM_freeN((void *)ccdm->mvert); MEM_freeN((void *)ccdm->tri); - if (ccdm->mprevvert) + if (ccdm->mprevvert) { MEM_freeN((void *)ccdm->mprevvert); + } MEM_freeN(ccdm->mima); MEM_freeN(ccdm); ccdm = NULL; @@ -510,8 +518,9 @@ static void ccd_build_deflector_hash(Depsgraph *depsgraph, Object *vertexowner, GHash *hash) { - if (!hash) + if (!hash) { return; + } unsigned int numobjects; Object **objects = BKE_collision_objects_create( @@ -546,8 +555,9 @@ static void ccd_update_deflector_hash(Depsgraph *depsgraph, Object *vertexowner, GHash *hash) { - if ((!hash) || (!vertexowner)) + if ((!hash) || (!vertexowner)) { return; + } unsigned int numobjects; Object **objects = BKE_collision_objects_create( @@ -589,7 +599,7 @@ static void add_mesh_quad_diag_springs(Object *ob) if (ob->soft) { int nofquads; - //float s_shear = ob->soft->shearstiff*ob->soft->shearstiff; + // float s_shear = ob->soft->shearstiff*ob->soft->shearstiff; nofquads = count_mesh_quads(me); if (nofquads) { @@ -636,16 +646,17 @@ static void add_2nd_order_roller(Object *ob, float UNUSED(stiffness), int *count } /* we are 2nd order here so 1rst should have been build :) */ /* first run counting second run adding */ *counter = 0; - if (addsprings) + if (addsprings) { bs3 = ob->soft->bspring + ob->soft->totspring; + } for (a = sb->totpoint, bp = sb->bpoint; a > 0; a--, bp++) { /*scan for neighborhood*/ bpo = NULL; v0 = (sb->totpoint - a); for (b = bp->nofsprings; b > 0; b--) { bs = sb->bspring + bp->springs[b - 1]; - /*nasty thing here that springs have two ends - so here we have to make sure we examine the other */ + /* Nasty thing here that springs have two ends + * so here we have to make sure we examine the other */ if (v0 == bs->v1) { bpo = sb->bpoint + bs->v2; notthis = bs->v2; @@ -699,8 +710,9 @@ static void add_2nd_order_springs(Object *ob, float stiffness) bs_new = MEM_callocN((ob->soft->totspring + counter) * sizeof(BodySpring), "bodyspring"); memcpy(bs_new, ob->soft->bspring, (ob->soft->totspring) * sizeof(BodySpring)); - if (ob->soft->bspring) + if (ob->soft->bspring) { MEM_freeN(ob->soft->bspring); + } ob->soft->bspring = bs_new; add_2nd_order_roller(ob, stiffness, &counter, 1); /* adding */ @@ -738,8 +750,9 @@ static void build_bps_springlist(Object *ob) BodySpring *bs; int a, b; - if (sb == NULL) + if (sb == NULL) { return; /* paranoya check */ + } for (a = sb->totpoint, bp = sb->bpoint; a > 0; a--, bp++) { /* throw away old list */ @@ -767,8 +780,9 @@ static void calculate_collision_balls(Object *ob) int a, b, akku_count; float min, max, akku; - if (sb == NULL) + if (sb == NULL) { return; /* paranoya check */ + } for (a = sb->totpoint, bp = sb->bpoint; a > 0; a--, bp++) { bp->colball = 0; @@ -804,8 +818,9 @@ static void calculate_collision_balls(Object *ob) bp->colball = (min + max) / 2.0f * sb->colball; } } - else + else { bp->colball = 0; + } } /*for bp*/ } @@ -815,10 +830,12 @@ static void renew_softbody(Scene *scene, Object *ob, int totpoint, int totspring SoftBody *sb; int i; short softflag; - if (ob->soft == NULL) + if (ob->soft == NULL) { ob->soft = sbNew(scene); - else + } + else { free_softbody_intern(ob->soft); + } sb = ob->soft; softflag = ob->softflag; @@ -827,8 +844,9 @@ static void renew_softbody(Scene *scene, Object *ob, int totpoint, int totspring sb->totspring = totspring; sb->bpoint = MEM_mallocN(totpoint * sizeof(BodyPoint), "bodypoint"); - if (totspring) + if (totspring) { sb->bspring = MEM_mallocN(totspring * sizeof(BodySpring), "bodyspring"); + } /* initialize BodyPoint array */ for (i = 0; i < totpoint; i++) { @@ -865,11 +883,13 @@ static void free_softbody_baked(SoftBody *sb) for (k = 0; k < sb->totkey; k++) { key = *(sb->keys + k); - if (key) + if (key) { MEM_freeN(key); + } } - if (sb->keys) + if (sb->keys) { MEM_freeN(sb->keys); + } sb->keys = NULL; sb->totkey = 0; @@ -912,8 +932,9 @@ static void free_softbody_intern(SoftBody *sb) MEM_freeN(sb->bpoint); } - if (sb->bspring) + if (sb->bspring) { MEM_freeN(sb->bspring); + } sb->totpoint = sb->totspring = 0; sb->bpoint = NULL; @@ -982,8 +1003,9 @@ static int sb_detect_aabb_collisionCached(float UNUSED(force[3]), int a; #endif - if ((sb == NULL) || (sb->scratch == NULL)) + if ((sb == NULL) || (sb->scratch == NULL)) { return 0; + } copy_v3_v3(aabbmin, sb->scratch->aabbmin); copy_v3_v3(aabbmax, sb->scratch->aabbmax); @@ -1437,7 +1459,7 @@ static void _scan_for_ext_spring_forces( sb->bpoint[bs->v1].pos, sb->bpoint[bs->v2].pos, &damp, feedback, ob, timenow)) { add_v3_v3(bs->ext_force, feedback); bs->flag |= BSF_INTERSECT; - //bs->cf=damp; + // bs->cf=damp; bs->cf = sb->choke * 0.01f; } } @@ -1506,8 +1528,10 @@ static void sb_sfesf_threads_run(struct Depsgraph *depsgraph, ListBase threads; SB_thread_context *sb_threads; int i, totthread, left, dec; - int lowsprings = - 100; /* wild guess .. may increase with better thread management 'above' or even be UI option sb->spawn_cf_threads_nopts */ + + /* wild guess .. may increase with better thread management 'above' + * or even be UI option sb->spawn_cf_threads_nopts */ + int lowsprings = 100; ListBase *effectors = BKE_effectors_create(depsgraph, ob, NULL, ob->soft->effector_weights); @@ -1532,8 +1556,9 @@ static void sb_sfesf_threads_run(struct Depsgraph *depsgraph, if (left > 0) { sb_threads[i].ifirst = left; } - else + else { sb_threads[i].ifirst = 0; + } sb_threads[i].effectors = effectors; sb_threads[i].do_deflector = false; // not used here sb_threads[i].fieldfactor = 0.0f; // not used here @@ -1544,13 +1569,15 @@ static void sb_sfesf_threads_run(struct Depsgraph *depsgraph, if (totthread > 1) { BLI_threadpool_init(&threads, exec_scan_for_ext_spring_forces, totthread); - for (i = 0; i < totthread; i++) + for (i = 0; i < totthread; i++) { BLI_threadpool_insert(&threads, &sb_threads[i]); + } BLI_threadpool_end(&threads); } - else + else { exec_scan_for_ext_spring_forces(&sb_threads[0]); + } /* clean up */ MEM_freeN(sb_threads); @@ -1716,9 +1743,10 @@ static int sb_detect_vertex_collisionCached(float opco[3], if ((facedist > innerfacethickness) && (facedist < outerfacethickness)) { if (isect_point_tri_prism_v3(opco, nv1, nv2, nv3)) { force_mag_norm = (float)exp(-ee * facedist); - if (facedist > outerfacethickness * ff) + if (facedist > outerfacethickness * ff) { force_mag_norm = (float)force_mag_norm * fa * (facedist - outerfacethickness) * (facedist - outerfacethickness); + } *damp = ob->pd->pdef_sbdamp; if (facedist > 0.0f) { *damp *= (1.0f - facedist / outerfacethickness); @@ -1727,8 +1755,9 @@ static int sb_detect_vertex_collisionCached(float opco[3], } else { madd_v3_v3fl(innerforceaccu, d_nvect, force_mag_norm); - if (deflected < 2) + if (deflected < 2) { deflected = 2; + } } if ((mprevvert) && (*damp > 0.0f)) { choose_winner(ve, opco, nv1, nv2, nv3, vv1, vv2, vv3); @@ -1750,9 +1779,10 @@ static int sb_detect_vertex_collisionCached(float opco[3], if (deflected == 1) { // no face but 'outer' edge cylinder sees vert force_mag_norm = (float)exp(-ee * mindistedge); - if (mindistedge > outerfacethickness * ff) + if (mindistedge > outerfacethickness * ff) { force_mag_norm = (float)force_mag_norm * fa * (mindistedge - outerfacethickness) * (mindistedge - outerfacethickness); + } madd_v3_v3fl(force, coledge, force_mag_norm); *damp = ob->pd->pdef_sbdamp; if (mindistedge > 0.0f) { @@ -1767,11 +1797,13 @@ static int sb_detect_vertex_collisionCached(float opco[3], } BLI_ghashIterator_free(ihash); - if (cavel) + if (cavel) { mul_v3_fl(avel, 1.0f / (float)cavel); + } copy_v3_v3(vel, avel); - if (ci) + if (ci) { *intrusion /= ci; + } if (deflected) { normalize_v3_v3(facenormal, force); } @@ -1793,7 +1825,10 @@ static int sb_deflect_face(Object *ob, copy_v3_v3(s_actpos, actpos); deflected = sb_detect_vertex_collisionCached( s_actpos, facenormal, cf, force, ob, time, vel, intrusion); - //deflected= sb_detect_vertex_collisionCachedEx(s_actpos, facenormal, cf, force, ob, time, vel, intrusion); +#if 0 + deflected = sb_detect_vertex_collisionCachedEx( + s_actpos, facenormal, cf, force, ob, time, vel, intrusion); +#endif return (deflected); } @@ -1804,35 +1839,36 @@ static void dfdx_spring(int ia, int ic, int op, float dir[3], float L, float len float m, delta_ij; int i, j; if (L < len) { - for (i=0;i<3;i++) { - for (j=0;j<3;j++) { - delta_ij = (i==j ? (1.0f): (0.0f)); - m=factor*(dir[i]*dir[j] + (1-L/len)*(delta_ij - dir[i]*dir[j])); - EIG_linear_solver_matrix_add(ia+i, op+ic+j, m); + for (i = 0; i < 3; i++) { + for (j = 0; j < 3; j++) { + delta_ij = (i == j ? (1.0f) : (0.0f)); + m = factor * (dir[i] * dir[j] + (1 - L / len) * (delta_ij - dir[i] * dir[j])); + EIG_linear_solver_matrix_add(ia + i, op + ic + j, m); } } } else { - for (i=0;i<3;i++) { - for (j=0;j<3;j++) { - m=factor*dir[i]*dir[j]; - EIG_linear_solver_matrix_add(ia+i, op+ic+j, m); + for (i = 0; i < 3; i++) { + for (j = 0; j < 3; j++) { + m = factor * dir[i] * dir[j]; + EIG_linear_solver_matrix_add(ia + i, op + ic + j, m); } } } } - static void dfdx_goal(int ia, int ic, int op, float factor) { int i; - for (i=0;i<3;i++) EIG_linear_solver_matrix_add(ia+i, op+ic+i, factor); + for (i = 0; i < 3; i++) + EIG_linear_solver_matrix_add(ia + i, op + ic + i, factor); } static void dfdv_goal(int ia, int ic, float factor) { int i; - for (i=0;i<3;i++) EIG_linear_solver_matrix_add(ia+i, ic+i, factor); + for (i = 0; i < 3; i++) + EIG_linear_solver_matrix_add(ia + i, ic + i, factor); } #endif /* if 0 */ @@ -1852,16 +1888,16 @@ static void sb_spring_force( bp1 = &sb->bpoint[bs->v1]; bp2 = &sb->bpoint[bs->v2]; #if 0 /* UNUSED */ - ia =3*bs->v1; - ic =3*bs->v2; + ia = 3 * bs->v1; + ic = 3 * bs->v2; #endif } else if (bpi == bs->v2) { bp1 = &sb->bpoint[bs->v2]; bp2 = &sb->bpoint[bs->v1]; #if 0 /* UNUSED */ - ia =3*bs->v2; - ic =3*bs->v1; + ia = 3 * bs->v2; + ic = 3 * bs->v1; #endif } else { @@ -1873,15 +1909,19 @@ static void sb_spring_force( /* do bp1 <--> bp2 elastic */ sub_v3_v3v3(dir, bp1->pos, bp2->pos); distance = normalize_v3(dir); - if (bs->len < distance) + if (bs->len < distance) { iks = 1.0f / (1.0f - sb->inspring) - 1.0f; /* inner spring constants function */ - else + } + else { iks = 1.0f / (1.0f - sb->inpush) - 1.0f; /* inner spring constants function */ + } - if (bs->len > 0.0f) /* check for degenerated springs */ + if (bs->len > 0.0f) { /* check for degenerated springs */ forcefactor = iks / bs->len; - else + } + else { forcefactor = iks; + } kw = (bp1->springweight + bp2->springweight) / 2.0f; kw = kw * kw; kw = kw * kw; @@ -1971,14 +2011,16 @@ static int _softbody_calc_forces_slice_in_a_thread(Scene *scene, float compare; float bstune = sb->ballstiff; - /* running in a slice we must not assume anything done with obp neither alter the data of obp */ + /* Running in a slice we must not assume anything done with obp + * neither alter the data of obp. */ for (c = sb->totpoint, obp = sb->bpoint; c > 0; c--, obp++) { compare = (obp->colball + bp->colball); sub_v3_v3v3(def, bp->pos, obp->pos); /* rather check the AABBoxes before ever calculating the real distance */ /* mathematically it is completely nuts, but performance is pretty much (3) times faster */ - if ((ABS(def[0]) > compare) || (ABS(def[1]) > compare) || (ABS(def[2]) > compare)) + if ((ABS(def[0]) > compare) || (ABS(def[1]) > compare) || (ABS(def[2]) > compare)) { continue; + } distance = normalize_v3(def); if (distance < compare) { /* exclude body points attached with a spring */ @@ -2114,8 +2156,9 @@ static int _softbody_calc_forces_slice_in_a_thread(Scene *scene, bs = sb->bspring + bp->springs[b - 1]; if (do_springcollision || do_aero) { add_v3_v3(bp->force, bs->ext_force); - if (bs->flag & BSF_INTERSECT) + if (bs->flag & BSF_INTERSECT) { bp->choke = bs->cf; + } } // sb_spring_force(Object *ob, int bpi, BodySpring *bs, float iks, float forcetime) sb_spring_force(ob, ilast - bb, bs, iks, forcetime); @@ -2159,8 +2202,10 @@ static void sb_cf_threads_run(Scene *scene, ListBase threads; SB_thread_context *sb_threads; int i, totthread, left, dec; - int lowpoints = - 100; /* wild guess .. may increase with better thread management 'above' or even be UI option sb->spawn_cf_threads_nopts */ + + /* wild guess .. may increase with better thread management 'above' + * or even be UI option sb->spawn_cf_threads_nopts. */ + int lowpoints = 100; /* figure the number of threads while preventing pretty pointless threading overhead */ totthread = BKE_scene_num_threads(scene); @@ -2185,8 +2230,9 @@ static void sb_cf_threads_run(Scene *scene, if (left > 0) { sb_threads[i].ifirst = left; } - else + else { sb_threads[i].ifirst = 0; + } sb_threads[i].effectors = effectors; sb_threads[i].do_deflector = do_deflector; sb_threads[i].fieldfactor = fieldfactor; @@ -2198,13 +2244,15 @@ static void sb_cf_threads_run(Scene *scene, if (totthread > 1) { BLI_threadpool_init(&threads, exec_softbody_calc_forces, totthread); - for (i = 0; i < totthread; i++) + for (i = 0; i < totthread; i++) { BLI_threadpool_insert(&threads, &sb_threads[i]); + } BLI_threadpool_end(&threads); } - else + else { exec_softbody_calc_forces(&sb_threads[0]); + } /* clean up */ MEM_freeN(sb_threads); } @@ -2226,7 +2274,9 @@ static void softbody_calc_forces( /* check conditions for various options */ do_deflector = query_external_colliders(depsgraph, sb->collision_group); - /* do_selfcollision=((ob->softflag & OB_SB_EDGES) && (sb->bspring)&& (ob->softflag & OB_SB_SELF)); */ /* UNUSED */ +#if 0 + do_selfcollision=((ob->softflag & OB_SB_EDGES) && (sb->bspring)&& (ob->softflag & OB_SB_SELF)); +#endif do_springcollision = do_deflector && (ob->softflag & OB_SB_EDGES) && (ob->softflag & OB_SB_EDGECOLL); do_aero = ((sb->aeroedge) && (ob->softflag & OB_SB_EDGES)); @@ -2234,8 +2284,9 @@ static void softbody_calc_forces( /* iks = 1.0f/(1.0f-sb->inspring)-1.0f; */ /* inner spring constants function */ /* UNUSED */ /* bproot= sb->bpoint; */ /* need this for proper spring addressing */ /* UNUSED */ - if (do_springcollision || do_aero) + if (do_springcollision || do_aero) { sb_sfesf_threads_run(depsgraph, scene, ob, timenow, sb->totspring, NULL); + } /* after spring scan because it uses Effoctors too */ ListBase *effectors = BKE_effectors_create(depsgraph, ob, NULL, sb->effector_weights); @@ -2257,8 +2308,9 @@ static void softbody_calc_forces( windfactor); /* finally add forces caused by face collision */ - if (ob->softflag & OB_SB_FACECOLL) + if (ob->softflag & OB_SB_FACECOLL) { scan_for_ext_face_forces(ob, timenow); + } /* finish matrix and solve */ BKE_effectors_free(effectors); @@ -2284,27 +2336,42 @@ static void softbody_apply_forces(Object *ob, float forcetime, int mode, float * /* old one with homogeneous masses */ /* claim a minimum mass for vertex */ #if 0 - if (sb->nodemass > 0.009999f) timeovermass = forcetime / sb->nodemass; - else timeovermass = forcetime / 0.009999f; + if (sb->nodemass > 0.009999f) + timeovermass = forcetime / sb->nodemass; + else + timeovermass = forcetime / 0.009999f; #endif for (a = sb->totpoint, bp = sb->bpoint; a > 0; a--, bp++) { - /* now we have individual masses */ + /* Now we have individual masses. */ /* claim a minimum mass for vertex */ - if (_final_mass(ob, bp) > 0.009999f) + if (_final_mass(ob, bp) > 0.009999f) { timeovermass = forcetime / _final_mass(ob, bp); - else + } + else { timeovermass = forcetime / 0.009999f; + } if (_final_goal(ob, bp) < SOFTGOALSNAP) { /* this makes t~ = t */ - if (mid_flags & MID_PRESERVE) + if (mid_flags & MID_PRESERVE) { copy_v3_v3(dx, bp->vec); + } - /* so here is (v)' = a(cceleration) = sum(F_springs)/m + gravitation + some friction forces + more forces*/ - /* the ( ... )' operator denotes derivate respective time */ - /* the euler step for velocity then becomes */ - /* v(t + dt) = v(t) + a(t) * dt */ + /** + * So here is: + * <pre> + * (v)' = a(cceleration) = + * sum(F_springs)/m + gravitation + some friction forces + more forces. + * </pre> + * + * The ( ... )' operator denotes derivate respective time. + * + * The euler step for velocity then becomes: + * <pre> + * v(t + dt) = v(t) + a(t) * dt + * </pre> + */ mul_v3_fl(bp->force, timeovermass); /* individual mass of node here */ /* some nasty if's to have heun in here too */ copy_v3_v3(dv, bp->force); @@ -2329,8 +2396,9 @@ static void softbody_apply_forces(Object *ob, float forcetime, int mode, float * } /* this makes t~ = t+dt */ - if (!(mid_flags & MID_PRESERVE)) + if (!(mid_flags & MID_PRESERVE)) { copy_v3_v3(dx, bp->vec); + } /* so here is (x)'= v(elocity) */ /* the euler step for location then becomes */ @@ -2339,11 +2407,11 @@ static void softbody_apply_forces(Object *ob, float forcetime, int mode, float * /* the freezer coming sooner or later */ #if 0 - if ((dot_v3v3(dx, dx)<freezeloc )&&(dot_v3v3(bp->force, bp->force)<freezeforce )) { - bp->frozen /=2; + if ((dot_v3v3(dx, dx) < freezeloc) && (dot_v3v3(bp->force, bp->force) < freezeforce)) { + bp->frozen /= 2; } else { - bp->frozen = min_ff(bp->frozen*1.05f, 1.0f); + bp->frozen = min_ff(bp->frozen * 1.05f, 1.0f); } mul_v3_fl(dx, bp->frozen); #endif @@ -2378,23 +2446,27 @@ static void softbody_apply_forces(Object *ob, float forcetime, int mode, float * } /*snap*/ /* so while we are looping BPs anyway do statistics on the fly */ minmax_v3v3_v3(aabbmin, aabbmax, bp->pos); - if (bp->loc_flag & SBF_DOFUZZY) + if (bp->loc_flag & SBF_DOFUZZY) { fuzzy = 1; + } } /*for*/ - if (sb->totpoint) + if (sb->totpoint) { mul_v3_fl(cm, 1.0f / sb->totpoint); + } if (sb->scratch) { copy_v3_v3(sb->scratch->aabbmin, aabbmin); copy_v3_v3(sb->scratch->aabbmax, aabbmax); } if (err) { /* so step size will be controlled by biggest difference in slope */ - if (sb->solverflags & SBSO_OLDERR) + if (sb->solverflags & SBSO_OLDERR) { *err = max_ff(maxerrpos, maxerrvel); - else + } + else { *err = maxerrpos; - //printf("EP %f EV %f\n", maxerrpos, maxerrvel); + } + // printf("EP %f EV %f\n", maxerrpos, maxerrvel); if (fuzzy) { *err /= sb->fuzzyness; } @@ -2417,73 +2489,72 @@ static void softbody_restore_prev_step(Object *ob) #if 0 static void softbody_store_step(Object *ob) { - SoftBody *sb= ob->soft; /* is supposed to be there*/ + SoftBody *sb = ob->soft; /* is supposed to be there*/ BodyPoint *bp; int a; - for (a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) { + for (a = sb->totpoint, bp = sb->bpoint; a > 0; a--, bp++) { copy_v3_v3(bp->prevvec, bp->vec); copy_v3_v3(bp->prevpos, bp->pos); } } - /* used by predictors and correctors */ static void softbody_store_state(Object *ob, float *ppos, float *pvel) { - SoftBody *sb= ob->soft; /* is supposed to be there*/ + SoftBody *sb = ob->soft; /* is supposed to be there*/ BodyPoint *bp; int a; - float *pp=ppos, *pv=pvel; + float *pp = ppos, *pv = pvel; - for (a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) { + for (a = sb->totpoint, bp = sb->bpoint; a > 0; a--, bp++) { copy_v3_v3(pv, bp->vec); - pv+=3; + pv += 3; copy_v3_v3(pp, bp->pos); - pp+=3; + pp += 3; } } /* used by predictors and correctors */ static void softbody_retrieve_state(Object *ob, float *ppos, float *pvel) { - SoftBody *sb= ob->soft; /* is supposed to be there*/ + SoftBody *sb = ob->soft; /* is supposed to be there*/ BodyPoint *bp; int a; - float *pp=ppos, *pv=pvel; + float *pp = ppos, *pv = pvel; - for (a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) { + for (a = sb->totpoint, bp = sb->bpoint; a > 0; a--, bp++) { copy_v3_v3(bp->vec, pv); - pv+=3; + pv += 3; copy_v3_v3(bp->pos, pp); - pp+=3; + pp += 3; } } /* used by predictors and correctors */ static void softbody_swap_state(Object *ob, float *ppos, float *pvel) { - SoftBody *sb= ob->soft; /* is supposed to be there*/ + SoftBody *sb = ob->soft; /* is supposed to be there*/ BodyPoint *bp; int a; - float *pp=ppos, *pv=pvel; + float *pp = ppos, *pv = pvel; float temp[3]; - for (a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) { + for (a = sb->totpoint, bp = sb->bpoint; a > 0; a--, bp++) { copy_v3_v3(temp, bp->vec); copy_v3_v3(bp->vec, pv); copy_v3_v3(pv, temp); - pv+=3; + pv += 3; copy_v3_v3(temp, bp->pos); copy_v3_v3(bp->pos, pp); copy_v3_v3(pp, temp); - pp+=3; + pp += 3; } } #endif @@ -2605,10 +2676,12 @@ static void mesh_to_softbody(Scene *scene, Object *ob) int a, totedge; int defgroup_index, defgroup_index_mass, defgroup_index_spring; - if (ob->softflag & OB_SB_EDGES) + if (ob->softflag & OB_SB_EDGES) { totedge = me->totedge; - else + } + else { totedge = 0; + } /* renew ends with ob->soft with points and edges, also checks & makes ob->soft */ renew_softbody(scene, ob, me->totvert, totedge); @@ -2911,15 +2984,21 @@ static void curve_surf_to_softbody(Scene *scene, Object *ob) /* weights from bpoints, same code used as for mesh vertices */ /* if ((ob->softflag & OB_SB_GOAL) && sb->vertgroup) 2.4x hack*/ /* new! take the weights from curve vertex anyhow */ - if (ob->softflag & OB_SB_GOAL) + if (ob->softflag & OB_SB_GOAL) { setgoal = 1; + } for (nu = cu->nurb.first; nu; nu = nu->next) { if (nu->bezt) { - /* bezier case ; this is nicly said naive; who ever wrote this part, it was not me (JOW) :) */ - /* a: never ever make tangent handles (sub) and or (ob)ject to collision */ - /* b: rather calculate them using some C2 (C2= continuous in second derivate -> no jump in bending ) condition */ - /* not too hard to do, but needs some more code to care for; some one may want look at it JOW 2010/06/12*/ + /* Bezier case; this is nicly said naive; who ever wrote this part, + * it was not me (JOW) :). + * + * a: never ever make tangent handles (sub) and or (ob)ject to collision. + * b: rather calculate them using some C2 + * (C2= continuous in second derivate -> no jump in bending ) condition. + * + * Not too hard to do, but needs some more code to care for; + * some one may want look at it JOW 2010/06/12. */ for (bezt = nu->bezt, a = 0; a < nu->pntsu; a++, bezt++, bp += 3, curindex += 3) { if (setgoal) { bp->goal *= bezt->weight; @@ -2993,8 +3072,9 @@ static void softbody_to_object(Object *ob, float (*vertexCos)[3], int numVerts, for (a = 0; a < numVerts; a++, bp++) { copy_v3_v3(vertexCos[a], bp->pos); - if (local == 0) + if (local == 0) { mul_m4_v3(ob->imat, vertexCos[a]); /* softbody is in global coords, baked optionally not */ + } } } } @@ -3002,8 +3082,9 @@ static void softbody_to_object(Object *ob, float (*vertexCos)[3], int numVerts, /* +++ ************ maintaining scratch *************** */ static void sb_new_scratch(SoftBody *sb) { - if (!sb) + if (!sb) { return; + } sb->scratch = MEM_callocN(sizeof(SBScratch), "SBScratch"); sb->scratch->colliderhash = BLI_ghash_ptr_new("sb_new_scratch gh"); sb->scratch->bodyface = NULL; @@ -3061,8 +3142,9 @@ SoftBody *sbNew(Scene *scene) sb->shared = MEM_callocN(sizeof(*sb->shared), "SoftBody_Shared"); sb->shared->pointcache = BKE_ptcache_add(&sb->shared->ptcaches); - if (!sb->effector_weights) + if (!sb->effector_weights) { sb->effector_weights = BKE_effector_add_weights(NULL); + } sb->last_frame = MINFRAME - 1; @@ -3085,8 +3167,9 @@ void sbFree(Object *ob) sb->shared->pointcache = NULL; MEM_freeN(sb->shared); } - if (sb->effector_weights) + if (sb->effector_weights) { MEM_freeN(sb->effector_weights); + } MEM_freeN(sb); ob->soft = NULL; @@ -3100,7 +3183,7 @@ void sbFreeSimulation(SoftBody *sb) /* makes totally fresh start situation */ void sbObjectToSoftbody(Object *ob) { - //ob->softflag |= OB_SB_REDO; + // ob->softflag |= OB_SB_REDO; free_softbody_intern(ob->soft); } @@ -3132,8 +3215,9 @@ static void softbody_update_positions(Object *ob, BodyPoint *bp; int a; - if (!sb || !sb->bpoint) + if (!sb || !sb->bpoint) { return; + } for (a = 0, bp = sb->bpoint; a < numVerts; a++, bp++) { /* store where goals are now */ @@ -3154,10 +3238,9 @@ static void softbody_update_positions(Object *ob, * that is: * a precise position vector denoting the motion of the center of mass * give a rotation/scale matrix using averaging method, that's why estimate and not calculate - * see: this is kind of reverse engineering: having to states of a point cloud and recover what happened - * our advantage here we know the identity of the vertex - * there are others methods giving other results. - * lloc, lrot, lscale are allowed to be NULL, just in case you don't need it. + * see: this is kind of reverse engineering: having to states of a point cloud and recover what + * happened our advantage here we know the identity of the vertex there are others methods giving + * other results. lloc, lrot, lscale are allowed to be NULL, just in case you don't need it. * should be pretty useful for pythoneers :) * not! velocity .. 2nd order stuff * vcloud_estimate_transform_v3 see @@ -3173,11 +3256,13 @@ void SB_estimate_transform(Object *ob, float lloc[3], float lrot[3][3], float ls float com[3], rcom[3]; int a; - if (!ob || !ob->soft) + if (!ob || !ob->soft) { return; /* why did we get here ? */ + } sb = ob->soft; - if (!sb || !sb->bpoint) + if (!sb || !sb->bpoint) { return; + } opos = MEM_callocN((sb->totpoint) * 3 * sizeof(float), "SB_OPOS"); rpos = MEM_callocN((sb->totpoint) * 3 * sizeof(float), "SB_RPOS"); /* might filter vertex selection with a vertex group */ @@ -3187,14 +3272,17 @@ void SB_estimate_transform(Object *ob, float lloc[3], float lrot[3][3], float ls } vcloud_estimate_transform_v3(sb->totpoint, opos, NULL, rpos, NULL, com, rcom, lrot, lscale); - //sub_v3_v3(com, rcom); - if (lloc) + // sub_v3_v3(com, rcom); + if (lloc) { copy_v3_v3(lloc, com); + } copy_v3_v3(sb->lcom, com); - if (lscale) + if (lscale) { copy_m3_m3(sb->lscale, lscale); - if (lrot) + } + if (lrot) { copy_m3_m3(sb->lrot, lrot); + } MEM_freeN(opos); MEM_freeN(rpos); @@ -3248,8 +3336,9 @@ static void softbody_reset(Object *ob, SoftBody *sb, float (*vertexCos)[3], int } switch (ob->type) { case OB_MESH: - if (ob->softflag & OB_SB_FACECOLL) + if (ob->softflag & OB_SB_FACECOLL) { mesh_faces_to_scratch(ob); + } break; case OB_LATTICE: break; @@ -3273,8 +3362,9 @@ static void softbody_step( * So we refuse to do so. Since we do not know anything about 'outside' changes * especially colliders we refuse to go more than 10 frames. */ - if (dtime < 0 || dtime > 10.5f) + if (dtime < 0 || dtime > 10.5f) { return; + } ccd_update_deflector_hash(depsgraph, sb->collision_group, ob, sb->scratch->colliderhash); @@ -3287,22 +3377,27 @@ static void softbody_step( /* special case of 2nd order Runge-Kutta type AKA Heun */ int mid_flags = 0; float err = 0; - float forcetimemax = 1.0f; /* set defaults guess we shall do one frame */ - float forcetimemin = 0.01f; /* set defaults guess 1/100 is tight enough */ - float timedone = 0.0; /* how far did we get without violating error condition */ - /* loops = counter for emergency brake - * we don't want to lock up the system if physics fail */ + /* Set defaults guess we shall do one frame */ + float forcetimemax = 1.0f; + /* Set defaults guess 1/100 is tight enough */ + float forcetimemin = 0.01f; + /* How far did we get without violating error condition. */ + float timedone = 0.0; + /* Loops = counter for emergency brake we don't want to lock up the system if physics fail. */ int loops = 0; SoftHeunTol = sb->rklimit; /* humm .. this should be calculated from sb parameters and sizes */ /* adjust loop limits */ - if (sb->minloops > 0) + if (sb->minloops > 0) { forcetimemax = dtime / sb->minloops; - if (sb->maxloops > 0) + } + if (sb->maxloops > 0) { forcetimemin = dtime / sb->maxloops; + } - if (sb->solver_ID > 0) + if (sb->solver_ID > 0) { mid_flags |= MID_PRESERVE; + } forcetime = forcetimemax; /* hope for integrating in one step */ while ((ABS(timedone) < ABS(dtime)) && (loops < 2000)) { @@ -3326,7 +3421,7 @@ static void softbody_step( if (forcetime > forcetimemin) { forcetime = max_ff(forcetime / 2.0f, forcetimemin); softbody_restore_prev_step(ob); - //printf("down, "); + // printf("down, "); } else { timedone += forcetime; @@ -3336,7 +3431,8 @@ static void softbody_step( float newtime = forcetime * 1.1f; /* hope for 1.1 times better conditions in next step */ if (sb->scratch->flag & SBF_DOFUZZY) { - //if (err > SoftHeunTol/(2.0f*sb->fuzzyness)) { /* stay with this stepsize unless err really small */ + ///* stay with this stepsize unless err really small */ + // if (err > SoftHeunTol/(2.0f*sb->fuzzyness)) { newtime = forcetime; //} } @@ -3347,21 +3443,25 @@ static void softbody_step( } timedone += forcetime; newtime = min_ff(forcetimemax, max_ff(newtime, forcetimemin)); - //if (newtime > forcetime) printf("up, "); - if (forcetime > 0.0f) + // if (newtime > forcetime) printf("up, "); + if (forcetime > 0.0f) { forcetime = min_ff(dtime - timedone, newtime); - else + } + else { forcetime = max_ff(dtime - timedone, newtime); + } } loops++; if (sb->solverflags & SBSO_MONITOR) { sct = PIL_check_seconds_timer(); - if (sct - sst > 0.5) + if (sct - sst > 0.5) { printf("%3.0f%% \r", 100.0f * timedone / dtime); + } } /* ask for user break */ - if (SB_localInterruptCallBack && SB_localInterruptCallBack()) + if (SB_localInterruptCallBack && SB_localInterruptCallBack()) { break; + } } /* move snapped to final position */ interpolate_exciter(ob, 2, 2); @@ -3369,20 +3469,21 @@ static void softbody_step( // if (G.debug & G_DEBUG) { if (sb->solverflags & SBSO_MONITOR) { - if (loops > HEUNWARNLIMIT) /* monitor high loop counts */ + if (loops > HEUNWARNLIMIT) { /* monitor high loop counts */ printf("\r needed %d steps/frame", loops); + } } } else if (sb->solver_ID == 2) { /* do semi "fake" implicit euler */ - //removed + // removed } /*SOLVER SELECT*/ else if (sb->solver_ID == 4) { /* do semi "fake" implicit euler */ } /*SOLVER SELECT*/ else if (sb->solver_ID == 3) { /* do "stupid" semi "fake" implicit euler */ - //removed + // removed } /*SOLVER SELECT*/ else { @@ -3394,8 +3495,9 @@ static void softbody_step( if (sb->solverflags & SBSO_MONITOR) { sct = PIL_check_seconds_timer(); - if ((sct - sst > 0.5) || (G.debug & G_DEBUG)) + if ((sct - sst > 0.5) || (G.debug & G_DEBUG)) { printf(" solver time %f sec %s\n", sct - sst, ob->id.name); + } } } @@ -3503,19 +3605,20 @@ void sbObjectStep(struct Depsgraph *depsgraph, BKE_ptcache_validate(cache, framenr); if (cache_result == PTCACHE_READ_INTERPOLATED && cache->flag & PTCACHE_REDO_NEEDED && - can_write_cache) + can_write_cache) { BKE_ptcache_write(&pid, framenr); + } sbStoreLastFrame(depsgraph, ob, framenr); return; } else if (cache_result == PTCACHE_READ_OLD) { - ; /* do nothing */ + /* pass */ } - else if (/*ob->id.lib || */ ( - cache->flag & - PTCACHE_BAKED)) { /* "library linking & pointcaches" has to be solved properly at some point */ + else if (/*ob->id.lib || */ + /* "library linking & pointcaches" has to be solved properly at some point */ + (cache->flag & PTCACHE_BAKED)) { /* if baked and nothing in cache, do nothing */ if (can_write_cache) { BKE_ptcache_invalidate(cache); @@ -3523,12 +3626,15 @@ void sbObjectStep(struct Depsgraph *depsgraph, return; } - if (!can_simulate) + if (!can_simulate) { return; + } /* if on second frame, write cache for first frame */ - if (cache->simframe == startframe && (cache->flag & PTCACHE_OUTDATED || cache->last_exact == 0)) + if (cache->simframe == startframe && + (cache->flag & PTCACHE_OUTDATED || cache->last_exact == 0)) { BKE_ptcache_write(&pid, startframe); + } softbody_update_positions(ob, sb, vertexCos, numVerts); diff --git a/source/blender/blenkernel/intern/sound.c b/source/blender/blenkernel/intern/sound.c index 383542fa335..c97baf8f7dd 100644 --- a/source/blender/blenkernel/intern/sound.c +++ b/source/blender/blenkernel/intern/sound.c @@ -61,7 +61,7 @@ static int sound_cfra; static char **audio_device_names = NULL; #endif -bSound *BKE_sound_new_file(struct Main *bmain, const char *filepath) +bSound *BKE_sound_new_file(Main *bmain, const char *filepath) { bSound *sound; const char *path; @@ -82,7 +82,7 @@ bSound *BKE_sound_new_file(struct Main *bmain, const char *filepath) return sound; } -bSound *BKE_sound_new_file_exists_ex(struct Main *bmain, const char *filepath, bool *r_exists) +bSound *BKE_sound_new_file_exists_ex(Main *bmain, const char *filepath, bool *r_exists) { bSound *sound; char str[FILE_MAX], strtest[FILE_MAX]; @@ -97,18 +97,20 @@ bSound *BKE_sound_new_file_exists_ex(struct Main *bmain, const char *filepath, b if (BLI_path_cmp(strtest, str) == 0) { id_us_plus(&sound->id); /* officially should not, it doesn't link here! */ - if (r_exists) + if (r_exists) { *r_exists = true; + } return sound; } } - if (r_exists) + if (r_exists) { *r_exists = false; + } return BKE_sound_new_file(bmain, filepath); } -bSound *BKE_sound_new_file_exists(struct Main *bmain, const char *filepath) +bSound *BKE_sound_new_file_exists(Main *bmain, const char *filepath) { return BKE_sound_new_file_exists_ex(bmain, filepath, NULL); } @@ -146,8 +148,10 @@ void BKE_sound_free(bSound *sound) } /** - * Only copy internal data of Sound ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of Sound ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * @@ -190,21 +194,25 @@ static const char *force_device = NULL; static void sound_sync_callback(void *data, int mode, float time) { // Ugly: Blender doesn't like it when the animation is played back during rendering - if (G.is_rendering) + if (G.is_rendering) { return; + } - struct Main *bmain = (struct Main *)data; - struct Scene *scene; + Main *bmain = (Main *)data; + Scene *scene; scene = bmain->scenes.first; while (scene) { if (scene->audio.flag & AUDIO_SYNC) { - if (mode) + if (mode) { BKE_sound_play_scene(scene); - else + } + else { BKE_sound_stop_scene(scene); - if (scene->playback_handle) + } + if (scene->playback_handle) { AUD_Handle_setPosition(scene->playback_handle, time); + } } scene = scene->id.next; } @@ -229,7 +237,7 @@ void *BKE_sound_get_device(void) return sound_device; } -void BKE_sound_init(struct Main *bmain) +void BKE_sound_init(Main *bmain) { /* Make sure no instance of the sound system is running, otherwise we get leaks. */ BKE_sound_exit(); @@ -256,32 +264,39 @@ void BKE_sound_init(struct Main *bmain) } } } - else + else { device_name = force_device; + } - if (buffersize < 128) + if (buffersize < 128) { buffersize = 1024; + } - if (specs.rate < AUD_RATE_8000) + if (specs.rate < AUD_RATE_8000) { specs.rate = AUD_RATE_48000; + } - if (specs.format <= AUD_FORMAT_INVALID) + if (specs.format <= AUD_FORMAT_INVALID) { specs.format = AUD_FORMAT_S16; + } - if (specs.channels <= AUD_CHANNELS_INVALID) + if (specs.channels <= AUD_CHANNELS_INVALID) { specs.channels = AUD_CHANNELS_STEREO; + } - if (!(sound_device = AUD_init(device_name, specs, buffersize, "Blender"))) + if (!(sound_device = AUD_init(device_name, specs, buffersize, "Blender"))) { sound_device = AUD_init("Null", specs, buffersize, "Blender"); + } BKE_sound_init_main(bmain); } -void BKE_sound_init_main(struct Main *bmain) +void BKE_sound_init_main(Main *bmain) { # ifdef WITH_JACK - if (sound_device) + if (sound_device) { AUD_setSynchronizerCallback(sound_sync_callback, bmain); + } # else (void)bmain; /* unused */ # endif @@ -311,7 +326,7 @@ void BKE_sound_exit_once(void) /* XXX unused currently */ # if 0 -bSound *BKE_sound_new_buffer(struct Main *bmain, bSound *source) +bSound *BKE_sound_new_buffer(Main *bmain, bSound *source) { bSound *sound = NULL; @@ -329,7 +344,7 @@ bSound *BKE_sound_new_buffer(struct Main *bmain, bSound *source) return sound; } -bSound *BKE_sound_new_limiter(struct Main *bmain, bSound *source, float start, float end) +bSound *BKE_sound_new_limiter(Main *bmain, bSound *source, float start, float end) { bSound *sound = NULL; @@ -353,14 +368,17 @@ bSound *BKE_sound_new_limiter(struct Main *bmain, bSound *source, float start, f void BKE_sound_cache(bSound *sound) { sound->flags |= SOUND_FLAGS_CACHING; - if (sound->cache) + if (sound->cache) { AUD_Sound_free(sound->cache); + } sound->cache = AUD_Sound_cache(sound->handle); - if (sound->cache) + if (sound->cache) { sound->playback_handle = sound->cache; - else + } + else { sound->playback_handle = sound->handle; + } } void BKE_sound_delete_cache(bSound *sound) @@ -373,7 +391,7 @@ void BKE_sound_delete_cache(bSound *sound) } } -void BKE_sound_load(struct Main *bmain, bSound *sound) +void BKE_sound_load(Main *bmain, bSound *sound) { if (sound) { if (sound->cache) { @@ -391,8 +409,7 @@ void BKE_sound_load(struct Main *bmain, bSound *sound) /* XXX unused currently */ # if 0 - switch (sound->type) - { + switch (sound->type) { case SOUND_TYPE_FILE: # endif { @@ -406,23 +423,27 @@ void BKE_sound_load(struct Main *bmain, bSound *sound) BLI_path_abs(fullpath, ID_BLEND_PATH(bmain, &sound->id)); /* but we need a packed file then */ - if (pf) + if (pf) { sound->handle = AUD_Sound_bufferFile((unsigned char *)pf->data, pf->size); - /* or else load it from disk */ - else + } + else { + /* or else load it from disk */ sound->handle = AUD_Sound_file(fullpath); + } } /* XXX unused currently */ # if 0 break; } case SOUND_TYPE_BUFFER: - if (sound->child_sound && sound->child_sound->handle) + if (sound->child_sound && sound->child_sound->handle) { sound->handle = AUD_bufferSound(sound->child_sound->handle); + } break; case SOUND_TYPE_LIMITER: - if (sound->child_sound && sound->child_sound->handle) + if (sound->child_sound && sound->child_sound->handle) { sound->handle = AUD_limitSound(sound->child_sound, sound->start, sound->end); + } break; } # endif @@ -436,25 +457,28 @@ void BKE_sound_load(struct Main *bmain, bSound *sound) sound->cache = AUD_Sound_cache(sound->handle); } - if (sound->cache) + if (sound->cache) { sound->playback_handle = sound->cache; - else + } + else { sound->playback_handle = sound->handle; + } BKE_sound_update_sequencer(bmain, sound); } } -AUD_Device *BKE_sound_mixdown(struct Scene *scene, AUD_DeviceSpecs specs, int start, float volume) +AUD_Device *BKE_sound_mixdown(Scene *scene, AUD_DeviceSpecs specs, int start, float volume) { return AUD_openMixdownDevice(specs, scene->sound_scene, volume, start / FPS); } -void BKE_sound_create_scene(struct Scene *scene) +void BKE_sound_create_scene(Scene *scene) { /* should be done in version patch, but this gets called before */ - if (scene->r.frs_sec_base == 0) + if (scene->r.frs_sec_base == 0) { scene->r.frs_sec_base = 1; + } scene->sound_scene = AUD_Sequence_create(FPS, scene->audio.flag & AUDIO_MUTE); AUD_Sequence_setSpeedOfSound(scene->sound_scene, scene->audio.speed_of_sound); @@ -465,19 +489,23 @@ void BKE_sound_create_scene(struct Scene *scene) scene->speaker_handles = NULL; } -void BKE_sound_destroy_scene(struct Scene *scene) +void BKE_sound_destroy_scene(Scene *scene) { - if (scene->playback_handle) + if (scene->playback_handle) { AUD_Handle_stop(scene->playback_handle); - if (scene->sound_scrub_handle) + } + if (scene->sound_scrub_handle) { AUD_Handle_stop(scene->sound_scrub_handle); - if (scene->sound_scene) + } + if (scene->sound_scene) { AUD_Sequence_free(scene->sound_scene); - if (scene->speaker_handles) + } + if (scene->speaker_handles) { AUD_destroySet(scene->speaker_handles); + } } -void BKE_sound_reset_scene_specs(struct Scene *scene) +void BKE_sound_reset_scene_specs(Scene *scene) { AUD_Specs specs; @@ -487,21 +515,23 @@ void BKE_sound_reset_scene_specs(struct Scene *scene) AUD_Sequence_setSpecs(scene->sound_scene, specs); } -void BKE_sound_mute_scene(struct Scene *scene, int muted) +void BKE_sound_mute_scene(Scene *scene, int muted) { - if (scene->sound_scene) + if (scene->sound_scene) { AUD_Sequence_setMuted(scene->sound_scene, muted); + } } -void BKE_sound_update_fps(struct Scene *scene) +void BKE_sound_update_fps(Scene *scene) { - if (scene->sound_scene) + if (scene->sound_scene) { AUD_Sequence_setFPS(scene->sound_scene, FPS); + } BKE_sequencer_refresh_sound_length(scene); } -void BKE_sound_update_scene_listener(struct Scene *scene) +void BKE_sound_update_scene_listener(Scene *scene) { AUD_Sequence_setSpeedOfSound(scene->sound_scene, scene->audio.speed_of_sound); AUD_Sequence_setDopplerFactor(scene->sound_scene, scene->audio.doppler_factor); @@ -509,7 +539,7 @@ void BKE_sound_update_scene_listener(struct Scene *scene) } void *BKE_sound_scene_add_scene_sound( - struct Scene *scene, struct Sequence *sequence, int startframe, int endframe, int frameskip) + Scene *scene, Sequence *sequence, int startframe, int endframe, int frameskip) { if (sequence->scene && scene != sequence->scene) { const double fps = FPS; @@ -522,7 +552,7 @@ void *BKE_sound_scene_add_scene_sound( return NULL; } -void *BKE_sound_scene_add_scene_sound_defaults(struct Scene *scene, struct Sequence *sequence) +void *BKE_sound_scene_add_scene_sound_defaults(Scene *scene, Sequence *sequence) { return BKE_sound_scene_add_scene_sound(scene, sequence, @@ -532,7 +562,7 @@ void *BKE_sound_scene_add_scene_sound_defaults(struct Scene *scene, struct Seque } void *BKE_sound_add_scene_sound( - struct Scene *scene, struct Sequence *sequence, int startframe, int endframe, int frameskip) + Scene *scene, Sequence *sequence, int startframe, int endframe, int frameskip) { /* Happens when sequence's sound datablock was removed. */ if (sequence->sound == NULL) { @@ -551,7 +581,7 @@ void *BKE_sound_add_scene_sound( return handle; } -void *BKE_sound_add_scene_sound_defaults(struct Scene *scene, struct Sequence *sequence) +void *BKE_sound_add_scene_sound_defaults(Scene *scene, Sequence *sequence) { return BKE_sound_add_scene_sound(scene, sequence, @@ -560,7 +590,7 @@ void *BKE_sound_add_scene_sound_defaults(struct Scene *scene, struct Sequence *s sequence->startofs + sequence->anim_startofs); } -void BKE_sound_remove_scene_sound(struct Scene *scene, void *handle) +void BKE_sound_remove_scene_sound(Scene *scene, void *handle) { AUD_Sequence_remove(scene->sound_scene, handle); } @@ -571,13 +601,13 @@ void BKE_sound_mute_scene_sound(void *handle, char mute) } void BKE_sound_move_scene_sound( - struct Scene *scene, void *handle, int startframe, int endframe, int frameskip) + Scene *scene, void *handle, int startframe, int endframe, int frameskip) { const double fps = FPS; AUD_SequenceEntry_move(handle, startframe / fps, endframe / fps, frameskip / fps); } -void BKE_sound_move_scene_sound_defaults(struct Scene *scene, struct Sequence *sequence) +void BKE_sound_move_scene_sound_defaults(Scene *scene, Sequence *sequence) { if (sequence->scene_sound) { BKE_sound_move_scene_sound(scene, @@ -598,7 +628,7 @@ void BKE_sound_set_cfra(int cfra) sound_cfra = cfra; } -void BKE_sound_set_scene_volume(struct Scene *scene, float volume) +void BKE_sound_set_scene_volume(Scene *scene, float volume) { AUD_Sequence_setAnimationData(scene->sound_scene, AUD_AP_VOLUME, @@ -623,27 +653,29 @@ void BKE_sound_set_scene_sound_pan(void *handle, float pan, char animated) AUD_SequenceEntry_setAnimationData(handle, AUD_AP_PANNING, sound_cfra, &pan, animated); } -void BKE_sound_update_sequencer(struct Main *main, bSound *sound) +void BKE_sound_update_sequencer(Main *main, bSound *sound) { - struct Scene *scene; + Scene *scene; for (scene = main->scenes.first; scene; scene = scene->id.next) { BKE_sequencer_update_sound(scene, sound); } } -static void sound_start_play_scene(struct Scene *scene) +static void sound_start_play_scene(Scene *scene) { - if (scene->playback_handle) + if (scene->playback_handle) { AUD_Handle_stop(scene->playback_handle); + } BKE_sound_reset_scene_specs(scene); - if ((scene->playback_handle = AUD_Device_play(sound_device, scene->sound_scene, 1))) + if ((scene->playback_handle = AUD_Device_play(sound_device, scene->sound_scene, 1))) { AUD_Handle_setLoopCount(scene->playback_handle, -1); + } } -void BKE_sound_play_scene(struct Scene *scene) +void BKE_sound_play_scene(Scene *scene) { AUD_Status status; const float cur_time = (float)((double)CFRA / FPS); @@ -667,23 +699,25 @@ void BKE_sound_play_scene(struct Scene *scene) AUD_Handle_resume(scene->playback_handle); } - if (scene->audio.flag & AUDIO_SYNC) + if (scene->audio.flag & AUDIO_SYNC) { AUD_playSynchronizer(); + } AUD_Device_unlock(sound_device); } -void BKE_sound_stop_scene(struct Scene *scene) +void BKE_sound_stop_scene(Scene *scene) { if (scene->playback_handle) { AUD_Handle_pause(scene->playback_handle); - if (scene->audio.flag & AUDIO_SYNC) + if (scene->audio.flag & AUDIO_SYNC) { AUD_stopSynchronizer(); + } } } -void BKE_sound_seek_scene(struct Main *bmain, struct Scene *scene) +void BKE_sound_seek_scene(Main *bmain, Scene *scene) { AUD_Status status; bScreen *screen; @@ -747,31 +781,37 @@ void BKE_sound_seek_scene(struct Main *bmain, struct Scene *scene) AUD_Device_unlock(sound_device); } -float BKE_sound_sync_scene(struct Scene *scene) +float BKE_sound_sync_scene(Scene *scene) { // Ugly: Blender doesn't like it when the animation is played back during rendering - if (G.is_rendering) + if (G.is_rendering) { return NAN_FLT; + } if (scene->playback_handle) { - if (scene->audio.flag & AUDIO_SYNC) + if (scene->audio.flag & AUDIO_SYNC) { return AUD_getSynchronizerPosition(scene->playback_handle); - else + } + else { return AUD_Handle_getPosition(scene->playback_handle); + } } return NAN_FLT; } -int BKE_sound_scene_playing(struct Scene *scene) +int BKE_sound_scene_playing(Scene *scene) { // Ugly: Blender doesn't like it when the animation is played back during rendering - if (G.is_rendering) + if (G.is_rendering) { return -1; + } - if (scene->audio.flag & AUDIO_SYNC) + if (scene->audio.flag & AUDIO_SYNC) { return AUD_isSynchronizerPlaying(); - else + } + else { return -1; + } } void BKE_sound_free_waveform(bSound *sound) @@ -976,7 +1016,7 @@ void BKE_sound_force_device(const char *UNUSED(device)) void BKE_sound_init_once(void) { } -void BKE_sound_init(struct Main *UNUSED(bmain)) +void BKE_sound_init(Main *UNUSED(bmain)) { } void BKE_sound_exit(void) @@ -985,110 +1025,107 @@ void BKE_sound_exit(void) void BKE_sound_exit_once(void) { } -void BKE_sound_cache(struct bSound *UNUSED(sound)) +void BKE_sound_cache(bSound *UNUSED(sound)) { } -void BKE_sound_delete_cache(struct bSound *UNUSED(sound)) +void BKE_sound_delete_cache(bSound *UNUSED(sound)) { } -void BKE_sound_load(struct Main *UNUSED(bmain), struct bSound *UNUSED(sound)) +void BKE_sound_load(Main *UNUSED(bmain), bSound *UNUSED(sound)) { } -void BKE_sound_create_scene(struct Scene *UNUSED(scene)) +void BKE_sound_create_scene(Scene *UNUSED(scene)) { } -void BKE_sound_destroy_scene(struct Scene *UNUSED(scene)) +void BKE_sound_destroy_scene(Scene *UNUSED(scene)) { } -void BKE_sound_reset_scene_specs(struct Scene *UNUSED(scene)) +void BKE_sound_reset_scene_specs(Scene *UNUSED(scene)) { } -void BKE_sound_mute_scene(struct Scene *UNUSED(scene), int UNUSED(muted)) +void BKE_sound_mute_scene(Scene *UNUSED(scene), int UNUSED(muted)) { } -void *BKE_sound_scene_add_scene_sound(struct Scene *UNUSED(scene), - struct Sequence *UNUSED(sequence), +void *BKE_sound_scene_add_scene_sound(Scene *UNUSED(scene), + Sequence *UNUSED(sequence), int UNUSED(startframe), int UNUSED(endframe), int UNUSED(frameskip)) { return NULL; } -void *BKE_sound_scene_add_scene_sound_defaults(struct Scene *UNUSED(scene), - struct Sequence *UNUSED(sequence)) +void *BKE_sound_scene_add_scene_sound_defaults(Scene *UNUSED(scene), Sequence *UNUSED(sequence)) { return NULL; } -void *BKE_sound_add_scene_sound(struct Scene *UNUSED(scene), - struct Sequence *UNUSED(sequence), +void *BKE_sound_add_scene_sound(Scene *UNUSED(scene), + Sequence *UNUSED(sequence), int UNUSED(startframe), int UNUSED(endframe), int UNUSED(frameskip)) { return NULL; } -void *BKE_sound_add_scene_sound_defaults(struct Scene *UNUSED(scene), - struct Sequence *UNUSED(sequence)) +void *BKE_sound_add_scene_sound_defaults(Scene *UNUSED(scene), Sequence *UNUSED(sequence)) { return NULL; } -void BKE_sound_remove_scene_sound(struct Scene *UNUSED(scene), void *UNUSED(handle)) +void BKE_sound_remove_scene_sound(Scene *UNUSED(scene), void *UNUSED(handle)) { } void BKE_sound_mute_scene_sound(void *UNUSED(handle), char UNUSED(mute)) { } -void BKE_sound_move_scene_sound(struct Scene *UNUSED(scene), +void BKE_sound_move_scene_sound(Scene *UNUSED(scene), void *UNUSED(handle), int UNUSED(startframe), int UNUSED(endframe), int UNUSED(frameskip)) { } -void BKE_sound_move_scene_sound_defaults(struct Scene *UNUSED(scene), - struct Sequence *UNUSED(sequence)) +void BKE_sound_move_scene_sound_defaults(Scene *UNUSED(scene), Sequence *UNUSED(sequence)) { } -void BKE_sound_play_scene(struct Scene *UNUSED(scene)) +void BKE_sound_play_scene(Scene *UNUSED(scene)) { } -void BKE_sound_stop_scene(struct Scene *UNUSED(scene)) +void BKE_sound_stop_scene(Scene *UNUSED(scene)) { } -void BKE_sound_seek_scene(struct Main *UNUSED(bmain), struct Scene *UNUSED(scene)) +void BKE_sound_seek_scene(Main *UNUSED(bmain), Scene *UNUSED(scene)) { } -float BKE_sound_sync_scene(struct Scene *UNUSED(scene)) +float BKE_sound_sync_scene(Scene *UNUSED(scene)) { return NAN_FLT; } -int BKE_sound_scene_playing(struct Scene *UNUSED(scene)) +int BKE_sound_scene_playing(Scene *UNUSED(scene)) { return -1; } -void BKE_sound_read_waveform(struct bSound *sound, short *stop) +void BKE_sound_read_waveform(bSound *sound, short *stop) { UNUSED_VARS(sound, stop); } -void BKE_sound_init_main(struct Main *UNUSED(bmain)) +void BKE_sound_init_main(Main *UNUSED(bmain)) { } void BKE_sound_set_cfra(int UNUSED(cfra)) { } -void BKE_sound_update_sequencer(struct Main *UNUSED(main), struct bSound *UNUSED(sound)) +void BKE_sound_update_sequencer(Main *UNUSED(main), bSound *UNUSED(sound)) { } -void BKE_sound_update_scene(struct Main *UNUSED(bmain), struct Scene *UNUSED(scene)) +void BKE_sound_update_scene(Main *UNUSED(bmain), Scene *UNUSED(scene)) { } -void BKE_sound_update_scene_sound(void *UNUSED(handle), struct bSound *UNUSED(sound)) +void BKE_sound_update_scene_sound(void *UNUSED(handle), bSound *UNUSED(sound)) { } -void BKE_sound_update_scene_listener(struct Scene *UNUSED(scene)) +void BKE_sound_update_scene_listener(Scene *UNUSED(scene)) { } -void BKE_sound_update_fps(struct Scene *UNUSED(scene)) +void BKE_sound_update_fps(Scene *UNUSED(scene)) { } void BKE_sound_set_scene_sound_volume(void *UNUSED(handle), @@ -1099,7 +1136,7 @@ void BKE_sound_set_scene_sound_volume(void *UNUSED(handle), void BKE_sound_set_scene_sound_pan(void *UNUSED(handle), float UNUSED(pan), char UNUSED(animated)) { } -void BKE_sound_set_scene_volume(struct Scene *UNUSED(scene), float UNUSED(volume)) +void BKE_sound_set_scene_volume(Scene *UNUSED(scene), float UNUSED(volume)) { } void BKE_sound_set_scene_sound_pitch(void *UNUSED(handle), @@ -1107,7 +1144,7 @@ void BKE_sound_set_scene_sound_pitch(void *UNUSED(handle), char UNUSED(animated)) { } -float BKE_sound_get_length(struct bSound *UNUSED(sound)) +float BKE_sound_get_length(bSound *UNUSED(sound)) { return 0; } diff --git a/source/blender/blenkernel/intern/speaker.c b/source/blender/blenkernel/intern/speaker.c index 8565fde4565..c7a0d65a2a9 100644 --- a/source/blender/blenkernel/intern/speaker.c +++ b/source/blender/blenkernel/intern/speaker.c @@ -60,8 +60,10 @@ void *BKE_speaker_add(Main *bmain, const char *name) } /** - * Only copy internal data of Speaker ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of Speaker ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * diff --git a/source/blender/blenkernel/intern/studiolight.c b/source/blender/blenkernel/intern/studiolight.c index 7a95ec3055e..e0ff5fcccca 100644 --- a/source/blender/blenkernel/intern/studiolight.c +++ b/source/blender/blenkernel/intern/studiolight.c @@ -129,12 +129,13 @@ static const char *STUDIOLIGHT_MATCAP_DEFAULT = "basic_1.exr"; static void studiolight_free(struct StudioLight *sl) { #define STUDIOLIGHT_DELETE_ICON(s) \ - { \ + do { \ if (s != 0) { \ BKE_icon_delete(s); \ s = 0; \ } \ - } + } while (0) + if (sl->free_function) { sl->free_function(sl, sl->free_function_data); } @@ -432,9 +433,8 @@ static void studiolight_calculate_radiance_buffer(ImBuf *ibuf, const float ysign, const float zsign) { - ITER_PIXELS( - float, colbuf, 4, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE) - { + ITER_PIXELS ( + float, colbuf, 4, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE) { float direction[3]; direction[index_x] = xsign * (x - 0.5f); direction[index_y] = ysign * (y - 0.5f); @@ -485,12 +485,24 @@ static void studiolight_calculate_radiance_cubemap_buffers(StudioLight *sl) NULL, colbuf, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE); #if 0 - IMB_saveiff(sl->radiance_cubemap_buffers[STUDIOLIGHT_X_POS], "/tmp/studiolight_radiance_left.png", IB_rectfloat); - IMB_saveiff(sl->radiance_cubemap_buffers[STUDIOLIGHT_X_NEG], "/tmp/studiolight_radiance_right.png", IB_rectfloat); - IMB_saveiff(sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_POS], "/tmp/studiolight_radiance_front.png", IB_rectfloat); - IMB_saveiff(sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_NEG], "/tmp/studiolight_radiance_back.png", IB_rectfloat); - IMB_saveiff(sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_POS], "/tmp/studiolight_radiance_bottom.png", IB_rectfloat); - IMB_saveiff(sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_NEG], "/tmp/studiolight_radiance_top.png", IB_rectfloat); + IMB_saveiff(sl->radiance_cubemap_buffers[STUDIOLIGHT_X_POS], + "/tmp/studiolight_radiance_left.png", + IB_rectfloat); + IMB_saveiff(sl->radiance_cubemap_buffers[STUDIOLIGHT_X_NEG], + "/tmp/studiolight_radiance_right.png", + IB_rectfloat); + IMB_saveiff(sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_POS], + "/tmp/studiolight_radiance_front.png", + IB_rectfloat); + IMB_saveiff(sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_NEG], + "/tmp/studiolight_radiance_back.png", + IB_rectfloat); + IMB_saveiff(sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_POS], + "/tmp/studiolight_radiance_bottom.png", + IB_rectfloat); + IMB_saveiff(sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_NEG], + "/tmp/studiolight_radiance_top.png", + IB_rectfloat); #endif MEM_freeN(colbuf); } @@ -531,12 +543,11 @@ static void studiolight_spherical_harmonics_calculate_coefficients(StudioLight * memset(sh, 0, sizeof(float) * 3 * STUDIOLIGHT_SH_COEFS_LEN); for (int face = 0; face < 6; face++) { - ITER_PIXELS(float, - sl->radiance_cubemap_buffers[face]->rect_float, - 4, - STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE, - STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE) - { + ITER_PIXELS (float, + sl->radiance_cubemap_buffers[face]->rect_float, + 4, + STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE, + STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE) { float color[3], cubevec[3], weight; studiolight_calculate_cubemap_vector_weight(cubevec, &weight, face, x, y); mul_v3_v3fl(color, pixel, weight); @@ -647,8 +658,9 @@ static float studiolight_spherical_harmonics_lambda_get(float *sh, float max_lap static void studiolight_spherical_harmonics_apply_windowing(float (*sh)[3], float max_laplacian) { - if (max_laplacian <= 0.0f) + if (max_laplacian <= 0.0f) { return; + } float sh_r[STUDIOLIGHT_SH_COEFS_LEN]; float sh_g[STUDIOLIGHT_SH_COEFS_LEN]; @@ -680,7 +692,8 @@ static float studiolight_spherical_harmonics_geomerics_eval( const float normal[3], float sh0, float sh1, float sh2, float sh3) { /* Use Geomerics non-linear SH. */ - /* http://www.geomerics.com/wp-content/uploads/2015/08/CEDEC_Geomerics_ReconstructingDiffuseLighting1.pdf */ + /* http://www.geomerics.com/wp-content/uploads/2015/08/CEDEC_Geomerics_ReconstructingDiffuseLighting1.pdf + */ float R0 = sh0 * M_1_PI; float R1[3] = {-sh3, sh2, -sh1}; @@ -822,12 +835,11 @@ BLI_INLINE void studiolight_evaluate_specular_radiance_buffer(ImBuf *radiance_bu float accum[3] = {0.0f, 0.0f, 0.0f}; float accum_weight = 0.00001f; - ITER_PIXELS(float, - radiance_buffer->rect_float, - 4, - STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE, - STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE) - { + ITER_PIXELS (float, + radiance_buffer->rect_float, + 4, + STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE, + STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE) { float direction[3]; direction[zoffset] = zsign * 0.5f; direction[xoffset] = x - 0.5f; @@ -1014,12 +1026,11 @@ static void studiolight_calculate_irradiance_equirect_image(StudioLight *sl) STUDIOLIGHT_IRRADIANCE_EQUIRECT_HEIGHT * sizeof(float[4]), __func__); - ITER_PIXELS(float, - colbuf, - 4, - STUDIOLIGHT_IRRADIANCE_EQUIRECT_WIDTH, - STUDIOLIGHT_IRRADIANCE_EQUIRECT_HEIGHT) - { + ITER_PIXELS (float, + colbuf, + 4, + STUDIOLIGHT_IRRADIANCE_EQUIRECT_WIDTH, + STUDIOLIGHT_IRRADIANCE_EQUIRECT_HEIGHT) { float dir[3]; equirect_to_direction(dir, x, y); #ifdef STUDIOLIGHT_IRRADIANCE_METHOD_RADIANCE @@ -1153,8 +1164,7 @@ static void studiolight_radiance_preview(uint *icon_buffer, StudioLight *sl) { BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_EXTERNAL_IMAGE_LOADED); - ITER_PIXELS(uint, icon_buffer, 1, STUDIOLIGHT_ICON_SIZE, STUDIOLIGHT_ICON_SIZE) - { + ITER_PIXELS (uint, icon_buffer, 1, STUDIOLIGHT_ICON_SIZE, STUDIOLIGHT_ICON_SIZE) { float dy = RESCALE_COORD(y); float dx = RESCALE_COORD(x); @@ -1188,8 +1198,7 @@ static void studiolight_matcap_preview(uint *icon_buffer, StudioLight *sl, bool ImBuf *ibuf = sl->equirect_radiance_buffer; - ITER_PIXELS(uint, icon_buffer, 1, STUDIOLIGHT_ICON_SIZE, STUDIOLIGHT_ICON_SIZE) - { + ITER_PIXELS (uint, icon_buffer, 1, STUDIOLIGHT_ICON_SIZE, STUDIOLIGHT_ICON_SIZE) { float dy = RESCALE_COORD(y); float dx = RESCALE_COORD(x); if (flipped) { @@ -1211,8 +1220,7 @@ static void studiolight_matcap_preview(uint *icon_buffer, StudioLight *sl, bool static void studiolight_irradiance_preview(uint *icon_buffer, StudioLight *sl) { - ITER_PIXELS(uint, icon_buffer, 1, STUDIOLIGHT_ICON_SIZE, STUDIOLIGHT_ICON_SIZE) - { + ITER_PIXELS (uint, icon_buffer, 1, STUDIOLIGHT_ICON_SIZE, STUDIOLIGHT_ICON_SIZE) { float dy = RESCALE_COORD(y); float dx = RESCALE_COORD(x); @@ -1276,7 +1284,8 @@ void BKE_studiolight_init(void) BLI_addtail(&studiolights, sl); /* go over the preset folder and add a studiolight for every image with its path */ - /* for portable installs (where USER and SYSTEM paths are the same), only go over LOCAL datafiles once */ + /* for portable installs (where USER and SYSTEM paths are the same), + * only go over LOCAL datafiles once */ /* Also reserve icon space for it. */ if (!BKE_appdir_app_is_portable_install()) { studiolight_add_files_from_datafolder(BLENDER_USER_DATAFILES, diff --git a/source/blender/blenkernel/intern/subdiv_mesh.c b/source/blender/blenkernel/intern/subdiv_mesh.c index d461394bc02..885898d9a57 100644 --- a/source/blender/blenkernel/intern/subdiv_mesh.c +++ b/source/blender/blenkernel/intern/subdiv_mesh.c @@ -267,8 +267,10 @@ static void vertex_interpolation_from_corner(const SubdivMeshContext *ctx, coarse_mloop[coarse_poly->loopstart + (first_loop_index - coarse_poly->loopstart + 1) % coarse_poly->totloop] .v}; - const int last_indices[2] = {coarse_mloop[first_loop_index].v, - coarse_mloop[last_loop_index].v}; + const int last_indices[2] = { + coarse_mloop[first_loop_index].v, + coarse_mloop[last_loop_index].v, + }; CustomData_interp(vertex_data, &vertex_interpolation->vertex_data_storage, first_indices, @@ -393,8 +395,10 @@ static void loop_interpolation_from_corner(const SubdivMeshContext *ctx, const int second_loop_index = base_loop_index + (first_loop_index - base_loop_index + 1) % coarse_poly->totloop; const int first_indices[2] = {first_loop_index, second_loop_index}; - const int last_indices[2] = {loops_of_ptex.last_loop - coarse_mloop, - loops_of_ptex.first_loop - coarse_mloop}; + const int last_indices[2] = { + loops_of_ptex.last_loop - coarse_mloop, + loops_of_ptex.first_loop - coarse_mloop, + }; CustomData_interp( loop_data, &loop_interpolation->loop_data_storage, first_indices, weights, NULL, 2, 1); CustomData_interp( diff --git a/source/blender/blenkernel/intern/subsurf_ccg.c b/source/blender/blenkernel/intern/subsurf_ccg.c index cba391a90a8..ad81fc49b19 100644 --- a/source/blender/blenkernel/intern/subsurf_ccg.c +++ b/source/blender/blenkernel/intern/subsurf_ccg.c @@ -156,10 +156,12 @@ static CCGSubSurf *_getSubSurf(CCGSubSurf *prevSS, int subdivLevels, int numLaye ifc.numLayers = numLayers; ifc.vertDataSize = sizeof(float) * numLayers; normalOffset += sizeof(float) * numLayers; - if (flags & CCG_CALC_NORMALS) + if (flags & CCG_CALC_NORMALS) { ifc.vertDataSize += sizeof(float) * 3; - if (flags & CCG_ALLOC_MASK) + } + if (flags & CCG_ALLOC_MASK) { ifc.vertDataSize += sizeof(float); + } ifc.simpleSubdiv = !!(flags & CCG_SIMPLE_SUBDIV); if (useArena) { @@ -187,10 +189,12 @@ static CCGSubSurf *_getSubSurf(CCGSubSurf *prevSS, int subdivLevels, int numLaye ccgSubSurf_setAllocMask(ccgSS, 1, sizeof(float) * numLayers); } - if (flags & CCG_CALC_NORMALS) + if (flags & CCG_CALC_NORMALS) { ccgSubSurf_setCalcVertexNormals(ccgSS, 1, normalOffset); - else + } + else { ccgSubSurf_setCalcVertexNormals(ccgSS, 0, 0); + } return ccgSS; } @@ -270,10 +274,12 @@ static void get_face_uv_map_vert( for (j = 0; j < nverts; j++) { for (nv = v = BKE_mesh_uv_vert_map_get_vert(vmap, ml[j].v); v; v = v->next) { - if (v->separate) + if (v->separate) { nv = v; - if (v->poly_index == fi) + } + if (v->poly_index == fi) { break; + } } fverts[j] = POINTER_FROM_UINT(mpoly[nv->poly_index].loopstart + nv->loop_of_poly_index); @@ -299,23 +305,27 @@ static int ss_sync_from_uv(CCGSubSurf *ss, CCGSubSurf *origss, DerivedMesh *dm, limit[0] = limit[1] = STD_UV_CONNECT_LIMIT; /* previous behavior here is without accounting for winding, however this causes stretching in - * UV map in really simple cases with mirror + subsurf, see second part of T44530. Also, initially - * intention is to treat merged vertices from mirror modifier as seams. + * UV map in really simple cases with mirror + subsurf, see second part of T44530. + * Also, initially intention is to treat merged vertices from mirror modifier as seams. * This fixes a very old regression (2.49 was correct here) */ vmap = BKE_mesh_uv_vert_map_create(mpoly, mloop, mloopuv, totface, totvert, limit, false, true); - if (!vmap) + if (!vmap) { return 0; + } ccgSubSurf_initFullSync(ss); /* create vertices */ for (i = 0; i < totvert; i++) { - if (!BKE_mesh_uv_vert_map_get_vert(vmap, i)) + if (!BKE_mesh_uv_vert_map_get_vert(vmap, i)) { continue; + } - for (v = BKE_mesh_uv_vert_map_get_vert(vmap, i)->next; v; v = v->next) - if (v->separate) + for (v = BKE_mesh_uv_vert_map_get_vert(vmap, i)->next; v; v = v->next) { + if (v->separate) { break; + } + } seam = (v != NULL); @@ -486,8 +496,9 @@ static void set_subsurf_legacy_uv(CCGSubSurf *ss, DerivedMesh *dm, DerivedMesh * MTFace *tface = CustomData_get_layer_n(&result->faceData, CD_MTFACE, n); MLoopUV *mloopuv = CustomData_get_layer_n(&result->loopData, CD_MLOOPUV, n); - if (!dmloopuv || (!tface && !mloopuv)) + if (!dmloopuv || (!tface && !mloopuv)) { return; + } /* create a CCGSubSurf from uv's */ uvss = _getSubSurf(NULL, ccgSubSurf_getSubdivisionLevels(ss), 2, CCG_USE_ARENA); @@ -643,12 +654,14 @@ static void free_ss_weights(WeightTable *wtable) int i; for (i = 0; i < wtable->len; i++) { - if (wtable->weight_table[i].valid) + if (wtable->weight_table[i].valid) { MEM_freeN(wtable->weight_table[i].w); + } } - if (wtable->weight_table) + if (wtable->weight_table) { MEM_freeN(wtable->weight_table); + } } static void ss_sync_ccg_from_derivedmesh(CCGSubSurf *ss, @@ -733,7 +746,7 @@ static void ss_sync_ccg_from_derivedmesh(CCGSubSurf *ss, static int hasGivenError = 0; if (!hasGivenError) { - //XXX error("Unrecoverable error in SubSurf calculation," + // XXX error("Unrecoverable error in SubSurf calculation," // " mesh is inconsistent."); hasGivenError = 1; @@ -807,18 +820,24 @@ static int ccgDM_getFaceMapIndex(CCGSubSurf *ss, CCGFace *f) static void minmax_v3_v3v3(const float vec[3], float min[3], float max[3]) { - if (min[0] > vec[0]) + if (min[0] > vec[0]) { min[0] = vec[0]; - if (min[1] > vec[1]) + } + if (min[1] > vec[1]) { min[1] = vec[1]; - if (min[2] > vec[2]) + } + if (min[2] > vec[2]) { min[2] = vec[2]; - if (max[0] < vec[0]) + } + if (max[0] < vec[0]) { max[0] = vec[0]; - if (max[1] < vec[1]) + } + if (max[1] < vec[1]) { max[1] = vec[1]; - if (max[2] < vec[2]) + } + if (max[2] < vec[2]) { max[2] = vec[2]; + } } static void ccgDM_getMinMax(DerivedMesh *dm, float r_min[3], float r_max[3]) @@ -841,8 +860,9 @@ static void ccgDM_getMinMax(DerivedMesh *dm, float r_min[3], float r_max[3]) CCG_key_top_level(&key, ss); - if (!ccgSubSurf_getNumVerts(ss)) + if (!ccgSubSurf_getNumVerts(ss)) { r_min[0] = r_min[1] = r_min[2] = r_max[0] = r_max[1] = r_max[2] = 0.0; + } for (ccgSubSurf_initVertIterator(ss, &vi); !ccgVertIterator_isStopped(&vi); ccgVertIterator_next(&vi)) { @@ -857,8 +877,9 @@ static void ccgDM_getMinMax(DerivedMesh *dm, float r_min[3], float r_max[3]) CCGEdge *e = ccgEdgeIterator_getCurrent(&ei); CCGElem *edgeData = ccgSubSurf_getEdgeDataArray(ss, e); - for (i = 0; i < edgeSize; i++) + for (i = 0; i < edgeSize; i++) { minmax_v3_v3v3(CCG_elem_offset_co(&key, edgeData, i), r_min, r_max); + } } for (ccgSubSurf_initFaceIterator(ss, &fi); !ccgFaceIterator_isStopped(&fi); @@ -869,9 +890,11 @@ static void ccgDM_getMinMax(DerivedMesh *dm, float r_min[3], float r_max[3]) for (S = 0; S < numVerts; S++) { CCGElem *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S); - for (y = 0; y < gridSize; y++) - for (x = 0; x < gridSize; x++) + for (y = 0; y < gridSize; y++) { + for (x = 0; x < gridSize; x++) { minmax_v3_v3v3(CCG_grid_elem_co(&key, faceGridData, x, y), r_min, r_max); + } + } } } } @@ -1083,8 +1106,9 @@ static void ccgDM_getFinalEdge(DerivedMesh *dm, int edgeNum, MEdge *med) e = ccgdm->edgeMap[i].edge; - if (!ccgSubSurf_getEdgeNumFaces(e)) + if (!ccgSubSurf_getEdgeNumFaces(e)) { flags |= ME_LOOSEEDGE; + } x = edgeNum - ccgdm->edgeMap[i].startEdge; @@ -1092,10 +1116,12 @@ static void ccgDM_getFinalEdge(DerivedMesh *dm, int edgeNum, MEdge *med) med->v2 = getEdgeIndex(ss, e, x + 1, edgeSize); edgeFlag = (ccgdm->edgeFlags) ? &ccgdm->edgeFlags[i] : NULL; - if (edgeFlag) + if (edgeFlag) { flags |= (*edgeFlag & (ME_SEAM | ME_SHARP)) | ME_EDGEDRAW | ME_EDGERENDER; - else + } + else { flags |= ME_EDGEDRAW | ME_EDGERENDER; + } med->flag = flags; } @@ -1119,8 +1145,9 @@ static void ccgDM_getFinalFace(DerivedMesh *dm, int faceNum, MFace *mf) DMFlagMat *faceFlags = ccgdm->faceFlags; memset(mf, 0, sizeof(*mf)); - if (faceNum >= ccgdm->dm.numTessFaceData) + if (faceNum >= ccgdm->dm.numTessFaceData) { return; + } i = ccgdm->reverseFaceMap[faceNum]; @@ -1173,8 +1200,9 @@ void subsurf_copy_grid_hidden(DerivedMesh *dm, int factor = BKE_ccg_factor(level, md->level); BLI_bitmap *hidden = md->hidden; - if (!hidden) + if (!hidden) { continue; + } for (y = 0; y < gridSize; y++) { for (x = 0; x < gridSize; x++) { @@ -1182,8 +1210,9 @@ void subsurf_copy_grid_hidden(DerivedMesh *dm, vndx = getFaceIndex(ss, f, j, x, y, edgeSize, gridSize); offset = (y * factor) * hidden_gridsize + (x * factor); - if (BLI_BITMAP_TEST(hidden, offset)) + if (BLI_BITMAP_TEST(hidden, offset)) { mvert[vndx].flag |= ME_HIDE; + } } } } @@ -1211,8 +1240,9 @@ void subsurf_copy_grid_paint_mask(DerivedMesh *dm, for (j = 0; j < p->totloop; j++) { const GridPaintMask *gpm = &grid_paint_mask[p->loopstart + j]; - if (!gpm->data) + if (!gpm->data) { continue; + } factor = BKE_ccg_factor(level, gpm->level); gpm_gridsize = BKE_ccg_gridsize(gpm->level); @@ -1699,8 +1729,8 @@ static void ccgDM_foreachMappedLoop(DerivedMesh *dm, void *userData, DMForeachFlag flag) { - /* We can't use dm->getLoopDataLayout(dm) here, we want to always access dm->loopData, EditDerivedBMesh would - * return loop data from bmesh itself. */ + /* We can't use dm->getLoopDataLayout(dm) here, we want to always access dm->loopData, + * EditDerivedBMesh would return loop data from bmesh itself. */ const float(*lnors)[3] = (flag & DM_FOREACH_USE_NORMAL) ? DM_get_loop_data_layer(dm, CD_NORMAL) : NULL; @@ -1779,26 +1809,34 @@ static void ccgDM_release(DerivedMesh *dm) } if (ccgdm->multires.mmd) { - if (ccgdm->multires.modified_flags & MULTIRES_COORDS_MODIFIED) + if (ccgdm->multires.modified_flags & MULTIRES_COORDS_MODIFIED) { multires_modifier_update_mdisps(dm, NULL); - if (ccgdm->multires.modified_flags & MULTIRES_HIDDEN_MODIFIED) + } + if (ccgdm->multires.modified_flags & MULTIRES_HIDDEN_MODIFIED) { multires_modifier_update_hidden(dm); + } } } - if (ccgdm->ehash) + if (ccgdm->ehash) { BLI_edgehash_free(ccgdm->ehash, NULL); + } - if (ccgdm->reverseFaceMap) + if (ccgdm->reverseFaceMap) { MEM_freeN(ccgdm->reverseFaceMap); - if (ccgdm->gridFaces) + } + if (ccgdm->gridFaces) { MEM_freeN(ccgdm->gridFaces); - if (ccgdm->gridData) + } + if (ccgdm->gridData) { MEM_freeN(ccgdm->gridData); - if (ccgdm->gridOffset) + } + if (ccgdm->gridOffset) { MEM_freeN(ccgdm->gridOffset); - if (ccgdm->gridFlagMats) + } + if (ccgdm->gridFlagMats) { MEM_freeN(ccgdm->gridFlagMats); + } if (ccgdm->gridHidden) { /* Using dm->getNumGrids(dm) accesses freed memory */ uint numGrids = ccgdm->numGrid; @@ -1809,12 +1847,15 @@ static void ccgDM_release(DerivedMesh *dm) } MEM_freeN(ccgdm->gridHidden); } - if (ccgdm->freeSS) + if (ccgdm->freeSS) { ccgSubSurf_free(ccgdm->ss); - if (ccgdm->pmap) + } + if (ccgdm->pmap) { MEM_freeN(ccgdm->pmap); - if (ccgdm->pmap_mem) + } + if (ccgdm->pmap_mem) { MEM_freeN(ccgdm->pmap_mem); + } MEM_freeN(ccgdm->edgeFlags); MEM_freeN(ccgdm->faceFlags); if (ccgdm->useGpuBackend == false) { @@ -1855,8 +1896,9 @@ static void *ccgDM_get_vert_data_layer(DerivedMesh *dm, int type) totnone = dm->numVertData - totorig; /* original vertices are at the end */ - for (a = 0; a < totnone; a++) + for (a = 0; a < totnone; a++) { origindex[a] = ORIGINDEX_NONE; + } for (index = 0; index < totorig; index++, a++) { CCGVert *v = ccgdm->vertMap[index].vert; @@ -1894,15 +1936,17 @@ static void *ccgDM_get_edge_data_layer(DerivedMesh *dm, int type) totnone = dm->numEdgeData - totorig; /* original edges are at the end */ - for (a = 0; a < totnone; a++) + for (a = 0; a < totnone; a++) { origindex[a] = ORIGINDEX_NONE; + } for (index = 0; index < totedge; index++) { CCGEdge *e = ccgdm->edgeMap[index].edge; int mapIndex = ccgDM_getEdgeMapIndex(ss, e); - for (i = 0; i < edgeSize - 1; i++, a++) + for (i = 0; i < edgeSize - 1; i++, a++) { origindex[a] = mapIndex; + } } return origindex; @@ -1934,10 +1978,9 @@ static void *ccgDM_get_tessface_data_layer(DerivedMesh *dm, int type) if (type == CD_TESSLOOPNORMAL) { /* Create tessloopnormal on demand to save memory. */ - /* Note that since tessellated face corners are the same a loops in CCGDM, and since all faces have four - * loops/corners, we can simplify the code here by converting tessloopnormals from 'short (*)[4][3]' - * to 'short (*)[3]'. - */ + /* Note that since tessellated face corners are the same a loops in CCGDM, + * and since all faces have four loops/corners, we can simplify the code + * here by converting tessloopnormals from 'short (*)[4][3]' to 'short (*)[3]'. */ short(*tlnors)[3]; /* Avoid re-creation if the layer exists already */ @@ -1956,7 +1999,8 @@ static void *ccgDM_get_tessface_data_layer(DerivedMesh *dm, int type) DM_add_tessface_layer(dm, CD_TESSLOOPNORMAL, CD_CALLOC, NULL); tlnors = tlnors_it = (short(*)[3])DM_get_tessface_data_layer(dm, CD_TESSLOOPNORMAL); - /* With ccgdm, we have a simple one to one mapping between loops and tessellated face corners. */ + /* With ccgdm, we have a simple one to one mapping between loops + * and tessellated face corners. */ for (i = 0; i < numLoops; ++i, ++tlnors_it, ++lnors) { normal_float_to_short_v3(*tlnors_it, *lnors); } @@ -1994,8 +2038,9 @@ static void *ccgDM_get_poly_data_layer(DerivedMesh *dm, int type) int numVerts = ccgSubSurf_getFaceNumVerts(f); int mapIndex = ccgDM_getFaceMapIndex(ss, f); - for (i = 0; i < gridFaces * gridFaces * numVerts; i++, a++) + for (i = 0; i < gridFaces * gridFaces * numVerts; i++, a++) { origindex[a] = mapIndex; + } } return origindex; @@ -2076,8 +2121,9 @@ static void ccgdm_create_grids(DerivedMesh *dm) int *gridOffset; int index, numFaces, numGrids, S, gIndex /*, gridSize*/; - if (ccgdm->gridData) + if (ccgdm->gridData) { return; + } numGrids = ccgDM_getNumGrids(dm); numFaces = ccgSubSurf_getNumFaces(ss); @@ -2182,8 +2228,9 @@ static int ccgDM_use_grid_pbvh(CCGDerivedMesh *ccgdm) /* both of multires and subsurf modifiers are CCG, but * grids should only be used when sculpting on multires */ - if (!mmd) + if (!mmd) { return 0; + } return 1; } @@ -2201,14 +2248,15 @@ static struct PBVH *ccgDM_getPBVH(Object *ob, DerivedMesh *dm) return NULL; } - if (!ob->sculpt) + if (!ob->sculpt) { return NULL; + } bool grid_pbvh = ccgDM_use_grid_pbvh(ccgdm); if ((ob->mode & OB_MODE_SCULPT) == 0) { /* In vwpaint, we may use a grid_pbvh for multires/subsurf, under certain conditions. - * More complex cases break 'history' trail back to original vertices, in that case we fall back to - * deformed cage only (i.e. original deformed mesh). */ + * More complex cases break 'history' trail back to original vertices, + * in that case we fall back to deformed cage only (i.e. original deformed mesh). */ VirtualModifierData virtualModifierData; ModifierData *md = modifiers_getVirtualModifierList(ob, &virtualModifierData); @@ -2246,8 +2294,8 @@ static struct PBVH *ccgDM_getPBVH(Object *ob, DerivedMesh *dm) } if (ob->sculpt->pbvh) { - /* Note that we have to clean up exisitng pbvh instead of updating it in case it does not match current - * grid_pbvh status. */ + /* Note that we have to clean up exisitng pbvh instead of updating it in case it does not + * match current grid_pbvh status. */ const PBVHType pbvh_type = BKE_pbvh_type(ob->sculpt->pbvh); if (grid_pbvh) { if (pbvh_type == PBVH_GRIDS) { @@ -2313,6 +2361,7 @@ static struct PBVH *ccgDM_getPBVH(Object *ob, DerivedMesh *dm) me->mvert, me->totvert, &me->vdata, + &me->ldata, looptri, looptris_num); @@ -2389,7 +2438,8 @@ 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 */ + /* reuse of ccgDM_getNumTessFaces is intentional here: + * subsurf polys are just created from tessfaces */ ccgdm->dm.getNumPolys = ccgDM_getNumPolys; ccgdm->dm.getNumTessFaces = ccgDM_getNumTessFaces; @@ -2692,8 +2742,9 @@ static void set_ccgdm_all_geometry(CCGDerivedMesh *ccgdm, ccgdm->edgeMap[index].startVert = vertNum; ccgdm->edgeMap[index].startEdge = edgeNum; - if (edgeIdx >= 0 && edgeFlags) + if (edgeIdx >= 0 && edgeFlags) { edgeFlags[edgeIdx] = medge[edgeIdx].flag; + } /* set the edge base vert */ *((int *)ccgSubSurf_getEdgeUserData(ss, e)) = vertNum; @@ -2732,8 +2783,9 @@ static void set_ccgdm_all_geometry(CCGDerivedMesh *ccgdm, int numlayer = CustomData_number_of_layers(ldata, CD_MLOOPUV); int dmnumlayer = CustomData_number_of_layers(dmldata, CD_MLOOPUV); - for (i = 0; i < numlayer && i < dmnumlayer; i++) + for (i = 0; i < numlayer && i < dmnumlayer; i++) { set_subsurf_uv(ss, dm, &ccgdm->dm, i); + } } for (index = 0; index < totvert; ++index) { @@ -2911,8 +2963,9 @@ struct DerivedMesh *subsurf_make_derived_from_derived(struct DerivedMesh *dm, get_render_subsurf_level(&scene->r, smd->renderLevels, true) : smd->renderLevels; - if (levels == 0) + if (levels == 0) { return dm; + } ss = _getSubSurf(NULL, levels, 3, useSimple | CCG_USE_ARENA | CCG_CALC_NORMALS); @@ -2979,8 +3032,9 @@ struct DerivedMesh *subsurf_make_derived_from_derived(struct DerivedMesh *dm, } } - if (flags & SUBSURF_ALLOC_PAINT_MASK) + if (flags & SUBSURF_ALLOC_PAINT_MASK) { ccg_flags |= CCG_ALLOC_MASK; + } ss = _getSubSurf(prevSS, levels, 3, ccg_flags); #ifdef WITH_OPENSUBDIV @@ -2990,13 +3044,16 @@ struct DerivedMesh *subsurf_make_derived_from_derived(struct DerivedMesh *dm, result = getCCGDerivedMesh(ss, drawInteriorEdges, useSubsurfUv, dm, use_gpu_backend); - if (flags & SUBSURF_IS_FINAL_CALC) + if (flags & SUBSURF_IS_FINAL_CALC) { smd->mCache = ss; - else + } + else { result->freeSS = 1; + } - if (flags & SUBSURF_ALLOC_PAINT_MASK) + if (flags & SUBSURF_ALLOC_PAINT_MASK) { ccgSubSurf_setNumLayers(ss, 4); + } } } @@ -3040,8 +3097,9 @@ void subsurf_calculate_limit_positions(Mesh *me, float (*r_positions)[3]) /* ad-hoc correction for boundary vertices, to at least avoid them * moving completely out of place (brecht) */ - if (numFaces && numFaces != N) + if (numFaces && numFaces != N) { mul_v3_fl(face_sum, (float)N / (float)numFaces); + } co = ccgSubSurf_getVertData(ss, v); r_positions[idx][0] = (co[0] * N * N + edge_sum[0] * 4 + face_sum[0]) / (N * (N + 5)); diff --git a/source/blender/blenkernel/intern/suggestions.c b/source/blender/blenkernel/intern/suggestions.c index 7631afaa680..47d536f4f4f 100644 --- a/source/blender/blenkernel/intern/suggestions.c +++ b/source/blender/blenkernel/intern/suggestions.c @@ -39,7 +39,7 @@ static Text *activeToolText = NULL; static SuggList suggestions = {NULL, NULL, NULL, NULL, NULL}; static char *documentation = NULL; -//static int doc_lines = 0; +// static int doc_lines = 0; static void txttl_free_suggest(void) { @@ -74,8 +74,9 @@ void free_texttools(void) void texttool_text_set_active(Text *text) { - if (activeToolText == text) + if (activeToolText == text) { return; + } texttool_text_clear(); activeToolText = text; } @@ -123,14 +124,16 @@ void texttool_suggest_add(const char *name, char type) /* Newitem comes after this item, insert here */ if (cmp >= 0) { newitem->prev = item; - if (item->next) + if (item->next) { item->next->prev = newitem; + } newitem->next = item->next; item->next = newitem; /* At last item, set last pointer here */ - if (item == suggestions.last) + if (item == suggestions.last) { suggestions.last = newitem; + } break; } } @@ -150,8 +153,9 @@ void texttool_suggest_prefix(const char *prefix, const int prefix_len) SuggItem *match, *first, *last; int cmp, top = 0; - if (!suggestions.first) + if (!suggestions.first) { return; + } if (prefix_len == 0) { suggestions.selected = suggestions.firstmatch = suggestions.first; suggestions.lastmatch = suggestions.last; @@ -176,8 +180,9 @@ void texttool_suggest_prefix(const char *prefix, const int prefix_len) top++; } if (first) { - if (!last) + if (!last) { last = suggestions.last; + } suggestions.firstmatch = first; suggestions.lastmatch = last; suggestions.selected = first; @@ -228,8 +233,9 @@ void texttool_docs_show(const char *docs) { int len; - if (!docs) + if (!docs) { return; + } len = strlen(docs); diff --git a/source/blender/blenkernel/intern/text.c b/source/blender/blenkernel/intern/text.c index ef4b9d95324..f07751e349f 100644 --- a/source/blender/blenkernel/intern/text.c +++ b/source/blender/blenkernel/intern/text.c @@ -209,8 +209,9 @@ void BKE_text_init(Text *ta) ta->nlines = 1; ta->flags = TXT_ISDIRTY | TXT_ISMEM; - if ((U.flag & USER_TXT_TABSTOSPACES_DISABLE) == 0) + if ((U.flag & USER_TXT_TABSTOSPACES_DISABLE) == 0) { ta->flags |= TXT_TABSTOSPACES; + } BLI_listbase_clear(&ta->lines); @@ -252,8 +253,9 @@ int txt_extended_ascii_as_utf8(char **str) int added = 0; while ((*str)[i]) { - if ((bad_char = BLI_utf8_invalid_byte(*str + i, length - i)) == -1) + if ((bad_char = BLI_utf8_invalid_byte(*str + i, length - i)) == -1) { break; + } added++; i += bad_char + 1; @@ -321,8 +323,9 @@ static void text_from_buf(Text *text, const unsigned char *buffer, const int len tmp->line = (char *)MEM_mallocN(llen + 1, "textline_string"); tmp->format = NULL; - if (llen) + if (llen) { memcpy(tmp->line, &buffer[i - llen], llen); + } tmp->line[llen] = 0; tmp->len = llen; @@ -350,8 +353,9 @@ static void text_from_buf(Text *text, const unsigned char *buffer, const int len tmp->line = (char *)MEM_mallocN(llen + 1, "textline_string"); tmp->format = NULL; - if (llen) + if (llen) { memcpy(tmp->line, &buffer[i - llen], llen); + } tmp->line[llen] = 0; tmp->len = llen; @@ -412,8 +416,9 @@ Text *BKE_text_load_ex(Main *bmain, const char *file, const char *relpath, const BLI_stat_t st; BLI_strncpy(filepath_abs, file, FILE_MAX); - if (relpath) /* can be NULL (bg mode) */ + if (relpath) { /* can be NULL (bg mode) */ BLI_path_abs(filepath_abs, relpath); + } buffer = BLI_file_read_text_as_mem(filepath_abs, 0, &buffer_len); if (buffer == NULL) { @@ -426,8 +431,9 @@ Text *BKE_text_load_ex(Main *bmain, const char *file, const char *relpath, const BLI_listbase_clear(&ta->lines); ta->curl = ta->sell = NULL; - if ((U.flag & USER_TXT_TABSTOSPACES_DISABLE) == 0) + if ((U.flag & USER_TXT_TABSTOSPACES_DISABLE) == 0) { ta->flags = TXT_TABSTOSPACES; + } if (is_internal == false) { ta->name = MEM_mallocN(strlen(file) + 1, "text_name"); @@ -458,8 +464,10 @@ Text *BKE_text_load(Main *bmain, const char *file, const char *relpath) } /** - * Only copy internal data of Text ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of Text ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * @@ -545,25 +553,30 @@ int BKE_text_file_modified_check(Text *text) int result; char file[FILE_MAX]; - if (!text->name) + if (!text->name) { return 0; + } BLI_strncpy(file, text->name, FILE_MAX); BLI_path_abs(file, BKE_main_blendfile_path_from_global()); - if (!BLI_exists(file)) + if (!BLI_exists(file)) { return 2; + } result = BLI_stat(file, &st); - if (result == -1) + if (result == -1) { return -1; + } - if ((st.st_mode & S_IFMT) != S_IFREG) + if ((st.st_mode & S_IFMT) != S_IFREG) { return -1; + } - if (st.st_mtime > text->mtime) + if (st.st_mtime > text->mtime) { return 1; + } return 0; } @@ -574,19 +587,22 @@ void BKE_text_file_modified_ignore(Text *text) int result; char file[FILE_MAX]; - if (!text->name) + if (!text->name) { return; + } BLI_strncpy(file, text->name, FILE_MAX); BLI_path_abs(file, BKE_main_blendfile_path_from_global()); - if (!BLI_exists(file)) + if (!BLI_exists(file)) { return; + } result = BLI_stat(file, &st); - if (result == -1 || (st.st_mode & S_IFMT) != S_IFREG) + if (result == -1 || (st.st_mode & S_IFMT) != S_IFREG) { return; + } text->mtime = st.st_mtime; } @@ -597,10 +613,12 @@ void BKE_text_file_modified_ignore(Text *text) static void make_new_line(TextLine *line, char *newline) { - if (line->line) + if (line->line) { MEM_freeN(line->line); - if (line->format) + } + if (line->format) { MEM_freeN(line->format); + } line->line = newline; line->len = strlen(newline); @@ -611,8 +629,9 @@ static TextLine *txt_new_line(const char *str) { TextLine *tmp; - if (!str) + if (!str) { str = ""; + } tmp = (TextLine *)MEM_mallocN(sizeof(TextLine), "textline"); tmp->line = MEM_mallocN(strlen(str) + 1, "textline_string"); @@ -647,28 +666,35 @@ void txt_clean_text(Text *text) TextLine **top, **bot; if (!text->lines.first) { - if (text->lines.last) + if (text->lines.last) { text->lines.first = text->lines.last; - else + } + else { text->lines.first = text->lines.last = txt_new_line(NULL); + } } - if (!text->lines.last) + if (!text->lines.last) { text->lines.last = text->lines.first; + } top = (TextLine **)&text->lines.first; bot = (TextLine **)&text->lines.last; - while ((*top)->prev) + while ((*top)->prev) { *top = (*top)->prev; - while ((*bot)->next) + } + while ((*bot)->next) { *bot = (*bot)->next; + } if (!text->curl) { - if (text->sell) + if (text->sell) { text->curl = text->sell; - else + } + else { text->curl = text->lines.first; + } text->curc = 0; } @@ -683,15 +709,18 @@ int txt_get_span(TextLine *from, TextLine *to) int ret = 0; TextLine *tmp = from; - if (!to || !from) + if (!to || !from) { return 0; - if (from == to) + } + if (from == to) { return 0; + } /* Look forwards */ while (tmp) { - if (tmp == to) + if (tmp == to) { return ret; + } ret++; tmp = tmp->next; } @@ -701,13 +730,15 @@ int txt_get_span(TextLine *from, TextLine *to) tmp = from; ret = 0; while (tmp) { - if (tmp == to) + if (tmp == to) { break; + } ret--; tmp = tmp->prev; } - if (!tmp) + if (!tmp) { ret = 0; + } } return ret; @@ -717,8 +748,9 @@ static void txt_make_dirty(Text *text) { text->flags |= TXT_ISDIRTY; #ifdef WITH_PYTHON - if (text->compiled) + if (text->compiled) { BPY_text_free_code(text); + } #endif } @@ -787,8 +819,9 @@ int txt_utf8_column_to_offset(const char *str, int column) int offset = 0, pos = 0, col; while (*(str + offset) && pos < column) { col = BLI_str_utf8_char_width_safe(str + offset); - if (pos + col > column) + if (pos + col > column) { break; + } offset += BLI_str_utf8_size_safe(str + offset); pos += col; } @@ -800,14 +833,16 @@ void txt_move_up(Text *text, const bool sel) TextLine **linep; int *charp; - if (sel) + if (sel) { txt_curs_sel(text, &linep, &charp); + } else { txt_pop_first(text); txt_curs_cur(text, &linep, &charp); } - if (!*linep) + if (!*linep) { return; + } if ((*linep)->prev) { int column = txt_utf8_offset_to_column((*linep)->line, *charp); @@ -818,8 +853,9 @@ void txt_move_up(Text *text, const bool sel) txt_move_bol(text, sel); } - if (!sel) + if (!sel) { txt_pop_sel(text); + } } void txt_move_down(Text *text, const bool sel) @@ -827,14 +863,16 @@ void txt_move_down(Text *text, const bool sel) TextLine **linep; int *charp; - if (sel) + if (sel) { txt_curs_sel(text, &linep, &charp); + } else { txt_pop_last(text); txt_curs_cur(text, &linep, &charp); } - if (!*linep) + if (!*linep) { return; + } if ((*linep)->next) { int column = txt_utf8_offset_to_column((*linep)->line, *charp); @@ -845,8 +883,9 @@ void txt_move_down(Text *text, const bool sel) txt_move_eol(text, sel); } - if (!sel) + if (!sel) { txt_pop_sel(text); + } } int txt_calc_tab_left(TextLine *tl, int ch) @@ -855,15 +894,17 @@ int txt_calc_tab_left(TextLine *tl, int ch) int tabsize = (ch < TXT_TABSIZE) ? ch : TXT_TABSIZE; - for (int i = 0; i < ch; i++) + for (int i = 0; i < ch; i++) { if (tl->line[i] != ' ') { tabsize = 0; break; } + } /* if in the middle of the space-tab */ - if (tabsize && ch % TXT_TABSIZE != 0) + if (tabsize && ch % TXT_TABSIZE != 0) { tabsize = (ch % TXT_TABSIZE); + } return tabsize; } @@ -895,14 +936,16 @@ void txt_move_left(Text *text, const bool sel) int *charp; int tabsize = 0; - if (sel) + if (sel) { txt_curs_sel(text, &linep, &charp); + } else { txt_pop_first(text); txt_curs_cur(text, &linep, &charp); } - if (!*linep) + if (!*linep) { return; + } if (*charp == 0) { if ((*linep)->prev) { @@ -926,8 +969,9 @@ void txt_move_left(Text *text, const bool sel) } } - if (!sel) + if (!sel) { txt_pop_sel(text); + } } void txt_move_right(Text *text, const bool sel) @@ -935,14 +979,16 @@ void txt_move_right(Text *text, const bool sel) TextLine **linep; int *charp; - if (sel) + if (sel) { txt_curs_sel(text, &linep, &charp); + } else { txt_pop_last(text); txt_curs_cur(text, &linep, &charp); } - if (!*linep) + if (!*linep) { return; + } if (*charp == (*linep)->len) { if ((*linep)->next) { @@ -967,8 +1013,9 @@ void txt_move_right(Text *text, const bool sel) } } - if (!sel) + if (!sel) { txt_pop_sel(text); + } } void txt_jump_left(Text *text, const bool sel, const bool use_init_step) @@ -976,20 +1023,23 @@ void txt_jump_left(Text *text, const bool sel, const bool use_init_step) TextLine **linep; int *charp; - if (sel) + if (sel) { txt_curs_sel(text, &linep, &charp); + } else { txt_pop_first(text); txt_curs_cur(text, &linep, &charp); } - if (!*linep) + if (!*linep) { return; + } BLI_str_cursor_step_utf8( (*linep)->line, (*linep)->len, charp, STRCUR_DIR_PREV, STRCUR_JUMP_DELIM, use_init_step); - if (!sel) + if (!sel) { txt_pop_sel(text); + } } void txt_jump_right(Text *text, const bool sel, const bool use_init_step) @@ -997,20 +1047,23 @@ void txt_jump_right(Text *text, const bool sel, const bool use_init_step) TextLine **linep; int *charp; - if (sel) + if (sel) { txt_curs_sel(text, &linep, &charp); + } else { txt_pop_last(text); txt_curs_cur(text, &linep, &charp); } - if (!*linep) + if (!*linep) { return; + } BLI_str_cursor_step_utf8( (*linep)->line, (*linep)->len, charp, STRCUR_DIR_NEXT, STRCUR_JUMP_DELIM, use_init_step); - if (!sel) + if (!sel) { txt_pop_sel(text); + } } void txt_move_bol(Text *text, const bool sel) @@ -1018,17 +1071,21 @@ void txt_move_bol(Text *text, const bool sel) TextLine **linep; int *charp; - if (sel) + if (sel) { txt_curs_sel(text, &linep, &charp); - else + } + else { txt_curs_cur(text, &linep, &charp); - if (!*linep) + } + if (!*linep) { return; + } *charp = 0; - if (!sel) + if (!sel) { txt_pop_sel(text); + } } void txt_move_eol(Text *text, const bool sel) @@ -1036,17 +1093,21 @@ void txt_move_eol(Text *text, const bool sel) TextLine **linep; int *charp; - if (sel) + if (sel) { txt_curs_sel(text, &linep, &charp); - else + } + else { txt_curs_cur(text, &linep, &charp); - if (!*linep) + } + if (!*linep) { return; + } *charp = (*linep)->len; - if (!sel) + if (!sel) { txt_pop_sel(text); + } } void txt_move_bof(Text *text, const bool sel) @@ -1054,18 +1115,22 @@ void txt_move_bof(Text *text, const bool sel) TextLine **linep; int *charp; - if (sel) + if (sel) { txt_curs_sel(text, &linep, &charp); - else + } + else { txt_curs_cur(text, &linep, &charp); - if (!*linep) + } + if (!*linep) { return; + } *linep = text->lines.first; *charp = 0; - if (!sel) + if (!sel) { txt_pop_sel(text); + } } void txt_move_eof(Text *text, const bool sel) @@ -1073,18 +1138,22 @@ void txt_move_eof(Text *text, const bool sel) TextLine **linep; int *charp; - if (sel) + if (sel) { txt_curs_sel(text, &linep, &charp); - else + } + else { txt_curs_cur(text, &linep, &charp); - if (!*linep) + } + if (!*linep) { return; + } *linep = text->lines.last; *charp = (*linep)->len; - if (!sel) + if (!sel) { txt_pop_sel(text); + } } void txt_move_toline(Text *text, unsigned int line, const bool sel) @@ -1099,26 +1168,33 @@ void txt_move_to(Text *text, unsigned int line, unsigned int ch, const bool sel) int *charp; unsigned int i; - if (sel) + if (sel) { txt_curs_sel(text, &linep, &charp); - else + } + else { txt_curs_cur(text, &linep, &charp); - if (!*linep) + } + if (!*linep) { return; + } *linep = text->lines.first; for (i = 0; i < line; i++) { - if ((*linep)->next) + if ((*linep)->next) { *linep = (*linep)->next; - else + } + else { break; + } } - if (ch > (unsigned int)((*linep)->len)) + if (ch > (unsigned int)((*linep)->len)) { ch = (unsigned int)((*linep)->len); + } *charp = ch; - if (!sel) + if (!sel) { txt_pop_sel(text); + } } /****************************/ @@ -1167,10 +1243,12 @@ void txt_pop_sel(Text *text) void txt_order_cursors(Text *text, const bool reverse) { - if (!text->curl) + if (!text->curl) { return; - if (!text->sell) + } + if (!text->sell) { return; + } /* Flip so text->curl is before/after text->sell */ if (reverse == false) { @@ -1197,13 +1275,16 @@ static void txt_delete_sel(Text *text, TextUndoBuf *utxt) TextLine *tmpl; char *buf; - if (!text->curl) + if (!text->curl) { return; - if (!text->sell) + } + if (!text->sell) { return; + } - if (!txt_has_sel(text)) + if (!txt_has_sel(text)) { return; + } txt_order_cursors(text, false); @@ -1224,8 +1305,9 @@ static void txt_delete_sel(Text *text, TextUndoBuf *utxt) tmpl = text->sell; while (tmpl != text->curl) { tmpl = tmpl->prev; - if (!tmpl) + if (!tmpl) { break; + } txt_delete_line(text, tmpl->next); } @@ -1258,8 +1340,9 @@ void txt_sel_clear(Text *text) void txt_sel_line(Text *text) { - if (!text->curl) + if (!text->curl) { return; + } text->curc = 0; text->sell = text->curl; @@ -1277,12 +1360,15 @@ char *txt_to_buf(Text *text) int charf, charl; char *buf; - if (!text->curl) + if (!text->curl) { return NULL; - if (!text->sell) + } + if (!text->sell) { return NULL; - if (!text->lines.first) + } + if (!text->lines.first) { return NULL; + } linef = text->lines.first; charf = 0; @@ -1341,32 +1427,40 @@ int txt_find_string(Text *text, const char *findstr, int wrap, int match_case) TextLine *tl, *startl; const char *s = NULL; - if (!text->curl || !text->sell) + if (!text->curl || !text->sell) { return 0; + } txt_order_cursors(text, false); tl = startl = text->sell; - if (match_case) + if (match_case) { s = strstr(&tl->line[text->selc], findstr); - else + } + else { s = BLI_strcasestr(&tl->line[text->selc], findstr); + } while (!s) { tl = tl->next; if (!tl) { - if (wrap) + if (wrap) { tl = text->lines.first; - else + } + else { break; + } } - if (match_case) + if (match_case) { s = strstr(tl->line, findstr); - else + } + else { s = BLI_strcasestr(tl->line, findstr); - if (tl == startl) + } + if (tl == startl) { break; + } } if (s) { @@ -1376,8 +1470,9 @@ int txt_find_string(Text *text, const char *findstr, int wrap, int match_case) txt_move_to(text, newl, newc + strlen(findstr), 1); return 1; } - else + else { return 0; + } } char *txt_sel_to_buf(Text *text) @@ -1387,10 +1482,12 @@ char *txt_sel_to_buf(Text *text) TextLine *tmp, *linef, *linel; int charf, charl; - if (!text->curl) + if (!text->curl) { return NULL; - if (!text->sell) + } + if (!text->sell) { return NULL; + } if (text->curl == text->sell) { linef = linel = text->curl; @@ -1470,8 +1567,9 @@ void txt_insert_buf(Text *text, TextUndoBuf *utxt, const char *in_buffer) TextLine *add; char *buffer; - if (!in_buffer) + if (!in_buffer) { return; + } txt_delete_sel(text, utxt); @@ -1563,7 +1661,8 @@ static void dump_buffer(TextUndoBuf *utxt) { int i = 0; - while (i++ < utxt->undo_pos) printf("%d: %d %c\n", i, utxt->buf[i], utxt->buf[i]); + while (i++ < utxt->undo_pos) + printf("%d: %d %c\n", i, utxt->buf[i], utxt->buf[i]); } /* Note: this function is outdated and must be updated if needed for future use */ @@ -1646,27 +1745,38 @@ void txt_print_undo(Text *text) i++; printf(" - Char is "); switch (op) { - case UNDO_INSERT_1: case UNDO_BS_1: case UNDO_DEL_1: + case UNDO_INSERT_1: + case UNDO_BS_1: + case UNDO_DEL_1: printf("%c", utxt->buf[i]); i++; break; - case UNDO_INSERT_2: case UNDO_BS_2: case UNDO_DEL_2: + case UNDO_INSERT_2: + case UNDO_BS_2: + case UNDO_DEL_2: printf("%c%c", utxt->buf[i], utxt->buf[i + 1]); i += 2; break; - case UNDO_INSERT_3: case UNDO_BS_3: case UNDO_DEL_3: + case UNDO_INSERT_3: + case UNDO_BS_3: + case UNDO_DEL_3: printf("%c%c%c", utxt->buf[i], utxt->buf[i + 1], utxt->buf[i + 2]); i += 3; break; - case UNDO_INSERT_4: case UNDO_BS_4: case UNDO_DEL_4: - { + case UNDO_INSERT_4: + case UNDO_BS_4: + case UNDO_DEL_4: { unsigned int uc; char c[BLI_UTF8_MAX + 1]; size_t c_len; - uc = utxt->buf[i]; i++; - uc = uc + (utxt->buf[i] << 8); i++; - uc = uc + (utxt->buf[i] << 16); i++; - uc = uc + (utxt->buf[i] << 24); i++; + uc = utxt->buf[i]; + i++; + uc = uc + (utxt->buf[i] << 8); + i++; + uc = uc + (utxt->buf[i] << 16); + i++; + uc = uc + (utxt->buf[i] << 24); + i++; c_len = BLI_str_utf8_from_unicode(uc, c); c[c_len] = '\0'; puts(c); @@ -1677,49 +1787,70 @@ void txt_print_undo(Text *text) else if (op == UNDO_DBLOCK || op == UNDO_IBLOCK) { i++; - linep = utxt->buf[i]; i++; - linep = linep + (utxt->buf[i] << 8); i++; - linep = linep + (utxt->buf[i] << 16); i++; - linep = linep + (utxt->buf[i] << 24); i++; + linep = utxt->buf[i]; + i++; + linep = linep + (utxt->buf[i] << 8); + i++; + linep = linep + (utxt->buf[i] << 16); + i++; + linep = linep + (utxt->buf[i] << 24); + i++; printf(" (length %d) <", linep); while (linep > 0) { putchar(utxt->buf[i]); - linep--; i++; + linep--; + i++; } - linep = utxt->buf[i]; i++; - linep = linep + (utxt->buf[i] << 8); i++; - linep = linep + (utxt->buf[i] << 16); i++; - linep = linep + (utxt->buf[i] << 24); i++; + linep = utxt->buf[i]; + i++; + linep = linep + (utxt->buf[i] << 8); + i++; + linep = linep + (utxt->buf[i] << 16); + i++; + linep = linep + (utxt->buf[i] << 24); + i++; printf("> (%d)", linep); } else if (op == UNDO_INDENT || op == UNDO_UNINDENT) { i++; - charp = utxt->buf[i]; i++; - charp = charp + (utxt->buf[i] << 8); i++; + charp = utxt->buf[i]; + i++; + charp = charp + (utxt->buf[i] << 8); + i++; - linep = utxt->buf[i]; i++; - linep = linep + (utxt->buf[i] << 8); i++; - linep = linep + (utxt->buf[i] << 16); i++; - linep = linep + (utxt->buf[i] << 24); i++; + linep = utxt->buf[i]; + i++; + linep = linep + (utxt->buf[i] << 8); + i++; + linep = linep + (utxt->buf[i] << 16); + i++; + linep = linep + (utxt->buf[i] << 24); + i++; printf("to <%d, %d> ", linep, charp); - charp = utxt->buf[i]; i++; - charp = charp + (utxt->buf[i] << 8); i++; + charp = utxt->buf[i]; + i++; + charp = charp + (utxt->buf[i] << 8); + i++; - linep = utxt->buf[i]; i++; - linep = linep + (utxt->buf[i] << 8); i++; - linep = linep + (utxt->buf[i] << 16); i++; - linep = linep + (utxt->buf[i] << 24); i++; + linep = utxt->buf[i]; + i++; + linep = linep + (utxt->buf[i] << 8); + i++; + linep = linep + (utxt->buf[i] << 16); + i++; + linep = linep + (utxt->buf[i] << 24); + i++; printf("from <%d, %d>", linep, charp); } - printf(" %d\n", i); + printf(" %d\n", i); i++; } } @@ -1875,7 +2006,7 @@ static void txt_undo_add_unprefix_op(Text *text, BLI_assert(BLI_listbase_count(line_index_mask) == line_index_mask_len); - /* OP byte + UInt32 count + counted UInt32 line numbers + UInt32 count + 12-bytes selection + OP byte */ + /* OP byte + u32 count + counted u32 line numbers + u32 count + 12-bytes selection + OP byte. */ if (!max_undo_test(utxt, 2 + 4 + (line_index_mask_len * 4) + 4 + 12 + 1)) { return; } @@ -2234,8 +2365,9 @@ void txt_do_undo(Text *text, TextUndoBuf *utxt) prev_flags = text->flags; text->flags &= ~TXT_TABSTOSPACES; - for (i = 0; i < linep; i++) + for (i = 0; i < linep; i++) { txt_move_right(text, 1); + } text->flags = prev_flags; } @@ -2316,7 +2448,7 @@ void txt_do_undo(Text *text, TextUndoBuf *utxt) break; } default: - //XXX error("Undo buffer error - resetting"); + // XXX error("Undo buffer error - resetting"); utxt->pos = -1; break; @@ -2508,7 +2640,7 @@ void txt_do_redo(Text *text, TextUndoBuf *utxt) break; } default: - //XXX error("Undo buffer error - resetting"); + // XXX error("Undo buffer error - resetting"); utxt->pos = -1; break; @@ -2526,27 +2658,31 @@ void txt_split_curline(Text *text, TextUndoBuf *utxt) TextLine *ins; char *left, *right; - if (!text->curl) + if (!text->curl) { return; + } txt_delete_sel(text, utxt); - if (!undoing) + if (!undoing) { txt_undo_add_charop(text, utxt, UNDO_INSERT_1, '\n'); + } /* Make the two half strings */ left = MEM_mallocN(text->curc + 1, "textline_string"); - if (text->curc) + if (text->curc) { memcpy(left, text->curl->line, text->curc); + } left[text->curc] = 0; right = MEM_mallocN(text->curl->len - text->curc + 1, "textline_string"); memcpy(right, text->curl->line + text->curc, text->curl->len - text->curc + 1); MEM_freeN(text->curl->line); - if (text->curl->format) + if (text->curl->format) { MEM_freeN(text->curl->format); + } /* Make the new TextLine */ @@ -2571,15 +2707,18 @@ void txt_split_curline(Text *text, TextUndoBuf *utxt) static void txt_delete_line(Text *text, TextLine *line) { - if (!text->curl) + if (!text->curl) { return; + } BLI_remlink(&text->lines, line); - if (line->line) + if (line->line) { MEM_freeN(line->line); - if (line->format) + } + if (line->format) { MEM_freeN(line->format); + } MEM_freeN(line); @@ -2591,8 +2730,9 @@ static void txt_combine_lines(Text *text, TextLine *linea, TextLine *lineb) { char *tmp, *s; - if (!linea || !lineb) + if (!linea || !lineb) { return; + } tmp = MEM_mallocN(linea->len + lineb->len + 1, "textline_string"); @@ -2613,8 +2753,9 @@ void txt_duplicate_line(Text *text, TextUndoBuf *utxt) { TextLine *textline; - if (!text->curl) + if (!text->curl) { return; + } if (text->curl == text->sell) { textline = txt_new_line(text->curl->line); @@ -2623,8 +2764,9 @@ void txt_duplicate_line(Text *text, TextUndoBuf *utxt) txt_make_dirty(text); txt_clean_text(text); - if (!undoing) + if (!undoing) { txt_undo_add_op(text, utxt, UNDO_DUPLICATE); + } } } @@ -2632,8 +2774,9 @@ void txt_delete_char(Text *text, TextUndoBuf *utxt) { unsigned int c = '\n'; - if (!text->curl) + if (!text->curl) { return; + } if (txt_has_sel(text)) { /* deleting a selection */ txt_delete_sel(text, utxt); @@ -2645,8 +2788,9 @@ void txt_delete_char(Text *text, TextUndoBuf *utxt) txt_combine_lines(text, text->curl, text->curl->next); txt_pop_sel(text); } - else + else { return; + } } else { /* Just deleting a char */ size_t c_len = 0; @@ -2664,8 +2808,9 @@ void txt_delete_char(Text *text, TextUndoBuf *utxt) txt_make_dirty(text); txt_clean_text(text); - if (!undoing) + if (!undoing) { txt_undo_add_charop(text, utxt, UNDO_DEL_1, c); + } } void txt_delete_word(Text *text, TextUndoBuf *utxt) @@ -2679,8 +2824,9 @@ void txt_backspace_char(Text *text, TextUndoBuf *utxt) { unsigned int c = '\n'; - if (!text->curl) + if (!text->curl) { return; + } if (txt_has_sel(text)) { /* deleting a selection */ txt_delete_sel(text, utxt); @@ -2688,8 +2834,9 @@ void txt_backspace_char(Text *text, TextUndoBuf *utxt) return; } else if (text->curc == 0) { /* Appending two lines */ - if (!text->curl->prev) + if (!text->curl->prev) { return; + } text->curl = text->curl->prev; text->curc = text->curl->len; @@ -2716,8 +2863,9 @@ void txt_backspace_char(Text *text, TextUndoBuf *utxt) txt_make_dirty(text); txt_clean_text(text); - if (!undoing) + if (!undoing) { txt_undo_add_charop(text, utxt, UNDO_BS_1, c); + } } void txt_backspace_word(Text *text, TextUndoBuf *utxt) @@ -2747,8 +2895,9 @@ static bool txt_add_char_intern(Text *text, TextUndoBuf *utxt, unsigned int add, char *tmp, ch[BLI_UTF8_MAX]; size_t add_len; - if (!text->curl) + if (!text->curl) { return 0; + } if (add == '\n') { txt_split_curline(text, utxt); @@ -2763,8 +2912,9 @@ static bool txt_add_char_intern(Text *text, TextUndoBuf *utxt, unsigned int add, txt_delete_sel(text, utxt); - if (!undoing) + if (!undoing) { txt_undo_add_charop(text, utxt, UNDO_INSERT_1, add); + } add_len = BLI_str_utf8_from_unicode(add, ch); @@ -2809,8 +2959,9 @@ bool txt_replace_char(Text *text, TextUndoBuf *utxt, unsigned int add) size_t del_size = 0, add_size; char ch[BLI_UTF8_MAX]; - if (!text->curl) + if (!text->curl) { return false; + } /* If text is selected or we're at the end of the line just use txt_add_char */ if (text->curc == text->curl->len || txt_has_sel(text) || add == '\n') { @@ -2880,13 +3031,15 @@ static void txt_select_prefix(Text *text, const char *add) tmp = MEM_mallocN(text->curl->len + indentlen + 1, "textline_string"); text->curc = 0; - if (text->curc) + if (text->curc) { memcpy(tmp, text->curl->line, text->curc); /* XXX never true, check prev line */ + } memcpy(tmp + text->curc, add, indentlen); len = text->curl->len - text->curc; - if (len > 0) + if (len > 0) { memcpy(tmp + text->curc + indentlen, text->curl->line + text->curc, len); + } tmp[text->curl->len + indentlen] = 0; make_new_line(text->curl, tmp); @@ -2906,10 +3059,12 @@ static void txt_select_prefix(Text *text, const char *add) num++; } } - if (!curc_old) + if (!curc_old) { text->curc = 0; - else + } + else { text->curc = curc_old + indentlen; + } while (num > 0) { text->curl = text->curl->prev; @@ -2950,8 +3105,9 @@ static void txt_select_unprefix(Text *text, while (true) { bool changed = false; if (STREQLEN(text->curl->line, remove, indentlen)) { - if (num == 0) + if (num == 0) { unindented_first = true; + } text->curl->len -= indentlen; memmove(text->curl->line, text->curl->line + indentlen, text->curl->len + 1); changed = true; @@ -2971,8 +3127,9 @@ static void txt_select_unprefix(Text *text, txt_clean_text(text); if (text->curl == text->sell) { - if (changed) + if (changed) { text->selc = MAX2(text->selc - indentlen, 0); + } break; } else { @@ -2981,8 +3138,9 @@ static void txt_select_unprefix(Text *text, } } - if (unindented_first) + if (unindented_first) { text->curc = MAX2(text->curc - indentlen, 0); + } while (num > 0) { text->curl = text->curl->prev; @@ -3066,15 +3224,17 @@ void txt_move_lines(struct Text *text, TextUndoBuf *utxt, const int direction) BLI_assert(ELEM(direction, TXT_MOVE_LINE_UP, TXT_MOVE_LINE_DOWN)); - if (!text->curl || !text->sell) + if (!text->curl || !text->sell) { return; + } txt_order_cursors(text, false); line_other = (direction == TXT_MOVE_LINE_DOWN) ? text->sell->next : text->curl->prev; - if (!line_other) + if (!line_other) { return; + } BLI_remlink(&text->lines, line_other); @@ -3103,11 +3263,12 @@ int txt_setcurr_tab_spaces(Text *text, int space) const char indent = (text->flags & TXT_TABSTOSPACES) ? ' ' : '\t'; static const char *back_words[] = {"return", "break", "continue", "pass", "yield", NULL}; - if (!text->curl) + if (!text->curl) { return 0; + } while (text->curl->line[i] == indent) { - //we only count those tabs/spaces that are before any text or before the curs; + // we only count those tabs/spaces that are before any text or before the curs; if (i == text->curc) { return i; } @@ -3162,65 +3323,82 @@ int text_check_bracket(const char ch) char close[] = ")]}"; for (a = 0; a < (sizeof(opens) - 1); a++) { - if (ch == opens[a]) + if (ch == opens[a]) { return a + 1; - else if (ch == close[a]) + } + else if (ch == close[a]) { return -(a + 1); + } } return 0; } -/* TODO, have a function for operators - http://docs.python.org/py3k/reference/lexical_analysis.html#operators */ +/* TODO, have a function for operators - + * http://docs.python.org/py3k/reference/lexical_analysis.html#operators */ bool text_check_delim(const char ch) { int a; char delims[] = "():\"\' ~!%^&*-+=[]{};/<>|.#\t,@"; for (a = 0; a < (sizeof(delims) - 1); a++) { - if (ch == delims[a]) + if (ch == delims[a]) { return true; + } } return false; } bool text_check_digit(const char ch) { - if (ch < '0') + if (ch < '0') { return false; - if (ch <= '9') + } + if (ch <= '9') { return true; + } return false; } bool text_check_identifier(const char ch) { - if (ch < '0') + if (ch < '0') { return false; - if (ch <= '9') + } + if (ch <= '9') { return true; - if (ch < 'A') + } + if (ch < 'A') { return false; - if (ch <= 'Z' || ch == '_') + } + if (ch <= 'Z' || ch == '_') { return true; - if (ch < 'a') + } + if (ch < 'a') { return false; - if (ch <= 'z') + } + if (ch <= 'z') { return true; + } return false; } bool text_check_identifier_nodigit(const char ch) { - if (ch <= '9') + if (ch <= '9') { return false; - if (ch < 'A') + } + if (ch < 'A') { return false; - if (ch <= 'Z' || ch == '_') + } + if (ch <= 'Z' || ch == '_') { return true; - if (ch < 'a') + } + if (ch < 'a') { return false; - if (ch <= 'z') + } + if (ch <= 'z') { return true; + } return false; } @@ -3238,8 +3416,9 @@ int text_check_identifier_nodigit_unicode(const unsigned int ch) bool text_check_whitespace(const char ch) { - if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n') + if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n') { return true; + } return false; } diff --git a/source/blender/blenkernel/intern/texture.c b/source/blender/blenkernel/intern/texture.c index dbbb231a18b..9baa8bd20e1 100644 --- a/source/blender/blenkernel/intern/texture.c +++ b/source/blender/blenkernel/intern/texture.c @@ -101,24 +101,30 @@ void BKE_texture_mapping_init(TexMapping *texmap) zero_m4(proj); proj[3][3] = 1.0f; - if (texmap->projx != PROJ_N) + if (texmap->projx != PROJ_N) { proj[texmap->projx - 1][0] = 1.0f; - if (texmap->projy != PROJ_N) + } + if (texmap->projy != PROJ_N) { proj[texmap->projy - 1][1] = 1.0f; - if (texmap->projz != PROJ_N) + } + if (texmap->projz != PROJ_N) { proj[texmap->projz - 1][2] = 1.0f; + } /* scale */ copy_v3_v3(size, texmap->size); if (ELEM(texmap->type, TEXMAP_TYPE_TEXTURE, TEXMAP_TYPE_NORMAL)) { /* keep matrix invertible */ - if (fabsf(size[0]) < 1e-5f) + if (fabsf(size[0]) < 1e-5f) { size[0] = signf(size[0]) * 1e-5f; - if (fabsf(size[1]) < 1e-5f) + } + if (fabsf(size[1]) < 1e-5f) { size[1] = signf(size[1]) * 1e-5f; - if (fabsf(size[2]) < 1e-5f) + } + if (fabsf(size[2]) < 1e-5f) { size[2] = signf(size[2]) * 1e-5f; + } } size_to_mat4(smat, texmap->size); @@ -208,7 +214,8 @@ void BKE_texture_free(Tex *tex) void BKE_texture_default(Tex *tex) { - /* BLI_assert(MEMCMP_STRUCT_AFTER_IS_ZERO(tex, id)); */ /* Not here, can be called with some pointers set. :/ */ + /* Not here, can be called with some pointers set. :/ */ + /* BLI_assert(MEMCMP_STRUCT_AFTER_IS_ZERO(tex, id)); */ tex->type = TEX_IMAGE; tex->ima = NULL; @@ -254,9 +261,7 @@ void BKE_texture_default(Tex *tex) tex->vn_distm = 0; tex->vn_coltype = 0; - tex->iuser.ok = 1; - tex->iuser.frames = 100; - tex->iuser.sfra = 1; + BKE_imageuser_default(&tex->iuser); tex->preview = NULL; } @@ -407,8 +412,10 @@ MTex *BKE_texture_mtex_add_id(ID *id, int slot) /* ------------------------------------------------------------------------- */ /** - * Only copy internal data of Texture ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of Texture ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * @@ -466,8 +473,9 @@ Tex *BKE_texture_localize(Tex *tex) /* image texture: BKE_texture_free also doesn't decrease */ - if (texn->coba) + if (texn->coba) { texn->coba = MEM_dupallocN(texn->coba); + } texn->preview = NULL; @@ -494,8 +502,9 @@ Tex *give_current_linestyle_texture(FreestyleLineStyle *linestyle) if (linestyle) { mtex = linestyle->mtex[(int)(linestyle->texact)]; - if (mtex) + if (mtex) { tex = mtex->tex; + } } return tex; @@ -505,8 +514,9 @@ void set_current_linestyle_texture(FreestyleLineStyle *linestyle, Tex *newtex) { int act = linestyle->texact; - if (linestyle->mtex[act] && linestyle->mtex[act]->tex) + if (linestyle->mtex[act] && linestyle->mtex[act]->tex) { id_us_min(&linestyle->mtex[act]->tex->id); + } if (newtex) { if (!linestyle->mtex[act]) { @@ -528,18 +538,21 @@ bool give_active_mtex(ID *id, MTex ***mtex_ar, short *act) switch (GS(id->name)) { case ID_LS: *mtex_ar = ((FreestyleLineStyle *)id)->mtex; - if (act) + if (act) { *act = (((FreestyleLineStyle *)id)->texact); + } break; case ID_PA: *mtex_ar = ((ParticleSettings *)id)->mtex; - if (act) + if (act) { *act = (((ParticleSettings *)id)->texact); + } break; default: *mtex_ar = NULL; - if (act) + if (act) { *act = 0; + } return false; } @@ -548,10 +561,12 @@ bool give_active_mtex(ID *id, MTex ***mtex_ar, short *act) void set_active_mtex(ID *id, short act) { - if (act < 0) + if (act < 0) { act = 0; - else if (act >= MAX_MTEX) + } + else if (act >= MAX_MTEX) { act = MAX_MTEX - 1; + } switch (GS(id->name)) { case ID_LS: @@ -572,8 +587,9 @@ Tex *give_current_brush_texture(Brush *br) void set_current_brush_texture(Brush *br, Tex *newtex) { - if (br->mtex.tex) + if (br->mtex.tex) { id_us_min(&br->mtex.tex->id); + } if (newtex) { br->mtex.tex = newtex; @@ -586,12 +602,14 @@ Tex *give_current_particle_texture(ParticleSettings *part) MTex *mtex = NULL; Tex *tex = NULL; - if (!part) + if (!part) { return NULL; + } mtex = part->mtex[(int)(part->texact)]; - if (mtex) + if (mtex) { tex = mtex->tex; + } return tex; } @@ -600,8 +618,9 @@ void set_current_particle_texture(ParticleSettings *part, Tex *newtex) { int act = part->texact; - if (part->mtex[act] && part->mtex[act]->tex) + if (part->mtex[act] && part->mtex[act]->tex) { id_us_min(&part->mtex[act]->tex->id); + } if (newtex) { if (!part->mtex[act]) { diff --git a/source/blender/blenkernel/intern/tracking.c b/source/blender/blenkernel/intern/tracking.c index c478ce274b8..a5445be7ce5 100644 --- a/source/blender/blenkernel/intern/tracking.c +++ b/source/blender/blenkernel/intern/tracking.c @@ -108,8 +108,9 @@ static void tracking_plane_tracks_free(ListBase *plane_tracks) */ static void tracking_reconstruction_free(MovieTrackingReconstruction *reconstruction) { - if (reconstruction->cameras) + if (reconstruction->cameras) { MEM_freeN(reconstruction->cameras); + } } /* Free memory used by tracking object, only frees contents of the structure, @@ -130,8 +131,9 @@ static void tracking_objects_free(ListBase *objects) MovieTrackingObject *object; /* Free objects contents. */ - for (object = objects->first; object; object = object->next) + for (object = objects->first; object; object = object->next) { tracking_object_free(object); + } /* Free objects themselves. */ BLI_freelistN(objects); @@ -176,8 +178,9 @@ void BKE_tracking_free(MovieTracking *tracking) tracking_reconstruction_free(&tracking->reconstruction); tracking_objects_free(&tracking->objects); - if (tracking->camera.intrinsics) + if (tracking->camera.intrinsics) { BKE_tracking_distortion_free(tracking->camera.intrinsics); + } tracking_dopesheet_free(&tracking->dopesheet); } @@ -206,7 +209,8 @@ static void tracking_tracks_copy(ListBase *tracks_dst, } } -/* copy the whole list of plane tracks (need whole MovieTracking structures due to embedded pointers to tracks). +/* Copy the whole list of plane tracks + * (need whole MovieTracking structures due to embedded pointers to tracks). * WARNING: implies tracking_[dst/src] and their tracks have already been copied. */ static void tracking_plane_tracks_copy(ListBase *plane_tracks_list_dst, const ListBase *plane_tracks_list_src, @@ -318,7 +322,8 @@ void BKE_tracking_copy(MovieTracking *tracking_dst, /* Warning! Will override tracks_mapping. */ tracking_objects_copy(&tracking_dst->objects, &tracking_src->objects, tracks_mapping, flag); - /* Those remaining are runtime data, they will be reconstructed as needed, do not bother copying them. */ + /* Those remaining are runtime data, they will be reconstructed as needed, + * do not bother copying them. */ tracking_dst->dopesheet.ok = false; BLI_listbase_clear(&tracking_dst->dopesheet.channels); BLI_listbase_clear(&tracking_dst->dopesheet.coverage_segments); @@ -406,16 +411,20 @@ MovieTrackingReconstruction *BKE_tracking_get_active_reconstruction(MovieTrackin void BKE_tracking_get_camera_object_matrix(Scene *scene, Object *ob, float mat[4][4]) { if (!ob) { - if (scene->camera) + if (scene->camera) { ob = scene->camera; - else + } + else { ob = BKE_view_layer_camera_find(BKE_view_layer_context_active_PLACEHOLDER(scene)); + } } - if (ob) + if (ob) { BKE_object_where_is_calc_mat4(ob, mat); - else + } + else { unit_m4(mat); + } } /* Get projection matrix for camera specified by given tracking object @@ -442,10 +451,12 @@ void BKE_tracking_get_projection_matrix(MovieTracking *tracking, clipsta = 0.1f; clipend = 1000.0f; - if (winx >= winy) + if (winx >= winy) { viewfac = (lens * winx) / tracking->camera.sensor_width; - else + } + else { viewfac = (ycor * lens * winy) / tracking->camera.sensor_width; + } pixsize = clipsta / viewfac; @@ -656,8 +667,9 @@ void BKE_tracking_track_unique_name(ListBase *tracksbase, MovieTrackingTrack *tr */ void BKE_tracking_track_free(MovieTrackingTrack *track) { - if (track->markers) + if (track->markers) { MEM_freeN(track->markers); + } } /* Set flag for all specified track's areas. @@ -667,15 +679,19 @@ void BKE_tracking_track_free(MovieTrackingTrack *track) */ void BKE_tracking_track_flag_set(MovieTrackingTrack *track, int area, int flag) { - if (area == TRACK_AREA_NONE) + if (area == TRACK_AREA_NONE) { return; + } - if (area & TRACK_AREA_POINT) + if (area & TRACK_AREA_POINT) { track->flag |= flag; - if (area & TRACK_AREA_PAT) + } + if (area & TRACK_AREA_PAT) { track->pat_flag |= flag; - if (area & TRACK_AREA_SEARCH) + } + if (area & TRACK_AREA_SEARCH) { track->search_flag |= flag; + } } /* Clear flag from all specified track's areas. @@ -685,15 +701,19 @@ void BKE_tracking_track_flag_set(MovieTrackingTrack *track, int area, int flag) */ void BKE_tracking_track_flag_clear(MovieTrackingTrack *track, int area, int flag) { - if (area == TRACK_AREA_NONE) + if (area == TRACK_AREA_NONE) { return; + } - if (area & TRACK_AREA_POINT) + if (area & TRACK_AREA_POINT) { track->flag &= ~flag; - if (area & TRACK_AREA_PAT) + } + if (area & TRACK_AREA_PAT) { track->pat_flag &= ~flag; - if (area & TRACK_AREA_SEARCH) + } + if (area & TRACK_AREA_SEARCH) { track->search_flag &= ~flag; + } } /* Check whether track has got marker at specified frame. @@ -747,8 +767,9 @@ void BKE_tracking_track_path_clear(MovieTrackingTrack *track, int ref_frame, int a++; } - if (track->markersnr) + if (track->markersnr) { tracking_marker_insert_disabled(track, &track->markers[track->markersnr - 1], false, true); + } } else if (action == TRACK_CLEAR_UPTO) { a = track->markersnr - 1; @@ -769,8 +790,9 @@ void BKE_tracking_track_path_clear(MovieTrackingTrack *track, int ref_frame, int a--; } - if (track->markersnr) + if (track->markersnr) { tracking_marker_insert_disabled(track, &track->markers[0], true, true); + } } else if (action == TRACK_CLEAR_ALL) { MovieTrackingMarker *marker, marker_new; @@ -832,11 +854,13 @@ void BKE_tracking_tracks_join(MovieTracking *tracking, marker_a = &src_track->markers[a]; marker_b = &dst_track->markers[b]; - if (marker_a->flag & MARKER_DISABLED || marker_b->flag & MARKER_DISABLED) + if (marker_a->flag & MARKER_DISABLED || marker_b->flag & MARKER_DISABLED) { break; + } - if (marker_a->framenr != frame || marker_b->framenr != frame) + if (marker_a->framenr != frame || marker_b->framenr != frame) { break; + } frame++; len++; @@ -851,11 +875,13 @@ void BKE_tracking_tracks_join(MovieTracking *tracking, for (j = 0; j < len; j++) { float fac = 0.5f; - if (len > 1) + if (len > 1) { fac = 1.0f / (len - 1) * j; + } - if (inverse) + if (inverse) { fac = 1.0f - fac; + } marker_a = &src_track->markers[a]; marker_b = &dst_track->markers[b]; @@ -907,8 +933,9 @@ MovieTrackingTrack *BKE_tracking_track_get_named(MovieTracking *tracking, MovieTrackingTrack *track = tracksbase->first; while (track) { - if (STREQ(track->name, name)) + if (STREQ(track->name, name)) { return track; + } track = track->next; } @@ -953,14 +980,16 @@ MovieTrackingTrack *BKE_tracking_track_get_active(MovieTracking *tracking) { ListBase *tracksbase; - if (!tracking->act_track) + if (!tracking->act_track) { return NULL; + } tracksbase = BKE_tracking_get_active_tracks(tracking); /* check that active track is in current tracks list */ - if (BLI_findindex(tracksbase, tracking->act_track) != -1) + if (BLI_findindex(tracksbase, tracking->act_track) != -1) { return tracking->act_track; + } return NULL; } @@ -969,8 +998,9 @@ static bGPDlayer *track_mask_gpencil_layer_get(MovieTrackingTrack *track) { bGPDlayer *layer; - if (!track->gpd) + if (!track->gpd) { return NULL; + } layer = track->gpd->layers.first; @@ -988,8 +1018,9 @@ static bGPDlayer *track_mask_gpencil_layer_get(MovieTrackingTrack *track) frame = frame->next; } - if (ok) + if (ok) { return layer; + } } layer = layer->next; @@ -1084,10 +1115,14 @@ float *BKE_tracking_track_get_mask(int frame_width, MovieTrackingMarker *marker) { /* Convert normalized space marker's search area to pixel-space region. */ - const float region_min[2] = {marker->search_min[0] * frame_width, - marker->search_min[1] * frame_height}; - const float region_max[2] = {marker->search_max[0] * frame_width, - marker->search_max[1] * frame_height}; + const float region_min[2] = { + marker->search_min[0] * frame_width, + marker->search_min[1] * frame_height, + }; + const float region_max[2] = { + marker->search_max[0] * frame_width, + marker->search_max[1] * frame_height, + }; return tracking_track_get_mask_for_region( frame_width, frame_height, region_min, region_max, track); } @@ -1161,8 +1196,9 @@ MovieTrackingMarker *BKE_tracking_marker_insert(MovieTrackingTrack *track, { MovieTrackingMarker *old_marker = NULL; - if (track->markersnr) + if (track->markersnr) { old_marker = BKE_tracking_marker_get_exact(track, marker->framenr); + } if (old_marker) { /* simply replace settings for already allocated marker */ @@ -1175,17 +1211,20 @@ MovieTrackingMarker *BKE_tracking_marker_insert(MovieTrackingTrack *track, /* find position in array where to add new marker */ while (a--) { - if (track->markers[a].framenr < marker->framenr) + if (track->markers[a].framenr < marker->framenr) { break; + } } track->markersnr++; - if (track->markers) + if (track->markers) { track->markers = MEM_reallocN(track->markers, sizeof(MovieTrackingMarker) * track->markersnr); - else + } + else { track->markers = MEM_callocN(sizeof(MovieTrackingMarker), "MovieTracking markers"); + } /* shift array to "free" space for new marker */ memmove(track->markers + a + 2, @@ -1251,12 +1290,14 @@ void BKE_tracking_marker_clamp(MovieTrackingMarker *marker, int event) int b; /* pattern shouldn't be moved outside of search */ if (pat_min[a] < marker->search_min[a]) { - for (b = 0; b < 4; b++) + for (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 (b = 0; b < 4; b++) + for (b = 0; b < 4; b++) { marker->pattern_corners[b][a] -= pat_max[a] - marker->search_max[a]; + } } } } @@ -1290,15 +1331,18 @@ MovieTrackingMarker *BKE_tracking_marker_get(MovieTrackingTrack *track, int fram { int a = track->markersnr - 1; - if (!track->markersnr) + if (!track->markersnr) { return NULL; + } /* approximate pre-first framenr marker with first marker */ - if (framenr < track->markers[0].framenr) + if (framenr < track->markers[0].framenr) { return &track->markers[0]; + } - if (track->last_marker < track->markersnr) + if (track->last_marker < track->markersnr) { a = track->last_marker; + } if (track->markers[a].framenr <= framenr) { while (a < track->markersnr && track->markers[a].framenr <= framenr) { @@ -1335,8 +1379,9 @@ MovieTrackingMarker *BKE_tracking_marker_get_exact(MovieTrackingTrack *track, in { MovieTrackingMarker *marker = BKE_tracking_marker_get(track, framenr); - if (marker->framenr != framenr) + if (marker->framenr != framenr) { return NULL; + } return marker; } @@ -1633,8 +1678,9 @@ MovieTrackingPlaneMarker *BKE_tracking_plane_marker_insert(MovieTrackingPlaneTra { MovieTrackingPlaneMarker *old_plane_marker = NULL; - if (plane_track->markersnr) + if (plane_track->markersnr) { old_plane_marker = BKE_tracking_plane_marker_get_exact(plane_track, plane_marker->framenr); + } if (old_plane_marker) { /* Simply replace settings in existing marker. */ @@ -1709,8 +1755,9 @@ MovieTrackingPlaneMarker *BKE_tracking_plane_marker_get(MovieTrackingPlaneTrack { int a = plane_track->markersnr - 1; - if (!plane_track->markersnr) + if (!plane_track->markersnr) { return NULL; + } /* Approximate pre-first framenr marker with first marker. */ if (framenr < plane_track->markers[0].framenr) { @@ -1849,8 +1896,9 @@ bool BKE_tracking_object_delete(MovieTracking *tracking, MovieTrackingObject *ob MovieTrackingTrack *track; int index = BLI_findindex(&tracking->objects, object); - if (index == -1) + if (index == -1) { return false; + } if (object->flag & TRACKING_OBJECT_CAMERA) { /* object used for camera solving can't be deleted */ @@ -1859,8 +1907,9 @@ bool BKE_tracking_object_delete(MovieTracking *tracking, MovieTrackingObject *ob track = object->tracks.first; while (track) { - if (track == tracking->act_track) + if (track == tracking->act_track) { tracking->act_track = NULL; + } track = track->next; } @@ -1870,10 +1919,12 @@ bool BKE_tracking_object_delete(MovieTracking *tracking, MovieTrackingObject *ob tracking->tot_object--; - if (index != 0) + if (index != 0) { tracking->objectnr = index - 1; - else + } + else { tracking->objectnr = 0; + } BKE_tracking_dopesheet_tag_update(tracking); @@ -1895,8 +1946,9 @@ MovieTrackingObject *BKE_tracking_object_get_named(MovieTracking *tracking, cons MovieTrackingObject *object = tracking->objects.first; while (object) { - if (STREQ(object->name, name)) + if (STREQ(object->name, name)) { return object; + } object = object->next; } @@ -1914,8 +1966,9 @@ MovieTrackingObject *BKE_tracking_object_get_camera(MovieTracking *tracking) MovieTrackingObject *object = tracking->objects.first; while (object) { - if (object->flag & TRACKING_OBJECT_CAMERA) + if (object->flag & TRACKING_OBJECT_CAMERA) { return object; + } object = object->next; } @@ -1961,28 +2014,35 @@ static int reconstructed_camera_index_get(MovieTrackingReconstruction *reconstru MovieReconstructedCamera *cameras = reconstruction->cameras; int a = 0, d = 1; - if (!reconstruction->camnr) + if (!reconstruction->camnr) { return -1; + } if (framenr < cameras[0].framenr) { - if (nearest) + if (nearest) { return 0; - else + } + else { return -1; + } } if (framenr > cameras[reconstruction->camnr - 1].framenr) { - if (nearest) + if (nearest) { return reconstruction->camnr - 1; - else + } + else { return -1; + } } - if (reconstruction->last_camera < reconstruction->camnr) + if (reconstruction->last_camera < reconstruction->camnr) { a = reconstruction->last_camera; + } - if (cameras[a].framenr >= framenr) + if (cameras[a].framenr >= framenr) { d = -1; + } while (a >= 0 && a < reconstruction->camnr) { int cfra = cameras[a].framenr; @@ -1991,18 +2051,22 @@ static int reconstructed_camera_index_get(MovieTrackingReconstruction *reconstru if (d > 0 && cfra > framenr) { /* interpolate with previous position */ - if (nearest) + if (nearest) { return a - 1; - else + } + else { break; + } } if (d < 0 && cfra < framenr) { /* interpolate with next position */ - if (nearest) + if (nearest) { return a; - else + } + else { break; + } } if (cfra == framenr) { @@ -2031,7 +2095,8 @@ static void reconstructed_camera_scale_set(MovieTrackingObject *object, float ma void BKE_tracking_camera_shift_get( MovieTracking *tracking, int winx, int winy, float *shiftx, float *shifty) { - /* indeed in both of cases it should be winx -- it's just how camera shift works for blender's camera */ + /* Indeed in both of cases it should be winx - + * it's just how camera shift works for blender's camera. */ *shiftx = (0.5f * winx - tracking->camera.principal[0]) / winx; *shifty = (0.5f * winy - tracking->camera.principal[1]) / winx; } @@ -2064,8 +2129,9 @@ MovieReconstructedCamera *BKE_tracking_camera_get_reconstructed(MovieTracking *t reconstruction = BKE_tracking_object_get_reconstruction(tracking, object); a = reconstructed_camera_index_get(reconstruction, framenr, false); - if (a == -1) + if (a == -1) { return NULL; + } return &reconstruction->cameras[a]; } @@ -2191,8 +2257,9 @@ ImBuf *BKE_tracking_distortion_exec(MovieDistortion *distortion, resibuf->rect_float); } - if (ibuf->rect) + if (ibuf->rect) { imb_freerectImBuf(ibuf); + } } else { if (undistort) { @@ -2347,8 +2414,9 @@ void BKE_tracking_max_distortion_delta_across_bound(MovieTracking *tracking, delta[0] = delta[1] = -FLT_MAX; for (a = rect->xmin; a <= rect->xmax + coord_delta; a += coord_delta) { - if (a > rect->xmax) + if (a > rect->xmax) { a = rect->xmax; + } /* bottom edge */ pos[0] = a; @@ -2368,13 +2436,15 @@ void BKE_tracking_max_distortion_delta_across_bound(MovieTracking *tracking, delta[0] = max_ff(delta[0], fabsf(pos[0] - warped_pos[0])); delta[1] = max_ff(delta[1], fabsf(pos[1] - warped_pos[1])); - if (a >= rect->xmax) + if (a >= rect->xmax) { break; + } } for (a = rect->ymin; a <= rect->ymax + coord_delta; a += coord_delta) { - if (a > rect->ymax) + if (a > rect->ymax) { a = rect->ymax; + } /* left edge */ pos[0] = rect->xmin; @@ -2394,8 +2464,9 @@ void BKE_tracking_max_distortion_delta_across_bound(MovieTracking *tracking, delta[0] = max_ff(delta[0], fabsf(pos[0] - warped_pos[0])); delta[1] = max_ff(delta[1], fabsf(pos[1] - warped_pos[1])); - if (a >= rect->ymax) + if (a >= rect->ymax) { break; + } } } @@ -2426,8 +2497,9 @@ ImBuf *BKE_tracking_sample_pattern(int frame_width, double warped_position_x, warped_position_y; float *mask = NULL; - if (num_samples_x <= 0 || num_samples_y <= 0) + if (num_samples_x <= 0 || num_samples_y <= 0) { return NULL; + } pattern_ibuf = IMB_allocImBuf( num_samples_x, num_samples_y, 32, search_ibuf->rect_float ? IB_rectfloat : IB_rect); @@ -2452,10 +2524,12 @@ ImBuf *BKE_tracking_sample_pattern(int frame_width, ((int)(track->offset[1] * frame_height))); /* when offset is negative, rounding happens in opposite direction */ - if (track->offset[0] < 0.0f) + if (track->offset[0] < 0.0f) { src_pixel_x[a] += 1.0; - if (track->offset[1] < 0.0f) + } + if (track->offset[1] < 0.0f) { src_pixel_y[a] += 1.0; + } } } @@ -2565,8 +2639,9 @@ ImBuf *BKE_tracking_get_search_imbuf(ImBuf *ibuf, w = (marker->search_max[0] - marker->search_min[0]) * ibuf->x; h = (marker->search_max[1] - marker->search_min[1]) * ibuf->y; - if (w <= 0 || h <= 0) + if (w <= 0 || h <= 0) { return NULL; + } searchibuf = IMB_allocImBuf(w, h, 32, ibuf->rect_float ? IB_rectfloat : IB_rect); @@ -2592,8 +2667,9 @@ void BKE_tracking_disable_channels( int x, y; float scale; - if (!disable_red && !disable_green && !disable_blue && !grayscale) + if (!disable_red && !disable_green && !disable_blue && !grayscale) { return; + } /* if only some components are selected, it's important to rescale the result * appropriately so that e.g. if only blue is selected, it's not zeroed out. @@ -2642,8 +2718,9 @@ void BKE_tracking_disable_channels( } } - if (ibuf->rect_float) + if (ibuf->rect_float) { ibuf->userflags |= IB_RECT_INVALID; + } } /*********************** Dopesheet functions *************************/ @@ -2655,10 +2732,12 @@ static int channels_alpha_sort(const void *a, const void *b) const MovieTrackingDopesheetChannel *channel_a = a; const MovieTrackingDopesheetChannel *channel_b = b; - if (BLI_strcasecmp(channel_a->track->name, channel_b->track->name) > 0) + if (BLI_strcasecmp(channel_a->track->name, channel_b->track->name) > 0) { return 1; - else + } + else { return 0; + } } static int channels_total_track_sort(const void *a, const void *b) @@ -2666,10 +2745,12 @@ static int channels_total_track_sort(const void *a, const void *b) const MovieTrackingDopesheetChannel *channel_a = a; const MovieTrackingDopesheetChannel *channel_b = b; - if (channel_a->total_frames > channel_b->total_frames) + if (channel_a->total_frames > channel_b->total_frames) { return 1; - else + } + else { return 0; + } } static int channels_longest_segment_sort(const void *a, const void *b) @@ -2677,10 +2758,12 @@ static int channels_longest_segment_sort(const void *a, const void *b) const MovieTrackingDopesheetChannel *channel_a = a; const MovieTrackingDopesheetChannel *channel_b = b; - if (channel_a->max_segment > channel_b->max_segment) + if (channel_a->max_segment > channel_b->max_segment) { return 1; - else + } + else { return 0; + } } static int channels_average_error_sort(const void *a, const void *b) @@ -2688,34 +2771,42 @@ static int channels_average_error_sort(const void *a, const void *b) const MovieTrackingDopesheetChannel *channel_a = a; const MovieTrackingDopesheetChannel *channel_b = b; - if (channel_a->track->error > channel_b->track->error) + if (channel_a->track->error > channel_b->track->error) { return 1; - else + } + else { return 0; + } } static int channels_alpha_inverse_sort(const void *a, const void *b) { - if (channels_alpha_sort(a, b)) + if (channels_alpha_sort(a, b)) { return 0; - else + } + else { return 1; + } } static int channels_total_track_inverse_sort(const void *a, const void *b) { - if (channels_total_track_sort(a, b)) + if (channels_total_track_sort(a, b)) { return 0; - else + } + else { return 1; + } } static int channels_longest_segment_inverse_sort(const void *a, const void *b) { - if (channels_longest_segment_sort(a, b)) + if (channels_longest_segment_sort(a, b)) { return 0; - else + } + else { return 1; + } } static int channels_average_error_inverse_sort(const void *a, const void *b) @@ -2723,10 +2814,12 @@ static int channels_average_error_inverse_sort(const void *a, const void *b) const MovieTrackingDopesheetChannel *channel_a = a; const MovieTrackingDopesheetChannel *channel_b = b; - if (channel_a->track->error < channel_b->track->error) + if (channel_a->track->error < channel_b->track->error) { return 1; - else + } + else { return 0; + } } /* Calculate frames segments at which track is tracked continuously. */ @@ -2755,10 +2848,12 @@ static void tracking_dopesheet_channels_segments_calc(MovieTrackingDopesheetChan while (i < track->markersnr) { marker = &track->markers[i]; - if (marker->framenr != prev_fra + 1) + if (marker->framenr != prev_fra + 1) { break; - if (marker->flag & MARKER_DISABLED) + } + if (marker->flag & MARKER_DISABLED) { break; + } prev_fra = marker->framenr; len++; @@ -2771,8 +2866,9 @@ static void tracking_dopesheet_channels_segments_calc(MovieTrackingDopesheetChan i++; } - if (!channel->tot_segment) + if (!channel->tot_segment) { return; + } channel->segments = MEM_callocN(2 * sizeof(int) * channel->tot_segment, "tracking channel segments"); @@ -2791,10 +2887,12 @@ static void tracking_dopesheet_channels_segments_calc(MovieTrackingDopesheetChan while (i < track->markersnr) { marker = &track->markers[i]; - if (marker->framenr != prev_fra + 1) + if (marker->framenr != prev_fra + 1) { break; - if (marker->flag & MARKER_DISABLED) + } + if (marker->flag & MARKER_DISABLED) { break; + } prev_fra = marker->framenr; channel->total_frames++; @@ -2829,11 +2927,13 @@ static void tracking_dopesheet_channels_calc(MovieTracking *tracking) for (track = tracksbase->first; track; track = track->next) { MovieTrackingDopesheetChannel *channel; - if (!show_hidden && (track->flag & TRACK_HIDDEN) != 0) + if (!show_hidden && (track->flag & TRACK_HIDDEN) != 0) { continue; + } - if (sel_only && !TRACK_SELECTED(track)) + if (sel_only && !TRACK_SELECTED(track)) { continue; + } channel = MEM_callocN(sizeof(MovieTrackingDopesheetChannel), "tracking dopesheet channel"); channel->track = track; @@ -2894,10 +2994,12 @@ static void tracking_dopesheet_channels_sort(MovieTracking *tracking, static int coverage_from_count(int count) { /* Values are actually arbitrary here, probably need to be tweaked. */ - if (count < 8) + if (count < 8) { return TRACKING_COVERAGE_BAD; - else if (count < 16) + } + else if (count < 16) { return TRACKING_COVERAGE_ACCEPTABLE; + } return TRACKING_COVERAGE_OK; } @@ -2932,8 +3034,9 @@ static void tracking_dopesheet_calc_coverage(MovieTracking *tracking) MovieTrackingMarker *marker = &track->markers[i]; /* TODO: perhaps we need to add check for non-single-frame track here */ - if ((marker->flag & MARKER_DISABLED) == 0) + if ((marker->flag & MARKER_DISABLED) == 0) { per_frame_counter[marker->framenr - start_frame]++; + } } } @@ -2942,22 +3045,25 @@ static void tracking_dopesheet_calc_coverage(MovieTracking *tracking) last_segment_frame = start_frame; /* means only disabled tracks in the beginning, could be ignored */ - if (!per_frame_counter[0]) + if (!per_frame_counter[0]) { prev_coverage = TRACKING_COVERAGE_OK; + } for (int i = 1; i < frames; i++) { int coverage = coverage_from_count(per_frame_counter[i]); /* means only disabled tracks in the end, could be ignored */ - if (i == frames - 1 && !per_frame_counter[i]) + if (i == frames - 1 && !per_frame_counter[i]) { coverage = TRACKING_COVERAGE_OK; + } if (coverage != prev_coverage || i == frames - 1) { MovieTrackingDopesheetCoverageSegment *coverage_segment; int end_segment_frame = i - 1 + start_frame; - if (end_segment_frame == last_segment_frame) + if (end_segment_frame == last_segment_frame) { end_segment_frame++; + } coverage_segment = MEM_callocN(sizeof(MovieTrackingDopesheetCoverageSegment), "tracking coverage segment"); @@ -2994,8 +3100,9 @@ void BKE_tracking_dopesheet_update(MovieTracking *tracking) short sort_method = dopesheet->sort_method; bool inverse = (dopesheet->flag & TRACKING_DOPE_SORT_INVERSE) != 0; - if (dopesheet->ok) + if (dopesheet->ok) { return; + } tracking_dopesheet_free(dopesheet); diff --git a/source/blender/blenkernel/intern/tracking_auto.c b/source/blender/blenkernel/intern/tracking_auto.c index e93a5780b81..8a474725b0c 100644 --- a/source/blender/blenkernel/intern/tracking_auto.c +++ b/source/blender/blenkernel/intern/tracking_auto.c @@ -45,8 +45,7 @@ typedef struct AutoTrackOptions { int clip_index; /** Index of the clip this track belogs to. */ int track_index; /* Index of the track in AutoTrack tracks structure. */ MovieTrackingTrack *track; /* Pointer to an original track/ */ - libmv_TrackRegionOptions track_region_options; /* Options for the region - tracker. */ + libmv_TrackRegionOptions track_region_options; /* Options for the region tracker. */ bool use_keyframe_match; /* Keyframe pattern matching. */ /* TODO(sergey): A bit awkward to keep it in here, only used to diff --git a/source/blender/blenkernel/intern/tracking_detect.c b/source/blender/blenkernel/intern/tracking_detect.c index 36d44f8fa5d..ec044f14fa8 100644 --- a/source/blender/blenkernel/intern/tracking_detect.c +++ b/source/blender/blenkernel/intern/tracking_detect.c @@ -56,8 +56,9 @@ static bool check_point_in_stroke(bGPDstroke *stroke, float x, float y) if ((points[i].y < y && points[prev].y >= y) || (points[prev].y < y && points[i].y >= y)) { float fac = (y - points[i].y) / (points[prev].y - points[i].y); - if (points[i].x + fac * (points[prev].x - points[i].x) < x) + if (points[i].x + fac * (points[prev].x - points[i].x) < x) { count++; + } } prev = i; @@ -75,8 +76,9 @@ static bool check_point_in_layer(bGPDlayer *layer, float x, float y) bGPDstroke *stroke = frame->strokes.first; while (stroke) { - if (check_point_in_stroke(stroke, x, y)) + if (check_point_in_stroke(stroke, x, y)) { return true; + } stroke = stroke->next; } @@ -113,8 +115,9 @@ static void detect_retrieve_libmv_features(MovieTracking *tracking, xu = (x + 0.5) / width; yu = (y + 0.5) / height; - if (layer) + if (layer) { ok = check_point_in_layer(layer, xu, yu) != place_outside_layer; + } if (ok) { track = BKE_tracking_track_add(tracking, tracksbase, xu, yu, framenr, width, height); diff --git a/source/blender/blenkernel/intern/tracking_region_tracker.c b/source/blender/blenkernel/intern/tracking_region_tracker.c index a66a521783b..1d6bb88c3f4 100644 --- a/source/blender/blenkernel/intern/tracking_region_tracker.c +++ b/source/blender/blenkernel/intern/tracking_region_tracker.c @@ -200,10 +200,12 @@ void tracking_configure_tracker(const MovieTrackingTrack *track, options->minimum_correlation = track->minimum_correlation; options->sigma = 0.9; - if ((track->algorithm_flag & TRACK_ALGORITHM_FLAG_USE_MASK) != 0) + if ((track->algorithm_flag & TRACK_ALGORITHM_FLAG_USE_MASK) != 0) { options->image1_mask = mask; - else + } + else { options->image1_mask = NULL; + } } /* Perform tracking from a reference_marker to destination_ibuf. @@ -250,14 +252,16 @@ static bool configure_and_run_tracker(ImBuf *destination_ibuf, /* configure the tracker */ tracking_configure_tracker(track, mask, &options); - /* convert the marker corners and center into pixel coordinates in the search/destination images. */ + /* Convert the marker corners and center into pixel coordinates in the + * search/destination images. */ tracking_get_marker_coords_for_tracking( frame_width, frame_height, reference_marker, src_pixel_x, src_pixel_y); tracking_get_marker_coords_for_tracking( frame_width, frame_height, marker, dst_pixel_x, dst_pixel_y); - if (patch_new == NULL || reference_search_area == NULL) + if (patch_new == NULL || reference_search_area == NULL) { return false; + } /* run the tracker! */ tracked = libmv_trackRegion(&options, @@ -289,10 +293,12 @@ static bool refine_marker_reference_frame_get(MovieTrackingTrack *track, while (reference >= first_marker && reference <= last_marker && (reference->flag & MARKER_DISABLED) != 0) { - if (backwards) + if (backwards) { reference++; - else + } + else { reference--; + } } if (reference < first_marker || reference > last_marker) { @@ -357,8 +363,9 @@ void BKE_tracking_refine_marker(MovieClip *clip, reference_ibuf, track, reference_marker, &search_area_width, &search_area_height); /* If needed, compute track's mask. */ - if ((track->algorithm_flag & TRACK_ALGORITHM_FLAG_USE_MASK) != 0) + if ((track->algorithm_flag & TRACK_ALGORITHM_FLAG_USE_MASK) != 0) { mask = BKE_tracking_track_get_mask(frame_width, frame_height, track, marker); + } /* Run the tracker from reference frame to current one. */ tracked = configure_and_run_tracker(destination_ibuf, @@ -381,8 +388,9 @@ void BKE_tracking_refine_marker(MovieClip *clip, /* Free memory used for refining */ MEM_freeN(search_area); - if (mask) + if (mask) { MEM_freeN(mask); + } IMB_freeImBuf(reference_ibuf); IMB_freeImBuf(destination_ibuf); } diff --git a/source/blender/blenkernel/intern/tracking_solver.c b/source/blender/blenkernel/intern/tracking_solver.c index c3759fd01bb..cfa41cb7d92 100644 --- a/source/blender/blenkernel/intern/tracking_solver.c +++ b/source/blender/blenkernel/intern/tracking_solver.c @@ -188,8 +188,9 @@ static bool reconstruct_retrieve_libmv_tracks(MovieReconstructContext *context, tracknr++; } - if (reconstruction->cameras) + if (reconstruction->cameras) { MEM_freeN(reconstruction->cameras); + } reconstruction->camnr = 0; reconstruction->cameras = NULL; @@ -205,8 +206,9 @@ static bool reconstruct_retrieve_libmv_tracks(MovieReconstructContext *context, float error = libmv_reprojectionErrorForImage(libmv_reconstruction, a); for (i = 0; i < 4; i++) { - for (j = 0; j < 4; j++) + for (j = 0; j < 4; j++) { mat[i][j] = matd[i][j]; + } } /* Ensure first camera has got zero rotation and transform. @@ -248,8 +250,9 @@ static bool reconstruct_retrieve_libmv_tracks(MovieReconstructContext *context, if (origin_set) { track = tracksbase->first; while (track) { - if (track->flag & TRACK_HAS_BUNDLE) + if (track->flag & TRACK_HAS_BUNDLE) { mul_v3_m4v3(track->bundle_pos, imat, track->bundle_pos); + } track = track->next; } @@ -276,20 +279,25 @@ static int reconstruct_refine_intrinsics_get_flags(MovieTracking *tracking, int refine = tracking->settings.refine_camera_intrinsics; int flags = 0; - if ((object->flag & TRACKING_OBJECT_CAMERA) == 0) + if ((object->flag & TRACKING_OBJECT_CAMERA) == 0) { return 0; + } - if (refine & REFINE_FOCAL_LENGTH) + if (refine & REFINE_FOCAL_LENGTH) { flags |= LIBMV_REFINE_FOCAL_LENGTH; + } - if (refine & REFINE_PRINCIPAL_POINT) + if (refine & REFINE_PRINCIPAL_POINT) { flags |= LIBMV_REFINE_PRINCIPAL_POINT; + } - if (refine & REFINE_RADIAL_DISTORTION_K1) + if (refine & REFINE_RADIAL_DISTORTION_K1) { flags |= LIBMV_REFINE_RADIAL_DISTORTION_K1; + } - if (refine & REFINE_RADIAL_DISTORTION_K2) + if (refine & REFINE_RADIAL_DISTORTION_K2) { flags |= LIBMV_REFINE_RADIAL_DISTORTION_K2; + } return flags; } @@ -397,11 +405,13 @@ MovieReconstructContext *BKE_tracking_reconstruction_context_new(MovieClip *clip last_marker--; } - if (first <= track->markersnr - 1) + if (first <= track->markersnr - 1) { sfra = min_ii(sfra, first_marker->framenr); + } - if (last >= 0) + if (last >= 0) { efra = max_ii(efra, last_marker->framenr); + } tracks_map_insert(context->tracks_map, track, NULL); @@ -422,8 +432,9 @@ MovieReconstructContext *BKE_tracking_reconstruction_context_new(MovieClip *clip /* Free memory used by a reconstruction process. */ void BKE_tracking_reconstruction_context_free(MovieReconstructContext *context) { - if (context->reconstruction) + if (context->reconstruction) { libmv_reconstructionDestroy(context->reconstruction); + } libmv_tracksDestroy(context->tracks); @@ -532,10 +543,12 @@ bool BKE_tracking_reconstruction_finish(MovieReconstructContext *context, MovieT object = BKE_tracking_object_get_named(tracking, context->object_name); - if (context->is_camera) + if (context->is_camera) { reconstruction = &tracking->reconstruction; - else + } + else { reconstruction = &object->reconstruction; + } /* update keyframe in the interface */ if (context->select_keyframes) { @@ -546,8 +559,9 @@ bool BKE_tracking_reconstruction_finish(MovieReconstructContext *context, MovieT reconstruction->error = context->reprojection_error; reconstruction->flag |= TRACKING_RECONSTRUCTED; - if (!reconstruct_retrieve_libmv(context, tracking)) + if (!reconstruct_retrieve_libmv(context, tracking)) { return false; + } return true; } diff --git a/source/blender/blenkernel/intern/tracking_stabilize.c b/source/blender/blenkernel/intern/tracking_stabilize.c index c98ee116df7..1fe63e21e78 100644 --- a/source/blender/blenkernel/intern/tracking_stabilize.c +++ b/source/blender/blenkernel/intern/tracking_stabilize.c @@ -274,10 +274,12 @@ static int search_closest_marker_index(MovieTrackingTrack *track, int ref_frame) i = MAX2(0, i); i = MIN2(i, end - 1); - for (; i < end - 1 && markers[i].framenr <= ref_frame; ++i) + for (; i < end - 1 && markers[i].framenr <= ref_frame; ++i) { ; - for (; 0 < i && markers[i].framenr > ref_frame; --i) + } + for (; 0 < i && markers[i].framenr > ref_frame; --i) { ; + } track->last_marker = i; return i; @@ -1374,32 +1376,39 @@ ImBuf *BKE_tracking_stabilize_frame( interpolation_func interpolation = NULL; int ibuf_flags; - if (translation) + if (translation) { copy_v2_v2(tloc, translation); + } - if (scale) + if (scale) { tscale = *scale; + } /* Perform early output if no stabilization is used. */ if ((stab->flag & TRACKING_2D_STABILIZATION) == 0) { - if (translation) + if (translation) { zero_v2(translation); + } - if (scale) + if (scale) { *scale = 1.0f; + } - if (angle) + if (angle) { *angle = 0.0f; + } return ibuf; } /* Allocate frame for stabilization result. */ ibuf_flags = 0; - if (ibuf->rect) + if (ibuf->rect) { ibuf_flags |= IB_rect; - if (ibuf->rect_float) + } + if (ibuf->rect_float) { ibuf_flags |= IB_rectfloat; + } tmpibuf = IMB_allocImBuf(ibuf->x, ibuf->y, ibuf->planes, ibuf_flags); @@ -1413,15 +1422,19 @@ ImBuf *BKE_tracking_stabilize_frame( * thus we need the inverse of the transformation to apply. */ invert_m4(mat); - if (filter == TRACKING_FILTER_NEAREST) + if (filter == TRACKING_FILTER_NEAREST) { interpolation = nearest_interpolation; - else if (filter == TRACKING_FILTER_BILINEAR) + } + else if (filter == TRACKING_FILTER_BILINEAR) { interpolation = bilinear_interpolation; - else if (filter == TRACKING_FILTER_BICUBIC) + } + else if (filter == TRACKING_FILTER_BICUBIC) { interpolation = bicubic_interpolation; - else + } + else { /* fallback to default interpolation method */ interpolation = nearest_interpolation; + } TrackingStabilizeFrameInterpolationData data = { .ibuf = ibuf, @@ -1436,17 +1449,21 @@ ImBuf *BKE_tracking_stabilize_frame( BLI_task_parallel_range( 0, tmpibuf->y, &data, tracking_stabilize_frame_interpolation_cb, &settings); - if (tmpibuf->rect_float) + if (tmpibuf->rect_float) { tmpibuf->userflags |= IB_RECT_INVALID; + } - if (translation) + if (translation) { copy_v2_v2(translation, tloc); + } - if (scale) + if (scale) { *scale = tscale; + } - if (angle) + if (angle) { *angle = tangle; + } return tmpibuf; } diff --git a/source/blender/blenkernel/intern/tracking_util.c b/source/blender/blenkernel/intern/tracking_util.c index 4de10aca0ec..358d8fa0a3e 100644 --- a/source/blender/blenkernel/intern/tracking_util.c +++ b/source/blender/blenkernel/intern/tracking_util.c @@ -76,8 +76,9 @@ TracksMap *tracks_map_new(const char *object_name, map->tracks = MEM_callocN(sizeof(MovieTrackingTrack) * num_tracks, "TrackingsMap tracks"); - if (customdata_size) + if (customdata_size) { map->customdata = MEM_callocN(customdata_size * num_tracks, "TracksMap customdata"); + } map->hash = BLI_ghash_ptr_new("TracksMap hash"); @@ -98,8 +99,9 @@ void tracks_map_get_indexed_element(TracksMap *map, { *track = &map->tracks[index]; - if (map->customdata) + if (map->customdata) { *customdata = &map->customdata[index * map->customdata_size]; + } } void tracks_map_insert(TracksMap *map, MovieTrackingTrack *track, void *customdata) @@ -110,8 +112,9 @@ void tracks_map_insert(TracksMap *map, MovieTrackingTrack *track, void *customda map->tracks[map->ptr] = new_track; - if (customdata) + if (customdata) { memcpy(&map->customdata[map->ptr * map->customdata_size], customdata, map->customdata_size); + } BLI_ghash_insert(map->hash, &map->tracks[map->ptr], track); @@ -223,14 +226,16 @@ void tracks_map_free(TracksMap *map, void (*customdata_free)(void *customdata)) BLI_ghash_free(map->hash, NULL, NULL); for (i = 0; i < map->num_tracks; i++) { - if (map->customdata && customdata_free) + if (map->customdata && customdata_free) { customdata_free(&map->customdata[i * map->customdata_size]); + } BKE_tracking_track_free(&map->tracks[i]); } - if (map->customdata) + if (map->customdata) { MEM_freeN(map->customdata); + } MEM_freeN(map->tracks); @@ -420,13 +425,16 @@ void tracking_marker_insert_disabled(MovieTrackingTrack *track, marker_new.flag &= ~MARKER_TRACKED; marker_new.flag |= MARKER_DISABLED; - if (before) + if (before) { marker_new.framenr--; - else + } + else { marker_new.framenr++; + } - if (overwrite || !BKE_tracking_track_has_marker_at_frame(track, marker_new.framenr)) + if (overwrite || !BKE_tracking_track_has_marker_at_frame(track, marker_new.framenr)) { BKE_tracking_marker_insert(track, &marker_new); + } } /* Fill in Libmv C-API camera intrinsics options from tracking structure. */ @@ -511,8 +519,9 @@ MovieTrackingMarker *tracking_get_keyframed_marker(MovieTrackingTrack *track, MovieTrackingMarker *cur_marker = &track->markers[a]; MovieTrackingMarker *next_marker = NULL; - if (next >= 0 && next < track->markersnr) + if (next >= 0 && next < track->markersnr) { next_marker = &track->markers[next]; + } if ((cur_marker->flag & MARKER_DISABLED) == 0) { /* If it'll happen so we didn't find a real keyframe marker, @@ -531,8 +540,9 @@ MovieTrackingMarker *tracking_get_keyframed_marker(MovieTrackingTrack *track, } } else if (next_marker->flag & MARKER_DISABLED) { - if (marker_keyed_fallback == NULL) + if (marker_keyed_fallback == NULL) { marker_keyed_fallback = cur_marker; + } } is_keyframed |= (cur_marker->flag & MARKER_TRACKED) == 0; @@ -547,8 +557,9 @@ MovieTrackingMarker *tracking_get_keyframed_marker(MovieTrackingTrack *track, a = next; } - if (marker_keyed == NULL) + if (marker_keyed == NULL) { marker_keyed = marker_keyed_fallback; + } return marker_keyed; } @@ -927,10 +938,14 @@ static libmv_CacheKey accessor_get_mask_for_track_callback(libmv_FrameAccessorUs BKE_movieclip_get_size(clip, &user, &frame_width, &frame_height); /* Actual mask sampling. */ MovieTrackingMarker *marker = BKE_tracking_marker_get_exact(track, frame); - const float region_min[2] = {region->min[0] - marker->pos[0] * frame_width, - region->min[1] - marker->pos[1] * frame_height}; - const float region_max[2] = {region->max[0] - marker->pos[0] * frame_width, - region->max[1] - marker->pos[1] * frame_height}; + const float region_min[2] = { + region->min[0] - marker->pos[0] * frame_width, + region->min[1] - marker->pos[1] * frame_height, + }; + const float region_max[2] = { + region->max[0] - marker->pos[0] * frame_width, + region->max[1] - marker->pos[1] * frame_height, + }; *r_destination = tracking_track_get_mask_for_region( frame_width, frame_height, region_min, region_max, track); *r_width = region->max[0] - region->min[0]; diff --git a/source/blender/blenkernel/intern/undo_system.c b/source/blender/blenkernel/intern/undo_system.c index d32bc7c6054..d3e0ff56977 100644 --- a/source/blender/blenkernel/intern/undo_system.c +++ b/source/blender/blenkernel/intern/undo_system.c @@ -135,7 +135,8 @@ static void undosys_id_ref_store(void *UNUSED(user_data), UndoRefID *id_ref) static void undosys_id_ref_resolve(void *user_data, UndoRefID *id_ref) { - /* Note: we could optimize this, for now it's not too bad since it only runs when we access undo! */ + /* Note: we could optimize this, + * for now it's not too bad since it only runs when we access undo! */ Main *bmain = user_data; ListBase *lb = which_libbase(bmain, GS(id_ref->name)); for (ID *id = lb->first; id; id = id->next) { @@ -154,7 +155,8 @@ static bool undosys_step_encode(bContext *C, Main *bmain, UndoStack *ustack, Und UNDO_NESTED_CHECK_END; if (ok) { if (us->type->step_foreach_ID_ref != NULL) { - /* Don't use from context yet because sometimes context is fake and not all members are filled in. */ + /* Don't use from context yet because sometimes context is fake and + * not all members are filled in. */ us->type->step_foreach_ID_ref(us, undosys_id_ref_store, bmain); } #ifdef WITH_GLOBAL_UNDO_CORRECT_ORDER @@ -193,7 +195,8 @@ static void undosys_step_decode(bContext *C, Main *bmain, UndoStack *ustack, Und } } #endif - /* Don't use from context yet because sometimes context is fake and not all members are filled in. */ + /* Don't use from context yet because sometimes context is fake and + * not all members are filled in. */ us->type->step_foreach_ID_ref(us, undosys_id_ref_resolve, bmain); } @@ -429,7 +432,8 @@ void BKE_undosys_stack_limit_steps_and_memory(UndoStack *ustack, int steps, size } } #endif - /* Free from first to last, free functions may update de-duplication info (see #MemFileUndoStep). */ + /* Free from first to last, free functions may update de-duplication info + * (see #MemFileUndoStep). */ undosys_stack_clear_all_first(ustack, us->prev); #ifdef WITH_GLOBAL_UNDO_KEEP_ONE diff --git a/source/blender/blenkernel/intern/unit.c b/source/blender/blenkernel/intern/unit.c index ac8e35cd781..293eed8cfe3 100644 --- a/source/blender/blenkernel/intern/unit.c +++ b/source/blender/blenkernel/intern/unit.c @@ -356,8 +356,9 @@ static const bUnitDef *unit_best_fit(double value, for (unit = unit_start ? unit_start : usys->units; unit->name; unit++) { - if (suppress && (unit->flag & B_UNIT_DEF_SUPPRESS)) + if (suppress && (unit->flag & B_UNIT_DEF_SUPPRESS)) { continue; + } /* scale down scalar so 1cm doesn't convert to 10mm because of float error */ if (UNLIKELY(unit->flag & B_UNIT_DEF_TENTH)) { @@ -385,10 +386,12 @@ static void unit_dual_convert(double value, const bUnitDef *main_unit) { const bUnitDef *unit; - if (main_unit) + if (main_unit) { unit = main_unit; - else + } + else { unit = unit_best_fit(value, usys, NULL, 1); + } *r_value_a = (value < 0.0 ? ceil : floor)(value / unit->scalar) * unit->scalar; *r_value_b = value - (*r_value_a); @@ -423,8 +426,8 @@ static size_t unit_as_string(char *str, value_conv = value / unit->scalar; /* Adjust precision to expected number of significant digits. - * Note that here, we shall not have to worry about very big/small numbers, units are expected to replace - * 'scientific notation' in those cases. */ + * Note that here, we shall not have to worry about very big/small numbers, units are expected to + * replace 'scientific notation' in those cases. */ prec -= integer_digits_d(value_conv); CLAMP(prec, 0, 6); @@ -458,8 +461,9 @@ static size_t unit_as_string(char *str, } /* terminate no matter what's done with padding above */ - if (i >= len_max) + if (i >= len_max) { i = len_max - 1; + } str[i] = '\0'; return i; @@ -532,8 +536,9 @@ static bool is_valid_unit_collection(const bUnitCollection *usys) static const bUnitDef *get_preferred_display_unit_if_used(int type, PreferredUnits units) { const bUnitCollection *usys = unit_get_system(units.system, type); - if (!is_valid_unit_collection(usys)) + if (!is_valid_unit_collection(usys)) { return NULL; + } int max_offset = usys->length - 1; @@ -541,22 +546,27 @@ static const bUnitDef *get_preferred_display_unit_if_used(int type, PreferredUni case B_UNIT_LENGTH: case B_UNIT_AREA: case B_UNIT_VOLUME: - if (units.length == USER_UNIT_ADAPTIVE) + if (units.length == USER_UNIT_ADAPTIVE) { return NULL; + } return usys->units + MIN2(units.length, max_offset); case B_UNIT_MASS: - if (units.mass == USER_UNIT_ADAPTIVE) + if (units.mass == USER_UNIT_ADAPTIVE) { return NULL; + } return usys->units + MIN2(units.mass, max_offset); case B_UNIT_TIME: - if (units.time == USER_UNIT_ADAPTIVE) + if (units.time == USER_UNIT_ADAPTIVE) { return NULL; + } return usys->units + MIN2(units.time, max_offset); case B_UNIT_ROTATION: - if (units.rotation == 0) + if (units.rotation == 0) { return usys->units + 0; - else if (units.rotation == USER_UNIT_ROT_RADIANS) + } + else if (units.rotation == USER_UNIT_ROT_RADIANS) { return usys->units + 3; + } break; default: break; @@ -587,8 +597,9 @@ static size_t unit_as_string_main(char *str, if (split && unit_should_be_split(type)) { int length = unit_as_string_splitted(str, len_max, value, prec, usys, main_unit); /* failed when length is negative, fallback to no split */ - if (length >= 0) + if (length >= 0) { return length; + } } return unit_as_string(str, len_max, value, prec, usys, main_unit, pad ? ' ' : '\0'); @@ -630,10 +641,12 @@ static const char *unit_find_str(const char *str, const char *substr, bool case_ while (true) { /* Unit detection is case insensitive. */ const char *str_found; - if (case_sensitive) + if (case_sensitive) { str_found = strstr(str, substr); - else + } + else { str_found = BLI_strcasestr(str, substr); + } if (str_found) { /* Previous char cannot be a letter. */ @@ -649,8 +662,9 @@ static const char *unit_find_str(const char *str, const char *substr, bool case_ } } /* If str_found is not a valid unit, we have to check further in the string... */ - for (str_found++; isalpha_or_utf8(*str_found); str_found++) + for (str_found++; isalpha_or_utf8(*str_found); str_found++) { ; + } str = str_found; } else { @@ -716,8 +730,9 @@ static int unit_scale_str(char *str, len_num = BLI_snprintf( str_tmp, TEMP_STR_SIZE, "*%.9g" SEP_STR, unit->scalar / scale_pref); /* # removed later */ - if (len_num > len_max) + if (len_num > len_max) { len_num = len_max; + } if (found_ofs + len_num + len_move > len_max) { /* can't move the whole string, move just as much as will fit */ @@ -766,14 +781,18 @@ static int unit_replace( static bool unit_find(const char *str, const bUnitDef *unit) { const bool case_sensitive = (unit->flag & B_UNIT_DEF_CASE_SENSITIVE) != 0; - if (unit_find_str(str, unit->name_short, case_sensitive)) + if (unit_find_str(str, unit->name_short, case_sensitive)) { return true; - if (unit_find_str(str, unit->name_plural, false)) + } + if (unit_find_str(str, unit->name_plural, false)) { return true; - if (unit_find_str(str, unit->name_alt, case_sensitive)) + } + if (unit_find_str(str, unit->name_alt, case_sensitive)) { return true; - if (unit_find_str(str, unit->name, false)) + } + if (unit_find_str(str, unit->name, false)) { return true; + } return false; } @@ -784,20 +803,23 @@ static const bUnitDef *unit_detect_from_str(const bUnitCollection *usys, { /* Try to find a default unit from current or previous string. * This allows us to handle cases like 2 + 2mm, people would expect to get 4mm, not 2.002m! - * Note this does not handle corner cases like 2 + 2cm + 1 + 2.5mm... We can't support everything. */ + * Note this does not handle corner cases like 2 + 2cm + 1 + 2.5mm... We can't support + * everything. */ const bUnitDef *unit = NULL; /* see which units the new value has */ for (unit = usys->units; unit->name; unit++) { - if (unit_find(str, unit)) + if (unit_find(str, unit)) { break; + } } /* Else, try to infer the default unit from the previous string. */ if (str_prev && (unit == NULL || unit->name == NULL)) { /* see which units the original value had */ for (unit = usys->units; unit->name; unit++) { - if (unit_find(str_prev, unit)) + if (unit_find(str_prev, unit)) { break; + } } } /* Else, fall back to default unit. */ @@ -812,8 +834,9 @@ bool bUnit_ContainsUnit(const char *str, int type) { for (int system = 0; system < UNIT_SYSTEM_TOT; system++) { const bUnitCollection *usys = unit_get_system(system, type); - if (!is_valid_unit_collection(usys)) + if (!is_valid_unit_collection(usys)) { continue; + } for (int i = 0; i < usys->length; i++) { if (unit_find(str, usys->units + i)) { @@ -828,10 +851,12 @@ double bUnit_PreferredInputUnitScalar(const struct UnitSettings *settings, int t { PreferredUnits units = preferred_units_from_UnitSettings(settings); const bUnitDef *unit = get_preferred_display_unit_if_used(type, units); - if (unit) + if (unit) { return unit->scalar; - else + } + else { return bUnit_BaseScalar(units.system, type); + } } /* make a copy of the string that replaces the units with numbers @@ -853,8 +878,9 @@ bool bUnit_ReplaceString( char *str, int len_max, const char *str_prev, double scale_pref, int system, int type) { const bUnitCollection *usys = unit_get_system(system, type); - if (!is_valid_unit_collection(usys)) + if (!is_valid_unit_collection(usys)) { return false; + } const bUnitDef *unit = NULL, *default_unit; double scale_pref_base = scale_pref; @@ -864,10 +890,12 @@ bool bUnit_ReplaceString( /* Try to find a default unit from current or previous string. */ default_unit = unit_detect_from_str(usys, str, str_prev); - /* We apply the default unit to the whole expression (default unit is now the reference '1.0' one). */ + /* We apply the default unit to the whole expression (default unit is now the reference '1.0' + * one). */ scale_pref_base *= default_unit->scalar; - /* Apply the default unit on the whole expression, this allows to handle nasty cases like '2+2in'. */ + /* Apply the default unit on the whole expression, this allows to handle nasty cases like + * '2+2in'. */ if (BLI_snprintf(str_tmp, sizeof(str_tmp), "(%s)*%.9g", str, default_unit->scalar) < sizeof(str_tmp)) { strncpy(str, str_tmp, len_max); @@ -880,16 +908,17 @@ bool bUnit_ReplaceString( for (unit = usys->units; unit->name; unit++) { /* in case there are multiple instances */ - while (unit_replace(str, len_max, str_tmp, scale_pref_base, unit)) + while (unit_replace(str, len_max, str_tmp, scale_pref_base, unit)) { changed = true; + } } unit = NULL; { /* try other unit systems now, so we can evaluate imperial when metric is set for eg. */ - /* Note that checking other systems at that point means we do not support their units as 'default' one. - * In other words, when in metrics, typing '2+2in' will give 2 meters 2 inches, not 4 inches. - * I do think this is the desired behavior! + /* Note that checking other systems at that point means we do not support their units as + * 'default' one. In other words, when in metrics, typing '2+2in' will give 2 meters 2 inches, + * not 4 inches. I do think this is the desired behavior! */ const bUnitCollection *usys_iter; int system_iter; @@ -901,8 +930,10 @@ bool bUnit_ReplaceString( for (unit = usys_iter->units; unit->name; unit++) { int ofs = 0; /* in case there are multiple instances */ - while ((ofs = unit_replace(str + ofs, len_max - ofs, str_tmp, scale_pref_base, unit))) + while ( + (ofs = unit_replace(str + ofs, len_max - ofs, str_tmp, scale_pref_base, unit))) { changed = true; + } } } } @@ -964,10 +995,12 @@ void bUnit_ToUnitAltName(char *str, int len_max, const char *orig_str, int syste len_max -= offset; /* print the alt_name */ - if (unit->name_alt) + if (unit->name_alt) { len_name = BLI_strncpy_rlen(str, unit->name_alt, len_max); - else + } + else { len_name = 0; + } len_name = (len_name < len_max ? len_name : len_max); str += len_name; @@ -985,12 +1018,14 @@ double bUnit_ClosestScalar(double value, int system, int type) const bUnitCollection *usys = unit_get_system(system, type); const bUnitDef *unit; - if (usys == NULL) + if (usys == NULL) { return -1; + } unit = unit_best_fit(value, usys, NULL, 1); - if (unit == NULL) + if (unit == NULL) { return -1; + } return unit->scalar; } @@ -998,10 +1033,12 @@ double bUnit_ClosestScalar(double value, int system, int type) double bUnit_BaseScalar(int system, int type) { const bUnitCollection *usys = unit_get_system(system, type); - if (usys) + if (usys) { return unit_default(usys)->scalar; - else + } + else { return 1.0; + } } /* external access */ diff --git a/source/blender/blenkernel/intern/workspace.c b/source/blender/blenkernel/intern/workspace.c index 2e9591a99c7..f9584adc6e0 100644 --- a/source/blender/blenkernel/intern/workspace.c +++ b/source/blender/blenkernel/intern/workspace.c @@ -113,8 +113,9 @@ static void *workspace_relation_get_data_matching_parent(const ListBase *relatio } /** - * Checks if \a screen is already used within any workspace. A screen should never be assigned to multiple - * WorkSpaceLayouts, but that should be ensured outside of the BKE_workspace module and without such checks. + * Checks if \a screen is already used within any workspace. A screen should never be assigned to + * multiple WorkSpaceLayouts, but that should be ensured outside of the BKE_workspace module + * and without such checks. * Hence, this should only be used as assert check before assigining a screen to a workspace. */ #ifndef NDEBUG @@ -143,8 +144,9 @@ WorkSpace *BKE_workspace_add(Main *bmain, const char *name) } /** - * The function that actually frees the workspace data (not workspace itself). It shouldn't be called - * directly, instead #BKE_workspace_remove should be, which calls this through #BKE_id_free then. + * The function that actually frees the workspace data (not workspace itself). + * It shouldn't be called directly, instead #BKE_workspace_remove should be, + * which calls this through #BKE_id_free then. * * Should something like a bke_internal.h be added, this should go there! */ @@ -275,7 +277,8 @@ WorkSpaceLayout *BKE_workspace_layout_find(const WorkSpace *workspace, const bSc * Find the layout for \a screen without knowing which workspace to look in. * Can also be used to find the workspace that contains \a screen. * - * \param r_workspace: Optionally return the workspace that contains the looked up layout (if found). + * \param r_workspace: Optionally return the workspace that contains the + * looked up layout (if found). */ WorkSpaceLayout *BKE_workspace_layout_find_global(const Main *bmain, const bScreen *screen, @@ -303,7 +306,8 @@ WorkSpaceLayout *BKE_workspace_layout_find_global(const Main *bmain, /** * Circular workspace layout iterator. * - * \param callback: Custom function which gets executed for each layout. Can return false to stop iterating. + * \param callback: Custom function which gets executed for each layout. + * Can return false to stop iterating. * \param arg: Custom data passed to each \a callback call. * * \return the layout at which \a callback returned false. diff --git a/source/blender/blenkernel/intern/world.c b/source/blender/blenkernel/intern/world.c index 8dcd31a13c9..109d615ae83 100644 --- a/source/blender/blenkernel/intern/world.c +++ b/source/blender/blenkernel/intern/world.c @@ -95,8 +95,10 @@ World *BKE_world_add(Main *bmain, const char *name) } /** - * Only copy internal data of World ID from source to already allocated/initialized destination. - * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs. + * Only copy internal data of World ID from source + * to already allocated/initialized destination. + * You probably never want to use that directly, + * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * @@ -144,8 +146,9 @@ World *BKE_world_localize(World *wrld) wrldn = BKE_libblock_copy_for_localize(&wrld->id); - if (wrld->nodetree) + if (wrld->nodetree) { wrldn->nodetree = ntreeLocalize(wrld->nodetree); + } wrldn->preview = NULL; diff --git a/source/blender/blenkernel/intern/writeavi.c b/source/blender/blenkernel/intern/writeavi.c index 9f76f1022d1..b72b99e514d 100644 --- a/source/blender/blenkernel/intern/writeavi.c +++ b/source/blender/blenkernel/intern/writeavi.c @@ -163,8 +163,9 @@ static void filepath_avi(char *string, RenderData *rd, bool preview, const char { int sfra, efra; - if (string == NULL) + if (string == NULL) { return; + } if (preview) { sfra = rd->psfra; @@ -219,10 +220,12 @@ static int start_avi(void *context_v, quality = rd->im_format.quality; framerate = (double)rd->frs_sec / (double)rd->frs_sec_base; - if (rd->im_format.imtype != R_IMF_IMTYPE_AVIJPEG) + if (rd->im_format.imtype != R_IMF_IMTYPE_AVIJPEG) { format = AVI_FORMAT_AVI_RGB; - else + } + else { format = AVI_FORMAT_MJPEG; + } if (AVI_open_compress(name, avi, 1, format) != AVI_ERROR_NONE) { BKE_report(reports, RPT_ERROR, "Cannot open or start AVI movie file"); @@ -256,8 +259,9 @@ static int append_avi(void *context_v, char *cp, rt; AviMovie *avi = context_v; - if (avi == NULL) + if (avi == NULL) { return 0; + } /* note that libavi free's the buffer... stupid interface - zr */ rectot = MEM_mallocN(rectx * recty * sizeof(int), "rectot"); @@ -289,8 +293,9 @@ static void end_avi(void *context_v) { AviMovie *avi = context_v; - if (avi == NULL) + if (avi == NULL) { return; + } AVI_close_compress(avi); } diff --git a/source/blender/blenkernel/intern/writeffmpeg.c b/source/blender/blenkernel/intern/writeffmpeg.c index 6bf8186e02f..a74d5b241ed 100644 --- a/source/blender/blenkernel/intern/writeffmpeg.c +++ b/source/blender/blenkernel/intern/writeffmpeg.c @@ -115,8 +115,9 @@ static void ffmpeg_filepath_get( static void delete_picture(AVFrame *f) { if (f) { - if (f->data[0]) + if (f->data[0]) { MEM_freeN(f->data[0]); + } av_free(f); } } @@ -207,12 +208,15 @@ static int write_audio_frame(FFMpegContext *context) # endif if (got_output) { - if (pkt.pts != AV_NOPTS_VALUE) + if (pkt.pts != AV_NOPTS_VALUE) { pkt.pts = av_rescale_q(pkt.pts, c->time_base, context->audio_stream->time_base); - if (pkt.dts != AV_NOPTS_VALUE) + } + if (pkt.dts != AV_NOPTS_VALUE) { pkt.dts = av_rescale_q(pkt.dts, c->time_base, context->audio_stream->time_base); - if (pkt.duration > 0) + } + if (pkt.duration > 0) { pkt.duration = av_rescale_q(pkt.duration, c->time_base, context->audio_stream->time_base); + } pkt.stream_index = context->audio_stream->index; @@ -220,16 +224,18 @@ static int write_audio_frame(FFMpegContext *context) if (av_interleaved_write_frame(context->outfile, &pkt) != 0) { fprintf(stderr, "Error writing audio packet!\n"); - if (frame) + if (frame) { av_frame_free(&frame); + } return -1; } av_free_packet(&pkt); } - if (frame) + if (frame) { av_frame_free(&frame); + } return 0; } @@ -244,8 +250,9 @@ static AVFrame *alloc_picture(int pix_fmt, int width, int height) /* allocate space for the struct */ f = av_frame_alloc(); - if (!f) + if (!f) { return NULL; + } size = avpicture_get_size(pix_fmt, width, height); /* allocate the actual picture buffer */ buf = MEM_mallocN(size, "AVFrame buffer"); @@ -353,8 +360,9 @@ static int write_video_frame( success = 0; } - if (!success) + if (!success) { BKE_report(reports, RPT_ERROR, "Error writing frame"); + } return success; } @@ -527,8 +535,9 @@ static void set_ffmpeg_properties(RenderData *rd, } for (curr = prop->data.group.first; curr; curr = curr->next) { - if (ffmpeg_proprty_valid(c, prop_name, curr)) + if (ffmpeg_proprty_valid(c, prop_name, curr)) { set_ffmpeg_property_option(c, curr, dictionary); + } } } @@ -551,8 +560,9 @@ static AVStream *alloc_video_stream(FFMpegContext *context, error[0] = '\0'; st = avformat_new_stream(of, NULL); - if (!st) + if (!st) { return NULL; + } st->id = 0; /* Set up the codec context */ @@ -627,11 +637,12 @@ static AVStream *alloc_video_stream(FFMpegContext *context, } /* Deprecated and not doing anything since July 2015, deleted in recent ffmpeg */ - //c->me_method = ME_EPZS; + // c->me_method = ME_EPZS; codec = avcodec_find_encoder(c->codec_id); - if (!codec) + if (!codec) { return NULL; + } /* Be sure to use the correct pixel format(e.g. RGB, YUV) */ @@ -731,8 +742,9 @@ static AVStream *alloc_audio_stream(FFMpegContext *context, error[0] = '\0'; st = avformat_new_stream(of, NULL); - if (!st) + if (!st) { return NULL; + } st->id = 1; c = st->codec; @@ -775,19 +787,21 @@ static AVStream *alloc_audio_stream(FFMpegContext *context, codec = avcodec_find_encoder(c->codec_id); if (!codec) { - //XXX error("Couldn't find a valid audio codec"); + // XXX error("Couldn't find a valid audio codec"); return NULL; } if (codec->sample_fmts) { - /* check if the preferred sample format for this codec is supported. - * this is because, depending on the version of libav, and with the whole ffmpeg/libav fork situation, - * you have various implementations around. float samples in particular are not always supported. - */ + /* Check if the preferred sample format for this codec is supported. + * this is because, depending on the version of libav, + * and with the whole ffmpeg/libav fork situation, + * you have various implementations around. + * Float samples in particular are not always supported. */ const enum AVSampleFormat *p = codec->sample_fmts; for (; *p != -1; p++) { - if (*p == st->codec->sample_fmt) + if (*p == st->codec->sample_fmt) { break; + } } if (*p == -1) { /* sample format incompatible with codec. Defaulting to a format known to work */ @@ -817,7 +831,7 @@ static AVStream *alloc_audio_stream(FFMpegContext *context, set_ffmpeg_properties(rd, c, "audio", &opts); if (avcodec_open2(c, codec, &opts) < 0) { - //XXX error("Couldn't initialize audio codec"); + // XXX error("Couldn't initialize audio codec"); BLI_strncpy(error, IMB_ffmpeg_last_error(), error_size); av_dict_free(&opts); return NULL; @@ -833,16 +847,18 @@ static AVStream *alloc_audio_stream(FFMpegContext *context, context->audio_outbuf_size = FF_MIN_BUFFER_SIZE; # endif - if (c->frame_size == 0) + if (c->frame_size == 0) { // used to be if ((c->codec_id >= CODEC_ID_PCM_S16LE) && (c->codec_id <= CODEC_ID_PCM_DVD)) // not sure if that is needed anymore, so let's try out if there are any // complaints regarding some ffmpeg versions users might have context->audio_input_samples = FF_MIN_BUFFER_SIZE * 8 / c->bits_per_coded_sample / c->channels; + } else { context->audio_input_samples = c->frame_size; # ifndef FFMPEG_HAVE_ENCODE_AUDIO2 - if (c->frame_size * c->channels * sizeof(int16_t) * 4 > context->audio_outbuf_size) + if (c->frame_size * c->channels * sizeof(int16_t) * 4 > context->audio_outbuf_size) { context->audio_outbuf_size = c->frame_size * c->channels * sizeof(int16_t) * 4; + } # endif } @@ -856,9 +872,10 @@ static AVStream *alloc_audio_stream(FFMpegContext *context, context->audio_output_buffer = (uint8_t *)av_malloc(context->audio_outbuf_size); # endif - if (context->audio_deinterleave) + if (context->audio_deinterleave) { context->audio_deinterleave_buffer = (uint8_t *)av_malloc( context->audio_input_samples * c->channels * context->audio_sample_size); + } context->audio_time = 0.0f; @@ -1041,10 +1058,12 @@ static int start_ffmpeg_impl(FFMpegContext *context, context, rd, fmt->video_codec, of, rectx, recty, error, sizeof(error)); PRINT("alloc video stream %p\n", context->video_stream); if (!context->video_stream) { - if (error[0]) + if (error[0]) { BKE_report(reports, RPT_ERROR, error); - else + } + else { BKE_report(reports, RPT_ERROR, "Error initializing video stream"); + } goto fail; } } @@ -1053,10 +1072,12 @@ static int start_ffmpeg_impl(FFMpegContext *context, context->audio_stream = alloc_audio_stream( context, rd, fmt->audio_codec, of, error, sizeof(error)); if (!context->audio_stream) { - if (error[0]) + if (error[0]) { BKE_report(reports, RPT_ERROR, error); - else + } + else { BKE_report(reports, RPT_ERROR, "Error initializing audio stream"); + } goto fail; } } @@ -1180,8 +1201,9 @@ static void ffmpeg_filepath_get( const char **fe = exts; int sfra, efra; - if (!string || !exts) + if (!string || !exts) { return; + } if (preview) { sfra = rd->psfra; @@ -1501,7 +1523,6 @@ static IDProperty *BKE_ffmpeg_property_add(RenderData *rd, (char *)" "; val.string.len = 80; - /* val.str = (char *)" ";*/ idp_type = IDP_STRING; break; case AV_OPT_TYPE_CONST: @@ -1533,8 +1554,9 @@ int BKE_ffmpeg_property_add_string(RenderData *rd, const char *type, const char BLI_strncpy(name_, str, sizeof(name_)); name = name_; - while (*name == ' ') + while (*name == ' ') { name++; + } param = strchr(name, ':'); @@ -1543,8 +1565,9 @@ int BKE_ffmpeg_property_add_string(RenderData *rd, const char *type, const char } if (param) { *param++ = '\0'; - while (*param == ' ') + while (*param == ' ') { param++; + } } o = av_opt_find(&c, name, NULL, 0, AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ); @@ -1592,8 +1615,9 @@ static void ffmpeg_set_expert_options(RenderData *rd) { int codec_id = rd->ffcodecdata.codec; - if (rd->ffcodecdata.properties) + if (rd->ffcodecdata.properties) { IDP_FreeProperty(rd->ffcodecdata.properties); + } if (codec_id == AV_CODEC_ID_H264) { /* @@ -1612,7 +1636,9 @@ static void ffmpeg_set_expert_options(RenderData *rd) * The other options were taken from the libx264-default.preset * included in the ffmpeg distribution. */ - // ffmpeg_property_add_string(rd, "video", "flags:loop"); // this breaks compatibility for QT + + /* This breaks compatibility for QT. */ + // BKE_ffmpeg_property_add_string(rd, "video", "flags:loop"); BKE_ffmpeg_property_add_string(rd, "video", "cmp:chroma"); BKE_ffmpeg_property_add_string(rd, "video", "partitions:parti4x4"); // Deprecated. BKE_ffmpeg_property_add_string(rd, "video", "partitions:partp8x8"); // Deprecated. @@ -1643,8 +1669,9 @@ static void ffmpeg_set_expert_options(RenderData *rd) # endif } else if (codec_id == AV_CODEC_ID_DNXHD) { - if (rd->ffcodecdata.flags & FFMPEG_LOSSLESS_OUTPUT) + if (rd->ffcodecdata.flags & FFMPEG_LOSSLESS_OUTPUT) { BKE_ffmpeg_property_add_string(rd, "video", "mbd:rd"); + } } } @@ -1652,8 +1679,9 @@ void BKE_ffmpeg_preset_set(RenderData *rd, int preset) { int isntsc = (rd->frs_sec != 25); - if (rd->ffcodecdata.properties) + if (rd->ffcodecdata.properties) { IDP_FreeProperty(rd->ffcodecdata.properties); + } switch (preset) { case FFMPEG_PRESET_VCD: @@ -1793,18 +1821,22 @@ bool BKE_ffmpeg_alpha_channel_is_supported(RenderData *rd) { int codec = rd->ffcodecdata.codec; - if (codec == AV_CODEC_ID_QTRLE) + if (codec == AV_CODEC_ID_QTRLE) { return true; + } - if (codec == AV_CODEC_ID_PNG) + if (codec == AV_CODEC_ID_PNG) { return true; + } - if (codec == AV_CODEC_ID_HUFFYUV) + if (codec == AV_CODEC_ID_HUFFYUV) { return true; + } # ifdef FFMPEG_FFV1_ALPHA_SUPPORTED - if (codec == AV_CODEC_ID_FFV1) + if (codec == AV_CODEC_ID_FFV1) { return true; + } # endif return false; diff --git a/source/blender/blenkernel/nla_private.h b/source/blender/blenkernel/nla_private.h index 59c9b4e7d33..dc086987e21 100644 --- a/source/blender/blenkernel/nla_private.h +++ b/source/blender/blenkernel/nla_private.h @@ -163,7 +163,8 @@ typedef struct NlaKeyframingContext { float nlastrip_get_frame(NlaStrip *strip, float cframe, short mode); /* --------------- NLA Evaluation (very-private stuff) ----------------------- */ -/* these functions are only defined here to avoid problems with the order in which they get defined... */ +/* these functions are only defined here to avoid problems with the order + * in which they get defined. */ NlaEvalStrip *nlastrips_ctime_get_strip( struct Depsgraph *depsgraph, ListBase *list, ListBase *strips, short index, float ctime); |