Merge branch 'master' into blender2.8
[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(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 = G.main->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(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 = G.main->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                 /* disable and clear constraints targets that are incorrect */
434                 for (ct = targets.first; ct; ct = ct->next) {
435                         /* general validity checks (for those constraints that need this) */
436                         if (BKE_object_exists_check(bmain, ct->tar) == 0) {
437                                 /* object doesn't exist, but constraint requires target */
438                                 ct->tar = NULL;
439                                 con->flag |= CONSTRAINT_DISABLE;
440                         }
441                         else if (ct->tar == owner) {
442                                 if (type == CONSTRAINT_OBTYPE_BONE) {
443                                         if (!BKE_armature_find_bone_name(BKE_armature_from_object(owner), ct->subtarget)) {
444                                                 /* bone must exist in armature... */
445                                                 /* TODO: clear subtarget? */
446                                                 con->flag |= CONSTRAINT_DISABLE;
447                                         }
448                                         else if (STREQ(pchan->name, ct->subtarget)) {
449                                                 /* cannot target self */
450                                                 ct->subtarget[0] = '\0';
451                                                 con->flag |= CONSTRAINT_DISABLE;
452                                         }
453                                 }
454                                 else {
455                                         /* cannot use self as target */
456                                         ct->tar = NULL;
457                                         con->flag |= CONSTRAINT_DISABLE;
458                                 }
459                         }
460
461                         /* target checks for specific constraints */
462                         if (ELEM(con->type, CONSTRAINT_TYPE_FOLLOWPATH, CONSTRAINT_TYPE_CLAMPTO, CONSTRAINT_TYPE_SPLINEIK)) {
463                                 if (ct->tar) {
464                                         if (ct->tar->type != OB_CURVE) {
465                                                 ct->tar = NULL;
466                                                 con->flag |= CONSTRAINT_DISABLE;
467                                         }
468                                         else {
469                                                 Curve *cu = ct->tar->data;
470
471                                                 /* auto-set 'Path' setting on curve so this works  */
472                                                 cu->flag |= CU_PATH;
473                                         }
474                                 }
475                         }
476                 }
477
478                 /* free any temporary targets */
479                 if (cti->flush_constraint_targets)
480                         cti->flush_constraint_targets(con, &targets, 0);
481         }
482 }
483
484 static int constraint_type_get(Object *owner, bPoseChannel *pchan)
485 {
486         int type;
487         /* Check parents */
488         if (pchan) {
489                 switch (owner->type) {
490                         case OB_ARMATURE:
491                                 type = CONSTRAINT_OBTYPE_BONE;
492                                 break;
493                         default:
494                                 type = CONSTRAINT_OBTYPE_OBJECT;
495                                 break;
496                 }
497         }
498         else
499                 type = CONSTRAINT_OBTYPE_OBJECT;
500         return type;
501 }
502
503 /* checks validity of object pointers, and NULLs,
504  * if Bone doesnt exist it sets the CONSTRAINT_DISABLE flag.
505  */
506 static void test_constraints(Main *bmain, Object *owner, bPoseChannel *pchan)
507 {
508         bConstraint *curcon;
509         ListBase *conlist = NULL;
510         int type;
511
512         if (owner == NULL) return;
513
514         type = constraint_type_get(owner, pchan);
515
516         /* Get the constraint list for this object */
517         switch (type) {
518                 case CONSTRAINT_OBTYPE_OBJECT:
519                         conlist = &owner->constraints;
520                         break;
521                 case CONSTRAINT_OBTYPE_BONE:
522                         conlist = &pchan->constraints;
523                         break;
524         }
525
526         /* Check all constraints - is constraint valid? */
527         if (conlist) {
528                 for (curcon = conlist->first; curcon; curcon = curcon->next) {
529                         test_constraint(bmain, owner, pchan, curcon, type);
530                 }
531         }
532 }
533
534 void object_test_constraints(Main *bmain, Object *owner)
535 {
536         if (owner->constraints.first)
537                 test_constraints(bmain, owner, NULL);
538
539         if (owner->type == OB_ARMATURE && owner->pose) {
540                 bPoseChannel *pchan;
541
542                 for (pchan = owner->pose->chanbase.first; pchan; pchan = pchan->next) {
543                         if (pchan->constraints.first)
544                                 test_constraints(bmain, owner, pchan);
545                 }
546         }
547 }
548
549 static void object_test_constraint(Main *bmain, Object *owner, bConstraint *con)
550 {
551         if (owner->type == OB_ARMATURE && owner->pose) {
552                 if (BLI_findindex(&owner->constraints, con) != -1) {
553                         test_constraint(bmain, owner, NULL, con, CONSTRAINT_OBTYPE_OBJECT);
554                 }
555                 else {
556                         bPoseChannel *pchan;
557                         for (pchan = owner->pose->chanbase.first; pchan; pchan = pchan->next) {
558                                 if (BLI_findindex(&pchan->constraints, con) != -1) {
559                                         test_constraint(bmain, owner, pchan, con, CONSTRAINT_OBTYPE_BONE);
560                                         break;
561                                 }
562                         }
563                 }
564         }
565         else {
566                 test_constraint(bmain, owner, NULL, con, CONSTRAINT_OBTYPE_OBJECT);
567         }
568 }
569
570 /************************ generic functions for operators using constraint names and data context *********************/
571
572 #define EDIT_CONSTRAINT_OWNER_OBJECT    0
573 #define EDIT_CONSTRAINT_OWNER_BONE      1
574
575 static const EnumPropertyItem constraint_owner_items[] = {
576         {EDIT_CONSTRAINT_OWNER_OBJECT, "OBJECT", 0, "Object", "Edit a constraint on the active object"},
577         {EDIT_CONSTRAINT_OWNER_BONE, "BONE", 0, "Bone", "Edit a constraint on the active bone"},
578         {0, NULL, 0, NULL, NULL}};
579
580
581 static int edit_constraint_poll_generic(bContext *C, StructRNA *rna_type)
582 {
583         PointerRNA ptr = CTX_data_pointer_get_type(C, "constraint", rna_type);
584         Object *ob = (ptr.id.data) ? ptr.id.data : ED_object_active_context(C);
585
586         if (!ptr.data) {
587                 CTX_wm_operator_poll_msg_set(C, "Context missing 'constraint'");
588                 return 0;
589         }
590
591         if (!ob) {
592                 CTX_wm_operator_poll_msg_set(C, "Context missing active object");
593                 return 0;
594         }
595
596         if (ID_IS_LINKED(ob) || (ptr.id.data && ID_IS_LINKED(ptr.id.data))) {
597                 CTX_wm_operator_poll_msg_set(C, "Cannot edit library data");
598                 return 0;
599         }
600
601         if (ID_IS_STATIC_OVERRIDE(ob)) {
602                 CTX_wm_operator_poll_msg_set(C, "Cannot edit constraints comming from static override");
603                 return (((bConstraint *)ptr.data)->flag & CONSTRAINT_STATICOVERRIDE_LOCAL) != 0;
604         }
605
606         return 1;
607 }
608
609 static int edit_constraint_poll(bContext *C)
610 {
611         return edit_constraint_poll_generic(C, &RNA_Constraint);
612 }
613
614 static void edit_constraint_properties(wmOperatorType *ot)
615 {
616         RNA_def_string(ot->srna, "constraint", NULL, MAX_NAME, "Constraint", "Name of the constraint to edit");
617         RNA_def_enum(ot->srna, "owner", constraint_owner_items, 0, "Owner", "The owner of this constraint");
618 }
619
620 static int edit_constraint_invoke_properties(bContext *C, wmOperator *op)
621 {
622         PointerRNA ptr = CTX_data_pointer_get_type(C, "constraint", &RNA_Constraint);
623         Object *ob = (ptr.id.data) ? ptr.id.data : ED_object_active_context(C);
624         bConstraint *con;
625         ListBase *list;
626
627         if (RNA_struct_property_is_set(op->ptr, "constraint") && RNA_struct_property_is_set(op->ptr, "owner"))
628                 return 1;
629
630         if (ptr.data) {
631                 con = ptr.data;
632                 RNA_string_set(op->ptr, "constraint", con->name);
633
634                 list = get_constraint_lb(ob, con, NULL);
635
636                 if (&ob->constraints == list)
637                         RNA_enum_set(op->ptr, "owner", EDIT_CONSTRAINT_OWNER_OBJECT);
638                 else
639                         RNA_enum_set(op->ptr, "owner", EDIT_CONSTRAINT_OWNER_BONE);
640
641                 return 1;
642         }
643
644         return 0;
645 }
646
647 static bConstraint *edit_constraint_property_get(wmOperator *op, Object *ob, int type)
648 {
649         char constraint_name[MAX_NAME];
650         int owner = RNA_enum_get(op->ptr, "owner");
651         bConstraint *con;
652         ListBase *list = NULL;
653
654         RNA_string_get(op->ptr, "constraint", constraint_name);
655
656         if (owner == EDIT_CONSTRAINT_OWNER_OBJECT) {
657                 list = &ob->constraints;
658         }
659         else if (owner == EDIT_CONSTRAINT_OWNER_BONE) {
660                 bPoseChannel *pchan = BKE_pose_channel_active(ob);
661                 if (pchan)
662                         list = &pchan->constraints;
663                 else {
664                         //if (G.debug & G_DEBUG)
665                         //printf("edit_constraint_property_get: No active bone for object '%s'\n", (ob) ? ob->id.name + 2 : "<None>");
666                         return NULL;
667                 }
668         }
669         else {
670                 //if (G.debug & G_DEBUG)
671                 //printf("edit_constraint_property_get: defaulting to getting list in the standard way\n");
672                 list = get_active_constraints(ob);
673         }
674
675         con = BKE_constraints_find_name(list, constraint_name);
676         //if (G.debug & G_DEBUG)
677         //printf("constraint found = %p, %s\n", (void *)con, (con) ? con->name : "<Not found>");
678
679         if (con && (type != 0) && (con->type != type))
680                 con = NULL;
681
682         return con;
683 }
684
685 /* ********************** CONSTRAINT-SPECIFIC STUFF ********************* */
686
687 /* ---------- Distance-Dependent Constraints ---------- */
688 /* StretchTo, Limit Distance */
689
690 static int stretchto_reset_exec(bContext *C, wmOperator *op)
691 {
692         Main *bmain = CTX_data_main(C);
693         Object *ob = ED_object_active_context(C);
694         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_STRETCHTO);
695         bStretchToConstraint *data = (con) ? (bStretchToConstraint *)con->data : NULL;
696
697         /* despite 3 layers of checks, we may still not be able to find a constraint */
698         if (data == NULL)
699                 return OPERATOR_CANCELLED;
700
701         /* just set original length to 0.0, which will cause a reset on next recalc */
702         data->orglength = 0.0f;
703         ED_object_constraint_update(bmain, ob);
704
705         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, NULL);
706         return OPERATOR_FINISHED;
707 }
708
709 static int stretchto_reset_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
710 {
711         if (edit_constraint_invoke_properties(C, op))
712                 return stretchto_reset_exec(C, op);
713         else
714                 return OPERATOR_CANCELLED;
715 }
716
717 void CONSTRAINT_OT_stretchto_reset(wmOperatorType *ot)
718 {
719         /* identifiers */
720         ot->name = "Reset Original Length";
721         ot->idname = "CONSTRAINT_OT_stretchto_reset";
722         ot->description = "Reset original length of bone for Stretch To Constraint";
723
724         /* callbacks */
725         ot->invoke = stretchto_reset_invoke;
726         ot->exec = stretchto_reset_exec;
727         ot->poll = edit_constraint_poll;
728
729         /* flags */
730         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
731
732         /* properties */
733         edit_constraint_properties(ot);
734 }
735
736
737 static int limitdistance_reset_exec(bContext *C, wmOperator *op)
738 {
739         Main *bmain = CTX_data_main(C);
740         Object *ob = ED_object_active_context(C);
741         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_DISTLIMIT);
742         bDistLimitConstraint *data = (con) ? (bDistLimitConstraint *)con->data : NULL;
743
744         /* despite 3 layers of checks, we may still not be able to find a constraint */
745         if (data == NULL)
746                 return OPERATOR_CANCELLED;
747
748         /* just set original length to 0.0, which will cause a reset on next recalc */
749         data->dist = 0.0f;
750         ED_object_constraint_update(bmain, ob);
751
752         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, NULL);
753         return OPERATOR_FINISHED;
754 }
755
756 static int limitdistance_reset_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
757 {
758         if (edit_constraint_invoke_properties(C, op))
759                 return limitdistance_reset_exec(C, op);
760         else
761                 return OPERATOR_CANCELLED;
762 }
763
764 void CONSTRAINT_OT_limitdistance_reset(wmOperatorType *ot)
765 {
766         /* identifiers */
767         ot->name = "Reset Distance";
768         ot->idname = "CONSTRAINT_OT_limitdistance_reset";
769         ot->description = "Reset limiting distance for Limit Distance Constraint";
770
771         /* callbacks */
772         ot->invoke = limitdistance_reset_invoke;
773         ot->exec = limitdistance_reset_exec;
774         ot->poll = edit_constraint_poll;
775
776         /* flags */
777         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
778
779         /* properties */
780         edit_constraint_properties(ot);
781 }
782
783 /* ------------- Child-Of Constraint ------------------ */
784
785 static void child_get_inverse_matrix(const bContext *C, Scene *scene, Object *ob, bConstraint *con, float invmat[4][4], const int owner)
786 {
787         Depsgraph *depsgraph = CTX_data_depsgraph(C);
788
789         /* nullify inverse matrix first */
790         unit_m4(invmat);
791
792         if (owner == EDIT_CONSTRAINT_OWNER_BONE) {
793                 bPoseChannel *pchan;
794                 /* try to find a pose channel - assume that this is the constraint owner */
795                 /* TODO: get from context instead? */
796                 if (ob && ob->pose && (pchan = BKE_pose_channel_active(ob))) {
797                         bConstraint *con_last;
798                         /* calculate/set inverse matrix:
799                          *  We just calculate all transform-stack eval up to but not including this constraint.
800                          *  This is because inverse should just inverse correct for just the constraint's influence
801                          *  when it gets applied; that is, at the time of application, we don't know anything about
802                          *  what follows.
803                          */
804                         float imat[4][4], tmat[4][4];
805                         float pmat[4][4];
806
807                         /* make sure we passed the correct constraint */
808                         BLI_assert(BLI_findindex(&pchan->constraints, con) != -1);
809
810                         /* 1. calculate posemat where inverse doesn't exist yet (inverse was cleared above),
811                          * to use as baseline ("pmat") to derive delta from. This extra calc saves users
812                          * from having pressing "Clear Inverse" first
813                          */
814                         BKE_pose_where_is(depsgraph, scene, ob);
815                         copy_m4_m4(pmat, pchan->pose_mat);
816
817                         /* 2. knock out constraints starting from this one */
818                         con_last = pchan->constraints.last;
819                         pchan->constraints.last = con->prev;
820
821                         if (con->prev) {
822                                 /* new end must not point to this one, else this chain cutting is useless */
823                                 con->prev->next = NULL;
824                         }
825                         else {
826                                 /* constraint was first */
827                                 pchan->constraints.first = NULL;
828                         }
829
830                         /* 3. solve pose without disabled constraints */
831                         BKE_pose_where_is(depsgraph, scene, ob);
832
833                         /* 4. determine effect of constraint by removing the newly calculated
834                          * pchan->pose_mat from the original pchan->pose_mat, thus determining
835                          * the effect of the constraint
836                          */
837                         invert_m4_m4(imat, pchan->pose_mat);
838                         mul_m4_m4m4(tmat, pmat, imat);
839                         invert_m4_m4(invmat, tmat);
840
841                         /* 5. restore constraints */
842                         pchan->constraints.last = con_last;
843
844                         if (con->prev) {
845                                 /* hook up prev to this one again */
846                                 con->prev->next = con;
847                         }
848                         else {
849                                 /* set as first again */
850                                 pchan->constraints.first = con;
851                         }
852
853                         /* 6. recalculate pose with new inv-mat applied */
854                         BKE_pose_where_is(depsgraph, scene, ob);
855                 }
856         }
857         if (owner == EDIT_CONSTRAINT_OWNER_OBJECT) {
858                 if (ob) {
859                         Object workob;
860
861                         /* make sure we passed the correct constraint */
862                         BLI_assert(BLI_findindex(&ob->constraints, con) != -1);
863
864                         /* use BKE_object_workob_calc_parent to find inverse - just like for normal parenting */
865                         BKE_object_workob_calc_parent(depsgraph, scene, ob, &workob);
866                         invert_m4_m4(invmat, workob.obmat);
867                 }
868         }
869 }
870
871 /* ChildOf Constraint - set inverse callback */
872 static int childof_set_inverse_exec(bContext *C, wmOperator *op)
873 {
874         Scene *scene = CTX_data_scene(C);
875         Object *ob = ED_object_active_context(C);
876         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_CHILDOF);
877         bChildOfConstraint *data = (con) ? (bChildOfConstraint *)con->data : NULL;
878         const int owner = RNA_enum_get(op->ptr, "owner");
879
880         /* despite 3 layers of checks, we may still not be able to find a constraint */
881         if (data == NULL) {
882                 printf("DEBUG: Child-Of Set Inverse - object = '%s'\n", (ob) ? ob->id.name + 2 : "<None>");
883                 BKE_report(op->reports, RPT_ERROR, "Could not find constraint data for Child-Of Set Inverse");
884                 return OPERATOR_CANCELLED;
885         }
886
887         child_get_inverse_matrix(C, scene, ob, con, data->invmat, owner);
888
889         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
890
891         return OPERATOR_FINISHED;
892 }
893
894 static int childof_set_inverse_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
895 {
896         if (edit_constraint_invoke_properties(C, op))
897                 return childof_set_inverse_exec(C, op);
898         else
899                 return OPERATOR_CANCELLED;
900 }
901
902 void CONSTRAINT_OT_childof_set_inverse(wmOperatorType *ot)
903 {
904         /* identifiers */
905         ot->name = "Set Inverse";
906         ot->idname = "CONSTRAINT_OT_childof_set_inverse";
907         ot->description = "Set inverse correction for ChildOf constraint";
908
909         /* callbacks */
910         ot->invoke = childof_set_inverse_invoke;
911         ot->exec = childof_set_inverse_exec;
912         ot->poll = edit_constraint_poll;
913
914         /* flags */
915         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
916
917         /* properties */
918         edit_constraint_properties(ot);
919 }
920
921 /* ChildOf Constraint - clear inverse callback */
922 static int childof_clear_inverse_exec(bContext *C, wmOperator *op)
923 {
924         Object *ob = ED_object_active_context(C);
925         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_CHILDOF);
926         bChildOfConstraint *data = (con) ? (bChildOfConstraint *)con->data : NULL;
927
928         if (data == NULL) {
929                 BKE_report(op->reports, RPT_ERROR, "Child Of constraint not found");
930                 return OPERATOR_CANCELLED;
931         }
932
933         /* simply clear the matrix */
934         unit_m4(data->invmat);
935
936         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
937
938         return OPERATOR_FINISHED;
939 }
940
941 static int childof_clear_inverse_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
942 {
943         if (edit_constraint_invoke_properties(C, op))
944                 return childof_clear_inverse_exec(C, op);
945         else
946                 return OPERATOR_CANCELLED;
947 }
948
949 void CONSTRAINT_OT_childof_clear_inverse(wmOperatorType *ot)
950 {
951         /* identifiers */
952         ot->name = "Clear Inverse";
953         ot->idname = "CONSTRAINT_OT_childof_clear_inverse";
954         ot->description = "Clear inverse correction for ChildOf constraint";
955
956         /* callbacks */
957         ot->invoke = childof_clear_inverse_invoke;
958         ot->exec = childof_clear_inverse_exec;
959         ot->poll = edit_constraint_poll;
960
961         /* flags */
962         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
963
964         /* properties */
965         edit_constraint_properties(ot);
966 }
967
968 /* --------------- Follow Path Constraint ------------------ */
969
970 static int followpath_path_animate_exec(bContext *C, wmOperator *op)
971 {
972         Object *ob = ED_object_active_context(C);
973         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_FOLLOWPATH);
974         bFollowPathConstraint *data = (con) ? (bFollowPathConstraint *)con->data : NULL;
975
976         bAction *act = NULL;
977         FCurve *fcu = NULL;
978         int sfra = RNA_int_get(op->ptr, "frame_start");
979         int len  = RNA_int_get(op->ptr, "length");
980         float standardRange = 1.0;
981
982         /* nearly impossible sanity check */
983         if (data == NULL) {
984                 BKE_report(op->reports, RPT_ERROR, "Follow Path constraint not found");
985                 return OPERATOR_CANCELLED;
986         }
987
988         /* add F-Curve as appropriate */
989         if (data->tar) {
990                 Curve *cu = (Curve *)data->tar->data;
991
992                 if (ELEM(NULL, cu->adt, cu->adt->action) ||
993                     (list_find_fcurve(&cu->adt->action->curves, "eval_time", 0) == NULL))
994                 {
995                         /* create F-Curve for path animation */
996                         act = verify_adt_action(&cu->id, 1);
997                         fcu = verify_fcurve(act, NULL, NULL, "eval_time", 0, 1);
998
999                         /* standard vertical range - 1:1 = 100 frames */
1000                         standardRange = 100.0f;
1001                 }
1002                 else {
1003                         /* path anim exists already - abort for now as this may well be what was intended */
1004                         BKE_report(op->reports, RPT_WARNING, "Path is already animated");
1005                         return OPERATOR_CANCELLED;
1006                 }
1007         }
1008         else {
1009                 /* animate constraint's "fixed offset" */
1010                 PointerRNA ptr;
1011                 PropertyRNA *prop;
1012                 char *path;
1013
1014                 /* get RNA pointer to constraint's "offset_factor" property - to build RNA path */
1015                 RNA_pointer_create(&ob->id, &RNA_FollowPathConstraint, con, &ptr);
1016                 prop = RNA_struct_find_property(&ptr, "offset_factor");
1017
1018                 path = RNA_path_from_ID_to_property(&ptr, prop);
1019
1020                 /* create F-Curve for constraint */
1021                 act = verify_adt_action(&ob->id, 1);
1022                 fcu = verify_fcurve(act, NULL, NULL, path, 0, 1);
1023
1024                 /* standard vertical range - 0.0 to 1.0 */
1025                 standardRange = 1.0f;
1026
1027                 /* enable "Use Fixed Position" so that animating this has effect */
1028                 data->followflag |= FOLLOWPATH_STATIC;
1029
1030                 /* path needs to be freed */
1031                 if (path)
1032                         MEM_freeN(path);
1033         }
1034
1035         /* setup dummy 'generator' modifier here to get 1-1 correspondence still working
1036          * and define basic slope of this curve based on the properties
1037          */
1038         if (!fcu->bezt && !fcu->fpt && !fcu->modifiers.first) {
1039                 FModifier *fcm = add_fmodifier(&fcu->modifiers, FMODIFIER_TYPE_GENERATOR, fcu);
1040                 FMod_Generator *gen = fcm->data;
1041
1042                 /* Assume that we have the following equation:
1043                  *     y = Ax + B
1044                  *         1    0       <-- coefficients array indices
1045                  */
1046                 float A = standardRange / (float)(len);
1047                 float B = (float)(-sfra) * A;
1048
1049                 gen->coefficients[1] = A;
1050                 gen->coefficients[0] = B;
1051         }
1052
1053         /* updates... */
1054         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
1055         return OPERATOR_FINISHED;
1056 }
1057
1058 static int followpath_path_animate_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1059 {
1060         /* hook up invoke properties for figuring out which constraint we're dealing with */
1061         if (edit_constraint_invoke_properties(C, op)) {
1062                 return followpath_path_animate_exec(C, op);
1063         }
1064         else {
1065                 return OPERATOR_CANCELLED;
1066         }
1067 }
1068
1069 void CONSTRAINT_OT_followpath_path_animate(wmOperatorType *ot)
1070 {
1071         /* identifiers */
1072         ot->name = "Auto Animate Path";
1073         ot->idname = "CONSTRAINT_OT_followpath_path_animate";
1074         ot->description = "Add default animation for path used by constraint if it isn't animated already";
1075
1076         /* callbacks */
1077         ot->invoke = followpath_path_animate_invoke;
1078         ot->exec = followpath_path_animate_exec;
1079         ot->poll = edit_constraint_poll;
1080
1081         /* flags */
1082         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1083
1084         /* props */
1085         edit_constraint_properties(ot);
1086         RNA_def_int(ot->srna, "frame_start", 1, MINAFRAME, MAXFRAME, "Start Frame",
1087                     "First frame of path animation", MINAFRAME, MAXFRAME);
1088         RNA_def_int(ot->srna, "length", 100, 0, MAXFRAME, "Length",
1089                     "Number of frames that path animation should take", 0, MAXFRAME);
1090 }
1091
1092 /* ------------- Object Solver Constraint ------------------ */
1093
1094 static int objectsolver_set_inverse_exec(bContext *C, wmOperator *op)
1095 {
1096         Scene *scene = CTX_data_scene(C);
1097         Object *ob = ED_object_active_context(C);
1098         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_OBJECTSOLVER);
1099         bObjectSolverConstraint *data = (con) ? (bObjectSolverConstraint *)con->data : NULL;
1100         const int owner = RNA_enum_get(op->ptr, "owner");
1101
1102         /* despite 3 layers of checks, we may still not be able to find a constraint */
1103         if (data == NULL) {
1104                 printf("DEBUG: Child-Of Set Inverse - object = '%s'\n", (ob) ? ob->id.name + 2 : "<None>");
1105                 BKE_report(op->reports, RPT_ERROR, "Could not find constraint data for Child-Of Set Inverse");
1106                 return OPERATOR_CANCELLED;
1107         }
1108
1109         child_get_inverse_matrix(C, scene, ob, con, data->invmat, owner);
1110
1111         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
1112
1113         return OPERATOR_FINISHED;
1114 }
1115
1116 static int objectsolver_set_inverse_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1117 {
1118         if (edit_constraint_invoke_properties(C, op))
1119                 return objectsolver_set_inverse_exec(C, op);
1120         else
1121                 return OPERATOR_CANCELLED;
1122 }
1123
1124 void CONSTRAINT_OT_objectsolver_set_inverse(wmOperatorType *ot)
1125 {
1126         /* identifiers */
1127         ot->name = "Set Inverse";
1128         ot->idname = "CONSTRAINT_OT_objectsolver_set_inverse";
1129         ot->description = "Set inverse correction for ObjectSolver constraint";
1130
1131         /* callbacks */
1132         ot->invoke = objectsolver_set_inverse_invoke;
1133         ot->exec = objectsolver_set_inverse_exec;
1134         ot->poll = edit_constraint_poll;
1135
1136         /* flags */
1137         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1138
1139         /* properties */
1140         edit_constraint_properties(ot);
1141 }
1142
1143 static int objectsolver_clear_inverse_exec(bContext *C, wmOperator *op)
1144 {
1145         Object *ob = ED_object_active_context(C);
1146         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_OBJECTSOLVER);
1147         bObjectSolverConstraint *data = (con) ? (bObjectSolverConstraint *)con->data : NULL;
1148
1149         if (data == NULL) {
1150                 BKE_report(op->reports, RPT_ERROR, "Child Of constraint not found");
1151                 return OPERATOR_CANCELLED;
1152         }
1153
1154         /* simply clear the matrix */
1155         unit_m4(data->invmat);
1156
1157         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
1158
1159         return OPERATOR_FINISHED;
1160 }
1161
1162 static int objectsolver_clear_inverse_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1163 {
1164         if (edit_constraint_invoke_properties(C, op))
1165                 return objectsolver_clear_inverse_exec(C, op);
1166         else
1167                 return OPERATOR_CANCELLED;
1168 }
1169
1170 void CONSTRAINT_OT_objectsolver_clear_inverse(wmOperatorType *ot)
1171 {
1172         /* identifiers */
1173         ot->name = "Clear Inverse";
1174         ot->idname = "CONSTRAINT_OT_objectsolver_clear_inverse";
1175         ot->description = "Clear inverse correction for ObjectSolver constraint";
1176
1177         /* callbacks */
1178         ot->invoke = objectsolver_clear_inverse_invoke;
1179         ot->exec = objectsolver_clear_inverse_exec;
1180         ot->poll = edit_constraint_poll;
1181
1182         /* flags */
1183         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1184
1185         /* properties */
1186         edit_constraint_properties(ot);
1187 }
1188
1189 /***************************** BUTTONS ****************************/
1190
1191 void ED_object_constraint_set_active(Object *ob, bConstraint *con)
1192 {
1193         ListBase *lb = get_constraint_lb(ob, con, NULL);
1194
1195         /* lets be nice and escape if its active already */
1196         /* NOTE: this assumes that the stack doesn't have other active ones set... */
1197         if ((lb && con) && (con->flag & CONSTRAINT_ACTIVE))
1198                 return;
1199
1200         BKE_constraints_active_set(lb, con);
1201 }
1202
1203 void ED_object_constraint_update(Main *bmain, Object *ob)
1204 {
1205         if (ob->pose) BKE_pose_update_constraint_flags(ob->pose);
1206
1207         object_test_constraints(bmain, ob);
1208
1209         if (ob->type == OB_ARMATURE)
1210                 DEG_id_tag_update(&ob->id, OB_RECALC_DATA | OB_RECALC_OB);
1211         else
1212                 DEG_id_tag_update(&ob->id, OB_RECALC_OB);
1213 }
1214
1215 static void object_pose_tag_update(Main *bmain, Object *ob)
1216 {
1217         BKE_pose_tag_recalc(bmain, ob->pose);    /* Checks & sort pose channels. */
1218         if (ob->proxy && ob->adt) {
1219                 /* We need to make use of ugly POSE_ANIMATION_WORKAROUND here too, else anim data are not reloaded
1220                  * after calling `BKE_pose_rebuild()`, which causes T43872.
1221                  * Note that this is a bit wide here, since we cannot be sure whether there are some locked proxy bones
1222                  * or not...
1223                  * XXX Temp hack until new depsgraph hopefully solves this. */
1224                 ob->adt->recalc |= ADT_RECALC_ANIM;
1225         }
1226 }
1227
1228 void ED_object_constraint_dependency_update(Main *bmain, Object *ob)
1229 {
1230         ED_object_constraint_update(bmain, ob);
1231
1232         if (ob->pose) {
1233                 object_pose_tag_update(bmain, ob);
1234         }
1235         DEG_relations_tag_update(bmain);
1236 }
1237
1238 void ED_object_constraint_tag_update(Main *bmain, Object *ob, bConstraint *con)
1239 {
1240         if (ob->pose) {
1241                 BKE_pose_tag_update_constraint_flags(ob->pose);
1242         }
1243
1244         object_test_constraint(bmain, ob, con);
1245
1246         if (ob->type == OB_ARMATURE)
1247                 DEG_id_tag_update(&ob->id, OB_RECALC_DATA | OB_RECALC_OB);
1248         else
1249                 DEG_id_tag_update(&ob->id, OB_RECALC_OB);
1250
1251         /* Do Copy-on-Write tag here too, otherwise constraint
1252          * influence/mute buttons in UI have no effect
1253          */
1254         DEG_id_tag_update(&ob->id, DEG_TAG_COPY_ON_WRITE);
1255 }
1256
1257 void ED_object_constraint_dependency_tag_update(Main *bmain, Object *ob, bConstraint *con)
1258 {
1259         ED_object_constraint_tag_update(bmain, ob, con);
1260
1261         if (ob->pose) {
1262                 object_pose_tag_update(bmain, ob);
1263         }
1264         DEG_relations_tag_update(bmain);
1265 }
1266
1267 static int constraint_poll(bContext *C)
1268 {
1269         PointerRNA ptr = CTX_data_pointer_get_type(C, "constraint", &RNA_Constraint);
1270         return (ptr.id.data && ptr.data);
1271 }
1272
1273
1274 static int constraint_delete_exec(bContext *C, wmOperator *UNUSED(op))
1275 {
1276         Main *bmain = CTX_data_main(C);
1277         PointerRNA ptr = CTX_data_pointer_get_type(C, "constraint", &RNA_Constraint);
1278         Object *ob = ptr.id.data;
1279         bConstraint *con = ptr.data;
1280         ListBase *lb = get_constraint_lb(ob, con, NULL);
1281
1282         /* free the constraint */
1283         if (BKE_constraint_remove_ex(lb, ob, con, true)) {
1284                 /* there's no active constraint now, so make sure this is the case */
1285                 BKE_constraints_active_set(&ob->constraints, NULL);
1286                 ED_object_constraint_update(bmain, ob); /* needed to set the flags on posebones correctly */
1287
1288                 /* relatiols */
1289                 DEG_relations_tag_update(CTX_data_main(C));
1290
1291                 /* notifiers */
1292                 WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT | NA_REMOVED, ob);
1293
1294                 return OPERATOR_FINISHED;
1295         }
1296         else {
1297                 /* couldn't remove due to some invalid data */
1298                 return OPERATOR_CANCELLED;
1299         }
1300 }
1301
1302 void CONSTRAINT_OT_delete(wmOperatorType *ot)
1303 {
1304         /* identifiers */
1305         ot->name = "Delete Constraint";
1306         ot->idname = "CONSTRAINT_OT_delete";
1307         ot->description = "Remove constraint from constraint stack";
1308
1309         /* callbacks */
1310         ot->exec = constraint_delete_exec;
1311         ot->poll = constraint_poll;
1312
1313         /* flags */
1314         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1315 }
1316
1317
1318 static int constraint_move_down_exec(bContext *C, wmOperator *op)
1319 {
1320         Object *ob = ED_object_active_context(C);
1321         bConstraint *con = edit_constraint_property_get(op, ob, 0);
1322
1323         if (con && con->next) {
1324                 ListBase *conlist = get_constraint_lb(ob, con, NULL);
1325                 bConstraint *nextCon = con->next;
1326
1327                 /* insert the nominated constraint after the one that used to be after it */
1328                 BLI_remlink(conlist, con);
1329                 BLI_insertlinkafter(conlist, nextCon, con);
1330
1331                 WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
1332
1333                 return OPERATOR_FINISHED;
1334         }
1335
1336         return OPERATOR_CANCELLED;
1337 }
1338
1339 static int constraint_move_down_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1340 {
1341         if (edit_constraint_invoke_properties(C, op))
1342                 return constraint_move_down_exec(C, op);
1343         else
1344                 return OPERATOR_CANCELLED;
1345 }
1346
1347 void CONSTRAINT_OT_move_down(wmOperatorType *ot)
1348 {
1349         /* identifiers */
1350         ot->name = "Move Constraint Down";
1351         ot->idname = "CONSTRAINT_OT_move_down";
1352         ot->description = "Move constraint down in constraint stack";
1353
1354         /* callbacks */
1355         ot->invoke = constraint_move_down_invoke;
1356         ot->exec = constraint_move_down_exec;
1357         ot->poll = edit_constraint_poll;
1358
1359         /* flags */
1360         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1361
1362         /* properties */
1363         edit_constraint_properties(ot);
1364 }
1365
1366
1367 static int constraint_move_up_exec(bContext *C, wmOperator *op)
1368 {
1369         Object *ob = ED_object_active_context(C);
1370         bConstraint *con = edit_constraint_property_get(op, ob, 0);
1371
1372         if (con && con->prev) {
1373                 ListBase *conlist = get_constraint_lb(ob, con, NULL);
1374                 bConstraint *prevCon = con->prev;
1375
1376                 /* insert the nominated constraint before the one that used to be before it */
1377                 BLI_remlink(conlist, con);
1378                 BLI_insertlinkbefore(conlist, prevCon, con);
1379
1380                 WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
1381
1382                 return OPERATOR_FINISHED;
1383         }
1384
1385         return OPERATOR_CANCELLED;
1386 }
1387
1388 static int constraint_move_up_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1389 {
1390         if (edit_constraint_invoke_properties(C, op))
1391                 return constraint_move_up_exec(C, op);
1392         else
1393                 return OPERATOR_CANCELLED;
1394 }
1395
1396 void CONSTRAINT_OT_move_up(wmOperatorType *ot)
1397 {
1398         /* identifiers */
1399         ot->name = "Move Constraint Up";
1400         ot->idname = "CONSTRAINT_OT_move_up";
1401         ot->description = "Move constraint up in constraint stack";
1402
1403         /* callbacks */
1404         ot->exec = constraint_move_up_exec;
1405         ot->invoke = constraint_move_up_invoke;
1406         ot->poll = edit_constraint_poll;
1407
1408         /* flags */
1409         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1410         edit_constraint_properties(ot);
1411 }
1412
1413 /***************************** OPERATORS ****************************/
1414
1415 /************************ remove constraint operators *********************/
1416
1417 static int pose_constraints_clear_exec(bContext *C, wmOperator *UNUSED(op))
1418 {
1419         Main *bmain = CTX_data_main(C);
1420         Object *ob = BKE_object_pose_armature_get(CTX_data_active_object(C));
1421
1422         /* free constraints for all selected bones */
1423         CTX_DATA_BEGIN (C, bPoseChannel *, pchan, selected_pose_bones)
1424         {
1425                 BKE_constraints_free(&pchan->constraints);
1426                 pchan->constflag &= ~(PCHAN_HAS_IK | PCHAN_HAS_SPLINEIK | PCHAN_HAS_CONST);
1427         }
1428         CTX_DATA_END;
1429
1430         /* force depsgraph to get recalculated since relationships removed */
1431         DEG_relations_tag_update(bmain);
1432
1433         /* note, calling BIK_clear_data() isn't needed here */
1434
1435         /* do updates */
1436         DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
1437         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT | NA_REMOVED, ob);
1438
1439         return OPERATOR_FINISHED;
1440 }
1441
1442 void POSE_OT_constraints_clear(wmOperatorType *ot)
1443 {
1444         /* identifiers */
1445         ot->name = "Clear Pose Constraints";
1446         ot->idname = "POSE_OT_constraints_clear";
1447         ot->description = "Clear all the constraints for the selected bones";
1448
1449         /* callbacks */
1450         ot->exec = pose_constraints_clear_exec;
1451         ot->poll = ED_operator_posemode_exclusive; // XXX - do we want to ensure there are selected bones too?
1452 }
1453
1454
1455 static int object_constraints_clear_exec(bContext *C, wmOperator *UNUSED(op))
1456 {
1457         Main *bmain = CTX_data_main(C);
1458
1459         /* do freeing */
1460         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1461         {
1462                 BKE_constraints_free(&ob->constraints);
1463                 DEG_id_tag_update(&ob->id, OB_RECALC_OB);
1464         }
1465         CTX_DATA_END;
1466
1467         /* force depsgraph to get recalculated since relationships removed */
1468         DEG_relations_tag_update(bmain);
1469
1470         /* do updates */
1471         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT | NA_REMOVED, NULL);
1472
1473         return OPERATOR_FINISHED;
1474 }
1475
1476 void OBJECT_OT_constraints_clear(wmOperatorType *ot)
1477 {
1478         /* identifiers */
1479         ot->name = "Clear Object Constraints";
1480         ot->idname = "OBJECT_OT_constraints_clear";
1481         ot->description = "Clear all the constraints for the active Object only";
1482
1483         /* callbacks */
1484         ot->exec = object_constraints_clear_exec;
1485         ot->poll = ED_operator_object_active_editable;
1486 }
1487
1488 /************************ copy all constraints operators *********************/
1489
1490 static int pose_constraint_copy_exec(bContext *C, wmOperator *op)
1491 {
1492         Main *bmain = CTX_data_main(C);
1493         bPoseChannel *pchan = CTX_data_active_pose_bone(C);
1494         ListBase lb;
1495         CollectionPointerLink *link;
1496
1497         /* don't do anything if bone doesn't exist or doesn't have any constraints */
1498         if (ELEM(NULL, pchan, pchan->constraints.first)) {
1499                 BKE_report(op->reports, RPT_ERROR, "No active bone with constraints for copying");
1500                 return OPERATOR_CANCELLED;
1501         }
1502
1503         /* copy all constraints from active posebone to all selected posebones */
1504         CTX_data_selected_pose_bones(C, &lb);
1505         for (link = lb.first; link; link = link->next) {
1506                 Object *ob = link->ptr.id.data;
1507                 bPoseChannel *chan = link->ptr.data;
1508
1509                 /* if we're not handling the object we're copying from, copy all constraints over */
1510                 if (pchan != chan) {
1511                         BKE_constraints_copy(&chan->constraints, &pchan->constraints, true);
1512                         /* update flags (need to add here, not just copy) */
1513                         chan->constflag |= pchan->constflag;
1514
1515                         BKE_pose_tag_recalc(bmain, ob->pose);
1516                         DEG_id_tag_update((ID *)ob, OB_RECALC_DATA);
1517                 }
1518         }
1519         BLI_freelistN(&lb);
1520
1521         /* force depsgraph to get recalculated since new relationships added */
1522         DEG_relations_tag_update(bmain);
1523
1524         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, NULL);
1525
1526         return OPERATOR_FINISHED;
1527 }
1528
1529 void POSE_OT_constraints_copy(wmOperatorType *ot)
1530 {
1531         /* identifiers */
1532         ot->name = "Copy Constraints to Selected Bones";
1533         ot->idname = "POSE_OT_constraints_copy";
1534         ot->description = "Copy constraints to other selected bones";
1535
1536         /* api callbacks */
1537         ot->exec = pose_constraint_copy_exec;
1538         ot->poll = ED_operator_posemode_exclusive;
1539
1540         /* flags */
1541         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1542 }
1543
1544 static int object_constraint_copy_exec(bContext *C, wmOperator *UNUSED(op))
1545 {
1546         Main *bmain = CTX_data_main(C);
1547         Object *obact = ED_object_active_context(C);
1548
1549         /* copy all constraints from active object to all selected objects */
1550         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1551         {
1552                 /* if we're not handling the object we're copying from, copy all constraints over */
1553                 if (obact != ob) {
1554                         BKE_constraints_copy(&ob->constraints, &obact->constraints, true);
1555                         DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
1556                 }
1557         }
1558         CTX_DATA_END;
1559
1560         /* force depsgraph to get recalculated since new relationships added */
1561         DEG_relations_tag_update(bmain);
1562
1563         /* notifiers for updates */
1564         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT | NA_ADDED, NULL);
1565
1566         return OPERATOR_FINISHED;
1567 }
1568
1569 void OBJECT_OT_constraints_copy(wmOperatorType *ot)
1570 {
1571         /* identifiers */
1572         ot->name = "Copy Constraints to Selected Objects";
1573         ot->idname = "OBJECT_OT_constraints_copy";
1574         ot->description = "Copy constraints to other selected objects";
1575
1576         /* api callbacks */
1577         ot->exec = object_constraint_copy_exec;
1578         ot->poll = ED_operator_object_active_editable;
1579
1580         /* flags */
1581         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1582 }
1583
1584 /************************ add constraint operators *********************/
1585
1586 /* get the Object and/or PoseChannel to use as target */
1587 static bool get_new_constraint_target(bContext *C, int con_type, Object **tar_ob, bPoseChannel **tar_pchan, bool add)
1588 {
1589         Object *obact = ED_object_active_context(C);
1590         bPoseChannel *pchanact = BKE_pose_channel_active(obact);
1591         bool only_curve = false, only_mesh = false, only_ob = false;
1592         bool found = false;
1593
1594         /* clear tar_ob and tar_pchan fields before use
1595          *      - assume for now that both always exist...
1596          */
1597         *tar_ob = NULL;
1598         *tar_pchan = NULL;
1599
1600         /* check if constraint type doesn't requires a target
1601          *      - if so, no need to get any targets
1602          */
1603         switch (con_type) {
1604                 /* no-target constraints --------------------------- */
1605                 /* null constraint - shouldn't even be added! */
1606                 case CONSTRAINT_TYPE_NULL:
1607                 /* limit constraints - no targets needed */
1608                 case CONSTRAINT_TYPE_LOCLIMIT:
1609                 case CONSTRAINT_TYPE_ROTLIMIT:
1610                 case CONSTRAINT_TYPE_SIZELIMIT:
1611                 case CONSTRAINT_TYPE_SAMEVOL:
1612                         return false;
1613
1614                 /* restricted target-type constraints -------------- */
1615                 /* NOTE: for these, we cannot try to add a target object if no valid ones are found, since that doesn't work */
1616                 /* curve-based constraints - set the only_curve and only_ob flags */
1617                 case CONSTRAINT_TYPE_CLAMPTO:
1618                 case CONSTRAINT_TYPE_FOLLOWPATH:
1619                 case CONSTRAINT_TYPE_SPLINEIK:
1620                         only_curve = true;
1621                         only_ob = true;
1622                         add = false;
1623                         break;
1624
1625                 /* mesh only? */
1626                 case CONSTRAINT_TYPE_SHRINKWRAP:
1627                         only_mesh = true;
1628                         only_ob = true;
1629                         add = false;
1630                         break;
1631         }
1632
1633         /* if the active Object is Armature, and we can search for bones, do so... */
1634         if ((obact->type == OB_ARMATURE) && (only_ob == false)) {
1635                 /* search in list of selected Pose-Channels for target */
1636                 CTX_DATA_BEGIN (C, bPoseChannel *, pchan, selected_pose_bones)
1637                 {
1638                         /* just use the first one that we encounter, as long as it is not the active one */
1639                         if (pchan != pchanact) {
1640                                 *tar_ob = obact;
1641                                 *tar_pchan = pchan;
1642                                 found = true;
1643
1644                                 break;
1645                         }
1646                 }
1647                 CTX_DATA_END;
1648         }
1649
1650         /* if not yet found, try selected Objects... */
1651         if (found == false) {
1652                 /* search in selected objects context */
1653                 CTX_DATA_BEGIN (C, Object *, ob, selected_objects)
1654                 {
1655                         /* just use the first object we encounter (that isn't the active object)
1656                          * and which fulfills the criteria for the object-target that we've got
1657                          */
1658                         if (ob != obact) {
1659                                 /* for armatures in pose mode, look inside the armature for the active bone
1660                                  * so that we set up cross-armature constraints with less effort
1661                                  */
1662                                 if ((ob->type == OB_ARMATURE) && (ob->mode & OB_MODE_POSE) &&
1663                                     (!only_curve && !only_mesh))
1664                                 {
1665                                         /* just use the active bone, and assume that it is visible + usable */
1666                                         *tar_ob = ob;
1667                                         *tar_pchan = BKE_pose_channel_active(ob);
1668                                         found = true;
1669
1670                                         break;
1671                                 }
1672                                 else if (((!only_curve) || (ob->type == OB_CURVE)) &&
1673                                          ((!only_mesh) || (ob->type == OB_MESH)))
1674                                 {
1675                                         /* set target */
1676                                         *tar_ob = ob;
1677                                         found = true;
1678
1679                                         /* perform some special operations on the target */
1680                                         if (only_curve) {
1681                                                 /* Curve-Path option must be enabled for follow-path constraints to be able to work */
1682                                                 Curve *cu = (Curve *)ob->data;
1683                                                 cu->flag |= CU_PATH;
1684                                         }
1685
1686                                         break;
1687                                 }
1688                         }
1689                 }
1690                 CTX_DATA_END;
1691         }
1692
1693         /* if still not found, add a new empty to act as a target (if allowed) */
1694         if ((found == false) && (add)) {
1695                 Main *bmain = CTX_data_main(C);
1696                 Scene *scene = CTX_data_scene(C);
1697                 ViewLayer *view_layer = CTX_data_view_layer(C);
1698                 Base *base = BASACT(view_layer), *newbase = NULL;
1699                 Object *obt;
1700
1701                 /* add new target object */
1702                 obt = BKE_object_add(bmain, scene, view_layer, OB_EMPTY, NULL);
1703
1704                 /* set layers OK */
1705                 newbase = BASACT(view_layer);
1706                 newbase->lay = base->lay;
1707                 obt->lay = newbase->lay;
1708
1709                 /* transform cent to global coords for loc */
1710                 if (pchanact) {
1711                         /* since by default, IK targets the tip of the last bone, use the tip of the active PoseChannel
1712                          * if adding a target for an IK Constraint
1713                          */
1714                         if (con_type == CONSTRAINT_TYPE_KINEMATIC)
1715                                 mul_v3_m4v3(obt->loc, obact->obmat, pchanact->pose_tail);
1716                         else
1717                                 mul_v3_m4v3(obt->loc, obact->obmat, pchanact->pose_head);
1718                 }
1719                 else {
1720                         copy_v3_v3(obt->loc, obact->obmat[3]);
1721                 }
1722
1723                 /* restore, BKE_object_add sets active */
1724                 BASACT(view_layer) = base;
1725                 base->flag |= BASE_SELECTED;
1726
1727                 /* make our new target the new object */
1728                 *tar_ob = obt;
1729                 found = true;
1730         }
1731
1732         /* return whether there's any target */
1733         return found;
1734 }
1735
1736 /* used by add constraint operators to add the constraint required */
1737 static int constraint_add_exec(bContext *C, wmOperator *op, Object *ob, ListBase *list, int type, const bool setTarget)
1738 {
1739         Main *bmain = CTX_data_main(C);
1740         bPoseChannel *pchan;
1741         bConstraint *con;
1742
1743         if (list == &ob->constraints) {
1744                 pchan = NULL;
1745         }
1746         else {
1747                 pchan = BKE_pose_channel_active(ob);
1748
1749                 /* ensure not to confuse object/pose adding */
1750                 if (pchan == NULL) {
1751                         BKE_report(op->reports, RPT_ERROR, "No active pose bone to add a constraint to");
1752                         return OPERATOR_CANCELLED;
1753                 }
1754         }
1755         /* check if constraint to be added is valid for the given constraints stack */
1756         if (type == CONSTRAINT_TYPE_NULL) {
1757                 return OPERATOR_CANCELLED;
1758         }
1759         if ((type == CONSTRAINT_TYPE_KINEMATIC) && ((!pchan) || (list != &pchan->constraints))) {
1760                 BKE_report(op->reports, RPT_ERROR, "IK constraint can only be added to bones");
1761                 return OPERATOR_CANCELLED;
1762         }
1763         if ((type == CONSTRAINT_TYPE_SPLINEIK) && ((!pchan) || (list != &pchan->constraints))) {
1764                 BKE_report(op->reports, RPT_ERROR, "Spline IK constraint can only be added to bones");
1765                 return OPERATOR_CANCELLED;
1766         }
1767
1768         /* create a new constraint of the type requried, and add it to the active/given constraints list */
1769         if (pchan)
1770                 con = BKE_constraint_add_for_pose(ob, pchan, NULL, type);
1771         else
1772                 con = BKE_constraint_add_for_object(ob, NULL, type);
1773
1774         /* get the first selected object/bone, and make that the target
1775          *      - apart from the buttons-window add buttons, we shouldn't add in this way
1776          */
1777         if (setTarget) {
1778                 Object *tar_ob = NULL;
1779                 bPoseChannel *tar_pchan = NULL;
1780
1781                 /* get the target objects, adding them as need be */
1782                 if (get_new_constraint_target(C, type, &tar_ob, &tar_pchan, 1)) {
1783                         /* method of setting target depends on the type of target we've got
1784                          *      - by default, just set the first target (distinction here is only for multiple-targeted constraints)
1785                          */
1786                         if (tar_pchan)
1787                                 set_constraint_nth_target(con, tar_ob, tar_pchan->name, 0);
1788                         else
1789                                 set_constraint_nth_target(con, tar_ob, "", 0);
1790                 }
1791         }
1792
1793         /* do type-specific tweaking to the constraint settings  */
1794         switch (type) {
1795                 case CONSTRAINT_TYPE_PYTHON: /* FIXME: this code is not really valid anymore */
1796                 {
1797 #ifdef WITH_PYTHON
1798                         char *menustr;
1799                         int scriptint = 0;
1800                         /* popup a list of usable scripts */
1801                         menustr = buildmenu_pyconstraints(NULL, &scriptint);
1802                         /* XXX scriptint = pupmenu(menustr); */
1803                         MEM_freeN(menustr);
1804
1805                         /* only add constraint if a script was chosen */
1806                         if (scriptint) {
1807                                 /* add constraint */
1808                                 validate_pyconstraint_cb(con->data, &scriptint);
1809
1810                                 /* make sure target allowance is set correctly */
1811                                 BPY_pyconstraint_update(ob, con);
1812                         }
1813 #endif
1814                         break;
1815                 }
1816
1817                 default:
1818                         break;
1819         }
1820
1821         /* make sure all settings are valid - similar to above checks, but sometimes can be wrong */
1822         object_test_constraints(bmain, ob);
1823
1824         if (pchan)
1825                 BKE_pose_update_constraint_flags(ob->pose);
1826
1827
1828         /* force depsgraph to get recalculated since new relationships added */
1829         DEG_relations_tag_update(bmain);
1830
1831         if ((ob->type == OB_ARMATURE) && (pchan)) {
1832                 BKE_pose_tag_recalc(bmain, ob->pose);  /* sort pose channels */
1833                 if (BKE_constraints_proxylocked_owner(ob, pchan) && ob->adt) {
1834                         /* We need to make use of ugly POSE_ANIMATION_WORKAROUND here too, else anim data are not reloaded
1835                          * after calling `BKE_pose_rebuild()`, which causes T43872.
1836                          * XXX Temp hack until new depsgraph hopefully solves this. */
1837                         ob->adt->recalc |= ADT_RECALC_ANIM;
1838                 }
1839                 DEG_id_tag_update(&ob->id, OB_RECALC_DATA | OB_RECALC_OB);
1840         }
1841         else
1842                 DEG_id_tag_update(&ob->id, OB_RECALC_OB);
1843
1844         /* notifiers for updates */
1845         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT | NA_ADDED, ob);
1846
1847         return OPERATOR_FINISHED;
1848 }
1849
1850 /* ------------------ */
1851
1852 /* dummy operator callback */
1853 static int object_constraint_add_exec(bContext *C, wmOperator *op)
1854 {
1855         Object *ob = ED_object_active_context(C);
1856         int type = RNA_enum_get(op->ptr, "type");
1857         short with_targets = 0;
1858
1859         if (!ob) {
1860                 BKE_report(op->reports, RPT_ERROR, "No active object to add constraint to");
1861                 return OPERATOR_CANCELLED;
1862         }
1863
1864         /* hack: set constraint targets from selected objects in context is allowed when
1865          *              operator name included 'with_targets', since the menu doesn't allow multiple properties
1866          */
1867         if (strstr(op->idname, "with_targets"))
1868                 with_targets = 1;
1869
1870         return constraint_add_exec(C, op, ob, &ob->constraints, type, with_targets);
1871 }
1872
1873 /* dummy operator callback */
1874 static int pose_constraint_add_exec(bContext *C, wmOperator *op)
1875 {
1876         Object *ob = BKE_object_pose_armature_get(ED_object_active_context(C));
1877         int type = RNA_enum_get(op->ptr, "type");
1878         short with_targets = 0;
1879
1880         if (!ob) {
1881                 BKE_report(op->reports, RPT_ERROR, "No active object to add constraint to");
1882                 return OPERATOR_CANCELLED;
1883         }
1884
1885         /* hack: set constraint targets from selected objects in context is allowed when
1886          *              operator name included 'with_targets', since the menu doesn't allow multiple properties
1887          */
1888         if (strstr(op->idname, "with_targets"))
1889                 with_targets = 1;
1890
1891         return constraint_add_exec(C, op, ob, get_active_constraints(ob), type, with_targets);
1892 }
1893
1894 /* ------------------ */
1895
1896 void OBJECT_OT_constraint_add(wmOperatorType *ot)
1897 {
1898         /* identifiers */
1899         ot->name = "Add Constraint";
1900         ot->description = "Add a constraint to the active object";
1901         ot->idname = "OBJECT_OT_constraint_add";
1902
1903         /* api callbacks */
1904         ot->invoke = WM_menu_invoke;
1905         ot->exec = object_constraint_add_exec;
1906         ot->poll = ED_operator_object_active_editable;
1907
1908         /* flags */
1909         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1910
1911         /* properties */
1912         ot->prop = RNA_def_enum(ot->srna, "type", rna_enum_constraint_type_items, 0, "Type", "");
1913 }
1914
1915 void OBJECT_OT_constraint_add_with_targets(wmOperatorType *ot)
1916 {
1917         /* identifiers */
1918         ot->name = "Add Constraint (with Targets)";
1919         ot->description = "Add a constraint to the active object, with target (where applicable) set to the selected Objects/Bones";
1920         ot->idname = "OBJECT_OT_constraint_add_with_targets";
1921
1922         /* api callbacks */
1923         ot->invoke = WM_menu_invoke;
1924         ot->exec = object_constraint_add_exec;
1925         ot->poll = ED_operator_object_active_editable;
1926
1927         /* flags */
1928         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1929
1930         /* properties */
1931         ot->prop = RNA_def_enum(ot->srna, "type", rna_enum_constraint_type_items, 0, "Type", "");
1932 }
1933
1934 void POSE_OT_constraint_add(wmOperatorType *ot)
1935 {
1936         /* identifiers */
1937         ot->name = "Add Constraint";
1938         ot->description = "Add a constraint to the active bone";
1939         ot->idname = "POSE_OT_constraint_add";
1940
1941         /* api callbacks */
1942         ot->invoke = WM_menu_invoke;
1943         ot->exec = pose_constraint_add_exec;
1944         ot->poll = ED_operator_posemode_exclusive;
1945
1946         /* flags */
1947         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1948
1949         /* properties */
1950         ot->prop = RNA_def_enum(ot->srna, "type", rna_enum_constraint_type_items, 0, "Type", "");
1951 }
1952
1953 void POSE_OT_constraint_add_with_targets(wmOperatorType *ot)
1954 {
1955         /* identifiers */
1956         ot->name = "Add Constraint (with Targets)";
1957         ot->description = "Add a constraint to the active bone, with target (where applicable) set to the selected Objects/Bones";
1958         ot->idname = "POSE_OT_constraint_add_with_targets";
1959
1960         /* api callbacks */
1961         ot->invoke = WM_menu_invoke;
1962         ot->exec = pose_constraint_add_exec;
1963         ot->poll = ED_operator_posemode_exclusive;
1964
1965         /* flags */
1966         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1967
1968         /* properties */
1969         ot->prop = RNA_def_enum(ot->srna, "type", rna_enum_constraint_type_items, 0, "Type", "");
1970 }
1971
1972 /************************ IK Constraint operators *********************/
1973 /* NOTE: only for Pose-Channels */
1974 // TODO: should these be here, or back in editors/armature/poseobject.c again?
1975
1976 /* present menu with options + validation for targets to use */
1977 static int pose_ik_add_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1978 {
1979         Object *ob = BKE_object_pose_armature_get(CTX_data_active_object(C));
1980         bPoseChannel *pchan = BKE_pose_channel_active(ob);
1981         bConstraint *con = NULL;
1982
1983         uiPopupMenu *pup;
1984         uiLayout *layout;
1985         Object *tar_ob = NULL;
1986         bPoseChannel *tar_pchan = NULL;
1987
1988         /* must have active bone */
1989         if (ELEM(NULL, ob, pchan)) {
1990                 BKE_report(op->reports, RPT_ERROR, "Must have an active bone to add IK constraint to");
1991                 return OPERATOR_CANCELLED;
1992         }
1993
1994         /* bone must not have any constraints already */
1995         for (con = pchan->constraints.first; con; con = con->next) {
1996                 if (con->type == CONSTRAINT_TYPE_KINEMATIC) break;
1997         }
1998         if (con) {
1999                 BKE_report(op->reports, RPT_ERROR, "Bone already has an IK constraint");
2000                 return OPERATOR_CANCELLED;
2001         }
2002
2003         /* prepare popup menu to choose targetting options */
2004         pup = UI_popup_menu_begin(C, IFACE_("Add IK"), ICON_NONE);
2005         layout = UI_popup_menu_layout(pup);
2006
2007         /* the type of targets we'll set determines the menu entries to show... */
2008         if (get_new_constraint_target(C, CONSTRAINT_TYPE_KINEMATIC, &tar_ob, &tar_pchan, 0)) {
2009                 /* bone target, or object target?
2010                  *      - the only thing that matters is that we want a target...
2011                  */
2012                 if (tar_pchan)
2013                         uiItemBooleanO(layout, IFACE_("To Active Bone"), ICON_NONE, "POSE_OT_ik_add", "with_targets", 1);
2014                 else
2015                         uiItemBooleanO(layout, IFACE_("To Active Object"), ICON_NONE, "POSE_OT_ik_add", "with_targets", 1);
2016         }
2017         else {
2018                 /* we have a choice of adding to a new empty, or not setting any target (targetless IK) */
2019                 uiItemBooleanO(layout, IFACE_("To New Empty Object"), ICON_NONE, "POSE_OT_ik_add", "with_targets", 1);
2020                 uiItemBooleanO(layout, IFACE_("Without Targets"), ICON_NONE, "POSE_OT_ik_add", "with_targets", 0);
2021         }
2022
2023         /* finish building the menu, and process it (should result in calling self again) */
2024         UI_popup_menu_end(C, pup);
2025
2026         return OPERATOR_INTERFACE;
2027 }
2028
2029 /* call constraint_add_exec() to add the IK constraint */
2030 static int pose_ik_add_exec(bContext *C, wmOperator *op)
2031 {
2032         Object *ob = CTX_data_active_object(C);
2033         const bool with_targets = RNA_boolean_get(op->ptr, "with_targets");
2034
2035         /* add the constraint - all necessary checks should have been done by the invoke() callback already... */
2036         return constraint_add_exec(C, op, ob, get_active_constraints(ob), CONSTRAINT_TYPE_KINEMATIC, with_targets);
2037 }
2038
2039 void POSE_OT_ik_add(wmOperatorType *ot)
2040 {
2041         /* identifiers */
2042         ot->name = "Add IK to Bone";
2043         ot->description = "Add IK Constraint to the active Bone";
2044         ot->idname = "POSE_OT_ik_add";
2045
2046         /* api callbacks */
2047         ot->invoke = pose_ik_add_invoke;
2048         ot->exec = pose_ik_add_exec;
2049         ot->poll = ED_operator_posemode_exclusive;
2050
2051         /* flags */
2052         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2053
2054         /* properties */
2055         RNA_def_boolean(ot->srna, "with_targets", 1, "With Targets", "Assign IK Constraint with targets derived from the select bones/objects");
2056 }
2057
2058 /* ------------------ */
2059
2060 /* remove IK constraints from selected bones */
2061 static int pose_ik_clear_exec(bContext *C, wmOperator *UNUSED(op))
2062 {
2063         Object *ob = BKE_object_pose_armature_get(CTX_data_active_object(C));
2064
2065         /* only remove IK Constraints */
2066         CTX_DATA_BEGIN (C, bPoseChannel *, pchan, selected_pose_bones)
2067         {
2068                 bConstraint *con, *next;
2069
2070                 /* TODO: should we be checking if these contraints were local before we try and remove them? */
2071                 for (con = pchan->constraints.first; con; con = next) {
2072                         next = con->next;
2073                         if (con->type == CONSTRAINT_TYPE_KINEMATIC) {
2074                                 BKE_constraint_remove(&pchan->constraints, con);
2075                         }
2076                 }
2077                 pchan->constflag &= ~(PCHAN_HAS_IK | PCHAN_HAS_TARGET);
2078         }
2079         CTX_DATA_END;
2080
2081         /* refresh depsgraph */
2082         DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
2083
2084         /* note, notifier might evolve */
2085         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT | NA_REMOVED, ob);
2086
2087         return OPERATOR_FINISHED;
2088 }
2089
2090 void POSE_OT_ik_clear(wmOperatorType *ot)
2091 {
2092         /* identifiers */
2093         ot->name = "Remove IK";
2094         ot->description = "Remove all IK Constraints from selected bones";
2095         ot->idname = "POSE_OT_ik_clear";
2096
2097         /* api callbacks */
2098         ot->exec = pose_ik_clear_exec;
2099         ot->poll = ED_operator_posemode_exclusive;
2100
2101         /* flags */
2102         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2103 }
2104