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