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