And more UI messages spell check.
[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 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 = 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 = 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 = 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])
722 {
723         bConstraint *lastcon = NULL;
724         bPoseChannel *pchan = NULL;
725         
726         /* nullify inverse matrix first */
727         unit_m4(invmat);
728         
729         /* try to find a pose channel - assume that this is the constraint owner */
730         /* TODO: get from context instead? */
731         if (ob && ob->pose)
732                 pchan = BKE_pose_channel_active(ob);
733         
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         if (pchan) {
741                 float imat[4][4], tmat[4][4];
742                 float pmat[4][4];
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                 lastcon = 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 = lastcon;
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         else if (ob) {
791                 Object workob;
792                 
793                 /* use BKE_object_workob_calc_parent to find inverse - just like for normal parenting */
794                 BKE_object_workob_calc_parent(scene, ob, &workob);
795                 invert_m4_m4(invmat, workob.obmat);
796         }
797 }
798
799 /* ChildOf Constraint - set inverse callback */
800 static int childof_set_inverse_exec(bContext *C, wmOperator *op)
801 {
802         Scene *scene = CTX_data_scene(C);
803         Object *ob = ED_object_active_context(C);
804         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_CHILDOF);
805         bChildOfConstraint *data = (con) ? (bChildOfConstraint *)con->data : NULL;
806
807         /* despite 3 layers of checks, we may still not be able to find a constraint */
808         if (data == NULL) {
809                 printf("DEBUG: Child-Of Set Inverse - object = '%s'\n", (ob) ? ob->id.name + 2 : "<None>");
810                 BKE_report(op->reports, RPT_ERROR, "Couldn't find constraint data for Child-Of Set Inverse");
811                 return OPERATOR_CANCELLED;
812         }
813         
814         child_get_inverse_matrix(scene, ob, con, data->invmat);
815
816         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
817         
818         return OPERATOR_FINISHED;
819 }
820
821 static int childof_set_inverse_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
822 {
823         if (edit_constraint_invoke_properties(C, op))
824                 return childof_set_inverse_exec(C, op);
825         else
826                 return OPERATOR_CANCELLED;
827 }
828
829 void CONSTRAINT_OT_childof_set_inverse(wmOperatorType *ot)
830 {
831         /* identifiers */
832         ot->name = "Set Inverse";
833         ot->idname = "CONSTRAINT_OT_childof_set_inverse";
834         ot->description = "Set inverse correction for ChildOf constraint";
835         
836         /* callbacks */
837         ot->invoke = childof_set_inverse_invoke;
838         ot->exec = childof_set_inverse_exec;
839         ot->poll = edit_constraint_poll;
840         
841         /* flags */
842         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
843         
844         /* properties */
845         edit_constraint_properties(ot);
846 }
847
848 /* ChildOf Constraint - clear inverse callback */
849 static int childof_clear_inverse_exec(bContext *C, wmOperator *op)
850 {
851         Object *ob = ED_object_active_context(C);
852         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_CHILDOF);
853         bChildOfConstraint *data = (con) ? (bChildOfConstraint *)con->data : NULL;
854         
855         if (data == NULL) {
856                 BKE_report(op->reports, RPT_ERROR, "Child Of constraint not found");
857                 return OPERATOR_CANCELLED;
858         }
859         
860         /* simply clear the matrix */
861         unit_m4(data->invmat);
862         
863         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
864         
865         return OPERATOR_FINISHED;
866 }
867
868 static int childof_clear_inverse_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
869 {
870         if (edit_constraint_invoke_properties(C, op))
871                 return childof_clear_inverse_exec(C, op);
872         else
873                 return OPERATOR_CANCELLED;
874 }
875
876 void CONSTRAINT_OT_childof_clear_inverse(wmOperatorType *ot)
877 {
878         /* identifiers */
879         ot->name = "Clear Inverse";
880         ot->idname = "CONSTRAINT_OT_childof_clear_inverse";
881         ot->description = "Clear inverse correction for ChildOf constraint";
882         
883         /* callbacks */
884         ot->invoke = childof_clear_inverse_invoke;
885         ot->exec = childof_clear_inverse_exec;
886         ot->poll = edit_constraint_poll;
887         
888         /* flags */
889         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
890         
891         /* properties */
892         edit_constraint_properties(ot);
893 }
894
895 /* --------------- Follow Path Constraint ------------------ */
896
897 static int followpath_path_animate_exec(bContext *C, wmOperator *op)
898 {
899         Object *ob = ED_object_active_context(C);
900         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_FOLLOWPATH);
901         bFollowPathConstraint *data = (con) ? (bFollowPathConstraint *)con->data : NULL;
902         
903         bAction *act = NULL;
904         FCurve *fcu = NULL;
905         int sfra = RNA_int_get(op->ptr, "frame_start");
906         int len  = RNA_int_get(op->ptr, "length");
907         float standardRange = 1.0;
908         
909         /* nearly impossible sanity check */
910         if (data == NULL) {
911                 BKE_report(op->reports, RPT_ERROR, "Follow Path constraint not found");
912                 return OPERATOR_CANCELLED;
913         }
914         
915         /* add F-Curve as appropriate */
916         if (data->tar) {
917                 Curve *cu = (Curve *)data->tar->data;
918                 
919                 if ( ELEM(NULL, cu->adt, cu->adt->action) ||
920                         (list_find_fcurve(&cu->adt->action->curves, "eval_time", 0) == NULL))
921                 {
922                         /* create F-Curve for path animation */
923                         act = verify_adt_action(&cu->id, 1);
924                         fcu = verify_fcurve(act, NULL, NULL, "eval_time", 0, 1);
925                         
926                         /* standard vertical range - 1:1 = 100 frames */
927                         standardRange = 100.0f;
928                 }
929                 else {
930                         /* path anim exists already - abort for now as this may well be what was intended */
931                         BKE_report(op->reports, RPT_WARNING, "Path is already animated");
932                         return OPERATOR_CANCELLED;
933                 }
934         }
935         else {
936                 /* animate constraint's "fixed offset" */
937                 PointerRNA ptr;
938                 PropertyRNA *prop;
939                 char *path;
940                 
941                 /* get RNA pointer to constraint's "offset_factor" property - to build RNA path */
942                 RNA_pointer_create(&ob->id, &RNA_FollowPathConstraint, con, &ptr);
943                 prop = RNA_struct_find_property(&ptr, "offset_factor");
944                 
945                 path = RNA_path_from_ID_to_property(&ptr, prop);
946                 
947                 /* create F-Curve for constraint */
948                 act = verify_adt_action(&ob->id, 1);
949                 fcu = verify_fcurve(act, NULL, NULL, path, 0, 1);
950                 
951                 /* standard vertical range - 0.0 to 1.0 */
952                 standardRange = 1.0f;
953                 
954                 /* enable "Use Fixed Position" so that animating this has effect */
955                 data->followflag |= FOLLOWPATH_STATIC;
956                 
957                 /* path needs to be freed */
958                 if (path) 
959                         MEM_freeN(path);
960         }
961         
962         /* setup dummy 'generator' modifier here to get 1-1 correspondence still working
963          * and define basic slope of this curve based on the properties
964          */
965         if (!fcu->bezt && !fcu->fpt && !fcu->modifiers.first) {
966                 FModifier *fcm = add_fmodifier(&fcu->modifiers, FMODIFIER_TYPE_GENERATOR);
967                 FMod_Generator *gen = fcm->data;
968                 
969                 /* Assume that we have the following equation:
970                  *     y = Ax + B
971                  *         1    0       <-- coefficients array indices
972                  */
973                 float A = standardRange / (float)(len);
974                 float B = (float)(-sfra) * A;
975                 
976                 gen->coefficients[1] = A;
977                 gen->coefficients[0] = B;
978         }
979         
980         /* updates... */
981         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
982         return OPERATOR_FINISHED;
983 }
984
985 static int followpath_path_animate_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
986 {
987         /* hook up invoke properties for figuring out which constraint we're dealing with */
988         if (edit_constraint_invoke_properties(C, op)) {
989                 return followpath_path_animate_exec(C, op);
990         }
991         else {
992                 return OPERATOR_CANCELLED;
993         }
994 }
995
996 void CONSTRAINT_OT_followpath_path_animate(wmOperatorType *ot)
997 {
998         /* identifiers */
999         ot->name = "Auto Animate Path";
1000         ot->idname = "CONSTRAINT_OT_followpath_path_animate";
1001         ot->description = "Add default animation for path used by constraint if it isn't animated already";
1002         
1003         /* callbacks */
1004         ot->invoke = followpath_path_animate_invoke;
1005         ot->exec = followpath_path_animate_exec;
1006         ot->poll = edit_constraint_poll;
1007         
1008         /* flags */
1009         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1010         
1011         /* props */
1012         edit_constraint_properties(ot);
1013         RNA_def_int(ot->srna, "frame_start", 1, MINAFRAME, MAXFRAME, "Start Frame", 
1014                     "First frame of path animation", MINAFRAME, MAXFRAME);
1015         RNA_def_int(ot->srna, "length", 100, 0, MAXFRAME, "Length", 
1016                     "Number of frames that path animation should take", 0, MAXFRAME);
1017 }
1018
1019 /* ------------- Object Solver Constraint ------------------ */
1020
1021 static int objectsolver_set_inverse_exec(bContext *C, wmOperator *op)
1022 {
1023         Scene *scene = CTX_data_scene(C);
1024         Object *ob = ED_object_active_context(C);
1025         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_OBJECTSOLVER);
1026         bObjectSolverConstraint *data = (con) ? (bObjectSolverConstraint *)con->data : NULL;
1027
1028         /* despite 3 layers of checks, we may still not be able to find a constraint */
1029         if (data == NULL) {
1030                 printf("DEBUG: Child-Of Set Inverse - object = '%s'\n", (ob) ? ob->id.name + 2 : "<None>");
1031                 BKE_report(op->reports, RPT_ERROR, "Couldn't find constraint data for Child-Of Set Inverse");
1032                 return OPERATOR_CANCELLED;
1033         }
1034
1035         child_get_inverse_matrix(scene, ob, con, data->invmat);
1036
1037         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
1038
1039         return OPERATOR_FINISHED;
1040 }
1041
1042 static int objectsolver_set_inverse_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1043 {
1044         if (edit_constraint_invoke_properties(C, op))
1045                 return objectsolver_set_inverse_exec(C, op);
1046         else
1047                 return OPERATOR_CANCELLED;
1048 }
1049
1050 void CONSTRAINT_OT_objectsolver_set_inverse(wmOperatorType *ot)
1051 {
1052         /* identifiers */
1053         ot->name = "Set Inverse";
1054         ot->idname = "CONSTRAINT_OT_objectsolver_set_inverse";
1055         ot->description = "Set inverse correction for ObjectSolver constraint";
1056         
1057         /* callbacks */
1058         ot->invoke = objectsolver_set_inverse_invoke;
1059         ot->exec = objectsolver_set_inverse_exec;
1060         ot->poll = edit_constraint_poll;
1061
1062         /* flags */
1063         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1064         
1065         /* properties */
1066         edit_constraint_properties(ot);
1067 }
1068
1069 static int objectsolver_clear_inverse_exec(bContext *C, wmOperator *op)
1070 {
1071         Object *ob = ED_object_active_context(C);
1072         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_OBJECTSOLVER);
1073         bObjectSolverConstraint *data = (con) ? (bObjectSolverConstraint *)con->data : NULL;
1074
1075         if (data == NULL) {
1076                 BKE_report(op->reports, RPT_ERROR, "Child Of constraint not found");
1077                 return OPERATOR_CANCELLED;
1078         }
1079
1080         /* simply clear the matrix */
1081         unit_m4(data->invmat);
1082
1083         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
1084
1085         return OPERATOR_FINISHED;
1086 }
1087
1088 static int objectsolver_clear_inverse_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1089 {
1090         if (edit_constraint_invoke_properties(C, op))
1091                 return objectsolver_clear_inverse_exec(C, op);
1092         else
1093                 return OPERATOR_CANCELLED;
1094 }
1095
1096 void CONSTRAINT_OT_objectsolver_clear_inverse(wmOperatorType *ot)
1097 {
1098         /* identifiers */
1099         ot->name = "Clear Inverse";
1100         ot->idname = "CONSTRAINT_OT_objectsolver_clear_inverse";
1101         ot->description = "Clear inverse correction for ObjectSolver constraint";
1102         
1103         /* callbacks */
1104         ot->invoke = objectsolver_clear_inverse_invoke;
1105         ot->exec = objectsolver_clear_inverse_exec;
1106         ot->poll = edit_constraint_poll;
1107
1108         /* flags */
1109         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1110         
1111         /* properties */
1112         edit_constraint_properties(ot);
1113 }
1114
1115 /***************************** BUTTONS ****************************/
1116
1117 void ED_object_constraint_set_active(Object *ob, bConstraint *con)
1118 {       
1119         ListBase *lb = get_constraint_lb(ob, con, NULL);
1120         
1121         /* lets be nice and escape if its active already */
1122         /* NOTE: this assumes that the stack doesn't have other active ones set... */
1123         if ((lb && con) && (con->flag & CONSTRAINT_ACTIVE))
1124                 return;
1125         
1126         constraints_set_active(lb, con);
1127 }
1128
1129 void ED_object_constraint_update(Object *ob)
1130 {
1131         if (ob->pose) BKE_pose_update_constraint_flags(ob->pose);
1132
1133         object_test_constraints(ob);
1134
1135         if (ob->type == OB_ARMATURE) 
1136                 DAG_id_tag_update(&ob->id, OB_RECALC_DATA | OB_RECALC_OB);
1137         else 
1138                 DAG_id_tag_update(&ob->id, OB_RECALC_OB);
1139 }
1140
1141 void ED_object_constraint_dependency_update(Main *bmain, Scene *scene, Object *ob)
1142 {
1143         ED_object_constraint_update(ob);
1144
1145         if (ob->pose) ob->pose->flag |= POSE_RECALC;    // checks & sorts pose channels
1146         DAG_scene_sort(bmain, scene);
1147 }
1148
1149 static int constraint_poll(bContext *C)
1150 {
1151         PointerRNA ptr = CTX_data_pointer_get_type(C, "constraint", &RNA_Constraint);
1152         return (ptr.id.data && ptr.data);
1153 }
1154
1155
1156 static int constraint_delete_exec(bContext *C, wmOperator *UNUSED(op))
1157 {
1158         PointerRNA ptr = CTX_data_pointer_get_type(C, "constraint", &RNA_Constraint);
1159         Object *ob = ptr.id.data;
1160         bConstraint *con = ptr.data;
1161         ListBase *lb = get_constraint_lb(ob, con, NULL);
1162         const short is_ik = ELEM(con->type, CONSTRAINT_TYPE_KINEMATIC, CONSTRAINT_TYPE_SPLINEIK);
1163
1164         /* free the constraint */
1165         if (remove_constraint(lb, con)) {
1166                 /* there's no active constraint now, so make sure this is the case */
1167                 constraints_set_active(lb, NULL);
1168                 
1169                 ED_object_constraint_update(ob); /* needed to set the flags on posebones correctly */
1170                 
1171                 /* ITASC needs to be rebuilt once a constraint is removed [#26920] */
1172                 if (is_ik) {
1173                         BIK_clear_data(ob->pose);
1174                 }
1175                 
1176                 /* notifiers */
1177                 WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT | NA_REMOVED, ob);
1178                 
1179                 return OPERATOR_FINISHED;
1180         }
1181         else {
1182                 /* couldn't remove due to some invalid data */
1183                 return OPERATOR_CANCELLED;
1184         }
1185 }
1186
1187 void CONSTRAINT_OT_delete(wmOperatorType *ot)
1188 {
1189         /* identifiers */
1190         ot->name = "Delete Constraint";
1191         ot->idname = "CONSTRAINT_OT_delete";
1192         ot->description = "Remove constraint from constraint stack";
1193         
1194         /* callbacks */
1195         ot->exec = constraint_delete_exec;
1196         ot->poll = constraint_poll;
1197         
1198         /* flags */
1199         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1200 }
1201
1202
1203 static int constraint_move_down_exec(bContext *C, wmOperator *op)
1204 {
1205         Object *ob = ED_object_active_context(C);
1206         bConstraint *con = edit_constraint_property_get(op, ob, 0);
1207         
1208         if (con && con->next) {
1209                 ListBase *conlist = get_constraint_lb(ob, con, NULL);
1210                 bConstraint *nextCon = con->next;
1211                 
1212                 /* insert the nominated constraint after the one that used to be after it */
1213                 BLI_remlink(conlist, con);
1214                 BLI_insertlinkafter(conlist, nextCon, con);
1215                 
1216                 WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
1217                 
1218                 return OPERATOR_FINISHED;
1219         }
1220         
1221         return OPERATOR_CANCELLED;
1222 }
1223
1224 static int constraint_move_down_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1225 {
1226         if (edit_constraint_invoke_properties(C, op))
1227                 return constraint_move_down_exec(C, op);
1228         else
1229                 return OPERATOR_CANCELLED;
1230 }
1231
1232 void CONSTRAINT_OT_move_down(wmOperatorType *ot)
1233 {
1234         /* identifiers */
1235         ot->name = "Move Constraint Down";
1236         ot->idname = "CONSTRAINT_OT_move_down";
1237         ot->description = "Move constraint down in constraint stack";
1238         
1239         /* callbacks */
1240         ot->invoke = constraint_move_down_invoke;
1241         ot->exec = constraint_move_down_exec;
1242         ot->poll = edit_constraint_poll;
1243         
1244         /* flags */
1245         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1246         
1247         /* properties */
1248         edit_constraint_properties(ot);
1249 }
1250
1251
1252 static int constraint_move_up_exec(bContext *C, wmOperator *op)
1253 {
1254         Object *ob = ED_object_active_context(C);
1255         bConstraint *con = edit_constraint_property_get(op, ob, 0);
1256         
1257         if (con && con->prev) {
1258                 ListBase *conlist = get_constraint_lb(ob, con, NULL);
1259                 bConstraint *prevCon = con->prev;
1260                 
1261                 /* insert the nominated constraint before the one that used to be before it */
1262                 BLI_remlink(conlist, con);
1263                 BLI_insertlinkbefore(conlist, prevCon, con);
1264                 
1265                 WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
1266                 
1267                 return OPERATOR_FINISHED;
1268         }
1269         
1270         return OPERATOR_CANCELLED;
1271 }
1272
1273 static int constraint_move_up_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
1274 {
1275         if (edit_constraint_invoke_properties(C, op))
1276                 return constraint_move_up_exec(C, op);
1277         else
1278                 return OPERATOR_CANCELLED;
1279 }
1280
1281 void CONSTRAINT_OT_move_up(wmOperatorType *ot)
1282 {
1283         /* identifiers */
1284         ot->name = "Move Constraint Up";
1285         ot->idname = "CONSTRAINT_OT_move_up";
1286         ot->description = "Move constraint up in constraint stack";
1287         
1288         /* callbacks */
1289         ot->exec = constraint_move_up_exec;
1290         ot->invoke = constraint_move_up_invoke;
1291         ot->poll = edit_constraint_poll;
1292         
1293         /* flags */
1294         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1295         edit_constraint_properties(ot);
1296 }
1297
1298 /***************************** OPERATORS ****************************/
1299
1300 /************************ remove constraint operators *********************/
1301
1302 static int pose_constraints_clear_exec(bContext *C, wmOperator *UNUSED(op))
1303 {
1304         Main *bmain = CTX_data_main(C);
1305         Scene *scene = CTX_data_scene(C);
1306         Object *ob = BKE_object_pose_armature_get(CTX_data_active_object(C));
1307         
1308         /* free constraints for all selected bones */
1309         CTX_DATA_BEGIN (C, bPoseChannel *, pchan, selected_pose_bones)
1310         {
1311                 free_constraints(&pchan->constraints);
1312                 pchan->constflag &= ~(PCHAN_HAS_IK | PCHAN_HAS_SPLINEIK | PCHAN_HAS_CONST);
1313         }
1314         CTX_DATA_END;
1315         
1316         /* force depsgraph to get recalculated since relationships removed */
1317         DAG_scene_sort(bmain, scene);       /* sort order of objects */
1318         
1319         /* note, calling BIK_clear_data() isn't needed here */
1320
1321         /* do updates */
1322         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
1323         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, ob);
1324         
1325         return OPERATOR_FINISHED;
1326 }
1327
1328 void POSE_OT_constraints_clear(wmOperatorType *ot)
1329 {
1330         /* identifiers */
1331         ot->name = "Clear Pose Constraints";
1332         ot->idname = "POSE_OT_constraints_clear";
1333         ot->description = "Clear all the constraints for the selected bones";
1334         
1335         /* callbacks */
1336         ot->exec = pose_constraints_clear_exec;
1337         ot->poll = ED_operator_posemode_exclusive; // XXX - do we want to ensure there are selected bones too?
1338 }
1339
1340
1341 static int object_constraints_clear_exec(bContext *C, wmOperator *UNUSED(op))
1342 {
1343         Main *bmain = CTX_data_main(C);
1344         Scene *scene = CTX_data_scene(C);
1345         
1346         /* do freeing */
1347         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1348         {
1349                 free_constraints(&ob->constraints);
1350                 DAG_id_tag_update(&ob->id, OB_RECALC_OB);
1351         }
1352         CTX_DATA_END;
1353         
1354         /* force depsgraph to get recalculated since relationships removed */
1355         DAG_scene_sort(bmain, scene);       /* sort order of objects */
1356         
1357         /* do updates */
1358         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, NULL);
1359         
1360         return OPERATOR_FINISHED;
1361 }
1362
1363 void OBJECT_OT_constraints_clear(wmOperatorType *ot)
1364 {
1365         /* identifiers */
1366         ot->name = "Clear Object Constraints";
1367         ot->idname = "OBJECT_OT_constraints_clear";
1368         ot->description = "Clear all the constraints for the active Object only";
1369         
1370         /* callbacks */
1371         ot->exec = object_constraints_clear_exec;
1372         ot->poll = ED_operator_object_active_editable;
1373 }
1374
1375 /************************ copy all constraints operators *********************/
1376
1377 static int pose_constraint_copy_exec(bContext *C, wmOperator *op)
1378 {
1379         Main *bmain = CTX_data_main(C);
1380         Scene *scene = CTX_data_scene(C);
1381         bPoseChannel *pchan = CTX_data_active_pose_bone(C);
1382         
1383         /* don't do anything if bone doesn't exist or doesn't have any constraints */
1384         if (ELEM(NULL, pchan, pchan->constraints.first)) {
1385                 BKE_report(op->reports, RPT_ERROR, "No active bone with constraints for copying");
1386                 return OPERATOR_CANCELLED;
1387         }
1388         
1389         /* copy all constraints from active posebone to all selected posebones */
1390         CTX_DATA_BEGIN (C, bPoseChannel *, chan, selected_pose_bones)
1391         {
1392                 /* if we're not handling the object we're copying from, copy all constraints over */
1393                 if (pchan != chan) {
1394                         copy_constraints(&chan->constraints, &pchan->constraints, TRUE);
1395                         /* update flags (need to add here, not just copy) */
1396                         chan->constflag |= pchan->constflag;
1397                 }
1398         }
1399         CTX_DATA_END;
1400         
1401         /* force depsgraph to get recalculated since new relationships added */
1402         DAG_scene_sort(bmain, scene);       /* sort order of objects/bones */
1403
1404         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT, NULL);
1405         
1406         return OPERATOR_FINISHED;
1407 }
1408
1409 void POSE_OT_constraints_copy(wmOperatorType *ot)
1410 {
1411         /* identifiers */
1412         ot->name = "Copy Constraints to Selected Bones";
1413         ot->idname = "POSE_OT_constraints_copy";
1414         ot->description = "Copy constraints to other selected bones";
1415         
1416         /* api callbacks */
1417         ot->exec = pose_constraint_copy_exec;
1418         ot->poll = ED_operator_posemode_exclusive;
1419
1420         /* flags */
1421         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1422 }
1423
1424 static int object_constraint_copy_exec(bContext *C, wmOperator *UNUSED(op))
1425 {
1426         Main *bmain = CTX_data_main(C);
1427         Scene *scene = CTX_data_scene(C);
1428         Object *obact = ED_object_active_context(C);
1429         
1430         /* copy all constraints from active object to all selected objects */
1431         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1432         {
1433                 /* if we're not handling the object we're copying from, copy all constraints over */
1434                 if (obact != ob) {
1435                         copy_constraints(&ob->constraints, &obact->constraints, TRUE);
1436                         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
1437                 }
1438         }
1439         CTX_DATA_END;
1440         
1441         /* force depsgraph to get recalculated since new relationships added */
1442         DAG_scene_sort(bmain, scene);       /* sort order of objects */
1443         
1444         /* notifiers for updates */
1445         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT | NA_ADDED, NULL);
1446         
1447         return OPERATOR_FINISHED;
1448 }
1449
1450 void OBJECT_OT_constraints_copy(wmOperatorType *ot)
1451 {
1452         /* identifiers */
1453         ot->name = "Copy Constraints to Selected Objects";
1454         ot->idname = "OBJECT_OT_constraints_copy";
1455         ot->description = "Copy constraints to other selected objects";
1456         
1457         /* api callbacks */
1458         ot->exec = object_constraint_copy_exec;
1459         ot->poll = ED_operator_object_active_editable;
1460
1461         /* flags */
1462         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1463 }
1464
1465 /************************ add constraint operators *********************/
1466
1467 /* get the Object and/or PoseChannel to use as target */
1468 static short get_new_constraint_target(bContext *C, int con_type, Object **tar_ob, bPoseChannel **tar_pchan, short add)
1469 {
1470         Object *obact = ED_object_active_context(C);
1471         bPoseChannel *pchanact = BKE_pose_channel_active(obact);
1472         short only_curve = 0, only_mesh = 0, only_ob = 0;
1473         short found = 0;
1474         
1475         /* clear tar_ob and tar_pchan fields before use 
1476          *      - assume for now that both always exist...
1477          */
1478         *tar_ob = NULL;
1479         *tar_pchan = NULL;
1480         
1481         /* check if constraint type doesn't requires a target
1482          *      - if so, no need to get any targets 
1483          */
1484         switch (con_type) {
1485                 /* no-target constraints --------------------------- */
1486                 /* null constraint - shouldn't even be added! */
1487                 case CONSTRAINT_TYPE_NULL:
1488                 /* limit constraints - no targets needed */
1489                 case CONSTRAINT_TYPE_LOCLIMIT:
1490                 case CONSTRAINT_TYPE_ROTLIMIT:
1491                 case CONSTRAINT_TYPE_SIZELIMIT:
1492                 case CONSTRAINT_TYPE_SAMEVOL:
1493                         return 0;
1494                         
1495                 /* restricted target-type constraints -------------- */
1496                 /* NOTE: for these, we cannot try to add a target object if no valid ones are found, since that doesn't work */
1497                 /* curve-based constraints - set the only_curve and only_ob flags */
1498                 case CONSTRAINT_TYPE_CLAMPTO:
1499                 case CONSTRAINT_TYPE_FOLLOWPATH:
1500                 case CONSTRAINT_TYPE_SPLINEIK:
1501                         only_curve = 1;
1502                         only_ob = 1;
1503                         add = 0;
1504                         break;
1505                         
1506                 /* mesh only? */
1507                 case CONSTRAINT_TYPE_SHRINKWRAP:
1508                         only_mesh = 1;
1509                         only_ob = 1;
1510                         add = 0;
1511                         break;
1512                         
1513                 /* object only - add here is ok? */
1514                 case CONSTRAINT_TYPE_RIGIDBODYJOINT:
1515                         only_ob = 1;
1516                         break;
1517         }
1518         
1519         /* if the active Object is Armature, and we can search for bones, do so... */
1520         if ((obact->type == OB_ARMATURE) && (only_ob == 0)) {
1521                 /* search in list of selected Pose-Channels for target */
1522                 CTX_DATA_BEGIN (C, bPoseChannel *, pchan, selected_pose_bones)
1523                 {
1524                         /* just use the first one that we encounter, as long as it is not the active one */
1525                         if (pchan != pchanact) {
1526                                 *tar_ob = obact;
1527                                 *tar_pchan = pchan;
1528                                 found = 1;
1529                                 
1530                                 break;
1531                         }
1532                 }
1533                 CTX_DATA_END;
1534         }
1535         
1536         /* if not yet found, try selected Objects... */
1537         if (found == 0) {
1538                 /* search in selected objects context */
1539                 CTX_DATA_BEGIN (C, Object *, ob, selected_objects)
1540                 {
1541                         /* just use the first object we encounter (that isn't the active object) 
1542                          * and which fulfills the criteria for the object-target that we've got 
1543                          */
1544                         if ((ob != obact) &&
1545                             ((!only_curve) || (ob->type == OB_CURVE)) &&
1546                             ((!only_mesh) || (ob->type == OB_MESH)))
1547                         {
1548                                 /* set target */
1549                                 *tar_ob = ob;
1550                                 found = 1;
1551                                 
1552                                 /* perform some special operations on the target */
1553                                 if (only_curve) {
1554                                         /* Curve-Path option must be enabled for follow-path constraints to be able to work */
1555                                         Curve *cu = (Curve *)ob->data;
1556                                         cu->flag |= CU_PATH;
1557                                 }
1558                                 
1559                                 break;
1560                         }
1561                 }
1562                 CTX_DATA_END;
1563         }
1564         
1565         /* if still not found, add a new empty to act as a target (if allowed) */
1566         if ((found == 0) && (add)) {
1567                 Scene *scene = CTX_data_scene(C);
1568                 Base *base = BASACT, *newbase = NULL;
1569                 Object *obt;
1570                 
1571                 /* add new target object */
1572                 obt = BKE_object_add(scene, OB_EMPTY);
1573                 
1574                 /* set layers OK */
1575                 newbase = BASACT;
1576                 newbase->lay = base->lay;
1577                 obt->lay = newbase->lay;
1578                 
1579                 /* transform cent to global coords for loc */
1580                 if (pchanact) {
1581                         /* since by default, IK targets the tip of the last bone, use the tip of the active PoseChannel 
1582                          * if adding a target for an IK Constraint
1583                          */
1584                         if (con_type == CONSTRAINT_TYPE_KINEMATIC)
1585                                 mul_v3_m4v3(obt->loc, obact->obmat, pchanact->pose_tail);
1586                         else
1587                                 mul_v3_m4v3(obt->loc, obact->obmat, pchanact->pose_head);
1588                 }
1589                 else {
1590                         copy_v3_v3(obt->loc, obact->obmat[3]);
1591                 }
1592
1593                 /* restore, BKE_object_add sets active */
1594                 BASACT = base;
1595                 base->flag |= SELECT;
1596                 
1597                 /* make our new target the new object */
1598                 *tar_ob = obt;
1599                 found = 1;
1600         }
1601         
1602         /* return whether there's any target */
1603         return found;
1604 }
1605
1606 /* used by add constraint operators to add the constraint required */
1607 static int constraint_add_exec(bContext *C, wmOperator *op, Object *ob, ListBase *list, int type, short setTarget)
1608 {
1609         Main *bmain = CTX_data_main(C);
1610         Scene *scene = CTX_data_scene(C);
1611         bPoseChannel *pchan;
1612         bConstraint *con;
1613         
1614         if (list == &ob->constraints) {
1615                 pchan = NULL;
1616         }
1617         else {
1618                 pchan = BKE_pose_channel_active(ob);
1619                 
1620                 /* ensure not to confuse object/pose adding */
1621                 if (pchan == NULL) {
1622                         BKE_report(op->reports, RPT_ERROR, "No active pose bone to add a constraint to");
1623                         return OPERATOR_CANCELLED;
1624                 }
1625         }
1626         /* check if constraint to be added is valid for the given constraints stack */
1627         if (type == CONSTRAINT_TYPE_NULL) {
1628                 return OPERATOR_CANCELLED;
1629         }
1630         if ((type == CONSTRAINT_TYPE_RIGIDBODYJOINT) && (list != &ob->constraints)) {
1631                 BKE_report(op->reports, RPT_ERROR, "Rigid Body Joint Constraint can only be added to Objects");
1632                 return OPERATOR_CANCELLED;
1633         }
1634         if ((type == CONSTRAINT_TYPE_KINEMATIC) && ((!pchan) || (list != &pchan->constraints))) {
1635                 BKE_report(op->reports, RPT_ERROR, "IK Constraint can only be added to Bones");
1636                 return OPERATOR_CANCELLED;
1637         }
1638         if ((type == CONSTRAINT_TYPE_SPLINEIK) && ((!pchan) || (list != &pchan->constraints))) {
1639                 BKE_report(op->reports, RPT_ERROR, "Spline IK Constraint can only be added to Bones");
1640                 return OPERATOR_CANCELLED;
1641         }
1642         
1643         /* create a new constraint of the type requried, and add it to the active/given constraints list */
1644         if (pchan)
1645                 con = add_pose_constraint(ob, pchan, NULL, type);
1646         else
1647                 con = add_ob_constraint(ob, NULL, type);
1648         
1649         /* get the first selected object/bone, and make that the target
1650          *      - apart from the buttons-window add buttons, we shouldn't add in this way
1651          */
1652         if (setTarget) {
1653                 Object *tar_ob = NULL;
1654                 bPoseChannel *tar_pchan = NULL;
1655                 
1656                 /* get the target objects, adding them as need be */
1657                 if (get_new_constraint_target(C, type, &tar_ob, &tar_pchan, 1)) {
1658                         /* method of setting target depends on the type of target we've got 
1659                          *      - by default, just set the first target (distinction here is only for multiple-targeted constraints)
1660                          */
1661                         if (tar_pchan)
1662                                 set_constraint_nth_target(con, tar_ob, tar_pchan->name, 0);
1663                         else
1664                                 set_constraint_nth_target(con, tar_ob, "", 0);
1665                 }
1666         }
1667         
1668         /* do type-specific tweaking to the constraint settings  */
1669         switch (type) {
1670                 case CONSTRAINT_TYPE_PYTHON: /* FIXME: this code is not really valid anymore */
1671                 {
1672 #ifdef WITH_PYTHON
1673                         char *menustr;
1674                         int scriptint = 0;
1675                         /* popup a list of usable scripts */
1676                         menustr = buildmenu_pyconstraints(NULL, &scriptint);
1677                         /* XXX scriptint = pupmenu(menustr); */
1678                         MEM_freeN(menustr);
1679
1680                         /* only add constraint if a script was chosen */
1681                         if (scriptint) {
1682                                 /* add constraint */
1683                                 validate_pyconstraint_cb(con->data, &scriptint);
1684                                 
1685                                 /* make sure target allowance is set correctly */
1686                                 BPY_pyconstraint_update(ob, con);
1687                         }
1688 #endif
1689                         break;
1690                 }
1691
1692                 default:
1693                         break;
1694         }
1695         
1696         /* make sure all settings are valid - similar to above checks, but sometimes can be wrong */
1697         object_test_constraints(ob);
1698
1699         if (pchan)
1700                 BKE_pose_update_constraint_flags(ob->pose);
1701
1702
1703         /* force depsgraph to get recalculated since new relationships added */
1704         DAG_scene_sort(bmain, scene);       /* sort order of objects */
1705         
1706         if ((ob->type == OB_ARMATURE) && (pchan)) {
1707                 ob->pose->flag |= POSE_RECALC;  /* sort pose channels */
1708                 DAG_id_tag_update(&ob->id, OB_RECALC_DATA | OB_RECALC_OB);
1709         }
1710         else
1711                 DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
1712         
1713         /* notifiers for updates */
1714         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT | NA_ADDED, ob);
1715         
1716         return OPERATOR_FINISHED;
1717 }
1718
1719 /* ------------------ */
1720
1721 /* dummy operator callback */
1722 static int object_constraint_add_exec(bContext *C, wmOperator *op)
1723 {
1724         Object *ob = ED_object_active_context(C);
1725         int type = RNA_enum_get(op->ptr, "type");
1726         short with_targets = 0;
1727         
1728         if (!ob) {
1729                 BKE_report(op->reports, RPT_ERROR, "No active object to add constraint to");
1730                 return OPERATOR_CANCELLED;
1731         }
1732                 
1733         /* hack: set constraint targets from selected objects in context is allowed when
1734          *              operator name included 'with_targets', since the menu doesn't allow multiple properties
1735          */
1736         if (strstr(op->idname, "with_targets"))
1737                 with_targets = 1;
1738
1739         return constraint_add_exec(C, op, ob, &ob->constraints, type, with_targets);
1740 }
1741
1742 /* dummy operator callback */
1743 static int pose_constraint_add_exec(bContext *C, wmOperator *op)
1744 {
1745         Object *ob = BKE_object_pose_armature_get(ED_object_active_context(C));
1746         int type = RNA_enum_get(op->ptr, "type");
1747         short with_targets = 0;
1748         
1749         if (!ob) {
1750                 BKE_report(op->reports, RPT_ERROR, "No active object to add constraint to");
1751                 return OPERATOR_CANCELLED;
1752         }
1753                 
1754         /* hack: set constraint targets from selected objects in context is allowed when
1755          *              operator name included 'with_targets', since the menu doesn't allow multiple properties
1756          */
1757         if (strstr(op->idname, "with_targets"))
1758                 with_targets = 1;
1759         
1760         return constraint_add_exec(C, op, ob, get_active_constraints(ob), type, with_targets);
1761 }
1762
1763 /* ------------------ */
1764
1765 void OBJECT_OT_constraint_add(wmOperatorType *ot)
1766 {
1767         /* identifiers */
1768         ot->name = "Add Constraint";
1769         ot->description = "Add a constraint to the active object";
1770         ot->idname = "OBJECT_OT_constraint_add";
1771         
1772         /* api callbacks */
1773         ot->invoke = WM_menu_invoke;
1774         ot->exec = object_constraint_add_exec;
1775         ot->poll = ED_operator_object_active_editable;
1776         
1777         /* flags */
1778         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1779         
1780         /* properties */
1781         ot->prop = RNA_def_enum(ot->srna, "type", constraint_type_items, 0, "Type", "");
1782 }
1783
1784 void OBJECT_OT_constraint_add_with_targets(wmOperatorType *ot)
1785 {
1786         /* identifiers */
1787         ot->name = "Add Constraint (with Targets)";
1788         ot->description = "Add a constraint to the active object, with target (where applicable) set to the selected Objects/Bones";
1789         ot->idname = "OBJECT_OT_constraint_add_with_targets";
1790         
1791         /* api callbacks */
1792         ot->invoke = WM_menu_invoke;
1793         ot->exec = object_constraint_add_exec;
1794         ot->poll = ED_operator_object_active_editable;
1795         
1796         /* flags */
1797         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1798         
1799         /* properties */
1800         ot->prop = RNA_def_enum(ot->srna, "type", constraint_type_items, 0, "Type", "");
1801 }
1802
1803 void POSE_OT_constraint_add(wmOperatorType *ot)
1804 {
1805         /* identifiers */
1806         ot->name = "Add Constraint";
1807         ot->description = "Add a constraint to the active bone";
1808         ot->idname = "POSE_OT_constraint_add";
1809         
1810         /* api callbacks */
1811         ot->invoke = WM_menu_invoke;
1812         ot->exec = pose_constraint_add_exec;
1813         ot->poll = ED_operator_posemode_exclusive;
1814         
1815         /* flags */
1816         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1817         
1818         /* properties */
1819         ot->prop = RNA_def_enum(ot->srna, "type", constraint_type_items, 0, "Type", "");
1820 }
1821
1822 void POSE_OT_constraint_add_with_targets(wmOperatorType *ot)
1823 {
1824         /* identifiers */
1825         ot->name = "Add Constraint (with Targets)";
1826         ot->description = "Add a constraint to the active bone, with target (where applicable) set to the selected Objects/Bones";
1827         ot->idname = "POSE_OT_constraint_add_with_targets";
1828         
1829         /* api callbacks */
1830         ot->invoke = WM_menu_invoke;
1831         ot->exec = pose_constraint_add_exec;
1832         ot->poll = ED_operator_posemode_exclusive;
1833         
1834         /* flags */
1835         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1836         
1837         /* properties */
1838         ot->prop = RNA_def_enum(ot->srna, "type", constraint_type_items, 0, "Type", "");
1839 }
1840
1841 /************************ IK Constraint operators *********************/
1842 /* NOTE: only for Pose-Channels */
1843 // TODO: should these be here, or back in editors/armature/poseobject.c again?
1844
1845 /* present menu with options + validation for targets to use */
1846 static int pose_ik_add_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(evt))
1847 {
1848         Object *ob = BKE_object_pose_armature_get(CTX_data_active_object(C));
1849         bPoseChannel *pchan = BKE_pose_channel_active(ob);
1850         bConstraint *con = NULL;
1851         
1852         uiPopupMenu *pup;
1853         uiLayout *layout;
1854         Object *tar_ob = NULL;
1855         bPoseChannel *tar_pchan = NULL;
1856         
1857         /* must have active bone */
1858         if (ELEM(NULL, ob, pchan)) {
1859                 BKE_report(op->reports, RPT_ERROR, "Must have active bone to add IK Constraint to");
1860                 return OPERATOR_CANCELLED;
1861         }
1862         
1863         /* bone must not have any constraints already */
1864         for (con = pchan->constraints.first; con; con = con->next) {
1865                 if (con->type == CONSTRAINT_TYPE_KINEMATIC) break;
1866         }
1867         if (con) {
1868                 BKE_report(op->reports, RPT_ERROR, "Bone already has IK Constraint");
1869                 return OPERATOR_CANCELLED;
1870         }
1871         
1872         /* prepare popup menu to choose targetting options */
1873         pup = uiPupMenuBegin(C, "Add IK", ICON_NONE);
1874         layout = uiPupMenuLayout(pup);
1875         
1876         /* the type of targets we'll set determines the menu entries to show... */
1877         if (get_new_constraint_target(C, CONSTRAINT_TYPE_KINEMATIC, &tar_ob, &tar_pchan, 0)) {
1878                 /* bone target, or object target? 
1879                  *      - the only thing that matters is that we want a target...
1880                  */
1881                 if (tar_pchan)
1882                         uiItemBooleanO(layout, "To Active Bone", ICON_NONE, "POSE_OT_ik_add", "with_targets", 1);
1883                 else
1884                         uiItemBooleanO(layout, "To Active Object", ICON_NONE, "POSE_OT_ik_add", "with_targets", 1);
1885         }
1886         else {
1887                 /* we have a choice of adding to a new empty, or not setting any target (targetless IK) */
1888                 uiItemBooleanO(layout, "To New Empty Object", ICON_NONE, "POSE_OT_ik_add", "with_targets", 1);
1889                 uiItemBooleanO(layout, "Without Targets", ICON_NONE, "POSE_OT_ik_add", "with_targets", 0);
1890         }
1891         
1892         /* finish building the menu, and process it (should result in calling self again) */
1893         uiPupMenuEnd(C, pup);
1894         
1895         return OPERATOR_CANCELLED;
1896 }
1897
1898 /* call constraint_add_exec() to add the IK constraint */
1899 static int pose_ik_add_exec(bContext *C, wmOperator *op)
1900 {
1901         Object *ob = CTX_data_active_object(C);
1902         int with_targets = RNA_boolean_get(op->ptr, "with_targets");
1903         
1904         /* add the constraint - all necessary checks should have been done by the invoke() callback already... */
1905         return constraint_add_exec(C, op, ob, get_active_constraints(ob), CONSTRAINT_TYPE_KINEMATIC, with_targets);
1906 }
1907
1908 void POSE_OT_ik_add(wmOperatorType *ot)
1909 {
1910         /* identifiers */
1911         ot->name = "Add IK to Bone";
1912         ot->description = "Add IK Constraint to the active Bone";
1913         ot->idname = "POSE_OT_ik_add";
1914         
1915         /* api callbacks */
1916         ot->invoke = pose_ik_add_invoke;
1917         ot->exec = pose_ik_add_exec;
1918         ot->poll = ED_operator_posemode_exclusive;
1919         
1920         /* flags */
1921         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1922         
1923         /* properties */
1924         RNA_def_boolean(ot->srna, "with_targets", 1, "With Targets", "Assign IK Constraint with targets derived from the select bones/objects");
1925 }
1926
1927 /* ------------------ */
1928
1929 /* remove IK constraints from selected bones */
1930 static int pose_ik_clear_exec(bContext *C, wmOperator *UNUSED(op))
1931 {
1932         Object *ob = BKE_object_pose_armature_get(CTX_data_active_object(C));
1933         
1934         /* only remove IK Constraints */
1935         CTX_DATA_BEGIN (C, bPoseChannel *, pchan, selected_pose_bones)
1936         {
1937                 bConstraint *con, *next;
1938                 
1939                 /* TODO: should we be checking if these contraints were local before we try and remove them? */
1940                 for (con = pchan->constraints.first; con; con = next) {
1941                         next = con->next;
1942                         if (con->type == CONSTRAINT_TYPE_KINEMATIC) {
1943                                 remove_constraint(&pchan->constraints, con);
1944                         }
1945                 }
1946                 pchan->constflag &= ~(PCHAN_HAS_IK | PCHAN_HAS_TARGET);
1947         }
1948         CTX_DATA_END;
1949         
1950         /* refresh depsgraph */
1951         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
1952
1953         /* note, notifier might evolve */
1954         WM_event_add_notifier(C, NC_OBJECT | ND_CONSTRAINT | NA_REMOVED, ob);
1955         
1956         return OPERATOR_FINISHED;
1957 }
1958
1959 void POSE_OT_ik_clear(wmOperatorType *ot)
1960 {
1961         /* identifiers */
1962         ot->name = "Remove IK";
1963         ot->description = "Remove all IK Constraints from selected bones";
1964         ot->idname = "POSE_OT_ik_clear";
1965         
1966         /* api callbacks */
1967         ot->exec = pose_ik_clear_exec;
1968         ot->poll = ED_operator_posemode_exclusive;
1969         
1970         /* flags */
1971         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1972 }
1973