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