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