=bmesh= merge from trunk at r36529
[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         const short is_ik= ELEM(con->type, CONSTRAINT_TYPE_KINEMATIC, CONSTRAINT_TYPE_SPLINEIK);
848
849         /* free the constraint */
850         if (remove_constraint(lb, con)) {
851                 /* there's no active constraint now, so make sure this is the case */
852                 constraints_set_active(lb, NULL);
853                 
854                 ED_object_constraint_update(ob); /* needed to set the flags on posebones correctly */
855
856                 /* ITASC needs to be rebuilt once a constraint is removed [#26920] */
857                 if(is_ik) {
858                         BIK_clear_data(ob->pose);
859                 }
860
861                 /* notifiers */
862                 WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT|NA_REMOVED, ob);
863                 
864                 return OPERATOR_FINISHED;
865         }
866         else {
867                 /* couldn't remove due to some invalid data */
868                 return OPERATOR_CANCELLED;
869         }
870 }
871
872 void CONSTRAINT_OT_delete (wmOperatorType *ot)
873 {
874         /* identifiers */
875         ot->name= "Delete Constraint";
876         ot->idname= "CONSTRAINT_OT_delete";
877         ot->description= "Remove constraint from constraint stack";
878         
879         /* callbacks */
880         ot->exec= constraint_delete_exec;
881         ot->poll= constraint_poll;
882         
883         /* flags */
884         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; 
885 }
886
887 static int constraint_move_down_exec (bContext *C, wmOperator *op)
888 {
889         Object *ob = ED_object_active_context(C);
890         bConstraint *con = edit_constraint_property_get(op, ob, 0);
891         
892         if (con && con->next) {
893                 ListBase *conlist= get_constraint_lb(ob, con, NULL);
894                 bConstraint *nextCon= con->next;
895                 
896                 /* insert the nominated constraint after the one that used to be after it */
897                 BLI_remlink(conlist, con);
898                 BLI_insertlinkafter(conlist, nextCon, con);
899                 
900                 WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
901                 
902                 return OPERATOR_FINISHED;
903         }
904         
905         return OPERATOR_CANCELLED;
906 }
907
908 static int constraint_move_down_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
909 {
910         if (edit_constraint_invoke_properties(C, op))
911                 return constraint_move_down_exec(C, op);
912         else
913                 return OPERATOR_CANCELLED;
914 }
915
916
917 void CONSTRAINT_OT_move_down (wmOperatorType *ot)
918 {
919         /* identifiers */
920         ot->name= "Move Constraint Down";
921         ot->idname= "CONSTRAINT_OT_move_down";
922         ot->description= "Move constraint down in constraint stack";
923         
924         /* callbacks */
925         ot->exec= constraint_move_down_exec;
926         ot->invoke= constraint_move_down_invoke;
927         ot->poll= edit_constraint_poll;
928         
929         /* flags */
930         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; 
931         edit_constraint_properties(ot);
932 }
933
934
935 static int constraint_move_up_exec (bContext *C, wmOperator *op)
936 {
937         Object *ob = ED_object_active_context(C);
938         bConstraint *con = edit_constraint_property_get(op, ob, 0);
939         
940         if (con && con->prev) {
941                 ListBase *conlist= get_constraint_lb(ob, con, NULL);
942                 bConstraint *prevCon= con->prev;
943                 
944                 /* insert the nominated constraint before the one that used to be before it */
945                 BLI_remlink(conlist, con);
946                 BLI_insertlinkbefore(conlist, prevCon, con);
947                 
948                 WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
949                 
950                 return OPERATOR_FINISHED;
951         }
952         
953         return OPERATOR_CANCELLED;
954 }
955
956 static int constraint_move_up_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
957 {
958         if (edit_constraint_invoke_properties(C, op))
959                 return constraint_move_up_exec(C, op);
960         else
961                 return OPERATOR_CANCELLED;
962 }
963
964 void CONSTRAINT_OT_move_up (wmOperatorType *ot)
965 {
966         /* identifiers */
967         ot->name= "Move Constraint Up";
968         ot->idname= "CONSTRAINT_OT_move_up";
969         ot->description= "Move constraint up in constraint stack";
970         
971         /* callbacks */
972         ot->exec= constraint_move_up_exec;
973         ot->invoke= constraint_move_up_invoke;
974         ot->poll= edit_constraint_poll;
975         
976         /* flags */
977         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; 
978         edit_constraint_properties(ot);
979 }
980
981 /***************************** OPERATORS ****************************/
982
983 /************************ remove constraint operators *********************/
984
985 static int pose_constraints_clear_exec(bContext *C, wmOperator *UNUSED(op))
986 {
987         Main *bmain= CTX_data_main(C);
988         Scene *scene= CTX_data_scene(C);
989         Object *ob= ED_object_pose_armature(CTX_data_active_object(C));
990         
991         /* free constraints for all selected bones */
992         CTX_DATA_BEGIN(C, bPoseChannel*, pchan, selected_pose_bones)
993         {
994                 free_constraints(&pchan->constraints);
995                 pchan->constflag &= ~(PCHAN_HAS_IK|PCHAN_HAS_SPLINEIK|PCHAN_HAS_CONST);
996         }
997         CTX_DATA_END;
998         
999         /* force depsgraph to get recalculated since relationships removed */
1000         DAG_scene_sort(bmain, scene);           /* sort order of objects */     
1001         
1002         /* note, calling BIK_clear_data() isnt needed here */
1003
1004         /* do updates */
1005         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
1006         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, ob);
1007         
1008         return OPERATOR_FINISHED;
1009 }
1010
1011 void POSE_OT_constraints_clear(wmOperatorType *ot)
1012 {
1013         /* identifiers */
1014         ot->name = "Clear Pose Constraints";
1015         ot->idname= "POSE_OT_constraints_clear";
1016         ot->description= "Clear all the constraints for the selected bones";
1017         
1018         /* callbacks */
1019         ot->exec= pose_constraints_clear_exec;
1020         ot->poll= ED_operator_posemode; // XXX - do we want to ensure there are selected bones too?
1021 }
1022
1023
1024 static int object_constraints_clear_exec(bContext *C, wmOperator *UNUSED(op))
1025 {
1026         Main *bmain= CTX_data_main(C);
1027         Scene *scene= CTX_data_scene(C);
1028         
1029         /* do freeing */
1030         CTX_DATA_BEGIN(C, Object*, ob, selected_editable_objects) 
1031         {
1032                 free_constraints(&ob->constraints);
1033                 DAG_id_tag_update(&ob->id, OB_RECALC_OB);
1034         }
1035         CTX_DATA_END;
1036         
1037         /* force depsgraph to get recalculated since relationships removed */
1038         DAG_scene_sort(bmain, scene);           /* sort order of objects */     
1039         
1040         /* do updates */
1041         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, NULL);
1042         
1043         return OPERATOR_FINISHED;
1044 }
1045
1046 void OBJECT_OT_constraints_clear(wmOperatorType *ot)
1047 {
1048         /* identifiers */
1049         ot->name = "Clear Object Constraints";
1050         ot->idname= "OBJECT_OT_constraints_clear";
1051         ot->description= "Clear all the constraints for the active Object only";
1052         
1053         /* callbacks */
1054         ot->exec= object_constraints_clear_exec;
1055         ot->poll= ED_operator_object_active_editable;
1056 }
1057
1058 /************************ copy all constraints operators *********************/
1059
1060 static int pose_constraint_copy_exec(bContext *C, wmOperator *op)
1061 {
1062         Main *bmain= CTX_data_main(C);
1063         Scene *scene = CTX_data_scene(C);
1064         bPoseChannel *pchan = CTX_data_active_pose_bone(C);
1065         
1066         /* don't do anything if bone doesn't exist or doesn't have any constraints */
1067         if (ELEM(NULL, pchan, pchan->constraints.first)) {
1068                 BKE_report(op->reports, RPT_ERROR, "No active bone with constraints for copying");
1069                 return OPERATOR_CANCELLED;
1070         }
1071         
1072         /* copy all constraints from active posebone to all selected posebones */
1073         CTX_DATA_BEGIN(C, bPoseChannel*, chan, selected_pose_bones) 
1074         {
1075                 /* if we're not handling the object we're copying from, copy all constraints over */
1076                 if (pchan != chan) {
1077                         copy_constraints(&chan->constraints, &pchan->constraints, TRUE);
1078                         /* update flags (need to add here, not just copy) */
1079                         chan->constflag |= pchan->constflag;
1080                 }
1081         }
1082         CTX_DATA_END;
1083         
1084         /* force depsgraph to get recalculated since new relationships added */
1085         DAG_scene_sort(bmain, scene);           /* sort order of objects/bones */
1086
1087         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT, NULL);
1088         
1089         return OPERATOR_FINISHED;
1090 }
1091
1092 void POSE_OT_constraints_copy(wmOperatorType *ot)
1093 {
1094         /* identifiers */
1095         ot->name= "Copy Constraints to Selected";
1096         ot->idname= "POSE_OT_constraints_copy";
1097         ot->description = "Copy constraints to other selected bones.";
1098         
1099         /* api callbacks */
1100         ot->exec= pose_constraint_copy_exec;
1101         ot->poll= ED_operator_posemode;
1102
1103         /* flags */
1104         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1105 }
1106
1107 static int object_constraint_copy_exec(bContext *C, wmOperator *UNUSED(op))
1108 {
1109         Main *bmain= CTX_data_main(C);
1110         Scene *scene = CTX_data_scene(C);
1111         Object *obact = ED_object_active_context(C);
1112         
1113         /* copy all constraints from active object to all selected objects */
1114         CTX_DATA_BEGIN(C, Object*, ob, selected_editable_objects) 
1115         {
1116                 /* if we're not handling the object we're copying from, copy all constraints over */
1117                 if (obact != ob)
1118                         copy_constraints(&ob->constraints, &obact->constraints, TRUE);
1119         }
1120         CTX_DATA_END;
1121         
1122         /* force depsgraph to get recalculated since new relationships added */
1123         DAG_scene_sort(bmain, scene);           /* sort order of objects */
1124
1125         return OPERATOR_FINISHED;
1126 }
1127
1128 void OBJECT_OT_constraints_copy(wmOperatorType *ot)
1129 {
1130         /* identifiers */
1131         ot->name= "Copy Constraints to Selected";
1132         ot->idname= "OBJECT_OT_constraints_copy";
1133         ot->description = "Copy constraints to other selected objects.";
1134         
1135         /* api callbacks */
1136         ot->exec= object_constraint_copy_exec;
1137         ot->poll= ED_operator_object_active_editable;
1138
1139         /* flags */
1140         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1141 }
1142
1143 /************************ add constraint operators *********************/
1144
1145 /* get the Object and/or PoseChannel to use as target */
1146 static short get_new_constraint_target(bContext *C, int con_type, Object **tar_ob, bPoseChannel **tar_pchan, short add)
1147 {
1148         Object *obact= ED_object_active_context(C);
1149         bPoseChannel *pchanact= get_active_posechannel(obact);
1150         short only_curve= 0, only_mesh= 0, only_ob= 0;
1151         short found= 0;
1152         
1153         /* clear tar_ob and tar_pchan fields before use 
1154          *      - assume for now that both always exist...
1155          */
1156         *tar_ob= NULL;
1157         *tar_pchan= NULL;
1158         
1159         /* check if constraint type doesn't requires a target
1160          *      - if so, no need to get any targets 
1161          */
1162         switch (con_type) {
1163                 /* no-target constraints --------------------------- */
1164                         /* null constraint - shouldn't even be added! */
1165                 case CONSTRAINT_TYPE_NULL:
1166                         /* limit constraints - no targets needed */
1167                 case CONSTRAINT_TYPE_LOCLIMIT:
1168                 case CONSTRAINT_TYPE_ROTLIMIT:
1169                 case CONSTRAINT_TYPE_SIZELIMIT:
1170                 case CONSTRAINT_TYPE_SAMEVOL:
1171                         return 0;
1172                         
1173                 /* restricted target-type constraints -------------- */
1174                 /* NOTE: for these, we cannot try to add a target object if no valid ones are found, since that doesn't work */
1175                         /* curve-based constraints - set the only_curve and only_ob flags */
1176                 case CONSTRAINT_TYPE_CLAMPTO:
1177                 case CONSTRAINT_TYPE_FOLLOWPATH:
1178                 case CONSTRAINT_TYPE_SPLINEIK:
1179                         only_curve= 1;
1180                         only_ob= 1;
1181                         add= 0;
1182                         break;
1183                         
1184                         /* mesh only? */
1185                 case CONSTRAINT_TYPE_SHRINKWRAP:
1186                         only_mesh= 1;
1187                         only_ob= 1;
1188                         add= 0;
1189                         break;
1190                         
1191                         /* object only - add here is ok? */
1192                 case CONSTRAINT_TYPE_RIGIDBODYJOINT:
1193                         only_ob= 1;
1194                         break;
1195         }
1196         
1197         /* if the active Object is Armature, and we can search for bones, do so... */
1198         if ((obact->type == OB_ARMATURE) && (only_ob == 0)) {
1199                 /* search in list of selected Pose-Channels for target */
1200                 CTX_DATA_BEGIN(C, bPoseChannel*, pchan, selected_pose_bones) 
1201                 {
1202                         /* just use the first one that we encounter, as long as it is not the active one */
1203                         if (pchan != pchanact) {
1204                                 *tar_ob= obact;
1205                                 *tar_pchan= pchan;
1206                                 found= 1;
1207                                 
1208                                 break;
1209                         }
1210                 }
1211                 CTX_DATA_END;
1212         }
1213         
1214         /* if not yet found, try selected Objects... */
1215         if (found == 0) {
1216                 /* search in selected objects context */
1217                 CTX_DATA_BEGIN(C, Object*, ob, selected_objects) 
1218                 {
1219                         /* just use the first object we encounter (that isn't the active object) 
1220                          * and which fulfills the criteria for the object-target that we've got 
1221                          */
1222                         if ( (ob != obact) &&
1223                                  ((!only_curve) || (ob->type == OB_CURVE)) && 
1224                                  ((!only_mesh) || (ob->type == OB_MESH)) )
1225                         {
1226                                 /* set target */
1227                                 *tar_ob= ob;
1228                                 found= 1;
1229                                 
1230                                 /* perform some special operations on the target */
1231                                 if (only_curve) {
1232                                         /* Curve-Path option must be enabled for follow-path constraints to be able to work */
1233                                         Curve *cu= (Curve *)ob->data;
1234                                         cu->flag |= CU_PATH;
1235                                 }
1236                                 
1237                                 break;
1238                         }
1239                 }
1240                 CTX_DATA_END;
1241         }
1242         
1243         /* if still not found, add a new empty to act as a target (if allowed) */
1244         if ((found == 0) && (add)) {
1245                 Scene *scene= CTX_data_scene(C);
1246                 Base *base= BASACT, *newbase=NULL;
1247                 Object *obt;
1248                 
1249                 /* add new target object */
1250                 obt= add_object(scene, OB_EMPTY);
1251                 
1252                 /* set layers OK */
1253                 newbase= BASACT;
1254                 newbase->lay= base->lay;
1255                 obt->lay= newbase->lay;
1256                 
1257                 /* transform cent to global coords for loc */
1258                 if (pchanact) {
1259                         /* since by default, IK targets the tip of the last bone, use the tip of the active PoseChannel 
1260                          * if adding a target for an IK Constraint
1261                          */
1262                         if (con_type == CONSTRAINT_TYPE_KINEMATIC)
1263                                 mul_v3_m4v3(obt->loc, obact->obmat, pchanact->pose_tail);
1264                         else
1265                                 mul_v3_m4v3(obt->loc, obact->obmat, pchanact->pose_head);
1266                 }
1267                 else
1268                         VECCOPY(obt->loc, obact->obmat[3]);
1269                 
1270                 /* restore, add_object sets active */
1271                 BASACT= base;
1272                 base->flag |= SELECT;
1273                 
1274                 /* make our new target the new object */
1275                 *tar_ob= obt;
1276                 found= 1;
1277         }
1278         
1279         /* return whether there's any target */
1280         return found;
1281 }
1282
1283 /* used by add constraint operators to add the constraint required */
1284 static int constraint_add_exec(bContext *C, wmOperator *op, Object *ob, ListBase *list, int type, short setTarget)
1285 {
1286         Main *bmain= CTX_data_main(C);
1287         Scene *scene= CTX_data_scene(C);
1288         bPoseChannel *pchan;
1289         bConstraint *con;
1290         
1291         if (list == &ob->constraints) {
1292                 pchan= NULL;
1293         }
1294         else {
1295                 pchan= get_active_posechannel(ob);
1296                 
1297                 /* ensure not to confuse object/pose adding */
1298                 if (pchan == NULL) {
1299                         BKE_report(op->reports, RPT_ERROR, "No active pose bone to add a constraint to.");
1300                         return OPERATOR_CANCELLED;
1301                 }
1302         }
1303         /* check if constraint to be added is valid for the given constraints stack */
1304         if (type == CONSTRAINT_TYPE_NULL) {
1305                 return OPERATOR_CANCELLED;
1306         }
1307         if ( (type == CONSTRAINT_TYPE_RIGIDBODYJOINT) && (list != &ob->constraints) ) {
1308                 BKE_report(op->reports, RPT_ERROR, "Rigid Body Joint Constraint can only be added to Objects.");
1309                 return OPERATOR_CANCELLED;
1310         }
1311         if ( (type == CONSTRAINT_TYPE_KINEMATIC) && ((!pchan) || (list != &pchan->constraints)) ) {
1312                 BKE_report(op->reports, RPT_ERROR, "IK Constraint can only be added to Bones.");
1313                 return OPERATOR_CANCELLED;
1314         }
1315         if ( (type == CONSTRAINT_TYPE_SPLINEIK) && ((!pchan) || (list != &pchan->constraints)) ) {
1316                 BKE_report(op->reports, RPT_ERROR, "Spline IK Constraint can only be added to Bones.");
1317                 return OPERATOR_CANCELLED;
1318         }
1319         
1320         /* create a new constraint of the type requried, and add it to the active/given constraints list */
1321         if (pchan)
1322                 con = add_pose_constraint(ob, pchan, NULL, type);
1323         else
1324                 con = add_ob_constraint(ob, NULL, type);
1325         
1326         /* get the first selected object/bone, and make that the target
1327          *      - apart from the buttons-window add buttons, we shouldn't add in this way
1328          */
1329         if (setTarget) {
1330                 Object *tar_ob= NULL;
1331                 bPoseChannel *tar_pchan= NULL;
1332                 
1333                 /* get the target objects, adding them as need be */
1334                 if (get_new_constraint_target(C, type, &tar_ob, &tar_pchan, 1)) {
1335                         /* method of setting target depends on the type of target we've got 
1336                          *      - by default, just set the first target (distinction here is only for multiple-targetted constraints)
1337                          */
1338                         if (tar_pchan)
1339                                 set_constraint_nth_target(con, tar_ob, tar_pchan->name, 0);
1340                         else
1341                                 set_constraint_nth_target(con, tar_ob, "", 0);
1342                 }
1343         }
1344         
1345         /* do type-specific tweaking to the constraint settings  */
1346         switch (type) {
1347                 case CONSTRAINT_TYPE_PYTHON: // FIXME: this code is not really valid anymore
1348                 {
1349 #ifdef WITH_PYTHON
1350                         char *menustr;
1351                         int scriptint= 0;
1352                         /* popup a list of usable scripts */
1353                         menustr = buildmenu_pyconstraints(NULL, &scriptint);
1354                         // XXX scriptint = pupmenu(menustr);
1355                         MEM_freeN(menustr);
1356                         
1357                         /* only add constraint if a script was chosen */
1358                         if (scriptint) {
1359                                 /* add constraint */
1360                                 validate_pyconstraint_cb(con->data, &scriptint);
1361                                 
1362                                 /* make sure target allowance is set correctly */
1363                                 BPY_pyconstraint_update(ob, con);
1364                         }
1365 #endif
1366                 }
1367                 default:
1368                         break;
1369         }
1370         
1371         /* make sure all settings are valid - similar to above checks, but sometimes can be wrong */
1372         object_test_constraints(ob);
1373
1374         if (pchan)
1375                 update_pose_constraint_flags(ob->pose);
1376
1377
1378         /* force depsgraph to get recalculated since new relationships added */
1379         DAG_scene_sort(bmain, scene);           /* sort order of objects */
1380         
1381         if ((ob->type==OB_ARMATURE) && (pchan)) {
1382                 ob->pose->flag |= POSE_RECALC;  /* sort pose channels */
1383                 DAG_id_tag_update(&ob->id, OB_RECALC_DATA|OB_RECALC_OB);
1384         }
1385         else
1386                 DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
1387         
1388         /* notifiers for updates */
1389         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT|NA_ADDED, ob);
1390         
1391         return OPERATOR_FINISHED;
1392 }
1393
1394 /* ------------------ */
1395
1396 /* dummy operator callback */
1397 static int object_constraint_add_exec(bContext *C, wmOperator *op)
1398 {
1399         Object *ob=ED_object_active_context(C);
1400         int type= RNA_enum_get(op->ptr, "type");
1401         short with_targets= 0;
1402         
1403         if (!ob) {
1404                 BKE_report(op->reports, RPT_ERROR, "No active object to add constraint to.");
1405                 return OPERATOR_CANCELLED;
1406         }
1407                 
1408         /* hack: set constraint targets from selected objects in context is allowed when
1409          *              operator name included 'with_targets', since the menu doesn't allow multiple properties
1410          */
1411         if (strstr(op->idname, "with_targets"))
1412                 with_targets= 1;
1413
1414         return constraint_add_exec(C, op, ob, &ob->constraints, type, with_targets);
1415 }
1416
1417 /* dummy operator callback */
1418 static int pose_constraint_add_exec(bContext *C, wmOperator *op)
1419 {
1420         Object *ob= ED_object_pose_armature(ED_object_active_context(C));
1421         int type= RNA_enum_get(op->ptr, "type");
1422         short with_targets= 0;
1423         
1424         if (!ob) {
1425                 BKE_report(op->reports, RPT_ERROR, "No active object to add constraint to.");
1426                 return OPERATOR_CANCELLED;
1427         }
1428                 
1429         /* hack: set constraint targets from selected objects in context is allowed when
1430          *              operator name included 'with_targets', since the menu doesn't allow multiple properties
1431          */
1432         if (strstr(op->idname, "with_targets"))
1433                 with_targets= 1;
1434         
1435         return constraint_add_exec(C, op, ob, get_active_constraints(ob), type, with_targets);
1436 }
1437
1438 /* ------------------ */
1439
1440 void OBJECT_OT_constraint_add(wmOperatorType *ot)
1441 {
1442         /* identifiers */
1443         ot->name= "Add Constraint";
1444         ot->description = "Add a constraint to the active object";
1445         ot->idname= "OBJECT_OT_constraint_add";
1446         
1447         /* api callbacks */
1448         ot->invoke= WM_menu_invoke;
1449         ot->exec= object_constraint_add_exec;
1450         ot->poll= ED_operator_object_active_editable;
1451         
1452         /* flags */
1453         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1454         
1455         /* properties */
1456         ot->prop= RNA_def_enum(ot->srna, "type", constraint_type_items, 0, "Type", "");
1457 }
1458
1459 void OBJECT_OT_constraint_add_with_targets(wmOperatorType *ot)
1460 {
1461         /* identifiers */
1462         ot->name= "Add Constraint (with Targets)";
1463         ot->description = "Add a constraint to the active object, with target (where applicable) set to the selected Objects/Bones";
1464         ot->idname= "OBJECT_OT_constraint_add_with_targets";
1465         
1466         /* api callbacks */
1467         ot->invoke= WM_menu_invoke;
1468         ot->exec= object_constraint_add_exec;
1469         ot->poll= ED_operator_object_active_editable;
1470         
1471         /* flags */
1472         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1473         
1474         /* properties */
1475         ot->prop= RNA_def_enum(ot->srna, "type", constraint_type_items, 0, "Type", "");
1476 }
1477
1478 void POSE_OT_constraint_add(wmOperatorType *ot)
1479 {
1480         /* identifiers */
1481         ot->name= "Add Constraint";
1482         ot->description = "Add a constraint to the active bone";
1483         ot->idname= "POSE_OT_constraint_add";
1484         
1485         /* api callbacks */
1486         ot->invoke= WM_menu_invoke;
1487         ot->exec= pose_constraint_add_exec;
1488         ot->poll= ED_operator_posemode;
1489         
1490         /* flags */
1491         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1492         
1493         /* properties */
1494         ot->prop= RNA_def_enum(ot->srna, "type", constraint_type_items, 0, "Type", "");
1495 }
1496
1497 void POSE_OT_constraint_add_with_targets(wmOperatorType *ot)
1498 {
1499         /* identifiers */
1500         ot->name= "Add Constraint (with Targets)";
1501         ot->description = "Add a constraint to the active bone, with target (where applicable) set to the selected Objects/Bones";
1502         ot->idname= "POSE_OT_constraint_add_with_targets";
1503         
1504         /* api callbacks */
1505         ot->invoke= WM_menu_invoke;
1506         ot->exec= pose_constraint_add_exec;
1507         ot->poll= ED_operator_posemode;
1508         
1509         /* flags */
1510         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1511         
1512         /* properties */
1513         ot->prop= RNA_def_enum(ot->srna, "type", constraint_type_items, 0, "Type", "");
1514 }
1515
1516 /************************ IK Constraint operators *********************/
1517 /* NOTE: only for Pose-Channels */
1518 // TODO: should these be here, or back in editors/armature/poseobject.c again?
1519
1520 /* present menu with options + validation for targets to use */
1521 static int pose_ik_add_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(evt))
1522 {
1523         Object *ob= ED_object_pose_armature(CTX_data_active_object(C));
1524         bPoseChannel *pchan= get_active_posechannel(ob);
1525         bConstraint *con= NULL;
1526         
1527         uiPopupMenu *pup;
1528         uiLayout *layout;
1529         Object *tar_ob= NULL;
1530         bPoseChannel *tar_pchan= NULL;
1531         
1532         /* must have active bone */
1533         if (ELEM(NULL, ob, pchan)) {
1534                 BKE_report(op->reports, RPT_ERROR, "Must have active bone to add IK Constraint to.");
1535                 return OPERATOR_CANCELLED;
1536         }
1537         
1538         /* bone must not have any constraints already */
1539         for (con= pchan->constraints.first; con; con= con->next) {
1540                 if (con->type==CONSTRAINT_TYPE_KINEMATIC) break;
1541         }
1542         if (con) {
1543                 BKE_report(op->reports, RPT_ERROR, "Bone already has IK Constraint.");
1544                 return OPERATOR_CANCELLED;
1545         }
1546         
1547         /* prepare popup menu to choose targetting options */
1548         pup= uiPupMenuBegin(C, "Add IK", ICON_NONE);
1549         layout= uiPupMenuLayout(pup);
1550         
1551         /* the type of targets we'll set determines the menu entries to show... */
1552         if (get_new_constraint_target(C, CONSTRAINT_TYPE_KINEMATIC, &tar_ob, &tar_pchan, 0)) {
1553                 /* bone target, or object target? 
1554                  *      - the only thing that matters is that we want a target...
1555                  */
1556                 if (tar_pchan)
1557                         uiItemBooleanO(layout, "To Active Bone", ICON_NONE, "POSE_OT_ik_add", "with_targets", 1);
1558                 else
1559                         uiItemBooleanO(layout, "To Active Object", ICON_NONE, "POSE_OT_ik_add", "with_targets", 1);
1560         }
1561         else {
1562                 /* we have a choice of adding to a new empty, or not setting any target (targetless IK) */
1563                 uiItemBooleanO(layout, "To New Empty Object", ICON_NONE, "POSE_OT_ik_add", "with_targets", 1);
1564                 uiItemBooleanO(layout, "Without Targets", ICON_NONE, "POSE_OT_ik_add", "with_targets", 0);
1565         }
1566         
1567         /* finish building the menu, and process it (should result in calling self again) */
1568         uiPupMenuEnd(C, pup);
1569         
1570         return OPERATOR_CANCELLED;
1571 }
1572
1573 /* call constraint_add_exec() to add the IK constraint */
1574 static int pose_ik_add_exec(bContext *C, wmOperator *op)
1575 {
1576         Object *ob= CTX_data_active_object(C);
1577         int with_targets= RNA_boolean_get(op->ptr, "with_targets");
1578         
1579         /* add the constraint - all necessary checks should have been done by the invoke() callback already... */
1580         return constraint_add_exec(C, op, ob, get_active_constraints(ob), CONSTRAINT_TYPE_KINEMATIC, with_targets);
1581 }
1582
1583 void POSE_OT_ik_add(wmOperatorType *ot)
1584 {
1585         /* identifiers */
1586         ot->name= "Add IK to Bone";
1587         ot->description= "Add IK Constraint to the active Bone";
1588         ot->idname= "POSE_OT_ik_add";
1589         
1590         /* api callbacks */
1591         ot->invoke= pose_ik_add_invoke;
1592         ot->exec= pose_ik_add_exec;
1593         ot->poll= ED_operator_posemode;
1594         
1595         /* flags */
1596         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1597         
1598         /* properties */
1599         RNA_def_boolean(ot->srna, "with_targets", 1, "With Targets", "Assign IK Constraint with targets derived from the select bones/objects");
1600 }
1601
1602 /* ------------------ */
1603
1604 /* remove IK constraints from selected bones */
1605 static int pose_ik_clear_exec(bContext *C, wmOperator *UNUSED(op))
1606 {
1607         Object *ob= ED_object_pose_armature(CTX_data_active_object(C));
1608         
1609         /* only remove IK Constraints */
1610         CTX_DATA_BEGIN(C, bPoseChannel*, pchan, selected_pose_bones) 
1611         {
1612                 bConstraint *con, *next;
1613                 
1614                 // TODO: should we be checking if these contraints were local before we try and remove them?
1615                 for (con= pchan->constraints.first; con; con= next) {
1616                         next= con->next;
1617                         if (con->type==CONSTRAINT_TYPE_KINEMATIC) {
1618                                 remove_constraint(&pchan->constraints, con);
1619                         }
1620                 }
1621                 pchan->constflag &= ~(PCHAN_HAS_IK|PCHAN_HAS_TARGET);
1622         }
1623         CTX_DATA_END;
1624         
1625         /* refresh depsgraph */
1626         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
1627
1628         /* note, notifier might evolve */
1629         WM_event_add_notifier(C, NC_OBJECT|ND_CONSTRAINT|NA_REMOVED, ob);
1630         
1631         return OPERATOR_FINISHED;
1632 }
1633
1634 void POSE_OT_ik_clear(wmOperatorType *ot)
1635 {
1636         /* identifiers */
1637         ot->name= "Remove IK";
1638         ot->description= "Remove all IK Constraints from selected bones";
1639         ot->idname= "POSE_OT_ik_clear";
1640         
1641         /* api callbacks */
1642         ot->exec= pose_ik_clear_exec;
1643         ot->poll= ED_operator_posemode;
1644         
1645         /* flags */
1646         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1647 }
1648