Merging r41158 through r41175 from trunk into soc-2011-tomato
[blender.git] / source / blender / editors / object / object_constraint.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): Joshua Leung, Blender Foundation
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 /** \file blender/editors/object/object_constraint.c
31  *  \ingroup edobj
32  */
33
34
35 #include <stdio.h>
36 #include <string.h>
37
38 #include "MEM_guardedalloc.h"
39
40 #include "BLI_blenlib.h"
41 #include "BLI_math.h"
42 #include "BLI_dynstr.h"
43 #include "BLI_utildefines.h"
44
45 #include "DNA_constraint_types.h"
46 #include "DNA_curve_types.h"
47 #include "DNA_scene_types.h"
48 #include "DNA_text_types.h"
49 #include "DNA_object_types.h"
50
51 #include "BKE_action.h"
52 #include "BKE_armature.h"
53 #include "BKE_constraint.h"
54 #include "BKE_context.h"
55 #include "BKE_depsgraph.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_screen.h"
77
78 #include "UI_interface.h"
79 #include "UI_resources.h"
80
81 #include "object_intern.h"
82
83 /* -------------- Get Active Constraint Data ---------------------- */
84
85 /* if object in posemode, active bone constraints, else object constraints */
86 ListBase *get_active_constraints (Object *ob)
87 {
88         if (ob == NULL)
89                 return NULL;
90         
91         if (ob->mode & OB_MODE_POSE) {
92                 bPoseChannel *pchan;
93                 
94                 pchan = get_active_posechannel(ob);
95                 if (pchan)
96                         return &pchan->constraints;
97         }
98         else 
99                 return &ob->constraints;
100         
101         return NULL;
102 }
103
104 /* Find the list that a given constraint belongs to, and/or also get the posechannel this is from (if applicable) */
105 ListBase *get_constraint_lb (Object *ob, bConstraint *con, bPoseChannel **pchan_r)
106 {
107         if (pchan_r)
108                 *pchan_r= NULL;
109         
110         if (ELEM(NULL, ob, con))
111                 return NULL;
112         
113         /* try object constraints first */
114         if ((BLI_findindex(&ob->constraints, con) != -1)) {
115                 return &ob->constraints;
116         }
117         
118         /* if armature, try pose bones too */
119         if (ob->pose) {
120                 bPoseChannel *pchan;
121                 
122                 /* try each bone in order 
123                  * NOTE: it's not possible to directly look up the active bone yet, so this will have to do
124                  */
125                 for (pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
126                         if ((BLI_findindex(&pchan->constraints, con) != -1)) {
127                                 
128                                 if (pchan_r)
129                                         *pchan_r= pchan;
130                                 
131                                 return &pchan->constraints;
132                         }
133                 }
134         }
135         
136         /* done */
137         return NULL;
138 }
139
140 /* single constraint */
141 bConstraint *get_active_constraint (Object *ob)
142 {
143         return constraints_get_active(get_active_constraints(ob));
144 }
145
146 /* -------------- Constraint Management (Add New, Remove, Rename) -------------------- */
147 /* ------------- PyConstraints ------------------ */
148
149 /* this callback sets the text-file to be used for selected menu item */
150 static void validate_pyconstraint_cb (void *arg1, void *arg2)
151 {
152         bPythonConstraint *data = arg1;
153         Text *text= NULL;
154         int index = *((int *)arg2);
155         int i;
156         
157         /* exception for no script */
158         if (index) {
159                 /* innovative use of a for...loop to search */
160                 for (text=G.main->text.first, i=1; text && index!=i; i++, text=text->id.next);
161         }
162         data->text = text;
163 }
164
165 #ifdef WITH_PYTHON
166 /* this returns a string for the list of usable pyconstraint script names */
167 static char *buildmenu_pyconstraints (Text *con_text, int *pyconindex)
168 {
169         DynStr *pupds= BLI_dynstr_new();
170         Text *text;
171         char *str;
172         char buf[64];
173         int i;
174         
175         /* add title first */
176         sprintf(buf, "Scripts: %%t|[None]%%x0|");
177         BLI_dynstr_append(pupds, buf);
178         
179         /* init active-index first */
180         if (con_text == NULL)
181                 *pyconindex= 0;
182         
183         /* loop through markers, adding them */
184         for (text=G.main->text.first, i=1; text; i++, text=text->id.next) {
185                 /* this is important to ensure that right script is shown as active */
186                 if (text == con_text) *pyconindex = i;
187                 
188                 /* only include valid pyconstraint scripts */
189                 if (BPY_is_pyconstraint(text)) {
190                         BLI_dynstr_append(pupds, text->id.name+2);
191                         
192                         sprintf(buf, "%%x%d", i);
193                         BLI_dynstr_append(pupds, buf);
194                         
195                         if (text->id.next)
196                                 BLI_dynstr_append(pupds, "|");
197                 }
198         }
199         
200         /* convert to normal MEM_malloc'd string */
201         str= BLI_dynstr_get_cstring(pupds);
202         BLI_dynstr_free(pupds);
203         
204         return str;
205 }
206 #endif /* WITH_PYTHON */
207
208 #if 0 // UNUSED, until pyconstraints are added back.
209 /* this callback gets called when the 'refresh' button of a pyconstraint gets pressed */
210 static void update_pyconstraint_cb (void *arg1, void *arg2)
211 {
212 #ifndef WITH_PYTHON
213         (void)arg1; /* unused */
214         (void)arg2; /* unused */
215 #else
216         Object *owner= (Object *)arg1;
217         bConstraint *con= (bConstraint *)arg2;
218         if (owner && con)
219                 BPY_pyconstraint_update(owner, con);
220 #endif
221 }
222 #endif // UNUSED
223
224 /* helper function for add_constriant - sets the last target for the active constraint */
225 static void set_constraint_nth_target (bConstraint *con, Object *target, const char subtarget[], int index)
226 {
227         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
228         ListBase targets = {NULL, NULL};
229         bConstraintTarget *ct;
230         int num_targets, i;
231         
232         if (cti && cti->get_constraint_targets) {
233                 cti->get_constraint_targets(con, &targets);
234                 num_targets= BLI_countlist(&targets);
235                 
236                 if (index < 0) {
237                         if (abs(index) < num_targets)
238                                 index= num_targets - abs(index);
239                         else
240                                 index= num_targets - 1;
241                 }
242                 else if (index >= num_targets) {
243                         index= num_targets - 1;
244                 }
245                 
246                 for (ct=targets.first, i=0; ct; ct= ct->next, i++) {
247                         if (i == index) {
248                                 ct->tar= target;
249                                 BLI_strncpy(ct->subtarget, subtarget, sizeof(ct->subtarget));
250                                 break;
251                         }
252                 }
253                 
254                 if (cti->flush_constraint_targets)
255                         cti->flush_constraint_targets(con, &targets, 0);
256         }
257 }
258
259 /* ------------- Constraint Sanity Testing ------------------- */
260
261 /* checks validity of object pointers, and NULLs,
262  * if Bone doesnt exist it sets the CONSTRAINT_DISABLE flag.
263  */
264 static void test_constraints (Object *owner, bPoseChannel *pchan)
265 {
266         bConstraint *curcon;
267         ListBase *conlist= NULL;
268         int type;
269         
270         if (owner==NULL) return;
271         
272         /* Check parents */
273         if (pchan) {
274                 switch (owner->type) {
275                         case OB_ARMATURE:
276                                 type = CONSTRAINT_OBTYPE_BONE;
277                                 break;
278                         default:
279                                 type = CONSTRAINT_OBTYPE_OBJECT;
280                                 break;
281                 }
282         }
283         else
284                 type = CONSTRAINT_OBTYPE_OBJECT;
285         
286         /* Get the constraint list for this object */
287         switch (type) {
288                 case CONSTRAINT_OBTYPE_OBJECT:
289                         conlist = &owner->constraints;
290                         break;
291                 case CONSTRAINT_OBTYPE_BONE:
292                         conlist = &pchan->constraints;
293                         break;
294         }
295         
296         /* Check all constraints - is constraint valid? */
297         if (conlist) {
298                 for (curcon = conlist->first; curcon; curcon=curcon->next) {
299                         bConstraintTypeInfo *cti= constraint_get_typeinfo(curcon);
300                         ListBase targets = {NULL, NULL};
301                         bConstraintTarget *ct;
302                         
303                         /* clear disabled-flag first */
304                         curcon->flag &= ~CONSTRAINT_DISABLE;
305                         
306                         if (curcon->type == CONSTRAINT_TYPE_KINEMATIC) {
307                                 bKinematicConstraint *data = curcon->data;
308                                 
309                                 /* bad: we need a separate set of checks here as poletarget is 
310                                  *              optional... otherwise poletarget must exist too or else
311                                  *              the constraint is deemed invalid
312                                  */
313                                 /* default IK check ... */
314                                 if (exist_object(data->tar) == 0) {
315                                         data->tar = NULL;
316                                         curcon->flag |= CONSTRAINT_DISABLE;
317                                 }
318                                 else if (data->tar == owner) {
319                                         if (!get_named_bone(get_armature(owner), data->subtarget)) {
320                                                 curcon->flag |= CONSTRAINT_DISABLE;
321                                         }
322                                 }
323                                 
324                                 if (data->poletar) {
325                                         if (exist_object(data->poletar) == 0) {
326                                                 data->poletar = NULL;
327                                                 curcon->flag |= CONSTRAINT_DISABLE;
328                                         }
329                                         else if (data->poletar == owner) {
330                                                 if (!get_named_bone(get_armature(owner), data->polesubtarget)) {
331                                                         curcon->flag |= CONSTRAINT_DISABLE;
332                                                 }
333                                         }
334                                 }
335                                 /* ... can be overwritten here */
336                                 BIK_test_constraint(owner, curcon);
337                                 /* targets have already been checked for this */
338                                 continue;
339                         }
340                         else if (curcon->type == CONSTRAINT_TYPE_PIVOT) {
341                                 bPivotConstraint *data = curcon->data;
342                                 
343                                 /* target doesn't have to exist, but if it is non-null, it must exist! */
344                                 if (data->tar && exist_object(data->tar)==0) {
345                                         data->tar = NULL;
346                                         curcon->flag |= CONSTRAINT_DISABLE;
347                                 }
348                                 else if (data->tar == owner) {
349                                         if (!get_named_bone(get_armature(owner), data->subtarget)) {
350                                                 curcon->flag |= CONSTRAINT_DISABLE;
351                                         }
352                                 }
353                                 
354                                 /* targets have already been checked for this */
355                                 continue;
356                         }
357                         else if (curcon->type == CONSTRAINT_TYPE_ACTION) {
358                                 bActionConstraint *data = curcon->data;
359                                 
360                                 /* validate action */
361                                 if (data->act == NULL) 
362                                         curcon->flag |= CONSTRAINT_DISABLE;
363                         }
364                         else if (curcon->type == CONSTRAINT_TYPE_FOLLOWPATH) {
365                                 bFollowPathConstraint *data = curcon->data;
366                                 
367                                 /* don't allow track/up axes to be the same */
368                                 if (data->upflag==data->trackflag)
369                                         curcon->flag |= CONSTRAINT_DISABLE;
370                                 if (data->upflag+3==data->trackflag)
371                                         curcon->flag |= CONSTRAINT_DISABLE;
372                         }
373                         else if (curcon->type == CONSTRAINT_TYPE_TRACKTO) {
374                                 bTrackToConstraint *data = curcon->data;
375                                 
376                                 /* don't allow track/up axes to be the same */
377                                 if (data->reserved2==data->reserved1)
378                                         curcon->flag |= CONSTRAINT_DISABLE;
379                                 if (data->reserved2+3==data->reserved1)
380                                         curcon->flag |= CONSTRAINT_DISABLE;
381                         }
382                         else if (curcon->type == CONSTRAINT_TYPE_LOCKTRACK) {
383                                 bLockTrackConstraint *data = curcon->data;
384                                 
385                                 if (data->lockflag==data->trackflag)
386                                         curcon->flag |= CONSTRAINT_DISABLE;
387                                 if (data->lockflag+3==data->trackflag)
388                                         curcon->flag |= CONSTRAINT_DISABLE;
389                         }
390                         else if (curcon->type == CONSTRAINT_TYPE_SPLINEIK) {
391                                 bSplineIKConstraint *data = curcon->data;
392                                 
393                                 /* if the number of points does not match the amount required by the chain length,
394                                  * free the points array and request a rebind...
395                                  */
396                                 if ((data->points == NULL) || (data->numpoints != data->chainlen+1))
397                                 {
398                                         /* free the points array */
399                                         if (data->points) {
400                                                 MEM_freeN(data->points);
401                                                 data->points = NULL;
402                                         }
403                                         
404                                         /* clear the bound flag, forcing a rebind next time this is evaluated */
405                                         data->flag &= ~CONSTRAINT_SPLINEIK_BOUND;
406                                 }
407                         }
408                         else if (curcon->type == CONSTRAINT_TYPE_FOLLOWTRACK) {
409                                 bFollowTrackConstraint *data = curcon->data;
410
411                                 if((data->flag&CAMERASOLVER_ACTIVECLIP)==0) {
412                                         if(data->clip != NULL && data->track[0]) {
413                                                 if (!BKE_find_track_by_name(&data->clip->tracking, data->track))
414                                                         curcon->flag |= CONSTRAINT_DISABLE;
415                                         }
416                                         else curcon->flag |= CONSTRAINT_DISABLE;
417                                 }
418                         }
419                         else if (curcon->type == CONSTRAINT_TYPE_CAMERASOLVER) {
420                                 bCameraSolverConstraint *data = curcon->data;
421
422                                 if((data->flag&CAMERASOLVER_ACTIVECLIP)==0 && data->clip == NULL)
423                                         curcon->flag |= CONSTRAINT_DISABLE;
424                         }
425                         
426                         /* Check targets for constraints */
427                         if (cti && cti->get_constraint_targets) {
428                                 cti->get_constraint_targets(curcon, &targets);
429                                 
430                                 /* disable and clear constraints targets that are incorrect */
431                                 for (ct= targets.first; ct; ct= ct->next) {
432                                         /* general validity checks (for those constraints that need this) */
433                                         if (exist_object(ct->tar) == 0) {
434                                                 /* object doesn't exist, but constraint requires target */
435                                                 ct->tar = NULL;
436                                                 curcon->flag |= CONSTRAINT_DISABLE;
437                                         }
438                                         else if (ct->tar == owner) {
439                                                 if (type == CONSTRAINT_OBTYPE_BONE) {
440                                                         if (!get_named_bone(get_armature(owner), ct->subtarget)) {
441                                                                 /* bone must exist in armature... */
442                                                                 // TODO: clear subtarget?
443                                                                 curcon->flag |= CONSTRAINT_DISABLE;
444                                                         }
445                                                         else if (strcmp(pchan->name, ct->subtarget) == 0) {
446                                                                 /* cannot target self */
447                                                                 ct->subtarget[0] = '\0';
448                                                                 curcon->flag |= CONSTRAINT_DISABLE;
449                                                         }
450                                                 }
451                                                 else {
452                                                         /* cannot use self as target */
453                                                         ct->tar = NULL;
454                                                         curcon->flag |= CONSTRAINT_DISABLE;
455                                                 }
456                                         }
457                                         
458                                         /* target checks for specific constraints */
459                                         if (ELEM3(curcon->type, CONSTRAINT_TYPE_FOLLOWPATH, CONSTRAINT_TYPE_CLAMPTO, CONSTRAINT_TYPE_SPLINEIK)) {
460                                                 if (ct->tar) {
461                                                         if (ct->tar->type != OB_CURVE) {
462                                                                 ct->tar= NULL;
463                                                                 curcon->flag |= CONSTRAINT_DISABLE;
464                                                         }
465                                                         else {
466                                                                 Curve *cu= ct->tar->data;
467                                                                 
468                                                                 /* auto-set 'Path' setting on curve so this works  */
469                                                                 cu->flag |= CU_PATH;
470                                                         }
471                                                 }                                               
472                                         }
473                                 }       
474                                 
475                                 /* free any temporary targets */
476                                 if (cti->flush_constraint_targets)
477                                         cti->flush_constraint_targets(curcon, &targets, 0);
478                         }
479                 }
480         }
481 }
482
483 void object_test_constraints (Object *owner)
484 {
485         if (owner->constraints.first)
486                 test_constraints(owner, NULL);
487         
488         if (owner->type==OB_ARMATURE && owner->pose) {
489                 bPoseChannel *pchan;
490                 
491                 for (pchan= owner->pose->chanbase.first; pchan; pchan= pchan->next) {
492                         if (pchan->constraints.first)
493                                 test_constraints(owner, pchan);
494                 }
495         }
496 }
497
498
499 /************************ generic functions for operators using constraint names and data context *********************/
500
501 #define EDIT_CONSTRAINT_OWNER_OBJECT    0
502 #define EDIT_CONSTRAINT_OWNER_BONE              1
503
504 static EnumPropertyItem constraint_owner_items[] = {
505         {EDIT_CONSTRAINT_OWNER_OBJECT, "OBJECT", 0, "Object", "Edit a constraint on the active object"},
506         {EDIT_CONSTRAINT_OWNER_BONE, "BONE", 0, "Bone", "Edit a constraint on the active bone"},
507         {0, NULL, 0, NULL, NULL}};
508
509
510 static int edit_constraint_poll_generic(bContext *C, StructRNA *rna_type)
511 {
512         PointerRNA ptr= CTX_data_pointer_get_type(C, "constraint", rna_type);
513         Object *ob= (ptr.id.data) ? ptr.id.data : ED_object_active_context(C);
514
515         if (!ob || ob->id.lib) return 0;
516         if (ptr.id.data && ((ID*)ptr.id.data)->lib) return 0;
517
518         return 1;
519 }
520
521 static int edit_constraint_poll(bContext *C)
522 {
523         return edit_constraint_poll_generic(C, &RNA_Constraint);
524 }
525
526 static void edit_constraint_properties(wmOperatorType *ot)
527 {
528         RNA_def_string(ot->srna, "constraint", "", 32, "Constraint", "Name of the constraint to edit");
529         RNA_def_enum(ot->srna, "owner", constraint_owner_items, 0, "Owner", "The owner of this constraint");
530 }
531
532 static int edit_constraint_invoke_properties(bContext *C, wmOperator *op)
533 {
534         PointerRNA ptr= CTX_data_pointer_get_type(C, "constraint", &RNA_Constraint);
535         Object *ob= (ptr.id.data)?ptr.id.data:ED_object_active_context(C);
536         bConstraint *con;
537         ListBase *list;
538         
539         if (RNA_property_is_set(op->ptr, "constraint") && RNA_property_is_set(op->ptr, "owner"))
540                 return 1;
541         
542         if (ptr.data) {
543                 con = ptr.data;
544                 RNA_string_set(op->ptr, "constraint", con->name);
545                 
546                 list = get_constraint_lb(ob, con, NULL);
547                 
548                 if (&ob->constraints == list)
549                         RNA_enum_set(op->ptr, "owner", EDIT_CONSTRAINT_OWNER_OBJECT);
550                 else
551                         RNA_enum_set(op->ptr, "owner", EDIT_CONSTRAINT_OWNER_BONE);
552                 
553                 return 1;
554         }
555         
556         return 0;
557 }
558
559 static bConstraint *edit_constraint_property_get(wmOperator *op, Object *ob, int type)
560 {
561         char constraint_name[32];
562         int owner = RNA_enum_get(op->ptr, "owner");
563         bConstraint *con;
564         ListBase *list=NULL;
565         
566         RNA_string_get(op->ptr, "constraint", constraint_name);
567         
568         if (owner == EDIT_CONSTRAINT_OWNER_OBJECT) {
569                 list = &ob->constraints;
570         } 
571         else if (owner == EDIT_CONSTRAINT_OWNER_BONE) {
572                 bPoseChannel *pchan= get_active_posechannel(ob);
573                 if (pchan)
574                         list = &pchan->constraints;
575                 else {
576                         //if (G.f & G_DEBUG)
577                         //printf("edit_constraint_property_get: No active bone for object '%s'\n", (ob)? ob->id.name+2 : "<None>");
578                         return NULL;
579                 }
580         }
581         else {
582                 //if (G.f & G_DEBUG)
583                 //printf("edit_constraint_property_get: defaulting to getting list in the standard way\n");
584                 list = get_active_constraints(ob);
585         }
586         
587         con = constraints_findByName(list, constraint_name);
588         //if (G.f & G_DEBUG)
589         //printf("constraint found = %p, %s\n", (void *)con, (con)?con->name:"<Not found>");
590
591         if (con && (type != 0) && (con->type != type))
592                 con = NULL;
593         
594         return con;
595 }
596
597 /* ********************** CONSTRAINT-SPECIFIC STUFF ********************* */
598
599 /* ---------- Distance-Dependent Constraints ---------- */
600 /* StretchTo, Limit Distance */
601
602 static int stretchto_reset_exec (bContext *C, wmOperator *op)
603 {
604         Object *ob = ED_object_active_context(C);
605         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_STRETCHTO);
606         bStretchToConstraint *data= (con) ? (bStretchToConstraint *)con->data : NULL;
607         
608         /* despite 3 layers of checks, we may still not be able to find a constraint */
609         if (data == NULL)
610                 return OPERATOR_CANCELLED;
611         
612         /* just set original length to 0.0, which will cause a reset on next recalc */
613         data->orglength = 0.0f;
614         ED_object_constraint_update(ob);
615         
616         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, NULL);
617         return OPERATOR_FINISHED;
618 }
619
620 static int stretchto_reset_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
621 {
622         if (edit_constraint_invoke_properties(C, op))
623                 return stretchto_reset_exec(C, op);
624         else
625                 return OPERATOR_CANCELLED;
626 }
627
628 void CONSTRAINT_OT_stretchto_reset (wmOperatorType *ot)
629 {
630         /* identifiers */
631         ot->name= "Reset Original Length";
632         ot->idname= "CONSTRAINT_OT_stretchto_reset";
633         ot->description= "Reset original length of bone for Stretch To Constraint";
634         
635         ot->exec= stretchto_reset_exec;
636         ot->invoke= stretchto_reset_invoke;
637         ot->poll= edit_constraint_poll;
638         
639         /* flags */
640         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
641         edit_constraint_properties(ot);
642 }
643
644
645 static int limitdistance_reset_exec (bContext *C, wmOperator *op)
646 {
647         Object *ob = ED_object_active_context(C);
648         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_DISTLIMIT);
649         bDistLimitConstraint *data= (con) ? (bDistLimitConstraint *)con->data : NULL;
650         
651         /* despite 3 layers of checks, we may still not be able to find a constraint */
652         if (data == NULL)
653                 return OPERATOR_CANCELLED;
654         
655         /* just set original length to 0.0, which will cause a reset on next recalc */
656         data->dist = 0.0f;
657         ED_object_constraint_update(ob);
658         
659         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, NULL);
660         return OPERATOR_FINISHED;
661 }
662
663 static int limitdistance_reset_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
664 {
665         if (edit_constraint_invoke_properties(C, op))
666                 return limitdistance_reset_exec(C, op);
667         else
668                 return OPERATOR_CANCELLED;
669 }
670
671 void CONSTRAINT_OT_limitdistance_reset (wmOperatorType *ot)
672 {
673         /* identifiers */
674         ot->name= "Reset Distance";
675         ot->idname= "CONSTRAINT_OT_limitdistance_reset";
676         ot->description= "Reset limiting distance for Limit Distance Constraint";
677         
678         ot->exec= limitdistance_reset_exec;
679         ot->invoke= limitdistance_reset_invoke;
680         ot->poll= edit_constraint_poll;
681         
682         /* flags */
683         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
684         edit_constraint_properties(ot);
685 }
686
687 /* ------------- Child-Of Constraint ------------------ */
688
689 /* ChildOf Constraint - set inverse callback */
690 static int childof_set_inverse_exec (bContext *C, wmOperator *op)
691 {
692         Scene *scene= CTX_data_scene(C);
693         Object *ob = ED_object_active_context(C);
694         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_CHILDOF);
695         bChildOfConstraint *data= (con) ? (bChildOfConstraint *)con->data : NULL;
696         bPoseChannel *pchan= NULL;
697         
698         /* despite 3 layers of checks, we may still not be able to find a constraint */
699         if (data == NULL) {
700                 printf("DEBUG: Child-Of Set Inverse - object = '%s'\n", (ob)? ob->id.name+2 : "<None>");
701                 BKE_report(op->reports, RPT_ERROR, "Couldn't find constraint data for Child-Of Set Inverse");
702                 return OPERATOR_CANCELLED;
703         }
704         
705         /* try to find a pose channel */
706         // TODO: get from context instead?
707         if (ob && ob->pose)
708                 pchan= get_active_posechannel(ob);
709         
710         /* calculate/set inverse matrix */
711         if (pchan) {
712                 float pmat[4][4], cinf;
713                 float imat[4][4], tmat[4][4];
714                 
715                 /* make copy of pchan's original pose-mat (for use later) */
716                 copy_m4_m4(pmat, pchan->pose_mat);
717                 
718                 /* disable constraint for pose to be solved without it */
719                 cinf= con->enforce;
720                 con->enforce= 0.0f;
721                 
722                 /* solve pose without constraint */
723                 where_is_pose(scene, ob);
724                 
725                 /* determine effect of constraint by removing the newly calculated 
726                  * pchan->pose_mat from the original pchan->pose_mat, thus determining 
727                  * the effect of the constraint
728                  */
729                 invert_m4_m4(imat, pchan->pose_mat);
730                 mul_m4_m4m4(tmat, imat, pmat);
731                 invert_m4_m4(data->invmat, tmat);
732                 
733                 /* recalculate pose with new inv-mat */
734                 con->enforce= cinf;
735                 where_is_pose(scene, ob);
736         }
737         else if (ob) {
738                 Object workob;
739                 /* use what_does_parent to find inverse - just like for normal parenting.
740                  * NOTE: what_does_parent uses a static workob defined in object.c 
741                  */
742                 what_does_parent(scene, ob, &workob);
743                 invert_m4_m4(data->invmat, workob.obmat);
744         }
745         else
746                 unit_m4(data->invmat);
747                 
748         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
749                 
750         return OPERATOR_FINISHED;
751 }
752
753 static int childof_set_inverse_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
754 {
755         if (edit_constraint_invoke_properties(C, op))
756                 return childof_set_inverse_exec(C, op);
757         else
758                 return OPERATOR_CANCELLED;
759 }
760
761 void CONSTRAINT_OT_childof_set_inverse (wmOperatorType *ot)
762 {
763         /* identifiers */
764         ot->name= "Set Inverse";
765         ot->idname= "CONSTRAINT_OT_childof_set_inverse";
766         ot->description= "Set inverse correction for ChildOf constraint";
767         
768         ot->exec= childof_set_inverse_exec;
769         ot->invoke= childof_set_inverse_invoke;
770         ot->poll= edit_constraint_poll;
771         
772         /* flags */
773         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
774         edit_constraint_properties(ot);
775 }
776
777 /* ChildOf Constraint - clear inverse callback */
778 static int childof_clear_inverse_exec (bContext *C, wmOperator *op)
779 {
780         Object *ob = ED_object_active_context(C);
781         bConstraint *con = edit_constraint_property_get(op, ob, CONSTRAINT_TYPE_CHILDOF);
782         bChildOfConstraint *data= (con) ? (bChildOfConstraint *)con->data : NULL;
783         
784         if(data==NULL) {
785                 BKE_report(op->reports, RPT_ERROR, "Childof constraint not found");
786                 return OPERATOR_CANCELLED;
787         }
788         
789         /* simply clear the matrix */
790         unit_m4(data->invmat);
791         
792         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
793         
794         return OPERATOR_FINISHED;
795 }
796
797 static int childof_clear_inverse_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
798 {
799         if (edit_constraint_invoke_properties(C, op))
800                 return childof_clear_inverse_exec(C, op);
801         else
802                 return OPERATOR_CANCELLED;
803 }
804
805 void CONSTRAINT_OT_childof_clear_inverse (wmOperatorType *ot)
806 {
807         /* identifiers */
808         ot->name= "Clear Inverse";
809         ot->idname= "CONSTRAINT_OT_childof_clear_inverse";
810         ot->description= "Clear inverse correction for ChildOf constraint";
811         
812         ot->exec= childof_clear_inverse_exec;
813         ot->invoke= childof_clear_inverse_invoke;
814         ot->poll= edit_constraint_poll;
815         
816         /* flags */
817         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
818         edit_constraint_properties(ot);
819 }
820
821 /***************************** BUTTONS ****************************/
822
823 void ED_object_constraint_set_active(Object *ob, bConstraint *con)
824 {       
825         ListBase *lb = get_constraint_lb(ob, con, NULL);
826         
827         /* lets be nice and escape if its active already */
828         // NOTE: this assumes that the stack doesn't have other active ones set...
829         if ((lb && con) && (con->flag & CONSTRAINT_ACTIVE))
830                 return;
831         
832         constraints_set_active(lb, con);
833 }
834
835 void ED_object_constraint_update(Object *ob)
836 {
837
838         if(ob->pose) update_pose_constraint_flags(ob->pose);
839
840         object_test_constraints(ob);
841
842         if(ob->type==OB_ARMATURE) DAG_id_tag_update(&ob->id, OB_RECALC_DATA|OB_RECALC_OB);
843         else DAG_id_tag_update(&ob->id, OB_RECALC_OB);
844 }
845
846 void ED_object_constraint_dependency_update(Main *bmain, Scene *scene, Object *ob)
847 {
848         ED_object_constraint_update(ob);
849
850         if(ob->pose) ob->pose->flag |= POSE_RECALC;     // checks & sorts pose channels
851         DAG_scene_sort(bmain, scene);
852 }
853
854 static int constraint_poll(bContext *C)
855 {
856         PointerRNA ptr= CTX_data_pointer_get_type(C, "constraint", &RNA_Constraint);
857         return (ptr.id.data && ptr.data);
858 }
859
860 static int constraint_delete_exec (bContext *C, wmOperator *UNUSED(op))
861 {
862         PointerRNA ptr= CTX_data_pointer_get_type(C, "constraint", &RNA_Constraint);
863         Object *ob= ptr.id.data;
864         bConstraint *con= ptr.data;
865         ListBase *lb = get_constraint_lb(ob, con, NULL);
866         const short is_ik= ELEM(con->type, CONSTRAINT_TYPE_KINEMATIC, CONSTRAINT_TYPE_SPLINEIK);
867
868         /* free the constraint */
869         if (remove_constraint(lb, con)) {
870                 /* there's no active constraint now, so make sure this is the case */
871                 constraints_set_active(lb, NULL);
872                 
873                 ED_object_constraint_update(ob); /* needed to set the flags on posebones correctly */
874
875                 /* ITASC needs to be rebuilt once a constraint is removed [#26920] */
876                 if(is_ik) {
877                         BIK_clear_data(ob->pose);
878                 }
879
880                 /* notifiers */
881                 WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT|NA_REMOVED, ob);
882                 
883                 return OPERATOR_FINISHED;
884         }
885         else {
886                 /* couldn't remove due to some invalid data */
887                 return OPERATOR_CANCELLED;
888         }
889 }
890
891 void CONSTRAINT_OT_delete (wmOperatorType *ot)
892 {
893         /* identifiers */
894         ot->name= "Delete Constraint";
895         ot->idname= "CONSTRAINT_OT_delete";
896         ot->description= "Remove constraint from constraint stack";
897         
898         /* callbacks */
899         ot->exec= constraint_delete_exec;
900         ot->poll= constraint_poll;
901         
902         /* flags */
903         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; 
904 }
905
906 static int constraint_move_down_exec (bContext *C, wmOperator *op)
907 {
908         Object *ob = ED_object_active_context(C);
909         bConstraint *con = edit_constraint_property_get(op, ob, 0);
910         
911         if (con && con->next) {
912                 ListBase *conlist= get_constraint_lb(ob, con, NULL);
913                 bConstraint *nextCon= con->next;
914                 
915                 /* insert the nominated constraint after the one that used to be after it */
916                 BLI_remlink(conlist, con);
917                 BLI_insertlinkafter(conlist, nextCon, con);
918                 
919                 WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
920                 
921                 return OPERATOR_FINISHED;
922         }
923         
924         return OPERATOR_CANCELLED;
925 }
926
927 static int constraint_move_down_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
928 {
929         if (edit_constraint_invoke_properties(C, op))
930                 return constraint_move_down_exec(C, op);
931         else
932                 return OPERATOR_CANCELLED;
933 }
934
935
936 void CONSTRAINT_OT_move_down (wmOperatorType *ot)
937 {
938         /* identifiers */
939         ot->name= "Move Constraint Down";
940         ot->idname= "CONSTRAINT_OT_move_down";
941         ot->description= "Move constraint down in constraint stack";
942         
943         /* callbacks */
944         ot->exec= constraint_move_down_exec;
945         ot->invoke= constraint_move_down_invoke;
946         ot->poll= edit_constraint_poll;
947         
948         /* flags */
949         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; 
950         edit_constraint_properties(ot);
951 }
952
953
954 static int constraint_move_up_exec (bContext *C, wmOperator *op)
955 {
956         Object *ob = ED_object_active_context(C);
957         bConstraint *con = edit_constraint_property_get(op, ob, 0);
958         
959         if (con && con->prev) {
960                 ListBase *conlist= get_constraint_lb(ob, con, NULL);
961                 bConstraint *prevCon= con->prev;
962                 
963                 /* insert the nominated constraint before the one that used to be before it */
964                 BLI_remlink(conlist, con);
965                 BLI_insertlinkbefore(conlist, prevCon, con);
966                 
967                 WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
968                 
969                 return OPERATOR_FINISHED;
970         }
971         
972         return OPERATOR_CANCELLED;
973 }
974
975 static int constraint_move_up_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
976 {
977         if (edit_constraint_invoke_properties(C, op))
978                 return constraint_move_up_exec(C, op);
979         else
980                 return OPERATOR_CANCELLED;
981 }
982
983 void CONSTRAINT_OT_move_up (wmOperatorType *ot)
984 {
985         /* identifiers */
986         ot->name= "Move Constraint Up";
987         ot->idname= "CONSTRAINT_OT_move_up";
988         ot->description= "Move constraint up in constraint stack";
989         
990         /* callbacks */
991         ot->exec= constraint_move_up_exec;
992         ot->invoke= constraint_move_up_invoke;
993         ot->poll= edit_constraint_poll;
994         
995         /* flags */
996         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; 
997         edit_constraint_properties(ot);
998 }
999
1000 /***************************** OPERATORS ****************************/
1001
1002 /************************ remove constraint operators *********************/
1003
1004 static int pose_constraints_clear_exec(bContext *C, wmOperator *UNUSED(op))
1005 {
1006         Main *bmain= CTX_data_main(C);
1007         Scene *scene= CTX_data_scene(C);
1008         Object *ob= object_pose_armature_get(CTX_data_active_object(C));
1009         
1010         /* free constraints for all selected bones */
1011         CTX_DATA_BEGIN(C, bPoseChannel*, pchan, selected_pose_bones)
1012         {
1013                 free_constraints(&pchan->constraints);
1014                 pchan->constflag &= ~(PCHAN_HAS_IK|PCHAN_HAS_SPLINEIK|PCHAN_HAS_CONST);
1015         }
1016         CTX_DATA_END;
1017         
1018         /* force depsgraph to get recalculated since relationships removed */
1019         DAG_scene_sort(bmain, scene);           /* sort order of objects */     
1020         
1021         /* note, calling BIK_clear_data() isnt needed here */
1022
1023         /* do updates */
1024         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
1025         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
1026         
1027         return OPERATOR_FINISHED;
1028 }
1029
1030 void POSE_OT_constraints_clear(wmOperatorType *ot)
1031 {
1032         /* identifiers */
1033         ot->name = "Clear Pose Constraints";
1034         ot->idname= "POSE_OT_constraints_clear";
1035         ot->description= "Clear all the constraints for the selected bones";
1036         
1037         /* callbacks */
1038         ot->exec= pose_constraints_clear_exec;
1039         ot->poll= ED_operator_posemode; // XXX - do we want to ensure there are selected bones too?
1040 }
1041
1042
1043 static int object_constraints_clear_exec(bContext *C, wmOperator *UNUSED(op))
1044 {
1045         Main *bmain= CTX_data_main(C);
1046         Scene *scene= CTX_data_scene(C);
1047         
1048         /* do freeing */
1049         CTX_DATA_BEGIN(C, Object*, ob, selected_editable_objects) 
1050         {
1051                 free_constraints(&ob->constraints);
1052                 DAG_id_tag_update(&ob->id, OB_RECALC_OB);
1053         }
1054         CTX_DATA_END;
1055         
1056         /* force depsgraph to get recalculated since relationships removed */
1057         DAG_scene_sort(bmain, scene);           /* sort order of objects */     
1058         
1059         /* do updates */
1060         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, NULL);
1061         
1062         return OPERATOR_FINISHED;
1063 }
1064
1065 void OBJECT_OT_constraints_clear(wmOperatorType *ot)
1066 {
1067         /* identifiers */
1068         ot->name = "Clear Object Constraints";
1069         ot->idname= "OBJECT_OT_constraints_clear";
1070         ot->description= "Clear all the constraints for the active Object only";
1071         
1072         /* callbacks */
1073         ot->exec= object_constraints_clear_exec;
1074         ot->poll= ED_operator_object_active_editable;
1075 }
1076
1077 /************************ copy all constraints operators *********************/
1078
1079 static int pose_constraint_copy_exec(bContext *C, wmOperator *op)
1080 {
1081         Main *bmain= CTX_data_main(C);
1082         Scene *scene = CTX_data_scene(C);
1083         bPoseChannel *pchan = CTX_data_active_pose_bone(C);
1084         
1085         /* don't do anything if bone doesn't exist or doesn't have any constraints */
1086         if (ELEM(NULL, pchan, pchan->constraints.first)) {
1087                 BKE_report(op->reports, RPT_ERROR, "No active bone with constraints for copying");
1088                 return OPERATOR_CANCELLED;
1089         }
1090         
1091         /* copy all constraints from active posebone to all selected posebones */
1092         CTX_DATA_BEGIN(C, bPoseChannel*, chan, selected_pose_bones) 
1093         {
1094                 /* if we're not handling the object we're copying from, copy all constraints over */
1095                 if (pchan != chan) {
1096                         copy_constraints(&chan->constraints, &pchan->constraints, TRUE);
1097                         /* update flags (need to add here, not just copy) */
1098                         chan->constflag |= pchan->constflag;
1099                 }
1100         }
1101         CTX_DATA_END;
1102         
1103         /* force depsgraph to get recalculated since new relationships added */
1104         DAG_scene_sort(bmain, scene);           /* sort order of objects/bones */
1105
1106         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, NULL);
1107         
1108         return OPERATOR_FINISHED;
1109 }
1110
1111 void POSE_OT_constraints_copy(wmOperatorType *ot)
1112 {
1113         /* identifiers */
1114         ot->name= "Copy Constraints to Selected";
1115         ot->idname= "POSE_OT_constraints_copy";
1116         ot->description = "Copy constraints to other selected bones";
1117         
1118         /* api callbacks */
1119         ot->exec= pose_constraint_copy_exec;
1120         ot->poll= ED_operator_posemode;
1121
1122         /* flags */
1123         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1124 }
1125
1126 static int object_constraint_copy_exec(bContext *C, wmOperator *UNUSED(op))
1127 {
1128         Main *bmain= CTX_data_main(C);
1129         Scene *scene = CTX_data_scene(C);
1130         Object *obact = ED_object_active_context(C);
1131         
1132         /* copy all constraints from active object to all selected objects */
1133         CTX_DATA_BEGIN(C, Object*, ob, selected_editable_objects) 
1134         {
1135                 /* if we're not handling the object we're copying from, copy all constraints over */
1136                 if (obact != ob) {
1137                         copy_constraints(&ob->constraints, &obact->constraints, TRUE);
1138                         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
1139                 }
1140         }
1141         CTX_DATA_END;
1142         
1143         /* force depsgraph to get recalculated since new relationships added */
1144         DAG_scene_sort(bmain, scene);           /* sort order of objects */
1145         
1146         /* notifiers for updates */
1147         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT|NA_ADDED, NULL);
1148         
1149         return OPERATOR_FINISHED;
1150 }
1151
1152 void OBJECT_OT_constraints_copy(wmOperatorType *ot)
1153 {
1154         /* identifiers */
1155         ot->name= "Copy Constraints to Selected";
1156         ot->idname= "OBJECT_OT_constraints_copy";
1157         ot->description = "Copy constraints to other selected objects";
1158         
1159         /* api callbacks */
1160         ot->exec= object_constraint_copy_exec;
1161         ot->poll= ED_operator_object_active_editable;
1162
1163         /* flags */
1164         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1165 }
1166
1167 /************************ add constraint operators *********************/
1168
1169 /* get the Object and/or PoseChannel to use as target */
1170 static short get_new_constraint_target(bContext *C, int con_type, Object **tar_ob, bPoseChannel **tar_pchan, short add)
1171 {
1172         Object *obact= ED_object_active_context(C);
1173         bPoseChannel *pchanact= get_active_posechannel(obact);
1174         short only_curve= 0, only_mesh= 0, only_ob= 0;
1175         short found= 0;
1176         
1177         /* clear tar_ob and tar_pchan fields before use 
1178          *      - assume for now that both always exist...
1179          */
1180         *tar_ob= NULL;
1181         *tar_pchan= NULL;
1182         
1183         /* check if constraint type doesn't requires a target
1184          *      - if so, no need to get any targets 
1185          */
1186         switch (con_type) {
1187                 /* no-target constraints --------------------------- */
1188                         /* null constraint - shouldn't even be added! */
1189                 case CONSTRAINT_TYPE_NULL:
1190                         /* limit constraints - no targets needed */
1191                 case CONSTRAINT_TYPE_LOCLIMIT:
1192                 case CONSTRAINT_TYPE_ROTLIMIT:
1193                 case CONSTRAINT_TYPE_SIZELIMIT:
1194                 case CONSTRAINT_TYPE_SAMEVOL:
1195                         return 0;
1196                         
1197                 /* restricted target-type constraints -------------- */
1198                 /* NOTE: for these, we cannot try to add a target object if no valid ones are found, since that doesn't work */
1199                         /* curve-based constraints - set the only_curve and only_ob flags */
1200                 case CONSTRAINT_TYPE_CLAMPTO:
1201                 case CONSTRAINT_TYPE_FOLLOWPATH:
1202                 case CONSTRAINT_TYPE_SPLINEIK:
1203                         only_curve= 1;
1204                         only_ob= 1;
1205                         add= 0;
1206                         break;
1207                         
1208                         /* mesh only? */
1209                 case CONSTRAINT_TYPE_SHRINKWRAP:
1210                         only_mesh= 1;
1211                         only_ob= 1;
1212                         add= 0;
1213                         break;
1214                         
1215                         /* object only - add here is ok? */
1216                 case CONSTRAINT_TYPE_RIGIDBODYJOINT:
1217                         only_ob= 1;
1218                         break;
1219         }
1220         
1221         /* if the active Object is Armature, and we can search for bones, do so... */
1222         if ((obact->type == OB_ARMATURE) && (only_ob == 0)) {
1223                 /* search in list of selected Pose-Channels for target */
1224                 CTX_DATA_BEGIN(C, bPoseChannel*, pchan, selected_pose_bones) 
1225                 {
1226                         /* just use the first one that we encounter, as long as it is not the active one */
1227                         if (pchan != pchanact) {
1228                                 *tar_ob= obact;
1229                                 *tar_pchan= pchan;
1230                                 found= 1;
1231                                 
1232                                 break;
1233                         }
1234                 }
1235                 CTX_DATA_END;
1236         }
1237         
1238         /* if not yet found, try selected Objects... */
1239         if (found == 0) {
1240                 /* search in selected objects context */
1241                 CTX_DATA_BEGIN(C, Object*, ob, selected_objects) 
1242                 {
1243                         /* just use the first object we encounter (that isn't the active object) 
1244                          * and which fulfills the criteria for the object-target that we've got 
1245                          */
1246                         if ( (ob != obact) &&
1247                                  ((!only_curve) || (ob->type == OB_CURVE)) && 
1248                                  ((!only_mesh) || (ob->type == OB_MESH)) )
1249                         {
1250                                 /* set target */
1251                                 *tar_ob= ob;
1252                                 found= 1;
1253                                 
1254                                 /* perform some special operations on the target */
1255                                 if (only_curve) {
1256                                         /* Curve-Path option must be enabled for follow-path constraints to be able to work */
1257                                         Curve *cu= (Curve *)ob->data;
1258                                         cu->flag |= CU_PATH;
1259                                 }
1260                                 
1261                                 break;
1262                         }
1263                 }
1264                 CTX_DATA_END;
1265         }
1266         
1267         /* if still not found, add a new empty to act as a target (if allowed) */
1268         if ((found == 0) && (add)) {
1269                 Scene *scene= CTX_data_scene(C);
1270                 Base *base= BASACT, *newbase=NULL;
1271                 Object *obt;
1272                 
1273                 /* add new target object */
1274                 obt= add_object(scene, OB_EMPTY);
1275                 
1276                 /* set layers OK */
1277                 newbase= BASACT;
1278                 newbase->lay= base->lay;
1279                 obt->lay= newbase->lay;
1280                 
1281                 /* transform cent to global coords for loc */
1282                 if (pchanact) {
1283                         /* since by default, IK targets the tip of the last bone, use the tip of the active PoseChannel 
1284                          * if adding a target for an IK Constraint
1285                          */
1286                         if (con_type == CONSTRAINT_TYPE_KINEMATIC)
1287                                 mul_v3_m4v3(obt->loc, obact->obmat, pchanact->pose_tail);
1288                         else
1289                                 mul_v3_m4v3(obt->loc, obact->obmat, pchanact->pose_head);
1290                 }
1291                 else
1292                         VECCOPY(obt->loc, obact->obmat[3]);
1293                 
1294                 /* restore, add_object sets active */
1295                 BASACT= base;
1296                 base->flag |= SELECT;
1297                 
1298                 /* make our new target the new object */
1299                 *tar_ob= obt;
1300                 found= 1;
1301         }
1302         
1303         /* return whether there's any target */
1304         return found;
1305 }
1306
1307 /* used by add constraint operators to add the constraint required */
1308 static int constraint_add_exec(bContext *C, wmOperator *op, Object *ob, ListBase *list, int type, short setTarget)
1309 {
1310         Main *bmain= CTX_data_main(C);
1311         Scene *scene= CTX_data_scene(C);
1312         bPoseChannel *pchan;
1313         bConstraint *con;
1314         
1315         if (list == &ob->constraints) {
1316                 pchan= NULL;
1317         }
1318         else {
1319                 pchan= get_active_posechannel(ob);
1320                 
1321                 /* ensure not to confuse object/pose adding */
1322                 if (pchan == NULL) {
1323                         BKE_report(op->reports, RPT_ERROR, "No active pose bone to add a constraint to");
1324                         return OPERATOR_CANCELLED;
1325                 }
1326         }
1327         /* check if constraint to be added is valid for the given constraints stack */
1328         if (type == CONSTRAINT_TYPE_NULL) {
1329                 return OPERATOR_CANCELLED;
1330         }
1331         if ( (type == CONSTRAINT_TYPE_RIGIDBODYJOINT) && (list != &ob->constraints) ) {
1332                 BKE_report(op->reports, RPT_ERROR, "Rigid Body Joint Constraint can only be added to Objects");
1333                 return OPERATOR_CANCELLED;
1334         }
1335         if ( (type == CONSTRAINT_TYPE_KINEMATIC) && ((!pchan) || (list != &pchan->constraints)) ) {
1336                 BKE_report(op->reports, RPT_ERROR, "IK Constraint can only be added to Bones");
1337                 return OPERATOR_CANCELLED;
1338         }
1339         if ( (type == CONSTRAINT_TYPE_SPLINEIK) && ((!pchan) || (list != &pchan->constraints)) ) {
1340                 BKE_report(op->reports, RPT_ERROR, "Spline IK Constraint can only be added to Bones");
1341                 return OPERATOR_CANCELLED;
1342         }
1343         
1344         /* create a new constraint of the type requried, and add it to the active/given constraints list */
1345         if (pchan)
1346                 con = add_pose_constraint(ob, pchan, NULL, type);
1347         else
1348                 con = add_ob_constraint(ob, NULL, type);
1349         
1350         /* get the first selected object/bone, and make that the target
1351          *      - apart from the buttons-window add buttons, we shouldn't add in this way
1352          */
1353         if (setTarget) {
1354                 Object *tar_ob= NULL;
1355                 bPoseChannel *tar_pchan= NULL;
1356                 
1357                 /* get the target objects, adding them as need be */
1358                 if (get_new_constraint_target(C, type, &tar_ob, &tar_pchan, 1)) {
1359                         /* method of setting target depends on the type of target we've got 
1360                          *      - by default, just set the first target (distinction here is only for multiple-targetted constraints)
1361                          */
1362                         if (tar_pchan)
1363                                 set_constraint_nth_target(con, tar_ob, tar_pchan->name, 0);
1364                         else
1365                                 set_constraint_nth_target(con, tar_ob, "", 0);
1366                 }
1367         }
1368         
1369         /* do type-specific tweaking to the constraint settings  */
1370         switch (type) {
1371                 case CONSTRAINT_TYPE_PYTHON: // FIXME: this code is not really valid anymore
1372                 {
1373 #ifdef WITH_PYTHON
1374                         char *menustr;
1375                         int scriptint= 0;
1376                         /* popup a list of usable scripts */
1377                         menustr = buildmenu_pyconstraints(NULL, &scriptint);
1378                         // XXX scriptint = pupmenu(menustr);
1379                         MEM_freeN(menustr);
1380                         
1381                         /* only add constraint if a script was chosen */
1382                         if (scriptint) {
1383                                 /* add constraint */
1384                                 validate_pyconstraint_cb(con->data, &scriptint);
1385                                 
1386                                 /* make sure target allowance is set correctly */
1387                                 BPY_pyconstraint_update(ob, con);
1388                         }
1389 #endif
1390                         break;
1391                 }
1392
1393                 default:
1394                         break;
1395         }
1396         
1397         /* make sure all settings are valid - similar to above checks, but sometimes can be wrong */
1398         object_test_constraints(ob);
1399
1400         if (pchan)
1401                 update_pose_constraint_flags(ob->pose);
1402
1403
1404         /* force depsgraph to get recalculated since new relationships added */
1405         DAG_scene_sort(bmain, scene);           /* sort order of objects */
1406         
1407         if ((ob->type==OB_ARMATURE) && (pchan)) {
1408                 ob->pose->flag |= POSE_RECALC;  /* sort pose channels */
1409                 DAG_id_tag_update(&ob->id, OB_RECALC_DATA|OB_RECALC_OB);
1410         }
1411         else
1412                 DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
1413         
1414         /* notifiers for updates */
1415         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT|NA_ADDED, ob);
1416         
1417         return OPERATOR_FINISHED;
1418 }
1419
1420 /* ------------------ */
1421
1422 /* dummy operator callback */
1423 static int object_constraint_add_exec(bContext *C, wmOperator *op)
1424 {
1425         Object *ob=ED_object_active_context(C);
1426         int type= RNA_enum_get(op->ptr, "type");
1427         short with_targets= 0;
1428         
1429         if (!ob) {
1430                 BKE_report(op->reports, RPT_ERROR, "No active object to add constraint to");
1431                 return OPERATOR_CANCELLED;
1432         }
1433                 
1434         /* hack: set constraint targets from selected objects in context is allowed when
1435          *              operator name included 'with_targets', since the menu doesn't allow multiple properties
1436          */
1437         if (strstr(op->idname, "with_targets"))
1438                 with_targets= 1;
1439
1440         return constraint_add_exec(C, op, ob, &ob->constraints, type, with_targets);
1441 }
1442
1443 /* dummy operator callback */
1444 static int pose_constraint_add_exec(bContext *C, wmOperator *op)
1445 {
1446         Object *ob= object_pose_armature_get(ED_object_active_context(C));
1447         int type= RNA_enum_get(op->ptr, "type");
1448         short with_targets= 0;
1449         
1450         if (!ob) {
1451                 BKE_report(op->reports, RPT_ERROR, "No active object to add constraint to");
1452                 return OPERATOR_CANCELLED;
1453         }
1454                 
1455         /* hack: set constraint targets from selected objects in context is allowed when
1456          *              operator name included 'with_targets', since the menu doesn't allow multiple properties
1457          */
1458         if (strstr(op->idname, "with_targets"))
1459                 with_targets= 1;
1460         
1461         return constraint_add_exec(C, op, ob, get_active_constraints(ob), type, with_targets);
1462 }
1463
1464 /* ------------------ */
1465
1466 void OBJECT_OT_constraint_add(wmOperatorType *ot)
1467 {
1468         /* identifiers */
1469         ot->name= "Add Constraint";
1470         ot->description = "Add a constraint to the active object";
1471         ot->idname= "OBJECT_OT_constraint_add";
1472         
1473         /* api callbacks */
1474         ot->invoke= WM_menu_invoke;
1475         ot->exec= object_constraint_add_exec;
1476         ot->poll= ED_operator_object_active_editable;
1477         
1478         /* flags */
1479         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1480         
1481         /* properties */
1482         ot->prop= RNA_def_enum(ot->srna, "type", constraint_type_items, 0, "Type", "");
1483 }
1484
1485 void OBJECT_OT_constraint_add_with_targets(wmOperatorType *ot)
1486 {
1487         /* identifiers */
1488         ot->name= "Add Constraint (with Targets)";
1489         ot->description = "Add a constraint to the active object, with target (where applicable) set to the selected Objects/Bones";
1490         ot->idname= "OBJECT_OT_constraint_add_with_targets";
1491         
1492         /* api callbacks */
1493         ot->invoke= WM_menu_invoke;
1494         ot->exec= object_constraint_add_exec;
1495         ot->poll= ED_operator_object_active_editable;
1496         
1497         /* flags */
1498         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1499         
1500         /* properties */
1501         ot->prop= RNA_def_enum(ot->srna, "type", constraint_type_items, 0, "Type", "");
1502 }
1503
1504 void POSE_OT_constraint_add(wmOperatorType *ot)
1505 {
1506         /* identifiers */
1507         ot->name= "Add Constraint";
1508         ot->description = "Add a constraint to the active bone";
1509         ot->idname= "POSE_OT_constraint_add";
1510         
1511         /* api callbacks */
1512         ot->invoke= WM_menu_invoke;
1513         ot->exec= pose_constraint_add_exec;
1514         ot->poll= ED_operator_posemode;
1515         
1516         /* flags */
1517         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1518         
1519         /* properties */
1520         ot->prop= RNA_def_enum(ot->srna, "type", constraint_type_items, 0, "Type", "");
1521 }
1522
1523 void POSE_OT_constraint_add_with_targets(wmOperatorType *ot)
1524 {
1525         /* identifiers */
1526         ot->name= "Add Constraint (with Targets)";
1527         ot->description = "Add a constraint to the active bone, with target (where applicable) set to the selected Objects/Bones";
1528         ot->idname= "POSE_OT_constraint_add_with_targets";
1529         
1530         /* api callbacks */
1531         ot->invoke= WM_menu_invoke;
1532         ot->exec= pose_constraint_add_exec;
1533         ot->poll= ED_operator_posemode;
1534         
1535         /* flags */
1536         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1537         
1538         /* properties */
1539         ot->prop= RNA_def_enum(ot->srna, "type", constraint_type_items, 0, "Type", "");
1540 }
1541
1542 /************************ IK Constraint operators *********************/
1543 /* NOTE: only for Pose-Channels */
1544 // TODO: should these be here, or back in editors/armature/poseobject.c again?
1545
1546 /* present menu with options + validation for targets to use */
1547 static int pose_ik_add_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(evt))
1548 {
1549         Object *ob= object_pose_armature_get(CTX_data_active_object(C));
1550         bPoseChannel *pchan= get_active_posechannel(ob);
1551         bConstraint *con= NULL;
1552         
1553         uiPopupMenu *pup;
1554         uiLayout *layout;
1555         Object *tar_ob= NULL;
1556         bPoseChannel *tar_pchan= NULL;
1557         
1558         /* must have active bone */
1559         if (ELEM(NULL, ob, pchan)) {
1560                 BKE_report(op->reports, RPT_ERROR, "Must have active bone to add IK Constraint to");
1561                 return OPERATOR_CANCELLED;
1562         }
1563         
1564         /* bone must not have any constraints already */
1565         for (con= pchan->constraints.first; con; con= con->next) {
1566                 if (con->type==CONSTRAINT_TYPE_KINEMATIC) break;
1567         }
1568         if (con) {
1569                 BKE_report(op->reports, RPT_ERROR, "Bone already has IK Constraint");
1570                 return OPERATOR_CANCELLED;
1571         }
1572         
1573         /* prepare popup menu to choose targetting options */
1574         pup= uiPupMenuBegin(C, "Add IK", ICON_NONE);
1575         layout= uiPupMenuLayout(pup);
1576         
1577         /* the type of targets we'll set determines the menu entries to show... */
1578         if (get_new_constraint_target(C, CONSTRAINT_TYPE_KINEMATIC, &tar_ob, &tar_pchan, 0)) {
1579                 /* bone target, or object target? 
1580                  *      - the only thing that matters is that we want a target...
1581                  */
1582                 if (tar_pchan)
1583                         uiItemBooleanO(layout, "To Active Bone", ICON_NONE, "POSE_OT_ik_add", "with_targets", 1);
1584                 else
1585                         uiItemBooleanO(layout, "To Active Object", ICON_NONE, "POSE_OT_ik_add", "with_targets", 1);
1586         }
1587         else {
1588                 /* we have a choice of adding to a new empty, or not setting any target (targetless IK) */
1589                 uiItemBooleanO(layout, "To New Empty Object", ICON_NONE, "POSE_OT_ik_add", "with_targets", 1);
1590                 uiItemBooleanO(layout, "Without Targets", ICON_NONE, "POSE_OT_ik_add", "with_targets", 0);
1591         }
1592         
1593         /* finish building the menu, and process it (should result in calling self again) */
1594         uiPupMenuEnd(C, pup);
1595         
1596         return OPERATOR_CANCELLED;
1597 }
1598
1599 /* call constraint_add_exec() to add the IK constraint */
1600 static int pose_ik_add_exec(bContext *C, wmOperator *op)
1601 {
1602         Object *ob= CTX_data_active_object(C);
1603         int with_targets= RNA_boolean_get(op->ptr, "with_targets");
1604         
1605         /* add the constraint - all necessary checks should have been done by the invoke() callback already... */
1606         return constraint_add_exec(C, op, ob, get_active_constraints(ob), CONSTRAINT_TYPE_KINEMATIC, with_targets);
1607 }
1608
1609 void POSE_OT_ik_add(wmOperatorType *ot)
1610 {
1611         /* identifiers */
1612         ot->name= "Add IK to Bone";
1613         ot->description= "Add IK Constraint to the active Bone";
1614         ot->idname= "POSE_OT_ik_add";
1615         
1616         /* api callbacks */
1617         ot->invoke= pose_ik_add_invoke;
1618         ot->exec= pose_ik_add_exec;
1619         ot->poll= ED_operator_posemode;
1620         
1621         /* flags */
1622         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1623         
1624         /* properties */
1625         RNA_def_boolean(ot->srna, "with_targets", 1, "With Targets", "Assign IK Constraint with targets derived from the select bones/objects");
1626 }
1627
1628 /* ------------------ */
1629
1630 /* remove IK constraints from selected bones */
1631 static int pose_ik_clear_exec(bContext *C, wmOperator *UNUSED(op))
1632 {
1633         Object *ob= object_pose_armature_get(CTX_data_active_object(C));
1634         
1635         /* only remove IK Constraints */
1636         CTX_DATA_BEGIN(C, bPoseChannel*, pchan, selected_pose_bones) 
1637         {
1638                 bConstraint *con, *next;
1639                 
1640                 // TODO: should we be checking if these contraints were local before we try and remove them?
1641                 for (con= pchan->constraints.first; con; con= next) {
1642                         next= con->next;
1643                         if (con->type==CONSTRAINT_TYPE_KINEMATIC) {
1644                                 remove_constraint(&pchan->constraints, con);
1645                         }
1646                 }
1647                 pchan->constflag &= ~(PCHAN_HAS_IK|PCHAN_HAS_TARGET);
1648         }
1649         CTX_DATA_END;
1650         
1651         /* refresh depsgraph */
1652         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
1653
1654         /* note, notifier might evolve */
1655         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT|NA_REMOVED, ob);
1656         
1657         return OPERATOR_FINISHED;
1658 }
1659
1660 void POSE_OT_ik_clear(wmOperatorType *ot)
1661 {
1662         /* identifiers */
1663         ot->name= "Remove IK";
1664         ot->description= "Remove all IK Constraints from selected bones";
1665         ot->idname= "POSE_OT_ik_clear";
1666         
1667         /* api callbacks */
1668         ot->exec= pose_ik_clear_exec;
1669         ot->poll= ED_operator_posemode;
1670         
1671         /* flags */
1672         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1673 }
1674