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