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