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