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