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