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