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