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