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