Cleanup: remove moar G.main usages.
[blender.git] / source / blender / editors / transform / transform_conversions.c
index b7456facbdfff9b6c7b7ed1a81ed7f767f538dae..6ce8d9dc5ac96e7a3bcc3f22a5d614ba9fb7d880 100644 (file)
@@ -174,7 +174,7 @@ void sort_trans_data_dist(TransInfo *t)
 
        for (i = 0; i < t->total && start->flag & TD_SELECTED; i++)
                start++;
-       
+
        if (i < t->total) {
                if (t->flag & T_PROP_CONNECTED)
                        qsort(start, t->total - i, sizeof(TransData), trans_data_compare_dist);
@@ -475,9 +475,9 @@ static short apply_targetless_ik(Object *ob)
                                /* apply and decompose, doesn't work for constraints or non-uniform scale well */
                                {
                                        float rmat3[3][3], qrmat[3][3], imat3[3][3], smat[3][3];
-                                       
+
                                        copy_m3_m4(rmat3, rmat);
-                                       
+
                                        /* rotation */
                                        /* [#22409] is partially caused by this, as slight numeric error introduced during
                                         * the solving process leads to locked-axis values changing. However, we cannot modify
@@ -490,7 +490,7 @@ static short apply_targetless_ik(Object *ob)
                                                mat3_to_axis_angle(parchan->rotAxis, &parchan->rotAngle, rmat3);
                                        else
                                                mat3_to_quat(parchan->quat, rmat3);
-                                       
+
                                        /* for size, remove rotation */
                                        /* causes problems with some constraints (so apply only if needed) */
                                        if (data->flag & CONSTRAINT_IK_STRETCH) {
@@ -500,12 +500,12 @@ static short apply_targetless_ik(Object *ob)
                                                        axis_angle_to_mat3(qrmat, parchan->rotAxis, parchan->rotAngle);
                                                else
                                                        quat_to_mat3(qrmat, parchan->quat);
-                                               
+
                                                invert_m3_m3(imat3, qrmat);
                                                mul_m3_m3m3(smat, rmat3, imat3);
                                                mat3_to_size(parchan->size, smat);
                                        }
-                                       
+
                                        /* causes problems with some constraints (e.g. childof), so disable this */
                                        /* as it is IK shouldn't affect location directly */
                                        /* copy_v3_v3(parchan->loc, rmat[3]); */
@@ -555,7 +555,7 @@ static void add_pose_transdata(TransInfo *t, bPoseChannel *pchan, Object *ob, Tr
                td->ext->rotAxis = NULL;
                td->ext->rotAngle = NULL;
                td->ext->quat = NULL;
-               
+
                copy_v3_v3(td->ext->irot, pchan->eul);
        }
        else if (pchan->rotmode == ROT_MODE_AXISANGLE) {
@@ -563,7 +563,7 @@ static void add_pose_transdata(TransInfo *t, bPoseChannel *pchan, Object *ob, Tr
                td->ext->rotAxis = pchan->rotAxis;
                td->ext->rotAngle = &pchan->rotAngle;
                td->ext->quat = NULL;
-               
+
                td->ext->irotAngle = pchan->rotAngle;
                copy_v3_v3(td->ext->irotAxis, pchan->rotAxis);
        }
@@ -572,7 +572,7 @@ static void add_pose_transdata(TransInfo *t, bPoseChannel *pchan, Object *ob, Tr
                td->ext->rotAxis = NULL;
                td->ext->rotAngle = NULL;
                td->ext->quat = pchan->quat;
-               
+
                copy_qt_qt(td->ext->iquat, pchan->quat);
        }
        td->ext->rotOrder = pchan->rotmode;
@@ -625,7 +625,7 @@ static void add_pose_transdata(TransInfo *t, bPoseChannel *pchan, Object *ob, Tr
                        td->flag |= TD_PBONE_LOCAL_MTX_P;
                }
        }
-       
+
        /* for axismat we use bone's own transform */
        copy_m3_m4(pmat, pchan->pose_mat);
        mul_m3_m3m3(td->axismtx, omat, pmat);
@@ -701,7 +701,6 @@ int count_set_pose_transflags(int *out_mode, short around, Object *ob)
        bPoseChannel *pchan;
        Bone *bone;
        int mode = *out_mode;
-       int hastranslation = 0;
        int total = 0;
 
        for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
@@ -711,7 +710,7 @@ int count_set_pose_transflags(int *out_mode, short around, Object *ob)
                                bone->flag |= BONE_TRANSFORM;
                        else
                                bone->flag &= ~BONE_TRANSFORM;
-                       
+
                        bone->flag &= ~BONE_HINGE_CHILD_TRANSFORM;
                        bone->flag &= ~BONE_TRANSFORM_CHILD;
                }
@@ -729,31 +728,40 @@ int count_set_pose_transflags(int *out_mode, short around, Object *ob)
                }
        }
        /* now count, and check if we have autoIK or have to switch from translate to rotate */
-       hastranslation = 0;
+       bool has_translation = false, has_rotation = false;
 
        for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
                bone = pchan->bone;
                if (bone->flag & BONE_TRANSFORM) {
                        total++;
-                       
+
                        if (mode == TFM_TRANSLATION) {
                                if (has_targetless_ik(pchan) == NULL) {
                                        if (pchan->parent && (pchan->bone->flag & BONE_CONNECTED)) {
                                                if (pchan->bone->flag & BONE_HINGE_CHILD_TRANSFORM)
-                                                       hastranslation = 1;
+                                                       has_translation = true;
+                                       }
+                                       else {
+                                               if ((pchan->protectflag & OB_LOCK_LOC) != OB_LOCK_LOC)
+                                                       has_translation = true;
                                        }
-                                       else if ((pchan->protectflag & OB_LOCK_LOC) != OB_LOCK_LOC)
-                                               hastranslation = 1;
+                                       if ((pchan->protectflag & OB_LOCK_ROT) != OB_LOCK_ROT)
+                                               has_rotation = true;
                                }
                                else
-                                       hastranslation = 1;
+                                       has_translation = true;
                        }
                }
        }
 
        /* if there are no translatable bones, do rotation */
-       if (mode == TFM_TRANSLATION && !hastranslation) {
-               *out_mode = TFM_ROTATION;
+       if (mode == TFM_TRANSLATION && !has_translation) {
+               if (has_rotation) {
+                       *out_mode = TFM_ROTATION;
+               }
+               else {
+                       *out_mode = TFM_RESIZE;
+               }
        }
 
        return total;
@@ -763,29 +771,37 @@ int count_set_pose_transflags(int *out_mode, short around, Object *ob)
 /* -------- Auto-IK ---------- */
 
 /* adjust pose-channel's auto-ik chainlen */
-static void pchan_autoik_adjust(bPoseChannel *pchan, short chainlen)
+static bool pchan_autoik_adjust(bPoseChannel *pchan, short chainlen)
 {
        bConstraint *con;
+       bool changed = false;
 
        /* don't bother to search if no valid constraints */
-       if ((pchan->constflag & (PCHAN_HAS_IK | PCHAN_HAS_TARGET)) == 0)
-               return;
+       if ((pchan->constflag & (PCHAN_HAS_IK | PCHAN_HAS_TARGET)) == 0) {
+               return changed;
+       }
 
        /* check if pchan has ik-constraint */
        for (con = pchan->constraints.first; con; con = con->next) {
                if (con->type == CONSTRAINT_TYPE_KINEMATIC && (con->enforce != 0.0f)) {
                        bKinematicConstraint *data = con->data;
-                       
+
                        /* only accept if a temporary one (for auto-ik) */
                        if (data->flag & CONSTRAINT_IK_TEMP) {
                                /* chainlen is new chainlen, but is limited by maximum chainlen */
-                               if ((chainlen == 0) || (chainlen > data->max_rootbone))
+                               const int old_rootbone = data->rootbone;
+                               if ((chainlen == 0) || (chainlen > data->max_rootbone)) {
                                        data->rootbone = data->max_rootbone;
-                               else
+                               }
+                               else {
                                        data->rootbone = chainlen;
+                               }
+                               changed |= (data->rootbone != old_rootbone);
                        }
                }
        }
+
+       return changed;
 }
 
 /* change the chain-length of auto-ik */
@@ -801,7 +817,13 @@ void transform_autoik_update(TransInfo *t, short mode)
        }
        else if (mode == -1) {
                /* mode==-1 is from WHEELMOUSEUP... decreases len */
-               if (*chainlen > 0) (*chainlen)--;
+               if (*chainlen > 0) {
+                       (*chainlen)--;
+               }
+               else {
+                       /* IK length did not change, skip updates. */
+                       return;
+               }
        }
 
        /* sanity checks (don't assume t->poseobj is set, or that it is an armature) */
@@ -809,8 +831,19 @@ void transform_autoik_update(TransInfo *t, short mode)
                return;
 
        /* apply to all pose-channels */
+       bool changed = false;
        for (pchan = t->poseobj->pose->chanbase.first; pchan; pchan = pchan->next) {
-               pchan_autoik_adjust(pchan, *chainlen);
+               changed |= pchan_autoik_adjust(pchan, *chainlen);
+       }
+
+#ifdef WITH_LEGACY_DEPSGRAPH
+       if (!DEG_depsgraph_use_legacy())
+#endif
+       {
+               if (changed) {
+                       /* TODO(sergey): Consider doing partial update only. */
+                       DAG_relations_tag_update(G.main);
+               }
        }
 }
 
@@ -820,14 +853,16 @@ static void pose_grab_with_ik_clear(Object *ob)
        bKinematicConstraint *data;
        bPoseChannel *pchan;
        bConstraint *con, *next;
+#ifdef WITH_LEGACY_DEPSGRAPH
        bool need_dependency_update = false;
+#endif
 
        for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
                /* clear all temporary lock flags */
                pchan->ikflag &= ~(BONE_IK_NO_XDOF_TEMP | BONE_IK_NO_YDOF_TEMP | BONE_IK_NO_ZDOF_TEMP);
-               
+
                pchan->constflag &= ~(PCHAN_HAS_IK | PCHAN_HAS_TARGET);
-               
+
                /* remove all temporary IK-constraints added */
                for (con = pchan->constraints.first; con; con = next) {
                        next = con->next;
@@ -835,7 +870,9 @@ static void pose_grab_with_ik_clear(Object *ob)
                                data = con->data;
                                if (data->flag & CONSTRAINT_IK_TEMP) {
                                        /* iTaSC needs clear for removed constraints */
+#ifdef WITH_LEGACY_DEPSGRAPH
                                        need_dependency_update = true;
+#endif
                                        BIK_clear_data(ob->pose);
 
                                        BLI_remlink(&pchan->constraints, con);
@@ -874,15 +911,15 @@ static short pose_grab_with_ik_add(bPoseChannel *pchan)
        for (con = pchan->constraints.first; con; con = con->next) {
                if (con->type == CONSTRAINT_TYPE_KINEMATIC) {
                        data = con->data;
-                       
+
                        if (data->tar == NULL || (data->tar->type == OB_ARMATURE && data->subtarget[0] == '\0')) {
                                /* make reference to constraint to base things off later (if it's the last targetless constraint encountered) */
                                targetless = (bKinematicConstraint *)con->data;
-                               
+
                                /* but, if this is a targetless IK, we make it auto anyway (for the children loop) */
                                if (con->enforce != 0.0f) {
                                        data->flag |= CONSTRAINT_IK_AUTO;
-                                       
+
                                        /* if no chain length has been specified, just make things obey standard rotation locks too */
                                        if (data->rootbone == 0) {
                                                for (; pchan; pchan = pchan->parent) {
@@ -893,11 +930,11 @@ static short pose_grab_with_ik_add(bPoseChannel *pchan)
                                                        if (pchan->protectflag & OB_LOCK_ROTZ) pchan->ikflag |= BONE_IK_NO_ZDOF_TEMP;
                                                }
                                        }
-                                       
-                                       return 0; 
+
+                                       return 0;
                                }
                        }
-                       
+
                        if ((con->flag & CONSTRAINT_DISABLE) == 0 && (con->enforce != 0.0f))
                                return 0;
                }
@@ -915,7 +952,7 @@ static short pose_grab_with_ik_add(bPoseChannel *pchan)
        data->flag |= CONSTRAINT_IK_TEMP | CONSTRAINT_IK_AUTO | CONSTRAINT_IK_POS;
        copy_v3_v3(data->grabtarget, pchan->pose_tail);
        data->rootbone = 0; /* watch-it! has to be 0 here, since we're still on the same bone for the first time through the loop [#25885] */
-       
+
        /* we only include bones that are part of a continual connected chain */
        do {
                /* here, we set ik-settings for bone from pchan->protectflag */
@@ -923,10 +960,10 @@ static short pose_grab_with_ik_add(bPoseChannel *pchan)
                if (pchan->protectflag & OB_LOCK_ROTX) pchan->ikflag |= BONE_IK_NO_XDOF_TEMP;
                if (pchan->protectflag & OB_LOCK_ROTY) pchan->ikflag |= BONE_IK_NO_YDOF_TEMP;
                if (pchan->protectflag & OB_LOCK_ROTZ) pchan->ikflag |= BONE_IK_NO_ZDOF_TEMP;
-               
+
                /* now we count this pchan as being included */
                data->rootbone++;
-               
+
                /* continue to parent, but only if we're connected to it */
                if (pchan->bone->flag & BONE_CONNECTED)
                        pchan = pchan->parent;
@@ -1095,7 +1132,7 @@ void restoreBones(TransInfo *t)
 
        while (bid->bone) {
                ebo = bid->bone;
-               
+
                ebo->dist = bid->dist;
                ebo->rad_tail = bid->rad_tail;
                ebo->roll = bid->roll;
@@ -1103,7 +1140,7 @@ void restoreBones(TransInfo *t)
                ebo->zwidth = bid->zwidth;
                copy_v3_v3(ebo->head, bid->head);
                copy_v3_v3(ebo->tail, bid->tail);
-               
+
                if (arm->flag & ARM_MIRROR_EDIT) {
                        EditBone *ebo_child;
 
@@ -1122,7 +1159,7 @@ void restoreBones(TransInfo *t)
                                parent->rad_tail = ebo->rad_head;
                        }
                }
-               
+
                bid++;
        }
 }
@@ -1140,7 +1177,7 @@ static void createTransArmatureVerts(TransInfo *t)
        int total_mirrored = 0, i;
        int oldtot;
        BoneInitData *bid;
-       
+
        t->total = 0;
        for (ebo = edbo->first; ebo; ebo = ebo->next) {
                oldtot = t->total;
@@ -1163,7 +1200,7 @@ static void createTransArmatureVerts(TransInfo *t)
                }
 
                if (mirror && (oldtot < t->total)) {
-                       eboflip = ED_armature_bone_get_mirrored(arm->edbo, ebo);
+                       eboflip = ED_armature_ebone_get_mirrored(arm->edbo, ebo);
                        if (eboflip)
                                total_mirrored++;
                }
@@ -1333,7 +1370,7 @@ static void createTransArmatureVerts(TransInfo *t)
                }
 
                if (mirror && (td_old != td)) {
-                       eboflip = ED_armature_bone_get_mirrored(arm->edbo, ebo);
+                       eboflip = ED_armature_ebone_get_mirrored(arm->edbo, ebo);
                        if (eboflip) {
                                bid[i].bone = eboflip;
                                bid[i].dist = eboflip->dist;
@@ -1488,6 +1525,48 @@ static TransDataCurveHandleFlags *initTransDataCurveHandles(TransData *td, struc
        return hdata;
 }
 
+/**
+ * For the purpose of transform code we need to behave as if handles are selected,
+ * even when they aren't (see special case below).
+ */
+static int bezt_select_to_transform_triple_flag(
+        const BezTriple *bezt, const bool hide_handles)
+{
+       int flag = 0;
+
+       if (hide_handles) {
+               if (bezt->f2 & SELECT) {
+                       flag = (1 << 0) | (1 << 1) | (1 << 2);
+               }
+       }
+       else {
+               flag = (
+                       ((bezt->f1 & SELECT) ? (1 << 0) : 0) |
+                       ((bezt->f2 & SELECT) ? (1 << 1) : 0) |
+                       ((bezt->f3 & SELECT) ? (1 << 2) : 0)
+               );
+       }
+
+       /* Special case for auto & aligned handles:
+        * When a center point is being moved without the handles,
+        * leaving the handles stationary makes no sense and only causes strange behavior,
+        * where one handle is arbitrarily anchored, the other one is aligned and lengthened
+        * based on where the center point is moved. Also a bug when cancelling, see: T52007.
+        *
+        * A more 'correct' solution could be to store handle locations in 'TransDataCurveHandleFlags'.
+        * However that doesn't resolve odd behavior, so best transform the handles in this case.
+        */
+       if ((flag != ((1 << 0) | (1 << 1) | (1 << 2))) && (flag & (1 << 1))) {
+               if (ELEM(bezt->h1, HD_AUTO, HD_ALIGN) &&
+                   ELEM(bezt->h2, HD_AUTO, HD_ALIGN))
+               {
+                       flag = (1 << 0) | (1 << 1) | (1 << 2);
+               }
+       }
+
+       return flag;
+}
+
 static void createTransCurveVerts(TransInfo *t)
 {
        Curve *cu = t->obedit->data;
@@ -1505,22 +1584,22 @@ static void createTransCurveVerts(TransInfo *t)
        /* to be sure */
        if (cu->editnurb == NULL) return;
 
+#define SEL_F1 (1 << 0)
+#define SEL_F2 (1 << 1)
+#define SEL_F3 (1 << 2)
+
        /* count total of vertices, check identical as in 2nd loop for making transdata! */
        nurbs = BKE_curve_editNurbs_get(cu);
        for (nu = nurbs->first; nu; nu = nu->next) {
                if (nu->type == CU_BEZIER) {
                        for (a = 0, bezt = nu->bezt; a < nu->pntsu; a++, bezt++) {
                                if (bezt->hide == 0) {
-                                       if (hide_handles) {
-                                               if (bezt->f2 & SELECT) countsel += 3;
-                                               if (is_prop_edit) count += 3;
-                                       }
-                                       else {
-                                               if (bezt->f1 & SELECT) countsel++;
-                                               if (bezt->f2 & SELECT) countsel++;
-                                               if (bezt->f3 & SELECT) countsel++;
-                                               if (is_prop_edit) count += 3;
-                                       }
+                                       const int bezt_tx = bezt_select_to_transform_triple_flag(bezt, hide_handles);
+                                       if (bezt_tx & SEL_F1) { countsel++; }
+                                       if (bezt_tx & SEL_F2) { countsel++; }
+                                       if (bezt_tx & SEL_F3) { countsel++; }
+                                       if (is_prop_edit) count += 3;
+
                                }
                        }
                }
@@ -1571,10 +1650,10 @@ static void createTransCurveVerts(TransInfo *t)
                                                }
                                        }
 
-                                       if (is_prop_edit ||
-                                           ((bezt->f2 & SELECT) && hide_handles) ||
-                                           ((bezt->f1 & SELECT) && hide_handles == 0))
-                                       {
+                                       /* Elements that will be transform (not always a match to selection). */
+                                       const int bezt_tx = bezt_select_to_transform_triple_flag(bezt, hide_handles);
+
+                                       if (is_prop_edit || bezt_tx & SEL_F1) {
                                                copy_v3_v3(td->iloc, bezt->vec[0]);
                                                td->loc = bezt->vec[0];
                                                copy_v3_v3(td->center, bezt->vec[(hide_handles ||
@@ -1605,7 +1684,7 @@ static void createTransCurveVerts(TransInfo *t)
                                        }
 
                                        /* This is the Curve Point, the other two are handles */
-                                       if (is_prop_edit || (bezt->f2 & SELECT)) {
+                                       if (is_prop_edit || bezt_tx & SEL_F2) {
                                                copy_v3_v3(td->iloc, bezt->vec[1]);
                                                td->loc = bezt->vec[1];
                                                copy_v3_v3(td->center, td->loc);
@@ -1631,7 +1710,7 @@ static void createTransCurveVerts(TransInfo *t)
                                                        copy_m3_m3(td->axismtx, axismtx);
                                                }
 
-                                               if ((bezt->f1 & SELECT) == 0 && (bezt->f3 & SELECT) == 0)
+                                               if ((bezt_tx & SEL_F1) == 0 && (bezt_tx & SEL_F3) == 0)
                                                        /* If the middle is selected but the sides arnt, this is needed */
                                                        if (hdata == NULL) { /* if the handle was not saved by the previous handle */
                                                                hdata = initTransDataCurveHandles(td, bezt);
@@ -1641,10 +1720,7 @@ static void createTransCurveVerts(TransInfo *t)
                                                count++;
                                                tail++;
                                        }
-                                       if (is_prop_edit ||
-                                           ((bezt->f2 & SELECT) && hide_handles) ||
-                                           ((bezt->f3 & SELECT) && hide_handles == 0))
-                                       {
+                                       if (is_prop_edit || bezt_tx & SEL_F3) {
                                                copy_v3_v3(td->iloc, bezt->vec[2]);
                                                td->loc = bezt->vec[2];
                                                copy_v3_v3(td->center, bezt->vec[(hide_handles ||
@@ -1699,6 +1775,26 @@ static void createTransCurveVerts(TransInfo *t)
                        for (a = nu->pntsu * nu->pntsv, bp = nu->bp; a > 0; a--, bp++) {
                                if (bp->hide == 0) {
                                        if (is_prop_edit || (bp->f1 & SELECT)) {
+                                               float axismtx[3][3];
+
+                                               if (t->around == V3D_AROUND_LOCAL_ORIGINS) {
+                                                       if (nu->pntsv == 1) {
+                                                               float normal[3], plane[3];
+
+                                                               BKE_nurb_bpoint_calc_normal(nu, bp, normal);
+                                                               BKE_nurb_bpoint_calc_plane(nu, bp, plane);
+
+                                                               if (createSpaceNormalTangent(axismtx, normal, plane)) {
+                                                                       /* pass */
+                                                               }
+                                                               else {
+                                                                       normalize_v3(normal);
+                                                                       axis_dominant_v3_to_m3(axismtx, normal);
+                                                                       invert_m3(axismtx);
+                                                               }
+                                                       }
+                                               }
+
                                                copy_v3_v3(td->iloc, bp->vec);
                                                td->loc = bp->vec;
                                                copy_v3_v3(td->center, td->loc);
@@ -1717,6 +1813,11 @@ static void createTransCurveVerts(TransInfo *t)
 
                                                copy_m3_m3(td->smtx, smtx);
                                                copy_m3_m3(td->mtx, mtx);
+                                               if (t->around == V3D_AROUND_LOCAL_ORIGINS) {
+                                                       if (nu->pntsv == 1) {
+                                                               copy_m3_m3(td->axismtx, axismtx);
+                                                       }
+                                               }
 
                                                td++;
                                                count++;
@@ -1732,6 +1833,10 @@ static void createTransCurveVerts(TransInfo *t)
                                calc_distanceCurveVerts(head, tail - 1);
                }
        }
+
+#undef SEL_F1
+#undef SEL_F2
+#undef SEL_F3
 }
 
 /* ********************* lattice *************** */
@@ -1800,7 +1905,6 @@ static void createTransParticleVerts(bContext *C, TransInfo *t)
 {
        TransData *td = NULL;
        TransDataExtension *tx;
-       Base *base = CTX_data_active_base(C);
        Object *ob = CTX_data_active_object(C);
        ParticleEditSettings *pset = PE_settings(t->scene);
        PTCacheEdit *edit = PE_get_current(t->scene, ob);
@@ -1820,8 +1924,6 @@ static void createTransParticleVerts(bContext *C, TransInfo *t)
        if (psys)
                psmd = psys_get_modifier(ob, psys);
 
-       base->flag |= BA_HAS_RECALC_DATA;
-
        for (i = 0, point = edit->points; i < edit->totpoint; i++, point++) {
                point->flag &= ~PEP_TRANSFORM;
                transformparticle = 0;
@@ -1965,9 +2067,12 @@ void flushTransParticles(TransInfo *t)
 
 /* ********************* mesh ****************** */
 
-static bool bmesh_test_dist_add(BMVert *v, BMVert *v_other,
-                                float *dists, const float *dists_prev,
-                                float mtx[3][3])
+static bool bmesh_test_dist_add(
+        BMVert *v, BMVert *v_other,
+        float *dists, const float *dists_prev,
+        /* optionally track original index */
+        int *index, const int *index_prev,
+        float mtx[3][3])
 {
        if ((BM_elem_flag_test(v_other, BM_ELEM_SELECT) == 0) &&
            (BM_elem_flag_test(v_other, BM_ELEM_HIDDEN) == 0))
@@ -1982,6 +2087,9 @@ static bool bmesh_test_dist_add(BMVert *v, BMVert *v_other,
                dist_other = dists_prev[i] + len_v3(vec);
                if (dist_other < dists[i_other]) {
                        dists[i_other] = dist_other;
+                       if (index != NULL) {
+                               index[i_other] = index_prev[i];
+                       }
                        return true;
                }
        }
@@ -1989,11 +2097,13 @@ static bool bmesh_test_dist_add(BMVert *v, BMVert *v_other,
        return false;
 }
 
-static void editmesh_set_connectivity_distance(BMesh *bm, float mtx[3][3], float *dists)
+/**
+ * \param mtx: Measure disatnce in this space.
+ * \param dists: Store the closest connected distance to selected vertices.
+ * \param index: Optionally store the original index we're measuring the distance to (can be NULL).
+ */
+static void editmesh_set_connectivity_distance(BMesh *bm, float mtx[3][3], float *dists, int *index)
 {
-       /* need to be very careful of feedback loops here, store previous dist's to avoid feedback */
-       float *dists_prev = MEM_mallocN(bm->totvert * sizeof(float), __func__);
-
        BLI_LINKSTACK_DECLARE(queue, BMVert *);
 
        /* any BM_ELEM_TAG'd vertex is in 'queue_next', so we don't add in twice */
@@ -2014,17 +2124,27 @@ static void editmesh_set_connectivity_distance(BMesh *bm, float mtx[3][3], float
 
                        if (BM_elem_flag_test(v, BM_ELEM_SELECT) == 0 || BM_elem_flag_test(v, BM_ELEM_HIDDEN)) {
                                dist = FLT_MAX;
+                               if (index != NULL) {
+                                       index[i] = i;
+                               }
                        }
                        else {
                                BLI_LINKSTACK_PUSH(queue, v);
                                dist = 0.0f;
+                               if (index != NULL) {
+                                       index[i] = i;
+                               }
                        }
 
-                       dists[i] = dists_prev[i] = dist;
+                       dists[i] = dist;
                }
                bm->elem_index_dirty &= ~BM_VERT;
        }
 
+       /* need to be very careful of feedback loops here, store previous dist's to avoid feedback */
+       float *dists_prev = MEM_dupallocN(dists);
+       int *index_prev = MEM_dupallocN(index);  /* may be NULL */
+
        do {
                BMVert *v;
                LinkNode *lnk;
@@ -2053,7 +2173,7 @@ static void editmesh_set_connectivity_distance(BMesh *bm, float mtx[3][3], float
                                                /* edge distance */
                                                {
                                                        BMVert *v_other = BM_edge_other_vert(e_iter, v);
-                                                       if (bmesh_test_dist_add(v, v_other, dists, dists_prev, mtx)) {
+                                                       if (bmesh_test_dist_add(v, v_other, dists, dists_prev, index, index_prev, mtx)) {
                                                                if (BM_elem_flag_test(v_other, BM_ELEM_TAG) == 0) {
                                                                        BM_elem_flag_enable(v_other, BM_ELEM_TAG);
                                                                        BLI_LINKSTACK_PUSH(queue_next, v_other);
@@ -2078,7 +2198,7 @@ static void editmesh_set_connectivity_distance(BMesh *bm, float mtx[3][3], float
                                                                    (BM_elem_flag_test(l_iter_radial->f, BM_ELEM_HIDDEN) == 0))
                                                                {
                                                                        BMVert *v_other = l_iter_radial->next->next->v;
-                                                                       if (bmesh_test_dist_add(v, v_other, dists, dists_prev, mtx)) {
+                                                                       if (bmesh_test_dist_add(v, v_other, dists, dists_prev, index, index_prev, mtx)) {
                                                                                if (BM_elem_flag_test(v_other, BM_ELEM_TAG) == 0) {
                                                                                        BM_elem_flag_enable(v_other, BM_ELEM_TAG);
                                                                                        BLI_LINKSTACK_PUSH(queue_next, v_other);
@@ -2102,6 +2222,9 @@ static void editmesh_set_connectivity_distance(BMesh *bm, float mtx[3][3], float
 
                        /* keep in sync, avoid having to do full memcpy each iteration */
                        dists_prev[i] = dists[i];
+                       if (index != NULL) {
+                               index_prev[i] = index[i];
+                       }
                }
 
                BLI_LINKSTACK_SWAP(queue, queue_next);
@@ -2115,9 +2238,14 @@ static void editmesh_set_connectivity_distance(BMesh *bm, float mtx[3][3], float
        BLI_LINKSTACK_FREE(queue_next);
 
        MEM_freeN(dists_prev);
+       if (index_prev != NULL) {
+               MEM_freeN(index_prev);
+       }
 }
 
-static struct TransIslandData *editmesh_islands_info_calc(BMEditMesh *em, int *r_island_tot, int **r_island_vert_map)
+static struct TransIslandData *editmesh_islands_info_calc(
+        BMEditMesh *em, int *r_island_tot, int **r_island_vert_map,
+        bool calc_single_islands)
 {
        BMesh *bm = em->bm;
        struct TransIslandData *trans_islands;
@@ -2229,6 +2357,42 @@ static struct TransIslandData *editmesh_islands_info_calc(BMEditMesh *em, int *r
        MEM_freeN(groups_array);
        MEM_freeN(group_index);
 
+       /* for PET we need islands of 1 so connected vertices can use it with V3D_AROUND_LOCAL_ORIGINS */
+       if (calc_single_islands) {
+               BMIter viter;
+               BMVert *v;
+               int group_tot_single = 0;
+
+               BM_ITER_MESH_INDEX (v, &viter, bm, BM_VERTS_OF_MESH, i) {
+                       if (BM_elem_flag_test(v, BM_ELEM_SELECT) && (vert_map[i] == -1)) {
+                               group_tot_single += 1;
+                       }
+               }
+
+               if (group_tot_single != 0) {
+                       trans_islands = MEM_reallocN(trans_islands, sizeof(*trans_islands) * (group_tot + group_tot_single));
+
+                       BM_ITER_MESH_INDEX (v, &viter, bm, BM_VERTS_OF_MESH, i) {
+                               if (BM_elem_flag_test(v, BM_ELEM_SELECT) && (vert_map[i] == -1)) {
+                                       struct TransIslandData *v_island = &trans_islands[group_tot];
+                                       vert_map[i] = group_tot;
+
+                                       copy_v3_v3(v_island->co, v->co);
+
+                                       if (is_zero_v3(v->no) != 0.0f) {
+                                               axis_dominant_v3_to_m3(v_island->axismtx, v->no);
+                                               invert_m3(v_island->axismtx);
+                                       }
+                                       else {
+                                               unit_m3(v_island->axismtx);
+                                       }
+
+                                       group_tot += 1;
+                               }
+                       }
+               }
+       }
+
        *r_island_tot = group_tot;
        *r_island_vert_map = vert_map;
 
@@ -2328,6 +2492,12 @@ static void createTransEditVerts(TransInfo *t)
        int island_info_tot;
        int *island_vert_map = NULL;
 
+       /* Even for translation this is needed because of island-orientation, see: T51651. */
+       const bool is_island_center = (t->around == V3D_AROUND_LOCAL_ORIGINS);
+       /* Original index of our connected vertex when connected distances are calculated.
+        * Optional, allocate if needed. */
+       int *dists_index = NULL;
+
        if (t->flag & T_MIRROR) {
                EDBM_verts_mirror_cache_begin(em, 0, false, (t->flag & T_PROP_EDIT) == 0, use_topology);
                mirror = 1;
@@ -2359,8 +2529,12 @@ static void createTransEditVerts(TransInfo *t)
                t->total = count;
 
                /* allocating scratch arrays */
-               if (prop_mode & T_PROP_CONNECTED)
-                       dists = MEM_mallocN(em->bm->totvert * sizeof(float), "scratch nears");
+               if (prop_mode & T_PROP_CONNECTED) {
+                       dists = MEM_mallocN(em->bm->totvert * sizeof(float), __func__);
+                       if (is_island_center) {
+                               dists_index =  MEM_mallocN(em->bm->totvert * sizeof(int), __func__);
+                       }
+               }
        }
        else {
                t->total = bm->totvertsel;
@@ -2382,11 +2556,17 @@ static void createTransEditVerts(TransInfo *t)
        pseudoinverse_m3_m3(smtx, mtx, PSEUDOINVERSE_EPSILON);
 
        if (prop_mode & T_PROP_CONNECTED) {
-               editmesh_set_connectivity_distance(em->bm, mtx, dists);
+               editmesh_set_connectivity_distance(em->bm, mtx, dists, dists_index);
        }
 
-       if (t->around == V3D_AROUND_LOCAL_ORIGINS) {
-               island_info = editmesh_islands_info_calc(em, &island_info_tot, &island_vert_map);
+       if (is_island_center) {
+               /* In this specific case, near-by vertices will need to know the island of the nearest connected vertex. */
+               const bool calc_single_islands = (
+                       (prop_mode & T_PROP_CONNECTED) &&
+                       (t->around == V3D_AROUND_LOCAL_ORIGINS) &&
+                       (em->selectmode & SCE_SELECT_VERTEX));
+
+               island_info = editmesh_islands_info_calc(em, &island_info_tot, &island_vert_map, calc_single_islands);
        }
 
        /* detect CrazySpace [tm] */
@@ -2436,10 +2616,16 @@ static void createTransEditVerts(TransInfo *t)
        BM_ITER_MESH_INDEX (eve, &iter, bm, BM_VERTS_OF_MESH, a) {
                if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) {
                        if (prop_mode || BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
-                               struct TransIslandData *v_island = (island_info && island_vert_map[a] != -1) ?
-                                                                  &island_info[island_vert_map[a]] : NULL;
+                               struct TransIslandData *v_island = NULL;
                                float *bweight = (cd_vert_bweight_offset != -1) ? BM_ELEM_CD_GET_VOID_P(eve, cd_vert_bweight_offset) : NULL;
 
+                               if (island_info) {
+                                       const int connected_index = (dists_index && dists_index[a] != -1) ? dists_index[a] : a;
+                                       v_island = (island_vert_map[connected_index] != -1) ?
+                                                  &island_info[island_vert_map[connected_index]] : NULL;
+                               }
+
+
                                VertsToTransData(t, tob, tx, em, eve, bweight, v_island);
                                if (tx)
                                        tx++;
@@ -2495,7 +2681,7 @@ static void createTransEditVerts(TransInfo *t)
                        }
                }
        }
-       
+
        if (island_info) {
                MEM_freeN(island_info);
                MEM_freeN(island_vert_map);
@@ -2518,6 +2704,8 @@ cleanup:
                MEM_freeN(defmats);
        if (dists)
                MEM_freeN(dists);
+       if (dists_index)
+               MEM_freeN(dists_index);
 
        if (t->flag & T_MIRROR) {
                EDBM_verts_mirror_cache_end(em);
@@ -2531,9 +2719,9 @@ void flushTransNodes(TransInfo *t)
        int a;
        TransData *td;
        TransData2D *td2d;
-       
+
        applyGridAbsolute(t);
-       
+
        /* flush to 2d vector from internally used 3d vector */
        for (a = 0, td = t->data, td2d = t->data2d; a < t->total; a++, td++, td2d++) {
                bNode *node = td->extra;
@@ -2547,7 +2735,7 @@ void flushTransNodes(TransInfo *t)
                locx = td2d->loc[0] / dpi_fac;
                locy = td2d->loc[1] / dpi_fac;
 #endif
-               
+
                /* account for parents (nested nodes) */
                if (node->parent) {
                        nodeFromView(node->parent, locx, locy, &node->locx, &node->locy);
@@ -2557,7 +2745,7 @@ void flushTransNodes(TransInfo *t)
                        node->locy = locy;
                }
        }
-       
+
        /* handle intersection with noodles */
        if (t->total == 1) {
                ED_node_link_intersect_test(t->sa, 1);
@@ -2610,7 +2798,7 @@ void flushTransSeq(TransInfo *t)
                tdsq = (TransDataSeq *)td->extra;
                seq = tdsq->seq;
                old_start = seq->start;
-               new_frame = iroundf(td2d->loc[0]);
+               new_frame = round_fl_to_int(td2d->loc[0]);
 
                switch (tdsq->sel_flag) {
                        case SELECT:
@@ -2622,7 +2810,7 @@ void flushTransSeq(TransInfo *t)
                                        seq->start = new_frame - tdsq->start_offset;
 #endif
                                if (seq->depth == 0) {
-                                       seq->machine = iroundf(td2d->loc[1]);
+                                       seq->machine = round_fl_to_int(td2d->loc[1]);
                                        CLAMP(seq->machine, 1, MAXSEQ);
                                }
                                break;
@@ -2884,7 +3072,7 @@ static void createTransUVs(bContext *C, TransInfo *t)
                                        center = island_center[element->island].co;
                                }
                        }
-                       
+
                        BM_elem_flag_enable(l, BM_ELEM_TAG);
                        luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
                        UVsToTransData(t->aspect, td++, td2d++, luv->uv, center, selected);
@@ -3032,28 +3220,28 @@ static void createTransNlaData(bContext *C, TransInfo *t)
        SpaceNla *snla = NULL;
        TransData *td = NULL;
        TransDataNla *tdn = NULL;
-       
+
        bAnimContext ac;
        ListBase anim_data = {NULL, NULL};
        bAnimListElem *ale;
        int filter;
-       
+
        int count = 0;
-       
+
        /* determine what type of data we are operating on */
        if (ANIM_animdata_get_context(C, &ac) == 0)
                return;
        snla = (SpaceNla *)ac.sl;
-       
+
        /* filter data */
        filter = (ANIMFILTER_DATA_VISIBLE | ANIMFILTER_LIST_VISIBLE | ANIMFILTER_FOREDIT);
        ANIM_animdata_filter(&ac, &anim_data, filter, ac.data, ac.datatype);
-       
+
        /* which side of the current frame should be allowed */
        if (t->mode == TFM_TIME_EXTEND) {
                /* only side on which mouse is gets transformed */
                float xmouse, ymouse;
-               
+
                UI_view2d_region_to_view(&ac.ar->v2d, t->mouse.imval[0], t->mouse.imval[1], &xmouse, &ymouse);
                t->frame_side = (xmouse > CFRA) ? 'R' : 'L';
        }
@@ -3061,15 +3249,15 @@ static void createTransNlaData(bContext *C, TransInfo *t)
                /* normal transform - both sides of current frame are considered */
                t->frame_side = 'B';
        }
-       
+
        /* loop 1: count how many strips are selected (consider each strip as 2 points) */
        for (ale = anim_data.first; ale; ale = ale->next) {
                NlaTrack *nlt = (NlaTrack *)ale->data;
                NlaStrip *strip;
-               
+
                /* make some meta-strips for chains of selected strips */
                BKE_nlastrips_make_metas(&nlt->strips, 1);
-               
+
                /* only consider selected strips */
                for (strip = nlt->strips.first; strip; strip = strip->next) {
                        // TODO: we can make strips have handles later on...
@@ -3082,30 +3270,30 @@ static void createTransNlaData(bContext *C, TransInfo *t)
                        }
                }
        }
-       
+
        /* stop if trying to build list if nothing selected */
        if (count == 0) {
-               /* clear temp metas that may have been created but aren't needed now 
+               /* clear temp metas that may have been created but aren't needed now
                 * because they fell on the wrong side of CFRA
                 */
                for (ale = anim_data.first; ale; ale = ale->next) {
                        NlaTrack *nlt = (NlaTrack *)ale->data;
                        BKE_nlastrips_clear_metas(&nlt->strips, 0, 1);
                }
-               
+
                /* cleanup temp list */
                ANIM_animdata_freelist(&anim_data);
                return;
        }
-       
+
        /* allocate memory for data */
        t->total = count;
-       
+
        t->data = MEM_callocN(t->total * sizeof(TransData), "TransData(NLA Editor)");
        td = t->data;
        t->custom.type.data = tdn = MEM_callocN(t->total * sizeof(TransDataNla), "TransDataNla (NLA Editor)");
        t->custom.type.use_free = true;
-       
+
        /* loop 2: build transdata array */
        for (ale = anim_data.first; ale; ale = ale->next) {
                /* only if a real NLA-track */
@@ -3113,7 +3301,7 @@ static void createTransNlaData(bContext *C, TransInfo *t)
                        AnimData *adt = ale->adt;
                        NlaTrack *nlt = (NlaTrack *)ale->data;
                        NlaStrip *strip;
-                       
+
                        /* only consider selected strips */
                        for (strip = nlt->strips.first; strip; strip = strip->next) {
                                // TODO: we can make strips have handles later on...
@@ -3130,44 +3318,44 @@ static void createTransNlaData(bContext *C, TransInfo *t)
                                                 *        cases, there will need to be 1 of these tdn elements in the array skipped...
                                                 */
                                                float center[3], yval;
-                                               
+
                                                /* firstly, init tdn settings */
                                                tdn->id = ale->id;
                                                tdn->oldTrack = tdn->nlt = nlt;
                                                tdn->strip = strip;
                                                tdn->trackIndex = BLI_findindex(&adt->nla_tracks, nlt);
-                                               
+
                                                yval = (float)(tdn->trackIndex * NLACHANNEL_STEP(snla));
-                                               
+
                                                tdn->h1[0] = strip->start;
                                                tdn->h1[1] = yval;
                                                tdn->h2[0] = strip->end;
                                                tdn->h2[1] = yval;
-                                               
+
                                                center[0] = (float)CFRA;
                                                center[1] = yval;
                                                center[2] = 0.0f;
-                                               
+
                                                /* set td's based on which handles are applicable */
                                                if (FrameOnMouseSide(t->frame_side, strip->start, (float)CFRA)) {
                                                        /* just set tdn to assume that it only has one handle for now */
                                                        tdn->handle = -1;
-                                                       
+
                                                        /* now, link the transform data up to this data */
                                                        if (ELEM(t->mode, TFM_TRANSLATION, TFM_TIME_EXTEND)) {
                                                                td->loc = tdn->h1;
                                                                copy_v3_v3(td->iloc, tdn->h1);
-                                                               
+
                                                                /* store all the other gunk that is required by transform */
                                                                copy_v3_v3(td->center, center);
                                                                memset(td->axismtx, 0, sizeof(td->axismtx));
                                                                td->axismtx[2][2] = 1.0f;
-                                                               
+
                                                                td->ext = NULL; td->val = NULL;
-                                                               
+
                                                                td->flag |= TD_SELECTED;
                                                                td->dist = 0.0f;
-                                                               
+
                                                                unit_m3(td->mtx);
                                                                unit_m3(td->smtx);
                                                        }
@@ -3176,29 +3364,29 @@ static void createTransNlaData(bContext *C, TransInfo *t)
                                                                td->val = &tdn->h1[0];
                                                                td->ival = tdn->h1[0];
                                                        }
-                                                       
+
                                                        td->extra = tdn;
                                                        td++;
                                                }
                                                if (FrameOnMouseSide(t->frame_side, strip->end, (float)CFRA)) {
                                                        /* if tdn is already holding the start handle, then we're doing both, otherwise, only end */
                                                        tdn->handle = (tdn->handle) ? 2 : 1;
-                                                       
+
                                                        /* now, link the transform data up to this data */
                                                        if (ELEM(t->mode, TFM_TRANSLATION, TFM_TIME_EXTEND)) {
                                                                td->loc = tdn->h2;
                                                                copy_v3_v3(td->iloc, tdn->h2);
-                                                               
+
                                                                /* store all the other gunk that is required by transform */
                                                                copy_v3_v3(td->center, center);
                                                                memset(td->axismtx, 0, sizeof(td->axismtx));
                                                                td->axismtx[2][2] = 1.0f;
-                                                               
+
                                                                td->ext = NULL; td->val = NULL;
-                                                               
+
                                                                td->flag |= TD_SELECTED;
                                                                td->dist = 0.0f;
-                                                               
+
                                                                unit_m3(td->mtx);
                                                                unit_m3(td->smtx);
                                                        }
@@ -3207,11 +3395,11 @@ static void createTransNlaData(bContext *C, TransInfo *t)
                                                                td->val = &tdn->h2[0];
                                                                td->ival = tdn->h2[0];
                                                        }
-                                                       
+
                                                        td->extra = tdn;
                                                        td++;
                                                }
-                                               
+
                                                /* if both handles were used, skip the next tdn (i.e. leave it blank) since the counting code is dumb...
                                                 * otherwise, just advance to the next one...
                                                 */
@@ -3224,7 +3412,7 @@ static void createTransNlaData(bContext *C, TransInfo *t)
                        }
                }
        }
-       
+
        /* cleanup temp list */
        ANIM_animdata_freelist(&anim_data);
 }
@@ -3273,7 +3461,7 @@ static int masklay_shape_cmp_frame(void *thunk, const void *a, const void *b)
 static void posttrans_gpd_clean(bGPdata *gpd)
 {
        bGPDlayer *gpl;
-       
+
        for (gpl = gpd->layers.first; gpl; gpl = gpl->next) {
                bGPDframe *gpf, *gpfn;
                bool is_double = false;
@@ -3284,7 +3472,7 @@ static void posttrans_gpd_clean(bGPdata *gpd)
                        for (gpf = gpl->frames.first; gpf; gpf = gpfn) {
                                gpfn = gpf->next;
                                if (gpfn && gpf->framenum == gpfn->framenum) {
-                                       gpencil_layer_delframe(gpl, gpf);
+                                       BKE_gpencil_layer_delframe(gpl, gpf);
                                }
                        }
                }
@@ -3324,65 +3512,134 @@ static void posttrans_mask_clean(Mask *mask)
        }
 }
 
+/* Time + Average value */
+typedef struct tRetainedKeyframe {
+       struct tRetainedKeyframe *next, *prev;
+       float frame;      /* frame to cluster around */
+       float val;        /* average value */
+
+       size_t tot_count; /* number of keyframes that have been averaged */
+       size_t del_count; /* number of keyframes of this sort that have been deleted so far */
+} tRetainedKeyframe;
+
 /* Called during special_aftertrans_update to make sure selected keyframes replace
  * any other keyframes which may reside on that frame (that is not selected).
  */
 static void posttrans_fcurve_clean(FCurve *fcu, const bool use_handle)
 {
-       float *selcache;    /* cache for frame numbers of selected frames (fcu->totvert*sizeof(float)) */
-       int len, index, i;  /* number of frames in cache, item index */
+       /* NOTE: We assume that all keys are sorted */
+       ListBase retained_keys = {NULL, NULL};
+       const bool can_average_points = ((fcu->flag & (FCURVE_INT_VALUES | FCURVE_DISCRETE_VALUES)) == 0);
 
-       /* allocate memory for the cache */
-       // TODO: investigate using BezTriple columns instead?
-       if (fcu->totvert == 0 || fcu->bezt == NULL)
+       /* sanity checks */
+       if ((fcu->totvert == 0) || (fcu->bezt == NULL))
                return;
-       selcache = MEM_callocN(sizeof(float) * fcu->totvert, "FCurveSelFrameNums");
-       len = 0;
-       index = 0;
 
-       /* We do 2 loops, 1 for marking keyframes for deletion, one for deleting
-        * as there is no guarantee what order the keyframes are exactly, even though
-        * they have been sorted by time.
+       /* 1) Identify selected keyframes, and average the values on those
+        * in case there are collisions due to multiple keys getting scaled
+        * to all end up on the same frame
         */
-
-       /*      Loop 1: find selected keyframes   */
-       for (i = 0; i < fcu->totvert; i++) {
+       for (int i = 0; i < fcu->totvert; i++) {
                BezTriple *bezt = &fcu->bezt[i];
-               
+
                if (BEZT_ISSEL_ANY(bezt)) {
-                       selcache[index] = bezt->vec[1][0];
-                       index++;
-                       len++;
+                       bool found = false;
+
+                       /* If there's another selected frame here, merge it */
+                       for (tRetainedKeyframe *rk = retained_keys.last; rk; rk = rk->prev) {
+                               if (IS_EQT(rk->frame, bezt->vec[1][0], BEZT_BINARYSEARCH_THRESH)) {
+                                       rk->val += bezt->vec[1][1];
+                                       rk->tot_count++;
+
+                                       found = true;
+                                       break;
+                               }
+                               else if (rk->frame < bezt->vec[1][0]) {
+                                       /* Terminate early if have passed the supposed insertion point? */
+                                       break;
+                               }
+                       }
+
+                       /* If nothing found yet, create a new one */
+                       if (found == false) {
+                               tRetainedKeyframe *rk = MEM_callocN(sizeof(tRetainedKeyframe), "tRetainedKeyframe");
+
+                               rk->frame = bezt->vec[1][0];
+                               rk->val   = bezt->vec[1][1];
+                               rk->tot_count = 1;
+
+                               BLI_addtail(&retained_keys, rk);
+                       }
+               }
+       }
+
+       if (BLI_listbase_is_empty(&retained_keys)) {
+               /* This may happen if none of the points were selected... */
+               if (G.debug & G_DEBUG) {
+                       printf("%s: nothing to do for FCurve %p (rna_path = '%s')\n", __func__, fcu, fcu->rna_path);
+               }
+               return;
+       }
+       else {
+               /* Compute the average values for each retained keyframe */
+               for (tRetainedKeyframe *rk = retained_keys.first; rk; rk = rk->next) {
+                       rk->val = rk->val / (float)rk->tot_count;
                }
        }
 
-       /* Loop 2: delete unselected keyframes on the same frames 
-        * (if any keyframes were found, or the whole curve wasn't affected) 
+       /* 2) Delete all keyframes duplicating the "retained keys" found above
+        *   - Most of these will be unselected keyframes
+        *   - Some will be selected keyframes though. For those, we only keep the last one
+        *     (or else everything is gone), and replace its value with the averaged value.
         */
-       if ((len) && (len != fcu->totvert)) {
-               for (i = fcu->totvert - 1; i >= 0; i--) {
-                       BezTriple *bezt = &fcu->bezt[i];
-                       
-                       if (BEZT_ISSEL_ANY(bezt) == 0) {
-                               /* check beztriple should be removed according to cache */
-                               for (index = 0; index < len; index++) {
-                                       if (IS_EQF(bezt->vec[1][0], selcache[index])) {
+       for (int i = fcu->totvert - 1; i >= 0; i--) {
+               BezTriple *bezt = &fcu->bezt[i];
+
+               /* Is this keyframe a candidate for deletion? */
+               /* TODO: Replace loop with an O(1) lookup instead */
+               for (tRetainedKeyframe *rk = retained_keys.last; rk; rk = rk->prev) {
+                       if (IS_EQT(bezt->vec[1][0], rk->frame, BEZT_BINARYSEARCH_THRESH)) {
+                               /* Selected keys are treated with greater care than unselected ones... */
+                               if (BEZT_ISSEL_ANY(bezt)) {
+                                       /* - If this is the last selected key left (based on rk->del_count) ==> UPDATE IT
+                                        *   (or else we wouldn't have any keyframe left here)
+                                        * - Otherwise, there are still other selected keyframes on this frame
+                                        *   to be merged down still ==> DELETE IT
+                                        */
+                                       if (rk->del_count == rk->tot_count - 1) {
+                                               /* Update keyframe... */
+                                               if (can_average_points) {
+                                                       /* TODO: update handles too? */
+                                                       bezt->vec[1][1] = rk->val;
+                                               }
+                                       }
+                                       else {
+                                               /* Delete Keyframe */
                                                delete_fcurve_key(fcu, i, 0);
-                                               break;
                                        }
-                                       else if (bezt->vec[1][0] < selcache[index])
-                                               break;
+
+                                       /* Update count of how many we've deleted
+                                        * - It should only matter that we're doing this for all but the last one
+                                        */
+                                       rk->del_count++;
                                }
+                               else {
+                                       /* Always delete - Unselected keys don't matter */
+                                       delete_fcurve_key(fcu, i, 0);
+                               }
+
+                               /* Stop the RK search... we've found our match now */
+                               break;
                        }
                }
-               
-               testhandles_fcurve(fcu, use_handle);
        }
 
-       /* free cache */
-       MEM_freeN(selcache);
-}
+       /* 3) Recalculate handles */
+       testhandles_fcurve(fcu, use_handle);
 
+       /* cleanup */
+       BLI_freelistN(&retained_keys);
+}
 
 
 /* Called by special_aftertrans_update to make sure selected keyframes replace
@@ -3404,7 +3661,7 @@ static void posttrans_action_clean(bAnimContext *ac, bAction *act)
         */
        for (ale = anim_data.first; ale; ale = ale->next) {
                AnimData *adt = ANIM_nla_mapping_get(ac, ale);
-               
+
                if (adt) {
                        ANIM_nla_mapping_apply_fcurve(adt, ale->key_data, 0, 0);
                        posttrans_fcurve_clean(ale->key_data, false); /* only use handles in graph editor */
@@ -3451,10 +3708,10 @@ static int count_gplayer_frames(bGPDlayer *gpl, char side, float cfra, bool is_p
 {
        bGPDframe *gpf;
        int count = 0, count_all = 0;
-       
+
        if (gpl == NULL)
                return count;
-       
+
        /* only include points that occur on the right side of cfra */
        for (gpf = gpl->frames.first; gpf; gpf = gpf->next) {
                if (FrameOnMouseSide(side, (float)gpf->framenum, cfra)) {
@@ -3463,7 +3720,7 @@ static int count_gplayer_frames(bGPDlayer *gpl, char side, float cfra, bool is_p
                        count_all++;
                }
        }
-       
+
        if (is_prop_edit && count > 0)
                return count_all;
        else
@@ -3533,7 +3790,7 @@ static TransData *ActionFCurveToTransData(TransData *td, TransData2D **td2dv, FC
                        /* only add if on the right 'side' of the current frame */
                        if (FrameOnMouseSide(side, bezt->vec[1][0], cfra)) {
                                TimeToTransData(td, bezt->vec[1], adt, ypos);
-                               
+
                                if (bezt->f2 & SELECT)
                                        td->flag |= TD_SELECTED;
 
@@ -3541,18 +3798,18 @@ static TransData *ActionFCurveToTransData(TransData *td, TransData2D **td2dv, FC
                                td->flag |= TD_MOVEHANDLE1 | TD_MOVEHANDLE2;
                                td2d->h1 = bezt->vec[0];
                                td2d->h2 = bezt->vec[2];
-                               
+
                                copy_v2_v2(td2d->ih1, td2d->h1);
                                copy_v2_v2(td2d->ih2, td2d->h2);
-                               
+
                                td++;
                                td2d++;
                        }
                }
        }
-       
+
        *td2dv = td2d;
-       
+
        return td;
 }
 
@@ -3570,7 +3827,7 @@ void flushTransIntFrameActionData(TransInfo *t)
 
        /* flush data! */
        for (i = 0; i < t->total; i++, tfd++) {
-               *(tfd->sdata) = iroundf(tfd->val);
+               *(tfd->sdata) = round_fl_to_int(tfd->val);
        }
 }
 
@@ -3585,7 +3842,7 @@ static int GPLayerToTransData(TransData *td, tGPFtransdata *tfd, bGPDlayer *gpl,
 {
        bGPDframe *gpf;
        int count = 0;
-       
+
        /* check for select frames on right side of current frame */
        for (gpf = gpl->frames.first; gpf; gpf = gpf->next) {
                if (is_prop_edit || (gpf->flag & GP_FRAME_SELECT)) {
@@ -3593,13 +3850,13 @@ static int GPLayerToTransData(TransData *td, tGPFtransdata *tfd, bGPDlayer *gpl,
                                /* memory is calloc'ed, so that should zero everything nicely for us */
                                td->val = &tfd->val;
                                td->ival = (float)gpf->framenum;
-                               
+
                                td->center[0] = td->ival;
                                td->center[1] = ypos;
 
                                tfd->val = (float)gpf->framenum;
                                tfd->sdata = &gpf->framenum;
-                               
+
                                /* advance td now */
                                td++;
                                tfd++;
@@ -3607,7 +3864,7 @@ static int GPLayerToTransData(TransData *td, tGPFtransdata *tfd, bGPDlayer *gpl,
                        }
                }
        }
-       
+
        return count;
 }
 
@@ -3671,19 +3928,19 @@ static void createTransActionData(bContext *C, TransInfo *t)
        /* determine what type of data we are operating on */
        if (ANIM_animdata_get_context(C, &ac) == 0)
                return;
-       
+
        /* filter data */
        if (ELEM(ac.datatype, ANIMCONT_GPENCIL, ANIMCONT_MASK))
                filter = (ANIMFILTER_DATA_VISIBLE | ANIMFILTER_FOREDIT);
        else
                filter = (ANIMFILTER_DATA_VISIBLE | ANIMFILTER_FOREDIT /*| ANIMFILTER_CURVESONLY*/);
        ANIM_animdata_filter(&ac, &anim_data, filter, ac.data, ac.datatype);
-       
+
        /* which side of the current frame should be allowed */
        if (t->mode == TFM_TIME_EXTEND) {
                /* only side on which mouse is gets transformed */
                float xmouse, ymouse;
-               
+
                UI_view2d_region_to_view(&ac.ar->v2d, t->mouse.imval[0], t->mouse.imval[1], &xmouse, &ymouse);
                t->frame_side = (xmouse > CFRA) ? 'R' : 'L'; // XXX use t->frame_side
        }
@@ -3691,7 +3948,7 @@ static void createTransActionData(bContext *C, TransInfo *t)
                /* normal transform - both sides of current frame are considered */
                t->frame_side = 'B';
        }
-       
+
        /* loop 1: fully select ipo-keys and count how many BezTriples are selected */
        for (ale = anim_data.first; ale; ale = ale->next) {
                AnimData *adt = ANIM_nla_mapping_get(&ac, ale);
@@ -3703,7 +3960,7 @@ static void createTransActionData(bContext *C, TransInfo *t)
                        cfra = BKE_nla_tweakedit_remap(adt, (float)CFRA, NLATIME_CONVERT_UNMAP);
                else
                        cfra = (float)CFRA;
-               
+
                if (ELEM(ale->type, ANIMTYPE_FCURVE, ANIMTYPE_NLACURVE))
                        adt_count = count_fcurve_keys(ale->key_data, t->frame_side, cfra, is_prop_edit);
                else if (ale->type == ANIMTYPE_GPLAYER)
@@ -3718,27 +3975,27 @@ static void createTransActionData(bContext *C, TransInfo *t)
                        ale->tag = true;
                }
        }
-       
+
        /* stop if trying to build list if nothing selected */
        if (count == 0) {
                /* cleanup temp list */
                ANIM_animdata_freelist(&anim_data);
                return;
        }
-       
+
        /* allocate memory for data */
        t->total = count;
-       
+
        t->data = MEM_callocN(t->total * sizeof(TransData), "TransData(Action Editor)");
        t->data2d = MEM_callocN(t->total * sizeof(TransData2D), "transdata2d");
        td = t->data;
        td2d = t->data2d;
-       
+
        if (ELEM(ac.datatype, ANIMCONT_GPENCIL, ANIMCONT_MASK)) {
                t->custom.type.data = tfd = MEM_callocN(sizeof(tGPFtransdata) * count, "tGPFtransdata");
                t->custom.type.use_free = true;
        }
-       
+
        /* loop 2: build transdata array */
        for (ale = anim_data.first; ale; ale = ale->next) {
 
@@ -3758,7 +4015,7 @@ static void createTransActionData(bContext *C, TransInfo *t)
                if (ale->type == ANIMTYPE_GPLAYER) {
                        bGPDlayer *gpl = (bGPDlayer *)ale->data;
                        int i;
-                       
+
                        i = GPLayerToTransData(td, tfd, gpl, t->frame_side, cfra, is_prop_edit, ypos);
                        td += i;
                        tfd += i;
@@ -3774,7 +4031,7 @@ static void createTransActionData(bContext *C, TransInfo *t)
                else {
                        AnimData *adt = ANIM_nla_mapping_get(&ac, ale);
                        FCurve *fcu = (FCurve *)ale->key_data;
-                       
+
                        td = ActionFCurveToTransData(td, &td2d, fcu, adt, t->frame_side, cfra, is_prop_edit, ypos);
                }
        }
@@ -3910,18 +4167,18 @@ static void bezt_to_transdata(TransData *td, TransData2D *td2d, TransDataGraph *
         * Due to NLA mapping, we apply NLA mapping to some of the verts here,
         * and then that mapping will be undone after transform is done.
         */
-       
+
        if (adt) {
                td2d->loc[0] = BKE_nla_tweakedit_remap(adt, loc[0], NLATIME_CONVERT_MAP);
                td2d->loc[1] = (loc[1] + offset) * unit_scale;
                td2d->loc[2] = 0.0f;
                td2d->loc2d = loc;
-               
+
                td->loc = td2d->loc;
                td->center[0] = BKE_nla_tweakedit_remap(adt, cent[0], NLATIME_CONVERT_MAP);
                td->center[1] = (cent[1] + offset) * unit_scale;
                td->center[2] = 0.0f;
-               
+
                copy_v3_v3(td->iloc, td->loc);
        }
        else {
@@ -3929,7 +4186,7 @@ static void bezt_to_transdata(TransData *td, TransData2D *td2d, TransDataGraph *
                td2d->loc[1] = (loc[1] + offset) * unit_scale;
                td2d->loc[2] = 0.0f;
                td2d->loc2d = loc;
-               
+
                td->loc = td2d->loc;
                copy_v3_v3(td->center, cent);
                td->center[1] = (td->center[1] + offset) * unit_scale;
@@ -3949,19 +4206,19 @@ static void bezt_to_transdata(TransData *td, TransData2D *td2d, TransDataGraph *
 
        memset(td->axismtx, 0, sizeof(td->axismtx));
        td->axismtx[2][2] = 1.0f;
-       
+
        td->ext = NULL; td->val = NULL;
-       
+
        /* store AnimData info in td->extra, for applying mapping when flushing */
        td->extra = adt;
-       
+
        if (selected) {
                td->flag |= TD_SELECTED;
                td->dist = 0.0f;
        }
        else
                td->dist = FLT_MAX;
-       
+
        if (ishandle)
                td->flag |= TD_NOTIMESNAP;
        if (intvals)
@@ -4015,16 +4272,16 @@ static void createTransGraphEditData(bContext *C, TransInfo *t)
        Scene *scene = t->scene;
        ARegion *ar = t->ar;
        View2D *v2d = &ar->v2d;
-       
+
        TransData *td = NULL;
        TransData2D *td2d = NULL;
        TransDataGraph *tdg = NULL;
-       
+
        bAnimContext ac;
        ListBase anim_data = {NULL, NULL};
        bAnimListElem *ale;
        int filter;
-       
+
        BezTriple *bezt;
        int count = 0, i;
        float mtx[3][3], smtx[3][3];
@@ -4033,7 +4290,7 @@ static void createTransGraphEditData(bContext *C, TransInfo *t)
        const bool use_local_center = graph_edit_use_local_center(t);
        const bool is_prop_edit = (t->flag & T_PROP_EDIT) != 0;
        short anim_map_flag = ANIM_UNITCONV_ONLYSEL | ANIM_UNITCONV_SELVERTS;
-       
+
        /* determine what type of data we are operating on */
        if (ANIM_animdata_get_context(C, &ac) == 0)
                return;
@@ -4043,13 +4300,13 @@ static void createTransGraphEditData(bContext *C, TransInfo *t)
        /* filter data */
        filter = (ANIMFILTER_DATA_VISIBLE | ANIMFILTER_FOREDIT | ANIMFILTER_CURVE_VISIBLE);
        ANIM_animdata_filter(&ac, &anim_data, filter, ac.data, ac.datatype);
-       
+
        /* which side of the current frame should be allowed */
        // XXX we still want this mode, but how to get this using standard transform too?
        if (t->mode == TFM_TIME_EXTEND) {
                /* only side on which mouse is gets transformed */
                float xmouse, ymouse;
-               
+
                UI_view2d_region_to_view(v2d, t->mouse.imval[0], t->mouse.imval[1], &xmouse, &ymouse);
                t->frame_side = (xmouse > CFRA) ? 'R' : 'L'; // XXX use t->frame_side
        }
@@ -4057,7 +4314,7 @@ static void createTransGraphEditData(bContext *C, TransInfo *t)
                /* normal transform - both sides of current frame are considered */
                t->frame_side = 'B';
        }
-       
+
        /* loop 1: count how many BezTriples (specifically their verts) are selected (or should be edited) */
        for (ale = anim_data.first; ale; ale = ale->next) {
                AnimData *adt = ANIM_nla_mapping_get(&ac, ale);
@@ -4116,46 +4373,46 @@ static void createTransGraphEditData(bContext *C, TransInfo *t)
                        }
                }
        }
-       
+
        /* stop if trying to build list if nothing selected */
        if (count == 0) {
                /* cleanup temp list */
                ANIM_animdata_freelist(&anim_data);
                return;
        }
-       
+
        /* allocate memory for data */
        t->total = count;
-       
+
        t->data = MEM_callocN(t->total * sizeof(TransData), "TransData (Graph Editor)");
        /* for each 2d vert a 3d vector is allocated, so that they can be treated just as if they were 3d verts */
        t->data2d = MEM_callocN(t->total * sizeof(TransData2D), "TransData2D (Graph Editor)");
        t->custom.type.data = MEM_callocN(t->total * sizeof(TransDataGraph), "TransDataGraph");
        t->custom.type.use_free = true;
-       
+
        td = t->data;
        td2d = t->data2d;
        tdg = t->custom.type.data;
-       
+
        /* precompute space-conversion matrices for dealing with non-uniform scaling of Graph Editor */
        unit_m3(mtx);
        unit_m3(smtx);
-       
+
        if (ELEM(t->mode, TFM_ROTATION, TFM_RESIZE)) {
                float xscale, yscale;
-               
+
                /* apply scale factors to x and y axes of space-conversion matrices */
                UI_view2d_scale_get(v2d, &xscale, &yscale);
-               
+
                /* mtx is data to global (i.e. view) conversion */
                mul_v3_fl(mtx[0], xscale);
                mul_v3_fl(mtx[1], yscale);
-               
+
                /* smtx is global (i.e. view) to data conversion */
                if (IS_EQF(xscale, 0.0f) == 0) mul_v3_fl(smtx[0], 1.0f / xscale);
                if (IS_EQF(yscale, 0.0f) == 0) mul_v3_fl(smtx[1], 1.0f / yscale);
        }
-       
+
        /* loop 2: build transdata arrays */
        for (ale = anim_data.first; ale; ale = ale->next) {
                AnimData *adt = ANIM_nla_mapping_get(&ac, ale);
@@ -4187,7 +4444,7 @@ static void createTransGraphEditData(bContext *C, TransInfo *t)
 
                                TransDataCurveHandleFlags *hdata = NULL;
                                /* short h1=1, h2=1; */ /* UNUSED */
-                               
+
                                if (is_prop_edit) {
                                        bool is_sel = (sel2 || sel1 || sel3);
                                        /* we always select all handles for proportional editing if central handle is selected */
@@ -4255,7 +4512,7 @@ static void createTransGraphEditData(bContext *C, TransInfo *t)
                                }
                        }
                }
-               
+
                /* Sets handles based on the selection */
                testhandles_fcurve(fcu, use_handle);
        }
@@ -4343,19 +4600,19 @@ static BeztMap *bezt_to_beztmaps(BezTriple *bezts, int totvert, const short UNUS
        BezTriple *prevbezt = NULL;
        BeztMap *bezm, *bezms;
        int i;
-       
+
        /* allocate memory for this array */
        if (totvert == 0 || bezts == NULL)
                return NULL;
        bezm = bezms = MEM_callocN(sizeof(BeztMap) * totvert, "BeztMaps");
-       
+
        /* assign beztriples to beztmaps */
        for (i = 0; i < totvert; i++, bezm++, prevbezt = bezt, bezt++) {
                bezm->bezt = bezt;
-               
+
                bezm->oldIndex = i;
                bezm->newIndex = i;
-               
+
                bezm->pipo = (prevbezt) ? prevbezt->ipo : bezt->ipo;
                bezm->cipo = bezt->ipo;
        }
@@ -4368,11 +4625,11 @@ static void sort_time_beztmaps(BeztMap *bezms, int totvert, const short UNUSED(u
 {
        BeztMap *bezm;
        int i, ok = 1;
-       
+
        /* keep repeating the process until nothing is out of place anymore */
        while (ok) {
                ok = 0;
-               
+
                bezm = bezms;
                i = totvert;
                while (i--) {
@@ -4381,13 +4638,13 @@ static void sort_time_beztmaps(BeztMap *bezms, int totvert, const short UNUSED(u
                                if (bezm->bezt->vec[1][0] > (bezm + 1)->bezt->vec[1][0]) {
                                        bezm->newIndex++;
                                        (bezm + 1)->newIndex--;
-                                       
+
                                        SWAP(BeztMap, *bezm, *(bezm + 1));
-                                       
+
                                        ok = 1;
                                }
                        }
-                       
+
                        /* do we need to check if the handles need to be swapped?
                         * optimization: this only needs to be performed in the first loop
                         */
@@ -4403,7 +4660,7 @@ static void sort_time_beztmaps(BeztMap *bezms, int totvert, const short UNUSED(u
                                        bezm->swapHs = -1;
                                }
                        }
-                       
+
                        bezm++;
                }
        }
@@ -4418,13 +4675,13 @@ static void beztmap_to_data(TransInfo *t, FCurve *fcu, BeztMap *bezms, int totve
        TransData *td;
        int i, j;
        char *adjusted;
-       
+
        /* dynamically allocate an array of chars to mark whether an TransData's
         * pointers have been fixed already, so that we don't override ones that are
         * already done
         */
        adjusted = MEM_callocN(t->total, "beztmap_adjusted_map");
-       
+
        /* for each beztmap item, find if it is used anywhere */
        bezm = bezms;
        for (i = 0; i < totvert; i++, bezm++) {
@@ -4436,7 +4693,7 @@ static void beztmap_to_data(TransInfo *t, FCurve *fcu, BeztMap *bezms, int totve
                for (j = 0; j < t->total; j++, td2d++, td++) {
                        /* skip item if already marked */
                        if (adjusted[j] != 0) continue;
-                       
+
                        /* update all transdata pointers, no need to check for selections etc,
                         * since only points that are really needed were created as transdata
                         */
@@ -4456,13 +4713,13 @@ static void beztmap_to_data(TransInfo *t, FCurve *fcu, BeztMap *bezms, int totve
                        }
                        else if (td2d->loc2d == bezm->bezt->vec[1]) {
                                td2d->loc2d = (bezts + bezm->newIndex)->vec[1];
-                                       
+
                                /* if only control point is selected, the handle pointers need to be updated as well */
                                if (td2d->h1)
                                        td2d->h1 = (bezts + bezm->newIndex)->vec[0];
                                if (td2d->h2)
                                        td2d->h2 = (bezts + bezm->newIndex)->vec[2];
-                                       
+
                                adjusted[j] = 1;
                        }
 
@@ -4478,9 +4735,9 @@ static void beztmap_to_data(TransInfo *t, FCurve *fcu, BeztMap *bezms, int totve
                                }
                        }
                }
-               
+
        }
-       
+
        /* free temp memory used for 'adjusted' array */
        MEM_freeN(adjusted);
 }
@@ -4497,26 +4754,26 @@ void remake_graph_transdata(TransInfo *t, ListBase *anim_data)
        SpaceIpo *sipo = (SpaceIpo *)t->sa->spacedata.first;
        bAnimListElem *ale;
        const bool use_handle = (sipo->flag & SIPO_NOHANDLES) == 0;
-       
+
        /* sort and reassign verts */
        for (ale = anim_data->first; ale; ale = ale->next) {
                FCurve *fcu = (FCurve *)ale->key_data;
-               
+
                if (fcu->bezt) {
                        BeztMap *bezm;
-                       
+
                        /* adjust transform-data pointers */
                        /* note, none of these functions use 'use_handle', it could be removed */
                        bezm = bezt_to_beztmaps(fcu->bezt, fcu->totvert, use_handle);
                        sort_time_beztmaps(bezm, fcu->totvert, use_handle);
                        beztmap_to_data(t, fcu, bezm, fcu->totvert, use_handle);
-                       
+
                        /* free mapping stuff */
                        MEM_freeN(bezm);
-                       
+
                        /* re-sort actual beztriples (perhaps this could be done using the beztmaps to save time?) */
                        sort_time_fcurve(fcu);
-                       
+
                        /* make sure handles are all set correctly */
                        testhandles_fcurve(fcu, use_handle);
                }
@@ -4554,11 +4811,11 @@ void flushTransGraphData(TransInfo *t)
                                case SACTSNAP_FRAME: /* snap to nearest frame */
                                        td2d->loc[0] = floor((double)td2d->loc[0] + 0.5);
                                        break;
-                               
+
                                case SACTSNAP_SECOND: /* snap to nearest second */
                                        td2d->loc[0] = floor(((double)td2d->loc[0] / secf) + 0.5) * secf;
                                        break;
-                               
+
                                case SACTSNAP_MARKER: /* snap to nearest marker */
                                        td2d->loc[0] = (float)ED_markers_find_nearest_marker_time(&t->scene->markers, td2d->loc[0]);
                                        break;
@@ -4570,7 +4827,7 @@ void flushTransGraphData(TransInfo *t)
                        td2d->loc2d[0] = BKE_nla_tweakedit_remap(adt, td2d->loc[0], NLATIME_CONVERT_UNMAP);
                else
                        td2d->loc2d[0] = td2d->loc[0];
-                       
+
                /* Time-stepping auto-snapping modes don't get applied for Graph Editor transforms,
                 * as these use the generic transform modes which don't account for this sort of thing.
                 * These ones aren't affected by NLA mapping, so we do this after the conversion...
@@ -4579,15 +4836,15 @@ void flushTransGraphData(TransInfo *t)
                 *       to, otherwise we get "swimming handles"
                 * NOTE: We don't do this when canceling transforms, or else these changes don't go away
                 */
-               if ((t->state != TRANS_CANCEL) && (td->flag & TD_NOTIMESNAP) == 0 && 
-                   ELEM(sipo->autosnap, SACTSNAP_STEP, SACTSNAP_TSTEP)) 
+               if ((t->state != TRANS_CANCEL) && (td->flag & TD_NOTIMESNAP) == 0 &&
+                   ELEM(sipo->autosnap, SACTSNAP_STEP, SACTSNAP_TSTEP))
                {
                        switch (sipo->autosnap) {
                                case SACTSNAP_STEP: /* frame step */
                                        td2d->loc2d[0] = floor((double)td2d->loc[0] + 0.5);
                                        td->loc[0]     = floor((double)td->loc[0] + 0.5);
                                        break;
-                               
+
                                case SACTSNAP_TSTEP: /* second step */
                                        /* XXX: the handle behaviour in this case is still not quite right... */
                                        td2d->loc[0] = floor(((double)td2d->loc[0] / secf) + 0.5) * secf;
@@ -4595,18 +4852,18 @@ void flushTransGraphData(TransInfo *t)
                                        break;
                        }
                }
-               
+
                /* if int-values only, truncate to integers */
                if (td->flag & TD_INTVALUES)
-                       td2d->loc2d[1] = floorf(td2d->loc[1] + 0.5f);
+                       td2d->loc2d[1] = floorf(td2d->loc[1] * inv_unit_scale - tdg->offset + 0.5f);
                else
                        td2d->loc2d[1] = td2d->loc[1] * inv_unit_scale - tdg->offset;
-               
+
                if ((td->flag & TD_MOVEHANDLE1) && td2d->h1) {
                        td2d->h1[0] = td2d->ih1[0] + td->loc[0] - td->iloc[0];
                        td2d->h1[1] = td2d->ih1[1] + (td->loc[1] - td->iloc[1]) * inv_unit_scale;
                }
-               
+
                if ((td->flag & TD_MOVEHANDLE2) && td2d->h2) {
                        td2d->h2[0] = td2d->ih2[0] + td->loc[0] - td->iloc[0];
                        td2d->h2[1] = td2d->ih2[1] + (td->loc[1] - td->iloc[1]) * inv_unit_scale;
@@ -5151,7 +5408,7 @@ static void createTransSeqData(bContext *C, TransInfo *t)
        /* loop 2: build transdata array */
        SeqToTransData_Recursive(t, ed->seqbasep, td, td2d, tdsq);
        SeqTransDataBounds(t, ed->seqbasep, ts);
-       
+
        /* set the snap mode based on how close the mouse is at the end/start points */
        if (abs(xmouse - ts->max) > abs(xmouse - ts->min))
                ts->snap_left = true;
@@ -5189,19 +5446,19 @@ static bool constraints_list_needinv(TransInfo *t, ListBase *list)
                                {
                                        return true;
                                }
-                               
+
                                /* constraints that require this only under special conditions */
                                if (con->type == CONSTRAINT_TYPE_CHILDOF) {
                                        /* ChildOf constraint only works when using all location components, see T42256. */
                                        bChildOfConstraint *data = (bChildOfConstraint *)con->data;
-                                       
+
                                        if ((data->flag & CHILDOF_LOCX) && (data->flag & CHILDOF_LOCY) && (data->flag & CHILDOF_LOCZ))
                                                return true;
                                }
                                else if (con->type == CONSTRAINT_TYPE_ROTLIKE) {
                                        /* CopyRot constraint only does this when rotating, and offset is on */
                                        bRotateLikeConstraint *data = (bRotateLikeConstraint *)con->data;
-                                       
+
                                        if ((data->flag & ROTLIKE_OFFSET) && (t->mode == TFM_ROTATION))
                                                return true;
                                }
@@ -5209,7 +5466,7 @@ static bool constraints_list_needinv(TransInfo *t, ListBase *list)
                                        /* Transform constraint needs it for rotation at least (r.57309),
                                         * but doing so when translating may also mess things up [#36203]
                                         */
-                                       
+
                                        if (t->mode == TFM_ROTATION)
                                                return true;
                                        /* ??? (t->mode == TFM_SCALE) ? */
@@ -5251,7 +5508,8 @@ static void ObjectToTransData(TransInfo *t, TransData *td, Object *ob)
                        }
                        /* update object's loc/rot to get current rigid body transform */
                        mat4_to_loc_rot_size(ob->loc, rot, scale, ob->obmat);
-                       BKE_object_mat3_to_rot(ob, rot, false);
+                       sub_v3_v3(ob->loc, ob->dloc);
+                       BKE_object_mat3_to_rot(ob, rot, false); /* drot is already corrected here */
                }
        }
 
@@ -5284,13 +5542,13 @@ static void ObjectToTransData(TransInfo *t, TransData *td, Object *ob)
 
        td->loc = ob->loc;
        copy_v3_v3(td->iloc, td->loc);
-       
+
        if (ob->rotmode > 0) {
                td->ext->rot = ob->rot;
                td->ext->rotAxis = NULL;
                td->ext->rotAngle = NULL;
                td->ext->quat = NULL;
-               
+
                copy_v3_v3(td->ext->irot, ob->rot);
                copy_v3_v3(td->ext->drot, ob->drot);
        }
@@ -5299,7 +5557,7 @@ static void ObjectToTransData(TransInfo *t, TransData *td, Object *ob)
                td->ext->rotAxis = ob->rotAxis;
                td->ext->rotAngle = &ob->rotAngle;
                td->ext->quat = NULL;
-               
+
                td->ext->irotAngle = ob->rotAngle;
                copy_v3_v3(td->ext->irotAxis, ob->rotAxis);
                // td->ext->drotAngle = ob->drotAngle;                  // XXX, not implemented
@@ -5310,7 +5568,7 @@ static void ObjectToTransData(TransInfo *t, TransData *td, Object *ob)
                td->ext->rotAxis = NULL;
                td->ext->rotAngle = NULL;
                td->ext->quat = ob->quat;
-               
+
                copy_qt_qt(td->ext->iquat, ob->quat);
                copy_qt_qt(td->ext->dquat, ob->dquat);
        }
@@ -5414,17 +5672,14 @@ static void set_trans_object_base_flags(TransInfo *t)
        }
 
        /* all recalc flags get flushed to all layers, so a layer flip later on works fine */
-#ifdef WITH_LEGACY_DEPSGRAPH
        DAG_scene_flush_update(G.main, t->scene, -1, 0);
-#endif
 
        /* and we store them temporal in base (only used for transform code) */
        /* this because after doing updates, the object->recalc is cleared */
        for (base = scene->base.first; base; base = base->next) {
-               if (base->object->recalc & OB_RECALC_OB)
-                       base->flag |= BA_HAS_RECALC_OB;
-               if (base->object->recalc & OB_RECALC_DATA)
-                       base->flag |= BA_HAS_RECALC_DATA;
+               if (base->object->recalc & (OB_RECALC_OB | OB_RECALC_DATA)) {
+                       base->flag |= BA_SNAP_FIX_DEPS_FIASCO;
+               }
        }
 }
 
@@ -5439,7 +5694,7 @@ static bool mark_children(Object *ob)
                        return true;
                }
        }
-       
+
        return false;
 }
 
@@ -5458,7 +5713,7 @@ static int count_proportional_objects(TransInfo *t)
                for (base = scene->base.first; base; base = base->next) {
                        if (TESTBASELIB_BGMODE(v3d, scene, base)) {
                                Object *parent = base->object->parent;
-       
+
                                /* flag all parents */
                                while (parent) {
                                        parent->flag |= BA_TRANSFORM_PARENT;
@@ -5477,7 +5732,7 @@ static int count_proportional_objects(TransInfo *t)
                        }
                }
        }
-       
+
        for (base = scene->base.first; base; base = base->next) {
                Object *ob = base->object;
 
@@ -5491,21 +5746,18 @@ static int count_proportional_objects(TransInfo *t)
                        total += 1;
                }
        }
-       
+
 
        /* all recalc flags get flushed to all layers, so a layer flip later on works fine */
        DAG_scene_relations_update(G.main, t->scene);
-#ifdef WITH_LEGACY_DEPSGRAPH
        DAG_scene_flush_update(G.main, t->scene, -1, 0);
-#endif
 
        /* and we store them temporal in base (only used for transform code) */
        /* this because after doing updates, the object->recalc is cleared */
        for (base = scene->base.first; base; base = base->next) {
-               if (base->object->recalc & OB_RECALC_OB)
-                       base->flag |= BA_HAS_RECALC_OB;
-               if (base->object->recalc & OB_RECALC_DATA)
-                       base->flag |= BA_HAS_RECALC_DATA;
+               if (base->object->recalc & (OB_RECALC_OB | OB_RECALC_DATA)) {
+                       base->flag |= BA_SNAP_FIX_DEPS_FIASCO;
+               }
        }
 
        return total;
@@ -5520,7 +5772,7 @@ static void clear_trans_object_base_flags(TransInfo *t)
                if (base->flag & BA_WAS_SEL)
                        base->flag |= SELECT;
 
-               base->flag &= ~(BA_WAS_SEL | BA_HAS_RECALC_OB | BA_HAS_RECALC_DATA | BA_TEMP_TAG | BA_TRANSFORM_CHILD | BA_TRANSFORM_PARENT);
+               base->flag &= ~(BA_WAS_SEL | BA_SNAP_FIX_DEPS_FIASCO | BA_TEMP_TAG | BA_TRANSFORM_CHILD | BA_TRANSFORM_PARENT);
        }
 }
 
@@ -5530,9 +5782,10 @@ static void clear_trans_object_base_flags(TransInfo *t)
 // NOTE: context may not always be available, so must check before using it as it's a luxury for a few cases
 void autokeyframe_ob_cb_func(bContext *C, Scene *scene, View3D *v3d, Object *ob, int tmode)
 {
+       Main *bmain = CTX_data_main(C);
        ID *id = &ob->id;
        FCurve *fcu;
-       
+
        // TODO: this should probably be done per channel instead...
        if (autokeyframe_cfra_can_key(scene, id)) {
                ReportList *reports = CTX_wm_reports(C);
@@ -5541,48 +5794,48 @@ void autokeyframe_ob_cb_func(bContext *C, Scene *scene, View3D *v3d, Object *ob,
                ListBase dsources = {NULL, NULL};
                float cfra = (float)CFRA; // xxx this will do for now
                short flag = 0;
-               
+
                /* get flags used for inserting keyframes */
                flag = ANIM_get_keyframing_flags(scene, 1);
-               
+
                /* add datasource override for the object */
-               ANIM_relative_keyingset_add_source(&dsources, id, NULL, NULL); 
-               
+               ANIM_relative_keyingset_add_source(&dsources, id, NULL, NULL);
+
                if (IS_AUTOKEY_FLAG(scene, ONLYKEYINGSET) && (active_ks)) {
-                       /* only insert into active keyingset 
+                       /* only insert into active keyingset
                         * NOTE: we assume here that the active Keying Set does not need to have its iterator overridden
                         */
                        ANIM_apply_keyingset(C, &dsources, NULL, active_ks, MODIFYKEY_MODE_INSERT, cfra);
                }
                else if (IS_AUTOKEY_FLAG(scene, INSERTAVAIL)) {
                        AnimData *adt = ob->adt;
-                       
+
                        /* only key on available channels */
                        if (adt && adt->action) {
                                for (fcu = adt->action->curves.first; fcu; fcu = fcu->next) {
                                        fcu->flag &= ~FCURVE_SELECTED;
-                                       insert_keyframe(reports, id, adt->action,
+                                       insert_keyframe(bmain, reports, id, adt->action,
                                                        (fcu->grp ? fcu->grp->name : NULL),
-                                                       fcu->rna_path, fcu->array_index, cfra, 
+                                                       fcu->rna_path, fcu->array_index, cfra,
                                                        ts->keyframe_type, flag);
                                }
                        }
                }
                else if (IS_AUTOKEY_FLAG(scene, INSERTNEEDED)) {
                        bool do_loc = false, do_rot = false, do_scale = false;
-                       
+
                        /* filter the conditions when this happens (assume that curarea->spacetype==SPACE_VIE3D) */
                        if (tmode == TFM_TRANSLATION) {
                                do_loc = true;
                        }
-                       else if (tmode == TFM_ROTATION) {
+                       else if (ELEM(tmode, TFM_ROTATION, TFM_TRACKBALL)) {
                                if (v3d->around == V3D_AROUND_ACTIVE) {
                                        if (ob != OBACT)
                                                do_loc = true;
                                }
                                else if (v3d->around == V3D_AROUND_CURSOR)
                                        do_loc = true;
-                               
+
                                if ((v3d->flag & V3D_ALIGN) == 0)
                                        do_rot = true;
                        }
@@ -5593,11 +5846,11 @@ void autokeyframe_ob_cb_func(bContext *C, Scene *scene, View3D *v3d, Object *ob,
                                }
                                else if (v3d->around == V3D_AROUND_CURSOR)
                                        do_loc = true;
-                               
+
                                if ((v3d->flag & V3D_ALIGN) == 0)
                                        do_scale = true;
                        }
-                       
+
                        /* insert keyframes for the affected sets of channels using the builtin KeyingSets found */
                        if (do_loc) {
                                KeyingSet *ks = ANIM_builtin_keyingset_get_named(NULL, ANIM_KS_LOCATION_ID);
@@ -5617,23 +5870,23 @@ void autokeyframe_ob_cb_func(bContext *C, Scene *scene, View3D *v3d, Object *ob,
                        KeyingSet *ks = ANIM_builtin_keyingset_get_named(NULL, ANIM_KS_LOC_ROT_SCALE_ID);
                        ANIM_apply_keyingset(C, &dsources, NULL, ks, MODIFYKEY_MODE_INSERT, cfra);
                }
-               
+
                /* only calculate paths if there are paths to be recalculated,
                 * assuming that since we've autokeyed the transforms this is
                 * now safe to apply...
-                * 
+                *
                 * NOTE: only do this when there's context info
                 */
                if (C && (ob->avs.path_bakeflag & MOTIONPATH_BAKE_HAS_PATHS)) {
                        //ED_objects_clear_paths(C); // XXX for now, don't need to clear
                        ED_objects_recalculate_paths(C, scene);
-                       
-                       /* XXX: there's potential here for problems with unkeyed rotations/scale, 
+
+                       /* XXX: there's potential here for problems with unkeyed rotations/scale,
                         *      but for now (until proper data-locality for baking operations),
                         *      this should be a better fix for T24451 and T37755
                         */
                }
-               
+
                /* free temp info */
                BLI_freelistN(&dsources);
        }
@@ -5646,13 +5899,14 @@ void autokeyframe_ob_cb_func(bContext *C, Scene *scene, View3D *v3d, Object *ob,
 // NOTE: context may not always be available, so must check before using it as it's a luxury for a few cases
 void autokeyframe_pose_cb_func(bContext *C, Scene *scene, View3D *v3d, Object *ob, int tmode, short targetless_ik)
 {
+       Main *bmain = CTX_data_main(C);
        ID *id = &ob->id;
        AnimData *adt = ob->adt;
        bAction *act = (adt) ? adt->action : NULL;
        bPose   *pose = ob->pose;
        bPoseChannel *pchan;
        FCurve *fcu;
-       
+
        // TODO: this should probably be done per channel instead...
        if (autokeyframe_cfra_can_key(scene, id)) {
                ReportList *reports = CTX_wm_reports(C);
@@ -5660,27 +5914,27 @@ void autokeyframe_pose_cb_func(bContext *C, Scene *scene, View3D *v3d, Object *o
                KeyingSet *active_ks = ANIM_scene_get_active_keyingset(scene);
                float cfra = (float)CFRA;
                short flag = 0;
-               
+
                /* flag is initialized from UserPref keyframing settings
                 *      - special exception for targetless IK - INSERTKEY_MATRIX keyframes should get
                 *    visual keyframes even if flag not set, as it's not that useful otherwise
                 *        (for quick animation recording)
                 */
                flag = ANIM_get_keyframing_flags(scene, 1);
-               
-               if (targetless_ik) 
+
+               if (targetless_ik)
                        flag |= INSERTKEY_MATRIX;
-               
+
                for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
                        if (pchan->bone->flag & BONE_TRANSFORM) {
                                ListBase dsources = {NULL, NULL};
-                               
+
                                /* clear any 'unkeyed' flag it may have */
                                pchan->bone->flag &= ~BONE_UNKEYED;
-                               
+
                                /* add datasource override for the camera object */
-                               ANIM_relative_keyingset_add_source(&dsources, id, &RNA_PoseBone, pchan); 
-                               
+                               ANIM_relative_keyingset_add_source(&dsources, id, &RNA_PoseBone, pchan);
+
                                /* only insert into active keyingset? */
                                if (IS_AUTOKEY_FLAG(scene, ONLYKEYINGSET) && (active_ks)) {
                                        /* run the active Keying Set on the current datasource */
@@ -5693,17 +5947,17 @@ void autokeyframe_pose_cb_func(bContext *C, Scene *scene, View3D *v3d, Object *o
                                                        /* only insert keyframes for this F-Curve if it affects the current bone */
                                                        if (strstr(fcu->rna_path, "bones")) {
                                                                char *pchanName = BLI_str_quoted_substrN(fcu->rna_path, "bones[");
-                                                               
-                                                               /* only if bone name matches too... 
+
+                                                               /* only if bone name matches too...
                                                                 * NOTE: this will do constraints too, but those are ok to do here too?
                                                                 */
                                                                if (pchanName && STREQ(pchanName, pchan->name)) {
-                                                                       insert_keyframe(reports, id, act, 
+                                                                       insert_keyframe(bmain, reports, id, act,
                                                                                        ((fcu->grp) ? (fcu->grp->name) : (NULL)),
                                                                                        fcu->rna_path, fcu->array_index, cfra,
                                                                                        ts->keyframe_type, flag);
                                                                }
-                                                               
+
                                                                if (pchanName) MEM_freeN(pchanName);
                                                        }
                                                }
@@ -5712,7 +5966,7 @@ void autokeyframe_pose_cb_func(bContext *C, Scene *scene, View3D *v3d, Object *o
                                /* only insert keyframe if needed? */
                                else if (IS_AUTOKEY_FLAG(scene, INSERTNEEDED)) {
                                        bool do_loc = false, do_rot = false, do_scale = false;
-                                       
+
                                        /* filter the conditions when this happens (assume that curarea->spacetype==SPACE_VIE3D) */
                                        if (tmode == TFM_TRANSLATION) {
                                                if (targetless_ik)
@@ -5720,21 +5974,21 @@ void autokeyframe_pose_cb_func(bContext *C, Scene *scene, View3D *v3d, Object *o
                                                else
                                                        do_loc = true;
                                        }
-                                       else if (tmode == TFM_ROTATION) {
+                                       else if (ELEM(tmode, TFM_ROTATION, TFM_TRACKBALL)) {
                                                if (ELEM(v3d->around, V3D_AROUND_CURSOR, V3D_AROUND_ACTIVE))
                                                        do_loc = true;
-                                                       
+
                                                if ((v3d->flag & V3D_ALIGN) == 0)
                                                        do_rot = true;
                                        }
                                        else if (tmode == TFM_RESIZE) {
                                                if (ELEM(v3d->around, V3D_AROUND_CURSOR, V3D_AROUND_ACTIVE))
                                                        do_loc = true;
-                                                       
+
                                                if ((v3d->flag & V3D_ALIGN) == 0)
                                                        do_scale = true;
                                        }
-                                       
+
                                        if (do_loc) {
                                                KeyingSet *ks = ANIM_builtin_keyingset_get_named(NULL, ANIM_KS_LOCATION_ID);
                                                ANIM_apply_keyingset(C, &dsources, NULL, ks, MODIFYKEY_MODE_INSERT, cfra);
@@ -5753,13 +6007,13 @@ void autokeyframe_pose_cb_func(bContext *C, Scene *scene, View3D *v3d, Object *o
                                        KeyingSet *ks = ANIM_builtin_keyingset_get_named(NULL, ANIM_KS_LOC_ROT_SCALE_ID);
                                        ANIM_apply_keyingset(C, &dsources, NULL, ks, MODIFYKEY_MODE_INSERT, cfra);
                                }
-                               
+
                                /* free temp info */
                                BLI_freelistN(&dsources);
                        }
                }
-               
-               /* do the bone paths 
+
+               /* do the bone paths
                 *  - only do this when there is context info, since we need that to resolve
                 *        how to do the updates and so on...
                 *      - do not calculate unless there are paths already to update...
@@ -5784,27 +6038,23 @@ static void special_aftertrans_update__movieclip(bContext *C, TransInfo *t)
 {
        SpaceClip *sc = t->sa->spacedata.first;
        MovieClip *clip = ED_space_clip_get_clip(sc);
-       MovieTrackingPlaneTrack *plane_track;
        ListBase *plane_tracks_base = BKE_tracking_get_active_plane_tracks(&clip->tracking);
-       int framenr = ED_space_clip_get_clip_frame_number(sc);
-
-       for (plane_track = plane_tracks_base->first;
+       const int framenr = ED_space_clip_get_clip_frame_number(sc);
+       /* Update coordinates of modified plane tracks. */
+       for (MovieTrackingPlaneTrack *plane_track = plane_tracks_base->first;
             plane_track;
             plane_track = plane_track->next)
        {
                bool do_update = false;
-
                if (plane_track->flag & PLANE_TRACK_HIDDEN) {
                        continue;
                }
-
                do_update |= PLANE_TRACK_VIEW_SELECTED(plane_track) != 0;
                if (do_update == false) {
                        if ((plane_track->flag & PLANE_TRACK_AUTOKEY) == 0) {
                                int i;
                                for (i = 0; i < plane_track->point_tracksnr; i++) {
                                        MovieTrackingTrack *track = plane_track->point_tracks[i];
-
                                        if (TRACK_VIEW_SELECTED(sc, track)) {
                                                do_update = true;
                                                break;
@@ -5812,15 +6062,14 @@ static void special_aftertrans_update__movieclip(bContext *C, TransInfo *t)
                                }
                        }
                }
-
                if (do_update) {
                        BKE_tracking_track_plane_from_existing_motion(plane_track, framenr);
                }
        }
-
-       if (t->scene->nodetree) {
-               /* tracks can be used for stabilization nodes,
-                * flush update for such nodes */
+       if (t->scene->nodetree != NULL) {
+               /* Tracks can be used for stabilization nodes,
+                * flush update for such nodes.
+                */
                nodeUpdateID(t->scene->nodetree, &clip->id);
                WM_event_add_notifier(C, NC_SCENE | ND_NODES, NULL);
        }
@@ -5862,7 +6111,7 @@ static void special_aftertrans_update__mask(bContext *C, TransInfo *t)
 static void special_aftertrans_update__node(bContext *UNUSED(C), TransInfo *t)
 {
        const bool canceled = (t->state == TRANS_CANCEL);
-       
+
        if (canceled && t->remove_on_cancel) {
                /* remove selected nodes on cancel */
                SpaceNode *snode = (SpaceNode *)t->sa->spacedata.first;
@@ -5920,7 +6169,7 @@ static void special_aftertrans_update__mesh(bContext *UNUSED(C), TransInfo *t)
 }
 
 /* inserting keys, pointcache, redraw events... */
-/* 
+/*
  * note: sequencer freeing has its own function now because of a conflict with transform's order of freeing (campbell)
  *       Order changed, the sequencer stuff should go back in here
  * */
@@ -5930,11 +6179,11 @@ void special_aftertrans_update(bContext *C, TransInfo *t)
 //     short redrawipo=0, resetslowpar=1;
        const bool canceled = (t->state == TRANS_CANCEL);
        const bool duplicate = (t->mode == TFM_TIME_DUPLICATE);
-       
+
        /* early out when nothing happened */
        if (t->total == 0 || t->mode == TFM_DUMMY)
                return;
-       
+
        if (t->spacetype == SPACE_VIEW3D) {
                if (t->obedit) {
                        /* Special Exception:
@@ -6017,10 +6266,10 @@ void special_aftertrans_update(bContext *C, TransInfo *t)
                special_aftertrans_update__node(C, t);
                if (canceled == 0) {
                        ED_node_post_apply_transform(C, snode->edittree);
-                       
+
                        ED_node_link_insert(t->sa);
                }
-               
+
                /* clear link line */
                ED_node_link_intersect_test(t->sa, 0);
        }
@@ -6035,26 +6284,26 @@ void special_aftertrans_update(bContext *C, TransInfo *t)
        else if (t->spacetype == SPACE_ACTION) {
                SpaceAction *saction = (SpaceAction *)t->sa->spacedata.first;
                bAnimContext ac;
-               
+
                /* initialize relevant anim-context 'context' data */
                if (ANIM_animdata_get_context(C, &ac) == 0)
                        return;
-                       
+
                ob = ac.obact;
-               
+
                if (ELEM(ac.datatype, ANIMCONT_DOPESHEET, ANIMCONT_SHAPEKEY)) {
                        ListBase anim_data = {NULL, NULL};
                        bAnimListElem *ale;
                        short filter = (ANIMFILTER_DATA_VISIBLE | ANIMFILTER_FOREDIT /*| ANIMFILTER_CURVESONLY*/);
-                       
+
                        /* get channels to work on */
                        ANIM_animdata_filter(&ac, &anim_data, filter, ac.data, ac.datatype);
-                       
+
                        /* these should all be F-Curves */
                        for (ale = anim_data.first; ale; ale = ale->next) {
                                AnimData *adt = ANIM_nla_mapping_get(&ac, ale);
                                FCurve *fcu = (FCurve *)ale->key_data;
-                               
+
                                /* 3 cases here for curve cleanups:
                                 * 1) NOTRANSKEYCULL on     -> cleanup of duplicates shouldn't be done
                                 * 2) canceled == 0        -> user confirmed the transform, so duplicates should be removed
@@ -6072,7 +6321,7 @@ void special_aftertrans_update(bContext *C, TransInfo *t)
                                                posttrans_fcurve_clean(fcu, false);  /* only use handles in graph editor */
                                }
                        }
-                       
+
                        /* free temp memory */
                        ANIM_animdata_freelist(&anim_data);
                }
@@ -6085,7 +6334,7 @@ void special_aftertrans_update(bContext *C, TransInfo *t)
                                else
                                        DAG_id_tag_update(&ob->id, OB_RECALC_OB);
                        }
-                       
+
                        /* 3 cases here for curve cleanups:
                         * 1) NOTRANSKEYCULL on     -> cleanup of duplicates shouldn't be done
                         * 2) canceled == 0        -> user confirmed the transform, so duplicates should be removed
@@ -6108,7 +6357,7 @@ void special_aftertrans_update(bContext *C, TransInfo *t)
                            ((canceled == 0) || (duplicate)))
                        {
                                bGPdata *gpd;
-                               
+
                                // XXX: BAD! this get gpencil datablocks directly from main db...
                                // but that's how this currently works :/
                                for (gpd = G.main->gpencil.first; gpd; gpd = gpd->id.next) {
@@ -6137,9 +6386,9 @@ void special_aftertrans_update(bContext *C, TransInfo *t)
                                }
                        }
                }
-               
+
                /* marker transform, not especially nice but we may want to move markers
-                * at the same time as keyframes in the dope sheet. 
+                * at the same time as keyframes in the dope sheet.
                 */
                if ((saction->flag & SACTION_MARKERS_MOVE) && (canceled == 0)) {
                        if (t->mode == TFM_TIME_TRANSLATE) {
@@ -6158,11 +6407,11 @@ void special_aftertrans_update(bContext *C, TransInfo *t)
                                ED_markers_post_apply_transform(ED_context_get_markers(C), t->scene, t->mode, t->values[0], t->frame_side);
                        }
                }
-               
+
                /* make sure all F-Curves are set correctly */
                if (!ELEM(ac.datatype, ANIMCONT_GPENCIL, ANIMCONT_MASK))
                        ANIM_editkeyframes_refresh(&ac);
-               
+
                /* clear flag that was set for time-slide drawing */
                saction->flag &= ~SACTION_MOVING;
        }
@@ -6170,23 +6419,23 @@ void special_aftertrans_update(bContext *C, TransInfo *t)
                SpaceIpo *sipo = (SpaceIpo *)t->sa->spacedata.first;
                bAnimContext ac;
                const bool use_handle = (sipo->flag & SIPO_NOHANDLES) == 0;
-               
+
                /* initialize relevant anim-context 'context' data */
                if (ANIM_animdata_get_context(C, &ac) == 0)
                        return;
-               
+
                if (ac.datatype) {
                        ListBase anim_data = {NULL, NULL};
                        bAnimListElem *ale;
                        short filter = (ANIMFILTER_DATA_VISIBLE | ANIMFILTER_FOREDIT | ANIMFILTER_CURVE_VISIBLE);
-                       
+
                        /* get channels to work on */
                        ANIM_animdata_filter(&ac, &anim_data, filter, ac.data, ac.datatype);
-                       
+
                        for (ale = anim_data.first; ale; ale = ale->next) {
                                AnimData *adt = ANIM_nla_mapping_get(&ac, ale);
                                FCurve *fcu = (FCurve *)ale->key_data;
-                               
+
                                /* 3 cases here for curve cleanups:
                                 * 1) NOTRANSKEYCULL on     -> cleanup of duplicates shouldn't be done
                                 * 2) canceled == 0        -> user confirmed the transform, so duplicates should be removed
@@ -6204,11 +6453,11 @@ void special_aftertrans_update(bContext *C, TransInfo *t)
                                                posttrans_fcurve_clean(fcu, use_handle);
                                }
                        }
-                       
+
                        /* free temp memory */
                        ANIM_animdata_freelist(&anim_data);
                }
-               
+
                /* Make sure all F-Curves are set correctly, but not if transform was
                 * canceled, since then curves were already restored to initial state.
                 * Note: if the refresh is really needed after cancel then some way
@@ -6219,32 +6468,32 @@ void special_aftertrans_update(bContext *C, TransInfo *t)
        }
        else if (t->spacetype == SPACE_NLA) {
                bAnimContext ac;
-               
+
                /* initialize relevant anim-context 'context' data */
                if (ANIM_animdata_get_context(C, &ac) == 0)
                        return;
-                       
+
                if (ac.datatype) {
                        ListBase anim_data = {NULL, NULL};
                        bAnimListElem *ale;
                        short filter = (ANIMFILTER_DATA_VISIBLE | ANIMFILTER_FOREDIT);
-                       
+
                        /* get channels to work on */
                        ANIM_animdata_filter(&ac, &anim_data, filter, ac.data, ac.datatype);
-                       
+
                        for (ale = anim_data.first; ale; ale = ale->next) {
                                NlaTrack *nlt = (NlaTrack *)ale->data;
-                               
+
                                /* make sure strips are in order again */
                                BKE_nlatrack_sort_strips(nlt);
-                               
+
                                /* remove the temp metas */
                                BKE_nlastrips_clear_metas(&nlt->strips, 0, 1);
                        }
-                       
+
                        /* free temp memory */
                        ANIM_animdata_freelist(&anim_data);
-                       
+
                        /* perform after-transfrom validation */
                        ED_nla_postop_refresh(&ac);
                }
@@ -6327,7 +6576,7 @@ void special_aftertrans_update(bContext *C, TransInfo *t)
 
                        if (td->flag & TD_NOACTION)
                                break;
-                       
+
                        if (td->flag & TD_SKIP)
                                continue;
 
@@ -6353,7 +6602,7 @@ void special_aftertrans_update(bContext *C, TransInfo *t)
                        if (!canceled) {
                                autokeyframe_ob_cb_func(C, t->scene, (View3D *)t->view, ob, t->mode);
                        }
-                       
+
                        /* restore rigid body transform */
                        if (ob->rigidbody_object && canceled) {
                                float ctime = BKE_scene_frame_get(t->scene);
@@ -6396,13 +6645,13 @@ static void createTransObject(bContext *C, TransInfo *t)
 
        /* count */
        t->total = CTX_DATA_COUNT(C, selected_objects);
-       
+
        if (!t->total) {
                /* clear here, main transform function escapes too */
                clear_trans_object_base_flags(t);
                return;
        }
-       
+
        if (is_prop_edit) {
                t->total += count_proportional_objects(t);
        }
@@ -6413,29 +6662,29 @@ static void createTransObject(bContext *C, TransInfo *t)
        CTX_DATA_BEGIN(C, Base *, base, selected_bases)
        {
                Object *ob = base->object;
-               
+
                td->flag = TD_SELECTED;
                td->protectflag = ob->protectflag;
                td->ext = tx;
                td->ext->rotOrder = ob->rotmode;
-               
+
                if (base->flag & BA_TRANSFORM_CHILD) {
                        td->flag |= TD_NOCENTER;
                        td->flag |= TD_NO_LOC;
                }
-               
+
                /* select linked objects, but skip them later */
-               if (ID_IS_LINKED_DATABLOCK(ob)) {
+               if (ID_IS_LINKED(ob)) {
                        td->flag |= TD_SKIP;
                }
-               
+
                ObjectToTransData(t, td, ob);
                td->val = NULL;
                td++;
                tx++;
        }
        CTX_DATA_END;
-       
+
        if (is_prop_edit) {
                View3D *v3d = t->view;
                Base *base;
@@ -6450,7 +6699,7 @@ static void createTransObject(bContext *C, TransInfo *t)
                                td->protectflag = ob->protectflag;
                                td->ext = tx;
                                td->ext->rotOrder = ob->rotmode;
-                               
+
                                ObjectToTransData(t, td, ob);
                                td->val = NULL;
                                td++;
@@ -6464,7 +6713,7 @@ static void createTransObject(bContext *C, TransInfo *t)
 static void NodeToTransData(TransData *td, TransData2D *td2d, bNode *node, const float dpi_fac)
 {
        float locx, locy;
-       
+
        /* account for parents (nested nodes) */
        if (node->parent) {
                nodeToView(node->parent, node->locx, node->locy, &locx, &locy);
@@ -6473,7 +6722,7 @@ static void NodeToTransData(TransData *td, TransData2D *td2d, bNode *node, const
                locx = node->locx;
                locy = node->locy;
        }
-       
+
        /* use top-left corner as the transform origin for nodes */
        /* weirdo - but the node system is a mix of free 2d elements and dpi sensitive UI */
 #ifdef USE_NODE_CENTER
@@ -7646,14 +7895,14 @@ static void createTransGPencil(bContext *C, TransInfo *t)
        bGPDlayer *gpl;
        TransData *td = NULL;
        float mtx[3][3], smtx[3][3];
-       
+
        const Scene *scene = CTX_data_scene(C);
-       const int cfra = CFRA;
-       
+       const int cfra_scene = CFRA;
+
        const bool is_prop_edit = (t->flag & T_PROP_EDIT) != 0;
        const bool is_prop_edit_connected = (t->flag & T_PROP_CONNECTED) != 0;
-       
-       
+
+
        /* == Grease Pencil Strokes to Transform Data ==
         * Grease Pencil stroke points can be a mixture of 2D (screen-space),
         * or 3D coordinates. However, they're always saved as 3D points.
@@ -7661,11 +7910,11 @@ static void createTransGPencil(bContext *C, TransInfo *t)
         * strokes. This may cause issues in future though.
         */
        t->total = 0;
-       
+
        if (gpd == NULL)
                return;
-       
-       /* First Pass: Count the number of datapoints required for the strokes, 
+
+       /* First Pass: Count the number of datapoints required for the strokes,
         * (and additional info about the configuration - e.g. 2D/3D?)
         */
        for (gpl = gpd->layers.first; gpl; gpl = gpl->next) {
@@ -7673,13 +7922,17 @@ static void createTransGPencil(bContext *C, TransInfo *t)
                if (gpencil_layer_is_editable(gpl) && (gpl->actframe != NULL)) {
                        bGPDframe *gpf = gpl->actframe;
                        bGPDstroke *gps;
-                       
+
                        for (gps = gpf->strokes.first; gps; gps = gps->next) {
                                /* skip strokes that are invalid for current view */
                                if (ED_gpencil_stroke_can_use(C, gps) == false) {
                                        continue;
                                }
-                               
+                               /* check if the color is editable */
+                               if (ED_gpencil_stroke_color_use(gpl, gps) == false) {
+                                       continue;
+                               }
+
                                if (is_prop_edit) {
                                        /* Proportional Editing... */
                                        if (is_prop_edit_connected) {
@@ -7697,57 +7950,73 @@ static void createTransGPencil(bContext *C, TransInfo *t)
                                        if (gps->flag & GP_STROKE_SELECT) {
                                                bGPDspoint *pt;
                                                int i;
-                                               
+
                                                // TODO: 2D vs 3D?
                                                for (i = 0, pt = gps->points; i < gps->totpoints; i++, pt++) {
                                                        if (pt->flag & GP_SPOINT_SELECT)
                                                                t->total++;
                                                }
                                        }
-                               }                               
+                               }
                        }
                }
        }
-       
+
        /* Stop trying if nothing selected */
        if (t->total == 0) {
                return;
        }
-       
+
        /* Allocate memory for data */
        t->data = MEM_callocN(t->total * sizeof(TransData), "TransData(GPencil)");
        td = t->data;
-       
+
        unit_m3(smtx);
        unit_m3(mtx);
-       
+
        /* Second Pass: Build transdata array */
        for (gpl = gpd->layers.first; gpl; gpl = gpl->next) {
                /* only editable and visible layers are considered */
                if (gpencil_layer_is_editable(gpl) && (gpl->actframe != NULL)) {
+                       const int cfra = (gpl->flag & GP_LAYER_FRAMELOCK) ? gpl->actframe->framenum : cfra_scene;
                        bGPDframe *gpf = gpl->actframe;
                        bGPDstroke *gps;
-                       
-                       /* Make a new frame to work on if the layer's frame and the current scene frame don't match up 
+                       float diff_mat[4][4];
+                       float inverse_diff_mat[4][4];
+
+                       /* calculate difference matrix if parent object */
+                       if (gpl->parent != NULL) {
+                               ED_gpencil_parent_location(gpl, diff_mat);
+                               /* undo matrix */
+                               invert_m4_m4(inverse_diff_mat, diff_mat);
+                       }
+
+                       /* Make a new frame to work on if the layer's frame and the current scene frame don't match up
                         * - This is useful when animating as it saves that "uh-oh" moment when you realize you've
                         *   spent too much time editing the wrong frame...
                         */
-                       // XXX: should this be allowed when framelock is enabled?
                        if (gpf->framenum != cfra) {
-                               gpf = gpencil_frame_addcopy(gpl, cfra);
+                               gpf = BKE_gpencil_frame_addcopy(gpl, cfra);
+                               /* in some weird situations (framelock enabled) return NULL */
+                               if (gpf == NULL) {
+                                       continue;
+                               }
                        }
-                       
+
                        /* Loop over strokes, adding TransData for points as needed... */
                        for (gps = gpf->strokes.first; gps; gps = gps->next) {
                                TransData *head = td;
                                TransData *tail = td;
                                bool stroke_ok;
-                               
+
                                /* skip strokes that are invalid for current view */
                                if (ED_gpencil_stroke_can_use(C, gps) == false) {
                                        continue;
                                }
-                               
+                               /* check if the color is editable */
+                               if (ED_gpencil_stroke_color_use(gpl, gps) == false) {
+                                       continue;
+                               }
                                /* What we need to include depends on proportional editing settings... */
                                if (is_prop_edit) {
                                        if (is_prop_edit_connected) {
@@ -7763,26 +8032,26 @@ static void createTransGPencil(bContext *C, TransInfo *t)
                                        /* C) Only selected points in selected strokes */
                                        stroke_ok = (gps->flag & GP_STROKE_SELECT) != 0;
                                }
-                               
+
                                /* Do stroke... */
                                if (stroke_ok && gps->totpoints) {
                                        bGPDspoint *pt;
                                        int i;
-                                       
+
 #if 0  /* XXX: this isn't needed anymore; cannot calculate center this way or is_prop_edit breaks */
                                        const float ninv = 1.0f / gps->totpoints;
                                        float center[3] = {0.0f};
-                                       
+
                                        /* compute midpoint of stroke */
                                        for (i = 0, pt = gps->points; i < gps->totpoints; i++, pt++) {
                                                madd_v3_v3v3fl(center, center, &pt->x, ninv);
                                        }
 #endif
-                                       
+
                                        /* add all necessary points... */
                                        for (i = 0, pt = gps->points; i < gps->totpoints; i++, pt++) {
                                                bool point_ok;
-                                               
+
                                                /* include point? */
                                                if (is_prop_edit) {
                                                        /* Always all points in strokes that get included */
@@ -7792,33 +8061,42 @@ static void createTransGPencil(bContext *C, TransInfo *t)
                                                        /* Only selected points in selected strokes */
                                                        point_ok = (pt->flag & GP_SPOINT_SELECT) != 0;
                                                }
-                                               
+
                                                /* do point... */
                                                if (point_ok) {
                                                        copy_v3_v3(td->iloc, &pt->x);
                                                        copy_v3_v3(td->center, &pt->x); // XXX: what about  t->around == local?
-                                                       
+
                                                        td->loc = &pt->x;
-                                                       
+
                                                        td->flag = 0;
-                                                       
+
                                                        if (pt->flag & GP_SPOINT_SELECT)
                                                                td->flag |= TD_SELECTED;
-                                                               
+
                                                        /* for other transform modes (e.g. shrink-fatten), need to additional data */
                                                        if (t->mode == TFM_GPENCIL_SHRINKFATTEN) {
                                                                td->val = &pt->pressure;
                                                                td->ival = pt->pressure;
                                                        }
-                                                       
+
                                                        /* screenspace needs special matrices... */
                                                        if ((gps->flag & (GP_STROKE_3DSPACE | GP_STROKE_2DSPACE | GP_STROKE_2DIMAGE)) == 0) {
                                                                /* screenspace */
                                                                td->protectflag = OB_LOCK_LOCZ | OB_LOCK_ROTZ | OB_LOCK_SCALEZ;
-                                                               
-                                                               copy_m3_m4(td->smtx, t->persmat);
-                                                               copy_m3_m4(td->mtx, t->persinv);
-                                                               unit_m3(td->axismtx);
+
+                                                               /* apply parent transformations */
+                                                               if (gpl->parent == NULL) {
+                                                                       copy_m3_m4(td->smtx, t->persmat);
+                                                                       copy_m3_m4(td->mtx, t->persinv);
+                                                                       unit_m3(td->axismtx);
+                                                               }
+                                                               else {
+                                                                       /* apply matrix transformation relative to parent */
+                                                                       copy_m3_m4(td->smtx, inverse_diff_mat); /* final position */
+                                                                       copy_m3_m4(td->mtx, diff_mat); /* display position */
+                                                                       copy_m3_m4(td->axismtx, diff_mat); /* axis orientation */
+                                                               }
                                                        }
                                                        else {
                                                                /* configure 2D dataspace points so that they don't play up... */
@@ -7826,10 +8104,19 @@ static void createTransGPencil(bContext *C, TransInfo *t)
                                                                        td->protectflag = OB_LOCK_LOCZ | OB_LOCK_ROTZ | OB_LOCK_SCALEZ;
                                                                        // XXX: matrices may need to be different?
                                                                }
-                                                               
-                                                               copy_m3_m3(td->smtx, smtx);
-                                                               copy_m3_m3(td->mtx, mtx);
-                                                               unit_m3(td->axismtx); // XXX?
+
+                                                               /* apply parent transformations */
+                                                               if (gpl->parent == NULL) {
+                                                                       copy_m3_m3(td->smtx, smtx);
+                                                                       copy_m3_m3(td->mtx, mtx);
+                                                                       unit_m3(td->axismtx); // XXX?
+                                                               }
+                                                               else {
+                                                                       /* apply matrix transformation relative to parent */
+                                                                       copy_m3_m4(td->smtx, inverse_diff_mat); /* final position */
+                                                                       copy_m3_m4(td->mtx, diff_mat);  /* display position */
+                                                                       copy_m3_m4(td->axismtx, diff_mat); /* axis orientation */
+                                                               }
                                                        }
                                                        /* Triangulation must be calculated again, so save the stroke for recalc function */
                                                        td->extra = gps;
@@ -7838,7 +8125,7 @@ static void createTransGPencil(bContext *C, TransInfo *t)
                                                        tail++;
                                                }
                                        }
-                                       
+
                                        /* March over these points, and calculate the proportional editing distances */
                                        if (is_prop_edit && (head != tail)) {
                                                /* XXX: for now, we are similar enough that this works... */
@@ -7875,7 +8162,7 @@ void createTransData(bContext *C, TransInfo *t)
                t->options |= CTX_GPENCIL_STROKES;
                t->flag |= T_POINTS;
                createTransGPencil(C, t);
-               
+
                if (t->data && (t->flag & T_PROP_EDIT)) {
                        sort_trans_data(t); // makes selected become first in array
                        set_prop_dist(t, 1);
@@ -7987,7 +8274,12 @@ void createTransData(bContext *C, TransInfo *t)
                if (t->data && t->flag & T_PROP_EDIT) {
                        if (ELEM(t->obedit->type, OB_CURVE, OB_MESH)) {
                                sort_trans_data(t); // makes selected become first in array
-                               set_prop_dist(t, 0);
+                               if ((t->obedit->type == OB_MESH) && (t->flag & T_PROP_CONNECTED)) {
+                                       /* already calculated by editmesh_set_connectivity_distance */
+                               }
+                               else {
+                                       set_prop_dist(t, 0);
+                               }
                                sort_trans_data_dist(t);
                        }
                        else {
@@ -8021,7 +8313,7 @@ void createTransData(bContext *C, TransInfo *t)
                                        createTransPose(t, ob_armature);
                                }
                        }
-                       
+
                }
        }
        else if (ob && (ob->mode & OB_MODE_PARTICLE_EDIT) && PE_start_edit(PE_get_current(scene, ob))) {