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