diff options
author | Jason Wilkins <Jason.A.Wilkins@gmail.com> | 2012-11-12 16:30:02 +0400 |
---|---|---|
committer | Jason Wilkins <Jason.A.Wilkins@gmail.com> | 2012-11-12 16:30:02 +0400 |
commit | 6b65102c20e9bdafd90f55f60c2a2084d873e809 (patch) | |
tree | a0f5554702501d2da1073b22ff55f740aff135f9 /source/blender/blenkernel | |
parent | 053710fcbc78ff83b9617be87558876e381f85a6 (diff) | |
parent | 83de5cb30831328548502126dff84ffdb72544f2 (diff) |
Merge w/ trunk: r51141-52085 (Important Note: gameengine and blenderplayer were not merged due to complex differences)
Diffstat (limited to 'source/blender/blenkernel')
115 files changed, 4690 insertions, 3417 deletions
diff --git a/source/blender/blenkernel/BKE_DerivedMesh.h b/source/blender/blenkernel/BKE_DerivedMesh.h index 273da05a017..7733a59b810 100644 --- a/source/blender/blenkernel/BKE_DerivedMesh.h +++ b/source/blender/blenkernel/BKE_DerivedMesh.h @@ -149,6 +149,11 @@ typedef enum DMDrawFlag { typedef enum DMDirtyFlag { /* dm has valid tessellated faces, but tessellated CDDATA need to be updated. */ DM_DIRTY_TESS_CDLAYERS = 1 << 0, + /* One of the MCOL layers have been updated, force updating of GPUDrawObject's colors buffer. + * This is necessary with modern, VBO draw code, as e.g. in vpaint mode me->mcol may be updated + * without actually rebuilding dm (hence by defautl keeping same GPUDrawObject, and same colors + * buffer, which prevents update during a stroke!). */ + DM_DIRTY_MCOL_UPDATE_DRAW = 1 << 1, } DMDirtyFlag; typedef struct DerivedMesh DerivedMesh; @@ -224,6 +229,7 @@ struct DerivedMesh { void *(*getVertData)(DerivedMesh * dm, int index, int type); void *(*getEdgeData)(DerivedMesh * dm, int index, int type); void *(*getTessFaceData)(DerivedMesh * dm, int index, int type); + void *(*getPolyData)(DerivedMesh * dm, int index, int type); /** Return a pointer to the entire array of vert/edge/face custom data * from the derived mesh (this gives a pointer to the actual data, not @@ -232,7 +238,8 @@ struct DerivedMesh { void *(*getVertDataArray)(DerivedMesh * dm, int type); void *(*getEdgeDataArray)(DerivedMesh * dm, int type); void *(*getTessFaceDataArray)(DerivedMesh * dm, int type); - + void *(*getPolyDataArray)(DerivedMesh * dm, int type); + /** Retrieves the base CustomData structures for * verts/edges/tessfaces/loops/facdes*/ CustomData *(*getVertDataLayout)(DerivedMesh * dm); @@ -494,6 +501,7 @@ void DM_add_poly_layer(struct DerivedMesh *dm, int type, int alloctype, void *DM_get_vert_data(struct DerivedMesh *dm, int index, int type); void *DM_get_edge_data(struct DerivedMesh *dm, int index, int type); void *DM_get_tessface_data(struct DerivedMesh *dm, int index, int type); +void *DM_get_poly_data(struct DerivedMesh *dm, int index, int type); /* custom data layer access functions * return pointer to first data layer which matches type (a flat array) @@ -702,4 +710,10 @@ void DM_debug_print(DerivedMesh *dm); void DM_debug_print_cdlayers(CustomData *cdata); #endif +BLI_INLINE int DM_origindex_mface_mpoly(const int *index_mf_to_mpoly, const int *index_mp_to_orig, const int i) +{ + const int j = index_mf_to_mpoly[i]; + return (j != ORIGINDEX_NONE) ? index_mp_to_orig[j] : ORIGINDEX_NONE; +} + #endif diff --git a/source/blender/blenkernel/BKE_armature.h b/source/blender/blenkernel/BKE_armature.h index 6b9de47836e..b0f372e0bac 100644 --- a/source/blender/blenkernel/BKE_armature.h +++ b/source/blender/blenkernel/BKE_armature.h @@ -99,7 +99,7 @@ void BKE_pose_where_is_bone_tail(struct bPoseChannel *pchan); /* get_objectspace_bone_matrix has to be removed still */ void get_objectspace_bone_matrix(struct Bone *bone, float M_accumulatedMatrix[][4], int root, int posed); void vec_roll_to_mat3(const float vec[3], const float roll, float mat[][3]); -void mat3_to_vec_roll(float mat[][3], float *vec, float *roll); +void mat3_to_vec_roll(float mat[][3], float r_vec[3], float *r_roll); /* Common Conversions Between Co-ordinate Spaces */ void BKE_armature_mat_world_to_pose(struct Object *ob, float inmat[][4], float outmat[][4]); diff --git a/source/blender/blenkernel/BKE_blender.h b/source/blender/blenkernel/BKE_blender.h index 56dfdf404f8..3c210877de7 100644 --- a/source/blender/blenkernel/BKE_blender.h +++ b/source/blender/blenkernel/BKE_blender.h @@ -42,16 +42,15 @@ extern "C" { * and keep comment above the defines. * Use STRINGIFY() rather than defining with quotes */ #define BLENDER_VERSION 264 -#define BLENDER_SUBVERSION 1 +#define BLENDER_SUBVERSION 9 -/* 262 was the last editmesh release but its has compatibility code for bmesh data, - * so set the minversion to 2.61 */ -#define BLENDER_MINVERSION 261 +/* 262 was the last editmesh release but it has compatibility code for bmesh data */ +#define BLENDER_MINVERSION 262 #define BLENDER_MINSUBVERSION 0 /* used by packaging tools */ /* can be left blank, otherwise a,b,c... etc with no quotes */ -#define BLENDER_VERSION_CHAR +#define BLENDER_VERSION_CHAR a /* alpha/beta/rc/release, docs use this */ #define BLENDER_VERSION_CYCLE alpha diff --git a/source/blender/blenkernel/BKE_bmesh.h b/source/blender/blenkernel/BKE_bmesh.h index 67b21eb764c..8bfee836c0d 100644 --- a/source/blender/blenkernel/BKE_bmesh.h +++ b/source/blender/blenkernel/BKE_bmesh.h @@ -99,7 +99,7 @@ typedef struct BME_Glob { /* stored in Global G for Transform() purposes */ struct BME_TransData *BME_get_transdata(struct BME_TransData_Head *td, struct BMVert *v); void BME_free_transdata(struct BME_TransData_Head *td); -struct BMesh *BME_bevel(struct BMEditMesh *em, float value, int res, int options, int defgrp_index, float angle, - BME_TransData_Head **rtd, int do_tessface); +struct BMesh *BME_bevel(struct BMesh *bm, float value, int res, int options, int defgrp_index, float angle, + BME_TransData_Head **rtd); #endif diff --git a/source/blender/blenkernel/BKE_cdderivedmesh.h b/source/blender/blenkernel/BKE_cdderivedmesh.h index d7882d8e7ec..2b2497f3f50 100644 --- a/source/blender/blenkernel/BKE_cdderivedmesh.h +++ b/source/blender/blenkernel/BKE_cdderivedmesh.h @@ -55,8 +55,10 @@ int CDDM_Check(struct DerivedMesh *dm); * data to not overwrite the original */ struct DerivedMesh *CDDM_from_mesh(struct Mesh *mesh, struct Object *ob); +struct DerivedMesh *CDDM_from_bmesh(struct BMesh *bm, int use_mdisps); + /* creates a CDDerivedMesh from the given BMEditMesh */ -DerivedMesh *CDDM_from_BMEditMesh(struct BMEditMesh *em, struct Mesh *me, int use_mdisps, int use_tessface); +DerivedMesh *CDDM_from_editbmesh(struct BMEditMesh *em, int use_mdisps, int use_tessface); /* merge verts */ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap); diff --git a/source/blender/blenkernel/BKE_colortools.h b/source/blender/blenkernel/BKE_colortools.h index 728f88b3c16..96e05aa87b9 100644 --- a/source/blender/blenkernel/BKE_colortools.h +++ b/source/blender/blenkernel/BKE_colortools.h @@ -63,8 +63,8 @@ void curvemapping_set_black_white(struct CurveMapping *cumap, con #define CURVEMAP_SLOPE_POSITIVE 1 void curvemap_reset(struct CurveMap *cuma, const struct rctf *clipr, int preset, int slope); void curvemap_remove(struct CurveMap *cuma, const short flag); -void curvemap_remove_point(struct CurveMap *cuma, struct CurveMapPoint *cmp); -struct CurveMapPoint *curvemap_insert(struct CurveMap *cuma, float x, float y); +int curvemap_remove_point(struct CurveMap *cuma, struct CurveMapPoint *cmp); +struct CurveMapPoint *curvemap_insert(struct CurveMap *cuma, float x, float y); void curvemap_sethandle(struct CurveMap *cuma, int type); void curvemapping_changed(struct CurveMapping *cumap, int rem_doubles); @@ -88,7 +88,6 @@ int curvemapping_RGBA_does_something(const struct CurveMapping * void curvemapping_table_RGBA(const struct CurveMapping *cumap, float **array, int *size); /* non-const, these modify the curve */ -void curvemapping_do_ibuf(struct CurveMapping *cumap, struct ImBuf *ibuf); void curvemapping_premultiply(struct CurveMapping *cumap, int restore); diff --git a/source/blender/blenkernel/BKE_curve.h b/source/blender/blenkernel/BKE_curve.h index e6161cebf54..536bbecb79b 100644 --- a/source/blender/blenkernel/BKE_curve.h +++ b/source/blender/blenkernel/BKE_curve.h @@ -108,7 +108,7 @@ void BKE_nurb_free(struct Nurb *nu); struct Nurb *BKE_nurb_duplicate(struct Nurb *nu); void BKE_nurb_test2D(struct Nurb *nu); -void BKE_nurb_minmax(struct Nurb *nu, float *min, float *max); +void BKE_nurb_minmax(struct Nurb *nu, float min[3], float max[3]); void BKE_nurb_makeFaces(struct Nurb *nu, float *coord_array, int rowstride, int resolu, int resolv); void BKE_nurb_makeCurve(struct Nurb *nu, float *coord_array, float *tilt_array, float *radius_array, float *weight_array, int resolu, int stride); diff --git a/source/blender/blenkernel/BKE_customdata.h b/source/blender/blenkernel/BKE_customdata.h index 33361b9921c..4736e7b7312 100644 --- a/source/blender/blenkernel/BKE_customdata.h +++ b/source/blender/blenkernel/BKE_customdata.h @@ -80,6 +80,13 @@ void customData_mask_layers__print(CustomDataMask mask); * the below operations. */ int CustomData_layer_has_math(struct CustomData *data, int layer_n); +int CustomData_layer_has_interp(struct CustomData *data, int layer_n); + +/** + * Checks if any of the customdata layers has math. + */ +int CustomData_has_math(struct CustomData *data); +int CustomData_has_interp(struct CustomData *data); /* copies the "value" (e.g. mloopuv uv or mloopcol colors) from one block to * another, while not overwriting anything else (e.g. flags). probably only @@ -115,7 +122,10 @@ void CustomData_merge(const struct CustomData *source, struct CustomData *dest, void CustomData_bmesh_merge(struct CustomData *source, struct CustomData *dest, CustomDataMask mask, int alloctype, struct BMesh *bm, const char htype); -/* frees data associated with a CustomData object (doesn't free the object +/** NULL's all members and resets the typemap. */ +void CustomData_reset(struct CustomData *data); + +/** frees data associated with a CustomData object (doesn't free the object * itself, though) */ void CustomData_free(struct CustomData *data, int totelem); @@ -205,8 +215,8 @@ void CustomData_free_elem(struct CustomData *data, int index, int count); void CustomData_interp(const struct CustomData *source, struct CustomData *dest, int *src_indices, float *weights, float *sub_weights, int count, int dest_index); -void CustomData_bmesh_interp(struct CustomData *data, void **src_blocks, - float *weights, float *sub_weights, int count, +void CustomData_bmesh_interp(struct CustomData *data, void **src_blocks, + const float *weights, const float *sub_weights, int count, void *dest_block); diff --git a/source/blender/blenkernel/BKE_deform.h b/source/blender/blenkernel/BKE_deform.h index 52a143ddf55..8306da71432 100644 --- a/source/blender/blenkernel/BKE_deform.h +++ b/source/blender/blenkernel/BKE_deform.h @@ -54,6 +54,7 @@ struct MDeformWeight *defvert_verify_index(struct MDeformVert *dv, const int void defvert_add_index_notest(struct MDeformVert *dv, int defgroup, const float weight); void defvert_remove_group(struct MDeformVert *dvert, struct MDeformWeight *dw); void defvert_clear(struct MDeformVert *dvert); +int defvert_find_shared(const struct MDeformVert *dvert_a, const struct MDeformVert *dvert_b); float defvert_find_weight(const struct MDeformVert *dvert, const int defgroup); float defvert_array_find_weight_safe(const struct MDeformVert *dvert, const int index, const int defgroup); diff --git a/source/blender/blenkernel/BKE_global.h b/source/blender/blenkernel/BKE_global.h index 2656495a918..f6276a69d57 100644 --- a/source/blender/blenkernel/BKE_global.h +++ b/source/blender/blenkernel/BKE_global.h @@ -130,8 +130,9 @@ enum { G_DEBUG_FFMPEG = (1 << 1), G_DEBUG_PYTHON = (1 << 2), /* extra python info */ G_DEBUG_EVENTS = (1 << 3), /* input/window/screen events */ - G_DEBUG_WM = (1 << 4), /* operator, undo */ - G_DEBUG_JOBS = (1 << 5) /* jobs time profiling */ + G_DEBUG_HANDLERS = (1 << 4), /* events handling */ + G_DEBUG_WM = (1 << 5), /* operator, undo */ + G_DEBUG_JOBS = (1 << 6) /* jobs time profiling */ }; #define G_DEBUG_ALL (G_DEBUG | G_DEBUG_FFMPEG | G_DEBUG_PYTHON | G_DEBUG_EVENTS | G_DEBUG_WM | G_DEBUG_JOBS) @@ -145,17 +146,17 @@ enum { #define G_FILE_ENABLE_ALL_FRAMES (1 << 3) /* deprecated */ #define G_FILE_SHOW_DEBUG_PROPS (1 << 4) /* deprecated */ #define G_FILE_SHOW_FRAMERATE (1 << 5) /* deprecated */ -/* #define G_FILE_SHOW_PROFILE (1 << 6) */ /* deprecated */ +/* #define G_FILE_SHOW_PROFILE (1 << 6) */ /* deprecated */ #define G_FILE_LOCK (1 << 7) #define G_FILE_SIGN (1 << 8) -/* #define G_FILE_PUBLISH (1 << 9) */ /* deprecated */ +/* #define G_FILE_PUBLISH (1 << 9) */ /* deprecated */ #define G_FILE_NO_UI (1 << 10) -/* #define G_FILE_GAME_TO_IPO (1 << 11) */ /* deprecated */ +/* #define G_FILE_GAME_TO_IPO (1 << 11) */ /* deprecated */ #define G_FILE_GAME_MAT (1 << 12) /* deprecated */ -/* #define G_FILE_DISPLAY_LISTS (1 << 13) */ /* deprecated */ +/* #define G_FILE_DISPLAY_LISTS (1 << 13) */ /* deprecated */ #define G_FILE_SHOW_PHYSICS (1 << 14) /* deprecated */ #define G_FILE_GAME_MAT_GLSL (1 << 15) /* deprecated */ -/* #define G_FILE_GLSL_NO_LIGHTS (1 << 16) */ /* deprecated */ +/* #define G_FILE_GLSL_NO_LIGHTS (1 << 16) */ /* deprecated */ #define G_FILE_GLSL_NO_SHADERS (1 << 17) /* deprecated */ #define G_FILE_GLSL_NO_SHADOWS (1 << 18) /* deprecated */ #define G_FILE_GLSL_NO_RAMPS (1 << 19) /* deprecated */ @@ -166,6 +167,9 @@ enum { #define G_FILE_RELATIVE_REMAP (1 << 24) #define G_FILE_HISTORY (1 << 25) #define G_FILE_MESH_COMPAT (1 << 26) /* BMesh option to save as older mesh format */ +#define G_FILE_SAVE_COPY (1 << 27) /* restore paths after editing them */ + +#define G_FILE_FLAGS_RUNTIME (G_FILE_NO_UI | G_FILE_RELATIVE_REMAP | G_FILE_MESH_COMPAT | G_FILE_SAVE_COPY) /* G.windowstate */ #define G_WINDOWSTATE_USERDEF 0 diff --git a/source/blender/blenkernel/BKE_idprop.h b/source/blender/blenkernel/BKE_idprop.h index 3cf4a2c5cdc..a9f6a61a655 100644 --- a/source/blender/blenkernel/BKE_idprop.h +++ b/source/blender/blenkernel/BKE_idprop.h @@ -154,6 +154,12 @@ __attribute__((nonnull)) #endif ; +void IDP_MergeGroup(IDProperty *dest, IDProperty *src, const int do_overwrite) +#ifdef __GNUC__ +__attribute__((nonnull)) +#endif +; + /** * This function has a sanity check to make sure ID properties with the same name don't * get added to the group. @@ -260,6 +266,12 @@ __attribute__((nonnull)) #endif ; +int IDP_EqualsProperties_ex(IDProperty *prop1, IDProperty *prop2, const int is_strict) +#ifdef __GNUC__ +__attribute__((warn_unused_result)) +#endif +; + int IDP_EqualsProperties(struct IDProperty *prop1, struct IDProperty *prop2) #ifdef __GNUC__ __attribute__((warn_unused_result)) @@ -306,11 +318,16 @@ void IDP_FreeProperty(struct IDProperty *prop); /** Unlinks any struct IDProperty<->ID linkage that might be going on.*/ void IDP_UnlinkProperty(struct IDProperty *prop); -#define IDP_Int(prop) ((prop)->data.val) -#define IDP_Float(prop) (*(float *)&(prop)->data.val) -#define IDP_String(prop) ((char *)(prop)->data.pointer) -#define IDP_Array(prop) ((prop)->data.pointer) -#define IDP_IDPArray(prop) ((IDProperty *)(prop)->data.pointer) -#define IDP_Double(prop) (*(double *)&(prop)->data.val) +#define IDP_Int(prop) ((prop)->data.val) +#define IDP_Float(prop) (*(float *)&(prop)->data.val) +#define IDP_Double(prop) (*(double *)&(prop)->data.val) +#define IDP_String(prop) ((char *) (prop)->data.pointer) +#define IDP_Array(prop) ((prop)->data.pointer) +#define IDP_IDPArray(prop) ((IDProperty *) (prop)->data.pointer) + +#ifdef DEBUG +/* for printout only */ +void IDP_spit(IDProperty *prop); +#endif #endif /* __BKE_IDPROP_H__ */ diff --git a/source/blender/blenkernel/BKE_image.h b/source/blender/blenkernel/BKE_image.h index 5e5f58f73fe..1875fd66628 100644 --- a/source/blender/blenkernel/BKE_image.h +++ b/source/blender/blenkernel/BKE_image.h @@ -127,6 +127,7 @@ enum { #define IMA_SIGNAL_SRC_CHANGE 5 /* image-user gets a new image, check settings */ #define IMA_SIGNAL_USER_NEW_IMAGE 6 +#define IMA_SIGNAL_COLORMANAGE 7 #define IMA_CHAN_FLAG_BW 1 #define IMA_CHAN_FLAG_RGB 2 diff --git a/source/blender/blenkernel/BKE_key.h b/source/blender/blenkernel/BKE_key.h index 01baf8feb2a..d7d75b4c4c9 100644 --- a/source/blender/blenkernel/BKE_key.h +++ b/source/blender/blenkernel/BKE_key.h @@ -92,4 +92,4 @@ extern int slurph_opt; }; #endif -#endif // __BKE_KEY_H__ +#endif /* __BKE_KEY_H__ */ diff --git a/source/blender/blenkernel/BKE_lamp.h b/source/blender/blenkernel/BKE_lamp.h index 3acd4d1986e..244decf9d52 100644 --- a/source/blender/blenkernel/BKE_lamp.h +++ b/source/blender/blenkernel/BKE_lamp.h @@ -37,6 +37,7 @@ extern "C" { #endif struct Lamp; +struct Scene; struct Lamp *BKE_lamp_add(const char *name) WARN_UNUSED; struct Lamp *BKE_lamp_copy(struct Lamp *la) WARN_UNUSED; @@ -44,6 +45,8 @@ struct Lamp *localize_lamp(struct Lamp *la) WARN_UNUSED; void BKE_lamp_make_local(struct Lamp *la); void BKE_lamp_free(struct Lamp *la); +void lamp_drivers_update(struct Scene *scene, struct Lamp *la, float ctime); + #ifdef __cplusplus } #endif diff --git a/source/blender/blenkernel/BKE_lattice.h b/source/blender/blenkernel/BKE_lattice.h index 31626ef4a58..34baa48dbe2 100644 --- a/source/blender/blenkernel/BKE_lattice.h +++ b/source/blender/blenkernel/BKE_lattice.h @@ -46,7 +46,7 @@ struct Lattice *BKE_lattice_add(const char *name); struct Lattice *BKE_lattice_copy(struct Lattice *lt); void BKE_lattice_free(struct Lattice *lt); void BKE_lattice_make_local(struct Lattice *lt); -void calc_lat_fudu(int flag, int res, float *fu, float *du); +void calc_lat_fudu(int flag, int res, float *r_fu, float *r_du); void init_latt_deform(struct Object *oblatt, struct Object *ob); void calc_latt_deform(struct Object *, float co[3], float weight); diff --git a/source/blender/blenkernel/BKE_library.h b/source/blender/blenkernel/BKE_library.h index 91756448297..bc081b7f308 100644 --- a/source/blender/blenkernel/BKE_library.h +++ b/source/blender/blenkernel/BKE_library.h @@ -81,6 +81,7 @@ int set_listbasepointers(struct Main *main, struct ListBase **lb); void BKE_libblock_free(struct ListBase *lb, void *idv); void BKE_libblock_free_us(struct ListBase *lb, void *idv); +void BKE_libblock_free_data(struct ID *id); void free_main(struct Main *mainvar); void tag_main_idcode(struct Main *mainvar, const short type, const short tag); diff --git a/source/blender/blenkernel/BKE_mesh.h b/source/blender/blenkernel/BKE_mesh.h index c14085a559a..e53d0efffbd 100644 --- a/source/blender/blenkernel/BKE_mesh.h +++ b/source/blender/blenkernel/BKE_mesh.h @@ -130,7 +130,7 @@ struct Mesh *BKE_mesh_copy(struct Mesh *me); void mesh_update_customdata_pointers(struct Mesh *me, const short do_ensure_tess_cd); void BKE_mesh_make_local(struct Mesh *me); -void BKE_mesh_boundbox_calc(struct Mesh *me, float *loc, float *size); +void BKE_mesh_boundbox_calc(struct Mesh *me, float r_loc[3], float r_size[3]); void BKE_mesh_texspace_calc(struct Mesh *me); float *BKE_mesh_orco_verts_get(struct Object *ob); void BKE_mesh_orco_verts_transform(struct Mesh *me, float (*orco)[3], int totvert, int invert); @@ -283,15 +283,16 @@ typedef struct IndexNode { void create_vert_poly_map(MeshElemMap **map, int **mem, const struct MPoly *mface, const struct MLoop *mloop, int totvert, int totface, int totloop); - + void create_vert_edge_map(MeshElemMap **map, int **mem, - const struct MEdge *medge, int totvert, int totedge); + const struct MEdge *medge, int totvert, int totedge); /* vertex level transformations & checks (no derived mesh) */ int BKE_mesh_minmax(struct Mesh *me, float r_min[3], float r_max[3]); int BKE_mesh_center_median(struct Mesh *me, float cent[3]); int BKE_mesh_center_bounds(struct Mesh *me, float cent[3]); +int BKE_mesh_center_centroid(struct Mesh *me, float cent[3]); void BKE_mesh_translate(struct Mesh *me, float offset[3], int do_keys); /* mesh_validate.c */ diff --git a/source/blender/blenkernel/BKE_modifier.h b/source/blender/blenkernel/BKE_modifier.h index 3b675f3b620..7ee1c85d0de 100644 --- a/source/blender/blenkernel/BKE_modifier.h +++ b/source/blender/blenkernel/BKE_modifier.h @@ -352,6 +352,7 @@ int modifiers_isParticleEnabled(struct Object *ob); struct Object *modifiers_isDeformedByArmature(struct Object *ob); struct Object *modifiers_isDeformedByLattice(struct Object *ob); +struct Object *modifiers_isDeformedByCurve(struct Object *ob); int modifiers_usesArmature(struct Object *ob, struct bArmature *arm); int modifiers_isCorrectableDeformed(struct Object *ob); void modifier_freeTemporaryData(struct ModifierData *md); diff --git a/source/blender/blenkernel/BKE_multires.h b/source/blender/blenkernel/BKE_multires.h index 82a791348dd..bee2c374f27 100644 --- a/source/blender/blenkernel/BKE_multires.h +++ b/source/blender/blenkernel/BKE_multires.h @@ -48,7 +48,7 @@ struct Scene; void multires_customdata_delete(struct Mesh *me); void multires_set_tot_level(struct Object *ob, - struct MultiresModifierData *mmd, int lvl); + struct MultiresModifierData *mmd, int lvl); void multires_mark_as_modified(struct Object *ob, enum MultiresModifiedFlags flags); @@ -116,5 +116,4 @@ void multires_topology_changed(struct Mesh *me); void old_mdisps_bilinear(float out[3], float (*disps)[3], const int st, float u, float v); int mdisp_rot_face_to_crn(const int corners, const int face_side, const float u, const float v, float *x, float *y); -#endif // __BKE_MULTIRES_H__ - +#endif /* __BKE_MULTIRES_H__ */ diff --git a/source/blender/blenkernel/BKE_navmesh_conversion.h b/source/blender/blenkernel/BKE_navmesh_conversion.h index aab359b307a..cc9c18c764d 100644 --- a/source/blender/blenkernel/BKE_navmesh_conversion.h +++ b/source/blender/blenkernel/BKE_navmesh_conversion.h @@ -60,4 +60,4 @@ int polyFindVertex(const unsigned short *p, const int vertsPerPoly, unsigned sho float distPointToSegmentSq(const float *point, const float *a, const float *b); -#endif //NAVMESH_CONVERSION_H +#endif /* NAVMESH_CONVERSION_H */ diff --git a/source/blender/blenkernel/BKE_node.h b/source/blender/blenkernel/BKE_node.h index acd6f120f93..b365d93b246 100644 --- a/source/blender/blenkernel/BKE_node.h +++ b/source/blender/blenkernel/BKE_node.h @@ -193,10 +193,8 @@ typedef struct bNodeType { struct bNodeTree *(*group_edit_set)(struct bNode *node, int edit); void (*group_edit_clear)(struct bNode *node); - /* Generate a temporary list of internal links (bNodeLink), for muting and disconnect operators. - * Result must be freed by caller! - */ - ListBase (*internal_connect)(struct bNodeTree *, struct bNode *node); + /* Update the internal links list, for muting and disconnect operators. */ + void (*update_internal_links)(struct bNodeTree *, struct bNode *node); /* **** execution callbacks **** */ void *(*initexecfunc)(struct bNode *node); @@ -247,6 +245,7 @@ typedef struct bNodeType { #define NODE_CLASS_PARTICLES 25 #define NODE_CLASS_TRANSFORM 30 #define NODE_CLASS_COMBINE 31 +#define NODE_CLASS_SCRIPT 32 #define NODE_CLASS_SHADER 40 #define NODE_CLASS_LAYOUT 100 @@ -293,7 +292,7 @@ typedef struct bNodeTreeType { int (*validate_link)(struct bNodeTree *ntree, struct bNodeLink *link); /* Default internal linking. */ - ListBase (*internal_connect)(struct bNodeTree *, struct bNode *node); + void (*update_internal_links)(struct bNodeTree *, struct bNode *node); } bNodeTreeType; /* ************** GENERIC API, TREES *************** */ @@ -349,7 +348,7 @@ struct bNodeSocket *nodeInsertSocket(struct bNodeTree *ntree, struct bNode *node void nodeRemoveSocket(struct bNodeTree *ntree, struct bNode *node, struct bNodeSocket *sock); void nodeRemoveAllSockets(struct bNodeTree *ntree, struct bNode *node); -void nodeAddToPreview(struct bNode *node, float col[4], int x, int y, int do_manage); +void nodeAddToPreview(struct bNode *node, const float col[4], int x, int y, int do_manage); struct bNode *nodeAddNode(struct bNodeTree *ntree, struct bNodeTemplate *ntemp); void nodeUnlinkNode(struct bNodeTree *ntree, struct bNode *node); @@ -389,6 +388,7 @@ struct bNode *nodeGetActiveTexture(struct bNodeTree *ntree); void nodeUpdate(struct bNodeTree *ntree, struct bNode *node); int nodeUpdateID(struct bNodeTree *ntree, struct ID *id); +void nodeUpdateInternalLinks(struct bNodeTree *ntree, struct bNode *node); void nodeFreePreview(struct bNode *node); @@ -445,7 +445,7 @@ void node_type_exec_new(struct bNodeType *ntype, void (*freeexecfunc)(struct bNode *node, void *nodedata), void (*newexecfunc)(void *data, int thread, struct bNode *, void *nodedata, struct bNodeStack **, struct bNodeStack **)); -void node_type_internal_connect(struct bNodeType *ntype, ListBase (*internal_connect)(struct bNodeTree *, struct bNode *)); +void node_type_internal_links(struct bNodeType *ntype, void (*update_internal_links)(struct bNodeTree *, struct bNode *)); void node_type_gpu(struct bNodeType *ntype, int (*gpufunc)(struct GPUMaterial *mat, struct bNode *node, struct GPUNodeStack *in, struct GPUNodeStack *out)); void node_type_gpu_ext(struct bNodeType *ntype, int (*gpuextfunc)(struct GPUMaterial *mat, struct bNode *node, @@ -456,8 +456,8 @@ void node_type_compatibility(struct bNodeType *ntype, short compatibi /* ************** COMMON NODES *************** */ #define NODE_GROUP 2 -#define NODE_FORLOOP 3 -#define NODE_WHILELOOP 4 +#define __NODE_FORLOOP 3 /* deprecated */ +#define __NODE_WHILELOOP 4 /* deprecated */ #define NODE_FRAME 5 #define NODE_REROUTE 6 @@ -551,6 +551,12 @@ struct ShadeResult; #define SH_NODE_OBJECT_INFO 167 #define SH_NODE_PARTICLE_INFO 168 #define SH_NODE_TEX_BRICK 169 +#define SH_NODE_BUMP 170 +#define SH_NODE_SCRIPT 171 +#define SH_NODE_AMBIENT_OCCLUSION 172 +#define SH_NODE_BSDF_REFRACTION 173 +#define SH_NODE_TANGENT 174 +#define SH_NODE_NORMAL_MAP 175 /* custom defines options for Material node */ #define SH_NODE_MAT_DIFF 1 @@ -698,6 +704,7 @@ void ntreeGPUMaterialNodes(struct bNodeTree *ntree, struct GPUMateria #define CMP_NODE_BOKEHIMAGE 315 #define CMP_NODE_BOKEHBLUR 316 #define CMP_NODE_SWITCH 317 +#define CMP_NODE_PIXELATE 318 /* channel toggles */ #define CMP_CHAN_RGB 1 @@ -784,7 +791,9 @@ void ntreeTexCheckCyclics(struct bNodeTree *ntree); struct bNodeTreeExec *ntreeTexBeginExecTree(struct bNodeTree *ntree, int use_tree_data); void ntreeTexEndExecTree(struct bNodeTreeExec *exec, int use_tree_data); -int ntreeTexExecTree(struct bNodeTree *ntree, struct TexResult *target, float *coord, float *dxt, float *dyt, int osatex, short thread, struct Tex *tex, short which_output, int cfra, int preview, struct ShadeInput *shi, struct MTex *mtex); +int ntreeTexExecTree(struct bNodeTree *ntree, struct TexResult *target, + float coord[3], float dxt[3], float dyt[3], int osatex, const short thread, + struct Tex *tex, short which_output, int cfra, int preview, struct ShadeInput *shi, struct MTex *mtex); /*************************************************/ diff --git a/source/blender/blenkernel/BKE_paint.h b/source/blender/blenkernel/BKE_paint.h index a93e542fe15..c452c177143 100644 --- a/source/blender/blenkernel/BKE_paint.h +++ b/source/blender/blenkernel/BKE_paint.h @@ -94,6 +94,7 @@ typedef struct SculptSession { /* PBVH acceleration structure */ struct PBVH *pbvh; + int show_diffuse_color; /* Paiting on deformed mesh */ int modifiers_active; /* object is deformed with some modifiers */ diff --git a/source/blender/blenkernel/BKE_particle.h b/source/blender/blenkernel/BKE_particle.h index b3e650b2aa5..ec03f53dbdb 100644 --- a/source/blender/blenkernel/BKE_particle.h +++ b/source/blender/blenkernel/BKE_particle.h @@ -257,7 +257,9 @@ void psys_interpolate_mcol(const struct MCol *mcol, int quad, const float w[4], void copy_particle_key(struct ParticleKey *to, struct ParticleKey *from, int time); -void psys_particle_on_emitter(struct ParticleSystemModifierData *psmd, int distr, int index, int index_dmcache, float *fuv, float foffset, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor); +void psys_particle_on_emitter(struct ParticleSystemModifierData *psmd, int distr, int index, int index_dmcache, + float fuv[4], float foffset, float vec[3], float nor[3], + float utan[3], float vtan[3], float orco[3], float ornor[3]); struct ParticleSystemModifierData *psys_get_modifier(struct Object *ob, struct ParticleSystem *psys); struct ModifierData *object_add_particle_system(struct Scene *scene, struct Object *ob, const char *name); @@ -282,8 +284,11 @@ void psys_get_particle_on_path(struct ParticleSimulationData *sim, int pa_num, s int psys_get_particle_state(struct ParticleSimulationData *sim, int p, struct ParticleKey *state, int always); /* for anim.c */ -void psys_get_dupli_texture(struct ParticleSystem *psys, struct ParticleSettings *part, struct ParticleSystemModifierData *psmd, struct ParticleData *pa, struct ChildParticle *cpa, float *uv, float *orco); -void psys_get_dupli_path_transform(struct ParticleSimulationData *sim, struct ParticleData *pa, struct ChildParticle *cpa, struct ParticleCacheKey *cache, float mat[][4], float *scale); +void psys_get_dupli_texture(struct ParticleSystem *psys, struct ParticleSettings *part, + struct ParticleSystemModifierData *psmd, struct ParticleData *pa, struct ChildParticle *cpa, + float uv[2], float orco[3]); +void psys_get_dupli_path_transform(struct ParticleSimulationData *sim, struct ParticleData *pa, struct ChildParticle *cpa, + struct ParticleCacheKey *cache, float mat[][4], float *scale); ParticleThread *psys_threads_create(struct ParticleSimulationData *sim); void psys_threads_free(ParticleThread *threads); @@ -327,13 +332,17 @@ void psys_free_pdd(struct ParticleSystem *psys); float *psys_cache_vgroup(struct DerivedMesh *dm, struct ParticleSystem *psys, int vgroup); void psys_get_texture(struct ParticleSimulationData *sim, struct ParticleData *pa, struct ParticleTexture *ptex, int event, float cfra); -void psys_interpolate_face(struct MVert *mvert, struct MFace *mface, struct MTFace *tface, float (*orcodata)[3], float *uv, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor); +void psys_interpolate_face(struct MVert *mvert, struct MFace *mface, struct MTFace *tface, + float (*orcodata)[3], float w[4], float vec[3], float nor[3], float utan[3], float vtan[3], + float orco[3], float ornor[3]); float psys_particle_value_from_verts(struct DerivedMesh *dm, short from, struct ParticleData *pa, float *values); -void psys_get_from_key(struct ParticleKey *key, float *loc, float *vel, float *rot, float *time); +void psys_get_from_key(struct ParticleKey *key, float loc[3], float vel[3], float rot[4], float *time); /* BLI_bvhtree_ray_cast callback */ void BKE_psys_collision_neartest_cb(void *userdata, int index, const struct BVHTreeRay *ray, struct BVHTreeRayHit *hit); -void psys_particle_on_dm(struct DerivedMesh *dm, int from, int index, int index_dmcache, const float fw[4], float foffset, float vec[3], float nor[3], float utan[3], float vtan[3], float orco[3], float ornor[3]); +void psys_particle_on_dm(struct DerivedMesh *dm, int from, int index, int index_dmcache, + const float fw[4], float foffset, float vec[3], float nor[3], float utan[3], float vtan[3], + float orco[3], float ornor[3]); /* particle_system.c */ void initialize_particle(struct ParticleSimulationData *sim, struct ParticleData *pa, int p); diff --git a/source/blender/blenkernel/BKE_scene.h b/source/blender/blenkernel/BKE_scene.h index c12e913be45..9927c7a42ed 100644 --- a/source/blender/blenkernel/BKE_scene.h +++ b/source/blender/blenkernel/BKE_scene.h @@ -55,7 +55,12 @@ struct Text; #define SCE_COPY_LINK_DATA 3 #define SCE_COPY_FULL 4 -#define SETLOOPER(_sce_basis, _sce_iter, _base) _sce_iter = _sce_basis, _base = _setlooper_base_step(&_sce_iter, NULL); _base; _base = _setlooper_base_step(&_sce_iter, _base) +/* Use as the contents of a 'for' loop: for (SETLOOPER(...)) { ... */ +#define SETLOOPER(_sce_basis, _sce_iter, _base) \ + _sce_iter = _sce_basis, _base = _setlooper_base_step(&_sce_iter, NULL); \ + _base; \ + _base = _setlooper_base_step(&_sce_iter, _base) + struct Base *_setlooper_base_step(struct Scene **sce_iter, struct Base *base); void free_avicodecdata(struct AviCodecData *acd); diff --git a/source/blender/blenkernel/BKE_sequencer.h b/source/blender/blenkernel/BKE_sequencer.h index 80431682d6f..ba611817c8f 100644 --- a/source/blender/blenkernel/BKE_sequencer.h +++ b/source/blender/blenkernel/BKE_sequencer.h @@ -68,27 +68,27 @@ void BKE_sequence_iterator_begin(struct Editing *ed, SeqIterator *iter, int use_ void BKE_sequence_iterator_next(SeqIterator *iter); void BKE_sequence_iterator_end(SeqIterator *iter); -#define SEQP_BEGIN(ed, _seq) \ +#define SEQP_BEGIN(_ed, _seq) \ { \ - SeqIterator iter; \ - for (BKE_sequence_iterator_begin(ed, &iter, 1); \ - iter.valid; \ - BKE_sequence_iterator_next(&iter)) \ + SeqIterator iter_macro; \ + for (BKE_sequence_iterator_begin(_ed, &iter_macro, 1); \ + iter_macro.valid; \ + BKE_sequence_iterator_next(&iter_macro)) \ { \ - _seq = iter.seq; + _seq = iter_macro.seq; #define SEQ_BEGIN(ed, _seq) \ { \ - SeqIterator iter; \ - for (BKE_sequence_iterator_begin(ed, &iter, 0); \ - iter.valid; \ - BKE_sequence_iterator_next(&iter)) \ + SeqIterator iter_macro; \ + for (BKE_sequence_iterator_begin(ed, &iter_macro, 0); \ + iter_macro.valid; \ + BKE_sequence_iterator_next(&iter_macro)) \ { \ - _seq = iter.seq; + _seq = iter_macro.seq; #define SEQ_END \ } \ - BKE_sequence_iterator_end(&iter); \ + BKE_sequence_iterator_end(&iter_macro); \ } typedef struct SeqRenderData { @@ -356,6 +356,7 @@ typedef struct SeqLoadInfo { typedef struct Sequence *(*SeqLoadFunc)(struct bContext *, ListBase *, struct SeqLoadInfo *); struct Sequence *BKE_sequence_alloc(ListBase *lb, int cfra, int machine); +void BKE_sequence_init_colorspace(struct Sequence *seq); struct Sequence *BKE_sequencer_add_image_strip(struct bContext *C, ListBase *seqbasep, struct SeqLoadInfo *seq_load); struct Sequence *BKE_sequencer_add_sound_strip(struct bContext *C, ListBase *seqbasep, struct SeqLoadInfo *seq_load); diff --git a/source/blender/blenkernel/BKE_smoke.h b/source/blender/blenkernel/BKE_smoke.h index 1f824ccbafc..3a9d2b86b41 100644 --- a/source/blender/blenkernel/BKE_smoke.h +++ b/source/blender/blenkernel/BKE_smoke.h @@ -35,8 +35,10 @@ typedef float (*bresenham_callback)(float *result, float *input, int res[3], int *pixel, float *tRay, float correct); -void smokeModifier_do(struct SmokeModifierData *smd, struct Scene *scene, struct Object *ob, struct DerivedMesh *dm); +struct DerivedMesh *smokeModifier_do(struct SmokeModifierData *smd, struct Scene *scene, struct Object *ob, struct DerivedMesh *dm); +void smoke_reallocate_fluid(struct SmokeDomainSettings *sds, float dx, int res[3], int free_old); +void smoke_reallocate_highres_fluid(struct SmokeDomainSettings *sds, float dx, int res[3], int free_old); void smokeModifier_free(struct SmokeModifierData *smd); void smokeModifier_reset(struct SmokeModifierData *smd); void smokeModifier_reset_turbulence(struct SmokeModifierData *smd); @@ -44,5 +46,7 @@ void smokeModifier_createType(struct SmokeModifierData *smd); void smokeModifier_copy(struct SmokeModifierData *smd, struct SmokeModifierData *tsmd); long long smoke_get_mem_req(int xres, int yres, int zres, int amplify); +float smoke_get_velocity_at(struct Object *ob, float position[3], float velocity[3]); +int smoke_get_data_flags(struct SmokeDomainSettings *sds); #endif /* __BKE_SMOKE_H__ */ diff --git a/source/blender/blenkernel/BKE_subsurf.h b/source/blender/blenkernel/BKE_subsurf.h index 3b8d0eafd4d..653f2a42675 100644 --- a/source/blender/blenkernel/BKE_subsurf.h +++ b/source/blender/blenkernel/BKE_subsurf.h @@ -64,10 +64,10 @@ typedef enum { } SubsurfFlags; struct DerivedMesh *subsurf_make_derived_from_derived( - struct DerivedMesh *dm, - struct SubsurfModifierData *smd, - float (*vertCos)[3], - SubsurfFlags flags); + struct DerivedMesh *dm, + struct SubsurfModifierData *smd, + float (*vertCos)[3], + SubsurfFlags flags); void subsurf_calculate_limit_positions(struct Mesh *me, float (*positions_r)[3]); diff --git a/source/blender/blenkernel/BKE_tracking.h b/source/blender/blenkernel/BKE_tracking.h index c14476a3b59..eb7004b1ced 100644 --- a/source/blender/blenkernel/BKE_tracking.h +++ b/source/blender/blenkernel/BKE_tracking.h @@ -80,7 +80,7 @@ int BKE_tracking_track_has_marker_at_frame(struct MovieTrackingTrack *track, int int BKE_tracking_track_has_enabled_marker_at_frame(struct MovieTrackingTrack *track, int framenr); void BKE_tracking_track_path_clear(struct MovieTrackingTrack *track, int ref_frame, int action); -void BKE_tracking_tracks_join(struct MovieTrackingTrack *dst_track, struct MovieTrackingTrack *src_track); +void BKE_tracking_tracks_join(struct MovieTracking *tracking, struct MovieTrackingTrack *dst_track, struct MovieTrackingTrack *src_track); struct MovieTrackingTrack *BKE_tracking_track_get_named(struct MovieTracking *tracking, struct MovieTrackingObject *object, @@ -114,7 +114,7 @@ void BKE_tracking_marker_get_subframe_position(struct MovieTrackingTrack *track, /* **** Object **** */ struct MovieTrackingObject *BKE_tracking_object_add(struct MovieTracking *tracking, const char *name); -void BKE_tracking_object_delete(struct MovieTracking *tracking, struct MovieTrackingObject *object); +int BKE_tracking_object_delete(struct MovieTracking *tracking, struct MovieTrackingObject *object); void BKE_tracking_object_unique_name(struct MovieTracking *tracking, struct MovieTrackingObject *object); diff --git a/source/blender/blenkernel/BKE_utildefines.h b/source/blender/blenkernel/BKE_utildefines.h index 63f5ec59a0b..7c1e0e97565 100644 --- a/source/blender/blenkernel/BKE_utildefines.h +++ b/source/blender/blenkernel/BKE_utildefines.h @@ -32,10 +32,14 @@ extern "C" { #endif -/* currently unused but we may want to add macros here for BKE later */ +#define BKE_BIT_TEST_SET(value, test, flag) \ +{ \ + if (test) (value) |= flag; \ + else (value) &= ~flag; \ +} (void)0 #ifdef __cplusplus } #endif -#endif // __BKE_UTILDEFINES_H__ +#endif /* __BKE_UTILDEFINES_H__ */ diff --git a/source/blender/blenkernel/CMakeLists.txt b/source/blender/blenkernel/CMakeLists.txt index efdb80433c6..c5dc7da8edf 100644 --- a/source/blender/blenkernel/CMakeLists.txt +++ b/source/blender/blenkernel/CMakeLists.txt @@ -25,7 +25,6 @@ set(INC . - ../avi ../blenfont ../blenlib ../blenloader @@ -194,8 +193,8 @@ set(SRC BKE_lamp.h BKE_lattice.h BKE_library.h - BKE_mask.h BKE_main.h + BKE_mask.h BKE_material.h BKE_mball.h BKE_mesh.h @@ -250,7 +249,7 @@ if(WITH_AUDASPACE) endif() if(WITH_BULLET) - list(APPEND INC + list(APPEND INC_SYS ../../../extern/bullet2/src ) add_definitions(-DUSE_BULLET) @@ -292,6 +291,13 @@ if(WITH_IMAGE_HDR) add_definitions(-DWITH_HDR) endif() +if(WITH_CODEC_AVI) + list(APPEND INC + ../avi + ) + add_definitions(-DWITH_AVI) +endif() + if(WITH_CODEC_QUICKTIME) list(APPEND INC ../quicktime @@ -350,12 +356,6 @@ if(WITH_MOD_OCEANSIM) add_definitions(-DWITH_OCEANSIM) endif() -if(WITH_MOD_DECIMATE) - list(APPEND INC - ../../../intern/decimation/extern - ) -endif() - if(WITH_MOD_BOOLEAN) list(APPEND INC ../../../intern/bsp/extern diff --git a/source/blender/blenkernel/SConscript b/source/blender/blenkernel/SConscript index d1a35b122e8..f7b8f59fa57 100644 --- a/source/blender/blenkernel/SConscript +++ b/source/blender/blenkernel/SConscript @@ -10,7 +10,7 @@ sources_mask = env.Glob('intern/mask*.c') incs = '. #/intern/guardedalloc #/intern/memutil' incs += ' ../blenlib ../blenfont ../makesdna ../windowmanager' -incs += ' ../render/extern/include #/intern/decimation/extern ../makesrna' +incs += ' ../render/extern/include ../makesrna' incs += ' ../imbuf ../ikplugin ../avi #/intern/elbeem/extern ../nodes ../modifiers' incs += ' #/intern/iksolver/extern ../blenloader' incs += ' #/extern/bullet2/src' diff --git a/source/blender/blenkernel/depsgraph_private.h b/source/blender/blenkernel/depsgraph_private.h index 512b799aeed..12c111f5f16 100644 --- a/source/blender/blenkernel/depsgraph_private.h +++ b/source/blender/blenkernel/depsgraph_private.h @@ -61,7 +61,7 @@ typedef struct DagAdjList { typedef struct DagNode { int color; short type; - float x, y, k; + float x, y, k; void *ob; void *first_ancestor; int ancestor_count; diff --git a/source/blender/blenkernel/intern/CCGSubSurf.c b/source/blender/blenkernel/intern/CCGSubSurf.c index 82ac0736b07..cc20470b4d5 100644 --- a/source/blender/blenkernel/intern/CCGSubSurf.c +++ b/source/blender/blenkernel/intern/CCGSubSurf.c @@ -868,7 +868,7 @@ CCGSubSurf *ccgSubSurf_new(CCGMeshIFC *ifc, int subdivLevels, CCGAllocatorIFC *a ss->oldVMap = ss->oldEMap = ss->oldFMap = NULL; ss->lenTempArrays = 0; ss->tempVerts = NULL; - ss->tempEdges = NULL; + ss->tempEdges = NULL; return ss; } diff --git a/source/blender/blenkernel/intern/DerivedMesh.c b/source/blender/blenkernel/intern/DerivedMesh.c index 5ff1ce2aec3..b329a502c42 100644 --- a/source/blender/blenkernel/intern/DerivedMesh.c +++ b/source/blender/blenkernel/intern/DerivedMesh.c @@ -51,8 +51,6 @@ #include "BLI_utildefines.h" #include "BLI_linklist.h" -#include "BLF_translation.h" - #include "BKE_cdderivedmesh.h" #include "BKE_displist.h" #include "BKE_key.h" @@ -266,9 +264,11 @@ void DM_init_funcs(DerivedMesh *dm) dm->getVertData = DM_get_vert_data; dm->getEdgeData = DM_get_edge_data; dm->getTessFaceData = DM_get_tessface_data; + dm->getPolyData = DM_get_poly_data; dm->getVertDataArray = DM_get_vert_data_layer; dm->getEdgeDataArray = DM_get_edge_data_layer; dm->getTessFaceDataArray = DM_get_tessface_data_layer; + dm->getPolyDataArray = DM_get_poly_data_layer; bvhcache_init(&dm->bvhCache); } @@ -288,6 +288,13 @@ void DM_init(DerivedMesh *dm, DerivedMeshType type, int numVerts, int numEdges, dm->needsFree = 1; dm->auto_bump_scale = -1.0f; dm->dirty = 0; + + /* don't use CustomData_reset(...); because we dont want to touch customdata */ + fill_vn_i(dm->vertData.typemap, CD_NUMTYPES, -1); + fill_vn_i(dm->edgeData.typemap, CD_NUMTYPES, -1); + fill_vn_i(dm->faceData.typemap, CD_NUMTYPES, -1); + fill_vn_i(dm->loopData.typemap, CD_NUMTYPES, -1); + fill_vn_i(dm->polyData.typemap, CD_NUMTYPES, -1); } void DM_from_template(DerivedMesh *dm, DerivedMesh *source, DerivedMeshType type, @@ -384,7 +391,7 @@ void DM_ensure_tessface(DerivedMesh *dm) } else if (dm->dirty & DM_DIRTY_TESS_CDLAYERS) { - BLI_assert(CustomData_has_layer(&dm->faceData, CD_POLYINDEX)); + BLI_assert(CustomData_has_layer(&dm->faceData, CD_ORIGINDEX)); DM_update_tessface_data(dm); } @@ -408,7 +415,7 @@ void DM_update_tessface_data(DerivedMesh *dm) const int hasPCol = CustomData_has_layer(ldata, CD_PREVIEW_MLOOPCOL); const int hasOrigSpace = CustomData_has_layer(ldata, CD_ORIGSPACE_MLOOP); - int *polyindex = CustomData_get_layer(fdata, CD_POLYINDEX); + int *polyindex = CustomData_get_layer(fdata, CD_ORIGINDEX); int mf_idx, totface = dm->getNumTessFaces(dm), @@ -465,11 +472,11 @@ void DM_to_mesh(DerivedMesh *dm, Mesh *me, Object *ob) int totvert, totedge /*, totface */ /* UNUSED */, totloop, totpoly; int did_shapekeys = 0; - memset(&tmp.vdata, 0, sizeof(tmp.vdata)); - memset(&tmp.edata, 0, sizeof(tmp.edata)); - memset(&tmp.fdata, 0, sizeof(tmp.fdata)); - memset(&tmp.ldata, 0, sizeof(tmp.ldata)); - memset(&tmp.pdata, 0, sizeof(tmp.pdata)); + CustomData_reset(&tmp.vdata); + CustomData_reset(&tmp.edata); + CustomData_reset(&tmp.fdata); + CustomData_reset(&tmp.ldata); + CustomData_reset(&tmp.pdata); totvert = tmp.totvert = dm->getNumVerts(dm); totedge = tmp.totedge = dm->getNumEdges(dm); @@ -626,6 +633,12 @@ void *DM_get_tessface_data(DerivedMesh *dm, int index, int type) return CustomData_get(&dm->faceData, index, type); } +void *DM_get_poly_data(DerivedMesh *dm, int index, int type) +{ + return CustomData_get(&dm->polyData, index, type); +} + + void *DM_get_vert_data_layer(DerivedMesh *dm, int type) { if (type == CD_MVERT) @@ -902,7 +915,7 @@ static DerivedMesh *create_orco_dm(Object *ob, Mesh *me, BMEditMesh *em, int lay float (*orco)[3]; int free; - if (em) dm = CDDM_from_BMEditMesh(em, me, FALSE, FALSE); + if (em) dm = CDDM_from_editbmesh(em, FALSE, FALSE); else dm = CDDM_from_mesh(me, ob); orco = get_orco_coords_dm(ob, em, layer, &free); @@ -1269,7 +1282,7 @@ static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape int i, j, tot; if (!me->key) - return; + return; tot = CustomData_number_of_layers(&dm->vertData, CD_SHAPEKEY); for (i = 0; i < tot; i++) { @@ -1374,7 +1387,7 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos ModifierData *firstmd, *md, *previewmd = NULL; CDMaskLink *datamasks, *curr; /* XXX Always copying POLYINDEX, else tessellated data are no more valid! */ - CustomDataMask mask, nextmask, append_mask = CD_MASK_POLYINDEX; + CustomDataMask mask, nextmask, append_mask = CD_MASK_ORIGINDEX; float (*deformedVerts)[3] = NULL; DerivedMesh *dm = NULL, *orcodm, *clothorcodm, *finaldm; int numVerts = me->totvert; @@ -1506,7 +1519,7 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos if (!modifier_isEnabled(scene, md, required_mode)) continue; if (mti->type == eModifierTypeType_OnlyDeform && !useDeform) continue; if ((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) { - modifier_setError(md, "%s", TIP_("Modifier requires original data, bad stack position.")); + modifier_setError(md, "Modifier requires original data, bad stack position"); continue; } if (sculpt_mode && (!has_multires || multires_applied)) { @@ -1519,7 +1532,7 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos unsupported |= multires_applied; if (unsupported) { - modifier_setError(md, "%s", TIP_("Not supported in sculpt mode.")); + modifier_setError(md, "Not supported in sculpt mode"); continue; } } @@ -1666,8 +1679,8 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos nextmask &= ~CD_MASK_ORCO; DM_set_only_copy(orcodm, nextmask | CD_MASK_ORIGINDEX | - (mti->requiredDataMask ? - mti->requiredDataMask(ob, md) : 0)); + (mti->requiredDataMask ? + mti->requiredDataMask(ob, md) : 0)); ndm = mti->applyModifier(md, ob, orcodm, app_flags & ~MOD_APPLY_USECACHE); if (ndm) { @@ -1802,7 +1815,7 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos #if 0 if (num_tessface == 0 && finaldm->getNumTessFaces(finaldm) == 0) #else - if (finaldm->getNumTessFaces(finaldm) == 0) /* || !CustomData_has_layer(&finaldm->faceData, CD_POLYINDEX)) */ + if (finaldm->getNumTessFaces(finaldm) == 0) /* || !CustomData_has_layer(&finaldm->faceData, CD_ORIGINDEX)) */ #endif { finaldm->recalcTessellation(finaldm); @@ -1810,8 +1823,8 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos /* Even if tessellation is not needed, some modifiers might have modified CD layers * (like mloopcol or mloopuv), hence we have to update those. */ else if (finaldm->dirty & DM_DIRTY_TESS_CDLAYERS) { - /* A tessellation already exists, it should always have a CD_POLYINDEX. */ - BLI_assert(CustomData_has_layer(&finaldm->faceData, CD_POLYINDEX)); + /* A tessellation already exists, it should always have a CD_ORIGINDEX. */ + BLI_assert(CustomData_has_layer(&finaldm->faceData, CD_ORIGINDEX)); DM_update_tessface_data(finaldm); } /* Need to watch this, it can cause issues, see bug [#29338] */ @@ -1880,7 +1893,7 @@ int editbmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh *d if (!modifier_isEnabled(scene, md, required_mode)) return 0; if ((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) { - modifier_setError(md, "%s", TIP_("Modifier requires original data, bad stack position.")); + modifier_setError(md, "Modifier requires original data, bad stack position"); return 0; } @@ -1975,7 +1988,7 @@ static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, D } else { - dm = CDDM_from_BMEditMesh(em, ob->data, FALSE, FALSE); + dm = CDDM_from_editbmesh(em, FALSE, FALSE); if (deformedVerts) { CDDM_apply_vert_coords(dm, deformedVerts); @@ -2066,12 +2079,18 @@ static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, D } else if (dm) { *final_r = dm; - (*final_r)->calcNormals(*final_r); /* BMESH_ONLY - BMESH_TODO. check if this is needed */ + + /* once we support skipping normal calculation with modifiers we may want to add this back */ +#if 0 // was added for bmesh but is not needed + (*final_r)->calcNormals(*final_r); +#endif } else if (!deformedVerts && cage_r && *cage_r) { /* cage should already have up to date normals */ *final_r = *cage_r; - (*final_r)->calcNormals(*final_r); /* BMESH_ONLY - BMESH_TODO. check if this is needed */ +#if 0 // was added for bmesh but is not needed + (*final_r)->calcNormals(*final_r); +#endif } else { /* this is just a copy of the editmesh, no need to calc normals */ @@ -2248,8 +2267,16 @@ DerivedMesh *mesh_create_derived_view(Scene *scene, Object *ob, CustomDataMask d { DerivedMesh *final; + /* XXX hack + * psys modifier updates particle state when called during dupli-list generation, + * which can lead to wrong transforms. This disables particle system modifier execution. + */ + ob->transflag |= OB_NO_PSYS_UPDATE; + mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1, 0, 0); + ob->transflag &= ~OB_NO_PSYS_UPDATE; + return final; } @@ -2419,7 +2446,7 @@ static int GetNumVertsOfFace(const SMikkTSpaceContext *pContext, const int face_ static void GetPosition(const SMikkTSpaceContext *pContext, float fPos[], 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 float *co = pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].co; copy_v3_v3(fPos, co); @@ -2427,7 +2454,7 @@ static void GetPosition(const SMikkTSpaceContext *pContext, float fPos[], const static void GetTextureCoordinate(const SMikkTSpaceContext *pContext, float fUV[], 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; if (pMesh->mtface != NULL) { @@ -2442,7 +2469,7 @@ static void GetTextureCoordinate(const SMikkTSpaceContext *pContext, float fUV[] static void GetNormal(const SMikkTSpaceContext *pContext, float fNorm[], 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 int smoothnormal = (pMesh->mface[face_num].flag & ME_SMOOTH); @@ -2472,7 +2499,7 @@ static void GetNormal(const SMikkTSpaceContext *pContext, float fNorm[], const i } static void SetTSpace(const SMikkTSpaceContext *pContext, const float fvTangent[], const float fSign, const int face_num, const int iVert) { - //assert(vert_index>=0 && vert_index<4); + //assert(vert_index >= 0 && vert_index < 4); SGLSLMeshToTangent *pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData; float *pRes = pMesh->tangent[4 * face_num + iVert]; copy_v3_v3(pRes, fvTangent); @@ -2483,15 +2510,11 @@ static void SetTSpace(const SMikkTSpaceContext *pContext, const float fvTangent[ void DM_add_tangent_layer(DerivedMesh *dm) { /* mesh vars */ - MTFace *mtface, *tf; - MFace *mface, *mf; - MVert *mvert, *v1, *v2, *v3, *v4; - MemArena *arena = NULL; - VertexTangent **vtangents = NULL; + MVert *mvert; + MTFace *mtface; + MFace *mface; float (*orco)[3] = NULL, (*tangent)[4]; - float *uv1, *uv2, *uv3, *uv4, *vtang; - float fno[3], tang[3], uv[4][2]; - int i, j, len, mf_vi[4], totvert, totface, iCalcNewMethod; + int /* totvert, */ totface; float *nors; if (CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1) @@ -2500,7 +2523,7 @@ void DM_add_tangent_layer(DerivedMesh *dm) nors = dm->getTessFaceDataArray(dm, CD_NORMAL); /* check we have all the needed layers */ - totvert = dm->getNumVerts(dm); + /* totvert = dm->getNumVerts(dm); */ /* UNUSED */ totface = dm->getNumTessFaces(dm); mvert = dm->getVertArray(dm); @@ -2517,14 +2540,8 @@ void DM_add_tangent_layer(DerivedMesh *dm) DM_add_tessface_layer(dm, CD_TANGENT, CD_CALLOC, NULL); tangent = DM_get_tessface_data_layer(dm, CD_TANGENT); - /* allocate some space */ - arena = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "tangent layer arena"); - BLI_memarena_use_calloc(arena); - vtangents = MEM_callocN(sizeof(VertexTangent *) * totvert, "VertexTangent"); - /* new computation method */ - iCalcNewMethod = 1; - if (iCalcNewMethod != 0) { + { SGLSLMeshToTangent mesh2tangent = {0}; SMikkTSpaceContext sContext = {0}; SMikkTSpaceInterface sInterface = {0}; @@ -2547,87 +2564,13 @@ void DM_add_tangent_layer(DerivedMesh *dm) sInterface.m_setTSpaceBasic = SetTSpace; /* 0 if failed */ - iCalcNewMethod = genTangSpaceDefault(&sContext); + genTangSpaceDefault(&sContext); } - - if (!iCalcNewMethod) { - /* sum tangents at connected vertices */ - for (i = 0, tf = mtface, mf = mface; i < totface; mf++, tf++, i++) { - v1 = &mvert[mf->v1]; - v2 = &mvert[mf->v2]; - v3 = &mvert[mf->v3]; - - if (mf->v4) { - v4 = &mvert[mf->v4]; - normal_quad_v3(fno, v4->co, v3->co, v2->co, v1->co); - } - else { - v4 = NULL; - normal_tri_v3(fno, v3->co, v2->co, v1->co); - } - - if (mtface) { - uv1 = tf->uv[0]; - uv2 = tf->uv[1]; - uv3 = tf->uv[2]; - uv4 = tf->uv[3]; - } - else { - uv1 = uv[0]; uv2 = uv[1]; uv3 = uv[2]; uv4 = uv[3]; - map_to_sphere(&uv[0][0], &uv[0][1], orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]); - map_to_sphere(&uv[1][0], &uv[1][1], orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]); - map_to_sphere(&uv[2][0], &uv[2][1], orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]); - if (v4) - map_to_sphere(&uv[3][0], &uv[3][1], orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]); - } - - tangent_from_uv(uv1, uv2, uv3, v1->co, v2->co, v3->co, fno, tang); - sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1); - sum_or_add_vertex_tangent(arena, &vtangents[mf->v2], tang, uv2); - sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3); - - if (mf->v4) { - v4 = &mvert[mf->v4]; - - tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, fno, tang); - sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1); - sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3); - sum_or_add_vertex_tangent(arena, &vtangents[mf->v4], tang, uv4); - } - } - - /* write tangent to layer */ - for (i = 0, tf = mtface, mf = mface; i < totface; mf++, tf++, i++, tangent += 4) { - len = (mf->v4) ? 4 : 3; - - if (mtface == NULL) { - map_to_sphere(&uv[0][0], &uv[0][1], orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]); - map_to_sphere(&uv[1][0], &uv[1][1], orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]); - map_to_sphere(&uv[2][0], &uv[2][1], orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]); - if (len == 4) - map_to_sphere(&uv[3][0], &uv[3][1], orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]); - } - - mf_vi[0] = mf->v1; - mf_vi[1] = mf->v2; - mf_vi[2] = mf->v3; - mf_vi[3] = mf->v4; - - for (j = 0; j < len; j++) { - vtang = find_vertex_tangent(vtangents[mf_vi[j]], mtface ? tf->uv[j] : uv[j]); - normalize_v3_v3(tangent[j], vtang); - ((float *) tangent[j])[3] = 1.0f; - } - } - } - - BLI_memarena_free(arena); - MEM_freeN(vtangents); } void DM_calc_auto_bump_scale(DerivedMesh *dm) { - /* int totvert= dm->getNumVerts(dm); */ /* UNUSED */ + /* int totvert = dm->getNumVerts(dm); */ /* UNUSED */ int totface = dm->getNumTessFaces(dm); MVert *mvert = dm->getVertArray(dm); diff --git a/source/blender/blenkernel/intern/action.c b/source/blender/blenkernel/intern/action.c index 66df7eccbd0..e95451252d0 100644 --- a/source/blender/blenkernel/intern/action.c +++ b/source/blender/blenkernel/intern/action.c @@ -224,7 +224,7 @@ bActionGroup *get_active_actiongroup(bAction *act) { bActionGroup *agrp = NULL; - if (act && act->groups.first) { + if (act && act->groups.first) { for (agrp = act->groups.first; agrp; agrp = agrp->next) { if (agrp->flag & AGRP_ACTIVE) break; @@ -301,7 +301,7 @@ bActionGroup *action_groups_add_new(bAction *act, const char name[]) /* add to action, and validate */ BLI_addtail(&act->groups, agrp); - BLI_uniquename(&act->groups, agrp, "Group", '.', offsetof(bActionGroup, name), sizeof(agrp->name)); + BLI_uniquename(&act->groups, agrp, "Group", '.', offsetof(bActionGroup, name), sizeof(agrp->name)); /* return the new group */ return agrp; @@ -380,7 +380,7 @@ 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 */ @@ -906,8 +906,8 @@ void calc_action_range(const bAction *act, float *start, float *end, short incl_ calc_fcurve_range(fcu, &nmin, &nmax, FALSE, TRUE); /* compare to the running tally */ - min = MIN2(min, nmin); - max = MAX2(max, nmax); + min = min_ff(min, nmin); + max = max_ff(max, nmax); foundvert = 1; } @@ -925,10 +925,10 @@ void calc_action_range(const bAction *act, float *start, float *end, short incl_ FMod_Limits *fmd = (FMod_Limits *)fcm->data; if (fmd->flag & FCM_LIMIT_XMIN) { - min = MIN2(min, fmd->rect.xmin); + min = min_ff(min, fmd->rect.xmin); } if (fmd->flag & FCM_LIMIT_XMAX) { - max = MAX2(max, fmd->rect.xmax); + max = max_ff(max, fmd->rect.xmax); } } break; @@ -955,7 +955,7 @@ void calc_action_range(const bAction *act, float *start, float *end, short incl_ foundmod = 1; } } - } + } if (foundvert || foundmod) { if (min == max) max += 1.0f; diff --git a/source/blender/blenkernel/intern/anim.c b/source/blender/blenkernel/intern/anim.c index 58d20fff2bc..f5c0660371b 100644 --- a/source/blender/blenkernel/intern/anim.c +++ b/source/blender/blenkernel/intern/anim.c @@ -40,6 +40,8 @@ #include "BLI_rand.h" #include "BLI_utildefines.h" +#include "BLF_translation.h" + #include "DNA_anim_types.h" #include "DNA_armature_types.h" #include "DNA_group_types.h" @@ -74,8 +76,8 @@ /* --------------------- */ /* forward declarations */ -static void object_duplilist_recursive(ID *id, Scene *scene, Object *ob, ListBase *duplilist, float par_space_mat[][4], int par_index, - int level, short flag); +static void object_duplilist_recursive(ID *id, Scene *scene, Object *ob, ListBase *duplilist, float par_space_mat[][4], + int persistent_id[MAX_DUPLI_RECUR], int level, int index, short flag); /* ******************************************************************** */ /* Animation Visualization */ @@ -174,10 +176,10 @@ bMotionPath *animviz_verify_motionpaths(ReportList *reports, Scene *scene, Objec /* avoid 0 size allocs */ if (avs->path_sf >= avs->path_ef) { BKE_reportf(reports, RPT_ERROR, - "Motion Path frame extents invalid for %s (%d to %d).%s\n", + "Motion path frame extents invalid for %s (%d to %d)%s", (pchan) ? pchan->name : ob->id.name, avs->path_sf, avs->path_ef, - (avs->path_sf == avs->path_ef) ? " Cannot have single-frame paths." : ""); + (avs->path_sf == avs->path_ef) ? TIP_(", cannot have single-frame paths") : ""); return NULL; } @@ -704,31 +706,45 @@ int where_on_path(Object *ob, float ctime, float vec[4], float dir[3], float qua #define DUPLILIST_FOR_RENDER 2 #define DUPLILIST_ANIMATED 4 -static DupliObject *new_dupli_object(ListBase *lb, Object *ob, float mat[][4], int lay, int index, int par_index, int type, short flag) +static DupliObject *new_dupli_object(ListBase *lb, Object *ob, float mat[][4], int lay, + int persistent_id[MAX_DUPLI_RECUR], int level, int index, int type, short flag) { DupliObject *dob = MEM_callocN(sizeof(DupliObject), "dupliobject"); - + int i; + BLI_addtail(lb, dob); dob->ob = ob; copy_m4_m4(dob->mat, mat); copy_m4_m4(dob->omat, ob->obmat); dob->origlay = ob->lay; - dob->index = index; - dob->particle_index = par_index; dob->type = type; dob->animated = (type == OB_DUPLIGROUP) && (flag & DUPLILIST_ANIMATED); ob->lay = lay; + + /* set persistent id, which is an array with a persistent index for each level + * (particle number, vertex number, ..). by comparing this we can find the same + * 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 < level; i++) + dob->persistent_id[i] = persistent_id[level - 1 - i]; + + /* 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) + dob->no_draw = TRUE; return dob; } -static void group_duplilist(ListBase *lb, Scene *scene, Object *ob, int par_index, +static void group_duplilist(ListBase *lb, Scene *scene, Object *ob, int persistent_id[MAX_DUPLI_RECUR], int level, short flag) { DupliObject *dob; Group *group; GroupObject *go; - float mat[4][4], tmat[4][4]; + float mat[4][4], tmat[4][4], id; if (ob->dup_group == NULL) return; group = ob->dup_group; @@ -748,7 +764,7 @@ static void group_duplilist(ListBase *lb, Scene *scene, Object *ob, int par_inde if (group_is_animated(ob, group)) flag |= DUPLILIST_ANIMATED; - for (go = group->gobject.first; go; go = go->next) { + for (go = group->gobject.first, id = 0; go; go = go->next, id++) { /* note, if you check on layer here, render goes wrong... it still deforms verts and uses parent imat */ if (go->ob != ob) { @@ -762,7 +778,7 @@ static void group_duplilist(ListBase *lb, Scene *scene, Object *ob, int par_inde mult_m4_m4m4(mat, ob->obmat, go->ob->obmat); } - dob = new_dupli_object(lb, go->ob, mat, ob->lay, 0, par_index, OB_DUPLIGROUP, flag); + dob = new_dupli_object(lb, go->ob, mat, ob->lay, persistent_id, level, id, OB_DUPLIGROUP, flag); /* check the group instance and object layers match, also that the object visible flags are ok. */ if ((dob->origlay & group->layer) == 0 || @@ -771,20 +787,17 @@ static void group_duplilist(ListBase *lb, Scene *scene, Object *ob, int par_inde { dob->no_draw = TRUE; } - else { - dob->no_draw = FALSE; - } if (go->ob->transflag & OB_DUPLI) { copy_m4_m4(dob->ob->obmat, dob->mat); - object_duplilist_recursive(&group->id, scene, go->ob, lb, ob->obmat, par_index, level + 1, flag); + object_duplilist_recursive(&group->id, scene, go->ob, lb, ob->obmat, persistent_id, level + 1, id, flag); copy_m4_m4(dob->ob->obmat, dob->omat); } } } } -static void frames_duplilist(ListBase *lb, Scene *scene, Object *ob, int par_index, int level, short flag) +static void frames_duplilist(ListBase *lb, Scene *scene, Object *ob, int persistent_id[MAX_DUPLI_RECUR], int level, short flag) { extern int enable_cu_speed; /* object.c */ Object copyob; @@ -822,7 +835,7 @@ static void frames_duplilist(ListBase *lb, Scene *scene, Object *ob, int par_ind ok = (ok < ob->dupon); } - if (ok) { + if (ok) { DupliObject *dob; /* WARNING: doing animation updates in this way is not terribly accurate, as the dependencies @@ -832,7 +845,7 @@ static void frames_duplilist(ListBase *lb, Scene *scene, Object *ob, int par_ind BKE_animsys_evaluate_animdata(scene, &ob->id, ob->adt, (float)scene->r.cfra, ADT_RECALC_ANIM); /* ob-eval will do drivers, so we don't need to do them */ BKE_object_where_is_calc_time(scene, ob, (float)scene->r.cfra); - dob = new_dupli_object(lb, ob, ob->obmat, ob->lay, scene->r.cfra, par_index, OB_DUPLIFRAMES, flag); + dob = new_dupli_object(lb, ob, ob->obmat, ob->lay, persistent_id, level, scene->r.cfra, OB_DUPLIFRAMES, flag); copy_m4_m4(dob->omat, copyob.obmat); } } @@ -863,7 +876,7 @@ typedef struct VertexDupliData { Scene *scene; Object *ob, *par; float (*orco)[3]; - int par_index; + int *persistent_id; } VertexDupliData; /* ------------- */ @@ -900,7 +913,7 @@ static void vertex_dupli__mapFunc(void *userData, int index, const float co[3], origlay = vdd->ob->lay; - dob = new_dupli_object(vdd->lb, vdd->ob, obmat, vdd->par->lay, index, vdd->par_index, OB_DUPLIVERTS, vdd->flag); + dob = new_dupli_object(vdd->lb, vdd->ob, obmat, vdd->par->lay, vdd->persistent_id, vdd->level, index, OB_DUPLIVERTS, vdd->flag); /* restore the original layer so that each dupli will have proper dob->origlay */ vdd->ob->lay = origlay; @@ -912,12 +925,12 @@ static void vertex_dupli__mapFunc(void *userData, int index, const float co[3], float tmpmat[4][4]; copy_m4_m4(tmpmat, vdd->ob->obmat); copy_m4_m4(vdd->ob->obmat, obmat); /* pretend we are really this mat */ - object_duplilist_recursive((ID *)vdd->id, vdd->scene, vdd->ob, vdd->lb, obmat, vdd->par_index, vdd->level + 1, vdd->flag); + object_duplilist_recursive((ID *)vdd->id, vdd->scene, vdd->ob, vdd->lb, obmat, vdd->persistent_id, vdd->level + 1, index, vdd->flag); copy_m4_m4(vdd->ob->obmat, tmpmat); } } -static void vertex_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, float par_space_mat[][4], int par_index, +static void vertex_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, float par_space_mat[][4], int persistent_id[MAX_DUPLI_RECUR], int level, short flag) { Object *ob, *ob_iter; @@ -968,7 +981,7 @@ static void vertex_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, fl } /* Start looping on Scene OR Group objects */ - while (base || go) { + while (base || go) { if (sce) { ob_iter = base->object; oblay = base->lay; @@ -1002,7 +1015,7 @@ static void vertex_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, fl vdd.scene = scene; vdd.par = par; copy_m4_m4(vdd.pmat, pmat); - vdd.par_index = par_index; + vdd.persistent_id = persistent_id; /* mballs have a different dupli handling */ if (ob->type != OB_MBALL) ob->flag |= OB_DONE; /* doesnt render */ @@ -1041,7 +1054,7 @@ static void vertex_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, fl dm->release(dm); } -static void face_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, float par_space_mat[][4], int par_index, +static void face_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, float par_space_mat[][4], int persistent_id[MAX_DUPLI_RECUR], int level, short flag) { Object *ob, *ob_iter; @@ -1102,7 +1115,7 @@ static void face_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, floa } /* Start looping on Scene OR Group objects */ - while (base || go) { + while (base || go) { if (sce) { ob_iter = base->object; oblay = base->lay; @@ -1184,7 +1197,7 @@ static void face_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, floa copy_m4_m4(tmat, obmat); mul_m4_m4m3(obmat, tmat, mat); - dob = new_dupli_object(lb, ob, obmat, par->lay, a, par_index, OB_DUPLIFACES, (flag & DUPLILIST_ANIMATED)); + dob = new_dupli_object(lb, ob, obmat, par->lay, persistent_id, level, a, OB_DUPLIFACES, (flag & DUPLILIST_ANIMATED)); if (flag & DUPLILIST_FOR_RENDER) { w = 1.0f / (float)mp->totloop; @@ -1207,7 +1220,7 @@ static void face_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, floa float tmpmat[4][4]; copy_m4_m4(tmpmat, ob->obmat); copy_m4_m4(ob->obmat, obmat); /* pretend we are really this mat */ - object_duplilist_recursive((ID *)id, scene, ob, lb, ob->obmat, par_index, level + 1, flag); + object_duplilist_recursive((ID *)id, scene, ob, lb, ob->obmat, persistent_id, level + 1, a, flag); copy_m4_m4(ob->obmat, tmpmat); } } @@ -1227,7 +1240,7 @@ static void face_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, floa dm->release(dm); } -static void new_particle_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, float par_space_mat[][4], int UNUSED(par_index), ParticleSystem *psys, +static void new_particle_duplilist(ListBase *lb, ID *id, Scene *scene, Object *par, float par_space_mat[][4], int persistent_id[MAX_DUPLI_RECUR], ParticleSystem *psys, int level, short flag) { GroupObject *go; @@ -1242,7 +1255,7 @@ static void new_particle_duplilist(ListBase *lb, ID *id, Scene *scene, Object *p float ctime, pa_time, scale = 1.0f; float tmat[4][4], mat[4][4], pamat[4][4], vec[3], size = 0.0; float (*obmat)[4], (*oldobmat)[4]; - int a, b, counter, index, hair = 0; + int a, b, hair = 0; int totpart, totchild, totgroup = 0 /*, pa_num */; int no_draw_flag = PARS_UNEXIST; @@ -1358,8 +1371,7 @@ static void new_particle_duplilist(ListBase *lb, ID *id, Scene *scene, Object *p else a = totpart; - index = 0; - for (pa = psys->particles, counter = 0; a < totpart + totchild; a++, pa++, counter++) { + for (pa = psys->particles; a < totpart + totchild; a++, pa++) { if (a < totpart) { /* handle parent particle */ if (pa->flag & no_draw_flag) @@ -1454,7 +1466,8 @@ static void new_particle_duplilist(ListBase *lb, ID *id, Scene *scene, Object *p else copy_m4_m4(mat, tmat); - dob = new_dupli_object(lb, go->ob, mat, par->lay, counter, index, OB_DUPLIPARTS, (flag & DUPLILIST_ANIMATED)); + dob = new_dupli_object(lb, go->ob, mat, par->lay, persistent_id, level, a, OB_DUPLIPARTS, (flag & DUPLILIST_ANIMATED)); + dob->particle_system = psys; copy_m4_m4(dob->omat, obcopylist[b].obmat); if (flag & DUPLILIST_FOR_RENDER) psys_get_dupli_texture(psys, part, sim.psmd, pa, cpa, dob->uv, dob->orco); @@ -1514,14 +1527,12 @@ static void new_particle_duplilist(ListBase *lb, ID *id, Scene *scene, Object *p if (part->draw & PART_DRAW_GLOBAL_OB) add_v3_v3v3(mat[3], mat[3], vec); - dob = new_dupli_object(lb, ob, mat, ob->lay, counter, index, GS(id->name) == ID_GR ? OB_DUPLIGROUP : OB_DUPLIPARTS, (flag & DUPLILIST_ANIMATED)); + dob = new_dupli_object(lb, ob, mat, ob->lay, persistent_id, level, a, GS(id->name) == ID_GR ? OB_DUPLIGROUP : OB_DUPLIPARTS, (flag & DUPLILIST_ANIMATED)); + dob->particle_system = psys; copy_m4_m4(dob->omat, oldobmat); if (flag & DUPLILIST_FOR_RENDER) psys_get_dupli_texture(psys, part, sim.psmd, pa, cpa, dob->uv, dob->orco); } - - /* only counts visible particles */ - index++; } /* restore objects since they were changed in BKE_object_where_is_calc_time */ @@ -1568,7 +1579,7 @@ static Object *find_family_object(Object **obar, char *family, char ch) } -static void font_duplilist(ListBase *lb, Scene *scene, Object *par, int par_index, int level, short flag) +static void font_duplilist(ListBase *lb, Scene *scene, Object *par, int persistent_id[MAX_DUPLI_RECUR], int level, short flag) { Object *ob, *obar[256] = {NULL}; Curve *cu; @@ -1607,7 +1618,7 @@ static void font_duplilist(ListBase *lb, Scene *scene, Object *par, int par_inde copy_m4_m4(obmat, par->obmat); copy_v3_v3(obmat[3], vec); - new_dupli_object(lb, ob, obmat, par->lay, a, par_index, OB_DUPLIVERTS, flag); + new_dupli_object(lb, ob, obmat, par->lay, persistent_id, level, a, OB_DUPLIVERTS, flag); } } @@ -1616,8 +1627,8 @@ static void font_duplilist(ListBase *lb, Scene *scene, Object *par, int par_inde /* ------------- */ -static void object_duplilist_recursive(ID *id, Scene *scene, Object *ob, ListBase *duplilist, float par_space_mat[][4], int par_index, - int level, short flag) +static void object_duplilist_recursive(ID *id, Scene *scene, Object *ob, ListBase *duplilist, float par_space_mat[][4], + int persistent_id[MAX_DUPLI_RECUR], int level, int index, short flag) { if ((ob->transflag & OB_DUPLI) == 0) return; @@ -1634,34 +1645,45 @@ static void object_duplilist_recursive(ID *id, Scene *scene, Object *ob, ListBas } } + /* keep track of persistent id */ + if (level > 0) + persistent_id[level - 1] = index; + if (ob->transflag & OB_DUPLIPARTS) { ParticleSystem *psys = ob->particlesystem.first; - for (; psys; psys = psys->next) - new_particle_duplilist(duplilist, id, scene, ob, par_space_mat, par_index, psys, level + 1, flag); + int psysid = 0; + + /* particle system take up one level in id, the particles another */ + for (; psys; psys = psys->next, psysid++) { + persistent_id[level] = psysid; + new_particle_duplilist(duplilist, id, scene, ob, par_space_mat, persistent_id, psys, level + 2, flag); + } + + persistent_id[level] = 0; } else if (ob->transflag & OB_DUPLIVERTS) { if (ob->type == OB_MESH) { - vertex_duplilist(duplilist, id, scene, ob, par_space_mat, par_index, level + 1, flag); + vertex_duplilist(duplilist, id, scene, ob, par_space_mat, persistent_id, level + 1, flag); } else if (ob->type == OB_FONT) { if (GS(id->name) == ID_SCE) { /* TODO - support dupligroups */ - font_duplilist(duplilist, scene, ob, par_index, level + 1, flag); + font_duplilist(duplilist, scene, ob, persistent_id, level + 1, flag); } } } else if (ob->transflag & OB_DUPLIFACES) { if (ob->type == OB_MESH) - face_duplilist(duplilist, id, scene, ob, par_space_mat, par_index, level + 1, flag); + face_duplilist(duplilist, id, scene, ob, par_space_mat, persistent_id, level + 1, flag); } else if (ob->transflag & OB_DUPLIFRAMES) { if (GS(id->name) == ID_SCE) { /* TODO - support dupligroups */ - frames_duplilist(duplilist, scene, ob, par_index, level + 1, flag); + frames_duplilist(duplilist, scene, ob, persistent_id, level + 1, flag); } } else if (ob->transflag & OB_DUPLIGROUP) { DupliObject *dob; - group_duplilist(duplilist, scene, ob, par_index, level + 1, flag); /* now recursive */ + group_duplilist(duplilist, scene, ob, persistent_id, level + 1, flag); /* now recursive */ if (level == 0) { for (dob = duplilist->first; dob; dob = dob->next) @@ -1669,6 +1691,10 @@ static void object_duplilist_recursive(ID *id, Scene *scene, Object *ob, ListBas copy_m4_m4(dob->ob->obmat, dob->mat); } } + + /* clear persistent id */ + if (level > 0) + persistent_id[level - 1] = 0; } /* Returns a list of DupliObject @@ -1676,13 +1702,14 @@ static void object_duplilist_recursive(ID *id, Scene *scene, Object *ob, ListBas ListBase *object_duplilist_ex(Scene *sce, Object *ob, int update, int for_render) { ListBase *duplilist = MEM_mallocN(sizeof(ListBase), "duplilist"); + int persistent_id[MAX_DUPLI_RECUR] = {0}; int flag = 0; - if(update) flag |= DUPLILIST_DO_UPDATE; - if(for_render) flag |= DUPLILIST_FOR_RENDER; + if (update) flag |= DUPLILIST_DO_UPDATE; + if (for_render) flag |= DUPLILIST_FOR_RENDER; duplilist->first = duplilist->last = NULL; - object_duplilist_recursive((ID *)sce, sce, ob, duplilist, NULL, 0, 0, flag); + object_duplilist_recursive((ID *)sce, sce, ob, duplilist, NULL, persistent_id, 0, 0, flag); return duplilist; } diff --git a/source/blender/blenkernel/intern/anim_sys.c b/source/blender/blenkernel/intern/anim_sys.c index 5dae2035ab0..40b883e3f4e 100644 --- a/source/blender/blenkernel/intern/anim_sys.c +++ b/source/blender/blenkernel/intern/anim_sys.c @@ -188,9 +188,9 @@ short BKE_animdata_set_action(ReportList *reports, ID *id, bAction *act) else { /* cannot set */ BKE_reportf(reports, RPT_ERROR, - "Couldn't set Action '%s' onto ID '%s', as it doesn't have suitably rooted paths for this purpose", - act->id.name + 2, id->name); - //ok = 0; + "Could not set action '%s' onto ID '%s', as it does not have suitably rooted paths " + "for this purpose", act->id.name + 2, id->name); + /* ok = 0; */ } } else { @@ -419,7 +419,7 @@ void action_move_fcurves_by_basepath(bAction *srcAct, bAction *dstAct, const cha /* should F-Curve be moved over? * - we only need the start of the path to match basepath */ - if (animpath_matches_basepath(fcu->rna_path, basepath)) { + if (animpath_matches_basepath(fcu->rna_path, basepath)) { bActionGroup *agrp = NULL; /* if grouped... */ @@ -574,7 +574,7 @@ static char *rna_path_rename_fix(ID *owner_id, const char *prefix, const char *o */ if ( (prefixPtr && oldNamePtr) && (prefixPtr + prefixLen == oldNamePtr) ) { /* if we haven't aren't able to resolve the path now, try again after fixing it */ - if (!verify_paths || check_rna_path_is_valid(owner_id, oldpath) == 0) { + if (!verify_paths || check_rna_path_is_valid(owner_id, oldpath) == 0) { DynStr *ds = BLI_dynstr_new(); char *postfixPtr = oldNamePtr + oldNameLen; char *newPath = NULL; @@ -724,7 +724,7 @@ void BKE_animdata_fix_paths_rename(ID *owner_id, AnimData *adt, ID *ref_id, cons /* pad the names with [" "] so that only exact matches are made */ oldN = BLI_sprintfN("[\"%s\"]", oldName); newN = BLI_sprintfN("[\"%s\"]", newName); - } + } else { oldN = BLI_sprintfN("[%d]", oldSubscript); newN = BLI_sprintfN("[%d]", newSubscript); @@ -781,7 +781,7 @@ void BKE_animdata_main_cb(Main *mainptr, ID_AnimData_Edit_Callback func, void *u ANIMDATA_NODETREE_IDS_CB(mainptr->tex.first, Tex); /* lamps */ - ANIMDATA_IDS_CB(mainptr->lamp.first); + ANIMDATA_NODETREE_IDS_CB(mainptr->lamp.first, Lamp); /* materials */ ANIMDATA_NODETREE_IDS_CB(mainptr->mat.first, Material); @@ -823,7 +823,7 @@ void BKE_animdata_main_cb(Main *mainptr, ID_AnimData_Edit_Callback func, void *u ANIMDATA_IDS_CB(mainptr->mask.first); /* worlds */ - ANIMDATA_IDS_CB(mainptr->world.first); + ANIMDATA_NODETREE_IDS_CB(mainptr->world.first, World); /* scenes */ ANIMDATA_NODETREE_IDS_CB(mainptr->scene.first, Scene); @@ -868,7 +868,7 @@ void BKE_all_animdata_fix_paths_rename(ID *ref_id, const char *prefix, const cha RENAMEFIX_ANIM_NODETREE_IDS(mainptr->tex.first, Tex); /* lamps */ - RENAMEFIX_ANIM_IDS(mainptr->lamp.first); + RENAMEFIX_ANIM_NODETREE_IDS(mainptr->lamp.first, Lamp); /* materials */ RENAMEFIX_ANIM_NODETREE_IDS(mainptr->mat.first, Material); @@ -910,7 +910,7 @@ void BKE_all_animdata_fix_paths_rename(ID *ref_id, const char *prefix, const cha RENAMEFIX_ANIM_IDS(mainptr->mask.first); /* worlds */ - RENAMEFIX_ANIM_IDS(mainptr->world.first); + RENAMEFIX_ANIM_NODETREE_IDS(mainptr->world.first, World); /* scenes */ RENAMEFIX_ANIM_NODETREE_IDS(mainptr->scene.first, Scene); @@ -973,9 +973,8 @@ KeyingSet *BKE_keyingset_add(ListBase *list, const char idname[], const char nam /* allocate new KeyingSet */ ks = MEM_callocN(sizeof(KeyingSet), "KeyingSet"); - BLI_strncpy(ks->idname, idname ? idname : name ? name : "KeyingSet", sizeof(ks->idname)); - - BLI_strncpy(ks->name, name ? name : idname ? idname : "Keying Set", sizeof(ks->name)); + BLI_strncpy(ks->idname, (idname) ? idname : (name) ? name : "KeyingSet", sizeof(ks->idname)); + BLI_strncpy(ks->name, (name) ? name : (idname) ? idname : "Keying Set", sizeof(ks->name)); ks->flag = flag; ks->keyingflag = keyingflag; @@ -983,10 +982,10 @@ KeyingSet *BKE_keyingset_add(ListBase *list, const char idname[], const char nam /* add KeyingSet to list */ BLI_addtail(list, ks); - /* Make sure KeyingSet has a unique idname. */ + /* Make sure KeyingSet has a unique idname */ BLI_uniquename(list, ks, "KeyingSet", '.', offsetof(KeyingSet, idname), sizeof(ks->idname)); - /* Make sure KeyingSet has a unique label (this helps with identification). */ + /* Make sure KeyingSet has a unique label (this helps with identification) */ BLI_uniquename(list, ks, "Keying Set", '.', offsetof(KeyingSet, name), sizeof(ks->name)); /* return new KeyingSet for further editing */ @@ -1239,7 +1238,7 @@ static short animsys_write_rna_setting(PointerRNA *ptr, char *path, int array_in if (new_ptr.type == &RNA_PoseBone) { /* bone transforms - update pose (i.e. tag depsgraph) */ skip_updates_hack = 1; - } + } if (skip_updates_hack == 0) RNA_property_update_cache_add(&new_ptr, prop); diff --git a/source/blender/blenkernel/intern/armature.c b/source/blender/blenkernel/intern/armature.c index b87342f85fa..b3cbc1f2b16 100644 --- a/source/blender/blenkernel/intern/armature.c +++ b/source/blender/blenkernel/intern/armature.c @@ -534,10 +534,12 @@ Mat4 *b_bone_spline_setup(bPoseChannel *pchan, int rest) mul_m4_v3(imat, h2); /* if next bone is B-bone too, use average handle direction */ - if (next->bone->segments > 1) - ; - else + if (next->bone->segments > 1) { + /* pass */ + } + else { h2[1] -= length; + } normalize_v3(h2); /* find the next roll to interpolate as well */ @@ -945,7 +947,7 @@ void armature_deform_verts(Object *armOb, Object *target, DerivedMesh *dm, float } } - if (use_dverts || armature_def_nr >= 0) { + if (use_dverts || armature_def_nr != -1) { if (dm) dvert = dm->getVertData(dm, i, CD_MDEFORMVERT); else if (dverts && i < target_totvert) @@ -956,7 +958,7 @@ void armature_deform_verts(Object *armOb, Object *target, DerivedMesh *dm, float else dvert = NULL; - if (armature_def_nr >= 0 && dvert) { + if (armature_def_nr != -1 && dvert) { armature_weight = defvert_find_weight(dvert, armature_def_nr); if (invert_vgroup) @@ -1423,19 +1425,20 @@ void BKE_rotMode_change_values(float quat[4], float eul[3], float axis[3], float * *************************************************************************** */ /* Computes vector and roll based on a rotation. * "mat" must contain only a rotation, and no scaling. */ -void mat3_to_vec_roll(float mat[][3], float vec[3], float *roll) +void mat3_to_vec_roll(float mat[][3], float r_vec[3], float *r_roll) { - if (vec) - copy_v3_v3(vec, mat[1]); + if (r_vec) { + copy_v3_v3(r_vec, mat[1]); + } - if (roll) { + if (r_roll) { float vecmat[3][3], vecmatinv[3][3], rollmat[3][3]; vec_roll_to_mat3(mat[1], 0.0f, vecmat); invert_m3_m3(vecmatinv, vecmat); mul_m3_m3m3(rollmat, vecmatinv, mat); - *roll = (float)atan2(rollmat[2][0], rollmat[2][2]); + *r_roll = atan2f(rollmat[2][0], rollmat[2][2]); } } @@ -1459,7 +1462,7 @@ void vec_roll_to_mat3(const float vec[3], const float roll, float mat[][3]) * so a value inbetween these is needed. * * was 0.000001, causes bug [#30438] (which is same as [#27675, imho). - * Reseting it to org value seems to cause no more [#23954]... + * Resetting it to org value seems to cause no more [#23954]... * * was 0.0000000000001, caused bug [#31333], smaller values give unstable * roll when toggling editmode again... @@ -1590,7 +1593,7 @@ static void pose_proxy_synchronize(Object *ob, Object *from, int layer_protected if (UNLIKELY(pchanp == NULL)) { /* happens for proxies that become invalid because of a missing link - * for regulat cases it shouldn't happen at all */ + * for regular cases it shouldn't happen at all */ } else if (pchan->bone->layer & layer_protected) { ListBase proxylocal_constraints = {NULL, NULL}; diff --git a/source/blender/blenkernel/intern/blender.c b/source/blender/blenkernel/intern/blender.c index 99b788e80ce..e1e868b234e 100644 --- a/source/blender/blenkernel/intern/blender.c +++ b/source/blender/blenkernel/intern/blender.c @@ -119,7 +119,7 @@ void free_blender(void) BKE_sequencer_cache_destruct(); IMB_moviecache_destruct(); - free_nodesystem(); + free_nodesystem(); } void initglobals(void) @@ -237,7 +237,7 @@ static void setup_app_data(bContext *C, BlendFileData *bfd, const char *filepath /* free G.main Main database */ // CTX_wm_manager_set(C, NULL); - clear_global(); + clear_global(); /* clear old property update cache, in case some old references are left dangling */ RNA_property_update_cache_free(); @@ -338,7 +338,7 @@ static int handle_subversion_warning(Main *main, ReportList *reports) (main->minversionfile == BLENDER_VERSION && main->minsubversionfile > BLENDER_SUBVERSION)) { - BKE_reportf(reports, RPT_ERROR, "File written by newer Blender binary: %d.%d, expect loss of data!", + BKE_reportf(reports, RPT_ERROR, "File written by newer Blender binary (%d.%d), expect loss of data!", main->minversionfile, main->minsubversionfile); } @@ -407,9 +407,9 @@ int BKE_read_file(bContext *C, const char *filepath, ReportList *reports) } else setup_app_data(C, bfd, filepath); // frees BFD - } + } else - BKE_reports_prependf(reports, "Loading %s failed: ", filepath); + BKE_reports_prependf(reports, "Loading '%s' failed: ", filepath); return (bfd ? retval : BKE_READ_FILE_FAIL); } @@ -485,7 +485,7 @@ static int read_undosave(bContext *C, UndoElem *uel) int success = 0, fileflags; /* This is needed so undoing/redoing doesn't crash with threaded previews going */ - WM_jobs_stop_all(CTX_wm_manager(C)); + WM_jobs_kill_all_except(CTX_wm_manager(C), CTX_wm_screen(C)); BLI_strncpy(mainstr, G.main->name, sizeof(mainstr)); /* temporal store */ @@ -612,7 +612,7 @@ void BKE_write_undo(bContext *C, const char *name) } } -/* 1= an undo, -1 is a redo. we have to make sure 'curundo' remains at current situation */ +/* 1 = an undo, -1 is a redo. we have to make sure 'curundo' remains at current situation */ void BKE_undo_step(bContext *C, int step) { @@ -621,7 +621,9 @@ void BKE_undo_step(bContext *C, int step) } else if (step == 1) { /* curundo should never be NULL, after restart or load file it should call undo_save */ - if (curundo == NULL || curundo->prev == NULL) ; // XXX error("No undo available"); + if (curundo == NULL || curundo->prev == NULL) { + // XXX error("No undo available"); + } else { if (G.debug & G_DEBUG) printf("undo %s\n", curundo->name); curundo = curundo->prev; @@ -631,7 +633,9 @@ void BKE_undo_step(bContext *C, int step) else { /* curundo has to remain current situation! */ - if (curundo == NULL || curundo->next == NULL) ; // XXX error("No redo available"); + if (curundo == NULL || curundo->next == NULL) { + // XXX error("No redo available"); + } else { read_undosave(C, curundo->next); curundo = curundo->next; diff --git a/source/blender/blenkernel/intern/bmfont.c b/source/blender/blenkernel/intern/bmfont.c index a7d90f09160..0495e729937 100644 --- a/source/blender/blenkernel/intern/bmfont.c +++ b/source/blender/blenkernel/intern/bmfont.c @@ -102,7 +102,7 @@ void readBitmapFontVersion0(ImBuf * ibuf, unsigned char * rect, int step) buffer = MEM_mallocN(bytes, "readBitmapFontVersion0:buffer"); - index = 0; + index = 0; for (i = 0; i < bytes; i++) { buffer[i] = rect[index]; index += step; @@ -247,12 +247,13 @@ int locateGlyph(bmFont *bmfont, unsigned short unicode) return(current); } -void matrixGlyph(ImBuf * ibuf, unsigned short unicode, - float *centerx, float *centery, - float *sizex, float *sizey, - float *transx, float *transy, - float *movex, float *movey, - float *advance) +void matrixGlyph( + ImBuf * ibuf, unsigned short unicode, + float *centerx, float *centery, + float *sizex, float *sizey, + float *transx, float *transy, + float *movex, float *movey, + float *advance) { int index; bmFont *bmfont; diff --git a/source/blender/blenkernel/intern/boids.c b/source/blender/blenkernel/intern/boids.c index 79d5e092a10..b6f1b88c912 100644 --- a/source/blender/blenkernel/intern/boids.c +++ b/source/blender/blenkernel/intern/boids.c @@ -101,13 +101,15 @@ static int rule_goal_avoid(BoidRule *rule, BoidBrainData *bbd, BoidValues *val, break; } } - else if (rule->type == eBoidRuleType_Goal && eob == bpa->ground) - ; /* skip current object */ + else if (rule->type == eBoidRuleType_Goal && eob == bpa->ground) { + /* skip current object */ + } else if (pd->forcefield == PFIELD_BOID && mul * pd->f_strength > 0.0f && get_effector_data(cur, &cur_efd, &epoint, 0)) { float temp = mul * pd->f_strength * effector_falloff(cur, &cur_efd, &epoint, bbd->part->effector_weights); - if (temp == 0.0f) - ; /* do nothing */ + if (temp == 0.0f) { + /* do nothing */ + } else if (temp > priority) { priority = temp; eff = cur; @@ -954,7 +956,8 @@ void boid_brain(BoidBrainData *bbd, int p, ParticleData *pa) // } //} - bbd->wanted_co[0]=bbd->wanted_co[1]=bbd->wanted_co[2]=bbd->wanted_speed=0.0f; + zero_v3(bbd->wanted_co); + bbd->wanted_speed = 0.0f; /* create random seed for every particle & frame */ rand = (int)(PSYS_FRAND(psys->seed + p) * 1000); @@ -988,7 +991,8 @@ void boid_brain(BoidBrainData *bbd, int p, ParticleData *pa) add_v3_v3(wanted_co, bbd->wanted_co); wanted_speed += bbd->wanted_speed; n++; - bbd->wanted_co[0]=bbd->wanted_co[1]=bbd->wanted_co[2]=bbd->wanted_speed=0.0f; + zero_v3(bbd->wanted_co); + bbd->wanted_speed = 0.0f; } } @@ -1168,7 +1172,7 @@ void boid_body(BoidBrainData *bbd, ParticleData *pa) /* constrain direction with maximum angular velocity */ angle = saacos(dot_v3v3(old_dir, wanted_dir)); - angle = minf(angle, val.max_ave); + angle = min_ff(angle, val.max_ave); cross_v3_v3v3(nor, old_dir, wanted_dir); axis_angle_to_quat(q, nor, angle); @@ -1264,9 +1268,9 @@ void boid_body(BoidBrainData *bbd, ParticleData *pa) { float grav[3]; - grav[0]= 0.0f; - grav[1]= 0.0f; - grav[2]= bbd->sim->scene->physics_settings.gravity[2] < 0.0f ? -1.0f : 0.0f; + grav[0] = 0.0f; + grav[1] = 0.0f; + grav[2] = bbd->sim->scene->physics_settings.gravity[2] < 0.0f ? -1.0f : 0.0f; /* don't take forward acceleration into account (better banking) */ if (dot_v3v3(bpa->data.acc, pa->state.vel) > 0.0f) { @@ -1307,9 +1311,9 @@ void boid_body(BoidBrainData *bbd, ParticleData *pa) { float grav[3]; - grav[0]= 0.0f; - grav[1]= 0.0f; - grav[2]= bbd->sim->scene->physics_settings.gravity[2] < 0.0f ? -1.0f : 0.0f; + grav[0] = 0.0f; + grav[1] = 0.0f; + grav[2] = bbd->sim->scene->physics_settings.gravity[2] < 0.0f ? -1.0f : 0.0f; /* gather apparent gravity */ diff --git a/source/blender/blenkernel/intern/booleanops_mesh.c b/source/blender/blenkernel/intern/booleanops_mesh.c index be79077bb58..461b945282f 100644 --- a/source/blender/blenkernel/intern/booleanops_mesh.c +++ b/source/blender/blenkernel/intern/booleanops_mesh.c @@ -142,7 +142,7 @@ CSG_AddMeshToBlender( /* Create a new blender mesh object - using 'base' as * a template for the new object. */ - ob_new= AddNewBlenderMesh(mesh->base); + ob_new = AddNewBlenderMesh(mesh->base); me_new = ob_new->data; @@ -180,7 +180,7 @@ CSG_PerformOp( if ((mesh1 == NULL) || (mesh2 == NULL) || (output == NULL)) { return 0; - } + } if ((int_op_type < 1) || (int_op_type > 3)) return 0; switch (int_op_type) { @@ -203,8 +203,8 @@ CSG_PerformOp( mesh1->m_face_iterator, mesh1->m_vertex_iterator, mesh2->m_face_iterator, - mesh2->m_vertex_iterator, - InterpFaceVertexData + mesh2->m_vertex_iterator, + InterpFaceVertexData ); } else { @@ -215,8 +215,8 @@ CSG_PerformOp( mesh1->m_face_iterator, mesh1->m_vertex_iterator, mesh2->m_face_iterator, - mesh2->m_vertex_iterator, - InterpNoUserData + mesh2->m_vertex_iterator, + InterpNoUserData ); } diff --git a/source/blender/blenkernel/intern/brush.c b/source/blender/blenkernel/intern/brush.c index ce39eea5ceb..98b206712d6 100644 --- a/source/blender/blenkernel/intern/brush.c +++ b/source/blender/blenkernel/intern/brush.c @@ -618,18 +618,18 @@ void BKE_brush_imbuf_new(const Scene *scene, Brush *brush, short flt, short texf /* Unified Size and Strength */ -// XXX: be careful about setting size and unprojected radius -// because they depend on one another -// these functions do not set the other corresponding value -// this can lead to odd behavior if size and unprojected -// radius become inconsistent. -// the biggest problem is that it isn't possible to change -// unprojected radius because a view context is not -// available. my ussual solution to this is to use the -// ratio of change of the size to change the unprojected -// radius. Not completely convinced that is correct. -// In anycase, a better solution is needed to prevent -// inconsistency. +/* XXX: be careful about setting size and unprojected radius + * because they depend on one another + * these functions do not set the other corresponding value + * this can lead to odd behavior if size and unprojected + * radius become inconsistent. + * the biggest problem is that it isn't possible to change + * unprojected radius because a view context is not + * available. my ussual solution to this is to use the + * ratio of change of the size to change the unprojected + * radius. Not completely convinced that is correct. + * In anycase, a better solution is needed to prevent + * inconsistency. */ void BKE_brush_size_set(Scene *scene, Brush *brush, int size) { @@ -741,7 +741,7 @@ void BKE_brush_scale_unprojected_radius(float *unprojected_radius, } /* scale brush size to reflect a change in the brush's unprojected radius */ -void BKE_brush_scale_size(int *BKE_brush_size_get, +void BKE_brush_scale_size(int *r_brush_size, float new_unprojected_radius, float old_unprojected_radius) { @@ -749,7 +749,7 @@ void BKE_brush_scale_size(int *BKE_brush_size_get, /* avoid division by zero */ if (old_unprojected_radius != 0) scale /= new_unprojected_radius; - (*BKE_brush_size_get) = (int)((float)(*BKE_brush_size_get) * scale); + (*r_brush_size) = (int)((float)(*r_brush_size) * scale); } /* Brush Painting */ @@ -876,8 +876,8 @@ static void brush_painter_do_partial(BrushPainter *painter, ImBuf *oldtexibuf, /* not sure if it's actually needed or it's a mistake in coords/sizes * calculation in brush_painter_fixed_tex_partial_update(), but without this * limitation memory gets corrupted at fast strokes with quite big spacing (sergey) */ - w = MIN2(w, ibuf->x); - h = MIN2(h, ibuf->y); + w = min_ii(w, ibuf->x); + h = min_ii(h, ibuf->y); if (painter->cache.flt) { for (; y < h; y++) { @@ -1052,13 +1052,13 @@ void BKE_brush_painter_break_stroke(BrushPainter *painter) static void brush_pressure_apply(BrushPainter *painter, Brush *brush, float pressure) { if (BKE_brush_use_alpha_pressure(painter->scene, brush)) - brush_alpha_set(painter->scene, brush, maxf(0.0f, painter->startalpha * pressure)); + brush_alpha_set(painter->scene, brush, max_ff(0.0f, painter->startalpha * pressure)); if (BKE_brush_use_size_pressure(painter->scene, brush)) - BKE_brush_size_set(painter->scene, brush, maxf(1.0f, painter->startsize * pressure)); + BKE_brush_size_set(painter->scene, brush, max_ff(1.0f, painter->startsize * pressure)); if (brush->flag & BRUSH_JITTER_PRESSURE) - brush->jitter = maxf(0.0f, painter->startjitter * pressure); + brush->jitter = max_ff(0.0f, painter->startjitter * pressure); if (brush->flag & BRUSH_SPACING_PRESSURE) - brush->spacing = maxf(1.0f, painter->startspacing * (1.5f - pressure)); + brush->spacing = max_ff(1.0f, painter->startspacing * (1.5f - pressure)); } void BKE_brush_jitter_pos(const Scene *scene, Brush *brush, const float pos[2], float jitterpos[2]) @@ -1158,7 +1158,7 @@ int BKE_brush_painter_paint(BrushPainter *painter, BrushFunc func, const float p /* compute brush spacing adapted to brush radius, spacing may depend * on pressure, so update it */ brush_pressure_apply(painter, brush, painter->lastpressure); - spacing = maxf(1.0f, radius) * brush->spacing * 0.01f; + spacing = max_ff(1.0f, radius) * brush->spacing * 0.01f; /* setup starting distance, direction vector and accumulated distance */ startdistance = painter->accumdistance; @@ -1176,7 +1176,7 @@ int BKE_brush_painter_paint(BrushPainter *painter, BrushFunc func, const float p t = step / len; press = (1.0f - t) * painter->lastpressure + t * pressure; brush_pressure_apply(painter, brush, press); - spacing = maxf(1.0f, radius) * brush->spacing * 0.01f; + spacing = max_ff(1.0f, radius) * brush->spacing * 0.01f; BKE_brush_jitter_pos(scene, brush, paintpos, finalpos); diff --git a/source/blender/blenkernel/intern/bullet.c b/source/blender/blenkernel/intern/bullet.c index 7defa7e1be3..088031e16a7 100644 --- a/source/blender/blenkernel/intern/bullet.c +++ b/source/blender/blenkernel/intern/bullet.c @@ -54,7 +54,7 @@ BulletSoftBody *bsbNew(void) bsb->viterations = 0; - bsb->piterations = 2; + bsb->piterations = 2; bsb->diterations = 0; bsb->citerations = 4; diff --git a/source/blender/blenkernel/intern/bvhutils.c b/source/blender/blenkernel/intern/bvhutils.c index 32ae6d04934..ad828a70dd8 100644 --- a/source/blender/blenkernel/intern/bvhutils.c +++ b/source/blender/blenkernel/intern/bvhutils.c @@ -358,8 +358,8 @@ float nearest_point_in_tri_surface(const float v0[3], const float v1[3], const f * BVH from meshs callbacks */ -// Callback to bvh tree nearest point. The tree must bust have been built using bvhtree_from_mesh_faces. -// userdata must be a BVHMeshCallbackUserdata built from the same mesh as the tree. +/* Callback to bvh tree nearest point. The tree must bust have been built using bvhtree_from_mesh_faces. + * userdata must be a BVHMeshCallbackUserdata built from the same mesh as the tree. */ static void mesh_faces_nearest_point(void *userdata, int index, const float co[3], BVHTreeNearest *nearest) { const BVHTreeFromMesh *data = (BVHTreeFromMesh *) userdata; @@ -395,8 +395,8 @@ static void mesh_faces_nearest_point(void *userdata, int index, const float co[3 } while (t2); } -// Callback to bvh tree raycast. The tree must bust have been built using bvhtree_from_mesh_faces. -// userdata must be a BVHMeshCallbackUserdata built from the same mesh as the tree. +/* Callback to bvh tree raycast. The tree must bust have been built using bvhtree_from_mesh_faces. + * userdata must be a BVHMeshCallbackUserdata built from the same mesh as the tree. */ static void mesh_faces_spherecast(void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit) { const BVHTreeFromMesh *data = (BVHTreeFromMesh *) userdata; @@ -435,8 +435,8 @@ static void mesh_faces_spherecast(void *userdata, int index, const BVHTreeRay *r } while (t2); } -// Callback to bvh tree nearest point. The tree must bust have been built using bvhtree_from_mesh_edges. -// userdata must be a BVHMeshCallbackUserdata built from the same mesh as the tree. +/* Callback to bvh tree nearest point. The tree must bust have been built using bvhtree_from_mesh_edges. + * userdata must be a BVHMeshCallbackUserdata built from the same mesh as the tree. */ static void mesh_edges_nearest_point(void *userdata, int index, const float co[3], BVHTreeNearest *nearest) { const BVHTreeFromMesh *data = (BVHTreeFromMesh *) userdata; @@ -463,12 +463,12 @@ static void mesh_edges_nearest_point(void *userdata, int index, const float co[3 /* * BVH builders */ -// Builds a bvh tree.. where nodes are the vertexs of the given mesh +/* Builds a bvh tree.. where nodes are the vertexs of the given mesh */ BVHTree *bvhtree_from_mesh_verts(BVHTreeFromMesh *data, DerivedMesh *mesh, float epsilon, int tree_type, int axis) { BVHTree *tree = bvhcache_find(&mesh->bvhCache, BVHTREE_FROM_VERTICES); - //Not in cache + /* Not in cache */ if (tree == NULL) { int i; int numVerts = mesh->getNumVerts(mesh); @@ -484,7 +484,7 @@ BVHTree *bvhtree_from_mesh_verts(BVHTreeFromMesh *data, DerivedMesh *mesh, float BLI_bvhtree_balance(tree); - //Save on cache for later use + /* Save on cache for later use */ // printf("BVHTree built and saved on cache\n"); bvhcache_insert(&mesh->bvhCache, tree, BVHTREE_FROM_VERTICES); } @@ -495,15 +495,15 @@ BVHTree *bvhtree_from_mesh_verts(BVHTreeFromMesh *data, DerivedMesh *mesh, float } - //Setup BVHTreeFromMesh + /* Setup BVHTreeFromMesh */ memset(data, 0, sizeof(*data)); data->tree = tree; if (data->tree) { data->cached = TRUE; - //a NULL nearest callback works fine - //remeber the min distance to point is the same as the min distance to BV of point + /* a NULL nearest callback works fine + * remeber the min distance to point is the same as the min distance to BV of point */ data->nearest_callback = NULL; data->raycast_callback = NULL; @@ -517,12 +517,12 @@ BVHTree *bvhtree_from_mesh_verts(BVHTreeFromMesh *data, DerivedMesh *mesh, float return data->tree; } -// Builds a bvh tree.. where nodes are the faces of the given mesh. +/* Builds a bvh tree.. where nodes are the faces of the given mesh. */ BVHTree *bvhtree_from_mesh_faces(BVHTreeFromMesh *data, DerivedMesh *mesh, float epsilon, int tree_type, int axis) { BVHTree *tree = bvhcache_find(&mesh->bvhCache, BVHTREE_FROM_FACES); - //Not in cache + /* Not in cache */ if (tree == NULL) { int i; int numFaces = mesh->getNumTessFaces(mesh); @@ -616,7 +616,7 @@ BVHTree *bvhtree_from_mesh_faces(BVHTreeFromMesh *data, DerivedMesh *mesh, float } BLI_bvhtree_balance(tree); - //Save on cache for later use + /* Save on cache for later use */ // printf("BVHTree built and saved on cache\n"); bvhcache_insert(&mesh->bvhCache, tree, BVHTREE_FROM_FACES); } @@ -627,7 +627,7 @@ BVHTree *bvhtree_from_mesh_faces(BVHTreeFromMesh *data, DerivedMesh *mesh, float } - //Setup BVHTreeFromMesh + /* Setup BVHTreeFromMesh */ memset(data, 0, sizeof(*data)); data->tree = tree; @@ -647,12 +647,12 @@ BVHTree *bvhtree_from_mesh_faces(BVHTreeFromMesh *data, DerivedMesh *mesh, float } -// Builds a bvh tree.. where nodes are the faces of the given mesh. +/* Builds a bvh tree.. where nodes are the faces of the given mesh. */ BVHTree *bvhtree_from_mesh_edges(BVHTreeFromMesh *data, DerivedMesh *mesh, float epsilon, int tree_type, int axis) { BVHTree *tree = bvhcache_find(&mesh->bvhCache, BVHTREE_FROM_EDGES); - //Not in cache + /* Not in cache */ if (tree == NULL) { int i; int numEdges = mesh->getNumEdges(mesh); @@ -672,7 +672,7 @@ BVHTree *bvhtree_from_mesh_edges(BVHTreeFromMesh *data, DerivedMesh *mesh, float } BLI_bvhtree_balance(tree); - //Save on cache for later use + /* Save on cache for later use */ // printf("BVHTree built and saved on cache\n"); bvhcache_insert(&mesh->bvhCache, tree, BVHTREE_FROM_EDGES); } @@ -683,7 +683,7 @@ BVHTree *bvhtree_from_mesh_edges(BVHTreeFromMesh *data, DerivedMesh *mesh, float } - //Setup BVHTreeFromMesh + /* Setup BVHTreeFromMesh */ memset(data, 0, sizeof(*data)); data->tree = tree; @@ -703,7 +703,7 @@ BVHTree *bvhtree_from_mesh_edges(BVHTreeFromMesh *data, DerivedMesh *mesh, float } -// Frees data allocated by a call to bvhtree_from_mesh_*. +/* Frees data allocated by a call to bvhtree_from_mesh_*. */ void free_bvhtree_from_mesh(struct BVHTreeFromMesh *data) { if (data->tree) { @@ -728,7 +728,7 @@ static void bvhcacheitem_set_if_match(void *_cached, void *_search) BVHCacheItem *search = (BVHCacheItem *)_search; if (search->type == cached->type) { - search->tree = cached->tree; + search->tree = cached->tree; } } diff --git a/source/blender/blenkernel/intern/camera.c b/source/blender/blenkernel/intern/camera.c index ed7ac0e1a32..9118baeae6f 100644 --- a/source/blender/blenkernel/intern/camera.c +++ b/source/blender/blenkernel/intern/camera.c @@ -151,7 +151,7 @@ float BKE_camera_object_dof_distance(Object *ob) Camera *cam = (Camera *)ob->data; if (ob->type != OB_CAMERA) return 0.0f; - if (cam->dof_ob) { + if (cam->dof_ob) { /* too simple, better to return the distance on the view axis only * return len_v3v3(ob->obmat[3], cam->dof_ob->obmat[3]); */ float mat[4][4], imat[4][4], obmat[4][4]; @@ -262,11 +262,12 @@ void BKE_camera_params_from_view3d(CameraParams *params, View3D *v3d, RegionView } else if (rv3d->persp == RV3D_ORTHO) { /* orthographic view */ + int sensor_size = BKE_camera_sensor_size(params->sensor_fit, params->sensor_x, params->sensor_y); params->clipend *= 0.5f; // otherwise too extreme low zbuffer quality params->clipsta = -params->clipend; params->is_ortho = TRUE; - params->ortho_scale = rv3d->dist; + params->ortho_scale = rv3d->dist * sensor_size / v3d->lens; params->zoom = 2.0f; } else { diff --git a/source/blender/blenkernel/intern/cdderivedmesh.c b/source/blender/blenkernel/intern/cdderivedmesh.c index e93c9373107..b7ad135fa72 100644 --- a/source/blender/blenkernel/intern/cdderivedmesh.c +++ b/source/blender/blenkernel/intern/cdderivedmesh.c @@ -272,6 +272,8 @@ static PBVH *cdDM_getPBVH(Object *ob, DerivedMesh *dm) cddm->pbvh = BLI_pbvh_new(); cddm->pbvh_draw = can_pbvh_draw(ob, dm); + pbvh_show_diffuse_color_set(cddm->pbvh, ob->sculpt->show_diffuse_color); + BKE_mesh_tessface_ensure(me); BLI_pbvh_build_mesh(cddm->pbvh, me->mface, me->mvert, @@ -382,7 +384,7 @@ static void cdDM_drawUVEdges(DerivedMesh *dm) for (i = 0; i < dm->numTessFaceData; i++, mf++) { if (!(mf->flag & ME_HIDE)) { draw = 1; - } + } else { draw = 0; } @@ -449,7 +451,7 @@ static void cdDM_drawEdges(DerivedMesh *dm, int drawLooseEdges, int drawAllEdges (drawLooseEdges || !(medge->flag & ME_LOOSEEDGE))) { draw = TRUE; - } + } else { draw = FALSE; } @@ -499,7 +501,7 @@ static void cdDM_drawLooseEdges(DerivedMesh *dm) for (i = 0; i < dm->numEdgeData; i++, medge++) { if (medge->flag & ME_LOOSEEDGE) { draw = 1; - } + } else { draw = 0; } @@ -566,7 +568,7 @@ static void cdDM_drawFacesSolid(DerivedMesh *dm, glShadeModel(shademodel = new_shademodel); gpuBegin(glmode = new_glmode); - } + } if (drawCurrentMat) { if (shademodel == GL_FLAT) { @@ -627,14 +629,29 @@ static void cdDM_drawFacesTex_common(DerivedMesh *dm, CDDerivedMesh *cddm = (CDDerivedMesh *) dm; MVert *mv = cddm->mvert; MFace *mf = DM_get_tessface_data_layer(dm, CD_MFACE); - MCol *realcol = dm->getTessFaceDataArray(dm, CD_TEXTURE_MCOL); float *nors = dm->getTessFaceDataArray(dm, CD_NORMAL); MTFace *tf = DM_get_tessface_data_layer(dm, CD_MTFACE); - int i, j, orig, *index = DM_get_tessface_data_layer(dm, CD_ORIGINDEX); - int startFace = 0 /*, lastFlag = 0xdeadbeef */ /* UNUSED */; - MCol *mcol = dm->getTessFaceDataArray(dm, CD_PREVIEW_MCOL); - if (!mcol) - mcol = dm->getTessFaceDataArray(dm, CD_MCOL); + MCol *mcol; + int i, orig; + int colType, startFace = 0; + + /* double lookup */ + const int *index_mf_to_mpoly = dm->getTessFaceDataArray(dm, CD_ORIGINDEX); + const int *index_mp_to_orig = dm->getPolyDataArray(dm, CD_ORIGINDEX); + if ((index_mf_to_mpoly && index_mp_to_orig) == FALSE) { + index_mf_to_mpoly = index_mp_to_orig = NULL; + } + + colType = CD_TEXTURE_MCOL; + mcol = dm->getTessFaceDataArray(dm, colType); + if (!mcol) { + colType = CD_PREVIEW_MCOL; + mcol = dm->getTessFaceDataArray(dm, colType); + } + if (!mcol) { + colType = CD_MCOL; + mcol = dm->getTessFaceDataArray(dm, colType); + } cdDM_update_normals_from_pbvh(dm); @@ -650,8 +667,8 @@ static void cdDM_drawFacesTex_common(DerivedMesh *dm, draw_option = drawParams(tf ? &tf[i] : NULL, (mcol != NULL), mf->mat_nr); } else { - if (index) { - orig = *index++; + if (index_mf_to_mpoly) { + orig = DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, i); if (orig == ORIGINDEX_NONE) { if (nors) nors += 3; continue; } if (drawParamsMapped) { draw_option = drawParamsMapped(userData, orig); } else { if (nors) nors += 3; continue; } @@ -714,42 +731,11 @@ static void cdDM_drawFacesTex_common(DerivedMesh *dm, gpuImmediateUnformat(); } else { /* use OpenGL VBOs or Vertex Arrays instead for better, faster rendering */ - MCol *col = realcol; - if (!col) - col = mcol; - GPU_vertex_setup(dm); GPU_normal_setup(dm); GPU_uv_setup(dm); - if (col != NULL) { -#if 0 - if (realcol && dm->drawObject->colType == CD_TEXTURE_MCOL) { - col = 0; - } - else if (mcol && dm->drawObject->colType == CD_MCOL) { - col = 0; - } - - if (col != 0) -#endif - { - unsigned char *colors = MEM_mallocN(dm->getNumTessFaces(dm) * 4 * 3 * sizeof(unsigned char), "cdDM_drawFacesTex_common"); - for (i = 0; i < dm->getNumTessFaces(dm); i++) { - for (j = 0; j < 4; j++) { - /* bgr -> rgb is intentional (and stupid), but how its stored internally */ - colors[i * 12 + j * 3] = col[i * 4 + j].b; - colors[i * 12 + j * 3 + 1] = col[i * 4 + j].g; - colors[i * 12 + j * 3 + 2] = col[i * 4 + j].r; - } - } - GPU_color3_upload(dm, colors); - MEM_freeN(colors); - if (realcol) - dm->drawObject->colType = CD_TEXTURE_MCOL; - else if (mcol) - dm->drawObject->colType = CD_MCOL; - } - GPU_color_setup(dm); + if (mcol) { + GPU_color_setup(dm, colType); } if (!GPU_buffer_legacy(dm)) { @@ -770,15 +756,18 @@ static void cdDM_drawFacesTex_common(DerivedMesh *dm, draw_option = drawParams(tf ? &tf[actualFace] : NULL, (mcol != NULL), mf[actualFace].mat_nr); } else { - if (index) { - orig = index[actualFace]; - if (orig == ORIGINDEX_NONE) continue; - if (drawParamsMapped) + if (index_mf_to_mpoly) { + orig = DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, actualFace); + if (orig == ORIGINDEX_NONE) { + continue; + } + if (drawParamsMapped) { draw_option = drawParamsMapped(userData, orig); + } } - else - if (drawParamsMapped) + else if (drawParamsMapped) { draw_option = drawParamsMapped(userData, actualFace); + } } /* flush buffer if current triangle isn't drawable or it's last triangle */ @@ -796,7 +785,7 @@ static void cdDM_drawFacesTex_common(DerivedMesh *dm, int count = (i - startFace + (draw_option != DM_DRAW_OPTION_SKIP ? 1 : 0)) * 3; if (count) { - if (col) + if (mcol && draw_option != DM_DRAW_OPTION_NO_MCOL) GPU_color_switch(1); else GPU_color_switch(0); @@ -833,12 +822,42 @@ static void cdDM_drawMappedFaces( CDDerivedMesh *cddm = (CDDerivedMesh *) dm; MVert *mv = cddm->mvert; MFace *mf = cddm->mface; - float *nors; - MCol *mc = NULL; + MCol *mcol; int *index; + int colType; + int i; + int orig; + int *index_mf_to_mpoly; + int *index_mp_to_orig; - int i, orig; + + /* double lookup */ + index_mf_to_mpoly = dm->getTessFaceDataArray(dm, CD_ORIGINDEX); + index_mp_to_orig = dm->getPolyDataArray(dm, CD_ORIGINDEX); + if ((index_mf_to_mpoly && index_mp_to_orig) == FALSE) { + index_mf_to_mpoly = index_mp_to_orig = NULL; + } + + + if (flag & DM_DRAW_USE_COLORS) { + colType = CD_ID_MCOL; + mcol = DM_get_tessface_data_layer(dm, colType); + + if (!mcol) { + colType = CD_PREVIEW_MCOL; + mcol = DM_get_tessface_data_layer(dm, colType); + + if (!mcol) { + colType = CD_MCOL; + mcol = DM_get_tessface_data_layer(dm, colType); + } + } + } + else { + mcol = NULL; + } + if (flag & DM_DRAW_USE_NORMALS) { nors = DM_get_tessface_data_layer(dm, CD_NORMAL); @@ -849,20 +868,10 @@ static void cdDM_drawMappedFaces( nors = NULL; } - if (flag & DM_DRAW_USE_COLORS) { - mc = DM_get_tessface_data_layer(dm, CD_ID_MCOL); - - if (!mc) { - mc = DM_get_tessface_data_layer(dm, CD_PREVIEW_MCOL); - - if (!mc) { - mc = DM_get_tessface_data_layer(dm, CD_MCOL); - } - } - } - + index = DM_get_tessface_data_layer(dm, CD_ORIGINDEX); + /* back-buffer always uses legacy since VBO's would need the * color array temporarily overwritten for drawing, then reset. */ if (GPU_buffer_legacy(dm) || G.f & G_BACKBUFSEL) { @@ -876,7 +885,7 @@ static void cdDM_drawMappedFaces( int drawSmooth = (flag & DM_DRAW_ALWAYS_SMOOTH) ? 1 : (mf->flag & ME_SMOOTH); DMDrawOption draw_option; - orig = (index == NULL) ? i : *index++; + orig = (index_mf_to_mpoly) ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, i) : i; if (orig == ORIGINDEX_NONE) draw_option = setMaterial(mf->mat_nr + 1, NULL); @@ -888,8 +897,8 @@ static void cdDM_drawMappedFaces( if (draw_option != DM_DRAW_OPTION_SKIP) { unsigned char *cp = NULL; - if (mc) - cp = (unsigned char *)&mc[i * 4]; + if (mcol) + cp = (unsigned char *)&mcol[i * 4]; gpuBegin(mf->v4 ? GL_QUADS : GL_TRIANGLES); @@ -951,8 +960,8 @@ static void cdDM_drawMappedFaces( GPU_normal_setup(dm); } - if (mc) { - GPU_color_setup(dm); + if (mcol) { + GPU_color_setup(dm, colType); } if (!GPU_buffer_legacy(dm)) { @@ -982,7 +991,7 @@ static void cdDM_drawMappedFaces( if (i != tottri - 1) next_actualFace = dm->drawObject->triangle_to_mface[i + 1]; - orig = (index == NULL) ? actualFace : index[actualFace]; + orig = (index_mf_to_mpoly) ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, actualFace) : actualFace; if (orig == ORIGINDEX_NONE) draw_option = setMaterial(mface->mat_nr + 1, NULL); @@ -1174,7 +1183,14 @@ static void cdDM_drawMappedFacesGLSL(DerivedMesh *dm, /* MTFace *tf = dm->getTessFaceDataArray(dm, CD_MTFACE); */ /* UNUSED */ float (*nors)[3] = dm->getTessFaceDataArray(dm, CD_NORMAL); int a, b, do_draw, matnr, new_matnr; - int orig, *index = dm->getTessFaceDataArray(dm, CD_ORIGINDEX); + int orig; + + /* double lookup */ + const int *index_mf_to_mpoly = dm->getTessFaceDataArray(dm, CD_ORIGINDEX); + const int *index_mp_to_orig = dm->getPolyDataArray(dm, CD_ORIGINDEX); + if ((index_mf_to_mpoly && index_mp_to_orig) == FALSE) { + index_mf_to_mpoly = index_mp_to_orig = NULL; + } cdDM_update_normals_from_pbvh(dm); @@ -1210,7 +1226,7 @@ static void cdDM_drawMappedFacesGLSL(DerivedMesh *dm, continue; } else if (setDrawOptions) { - orig = (index) ? index[a] : a; + orig = (index_mf_to_mpoly) ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, a) : a; if (orig == ORIGINDEX_NONE) { /* since the material is set by setMaterial(), faces with no @@ -1316,13 +1332,13 @@ static void cdDM_drawMappedFacesGLSL(DerivedMesh *dm, datatypes[numdata].size = 2; datatypes[numdata].type = GL_FLOAT; numdata++; - } + } for (b = 0; b < attribs.totmcol; b++) { datatypes[numdata].index = attribs.mcol[b].gl_index; datatypes[numdata].size = 4; datatypes[numdata].type = GL_UNSIGNED_BYTE; numdata++; - } + } if (attribs.tottang) { datatypes[numdata].index = attribs.tang.gl_index; datatypes[numdata].size = 4; @@ -1382,7 +1398,7 @@ static void cdDM_drawMappedFacesGLSL(DerivedMesh *dm, col[0] = cp->b; col[1] = cp->g; col[2] = cp->r; col[3] = cp->a; copy_v4_v4_char((char *)&varray[elementsize * curface * 3 + offset + elementsize * 2], (char *)col); offset += sizeof(unsigned char) * 4; - } + } if (attribs.tottang) { float *tang = attribs.tang.array[a * 4 + 0]; copy_v4_v4((float *)&varray[elementsize * curface * 3 + offset], tang); @@ -1423,7 +1439,7 @@ static void cdDM_drawMappedFacesGLSL(DerivedMesh *dm, col[0] = cp->b; col[1] = cp->g; col[2] = cp->r; col[3] = cp->a; copy_v4_v4_char((char *)&varray[elementsize * curface * 3 + offset + elementsize * 2], (char *)col); offset += sizeof(unsigned char) * 4; - } + } if (attribs.tottang) { float *tang = attribs.tang.array[a * 4 + 2]; copy_v4_v4((float *)&varray[elementsize * curface * 3 + offset], tang); @@ -1474,7 +1490,14 @@ static void cdDM_drawMappedFacesMat(DerivedMesh *dm, MFace *mf = cddm->mface; float (*nors)[3] = dm->getTessFaceDataArray(dm, CD_NORMAL); int a, matnr, new_matnr; - int orig, *index = dm->getTessFaceDataArray(dm, CD_ORIGINDEX); + int orig; + + /* double lookup */ + const int *index_mf_to_mpoly = dm->getTessFaceDataArray(dm, CD_ORIGINDEX); + const int *index_mp_to_orig = dm->getPolyDataArray(dm, CD_ORIGINDEX); + if ((index_mf_to_mpoly && index_mp_to_orig) == FALSE) { + index_mf_to_mpoly = index_mp_to_orig = NULL; + } cdDM_update_normals_from_pbvh(dm); @@ -1506,7 +1529,7 @@ static void cdDM_drawMappedFacesMat(DerivedMesh *dm, /* skipping faces */ if (setFace) { - orig = (index) ? index[a] : a; + orig = (index_mf_to_mpoly) ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, a) : a; if (orig != ORIGINDEX_NONE && !setFace(userData, orig)) continue; @@ -1674,11 +1697,6 @@ void CDDM_recalc_tessellation_ex(DerivedMesh *dm, const int do_face_nor_cpy) dm->numTessFaceData, dm->numLoopData, dm->numPolyData, do_face_nor_cpy); - if (!CustomData_get_layer(&dm->faceData, CD_ORIGINDEX)) { - int *polyIndex = CustomData_get_layer(&dm->faceData, CD_POLYINDEX); - CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_REFERENCE, polyIndex, dm->numTessFaceData); - } - cddm->mface = CustomData_get_layer(&dm->faceData, CD_MFACE); /* Tessellation recreated faceData, and the active layer indices need to get re-propagated @@ -1790,7 +1808,6 @@ DerivedMesh *CDDM_new(int numVerts, int numEdges, int numTessFaces, int numLoops CustomData_add_layer(&dm->vertData, CD_ORIGINDEX, CD_CALLOC, NULL, numVerts); CustomData_add_layer(&dm->edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges); CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_CALLOC, NULL, numTessFaces); - CustomData_add_layer(&dm->faceData, CD_POLYINDEX, CD_CALLOC, NULL, numTessFaces); CustomData_add_layer(&dm->polyData, CD_ORIGINDEX, CD_CALLOC, NULL, numPolys); CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL, numVerts); @@ -1814,7 +1831,6 @@ DerivedMesh *CDDM_from_mesh(Mesh *mesh, Object *UNUSED(ob)) DerivedMesh *dm = &cddm->dm; CustomDataMask mask = CD_MASK_MESH & (~CD_MASK_MDISPS); int alloctype; - int *polyindex = NULL; /* this does a referenced copy, with an exception for fluidsim */ @@ -1829,7 +1845,7 @@ DerivedMesh *CDDM_from_mesh(Mesh *mesh, Object *UNUSED(ob)) mesh->totvert); CustomData_merge(&mesh->edata, &dm->edgeData, mask, alloctype, mesh->totedge); - CustomData_merge(&mesh->fdata, &dm->faceData, mask | CD_MASK_POLYINDEX, alloctype, + CustomData_merge(&mesh->fdata, &dm->faceData, mask | CD_MASK_ORIGINDEX, alloctype, mesh->totface); CustomData_merge(&mesh->ldata, &dm->loopData, mask, alloctype, mesh->totloop); @@ -1842,17 +1858,12 @@ DerivedMesh *CDDM_from_mesh(Mesh *mesh, Object *UNUSED(ob)) cddm->mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY); cddm->mface = CustomData_get_layer(&dm->faceData, CD_MFACE); - /* commented since even when CD_POLYINDEX was first added this line fails + /* commented since even when CD_ORIGINDEX was first added this line fails * on the default cube, (after editmode toggle too) - campbell */ #if 0 - BLI_assert(CustomData_has_layer(&cddm->dm.faceData, CD_POLYINDEX)); + BLI_assert(CustomData_has_layer(&cddm->dm.faceData, CD_ORIGINDEX)); #endif - polyindex = CustomData_get_layer(&dm->faceData, CD_POLYINDEX); - if (!CustomData_has_layer(&cddm->dm.faceData, CD_ORIGINDEX)) { - CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_REFERENCE, polyindex, mesh->totface); - } - return dm; } @@ -1938,10 +1949,10 @@ DerivedMesh *CDDM_from_curve_displist(Object *ob, ListBase *dispbase, int **orco } static void loops_to_customdata_corners(BMesh *bm, CustomData *facedata, - int cdindex, BMLoop *l3[3], + int cdindex, const BMLoop *l3[3], int numCol, int numTex) { - BMLoop *l; + const BMLoop *l; BMFace *f = l3[0]->f; MTFace *texface; MTexPoly *texpoly; @@ -1984,13 +1995,16 @@ static void loops_to_customdata_corners(BMesh *bm, CustomData *facedata, } } -DerivedMesh *CDDM_from_BMEditMesh(BMEditMesh *em, Mesh *UNUSED(me), int use_mdisps, int use_tessface) +/* used for both editbmesh and bmesh */ +static DerivedMesh *cddm_from_bmesh_ex(struct BMesh *bm, int use_mdisps, + /* EditBMesh vars for use_tessface */ + int use_tessface, + const int em_tottri, const BMLoop *(*em_looptris)[3] + ) { - BMesh *bm = em->bm; - DerivedMesh *dm = CDDM_new(bm->totvert, bm->totedge, - use_tessface ? em->tottri : 0, + use_tessface ? em_tottri : 0, bm->totloop, bm->totface); @@ -2036,7 +2050,7 @@ DerivedMesh *CDDM_from_BMEditMesh(BMEditMesh *em, Mesh *UNUSED(me), int use_mdis /* add tessellation mface layers */ if (use_tessface) { - CustomData_from_bmeshpoly(&dm->faceData, &dm->polyData, &dm->loopData, em->tottri); + CustomData_from_bmeshpoly(&dm->faceData, &dm->polyData, &dm->loopData, em_tottri); } index = dm->getVertDataArray(dm, CD_ORIGINDEX); @@ -2094,15 +2108,13 @@ DerivedMesh *CDDM_from_BMEditMesh(BMEditMesh *em, Mesh *UNUSED(me), int use_mdis /* avoid this where possiblem, takes extra memory */ if (use_tessface) { - int *polyindex; BM_mesh_elem_index_ensure(bm, BM_FACE); - polyindex = dm->getTessFaceDataArray(dm, CD_POLYINDEX); index = dm->getTessFaceDataArray(dm, CD_ORIGINDEX); - for (i = 0; i < dm->numTessFaceData; i++, index++, polyindex++) { + for (i = 0; i < dm->numTessFaceData; i++, index++) { MFace *mf = &mface[i]; - BMLoop **l = em->looptris[i]; + const BMLoop **l = em_looptris[i]; efa = l[0]->f; mf->v1 = BM_elem_index_get(l[0]->v); @@ -2112,8 +2124,8 @@ DerivedMesh *CDDM_from_BMEditMesh(BMEditMesh *em, Mesh *UNUSED(me), int use_mdis mf->mat_nr = efa->mat_nr; mf->flag = BM_face_flag_to_mflag(efa); - *index = add_orig ? BM_elem_index_get(efa) : *(int *)CustomData_bmesh_get(&bm->pdata, efa->head.data, CD_ORIGINDEX); - *polyindex = BM_elem_index_get(efa); + /* map mfaces to polygons in the same cddm intentionally */ + *index = BM_elem_index_get(efa); loops_to_customdata_corners(bm, &dm->faceData, i, l, numCol, numTex); test_index_face(mf, &dm->faceData, i, 3); @@ -2152,6 +2164,20 @@ DerivedMesh *CDDM_from_BMEditMesh(BMEditMesh *em, Mesh *UNUSED(me), int use_mdis return dm; } +struct DerivedMesh *CDDM_from_bmesh(struct BMesh *bm, int use_mdisps) +{ + return cddm_from_bmesh_ex(bm, use_mdisps, FALSE, + /* these vars are for editmesh only */ + 0, NULL); +} + +DerivedMesh *CDDM_from_editbmesh(BMEditMesh *em, int use_mdisps, int use_tessface) +{ + return cddm_from_bmesh_ex(em->bm, use_mdisps, + /* editmesh */ + use_tessface, em->tottri, (const BMLoop *(*)[3])em->looptris); +} + static DerivedMesh *cddm_copy_ex(DerivedMesh *source, int faces_from_tessfaces) { CDDerivedMesh *cddm = cdDM_create("CDDM_copy cddm"); @@ -2166,6 +2192,7 @@ static DerivedMesh *cddm_copy_ex(DerivedMesh *source, int faces_from_tessfaces) source->getVertDataArray(source, CD_ORIGINDEX); source->getEdgeDataArray(source, CD_ORIGINDEX); source->getTessFaceDataArray(source, CD_ORIGINDEX); + source->getPolyDataArray(source, CD_ORIGINDEX); /* this initializes dm, and copies all non mvert/medge/mface layers */ DM_from_template(dm, source, DM_TYPE_CDDM, numVerts, numEdges, numTessFaces, @@ -2220,6 +2247,7 @@ DerivedMesh *CDDM_from_template(DerivedMesh *source, source->getVertDataArray(source, CD_ORIGINDEX); source->getEdgeDataArray(source, CD_ORIGINDEX); source->getTessFaceDataArray(source, CD_ORIGINDEX); + source->getPolyDataArray(source, CD_ORIGINDEX); /* this does a copy of all non mvert/medge/mface layers */ DM_from_template(dm, source, DM_TYPE_CDDM, numVerts, numEdges, numTessFaces, numLoops, numPolys); @@ -2237,8 +2265,6 @@ DerivedMesh *CDDM_from_template(DerivedMesh *source, CustomData_add_layer(&dm->edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges); if (!CustomData_get_layer(&dm->faceData, CD_ORIGINDEX)) CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_CALLOC, NULL, numTessFaces); - if (!CustomData_get_layer(&dm->faceData, CD_POLYINDEX)) - CustomData_add_layer(&dm->faceData, CD_POLYINDEX, CD_CALLOC, NULL, numTessFaces); cddm->mvert = CustomData_get_layer(&dm->vertData, CD_MVERT); cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE); @@ -2303,8 +2329,8 @@ void CDDM_calc_normals_mapping_ex(DerivedMesh *dm, const short only_face_normals CDDM_recalc_tessellation_ex(dm, FALSE); } else { - /* A tessellation already exists, it should always have a CD_POLYINDEX */ - BLI_assert(CustomData_has_layer(&dm->faceData, CD_POLYINDEX)); + /* A tessellation already exists, it should always have a CD_ORIGINDEX */ + BLI_assert(CustomData_has_layer(&dm->faceData, CD_ORIGINDEX)); CustomData_free_layers(&dm->faceData, CD_NORMAL, dm->numTessFaceData); } @@ -2314,7 +2340,7 @@ void CDDM_calc_normals_mapping_ex(DerivedMesh *dm, const short only_face_normals /* calculate face normals */ BKE_mesh_calc_normals_mapping_ex(cddm->mvert, dm->numVertData, CDDM_get_loops(dm), CDDM_get_polys(dm), dm->numLoopData, dm->numPolyData, NULL, cddm->mface, dm->numTessFaceData, - CustomData_get_layer(&dm->faceData, CD_POLYINDEX), face_nors, + CustomData_get_layer(&dm->faceData, CD_ORIGINDEX), face_nors, only_face_normals); CustomData_add_layer(&dm->faceData, CD_NORMAL, CD_ASSIGN, @@ -2488,7 +2514,7 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap) BLI_array_append(oldp, i); } - /*create new cddm*/ + /*create new cddm*/ cddm2 = (CDDerivedMesh *) CDDM_from_template((DerivedMesh *)cddm, BLI_array_count(mvert), BLI_array_count(medge), 0, BLI_array_count(mloop), BLI_array_count(mpoly)); /*update edge indices and copy customdata*/ @@ -2513,7 +2539,7 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap) CustomData_copy_data(&dm->loopData, &cddm2->dm.loopData, oldl[i], i, 1); } - /*copy vertex customdata*/ + /*copy vertex customdata*/ mv = mvert; for (i = 0; i < cddm2->dm.numVertData; i++, mv++) { CustomData_copy_data(&dm->vertData, &cddm2->dm.vertData, oldv[i], i, 1); @@ -2588,7 +2614,7 @@ void CDDM_calc_edges_tessface(DerivedMesh *dm) numEdges = BLI_edgehash_size(eh); /* write new edges into a temporary CustomData */ - memset(&edgeData, 0, sizeof(edgeData)); + CustomData_reset(&edgeData); CustomData_add_layer(&edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges); CustomData_add_layer(&edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges); @@ -2653,7 +2679,7 @@ void CDDM_calc_edges(DerivedMesh *dm) numEdges = BLI_edgehash_size(eh); /* write new edges into a temporary CustomData */ - memset(&edgeData, 0, sizeof(edgeData)); + CustomData_reset(&edgeData); CustomData_add_layer(&edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges); CustomData_add_layer(&edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges); diff --git a/source/blender/blenkernel/intern/cloth.c b/source/blender/blenkernel/intern/cloth.c index 4241756a109..f1d73c7777a 100644 --- a/source/blender/blenkernel/intern/cloth.c +++ b/source/blender/blenkernel/intern/cloth.c @@ -41,8 +41,6 @@ #include "BLI_utildefines.h" #include "BLI_linklist.h" -#include "BLF_translation.h" - #include "BKE_cdderivedmesh.h" #include "BKE_cloth.h" #include "BKE_effect.h" @@ -331,7 +329,7 @@ static int do_init_cloth(Object *ob, ClothModifierData *clmd, DerivedMesh *resul cache= clmd->point_cache; /* initialize simulation data if it didn't exist already */ - if (clmd->clothObject == NULL) { + if (clmd->clothObject == NULL) { if (!cloth_from_object(ob, clmd, result, framenr, 1)) { BKE_ptcache_invalidate(cache); return 0; @@ -773,11 +771,13 @@ static void cloth_apply_vgroup ( ClothModifierData *clmd, DerivedMesh *dm ) else verts->goal= 0.0f; + /* Reset vertex flags */ + verts->flags &= ~CLOTH_VERT_FLAG_PINNED; + verts->flags &= ~CLOTH_VERT_FLAG_NOSELFCOLL; + dvert = dm->getVertData ( dm, i, CD_MDEFORMVERT ); if ( dvert ) { - for ( j = 0; j < dvert->totweight; j++ ) { - verts->flags &= ~CLOTH_VERT_FLAG_PINNED; if (( dvert->dw[j].def_nr == (clmd->sim_parms->vgroup_mass-1)) && (clmd->sim_parms->flags & CLOTH_SIMSETTINGS_FLAG_GOAL )) { verts->goal = dvert->dw [j].weight; @@ -789,7 +789,7 @@ static void cloth_apply_vgroup ( ClothModifierData *clmd, DerivedMesh *dm ) */ verts->goal = powf(verts->goal, 4.0f); - if ( verts->goal >=SOFTGOALSNAP ) + if ( verts->goal >= SOFTGOALSNAP ) verts->flags |= CLOTH_VERT_FLAG_PINNED; } @@ -804,7 +804,6 @@ static void cloth_apply_vgroup ( ClothModifierData *clmd, DerivedMesh *dm ) } } - verts->flags &= ~CLOTH_VERT_FLAG_NOSELFCOLL; if (clmd->coll_parms->flags & CLOTH_COLLSETTINGS_FLAG_SELF ) { if ( dvert->dw[j].def_nr == (clmd->coll_parms->vgroup_selfcol-1)) { if (dvert->dw [j].weight > 0.0f) { @@ -823,7 +822,7 @@ static int cloth_from_object(Object *ob, ClothModifierData *clmd, DerivedMesh *d int i = 0; MVert *mvert = NULL; ClothVertex *verts = NULL; - float (*shapekey_rest)[3]= NULL; + float (*shapekey_rest)[3] = NULL; float tnull[3] = {0, 0, 0}; Cloth *cloth = NULL; float maxdist = 0; @@ -844,7 +843,7 @@ static int cloth_from_object(Object *ob, ClothModifierData *clmd, DerivedMesh *d clmd->clothObject->edgehash = NULL; } else if (!clmd->clothObject) { - modifier_setError(&(clmd->modifier), "%s", TIP_("Out of memory on allocating clmd->clothObject.")); + modifier_setError(&(clmd->modifier), "Out of memory on allocating clmd->clothObject"); return 0; } @@ -906,7 +905,7 @@ static int cloth_from_object(Object *ob, ClothModifierData *clmd, DerivedMesh *d if ( !cloth_build_springs ( clmd, dm ) ) { cloth_free_modifier ( clmd ); - modifier_setError(&(clmd->modifier), "%s", TIP_("Can't build springs.")); + modifier_setError(&(clmd->modifier), "Cannot build springs"); printf("cloth_free_modifier cloth_build_springs\n"); return 0; } @@ -948,7 +947,7 @@ static void cloth_from_mesh ( ClothModifierData *clmd, DerivedMesh *dm ) clmd->clothObject->verts = MEM_callocN ( sizeof ( ClothVertex ) * clmd->clothObject->numverts, "clothVertex" ); if ( clmd->clothObject->verts == NULL ) { cloth_free_modifier ( clmd ); - modifier_setError(&(clmd->modifier), "%s", TIP_("Out of memory on allocating clmd->clothObject->verts.")); + modifier_setError(&(clmd->modifier), "Out of memory on allocating clmd->clothObject->verts"); printf("cloth_free_modifier clmd->clothObject->verts\n"); return; } @@ -958,7 +957,7 @@ static void cloth_from_mesh ( ClothModifierData *clmd, DerivedMesh *dm ) clmd->clothObject->mfaces = MEM_callocN ( sizeof ( MFace ) * clmd->clothObject->numfaces, "clothMFaces" ); if ( clmd->clothObject->mfaces == NULL ) { cloth_free_modifier ( clmd ); - modifier_setError(&(clmd->modifier), "%s", TIP_("Out of memory on allocating clmd->clothObject->mfaces.")); + modifier_setError(&(clmd->modifier), "Out of memory on allocating clmd->clothObject->mfaces"); printf("cloth_free_modifier clmd->clothObject->mfaces\n"); return; } @@ -1049,29 +1048,25 @@ static void cloth_update_springs( ClothModifierData *clmd ) spring->stiffness = 0.0f; - if(spring->type == CLOTH_SPRING_TYPE_STRUCTURAL) - { + if (spring->type == CLOTH_SPRING_TYPE_STRUCTURAL) { spring->stiffness = (cloth->verts[spring->kl].struct_stiff + cloth->verts[spring->ij].struct_stiff) / 2.0f; } - else if(spring->type == CLOTH_SPRING_TYPE_SHEAR) - { + else if (spring->type == CLOTH_SPRING_TYPE_SHEAR) { spring->stiffness = (cloth->verts[spring->kl].shear_stiff + cloth->verts[spring->ij].shear_stiff) / 2.0f; } - else if(spring->type == CLOTH_SPRING_TYPE_BENDING) - { + else if (spring->type == CLOTH_SPRING_TYPE_BENDING) { spring->stiffness = (cloth->verts[spring->kl].bend_stiff + cloth->verts[spring->ij].bend_stiff) / 2.0f; } - else if(spring->type == CLOTH_SPRING_TYPE_GOAL) - { + else if (spring->type == CLOTH_SPRING_TYPE_GOAL) { /* 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)) && (cloth->verts[spring->ij].goal > ALMOST_ZERO)) + if ((!(cloth->verts[spring->ij].flags & CLOTH_VERT_FLAG_PINNED)) && + (cloth->verts[spring->ij].goal > ALMOST_ZERO)) { spring->flags &= ~CLOTH_SPRING_FLAG_DEACTIVATE; } - else - { + else { spring->flags |= CLOTH_SPRING_FLAG_DEACTIVATE; } } diff --git a/source/blender/blenkernel/intern/collision.c b/source/blender/blenkernel/intern/collision.c index 6631afcddaf..b488e683947 100644 --- a/source/blender/blenkernel/intern/collision.c +++ b/source/blender/blenkernel/intern/collision.c @@ -198,6 +198,9 @@ static void collision_compute_barycentric ( float pv[3], float p1[3], float p2[3 w3[0] = 1.0f - w1[0] - w2[0]; } +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdouble-promotion" + DO_INLINE void collision_interpolateOnTriangle ( float to[3], float v1[3], float v2[3], float v3[3], double w1, double w2, double w3 ) { zero_v3(to); @@ -272,7 +275,7 @@ static int cloth_collision_response_static ( ClothModifierData *clmd, CollisionM /* 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" */ - magtangent = minf(clmd->coll_parms->friction * 0.01f * magrelVel, sqrtf(dot_v3v3(vrel_t_pre, vrel_t_pre))); + magtangent = min_ff(clmd->coll_parms->friction * 0.01f * magrelVel, sqrtf(dot_v3v3(vrel_t_pre, vrel_t_pre))); /* Apply friction impulse. */ if ( magtangent > ALMOST_ZERO ) { @@ -312,8 +315,8 @@ static int cloth_collision_response_static ( ClothModifierData *clmd, CollisionM /* stay on the safe side and clamp repulse */ if ( impulse > ALMOST_ZERO ) - repulse = MIN2 ( repulse, 5.0*impulse ); - repulse = MAX2 ( impulse, repulse ); + repulse = min_ff( repulse, 5.0*impulse ); + repulse = max_ff(impulse, repulse); impulse = repulse / ( 1.0f + w1*w1 + w2*w2 + w3*w3 ); /* original 2.0 / 0.25 */ VECADDMUL ( i1, collpair->normal, impulse ); @@ -331,12 +334,12 @@ static int cloth_collision_response_static ( ClothModifierData *clmd, CollisionM * We don't use dt!! */ float spf = (float)clmd->sim_parms->stepsPerFrame / clmd->sim_parms->timescale; - float d = clmd->coll_parms->epsilon*8.0f/9.0f + epsilon2*8.0f/9.0f - collpair->distance; + float d = clmd->coll_parms->epsilon*8.0f/9.0f + epsilon2*8.0f/9.0f - (float)collpair->distance; if ( d > ALMOST_ZERO) { /* stay on the safe side and clamp repulse */ float repulse = d*1.0f/spf; - float impulse = repulse / ( 3.0 * ( 1.0f + w1*w1 + w2*w2 + w3*w3 )); /* original 2.0 / 0.25 */ + float impulse = repulse / ( 3.0f * ( 1.0f + w1*w1 + w2*w2 + w3*w3 )); /* original 2.0 / 0.25 */ VECADDMUL ( i1, collpair->normal, impulse ); VECADDMUL ( i2, collpair->normal, impulse ); @@ -368,6 +371,8 @@ static int cloth_collision_response_static ( ClothModifierData *clmd, CollisionM return result; } +#pragma GCC diagnostic pop + //Determines collisions on overlap, collisions are written to collpair[i] and collision+number_collision_found is returned static CollPair* cloth_collision(ModifierData *md1, ModifierData *md2, BVHTreeOverlap *overlap, CollPair *collpair, float UNUSED(dt)) @@ -458,7 +463,8 @@ static CollPair* cloth_collision(ModifierData *md1, ModifierData *md2, distance = 2.0 * (double)( epsilon1 + epsilon2 + ALMOST_ZERO ); #endif - if (distance <= (epsilon1 + epsilon2 + ALMOST_ZERO)) { + // distance -1 means no collision result + if (distance != -1.0 && (distance <= (double)(epsilon1 + epsilon2 + ALMOST_ZERO))) { normalize_v3_v3(collpair->normal, collpair->vector); collpair->distance = distance; @@ -514,7 +520,7 @@ static void add_collision_object(Object ***objs, unsigned int *numobj, unsigned if (((modifier_type == eModifierType_Collision) && ob->pd && ob->pd->deflect) || (modifier_type != eModifierType_Collision)) cmd= (CollisionModifierData *)modifiers_findByType(ob, modifier_type); - if (cmd) { + if (cmd) { /* extend array */ if (*numobj >= *maxobj) { *maxobj *= 2; @@ -533,7 +539,7 @@ static void add_collision_object(Object ***objs, unsigned int *numobj, unsigned /* add objects */ for (go= group->gobject.first; go; go= go->next) add_collision_object(objs, numobj, maxobj, go->ob, self, level+1, modifier_type); - } + } } // return all collision objects in scene @@ -579,7 +585,7 @@ static void add_collider_cache_object(ListBase **objs, Object *ob, Object *self, if (ob->pd && ob->pd->deflect) cmd =(CollisionModifierData *)modifiers_findByType(ob, eModifierType_Collision); - if (cmd && cmd->bvhtree) { + if (cmd && cmd->bvhtree) { if (*objs == NULL) *objs = MEM_callocN(sizeof(ListBase), "ColliderCache array"); @@ -737,8 +743,7 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData * clmd, float step, flo collision_move_object ( collmd, step + dt, step ); } - do - { + do { CollPair **collisions, **collisions_index; ret2 = 0; @@ -869,7 +874,7 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData * clmd, float step, flo VECADD ( verts[i].tx, verts[i].tx, temp ); } else { - mul_v3_fl(temp, correction * -0.5); + mul_v3_fl(temp, correction * -0.5f); VECADD ( verts[j].tx, verts[j].tx, temp ); sub_v3_v3v3(verts[i].tx, verts[i].tx, temp); diff --git a/source/blender/blenkernel/intern/colortools.c b/source/blender/blenkernel/intern/colortools.c index 1bd5786debd..75276adf518 100644 --- a/source/blender/blenkernel/intern/colortools.c +++ b/source/blender/blenkernel/intern/colortools.c @@ -65,10 +65,10 @@ void curvemapping_set_defaults(CurveMapping *cumap, int tot, float minx, float m cumap->flag = CUMA_DO_CLIP; if (tot == 4) cumap->cur = 3; /* rhms, hack for 'col' curve? */ - clipminx = minf(minx, maxx); - clipminy = minf(miny, maxy); - clipmaxx = maxf(minx, maxx); - clipmaxy = maxf(miny, maxy); + clipminx = min_ff(minx, maxx); + clipminy = min_ff(miny, maxy); + clipmaxx = max_ff(minx, maxx); + clipmaxy = max_ff(miny, maxy); BLI_rctf_init(&cumap->curr, clipminx, clipmaxx, clipminy, clipmaxy); cumap->clipr = cumap->curr; @@ -85,7 +85,7 @@ void curvemapping_set_defaults(CurveMapping *cumap, int tot, float minx, float m cumap->cm[a].curve[0].y = miny; cumap->cm[a].curve[1].x = maxx; cumap->cm[a].curve[1].y = maxy; - } + } cumap->changed_timestamp = 0; } @@ -160,7 +160,7 @@ void curvemapping_set_black_white_ex(const float black[3], const float white[3], int a; for (a = 0; a < 3; a++) { - const float delta = maxf(white[a] - black[a], 1e-5f); + const float delta = max_ff(white[a] - black[a], 1e-5f); r_bwmul[a] = 1.0f / delta; } } @@ -182,14 +182,14 @@ void curvemapping_set_black_white(CurveMapping *cumap, const float black[3], con /* ********** NOTE: requires curvemapping_changed() call after ******** */ /* remove specified point */ -void curvemap_remove_point(CurveMap *cuma, CurveMapPoint *point) +int curvemap_remove_point(CurveMap *cuma, CurveMapPoint *point) { CurveMapPoint *cmp; int a, b, removed = 0; /* must have 2 points minimum */ if (cuma->totpoint <= 2) - return; + return FALSE; cmp = MEM_mallocN((cuma->totpoint) * sizeof(CurveMapPoint), "curve points"); @@ -205,6 +205,7 @@ void curvemap_remove_point(CurveMap *cuma, CurveMapPoint *point) MEM_freeN(cuma->curve); cuma->curve = cmp; cuma->totpoint -= removed; + return (removed != 0); } /* removes with flag set */ @@ -498,8 +499,8 @@ static void curvemap_make_table(CurveMap *cuma, const rctf *clipr) bezt = MEM_callocN(cuma->totpoint * sizeof(BezTriple), "beztarr"); for (a = 0; a < cuma->totpoint; a++) { - cuma->mintable = minf(cuma->mintable, cmp[a].x); - cuma->maxtable = maxf(cuma->maxtable, cmp[a].x); + cuma->mintable = min_ff(cuma->mintable, cmp[a].x); + cuma->maxtable = max_ff(cuma->maxtable, cmp[a].x); bezt[a].vec[1][0] = cmp[a].x; bezt[a].vec[1][1] = cmp[a].y; if (cmp[a].flag & CUMA_VECTOR) @@ -555,7 +556,7 @@ static void curvemap_make_table(CurveMap *cuma, const rctf *clipr) sub_v3_v3v3(bezt[a].vec[2], bezt[a].vec[1], vec); } } - } + } /* make the bezier curve */ if (cuma->table) MEM_freeN(cuma->table); @@ -690,13 +691,13 @@ void curvemapping_changed(CurveMapping *cumap, int rem_doubles) for (a = 0; a < cuma->totpoint; a++) { if (cmp[a].flag & CUMA_SELECT) { if (cmp[a].x < clipr->xmin) - dx = minf(dx, cmp[a].x - clipr->xmin); + dx = min_ff(dx, cmp[a].x - clipr->xmin); else if (cmp[a].x > clipr->xmax) - dx = maxf(dx, cmp[a].x - clipr->xmax); + dx = max_ff(dx, cmp[a].x - clipr->xmax); if (cmp[a].y < clipr->ymin) - dy = minf(dy, cmp[a].y - clipr->ymin); + dy = min_ff(dy, cmp[a].y - clipr->ymin); else if (cmp[a].y > clipr->ymax) - dy = maxf(dy, cmp[a].y - clipr->ymax); + dy = max_ff(dy, cmp[a].y - clipr->ymax); } } for (a = 0; a < cuma->totpoint; a++) { @@ -731,7 +732,7 @@ void curvemapping_changed(CurveMapping *cumap, int rem_doubles) } if (a != cuma->totpoint - 1) curvemap_remove(cuma, 2); - } + } curvemap_make_table(cuma, clipr); } @@ -835,64 +836,6 @@ void curvemapping_evaluate_premulRGB(const CurveMapping *cumap, unsigned char ve vecout_byte[2] = FTOCHAR(vecout[2]); } - -/* only used for image editor curves */ -void curvemapping_do_ibuf(CurveMapping *cumap, ImBuf *ibuf) -{ - ImBuf *tmpbuf; - int pixel; - float *pix_in; - float col[3]; - int stride = 4; - float *pix_out; - - if (ibuf == NULL) - return; - if (ibuf->rect_float == NULL) - IMB_float_from_rect(ibuf); - else if (ibuf->rect == NULL) - imb_addrectImBuf(ibuf); - - if (!ibuf->rect || !ibuf->rect_float) - return; - - /* work on a temp buffer, so can color manage afterwards. - * No worse off memory wise than comp nodes */ - tmpbuf = IMB_dupImBuf(ibuf); - - curvemapping_premultiply(cumap, 0); - - pix_in = ibuf->rect_float; - pix_out = tmpbuf->rect_float; - - if (ibuf->channels) - stride = ibuf->channels; - - for (pixel = ibuf->x * ibuf->y; pixel > 0; pixel--, pix_in += stride, pix_out += stride) { - if (stride < 3) { - col[0] = curvemap_evaluateF(cumap->cm, *pix_in); - - pix_out[1] = pix_out[2] = pix_out[3] = pix_out[0] = col[0]; - } - else { - curvemapping_evaluate_premulRGBF(cumap, col, pix_in); - pix_out[0] = col[0]; - pix_out[1] = col[1]; - pix_out[2] = col[2]; - if (stride > 3) - pix_out[3] = pix_in[3]; - else - pix_out[3] = 1.f; - } - } - - IMB_rect_from_float(tmpbuf); - SWAP(unsigned int *, tmpbuf->rect, ibuf->rect); - IMB_freeImBuf(tmpbuf); - - curvemapping_premultiply(cumap, 1); -} - int curvemapping_RGBA_does_something(const CurveMapping *cumap) { int a; diff --git a/source/blender/blenkernel/intern/constraint.c b/source/blender/blenkernel/intern/constraint.c index e3f7ae1b1c7..e300b5e0f19 100644 --- a/source/blender/blenkernel/intern/constraint.c +++ b/source/blender/blenkernel/intern/constraint.c @@ -221,51 +221,6 @@ void constraints_clear_evalob(bConstraintOb *cob) /* -------------- Space-Conversion API -------------- */ -#if 0 /* XXX Old code, does the same as one in armature.c, will remove it later. */ -static void constraint_pchan_diff_mat(bPoseChannel *pchan, float diff_mat[4][4]) -{ - if (pchan->parent) { - float offs_bone[4][4]; - - /* construct offs_bone the same way it is done in armature.c */ - copy_m4_m3(offs_bone, pchan->bone->bone_mat); - copy_v3_v3(offs_bone[3], pchan->bone->head); - offs_bone[3][1] += pchan->bone->parent->length; - - if (pchan->bone->flag & BONE_HINGE) { - /* pose_mat = par_pose-space_location * chan_mat */ - float tmat[4][4]; - - /* the rotation of the parent restposition */ - copy_m4_m4(tmat, pchan->bone->parent->arm_mat); - - /* the location of actual parent transform */ - copy_v3_v3(tmat[3], offs_bone[3]); - zero_v3(offs_bone[3]); - mul_m4_v3(pchan->parent->pose_mat, tmat[3]); - - mult_m4_m4m4(diff_mat, tmat, offs_bone); - } - else { - /* pose_mat = par_pose_mat * bone_mat * chan_mat */ - if (pchan->bone->flag & BONE_NO_SCALE) { - float tmat[4][4]; - copy_m4_m4(tmat, pchan->parent->pose_mat); - normalize_m4(tmat); - mult_m4_m4m4(diff_mat, tmat, offs_bone); - } - else { - mult_m4_m4m4(diff_mat, pchan->parent->pose_mat, offs_bone); - } - } - } - else { - /* pose_mat = chan_mat * arm_mat */ - copy_m4_m4(diff_mat, pchan->bone->arm_mat); - } -} -#endif - /* This function is responsible for the correct transformations/conversions * of a matrix from one space to another for constraint evaluation. * For now, this is only implemented for Objects and PoseChannels. @@ -307,18 +262,6 @@ void constraint_mat_convertspace(Object *ob, bPoseChannel *pchan, float mat[][4] else if (to == CONSTRAINT_SPACE_LOCAL) { if (pchan->bone) { BKE_armature_mat_pose_to_bone(pchan, mat, mat); -#if 0 /* XXX Old code, will remove it later. */ - constraint_pchan_diff_mat(pchan, diff_mat); - - invert_m4_m4(imat, diff_mat); - mult_m4_m4m4(mat, imat, mat); - - /* override with local location */ - if ((pchan->parent) && (pchan->bone->flag & BONE_NO_LOCAL_LOCATION)) { - BKE_armature_mat_pose_to_bone_ex(ob, pchan, pchan->pose_mat, tempmat); - copy_v3_v3(mat[3], tempmat[3]); - } -#endif } } /* pose to local with parent */ @@ -336,24 +279,19 @@ void constraint_mat_convertspace(Object *ob, bPoseChannel *pchan, float mat[][4] if (pchan->bone) { /* we need the posespace_matrix = local_matrix + (parent_posespace_matrix + restpos) */ BKE_armature_mat_bone_to_pose(pchan, mat, mat); -#if 0 - constraint_pchan_diff_mat(pchan, diff_mat); - - mult_m4_m4m4(mat, diff_mat, mat); -#endif } /* use pose-space as stepping stone for other spaces */ if (ELEM(to, CONSTRAINT_SPACE_WORLD, CONSTRAINT_SPACE_PARLOCAL)) { /* call self with slightly different values */ constraint_mat_convertspace(ob, pchan, mat, CONSTRAINT_SPACE_POSE, to); - } + } } break; case CONSTRAINT_SPACE_PARLOCAL: /* -------------- FROM LOCAL WITH PARENT ---------- */ { /* local + parent to pose */ - if (pchan->bone) { + if (pchan->bone) { copy_m4_m4(diff_mat, pchan->bone->arm_mat); mult_m4_m4m4(mat, mat, diff_mat); } @@ -432,7 +370,7 @@ static void contarget_get_mesh_mat(Object *ob, const char *substring, float mat[ /* get DerivedMesh */ if (em) { /* target is in editmode, so get a special derived mesh */ - dm = CDDM_from_BMEditMesh(em, ob->data, FALSE, FALSE); + dm = CDDM_from_editbmesh(em, FALSE, FALSE); freeDM = 1; } else { @@ -604,15 +542,15 @@ static void constraint_target_to_mat4(Object *ob, const char *substring, float m float tempmat[4][4], loc[3]; /* interpolate along length of bone */ - interp_v3_v3v3(loc, pchan->pose_head, pchan->pose_tail, headtail); + interp_v3_v3v3(loc, pchan->pose_head, pchan->pose_tail, headtail); /* use interpolated distance for subtarget */ - copy_m4_m4(tempmat, pchan->pose_mat); + copy_m4_m4(tempmat, pchan->pose_mat); copy_v3_v3(tempmat[3], loc); mult_m4_m4m4(mat, ob->obmat, tempmat); } - } + } else copy_m4_m4(mat, ob->obmat); @@ -976,11 +914,11 @@ static void vectomat(const float vec[3], const float target_up[3], short axis, s else negate_v3(n); /* n specifies the transformation of the track axis */ - if (flags & TARGET_Z_UP) { + if (flags & TARGET_Z_UP) { /* target Z axis is the global up axis */ copy_v3_v3(u, target_up); } - else { + else { /* world Z axis is the global up axis */ u[0] = 0; u[1] = 0; @@ -1034,7 +972,7 @@ static void trackto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *tar /* Get size property, since ob->size is only the object's own relative size, not its global one */ mat4_to_size(size, cob->matrix); - /* Clear the object's rotation */ + /* Clear the object's rotation */ cob->matrix[0][0] = size[0]; cob->matrix[0][1] = 0; cob->matrix[0][2] = 0; @@ -1468,7 +1406,7 @@ static void sizelimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *U if (data->flag & LIMIT_XMIN) { if (size[0] < data->xmin) - size[0] = data->xmin; + size[0] = data->xmin; } if (data->flag & LIMIT_XMAX) { if (size[0] > data->xmax) @@ -1476,7 +1414,7 @@ static void sizelimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *U } if (data->flag & LIMIT_YMIN) { if (size[1] < data->ymin) - size[1] = data->ymin; + size[1] = data->ymin; } if (data->flag & LIMIT_YMAX) { if (size[1] > data->ymax) @@ -1484,7 +1422,7 @@ static void sizelimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *U } if (data->flag & LIMIT_ZMIN) { if (size[2] < data->zmin) - size[2] = data->zmin; + size[2] = data->zmin; } if (data->flag & LIMIT_ZMAX) { if (size[2] > data->zmax) @@ -2002,7 +1940,7 @@ static void pycon_get_tarmat(bConstraint *con, bConstraintOb *cob, bConstraintTa /* this check is to make sure curve objects get updated on file load correctly.*/ if (cu->path == NULL || cu->path->data == NULL) /* only happens on reload file, but violates depsgraph still... fix! */ - BKE_displist_make_curveTypes(cob->scene, ct->tar, 0); + BKE_displist_make_curveTypes(cob->scene, ct->tar, 0); } /* firstly calculate the matrix the normal way, then let the py-function override @@ -2764,7 +2702,7 @@ static void stretchto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t default: /* should not happen, but in case*/ return; } /* switch (data->volmode) */ - + /* Clear the object's rotation and scale */ cob->matrix[0][0] = size[0] * scale[0]; cob->matrix[0][1] = 0; @@ -2787,10 +2725,10 @@ static void stretchto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t /* othogonal to "new Y" "old X! plane */ cross_v3_v3v3(orth, vec, xx); normalize_v3(orth); - + /* new Z*/ copy_v3_v3(totmat[2], orth); - + /* we decided to keep X plane*/ cross_v3_v3v3(xx, orth, vec); normalize_v3_v3(totmat[0], xx); @@ -2800,16 +2738,16 @@ static void stretchto_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t /* othogonal to "new Y" "old Z! plane */ cross_v3_v3v3(orth, vec, zz); normalize_v3(orth); - + /* new X */ negate_v3_v3(totmat[0], orth); - + /* we decided to keep Z */ cross_v3_v3v3(zz, orth, vec); normalize_v3_v3(totmat[2], zz); break; } /* switch (data->plane) */ - + mul_m4_m3m4(cob->matrix, totmat, cob->matrix); } } @@ -2937,7 +2875,7 @@ static void minmax_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targ if (data->flag & MINMAX_STICKY) { if (data->flag & MINMAX_STUCK) { copy_v3_v3(obmat[3], data->cache); - } + } else { copy_v3_v3(data->cache, obmat[3]); data->flag |= MINMAX_STUCK; @@ -2947,11 +2885,11 @@ static void minmax_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *targ /* get out of localspace */ mult_m4_m4m4(tmat, ct->matrix, obmat); copy_m4_m4(cob->matrix, tmat); - } - else { + } + else { copy_v3_v3(cob->matrix[3], obmat[3]); } - } + } else { data->flag &= ~MINMAX_STUCK; } @@ -3291,7 +3229,7 @@ static void transform_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t /* extract components of owner's matrix */ copy_v3_v3(loc, cob->matrix[3]); mat4_to_eulO(eul, cob->rotOrder, cob->matrix); - mat4_to_size(size, cob->matrix); + mat4_to_size(size, cob->matrix); /* determine where in range current transforms lie */ if (data->expo) { @@ -3615,7 +3553,7 @@ static void damptrack_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t cross_v3_v3v3(raxis, obvec, tarvec); rangle = dot_v3v3(obvec, tarvec); - rangle = acos(maxf(-1.0f, minf(1.0f, rangle))); + rangle = acos(max_ff(-1.0f, min_ff(1.0f, rangle))); /* construct rotation matrix from the axis-angle rotation found above * - this call takes care to make sure that the axis provided is a unit vector first @@ -4663,7 +4601,7 @@ short proxylocked_constraints_owner(Object *ob, bPoseChannel *pchan) else { /* FIXME: constraints on object-level are not handled well yet */ return 1; - } + } } return 0; @@ -4703,7 +4641,7 @@ void get_constraint_target_matrix(struct Scene *scene, bConstraint *con, int n, unit_m4(cob->matrix); unit_m4(cob->startmat); } - } + } break; case CONSTRAINT_OBTYPE_BONE: /* this may occur in some cases */ { @@ -4839,7 +4777,7 @@ void solve_constraints(ListBase *conlist, bConstraintOb *cob, float ctime) * 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 */ + /* Note: all kind of stuff here before (caused trouble), much easier to just interpolate, or did I miss something? -jahka (r.32105) */ if (enf < 1.0f) { float solution[4][4]; copy_m4_m4(solution, cob->matrix); diff --git a/source/blender/blenkernel/intern/context.c b/source/blender/blenkernel/intern/context.c index be81c70f261..719ae7357b4 100644 --- a/source/blender/blenkernel/intern/context.c +++ b/source/blender/blenkernel/intern/context.c @@ -234,9 +234,8 @@ struct bContextDataResult { static void *ctx_wm_python_context_get(const bContext *C, const char *member, void *fall_through) { #ifdef WITH_PYTHON - bContextDataResult result; - - if (C && CTX_py_dict_get(C)) { + if (UNLIKELY(C && CTX_py_dict_get(C))) { + bContextDataResult result; memset(&result, 0, sizeof(bContextDataResult)); BPY_context_member_get((bContext *)C, member, &result); if (result.ptr.data) diff --git a/source/blender/blenkernel/intern/curve.c b/source/blender/blenkernel/intern/curve.c index 0bda3b266b8..f2cd695d64a 100644 --- a/source/blender/blenkernel/intern/curve.c +++ b/source/blender/blenkernel/intern/curve.c @@ -820,8 +820,8 @@ static void basisNurb(float t, short order, short pnts, float *knots, float *bas /* this is for float inaccuracy */ if (t < knots[0]) t = knots[0]; - else - if (t > knots[opp2]) t = knots[opp2]; + else if (t > knots[opp2]) + t = knots[opp2]; /* this part is order '1' */ o2 = order + 1; @@ -1050,10 +1050,13 @@ void BKE_nurb_makeFaces(Nurb *nu, float *coord_array, int rowstride, int resolu, MEM_freeN(jend); } +/** + * \param coord_array Has to be 3 * 4 * pntsu * resolu in size and zero-ed + * \param tilt_array set when non-NULL + * \param radius_array set when non-NULL + */ void BKE_nurb_makeCurve(Nurb *nu, float *coord_array, float *tilt_array, float *radius_array, float *weight_array, int resolu, int stride) -/* coord_array has to be 3*4*pntsu*resolu in size and zero-ed - * tilt_array and radius_array will be written to if valid */ { BPoint *bp; float u, ustart, uend, ustep, sumdiv; @@ -1114,12 +1117,12 @@ void BKE_nurb_makeCurve(Nurb *nu, float *coord_array, float *tilt_array, float * sumdiv += *fp; } if (sumdiv != 0.0f) if (sumdiv < 0.999f || sumdiv > 1.001f) { - /* is normalizing needed? */ - fp = sum; - for (i = istart; i <= iend; i++, fp++) { - *fp /= sumdiv; - } + /* is normalizing needed? */ + fp = sum; + for (i = istart; i <= iend; i++, fp++) { + *fp /= sumdiv; } + } /* one! (1.0) real point */ fp = sum; @@ -1476,7 +1479,7 @@ void BKE_curve_bevel_make(Scene *scene, Object *ob, ListBase *disp, int forRende } } else if (cu->ext1 == 0.0f && cu->ext2 == 0.0f) { - ; + /* pass */ } else if (cu->ext2 == 0.0f) { dl = MEM_callocN(sizeof(DispList), "makebevelcurve2"); @@ -1945,7 +1948,7 @@ static void bevel_list_smooth(BevList *bl, int smooth_iter) if (bl->poly == -1) { /* check its not cyclic */ /* skip the first point */ - /* bevp0= bevp1; */ + /* bevp0 = bevp1; */ bevp1 = bevp2; bevp2++; nr--; @@ -1974,7 +1977,7 @@ static void bevel_list_smooth(BevList *bl, int smooth_iter) interp_qt_qtqt(bevp1->quat, bevp1->quat, q, 0.5); normalize_qt(bevp1->quat); - /* bevp0= bevp1; */ /* UNUSED */ + /* bevp0 = bevp1; */ /* UNUSED */ bevp1 = bevp2; bevp2++; } @@ -2109,7 +2112,7 @@ static void make_bevel_list_3D_tangent(BevList *bl) BevPoint *bevp2, *bevp1, *bevp0; /* standard for all make_bevel_list_3D_* funcs */ int nr; - float bevp0_tan[3], cross_tmp[3]; + float bevp0_tan[3]; bevel_list_calc_bisect(bl); if (bl->poly == -1) /* check its not cyclic */ @@ -2123,6 +2126,7 @@ static void make_bevel_list_3D_tangent(BevList *bl) nr = bl->nr; while (nr--) { + float cross_tmp[3]; cross_v3_v3v3(cross_tmp, bevp1->tan, bevp1->dir); cross_v3_v3v3(bevp1->tan, cross_tmp, bevp1->dir); normalize_v3(bevp1->tan); @@ -2150,7 +2154,7 @@ static void make_bevel_list_3D_tangent(BevList *bl) normalize_v3(cross_tmp); tri_to_quat(bevp1->quat, zero, cross_tmp, bevp1->tan); /* XXX - could be faster */ - /* bevp0= bevp1; */ /* UNUSED */ + /* bevp0 = bevp1; */ /* UNUSED */ bevp1 = bevp2; bevp2++; } @@ -2477,8 +2481,8 @@ void BKE_curve_bevelList_make(Object *ob) 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]); + 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) sd->dir = 1; diff --git a/source/blender/blenkernel/intern/customdata.c b/source/blender/blenkernel/intern/customdata.c index de55751f2ec..93c776ae30e 100644 --- a/source/blender/blenkernel/intern/customdata.c +++ b/source/blender/blenkernel/intern/customdata.c @@ -65,11 +65,20 @@ /* number of layers to add when growing a CustomData object */ #define CUSTOMDATA_GROW 5 +/* ensure typemap size is ok */ +BLI_STATIC_ASSERT(sizeof(((CustomData *)NULL)->typemap) / + sizeof(((CustomData *)NULL)->typemap[0]) == CD_NUMTYPES, + "size mismatch"); + + /********************* Layer type information **********************/ typedef struct LayerTypeInfo { int size; /* the memory size of one element of this layer's data */ - const char *structname; /* name of the struct used, for file writing */ - int structnum; /* number of structs per element, for file writing */ + + /** name of the struct used, for file writing */ + const char *structname; + /** number of structs per element, for file writing */ + int structnum; /** * default layer name. @@ -1055,8 +1064,8 @@ static const LayerTypeInfo LAYERTYPEINFO[CD_NUMTYPES] = { /* 8: CD_NORMAL */ /* 3 floats per normal vector */ {sizeof(float) * 3, "vec3f", 1, NULL, NULL, NULL, NULL, NULL, NULL}, - /* 9: CD_POLYINDEX */ - {sizeof(int), "MIntProperty", 1, NULL, NULL, NULL, NULL, NULL, NULL}, + /* 9: CD_POLYINDEX (deprecated) */ + {sizeof(int), "", 0, NULL, NULL, NULL, NULL, NULL, NULL}, /* 10: CD_PROP_FLT */ {sizeof(MFloatProperty), "MFloatProperty", 1, "Float", layerCopy_propFloat, NULL, NULL, NULL}, /* 11: CD_PROP_INT */ @@ -1076,7 +1085,7 @@ static const LayerTypeInfo LAYERTYPEINFO[CD_NUMTYPES] = { layerEqual_mloopuv, layerMultiply_mloopuv, layerInitMinMax_mloopuv, layerAdd_mloopuv, layerDoMinMax_mloopuv, layerCopyValue_mloopuv}, /* 17: CD_MLOOPCOL */ - {sizeof(MLoopCol), "MLoopCol", 1, "Col", NULL, NULL, layerInterp_mloopcol, NULL, + {sizeof(MLoopCol), "MLoopCol", 1, "Col", NULL, NULL, layerInterp_mloopcol, NULL, layerDefault_mloopcol, layerEqual_mloopcol, layerMultiply_mloopcol, layerInitMinMax_mloopcol, layerAdd_mloopcol, layerDoMinMax_mloopcol, layerCopyValue_mloopcol}, /* 18: CD_TANGENT */ @@ -1174,7 +1183,7 @@ const CustomDataMask CD_MASK_DERIVEDMESH = CD_MASK_MLOOPUV | CD_MASK_MLOOPCOL | CD_MASK_MTEXPOLY | CD_MASK_PREVIEW_MLOOPCOL | CD_MASK_PROP_STR | CD_MASK_ORIGSPACE | CD_MASK_ORIGSPACE_MLOOP | CD_MASK_ORCO | CD_MASK_TANGENT | CD_MASK_PREVIEW_MCOL | CD_MASK_NORMAL | CD_MASK_SHAPEKEY | CD_MASK_RECAST | - CD_MASK_ORIGINDEX | CD_MASK_POLYINDEX | CD_MASK_MVERT_SKIN; + CD_MASK_ORIGINDEX | CD_MASK_MVERT_SKIN; const CustomDataMask CD_MASK_BMESH = CD_MASK_MLOOPUV | CD_MASK_MLOOPCOL | CD_MASK_MTEXPOLY | CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_PROP_FLT | CD_MASK_PROP_INT | @@ -1221,9 +1230,6 @@ void CustomData_update_typemap(CustomData *data) { int i, lasttype = -1; - /* since we cant do in a pre-processor do here as an assert */ - BLI_assert(sizeof(data->typemap) / sizeof(int) >= CD_NUMTYPES); - for (i = 0; i < CD_NUMTYPES; i++) { data->typemap[i] = -1; } @@ -1236,6 +1242,13 @@ void CustomData_update_typemap(CustomData *data) } } +static int customdata_typemap_is_valid(const CustomData *data) +{ + CustomData data_copy = *data; + CustomData_update_typemap(&data_copy); + return (memcmp(data->typemap, data_copy.typemap, sizeof(data->typemap)) == 0); +} + void CustomData_merge(const struct CustomData *source, struct CustomData *dest, CustomDataMask mask, int alloctype, int totelem) { @@ -1301,7 +1314,7 @@ void CustomData_merge(const struct CustomData *source, struct CustomData *dest, void CustomData_copy(const struct CustomData *source, struct CustomData *dest, CustomDataMask mask, int alloctype, int totelem) { - memset(dest, 0, sizeof(*dest)); + CustomData_reset(dest); if (source->external) dest->external = MEM_dupallocN(source->external); @@ -1332,6 +1345,12 @@ static void CustomData_external_free(CustomData *data) } } +void CustomData_reset(CustomData *data) +{ + memset(data, 0, sizeof(*data)); + fill_vn_i(data->typemap, CD_NUMTYPES, -1); +} + void CustomData_free(CustomData *data, int totelem) { int i; @@ -1343,8 +1362,7 @@ void CustomData_free(CustomData *data, int totelem) MEM_freeN(data->layers); CustomData_external_free(data); - - memset(data, 0, sizeof(*data)); + CustomData_reset(data); } static void customData_update_offsets(CustomData *data) @@ -1363,9 +1381,10 @@ static void customData_update_offsets(CustomData *data) CustomData_update_typemap(data); } -int CustomData_get_layer_index(const CustomData *data, int type) +/* to use when we're in the middle of modifying layers */ +static int CustomData_get_layer_index__notypemap(const CustomData *data, int type) { - int i; + int i; for (i = 0; i < data->totlayer; ++i) if (data->layers[i].type == type) @@ -1374,11 +1393,21 @@ int CustomData_get_layer_index(const CustomData *data, int type) return -1; } +/* -------------------------------------------------------------------- */ +/* index values to access the layers (offset from the layer start) */ + +int CustomData_get_layer_index(const CustomData *data, int type) +{ + BLI_assert(customdata_typemap_is_valid(data)); + return data->typemap[type]; +} + int CustomData_get_layer_index_n(const struct CustomData *data, int type, int n) { int i = CustomData_get_layer_index(data, type); if (i != -1) { + BLI_assert(i + n < data->totlayer); i = (data->layers[i + n].type == type) ? (i + n) : (-1); } @@ -1398,91 +1427,62 @@ int CustomData_get_named_layer_index(const CustomData *data, int type, const cha int CustomData_get_active_layer_index(const CustomData *data, int type) { - if (!data->totlayer) - return -1; - - if (data->typemap[type] != -1) { - return data->typemap[type] + data->layers[data->typemap[type]].active; - } - - return -1; + const int layer_index = data->typemap[type]; + BLI_assert(customdata_typemap_is_valid(data)); + return (layer_index != -1) ? layer_index + data->layers[layer_index].active: -1; } int CustomData_get_render_layer_index(const CustomData *data, int type) { - int i; - - for (i = 0; i < data->totlayer; ++i) - if (data->layers[i].type == type) - return i + data->layers[i].active_rnd; - - return -1; + const int layer_index = data->typemap[type]; + BLI_assert(customdata_typemap_is_valid(data)); + return (layer_index != -1) ? layer_index + data->layers[layer_index].active_rnd : -1; } int CustomData_get_clone_layer_index(const CustomData *data, int type) { - int i; - - for (i = 0; i < data->totlayer; ++i) - if (data->layers[i].type == type) - return i + data->layers[i].active_clone; - - return -1; + const int layer_index = data->typemap[type]; + BLI_assert(customdata_typemap_is_valid(data)); + return (layer_index != -1) ? layer_index + data->layers[layer_index].active_clone : -1; } int CustomData_get_stencil_layer_index(const CustomData *data, int type) { - int i; + const int layer_index = data->typemap[type]; + BLI_assert(customdata_typemap_is_valid(data)); + return (layer_index != -1) ? layer_index + data->layers[layer_index].active_mask : -1; +} - for (i = 0; i < data->totlayer; ++i) - if (data->layers[i].type == type) - return i + data->layers[i].active_mask; - return -1; -} +/* -------------------------------------------------------------------- */ +/* index values per layer type */ int CustomData_get_active_layer(const CustomData *data, int type) { - int i; - - for (i = 0; i < data->totlayer; ++i) - if (data->layers[i].type == type) - return data->layers[i].active; - - return -1; + const int layer_index = data->typemap[type]; + BLI_assert(customdata_typemap_is_valid(data)); + return (layer_index != -1) ? data->layers[layer_index].active : -1; } int CustomData_get_render_layer(const CustomData *data, int type) { - int i; - - for (i = 0; i < data->totlayer; ++i) - if (data->layers[i].type == type) - return data->layers[i].active_rnd; - - return -1; + const int layer_index = data->typemap[type]; + BLI_assert(customdata_typemap_is_valid(data)); + return (layer_index != -1) ? data->layers[layer_index].active_rnd : -1; } int CustomData_get_clone_layer(const CustomData *data, int type) { - int i; - - for (i = 0; i < data->totlayer; ++i) - if (data->layers[i].type == type) - return data->layers[i].active_clone; - - return -1; + const int layer_index = data->typemap[type]; + BLI_assert(customdata_typemap_is_valid(data)); + return (layer_index != -1) ? data->layers[layer_index].active_clone : -1; } int CustomData_get_stencil_layer(const CustomData *data, int type) { - int i; - - for (i = 0; i < data->totlayer; ++i) - if (data->layers[i].type == type) - return data->layers[i].active_mask; - - return -1; + const int layer_index = data->typemap[type]; + BLI_assert(customdata_typemap_is_valid(data)); + return (layer_index != -1) ? data->layers[layer_index].active_mask : -1; } void CustomData_set_layer_active(CustomData *data, int type, int n) @@ -1713,7 +1713,7 @@ int CustomData_free_layer(CustomData *data, int type, int totelem, int index) /* if layer was last of type in array, set new active layer */ if ((index >= data->totlayer) || (data->layers[index].type != type)) { - i = CustomData_get_layer_index(data, type); + i = CustomData_get_layer_index__notypemap(data, type); if (i >= 0) for (; i < data->totlayer && data->layers[i].type == type; i++) { @@ -1728,7 +1728,6 @@ int CustomData_free_layer(CustomData *data, int type, int totelem, int index) customData_resize(data, -CUSTOMDATA_GROW); customData_update_offsets(data); - CustomData_update_typemap(data); return 1; } @@ -2358,7 +2357,9 @@ void CustomData_bmesh_free_block(CustomData *data, void **block) const LayerTypeInfo *typeInfo; int i; - if (!*block) return; + if (*block == NULL) + return; + for (i = 0; i < data->totlayer; ++i) { if (!(data->layers[i].flag & CD_FLAG_NOFREE)) { typeInfo = layerType_getInfo(data->layers[i].type); @@ -2394,7 +2395,7 @@ void CustomData_bmesh_copy_data(const CustomData *source, CustomData *dest, const LayerTypeInfo *typeInfo; int dest_i, src_i; - if (!*dest_block) { + if (*dest_block == NULL) { CustomData_bmesh_alloc_block(dest, dest_block); if (*dest_block) memset(*dest_block, 0, dest->totsize); @@ -2475,10 +2476,49 @@ int CustomData_layer_has_math(struct CustomData *data, int layer_n) if (typeInfo->equal && typeInfo->add && typeInfo->multiply && typeInfo->initminmax && typeInfo->dominmax) { - return 1; + return TRUE; } - return 0; + return FALSE; +} + +int CustomData_layer_has_interp(struct CustomData *data, int layer_n) +{ + const LayerTypeInfo *typeInfo = layerType_getInfo(data->layers[layer_n].type); + + if (typeInfo->interp) { + return TRUE; + } + + return FALSE; +} + +int CustomData_has_math(struct CustomData *data) +{ + int i; + + /* interpolates a layer at a time */ + for (i = 0; i < data->totlayer; ++i) { + if (CustomData_layer_has_math(data, i)) { + return TRUE; + } + } + + return FALSE; +} + +int CustomData_has_interp(struct CustomData *data) +{ + int i; + + /* interpolates a layer at a time */ + for (i = 0; i < data->totlayer; ++i) { + if (CustomData_layer_has_interp(data, i)) { + return TRUE; + } + } + + return FALSE; } /* copies the "value" (e.g. mloopuv uv or mloopcol colors) from one block to @@ -2578,8 +2618,8 @@ void CustomData_bmesh_set_layer_n(CustomData *data, void *block, int n, void *so memcpy(dest, source, typeInfo->size); } -void CustomData_bmesh_interp(CustomData *data, void **src_blocks, float *weights, - float *sub_weights, int count, void *dest_block) +void CustomData_bmesh_interp(CustomData *data, void **src_blocks, const float *weights, + const float *sub_weights, int count, void *dest_block) { int i, j; void *source_buf[SOURCE_BUF_SIZE]; @@ -2614,7 +2654,7 @@ void CustomData_bmesh_set_default(CustomData *data, void **block) const LayerTypeInfo *typeInfo; int i; - if (!*block) + if (*block == NULL) CustomData_bmesh_alloc_block(data, block); for (i = 0; i < data->totlayer; ++i) { @@ -2634,7 +2674,7 @@ void CustomData_to_bmesh_block(const CustomData *source, CustomData *dest, const LayerTypeInfo *typeInfo; int dest_i, src_i, src_offset; - if (!*dest_block) + if (*dest_block == NULL) CustomData_bmesh_alloc_block(dest, dest_block); /* copies a layer at a time */ @@ -2866,7 +2906,9 @@ void CustomData_external_reload(CustomData *data, ID *UNUSED(id), CustomDataMask layer = &data->layers[i]; typeInfo = layerType_getInfo(layer->type); - if (!(mask & CD_TYPE_AS_MASK(layer->type))) ; + if (!(mask & CD_TYPE_AS_MASK(layer->type))) { + /* pass */ + } else if ((layer->flag & CD_FLAG_EXTERNAL) && (layer->flag & CD_FLAG_IN_MEMORY)) { if (typeInfo->free) typeInfo->free(layer->data, totelem, typeInfo->size); @@ -2892,10 +2934,15 @@ void CustomData_external_read(CustomData *data, ID *id, CustomDataMask mask, int layer = &data->layers[i]; typeInfo = layerType_getInfo(layer->type); - if (!(mask & CD_TYPE_AS_MASK(layer->type))) ; - else if (layer->flag & CD_FLAG_IN_MEMORY) ; - else if ((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->read) + if (!(mask & CD_TYPE_AS_MASK(layer->type))) { + /* pass */ + } + else if (layer->flag & CD_FLAG_IN_MEMORY) { + /* pass */ + } + else if ((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->read) { update = 1; + } } if (!update) @@ -2913,15 +2960,23 @@ void CustomData_external_read(CustomData *data, ID *id, CustomDataMask mask, int layer = &data->layers[i]; typeInfo = layerType_getInfo(layer->type); - if (!(mask & CD_TYPE_AS_MASK(layer->type))) ; - else if (layer->flag & CD_FLAG_IN_MEMORY) ; + if (!(mask & CD_TYPE_AS_MASK(layer->type))) { + /* pass */ + } + else if (layer->flag & CD_FLAG_IN_MEMORY) { + /* pass */ + } else if ((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->read) { blay = cdf_layer_find(cdf, layer->type, layer->name); if (blay) { if (cdf_read_layer(cdf, blay)) { - if (typeInfo->read(cdf, layer->data, totelem)) ; - else break; + if (typeInfo->read(cdf, layer->data, totelem)) { + /* pass */ + } + else { + break; + } layer->flag |= CD_FLAG_IN_MEMORY; } else @@ -2952,9 +3007,12 @@ void CustomData_external_write(CustomData *data, ID *id, CustomDataMask mask, in layer = &data->layers[i]; typeInfo = layerType_getInfo(layer->type); - if (!(mask & CD_TYPE_AS_MASK(layer->type))) ; - else if ((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write) + if (!(mask & CD_TYPE_AS_MASK(layer->type))) { + /* pass */ + } + else if ((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write) { update = 1; + } } if (!update) @@ -2995,11 +3053,16 @@ void CustomData_external_write(CustomData *data, ID *id, CustomDataMask mask, in blay = cdf_layer_find(cdf, layer->type, layer->name); if (cdf_write_layer(cdf, blay)) { - if (typeInfo->write(cdf, layer->data, totelem)) ; - else break; + if (typeInfo->write(cdf, layer->data, totelem)) { + /* pass */ + } + else { + break; + } } - else + else { break; + } } } diff --git a/source/blender/blenkernel/intern/deform.c b/source/blender/blenkernel/intern/deform.c index 4110d4565b2..7c13ca388e0 100644 --- a/source/blender/blenkernel/intern/deform.c +++ b/source/blender/blenkernel/intern/deform.c @@ -278,7 +278,7 @@ void defvert_normalize_lock_map(MDeformVert *dvert, const char *lock_flags, cons } } - lock_iweight = maxf(0.0f, 1.0f - lock_iweight); + lock_iweight = max_ff(0.0f, 1.0f - lock_iweight); if (tot_weight > 0.0f) { /* paranoid, should be 1.0 but in case of float error clamp anyway */ @@ -431,7 +431,7 @@ int *defgroup_flip_map_single(Object *ob, int *flip_map_len, int use_default, in if (strcmp(name, dg->name)) { flip_num = defgroup_name_index(ob, name); - if (flip_num >= 0) { + if (flip_num != -1) { map[defgroup] = flip_num; map[flip_num] = defgroup; } @@ -790,3 +790,23 @@ void defvert_clear(MDeformVert *dvert) dvert->totweight = 0; } + +/** + * \return The first group index shared by both deform verts + * or -1 if none are found. + */ +int defvert_find_shared(const MDeformVert *dvert_a, const MDeformVert *dvert_b) +{ + if (dvert_a->totweight && dvert_b->totweight) { + MDeformWeight *dw = dvert_a->dw; + unsigned int i; + + for (i = dvert_a->totweight; i != 0; i--, dw++) { + if (dw->weight > 0.0f && defvert_find_weight(dvert_b, dw->def_nr) > 0.0f) { + return dw->def_nr; + } + } + } + + return -1; +} diff --git a/source/blender/blenkernel/intern/depsgraph.c b/source/blender/blenkernel/intern/depsgraph.c index 48040867ad4..9d3a7ec57cf 100644 --- a/source/blender/blenkernel/intern/depsgraph.c +++ b/source/blender/blenkernel/intern/depsgraph.c @@ -45,6 +45,7 @@ #include "DNA_anim_types.h" #include "DNA_camera_types.h" #include "DNA_group_types.h" +#include "DNA_lamp_types.h" #include "DNA_lattice_types.h" #include "DNA_key_types.h" #include "DNA_material_types.h" @@ -150,8 +151,8 @@ void queue_delete(DagNodeQueue *queue) MEM_freeN(temp); } - MEM_freeN(queue->freenodes); - MEM_freeN(queue); + MEM_freeN(queue->freenodes); + MEM_freeN(queue); } /* insert in queue, remove in front */ @@ -190,8 +191,8 @@ void push_queue(DagNodeQueue *queue, DagNode *node) } queue->freenodes->count = DAGQUEUEALLOC; - elem = queue->freenodes->first; - queue->freenodes->first = elem->next; + elem = queue->freenodes->first; + queue->freenodes->first = elem->next; } elem->next = NULL; elem->node = node; @@ -211,7 +212,7 @@ void push_stack(DagNodeQueue *queue, DagNode *node) DagNodeQueueElem *elem; int i; - elem = queue->freenodes->first; + elem = queue->freenodes->first; if (elem != NULL) { queue->freenodes->first = elem->next; if (queue->freenodes->last == elem) { @@ -235,8 +236,8 @@ void push_stack(DagNodeQueue *queue, DagNode *node) } queue->freenodes->count = DAGQUEUEALLOC; - elem = queue->freenodes->first; - queue->freenodes->first = elem->next; + elem = queue->freenodes->first; + queue->freenodes->first = elem->next; } elem->next = queue->first; elem->node = node; @@ -302,7 +303,7 @@ DagForest *dag_init(void) } /* isdata = object data... */ -// XXX this needs to be extended to be more flexible (so that not only objects are evaluated via depsgraph)... +/* XXX this needs to be extended to be more flexible (so that not only objects are evaluated via depsgraph)... */ static void dag_add_driver_relation(AnimData *adt, DagForest *dag, DagNode *node, int isdata) { FCurve *fcu; @@ -350,8 +351,8 @@ static void dag_add_driver_relation(AnimData *adt, DagForest *dag, DagNode *node /* XXX: forward def for material driver handling... */ static void dag_add_material_driver_relations(DagForest *dag, DagNode *node, Material *ma); -/* recursive handling for material nodetree drivers */ -static void dag_add_material_nodetree_driver_relations(DagForest *dag, DagNode *node, bNodeTree *ntree) +/* recursive handling for shader nodetree drivers */ +static void dag_add_shader_nodetree_driver_relations(DagForest *dag, DagNode *node, bNodeTree *ntree) { bNode *n; @@ -367,7 +368,7 @@ static void dag_add_material_nodetree_driver_relations(DagForest *dag, DagNode * dag_add_material_driver_relations(dag, node, (Material *)n->id); } else if (n->type == NODE_GROUP) { - dag_add_material_nodetree_driver_relations(dag, node, (bNodeTree *)n->id); + dag_add_shader_nodetree_driver_relations(dag, node, (bNodeTree *)n->id); } } } @@ -386,21 +387,44 @@ static void dag_add_material_driver_relations(DagForest *dag, DagNode *node, Mat ma->id.flag |= LIB_DOIT; /* material itself */ - if (ma->adt) { + if (ma->adt) dag_add_driver_relation(ma->adt, dag, node, 1); - } /* textures */ // TODO... //dag_add_texture_driver_relations(DagForest *dag, DagNode *node, ID *id); /* material's nodetree */ - if (ma->nodetree) { - dag_add_material_nodetree_driver_relations(dag, node, ma->nodetree); - } + if (ma->nodetree) + dag_add_shader_nodetree_driver_relations(dag, node, ma->nodetree); +} + +/* recursive handling for lamp drivers */ +static void dag_add_lamp_driver_relations(DagForest *dag, DagNode *node, Lamp *la) +{ + /* Prevent infinite recursion by checking (and tagging the lamp) as having been visited + * already (see build_dag()). This assumes la->id.flag & LIB_DOIT isn't set by anything else + * in the meantime... [#32017] + */ + if (la->id.flag & LIB_DOIT) + return; + else + la->id.flag |= LIB_DOIT; + + /* lamp itself */ + if (la->adt) + dag_add_driver_relation(la->adt, dag, node, 1); + + /* textures */ + // TODO... + //dag_add_texture_driver_relations(DagForest *dag, DagNode *node, ID *id); + + /* lamp's nodetree */ + if (la->nodetree) + dag_add_shader_nodetree_driver_relations(dag, node, la->nodetree); } -static void dag_add_collision_field_relation(DagForest *dag, Scene *scene, Object *ob, DagNode *node) +static void dag_add_collision_field_relation(DagForest *dag, Scene *scene, Object *ob, DagNode *node, int skip_forcefield) { Base *base; DagNode *node2; @@ -411,7 +435,9 @@ static void dag_add_collision_field_relation(DagForest *dag, Scene *scene, Objec if ((base->lay & ob->lay) && base->object->pd) { Object *ob1 = base->object; if ((ob1->pd->deflect || ob1->pd->forcefield) && (ob1 != ob)) { - node2 = dag_get_node(dag, ob1); + if (skip_forcefield && ob1->pd->forcefield == skip_forcefield) + continue; + node2 = dag_get_node(dag, ob1); dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Field Collision"); } } @@ -443,7 +469,6 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, O if (ob->type == OB_ARMATURE) { if (ob->pose) { bPoseChannel *pchan; - bConstraint *con; for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) { for (con = pchan->constraints.first; con; con = con->next) { @@ -464,7 +489,7 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, O if (ct->tar->type == OB_MESH) node3->customdata_mask |= CD_MASK_MDEFORMVERT; } - else if (ELEM3(con->type, CONSTRAINT_TYPE_FOLLOWPATH, CONSTRAINT_TYPE_CLAMPTO, CONSTRAINT_TYPE_SPLINEIK)) + else if (ELEM3(con->type, CONSTRAINT_TYPE_FOLLOWPATH, CONSTRAINT_TYPE_CLAMPTO, CONSTRAINT_TYPE_SPLINEIK)) dag_add_relation(dag, node3, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, cti->name); else dag_add_relation(dag, node3, node, DAG_RL_OB_DATA, cti->name); @@ -570,12 +595,14 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, O /* softbody collision */ if ((ob->type == OB_MESH) || (ob->type == OB_CURVE) || (ob->type == OB_LATTICE)) { if (ob->particlesystem.first || - modifiers_isModifierEnabled(ob, eModifierType_Softbody) || - modifiers_isModifierEnabled(ob, eModifierType_Cloth) || - modifiers_isModifierEnabled(ob, eModifierType_Smoke) || - modifiers_isModifierEnabled(ob, eModifierType_DynamicPaint)) + modifiers_isModifierEnabled(ob, eModifierType_Softbody) || + modifiers_isModifierEnabled(ob, eModifierType_Cloth) || + modifiers_isModifierEnabled(ob, eModifierType_DynamicPaint)) { - dag_add_collision_field_relation(dag, scene, ob, node); /* TODO: use effectorweight->group */ + dag_add_collision_field_relation(dag, scene, ob, node, 0); /* TODO: use effectorweight->group */ + } + else if (modifiers_isModifierEnabled(ob, eModifierType_Smoke)) { + dag_add_collision_field_relation(dag, scene, ob, node, PFIELD_SMOKEFLOW); } } @@ -604,7 +631,7 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, O if (mom != ob) { node2 = dag_get_node(dag, mom); - dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Metaball"); // mom depends on children! + dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Metaball"); /* mom depends on children! */ } } break; @@ -632,18 +659,20 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, O } /* material drivers */ - //if (ob->totcol) { - // int a; - // - // for (a = 1; a <= ob->totcol; a++) { - // Material *ma = give_current_material(ob, a); - // - // if (ma) { - // /* recursively figure out if there are drivers, and hook these up to this object */ - // dag_add_material_driver_relations(dag, node, ma); - // } - // } - //} + if (ob->totcol) { + int a; + + for (a = 1; a <= ob->totcol; a++) { + Material *ma = give_current_material(ob, a); + + if (ma) { + /* recursively figure out if there are drivers, and hook these up to this object */ + dag_add_material_driver_relations(dag, node, ma); + } + } + } + else if(ob->type == OB_LAMP) + dag_add_lamp_driver_relations(dag, node, ob->data); /* particles */ psys = ob->particlesystem.first; @@ -814,9 +843,10 @@ DagForest *build_dag(Main *bmain, Scene *sce, short mask) /* clear "LIB_DOIT" flag from all materials, to prevent infinite recursion problems later [#32017] */ tag_main_idcode(bmain, ID_MA, FALSE); + tag_main_idcode(bmain, ID_LA, FALSE); /* add base node for scene. scene is always the first node in DAG */ - scenenode = dag_add_node(dag, sce); + scenenode = dag_add_node(dag, sce); /* add current scene objects */ for (base = sce->base.first; base; base = base->next) { @@ -870,7 +900,7 @@ DagForest *build_dag(Main *bmain, Scene *sce, short mask) } /* cycle detection and solving */ - // solve_cycles(dag); + // solve_cycles(dag); return dag; } @@ -879,23 +909,23 @@ DagForest *build_dag(Main *bmain, Scene *sce, short mask) void free_forest(DagForest *Dag) { /* remove all nodes and deps */ DagNode *tempN; - DagAdjList *tempA; + DagAdjList *tempA; DagAdjList *itA; DagNode *itN = Dag->DagNode.first; while (itN) { - itA = itN->child; + itA = itN->child; while (itA) { tempA = itA; itA = itA->next; - MEM_freeN(tempA); + MEM_freeN(tempA); } - itA = itN->parent; + itA = itN->parent; while (itA) { tempA = itA; itA = itA->next; - MEM_freeN(tempA); + MEM_freeN(tempA); } tempN = itN; @@ -919,8 +949,8 @@ DagNode *dag_find_node(DagForest *forest, void *fob) return NULL; } -static int ugly_hack_sorry = 1; // prevent type check -static int dag_print_dependencies = 0; // debugging +static int ugly_hack_sorry = 1; /* prevent type check */ +static int dag_print_dependencies = 0; /* debugging */ /* no checking of existence, use dag_find_node first or dag_get_node */ DagNode *dag_add_node(DagForest *forest, void *fob) @@ -932,7 +962,7 @@ DagNode *dag_add_node(DagForest *forest, void *fob) node->ob = fob; node->color = DAG_WHITE; - if (ugly_hack_sorry) node->type = GS(((ID *) fob)->name); // sorry, done for pose sorting + if (ugly_hack_sorry) node->type = GS(((ID *) fob)->name); /* sorry, done for pose sorting */ if (forest->numNodes) { ((DagNode *) forest->DagNode.last)->next = node; forest->DagNode.last = node; @@ -1151,7 +1181,7 @@ static void dag_check_cycle(DagForest *dag) for (node = dag->DagNode.first; node; node = node->next) { while (node->parent) { itA = node->parent->next; - MEM_freeN(node->parent); + MEM_freeN(node->parent); node->parent = itA; } } @@ -1240,7 +1270,7 @@ void graph_bfs(void) itA = itA->next; } if (pos[node->BFS_dist] > node->k) { - pos[node->BFS_dist] += 1; + pos[node->BFS_dist] += 1; node->k = (float) pos[node->BFS_dist]; } else { @@ -1301,7 +1331,7 @@ int pre_and_post_source_BFS(DagForest *dag, short mask, DagNode *source, graph_a pre_func(node->ob, data); } - else { // back or cross edge + else { /* back or cross edge */ retval = 1; } itA = itA->next; @@ -1332,7 +1362,7 @@ DagNodeQueue *graph_dfs(void) /* int is_cycle = 0; */ /* UNUSED */ /* *fprintf(stderr, "starting DFS\n ------------\n"); - */ + */ nqueue = queue_create(DAGQUEUEALLOC); retqueue = queue_create(MainDag->numNodes); for (i = 0; i < 50; i++) @@ -1384,7 +1414,7 @@ DagNodeQueue *graph_dfs(void) break; } else { - if (itA->node->color == DAG_GRAY) { // back edge + if (itA->node->color == DAG_GRAY) { /* back edge */ fprintf(stderr, "dfs back edge :%15s %15s\n", ((ID *) node->ob)->name, ((ID *) itA->node->ob)->name); /* is_cycle = 1; */ /* UNUSED */ } @@ -1462,7 +1492,7 @@ int pre_and_post_source_DFS(DagForest *dag, short mask, DagNode *source, graph_a int retval = 0; /* * fprintf(stderr, "starting DFS\n ------------\n"); - */ + */ nqueue = queue_create(DAGQUEUEALLOC); /* Init @@ -1516,7 +1546,7 @@ int pre_and_post_source_DFS(DagForest *dag, short mask, DagNode *source, graph_a // } } itA = itA->next; - } + } if (!skip) { node = pop_queue(nqueue); @@ -1535,7 +1565,7 @@ int pre_and_post_source_DFS(DagForest *dag, short mask, DagNode *source, graph_a } -// used to get the obs owning a datablock +/* used to get the obs owning a datablock */ DagNodeQueue *get_obparents(struct DagForest *dag, void *ob) { DagNode *node, *node1; @@ -1546,7 +1576,7 @@ DagNodeQueue *get_obparents(struct DagForest *dag, void *ob) if (node == NULL) { return NULL; } - else if (node->ancestor_count == 1) { // simple case + else if (node->ancestor_count == 1) { /* simple case */ nqueue = queue_create(1); push_queue(nqueue, node); } @@ -1555,7 +1585,7 @@ DagNodeQueue *get_obparents(struct DagForest *dag, void *ob) node1 = dag->DagNode.first; do { - if (node1->DFS_fntm > node->DFS_fntm) { // a parent is finished after child. must check adj list + if (node1->DFS_fntm > node->DFS_fntm) { /* a parent is finished after child. must check adj list */ itA = node->child; while (itA != NULL) { if ((itA->node == node) && (itA->type == DAG_RL_DATA)) { @@ -1583,7 +1613,7 @@ DagNodeQueue *get_first_ancestors(struct DagForest *dag, void *ob) node1 = dag->DagNode.first; do { - if (node1->DFS_fntm > node->DFS_fntm) { + if (node1->DFS_fntm > node->DFS_fntm) { itA = node->child; while (itA != NULL) { if (itA->node == node) { @@ -1595,10 +1625,10 @@ DagNodeQueue *get_first_ancestors(struct DagForest *dag, void *ob) node1 = node1->next; } while (node1); - return nqueue; + return nqueue; } -// standard DFS list +/* standard DFS list */ DagNodeQueue *get_all_childs(struct DagForest *dag, void *ob) { DagNode *node; @@ -1609,7 +1639,7 @@ DagNodeQueue *get_all_childs(struct DagForest *dag, void *ob) int skip = 0; nqueue = queue_create(DAGQUEUEALLOC); - retqueue = queue_create(dag->numNodes); // was MainDag... why? (ton) + retqueue = queue_create(dag->numNodes); /* was MainDag... why? (ton) */ node = dag->DagNode.first; while (node) { @@ -1619,8 +1649,8 @@ DagNodeQueue *get_all_childs(struct DagForest *dag, void *ob) time = 1; - node = dag_find_node(dag, ob); // could be done in loop above (ton) - if (node) { // can be null for newly added objects + node = dag_find_node(dag, ob); /* could be done in loop above (ton) */ + if (node) { /* can be null for newly added objects */ node->color = DAG_GRAY; time++; @@ -1641,9 +1671,9 @@ DagNodeQueue *get_all_childs(struct DagForest *dag, void *ob) push_stack(nqueue, itA->node); skip = 1; break; - } + } itA = itA->next; - } + } if (!skip) { node = pop_queue(nqueue); @@ -1671,7 +1701,7 @@ short are_obs_related(struct DagForest *dag, void *ob1, void *ob2) while (itA != NULL) { if (itA->node->ob == ob2) { return itA->node->type; - } + } itA = itA->next; } return DAG_NO_RELATION; @@ -1699,7 +1729,7 @@ void graph_print_queue(DagNodeQueue *nqueue) queueElem = nqueue->first; while (queueElem) { fprintf(stderr, "** %s %i %i-%i ", ((ID *) queueElem->node->ob)->name, queueElem->node->color, queueElem->node->DFS_dvtm, queueElem->node->DFS_fntm); - queueElem = queueElem->next; + queueElem = queueElem->next; } fprintf(stderr, "\n"); } @@ -1719,7 +1749,7 @@ void graph_print_queue_dist(DagNodeQueue *nqueue) fputc('|', stderr); fputc('\n', stderr); count = 0; - queueElem = queueElem->next; + queueElem = queueElem->next; } fprintf(stderr, "\n"); } @@ -1857,14 +1887,14 @@ void DAG_scene_sort(Main *bmain, Scene *sce) push_stack(nqueue, itA->node); skip = 1; break; - } + } itA = itA->next; - } + } if (!skip) { if (node) { node = pop_queue(nqueue); - if (node->ob == sce) // we are done + if (node->ob == sce) /* we are done */ break; node->color = DAG_BLACK; @@ -1876,7 +1906,7 @@ void DAG_scene_sort(Main *bmain, Scene *sce) BLI_remlink(&sce->base, base); BLI_addhead(&tempbase, base); } - } + } } } @@ -2021,7 +2051,7 @@ static unsigned int flush_layer_node(Scene *sce, DagNode *node, int curtime) for (itA = node->child; itA; itA = itA->next) { if (itA->node->type == ID_OB) { if (itA->node->lasttime != curtime) { - itA->lay = flush_layer_node(sce, itA->node, curtime); // lay is only set once for each relation + itA->lay = flush_layer_node(sce, itA->node, curtime); /* lay is only set once for each relation */ } else itA->lay = itA->node->lay; @@ -2069,12 +2099,12 @@ static void dag_scene_flush_layers(Scene *sce, int lay) Base *base; int lasttime; - firstnode = sce->theDag->DagNode.first; // always scene node + firstnode = sce->theDag->DagNode.first; /* always scene node */ for (itA = firstnode->child; itA; itA = itA->next) itA->lay = 0; - sce->theDag->time++; // so we know which nodes were accessed + sce->theDag->time++; /* so we know which nodes were accessed */ lasttime = sce->theDag->time; /* update layer flags in nodes */ @@ -2146,13 +2176,13 @@ void DAG_scene_flush_update(Main *bmain, Scene *sce, unsigned int lay, const sho DAG_scene_sort(bmain, sce); } - firstnode = sce->theDag->DagNode.first; // always scene node + firstnode = sce->theDag->DagNode.first; /* always scene node */ /* first we flush the layer flags */ dag_scene_flush_layers(sce, lay); /* then we use the relationships + layer info to flush update events */ - sce->theDag->time++; // so we know which nodes were accessed + sce->theDag->time++; /* so we know which nodes were accessed */ lasttime = sce->theDag->time; for (itA = firstnode->child; itA; itA = itA->next) if (itA->node->lasttime != lasttime && itA->node->type == ID_OB) @@ -2160,7 +2190,7 @@ void DAG_scene_flush_update(Main *bmain, Scene *sce, unsigned int lay, const sho /* if update is not due to time change, do pointcache clears */ if (!time) { - sce->theDag->time++; // so we know which nodes were accessed + sce->theDag->time++; /* so we know which nodes were accessed */ lasttime = sce->theDag->time; for (itA = firstnode->child; itA; itA = itA->next) { if (itA->node->lasttime != lasttime && itA->node->type == ID_OB) { @@ -2378,7 +2408,7 @@ static void dag_object_time_update_flags(Object *ob) } } } - } + } if (ob->recalc & OB_RECALC_OB) lib_id_recalc_tag(G.main, &ob->id); @@ -2928,9 +2958,9 @@ void DAG_pose_sort(Object *ob) int skip = 0; dag = dag_init(); - ugly_hack_sorry = 0; // no ID structs + ugly_hack_sorry = 0; /* no ID structs */ - rootnode = dag_add_node(dag, NULL); // node->ob becomes NULL + rootnode = dag_add_node(dag, NULL); /* node->ob becomes NULL */ /* we add the hierarchy and the constraints */ for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) { @@ -2975,7 +3005,7 @@ void DAG_pose_sort(Object *ob) dag_add_relation(dag, node2, node3, 0, "IK Constraint"); segcount++; - if (segcount == data->rootbone || segcount > 255) break; // 255 is weak + if (segcount == data->rootbone || segcount > 255) break; /* 255 is weak */ parchan = parchan->parent; } } @@ -3018,21 +3048,21 @@ void DAG_pose_sort(Object *ob) push_stack(nqueue, itA->node); skip = 1; break; - } + } itA = itA->next; - } + } if (!skip) { if (node) { node = pop_queue(nqueue); - if (node->ob == NULL) // we are done + if (node->ob == NULL) /* we are done */ break; node->color = DAG_BLACK; /* put node in new list */ BLI_remlink(&pose->chanbase, node->ob); BLI_addhead(&tempbase, node->ob); - } + } } } diff --git a/source/blender/blenkernel/intern/displist.c b/source/blender/blenkernel/intern/displist.c index 64959fd3aa1..a78a9af54ae 100644 --- a/source/blender/blenkernel/intern/displist.c +++ b/source/blender/blenkernel/intern/displist.c @@ -299,7 +299,9 @@ static void curve_to_displist(Curve *cu, ListBase *nubase, ListBase *dispbase, i else resolu = nu->resolu; - if (!BKE_nurb_check_valid_u(nu)) ; + if (!BKE_nurb_check_valid_u(nu)) { + /* pass */ + } else if (nu->type == CU_BEZIER) { /* count */ len = 0; @@ -628,7 +630,7 @@ static void curve_to_filledpoly(Curve *cu, ListBase *UNUSED(nurb), ListBase *dis * - first point left, last point right * - based on subdivided points in original curve, not on points in taper curve (still) */ -float BKE_displist_calc_taper(Scene *scene, Object *taperobj, int cur, int tot) +static float displist_calc_taper(Scene *scene, Object *taperobj, float fac) { DispList *dl; @@ -641,7 +643,6 @@ float BKE_displist_calc_taper(Scene *scene, Object *taperobj, int cur, int tot) dl = taperobj->disp.first; } if (dl) { - float fac = ((float)cur) / (float)(tot - 1); float minx, dx, *fp; int a; @@ -669,6 +670,13 @@ float BKE_displist_calc_taper(Scene *scene, Object *taperobj, int cur, int tot) return 1.0; } +float BKE_displist_calc_taper(Scene *scene, Object *taperobj, int cur, int tot) +{ + float fac = ((float)cur) / (float)(tot - 1); + + return displist_calc_taper(scene, taperobj, fac); +} + void BKE_displist_make_mball(Scene *scene, Object *ob) { if (!ob || ob->type != OB_MBALL) @@ -1238,7 +1246,7 @@ void BKE_displist_make_surf(Scene *scene, Object *ob, ListBase *dispbase, } } -static void rotateBevelPiece(Curve *cu, BevPoint *bevp, DispList *dlb, float widfac, float fac, float **data_r) +static void rotateBevelPiece(Curve *cu, BevPoint *bevp, BevPoint *nbevp, DispList *dlb, float bev_blend, float widfac, float fac, float **data_r) { float *fp, *data = *data_r; int b; @@ -1246,22 +1254,48 @@ static void rotateBevelPiece(Curve *cu, BevPoint *bevp, DispList *dlb, float wid fp = dlb->verts; for (b = 0; b < dlb->nr; b++, fp += 3, data += 3) { if (cu->flag & CU_3D) { - float vec[3]; + float vec[3], quat[4]; vec[0] = fp[1] + widfac; vec[1] = fp[2]; vec[2] = 0.0; - mul_qt_v3(bevp->quat, vec); + if (nbevp == NULL) { + copy_v3_v3(data, bevp->vec); + copy_qt_qt(quat, bevp->quat); + } + else { + interp_v3_v3v3(data, bevp->vec, nbevp->vec, bev_blend); + interp_qt_qtqt(quat, bevp->quat, nbevp->quat, bev_blend); + } - data[0] = bevp->vec[0] + fac * vec[0]; - data[1] = bevp->vec[1] + fac * vec[1]; - data[2] = bevp->vec[2] + fac * vec[2]; + mul_qt_v3(quat, vec); + + data[0] += fac * vec[0]; + data[1] += fac * vec[1]; + data[2] += fac * vec[2]; } else { - data[0] = bevp->vec[0] + fac * (widfac + fp[1]) * bevp->sina; - data[1] = bevp->vec[1] + fac * (widfac + fp[1]) * bevp->cosa; - data[2] = bevp->vec[2] + fac * fp[2]; + float sina, cosa; + + if (nbevp == NULL) { + copy_v3_v3(data, bevp->vec); + sina = bevp->sina; + cosa = bevp->cosa; + } + else { + interp_v3_v3v3(data, bevp->vec, nbevp->vec, bev_blend); + + /* perhaps we need to interpolate angles instead. but the thing is + * cosa and sina are not actually sine and cosine + */ + sina = nbevp->sina * bev_blend + bevp->sina * (1.0f - bev_blend); + cosa = nbevp->cosa * bev_blend + bevp->cosa * (1.0f - bev_blend); + } + + data[0] += fac * (widfac + fp[1]) * sina; + data[1] += fac * (widfac + fp[1]) * cosa; + data[2] += fac * fp[2]; } } @@ -1384,8 +1418,8 @@ static void do_makeDispListCurveTypes(Scene *scene, Object *ob, ListBase *dispba ListBase top_capbase = {NULL, NULL}; for (dlb = dlbev.first; dlb; dlb = dlb->next) { - const float bevfac1 = minf(cu->bevfac1, cu->bevfac2); - const float bevfac2 = maxf(cu->bevfac1, cu->bevfac2); + const float bevfac1 = min_ff(cu->bevfac1, cu->bevfac2); + const float bevfac2 = max_ff(cu->bevfac1, cu->bevfac2); float firstblend = 0.0f, lastblend = 0.0f; int i, start, steps; @@ -1397,8 +1431,8 @@ static void do_makeDispListCurveTypes(Scene *scene, Object *ob, ListBase *dispba firstblend = 1.0f - (bevfac1 * (bl->nr - 1) - (int)(bevfac1 * (bl->nr - 1))); lastblend = bevfac2 * (bl->nr - 1) - (int)(bevfac2 * (bl->nr - 1)); - if (steps > bl->nr) { - steps = bl->nr; + if (start + steps > bl->nr) { + steps = bl->nr - start; lastblend = 1.0f; } @@ -1436,7 +1470,29 @@ static void do_makeDispListCurveTypes(Scene *scene, Object *ob, ListBase *dispba fac = bevp->radius; } else { - fac = BKE_displist_calc_taper(scene, cu->taperobj, i, bl->nr); + float len, taper_fac; + + if (cu->flag & CU_MAP_TAPER) { + len = (steps - 3) + firstblend + lastblend; + + if (a == 0) + taper_fac = 0.0f; + else if (a == steps - 1) + taper_fac = 1.0f; + else + taper_fac = ((float) a - (1.0f - firstblend)) / len; + } + else { + len = bl->nr - 1; + taper_fac = (float) i / len; + + if (a == 0) + taper_fac += (1.0f - firstblend) / len; + else if (a == steps - 1) + taper_fac -= (1.0f - lastblend) / len; + } + + fac = displist_calc_taper(scene, cu->taperobj, taper_fac); } if (bevp->split_tag) { @@ -1444,27 +1500,12 @@ static void do_makeDispListCurveTypes(Scene *scene, Object *ob, ListBase *dispba } /* rotate bevel piece and write in data */ - rotateBevelPiece(cu, bevp, dlb, widfac, fac, &data); - - if (a == 1 || a == steps - 1) { - float *cur_fp = cur_data, *prev_fp = cur_data - 3 * dlb->nr; - int b; - - for (b = 0; b < dlb->nr; b++, prev_fp += 3, cur_fp += 3) { - float cur[3], prev[3]; - - copy_v3_v3(cur, cur_fp); - copy_v3_v3(prev, prev_fp); - - if (a == 1) - interp_v3_v3v3(prev, cur_fp, prev_fp, firstblend); - if (a == steps - 1) - interp_v3_v3v3(cur, prev_fp, cur_fp, lastblend); - - copy_v3_v3(cur_fp, cur); - copy_v3_v3(prev_fp, prev); - } - } + if (a == 0) + rotateBevelPiece(cu, bevp, bevp + 1, dlb, 1.0f - firstblend, widfac, fac, &data); + else if (a == steps - 1) + rotateBevelPiece(cu, bevp, bevp - 1, dlb, 1.0f - lastblend, widfac, fac, &data); + else + rotateBevelPiece(cu, bevp, NULL, dlb, 0.0f, widfac, fac, &data); if (cu->bevobj && (cu->flag & CU_FILL_CAPS)) { if (a == 1) diff --git a/source/blender/blenkernel/intern/dynamicpaint.c b/source/blender/blenkernel/intern/dynamicpaint.c index d55848514cc..89d728c0419 100644 --- a/source/blender/blenkernel/intern/dynamicpaint.c +++ b/source/blender/blenkernel/intern/dynamicpaint.c @@ -32,6 +32,8 @@ #include "BLI_threads.h" #include "BLI_utildefines.h" +#include "BLF_translation.h" + #include "DNA_anim_types.h" #include "DNA_armature_types.h" #include "DNA_constraint_types.h" @@ -87,6 +89,9 @@ #include <omp.h> #endif +/* could enable at some point but for now there are far too many conversions */ +#pragma GCC diagnostic ignored "-Wdouble-promotion" + /* precalculated gaussian factors for 5x super sampling */ static float gaussianFactors[5] = {0.996849f, 0.596145f, @@ -120,8 +125,16 @@ static int neighY[8] = {0, 1, 1, 1, 0, -1, -1, -1}; /* drying limits */ #define MIN_WETNESS 0.001f #define MAX_WETNESS 5.0f -/* dissolve macro */ -#define VALUE_DISSOLVE(VALUE, TIME, SCALE, LOG) (VALUE) = (LOG) ? (VALUE) *(pow(MIN_WETNESS, 1.0f / (1.2f * ((float)(TIME)) / (SCALE)))) : (VALUE) -1.0f / (TIME)*(SCALE) + + +/* dissolve inline function */ +BLI_INLINE void value_dissolve(float *r_value, const float time, const float scale, const int is_log) +{ + *r_value = (is_log) ? + (*r_value) * (powf(MIN_WETNESS, 1.0f / (1.2f * time / scale))) : + (*r_value) - 1.0f / time * scale; +} + /***************************** Internal Structs ***************************/ @@ -569,7 +582,7 @@ static void scene_setSubframe(Scene *scene, float subframe) static int surface_getBrushFlags(DynamicPaintSurface *surface, Scene *scene) { Base *base = NULL; - GroupObject *go = NULL; + GroupObject *go = NULL; Object *brushObj = NULL; ModifierData *md = NULL; @@ -757,7 +770,7 @@ static void surfaceGenerateGrid(struct DynamicPaintSurface *surface) volume = td[0] * td[1] * td[2]; /* determine final grid size by trying to fit average 10.000 points per grid cell */ - dim_factor = (float)pow(volume / ((double)sData->total_points / 10000.0), 1.0 / (double)axis); + dim_factor = (float)pow((double)volume / ((double)sData->total_points / 10000.0), 1.0 / (double)axis); /* define final grid size using dim_factor, use min 3 for active axises */ for (i = 0; i < 3; i++) { @@ -848,7 +861,7 @@ static void surfaceGenerateGrid(struct DynamicPaintSurface *surface) grid->s_num = MEM_reallocN(grid->s_num, sizeof(int) * grid_cells); if (error || !grid->s_num) { - setError(surface->canvas, "Not enough free memory."); + setError(surface->canvas, N_("Not enough free memory")); freeGrid(sData); } } @@ -1235,7 +1248,7 @@ static void dynamicPaint_allocateSurfaceType(DynamicPaintSurface *surface) break; } - if (sData->type_data == NULL) setError(surface->canvas, "Not enough free memory!"); + if (sData->type_data == NULL) setError(surface->canvas, N_("Not enough free memory")); } static int surface_usesAdjDistance(DynamicPaintSurface *surface) @@ -1292,7 +1305,7 @@ static void dynamicPaint_initAdjacencyData(DynamicPaintSurface *surface, int for if (!ad->n_index || !ad->n_num || !ad->n_target || !temp_data) { dynamicPaint_freeAdjData(sData); if (temp_data) MEM_freeN(temp_data); - setError(surface->canvas, "Not enough free memory."); + setError(surface->canvas, N_("Not enough free memory")); return; } @@ -1762,10 +1775,10 @@ static DerivedMesh *dynamicPaint_Modifier_apply(DynamicPaintModifierData *pmd, } /* apply weights into a vertex group, if doesnt exists add a new layer */ - if (defgrp_index >= 0 && !dvert && (surface->output_name[0] != '\0')) + if (defgrp_index != -1 && !dvert && (surface->output_name[0] != '\0')) dvert = CustomData_add_layer_named(&result->vertData, CD_MDEFORMVERT, CD_CALLOC, NULL, sData->total_points, surface->output_name); - if (defgrp_index >= 0 && dvert) { + if (defgrp_index != -1 && dvert) { int i; for (i = 0; i < sData->total_points; i++) { MDeformVert *dv = &dvert[i]; @@ -2165,8 +2178,10 @@ int dynamicPaint_createUVSurface(DynamicPaintSurface *surface) int *final_index; int aa_samples; - if (!dm) return setError(canvas, "Canvas mesh not updated."); - if (surface->format != MOD_DPAINT_SURFACE_F_IMAGESEQ) return setError(canvas, "Can't bake non-\"image sequence\" formats."); + if (!dm) + return setError(canvas, N_("Canvas mesh not updated")); + if (surface->format != MOD_DPAINT_SURFACE_F_IMAGESEQ) + return setError(canvas, N_("Cannot bake non-'image sequence' formats")); numOfFaces = dm->getNumTessFaces(dm); mface = dm->getTessFaceArray(dm); @@ -2176,8 +2191,10 @@ int dynamicPaint_createUVSurface(DynamicPaintSurface *surface) tface = CustomData_get_layer_named(&dm->faceData, CD_MTFACE, uvname); /* Check for validity */ - if (!tface) return setError(canvas, "No UV data on canvas."); - if (surface->image_resolution < 16 || surface->image_resolution > 8192) return setError(canvas, "Invalid resolution."); + if (!tface) + return setError(canvas, N_("No UV data on canvas")); + if (surface->image_resolution < 16 || surface->image_resolution > 8192) + return setError(canvas, N_("Invalid resolution")); w = h = surface->image_resolution; @@ -2189,7 +2206,8 @@ int dynamicPaint_createUVSurface(DynamicPaintSurface *surface) /* Init data struct */ if (surface->data) dynamicPaint_freeSurfaceData(surface); sData = surface->data = MEM_callocN(sizeof(PaintSurfaceData), "PaintSurfaceData"); - if (!surface->data) return setError(canvas, "Not enough free memory."); + if (!surface->data) + return setError(canvas, N_("Not enough free memory")); aa_samples = (surface->flags & MOD_DPAINT_ANTIALIAS) ? 5 : 1; tempPoints = (struct PaintUVPoint *) MEM_callocN(w * h * sizeof(struct PaintUVPoint), "Temp PaintUVPoint"); @@ -2547,7 +2565,8 @@ int dynamicPaint_createUVSurface(DynamicPaintSurface *surface) } } } - if (error == 1) setError(canvas, "Not enough free memory."); + if (error == 1) + setError(canvas, N_("Not enough free memory")); if (faceBB) MEM_freeN(faceBB); if (tempPoints) MEM_freeN(tempPoints); @@ -2598,7 +2617,10 @@ void dynamicPaint_outputSurfaceImage(DynamicPaintSurface *surface, char *filenam int format = (surface->image_fileformat & MOD_DPAINT_IMGFORMAT_OPENEXR) ? R_IMF_IMTYPE_OPENEXR : R_IMF_IMTYPE_PNG; char output_file[FILE_MAX]; - if (!sData->type_data) { setError(surface->canvas, "Image save failed: Invalid surface."); return; } + if (!sData->type_data) { + setError(surface->canvas, N_("Image save failed: invalid surface")); + return; + } /* if selected format is openexr, but current build doesnt support one */ #ifndef WITH_OPENEXR if (format == R_IMF_IMTYPE_OPENEXR) format = R_IMF_IMTYPE_PNG; @@ -2612,7 +2634,10 @@ void dynamicPaint_outputSurfaceImage(DynamicPaintSurface *surface, char *filenam /* Init image buffer */ ibuf = IMB_allocImBuf(surface->image_resolution, surface->image_resolution, 32, IB_rectfloat); - if (ibuf == NULL) { setError(surface->canvas, "Image save failed: Not enough free memory."); return; } + if (ibuf == NULL) { + setError(surface->canvas, N_("Image save failed: not enough free memory")); + return; + } #pragma omp parallel for schedule(static) for (index = 0; index < sData->total_points; index++) { @@ -4473,7 +4498,7 @@ static void dynamicPaint_surfacePreStep(DynamicPaintSurface *surface, float time int i; float dry_ratio, f_color[4]; float p_wetness = pPoint->wetness; - VALUE_DISSOLVE(pPoint->wetness, surface->dry_speed, timescale, (surface->flags & MOD_DPAINT_DRY_LOG)); + value_dissolve(&pPoint->wetness, surface->dry_speed, timescale, (surface->flags & MOD_DPAINT_DRY_LOG)); if (pPoint->wetness < 0.0f) pPoint->wetness = 0.0f; if (pPoint->wetness < surface->color_dry_threshold) { @@ -4518,10 +4543,10 @@ static void dynamicPaint_surfacePreStep(DynamicPaintSurface *surface, float time } if (surface->flags & MOD_DPAINT_DISSOLVE) { - VALUE_DISSOLVE(pPoint->alpha, surface->diss_speed, timescale, (surface->flags & MOD_DPAINT_DISSOLVE_LOG)); + value_dissolve(&pPoint->alpha, surface->diss_speed, timescale, (surface->flags & MOD_DPAINT_DISSOLVE_LOG)); if (pPoint->alpha < 0.0f) pPoint->alpha = 0.0f; - VALUE_DISSOLVE(pPoint->e_alpha, surface->diss_speed, timescale, (surface->flags & MOD_DPAINT_DISSOLVE_LOG)); + value_dissolve(&pPoint->e_alpha, surface->diss_speed, timescale, (surface->flags & MOD_DPAINT_DISSOLVE_LOG)); if (pPoint->e_alpha < 0.0f) pPoint->e_alpha = 0.0f; } } @@ -4533,7 +4558,7 @@ static void dynamicPaint_surfacePreStep(DynamicPaintSurface *surface, float time float *point = &((float *)sData->type_data)[index]; /* log or linear */ - VALUE_DISSOLVE(*point, surface->diss_speed, timescale, (surface->flags & MOD_DPAINT_DISSOLVE_LOG)); + value_dissolve(point, surface->diss_speed, timescale, (surface->flags & MOD_DPAINT_DISSOLVE_LOG)); if (*point < 0.0f) *point = 0.0f; } } @@ -4649,7 +4674,7 @@ static int dynamicPaint_generateBakeData(DynamicPaintSurface *surface, Scene *sc if (bData->realCoord) MEM_freeN(bData->realCoord); if (canvas_verts) MEM_freeN(canvas_verts); - return setError(surface->canvas, "Not enough free memory."); + return setError(surface->canvas, N_("Not enough free memory")); } new_bdata = 1; @@ -4811,7 +4836,7 @@ static int dynamicPaint_doStep(Scene *scene, Object *ob, DynamicPaintSurface *su */ { Base *base = NULL; - GroupObject *go = NULL; + GroupObject *go = NULL; Object *brushObj = NULL; ModifierData *md = NULL; @@ -4878,7 +4903,7 @@ static int dynamicPaint_doStep(Scene *scene, Object *ob, DynamicPaintSurface *su /* Apply brush on the surface depending on it's collision type */ /* Particle brush: */ if (brush->collision == MOD_DPAINT_COL_PSYS) { - if (brush->psys && brush->psys->part && brush->psys->part->type == PART_EMITTER && + if (brush->psys && brush->psys->part && ELEM(brush->psys->part->type, PART_EMITTER, PART_FLUID) && psys_check_enabled(brushObj, brush->psys)) { @@ -4934,7 +4959,7 @@ static int dynamicPaint_doStep(Scene *scene, Object *ob, DynamicPaintSurface *su /* Allocate memory for surface previous points to read unchanged values from */ prevPoint = MEM_mallocN(sData->total_points * sizeof(struct PaintPoint), "PaintSurfaceDataCopy"); if (!prevPoint) - return setError(canvas, "Not enough free memory."); + return setError(canvas, N_("Not enough free memory")); /* Prepare effects and get number of required steps */ steps = dynamicPaint_prepareEffectStep(surface, scene, ob, &force, timescale); diff --git a/source/blender/blenkernel/intern/effect.c b/source/blender/blenkernel/intern/effect.c index 4f4bafd00b4..1f6db19ac27 100644 --- a/source/blender/blenkernel/intern/effect.c +++ b/source/blender/blenkernel/intern/effect.c @@ -54,6 +54,7 @@ #include "BLI_math.h" #include "BLI_blenlib.h" +#include "BLI_noise.h" #include "BLI_jitter.h" #include "BLI_rand.h" #include "BLI_utildefines.h" @@ -84,6 +85,7 @@ #include "BKE_object.h" #include "BKE_particle.h" #include "BKE_scene.h" +#include "BKE_smoke.h" #include "RE_render_ext.h" @@ -137,6 +139,9 @@ PartDeflect *object_add_collision_fields(int type) case PFIELD_TEXTURE: pd->f_size = 1.0f; break; + case PFIELD_SMOKEFLOW: + pd->f_flow = 1.0f; + break; } pd->flag = PFIELD_DO_LOCATION|PFIELD_DO_ROTATION; @@ -161,7 +166,7 @@ void free_partdeflect(PartDeflect *pd) pd->tex->id.us--; if (pd->rng) - rng_free(pd->rng); + BLI_rng_free(pd->rng); MEM_freeN(pd); } @@ -170,9 +175,9 @@ static void precalculate_effector(EffectorCache *eff) { unsigned int cfra = (unsigned int)(eff->scene->r.cfra >= 0 ? eff->scene->r.cfra : -eff->scene->r.cfra); if (!eff->pd->rng) - eff->pd->rng = rng_new(eff->pd->seed + cfra); + eff->pd->rng = BLI_rng_new(eff->pd->seed + cfra); else - rng_srandom(eff->pd->rng, eff->pd->seed + cfra); + BLI_rng_srandom(eff->pd->rng, eff->pd->seed + cfra); if (eff->pd->forcefield == PFIELD_GUIDE && eff->ob->type==OB_CURVE) { Curve *cu= eff->ob->data; @@ -200,7 +205,7 @@ static void precalculate_effector(EffectorCache *eff) float old_vel[3]; BKE_object_where_is_calc_time(eff->scene, eff->ob, cfra - 1.0f); - copy_v3_v3(old_vel, eff->ob->obmat[3]); + copy_v3_v3(old_vel, eff->ob->obmat[3]); BKE_object_where_is_calc_time(eff->scene, eff->ob, cfra); sub_v3_v3v3(eff->velocity, eff->ob->obmat[3], old_vel); } @@ -450,8 +455,8 @@ static float eff_calc_visibility(ListBase *colliders, EffectorCache *eff, Effect // noise function for wind e.g. static float wind_func(struct RNG *rng, float strength) { - int random = (rng_getInt(rng)+1) % 128; // max 2357 - float force = rng_getFloat(rng) + 1.0f; + int random = (BLI_rng_get_int(rng)+1) % 128; // max 2357 + float force = BLI_rng_get_float(rng) + 1.0f; float ret; float sign = 0; @@ -713,8 +718,8 @@ static void get_effector_tot(EffectorCache *eff, EffectorData *efd, EffectedPoin if (eff->pd->forcefield == PFIELD_CHARGE) { /* Only the charge of the effected particle is used for - * interaction, not fall-offs. If the fall-offs aren't the - * same this will be unphysical, but for animation this + * interaction, not fall-offs. If the fall-offs aren't the + * same this will be unphysical, but for animation this * could be the wanted behavior. If you want physical * correctness the fall-off should be spherical 2.0 anyways. */ @@ -823,7 +828,7 @@ static void do_physical_effector(EffectorCache *eff, EffectorData *efd, Effected { PartDeflect *pd = eff->pd; RNG *rng = pd->rng; - float force[3]={0, 0, 0}; + float force[3] = {0, 0, 0}; float temp[3]; float fac; float strength = pd->f_strength; @@ -922,12 +927,27 @@ static void do_physical_effector(EffectorCache *eff, EffectorData *efd, Effected mul_v3_fl(force, -efd->falloff * fac * (strength * fac + damp)); break; + case PFIELD_SMOKEFLOW: + zero_v3(force); + if (pd->f_source) { + float density; + if ((density = smoke_get_velocity_at(pd->f_source, point->loc, force)) >= 0.0f) { + float influence = strength * efd->falloff; + if (pd->flag & PFIELD_SMOKE_DENSITY) + influence *= density; + mul_v3_fl(force, influence); + /* apply flow */ + madd_v3_v3fl(total_force, point->vel, -pd->f_flow * influence); + } + } + break; + } if (pd->flag & PFIELD_DO_LOCATION) { madd_v3_v3fl(total_force, force, 1.0f/point->vel_to_sec); - if (ELEM(pd->forcefield, PFIELD_HARMONIC, PFIELD_DRAG)==0 && pd->f_flow != 0.0f) { + if (ELEM3(pd->forcefield, PFIELD_HARMONIC, PFIELD_DRAG, PFIELD_SMOKEFLOW)==0 && pd->f_flow != 0.0f) { madd_v3_v3fl(total_force, point->vel, -pd->f_flow * efd->falloff); } } @@ -993,12 +1013,14 @@ void pdDoEffectors(ListBase *effectors, ListBase *colliders, EffectorWeights *we if (efd.falloff > 0.0f) efd.falloff *= eff_calc_visibility(colliders, eff, &efd, point); - if (efd.falloff <= 0.0f) - ; /* don't do anything */ - else if (eff->pd->forcefield == PFIELD_TEXTURE) + if (efd.falloff <= 0.0f) { + /* don't do anything */ + } + else if (eff->pd->forcefield == PFIELD_TEXTURE) { do_texture_effector(eff, &efd, point, force); + } else { - float temp1[3]={0, 0, 0}, temp2[3]; + float temp1[3] = {0, 0, 0}, temp2[3]; copy_v3_v3(temp1, force); do_physical_effector(eff, &efd, point, force); diff --git a/source/blender/blenkernel/intern/fcurve.c b/source/blender/blenkernel/intern/fcurve.c index 2dbc63e6944..ec61311d89e 100644 --- a/source/blender/blenkernel/intern/fcurve.c +++ b/source/blender/blenkernel/intern/fcurve.c @@ -504,14 +504,14 @@ short calc_fcurve_bounds(FCurve *fcu, float *xmin, float *xmax, float *ymin, flo xmaxv = MAX3(xmaxv, bezt_last->vec[1][0], bezt_last->vec[2][0]); } else { - xminv = minf(xminv, bezt_first->vec[1][0]); - xmaxv = maxf(xmaxv, bezt_last->vec[1][0]); + xminv = min_ff(xminv, bezt_first->vec[1][0]); + xmaxv = max_ff(xmaxv, bezt_last->vec[1][0]); } } } /* only loop over keyframes to find extents for values if needed */ - if (ymin || ymax) { + if (ymin || ymax) { BezTriple *bezt; for (bezt = fcu->bezt, i = 0; i < fcu->totvert; bezt++, i++) { @@ -521,8 +521,8 @@ short calc_fcurve_bounds(FCurve *fcu, float *xmin, float *xmax, float *ymin, flo ymaxv = MAX4(ymaxv, bezt->vec[1][1], bezt->vec[0][1], bezt->vec[2][1]); } else { - yminv = minf(yminv, bezt->vec[1][1]); - ymaxv = maxf(ymaxv, bezt->vec[1][1]); + yminv = min_ff(yminv, bezt->vec[1][1]); + ymaxv = max_ff(ymaxv, bezt->vec[1][1]); } foundvert = TRUE; @@ -533,8 +533,8 @@ short calc_fcurve_bounds(FCurve *fcu, float *xmin, float *xmax, float *ymin, flo else if (fcu->fpt) { /* frame range can be directly calculated from end verts */ if (xmin || xmax) { - xminv = minf(xminv, fcu->fpt[0].vec[0]); - xmaxv = maxf(xmaxv, fcu->fpt[fcu->totvert - 1].vec[0]); + xminv = min_ff(xminv, fcu->fpt[0].vec[0]); + xmaxv = max_ff(xmaxv, fcu->fpt[fcu->totvert - 1].vec[0]); } /* only loop over keyframes to find extents for values if needed */ @@ -591,15 +591,15 @@ void calc_fcurve_range(FCurve *fcu, float *start, float *end, if (bezt_first) { BLI_assert(bezt_last != NULL); - min = minf(min, bezt_first->vec[1][0]); - max = maxf(max, bezt_last->vec[1][0]); + min = min_ff(min, bezt_first->vec[1][0]); + max = max_ff(max, bezt_last->vec[1][0]); foundvert = TRUE; } } else if (fcu->fpt) { - min = minf(min, fcu->fpt[0].vec[0]); - max = maxf(max, fcu->fpt[fcu->totvert - 1].vec[0]); + min = min_ff(min, fcu->fpt[0].vec[0]); + max = max_ff(max, fcu->fpt[fcu->totvert - 1].vec[0]); foundvert = TRUE; } @@ -1039,7 +1039,7 @@ static float dtar_get_prop_val(ChannelDriver *driver, DriverTarget *dtar) if (RNA_path_resolve_full(&id_ptr, dtar->rna_path, &ptr, &prop, &index)) { if (RNA_property_array_check(prop)) { /* array */ - if (index < RNA_property_array_length(&ptr, prop)) { + if (index < RNA_property_array_length(&ptr, prop)) { switch (RNA_property_type(prop)) { case PROP_BOOLEAN: value = (float)RNA_property_boolean_get_index(&ptr, prop, index); @@ -1143,7 +1143,7 @@ static float dvar_eval_rotDiff(ChannelDriver *driver, DriverVar *dvar) /* stop here... */ return 0.0f; - } + } /* use the final posed locations */ mat4_to_quat(q1, pchan->pose_mat); @@ -1549,7 +1549,7 @@ ChannelDriver *fcurve_copy_driver(ChannelDriver *driver) for (dvar = ndriver->variables.first; dvar; dvar = dvar->next) { /* need to go over all targets so that we don't leave any dangling paths */ DRIVER_TARGETS_LOOPER(dvar) - { + { /* make a copy of target's rna path if available */ if (dtar->rna_path) dtar->rna_path = MEM_dupallocN(dtar->rna_path); @@ -1832,7 +1832,7 @@ static int findzero(float x, float q0, float q1, float q2, float q3, float *o) return 1; } - return 0; + return 0; } } @@ -1916,7 +1916,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime cvalue = prevbezt->vec[1][1]; } } - } + } else { /* Use the first handle (earlier) of first BezTriple to calculate the * gradient and thus the value of the curve at evaltime @@ -1968,7 +1968,7 @@ static float fcurve_eval_keyframes(FCurve *fcu, BezTriple *bezts, float evaltime cvalue = lastbezt->vec[1][1]; } } - } + } else { /* Use the gradient of the second handle (later) of last BezTriple to calculate the * gradient and thus the value of the curve at evaltime diff --git a/source/blender/blenkernel/intern/fluidsim.c b/source/blender/blenkernel/intern/fluidsim.c index 9be599ac66c..efc9869c5ca 100644 --- a/source/blender/blenkernel/intern/fluidsim.c +++ b/source/blender/blenkernel/intern/fluidsim.c @@ -41,7 +41,7 @@ #include "DNA_mesh_types.h" #include "DNA_meshdata_types.h" #include "DNA_object_fluidsim.h" -#include "DNA_object_force.h" // for pointcache +#include "DNA_object_force.h" // for pointcache #include "DNA_object_types.h" #include "DNA_particle_types.h" #include "DNA_scene_types.h" // N_T @@ -66,14 +66,14 @@ //------------------------------------------------------------------------------- void initElbeemMesh(struct Scene *scene, struct Object *ob, - int *numVertices, float **vertices, - int *numTriangles, int **triangles, - int useGlobalCoords, int modifierIndex) + int *numVertices, float **vertices, + int *numTriangles, int **triangles, + int useGlobalCoords, int modifierIndex) { DerivedMesh *dm = NULL; MVert *mvert; MFace *mface; - int countTris=0, i, totvert, totface; + int countTris = 0, i, totvert, totface; float *verts; int *tris; @@ -87,35 +87,35 @@ void initElbeemMesh(struct Scene *scene, struct Object *ob, totface = dm->getNumTessFaces(dm); *numVertices = totvert; - verts = MEM_callocN(totvert*3*sizeof(float), "elbeemmesh_vertices"); - for (i=0; i<totvert; i++) { - copy_v3_v3(&verts[i*3], mvert[i].co); - if (useGlobalCoords) { mul_m4_v3(ob->obmat, &verts[i*3]); } + verts = MEM_callocN(totvert * 3 * sizeof(float), "elbeemmesh_vertices"); + for (i = 0; i < totvert; i++) { + copy_v3_v3(&verts[i * 3], mvert[i].co); + if (useGlobalCoords) { mul_m4_v3(ob->obmat, &verts[i * 3]); } } *vertices = verts; - for (i=0; i<totface; i++) { + for (i = 0; i < totface; i++) { countTris++; if (mface[i].v4) { countTris++; } } *numTriangles = countTris; - tris = MEM_callocN(countTris*3*sizeof(int), "elbeemmesh_triangles"); + tris = MEM_callocN(countTris * 3 * sizeof(int), "elbeemmesh_triangles"); countTris = 0; - for (i=0; i<totface; i++) { + for (i = 0; i < totface; i++) { int face[4]; face[0] = mface[i].v1; face[1] = mface[i].v2; face[2] = mface[i].v3; face[3] = mface[i].v4; - tris[countTris*3+0] = face[0]; - tris[countTris*3+1] = face[1]; - tris[countTris*3+2] = face[2]; + tris[countTris * 3 + 0] = face[0]; + tris[countTris * 3 + 1] = face[1]; + tris[countTris * 3 + 2] = face[2]; countTris++; if (face[3]) { - tris[countTris*3+0] = face[0]; - tris[countTris*3+1] = face[2]; - tris[countTris*3+2] = face[3]; + tris[countTris * 3 + 0] = face[0]; + tris[countTris * 3 + 1] = face[2]; + tris[countTris * 3 + 2] = face[3]; countTris++; } } diff --git a/source/blender/blenkernel/intern/fmodifier.c b/source/blender/blenkernel/intern/fmodifier.c index 68321076398..2b393b4d90b 100644 --- a/source/blender/blenkernel/intern/fmodifier.c +++ b/source/blender/blenkernel/intern/fmodifier.c @@ -42,6 +42,7 @@ #include "BLF_translation.h" #include "BLI_blenlib.h" +#include "BLI_noise.h" #include "BLI_math.h" /* windows needs for M_PI */ #include "BLI_utildefines.h" @@ -155,7 +156,7 @@ static void fcm_generator_verify(FModifier *fcm) /* free the old data */ MEM_freeN(data->coefficients); - } + } /* set the new data */ data->coefficients = nc; @@ -181,7 +182,7 @@ static void fcm_generator_verify(FModifier *fcm) /* free the old data */ MEM_freeN(data->coefficients); - } + } /* set the new data */ data->coefficients = nc; @@ -275,7 +276,7 @@ static FModifierTypeInfo FMI_GENERATOR = { /* Built-In Function Generator F-Curve Modifier --------------------------- */ /* This uses the general equation for equations: - * y = amplitude * fn(phase_multiplier*x + phase_offset) + y_offset + * y = amplitude * fn(phase_multiplier * x + phase_offset) + y_offset * * where amplitude, phase_multiplier/offset, y_offset are user-defined coefficients, * x is the evaluation 'time', and 'y' is the resultant value @@ -315,7 +316,7 @@ static void fcm_fn_generator_evaluate(FCurve *UNUSED(fcu), FModifier *fcm, float * WARNING: must perform special argument validation hereto guard against crashes */ switch (data->type) { - /* simple ones */ + /* simple ones */ case FCM_GENERATOR_FN_SIN: /* sine wave */ fn = sin; break; @@ -1021,7 +1022,7 @@ FModifier *add_fmodifier(ListBase *modifiers, int type) 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); /* return modifier for further editing */ @@ -1098,7 +1099,7 @@ int remove_fmodifier(ListBase *modifiers, FModifier *fcm) if (modifiers) { BLI_freelinkN(modifiers, fcm); return 1; - } + } else { /* XXX this case can probably be removed some day, as it shouldn't happen... */ printf("remove_fmodifier() - no modifier stack given\n"); diff --git a/source/blender/blenkernel/intern/font.c b/source/blender/blenkernel/intern/font.c index 8b35974ea62..d4634748c71 100644 --- a/source/blender/blenkernel/intern/font.c +++ b/source/blender/blenkernel/intern/font.c @@ -177,7 +177,7 @@ static VFontData *vfont_get_data(Main *bmain, VFont *vfont) } } - return vfont->data; + return vfont->data; } VFont *BKE_vfont_load(Main *bmain, const char *name) @@ -306,23 +306,23 @@ static void build_underline(Curve *cu, float x1, float y1, float x2, float y2, i nu2->bp = bp; nu2->bp[0].vec[0] = x1; - nu2->bp[0].vec[1] = y1; + nu2->bp[0].vec[1] = y1; nu2->bp[0].vec[2] = 0; nu2->bp[0].vec[3] = 1.0f; nu2->bp[1].vec[0] = x2; nu2->bp[1].vec[1] = y1; - nu2->bp[1].vec[2] = 0; + nu2->bp[1].vec[2] = 0; nu2->bp[1].vec[3] = 1.0f; nu2->bp[2].vec[0] = x2; - nu2->bp[2].vec[1] = y2; + nu2->bp[2].vec[1] = y2; nu2->bp[2].vec[2] = 0; nu2->bp[2].vec[3] = 1.0f; nu2->bp[3].vec[0] = x1; nu2->bp[3].vec[1] = y2; - nu2->bp[3].vec[2] = 0; + nu2->bp[3].vec[2] = 0; nu2->bp[3].vec[3] = 1.0f; - BLI_addtail(&(cu->nurb), nu2); + BLI_addtail(&(cu->nurb), nu2); } @@ -545,7 +545,7 @@ struct CharTrans *BKE_vfont_to_curve(Main *bmain, Scene *scene, Object *ob, int /* The VFont Data can not be found */ if (!vfd) { if (mem) - MEM_freeN(mem); + MEM_freeN(mem); return NULL; } @@ -671,7 +671,7 @@ makebreak: yof -= linedist; - maxlen = maxf(maxlen, (xof - tb->x / cu->fsize)); + maxlen = max_ff(maxlen, (xof - tb->x / cu->fsize)); linedata[lnr] = xof - tb->x / cu->fsize; linedata2[lnr] = cnr; linedata3[lnr] = tb->w / cu->fsize; @@ -731,7 +731,7 @@ makebreak: if (ascii == 32) { wsfac = cu->wordspace; wsnr++; - } + } else { wsfac = 1.0f; } @@ -754,7 +754,7 @@ makebreak: for (i = 0; i <= slen; i++, tmp++, ct++) { ascii = *tmp; if (ascii == '\n' || ascii == '\r' || ct->dobreak) cu->lines++; - } + } /* linedata is now: width of line * linedata2 is now: number of characters @@ -792,7 +792,7 @@ makebreak: // } ct++; } - } + } else if ((cu->spacemode == CU_JUSTIFY) && (cu->tb[0].w != 0.0f)) { float curofs = 0.0f; for (i = 0; i <= slen; i++) { @@ -928,8 +928,12 @@ makebreak: * 3: curs down */ ct = chartransdata + cu->pos; - if ((mode == FO_CURSUP || mode == FO_PAGEUP) && ct->linenr == 0) ; - else if ((mode == FO_CURSDOWN || mode == FO_PAGEDOWN) && ct->linenr == lnr) ; + if ((mode == FO_CURSUP || mode == FO_PAGEUP) && ct->linenr == 0) { + /* pass */ + } + else if ((mode == FO_CURSDOWN || mode == FO_PAGEDOWN) && ct->linenr == lnr) { + /* pass */ + } else { switch (mode) { case FO_CURSUP: lnr = ct->linenr - 1; break; diff --git a/source/blender/blenkernel/intern/gpencil.c b/source/blender/blenkernel/intern/gpencil.c index 84871375788..a7d0152a799 100644 --- a/source/blender/blenkernel/intern/gpencil.c +++ b/source/blender/blenkernel/intern/gpencil.c @@ -87,6 +87,7 @@ void free_gpencil_frames(bGPDlayer *gpl) free_gpencil_strokes(gpf); BLI_freelinkN(&gpl->frames, gpf); } + gpl->actframe = NULL; } /* Free all of the gp-layers for a viewport (list should be &gpd->layers or so) */ @@ -516,7 +517,7 @@ void gpencil_layer_delete(bGPdata *gpd, bGPDlayer *gpl) if (ELEM(NULL, gpd, gpl)) return; - /* free layer */ + /* free layer */ free_gpencil_frames(gpl); BLI_freelinkN(&gpd->layers, gpl); } diff --git a/source/blender/blenkernel/intern/group.c b/source/blender/blenkernel/intern/group.c index 634428d9194..20d874e7243 100644 --- a/source/blender/blenkernel/intern/group.c +++ b/source/blender/blenkernel/intern/group.c @@ -98,7 +98,7 @@ void BKE_group_unlink(Group *group) base->object->flag &= ~OB_FROMGROUP; base->flag &= ~OB_FROMGROUP; } - } + } for (srl = sce->r.layers.first; srl; srl = srl->next) { if (srl->light_override == group) diff --git a/source/blender/blenkernel/intern/idprop.c b/source/blender/blenkernel/intern/idprop.c index 8ceaab56f83..5dd0f08dc71 100644 --- a/source/blender/blenkernel/intern/idprop.c +++ b/source/blender/blenkernel/intern/idprop.c @@ -492,6 +492,30 @@ void IDP_ReplaceInGroup(IDProperty *group, IDProperty *prop) } } +/* + * If a property is missing in \a dest, add it. + */ +void IDP_MergeGroup(IDProperty *dest, IDProperty *src, const int do_overwrite) +{ + IDProperty *prop; + + if (do_overwrite) { + for (prop = src->data.group.first; prop; prop = prop->next) { + IDProperty *copy = IDP_CopyProperty(prop); + IDP_ReplaceInGroup(dest, copy); + } + } + else { + for (prop = src->data.group.first; prop; prop = prop->next) { + if (IDP_GetPropertyFromGroup(dest, prop->name) == NULL) { + IDProperty *copy = IDP_CopyProperty(prop); + dest->len++; + BLI_addtail(&dest->data.group, copy); + } + } + } +} + /* returns 0 if an id property with the same name exists and it failed, * or 1 if it succeeded in adding to the group.*/ int IDP_AddToGroup(IDProperty *group, IDProperty *prop) @@ -608,60 +632,77 @@ IDProperty *IDP_GetProperties(ID *id, int create_if_needed) } } -int IDP_EqualsProperties(IDProperty *prop1, IDProperty *prop2) +/** + * \param is_strict When FALSE treat missing items as a match */ +int IDP_EqualsProperties_ex(IDProperty *prop1, IDProperty *prop2, const int is_strict) { if (prop1 == NULL && prop2 == NULL) return 1; else if (prop1 == NULL || prop2 == NULL) - return 0; + return is_strict ? 0 : 1; else if (prop1->type != prop2->type) return 0; - if (prop1->type == IDP_INT) - return (IDP_Int(prop1) == IDP_Int(prop2)); - else if (prop1->type == IDP_FLOAT) - return (IDP_Float(prop1) == IDP_Float(prop2)); - else if (prop1->type == IDP_DOUBLE) - return (IDP_Double(prop1) == IDP_Double(prop2)); - else if (prop1->type == IDP_STRING) - return ((prop1->len == prop2->len) && strncmp(IDP_String(prop1), IDP_String(prop2), prop1->len) == 0); - else if (prop1->type == IDP_ARRAY) { - if (prop1->len == prop2->len && prop1->subtype == prop2->subtype) - return memcmp(IDP_Array(prop1), IDP_Array(prop2), idp_size_table[(int)prop1->subtype] * prop1->len); - else - return 0; - } - else if (prop1->type == IDP_GROUP) { - IDProperty *link1, *link2; - - if (BLI_countlist(&prop1->data.group) != BLI_countlist(&prop2->data.group)) - return 0; - - for (link1 = prop1->data.group.first; link1; link1 = link1->next) { - link2 = IDP_GetPropertyFromGroup(prop2, link1->name); - - if (!IDP_EqualsProperties(link1, link2)) + switch (prop1->type) { + case IDP_INT: + return (IDP_Int(prop1) == IDP_Int(prop2)); + case IDP_FLOAT: + return (IDP_Float(prop1) == IDP_Float(prop2)); + case IDP_DOUBLE: + return (IDP_Double(prop1) == IDP_Double(prop2)); + case IDP_STRING: + return ((prop1->len == prop2->len) && strncmp(IDP_String(prop1), IDP_String(prop2), prop1->len) == 0); + case IDP_ARRAY: + if (prop1->len == prop2->len && prop1->subtype == prop2->subtype) { + return memcmp(IDP_Array(prop1), IDP_Array(prop2), idp_size_table[(int)prop1->subtype] * prop1->len); + } + else { return 0; - } + } + case IDP_GROUP: + { + IDProperty *link1, *link2; - return 1; - } - else if (prop1->type == IDP_IDPARRAY) { - IDProperty *array1 = IDP_IDPArray(prop1); - IDProperty *array2 = IDP_IDPArray(prop2); - int i; + if (is_strict && BLI_countlist(&prop1->data.group) != BLI_countlist(&prop2->data.group)) + return 0; - if (prop1->len != prop2->len) - return 0; - - for (i = 0; i < prop1->len; i++) - if (!IDP_EqualsProperties(&array1[i], &array2[i])) + for (link1 = prop1->data.group.first; link1; link1 = link1->next) { + link2 = IDP_GetPropertyFromGroup(prop2, link1->name); + + if (!IDP_EqualsProperties_ex(link1, link2, is_strict)) + return 0; + } + + return 1; + } + case IDP_IDPARRAY: + { + IDProperty *array1 = IDP_IDPArray(prop1); + IDProperty *array2 = IDP_IDPArray(prop2); + int i; + + if (prop1->len != prop2->len) return 0; + + for (i = 0; i < prop1->len; i++) + if (!IDP_EqualsProperties(&array1[i], &array2[i])) + return 0; + return 1; + } + default: + /* should never get here */ + BLI_assert(0); + break; } - + return 1; } +int IDP_EqualsProperties(IDProperty *prop1, IDProperty *prop2) +{ + return IDP_EqualsProperties_ex(prop1, prop2, TRUE); +} + /* 'val' is never NULL, don't check */ IDProperty *IDP_New(const int type, const IDPropertyTemplate *val, const char *name) { diff --git a/source/blender/blenkernel/intern/image.c b/source/blender/blenkernel/intern/image.c index c003a86a0b7..55d37c91859 100644 --- a/source/blender/blenkernel/intern/image.c +++ b/source/blender/blenkernel/intern/image.c @@ -1063,6 +1063,7 @@ char BKE_imtype_valid_channels(const char imtype) case R_IMF_IMTYPE_DDS: case R_IMF_IMTYPE_JP2: case R_IMF_IMTYPE_QUICKTIME: + case R_IMF_IMTYPE_DPX: chan_flag |= IMA_CHAN_FLAG_ALPHA; } @@ -1091,10 +1092,11 @@ char BKE_imtype_valid_depths(const char imtype) return R_IMF_CHAN_DEPTH_16 | R_IMF_CHAN_DEPTH_32; case R_IMF_IMTYPE_MULTILAYER: return R_IMF_CHAN_DEPTH_32; - /* eeh, cineone does some strange 10bits per channel */ + /* eeh, cineon does some strange 10bits per channel */ case R_IMF_IMTYPE_DPX: + return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_10 | R_IMF_CHAN_DEPTH_12 | R_IMF_CHAN_DEPTH_16; case R_IMF_IMTYPE_CINEON: - return R_IMF_CHAN_DEPTH_12; + return R_IMF_CHAN_DEPTH_10; case R_IMF_IMTYPE_JP2: return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_12 | R_IMF_CHAN_DEPTH_16; /* most formats are 8bit only */ @@ -1559,7 +1561,7 @@ void BKE_stamp_buf(Scene *scene, Object *camera, unsigned char *rect, float *rec /* also a little of space to the background. */ buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display, - x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y); + x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y); /* and draw the text. */ BLF_position(mono, x, y + y_ofs, 0.0); @@ -1576,7 +1578,7 @@ void BKE_stamp_buf(Scene *scene, Object *camera, unsigned char *rect, float *rec /* and space for background. */ buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display, - 0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y); + 0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y); BLF_position(mono, x, y + y_ofs, 0.0); BLF_draw_buffer(mono, stamp_data.note); @@ -1592,7 +1594,7 @@ void BKE_stamp_buf(Scene *scene, Object *camera, unsigned char *rect, float *rec /* and space for background. */ buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display, - 0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y); + 0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y); BLF_position(mono, x, y + y_ofs, 0.0); BLF_draw_buffer(mono, stamp_data.date); @@ -1608,7 +1610,7 @@ void BKE_stamp_buf(Scene *scene, Object *camera, unsigned char *rect, float *rec /* and space for background. */ buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display, - 0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y); + 0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y); BLF_position(mono, x, y + y_ofs, 0.0); BLF_draw_buffer(mono, stamp_data.rendertime); @@ -1623,7 +1625,7 @@ void BKE_stamp_buf(Scene *scene, Object *camera, unsigned char *rect, float *rec /* extra space for background. */ buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display, - x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y); + x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y); /* and pad the text. */ BLF_position(mono, x, y + y_ofs, 0.0); @@ -1639,7 +1641,7 @@ void BKE_stamp_buf(Scene *scene, Object *camera, unsigned char *rect, float *rec /* extra space for background */ buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display, - x - BUFF_MARGIN_X, y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y); + x - BUFF_MARGIN_X, y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y); /* and pad the text. */ BLF_position(mono, x, y + y_ofs, 0.0); @@ -1654,7 +1656,7 @@ void BKE_stamp_buf(Scene *scene, Object *camera, unsigned char *rect, float *rec /* extra space for background. */ buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display, - x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y); + x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y); /* and pad the text. */ BLF_position(mono, x, y + y_ofs, 0.0); @@ -1669,7 +1671,7 @@ void BKE_stamp_buf(Scene *scene, Object *camera, unsigned char *rect, float *rec /* extra space for background. */ buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display, - x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y); + x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y); BLF_position(mono, x, y + y_ofs, 0.0); BLF_draw_buffer(mono, stamp_data.camera); @@ -1682,7 +1684,7 @@ void BKE_stamp_buf(Scene *scene, Object *camera, unsigned char *rect, float *rec /* extra space for background. */ buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display, - x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y); + x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y); BLF_position(mono, x, y + y_ofs, 0.0); BLF_draw_buffer(mono, stamp_data.cameralens); } @@ -1695,7 +1697,7 @@ void BKE_stamp_buf(Scene *scene, Object *camera, unsigned char *rect, float *rec /* extra space for background. */ buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display, - x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y); + x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y); /* and pad the text. */ BLF_position(mono, x, y + y_ofs, 0.0); @@ -1711,7 +1713,7 @@ void BKE_stamp_buf(Scene *scene, Object *camera, unsigned char *rect, float *rec /* extra space for background. */ buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display, - x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y); + x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y); BLF_position(mono, x, y + y_ofs, 0.0); BLF_draw_buffer(mono, stamp_data.strip); @@ -1825,9 +1827,33 @@ int BKE_imbuf_write(ImBuf *ibuf, const char *name, ImageFormatData *imf) #ifdef WITH_CINEON else if (imtype == R_IMF_IMTYPE_CINEON) { ibuf->ftype = CINEON; + if (imf->cineon_flag & R_IMF_CINEON_FLAG_LOG) { + ibuf->ftype |= CINEON_LOG; + } + if (imf->depth == R_IMF_CHAN_DEPTH_16) { + ibuf->ftype |= CINEON_16BIT; + } + else if (imf->depth == R_IMF_CHAN_DEPTH_12) { + ibuf->ftype |= CINEON_12BIT; + } + else if (imf->depth == R_IMF_CHAN_DEPTH_10) { + ibuf->ftype |= CINEON_10BIT; + } } else if (imtype == R_IMF_IMTYPE_DPX) { ibuf->ftype = DPX; + if (imf->cineon_flag & R_IMF_CINEON_FLAG_LOG) { + ibuf->ftype |= CINEON_LOG; + } + if (imf->depth == R_IMF_CHAN_DEPTH_16) { + ibuf->ftype |= CINEON_16BIT; + } + else if (imf->depth == R_IMF_CHAN_DEPTH_12) { + ibuf->ftype |= CINEON_12BIT; + } + else if (imf->depth == R_IMF_CHAN_DEPTH_10) { + ibuf->ftype |= CINEON_10BIT; + } } #endif else if (imtype == R_IMF_IMTYPE_TARGA) { @@ -2120,6 +2146,15 @@ void BKE_image_signal(Image *ima, ImageUser *iuser, int signal) } } break; + case IMA_SIGNAL_COLORMANAGE: + image_free_buffers(ima); + + ima->ok = 1; + + if (iuser) + iuser->ok = 1; + + break; } /* don't use notifiers because they are not 100% sure to succeeded @@ -2617,11 +2652,21 @@ static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **lock_ /* free rect buffer if float buffer changes, so it can be recreated with * the updated result, and also in case we got byte buffer from sequencer, * so we don't keep reference to freed buffer */ - if (ibuf->rect_float != rectf || rect || !rectf) + if (ibuf->rect_float != rectf || rect) imb_freerectImBuf(ibuf); - if (rect) + if (rect) { ibuf->rect = rect; + } + else { + /* byte buffer of render result has been freed, make sure image buffers + * does not reference to this buffer anymore + * 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) + ibuf->rect = NULL; + } if (rectf) { ibuf->rect_float = rectf; diff --git a/source/blender/blenkernel/intern/image_gen.c b/source/blender/blenkernel/intern/image_gen.c index 37572eebed6..468a88775c6 100644 --- a/source/blender/blenkernel/intern/image_gen.c +++ b/source/blender/blenkernel/intern/image_gen.c @@ -244,7 +244,7 @@ static void checker_board_color_tint(unsigned char *rect, float *rect_float, int } } - } + } } static void checker_board_grid_fill(unsigned char *rect, float *rect_float, int width, int height, float blend) diff --git a/source/blender/blenkernel/intern/implicit.c b/source/blender/blenkernel/intern/implicit.c index ebb95a6561e..90cd7bc2df5 100644 --- a/source/blender/blenkernel/intern/implicit.c +++ b/source/blender/blenkernel/intern/implicit.c @@ -590,7 +590,7 @@ DO_INLINE void mul_bfmatrix_lfvector( float (*to)[3], fmatrix3x3 *from, lfVector for (i = from[0].vcount; i < from[0].vcount+from[0].scount; i++) { muladd_fmatrix_fvector(to[from[i].c], from[i].m, fLongVector[from[i].r]); } - } + } #pragma omp section { for (i = 0; i < from[0].vcount+from[0].scount; i++) { @@ -623,7 +623,7 @@ DO_INLINE void add_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from, fmatrix /* process diagonal elements */ for (i = 0; i < matrix[0].vcount+matrix[0].scount; i++) { - add_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m); + add_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m); } } @@ -634,7 +634,7 @@ DO_INLINE void addadd_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from, fmat /* process diagonal elements */ for (i = 0; i < matrix[0].vcount+matrix[0].scount; i++) { - addadd_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m); + addadd_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m); } } @@ -645,7 +645,7 @@ DO_INLINE void subadd_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from, fmat /* process diagonal elements */ for (i = 0; i < matrix[0].vcount+matrix[0].scount; i++) { - subadd_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m); + subadd_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m); } } @@ -656,7 +656,7 @@ DO_INLINE void sub_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from, fmatrix /* process diagonal elements */ for (i = 0; i < matrix[0].vcount+matrix[0].scount; i++) { - sub_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m); + sub_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m); } } @@ -667,7 +667,7 @@ DO_INLINE void sub_bfmatrix_Smatrix( fmatrix3x3 *to, fmatrix3x3 *from, fmatrix3 /* process diagonal elements */ for (i = 0; i < matrix[0].vcount; i++) { - sub_fmatrix_fmatrix(to[matrix[i].c].m, from[matrix[i].c].m, matrix[i].m); + sub_fmatrix_fmatrix(to[matrix[i].c].m, from[matrix[i].c].m, matrix[i].m); } } @@ -678,7 +678,7 @@ DO_INLINE void addsub_bfmatrix_bfmatrix( fmatrix3x3 *to, fmatrix3x3 *from, fmat /* process diagonal elements */ for (i = 0; i < matrix[0].vcount+matrix[0].scount; i++) { - addsub_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m); + addsub_fmatrix_fmatrix(to[i].m, from[i].m, matrix[i].m); } } @@ -691,7 +691,7 @@ DO_INLINE void subadd_bfmatrixS_bfmatrixS( fmatrix3x3 *to, fmatrix3x3 *from, flo /* process diagonal elements */ for (i = 0; i < matrix[0].vcount+matrix[0].scount; i++) { - subadd_fmatrixS_fmatrixS(to[i].m, from[i].m, aS, matrix[i].m, bS); + subadd_fmatrixS_fmatrixS(to[i].m, from[i].m, aS, matrix[i].m, bS); } } @@ -711,7 +711,7 @@ static void update_matrixS(ClothVertex *verts, int numverts, fmatrix3x3 *S) int i = 0; /* Clear matrix from old vertex constraints */ - for(i = 0; i < S[0].vcount; i++) + for (i = 0; i < S[0].vcount; i++) S[i].c = S[i].r = 0; /* Set new vertex constraints */ @@ -749,7 +749,7 @@ int implicit_init(Object *UNUSED(ob), ClothModifierData *clmd) id = (Implicit_Data *)MEM_callocN(sizeof(Implicit_Data), "implicit vecmat"); cloth->implicit = id; - /* process diagonal elements */ + /* process diagonal elements */ id->A = create_bfmatrix(cloth->numverts, cloth->numsprings); id->dFdV = create_bfmatrix(cloth->numverts, cloth->numsprings); id->dFdX = create_bfmatrix(cloth->numverts, cloth->numsprings); @@ -844,41 +844,40 @@ int implicit_free(ClothModifierData *clmd) DO_INLINE float fb(float length, float L) { - float x = length/L; - return (-11.541f*pow(x, 4)+34.193f*pow(x, 3)-39.083f*pow(x, 2)+23.116f*x-9.713f); + float x = length / L; + return (-11.541f * powf(x, 4) + 34.193f * powf(x, 3) - 39.083f * powf(x, 2) + 23.116f * x - 9.713f); } DO_INLINE float fbderiv(float length, float L) { float x = length/L; - return (-46.164f*pow(x, 3)+102.579f*pow(x, 2)-78.166f*x+23.116f); + return (-46.164f * powf(x, 3) + 102.579f * powf(x, 2) - 78.166f * x + 23.116f); } DO_INLINE float fbstar(float length, float L, float kb, float cb) { - float tempfb = kb * fb(length, L); - - float fbstar = cb * (length - L); + float tempfb_fl = kb * fb(length, L); + float fbstar_fl = cb * (length - L); - if (tempfb < fbstar) - return fbstar; + if (tempfb_fl < fbstar_fl) + return fbstar_fl; else - return tempfb; + return tempfb_fl; } // function to calculae bending spring force (taken from Choi & Co) DO_INLINE float fbstar_jacobi(float length, float L, float kb, float cb) { - float tempfb = kb * fb(length, L); - float fbstar = cb * (length - L); + float tempfb_fl = kb * fb(length, L); + float fbstar_fl = cb * (length - L); - if (tempfb < fbstar) { + if (tempfb_fl < fbstar_fl) { return cb; } else { - return kb * fbderiv(length, L); - } + return kb * fbderiv(length, L); + } } DO_INLINE void filter(lfVector *V, fmatrix3x3 *S) @@ -918,7 +917,7 @@ static int cg_filtered(lfVector *ldV, fmatrix3x3 *lA, lfVector *lB, lfVector *z cp_lfvector(d, r, numverts); s = dot_lfvector(r, r, numverts); - starget = s * sqrt(conjgrad_epsilon); + starget = s * sqrtf(conjgrad_epsilon); while (s>starget && conjgrad_loopcount < conjgrad_looplimit) { // Mul(q, A, d); // q = A*d; @@ -1149,9 +1148,9 @@ DO_INLINE void dfdx_spring_type1(float to[3][3], float extent[3], float length, // dir is unit length direction, rest is spring's restlength, k is spring constant. // return (outerprod(dir, dir)*k + (I - outerprod(dir, dir))*(k - ((k*L)/length))); float temp[3][3]; - float temp1 = k*(1.0 - (L/length)); + float temp1 = k * (1.0f - (L / length)); - mul_fvectorT_fvectorS(temp, extent, extent, 1.0 / dot); + mul_fvectorT_fvectorS(temp, extent, extent, 1.0f / dot); sub_fmatrix_fmatrix(to, I, temp); mul_fmatrix_S(to, temp1); @@ -1219,7 +1218,7 @@ DO_INLINE void cloth_calc_spring_force(ClothModifierData *clmd, ClothSpring *s, float stretch_force[3] = {0, 0, 0}; float bending_force[3] = {0, 0, 0}; float damping_force[3] = {0, 0, 0}; - float nulldfdx[3][3]={ {0, 0, 0}, {0, 0, 0}, {0, 0, 0}}; + float nulldfdx[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}; float scaling = 0.0; @@ -1247,7 +1246,7 @@ DO_INLINE void cloth_calc_spring_force(ClothModifierData *clmd, ClothSpring *s, s->flags |= CSPRING_FLAG_DEACTIVATE; return; } - } + } */ mul_fvector_S(dir, extent, 1.0f/length); } @@ -1308,7 +1307,7 @@ DO_INLINE void cloth_calc_spring_force(ClothModifierData *clmd, ClothSpring *s, VECADDS(s->f, s->f, extent, -k); - mul_fvector_S(damping_force, dir, clmd->sim_parms->goalfrict * 0.01 * dot_v3v3(vel, dir)); + mul_fvector_S(damping_force, dir, clmd->sim_parms->goalfrict * 0.01f * dot_v3v3(vel, dir)); VECADD(s->f, s->f, damping_force); // HERE IS THE PROBLEM!!!! @@ -1319,10 +1318,10 @@ DO_INLINE void cloth_calc_spring_force(ClothModifierData *clmd, ClothSpring *s, if (length < L) { s->flags |= CLOTH_SPRING_FLAG_NEEDED; - k = clmd->sim_parms->bending; + k = clmd->sim_parms->bending; - scaling = k + s->stiffness * ABS(clmd->sim_parms->max_bend-k); - cb = k = scaling / (20.0*(clmd->sim_parms->avg_spring_len + FLT_EPSILON)); + scaling = k + s->stiffness * ABS(clmd->sim_parms->max_bend-k); + cb = k = scaling / (20.0f * (clmd->sim_parms->avg_spring_len + FLT_EPSILON)); mul_fvector_S(bending_force, dir, fbstar(length, L, k, cb)); VECADD(s->f, s->f, bending_force); @@ -1338,7 +1337,7 @@ DO_INLINE void cloth_apply_spring_force(ClothModifierData *UNUSED(clmd), ClothSp if (!(s->type & CLOTH_SPRING_TYPE_BENDING)) { sub_fmatrix_fmatrix(dFdV[s->ij].m, dFdV[s->ij].m, s->dfdv); sub_fmatrix_fmatrix(dFdV[s->kl].m, dFdV[s->kl].m, s->dfdv); - add_fmatrix_fmatrix(dFdV[s->matrix_index].m, dFdV[s->matrix_index].m, s->dfdv); + add_fmatrix_fmatrix(dFdV[s->matrix_index].m, dFdV[s->matrix_index].m, s->dfdv); } VECADD(lF[s->ij], lF[s->ij], s->f); @@ -1349,7 +1348,7 @@ DO_INLINE void cloth_apply_spring_force(ClothModifierData *UNUSED(clmd), ClothSp sub_fmatrix_fmatrix(dFdX[s->kl].m, dFdX[s->kl].m, s->dfdx); sub_fmatrix_fmatrix(dFdX[s->ij].m, dFdX[s->ij].m, s->dfdx); add_fmatrix_fmatrix(dFdX[s->matrix_index].m, dFdX[s->matrix_index].m, s->dfdx); - } + } } @@ -1357,15 +1356,15 @@ static void CalcFloat( float *v1, float *v2, float *v3, float *n) { float n1[3], n2[3]; - n1[0]= v1[0]-v2[0]; - n2[0]= v2[0]-v3[0]; - n1[1]= v1[1]-v2[1]; - n2[1]= v2[1]-v3[1]; - n1[2]= v1[2]-v2[2]; - n2[2]= v2[2]-v3[2]; - n[0]= n1[1]*n2[2]-n1[2]*n2[1]; - n[1]= n1[2]*n2[0]-n1[0]*n2[2]; - n[2]= n1[0]*n2[1]-n1[1]*n2[0]; + n1[0] = v1[0]-v2[0]; + n2[0] = v2[0]-v3[0]; + n1[1] = v1[1]-v2[1]; + n2[1] = v2[1]-v3[1]; + n1[2] = v1[2]-v2[2]; + n2[2] = v2[2]-v3[2]; + n[0] = n1[1]*n2[2]-n1[2]*n2[1]; + n[1] = n1[2]*n2[0]-n1[0]*n2[2]; + n[2] = n1[0]*n2[1]-n1[1]*n2[0]; } static void CalcFloat4( float *v1, float *v2, float *v3, float *v4, float *n) @@ -1373,17 +1372,17 @@ static void CalcFloat4( float *v1, float *v2, float *v3, float *v4, float *n) /* real cross! */ float n1[3], n2[3]; - n1[0]= v1[0]-v3[0]; - n1[1]= v1[1]-v3[1]; - n1[2]= v1[2]-v3[2]; + n1[0] = v1[0]-v3[0]; + n1[1] = v1[1]-v3[1]; + n1[2] = v1[2]-v3[2]; - n2[0]= v2[0]-v4[0]; - n2[1]= v2[1]-v4[1]; - n2[2]= v2[2]-v4[2]; + n2[0] = v2[0]-v4[0]; + n2[1] = v2[1]-v4[1]; + n2[2] = v2[2]-v4[2]; - n[0]= n1[1]*n2[2]-n1[2]*n2[1]; - n[1]= n1[2]*n2[0]-n1[0]*n2[2]; - n[2]= n1[0]*n2[1]-n1[1]*n2[0]; + n[0] = n1[1]*n2[2]-n1[2]*n2[1]; + n[1] = n1[2]*n2[0]-n1[0]*n2[2]; + n[2] = n1[0]*n2[1]-n1[1]*n2[0]; } static float calculateVertexWindForce(float wind[3], float vertexnormal[3]) @@ -1450,7 +1449,7 @@ static void hair_velocity_smoothing(ClothModifierData *clmd, lfVector *lF, lfVec i = HAIR_GRID_INDEX(lX[v], gmin, gmax, 0); j = HAIR_GRID_INDEX(lX[v], gmin, gmax, 1); k = HAIR_GRID_INDEX(lX[v], gmin, gmax, 2); - if (i < 0 || j < 0 || k < 0 || i > 10 || j >= 10 || k >= 10) + if (i < 0 || j < 0 || k < 0 || i >= 10 || j >= 10 || k >= 10) continue; grid[i][j][k].velocity[0] += lV[v][0]; @@ -1480,7 +1479,7 @@ static void hair_velocity_smoothing(ClothModifierData *clmd, lfVector *lF, lfVec colg[i][j][k].velocity[0] += vel[0]; colg[i][j][k].velocity[1] += vel[1]; colg[i][j][k].velocity[2] += vel[2]; - colg[i][j][k].density += 1.0; + colg[i][j][k].density += 1.0f; } } } @@ -1514,7 +1513,7 @@ static void hair_velocity_smoothing(ClothModifierData *clmd, lfVector *lF, lfVec i = HAIR_GRID_INDEX(lX[v], gmin, gmax, 0); j = HAIR_GRID_INDEX(lX[v], gmin, gmax, 1); k = HAIR_GRID_INDEX(lX[v], gmin, gmax, 2); - if (i < 0 || j < 0 || k < 0 || i > 10 || j >= 10 || k >= 10) + if (i < 0 || j < 0 || k < 0 || i >= 10 || j >= 10 || k >= 10) continue; lF[v][0] += smoothfac * (grid[i][j][k].velocity[0] - lV[v][0]); @@ -1545,7 +1544,7 @@ static void cloth_calc_force(ClothModifierData *clmd, float UNUSED(frame), lfVec lfVector *winvec; EffectedPoint epoint; - tm2[0][0]= tm2[1][1]= tm2[2][2]= -spring_air; + tm2[0][0] = tm2[1][1] = tm2[2][2] = -spring_air; /* global acceleration (gravitation) */ if (clmd->scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) { @@ -1589,11 +1588,11 @@ static void cloth_calc_force(ClothModifierData *clmd, float UNUSED(frame), lfVec } for (i = 0; i < cloth->numfaces; i++) { - float trinormal[3]={0, 0, 0}; // normalized triangle normal - float triunnormal[3]={0, 0, 0}; // not-normalized-triangle normal - float tmp[3]={0, 0, 0}; + float trinormal[3] = {0, 0, 0}; // normalized triangle normal + float triunnormal[3] = {0, 0, 0}; // not-normalized-triangle normal + float tmp[3] = {0, 0, 0}; float factor = (mfaces[i].v4) ? 0.25 : 1.0 / 3.0; - factor *= 0.02; + factor *= 0.02f; // calculate face normal if (mfaces[i].v4) @@ -1629,9 +1628,9 @@ static void cloth_calc_force(ClothModifierData *clmd, float UNUSED(frame), lfVec /* Hair has only edges */ if (cloth->numfaces == 0) { ClothSpring *spring; - float edgevec[3]={0, 0, 0}; //edge vector - float edgeunnormal[3]={0, 0, 0}; // not-normalized-edge normal - float tmp[3]={0, 0, 0}; + float edgevec[3] = {0, 0, 0}; //edge vector + float edgeunnormal[3] = {0, 0, 0}; // not-normalized-edge normal + float tmp[3] = {0, 0, 0}; float factor = 0.01; search = cloth->springs; @@ -1663,7 +1662,7 @@ static void cloth_calc_force(ClothModifierData *clmd, float UNUSED(frame), lfVec while (search) { // only handle active springs ClothSpring *spring = search->link; - if( !(spring->flags & CLOTH_SPRING_FLAG_DEACTIVATE)) + if (!(spring->flags & CLOTH_SPRING_FLAG_DEACTIVATE)) cloth_calc_spring_force(clmd, search->link, lF, lX, lV, dFdV, dFdX, time); search = search->next; @@ -1731,8 +1730,8 @@ static int UNUSED_FUNCTION(cloth_calc_helper_forces)(Object *UNUSED(ob), ClothMo for (i=0; i<cloth->numverts; i++, cv++) { copy_v3_v3(cos[i], cv->tx); - if (cv->goal == 1.0f || len_v3v3(initial_cos[i], cv->tx) != 0.0) { - masses[i] = 1e+10; + if (cv->goal == 1.0f || len_squared_v3v3(initial_cos[i], cv->tx) != 0.0f) { + masses[i] = 1e+10; } else { masses[i] = cv->mass; @@ -1759,18 +1758,18 @@ static int UNUSED_FUNCTION(cloth_calc_helper_forces)(Object *UNUSED(ob), ClothMo normalize_v3(vec); c = (len - spring->restlen); - if (c == 0.0) + if (c == 0.0f) continue; - l = c / ((1.0/masses[v1]) + (1.0/masses[v2])); + l = c / ((1.0f / masses[v1]) + (1.0f / masses[v2])); - mul_v3_fl(vec, -(1.0/masses[v1])*l); + mul_v3_fl(vec, -(1.0f / masses[v1]) * l); add_v3_v3(cos[v1], vec); sub_v3_v3v3(vec, cos[v2], cos[v1]); normalize_v3(vec); - mul_v3_fl(vec, -(1.0/masses[v2])*l); + mul_v3_fl(vec, -(1.0f / masses[v2]) * l); add_v3_v3(cos[v2], vec); } } @@ -1815,7 +1814,7 @@ int implicit_solver(Object *ob, float frame, ClothModifierData *clmd, ListBase * sub_v3_v3v3(id->V[i], verts[i].xconst, verts[i].xold); // mul_v3_fl(id->V[i], clmd->sim_parms->stepsPerFrame); } - } + } } while (step < tf) { @@ -1840,7 +1839,7 @@ int implicit_solver(Object *ob, float frame, ClothModifierData *clmd, ListBase * mul_fvector_S(tvect, tvect, step+dt); VECADD(tvect, tvect, verts[i].xold); copy_v3_v3(id->Xnew[i], tvect); - } + } } copy_v3_v3(verts[i].txold, id->X[i]); @@ -1898,7 +1897,7 @@ int implicit_solver(Object *ob, float frame, ClothModifierData *clmd, ListBase * cp_lfvector(id->V, id->Vnew, numverts); // calculate - cloth_calc_force(clmd, frame, id->F, id->X, id->V, id->dFdV, id->dFdX, effectors, step+dt, id->M); + cloth_calc_force(clmd, frame, id->F, id->X, id->V, id->dFdV, id->dFdX, effectors, step+dt, id->M); simulate_implicit_euler(id->Vnew, id->X, id->V, id->F, id->dFdV, id->dFdX, dt / 2.0f, id->A, id->B, id->dV, id->S, id->z, id->olddV, id->P, id->Pinv, id->M, id->bigI); } @@ -1947,6 +1946,6 @@ void implicit_set_positions(ClothModifierData *clmd) copy_v3_v3(id->V[i], verts[i].v); } if (G.debug_value > 0) - printf("implicit_set_positions\n"); + printf("implicit_set_positions\n"); } diff --git a/source/blender/blenkernel/intern/ipo.c b/source/blender/blenkernel/intern/ipo.c index 5216aefab58..59dd02849dd 100644 --- a/source/blender/blenkernel/intern/ipo.c +++ b/source/blender/blenkernel/intern/ipo.c @@ -569,7 +569,7 @@ static const char *material_adrcodes_to_paths(int adrcode, int *array_index) return mtex_adrcodes_to_paths(adrcode, array_index); } - return NULL; + return NULL; } /* Camera Types */ @@ -727,7 +727,7 @@ static const char *world_adrcodes_to_paths(int adrcode, int *array_index) return mtex_adrcodes_to_paths(adrcode, array_index); } - return NULL; + return NULL; } /* Particle Types */ @@ -873,7 +873,7 @@ static char *get_rna_access(int blocktype, int adrcode, char actname[], char con propname = "eval_time"; break; - /* XXX problematic blocktypes */ + /* XXX problematic blocktypes */ case ID_SEQ: /* sequencer strip */ //SEQ_FAC1: switch (adrcode) { @@ -981,21 +981,21 @@ static char *get_rna_access(int blocktype, int adrcode, char actname[], char con static short adrcode_to_dtar_transchan(short adrcode) { switch (adrcode) { - case OB_LOC_X: + case OB_LOC_X: return DTAR_TRANSCHAN_LOCX; case OB_LOC_Y: return DTAR_TRANSCHAN_LOCY; case OB_LOC_Z: return DTAR_TRANSCHAN_LOCZ; - case OB_ROT_X: + case OB_ROT_X: return DTAR_TRANSCHAN_ROTX; case OB_ROT_Y: return DTAR_TRANSCHAN_ROTY; case OB_ROT_Z: return DTAR_TRANSCHAN_ROTZ; - case OB_SIZE_X: + case OB_SIZE_X: return DTAR_TRANSCHAN_SCALEX; case OB_SIZE_Y: return DTAR_TRANSCHAN_SCALEX; @@ -1359,8 +1359,8 @@ static void icu_to_fcurves(ID *id, ListBase *groups, ListBase *list, IpoCurve *i /* correct values for sequencer curves, that were not locked to frame */ if (seq && (seq->flag & SEQ_IPO_FRAME_LOCKED) == 0) { - double mul = (seq->enddisp - seq->startdisp) / 100.0f; - double offset = seq->startdisp; + const float mul = (seq->enddisp - seq->startdisp) / 100.0f; + const float offset = seq->startdisp; dst->vec[0][0] *= mul; dst->vec[0][0] += offset; @@ -1645,7 +1645,7 @@ static void nlastrips_to_animdata(ID *id, ListBase *strips) /* by default, we now always extrapolate, while in the past this was optional */ 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) */ if (BKE_nlatrack_add_strip(nlt, strip) == 0) { @@ -2093,7 +2093,7 @@ void do_versions_ipos_to_animato(Main *main) bAction *new_act; /* add a new action for this, and convert all data into that action */ - new_act = add_empty_action(id->name+2); + new_act = add_empty_action(id->name + 2); ipo_to_animato(NULL, ipo, NULL, NULL, NULL, NULL, &new_act->curves, &drivers); new_act->idroot = ipo->blocktype; } diff --git a/source/blender/blenkernel/intern/key.c b/source/blender/blenkernel/intern/key.c index b9bf2fd01a3..782d796b8a7 100644 --- a/source/blender/blenkernel/intern/key.c +++ b/source/blender/blenkernel/intern/key.c @@ -389,7 +389,7 @@ static int setkeys(float fac, ListBase *lb, KeyBlock *k[], float t[4], int cycl) if (k1->next == NULL) k[0] = k1; k1 = k1->next; } - /* k1= k[1]; */ /* UNUSED */ + /* k1 = k[1]; */ /* UNUSED */ t[0] = k[0]->pos; t[1] += dpos; t[2] = k[2]->pos + dpos; @@ -609,7 +609,7 @@ static void cp_key(const int start, int end, const int tot, char *poin, Key *key } } else k1 += start * key->elemsize; - } + } if (mode == KEY_MODE_BEZTRIPLE) { elemstr[0] = 1; @@ -691,8 +691,8 @@ static void cp_cu_key(Curve *cu, Key *key, KeyBlock *actkb, KeyBlock *kb, const if (nu->bp) { step = nu->pntsu * nu->pntsv; - a1 = maxi(a, start); - a2 = mini(a + step, end); + a1 = max_ii(a, start); + a2 = min_ii(a + step, end); if (a1 < a2) cp_key(a1, a2, tot, out, key, actkb, kb, NULL, KEY_MODE_BPOINT); } @@ -700,8 +700,8 @@ static void cp_cu_key(Curve *cu, Key *key, KeyBlock *actkb, KeyBlock *kb, const step = 3 * nu->pntsu; /* exception because keys prefer to work with complete blocks */ - a1 = maxi(a, start); - a2 = mini(a + step, end); + a1 = max_ii(a, start); + a2 = min_ii(a + step, end); if (a1 < a2) cp_key(a1, a2, tot, out, key, actkb, kb, NULL, KEY_MODE_BEZTRIPLE); } @@ -1043,7 +1043,7 @@ static float *get_weights_array(Object *ob, char *vgroup) /* find the group (weak loop-in-loop) */ defgrp_index = defgroup_name_index(ob, vgroup); - if (defgrp_index >= 0) { + if (defgrp_index != -1) { float *weights; int i; @@ -1217,7 +1217,7 @@ static void do_curve_key(Scene *scene, Object *ob, Key *key, char *out, const in remain = step; } - count = mini(remain, estep); + count = min_ii(remain, estep); if (mode == KEY_MODE_BEZTRIPLE) { count += 3 - count % 3; } @@ -1268,7 +1268,7 @@ static void do_latt_key(Scene *scene, Object *ob, Key *key, char *out, const int do_key(a, a + 1, tot, out, key, actkb, k, t, KEY_MODE_DUMMY); else cp_key(a, a + 1, tot, out, key, actkb, k[2], NULL, KEY_MODE_DUMMY); - } + } } else { if (key->type == KEY_RELATIVE) { @@ -1584,7 +1584,7 @@ void BKE_key_convert_to_lattice(KeyBlock *kb, Lattice *lt) fp = kb->data; tot = lt->pntsu * lt->pntsv * lt->pntsw; - tot = mini(kb->totelem, tot); + tot = min_ii(kb->totelem, tot); for (a = 0; a < tot; a++, fp += 3, bp++) { copy_v3_v3(bp->vec, fp); @@ -1656,7 +1656,7 @@ void BKE_key_convert_to_curve(KeyBlock *kb, Curve *UNUSED(cu), ListBase *nurb) tot = BKE_nurbList_verts_count(nurb); - tot = mini(kb->totelem, tot); + tot = min_ii(kb->totelem, tot); while (nu && tot > 0) { @@ -1724,7 +1724,7 @@ void BKE_key_convert_to_mesh(KeyBlock *kb, Mesh *me) mvert = me->mvert; fp = kb->data; - tot = mini(kb->totelem, me->totvert); + tot = min_ii(kb->totelem, me->totvert); for (a = 0; a < tot; a++, fp += 3, mvert++) { copy_v3_v3(mvert->co, fp); diff --git a/source/blender/blenkernel/intern/lamp.c b/source/blender/blenkernel/intern/lamp.c index 4782d09a7c8..2f37db846f3 100644 --- a/source/blender/blenkernel/intern/lamp.c +++ b/source/blender/blenkernel/intern/lamp.c @@ -33,9 +33,12 @@ #include "MEM_guardedalloc.h" +#include "DNA_anim_types.h" #include "DNA_lamp_types.h" #include "DNA_material_types.h" +#include "DNA_node_types.h" #include "DNA_object_types.h" +#include "DNA_scene_types.h" #include "DNA_texture_types.h" #include "BLI_listbase.h" @@ -73,7 +76,7 @@ Lamp *BKE_lamp_add(const char *name) la->soft = 3.0f; la->compressthresh = 0.05f; la->ray_samp = la->ray_sampy = la->ray_sampz = 1; - la->area_size = la->area_sizey = la->area_sizez = 1.0f; + la->area_size = la->area_sizey = la->area_sizez = 0.1f; la->buffers = 1; la->buftype = LA_SHADBUF_HALFWAY; la->ray_samp_method = LA_SAMP_HALTON; @@ -232,3 +235,38 @@ void BKE_lamp_free(Lamp *la) la->id.icon_id = 0; } +/* Calculate all drivers for lamps, see material_drivers_update for why this is a bad hack */ + +static void lamp_node_drivers_update(Scene *scene, bNodeTree *ntree, float ctime) +{ + bNode *node; + + /* nodetree itself */ + if (ntree->adt && ntree->adt->drivers.first) + BKE_animsys_evaluate_animdata(scene, &ntree->id, ntree->adt, ctime, ADT_RECALC_DRIVERS); + + /* nodes */ + for (node = ntree->nodes.first; node; node = node->next) + if (node->id && node->type == NODE_GROUP) + lamp_node_drivers_update(scene, (bNodeTree *)node->id, ctime); +} + +void lamp_drivers_update(Scene *scene, Lamp *la, float ctime) +{ + /* Prevent infinite recursion by checking (and tagging the lamp) as having been visited already + * (see BKE_scene_update_tagged()). This assumes la->id.flag & LIB_DOIT isn't set by anything else + * in the meantime... [#32017] */ + if (la->id.flag & LIB_DOIT) + return; + else + la->id.flag |= LIB_DOIT; + + /* lamp itself */ + if (la->adt && la->adt->drivers.first) + BKE_animsys_evaluate_animdata(scene, &la->id, la->adt, ctime, ADT_RECALC_DRIVERS); + + /* nodes */ + if (la->nodetree) + lamp_node_drivers_update(scene, la->nodetree, ctime); +} + diff --git a/source/blender/blenkernel/intern/lattice.c b/source/blender/blenkernel/intern/lattice.c index 17e4103c7d3..a15ca7cb5ce 100644 --- a/source/blender/blenkernel/intern/lattice.c +++ b/source/blender/blenkernel/intern/lattice.c @@ -64,19 +64,19 @@ #include "BKE_deform.h" -void calc_lat_fudu(int flag, int res, float *fu, float *du) +void calc_lat_fudu(int flag, int res, float *r_fu, float *r_du) { if (res == 1) { - *fu = 0.0; - *du = 0.0; + *r_fu = 0.0; + *r_du = 0.0; } else if (flag & LT_GRID) { - *fu = -0.5f * (res - 1); - *du = 1.0f; + *r_fu = -0.5f * (res - 1); + *r_du = 1.0f; } else { - *fu = -1.0f; - *du = 2.0f / (res - 1); + *r_fu = -1.0f; + *r_du = 2.0f / (res - 1); } } @@ -348,7 +348,7 @@ void calc_latt_deform(Object *ob, float co[3], float weight) int ui, vi, wi, uu, vv, ww; /* vgroup influence */ - int defgroup_nr = -1; + int defgrp_index = -1; float co_prev[3], weight_blend = 0.0f; MDeformVert *dvert = BKE_lattice_deform_verts_get(ob); @@ -357,7 +357,7 @@ void calc_latt_deform(Object *ob, float co[3], float weight) if (lt->latticedata == NULL) return; if (lt->vgroup[0] && dvert) { - defgroup_nr = defgroup_name_index(ob, lt->vgroup); + defgrp_index = defgroup_name_index(ob, lt->vgroup); copy_v3_v3(co_prev, co); } @@ -431,8 +431,8 @@ void calc_latt_deform(Object *ob, float co[3], float weight) madd_v3_v3fl(co, <->latticedata[idx_u * 3], u); - if (defgroup_nr != -1) - weight_blend += (u * defvert_find_weight(dvert + idx_u, defgroup_nr)); + if (defgrp_index != -1) + weight_blend += (u * defvert_find_weight(dvert + idx_u, defgrp_index)); } } } @@ -440,7 +440,7 @@ void calc_latt_deform(Object *ob, float co[3], float weight) } } - if (defgroup_nr != -1) + if (defgrp_index != -1) interp_v3_v3v3(co, co_prev, co, weight_blend); } @@ -669,9 +669,9 @@ void curve_deform_verts(Scene *scene, Object *cuOb, Object *target, if (vgroup && vgroup[0] && use_vgroups) { Mesh *me = target->data; - int index = defgroup_name_index(target, vgroup); + const int defgrp_index = defgroup_name_index(target, vgroup); - if (index != -1 && (me->dvert || dm)) { + if (defgrp_index != -1 && (me->dvert || dm)) { MDeformVert *dvert = me->dvert; float vec[3]; float weight; @@ -681,7 +681,7 @@ void curve_deform_verts(Scene *scene, Object *cuOb, Object *target, dvert = me->dvert; for (a = 0; a < numVerts; a++, dvert++) { if (dm) dvert = dm->getVertData(dm, a, CD_MDEFORMVERT); - weight = defvert_find_weight(dvert, index); + weight = defvert_find_weight(dvert, defgrp_index); if (weight > 0.0f) { mul_m4_v3(cd.curvespace, vertexCos[a]); @@ -699,7 +699,7 @@ void curve_deform_verts(Scene *scene, Object *cuOb, Object *target, for (a = 0; a < numVerts; a++, dvert++) { if (dm) dvert = dm->getVertData(dm, a, CD_MDEFORMVERT); - if (defvert_find_weight(dvert, index) > 0.0f) { + if (defvert_find_weight(dvert, defgrp_index) > 0.0f) { mul_m4_v3(cd.curvespace, vertexCos[a]); minmax_v3v3_v3(cd.dmin, cd.dmax, vertexCos[a]); } @@ -709,7 +709,7 @@ void curve_deform_verts(Scene *scene, Object *cuOb, Object *target, for (a = 0; a < numVerts; a++, dvert++) { if (dm) dvert = dm->getVertData(dm, a, CD_MDEFORMVERT); - weight = defvert_find_weight(dvert, index); + weight = defvert_find_weight(dvert, defgrp_index); if (weight > 0.0f) { /* already in 'cd.curvespace', prev for loop */ @@ -815,16 +815,16 @@ void lattice_deform_verts(Object *laOb, Object *target, DerivedMesh *dm, if (vgroup && vgroup[0] && use_vgroups) { Mesh *me = target->data; - int index = defgroup_name_index(target, vgroup); + const int defgrp_index = defgroup_name_index(target, vgroup); float weight; - if (index >= 0 && (me->dvert || dm)) { + if (defgrp_index >= 0 && (me->dvert || dm)) { MDeformVert *dvert = me->dvert; for (a = 0; a < numVerts; a++, dvert++) { if (dm) dvert = dm->getVertData(dm, a, CD_MDEFORMVERT); - weight = defvert_find_weight(dvert, index); + weight = defvert_find_weight(dvert, defgrp_index); if (weight > 0.0f) calc_latt_deform(laOb, vertexCos[a], weight * fac); @@ -879,9 +879,10 @@ void outside_lattice(Lattice *lt) for (v = 0; v < lt->pntsv; v++) { for (u = 0; u < lt->pntsu; u++, bp++) { - if (u == 0 || v == 0 || w == 0 || u == lt->pntsu - 1 || v == lt->pntsv - 1 || w == lt->pntsw - 1) ; + if (u == 0 || v == 0 || w == 0 || u == lt->pntsu - 1 || v == lt->pntsv - 1 || w == lt->pntsw - 1) { + /* pass */ + } else { - bp->hide = 1; bp->f1 &= ~SELECT; diff --git a/source/blender/blenkernel/intern/library.c b/source/blender/blenkernel/intern/library.c index 45364f5aafa..9deff12f124 100644 --- a/source/blender/blenkernel/intern/library.c +++ b/source/blender/blenkernel/intern/library.c @@ -796,6 +796,18 @@ static void animdata_dtar_clear_cb(ID *UNUSED(id), AnimData *adt, void *userdata } } +void BKE_libblock_free_data(ID *id) +{ + Main *bmain = G.main; /* should eventually be an arg */ + + if (id->properties) { + IDP_FreeProperty(id->properties); + MEM_freeN(id->properties); + } + + /* this ID may be a driver target! */ + BKE_animdata_main_cb(bmain, animdata_dtar_clear_cb, (void *)id); +} /* used in headerbuttons.c image.c mesh.c screen.c sound.c and library.c */ void BKE_libblock_free(ListBase *lb, void *idv) @@ -904,15 +916,9 @@ void BKE_libblock_free(ListBase *lb, void *idv) break; } - if (id->properties) { - IDP_FreeProperty(id->properties); - MEM_freeN(id->properties); - } - BLI_remlink(lb, id); - /* this ID may be a driver target! */ - BKE_animdata_main_cb(bmain, animdata_dtar_clear_cb, (void *)id); + BKE_libblock_free_data(id); MEM_freeN(id); } @@ -992,7 +998,6 @@ void free_main(Main *mainvar) #endif } } - a = set_listbasepointers(mainvar, lbarray); MEM_freeN(mainvar); } @@ -1200,7 +1205,7 @@ static int check_for_dupid(ListBase *lb, ID *id, char *name) char left[MAX_ID_NAME + 8], leftest[MAX_ID_NAME + 8]; /* make sure input name is terminated properly */ - /* if ( strlen(name) > MAX_ID_NAME-3 ) name[MAX_ID_NAME-3]= 0; */ + /* if ( strlen(name) > MAX_ID_NAME-3 ) name[MAX_ID_NAME-3] = 0; */ /* removed since this is only ever called from one place - campbell */ while (1) { @@ -1547,7 +1552,7 @@ void rename_id(ID *id, const char *name) BLI_strncpy(id->name + 2, name, sizeof(id->name) - 2); lb = which_libbase(G.main, GS(id->name) ); - new_id(lb, id, name); + new_id(lb, id, name); } void name_uiprefix_id(char *name, ID *id) diff --git a/source/blender/blenkernel/intern/mask.c b/source/blender/blenkernel/intern/mask.c index aa19350c456..b7f4c4bd61e 100644 --- a/source/blender/blenkernel/intern/mask.c +++ b/source/blender/blenkernel/intern/mask.c @@ -378,8 +378,8 @@ float BKE_mask_spline_project_co(MaskSpline *spline, MaskSplinePoint *point, if (len_squared_v2(v1) > proj_eps_squared) { ang1 = angle_v2v2(v1, n1); - if (ang1 > M_PI / 2.0f) - ang1 = M_PI - ang1; + if (ang1 > (float)M_PI / 2.0f) + ang1 = (float)M_PI - ang1; if (ang < 0.0f || ang1 < ang) { ang = ang1; @@ -405,8 +405,8 @@ float BKE_mask_spline_project_co(MaskSpline *spline, MaskSplinePoint *point, if (len_squared_v2(v2) > proj_eps_squared) { ang2 = angle_v2v2(v2, n2); - if (ang2 > M_PI / 2.0f) - ang2 = M_PI - ang2; + if (ang2 > (float)M_PI / 2.0f) + ang2 = (float)M_PI - ang2; if (ang2 < ang) { ang = ang2; @@ -555,7 +555,7 @@ float BKE_mask_point_weight_scalar(MaskSpline *spline, MaskSplinePoint *point, c if (!bezt_next) { return bezt->weight; } - else if (u <= 0.0) { + else if (u <= 0.0f) { return bezt->weight; } else if (u >= 1.0f) { @@ -576,7 +576,7 @@ float BKE_mask_point_weight(MaskSpline *spline, MaskSplinePoint *point, const fl if (!bezt_next) { return bezt->weight; } - else if (u <= 0.0) { + else if (u <= 0.0f) { return bezt->weight; } else if (u >= 1.0f) { @@ -1805,7 +1805,7 @@ static void interp_weights_uv_v2_calc(float r_uv[2], const float pt[2], const fl float pt_on_line[2]; r_uv[0] = closest_to_line_v2(pt_on_line, pt, pt_a, pt_b); r_uv[1] = (len_v2v2(pt_on_line, pt) / len_v2v2(pt_a, pt_b)) * - ((line_point_side_v2(pt_a, pt_b, pt) < 0.0f) ? -1.0 : 1.0); /* this line only sets the sign */ + ((line_point_side_v2(pt_a, pt_b, pt) < 0.0f) ? -1.0f : 1.0f); /* this line only sets the sign */ } @@ -1955,5 +1955,5 @@ void BKE_mask_layer_shape_changed_remove(MaskLayer *masklay, int index, int coun int BKE_mask_get_duration(Mask *mask) { - return maxi(1, mask->efra - mask->sfra); + return max_ii(1, mask->efra - mask->sfra); } diff --git a/source/blender/blenkernel/intern/mask_evaluate.c b/source/blender/blenkernel/intern/mask_evaluate.c index 4a8601df0b8..7d89678d36f 100644 --- a/source/blender/blenkernel/intern/mask_evaluate.c +++ b/source/blender/blenkernel/intern/mask_evaluate.c @@ -69,7 +69,7 @@ unsigned int BKE_mask_spline_resolution(MaskSpline *spline, int width, int heigh unsigned int i, resol = 1; if (width != 0 && height != 0) { - max_segment = 1.0f / (float)maxi(width, height); + max_segment = 1.0f / (float)max_ii(width, height); } for (i = 0; i < spline->tot_point; i++) { @@ -131,7 +131,7 @@ unsigned int BKE_mask_spline_feather_resolution(MaskSpline *spline, int width, i if (u_diff > FLT_EPSILON) { float jump = fabsf(w_diff / u_diff); - max_jump = MAX2(max_jump, jump); + max_jump = max_ff(max_jump, jump); } prev_u = point->uw[j].u; @@ -245,7 +245,7 @@ static void feather_bucket_add_edge(FeatherEdgesBucket *bucket, int start, int e } else { bucket->segments = MEM_reallocN(bucket->segments, - (alloc_delta + bucket->tot_segment) * sizeof(*bucket->segments)); + (alloc_delta + bucket->tot_segment) * sizeof(*bucket->segments)); } bucket->alloc_segment += alloc_delta; @@ -418,7 +418,7 @@ void BKE_mask_spline_feather_collapse_inner_loops(MaskSpline *spline, float (*fe max_delta = MAX2(max_delta_x, max_delta_y); - buckets_per_side = MIN2(512, 0.9f / max_delta); + buckets_per_side = min_ii(512, 0.9f / max_delta); if (buckets_per_side == 0) { /* happens when some segment fills the whole bounding box across some of dimension */ diff --git a/source/blender/blenkernel/intern/mask_rasterize.c b/source/blender/blenkernel/intern/mask_rasterize.c index 13ad9962aff..88393fab79c 100644 --- a/source/blender/blenkernel/intern/mask_rasterize.c +++ b/source/blender/blenkernel/intern/mask_rasterize.c @@ -104,7 +104,7 @@ /* for debugging add... */ #ifndef NDEBUG -/* printf("%u %u %u %u\n", _t[0], _t[1], _t[2], _t[3]); \ */ +/* printf("%u %u %u %u\n", _t[0], _t[1], _t[2], _t[3]); \ */ # define FACE_ASSERT(face, vert_max) \ { \ unsigned int *_t = face; \ @@ -428,7 +428,7 @@ static void layer_bucket_init(MaskRasterLayer *layer, const float pixel_size) /* width and height of each bucket */ const float bucket_size_x = (bucket_dim_x + FLT_EPSILON) / layer->buckets_x; const float bucket_size_y = (bucket_dim_y + FLT_EPSILON) / layer->buckets_y; - const float bucket_max_rad = (maxf(bucket_size_x, bucket_size_y) * M_SQRT2) + FLT_EPSILON; + const float bucket_max_rad = (max_ff(bucket_size_x, bucket_size_y) * (float)M_SQRT2) + FLT_EPSILON; const float bucket_max_rad_squared = bucket_max_rad * bucket_max_rad; unsigned int *face = &layer->face_array[0][0]; @@ -451,10 +451,10 @@ static void layer_bucket_init(MaskRasterLayer *layer, const float pixel_size) const float *v2 = cos[face[1]]; const float *v3 = cos[face[2]]; - xmin = minf(v1[0], minf(v2[0], v3[0])); - xmax = maxf(v1[0], maxf(v2[0], v3[0])); - ymin = minf(v1[1], minf(v2[1], v3[1])); - ymax = maxf(v1[1], maxf(v2[1], v3[1])); + xmin = min_ff(v1[0], min_ff(v2[0], v3[0])); + xmax = max_ff(v1[0], max_ff(v2[0], v3[0])); + ymin = min_ff(v1[1], min_ff(v2[1], v3[1])); + ymax = max_ff(v1[1], max_ff(v2[1], v3[1])); } else { const float *v1 = cos[face[0]]; @@ -462,10 +462,10 @@ static void layer_bucket_init(MaskRasterLayer *layer, const float pixel_size) const float *v3 = cos[face[2]]; const float *v4 = cos[face[3]]; - xmin = minf(v1[0], minf(v2[0], minf(v3[0], v4[0]))); - xmax = maxf(v1[0], maxf(v2[0], maxf(v3[0], v4[0]))); - ymin = minf(v1[1], minf(v2[1], minf(v3[1], v4[1]))); - ymax = maxf(v1[1], maxf(v2[1], maxf(v3[1], v4[1]))); + xmin = min_ff(v1[0], min_ff(v2[0], min_ff(v3[0], v4[0]))); + xmax = max_ff(v1[0], max_ff(v2[0], max_ff(v3[0], v4[0]))); + ymin = min_ff(v1[1], min_ff(v2[1], min_ff(v3[1], v4[1]))); + ymax = max_ff(v1[1], max_ff(v2[1], max_ff(v3[1], v4[1]))); } @@ -503,7 +503,7 @@ static void layer_bucket_init(MaskRasterLayer *layer, const float pixel_size) BLI_assert(bucket_index < bucket_tot); /* check if the bucket intersects with the face */ - /* note: there is a tradeoff here since checking box/tri intersections isn't + /* 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, @@ -560,7 +560,7 @@ void BKE_maskrasterize_handle_init(MaskRasterHandle *mr_handle, struct Mask *mas const short do_feather) { const rctf default_bounds = {0.0f, 1.0f, 0.0f, 1.0f}; - const float pixel_size = 1.0f / MIN2(width, height); + const float pixel_size = 1.0f / (float)min_ii(width, height); const float asp_xy[2] = {(do_aspect_correct && width > height) ? (float)height / (float)width : 1.0f, (do_aspect_correct && width < height) ? (float)width / (float)height : 1.0f}; @@ -1335,10 +1335,10 @@ float BKE_maskrasterize_handle_sample(MaskRasterHandle *mr_handle, const float x value -= value_layer; break; case MASK_BLEND_LIGHTEN: - value = maxf(value, value_layer); + value = max_ff(value, value_layer); break; case MASK_BLEND_DARKEN: - value = minf(value, value_layer); + value = min_ff(value, value_layer); break; case MASK_BLEND_MUL: value *= value_layer; diff --git a/source/blender/blenkernel/intern/material.c b/source/blender/blenkernel/intern/material.c index bea0e33da9a..ea317956255 100644 --- a/source/blender/blenkernel/intern/material.c +++ b/source/blender/blenkernel/intern/material.c @@ -38,6 +38,7 @@ #include "DNA_anim_types.h" #include "DNA_curve_types.h" +#include "DNA_group_types.h" #include "DNA_material_types.h" #include "DNA_mesh_types.h" #include "DNA_meshdata_types.h" @@ -214,7 +215,7 @@ Material *BKE_material_add(const char *name) init_material(ma); - return ma; + return ma; } /* XXX keep synced with next function */ @@ -903,7 +904,7 @@ short find_material_index(Object *ob, Material *ma) break; if (a < *totcolp) return a + 1; - return 0; + return 0; } int object_add_material_slot(Object *ob) @@ -969,7 +970,7 @@ static void do_init_render_material(Material *ma, int r_mode, float *amb) ma->ambr = ma->amb * amb[0]; ma->ambg = ma->amb * amb[1]; ma->ambb = ma->amb * amb[2]; - } + } /* will become or-ed result of all node modes */ ma->mode_l = ma->mode; ma->mode_l &= ~MA_SHLESS; @@ -980,6 +981,17 @@ static void do_init_render_material(Material *ma, int r_mode, float *amb) /* parses the geom+tex nodes */ if (ma->nodetree && ma->use_nodes) ntreeShaderGetTexcoMode(ma->nodetree, r_mode, &ma->texco, &ma->mode_l); + + /* local group override */ + if ((ma->shade_flag & MA_GROUP_LOCAL) && ma->id.lib && ma->group && ma->group->id.lib) { + Group *group; + + for (group = G.main->group.first; group; group = group->id.next) { + if (!group->id.lib && strcmp(group->id.name, ma->group->id.name) == 0) { + ma->group = group; + } + } + } } static void init_render_nodetree(bNodeTree *ntree, Material *basemat, int r_mode, float *amb) @@ -1147,7 +1159,7 @@ void material_drivers_update(Scene *scene, Material *ma, float ctime) /* ****************** */ #if 0 /* UNUSED */ -static char colname_array[125][20]= { +static char colname_array[125][20] = { "Black", "DarkRed", "HalfRed", "Red", "Red", "DarkGreen", "DarkOlive", "Brown", "Chocolate", "OrangeRed", "HalfGreen", "GreenOlive", "DryOlive", "Goldenrod", "DarkOrange", @@ -1603,7 +1615,7 @@ static int encode_tfaceflag(MTFace *tf, int convertall) /* calculate the flag */ int flag = tf->mode; - /* options that change the material offline render */ + /* options that change the material offline render */ if (!convertall) { flag &= ~TF_OBCOL; } @@ -1627,7 +1639,7 @@ static int encode_tfaceflag(MTFace *tf, int convertall) /* set the material options based in the tface flag */ static void decode_tfaceflag(Material *ma, int flag, int convertall) { - int alphablend; + int alphablend; GameSettings *game = &ma->game; /* flag is shifted in 1 to make 0 != no flag yet (see encode_tfaceflag) */ @@ -1786,13 +1798,13 @@ static short convert_tfacenomaterial(Main *main, Mesh *me, MTFace *tf, int flag) * for now store the flag into the material and change light/tex/collision * store the flag as a negative number */ ma->game.flag = -flag; - id_us_min((ID *)ma); + id_us_min((ID *)ma); } else printf("Error: Unable to create Material \"%s\" for Mesh \"%s\".", idname + 2, me->id.name + 2); } /* set as converted, no need to go bad to this face */ - tf->mode |= TF_CONVERTED; + tf->mode |= TF_CONVERTED; return mat_nr; } @@ -1845,7 +1857,7 @@ static void convert_tfacematerial(Main *main, Material *ma) if (mat_new) { /* rename the material*/ strcpy(mat_new->id.name, idname); - id_us_min((ID *)mat_new); + id_us_min((ID *)mat_new); mat_nr = mesh_addmaterial(me, mat_new); decode_tfaceflag(mat_new, flag, 1); @@ -2033,7 +2045,7 @@ int do_version_tface(Main *main, int fileload) nowarning = 0; } else - convert_tfacematerial(main, ma); continue; + convert_tfacematerial(main, ma); continue; } /* no conflicts in this material - 90% of cases diff --git a/source/blender/blenkernel/intern/mball.c b/source/blender/blenkernel/intern/mball.c index 9eea075c97a..759e858cc62 100644 --- a/source/blender/blenkernel/intern/mball.c +++ b/source/blender/blenkernel/intern/mball.c @@ -1319,12 +1319,16 @@ static void addtovertices(VERTICES *vertices, VERTEX v) static void vnormal(const float point[3], PROCESS *p, float r_no[3]) { - float delta = 0.2f * p->delta; - float f = p->function(point[0], point[1], point[2]); + const float delta = 0.2f * p->delta; + const float f = p->function(point[0], point[1], point[2]); r_no[0] = p->function(point[0] + delta, point[1], point[2]) - f; r_no[1] = p->function(point[0], point[1] + delta, point[2]) - f; r_no[2] = p->function(point[0], point[1], point[2] + delta) - f; + +#if 1 + normalize_v3(r_no); +#else f = normalize_v3(r_no); if (0) { @@ -1343,6 +1347,7 @@ static void vnormal(const float point[3], PROCESS *p, float r_no[3]) normalize_v3(r_no); } } +#endif } @@ -1500,7 +1505,7 @@ static void find_first_points(PROCESS *mbproc, MetaBall *mb, int a) float f = 0.0f; ml = G_mb.mainb[a]; - f = 1.0 - (mb->thresh / ml->s); + f = 1.0f - (mb->thresh / ml->s); /* Skip, when Stiffness of MetaElement is too small ... MetaElement can't be * visible alone ... but still can influence others MetaElements :-) */ diff --git a/source/blender/blenkernel/intern/mesh.c b/source/blender/blenkernel/intern/mesh.c index 1aaeebf5109..068059dc29a 100644 --- a/source/blender/blenkernel/intern/mesh.c +++ b/source/blender/blenkernel/intern/mesh.c @@ -469,15 +469,17 @@ void free_dverts(MDeformVert *dvert, int totvert) static void mesh_tessface_clear_intern(Mesh *mesh, int free_customdata) { - if (free_customdata) + if (free_customdata) { CustomData_free(&mesh->fdata, mesh->totface); + } + else { + CustomData_reset(&mesh->fdata); + } mesh->mface = NULL; mesh->mtface = NULL; mesh->mcol = NULL; mesh->totface = 0; - - memset(&mesh->fdata, 0, sizeof(mesh->fdata)); } Mesh *BKE_mesh_add(const char *name) @@ -491,7 +493,13 @@ Mesh *BKE_mesh_add(const char *name) me->texflag = ME_AUTOSPACE; me->flag = ME_TWOSIDED; me->drawflag = ME_DRAWEDGES | ME_DRAWFACES | ME_DRAWCREASES; - + + CustomData_reset(&me->vdata); + CustomData_reset(&me->edata); + CustomData_reset(&me->fdata); + CustomData_reset(&me->pdata); + CustomData_reset(&me->ldata); + return me; } @@ -576,7 +584,7 @@ static void expand_local_mesh(Mesh *me) for (i = 0; i < me->pdata.totlayer; i++) { if (me->pdata.layers[i].type == CD_MTEXPOLY) { - MTexPoly *txface = (MTexPoly *)me->fdata.layers[i].data; + MTexPoly *txface = (MTexPoly *)me->pdata.layers[i].data; for (a = 0; a < me->totpoly; a++, txface++) { /* special case: ima always local immediately */ @@ -735,7 +743,7 @@ float *BKE_mesh_orco_verts_get(Object *ob) /* Get appropriate vertex coordinates */ vcos = MEM_callocN(sizeof(*vcos) * me->totvert, "orco mesh"); mvert = tme->mvert; - totvert = MIN2(tme->totvert, me->totvert); + totvert = min_ii(tme->totvert, me->totvert); for (a = 0; a < totvert; a++, mvert++) { copy_v3_v3(vcos[a], mvert->co); @@ -2039,7 +2047,7 @@ static void bm_corners_to_loops_ex(ID *id, CustomData *fdata, CustomData *ldata, MDisps *ld = CustomData_get(ldata, loopstart, CD_MDISPS); MDisps *fd = CustomData_get(fdata, findex, CD_MDISPS); float (*disps)[3] = fd->disps; - int i, tot = mf->v4 ? 4 : 3; + int tot = mf->v4 ? 4 : 3; int side, corners; if (CustomData_external_test(fdata, CD_MDISPS)) { @@ -2125,8 +2133,6 @@ void BKE_mesh_convert_mfaces_to_mpolys_ex(ID *id, CustomData *fdata, CustomData /* just in case some of these layers are filled in (can happen with python created meshes) */ CustomData_free(ldata, totloop_i); CustomData_free(pdata, totpoly_i); - memset(ldata, 0, sizeof(*ldata)); - memset(pdata, 0, sizeof(*pdata)); totpoly = totface_i; mpoly = MEM_callocN(sizeof(MPoly) * totpoly, "mpoly converted"); @@ -2163,7 +2169,7 @@ void BKE_mesh_convert_mfaces_to_mpolys_ex(ID *id, CustomData *fdata, CustomData me->flag &= ~ME_FGON; } - polyindex = CustomData_get_layer(fdata, CD_POLYINDEX); + polyindex = CustomData_get_layer(fdata, CD_ORIGINDEX); j = 0; /* current loop index */ ml = mloop; @@ -2382,7 +2388,7 @@ void create_vert_poly_map(MeshElemMap **map, int **mem, * of edges that use that vertex as an endpoint. The lists are allocated * from one memory pool. */ void create_vert_edge_map(MeshElemMap **map, int **mem, - const MEdge *medge, int totvert, int totedge) + const MEdge *medge, int totvert, int totedge) { int i, *indices; @@ -2505,12 +2511,9 @@ int BKE_mesh_recalc_tessellation(CustomData *fdata, ScanFillContext sf_ctx; ScanFillVert *sf_vert, *sf_vert_last, *sf_vert_first; ScanFillFace *sf_tri; - int *mface_orig_index = NULL; - BLI_array_declare(mface_orig_index); int *mface_to_poly_map = NULL; BLI_array_declare(mface_to_poly_map); int lindex[4]; /* only ever use 3 in this case */ - int *poly_orig_index; int poly_index, j, mface_index; const int numTex = CustomData_number_of_layers(pdata, CD_MTEXPOLY); @@ -2528,7 +2531,6 @@ int BKE_mesh_recalc_tessellation(CustomData *fdata, mface_index = 0; mp = mpoly; - poly_orig_index = CustomData_get_layer(pdata, CD_ORIGINDEX); for (poly_index = 0; poly_index < totpoly; poly_index++, mp++) { if (mp->totloop < 3) { /* do nothing */ @@ -2548,10 +2550,6 @@ int BKE_mesh_recalc_tessellation(CustomData *fdata, mf->v4 = 0; \ mf->mat_nr = mp->mat_nr; \ mf->flag = mp->flag; \ - if (poly_orig_index) { \ - BLI_array_append(mface_orig_index, \ - poly_orig_index[poly_index]); \ - } \ (void)0 /* ALMOST IDENTICAL TO DEFINE ABOVE (see EXCEPTION) */ @@ -2567,10 +2565,6 @@ int BKE_mesh_recalc_tessellation(CustomData *fdata, mf->v4 = mp->loopstart + 3; /* EXCEPTION */ \ mf->mat_nr = mp->mat_nr; \ mf->flag = mp->flag; \ - if (poly_orig_index) { \ - BLI_array_append(mface_orig_index, \ - poly_orig_index[poly_index]); \ - } \ mf->edcode |= TESSFACE_IS_QUAD; /* EXCEPTION */ \ (void)0 @@ -2617,9 +2611,6 @@ int BKE_mesh_recalc_tessellation(CustomData *fdata, if (totfilltri) { BLI_array_grow_items(mface_to_poly_map, totfilltri); BLI_array_grow_items(mface, totfilltri); - if (poly_orig_index) { - BLI_array_grow_items(mface_orig_index, totfilltri); - } for (sf_tri = sf_ctx.fillfacebase.first; sf_tri; sf_tri = sf_tri->next, mf++) { mface_to_poly_map[mface_index] = poly_index; @@ -2638,10 +2629,6 @@ int BKE_mesh_recalc_tessellation(CustomData *fdata, mf->edcode |= TESSFACE_SCANFILL; /* tag for sorting loop indices */ #endif - if (poly_orig_index) { - mface_orig_index[mface_index] = poly_orig_index[poly_index]; - } - mface_index++; } } @@ -2651,7 +2638,6 @@ int BKE_mesh_recalc_tessellation(CustomData *fdata, } CustomData_free(fdata, totface); - memset(fdata, 0, sizeof(CustomData)); totface = mface_index; @@ -2659,23 +2645,13 @@ int BKE_mesh_recalc_tessellation(CustomData *fdata, if (LIKELY((MEM_allocN_len(mface) / sizeof(*mface)) != totface)) { mface = MEM_reallocN(mface, sizeof(*mface) * totface); mface_to_poly_map = MEM_reallocN(mface_to_poly_map, sizeof(*mface_to_poly_map) * totface); - if (mface_orig_index) { - mface_orig_index = MEM_reallocN(mface_orig_index, sizeof(*mface_orig_index) * totface); - } } CustomData_add_layer(fdata, CD_MFACE, CD_ASSIGN, mface, totface); - /* CD_POLYINDEX will contain an array of indices from tessfaces to the polygons + /* CD_ORIGINDEX will contain an array of indices from tessfaces to the polygons * they are directly tessellated from */ - CustomData_add_layer(fdata, CD_POLYINDEX, CD_ASSIGN, mface_to_poly_map, totface); - if (mface_orig_index) { - /* If polys had a CD_ORIGINDEX layer, then the tessellated faces will get this - * layer as well, pointing to polys from the original mesh (not the polys - * that just got tessellated) */ - CustomData_add_layer(fdata, CD_ORIGINDEX, CD_ASSIGN, mface_orig_index, totface); - } - + CustomData_add_layer(fdata, CD_ORIGINDEX, CD_ASSIGN, mface_to_poly_map, totface); CustomData_from_bmeshpoly(fdata, pdata, ldata, totface); if (do_face_nor_cpy) { @@ -2806,7 +2782,6 @@ int BKE_mesh_mpoly_to_mface(struct CustomData *fdata, struct CustomData *ldata, } CustomData_free(fdata, totface); - memset(fdata, 0, sizeof(CustomData)); totface = k; @@ -3175,6 +3150,32 @@ int BKE_mesh_center_bounds(Mesh *me, float cent[3]) return 0; } +int BKE_mesh_center_centroid(Mesh *me, float cent[3]) +{ + int i = me->totpoly; + MPoly *mpoly; + float poly_area; + float total_area = 0.0f; + float poly_cent[3]; + + zero_v3(cent); + + /* calculate a weighted average of polygon centroids */ + for (mpoly = me->mpoly; i--; mpoly++) { + BKE_mesh_calc_poly_center(mpoly, me->mloop + mpoly->loopstart, me->mvert, poly_cent); + poly_area = BKE_mesh_calc_poly_area(mpoly, me->mloop + mpoly->loopstart, me->mvert, NULL); + + madd_v3_v3fl(cent, poly_cent, poly_area); + total_area += poly_area; + } + /* otherwise we get NAN for 0 polys */ + if (me->totpoly) { + mul_v3_fl(cent, 1.0f / total_area); + } + + return (me->totpoly != 0); +} + void BKE_mesh_translate(Mesh *me, float offset[3], int do_keys) { int i = me->totvert; diff --git a/source/blender/blenkernel/intern/mesh_validate.c b/source/blender/blenkernel/intern/mesh_validate.c index 79e3fc19d20..128b9ae242e 100644 --- a/source/blender/blenkernel/intern/mesh_validate.c +++ b/source/blender/blenkernel/intern/mesh_validate.c @@ -228,7 +228,6 @@ int BKE_mesh_validate_arrays(Mesh *mesh, } for (i = 1; i < totvert; i++, mv++) { - int j; int fix_normal = TRUE; for (j = 0; j < 3; j++) { @@ -717,7 +716,6 @@ int BKE_mesh_validate_arrays(Mesh *mesh, MDeformVert *dv; for (i = 0, dv = dverts; i < totvert; i++, dv++) { MDeformWeight *dw; - unsigned int j; for (j = 0, dw = dv->dw; j < dv->totweight; j++, dw++) { /* note, greater then max defgroups is accounted for in our code, but not < 0 */ @@ -914,7 +912,7 @@ void BKE_mesh_calc_edges(Mesh *mesh, int update) { CustomData edata; EdgeHashIterator *ehi; - MPoly *mp = mesh->mpoly; + MPoly *mp; MEdge *med, *med_orig; EdgeHash *eh = BLI_edgehash_new(); int i, totedge, totpoly = mesh->totpoly; @@ -932,7 +930,7 @@ void BKE_mesh_calc_edges(Mesh *mesh, int update) } /* mesh loops (bmesh only) */ - for (i = 0; i < totpoly; i++, mp++) { + for (mp = mesh->mpoly, i = 0; i < totpoly; mp++, i++) { MLoop *l = &mesh->mloop[mp->loopstart]; int j, l_prev = (l + (mp->totloop - 1))->v; for (j = 0; j < mp->totloop; j++, l++) { @@ -946,7 +944,7 @@ void BKE_mesh_calc_edges(Mesh *mesh, int update) totedge = BLI_edgehash_size(eh); /* write new edges into a temporary CustomData */ - memset(&edata, 0, sizeof(edata)); + CustomData_reset(&edata); CustomData_add_layer(&edata, CD_MEDGE, CD_CALLOC, NULL, totedge); med = CustomData_get_layer(&edata, CD_MEDGE); @@ -970,8 +968,7 @@ void BKE_mesh_calc_edges(Mesh *mesh, int update) if (mesh->totpoly) { /* second pass, iterate through all loops again and assign * the newly created edges to them. */ - MPoly *mp = mesh->mpoly; - for (i = 0; i < mesh->totpoly; i++, mp++) { + for (mp = mesh->mpoly, i = 0; i < mesh->totpoly; mp++, i++) { MLoop *l = &mesh->mloop[mp->loopstart]; MLoop *l_prev = (l + (mp->totloop - 1)); int j; diff --git a/source/blender/blenkernel/intern/modifier.c b/source/blender/blenkernel/intern/modifier.c index 28de80a7157..9c7cbc42bdd 100644 --- a/source/blender/blenkernel/intern/modifier.c +++ b/source/blender/blenkernel/intern/modifier.c @@ -55,6 +55,8 @@ #include "BLI_linklist.h" #include "BLI_string.h" +#include "BLF_translation.h" + #include "BKE_cloth.h" #include "BKE_key.h" #include "BKE_multires.h" @@ -259,12 +261,13 @@ int modifier_nonGeometrical(ModifierData *md) return (mti->type == eModifierTypeType_NonGeometrical); } -void modifier_setError(ModifierData *md, const char *format, ...) +void modifier_setError(ModifierData *md, const char *_format, ...) { char buffer[512]; va_list ap; + const char *format = TIP_(_format); - va_start(ap, format); + va_start(ap, _format); vsnprintf(buffer, sizeof(buffer), format, ap); va_end(ap); buffer[sizeof(buffer) - 1] = '\0'; @@ -494,8 +497,8 @@ ModifierData *modifiers_getVirtualModifierList(Object *ob) return md; } -/* Takes an object and returns its first selected armature, else just its - * armature + +/* Takes an object and returns its first selected armature, else just its armature * This should work for multiple armatures per object */ Object *modifiers_isDeformedByArmature(Object *ob) @@ -518,9 +521,8 @@ Object *modifiers_isDeformedByArmature(Object *ob) return NULL; } -/* Takes an object and returns its first selected lattice, else just its - * lattice - * This should work for multiple lattics per object +/* Takes an object and returns its first selected lattice, else just its lattice + * This should work for multiple lattices per object */ Object *modifiers_isDeformedByLattice(Object *ob) { @@ -542,7 +544,28 @@ Object *modifiers_isDeformedByLattice(Object *ob) return NULL; } - +/* Takes an object and returns its first selected curve, else just its curve + * This should work for multiple curves per object + */ +Object *modifiers_isDeformedByCurve(Object *ob) +{ + ModifierData *md = modifiers_getVirtualModifierList(ob); + CurveModifierData *cmd = NULL; + + /* return the first selected curve, this lets us use multiple curves */ + for (; md; md = md->next) { + if (md->type == eModifierType_Curve) { + cmd = (CurveModifierData *) md; + if (cmd->object && (cmd->object->flag & SELECT)) + return cmd->object; + } + } + + if (cmd) /* if were still here then return the last curve */ + return cmd->object; + + return NULL; +} int modifiers_usesArmature(Object *ob, bArmature *arm) { @@ -574,10 +597,12 @@ int modifiers_isCorrectableDeformed(Object *ob) ModifierData *md = modifiers_getVirtualModifierList(ob); for (; md; md = md->next) { - if (ob->mode == OB_MODE_EDIT && (md->mode & eModifierMode_Editmode) == 0) ; - else - if (modifier_isCorrectableDeformed(md)) + if (ob->mode == OB_MODE_EDIT && (md->mode & eModifierMode_Editmode) == 0) { + /* pass */ + } + else if (modifier_isCorrectableDeformed(md)) { return 1; + } } return 0; } diff --git a/source/blender/blenkernel/intern/modifiers_bmesh.c b/source/blender/blenkernel/intern/modifiers_bmesh.c index dc3d4a89e62..98eac9b95af 100644 --- a/source/blender/blenkernel/intern/modifiers_bmesh.c +++ b/source/blender/blenkernel/intern/modifiers_bmesh.c @@ -55,6 +55,7 @@ void DM_to_bmesh_ex(DerivedMesh *dm, BMesh *bm) BLI_array_declare(verts); BLI_array_declare(edges); int i, j, k, totvert, totedge /* , totface */ /* UNUSED */ ; + int is_init = (bm->totvert == 0) && (bm->totedge == 0) && (bm->totface == 0); /*merge custom data layout*/ CustomData_bmesh_merge(&dm->vertData, &bm->vdata, CD_MASK_DERIVEDMESH, CD_CALLOC, bm, BM_VERT); @@ -81,6 +82,7 @@ void DM_to_bmesh_ex(DerivedMesh *dm, BMesh *bm) v = BM_vert_create(bm, mv->co, NULL); normal_short_to_float_v3(v->no, mv->no); v->head.hflag = BM_vert_flag_from_mflag(mv->flag); + BM_elem_index_set(v, i); /* set_inline */ CustomData_to_bmesh_block(&dm->vertData, &bm->vdata, i, &v->head.data); @@ -89,13 +91,16 @@ void DM_to_bmesh_ex(DerivedMesh *dm, BMesh *bm) vtable[i] = v; } MEM_freeN(mvert); + if (is_init) bm->elem_index_dirty &= ~BM_VERT; /*do edges*/ me = medge = dm->dupEdgeArray(dm); for (i = 0; i < totedge; i++, me++) { + //BLI_assert(BM_edge_exists(vtable[me->v1], vtable[me->v2]) == NULL); e = BM_edge_create(bm, vtable[me->v1], vtable[me->v2], NULL, FALSE); e->head.hflag = BM_edge_flag_from_mflag(me->flag); + BM_elem_index_set(e, i); /* set_inline */ CustomData_to_bmesh_block(&dm->edgeData, &bm->edata, i, &e->head.data); etable[i] = e; @@ -106,8 +111,10 @@ void DM_to_bmesh_ex(DerivedMesh *dm, BMesh *bm) BM_elem_float_data_set(&bm->edata, e, CD_BWEIGHT, (float)me->bweight / 255.0f); } MEM_freeN(medge); + if (is_init) bm->elem_index_dirty &= ~BM_EDGE; - /*do faces*/ + /* do faces */ + /* note: i_alt is aligned with bmesh faces which may not always align with mpolys */ mp = dm->getPolyArray(dm); mloop = dm->getLoopArray(dm); face_normals = CustomData_get_layer(&dm->polyData, CD_NORMAL); /* can be NULL */ @@ -134,6 +141,7 @@ void DM_to_bmesh_ex(DerivedMesh *dm, BMesh *bm) } f->head.hflag = BM_face_flag_from_mflag(mp->flag); + BM_elem_index_set(f, bm->totface - 1); /* set_inline */ f->mat_nr = mp->mat_nr; l = BM_iter_new(&liter, bm, BM_LOOPS_OF_FACE, f); @@ -151,6 +159,7 @@ void DM_to_bmesh_ex(DerivedMesh *dm, BMesh *bm) BM_face_normal_update(f); } } + if (is_init) bm->elem_index_dirty &= ~BM_FACE; MEM_freeN(vtable); MEM_freeN(etable); diff --git a/source/blender/blenkernel/intern/movieclip.c b/source/blender/blenkernel/intern/movieclip.c index 0aa1f9e0822..4156b5b4367 100644 --- a/source/blender/blenkernel/intern/movieclip.c +++ b/source/blender/blenkernel/intern/movieclip.c @@ -520,6 +520,24 @@ static void movieclip_load_get_szie(MovieClip *clip) } } +static void detect_clip_source(MovieClip *clip) +{ + ImBuf *ibuf; + char name[FILE_MAX]; + + BLI_strncpy(name, clip->name, sizeof(name)); + BLI_path_abs(name, G.main->name); + + ibuf = IMB_testiffname(name, IB_rect | IB_multilayer); + if (ibuf) { + clip->source = MCLIP_SRC_SEQUENCE; + IMB_freeImBuf(ibuf); + } + else { + clip->source = MCLIP_SRC_MOVIE; + } +} + /* checks if image was already loaded, then returns same image * otherwise creates new. * does not load ibuf itself @@ -565,10 +583,7 @@ MovieClip *BKE_movieclip_file_add(const char *name) clip = movieclip_alloc(libname); BLI_strncpy(clip->name, name, sizeof(clip->name)); - if (BLI_testextensie_array(name, imb_ext_movie)) - clip->source = MCLIP_SRC_MOVIE; - else - clip->source = MCLIP_SRC_SEQUENCE; + detect_clip_source(clip); movieclip_load_get_szie(clip); if (clip->lastsize[0]) { @@ -616,11 +631,6 @@ static ImBuf *get_undistorted_ibuf(MovieClip *clip, struct MovieDistortion *dist else undistibuf = BKE_tracking_undistort_frame(&clip->tracking, ibuf, ibuf->x, ibuf->y, 0.0f); - if (undistibuf->userflags & IB_RECT_INVALID) { - ibuf->userflags &= ~IB_RECT_INVALID; - IMB_rect_from_float(undistibuf); - } - IMB_scaleImBuf(undistibuf, ibuf->x, ibuf->y); return undistibuf; @@ -1087,15 +1097,24 @@ void BKE_movieclip_reload(MovieClip *clip) clip->tracking.stabilization.ok = FALSE; /* update clip source */ - if (BLI_testextensie_array(clip->name, imb_ext_movie)) - clip->source = MCLIP_SRC_MOVIE; - else - clip->source = MCLIP_SRC_SEQUENCE; + detect_clip_source(clip); clip->lastsize[0] = clip->lastsize[1] = 0; movieclip_load_get_szie(clip); movieclip_calc_length(clip); + + /* same as for image update -- don't use notifiers because they are not 100% sure to succeeded + * (node trees which are not currently visible wouldn't be refreshed) + */ + { + Scene *scene; + for (scene = G.main->scene.first; scene; scene = scene->id.next) { + if (scene->nodetree) { + nodeUpdateID(scene->nodetree, &clip->id); + } + } + } } void BKE_movieclip_update_scopes(MovieClip *clip, MovieClipUser *user, MovieClipScopes *scopes) @@ -1157,13 +1176,16 @@ void BKE_movieclip_update_scopes(MovieClip *clip, MovieClipUser *user, MovieClip search_ibuf = BKE_tracking_get_search_imbuf(ibuf, track, &undist_marker, TRUE, TRUE); - if (!search_ibuf->rect_float) { - /* sampling happens in float buffer */ - IMB_float_from_rect(search_ibuf); + if (search_ibuf) { + if (!search_ibuf->rect_float) { + /* sampling happens in float buffer */ + IMB_float_from_rect(search_ibuf); + } + + scopes->track_search = search_ibuf; } scopes->undist_marker = undist_marker; - scopes->track_search = search_ibuf; scopes->frame_width = ibuf->x; scopes->frame_height = ibuf->y; diff --git a/source/blender/blenkernel/intern/multires.c b/source/blender/blenkernel/intern/multires.c index 591524e5156..c737dccc5d2 100644 --- a/source/blender/blenkernel/intern/multires.c +++ b/source/blender/blenkernel/intern/multires.c @@ -984,7 +984,7 @@ static void grid_tangent(const CCGKey *key, int x, int y, int axis, CCGElem *gri /* Construct 3x3 tangent-space matrix in 'mat' */ static void grid_tangent_matrix(float mat[3][3], const CCGKey *key, - int x, int y, CCGElem *grid) + int x, int y, CCGElem *grid) { grid_tangent(key, x, y, 0, grid, mat[0]); normalize_v3(mat[0]); @@ -1045,7 +1045,7 @@ static void multiresModifier_disp_run(DerivedMesh *dm, Mesh *me, DerivedMesh *dm k = 0; /*current loop/mdisp index within the mloop array*/ - #pragma omp parallel for private(i) if (totloop*gridSize*gridSize >= CCG_OMP_LIMIT) + #pragma omp parallel for private(i) if (totloop * gridSize * gridSize >= CCG_OMP_LIMIT) for (i = 0; i < totpoly; ++i) { const int numVerts = mpoly[i].totloop; @@ -1161,7 +1161,6 @@ void multires_modifier_update_mdisps(struct DerivedMesh *dm) int totlvl = ccgdm->multires.totlvl; if (lvl < totlvl) { - Mesh *me = ob->data; DerivedMesh *lowdm, *cddm, *highdm; CCGElem **highGridData, **lowGridData, **subGridData, **gridData, *diffGrid; CCGKey highGridKey, lowGridKey; @@ -1326,7 +1325,7 @@ void multires_set_space(DerivedMesh *dm, Object *ob, int from, int to) k = 0; /*current loop/mdisp index within the mloop array*/ - //#pragma omp parallel for private(i) if (dm->numLoopData*gridSize*gridSize >= CCG_OMP_LIMIT) + //#pragma omp parallel for private(i) if (dm->numLoopData * gridSize * gridSize >= CCG_OMP_LIMIT) for (i = 0; i < dm->numPolyData; ++i) { const int numVerts = mpoly[i].totloop; @@ -1631,7 +1630,7 @@ void multires_free(Multires *mr) } while (lvl) { - multires_free_level(lvl); + multires_free_level(lvl); lvl = lvl->next; } @@ -2086,8 +2085,8 @@ void multires_load_old(Object *ob, Mesh *me) 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) CustomData_add_layer(&me->fdata, l->type, CD_REFERENCE, l->data, me->totface); - memset(&me->mr->vdata, 0, sizeof(CustomData)); - memset(&me->mr->fdata, 0, sizeof(CustomData)); + CustomData_reset(&me->mr->vdata); + CustomData_reset(&me->mr->fdata); multires_load_old_vcols(me); multires_load_old_face_flags(me); @@ -2201,7 +2200,7 @@ static void multires_apply_smat(Scene *scene, Object *ob, float smat[3][3]) dGridSize = multires_side_tot[high_mmd.totlvl]; dSkip = (dGridSize - 1) / (gridSize - 1); - #pragma omp parallel for private(i) if (me->totface*gridSize*gridSize*4 >= CCG_OMP_LIMIT) + #pragma omp parallel for private(i) if (me->totface * gridSize * gridSize * 4 >= CCG_OMP_LIMIT) for (i = 0; i < me->totpoly; ++i) { const int numVerts = mpoly[i].totloop; MDisps *mdisp = &mdisps[mpoly[i].loopstart]; diff --git a/source/blender/blenkernel/intern/navmesh_conversion.c b/source/blender/blenkernel/intern/navmesh_conversion.c index a21878d1d7d..3bf5f863557 100644 --- a/source/blender/blenkernel/intern/navmesh_conversion.c +++ b/source/blender/blenkernel/intern/navmesh_conversion.c @@ -36,44 +36,44 @@ #include "DNA_meshdata_types.h" -#include "BKE_navmesh_conversion.h" -#include "BKE_cdderivedmesh.h" - #include "BLI_utildefines.h" #include "BLI_math.h" +#include "BKE_navmesh_conversion.h" +#include "BKE_cdderivedmesh.h" + #include "recast-capi.h" -BLI_INLINE float area2(const float* a, const float* b, const float* c) +BLI_INLINE float area2(const float *a, const float *b, const float *c) { return (b[0] - a[0]) * (c[2] - a[2]) - (c[0] - a[0]) * (b[2] - a[2]); } -BLI_INLINE int left(const float* a, const float* b, const float* c) +BLI_INLINE int left(const float *a, const float *b, const float *c) { return area2(a, b, c) < 0; } -int polyNumVerts(const unsigned short* p, const int vertsPerPoly) +int polyNumVerts(const unsigned short *p, const int vertsPerPoly) { int i, nv = 0; - for (i=0; i<vertsPerPoly; i++) { - if (p[i]==0xffff) + for (i = 0; i < vertsPerPoly; i++) { + if (p[i] == 0xffff) break; nv++; } return nv; } -int polyIsConvex(const unsigned short* p, const int vertsPerPoly, const float* verts) +int polyIsConvex(const unsigned short *p, const int vertsPerPoly, const float *verts) { int j, nv = polyNumVerts(p, vertsPerPoly); - if (nv<3) + if (nv < 3) return 0; - for (j=0; j<nv; j++) { - const float* v = &verts[3*p[j]]; - const float* v_next = &verts[3*p[(j+1)%nv]]; - const float* v_prev = &verts[3*p[(nv+j-1)%nv]]; + for (j = 0; j < nv; j++) { + const float *v = &verts[3 * p[j]]; + const float *v_next = &verts[3 * p[(j + 1) % nv]]; + const float *v_prev = &verts[3 * p[(nv + j - 1) % nv]]; if (!left(v_prev, v, v_next)) return 0; @@ -81,7 +81,8 @@ int polyIsConvex(const unsigned short* p, const int vertsPerPoly, const float* v return 1; } -float distPointToSegmentSq(const float* point, const float* a, const float* b) +/* XXX, could replace with #dist_to_line_segment_v3(), or add a squared version */ +float distPointToSegmentSq(const float point[3], const float a[3], const float b[3]) { float abx[3], dx[3]; float d, t; @@ -89,24 +90,24 @@ float distPointToSegmentSq(const float* point, const float* a, const float* b) sub_v3_v3v3(abx, b, a); sub_v3_v3v3(dx, point, a); - d = abx[0]*abx[0]+abx[2]*abx[2]; - t = abx[0]*dx[0]+abx[2]*dx[2]; + d = abx[0] * abx[0] + abx[2] * abx[2]; + t = abx[0] * dx[0] + abx[2] * dx[2]; - if (d > 0) + if (d > 0.0f) t /= d; - if (t < 0) - t = 0; - else if (t > 1) - t = 1; - dx[0] = a[0] + t*abx[0] - point[0]; - dx[2] = a[2] + t*abx[2] - point[2]; - - return dx[0]*dx[0] + dx[2]*dx[2]; + if (t < 0.0f) + t = 0.0f; + else if (t > 1.0f) + t = 1.0f; + dx[0] = a[0] + t * abx[0] - point[0]; + dx[2] = a[2] + t * abx[2] - point[2]; + + return dx[0] * dx[0] + dx[2] * dx[2]; } -int buildRawVertIndicesData(DerivedMesh* dm, int *nverts_r, float **verts_r, - int *ntris_r, unsigned short **tris_r, int **trisToFacesMap_r, - int **recastData) +int buildRawVertIndicesData(DerivedMesh *dm, int *nverts_r, float **verts_r, + int *ntris_r, unsigned short **tris_r, int **trisToFacesMap_r, + int **recastData) { int vi, fi, triIdx; int nverts, ntris; @@ -117,49 +118,49 @@ int buildRawVertIndicesData(DerivedMesh* dm, int *nverts_r, float **verts_r, MFace *faces; nverts = dm->getNumVerts(dm); - if (nverts>=0xffff) { + if (nverts >= 0xffff) { printf("Converting navmesh: Error! Too many vertices. Max number of vertices %d\n", 0xffff); return 0; } - verts = MEM_callocN(sizeof(float)*3*nverts, "buildRawVertIndicesData verts"); + verts = MEM_callocN(sizeof(float) * 3 * nverts, "buildRawVertIndicesData verts"); dm->getVertCos(dm, (float(*)[3])verts); - //flip coordinates - for (vi=0; vi<nverts; vi++) { - SWAP(float, verts[3*vi+1], verts[3*vi+2]); + /* flip coordinates */ + for (vi = 0; vi < nverts; vi++) { + SWAP(float, verts[3 * vi + 1], verts[3 * vi + 2]); } - //calculate number of tris + /* calculate number of tris */ nfaces = dm->getNumTessFaces(dm); faces = dm->getTessFaceArray(dm); ntris = nfaces; - for (fi=0; fi<nfaces; fi++) { - MFace* face = &faces[fi]; + for (fi = 0; fi < nfaces; fi++) { + MFace *face = &faces[fi]; if (face->v4) ntris++; } - //copy and transform to triangles (reorder on the run) - trisToFacesMap = MEM_callocN(sizeof(int)*ntris, "buildRawVertIndicesData trisToFacesMap"); - tris = MEM_callocN(sizeof(unsigned short)*3*ntris, "buildRawVertIndicesData tris"); + /* copy and transform to triangles (reorder on the run) */ + trisToFacesMap = MEM_callocN(sizeof(int) * ntris, "buildRawVertIndicesData trisToFacesMap"); + tris = MEM_callocN(sizeof(unsigned short) * 3 * ntris, "buildRawVertIndicesData tris"); tri = tris; triIdx = 0; - for (fi=0; fi<nfaces; fi++) { - MFace* face = &faces[fi]; - tri[3*triIdx+0] = (unsigned short) face->v1; - tri[3*triIdx+1] = (unsigned short) face->v3; - tri[3*triIdx+2] = (unsigned short) face->v2; - trisToFacesMap[triIdx++]=fi; + for (fi = 0; fi < nfaces; fi++) { + MFace *face = &faces[fi]; + tri[3 * triIdx + 0] = (unsigned short) face->v1; + tri[3 * triIdx + 1] = (unsigned short) face->v3; + tri[3 * triIdx + 2] = (unsigned short) face->v2; + trisToFacesMap[triIdx++] = fi; if (face->v4) { - tri[3*triIdx+0] = (unsigned short) face->v1; - tri[3*triIdx+1] = (unsigned short) face->v4; - tri[3*triIdx+2] = (unsigned short) face->v3; - trisToFacesMap[triIdx++]=fi; + tri[3 * triIdx + 0] = (unsigned short) face->v1; + tri[3 * triIdx + 1] = (unsigned short) face->v4; + tri[3 * triIdx + 2] = (unsigned short) face->v3; + trisToFacesMap[triIdx++] = fi; } } - //carefully, recast data is just reference to data in derived mesh - *recastData = (int*)CustomData_get_layer(&dm->polyData, CD_RECAST); + /* carefully, recast data is just reference to data in derived mesh */ + *recastData = (int *)CustomData_get_layer(&dm->polyData, CD_RECAST); *nverts_r = nverts; *verts_r = verts; @@ -170,122 +171,122 @@ int buildRawVertIndicesData(DerivedMesh* dm, int *nverts_r, float **verts_r, return 1; } -int buildPolygonsByDetailedMeshes(const int vertsPerPoly, const int npolys, - unsigned short* polys, const unsigned short* dmeshes, - const float* verts, const unsigned short* dtris, - const int* dtrisToPolysMap) +int buildPolygonsByDetailedMeshes(const int vertsPerPoly, const int npolys, + unsigned short *polys, const unsigned short *dmeshes, + const float *verts, const unsigned short *dtris, + const int *dtrisToPolysMap) { int polyidx; int capacity = vertsPerPoly; - unsigned short* newPoly = MEM_callocN(sizeof(unsigned short)*capacity, "buildPolygonsByDetailedMeshes newPoly"); - memset(newPoly, 0xff, sizeof(unsigned short)*capacity); + unsigned short *newPoly = MEM_callocN(sizeof(unsigned short) * capacity, "buildPolygonsByDetailedMeshes newPoly"); + memset(newPoly, 0xff, sizeof(unsigned short) * capacity); - for (polyidx=0; polyidx<npolys; polyidx++) { + for (polyidx = 0; polyidx < npolys; polyidx++) { size_t i; int j, k; int nv = 0; - //search border + /* search border */ int tri, btri = -1; int edge, bedge = -1; - int dtrisNum = dmeshes[polyidx*4+3]; - int dtrisBase = dmeshes[polyidx*4+2]; - unsigned char *traversedTris = MEM_callocN(sizeof(unsigned char)*dtrisNum, "buildPolygonsByDetailedMeshes traversedTris"); - unsigned short* adjustedPoly; + int dtrisNum = dmeshes[polyidx * 4 + 3]; + int dtrisBase = dmeshes[polyidx * 4 + 2]; + unsigned char *traversedTris = MEM_callocN(sizeof(unsigned char) * dtrisNum, "buildPolygonsByDetailedMeshes traversedTris"); + unsigned short *adjustedPoly; int adjustedNv; int allBorderTraversed; - for (j=0; j<dtrisNum && btri==-1;j++) { - int curpolytri = dtrisBase+j; - for (k=0; k<3; k++) { - unsigned short neighbortri = dtris[curpolytri*3*2+3+k]; - if ( neighbortri==0xffff || dtrisToPolysMap[neighbortri]!=polyidx+1) { + for (j = 0; j < dtrisNum && btri == -1; j++) { + int curpolytri = dtrisBase + j; + for (k = 0; k < 3; k++) { + unsigned short neighbortri = dtris[curpolytri * 3 * 2 + 3 + k]; + if (neighbortri == 0xffff || dtrisToPolysMap[neighbortri] != polyidx + 1) { btri = curpolytri; bedge = k; break; } - } + } } - if (btri==-1 || bedge==-1) { - //can't find triangle with border edge + if (btri == -1 || bedge == -1) { + /* can't find triangle with border edge */ MEM_freeN(traversedTris); MEM_freeN(newPoly); return 0; } - newPoly[nv++] = dtris[btri*3*2+bedge]; + newPoly[nv++] = dtris[btri * 3 * 2 + bedge]; tri = btri; - edge = (bedge+1)%3; - traversedTris[tri-dtrisBase] = 1; + edge = (bedge + 1) % 3; + traversedTris[tri - dtrisBase] = 1; while (tri != btri || edge != bedge) { - int neighbortri = dtris[tri*3*2+3+edge]; - if (neighbortri==0xffff || dtrisToPolysMap[neighbortri]!=polyidx+1) { - if (nv==capacity) { - unsigned short* newPolyBig; + int neighbortri = dtris[tri * 3 * 2 + 3 + edge]; + if (neighbortri == 0xffff || dtrisToPolysMap[neighbortri] != polyidx + 1) { + if (nv == capacity) { + unsigned short *newPolyBig; capacity += vertsPerPoly; - newPolyBig = MEM_callocN(sizeof(unsigned short)*capacity, "buildPolygonsByDetailedMeshes newPolyBig"); - memset(newPolyBig, 0xff, sizeof(unsigned short)*capacity); - memcpy(newPolyBig, newPoly, sizeof(unsigned short)*nv); + newPolyBig = MEM_callocN(sizeof(unsigned short) * capacity, "buildPolygonsByDetailedMeshes newPolyBig"); + memset(newPolyBig, 0xff, sizeof(unsigned short) * capacity); + memcpy(newPolyBig, newPoly, sizeof(unsigned short) * nv); MEM_freeN(newPoly); - newPoly = newPolyBig; + newPoly = newPolyBig; } - newPoly[nv++] = dtris[tri*3*2+edge]; - //move to next edge - edge = (edge+1)%3; + newPoly[nv++] = dtris[tri * 3 * 2 + edge]; + /* move to next edge */ + edge = (edge + 1) % 3; } else { - //move to next tri + /* move to next tri */ int twinedge = -1; - for (k=0; k<3; k++) { - if (dtris[neighbortri*3*2+3+k] == tri) { + for (k = 0; k < 3; k++) { + if (dtris[neighbortri * 3 * 2 + 3 + k] == tri) { twinedge = k; break; } } - if (twinedge==-1) { + if (twinedge == -1) { printf("Converting navmesh: Error! Can't find neighbor edge - invalid adjacency info\n"); MEM_freeN(traversedTris); goto returnLabel; } tri = neighbortri; - edge = (twinedge+1)%3; - traversedTris[tri-dtrisBase] = 1; + edge = (twinedge + 1) % 3; + traversedTris[tri - dtrisBase] = 1; } } - adjustedPoly = MEM_callocN(sizeof(unsigned short)*nv, "buildPolygonsByDetailedMeshes adjustedPoly"); + adjustedPoly = MEM_callocN(sizeof(unsigned short) * nv, "buildPolygonsByDetailedMeshes adjustedPoly"); adjustedNv = 0; - for (i=0; i<nv; i++) { - unsigned short prev = newPoly[(nv+i-1)%nv]; + for (i = 0; i < nv; i++) { + unsigned short prev = newPoly[(nv + i - 1) % nv]; unsigned short cur = newPoly[i]; - unsigned short next = newPoly[(i+1)%nv]; - float distSq = distPointToSegmentSq(&verts[3*cur], &verts[3*prev], &verts[3*next]); + unsigned short next = newPoly[(i + 1) % nv]; + float distSq = distPointToSegmentSq(&verts[3 * cur], &verts[3 * prev], &verts[3 * next]); static const float tolerance = 0.001f; - if (distSq>tolerance) + if (distSq > tolerance) adjustedPoly[adjustedNv++] = cur; } - memcpy(newPoly, adjustedPoly, adjustedNv*sizeof(unsigned short)); + memcpy(newPoly, adjustedPoly, adjustedNv * sizeof(unsigned short)); MEM_freeN(adjustedPoly); nv = adjustedNv; allBorderTraversed = 1; - for (i=0; i<dtrisNum; i++) { - if (traversedTris[i]==0) { - //check whether it has border edges - int curpolytri = dtrisBase+i; - for (k=0; k<3; k++) { - unsigned short neighbortri = dtris[curpolytri*3*2+3+k]; - if ( neighbortri==0xffff || dtrisToPolysMap[neighbortri]!=polyidx+1) { + for (i = 0; i < dtrisNum; i++) { + if (traversedTris[i] == 0) { + /* check whether it has border edges */ + int curpolytri = dtrisBase + i; + for (k = 0; k < 3; k++) { + unsigned short neighbortri = dtris[curpolytri * 3 * 2 + 3 + k]; + if (neighbortri == 0xffff || dtrisToPolysMap[neighbortri] != polyidx + 1) { allBorderTraversed = 0; break; } } - } + } } - if (nv<=vertsPerPoly && allBorderTraversed) { - for (i=0; i<nv; i++) { - polys[polyidx*vertsPerPoly*2+i] = newPoly[i]; + if (nv <= vertsPerPoly && allBorderTraversed) { + for (i = 0; i < nv; i++) { + polys[polyidx * vertsPerPoly * 2 + i] = newPoly[i]; } } @@ -298,21 +299,20 @@ returnLabel: return 1; } -struct SortContext -{ - const int* recastData; - const int* trisToFacesMap; +struct SortContext { + const int *recastData; + const int *trisToFacesMap; }; -static int compareByData(void *ctx, const void * a, const void * b) +static int compareByData(void *ctx, const void *a, const void *b) { - return (((struct SortContext *)ctx)->recastData[((struct SortContext *)ctx)->trisToFacesMap[*(int*)a]] - - ((struct SortContext *)ctx)->recastData[((struct SortContext *)ctx)->trisToFacesMap[*(int*)b]] ); + return (((struct SortContext *)ctx)->recastData[((struct SortContext *)ctx)->trisToFacesMap[*(int *)a]] - + ((struct SortContext *)ctx)->recastData[((struct SortContext *)ctx)->trisToFacesMap[*(int *)b]]); } -int buildNavMeshData(const int nverts, const float* verts, +int buildNavMeshData(const int nverts, const float *verts, const int ntris, const unsigned short *tris, - const int* recastData, const int* trisToFacesMap, + const int *recastData, const int *trisToFacesMap, int *ndtris_r, unsigned short **dtris_r, int *npolys_r, unsigned short **dmeshes_r, unsigned short **polys_r, int *vertsPerPoly_r, int **dtrisToPolysMap_r, int **dtrisToTrisMap_r) @@ -333,86 +333,86 @@ int buildNavMeshData(const int nverts, const float* verts, return 0; } - trisMapping = MEM_callocN(sizeof(int)*ntris, "buildNavMeshData trisMapping"); + trisMapping = MEM_callocN(sizeof(int) * ntris, "buildNavMeshData trisMapping"); - //sort the triangles by polygon idx - for (i=0; i<ntris; i++) - trisMapping[i]=i; + /* sort the triangles by polygon idx */ + for (i = 0; i < ntris; i++) + trisMapping[i] = i; context.recastData = recastData; context.trisToFacesMap = trisToFacesMap; recast_qsort(trisMapping, ntris, sizeof(int), &context, compareByData); - //search first valid triangle - triangle of convex polygon + /* search first valid triangle - triangle of convex polygon */ validTriStart = -1; - for (i=0; i< ntris; i++) { - if (recastData[trisToFacesMap[trisMapping[i]]]>0) { + for (i = 0; i < ntris; i++) { + if (recastData[trisToFacesMap[trisMapping[i]]] > 0) { validTriStart = i; break; } } - if (validTriStart<0) { + if (validTriStart < 0) { printf("Converting navmesh: Error! No valid polygons in mesh\n"); MEM_freeN(trisMapping); return 0; } - ndtris = ntris-validTriStart; - //fill dtris to faces mapping - dtrisToTrisMap = MEM_callocN(sizeof(int)*ndtris, "buildNavMeshData dtrisToTrisMap"); - memcpy(dtrisToTrisMap, &trisMapping[validTriStart], ndtris*sizeof(int)); + ndtris = ntris - validTriStart; + /* fill dtris to faces mapping */ + dtrisToTrisMap = MEM_callocN(sizeof(int) * ndtris, "buildNavMeshData dtrisToTrisMap"); + memcpy(dtrisToTrisMap, &trisMapping[validTriStart], ndtris * sizeof(int)); MEM_freeN(trisMapping); - //create detailed mesh triangles - copy only valid triangles - //and reserve memory for adjacency info - dtris = MEM_callocN(sizeof(unsigned short)*3*2*ndtris, "buildNavMeshData dtris"); - memset(dtris, 0xffff, sizeof(unsigned short)*3*2*ndtris); - for (i=0; i<ndtris; i++) { - memcpy(dtris+3*2*i, tris+3*dtrisToTrisMap[i], sizeof(unsigned short)*3); + /* create detailed mesh triangles - copy only valid triangles + * and reserve memory for adjacency info */ + dtris = MEM_callocN(sizeof(unsigned short) * 3 * 2 * ndtris, "buildNavMeshData dtris"); + memset(dtris, 0xffff, sizeof(unsigned short) * 3 * 2 * ndtris); + for (i = 0; i < ndtris; i++) { + memcpy(dtris + 3 * 2 * i, tris + 3 * dtrisToTrisMap[i], sizeof(unsigned short) * 3); } - //create new recast data corresponded to dtris and renumber for continuous indices + /* create new recast data corresponded to dtris and renumber for continuous indices */ prevPolyIdx = -1; newPolyIdx = 0; - dtrisToPolysMap = MEM_callocN(sizeof(int)*ndtris, "buildNavMeshData dtrisToPolysMap"); - for (i=0; i<ndtris; i++) { + dtrisToPolysMap = MEM_callocN(sizeof(int) * ndtris, "buildNavMeshData dtrisToPolysMap"); + for (i = 0; i < ndtris; i++) { curPolyIdx = recastData[trisToFacesMap[dtrisToTrisMap[i]]]; - if (curPolyIdx!=prevPolyIdx) { + if (curPolyIdx != prevPolyIdx) { newPolyIdx++; - prevPolyIdx=curPolyIdx; + prevPolyIdx = curPolyIdx; } dtrisToPolysMap[i] = newPolyIdx; } - //build adjacency info for detailed mesh triangles + /* build adjacency info for detailed mesh triangles */ recast_buildMeshAdjacency(dtris, ndtris, nverts, 3); - //create detailed mesh description for each navigation polygon - npolys = dtrisToPolysMap[ndtris-1]; - dmeshes = MEM_callocN(sizeof(unsigned short)*npolys*4, "buildNavMeshData dmeshes"); - memset(dmeshes, 0, npolys*4*sizeof(unsigned short)); + /* create detailed mesh description for each navigation polygon */ + npolys = dtrisToPolysMap[ndtris - 1]; + dmeshes = MEM_callocN(sizeof(unsigned short) * npolys * 4, "buildNavMeshData dmeshes"); + memset(dmeshes, 0, npolys * 4 * sizeof(unsigned short)); dmesh = NULL; prevpolyidx = 0; - for (i=0; i<ndtris; i++) { + for (i = 0; i < ndtris; i++) { int curpolyidx = dtrisToPolysMap[i]; - if (curpolyidx!=prevpolyidx) { - if (curpolyidx!=prevpolyidx+1) { + if (curpolyidx != prevpolyidx) { + if (curpolyidx != prevpolyidx + 1) { printf("Converting navmesh: Error! Wrong order of detailed mesh faces\n"); return 0; } - dmesh = dmesh==NULL ? dmeshes : dmesh+4; - dmesh[2] = (unsigned short)i; //tbase - dmesh[3] = 0; //tnum + dmesh = dmesh == NULL ? dmeshes : dmesh + 4; + dmesh[2] = (unsigned short)i; /* tbase */ + dmesh[3] = 0; /* tnum */ prevpolyidx = curpolyidx; } dmesh[3]++; } - //create navigation polygons + /* create navigation polygons */ vertsPerPoly = 6; - polys = MEM_callocN(sizeof(unsigned short)*npolys*vertsPerPoly*2, "buildNavMeshData polys"); - memset(polys, 0xff, sizeof(unsigned short)*vertsPerPoly*2*npolys); + polys = MEM_callocN(sizeof(unsigned short) * npolys * vertsPerPoly * 2, "buildNavMeshData polys"); + memset(polys, 0xff, sizeof(unsigned short) * vertsPerPoly * 2 * npolys); buildPolygonsByDetailedMeshes(vertsPerPoly, npolys, polys, dmeshes, verts, dtris, dtrisToPolysMap); @@ -429,16 +429,16 @@ int buildNavMeshData(const int nverts, const float* verts, } -int buildNavMeshDataByDerivedMesh(DerivedMesh *dm, int *vertsPerPoly, - int *nverts, float **verts, - int *ndtris, unsigned short **dtris, - int *npolys, unsigned short **dmeshes, - unsigned short **polys, int **dtrisToPolysMap, - int **dtrisToTrisMap, int **trisToFacesMap) +int buildNavMeshDataByDerivedMesh(DerivedMesh *dm, int *vertsPerPoly, + int *nverts, float **verts, + int *ndtris, unsigned short **dtris, + int *npolys, unsigned short **dmeshes, + unsigned short **polys, int **dtrisToPolysMap, + int **dtrisToTrisMap, int **trisToFacesMap) { int res = 1; - int ntris = 0, *recastData=NULL; - unsigned short *tris=NULL; + int ntris = 0, *recastData = NULL; + unsigned short *tris = NULL; res = buildRawVertIndicesData(dm, nverts, verts, &ntris, &tris, trisToFacesMap, &recastData); if (!res) { @@ -447,8 +447,8 @@ int buildNavMeshDataByDerivedMesh(DerivedMesh *dm, int *vertsPerPoly, } res = buildNavMeshData(*nverts, *verts, ntris, tris, recastData, *trisToFacesMap, - ndtris, dtris, npolys, dmeshes, polys, vertsPerPoly, - dtrisToPolysMap, dtrisToTrisMap); + ndtris, dtris, npolys, dmeshes, polys, vertsPerPoly, + dtrisToPolysMap, dtrisToTrisMap); if (!res) { printf("Converting navmesh: Error! Can't get vertices and indices from mesh\n"); goto exit; @@ -461,11 +461,11 @@ exit: return res; } -int polyFindVertex(const unsigned short* p, const int vertsPerPoly, unsigned short vertexIdx) +int polyFindVertex(const unsigned short *p, const int vertsPerPoly, unsigned short vertexIdx) { int i, res = -1; - for (i=0; i<vertsPerPoly; i++) { - if (p[i]==0xffff) + for (i = 0; i < vertsPerPoly; i++) { + if (p[i] == 0xffff) break; if (p[i] == vertexIdx) { res = i; diff --git a/source/blender/blenkernel/intern/nla.c b/source/blender/blenkernel/intern/nla.c index 9590160c8f3..6f585198524 100644 --- a/source/blender/blenkernel/intern/nla.c +++ b/source/blender/blenkernel/intern/nla.c @@ -423,7 +423,7 @@ static float nlastrip_get_frame_actionclip(NlaStrip *strip, float cframe, short return strip->actstart; } else { - /* - the 'fmod(..., actlength*scale)' is needed to get the repeats working + /* - the 'fmod(..., actlength * scale)' is needed to get the repeats working * - the '/ scale' is needed to ensure that scaling influences the timing within the repeat */ return strip->actend - fmodf(cframe - strip->start, actlength * scale) / scale; @@ -446,7 +446,7 @@ static float nlastrip_get_frame_actionclip(NlaStrip *strip, float cframe, short return strip->actend; } else { - /* - the 'fmod(..., actlength*scale)' is needed to get the repeats working + /* - the 'fmod(..., actlength * scale)' is needed to get the repeats working * - the '/ scale' is needed to ensure that scaling influences the timing within the repeat */ return strip->actstart + fmodf(cframe - strip->start, actlength * scale) / scale; @@ -496,7 +496,7 @@ float nlastrip_get_frame(NlaStrip *strip, float cframe, short mode) case NLASTRIP_TYPE_CLIP: /* action-clip (default) */ default: return nlastrip_get_frame_actionclip(strip, cframe, mode); - } + } } @@ -1162,7 +1162,7 @@ static short nlastrip_is_first(AnimData *adt, NlaStrip *strip) if (ns->start < strip->start) return 0; } - } + } /* should be first now */ return 1; @@ -1491,7 +1491,7 @@ void BKE_nla_action_pushdown(AnimData *adt) /* add a new NLA strip to the track, which references the active action */ strip = add_nlastrip_to_stack(adt, adt->action); - /* do other necessary work on strip */ + /* do other necessary work on strip */ if (strip) { /* clear reference to action now that we've pushed it onto the stack */ id_us_min(&adt->action->id); @@ -1545,7 +1545,7 @@ short BKE_nla_tweakmode_enter(AnimData *adt) /* now try to find active strip */ activeStrip = BKE_nlastrip_find_active(nlt); break; - } + } } /* There are situations where we may have multiple strips selected and we want to enter tweakmode on all @@ -1563,7 +1563,7 @@ short BKE_nla_tweakmode_enter(AnimData *adt) activeStrip = BKE_nlastrip_find_active(nlt); break; } - } + } } if ((activeTrack) && (activeStrip == NULL)) { /* no active strip in active or last selected track; compromise for first selected (assuming only single)... */ diff --git a/source/blender/blenkernel/intern/node.c b/source/blender/blenkernel/intern/node.c index 8cede4f51a5..2d76484b60a 100644 --- a/source/blender/blenkernel/intern/node.c +++ b/source/blender/blenkernel/intern/node.c @@ -147,6 +147,7 @@ static bNodeSocket *make_socket(bNodeTree *UNUSED(ntree), int in_out, const char sock->limit = (in_out == SOCK_IN ? 1 : 0xFFF); sock->type = type; sock->storage = NULL; + sock->flag |= SOCK_COLLAPSED; sock->default_value = node_socket_make_default_value(type); node_socket_init_default_value(type, sock->default_value); @@ -326,10 +327,13 @@ bNode *nodeAddNode(bNodeTree *ntree, struct bNodeTemplate *ntemp) ntype->initfunc(ntree, node, ntemp); /* 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 + * note: do this after the initfunc so nodes get their data set which may be used in naming * (node groups for example) */ - BLI_strncpy(node->name, nodeLabel(node), NODE_MAXSTR); + /* XXX Do not use nodeLabel() here, it returns translated content, which should *only* be used + * in UI, *never* in data... + * This solution may be a bit rougher than nodeLabel()'s returned string, but it's simpler + * than adding a "no translate" flag to this func (and labelfunc() as well). */ + BLI_strncpy(node->name, node->typeinfo->name, NODE_MAXSTR); nodeUniqueName(ntree, node); ntree->update |= NTREE_UPDATE_NODES; @@ -343,6 +347,7 @@ bNode *nodeCopyNode(struct bNodeTree *ntree, struct bNode *node) { bNode *nnode = MEM_callocN(sizeof(bNode), "dupli node"); bNodeSocket *sock, *oldsock; + bNodeLink *link, *oldlink; *nnode = *node; /* can be called for nodes outside a node tree (e.g. clipboard) */ @@ -382,6 +387,15 @@ bNode *nodeCopyNode(struct bNodeTree *ntree, struct bNode *node) sock->cache = NULL; } + BLI_duplicatelist(&nnode->internal_links, &node->internal_links); + oldlink = node->internal_links.first; + for (link = nnode->internal_links.first; link; link = link->next, oldlink = oldlink->next) { + link->fromnode = nnode; + link->tonode = nnode; + link->fromsock = link->fromsock->new_sock; + link->tosock = link->tosock->new_sock; + } + /* don't increase node->id users, freenode doesn't decrement either */ if (node->typeinfo->copystoragefunc) @@ -389,7 +403,17 @@ bNode *nodeCopyNode(struct bNodeTree *ntree, struct bNode *node) node->new_node = nnode; nnode->new_node = NULL; - nnode->preview = NULL; + + /* only shader nodes get pleasant preview updating this way, compo uses own system */ + if (node->preview) { + if (ntree->type == NTREE_SHADER) { + nnode->preview = MEM_dupallocN(node->preview); + if (node->preview->rect) + nnode->preview->rect = MEM_dupallocN(node->preview->rect); + } + else + nnode->preview = NULL; + } if (ntree) ntree->update |= NTREE_UPDATE_NODES; @@ -520,15 +544,12 @@ void nodeRemSocketLinks(bNodeTree *ntree, bNodeSocket *sock) void nodeInternalRelink(bNodeTree *ntree, bNode *node) { bNodeLink *link, *link_next; - ListBase intlinks; - if (!node->typeinfo->internal_connect) + if (node->internal_links.first == NULL) return; - intlinks = node->typeinfo->internal_connect(ntree, node); - /* store link pointers in output sockets, for efficient lookup */ - for (link = intlinks.first; link; link = link->next) + for (link = node->internal_links.first; link; link = link->next) link->tosock->link = link; /* redirect downstream links */ @@ -562,8 +583,6 @@ void nodeInternalRelink(bNodeTree *ntree, bNode *node) if (link->tonode == node) nodeRemLink(ntree, link); } - - BLI_freelistN(&intlinks); } void nodeToView(bNode *node, float x, float y, float *rx, float *ry) @@ -710,7 +729,7 @@ static bNodeTree *ntreeCopyTree_internal(bNodeTree *ntree, const short do_id_use } node->new_node = NULL; - /* nnode= */ nodeCopyNode(newtree, node); /* sets node->new */ + /* nnode = */ nodeCopyNode(newtree, node); /* sets node->new */ /* make sure we don't copy new nodes again! */ if (node == last) @@ -815,7 +834,7 @@ void nodeFreePreview(bNode *node) MEM_freeN(node->preview->rect); MEM_freeN(node->preview); node->preview = NULL; - } + } } static void node_init_preview(bNode *node, int xsize, int ysize) @@ -858,7 +877,7 @@ void ntreeInitPreview(bNodeTree *ntree, int xsize, int ysize) node_init_preview(node, xsize, ysize); if (node->type == NODE_GROUP && (node->flag & NODE_GROUP_EDIT)) ntreeInitPreview((bNodeTree *)node->id, xsize, ysize); - } + } } static void nodeClearPreview(bNode *node) @@ -880,13 +899,13 @@ void ntreeClearPreview(bNodeTree *ntree) nodeClearPreview(node); if (node->type == NODE_GROUP && (node->flag & NODE_GROUP_EDIT)) ntreeClearPreview((bNodeTree *)node->id); - } + } } /* hack warning! this function is only used for shader previews, and * since it gets called multiple times per pixel for Ztransp we only * add the color once. Preview gets cleared before it starts render though */ -void nodeAddToPreview(bNode *node, float col[4], int x, int y, int do_manage) +void nodeAddToPreview(bNode *node, const float col[4], int x, int y, int do_manage) { bNodePreview *preview = node->preview; if (preview) { @@ -985,6 +1004,8 @@ void nodeFreeNode(bNodeTree *ntree, bNode *node) MEM_freeN(sock); } + BLI_freelistN(&node->internal_links); + nodeFreePreview(node); MEM_freeN(node); @@ -996,6 +1017,7 @@ void nodeFreeNode(bNodeTree *ntree, bNode *node) /* do not free ntree itself here, BKE_libblock_free calls this function too */ void ntreeFreeTree_ex(bNodeTree *ntree, const short do_id_user) { + bNodeTree *tntree; bNode *node, *next; bNodeSocket *sock; @@ -1052,6 +1074,14 @@ void ntreeFreeTree_ex(bNodeTree *ntree, const short do_id_user) for (sock = ntree->outputs.first; sock; sock = sock->next) node_socket_free_default_value(sock->type, sock->default_value); BLI_freelistN(&ntree->outputs); + + /* if ntree is not part of library, free the libblock data explicitly */ + for (tntree = G.main->nodetree.first; tntree; tntree = tntree->id.next) + if (tntree == ntree) + break; + if (tntree == NULL) { + BKE_libblock_free_data(&ntree->id); + } } /* same as ntreeFreeTree_ex but always manage users */ void ntreeFreeTree(bNodeTree *ntree) @@ -1554,11 +1584,11 @@ int BKE_node_clipboard_validate(void) /* lists must be aligned */ BLI_assert(BLI_countlist(&node_clipboard.nodes) == - BLI_countlist(&node_clipboard.nodes_extra_info)); + BLI_countlist(&node_clipboard.nodes_extra_info)); for (node = node_clipboard.nodes.first, node_info = node_clipboard.nodes_extra_info.first; - node; - node = node->next, node_info = node_info->next) + node; + node = node->next, node_info = node_info->next) { /* validate the node against the stored node info */ @@ -1638,21 +1668,21 @@ int BKE_node_clipboard_get_type(void) /* ************** dependency stuff *********** */ /* node is guaranteed to be not checked before */ -static int node_get_deplist_recurs(bNode *node, bNode ***nsort) +static int node_get_deplist_recurs(bNodeTree *ntree, bNode *node, bNode ***nsort) { bNode *fromnode; - bNodeSocket *sock; + bNodeLink *link; int level = 0xFFF; node->done = TRUE; /* check linked nodes */ - for (sock = node->inputs.first; sock; sock = sock->next) { - if (sock->link) { - fromnode = sock->link->fromnode; + for (link = ntree->links.first; link; link = link->next) { + if (link->tonode == node) { + fromnode = link->fromnode; if (fromnode) { if (fromnode->done == 0) - fromnode->level = node_get_deplist_recurs(fromnode, nsort); + fromnode->level = node_get_deplist_recurs(ntree, fromnode, nsort); if (fromnode->level <= level) level = fromnode->level - 1; } @@ -1662,7 +1692,7 @@ static int node_get_deplist_recurs(bNode *node, bNode ***nsort) /* check parent node */ if (node->parent) { if (node->parent->done == 0) - node->parent->level = node_get_deplist_recurs(node->parent, nsort); + node->parent->level = node_get_deplist_recurs(ntree, node->parent, nsort); if (node->parent->level <= level) level = node->parent->level - 1; } @@ -1696,7 +1726,7 @@ void ntreeGetDependencyList(struct bNodeTree *ntree, struct bNode ***deplist, in /* recursive check */ for (node = ntree->nodes.first; node; node = node->next) { if (node->done == 0) { - node->level = node_get_deplist_recurs(node, &nsort); + node->level = node_get_deplist_recurs(ntree, node, &nsort); } } } @@ -1714,7 +1744,7 @@ static void ntree_update_node_level(bNodeTree *ntree) /* recursive check */ for (node = ntree->nodes.first; node; node = node->next) { if (node->done == 0) { - node->level = node_get_deplist_recurs(node, NULL); + node->level = node_get_deplist_recurs(ntree, node, NULL); } } } @@ -1813,6 +1843,8 @@ void ntreeUpdateTree(bNodeTree *ntree) ntreetype->update_node(ntree, node); else if (node->typeinfo->updatefunc) node->typeinfo->updatefunc(ntree, node); + + nodeUpdateInternalLinks(ntree, node); } } @@ -1850,6 +1882,9 @@ void nodeUpdate(bNodeTree *ntree, bNode *node) ntreetype->update_node(ntree, node); else if (node->typeinfo->updatefunc) node->typeinfo->updatefunc(ntree, node); + + nodeUpdateInternalLinks(ntree, node); + /* clear update flag */ node->update = 0; } @@ -1889,9 +1924,21 @@ int nodeUpdateID(bNodeTree *ntree, ID *id) } } + for (node = ntree->nodes.first; node; node = node->next) { + nodeUpdateInternalLinks(ntree, node); + } + return change; } +void nodeUpdateInternalLinks(bNodeTree *ntree, bNode *node) +{ + BLI_freelistN(&node->internal_links); + + if (node->typeinfo && node->typeinfo->update_internal_links) + node->typeinfo->update_internal_links(ntree, node); +} + /* ************* node type access ********** */ @@ -1964,7 +2011,7 @@ void node_type_base(bNodeTreeType *ttype, bNodeType *ntype, int type, const char /* Default muting stuff. */ if (ttype) - ntype->internal_connect = ttype->internal_connect; + ntype->update_internal_links = ttype->update_internal_links; /* default size values */ ntype->width = 140; @@ -2060,9 +2107,9 @@ void node_type_exec_new(struct bNodeType *ntype, ntype->newexecfunc = newexecfunc; } -void node_type_internal_connect(bNodeType *ntype, ListBase (*internal_connect)(bNodeTree *, bNode *)) +void node_type_internal_links(bNodeType *ntype, void (*update_internal_links)(bNodeTree *, bNode *)) { - ntype->internal_connect = internal_connect; + ntype->update_internal_links = update_internal_links; } void node_type_gpu(struct bNodeType *ntype, int (*gpufunc)(struct GPUMaterial *mat, struct bNode *node, struct GPUNodeStack *in, struct GPUNodeStack *out)) @@ -2195,6 +2242,7 @@ static void registerCompositNodes(bNodeTreeType *ttype) register_node_type_cmp_bokehimage(ttype); register_node_type_cmp_bokehblur(ttype); register_node_type_cmp_switch(ttype); + register_node_type_cmp_pixelate(ttype); register_node_type_cmp_mask(ttype); register_node_type_cmp_trackpos(ttype); @@ -2243,16 +2291,23 @@ static void registerShaderNodes(bNodeTreeType *ttype) register_node_type_sh_layer_weight(ttype); register_node_type_sh_tex_coord(ttype); register_node_type_sh_particle_info(ttype); + register_node_type_sh_bump(ttype); + register_node_type_sh_script(ttype); + register_node_type_sh_tangent(ttype); + register_node_type_sh_normal_map(ttype); register_node_type_sh_background(ttype); + register_node_type_sh_bsdf_anisotropic(ttype); register_node_type_sh_bsdf_diffuse(ttype); register_node_type_sh_bsdf_glossy(ttype); register_node_type_sh_bsdf_glass(ttype); + register_node_type_sh_bsdf_refraction(ttype); register_node_type_sh_bsdf_translucent(ttype); register_node_type_sh_bsdf_transparent(ttype); register_node_type_sh_bsdf_velvet(ttype); register_node_type_sh_emission(ttype); register_node_type_sh_holdout(ttype); + register_node_type_sh_ambient_occlusion(ttype); //register_node_type_sh_volume_transparent(ttype); //register_node_type_sh_volume_isotropic(ttype); register_node_type_sh_mix_shader(ttype); diff --git a/source/blender/blenkernel/intern/object.c b/source/blender/blenkernel/intern/object.c index f72372742d0..6ec173a5908 100644 --- a/source/blender/blenkernel/intern/object.c +++ b/source/blender/blenkernel/intern/object.c @@ -300,11 +300,11 @@ void BKE_object_free(Object *ob) BKE_object_free_display(ob); - /* disconnect specific data */ + /* disconnect specific data, but not for lib data (might be indirect data, can get relinked) */ if (ob->data) { ID *id = ob->data; id->us--; - if (id->us == 0) { + if (id->us == 0 && id->lib == NULL) { switch (ob->type) { case OB_MESH: BKE_mesh_unlink((Mesh *)id); @@ -454,7 +454,7 @@ void BKE_object_unlink(Object *ob) if (pchan->custom == ob) pchan->custom = NULL; } - } + } else if (ELEM(OB_MBALL, ob->type, obt->type)) { if (BKE_mball_is_basis_for(obt, ob)) obt->recalc |= OB_RECALC_DATA; @@ -689,8 +689,8 @@ void BKE_object_unlink(Object *ob) if (so->treestore) { TreeStoreElem *tselem = so->treestore->data; - int a; - for (a = 0; a < so->treestore->usedelem; a++, tselem++) { + int i; + for (i = 0; i < so->treestore->usedelem; i++, tselem++) { if (tselem->id == (ID *)ob) tselem->id = NULL; } } @@ -854,7 +854,9 @@ Object *BKE_object_add_only_object(int type, const char *name) ob->step_height = 0.15f; ob->jump_speed = 10.0f; ob->fall_speed = 55.0f; - + ob->col_group = 0x01; + ob->col_mask = 0xff; + /* NT fluid sim defaults */ ob->fluidsimSettings = NULL; @@ -1781,7 +1783,7 @@ static void ob_parbone(Object *ob, Object *par, float mat[][4]) /* Make sure the bone is still valid */ pchan = BKE_pose_channel_find_name(par->pose, ob->parsubstr); - if (!pchan) { + if (!pchan || !pchan->bone) { printf("Object %s with Bone parent: bone %s doesn't exist\n", ob->id.name + 2, ob->parsubstr); unit_m4(mat); return; @@ -2300,11 +2302,9 @@ void BKE_object_minmax(Object *ob, float min_r[3], float max_r[3], const short u bPoseChannel *pchan; for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) { - - if ((use_hidden == FALSE) && (PBONE_VISIBLE(arm, pchan->bone) == FALSE)) { - /* pass */ - } - else { + /* XXX pchan->bone may be NULL for duplicated bones, see duplicateEditBoneObjects() comment + * (editarmature.c:2592)... Skip in this case too! */ + if (pchan->bone && !((use_hidden == FALSE) && (PBONE_VISIBLE(arm, pchan->bone) == FALSE))) { mul_v3_m4v3(vec, ob->obmat, pchan->pose_head); minmax_v3v3_v3(min_r, max_r, vec); mul_v3_m4v3(vec, ob->obmat, pchan->pose_tail); @@ -2573,9 +2573,7 @@ void BKE_object_handle_update(Scene *scene, Object *ob) if (ob->recalc & OB_RECALC_DATA) { ID *data_id = (ID *)ob->data; AnimData *adt = BKE_animdata_from_id(data_id); - float ctime = (float)scene->r.cfra; // XXX this is bad... - ListBase pidlist; - PTCacheID *pid; + float ctime = (float)scene->r.cfra; /* XXX this is bad... */ if (G.debug & G_DEBUG) printf("recalcdata %s\n", ob->id.name + 2); @@ -2644,18 +2642,20 @@ void BKE_object_handle_update(Scene *scene, Object *ob) * However, not doing anything (or trying to hack around this lack) is not an option * anymore, especially due to Cycles [#31834] */ - //if (ob->totcol) { - // int a; - // - // for (a = 1; a <= ob->totcol; a++) { - // Material *ma = give_current_material(ob, a); - // - // if (ma) { - // /* recursively update drivers for this material */ - // material_drivers_update(scene, ma, ctime); - // } - // } - //} + if (ob->totcol) { + int a; + + for (a = 1; a <= ob->totcol; a++) { + Material *ma = give_current_material(ob, a); + + if (ma) { + /* recursively update drivers for this material */ + material_drivers_update(scene, ma, ctime); + } + } + } + else if (ob->type == OB_LAMP) + lamp_drivers_update(scene, ob->data, ctime); /* particles */ if (ob->particlesystem.first) { @@ -2698,26 +2698,8 @@ void BKE_object_handle_update(Scene *scene, Object *ob) psys_get_modifier(ob, psys)->flag &= ~eParticleSystemFlag_psys_updated; } } - - /* check if quick cache is needed */ - BKE_ptcache_ids_from_object(&pidlist, ob, scene, MAX_DUPLI_RECUR); - - for (pid = pidlist.first; pid; pid = pid->next) { - if ((pid->cache->flag & PTCACHE_BAKED) || - (pid->cache->flag & PTCACHE_QUICK_CACHE) == 0) - { - continue; - } - - if (pid->cache->flag & PTCACHE_OUTDATED || (pid->cache->flag & PTCACHE_SIMULATION_VALID) == 0) { - scene->physics_settings.quick_cache_step = - scene->physics_settings.quick_cache_step ? - mini(scene->physics_settings.quick_cache_step, pid->cache->step) : - pid->cache->step; - } - } - - BLI_freelistN(&pidlist); + + /* quick cache removed */ } /* the no-group proxy case, we call update */ diff --git a/source/blender/blenkernel/intern/ocean.c b/source/blender/blenkernel/intern/ocean.c index 4f3921936e8..e694a7e7eb3 100644 --- a/source/blender/blenkernel/intern/ocean.c +++ b/source/blender/blenkernel/intern/ocean.c @@ -183,7 +183,7 @@ MINLINE float catrom(float p0, float p1, float p2, float p3, float f) MINLINE float omega(float k, float depth) { - return sqrt(GRAVITY * k * tanh(k * depth)); + return sqrtf(GRAVITY * k * tanhf(k * depth)); } // modified Phillips spectrum @@ -256,8 +256,8 @@ static void add_comlex_c(fftw_complex res, fftw_complex cmpl1, fftw_complex cmpl static void mul_complex_f(fftw_complex res, fftw_complex cmpl, float f) { - res[0] = cmpl[0] * f; - res[1] = cmpl[1] * f; + res[0] = cmpl[0] * (double)f; + res[1] = cmpl[1] * (double)f; } static void mul_complex_c(fftw_complex res, fftw_complex cmpl1, fftw_complex cmpl2) @@ -289,8 +289,8 @@ static void exp_complex(fftw_complex res, fftw_complex cmpl) { float r = expf(cmpl[0]); - res[0] = cos(cmpl[1]) * r; - res[1] = sin(cmpl[1]) * r; + res[0] = cosf(cmpl[1]) * r; + res[1] = sinf(cmpl[1]) * r; } float BKE_ocean_jminus_to_foam(float jminus, float coverage) @@ -462,7 +462,7 @@ void BKE_ocean_eval_ij(struct Ocean *oc, struct OceanResult *ocr, int i, int j) i = abs(i) % oc->_M; j = abs(j) % oc->_N; - ocr->disp[1] = oc->_do_disp_y ? oc->_disp_y[i * oc->_N + j] : 0.0f; + ocr->disp[1] = oc->_do_disp_y ? (float)oc->_disp_y[i * oc->_N + j] : 0.0f; if (oc->_do_chop) { ocr->disp[0] = oc->_disp_x[i * oc->_N + j]; @@ -475,7 +475,7 @@ void BKE_ocean_eval_ij(struct Ocean *oc, struct OceanResult *ocr, int i, int j) if (oc->_do_normals) { ocr->normal[0] = oc->_N_x[i * oc->_N + j]; - ocr->normal[1] = oc->_N_y /*oc->_N_y[i*oc->_N+j] (MEM01)*/; + ocr->normal[1] = oc->_N_y /* oc->_N_y[i * oc->_N + j] (MEM01) */; ocr->normal[2] = oc->_N_z[i * oc->_N + j]; normalize_v3(ocr->normal); @@ -546,7 +546,7 @@ void BKE_simulate_ocean(struct Ocean *o, float t, float scale, float chop_amount mul_complex_f(mul_param, mul_param, chop_amount); mul_complex_c(mul_param, mul_param, minus_i); mul_complex_c(mul_param, mul_param, o->_htilda[i * (1 + o->_N / 2) + j]); - mul_complex_f(mul_param, mul_param, (o->_k[i * (1 + o->_N / 2) + j] == 0.0 ? 0.0 : o->_kx[i] / o->_k[i * (1 + o->_N / 2) + j])); + mul_complex_f(mul_param, mul_param, (o->_k[i * (1 + o->_N / 2) + j] == 0.0f ? 0.0f : o->_kx[i] / o->_k[i * (1 + o->_N / 2) + j])); init_complex(o->_fft_in_x[i * (1 + o->_N / 2) + j], real_c(mul_param), image_c(mul_param)); } } @@ -568,7 +568,7 @@ void BKE_simulate_ocean(struct Ocean *o, float t, float scale, float chop_amount mul_complex_f(mul_param, mul_param, chop_amount); mul_complex_c(mul_param, mul_param, minus_i); mul_complex_c(mul_param, mul_param, o->_htilda[i * (1 + o->_N / 2) + j]); - mul_complex_f(mul_param, mul_param, (o->_k[i * (1 + o->_N / 2) + j] == 0.0 ? 0.0 : o->_kz[j] / o->_k[i * (1 + o->_N / 2) + j])); + mul_complex_f(mul_param, mul_param, (o->_k[i * (1 + o->_N / 2) + j] == 0.0f ? 0.0f : o->_kz[j] / o->_k[i * (1 + o->_N / 2) + j])); init_complex(o->_fft_in_z[i * (1 + o->_N / 2) + j], real_c(mul_param), image_c(mul_param)); } } @@ -589,7 +589,7 @@ void BKE_simulate_ocean(struct Ocean *o, float t, float scale, float chop_amount mul_complex_f(mul_param, mul_param, chop_amount); mul_complex_c(mul_param, mul_param, o->_htilda[i * (1 + o->_N / 2) + j]); - mul_complex_f(mul_param, mul_param, (o->_k[i * (1 + o->_N / 2) + j] == 0.0 ? 0.0 : o->_kx[i] * o->_kx[i] / o->_k[i * (1 + o->_N / 2) + j])); + mul_complex_f(mul_param, mul_param, (o->_k[i * (1 + o->_N / 2) + j] == 0.0f ? 0.0f : o->_kx[i] * o->_kx[i] / o->_k[i * (1 + o->_N / 2) + j])); init_complex(o->_fft_in_jxx[i * (1 + o->_N / 2) + j], real_c(mul_param), image_c(mul_param)); } } @@ -616,7 +616,7 @@ void BKE_simulate_ocean(struct Ocean *o, float t, float scale, float chop_amount mul_complex_f(mul_param, mul_param, chop_amount); mul_complex_c(mul_param, mul_param, o->_htilda[i * (1 + o->_N / 2) + j]); - mul_complex_f(mul_param, mul_param, (o->_k[i * (1 + o->_N / 2) + j] == 0.0 ? 0.0 : o->_kz[j] * o->_kz[j] / o->_k[i * (1 + o->_N / 2) + j])); + mul_complex_f(mul_param, mul_param, (o->_k[i * (1 + o->_N / 2) + j] == 0.0f ? 0.0f : o->_kz[j] * o->_kz[j] / o->_k[i * (1 + o->_N / 2) + j])); init_complex(o->_fft_in_jzz[i * (1 + o->_N / 2) + j], real_c(mul_param), image_c(mul_param)); } } diff --git a/source/blender/blenkernel/intern/packedFile.c b/source/blender/blenkernel/intern/packedFile.c index 03342d0f6d1..dec49f417ae 100644 --- a/source/blender/blenkernel/intern/packedFile.c +++ b/source/blender/blenkernel/intern/packedFile.c @@ -201,7 +201,7 @@ PackedFile *newPackedFile(ReportList *reports, const char *filename, const char file = BLI_open(name, O_BINARY | O_RDONLY, 0); if (file <= 0) { - BKE_reportf(reports, RPT_ERROR, "Unable to pack file, source path not found: \"%s\"", name); + BKE_reportf(reports, RPT_ERROR, "Unable to pack file, source path '%s' not found", name); } else { filelen = BLI_file_descriptor_size(file); @@ -238,7 +238,8 @@ void packAll(Main *bmain, ReportList *reports) ima->packedfile = newPackedFile(reports, ima->name, ID_BLEND_PATH(bmain, &ima->id)); } else if (ELEM(ima->source, IMA_SRC_SEQUENCE, IMA_SRC_MOVIE)) { - BKE_reportf(reports, RPT_WARNING, "Image '%s' skipped, movies and image sequences not supported.", ima->id.name + 2); + BKE_reportf(reports, RPT_WARNING, "Image '%s' skipped, movies and image sequences not supported", + ima->id.name + 2); } } } @@ -310,20 +311,20 @@ int writePackedFile(ReportList *reports, const char *filename, PackedFile *pf, i file = BLI_open(name, O_BINARY + O_WRONLY + O_CREAT + O_TRUNC, 0666); if (file >= 0) { if (write(file, pf->data, pf->size) != pf->size) { - BKE_reportf(reports, RPT_ERROR, "Error writing file: %s", name); + BKE_reportf(reports, RPT_ERROR, "Error writing file '%s'", name); ret_value = RET_ERROR; } close(file); } else { - BKE_reportf(reports, RPT_ERROR, "Error creating file: %s", name); + BKE_reportf(reports, RPT_ERROR, "Error creating file '%s'", name); ret_value = RET_ERROR; } if (remove_tmp) { if (ret_value == RET_ERROR) { if (BLI_rename(tempname, name) != 0) { - BKE_reportf(reports, RPT_ERROR, "Error restoring tempfile. Check files: '%s' '%s'", tempname, name); + BKE_reportf(reports, RPT_ERROR, "Error restoring temp file (check files '%s' '%s')", tempname, name); } } else { diff --git a/source/blender/blenkernel/intern/paint.c b/source/blender/blenkernel/intern/paint.c index 5a302cba2ab..36f96045ced 100644 --- a/source/blender/blenkernel/intern/paint.c +++ b/source/blender/blenkernel/intern/paint.c @@ -36,6 +36,7 @@ #include "DNA_meshdata_types.h" #include "DNA_scene_types.h" #include "DNA_brush_types.h" +#include "DNA_space_types.h" #include "BLI_bitmap.h" #include "BLI_utildefines.h" @@ -87,6 +88,7 @@ Paint *paint_get_active(Scene *sce) Paint *paint_get_active_from_context(const bContext *C) { Scene *sce = CTX_data_scene(C); + SpaceImage *sima; if (sce) { ToolSettings *ts = sce->toolsettings; @@ -95,12 +97,12 @@ Paint *paint_get_active_from_context(const bContext *C) if (sce->basact && sce->basact->object) obact = sce->basact->object; - if (CTX_wm_space_image(C) != NULL) { + if ((sima = CTX_wm_space_image(C)) != NULL) { if (obact && obact->mode == OB_MODE_EDIT) { - if (ts->use_uv_sculpt) - return &ts->uvsculpt->paint; - else + if (sima->mode == SI_MODE_PAINT) return &ts->imapaint.paint; + else if (ts->use_uv_sculpt) + return &ts->uvsculpt->paint; } else { return &ts->imapaint.paint; diff --git a/source/blender/blenkernel/intern/particle.c b/source/blender/blenkernel/intern/particle.c index e8af794eaea..d645204d29c 100644 --- a/source/blender/blenkernel/intern/particle.c +++ b/source/blender/blenkernel/intern/particle.c @@ -48,6 +48,7 @@ #include "DNA_dynamicpaint_types.h" #include "BLI_blenlib.h" +#include "BLI_noise.h" #include "BLI_math.h" #include "BLI_utildefines.h" #include "BLI_kdtree.h" @@ -97,8 +98,8 @@ int count_particles(ParticleSystem *psys) int tot = 0; LOOP_SHOWN_PARTICLES { - if (pa->alive == PARS_UNBORN && (part->flag & PART_UNBORN) == 0) ; - else if (pa->alive == PARS_DEAD && (part->flag & PART_DIED) == 0) ; + if (pa->alive == PARS_UNBORN && (part->flag & PART_UNBORN) == 0) {} + else if (pa->alive == PARS_DEAD && (part->flag & PART_DIED) == 0) {} else tot++; } return tot; @@ -110,8 +111,8 @@ int count_particles_mod(ParticleSystem *psys, int totgr, int cur) int tot = 0; LOOP_SHOWN_PARTICLES { - if (pa->alive == PARS_UNBORN && (part->flag & PART_UNBORN) == 0) ; - else if (pa->alive == PARS_DEAD && (part->flag & PART_DIED) == 0) ; + if (pa->alive == PARS_UNBORN && (part->flag & PART_UNBORN) == 0) {} + else if (pa->alive == PARS_DEAD && (part->flag & PART_DIED) == 0) {} else if (p % totgr == cur) tot++; } return tot; @@ -335,7 +336,7 @@ void psys_check_group_weights(ParticleSettings *part) BLI_addtail(&part->dupliweights, dw); } - go = go->next; + go = go->next; } dw = part->dupliweights.first; @@ -560,7 +561,7 @@ void psys_free(Object *ob, ParticleSystem *psys) ob->transflag &= ~OB_DUPLIPARTS; if (psys->part) { - psys->part->id.us--; + psys->part->id.us--; psys->part = NULL; } @@ -617,7 +618,10 @@ typedef struct ParticleRenderData { int do_simplify; int timeoffset; ParticleRenderElem *elems; - int *origindex; + + /* ORIGINDEX */ + const int *index_mf_to_mpoly; + const int *index_mp_to_orig; } ParticleRenderData; static float psys_render_viewport_falloff(double rate, float dist, float width) @@ -790,9 +794,13 @@ int psys_render_simplify_distribution(ParticleThreadContext *ctx, int tot) float *facearea, (*facecenter)[3], size[3], fac, powrate, scaleclamp; float co1[3], co2[3], co3[3], co4[3], lambda, arearatio, t, area, viewport; double vprate; - int *origindex, *facetotvert; + int *facetotvert; int a, b, totorigface, totface, newtot, skipped; + /* double lookup */ + const int *index_mf_to_mpoly; + const int *index_mp_to_orig; + if (part->ren_as != PART_DRAW_PATH || !(part->draw & PART_DRAW_REN_STRAND)) return tot; if (!ctx->sim.psys->renderdata) @@ -806,13 +814,18 @@ int psys_render_simplify_distribution(ParticleThreadContext *ctx, int tot) mvert = dm->getVertArray(dm); mface = dm->getTessFaceArray(dm); - origindex = dm->getTessFaceDataArray(dm, CD_ORIGINDEX); totface = dm->getNumTessFaces(dm); totorigface = me->totpoly; if (totface == 0 || totorigface == 0) return tot; + index_mf_to_mpoly = dm->getTessFaceDataArray(dm, CD_ORIGINDEX); + index_mp_to_orig = dm->getPolyDataArray(dm, CD_ORIGINDEX); + if ((index_mf_to_mpoly && index_mp_to_orig) == FALSE) { + index_mf_to_mpoly = index_mp_to_orig = NULL; + } + facearea = MEM_callocN(sizeof(float) * totorigface, "SimplifyFaceArea"); facecenter = MEM_callocN(sizeof(float[3]) * totorigface, "SimplifyFaceCenter"); facetotvert = MEM_callocN(sizeof(int) * totorigface, "SimplifyFaceArea"); @@ -823,20 +836,22 @@ int psys_render_simplify_distribution(ParticleThreadContext *ctx, int tot) data->do_simplify = TRUE; data->elems = elems; - data->origindex = origindex; + data->index_mf_to_mpoly = index_mf_to_mpoly; + data->index_mp_to_orig = index_mp_to_orig; /* compute number of children per original face */ for (a = 0; a < tot; a++) { - b = (origindex) ? origindex[ctx->index[a]] : ctx->index[a]; - if (b != -1) + b = (index_mf_to_mpoly) ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, ctx->index[a]) : ctx->index[a]; + if (b != ORIGINDEX_NONE) { elems[b].totchild++; + } } /* compute areas and centers of original faces */ for (mf = mface, a = 0; a < totface; a++, mf++) { - b = (origindex) ? origindex[a] : a; + b = (index_mf_to_mpoly) ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, a) : a; - if (b != -1) { + if (b != ORIGINDEX_NONE) { copy_v3_v3(co1, mvert[mf->v1].co); copy_v3_v3(co2, mvert[mf->v2].co); copy_v3_v3(co3, mvert[mf->v3].co); @@ -898,7 +913,7 @@ int psys_render_simplify_distribution(ParticleThreadContext *ctx, int tot) elem->scalemax = sqrt(elem->scalemax); /* clamp scaling */ - scaleclamp = MIN2(elem->totchild, 10.0f); + scaleclamp = (float)min_ii(elem->totchild, 10); elem->scalemin = MIN2(scaleclamp, elem->scalemin); elem->scalemax = MIN2(scaleclamp, elem->scalemax); @@ -930,8 +945,9 @@ int psys_render_simplify_distribution(ParticleThreadContext *ctx, int tot) skipped = 0; for (a = 0, newtot = 0; a < tot; a++) { - b = (origindex) ? origindex[ctx->index[a]] : ctx->index[a]; - if (b != -1) { + b = (index_mf_to_mpoly) ? DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, ctx->index[a]) : ctx->index[a]; + + if (b != ORIGINDEX_NONE) { if (elems[b].curchild++ < ceil(elems[b].lambda * elems[b].totchild)) { ctx->index[newtot] = ctx->index[a]; ctx->skip[newtot] = skipped; @@ -962,10 +978,10 @@ int psys_render_simplify_params(ParticleSystem *psys, ChildParticle *cpa, float data = psys->renderdata; if (!data->do_simplify) return 0; - - b = (data->origindex) ? data->origindex[cpa->num] : cpa->num; - if (b == -1) + b = (data->index_mf_to_mpoly) ? DM_origindex_mface_mpoly(data->index_mf_to_mpoly, data->index_mp_to_orig, cpa->num) : cpa->num; + if (b == ORIGINDEX_NONE) { return 0; + } elem = &data->elems[b]; @@ -1403,7 +1419,8 @@ static void interpolate_pathcache(ParticleCacheKey *first, float t, ParticleCach /************************************************/ /* interpolate a location on a face based on face coordinates */ void psys_interpolate_face(MVert *mvert, MFace *mface, MTFace *tface, float (*orcodata)[3], - float *w, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor) + float w[4], float vec[3], float nor[3], float utan[3], float vtan[3], + float orco[3], float ornor[3]) { float *v1 = 0, *v2 = 0, *v3 = 0, *v4 = 0; float e1[3], e2[3], s1, s2, t1, t2; @@ -1622,17 +1639,22 @@ int psys_particle_dm_face_lookup(Object *ob, DerivedMesh *dm, int index, const f Mesh *me = (Mesh *)ob->data; MPoly *mpoly; OrigSpaceFace *osface; - int *origindex; int quad, findex, totface; float uv[2], (*faceuv)[2]; + /* double lookup */ + const int *index_mf_to_mpoly = dm->getTessFaceDataArray(dm, CD_ORIGINDEX); + const int *index_mp_to_orig = dm->getPolyDataArray(dm, CD_ORIGINDEX); + if ((index_mf_to_mpoly && index_mp_to_orig) == FALSE) { + index_mf_to_mpoly = index_mp_to_orig = NULL; + } + mpoly = dm->getPolyArray(dm); - origindex = dm->getTessFaceDataArray(dm, CD_ORIGINDEX); osface = dm->getTessFaceDataArray(dm, CD_ORIGSPACE); totface = dm->getNumTessFaces(dm); - if (osface == NULL || origindex == NULL) { + if (osface == NULL || index_mf_to_mpoly == NULL) { /* Assume we don't need osface data */ if (index < totface) { //printf("\tNO CD_ORIGSPACE, assuming not needed\n"); @@ -1666,7 +1688,8 @@ int psys_particle_dm_face_lookup(Object *ob, DerivedMesh *dm, int index, const f } else { /* if we have no node, try every face */ for (findex = 0; findex < totface; findex++) { - if (origindex[findex] == index) { + const int findex_orig = DM_origindex_mface_mpoly(index_mf_to_mpoly, index_mp_to_orig, findex); + if (findex_orig == index) { faceuv = osface[findex].uv; quad = (mpoly[findex].totloop == 4); @@ -1746,7 +1769,9 @@ static int psys_map_index_on_dm(DerivedMesh *dm, int from, int index, int index_ } /* interprets particle data to get a point on a mesh in object space */ -void psys_particle_on_dm(DerivedMesh *dm, int from, int index, int index_dmcache, const float fw[4], float foffset, float vec[3], float nor[3], float utan[3], float vtan[3], float orco[3], float ornor[3]) +void psys_particle_on_dm(DerivedMesh *dm, int from, int index, int index_dmcache, + const float fw[4], float foffset, float vec[3], float nor[3], float utan[3], float vtan[3], + float orco[3], float ornor[3]) { float tmpnor[3], mapfw[4]; float (*orcodata)[3]; @@ -1842,7 +1867,9 @@ ParticleSystemModifierData *psys_get_modifier(Object *ob, ParticleSystem *psys) /* Particles on a shape */ /************************************************/ /* ready for future use */ -static void psys_particle_on_shape(int UNUSED(distr), int UNUSED(index), float *UNUSED(fuv), float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor) +static void psys_particle_on_shape(int UNUSED(distr), int UNUSED(index), + float *UNUSED(fuv), float vec[3], float nor[3], float utan[3], float vtan[3], + float orco[3], float ornor[3]) { /* TODO */ float zerovec[3] = {0.0f, 0.0f, 0.0f}; @@ -1868,7 +1895,9 @@ static void psys_particle_on_shape(int UNUSED(distr), int UNUSED(index), float * /************************************************/ /* Particles on emitter */ /************************************************/ -void psys_particle_on_emitter(ParticleSystemModifierData *psmd, int from, int index, int index_dmcache, float *fuv, float foffset, float *vec, float *nor, float *utan, float *vtan, float *orco, float *ornor) +void psys_particle_on_emitter(ParticleSystemModifierData *psmd, int from, int index, int index_dmcache, + float fuv[4], float foffset, float vec[3], float nor[3], float utan[3], float vtan[3], + float orco[3], float ornor[3]) { if (psmd) { if (psmd->psys->part->distr == PART_DISTR_GRID && psmd->psys->part->from != PART_FROM_VERT) { @@ -2456,7 +2485,7 @@ static int psys_threads_init_path(ParticleThread *threads, Scene *scene, float c totthread = 1; for (i = 0; i < totthread; i++) { - threads[i].rng_path = rng_new(seed); + threads[i].rng_path = BLI_rng_new(seed); threads[i].tot = totthread; } @@ -3298,7 +3327,7 @@ void copy_particle_key(ParticleKey *to, ParticleKey *from, int time) to->time = to_time; } } -void psys_get_from_key(ParticleKey *key, float *loc, float *vel, float *rot, float *time) +void psys_get_from_key(ParticleKey *key, float loc[3], float vel[3], float rot[4], float *time) { if (loc) copy_v3_v3(loc, key->co); if (vel) copy_v3_v3(vel, key->vel); @@ -4319,7 +4348,7 @@ int psys_get_particle_state(ParticleSimulationData *sim, int p, ParticleKey *sta if (pa) { if (!always) { if ((cfra < pa->time && (part->flag & PART_UNBORN) == 0) || - (cfra > pa->dietime && (part->flag & PART_DIED) == 0)) + (cfra >= pa->dietime && (part->flag & PART_DIED) == 0)) { return 0; } @@ -4414,7 +4443,9 @@ int psys_get_particle_state(ParticleSimulationData *sim, int p, ParticleKey *sta } } -void psys_get_dupli_texture(ParticleSystem *psys, ParticleSettings *part, ParticleSystemModifierData *psmd, ParticleData *pa, ChildParticle *cpa, float *uv, float *orco) +void psys_get_dupli_texture(ParticleSystem *psys, ParticleSettings *part, + ParticleSystemModifierData *psmd, ParticleData *pa, ChildParticle *cpa, + float uv[2], float orco[3]) { MFace *mface; MTFace *mtface; diff --git a/source/blender/blenkernel/intern/particle_system.c b/source/blender/blenkernel/intern/particle_system.c index 154c8cca75d..a780a9e8684 100644 --- a/source/blender/blenkernel/intern/particle_system.c +++ b/source/blender/blenkernel/intern/particle_system.c @@ -346,7 +346,7 @@ void psys_calc_dmcache(Object *ob, DerivedMesh *dm, ParticleSystem *psys) if (!dm->deformedOnly) { /* Will use later to speed up subsurf/derivedmesh */ LinkNode *node, *nodedmelem, **nodearray; - int totdmelem, totelem, i, *origindex; + int totdmelem, totelem, i, *origindex, *origindex_poly = NULL; if (psys->part->from == PART_FROM_VERT) { totdmelem= dm->getNumVerts(dm); @@ -356,23 +356,38 @@ void psys_calc_dmcache(Object *ob, DerivedMesh *dm, ParticleSystem *psys) else { /* FROM_FACE/FROM_VOLUME */ totdmelem= dm->getNumTessFaces(dm); totelem= me->totpoly; - origindex= dm->getTessFaceDataArray(dm, CD_ORIGINDEX); + origindex = dm->getTessFaceDataArray(dm, CD_ORIGINDEX); + /* for face lookups we need the poly origindex too */ + origindex_poly = dm->getPolyDataArray(dm, CD_ORIGINDEX); + if (origindex_poly == NULL) { + origindex = NULL; + } } nodedmelem= MEM_callocN(sizeof(LinkNode)*totdmelem, "psys node elems"); nodearray= MEM_callocN(sizeof(LinkNode *)*totelem, "psys node array"); - for (i=0, node=nodedmelem; i<totdmelem; i++, origindex++, node++) { - node->link= SET_INT_IN_POINTER(i); + for (i=0, node=nodedmelem; i<totdmelem; i++, node++) { + int origindex_final; + node->link = SET_INT_IN_POINTER(i); + + /* may be vertex or face origindex */ + origindex_final = origindex ? origindex[i] : ORIGINDEX_NONE; - if (*origindex != -1) { - if (nodearray[*origindex]) { + /* if we have a poly source, do an index lookup */ + if (origindex_poly && origindex_final != ORIGINDEX_NONE) { + origindex_final = origindex_poly[origindex_final]; + } + + if (origindex_final != ORIGINDEX_NONE) { + if (nodearray[origindex_final]) { /* prepend */ - node->next = nodearray[*origindex]; - nodearray[*origindex]= node; + node->next = nodearray[origindex_final]; + nodearray[origindex_final] = node; + } + else { + nodearray[origindex_final] = node; } - else - nodearray[*origindex]= node; } } @@ -452,13 +467,7 @@ static void distribute_grid(DerivedMesh *dm, ParticleSystem *psys) mv++; for (i=1; i<totvert; i++, mv++) { - min[0]=MIN2(min[0],mv->co[0]); - min[1]=MIN2(min[1],mv->co[1]); - min[2]=MIN2(min[2],mv->co[2]); - - max[0]=MAX2(max[0],mv->co[0]); - max[1]=MAX2(max[1],mv->co[1]); - max[2]=MAX2(max[2],mv->co[2]); + minmax_v3v3_v3(min, max, mv->co); } sub_v3_v3v3(delta, max, min); @@ -556,8 +565,7 @@ static void distribute_grid(DerivedMesh *dm, ParticleSystem *psys) else /* store number of intersections */ (pa+(int)(lambda*size[a])*a0mul)->hair_index++; } - - if (mface->v4) { + else if (mface->v4) { copy_v3_v3(v4, mvert[mface->v4].co); if (isect_axial_line_tri_v3(a, co1, co2, v4, v1, v3, &lambda)) { @@ -632,10 +640,10 @@ static void hammersley_create(float *out, int n, int seed, float amount) double p, t, offs[2]; int k, kk; - rng = rng_new(31415926 + n + seed); - offs[0]= rng_getDouble(rng) + (double)amount; - offs[1]= rng_getDouble(rng) + (double)amount; - rng_free(rng); + rng = BLI_rng_new(31415926 + n + seed); + offs[0] = BLI_rng_get_double(rng) + (double)amount; + offs[1] = BLI_rng_get_double(rng) + (double)amount; + BLI_rng_free(rng); for (k = 0; k < n; k++) { t = 0; @@ -643,8 +651,8 @@ static void hammersley_create(float *out, int n, int seed, float amount) if (kk & 1) /* kk mod 2 = 1 */ t += p; - out[2*k + 0]= fmod((double)k/(double)n + offs[0], 1.0); - out[2*k + 1]= fmod(t + offs[1], 1.0); + out[2*k + 0] = fmod((double)k/(double)n + offs[0], 1.0); + out[2*k + 1] = fmod(t + offs[1], 1.0); } } @@ -661,13 +669,13 @@ static void init_mv_jit(float *jit, int num, int seed2, float amount) rad2= (float)(1.0f/((float)num)); rad3= (float)sqrt((float)num)/((float)num); - rng = rng_new(31415926 + num + seed2); + rng = BLI_rng_new(31415926 + num + seed2); x= 0; num2 = 2 * num; for (i=0; i<num2; i+=2) { - jit[i]= x + amount*rad1*(0.5f - rng_getFloat(rng)); - jit[i+1]= i/(2.0f*num) + amount*rad1*(0.5f - rng_getFloat(rng)); + jit[i] = x + amount*rad1*(0.5f - BLI_rng_get_float(rng)); + jit[i+1] = i/(2.0f*num) + amount*rad1*(0.5f - BLI_rng_get_float(rng)); jit[i]-= (float)floor(jit[i]); jit[i+1]-= (float)floor(jit[i+1]); @@ -684,7 +692,7 @@ static void init_mv_jit(float *jit, int num, int seed2, float amount) BLI_jitterate2(jit, jit2, num, rad2); } MEM_freeN(jit2); - rng_free(rng); + BLI_rng_free(rng); } static void psys_uv_to_w(float u, float v, int quad, float *w) @@ -698,21 +706,21 @@ static void psys_uv_to_w(float u, float v, int quad, float *w) u= 1.0f-u; } - vert[0][0]= 0.0f; vert[0][1]= 0.0f; vert[0][2]= 0.0f; - vert[1][0]= 1.0f; vert[1][1]= 0.0f; vert[1][2]= 0.0f; - vert[2][0]= 1.0f; vert[2][1]= 1.0f; vert[2][2]= 0.0f; + vert[0][0] = 0.0f; vert[0][1] = 0.0f; vert[0][2] = 0.0f; + vert[1][0] = 1.0f; vert[1][1] = 0.0f; vert[1][2] = 0.0f; + vert[2][0] = 1.0f; vert[2][1] = 1.0f; vert[2][2] = 0.0f; - co[0]= u; - co[1]= v; - co[2]= 0.0f; + co[0] = u; + co[1] = v; + co[2] = 0.0f; if (quad) { - vert[3][0]= 0.0f; vert[3][1]= 1.0f; vert[3][2]= 0.0f; + vert[3][0] = 0.0f; vert[3][1] = 1.0f; vert[3][2] = 0.0f; interp_weights_poly_v3( w,vert, 4, co); } else { interp_weights_poly_v3( w,vert, 3, co); - w[3]= 0.0f; + w[3] = 0.0f; } } @@ -804,8 +812,8 @@ static void distribute_threads_exec(ParticleThread *thread, ParticleData *pa, Ch } break; case PART_DISTR_RAND: - randu= rng_getFloat(thread->rng); - randv= rng_getFloat(thread->rng); + randu= BLI_rng_get_float(thread->rng); + randv= BLI_rng_get_float(thread->rng); rng_skip_tot -= 2; psys_uv_to_w(randu, randv, mface->v4, pa->fuv); @@ -881,8 +889,8 @@ static void distribute_threads_exec(ParticleThread *thread, ParticleData *pa, Ch mf= dm->getTessFaceData(dm, ctx->index[p], CD_MFACE); - randu= rng_getFloat(thread->rng); - randv= rng_getFloat(thread->rng); + randu= BLI_rng_get_float(thread->rng); + randv= BLI_rng_get_float(thread->rng); rng_skip_tot -= 2; psys_uv_to_w(randu, randv, mf->v4, cpa->fuv); @@ -934,7 +942,7 @@ static void distribute_threads_exec(ParticleThread *thread, ParticleData *pa, Ch } if (rng_skip_tot > 0) /* should never be below zero */ - rng_skip(thread->rng, rng_skip_tot); + BLI_rng_skip(thread->rng, rng_skip_tot); } static void *distribute_threads_exec_cb(void *data) @@ -951,12 +959,12 @@ static void *distribute_threads_exec_cb(void *data) for (p=0; p<totpart; p++, cpa++) { if (thread->ctx->skip) /* simplification skip */ - rng_skip(thread->rng, PSYS_RND_DIST_SKIP * thread->ctx->skip[p]); + BLI_rng_skip(thread->rng, PSYS_RND_DIST_SKIP * thread->ctx->skip[p]); if ((p+thread->num) % thread->tot == 0) distribute_threads_exec(thread, NULL, cpa, p); else /* thread skip */ - rng_skip(thread->rng, PSYS_RND_DIST_SKIP); + BLI_rng_skip(thread->rng, PSYS_RND_DIST_SKIP); } } else { @@ -973,8 +981,8 @@ static void *distribute_threads_exec_cb(void *data) static int *COMPARE_ORIG_INDEX = NULL; static int distribute_compare_orig_index(const void *p1, const void *p2) { - int index1 = COMPARE_ORIG_INDEX[*(const int*)p1]; - int index2 = COMPARE_ORIG_INDEX[*(const int*)p2]; + int index1 = COMPARE_ORIG_INDEX[*(const int *)p1]; + int index2 = COMPARE_ORIG_INDEX[*(const int *)p2]; if (index1 < index2) return -1; @@ -1000,7 +1008,7 @@ static void distribute_invalid(Scene *scene, ParticleSystem *psys, int from) if (psys->child && totchild) { for (p=0,cpa=psys->child; p<totchild; p++,cpa++) { - cpa->fuv[0]=cpa->fuv[1]=cpa->fuv[2]=cpa->fuv[3]= 0.0; + cpa->fuv[0]=cpa->fuv[1]=cpa->fuv[2]=cpa->fuv[3] = 0.0; cpa->foffset= 0.0f; cpa->parent=0; cpa->pa[0]=cpa->pa[1]=cpa->pa[2]=cpa->pa[3]=0; @@ -1011,7 +1019,7 @@ static void distribute_invalid(Scene *scene, ParticleSystem *psys, int from) else { PARTICLE_P; LOOP_PARTICLES { - pa->fuv[0]=pa->fuv[1]=pa->fuv[2]= pa->fuv[3]= 0.0; + pa->fuv[0] = pa->fuv[1] = pa->fuv[2] = pa->fuv[3] = 0.0; pa->foffset= 0.0f; pa->num= -1; } @@ -1113,7 +1121,7 @@ static int distribute_threads_init_data(ParticleThread *threads, Scene *scene, D if (from == PART_FROM_VERT) { MVert *mv= dm->getVertDataArray(dm, CD_MVERT); - float (*orcodata)[3]= dm->getVertDataArray(dm, CD_ORCO); + float (*orcodata)[3] = dm->getVertDataArray(dm, CD_ORCO); int totvert = dm->getNumVerts(dm); tree=BLI_kdtree_new(totvert); @@ -1245,9 +1253,9 @@ static int distribute_threads_init_data(ParticleThread *threads, Scene *scene, D inv_totweight = (totweight > 0.f ? 1.f/totweight : 0.f); /* Calculate cumulative weights */ - element_sum[0]= 0.0f; + element_sum[0] = 0.0f; for (i=0; i<totelem; i++) - element_sum[i+1]= element_sum[i] + element_weight[i] * inv_totweight; + element_sum[i+1] = element_sum[i] + element_weight[i] * inv_totweight; /* Finally assign elements to particles */ if ((part->flag&PART_TRAND) || (part->simplify_flag&PART_SIMPLIFY_ENABLE)) { @@ -1256,9 +1264,9 @@ static int distribute_threads_init_data(ParticleThread *threads, Scene *scene, D for (p=0; p<totpart; p++) { /* In theory element_sum[totelem] should be 1.0, but due to float errors this is not necessarily always true, so scale pos accordingly. */ pos= BLI_frand() * element_sum[totelem]; - particle_element[p]= distribute_binary_search(element_sum, totelem, pos); - particle_element[p]= MIN2(totelem-1, particle_element[p]); - jitter_offset[particle_element[p]]= pos; + particle_element[p] = distribute_binary_search(element_sum, totelem, pos); + particle_element[p] = MIN2(totelem-1, particle_element[p]); + jitter_offset[particle_element[p]] = pos; } } else { @@ -1269,16 +1277,16 @@ static int distribute_threads_init_data(ParticleThread *threads, Scene *scene, D i= 0; for (p=0; p<totpart; p++, pos+=step) { - while ((i < totelem) && (pos > element_sum[i+1])) + while ((i < totelem) && (pos > (double)element_sum[i + 1])) i++; - particle_element[p]= MIN2(totelem-1, i); + particle_element[p] = MIN2(totelem-1, i); /* avoid zero weight face */ if (p == totpart-1 && element_weight[particle_element[p]] == 0.0f) - particle_element[p]= particle_element[p-1]; + particle_element[p] = particle_element[p-1]; - jitter_offset[particle_element[p]]= pos; + jitter_offset[particle_element[p]] = pos; } } @@ -1353,7 +1361,7 @@ static int distribute_threads_init_data(ParticleThread *threads, Scene *scene, D seed= 31415926 + ctx->sim.psys->seed; for (i=0; i<totthread; i++) { - threads[i].rng= rng_new(seed); + threads[i].rng= BLI_rng_new(seed); threads[i].tot= totthread; } @@ -1492,9 +1500,9 @@ void psys_threads_free(ParticleThread *threads) /* threads */ for (i=0; i<totthread; i++) { if (threads[i].rng) - rng_free(threads[i].rng); + BLI_rng_free(threads[i].rng); if (threads[i].rng_path) - rng_free(threads[i].rng_path); + BLI_rng_free(threads[i].rng_path); } MEM_freeN(ctx); @@ -1583,7 +1591,7 @@ static void get_angular_velocity_vector(short avemode, ParticleKey *state, float switch (avemode) { case PART_AVE_VELOCITY: copy_v3_v3(vec, state->vel); - break; + break; case PART_AVE_HORIZONTAL: { float zvec[3]; @@ -1622,9 +1630,9 @@ void psys_get_birth_coordinates(ParticleSimulationData *sim, ParticleData *pa, P ParticleSystem *psys = sim->psys; ParticleSettings *part; ParticleTexture ptex; - float fac, phasefac, nor[3]={0,0,0},loc[3],vel[3]={0.0,0.0,0.0},rot[4],q2[4]; - float r_vel[3],r_ave[3],r_rot[4],vec[3],p_vel[3]={0.0,0.0,0.0}; - float x_vec[3]={1.0,0.0,0.0}, utan[3]={0.0,1.0,0.0}, vtan[3]={0.0,0.0,1.0}, rot_vec[3]={0.0,0.0,0.0}; + float fac, phasefac, nor[3] = {0,0,0},loc[3],vel[3] = {0.0,0.0,0.0},rot[4],q2[4]; + float r_vel[3],r_ave[3],r_rot[4],vec[3],p_vel[3] = {0.0,0.0,0.0}; + float x_vec[3] = {1.0,0.0,0.0}, utan[3] = {0.0,1.0,0.0}, vtan[3] = {0.0,0.0,1.0}, rot_vec[3] = {0.0,0.0,0.0}; float q_phase[4]; int p = pa - psys->particles; part=psys->part; @@ -2537,7 +2545,7 @@ static void sph_force_cb(void *sphdata_v, ParticleKey *state, float *force, floa madd_v3_v3fl(force, vec, -(pressure + near_pressure*q)*q); /* Viscosity */ - if (visc > 0.f || stiff_visc > 0.f) { + if (visc > 0.f || stiff_visc > 0.f) { sub_v3_v3v3(dv, vel, state->vel); u = dot_v3v3(vec, dv); @@ -2736,7 +2744,7 @@ static void basic_integrate(ParticleSimulationData *sim, int p, float dfra, floa } static void basic_rotate(ParticleSettings *part, ParticleData *pa, float dfra, float timestep) { - float rotfac, rot1[4], rot2[4]={1.0,0.0,0.0,0.0}, dtime=dfra*timestep, extrotfac; + float rotfac, rot1[4], rot2[4] = {1.0,0.0,0.0,0.0}, dtime=dfra*timestep, extrotfac; if ((part->flag & PART_ROTATIONS) == 0) { unit_qt(pa->state.rot); @@ -3166,8 +3174,7 @@ void BKE_psys_collision_neartest_cb(void *userdata, int index, const BVHTreeRay if (col->hit == col->current && col->pce.index == index && col->pce.tot == 3) return; - do - { + do { collision = collision_sphere_to_tri(col, ray->radius, &pce, &t); if (col->pce.inside == 0) { collision += collision_sphere_to_edges(col, ray->radius, &pce, &t); @@ -4076,7 +4083,7 @@ static void particles_fluid_step(ParticleSimulationData *sim, int UNUSED(cfra)) { FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(sim->ob, eModifierType_Fluidsim); - if ( fluidmd && fluidmd->fss) { + if ( fluidmd && fluidmd->fss) { FluidsimSettings *fss= fluidmd->fss; ParticleSettings *part = psys->part; ParticleData *pa=NULL; @@ -4121,7 +4128,7 @@ static void particles_fluid_step(ParticleSimulationData *sim, int UNUSED(cfra)) int ptype=0; gzread(gzf, &ptype, sizeof( ptype )); - if (ptype&readMask) { + if (ptype & readMask) { activeParts++; gzread(gzf, &(pa->size), sizeof(float)); diff --git a/source/blender/blenkernel/intern/pointcache.c b/source/blender/blenkernel/intern/pointcache.c index 8c0d19ba1fd..f195b3d71b0 100644 --- a/source/blender/blenkernel/intern/pointcache.c +++ b/source/blender/blenkernel/intern/pointcache.c @@ -249,9 +249,9 @@ static int ptcache_particle_write(int index, void *psys_v, void **data, int cfr if (data[BPHYS_DATA_INDEX] && (cfra < pa->time - step || cfra > pa->dietime + step)) return 0; - times[0]= pa->time; - times[1]= pa->dietime; - times[2]= pa->lifetime; + times[0] = pa->time; + times[1] = pa->dietime; + times[2] = pa->lifetime; PTCACHE_DATA_FROM(data, BPHYS_DATA_INDEX, &index); PTCACHE_DATA_FROM(data, BPHYS_DATA_LOCATION, pa->state.co); @@ -532,20 +532,31 @@ static int ptcache_smoke_totpoint(void *smoke_v, int UNUSED(cfra)) SmokeDomainSettings *sds = smd->domain; if (sds->fluid) { - return sds->res[0]*sds->res[1]*sds->res[2]; + return sds->base_res[0]*sds->base_res[1]*sds->base_res[2]; } else return 0; } + +#define SMOKE_CACHE_VERSION "1.04" + static int ptcache_smoke_write(PTCacheFile *pf, void *smoke_v) { SmokeModifierData *smd= (SmokeModifierData *)smoke_v; SmokeDomainSettings *sds = smd->domain; int ret = 0; + int fluid_fields = smoke_get_data_flags(sds); + + /* version header */ + ptcache_file_write(pf, SMOKE_CACHE_VERSION, 4, sizeof(char)); + ptcache_file_write(pf, &fluid_fields, 1, sizeof(int)); + ptcache_file_write(pf, &sds->active_fields, 1, sizeof(int)); + ptcache_file_write(pf, &sds->res, 3, sizeof(int)); + ptcache_file_write(pf, &sds->dx, 1, sizeof(float)); if (sds->fluid) { size_t res = sds->res[0]*sds->res[1]*sds->res[2]; - float dt, dx, *dens, *densold, *heat, *heatold, *vx, *vy, *vz, *vxold, *vyold, *vzold; + float dt, dx, *dens, *react, *fuel, *flame, *heat, *heatold, *vx, *vy, *vz, *r, *g, *b; unsigned char *obstacles; 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"); @@ -553,22 +564,40 @@ static int ptcache_smoke_write(PTCacheFile *pf, void *smoke_v) int mode=1; // light if (sds->cache_comp == SM_CACHE_HEAVY) mode=2; // heavy - smoke_export(sds->fluid, &dt, &dx, &dens, &densold, &heat, &heatold, &vx, &vy, &vz, &vxold, &vyold, &vzold, &obstacles); + smoke_export(sds->fluid, &dt, &dx, &dens, &react, &flame, &fuel, &heat, &heatold, &vx, &vy, &vz, &r, &g, &b, &obstacles); ptcache_file_compressed_write(pf, (unsigned char *)sds->shadow, in_len, out, mode); ptcache_file_compressed_write(pf, (unsigned char *)dens, in_len, out, mode); - ptcache_file_compressed_write(pf, (unsigned char *)densold, in_len, out, mode); - ptcache_file_compressed_write(pf, (unsigned char *)heat, in_len, out, mode); - ptcache_file_compressed_write(pf, (unsigned char *)heatold, in_len, out, mode); + if (fluid_fields & SM_ACTIVE_HEAT) { + ptcache_file_compressed_write(pf, (unsigned char *)heat, in_len, out, mode); + ptcache_file_compressed_write(pf, (unsigned char *)heatold, in_len, out, mode); + } + if (fluid_fields & SM_ACTIVE_FIRE) { + ptcache_file_compressed_write(pf, (unsigned char *)flame, in_len, out, mode); + ptcache_file_compressed_write(pf, (unsigned char *)fuel, in_len, out, mode); + ptcache_file_compressed_write(pf, (unsigned char *)react, in_len, out, mode); + } + if (fluid_fields & SM_ACTIVE_COLORS) { + ptcache_file_compressed_write(pf, (unsigned char *)r, in_len, out, mode); + ptcache_file_compressed_write(pf, (unsigned char *)g, in_len, out, mode); + ptcache_file_compressed_write(pf, (unsigned char *)b, in_len, out, mode); + } ptcache_file_compressed_write(pf, (unsigned char *)vx, in_len, out, mode); ptcache_file_compressed_write(pf, (unsigned char *)vy, in_len, out, mode); ptcache_file_compressed_write(pf, (unsigned char *)vz, in_len, out, mode); - ptcache_file_compressed_write(pf, (unsigned char *)vxold, in_len, out, mode); - ptcache_file_compressed_write(pf, (unsigned char *)vyold, in_len, out, mode); - ptcache_file_compressed_write(pf, (unsigned char *)vzold, in_len, out, mode); ptcache_file_compressed_write(pf, (unsigned char *)obstacles, (unsigned int)res, out, mode); ptcache_file_write(pf, &dt, 1, sizeof(float)); ptcache_file_write(pf, &dx, 1, sizeof(float)); + ptcache_file_write(pf, &sds->p0, 3, sizeof(float)); + ptcache_file_write(pf, &sds->p1, 3, sizeof(float)); + ptcache_file_write(pf, &sds->dp0, 3, sizeof(float)); + ptcache_file_write(pf, &sds->shift, 3, sizeof(int)); + ptcache_file_write(pf, &sds->obj_shift_f, 3, sizeof(float)); + ptcache_file_write(pf, &sds->obmat, 16, sizeof(float)); + ptcache_file_write(pf, &sds->base_res, 3, sizeof(int)); + ptcache_file_write(pf, &sds->res_min, 3, sizeof(int)); + ptcache_file_write(pf, &sds->res_max, 3, sizeof(int)); + ptcache_file_write(pf, &sds->active_color, 3, sizeof(float)); MEM_freeN(out); @@ -579,7 +608,7 @@ static int ptcache_smoke_write(PTCacheFile *pf, void *smoke_v) int res_big_array[3]; int res_big; int res = sds->res[0]*sds->res[1]*sds->res[2]; - float *dens, *densold, *tcu, *tcv, *tcw; + float *dens, *react, *fuel, *flame, *tcu, *tcv, *tcw, *r, *g, *b; unsigned int in_len = sizeof(float)*(unsigned int)res; unsigned int in_len_big; unsigned char *out; @@ -593,11 +622,20 @@ static int ptcache_smoke_write(PTCacheFile *pf, void *smoke_v) in_len_big = sizeof(float) * (unsigned int)res_big; - smoke_turbulence_export(sds->wt, &dens, &densold, &tcu, &tcv, &tcw); + smoke_turbulence_export(sds->wt, &dens, &react, &flame, &fuel, &r, &g, &b, &tcu, &tcv, &tcw); out = (unsigned char *)MEM_callocN(LZO_OUT_LEN(in_len_big), "pointcache_lzo_buffer"); ptcache_file_compressed_write(pf, (unsigned char *)dens, in_len_big, out, mode); - ptcache_file_compressed_write(pf, (unsigned char *)densold, in_len_big, out, mode); + if (fluid_fields & SM_ACTIVE_FIRE) { + ptcache_file_compressed_write(pf, (unsigned char *)flame, in_len_big, out, mode); + ptcache_file_compressed_write(pf, (unsigned char *)fuel, in_len_big, out, mode); + ptcache_file_compressed_write(pf, (unsigned char *)react, in_len_big, out, mode); + } + if (fluid_fields & SM_ACTIVE_COLORS) { + ptcache_file_compressed_write(pf, (unsigned char *)r, in_len_big, out, mode); + ptcache_file_compressed_write(pf, (unsigned char *)g, in_len_big, out, mode); + ptcache_file_compressed_write(pf, (unsigned char *)b, in_len_big, out, mode); + } MEM_freeN(out); out = (unsigned char *)MEM_callocN(LZO_OUT_LEN(in_len), "pointcache_lzo_buffer"); @@ -615,34 +653,95 @@ static int ptcache_smoke_read(PTCacheFile *pf, void *smoke_v) { SmokeModifierData *smd= (SmokeModifierData *)smoke_v; SmokeDomainSettings *sds = smd->domain; + char version[4]; + int ch_res[3]; + float ch_dx; + int fluid_fields = smoke_get_data_flags(sds); + int cache_fields = 0; + int active_fields = 0; + int reallocate = 0; + + /* version header */ + ptcache_file_read(pf, version, 4, sizeof(char)); + if (strncmp(version, SMOKE_CACHE_VERSION, 4)) return 0; + /* fluid info */ + ptcache_file_read(pf, &cache_fields, 1, sizeof(int)); + ptcache_file_read(pf, &active_fields, 1, sizeof(int)); + ptcache_file_read(pf, &ch_res, 3, sizeof(int)); + ptcache_file_read(pf, &ch_dx, 1, sizeof(float)); + + /* 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) + reallocate = 1; + else + return 0; + } + /* check if active fields have changed */ + if (fluid_fields != cache_fields || + active_fields != sds->active_fields) + reallocate = 1; + + /* reallocate fluid if needed*/ + if (reallocate) { + sds->active_fields = active_fields; + smoke_reallocate_fluid(sds, ch_dx, ch_res, 1); + sds->dx = ch_dx; + VECCOPY(sds->res, ch_res); + sds->total_cells = ch_res[0]*ch_res[1]*ch_res[2]; + if (sds->flags & MOD_SMOKE_HIGHRES) { + smoke_reallocate_highres_fluid(sds, ch_dx, ch_res, 1); + } + } if (sds->fluid) { size_t res = sds->res[0]*sds->res[1]*sds->res[2]; - float dt, dx, *dens, *densold, *heat, *heatold, *vx, *vy, *vz, *vxold, *vyold, *vzold; + float dt, dx, *dens, *react, *fuel, *flame, *heat, *heatold, *vx, *vy, *vz, *r, *g, *b; unsigned char *obstacles; unsigned int out_len = (unsigned int)res * sizeof(float); - smoke_export(sds->fluid, &dt, &dx, &dens, &densold, &heat, &heatold, &vx, &vy, &vz, &vxold, &vyold, &vzold, &obstacles); + smoke_export(sds->fluid, &dt, &dx, &dens, &react, &flame, &fuel, &heat, &heatold, &vx, &vy, &vz, &r, &g, &b, &obstacles); ptcache_file_compressed_read(pf, (unsigned char *)sds->shadow, out_len); - ptcache_file_compressed_read(pf, (unsigned char*)dens, out_len); - ptcache_file_compressed_read(pf, (unsigned char*)densold, out_len); - ptcache_file_compressed_read(pf, (unsigned char*)heat, out_len); - ptcache_file_compressed_read(pf, (unsigned char*)heatold, out_len); - ptcache_file_compressed_read(pf, (unsigned char*)vx, out_len); - ptcache_file_compressed_read(pf, (unsigned char*)vy, out_len); - ptcache_file_compressed_read(pf, (unsigned char*)vz, out_len); - ptcache_file_compressed_read(pf, (unsigned char*)vxold, out_len); - ptcache_file_compressed_read(pf, (unsigned char*)vyold, out_len); - ptcache_file_compressed_read(pf, (unsigned char*)vzold, out_len); - ptcache_file_compressed_read(pf, (unsigned char*)obstacles, (unsigned int)res); + ptcache_file_compressed_read(pf, (unsigned char *)dens, out_len); + if (cache_fields & SM_ACTIVE_HEAT) { + ptcache_file_compressed_read(pf, (unsigned char *)heat, out_len); + ptcache_file_compressed_read(pf, (unsigned char *)heatold, out_len); + } + if (cache_fields & SM_ACTIVE_FIRE) { + ptcache_file_compressed_read(pf, (unsigned char *)flame, out_len); + ptcache_file_compressed_read(pf, (unsigned char *)fuel, out_len); + ptcache_file_compressed_read(pf, (unsigned char *)react, out_len); + } + if (cache_fields & SM_ACTIVE_COLORS) { + ptcache_file_compressed_read(pf, (unsigned char *)r, out_len); + ptcache_file_compressed_read(pf, (unsigned char *)g, out_len); + ptcache_file_compressed_read(pf, (unsigned char *)b, out_len); + } + ptcache_file_compressed_read(pf, (unsigned char *)vx, out_len); + ptcache_file_compressed_read(pf, (unsigned char *)vy, out_len); + ptcache_file_compressed_read(pf, (unsigned char *)vz, out_len); + ptcache_file_compressed_read(pf, (unsigned char *)obstacles, (unsigned int)res); ptcache_file_read(pf, &dt, 1, sizeof(float)); ptcache_file_read(pf, &dx, 1, sizeof(float)); - - if (pf->data_types & (1<<BPHYS_DATA_SMOKE_HIGH) && sds->wt) { + ptcache_file_read(pf, &sds->p0, 3, sizeof(float)); + ptcache_file_read(pf, &sds->p1, 3, sizeof(float)); + ptcache_file_read(pf, &sds->dp0, 3, sizeof(float)); + ptcache_file_read(pf, &sds->shift, 3, sizeof(int)); + ptcache_file_read(pf, &sds->obj_shift_f, 3, sizeof(float)); + ptcache_file_read(pf, &sds->obmat, 16, sizeof(float)); + ptcache_file_read(pf, &sds->base_res, 3, sizeof(int)); + ptcache_file_read(pf, &sds->res_min, 3, sizeof(int)); + ptcache_file_read(pf, &sds->res_max, 3, sizeof(int)); + ptcache_file_read(pf, &sds->active_color, 3, sizeof(float)); + } + + if (pf->data_types & (1<<BPHYS_DATA_SMOKE_HIGH) && sds->wt) { int res = sds->res[0]*sds->res[1]*sds->res[2]; int res_big, res_big_array[3]; - float *dens, *densold, *tcu, *tcv, *tcw; + float *dens, *react, *fuel, *flame, *tcu, *tcv, *tcw, *r, *g, *b; unsigned int out_len = sizeof(float)*(unsigned int)res; unsigned int out_len_big; @@ -650,16 +749,23 @@ static int ptcache_smoke_read(PTCacheFile *pf, void *smoke_v) res_big = res_big_array[0]*res_big_array[1]*res_big_array[2]; out_len_big = sizeof(float) * (unsigned int)res_big; - smoke_turbulence_export(sds->wt, &dens, &densold, &tcu, &tcv, &tcw); + smoke_turbulence_export(sds->wt, &dens, &react, &flame, &fuel, &r, &g, &b, &tcu, &tcv, &tcw); - ptcache_file_compressed_read(pf, (unsigned char*)dens, out_len_big); - ptcache_file_compressed_read(pf, (unsigned char*)densold, out_len_big); + ptcache_file_compressed_read(pf, (unsigned char *)dens, out_len_big); + if (cache_fields & SM_ACTIVE_FIRE) { + ptcache_file_compressed_read(pf, (unsigned char *)flame, out_len_big); + ptcache_file_compressed_read(pf, (unsigned char *)fuel, out_len_big); + } + if (cache_fields & SM_ACTIVE_COLORS) { + ptcache_file_compressed_read(pf, (unsigned char *)r, out_len_big); + ptcache_file_compressed_read(pf, (unsigned char *)g, out_len_big); + ptcache_file_compressed_read(pf, (unsigned char *)b, out_len_big); + } - ptcache_file_compressed_read(pf, (unsigned char*)tcu, out_len); - ptcache_file_compressed_read(pf, (unsigned char*)tcv, out_len); - ptcache_file_compressed_read(pf, (unsigned char*)tcw, out_len); + ptcache_file_compressed_read(pf, (unsigned char *)tcu, out_len); + ptcache_file_compressed_read(pf, (unsigned char *)tcv, out_len); + ptcache_file_compressed_read(pf, (unsigned char *)tcw, out_len); } - } return 1; } @@ -753,7 +859,7 @@ static int ptcache_dynamicpaint_read(PTCacheFile *pf, void *dp_v) return 0; } - ptcache_file_compressed_read(pf, (unsigned char*)surface->data->type_data, data_len*surface->data->total_points); + ptcache_file_compressed_read(pf, (unsigned char *)surface->data->type_data, data_len*surface->data->total_points); } return 1; @@ -1257,7 +1363,7 @@ static int ptcache_file_compressed_write(PTCacheFile *pf, unsigned char *in, uns if (mode == 1) { LZO_HEAP_ALLOC(wrkmem, LZO1X_MEM_COMPRESS); - r = lzo1x_1_compress(in, (lzo_uint)in_len, out, (lzo_uint *)&out_len, wrkmem); + r = lzo1x_1_compress(in, (lzo_uint)in_len, out, (lzo_uint *)&out_len, wrkmem); if (!(r == LZO_E_OK) || (out_len >= in_len)) compressed = 0; else @@ -1593,7 +1699,7 @@ static PTCacheMem *ptcache_disk_frame_to_mem(PTCacheID *pid, int cfra) for (i=0; i<BPHYS_TOT_DATA; i++) { unsigned int out_len = pm->totpoint*ptcache_data_size[i]; if (pf->data_types & (1<<i)) - ptcache_file_compressed_read(pf, (unsigned char*)(pm->data[i]), out_len); + ptcache_file_compressed_read(pf, (unsigned char *)(pm->data[i]), out_len); } } else { @@ -1624,7 +1730,7 @@ 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) - ptcache_file_compressed_read(pf, (unsigned char*)(extra->data), extra->totdata*ptcache_extra_datasize[extra->type]); + ptcache_file_compressed_read(pf, (unsigned char *)(extra->data), extra->totdata*ptcache_extra_datasize[extra->type]); else ptcache_file_read(pf, extra->data, extra->totdata, ptcache_extra_datasize[extra->type]); @@ -1681,7 +1787,7 @@ static int ptcache_mem_frame_to_disk(PTCacheID *pid, PTCacheMem *pm) if (pm->data[i]) { unsigned int in_len = pm->totpoint*ptcache_data_size[i]; unsigned char *out = (unsigned char *)MEM_callocN(LZO_OUT_LEN(in_len)*4, "pointcache_lzo_buffer"); - ptcache_file_compressed_write(pf, (unsigned char*)(pm->data[i]), in_len, out, pid->cache->compression); + ptcache_file_compressed_write(pf, (unsigned char *)(pm->data[i]), in_len, out, pid->cache->compression); MEM_freeN(out); } } @@ -1714,7 +1820,7 @@ static int ptcache_mem_frame_to_disk(PTCacheID *pid, PTCacheMem *pm) if (pid->cache->compression) { unsigned int in_len = extra->totdata * ptcache_extra_datasize[extra->type]; unsigned char *out = (unsigned char *)MEM_callocN(LZO_OUT_LEN(in_len)*4, "pointcache_lzo_buffer"); - ptcache_file_compressed_write(pf, (unsigned char*)(extra->data), in_len, out, pid->cache->compression); + ptcache_file_compressed_write(pf, (unsigned char *)(extra->data), in_len, out, pid->cache->compression); MEM_freeN(out); } else { @@ -1925,18 +2031,16 @@ int BKE_ptcache_read(PTCacheID *pid, float cfra) pid->cache->simframe = cfra2; } - if ((pid->cache->flag & PTCACHE_QUICK_CACHE)==0) { - cfrai = (int)cfra; - /* clear invalid cache frames so that better stuff can be simulated */ - if (pid->cache->flag & PTCACHE_OUTDATED) { - BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_AFTER, cfrai); - } - else if (pid->cache->flag & PTCACHE_FRAMES_SKIPPED) { - if (cfra <= pid->cache->last_exact) - pid->cache->flag &= ~PTCACHE_FRAMES_SKIPPED; + cfrai = (int)cfra; + /* clear invalid cache frames so that better stuff can be simulated */ + if (pid->cache->flag & PTCACHE_OUTDATED) { + BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_AFTER, cfrai); + } + else if (pid->cache->flag & PTCACHE_FRAMES_SKIPPED) { + 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)); - } + BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_AFTER, MAX2(cfrai, pid->cache->last_exact)); } return ret; @@ -2167,7 +2271,7 @@ void BKE_ptcache_id_clear(PTCacheID *pid, int mode, unsigned int cfra) /* clear all files in the temp dir with the prefix of the ID and the ".bphys" suffix */ switch (mode) { case PTCACHE_CLEAR_ALL: - case PTCACHE_CLEAR_BEFORE: + case PTCACHE_CLEAR_BEFORE: case PTCACHE_CLEAR_AFTER: if (pid->cache->flag & PTCACHE_DISK_CACHE) { ptcache_path(pid, path); @@ -2271,7 +2375,7 @@ 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; } @@ -2358,7 +2462,7 @@ void BKE_ptcache_id_time(PTCacheID *pid, Scene *scene, float cfra, int *startfra if (MEM_allocN_len(cache->cached_frames) != sizeof(char) * (cache->endframe-cache->startframe+1)) { MEM_freeN(cache->cached_frames); cache->cached_frames = NULL; - } + } } if (cache->cached_frames==NULL && cache->endframe > cache->startframe) { @@ -2431,8 +2535,6 @@ int BKE_ptcache_id_reset(Scene *scene, PTCacheID *pid, int mode) if (mode == PTCACHE_RESET_DEPSGRAPH) { if (!(cache->flag & PTCACHE_BAKED) && !BKE_ptcache_get_continue_physics()) { - if (cache->flag & PTCACHE_QUICK_CACHE) - clear= 1; after= 1; } @@ -2466,10 +2568,10 @@ int BKE_ptcache_id_reset(Scene *scene, PTCacheID *pid, int mode) sbFreeSimulation(pid->calldata); else if (pid->type == PTCACHE_TYPE_PARTICLES) psys_reset(pid->calldata, PSYS_RESET_DEPSGRAPH); - else if (pid->type == PTCACHE_TYPE_SMOKE_DOMAIN) + /*else if (pid->type == PTCACHE_TYPE_SMOKE_DOMAIN) smokeModifier_reset(pid->calldata); else if (pid->type == PTCACHE_TYPE_SMOKE_HIGHRES) - smokeModifier_reset_turbulence(pid->calldata); + smokeModifier_reset_turbulence(pid->calldata);*/ else if (pid->type == PTCACHE_TYPE_DYNAMICPAINT) dynamicPaint_clearSurface((DynamicPaintSurface*)pid->calldata); } @@ -2496,7 +2598,7 @@ 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 reseting anything */ + /* children or just redo can be calculated without resetting anything */ if (psys->recalc & PSYS_RECALC_REDO || psys->recalc & PSYS_RECALC_CHILD) skip = 1; /* Baked cloth hair has to be checked too, because we don't want to reset */ @@ -2720,6 +2822,8 @@ PointCache *BKE_ptcache_copy_list(ListBase *ptcaches_new, ListBase *ptcaches_old return ptcaches_new->first; } +/* Disabled this code; this is being called on scene_update_tagged, and that in turn gets called on + * every user action changing stuff, and then it runs a complete bake??? (ton) */ /* Baking */ void BKE_ptcache_quick_cache_all(Main *bmain, Scene *scene) @@ -2903,7 +3007,7 @@ void BKE_ptcache_bake(PTCacheBaker* baker) } if ((cache->flag & PTCACHE_REDO_NEEDED || (cache->flag & PTCACHE_SIMULATION_VALID)==0) && - ((cache->flag & PTCACHE_QUICK_CACHE)==0 || render || bake)) + (render || bake)) { BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_ALL, 0); } @@ -3222,8 +3326,9 @@ void BKE_ptcache_load_external(PTCacheID *pid) cache->endframe = end; cache->totpoint = 0; - if (pid->type == PTCACHE_TYPE_SMOKE_DOMAIN) - ; /*necessary info in every file*/ + if (pid->type == PTCACHE_TYPE_SMOKE_DOMAIN) { + /* necessary info in every file */ + } /* read totpoint from info file (frame 0) */ else if (info) { pf= ptcache_file_open(pid, PTCACHE_FILE_READ, 0); @@ -3271,7 +3376,7 @@ void BKE_ptcache_update_info(PTCacheID *pid) if (cache->flag & PTCACHE_EXTERNAL) { int cfra = cache->startframe; - for (; cfra<=cache->endframe; cfra++) { + for (; cfra <= cache->endframe; cfra++) { if (BKE_ptcache_id_exist(pid, cfra)) totframes++; } @@ -3298,7 +3403,7 @@ void BKE_ptcache_update_info(PTCacheID *pid) else { int cfra = cache->startframe; - for (; cfra<=cache->endframe; cfra++) { + for (; cfra <= cache->endframe; cfra++) { if (BKE_ptcache_id_exist(pid, cfra)) totframes++; } @@ -3307,7 +3412,7 @@ void BKE_ptcache_update_info(PTCacheID *pid) } } else { - PTCacheMem *pm = cache->mem_cache.first; + PTCacheMem *pm = cache->mem_cache.first; float bytes = 0.0f; int i, mb; diff --git a/source/blender/blenkernel/intern/report.c b/source/blender/blenkernel/intern/report.c index 3a66ec23412..d925d736358 100644 --- a/source/blender/blenkernel/intern/report.c +++ b/source/blender/blenkernel/intern/report.c @@ -34,6 +34,8 @@ #include "BLI_dynstr.h" #include "BLI_utildefines.h" +#include "BLF_translation.h" + #include "BKE_report.h" #include "BKE_global.h" /* G.background only */ @@ -44,15 +46,24 @@ static const char *report_type_str(int type) { switch (type) { - case RPT_DEBUG: return "Debug"; - case RPT_INFO: return "Info"; - case RPT_OPERATOR: return "Operator"; - case RPT_WARNING: return "Warning"; - case RPT_ERROR: return "Error"; - case RPT_ERROR_INVALID_INPUT: return "Invalid Input Error"; - case RPT_ERROR_INVALID_CONTEXT: return "Invalid Context Error"; - case RPT_ERROR_OUT_OF_MEMORY: return "Out Of Memory Error"; - default: return "Undefined Type"; + case RPT_DEBUG: + return TIP_("Debug"); + case RPT_INFO: + return TIP_("Info"); + case RPT_OPERATOR: + return TIP_("Operator"); + case RPT_WARNING: + return TIP_("Warning"); + case RPT_ERROR: + return TIP_("Error"); + case RPT_ERROR_INVALID_INPUT: + return TIP_("Invalid Input Error"); + case RPT_ERROR_INVALID_CONTEXT: + return TIP_("Invalid Context Error"); + case RPT_ERROR_OUT_OF_MEMORY: + return TIP_("Out Of Memory Error"); + default: + return TIP_("Undefined Type"); } } @@ -87,10 +98,11 @@ void BKE_reports_clear(ReportList *reports) reports->list.first = reports->list.last = NULL; } -void BKE_report(ReportList *reports, ReportType type, const char *message) +void BKE_report(ReportList *reports, ReportType type, const char *_message) { Report *report; int len; + const char *message = TIP_(_message); /* in background mode always print otherwise there are cases the errors wont be displayed, * but still add to the report list since this is used for python exception handling */ @@ -114,14 +126,16 @@ void BKE_report(ReportList *reports, ReportType type, const char *message) } } -void BKE_reportf(ReportList *reports, ReportType type, const char *format, ...) +void BKE_reportf(ReportList *reports, ReportType type, const char *_format, ...) { DynStr *ds; Report *report; va_list args; + const char *format = TIP_(_format); if (G.background || !reports || ((reports->flag & RPT_PRINT) && (type >= reports->printlevel))) { - va_start(args, format); + printf("%s: ", report_type_str(type)); + va_start(args, _format); vprintf(format, args); va_end(args); fprintf(stdout, "\n"); /* otherise each report needs to include a \n */ @@ -132,7 +146,7 @@ void BKE_reportf(ReportList *reports, ReportType type, const char *format, ...) report = MEM_callocN(sizeof(Report), "Report"); ds = BLI_dynstr_new(); - va_start(args, format); + va_start(args, _format); BLI_dynstr_vappendf(ds, format, args); va_end(args); @@ -147,10 +161,11 @@ void BKE_reportf(ReportList *reports, ReportType type, const char *format, ...) } } -void BKE_reports_prepend(ReportList *reports, const char *prepend) +void BKE_reports_prepend(ReportList *reports, const char *_prepend) { Report *report; DynStr *ds; + const char *prepend = TIP_(_prepend); if (!reports) return; @@ -169,18 +184,19 @@ void BKE_reports_prepend(ReportList *reports, const char *prepend) } } -void BKE_reports_prependf(ReportList *reports, const char *prepend, ...) +void BKE_reports_prependf(ReportList *reports, const char *_prepend, ...) { Report *report; DynStr *ds; va_list args; + const char *prepend = TIP_(_prepend); if (!reports) return; for (report = reports->list.first; report; report = report->next) { ds = BLI_dynstr_new(); - va_start(args, prepend); + va_start(args, _prepend); BLI_dynstr_vappendf(ds, prepend, args); va_end(args); diff --git a/source/blender/blenkernel/intern/sca.c b/source/blender/blenkernel/intern/sca.c index 6c1fbbfa9a0..eb4e0d9c679 100644 --- a/source/blender/blenkernel/intern/sca.c +++ b/source/blender/blenkernel/intern/sca.c @@ -552,7 +552,7 @@ void set_sca_new_poins_ob(Object *ob) if (sens->flag & SENS_NEW) { for (a=0; a<sens->totlinks; a++) { if (sens->links[a] && sens->links[a]->mynew) - sens->links[a]= sens->links[a]->mynew; + sens->links[a] = sens->links[a]->mynew; } } sens= sens->next; @@ -563,7 +563,7 @@ void set_sca_new_poins_ob(Object *ob) if (cont->flag & CONT_NEW) { for (a=0; a<cont->totlinks; a++) { if ( cont->links[a] && cont->links[a]->mynew) - cont->links[a]= cont->links[a]->mynew; + cont->links[a] = cont->links[a]->mynew; } } cont= cont->next; diff --git a/source/blender/blenkernel/intern/scene.c b/source/blender/blenkernel/intern/scene.c index f8777f87369..4f62732f5e6 100644 --- a/source/blender/blenkernel/intern/scene.c +++ b/source/blender/blenkernel/intern/scene.c @@ -54,11 +54,14 @@ #include "BLI_blenlib.h" #include "BLI_utildefines.h" #include "BLI_callbacks.h" +#include "BLI_string.h" #include "BKE_anim.h" #include "BKE_animsys.h" +#include "BKE_action.h" #include "BKE_colortools.h" #include "BKE_depsgraph.h" +#include "BKE_fcurve.h" #include "BKE_global.h" #include "BKE_group.h" #include "BKE_idprop.h" @@ -114,6 +117,24 @@ void free_qtcodecdata(QuicktimeCodecData *qcd) } } +static void remove_sequencer_fcurves(Scene *sce) +{ + AnimData *adt = BKE_animdata_from_id(&sce->id); + + if (adt && adt->action) { + FCurve *fcu, *nextfcu; + + for (fcu = adt->action->curves.first; fcu; fcu = nextfcu) { + nextfcu = fcu->next; + + if ((fcu->rna_path) && strstr(fcu->rna_path, "sequences_all")) { + action_groups_remove_channel(adt->action, fcu); + free_fcurve(fcu); + } + } + } +} + Scene *BKE_scene_copy(Scene *sce, int type) { Scene *scen; @@ -175,6 +196,13 @@ Scene *BKE_scene_copy(Scene *sce, int type) BKE_color_managed_display_settings_copy(&scen->display_settings, &sce->display_settings); BKE_color_managed_view_settings_copy(&scen->view_settings, &sce->view_settings); BKE_color_managed_view_settings_copy(&scen->r.im_format.view_settings, &sce->r.im_format.view_settings); + + BLI_strncpy(scen->sequencer_colorspace_settings.name, sce->sequencer_colorspace_settings.name, + sizeof(scen->sequencer_colorspace_settings.name)); + + /* remove animation used by sequencer */ + if (type != SCE_COPY_FULL) + remove_sequencer_fcurves(scen); } /* tool settings */ @@ -321,7 +349,7 @@ void BKE_scene_free(Scene *sce) BKE_paint_free(&sce->toolsettings->imapaint.paint); MEM_freeN(sce->toolsettings); - sce->toolsettings = NULL; + sce->toolsettings = NULL; } if (sce->theDag) { @@ -350,6 +378,7 @@ Scene *BKE_scene_add(const char *name) Scene *sce; ParticleEditSettings *pset; int a; + const char *colorspace_name; sce = BKE_libblock_alloc(&bmain->scene, ID_SCE, name); sce->lay = sce->layact = 1; @@ -363,8 +392,8 @@ Scene *BKE_scene_add(const char *name) sce->r.ysch = 1080; sce->r.xasp = 1; sce->r.yasp = 1; - sce->r.xparts = 8; - sce->r.yparts = 8; + sce->r.tilex = 256; + sce->r.tiley = 256; sce->r.mblur_samples = 1; sce->r.filtertype = R_FILTER_MITCH; sce->r.size = 50; @@ -431,7 +460,7 @@ Scene *BKE_scene_add(const char *name) sce->toolsettings->cornertype = 1; sce->toolsettings->degr = 90; sce->toolsettings->step = 9; - sce->toolsettings->turn = 1; + sce->toolsettings->turn = 1; sce->toolsettings->extr_offs = 1; sce->toolsettings->doublimit = 0.001; sce->toolsettings->segments = 32; @@ -441,6 +470,7 @@ Scene *BKE_scene_add(const char *name) sce->toolsettings->uvcalc_cubesize = 1.0f; sce->toolsettings->uvcalc_mapdir = 1; sce->toolsettings->uvcalc_mapalign = 1; + sce->toolsettings->uvcalc_margin = 0.001f; sce->toolsettings->unwrapper = 1; sce->toolsettings->select_thresh = 0.01f; sce->toolsettings->jointrilimit = 0.8f; @@ -563,8 +593,13 @@ Scene *BKE_scene_add(const char *name) sound_create_scene(sce); + /* color management */ + colorspace_name = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_SEQUENCER); + BKE_color_managed_display_settings_init(&sce->display_settings); BKE_color_managed_view_settings_init(&sce->view_settings); + BLI_strncpy(sce->sequencer_colorspace_settings.name, colorspace_name, + sizeof(sce->sequencer_colorspace_settings.name)); return sce; } @@ -947,7 +982,7 @@ float BKE_scene_frame_get_from_ctime(Scene *scene, const float frame) { float ctime = frame; ctime += scene->r.subframe; - ctime *= scene->r.framelen; + ctime *= scene->r.framelen; return ctime; } @@ -1008,8 +1043,10 @@ static void scene_update_tagged_recursive(Main *bmain, Scene *scene, Scene *scen if (ob->dup_group && (ob->transflag & OB_DUPLIGROUP)) group_handle_recalc_and_update(scene_parent, ob, ob->dup_group); - /* always update layer, so that animating layers works */ - base->lay = ob->lay; + /* always update layer, so that animating layers works (joshua july 2010) */ + /* XXX commented out, this has depsgraph issues anyway - and this breaks setting scenes + (on scene-set, the base-lay is copied to ob-lay (ton nov 2012) */ + // base->lay = ob->lay; } /* scene drivers... */ @@ -1031,12 +1068,13 @@ void BKE_scene_update_tagged(Main *bmain, Scene *scene) /* flush recalc flags to dependencies */ DAG_ids_flush_tagged(bmain); - scene->physics_settings.quick_cache_step = 0; + /* removed calls to quick_cache, see pointcache.c */ /* clear "LIB_DOIT" flag from all materials, to prevent infinite recursion problems later * when trying to find materials with drivers that need evaluating [#32017] */ tag_main_idcode(bmain, ID_MA, FALSE); + tag_main_idcode(bmain, ID_LA, FALSE); /* update all objects: drivers, matrices, displists, etc. flags set * by depgraph or manual, no layer check here, gets correct flushed @@ -1054,10 +1092,6 @@ void BKE_scene_update_tagged(Main *bmain, Scene *scene) BKE_animsys_evaluate_animdata(scene, &scene->id, adt, ctime, 0); } - /* quick point cache updates */ - if (scene->physics_settings.quick_cache_step) - BKE_ptcache_quick_cache_all(bmain, scene); - /* notify editors and python about recalc */ BLI_callback_exec(bmain, &scene->id, BLI_CB_EVT_SCENE_UPDATE_POST); DAG_ids_check_recalc(bmain, scene, FALSE); @@ -1106,6 +1140,12 @@ void BKE_scene_update_for_newframe(Main *bmain, Scene *sce, unsigned int lay) BKE_animsys_evaluate_all_animation(bmain, sce, ctime); /*...done with recusrive funcs */ + /* clear "LIB_DOIT" flag from all materials, to prevent infinite recursion problems later + * when trying to find materials with drivers that need evaluating [#32017] + */ + tag_main_idcode(bmain, ID_MA, FALSE); + tag_main_idcode(bmain, ID_LA, FALSE); + /* BKE_object_handle_update() on all objects, groups and sets */ scene_update_tagged_recursive(bmain, sce, sce); @@ -1182,7 +1222,7 @@ int BKE_scene_remove_render_layer(Main *bmain, Scene *scene, SceneRenderLayer *s int get_render_subsurf_level(RenderData *r, int lvl) { if (r->mode & R_SIMPLIFY) - return MIN2(r->simplify_subsurf, lvl); + return min_ii(r->simplify_subsurf, lvl); else return lvl; } @@ -1198,7 +1238,7 @@ int get_render_child_particle_number(RenderData *r, int num) int get_render_shadow_samples(RenderData *r, int samples) { if ((r->mode & R_SIMPLIFY) && samples > 0) - return MIN2(r->simplify_shadowsamples, samples); + return min_ii(r->simplify_shadowsamples, samples); else return samples; } diff --git a/source/blender/blenkernel/intern/seqeffects.c b/source/blender/blenkernel/intern/seqeffects.c index 33519483843..469881020c1 100644 --- a/source/blender/blenkernel/intern/seqeffects.c +++ b/source/blender/blenkernel/intern/seqeffects.c @@ -62,14 +62,14 @@ static void slice_get_byte_buffers(const SeqRenderData *context, const ImBuf *ib { int offset = 4 * start_line * context->rectx; - *rect1 = (unsigned char*) ibuf1->rect + offset; - *rect_out = (unsigned char*) out->rect + offset; + *rect1 = (unsigned char *)ibuf1->rect + offset; + *rect_out = (unsigned char *)out->rect + offset; if (ibuf2) - *rect2 = (unsigned char*) ibuf2->rect + offset; + *rect2 = (unsigned char *)ibuf2->rect + offset; if (ibuf3) - *rect3 = (unsigned char*) ibuf3->rect + offset; + *rect3 = (unsigned char *)ibuf3->rect + offset; } static void slice_get_float_buffers(const SeqRenderData *context, const ImBuf *ibuf1, const ImBuf *ibuf2, @@ -600,7 +600,7 @@ static void makeGammaTables(float gamma) color_step = 1.0f / RE_GAMMA_TABLE_SIZE; inv_color_step = (float) RE_GAMMA_TABLE_SIZE; - /* We could squeeze out the two range tables to gain some memory */ + /* We could squeeze out the two range tables to gain some memory */ for (i = 0; i < RE_GAMMA_TABLE_SIZE; i++) { color_domain_table[i] = i * color_step; gamma_range_table[i] = pow(color_domain_table[i], valid_gamma); @@ -1178,7 +1178,7 @@ static void do_mul_effect_float(float facf0, float facf1, int x, int y, float *r fac3 = facf1; /* formula: - * fac*(a*b) + (1-fac)*a => fac*a*(b-1)+a + * fac * (a * b) + (1 - fac) * a => fac * a * (b - 1) + a */ while (y--) { @@ -1353,7 +1353,7 @@ static float check_zone(WipeZone *wipezone, int x, int y, Sequence *seq, float f hyp2 = fabsf(angle * x + y + (-(yo - posy * 0.5f) - angle * (xo - posx * 0.5f))) * wipezone->pythangle; } - hwidth = minf(hwidth, fabsf(b3 - b1) / 2.0f); + hwidth = min_ff(hwidth, fabsf(b3 - b1) / 2.0f); if (b2 < b1 && b2 < b3) { output = in_band(hwidth, hyp, 0, 1); @@ -2373,7 +2373,7 @@ static ImBuf *do_solid_color(SeqRenderData context, Sequence *seq, float UNUSED( rect[1] = col1[1]; rect[2] = col1[2]; rect[3] = 255; - } + } } } @@ -2609,7 +2609,7 @@ static void store_icu_yrange_speed(Sequence *seq, short UNUSED(adrcode), float * *ymin = 0.0; *ymax = seq->len; } - } + } } void BKE_sequence_effect_speed_rebuild_map(Scene *scene, Sequence *seq, int force) diff --git a/source/blender/blenkernel/intern/seqmodifier.c b/source/blender/blenkernel/intern/seqmodifier.c index b0dcad64722..609724e802f 100644 --- a/source/blender/blenkernel/intern/seqmodifier.c +++ b/source/blender/blenkernel/intern/seqmodifier.c @@ -349,9 +349,9 @@ static void hue_correct_apply_threaded(int width, int height, unsigned char *rec hsv_to_rgb(hsv[0], hsv[1], hsv[2], result, result + 1, result + 2); if (mask_rect_float) - copy_v3_v3(mask, mask_rect_float + pixel_index); + copy_v3_v3(mask, mask_rect_float + pixel_index); else if (mask_rect) - rgb_uchar_to_float(mask, mask_rect + pixel_index); + 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]; diff --git a/source/blender/blenkernel/intern/sequencer.c b/source/blender/blenkernel/intern/sequencer.c index 90c3347a1df..a947a48938e 100644 --- a/source/blender/blenkernel/intern/sequencer.c +++ b/source/blender/blenkernel/intern/sequencer.c @@ -53,6 +53,8 @@ #include "BLI_threads.h" #include "BLI_utildefines.h" +#include "BLF_translation.h" + #include "BKE_animsys.h" #include "BKE_global.h" #include "BKE_image.h" @@ -507,8 +509,8 @@ static void seq_update_sound_bounds_recursive_rec(Scene *scene, Sequence *metase * since sound is played outside of evaluating the imbufs, */ for (seq = metaseq->seqbase.first; seq; seq = seq->next) { if (seq->type == SEQ_TYPE_META) { - seq_update_sound_bounds_recursive_rec(scene, seq, maxi(start, metaseq_start(seq)), - mini(end, metaseq_end(seq))); + seq_update_sound_bounds_recursive_rec(scene, seq, max_ii(start, metaseq_start(seq)), + min_ii(end, metaseq_end(seq))); } else if (ELEM(seq->type, SEQ_TYPE_SOUND_RAM, SEQ_TYPE_SCENE)) { if (seq->scene_sound) { @@ -674,8 +676,8 @@ void BKE_sequence_reload_new_file(Scene *scene, Sequence *seq, int lock_range) if (seq->anim) IMB_free_anim(seq->anim); - /* OCIO_TODO: support configurable input space for strips */ - seq->anim = openanim(str, IB_rect | ((seq->flag & SEQ_FILTERY) ? IB_animdeinterlace : 0), seq->streamindex, NULL); + seq->anim = openanim(str, IB_rect | ((seq->flag & SEQ_FILTERY) ? IB_animdeinterlace : 0), + seq->streamindex, seq->strip->colorspace_settings.name); if (!seq->anim) { return; @@ -717,7 +719,7 @@ void BKE_sequence_reload_new_file(Scene *scene, Sequence *seq, int lock_range) #ifdef WITH_AUDASPACE if (!seq->sound) return; - seq->len = ceil(AUD_getInfo(seq->sound->playback_handle).length * FPS); + seq->len = ceil((double)AUD_getInfo(seq->sound->playback_handle).length * FPS); seq->len -= seq->anim_startofs; seq->len -= seq->anim_endofs; if (seq->len < 0) { @@ -991,7 +993,7 @@ static float give_stripelem_index(Sequence *seq, float cfra) if (seq->type & SEQ_TYPE_EFFECT) { end = seq->enddisp; - } + } if (end < sta) { return -1; @@ -1172,8 +1174,8 @@ static void seq_open_anim_file(Sequence *seq) seq->strip->dir, seq->strip->stripdata->name); BLI_path_abs(name, G.main->name); - /* OCIO_TODO: support configurable input space for strips */ - seq->anim = openanim(name, IB_rect | ((seq->flag & SEQ_FILTERY) ? IB_animdeinterlace : 0), seq->streamindex, NULL); + seq->anim = openanim(name, IB_rect | ((seq->flag & SEQ_FILTERY) ? IB_animdeinterlace : 0), + seq->streamindex, seq->strip->colorspace_settings.name); if (seq->anim == NULL) { return; @@ -1299,7 +1301,6 @@ static ImBuf *seq_proxy_fetch(SeqRenderData context, Sequence *seq, int cfra) } if (BLI_exists(name)) { - /* OCIO_TODO: support configurable spaces for strips */ ImBuf *ibuf = IMB_loadiffname(name, IB_rect, NULL); if (ibuf) @@ -1344,7 +1345,6 @@ static void seq_proxy_build_frame(SeqRenderData context, Sequence *seq, int cfra BLI_make_existing_file(name); - /* OCIO_TODO: support per-strip color space settings */ ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat); if (ok == 0) { perror(name); @@ -1882,7 +1882,7 @@ static ImBuf *input_preprocess(SeqRenderData context, Sequence *seq, float cfra, ibuf = i; } - } + } if (seq->flag & SEQ_FLIPX) { IMB_flipx(ibuf); @@ -1965,17 +1965,20 @@ static ImBuf *copy_from_ibuf_still(SeqRenderData context, Sequence *seq, float n static void copy_to_ibuf_still(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... */ ibuf = IMB_dupImBuf(ibuf); - sequencer_imbuf_assign_spaces(context.scene, ibuf); + if (ibuf) { + 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); @@ -2334,11 +2337,14 @@ static ImBuf *seq_render_scene_strip(SeqRenderData context, Sequence *seq, float * -jahka */ - int rendering = G.is_rendering; - int doseq; - int doseq_gl = G.is_rendering ? /*(scene->r.seq_flag & R_SEQ_GL_REND)*/ 0 : /*(scene->r.seq_flag & R_SEQ_GL_PREV)*/ 1; + const short is_rendering = G.is_rendering; + const int do_seq_gl = G.is_rendering ? + 0 /* (context.scene->r.seq_flag & R_SEQ_GL_REND) */ : + (context.scene->r.seq_flag & R_SEQ_GL_PREV); + int do_seq; int have_seq = FALSE; Scene *scene; + int is_thread_main = BLI_thread_is_main(); /* don't refer to seq->scene above this point!, it can be NULL */ if (seq->scene == NULL) { @@ -2353,9 +2359,10 @@ static ImBuf *seq_render_scene_strip(SeqRenderData context, Sequence *seq, float oldcfra = scene->r.cfra; scene->r.cfra = frame; - if (seq->scene_camera) + if (seq->scene_camera) { camera = seq->scene_camera; - else { + } + else { BKE_scene_camera_switch_update(scene); camera = scene->camera; } @@ -2366,8 +2373,8 @@ static ImBuf *seq_render_scene_strip(SeqRenderData context, Sequence *seq, float } /* prevent eternal loop */ - doseq = context.scene->r.scemode & R_DOSEQ; - context.scene->r.scemode &= ~R_DOSEQ; + do_seq = context.scene->r.scemode & R_DOSEQ; + scene->r.scemode &= ~R_DOSEQ; #ifdef DURIAN_CAMERA_SWITCH /* stooping to new low's in hackyness :( */ @@ -2376,8 +2383,9 @@ static ImBuf *seq_render_scene_strip(SeqRenderData context, Sequence *seq, float #else (void)oldmarkers; #endif - - if (sequencer_view3d_cb && BLI_thread_is_main() && doseq_gl && (scene == context.scene || have_seq == 0) && camera) { + + if ((sequencer_view3d_cb && do_seq_gl && camera) && is_thread_main) + { char err_out[256] = "unknown"; /* for old scened this can be uninitialized, * should probably be added to do_versions at some point if the functionality stays */ @@ -2396,15 +2404,19 @@ static ImBuf *seq_render_scene_strip(SeqRenderData context, Sequence *seq, float Render *re = RE_GetRender(scene->id.name); RenderResult rres; - /* XXX: this if can be removed when sequence preview rendering uses the job system */ - if (rendering || context.scene != scene) { + /* XXX: this if can be removed when sequence preview rendering uses the job system + * + * disable rendered preview for sequencer while rendering -- it's very much possible + * that preview render will went into conflict with final render + */ + if (!is_thread_main || is_rendering == FALSE) { if (re == NULL) re = RE_NewRender(scene->id.name); RE_BlenderFrame(re, context.bmain, scene, NULL, camera, scene->lay, frame, FALSE); /* restore previous state after it was toggled on & off by RE_BlenderFrame */ - G.is_rendering = rendering; + G.is_rendering = is_rendering; } RE_AcquireResultImage(re, &rres); @@ -2431,7 +2443,7 @@ static ImBuf *seq_render_scene_strip(SeqRenderData context, Sequence *seq, float } /* restore */ - context.scene->r.scemode |= doseq; + scene->r.scemode |= do_seq; scene->r.cfra = oldcfra; @@ -2518,8 +2530,7 @@ static ImBuf *do_render_strip_uncached(SeqRenderData context, Sequence *seq, flo BLI_path_abs(name, G.main->name); } - /* OCIO_TODO: support configurable space for image strips */ - if (s_elem && (ibuf = IMB_loadiffname(name, IB_rect, NULL))) { + if (s_elem && (ibuf = IMB_loadiffname(name, IB_rect, seq->strip->colorspace_settings.name))) { /* we don't need both (speed reasons)! */ if (ibuf->rect_float && ibuf->rect) imb_freerectImBuf(ibuf); @@ -2822,7 +2833,7 @@ ImBuf *BKE_sequencer_give_ibuf(SeqRenderData context, float cfra, int chanshown) count = BLI_countlist(&ed->metastack); if ((chanshown < 0) && (count > 0)) { - count = MAX2(count + chanshown, 0); + count = max_ii(count + chanshown, 0); seqbasep = ((MetaStack *)BLI_findlink(&ed->metastack, count))->oldbasep; } else { @@ -3191,7 +3202,7 @@ int BKE_sequence_tx_get_final_left(Sequence *seq, int metaclip) { if (metaclip && seq->tmp) { /* return the range clipped by the parents range */ - return maxi(BKE_sequence_tx_get_final_left(seq, 0), BKE_sequence_tx_get_final_left((Sequence *)seq->tmp, TRUE)); + return max_ii(BKE_sequence_tx_get_final_left(seq, 0), BKE_sequence_tx_get_final_left((Sequence *)seq->tmp, TRUE)); } else { return (seq->start - seq->startstill) + seq->startofs; @@ -3202,7 +3213,7 @@ int BKE_sequence_tx_get_final_right(Sequence *seq, int metaclip) { if (metaclip && seq->tmp) { /* return the range clipped by the parents range */ - return mini(BKE_sequence_tx_get_final_right(seq, 0), BKE_sequence_tx_get_final_right((Sequence *)seq->tmp, TRUE)); + return min_ii(BKE_sequence_tx_get_final_right(seq, 0), BKE_sequence_tx_get_final_right((Sequence *)seq->tmp, TRUE)); } else { return ((seq->start + seq->len) + seq->endstill) - seq->endofs; @@ -3454,7 +3465,7 @@ int BKE_sequence_base_shuffle(ListBase *seqbasep, Sequence *test, Scene *evil_sc for (seq = seqbasep->first; seq; seq = seq->next) { if (seq->machine == orig_machine) - new_frame = MAX2(new_frame, seq->enddisp); + new_frame = max_ii(new_frame, seq->enddisp); } test->machine = orig_machine; @@ -3479,10 +3490,10 @@ static int shuffle_seq_time_offset_test(ListBase *seqbasep, char dir) for (seq_other = seqbasep->first; seq_other; seq_other = seq_other->next) { if (!seq_other->tmp && seq_overlap(seq, seq_other)) { if (dir == 'L') { - offset = MIN2(offset, seq_other->startdisp - seq->enddisp); + offset = min_ii(offset, seq_other->startdisp - seq->enddisp); } else { - offset = MAX2(offset, seq_other->enddisp - seq->startdisp); + offset = max_ii(offset, seq_other->enddisp - seq->startdisp); } } } @@ -3667,26 +3678,26 @@ int BKE_sequence_swap(Sequence *seq_a, Sequence *seq_b, const char **error_str) char name[sizeof(seq_a->name)]; if (seq_a->len != seq_b->len) { - *error_str = "Strips must be the same length"; + *error_str = N_("Strips must be the same length"); return 0; } - /* type checking, could be more advanced but disalow sound vs non-sound copy */ + /* type checking, could be more advanced but disallow sound vs non-sound copy */ if (seq_a->type != seq_b->type) { if (seq_a->type == SEQ_TYPE_SOUND_RAM || seq_b->type == SEQ_TYPE_SOUND_RAM) { - *error_str = "Strips were not compatible"; + *error_str = N_("Strips were not compatible"); return 0; } /* disallow effects to swap with non-effects strips */ if ((seq_a->type & SEQ_TYPE_EFFECT) != (seq_b->type & SEQ_TYPE_EFFECT)) { - *error_str = "Strips were not compatible"; + *error_str = N_("Strips were not compatible"); return 0; } if ((seq_a->type & SEQ_TYPE_EFFECT) && (seq_b->type & SEQ_TYPE_EFFECT)) { if (BKE_sequence_effect_get_num_inputs(seq_a->type) != BKE_sequence_effect_get_num_inputs(seq_b->type)) { - *error_str = "Strips must have the same number of inputs"; + *error_str = N_("Strips must have the same number of inputs"); return 0; } } @@ -3929,6 +3940,25 @@ Sequence *BKE_sequence_alloc(ListBase *lb, int cfra, int machine) return seq; } +void BKE_sequence_init_colorspace(Sequence *seq) +{ + if (seq->strip && seq->strip->stripdata) { + char name[FILE_MAX]; + ImBuf *ibuf; + + BLI_join_dirfile(name, sizeof(name), seq->strip->dir, seq->strip->stripdata->name); + BLI_path_abs(name, G.main->name); + + /* initialize input color space */ + if (seq->type == SEQ_TYPE_IMAGE) { + ibuf = IMB_loadiffname(name, IB_rect, seq->strip->colorspace_settings.name); + + if (ibuf) + IMB_freeImBuf(ibuf); + } + } +} + /* NOTE: this function doesn't fill in image names */ Sequence *BKE_sequencer_add_image_strip(bContext *C, ListBase *seqbasep, SeqLoadInfo *seq_load) { @@ -3998,7 +4028,7 @@ Sequence *BKE_sequencer_add_sound_strip(bContext *C, ListBase *seqbasep, SeqLoad /* basic defaults */ seq->strip = strip = MEM_callocN(sizeof(Strip), "strip"); - seq->len = ceil(info.length * FPS); + seq->len = (int)ceil((double)info.length * FPS); strip->us = 1; /* we only need 1 element to store the filename */ @@ -4035,14 +4065,14 @@ Sequence *BKE_sequencer_add_movie_strip(bContext *C, ListBase *seqbasep, SeqLoad Sequence *seq; /* generic strip vars */ Strip *strip; StripElem *se; + char colorspace[64] = "\0"; /* MAX_COLORSPACE_NAME */ struct anim *an; BLI_strncpy(path, seq_load->path, sizeof(path)); BLI_path_abs(path, G.main->name); - /* OCIO_TODO: support configurable input space for strips */ - an = openanim(path, IB_rect, 0, NULL); + an = openanim(path, IB_rect, 0, colorspace); if (an == NULL) return NULL; @@ -4061,6 +4091,8 @@ Sequence *BKE_sequencer_add_movie_strip(bContext *C, ListBase *seqbasep, SeqLoad seq->len = IMB_anim_get_duration(an, IMB_TC_RECORD_RUN); strip->us = 1; + BLI_strncpy(seq->strip->colorspace_settings.name, colorspace, sizeof(seq->strip->colorspace_settings.name)); + /* we only need 1 element for MOVIE strips */ strip->stripdata = se = MEM_callocN(sizeof(StripElem), "stripelem"); diff --git a/source/blender/blenkernel/intern/shrinkwrap.c b/source/blender/blenkernel/intern/shrinkwrap.c index 9a8bcaabe0c..72db34d339c 100644 --- a/source/blender/blenkernel/intern/shrinkwrap.c +++ b/source/blender/blenkernel/intern/shrinkwrap.c @@ -56,35 +56,18 @@ #include "BKE_mesh.h" #include "BKE_tessmesh.h" -/* Util macros */ -#define OUT_OF_MEMORY() ((void)printf("Shrinkwrap: Out of memory\n")) - -/* Benchmark macros */ -#if !defined(_WIN32) && 0 - -#include <sys/time.h> - -#define BENCH(a) \ - do { \ - double _t1, _t2; \ - struct timeval _tstart, _tend; \ - clock_t _clock_init = clock(); \ - gettimeofday ( &_tstart, NULL); \ - (a); \ - gettimeofday ( &_tend, NULL); \ - _t1 = ( double ) _tstart.tv_sec + ( double ) _tstart.tv_usec/ ( 1000*1000 ); \ - _t2 = ( double ) _tend.tv_sec + ( double ) _tend.tv_usec/ ( 1000*1000 ); \ - printf("%s: %fs (real) %fs (cpu)\n", #a, _t2-_t1, (float)(clock()-_clock_init)/CLOCKS_PER_SEC);\ - } while (0) - +/* for timing... */ +#if 0 +# include "PIL_time.h" #else - -#define BENCH(a) (a) - +# define TIMEIT_BENCH(expr, id) (expr) #endif +/* Util macros */ +#define OUT_OF_MEMORY() ((void)printf("Shrinkwrap: Out of memory\n")) + /* get derived mesh */ -//TODO is anyfunction that does this? returning the derivedFinal without we caring if its in edit mode or not? +/* TODO is anyfunction that does this? returning the derivedFinal without we caring if its in edit mode or not? */ DerivedMesh *object_get_derived_final(Object *ob) { Mesh *me = ob->data; @@ -143,13 +126,13 @@ static void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *calc) BVHTreeNearest nearest = NULL_BVHTreeNearest; - BENCH(bvhtree_from_mesh_verts(&treeData, calc->target, 0.0, 2, 6)); + TIMEIT_BENCH(bvhtree_from_mesh_verts(&treeData, calc->target, 0.0, 2, 6), bvhtree_verts); if (treeData.tree == NULL) { OUT_OF_MEMORY(); return; } - //Setup nearest + /* Setup nearest */ nearest.index = -1; nearest.dist = FLT_MAX; #ifndef __APPLE__ @@ -159,10 +142,12 @@ static void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *calc) float *co = calc->vertexCos[i]; float tmp_co[3]; float weight = defvert_array_find_weight_safe(calc->dvert, i, calc->vgroup); - if (weight == 0.0f) continue; + if (weight == 0.0f) { + continue; + } - //Convert the vertex to tree coordinates + /* Convert the vertex to tree coordinates */ if (calc->vert) { copy_v3_v3(tmp_co, calc->vert[i].co); } @@ -171,11 +156,11 @@ static void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *calc) } space_transform_apply(&calc->local2target, tmp_co); - //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. - //This will lead in prunning of the search tree. + /* 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. + * This will lead in prunning of the search tree. */ if (nearest.index != -1) nearest.dist = len_squared_v3v3(tmp_co, nearest.co); else @@ -184,23 +169,27 @@ static void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *calc) BLI_bvhtree_find_nearest(treeData.tree, tmp_co, &nearest, treeData.nearest_callback, &treeData); - //Found the nearest vertex + /* Found the nearest vertex */ if (nearest.index != -1) { - //Adjusting the vertex weight, so that after interpolating it keeps a certain distance from the nearest position - float dist = sasqrt(nearest.dist); - if (dist > FLT_EPSILON) weight *= (dist - calc->keepDist) / dist; + /* Adjusting the vertex weight, + * so that after interpolating it keeps a certain distance from the nearest position */ + if (nearest.dist > FLT_EPSILON) { + const float dist = sqrtf(nearest.dist); + weight *= (dist - calc->keepDist) / dist; + } - //Convert the coordinates back to mesh coordinates + /* Convert the coordinates back to mesh coordinates */ copy_v3_v3(tmp_co, nearest.co); space_transform_invert(&calc->local2target, tmp_co); - interp_v3_v3v3(co, co, tmp_co, weight); //linear interpolation + interp_v3_v3v3(co, co, tmp_co, weight); /* linear interpolation */ } } free_bvhtree_from_mesh(&treeData); } + /* * This function raycast a single vertex and updates the hit if the "hit" is considered valid. * Returns TRUE if "hit" was updated. @@ -209,16 +198,24 @@ static void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *calc) * MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE (front faces hits are ignored) * MOD_SHRINKWRAP_CULL_TARGET_BACKFACE (back faces hits are ignored) */ -int normal_projection_project_vertex(char options, const float vert[3], const float dir[3], const SpaceTransform *transf, BVHTree *tree, BVHTreeRayHit *hit, BVHTree_RayCastCallback callback, void *userdata) +int normal_projection_project_vertex(char options, const float vert[3], const float dir[3], + const SpaceTransform *transf, + BVHTree *tree, BVHTreeRayHit *hit, + BVHTree_RayCastCallback callback, void *userdata) { + /* don't use this because this dist value could be incompatible + * this value used by the callback for comparing prev/new dist values. + * also, at the moment there is no need to have a corrected 'dist' value */ +// #define USE_DIST_CORRECT + float tmp_co[3], tmp_no[3]; const float *co, *no; BVHTreeRayHit hit_tmp; - //Copy from hit (we need to convert hit rays from one space coordinates to the other + /* Copy from hit (we need to convert hit rays from one space coordinates to the other */ memcpy(&hit_tmp, hit, sizeof(hit_tmp)); - //Apply space transform (TODO readjust dist) + /* Apply space transform (TODO readjust dist) */ if (transf) { copy_v3_v3(tmp_co, vert); space_transform_apply(transf, tmp_co); @@ -228,7 +225,9 @@ int normal_projection_project_vertex(char options, const float vert[3], const fl space_transform_apply_normal(transf, tmp_no); no = tmp_no; +#ifdef USE_DIST_CORRECT hit_tmp.dist *= mat4_to_scale(((SpaceTransform *)transf)->local2target); +#endif } else { co = vert; @@ -249,7 +248,7 @@ int normal_projection_project_vertex(char options, const float vert[3], const fl /* apply backface */ const float dot = dot_v3v3(dir, hit_tmp.no); if (((options & MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE) && dot <= 0.0f) || - ((options & MOD_SHRINKWRAP_CULL_TARGET_BACKFACE) && dot >= 0.0f)) + ((options & MOD_SHRINKWRAP_CULL_TARGET_BACKFACE) && dot >= 0.0f)) { return FALSE; /* Ignore hit */ } @@ -258,9 +257,13 @@ int normal_projection_project_vertex(char options, const float vert[3], const fl if (transf) { /* Inverting space transform (TODO make coeherent with the initial dist readjust) */ space_transform_invert(transf, hit_tmp.co); - hit_tmp.dist = len_v3v3((float *)vert, hit_tmp.co); +#ifdef USE_DIST_CORRECT + hit_tmp.dist = len_v3v3(vert, hit_tmp.co); +#endif } + BLI_assert(hit_tmp.dist <= hit->dist); + memcpy(hit, &hit_tmp, sizeof(hit_tmp)); return TRUE; } @@ -272,41 +275,47 @@ static void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *calc) { int i; - //Options about projection direction + /* Options about projection direction */ const char use_normal = calc->smd->shrinkOpts; + const float proj_limit_squared = calc->smd->projLimit * calc->smd->projLimit; float proj_axis[3] = {0.0f, 0.0f, 0.0f}; - //Raycast and tree stuff + /* Raycast and tree stuff */ + + /** \note 'hit.dist' is kept in the targets space, this is only used + * for finding the best hit, to get the real dist, + * measure the len_v3v3() from the input coord to hit.co */ BVHTreeRayHit hit; BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh; - //auxiliary target + /* auxiliary target */ DerivedMesh *auxMesh = NULL; BVHTreeFromMesh auxData = NULL_BVHTreeFromMesh; SpaceTransform local2aux; - //If the user doesn't allows to project in any direction of projection axis - //then theres nothing todo. + /* If the user doesn't allows to project in any direction of projection axis + * then theres nothing todo. */ if ((use_normal & (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 + /* 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) 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 + /* 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) proj_axis[0] = 1.0f; 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) proj_axis[2] = 1.0f; normalize_v3(proj_axis); - //Invalid projection direction - if (dot_v3v3(proj_axis, proj_axis) < FLT_EPSILON) - return; + /* Invalid projection direction */ + if (len_squared_v3(proj_axis) < FLT_EPSILON) { + return; + } } if (calc->smd->auxTarget) { @@ -316,7 +325,7 @@ static void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *calc) SPACE_TRANSFORM_SETUP(&local2aux, calc->ob, calc->smd->auxTarget); } - //After sucessufuly build the trees, start projection vertexs + /* After sucessufuly build the trees, start projection vertexs */ if (bvhtree_from_mesh_faces(&treeData, calc->target, 0.0, 4, 6) && (auxMesh == NULL || bvhtree_from_mesh_faces(&auxData, auxMesh, 0.0, 4, 6))) { @@ -327,9 +336,11 @@ static void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *calc) for (i = 0; i < calc->numVerts; ++i) { float *co = calc->vertexCos[i]; float tmp_co[3], tmp_no[3]; - float weight = defvert_array_find_weight_safe(calc->dvert, i, calc->vgroup); + const float weight = defvert_array_find_weight_safe(calc->dvert, i, calc->vgroup); - if (weight == 0.0f) continue; + if (weight == 0.0f) { + continue; + } if (calc->vert) { /* calc->vert contains verts from derivedMesh */ @@ -351,28 +362,45 @@ static void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *calc) hit.index = -1; - hit.dist = 10000.0f; //TODO: we should use FLT_MAX here, but sweepsphere code isn't prepared for that + hit.dist = 10000.0f; /* TODO: we should use FLT_MAX here, but sweepsphere code isn't prepared for that */ - //Project over positive direction of axis + /* Project over positive direction of axis */ if (use_normal & MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR) { - if (auxData.tree) - normal_projection_project_vertex(0, tmp_co, tmp_no, &local2aux, auxData.tree, &hit, auxData.raycast_callback, &auxData); + if (auxData.tree) { + normal_projection_project_vertex(0, tmp_co, tmp_no, + &local2aux, auxData.tree, &hit, + auxData.raycast_callback, &auxData); + } - normal_projection_project_vertex(calc->smd->shrinkOpts, tmp_co, tmp_no, &calc->local2target, treeData.tree, &hit, treeData.raycast_callback, &treeData); + normal_projection_project_vertex(calc->smd->shrinkOpts, tmp_co, tmp_no, + &calc->local2target, treeData.tree, &hit, + treeData.raycast_callback, &treeData); } - //Project over negative direction of axis - if (use_normal & MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR && hit.index == -1) { + /* Project over negative direction of axis */ + if (use_normal & MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR) { float inv_no[3]; negate_v3_v3(inv_no, tmp_no); - if (auxData.tree) - normal_projection_project_vertex(0, tmp_co, inv_no, &local2aux, auxData.tree, &hit, auxData.raycast_callback, &auxData); + if (auxData.tree) { + normal_projection_project_vertex(0, tmp_co, inv_no, + &local2aux, auxData.tree, &hit, + auxData.raycast_callback, &auxData); + } - normal_projection_project_vertex(calc->smd->shrinkOpts, tmp_co, inv_no, &calc->local2target, treeData.tree, &hit, treeData.raycast_callback, &treeData); + normal_projection_project_vertex(calc->smd->shrinkOpts, tmp_co, inv_no, + &calc->local2target, treeData.tree, &hit, + treeData.raycast_callback, &treeData); } + /* don't set the initial dist (which is more efficient), + * because its calculated in the targets space, we want the dist in our own space */ + if (proj_limit_squared != 0.0f) { + if (len_squared_v3v3(hit.co, co) > proj_limit_squared) { + hit.index = -1; + } + } if (hit.index != -1) { madd_v3_v3v3fl(hit.co, hit.co, tmp_no, calc->keepDist); @@ -381,7 +409,7 @@ static void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *calc) } } - //free data structures + /* free data structures */ free_bvhtree_from_mesh(&treeData); free_bvhtree_from_mesh(&auxData); } @@ -399,19 +427,19 @@ static void shrinkwrap_calc_nearest_surface_point(ShrinkwrapCalcData *calc) BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh; BVHTreeNearest nearest = NULL_BVHTreeNearest; - //Create a bvh-tree of the given target - BENCH(bvhtree_from_mesh_faces(&treeData, calc->target, 0.0, 2, 6)); + /* Create a bvh-tree of the given target */ + TIMEIT_BENCH(bvhtree_from_mesh_faces(&treeData, calc->target, 0.0, 2, 6), bvhtree_faces); if (treeData.tree == NULL) { OUT_OF_MEMORY(); return; } - //Setup nearest + /* Setup nearest */ nearest.index = -1; nearest.dist = FLT_MAX; - //Find the nearest vertex + /* Find the nearest vertex */ #ifndef __APPLE__ #pragma omp parallel for default(none) private(i) firstprivate(nearest) shared(calc,treeData) schedule(static) #endif @@ -421,7 +449,7 @@ static void shrinkwrap_calc_nearest_surface_point(ShrinkwrapCalcData *calc) float weight = defvert_array_find_weight_safe(calc->dvert, i, calc->vgroup); if (weight == 0.0f) continue; - //Convert the vertex to tree coordinates + /* Convert the vertex to tree coordinates */ if (calc->vert) { copy_v3_v3(tmp_co, calc->vert[i].co); } @@ -430,11 +458,11 @@ static void shrinkwrap_calc_nearest_surface_point(ShrinkwrapCalcData *calc) } space_transform_apply(&calc->local2target, tmp_co); - //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. - //This will lead in prunning of the search tree. + /* 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. + * This will lead in prunning of the search tree. */ if (nearest.index != -1) nearest.dist = len_squared_v3v3(tmp_co, nearest.co); else @@ -442,24 +470,28 @@ static void shrinkwrap_calc_nearest_surface_point(ShrinkwrapCalcData *calc) BLI_bvhtree_find_nearest(treeData.tree, tmp_co, &nearest, treeData.nearest_callback, &treeData); - //Found the nearest vertex + /* Found the nearest vertex */ if (nearest.index != -1) { if (calc->smd->shrinkOpts & MOD_SHRINKWRAP_KEEP_ABOVE_SURFACE) { - //Make the vertex stay on the front side of the face + /* Make the vertex stay on the front side of the face */ madd_v3_v3v3fl(tmp_co, nearest.co, nearest.no, calc->keepDist); } else { - //Adjusting the vertex weight, so that after interpolating it keeps a certain distance from the nearest position + /* Adjusting the vertex weight, + * so that after interpolating it keeps a certain distance from the nearest position */ float dist = sasqrt(nearest.dist); - if (dist > FLT_EPSILON) - interp_v3_v3v3(tmp_co, tmp_co, nearest.co, (dist - calc->keepDist) / dist); //linear interpolation - else + if (dist > FLT_EPSILON) { + /* linear interpolation */ + interp_v3_v3v3(tmp_co, tmp_co, nearest.co, (dist - calc->keepDist) / dist); + } + else { copy_v3_v3(tmp_co, nearest.co); + } } - //Convert the coordinates back to mesh coordinates + /* Convert the coordinates back to mesh coordinates */ space_transform_invert(&calc->local2target, tmp_co); - interp_v3_v3v3(co, co, tmp_co, weight); //linear interpolation + interp_v3_v3v3(co, co, tmp_co, weight); /* linear interpolation */ } } @@ -467,24 +499,25 @@ static void shrinkwrap_calc_nearest_surface_point(ShrinkwrapCalcData *calc) } /* Main shrinkwrap function */ -void shrinkwrapModifier_deform(ShrinkwrapModifierData *smd, Object *ob, DerivedMesh *dm, float (*vertexCos)[3], int numVerts) +void shrinkwrapModifier_deform(ShrinkwrapModifierData *smd, Object *ob, DerivedMesh *dm, + float (*vertexCos)[3], int numVerts) { DerivedMesh *ss_mesh = NULL; ShrinkwrapCalcData calc = NULL_ShrinkwrapCalcData; - //remove loop dependencies on derived meshs (TODO should this be done elsewhere?) + /* remove loop dependencies on derived meshs (TODO should this be done elsewhere?) */ if (smd->target == ob) smd->target = NULL; if (smd->auxTarget == ob) smd->auxTarget = NULL; - //Configure Shrinkwrap calc data + /* Configure Shrinkwrap calc data */ calc.smd = smd; calc.ob = ob; calc.numVerts = numVerts; calc.vertexCos = vertexCos; - //DeformVertex + /* DeformVertex */ calc.vgroup = defgroup_name_index(calc.ob, calc.smd->vgroup_name); if (dm) { calc.dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT); @@ -497,12 +530,12 @@ void shrinkwrapModifier_deform(ShrinkwrapModifierData *smd, Object *ob, DerivedM if (smd->target) { calc.target = object_get_derived_final(smd->target); - //TODO there might be several "bugs" on non-uniform scales matrixs - //because it will no longer be nearest surface, not sphere projection - //because space has been deformed + /* TODO there might be several "bugs" on non-uniform scales matrixs + * because it will no longer be nearest surface, not sphere projection + * because space has been deformed */ SPACE_TRANSFORM_SETUP(&calc.local2target, ob, smd->target); - //TODO: smd->keepDist is in global units.. must change to local + /* TODO: smd->keepDist is in global units.. must change to local */ calc.keepDist = smd->keepDist; } @@ -511,15 +544,15 @@ void shrinkwrapModifier_deform(ShrinkwrapModifierData *smd, Object *ob, DerivedM calc.vgroup = defgroup_name_index(calc.ob, smd->vgroup_name); if (dm != NULL && smd->shrinkType == MOD_SHRINKWRAP_PROJECT) { - //Setup arrays to get vertexs positions, normals and deform weights + /* Setup arrays to get vertexs positions, normals and deform weights */ calc.vert = dm->getVertDataArray(dm, CD_MVERT); calc.dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT); - //Using vertexs positions/normals as if a subsurface was applied + /* Using vertexs positions/normals as if a subsurface was applied */ if (smd->subsurfLevels) { SubsurfModifierData ssmd = {{NULL}}; - ssmd.subdivType = ME_CC_SUBSURF; //catmull clark - ssmd.levels = smd->subsurfLevels; //levels + ssmd.subdivType = ME_CC_SUBSURF; /* catmull clark */ + ssmd.levels = smd->subsurfLevels; /* levels */ ss_mesh = subsurf_make_derived_from_derived(dm, &ssmd, NULL, (ob->mode & OB_MODE_EDIT) ? SUBSURF_IN_EDIT_MODE : 0); @@ -532,31 +565,30 @@ void shrinkwrapModifier_deform(ShrinkwrapModifierData *smd, Object *ob, DerivedM } } - //Just to make sure we are not leaving any memory behind + /* Just to make sure we are not leaving any memory behind */ assert(ssmd.emCache == NULL); assert(ssmd.mCache == NULL); } } - //Projecting target defined - lets work! + /* Projecting target defined - lets work! */ if (calc.target) { switch (smd->shrinkType) { case MOD_SHRINKWRAP_NEAREST_SURFACE: - BENCH(shrinkwrap_calc_nearest_surface_point(&calc)); + TIMEIT_BENCH(shrinkwrap_calc_nearest_surface_point(&calc), deform_surface); break; case MOD_SHRINKWRAP_PROJECT: - BENCH(shrinkwrap_calc_normal_projection(&calc)); + TIMEIT_BENCH(shrinkwrap_calc_normal_projection(&calc), deform_project); break; case MOD_SHRINKWRAP_NEAREST_VERTEX: - BENCH(shrinkwrap_calc_nearest_vertex(&calc)); + TIMEIT_BENCH(shrinkwrap_calc_nearest_vertex(&calc), deform_vertex); break; } } - //free memory + /* free memory */ 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 1909e65d0ab..0c440c6f968 100644 --- a/source/blender/blenkernel/intern/smoke.c +++ b/source/blender/blenkernel/intern/smoke.c @@ -49,18 +49,7 @@ #include "BLI_kdtree.h" #include "BLI_kdopbvh.h" #include "BLI_utildefines.h" - -#include "BKE_bvhutils.h" -#include "BKE_cdderivedmesh.h" -#include "BKE_collision.h" -#include "BKE_customdata.h" -#include "BKE_DerivedMesh.h" -#include "BKE_effect.h" -#include "BKE_modifier.h" -#include "BKE_particle.h" -#include "BKE_pointcache.h" -#include "BKE_smoke.h" - +#include "BLI_voxel.h" #include "DNA_customdata_types.h" #include "DNA_group_types.h" @@ -73,10 +62,22 @@ #include "DNA_scene_types.h" #include "DNA_smoke_types.h" +#include "BKE_bvhutils.h" +#include "BKE_cdderivedmesh.h" +#include "BKE_collision.h" +#include "BKE_customdata.h" +#include "BKE_deform.h" +#include "BKE_DerivedMesh.h" +#include "BKE_effect.h" +#include "BKE_modifier.h" +#include "BKE_particle.h" +#include "BKE_pointcache.h" #include "BKE_smoke.h" #include "GPU_compatibility.h" +#include "RE_shader_ext.h" + /* UNUSED so far, may be enabled later */ /* #define USE_SMOKE_COLLISION_DM */ @@ -94,38 +95,38 @@ static LARGE_INTEGER liFrequency; static LARGE_INTEGER liStartTime; static LARGE_INTEGER liCurrentTime; -static void tstart ( void ) +static void tstart(void) { - QueryPerformanceFrequency ( &liFrequency ); - QueryPerformanceCounter ( &liStartTime ); + QueryPerformanceFrequency(&liFrequency); + QueryPerformanceCounter(&liStartTime); } -static void tend ( void ) +static void tend(void) { - QueryPerformanceCounter ( &liCurrentTime ); + QueryPerformanceCounter(&liCurrentTime); } -static double UNUSED_FUNCTION(tval)( void ) +static double tval(void) { - return ((double)( (liCurrentTime.QuadPart - liStartTime.QuadPart)* (double)1000.0/(double)liFrequency.QuadPart )); + return ((double)( (liCurrentTime.QuadPart - liStartTime.QuadPart) * (double)1000.0 / (double)liFrequency.QuadPart)); } #else #include <sys/time.h> static struct timeval _tstart, _tend; static struct timezone tz; -static void tstart ( void ) +static void tstart(void) { - gettimeofday ( &_tstart, &tz ); + gettimeofday(&_tstart, &tz); } -static void tend ( void ) +static void tend(void) { - gettimeofday ( &_tend,&tz ); + gettimeofday(&_tend, &tz); } -static double UNUSED_FUNCTION(tval)( void ) +static double UNUSED_FUNCTION(tval) (void) { double t1, t2; - t1 = ( double ) _tstart.tv_sec*1000 + ( double ) _tstart.tv_usec/ ( 1000 ); - t2 = ( double ) _tend.tv_sec*1000 + ( double ) _tend.tv_usec/ ( 1000 ); - return t2-t1; + t1 = ( double ) _tstart.tv_sec * 1000 + ( double ) _tstart.tv_usec / (1000); + t2 = ( double ) _tend.tv_sec * 1000 + ( double ) _tend.tv_usec / (1000); + return t2 - t1; } #endif @@ -134,608 +135,238 @@ struct Scene; struct DerivedMesh; struct SmokeModifierData; -#define TRI_UVOFFSET (1./4.) - // timestep default value for nice appearance 0.1f #define DT_DEFAULT 0.1f -/* forward declerations */ -static void calcTriangleDivs(Object *ob, MVert *verts, int numverts, MFace *tris, int numfaces, int numtris, int **tridivs, float cell_len); -static void get_cell(const float p0[3], const int res[3], float dx, const float pos[3], int cell[3], int correct); -static void fill_scs_points(Object *ob, DerivedMesh *dm, SmokeCollSettings *scs); +#define ADD_IF_LOWER_POS(a, b) (MIN2((a) + (b), MAX2((a), (b)))) +#define ADD_IF_LOWER_NEG(a, b) (MAX2((a) + (b), MIN2((a), (b)))) +#define ADD_IF_LOWER(a, b) (((b) > 0) ? ADD_IF_LOWER_POS((a), (b)) : ADD_IF_LOWER_NEG((a), (b))) #else /* WITH_SMOKE */ /* Stubs to use when smoke is disabled */ -struct WTURBULENCE *smoke_turbulence_init(int *UNUSED(res), int UNUSED(amplify), int UNUSED(noisetype)) { return NULL; } -// struct FLUID_3D *smoke_init(int *UNUSED(res), float *UNUSED(p0)) { return NULL; } +struct WTURBULENCE *smoke_turbulence_init(int *UNUSED(res), int UNUSED(amplify), int UNUSED(noisetype), int UNUSED(use_fire), int UNUSED(use_colors)) { 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)) {} float *smoke_get_density(struct FLUID_3D *UNUSED(fluid)) { return NULL; } void smoke_turbulence_free(struct WTURBULENCE *UNUSED(wt)) {} void smoke_initWaveletBlenderRNA(struct WTURBULENCE *UNUSED(wt), float *UNUSED(strength)) {} -void smoke_initBlenderRNA(struct FLUID_3D *UNUSED(fluid), float *UNUSED(alpha), float *UNUSED(beta), float *UNUSED(dt_factor), float *UNUSED(vorticity), int *UNUSED(border_colli)) {} -long long smoke_get_mem_req(int UNUSED(xres), int UNUSED(yres), int UNUSED(zres), int UNUSED(amplify)) { return 0; } -void smokeModifier_do(SmokeModifierData *UNUSED(smd), Scene *UNUSED(scene), Object *UNUSED(ob), DerivedMesh *UNUSED(dm)) {} +void smoke_initBlenderRNA(struct FLUID_3D *UNUSED(fluid), float *UNUSED(alpha), float *UNUSED(beta), float *UNUSED(dt_factor), float *UNUSED(vorticity), + int *UNUSED(border_colli), float *UNUSED(burning_rate), float *UNUSED(flame_smoke), float *UNUSED(flame_smoke_color), + float *UNUSED(flame_vorticity), float *UNUSED(flame_ignition_temp), float *UNUSED(flame_max_temp)) {} +struct DerivedMesh *smokeModifier_do(SmokeModifierData *UNUSED(smd), Scene *UNUSED(scene), Object *UNUSED(ob), DerivedMesh *UNUSED(dm)) { return NULL; } +float smoke_get_velocity_at(struct Object *UNUSED(ob), float UNUSED(position[3]), float UNUSED(velocity[3])) { return 0.0f; } +void flame_get_spectrum(unsigned char *UNUSED(spec), int UNUSED(width), float UNUSED(t1), float UNUSED(t2)) {} #endif /* WITH_SMOKE */ #ifdef WITH_SMOKE -static int smokeModifier_init (SmokeModifierData *smd, Object *ob, Scene *scene, DerivedMesh *dm) +void smoke_reallocate_fluid(SmokeDomainSettings *sds, float dx, int res[3], int free_old) { - if((smd->type & MOD_SMOKE_TYPE_DOMAIN) && smd->domain && !smd->domain->fluid) - { - size_t i; - float min[3] = {FLT_MAX, FLT_MAX, FLT_MAX}, max[3] = {-FLT_MAX, -FLT_MAX, -FLT_MAX}; - float size[3]; - MVert *verts = dm->getVertArray(dm); - float scale = 0.0; - int res; - - res = smd->domain->maxres; - - // get BB of domain - for(i = 0; i < dm->getNumVerts(dm); i++) - { - float tmp[3]; - - copy_v3_v3(tmp, verts[i].co); - mul_m4_v3(ob->obmat, tmp); - - // min BB - min[0] = MIN2(min[0], tmp[0]); - min[1] = MIN2(min[1], tmp[1]); - min[2] = MIN2(min[2], tmp[2]); - - // max BB - max[0] = MAX2(max[0], tmp[0]); - max[1] = MAX2(max[1], tmp[1]); - max[2] = MAX2(max[2], tmp[2]); - } - - copy_v3_v3(smd->domain->p0, min); - copy_v3_v3(smd->domain->p1, max); - - // calc other res with max_res provided - sub_v3_v3v3(size, max, min); - - // prevent crash when initializing a plane as domain - if((size[0] < FLT_EPSILON) || (size[1] < FLT_EPSILON) || (size[2] < FLT_EPSILON)) - return 0; - - if(size[0] > size[1]) - { - if(size[0] > size[2]) - { - scale = res / size[0]; - smd->domain->scale = size[0]; - smd->domain->dx = 1.0f / res; - smd->domain->res[0] = res; - smd->domain->res[1] = (int)(size[1] * scale + 0.5); - smd->domain->res[2] = (int)(size[2] * scale + 0.5); - } - else { - scale = res / size[2]; - smd->domain->scale = size[2]; - smd->domain->dx = 1.0f / res; - smd->domain->res[2] = res; - smd->domain->res[0] = (int)(size[0] * scale + 0.5); - smd->domain->res[1] = (int)(size[1] * scale + 0.5); - } - } - else { - if(size[1] > size[2]) - { - scale = res / size[1]; - smd->domain->scale = size[1]; - smd->domain->dx = 1.0f / res; - smd->domain->res[1] = res; - smd->domain->res[0] = (int)(size[0] * scale + 0.5); - smd->domain->res[2] = (int)(size[2] * scale + 0.5); - } - else { - scale = res / size[2]; - smd->domain->scale = size[2]; - smd->domain->dx = 1.0f / res; - smd->domain->res[2] = res; - smd->domain->res[0] = (int)(size[0] * scale + 0.5); - smd->domain->res[1] = (int)(size[1] * scale + 0.5); - } - } - - // TODO: put in failsafe if res<=0 - dg - - // dt max is 0.1 - smd->domain->fluid = smoke_init(smd->domain->res, smd->domain->p0, DT_DEFAULT); - smd->time = scene->r.cfra; - - if(smd->domain->flags & MOD_SMOKE_HIGHRES) - { - smd->domain->wt = smoke_turbulence_init(smd->domain->res, smd->domain->amplify + 1, smd->domain->noise); - smd->domain->res_wt[0] = smd->domain->res[0] * (smd->domain->amplify + 1); - smd->domain->res_wt[1] = smd->domain->res[1] * (smd->domain->amplify + 1); - smd->domain->res_wt[2] = smd->domain->res[2] * (smd->domain->amplify + 1); - smd->domain->dx_wt = smd->domain->dx / (smd->domain->amplify + 1); - } - - if(!smd->domain->shadow) - smd->domain->shadow = MEM_callocN(sizeof(float) * smd->domain->res[0] * smd->domain->res[1] * smd->domain->res[2], "SmokeDomainShadow"); - - smoke_initBlenderRNA(smd->domain->fluid, &(smd->domain->alpha), &(smd->domain->beta), &(smd->domain->time_scale), &(smd->domain->vorticity), &(smd->domain->border_collisions)); - - if(smd->domain->wt) - { - smoke_initWaveletBlenderRNA(smd->domain->wt, &(smd->domain->strength)); - } - return 1; - } - else if((smd->type & MOD_SMOKE_TYPE_FLOW) && smd->flow) - { - // handle flow object here - // XXX TODO - - smd->time = scene->r.cfra; - - return 1; - } - else if((smd->type & MOD_SMOKE_TYPE_COLL)) - { - // todo: delete this when loading colls work -dg - - if(!smd->coll) - { - smokeModifier_createType(smd); - } - - if(!smd->coll->points) - { - // init collision points - SmokeCollSettings *scs = smd->coll; - - smd->time = scene->r.cfra; - - // copy obmat - copy_m4_m4(scs->mat, ob->obmat); - copy_m4_m4(scs->mat_old, ob->obmat); - - DM_ensure_tessface(dm); - fill_scs_points(ob, dm, scs); - } - - if(!smd->coll->bvhtree) - { - smd->coll->bvhtree = NULL; // bvhtree_build_from_smoke ( ob->obmat, dm->getTessFaceArray(dm), dm->getNumTessFaces(dm), dm->getVertArray(dm), dm->getNumVerts(dm), 0.0 ); - } - return 1; + int use_heat = (sds->active_fields & SM_ACTIVE_HEAT); + 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->fluid) + smoke_free(sds->fluid); + if (!MIN3(res[0], res[1], res[2])) { + sds->fluid = NULL; + return; } - - return 2; + sds->fluid = smoke_init(res, dx, DT_DEFAULT, use_heat, use_fire, use_colors); + smoke_initBlenderRNA(sds->fluid, &(sds->alpha), &(sds->beta), &(sds->time_scale), &(sds->vorticity), &(sds->border_collisions), + &(sds->burning_rate), &(sds->flame_smoke), sds->flame_smoke_color, &(sds->flame_vorticity), &(sds->flame_ignition), &(sds->flame_max_temp)); + + /* reallocate shadow buffer */ + if (sds->shadow) + MEM_freeN(sds->shadow); + sds->shadow = MEM_callocN(sizeof(float) * res[0] * res[1] * res[2], "SmokeDomainShadow"); } -static void fill_scs_points(Object *ob, DerivedMesh *dm, SmokeCollSettings *scs) +void smoke_reallocate_highres_fluid(SmokeDomainSettings *sds, float dx, int res[3], int free_old) { - MVert *mvert = dm->getVertArray(dm); - MFace *mface = dm->getTessFaceArray(dm); - int i = 0, divs = 0; - - // DG TODO: need to do this dynamically according to the domain object! - float cell_len = scs->dx; - int newdivs = 0; - int quads = 0, facecounter = 0; + int use_fire = (sds->active_fields & (SM_ACTIVE_HEAT | SM_ACTIVE_FIRE)); + int use_colors = (sds->active_fields & SM_ACTIVE_COLORS); - // count quads - for(i = 0; i < dm->getNumTessFaces(dm); i++) - { - if(mface[i].v4) - quads++; + if (free_old && sds->wt) + smoke_turbulence_free(sds->wt); + if (!MIN3(res[0], res[1], res[2])) { + sds->wt = NULL; + return; } + sds->wt = smoke_turbulence_init(res, sds->amplify + 1, sds->noise, use_fire, use_colors); + sds->res_wt[0] = res[0] * (sds->amplify + 1); + sds->res_wt[1] = res[1] * (sds->amplify + 1); + sds->res_wt[2] = res[2] * (sds->amplify + 1); + sds->dx_wt = dx / (sds->amplify + 1); + smoke_initWaveletBlenderRNA(sds->wt, &(sds->strength)); +} - scs->numtris = dm->getNumTessFaces(dm) + quads; - scs->tridivs = NULL; - calcTriangleDivs(ob, mvert, dm->getNumVerts(dm), mface, dm->getNumTessFaces(dm), scs->numtris, &(scs->tridivs), cell_len); +/* convert global position to domain cell space */ +static void smoke_pos_to_cell(SmokeDomainSettings *sds, float pos[3]) +{ + mul_m4_v3(sds->imat, pos); + sub_v3_v3(pos, sds->p0); + pos[0] *= 1.0f / sds->cell_size[0]; + pos[1] *= 1.0f / sds->cell_size[1]; + pos[2] *= 1.0f / sds->cell_size[2]; +} - // count triangle divisions - for(i = 0; i < dm->getNumTessFaces(dm) + quads; i++) - { - divs += (scs->tridivs[3 * i] + 1) * (scs->tridivs[3 * i + 1] + 1) * (scs->tridivs[3 * i + 2] + 1); - } +/* set domain resolution and dimensions from object derivedmesh */ +static void smoke_set_domain_from_derivedmesh(SmokeDomainSettings *sds, Object *ob, DerivedMesh *dm) +{ + size_t i; + float min[3] = {FLT_MAX, FLT_MAX, FLT_MAX}, max[3] = {-FLT_MAX, -FLT_MAX, -FLT_MAX}; + float size[3]; + MVert *verts = dm->getVertArray(dm); + float scale = 0.0; + int res; - scs->points = MEM_callocN(sizeof(float) * (dm->getNumVerts(dm) + divs) * 3, "SmokeCollPoints"); - scs->points_old = MEM_callocN(sizeof(float) * (dm->getNumVerts(dm) + divs) * 3, "SmokeCollPointsOld"); + res = sds->maxres; - for(i = 0; i < dm->getNumVerts(dm); i++) + // get BB of domain + for (i = 0; i < dm->getNumVerts(dm); i++) { - float tmpvec[3]; - copy_v3_v3(tmpvec, mvert[i].co); - // mul_m4_v3(ob->obmat, tmpvec); // DG: use local coordinates, we save MAT anyway - copy_v3_v3(&scs->points[i * 3], tmpvec); + // min BB + min[0] = MIN2(min[0], verts[i].co[0]); + min[1] = MIN2(min[1], verts[i].co[1]); + min[2] = MIN2(min[2], verts[i].co[2]); + + // max BB + max[0] = MAX2(max[0], verts[i].co[0]); + max[1] = MAX2(max[1], verts[i].co[1]); + max[2] = MAX2(max[2], verts[i].co[2]); } - - for(i = 0, facecounter = 0; i < dm->getNumTessFaces(dm); i++) - { - int again = 0; - do - { - int j, k; - int divs1 = scs->tridivs[3 * facecounter + 0]; - int divs2 = scs->tridivs[3 * facecounter + 1]; - //int divs3 = scs->tridivs[3 * facecounter + 2]; - float side1[3], side2[3], trinormorg[3], trinorm[3]; - - if(again == 1 && mface[i].v4) - { - sub_v3_v3v3(side1, mvert[ mface[i].v3 ].co, mvert[ mface[i].v1 ].co); - sub_v3_v3v3(side2, mvert[ mface[i].v4 ].co, mvert[ mface[i].v1 ].co); - } - else { - sub_v3_v3v3(side1, mvert[ mface[i].v2 ].co, mvert[ mface[i].v1 ].co); - sub_v3_v3v3(side2, mvert[ mface[i].v3 ].co, mvert[ mface[i].v1 ].co); - } - cross_v3_v3v3(trinormorg, side1, side2); - normalize_v3(trinormorg); - copy_v3_v3(trinorm, trinormorg); - mul_v3_fl(trinorm, 0.25 * cell_len); + /* set domain bounds */ + copy_v3_v3(sds->p0, min); + copy_v3_v3(sds->p1, max); + sds->dx = 1.0f / res; - for(j = 0; j <= divs1; j++) - { - for(k = 0; k <= divs2; k++) - { - float p1[3], p2[3], p3[3], p[3]={0,0,0}; - const float uf = (float)(j + TRI_UVOFFSET) / (float)(divs1 + 0.0); - const float vf = (float)(k + TRI_UVOFFSET) / (float)(divs2 + 0.0); - float tmpvec[3]; - - if(uf+vf > 1.0) - { - // printf("bigger - divs1: %d, divs2: %d\n", divs1, divs2); - continue; - } + /* calculate domain dimensions */ + sub_v3_v3v3(size, max, min); + copy_v3_v3(sds->cell_size, size); + mul_v3_v3(size, ob->size); + copy_v3_v3(sds->global_size, size); + copy_v3_v3(sds->dp0, min); - copy_v3_v3(p1, mvert[ mface[i].v1 ].co); - if(again == 1 && mface[i].v4) - { - copy_v3_v3(p2, mvert[ mface[i].v3 ].co); - copy_v3_v3(p3, mvert[ mface[i].v4 ].co); - } - else { - copy_v3_v3(p2, mvert[ mface[i].v2 ].co); - copy_v3_v3(p3, mvert[ mface[i].v3 ].co); - } + invert_m4_m4(sds->imat, ob->obmat); - mul_v3_fl(p1, (1.0-uf-vf)); - mul_v3_fl(p2, uf); - mul_v3_fl(p3, vf); - - add_v3_v3v3(p, p1, p2); - add_v3_v3(p, p3); - - if(newdivs > divs) - printf("mem problem\n"); - - // mMovPoints.push_back(p + trinorm); - add_v3_v3v3(tmpvec, p, trinorm); - // mul_m4_v3(ob->obmat, tmpvec); // DG: use local coordinates, we save MAT anyway - copy_v3_v3(&scs->points[3 * (dm->getNumVerts(dm) + newdivs)], tmpvec); - newdivs++; - - if(newdivs > divs) - printf("mem problem\n"); - - // mMovPoints.push_back(p - trinorm); - copy_v3_v3(tmpvec, p); - sub_v3_v3(tmpvec, trinorm); - // mul_m4_v3(ob->obmat, tmpvec); // DG: use local coordinates, we save MAT anyway - copy_v3_v3(&scs->points[3 * (dm->getNumVerts(dm) + newdivs)], tmpvec); - newdivs++; - } - } - - if(again == 0 && mface[i].v4) - again++; - else - again = 0; - - facecounter++; + // prevent crash when initializing a plane as domain + if ((size[0] < FLT_EPSILON) || (size[1] < FLT_EPSILON) || (size[2] < FLT_EPSILON)) + return; - } while(again!=0); + /* define grid resolutions from longest domain side */ + if (size[0] > MAX2(size[1], size[2])) { + scale = res / size[0]; + sds->scale = size[0] / ob->size[0]; + sds->base_res[0] = res; + sds->base_res[1] = (int)(size[1] * scale + 0.5f); + sds->base_res[2] = (int)(size[2] * scale + 0.5f); } - - scs->numverts = dm->getNumVerts(dm); - // DG TODO: also save triangle count? - - scs->numpoints = dm->getNumVerts(dm) + newdivs; - - for(i = 0; i < scs->numpoints * 3; i++) - { - scs->points_old[i] = scs->points[i]; + else if (size[1] > MAX2(size[0], size[2])) { + scale = res / size[1]; + sds->scale = size[1] / ob->size[1]; + sds->base_res[0] = (int)(size[0] * scale + 0.5f); + sds->base_res[1] = res; + sds->base_res[2] = (int)(size[2] * scale + 0.5f); + } + else { + scale = res / size[2]; + sds->scale = size[2] / ob->size[2]; + sds->base_res[0] = (int)(size[0] * scale + 0.5f); + sds->base_res[1] = (int)(size[1] * scale + 0.5f); + sds->base_res[2] = res; } -} + /* set cell size */ + sds->cell_size[0] /= (float)sds->base_res[0]; + sds->cell_size[1] /= (float)sds->base_res[1]; + sds->cell_size[2] /= (float)sds->base_res[2]; +} -static void fill_scs_points_anim(Object *UNUSED(ob), DerivedMesh *dm, SmokeCollSettings *scs) +static int smokeModifier_init(SmokeModifierData *smd, Object *ob, Scene *scene, DerivedMesh *dm) { - MVert *mvert = dm->getVertArray(dm); - MFace *mface = dm->getTessFaceArray(dm); - int quads = 0, numtris = 0, facecounter = 0; - unsigned int i = 0; - int divs = 0, newdivs = 0; - - // DG TODO: need to do this dynamically according to the domain object! - float cell_len = scs->dx; - - // count quads - for(i = 0; i < dm->getNumTessFaces(dm); i++) + if ((smd->type & MOD_SMOKE_TYPE_DOMAIN) && smd->domain && !smd->domain->fluid) { - if(mface[i].v4) - quads++; - } + SmokeDomainSettings *sds = smd->domain; + int res[3]; + /* set domain dimensions from derivedmesh */ + smoke_set_domain_from_derivedmesh(sds, ob, dm); + /* reset domain values */ + zero_v3_int(sds->shift); + zero_v3(sds->shift_f); + add_v3_fl(sds->shift_f, 0.5f); + zero_v3(sds->prev_loc); + mul_m4_v3(ob->obmat, sds->prev_loc); + + /* set resolutions */ + if (smd->domain->flags & MOD_SMOKE_ADAPTIVE_DOMAIN) { + res[0] = res[1] = res[2] = 1; /* use minimum res for adaptive init */ + } + else { + VECCOPY(res, sds->base_res); + } + VECCOPY(sds->res, res); + sds->total_cells = sds->res[0] * sds->res[1] * sds->res[2]; + sds->res_min[0] = sds->res_min[1] = sds->res_min[2] = 0; + VECCOPY(sds->res_max, res); - numtris = dm->getNumTessFaces(dm) + quads; + /* allocate fluid */ + smoke_reallocate_fluid(sds, sds->dx, sds->res, 0); - // check if mesh changed topology - if(scs->numtris != numtris) - return; - if(scs->numverts != dm->getNumVerts(dm)) - return; + smd->time = scene->r.cfra; - // update new positions - for(i = 0; i < dm->getNumVerts(dm); i++) - { - float tmpvec[3]; - copy_v3_v3(tmpvec, mvert[i].co); - copy_v3_v3(&scs->points[i * 3], tmpvec); - } + /* allocate highres fluid */ + if (sds->flags & MOD_SMOKE_HIGHRES) { + smoke_reallocate_highres_fluid(sds, sds->dx, sds->res, 0); + } + /* allocate shadow buffer */ + if (!sds->shadow) + sds->shadow = MEM_callocN(sizeof(float) * sds->res[0] * sds->res[1] * sds->res[2], "SmokeDomainShadow"); - // for every triangle // update div points - for(i = 0, facecounter = 0; i < dm->getNumTessFaces(dm); i++) + return 1; + } + else if ((smd->type & MOD_SMOKE_TYPE_FLOW) && smd->flow) { - int again = 0; - do - { - int j, k; - int divs1 = scs->tridivs[3 * facecounter + 0]; - int divs2 = scs->tridivs[3 * facecounter + 1]; - float srcside1[3], srcside2[3], destside1[3], destside2[3], src_trinormorg[3], dest_trinormorg[3], src_trinorm[3], dest_trinorm[3]; - - if(again == 1 && mface[i].v4) - { - sub_v3_v3v3(srcside1, &scs->points_old[mface[i].v3 * 3], &scs->points_old[mface[i].v1 * 3]); - sub_v3_v3v3(destside1, &scs->points[mface[i].v3 * 3], &scs->points[mface[i].v1 * 3]); - - sub_v3_v3v3(srcside2, &scs->points_old[mface[i].v4 * 3], &scs->points_old[mface[i].v1 * 3]); - sub_v3_v3v3(destside2, &scs->points[mface[i].v4 * 3], &scs->points[mface[i].v1 * 3]); - } - else { - sub_v3_v3v3(srcside1, &scs->points_old[mface[i].v2 * 3], &scs->points_old[mface[i].v1 * 3]); - sub_v3_v3v3(destside1, &scs->points[mface[i].v2 * 3], &scs->points[mface[i].v1 * 3]); - - sub_v3_v3v3(srcside2, &scs->points_old[mface[i].v3 * 3], &scs->points_old[mface[i].v1 * 3]); - sub_v3_v3v3(destside2, &scs->points[mface[i].v3 * 3], &scs->points[mface[i].v1 * 3]); - } - - cross_v3_v3v3(src_trinormorg, srcside1, srcside2); - cross_v3_v3v3(dest_trinormorg, destside1, destside2); - - normalize_v3(src_trinormorg); - normalize_v3(dest_trinormorg); - - copy_v3_v3(src_trinorm, src_trinormorg); - copy_v3_v3(dest_trinorm, dest_trinormorg); - - mul_v3_fl(src_trinorm, 0.25 * cell_len); - mul_v3_fl(dest_trinorm, 0.25 * cell_len); - - for(j = 0; j <= divs1; j++) - { - for(k = 0; k <= divs2; k++) - { - float src_p1[3], src_p2[3], src_p3[3], src_p[3]={0,0,0}; - float dest_p1[3], dest_p2[3], dest_p3[3], dest_p[3]={0,0,0}; - const float uf = (float)(j + TRI_UVOFFSET) / (float)(divs1 + 0.0); - const float vf = (float)(k + TRI_UVOFFSET) / (float)(divs2 + 0.0); - float src_tmpvec[3], dest_tmpvec[3]; - - if(uf+vf > 1.0) - { - // printf("bigger - divs1: %d, divs2: %d\n", divs1, divs2); - continue; - } - - copy_v3_v3(src_p1, &scs->points_old[mface[i].v1 * 3]); - copy_v3_v3(dest_p1, &scs->points[mface[i].v1 * 3]); - if(again == 1 && mface[i].v4) - { - copy_v3_v3(src_p2, &scs->points_old[mface[i].v3 * 3]); - copy_v3_v3(dest_p2, &scs->points[mface[i].v3 * 3]); - - copy_v3_v3(src_p3,&scs->points_old[mface[i].v4 * 3]); - copy_v3_v3(dest_p3, &scs->points[mface[i].v4 * 3]); - } - else { - copy_v3_v3(src_p2, &scs->points_old[mface[i].v2 * 3]); - copy_v3_v3(dest_p2, &scs->points[mface[i].v2 * 3]); - copy_v3_v3(src_p3, &scs->points_old[mface[i].v3 * 3]); - copy_v3_v3(dest_p3, &scs->points[mface[i].v3 * 3]); - } - - mul_v3_fl(src_p1, (1.0-uf-vf)); - mul_v3_fl(dest_p1, (1.0-uf-vf)); - - mul_v3_fl(src_p2, uf); - mul_v3_fl(dest_p2, uf); - - mul_v3_fl(src_p3, vf); - mul_v3_fl(dest_p3, vf); - - add_v3_v3v3(src_p, src_p1, src_p2); - add_v3_v3v3(dest_p, dest_p1, dest_p2); - - add_v3_v3(src_p, src_p3); - add_v3_v3(dest_p, dest_p3); - - if(newdivs > divs) - printf("mem problem\n"); - - // mMovPoints.push_back(p + trinorm); - add_v3_v3v3(src_tmpvec, src_p, src_trinorm); - add_v3_v3v3(dest_tmpvec, dest_p, dest_trinorm); - - // mul_m4_v3(ob->obmat, tmpvec); // DG: use local coordinates, we save MAT anyway - copy_v3_v3(&scs->points_old[3 * (dm->getNumVerts(dm) + newdivs)], src_tmpvec); - copy_v3_v3(&scs->points[3 * (dm->getNumVerts(dm) + newdivs)], dest_tmpvec); - newdivs++; - - if(newdivs > divs) - printf("mem problem\n"); - - // mMovPoints.push_back(p - trinorm); - copy_v3_v3(src_tmpvec, src_p); - copy_v3_v3(dest_tmpvec, dest_p); - - sub_v3_v3(src_tmpvec, src_trinorm); - sub_v3_v3(dest_tmpvec, dest_trinorm); - - // mul_m4_v3(ob->obmat, tmpvec); // DG: use local coordinates, we save MAT anyway - copy_v3_v3(&scs->points_old[3 * (dm->getNumVerts(dm) + newdivs)], src_tmpvec); - copy_v3_v3(&scs->points[3 * (dm->getNumVerts(dm) + newdivs)], dest_tmpvec); - newdivs++; - } - } - - if(again == 0 && mface[i].v4) - again++; - else - again = 0; - - facecounter++; + smd->time = scene->r.cfra; - } while(again!=0); + return 1; } - - // scs->numpoints = dm->getNumVerts(dm) + newdivs; - -} - -/*! init triangle divisions */ -static void calcTriangleDivs(Object *ob, MVert *verts, int UNUSED(numverts), MFace *faces, int numfaces, int numtris, int **tridivs, float cell_len) -{ - // mTriangleDivs1.resize( faces.size() ); - // mTriangleDivs2.resize( faces.size() ); - // mTriangleDivs3.resize( faces.size() ); - - size_t i = 0, facecounter = 0; - float maxscale[3] = {1,1,1}; // = channelFindMaxVf(mcScale); get max scale value - float maxpart = ABS(maxscale[0]); - float scaleFac = 0; - float fsTri = 0; - if(ABS(maxscale[1])>maxpart) maxpart = ABS(maxscale[1]); - if(ABS(maxscale[2])>maxpart) maxpart = ABS(maxscale[2]); - scaleFac = 1.0 / maxpart; - // featureSize = mLevel[mMaxRefine].nodeSize - fsTri = cell_len * 0.75 * scaleFac; // fsTri = cell_len * 0.9; - - if(*tridivs) - MEM_freeN(*tridivs); - - *tridivs = MEM_callocN(sizeof(int) * numtris * 3, "Smoke_Tridivs"); - - for(i = 0, facecounter = 0; i < numfaces; i++) + else if ((smd->type & MOD_SMOKE_TYPE_COLL)) { - float p0[3], p1[3], p2[3]; - float side1[3]; - float side2[3]; - float side3[3]; - int divs1=0, divs2=0, divs3=0; - - copy_v3_v3(p0, verts[faces[i].v1].co); - mul_m4_v3(ob->obmat, p0); - copy_v3_v3(p1, verts[faces[i].v2].co); - mul_m4_v3(ob->obmat, p1); - copy_v3_v3(p2, verts[faces[i].v3].co); - mul_m4_v3(ob->obmat, p2); - - sub_v3_v3v3(side1, p1, p0); - sub_v3_v3v3(side2, p2, p0); - sub_v3_v3v3(side3, p1, p2); - - if(dot_v3v3(side1, side1) > fsTri*fsTri) - { - float tmp = normalize_v3(side1); - divs1 = (int)ceil(tmp/fsTri); - } - if(dot_v3v3(side2, side2) > fsTri*fsTri) - { - float tmp = normalize_v3(side2); - divs2 = (int)ceil(tmp/fsTri); - - /* - // debug - if(i==0) - printf("b tmp: %f, fsTri: %f, divs2: %d\n", tmp, fsTri, divs2); - */ - + if (!smd->coll) + { + smokeModifier_createType(smd); } - (*tridivs)[3 * facecounter + 0] = divs1; - (*tridivs)[3 * facecounter + 1] = divs2; - (*tridivs)[3 * facecounter + 2] = divs3; - - // TODO quad case - if(faces[i].v4) - { - divs1=0, divs2=0, divs3=0; - - facecounter++; - - copy_v3_v3(p0, verts[faces[i].v3].co); - mul_m4_v3(ob->obmat, p0); - copy_v3_v3(p1, verts[faces[i].v4].co); - mul_m4_v3(ob->obmat, p1); - copy_v3_v3(p2, verts[faces[i].v1].co); - mul_m4_v3(ob->obmat, p2); - - sub_v3_v3v3(side1, p1, p0); - sub_v3_v3v3(side2, p2, p0); - sub_v3_v3v3(side3, p1, p2); - - if(dot_v3v3(side1, side1) > fsTri*fsTri) - { - float tmp = normalize_v3(side1); - divs1 = (int)ceil(tmp/fsTri); - } - if(dot_v3v3(side2, side2) > fsTri*fsTri) - { - float tmp = normalize_v3(side2); - divs2 = (int)ceil(tmp/fsTri); - } + smd->time = scene->r.cfra; - (*tridivs)[3 * facecounter + 0] = divs1; - (*tridivs)[3 * facecounter + 1] = divs2; - (*tridivs)[3 * facecounter + 2] = divs3; - } - facecounter++; + return 1; } + + return 2; } #endif /* WITH_SMOKE */ static void smokeModifier_freeDomain(SmokeModifierData *smd) { - if(smd->domain) + if (smd->domain) { - if(smd->domain->shadow) - MEM_freeN(smd->domain->shadow); - smd->domain->shadow = NULL; + 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->wt) + if (smd->domain->wt) smoke_turbulence_free(smd->domain->wt); - if(smd->domain->effector_weights) - MEM_freeN(smd->domain->effector_weights); + if (smd->domain->effector_weights) + MEM_freeN(smd->domain->effector_weights); smd->domain->effector_weights = NULL; BKE_ptcache_free_list(&(smd->domain->ptcaches[0])); @@ -748,16 +379,10 @@ static void smokeModifier_freeDomain(SmokeModifierData *smd) static void smokeModifier_freeFlow(SmokeModifierData *smd) { - if(smd->flow) + if (smd->flow) { -/* - if(smd->flow->bvh) - { - free_bvhtree_from_mesh(smd->flow->bvh); - MEM_freeN(smd->flow->bvh); - } - smd->flow->bvh = NULL; -*/ + if (smd->flow->dm) smd->flow->dm->release(smd->flow->dm); + if (smd->flow->verts_old) MEM_freeN(smd->flow->verts_old); MEM_freeN(smd->flow); smd->flow = NULL; } @@ -765,40 +390,22 @@ static void smokeModifier_freeFlow(SmokeModifierData *smd) static void smokeModifier_freeCollision(SmokeModifierData *smd) { - if(smd->coll) + if (smd->coll) { SmokeCollSettings *scs = smd->coll; - if(scs->numpoints) + if (scs->numverts) { - if(scs->points) + if (scs->verts_old) { - MEM_freeN(scs->points); - scs->points = NULL; - } - if(scs->points_old) - { - MEM_freeN(scs->points_old); - scs->points_old = NULL; - } - if(scs->tridivs) - { - MEM_freeN(scs->tridivs); - scs->tridivs = NULL; + MEM_freeN(scs->verts_old); + scs->verts_old = NULL; } } - if(scs->bvhtree) - { - BLI_bvhtree_free(scs->bvhtree); - scs->bvhtree = NULL; - } - -#ifdef USE_SMOKE_COLLISION_DM - if(smd->coll->dm) + if (smd->coll->dm) smd->coll->dm->release(smd->coll->dm); smd->coll->dm = NULL; -#endif MEM_freeN(smd->coll); smd->coll = NULL; @@ -807,7 +414,7 @@ static void smokeModifier_freeCollision(SmokeModifierData *smd) void smokeModifier_reset_turbulence(struct SmokeModifierData *smd) { - if(smd && smd->domain && smd->domain->wt) + if (smd && smd->domain && smd->domain->wt) { smoke_turbulence_free(smd->domain->wt); smd->domain->wt = NULL; @@ -816,15 +423,15 @@ void smokeModifier_reset_turbulence(struct SmokeModifierData *smd) void smokeModifier_reset(struct SmokeModifierData *smd) { - if(smd) + if (smd) { - if(smd->domain) + 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); smd->domain->fluid = NULL; @@ -833,39 +440,23 @@ void smokeModifier_reset(struct SmokeModifierData *smd) smokeModifier_reset_turbulence(smd); smd->time = -1; - - // printf("reset domain end\n"); + smd->domain->total_cells = 0; + smd->domain->active_fields = 0; } - else if(smd->flow) + else if (smd->flow) { - /* - if(smd->flow->bvh) - { - free_bvhtree_from_mesh(smd->flow->bvh); - MEM_freeN(smd->flow->bvh); - } - smd->flow->bvh = NULL; - */ + if (smd->flow->verts_old) MEM_freeN(smd->flow->verts_old); + smd->flow->verts_old = NULL; + smd->flow->numverts = 0; } - else if(smd->coll) + else if (smd->coll) { SmokeCollSettings *scs = smd->coll; - if(scs->numpoints && scs->points) + if (scs->numverts && scs->verts_old) { - MEM_freeN(scs->points); - scs->points = NULL; - - if(scs->points_old) - { - MEM_freeN(scs->points_old); - scs->points_old = NULL; - } - if(scs->tridivs) - { - MEM_freeN(scs->tridivs); - scs->tridivs = NULL; - } + MEM_freeN(scs->verts_old); + scs->verts_old = NULL; } } } @@ -873,7 +464,7 @@ void smokeModifier_reset(struct SmokeModifierData *smd) void smokeModifier_free(SmokeModifierData *smd) { - if(smd) + if (smd) { smokeModifier_freeDomain(smd); smokeModifier_freeFlow(smd); @@ -883,11 +474,11 @@ void smokeModifier_free(SmokeModifierData *smd) void smokeModifier_createType(struct SmokeModifierData *smd) { - if(smd) + if (smd) { - if(smd->type & MOD_SMOKE_TYPE_DOMAIN) + if (smd->type & MOD_SMOKE_TYPE_DOMAIN) { - if(smd->domain) + if (smd->domain) smokeModifier_freeDomain(smd); smd->domain = MEM_callocN(sizeof(SmokeDomainSettings), "SmokeDomain"); @@ -903,13 +494,12 @@ void smokeModifier_createType(struct SmokeModifierData *smd) smd->domain->ptcaches[1].first = smd->domain->ptcaches[1].last = NULL; /* set some standard values */ smd->domain->fluid = NULL; - smd->domain->wt = NULL; + smd->domain->wt = NULL; smd->domain->eff_group = NULL; smd->domain->fluid_group = NULL; smd->domain->coll_group = NULL; smd->domain->maxres = 32; - smd->domain->amplify = 1; - smd->domain->omega = 1.0; + smd->domain->amplify = 1; smd->domain->alpha = -0.001; smd->domain->beta = 0.1; smd->domain->time_scale = 1.0; @@ -919,14 +509,28 @@ void smokeModifier_createType(struct SmokeModifierData *smd) smd->domain->strength = 2.0; smd->domain->noise = MOD_SMOKE_NOISEWAVE; smd->domain->diss_speed = 5; - // init 3dview buffer + smd->domain->active_fields = 0; + + smd->domain->adapt_margin = 4; + smd->domain->adapt_res = 0; + smd->domain->adapt_threshold = 0.02f; + + smd->domain->burning_rate = 0.75f; + smd->domain->flame_smoke = 1.0f; + smd->domain->flame_vorticity = 0.5f; + smd->domain->flame_ignition = 1.25f; + smd->domain->flame_max_temp = 1.75f; + /* color */ + smd->domain->flame_smoke_color[0] = 0.7f; + smd->domain->flame_smoke_color[1] = 0.7f; + smd->domain->flame_smoke_color[2] = 0.7f; smd->domain->viewsettings = MOD_SMOKE_VIEW_SHOWBIG; smd->domain->effector_weights = BKE_add_effector_weights(NULL); } - else if(smd->type & MOD_SMOKE_TYPE_FLOW) + else if (smd->type & MOD_SMOKE_TYPE_FLOW) { - if(smd->flow) + if (smd->flow) smokeModifier_freeFlow(smd); smd->flow = MEM_callocN(sizeof(SmokeFlowSettings), "SmokeFlow"); @@ -934,31 +538,35 @@ void smokeModifier_createType(struct SmokeModifierData *smd) smd->flow->smd = smd; /* set some standard values */ - smd->flow->density = 1.0; - smd->flow->temp = 1.0; + smd->flow->density = 1.0f; + smd->flow->fuel_amount = 1.0f; + smd->flow->temp = 1.0f; smd->flow->flags = MOD_SMOKE_FLOW_ABSOLUTE; - smd->flow->vel_multi = 1.0; + smd->flow->vel_multi = 1.0f; + smd->flow->surface_distance = 1.5f; + smd->flow->source = MOD_SMOKE_FLOW_SOURCE_MESH; + smd->flow->texture_size = 1.0f; + + smd->flow->color[0] = 0.7f; + smd->flow->color[1] = 0.7f; + smd->flow->color[2] = 0.7f; + smd->flow->dm = NULL; smd->flow->psys = NULL; } - else if(smd->type & MOD_SMOKE_TYPE_COLL) + else if (smd->type & MOD_SMOKE_TYPE_COLL) { - if(smd->coll) + if (smd->coll) smokeModifier_freeCollision(smd); smd->coll = MEM_callocN(sizeof(SmokeCollSettings), "SmokeColl"); smd->coll->smd = smd; - smd->coll->points = NULL; - smd->coll->points_old = NULL; - smd->coll->tridivs = NULL; - smd->coll->vel = NULL; - smd->coll->numpoints = 0; - smd->coll->numtris = 0; - smd->coll->bvhtree = NULL; + smd->coll->verts_old = NULL; + smd->coll->numverts = 0; smd->coll->type = 0; // static obstacle - smd->coll->dx = 1.0f / 50.0f; + smd->coll->dm = NULL; #ifdef USE_SMOKE_COLLISION_DM smd->coll->dm = NULL; @@ -971,39 +579,67 @@ void smokeModifier_copy(struct SmokeModifierData *smd, struct SmokeModifierData { tsmd->type = smd->type; tsmd->time = smd->time; - + smokeModifier_createType(tsmd); if (tsmd->domain) { - tsmd->domain->maxres = smd->domain->maxres; - tsmd->domain->amplify = smd->domain->amplify; - tsmd->domain->omega = smd->domain->omega; + tsmd->domain->fluid_group = smd->domain->fluid_group; + tsmd->domain->coll_group = smd->domain->coll_group; + + tsmd->domain->adapt_margin = smd->domain->adapt_margin; + tsmd->domain->adapt_res = smd->domain->adapt_res; + tsmd->domain->adapt_threshold = smd->domain->adapt_threshold; + tsmd->domain->alpha = smd->domain->alpha; tsmd->domain->beta = smd->domain->beta; + tsmd->domain->amplify = smd->domain->amplify; + tsmd->domain->maxres = smd->domain->maxres; tsmd->domain->flags = smd->domain->flags; - tsmd->domain->strength = smd->domain->strength; + tsmd->domain->viewsettings = smd->domain->viewsettings; tsmd->domain->noise = smd->domain->noise; tsmd->domain->diss_speed = smd->domain->diss_speed; - tsmd->domain->viewsettings = smd->domain->viewsettings; - tsmd->domain->fluid_group = smd->domain->fluid_group; - tsmd->domain->coll_group = smd->domain->coll_group; + tsmd->domain->strength = smd->domain->strength; + + tsmd->domain->border_collisions = smd->domain->border_collisions; tsmd->domain->vorticity = smd->domain->vorticity; tsmd->domain->time_scale = smd->domain->time_scale; - tsmd->domain->border_collisions = smd->domain->border_collisions; - + + tsmd->domain->burning_rate = smd->domain->burning_rate; + tsmd->domain->flame_smoke = smd->domain->flame_smoke; + tsmd->domain->flame_vorticity = smd->domain->flame_vorticity; + tsmd->domain->flame_ignition = smd->domain->flame_ignition; + tsmd->domain->flame_max_temp = smd->domain->flame_max_temp; + copy_v3_v3(tsmd->domain->flame_smoke_color, smd->domain->flame_smoke_color); + MEM_freeN(tsmd->domain->effector_weights); tsmd->domain->effector_weights = MEM_dupallocN(smd->domain->effector_weights); - } + } else if (tsmd->flow) { + tsmd->flow->psys = smd->flow->psys; + tsmd->flow->noise_texture = smd->flow->noise_texture; + + tsmd->flow->vel_multi = smd->flow->vel_multi; + tsmd->flow->vel_normal = smd->flow->vel_normal; + tsmd->flow->vel_random = smd->flow->vel_random; + tsmd->flow->density = smd->flow->density; + copy_v3_v3(tsmd->flow->color, smd->flow->color); + tsmd->flow->fuel_amount = smd->flow->fuel_amount; tsmd->flow->temp = smd->flow->temp; - tsmd->flow->psys = smd->flow->psys; + tsmd->flow->volume_density = smd->flow->volume_density; + tsmd->flow->surface_distance = smd->flow->surface_distance; + + tsmd->flow->texture_size = smd->flow->texture_size; + tsmd->flow->texture_offset = smd->flow->texture_offset; + BLI_strncpy(tsmd->flow->uvlayer_name, tsmd->flow->uvlayer_name, sizeof(tsmd->flow->uvlayer_name)); + tsmd->flow->vgroup_density = smd->flow->vgroup_density; + tsmd->flow->type = smd->flow->type; + tsmd->flow->source = smd->flow->source; + tsmd->flow->texture_type = smd->flow->texture_type; tsmd->flow->flags = smd->flow->flags; - tsmd->flow->vel_multi = smd->flow->vel_multi; } else if (tsmd->coll) { - ; /* leave it as initialized, collision settings is mostly caches */ } } @@ -1011,24 +647,24 @@ void smokeModifier_copy(struct SmokeModifierData *smd, struct SmokeModifierData #ifdef WITH_SMOKE // forward decleration -static void smoke_calc_transparency(float *result, float *input, float *p0, float *p1, int res[3], float dx, float *light, bresenham_callback cb, float correct); +static void smoke_calc_transparency(SmokeDomainSettings *sds, Scene *scene); static float calc_voxel_transp(float *result, float *input, int res[3], int *pixel, float *tRay, float correct); static int get_lamp(Scene *scene, float *light) -{ - Base *base_tmp = NULL; +{ + Base *base_tmp = NULL; int found_lamp = 0; // try to find a lamp, preferably local - for(base_tmp = scene->base.first; base_tmp; base_tmp= base_tmp->next) { - if(base_tmp->object->type == OB_LAMP) { + for (base_tmp = scene->base.first; base_tmp; base_tmp = base_tmp->next) { + if (base_tmp->object->type == OB_LAMP) { Lamp *la = base_tmp->object->data; - if(la->type == LA_LOCAL) { + if (la->type == LA_LOCAL) { copy_v3_v3(light, base_tmp->object->obmat[3]); return 1; } - else if(!found_lamp) { + else if (!found_lamp) { copy_v3_v3(light, base_tmp->object->obmat[3]); found_lamp = 1; } @@ -1038,48 +674,131 @@ static int get_lamp(Scene *scene, float *light) return found_lamp; } -static void smoke_calc_domain(Scene *UNUSED(scene), Object *UNUSED(ob), SmokeModifierData *UNUSED(smd)) +static void obstacles_from_derivedmesh(Object *coll_ob, SmokeDomainSettings *sds, SmokeCollSettings *scs, unsigned char *obstacle_map, float *velocityX, float *velocityY, float *velocityZ, float dt) { -#if 0 - SmokeDomainSettings *sds = smd->domain; - GroupObject *go = NULL; - Base *base = NULL; - - /* do collisions, needs to be done before emission, so that smoke isn't emitted inside collision cells */ - if(1) + if (!scs->dm) return; { - unsigned int i; - Object **collobjs = NULL; - unsigned int numcollobj = 0; - collobjs = get_collisionobjects(scene, ob, sds->coll_group, &numcollobj); + DerivedMesh *dm = NULL; + MVert *mvert = NULL; + MFace *mface = NULL; + BVHTreeFromMesh treeData = {0}; + int numverts, i, z; + + float surface_distance = 0.6; + + float *vert_vel = NULL; + int has_velocity = 0; + + tstart(); + + dm = CDDM_copy(scs->dm); + CDDM_calc_normals(dm); + mvert = dm->getVertArray(dm); + mface = dm->getTessFaceArray(dm); + numverts = dm->getNumVerts(dm); + + // 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" - for(i = 0; i < numcollobj; i++) { - Object *collob= collobjs[i]; - SmokeModifierData *smd2 = (SmokeModifierData*)modifiers_findByType(collob, eModifierType_Smoke); - - // check for active smoke modifier - // if(md && md->mode & (eModifierMode_Realtime | eModifierMode_Render)) - // SmokeModifierData *smd2 = (SmokeModifierData *)md; - - if((smd2->type & MOD_SMOKE_TYPE_COLL) && smd2->coll && smd2->coll->points && smd2->coll->points_old) + vert_vel = MEM_callocN(sizeof(float) * numverts * 3, "smoke_obs_velocity"); + + if (scs->numverts != numverts || !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; + } + else { + has_velocity = 1; + } + } + + /* Transform collider vertices to + * domain grid space for fast lookups */ + for (i = 0; i < numverts; i++) { + float n[3]; + float co[3]; + + /* vert pos */ + mul_m4_v3(coll_ob->obmat, mvert[i].co); + smoke_pos_to_cell(sds, mvert[i].co); + + /* vert normal */ + normal_short_to_float_v3(n, mvert[i].no); + mul_mat3_m4_v3(coll_ob->obmat, n); + mul_mat3_m4_v3(sds->imat, n); + normalize_v3(n); + normal_float_to_short_v3(mvert[i].no, n); + + /* vert velocity */ + VECADD(co, mvert[i].co, sds->shift); + if (has_velocity) { - // ??? anything to do here? + sub_v3_v3v3(&vert_vel[i * 3], co, &scs->verts_old[i * 3]); + mul_v3_fl(&vert_vel[i * 3], sds->dx / dt); + } + copy_v3_v3(&scs->verts_old[i * 3], co); + } + + if (bvhtree_from_mesh_faces(&treeData, dm, 0.0f, 4, 6)) { + #pragma omp parallel for schedule(static) + for (z = sds->res_min[2]; z < sds->res_max[2]; z++) { + int x, 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++) { + int index = smoke_get_index(x - sds->res_min[0], sds->res[0], y - sds->res_min[1], sds->res[1], z - sds->res_min[2]); + + float ray_start[3] = {(float)x + 0.5f, (float)y + 0.5f, (float)z + 0.5f}; + BVHTreeNearest nearest = {0}; + nearest.index = -1; + nearest.dist = surface_distance * surface_distance; /* find_nearest uses squared distance */ + + /* find the nearest point on the mesh */ + if (BLI_bvhtree_find_nearest(treeData.tree, ray_start, &nearest, treeData.nearest_callback, &treeData) != -1) { + float weights[4]; + int v1, v2, v3, f_index = nearest.index; + + /* calculate barycentric weights for nearest point */ + v1 = mface[f_index].v1; + v2 = (nearest.flags & BVH_ONQUAD) ? mface[f_index].v3 : mface[f_index].v2; + v3 = (nearest.flags & BVH_ONQUAD) ? mface[f_index].v4 : mface[f_index].v3; + interp_weights_face_v3(weights, mvert[v1].co, mvert[v2].co, mvert[v3].co, NULL, nearest.co); + + // DG TODO + if (has_velocity) + { + /* apply object velocity */ + { + float hit_vel[3]; + interp_v3_v3v3v3(hit_vel, &vert_vel[v1 * 3], &vert_vel[v2 * 3], &vert_vel[v3 * 3], weights); + velocityX[index] += hit_vel[0]; + velocityY[index] += hit_vel[1]; + velocityZ[index] += hit_vel[2]; + } + } - // TODO: only something to do for ANIMATED obstacles: need to update positions + /* tag obstacle cells */ + obstacle_map[index] = 1; + if (has_velocity) + obstacle_map[index] |= 8; + } + } } } + /* free bvh tree */ + free_bvhtree_from_mesh(&treeData); + dm->release(dm); - if(collobjs) - MEM_freeN(collobjs); + if (vert_vel) MEM_freeN(vert_vel); } - -#endif } /* Animated obstacles: dx_step = ((x_new - x_old) / totalsteps) * substep */ -static void update_obstacles(Scene *scene, Object *ob, SmokeDomainSettings *sds, float dt, int substep, int totalsteps) +static void update_obstacles(Scene *scene, Object *ob, SmokeDomainSettings *sds, float dt, + int UNUSED(substep), int UNUSED(totalsteps)) { Object **collobjs = NULL; unsigned int numcollobj = 0; @@ -1092,24 +811,20 @@ static void update_obstacles(Scene *scene, Object *ob, SmokeDomainSettings *sds, float *velxOrig = smoke_get_velocity_x(sds->fluid); float *velyOrig = smoke_get_velocity_y(sds->fluid); float *velzOrig = smoke_get_velocity_z(sds->fluid); - // float *density = smoke_get_density(sds->fluid); + float *density = smoke_get_density(sds->fluid); + float *fuel = smoke_get_fuel(sds->fluid); + float *flame = smoke_get_flame(sds->fluid); + float *r = smoke_get_color_r(sds->fluid); + float *g = smoke_get_color_g(sds->fluid); + float *b = smoke_get_color_b(sds->fluid); unsigned int z; smoke_get_ob_velocity(sds->fluid, &velx, &vely, &velz); // TODO: delete old obstacle flags - for(z = 0; z < sds->res[0] * sds->res[1] * sds->res[2]; z++) + for (z = 0; z < sds->res[0] * sds->res[1] * sds->res[2]; z++) { - if(obstacles[z]) - { - // density[z] = 0; - - velxOrig[z] = 0; - velyOrig[z] = 0; - velzOrig[z] = 0; - } - - if(obstacles[z] & 8) // Do not delete static obstacles + if (obstacles[z] & 8) // Do not delete static obstacles { obstacles[z] = 0; } @@ -1119,410 +834,1064 @@ static void update_obstacles(Scene *scene, Object *ob, SmokeDomainSettings *sds, velz[z] = 0; } + collobjs = get_collisionobjects(scene, ob, sds->coll_group, &numcollobj, eModifierType_Smoke); // update obstacle tags in cells - for(collIndex = 0; collIndex < numcollobj; collIndex++) + for (collIndex = 0; collIndex < numcollobj; collIndex++) { - Object *collob= collobjs[collIndex]; - SmokeModifierData *smd2 = (SmokeModifierData*)modifiers_findByType(collob, eModifierType_Smoke); + Object *collob = collobjs[collIndex]; + SmokeModifierData *smd2 = (SmokeModifierData *)modifiers_findByType(collob, eModifierType_Smoke); // DG TODO: check if modifier is active? - - if((smd2->type & MOD_SMOKE_TYPE_COLL) && smd2->coll && smd2->coll->points && smd2->coll->points_old) + + if ((smd2->type & MOD_SMOKE_TYPE_COLL) && smd2->coll) { SmokeCollSettings *scs = smd2->coll; - unsigned int i; + obstacles_from_derivedmesh(collob, sds, scs, obstacles, velx, vely, velz, dt); + } + } + + if (collobjs) + MEM_freeN(collobjs); + + /* obstacle cells should not contain any velocity from the smoke simulation */ + for (z = 0; z < sds->res[0] * sds->res[1] * sds->res[2]; z++) + { + if (obstacles[z]) + { + velxOrig[z] = 0; + velyOrig[z] = 0; + velzOrig[z] = 0; + density[z] = 0; + if (fuel) { + fuel[z] = 0; + flame[z] = 0; + } + if (r) { + r[z] = 0; + g[z] = 0; + b[z] = 0; + } + } + } +} - /* - // DG TODO: support static cobstacles, but basicly we could even support static + rigid with one set of code - if(scs->type > SM_COLL_STATIC) - */ - /* Handle collisions */ - for(i = 0; i < scs->numpoints; i++) +typedef struct EmissionMap { + float *influence; + float *velocity; + int min[3], max[3], res[3]; + int total_cells, valid; +} EmissionMap; + +static void em_boundInsert(EmissionMap *em, float point[3]) +{ + int i = 0; + if (!em->valid) { + VECCOPY(em->min, point); + VECCOPY(em->max, point); + em->valid = 1; + } + else { + for (; i < 3; i++) { + if (point[i] < em->min[i]) em->min[i] = (int)floor(point[i]); + if (point[i] > em->max[i]) em->max[i] = (int)ceil(point[i]); + } + } +} + +static void clampBoundsInDomain(SmokeDomainSettings *sds, int min[3], int max[3], float *min_vel, float *max_vel, int margin, float dt) +{ + int i; + for (i = 0; i < 3; i++) { + int adapt = (sds->flags & MOD_SMOKE_ADAPTIVE_DOMAIN) ? sds->adapt_res : 0; + /* add margin */ + min[i] -= margin; + max[i] += margin; + + /* adapt to velocity */ + if (min_vel && min_vel[i] < 0.0f) { + min[i] += (int)ceil(min_vel[i] * dt); + } + if (max_vel && max_vel[i] > 0.0f) { + max[i] += (int)ceil(max_vel[i] * dt); + } + + /* clamp within domain max size */ + CLAMP(min[i], -adapt, sds->base_res[i] + adapt); + CLAMP(max[i], -adapt, sds->base_res[i] + adapt); + } +} + +static void em_allocateData(EmissionMap *em, int use_velocity) { + int i, res[3]; + + for (i = 0; i < 3; i++) { + res[i] = em->max[i] - em->min[i]; + 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) + em->velocity = MEM_callocN(sizeof(float) * em->total_cells * 3, "smoke_flow_velocity"); +} + +static void em_freeData(EmissionMap *em) { + if (em->influence) + MEM_freeN(em->influence); + if (em->velocity) + MEM_freeN(em->velocity); +} + + +static void emit_from_particles(Object *flow_ob, SmokeDomainSettings *sds, SmokeFlowSettings *sfs, EmissionMap *em, Scene *scene, float time, float dt) +{ + if (sfs && sfs->psys && sfs->psys->part && ELEM(sfs->psys->part->type, PART_EMITTER, PART_FLUID)) // is particle system selected + { + ParticleSimulationData sim; + ParticleSystem *psys = sfs->psys; + float *particle_pos; + float *particle_vel; + int totpart = psys->totpart, totchild; + int p = 0; + int valid_particles = 0; + + sim.scene = scene; + sim.ob = flow_ob; + sim.psys = psys; + + if (psys->part->type == PART_HAIR) + { + // TODO: PART_HAIR not supported whatsoever + totchild = 0; + } + else + totchild = psys->totchild * psys->part->disp / 100; + + particle_pos = MEM_callocN(sizeof(float) * (totpart + totchild) * 3, "smoke_flow_particles"); + particle_vel = MEM_callocN(sizeof(float) * (totpart + totchild) * 3, "smoke_flow_particles"); + + /* calculate local position for each particle */ + for (p = 0; p < totpart + totchild; p++) + { + ParticleKey state; + float *pos; + if (p < totpart) { + 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)) + continue; + } + + state.time = time; + if (psys_get_particle_state(&sim, p, &state, 0) == 0) + continue; + + /* location */ + pos = &particle_pos[valid_particles * 3]; + copy_v3_v3(pos, state.co); + smoke_pos_to_cell(sds, pos); + + /* velocity */ + copy_v3_v3(&particle_vel[valid_particles * 3], state.vel); + mul_mat3_m4_v3(sds->imat, &particle_vel[valid_particles * 3]); + + /* calculate emission map bounds */ + em_boundInsert(em, pos); + valid_particles++; + } + + /* set emission map */ + clampBoundsInDomain(sds, em->min, em->max, NULL, NULL, 1, dt); + em_allocateData(em, sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY); + + for (p = 0; p < valid_particles; p++) + { + int cell[3]; + size_t i = 0; + size_t index = 0; + int badcell = 0; + + /* 1. get corresponding cell */ + cell[0] = floor(particle_pos[p * 3]) - em->min[0]; + cell[1] = floor(particle_pos[p * 3 + 1]) - em->min[1]; + cell[2] = floor(particle_pos[p * 3 + 2]) - em->min[2]; + /* check if cell is valid (in the domain boundary) */ + for (i = 0; i < 3; i++) { + if ((cell[i] > em->res[i] - 1) || (cell[i] < 0)) { + badcell = 1; + break; + } + } + 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 */ + em->influence[index] = 1.0f; + /* Uses particle velocity as initial velocity for smoke */ + if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY && (psys->part->phystype != PART_PHYS_NO)) { - // 1. get corresponding cell - int cell[3]; - float pos[3], oldpos[3], vel[3]; - float cPos[3], cOldpos[3]; /* current position in substeps */ - int badcell = 0; - size_t index; - int j; - - // translate local points into global positions - copy_v3_v3(cPos, &scs->points[3 * i]); - mul_m4_v3(scs->mat, cPos); - copy_v3_v3(pos, cPos); - - copy_v3_v3(cOldpos, &scs->points_old[3 * i]); - mul_m4_v3(scs->mat_old, cOldpos); - copy_v3_v3(oldpos, cOldpos); - - /* support for rigid bodies, armatures etc */ - { - float tmp[3]; + VECADDFAC(&em->velocity[index * 3], &em->velocity[index * 3], &particle_vel[p * 3], sfs->vel_multi); + } + } // particles loop + + /* free data */ + if (particle_pos) + MEM_freeN(particle_pos); + if (particle_vel) + MEM_freeN(particle_vel); + } +} + +static void get_texture_value(Tex *texture, float tex_co[3], TexResult *texres) +{ + int result_type; - /* x_current = x_old + (x_new - x_old) * step_current / steps_total */ - float mulStep = (float)(((float)substep) / ((float)totalsteps)); + /* no node textures for now */ + result_type = multitex_ext_safe(texture, tex_co, texres); + + /* if the texture gave an RGB value, we assume it didn't give a valid + * intensity, since this is in the context of modifiers don't use perceptual color conversion. + * if the texture didn't give an RGB value, copy the intensity across + */ + if (result_type & TEX_RGB) { + texres->tin = (1.0f / 3.0f) * (texres->tr + texres->tg + texres->tb); + } + else { + copy_v3_fl(&texres->tr, texres->tin); + } +} + +static void emit_from_derivedmesh(Object *flow_ob, SmokeDomainSettings *sds, SmokeFlowSettings *sfs, EmissionMap *em, float dt) +{ + if (!sfs->dm) return; + { + DerivedMesh *dm = sfs->dm; + int defgrp_index = sfs->vgroup_density - 1; + MDeformVert *dvert = NULL; + MVert *mvert = NULL; + MVert *mvert_orig = NULL; + MFace *mface = NULL; + MTFace *tface = NULL; + BVHTreeFromMesh treeData = {0}; + int numOfVerts, i, z; + float flow_center[3] = {0}; + + float *vert_vel = NULL; + int has_velocity = 0; + + CDDM_calc_normals(dm); + mvert = dm->getVertArray(dm); + mvert_orig = dm->dupVertArray(dm); /* copy original mvert and restore when done */ + mface = dm->getTessFaceArray(dm); + numOfVerts = dm->getNumVerts(dm); + dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT); + tface = CustomData_get_layer_named(&dm->faceData, CD_MTFACE, sfs->uvlayer_name); + + if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY) { + vert_vel = MEM_callocN(sizeof(float) * numOfVerts * 3, "smoke_flow_velocity"); + + if (sfs->numverts != numOfVerts || !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; + } + else { + has_velocity = 1; + } + } - sub_v3_v3v3(tmp, cPos, cOldpos); - mul_v3_fl(tmp, mulStep); - add_v3_v3(cOldpos, tmp); + /* Transform dm vertices to + * domain grid space for fast lookups */ + for (i = 0; i < numOfVerts; i++) { + float n[3]; + /* vert pos */ + mul_m4_v3(flow_ob->obmat, mvert[i].co); + smoke_pos_to_cell(sds, mvert[i].co); + /* vert normal */ + normal_short_to_float_v3(n, mvert[i].no); + mul_mat3_m4_v3(flow_ob->obmat, n); + mul_mat3_m4_v3(sds->imat, n); + normalize_v3(n); + normal_float_to_short_v3(mvert[i].no, n); + /* vert velocity */ + if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY) { + float co[3]; + VECADD(co, mvert[i].co, sds->shift); + if (has_velocity) { + sub_v3_v3v3(&vert_vel[i * 3], co, &sfs->verts_old[i * 3]); + mul_v3_fl(&vert_vel[i * 3], sds->dx / dt); } + copy_v3_v3(&sfs->verts_old[i * 3], co); + } - sub_v3_v3v3(vel, pos, oldpos); - /* Scale velocity to incorperate the object movement during this step */ - mul_v3_fl(vel, 1.0 / (totalsteps * dt * sds->scale)); - // mul_v3_fl(vel, 1.0 / dt); + /* calculate emission map bounds */ + em_boundInsert(em, mvert[i].co); + } + mul_m4_v3(flow_ob->obmat, flow_center); + smoke_pos_to_cell(sds, flow_center); + + /* set emission map */ + clampBoundsInDomain(sds, em->min, em->max, NULL, NULL, sfs->surface_distance, dt); + em_allocateData(em, sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY); + + if (bvhtree_from_mesh_faces(&treeData, dm, 0.0f, 4, 6)) { + #pragma omp parallel for schedule(static) + for (z = em->min[2]; z < em->max[2]; z++) { + int x, y; + for (x = em->min[0]; x < em->max[0]; x++) + for (y = em->min[1]; y < em->max[1]; y++) { + int index = smoke_get_index(x - em->min[0], em->res[0], y - em->min[1], em->res[1], z - em->min[2]); + + float ray_start[3] = {(float)x + 0.5f, (float)y + 0.5f, (float)z + 0.5f}; + float ray_dir[3] = {1.0f, 0.0f, 0.0f}; + + BVHTreeRayHit hit = {0}; + BVHTreeNearest nearest = {0}; + + float volume_factor = 0.0f; + float sample_str = 0.0f; + + hit.index = -1; + hit.dist = 9999; + nearest.index = -1; + nearest.dist = sfs->surface_distance * sfs->surface_distance; /* find_nearest uses squared distance */ + + /* Check volume collision */ + if (sfs->volume_density) { + if (BLI_bvhtree_ray_cast(treeData.tree, ray_start, ray_dir, 0.0f, &hit, treeData.raycast_callback, &treeData) != -1) { + float dot = ray_dir[0] * hit.no[0] + ray_dir[1] * hit.no[1] + ray_dir[2] * hit.no[2]; + /* If ray and hit face normal are facing same direction + * hit point is inside a closed mesh. */ + if (dot >= 0) { + /* Also cast a ray in opposite direction to make sure + * point is at least surrounded by two faces */ + negate_v3(ray_dir); + hit.index = -1; + hit.dist = 9999; + + BLI_bvhtree_ray_cast(treeData.tree, ray_start, ray_dir, 0.0f, &hit, treeData.raycast_callback, &treeData); + if (hit.index != -1) { + volume_factor = sfs->volume_density; + nearest.dist = hit.dist * hit.dist; + } + } + } + } - // DG TODO: cap velocity to maxVelMag (or maxvel) + /* find the nearest point on the mesh */ + if (BLI_bvhtree_find_nearest(treeData.tree, ray_start, &nearest, treeData.nearest_callback, &treeData) != -1) { + float weights[4]; + int v1, v2, v3, f_index = nearest.index; + float n1[3], n2[3], n3[3], hit_normal[3]; + + /* emit from surface based on distance */ + if (sfs->surface_distance) { + sample_str = sqrtf(nearest.dist) / sfs->surface_distance; + CLAMP(sample_str, 0.0f, 1.0f); + sample_str = pow(1.0f - sample_str, 0.5f); + } + else + sample_str = 0.0f; + + /* calculate barycentric weights for nearest point */ + v1 = mface[f_index].v1; + v2 = (nearest.flags & BVH_ONQUAD) ? mface[f_index].v3 : mface[f_index].v2; + v3 = (nearest.flags & BVH_ONQUAD) ? mface[f_index].v4 : mface[f_index].v3; + interp_weights_face_v3(weights, mvert[v1].co, mvert[v2].co, mvert[v3].co, NULL, nearest.co); + + if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY) { + /* apply normal directional velocity */ + if (sfs->vel_normal) { + /* interpolate vertex normal vectors to get nearest point normal */ + normal_short_to_float_v3(n1, mvert[v1].no); + normal_short_to_float_v3(n2, mvert[v2].no); + normal_short_to_float_v3(n3, mvert[v3].no); + 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 doesnt really work well as pressure calc smoothens it out... */ + em->velocity[index * 3] += hit_normal[0] * sfs->vel_normal * 0.25f; + em->velocity[index * 3 + 1] += hit_normal[1] * sfs->vel_normal * 0.25f; + em->velocity[index * 3 + 2] += hit_normal[2] * sfs->vel_normal * 0.25f; + /* TODO: for fire emitted from mesh surface we can use + * Vf = Vs + (Ps/Pf - 1)*S to model gaseous expansion from solid to fuel */ + } + /* apply object velocity */ + if (has_velocity && sfs->vel_multi) { + float hit_vel[3]; + interp_v3_v3v3v3(hit_vel, &vert_vel[v1 * 3], &vert_vel[v2 * 3], &vert_vel[v3 * 3], weights); + em->velocity[index * 3] += hit_vel[0] * sfs->vel_multi; + em->velocity[index * 3 + 1] += hit_vel[1] * sfs->vel_multi; + em->velocity[index * 3 + 2] += hit_vel[2] * sfs->vel_multi; + } + } + + /* apply vertex group influence if used */ + if (defgrp_index != -1 && dvert) { + float weight_mask = defvert_find_weight(&dvert[v1], defgrp_index) * weights[0] + + defvert_find_weight(&dvert[v2], defgrp_index) * weights[1] + + defvert_find_weight(&dvert[v3], defgrp_index) * weights[2]; + sample_str *= weight_mask; + } + + /* apply emission texture */ + if ((sfs->flags & MOD_SMOKE_FLOW_TEXTUREEMIT) && sfs->noise_texture) { + float tex_co[3] = {0}; + TexResult texres; + + if (sfs->texture_type == MOD_SMOKE_FLOW_TEXTURE_MAP_AUTO) { + tex_co[0] = ((float)(x - flow_center[0]) / sds->base_res[0]) / sfs->texture_size; + tex_co[1] = ((float)(y - flow_center[1]) / sds->base_res[1]) / sfs->texture_size; + tex_co[2] = ((float)(z - flow_center[2]) / sds->base_res[2] - sfs->texture_offset) / sfs->texture_size; + } + else if (tface) { + interp_v2_v2v2v2(tex_co, tface[f_index].uv[0], tface[f_index].uv[(nearest.flags & BVH_ONQUAD) ? 2 : 1], + tface[f_index].uv[(nearest.flags & BVH_ONQUAD) ? 3 : 2], weights); + /* map between -1.0f and 1.0f */ + tex_co[0] = tex_co[0] * 2.0f - 1.0f; + tex_co[1] = tex_co[1] * 2.0f - 1.0f; + tex_co[2] = sfs->texture_offset; + } + texres.nor = NULL; + get_texture_value(sfs->noise_texture, tex_co, &texres); + sample_str *= texres.tin; + } + } - // oldpos + velocity * dt = newpos - get_cell(sds->p0, sds->res, sds->dx*sds->scale, cOldpos /* use current position here instead of "pos" */, cell, 0); + /* multiply initial velocity by emitter influence */ + if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY) { + mul_v3_fl(&em->velocity[index * 3], sample_str); + } - // check if cell is valid (in the domain boundary) - for(j = 0; j < 3; j++) - if((cell[j] > sds->res[j] - 1) || (cell[j] < 0)) - { - badcell = 1; - break; + /* apply final influence based on volume factor */ + em->influence[index] = MAX2(volume_factor, sample_str); } - - if(badcell) - continue; + } + } + /* free bvh tree */ + free_bvhtree_from_mesh(&treeData); + /* restore original mverts */ + CustomData_set_layer(&dm->vertData, CD_MVERT, mvert_orig); + if (mvert) + MEM_freeN(mvert); + + if (vert_vel) MEM_freeN(vert_vel); + } +} - // 2. set cell values (heat, density and velocity) - index = smoke_get_index(cell[0], sds->res[0], cell[1], sds->res[1], cell[2]); +static void adjustDomainResolution(SmokeDomainSettings *sds, int new_shift[3], EmissionMap *emaps, unsigned int numflowobj, float dt) +{ + int min[3] = {32767, 32767, 32767}, max[3] = {-32767, -32767, -32767}, res[3]; + int total_cells = 1, res_changed = 0, shift_changed = 0; + float min_vel[3], max_vel[3]; + int x, y, z, i; + float *density = smoke_get_density(sds->fluid); + float *fuel = smoke_get_fuel(sds->fluid); + float *vx = smoke_get_velocity_x(sds->fluid); + float *vy = smoke_get_velocity_y(sds->fluid); + float *vz = smoke_get_velocity_z(sds->fluid); + + 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 (z = sds->res_min[2]; z < sds->res_max[2]; z++) + { + int xn = x - new_shift[0]; + int yn = y - new_shift[1]; + int zn = z - new_shift[2]; + int index = smoke_get_index(x - sds->res_min[0], sds->res[0], y - sds->res_min[1], sds->res[1], z - sds->res_min[2]); + float max_den = (fuel) ? MAX2(density[index], fuel[index]) : density[index]; + + /* content bounds (use shifted coordinates) */ + if (max_den >= sds->adapt_threshold) { + if (min[0] > xn) min[0] = xn; + if (min[1] > yn) min[1] = yn; + if (min[2] > zn) min[2] = zn; + if (max[0] < xn) max[0] = xn; + if (max[1] < yn) max[1] = yn; + if (max[2] < zn) max[2] = zn; + } + /* velocity bounds */ + if (min_vel[0] > vx[index]) min_vel[0] = vx[index]; + if (min_vel[1] > vy[index]) min_vel[1] = vy[index]; + if (min_vel[2] > vz[index]) min_vel[2] = vz[index]; + if (max_vel[0] < vx[index]) max_vel[0] = vx[index]; + if (max_vel[1] < vy[index]) max_vel[1] = vy[index]; + if (max_vel[2] < vz[index]) max_vel[2] = vz[index]; + } - // Don't overwrite existing obstacles - if(obstacles[index]) - continue; - - // printf("cell[0]: %d, cell[1]: %d, cell[2]: %d\n", cell[0], cell[1], cell[2]); - // printf("res[0]: %d, res[1]: %d, res[2]: %d, index: %d\n\n", sds->res[0], sds->res[1], sds->res[2], index); - obstacles[index] = 1 | 8 /* ANIMATED */; + /* also apply emission maps */ + for (i = 0; i < numflowobj; i++) + { + EmissionMap *em = &emaps[i]; - if(len_v3(vel) > FLT_EPSILON) + 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++) { - // Collision object is moving - - velx[index] = vel[0]; // use "+="? - vely[index] = vel[1]; - velz[index] = vel[2]; + int index = smoke_get_index(x - em->min[0], em->res[0], y - em->min[1], em->res[1], z - em->min[2]); + float max_den = em->influence[index]; + + /* density bounds */ + if (max_den >= sds->adapt_threshold) { + if (min[0] > x) min[0] = x; + if (min[1] > y) min[1] = y; + if (min[2] > z) min[2] = z; + if (max[0] < x) max[0] = x; + if (max[1] < y) max[1] = y; + if (max[2] < z) max[2] = z; + } + /* velocity bounds */ + if (em->velocity) { + if (min_vel[0] > em->velocity[index * 3]) min_vel[0] = em->velocity[index * 3]; + if (min_vel[1] > em->velocity[index * 3 + 1]) min_vel[1] = em->velocity[index * 3 + 1]; + if (min_vel[2] > em->velocity[index * 3 + 2]) min_vel[2] = em->velocity[index * 3 + 2]; + if (max_vel[0] < em->velocity[index * 3]) max_vel[0] = em->velocity[index * 3]; + if (max_vel[1] < em->velocity[index * 3 + 1]) max_vel[1] = em->velocity[index * 3 + 1]; + if (max_vel[2] < em->velocity[index * 3 + 2]) max_vel[2] = em->velocity[index * 3 + 2]; + } } + } + + /* calculate new bounds based on these values */ + clampBoundsInDomain(sds, min, max, min_vel, max_vel, sds->adapt_margin + 1, dt); + + for (i = 0; i < 3; i++) { + /* calculate new resolution */ + res[i] = max[i] - min[i]; + total_cells *= res[i]; + + if (new_shift[i]) + shift_changed = 1; + + /* if no content set minimum dimensions */ + if (res[i] <= 0) { + int j; + for (j = 0; j < 3; j++) { + min[j] = 0; + max[j] = 1; + res[j] = 1; } + res_changed = 1; + total_cells = 1; + break; } + if (min[i] != sds->res_min[i] || max[i] != sds->res_max[i]) + res_changed = 1; } - if(collobjs) - MEM_freeN(collobjs); + if (res_changed || shift_changed) { + struct FLUID_3D *fluid_old = sds->fluid; + struct WTURBULENCE *turb_old = sds->wt; + /* allocate new fluid data */ + smoke_reallocate_fluid(sds, sds->dx, res, 0); + if (sds->flags & MOD_SMOKE_HIGHRES) { + smoke_reallocate_highres_fluid(sds, sds->dx, res, 0); + } + + /* copy values from old fluid to new */ + if (sds->total_cells > 1 && total_cells > 1) { + /* low res smoke */ + float *o_dens, *o_react, *o_flame, *o_fuel, *o_heat, *o_heatold, *o_vx, *o_vy, *o_vz, *o_r, *o_g, *o_b; + float *n_dens, *n_react, *n_flame, *n_fuel, *n_heat, *n_heatold, *n_vx, *n_vy, *n_vz, *n_r, *n_g, *n_b; + float dummy; + unsigned char *dummy_p; + /* high res smoke */ + int wt_res_old[3]; + float *o_wt_dens, *o_wt_react, *o_wt_flame, *o_wt_fuel, *o_wt_tcu, *o_wt_tcv, *o_wt_tcw, *o_wt_r, *o_wt_g, *o_wt_b; + float *n_wt_dens, *n_wt_react, *n_wt_flame, *n_wt_fuel, *n_wt_tcu, *n_wt_tcv, *n_wt_tcw, *n_wt_r, *n_wt_g, *n_wt_b; + + smoke_export(fluid_old, &dummy, &dummy, &o_dens, &o_react, &o_flame, &o_fuel, &o_heat, &o_heatold, &o_vx, &o_vy, &o_vz, &o_r, &o_g, &o_b, &dummy_p); + smoke_export(sds->fluid, &dummy, &dummy, &n_dens, &n_react, &n_flame, &n_fuel, &n_heat, &n_heatold, &n_vx, &n_vy, &n_vz, &n_r, &n_g, &n_b, &dummy_p); + + if (sds->flags & MOD_SMOKE_HIGHRES) { + smoke_turbulence_export(turb_old, &o_wt_dens, &o_wt_react, &o_wt_flame, &o_wt_fuel, &o_wt_r, &o_wt_g, &o_wt_b, &o_wt_tcu, &o_wt_tcv, &o_wt_tcw); + smoke_turbulence_get_res(turb_old, wt_res_old); + smoke_turbulence_export(sds->wt, &n_wt_dens, &n_wt_react, &n_wt_flame, &n_wt_fuel, &n_wt_r, &n_wt_g, &n_wt_b, &n_wt_tcu, &n_wt_tcv, &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 (z = sds->res_min[2]; z < sds->res_max[2]; z++) + { + /* old grid index */ + int xo = x - sds->res_min[0]; + int yo = y - sds->res_min[1]; + int zo = z - sds->res_min[2]; + int index_old = smoke_get_index(xo, sds->res[0], yo, sds->res[1], zo); + /* new grid index */ + int xn = x - min[0] - new_shift[0]; + int yn = y - min[1] - new_shift[1]; + int zn = z - min[2] - new_shift[2]; + 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]) + continue; + + /* copy data */ + n_dens[index_new] = o_dens[index_old]; + /* heat */ + if (n_heat && o_heat) { + n_heat[index_new] = o_heat[index_old]; + n_heatold[index_new] = o_heatold[index_old]; + } + /* fuel */ + if (n_fuel && o_fuel) { + n_flame[index_new] = o_flame[index_old]; + n_fuel[index_new] = o_fuel[index_old]; + n_react[index_new] = o_react[index_old]; + } + /* color */ + if (o_r && n_r) { + n_r[index_new] = o_r[index_old]; + n_g[index_new] = o_g[index_old]; + n_b[index_new] = o_b[index_old]; + } + n_vx[index_new] = o_vx[index_old]; + n_vy[index_new] = o_vy[index_old]; + n_vz[index_new] = o_vz[index_old]; + + if (sds->flags & MOD_SMOKE_HIGHRES && turb_old) { + int block_size = sds->amplify + 1; + int i, j, k; + /* old grid index */ + int xx_o = xo * block_size; + int yy_o = yo * block_size; + int zz_o = zo * block_size; + /* new grid index */ + int xx_n = xn * block_size; + int yy_n = yn * block_size; + int zz_n = zn * block_size; + + n_wt_tcu[index_new] = o_wt_tcu[index_old]; + 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 (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); + int big_index_new = smoke_get_index(xx_n + i, sds->res_wt[0], yy_n + j, sds->res_wt[1], zz_n + k); + /* copy data */ + n_wt_dens[big_index_new] = o_wt_dens[big_index_old]; + if (n_wt_flame && o_wt_flame) { + n_wt_flame[big_index_new] = o_wt_flame[big_index_old]; + n_wt_fuel[big_index_new] = o_wt_fuel[big_index_old]; + n_wt_react[big_index_new] = o_wt_react[big_index_old]; + } + if (n_wt_r && o_wt_r) { + n_wt_r[big_index_new] = o_wt_r[big_index_old]; + n_wt_g[big_index_new] = o_wt_g[big_index_old]; + n_wt_b[big_index_new] = o_wt_b[big_index_old]; + } + } + } + } + } + smoke_free(fluid_old); + if (turb_old) + smoke_turbulence_free(turb_old); + + /* set new domain dimensions */ + VECCOPY(sds->res_min, min); + VECCOPY(sds->res_max, max); + VECCOPY(sds->res, res); + sds->total_cells = total_cells; + } +} + +BLI_INLINE void apply_outflow_fields(int index, float *density, float *heat, float *fuel, float *react, float *color_r, float *color_g, float *color_b) +{ + density[index] = 0.f; + if (heat) { + heat[index] = 0.f; + } + if (fuel) { + fuel[index] = 0.f; + react[index] = 0.f; + } + if (color_r) { + color_r[index] = 0.f; + color_g[index] = 0.f; + color_b[index] = 0.f; + } +} + +BLI_INLINE void apply_inflow_fields(SmokeFlowSettings *sfs, float emission_value, int index, float *density, float *heat, float *fuel, float *react, float *color_r, float *color_g, float *color_b) +{ + int absolute_flow = (sfs->flags & MOD_SMOKE_FLOW_ABSOLUTE); + float dens_old = density[index]; + // float fuel_old = (fuel) ? fuel[index] : 0.0f; /* UNUSED */ + float dens_flow = (sfs->type == MOD_SMOKE_FLOW_TYPE_FIRE) ? 0.0f : emission_value * sfs->density; + float fuel_flow = emission_value * sfs->fuel_amount; + /* add heat */ + if (heat) { + heat[index] = MAX2(emission_value * sfs->temp, heat[index]); + } + /* absolute */ + if (absolute_flow) { + if (sfs->type != MOD_SMOKE_FLOW_TYPE_FIRE) { + 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]) + fuel[index] = fuel_flow; + } + } + /* additive */ + else { + if (sfs->type != MOD_SMOKE_FLOW_TYPE_FIRE) { + density[index] += dens_flow; + CLAMP(density[index], 0.0f, 1.0f); + } + if (sfs->type != MOD_SMOKE_FLOW_TYPE_SMOKE && fuel && sfs->fuel_amount) { + fuel[index] += fuel_flow; + CLAMP(fuel[index], 0.0f, 10.0f); + } + } + + /* set color */ + if (color_r && dens_flow) { + float total_dens = density[index] / (dens_old + dens_flow); + color_r[index] = (color_r[index] + sfs->color[0] * dens_flow) * total_dens; + color_g[index] = (color_g[index] + sfs->color[1] * dens_flow) * total_dens; + color_b[index] = (color_b[index] + sfs->color[2] * dens_flow) * total_dens; + } + + /* set fire reaction coordinate */ + if (fuel && fuel[index]) { + /* instead of using 1.0 for all new fuel add slight falloff + * to reduce flow blockiness */ + float value = 1.0f - powf(1.0f - emission_value, 2.0f); + + if (value > react[index]) { + float f = fuel_flow / fuel[index]; + react[index] = value * f + (1.0f - f) * react[index]; + } + } } -static void update_flowsfluids(Scene *scene, Object *ob, SmokeDomainSettings *sds, float time) +static void update_flowsfluids(Scene *scene, Object *ob, SmokeDomainSettings *sds, float time, float dt) { Object **flowobjs = NULL; + EmissionMap *emaps = NULL; unsigned int numflowobj = 0; unsigned int flowIndex; + int new_shift[3] = {0}; + int active_fields = sds->active_fields; + + /* calculate domain shift for current frame if using adaptive domain */ + if (sds->flags & MOD_SMOKE_ADAPTIVE_DOMAIN) { + int total_shift[3]; + float frame_shift_f[3]; + float ob_loc[3] = {0}; + + mul_m4_v3(ob->obmat, ob_loc); + + VECSUB(frame_shift_f, ob_loc, sds->prev_loc); + copy_v3_v3(sds->prev_loc, ob_loc); + /* convert global space shift to local "cell" space */ + mul_mat3_m4_v3(sds->imat, frame_shift_f); + frame_shift_f[0] = frame_shift_f[0] / sds->cell_size[0]; + frame_shift_f[1] = frame_shift_f[1] / sds->cell_size[1]; + frame_shift_f[2] = frame_shift_f[2] / sds->cell_size[2]; + /* add to total shift */ + VECADD(sds->shift_f, sds->shift_f, frame_shift_f); + /* convert to integer */ + total_shift[0] = floor(sds->shift_f[0]); + total_shift[1] = floor(sds->shift_f[1]); + total_shift[2] = floor(sds->shift_f[2]); + VECSUB(new_shift, total_shift, sds->shift); + copy_v3_v3_int(sds->shift, total_shift); + + /* calculate new domain boundary points so that smoke doesnt slide on sub-cell movement */ + sds->p0[0] = sds->dp0[0] - sds->cell_size[0] * (sds->shift_f[0] - total_shift[0] - 0.5f); + sds->p0[1] = sds->dp0[1] - sds->cell_size[1] * (sds->shift_f[1] - total_shift[1] - 0.5f); + sds->p0[2] = sds->dp0[2] - sds->cell_size[2] * (sds->shift_f[2] - total_shift[2] - 0.5f); + sds->p1[0] = sds->p0[0] + sds->cell_size[0] * sds->base_res[0]; + sds->p1[1] = sds->p0[1] + sds->cell_size[1] * sds->base_res[1]; + sds->p1[2] = sds->p0[2] + sds->cell_size[2] * sds->base_res[2]; + } flowobjs = get_collisionobjects(scene, ob, sds->fluid_group, &numflowobj, eModifierType_Smoke); - // update obstacle tags in cells - for(flowIndex = 0; flowIndex < numflowobj; flowIndex++) + /* init emission maps for each flow */ + emaps = MEM_callocN(sizeof(struct EmissionMap) * numflowobj, "smoke_flow_maps"); + + /* Prepare flow emission maps */ + for (flowIndex = 0; flowIndex < numflowobj; flowIndex++) { - Object *collob= flowobjs[flowIndex]; - SmokeModifierData *smd2 = (SmokeModifierData*)modifiers_findByType(collob, eModifierType_Smoke); + Object *collob = flowobjs[flowIndex]; + SmokeModifierData *smd2 = (SmokeModifierData *)modifiers_findByType(collob, eModifierType_Smoke); // check for initialized smoke object - if((smd2->type & MOD_SMOKE_TYPE_FLOW) && smd2->flow) + if ((smd2->type & MOD_SMOKE_TYPE_FLOW) && smd2->flow) { // we got nice flow object SmokeFlowSettings *sfs = smd2->flow; + EmissionMap *em = &emaps[flowIndex]; - if(sfs && sfs->psys && sfs->psys->part && sfs->psys->part->type==PART_EMITTER) // is particle system selected - { - ParticleSimulationData sim; - ParticleSystem *psys = sfs->psys; - int totpart=psys->totpart, totchild; - int p = 0; - float *density = smoke_get_density(sds->fluid); - float *bigdensity = smoke_turbulence_get_density(sds->wt); - float *heat = smoke_get_heat(sds->fluid); - 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); - // DG TODO UNUSED unsigned char *obstacleAnim = smoke_get_obstacle_anim(sds->fluid); - int bigres[3]; - short absolute_flow = (sfs->flags & MOD_SMOKE_FLOW_ABSOLUTE); - short high_emission_smoothing = bigdensity ? (sds->flags & MOD_SMOKE_HIGH_SMOOTH) : 0; - - /* - * A temporary volume map used to store whole emissive - * area to be added to smoke density and interpolated - * for high resolution smoke. - */ - float *temp_emission_map = NULL; - - sim.scene = scene; - sim.ob = collob; - sim.psys = psys; - - // initialize temp emission map - if(!(sfs->type & MOD_SMOKE_FLOW_TYPE_OUTFLOW)) - { - int i; - temp_emission_map = MEM_callocN(sizeof(float) * sds->res[0]*sds->res[1]*sds->res[2], "SmokeTempEmission"); - // set whole volume to 0.0f - for (i=0; i<sds->res[0]*sds->res[1]*sds->res[2]; i++) { - temp_emission_map[i] = 0.0f; - } - } + if (sfs->source == MOD_SMOKE_FLOW_SOURCE_PARTICLES) { + emit_from_particles(collob, sds, sfs, em, scene, time, dt); + } + else { + emit_from_derivedmesh(collob, sds, sfs, em, dt); + } - // mostly copied from particle code - if(psys->part->type==PART_HAIR) - { - /* - if(psys->childcache) - { - totchild = psys->totchildcache; + /* update required data fields */ + if (em->total_cells && sfs->type != MOD_SMOKE_FLOW_TYPE_OUTFLOW) { + /* activate heat field if flow produces any heat */ + if (sfs->temp) { + active_fields |= SM_ACTIVE_HEAT; + } + /* activate fuel field if flow adds any fuel */ + if (sfs->type != MOD_SMOKE_FLOW_TYPE_SMOKE && sfs->fuel_amount) { + active_fields |= SM_ACTIVE_FIRE; + } + /* activate color field if flows add smoke with varying colors */ + if (sfs->type != MOD_SMOKE_FLOW_TYPE_FIRE && sfs->density) { + if (!(active_fields & SM_ACTIVE_COLOR_SET)) { + copy_v3_v3(sds->active_color, sfs->color); + active_fields |= SM_ACTIVE_COLOR_SET; + } + else if (!equals_v3v3(sds->active_color, sfs->color)) { + active_fields |= SM_ACTIVE_COLORS; } - else - */ - - // TODO: PART_HAIR not supported whatsoever - totchild=0; } - else - totchild=psys->totchild*psys->part->disp/100; + } + } + } - for(p=0; p<totpart+totchild; p++) - { - int cell[3]; - size_t i = 0; - size_t index = 0; - int badcell = 0; - ParticleKey state; + /* monitor active fields based on domain settings */ + /* if domain has fire, activate new fields if required */ + if (active_fields & SM_ACTIVE_FIRE) { + /* heat is always needed for fire */ + active_fields |= SM_ACTIVE_HEAT; + /* also activate colors if domain smoke color differs from active color */ + if (!(active_fields & SM_ACTIVE_COLOR_SET)) { + copy_v3_v3(sds->active_color, sds->flame_smoke_color); + active_fields |= SM_ACTIVE_COLOR_SET; + } + else if (!equals_v3v3(sds->active_color, sds->flame_smoke_color)) { + active_fields |= SM_ACTIVE_COLORS; + } + } - if(p < totpart) - { - if(psys->particles[p].flag & (PARS_NO_DISP|PARS_UNEXIST)) - continue; - } - else { - /* handle child particle */ - ChildParticle *cpa = &psys->child[p - totpart]; + /* Adjust domain size if needed */ + if (sds->flags & MOD_SMOKE_ADAPTIVE_DOMAIN) { + adjustDomainResolution(sds, new_shift, emaps, numflowobj, dt); + } - if(psys->particles[cpa->parent].flag & (PARS_NO_DISP|PARS_UNEXIST)) - continue; - } + /* Initialize new data fields if any */ + if (active_fields & SM_ACTIVE_HEAT) { + smoke_ensure_heat(sds->fluid); + } + if (active_fields & SM_ACTIVE_FIRE) { + smoke_ensure_fire(sds->fluid, sds->wt); + } + if (active_fields & SM_ACTIVE_COLORS) { + /* initialize all smoke with "active_color" */ + smoke_ensure_colors(sds->fluid, sds->wt, sds->active_color[0], sds->active_color[1], sds->active_color[2]); + } + sds->active_fields = active_fields; - state.time = time; - if(psys_get_particle_state(&sim, p, &state, 0) == 0) - continue; + /* Apply emission data */ + if (sds->fluid) { + for (flowIndex = 0; flowIndex < numflowobj; flowIndex++) + { + Object *collob = flowobjs[flowIndex]; + SmokeModifierData *smd2 = (SmokeModifierData *)modifiers_findByType(collob, eModifierType_Smoke); - // copy_v3_v3(pos, pa->state.co); - // mul_m4_v3(ob->imat, pos); - // 1. get corresponding cell - get_cell(sds->p0, sds->res, sds->dx*sds->scale, state.co, cell, 0); - // check if cell is valid (in the domain boundary) - for(i = 0; i < 3; i++) - { - if((cell[i] > sds->res[i] - 1) || (cell[i] < 0)) - { - badcell = 1; - break; - } - } - if(badcell) - continue; - // 2. set cell values (heat, density and velocity) - index = smoke_get_index(cell[0], sds->res[0], cell[1], sds->res[1], cell[2]); - if(!(sfs->type & MOD_SMOKE_FLOW_TYPE_OUTFLOW) && !(obstacle[index])) // this is inflow - { - // heat[index] += sfs->temp * 0.1; - // density[index] += sfs->density * 0.1; - heat[index] = sfs->temp; - - // Add emitter density to temp emission map - temp_emission_map[index] = sfs->density; - - // Uses particle velocity as initial velocity for smoke - if(sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY && (psys->part->phystype != PART_PHYS_NO)) - { - velocity_x[index] = state.vel[0]*sfs->vel_multi; - velocity_y[index] = state.vel[1]*sfs->vel_multi; - velocity_z[index] = state.vel[2]*sfs->vel_multi; - } - } - else if(sfs->type & MOD_SMOKE_FLOW_TYPE_OUTFLOW) // outflow - { - heat[index] = 0.f; - density[index] = 0.f; - velocity_x[index] = 0.f; - velocity_y[index] = 0.f; - velocity_z[index] = 0.f; - // we need different handling for the high-res feature - if(bigdensity) - { - // init all surrounding cells according to amplification, too - int i, j, k; - smoke_turbulence_get_res(sds->wt, bigres); - - for(i = 0; i < sds->amplify + 1; i++) - for(j = 0; j < sds->amplify + 1; j++) - for(k = 0; k < sds->amplify + 1; k++) - { - index = smoke_get_index((sds->amplify + 1)* cell[0] + i, bigres[0], (sds->amplify + 1)* cell[1] + j, bigres[1], (sds->amplify + 1)* cell[2] + k); - bigdensity[index] = 0.f; - } - } - } - } // particles loop + // check for initialized smoke object + if ((smd2->type & MOD_SMOKE_TYPE_FLOW) && smd2->flow) + { + // we got nice flow object + SmokeFlowSettings *sfs = smd2->flow; + EmissionMap *em = &emaps[flowIndex]; + + float *density = smoke_get_density(sds->fluid); + float *color_r = smoke_get_color_r(sds->fluid); + float *color_g = smoke_get_color_g(sds->fluid); + float *color_b = smoke_get_color_b(sds->fluid); + float *fuel = smoke_get_fuel(sds->fluid); + float *react = smoke_get_react(sds->fluid); + float *bigdensity = smoke_turbulence_get_density(sds->wt); + float *bigfuel = smoke_turbulence_get_fuel(sds->wt); + float *bigreact = smoke_turbulence_get_react(sds->wt); + float *bigcolor_r = smoke_turbulence_get_color_r(sds->wt); + float *bigcolor_g = smoke_turbulence_get_color_g(sds->wt); + float *bigcolor_b = smoke_turbulence_get_color_b(sds->wt); + float *heat = smoke_get_heat(sds->fluid); + 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); + // DG TODO UNUSED unsigned char *obstacleAnim = smoke_get_obstacle_anim(sds->fluid); + int bigres[3]; + short high_emission_smoothing = (sds->flags & MOD_SMOKE_HIGH_SMOOTH); + float *velocity_map = em->velocity; + float *emission_map = em->influence; - // apply emission values - if(!(sfs->type & MOD_SMOKE_FLOW_TYPE_OUTFLOW)) - { - // initialize variables - int ii, jj, kk, x, y, z, block_size; - size_t index, index_big; + int ii, jj, kk, gx, gy, gz, ex, ey, ez, dx, dy, dz, block_size; + size_t e_index, d_index, index_big; - smoke_turbulence_get_res(sds->wt, bigres); - block_size = sds->amplify + 1; // high res block size + // 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 (gz = em->min[2]; gz < em->max[2]; gz++) + { + /* get emission map index */ + ex = gx - em->min[0]; + ey = gy - em->min[1]; + ez = gz - em->min[2]; + e_index = smoke_get_index(ex, em->res[0], ey, em->res[1], ez); + if (!emission_map[e_index]) continue; + /* get domain index */ + dx = gx - sds->res_min[0]; + dy = gy - sds->res_min[1]; + dz = gz - sds->res_min[2]; + d_index = smoke_get_index(dx, sds->res[0], dy, sds->res[1], dz); + + if (sfs->type == MOD_SMOKE_FLOW_TYPE_OUTFLOW) { // outflow + apply_outflow_fields(d_index, density, heat, fuel, react, color_r, color_g, color_b); + } + else { // inflow + apply_inflow_fields(sfs, emission_map[e_index], d_index, density, heat, fuel, react, color_r, color_g, color_b); + + /* initial velocity */ + if (sfs->flags & MOD_SMOKE_FLOW_INITVELOCITY) { + velocity_x[d_index] = ADD_IF_LOWER(velocity_x[d_index], velocity_map[e_index * 3]); + velocity_y[d_index] = ADD_IF_LOWER(velocity_y[d_index], velocity_map[e_index * 3 + 1]); + velocity_z[d_index] = ADD_IF_LOWER(velocity_z[d_index], velocity_map[e_index * 3 + 2]); + } + } - // loop through every low res cell - for(x = 0; x < sds->res[0]; x++) - for(y = 0; y < sds->res[1]; y++) - for(z = 0; z < sds->res[2]; z++) - { + /* loop through high res blocks if high res enabled */ + if (bigdensity) { // neighbor cell emission densities (for high resolution smoke smooth interpolation) float c000, c001, c010, c011, c100, c101, c110, c111; - c000 = (x>0 && y>0 && z>0) ? temp_emission_map[smoke_get_index(x-1, sds->res[0], y-1, sds->res[1], z-1)] : 0; - c001 = (x>0 && y>0) ? temp_emission_map[smoke_get_index(x-1, sds->res[0], y-1, sds->res[1], z)] : 0; - c010 = (x>0 && z>0) ? temp_emission_map[smoke_get_index(x-1, sds->res[0], y, sds->res[1], z-1)] : 0; - c011 = (x>0) ? temp_emission_map[smoke_get_index(x-1, sds->res[0], y, sds->res[1], z)] : 0; + smoke_turbulence_get_res(sds->wt, bigres); + block_size = sds->amplify + 1; // high res block size - c100 = (y>0 && z>0) ? temp_emission_map[smoke_get_index(x, sds->res[0], y-1, sds->res[1], z-1)] : 0; - c101 = (y>0) ? temp_emission_map[smoke_get_index(x, sds->res[0], y-1, sds->res[1], z)] : 0; - c110 = (z>0) ? temp_emission_map[smoke_get_index(x, sds->res[0], y, sds->res[1], z-1)] : 0; - c111 = temp_emission_map[smoke_get_index(x, sds->res[0], y, sds->res[1], z)]; // this cell + c000 = (ex > 0 && ey > 0 && ez > 0) ? emission_map[smoke_get_index(ex - 1, em->res[0], ey - 1, em->res[1], ez - 1)] : 0; + c001 = (ex > 0 && ey > 0) ? emission_map[smoke_get_index(ex - 1, em->res[0], ey - 1, em->res[1], ez)] : 0; + c010 = (ex > 0 && ez > 0) ? emission_map[smoke_get_index(ex - 1, em->res[0], ey, em->res[1], ez - 1)] : 0; + c011 = (ex > 0) ? emission_map[smoke_get_index(ex - 1, em->res[0], ey, em->res[1], ez)] : 0; - // get cell index - index = smoke_get_index(x, sds->res[0], y, sds->res[1], z); + c100 = (ey > 0 && ez > 0) ? emission_map[smoke_get_index(ex, em->res[0], ey - 1, em->res[1], ez - 1)] : 0; + c101 = (ey > 0) ? emission_map[smoke_get_index(ex, em->res[0], ey - 1, em->res[1], ez)] : 0; + c110 = (ez > 0) ? emission_map[smoke_get_index(ex, em->res[0], ey, em->res[1], ez - 1)] : 0; + c111 = emission_map[smoke_get_index(ex, em->res[0], ey, em->res[1], ez)]; // this cell - // add emission to low resolution density - if (absolute_flow) - { - if (temp_emission_map[index]>0) - density[index] = temp_emission_map[index]; - } - else - { - density[index] += temp_emission_map[index]; + for (ii = 0; ii < block_size; ii++) + for (jj = 0; jj < block_size; jj++) + for (kk = 0; kk < block_size; kk++) + { - if (density[index]>1) - density[index]=1.0f; - } + float fx, fy, fz, interpolated_value; + int shift_x, shift_y, shift_z; - smoke_turbulence_get_res(sds->wt, bigres); - /* loop through high res blocks if high res enabled */ - if (bigdensity) - for(ii = 0; ii < block_size; ii++) - for(jj = 0; jj < block_size; jj++) - for(kk = 0; kk < block_size; kk++) + /* + * Do volume interpolation if emitter smoothing + * is enabled + */ + if (high_emission_smoothing) { - - float fx,fy,fz, interpolated_value; - int shift_x, shift_y, shift_z; - - - /* - * Do volume interpolation if emitter smoothing - * is enabled - */ - if (high_emission_smoothing) - { - // convert block position to relative - // for interpolation smoothing - fx = (float)ii/block_size + 0.5f/block_size; - fy = (float)jj/block_size + 0.5f/block_size; - fz = (float)kk/block_size + 0.5f/block_size; - - // calculate trilinear interpolation - interpolated_value = c000 * (1-fx) * (1-fy) * (1-fz) + - c100 * fx * (1-fy) * (1-fz) + - c010 * (1-fx) * fy * (1-fz) + - c001 * (1-fx) * (1-fy) * fz + - c101 * fx * (1-fy) * fz + - c011 * (1-fx) * fy * fz + - c110 * fx * fy * (1-fz) + - c111 * fx * fy * fz; - - - // add some contrast / sharpness - // depending on hi-res block size - - interpolated_value = (interpolated_value-0.4f*sfs->density)*(block_size/2) + 0.4f*sfs->density; - if (interpolated_value<0.0f) interpolated_value = 0.0f; - if (interpolated_value>1.0f) interpolated_value = 1.0f; - - // shift smoke block index - // (because pixel center is actually - // in halfway of the low res block) - shift_x = (x < 1) ? 0 : block_size/2; - shift_y = (y < 1) ? 0 : block_size/2; - shift_z = (z < 1) ? 0 : block_size/2; - } - else - { - // without interpolation use same low resolution - // block value for all hi-res blocks - interpolated_value = c111; - shift_x = 0; - shift_y = 0; - shift_z = 0; - } - - // get shifted index for current high resolution block - index_big = smoke_get_index(block_size * x + ii - shift_x, bigres[0], block_size * y + jj - shift_y, bigres[1], block_size * z + kk - shift_z); - - // add emission data to high resolution density - if (absolute_flow) - { - if (interpolated_value > 0) - bigdensity[index_big] = interpolated_value; - } - else - { - bigdensity[index_big] += interpolated_value; - - if (bigdensity[index_big]>1) - bigdensity[index_big]=1.0f; + /* get relative block position + * for interpolation smoothing */ + fx = (float)ii / block_size + 0.5f / block_size; + fy = (float)jj / block_size + 0.5f / block_size; + fz = (float)kk / block_size + 0.5f / block_size; + + /* calculate trilinear interpolation */ + interpolated_value = c000 * (1 - fx) * (1 - fy) * (1 - fz) + + c100 * fx * (1 - fy) * (1 - fz) + + c010 * (1 - fx) * fy * (1 - fz) + + c001 * (1 - fx) * (1 - fy) * fz + + c101 * fx * (1 - fy) * fz + + c011 * (1 - fx) * fy * fz + + c110 * fx * fy * (1 - fz) + + c111 * fx * fy * fz; + + + /* add some contrast / sharpness + * depending on hi-res block size */ + interpolated_value = (interpolated_value - 0.4f) * (block_size / 2) + 0.4f; + CLAMP(interpolated_value, 0.0f, 1.0f); + + /* shift smoke block index + * (because pixel center is actually + * in halfway of the low res block) */ + shift_x = (dx < 1) ? 0 : block_size / 2; + shift_y = (dy < 1) ? 0 : block_size / 2; + shift_z = (dz < 1) ? 0 : block_size / 2; + } + else { + /* without interpolation use same low resolution + * block value for all hi-res blocks */ + interpolated_value = c111; + shift_x = 0; + shift_y = 0; + shift_z = 0; + } + + /* get shifted index for current high resolution block */ + index_big = smoke_get_index(block_size * dx + ii - shift_x, bigres[0], block_size * dy + jj - shift_y, bigres[1], block_size * dz + kk - shift_z); + + if (sfs->type == MOD_SMOKE_FLOW_TYPE_OUTFLOW) { // outflow + if (interpolated_value) { + apply_outflow_fields(index_big, bigdensity, NULL, bigfuel, bigreact, bigcolor_r, bigcolor_g, bigcolor_b); } - } // end of hires loop - - } // end of low res loop - - // free temporary emission map - if (temp_emission_map) - MEM_freeN(temp_emission_map); - - } // end emission - } + } + else { // inflow + apply_inflow_fields(sfs, interpolated_value, index_big, bigdensity, NULL, bigfuel, bigreact, bigcolor_r, bigcolor_g, bigcolor_b); + } + } // hires loop + } // bigdensity + } // low res loop + + // free emission maps + em_freeData(em); + + } // end emission } } - if(flowobjs) + if (flowobjs) MEM_freeN(flowobjs); + if (emaps) + MEM_freeN(emaps); } static void update_effectors(Scene *scene, Object *ob, SmokeDomainSettings *sds, float UNUSED(dt)) { - ListBase *effectors = pdInitEffectors(scene, ob, NULL, sds->effector_weights); + ListBase *effectors; + /* make sure smoke flow influence is 0.0f */ + sds->effector_weights->weight[PFIELD_SMOKEFLOW] = 0.0f; + effectors = pdInitEffectors(scene, ob, NULL, sds->effector_weights); - if(effectors) + if (effectors) { float *density = smoke_get_density(sds->fluid); float *force_x = smoke_get_force_x(sds->fluid); @@ -1532,223 +1901,269 @@ static void update_effectors(Scene *scene, Object *ob, SmokeDomainSettings *sds, 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); - int x, y, z; + int x; // precalculate wind forces - for(x = 0; x < sds->res[0]; x++) - for(y = 0; y < sds->res[1]; y++) - for(z = 0; z < sds->res[2]; z++) - { - EffectedPoint epoint; - float voxelCenter[3] = {0,0,0}, vel[3] = {0,0,0}, retvel[3] = {0,0,0}; - unsigned int index = smoke_get_index(x, sds->res[0], y, sds->res[1], z); - - if((density[index] < FLT_EPSILON) || obstacle[index]) - continue; - - vel[0] = velocity_x[index]; - vel[1] = velocity_y[index]; - vel[2] = velocity_z[index]; - - voxelCenter[0] = sds->p0[0] + sds->dx * sds->scale * x + sds->dx * sds->scale * 0.5; - voxelCenter[1] = sds->p0[1] + sds->dx * sds->scale * y + sds->dx * sds->scale * 0.5; - voxelCenter[2] = sds->p0[2] + sds->dx * sds->scale * z + sds->dx * sds->scale * 0.5; - - pd_point_from_loc(scene, voxelCenter, vel, index, &epoint); - pdDoEffectors(effectors, NULL, sds->effector_weights, &epoint, retvel, NULL); - - // TODO dg - do in force! - force_x[index] = MIN2(MAX2(-1.0, retvel[0] * 0.2), 1.0); - force_y[index] = MIN2(MAX2(-1.0, retvel[1] * 0.2), 1.0); - force_z[index] = MIN2(MAX2(-1.0, retvel[2] * 0.2), 1.0); + #pragma omp parallel for schedule(static) + for (x = 0; x < sds->res[0]; x++) + { + int y, z; + for (y = 0; y < sds->res[1]; y++) + for (z = 0; z < sds->res[2]; z++) + { + EffectedPoint epoint; + float mag; + float voxelCenter[3] = {0, 0, 0}, vel[3] = {0, 0, 0}, retvel[3] = {0, 0, 0}; + unsigned int index = smoke_get_index(x, sds->res[0], y, sds->res[1], z); + + if ((density[index] < FLT_EPSILON) || obstacle[index]) + continue; + + vel[0] = velocity_x[index]; + vel[1] = velocity_y[index]; + vel[2] = velocity_z[index]; + + /* convert vel to global space */ + mag = len_v3(vel); + mul_mat3_m4_v3(sds->obmat, vel); + normalize_v3(vel); + mul_v3_fl(vel, mag); + + voxelCenter[0] = sds->p0[0] + sds->cell_size[0] * ((float)(x + sds->res_min[0]) + 0.5f); + voxelCenter[1] = sds->p0[1] + sds->cell_size[1] * ((float)(y + sds->res_min[1]) + 0.5f); + voxelCenter[2] = sds->p0[2] + sds->cell_size[2] * ((float)(z + sds->res_min[2]) + 0.5f); + mul_m4_v3(sds->obmat, voxelCenter); + + pd_point_from_loc(scene, voxelCenter, vel, index, &epoint); + pdDoEffectors(effectors, NULL, sds->effector_weights, &epoint, retvel, NULL); + + /* convert retvel to local space */ + mag = len_v3(retvel); + mul_mat3_m4_v3(sds->imat, retvel); + normalize_v3(retvel); + mul_v3_fl(retvel, mag); + + // TODO dg - do in force! + force_x[index] = min_ff(max_ff(-1.0f, retvel[0] * 0.2f), 1.0f); + force_y[index] = min_ff(max_ff(-1.0f, retvel[1] * 0.2f), 1.0f); + force_z[index] = min_ff(max_ff(-1.0f, retvel[2] * 0.2f), 1.0f); + } } } pdEndEffectors(&effectors); } -static void step(Scene *scene, Object *ob, SmokeModifierData *smd, float fps) +static void step(Scene *scene, Object *ob, SmokeModifierData *smd, DerivedMesh *domain_dm, float fps) { + SmokeDomainSettings *sds = smd->domain; /* stability values copied from wturbulence.cpp */ const int maxSubSteps = 25; float maxVel; // maxVel should be 1.5 (1.5 cell max movement) * dx (cell size) - float dt = DT_DEFAULT; + float dt; float maxVelMag = 0.0f; int totalSubsteps; int substep = 0; float dtSubdiv; + float gravity[3] = {0.0f, 0.0f, -1.0f}; + float gravity_mag; - SmokeDomainSettings *sds = smd->domain; - - /* get max velocity and lower the dt value if it is too high */ - size_t size= sds->res[0] * sds->res[1] * sds->res[2]; - +#if 0 /* UNUSED */ + /* get max velocity and lower the dt value if it is too high */ + size_t size = sds->res[0] * sds->res[1] * sds->res[2]; float *velX = smoke_get_velocity_x(sds->fluid); float *velY = smoke_get_velocity_y(sds->fluid); float *velZ = smoke_get_velocity_z(sds->fluid); size_t i; +#endif - /* adapt timestep for different framerates, dt = 0.1 is at 25fps */ - dt *= (25.0f / fps); + /* update object state */ + invert_m4_m4(sds->imat, ob->obmat); + copy_m4_m4(sds->obmat, ob->obmat); + smoke_set_domain_from_derivedmesh(sds, ob, domain_dm); + + /* use global gravity if enabled */ + if (scene->physics_settings.flag & PHYS_GLOBAL_GRAVITY) { + copy_v3_v3(gravity, scene->physics_settings.gravity); + /* map default value to 1.0 */ + mul_v3_fl(gravity, 1.0f / 9.810f); + } + /* convert gravity to domain space */ + gravity_mag = len_v3(gravity); + mul_mat3_m4_v3(sds->imat, gravity); + normalize_v3(gravity); + mul_v3_fl(gravity, gravity_mag); + /* adapt timestep for different framerates, dt = 0.1 is at 25fps */ + dt = DT_DEFAULT * (25.0f / fps); // maximum timestep/"CFL" constraint: dt < 5.0 *dx / maxVel - maxVel = (sds->dx * 5.0); + maxVel = (sds->dx * 5.0f); - for(i = 0; i < size; i++) - { - float vtemp = (velX[i]*velX[i]+velY[i]*velY[i]+velZ[i]*velZ[i]); - if(vtemp > maxVelMag) +#if 0 + for (i = 0; i < size; i++) { + float vtemp = (velX[i] * velX[i] + velY[i] * velY[i] + velZ[i] * velZ[i]); + if (vtemp > maxVelMag) maxVelMag = vtemp; } +#endif - maxVelMag = sqrt(maxVelMag) * dt * sds->time_scale; + maxVelMag = sqrtf(maxVelMag) * dt * sds->time_scale; totalSubsteps = (int)((maxVelMag / maxVel) + 1.0f); /* always round up */ totalSubsteps = (totalSubsteps < 1) ? 1 : totalSubsteps; totalSubsteps = (totalSubsteps > maxSubSteps) ? maxSubSteps : totalSubsteps; /* Disable substeps for now, since it results in numerical instability */ - totalSubsteps = 1.0f; + totalSubsteps = 1.0f; dtSubdiv = (float)dt / (float)totalSubsteps; // printf("totalSubsteps: %d, maxVelMag: %f, dt: %f\n", totalSubsteps, maxVelMag, dt); - for(substep = 0; substep < totalSubsteps; substep++) + for (substep = 0; substep < totalSubsteps; substep++) { // calc animated obstacle velocities + update_flowsfluids(scene, ob, sds, smd->time, dtSubdiv); update_obstacles(scene, ob, sds, dtSubdiv, substep, totalSubsteps); - update_flowsfluids(scene, ob, sds, smd->time); - update_effectors(scene, ob, sds, dtSubdiv); // DG TODO? problem --> uses forces instead of velocity, need to check how they need to be changed with variable dt - smoke_step(sds->fluid, dtSubdiv); + if (sds->total_cells > 1) { + update_effectors(scene, ob, sds, dtSubdiv); // DG TODO? problem --> uses forces instead of velocity, need to check how they need to be changed with variable dt + smoke_step(sds->fluid, gravity, dtSubdiv); + } + } +} - // move animated obstacle: Done in update_obstacles() */ +static DerivedMesh *createDomainGeometry(SmokeDomainSettings *sds, Object *ob) +{ + DerivedMesh *result; + MVert *mverts; + MPoly *mpolys; + MLoop *mloops; + float min[3]; + float max[3]; + float *co; + MPoly *mp; + MLoop *ml; + + int num_verts = 8; + int num_faces = 6; + int i; + float ob_loc[3] = {0}; + float ob_cache_loc[3] = {0}; + + /* dont generate any mesh if there isnt any content */ + if (sds->total_cells <= 1) { + num_verts = 0; + num_faces = 0; + } - // where to delete old obstacles from array? Done in update_obstacles() */ + result = CDDM_new(num_verts, 0, 0, num_faces * 4, num_faces); + mverts = CDDM_get_verts(result); + mpolys = CDDM_get_polys(result); + mloops = CDDM_get_loops(result); + + + if (num_verts) { + /* volume bounds */ + VECMADD(min, sds->p0, sds->cell_size, sds->res_min); + VECMADD(max, sds->p0, sds->cell_size, sds->res_max); + + /* set vertices */ + /* top slab */ + co = mverts[0].co; co[0] = min[0]; co[1] = min[1]; co[2] = max[2]; + co = mverts[1].co; co[0] = max[0]; co[1] = min[1]; co[2] = max[2]; + co = mverts[2].co; co[0] = max[0]; co[1] = max[1]; co[2] = max[2]; + co = mverts[3].co; co[0] = min[0]; co[1] = max[1]; co[2] = max[2]; + /* bottom slab */ + co = mverts[4].co; co[0] = min[0]; co[1] = min[1]; co[2] = min[2]; + co = mverts[5].co; co[0] = max[0]; co[1] = min[1]; co[2] = min[2]; + co = mverts[6].co; co[0] = max[0]; co[1] = max[1]; co[2] = min[2]; + co = mverts[7].co; co[0] = min[0]; co[1] = max[1]; co[2] = min[2]; + + /* create faces */ + /* top */ + mp = &mpolys[0]; ml = &mloops[0 * 4]; mp->loopstart = 0 * 4; mp->totloop = 4; + ml[0].v = 0; ml[1].v = 1; ml[2].v = 2; ml[3].v = 3; + /* right */ + mp = &mpolys[1]; ml = &mloops[1 * 4]; mp->loopstart = 1 * 4; mp->totloop = 4; + ml[0].v = 2; ml[1].v = 1; ml[2].v = 5; ml[3].v = 6; + /* bottom */ + mp = &mpolys[2]; ml = &mloops[2 * 4]; mp->loopstart = 2 * 4; mp->totloop = 4; + ml[0].v = 7; ml[1].v = 6; ml[2].v = 5; ml[3].v = 4; + /* left */ + mp = &mpolys[3]; ml = &mloops[3 * 4]; mp->loopstart = 3 * 4; mp->totloop = 4; + ml[0].v = 0; ml[1].v = 3; ml[2].v = 7; ml[3].v = 4; + /* front */ + mp = &mpolys[4]; ml = &mloops[4 * 4]; mp->loopstart = 4 * 4; mp->totloop = 4; + ml[0].v = 3; ml[1].v = 2; ml[2].v = 6; ml[3].v = 7; + /* back */ + mp = &mpolys[5]; ml = &mloops[5 * 4]; mp->loopstart = 5 * 4; mp->totloop = 4; + ml[0].v = 1; ml[1].v = 0; ml[2].v = 4; ml[3].v = 5; + + /* calculate required shift to match domain's global position + * it was originally simulated at (if object moves without smoke step) */ + invert_m4_m4(ob->imat, ob->obmat); + mul_m4_v3(ob->obmat, ob_loc); + mul_m4_v3(sds->obmat, ob_cache_loc); + VECSUB(sds->obj_shift_f, ob_cache_loc, ob_loc); + /* convert shift to local space and apply to vertices */ + mul_mat3_m4_v3(ob->imat, sds->obj_shift_f); + /* apply */ + for (i = 0; i < num_verts; i++) { + add_v3_v3(mverts[i].co, sds->obj_shift_f); + } } + + + CDDM_calc_edges(result); + return result; } -void smokeModifier_do(SmokeModifierData *smd, Scene *scene, Object *ob, DerivedMesh *dm) -{ - if((smd->type & MOD_SMOKE_TYPE_FLOW)) +static void smokeModifier_process(SmokeModifierData *smd, Scene *scene, Object *ob, DerivedMesh *dm) +{ + if ((smd->type & MOD_SMOKE_TYPE_FLOW)) { - if(scene->r.cfra >= smd->time) + if (scene->r.cfra >= smd->time) smokeModifier_init(smd, ob, scene, dm); - if(scene->r.cfra > smd->time) + if (smd->flow->dm) smd->flow->dm->release(smd->flow->dm); + smd->flow->dm = CDDM_copy(dm); + DM_ensure_tessface(smd->flow->dm); + + if (scene->r.cfra > smd->time) { - // XXX TODO smd->time = scene->r.cfra; - - // rigid movement support - /* - copy_m4_m4(smd->flow->mat_old, smd->flow->mat); - copy_m4_m4(smd->flow->mat, ob->obmat); - */ } - else if(scene->r.cfra < smd->time) + else if (scene->r.cfra < smd->time) { smd->time = scene->r.cfra; smokeModifier_reset(smd); } } - else if(smd->type & MOD_SMOKE_TYPE_COLL) + else if (smd->type & MOD_SMOKE_TYPE_COLL) { - /* Check if domain resolution changed */ - /* DG TODO: can this be solved more elegant using dependancy graph? */ - { - SmokeCollSettings *scs = smd->coll; - Base *base = scene->base.first; - int changed = 0; - float dx = FLT_MAX; - float scale = 1.0f; - int haveDomain = 0; - - for ( ; base; base = base->next) - { - SmokeModifierData *smd2 = (SmokeModifierData *)modifiers_findByType(base->object, eModifierType_Smoke); - - if (smd2 && (smd2->type & MOD_SMOKE_TYPE_DOMAIN) && smd2->domain) - { - SmokeDomainSettings *sds = smd2->domain; - - if(sds->dx * sds->scale < dx) - { - dx = sds->dx; - scale = sds->scale; - changed = 1; - } - - haveDomain = 1; - } - } - - if(!haveDomain) - return; - - if(changed) - { - if(dx*scale != scs->dx) - { - scs->dx = dx*scale; - smokeModifier_reset(smd); - } - } - } - - if(scene->r.cfra >= smd->time) + if (scene->r.cfra >= smd->time) smokeModifier_init(smd, ob, scene, dm); - if(scene->r.cfra > smd->time) + if (smd->coll) { - unsigned int i; - SmokeCollSettings *scs = smd->coll; - float *points_old = scs->points_old; - float *points = scs->points; - unsigned int numpoints = scs->numpoints; - - // XXX TODO <-- DG: what is TODO here? - smd->time = scene->r.cfra; - - // rigid movement support - copy_m4_m4(scs->mat_old, scs->mat); - copy_m4_m4(scs->mat, ob->obmat); - - if(scs->type != SM_COLL_ANIMATED) // if(not_animated) - { - // nothing to do, "mat" is already up to date - } - else - { - // XXX TODO: need to update positions + divs - - if(scs->numverts != dm->getNumVerts(dm)) - { - // DG TODO: reset modifier? - return; - } + if (smd->coll->dm) + smd->coll->dm->release(smd->coll->dm); - for(i = 0; i < numpoints * 3; i++) - { - points_old[i] = points[i]; - } - - DM_ensure_tessface(dm); - fill_scs_points_anim(ob, dm, scs); - } + smd->coll->dm = CDDM_copy(dm); + DM_ensure_tessface(smd->coll->dm); } - else if(scene->r.cfra < smd->time) + + smd->time = scene->r.cfra; + if (scene->r.cfra < smd->time) { - smd->time = scene->r.cfra; smokeModifier_reset(smd); } } - else if(smd->type & MOD_SMOKE_TYPE_DOMAIN) + else if (smd->type & MOD_SMOKE_TYPE_DOMAIN) { SmokeDomainSettings *sds = smd->domain; - float light[3]; PointCache *cache = NULL; PTCacheID pid; int startframe, endframe, framenr; @@ -1762,41 +2177,39 @@ void smokeModifier_do(SmokeModifierData *smd, Scene *scene, Object *ob, DerivedM BKE_ptcache_id_from_smoke(&pid, ob, smd); BKE_ptcache_id_time(&pid, scene, framenr, &startframe, &endframe, ×cale); - if(!smd->domain->fluid || framenr == startframe) + if (!smd->domain->fluid || framenr == startframe) { BKE_ptcache_id_reset(scene, &pid, PTCACHE_RESET_OUTDATED); + smokeModifier_reset(smd); BKE_ptcache_validate(cache, framenr); cache->flag &= ~PTCACHE_REDO_NEEDED; } - if(!smd->domain->fluid && (framenr != startframe) && (smd->domain->flags & MOD_SMOKE_FILE_LOAD)==0 && (cache->flag & PTCACHE_BAKED)==0) + if (!smd->domain->fluid && (framenr != startframe) && (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->r.cfra)) return; - // printf("startframe: %d, framenr: %d\n", startframe, framenr); - - if(smokeModifier_init(smd, ob, scene, dm)==0) + if (smokeModifier_init(smd, ob, scene, dm) == 0) { printf("bad smokeModifier_init\n"); return; } /* try to read from cache */ - if(BKE_ptcache_read(&pid, (float)framenr) == PTCACHE_READ_EXACT) { + if (BKE_ptcache_read(&pid, (float)framenr) == PTCACHE_READ_EXACT) { BKE_ptcache_validate(cache, framenr); smd->time = framenr; return; } - + /* only calculate something when we advanced a single frame */ - if(framenr != (int)smd->time+1) + if (framenr != (int)smd->time + 1) return; /* don't simulate if viewing start frame, but scene frame is not real start frame */ @@ -1805,54 +2218,48 @@ void smokeModifier_do(SmokeModifierData *smd, Scene *scene, Object *ob, DerivedM tstart(); - smoke_calc_domain(scene, ob, smd); - /* if on second frame, write cache for first frame */ - if((int)smd->time == startframe && (cache->flag & PTCACHE_OUTDATED || cache->last_exact==0)) { + if ((int)smd->time == startframe && (cache->flag & PTCACHE_OUTDATED || cache->last_exact == 0)) { // create shadows straight after domain initialization so we get nice shadows for startframe, too - if(get_lamp(scene, light)) - smoke_calc_transparency(sds->shadow, smoke_get_density(sds->fluid), sds->p0, sds->p1, sds->res, sds->dx, light, calc_voxel_transp, -7.0*sds->dx); + smoke_calc_transparency(sds, scene); - if(sds->wt) + if (sds->wt && sds->total_cells > 1) { - if(sds->flags & MOD_SMOKE_DISSOLVE) + if (sds->flags & MOD_SMOKE_DISSOLVE) smoke_dissolve_wavelet(sds->wt, sds->diss_speed, sds->flags & MOD_SMOKE_DISSOLVE_LOG); smoke_turbulence_step(sds->wt, sds->fluid); } BKE_ptcache_write(&pid, startframe); } - + // set new time smd->time = scene->r.cfra; /* do simulation */ - // low res - // simulate the actual smoke (c++ code in intern/smoke) // DG: interesting commenting this line + deactivating loading of noise files - if(framenr!=startframe) + if (framenr != startframe) { - if(sds->flags & MOD_SMOKE_DISSOLVE) + if (sds->flags & MOD_SMOKE_DISSOLVE) smoke_dissolve(sds->fluid, sds->diss_speed, sds->flags & MOD_SMOKE_DISSOLVE_LOG); - - step(scene, ob, smd, scene->r.frs_sec / scene->r.frs_sec_base); + + step(scene, ob, smd, dm, scene->r.frs_sec / scene->r.frs_sec_base); } // create shadows before writing cache so they get stored - if(get_lamp(scene, light)) - smoke_calc_transparency(sds->shadow, smoke_get_density(sds->fluid), sds->p0, sds->p1, sds->res, sds->dx, light, calc_voxel_transp, -7.0*sds->dx); + smoke_calc_transparency(sds, scene); - if(sds->wt) + if (sds->wt) { - if(sds->flags & MOD_SMOKE_DISSOLVE) + if (sds->flags & MOD_SMOKE_DISSOLVE) smoke_dissolve_wavelet(sds->wt, sds->diss_speed, sds->flags & MOD_SMOKE_DISSOLVE_LOG); smoke_turbulence_step(sds->wt, sds->fluid); } - + BKE_ptcache_validate(cache, framenr); - if(framenr != startframe) + if (framenr != startframe) BKE_ptcache_write(&pid, framenr); tend(); @@ -1860,38 +2267,34 @@ void smokeModifier_do(SmokeModifierData *smd, Scene *scene, Object *ob, DerivedM } } -static float calc_voxel_transp(float *result, float *input, int res[3], int *pixel, float *tRay, float correct) +struct DerivedMesh *smokeModifier_do(SmokeModifierData *smd, Scene *scene, Object *ob, DerivedMesh *dm) { - const size_t index = smoke_get_index(pixel[0], res[0], pixel[1], res[1], pixel[2]); + smokeModifier_process(smd, scene, ob, dm); - // T_ray *= T_vox - *tRay *= exp(input[index]*correct); - - if(result[index] < 0.0f) + /* return generated geometry for adaptive domain */ + if (smd->type & MOD_SMOKE_TYPE_DOMAIN && smd->domain && + smd->domain->flags & MOD_SMOKE_ADAPTIVE_DOMAIN && + smd->domain->base_res[0]) { -// #pragma omp critical - result[index] = *tRay; - } - - return *tRay; + return createDomainGeometry(smd->domain, ob); + } + else return CDDM_copy(dm); } -long long smoke_get_mem_req(int xres, int yres, int zres, int amplify) +static float calc_voxel_transp(float *result, float *input, int res[3], int *pixel, float *tRay, float correct) { - int totalCells = xres * yres * zres; - int amplifiedCells = totalCells * amplify * amplify * amplify; - - // print out memory requirements - long long int coarseSize = sizeof(float) * totalCells * 22 + - sizeof(unsigned char) * totalCells; + const size_t index = smoke_get_index(pixel[0], res[0], pixel[1], res[1], pixel[2]); - long long int fineSize = sizeof(float) * amplifiedCells * 7 + // big grids - sizeof(float) * totalCells * 8 + // small grids - sizeof(float) * 128 * 128 * 128; // noise tile + // T_ray *= T_vox + *tRay *= expf(input[index] * correct); - long long int totalMB = (coarseSize + fineSize) / (1024 * 1024); + if (result[index] < 0.0f) + { +// #pragma omp critical + result[index] = *tRay; + } - return totalMB; + return *tRay; } static void bresenham_linie_3D(int x1, int y1, int z1, int x2, int y2, int z2, float *tRay, bresenham_callback cb, float *result, float *input, int res[3], float correct) @@ -1921,7 +2324,7 @@ static void bresenham_linie_3D(int x1, int y1, int z1, int x2, int y2, int z2, f 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; @@ -1935,12 +2338,12 @@ static void bresenham_linie_3D(int x1, int y1, int z1, int x2, int y2, int z2, f err_2 += dz2; pixel[0] += x_inc; } - } + } else if ((m >= l) && (m >= n)) { 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; @@ -1954,12 +2357,12 @@ static void bresenham_linie_3D(int x1, int y1, int z1, int x2, int y2, int z2, f err_2 += dz2; pixel[1] += y_inc; } - } + } else { 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; @@ -1977,80 +2380,142 @@ static void bresenham_linie_3D(int x1, int y1, int z1, int x2, int y2, int z2, f cb(result, input, res, pixel, tRay, correct); } -static void get_cell(const float p0[3], const int res[3], float dx, const float pos[3], int cell[3], int correct) +static void smoke_calc_transparency(SmokeDomainSettings *sds, Scene *scene) { - float tmp[3]; + float bv[6] = {0}; + float light[3]; + int a, z, slabsize = sds->res[0] * sds->res[1], size = sds->res[0] * sds->res[1] * sds->res[2]; + float *density = smoke_get_density(sds->fluid); + float correct = -7.0f * sds->dx; - sub_v3_v3v3(tmp, pos, p0); - mul_v3_fl(tmp, 1.0 / dx); + if (!get_lamp(scene, light)) return; - if (correct) { - cell[0] = MIN2(res[0] - 1, MAX2(0, (int)floor(tmp[0]))); - cell[1] = MIN2(res[1] - 1, MAX2(0, (int)floor(tmp[1]))); - cell[2] = MIN2(res[2] - 1, MAX2(0, (int)floor(tmp[2]))); - } - else { - cell[0] = (int)floor(tmp[0]); - cell[1] = (int)floor(tmp[1]); - cell[2] = (int)floor(tmp[2]); - } -} - -static void smoke_calc_transparency(float *result, float *input, float *p0, float *p1, int res[3], float dx, float *light, bresenham_callback cb, float correct) -{ - float bv[6]; - int a, z, slabsize=res[0]*res[1], size= res[0]*res[1]*res[2]; + /* convert light pos to sim cell space */ + mul_m4_v3(sds->imat, light); + light[0] = (light[0] - sds->p0[0]) / sds->cell_size[0] - 0.5f - (float)sds->res_min[0]; + 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++) - result[a]= -1.0f; + for (a = 0; a < size; a++) + sds->shadow[a] = -1.0f; - bv[0] = p0[0]; - bv[1] = p1[0]; - // y - bv[2] = p0[1]; - bv[3] = p1[1]; - // z - bv[4] = p0[2]; - bv[5] = p1[2]; + /* calculate domain bounds in sim cell space */ + // 0,2,4 = 0.0f + bv[1] = (float)sds->res[0]; // x + bv[3] = (float)sds->res[1]; // y + bv[5] = (float)sds->res[2]; // z // #pragma omp parallel for schedule(static,1) - for(z = 0; z < res[2]; z++) + for (z = 0; z < sds->res[2]; z++) { - size_t index = z*slabsize; - int x,y; + size_t index = z * slabsize; + int x, y; - for(y = 0; y < res[1]; y++) - for(x = 0; x < res[0]; x++, index++) + 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(result[index] >= 0.0f) - continue; - voxelCenter[0] = p0[0] + dx * x + dx * 0.5; - voxelCenter[1] = p0[1] + dx * y + dx * 0.5; - voxelCenter[2] = p0[2] + dx * z + dx * 0.5; + if (sds->shadow[index] >= 0.0f) + continue; + voxelCenter[0] = (float)x; + voxelCenter[1] = (float)y; + voxelCenter[2] = (float)z; - // get starting position (in voxel coords) - if(BLI_bvhtree_bb_raycast(bv, light, voxelCenter, pos) > FLT_EPSILON) + // get starting cell (light pos) + if (BLI_bvhtree_bb_raycast(bv, light, voxelCenter, pos) > FLT_EPSILON) { - // we're ouside - get_cell(p0, res, dx, pos, cell, 1); + // we're ouside -> use point on side of domain + cell[0] = (int)floor(pos[0]); + cell[1] = (int)floor(pos[1]); + cell[2] = (int)floor(pos[2]); } else { - // we're inside - get_cell(p0, res, dx, light, cell, 1); + // we're inside -> use light itself + cell[0] = (int)floor(light[0]); + cell[1] = (int)floor(light[1]); + cell[2] = (int)floor(light[2]); } + /* clamp within grid bounds */ + CLAMP(cell[0], 0, sds->res[0] - 1); + CLAMP(cell[1], 0, sds->res[1] - 1); + CLAMP(cell[2], 0, sds->res[2] - 1); - bresenham_linie_3D(cell[0], cell[1], cell[2], x, y, z, &tRay, cb, result, input, res, correct); + bresenham_linie_3D(cell[0], cell[1], cell[2], x, y, z, &tRay, calc_voxel_transp, sds->shadow, density, sds->res, correct); // convention -> from a RGBA float array, use G value for tRay // #pragma omp critical - result[index] = tRay; + sds->shadow[index] = tRay; } } } +/* get smoke velocity and density at given coordinates + * returns fluid density or -1.0f if outside domain*/ +float smoke_get_velocity_at(struct Object *ob, float position[3], float velocity[3]) +{ + SmokeModifierData *smd = (SmokeModifierData *)modifiers_findByType(ob, eModifierType_Smoke); + zero_v3(velocity); + + if (smd && (smd->type & MOD_SMOKE_TYPE_DOMAIN) && smd->domain && smd->domain->fluid) { + SmokeDomainSettings *sds = smd->domain; + float time_mult = 25.f * DT_DEFAULT; + float vel_mag; + float *velX = smoke_get_velocity_x(sds->fluid); + float *velY = smoke_get_velocity_y(sds->fluid); + float *velZ = smoke_get_velocity_z(sds->fluid); + float density = 0.0f, fuel = 0.0f; + float pos[3]; + copy_v3_v3(pos, position); + 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]) return -1.0f; + 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]); + pos[1] = (pos[1] - sds->res_min[1]) / ((float)sds->res[1]); + pos[2] = (pos[2] - sds->res_min[2]) / ((float)sds->res[2]); + + + /* 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) return 0.0f; + if (pos[0] > 1.0f || pos[1] > 1.0f || pos[2] > 1.0f) return 0.0f; + } + + /* get interpolated velocity */ + velocity[0] = BLI_voxel_sample_trilinear(velX, sds->res, pos) * sds->global_size[0] * time_mult; + velocity[1] = BLI_voxel_sample_trilinear(velY, sds->res, pos) * sds->global_size[1] * time_mult; + velocity[2] = BLI_voxel_sample_trilinear(velZ, sds->res, pos) * sds->global_size[2] * time_mult; + + /* convert velocity direction to global space */ + vel_mag = len_v3(velocity); + mul_mat3_m4_v3(sds->obmat, velocity); + normalize_v3(velocity); + mul_v3_fl(velocity, vel_mag); + + /* use max value of fuel or smoke density */ + density = BLI_voxel_sample_trilinear(smoke_get_density(sds->fluid), sds->res, pos); + if (smoke_has_fuel(sds->fluid)) { + fuel = BLI_voxel_sample_trilinear(smoke_get_fuel(sds->fluid), sds->res, pos); + } + return MAX2(density, fuel); + } + return -1.0f; +} + +int smoke_get_data_flags(SmokeDomainSettings *sds) { + int flags = 0; + if (smoke_has_heat(sds->fluid)) flags |= SM_ACTIVE_HEAT; + if (smoke_has_fuel(sds->fluid)) flags |= SM_ACTIVE_FIRE; + if (smoke_has_colors(sds->fluid)) flags |= SM_ACTIVE_COLORS; + + return flags; +} + #endif /* WITH_SMOKE */ diff --git a/source/blender/blenkernel/intern/softbody.c b/source/blender/blenkernel/intern/softbody.c index f47c931e309..bb0cfe1a5c6 100644 --- a/source/blender/blenkernel/intern/softbody.c +++ b/source/blender/blenkernel/intern/softbody.c @@ -1170,7 +1170,7 @@ static int sb_detect_face_pointCached(float face_v1[3], float face_v2[3], float *damp=df*tune*ob->pd->pdef_sbdamp; - df = 0.01f*exp(- 100.0f*df); + df = 0.01f * expf(-100.0f * df); Vec3PlusStVec(force, -df, d_nvect); deflected = 3; } @@ -1598,7 +1598,7 @@ static void _scan_for_ext_spring_forces(Scene *scene, Object *ob, float timenow, /*see if we have wind*/ if (do_effector) { EffectedPoint epoint; - float speed[3]={0.0f, 0.0f, 0.0f}; + float speed[3] = {0.0f, 0.0f, 0.0f}; float pos[3]; mid_v3_v3v3(pos, sb->bpoint[bs->v1].pos, sb->bpoint[bs->v2].pos); mid_v3_v3v3(vel, sb->bpoint[bs->v1].vec, sb->bpoint[bs->v2].vec); @@ -1749,8 +1749,8 @@ static int sb_detect_vertex_collisionCached(float opco[3], float facenormal[3], Object *ob= NULL; GHash *hash; GHashIterator *ihash; - float nv1[3], nv2[3], nv3[3], nv4[3], edge1[3], edge2[3], d_nvect[3], dv1[3], ve[3], avel[3]={0.0, 0.0, 0.0}, - vv1[3], vv2[3], vv3[3], vv4[3], coledge[3]={0.0f, 0.0f, 0.0f}, mindistedge = 1000.0f, + float nv1[3], nv2[3], nv3[3], nv4[3], edge1[3], edge2[3], d_nvect[3], dv1[3], ve[3], avel[3] = {0.0, 0.0, 0.0}, + vv1[3], vv2[3], vv3[3], vv4[3], coledge[3] = {0.0f, 0.0f, 0.0f}, mindistedge = 1000.0f, outerforceaccu[3], innerforceaccu[3], facedist, /* n_mag, */ /* UNUSED */ force_mag_norm, minx, miny, minz, maxx, maxy, maxz, innerfacethickness = -0.5f, outerfacethickness = 0.2f, @@ -2209,7 +2209,7 @@ static int _softbody_calc_forces_slice_in_a_thread(Scene *scene, Object *ob, flo bp = &sb->bpoint[ifirst]; for (bb=number_of_points_here; bb>0; bb--, bp++) { /* clear forces accumulator */ - bp->force[0]= bp->force[1]= bp->force[2]= 0.0; + bp->force[0] = bp->force[1] = bp->force[2] = 0.0; /* naive ball self collision */ /* needs to be done if goal snaps or not */ if (do_selfcollision) { @@ -2304,8 +2304,8 @@ static int _softbody_calc_forces_slice_in_a_thread(Scene *scene, Object *ob, flo if (do_effector) { EffectedPoint epoint; float kd; - float force[3]= {0.0f, 0.0f, 0.0f}; - float speed[3]= {0.0f, 0.0f, 0.0f}; + float force[3] = {0.0f, 0.0f, 0.0f}; + float speed[3] = {0.0f, 0.0f, 0.0f}; float eval_sb_fric_force_scale = sb_fric_force_scale(ob); /* just for calling function once */ pd_point_from_soft(scene, bp->pos, bp->vec, sb->bpoint-bp, &epoint); pdDoEffectors(do_effector, NULL, sb->effector_weights, &epoint, force, speed); @@ -2557,7 +2557,7 @@ static void softbody_calc_forces(Scene *scene, Object *ob, float forcetime, floa for (a=sb->totpoint, bp= sb->bpoint; a>0; a--, bp++) { /* clear forces accumulator */ - bp->force[0]= bp->force[1]= bp->force[2]= 0.0; + bp->force[0] = bp->force[1] = bp->force[2] = 0.0; if (nl_flags & NLF_BUILD) { //int ia =3*(sb->totpoint-a); //int op =3*sb->totpoint; @@ -2712,8 +2712,8 @@ static void softbody_calc_forces(Scene *scene, Object *ob, float forcetime, floa /* particle field & vortex */ if (do_effector) { EffectedPoint epoint; - float force[3]= {0.0f, 0.0f, 0.0f}; - float speed[3]= {0.0f, 0.0f, 0.0f}; + float force[3] = {0.0f, 0.0f, 0.0f}; + float speed[3] = {0.0f, 0.0f, 0.0f}; float eval_sb_fric_force_scale = sb_fric_force_scale(ob); /* just for calling function once */ pd_point_from_soft(scene, bp->pos, bp->vec, sb->bpoint-bp, &epoint); pdDoEffectors(do_effector, NULL, sb->effector_weights, &epoint, force, speed); @@ -2905,7 +2905,7 @@ static void softbody_apply_forces(Object *ob, float forcetime, int mode, float * /* or heun ~ 2nd order runge-kutta steps, mode 1, 2 */ SoftBody *sb= ob->soft; /* is supposed to be there */ BodyPoint *bp; - float dx[3]={0}, dv[3], aabbmin[3], aabbmax[3], cm[3]={0.0f, 0.0f, 0.0f}; + float dx[3] = {0}, dv[3], aabbmin[3], aabbmax[3], cm[3] = {0.0f, 0.0f, 0.0f}; float timeovermass/*, freezeloc=0.00001f, freezeforce=0.00000000001f*/; float maxerrpos= 0.0f, maxerrvel = 0.0f; int a, fuzzy=0; @@ -3194,7 +3194,7 @@ static void interpolate_exciter(Object *ob, int timescale, int time) - xxxx_to_softbody(Object *ob) : a full (new) copy, creates SB geometry */ -static void get_scalar_from_vertexgroup(Object *ob, int vertID, short groupindex, float *target) +static void get_scalar_from_vertexgroup(Object *ob, int vertID, int groupindex, float *target) /* result 0 on success, else indicates error number -- kind of *inverse* result defintion, -- but this way we can signal error condition to caller @@ -3297,7 +3297,7 @@ static void mesh_to_softbody(Scene *scene, Object *ob) if ((ob->softflag & OB_SB_GOAL) && sb->vertgroup) { /* even this is a deprecated evil hack */ /* I'd like to have it .. if (sb->namedVG_Goal[0]) */ - get_scalar_from_vertexgroup(ob, a, (short) (sb->vertgroup-1), &bp->goal); + get_scalar_from_vertexgroup(ob, a, sb->vertgroup - 1, &bp->goal); /* do this always, regardless successful read from vertex group */ /* this is where '2.5 every thing is animatable' goes wrong in the first place jow_go_for2_5 */ /* 1st coding action to take : move this to frame level */ @@ -3316,10 +3316,10 @@ static void mesh_to_softbody(Scene *scene, Object *ob) */ if (sb->namedVG_Mass[0]) { - int grp= defgroup_name_index (ob, sb->namedVG_Mass); - /* printf("VGN %s %d\n", sb->namedVG_Mass, grp); */ - if (grp > -1) { - get_scalar_from_vertexgroup(ob, a, (short) (grp), &bp->mass); + int defgrp_index = defgroup_name_index (ob, sb->namedVG_Mass); + /* printf("VGN %s %d\n", sb->namedVG_Mass, defgrp_index); */ + if (defgrp_index != -1) { + get_scalar_from_vertexgroup(ob, a, defgrp_index, &bp->mass); /* 2.5 bp->mass = bp->mass * sb->nodemass; */ /* printf("bp->mass %f\n", bp->mass); */ @@ -3329,10 +3329,10 @@ static void mesh_to_softbody(Scene *scene, Object *ob) bp->springweight = 1.0f; if (sb->namedVG_Spring_K[0]) { - int grp= defgroup_name_index (ob, sb->namedVG_Spring_K); - //printf("VGN %s %d\n", sb->namedVG_Spring_K, grp); - if (grp > -1) { - get_scalar_from_vertexgroup(ob, a, (short) (grp), &bp->springweight); + int defgrp_index = defgroup_name_index (ob, sb->namedVG_Spring_K); + //printf("VGN %s %d\n", sb->namedVG_Spring_K, defgrp_index); + if (defgrp_index != -1) { + get_scalar_from_vertexgroup(ob, a, defgrp_index , &bp->springweight); //printf("bp->springweight %f\n", bp->springweight); } @@ -3865,7 +3865,7 @@ static void softbody_reset(Object *ob, SoftBody *sb, float (*vertexCos)[3], int copy_v3_v3(bp->origS, bp->pos); copy_v3_v3(bp->origE, bp->pos); copy_v3_v3(bp->origT, bp->pos); - bp->vec[0]= bp->vec[1]= bp->vec[2]= 0.0f; + bp->vec[0] = bp->vec[1] = bp->vec[2] = 0.0f; /* the bp->prev*'s are for rolling back from a canceled try to propagate in time * adaptive step size algo in a nutshell: @@ -4008,8 +4008,8 @@ static void softbody_step(Scene *scene, Object *ob, SoftBody *sb, float dtime) } loops++; if (sb->solverflags & SBSO_MONITOR ) { - sct=PIL_check_seconds_timer(); - if (sct-sst > 0.5f) printf("%3.0f%% \r", 100.0f*timedone/dtime); + sct = PIL_check_seconds_timer(); + if (sct - sst > 0.5) printf("%3.0f%% \r", 100.0f * timedone / dtime); } /* ask for user break */ if (SB_localInterruptCallBack && SB_localInterruptCallBack()) break; @@ -4045,7 +4045,7 @@ static void softbody_step(Scene *scene, Object *ob, SoftBody *sb, float dtime) if (sb->solverflags & SBSO_MONITOR ) { sct=PIL_check_seconds_timer(); - if ((sct-sst > 0.5f) || (G.debug & G_DEBUG)) printf(" solver time %f sec %s\n", sct-sst, ob->id.name); + if ((sct - sst > 0.5) || (G.debug & G_DEBUG)) printf(" solver time %f sec %s\n", sct-sst, ob->id.name); } } diff --git a/source/blender/blenkernel/intern/sound.c b/source/blender/blenkernel/intern/sound.c index 385d1bb6fc5..af9d21d8cbc 100644 --- a/source/blender/blenkernel/intern/sound.c +++ b/source/blender/blenkernel/intern/sound.c @@ -353,17 +353,17 @@ void sound_load(struct Main *bmain, bSound *sound) } // XXX unused currently #if 0 - break; + break; + } + case SOUND_TYPE_BUFFER: + 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) + sound->handle = AUD_limitSound(sound->child_sound, sound->start, sound->end); + break; } - case SOUND_TYPE_BUFFER: - 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) - sound->handle = AUD_limitSound(sound->child_sound, sound->start, sound->end); - break; -} #endif if (sound->flags & SOUND_FLAGS_MONO) { void *handle = AUD_monoSound(sound->handle); @@ -701,7 +701,7 @@ void sound_update_scene(struct Scene *scene) if (AUD_removeSet(scene->speaker_handles, strip->speaker_handle)) { if (speaker->sound) - AUD_moveSequence(strip->speaker_handle, strip->start / FPS, -1, 0); + AUD_moveSequence(strip->speaker_handle, (double)strip->start / FPS, -1, 0); else { AUD_removeSequence(scene->sound_scene, strip->speaker_handle); strip->speaker_handle = NULL; @@ -709,7 +709,9 @@ void sound_update_scene(struct Scene *scene) } else { if (speaker->sound) { - strip->speaker_handle = AUD_addSequence(scene->sound_scene, speaker->sound->playback_handle, strip->start / FPS, -1, 0); + strip->speaker_handle = AUD_addSequence(scene->sound_scene, + speaker->sound->playback_handle, + (double)strip->start / FPS, -1, 0); AUD_setRelativeSequence(strip->speaker_handle, 0); } } diff --git a/source/blender/blenkernel/intern/subsurf_ccg.c b/source/blender/blenkernel/intern/subsurf_ccg.c index e1a7bb792f8..ff975535cf6 100644 --- a/source/blender/blenkernel/intern/subsurf_ccg.c +++ b/source/blender/blenkernel/intern/subsurf_ccg.c @@ -602,7 +602,7 @@ static void ss_sync_from_derivedmesh(CCGSubSurf *ss, DerivedMesh *dm, } mp = mpoly; - index = DM_get_poly_data_layer(dm, CD_ORIGINDEX); + index = (int *)dm->getPolyDataArray(dm, CD_ORIGINDEX); for (i = 0; i < dm->numPolyData; i++, mp++) { CCGFace *f; @@ -2802,6 +2802,30 @@ static void *ccgDM_get_tessface_data_layer(DerivedMesh *dm, int type) { if (type == CD_ORIGINDEX) { /* create origindex on demand to save memory */ + int *origindex; + + /* Avoid re-creation if the layer exists already */ + origindex = DM_get_tessface_data_layer(dm, CD_ORIGINDEX); + if (origindex) { + return origindex; + } + + DM_add_tessface_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL); + origindex = DM_get_tessface_data_layer(dm, CD_ORIGINDEX); + + /* silly loop counting up */ + range_vn_i(origindex, dm->getNumTessFaces(dm), 0); + + return origindex; + } + + return DM_get_tessface_data_layer(dm, type); +} + +static void *ccgDM_get_poly_data_layer(DerivedMesh *dm, int type) +{ + if (type == CD_ORIGINDEX) { + /* create origindex on demand to save memory */ CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm; CCGSubSurf *ss = ccgdm->ss; int *origindex; @@ -2809,13 +2833,13 @@ static void *ccgDM_get_tessface_data_layer(DerivedMesh *dm, int type) int gridFaces = ccgSubSurf_getGridSize(ss) - 1; /* Avoid re-creation if the layer exists already */ - origindex = DM_get_tessface_data_layer(dm, CD_ORIGINDEX); + origindex = DM_get_poly_data_layer(dm, CD_ORIGINDEX); if (origindex) { return origindex; } - DM_add_tessface_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL); - origindex = DM_get_tessface_data_layer(dm, CD_ORIGINDEX); + DM_add_poly_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL); + origindex = DM_get_poly_data_layer(dm, CD_ORIGINDEX); totface = ccgSubSurf_getNumFaces(ss); @@ -2831,7 +2855,7 @@ static void *ccgDM_get_tessface_data_layer(DerivedMesh *dm, int type) return origindex; } - return DM_get_tessface_data_layer(dm, type); + return DM_get_poly_data_layer(dm, type); } static void *ccgDM_get_vert_data(DerivedMesh *dm, int index, int type) @@ -2864,6 +2888,16 @@ static void *ccgDM_get_tessface_data(DerivedMesh *dm, int index, int type) return DM_get_tessface_data(dm, index, type); } +static void *ccgDM_get_poly_data(DerivedMesh *dm, int index, int type) +{ + if (type == CD_ORIGINDEX) { + /* ensure creation of CD_ORIGINDEX layer */ + ccgDM_get_tessface_data_layer(dm, type); + } + + return DM_get_poly_data(dm, index, type); +} + static int ccgDM_getNumGrids(DerivedMesh *dm) { CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm; @@ -3087,7 +3121,8 @@ static struct PBVH *ccgDM_getPBVH(Object *ob, DerivedMesh *dm) * when the ccgdm gets remade, the assumption is that the topology * does not change. */ ccgdm_create_grids(dm); - BLI_pbvh_grids_update(ob->sculpt->pbvh, ccgdm->gridData, ccgdm->gridAdjacency, (void **)ccgdm->gridFaces); + BLI_pbvh_grids_update(ob->sculpt->pbvh, ccgdm->gridData, ccgdm->gridAdjacency, (void **)ccgdm->gridFaces, + ccgdm->gridFlagMats, ccgdm->gridHidden); } ccgdm->pbvh = ob->sculpt->pbvh; @@ -3116,6 +3151,9 @@ static struct PBVH *ccgDM_getPBVH(Object *ob, DerivedMesh *dm) me->totface, me->totvert, &me->vdata); } + if (ccgdm->pbvh) + pbvh_show_diffuse_color_set(ccgdm->pbvh, ob->sculpt->show_diffuse_color); + return ccgdm->pbvh; } @@ -3191,7 +3229,7 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss, } /* We absolutely need that layer, else it's no valid tessellated data! */ - polyidx = CustomData_add_layer(&ccgdm->dm.faceData, CD_POLYINDEX, CD_CALLOC, + polyidx = CustomData_add_layer(&ccgdm->dm.faceData, CD_ORIGINDEX, CD_CALLOC, NULL, ccgSubSurf_getNumFinalFaces(ss)); ccgdm->dm.getMinMax = ccgDM_getMinMax; @@ -3219,9 +3257,11 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss, ccgdm->dm.getVertData = ccgDM_get_vert_data; ccgdm->dm.getEdgeData = ccgDM_get_edge_data; ccgdm->dm.getTessFaceData = ccgDM_get_tessface_data; + ccgdm->dm.getPolyData = ccgDM_get_poly_data; ccgdm->dm.getVertDataArray = ccgDM_get_vert_data_layer; ccgdm->dm.getEdgeDataArray = ccgDM_get_edge_data_layer; ccgdm->dm.getTessFaceDataArray = ccgDM_get_tessface_data_layer; + ccgdm->dm.getPolyDataArray = ccgDM_get_poly_data_layer; ccgdm->dm.getNumGrids = ccgDM_getNumGrids; ccgdm->dm.getGridSize = ccgDM_getGridSize; ccgdm->dm.getGridData = ccgDM_getGridData; @@ -3320,8 +3360,8 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss, vertOrigIndex = DM_get_vert_data_layer(&ccgdm->dm, CD_ORIGINDEX); /*edgeOrigIndex = DM_get_edge_data_layer(&ccgdm->dm, CD_ORIGINDEX);*/ - faceOrigIndex = DM_get_tessface_data_layer(&ccgdm->dm, CD_ORIGINDEX); + faceOrigIndex = DM_get_tessface_data_layer(&ccgdm->dm, CD_ORIGINDEX); polyOrigIndex = DM_get_poly_data_layer(&ccgdm->dm, CD_ORIGINDEX); #if 0 @@ -3459,7 +3499,8 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss, /*set original index data*/ if (faceOrigIndex) { - *faceOrigIndex = origIndex; + /* reference the index in 'polyOrigIndex' */ + *faceOrigIndex = faceNum; faceOrigIndex++; } if (polyOrigIndex) { diff --git a/source/blender/blenkernel/intern/text.c b/source/blender/blenkernel/intern/text.c index 05d0705107d..d230cf8f1fe 100644 --- a/source/blender/blenkernel/intern/text.c +++ b/source/blender/blenkernel/intern/text.c @@ -55,12 +55,15 @@ #include "DNA_text_types.h" #include "DNA_userdef_types.h" #include "DNA_object_types.h" +#include "DNA_node_types.h" +#include "DNA_material_types.h" #include "BKE_depsgraph.h" #include "BKE_global.h" #include "BKE_library.h" #include "BKE_main.h" #include "BKE_text.h" +#include "BKE_node.h" #ifdef WITH_PYTHON @@ -314,7 +317,7 @@ int BKE_text_reload(Text *text) fseek(fp, 0L, SEEK_END); len = ftell(fp); - fseek(fp, 0L, SEEK_SET); + fseek(fp, 0L, SEEK_SET); text->undo_pos = -1; @@ -370,7 +373,7 @@ int BKE_text_reload(Text *text) text->curl = text->sell = text->lines.first; text->curc = text->selc = 0; - MEM_freeN(buffer); + MEM_freeN(buffer); return 1; } @@ -404,7 +407,7 @@ Text *BKE_text_load(const char *file, const char *relpath) fseek(fp, 0L, SEEK_END); len = ftell(fp); - fseek(fp, 0L, SEEK_SET); + fseek(fp, 0L, SEEK_SET); ta->name = MEM_mallocN(strlen(file) + 1, "text_name"); strcpy(ta->name, file); @@ -469,7 +472,7 @@ Text *BKE_text_load(const char *file, const char *relpath) ta->curl = ta->sell = ta->lines.first; ta->curc = ta->selc = 0; - MEM_freeN(buffer); + MEM_freeN(buffer); return ta; } @@ -531,6 +534,9 @@ void BKE_text_unlink(Main *bmain, Text *text) bController *cont; bActuator *act; bConstraint *con; + bNodeTree *ntree; + bNode *node; + Material *mat; short update; for (ob = bmain->object.first; ob; ob = ob->id.next) { @@ -582,6 +588,28 @@ void BKE_text_unlink(Main *bmain, Text *text) DAG_id_tag_update(&ob->id, OB_RECALC_DATA); } + /* nodes */ + for (mat = bmain->mat.first; mat; mat = mat->id.next) { + ntree = mat->nodetree; + if (!ntree) + continue; + for (node = ntree->nodes.first; node; node = node->next) { + if (node->type == SH_NODE_SCRIPT) { + Text *ntext = (Text *)node->id; + if (ntext == text) node->id = NULL; + } + } + } + + for (ntree = bmain->nodetree.first; ntree; ntree = ntree->id.next) { + for (node = ntree->nodes.first; node; node = node->next) { + if (node->type == SH_NODE_SCRIPT) { + Text *ntext = (Text *)node->id; + if (ntext == text) node->id = NULL; + } + } + } + /* text space */ for (scr = bmain->screen.first; scr; scr = scr->id.next) { for (area = scr->areabase.first; area; area = area->next) { @@ -683,7 +711,7 @@ void txt_clean_text(Text *text) if (!text->lines.first) { if (text->lines.last) text->lines.first = text->lines.last; else text->lines.first = text->lines.last = txt_new_line(NULL); - } + } if (!text->lines.last) text->lines.last = text->lines.first; @@ -732,7 +760,7 @@ int txt_get_span(TextLine *from, TextLine *to) if (!tmp) ret = 0; } - return ret; + return ret; } static void txt_make_dirty(Text *text) @@ -934,7 +962,7 @@ void txt_move_right(Text *text, short sel) txt_move_down(text, sel); *charp = 0; } - } + } else { // do nice right only if there are only spaces // spaces hardcoded in DNA_text_types.h @@ -1376,7 +1404,7 @@ int txt_find_string(Text *text, const char *findstr, int wrap, int match_case) int newc = (int)(s - tl->line); txt_move_to(text, newl, newc, 0); txt_move_to(text, newl, newc + strlen(findstr), 1); - return 1; + return 1; } else return 0; @@ -1458,7 +1486,7 @@ char *txt_sel_to_buf(Text *text) length += charl; buf[length] = 0; - } + } return buf; } @@ -2078,7 +2106,7 @@ void txt_do_undo(Text *text) charp = op - UNDO_BS_1 + 1; txt_add_char(text, txt_undo_read_unicode(text->undo_buf, &text->undo_pos, charp)); text->undo_pos--; - break; + break; case UNDO_DEL_1: case UNDO_DEL_2: case UNDO_DEL_3: case UNDO_DEL_4: charp = op - UNDO_DEL_1 + 1; @@ -2104,7 +2132,7 @@ void txt_do_undo(Text *text) txt_curs_first(text, &holdl, &holdc); holdln = txt_get_span(text->lines.first, holdl); - txt_insert_buf(text, buf); + txt_insert_buf(text, buf); MEM_freeN(buf); text->curl = text->lines.first; @@ -2235,7 +2263,7 @@ void txt_do_redo(Text *text) unsigned short charp; char *buf; - text->undo_pos++; + text->undo_pos++; op = text->undo_buf[text->undo_pos]; if (!op) { @@ -2351,7 +2379,7 @@ void txt_do_redo(Text *text) text->undo_pos += linep; buf[linep] = 0; - txt_insert_buf(text, buf); + txt_insert_buf(text, buf); MEM_freeN(buf); text->undo_pos++; @@ -2369,7 +2397,7 @@ void txt_do_redo(Text *text) //charp is the first char selected or 0 linep = txt_redo_read_uint32(text->undo_buf, &text->undo_pos); - //linep is now the first line of the selection + //linep is now the first line of the selection //set the selcetion for this now text->curc = charp; text->curl = text->lines.first; @@ -2476,7 +2504,7 @@ void txt_split_curline(Text *text) text->curl->format = NULL; text->curl->len = text->curl->len - text->curc; - BLI_insertlinkbefore(&text->lines, text->curl, ins); + BLI_insertlinkbefore(&text->lines, text->curl, ins); text->curc = 0; @@ -2834,7 +2862,7 @@ int txt_replace_char(Text *text, unsigned int add) void txt_indent(Text *text) { - int len, num; + int len, num, curc_old; char *tmp; const char *add = "\t"; @@ -2857,6 +2885,8 @@ void txt_indent(Text *text) indentlen = spaceslen; } + curc_old = text->curc; + num = 0; while (TRUE) { tmp = MEM_mallocN(text->curl->len + indentlen + 1, "textline_string"); @@ -2877,7 +2907,7 @@ void txt_indent(Text *text) txt_clean_text(text); if (text->curl == text->sell) { - text->selc = text->sell->len; + text->selc += indentlen; break; } else { @@ -2885,7 +2915,9 @@ void txt_indent(Text *text) num++; } } - text->curc = 0; + if (!curc_old) text->curc = 0; + else text->curc = curc_old + indentlen; + while (num > 0) { text->curl = text->curl->prev; num--; @@ -2900,7 +2932,8 @@ void txt_unindent(Text *text) { int num = 0; const char *remove = "\t"; - int indent = 1; + int indentlen = 1; + int unindented_first = FALSE; /* hardcoded: TXT_TABSIZE = 4 spaces: */ int spaceslen = TXT_TABSIZE; @@ -2912,25 +2945,26 @@ void txt_unindent(Text *text) /* insert spaces rather than tabs */ if (text->flags & TXT_TABSTOSPACES) { remove = tab_to_spaces; - indent = spaceslen; + indentlen = spaceslen; } while (TRUE) { int i = 0; - if (BLI_strncasecmp(text->curl->line, remove, indent) == 0) { + if (BLI_strncasecmp(text->curl->line, remove, indentlen) == 0) { + if (num == 0) unindented_first = TRUE; while (i < text->curl->len) { - text->curl->line[i] = text->curl->line[i + indent]; + text->curl->line[i] = text->curl->line[i + indentlen]; i++; } - text->curl->len -= indent; + text->curl->len -= indentlen; } txt_make_dirty(text); txt_clean_text(text); if (text->curl == text->sell) { - text->selc = text->sell->len; + if (i > 0) text->selc = MAX2(text->selc - indentlen, 0); break; } else { @@ -2939,7 +2973,9 @@ void txt_unindent(Text *text) } } - text->curc = 0; + + if (unindented_first) text->curc = MAX2(text->curc - indentlen, 0); + while (num > 0) { text->curl = text->curl->prev; num--; diff --git a/source/blender/blenkernel/intern/texture.c b/source/blender/blenkernel/intern/texture.c index 9dd83181521..6d0313f6334 100644 --- a/source/blender/blenkernel/intern/texture.c +++ b/source/blender/blenkernel/intern/texture.c @@ -571,7 +571,7 @@ void default_mtex(MTex *mtex) mtex->size[1] = 1.0; mtex->size[2] = 1.0; mtex->tex = NULL; - mtex->texflag = MTEX_3TAP_BUMP | MTEX_BUMP_OBJECTSPACE; + mtex->texflag = MTEX_3TAP_BUMP | MTEX_BUMP_OBJECTSPACE | MTEX_MAPTO_BOUNDS; mtex->colormodel = 0; mtex->r = 1.0; mtex->g = 0.0; @@ -646,7 +646,7 @@ MTex *add_mtex_id(ID *id, int slot) if (slot == -1) { /* find first free */ - int i; + int i; for (i = 0; i < MAX_MTEX; i++) { if (!mtex_ar[i]) { slot = i; @@ -909,8 +909,7 @@ void autotexname(Tex *tex) if (tex->use_nodes) { new_id(&bmain->tex, (ID *)tex, "Noddy"); } - else - if (tex->type == TEX_IMAGE) { + else if (tex->type == TEX_IMAGE) { ima = tex->ima; if (ima) { BLI_strncpy(di, ima->name, sizeof(di)); diff --git a/source/blender/blenkernel/intern/tracking.c b/source/blender/blenkernel/intern/tracking.c index c9d7ec3964f..b174f27b7e1 100644 --- a/source/blender/blenkernel/intern/tracking.c +++ b/source/blender/blenkernel/intern/tracking.c @@ -51,6 +51,8 @@ #include "BLI_string.h" #include "BLI_threads.h" +#include "BLF_translation.h" + #include "BKE_global.h" #include "BKE_tracking.h" #include "BKE_movieclip.h" @@ -169,10 +171,9 @@ void BKE_tracking_settings_init(MovieTracking *tracking) tracking->settings.default_minimum_correlation = 0.75; tracking->settings.default_pattern_size = 11; tracking->settings.default_search_size = 61; - tracking->settings.keyframe1 = 1; - tracking->settings.keyframe2 = 30; tracking->settings.dist = 1; tracking->settings.object_distance = 1; + tracking->settings.reconstruction_success_threshold = 1e-3; tracking->stabilization.scaleinf = 1.0f; tracking->stabilization.locinf = 1.0f; @@ -223,7 +224,7 @@ void BKE_tracking_get_projection_matrix(MovieTracking *tracking, MovieTrackingOb float viewfac, pixsize, left, right, bottom, top, clipsta, clipend; float winmat[4][4]; float ycor = 1.0f / tracking->camera.pixel_aspect; - float shiftx, shifty, winside = MAX2(winx, winy); + float shiftx, shifty, winside = (float)min_ii(winx, winy); BKE_tracking_camera_shift_get(tracking, winx, winy, &shiftx, &shifty); @@ -633,7 +634,7 @@ void BKE_tracking_track_path_clear(MovieTrackingTrack *track, int ref_frame, int } } -void BKE_tracking_tracks_join(MovieTrackingTrack *dst_track, MovieTrackingTrack *src_track) +void BKE_tracking_tracks_join(MovieTracking *tracking, MovieTrackingTrack *dst_track, MovieTrackingTrack *src_track) { int i = 0, a = 0, b = 0, tot; MovieTrackingMarker *markers; @@ -736,6 +737,8 @@ void BKE_tracking_tracks_join(MovieTrackingTrack *dst_track, MovieTrackingTrack dst_track->markersnr = i; MEM_freeN(markers); + + BKE_tracking_dopesheet_tag_update(tracking); } MovieTrackingTrack *BKE_tracking_track_get_named(MovieTracking *tracking, MovieTrackingObject *object, const char *name) @@ -997,8 +1000,8 @@ void BKE_tracking_marker_clamp(MovieTrackingMarker *marker, int event) if (event == CLAMP_PAT_DIM) { for (a = 0; a < 2; a++) { /* search shouldn't be resized smaller than pattern */ - marker->search_min[a] = minf(pat_min[a], marker->search_min[a]); - marker->search_max[a] = maxf(pat_max[a], marker->search_max[a]); + marker->search_min[a] = min_ff(pat_min[a], marker->search_min[a]); + marker->search_max[a] = max_ff(pat_max[a], marker->search_max[a]); } } else if (event == CLAMP_PAT_POS) { @@ -1022,8 +1025,8 @@ void BKE_tracking_marker_clamp(MovieTrackingMarker *marker, int event) else if (event == CLAMP_SEARCH_DIM) { for (a = 0; a < 2; a++) { /* search shouldn't be resized smaller than pattern */ - marker->search_min[a] = minf(pat_min[a], marker->search_min[a]); - marker->search_max[a] = maxf(pat_max[a], marker->search_max[a]); + marker->search_min[a] = min_ff(pat_min[a], marker->search_min[a]); + marker->search_max[a] = max_ff(pat_max[a], marker->search_max[a]); } } else if (event == CLAMP_SEARCH_POS) { @@ -1179,23 +1182,25 @@ MovieTrackingObject *BKE_tracking_object_add(MovieTracking *tracking, const char tracking->objectnr = BLI_countlist(&tracking->objects) - 1; object->scale = 1.0f; + object->keyframe1 = 1; + object->keyframe2 = 30; BKE_tracking_object_unique_name(tracking, object); return object; } -void BKE_tracking_object_delete(MovieTracking *tracking, MovieTrackingObject *object) +int BKE_tracking_object_delete(MovieTracking *tracking, MovieTrackingObject *object) { MovieTrackingTrack *track; int index = BLI_findindex(&tracking->objects, object); - if (index < 0) - return; + if (index == -1) + return FALSE; if (object->flag & TRACKING_OBJECT_CAMERA) { /* object used for camera solving can't be deleted */ - return; + return FALSE; } track = object->tracks.first; @@ -1211,10 +1216,11 @@ void BKE_tracking_object_delete(MovieTracking *tracking, MovieTrackingObject *ob tracking->tot_object--; - if (index > 0) + if (index != 0) tracking->objectnr = index - 1; else tracking->objectnr = 0; + return TRUE; } void BKE_tracking_object_unique_name(MovieTracking *tracking, MovieTrackingObject *object) @@ -1494,7 +1500,8 @@ ImBuf *BKE_tracking_distortion_exec(MovieDistortion *distortion, MovieTracking * ibuf->x, ibuf->y, overscan, ibuf->channels); } - resibuf->userflags |= IB_RECT_INVALID; + if (ibuf->rect) + imb_freerectImBuf(ibuf); } else { if (undistort) { @@ -1512,9 +1519,8 @@ ImBuf *BKE_tracking_distortion_exec(MovieDistortion *distortion, MovieTracking * (void) overscan; (void) undistort; - if (ibuf->rect_float) { - resibuf->userflags |= IB_RECT_INVALID; - } + if (ibuf->rect_float && ibuf->rect) + imb_freerectImBuf(ibuf); #endif return resibuf; @@ -1618,6 +1624,9 @@ ImBuf *BKE_tracking_sample_pattern(int frame_width, int frame_height, ImBuf *sea double warped_position_x, warped_position_y; float *mask = NULL; + if (num_samples_x <= 0 || num_samples_y <= 0) + return NULL; + pattern_ibuf = IMB_allocImBuf(num_samples_x, num_samples_y, 32, IB_rectfloat); if (!search_ibuf->rect_float) { @@ -1684,10 +1693,15 @@ ImBuf *BKE_tracking_get_pattern_imbuf(ImBuf *ibuf, MovieTrackingTrack *track, Mo search_ibuf = BKE_tracking_get_search_imbuf(ibuf, track, marker, anchored, disable_channels); - pattern_ibuf = BKE_tracking_sample_pattern(ibuf->x, ibuf->y, search_ibuf, track, marker, - FALSE, num_samples_x, num_samples_y, NULL); + if (search_ibuf) { + pattern_ibuf = BKE_tracking_sample_pattern(ibuf->x, ibuf->y, search_ibuf, track, marker, + FALSE, num_samples_x, num_samples_y, NULL); - IMB_freeImBuf(search_ibuf); + IMB_freeImBuf(search_ibuf); + } + else { + pattern_ibuf = NULL; + } return pattern_ibuf; } @@ -1712,6 +1726,9 @@ ImBuf *BKE_tracking_get_search_imbuf(ImBuf *ibuf, MovieTrackingTrack *track, Mov 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) + return NULL; + searchibuf = IMB_allocImBuf(w, h, 32, ibuf->rect_float ? IB_rectfloat : IB_rect); IMB_rectcpy(searchibuf, ibuf, 0, 0, x, y, w, h); @@ -2136,7 +2153,7 @@ void BKE_tracking_context_sync(MovieTrackingContext *context) context->sync_frame = newframe; - tracking->dopesheet.ok = FALSE; + BKE_tracking_dopesheet_tag_update(tracking); } void BKE_tracking_context_sync_user(const MovieTrackingContext *context, MovieClipUser *user) @@ -2181,6 +2198,12 @@ static float *track_get_search_floatbuf(ImBuf *ibuf, MovieTrackingTrack *track, searchibuf = BKE_tracking_get_search_imbuf(ibuf, track, marker, FALSE, TRUE); + if (!searchibuf) { + *width_r = 0; + *height_r = 0; + return NULL; + } + width = searchibuf->x; height = searchibuf->y; @@ -2343,10 +2366,10 @@ static int tracking_check_marker_margin(MovieTrackingTrack *track, MovieTracking /* margin from frame boundaries */ BKE_tracking_marker_pattern_minmax(marker, pat_min, pat_max); sub_v2_v2v2(dim, pat_max, pat_min); - margin[0] = margin[1] = maxf(dim[0], dim[1]) / 2.0f; + margin[0] = margin[1] = max_ff(dim[0], dim[1]) / 2.0f; - margin[0] = maxf(margin[0], (float)track->margin / frame_width); - margin[1] = maxf(margin[1], (float)track->margin / frame_height); + margin[0] = max_ff(margin[0], (float)track->margin / frame_width); + margin[1] = max_ff(margin[1], (float)track->margin / frame_height); /* do not track markers which are too close to boundary */ if (marker->pos[0] < margin[0] || marker->pos[0] > 1.0f - margin[0] || @@ -2500,6 +2523,9 @@ int BKE_tracking_context_step(MovieTrackingContext *context) get_marker_coords_for_tracking(frame_width, frame_height, &track_context->marker, src_pixel_x, src_pixel_y); get_marker_coords_for_tracking(frame_width, frame_height, marker, dst_pixel_x, dst_pixel_y); + if (!patch_new || !track_context->search_area) + continue; + /* run the tracker! */ tracked = libmv_trackRegion(&options, track_context->search_area, @@ -2556,6 +2582,9 @@ typedef struct MovieReconstructContext { TracksMap *tracks_map; + float success_threshold; + int use_fallback_reconstruction; + int sfra, efra; } MovieReconstructContext; @@ -2755,10 +2784,11 @@ static int reconstruct_refine_intrinsics_get_flags(MovieTracking *tracking, Movi return flags; } -static int reconstruct_count_tracks_on_both_keyframes(MovieTracking *tracking, ListBase *tracksbase) +static int reconstruct_count_tracks_on_both_keyframes(MovieTracking *tracking, MovieTrackingObject *object) { + ListBase *tracksbase = BKE_tracking_object_get_tracks(tracking, object); int tot = 0; - int frame1 = tracking->settings.keyframe1, frame2 = tracking->settings.keyframe2; + int frame1 = object->keyframe1, frame2 = object->keyframe2; MovieTrackingTrack *track; track = tracksbase->first; @@ -2779,14 +2809,12 @@ static int reconstruct_count_tracks_on_both_keyframes(MovieTracking *tracking, L int BKE_tracking_reconstruction_check(MovieTracking *tracking, MovieTrackingObject *object, char *error_msg, int error_size) { #ifdef WITH_LIBMV - ListBase *tracksbase = BKE_tracking_object_get_tracks(tracking, object); - if (tracking->settings.motion_flag & TRACKING_MOTION_MODAL) { /* TODO: check for number of tracks? */ return TRUE; } - else if (reconstruct_count_tracks_on_both_keyframes(tracking, tracksbase) < 8) { - BLI_strncpy(error_msg, "At least 8 common tracks on both of keyframes are needed for reconstruction", + else if (reconstruct_count_tracks_on_both_keyframes(tracking, object) < 8) { + BLI_strncpy(error_msg, N_("At least 8 common tracks on both of keyframes are needed for reconstruction"), error_size); return FALSE; @@ -2794,7 +2822,7 @@ int BKE_tracking_reconstruction_check(MovieTracking *tracking, MovieTrackingObje return TRUE; #else - BLI_strncpy(error_msg, "Blender is compiled without motion tracking library", error_size); + BLI_strncpy(error_msg, N_("Blender is compiled without motion tracking library"), error_size); (void) tracking; (void) object; @@ -2826,6 +2854,9 @@ MovieReconstructContext *BKE_tracking_reconstruction_context_new(MovieTracking * context->k2 = camera->k2; context->k3 = camera->k3; + context->success_threshold = tracking->settings.reconstruction_success_threshold; + context->use_fallback_reconstruction = tracking->settings.reconstruction_flag & TRACKING_USE_FALLBACK_RECONSTRUCTION; + context->tracks_map = tracks_map_new(context->object_name, context->is_camera, num_tracks, 0); track = tracksbase->first; @@ -2847,10 +2878,10 @@ MovieReconstructContext *BKE_tracking_reconstruction_context_new(MovieTracking * } if (first < track->markersnr - 1) - sfra = MIN2(sfra, first_marker->framenr); + sfra = min_ii(sfra, first_marker->framenr); if (last >= 0) - efra = MAX2(efra, last_marker->framenr); + efra = max_ii(efra, last_marker->framenr); tracks_map_insert(context->tracks_map, track, NULL); @@ -2925,12 +2956,18 @@ void BKE_tracking_reconstruction_solve(MovieReconstructContext *context, short * reconstruct_update_solve_cb, &progressdata); } else { + struct libmv_reconstructionOptions options; + + options.success_threshold = context->success_threshold; + options.use_fallback_reconstruction = context->use_fallback_reconstruction; + context->reconstruction = libmv_solveReconstruction(context->tracks, context->keyframe1, context->keyframe2, context->refine_flags, context->focal_length, context->principal_point[0], context->principal_point[1], context->k1, context->k2, context->k3, + &options, reconstruct_update_solve_cb, &progressdata); } @@ -2952,6 +2989,7 @@ int BKE_tracking_reconstruction_finish(MovieReconstructContext *context, MovieTr MovieTrackingReconstruction *reconstruction; tracks_map_merge(context->tracks_map, tracking); + BKE_tracking_dopesheet_tag_update(tracking); if (context->is_camera) { reconstruction = &tracking->reconstruction; @@ -3197,8 +3235,8 @@ static float stabilization_calculate_autoscale_factor(MovieTracking *tracking, i if (track->flag & TRACK_USE_2D_STAB || ((stab->flag & TRACKING_STABILIZE_ROTATION) && track == stab->rot_track)) { - sfra = MIN2(sfra, track->markers[0].framenr); - efra = MAX2(efra, track->markers[track->markersnr - 1].framenr); + sfra = min_ii(sfra, track->markers[0].framenr); + efra = max_ii(efra, track->markers[track->markersnr - 1].framenr); } track = track->next; @@ -3274,7 +3312,7 @@ static float stabilization_calculate_autoscale_factor(MovieTracking *tracking, i S = (-w * I - h * J) / (dx * I + dy * J + K); - scale = maxf(scale, S); + scale = max_ff(scale, S); } } } @@ -3283,7 +3321,7 @@ static float stabilization_calculate_autoscale_factor(MovieTracking *tracking, i stab->scale = scale; if (stab->maxscale > 0.0f) - stab->scale = minf(stab->scale, stab->maxscale); + stab->scale = min_ff(stab->scale, stab->maxscale); } else { stab->scale = 1.0f; @@ -3642,7 +3680,7 @@ static void channels_segments_calc(MovieTrackingDopesheetChannel *channel) channel->segments[2 * segment] = start_marker->framenr; channel->segments[2 * segment + 1] = start_marker->framenr + len; - channel->max_segment = MAX2(channel->max_segment, len); + channel->max_segment = max_ii(channel->max_segment, len); segment++; } @@ -3650,7 +3688,7 @@ static void channels_segments_calc(MovieTrackingDopesheetChannel *channel) } } -static void tracking_dopesheet_sort(MovieTracking *tracking, int sort_method, int inverse) +static void tracking_dopesheet_sort(MovieTracking *tracking, int sort_method, int inverse) { MovieTrackingDopesheet *dopesheet = &tracking->dopesheet; diff --git a/source/blender/blenkernel/intern/unit.c b/source/blender/blenkernel/intern/unit.c index 46836b1f8d1..84e1f29f6c0 100644 --- a/source/blender/blenkernel/intern/unit.c +++ b/source/blender/blenkernel/intern/unit.c @@ -259,7 +259,7 @@ static struct bUnitCollection buNaturalTimeCollecton = {buNaturalTimeDef, 3, 0, static struct bUnitDef buNaturalRotDef[] = { - {"degree", "degrees", "°", NULL, "Degrees", M_PI/180.0, 0.0, B_UNIT_DEF_NONE}, + {"degree", "degrees", "°", NULL, "Degrees", M_PI / 180.0, 0.0, B_UNIT_DEF_NONE}, // {"radian", "radians", "r", NULL, "Radians", 1.0, 0.0, B_UNIT_DEF_NONE}, // {"turn", "turns", "t", NULL, "Turns", 1.0/(M_PI*2.0), 0.0,B_UNIT_DEF_NONE}, {NULL, NULL, NULL, NULL, NULL, 0.0, 0.0} diff --git a/source/blender/blenkernel/intern/world.c b/source/blender/blenkernel/intern/world.c index 434bfe19c1f..4bde895cf7d 100644 --- a/source/blender/blenkernel/intern/world.c +++ b/source/blender/blenkernel/intern/world.c @@ -107,7 +107,7 @@ World *add_world(const char *name) wrld->ao_indirect_energy = 1.0f; wrld->ao_indirect_bounces = 1; wrld->aobias = 0.05f; - wrld->ao_samp_method = WO_AOSAMP_HAMMERSLEY; + wrld->ao_samp_method = WO_AOSAMP_HAMMERSLEY; wrld->ao_approx_error = 0.25f; wrld->preview = NULL; diff --git a/source/blender/blenkernel/intern/writeavi.c b/source/blender/blenkernel/intern/writeavi.c index dab44b5463c..d4428be3faf 100644 --- a/source/blender/blenkernel/intern/writeavi.c +++ b/source/blender/blenkernel/intern/writeavi.c @@ -47,7 +47,11 @@ #include "BKE_report.h" #include "BKE_writeavi.h" -#include "AVI_avi.h" + +/* ********************** general blender movie support ***************************** */ + +#ifdef WITH_AVI +# include "AVI_avi.h" /* callbacks */ static int start_avi(Scene *scene, RenderData *rd, int rectx, int recty, ReportList *reports); @@ -55,30 +59,31 @@ static void end_avi(void); static int append_avi(RenderData *rd, int start_frame, int frame, int *pixels, int rectx, int recty, ReportList *reports); static void filepath_avi(char *string, RenderData *rd); - -/* ********************** general blender movie support ***************************** */ +#endif /* WITH_AVI */ #ifdef WITH_QUICKTIME -#include "quicktime_export.h" +# include "quicktime_export.h" #endif #ifdef WITH_FFMPEG -#include "BKE_writeffmpeg.h" +# include "BKE_writeffmpeg.h" #endif #include "BKE_writeframeserver.h" bMovieHandle *BKE_movie_handle_get(const char imtype) { - static bMovieHandle mh; + static bMovieHandle mh = {0}; /* set the default handle, as builtin */ +#ifdef WITH_AVI mh.start_movie = start_avi; mh.append_movie = append_avi; mh.end_movie = end_avi; mh.get_next_frame = NULL; mh.get_movie_path = filepath_avi; - +#endif + /* do the platform specific handles */ #ifdef WITH_QUICKTIME if (imtype == R_IMF_IMTYPE_QUICKTIME) { @@ -114,6 +119,8 @@ bMovieHandle *BKE_movie_handle_get(const char imtype) /* ****************************************************************** */ +#ifdef WITH_AVI + static AviMovie *avi = NULL; static void filepath_avi(char *string, RenderData *rd) @@ -155,7 +162,7 @@ static int start_avi(Scene *scene, RenderData *rd, int rectx, int recty, ReportL 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."); + BKE_report(reports, RPT_ERROR, "Cannot open or start AVI movie file"); MEM_freeN(avi); avi = NULL; return 0; @@ -168,8 +175,8 @@ static int start_avi(Scene *scene, RenderData *rd, int rectx, int recty, ReportL avi->interlace = 0; avi->odd_fields = 0; -/* avi->interlace= rd->mode & R_FIELDS; */ -/* avi->odd_fields= (rd->mode & R_ODDFIELD)?1:0; */ +/* avi->interlace = rd->mode & R_FIELDS; */ +/* avi->odd_fields = (rd->mode & R_ODDFIELD) ? 1 : 0; */ printf("Created avi: %s\n", name); return 1; @@ -219,6 +226,7 @@ static void end_avi(void) MEM_freeN(avi); avi = NULL; } +#endif /* WITH_AVI */ /* similar to BKE_makepicstring() */ void BKE_movie_filepath_get(char *string, RenderData *rd) diff --git a/source/blender/blenkernel/intern/writeffmpeg.c b/source/blender/blenkernel/intern/writeffmpeg.c index ff1fdebb728..da9c919c109 100644 --- a/source/blender/blenkernel/intern/writeffmpeg.c +++ b/source/blender/blenkernel/intern/writeffmpeg.c @@ -289,7 +289,7 @@ static int write_video_frame(RenderData *rd, int cfra, AVFrame *frame, ReportLis } if (!success) - BKE_report(reports, RPT_ERROR, "Error writing frame."); + BKE_report(reports, RPT_ERROR, "Error writing frame"); return success; } @@ -307,7 +307,7 @@ static AVFrame *generate_video_frame(uint8_t *pixels, ReportList *reports) if (c->pix_fmt != PIX_FMT_BGR32) { rgb_frame = alloc_picture(PIX_FMT_BGR32, width, height); if (!rgb_frame) { - BKE_report(reports, RPT_ERROR, "Couldn't allocate temporary frame."); + BKE_report(reports, RPT_ERROR, "Could not allocate temporary frame"); return NULL; } } @@ -478,9 +478,7 @@ static AVStream *alloc_video_stream(RenderData *rd, int codec_id, AVFormatContex c->time_base.den = 2997; c->time_base.num = 100; } - else if ((double) ((int) rd->frs_sec_base) == - rd->frs_sec_base) - { + else if ((float) ((int) rd->frs_sec_base) == rd->frs_sec_base) { c->time_base.den = rd->frs_sec; c->time_base.num = (int) rd->frs_sec_base; } @@ -695,12 +693,12 @@ static int start_ffmpeg_impl(struct RenderData *rd, int rectx, int recty, Report exts = get_file_extensions(ffmpeg_type); if (!exts) { - BKE_report(reports, RPT_ERROR, "No valid formats found."); + BKE_report(reports, RPT_ERROR, "No valid formats found"); return 0; } fmt = av_guess_format(NULL, exts[0], NULL); if (!fmt) { - BKE_report(reports, RPT_ERROR, "No valid formats found."); + BKE_report(reports, RPT_ERROR, "No valid formats found"); return 0; } @@ -795,7 +793,7 @@ static int start_ffmpeg_impl(struct RenderData *rd, int rectx, int recty, Report if (error[0]) BKE_report(reports, RPT_ERROR, error); else - BKE_report(reports, RPT_ERROR, "Error initializing video stream."); + BKE_report(reports, RPT_ERROR, "Error initializing video stream"); av_dict_free(&opts); return 0; @@ -805,20 +803,20 @@ static int start_ffmpeg_impl(struct RenderData *rd, int rectx, int recty, Report if (ffmpeg_audio_codec != CODEC_ID_NONE) { audio_stream = alloc_audio_stream(rd, fmt->audio_codec, of); if (!audio_stream) { - BKE_report(reports, RPT_ERROR, "Error initializing audio stream."); + BKE_report(reports, RPT_ERROR, "Error initializing audio stream"); av_dict_free(&opts); return 0; } } if (!(fmt->flags & AVFMT_NOFILE)) { if (avio_open(&of->pb, name, AVIO_FLAG_WRITE) < 0) { - BKE_report(reports, RPT_ERROR, "Could not open file for writing."); + BKE_report(reports, RPT_ERROR, "Could not open file for writing"); av_dict_free(&opts); return 0; } } if (avformat_write_header(of, NULL) < 0) { - BKE_report(reports, RPT_ERROR, "Could not initialize streams. Probably unsupported codec combination."); + BKE_report(reports, RPT_ERROR, "Could not initialize streams, probably unsupported codec combination"); av_dict_free(&opts); return 0; } @@ -982,7 +980,7 @@ int BKE_ffmpeg_append(RenderData *rd, int start_frame, int frame, int *pixels, i PRINT("Writing frame %i, render width=%d, render height=%d\n", frame, rectx, recty); -// why is this done before writing the video frame and again at end_ffmpeg? +/* why is this done before writing the video frame and again at end_ffmpeg? */ // write_audio_frames(frame / (((double)rd->frs_sec) / rd->frs_sec_base)); if (video_stream) { @@ -999,7 +997,7 @@ int BKE_ffmpeg_append(RenderData *rd, int start_frame, int frame, int *pixels, i } #ifdef WITH_AUDASPACE - write_audio_frames((frame - rd->sfra) / (((double)rd->frs_sec) / rd->frs_sec_base)); + write_audio_frames((frame - rd->sfra) / (((double)rd->frs_sec) / (double)rd->frs_sec_base)); #endif return success; } @@ -1225,7 +1223,7 @@ int BKE_ffmpeg_property_add_string(RenderData *rd, const char *type, const char while (*param == ' ') param++; } - o = my_av_find_opt(&c, name, NULL, 0, 0); + o = my_av_find_opt(&c, name, NULL, 0, 0); if (!o) { return 0; } @@ -1233,7 +1231,7 @@ int BKE_ffmpeg_property_add_string(RenderData *rd, const char *type, const char return 0; } if (param && o->type != FF_OPT_TYPE_CONST && o->unit) { - p = my_av_find_opt(&c, param, o->unit, 0, 0); + p = my_av_find_opt(&c, param, o->unit, 0, 0); if (p) { prop = BKE_ffmpeg_property_add(rd, (char *) type, p - c.av_class->option, o - c.av_class->option); } diff --git a/source/blender/blenkernel/intern/writeframeserver.c b/source/blender/blenkernel/intern/writeframeserver.c index d8fddb9851a..acbbcb0b043 100644 --- a/source/blender/blenkernel/intern/writeframeserver.c +++ b/source/blender/blenkernel/intern/writeframeserver.c @@ -118,13 +118,13 @@ int BKE_frameserver_start(struct Scene *scene, RenderData *UNUSED(rd), int rectx (void)scene; /* unused */ if (!startup_socket_system()) { - BKE_report(reports, RPT_ERROR, "Can't startup socket system"); + BKE_report(reports, RPT_ERROR, "Cannot startup socket system"); return 0; } if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { shutdown_socket_system(); - BKE_report(reports, RPT_ERROR, "Can't open socket"); + BKE_report(reports, RPT_ERROR, "Cannot open socket"); return 0; } @@ -136,13 +136,13 @@ int BKE_frameserver_start(struct Scene *scene, RenderData *UNUSED(rd), int rectx if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) { shutdown_socket_system(); - BKE_report(reports, RPT_ERROR, "Can't bind to socket"); + BKE_report(reports, RPT_ERROR, "Cannot bind to socket"); return 0; } if (listen(sock, SOMAXCONN) < 0) { shutdown_socket_system(); - BKE_report(reports, RPT_ERROR, "Can't establish listen backlog"); + BKE_report(reports, RPT_ERROR, "Cannot establish listen backlog"); return 0; } connsock = -1; diff --git a/source/blender/blenkernel/nla_private.h b/source/blender/blenkernel/nla_private.h index 941a74ec2ab..f068c4c58f0 100644 --- a/source/blender/blenkernel/nla_private.h +++ b/source/blender/blenkernel/nla_private.h @@ -85,4 +85,4 @@ NlaEvalStrip *nlastrips_ctime_get_strip(ListBase *list, ListBase *strips, short void nlastrip_evaluate(PointerRNA *ptr, ListBase *channels, ListBase *modifiers, NlaEvalStrip *nes); void nladata_flush_channels(ListBase *channels); -#endif // __NLA_PRIVATE_H__ +#endif /* __NLA_PRIVATE_H__ */ |