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