diff options
Diffstat (limited to 'source/blender/blenkernel/intern')
84 files changed, 2978 insertions, 2126 deletions
diff --git a/source/blender/blenkernel/intern/DerivedMesh.c b/source/blender/blenkernel/intern/DerivedMesh.c index 22d2eff6672..539a995078f 100644 --- a/source/blender/blenkernel/intern/DerivedMesh.c +++ b/source/blender/blenkernel/intern/DerivedMesh.c @@ -93,6 +93,10 @@ static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm); # define ASSERT_IS_VALID_DM(dm) #endif + +static ThreadMutex loops_cache_lock = BLI_MUTEX_INITIALIZER; + + static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *ob); static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape_uid); @@ -235,6 +239,23 @@ static int dm_getNumLoopTri(DerivedMesh *dm) return numlooptris; } +static const MLoopTri *dm_getLoopTriArray(DerivedMesh *dm) +{ + if (dm->looptris.array) { + BLI_assert(dm->getNumLoopTri(dm) == dm->looptris.num); + } + else { + BLI_mutex_lock(&loops_cache_lock); + /* We need to ensure array is still NULL inside mutex-protected code, some other thread might have already + * recomputed those looptris. */ + if (dm->looptris.array == NULL) { + dm->recalcLoopTri(dm); + } + BLI_mutex_unlock(&loops_cache_lock); + } + return dm->looptris.array; +} + static CustomData *dm_getVertCData(DerivedMesh *dm) { return &dm->vertData; @@ -278,6 +299,8 @@ void DM_init_funcs(DerivedMesh *dm) dm->dupLoopArray = dm_dupLoopArray; dm->dupPolyArray = dm_dupPolyArray; + dm->getLoopTriArray = dm_getLoopTriArray; + /* subtypes handle getting actual data */ dm->getNumLoopTri = dm_getNumLoopTri; @@ -497,19 +520,6 @@ void DM_ensure_looptri_data(DerivedMesh *dm) } } -/** - * The purpose of this function is that we can call: - * `dm->getLoopTriArray(dm)` and get the array returned. - */ -void DM_ensure_looptri(DerivedMesh *dm) -{ - const int numPolys = dm->getNumPolys(dm); - - if ((dm->looptris.num == 0) && (numPolys != 0)) { - dm->recalcLoopTri(dm); - } -} - void DM_verttri_from_looptri(MVertTri *verttri, const MLoop *mloop, const MLoopTri *looptri, int looptri_num) { int i; @@ -2201,7 +2211,6 @@ static void mesh_calc_modifiers( if (dataMask & CD_MASK_MFACE) { DM_ensure_tessface(finaldm); } - DM_ensure_looptri(finaldm); /* without this, drawing ngon tri's faces will show ugly tessellated face * normals and will also have to calculate normals on the fly, try avoid @@ -3322,7 +3331,8 @@ void DM_calc_loop_tangents_step_0( const CustomData *loopData, bool calc_active_tangent, const char (*tangent_names)[MAX_NAME], int tangent_names_count, bool *rcalc_act, bool *rcalc_ren, int *ract_uv_n, int *rren_uv_n, - char *ract_uv_name, char *rren_uv_name, char *rtangent_mask) { + char *ract_uv_name, char *rren_uv_name, short *rtangent_mask) +{ /* Active uv in viewport */ int layer_index = CustomData_get_layer_index(loopData, CD_MLOOPUV); *ract_uv_n = CustomData_get_active_layer(loopData, CD_MLOOPUV); @@ -3376,21 +3386,22 @@ void DM_calc_loop_tangents_step_0( if (add) *rtangent_mask |= 1 << n; } + + if (uv_layer_num == 0) + *rtangent_mask |= DM_TANGENT_MASK_ORCO; } void DM_calc_loop_tangents( DerivedMesh *dm, bool calc_active_tangent, const char (*tangent_names)[MAX_NAME], int tangent_names_count) { - if (CustomData_number_of_layers(&dm->loopData, CD_MLOOPUV) == 0) - return; int act_uv_n = -1; int ren_uv_n = -1; bool calc_act = false; bool calc_ren = false; char act_uv_name[MAX_NAME]; char ren_uv_name[MAX_NAME]; - char tangent_mask = 0; + short tangent_mask = 0; DM_calc_loop_tangents_step_0( &dm->loopData, calc_active_tangent, tangent_names, tangent_names_count, &calc_act, &calc_ren, &act_uv_n, &ren_uv_n, act_uv_name, ren_uv_name, &tangent_mask); @@ -3403,6 +3414,8 @@ void DM_calc_loop_tangents( for (int i = 0; i < tangent_names_count; i++) if (tangent_names[i][0]) DM_add_named_tangent_layer_for_uv(&dm->loopData, &dm->loopData, dm->numLoopData, tangent_names[i]); + if ((tangent_mask & DM_TANGENT_MASK_ORCO) && CustomData_get_named_layer_index(&dm->loopData, CD_TANGENT, "") == -1) + CustomData_add_layer_named(&dm->loopData, CD_TANGENT, CD_CALLOC, NULL, dm->numLoopData, ""); if (calc_act && act_uv_name[0]) DM_add_named_tangent_layer_for_uv(&dm->loopData, &dm->loopData, dm->numLoopData, act_uv_name); if (calc_ren && ren_uv_name[0]) @@ -3464,19 +3477,24 @@ void DM_calc_loop_tangents( mesh2tangent->orco = NULL; mesh2tangent->mloopuv = CustomData_get_layer_named(&dm->loopData, CD_MLOOPUV, dm->loopData.layers[index].name); + + /* Fill the resulting tangent_mask */ if (!mesh2tangent->mloopuv) { mesh2tangent->orco = dm->getVertDataArray(dm, CD_ORCO); if (!mesh2tangent->orco) continue; + + dm->tangent_mask |= DM_TANGENT_MASK_ORCO; + } + else { + int uv_ind = CustomData_get_named_layer_index(&dm->loopData, CD_MLOOPUV, dm->loopData.layers[index].name); + int uv_start = CustomData_get_layer_index(&dm->loopData, CD_MLOOPUV); + BLI_assert(uv_ind != -1 && uv_start != -1); + BLI_assert(uv_ind - uv_start < MAX_MTFACE); + dm->tangent_mask |= 1 << (uv_ind - uv_start); } - mesh2tangent->tangent = dm->loopData.layers[index].data; - /* Fill the resulting tangent_mask */ - int uv_ind = CustomData_get_named_layer_index(&dm->loopData, CD_MLOOPUV, dm->loopData.layers[index].name); - int uv_start = CustomData_get_layer_index(&dm->loopData, CD_MLOOPUV); - BLI_assert(uv_ind != -1 && uv_start != -1); - BLI_assert(uv_ind - uv_start < MAX_MTFACE); - dm->tangent_mask |= 1 << (uv_ind - uv_start); + mesh2tangent->tangent = dm->loopData.layers[index].data; BLI_task_pool_push(task_pool, DM_calc_loop_tangents_thread, mesh2tangent, false, TASK_PRIORITY_LOW); } @@ -3492,21 +3510,19 @@ void DM_calc_loop_tangents( #endif - int uv_index, tan_index; - /* Update active layer index */ - uv_index = CustomData_get_layer_index_n(&dm->loopData, CD_MLOOPUV, act_uv_n); - if (uv_index != -1) { - tan_index = CustomData_get_named_layer_index(&dm->loopData, CD_TANGENT, dm->loopData.layers[uv_index].name); + int act_uv_index = CustomData_get_layer_index_n(&dm->loopData, CD_MLOOPUV, act_uv_n); + if (act_uv_index != -1) { + int tan_index = CustomData_get_named_layer_index(&dm->loopData, CD_TANGENT, dm->loopData.layers[act_uv_index].name); CustomData_set_layer_active_index(&dm->loopData, CD_TANGENT, tan_index); - } + } /* else tangent has been built from orco */ /* Update render layer index */ - uv_index = CustomData_get_layer_index_n(&dm->loopData, CD_MLOOPUV, ren_uv_n); - if (uv_index != -1) { - tan_index = CustomData_get_named_layer_index(&dm->loopData, CD_TANGENT, dm->loopData.layers[uv_index].name); + int ren_uv_index = CustomData_get_layer_index_n(&dm->loopData, CD_MLOOPUV, ren_uv_n); + if (ren_uv_index != -1) { + int tan_index = CustomData_get_named_layer_index(&dm->loopData, CD_TANGENT, dm->loopData.layers[ren_uv_index].name); CustomData_set_layer_render_index(&dm->loopData, CD_TANGENT, tan_index); - } + } /* else tangent has been built from orco */ } } @@ -4379,35 +4395,3 @@ MFace *DM_get_tessface_array(DerivedMesh *dm, bool *r_allocated) return mface; } - -const MLoopTri *DM_get_looptri_array( - DerivedMesh *dm, - const MVert *mvert, - const MPoly *mpoly, int mpoly_len, - const MLoop *mloop, int mloop_len, - bool *r_allocated) -{ - const MLoopTri *looptri = dm->getLoopTriArray(dm); - *r_allocated = false; - - if (looptri == NULL) { - if (mpoly_len > 0) { - const int looptris_num = poly_to_tri_count(mpoly_len, mloop_len); - MLoopTri *looptri_data; - - looptri_data = MEM_mallocN(sizeof(MLoopTri) * looptris_num, __func__); - - BKE_mesh_recalc_looptri( - mloop, mpoly, - mvert, - mloop_len, mpoly_len, - looptri_data); - - looptri = looptri_data; - - *r_allocated = true; - } - } - - return looptri; -} diff --git a/source/blender/blenkernel/intern/action.c b/source/blender/blenkernel/intern/action.c index 1e33fe4ab46..bb4e09364d4 100644 --- a/source/blender/blenkernel/intern/action.c +++ b/source/blender/blenkernel/intern/action.c @@ -88,7 +88,7 @@ bAction *add_empty_action(Main *bmain, const char name[]) { bAction *act; - act = BKE_libblock_alloc(bmain, ID_AC, name); + act = BKE_libblock_alloc(bmain, ID_AC, name, 0); return act; } @@ -120,46 +120,56 @@ void BKE_action_free(bAction *act) /* .................................. */ -bAction *BKE_action_copy(Main *bmain, bAction *src) +/** + * Only copy internal data of Action ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_action_copy_data(Main *UNUSED(bmain), bAction *act_dst, const bAction *act_src, const int UNUSED(flag)) { - bAction *dst = NULL; - bActionGroup *dgrp, *sgrp; - FCurve *dfcu, *sfcu; - - if (src == NULL) - return NULL; - dst = BKE_libblock_copy(bmain, &src->id); - + bActionGroup *grp_dst, *grp_src; + FCurve *fcu_dst, *fcu_src; + /* duplicate the lists of groups and markers */ - BLI_duplicatelist(&dst->groups, &src->groups); - BLI_duplicatelist(&dst->markers, &src->markers); - + BLI_duplicatelist(&act_dst->groups, &act_src->groups); + BLI_duplicatelist(&act_dst->markers, &act_src->markers); + /* copy F-Curves, fixing up the links as we go */ - BLI_listbase_clear(&dst->curves); - - for (sfcu = src->curves.first; sfcu; sfcu = sfcu->next) { + BLI_listbase_clear(&act_dst->curves); + + for (fcu_src = act_src->curves.first; fcu_src; fcu_src = fcu_src->next) { /* duplicate F-Curve */ - dfcu = copy_fcurve(sfcu); - BLI_addtail(&dst->curves, dfcu); - + fcu_dst = copy_fcurve(fcu_src); /* XXX TODO pass subdata flag? But surprisingly does not seem to be doing any ID refcounting... */ + BLI_addtail(&act_dst->curves, fcu_dst); + /* fix group links (kindof bad list-in-list search, but this is the most reliable way) */ - for (dgrp = dst->groups.first, sgrp = src->groups.first; dgrp && sgrp; dgrp = dgrp->next, sgrp = sgrp->next) { - if (sfcu->grp == sgrp) { - dfcu->grp = dgrp; - - if (dgrp->channels.first == sfcu) - dgrp->channels.first = dfcu; - if (dgrp->channels.last == sfcu) - dgrp->channels.last = dfcu; - + for (grp_dst = act_dst->groups.first, grp_src = act_src->groups.first; + grp_dst && grp_src; + grp_dst = grp_dst->next, grp_src = grp_src->next) + { + if (fcu_src->grp == grp_src) { + fcu_dst->grp = grp_dst; + + if (grp_dst->channels.first == fcu_src) { + grp_dst->channels.first = fcu_dst; + } + if (grp_dst->channels.last == fcu_src) { + grp_dst->channels.last = fcu_dst; + } break; } } } - - BKE_id_copy_ensure_local(bmain, &src->id, &dst->id); +} - return dst; +bAction *BKE_action_copy(Main *bmain, const bAction *act_src) +{ + bAction *act_copy; + BKE_id_copy_ex(bmain, &act_src->id, (ID **)&act_copy, 0, false); + return act_copy; } /* *************** Action Groups *************** */ @@ -523,7 +533,7 @@ const char *BKE_pose_ikparam_get_name(bPose *pose) * * \param dst Should be freed already, makes entire duplicate. */ -void BKE_pose_copy_data(bPose **dst, bPose *src, const bool copy_constraints) +void BKE_pose_copy_data_ex(bPose **dst, const bPose *src, const int flag, const bool copy_constraints) { bPose *outPose; bPoseChannel *pchan; @@ -553,9 +563,8 @@ void BKE_pose_copy_data(bPose **dst, bPose *src, const bool copy_constraints) outPose->avs = src->avs; for (pchan = outPose->chanbase.first; pchan; pchan = pchan->next) { - - if (pchan->custom) { - id_us_plus(&pchan->custom->id); + if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) { + id_us_plus((ID *)pchan->custom); } /* warning, O(n2) here, if done without the hash, but these are rarely used features. */ @@ -570,13 +579,13 @@ void BKE_pose_copy_data(bPose **dst, bPose *src, const bool copy_constraints) } if (copy_constraints) { - BKE_constraints_copy(&listb, &pchan->constraints, true); // BKE_constraints_copy NULLs listb + BKE_constraints_copy_ex(&listb, &pchan->constraints, flag, true); // BKE_constraints_copy NULLs listb pchan->constraints = listb; pchan->mpath = NULL; /* motion paths should not get copied yet... */ } if (pchan->prop) { - pchan->prop = IDP_CopyProperty(pchan->prop); + pchan->prop = IDP_CopyProperty_ex(pchan->prop, flag); } } @@ -588,6 +597,11 @@ void BKE_pose_copy_data(bPose **dst, bPose *src, const bool copy_constraints) *dst = outPose; } +void BKE_pose_copy_data(bPose **dst, const bPose *src, const bool copy_constraints) +{ + BKE_pose_copy_data_ex(dst, src, 0, copy_constraints); +} + void BKE_pose_itasc_init(bItasc *itasc) { if (itasc) { diff --git a/source/blender/blenkernel/intern/anim_sys.c b/source/blender/blenkernel/intern/anim_sys.c index 0b637355ecf..64b33326aa9 100644 --- a/source/blender/blenkernel/intern/anim_sys.c +++ b/source/blender/blenkernel/intern/anim_sys.c @@ -259,7 +259,7 @@ void BKE_animdata_free(ID *id, const bool do_id_user) /* Copying -------------------------------------------- */ /* Make a copy of the given AnimData - to be used when copying datablocks */ -AnimData *BKE_animdata_copy(AnimData *adt, const bool do_action) +AnimData *BKE_animdata_copy(Main *bmain, AnimData *adt, const bool do_action) { AnimData *dadt; @@ -270,8 +270,9 @@ AnimData *BKE_animdata_copy(AnimData *adt, const bool do_action) /* make a copy of action - at worst, user has to delete copies... */ if (do_action) { - dadt->action = BKE_action_copy(G.main, adt->action); - dadt->tmpact = BKE_action_copy(G.main, adt->tmpact); + BLI_assert(bmain != NULL); + BKE_id_copy_ex(bmain, (ID *)dadt->action, (ID **)&dadt->action, 0, false); + BKE_id_copy_ex(bmain, (ID *)dadt->tmpact, (ID **)&dadt->tmpact, 0, false); } else { id_us_plus((ID *)dadt->action); @@ -291,7 +292,7 @@ AnimData *BKE_animdata_copy(AnimData *adt, const bool do_action) return dadt; } -bool BKE_animdata_copy_id(ID *id_to, ID *id_from, const bool do_action) +bool BKE_animdata_copy_id(Main *bmain, ID *id_to, ID *id_from, const bool do_action) { AnimData *adt; @@ -303,7 +304,7 @@ bool BKE_animdata_copy_id(ID *id_to, ID *id_from, const bool do_action) adt = BKE_animdata_from_id(id_from); if (adt) { IdAdtTemplate *iat = (IdAdtTemplate *)id_to; - iat->adt = BKE_animdata_copy(adt, do_action); + iat->adt = BKE_animdata_copy(bmain, adt, do_action); } return true; @@ -397,73 +398,6 @@ void BKE_animdata_merge_copy(ID *dst_id, ID *src_id, eAnimData_MergeCopy_Modes a } } -/* Make Local -------------------------------------------- */ - -static void make_local_strips(ListBase *strips) -{ - NlaStrip *strip; - - for (strip = strips->first; strip; strip = strip->next) { - if (strip->act) BKE_action_make_local(G.main, strip->act, false); - if (strip->remap && strip->remap->target) BKE_action_make_local(G.main, strip->remap->target, false); - - make_local_strips(&strip->strips); - } -} - -/* Use local copy instead of linked copy of various ID-blocks */ -void BKE_animdata_make_local(AnimData *adt) -{ - NlaTrack *nlt; - - /* Actions - Active and Temp */ - if (adt->action) BKE_action_make_local(G.main, adt->action, false); - if (adt->tmpact) BKE_action_make_local(G.main, adt->tmpact, false); - /* Remaps */ - if (adt->remap && adt->remap->target) BKE_action_make_local(G.main, adt->remap->target, false); - - /* Drivers */ - /* TODO: need to remap the ID-targets too? */ - - /* NLA Data */ - for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) - make_local_strips(&nlt->strips); -} - - -/* When duplicating data (i.e. objects), drivers referring to the original data will - * get updated to point to the duplicated data (if drivers belong to the new data) - */ -void BKE_animdata_relink(AnimData *adt) -{ - /* sanity check */ - if (adt == NULL) - return; - - /* drivers */ - if (adt->drivers.first) { - FCurve *fcu; - - /* check each driver against all the base paths to see if any should go */ - for (fcu = adt->drivers.first; fcu; fcu = fcu->next) { - ChannelDriver *driver = fcu->driver; - DriverVar *dvar; - - /* driver variables */ - for (dvar = driver->variables.first; dvar; dvar = dvar->next) { - /* only change the used targets, since the others will need fixing manually anyway */ - DRIVER_TARGETS_USED_LOOPER(dvar) - { - if (dtar->id && dtar->id->newid) { - dtar->id = dtar->id->newid; - } - } - DRIVER_TARGETS_LOOPER_END - } - } - } -} - /* Sub-ID Regrouping ------------------------------------------- */ /** @@ -690,6 +624,8 @@ char *BKE_animdata_driver_path_hack(bContext *C, PointerRNA *ptr, PropertyRNA *p } break; } + default: + break; } /* fix RNA pointer, as we've now changed the ID root by changing the paths */ @@ -1414,7 +1350,7 @@ void BKE_keyingset_free_path(KeyingSet *ks, KS_Path *ksp) } /* Copy all KeyingSets in the given list */ -void BKE_keyingsets_copy(ListBase *newlist, ListBase *list) +void BKE_keyingsets_copy(ListBase *newlist, const ListBase *list) { KeyingSet *ksn; KS_Path *kspn; @@ -1586,7 +1522,8 @@ static bool animsys_write_rna_setting(PathResolvedRNA *anim_rna, const float val } case PROP_INT: { - const int value_coerce = (int)value; + int value_coerce = (int)value; + RNA_property_int_clamp(ptr, prop, &value_coerce); if (array_index != -1) { if (RNA_property_int_get_index(ptr, prop, array_index) != value_coerce) { RNA_property_int_set_index(ptr, prop, array_index, value_coerce); @@ -1603,15 +1540,17 @@ static bool animsys_write_rna_setting(PathResolvedRNA *anim_rna, const float val } case PROP_FLOAT: { + float value_coerce = value; + RNA_property_float_clamp(ptr, prop, &value_coerce); if (array_index != -1) { - if (RNA_property_float_get_index(ptr, prop, array_index) != value) { - RNA_property_float_set_index(ptr, prop, array_index, value); + if (RNA_property_float_get_index(ptr, prop, array_index) != value_coerce) { + RNA_property_float_set_index(ptr, prop, array_index, value_coerce); written = true; } } else { - if (RNA_property_float_get(ptr, prop) != value) { - RNA_property_float_set(ptr, prop, value); + if (RNA_property_float_get(ptr, prop) != value_coerce) { + RNA_property_float_set(ptr, prop, value_coerce); written = true; } } diff --git a/source/blender/blenkernel/intern/appdir.c b/source/blender/blenkernel/intern/appdir.c index 43fd47981b1..f39d8006f76 100644 --- a/source/blender/blenkernel/intern/appdir.c +++ b/source/blender/blenkernel/intern/appdir.c @@ -106,7 +106,8 @@ const char *BKE_appdir_folder_default(void) static char *blender_version_decimal(const int ver) { static char version_str[5]; - sprintf(version_str, "%d.%02d", ver / 100, ver % 100); + BLI_assert(ver < 1000); + BLI_snprintf(version_str, sizeof(version_str), "%d.%02d", ver / 100, ver % 100); return version_str; } @@ -212,8 +213,10 @@ static bool get_path_local( /* try EXECUTABLE_DIR/2.5x/folder_name - new default directory for local blender installed files */ #ifdef __APPLE__ /* due new codesign situation in OSX > 10.9.5 we must move the blender_version dir with contents to Resources */ - static char osx_resourses[FILE_MAX]; - sprintf(osx_resourses, "%s../Resources", bprogdir); + char osx_resourses[FILE_MAX]; + BLI_snprintf(osx_resourses, sizeof(osx_resourses), "%s../Resources", bprogdir); + /* Remove the '/../' added above. */ + BLI_cleanup_path(NULL, osx_resourses); return test_path(targetpath, targetpath_len, osx_resourses, blender_version_decimal(ver), relfolder); #else return test_path(targetpath, targetpath_len, bprogdir, blender_version_decimal(ver), relfolder); @@ -591,6 +594,9 @@ static void where_am_i(char *fullname, const size_t maxlen, const char *name) else { BLI_path_program_search(fullname, maxlen, name); } + /* Remove "/./" and "/../" so string comparisons can be used on the path. */ + BLI_cleanup_path(NULL, fullname); + #if defined(DEBUG) if (!STREQ(name, fullname)) { printf("guessing '%s' == '%s'\n", name, fullname); diff --git a/source/blender/blenkernel/intern/armature.c b/source/blender/blenkernel/intern/armature.c index d7ea534068d..669344e18d7 100644 --- a/source/blender/blenkernel/intern/armature.c +++ b/source/blender/blenkernel/intern/armature.c @@ -83,7 +83,7 @@ bArmature *BKE_armature_add(Main *bmain, const char *name) { bArmature *arm; - arm = BKE_libblock_alloc(bmain, ID_AR, name); + arm = BKE_libblock_alloc(bmain, ID_AR, name, 0); arm->deformflag = ARM_DEF_VGROUP | ARM_DEF_ENVELOPE; arm->flag = ARM_COL_CUSTOM; /* custom bone-group colors */ arm->layer = 1; @@ -150,54 +150,70 @@ void BKE_armature_make_local(Main *bmain, bArmature *arm, const bool lib_local) BKE_id_make_local_generic(bmain, &arm->id, true, lib_local); } -static void copy_bonechildren(Bone *newBone, Bone *oldBone, Bone *actBone, Bone **newActBone) +static void copy_bonechildren( + Bone *bone_dst, const Bone *bone_src, const Bone *bone_src_act, Bone **r_bone_dst_act, const int flag) { - Bone *curBone, *newChildBone; + Bone *bone_src_child, *bone_dst_child; - if (oldBone == actBone) - *newActBone = newBone; + if (bone_src == bone_src_act) { + *r_bone_dst_act = bone_dst; + } - if (oldBone->prop) - newBone->prop = IDP_CopyProperty(oldBone->prop); + if (bone_src->prop) { + bone_dst->prop = IDP_CopyProperty_ex(bone_src->prop, flag); + } /* Copy this bone's list */ - BLI_duplicatelist(&newBone->childbase, &oldBone->childbase); + BLI_duplicatelist(&bone_dst->childbase, &bone_src->childbase); /* For each child in the list, update it's children */ - newChildBone = newBone->childbase.first; - for (curBone = oldBone->childbase.first; curBone; curBone = curBone->next) { - newChildBone->parent = newBone; - copy_bonechildren(newChildBone, curBone, actBone, newActBone); - newChildBone = newChildBone->next; + for (bone_src_child = bone_src->childbase.first, bone_dst_child = bone_dst->childbase.first; + bone_src_child; + bone_src_child = bone_src_child->next, bone_dst_child = bone_dst_child->next) + { + bone_dst_child->parent = bone_dst; + copy_bonechildren(bone_dst_child, bone_src_child, bone_src_act, r_bone_dst_act, flag); } } -bArmature *BKE_armature_copy(Main *bmain, bArmature *arm) +/** + * Only copy internal data of Armature ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_armature_copy_data(Main *UNUSED(bmain), bArmature *arm_dst, const bArmature *arm_src, const int flag) { - bArmature *newArm; - Bone *oldBone, *newBone; - Bone *newActBone = NULL; + Bone *bone_src, *bone_dst; + Bone *bone_dst_act = NULL; + + /* We never handle usercount here for own data. */ + const int flag_subdata = flag | LIB_ID_CREATE_NO_USER_REFCOUNT; - newArm = BKE_libblock_copy(bmain, &arm->id); - BLI_duplicatelist(&newArm->bonebase, &arm->bonebase); + BLI_duplicatelist(&arm_dst->bonebase, &arm_src->bonebase); /* Duplicate the childrens' lists */ - newBone = newArm->bonebase.first; - for (oldBone = arm->bonebase.first; oldBone; oldBone = oldBone->next) { - newBone->parent = NULL; - copy_bonechildren(newBone, oldBone, arm->act_bone, &newActBone); - newBone = newBone->next; + bone_dst = arm_dst->bonebase.first; + for (bone_src = arm_src->bonebase.first; bone_src; bone_src = bone_src->next) { + bone_dst->parent = NULL; + copy_bonechildren(bone_dst, bone_src, arm_src->act_bone, &bone_dst_act, flag_subdata); + bone_dst = bone_dst->next; } - newArm->act_bone = newActBone; - - newArm->edbo = NULL; - newArm->act_edbone = NULL; - newArm->sketch = NULL; + arm_dst->act_bone = bone_dst_act; - BKE_id_copy_ensure_local(bmain, &arm->id, &newArm->id); + arm_dst->edbo = NULL; + arm_dst->act_edbone = NULL; + arm_dst->sketch = NULL; +} - return newArm; +bArmature *BKE_armature_copy(Main *bmain, const bArmature *arm) +{ + bArmature *arm_copy; + BKE_id_copy_ex(bmain, &arm->id, (ID **)&arm_copy, 0, false); + return arm_copy; } static Bone *get_named_bone_bonechildren(ListBase *lb, const char *name) diff --git a/source/blender/blenkernel/intern/armature_update.c b/source/blender/blenkernel/intern/armature_update.c index df0bddede3b..a4714041edf 100644 --- a/source/blender/blenkernel/intern/armature_update.c +++ b/source/blender/blenkernel/intern/armature_update.c @@ -702,4 +702,8 @@ void BKE_pose_eval_proxy_copy(EvaluationContext *UNUSED(eval_ctx), Object *ob) printf("Proxy copy error, lib Object: %s proxy Object: %s\n", ob->id.name + 2, ob->proxy_from->id.name + 2); } + /* Rest of operations are NO-OP in depsgraph, so can clear + * flag now. + */ + ob->recalc &= ~OB_RECALC_ALL; } diff --git a/source/blender/blenkernel/intern/blender.c b/source/blender/blenkernel/intern/blender.c index ceb641073e0..2624019e63a 100644 --- a/source/blender/blenkernel/intern/blender.c +++ b/source/blender/blenkernel/intern/blender.c @@ -226,19 +226,6 @@ void BKE_blender_userdef_free_data(UserDef *userdef) } /** - * Handle changes in settings that need refreshing. - */ -void BKE_blender_userdef_refresh(void) -{ - /* prevent accidents */ - if (U.pixelsize == 0) U.pixelsize = 1; - - BLF_default_dpi(U.pixelsize * U.dpi); - U.widget_unit = (U.pixelsize * U.dpi * 20 + 36) / 72; - -} - -/** * Write U from userdef. * This function defines which settings a template will override for the user preferences. */ diff --git a/source/blender/blenkernel/intern/blendfile.c b/source/blender/blenkernel/intern/blendfile.c index a521d671ea4..980df05aca2 100644 --- a/source/blender/blenkernel/intern/blendfile.c +++ b/source/blender/blenkernel/intern/blendfile.c @@ -114,6 +114,7 @@ static void setup_app_data( const char *filepath, ReportList *reports) { Scene *curscene = NULL; + const bool is_startup = (bfd->filename[0] == '\0'); const bool recover = (G.fileflags & G_FILE_RECOVER) != 0; enum { LOAD_UI = 1, @@ -129,7 +130,7 @@ static void setup_app_data( else if (BLI_listbase_is_empty(&bfd->main->screen)) { mode = LOAD_UNDO; } - else if (G.fileflags & G_FILE_NO_UI) { + else if ((G.fileflags & G_FILE_NO_UI) && (is_startup == false)) { mode = LOAD_UI_OFF; } else { @@ -250,7 +251,9 @@ static void setup_app_data( CTX_data_scene_set(C, curscene); } else { - G.fileflags = bfd->fileflags; + /* Keep state from preferences. */ + const int fileflags_skip = G_FILE_FLAGS_RUNTIME; + G.fileflags = (G.fileflags & fileflags_skip) | (bfd->fileflags & ~fileflags_skip); CTX_wm_manager_set(C, G.main->wm.first); CTX_wm_screen_set(C, bfd->curscreen); CTX_data_scene_set(C, bfd->curscene); @@ -413,9 +416,9 @@ bool BKE_blendfile_read_from_memfile( if (bfd) { /* remove the unused screens and wm */ while (bfd->main->wm.first) - BKE_libblock_free_ex(bfd->main, bfd->main->wm.first, true, true); + BKE_libblock_free(bfd->main, bfd->main->wm.first); while (bfd->main->screen.first) - BKE_libblock_free_ex(bfd->main, bfd->main->screen.first, true, true); + BKE_libblock_free(bfd->main, bfd->main->screen.first); setup_app_data(C, bfd, "<memory1>", reports); } diff --git a/source/blender/blenkernel/intern/boids.c b/source/blender/blenkernel/intern/boids.c index b4bc83bf94c..7ca4e07076d 100644 --- a/source/blender/blenkernel/intern/boids.c +++ b/source/blender/blenkernel/intern/boids.c @@ -1581,7 +1581,7 @@ void boid_free_settings(BoidSettings *boids) MEM_freeN(boids); } } -BoidSettings *boid_copy_settings(BoidSettings *boids) +BoidSettings *boid_copy_settings(const BoidSettings *boids) { BoidSettings *nboids = NULL; diff --git a/source/blender/blenkernel/intern/brush.c b/source/blender/blenkernel/intern/brush.c index 57b707a31d3..03b0710c8fc 100644 --- a/source/blender/blenkernel/intern/brush.c +++ b/source/blender/blenkernel/intern/brush.c @@ -152,7 +152,7 @@ Brush *BKE_brush_add(Main *bmain, const char *name, short ob_mode) { Brush *brush; - brush = BKE_libblock_alloc(bmain, ID_BR, name); + brush = BKE_libblock_alloc(bmain, ID_BR, name, 0); BKE_brush_init(brush); @@ -172,34 +172,38 @@ struct Brush *BKE_brush_first_search(struct Main *bmain, short ob_mode) return NULL; } -Brush *BKE_brush_copy(Main *bmain, Brush *brush) +/** + * Only copy internal data of Brush ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_brush_copy_data(Main *UNUSED(bmain), Brush *brush_dst, const Brush *brush_src, const int flag) { - Brush *brushn; - - brushn = BKE_libblock_copy(bmain, &brush->id); - - if (brush->mtex.tex) - id_us_plus((ID *)brush->mtex.tex); - - if (brush->mask_mtex.tex) - id_us_plus((ID *)brush->mask_mtex.tex); - - if (brush->paint_curve) - id_us_plus((ID *)brush->paint_curve); - - if (brush->icon_imbuf) - brushn->icon_imbuf = IMB_dupImBuf(brush->icon_imbuf); + if (brush_src->icon_imbuf) { + brush_dst->icon_imbuf = IMB_dupImBuf(brush_src->icon_imbuf); + } - brushn->preview = NULL; + if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0) { + BKE_previewimg_id_copy(&brush_dst->id, &brush_src->id); + } + else { + brush_dst->preview = NULL; + } - brushn->curve = curvemapping_copy(brush->curve); + brush_dst->curve = curvemapping_copy(brush_src->curve); /* enable fake user by default */ - id_fake_user_set(&brush->id); - - BKE_id_copy_ensure_local(bmain, &brush->id, &brushn->id); + id_fake_user_set(&brush_dst->id); +} - return brushn; +Brush *BKE_brush_copy(Main *bmain, const Brush *brush) +{ + Brush *brush_copy; + BKE_id_copy_ex(bmain, &brush->id, (ID **)&brush_copy, 0, false); + return brush_copy; } /** Free (or release) any data used by this brush (does not free the brush itself). */ diff --git a/source/blender/blenkernel/intern/bvhutils.c b/source/blender/blenkernel/intern/bvhutils.c index c0e4ef37a93..775499304d4 100644 --- a/source/blender/blenkernel/intern/bvhutils.c +++ b/source/blender/blenkernel/intern/bvhutils.c @@ -917,10 +917,10 @@ BVHTree *bvhtree_from_mesh_faces( /** * Builds a bvh tree where nodes are the given tessellated faces (note: does not copy given mfaces!). - * \param vert_allocated if true, vert freeing will be done when freeing data. - * \param face_allocated if true, face freeing will be done when freeing data. + * \param vert_allocated: if true, vert freeing will be done when freeing data. + * \param face_allocated: if true, face freeing will be done when freeing data. * \param faces_mask: if not null, true elements give which faces to add to BVH tree. - * \param numFaces_active if >= 0, number of active faces to add to BVH tree (else will be computed from mask). + * \param faces_num_active: if >= 0, number of active faces to add to BVH tree (else will be computed from mask). */ BVHTree *bvhtree_from_mesh_faces_ex( BVHTreeFromMesh *data, const MVert *vert, const bool vert_allocated, @@ -1137,7 +1137,6 @@ BVHTree *bvhtree_from_mesh_looptri( const MLoopTri *looptri = NULL; bool vert_allocated = false; bool loop_allocated = false; - bool looptri_allocated = false; BLI_rw_mutex_lock(&cache_rwlock, THREAD_LOCK_READ); tree = bvhcache_find(dm->bvhCache, BVHTREE_FROM_LOOPTRI); @@ -1150,12 +1149,7 @@ BVHTree *bvhtree_from_mesh_looptri( mpoly = DM_get_poly_array(dm, &poly_allocated); mloop = DM_get_loop_array(dm, &loop_allocated); - looptri = DM_get_looptri_array( - dm, - mvert, - mpoly, dm->getNumPolys(dm), - mloop, dm->getNumLoops(dm), - &looptri_allocated); + looptri = dm->getLoopTriArray(dm); if (poly_allocated) { MEM_freeN(mpoly); @@ -1193,7 +1187,7 @@ BVHTree *bvhtree_from_mesh_looptri( data, tree, true, epsilon, mvert, vert_allocated, mloop, loop_allocated, - looptri, looptri_allocated); + looptri, false); } else { if (vert_allocated) { @@ -1202,9 +1196,6 @@ BVHTree *bvhtree_from_mesh_looptri( if (loop_allocated) { MEM_freeN(mloop); } - if (looptri_allocated) { - MEM_freeN((void *)looptri); - } memset(data, 0, sizeof(*data)); } diff --git a/source/blender/blenkernel/intern/cachefile.c b/source/blender/blenkernel/intern/cachefile.c index 67c66d4e40b..1916531b066 100644 --- a/source/blender/blenkernel/intern/cachefile.c +++ b/source/blender/blenkernel/intern/cachefile.c @@ -66,7 +66,7 @@ void BKE_cachefiles_exit(void) void *BKE_cachefile_add(Main *bmain, const char *name) { - CacheFile *cache_file = BKE_libblock_alloc(bmain, ID_CF, name); + CacheFile *cache_file = BKE_libblock_alloc(bmain, ID_CF, name, 0); BKE_cachefile_init(cache_file); @@ -100,16 +100,26 @@ void BKE_cachefile_free(CacheFile *cache_file) BLI_freelistN(&cache_file->object_paths); } -CacheFile *BKE_cachefile_copy(Main *bmain, CacheFile *cache_file) +/** + * Only copy internal data of CacheFile ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_cachefile_copy_data( + Main *UNUSED(bmain), CacheFile *cache_file_dst, const CacheFile *UNUSED(cache_file_src), const int UNUSED(flag)) { - CacheFile *new_cache_file = BKE_libblock_copy(bmain, &cache_file->id); - new_cache_file->handle = NULL; - - BLI_listbase_clear(&cache_file->object_paths); - - BKE_id_copy_ensure_local(bmain, &cache_file->id, &new_cache_file->id); + cache_file_dst->handle = NULL; + BLI_listbase_clear(&cache_file_dst->object_paths); +} - return new_cache_file; +CacheFile *BKE_cachefile_copy(Main *bmain, const CacheFile *cache_file) +{ + CacheFile *cache_file_copy; + BKE_id_copy_ex(bmain, &cache_file->id, (ID **)&cache_file_copy, 0, false); + return cache_file_copy; } void BKE_cachefile_make_local(Main *bmain, CacheFile *cache_file, const bool lib_local) @@ -166,10 +176,12 @@ void BKE_cachefile_update_frame(Main *bmain, Scene *scene, const float ctime, co const float time = BKE_cachefile_time_offset(cache_file, ctime, fps); if (BKE_cachefile_filepath_get(bmain, cache_file, time, filename)) { + BKE_cachefile_clean(scene, cache_file); #ifdef WITH_ALEMBIC ABC_free_handle(cache_file->handle); cache_file->handle = ABC_create_handle(filename, NULL); #endif + break; } } } diff --git a/source/blender/blenkernel/intern/camera.c b/source/blender/blenkernel/intern/camera.c index 9cb553aa27b..719125b3317 100644 --- a/source/blender/blenkernel/intern/camera.c +++ b/source/blender/blenkernel/intern/camera.c @@ -86,22 +86,31 @@ void *BKE_camera_add(Main *bmain, const char *name) { Camera *cam; - cam = BKE_libblock_alloc(bmain, ID_CA, name); + cam = BKE_libblock_alloc(bmain, ID_CA, name, 0); BKE_camera_init(cam); return cam; } -Camera *BKE_camera_copy(Main *bmain, Camera *cam) +/** + * Only copy internal data of Camera ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_camera_copy_data(Main *UNUSED(bmain), Camera *UNUSED(cam_dst), const Camera *UNUSED(cam_src), const int UNUSED(flag)) { - Camera *camn; - - camn = BKE_libblock_copy(bmain, &cam->id); - - BKE_id_copy_ensure_local(bmain, &cam->id, &camn->id); + /* Nothing to do! */ +} - return camn; +Camera *BKE_camera_copy(Main *bmain, const Camera *cam) +{ + Camera *cam_copy; + BKE_id_copy_ex(bmain, &cam->id, (ID **)&cam_copy, 0, false); + return cam_copy; } void BKE_camera_make_local(Main *bmain, Camera *cam, const bool lib_local) diff --git a/source/blender/blenkernel/intern/cdderivedmesh.c b/source/blender/blenkernel/intern/cdderivedmesh.c index ee3a763e4c8..42f818b8c92 100644 --- a/source/blender/blenkernel/intern/cdderivedmesh.c +++ b/source/blender/blenkernel/intern/cdderivedmesh.c @@ -1935,19 +1935,6 @@ void CDDM_recalc_looptri(DerivedMesh *dm) cddm->dm.looptris.array); } -static const MLoopTri *cdDM_getLoopTriArray(DerivedMesh *dm) -{ - if (dm->looptris.array) { - BLI_assert(poly_to_tri_count(dm->numPolyData, dm->numLoopData) == dm->looptris.num); - } - else { - dm->recalcLoopTri(dm); - - /* ccdm is an exception here, that recalcLoopTri will fill in the array too */ - } - return dm->looptris.array; -} - static void cdDM_free_internal(CDDerivedMesh *cddm) { if (cddm->pmap) MEM_freeN(cddm->pmap); @@ -1998,8 +1985,6 @@ static CDDerivedMesh *cdDM_create(const char *desc) dm->getEdgeDataArray = DM_get_edge_data_layer; dm->getTessFaceDataArray = DM_get_tessface_data_layer; - dm->getLoopTriArray = cdDM_getLoopTriArray; - dm->calcNormals = CDDM_calc_normals; dm->calcLoopNormals = CDDM_calc_loop_normals; dm->calcLoopNormalsSpaceArray = CDDM_calc_loop_normals_spacearr; @@ -3192,7 +3177,7 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap, const int MPoly *target_poly = cddm->mpoly + *(cddm->pmap[v_target].indices + i_poly); if (cddm_poly_compare(cddm->mloop, mp, target_poly, vtargetmap, +1) || - cddm_poly_compare(cddm->mloop, mp, target_poly, vtargetmap, -1)) + cddm_poly_compare(cddm->mloop, mp, target_poly, vtargetmap, -1)) { found = true; break; diff --git a/source/blender/blenkernel/intern/cloth.c b/source/blender/blenkernel/intern/cloth.c index ee0fde1ea61..dd93606a67c 100644 --- a/source/blender/blenkernel/intern/cloth.c +++ b/source/blender/blenkernel/intern/cloth.c @@ -807,7 +807,6 @@ static int cloth_from_object(Object *ob, ClothModifierData *clmd, DerivedMesh *d if ( !dm ) return 0; - DM_ensure_looptri(dm); cloth_from_mesh ( clmd, dm ); // create springs diff --git a/source/blender/blenkernel/intern/colortools.c b/source/blender/blenkernel/intern/colortools.c index b3a0895d063..ee0f904c3a6 100644 --- a/source/blender/blenkernel/intern/colortools.c +++ b/source/blender/blenkernel/intern/colortools.c @@ -130,7 +130,7 @@ void curvemapping_free(CurveMapping *cumap) } } -void curvemapping_copy_data(CurveMapping *target, CurveMapping *cumap) +void curvemapping_copy_data(CurveMapping *target, const CurveMapping *cumap) { int a; @@ -146,7 +146,7 @@ void curvemapping_copy_data(CurveMapping *target, CurveMapping *cumap) } } -CurveMapping *curvemapping_copy(CurveMapping *cumap) +CurveMapping *curvemapping_copy(const CurveMapping *cumap) { if (cumap) { CurveMapping *cumapn = MEM_dupallocN(cumap); diff --git a/source/blender/blenkernel/intern/constraint.c b/source/blender/blenkernel/intern/constraint.c index 9bc1ce16284..7ad2ed91e87 100644 --- a/source/blender/blenkernel/intern/constraint.c +++ b/source/blender/blenkernel/intern/constraint.c @@ -790,7 +790,7 @@ static void default_get_tarmat(bConstraint *con, bConstraintOb *UNUSED(cob), bCo ct = ctn; \ } \ } (void)0 - + /* --------- ChildOf Constraint ------------ */ static void childof_new_data(void *cdata) @@ -1019,7 +1019,7 @@ static void vectomat(const float vec[3], const float target_up[3], short axis, s } /* project the up vector onto the plane specified by n */ - project_v3_v3v3(proj, u, n); /* first u onto n... */ + project_v3_v3v3_normalized(proj, u, n); /* first u onto n... */ sub_v3_v3v3(proj, u, proj); /* then onto the plane */ /* proj specifies the transformation of the up axis */ @@ -1930,7 +1930,7 @@ static void samevolume_evaluate(bConstraint *con, bConstraintOb *cob, ListBase * /* calculate normalizing scale factor for non-essential values */ if (obsize[data->flag] != 0) - fac = sqrtf(volume / obsize[data->flag]) / obsize[data->flag]; + fac = sqrtf(volume / obsize[data->flag]); /* apply scaling factor to the channels not being kept */ switch (data->flag) { @@ -4737,29 +4737,30 @@ static void con_fix_copied_refs_cb(bConstraint *UNUSED(con), ID **idpoin, bool i } /* duplicate all of the constraints in a constraint stack */ -void BKE_constraints_copy(ListBase *dst, const ListBase *src, bool do_extern) +void BKE_constraints_copy_ex(ListBase *dst, const ListBase *src, const int flag, bool do_extern) { bConstraint *con, *srccon; - + BLI_listbase_clear(dst); BLI_duplicatelist(dst, src); - + for (con = dst->first, srccon = src->first; con && srccon; srccon = srccon->next, con = con->next) { const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con); - + /* make a new copy of the constraint's data */ con->data = MEM_dupallocN(con->data); - + /* only do specific constraints if required */ if (cti) { /* perform custom copying operations if needed */ if (cti->copy_data) cti->copy_data(con, srccon); - - /* fix usercounts for all referenced data in referenced data */ - if (cti->id_looper) + + /* Fix usercounts for all referenced data that need it. */ + if (cti->id_looper && (flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) { cti->id_looper(con, con_fix_copied_refs_cb, NULL); - + } + /* for proxies we don't want to make extern */ if (do_extern) { /* go over used ID-links for this constraint to ensure that they are valid for proxies */ @@ -4770,6 +4771,11 @@ void BKE_constraints_copy(ListBase *dst, const ListBase *src, bool do_extern) } } +void BKE_constraints_copy(ListBase *dst, const ListBase *src, bool do_extern) +{ + BKE_constraints_copy_ex(dst, src, 0, do_extern); +} + /* ......... */ bConstraint *BKE_constraints_find_name(ListBase *list, const char *name) diff --git a/source/blender/blenkernel/intern/curve.c b/source/blender/blenkernel/intern/curve.c index 439abb1d593..795feb58bf6 100644 --- a/source/blender/blenkernel/intern/curve.c +++ b/source/blender/blenkernel/intern/curve.c @@ -179,7 +179,7 @@ Curve *BKE_curve_add(Main *bmain, const char *name, int type) { Curve *cu; - cu = BKE_libblock_alloc(bmain, ID_CU, name); + cu = BKE_libblock_alloc(bmain, ID_CU, name, 0); cu->type = type; BKE_curve_init(cu); @@ -187,42 +187,39 @@ Curve *BKE_curve_add(Main *bmain, const char *name, int type) return cu; } -Curve *BKE_curve_copy(Main *bmain, Curve *cu) +/** + * Only copy internal data of Curve ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_curve_copy_data(Main *bmain, Curve *cu_dst, const Curve *cu_src, const int flag) { - Curve *cun; - int a; - - cun = BKE_libblock_copy(bmain, &cu->id); + BLI_listbase_clear(&cu_dst->nurb); + BKE_nurbList_duplicate(&(cu_dst->nurb), &(cu_src->nurb)); - BLI_listbase_clear(&cun->nurb); - BKE_nurbList_duplicate(&(cun->nurb), &(cu->nurb)); + cu_dst->mat = MEM_dupallocN(cu_src->mat); - cun->mat = MEM_dupallocN(cu->mat); - for (a = 0; a < cun->totcol; a++) { - id_us_plus((ID *)cun->mat[a]); - } - - cun->str = MEM_dupallocN(cu->str); - cun->strinfo = MEM_dupallocN(cu->strinfo); - cun->tb = MEM_dupallocN(cu->tb); - cun->bb = MEM_dupallocN(cu->bb); + cu_dst->str = MEM_dupallocN(cu_src->str); + cu_dst->strinfo = MEM_dupallocN(cu_src->strinfo); + cu_dst->tb = MEM_dupallocN(cu_src->tb); + cu_dst->bb = MEM_dupallocN(cu_src->bb); - if (cu->key) { - cun->key = BKE_key_copy(bmain, cu->key); - cun->key->from = (ID *)cun; + if (cu_src->key) { + BKE_id_copy_ex(bmain, &cu_src->key->id, (ID **)&cu_dst->key, flag, false); } - cun->editnurb = NULL; - cun->editfont = NULL; - - id_us_plus((ID *)cun->vfont); - id_us_plus((ID *)cun->vfontb); - id_us_plus((ID *)cun->vfonti); - id_us_plus((ID *)cun->vfontbi); - - BKE_id_copy_ensure_local(bmain, &cu->id, &cun->id); + cu_dst->editnurb = NULL; + cu_dst->editfont = NULL; +} - return cun; +Curve *BKE_curve_copy(Main *bmain, const Curve *cu) +{ + Curve *cu_copy; + BKE_id_copy_ex(bmain, &cu->id, (ID **)&cu_copy, 0, false); + return cu_copy; } void BKE_curve_make_local(Main *bmain, Curve *cu, const bool lib_local) @@ -468,7 +465,7 @@ void BKE_nurbList_free(ListBase *lb) BLI_listbase_clear(lb); } -Nurb *BKE_nurb_duplicate(Nurb *nu) +Nurb *BKE_nurb_duplicate(const Nurb *nu) { Nurb *newnu; int len; @@ -532,7 +529,7 @@ Nurb *BKE_nurb_copy(Nurb *src, int pntsu, int pntsv) return newnu; } -void BKE_nurbList_duplicate(ListBase *lb1, ListBase *lb2) +void BKE_nurbList_duplicate(ListBase *lb1, const ListBase *lb2) { Nurb *nu, *nun; @@ -744,6 +741,7 @@ BezTriple *BKE_nurb_bezt_get_prev(Nurb *nu, BezTriple *bezt) BezTriple *bezt_prev; BLI_assert(ARRAY_HAS_ITEM(bezt, nu->bezt, nu->pntsu)); + BLI_assert(nu->pntsv == 1); if (bezt == nu->bezt) { if (nu->flagu & CU_NURB_CYCLIC) { @@ -765,6 +763,7 @@ BPoint *BKE_nurb_bpoint_get_prev(Nurb *nu, BPoint *bp) BPoint *bp_prev; BLI_assert(ARRAY_HAS_ITEM(bp, nu->bp, nu->pntsu)); + BLI_assert(nu->pntsv == 1); if (bp == nu->bp) { if (nu->flagu & CU_NURB_CYCLIC) { @@ -781,7 +780,7 @@ BPoint *BKE_nurb_bpoint_get_prev(Nurb *nu, BPoint *bp) return bp_prev; } -void BKE_nurb_bezt_calc_normal(struct Nurb *UNUSED(nu), struct BezTriple *bezt, float r_normal[3]) +void BKE_nurb_bezt_calc_normal(struct Nurb *UNUSED(nu), BezTriple *bezt, float r_normal[3]) { /* calculate the axis matrix from the spline */ float dir_prev[3], dir_next[3]; @@ -796,7 +795,7 @@ void BKE_nurb_bezt_calc_normal(struct Nurb *UNUSED(nu), struct BezTriple *bezt, normalize_v3(r_normal); } -void BKE_nurb_bezt_calc_plane(struct Nurb *nu, struct BezTriple *bezt, float r_plane[3]) +void BKE_nurb_bezt_calc_plane(struct Nurb *nu, BezTriple *bezt, float r_plane[3]) { float dir_prev[3], dir_next[3]; @@ -833,7 +832,7 @@ void BKE_nurb_bezt_calc_plane(struct Nurb *nu, struct BezTriple *bezt, float r_p normalize_v3(r_plane); } -void BKE_nurb_bpoint_calc_normal(struct Nurb *nu, struct BPoint *bp, float r_normal[3]) +void BKE_nurb_bpoint_calc_normal(struct Nurb *nu, BPoint *bp, float r_normal[3]) { BPoint *bp_prev = BKE_nurb_bpoint_get_prev(nu, bp); BPoint *bp_next = BKE_nurb_bpoint_get_next(nu, bp); @@ -856,6 +855,34 @@ void BKE_nurb_bpoint_calc_normal(struct Nurb *nu, struct BPoint *bp, float r_nor normalize_v3(r_normal); } +void BKE_nurb_bpoint_calc_plane(struct Nurb *nu, BPoint *bp, float r_plane[3]) +{ + BPoint *bp_prev = BKE_nurb_bpoint_get_prev(nu, bp); + BPoint *bp_next = BKE_nurb_bpoint_get_next(nu, bp); + + float dir_prev[3] = {0.0f}, dir_next[3] = {0.0f}; + + if (bp_prev) { + sub_v3_v3v3(dir_prev, bp_prev->vec, bp->vec); + normalize_v3(dir_prev); + } + if (bp_next) { + sub_v3_v3v3(dir_next, bp->vec, bp_next->vec); + normalize_v3(dir_next); + } + cross_v3_v3v3(r_plane, dir_prev, dir_next); + + /* matches with bones more closely */ + { + float dir_mid[3], tvec[3]; + add_v3_v3v3(dir_mid, dir_prev, dir_next); + cross_v3_v3v3(tvec, r_plane, dir_mid); + copy_v3_v3(r_plane, tvec); + } + + normalize_v3(r_plane); +} + /* ~~~~~~~~~~~~~~~~~~~~Non Uniform Rational B Spline calculations ~~~~~~~~~~~ */ @@ -4415,7 +4442,9 @@ bool BKE_curve_center_bounds(Curve *cu, float cent[3]) } -void BKE_curve_transform_ex(Curve *cu, float mat[4][4], const bool do_keys, const float unit_scale) +void BKE_curve_transform_ex( + Curve *cu, float mat[4][4], + const bool do_keys, const bool do_props, const float unit_scale) { Nurb *nu; BPoint *bp; @@ -4429,7 +4458,9 @@ void BKE_curve_transform_ex(Curve *cu, float mat[4][4], const bool do_keys, cons mul_m4_v3(mat, bezt->vec[0]); mul_m4_v3(mat, bezt->vec[1]); mul_m4_v3(mat, bezt->vec[2]); - bezt->radius *= unit_scale; + if (do_props) { + bezt->radius *= unit_scale; + } } BKE_nurb_handles_calc(nu); } @@ -4437,7 +4468,9 @@ void BKE_curve_transform_ex(Curve *cu, float mat[4][4], const bool do_keys, cons i = nu->pntsu * nu->pntsv; for (bp = nu->bp; i--; bp++) { mul_m4_v3(mat, bp->vec); - bp->radius *= unit_scale; + if (do_props) { + bp->radius *= unit_scale; + } } } } @@ -4453,10 +4486,12 @@ void BKE_curve_transform_ex(Curve *cu, float mat[4][4], const bool do_keys, cons } } -void BKE_curve_transform(Curve *cu, float mat[4][4], const bool do_keys) +void BKE_curve_transform( + Curve *cu, float mat[4][4], + const bool do_keys, const bool do_props) { float unit_scale = mat4_to_scale(mat); - BKE_curve_transform_ex(cu, mat, do_keys, unit_scale); + BKE_curve_transform_ex(cu, mat, do_keys, do_props, unit_scale); } void BKE_curve_translate(Curve *cu, float offset[3], const bool do_keys) @@ -4645,14 +4680,3 @@ void BKE_curve_eval_geometry(EvaluationContext *UNUSED(eval_ctx), BKE_curve_texspace_calc(curve); } } - -void BKE_curve_eval_path(EvaluationContext *UNUSED(eval_ctx), - Curve *curve) -{ - /* TODO(sergey): This will probably need to be a part of - * the modifier stack still. - */ - if (G.debug & G_DEBUG_DEPSGRAPH) { - printf("%s on %s\n", __func__, curve->id.name); - } -} diff --git a/source/blender/blenkernel/intern/deform.c b/source/blender/blenkernel/intern/deform.c index 13b1aab5e1c..eec8d2478da 100644 --- a/source/blender/blenkernel/intern/deform.c +++ b/source/blender/blenkernel/intern/deform.c @@ -76,7 +76,7 @@ bDeformGroup *BKE_defgroup_new(Object *ob, const char *name) return defgroup; } -void defgroup_copy_list(ListBase *outbase, ListBase *inbase) +void defgroup_copy_list(ListBase *outbase, const ListBase *inbase) { bDeformGroup *defgroup, *defgroupn; @@ -88,7 +88,7 @@ void defgroup_copy_list(ListBase *outbase, ListBase *inbase) } } -bDeformGroup *defgroup_duplicate(bDeformGroup *ingroup) +bDeformGroup *defgroup_duplicate(const bDeformGroup *ingroup) { bDeformGroup *outgroup; @@ -621,8 +621,17 @@ 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) { - if (defgroup == -1 || dvert == NULL) + /* Invalid defgroup index means the vgroup selected is invalid, does not exist, in that case it is OK to return 1.0 + * (i.e. maximum weight, as if no vgroup was selected). + * But in case of valid defgroup and NULL dvert data pointer, it means that vgroup **is** valid, + * and just totally empty, so we shall return '0.0' value then! + */ + if (defgroup == -1) { return 1.0f; + } + else if (dvert == NULL) { + return 0.0f; + } return defvert_find_weight(dvert + index, defgroup); } diff --git a/source/blender/blenkernel/intern/dynamicpaint.c b/source/blender/blenkernel/intern/dynamicpaint.c index 1db69d23607..ae896176b6d 100644 --- a/source/blender/blenkernel/intern/dynamicpaint.c +++ b/source/blender/blenkernel/intern/dynamicpaint.c @@ -2060,9 +2060,6 @@ DerivedMesh *dynamicPaint_Modifier_do(DynamicPaintModifierData *pmd, Scene *scen if (pmd->canvas) { DerivedMesh *ret; - /* For now generate looptris in every case */ - DM_ensure_looptri(dm); - /* Update canvas data for a new frame */ dynamicPaint_frameUpdate(pmd, scene, ob, dm); @@ -2072,9 +2069,6 @@ DerivedMesh *dynamicPaint_Modifier_do(DynamicPaintModifierData *pmd, Scene *scen return ret; } else { - /* For now generate looptris in every case */ - DM_ensure_looptri(dm); - /* Update canvas data for a new frame */ dynamicPaint_frameUpdate(pmd, scene, ob, dm); diff --git a/source/blender/blenkernel/intern/editderivedmesh.c b/source/blender/blenkernel/intern/editderivedmesh.c index 5591ee2a0d4..f29af28a782 100644 --- a/source/blender/blenkernel/intern/editderivedmesh.c +++ b/source/blender/blenkernel/intern/editderivedmesh.c @@ -149,6 +149,8 @@ static void emDM_ensurePolyCenters(EditDerivedBMesh *bmdm) const float (*vertexCos)[3]; vertexCos = bmdm->vertexCos; + BM_mesh_elem_index_ensure(bm, BM_VERT); + BM_ITER_MESH_INDEX (efa, &fiter, bm, BM_FACES_OF_MESH, i) { BM_face_calc_center_mean_vcos(bm, efa, polyCos[i], vertexCos); } @@ -487,8 +489,6 @@ static void emDM_calc_loop_tangents( EditDerivedBMesh *bmdm = (EditDerivedBMesh *)dm; BMEditMesh *em = bmdm->em; BMesh *bm = bmdm->em->bm; - if (CustomData_number_of_layers(&bm->ldata, CD_MLOOPUV) == 0) - return; int act_uv_n = -1; int ren_uv_n = -1; @@ -496,7 +496,7 @@ static void emDM_calc_loop_tangents( bool calc_ren = false; char act_uv_name[MAX_NAME]; char ren_uv_name[MAX_NAME]; - char tangent_mask = 0; + short tangent_mask = 0; DM_calc_loop_tangents_step_0( &bm->ldata, calc_active_tangent, tangent_names, tangent_names_count, @@ -506,6 +506,8 @@ static void emDM_calc_loop_tangents( for (int i = 0; i < tangent_names_count; i++) if (tangent_names[i][0]) DM_add_named_tangent_layer_for_uv(&bm->ldata, &dm->loopData, dm->numLoopData, tangent_names[i]); + if ((tangent_mask & DM_TANGENT_MASK_ORCO) && CustomData_get_named_layer_index(&dm->loopData, CD_TANGENT, "") == -1) + CustomData_add_layer_named(&dm->loopData, CD_TANGENT, CD_CALLOC, NULL, dm->numLoopData, ""); if (calc_act && act_uv_name[0]) DM_add_named_tangent_layer_for_uv(&bm->ldata, &dm->loopData, dm->numLoopData, act_uv_name); if (calc_ren && ren_uv_name[0]) @@ -572,7 +574,17 @@ static void emDM_calc_loop_tangents( continue; /* needed for orco lookups */ htype_index |= BM_VERT; + dm->tangent_mask |= DM_TANGENT_MASK_ORCO; + } + else { + /* Fill the resulting tangent_mask */ + int uv_ind = CustomData_get_named_layer_index(&bm->ldata, CD_MLOOPUV, dm->loopData.layers[index].name); + int uv_start = CustomData_get_layer_index(&bm->ldata, CD_MLOOPUV); + BLI_assert(uv_ind != -1 && uv_start != -1); + BLI_assert(uv_ind - uv_start < MAX_MTFACE); + dm->tangent_mask |= 1 << (uv_ind - uv_start); } + if (mesh2tangent->precomputedFaceNormals) { /* needed for face normal lookups */ htype_index |= BM_FACE; @@ -582,12 +594,6 @@ static void emDM_calc_loop_tangents( mesh2tangent->looptris = (const BMLoop *(*)[3])em->looptris; mesh2tangent->tangent = dm->loopData.layers[index].data; - /* Fill the resulting tangent_mask */ - int uv_ind = CustomData_get_named_layer_index(&bm->ldata, CD_MLOOPUV, dm->loopData.layers[index].name); - int uv_start = CustomData_get_layer_index(&bm->ldata, CD_MLOOPUV); - BLI_assert(uv_ind != -1 && uv_start != -1); - BLI_assert(uv_ind - uv_start < MAX_MTFACE); - dm->tangent_mask |= 1 << (uv_ind - uv_start); BLI_task_pool_push(task_pool, emDM_calc_loop_tangents_thread, mesh2tangent, false, TASK_PRIORITY_LOW); } @@ -602,15 +608,20 @@ static void emDM_calc_loop_tangents( #undef USE_LOOPTRI_DETECT_QUADS #endif } + /* Update active layer index */ - int uv_index = CustomData_get_layer_index_n(&bm->ldata, CD_MLOOPUV, act_uv_n); - int tan_index = CustomData_get_named_layer_index(&dm->loopData, CD_TANGENT, bm->ldata.layers[uv_index].name); - CustomData_set_layer_active_index(&dm->loopData, CD_TANGENT, tan_index); + int act_uv_index = CustomData_get_layer_index_n(&bm->ldata, CD_MLOOPUV, act_uv_n); + if (act_uv_index >= 0) { + int tan_index = CustomData_get_named_layer_index(&dm->loopData, CD_TANGENT, bm->ldata.layers[act_uv_index].name); + CustomData_set_layer_active_index(&dm->loopData, CD_TANGENT, tan_index); + } /* else tangent has been built from orco */ /* Update render layer index */ - uv_index = CustomData_get_layer_index_n(&bm->ldata, CD_MLOOPUV, ren_uv_n); - tan_index = CustomData_get_named_layer_index(&dm->loopData, CD_TANGENT, bm->ldata.layers[uv_index].name); - CustomData_set_layer_render_index(&dm->loopData, CD_TANGENT, tan_index); + int ren_uv_index = CustomData_get_layer_index_n(&bm->ldata, CD_MLOOPUV, ren_uv_n); + if (ren_uv_index >= 0) { + int tan_index = CustomData_get_named_layer_index(&dm->loopData, CD_TANGENT, bm->ldata.layers[ren_uv_index].name); + CustomData_set_layer_render_index(&dm->loopData, CD_TANGENT, tan_index); + } /* else tangent has been built from orco */ } /** \} */ @@ -650,18 +661,6 @@ static void emDM_recalcLoopTri(DerivedMesh *dm) } } -static const MLoopTri *emDM_getLoopTriArray(DerivedMesh *dm) -{ - if (dm->looptris.array) { - BLI_assert(poly_to_tri_count(dm->numPolyData, dm->numLoopData) == dm->looptris.num); - } - else { - dm->recalcLoopTri(dm); - } - - return dm->looptris.array; -} - static void emDM_foreachMappedVert( DerivedMesh *dm, void (*func)(void *userData, int index, const float co[3], const float no_f[3], const short no_s[3]), @@ -2248,8 +2247,6 @@ DerivedMesh *getEditDerivedBMesh( bmdm->dm.getNumLoops = emDM_getNumLoops; bmdm->dm.getNumPolys = emDM_getNumPolys; - bmdm->dm.getLoopTriArray = emDM_getLoopTriArray; - bmdm->dm.getVert = emDM_getVert; bmdm->dm.getVertCo = emDM_getVertCo; bmdm->dm.getVertNo = emDM_getVertNo; @@ -2630,7 +2627,7 @@ static void statvis_calc_distort( vertexCos[BM_elem_index_get(l_iter->next->v)]); } else { - BM_loop_calc_face_normal(l_iter, no_corner); + BM_loop_calc_face_normal_safe(l_iter, no_corner); } /* simple way to detect (what is most likely) concave */ if (dot_v3v3(f_no, no_corner) < 0.0f) { diff --git a/source/blender/blenkernel/intern/effect.c b/source/blender/blenkernel/intern/effect.c index 4eee24b378f..38f5c00941c 100644 --- a/source/blender/blenkernel/intern/effect.c +++ b/source/blender/blenkernel/intern/effect.c @@ -986,19 +986,19 @@ static void do_physical_effector(EffectorCache *eff, EffectorData *efd, Effected */ void pdDoEffectors(ListBase *effectors, ListBase *colliders, EffectorWeights *weights, EffectedPoint *point, float *force, float *impulse) { -/* - * Modifies the force on a particle according to its - * relation with the effector object - * Different kind of effectors include: - * Forcefields: Gravity-like attractor - * (force power is related to the inverse of distance to the power of a falloff value) - * Vortex fields: swirling effectors - * (particles rotate around Z-axis of the object. otherwise, same relation as) - * (Forcefields, but this is not done through a force/acceleration) - * Guide: particles on a path - * (particles are guided along a curve bezier or old nurbs) - * (is independent of other effectors) - */ + /* + * Modifies the force on a particle according to its + * relation with the effector object + * Different kind of effectors include: + * Forcefields: Gravity-like attractor + * (force power is related to the inverse of distance to the power of a falloff value) + * Vortex fields: swirling effectors + * (particles rotate around Z-axis of the object. otherwise, same relation as) + * (Forcefields, but this is not done through a force/acceleration) + * Guide: particles on a path + * (particles are guided along a curve bezier or old nurbs) + * (is independent of other effectors) + */ EffectorCache *eff; EffectorData efd; int p=0, tot = 1, step = 1; diff --git a/source/blender/blenkernel/intern/fcurve.c b/source/blender/blenkernel/intern/fcurve.c index 7dbc43e0a32..db6c533ab57 100644 --- a/source/blender/blenkernel/intern/fcurve.c +++ b/source/blender/blenkernel/intern/fcurve.c @@ -126,7 +126,7 @@ void free_fcurves(ListBase *list) /* ---------------------- Copy --------------------------- */ /* duplicate an F-Curve */ -FCurve *copy_fcurve(FCurve *fcu) +FCurve *copy_fcurve(const FCurve *fcu) { FCurve *fcu_d; @@ -1805,7 +1805,7 @@ void fcurve_free_driver(FCurve *fcu) } /* This makes a copy of the given driver */ -ChannelDriver *fcurve_copy_driver(ChannelDriver *driver) +ChannelDriver *fcurve_copy_driver(const ChannelDriver *driver) { ChannelDriver *ndriver; @@ -1945,7 +1945,7 @@ float evaluate_driver(PathResolvedRNA *anim_rna, ChannelDriver *driver, const fl BLI_mutex_unlock(&python_driver_lock); } #else /* WITH_PYTHON*/ - (void)evaltime; + UNUSED_VARS(anim_rna, evaltime); #endif /* WITH_PYTHON*/ break; } diff --git a/source/blender/blenkernel/intern/fluidsim.c b/source/blender/blenkernel/intern/fluidsim.c index 8247336d915..8e98a9f672d 100644 --- a/source/blender/blenkernel/intern/fluidsim.c +++ b/source/blender/blenkernel/intern/fluidsim.c @@ -80,8 +80,6 @@ void initElbeemMesh(struct Scene *scene, struct Object *ob, dm = mesh_create_derived_index_render(scene, ob, CD_MASK_BAREMESH, modifierIndex); - DM_ensure_looptri(dm); - mvert = dm->getVertArray(dm); mloop = dm->getLoopArray(dm); looptri = dm->getLoopTriArray(dm); diff --git a/source/blender/blenkernel/intern/fmodifier.c b/source/blender/blenkernel/intern/fmodifier.c index 2c301c04100..f1732ee7a9a 100644 --- a/source/blender/blenkernel/intern/fmodifier.c +++ b/source/blender/blenkernel/intern/fmodifier.c @@ -116,7 +116,7 @@ static void fcm_generator_free(FModifier *fcm) MEM_freeN(data->coefficients); } -static void fcm_generator_copy(FModifier *fcm, FModifier *src) +static void fcm_generator_copy(FModifier *fcm, const FModifier *src) { FMod_Generator *gen = (FMod_Generator *)fcm->data; FMod_Generator *ogen = (FMod_Generator *)src->data; @@ -386,7 +386,7 @@ static void fcm_envelope_free(FModifier *fcm) MEM_freeN(env->data); } -static void fcm_envelope_copy(FModifier *fcm, FModifier *src) +static void fcm_envelope_copy(FModifier *fcm, const FModifier *src) { FMod_Envelope *env = (FMod_Envelope *)fcm->data; FMod_Envelope *oenv = (FMod_Envelope *)src->data; @@ -877,7 +877,7 @@ static void fcm_python_new_data(void *mdata) data->prop->type = IDP_GROUP; } -static void fcm_python_copy(FModifier *fcm, FModifier *src) +static void fcm_python_copy(FModifier *fcm, const FModifier *src) { FMod_Python *pymod = (FMod_Python *)fcm->data; FMod_Python *opymod = (FMod_Python *)src->data; @@ -1040,7 +1040,7 @@ static void fmods_init_typeinfo(void) /* This function should be used for getting the appropriate type-info when only * a F-Curve modifier type is known */ -const FModifierTypeInfo *get_fmodifier_typeinfo(int type) +const FModifierTypeInfo *get_fmodifier_typeinfo(const int type) { /* initialize the type-info list? */ if (FMI_INIT) { @@ -1065,7 +1065,7 @@ const FModifierTypeInfo *get_fmodifier_typeinfo(int type) /* This function should always be used to get the appropriate type-info, as it * has checks which prevent segfaults in some weird cases. */ -const FModifierTypeInfo *fmodifier_get_typeinfo(FModifier *fcm) +const FModifierTypeInfo *fmodifier_get_typeinfo(const FModifier *fcm) { /* only return typeinfo for valid modifiers */ if (fcm) @@ -1117,7 +1117,7 @@ FModifier *add_fmodifier(ListBase *modifiers, int type) } /* Make a copy of the specified F-Modifier */ -FModifier *copy_fmodifier(FModifier *src) +FModifier *copy_fmodifier(const FModifier *src) { const FModifierTypeInfo *fmi = fmodifier_get_typeinfo(src); FModifier *dst; @@ -1142,7 +1142,7 @@ FModifier *copy_fmodifier(FModifier *src) } /* Duplicate all of the F-Modifiers in the Modifier stacks */ -void copy_fmodifiers(ListBase *dst, ListBase *src) +void copy_fmodifiers(ListBase *dst, const ListBase *src) { FModifier *fcm, *srcfcm; diff --git a/source/blender/blenkernel/intern/font.c b/source/blender/blenkernel/intern/font.c index 401fed74c52..d6b28cfaf70 100644 --- a/source/blender/blenkernel/intern/font.c +++ b/source/blender/blenkernel/intern/font.c @@ -106,6 +106,23 @@ void BKE_vfont_free(struct VFont *vf) } } +void BKE_vfont_copy_data(Main *UNUSED(bmain), VFont *vfont_dst, const VFont *UNUSED(vfont_src), const int flag) +{ + /* We never handle usercount here for own data. */ + const int flag_subdata = flag | LIB_ID_CREATE_NO_USER_REFCOUNT; + + /* Just to be sure, should not have any value actually after reading time. */ + vfont_dst->temp_pf = NULL; + + if (vfont_dst->packedfile) { + vfont_dst->packedfile = dupPackedFile(vfont_dst->packedfile); + } + + if (vfont_dst->data) { + vfont_dst->data = BLI_vfontdata_copy(vfont_dst->data, flag_subdata); + } +} + static void *builtin_font_data = NULL; static int builtin_font_size = 0; @@ -249,7 +266,7 @@ VFont *BKE_vfont_load(Main *bmain, const char *filepath) vfd = BLI_vfontdata_from_freetypefont(pf); if (vfd) { - vfont = BKE_libblock_alloc(bmain, ID_VF, filename); + vfont = BKE_libblock_alloc(bmain, ID_VF, filename, 0); vfont->data = vfd; /* if there's a font name, use it for the ID name */ diff --git a/source/blender/blenkernel/intern/freestyle.c b/source/blender/blenkernel/intern/freestyle.c index 0a0b023df82..e45a938a4fc 100644 --- a/source/blender/blenkernel/intern/freestyle.c +++ b/source/blender/blenkernel/intern/freestyle.c @@ -44,7 +44,7 @@ // function declarations static FreestyleLineSet *alloc_lineset(void); -static void copy_lineset(FreestyleLineSet *new_lineset, FreestyleLineSet *lineset); +static void copy_lineset(FreestyleLineSet *new_lineset, FreestyleLineSet *lineset, const int flag); static FreestyleModuleConfig *alloc_module(void); static void copy_module(FreestyleModuleConfig *new_module, FreestyleModuleConfig *module); @@ -79,7 +79,7 @@ void BKE_freestyle_config_free(FreestyleConfig *config) BLI_freelistN(&config->modules); } -void BKE_freestyle_config_copy(FreestyleConfig *new_config, FreestyleConfig *config) +void BKE_freestyle_config_copy(FreestyleConfig *new_config, FreestyleConfig *config, const int flag) { FreestyleLineSet *lineset, *new_lineset; FreestyleModuleConfig *module, *new_module; @@ -93,7 +93,7 @@ void BKE_freestyle_config_copy(FreestyleConfig *new_config, FreestyleConfig *con BLI_listbase_clear(&new_config->linesets); for (lineset = (FreestyleLineSet *)config->linesets.first; lineset; lineset = lineset->next) { new_lineset = alloc_lineset(); - copy_lineset(new_lineset, lineset); + copy_lineset(new_lineset, lineset, flag); BLI_addtail(&new_config->linesets, (void *)new_lineset); } @@ -105,11 +105,9 @@ void BKE_freestyle_config_copy(FreestyleConfig *new_config, FreestyleConfig *con } } -static void copy_lineset(FreestyleLineSet *new_lineset, FreestyleLineSet *lineset) +static void copy_lineset(FreestyleLineSet *new_lineset, FreestyleLineSet *lineset, const int flag) { new_lineset->linestyle = lineset->linestyle; - if (new_lineset->linestyle) - id_us_plus(&new_lineset->linestyle->id); new_lineset->flags = lineset->flags; new_lineset->selection = lineset->selection; new_lineset->qi = lineset->qi; @@ -118,10 +116,12 @@ static void copy_lineset(FreestyleLineSet *new_lineset, FreestyleLineSet *linese new_lineset->edge_types = lineset->edge_types; new_lineset->exclude_edge_types = lineset->exclude_edge_types; new_lineset->group = lineset->group; - if (new_lineset->group) { - id_us_plus(&new_lineset->group->id); - } strcpy(new_lineset->name, lineset->name); + + if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) { + id_us_plus((ID *)new_lineset->linestyle); + id_us_plus((ID *)new_lineset->group); + } } static FreestyleModuleConfig *alloc_module(void) diff --git a/source/blender/blenkernel/intern/gpencil.c b/source/blender/blenkernel/intern/gpencil.c index 30fc8915d46..ee0d0b41898 100644 --- a/source/blender/blenkernel/intern/gpencil.c +++ b/source/blender/blenkernel/intern/gpencil.c @@ -627,7 +627,7 @@ bGPdata *BKE_gpencil_data_addnew(const char name[]) bGPdata *gpd; /* allocate memory for a new block */ - gpd = BKE_libblock_alloc(G.main, ID_GD, name); + gpd = BKE_libblock_alloc(G.main, ID_GD, name, 0); /* initial settings */ gpd->flag = (GP_DATA_DISPINFO | GP_DATA_EXPAND); @@ -753,47 +753,62 @@ bGPDlayer *BKE_gpencil_layer_duplicate(const bGPDlayer *gpl_src) return gpl_dst; } -/* make a copy of a given gpencil datablock */ -bGPdata *BKE_gpencil_data_duplicate(Main *bmain, bGPdata *gpd_src, bool internal_copy) +/** + * Only copy internal data of GreasePencil ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_gpencil_copy_data(Main *UNUSED(bmain), bGPdata *gpd_dst, const bGPdata *gpd_src, const int UNUSED(flag)) { - const bGPDlayer *gpl_src; - bGPDlayer *gpl_dst; - bGPdata *gpd_dst; + /* copy layers */ + BLI_listbase_clear(&gpd_dst->layers); + for (const bGPDlayer *gpl_src = gpd_src->layers.first; gpl_src; gpl_src = gpl_src->next) { + /* make a copy of source layer and its data */ + bGPDlayer *gpl_dst = BKE_gpencil_layer_duplicate(gpl_src); /* TODO here too could add unused flags... */ + BLI_addtail(&gpd_dst->layers, gpl_dst); + } - /* error checking */ - if (gpd_src == NULL) { - return NULL; + /* copy palettes */ + BLI_listbase_clear(&gpd_dst->palettes); + for (const bGPDpalette *palette_src = gpd_src->palettes.first; palette_src; palette_src = palette_src->next) { + bGPDpalette *palette_dst = BKE_gpencil_palette_duplicate(palette_src); /* TODO here too could add unused flags... */ + BLI_addtail(&gpd_dst->palettes, palette_dst); } - - /* make a copy of the base-data */ +} + +/* make a copy of a given gpencil datablock */ +bGPdata *BKE_gpencil_data_duplicate(Main *bmain, const bGPdata *gpd_src, bool internal_copy) +{ + /* Yuck and super-uber-hyper yuck!!! + * Should be replaceable with a no-main copy (LIB_ID_COPY_NO_MAIN etc.), but not sure about it, + * so for now keep old code for that one. */ if (internal_copy) { + const bGPDlayer *gpl_src; + bGPDlayer *gpl_dst; + bGPdata *gpd_dst; + /* make a straight copy for undo buffers used during stroke drawing */ gpd_dst = MEM_dupallocN(gpd_src); + + /* copy layers */ + BLI_listbase_clear(&gpd_dst->layers); + for (gpl_src = gpd_src->layers.first; gpl_src; gpl_src = gpl_src->next) { + /* make a copy of source layer and its data */ + gpl_dst = BKE_gpencil_layer_duplicate(gpl_src); + BLI_addtail(&gpd_dst->layers, gpl_dst); + } + + /* return new */ + return gpd_dst; } else { - /* make a copy when others use this */ - gpd_dst = BKE_libblock_copy(bmain, &gpd_src->id); + bGPdata *gpd_copy; + BKE_id_copy_ex(bmain, &gpd_src->id, (ID **)&gpd_copy, 0, false); + return gpd_copy; } - - /* copy layers */ - BLI_listbase_clear(&gpd_dst->layers); - for (gpl_src = gpd_src->layers.first; gpl_src; gpl_src = gpl_src->next) { - /* make a copy of source layer and its data */ - gpl_dst = BKE_gpencil_layer_duplicate(gpl_src); - BLI_addtail(&gpd_dst->layers, gpl_dst); - } - if (!internal_copy) { - /* copy palettes */ - bGPDpalette *palette_src, *palette_dst; - BLI_listbase_clear(&gpd_dst->palettes); - for (palette_src = gpd_src->palettes.first; palette_src; palette_src = palette_src->next) { - palette_dst = BKE_gpencil_palette_duplicate(palette_src); - BLI_addtail(&gpd_dst->palettes, palette_dst); - } - } - - /* return new */ - return gpd_dst; } void BKE_gpencil_make_local(Main *bmain, bGPdata *gpd, const bool lib_local) diff --git a/source/blender/blenkernel/intern/group.c b/source/blender/blenkernel/intern/group.c index 9b011dbb003..fd6e9681e64 100644 --- a/source/blender/blenkernel/intern/group.c +++ b/source/blender/blenkernel/intern/group.c @@ -79,7 +79,9 @@ Group *BKE_group_add(Main *bmain, const char *name) { Group *group; - group = BKE_libblock_alloc(bmain, ID_GR, name); + group = BKE_libblock_alloc(bmain, ID_GR, name, 0); + id_us_min(&group->id); + id_us_ensure_real(&group->id); group->layer = (1 << 20) - 1; group->preview = NULL; @@ -87,19 +89,32 @@ Group *BKE_group_add(Main *bmain, const char *name) return group; } -Group *BKE_group_copy(Main *bmain, Group *group) +/** + * Only copy internal data of Group ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_group_copy_data(Main *UNUSED(bmain), Group *group_dst, const Group *group_src, const int flag) { - Group *groupn; - - groupn = BKE_libblock_copy(bmain, &group->id); - BLI_duplicatelist(&groupn->gobject, &group->gobject); + BLI_duplicatelist(&group_dst->gobject, &group_src->gobject); /* Do not copy group's preview (same behavior as for objects). */ - groupn->preview = NULL; - - BKE_id_copy_ensure_local(bmain, &group->id, &groupn->id); + if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0 && false) { /* XXX TODO temp hack */ + BKE_previewimg_id_copy(&group_dst->id, &group_src->id); + } + else { + group_dst->preview = NULL; + } +} - return groupn; +Group *BKE_group_copy(Main *bmain, const Group *group) +{ + Group *group_copy; + BKE_id_copy_ex(bmain, &group->id, (ID **)&group_copy, 0, false); + return group_copy; } void BKE_group_make_local(Main *bmain, Group *group, const bool lib_local) diff --git a/source/blender/blenkernel/intern/icons.c b/source/blender/blenkernel/intern/icons.c index 7669c4ba112..a98a1b13402 100644 --- a/source/blender/blenkernel/intern/icons.c +++ b/source/blender/blenkernel/intern/icons.c @@ -204,7 +204,7 @@ void BKE_previewimg_clear(struct PreviewImage *prv) } } -PreviewImage *BKE_previewimg_copy(PreviewImage *prv) +PreviewImage *BKE_previewimg_copy(const PreviewImage *prv) { PreviewImage *prv_img = NULL; int i; @@ -222,7 +222,7 @@ PreviewImage *BKE_previewimg_copy(PreviewImage *prv) } /** Duplicate preview image from \a id and clear icon_id, to be used by datablock copy functions. */ -void BKE_previewimg_id_copy(ID *new_id, ID *old_id) +void BKE_previewimg_id_copy(ID *new_id, const ID *old_id) { PreviewImage **old_prv_p = BKE_previewimg_id_get_p(old_id); PreviewImage **new_prv_p = BKE_previewimg_id_get_p(new_id); @@ -239,7 +239,7 @@ void BKE_previewimg_id_copy(ID *new_id, ID *old_id) } } -PreviewImage **BKE_previewimg_id_get_p(ID *id) +PreviewImage **BKE_previewimg_id_get_p(const ID *id) { switch (GS(id->name)) { #define ID_PRV_CASE(id_code, id_struct) case id_code: { return &((id_struct *)id)->preview; } ((void)0) @@ -253,6 +253,8 @@ PreviewImage **BKE_previewimg_id_get_p(ID *id) ID_PRV_CASE(ID_GR, Group); ID_PRV_CASE(ID_SCE, Scene); #undef ID_PRV_CASE + default: + break; } return NULL; diff --git a/source/blender/blenkernel/intern/idprop.c b/source/blender/blenkernel/intern/idprop.c index e98181be444..45b41fa01ed 100644 --- a/source/blender/blenkernel/intern/idprop.c +++ b/source/blender/blenkernel/intern/idprop.c @@ -90,7 +90,7 @@ IDProperty *IDP_NewIDPArray(const char *name) return prop; } -IDProperty *IDP_CopyIDPArray(const IDProperty *array) +IDProperty *IDP_CopyIDPArray(const IDProperty *array, const int flag) { /* don't use MEM_dupallocN because this may be part of an array */ IDProperty *narray, *tmp; @@ -109,7 +109,7 @@ IDProperty *IDP_CopyIDPArray(const IDProperty *array) * then free it. this makes for more maintainable * code than simply reimplementing the copy functions * in this loop.*/ - tmp = IDP_CopyProperty(GETPROP(narray, i)); + tmp = IDP_CopyProperty_ex(GETPROP(narray, i), flag); memcpy(GETPROP(narray, i), tmp, sizeof(IDProperty)); MEM_freeN(tmp); } @@ -285,9 +285,9 @@ void IDP_FreeArray(IDProperty *prop) } -static IDProperty *idp_generic_copy(const IDProperty *prop) +static IDProperty *idp_generic_copy(const IDProperty *prop, const int UNUSED(flag)) { - IDProperty *newp = MEM_callocN(sizeof(IDProperty), "IDProperty array dup"); + IDProperty *newp = MEM_callocN(sizeof(IDProperty), __func__); BLI_strncpy(newp->name, prop->name, MAX_IDPROP_NAME); newp->type = prop->type; @@ -298,9 +298,9 @@ static IDProperty *idp_generic_copy(const IDProperty *prop) return newp; } -static IDProperty *IDP_CopyArray(const IDProperty *prop) +static IDProperty *IDP_CopyArray(const IDProperty *prop, const int flag) { - IDProperty *newp = idp_generic_copy(prop); + IDProperty *newp = idp_generic_copy(prop, flag); if (prop->data.pointer) { newp->data.pointer = MEM_dupallocN(prop->data.pointer); @@ -310,7 +310,7 @@ static IDProperty *IDP_CopyArray(const IDProperty *prop) int a; for (a = 0; a < prop->len; a++) - array[a] = IDP_CopyProperty(array[a]); + array[a] = IDP_CopyProperty_ex(array[a], flag); } } newp->len = prop->len; @@ -363,12 +363,12 @@ IDProperty *IDP_NewString(const char *st, const char *name, int maxlen) return prop; } -static IDProperty *IDP_CopyString(const IDProperty *prop) +static IDProperty *IDP_CopyString(const IDProperty *prop, const int flag) { IDProperty *newp; BLI_assert(prop->type == IDP_STRING); - newp = idp_generic_copy(prop); + newp = idp_generic_copy(prop, flag); if (prop->data.pointer) newp->data.pointer = MEM_dupallocN(prop->data.pointer); @@ -442,15 +442,17 @@ void IDP_FreeString(IDProperty *prop) /** \name IDProperty ID API * \{ */ -static IDProperty *IDP_CopyID(const IDProperty *prop) +static IDProperty *IDP_CopyID(const IDProperty *prop, const int flag) { IDProperty *newp; BLI_assert(prop->type == IDP_ID); - newp = idp_generic_copy(prop); + newp = idp_generic_copy(prop, flag); newp->data.pointer = prop->data.pointer; - id_us_plus(IDP_Id(newp)); + if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) { + id_us_plus(IDP_Id(newp)); + } return newp; } @@ -467,16 +469,16 @@ static IDProperty *IDP_CopyID(const IDProperty *prop) /** * Checks if a property with the same name as prop exists, and if so replaces it. */ -static IDProperty *IDP_CopyGroup(const IDProperty *prop) +static IDProperty *IDP_CopyGroup(const IDProperty *prop, const int flag) { IDProperty *newp, *link; BLI_assert(prop->type == IDP_GROUP); - newp = idp_generic_copy(prop); + newp = idp_generic_copy(prop, flag); newp->len = prop->len; for (link = prop->data.group.first; link; link = link->next) { - BLI_addtail(&newp->data.group, IDP_CopyProperty(link)); + BLI_addtail(&newp->data.group, IDP_CopyProperty_ex(link, flag)); } return newp; @@ -730,18 +732,23 @@ static void IDP_FreeGroup(IDProperty *prop, const bool do_id_user) /** \name IDProperty Main API * \{ */ -IDProperty *IDP_CopyProperty(const IDProperty *prop) +IDProperty *IDP_CopyProperty_ex(const IDProperty *prop, const int flag) { switch (prop->type) { - case IDP_GROUP: return IDP_CopyGroup(prop); - case IDP_STRING: return IDP_CopyString(prop); - case IDP_ID: return IDP_CopyID(prop); - case IDP_ARRAY: return IDP_CopyArray(prop); - case IDP_IDPARRAY: return IDP_CopyIDPArray(prop); - default: return idp_generic_copy(prop); + case IDP_GROUP: return IDP_CopyGroup(prop, flag); + case IDP_STRING: return IDP_CopyString(prop, flag); + case IDP_ID: return IDP_CopyID(prop, flag); + case IDP_ARRAY: return IDP_CopyArray(prop, flag); + case IDP_IDPARRAY: return IDP_CopyIDPArray(prop, flag); + default: return idp_generic_copy(prop, flag); } } +IDProperty *IDP_CopyProperty(const IDProperty *prop) +{ + return IDP_CopyProperty_ex(prop, 0); +} + /* Updates ID pointers after an object has been copied */ /* TODO Nuke this once its only user has been correctly converted to use generic ID management from BKE_library! */ void IDP_RelinkProperty(struct IDProperty *prop) diff --git a/source/blender/blenkernel/intern/image.c b/source/blender/blenkernel/intern/image.c index 026e8aea74f..902076c2d14 100644 --- a/source/blender/blenkernel/intern/image.c +++ b/source/blender/blenkernel/intern/image.c @@ -62,6 +62,7 @@ #include "BLI_blenlib.h" #include "BLI_math_vector.h" +#include "BLI_mempool.h" #include "BLI_threads.h" #include "BLI_timecode.h" /* for stamp timecode format */ #include "BLI_utildefines.h" @@ -302,8 +303,11 @@ static void image_free_anims(Image *ima) * Simply free the image data from memory, * on display the image can load again (except for render buffers). */ -void BKE_image_free_buffers(Image *ima) +void BKE_image_free_buffers_ex(Image *ima, bool do_lock) { + if (do_lock) { + BLI_spin_lock(&image_spin); + } image_free_cached_frames(ima); image_free_anims(ima); @@ -322,6 +326,15 @@ void BKE_image_free_buffers(Image *ima) } ima->ok = IMA_OK; + + if (do_lock) { + BLI_spin_unlock(&image_spin); + } +} + +void BKE_image_free_buffers(Image *ima) +{ + BKE_image_free_buffers_ex(ima, false); } /** Free (or release) any data used by this image (does not free the image itself). */ @@ -381,7 +394,7 @@ static Image *image_alloc(Main *bmain, const char *name, short source, short typ { Image *ima; - ima = BKE_libblock_alloc(bmain, ID_IM, name); + ima = BKE_libblock_alloc(bmain, ID_IM, name, 0); if (ima) { image_init(ima, source, type); } @@ -432,39 +445,53 @@ static void copy_image_packedfiles(ListBase *lb_dst, const ListBase *lb_src) } } -/* empty image block, of similar type and filename */ -Image *BKE_image_copy(Main *bmain, Image *ima) +/** + * Only copy internal data of Image ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_image_copy_data(Main *UNUSED(bmain), Image *ima_dst, const Image *ima_src, const int flag) { - Image *nima = image_alloc(bmain, ima->id.name + 2, ima->source, ima->type); - - BLI_strncpy(nima->name, ima->name, sizeof(ima->name)); - - nima->flag = ima->flag; - nima->tpageflag = ima->tpageflag; - - nima->gen_x = ima->gen_x; - nima->gen_y = ima->gen_y; - nima->gen_type = ima->gen_type; - copy_v4_v4(nima->gen_color, ima->gen_color); + BKE_color_managed_colorspace_settings_copy(&ima_dst->colorspace_settings, &ima_src->colorspace_settings); - nima->animspeed = ima->animspeed; + copy_image_packedfiles(&ima_dst->packedfiles, &ima_src->packedfiles); - nima->aspx = ima->aspx; - nima->aspy = ima->aspy; + ima_dst->stereo3d_format = MEM_dupallocN(ima_src->stereo3d_format); + BLI_duplicatelist(&ima_dst->views, &ima_src->views); - BKE_color_managed_colorspace_settings_copy(&nima->colorspace_settings, &ima->colorspace_settings); - - copy_image_packedfiles(&nima->packedfiles, &ima->packedfiles); + /* Cleanup stuff that cannot be copied. */ + ima_dst->cache = NULL; + ima_dst->rr = NULL; + for (int i = 0; i < IMA_MAX_RENDER_SLOT; i++) { + ima_dst->renders[i] = NULL; + } - /* nima->stere3d_format is already allocated by image_alloc... */ - *nima->stereo3d_format = *ima->stereo3d_format; - BLI_duplicatelist(&nima->views, &ima->views); + BLI_listbase_clear(&ima_dst->anims); - BKE_previewimg_id_copy(&nima->id, &ima->id); + ima_dst->totbind = 0; + for (int i = 0; i < TEXTARGET_COUNT; i++) { + ima_dst->bindcode[i] = 0; + ima_dst->gputexture[i] = NULL; + } + ima_dst->repbind = NULL; - BKE_id_copy_ensure_local(bmain, &ima->id, &nima->id); + if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0) { + BKE_previewimg_id_copy(&ima_dst->id, &ima_src->id); + } + else { + ima_dst->preview = NULL; + } +} - return nima; +/* empty image block, of similar type and filename */ +Image *BKE_image_copy(Main *bmain, const Image *ima) +{ + Image *ima_copy; + BKE_id_copy_ex(bmain, &ima->id, (ID **)&ima_copy, 0, false); + return ima_copy; } void BKE_image_make_local(Main *bmain, Image *ima, const bool lib_local) @@ -2862,7 +2889,7 @@ bool BKE_image_is_stereo(Image *ima) { return BKE_image_is_multiview(ima) && (BLI_findstring(&ima->views, STEREO_LEFT_NAME, offsetof(ImageView, name)) && - BLI_findstring(&ima->views, STEREO_RIGHT_NAME, offsetof(ImageView, name))); + BLI_findstring(&ima->views, STEREO_RIGHT_NAME, offsetof(ImageView, name))); } static void image_init_multilayer_multiview(Image *ima, RenderResult *rr) @@ -4132,33 +4159,32 @@ typedef struct ImagePoolEntry { typedef struct ImagePool { ListBase image_buffers; + BLI_mempool *memory_pool; } ImagePool; ImagePool *BKE_image_pool_new(void) { ImagePool *pool = MEM_callocN(sizeof(ImagePool), "Image Pool"); + pool->memory_pool = BLI_mempool_create(sizeof(ImagePoolEntry), 0, 128, BLI_MEMPOOL_NOP); return pool; } void BKE_image_pool_free(ImagePool *pool) { - ImagePoolEntry *entry, *next_entry; - - /* use single lock to dereference all the image buffers */ + /* Use single lock to dereference all the image buffers. */ BLI_spin_lock(&image_spin); - - for (entry = pool->image_buffers.first; entry; entry = next_entry) { - next_entry = entry->next; - - if (entry->ibuf) + for (ImagePoolEntry *entry = pool->image_buffers.first; + entry != NULL; + entry = entry->next) + { + if (entry->ibuf) { IMB_freeImBuf(entry->ibuf); - - MEM_freeN(entry); + } } - BLI_spin_unlock(&image_spin); + BLI_mempool_destroy(pool->memory_pool); MEM_freeN(pool); } @@ -4210,7 +4236,7 @@ ImBuf *BKE_image_pool_acquire_ibuf(Image *ima, ImageUser *iuser, ImagePool *pool ibuf = image_acquire_ibuf(ima, iuser, NULL); - entry = MEM_callocN(sizeof(ImagePoolEntry), "Image Pool Entry"); + entry = BLI_mempool_alloc(pool->memory_pool); entry->image = ima; entry->frame = frame; entry->index = index; diff --git a/source/blender/blenkernel/intern/image_gen.c b/source/blender/blenkernel/intern/image_gen.c index 2c8399adece..1f1f4c9d341 100644 --- a/source/blender/blenkernel/intern/image_gen.c +++ b/source/blender/blenkernel/intern/image_gen.c @@ -132,7 +132,7 @@ static void image_buf_fill_checker_slice(unsigned char *rect, float hsv[3] = {0.0f, 0.9f, 0.9f}; float rgb[3]; - float dark_linear_color, bright_linear_color; + float dark_linear_color = 0.0f, bright_linear_color = 0.0f; if (rect_float != NULL) { dark_linear_color = srgb_to_linearrgb(0.25f); bright_linear_color = srgb_to_linearrgb(0.58f); diff --git a/source/blender/blenkernel/intern/key.c b/source/blender/blenkernel/intern/key.c index 8a7c1dd2833..fd42556067e 100644 --- a/source/blender/blenkernel/intern/key.c +++ b/source/blender/blenkernel/intern/key.c @@ -107,7 +107,7 @@ Key *BKE_key_add(ID *id) /* common function */ Key *key; char *el; - key = BKE_libblock_alloc(G.main, ID_KE, "Key"); + key = BKE_libblock_alloc(G.main, ID_KE, "Key", 0); key->type = KEY_NORMAL; key->from = id; @@ -146,36 +146,48 @@ Key *BKE_key_add(ID *id) /* common function */ key->elemsize = 16; break; + + default: + break; } return key; } -Key *BKE_key_copy(Main *bmain, Key *key) +/** + * Only copy internal data of ShapeKey ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_key_copy_data(Main *UNUSED(bmain), Key *key_dst, const Key *key_src, const int UNUSED(flag)) { - Key *keyn; - KeyBlock *kbn, *kb; - - keyn = BKE_libblock_copy(bmain, &key->id); - - BLI_duplicatelist(&keyn->block, &key->block); - - kb = key->block.first; - kbn = keyn->block.first; - while (kbn) { - - if (kbn->data) kbn->data = MEM_dupallocN(kbn->data); - if (kb == key->refkey) keyn->refkey = kbn; - - kbn = kbn->next; - kb = kb->next; - } + BLI_duplicatelist(&key_dst->block, &key_src->block); - BKE_id_copy_ensure_local(bmain, &key->id, &keyn->id); + KeyBlock *kb_dst, *kb_src; + for (kb_src = key_src->block.first, kb_dst = key_dst->block.first; + kb_dst; + kb_src = kb_src->next, kb_dst = kb_dst->next) + { + if (kb_dst->data) { + kb_dst->data = MEM_dupallocN(kb_dst->data); + } + if (kb_src == key_src->refkey) { + key_dst->refkey = kb_dst; + } + } +} - return keyn; +Key *BKE_key_copy(Main *bmain, const Key *key) +{ + Key *key_copy; + BKE_id_copy_ex(bmain, &key->id, (ID **)&key_copy, 0, false); + return key_copy; } +/* XXX TODO get rid of this! */ Key *BKE_key_copy_nolib(Key *key) { Key *keyn; @@ -1397,6 +1409,8 @@ Key **BKE_key_from_id_p(ID *id) Lattice *lt = (Lattice *)id; return <->key; } + default: + break; } return NULL; diff --git a/source/blender/blenkernel/intern/lamp.c b/source/blender/blenkernel/intern/lamp.c index 69a2067f4e6..e8ef346927e 100644 --- a/source/blender/blenkernel/intern/lamp.c +++ b/source/blender/blenkernel/intern/lamp.c @@ -109,42 +109,60 @@ Lamp *BKE_lamp_add(Main *bmain, const char *name) { Lamp *la; - la = BKE_libblock_alloc(bmain, ID_LA, name); + la = BKE_libblock_alloc(bmain, ID_LA, name, 0); BKE_lamp_init(la); return la; } -Lamp *BKE_lamp_copy(Main *bmain, Lamp *la) +/** + * Only copy internal data of Lamp ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_lamp_copy_data(Main *bmain, Lamp *la_dst, const Lamp *la_src, const int flag) { - Lamp *lan; - int a; - - lan = BKE_libblock_copy(bmain, &la->id); - - for (a = 0; a < MAX_MTEX; a++) { - if (lan->mtex[a]) { - lan->mtex[a] = MEM_mallocN(sizeof(MTex), "copylamptex"); - memcpy(lan->mtex[a], la->mtex[a], sizeof(MTex)); - id_us_plus((ID *)lan->mtex[a]->tex); + for (int a = 0; a < MAX_MTEX; a++) { + if (la_dst->mtex[a]) { + la_dst->mtex[a] = MEM_mallocN(sizeof(*la_dst->mtex[a]), __func__); + *la_dst->mtex[a] = *la_src->mtex[a]; } } - - lan->curfalloff = curvemapping_copy(la->curfalloff); - if (la->nodetree) - lan->nodetree = ntreeCopyTree(bmain, la->nodetree); + la_dst->curfalloff = curvemapping_copy(la_src->curfalloff); - BKE_previewimg_id_copy(&lan->id, &la->id); + if (la_src->nodetree) { + BKE_id_copy_ex(bmain, (ID *)la_src->nodetree, (ID **)&la_dst->nodetree, flag, false); + } - BKE_id_copy_ensure_local(bmain, &la->id, &lan->id); + if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0) { + BKE_previewimg_id_copy(&la_dst->id, &la_src->id); + } + else { + la_dst->preview = NULL; + } +} - return lan; +Lamp *BKE_lamp_copy(Main *bmain, const Lamp *la) +{ + Lamp *la_copy; + BKE_id_copy_ex(bmain, &la->id, (ID **)&la_copy, 0, false); + return la_copy; } Lamp *localize_lamp(Lamp *la) { + /* TODO replace with something like + * Lamp *la_copy; + * BKE_id_copy_ex(bmain, &la->id, (ID **)&la_copy, LIB_ID_COPY_NO_MAIN | LIB_ID_COPY_NO_PREVIEW | LIB_ID_COPY_NO_USER_REFCOUNT, false); + * return la_copy; + * + * ... Once f*** nodes are fully converted to that too :( */ + Lamp *lan; int a; diff --git a/source/blender/blenkernel/intern/lattice.c b/source/blender/blenkernel/intern/lattice.c index 54cfae620a1..ea4c3f380ff 100644 --- a/source/blender/blenkernel/intern/lattice.c +++ b/source/blender/blenkernel/intern/lattice.c @@ -270,39 +270,46 @@ Lattice *BKE_lattice_add(Main *bmain, const char *name) { Lattice *lt; - lt = BKE_libblock_alloc(bmain, ID_LT, name); + lt = BKE_libblock_alloc(bmain, ID_LT, name, 0); BKE_lattice_init(lt); return lt; } -Lattice *BKE_lattice_copy(Main *bmain, Lattice *lt) +/** + * Only copy internal data of Lattice ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_lattice_copy_data(Main *bmain, Lattice *lt_dst, const Lattice *lt_src, const int flag) { - Lattice *ltn; + lt_dst->def = MEM_dupallocN(lt_src->def); - ltn = BKE_libblock_copy(bmain, <->id); - ltn->def = MEM_dupallocN(lt->def); - - if (lt->key) { - ltn->key = BKE_key_copy(bmain, ltn->key); - ltn->key->from = (ID *)ltn; - } - - if (lt->dvert) { - int tot = lt->pntsu * lt->pntsv * lt->pntsw; - ltn->dvert = MEM_mallocN(sizeof(MDeformVert) * tot, "Lattice MDeformVert"); - BKE_defvert_array_copy(ltn->dvert, lt->dvert, tot); + if (lt_src->key) { + BKE_id_copy_ex(bmain, <_src->key->id, (ID **)<_dst->key, flag, false); } - ltn->editlatt = NULL; + if (lt_src->dvert) { + int tot = lt_src->pntsu * lt_src->pntsv * lt_src->pntsw; + lt_dst->dvert = MEM_mallocN(sizeof(MDeformVert) * tot, "Lattice MDeformVert"); + BKE_defvert_array_copy(lt_dst->dvert, lt_src->dvert, tot); + } - BKE_id_copy_ensure_local(bmain, <->id, <n->id); + lt_dst->editlatt = NULL; +} - return ltn; +Lattice *BKE_lattice_copy(Main *bmain, const Lattice *lt) +{ + Lattice *lt_copy; + BKE_id_copy_ex(bmain, <->id, (ID **)<_copy, 0, false); + return lt_copy; } -/** Free (or release) any data used by this lattice (does not free the lattice itself). */ + /** Free (or release) any data used by this lattice (does not free the lattice itself). */ void BKE_lattice_free(Lattice *lt) { BKE_animdata_free(<->id, false); diff --git a/source/blender/blenkernel/intern/library.c b/source/blender/blenkernel/intern/library.c index c249577686e..d5dfc63b317 100644 --- a/source/blender/blenkernel/intern/library.c +++ b/source/blender/blenkernel/intern/library.c @@ -307,7 +307,7 @@ void BKE_id_expand_local(Main *bmain, ID *id) /** * Ensure new (copied) ID is fully made local. */ -void BKE_id_copy_ensure_local(Main *bmain, ID *old_id, ID *new_id) +void BKE_id_copy_ensure_local(Main *bmain, const ID *old_id, ID *new_id) { if (ID_IS_LINKED_DATABLOCK(old_id)) { BKE_id_expand_local(bmain, new_id); @@ -383,7 +383,6 @@ bool id_make_local(Main *bmain, ID *id, const bool test, const bool lib_local) switch ((ID_Type)GS(id->name)) { case ID_SCE: - /* Partially implemented (has no copy...). */ if (!test) BKE_scene_make_local(bmain, (Scene *)id, lib_local); return true; case ID_OB: @@ -423,14 +422,12 @@ bool id_make_local(Main *bmain, ID *id, const bool test, const bool lib_local) if (!test) BKE_world_make_local(bmain, (World *)id, lib_local); return true; case ID_VF: - /* Partially implemented (has no copy...). */ if (!test) BKE_vfont_make_local(bmain, (VFont *)id, lib_local); return true; case ID_TXT: if (!test) BKE_text_make_local(bmain, (Text *)id, lib_local); return true; case ID_SO: - /* Partially implemented (has no copy...). */ if (!test) BKE_sound_make_local(bmain, (bSound *)id, lib_local); return true; case ID_GR: @@ -484,114 +481,189 @@ bool id_make_local(Main *bmain, ID *id, const bool test, const bool lib_local) return false; } +struct IDCopyLibManagementData { + const ID *id_src; + ID *id_dst; + int flag; +}; + +/* Increases usercount as required, and remap self ID pointers. */ +static int id_copy_libmanagement_cb(void *user_data, ID *UNUSED(id_self), ID **id_pointer, int cb_flag) +{ + struct IDCopyLibManagementData *data = user_data; + ID *id = *id_pointer; + + /* Remap self-references to new copied ID. */ + if (id == data->id_src) { + /* We cannot use id_self here, it is not *always* id_dst (thanks to $£!+@#&/? nodetrees). */ + id = *id_pointer = data->id_dst; + } + + /* Increase used IDs refcount if needed and required. */ + if ((data->flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0 && (cb_flag & IDWALK_CB_USER)) { + id_us_plus(id); + } + + return IDWALK_RET_NOP; +} + /** - * Invokes the appropriate copy method for the block and returns the result in - * newid, unless test. Returns true if the block can be copied. + * Generic entry point for copying a datablock (new API). + * + * \note Copy is only affecting given data-block (no ID used by copied one will be affected, besides usercount). + * There is only one exception, if LIB_ID_COPY_ACTIONS is defined, actions used by animdata will be duplicated. + * + * \note Usercount of new copy is always set to 1. + * + * \param bmain Main database, may be NULL only if LIB_ID_COPY_NO_MAIN is specified. + * \param id Source datablock. + * \param r_newid Pointer to new (copied) ID pointer. + * \param flag Set of copy options, see DNA_ID.h enum for details (leave to zero for default, full copy). + * \param test If set, do not do any copy, just test whether copy is supported. + * \return False when copying that ID type is not supported, true otherwise. */ -bool id_copy(Main *bmain, ID *id, ID **newid, bool test) +/* XXX TODO remove test thing, *all* IDs should be copyable that way! */ +bool BKE_id_copy_ex(Main *bmain, const ID *id, ID **r_newid, const int flag, const bool test) { - if (!test) { - *newid = NULL; +#define LIB_ID_TYPES_NOCOPY ID_LI, ID_SCR, ID_WM, /* Not supported */ \ + ID_IP /* Deprecated */ + + BLI_assert(test || (r_newid != NULL)); + if (r_newid != NULL) { + *r_newid = NULL; + } + if (id == NULL) { + return false; } - /* conventions: - * - make shallow copy, only this ID block - * - id.us of the new ID is set to 1 */ + if (ELEM(GS(id->name), LIB_ID_TYPES_NOCOPY)) { + return false; + } + else if (test) { + return true; + } + + BKE_libblock_copy_ex(bmain, id, r_newid, flag); + switch ((ID_Type)GS(id->name)) { + case ID_SCE: + BKE_scene_copy_data(bmain, (Scene *)*r_newid, (Scene *)id, flag); + break; case ID_OB: - if (!test) *newid = (ID *)BKE_object_copy(bmain, (Object *)id); - return true; + BKE_object_copy_data(bmain, (Object *)*r_newid, (Object *)id, flag); + break; case ID_ME: - if (!test) *newid = (ID *)BKE_mesh_copy(bmain, (Mesh *)id); - return true; + BKE_mesh_copy_data(bmain, (Mesh *)*r_newid, (Mesh *)id, flag); + break; case ID_CU: - if (!test) *newid = (ID *)BKE_curve_copy(bmain, (Curve *)id); - return true; + BKE_curve_copy_data(bmain, (Curve *)*r_newid, (Curve *)id, flag); + break; case ID_MB: - if (!test) *newid = (ID *)BKE_mball_copy(bmain, (MetaBall *)id); - return true; + BKE_mball_copy_data(bmain, (MetaBall *)*r_newid, (MetaBall *)id, flag); + break; case ID_MA: - if (!test) *newid = (ID *)BKE_material_copy(bmain, (Material *)id); - return true; + BKE_material_copy_data(bmain, (Material *)*r_newid, (Material *)id, flag); + break; case ID_TE: - if (!test) *newid = (ID *)BKE_texture_copy(bmain, (Tex *)id); - return true; + BKE_texture_copy_data(bmain, (Tex *)*r_newid, (Tex *)id, flag); + break; case ID_IM: - if (!test) *newid = (ID *)BKE_image_copy(bmain, (Image *)id); - return true; + BKE_image_copy_data(bmain, (Image *)*r_newid, (Image *)id, flag); + break; case ID_LT: - if (!test) *newid = (ID *)BKE_lattice_copy(bmain, (Lattice *)id); - return true; + BKE_lattice_copy_data(bmain, (Lattice *)*r_newid, (Lattice *)id, flag); + break; case ID_LA: - if (!test) *newid = (ID *)BKE_lamp_copy(bmain, (Lamp *)id); - return true; + BKE_lamp_copy_data(bmain, (Lamp *)*r_newid, (Lamp *)id, flag); + break; case ID_SPK: - if (!test) *newid = (ID *)BKE_speaker_copy(bmain, (Speaker *)id); - return true; + BKE_speaker_copy_data(bmain, (Speaker *)*r_newid, (Speaker *)id, flag); + break; case ID_CA: - if (!test) *newid = (ID *)BKE_camera_copy(bmain, (Camera *)id); - return true; + BKE_camera_copy_data(bmain, (Camera *)*r_newid, (Camera *)id, flag); + break; case ID_KE: - if (!test) *newid = (ID *)BKE_key_copy(bmain, (Key *)id); - return true; + BKE_key_copy_data(bmain, (Key *)*r_newid, (Key *)id, flag); + break; case ID_WO: - if (!test) *newid = (ID *)BKE_world_copy(bmain, (World *)id); - return true; + BKE_world_copy_data(bmain, (World *)*r_newid, (World *)id, flag); + break; case ID_TXT: - if (!test) *newid = (ID *)BKE_text_copy(bmain, (Text *)id); - return true; + BKE_text_copy_data(bmain, (Text *)*r_newid, (Text *)id, flag); + break; case ID_GR: - if (!test) *newid = (ID *)BKE_group_copy(bmain, (Group *)id); - return true; + BKE_group_copy_data(bmain, (Group *)*r_newid, (Group *)id, flag); + break; case ID_AR: - if (!test) *newid = (ID *)BKE_armature_copy(bmain, (bArmature *)id); - return true; + BKE_armature_copy_data(bmain, (bArmature *)*r_newid, (bArmature *)id, flag); + break; case ID_AC: - if (!test) *newid = (ID *)BKE_action_copy(bmain, (bAction *)id); - return true; + BKE_action_copy_data(bmain, (bAction *)*r_newid, (bAction *)id, flag); + break; case ID_NT: - if (!test) *newid = (ID *)ntreeCopyTree(bmain, (bNodeTree *)id); - return true; + BKE_node_tree_copy_data(bmain, (bNodeTree *)*r_newid, (bNodeTree *)id, flag); + break; case ID_BR: - if (!test) *newid = (ID *)BKE_brush_copy(bmain, (Brush *)id); - return true; + BKE_brush_copy_data(bmain, (Brush *)*r_newid, (Brush *)id, flag); + break; case ID_PA: - if (!test) *newid = (ID *)BKE_particlesettings_copy(bmain, (ParticleSettings *)id); - return true; + BKE_particlesettings_copy_data(bmain, (ParticleSettings *)*r_newid, (ParticleSettings *)id, flag); + break; case ID_GD: - if (!test) *newid = (ID *)BKE_gpencil_data_duplicate(bmain, (bGPdata *)id, false); - return true; + BKE_gpencil_copy_data(bmain, (bGPdata *)*r_newid, (bGPdata *)id, flag); + break; case ID_MC: - if (!test) *newid = (ID *)BKE_movieclip_copy(bmain, (MovieClip *)id); - return true; + BKE_movieclip_copy_data(bmain, (MovieClip *)*r_newid, (MovieClip *)id, flag); + break; case ID_MSK: - if (!test) *newid = (ID *)BKE_mask_copy(bmain, (Mask *)id); - return true; + BKE_mask_copy_data(bmain, (Mask *)*r_newid, (Mask *)id, flag); + break; case ID_LS: - if (!test) *newid = (ID *)BKE_linestyle_copy(bmain, (FreestyleLineStyle *)id); - return true; + BKE_linestyle_copy_data(bmain, (FreestyleLineStyle *)*r_newid, (FreestyleLineStyle *)id, flag); + break; case ID_PAL: - if (!test) *newid = (ID *)BKE_palette_copy(bmain, (Palette *)id); - return true; + BKE_palette_copy_data(bmain, (Palette *)*r_newid, (Palette *)id, flag); + break; case ID_PC: - if (!test) *newid = (ID *)BKE_paint_curve_copy(bmain, (PaintCurve *)id); - return true; + BKE_paint_curve_copy_data(bmain, (PaintCurve *)*r_newid, (PaintCurve *)id, flag); + break; case ID_CF: - if (!test) *newid = (ID *)BKE_cachefile_copy(bmain, (CacheFile *)id); - return true; - case ID_SCE: + BKE_cachefile_copy_data(bmain, (CacheFile *)*r_newid, (CacheFile *)id, flag); + break; + case ID_SO: + BKE_sound_copy_data(bmain, (bSound *)*r_newid, (bSound *)id, flag); + break; + case ID_VF: + BKE_vfont_copy_data(bmain, (VFont *)*r_newid, (VFont *)id, flag); + break; case ID_LI: case ID_SCR: case ID_WM: - return false; /* can't be copied from here */ - case ID_VF: - case ID_SO: - return false; /* not implemented */ case ID_IP: - return false; /* deprecated */ + BLI_assert(0); /* Should have been rejected at start of function! */ + break; } - - return false; + + /* Update ID refcount, remap pointers to self in new ID. */ + struct IDCopyLibManagementData data = {.id_src = id, .id_dst = *r_newid, .flag = flag}; + BKE_library_foreach_ID_link(bmain, *r_newid, id_copy_libmanagement_cb, &data, IDWALK_NOP); + + /* Do not make new copy local in case we are copying outside of main... + * XXX TODO: is this behavior OK, or should we need own flag to control that? */ + if ((flag & LIB_ID_CREATE_NO_MAIN) == 0) { + BKE_id_copy_ensure_local(bmain, id, *r_newid); + } + + return true; +} + +/** + * Invokes the appropriate copy method for the block and returns the result in + * newid, unless test. Returns true if the block can be copied. + */ +bool id_copy(Main *bmain, const ID *id, ID **newid, bool test) +{ + return BKE_id_copy_ex(bmain, id, newid, 0, test); } /** Does *not* set ID->newid pointer. */ @@ -623,6 +695,101 @@ bool id_single_user(bContext *C, ID *id, PointerRNA *ptr, PropertyRNA *prop) return false; } +static int libblock_management_us_plus(void *UNUSED(user_data), ID *UNUSED(id_self), ID **id_pointer, int cb_flag) +{ + if (cb_flag & IDWALK_CB_USER) { + id_us_plus(*id_pointer); + } + if (cb_flag & IDWALK_CB_USER_ONE) { + id_us_ensure_real(*id_pointer); + } + + return IDWALK_RET_NOP; +} + +static int libblock_management_us_min(void *UNUSED(user_data), ID *UNUSED(id_self), ID **id_pointer, int cb_flag) +{ + if (cb_flag & IDWALK_CB_USER) { + id_us_min(*id_pointer); + } + /* We can do nothing in IDWALK_CB_USER_ONE case! */ + + return IDWALK_RET_NOP; +} + +/** Add a 'NO_MAIN' datablock to given main (also sets usercounts of its IDs if needed). */ +void BKE_libblock_management_main_add(Main *bmain, void *idv) +{ + ID *id = idv; + + BLI_assert(bmain != NULL); + if ((id->tag & LIB_TAG_NO_MAIN) == 0) { + return; + } + + if ((id->tag & LIB_TAG_NOT_ALLOCATED) != 0) { + /* We cannot add non-allocated ID to Main! */ + return; + } + + /* We cannot allow non-userrefcounting IDs in Main database! */ + if ((id->tag & LIB_TAG_NO_USER_REFCOUNT) != 0) { + BKE_library_foreach_ID_link(bmain, id, libblock_management_us_plus, NULL, IDWALK_NOP); + } + + ListBase *lb = which_libbase(bmain, GS(id->name)); + BKE_main_lock(bmain); + BLI_addtail(lb, id); + new_id(lb, id, NULL); + /* alphabetic insertion: is in new_id */ + id->tag &= ~(LIB_TAG_NO_MAIN | LIB_TAG_NO_USER_REFCOUNT); + BKE_main_unlock(bmain); +} + +/** Remove a datablock from given main (set it to 'NO_MAIN' status). */ +void BKE_libblock_management_main_remove(Main *bmain, void *idv) +{ + ID *id = idv; + + BLI_assert(bmain != NULL); + if ((id->tag & LIB_TAG_NO_MAIN) != 0) { + return; + } + + /* For now, allow userrefcounting IDs to get out of Main - can be handy in some cases... */ + + ListBase *lb = which_libbase(bmain, GS(id->name)); + BKE_main_lock(bmain); + BLI_remlink(lb, id); + id->tag |= LIB_TAG_NO_MAIN; + BKE_main_unlock(bmain); +} + +void BKE_libblock_management_usercounts_set(Main *bmain, void *idv) +{ + ID *id = idv; + + if ((id->tag & LIB_TAG_NO_USER_REFCOUNT) == 0) { + return; + } + + BKE_library_foreach_ID_link(bmain, id, libblock_management_us_plus, NULL, IDWALK_NOP); + id->tag &= ~LIB_TAG_NO_USER_REFCOUNT; +} + +void BKE_libblock_management_usercounts_clear(Main *bmain, void *idv) +{ + ID *id = idv; + + /* We do not allow IDs in Main database to not be userrefcounting. */ + if ((id->tag & LIB_TAG_NO_USER_REFCOUNT) != 0 || (id->tag & LIB_TAG_NO_MAIN) != 0) { + return; + } + + BKE_library_foreach_ID_link(bmain, id, libblock_management_us_min, NULL, IDWALK_NOP); + id->tag |= LIB_TAG_NO_USER_REFCOUNT; +} + ListBase *which_libbase(Main *mainlib, short type) { switch ((ID_Type)type) { @@ -858,118 +1025,72 @@ int set_listbasepointers(Main *main, ListBase **lb) * **************************** */ /** + * Get allocation size fo a given datablock type and optionally allocation name. + */ +size_t BKE_libblock_get_alloc_info(short type, const char **name) +{ +#define CASE_RETURN(id_code, type) \ + case id_code: \ + do { \ + if (name != NULL) { \ + *name = #type; \ + } \ + return sizeof(type); \ + } while(0) + + switch ((ID_Type)type) { + CASE_RETURN(ID_SCE, Scene); + CASE_RETURN(ID_LI, Library); + CASE_RETURN(ID_OB, Object); + CASE_RETURN(ID_ME, Mesh); + CASE_RETURN(ID_CU, Curve); + CASE_RETURN(ID_MB, MetaBall); + CASE_RETURN(ID_MA, Material); + CASE_RETURN(ID_TE, Tex); + CASE_RETURN(ID_IM, Image); + CASE_RETURN(ID_LT, Lattice); + CASE_RETURN(ID_LA, Lamp); + CASE_RETURN(ID_CA, Camera); + CASE_RETURN(ID_IP, Ipo); + CASE_RETURN(ID_KE, Key); + CASE_RETURN(ID_WO, World); + CASE_RETURN(ID_SCR, bScreen); + CASE_RETURN(ID_VF, VFont); + CASE_RETURN(ID_TXT, Text); + CASE_RETURN(ID_SPK, Speaker); + CASE_RETURN(ID_SO, bSound); + CASE_RETURN(ID_GR, Group); + CASE_RETURN(ID_AR, bArmature); + CASE_RETURN(ID_AC, bAction); + CASE_RETURN(ID_NT, bNodeTree); + CASE_RETURN(ID_BR, Brush); + CASE_RETURN(ID_PA, ParticleSettings); + CASE_RETURN(ID_WM, wmWindowManager); + CASE_RETURN(ID_GD, bGPdata); + CASE_RETURN(ID_MC, MovieClip); + CASE_RETURN(ID_MSK, Mask); + CASE_RETURN(ID_LS, FreestyleLineStyle); + CASE_RETURN(ID_PAL, Palette); + CASE_RETURN(ID_PC, PaintCurve); + CASE_RETURN(ID_CF, CacheFile); + } + return 0; +#undef CASE_RETURN +} + +/** * Allocates and returns memory of the right size for the specified block type, * initialized to zero. */ void *BKE_libblock_alloc_notest(short type) { - ID *id = NULL; - - switch ((ID_Type)type) { - case ID_SCE: - id = MEM_callocN(sizeof(Scene), "scene"); - break; - case ID_LI: - id = MEM_callocN(sizeof(Library), "library"); - break; - case ID_OB: - id = MEM_callocN(sizeof(Object), "object"); - break; - case ID_ME: - id = MEM_callocN(sizeof(Mesh), "mesh"); - break; - case ID_CU: - id = MEM_callocN(sizeof(Curve), "curve"); - break; - case ID_MB: - id = MEM_callocN(sizeof(MetaBall), "mball"); - break; - case ID_MA: - id = MEM_callocN(sizeof(Material), "mat"); - break; - case ID_TE: - id = MEM_callocN(sizeof(Tex), "tex"); - break; - case ID_IM: - id = MEM_callocN(sizeof(Image), "image"); - break; - case ID_LT: - id = MEM_callocN(sizeof(Lattice), "latt"); - break; - case ID_LA: - id = MEM_callocN(sizeof(Lamp), "lamp"); - break; - case ID_CA: - id = MEM_callocN(sizeof(Camera), "camera"); - break; - case ID_IP: - id = MEM_callocN(sizeof(Ipo), "ipo"); - break; - case ID_KE: - id = MEM_callocN(sizeof(Key), "key"); - break; - case ID_WO: - id = MEM_callocN(sizeof(World), "world"); - break; - case ID_SCR: - id = MEM_callocN(sizeof(bScreen), "screen"); - break; - case ID_VF: - id = MEM_callocN(sizeof(VFont), "vfont"); - break; - case ID_TXT: - id = MEM_callocN(sizeof(Text), "text"); - break; - case ID_SPK: - id = MEM_callocN(sizeof(Speaker), "speaker"); - break; - case ID_SO: - id = MEM_callocN(sizeof(bSound), "sound"); - break; - case ID_GR: - id = MEM_callocN(sizeof(Group), "group"); - break; - case ID_AR: - id = MEM_callocN(sizeof(bArmature), "armature"); - break; - case ID_AC: - id = MEM_callocN(sizeof(bAction), "action"); - break; - case ID_NT: - id = MEM_callocN(sizeof(bNodeTree), "nodetree"); - break; - case ID_BR: - id = MEM_callocN(sizeof(Brush), "brush"); - break; - case ID_PA: - id = MEM_callocN(sizeof(ParticleSettings), "ParticleSettings"); - break; - case ID_WM: - id = MEM_callocN(sizeof(wmWindowManager), "Window manager"); - break; - case ID_GD: - id = MEM_callocN(sizeof(bGPdata), "Grease Pencil"); - break; - case ID_MC: - id = MEM_callocN(sizeof(MovieClip), "Movie Clip"); - break; - case ID_MSK: - id = MEM_callocN(sizeof(Mask), "Mask"); - break; - case ID_LS: - id = MEM_callocN(sizeof(FreestyleLineStyle), "Freestyle Line Style"); - break; - case ID_PAL: - id = MEM_callocN(sizeof(Palette), "Palette"); - break; - case ID_PC: - id = MEM_callocN(sizeof(PaintCurve), "Paint Curve"); - break; - case ID_CF: - id = MEM_callocN(sizeof(CacheFile), "Cache File"); - break; + const char *name; + size_t size = BKE_libblock_get_alloc_info(type, &name); + if (size != 0) { + return MEM_callocN(size, name); } - return id; + BLI_assert(!"Request to allocate unknown data type"); + return NULL; } /** @@ -978,23 +1099,44 @@ void *BKE_libblock_alloc_notest(short type) * The user count is set to 1, all other content (apart from name and links) being * initialized to zero. */ -void *BKE_libblock_alloc(Main *bmain, short type, const char *name) +void *BKE_libblock_alloc(Main *bmain, short type, const char *name, const int flag) { - ID *id = NULL; - ListBase *lb = which_libbase(bmain, type); - - id = BKE_libblock_alloc_notest(type); + BLI_assert((flag & LIB_ID_CREATE_NO_ALLOCATE) == 0); + + ID *id = BKE_libblock_alloc_notest(type); + if (id) { - BKE_main_lock(bmain); - BLI_addtail(lb, id); - id->us = 1; + if ((flag & LIB_ID_CREATE_NO_MAIN) != 0) { + id->tag |= LIB_TAG_NO_MAIN; + } + if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) != 0) { + id->tag |= LIB_TAG_NO_USER_REFCOUNT; + } + id->icon_id = 0; - *( (short *)id->name) = type; - new_id(lb, id, name); - /* alphabetic insertion: is in new_id */ - BKE_main_unlock(bmain); + *((short *)id->name) = type; + if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) { + id->us = 1; + } + if ((flag & LIB_ID_CREATE_NO_MAIN) == 0) { + ListBase *lb = which_libbase(bmain, type); + + BKE_main_lock(bmain); + BLI_addtail(lb, id); + new_id(lb, id, name); + /* alphabetic insertion: is in new_id */ + BKE_main_unlock(bmain); + + /* TODO to be removed from here! */ + if ((flag & LIB_ID_CREATE_NO_DEG_TAG) == 0) { + DAG_id_type_tag(bmain, type); + } + } + else { + BLI_strncpy(id->name + 2, name, sizeof(id->name) - 2); + } } - DAG_id_type_tag(bmain, type); + return id; } @@ -1117,70 +1259,80 @@ void BKE_libblock_init_empty(ID *id) /* by spec, animdata is first item after ID */ /* and, trust that BKE_animdata_from_id() will only find AnimData for valid ID-types */ -static void id_copy_animdata(ID *id, const bool do_action) +static void id_copy_animdata(Main *bmain, ID *id, const bool do_action) { AnimData *adt = BKE_animdata_from_id(id); if (adt) { IdAdtTemplate *iat = (IdAdtTemplate *)id; - iat->adt = BKE_animdata_copy(iat->adt, do_action); /* could be set to false, need to investigate */ + iat->adt = BKE_animdata_copy(bmain, iat->adt, do_action); /* could be set to false, need to investigate */ } } -/* material nodes use this since they are not treated as libdata */ -void BKE_libblock_copy_data(ID *id, const ID *id_from, const bool do_action) +void BKE_libblock_copy_ex(Main *bmain, const ID *id, ID **r_newid, const int flag) { - if (id_from->properties) - id->properties = IDP_CopyProperty(id_from->properties); + ID *new_id = *r_newid; - /* the duplicate should get a copy of the animdata */ - id_copy_animdata(id, do_action); -} - -/* used everywhere in blenkernel */ -void *BKE_libblock_copy(Main *bmain, ID *id) -{ - ID *idn; - size_t idn_len; + /* Grrrrrrrrr... Not adding 'root' nodetrees to bmain.... grrrrrrrrrrrrrrrrrrrr! */ + /* This is taken from original ntree copy code, might be weak actually? */ + const bool use_nodetree_alloc_exception = ((GS(id->name) == ID_NT) && (bmain != NULL) && + (BLI_findindex(&bmain->nodetree, id) < 0)); - idn = BKE_libblock_alloc(bmain, GS(id->name), id->name + 2); + BLI_assert((flag & LIB_ID_CREATE_NO_MAIN) != 0 || bmain != NULL); + BLI_assert((flag & LIB_ID_CREATE_NO_MAIN) != 0 || (flag & LIB_ID_CREATE_NO_ALLOCATE) == 0); + BLI_assert((flag & LIB_ID_CREATE_NO_MAIN) == 0 || (flag & LIB_ID_CREATE_NO_USER_REFCOUNT) != 0); - assert(idn != NULL); + if ((flag & LIB_ID_CREATE_NO_ALLOCATE) != 0) { + /* r_newid already contains pointer to allocated memory. */ + /* TODO do we want to memset(0) whole mem before filling it? */ + BLI_strncpy(new_id->name, id->name, sizeof(new_id->name)); + new_id->us = 0; + new_id->tag |= LIB_TAG_NOT_ALLOCATED | LIB_TAG_NO_MAIN | LIB_TAG_NO_USER_REFCOUNT; + /* TODO Do we want/need to copy more from ID struct itself? */ + } + else { + new_id = BKE_libblock_alloc(bmain, GS(id->name), id->name + 2, flag | (use_nodetree_alloc_exception ? LIB_ID_CREATE_NO_MAIN : 0)); + } + BLI_assert(new_id != NULL); - idn_len = MEM_allocN_len(idn); - if ((int)idn_len - (int)sizeof(ID) > 0) { /* signed to allow neg result */ + const size_t id_len = BKE_libblock_get_alloc_info(GS(new_id->name), NULL); + const size_t id_offset = sizeof(ID); + if ((int)id_len - (int)id_offset > 0) { /* signed to allow neg result */ /* XXX ????? */ const char *cp = (const char *)id; - char *cpn = (char *)idn; + char *cpn = (char *)new_id; - memcpy(cpn + sizeof(ID), cp + sizeof(ID), idn_len - sizeof(ID)); + memcpy(cpn + id_offset, cp + id_offset, id_len - id_offset); } - BKE_libblock_copy_data(idn, id, false); - - return idn; + if (id->properties) { + new_id->properties = IDP_CopyProperty_ex(id->properties, flag); + } + + /* the duplicate should get a copy of the animdata */ + id_copy_animdata(bmain, new_id, (flag & LIB_ID_COPY_ACTIONS) != 0 && (flag & LIB_ID_CREATE_NO_MAIN) == 0); + + if ((flag & LIB_ID_CREATE_NO_DEG_TAG) == 0 && (flag & LIB_ID_CREATE_NO_MAIN) == 0) { + DAG_id_type_tag(bmain, GS(new_id->name)); + } + + *r_newid = new_id; } -void *BKE_libblock_copy_nolib(ID *id, const bool do_action) +/* used everywhere in blenkernel */ +void *BKE_libblock_copy(Main *bmain, const ID *id) { ID *idn; - size_t idn_len; - idn = BKE_libblock_alloc_notest(GS(id->name)); - assert(idn != NULL); + BKE_libblock_copy_ex(bmain, id, &idn, 0); - BLI_strncpy(idn->name, id->name, sizeof(idn->name)); - - idn_len = MEM_allocN_len(idn); - if ((int)idn_len - (int)sizeof(ID) > 0) { /* signed to allow neg result */ - const char *cp = (const char *)id; - char *cpn = (char *)idn; - - memcpy(cpn + sizeof(ID), cp + sizeof(ID), idn_len - sizeof(ID)); - } + return idn; +} - idn->us = 1; +void *BKE_libblock_copy_nolib(const ID *id, const bool do_action) +{ + ID *idn; - BKE_libblock_copy_data(idn, id, do_action); + BKE_libblock_copy_ex(NULL, id, &idn, LIB_ID_CREATE_NO_MAIN | LIB_ID_CREATE_NO_USER_REFCOUNT | (do_action ? LIB_ID_COPY_ACTIONS : 0)); return idn; } diff --git a/source/blender/blenkernel/intern/library_query.c b/source/blender/blenkernel/intern/library_query.c index 931002e6bbc..d1f0c87183d 100644 --- a/source/blender/blenkernel/intern/library_query.c +++ b/source/blender/blenkernel/intern/library_query.c @@ -512,7 +512,8 @@ void BKE_library_foreach_ID_link(Main *bmain, ID *id, LibraryIDLinkCallback call /* Object is special, proxies make things hard... */ const int data_cb_flag = data.cb_flag; - const int proxy_cb_flag = (object->proxy || object->proxy_group) ? IDWALK_CB_INDIRECT_USAGE : 0; + const int proxy_cb_flag = ((data.flag & IDWALK_NO_INDIRECT_PROXY_DATA_USAGE) == 0 && (object->proxy || object->proxy_group)) ? + IDWALK_CB_INDIRECT_USAGE : 0; /* object data special case */ data.cb_flag |= proxy_cb_flag; diff --git a/source/blender/blenkernel/intern/library_remap.c b/source/blender/blenkernel/intern/library_remap.c index 24626c6ead7..f8c193fe108 100644 --- a/source/blender/blenkernel/intern/library_remap.c +++ b/source/blender/blenkernel/intern/library_remap.c @@ -186,8 +186,8 @@ static int foreach_libblock_remap_callback(void *user_data, ID *id_self, ID **id const bool skip_never_null = (id_remap_data->flag & ID_REMAP_SKIP_NEVER_NULL_USAGE) != 0; #ifdef DEBUG_PRINT - printf("In %s: Remapping %s (%p) to %s (%p) (skip_indirect: %d)\n", - id->name, old_id->name, old_id, new_id ? new_id->name : "<NONE>", new_id, skip_indirect); + printf("In %s: Remapping %s (%p) to %s (%p) (is_indirect: %d, skip_indirect: %d)\n", + id->name, old_id->name, old_id, new_id ? new_id->name : "<NONE>", new_id, is_indirect, skip_indirect); #endif if ((id_remap_data->flag & ID_REMAP_FLAG_NEVER_NULL_USAGE) && (cb_flag & IDWALK_CB_NEVER_NULL)) { @@ -201,6 +201,14 @@ static int foreach_libblock_remap_callback(void *user_data, ID *id_self, ID **id { if (is_indirect) { id_remap_data->skipped_indirect++; + if (is_obj) { + Object *ob = (Object *)id; + if (ob->data == *id_p && ob->proxy != NULL) { + /* And another 'Proudly brought to you by Proxy Hell' hack! + * This will allow us to avoid clearing 'LIB_EXTERN' flag of obdata of proxies... */ + id_remap_data->skipped_direct++; + } + } } else if (is_never_null || is_obj_editmode) { id_remap_data->skipped_direct++; @@ -241,7 +249,7 @@ static int foreach_libblock_remap_callback(void *user_data, ID *id_self, ID **id return IDWALK_RET_NOP; } -/* Some reamapping unfortunately require extra and/or specific handling, tackle those here. */ +/* Some remapping unfortunately require extra and/or specific handling, tackle those here. */ static void libblock_remap_data_preprocess_scene_base_unlink( IDRemap *r_id_remap_data, Scene *sce, Base *base, const bool skip_indirect, const bool is_indirect) { @@ -318,7 +326,7 @@ static void libblock_remap_data_preprocess(IDRemap *r_id_remap_data) } } -static void libblock_remap_data_postprocess_object_fromgroup_update(Main *bmain, Object *old_ob, Object *new_ob) +static void libblock_remap_data_postprocess_object_update(Main *bmain, Object *old_ob, Object *new_ob) { if (old_ob->flag & OB_FROMGROUP) { /* Note that for Scene's BaseObject->flag, either we: @@ -337,6 +345,13 @@ static void libblock_remap_data_postprocess_object_fromgroup_update(Main *bmain, new_ob->flag |= OB_FROMGROUP; } } + if (old_ob->type == OB_MBALL) { + for (Object *ob = bmain->object.first; ob; ob = ob->id.next) { + if (ob->type == OB_MBALL && BKE_mball_is_basis_for(ob, old_ob)) { + DAG_id_tag_update(&ob->id, OB_RECALC_DATA); + } + } + } } static void libblock_remap_data_postprocess_group_scene_unlink(Main *UNUSED(bmain), Scene *sce, ID *old_id) @@ -419,6 +434,7 @@ ATTR_NONNULL(1) static void libblock_remap_data( IDRemap id_remap_data; ListBase *lb_array[MAX_LIBARRAY]; int i; + const int foreach_id_flags = (remap_flags & ID_REMAP_NO_INDIRECT_PROXY_DATA_USAGE) != 0 ? IDWALK_NO_INDIRECT_PROXY_DATA_USAGE : IDWALK_NOP; if (r_id_remap_data == NULL) { r_id_remap_data = &id_remap_data; @@ -439,7 +455,7 @@ ATTR_NONNULL(1) static void libblock_remap_data( #endif r_id_remap_data->id = id; libblock_remap_data_preprocess(r_id_remap_data); - BKE_library_foreach_ID_link(NULL, id, foreach_libblock_remap_callback, (void *)r_id_remap_data, IDWALK_NOP); + BKE_library_foreach_ID_link(NULL, id, foreach_libblock_remap_callback, (void *)r_id_remap_data, foreach_id_flags); } else { i = set_listbasepointers(bmain, lb_array); @@ -456,7 +472,7 @@ ATTR_NONNULL(1) static void libblock_remap_data( r_id_remap_data->id = id_curr; libblock_remap_data_preprocess(r_id_remap_data); BKE_library_foreach_ID_link( - NULL, id_curr, foreach_libblock_remap_callback, (void *)r_id_remap_data, IDWALK_NOP); + NULL, id_curr, foreach_libblock_remap_callback, (void *)r_id_remap_data, foreach_id_flags); } } } @@ -546,7 +562,7 @@ void BKE_libblock_remap_locked( */ switch (GS(old_id->name)) { case ID_OB: - libblock_remap_data_postprocess_object_fromgroup_update(bmain, (Object *)old_id, (Object *)new_id); + libblock_remap_data_postprocess_object_update(bmain, (Object *)old_id, (Object *)new_id); break; case ID_GR: if (!new_id) { /* Only affects us in case group was unlinked. */ @@ -656,8 +672,7 @@ void BKE_libblock_relink_ex( switch (GS(old_id->name)) { case ID_OB: { - libblock_remap_data_postprocess_object_fromgroup_update( - bmain, (Object *)old_id, (Object *)new_id); + libblock_remap_data_postprocess_object_update(bmain, (Object *)old_id, (Object *)new_id); break; } case ID_GR: @@ -672,7 +687,7 @@ void BKE_libblock_relink_ex( else { /* No choice but to check whole objects/groups. */ for (Object *ob = bmain->object.first; ob; ob = ob->id.next) { - libblock_remap_data_postprocess_object_fromgroup_update(bmain, ob, NULL); + libblock_remap_data_postprocess_object_update(bmain, ob, NULL); } for (Group *grp = bmain->group.first; grp; grp = grp->id.next) { libblock_remap_data_postprocess_group_scene_unlink(bmain, sce, NULL); @@ -723,38 +738,19 @@ void BKE_libblock_relink_to_newid(ID *id) BKE_library_foreach_ID_link(NULL, id, id_relink_to_newid_looper, NULL, 0); } -void BKE_libblock_free_data(Main *UNUSED(bmain), ID *id, const bool do_id_user) +void BKE_libblock_free_data(ID *id, const bool do_id_user) { if (id->properties) { IDP_FreeProperty_ex(id->properties, do_id_user); MEM_freeN(id->properties); } + + /* XXX TODO remove animdata handling from each type's freeing func, and do it here, like for copy! */ } -/** - * used in headerbuttons.c image.c mesh.c screen.c sound.c and library.c - * - * \param do_id_user: if \a true, try to release other ID's 'references' hold by \a idv. - * (only applies to main database) - * \param do_ui_user: similar to do_id_user but makes sure UI does not hold references to - * \a id. - */ -void BKE_libblock_free_ex(Main *bmain, void *idv, const bool do_id_user, const bool do_ui_user) +void BKE_libblock_free_datablock(ID *id, const int UNUSED(flag)) { - ID *id = idv; - short type = GS(id->name); - ListBase *lb = which_libbase(bmain, type); - - DAG_id_type_tag(bmain, type); - -#ifdef WITH_PYTHON - BPY_id_release(id); -#endif - - if (do_id_user) { - BKE_libblock_relink_ex(bmain, id, NULL, NULL, true); - } - + const short type = GS(id->name); switch (type) { case ID_SCE: BKE_scene_free((Scene *)id); @@ -860,6 +856,117 @@ void BKE_libblock_free_ex(Main *bmain, void *idv, const bool do_id_user, const b BKE_cachefile_free((CacheFile *)id); break; } +} + + +void BKE_id_free_ex(Main *bmain, void *idv, int flag, const bool use_flag_from_idtag) +{ + ID *id = idv; + + if (use_flag_from_idtag) { + if ((id->tag & LIB_TAG_NO_MAIN) != 0) { + flag |= LIB_ID_FREE_NO_MAIN; + } + else { + flag &= ~LIB_ID_FREE_NO_MAIN; + } + + if ((id->tag & LIB_TAG_NO_USER_REFCOUNT) != 0) { + flag |= LIB_ID_FREE_NO_USER_REFCOUNT; + } + else { + flag &= ~LIB_ID_FREE_NO_USER_REFCOUNT; + } + + if ((id->tag & LIB_TAG_NOT_ALLOCATED) != 0) { + flag |= LIB_ID_FREE_NOT_ALLOCATED; + } + else { + flag &= ~LIB_ID_FREE_NOT_ALLOCATED; + } + } + + BLI_assert((flag & LIB_ID_FREE_NO_MAIN) != 0 || bmain != NULL); + BLI_assert((flag & LIB_ID_FREE_NO_MAIN) != 0 || (flag & LIB_ID_FREE_NOT_ALLOCATED) == 0); + BLI_assert((flag & LIB_ID_FREE_NO_MAIN) != 0 || (flag & LIB_ID_FREE_NO_USER_REFCOUNT) == 0); + + const short type = GS(id->name); + + if (bmain && (flag & LIB_ID_FREE_NO_DEG_TAG) == 0) { + DAG_id_type_tag(bmain, type); + } + +#ifdef WITH_PYTHON + BPY_id_release(id); +#endif + + if ((flag & LIB_ID_FREE_NO_USER_REFCOUNT) == 0) { + BKE_libblock_relink_ex(bmain, id, NULL, NULL, true); + } + + BKE_libblock_free_datablock(id, flag); + + /* avoid notifying on removed data */ + if (bmain) { + BKE_main_lock(bmain); + } + + if ((flag & LIB_ID_FREE_NO_UI_USER) == 0) { + if (free_notifier_reference_cb) { + free_notifier_reference_cb(id); + } + + if (remap_editor_id_reference_cb) { + remap_editor_id_reference_cb(id, NULL); + } + } + + if ((flag & LIB_ID_FREE_NO_MAIN) == 0) { + ListBase *lb = which_libbase(bmain, type); + BLI_remlink(lb, id); + } + + BKE_libblock_free_data(id, (flag & LIB_ID_FREE_NO_USER_REFCOUNT) == 0); + + if (bmain) { + BKE_main_unlock(bmain); + } + + if ((flag & LIB_ID_FREE_NOT_ALLOCATED) == 0) { + MEM_freeN(id); + } +} + +void BKE_id_free(Main *bmain, void *idv) +{ + BKE_id_free_ex(bmain, idv, 0, true); +} + +/** + * used in headerbuttons.c image.c mesh.c screen.c sound.c and library.c + * + * \param do_id_user: if \a true, try to release other ID's 'references' hold by \a idv. + * (only applies to main database) + * \param do_ui_user: similar to do_id_user but makes sure UI does not hold references to + * \a id. + */ +void BKE_libblock_free_ex(Main *bmain, void *idv, const bool do_id_user, const bool do_ui_user) +{ + ID *id = idv; + short type = GS(id->name); + ListBase *lb = which_libbase(bmain, type); + + DAG_id_type_tag(bmain, type); + +#ifdef WITH_PYTHON + BPY_id_release(id); +#endif + + if (do_id_user) { + BKE_libblock_relink_ex(bmain, id, NULL, NULL, true); + } + + BKE_libblock_free_datablock(id, 0); /* avoid notifying on removed data */ BKE_main_lock(bmain); @@ -876,7 +983,7 @@ void BKE_libblock_free_ex(Main *bmain, void *idv, const bool do_id_user, const b BLI_remlink(lb, id); - BKE_libblock_free_data(bmain, id, do_id_user); + BKE_libblock_free_data(id, do_id_user); BKE_main_unlock(bmain); MEM_freeN(id); diff --git a/source/blender/blenkernel/intern/linestyle.c b/source/blender/blenkernel/intern/linestyle.c index 1eb909bd9f9..1b1a12e702a 100644 --- a/source/blender/blenkernel/intern/linestyle.c +++ b/source/blender/blenkernel/intern/linestyle.c @@ -119,7 +119,7 @@ FreestyleLineStyle *BKE_linestyle_new(struct Main *bmain, const char *name) { FreestyleLineStyle *linestyle; - linestyle = (FreestyleLineStyle *)BKE_libblock_alloc(bmain, ID_LS, name); + linestyle = (FreestyleLineStyle *)BKE_libblock_alloc(bmain, ID_LS, name, 0); BKE_linestyle_init(linestyle); @@ -155,73 +155,54 @@ void BKE_linestyle_free(FreestyleLineStyle *linestyle) BKE_linestyle_geometry_modifier_remove(linestyle, m); } -FreestyleLineStyle *BKE_linestyle_copy(struct Main *bmain, FreestyleLineStyle *linestyle) +/** + * Only copy internal data of Linestyle ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_linestyle_copy_data( + struct Main *bmain, FreestyleLineStyle *linestyle_dst, const FreestyleLineStyle *linestyle_src, const int flag) { - FreestyleLineStyle *new_linestyle; - LineStyleModifier *m; - int a; + /* We never handle usercount here for own data. */ + const int flag_subdata = flag | LIB_ID_CREATE_NO_USER_REFCOUNT; - new_linestyle = BKE_linestyle_new(bmain, linestyle->id.name + 2); - BKE_linestyle_free(new_linestyle); - - for (a = 0; a < MAX_MTEX; a++) { - if (linestyle->mtex[a]) { - new_linestyle->mtex[a] = MEM_mallocN(sizeof(MTex), "BKE_linestyle_copy"); - memcpy(new_linestyle->mtex[a], linestyle->mtex[a], sizeof(MTex)); - id_us_plus((ID *)new_linestyle->mtex[a]->tex); + for (int a = 0; a < MAX_MTEX; a++) { + if (linestyle_src->mtex[a]) { + linestyle_dst->mtex[a] = MEM_mallocN(sizeof(*linestyle_dst->mtex[a]), __func__); + *linestyle_dst->mtex[a] = *linestyle_src->mtex[a]; } } - if (linestyle->nodetree) { - new_linestyle->nodetree = ntreeCopyTree(bmain, linestyle->nodetree); + if (linestyle_src->nodetree) { + BKE_id_copy_ex(bmain, (ID *)linestyle_src->nodetree, (ID **)&linestyle_dst->nodetree, flag, false); } - new_linestyle->r = linestyle->r; - new_linestyle->g = linestyle->g; - new_linestyle->b = linestyle->b; - new_linestyle->alpha = linestyle->alpha; - new_linestyle->thickness = linestyle->thickness; - new_linestyle->thickness_position = linestyle->thickness_position; - new_linestyle->thickness_ratio = linestyle->thickness_ratio; - new_linestyle->flag = linestyle->flag; - new_linestyle->caps = linestyle->caps; - new_linestyle->chaining = linestyle->chaining; - new_linestyle->rounds = linestyle->rounds; - new_linestyle->split_length = linestyle->split_length; - new_linestyle->min_angle = linestyle->min_angle; - new_linestyle->max_angle = linestyle->max_angle; - new_linestyle->min_length = linestyle->min_length; - new_linestyle->max_length = linestyle->max_length; - new_linestyle->chain_count = linestyle->chain_count; - new_linestyle->split_dash1 = linestyle->split_dash1; - new_linestyle->split_gap1 = linestyle->split_gap1; - new_linestyle->split_dash2 = linestyle->split_dash2; - new_linestyle->split_gap2 = linestyle->split_gap2; - new_linestyle->split_dash3 = linestyle->split_dash3; - new_linestyle->split_gap3 = linestyle->split_gap3; - new_linestyle->dash1 = linestyle->dash1; - new_linestyle->gap1 = linestyle->gap1; - new_linestyle->dash2 = linestyle->dash2; - new_linestyle->gap2 = linestyle->gap2; - new_linestyle->dash3 = linestyle->dash3; - new_linestyle->gap3 = linestyle->gap3; - new_linestyle->panel = linestyle->panel; - new_linestyle->sort_key = linestyle->sort_key; - new_linestyle->integration_type = linestyle->integration_type; - new_linestyle->texstep = linestyle->texstep; - new_linestyle->pr_texture = linestyle->pr_texture; - new_linestyle->use_nodes = linestyle->use_nodes; - for (m = (LineStyleModifier *)linestyle->color_modifiers.first; m; m = m->next) - BKE_linestyle_color_modifier_copy(new_linestyle, m); - for (m = (LineStyleModifier *)linestyle->alpha_modifiers.first; m; m = m->next) - BKE_linestyle_alpha_modifier_copy(new_linestyle, m); - for (m = (LineStyleModifier *)linestyle->thickness_modifiers.first; m; m = m->next) - BKE_linestyle_thickness_modifier_copy(new_linestyle, m); - for (m = (LineStyleModifier *)linestyle->geometry_modifiers.first; m; m = m->next) - BKE_linestyle_geometry_modifier_copy(new_linestyle, m); - - BKE_id_copy_ensure_local(bmain, &linestyle->id, &new_linestyle->id); - - return new_linestyle; + LineStyleModifier *m; + BLI_listbase_clear(&linestyle_dst->color_modifiers); + for (m = (LineStyleModifier *)linestyle_src->color_modifiers.first; m; m = m->next) { + BKE_linestyle_color_modifier_copy(linestyle_dst, m, flag_subdata); + } + BLI_listbase_clear(&linestyle_dst->alpha_modifiers); + for (m = (LineStyleModifier *)linestyle_src->alpha_modifiers.first; m; m = m->next) { + BKE_linestyle_alpha_modifier_copy(linestyle_dst, m, flag_subdata); + } + BLI_listbase_clear(&linestyle_dst->thickness_modifiers); + for (m = (LineStyleModifier *)linestyle_src->thickness_modifiers.first; m; m = m->next) { + BKE_linestyle_thickness_modifier_copy(linestyle_dst, m, flag_subdata); + } + BLI_listbase_clear(&linestyle_dst->geometry_modifiers); + for (m = (LineStyleModifier *)linestyle_src->geometry_modifiers.first; m; m = m->next) { + BKE_linestyle_geometry_modifier_copy(linestyle_dst, m, flag_subdata); + } +} + +FreestyleLineStyle *BKE_linestyle_copy(struct Main *bmain, const FreestyleLineStyle *linestyle) +{ + FreestyleLineStyle *linestyle_copy; + BKE_id_copy_ex(bmain, &linestyle->id, (ID **)&linestyle_copy, 0, false); + return linestyle_copy; } void BKE_linestyle_make_local(struct Main *bmain, FreestyleLineStyle *linestyle, const bool lib_local) @@ -355,7 +336,8 @@ LineStyleModifier *BKE_linestyle_color_modifier_add(FreestyleLineStyle *linestyl return m; } -LineStyleModifier *BKE_linestyle_color_modifier_copy(FreestyleLineStyle *linestyle, LineStyleModifier *m) +LineStyleModifier *BKE_linestyle_color_modifier_copy( + FreestyleLineStyle *linestyle, const LineStyleModifier *m, const int flag) { LineStyleModifier *new_m; @@ -388,9 +370,10 @@ LineStyleModifier *BKE_linestyle_color_modifier_copy(FreestyleLineStyle *linesty { LineStyleColorModifier_DistanceFromObject *p = (LineStyleColorModifier_DistanceFromObject *)m; LineStyleColorModifier_DistanceFromObject *q = (LineStyleColorModifier_DistanceFromObject *)new_m; - if (p->target) - id_us_plus(&p->target->id); q->target = p->target; + if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) { + id_us_plus((ID *)q->target); + } q->color_ramp = MEM_dupallocN(p->color_ramp); q->range_min = p->range_min; q->range_max = p->range_max; @@ -594,7 +577,8 @@ LineStyleModifier *BKE_linestyle_alpha_modifier_add(FreestyleLineStyle *linestyl return m; } -LineStyleModifier *BKE_linestyle_alpha_modifier_copy(FreestyleLineStyle *linestyle, LineStyleModifier *m) +LineStyleModifier *BKE_linestyle_alpha_modifier_copy( + FreestyleLineStyle *linestyle, const LineStyleModifier *m, const int UNUSED(flag)) { LineStyleModifier *new_m; @@ -863,7 +847,8 @@ LineStyleModifier *BKE_linestyle_thickness_modifier_add(FreestyleLineStyle *line return m; } -LineStyleModifier *BKE_linestyle_thickness_modifier_copy(FreestyleLineStyle *linestyle, LineStyleModifier *m) +LineStyleModifier *BKE_linestyle_thickness_modifier_copy( + FreestyleLineStyle *linestyle, const LineStyleModifier *m, const int flag) { LineStyleModifier *new_m; @@ -901,9 +886,10 @@ LineStyleModifier *BKE_linestyle_thickness_modifier_copy(FreestyleLineStyle *lin { LineStyleThicknessModifier_DistanceFromObject *p = (LineStyleThicknessModifier_DistanceFromObject *)m; LineStyleThicknessModifier_DistanceFromObject *q = (LineStyleThicknessModifier_DistanceFromObject *)new_m; - if (p->target) - id_us_plus(&p->target->id); q->target = p->target; + if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) { + id_us_plus((ID *)q->target); + } q->curve = curvemapping_copy(p->curve); q->flags = p->flags; q->range_min = p->range_min; @@ -1195,7 +1181,8 @@ LineStyleModifier *BKE_linestyle_geometry_modifier_add(FreestyleLineStyle *lines return m; } -LineStyleModifier *BKE_linestyle_geometry_modifier_copy(FreestyleLineStyle *linestyle, LineStyleModifier *m) +LineStyleModifier *BKE_linestyle_geometry_modifier_copy( + FreestyleLineStyle *linestyle, const LineStyleModifier *m, const int UNUSED(flag)) { LineStyleModifier *new_m; diff --git a/source/blender/blenkernel/intern/mask.c b/source/blender/blenkernel/intern/mask.c index 6f23b82c6df..435bc949af0 100644 --- a/source/blender/blenkernel/intern/mask.c +++ b/source/blender/blenkernel/intern/mask.c @@ -192,7 +192,7 @@ void BKE_mask_layer_rename(Mask *mask, MaskLayer *masklay, char *oldname, char * BKE_animdata_fix_paths_rename_all(&mask->id, "layers", oldname, masklay->name); } -MaskLayer *BKE_mask_layer_copy(MaskLayer *masklay) +MaskLayer *BKE_mask_layer_copy(const MaskLayer *masklay) { MaskLayer *masklay_new; MaskSpline *spline; @@ -236,7 +236,7 @@ MaskLayer *BKE_mask_layer_copy(MaskLayer *masklay) return masklay_new; } -void BKE_mask_layer_copy_list(ListBase *masklayers_new, ListBase *masklayers) +void BKE_mask_layer_copy_list(ListBase *masklayers_new, const ListBase *masklayers) { MaskLayer *layer; @@ -794,7 +794,7 @@ static Mask *mask_alloc(Main *bmain, const char *name) { Mask *mask; - mask = BKE_libblock_alloc(bmain, ID_MSK, name); + mask = BKE_libblock_alloc(bmain, ID_MSK, name, 0); id_fake_user_set(&mask->id); @@ -821,6 +821,7 @@ Mask *BKE_mask_new(Main *bmain, const char *name) } /* TODO(sergey): Use generic BKE_libblock_copy_nolib() instead. */ +/* TODO(bastien): Use new super cool & generic BKE_id_copy_ex() instead! */ Mask *BKE_mask_copy_nolib(Mask *mask) { Mask *mask_new; @@ -840,22 +841,29 @@ Mask *BKE_mask_copy_nolib(Mask *mask) return mask_new; } -Mask *BKE_mask_copy(Main *bmain, Mask *mask) +/** + * Only copy internal data of Mask ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_mask_copy_data(Main *UNUSED(bmain), Mask *mask_dst, const Mask *mask_src, const int UNUSED(flag)) { - Mask *mask_new; - - mask_new = BKE_libblock_copy(bmain, &mask->id); - - BLI_listbase_clear(&mask_new->masklayers); + BLI_listbase_clear(&mask_dst->masklayers); - BKE_mask_layer_copy_list(&mask_new->masklayers, &mask->masklayers); + BKE_mask_layer_copy_list(&mask_dst->masklayers, &mask_src->masklayers); /* TODO add unused flag to those as well. */ /* enable fake user by default */ - id_fake_user_set(&mask->id); - - BKE_id_copy_ensure_local(bmain, &mask->id, &mask_new->id); + id_fake_user_set(&mask_dst->id); +} - return mask_new; +Mask *BKE_mask_copy(Main *bmain, const Mask *mask) +{ + Mask *mask_copy; + BKE_id_copy_ex(bmain, &mask->id, (ID **)&mask_copy, 0, false); + return mask_copy; } void BKE_mask_make_local(Main *bmain, Mask *mask, const bool lib_local) @@ -906,7 +914,7 @@ void BKE_mask_spline_free_list(ListBase *splines) } } -static MaskSplinePoint *mask_spline_points_copy(MaskSplinePoint *points, int tot_point) +static MaskSplinePoint *mask_spline_points_copy(const MaskSplinePoint *points, int tot_point) { MaskSplinePoint *npoints; int i; @@ -923,7 +931,7 @@ static MaskSplinePoint *mask_spline_points_copy(MaskSplinePoint *points, int tot return npoints; } -MaskSpline *BKE_mask_spline_copy(MaskSpline *spline) +MaskSpline *BKE_mask_spline_copy(const MaskSpline *spline) { MaskSpline *nspline = MEM_callocN(sizeof(MaskSpline), "new spline"); diff --git a/source/blender/blenkernel/intern/material.c b/source/blender/blenkernel/intern/material.c index 54945242fe4..f5be72c6b4d 100644 --- a/source/blender/blenkernel/intern/material.c +++ b/source/blender/blenkernel/intern/material.c @@ -212,50 +212,68 @@ Material *BKE_material_add(Main *bmain, const char *name) { Material *ma; - ma = BKE_libblock_alloc(bmain, ID_MA, name); + ma = BKE_libblock_alloc(bmain, ID_MA, name, 0); BKE_material_init(ma); return ma; } -/* XXX keep synced with next function */ -Material *BKE_material_copy(Main *bmain, Material *ma) +/** + * Only copy internal data of Material ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_material_copy_data(Main *bmain, Material *ma_dst, const Material *ma_src, const int flag) { - Material *man; - int a; - - man = BKE_libblock_copy(bmain, &ma->id); - - id_lib_extern((ID *)man->group); - - for (a = 0; a < MAX_MTEX; a++) { - if (ma->mtex[a]) { - man->mtex[a] = MEM_mallocN(sizeof(MTex), "copymaterial"); - memcpy(man->mtex[a], ma->mtex[a], sizeof(MTex)); - id_us_plus((ID *)man->mtex[a]->tex); + for (int a = 0; a < MAX_MTEX; a++) { + if (ma_src->mtex[a]) { + ma_dst->mtex[a] = MEM_mallocN(sizeof(*ma_dst->mtex[a]), __func__); + *ma_dst->mtex[a] = *ma_src->mtex[a]; } } - - if (ma->ramp_col) man->ramp_col = MEM_dupallocN(ma->ramp_col); - if (ma->ramp_spec) man->ramp_spec = MEM_dupallocN(ma->ramp_spec); - - if (ma->nodetree) { - man->nodetree = ntreeCopyTree(bmain, ma->nodetree); + + if (ma_src->ramp_col) { + ma_dst->ramp_col = MEM_dupallocN(ma_src->ramp_col); + } + if (ma_src->ramp_spec) { + ma_dst->ramp_spec = MEM_dupallocN(ma_src->ramp_spec); } - BKE_previewimg_id_copy(&man->id, &ma->id); + if (ma_src->nodetree) { + BKE_id_copy_ex(bmain, (ID *)ma_src->nodetree, (ID **)&ma_dst->nodetree, flag, false); + } - BLI_listbase_clear(&man->gpumaterial); + if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0) { + BKE_previewimg_id_copy(&ma_dst->id, &ma_src->id); + } + else { + ma_dst->preview = NULL; + } - BKE_id_copy_ensure_local(bmain, &ma->id, &man->id); + BLI_listbase_clear(&ma_dst->gpumaterial); +} - return man; +Material *BKE_material_copy(Main *bmain, const Material *ma) +{ + Material *ma_copy; + BKE_id_copy_ex(bmain, &ma->id, (ID **)&ma_copy, 0, false); + return ma_copy; } /* XXX (see above) material copy without adding to main dbase */ Material *localize_material(Material *ma) { + /* TODO replace with something like + * Material *ma_copy; + * BKE_id_copy_ex(bmain, &ma->id, (ID **)&ma_copy, LIB_ID_COPY_NO_MAIN | LIB_ID_COPY_NO_PREVIEW | LIB_ID_COPY_NO_USER_REFCOUNT, false); + * return ma_copy; + * + * ... Once f*** nodes are fully converted to that too :( */ + Material *man; int a; @@ -343,6 +361,8 @@ Material ***give_matarar_id(ID *id) return &(((Curve *)id)->mat); case ID_MB: return &(((MetaBall *)id)->mat); + default: + break; } return NULL; } @@ -359,6 +379,8 @@ short *give_totcolp_id(ID *id) return &(((Curve *)id)->totcol); case ID_MB: return &(((MetaBall *)id)->totcol); + default: + break; } return NULL; } @@ -378,6 +400,8 @@ static void material_data_index_remove_id(ID *id, short index) case ID_MB: /* meta-elems don't have materials atm */ break; + default: + break; } } @@ -396,6 +420,8 @@ static void material_data_index_clear_id(ID *id) case ID_MB: /* meta-elems don't have materials atm */ break; + default: + break; } } diff --git a/source/blender/blenkernel/intern/mball.c b/source/blender/blenkernel/intern/mball.c index 97033a9555d..dfc49c996b1 100644 --- a/source/blender/blenkernel/intern/mball.c +++ b/source/blender/blenkernel/intern/mball.c @@ -96,33 +96,36 @@ MetaBall *BKE_mball_add(Main *bmain, const char *name) { MetaBall *mb; - mb = BKE_libblock_alloc(bmain, ID_MB, name); + mb = BKE_libblock_alloc(bmain, ID_MB, name, 0); BKE_mball_init(mb); return mb; } -MetaBall *BKE_mball_copy(Main *bmain, MetaBall *mb) +/** + * Only copy internal data of MetaBall ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_mball_copy_data(Main *UNUSED(bmain), MetaBall *mb_dst, const MetaBall *mb_src, const int UNUSED(flag)) { - MetaBall *mbn; - int a; - - mbn = BKE_libblock_copy(bmain, &mb->id); + BLI_duplicatelist(&mb_dst->elems, &mb_src->elems); - BLI_duplicatelist(&mbn->elems, &mb->elems); - - mbn->mat = MEM_dupallocN(mb->mat); - for (a = 0; a < mbn->totcol; a++) { - id_us_plus((ID *)mbn->mat[a]); - } + mb_dst->mat = MEM_dupallocN(mb_src->mat); - mbn->editelems = NULL; - mbn->lastelem = NULL; - - BKE_id_copy_ensure_local(bmain, &mb->id, &mbn->id); + mb_dst->editelems = NULL; + mb_dst->lastelem = NULL; +} - return mbn; +MetaBall *BKE_mball_copy(Main *bmain, const MetaBall *mb) +{ + MetaBall *mb_copy; + BKE_id_copy_ex(bmain, &mb->id, (ID **)&mb_copy, 0, false); + return mb_copy; } void BKE_mball_make_local(Main *bmain, MetaBall *mb, const bool lib_local) @@ -470,7 +473,7 @@ bool BKE_mball_center_bounds(MetaBall *mb, float r_cent[3]) return false; } -void BKE_mball_transform(MetaBall *mb, float mat[4][4]) +void BKE_mball_transform(MetaBall *mb, float mat[4][4], const bool do_props) { MetaElem *me; float quat[4]; @@ -482,14 +485,17 @@ void BKE_mball_transform(MetaBall *mb, float mat[4][4]) for (me = mb->elems.first; me; me = me->next) { mul_m4_v3(mat, &me->x); mul_qt_qtqt(me->quat, quat, me->quat); - me->rad *= scale; - /* hrmf, probably elems shouldn't be - * treating scale differently - campbell */ - if (!MB_TYPE_SIZE_SQUARED(me->type)) { - mul_v3_fl(&me->expx, scale); - } - else { - mul_v3_fl(&me->expx, scale_sqrt); + + if (do_props) { + me->rad *= scale; + /* hrmf, probably elems shouldn't be + * treating scale differently - campbell */ + if (!MB_TYPE_SIZE_SQUARED(me->type)) { + mul_v3_fl(&me->expx, scale); + } + else { + mul_v3_fl(&me->expx, scale_sqrt); + } } } } diff --git a/source/blender/blenkernel/intern/mesh.c b/source/blender/blenkernel/intern/mesh.c index c12890a354e..0d01fe77453 100644 --- a/source/blender/blenkernel/intern/mesh.c +++ b/source/blender/blenkernel/intern/mesh.c @@ -494,53 +494,56 @@ Mesh *BKE_mesh_add(Main *bmain, const char *name) { Mesh *me; - me = BKE_libblock_alloc(bmain, ID_ME, name); + me = BKE_libblock_alloc(bmain, ID_ME, name, 0); BKE_mesh_init(me); return me; } -Mesh *BKE_mesh_copy(Main *bmain, Mesh *me) +/** + * Only copy internal data of Mesh ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_mesh_copy_data(Main *bmain, Mesh *me_dst, const Mesh *me_src, const int flag) { - Mesh *men; - int a; - const int do_tessface = ((me->totface != 0) && (me->totpoly == 0)); /* only do tessface if we have no polys */ - - men = BKE_libblock_copy(bmain, &me->id); - - men->mat = MEM_dupallocN(me->mat); - for (a = 0; a < men->totcol; a++) { - id_us_plus((ID *)men->mat[a]); - } - id_us_plus((ID *)men->texcomesh); + const bool do_tessface = ((me_src->totface != 0) && (me_src->totpoly == 0)); /* only do tessface if we have no polys */ + + me_dst->mat = MEM_dupallocN(me_src->mat); - CustomData_copy(&me->vdata, &men->vdata, CD_MASK_MESH, CD_DUPLICATE, men->totvert); - CustomData_copy(&me->edata, &men->edata, CD_MASK_MESH, CD_DUPLICATE, men->totedge); - CustomData_copy(&me->ldata, &men->ldata, CD_MASK_MESH, CD_DUPLICATE, men->totloop); - CustomData_copy(&me->pdata, &men->pdata, CD_MASK_MESH, CD_DUPLICATE, men->totpoly); + CustomData_copy(&me_src->vdata, &me_dst->vdata, CD_MASK_MESH, CD_DUPLICATE, me_dst->totvert); + CustomData_copy(&me_src->edata, &me_dst->edata, CD_MASK_MESH, CD_DUPLICATE, me_dst->totedge); + CustomData_copy(&me_src->ldata, &me_dst->ldata, CD_MASK_MESH, CD_DUPLICATE, me_dst->totloop); + CustomData_copy(&me_src->pdata, &me_dst->pdata, CD_MASK_MESH, CD_DUPLICATE, me_dst->totpoly); if (do_tessface) { - CustomData_copy(&me->fdata, &men->fdata, CD_MASK_MESH, CD_DUPLICATE, men->totface); + CustomData_copy(&me_src->fdata, &me_dst->fdata, CD_MASK_MESH, CD_DUPLICATE, me_dst->totface); } else { - mesh_tessface_clear_intern(men, false); + mesh_tessface_clear_intern(me_dst, false); } - BKE_mesh_update_customdata_pointers(men, do_tessface); + BKE_mesh_update_customdata_pointers(me_dst, do_tessface); - men->edit_btmesh = NULL; + me_dst->edit_btmesh = NULL; - men->mselect = MEM_dupallocN(men->mselect); - men->bb = MEM_dupallocN(men->bb); + me_dst->mselect = MEM_dupallocN(me_dst->mselect); + me_dst->bb = MEM_dupallocN(me_dst->bb); - if (me->key) { - men->key = BKE_key_copy(bmain, me->key); - men->key->from = (ID *)men; + /* TODO Do we want to add flag to prevent this? */ + if (me_src->key) { + BKE_id_copy_ex(bmain, &me_src->key->id, (ID **)&me_dst->key, flag, false); } +} - BKE_id_copy_ensure_local(bmain, &me->id, &men->id); - - return men; +Mesh *BKE_mesh_copy(Main *bmain, const Mesh *me) +{ + Mesh *me_copy; + BKE_id_copy_ex(bmain, &me->id, (ID **)&me_copy, 0, false); + return me_copy; } BMesh *BKE_mesh_to_bmesh( @@ -1339,7 +1342,7 @@ int BKE_mesh_nurbs_displist_to_mdata( /* this may fail replacing ob->data, be sure to check ob->type */ -void BKE_mesh_from_nurbs_displist(Object *ob, ListBase *dispbase, const bool use_orco_uv) +void BKE_mesh_from_nurbs_displist(Object *ob, ListBase *dispbase, const bool use_orco_uv, const char *obdata_name) { Main *bmain = G.main; Object *ob1; @@ -1366,7 +1369,7 @@ void BKE_mesh_from_nurbs_displist(Object *ob, ListBase *dispbase, const bool use } /* make mesh */ - me = BKE_mesh_add(bmain, "Mesh"); + me = BKE_mesh_add(bmain, obdata_name); me->totvert = totvert; me->totedge = totedge; me->totloop = totloop; @@ -1386,7 +1389,7 @@ void BKE_mesh_from_nurbs_displist(Object *ob, ListBase *dispbase, const bool use BKE_mesh_calc_normals(me); } else { - me = BKE_mesh_add(bmain, "Mesh"); + me = BKE_mesh_add(bmain, obdata_name); DM_to_mesh(dm, me, ob, CD_MASK_MESH, false); } @@ -1398,9 +1401,7 @@ void BKE_mesh_from_nurbs_displist(Object *ob, ListBase *dispbase, const bool use cu->mat = NULL; cu->totcol = 0; - if (ob->data) { - BKE_libblock_free(bmain, ob->data); - } + /* Do not decrement ob->data usercount here, it's done at end of func with BKE_libblock_free_us() call. */ ob->data = me; ob->type = OB_MESH; @@ -1410,11 +1411,14 @@ void BKE_mesh_from_nurbs_displist(Object *ob, ListBase *dispbase, const bool use if (ob1->data == cu) { ob1->type = OB_MESH; + id_us_min((ID *)ob1->data); ob1->data = ob->data; - id_us_plus((ID *)ob->data); + id_us_plus((ID *)ob1->data); } ob1 = ob1->id.next; } + + BKE_libblock_free_us(bmain, cu); } void BKE_mesh_from_nurbs(Object *ob) @@ -1427,7 +1431,7 @@ void BKE_mesh_from_nurbs(Object *ob) disp = ob->curve_cache->disp; } - BKE_mesh_from_nurbs_displist(ob, &disp, use_orco_uv); + BKE_mesh_from_nurbs_displist(ob, &disp, use_orco_uv, cu->id.name); } typedef struct EdgeLink { @@ -2055,6 +2059,12 @@ void BKE_mesh_mselect_active_set(Mesh *me, int index, int type) (me->mselect[me->totselect - 1].type == type)); } +/** + * Compute 'split' (aka loop, or per face corner's) normals. + * + * \param r_lnors_spacearr Allows to get computed loop normal space array. That data, among other things, + * contains 'smooth fan' info, useful e.g. to split geometry along sharp edges... + */ void BKE_mesh_calc_normals_split_ex(Mesh *mesh, MLoopNorSpaceArray *r_lnors_spacearr) { float (*r_loopnors)[3]; @@ -2062,6 +2072,11 @@ void BKE_mesh_calc_normals_split_ex(Mesh *mesh, MLoopNorSpaceArray *r_lnors_spac short (*clnors)[2] = NULL; bool free_polynors = false; + /* Note that we enforce computing clnors when the clnor space array is requested by caller here. + * However, we obviously only use the autosmooth angle threshold only in case autosmooth is enabled. */ + const bool use_split_normals = (r_lnors_spacearr != NULL) || ((mesh->flag & ME_AUTOSMOOTH) != 0); + const float split_angle = (mesh->flag & ME_AUTOSMOOTH) != 0 ? mesh->smoothresh : (float)M_PI; + if (CustomData_has_layer(&mesh->ldata, CD_NORMAL)) { r_loopnors = CustomData_get_layer(&mesh->ldata, CD_NORMAL); memset(r_loopnors, 0, sizeof(float[3]) * mesh->totloop); @@ -2090,7 +2105,7 @@ void BKE_mesh_calc_normals_split_ex(Mesh *mesh, MLoopNorSpaceArray *r_lnors_spac BKE_mesh_normals_loop_split( mesh->mvert, mesh->totvert, mesh->medge, mesh->totedge, mesh->mloop, r_loopnors, mesh->totloop, mesh->mpoly, (const float (*)[3])polynors, mesh->totpoly, - (mesh->flag & ME_AUTOSMOOTH) != 0, mesh->smoothresh, r_lnors_spacearr, clnors, NULL); + use_split_normals, split_angle, r_lnors_spacearr, clnors, NULL); if (free_polynors) { MEM_freeN(polynors); @@ -2122,118 +2137,70 @@ typedef struct SplitFaceNewEdge { /* Detect needed new vertices, and update accordingly loops' vertex indices. * WARNING! Leaves mesh in invalid state. */ static int split_faces_prepare_new_verts( - const Mesh *mesh, MLoopNorSpaceArray *lnors_spacearr, SplitFaceNewVert **new_verts, MemArena *memarena, - bool *r_need_vnors_recalc) + const Mesh *mesh, MLoopNorSpaceArray *lnors_spacearr, SplitFaceNewVert **new_verts, MemArena *memarena) { - /* Note: if lnors_spacearr is NULL, ther is no autosmooth handling, and we only split out flat polys. */ + /* This is now mandatory, trying to do the job in simple way without that data is doomed to fail, even when only + * dealing with smooth/flat faces one can find cases that no simple algorithm can handle properly. */ + BLI_assert(lnors_spacearr != NULL); + const int num_loops = mesh->totloop; int num_verts = mesh->totvert; MVert *mvert = mesh->mvert; MLoop *mloop = mesh->mloop; BLI_bitmap *verts_used = BLI_BITMAP_NEW(num_verts, __func__); + BLI_bitmap *done_loops = BLI_BITMAP_NEW(num_loops, __func__); - if (lnors_spacearr) { - BLI_bitmap *done_loops = BLI_BITMAP_NEW(num_loops, __func__); - - MLoop *ml = mloop; - MLoopNorSpace **lnor_space = lnors_spacearr->lspacearr; - for (int loop_idx = 0; loop_idx < num_loops; loop_idx++, ml++, lnor_space++) { - if (!BLI_BITMAP_TEST(done_loops, loop_idx)) { - const int vert_idx = ml->v; - const bool vert_used = BLI_BITMAP_TEST_BOOL(verts_used, vert_idx); - /* If vert is already used by another smooth fan, we need a new vert for this one. */ - const int new_vert_idx = vert_used ? num_verts++ : vert_idx; - - BLI_assert(*lnor_space); - - if ((*lnor_space)->loops) { - for (LinkNode *lnode = (*lnor_space)->loops; lnode; lnode = lnode->next) { - const int ml_fan_idx = GET_INT_FROM_POINTER(lnode->link); - BLI_BITMAP_ENABLE(done_loops, ml_fan_idx); - if (vert_used) { - mloop[ml_fan_idx].v = new_vert_idx; - } - } - } - else { - /* Single loop in this fan... */ - BLI_BITMAP_ENABLE(done_loops, loop_idx); + MLoop *ml = mloop; + MLoopNorSpace **lnor_space = lnors_spacearr->lspacearr; + + for (int loop_idx = 0; loop_idx < num_loops; loop_idx++, ml++, lnor_space++) { + if (!BLI_BITMAP_TEST(done_loops, loop_idx)) { + const int vert_idx = ml->v; + const bool vert_used = BLI_BITMAP_TEST_BOOL(verts_used, vert_idx); + /* If vert is already used by another smooth fan, we need a new vert for this one. */ + const int new_vert_idx = vert_used ? num_verts++ : vert_idx; + + BLI_assert(*lnor_space); + + if ((*lnor_space)->loops) { + for (LinkNode *lnode = (*lnor_space)->loops; lnode; lnode = lnode->next) { + const int ml_fan_idx = GET_INT_FROM_POINTER(lnode->link); + BLI_BITMAP_ENABLE(done_loops, ml_fan_idx); if (vert_used) { - ml->v = new_vert_idx; + mloop[ml_fan_idx].v = new_vert_idx; } } - - if (!vert_used) { - BLI_BITMAP_ENABLE(verts_used, vert_idx); - /* We need to update that vertex's normal here, we won't go over it again. */ - /* This is important! *DO NOT* set vnor to final computed lnor, vnor should always be defined to - * 'automatic normal' value computed from its polys, not some custom normal. - * Fortunately, that's the loop normal space's 'lnor' reference vector. ;) */ - normal_float_to_short_v3(mvert[vert_idx].no, (*lnor_space)->vec_lnor); - } - else { - /* Add new vert to list. */ - SplitFaceNewVert *new_vert = BLI_memarena_alloc(memarena, sizeof(*new_vert)); - new_vert->orig_index = vert_idx; - new_vert->new_index = new_vert_idx; - new_vert->vnor = (*lnor_space)->vec_lnor; /* See note above. */ - new_vert->next = *new_verts; - *new_verts = new_vert; - } } - } - - MEM_freeN(done_loops); - } - else { - /* No loop normal spaces available, we only split out flat polys. */ - const int num_polys = mesh->totpoly; - const MPoly *mpoly = mesh->mpoly; - - /* We do that in two loops, to keep original edges/verts to smooth polys preferencially. */ - const MPoly *mp = mpoly; - for (int i = 0; i < num_polys; i++, mp++) { - if (mp->flag & ME_SMOOTH) { - const MLoop *ml = &mloop[mp->loopstart]; - for (int j = 0; j < mp->totloop; j++, ml++) { - /* Just mark the vertex as used/reserved, that way neighbor flat polys, if any, - * will have to create their own. */ - BLI_BITMAP_ENABLE(verts_used, ml->v); + else { + /* Single loop in this fan... */ + BLI_BITMAP_ENABLE(done_loops, loop_idx); + if (vert_used) { + ml->v = new_vert_idx; } } - } - mp = mpoly; - for (int i = 0; i < num_polys; i++, mp++) { - if (!(mp->flag & ME_SMOOTH)) { - MLoop *ml = &mloop[mp->loopstart]; - for (int j = 0; j < mp->totloop; j++, ml++) { - const int vert_idx = ml->v; - - if (BLI_BITMAP_TEST(verts_used, vert_idx)) { - /* Add new vert to list. */ - const int new_vert_idx = num_verts++; - ml->v = new_vert_idx; - - SplitFaceNewVert *new_vert = BLI_memarena_alloc(memarena, sizeof(*new_vert)); - new_vert->orig_index = vert_idx; - new_vert->new_index = new_vert_idx; - new_vert->vnor = NULL; /* See note below about normals. */ - new_vert->next = *new_verts; - *new_verts = new_vert; - } - else { - BLI_BITMAP_ENABLE(verts_used, vert_idx); - } - } - /* Note: there is no way to get new normals for smooth vertices here (and we don't have direct access - * to poly normals either for flat ones), so we'll have to recompute all vnors at the end... */ - *r_need_vnors_recalc = true; + if (!vert_used) { + BLI_BITMAP_ENABLE(verts_used, vert_idx); + /* We need to update that vertex's normal here, we won't go over it again. */ + /* This is important! *DO NOT* set vnor to final computed lnor, vnor should always be defined to + * 'automatic normal' value computed from its polys, not some custom normal. + * Fortunately, that's the loop normal space's 'lnor' reference vector. ;) */ + normal_float_to_short_v3(mvert[vert_idx].no, (*lnor_space)->vec_lnor); + } + else { + /* Add new vert to list. */ + SplitFaceNewVert *new_vert = BLI_memarena_alloc(memarena, sizeof(*new_vert)); + new_vert->orig_index = vert_idx; + new_vert->new_index = new_vert_idx; + new_vert->vnor = (*lnor_space)->vec_lnor; /* See note above. */ + new_vert->next = *new_verts; + *new_verts = new_vert; } } } + MEM_freeN(done_loops); MEM_freeN(verts_used); return num_verts - mesh->totvert; @@ -2352,27 +2319,17 @@ void BKE_mesh_split_faces(Mesh *mesh, bool free_loop_normals) } BKE_mesh_tessface_clear(mesh); - MLoopNorSpaceArray *lnors_spacearr = NULL; - MemArena *memarena; - bool need_vnors_recalc = false; - - if (mesh->flag & ME_AUTOSMOOTH) { - lnors_spacearr = MEM_callocN(sizeof(*lnors_spacearr), __func__); - /* Compute loop normals and loop normal spaces (a.k.a. smooth fans of faces around vertices). */ - BKE_mesh_calc_normals_split_ex(mesh, lnors_spacearr); - /* Stealing memarena from loop normals space array. */ - memarena = lnors_spacearr->mem; - } - else { - /* We still have to split out flat faces... */ - memarena = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, __func__); - } + MLoopNorSpaceArray lnors_spacearr = {NULL}; + /* Compute loop normals and loop normal spaces (a.k.a. smooth fans of faces around vertices). */ + BKE_mesh_calc_normals_split_ex(mesh, &lnors_spacearr); + /* Stealing memarena from loop normals space array. */ + MemArena *memarena = lnors_spacearr.mem; SplitFaceNewVert *new_verts = NULL; SplitFaceNewEdge *new_edges = NULL; /* Detect loop normal spaces (a.k.a. smooth fans) that will need a new vert. */ - const int num_new_verts = split_faces_prepare_new_verts(mesh, lnors_spacearr, &new_verts, memarena, &need_vnors_recalc); + const int num_new_verts = split_faces_prepare_new_verts(mesh, &lnors_spacearr, &new_verts, memarena); if (num_new_verts > 0) { /* Reminder: beyond this point, there is no way out, mesh is in invalid state (due to early-reassignment of @@ -2384,9 +2341,9 @@ void BKE_mesh_split_faces(Mesh *mesh, bool free_loop_normals) /* Reallocate all vert and edge related data. */ mesh->totvert += num_new_verts; - mesh->totedge += num_new_edges; CustomData_realloc(&mesh->vdata, mesh->totvert); if (do_edges) { + mesh->totedge += num_new_edges; CustomData_realloc(&mesh->edata, mesh->totedge); } /* Update pointers to a newly allocated memory. */ @@ -2406,18 +2363,9 @@ void BKE_mesh_split_faces(Mesh *mesh, bool free_loop_normals) CustomData_free_layers(&mesh->ldata, CD_NORMAL, mesh->totloop); } - if (lnors_spacearr) { - /* Also frees new_verts/edges temp data, since we used its memarena to allocate them. */ - BKE_lnor_spacearr_free(lnors_spacearr); - MEM_freeN(lnors_spacearr); - } - else { - BLI_memarena_free(memarena); - } + /* Also frees new_verts/edges temp data, since we used its memarena to allocate them. */ + BKE_lnor_spacearr_free(&lnors_spacearr); - if (need_vnors_recalc) { - BKE_mesh_calc_normals(mesh); - } #ifdef VALIDATE_MESH BKE_mesh_validate(mesh, true, true); #endif @@ -2446,7 +2394,9 @@ Mesh *BKE_mesh_new_from_object( int uv_from_orco; /* copies object and modifiers (but not the data) */ - Object *tmpobj = BKE_object_copy_ex(bmain, ob, true); + Object *tmpobj; + /* TODO: make it temp copy outside bmain! */ + BKE_id_copy_ex(bmain, &ob->id, (ID **)&tmpobj, LIB_ID_COPY_CACHES, false); tmpcu = (Curve *)tmpobj->data; id_us_min(&tmpcu->id); @@ -2486,7 +2436,7 @@ Mesh *BKE_mesh_new_from_object( /* convert object type to mesh */ uv_from_orco = (tmpcu->flag & CU_UV_ORCO) != 0; - BKE_mesh_from_nurbs_displist(tmpobj, &dispbase, uv_from_orco); + BKE_mesh_from_nurbs_displist(tmpobj, &dispbase, uv_from_orco, tmpcu->id.name + 2); tmpmesh = tmpobj->data; @@ -2522,7 +2472,7 @@ Mesh *BKE_mesh_new_from_object( if (ob != basis_ob) return NULL; /* only do basis metaball */ - tmpmesh = BKE_mesh_add(bmain, "Mesh"); + tmpmesh = BKE_mesh_add(bmain, ((ID *)ob->data)->name + 2); /* BKE_mesh_add gives us a user count we don't need */ id_us_min(&tmpmesh->id); @@ -2577,7 +2527,7 @@ Mesh *BKE_mesh_new_from_object( else dm = mesh_create_derived_view(sce, ob, mask); - tmpmesh = BKE_mesh_add(bmain, "Mesh"); + tmpmesh = BKE_mesh_add(bmain, ((ID *)ob->data)->name + 2); DM_to_mesh(dm, tmpmesh, ob, mask, true); /* Copy autosmooth settings from original mesh. */ diff --git a/source/blender/blenkernel/intern/mesh_evaluate.c b/source/blender/blenkernel/intern/mesh_evaluate.c index 37f4477febf..643ca3ee536 100644 --- a/source/blender/blenkernel/intern/mesh_evaluate.c +++ b/source/blender/blenkernel/intern/mesh_evaluate.c @@ -1629,8 +1629,8 @@ void BKE_mesh_normals_loop_custom_from_vertices_set( /** * Computes average per-vertex normals from given custom loop normals. * - * @param clnors The computed custom loop normals. - * @param r_vert_clnors The (already allocated) array where to store averaged per-vertex normals. + * \param clnors: The computed custom loop normals. + * \param r_vert_clnors: The (already allocated) array where to store averaged per-vertex normals. */ void BKE_mesh_normals_loop_to_vertex( const int numVerts, const MLoop *mloops, const int numLoops, @@ -2002,11 +2002,14 @@ float BKE_mesh_calc_poly_area( * - http://forums.cgsociety.org/archive/index.php?t-756235.html * - http://www.globalspec.com/reference/52702/203279/4-8-the-centroid-of-a-tetrahedron * - * \note volume is 6x actual volume, and centroid is 4x actual volume-weighted centroid - * (so division can be done once at the end) - * \note results will have bias if polygon is non-planar. + * \note + * - Volume is 6x actual volume, and centroid is 4x actual volume-weighted centroid + * (so division can be done once at the end). + * - Results will have bias if polygon is non-planar. + * - The resulting volume will only be correct if the mesh is manifold and has consistent face winding + * (non-contiguous face normals or holes in the mesh surface). */ -static float mesh_calc_poly_volume_and_weighted_centroid( +static float mesh_calc_poly_volume_centroid( const MPoly *mpoly, const MLoop *loopstart, const MVert *mvarray, float r_cent[3]) { @@ -2043,6 +2046,43 @@ static float mesh_calc_poly_volume_and_weighted_centroid( return total_volume; } +/** + * \note + * - Results won't be correct if polygon is non-planar. + * - This has the advantage over #mesh_calc_poly_volume_centroid + * that it doesn't depend on solid geometry, instead it weights the surface by volume. + */ +static float mesh_calc_poly_area_centroid( + const MPoly *mpoly, const MLoop *loopstart, const MVert *mvarray, + float r_cent[3]) +{ + int i; + float tri_area; + float total_area = 0.0f; + float v1[3], v2[3], v3[3], normal[3], tri_cent[3]; + + BKE_mesh_calc_poly_normal(mpoly, loopstart, mvarray, normal); + copy_v3_v3(v1, mvarray[loopstart[0].v].co); + copy_v3_v3(v2, mvarray[loopstart[1].v].co); + zero_v3(r_cent); + + for (i = 2; i < mpoly->totloop; i++) { + copy_v3_v3(v3, mvarray[loopstart[i].v].co); + + tri_area = area_tri_signed_v3(v1, v2, v3, normal); + total_area += tri_area; + + mid_v3_v3v3v3(tri_cent, v1, v2, v3); + madd_v3_v3fl(r_cent, tri_cent, tri_area); + + copy_v3_v3(v2, v3); + } + + mul_v3_fl(r_cent, 1.0f / total_area); + + return total_area; +} + #if 0 /* slow version of the function below */ void BKE_mesh_calc_poly_angles(MPoly *mpoly, MLoop *loopstart, MVert *mvarray, float angles[]) @@ -2157,7 +2197,40 @@ bool BKE_mesh_center_bounds(const Mesh *me, float r_cent[3]) return false; } -bool BKE_mesh_center_centroid(const Mesh *me, float r_cent[3]) +bool BKE_mesh_center_of_surface(const Mesh *me, float r_cent[3]) +{ + int i = me->totpoly; + MPoly *mpoly; + float poly_area; + float total_area = 0.0f; + float poly_cent[3]; + + zero_v3(r_cent); + + /* calculate a weighted average of polygon centroids */ + for (mpoly = me->mpoly; i--; mpoly++) { + poly_area = mesh_calc_poly_area_centroid(mpoly, me->mloop + mpoly->loopstart, me->mvert, poly_cent); + + madd_v3_v3fl(r_cent, poly_cent, poly_area); + total_area += poly_area; + } + /* otherwise we get NAN for 0 polys */ + if (me->totpoly) { + mul_v3_fl(r_cent, 1.0f / total_area); + } + + /* zero area faces cause this, fallback to median */ + if (UNLIKELY(!is_finite_v3(r_cent))) { + return BKE_mesh_center_median(me, r_cent); + } + + return (me->totpoly != 0); +} + +/** + * \note Mesh must be manifold with consistent face-winding, see #mesh_calc_poly_volume_centroid for details. + */ +bool BKE_mesh_center_of_volume(const Mesh *me, float r_cent[3]) { int i = me->totpoly; MPoly *mpoly; @@ -2169,7 +2242,7 @@ bool BKE_mesh_center_centroid(const Mesh *me, float r_cent[3]) /* calculate a weighted average of polyhedron centroids */ for (mpoly = me->mpoly; i--; mpoly++) { - poly_volume = mesh_calc_poly_volume_and_weighted_centroid(mpoly, me->mloop + mpoly->loopstart, me->mvert, poly_cent); + poly_volume = mesh_calc_poly_volume_centroid(mpoly, me->mloop + mpoly->loopstart, me->mvert, poly_cent); /* poly_cent is already volume-weighted, so no need to multiply by the volume */ add_v3_v3(r_cent, poly_cent); @@ -2189,6 +2262,7 @@ bool BKE_mesh_center_centroid(const Mesh *me, float r_cent[3]) return (me->totpoly != 0); } + /** \} */ diff --git a/source/blender/blenkernel/intern/mesh_mapping.c b/source/blender/blenkernel/intern/mesh_mapping.c index 8562988b5e1..525c0c9728e 100644 --- a/source/blender/blenkernel/intern/mesh_mapping.c +++ b/source/blender/blenkernel/intern/mesh_mapping.c @@ -165,7 +165,7 @@ UvVertMap *BKE_mesh_uv_vert_map_create( vmap->vert[a] = newvlist; } - if (use_winding) { + if (use_winding) { MEM_freeN(winding); } diff --git a/source/blender/blenkernel/intern/mesh_remap.c b/source/blender/blenkernel/intern/mesh_remap.c index c5fa9b15896..d2fe8f27f4a 100644 --- a/source/blender/blenkernel/intern/mesh_remap.c +++ b/source/blender/blenkernel/intern/mesh_remap.c @@ -1184,7 +1184,6 @@ void BKE_mesh_remap_calc_loops_from_dm( bool polys_allocated_src; MPoly *polys_src = DM_get_poly_array(dm_src, &polys_allocated_src); const int num_polys_src = dm_src->getNumPolys(dm_src); - bool looptri_allocated_src = false; const MLoopTri *looptri_src = NULL; int num_looptri_src = 0; @@ -1374,17 +1373,11 @@ void BKE_mesh_remap_calc_loops_from_dm( if (dirty_tess_flag) { dm_src->dirty &= ~dirty_tess_flag; } - DM_ensure_looptri(dm_src); if (dirty_tess_flag) { dm_src->dirty |= dirty_tess_flag; } - looptri_src = DM_get_looptri_array( - dm_src, - verts_src, - polys_src, num_polys_src, - loops_src, num_loops_src, - &looptri_allocated_src); + looptri_src = dm_src->getLoopTriArray(dm_src); num_looptri_src = dm_src->getNumLoopTri(dm_src); looptri_active = BLI_BITMAP_NEW((size_t)num_looptri_src, __func__); @@ -1403,7 +1396,7 @@ void BKE_mesh_remap_calc_loops_from_dm( &treedata[tindex], verts_src, verts_allocated_src, loops_src, loops_allocated_src, - looptri_src, num_looptri_src, looptri_allocated_src, + looptri_src, num_looptri_src, false, looptri_active, num_looptri_active, bvh_epsilon, 2, 6); if (verts_allocated_src) { verts_allocated_src = false; /* Only 'give' our verts once, to first tree! */ @@ -1411,9 +1404,6 @@ void BKE_mesh_remap_calc_loops_from_dm( if (loops_allocated_src) { loops_allocated_src = false; /* Only 'give' our loops once, to first tree! */ } - if (looptri_allocated_src) { - looptri_allocated_src = false; /* Only 'give' our looptri once, to first tree! */ - } } MEM_freeN(looptri_active); @@ -1928,9 +1918,6 @@ void BKE_mesh_remap_calc_loops_from_dm( if (polys_allocated_src) { MEM_freeN(polys_src); } - if (looptri_allocated_src) { - MEM_freeN((void *)looptri_src); - } if (vert_to_loop_map_src) { MEM_freeN(vert_to_loop_map_src); } diff --git a/source/blender/blenkernel/intern/modifier.c b/source/blender/blenkernel/intern/modifier.c index 2276d56b9c6..118bafa94d2 100644 --- a/source/blender/blenkernel/intern/modifier.c +++ b/source/blender/blenkernel/intern/modifier.c @@ -59,6 +59,8 @@ #include "BKE_appdir.h" #include "BKE_key.h" +#include "BKE_library.h" +#include "BKE_library_query.h" #include "BKE_multires.h" #include "BKE_DerivedMesh.h" @@ -269,14 +271,37 @@ void modifier_copyData_generic(const ModifierData *md_src, ModifierData *md_dst) memcpy(md_dst_data, md_src_data, (size_t)mti->structSize - data_size); } -void modifier_copyData(ModifierData *md, ModifierData *target) +static void modifier_copy_data_id_us_cb(void *UNUSED(userData), Object *UNUSED(ob), ID **idpoin, int cb_flag) +{ + ID *id = *idpoin; + if (id != NULL && (cb_flag & IDWALK_CB_USER) != 0) { + id_us_plus(id); + } +} + +void modifier_copyData_ex(ModifierData *md, ModifierData *target, const int flag) { const ModifierTypeInfo *mti = modifierType_getInfo(md->type); target->mode = md->mode; - if (mti->copyData) + if (mti->copyData) { mti->copyData(md, target); + } + + if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) { + if (mti->foreachIDLink) { + mti->foreachIDLink(target, NULL, modifier_copy_data_id_us_cb, NULL); + } + else if (mti->foreachObjectLink) { + mti->foreachObjectLink(target, NULL, (ObjectWalkFunc)modifier_copy_data_id_us_cb, NULL); + } + } +} + +void modifier_copyData(ModifierData *md, ModifierData *target) +{ + modifier_copyData_ex(md, target, 0); } diff --git a/source/blender/blenkernel/intern/movieclip.c b/source/blender/blenkernel/intern/movieclip.c index 6794a8e8f93..16d597e25fa 100644 --- a/source/blender/blenkernel/intern/movieclip.c +++ b/source/blender/blenkernel/intern/movieclip.c @@ -588,7 +588,7 @@ static MovieClip *movieclip_alloc(Main *bmain, const char *name) { MovieClip *clip; - clip = BKE_libblock_alloc(bmain, ID_MC, name); + clip = BKE_libblock_alloc(bmain, ID_MC, name, 0); clip->aspx = clip->aspy = 1.0f; @@ -1488,25 +1488,33 @@ void BKE_movieclip_free(MovieClip *clip) BKE_animdata_free((ID *) clip, false); } -MovieClip *BKE_movieclip_copy(Main *bmain, MovieClip *clip) +/** + * Only copy internal data of MovieClip ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_movieclip_copy_data(Main *UNUSED(bmain), MovieClip *clip_dst, const MovieClip *clip_src, const int flag) { - MovieClip *clip_new; - - clip_new = BKE_libblock_copy(bmain, &clip->id); + /* We never handle usercount here for own data. */ + const int flag_subdata = flag | LIB_ID_CREATE_NO_USER_REFCOUNT; - clip_new->anim = NULL; - clip_new->cache = NULL; + clip_dst->anim = NULL; + clip_dst->cache = NULL; - BKE_tracking_copy(&clip_new->tracking, &clip->tracking); - clip_new->tracking_context = NULL; + BKE_tracking_copy(&clip_dst->tracking, &clip_src->tracking, flag_subdata); + clip_dst->tracking_context = NULL; - id_us_plus((ID *)clip_new->gpd); - - BKE_color_managed_colorspace_settings_copy(&clip_new->colorspace_settings, &clip->colorspace_settings); - - BKE_id_copy_ensure_local(bmain, &clip->id, &clip_new->id); + BKE_color_managed_colorspace_settings_copy(&clip_dst->colorspace_settings, &clip_src->colorspace_settings); +} - return clip_new; +MovieClip *BKE_movieclip_copy(Main *bmain, const MovieClip *clip) +{ + MovieClip *clip_copy; + BKE_id_copy_ex(bmain, &clip->id, (ID **)&clip_copy, 0, false); + return clip_copy; } void BKE_movieclip_make_local(Main *bmain, MovieClip *clip, const bool lib_local) diff --git a/source/blender/blenkernel/intern/node.c b/source/blender/blenkernel/intern/node.c index 63da1b5f9e7..54afe76ec07 100644 --- a/source/blender/blenkernel/intern/node.c +++ b/source/blender/blenkernel/intern/node.c @@ -902,80 +902,100 @@ bNode *nodeAddStaticNode(const struct bContext *C, bNodeTree *ntree, int type) return nodeAddNode(C, ntree, idname); } -static void node_socket_copy(bNodeSocket *dst, bNodeSocket *src) +static void node_socket_copy(bNodeSocket *sock_dst, bNodeSocket *sock_src, const int flag) { - src->new_sock = dst; - - if (src->prop) - dst->prop = IDP_CopyProperty(src->prop); - - if (src->default_value) - dst->default_value = MEM_dupallocN(src->default_value); - - dst->stack_index = 0; + sock_src->new_sock = sock_dst; + + if (sock_src->prop) { + sock_dst->prop = IDP_CopyProperty_ex(sock_src->prop, flag); + } + + if (sock_src->default_value) { + sock_dst->default_value = MEM_dupallocN(sock_src->default_value); + } + + sock_dst->stack_index = 0; /* XXX some compositor node (e.g. image, render layers) still store * some persistent buffer data here, need to clear this to avoid dangling pointers. */ - dst->cache = NULL; + sock_dst->cache = NULL; } /* keep socket listorder identical, for copying links */ /* ntree is the target tree */ -bNode *nodeCopyNode(struct bNodeTree *ntree, struct bNode *node) +bNode *BKE_node_copy_ex(bNodeTree *ntree, bNode *node_src, const int flag) { - bNode *nnode = MEM_callocN(sizeof(bNode), "dupli node"); - bNodeSocket *sock, *oldsock; - bNodeLink *link, *oldlink; + bNode *node_dst = MEM_callocN(sizeof(bNode), "dupli node"); + bNodeSocket *sock_dst, *sock_src; + bNodeLink *link_dst, *link_src; - *nnode = *node; + *node_dst = *node_src; /* can be called for nodes outside a node tree (e.g. clipboard) */ if (ntree) { - nodeUniqueName(ntree, nnode); + nodeUniqueName(ntree, node_dst); - BLI_addtail(&ntree->nodes, nnode); + BLI_addtail(&ntree->nodes, node_dst); } - BLI_duplicatelist(&nnode->inputs, &node->inputs); - oldsock = node->inputs.first; - for (sock = nnode->inputs.first; sock; sock = sock->next, oldsock = oldsock->next) - node_socket_copy(sock, oldsock); - - BLI_duplicatelist(&nnode->outputs, &node->outputs); - oldsock = node->outputs.first; - for (sock = nnode->outputs.first; sock; sock = sock->next, oldsock = oldsock->next) - node_socket_copy(sock, oldsock); - - if (node->prop) - nnode->prop = IDP_CopyProperty(node->prop); - - 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; + BLI_duplicatelist(&node_dst->inputs, &node_src->inputs); + for (sock_dst = node_dst->inputs.first, sock_src = node_src->inputs.first; + sock_dst != NULL; + sock_dst = sock_dst->next, sock_src = sock_src->next) + { + node_socket_copy(sock_dst, sock_src, flag); } - - /* don't increase node->id users, freenode doesn't decrement either */ - - if (node->typeinfo->copyfunc) - node->typeinfo->copyfunc(ntree, nnode, node); - - node->new_node = nnode; - nnode->new_node = NULL; - - if (nnode->typeinfo->copyfunc_api) { + + BLI_duplicatelist(&node_dst->outputs, &node_src->outputs); + for (sock_dst = node_dst->outputs.first, sock_src = node_src->outputs.first; + sock_dst != NULL; + sock_dst = sock_dst->next, sock_src = sock_src->next) + { + node_socket_copy(sock_dst, sock_src, flag); + } + + if (node_src->prop) { + node_dst->prop = IDP_CopyProperty_ex(node_src->prop, flag); + } + + BLI_duplicatelist(&node_dst->internal_links, &node_src->internal_links); + for (link_dst = node_dst->internal_links.first, link_src = node_src->internal_links.first; + link_dst != NULL; + link_dst = link_dst->next, link_src = link_src->next) + { + link_dst->fromnode = node_dst; + link_dst->tonode = node_dst; + link_dst->fromsock = link_dst->fromsock->new_sock; + link_dst->tosock = link_dst->tosock->new_sock; + } + + if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) { + id_us_plus(node_dst->id); + } + + if (node_src->typeinfo->copyfunc) { + node_src->typeinfo->copyfunc(ntree, node_dst, node_src); + } + + node_src->new_node = node_dst; + node_dst->new_node = NULL; + + if (node_dst->typeinfo->copyfunc_api) { PointerRNA ptr; - RNA_pointer_create((ID *)ntree, &RNA_Node, nnode, &ptr); - - nnode->typeinfo->copyfunc_api(&ptr, node); + RNA_pointer_create((ID *)ntree, &RNA_Node, node_dst, &ptr); + + node_dst->typeinfo->copyfunc_api(&ptr, node_src); } - - if (ntree) + + if (ntree) { ntree->update |= NTREE_UPDATE_NODES; - - return nnode; + } + + return node_dst; +} + +bNode *nodeCopyNode(bNodeTree *ntree, bNode *node) +{ + return BKE_node_copy_ex(ntree, node, LIB_ID_CREATE_NO_USER_REFCOUNT); } /* also used via rna api, so we check for proper input output direction */ @@ -1172,7 +1192,7 @@ bNodeTree *ntreeAddTree(Main *bmain, const char *name, const char *idname) * node groups and other tree types are created as library data. */ if (bmain) { - ntree = BKE_libblock_alloc(bmain, ID_NT, name); + ntree = BKE_libblock_alloc(bmain, ID_NT, name, 0); } else { ntree = MEM_callocN(sizeof(bNodeTree), "new node tree"); @@ -1191,119 +1211,98 @@ bNodeTree *ntreeAddTree(Main *bmain, const char *name, const char *idname) return ntree; } -/* Warning: this function gets called during some rather unexpected times - * - this gets called when executing compositing updates (for threaded previews) - * - when the nodetree datablock needs to be copied (i.e. when users get copied) - * - for scene duplication use ntreeSwapID() after so we don't have stale pointers. +/** + * Only copy internal data of NodeTree ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. * - * do_make_extern: keep enabled for general use, only reason _not_ to enable is when - * copying for internal use (threads for eg), where you wont want it to modify the - * scene data. + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). */ -static bNodeTree *ntreeCopyTree_internal(bNodeTree *ntree, Main *bmain, bool skip_database, bool do_id_user, bool do_make_extern, bool copy_previews) +void BKE_node_tree_copy_data(Main *UNUSED(bmain), bNodeTree *ntree_dst, const bNodeTree *ntree_src, const int flag) { - bNodeTree *newtree; - bNode *node /*, *nnode */ /* UNUSED */, *last; - bNodeSocket *sock, *oldsock; - bNodeLink *link; - - if (ntree == NULL) return NULL; - - /* is ntree part of library? */ - if (bmain && !skip_database && BLI_findindex(&bmain->nodetree, ntree) >= 0) { - newtree = BKE_libblock_copy(bmain, &ntree->id); - } - else { - newtree = BKE_libblock_copy_nolib(&ntree->id, true); - } + bNodeSocket *sock_dst, *sock_src; + bNodeLink *link_dst; - id_us_plus((ID *)newtree->gpd); + /* We never handle usercount here for own data. */ + const int flag_subdata = flag | LIB_ID_CREATE_NO_USER_REFCOUNT; /* in case a running nodetree is copied */ - newtree->execdata = NULL; - - newtree->duplilock = NULL; - - BLI_listbase_clear(&newtree->nodes); - BLI_listbase_clear(&newtree->links); - - last = ntree->nodes.last; - for (node = ntree->nodes.first; node; node = node->next) { + ntree_dst->execdata = NULL; - /* ntreeUserDecrefID inline */ - if (do_id_user) { - id_us_plus(node->id); - } + ntree_dst->duplilock = NULL; - if (do_make_extern) { - id_lib_extern(node->id); - } + BLI_listbase_clear(&ntree_dst->nodes); + BLI_listbase_clear(&ntree_dst->links); - node->new_node = NULL; - /* nnode = */ nodeCopyNode(newtree, node); /* sets node->new */ - - /* make sure we don't copy new nodes again! */ - if (node == last) - break; + for (bNode *node_src = ntree_src->nodes.first; node_src; node_src = node_src->next) { + BKE_node_copy_ex(ntree_dst, node_src, flag_subdata); } - + /* copy links */ - BLI_duplicatelist(&newtree->links, &ntree->links); - for (link = newtree->links.first; link; link = link->next) { - link->fromnode = (link->fromnode ? link->fromnode->new_node : NULL); - link->fromsock = (link->fromsock ? link->fromsock->new_sock : NULL); - link->tonode = (link->tonode ? link->tonode->new_node : NULL); - link->tosock = (link->tosock ? link->tosock->new_sock : NULL); + BLI_duplicatelist(&ntree_dst->links, &ntree_src->links); + for (link_dst = ntree_dst->links.first; link_dst; link_dst = link_dst->next) { + link_dst->fromnode = (link_dst->fromnode ? link_dst->fromnode->new_node : NULL); + link_dst->fromsock = (link_dst->fromsock ? link_dst->fromsock->new_sock : NULL); + link_dst->tonode = (link_dst->tonode ? link_dst->tonode->new_node : NULL); + link_dst->tosock = (link_dst->tosock ? link_dst->tosock->new_sock : NULL); /* update the link socket's pointer */ - if (link->tosock) - link->tosock->link = link; + if (link_dst->tosock) { + link_dst->tosock->link = link_dst; + } } - + /* copy interface sockets */ - BLI_duplicatelist(&newtree->inputs, &ntree->inputs); - oldsock = ntree->inputs.first; - for (sock = newtree->inputs.first; sock; sock = sock->next, oldsock = oldsock->next) - node_socket_copy(sock, oldsock); - - BLI_duplicatelist(&newtree->outputs, &ntree->outputs); - oldsock = ntree->outputs.first; - for (sock = newtree->outputs.first; sock; sock = sock->next, oldsock = oldsock->next) - node_socket_copy(sock, oldsock); - + BLI_duplicatelist(&ntree_dst->inputs, &ntree_src->inputs); + for (sock_dst = ntree_dst->inputs.first, sock_src = ntree_src->inputs.first; + sock_dst != NULL; + sock_dst = sock_dst->next, sock_src = sock_src->next) + { + node_socket_copy(sock_dst, sock_src, flag_subdata); + } + + BLI_duplicatelist(&ntree_dst->outputs, &ntree_src->outputs); + for (sock_dst = ntree_dst->outputs.first, sock_src = ntree_src->outputs.first; + sock_dst != NULL; + sock_dst = sock_dst->next, sock_src = sock_src->next) + { + node_socket_copy(sock_dst, sock_src, flag_subdata); + } + /* copy preview hash */ - if (ntree->previews && copy_previews) { + if (ntree_src->previews && (flag & LIB_ID_COPY_NO_PREVIEW) == 0) { bNodeInstanceHashIterator iter; - - newtree->previews = BKE_node_instance_hash_new("node previews"); - - NODE_INSTANCE_HASH_ITER(iter, ntree->previews) { + + ntree_dst->previews = BKE_node_instance_hash_new("node previews"); + + NODE_INSTANCE_HASH_ITER(iter, ntree_src->previews) { bNodeInstanceKey key = BKE_node_instance_hash_iterator_get_key(&iter); bNodePreview *preview = BKE_node_instance_hash_iterator_get_value(&iter); - BKE_node_instance_hash_insert(newtree->previews, key, BKE_node_preview_copy(preview)); + BKE_node_instance_hash_insert(ntree_dst->previews, key, BKE_node_preview_copy(preview)); } } - else - newtree->previews = NULL; - + else { + ntree_dst->previews = NULL; + } + /* update node->parent pointers */ - for (node = newtree->nodes.first; node; node = node->next) { - if (node->parent) - node->parent = node->parent->new_node; + for (bNode *node_dst = ntree_dst->nodes.first, *node_src = ntree_src->nodes.first; node_dst; node_dst = node_dst->next, node_src = node_src->next) { + if (node_dst->parent) { + node_dst->parent = node_dst->parent->new_node; + } } - - /* node tree will generate its own interface type */ - newtree->interface_type = NULL; - - BKE_id_copy_ensure_local(bmain, &ntree->id, &newtree->id); - return newtree; + /* node tree will generate its own interface type */ + ntree_dst->interface_type = NULL; } -bNodeTree *ntreeCopyTree_ex(bNodeTree *ntree, Main *bmain, const bool do_id_user) +bNodeTree *ntreeCopyTree_ex(const bNodeTree *ntree, Main *bmain, const bool do_id_user) { - return ntreeCopyTree_internal(ntree, bmain, false, do_id_user, true, true); + bNodeTree *ntree_copy; + BKE_id_copy_ex(bmain, (ID *)ntree, (ID **)&ntree_copy, do_id_user ? 0 : LIB_ID_CREATE_NO_USER_REFCOUNT, false); + return ntree_copy; } -bNodeTree *ntreeCopyTree(Main *bmain, bNodeTree *ntree) +bNodeTree *ntreeCopyTree(Main *bmain, const bNodeTree *ntree) { return ntreeCopyTree_ex(ntree, bmain, true); } @@ -1698,11 +1697,12 @@ static void node_free_node_ex(bNodeTree *ntree, bNode *node, bool remove_animdat ntreeTexEndExecTree(ntree->execdata); ntree->execdata = NULL; } - - if (node->typeinfo->freefunc) - node->typeinfo->freefunc(node); } - + + if (node->typeinfo->freefunc) { + node->typeinfo->freefunc(node); + } + for (sock = node->inputs.first; sock; sock = nextsock) { nextsock = sock->next; node_socket_free(ntree, sock, node); @@ -1828,7 +1828,7 @@ void ntreeFreeTree(bNodeTree *ntree) if (tntree == ntree) break; if (tntree == NULL) { - BKE_libblock_free_data(G.main, &ntree->id, true); + BKE_libblock_free_data(&ntree->id, true); } } @@ -1991,10 +1991,11 @@ bNodeTree *ntreeLocalize(bNodeTree *ntree) adt->tmpact = NULL; } - /* Make full copy. + /* Make full copy outside of Main database. * Note: previews are not copied here. */ - ltree = ntreeCopyTree_internal(ntree, G.main, true, false, false, false); + BKE_id_copy_ex(G.main, (ID *)ntree, (ID **)<ree, + LIB_ID_CREATE_NO_MAIN | LIB_ID_CREATE_NO_USER_REFCOUNT | LIB_ID_COPY_NO_PREVIEW, false); ltree->flag |= NTREE_IS_LOCALIZED; for (node = ltree->nodes.first; node; node = node->next) { @@ -2234,7 +2235,7 @@ static void ntree_interface_type_create(bNodeTree *ntree) /* register a subtype of PropertyGroup */ srna = RNA_def_struct_ptr(&BLENDER_RNA, identifier, &RNA_PropertyGroup); RNA_def_struct_ui_text(srna, name, description); - RNA_def_struct_duplicate_pointers(srna); + RNA_def_struct_duplicate_pointers(&BLENDER_RNA, srna); /* associate the RNA type with the node tree */ ntree->interface_type = srna; @@ -2273,10 +2274,10 @@ StructRNA *ntreeInterfaceTypeGet(bNodeTree *ntree, int create) ntree_interface_identifier(ntree, base, identifier, sizeof(identifier), name, description); /* rename the RNA type */ - RNA_def_struct_free_pointers(srna); - RNA_def_struct_identifier(srna, identifier); + RNA_def_struct_free_pointers(&BLENDER_RNA, srna); + RNA_def_struct_identifier(&BLENDER_RNA, srna, identifier); RNA_def_struct_ui_text(srna, name, description); - RNA_def_struct_duplicate_pointers(srna); + RNA_def_struct_duplicate_pointers(&BLENDER_RNA, srna); } } else if (create) { @@ -3172,12 +3173,20 @@ void nodeSynchronizeID(bNode *node, bool copy_to_id) void nodeLabel(bNodeTree *ntree, bNode *node, char *label, int maxlen) { - if (node->label[0] != '\0') + if (node->label[0] != '\0') { BLI_strncpy(label, node->label, maxlen); - else if (node->typeinfo->labelfunc) + } + else if (node->typeinfo->labelfunc) { node->typeinfo->labelfunc(ntree, node, label, maxlen); - else - BLI_strncpy(label, IFACE_(node->typeinfo->ui_name), maxlen); + } + else { + /* Kind of hacky and weak... Ideally would be better to use RNA here. :| */ + const char *tmp = CTX_IFACE_(BLT_I18NCONTEXT_ID_NODETREE, node->typeinfo->ui_name); + if (tmp == node->typeinfo->ui_name) { + tmp = IFACE_(node->typeinfo->ui_name); + } + BLI_strncpy(label, tmp, maxlen); + } } static void node_type_base_defaults(bNodeType *ntype) diff --git a/source/blender/blenkernel/intern/object.c b/source/blender/blenkernel/intern/object.c index 536170bf108..a89b1a2d60e 100644 --- a/source/blender/blenkernel/intern/object.c +++ b/source/blender/blenkernel/intern/object.c @@ -312,7 +312,7 @@ void BKE_object_link_modifiers(struct Object *ob_dst, const struct Object *ob_sr modifier_unique_name(&ob_dst->modifiers, nmd); } - BKE_object_copy_particlesystems(ob_dst, ob_src); + BKE_object_copy_particlesystems(ob_dst, ob_src, 0); /* TODO: smoke?, cloth? */ } @@ -330,14 +330,14 @@ void BKE_object_free_derived_caches(Object *ob) Mesh *me = ob->data; if (me && me->bb) { - atomic_fetch_and_or_uint32((uint*)&me->bb->flag, BOUNDBOX_DIRTY); + atomic_fetch_and_or_uint32((uint *)&me->bb->flag, BOUNDBOX_DIRTY); } } else if (ELEM(ob->type, OB_SURF, OB_CURVE, OB_FONT)) { Curve *cu = ob->data; if (cu && cu->bb) { - atomic_fetch_and_or_uint32((uint*)&cu->bb->flag, BOUNDBOX_DIRTY); + atomic_fetch_and_or_uint32((uint *)&cu->bb->flag, BOUNDBOX_DIRTY); } } @@ -670,7 +670,7 @@ Object *BKE_object_add_only_object(Main *bmain, int type, const char *name) if (!name) name = get_obdata_defname(type); - ob = BKE_libblock_alloc(bmain, ID_OB, name); + ob = BKE_libblock_alloc(bmain, ID_OB, name, 0); /* default object vars */ ob->type = type; @@ -837,7 +837,7 @@ struct Object *BKE_object_lod_matob_get(Object *ob, Scene *scene) #endif /* WITH_GAMEENGINE */ -SoftBody *copy_softbody(const SoftBody *sb, bool copy_caches) +SoftBody *copy_softbody(const SoftBody *sb, const int flag) { SoftBody *sbn; @@ -845,7 +845,7 @@ SoftBody *copy_softbody(const SoftBody *sb, bool copy_caches) sbn = MEM_dupallocN(sb); - if (copy_caches == false) { + if ((flag & LIB_ID_COPY_CACHES) == 0) { sbn->totspring = sbn->totpoint = 0; sbn->bpoint = NULL; sbn->bspring = NULL; @@ -874,7 +874,7 @@ SoftBody *copy_softbody(const SoftBody *sb, bool copy_caches) sbn->scratch = NULL; - sbn->pointcache = BKE_ptcache_copy_list(&sbn->ptcaches, &sb->ptcaches, copy_caches); + sbn->pointcache = BKE_ptcache_copy_list(&sbn->ptcaches, &sb->ptcaches, flag); if (sb->effector_weights) sbn->effector_weights = MEM_dupallocN(sb->effector_weights); @@ -882,7 +882,7 @@ SoftBody *copy_softbody(const SoftBody *sb, bool copy_caches) return sbn; } -BulletSoftBody *copy_bulletsoftbody(BulletSoftBody *bsb) +BulletSoftBody *copy_bulletsoftbody(const BulletSoftBody *bsb, const int UNUSED(flag)) { BulletSoftBody *bsbn; @@ -893,7 +893,7 @@ BulletSoftBody *copy_bulletsoftbody(BulletSoftBody *bsb) return bsbn; } -ParticleSystem *BKE_object_copy_particlesystem(ParticleSystem *psys) +ParticleSystem *BKE_object_copy_particlesystem(ParticleSystem *psys, const int flag) { ParticleSystem *psysn; ParticleData *pa; @@ -930,7 +930,7 @@ ParticleSystem *BKE_object_copy_particlesystem(ParticleSystem *psys) if (psys->clmd) { psysn->clmd = (ClothModifierData *)modifier_new(eModifierType_Cloth); - modifier_copyData((ModifierData *)psys->clmd, (ModifierData *)psysn->clmd); + modifier_copyData_ex((ModifierData *)psys->clmd, (ModifierData *)psysn->clmd, flag); psys->hair_in_dm = psys->hair_out_dm = NULL; } @@ -948,7 +948,8 @@ ParticleSystem *BKE_object_copy_particlesystem(ParticleSystem *psys) BLI_listbase_clear(&psysn->childcachebufs); psysn->renderdata = NULL; - psysn->pointcache = BKE_ptcache_copy_list(&psysn->ptcaches, &psys->ptcaches, false); + /* XXX Never copy caches here? */ + psysn->pointcache = BKE_ptcache_copy_list(&psysn->ptcaches, &psys->ptcaches, flag & ~LIB_ID_COPY_CACHES); /* XXX - from reading existing code this seems correct but intended usage of * pointcache should /w cloth should be added in 'ParticleSystem' - campbell */ @@ -956,12 +957,14 @@ ParticleSystem *BKE_object_copy_particlesystem(ParticleSystem *psys) psysn->clmd->point_cache = psysn->pointcache; } - id_us_plus((ID *)psysn->part); + if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) { + id_us_plus((ID *)psysn->part); + } return psysn; } -void BKE_object_copy_particlesystems(Object *ob_dst, const Object *ob_src) +void BKE_object_copy_particlesystems(Object *ob_dst, const Object *ob_src, const int flag) { ParticleSystem *psys, *npsys; ModifierData *md; @@ -973,7 +976,7 @@ void BKE_object_copy_particlesystems(Object *ob_dst, const Object *ob_src) BLI_listbase_clear(&ob_dst->particlesystem); for (psys = ob_src->particlesystem.first; psys; psys = psys->next) { - npsys = BKE_object_copy_particlesystem(psys); + npsys = BKE_object_copy_particlesystem(psys, flag); BLI_addtail(&ob_dst->particlesystem, npsys); @@ -1010,23 +1013,25 @@ void BKE_object_copy_softbody(Object *ob_dst, const Object *ob_src) { if (ob_src->soft) { ob_dst->softflag = ob_src->softflag; - ob_dst->soft = copy_softbody(ob_src->soft, false); + ob_dst->soft = copy_softbody(ob_src->soft, 0); } } -static void copy_object_pose(Object *obn, Object *ob) +static void copy_object_pose(Object *obn, const Object *ob, const int flag) { bPoseChannel *chan; /* note: need to clear obn->pose pointer first, so that BKE_pose_copy_data works (otherwise there's a crash) */ obn->pose = NULL; - BKE_pose_copy_data(&obn->pose, ob->pose, 1); /* 1 = copy constraints */ + BKE_pose_copy_data_ex(&obn->pose, ob->pose, flag, true); /* true = copy constraints */ for (chan = obn->pose->chanbase.first; chan; chan = chan->next) { bConstraint *con; chan->flag &= ~(POSE_LOC | POSE_ROT | POSE_SIZE); + /* XXX Remapping object pointing onto itself should be handled by generic BKE_library_remap stuff, but... + * the flush_constraint_targets callback am not sure about, so will delay that for now. */ for (con = chan->constraints.first; con; con = con->next) { const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con); ListBase targets = {NULL, NULL}; @@ -1047,13 +1052,10 @@ static void copy_object_pose(Object *obn, Object *ob) } } -static void copy_object_lod(Object *obn, Object *ob) +static void copy_object_lod(Object *obn, const Object *ob, const int UNUSED(flag)) { BLI_duplicatelist(&obn->lodlevels, &ob->lodlevels); - if (obn->lodlevels.first) - ((LodLevel *)obn->lodlevels.first)->source = obn; - obn->currentlod = (LodLevel *)obn->lodlevels.first; } @@ -1098,98 +1100,99 @@ void BKE_object_transform_copy(Object *ob_tar, const Object *ob_src) copy_v3_v3(ob_tar->size, ob_src->size); } -Object *BKE_object_copy_ex(Main *bmain, Object *ob, bool copy_caches) +/** + * Only copy internal data of Object ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_object_copy_data(Main *UNUSED(bmain), Object *ob_dst, const Object *ob_src, const int flag) { - Object *obn; ModifierData *md; - int a; - obn = BKE_libblock_copy(bmain, &ob->id); - - if (ob->totcol) { - obn->mat = MEM_dupallocN(ob->mat); - obn->matbits = MEM_dupallocN(ob->matbits); - obn->totcol = ob->totcol; + /* We never handle usercount here for own data. */ + const int flag_subdata = flag | LIB_ID_CREATE_NO_USER_REFCOUNT; + + if (ob_src->totcol) { + ob_dst->mat = MEM_dupallocN(ob_src->mat); + ob_dst->matbits = MEM_dupallocN(ob_src->matbits); + ob_dst->totcol = ob_src->totcol; } - if (ob->iuser) obn->iuser = MEM_dupallocN(ob->iuser); + if (ob_src->iuser) ob_dst->iuser = MEM_dupallocN(ob_src->iuser); - if (ob->bb) obn->bb = MEM_dupallocN(ob->bb); - obn->flag &= ~OB_FROMGROUP; + if (ob_src->bb) ob_dst->bb = MEM_dupallocN(ob_src->bb); + ob_dst->flag &= ~OB_FROMGROUP; - BLI_listbase_clear(&obn->modifiers); + BLI_listbase_clear(&ob_dst->modifiers); - for (md = ob->modifiers.first; md; md = md->next) { + for (md = ob_src->modifiers.first; md; md = md->next) { ModifierData *nmd = modifier_new(md->type); BLI_strncpy(nmd->name, md->name, sizeof(nmd->name)); - modifier_copyData(md, nmd); - BLI_addtail(&obn->modifiers, nmd); + modifier_copyData_ex(md, nmd, flag_subdata); + BLI_addtail(&ob_dst->modifiers, nmd); } - BLI_listbase_clear(&obn->prop); - BKE_bproperty_copy_list(&obn->prop, &ob->prop); + BLI_listbase_clear(&ob_dst->prop); + BKE_bproperty_copy_list(&ob_dst->prop, &ob_src->prop); - BKE_sca_logic_copy(obn, ob); + BKE_sca_logic_copy(ob_dst, ob_src, flag_subdata); - if (ob->pose) { - copy_object_pose(obn, ob); + if (ob_src->pose) { + copy_object_pose(ob_dst, ob_src, flag_subdata); /* backwards compat... non-armatures can get poses in older files? */ - if (ob->type == OB_ARMATURE) - BKE_pose_rebuild(obn, obn->data); + if (ob_src->type == OB_ARMATURE) + BKE_pose_rebuild(ob_dst, ob_dst->data); } - defgroup_copy_list(&obn->defbase, &ob->defbase); - BKE_constraints_copy(&obn->constraints, &ob->constraints, true); - - obn->mode = OB_MODE_OBJECT; - obn->sculpt = NULL; + defgroup_copy_list(&ob_dst->defbase, &ob_src->defbase); + BKE_constraints_copy_ex(&ob_dst->constraints, &ob_src->constraints, flag_subdata, true); - /* increase user numbers */ - id_us_plus((ID *)obn->data); - id_us_plus((ID *)obn->poselib); - id_us_plus((ID *)obn->gpd); - id_us_plus((ID *)obn->dup_group); + ob_dst->mode = OB_MODE_OBJECT; + ob_dst->sculpt = NULL; - for (a = 0; a < obn->totcol; a++) id_us_plus((ID *)obn->mat[a]); - - if (ob->pd) { - obn->pd = MEM_dupallocN(ob->pd); - if (obn->pd->tex) - id_us_plus(&(obn->pd->tex->id)); - if (obn->pd->rng) - obn->pd->rng = MEM_dupallocN(ob->pd->rng); + if (ob_src->pd) { + ob_dst->pd = MEM_dupallocN(ob_src->pd); + if (ob_dst->pd->rng) { + ob_dst->pd->rng = MEM_dupallocN(ob_src->pd->rng); + } } - obn->soft = copy_softbody(ob->soft, copy_caches); - obn->bsoft = copy_bulletsoftbody(ob->bsoft); - obn->rigidbody_object = BKE_rigidbody_copy_object(ob); - obn->rigidbody_constraint = BKE_rigidbody_copy_constraint(ob); + ob_dst->soft = copy_softbody(ob_src->soft, flag_subdata); + ob_dst->bsoft = copy_bulletsoftbody(ob_src->bsoft, flag_subdata); + ob_dst->rigidbody_object = BKE_rigidbody_copy_object(ob_src, flag_subdata); + ob_dst->rigidbody_constraint = BKE_rigidbody_copy_constraint(ob_src, flag_subdata); - BKE_object_copy_particlesystems(obn, ob); + BKE_object_copy_particlesystems(ob_dst, ob_src, flag_subdata); - obn->derivedDeform = NULL; - obn->derivedFinal = NULL; + ob_dst->derivedDeform = NULL; + ob_dst->derivedFinal = NULL; - BLI_listbase_clear(&obn->gpulamp); - BLI_listbase_clear(&obn->pc_ids); + BLI_listbase_clear(&ob_dst->gpulamp); + BLI_listbase_clear(&ob_dst->pc_ids); - obn->mpath = NULL; + ob_dst->mpath = NULL; - copy_object_lod(obn, ob); + copy_object_lod(ob_dst, ob_src, flag_subdata); - /* Copy runtime surve data. */ - obn->curve_cache = NULL; - - BKE_id_copy_ensure_local(bmain, &ob->id, &obn->id); + /* Do not copy runtime curve data. */ + ob_dst->curve_cache = NULL; /* Do not copy object's preview (mostly due to the fact renderers create temp copy of objects). */ - obn->preview = NULL; - - return obn; + if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0 && false) { /* XXX TODO temp hack */ + BKE_previewimg_id_copy(&ob_dst->id, &ob_src->id); + } + else { + ob_dst->preview = NULL; + } } /* copy objects, will re-initialize cached simulation data */ -Object *BKE_object_copy(Main *bmain, Object *ob) +Object *BKE_object_copy(Main *bmain, const Object *ob) { - return BKE_object_copy_ex(bmain, ob, false); + Object *ob_copy; + BKE_id_copy_ex(bmain, &ob->id, (ID **)&ob_copy, 0, false); + return ob_copy; } void BKE_object_make_local_ex(Main *bmain, Object *ob, const bool lib_local, const bool clear_proxy) @@ -1387,7 +1390,7 @@ void BKE_object_make_proxy(Object *ob, Object *target, Object *gob) /* type conversions */ if (target->type == OB_ARMATURE) { - copy_object_pose(ob, target); /* data copy, object pointers in constraints */ + copy_object_pose(ob, target, 0); /* data copy, object pointers in constraints */ BKE_pose_rest(ob->pose); /* clear all transforms in channels */ BKE_pose_rebuild(ob, ob->data); /* set all internal links */ diff --git a/source/blender/blenkernel/intern/object_deform.c b/source/blender/blenkernel/intern/object_deform.c index ccf2aec5c7a..d387e30050c 100644 --- a/source/blender/blenkernel/intern/object_deform.c +++ b/source/blender/blenkernel/intern/object_deform.c @@ -481,6 +481,8 @@ bool BKE_object_defgroup_array_get(ID *id, MDeformVert **dvert_arr, int *dvert_t *dvert_tot = lt->pntsu * lt->pntsv * lt->pntsw; return true; } + default: + break; } } diff --git a/source/blender/blenkernel/intern/object_dupli.c b/source/blender/blenkernel/intern/object_dupli.c index e9ebd397df0..b49e481b068 100644 --- a/source/blender/blenkernel/intern/object_dupli.c +++ b/source/blender/blenkernel/intern/object_dupli.c @@ -343,7 +343,7 @@ static void make_duplis_group(const DupliContext *ctx) } } -const DupliGenerator gen_dupli_group = { +static const DupliGenerator gen_dupli_group = { OB_DUPLIGROUP, /* type */ make_duplis_group /* make_duplis */ }; @@ -421,7 +421,7 @@ static void make_duplis_frames(const DupliContext *ctx) *ob = copyob; } -const DupliGenerator gen_dupli_frames = { +static const DupliGenerator gen_dupli_frames = { OB_DUPLIFRAMES, /* type */ make_duplis_frames /* make_duplis */ }; @@ -547,10 +547,15 @@ static void make_duplis_verts(const DupliContext *ctx) BMEditMesh *em = BKE_editmesh_from_object(parent); CustomDataMask dm_mask = (use_texcoords ? CD_MASK_BAREMESH | CD_MASK_ORCO : CD_MASK_BAREMESH); - if (em) + if (ctx->eval_ctx->mode == DAG_EVAL_RENDER) { + vdd.dm = mesh_create_derived_render(scene, parent, dm_mask); + } + else if (em) { vdd.dm = editbmesh_get_derived_cage(scene, parent, em, dm_mask); - else + } + else { vdd.dm = mesh_get_derived_final(scene, parent, dm_mask); + } vdd.edit_btmesh = me->edit_btmesh; if (use_texcoords) @@ -566,7 +571,7 @@ static void make_duplis_verts(const DupliContext *ctx) vdd.dm->release(vdd.dm); } -const DupliGenerator gen_dupli_verts = { +static const DupliGenerator gen_dupli_verts = { OB_DUPLIVERTS, /* type */ make_duplis_verts /* make_duplis */ }; @@ -679,7 +684,7 @@ static void make_duplis_font(const DupliContext *ctx) MEM_freeN(chartransdata); } -const DupliGenerator gen_dupli_verts_font = { +static const DupliGenerator gen_dupli_verts_font = { OB_DUPLIVERTS, /* type */ make_duplis_font /* make_duplis */ }; @@ -810,10 +815,15 @@ static void make_duplis_faces(const DupliContext *ctx) BMEditMesh *em = BKE_editmesh_from_object(parent); CustomDataMask dm_mask = (use_texcoords ? CD_MASK_BAREMESH | CD_MASK_ORCO | CD_MASK_MLOOPUV : CD_MASK_BAREMESH); - if (em) + if (ctx->eval_ctx->mode == DAG_EVAL_RENDER) { + fdd.dm = mesh_create_derived_render(scene, parent, dm_mask); + } + else if (em) { fdd.dm = editbmesh_get_derived_cage(scene, parent, em, dm_mask); - else + } + else { fdd.dm = mesh_get_derived_final(scene, parent, dm_mask); + } if (use_texcoords) { CustomData *ml_data = fdd.dm->getLoopDataLayout(fdd.dm); @@ -837,7 +847,7 @@ static void make_duplis_faces(const DupliContext *ctx) fdd.dm->release(fdd.dm); } -const DupliGenerator gen_dupli_faces = { +static const DupliGenerator gen_dupli_faces = { OB_DUPLIFACES, /* type */ make_duplis_faces /* make_duplis */ }; @@ -1158,7 +1168,7 @@ static void make_duplis_particles(const DupliContext *ctx) } } -const DupliGenerator gen_dupli_particles = { +static const DupliGenerator gen_dupli_particles = { OB_DUPLIPARTS, /* type */ make_duplis_particles /* make_duplis */ }; diff --git a/source/blender/blenkernel/intern/object_update.c b/source/blender/blenkernel/intern/object_update.c index a531466294e..e03af585cf2 100644 --- a/source/blender/blenkernel/intern/object_update.c +++ b/source/blender/blenkernel/intern/object_update.c @@ -145,18 +145,6 @@ void BKE_object_eval_done(EvaluationContext *UNUSED(eval_ctx), Object *ob) else ob->transflag &= ~OB_NEG_SCALE; } -void BKE_object_eval_modifier(struct EvaluationContext *eval_ctx, - struct Scene *scene, - struct Object *ob, - struct ModifierData *md) -{ - DEBUG_PRINT("%s on %s\n", __func__, ob->id.name); - (void) eval_ctx; /* Ignored. */ - (void) scene; /* Ignored. */ - (void) ob; /* Ignored. */ - (void) md; /* Ignored. */ -} - void BKE_object_handle_data_update(EvaluationContext *eval_ctx, Scene *scene, Object *ob) diff --git a/source/blender/blenkernel/intern/ocean.c b/source/blender/blenkernel/intern/ocean.c index 621ac9c2480..537c8926a5b 100644 --- a/source/blender/blenkernel/intern/ocean.c +++ b/source/blender/blenkernel/intern/ocean.c @@ -334,10 +334,10 @@ void BKE_ocean_eval_uv(struct Ocean *oc, struct OceanResult *ocr, float u, float i1 = i1 % oc->_M; j1 = j1 % oc->_N; - #define BILERP(m) (interpf(interpf(m[i1 * oc->_N + j1], m[i0 * oc->_N + j1], frac_x), \ interpf(m[i1 * oc->_N + j0], m[i0 * oc->_N + j0], frac_x), \ frac_z)) + { if (oc->_do_disp_y) { ocr->disp[1] = BILERP(oc->_disp_y); diff --git a/source/blender/blenkernel/intern/packedFile.c b/source/blender/blenkernel/intern/packedFile.c index 64f90ef5c52..89f25136caf 100644 --- a/source/blender/blenkernel/intern/packedFile.c +++ b/source/blender/blenkernel/intern/packedFile.c @@ -522,6 +522,8 @@ static void unpack_generate_paths( case ID_IM: BLI_snprintf(r_relpath, relpathlen, "//textures/%s", tempname); break; + default: + break; } { @@ -712,6 +714,8 @@ bool BKE_pack_check(ID *id) Library *li = (Library *)id; return li->packedfile != NULL; } + default: + break; } return false; } @@ -750,5 +754,7 @@ void BKE_unpack_id(Main *bmain, ID *id, ReportList *reports, int how) BKE_reportf(reports, RPT_ERROR, "Cannot unpack individual Library file, '%s'", li->name); break; } + default: + break; } } diff --git a/source/blender/blenkernel/intern/paint.c b/source/blender/blenkernel/intern/paint.c index e56db89097d..24544e571d7 100644 --- a/source/blender/blenkernel/intern/paint.c +++ b/source/blender/blenkernel/intern/paint.c @@ -309,24 +309,31 @@ PaintCurve *BKE_paint_curve_add(Main *bmain, const char *name) { PaintCurve *pc; - pc = BKE_libblock_alloc(bmain, ID_PC, name); + pc = BKE_libblock_alloc(bmain, ID_PC, name, 0); return pc; } -PaintCurve *BKE_paint_curve_copy(Main *bmain, PaintCurve *pc) +/** + * Only copy internal data of PaintCurve ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_paint_curve_copy_data(Main *UNUSED(bmain), PaintCurve *pc_dst, const PaintCurve *pc_src, const int UNUSED(flag)) { - PaintCurve *pc_new; - - pc_new = BKE_libblock_copy(bmain, &pc->id); - - if (pc->tot_points != 0) { - pc_new->points = MEM_dupallocN(pc->points); + if (pc_src->tot_points != 0) { + pc_dst->points = MEM_dupallocN(pc_src->points); } +} - BKE_id_copy_ensure_local(bmain, &pc->id, &pc_new->id); - - return pc_new; +PaintCurve *BKE_paint_curve_copy(Main *bmain, const PaintCurve *pc) +{ + PaintCurve *pc_copy; + BKE_id_copy_ex(bmain, &pc->id, (ID **)&pc_copy, 0, false); + return pc_copy; } void BKE_paint_curve_make_local(Main *bmain, PaintCurve *pc, const bool lib_local) @@ -388,7 +395,7 @@ Palette *BKE_palette_add(Main *bmain, const char *name) { Palette *palette; - palette = BKE_libblock_alloc(bmain, ID_PAL, name); + palette = BKE_libblock_alloc(bmain, ID_PAL, name, 0); /* enable fake user by default */ id_fake_user_set(&palette->id); @@ -396,17 +403,24 @@ Palette *BKE_palette_add(Main *bmain, const char *name) return palette; } -Palette *BKE_palette_copy(Main *bmain, Palette *palette) +/** + * Only copy internal data of Palette ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_palette_copy_data(Main *UNUSED(bmain), Palette *palette_dst, const Palette *palette_src, const int UNUSED(flag)) { - Palette *palette_new; - - palette_new = BKE_libblock_copy(bmain, &palette->id); - - BLI_duplicatelist(&palette_new->colors, &palette->colors); - - BKE_id_copy_ensure_local(bmain, &palette->id, &palette_new->id); + BLI_duplicatelist(&palette_dst->colors, &palette_src->colors); +} - return palette_new; +Palette *BKE_palette_copy(Main *bmain, const Palette *palette) +{ + Palette *palette_copy; + BKE_id_copy_ex(bmain, &palette->id, (ID **)&palette_copy, 0, false); + return palette_copy; } void BKE_palette_make_local(Main *bmain, Palette *palette, const bool lib_local) @@ -537,12 +551,15 @@ void BKE_paint_free(Paint *paint) * still do a id_us_plus(), rather then if we were copying between 2 existing * scenes where a matching value should decrease the existing user count as * with paint_brush_set() */ -void BKE_paint_copy(Paint *src, Paint *tar) +void BKE_paint_copy(Paint *src, Paint *tar, const int flag) { tar->brush = src->brush; - id_us_plus((ID *)tar->brush); - id_us_plus((ID *)tar->palette); tar->cavity_curve = curvemapping_copy(src->cavity_curve); + + if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) { + id_us_plus((ID *)tar->brush); + id_us_plus((ID *)tar->palette); + } } void BKE_paint_stroke_get_average(Scene *scene, Object *ob, float stroke[3]) diff --git a/source/blender/blenkernel/intern/particle.c b/source/blender/blenkernel/intern/particle.c index bb5cea9dcc7..8c94cdfe784 100644 --- a/source/blender/blenkernel/intern/particle.c +++ b/source/blender/blenkernel/intern/particle.c @@ -253,11 +253,16 @@ struct LatticeDeformData *psys_create_lattice_deform_data(ParticleSimulationData if (psys_in_edit_mode(sim->scene, sim->psys) == 0) { Object *lattice = NULL; ModifierData *md = (ModifierData *)psys_get_modifier(sim->ob, sim->psys); + int mode = G.is_rendering ? eModifierMode_Render : eModifierMode_Realtime; for (; md; md = md->next) { if (md->type == eModifierType_Lattice) { - LatticeModifierData *lmd = (LatticeModifierData *)md; - lattice = lmd->object; + if (md->mode & mode) { + LatticeModifierData *lmd = (LatticeModifierData *)md; + lattice = lmd->object; + sim->psys->lattice_strength = lmd->strength; + } + break; } } @@ -590,7 +595,7 @@ void psys_free(Object *ob, ParticleSystem *psys) BLI_bvhtree_free(psys->bvhtree); BLI_kdtree_free(psys->tree); - + if (psys->fluid_springs) MEM_freeN(psys->fluid_springs); @@ -2706,7 +2711,7 @@ void psys_cache_paths(ParticleSimulationData *sim, float cfra, const bool use_re /* lattices have to be calculated separately to avoid mixups between effector calculations */ if (psys->lattice_deform_data) { for (k = 0, ca = cache[p]; k <= segments; k++, ca++) - calc_latt_deform(psys->lattice_deform_data, ca->co, 1.0f); + calc_latt_deform(psys->lattice_deform_data, ca->co, psys->lattice_strength); } } @@ -3295,7 +3300,7 @@ ParticleSettings *psys_new_settings(const char *name, Main *main) if (main == NULL) main = G.main; - part = BKE_libblock_alloc(main, ID_PA, name); + part = BKE_libblock_alloc(main, ID_PA, name, 0); default_particle_settings(part); @@ -3326,38 +3331,45 @@ void BKE_particlesettings_rough_curve_init(ParticleSettings *part) part->roughcurve = cumap; } -ParticleSettings *BKE_particlesettings_copy(Main *bmain, ParticleSettings *part) +/** + * Only copy internal data of ParticleSettings ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_particlesettings_copy_data( + Main *UNUSED(bmain), ParticleSettings *part_dst, const ParticleSettings *part_src, const int UNUSED(flag)) { - ParticleSettings *partn; - int a; + part_dst->pd = MEM_dupallocN(part_src->pd); + part_dst->pd2 = MEM_dupallocN(part_src->pd2); + part_dst->effector_weights = MEM_dupallocN(part_src->effector_weights); + part_dst->fluid = MEM_dupallocN(part_src->fluid); - partn = BKE_libblock_copy(bmain, &part->id); - - partn->pd = MEM_dupallocN(part->pd); - partn->pd2 = MEM_dupallocN(part->pd2); - partn->effector_weights = MEM_dupallocN(part->effector_weights); - partn->fluid = MEM_dupallocN(part->fluid); + if (part_src->clumpcurve) { + part_dst->clumpcurve = curvemapping_copy(part_src->clumpcurve); + } + if (part_src->roughcurve) { + part_dst->roughcurve = curvemapping_copy(part_src->roughcurve); + } - if (part->clumpcurve) - partn->clumpcurve = curvemapping_copy(part->clumpcurve); - if (part->roughcurve) - partn->roughcurve = curvemapping_copy(part->roughcurve); - - partn->boids = boid_copy_settings(part->boids); + part_dst->boids = boid_copy_settings(part_src->boids); - for (a = 0; a < MAX_MTEX; a++) { - if (part->mtex[a]) { - partn->mtex[a] = MEM_mallocN(sizeof(MTex), "psys_copy_tex"); - memcpy(partn->mtex[a], part->mtex[a], sizeof(MTex)); - id_us_plus((ID *)partn->mtex[a]->tex); + for (int a = 0; a < MAX_MTEX; a++) { + if (part_src->mtex[a]) { + part_dst->mtex[a] = MEM_dupallocN(part_src->mtex[a]); } } - BLI_duplicatelist(&partn->dupliweights, &part->dupliweights); - - BKE_id_copy_ensure_local(bmain, &part->id, &partn->id); + BLI_duplicatelist(&part_dst->dupliweights, &part_src->dupliweights); +} - return partn; +ParticleSettings *BKE_particlesettings_copy(Main *bmain, const ParticleSettings *part) +{ + ParticleSettings *part_copy; + BKE_id_copy_ex(bmain, &part->id, (ID **)&part_copy, 0, false); + return part_copy; } void BKE_particlesettings_make_local(Main *bmain, ParticleSettings *part, const bool lib_local) @@ -3369,7 +3381,8 @@ void BKE_particlesettings_make_local(Main *bmain, ParticleSettings *part, const /* Textures */ /************************************************/ -static int get_particle_uv(DerivedMesh *dm, ParticleData *pa, int face_index, const float fuv[4], char *name, float *texco) +static int get_particle_uv(DerivedMesh *dm, ParticleData *pa, int index, const float fuv[4], + char *name, float *texco, bool from_vert) { MFace *mf; MTFace *tf; @@ -3385,11 +3398,15 @@ static int get_particle_uv(DerivedMesh *dm, ParticleData *pa, int face_index, co if (pa) { i = ELEM(pa->num_dmcache, DMCACHE_NOTFOUND, DMCACHE_ISCHILD) ? pa->num : pa->num_dmcache; - if (i >= dm->getNumTessFaces(dm)) + if ((!from_vert && i >= dm->getNumTessFaces(dm)) || + (from_vert && i >= dm->getNumVerts(dm))) + { i = -1; + } + } + else { + i = index; } - else - i = face_index; if (i == -1) { texco[0] = 0.0f; @@ -3397,7 +3414,22 @@ static int get_particle_uv(DerivedMesh *dm, ParticleData *pa, int face_index, co texco[2] = 0.0f; } else { - mf = dm->getTessFaceData(dm, i, CD_MFACE); + if (from_vert) { + mf = dm->getTessFaceDataArray(dm, CD_MFACE); + + /* This finds the first face to contain the emitting vertex, + * this is not ideal, but is mostly fine as UV seams generally + * map to equal-colored parts of a texture */ + for (int j = 0; j < dm->getNumTessFaces(dm); j++, mf++) { + if (ELEM(i, mf->v1, mf->v2, mf->v3, mf->v4)) { + i = j; + break; + } + } + } + else { + mf = dm->getTessFaceData(dm, i, CD_MFACE); + } psys_interpolate_uvs(&tf[i], mf->v4, fuv, texco); @@ -3464,8 +3496,11 @@ static void get_cpa_texture(DerivedMesh *dm, ParticleSystem *psys, ParticleSetti mul_m4_v3(mtex->object->imat, texvec); break; case TEXCO_UV: - if (fw && get_particle_uv(dm, NULL, face_index, fw, mtex->uvname, texvec)) + if (fw && get_particle_uv(dm, NULL, face_index, fw, mtex->uvname, + texvec, (part->from == PART_FROM_VERT))) + { break; + } /* no break, failed to get uv's, so let's try orco's */ ATTR_FALLTHROUGH; case TEXCO_ORCO: @@ -3537,8 +3572,11 @@ void psys_get_texture(ParticleSimulationData *sim, ParticleData *pa, ParticleTex mul_m4_v3(mtex->object->imat, texvec); break; case TEXCO_UV: - if (get_particle_uv(sim->psmd->dm_final, pa, 0, pa->fuv, mtex->uvname, texvec)) + if (get_particle_uv(sim->psmd->dm_final, pa, 0, pa->fuv, mtex->uvname, + texvec, (part->from == PART_FROM_VERT))) + { break; + } /* no break, failed to get uv's, so let's try orco's */ ATTR_FALLTHROUGH; case TEXCO_ORCO: @@ -3748,7 +3786,7 @@ void psys_get_particle_on_path(ParticleSimulationData *sim, int p, ParticleKey * } if (psys->lattice_deform_data && edit == 0) - calc_latt_deform(psys->lattice_deform_data, state->co, 1.0f); + calc_latt_deform(psys->lattice_deform_data, state->co, psys->lattice_strength); } } } @@ -3987,7 +4025,7 @@ int psys_get_particle_state(ParticleSimulationData *sim, int p, ParticleKey *sta do_child_modifiers(NULL, sim, NULL, key1->co, key1->vel, key1->rot, par_orco, cpa, cpa->fuv, mat, state, t); if (psys->lattice_deform_data) - calc_latt_deform(psys->lattice_deform_data, state->co, 1.0f); + calc_latt_deform(psys->lattice_deform_data, state->co, psys->lattice_strength); } else { if (pa->state.time == cfra || ELEM(part->phystype, PART_PHYS_NO, PART_PHYS_KEYED)) @@ -4046,7 +4084,7 @@ int psys_get_particle_state(ParticleSimulationData *sim, int p, ParticleKey *sta } if (sim->psys->lattice_deform_data) - calc_latt_deform(sim->psys->lattice_deform_data, state->co, 1.0f); + calc_latt_deform(sim->psys->lattice_deform_data, state->co, psys->lattice_strength); } return 1; @@ -4293,7 +4331,7 @@ void psys_apply_hair_lattice(Scene *scene, Object *ob, ParticleSystem *psys) hkey = pa->hair; for (h = 0; h < pa->totkey; h++, hkey++) { mul_m4_v3(hairmat, hkey->co); - calc_latt_deform(psys->lattice_deform_data, hkey->co, 1.0f); + calc_latt_deform(psys->lattice_deform_data, hkey->co, psys->lattice_strength); mul_m4_v3(imat, hkey->co); } } diff --git a/source/blender/blenkernel/intern/particle_child.c b/source/blender/blenkernel/intern/particle_child.c index 842de869291..bfcda89a635 100644 --- a/source/blender/blenkernel/intern/particle_child.c +++ b/source/blender/blenkernel/intern/particle_child.c @@ -355,9 +355,13 @@ void psys_apply_child_modifiers(ParticleThreadContext *ctx, struct ListBase *mod { const float step_length = 1.0f / (float)(totkeys - 1); - float cur_length = 0.0f; - + + if (max_length <= 0.0f) { + keys->segments = -1; + totkeys = 0; + } + /* we have to correct velocity because of kink & clump */ for (k = 0, key = keys; k < totkeys; ++k, ++key) { if (k >= 2) { diff --git a/source/blender/blenkernel/intern/particle_distribute.c b/source/blender/blenkernel/intern/particle_distribute.c index 44cf5b119c1..ac9c60e8999 100644 --- a/source/blender/blenkernel/intern/particle_distribute.c +++ b/source/blender/blenkernel/intern/particle_distribute.c @@ -427,12 +427,37 @@ static int distribute_binary_search(float *sum, int n, float value) static void distribute_from_verts_exec(ParticleTask *thread, ParticleData *pa, int p) { ParticleThreadContext *ctx= thread->ctx; - int rng_skip_tot= PSYS_RND_DIST_SKIP; /* count how many rng_* calls wont need skipping */ + MFace *mface; + + mface = ctx->dm->getTessFaceDataArray(ctx->dm, CD_MFACE); + + int rng_skip_tot = PSYS_RND_DIST_SKIP; /* count how many rng_* calls wont need skipping */ /* TODO_PARTICLE - use original index */ - pa->num= ctx->index[p]; - pa->fuv[0] = 1.0f; - pa->fuv[1] = pa->fuv[2] = pa->fuv[3] = 0.0; + pa->num = ctx->index[p]; + + zero_v4(pa->fuv); + + if (pa->num != DMCACHE_NOTFOUND && pa->num < ctx->dm->getNumVerts(ctx->dm)) { + + /* This finds the first face to contain the emitting vertex, + * this is not ideal, but is mostly fine as UV seams generally + * map to equal-colored parts of a texture */ + for (int i = 0; i < ctx->dm->getNumTessFaces(ctx->dm); i++, mface++) { + if (ELEM(pa->num, mface->v1, mface->v2, mface->v3, mface->v4)) { + unsigned int *vert = &mface->v1; + + for (int j = 0; j < 4; j++, vert++) { + if (*vert == pa->num) { + pa->fuv[j] = 1.0f; + break; + } + } + + break; + } + } + } #if ONLY_WORKING_WITH_PA_VERTS if (ctx->tree) { @@ -873,10 +898,7 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti else dm= CDDM_from_mesh((Mesh*)ob->data); - /* BMESH ONLY, for verts we don't care about tessfaces */ - if (from != PART_FROM_VERT) { - DM_ensure_tessface(dm); - } + DM_ensure_tessface(dm); /* we need orco for consistent distributions */ if (!CustomData_has_layer(&dm->vertData, CD_ORCO)) @@ -1092,7 +1114,7 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti /* For hair, sort by origindex (allows optimization's in rendering), */ /* however with virtual parents the children need to be in random order. */ - if (part->type == PART_HAIR && !(part->childtype==PART_CHILD_FACES && part->parents!=0.0f)) { + if (part->type == PART_HAIR && !(part->childtype==PART_CHILD_FACES && part->parents != 0.0f)) { int *orig_index = NULL; if (from == PART_FROM_VERT) { diff --git a/source/blender/blenkernel/intern/particle_system.c b/source/blender/blenkernel/intern/particle_system.c index 943dc781246..9ee456227e2 100644 --- a/source/blender/blenkernel/intern/particle_system.c +++ b/source/blender/blenkernel/intern/particle_system.c @@ -1000,7 +1000,7 @@ void reset_particle(ParticleSimulationData *sim, ParticleData *pa, float dtime, part=psys->part; /* get precise emitter matrix if particle is born */ - if (part->type!=PART_HAIR && dtime > 0.f && pa->time < cfra && pa->time >= sim->psys->cfra) { + if (part->type != PART_HAIR && dtime > 0.f && pa->time < cfra && pa->time >= sim->psys->cfra) { evaluate_emitter_anim(sim->scene, sim->ob, pa->time); psys->flag |= PSYS_OB_ANIM_RESTORE; @@ -1183,7 +1183,7 @@ static void set_keyed_keys(ParticleSimulationData *sim) key->time = pa->time; } - if (psys->flag & PSYS_KEYED_TIMING && pt->duration!=0.0f) + if (psys->flag & PSYS_KEYED_TIMING && pt->duration != 0.0f) k++; ksim.psys->flag |= keyed_flag; @@ -3042,10 +3042,12 @@ static void hair_create_input_dm(ParticleSimulationData *sim, int totpoint, int /* calculate maximum segment length */ max_length = 0.0f; LOOP_PARTICLES { - for (k=1, key=pa->hair+1; k<pa->totkey; k++,key++) { - float length = len_v3v3(key->co, (key-1)->co); - if (max_length < length) - max_length = length; + if (!(pa->flag & PARS_UNEXIST)) { + for (k=1, key=pa->hair+1; k<pa->totkey; k++,key++) { + float length = len_v3v3(key->co, (key-1)->co); + if (max_length < length) + max_length = length; + } } } @@ -3057,76 +3059,78 @@ static void hair_create_input_dm(ParticleSimulationData *sim, int totpoint, int /* make vgroup for pin roots etc.. */ hair_index = 1; LOOP_PARTICLES { - float root_mat[4][4]; - float bending_stiffness; - bool use_hair; - - pa->hair_index = hair_index; - use_hair = psys_hair_use_simulation(pa, max_length); - - psys_mat_hair_to_object(sim->ob, sim->psmd->dm_final, psys->part->from, pa, hairmat); - mul_m4_m4m4(root_mat, sim->ob->obmat, hairmat); - normalize_m4(root_mat); - - bending_stiffness = CLAMPIS(1.0f - part->bending_random * psys_frand(psys, p + 666), 0.0f, 1.0f); - - for (k=0, key=pa->hair; k<pa->totkey; k++,key++) { - ClothHairData *hair; - float *co, *co_next; - - co = key->co; - co_next = (key+1)->co; - - /* create fake root before actual root to resist bending */ - if (k==0) { - hair = &psys->clmd->hairdata[pa->hair_index - 1]; + if (!(pa->flag & PARS_UNEXIST)) { + float root_mat[4][4]; + float bending_stiffness; + bool use_hair; + + pa->hair_index = hair_index; + use_hair = psys_hair_use_simulation(pa, max_length); + + psys_mat_hair_to_object(sim->ob, sim->psmd->dm_final, psys->part->from, pa, hairmat); + mul_m4_m4m4(root_mat, sim->ob->obmat, hairmat); + normalize_m4(root_mat); + + bending_stiffness = CLAMPIS(1.0f - part->bending_random * psys_frand(psys, p + 666), 0.0f, 1.0f); + + for (k=0, key=pa->hair; k<pa->totkey; k++,key++) { + ClothHairData *hair; + float *co, *co_next; + + co = key->co; + co_next = (key+1)->co; + + /* create fake root before actual root to resist bending */ + if (k==0) { + hair = &psys->clmd->hairdata[pa->hair_index - 1]; + copy_v3_v3(hair->loc, root_mat[3]); + copy_m3_m4(hair->rot, root_mat); + + hair->radius = hair_radius; + hair->bending_stiffness = bending_stiffness; + + add_v3_v3v3(mvert->co, co, co); + sub_v3_v3(mvert->co, co_next); + mul_m4_v3(hairmat, mvert->co); + + medge->v1 = pa->hair_index - 1; + medge->v2 = pa->hair_index; + + dvert = hair_set_pinning(dvert, 1.0f); + + mvert++; + medge++; + } + + /* store root transform in cloth data */ + hair = &psys->clmd->hairdata[pa->hair_index + k]; copy_v3_v3(hair->loc, root_mat[3]); copy_m3_m4(hair->rot, root_mat); - + hair->radius = hair_radius; hair->bending_stiffness = bending_stiffness; - - add_v3_v3v3(mvert->co, co, co); - sub_v3_v3(mvert->co, co_next); + + copy_v3_v3(mvert->co, co); mul_m4_v3(hairmat, mvert->co); - - medge->v1 = pa->hair_index - 1; - medge->v2 = pa->hair_index; - - dvert = hair_set_pinning(dvert, 1.0f); - + + if (k) { + medge->v1 = pa->hair_index + k - 1; + medge->v2 = pa->hair_index + k; + } + + /* roots and disabled hairs should be 1.0, the rest can be anything from 0.0 to 1.0 */ + if (use_hair) + dvert = hair_set_pinning(dvert, key->weight); + else + dvert = hair_set_pinning(dvert, 1.0f); + mvert++; - medge++; + if (k) + medge++; } - - /* store root transform in cloth data */ - hair = &psys->clmd->hairdata[pa->hair_index + k]; - copy_v3_v3(hair->loc, root_mat[3]); - copy_m3_m4(hair->rot, root_mat); - - hair->radius = hair_radius; - hair->bending_stiffness = bending_stiffness; - - copy_v3_v3(mvert->co, co); - mul_m4_v3(hairmat, mvert->co); - - if (k) { - medge->v1 = pa->hair_index + k - 1; - medge->v2 = pa->hair_index + k; - } - - /* roots and disabled hairs should be 1.0, the rest can be anything from 0.0 to 1.0 */ - if (use_hair) - dvert = hair_set_pinning(dvert, key->weight); - else - dvert = hair_set_pinning(dvert, 1.0f); - - mvert++; - if (k) - medge++; + + hair_index += pa->totkey + 1; } - - hair_index += pa->totkey + 1; } } @@ -3152,9 +3156,11 @@ static void do_hair_dynamics(ParticleSimulationData *sim) totpoint = 0; totedge = 0; LOOP_PARTICLES { - /* "out" dm contains all hairs */ - totedge += pa->totkey; - totpoint += pa->totkey + 1; /* +1 for virtual root point */ + if (!(pa->flag & PARS_UNEXIST)) { + /* "out" dm contains all hairs */ + totedge += pa->totkey; + totpoint += pa->totkey + 1; /* +1 for virtual root point */ + } } realloc_roots = false; /* whether hair root info array has to be reallocated */ @@ -4350,13 +4356,12 @@ void BKE_particlesystem_id_loop(ParticleSystem *psys, ParticleSystemIDFunc func, /* **** Depsgraph evaluation **** */ -void BKE_particle_system_eval(EvaluationContext *UNUSED(eval_ctx), - Scene *scene, - Object *ob, - ParticleSystem *psys) +void BKE_particle_system_eval_init(EvaluationContext *UNUSED(eval_ctx), + Scene *scene, + Object *ob) { if (G.debug & G_DEBUG_DEPSGRAPH) { - printf("%s on %s:%s\n", __func__, ob->id.name, psys->name); + printf("%s on %s\n", __func__, ob->id.name); } BKE_ptcache_object_reset(scene, ob, PTCACHE_RESET_DEPSGRAPH); } diff --git a/source/blender/blenkernel/intern/pbvh.c b/source/blender/blenkernel/intern/pbvh.c index 549b0293bd1..f6d53075bf0 100644 --- a/source/blender/blenkernel/intern/pbvh.c +++ b/source/blender/blenkernel/intern/pbvh.c @@ -1118,7 +1118,7 @@ static void pbvh_update_draw_buffers(PBVH *bvh, PBVHNode **nodes, int totnode) GPU_pbvh_bmesh_buffers_build(bvh->flags & PBVH_DYNTOPO_SMOOTH_SHADING); break; } - + node->flag &= ~PBVH_RebuildDrawBuffers; } diff --git a/source/blender/blenkernel/intern/pointcache.c b/source/blender/blenkernel/intern/pointcache.c index a7e00a8103a..7a1b378b3c4 100644 --- a/source/blender/blenkernel/intern/pointcache.c +++ b/source/blender/blenkernel/intern/pointcache.c @@ -3449,7 +3449,7 @@ void BKE_ptcache_free_list(ListBase *ptcaches) } } -static PointCache *ptcache_copy(PointCache *cache, bool copy_data) +static PointCache *ptcache_copy(PointCache *cache, const bool copy_data) { PointCache *ncache; @@ -3492,14 +3492,15 @@ static PointCache *ptcache_copy(PointCache *cache, bool copy_data) } /* returns first point cache */ -PointCache *BKE_ptcache_copy_list(ListBase *ptcaches_new, const ListBase *ptcaches_old, bool copy_data) +PointCache *BKE_ptcache_copy_list(ListBase *ptcaches_new, const ListBase *ptcaches_old, const int flag) { PointCache *cache = ptcaches_old->first; BLI_listbase_clear(ptcaches_new); - for (; cache; cache=cache->next) - BLI_addtail(ptcaches_new, ptcache_copy(cache, copy_data)); + for (; cache; cache=cache->next) { + BLI_addtail(ptcaches_new, ptcache_copy(cache, (flag & LIB_ID_COPY_CACHES) != 0)); + } return ptcaches_new->first; } @@ -3618,7 +3619,13 @@ void BKE_ptcache_bake(PTCacheBaker *baker) psys_get_pointcache_start_end(scene, pid->calldata, &cache->startframe, &cache->endframe); } - if (((cache->flag & PTCACHE_BAKED) == 0) && (render || bake)) { + // XXX workaround for regression inroduced in ee3fadd, needs looking into + if (pid->type == PTCACHE_TYPE_RIGIDBODY) { + if ((cache->flag & PTCACHE_REDO_NEEDED || (cache->flag & PTCACHE_SIMULATION_VALID)==0) && (render || bake)) { + BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_ALL, 0); + } + } + else if (((cache->flag & PTCACHE_BAKED) == 0) && (render || bake)) { BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_ALL, 0); } diff --git a/source/blender/blenkernel/intern/property.c b/source/blender/blenkernel/intern/property.c index dc4063b42ed..b163f623d21 100644 --- a/source/blender/blenkernel/intern/property.c +++ b/source/blender/blenkernel/intern/property.c @@ -65,7 +65,7 @@ void BKE_bproperty_free_list(ListBase *lb) } } -bProperty *BKE_bproperty_copy(bProperty *prop) +bProperty *BKE_bproperty_copy(const bProperty *prop) { bProperty *propn; @@ -80,7 +80,7 @@ bProperty *BKE_bproperty_copy(bProperty *prop) return propn; } -void BKE_bproperty_copy_list(ListBase *lbn, ListBase *lbo) +void BKE_bproperty_copy_list(ListBase *lbn, const ListBase *lbo) { bProperty *prop, *propn; BKE_bproperty_free_list(lbn); /* in case we are copying to an object with props */ diff --git a/source/blender/blenkernel/intern/rigidbody.c b/source/blender/blenkernel/intern/rigidbody.c index b3a36bfb089..03eb83376e7 100644 --- a/source/blender/blenkernel/intern/rigidbody.c +++ b/source/blender/blenkernel/intern/rigidbody.c @@ -184,7 +184,7 @@ void BKE_rigidbody_free_constraint(Object *ob) * be added to relevant groups later... */ -RigidBodyOb *BKE_rigidbody_copy_object(Object *ob) +RigidBodyOb *BKE_rigidbody_copy_object(const Object *ob, const int UNUSED(flag)) { RigidBodyOb *rboN = NULL; @@ -204,7 +204,7 @@ RigidBodyOb *BKE_rigidbody_copy_object(Object *ob) return rboN; } -RigidBodyCon *BKE_rigidbody_copy_constraint(Object *ob) +RigidBodyCon *BKE_rigidbody_copy_constraint(const Object *ob, const int UNUSED(flag)) { RigidBodyCon *rbcN = NULL; @@ -291,8 +291,6 @@ static rbCollisionShape *rigidbody_get_shape_trimesh_from_mesh(Object *ob) if (dm == NULL) return NULL; - DM_ensure_looptri(dm); - mvert = dm->getVertArray(dm); totvert = dm->getNumVerts(dm); looptri = dm->getLoopTriArray(dm); @@ -524,8 +522,6 @@ void BKE_rigidbody_calc_volume(Object *ob, float *r_vol) if (dm == NULL) return; - DM_ensure_looptri(dm); - mvert = dm->getVertArray(dm); totvert = dm->getNumVerts(dm); lt = dm->getLoopTriArray(dm); @@ -609,8 +605,6 @@ void BKE_rigidbody_calc_center_of_mass(Object *ob, float r_center[3]) if (dm == NULL) return; - DM_ensure_looptri(dm); - mvert = dm->getVertArray(dm); totvert = dm->getNumVerts(dm); looptri = dm->getLoopTriArray(dm); @@ -945,24 +939,26 @@ RigidBodyWorld *BKE_rigidbody_create_world(Scene *scene) return rbw; } -RigidBodyWorld *BKE_rigidbody_world_copy(RigidBodyWorld *rbw) +RigidBodyWorld *BKE_rigidbody_world_copy(RigidBodyWorld *rbw, const int flag) { - RigidBodyWorld *rbwn = MEM_dupallocN(rbw); + RigidBodyWorld *rbw_copy = MEM_dupallocN(rbw); - if (rbw->effector_weights) - rbwn->effector_weights = MEM_dupallocN(rbw->effector_weights); - if (rbwn->group) - id_us_plus(&rbwn->group->id); - if (rbwn->constraints) - id_us_plus(&rbwn->constraints->id); + if (rbw->effector_weights) { + rbw_copy->effector_weights = MEM_dupallocN(rbw->effector_weights); + } + if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) { + id_us_plus((ID *)rbw_copy->group); + id_us_plus((ID *)rbw_copy->constraints); + } - rbwn->pointcache = BKE_ptcache_copy_list(&rbwn->ptcaches, &rbw->ptcaches, false); + /* XXX Never copy caches here? */ + rbw_copy->pointcache = BKE_ptcache_copy_list(&rbw_copy->ptcaches, &rbw->ptcaches, flag & ~LIB_ID_COPY_CACHES); - rbwn->objects = NULL; - rbwn->physics_world = NULL; - rbwn->numbodies = 0; + rbw_copy->objects = NULL; + rbw_copy->physics_world = NULL; + rbw_copy->numbodies = 0; - return rbwn; + return rbw_copy; } void BKE_rigidbody_world_groups_relink(RigidBodyWorld *rbw) @@ -1486,24 +1482,60 @@ void BKE_rigidbody_sync_transforms(RigidBodyWorld *rbw, Object *ob, float ctime) void BKE_rigidbody_aftertrans_update(Object *ob, float loc[3], float rot[3], float quat[4], float rotAxis[3], float rotAngle) { RigidBodyOb *rbo = ob->rigidbody_object; + bool correct_delta = !(rbo->flag & RBO_FLAG_KINEMATIC || rbo->type == RBO_TYPE_PASSIVE); /* return rigid body and object to their initial states */ copy_v3_v3(rbo->pos, ob->loc); copy_v3_v3(ob->loc, loc); + if (correct_delta) { + add_v3_v3(rbo->pos, ob->dloc); + } + if (ob->rotmode > 0) { - eulO_to_quat(rbo->orn, ob->rot, ob->rotmode); + float qt[4]; + eulO_to_quat(qt, ob->rot, ob->rotmode); + + if (correct_delta) { + float dquat[4]; + eulO_to_quat(dquat, ob->drot, ob->rotmode); + + mul_qt_qtqt(rbo->orn, dquat, qt); + } + else { + copy_qt_qt(rbo->orn, qt); + } + copy_v3_v3(ob->rot, rot); } else if (ob->rotmode == ROT_MODE_AXISANGLE) { - axis_angle_to_quat(rbo->orn, ob->rotAxis, ob->rotAngle); + float qt[4]; + axis_angle_to_quat(qt, ob->rotAxis, ob->rotAngle); + + if (correct_delta) { + float dquat[4]; + axis_angle_to_quat(dquat, ob->drotAxis, ob->drotAngle); + + mul_qt_qtqt(rbo->orn, dquat, qt); + } + else { + copy_qt_qt(rbo->orn, qt); + } + copy_v3_v3(ob->rotAxis, rotAxis); ob->rotAngle = rotAngle; } else { - copy_qt_qt(rbo->orn, ob->quat); + if (correct_delta) { + mul_qt_qtqt(rbo->orn, ob->dquat, ob->quat); + } + else { + copy_qt_qt(rbo->orn, ob->quat); + } + copy_qt_qt(ob->quat, quat); } + if (rbo->physics_object) { /* allow passive objects to return to original transform */ if (rbo->type == RBO_TYPE_PASSIVE) @@ -1515,8 +1547,9 @@ void BKE_rigidbody_aftertrans_update(Object *ob, float loc[3], float rot[3], flo void BKE_rigidbody_cache_reset(RigidBodyWorld *rbw) { - if (rbw) + if (rbw) { rbw->pointcache->flag |= PTCACHE_OUTDATED; + } } /* ------------------ */ @@ -1582,7 +1615,7 @@ void BKE_rigidbody_do_simulation(Scene *scene, float ctime) // RB_TODO deal with interpolated, old and baked results bool can_simulate = (ctime == rbw->ltime + 1) && !(cache->flag & PTCACHE_BAKED); - if (BKE_ptcache_read(&pid, ctime, can_simulate)) { + if (BKE_ptcache_read(&pid, ctime, can_simulate) == PTCACHE_READ_EXACT) { BKE_ptcache_validate(cache, (int)ctime); rbw->ltime = ctime; return; @@ -1622,13 +1655,13 @@ void BKE_rigidbody_do_simulation(Scene *scene, float ctime) # pragma GCC diagnostic ignored "-Wunused-parameter" #endif -struct RigidBodyOb *BKE_rigidbody_copy_object(Object *ob) { return NULL; } -struct RigidBodyCon *BKE_rigidbody_copy_constraint(Object *ob) { return NULL; } +struct RigidBodyOb *BKE_rigidbody_copy_object(const Object *ob, const int flag) { return NULL; } +struct RigidBodyCon *BKE_rigidbody_copy_constraint(const Object *ob, const int flag) { return NULL; } void BKE_rigidbody_validate_sim_world(Scene *scene, RigidBodyWorld *rbw, bool rebuild) {} void BKE_rigidbody_calc_volume(Object *ob, float *r_vol) { if (r_vol) *r_vol = 0.0f; } void BKE_rigidbody_calc_center_of_mass(Object *ob, float r_center[3]) { zero_v3(r_center); } struct RigidBodyWorld *BKE_rigidbody_create_world(Scene *scene) { return NULL; } -struct RigidBodyWorld *BKE_rigidbody_world_copy(RigidBodyWorld *rbw) { return NULL; } +struct RigidBodyWorld *BKE_rigidbody_world_copy(RigidBodyWorld *rbw, const int flag) { return NULL; } void BKE_rigidbody_world_groups_relink(struct RigidBodyWorld *rbw) {} void BKE_rigidbody_world_id_loop(struct RigidBodyWorld *rbw, RigidbodyWorldIDFunc func, void *userdata) {} struct RigidBodyOb *BKE_rigidbody_create_object(Scene *scene, Object *ob, short type) { return NULL; } diff --git a/source/blender/blenkernel/intern/sca.c b/source/blender/blenkernel/intern/sca.c index 7920d8b5696..fb81ed4d47f 100644 --- a/source/blender/blenkernel/intern/sca.c +++ b/source/blender/blenkernel/intern/sca.c @@ -72,7 +72,7 @@ void free_sensors(ListBase *lb) } } -bSensor *copy_sensor(bSensor *sens) +bSensor *copy_sensor(bSensor *sens, const int UNUSED(flag)) { bSensor *sensn; @@ -87,14 +87,14 @@ bSensor *copy_sensor(bSensor *sens) return sensn; } -void copy_sensors(ListBase *lbn, ListBase *lbo) +void copy_sensors(ListBase *lbn, const ListBase *lbo, const int flag) { bSensor *sens, *sensn; lbn->first= lbn->last= NULL; sens= lbo->first; while (sens) { - sensn= copy_sensor(sens); + sensn= copy_sensor(sens, flag); BLI_addtail(lbn, sensn); sens= sens->next; } @@ -234,7 +234,7 @@ void free_controllers(ListBase *lb) } } -bController *copy_controller(bController *cont) +bController *copy_controller(bController *cont, const int UNUSED(flag)) { bController *contn; @@ -251,14 +251,14 @@ bController *copy_controller(bController *cont) return contn; } -void copy_controllers(ListBase *lbn, ListBase *lbo) +void copy_controllers(ListBase *lbn, const ListBase *lbo, const int flag) { bController *cont, *contn; lbn->first= lbn->last= NULL; cont= lbo->first; while (cont) { - contn= copy_controller(cont); + contn= copy_controller(cont, flag); BLI_addtail(lbn, contn); cont= cont->next; } @@ -359,7 +359,7 @@ void free_actuators(ListBase *lb) } } -bActuator *copy_actuator(bActuator *act) +bActuator *copy_actuator(bActuator *act, const int flag) { bActuator *actn; @@ -374,29 +374,31 @@ bActuator *copy_actuator(bActuator *act) case ACT_SHAPEACTION: { bActionActuator *aa = (bActionActuator *)act->data; - if (aa->act) + if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) { id_us_plus((ID *)aa->act); + } break; } case ACT_SOUND: { bSoundActuator *sa = (bSoundActuator *)act->data; - if (sa->sound) + if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) { id_us_plus((ID *)sa->sound); + } break; } } return actn; } -void copy_actuators(ListBase *lbn, ListBase *lbo) +void copy_actuators(ListBase *lbn, const ListBase *lbo, const int flag) { bActuator *act, *actn; lbn->first= lbn->last= NULL; act= lbo->first; while (act) { - actn= copy_actuator(act); + actn= copy_actuator(act, flag); BLI_addtail(lbn, actn); act= act->next; } @@ -783,11 +785,11 @@ void BKE_sca_logic_links_remap(Main *bmain, Object *ob_old, Object *ob_new) * Handle the copying of logic data into a new object, including internal logic links update. * External links (links between logic bricks of different objects) must be handled separately. */ -void BKE_sca_logic_copy(Object *ob_new, Object *ob) +void BKE_sca_logic_copy(Object *ob_new, const Object *ob, const int flag) { - copy_sensors(&ob_new->sensors, &ob->sensors); - copy_controllers(&ob_new->controllers, &ob->controllers); - copy_actuators(&ob_new->actuators, &ob->actuators); + copy_sensors(&ob_new->sensors, &ob->sensors, flag); + copy_controllers(&ob_new->controllers, &ob->controllers, flag); + copy_actuators(&ob_new->actuators, &ob->actuators, flag); for (bSensor *sens = ob_new->sensors.first; sens; sens = sens->next) { if (sens->flag & SENS_NEW) { diff --git a/source/blender/blenkernel/intern/scene.c b/source/blender/blenkernel/intern/scene.c index 5933aaccd66..b8ad54dc533 100644 --- a/source/blender/blenkernel/intern/scene.c +++ b/source/blender/blenkernel/intern/scene.c @@ -154,213 +154,316 @@ static void remove_sequencer_fcurves(Scene *sce) } } -Scene *BKE_scene_copy(Main *bmain, Scene *sce, int type) -{ - Scene *scen; - SceneRenderLayer *srl, *new_srl; - FreestyleLineSet *lineset; - ToolSettings *ts; - Base *base, *obase; - - if (type == SCE_COPY_EMPTY) { - ListBase rl, rv; - scen = BKE_scene_add(bmain, sce->id.name + 2); - - rl = scen->r.layers; - rv = scen->r.views; - curvemapping_free_data(&scen->r.mblur_shutter_curve); - scen->r = sce->r; - scen->r.layers = rl; - scen->r.actlay = 0; - scen->r.views = rv; - scen->unit = sce->unit; - scen->physics_settings = sce->physics_settings; - scen->gm = sce->gm; - scen->audio = sce->audio; - - if (sce->id.properties) - scen->id.properties = IDP_CopyProperty(sce->id.properties); - - MEM_freeN(scen->toolsettings); - BKE_sound_destroy_scene(scen); - } - else { - scen = BKE_libblock_copy(bmain, &sce->id); - BLI_duplicatelist(&(scen->base), &(sce->base)); - - id_us_plus((ID *)scen->world); - id_us_plus((ID *)scen->set); - /* id_us_plus((ID *)scen->gm.dome.warptext); */ /* XXX Not refcounted? see readfile.c */ - - scen->ed = NULL; - scen->theDag = NULL; - scen->depsgraph = NULL; - scen->obedit = NULL; - scen->stats = NULL; - scen->fps_info = NULL; - - if (sce->rigidbody_world) - scen->rigidbody_world = BKE_rigidbody_world_copy(sce->rigidbody_world); - - BLI_duplicatelist(&(scen->markers), &(sce->markers)); - BLI_duplicatelist(&(scen->transform_spaces), &(sce->transform_spaces)); - BLI_duplicatelist(&(scen->r.layers), &(sce->r.layers)); - BLI_duplicatelist(&(scen->r.views), &(sce->r.views)); - BKE_keyingsets_copy(&(scen->keyingsets), &(sce->keyingsets)); - - if (sce->nodetree) { - /* ID's are managed on both copy and switch */ - scen->nodetree = ntreeCopyTree(bmain, sce->nodetree); - BKE_libblock_relink_ex(bmain, scen->nodetree, &sce->id, &scen->id, false); +/** + * Only copy internal data of Scene ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_scene_copy_data(Main *bmain, Scene *sce_dst, const Scene *sce_src, const int flag) +{ + /* We never handle usercount here for own data. */ + const int flag_subdata = flag | LIB_ID_CREATE_NO_USER_REFCOUNT; + + sce_dst->ed = NULL; + sce_dst->theDag = NULL; + sce_dst->depsgraph = NULL; + sce_dst->obedit = NULL; + sce_dst->stats = NULL; + sce_dst->fps_info = NULL; + + BLI_duplicatelist(&(sce_dst->base), &(sce_src->base)); + for (Base *base_dst = sce_dst->base.first, *base_src = sce_src->base.first; + base_dst; + base_dst = base_dst->next, base_src = base_src->next) + { + if (base_src == sce_src->basact) { + sce_dst->basact = base_dst; } + } - obase = sce->base.first; - base = scen->base.first; - while (base) { - id_us_plus(&base->object->id); - if (obase == sce->basact) scen->basact = base; - - obase = obase->next; - base = base->next; - } + BLI_duplicatelist(&(sce_dst->markers), &(sce_src->markers)); + BLI_duplicatelist(&(sce_dst->transform_spaces), &(sce_src->transform_spaces)); + BLI_duplicatelist(&(sce_dst->r.layers), &(sce_src->r.layers)); + BLI_duplicatelist(&(sce_dst->r.views), &(sce_src->r.views)); + BKE_keyingsets_copy(&(sce_dst->keyingsets), &(sce_src->keyingsets)); - /* copy action and remove animation used by sequencer */ - BKE_animdata_copy_id_action(&scen->id, false); + if (sce_src->nodetree) { + BKE_id_copy_ex(bmain, (ID *)sce_src->nodetree, (ID **)&sce_dst->nodetree, flag, false); + BKE_libblock_relink_ex(bmain, sce_dst->nodetree, (void *)(&sce_src->id), &sce_dst->id, false); + } - if (type != SCE_COPY_FULL) - remove_sequencer_fcurves(scen); + if (sce_src->rigidbody_world) { + sce_dst->rigidbody_world = BKE_rigidbody_world_copy(sce_src->rigidbody_world, flag_subdata); + } - /* copy Freestyle settings */ - new_srl = scen->r.layers.first; - for (srl = sce->r.layers.first; srl; srl = srl->next) { - if (new_srl->prop != NULL) { - new_srl->prop = IDP_CopyProperty(new_srl->prop); - } - BKE_freestyle_config_copy(&new_srl->freestyleConfig, &srl->freestyleConfig); - if (type == SCE_COPY_FULL) { - for (lineset = new_srl->freestyleConfig.linesets.first; lineset; lineset = lineset->next) { - if (lineset->linestyle) { - id_us_plus((ID *)lineset->linestyle); - lineset->linestyle = BKE_linestyle_copy(bmain, lineset->linestyle); - } - } - } - new_srl = new_srl->next; + /* copy Freestyle settings */ + for (SceneRenderLayer *srl_dst = sce_dst->r.layers.first, *srl_src = sce_src->r.layers.first; + srl_src; + srl_dst = srl_dst->next, srl_src = srl_src->next) + { + if (srl_dst->prop != NULL) { + srl_dst->prop = IDP_CopyProperty_ex(srl_dst->prop, flag_subdata); } + BKE_freestyle_config_copy(&srl_dst->freestyleConfig, &srl_src->freestyleConfig, flag_subdata); } /* copy color management settings */ - 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_colorspace_settings_copy(&scen->sequencer_colorspace_settings, &sce->sequencer_colorspace_settings); + BKE_color_managed_display_settings_copy(&sce_dst->display_settings, &sce_src->display_settings); + BKE_color_managed_view_settings_copy(&sce_dst->view_settings, &sce_src->view_settings); + BKE_color_managed_colorspace_settings_copy(&sce_dst->sequencer_colorspace_settings, &sce_src->sequencer_colorspace_settings); - BKE_color_managed_display_settings_copy(&scen->r.im_format.display_settings, &sce->r.im_format.display_settings); - BKE_color_managed_view_settings_copy(&scen->r.im_format.view_settings, &sce->r.im_format.view_settings); + BKE_color_managed_display_settings_copy(&sce_dst->r.im_format.display_settings, &sce_src->r.im_format.display_settings); + BKE_color_managed_view_settings_copy(&sce_dst->r.im_format.view_settings, &sce_src->r.im_format.view_settings); - BKE_color_managed_display_settings_copy(&scen->r.bake.im_format.display_settings, &sce->r.bake.im_format.display_settings); - BKE_color_managed_view_settings_copy(&scen->r.bake.im_format.view_settings, &sce->r.bake.im_format.view_settings); + BKE_color_managed_display_settings_copy(&sce_dst->r.bake.im_format.display_settings, &sce_src->r.bake.im_format.display_settings); + BKE_color_managed_view_settings_copy(&sce_dst->r.bake.im_format.view_settings, &sce_src->r.bake.im_format.view_settings); - curvemapping_copy_data(&scen->r.mblur_shutter_curve, &sce->r.mblur_shutter_curve); + curvemapping_copy_data(&sce_dst->r.mblur_shutter_curve, &sce_src->r.mblur_shutter_curve); /* tool settings */ - scen->toolsettings = MEM_dupallocN(sce->toolsettings); - - ts = scen->toolsettings; - if (ts) { + if (sce_dst->toolsettings != NULL) { + ToolSettings *ts = sce_dst->toolsettings = MEM_dupallocN(sce_dst->toolsettings); if (ts->vpaint) { ts->vpaint = MEM_dupallocN(ts->vpaint); ts->vpaint->paintcursor = NULL; ts->vpaint->vpaint_prev = NULL; ts->vpaint->wpaint_prev = NULL; - BKE_paint_copy(&ts->vpaint->paint, &ts->vpaint->paint); + BKE_paint_copy(&ts->vpaint->paint, &ts->vpaint->paint, flag_subdata); } if (ts->wpaint) { ts->wpaint = MEM_dupallocN(ts->wpaint); ts->wpaint->paintcursor = NULL; ts->wpaint->vpaint_prev = NULL; ts->wpaint->wpaint_prev = NULL; - BKE_paint_copy(&ts->wpaint->paint, &ts->wpaint->paint); + BKE_paint_copy(&ts->wpaint->paint, &ts->wpaint->paint, flag_subdata); } if (ts->sculpt) { ts->sculpt = MEM_dupallocN(ts->sculpt); - BKE_paint_copy(&ts->sculpt->paint, &ts->sculpt->paint); + BKE_paint_copy(&ts->sculpt->paint, &ts->sculpt->paint, flag_subdata); + } + if (ts->uvsculpt) { + ts->uvsculpt = MEM_dupallocN(ts->uvsculpt); + BKE_paint_copy(&ts->uvsculpt->paint, &ts->uvsculpt->paint, flag_subdata); } - BKE_paint_copy(&ts->imapaint.paint, &ts->imapaint.paint); + BKE_paint_copy(&ts->imapaint.paint, &ts->imapaint.paint, flag_subdata); ts->imapaint.paintcursor = NULL; - id_us_plus((ID *)ts->imapaint.stencil); ts->particle.paintcursor = NULL; - + ts->particle.scene = NULL; + ts->particle.object = NULL; + /* duplicate Grease Pencil Drawing Brushes */ BLI_listbase_clear(&ts->gp_brushes); - for (bGPDbrush *brush = sce->toolsettings->gp_brushes.first; brush; brush = brush->next) { + for (bGPDbrush *brush = sce_src->toolsettings->gp_brushes.first; brush; brush = brush->next) { bGPDbrush *newbrush = BKE_gpencil_brush_duplicate(brush); BLI_addtail(&ts->gp_brushes, newbrush); } - + /* duplicate Grease Pencil interpolation curve */ ts->gp_interpolate.custom_ipo = curvemapping_copy(ts->gp_interpolate.custom_ipo); } - + /* make a private copy of the avicodecdata */ - if (sce->r.avicodecdata) { - scen->r.avicodecdata = MEM_dupallocN(sce->r.avicodecdata); - scen->r.avicodecdata->lpFormat = MEM_dupallocN(scen->r.avicodecdata->lpFormat); - scen->r.avicodecdata->lpParms = MEM_dupallocN(scen->r.avicodecdata->lpParms); + if (sce_src->r.avicodecdata) { + sce_dst->r.avicodecdata = MEM_dupallocN(sce_src->r.avicodecdata); + sce_dst->r.avicodecdata->lpFormat = MEM_dupallocN(sce_dst->r.avicodecdata->lpFormat); + sce_dst->r.avicodecdata->lpParms = MEM_dupallocN(sce_dst->r.avicodecdata->lpParms); } - + /* make a private copy of the qtcodecdata */ - if (sce->r.qtcodecdata) { - scen->r.qtcodecdata = MEM_dupallocN(sce->r.qtcodecdata); - scen->r.qtcodecdata->cdParms = MEM_dupallocN(scen->r.qtcodecdata->cdParms); + if (sce_src->r.qtcodecdata) { + sce_dst->r.qtcodecdata = MEM_dupallocN(sce_src->r.qtcodecdata); + sce_dst->r.qtcodecdata->cdParms = MEM_dupallocN(sce_dst->r.qtcodecdata->cdParms); } - - if (sce->r.ffcodecdata.properties) { /* intentionally check scen not sce. */ - scen->r.ffcodecdata.properties = IDP_CopyProperty(sce->r.ffcodecdata.properties); + + if (sce_src->r.ffcodecdata.properties) { /* intentionally check sce_dst not sce_src. */ /* XXX ??? comment outdated... */ + sce_dst->r.ffcodecdata.properties = IDP_CopyProperty_ex(sce_src->r.ffcodecdata.properties, flag_subdata); } - /* NOTE: part of SCE_COPY_LINK_DATA and SCE_COPY_FULL operations - * are done outside of blenkernel with ED_objects_single_users! */ + /* before scene copy */ + BKE_sound_create_scene(sce_dst); - /* camera */ - if (type == SCE_COPY_LINK_DATA || type == SCE_COPY_FULL) { - ID_NEW_REMAP(scen->camera); + /* Copy sequencer, this is local data! */ + if (sce_src->ed) { + sce_dst->ed = MEM_callocN(sizeof(*sce_dst->ed), __func__); + sce_dst->ed->seqbasep = &sce_dst->ed->seqbase; + BKE_sequence_base_dupli_recursive( + sce_src, sce_dst, &sce_dst->ed->seqbase, &sce_src->ed->seqbase, SEQ_DUPE_ALL, flag_subdata); } - - /* before scene copy */ - BKE_sound_create_scene(scen); - /* world */ - if (type == SCE_COPY_FULL) { - if (scen->world) { - id_us_plus((ID *)scen->world); - scen->world = BKE_world_copy(bmain, scen->world); - BKE_animdata_copy_id_action((ID *)scen->world, false); + if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0) { + BKE_previewimg_id_copy(&sce_dst->id, &sce_src->id); + } + else { + sce_dst->preview = NULL; + } +} + +Scene *BKE_scene_copy(Main *bmain, Scene *sce, int type) +{ + Scene *sce_copy; + + /* TODO this should/could most likely be replaced by call to more generic code at some point... + * But for now, let's keep it well isolated here. */ + if (type == SCE_COPY_EMPTY) { + ToolSettings *ts; + ListBase rl, rv; + + sce_copy = BKE_scene_add(bmain, sce->id.name + 2); + + rl = sce_copy->r.layers; + rv = sce_copy->r.views; + curvemapping_free_data(&sce_copy->r.mblur_shutter_curve); + sce_copy->r = sce->r; + sce_copy->r.layers = rl; + sce_copy->r.actlay = 0; + sce_copy->r.views = rv; + sce_copy->unit = sce->unit; + sce_copy->physics_settings = sce->physics_settings; + sce_copy->gm = sce->gm; + sce_copy->audio = sce->audio; + + if (sce->id.properties) + sce_copy->id.properties = IDP_CopyProperty(sce->id.properties); + + MEM_freeN(sce_copy->toolsettings); + BKE_sound_destroy_scene(sce_copy); + + /* copy color management settings */ + BKE_color_managed_display_settings_copy(&sce_copy->display_settings, &sce->display_settings); + BKE_color_managed_view_settings_copy(&sce_copy->view_settings, &sce->view_settings); + BKE_color_managed_colorspace_settings_copy(&sce_copy->sequencer_colorspace_settings, &sce->sequencer_colorspace_settings); + + BKE_color_managed_display_settings_copy(&sce_copy->r.im_format.display_settings, &sce->r.im_format.display_settings); + BKE_color_managed_view_settings_copy(&sce_copy->r.im_format.view_settings, &sce->r.im_format.view_settings); + + BKE_color_managed_display_settings_copy(&sce_copy->r.bake.im_format.display_settings, &sce->r.bake.im_format.display_settings); + BKE_color_managed_view_settings_copy(&sce_copy->r.bake.im_format.view_settings, &sce->r.bake.im_format.view_settings); + + curvemapping_copy_data(&sce_copy->r.mblur_shutter_curve, &sce->r.mblur_shutter_curve); + + /* tool settings */ + sce_copy->toolsettings = MEM_dupallocN(sce->toolsettings); + + ts = sce_copy->toolsettings; + if (ts) { + if (ts->vpaint) { + ts->vpaint = MEM_dupallocN(ts->vpaint); + ts->vpaint->paintcursor = NULL; + ts->vpaint->vpaint_prev = NULL; + ts->vpaint->wpaint_prev = NULL; + BKE_paint_copy(&ts->vpaint->paint, &ts->vpaint->paint, 0); + } + if (ts->wpaint) { + ts->wpaint = MEM_dupallocN(ts->wpaint); + ts->wpaint->paintcursor = NULL; + ts->wpaint->vpaint_prev = NULL; + ts->wpaint->wpaint_prev = NULL; + BKE_paint_copy(&ts->wpaint->paint, &ts->wpaint->paint, 0); + } + if (ts->sculpt) { + ts->sculpt = MEM_dupallocN(ts->sculpt); + BKE_paint_copy(&ts->sculpt->paint, &ts->sculpt->paint, 0); + } + if (ts->uvsculpt) { + ts->uvsculpt = MEM_dupallocN(ts->uvsculpt); + BKE_paint_copy(&ts->uvsculpt->paint, &ts->uvsculpt->paint, 0); + } + + BKE_paint_copy(&ts->imapaint.paint, &ts->imapaint.paint, 0); + ts->imapaint.paintcursor = NULL; + id_us_plus((ID *)ts->imapaint.stencil); + id_us_plus((ID *)ts->imapaint.clone); + id_us_plus((ID *)ts->imapaint.canvas); + ts->particle.paintcursor = NULL; + ts->particle.scene = NULL; + ts->particle.object = NULL; + + /* duplicate Grease Pencil Drawing Brushes */ + BLI_listbase_clear(&ts->gp_brushes); + for (bGPDbrush *brush = sce->toolsettings->gp_brushes.first; brush; brush = brush->next) { + bGPDbrush *newbrush = BKE_gpencil_brush_duplicate(brush); + BLI_addtail(&ts->gp_brushes, newbrush); + } + + /* duplicate Grease Pencil interpolation curve */ + ts->gp_interpolate.custom_ipo = curvemapping_copy(ts->gp_interpolate.custom_ipo); + } + + /* make a private copy of the avicodecdata */ + if (sce->r.avicodecdata) { + sce_copy->r.avicodecdata = MEM_dupallocN(sce->r.avicodecdata); + sce_copy->r.avicodecdata->lpFormat = MEM_dupallocN(sce_copy->r.avicodecdata->lpFormat); + sce_copy->r.avicodecdata->lpParms = MEM_dupallocN(sce_copy->r.avicodecdata->lpParms); + } + + /* make a private copy of the qtcodecdata */ + if (sce->r.qtcodecdata) { + sce_copy->r.qtcodecdata = MEM_dupallocN(sce->r.qtcodecdata); + sce_copy->r.qtcodecdata->cdParms = MEM_dupallocN(sce_copy->r.qtcodecdata->cdParms); } - if (sce->ed) { - scen->ed = MEM_callocN(sizeof(Editing), "addseq"); - scen->ed->seqbasep = &scen->ed->seqbase; - BKE_sequence_base_dupli_recursive(sce, scen, &scen->ed->seqbase, &sce->ed->seqbase, SEQ_DUPE_ALL); + if (sce->r.ffcodecdata.properties) { /* intentionally check scen not sce. */ + sce_copy->r.ffcodecdata.properties = IDP_CopyProperty(sce->r.ffcodecdata.properties); } + + /* before scene copy */ + BKE_sound_create_scene(sce_copy); + + /* grease pencil */ + sce_copy->gpd = NULL; + + sce_copy->preview = NULL; + + return sce_copy; } - - /* grease pencil */ - if (scen->gpd) { + else { + BKE_id_copy_ex(bmain, (ID *)sce, (ID **)&sce_copy, LIB_ID_COPY_ACTIONS, false); + + /* Extra actions, most notably SCE_FULL_COPY also duplicates several 'children' datablocks... */ + if (type == SCE_COPY_FULL) { - scen->gpd = BKE_gpencil_data_duplicate(bmain, scen->gpd, false); - } - else if (type == SCE_COPY_EMPTY) { - scen->gpd = NULL; + /* Copy Freestyle LineStyle datablocks. */ + for (SceneRenderLayer *srl_dst = sce_copy->r.layers.first; srl_dst; srl_dst = srl_dst->next) { + for (FreestyleLineSet *lineset = srl_dst->freestyleConfig.linesets.first; lineset; lineset = lineset->next) { + if (lineset->linestyle) { + /* XXX Not copying anim/actions here? */ + BKE_id_copy_ex(bmain, (ID *)lineset->linestyle, (ID **)&lineset->linestyle, 0, false); + } + } + } + + /* Full copy of world (included animations) */ + if (sce_copy->world) { + BKE_id_copy_ex(bmain, (ID *)sce_copy->world, (ID **)&sce_copy->world, LIB_ID_COPY_ACTIONS, false); + } + + /* Full copy of GreasePencil. */ + /* XXX Not copying anim/actions here? */ + if (sce_copy->gpd) { + BKE_id_copy_ex(bmain, (ID *)sce_copy->gpd, (ID **)&sce_copy->gpd, 0, false); + } } else { - id_us_plus((ID *)scen->gpd); + /* Remove sequencer if not full copy */ + /* XXX Why in Hell? :/ */ + remove_sequencer_fcurves(sce_copy); + BKE_sequencer_editing_free(sce_copy); } - } - BKE_previewimg_id_copy(&scen->id, &sce->id); + /* NOTE: part of SCE_COPY_LINK_DATA and SCE_COPY_FULL operations + * are done outside of blenkernel with ED_objects_single_users! */ + + /* camera */ + if (ELEM(type, SCE_COPY_LINK_DATA, SCE_COPY_FULL)) { + ID_NEW_REMAP(sce_copy->camera); + } - return scen; + return sce_copy; + } } void BKE_scene_groups_relink(Scene *sce) @@ -573,7 +676,7 @@ void BKE_scene_init(Scene *sce) sce->r.seq_prev_type = OB_SOLID; sce->r.seq_rend_type = OB_SOLID; - sce->r.seq_flag = R_SEQ_GL_PREV; + sce->r.seq_flag = 0; sce->r.threads = 1; @@ -833,7 +936,7 @@ Scene *BKE_scene_add(Main *bmain, const char *name) { Scene *sce; - sce = BKE_libblock_alloc(bmain, ID_SCE, name); + sce = BKE_libblock_alloc(bmain, ID_SCE, name, 0); id_us_min(&sce->id); id_us_ensure_real(&sce->id); @@ -2137,7 +2240,7 @@ bool BKE_scene_remove_render_view(Scene *scene, SceneRenderView *srv) int get_render_subsurf_level(const RenderData *r, int lvl, bool for_render) { - if (r->mode & R_SIMPLIFY) { + if (r->mode & R_SIMPLIFY) { if (for_render) return min_ii(r->simplify_subsurf_render, lvl); else @@ -2308,6 +2411,14 @@ int BKE_scene_num_threads(const Scene *scene) return BKE_render_num_threads(&scene->r); } +int BKE_render_preview_pixel_size(const RenderData *r) +{ + if (r->preview_pixel_size == 0) { + return (U.pixelsize > 1.5f)? 2 : 1; + } + return r->preview_pixel_size; +} + /* Apply the needed correction factor to value, based on unit_type (only length-related are affected currently) * and unit->scale_length. */ diff --git a/source/blender/blenkernel/intern/screen.c b/source/blender/blenkernel/intern/screen.c index 857bd5447c8..df47b89fadc 100644 --- a/source/blender/blenkernel/intern/screen.c +++ b/source/blender/blenkernel/intern/screen.c @@ -181,6 +181,7 @@ ARegion *BKE_area_region_copy(SpaceType *st, ARegion *ar) BLI_listbase_clear(&newar->ui_lists); newar->swinid = 0; newar->regiontimer = NULL; + newar->headerstr = NULL; /* use optional regiondata callback */ if (ar->regiondata) { diff --git a/source/blender/blenkernel/intern/seqeffects.c b/source/blender/blenkernel/intern/seqeffects.c index 298671beedb..e435d87024e 100644 --- a/source/blender/blenkernel/intern/seqeffects.c +++ b/source/blender/blenkernel/intern/seqeffects.c @@ -684,7 +684,7 @@ static float invGammaCorrect(float c) else if (i >= RE_GAMMA_TABLE_SIZE) res = powf(c, valid_inv_gamma); else res = inv_gamma_range_table[i] + ((c - color_domain_table[i]) * inv_gamfactor_table[i]); - + return res; } diff --git a/source/blender/blenkernel/intern/sequencer.c b/source/blender/blenkernel/intern/sequencer.c index 2de7cd49901..05ce9c4bbb6 100644 --- a/source/blender/blenkernel/intern/sequencer.c +++ b/source/blender/blenkernel/intern/sequencer.c @@ -377,6 +377,8 @@ static void seqclipboard_ptr_restore(Main *bmain, ID **id_pt) } break; } + default: + break; } } @@ -480,9 +482,12 @@ void BKE_sequencer_editing_free(Scene *scene) static void sequencer_imbuf_assign_spaces(Scene *scene, ImBuf *ibuf) { +#if 0 + /* Bute buffer is supposed to be in sequencer working space already. */ if (ibuf->rect != NULL) { IMB_colormanagement_assign_rect_colorspace(ibuf, scene->sequencer_colorspace_settings.name); } +#endif if (ibuf->rect_float != NULL) { IMB_colormanagement_assign_float_colorspace(ibuf, scene->sequencer_colorspace_settings.name); } @@ -1775,7 +1780,7 @@ static ImBuf *seq_proxy_fetch(const SeqRenderData *context, Sequence *seq, int c if (proxy->anim == NULL) { return NULL; } - + seq_open_anim_file(context->scene, seq, true); sanim = seq->anims.first; @@ -1783,7 +1788,7 @@ static ImBuf *seq_proxy_fetch(const SeqRenderData *context, Sequence *seq, int c return IMB_anim_absolute(proxy->anim, frameno, IMB_TC_NONE, IMB_PROXY_NONE); } - + if (seq_proxy_get_fname(ed, seq, cfra, render_size, name, context->view_id) == 0) { return NULL; } @@ -2082,7 +2087,7 @@ void BKE_sequencer_proxy_set(struct Sequence *seq, bool value) } } else { - seq->flag ^= SEQ_USE_PROXY; + seq->flag &= ~SEQ_USE_PROXY; } } @@ -3233,7 +3238,7 @@ static ImBuf *seq_render_scene_strip(const SeqRenderData *context, Sequence *seq const bool is_background = G.background; const bool do_seq_gl = is_rendering ? 0 /* (context->scene->r.seq_flag & R_SEQ_GL_REND) */ : - (context->scene->r.seq_flag & R_SEQ_GL_PREV) != 0; + (context->scene->r.seq_prev_type) != OB_RENDER; // bool have_seq = false; /* UNUSED */ bool have_comp = false; bool use_gpencil = true; @@ -4190,9 +4195,10 @@ static bool update_changed_seq_recurs(Scene *scene, Sequence *seq, Sequence *cha if (free_imbuf) { if (ibuf_change) { - if (seq->type == SEQ_TYPE_MOVIE) + if (seq->type == SEQ_TYPE_MOVIE) { BKE_sequence_free_anim(seq); - if (seq->type == SEQ_TYPE_SPEED) { + } + else if (seq->type == SEQ_TYPE_SPEED) { BKE_sequence_effect_speed_rebuild_map(scene, seq, true); } } @@ -5182,6 +5188,7 @@ Sequence *BKE_sequencer_add_sound_strip(bContext *C, ListBase *seqbasep, SeqLoad sound = BKE_sound_new_file(bmain, seq_load->path); /* handles relative paths */ if (sound->playback_handle == NULL) { + BKE_libblock_free(bmain, sound); #if 0 if (op) BKE_report(op->reports, RPT_ERROR, "Unsupported audio format"); @@ -5369,9 +5376,8 @@ Sequence *BKE_sequencer_add_movie_strip(bContext *C, ListBase *seqbasep, SeqLoad return seq; } -static Sequence *seq_dupli(Scene *scene, Scene *scene_to, Sequence *seq, int dupe_flag) +static Sequence *seq_dupli(const Scene *scene_src, Scene *scene_dst, Sequence *seq, int dupe_flag, const int flag) { - Scene *sce_audio = scene_to ? scene_to : scene; Sequence *seqn = MEM_dupallocN(seq); seq->tmp = seqn; @@ -5395,7 +5401,7 @@ static Sequence *seq_dupli(Scene *scene, Scene *scene_to, Sequence *seq, int dup } if (seq->prop) { - seqn->prop = IDP_CopyProperty(seq->prop); + seqn->prop = IDP_CopyProperty_ex(seq->prop, flag); } if (seqn->modifiers.first) { @@ -5414,7 +5420,7 @@ static Sequence *seq_dupli(Scene *scene, Scene *scene_to, Sequence *seq, int dup else if (seq->type == SEQ_TYPE_SCENE) { seqn->strip->stripdata = NULL; if (seq->scene_sound) - seqn->scene_sound = BKE_sound_scene_add_scene_sound_defaults(sce_audio, seqn); + seqn->scene_sound = BKE_sound_scene_add_scene_sound_defaults(scene_dst, seqn); } else if (seq->type == SEQ_TYPE_MOVIECLIP) { /* avoid assert */ @@ -5431,9 +5437,11 @@ static Sequence *seq_dupli(Scene *scene, Scene *scene_to, Sequence *seq, int dup seqn->strip->stripdata = MEM_dupallocN(seq->strip->stripdata); if (seq->scene_sound) - seqn->scene_sound = BKE_sound_add_scene_sound_defaults(sce_audio, seqn); + seqn->scene_sound = BKE_sound_add_scene_sound_defaults(scene_dst, seqn); - id_us_plus((ID *)seqn->sound); + if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) { + id_us_plus((ID *)seqn->sound); + } } else if (seq->type == SEQ_TYPE_IMAGE) { seqn->strip->stripdata = @@ -5453,11 +5461,15 @@ static Sequence *seq_dupli(Scene *scene, Scene *scene_to, Sequence *seq, int dup BLI_assert(0); } - if (dupe_flag & SEQ_DUPE_UNIQUE_NAME) - BKE_sequence_base_unique_name_recursive(&scene->ed->seqbase, seqn); + if (scene_src == scene_dst) { + if (dupe_flag & SEQ_DUPE_UNIQUE_NAME) { + BKE_sequence_base_unique_name_recursive(&scene_dst->ed->seqbase, seqn); + } - if (dupe_flag & SEQ_DUPE_ANIM) - BKE_sequencer_dupe_animdata(scene, seq->name + 2, seqn->name + 2); + if (dupe_flag & SEQ_DUPE_ANIM) { + BKE_sequencer_dupe_animdata(scene_dst, seq->name + 2, seqn->name + 2); + } + } return seqn; } @@ -5484,16 +5496,16 @@ static void seq_new_fix_links_recursive(Sequence *seq) } } -Sequence *BKE_sequence_dupli_recursive(Scene *scene, Scene *scene_to, Sequence *seq, int dupe_flag) +Sequence *BKE_sequence_dupli_recursive(const Scene *scene_src, Scene *scene_dst, Sequence *seq, int dupe_flag) { Sequence *seqn; seq->tmp = NULL; - seqn = seq_dupli(scene, scene_to, seq, dupe_flag); + seqn = seq_dupli(scene_src, scene_dst, seq, dupe_flag, 0); if (seq->type == SEQ_TYPE_META) { Sequence *s; for (s = seq->seqbase.first; s; s = s->next) { - Sequence *n = BKE_sequence_dupli_recursive(scene, scene_to, s, dupe_flag); + Sequence *n = BKE_sequence_dupli_recursive(scene_src, scene_dst, s, dupe_flag); if (n) { BLI_addtail(&seqn->seqbase, n); } @@ -5506,19 +5518,19 @@ Sequence *BKE_sequence_dupli_recursive(Scene *scene, Scene *scene_to, Sequence * } void BKE_sequence_base_dupli_recursive( - Scene *scene, Scene *scene_to, ListBase *nseqbase, ListBase *seqbase, - int dupe_flag) + const Scene *scene_src, Scene *scene_dst, ListBase *nseqbase, const ListBase *seqbase, + int dupe_flag, const int flag) { Sequence *seq; Sequence *seqn = NULL; - Sequence *last_seq = BKE_sequencer_active_get(scene); + Sequence *last_seq = BKE_sequencer_active_get((Scene *)scene_src); /* always include meta's strips */ int dupe_flag_recursive = dupe_flag | SEQ_DUPE_ALL; for (seq = seqbase->first; seq; seq = seq->next) { seq->tmp = NULL; if ((seq->flag & SELECT) || (dupe_flag & SEQ_DUPE_ALL)) { - seqn = seq_dupli(scene, scene_to, seq, dupe_flag); + seqn = seq_dupli(scene_src, scene_dst, seq, dupe_flag, flag); if (seqn) { /*should never fail */ if (dupe_flag & SEQ_DUPE_CONTEXT) { seq->flag &= ~SEQ_ALLSEL; @@ -5528,13 +5540,13 @@ void BKE_sequence_base_dupli_recursive( BLI_addtail(nseqbase, seqn); if (seq->type == SEQ_TYPE_META) { BKE_sequence_base_dupli_recursive( - scene, scene_to, &seqn->seqbase, &seq->seqbase, - dupe_flag_recursive); + scene_src, scene_dst, &seqn->seqbase, &seq->seqbase, + dupe_flag_recursive, flag); } if (dupe_flag & SEQ_DUPE_CONTEXT) { if (seq == last_seq) { - BKE_sequencer_active_set(scene, seqn); + BKE_sequencer_active_set(scene_dst, seqn); } } } diff --git a/source/blender/blenkernel/intern/shrinkwrap.c b/source/blender/blenkernel/intern/shrinkwrap.c index 7094d5a3547..f9d1793d7cb 100644 --- a/source/blender/blenkernel/intern/shrinkwrap.c +++ b/source/blender/blenkernel/intern/shrinkwrap.c @@ -152,6 +152,9 @@ static void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *calc) BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh; BVHTreeNearest nearest = NULL_BVHTreeNearest; + if (calc->target != NULL && calc->target->getNumVerts(calc->target) == 0) { + return; + } TIMEIT_BENCH(bvhtree_from_mesh_verts(&treeData, calc->target, 0.0, 2, 6), bvhtree_verts); if (treeData.tree == NULL) { @@ -376,6 +379,9 @@ static void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *calc, bool for if ((calc->smd->shrinkOpts & (MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR | MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR)) == 0) return; + if (calc->target != NULL && calc->target->getNumPolys(calc->target) == 0) { + return; + } /* Prepare data to retrieve the direction in which we should project each vertex */ if (calc->smd->projAxis == MOD_SHRINKWRAP_PROJECT_OVER_NORMAL) { @@ -432,7 +438,7 @@ static void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *calc, bool for if (targ_tree) { BVHTree *aux_tree = NULL; void *aux_callback = NULL; - if (auxMesh != NULL) { + if (auxMesh != NULL && auxMesh->getNumPolys(auxMesh) != 0) { /* use editmesh to avoid array allocation */ if (calc->smd->auxTarget && auxMesh->type == DM_TYPE_EDITBMESH) { emaux = BKE_editmesh_from_object(calc->smd->auxTarget); @@ -560,6 +566,10 @@ static void shrinkwrap_calc_nearest_surface_point(ShrinkwrapCalcData *calc) BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh; BVHTreeNearest nearest = NULL_BVHTreeNearest; + if (calc->target->getNumPolys(calc->target) == 0) { + return; + } + /* Create a bvh-tree of the given target */ bvhtree_from_mesh_looptri(&treeData, calc->target, 0.0, 2, 6); if (treeData.tree == NULL) { diff --git a/source/blender/blenkernel/intern/smoke.c b/source/blender/blenkernel/intern/smoke.c index d0ef5cfc092..adecea7080c 100644 --- a/source/blender/blenkernel/intern/smoke.c +++ b/source/blender/blenkernel/intern/smoke.c @@ -2692,7 +2692,6 @@ static void smokeModifier_process(SmokeModifierData *smd, Scene *scene, Object * if (smd->flow->dm) smd->flow->dm->release(smd->flow->dm); smd->flow->dm = CDDM_copy(dm); - DM_ensure_looptri(smd->flow->dm); if (scene->r.cfra > smd->time) { @@ -2715,7 +2714,6 @@ static void smokeModifier_process(SmokeModifierData *smd, Scene *scene, Object * smd->coll->dm->release(smd->coll->dm); smd->coll->dm = CDDM_copy(dm); - DM_ensure_looptri(smd->coll->dm); } smd->time = scene->r.cfra; diff --git a/source/blender/blenkernel/intern/softbody.c b/source/blender/blenkernel/intern/softbody.c index 4f73e153074..600bc3f453d 100644 --- a/source/blender/blenkernel/intern/softbody.c +++ b/source/blender/blenkernel/intern/softbody.c @@ -2235,9 +2235,9 @@ static void sb_cf_threads_run(Scene *scene, Object *ob, float forcetime, float t static void softbody_calc_forcesEx(Scene *scene, Object *ob, float forcetime, float timenow) { -/* rule we never alter free variables :bp->vec bp->pos in here ! - * this will ruin adaptive stepsize AKA heun! (BM) - */ + /* rule we never alter free variables :bp->vec bp->pos in here ! + * this will ruin adaptive stepsize AKA heun! (BM) + */ SoftBody *sb= ob->soft; /* is supposed to be there */ /*BodyPoint *bproot;*/ /* UNUSED */ ListBase *do_effector = NULL; diff --git a/source/blender/blenkernel/intern/sound.c b/source/blender/blenkernel/intern/sound.c index 8469351c54a..45d1f969d64 100644 --- a/source/blender/blenkernel/intern/sound.c +++ b/source/blender/blenkernel/intern/sound.c @@ -83,7 +83,7 @@ bSound *BKE_sound_new_file(struct Main *bmain, const char *filepath) BLI_path_abs(str, path); - sound = BKE_libblock_alloc(bmain, ID_SO, BLI_path_basename(filepath)); + sound = BKE_libblock_alloc(bmain, ID_SO, BLI_path_basename(filepath), 0); BLI_strncpy(sound->name, filepath, FILE_MAX); /* sound->type = SOUND_TYPE_FILE; */ /* XXX unused currently */ @@ -155,6 +155,34 @@ void BKE_sound_free(bSound *sound) } } +/** + * Only copy internal data of Sound ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_sound_copy_data(Main *bmain, bSound *sound_dst, const bSound *UNUSED(sound_src), const int UNUSED(flag)) +{ + sound_dst->handle = NULL; + sound_dst->cache = NULL; + sound_dst->waveform = NULL; + sound_dst->playback_handle = NULL; + sound_dst->spinlock = NULL; /* Think this is OK? Otherwise, easy to create new spinlock here... */ + + /* Just to be sure, should not have any value actually after reading time. */ + sound_dst->ipo = NULL; + sound_dst->newpackedfile = NULL; + + if (sound_dst->packedfile) { + sound_dst->packedfile = dupPackedFile(sound_dst->packedfile); + } + + /* Initialize whole runtime (audaspace) stuff. */ + BKE_sound_load(bmain, sound_dst); +} + void BKE_sound_make_local(Main *bmain, bSound *sound, const bool lib_local) { BKE_id_make_local_generic(bmain, &sound->id, true, lib_local); diff --git a/source/blender/blenkernel/intern/speaker.c b/source/blender/blenkernel/intern/speaker.c index ee6886e3fb2..9d604a9382a 100644 --- a/source/blender/blenkernel/intern/speaker.c +++ b/source/blender/blenkernel/intern/speaker.c @@ -61,25 +61,31 @@ void *BKE_speaker_add(Main *bmain, const char *name) { Speaker *spk; - spk = BKE_libblock_alloc(bmain, ID_SPK, name); + spk = BKE_libblock_alloc(bmain, ID_SPK, name, 0); BKE_speaker_init(spk); return spk; } -Speaker *BKE_speaker_copy(Main *bmain, Speaker *spk) +/** + * Only copy internal data of Speaker ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_speaker_copy_data(Main *UNUSED(bmain), Speaker *UNUSED(spk_dst), const Speaker *UNUSED(spk_src), const int UNUSED(flag)) { - Speaker *spkn; - - spkn = BKE_libblock_copy(bmain, &spk->id); - - if (spkn->sound) - id_us_plus(&spkn->sound->id); - - BKE_id_copy_ensure_local(bmain, &spk->id, &spkn->id); + /* Nothing to do! */ +} - return spkn; +Speaker *BKE_speaker_copy(Main *bmain, const Speaker *spk) +{ + Speaker *spk_copy; + BKE_id_copy_ex(bmain, &spk->id, (ID **)&spk_copy, 0, false); + return spk_copy; } void BKE_speaker_make_local(Main *bmain, Speaker *spk, const bool lib_local) diff --git a/source/blender/blenkernel/intern/subsurf_ccg.c b/source/blender/blenkernel/intern/subsurf_ccg.c index e466c5fc3c1..c06ac91d6c8 100644 --- a/source/blender/blenkernel/intern/subsurf_ccg.c +++ b/source/blender/blenkernel/intern/subsurf_ccg.c @@ -4494,10 +4494,10 @@ static void ccgDM_recalcTessellation(DerivedMesh *UNUSED(dm)) /* Nothing to do: CCG handles creating its own tessfaces */ } +/* WARNING! *MUST* be called in an 'loops_cache_rwlock' protected thread context! */ static void ccgDM_recalcLoopTri(DerivedMesh *dm) { - BLI_rw_mutex_lock(&loops_cache_rwlock, THREAD_LOCK_WRITE); - MLoopTri *mlooptri; + MLoopTri *mlooptri = dm->looptris.array; const int tottri = dm->numPolyData * 2; int i, poly_index; @@ -4522,19 +4522,6 @@ static void ccgDM_recalcLoopTri(DerivedMesh *dm) lt->tri[2] = (poly_index * 4) + 2; lt->poly = poly_index; } - BLI_rw_mutex_unlock(&loops_cache_rwlock); -} - -static const MLoopTri *ccgDM_getLoopTriArray(DerivedMesh *dm) -{ - if (dm->looptris.array) { - BLI_assert(poly_to_tri_count(dm->numPolyData, dm->numLoopData) == dm->looptris.num); - } - else { - dm->recalcLoopTri(dm); - } - - return dm->looptris.array; } static void ccgDM_calcNormals(DerivedMesh *dm) @@ -4553,8 +4540,6 @@ static void set_default_ccgdm_callbacks(CCGDerivedMesh *ccgdm) ccgdm->dm.getNumPolys = ccgDM_getNumPolys; ccgdm->dm.getNumTessFaces = ccgDM_getNumTessFaces; - ccgdm->dm.getLoopTriArray = ccgDM_getLoopTriArray; - ccgdm->dm.getVert = ccgDM_getFinalVert; ccgdm->dm.getEdge = ccgDM_getFinalEdge; ccgdm->dm.getTessFace = ccgDM_getFinalFace; diff --git a/source/blender/blenkernel/intern/text.c b/source/blender/blenkernel/intern/text.c index 298790a9e9b..7c4aa81ee46 100644 --- a/source/blender/blenkernel/intern/text.c +++ b/source/blender/blenkernel/intern/text.c @@ -224,7 +224,7 @@ Text *BKE_text_add(Main *bmain, const char *name) { Text *ta; - ta = BKE_libblock_alloc(bmain, ID_TXT, name); + ta = BKE_libblock_alloc(bmain, ID_TXT, name, 0); BKE_text_init(ta); @@ -410,7 +410,7 @@ Text *BKE_text_load_ex(Main *bmain, const char *file, const char *relpath, const return false; } - ta = BKE_libblock_alloc(bmain, ID_TXT, BLI_path_basename(filepath_abs)); + ta = BKE_libblock_alloc(bmain, ID_TXT, BLI_path_basename(filepath_abs), 0); ta->id.us = 0; BLI_listbase_clear(&ta->lines); @@ -449,53 +449,49 @@ Text *BKE_text_load(Main *bmain, const char *file, const char *relpath) return BKE_text_load_ex(bmain, file, relpath, false); } -Text *BKE_text_copy(Main *bmain, Text *ta) +/** + * Only copy internal data of Text ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_text_copy_data(Main *UNUSED(bmain), Text *ta_dst, const Text *ta_src, const int UNUSED(flag)) { - Text *tan; - TextLine *line, *tmp; - - tan = BKE_libblock_copy(bmain, &ta->id); - /* file name can be NULL */ - if (ta->name) { - tan->name = BLI_strdup(ta->name); - } - else { - tan->name = NULL; + if (ta_src->name) { + ta_dst->name = BLI_strdup(ta_src->name); } - tan->flags = ta->flags | TXT_ISDIRTY; - - BLI_listbase_clear(&tan->lines); - tan->curl = tan->sell = NULL; - tan->compiled = NULL; - - tan->nlines = ta->nlines; + ta_dst->flags |= TXT_ISDIRTY; + + BLI_listbase_clear(&ta_dst->lines); + ta_dst->curl = ta_dst->sell = NULL; + ta_dst->compiled = NULL; - line = ta->lines.first; /* Walk down, reconstructing */ - while (line) { - tmp = (TextLine *) MEM_mallocN(sizeof(TextLine), "textline"); - tmp->line = MEM_mallocN(line->len + 1, "textline_string"); - tmp->format = NULL; - - strcpy(tmp->line, line->line); + for (TextLine *line_src = ta_src->lines.first; line_src; line_src = line_src->next) { + TextLine *line_dst = MEM_mallocN(sizeof(*line_dst), __func__); - tmp->len = line->len; - - BLI_addtail(&tan->lines, tmp); - - line = line->next; - } + line_dst->line = BLI_strdup(line_src->line); + line_dst->format = NULL; + line_dst->len = line_src->len; - tan->curl = tan->sell = tan->lines.first; - tan->curc = tan->selc = 0; + BLI_addtail(&ta_dst->lines, line_dst); + } - init_undo_text(tan); + ta_dst->curl = ta_dst->sell = ta_dst->lines.first; + ta_dst->curc = ta_dst->selc = 0; - BKE_id_copy_ensure_local(bmain, &ta->id, &tan->id); + init_undo_text(ta_dst); +} - return tan; +Text *BKE_text_copy(Main *bmain, const Text *ta) +{ + Text *ta_copy; + BKE_id_copy_ex(bmain, &ta->id, (ID **)&ta_copy, 0, false); + return ta_copy; } void BKE_text_make_local(Main *bmain, Text *text, const bool lib_local) diff --git a/source/blender/blenkernel/intern/texture.c b/source/blender/blenkernel/intern/texture.c index ba04dd9b8f4..8f0334a4752 100644 --- a/source/blender/blenkernel/intern/texture.c +++ b/source/blender/blenkernel/intern/texture.c @@ -707,7 +707,7 @@ Tex *BKE_texture_add(Main *bmain, const char *name) { Tex *tex; - tex = BKE_libblock_alloc(bmain, ID_TE, name); + tex = BKE_libblock_alloc(bmain, ID_TE, name, 0); BKE_texture_default(tex); @@ -846,41 +846,71 @@ MTex *BKE_texture_mtex_add_id(ID *id, int slot) /* ------------------------------------------------------------------------- */ -Tex *BKE_texture_copy(Main *bmain, Tex *tex) +/** + * Only copy internal data of Texture ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_texture_copy_data(Main *bmain, Tex *tex_dst, const Tex *tex_src, const int flag) { - Tex *texn; - - texn = BKE_libblock_copy(bmain, &tex->id); - if (BKE_texture_is_image_user(tex)) { - id_us_plus((ID *)texn->ima); + /* We never handle usercount here for own data. */ + const int flag_subdata = flag | LIB_ID_CREATE_NO_USER_REFCOUNT; + + if (!BKE_texture_is_image_user(tex_src)) { + tex_dst->ima = NULL; } - else { - texn->ima = NULL; + + if (tex_dst->coba) { + tex_dst->coba = MEM_dupallocN(tex_dst->coba); + } + if (tex_dst->env) { + tex_dst->env = BKE_texture_envmap_copy(tex_dst->env, flag_subdata); + } + if (tex_dst->pd) { + tex_dst->pd = BKE_texture_pointdensity_copy(tex_dst->pd, flag_subdata); + } + if (tex_dst->vd) { + tex_dst->vd = MEM_dupallocN(tex_dst->vd); + } + if (tex_dst->ot) { + tex_dst->ot = BKE_texture_ocean_copy(tex_dst->ot, flag_subdata); } - - if (texn->coba) texn->coba = MEM_dupallocN(texn->coba); - if (texn->env) texn->env = BKE_texture_envmap_copy(texn->env); - if (texn->pd) texn->pd = BKE_texture_pointdensity_copy(texn->pd); - if (texn->vd) texn->vd = MEM_dupallocN(texn->vd); - if (texn->ot) texn->ot = BKE_texture_ocean_copy(texn->ot); - if (tex->nodetree) { - if (tex->nodetree->execdata) { - ntreeTexEndExecTree(tex->nodetree->execdata); + if (tex_src->nodetree) { + if (tex_src->nodetree->execdata) { + ntreeTexEndExecTree(tex_src->nodetree->execdata); } - texn->nodetree = ntreeCopyTree(bmain, tex->nodetree); + BKE_id_copy_ex(bmain, (ID *)tex_src->nodetree, (ID **)&tex_dst->nodetree, flag, false); } - BKE_previewimg_id_copy(&texn->id, &tex->id); - - BKE_id_copy_ensure_local(bmain, &tex->id, &texn->id); + if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0) { + BKE_previewimg_id_copy(&tex_dst->id, &tex_src->id); + } + else { + tex_dst->preview = NULL; + } +} - return texn; +Tex *BKE_texture_copy(Main *bmain, const Tex *tex) +{ + Tex *tex_copy; + BKE_id_copy_ex(bmain, &tex->id, (ID **)&tex_copy, 0, false); + return tex_copy; } /* texture copy without adding to main dbase */ Tex *BKE_texture_localize(Tex *tex) { + /* TODO replace with something like + * Tex *tex_copy; + * BKE_id_copy_ex(bmain, &tex->id, (ID **)&tex_copy, LIB_ID_COPY_NO_MAIN | LIB_ID_COPY_NO_PREVIEW | LIB_ID_COPY_NO_USER_REFCOUNT, false); + * return tex_copy; + * + * ... Once f*** nodes are fully converted to that too :( */ + Tex *texn; texn = BKE_libblock_copy_nolib(&tex->id, false); @@ -889,17 +919,17 @@ Tex *BKE_texture_localize(Tex *tex) if (texn->coba) texn->coba = MEM_dupallocN(texn->coba); if (texn->env) { - texn->env = BKE_texture_envmap_copy(texn->env); + texn->env = BKE_texture_envmap_copy(texn->env, LIB_ID_CREATE_NO_USER_REFCOUNT); id_us_min(&texn->env->ima->id); } - if (texn->pd) texn->pd = BKE_texture_pointdensity_copy(texn->pd); + if (texn->pd) texn->pd = BKE_texture_pointdensity_copy(texn->pd, LIB_ID_CREATE_NO_USER_REFCOUNT); if (texn->vd) { texn->vd = MEM_dupallocN(texn->vd); if (texn->vd->dataset) texn->vd->dataset = MEM_dupallocN(texn->vd->dataset); } if (texn->ot) { - texn->ot = BKE_texture_ocean_copy(tex->ot); + texn->ot = BKE_texture_ocean_copy(tex->ot, LIB_ID_CREATE_NO_USER_REFCOUNT); } texn->preview = NULL; @@ -1099,6 +1129,8 @@ void set_active_mtex(ID *id, short act) case ID_PA: ((ParticleSettings *)id)->texact = act; break; + default: + break; } } @@ -1263,16 +1295,20 @@ EnvMap *BKE_texture_envmap_add(void) /* ------------------------------------------------------------------------- */ -EnvMap *BKE_texture_envmap_copy(EnvMap *env) +EnvMap *BKE_texture_envmap_copy(const EnvMap *env, const int flag) { EnvMap *envn; int a; envn = MEM_dupallocN(env); envn->ok = 0; - for (a = 0; a < 6; a++) envn->cube[a] = NULL; - if (envn->ima) id_us_plus((ID *)envn->ima); - + for (a = 0; a < 6; a++) { + envn->cube[a] = NULL; + } + if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) { + id_us_plus((ID *)envn->ima); + } + return envn; } @@ -1336,14 +1372,16 @@ PointDensity *BKE_texture_pointdensity_add(void) return pd; } -PointDensity *BKE_texture_pointdensity_copy(PointDensity *pd) +PointDensity *BKE_texture_pointdensity_copy(const PointDensity *pd, const int UNUSED(flag)) { PointDensity *pdn; pdn = MEM_dupallocN(pd); pdn->point_tree = NULL; pdn->point_data = NULL; - if (pdn->coba) pdn->coba = MEM_dupallocN(pdn->coba); + if (pdn->coba) { + pdn->coba = MEM_dupallocN(pdn->coba); + } pdn->falloff_curve = curvemapping_copy(pdn->falloff_curve); /* can be NULL */ return pdn; } @@ -1430,7 +1468,7 @@ OceanTex *BKE_texture_ocean_add(void) return ot; } -OceanTex *BKE_texture_ocean_copy(struct OceanTex *ot) +OceanTex *BKE_texture_ocean_copy(const OceanTex *ot, const int UNUSED(flag)) { OceanTex *otn = MEM_dupallocN(ot); @@ -1519,3 +1557,33 @@ void BKE_texture_get_value( { BKE_texture_get_value_ex(scene, texture, tex_co, texres, NULL, use_color_management); } + +static void texture_nodes_fetch_images_for_pool(bNodeTree *ntree, struct ImagePool *pool) +{ + for (bNode *node = ntree->nodes.first; node; node = node->next) { + if (node->type == SH_NODE_TEX_IMAGE && node->id != NULL) { + Image *image = (Image *)node->id; + BKE_image_pool_acquire_ibuf(image, NULL, pool); + } + else if (node->type == NODE_GROUP && node->id != NULL) { + /* TODO(sergey): Do we need to control recursion here? */ + bNodeTree *nested_tree = (bNodeTree *)node->id; + texture_nodes_fetch_images_for_pool(nested_tree, pool); + } + } +} + +/* Make sure all images used by texture are loaded into pool. */ +void BKE_texture_fetch_images_for_pool(Tex *texture, struct ImagePool *pool) +{ + if (texture->nodetree != NULL) { + texture_nodes_fetch_images_for_pool(texture->nodetree, pool); + } + else { + if (texture->type == TEX_IMAGE) { + if (texture->ima != NULL) { + BKE_image_pool_acquire_ibuf(texture->ima, NULL, pool); + } + } + } +} diff --git a/source/blender/blenkernel/intern/tracking.c b/source/blender/blenkernel/intern/tracking.c index bfe8dcbb21e..b4ef381534f 100644 --- a/source/blender/blenkernel/intern/tracking.c +++ b/source/blender/blenkernel/intern/tracking.c @@ -190,7 +190,7 @@ void BKE_tracking_free(MovieTracking *tracking) } /* Copy the whole list of tracks. */ -static void tracking_tracks_copy(ListBase *tracks_dst, ListBase *tracks_src, GHash *tracks_mapping) +static void tracking_tracks_copy(ListBase *tracks_dst, const ListBase *tracks_src, GHash *tracks_mapping, const int flag) { MovieTrackingTrack *track_dst, *track_src; @@ -202,7 +202,9 @@ static void tracking_tracks_copy(ListBase *tracks_dst, ListBase *tracks_src, GHa if (track_src->markers) { track_dst->markers = MEM_dupallocN(track_src->markers); } - id_us_plus(&track_dst->gpd->id); + if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) { + id_us_plus(&track_dst->gpd->id); + } BLI_addtail(tracks_dst, track_dst); BLI_ghash_insert(tracks_mapping, track_src, track_dst); } @@ -210,7 +212,8 @@ static void tracking_tracks_copy(ListBase *tracks_dst, ListBase *tracks_src, GHa /* copy the whole list of plane tracks (need whole MovieTracking structures due to embedded pointers to tracks). * WARNING: implies tracking_[dst/src] and their tracks have already been copied. */ -static void tracking_plane_tracks_copy(ListBase *plane_tracks_dst, ListBase *plane_tracks_src, GHash *tracks_mapping) +static void tracking_plane_tracks_copy( + ListBase *plane_tracks_dst, const ListBase *plane_tracks_src, GHash *tracks_mapping, const int flag) { MovieTrackingPlaneTrack *plane_track_dst, *plane_track_src; @@ -225,14 +228,17 @@ static void tracking_plane_tracks_copy(ListBase *plane_tracks_dst, ListBase *pla for (int i = 0; i < plane_track_dst->point_tracksnr; i++) { plane_track_dst->point_tracks[i] = BLI_ghash_lookup(tracks_mapping, plane_track_src->point_tracks[i]); } - id_us_plus(&plane_track_dst->image->id); + if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) { + id_us_plus(&plane_track_dst->image->id); + } BLI_addtail(plane_tracks_dst, plane_track_dst); } } /* Copy reconstruction structure. */ static void tracking_reconstruction_copy( - MovieTrackingReconstruction *reconstruction_dst, MovieTrackingReconstruction *reconstruction_src) + MovieTrackingReconstruction *reconstruction_dst, const MovieTrackingReconstruction *reconstruction_src, + const int UNUSED(flag)) { *reconstruction_dst = *reconstruction_src; if (reconstruction_src->cameras) { @@ -242,23 +248,25 @@ static void tracking_reconstruction_copy( /* Copy stabilization structure. */ static void tracking_stabilization_copy( - MovieTrackingStabilization *stabilization_dst, MovieTrackingStabilization *stabilization_src) + MovieTrackingStabilization *stabilization_dst, const MovieTrackingStabilization *stabilization_src, + const int UNUSED(flag)) { *stabilization_dst = *stabilization_src; } /* Copy tracking object. */ static void tracking_object_copy( - MovieTrackingObject *object_dst, MovieTrackingObject *object_src, GHash *tracks_mapping) + MovieTrackingObject *object_dst, const MovieTrackingObject *object_src, GHash *tracks_mapping, const int flag) { *object_dst = *object_src; - tracking_tracks_copy(&object_dst->tracks, &object_src->tracks, tracks_mapping); - tracking_plane_tracks_copy(&object_dst->plane_tracks, &object_src->plane_tracks, tracks_mapping); - tracking_reconstruction_copy(&object_dst->reconstruction, &object_src->reconstruction); + tracking_tracks_copy(&object_dst->tracks, &object_src->tracks, tracks_mapping, flag); + tracking_plane_tracks_copy(&object_dst->plane_tracks, &object_src->plane_tracks, tracks_mapping, flag); + tracking_reconstruction_copy(&object_dst->reconstruction, &object_src->reconstruction, flag); } /* Copy list of tracking objects. */ -static void tracking_objects_copy(ListBase *objects_dst, ListBase *objects_src, GHash *tracks_mapping) +static void tracking_objects_copy( + ListBase *objects_dst, const ListBase *objects_src, GHash *tracks_mapping, const int flag) { MovieTrackingObject *object_dst, *object_src; @@ -266,22 +274,22 @@ static void tracking_objects_copy(ListBase *objects_dst, ListBase *objects_src, for (object_src = objects_src->first; object_src != NULL; object_src = object_src->next) { object_dst = MEM_mallocN(sizeof(*object_dst), __func__); - tracking_object_copy(object_dst, object_src, tracks_mapping); + tracking_object_copy(object_dst, object_src, tracks_mapping, flag); BLI_addtail(objects_dst, object_dst); } } /* Copy tracking structure content. */ -void BKE_tracking_copy(MovieTracking *tracking_dst, MovieTracking *tracking_src) +void BKE_tracking_copy(MovieTracking *tracking_dst, const MovieTracking *tracking_src, const int flag) { GHash *tracks_mapping = BLI_ghash_ptr_new(__func__); *tracking_dst = *tracking_src; - tracking_tracks_copy(&tracking_dst->tracks, &tracking_src->tracks, tracks_mapping); - tracking_plane_tracks_copy(&tracking_dst->plane_tracks, &tracking_src->plane_tracks, tracks_mapping); - tracking_reconstruction_copy(&tracking_dst->reconstruction, &tracking_src->reconstruction); - tracking_stabilization_copy(&tracking_dst->stabilization, &tracking_src->stabilization); + tracking_tracks_copy(&tracking_dst->tracks, &tracking_src->tracks, tracks_mapping, flag); + tracking_plane_tracks_copy(&tracking_dst->plane_tracks, &tracking_src->plane_tracks, tracks_mapping, flag); + tracking_reconstruction_copy(&tracking_dst->reconstruction, &tracking_src->reconstruction, flag); + tracking_stabilization_copy(&tracking_dst->stabilization, &tracking_src->stabilization, flag); if (tracking_src->act_track) { tracking_dst->act_track = BLI_ghash_lookup(tracks_mapping, tracking_src->act_track); } @@ -299,7 +307,7 @@ void BKE_tracking_copy(MovieTracking *tracking_dst, MovieTracking *tracking_src) } /* Warning! Will override tracks_mapping. */ - tracking_objects_copy(&tracking_dst->objects, &tracking_src->objects, tracks_mapping); + tracking_objects_copy(&tracking_dst->objects, &tracking_src->objects, tracks_mapping, flag); /* Those remaining are runtime data, they will be reconstructed as needed, do not bother copying them. */ tracking_dst->dopesheet.ok = false; diff --git a/source/blender/blenkernel/intern/tracking_auto.c b/source/blender/blenkernel/intern/tracking_auto.c index 9475925cdda..30981ed8f23 100644 --- a/source/blender/blenkernel/intern/tracking_auto.c +++ b/source/blender/blenkernel/intern/tracking_auto.c @@ -312,7 +312,7 @@ AutoTrackContext *BKE_autotrack_context_new(MovieClip *clip, int num_total_tracks = BLI_listbase_count(tracksbase); context->tracks = - MEM_callocN(sizeof(MovieTrackingTrack*) * num_total_tracks, + MEM_callocN(sizeof(MovieTrackingTrack *) * num_total_tracks, "auto track pointers"); context->image_accessor = @@ -381,7 +381,7 @@ AutoTrackContext *BKE_autotrack_context_new(MovieClip *clip, bool BKE_autotrack_context_step(AutoTrackContext *context) { - int frame_delta = context->backwards ? -1 : 1; + const int frame_delta = context->backwards ? -1 : 1; bool ok = false; int track; @@ -395,67 +395,64 @@ bool BKE_autotrack_context_step(AutoTrackContext *context) libmv_reference_marker, libmv_tracked_marker; libmv_TrackRegionResult libmv_result; - int frame = BKE_movieclip_remap_scene_to_clip_frame( - context->clips[options->clip_index], - context->user.framenr); - bool has_marker; - + const int frame = BKE_movieclip_remap_scene_to_clip_frame( + context->clips[options->clip_index], + context->user.framenr); BLI_spin_lock(&context->spin_lock); - has_marker = libmv_autoTrackGetMarker(context->autotrack, - options->clip_index, - frame, - options->track_index, - &libmv_current_marker); + const bool has_marker = libmv_autoTrackGetMarker(context->autotrack, + options->clip_index, + frame, + options->track_index, + &libmv_current_marker); BLI_spin_unlock(&context->spin_lock); - - if (has_marker) { - if (!tracking_check_marker_margin(&libmv_current_marker, - options->track->margin, - context->frame_width, - context->frame_height)) - { - continue; - } - - libmv_tracked_marker = libmv_current_marker; - libmv_tracked_marker.frame = frame + frame_delta; - - if (options->use_keyframe_match) { - libmv_tracked_marker.reference_frame = - libmv_current_marker.reference_frame; - libmv_autoTrackGetMarker(context->autotrack, - options->clip_index, - libmv_tracked_marker.reference_frame, - options->track_index, - &libmv_reference_marker); - } - else { - libmv_tracked_marker.reference_frame = frame; - libmv_reference_marker = libmv_current_marker; - } - - if (libmv_autoTrackMarker(context->autotrack, - &options->track_region_options, - &libmv_tracked_marker, - &libmv_result)) - { - BLI_spin_lock(&context->spin_lock); - libmv_autoTrackAddMarker(context->autotrack, - &libmv_tracked_marker); - BLI_spin_unlock(&context->spin_lock); - } - else { - options->is_failed = true; - options->failed_frame = frame + frame_delta; - } - ok = true; + /* Check whether we've got marker to sync with. */ + if (!has_marker) { + continue; + } + /* Check whether marker is going outside of allowed frame margin. */ + if (!tracking_check_marker_margin(&libmv_current_marker, + options->track->margin, + context->frame_width, + context->frame_height)) + { + continue; + } + libmv_tracked_marker = libmv_current_marker; + libmv_tracked_marker.frame = frame + frame_delta; + /* Update reference frame. */ + if (options->use_keyframe_match) { + libmv_tracked_marker.reference_frame = + libmv_current_marker.reference_frame; + libmv_autoTrackGetMarker(context->autotrack, + options->clip_index, + libmv_tracked_marker.reference_frame, + options->track_index, + &libmv_reference_marker); } + else { + libmv_tracked_marker.reference_frame = frame; + libmv_reference_marker = libmv_current_marker; + } + /* Perform actual tracking. */ + if (libmv_autoTrackMarker(context->autotrack, + &options->track_region_options, + &libmv_tracked_marker, + &libmv_result)) + { + BLI_spin_lock(&context->spin_lock); + libmv_autoTrackAddMarker(context->autotrack, &libmv_tracked_marker); + BLI_spin_unlock(&context->spin_lock); + } + else { + options->is_failed = true; + options->failed_frame = frame + frame_delta; + } + ok = true; } - + /* Advance the frame. */ BLI_spin_lock(&context->spin_lock); context->user.framenr += frame_delta; BLI_spin_unlock(&context->spin_lock); - return ok; } diff --git a/source/blender/blenkernel/intern/tracking_stabilize.c b/source/blender/blenkernel/intern/tracking_stabilize.c index 3dfaa1ed77d..b8dfb217c16 100644 --- a/source/blender/blenkernel/intern/tracking_stabilize.c +++ b/source/blender/blenkernel/intern/tracking_stabilize.c @@ -203,7 +203,7 @@ static float get_animated_scaleinf(StabContext *ctx, int framenr) static void get_animated_target_pos(StabContext *ctx, int framenr, - float target_pos[2]) + float target_pos[2]) { target_pos[0] = fetch_from_fcurve(ctx->target_pos[0], framenr, diff --git a/source/blender/blenkernel/intern/tracking_util.c b/source/blender/blenkernel/intern/tracking_util.c index a95399562d5..d8e98291117 100644 --- a/source/blender/blenkernel/intern/tracking_util.c +++ b/source/blender/blenkernel/intern/tracking_util.c @@ -58,6 +58,15 @@ #include "libmv-capi.h" +/* Uncomment this to have caching-specific debug prints. */ +// #define DEBUG_CACHE + +#ifdef DEBUG_CACHE +# define CACHE_PRINTF(...) printf(__VA_ARGS__) +#else +# define CACHE_PRINTF(...) +#endif + /*********************** Tracks map *************************/ TracksMap *tracks_map_new(const char *object_name, bool is_camera, int num_tracks, int customdata_size) @@ -523,6 +532,8 @@ typedef struct AccessCacheKey { int frame; int downscale; libmv_InputMode input_mode; + bool has_region; + float region_min[2], region_max[2]; int64_t transform_key; } AccessCacheKey; @@ -537,23 +548,44 @@ static bool accesscache_hashcmp(const void *a_v, const void *b_v) { const AccessCacheKey *a = (const AccessCacheKey *) a_v; const AccessCacheKey *b = (const AccessCacheKey *) b_v; - -#define COMPARE_FIELD(field) - { \ - if (a->clip_index != b->clip_index) { \ - return false; \ - } \ - } (void) 0 - - COMPARE_FIELD(clip_index); - COMPARE_FIELD(frame); - COMPARE_FIELD(downscale); - COMPARE_FIELD(input_mode); - COMPARE_FIELD(transform_key); - -#undef COMPARE_FIELD - - return true; + if (a->clip_index != b->clip_index || + a->frame != b->frame || + a->downscale != b->downscale || + a->input_mode != b->input_mode || + a->has_region != b->has_region || + a->transform_key != b->transform_key) + { + return true; + } + /* If there is region applied, compare it. */ + if (a->has_region) { + if (!equals_v2v2(a->region_min, b->region_min) || + !equals_v2v2(a->region_max, b->region_max)) + { + return true; + } + } + return false; +} + +static void accesscache_construct_key(AccessCacheKey *key, + int clip_index, + int frame, + libmv_InputMode input_mode, + int downscale, + const libmv_Region *region, + int64_t transform_key) +{ + key->clip_index = clip_index; + key->frame = frame; + key->input_mode = input_mode; + key->downscale = downscale; + key->has_region = (region != NULL); + if (key->has_region) { + copy_v2_v2(key->region_min, region->min); + copy_v2_v2(key->region_max, region->max); + } + key->transform_key = transform_key; } static void accesscache_put(TrackingImageAccessor *accessor, @@ -561,15 +593,13 @@ static void accesscache_put(TrackingImageAccessor *accessor, int frame, libmv_InputMode input_mode, int downscale, + const libmv_Region *region, int64_t transform_key, ImBuf *ibuf) { AccessCacheKey key; - key.clip_index = clip_index; - key.frame = frame; - key.input_mode = input_mode; - key.downscale = downscale; - key.transform_key = transform_key; + accesscache_construct_key(&key, clip_index, frame, input_mode, downscale, + region, transform_key); IMB_moviecache_put(accessor->cache, &key, ibuf); } @@ -578,14 +608,12 @@ static ImBuf *accesscache_get(TrackingImageAccessor *accessor, int frame, libmv_InputMode input_mode, int downscale, + const libmv_Region *region, int64_t transform_key) { AccessCacheKey key; - key.clip_index = clip_index; - key.frame = frame; - key.input_mode = input_mode; - key.downscale = downscale; - key.transform_key = transform_key; + accesscache_construct_key(&key, clip_index, frame, input_mode, downscale, + region, transform_key); return IMB_moviecache_get(accessor->cache, &key); } @@ -674,29 +702,37 @@ static ImBuf *accessor_get_ibuf(TrackingImageAccessor *accessor, { ImBuf *ibuf, *orig_ibuf, *final_ibuf; int64_t transform_key = 0; - if (transform != NULL) { transform_key = libmv_frameAccessorgetTransformKey(transform); } - /* First try to get fully processed image from the cache. */ + BLI_spin_lock(&accessor->cache_lock); ibuf = accesscache_get(accessor, clip_index, frame, input_mode, downscale, + region, transform_key); + BLI_spin_unlock(&accessor->cache_lock); if (ibuf != NULL) { + CACHE_PRINTF("Used cached buffer for frame %d\n", frame); + /* This is a little heuristic here: if we re-used image once, this is + * a high probability of the image to be related to a keyframe matched + * reference image. Those images we don't want to be thrown away because + * if we toss them out we'll be re-calculating them at the next + * iteration. + */ + ibuf->userflags |= IB_PERSISTENT; return ibuf; } - + CACHE_PRINTF("Calculate new buffer for frame %d\n", frame); /* And now we do postprocessing of the original frame. */ orig_ibuf = accessor_get_preprocessed_ibuf(accessor, clip_index, frame); - if (orig_ibuf == NULL) { return NULL; } - + /* Cut a region if requested. */ if (region != NULL) { int width = region->max[0] - region->min[0], height = region->max[1] - region->min[1]; @@ -756,7 +792,7 @@ static ImBuf *accessor_get_ibuf(TrackingImageAccessor *accessor, BLI_unlock_thread(LOCK_MOVIECLIP); final_ibuf = orig_ibuf; } - + /* Downscale if needed. */ if (downscale > 0) { if (final_ibuf == orig_ibuf) { final_ibuf = IMB_dupImBuf(orig_ibuf); @@ -765,7 +801,7 @@ static ImBuf *accessor_get_ibuf(TrackingImageAccessor *accessor, orig_ibuf->x / (1 << downscale), orig_ibuf->y / (1 << downscale)); } - + /* Apply possible transformation. */ if (transform != NULL) { libmv_FloatImage input_image, output_image; ibuf_to_float_image(final_ibuf, &input_image); @@ -778,12 +814,13 @@ static ImBuf *accessor_get_ibuf(TrackingImageAccessor *accessor, final_ibuf = float_image_to_ibuf(&output_image); libmv_floatImageDestroy(&output_image); } - + /* Transform number of channels. */ if (input_mode == LIBMV_IMAGE_MODE_RGBA) { BLI_assert(orig_ibuf->channels == 3 || orig_ibuf->channels == 4); /* pass */ } else /* if (input_mode == LIBMV_IMAGE_MODE_MONO) */ { + BLI_assert(input_mode == LIBMV_IMAGE_MODE_MONO); if (final_ibuf->channels != 1) { ImBuf *grayscale_ibuf = make_grayscale_ibuf_copy(final_ibuf); if (final_ibuf != orig_ibuf) { @@ -793,37 +830,25 @@ static ImBuf *accessor_get_ibuf(TrackingImageAccessor *accessor, final_ibuf = grayscale_ibuf; } } - - /* it's possible processing still didn't happen at this point, + /* It's possible processing still didn't happen at this point, * but we really need a copy of the buffer to be transformed * and to be put to the cache. */ if (final_ibuf == orig_ibuf) { final_ibuf = IMB_dupImBuf(orig_ibuf); } - IMB_freeImBuf(orig_ibuf); - - /* We put postprocessed frame to the cache always for now, - * not the smartest thing in the world, but who cares at this point. - */ - - /* TODO(sergey): Disable cache for now, because we don't store region - * in the cache key and can't check whether cached version is usable for - * us or not. - * - * Need to think better about what to cache and when. - */ - if (false) { - accesscache_put(accessor, - clip_index, - frame, - input_mode, - downscale, - transform_key, - final_ibuf); - } - + BLI_spin_lock(&accessor->cache_lock); + /* Put final buffer to cache. */ + accesscache_put(accessor, + clip_index, + frame, + input_mode, + downscale, + region, + transform_key, + final_ibuf); + BLI_spin_unlock(&accessor->cache_lock); return final_ibuf; } @@ -876,7 +901,7 @@ static void accessor_release_image_callback(libmv_CacheKey cache_key) } static libmv_CacheKey accessor_get_mask_for_track_callback( - libmv_FrameAccessorUserData* user_data, + libmv_FrameAccessorUserData *user_data, int clip_index, int frame, int track_index, @@ -958,6 +983,8 @@ TrackingImageAccessor *tracking_image_accessor_new(MovieClip *clips[MAX_ACCESSOR accessor_get_mask_for_track_callback, accessor_release_mask_callback); + BLI_spin_init(&accessor->cache_lock); + return accessor; } @@ -965,5 +992,6 @@ void tracking_image_accessor_destroy(TrackingImageAccessor *accessor) { IMB_moviecache_free(accessor->cache); libmv_FrameAccessorDestroy(accessor->libmv_accessor); + BLI_spin_end(&accessor->cache_lock); MEM_freeN(accessor); } diff --git a/source/blender/blenkernel/intern/unit.c b/source/blender/blenkernel/intern/unit.c index c0a373395dc..8606da0743b 100644 --- a/source/blender/blenkernel/intern/unit.c +++ b/source/blender/blenkernel/intern/unit.c @@ -372,6 +372,12 @@ static size_t unit_as_string(char *str, int len_max, double value, int prec, con value_conv = value / unit->scalar; + /* Adjust precision to expected number of significant digits. + * Note that here, we shall not have to worry about very big/small numbers, units are expected to replace + * 'scientific notation' in those cases. */ + prec -= integer_digits_d(value_conv); + CLAMP(prec, 0, 6); + /* Convert to a string */ len = BLI_snprintf_rlen(str, len_max, "%.*f", prec, value_conv); @@ -442,12 +448,15 @@ size_t bUnit_AsString(char *str, int len_max, double value, int prec, int system size_t i; i = unit_as_string(str, len_max, value_a, prec, usys, unit_a, '\0'); + prec -= integer_digits_d(value_a / unit_b->scalar) - integer_digits_d(value_b / unit_b->scalar); + prec = max_ii(prec, 0); + /* is there enough space for at least 1 char of the next unit? */ if (i + 2 < len_max) { str[i++] = ' '; /* use low precision since this is a smaller unit */ - i += unit_as_string(str + i, len_max - i, value_b, prec ? 1 : 0, usys, unit_b, '\0'); + i += unit_as_string(str + i, len_max - i, value_b, prec, usys, unit_b, '\0'); } return i; } diff --git a/source/blender/blenkernel/intern/world.c b/source/blender/blenkernel/intern/world.c index caa9a1e357f..e79b06a44fe 100644 --- a/source/blender/blenkernel/intern/world.c +++ b/source/blender/blenkernel/intern/world.c @@ -112,43 +112,59 @@ World *add_world(Main *bmain, const char *name) { World *wrld; - wrld = BKE_libblock_alloc(bmain, ID_WO, name); + wrld = BKE_libblock_alloc(bmain, ID_WO, name, 0); BKE_world_init(wrld); return wrld; } -World *BKE_world_copy(Main *bmain, World *wrld) +/** + * Only copy internal data of World ID from source to already allocated/initialized destination. + * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs. + * + * WARNING! This function will not handle ID user count! + * + * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). + */ +void BKE_world_copy_data(Main *bmain, World *wrld_dst, const World *wrld_src, const int flag) { - World *wrldn; - int a; - - wrldn = BKE_libblock_copy(bmain, &wrld->id); - - for (a = 0; a < MAX_MTEX; a++) { - if (wrld->mtex[a]) { - wrldn->mtex[a] = MEM_mallocN(sizeof(MTex), "BKE_world_copy"); - memcpy(wrldn->mtex[a], wrld->mtex[a], sizeof(MTex)); - id_us_plus((ID *)wrldn->mtex[a]->tex); + for (int a = 0; a < MAX_MTEX; a++) { + if (wrld_src->mtex[a]) { + wrld_dst->mtex[a] = MEM_dupallocN(wrld_src->mtex[a]); } } - if (wrld->nodetree) { - wrldn->nodetree = ntreeCopyTree(bmain, wrld->nodetree); + if (wrld_src->nodetree) { + BKE_id_copy_ex(bmain, (ID *)wrld_src->nodetree, (ID **)&wrld_dst->nodetree, flag, false); } - - BKE_previewimg_id_copy(&wrldn->id, &wrld->id); - BLI_listbase_clear(&wrldn->gpumaterial); + BLI_listbase_clear(&wrld_dst->gpumaterial); - BKE_id_copy_ensure_local(bmain, &wrld->id, &wrldn->id); + if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0) { + BKE_previewimg_id_copy(&wrld_dst->id, &wrld_src->id); + } + else { + wrld_dst->preview = NULL; + } +} - return wrldn; +World *BKE_world_copy(Main *bmain, const World *wrld) +{ + World *wrld_copy; + BKE_id_copy_ex(bmain, &wrld->id, (ID **)&wrld_copy, 0, false); + return wrld_copy; } World *localize_world(World *wrld) { + /* TODO replace with something like + * World *wrld_copy; + * BKE_id_copy_ex(bmain, &wrld->id, (ID **)&wrld_copy, LIB_ID_COPY_NO_MAIN | LIB_ID_COPY_NO_PREVIEW | LIB_ID_COPY_NO_USER_REFCOUNT, false); + * return wrld_copy; + * + * ... Once f*** nodes are fully converted to that too :( */ + World *wrldn; int a; |