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