Fix some inconsistencies in object visibility/selectability tests.
[blender.git] / source / blender / editors / object / object_constraint.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Joshua Leung, Blender Foundation
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/object/object_constraint.c
29  *  \ingroup edobj
30  */
31
32
33 #include <stdio.h>
34 #include <string.h>
35
36 #include "MEM_guardedalloc.h"
37
38 #include "BLI_blenlib.h"
39 #include "BLI_math.h"
40 #include "BLI_dynstr.h"
41 #include "BLI_utildefines.h"
42
43 #include "BLT_translation.h"
44
45 #include "DNA_anim_types.h"
46 #include "DNA_constraint_types.h"
47 #include "DNA_curve_types.h"
48 #include "DNA_scene_types.h"
49 #include "DNA_text_types.h"
50 #include "DNA_object_types.h"
51
52 #include "BKE_action.h"
53 #include "BKE_armature.h"
54 #include "BKE_constraint.h"
55 #include "BKE_context.h"
56 #include "BKE_fcurve.h"
57 #include "BKE_global.h"
58 #include "BKE_main.h"
59 #include "BKE_object.h"
60 #include "BKE_report.h"
61 #include "BKE_tracking.h"
62 #include "BIK_api.h"
63
64 #include "DEG_depsgraph.h"
65 #include "DEG_depsgraph_build.h"
66
67 #ifdef WITH_PYTHON
68 #include "BPY_extern.h"
69 #endif
70
71 #include "WM_api.h"
72 #include "WM_types.h"
73
74 #include "RNA_access.h"
75 #include "RNA_define.h"
76 #include "RNA_enum_types.h"
77
78 #include "ED_object.h"
79 #include "ED_keyframing.h"
80 #include "ED_screen.h"
81
82 #include "UI_interface.h"
83 #include "UI_resources.h"
84
85 #include "object_intern.h"
86
87 /* -------------- Get Active Constraint Data ---------------------- */
88
89 /* if object in posemode, active bone constraints, else object constraints */
90 ListBase *get_active_constraints(Object *ob)
91 {
92         if (ob == NULL)
93                 return NULL;
94
95         if (ob->mode & OB_MODE_POSE) {
96                 bPoseChannel *pchan;
97
98                 pchan = BKE_pose_channel_active(ob);
99                 if (pchan)
100                         return &pchan->constraints;
101         }
102         else
103                 return &ob->constraints;
104
105         return NULL;
106 }
107
108 /* Find the list that a given constraint belongs to, and/or also get the posechannel this is from (if applicable) */
109 ListBase *get_constraint_lb(Object *ob, bConstraint *con, bPoseChannel **r_pchan)
110 {
111         if (r_pchan)
112                 *r_pchan = NULL;
113
114         if (ELEM(NULL, ob, con))
115                 return NULL;
116
117         /* try object constraints first */
118         if ((BLI_findindex(&ob->constraints, con) != -1)) {
119                 return &ob->constraints;
120         }
121
122         /* if armature, try pose bones too */
123         if (ob->pose) {
124                 bPoseChannel *pchan;
125
126                 /* try each bone in order
127                  * NOTE: it's not possible to directly look up the active bone yet, so this will have to do
128                  */
129                 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
130                         if ((BLI_findindex(&pchan->constraints, con) != -1)) {
131
132                                 if (r_pchan)
133                                         *r_pchan = pchan;
134
135                                 return &pchan->constraints;
136                         }
137                 }
138         }
139
140         /* done */
141         return NULL;
142 }
143
144 /* single constraint */
145 bConstraint *get_active_constraint(Object *ob)
146 {
147         return BKE_constraints_active_get(get_active_constraints(ob));
148 }
149
150 /* -------------- Constraint Management (Add New, Remove, Rename) -------------------- */
151 #ifdef WITH_PYTHON
152 /* ------------- PyConstraints ------------------ */
153
154 /* this callback sets the text-file to be used for selected menu item */
155 static void validate_pyconstraint_cb(Main *bmain, void *arg1, void *arg2)
156 {
157         bPythonConstraint *data = arg1;
158         Text *text = NULL;
159         int index = *((int *)arg2);
160         int i;
161
162         /* exception for no script */
163         if (index) {
164                 /* innovative use of a for...loop to search */
165                 for (text = bmain->text.first, i = 1; text && index != i; i++, text = text->id.next) ;
166         }
167         data->text = text;
168 }
169
170 /* this returns a string for the list of usable pyconstraint script names */
171 static char *buildmenu_pyconstraints(Main *bmain, Text *con_text, int *pyconindex)
172 {
173         DynStr *pupds = BLI_dynstr_new();
174         Text *text;
175         char *str;
176         char buf[64];
177         int i;
178
179         /* add title first */
180         sprintf(buf, "Scripts: %%t|[None]%%x0|");
181         BLI_dynstr_append(pupds, buf);
182
183         /* init active-index first */
184         if (con_text == NULL)
185                 *pyconindex = 0;
186
187         /* loop through markers, adding them */
188         for (text = bmain->text.first, i = 1; text; i++, text = text->id.next) {
189                 /* this is important to ensure that right script is shown as active */
190                 if (text == con_text) *pyconindex = i;
191
192                 /* only include valid pyconstraint scripts */
193                 if (BPY_is_pyconstraint(text)) {
194                         BLI_dynstr_append(pupds, text->id.name + 2);
195
196                         sprintf(buf, "%%x%d", i);
197                         BLI_dynstr_append(pupds, buf);
198
199                         if (text->id.next)
200                                 BLI_dynstr_append(pupds, "|");
201                 }
202         }
203
204         /* convert to normal MEM_malloc'd string */
205         str = BLI_dynstr_get_cstring(pupds);
206         BLI_dynstr_free(pupds);
207
208         return str;
209 }
210 #endif /* WITH_PYTHON */
211
212 #if 0 // UNUSED, until pyconstraints are added back.
213 /* this callback gets called when the 'refresh' button of a pyconstraint gets pressed */
214 static void update_pyconstraint_cb(void *arg1, void *arg2)
215 {
216 #ifndef WITH_PYTHON
217         (void)arg1; /* unused */
218         (void)arg2; /* unused */
219 #else
220         Object *owner = (Object *)arg1;
221         bConstraint *con = (bConstraint *)arg2;
222         if (owner && con)
223                 BPY_pyconstraint_update(owner, con);
224 #endif
225 }
226 #endif // UNUSED
227
228 /* helper function for add_constriant - sets the last target for the active constraint */
229 static void set_constraint_nth_target(bConstraint *con, Object *target, const char subtarget[], int index)
230 {
231         const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
232         ListBase targets = {NULL, NULL};
233         bConstraintTarget *ct;
234         int num_targets, i;
235
236         if (cti && cti->get_constraint_targets) {
237                 cti->get_constraint_targets(con, &targets);
238                 num_targets = BLI_listbase_count(&targets);
239
240                 if (index < 0) {
241                         if (abs(index) < num_targets)
242                                 index = num_targets - abs(index);
243                         else
244                                 index = num_targets - 1;
245                 }
246                 else if (index >= num_targets) {
247                         index = num_targets - 1;
248                 }
249
250                 for (ct = targets.first, i = 0; ct; ct = ct->next, i++) {
251                         if (i == index) {
252                                 ct->tar = target;
253                                 BLI_strncpy(ct->subtarget, subtarget, sizeof(ct->subtarget));
254                                 break;
255                         }
256                 }
257
258                 if (cti->flush_constraint_targets)
259                         cti->flush_constraint_targets(con, &targets, 0);
260         }
261 }
262
263 /* ------------- Constraint Sanity Testing ------------------- */
264
265 static void test_constraint(Main *bmain, Object *owner, bPoseChannel *pchan, bConstraint *con, int type)
266 {
267         const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
268         ListBase targets = {NULL, NULL};
269         bConstraintTarget *ct;
270         bool check_targets = true;
271
272         /* clear disabled-flag first */
273         con->flag &= ~CONSTRAINT_DISABLE;
274
275         if (con->type == CONSTRAINT_TYPE_KINEMATIC) {
276                 bKinematicConstraint *data = con->data;
277
278                 /* bad: we need a separate set of checks here as poletarget is
279                  * optional... otherwise poletarget must exist too or else
280                  * the constraint is deemed invalid
281                  */
282                 /* default IK check ... */
283                 if (BKE_object_exists_check(bmain, data->tar) == 0) {
284                         data->tar = NULL;
285                         con->flag |= CONSTRAINT_DISABLE;
286                 }
287                 else if (data->tar == owner) {
288                         if (!BKE_armature_find_bone_name(BKE_armature_from_object(owner), data->subtarget)) {
289                                 con->flag |= CONSTRAINT_DISABLE;
290                         }
291                 }
292
293                 if (data->poletar) {
294                         if (BKE_object_exists_check(bmain, data->poletar) == 0) {
295                                 data->poletar = NULL;
296                                 con->flag |= CONSTRAINT_DISABLE;
297                         }
298                         else if (data->poletar == owner) {
299                                 if (!BKE_armature_find_bone_name(BKE_armature_from_object(owner), data->polesubtarget)) {
300                                         con->flag |= CONSTRAINT_DISABLE;
301                                 }
302                         }
303                 }
304                 /* ... can be overwritten here */
305                 BIK_test_constraint(owner, con);
306                 /* targets have already been checked for this */
307                 check_targets = false;
308         }
309         else if (con->type == CONSTRAINT_TYPE_PIVOT) {
310                 bPivotConstraint *data = con->data;
311
312                 /* target doesn't have to exist, but if it is non-null, it must exist! */
313                 if (data->tar && BKE_object_exists_check(bmain, data->tar) == 0) {
314                         data->tar = NULL;
315                         con->flag |= CONSTRAINT_DISABLE;
316                 }
317                 else if (data->tar == owner) {
318                         if (!BKE_armature_find_bone_name(BKE_armature_from_object(owner), data->subtarget)) {
319                                 con->flag |= CONSTRAINT_DISABLE;
320                         }
321                 }
322
323                 /* targets have already been checked for this */
324                 check_targets = false;
325         }
326         else if (con->type == CONSTRAINT_TYPE_ACTION) {
327                 bActionConstraint *data = con->data;
328
329                 /* validate action */
330                 if (data->act == NULL) {
331                         /* must have action */
332                         con->flag |= CONSTRAINT_DISABLE;
333                 }
334                 else if (data->act->idroot != ID_OB) {
335                         /* only object-rooted actions can be used */
336                         data->act = NULL;
337                         con->flag |= CONSTRAINT_DISABLE;
338                 }
339         }
340         else if (con->type == CONSTRAINT_TYPE_FOLLOWPATH) {
341                 bFollowPathConstraint *data = con->data;
342
343                 /* don't allow track/up axes to be the same */
344                 if (data->upflag == data->trackflag)
345                         con->flag |= CONSTRAINT_DISABLE;
346                 if (data->upflag + 3 == data->trackflag)
347                         con->flag |= CONSTRAINT_DISABLE;
348         }
349         else if (con->type == CONSTRAINT_TYPE_TRACKTO) {
350                 bTrackToConstraint *data = con->data;
351
352                 /* don't allow track/up axes to be the same */
353                 if (data->reserved2 == data->reserved1)
354                         con->flag |= CONSTRAINT_DISABLE;
355                 if (data->reserved2 + 3 == data->reserved1)
356                         con->flag |= CONSTRAINT_DISABLE;
357         }
358         else if (con->type == CONSTRAINT_TYPE_LOCKTRACK) {
359                 bLockTrackConstraint *data = con->data;
360
361                 if (data->lockflag == data->trackflag)
362                         con->flag |= CONSTRAINT_DISABLE;
363                 if (data->lockflag + 3 == data->trackflag)
364                         con->flag |= CONSTRAINT_DISABLE;
365         }
366         else if (con->type == CONSTRAINT_TYPE_SPLINEIK) {
367                 bSplineIKConstraint *data = con->data;
368
369                 /* if the number of points does not match the amount required by the chain length,
370                  * free the points array and request a rebind...
371                  */
372                 if ((data->points == NULL) || (data->numpoints != data->chainlen + 1)) {
373                         /* free the points array */
374                         if (data->points) {
375                                 MEM_freeN(data->points);
376                                 data->points = NULL;
377                         }
378
379                         /* clear the bound flag, forcing a rebind next time this is evaluated */
380                         data->flag &= ~CONSTRAINT_SPLINEIK_BOUND;
381                 }
382         }
383         else if (con->type == CONSTRAINT_TYPE_FOLLOWTRACK) {
384                 bFollowTrackConstraint *data = con->data;
385
386                 if ((data->flag & CAMERASOLVER_ACTIVECLIP) == 0) {
387                         if (data->clip != NULL && data->track[0]) {
388                                 MovieTracking *tracking = &data->clip->tracking;
389                                 MovieTrackingObject *tracking_object;
390
391                                 if (data->object[0])
392                                         tracking_object = BKE_tracking_object_get_named(tracking, data->object);
393                                 else
394                                         tracking_object = BKE_tracking_object_get_camera(tracking);
395
396                                 if (!tracking_object) {
397                                         con->flag |= CONSTRAINT_DISABLE;
398                                 }
399                                 else {
400                                         if (!BKE_tracking_track_get_named(tracking, tracking_object, data->track))
401                                                 con->flag |= CONSTRAINT_DISABLE;
402                                 }
403                         }
404                         else {
405                                 con->flag |= CONSTRAINT_DISABLE;
406                         }
407                 }
408         }
409         else if (con->type == CONSTRAINT_TYPE_CAMERASOLVER) {
410                 bCameraSolverConstraint *data = con->data;
411
412                 if ((data->flag & CAMERASOLVER_ACTIVECLIP) == 0 && (data->clip == NULL))
413                         con->flag |= CONSTRAINT_DISABLE;
414         }
415         else if (con->type == CONSTRAINT_TYPE_OBJECTSOLVER) {
416                 bObjectSolverConstraint *data = con->data;
417
418                 if ((data->flag & CAMERASOLVER_ACTIVECLIP) == 0 && (data->clip == NULL))
419                         con->flag |= CONSTRAINT_DISABLE;
420         }
421         else if (con->type == CONSTRAINT_TYPE_TRANSFORM_CACHE) {
422                 bTransformCacheConstraint *data = con->data;
423
424                 if ((data->cache_file == NULL) || (data->object_path[0] == '\0')) {
425                         con->flag |= CONSTRAINT_DISABLE;
426                 }
427         }
428
429         /* Check targets for constraints */
430         if (check_targets && cti && cti->get_constraint_targets) {
431                 cti->get_constraint_targets(con, &targets);
432
433                 /* constraints with empty target list that actually require targets */
434                 if (!targets.first && ELEM(con->type, CONSTRAINT_TYPE_ARMATURE)) {
435                         con->flag |= CONSTRAINT_DISABLE;
436                 }
437
438                 /* disable and clear constraints targets that are incorrect */
439                 for (ct = targets.first; ct; ct = ct->next) {
440                         /* general validity checks (for those constraints that need this) */
441                         if (BKE_object_exists_check(bmain, ct->tar) == 0) {
442                                 /* object doesn't exist, but constraint requires target */
443                                 ct->tar = NULL;
444                                 con->flag |= CONSTRAINT_DISABLE;
445                         }
446                         else if (ct->tar == owner) {
447                                 if (type == CONSTRAINT_OBTYPE_BONE) {
448                                         if (!BKE_armature_find_bone_name(BKE_armature_from_object(owner), ct->subtarget)) {
449                                                 /* bone must exist in armature... */
450                                                 /* TODO: clear subtarget? */
451                                                 con->flag |= CONSTRAINT_DISABLE;
452                                         }
453                                         else if (STREQ(pchan->name, ct->subtarget)) {
454                                                 /* cannot target self */
455                                                 ct->subtarget[0] = '\0';
456                                                 con->flag |= CONSTRAINT_DISABLE;
457                                         }
458                                 }
459                                 else {
460                                         /* cannot use self as target */
461                                         ct->tar = NULL;
462                                         con->flag |= CONSTRAINT_DISABLE;
463                                 }
464                         }
465
466                         /* target checks for specific constraints */
467                         if (ELEM(con->type, CONSTRAINT_TYPE_FOLLOWPATH, CONSTRAINT_TYPE_CLAMPTO, CONSTRAINT_TYPE_SPLINEIK)) {
468                                 if (ct->tar) {
469                                         if (ct->tar->type != OB_CURVE) {
470                                                 ct->tar = NULL;
471                                                 con->flag |= CONSTRAINT_DISABLE;
472                                         }
473                                         else {
474                                                 Curve *cu = ct->tar->data;
475
476                                                 /* auto-set 'Path' setting on curve so this works  */
477                                                 cu->flag |= CU_PATH;
478                                         }
479                                 }
480                         }
481                         else if (con->type == CONSTRAINT_TYPE_ARMATURE) {
482                                 if (ct->tar) {
483                                         if (ct->tar->type != OB_ARMATURE) {
484                                                 ct->tar = NULL;
485                                                 con->flag |= CONSTRAINT_DISABLE;
486                                         }
487                                         else if (!BKE_armature_find_bone_name(BKE_armature_from_object(ct->tar), ct->subtarget)) {
488                                                 /* bone must exist in armature... */
489                                                 con->flag |= CONSTRAINT_DISABLE;
490                                         }
491                                 }
492                         }
493                 }
494
495                 /* free any temporary targets */
496                 if (cti->flush_constraint_targets)
497                         cti->flush_constraint_targets(con, &targets, 0);
498         }
499 }
500
501 static int constraint_type_get(Object *owner, bPoseChannel *pchan)
502 {
503         int type;
504         /* Check parents */
505         if (pchan) {
506                 switch (owner->type) {
507                         case OB_ARMATURE:
508                                 type = CONSTRAINT_OBTYPE_BONE;
509                                 break;
510                         default:
511                                 type = CONSTRAINT_OBTYPE_OBJECT;
512                                 break;
513                 }
514         }
515         else
516                 type = CONSTRAINT_OBTYPE_OBJECT;
517         return type;
518 }
519
520 /* checks validity of object pointers, and NULLs,
521  * if Bone doesn't exist it sets the CONSTRAINT_DISABLE flag.
522  */
523 static void test_constraints(Main *bmain, Object *owner, bPoseChannel *pchan)
524 {
525         bConstraint *curcon;
526         ListBase *conlist = NULL;
527         int type;
528
529         if (owner == NULL) return;
530
531         type = constraint_type_get(owner, pchan);
532
533         /* Get the constraint list for this object */
534         switch (type) {
535                 case CONSTRAINT_OBTYPE_OBJECT:
536                         conlist = &owner->constraints;
537                         break;
538                 case CONSTRAINT_OBTYPE_BONE:
539                         conlist = &pchan->constraints;
540                         break;
541         }
542
543         /* Check all constraints - is constraint valid? */
544         if (conlist) {
545                 for (curcon = conlist->first; curcon; curcon = curcon->next) {
546                         test_constraint(bmain, owner, pchan, curcon, type);
547                 }
548         }
549 }
550
551 void object_test_constraints(Main *bmain, Object *owner)
552 {
553         if (owner->constraints.first)
554                 test_constraints(bmain, owner, NULL);
555
556         if (owner->type == OB_ARMATURE && owner->pose) {
557                 bPoseChannel *pchan;
558
559                 for (pchan = owner->pose->chanbase.first; pchan; pchan = pchan->next) {
560                         if (pchan->constraints.first)
561                                 test_constraints(bmain, owner, pchan);
562                 }
563         }
564 }
565
566 static void object_test_constraint(Main *bmain, Object *owner, bConstraint *con)
567 {
568         if (owner->type == OB_ARMATURE && owner->pose) {
569                 if (BLI_findindex(&owner->constraints, con) != -1) {
570                         test_constraint(bmain, owner, NULL, con, CONSTRAINT_OBTYPE_OBJECT);
571                 }
572                 else {
573                         bPoseChannel *pchan;
574                         for (pchan = owner->pose->chanbase.first; pchan; pchan = pchan->next) {
575                                 if (BLI_findindex(&pchan->constraints, con) != -1) {
576                                         test_constraint(bmain, owner, pchan, con, CONSTRAINT_OBTYPE_BONE);
577                                         break;
578                                 }
579                         }
580                 }
581         }
582         else {
583                 test_constraint(bmain, owner, NULL, con, CONSTRAINT_OBTYPE_OBJECT);
584         }
585 }
586
587 /************************ generic functions for operators using constraint names and data context *********************/
588
589 #define EDIT_CONSTRAINT_OWNER_OBJECT    0
590 #define EDIT_CONSTRAINT_OWNER_BONE      1
591
592 static const EnumPropertyItem constraint_owner_items[] = {
593         {EDIT_CONSTRAINT_OWNER_OBJECT, "OBJECT", 0, "Object", "Edit a constraint on the active object"},
594         {EDIT_CONSTRAINT_OWNER_BONE, "BONE", 0, "Bone", "Edit a constraint on the active bone"},
595         {0, NULL, 0, NULL, NULL}};
596
597
598 static bool edit_constraint_poll_generic(bContext *C, StructRNA *rna_type)
599 {
600         PointerRNA ptr = CTX_data_pointer_get_type(C, "constraint", rna_type);
601         Object *ob = (ptr.id.data) ? ptr.id.data : ED_object_active_context(C);
602
603         if (!ptr.data) {
604                 CTX_wm_operator_poll_msg_set(C, "Context missing 'constraint'");
605                 return 0;
606         }
607
608         if (!ob) {
609                 CTX_wm_operator_poll_msg_set(C, "Context missing active object");
610                 return 0;
611         }
612
613         if (ID_IS_LINKED(ob) || (ptr.id.data && ID_IS_LINKED(ptr.id.data))) {
614                 CTX_wm_operator_poll_msg_set(C, "Cannot edit library data");
615                 return 0;
616         }
617
618         if (ID_IS_STATIC_OVERRIDE(ob)) {
619                 CTX_wm_operator_poll_msg_set(C, "Cannot edit constraints coming from static override");
620                 return (((bConstraint *)ptr.data)->flag & CONSTRAINT_STATICOVERRIDE_LOCAL) != 0;
621         }
622
623         return 1;
624 }
625
626 static bool edit_constraint_poll(bContext *C)
627 {
628         return edit_constraint_poll_generic(C, &RNA_Constraint);
629 }
630
631 static void edit_constraint_properties(wmOperatorType *ot)
632 {
633         PropertyRNA *prop;
634         prop = RNA_def_string(ot->srna, "constraint", NULL, MAX_NAME, "Constraint", "Name of the constraint to edit");
635         RNA_def_property_flag(prop, PROP_HIDDEN);
636         prop = RNA_def_enum(ot->srna, "owner", constraint_owner_items, 0, "Owner", "The owner of this constraint");
637         RNA_def_property_flag(prop, PROP_HIDDEN);
638 }
639
640 static int edit_constraint_invoke_properties(bContext *C, wmOperator *op)
641 {
642         PointerRNA ptr = CTX_data_pointer_get_type(C, "constraint", &RNA_Constraint);
643         Object *ob = (ptr.id.data) ? ptr.id.data : ED_object_active_context(C);
644         bConstraint *con;
645         ListBase *list;
646
647         if (RNA_struct_property_is_set(op->ptr, "constraint") && RNA_struct_property_is_set(op->ptr, "owner"))
648                 return 1;
649
650         if (ptr.data) {
651                 con = ptr.data;
652                 RNA_string_set(op->ptr, "constraint", con->name);
653
654                 list = get_constraint_lb(ob, con, NULL);
655
656                 if (&ob->constraints == list)
657                         RNA_enum_set(op->ptr, "owner", EDIT_CONSTRAINT_OWNER_OBJECT);
658                 else
659                         RNA_enum_set(op->ptr, "owner", EDIT_CONSTRAINT_OWNER_BONE);
660
661                 return 1;
662         }
663
664         return 0;
665 }
666
667 static bConstraint *edit_constraint_property_get(wmOperator *op, Object *ob, int type)
668 {
669         char constraint_name[MAX_NAME];
670         int owner = RNA_enum_get(op->ptr, "owner");
671         bConstraint *con;
672         ListBase *list = NULL;
673
674         RNA_string_get(op->ptr, "constraint", constraint_name);
675
676         if (owner == EDIT_CONSTRAINT_OWNER_OBJECT) {
677                 list = &ob->constraints;
678         }
679         else if (owner == EDIT_CONSTRAINT_OWNER_BONE) {
680                 bPoseChannel *pchan = BKE_pose_channel_active(ob);
681                 if (pchan)
682                         list = &pchan->constraints;
683                 else {
684                         //if (G.debug & G_DEBUG)
685                         //printf("edit_constraint_property_get: No active bone for object '%s'\n", (ob) ? ob->id.name + 2 : "<None>");
686                         return NULL;
687                 }
688         }
689         else {
690                 //if (G.debug & G_DEBUG)
691                 //printf("edit_constraint_property_get: defaulting to getting list in the standard way\n");
692                 list = get_active_constraints(ob);
693         }
694
695         con = BKE_constraints_find_name(list, constraint_name);
696         //if (G.debug & G_DEBUG)
697         //printf("constraint found = %p, %s\n", (void *)con, (con) ? con->name : "<Not found>");
698
699         if (con && (type != 0) && (con->type != type))
700                 con = NULL;
701
702         return con;
703 }
704
705 /* ********************** CONSTRAINT-SPECIFIC STUFF ********************* */
706
707 /* ---------- Distance-Dependent Constraints ---------- */
708 /* StretchTo, Limit Distance */
709
710 static int stretchto_reset_exec(bContext *C, wmOperator *op)
711 {
712         Main *bmain = CTX_data_main(C);
713         Object *ob = ED_object_active_context(C);
714         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_STRETCHTO);
715         bStretchToConstraint *data = (con) ? (bStretchToConstraint *)con->data : NULL;
716
717         /* despite 3 layers of checks, we may still not be able to find a constraint */
718         if (data == NULL)
719                 return OPERATOR_CANCELLED;
720
721         /* just set original length to 0.0, which will cause a reset on next recalc */
722         data->orglength = 0.0f;
723         ED_object_constraint_update(bmain, ob);
724
725         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, NULL);
726         return OPERATOR_FINISHED;
727 }
728
729 static int stretchto_reset_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
730 {
731         if (edit_constraint_invoke_properties(C, op))
732                 return stretchto_reset_exec(C, op);
733         else
734                 return OPERATOR_CANCELLED;
735 }
736
737 void CONSTRAINT_OT_stretchto_reset(wmOperatorType *ot)
738 {
739         /* identifiers */
740         ot->name = "Reset Original Length";
741         ot->idname = "CONSTRAINT_OT_stretchto_reset";
742         ot->description = "Reset original length of bone for Stretch To Constraint";
743
744         /* callbacks */
745         ot->invoke = stretchto_reset_invoke;
746         ot->exec = stretchto_reset_exec;
747         ot->poll = edit_constraint_poll;
748
749         /* flags */
750         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
751
752         /* properties */
753         edit_constraint_properties(ot);
754 }
755
756
757 static int limitdistance_reset_exec(bContext *C, wmOperator *op)
758 {
759         Main *bmain = CTX_data_main(C);
760         Object *ob = ED_object_active_context(C);
761         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_DISTLIMIT);
762         bDistLimitConstraint *data = (con) ? (bDistLimitConstraint *)con->data : NULL;
763
764         /* despite 3 layers of checks, we may still not be able to find a constraint */
765         if (data == NULL)
766                 return OPERATOR_CANCELLED;
767
768         /* just set original length to 0.0, which will cause a reset on next recalc */
769         data->dist = 0.0f;
770         ED_object_constraint_update(bmain, ob);
771
772         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, NULL);
773         return OPERATOR_FINISHED;
774 }
775
776 static int limitdistance_reset_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
777 {
778         if (edit_constraint_invoke_properties(C, op))
779                 return limitdistance_reset_exec(C, op);
780         else
781                 return OPERATOR_CANCELLED;
782 }
783
784 void CONSTRAINT_OT_limitdistance_reset(wmOperatorType *ot)
785 {
786         /* identifiers */
787         ot->name = "Reset Distance";
788         ot->idname = "CONSTRAINT_OT_limitdistance_reset";
789         ot->description = "Reset limiting distance for Limit Distance Constraint";
790
791         /* callbacks */
792         ot->invoke = limitdistance_reset_invoke;
793         ot->exec = limitdistance_reset_exec;
794         ot->poll = edit_constraint_poll;
795
796         /* flags */
797         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
798
799         /* properties */
800         edit_constraint_properties(ot);
801 }
802
803 /* ------------- Child-Of Constraint ------------------ */
804
805 static void child_get_inverse_matrix(const bContext *C, Scene *scene, Object *ob, bConstraint *con, float invmat[4][4], const int owner)
806 {
807         Depsgraph *depsgraph = CTX_data_depsgraph(C);
808
809         /* nullify inverse matrix first */
810         unit_m4(invmat);
811
812         if (owner == EDIT_CONSTRAINT_OWNER_BONE) {
813                 bPoseChannel *pchan;
814                 /* try to find a pose channel - assume that this is the constraint owner */
815                 /* TODO: get from context instead? */
816                 if (ob && ob->pose && (pchan = BKE_pose_channel_active(ob))) {
817                         bConstraint *con_last;
818                         /* calculate/set inverse matrix:
819                          * We just calculate all transform-stack eval up to but not including this constraint.
820                          * This is because inverse should just inverse correct for just the constraint's influence
821                          * when it gets applied; that is, at the time of application, we don't know anything about
822                          * what follows.
823                          */
824                         float imat[4][4], tmat[4][4];
825                         float pmat[4][4];
826
827                         /* make sure we passed the correct constraint */
828                         BLI_assert(BLI_findindex(&pchan->constraints, con) != -1);
829
830                         /* 1. calculate posemat where inverse doesn't exist yet (inverse was cleared above),
831                          * to use as baseline ("pmat") to derive delta from. This extra calc saves users
832                          * from having pressing "Clear Inverse" first
833                          */
834                         BKE_pose_where_is(depsgraph, scene, ob);
835                         copy_m4_m4(pmat, pchan->pose_mat);
836
837                         /* 2. knock out constraints starting from this one */
838                         con_last = pchan->constraints.last;
839                         pchan->constraints.last = con->prev;
840
841                         if (con->prev) {
842                                 /* new end must not point to this one, else this chain cutting is useless */
843                                 con->prev->next = NULL;
844                         }
845                         else {
846                                 /* constraint was first */
847                                 pchan->constraints.first = NULL;
848                         }
849
850                         /* 3. solve pose without disabled constraints */
851                         BKE_pose_where_is(depsgraph, scene, ob);
852
853                         /* 4. determine effect of constraint by removing the newly calculated
854                          * pchan->pose_mat from the original pchan->pose_mat, thus determining
855                          * the effect of the constraint
856                          */
857                         invert_m4_m4(imat, pchan->pose_mat);
858                         mul_m4_m4m4(tmat, pmat, imat);
859                         invert_m4_m4(invmat, tmat);
860
861                         /* 5. restore constraints */
862                         pchan->constraints.last = con_last;
863
864                         if (con->prev) {
865                                 /* hook up prev to this one again */
866                                 con->prev->next = con;
867                         }
868                         else {
869                                 /* set as first again */
870                                 pchan->constraints.first = con;
871                         }
872
873                         /* 6. recalculate pose with new inv-mat applied */
874                         BKE_pose_where_is(depsgraph, scene, ob);
875                 }
876         }
877         if (owner == EDIT_CONSTRAINT_OWNER_OBJECT) {
878                 if (ob) {
879                         Object workob;
880
881                         /* make sure we passed the correct constraint */
882                         BLI_assert(BLI_findindex(&ob->constraints, con) != -1);
883
884                         /* use BKE_object_workob_calc_parent to find inverse - just like for normal parenting */
885                         BKE_object_workob_calc_parent(depsgraph, scene, ob, &workob);
886                         invert_m4_m4(invmat, workob.obmat);
887                 }
888         }
889 }
890
891 /* ChildOf Constraint - set inverse callback */
892 static int childof_set_inverse_exec(bContext *C, wmOperator *op)
893 {
894         Scene *scene = CTX_data_scene(C);
895         Object *ob = ED_object_active_context(C);
896         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_CHILDOF);
897         bChildOfConstraint *data = (con) ? (bChildOfConstraint *)con->data : NULL;
898         const int owner = RNA_enum_get(op->ptr, "owner");
899
900         /* despite 3 layers of checks, we may still not be able to find a constraint */
901         if (data == NULL) {
902                 printf("DEBUG: Child-Of Set Inverse - object = '%s'\n", (ob) ? ob->id.name + 2 : "<None>");
903                 BKE_report(op->reports, RPT_ERROR, "Could not find constraint data for Child-Of Set Inverse");
904                 return OPERATOR_CANCELLED;
905         }
906
907         child_get_inverse_matrix(C, scene, ob, con, data->invmat, owner);
908
909         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
910
911         return OPERATOR_FINISHED;
912 }
913
914 static int childof_set_inverse_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
915 {
916         if (edit_constraint_invoke_properties(C, op))
917                 return childof_set_inverse_exec(C, op);
918         else
919                 return OPERATOR_CANCELLED;
920 }
921
922 void CONSTRAINT_OT_childof_set_inverse(wmOperatorType *ot)
923 {
924         /* identifiers */
925         ot->name = "Set Inverse";
926         ot->idname = "CONSTRAINT_OT_childof_set_inverse";
927         ot->description = "Set inverse correction for ChildOf constraint";
928
929         /* callbacks */
930         ot->invoke = childof_set_inverse_invoke;
931         ot->exec = childof_set_inverse_exec;
932         ot->poll = edit_constraint_poll;
933
934         /* flags */
935         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
936
937         /* properties */
938         edit_constraint_properties(ot);
939 }
940
941 /* ChildOf Constraint - clear inverse callback */
942 static int childof_clear_inverse_exec(bContext *C, wmOperator *op)
943 {
944         Object *ob = ED_object_active_context(C);
945         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_CHILDOF);
946         bChildOfConstraint *data = (con) ? (bChildOfConstraint *)con->data : NULL;
947
948         if (data == NULL) {
949                 BKE_report(op->reports, RPT_ERROR, "Child Of constraint not found");
950                 return OPERATOR_CANCELLED;
951         }
952
953         /* simply clear the matrix */
954         unit_m4(data->invmat);
955
956         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
957
958         return OPERATOR_FINISHED;
959 }
960
961 static int childof_clear_inverse_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
962 {
963         if (edit_constraint_invoke_properties(C, op))
964                 return childof_clear_inverse_exec(C, op);
965         else
966                 return OPERATOR_CANCELLED;
967 }
968
969 void CONSTRAINT_OT_childof_clear_inverse(wmOperatorType *ot)
970 {
971         /* identifiers */
972         ot->name = "Clear Inverse";
973         ot->idname = "CONSTRAINT_OT_childof_clear_inverse";
974         ot->description = "Clear inverse correction for ChildOf constraint";
975
976         /* callbacks */
977         ot->invoke = childof_clear_inverse_invoke;
978         ot->exec = childof_clear_inverse_exec;
979         ot->poll = edit_constraint_poll;
980
981         /* flags */
982         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
983
984         /* properties */
985         edit_constraint_properties(ot);
986 }
987
988 /* --------------- Follow Path Constraint ------------------ */
989
990 static int followpath_path_animate_exec(bContext *C, wmOperator *op)
991 {
992         Main *bmain = CTX_data_main(C);
993         Object *ob = ED_object_active_context(C);
994         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_FOLLOWPATH);
995         bFollowPathConstraint *data = (con) ? (bFollowPathConstraint *)con->data : NULL;
996
997         bAction *act = NULL;
998         FCurve *fcu = NULL;
999         int sfra = RNA_int_get(op->ptr, "frame_start");
1000         int len  = RNA_int_get(op->ptr, "length");
1001         float standardRange = 1.0;
1002
1003         /* nearly impossible sanity check */
1004         if (data == NULL) {
1005                 BKE_report(op->reports, RPT_ERROR, "Follow Path constraint not found");
1006                 return OPERATOR_CANCELLED;
1007         }
1008
1009         /* add F-Curve as appropriate */
1010         if (data->tar) {
1011                 Curve *cu = (Curve *)data->tar->data;
1012
1013                 if (ELEM(NULL, cu->adt, cu->adt->action) ||
1014                     (list_find_fcurve(&cu->adt->action->curves, "eval_time", 0) == NULL))
1015                 {
1016                         /* create F-Curve for path animation */
1017                         act = verify_adt_action(bmain, &cu->id, 1);
1018                         fcu = verify_fcurve(bmain, act, NULL, NULL, "eval_time", 0, 1);
1019
1020                         /* standard vertical range - 1:1 = 100 frames */
1021                         standardRange = 100.0f;
1022                 }
1023                 else {
1024                         /* path anim exists already - abort for now as this may well be what was intended */
1025                         BKE_report(op->reports, RPT_WARNING, "Path is already animated");
1026                         return OPERATOR_CANCELLED;
1027                 }
1028         }
1029         else {
1030                 /* animate constraint's "fixed offset" */
1031                 PointerRNA ptr;
1032                 PropertyRNA *prop;
1033                 char *path;
1034
1035                 /* get RNA pointer to constraint's "offset_factor" property - to build RNA path */
1036                 RNA_pointer_create(&ob->id, &RNA_FollowPathConstraint, con, &ptr);
1037                 prop = RNA_struct_find_property(&ptr, "offset_factor");
1038
1039                 path = RNA_path_from_ID_to_property(&ptr, prop);
1040
1041                 /* create F-Curve for constraint */
1042                 act = verify_adt_action(bmain, &ob->id, 1);
1043                 fcu = verify_fcurve(bmain, act, NULL, NULL, path, 0, 1);
1044
1045                 /* standard vertical range - 0.0 to 1.0 */
1046                 standardRange = 1.0f;
1047
1048                 /* enable "Use Fixed Position" so that animating this has effect */
1049                 data->followflag |= FOLLOWPATH_STATIC;
1050
1051                 /* path needs to be freed */
1052                 if (path)
1053                         MEM_freeN(path);
1054         }
1055
1056         /* setup dummy 'generator' modifier here to get 1-1 correspondence still working
1057          * and define basic slope of this curve based on the properties
1058          */
1059         if (!fcu->bezt && !fcu->fpt && !fcu->modifiers.first) {
1060                 FModifier *fcm = add_fmodifier(&fcu->modifiers, FMODIFIER_TYPE_GENERATOR, fcu);
1061                 FMod_Generator *gen = fcm->data;
1062
1063                 /* Assume that we have the following equation:
1064                  *     y = Ax + B
1065                  *         1    0       <-- coefficients array indices
1066                  */
1067                 float A = standardRange / (float)(len);
1068                 float B = (float)(-sfra) * A;
1069
1070                 gen->coefficients[1] = A;
1071                 gen->coefficients[0] = B;
1072         }
1073
1074         /* updates... */
1075         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
1076         return OPERATOR_FINISHED;
1077 }
1078
1079 static int followpath_path_animate_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1080 {
1081         /* hook up invoke properties for figuring out which constraint we're dealing with */
1082         if (edit_constraint_invoke_properties(C, op)) {
1083                 return followpath_path_animate_exec(C, op);
1084         }
1085         else {
1086                 return OPERATOR_CANCELLED;
1087         }
1088 }
1089
1090 void CONSTRAINT_OT_followpath_path_animate(wmOperatorType *ot)
1091 {
1092         /* identifiers */
1093         ot->name = "Auto Animate Path";
1094         ot->idname = "CONSTRAINT_OT_followpath_path_animate";
1095         ot->description = "Add default animation for path used by constraint if it isn't animated already";
1096
1097         /* callbacks */
1098         ot->invoke = followpath_path_animate_invoke;
1099         ot->exec = followpath_path_animate_exec;
1100         ot->poll = edit_constraint_poll;
1101
1102         /* flags */
1103         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1104
1105         /* props */
1106         edit_constraint_properties(ot);
1107         RNA_def_int(ot->srna, "frame_start", 1, MINAFRAME, MAXFRAME, "Start Frame",
1108                     "First frame of path animation", MINAFRAME, MAXFRAME);
1109         RNA_def_int(ot->srna, "length", 100, 0, MAXFRAME, "Length",
1110                     "Number of frames that path animation should take", 0, MAXFRAME);
1111 }
1112
1113 /* ------------- Object Solver Constraint ------------------ */
1114
1115 static int objectsolver_set_inverse_exec(bContext *C, wmOperator *op)
1116 {
1117         Scene *scene = CTX_data_scene(C);
1118         Object *ob = ED_object_active_context(C);
1119         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_OBJECTSOLVER);
1120         bObjectSolverConstraint *data = (con) ? (bObjectSolverConstraint *)con->data : NULL;
1121         const int owner = RNA_enum_get(op->ptr, "owner");
1122
1123         /* despite 3 layers of checks, we may still not be able to find a constraint */
1124         if (data == NULL) {
1125                 printf("DEBUG: Child-Of Set Inverse - object = '%s'\n", (ob) ? ob->id.name + 2 : "<None>");
1126                 BKE_report(op->reports, RPT_ERROR, "Could not find constraint data for Child-Of Set Inverse");
1127                 return OPERATOR_CANCELLED;
1128         }
1129
1130         child_get_inverse_matrix(C, scene, ob, con, data->invmat, owner);
1131
1132         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
1133
1134         return OPERATOR_FINISHED;
1135 }
1136
1137 static int objectsolver_set_inverse_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1138 {
1139         if (edit_constraint_invoke_properties(C, op))
1140                 return objectsolver_set_inverse_exec(C, op);
1141         else
1142                 return OPERATOR_CANCELLED;
1143 }
1144
1145 void CONSTRAINT_OT_objectsolver_set_inverse(wmOperatorType *ot)
1146 {
1147         /* identifiers */
1148         ot->name = "Set Inverse";
1149         ot->idname = "CONSTRAINT_OT_objectsolver_set_inverse";
1150         ot->description = "Set inverse correction for ObjectSolver constraint";
1151
1152         /* callbacks */
1153         ot->invoke = objectsolver_set_inverse_invoke;
1154         ot->exec = objectsolver_set_inverse_exec;
1155         ot->poll = edit_constraint_poll;
1156
1157         /* flags */
1158         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1159
1160         /* properties */
1161         edit_constraint_properties(ot);
1162 }
1163
1164 static int objectsolver_clear_inverse_exec(bContext *C, wmOperator *op)
1165 {
1166         Object *ob = ED_object_active_context(C);
1167         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_OBJECTSOLVER);
1168         bObjectSolverConstraint *data = (con) ? (bObjectSolverConstraint *)con->data : NULL;
1169
1170         if (data == NULL) {
1171                 BKE_report(op->reports, RPT_ERROR, "Child Of constraint not found");
1172                 return OPERATOR_CANCELLED;
1173         }
1174
1175         /* simply clear the matrix */
1176         unit_m4(data->invmat);
1177
1178         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
1179
1180         return OPERATOR_FINISHED;
1181 }
1182
1183 static int objectsolver_clear_inverse_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1184 {
1185         if (edit_constraint_invoke_properties(C, op))
1186                 return objectsolver_clear_inverse_exec(C, op);
1187         else
1188                 return OPERATOR_CANCELLED;
1189 }
1190
1191 void CONSTRAINT_OT_objectsolver_clear_inverse(wmOperatorType *ot)
1192 {
1193         /* identifiers */
1194         ot->name = "Clear Inverse";
1195         ot->idname = "CONSTRAINT_OT_objectsolver_clear_inverse";
1196         ot->description = "Clear inverse correction for ObjectSolver constraint";
1197
1198         /* callbacks */
1199         ot->invoke = objectsolver_clear_inverse_invoke;
1200         ot->exec = objectsolver_clear_inverse_exec;
1201         ot->poll = edit_constraint_poll;
1202
1203         /* flags */
1204         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1205
1206         /* properties */
1207         edit_constraint_properties(ot);
1208 }
1209
1210 /***************************** BUTTONS ****************************/
1211
1212 void ED_object_constraint_set_active(Object *ob, bConstraint *con)
1213 {
1214         ListBase *lb = get_constraint_lb(ob, con, NULL);
1215
1216         /* lets be nice and escape if its active already */
1217         /* NOTE: this assumes that the stack doesn't have other active ones set... */
1218         if ((lb && con) && (con->flag & CONSTRAINT_ACTIVE))
1219                 return;
1220
1221         BKE_constraints_active_set(lb, con);
1222 }
1223
1224 void ED_object_constraint_update(Main *bmain, Object *ob)
1225 {
1226         if (ob->pose) BKE_pose_update_constraint_flags(ob->pose);
1227
1228         object_test_constraints(bmain, ob);
1229
1230         if (ob->type == OB_ARMATURE)
1231                 DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY | ID_RECALC_TRANSFORM);
1232         else
1233                 DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM);
1234 }
1235
1236 static void object_pose_tag_update(Main *bmain, Object *ob)
1237 {
1238         BKE_pose_tag_recalc(bmain, ob->pose);    /* Checks & sort pose channels. */
1239         if (ob->proxy && ob->adt) {
1240                 /* We need to make use of ugly POSE_ANIMATION_WORKAROUND here too, else anim data are not reloaded
1241                  * after calling `BKE_pose_rebuild()`, which causes T43872.
1242                  * Note that this is a bit wide here, since we cannot be sure whether there are some locked proxy bones
1243                  * or not...
1244                  * XXX Temp hack until new depsgraph hopefully solves this. */
1245                 ob->adt->recalc |= ADT_RECALC_ANIM;
1246         }
1247 }
1248
1249 void ED_object_constraint_dependency_update(Main *bmain, Object *ob)
1250 {
1251         ED_object_constraint_update(bmain, ob);
1252
1253         if (ob->pose) {
1254                 object_pose_tag_update(bmain, ob);
1255         }
1256         DEG_relations_tag_update(bmain);
1257 }
1258
1259 void ED_object_constraint_tag_update(Main *bmain, Object *ob, bConstraint *con)
1260 {
1261         if (ob->pose) {
1262                 BKE_pose_tag_update_constraint_flags(ob->pose);
1263         }
1264
1265         if (con) {
1266                 object_test_constraint(bmain, ob, con);
1267         }
1268
1269         if (ob->type == OB_ARMATURE)
1270                 DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY | ID_RECALC_TRANSFORM);
1271         else
1272                 DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM);
1273
1274         /* Do Copy-on-Write tag here too, otherwise constraint
1275          * influence/mute buttons in UI have no effect
1276          */
1277         DEG_id_tag_update(&ob->id, ID_RECALC_COPY_ON_WRITE);
1278 }
1279
1280 void ED_object_constraint_dependency_tag_update(Main *bmain, Object *ob, bConstraint *con)
1281 {
1282         ED_object_constraint_tag_update(bmain, ob, con);
1283
1284         if (ob->pose) {
1285                 object_pose_tag_update(bmain, ob);
1286         }
1287         DEG_relations_tag_update(bmain);
1288 }
1289
1290 static bool constraint_poll(bContext *C)
1291 {
1292         PointerRNA ptr = CTX_data_pointer_get_type(C, "constraint", &RNA_Constraint);
1293         return (ptr.id.data && ptr.data);
1294 }
1295
1296
1297 static int constraint_delete_exec(bContext *C, wmOperator *UNUSED(op))
1298 {
1299         Main *bmain = CTX_data_main(C);
1300         PointerRNA ptr = CTX_data_pointer_get_type(C, "constraint", &RNA_Constraint);
1301         Object *ob = ptr.id.data;
1302         bConstraint *con = ptr.data;
1303         ListBase *lb = get_constraint_lb(ob, con, NULL);
1304
1305         /* free the constraint */
1306         if (BKE_constraint_remove_ex(lb, ob, con, true)) {
1307                 /* there's no active constraint now, so make sure this is the case */
1308                 BKE_constraints_active_set(&ob->constraints, NULL);
1309                 ED_object_constraint_update(bmain, ob); /* needed to set the flags on posebones correctly */
1310
1311                 /* relatiols */
1312                 DEG_relations_tag_update(CTX_data_main(C));
1313
1314                 /* notifiers */
1315                 WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT | NA_REMOVED, ob);
1316
1317                 return OPERATOR_FINISHED;
1318         }
1319         else {
1320                 /* couldn't remove due to some invalid data */
1321                 return OPERATOR_CANCELLED;
1322         }
1323 }
1324
1325 void CONSTRAINT_OT_delete(wmOperatorType *ot)
1326 {
1327         /* identifiers */
1328         ot->name = "Delete Constraint";
1329         ot->idname = "CONSTRAINT_OT_delete";
1330         ot->description = "Remove constraint from constraint stack";
1331
1332         /* callbacks */
1333         ot->exec = constraint_delete_exec;
1334         ot->poll = constraint_poll;
1335
1336         /* flags */
1337         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1338 }
1339
1340
1341 static int constraint_move_down_exec(bContext *C, wmOperator *op)
1342 {
1343         Object *ob = ED_object_active_context(C);
1344         bConstraint *con = edit_constraint_property_get(op, ob, 0);
1345
1346         if (con && con->next) {
1347                 ListBase *conlist = get_constraint_lb(ob, con, NULL);
1348                 bConstraint *nextCon = con->next;
1349
1350                 /* insert the nominated constraint after the one that used to be after it */
1351                 BLI_remlink(conlist, con);
1352                 BLI_insertlinkafter(conlist, nextCon, con);
1353
1354                 WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
1355
1356                 return OPERATOR_FINISHED;
1357         }
1358
1359         return OPERATOR_CANCELLED;
1360 }
1361
1362 static int constraint_move_down_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1363 {
1364         if (edit_constraint_invoke_properties(C, op))
1365                 return constraint_move_down_exec(C, op);
1366         else
1367                 return OPERATOR_CANCELLED;
1368 }
1369
1370 void CONSTRAINT_OT_move_down(wmOperatorType *ot)
1371 {
1372         /* identifiers */
1373         ot->name = "Move Constraint Down";
1374         ot->idname = "CONSTRAINT_OT_move_down";
1375         ot->description = "Move constraint down in constraint stack";
1376
1377         /* callbacks */
1378         ot->invoke = constraint_move_down_invoke;
1379         ot->exec = constraint_move_down_exec;
1380         ot->poll = edit_constraint_poll;
1381
1382         /* flags */
1383         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1384
1385         /* properties */
1386         edit_constraint_properties(ot);
1387 }
1388
1389
1390 static int constraint_move_up_exec(bContext *C, wmOperator *op)
1391 {
1392         Object *ob = ED_object_active_context(C);
1393         bConstraint *con = edit_constraint_property_get(op, ob, 0);
1394
1395         if (con && con->prev) {
1396                 ListBase *conlist = get_constraint_lb(ob, con, NULL);
1397                 bConstraint *prevCon = con->prev;
1398
1399                 /* insert the nominated constraint before the one that used to be before it */
1400                 BLI_remlink(conlist, con);
1401                 BLI_insertlinkbefore(conlist, prevCon, con);
1402
1403                 WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
1404
1405                 return OPERATOR_FINISHED;
1406         }
1407
1408         return OPERATOR_CANCELLED;
1409 }
1410
1411 static int constraint_move_up_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1412 {
1413         if (edit_constraint_invoke_properties(C, op))
1414                 return constraint_move_up_exec(C, op);
1415         else
1416                 return OPERATOR_CANCELLED;
1417 }
1418
1419 void CONSTRAINT_OT_move_up(wmOperatorType *ot)
1420 {
1421         /* identifiers */
1422         ot->name = "Move Constraint Up";
1423         ot->idname = "CONSTRAINT_OT_move_up";
1424         ot->description = "Move constraint up in constraint stack";
1425
1426         /* callbacks */
1427         ot->exec = constraint_move_up_exec;
1428         ot->invoke = constraint_move_up_invoke;
1429         ot->poll = edit_constraint_poll;
1430
1431         /* flags */
1432         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1433         edit_constraint_properties(ot);
1434 }
1435
1436 /***************************** OPERATORS ****************************/
1437
1438 /************************ remove constraint operators *********************/
1439
1440 static int pose_constraints_clear_exec(bContext *C, wmOperator *UNUSED(op))
1441 {
1442         Main *bmain = CTX_data_main(C);
1443         Object *prev_ob = NULL;
1444
1445         /* free constraints for all selected bones */
1446         CTX_DATA_BEGIN_WITH_ID (C, bPoseChannel *, pchan, selected_pose_bones, Object *, ob)
1447         {
1448                 BKE_constraints_free(&pchan->constraints);
1449                 pchan->constflag &= ~(PCHAN_HAS_IK | PCHAN_HAS_SPLINEIK | PCHAN_HAS_CONST);
1450
1451                 if (prev_ob != ob) {
1452                         DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY);
1453                         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT | NA_REMOVED, ob);
1454                         prev_ob = ob;
1455                 }
1456         }
1457         CTX_DATA_END;
1458
1459         /* force depsgraph to get recalculated since relationships removed */
1460         DEG_relations_tag_update(bmain);
1461
1462         /* note, calling BIK_clear_data() isn't needed here */
1463
1464         return OPERATOR_FINISHED;
1465 }
1466
1467 void POSE_OT_constraints_clear(wmOperatorType *ot)
1468 {
1469         /* identifiers */
1470         ot->name = "Clear Pose Constraints";
1471         ot->idname = "POSE_OT_constraints_clear";
1472         ot->description = "Clear all the constraints for the selected bones";
1473
1474         /* callbacks */
1475         ot->exec = pose_constraints_clear_exec;
1476         ot->poll = ED_operator_posemode_exclusive; // XXX - do we want to ensure there are selected bones too?
1477 }
1478
1479
1480 static int object_constraints_clear_exec(bContext *C, wmOperator *UNUSED(op))
1481 {
1482         Main *bmain = CTX_data_main(C);
1483
1484         /* do freeing */
1485         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1486         {
1487                 BKE_constraints_free(&ob->constraints);
1488                 DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM);
1489         }
1490         CTX_DATA_END;
1491
1492         /* force depsgraph to get recalculated since relationships removed */
1493         DEG_relations_tag_update(bmain);
1494
1495         /* do updates */
1496         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT | NA_REMOVED, NULL);
1497
1498         return OPERATOR_FINISHED;
1499 }
1500
1501 void OBJECT_OT_constraints_clear(wmOperatorType *ot)
1502 {
1503         /* identifiers */
1504         ot->name = "Clear Object Constraints";
1505         ot->idname = "OBJECT_OT_constraints_clear";
1506         ot->description = "Clear all the constraints for the active Object only";
1507
1508         /* callbacks */
1509         ot->exec = object_constraints_clear_exec;
1510         ot->poll = ED_operator_object_active_editable;
1511 }
1512
1513 /************************ copy all constraints operators *********************/
1514
1515 static int pose_constraint_copy_exec(bContext *C, wmOperator *op)
1516 {
1517         Main *bmain = CTX_data_main(C);
1518         bPoseChannel *pchan = CTX_data_active_pose_bone(C);
1519
1520         /* don't do anything if bone doesn't exist or doesn't have any constraints */
1521         if (ELEM(NULL, pchan, pchan->constraints.first)) {
1522                 BKE_report(op->reports, RPT_ERROR, "No active bone with constraints for copying");
1523                 return OPERATOR_CANCELLED;
1524         }
1525
1526         Object *prev_ob = NULL;
1527
1528         /* copy all constraints from active posebone to all selected posebones */
1529         CTX_DATA_BEGIN_WITH_ID(C, bPoseChannel *, chan, selected_pose_bones, Object *, ob)
1530         {
1531                 /* if we're not handling the object we're copying from, copy all constraints over */
1532                 if (pchan != chan) {
1533                         BKE_constraints_copy(&chan->constraints, &pchan->constraints, true);
1534                         /* update flags (need to add here, not just copy) */
1535                         chan->constflag |= pchan->constflag;
1536
1537                         if (prev_ob != ob) {
1538                                 BKE_pose_tag_recalc(bmain, ob->pose);
1539                                 DEG_id_tag_update((ID *)ob, ID_RECALC_GEOMETRY);
1540                                 prev_ob = ob;
1541                         }
1542                 }
1543         }
1544         CTX_DATA_END;
1545
1546         /* force depsgraph to get recalculated since new relationships added */
1547         DEG_relations_tag_update(bmain);
1548
1549         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, NULL);
1550
1551         return OPERATOR_FINISHED;
1552 }
1553
1554 void POSE_OT_constraints_copy(wmOperatorType *ot)
1555 {
1556         /* identifiers */
1557         ot->name = "Copy Constraints to Selected Bones";
1558         ot->idname = "POSE_OT_constraints_copy";
1559         ot->description = "Copy constraints to other selected bones";
1560
1561         /* api callbacks */
1562         ot->exec = pose_constraint_copy_exec;
1563         ot->poll = ED_operator_posemode_exclusive;
1564
1565         /* flags */
1566         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1567 }
1568
1569 static int object_constraint_copy_exec(bContext *C, wmOperator *UNUSED(op))
1570 {
1571         Main *bmain = CTX_data_main(C);
1572         Object *obact = ED_object_active_context(C);
1573
1574         /* copy all constraints from active object to all selected objects */
1575         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1576         {
1577                 /* if we're not handling the object we're copying from, copy all constraints over */
1578                 if (obact != ob) {
1579                         BKE_constraints_copy(&ob->constraints, &obact->constraints, true);
1580                         DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY);
1581                 }
1582         }
1583         CTX_DATA_END;
1584
1585         /* force depsgraph to get recalculated since new relationships added */
1586         DEG_relations_tag_update(bmain);
1587
1588         /* notifiers for updates */
1589         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT | NA_ADDED, NULL);
1590
1591         return OPERATOR_FINISHED;
1592 }
1593
1594 void OBJECT_OT_constraints_copy(wmOperatorType *ot)
1595 {
1596         /* identifiers */
1597         ot->name = "Copy Constraints to Selected Objects";
1598         ot->idname = "OBJECT_OT_constraints_copy";
1599         ot->description = "Copy constraints to other selected objects";
1600
1601         /* api callbacks */
1602         ot->exec = object_constraint_copy_exec;
1603         ot->poll = ED_operator_object_active_editable;
1604
1605         /* flags */
1606         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1607 }
1608
1609 /************************ add constraint operators *********************/
1610
1611 /* get the Object and/or PoseChannel to use as target */
1612 static bool get_new_constraint_target(bContext *C, int con_type, Object **tar_ob, bPoseChannel **tar_pchan, bool add)
1613 {
1614         Object *obact = ED_object_active_context(C);
1615         bPoseChannel *pchanact = BKE_pose_channel_active(obact);
1616         bool only_curve = false, only_mesh = false, only_ob = false;
1617         bool found = false;
1618
1619         /* clear tar_ob and tar_pchan fields before use
1620          * - assume for now that both always exist...
1621          */
1622         *tar_ob = NULL;
1623         *tar_pchan = NULL;
1624
1625         /* check if constraint type doesn't requires a target
1626          * - if so, no need to get any targets
1627          */
1628         switch (con_type) {
1629                 /* no-target constraints --------------------------- */
1630                 /* null constraint - shouldn't even be added! */
1631                 case CONSTRAINT_TYPE_NULL:
1632                 /* limit constraints - no targets needed */
1633                 case CONSTRAINT_TYPE_LOCLIMIT:
1634                 case CONSTRAINT_TYPE_ROTLIMIT:
1635                 case CONSTRAINT_TYPE_SIZELIMIT:
1636                 case CONSTRAINT_TYPE_SAMEVOL:
1637                         return false;
1638
1639                 /* restricted target-type constraints -------------- */
1640                 /* NOTE: for these, we cannot try to add a target object if no valid ones are found, since that doesn't work */
1641                 /* curve-based constraints - set the only_curve and only_ob flags */
1642                 case CONSTRAINT_TYPE_CLAMPTO:
1643                 case CONSTRAINT_TYPE_FOLLOWPATH:
1644                 case CONSTRAINT_TYPE_SPLINEIK:
1645                         only_curve = true;
1646                         only_ob = true;
1647                         add = false;
1648                         break;
1649
1650                 /* mesh only? */
1651                 case CONSTRAINT_TYPE_SHRINKWRAP:
1652                         only_mesh = true;
1653                         only_ob = true;
1654                         add = false;
1655                         break;
1656         }
1657
1658         /* if the active Object is Armature, and we can search for bones, do so... */
1659         if ((obact->type == OB_ARMATURE) && (only_ob == false)) {
1660                 /* search in list of selected Pose-Channels for target */
1661                 CTX_DATA_BEGIN (C, bPoseChannel *, pchan, selected_pose_bones_from_active_object)
1662                 {
1663                         /* just use the first one that we encounter, as long as it is not the active one */
1664                         if (pchan != pchanact) {
1665                                 *tar_ob = obact;
1666                                 *tar_pchan = pchan;
1667                                 found = true;
1668
1669                                 break;
1670                         }
1671                 }
1672                 CTX_DATA_END;
1673         }
1674
1675         /* if not yet found, try selected Objects... */
1676         if (found == false) {
1677                 /* search in selected objects context */
1678                 CTX_DATA_BEGIN (C, Object *, ob, selected_objects)
1679                 {
1680                         /* just use the first object we encounter (that isn't the active object)
1681                          * and which fulfills the criteria for the object-target that we've got
1682                          */
1683                         if (ob != obact) {
1684                                 /* for armatures in pose mode, look inside the armature for the active bone
1685                                  * so that we set up cross-armature constraints with less effort
1686                                  */
1687                                 if ((ob->type == OB_ARMATURE) && (ob->mode & OB_MODE_POSE) &&
1688                                     (!only_curve && !only_mesh))
1689                                 {
1690                                         /* just use the active bone, and assume that it is visible + usable */
1691                                         *tar_ob = ob;
1692                                         *tar_pchan = BKE_pose_channel_active(ob);
1693                                         found = true;
1694
1695                                         break;
1696                                 }
1697                                 else if (((!only_curve) || (ob->type == OB_CURVE)) &&
1698                                          ((!only_mesh) || (ob->type == OB_MESH)))
1699                                 {
1700                                         /* set target */
1701                                         *tar_ob = ob;
1702                                         found = true;
1703
1704                                         /* perform some special operations on the target */
1705                                         if (only_curve) {
1706                                                 /* Curve-Path option must be enabled for follow-path constraints to be able to work */
1707                                                 Curve *cu = (Curve *)ob->data;
1708                                                 cu->flag |= CU_PATH;
1709                                         }
1710
1711                                         break;
1712                                 }
1713                         }
1714                 }
1715                 CTX_DATA_END;
1716         }
1717
1718         /* if still not found, add a new empty to act as a target (if allowed) */
1719         if ((found == false) && (add)) {
1720                 Main *bmain = CTX_data_main(C);
1721                 Scene *scene = CTX_data_scene(C);
1722                 ViewLayer *view_layer = CTX_data_view_layer(C);
1723                 Base *base = BASACT(view_layer);
1724                 Object *obt;
1725
1726                 /* add new target object */
1727                 obt = BKE_object_add(bmain, scene, view_layer, OB_EMPTY, NULL);
1728
1729                 /* transform cent to global coords for loc */
1730                 if (pchanact) {
1731                         /* since by default, IK targets the tip of the last bone, use the tip of the active PoseChannel
1732                          * if adding a target for an IK Constraint
1733                          */
1734                         if (con_type == CONSTRAINT_TYPE_KINEMATIC)
1735                                 mul_v3_m4v3(obt->loc, obact->obmat, pchanact->pose_tail);
1736                         else
1737                                 mul_v3_m4v3(obt->loc, obact->obmat, pchanact->pose_head);
1738                 }
1739                 else {
1740                         copy_v3_v3(obt->loc, obact->obmat[3]);
1741                 }
1742
1743                 /* restore, BKE_object_add sets active */
1744                 BASACT(view_layer) = base;
1745                 base->flag |= BASE_SELECTED;
1746
1747                 /* make our new target the new object */
1748                 *tar_ob = obt;
1749                 found = true;
1750         }
1751
1752         /* return whether there's any target */
1753         return found;
1754 }
1755
1756 /* used by add constraint operators to add the constraint required */
1757 static int constraint_add_exec(bContext *C, wmOperator *op, Object *ob, ListBase *list, int type, const bool setTarget)
1758 {
1759         Main *bmain = CTX_data_main(C);
1760         bPoseChannel *pchan;
1761         bConstraint *con;
1762
1763         if (list == &ob->constraints) {
1764                 pchan = NULL;
1765         }
1766         else {
1767                 pchan = BKE_pose_channel_active(ob);
1768
1769                 /* ensure not to confuse object/pose adding */
1770                 if (pchan == NULL) {
1771                         BKE_report(op->reports, RPT_ERROR, "No active pose bone to add a constraint to");
1772                         return OPERATOR_CANCELLED;
1773                 }
1774         }
1775         /* check if constraint to be added is valid for the given constraints stack */
1776         if (type == CONSTRAINT_TYPE_NULL) {
1777                 return OPERATOR_CANCELLED;
1778         }
1779         if ((type == CONSTRAINT_TYPE_KINEMATIC) && ((!pchan) || (list != &pchan->constraints))) {
1780                 BKE_report(op->reports, RPT_ERROR, "IK constraint can only be added to bones");
1781                 return OPERATOR_CANCELLED;
1782         }
1783         if ((type == CONSTRAINT_TYPE_SPLINEIK) && ((!pchan) || (list != &pchan->constraints))) {
1784                 BKE_report(op->reports, RPT_ERROR, "Spline IK constraint can only be added to bones");
1785                 return OPERATOR_CANCELLED;
1786         }
1787
1788         /* create a new constraint of the type required, and add it to the active/given constraints list */
1789         if (pchan)
1790                 con = BKE_constraint_add_for_pose(ob, pchan, NULL, type);
1791         else
1792                 con = BKE_constraint_add_for_object(ob, NULL, type);
1793
1794         /* get the first selected object/bone, and make that the target
1795          * - apart from the buttons-window add buttons, we shouldn't add in this way
1796          */
1797         if (setTarget) {
1798                 Object *tar_ob = NULL;
1799                 bPoseChannel *tar_pchan = NULL;
1800
1801                 /* get the target objects, adding them as need be */
1802                 if (get_new_constraint_target(C, type, &tar_ob, &tar_pchan, 1)) {
1803                         /* method of setting target depends on the type of target we've got
1804                          * - by default, just set the first target (distinction here is only for multiple-targeted constraints)
1805                          */
1806                         if (tar_pchan)
1807                                 set_constraint_nth_target(con, tar_ob, tar_pchan->name, 0);
1808                         else
1809                                 set_constraint_nth_target(con, tar_ob, "", 0);
1810                 }
1811         }
1812
1813         /* do type-specific tweaking to the constraint settings  */
1814         switch (type) {
1815                 case CONSTRAINT_TYPE_PYTHON: /* FIXME: this code is not really valid anymore */
1816                 {
1817 #ifdef WITH_PYTHON
1818                         char *menustr;
1819                         int scriptint = 0;
1820                         /* popup a list of usable scripts */
1821                         menustr = buildmenu_pyconstraints(bmain, NULL, &scriptint);
1822                         /* XXX scriptint = pupmenu(menustr); */
1823                         MEM_freeN(menustr);
1824
1825                         /* only add constraint if a script was chosen */
1826                         if (scriptint) {
1827                                 /* add constraint */
1828                                 validate_pyconstraint_cb(bmain, con->data, &scriptint);
1829
1830                                 /* make sure target allowance is set correctly */
1831                                 BPY_pyconstraint_update(ob, con);
1832                         }
1833 #endif
1834                         break;
1835                 }
1836
1837                 default:
1838                         break;
1839         }
1840
1841         /* make sure all settings are valid - similar to above checks, but sometimes can be wrong */
1842         object_test_constraints(bmain, ob);
1843
1844         if (pchan)
1845                 BKE_pose_update_constraint_flags(ob->pose);
1846
1847
1848         /* force depsgraph to get recalculated since new relationships added */
1849         DEG_relations_tag_update(bmain);
1850
1851         if ((ob->type == OB_ARMATURE) && (pchan)) {
1852                 BKE_pose_tag_recalc(bmain, ob->pose);  /* sort pose channels */
1853                 if (BKE_constraints_proxylocked_owner(ob, pchan) && ob->adt) {
1854                         /* We need to make use of ugly POSE_ANIMATION_WORKAROUND here too, else anim data are not reloaded
1855                          * after calling `BKE_pose_rebuild()`, which causes T43872.
1856                          * XXX Temp hack until new depsgraph hopefully solves this. */
1857                         ob->adt->recalc |= ADT_RECALC_ANIM;
1858                 }
1859                 DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY | ID_RECALC_TRANSFORM);
1860         }
1861         else
1862                 DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM);
1863
1864         /* notifiers for updates */
1865         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT | NA_ADDED, ob);
1866
1867         return OPERATOR_FINISHED;
1868 }
1869
1870 /* ------------------ */
1871
1872 /* dummy operator callback */
1873 static int object_constraint_add_exec(bContext *C, wmOperator *op)
1874 {
1875         Object *ob = ED_object_active_context(C);
1876         int type = RNA_enum_get(op->ptr, "type");
1877         short with_targets = 0;
1878
1879         if (!ob) {
1880                 BKE_report(op->reports, RPT_ERROR, "No active object to add constraint to");
1881                 return OPERATOR_CANCELLED;
1882         }
1883
1884         /* hack: set constraint targets from selected objects in context is allowed when
1885          * operator name included 'with_targets', since the menu doesn't allow multiple properties
1886          */
1887         if (strstr(op->idname, "with_targets"))
1888                 with_targets = 1;
1889
1890         return constraint_add_exec(C, op, ob, &ob->constraints, type, with_targets);
1891 }
1892
1893 /* dummy operator callback */
1894 static int pose_constraint_add_exec(bContext *C, wmOperator *op)
1895 {
1896         Object *ob = BKE_object_pose_armature_get(ED_object_active_context(C));
1897         int type = RNA_enum_get(op->ptr, "type");
1898         short with_targets = 0;
1899
1900         if (!ob) {
1901                 BKE_report(op->reports, RPT_ERROR, "No active object to add constraint to");
1902                 return OPERATOR_CANCELLED;
1903         }
1904
1905         /* hack: set constraint targets from selected objects in context is allowed when
1906          * operator name included 'with_targets', since the menu doesn't allow multiple properties
1907          */
1908         if (strstr(op->idname, "with_targets"))
1909                 with_targets = 1;
1910
1911         return constraint_add_exec(C, op, ob, get_active_constraints(ob), type, with_targets);
1912 }
1913
1914 /* ------------------ */
1915
1916 void OBJECT_OT_constraint_add(wmOperatorType *ot)
1917 {
1918         /* identifiers */
1919         ot->name = "Add Constraint";
1920         ot->description = "Add a constraint to the active object";
1921         ot->idname = "OBJECT_OT_constraint_add";
1922
1923         /* api callbacks */
1924         ot->invoke = WM_menu_invoke;
1925         ot->exec = object_constraint_add_exec;
1926         ot->poll = ED_operator_object_active_editable;
1927
1928         /* flags */
1929         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1930
1931         /* properties */
1932         ot->prop = RNA_def_enum(ot->srna, "type", rna_enum_constraint_type_items, 0, "Type", "");
1933 }
1934
1935 void OBJECT_OT_constraint_add_with_targets(wmOperatorType *ot)
1936 {
1937         /* identifiers */
1938         ot->name = "Add Constraint (with Targets)";
1939         ot->description = "Add a constraint to the active object, with target (where applicable) set to the selected Objects/Bones";
1940         ot->idname = "OBJECT_OT_constraint_add_with_targets";
1941
1942         /* api callbacks */
1943         ot->invoke = WM_menu_invoke;
1944         ot->exec = object_constraint_add_exec;
1945         ot->poll = ED_operator_object_active_editable;
1946
1947         /* flags */
1948         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1949
1950         /* properties */
1951         ot->prop = RNA_def_enum(ot->srna, "type", rna_enum_constraint_type_items, 0, "Type", "");
1952 }
1953
1954 void POSE_OT_constraint_add(wmOperatorType *ot)
1955 {
1956         /* identifiers */
1957         ot->name = "Add Constraint";
1958         ot->description = "Add a constraint to the active bone";
1959         ot->idname = "POSE_OT_constraint_add";
1960
1961         /* api callbacks */
1962         ot->invoke = WM_menu_invoke;
1963         ot->exec = pose_constraint_add_exec;
1964         ot->poll = ED_operator_posemode_exclusive;
1965
1966         /* flags */
1967         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1968
1969         /* properties */
1970         ot->prop = RNA_def_enum(ot->srna, "type", rna_enum_constraint_type_items, 0, "Type", "");
1971 }
1972
1973 void POSE_OT_constraint_add_with_targets(wmOperatorType *ot)
1974 {
1975         /* identifiers */
1976         ot->name = "Add Constraint (with Targets)";
1977         ot->description = "Add a constraint to the active bone, with target (where applicable) set to the selected Objects/Bones";
1978         ot->idname = "POSE_OT_constraint_add_with_targets";
1979
1980         /* api callbacks */
1981         ot->invoke = WM_menu_invoke;
1982         ot->exec = pose_constraint_add_exec;
1983         ot->poll = ED_operator_posemode_exclusive;
1984
1985         /* flags */
1986         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1987
1988         /* properties */
1989         ot->prop = RNA_def_enum(ot->srna, "type", rna_enum_constraint_type_items, 0, "Type", "");
1990 }
1991
1992 /************************ IK Constraint operators *********************/
1993 /* NOTE: only for Pose-Channels */
1994 // TODO: should these be here, or back in editors/armature/poseobject.c again?
1995
1996 /* present menu with options + validation for targets to use */
1997 static int pose_ik_add_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1998 {
1999         Object *ob = BKE_object_pose_armature_get(CTX_data_active_object(C));
2000         bPoseChannel *pchan = BKE_pose_channel_active(ob);
2001         bConstraint *con = NULL;
2002
2003         uiPopupMenu *pup;
2004         uiLayout *layout;
2005         Object *tar_ob = NULL;
2006         bPoseChannel *tar_pchan = NULL;
2007
2008         /* must have active bone */
2009         if (ELEM(NULL, ob, pchan)) {
2010                 BKE_report(op->reports, RPT_ERROR, "Must have an active bone to add IK constraint to");
2011                 return OPERATOR_CANCELLED;
2012         }
2013
2014         /* bone must not have any constraints already */
2015         for (con = pchan->constraints.first; con; con = con->next) {
2016                 if (con->type == CONSTRAINT_TYPE_KINEMATIC) break;
2017         }
2018         if (con) {
2019                 BKE_report(op->reports, RPT_ERROR, "Bone already has an IK constraint");
2020                 return OPERATOR_CANCELLED;
2021         }
2022
2023         /* prepare popup menu to choose targeting options */
2024         pup = UI_popup_menu_begin(C, IFACE_("Add IK"), ICON_NONE);
2025         layout = UI_popup_menu_layout(pup);
2026
2027         /* the type of targets we'll set determines the menu entries to show... */
2028         if (get_new_constraint_target(C, CONSTRAINT_TYPE_KINEMATIC, &tar_ob, &tar_pchan, 0)) {
2029                 /* bone target, or object target?
2030                  * - the only thing that matters is that we want a target...
2031                  */
2032                 if (tar_pchan)
2033                         uiItemBooleanO(layout, IFACE_("To Active Bone"), ICON_NONE, "POSE_OT_ik_add", "with_targets", 1);
2034                 else
2035                         uiItemBooleanO(layout, IFACE_("To Active Object"), ICON_NONE, "POSE_OT_ik_add", "with_targets", 1);
2036         }
2037         else {
2038                 /* we have a choice of adding to a new empty, or not setting any target (targetless IK) */
2039                 uiItemBooleanO(layout, IFACE_("To New Empty Object"), ICON_NONE, "POSE_OT_ik_add", "with_targets", 1);
2040                 uiItemBooleanO(layout, IFACE_("Without Targets"), ICON_NONE, "POSE_OT_ik_add", "with_targets", 0);
2041         }
2042
2043         /* finish building the menu, and process it (should result in calling self again) */
2044         UI_popup_menu_end(C, pup);
2045
2046         return OPERATOR_INTERFACE;
2047 }
2048
2049 /* call constraint_add_exec() to add the IK constraint */
2050 static int pose_ik_add_exec(bContext *C, wmOperator *op)
2051 {
2052         Object *ob = CTX_data_active_object(C);
2053         const bool with_targets = RNA_boolean_get(op->ptr, "with_targets");
2054
2055         /* add the constraint - all necessary checks should have been done by the invoke() callback already... */
2056         return constraint_add_exec(C, op, ob, get_active_constraints(ob), CONSTRAINT_TYPE_KINEMATIC, with_targets);
2057 }
2058
2059 void POSE_OT_ik_add(wmOperatorType *ot)
2060 {
2061         /* identifiers */
2062         ot->name = "Add IK to Bone";
2063         ot->description = "Add IK Constraint to the active Bone";
2064         ot->idname = "POSE_OT_ik_add";
2065
2066         /* api callbacks */
2067         ot->invoke = pose_ik_add_invoke;
2068         ot->exec = pose_ik_add_exec;
2069         ot->poll = ED_operator_posemode_exclusive;
2070
2071         /* flags */
2072         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2073
2074         /* properties */
2075         RNA_def_boolean(ot->srna, "with_targets", 1, "With Targets", "Assign IK Constraint with targets derived from the select bones/objects");
2076 }
2077
2078 /* ------------------ */
2079
2080 /* remove IK constraints from selected bones */
2081 static int pose_ik_clear_exec(bContext *C, wmOperator *UNUSED(op))
2082 {
2083         Object *prev_ob = NULL;
2084
2085         /* only remove IK Constraints */
2086         CTX_DATA_BEGIN_WITH_ID (C, bPoseChannel *, pchan, selected_pose_bones, Object *, ob)
2087         {
2088                 bConstraint *con, *next;
2089
2090                 /* TODO: should we be checking if these constraints were local before we try and remove them? */
2091                 for (con = pchan->constraints.first; con; con = next) {
2092                         next = con->next;
2093                         if (con->type == CONSTRAINT_TYPE_KINEMATIC) {
2094                                 BKE_constraint_remove(&pchan->constraints, con);
2095                         }
2096                 }
2097                 pchan->constflag &= ~(PCHAN_HAS_IK | PCHAN_HAS_TARGET);
2098
2099                 if (prev_ob != ob) {
2100                         prev_ob = ob;
2101
2102                         /* Refresh depsgraph. */
2103                         DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY);
2104
2105                         /* Note, notifier might evolve. */
2106                         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT | NA_REMOVED, ob);
2107                 }
2108         }
2109         CTX_DATA_END;
2110
2111         return OPERATOR_FINISHED;
2112 }
2113
2114 void POSE_OT_ik_clear(wmOperatorType *ot)
2115 {
2116         /* identifiers */
2117         ot->name = "Remove IK";
2118         ot->description = "Remove all IK Constraints from selected bones";
2119         ot->idname = "POSE_OT_ik_clear";
2120
2121         /* api callbacks */
2122         ot->exec = pose_ik_clear_exec;
2123         ot->poll = ED_operator_posemode_exclusive;
2124
2125         /* flags */
2126         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2127 }